#!/usr/bin/env node
// Force strict mode and setup for ESM
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod2) => function __require2() {
  return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
};
var __export = (target, all2) => {
  for (var name3 in all2)
    __defProp(target, name3, { get: all2[name3], enumerable: true });
};
var __copyProps = (to, from, except, desc2) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc(from, key)) || desc2.enumerable });
  }
  return to;
};
var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
  mod2
));
var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);

// scripts/esbuild-shims.js
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import { dirname } from "node:path";
var _require, __filename, __dirname;
var init_esbuild_shims = __esm({
  "scripts/esbuild-shims.js"() {
    "use strict";
    _require = createRequire(import.meta.url);
    if (typeof globalThis.require === "undefined") {
      globalThis.require = _require;
    }
    __filename = fileURLToPath(import.meta.url);
    __dirname = dirname(__filename);
  }
});

// node_modules/react/cjs/react.production.js
var require_react_production = __commonJS({
  "node_modules/react/cjs/react.production.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element");
    var REACT_PORTAL_TYPE = Symbol.for("react.portal");
    var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
    var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode");
    var REACT_PROFILER_TYPE = Symbol.for("react.profiler");
    var REACT_CONSUMER_TYPE = Symbol.for("react.consumer");
    var REACT_CONTEXT_TYPE = Symbol.for("react.context");
    var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
    var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense");
    var REACT_MEMO_TYPE = Symbol.for("react.memo");
    var REACT_LAZY_TYPE = Symbol.for("react.lazy");
    var 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;
    }
    __name(getIteratorFn, "getIteratorFn");
    var ReactNoopUpdateQueue = {
      isMounted: /* @__PURE__ */ __name(function() {
        return false;
      }, "isMounted"),
      enqueueForceUpdate: /* @__PURE__ */ __name(function() {
      }, "enqueueForceUpdate"),
      enqueueReplaceState: /* @__PURE__ */ __name(function() {
      }, "enqueueReplaceState"),
      enqueueSetState: /* @__PURE__ */ __name(function() {
      }, "enqueueSetState")
    };
    var assign = Object.assign;
    var emptyObject = {};
    function Component(props, context2, updater) {
      this.props = props;
      this.context = context2;
      this.refs = emptyObject;
      this.updater = updater || ReactNoopUpdateQueue;
    }
    __name(Component, "Component");
    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() {
    }
    __name(ComponentDummy, "ComponentDummy");
    ComponentDummy.prototype = Component.prototype;
    function PureComponent2(props, context2, updater) {
      this.props = props;
      this.context = context2;
      this.refs = emptyObject;
      this.updater = updater || ReactNoopUpdateQueue;
    }
    __name(PureComponent2, "PureComponent");
    var pureComponentPrototype = PureComponent2.prototype = new ComponentDummy();
    pureComponentPrototype.constructor = PureComponent2;
    assign(pureComponentPrototype, Component.prototype);
    pureComponentPrototype.isPureReactComponent = true;
    var isArrayImpl = Array.isArray;
    var ReactSharedInternals = { H: null, A: null, T: null, S: null, V: null };
    var hasOwnProperty2 = Object.prototype.hasOwnProperty;
    function ReactElement(type, key, self2, source2, owner, props) {
      self2 = props.ref;
      return {
        $$typeof: REACT_ELEMENT_TYPE,
        type,
        key,
        ref: void 0 !== self2 ? self2 : null,
        props
      };
    }
    __name(ReactElement, "ReactElement");
    function cloneAndReplaceKey(oldElement, newKey) {
      return ReactElement(
        oldElement.type,
        newKey,
        void 0,
        void 0,
        void 0,
        oldElement.props
      );
    }
    __name(cloneAndReplaceKey, "cloneAndReplaceKey");
    function isValidElement(object) {
      return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
    }
    __name(isValidElement, "isValidElement");
    function escape7(key) {
      var escaperLookup = { "=": "=0", ":": "=2" };
      return "$" + key.replace(/[=:]/g, function(match2) {
        return escaperLookup[match2];
      });
    }
    __name(escape7, "escape");
    var userProvidedKeyEscapeRegex = /\/+/g;
    function getElementKey(element, index) {
      return "object" === typeof element && null !== element && null != element.key ? escape7("" + element.key) : index.toString(36);
    }
    __name(getElementKey, "getElementKey");
    function noop$1() {
    }
    __name(noop$1, "noop$1");
    function resolveThenable(thenable) {
      switch (thenable.status) {
        case "fulfilled":
          return thenable.value;
        case "rejected":
          throw thenable.reason;
        default:
          switch ("string" === typeof thenable.status ? thenable.then(noop$1, noop$1) : (thenable.status = "pending", thenable.then(
            function(fulfilledValue) {
              "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
            },
            function(error) {
              "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error);
            }
          )), thenable.status) {
            case "fulfilled":
              return thenable.value;
            case "rejected":
              throw thenable.reason;
          }
      }
      throw thenable;
    }
    __name(resolveThenable, "resolveThenable");
    function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
      var type = typeof children;
      if ("undefined" === type || "boolean" === type) children = null;
      var invokeCallback = false;
      if (null === children) invokeCallback = true;
      else
        switch (type) {
          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),
                  array,
                  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, array, escapedPrefix, "", function(c3) {
          return c3;
        })) : null != callback && (isValidElement(callback) && (callback = cloneAndReplaceKey(
          callback,
          escapedPrefix + (null == callback.key || children && children.key === callback.key ? "" : ("" + callback.key).replace(
            userProvidedKeyEscapeRegex,
            "$&/"
          ) + "/") + invokeCallback
        )), array.push(callback)), 1;
      invokeCallback = 0;
      var nextNamePrefix = "" === nameSoFar ? "." : nameSoFar + ":";
      if (isArrayImpl(children))
        for (var i = 0; i < children.length; i++)
          nameSoFar = children[i], type = nextNamePrefix + getElementKey(nameSoFar, i), invokeCallback += mapIntoArray(
            nameSoFar,
            array,
            escapedPrefix,
            type,
            callback
          );
      else if (i = getIteratorFn(children), "function" === typeof i)
        for (children = i.call(children), i = 0; !(nameSoFar = children.next()).done; )
          nameSoFar = nameSoFar.value, type = nextNamePrefix + getElementKey(nameSoFar, i++), invokeCallback += mapIntoArray(
            nameSoFar,
            array,
            escapedPrefix,
            type,
            callback
          );
      else if ("object" === type) {
        if ("function" === typeof children.then)
          return mapIntoArray(
            resolveThenable(children),
            array,
            escapedPrefix,
            nameSoFar,
            callback
          );
        array = String(children);
        throw Error(
          "Objects are not valid as a React child (found: " + ("[object Object]" === array ? "object with keys {" + Object.keys(children).join(", ") + "}" : array) + "). If you meant to render a collection of children, use an array instead."
        );
      }
      return invokeCallback;
    }
    __name(mapIntoArray, "mapIntoArray");
    function mapChildren(children, func, context2) {
      if (null == children) return children;
      var result = [], count = 0;
      mapIntoArray(children, result, "", "", function(child) {
        return func.call(context2, child, count++);
      });
      return result;
    }
    __name(mapChildren, "mapChildren");
    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(error) {
            if (0 === payload._status || -1 === payload._status)
              payload._status = 2, payload._result = error;
          }
        );
        -1 === payload._status && (payload._status = 0, payload._result = ctor);
      }
      if (1 === payload._status) return payload._result.default;
      throw payload._result;
    }
    __name(lazyInitializer, "lazyInitializer");
    var reportGlobalError = "function" === typeof reportError ? reportError : function(error) {
      if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
        var event = new window.ErrorEvent("error", {
          bubbles: true,
          cancelable: true,
          message: "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error),
          error
        });
        if (!window.dispatchEvent(event)) return;
      } else if ("object" === typeof process && "function" === typeof process.emit) {
        process.emit("uncaughtException", error);
        return;
      }
      console.error(error);
    };
    function noop6() {
    }
    __name(noop6, "noop");
    exports2.Children = {
      map: mapChildren,
      forEach: /* @__PURE__ */ __name(function(children, forEachFunc, forEachContext) {
        mapChildren(
          children,
          function() {
            forEachFunc.apply(this, arguments);
          },
          forEachContext
        );
      }, "forEach"),
      count: /* @__PURE__ */ __name(function(children) {
        var n2 = 0;
        mapChildren(children, function() {
          n2++;
        });
        return n2;
      }, "count"),
      toArray: /* @__PURE__ */ __name(function(children) {
        return mapChildren(children, function(child) {
          return child;
        }) || [];
      }, "toArray"),
      only: /* @__PURE__ */ __name(function(children) {
        if (!isValidElement(children))
          throw Error(
            "React.Children.only expected to receive a single React element child."
          );
        return children;
      }, "only")
    };
    exports2.Component = Component;
    exports2.Fragment = REACT_FRAGMENT_TYPE;
    exports2.Profiler = REACT_PROFILER_TYPE;
    exports2.PureComponent = PureComponent2;
    exports2.StrictMode = REACT_STRICT_MODE_TYPE;
    exports2.Suspense = REACT_SUSPENSE_TYPE;
    exports2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals;
    exports2.__COMPILER_RUNTIME = {
      __proto__: null,
      c: /* @__PURE__ */ __name(function(size) {
        return ReactSharedInternals.H.useMemoCache(size);
      }, "c")
    };
    exports2.cache = function(fn) {
      return function() {
        return fn.apply(null, arguments);
      };
    };
    exports2.cloneElement = function(element, config, 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, owner = void 0;
      if (null != config)
        for (propName in void 0 !== config.ref && (owner = void 0), void 0 !== config.key && (key = "" + config.key), config)
          !hasOwnProperty2.call(config, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config.ref || (props[propName] = config[propName]);
      var propName = arguments.length - 2;
      if (1 === propName) props.children = children;
      else if (1 < propName) {
        for (var childArray = Array(propName), i = 0; i < propName; i++)
          childArray[i] = arguments[i + 2];
        props.children = childArray;
      }
      return ReactElement(element.type, key, void 0, void 0, owner, props);
    };
    exports2.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;
    };
    exports2.createElement = function(type, config, children) {
      var propName, props = {}, key = null;
      if (null != config)
        for (propName in void 0 !== config.key && (key = "" + config.key), config)
          hasOwnProperty2.call(config, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (props[propName] = config[propName]);
      var childrenLength = arguments.length - 2;
      if (1 === childrenLength) props.children = children;
      else if (1 < childrenLength) {
        for (var childArray = Array(childrenLength), i = 0; i < childrenLength; i++)
          childArray[i] = arguments[i + 2];
        props.children = childArray;
      }
      if (type && type.defaultProps)
        for (propName in childrenLength = type.defaultProps, childrenLength)
          void 0 === props[propName] && (props[propName] = childrenLength[propName]);
      return ReactElement(type, key, void 0, void 0, null, props);
    };
    exports2.createRef = function() {
      return { current: null };
    };
    exports2.forwardRef = function(render3) {
      return { $$typeof: REACT_FORWARD_REF_TYPE, render: render3 };
    };
    exports2.isValidElement = isValidElement;
    exports2.lazy = function(ctor) {
      return {
        $$typeof: REACT_LAZY_TYPE,
        _payload: { _status: -1, _result: ctor },
        _init: lazyInitializer
      };
    };
    exports2.memo = function(type, compare) {
      return {
        $$typeof: REACT_MEMO_TYPE,
        type,
        compare: void 0 === compare ? null : compare
      };
    };
    exports2.startTransition = function(scope) {
      var prevTransition = ReactSharedInternals.T, currentTransition = {};
      ReactSharedInternals.T = currentTransition;
      try {
        var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S;
        null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
        "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && returnValue.then(noop6, reportGlobalError);
      } catch (error) {
        reportGlobalError(error);
      } finally {
        ReactSharedInternals.T = prevTransition;
      }
    };
    exports2.unstable_useCacheRefresh = function() {
      return ReactSharedInternals.H.useCacheRefresh();
    };
    exports2.use = function(usable) {
      return ReactSharedInternals.H.use(usable);
    };
    exports2.useActionState = function(action, initialState2, permalink) {
      return ReactSharedInternals.H.useActionState(action, initialState2, permalink);
    };
    exports2.useCallback = function(callback, deps) {
      return ReactSharedInternals.H.useCallback(callback, deps);
    };
    exports2.useContext = function(Context) {
      return ReactSharedInternals.H.useContext(Context);
    };
    exports2.useDebugValue = function() {
    };
    exports2.useDeferredValue = function(value, initialValue) {
      return ReactSharedInternals.H.useDeferredValue(value, initialValue);
    };
    exports2.useEffect = function(create3, createDeps, update2) {
      var dispatcher = ReactSharedInternals.H;
      if ("function" === typeof update2)
        throw Error(
          "useEffect CRUD overload is not enabled in this build of React."
        );
      return dispatcher.useEffect(create3, createDeps);
    };
    exports2.useId = function() {
      return ReactSharedInternals.H.useId();
    };
    exports2.useImperativeHandle = function(ref, create3, deps) {
      return ReactSharedInternals.H.useImperativeHandle(ref, create3, deps);
    };
    exports2.useInsertionEffect = function(create3, deps) {
      return ReactSharedInternals.H.useInsertionEffect(create3, deps);
    };
    exports2.useLayoutEffect = function(create3, deps) {
      return ReactSharedInternals.H.useLayoutEffect(create3, deps);
    };
    exports2.useMemo = function(create3, deps) {
      return ReactSharedInternals.H.useMemo(create3, deps);
    };
    exports2.useOptimistic = function(passthrough, reducer) {
      return ReactSharedInternals.H.useOptimistic(passthrough, reducer);
    };
    exports2.useReducer = function(reducer, initialArg, init) {
      return ReactSharedInternals.H.useReducer(reducer, initialArg, init);
    };
    exports2.useRef = function(initialValue) {
      return ReactSharedInternals.H.useRef(initialValue);
    };
    exports2.useState = function(initialState2) {
      return ReactSharedInternals.H.useState(initialState2);
    };
    exports2.useSyncExternalStore = function(subscribe, getSnapshot, getServerSnapshot) {
      return ReactSharedInternals.H.useSyncExternalStore(
        subscribe,
        getSnapshot,
        getServerSnapshot
      );
    };
    exports2.useTransition = function() {
      return ReactSharedInternals.H.useTransition();
    };
    exports2.version = "19.1.0";
  }
});

// node_modules/react/cjs/react.development.js
var require_react_development = __commonJS({
  "node_modules/react/cjs/react.development.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    "production" !== process.env.NODE_ENV && function() {
      function defineDeprecationWarning(methodName, info) {
        Object.defineProperty(Component.prototype, methodName, {
          get: /* @__PURE__ */ __name(function() {
            console.warn(
              "%s(...) is deprecated in plain JavaScript React classes. %s",
              info[0],
              info[1]
            );
          }, "get")
        });
      }
      __name(defineDeprecationWarning, "defineDeprecationWarning");
      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;
      }
      __name(getIteratorFn, "getIteratorFn");
      function warnNoop(publicInstance, callerName) {
        publicInstance = (publicInstance = publicInstance.constructor) && (publicInstance.displayName || publicInstance.name) || "ReactClass";
        var warningKey = publicInstance + "." + callerName;
        didWarnStateUpdateForUnmountedComponent[warningKey] || (console.error(
          "Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",
          callerName,
          publicInstance
        ), didWarnStateUpdateForUnmountedComponent[warningKey] = true);
      }
      __name(warnNoop, "warnNoop");
      function Component(props, context2, updater) {
        this.props = props;
        this.context = context2;
        this.refs = emptyObject;
        this.updater = updater || ReactNoopUpdateQueue;
      }
      __name(Component, "Component");
      function ComponentDummy() {
      }
      __name(ComponentDummy, "ComponentDummy");
      function PureComponent2(props, context2, updater) {
        this.props = props;
        this.context = context2;
        this.refs = emptyObject;
        this.updater = updater || ReactNoopUpdateQueue;
      }
      __name(PureComponent2, "PureComponent");
      function testStringCoercion(value) {
        return "" + value;
      }
      __name(testStringCoercion, "testStringCoercion");
      function checkKeyStringCoercion(value) {
        try {
          testStringCoercion(value);
          var JSCompiler_inline_result = false;
        } catch (e2) {
          JSCompiler_inline_result = true;
        }
        if (JSCompiler_inline_result) {
          JSCompiler_inline_result = console;
          var JSCompiler_temp_const = JSCompiler_inline_result.error;
          var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
          JSCompiler_temp_const.call(
            JSCompiler_inline_result,
            "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
            JSCompiler_inline_result$jscomp$0
          );
          return testStringCoercion(value);
        }
      }
      __name(checkKeyStringCoercion, "checkKeyStringCoercion");
      function getComponentNameFromType(type) {
        if (null == type) return null;
        if ("function" === typeof type)
          return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
        if ("string" === typeof type) return type;
        switch (type) {
          case REACT_FRAGMENT_TYPE:
            return "Fragment";
          case REACT_PROFILER_TYPE:
            return "Profiler";
          case REACT_STRICT_MODE_TYPE:
            return "StrictMode";
          case REACT_SUSPENSE_TYPE:
            return "Suspense";
          case REACT_SUSPENSE_LIST_TYPE:
            return "SuspenseList";
          case REACT_ACTIVITY_TYPE:
            return "Activity";
        }
        if ("object" === typeof type)
          switch ("number" === typeof type.tag && console.error(
            "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
          ), type.$$typeof) {
            case REACT_PORTAL_TYPE:
              return "Portal";
            case REACT_CONTEXT_TYPE:
              return (type.displayName || "Context") + ".Provider";
            case REACT_CONSUMER_TYPE:
              return (type._context.displayName || "Context") + ".Consumer";
            case REACT_FORWARD_REF_TYPE:
              var innerType = type.render;
              type = type.displayName;
              type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
              return type;
            case REACT_MEMO_TYPE:
              return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
            case REACT_LAZY_TYPE:
              innerType = type._payload;
              type = type._init;
              try {
                return getComponentNameFromType(type(innerType));
              } catch (x) {
              }
          }
        return null;
      }
      __name(getComponentNameFromType, "getComponentNameFromType");
      function getTaskName(type) {
        if (type === REACT_FRAGMENT_TYPE) return "<>";
        if ("object" === typeof type && null !== type && type.$$typeof === REACT_LAZY_TYPE)
          return "<...>";
        try {
          var name3 = getComponentNameFromType(type);
          return name3 ? "<" + name3 + ">" : "<...>";
        } catch (x) {
          return "<...>";
        }
      }
      __name(getTaskName, "getTaskName");
      function getOwner() {
        var dispatcher = ReactSharedInternals.A;
        return null === dispatcher ? null : dispatcher.getOwner();
      }
      __name(getOwner, "getOwner");
      function UnknownOwner() {
        return Error("react-stack-top-frame");
      }
      __name(UnknownOwner, "UnknownOwner");
      function hasValidKey(config) {
        if (hasOwnProperty2.call(config, "key")) {
          var getter = Object.getOwnPropertyDescriptor(config, "key").get;
          if (getter && getter.isReactWarning) return false;
        }
        return void 0 !== config.key;
      }
      __name(hasValidKey, "hasValidKey");
      function defineKeyPropWarningGetter(props, displayName) {
        function warnAboutAccessingKey() {
          specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error(
            "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
            displayName
          ));
        }
        __name(warnAboutAccessingKey, "warnAboutAccessingKey");
        warnAboutAccessingKey.isReactWarning = true;
        Object.defineProperty(props, "key", {
          get: warnAboutAccessingKey,
          configurable: true
        });
      }
      __name(defineKeyPropWarningGetter, "defineKeyPropWarningGetter");
      function elementRefGetterWithDeprecationWarning() {
        var componentName = getComponentNameFromType(this.type);
        didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error(
          "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
        ));
        componentName = this.props.ref;
        return void 0 !== componentName ? componentName : null;
      }
      __name(elementRefGetterWithDeprecationWarning, "elementRefGetterWithDeprecationWarning");
      function ReactElement(type, key, self2, source2, owner, props, debugStack, debugTask) {
        self2 = props.ref;
        type = {
          $$typeof: REACT_ELEMENT_TYPE,
          type,
          key,
          props,
          _owner: owner
        };
        null !== (void 0 !== self2 ? self2 : null) ? Object.defineProperty(type, "ref", {
          enumerable: false,
          get: elementRefGetterWithDeprecationWarning
        }) : Object.defineProperty(type, "ref", { enumerable: false, value: null });
        type._store = {};
        Object.defineProperty(type._store, "validated", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: 0
        });
        Object.defineProperty(type, "_debugInfo", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: null
        });
        Object.defineProperty(type, "_debugStack", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: debugStack
        });
        Object.defineProperty(type, "_debugTask", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: debugTask
        });
        Object.freeze && (Object.freeze(type.props), Object.freeze(type));
        return type;
      }
      __name(ReactElement, "ReactElement");
      function cloneAndReplaceKey(oldElement, newKey) {
        newKey = ReactElement(
          oldElement.type,
          newKey,
          void 0,
          void 0,
          oldElement._owner,
          oldElement.props,
          oldElement._debugStack,
          oldElement._debugTask
        );
        oldElement._store && (newKey._store.validated = oldElement._store.validated);
        return newKey;
      }
      __name(cloneAndReplaceKey, "cloneAndReplaceKey");
      function isValidElement(object) {
        return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
      }
      __name(isValidElement, "isValidElement");
      function escape7(key) {
        var escaperLookup = { "=": "=0", ":": "=2" };
        return "$" + key.replace(/[=:]/g, function(match2) {
          return escaperLookup[match2];
        });
      }
      __name(escape7, "escape");
      function getElementKey(element, index) {
        return "object" === typeof element && null !== element && null != element.key ? (checkKeyStringCoercion(element.key), escape7("" + element.key)) : index.toString(36);
      }
      __name(getElementKey, "getElementKey");
      function noop$1() {
      }
      __name(noop$1, "noop$1");
      function resolveThenable(thenable) {
        switch (thenable.status) {
          case "fulfilled":
            return thenable.value;
          case "rejected":
            throw thenable.reason;
          default:
            switch ("string" === typeof thenable.status ? thenable.then(noop$1, noop$1) : (thenable.status = "pending", thenable.then(
              function(fulfilledValue) {
                "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
              },
              function(error) {
                "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error);
              }
            )), thenable.status) {
              case "fulfilled":
                return thenable.value;
              case "rejected":
                throw thenable.reason;
            }
        }
        throw thenable;
      }
      __name(resolveThenable, "resolveThenable");
      function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
        var type = typeof children;
        if ("undefined" === type || "boolean" === type) children = null;
        var invokeCallback = false;
        if (null === children) invokeCallback = true;
        else
          switch (type) {
            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),
                    array,
                    escapedPrefix,
                    nameSoFar,
                    callback
                  );
              }
          }
        if (invokeCallback) {
          invokeCallback = children;
          callback = callback(invokeCallback);
          var childKey = "" === nameSoFar ? "." + getElementKey(invokeCallback, 0) : nameSoFar;
          isArrayImpl(callback) ? (escapedPrefix = "", null != childKey && (escapedPrefix = childKey.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array, escapedPrefix, "", function(c3) {
            return c3;
          })) : null != callback && (isValidElement(callback) && (null != callback.key && (invokeCallback && invokeCallback.key === callback.key || checkKeyStringCoercion(callback.key)), escapedPrefix = cloneAndReplaceKey(
            callback,
            escapedPrefix + (null == callback.key || invokeCallback && invokeCallback.key === callback.key ? "" : ("" + callback.key).replace(
              userProvidedKeyEscapeRegex,
              "$&/"
            ) + "/") + childKey
          ), "" !== nameSoFar && null != invokeCallback && isValidElement(invokeCallback) && null == invokeCallback.key && invokeCallback._store && !invokeCallback._store.validated && (escapedPrefix._store.validated = 2), callback = escapedPrefix), array.push(callback));
          return 1;
        }
        invokeCallback = 0;
        childKey = "" === nameSoFar ? "." : nameSoFar + ":";
        if (isArrayImpl(children))
          for (var i = 0; i < children.length; i++)
            nameSoFar = children[i], type = childKey + getElementKey(nameSoFar, i), invokeCallback += mapIntoArray(
              nameSoFar,
              array,
              escapedPrefix,
              type,
              callback
            );
        else if (i = getIteratorFn(children), "function" === typeof i)
          for (i === children.entries && (didWarnAboutMaps || console.warn(
            "Using Maps as children is not supported. Use an array of keyed ReactElements instead."
          ), didWarnAboutMaps = true), children = i.call(children), i = 0; !(nameSoFar = children.next()).done; )
            nameSoFar = nameSoFar.value, type = childKey + getElementKey(nameSoFar, i++), invokeCallback += mapIntoArray(
              nameSoFar,
              array,
              escapedPrefix,
              type,
              callback
            );
        else if ("object" === type) {
          if ("function" === typeof children.then)
            return mapIntoArray(
              resolveThenable(children),
              array,
              escapedPrefix,
              nameSoFar,
              callback
            );
          array = String(children);
          throw Error(
            "Objects are not valid as a React child (found: " + ("[object Object]" === array ? "object with keys {" + Object.keys(children).join(", ") + "}" : array) + "). If you meant to render a collection of children, use an array instead."
          );
        }
        return invokeCallback;
      }
      __name(mapIntoArray, "mapIntoArray");
      function mapChildren(children, func, context2) {
        if (null == children) return children;
        var result = [], count = 0;
        mapIntoArray(children, result, "", "", function(child) {
          return func.call(context2, child, count++);
        });
        return result;
      }
      __name(mapChildren, "mapChildren");
      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(error) {
              if (0 === payload._status || -1 === payload._status)
                payload._status = 2, payload._result = error;
            }
          );
          -1 === payload._status && (payload._status = 0, payload._result = ctor);
        }
        if (1 === payload._status)
          return ctor = payload._result, void 0 === ctor && console.error(
            "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n  const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?",
            ctor
          ), "default" in ctor || console.error(
            "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n  const MyComponent = lazy(() => import('./MyComponent'))",
            ctor
          ), ctor.default;
        throw payload._result;
      }
      __name(lazyInitializer, "lazyInitializer");
      function resolveDispatcher() {
        var dispatcher = ReactSharedInternals.H;
        null === dispatcher && console.error(
          "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
        );
        return dispatcher;
      }
      __name(resolveDispatcher, "resolveDispatcher");
      function noop6() {
      }
      __name(noop6, "noop");
      function enqueueTask(task) {
        if (null === enqueueTaskImpl)
          try {
            var requireString = ("require" + Math.random()).slice(0, 7);
            enqueueTaskImpl = (module2 && module2[requireString]).call(
              module2,
              "timers"
            ).setImmediate;
          } catch (_err) {
            enqueueTaskImpl = /* @__PURE__ */ __name(function(callback) {
              false === didWarnAboutMessageChannel && (didWarnAboutMessageChannel = true, "undefined" === typeof MessageChannel && console.error(
                "This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."
              ));
              var channel = new MessageChannel();
              channel.port1.onmessage = callback;
              channel.port2.postMessage(void 0);
            }, "enqueueTaskImpl");
          }
        return enqueueTaskImpl(task);
      }
      __name(enqueueTask, "enqueueTask");
      function aggregateErrors(errors) {
        return 1 < errors.length && "function" === typeof AggregateError ? new AggregateError(errors) : errors[0];
      }
      __name(aggregateErrors, "aggregateErrors");
      function popActScope(prevActQueue, prevActScopeDepth) {
        prevActScopeDepth !== actScopeDepth - 1 && console.error(
          "You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "
        );
        actScopeDepth = prevActScopeDepth;
      }
      __name(popActScope, "popActScope");
      function recursivelyFlushAsyncActWork(returnValue, resolve24, reject) {
        var queue = ReactSharedInternals.actQueue;
        if (null !== queue)
          if (0 !== queue.length)
            try {
              flushActQueue(queue);
              enqueueTask(function() {
                return recursivelyFlushAsyncActWork(returnValue, resolve24, reject);
              });
              return;
            } catch (error) {
              ReactSharedInternals.thrownErrors.push(error);
            }
          else ReactSharedInternals.actQueue = null;
        0 < ReactSharedInternals.thrownErrors.length ? (queue = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(queue)) : resolve24(returnValue);
      }
      __name(recursivelyFlushAsyncActWork, "recursivelyFlushAsyncActWork");
      function flushActQueue(queue) {
        if (!isFlushing) {
          isFlushing = true;
          var i = 0;
          try {
            for (; i < queue.length; i++) {
              var callback = queue[i];
              do {
                ReactSharedInternals.didUsePromise = false;
                var continuation = callback(false);
                if (null !== continuation) {
                  if (ReactSharedInternals.didUsePromise) {
                    queue[i] = callback;
                    queue.splice(0, i);
                    return;
                  }
                  callback = continuation;
                } else break;
              } while (1);
            }
            queue.length = 0;
          } catch (error) {
            queue.splice(0, i + 1), ReactSharedInternals.thrownErrors.push(error);
          } finally {
            isFlushing = false;
          }
        }
      }
      __name(flushActQueue, "flushActQueue");
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
      var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler");
      Symbol.for("react.provider");
      var REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator, didWarnStateUpdateForUnmountedComponent = {}, ReactNoopUpdateQueue = {
        isMounted: /* @__PURE__ */ __name(function() {
          return false;
        }, "isMounted"),
        enqueueForceUpdate: /* @__PURE__ */ __name(function(publicInstance) {
          warnNoop(publicInstance, "forceUpdate");
        }, "enqueueForceUpdate"),
        enqueueReplaceState: /* @__PURE__ */ __name(function(publicInstance) {
          warnNoop(publicInstance, "replaceState");
        }, "enqueueReplaceState"),
        enqueueSetState: /* @__PURE__ */ __name(function(publicInstance) {
          warnNoop(publicInstance, "setState");
        }, "enqueueSetState")
      }, assign = Object.assign, emptyObject = {};
      Object.freeze(emptyObject);
      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");
      };
      var deprecatedAPIs = {
        isMounted: [
          "isMounted",
          "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."
        ],
        replaceState: [
          "replaceState",
          "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."
        ]
      }, fnName;
      for (fnName in deprecatedAPIs)
        deprecatedAPIs.hasOwnProperty(fnName) && defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
      ComponentDummy.prototype = Component.prototype;
      deprecatedAPIs = PureComponent2.prototype = new ComponentDummy();
      deprecatedAPIs.constructor = PureComponent2;
      assign(deprecatedAPIs, Component.prototype);
      deprecatedAPIs.isPureReactComponent = true;
      var isArrayImpl = Array.isArray, REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), ReactSharedInternals = {
        H: null,
        A: null,
        T: null,
        S: null,
        V: null,
        actQueue: null,
        isBatchingLegacy: false,
        didScheduleLegacyUpdate: false,
        didUsePromise: false,
        thrownErrors: [],
        getCurrentStack: null,
        recentlyCreatedOwnerStacks: 0
      }, hasOwnProperty2 = Object.prototype.hasOwnProperty, createTask = console.createTask ? console.createTask : function() {
        return null;
      };
      deprecatedAPIs = {
        "react-stack-bottom-frame": /* @__PURE__ */ __name(function(callStackForError) {
          return callStackForError();
        }, "react-stack-bottom-frame")
      };
      var specialPropKeyWarningShown, didWarnAboutOldJSXRuntime;
      var didWarnAboutElementRef = {};
      var unknownOwnerDebugStack = deprecatedAPIs["react-stack-bottom-frame"].bind(deprecatedAPIs, UnknownOwner)();
      var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
      var didWarnAboutMaps = false, userProvidedKeyEscapeRegex = /\/+/g, reportGlobalError = "function" === typeof reportError ? reportError : function(error) {
        if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
          var event = new window.ErrorEvent("error", {
            bubbles: true,
            cancelable: true,
            message: "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error),
            error
          });
          if (!window.dispatchEvent(event)) return;
        } else if ("object" === typeof process && "function" === typeof process.emit) {
          process.emit("uncaughtException", error);
          return;
        }
        console.error(error);
      }, didWarnAboutMessageChannel = false, enqueueTaskImpl = null, actScopeDepth = 0, didWarnNoAwaitAct = false, isFlushing = false, queueSeveralMicrotasks = "function" === typeof queueMicrotask ? function(callback) {
        queueMicrotask(function() {
          return queueMicrotask(callback);
        });
      } : enqueueTask;
      deprecatedAPIs = Object.freeze({
        __proto__: null,
        c: /* @__PURE__ */ __name(function(size) {
          return resolveDispatcher().useMemoCache(size);
        }, "c")
      });
      exports2.Children = {
        map: mapChildren,
        forEach: /* @__PURE__ */ __name(function(children, forEachFunc, forEachContext) {
          mapChildren(
            children,
            function() {
              forEachFunc.apply(this, arguments);
            },
            forEachContext
          );
        }, "forEach"),
        count: /* @__PURE__ */ __name(function(children) {
          var n2 = 0;
          mapChildren(children, function() {
            n2++;
          });
          return n2;
        }, "count"),
        toArray: /* @__PURE__ */ __name(function(children) {
          return mapChildren(children, function(child) {
            return child;
          }) || [];
        }, "toArray"),
        only: /* @__PURE__ */ __name(function(children) {
          if (!isValidElement(children))
            throw Error(
              "React.Children.only expected to receive a single React element child."
            );
          return children;
        }, "only")
      };
      exports2.Component = Component;
      exports2.Fragment = REACT_FRAGMENT_TYPE;
      exports2.Profiler = REACT_PROFILER_TYPE;
      exports2.PureComponent = PureComponent2;
      exports2.StrictMode = REACT_STRICT_MODE_TYPE;
      exports2.Suspense = REACT_SUSPENSE_TYPE;
      exports2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals;
      exports2.__COMPILER_RUNTIME = deprecatedAPIs;
      exports2.act = function(callback) {
        var prevActQueue = ReactSharedInternals.actQueue, prevActScopeDepth = actScopeDepth;
        actScopeDepth++;
        var queue = ReactSharedInternals.actQueue = null !== prevActQueue ? prevActQueue : [], didAwaitActCall = false;
        try {
          var result = callback();
        } catch (error) {
          ReactSharedInternals.thrownErrors.push(error);
        }
        if (0 < ReactSharedInternals.thrownErrors.length)
          throw popActScope(prevActQueue, prevActScopeDepth), callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
        if (null !== result && "object" === typeof result && "function" === typeof result.then) {
          var thenable = result;
          queueSeveralMicrotasks(function() {
            didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error(
              "You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"
            ));
          });
          return {
            then: /* @__PURE__ */ __name(function(resolve24, reject) {
              didAwaitActCall = true;
              thenable.then(
                function(returnValue) {
                  popActScope(prevActQueue, prevActScopeDepth);
                  if (0 === prevActScopeDepth) {
                    try {
                      flushActQueue(queue), enqueueTask(function() {
                        return recursivelyFlushAsyncActWork(
                          returnValue,
                          resolve24,
                          reject
                        );
                      });
                    } catch (error$0) {
                      ReactSharedInternals.thrownErrors.push(error$0);
                    }
                    if (0 < ReactSharedInternals.thrownErrors.length) {
                      var _thrownError = aggregateErrors(
                        ReactSharedInternals.thrownErrors
                      );
                      ReactSharedInternals.thrownErrors.length = 0;
                      reject(_thrownError);
                    }
                  } else resolve24(returnValue);
                },
                function(error) {
                  popActScope(prevActQueue, prevActScopeDepth);
                  0 < ReactSharedInternals.thrownErrors.length ? (error = aggregateErrors(
                    ReactSharedInternals.thrownErrors
                  ), ReactSharedInternals.thrownErrors.length = 0, reject(error)) : reject(error);
                }
              );
            }, "then")
          };
        }
        var returnValue$jscomp$0 = result;
        popActScope(prevActQueue, prevActScopeDepth);
        0 === prevActScopeDepth && (flushActQueue(queue), 0 !== queue.length && queueSeveralMicrotasks(function() {
          didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error(
            "A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"
          ));
        }), ReactSharedInternals.actQueue = null);
        if (0 < ReactSharedInternals.thrownErrors.length)
          throw callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
        return {
          then: /* @__PURE__ */ __name(function(resolve24, reject) {
            didAwaitActCall = true;
            0 === prevActScopeDepth ? (ReactSharedInternals.actQueue = queue, enqueueTask(function() {
              return recursivelyFlushAsyncActWork(
                returnValue$jscomp$0,
                resolve24,
                reject
              );
            })) : resolve24(returnValue$jscomp$0);
          }, "then")
        };
      };
      exports2.cache = function(fn) {
        return function() {
          return fn.apply(null, arguments);
        };
      };
      exports2.captureOwnerStack = function() {
        var getCurrentStack = ReactSharedInternals.getCurrentStack;
        return null === getCurrentStack ? null : getCurrentStack();
      };
      exports2.cloneElement = function(element, config, 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, owner = element._owner;
        if (null != config) {
          var JSCompiler_inline_result;
          a: {
            if (hasOwnProperty2.call(config, "ref") && (JSCompiler_inline_result = Object.getOwnPropertyDescriptor(
              config,
              "ref"
            ).get) && JSCompiler_inline_result.isReactWarning) {
              JSCompiler_inline_result = false;
              break a;
            }
            JSCompiler_inline_result = void 0 !== config.ref;
          }
          JSCompiler_inline_result && (owner = getOwner());
          hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key);
          for (propName in config)
            !hasOwnProperty2.call(config, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config.ref || (props[propName] = config[propName]);
        }
        var propName = arguments.length - 2;
        if (1 === propName) props.children = children;
        else if (1 < propName) {
          JSCompiler_inline_result = Array(propName);
          for (var i = 0; i < propName; i++)
            JSCompiler_inline_result[i] = arguments[i + 2];
          props.children = JSCompiler_inline_result;
        }
        props = ReactElement(
          element.type,
          key,
          void 0,
          void 0,
          owner,
          props,
          element._debugStack,
          element._debugTask
        );
        for (key = 2; key < arguments.length; key++)
          owner = arguments[key], isValidElement(owner) && owner._store && (owner._store.validated = 1);
        return props;
      };
      exports2.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
        };
        defaultValue._currentRenderer = null;
        defaultValue._currentRenderer2 = null;
        return defaultValue;
      };
      exports2.createElement = function(type, config, children) {
        for (var i = 2; i < arguments.length; i++) {
          var node = arguments[i];
          isValidElement(node) && node._store && (node._store.validated = 1);
        }
        i = {};
        node = null;
        if (null != config)
          for (propName in didWarnAboutOldJSXRuntime || !("__self" in config) || "key" in config || (didWarnAboutOldJSXRuntime = true, console.warn(
            "Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform"
          )), hasValidKey(config) && (checkKeyStringCoercion(config.key), node = "" + config.key), config)
            hasOwnProperty2.call(config, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (i[propName] = config[propName]);
        var childrenLength = arguments.length - 2;
        if (1 === childrenLength) i.children = children;
        else if (1 < childrenLength) {
          for (var childArray = Array(childrenLength), _i = 0; _i < childrenLength; _i++)
            childArray[_i] = arguments[_i + 2];
          Object.freeze && Object.freeze(childArray);
          i.children = childArray;
        }
        if (type && type.defaultProps)
          for (propName in childrenLength = type.defaultProps, childrenLength)
            void 0 === i[propName] && (i[propName] = childrenLength[propName]);
        node && defineKeyPropWarningGetter(
          i,
          "function" === typeof type ? type.displayName || type.name || "Unknown" : type
        );
        var propName = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
        return ReactElement(
          type,
          node,
          void 0,
          void 0,
          getOwner(),
          i,
          propName ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
          propName ? createTask(getTaskName(type)) : unknownOwnerDebugTask
        );
      };
      exports2.createRef = function() {
        var refObject = { current: null };
        Object.seal(refObject);
        return refObject;
      };
      exports2.forwardRef = function(render3) {
        null != render3 && render3.$$typeof === REACT_MEMO_TYPE ? console.error(
          "forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."
        ) : "function" !== typeof render3 ? console.error(
          "forwardRef requires a render function but was given %s.",
          null === render3 ? "null" : typeof render3
        ) : 0 !== render3.length && 2 !== render3.length && console.error(
          "forwardRef render functions accept exactly two parameters: props and ref. %s",
          1 === render3.length ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."
        );
        null != render3 && null != render3.defaultProps && console.error(
          "forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?"
        );
        var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render: render3 }, ownName;
        Object.defineProperty(elementType, "displayName", {
          enumerable: false,
          configurable: true,
          get: /* @__PURE__ */ __name(function() {
            return ownName;
          }, "get"),
          set: /* @__PURE__ */ __name(function(name3) {
            ownName = name3;
            render3.name || render3.displayName || (Object.defineProperty(render3, "name", { value: name3 }), render3.displayName = name3);
          }, "set")
        });
        return elementType;
      };
      exports2.isValidElement = isValidElement;
      exports2.lazy = function(ctor) {
        return {
          $$typeof: REACT_LAZY_TYPE,
          _payload: { _status: -1, _result: ctor },
          _init: lazyInitializer
        };
      };
      exports2.memo = function(type, compare) {
        null == type && console.error(
          "memo: The first argument must be a component. Instead received: %s",
          null === type ? "null" : typeof type
        );
        compare = {
          $$typeof: REACT_MEMO_TYPE,
          type,
          compare: void 0 === compare ? null : compare
        };
        var ownName;
        Object.defineProperty(compare, "displayName", {
          enumerable: false,
          configurable: true,
          get: /* @__PURE__ */ __name(function() {
            return ownName;
          }, "get"),
          set: /* @__PURE__ */ __name(function(name3) {
            ownName = name3;
            type.name || type.displayName || (Object.defineProperty(type, "name", { value: name3 }), type.displayName = name3);
          }, "set")
        });
        return compare;
      };
      exports2.startTransition = function(scope) {
        var prevTransition = ReactSharedInternals.T, currentTransition = {};
        ReactSharedInternals.T = currentTransition;
        currentTransition._updatedFibers = /* @__PURE__ */ new Set();
        try {
          var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S;
          null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
          "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && returnValue.then(noop6, reportGlobalError);
        } catch (error) {
          reportGlobalError(error);
        } finally {
          null === prevTransition && currentTransition._updatedFibers && (scope = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < scope && console.warn(
            "Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."
          )), ReactSharedInternals.T = prevTransition;
        }
      };
      exports2.unstable_useCacheRefresh = function() {
        return resolveDispatcher().useCacheRefresh();
      };
      exports2.use = function(usable) {
        return resolveDispatcher().use(usable);
      };
      exports2.useActionState = function(action, initialState2, permalink) {
        return resolveDispatcher().useActionState(
          action,
          initialState2,
          permalink
        );
      };
      exports2.useCallback = function(callback, deps) {
        return resolveDispatcher().useCallback(callback, deps);
      };
      exports2.useContext = function(Context) {
        var dispatcher = resolveDispatcher();
        Context.$$typeof === REACT_CONSUMER_TYPE && console.error(
          "Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?"
        );
        return dispatcher.useContext(Context);
      };
      exports2.useDebugValue = function(value, formatterFn) {
        return resolveDispatcher().useDebugValue(value, formatterFn);
      };
      exports2.useDeferredValue = function(value, initialValue) {
        return resolveDispatcher().useDeferredValue(value, initialValue);
      };
      exports2.useEffect = function(create3, createDeps, update2) {
        null == create3 && console.warn(
          "React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"
        );
        var dispatcher = resolveDispatcher();
        if ("function" === typeof update2)
          throw Error(
            "useEffect CRUD overload is not enabled in this build of React."
          );
        return dispatcher.useEffect(create3, createDeps);
      };
      exports2.useId = function() {
        return resolveDispatcher().useId();
      };
      exports2.useImperativeHandle = function(ref, create3, deps) {
        return resolveDispatcher().useImperativeHandle(ref, create3, deps);
      };
      exports2.useInsertionEffect = function(create3, deps) {
        null == create3 && console.warn(
          "React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?"
        );
        return resolveDispatcher().useInsertionEffect(create3, deps);
      };
      exports2.useLayoutEffect = function(create3, deps) {
        null == create3 && console.warn(
          "React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?"
        );
        return resolveDispatcher().useLayoutEffect(create3, deps);
      };
      exports2.useMemo = function(create3, deps) {
        return resolveDispatcher().useMemo(create3, deps);
      };
      exports2.useOptimistic = function(passthrough, reducer) {
        return resolveDispatcher().useOptimistic(passthrough, reducer);
      };
      exports2.useReducer = function(reducer, initialArg, init) {
        return resolveDispatcher().useReducer(reducer, initialArg, init);
      };
      exports2.useRef = function(initialValue) {
        return resolveDispatcher().useRef(initialValue);
      };
      exports2.useState = function(initialState2) {
        return resolveDispatcher().useState(initialState2);
      };
      exports2.useSyncExternalStore = function(subscribe, getSnapshot, getServerSnapshot) {
        return resolveDispatcher().useSyncExternalStore(
          subscribe,
          getSnapshot,
          getServerSnapshot
        );
      };
      exports2.useTransition = function() {
        return resolveDispatcher().useTransition();
      };
      exports2.version = "19.1.0";
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
    }();
  }
});

// node_modules/react/index.js
var require_react = __commonJS({
  "node_modules/react/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    if (process.env.NODE_ENV === "production") {
      module2.exports = require_react_production();
    } else {
      module2.exports = require_react_development();
    }
  }
});

// node_modules/ink/node_modules/signal-exit/signals.js
var require_signals = __commonJS({
  "node_modules/ink/node_modules/signal-exit/signals.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = [
      "SIGABRT",
      "SIGALRM",
      "SIGHUP",
      "SIGINT",
      "SIGTERM"
    ];
    if (process.platform !== "win32") {
      module2.exports.push(
        "SIGVTALRM",
        "SIGXCPU",
        "SIGXFSZ",
        "SIGUSR2",
        "SIGTRAP",
        "SIGSYS",
        "SIGQUIT",
        "SIGIOT"
        // should detect profiler and enable/disable accordingly.
        // see #21
        // 'SIGPROF'
      );
    }
    if (process.platform === "linux") {
      module2.exports.push(
        "SIGIO",
        "SIGPOLL",
        "SIGPWR",
        "SIGSTKFLT",
        "SIGUNUSED"
      );
    }
  }
});

// node_modules/ink/node_modules/signal-exit/index.js
var require_signal_exit = __commonJS({
  "node_modules/ink/node_modules/signal-exit/index.js"(exports2, module2) {
    init_esbuild_shims();
    var process51 = globalThis.process;
    var processOk = /* @__PURE__ */ __name(function(process52) {
      return process52 && typeof process52 === "object" && typeof process52.removeListener === "function" && typeof process52.emit === "function" && typeof process52.reallyExit === "function" && typeof process52.listeners === "function" && typeof process52.kill === "function" && typeof process52.pid === "number" && typeof process52.on === "function";
    }, "processOk");
    if (!processOk(process51)) {
      module2.exports = function() {
        return function() {
        };
      };
    } else {
      assert3 = __require("assert");
      signals = require_signals();
      isWin = /^win/i.test(process51.platform);
      EE3 = __require("events");
      if (typeof EE3 !== "function") {
        EE3 = EE3.EventEmitter;
      }
      if (process51.__signal_exit_emitter__) {
        emitter = process51.__signal_exit_emitter__;
      } else {
        emitter = process51.__signal_exit_emitter__ = new EE3();
        emitter.count = 0;
        emitter.emitted = {};
      }
      if (!emitter.infinite) {
        emitter.setMaxListeners(Infinity);
        emitter.infinite = true;
      }
      module2.exports = function(cb, opts) {
        if (!processOk(globalThis.process)) {
          return function() {
          };
        }
        assert3.equal(typeof cb, "function", "a callback must be provided for exit handler");
        if (loaded === false) {
          load();
        }
        var ev = "exit";
        if (opts && opts.alwaysLast) {
          ev = "afterexit";
        }
        var remove2 = /* @__PURE__ */ __name(function() {
          emitter.removeListener(ev, cb);
          if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) {
            unload();
          }
        }, "remove");
        emitter.on(ev, cb);
        return remove2;
      };
      unload = /* @__PURE__ */ __name(function unload2() {
        if (!loaded || !processOk(globalThis.process)) {
          return;
        }
        loaded = false;
        signals.forEach(function(sig) {
          try {
            process51.removeListener(sig, sigListeners[sig]);
          } catch (er) {
          }
        });
        process51.emit = originalProcessEmit;
        process51.reallyExit = originalProcessReallyExit;
        emitter.count -= 1;
      }, "unload");
      module2.exports.unload = unload;
      emit = /* @__PURE__ */ __name(function emit2(event, code2, signal) {
        if (emitter.emitted[event]) {
          return;
        }
        emitter.emitted[event] = true;
        emitter.emit(event, code2, signal);
      }, "emit");
      sigListeners = {};
      signals.forEach(function(sig) {
        sigListeners[sig] = /* @__PURE__ */ __name(function listener() {
          if (!processOk(globalThis.process)) {
            return;
          }
          var listeners = process51.listeners(sig);
          if (listeners.length === emitter.count) {
            unload();
            emit("exit", null, sig);
            emit("afterexit", null, sig);
            if (isWin && sig === "SIGHUP") {
              sig = "SIGINT";
            }
            process51.kill(process51.pid, sig);
          }
        }, "listener");
      });
      module2.exports.signals = function() {
        return signals;
      };
      loaded = false;
      load = /* @__PURE__ */ __name(function load2() {
        if (loaded || !processOk(globalThis.process)) {
          return;
        }
        loaded = true;
        emitter.count += 1;
        signals = signals.filter(function(sig) {
          try {
            process51.on(sig, sigListeners[sig]);
            return true;
          } catch (er) {
            return false;
          }
        });
        process51.emit = processEmit;
        process51.reallyExit = processReallyExit;
      }, "load");
      module2.exports.load = load;
      originalProcessReallyExit = process51.reallyExit;
      processReallyExit = /* @__PURE__ */ __name(function processReallyExit2(code2) {
        if (!processOk(globalThis.process)) {
          return;
        }
        process51.exitCode = code2 || /* istanbul ignore next */
        0;
        emit("exit", process51.exitCode, null);
        emit("afterexit", process51.exitCode, null);
        originalProcessReallyExit.call(process51, process51.exitCode);
      }, "processReallyExit");
      originalProcessEmit = process51.emit;
      processEmit = /* @__PURE__ */ __name(function processEmit2(ev, arg) {
        if (ev === "exit" && processOk(globalThis.process)) {
          if (arg !== void 0) {
            process51.exitCode = arg;
          }
          var ret = originalProcessEmit.apply(this, arguments);
          emit("exit", process51.exitCode, null);
          emit("afterexit", process51.exitCode, null);
          return ret;
        } else {
          return originalProcessEmit.apply(this, arguments);
        }
      }, "processEmit");
    }
    var assert3;
    var signals;
    var isWin;
    var EE3;
    var emitter;
    var unload;
    var emit;
    var sigListeners;
    var loaded;
    var load;
    var originalProcessReallyExit;
    var processReallyExit;
    var originalProcessEmit;
    var processEmit;
  }
});

// node_modules/react-reconciler/cjs/react-reconciler-constants.production.js
var require_react_reconciler_constants_production = __commonJS({
  "node_modules/react-reconciler/cjs/react-reconciler-constants.production.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    exports2.ConcurrentRoot = 1;
    exports2.ContinuousEventPriority = 8;
    exports2.DefaultEventPriority = 32;
    exports2.DiscreteEventPriority = 2;
    exports2.IdleEventPriority = 268435456;
    exports2.LegacyRoot = 0;
    exports2.NoEventPriority = 0;
  }
});

// node_modules/react-reconciler/cjs/react-reconciler-constants.development.js
var require_react_reconciler_constants_development = __commonJS({
  "node_modules/react-reconciler/cjs/react-reconciler-constants.development.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    "production" !== process.env.NODE_ENV && (exports2.ConcurrentRoot = 1, exports2.ContinuousEventPriority = 8, exports2.DefaultEventPriority = 32, exports2.DiscreteEventPriority = 2, exports2.IdleEventPriority = 268435456, exports2.LegacyRoot = 0, exports2.NoEventPriority = 0);
  }
});

// node_modules/react-reconciler/constants.js
var require_constants = __commonJS({
  "node_modules/react-reconciler/constants.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    if (process.env.NODE_ENV === "production") {
      module2.exports = require_react_reconciler_constants_production();
    } else {
      module2.exports = require_react_reconciler_constants_development();
    }
  }
});

// node_modules/ansi-regex/index.js
var ansi_regex_exports = {};
__export(ansi_regex_exports, {
  default: () => ansiRegex
});
function ansiRegex({ onlyFirst = false } = {}) {
  const ST = "(?:\\u0007|\\u001B\\u005C|\\u009C)";
  const osc = `(?:\\u001B\\][\\s\\S]*?${ST})`;
  const csi = "[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";
  const pattern = `${osc}|${csi}`;
  return new RegExp(pattern, onlyFirst ? void 0 : "g");
}
var init_ansi_regex = __esm({
  "node_modules/ansi-regex/index.js"() {
    init_esbuild_shims();
    __name(ansiRegex, "ansiRegex");
  }
});

// node_modules/strip-ansi/index.js
function stripAnsi(string) {
  if (typeof string !== "string") {
    throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
  }
  return string.replace(regex, "");
}
var regex;
var init_strip_ansi = __esm({
  "node_modules/strip-ansi/index.js"() {
    init_esbuild_shims();
    init_ansi_regex();
    regex = ansiRegex();
    __name(stripAnsi, "stripAnsi");
  }
});

// node_modules/wrap-ansi/node_modules/emoji-regex/index.js
var require_emoji_regex = __commonJS({
  "node_modules/wrap-ansi/node_modules/emoji-regex/index.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = () => {
      return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g;
    };
  }
});

// node_modules/scheduler/cjs/scheduler.production.js
var require_scheduler_production = __commonJS({
  "node_modules/scheduler/cjs/scheduler.production.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    function push2(heap, node) {
      var index = heap.length;
      heap.push(node);
      a: for (; 0 < index; ) {
        var parentIndex = index - 1 >>> 1, parent = heap[parentIndex];
        if (0 < compare(parent, node))
          heap[parentIndex] = node, heap[index] = parent, index = parentIndex;
        else break a;
      }
    }
    __name(push2, "push");
    function peek(heap) {
      return 0 === heap.length ? null : heap[0];
    }
    __name(peek, "peek");
    function pop(heap) {
      if (0 === heap.length) return null;
      var first2 = heap[0], last2 = heap.pop();
      if (last2 !== first2) {
        heap[0] = last2;
        a: for (var index = 0, length = heap.length, halfLength = length >>> 1; index < halfLength; ) {
          var leftIndex = 2 * (index + 1) - 1, left3 = heap[leftIndex], rightIndex = leftIndex + 1, right3 = heap[rightIndex];
          if (0 > compare(left3, last2))
            rightIndex < length && 0 > compare(right3, left3) ? (heap[index] = right3, heap[rightIndex] = last2, index = rightIndex) : (heap[index] = left3, heap[leftIndex] = last2, index = leftIndex);
          else if (rightIndex < length && 0 > compare(right3, last2))
            heap[index] = right3, heap[rightIndex] = last2, index = rightIndex;
          else break a;
        }
      }
      return first2;
    }
    __name(pop, "pop");
    function compare(a, b) {
      var diff4 = a.sortIndex - b.sortIndex;
      return 0 !== diff4 ? diff4 : a.id - b.id;
    }
    __name(compare, "compare");
    exports2.unstable_now = void 0;
    if ("object" === typeof performance && "function" === typeof performance.now) {
      localPerformance = performance;
      exports2.unstable_now = function() {
        return localPerformance.now();
      };
    } else {
      localDate = Date, initialTime = localDate.now();
      exports2.unstable_now = function() {
        return localDate.now() - initialTime;
      };
    }
    var localPerformance;
    var localDate;
    var initialTime;
    var taskQueue = [];
    var timerQueue = [];
    var taskIdCounter = 1;
    var currentTask = null;
    var currentPriorityLevel = 3;
    var isPerformingWork = false;
    var isHostCallbackScheduled = false;
    var isHostTimeoutScheduled = false;
    var needsPaint = false;
    var localSetTimeout = "function" === typeof setTimeout ? setTimeout : null;
    var localClearTimeout = "function" === typeof clearTimeout ? clearTimeout : null;
    var localSetImmediate = "undefined" !== typeof setImmediate ? setImmediate : null;
    function advanceTimers(currentTime) {
      for (var timer = peek(timerQueue); null !== timer; ) {
        if (null === timer.callback) pop(timerQueue);
        else if (timer.startTime <= currentTime)
          pop(timerQueue), timer.sortIndex = timer.expirationTime, push2(taskQueue, timer);
        else break;
        timer = peek(timerQueue);
      }
    }
    __name(advanceTimers, "advanceTimers");
    function handleTimeout(currentTime) {
      isHostTimeoutScheduled = false;
      advanceTimers(currentTime);
      if (!isHostCallbackScheduled)
        if (null !== peek(taskQueue))
          isHostCallbackScheduled = true, isMessageLoopRunning || (isMessageLoopRunning = true, schedulePerformWorkUntilDeadline());
        else {
          var firstTimer = peek(timerQueue);
          null !== firstTimer && requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
        }
    }
    __name(handleTimeout, "handleTimeout");
    var isMessageLoopRunning = false;
    var taskTimeoutID = -1;
    var frameInterval = 5;
    var startTime = -1;
    function shouldYieldToHost() {
      return needsPaint ? true : exports2.unstable_now() - startTime < frameInterval ? false : true;
    }
    __name(shouldYieldToHost, "shouldYieldToHost");
    function performWorkUntilDeadline() {
      needsPaint = false;
      if (isMessageLoopRunning) {
        var currentTime = exports2.unstable_now();
        startTime = currentTime;
        var hasMoreWork = true;
        try {
          a: {
            isHostCallbackScheduled = false;
            isHostTimeoutScheduled && (isHostTimeoutScheduled = false, localClearTimeout(taskTimeoutID), taskTimeoutID = -1);
            isPerformingWork = true;
            var previousPriorityLevel = currentPriorityLevel;
            try {
              b: {
                advanceTimers(currentTime);
                for (currentTask = peek(taskQueue); null !== currentTask && !(currentTask.expirationTime > currentTime && shouldYieldToHost()); ) {
                  var callback = currentTask.callback;
                  if ("function" === typeof callback) {
                    currentTask.callback = null;
                    currentPriorityLevel = currentTask.priorityLevel;
                    var continuationCallback = callback(
                      currentTask.expirationTime <= currentTime
                    );
                    currentTime = exports2.unstable_now();
                    if ("function" === typeof continuationCallback) {
                      currentTask.callback = continuationCallback;
                      advanceTimers(currentTime);
                      hasMoreWork = true;
                      break b;
                    }
                    currentTask === peek(taskQueue) && pop(taskQueue);
                    advanceTimers(currentTime);
                  } else pop(taskQueue);
                  currentTask = peek(taskQueue);
                }
                if (null !== currentTask) hasMoreWork = true;
                else {
                  var firstTimer = peek(timerQueue);
                  null !== firstTimer && requestHostTimeout(
                    handleTimeout,
                    firstTimer.startTime - currentTime
                  );
                  hasMoreWork = false;
                }
              }
              break a;
            } finally {
              currentTask = null, currentPriorityLevel = previousPriorityLevel, isPerformingWork = false;
            }
            hasMoreWork = void 0;
          }
        } finally {
          hasMoreWork ? schedulePerformWorkUntilDeadline() : isMessageLoopRunning = false;
        }
      }
    }
    __name(performWorkUntilDeadline, "performWorkUntilDeadline");
    var schedulePerformWorkUntilDeadline;
    if ("function" === typeof localSetImmediate)
      schedulePerformWorkUntilDeadline = /* @__PURE__ */ __name(function() {
        localSetImmediate(performWorkUntilDeadline);
      }, "schedulePerformWorkUntilDeadline");
    else if ("undefined" !== typeof MessageChannel) {
      channel = new MessageChannel(), port = channel.port2;
      channel.port1.onmessage = performWorkUntilDeadline;
      schedulePerformWorkUntilDeadline = /* @__PURE__ */ __name(function() {
        port.postMessage(null);
      }, "schedulePerformWorkUntilDeadline");
    } else
      schedulePerformWorkUntilDeadline = /* @__PURE__ */ __name(function() {
        localSetTimeout(performWorkUntilDeadline, 0);
      }, "schedulePerformWorkUntilDeadline");
    var channel;
    var port;
    function requestHostTimeout(callback, ms) {
      taskTimeoutID = localSetTimeout(function() {
        callback(exports2.unstable_now());
      }, ms);
    }
    __name(requestHostTimeout, "requestHostTimeout");
    exports2.unstable_IdlePriority = 5;
    exports2.unstable_ImmediatePriority = 1;
    exports2.unstable_LowPriority = 4;
    exports2.unstable_NormalPriority = 3;
    exports2.unstable_Profiling = null;
    exports2.unstable_UserBlockingPriority = 2;
    exports2.unstable_cancelCallback = function(task) {
      task.callback = null;
    };
    exports2.unstable_forceFrameRate = function(fps) {
      0 > fps || 125 < fps ? console.error(
        "forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"
      ) : frameInterval = 0 < fps ? Math.floor(1e3 / fps) : 5;
    };
    exports2.unstable_getCurrentPriorityLevel = function() {
      return currentPriorityLevel;
    };
    exports2.unstable_next = function(eventHandler) {
      switch (currentPriorityLevel) {
        case 1:
        case 2:
        case 3:
          var priorityLevel = 3;
          break;
        default:
          priorityLevel = currentPriorityLevel;
      }
      var previousPriorityLevel = currentPriorityLevel;
      currentPriorityLevel = priorityLevel;
      try {
        return eventHandler();
      } finally {
        currentPriorityLevel = previousPriorityLevel;
      }
    };
    exports2.unstable_requestPaint = function() {
      needsPaint = true;
    };
    exports2.unstable_runWithPriority = function(priorityLevel, eventHandler) {
      switch (priorityLevel) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
          break;
        default:
          priorityLevel = 3;
      }
      var previousPriorityLevel = currentPriorityLevel;
      currentPriorityLevel = priorityLevel;
      try {
        return eventHandler();
      } finally {
        currentPriorityLevel = previousPriorityLevel;
      }
    };
    exports2.unstable_scheduleCallback = function(priorityLevel, callback, options2) {
      var currentTime = exports2.unstable_now();
      "object" === typeof options2 && null !== options2 ? (options2 = options2.delay, options2 = "number" === typeof options2 && 0 < options2 ? currentTime + options2 : currentTime) : options2 = currentTime;
      switch (priorityLevel) {
        case 1:
          var timeout2 = -1;
          break;
        case 2:
          timeout2 = 250;
          break;
        case 5:
          timeout2 = 1073741823;
          break;
        case 4:
          timeout2 = 1e4;
          break;
        default:
          timeout2 = 5e3;
      }
      timeout2 = options2 + timeout2;
      priorityLevel = {
        id: taskIdCounter++,
        callback,
        priorityLevel,
        startTime: options2,
        expirationTime: timeout2,
        sortIndex: -1
      };
      options2 > currentTime ? (priorityLevel.sortIndex = options2, push2(timerQueue, priorityLevel), null === peek(taskQueue) && priorityLevel === peek(timerQueue) && (isHostTimeoutScheduled ? (localClearTimeout(taskTimeoutID), taskTimeoutID = -1) : isHostTimeoutScheduled = true, requestHostTimeout(handleTimeout, options2 - currentTime))) : (priorityLevel.sortIndex = timeout2, push2(taskQueue, priorityLevel), isHostCallbackScheduled || isPerformingWork || (isHostCallbackScheduled = true, isMessageLoopRunning || (isMessageLoopRunning = true, schedulePerformWorkUntilDeadline())));
      return priorityLevel;
    };
    exports2.unstable_shouldYield = shouldYieldToHost;
    exports2.unstable_wrapCallback = function(callback) {
      var parentPriorityLevel = currentPriorityLevel;
      return function() {
        var previousPriorityLevel = currentPriorityLevel;
        currentPriorityLevel = parentPriorityLevel;
        try {
          return callback.apply(this, arguments);
        } finally {
          currentPriorityLevel = previousPriorityLevel;
        }
      };
    };
  }
});

// node_modules/scheduler/cjs/scheduler.development.js
var require_scheduler_development = __commonJS({
  "node_modules/scheduler/cjs/scheduler.development.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    "production" !== process.env.NODE_ENV && function() {
      function performWorkUntilDeadline() {
        needsPaint = false;
        if (isMessageLoopRunning) {
          var currentTime = exports2.unstable_now();
          startTime = currentTime;
          var hasMoreWork = true;
          try {
            a: {
              isHostCallbackScheduled = false;
              isHostTimeoutScheduled && (isHostTimeoutScheduled = false, localClearTimeout(taskTimeoutID), taskTimeoutID = -1);
              isPerformingWork = true;
              var previousPriorityLevel = currentPriorityLevel;
              try {
                b: {
                  advanceTimers(currentTime);
                  for (currentTask = peek(taskQueue); null !== currentTask && !(currentTask.expirationTime > currentTime && shouldYieldToHost()); ) {
                    var callback = currentTask.callback;
                    if ("function" === typeof callback) {
                      currentTask.callback = null;
                      currentPriorityLevel = currentTask.priorityLevel;
                      var continuationCallback = callback(
                        currentTask.expirationTime <= currentTime
                      );
                      currentTime = exports2.unstable_now();
                      if ("function" === typeof continuationCallback) {
                        currentTask.callback = continuationCallback;
                        advanceTimers(currentTime);
                        hasMoreWork = true;
                        break b;
                      }
                      currentTask === peek(taskQueue) && pop(taskQueue);
                      advanceTimers(currentTime);
                    } else pop(taskQueue);
                    currentTask = peek(taskQueue);
                  }
                  if (null !== currentTask) hasMoreWork = true;
                  else {
                    var firstTimer = peek(timerQueue);
                    null !== firstTimer && requestHostTimeout(
                      handleTimeout,
                      firstTimer.startTime - currentTime
                    );
                    hasMoreWork = false;
                  }
                }
                break a;
              } finally {
                currentTask = null, currentPriorityLevel = previousPriorityLevel, isPerformingWork = false;
              }
              hasMoreWork = void 0;
            }
          } finally {
            hasMoreWork ? schedulePerformWorkUntilDeadline() : isMessageLoopRunning = false;
          }
        }
      }
      __name(performWorkUntilDeadline, "performWorkUntilDeadline");
      function push2(heap, node) {
        var index = heap.length;
        heap.push(node);
        a: for (; 0 < index; ) {
          var parentIndex = index - 1 >>> 1, parent = heap[parentIndex];
          if (0 < compare(parent, node))
            heap[parentIndex] = node, heap[index] = parent, index = parentIndex;
          else break a;
        }
      }
      __name(push2, "push");
      function peek(heap) {
        return 0 === heap.length ? null : heap[0];
      }
      __name(peek, "peek");
      function pop(heap) {
        if (0 === heap.length) return null;
        var first2 = heap[0], last2 = heap.pop();
        if (last2 !== first2) {
          heap[0] = last2;
          a: for (var index = 0, length = heap.length, halfLength = length >>> 1; index < halfLength; ) {
            var leftIndex = 2 * (index + 1) - 1, left3 = heap[leftIndex], rightIndex = leftIndex + 1, right3 = heap[rightIndex];
            if (0 > compare(left3, last2))
              rightIndex < length && 0 > compare(right3, left3) ? (heap[index] = right3, heap[rightIndex] = last2, index = rightIndex) : (heap[index] = left3, heap[leftIndex] = last2, index = leftIndex);
            else if (rightIndex < length && 0 > compare(right3, last2))
              heap[index] = right3, heap[rightIndex] = last2, index = rightIndex;
            else break a;
          }
        }
        return first2;
      }
      __name(pop, "pop");
      function compare(a, b) {
        var diff4 = a.sortIndex - b.sortIndex;
        return 0 !== diff4 ? diff4 : a.id - b.id;
      }
      __name(compare, "compare");
      function advanceTimers(currentTime) {
        for (var timer = peek(timerQueue); null !== timer; ) {
          if (null === timer.callback) pop(timerQueue);
          else if (timer.startTime <= currentTime)
            pop(timerQueue), timer.sortIndex = timer.expirationTime, push2(taskQueue, timer);
          else break;
          timer = peek(timerQueue);
        }
      }
      __name(advanceTimers, "advanceTimers");
      function handleTimeout(currentTime) {
        isHostTimeoutScheduled = false;
        advanceTimers(currentTime);
        if (!isHostCallbackScheduled)
          if (null !== peek(taskQueue))
            isHostCallbackScheduled = true, isMessageLoopRunning || (isMessageLoopRunning = true, schedulePerformWorkUntilDeadline());
          else {
            var firstTimer = peek(timerQueue);
            null !== firstTimer && requestHostTimeout(
              handleTimeout,
              firstTimer.startTime - currentTime
            );
          }
      }
      __name(handleTimeout, "handleTimeout");
      function shouldYieldToHost() {
        return needsPaint ? true : exports2.unstable_now() - startTime < frameInterval ? false : true;
      }
      __name(shouldYieldToHost, "shouldYieldToHost");
      function requestHostTimeout(callback, ms) {
        taskTimeoutID = localSetTimeout(function() {
          callback(exports2.unstable_now());
        }, ms);
      }
      __name(requestHostTimeout, "requestHostTimeout");
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
      exports2.unstable_now = void 0;
      if ("object" === typeof performance && "function" === typeof performance.now) {
        var localPerformance = performance;
        exports2.unstable_now = function() {
          return localPerformance.now();
        };
      } else {
        var localDate = Date, initialTime = localDate.now();
        exports2.unstable_now = function() {
          return localDate.now() - initialTime;
        };
      }
      var taskQueue = [], timerQueue = [], taskIdCounter = 1, currentTask = null, currentPriorityLevel = 3, isPerformingWork = false, isHostCallbackScheduled = false, isHostTimeoutScheduled = false, needsPaint = false, localSetTimeout = "function" === typeof setTimeout ? setTimeout : null, localClearTimeout = "function" === typeof clearTimeout ? clearTimeout : null, localSetImmediate = "undefined" !== typeof setImmediate ? setImmediate : null, isMessageLoopRunning = false, taskTimeoutID = -1, frameInterval = 5, startTime = -1;
      if ("function" === typeof localSetImmediate)
        var schedulePerformWorkUntilDeadline = /* @__PURE__ */ __name(function() {
          localSetImmediate(performWorkUntilDeadline);
        }, "schedulePerformWorkUntilDeadline");
      else if ("undefined" !== typeof MessageChannel) {
        var channel = new MessageChannel(), port = channel.port2;
        channel.port1.onmessage = performWorkUntilDeadline;
        schedulePerformWorkUntilDeadline = /* @__PURE__ */ __name(function() {
          port.postMessage(null);
        }, "schedulePerformWorkUntilDeadline");
      } else
        schedulePerformWorkUntilDeadline = /* @__PURE__ */ __name(function() {
          localSetTimeout(performWorkUntilDeadline, 0);
        }, "schedulePerformWorkUntilDeadline");
      exports2.unstable_IdlePriority = 5;
      exports2.unstable_ImmediatePriority = 1;
      exports2.unstable_LowPriority = 4;
      exports2.unstable_NormalPriority = 3;
      exports2.unstable_Profiling = null;
      exports2.unstable_UserBlockingPriority = 2;
      exports2.unstable_cancelCallback = function(task) {
        task.callback = null;
      };
      exports2.unstable_forceFrameRate = function(fps) {
        0 > fps || 125 < fps ? console.error(
          "forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"
        ) : frameInterval = 0 < fps ? Math.floor(1e3 / fps) : 5;
      };
      exports2.unstable_getCurrentPriorityLevel = function() {
        return currentPriorityLevel;
      };
      exports2.unstable_next = function(eventHandler) {
        switch (currentPriorityLevel) {
          case 1:
          case 2:
          case 3:
            var priorityLevel = 3;
            break;
          default:
            priorityLevel = currentPriorityLevel;
        }
        var previousPriorityLevel = currentPriorityLevel;
        currentPriorityLevel = priorityLevel;
        try {
          return eventHandler();
        } finally {
          currentPriorityLevel = previousPriorityLevel;
        }
      };
      exports2.unstable_requestPaint = function() {
        needsPaint = true;
      };
      exports2.unstable_runWithPriority = function(priorityLevel, eventHandler) {
        switch (priorityLevel) {
          case 1:
          case 2:
          case 3:
          case 4:
          case 5:
            break;
          default:
            priorityLevel = 3;
        }
        var previousPriorityLevel = currentPriorityLevel;
        currentPriorityLevel = priorityLevel;
        try {
          return eventHandler();
        } finally {
          currentPriorityLevel = previousPriorityLevel;
        }
      };
      exports2.unstable_scheduleCallback = function(priorityLevel, callback, options2) {
        var currentTime = exports2.unstable_now();
        "object" === typeof options2 && null !== options2 ? (options2 = options2.delay, options2 = "number" === typeof options2 && 0 < options2 ? currentTime + options2 : currentTime) : options2 = currentTime;
        switch (priorityLevel) {
          case 1:
            var timeout2 = -1;
            break;
          case 2:
            timeout2 = 250;
            break;
          case 5:
            timeout2 = 1073741823;
            break;
          case 4:
            timeout2 = 1e4;
            break;
          default:
            timeout2 = 5e3;
        }
        timeout2 = options2 + timeout2;
        priorityLevel = {
          id: taskIdCounter++,
          callback,
          priorityLevel,
          startTime: options2,
          expirationTime: timeout2,
          sortIndex: -1
        };
        options2 > currentTime ? (priorityLevel.sortIndex = options2, push2(timerQueue, priorityLevel), null === peek(taskQueue) && priorityLevel === peek(timerQueue) && (isHostTimeoutScheduled ? (localClearTimeout(taskTimeoutID), taskTimeoutID = -1) : isHostTimeoutScheduled = true, requestHostTimeout(handleTimeout, options2 - currentTime))) : (priorityLevel.sortIndex = timeout2, push2(taskQueue, priorityLevel), isHostCallbackScheduled || isPerformingWork || (isHostCallbackScheduled = true, isMessageLoopRunning || (isMessageLoopRunning = true, schedulePerformWorkUntilDeadline())));
        return priorityLevel;
      };
      exports2.unstable_shouldYield = shouldYieldToHost;
      exports2.unstable_wrapCallback = function(callback) {
        var parentPriorityLevel = currentPriorityLevel;
        return function() {
          var previousPriorityLevel = currentPriorityLevel;
          currentPriorityLevel = parentPriorityLevel;
          try {
            return callback.apply(this, arguments);
          } finally {
            currentPriorityLevel = previousPriorityLevel;
          }
        };
      };
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
    }();
  }
});

// node_modules/scheduler/index.js
var require_scheduler = __commonJS({
  "node_modules/scheduler/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    if (process.env.NODE_ENV === "production") {
      module2.exports = require_scheduler_production();
    } else {
      module2.exports = require_scheduler_development();
    }
  }
});

// node_modules/react-reconciler/cjs/react-reconciler.production.js
var require_react_reconciler_production = __commonJS({
  "node_modules/react-reconciler/cjs/react-reconciler.production.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = function($$$config) {
      function createFiber(tag2, pendingProps, key, mode) {
        return new FiberNode(tag2, pendingProps, key, mode);
      }
      __name(createFiber, "createFiber");
      function noop6() {
      }
      __name(noop6, "noop");
      function formatProdErrorMessage(code2) {
        var url2 = "https://react.dev/errors/" + code2;
        if (1 < arguments.length) {
          url2 += "?args[]=" + encodeURIComponent(arguments[1]);
          for (var i = 2; i < arguments.length; i++)
            url2 += "&args[]=" + encodeURIComponent(arguments[i]);
        }
        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.";
      }
      __name(formatProdErrorMessage, "formatProdErrorMessage");
      function getNearestMountedFiber(fiber) {
        var node = fiber, nearestMounted = fiber;
        if (fiber.alternate) for (; node.return; ) node = node.return;
        else {
          fiber = node;
          do
            node = fiber, 0 !== (node.flags & 4098) && (nearestMounted = node.return), fiber = node.return;
          while (fiber);
        }
        return 3 === node.tag ? nearestMounted : null;
      }
      __name(getNearestMountedFiber, "getNearestMountedFiber");
      function assertIsMounted(fiber) {
        if (getNearestMountedFiber(fiber) !== fiber)
          throw Error(formatProdErrorMessage(188));
      }
      __name(assertIsMounted, "assertIsMounted");
      function findCurrentFiberUsingSlowPath(fiber) {
        var alternate = fiber.alternate;
        if (!alternate) {
          alternate = getNearestMountedFiber(fiber);
          if (null === alternate) throw Error(formatProdErrorMessage(188));
          return alternate !== fiber ? null : fiber;
        }
        for (var a = fiber, b = alternate; ; ) {
          var parentA = a.return;
          if (null === parentA) break;
          var parentB = parentA.alternate;
          if (null === parentB) {
            b = parentA.return;
            if (null !== b) {
              a = b;
              continue;
            }
            break;
          }
          if (parentA.child === parentB.child) {
            for (parentB = parentA.child; parentB; ) {
              if (parentB === a) return assertIsMounted(parentA), fiber;
              if (parentB === b) return assertIsMounted(parentA), alternate;
              parentB = parentB.sibling;
            }
            throw Error(formatProdErrorMessage(188));
          }
          if (a.return !== b.return) a = parentA, b = parentB;
          else {
            for (var didFindChild = false, child$0 = parentA.child; child$0; ) {
              if (child$0 === a) {
                didFindChild = true;
                a = parentA;
                b = parentB;
                break;
              }
              if (child$0 === b) {
                didFindChild = true;
                b = parentA;
                a = parentB;
                break;
              }
              child$0 = child$0.sibling;
            }
            if (!didFindChild) {
              for (child$0 = parentB.child; child$0; ) {
                if (child$0 === a) {
                  didFindChild = true;
                  a = parentB;
                  b = parentA;
                  break;
                }
                if (child$0 === b) {
                  didFindChild = true;
                  b = parentB;
                  a = parentA;
                  break;
                }
                child$0 = child$0.sibling;
              }
              if (!didFindChild) throw Error(formatProdErrorMessage(189));
            }
          }
          if (a.alternate !== b) throw Error(formatProdErrorMessage(190));
        }
        if (3 !== a.tag) throw Error(formatProdErrorMessage(188));
        return a.stateNode.current === a ? fiber : alternate;
      }
      __name(findCurrentFiberUsingSlowPath, "findCurrentFiberUsingSlowPath");
      function findCurrentHostFiberImpl(node) {
        var tag2 = node.tag;
        if (5 === tag2 || 26 === tag2 || 27 === tag2 || 6 === tag2) return node;
        for (node = node.child; null !== node; ) {
          tag2 = findCurrentHostFiberImpl(node);
          if (null !== tag2) return tag2;
          node = node.sibling;
        }
        return null;
      }
      __name(findCurrentHostFiberImpl, "findCurrentHostFiberImpl");
      function findCurrentHostFiberWithNoPortalsImpl(node) {
        var tag2 = node.tag;
        if (5 === tag2 || 26 === tag2 || 27 === tag2 || 6 === tag2) return node;
        for (node = node.child; null !== node; ) {
          if (4 !== node.tag && (tag2 = findCurrentHostFiberWithNoPortalsImpl(node), null !== tag2))
            return tag2;
          node = node.sibling;
        }
        return null;
      }
      __name(findCurrentHostFiberWithNoPortalsImpl, "findCurrentHostFiberWithNoPortalsImpl");
      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;
      }
      __name(getIteratorFn, "getIteratorFn");
      function getComponentNameFromType(type) {
        if (null == type) return null;
        if ("function" === typeof type)
          return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
        if ("string" === typeof type) return type;
        switch (type) {
          case REACT_FRAGMENT_TYPE:
            return "Fragment";
          case REACT_PROFILER_TYPE:
            return "Profiler";
          case REACT_STRICT_MODE_TYPE:
            return "StrictMode";
          case REACT_SUSPENSE_TYPE:
            return "Suspense";
          case REACT_SUSPENSE_LIST_TYPE:
            return "SuspenseList";
          case REACT_ACTIVITY_TYPE:
            return "Activity";
        }
        if ("object" === typeof type)
          switch (type.$$typeof) {
            case REACT_PORTAL_TYPE:
              return "Portal";
            case REACT_CONTEXT_TYPE:
              return (type.displayName || "Context") + ".Provider";
            case REACT_CONSUMER_TYPE:
              return (type._context.displayName || "Context") + ".Consumer";
            case REACT_FORWARD_REF_TYPE:
              var innerType = type.render;
              type = type.displayName;
              type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
              return type;
            case REACT_MEMO_TYPE:
              return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
            case REACT_LAZY_TYPE:
              innerType = type._payload;
              type = type._init;
              try {
                return getComponentNameFromType(type(innerType));
              } catch (x) {
              }
          }
        return null;
      }
      __name(getComponentNameFromType, "getComponentNameFromType");
      function createCursor(defaultValue) {
        return { current: defaultValue };
      }
      __name(createCursor, "createCursor");
      function pop(cursor) {
        0 > index$jscomp$0 || (cursor.current = valueStack[index$jscomp$0], valueStack[index$jscomp$0] = null, index$jscomp$0--);
      }
      __name(pop, "pop");
      function push2(cursor, value) {
        index$jscomp$0++;
        valueStack[index$jscomp$0] = cursor.current;
        cursor.current = value;
      }
      __name(push2, "push");
      function clz32Fallback(x) {
        x >>>= 0;
        return 0 === x ? 32 : 31 - (log$1(x) / LN2 | 0) | 0;
      }
      __name(clz32Fallback, "clz32Fallback");
      function getHighestPriorityLanes(lanes) {
        var pendingSyncLanes = lanes & 42;
        if (0 !== pendingSyncLanes) return pendingSyncLanes;
        switch (lanes & -lanes) {
          case 1:
            return 1;
          case 2:
            return 2;
          case 4:
            return 4;
          case 8:
            return 8;
          case 16:
            return 16;
          case 32:
            return 32;
          case 64:
            return 64;
          case 128:
            return 128;
          case 256:
          case 512:
          case 1024:
          case 2048:
          case 4096:
          case 8192:
          case 16384:
          case 32768:
          case 65536:
          case 131072:
          case 262144:
          case 524288:
          case 1048576:
          case 2097152:
            return lanes & 4194048;
          case 4194304:
          case 8388608:
          case 16777216:
          case 33554432:
            return lanes & 62914560;
          case 67108864:
            return 67108864;
          case 134217728:
            return 134217728;
          case 268435456:
            return 268435456;
          case 536870912:
            return 536870912;
          case 1073741824:
            return 0;
          default:
            return lanes;
        }
      }
      __name(getHighestPriorityLanes, "getHighestPriorityLanes");
      function getNextLanes(root, wipLanes, rootHasPendingCommit) {
        var pendingLanes = root.pendingLanes;
        if (0 === pendingLanes) return 0;
        var nextLanes = 0, suspendedLanes = root.suspendedLanes, pingedLanes = root.pingedLanes;
        root = root.warmLanes;
        var nonIdlePendingLanes = pendingLanes & 134217727;
        0 !== nonIdlePendingLanes ? (pendingLanes = nonIdlePendingLanes & ~suspendedLanes, 0 !== pendingLanes ? nextLanes = getHighestPriorityLanes(pendingLanes) : (pingedLanes &= nonIdlePendingLanes, 0 !== pingedLanes ? nextLanes = getHighestPriorityLanes(pingedLanes) : rootHasPendingCommit || (rootHasPendingCommit = nonIdlePendingLanes & ~root, 0 !== rootHasPendingCommit && (nextLanes = getHighestPriorityLanes(rootHasPendingCommit))))) : (nonIdlePendingLanes = pendingLanes & ~suspendedLanes, 0 !== nonIdlePendingLanes ? nextLanes = getHighestPriorityLanes(nonIdlePendingLanes) : 0 !== pingedLanes ? nextLanes = getHighestPriorityLanes(pingedLanes) : rootHasPendingCommit || (rootHasPendingCommit = pendingLanes & ~root, 0 !== rootHasPendingCommit && (nextLanes = getHighestPriorityLanes(rootHasPendingCommit))));
        return 0 === nextLanes ? 0 : 0 !== wipLanes && wipLanes !== nextLanes && 0 === (wipLanes & suspendedLanes) && (suspendedLanes = nextLanes & -nextLanes, rootHasPendingCommit = wipLanes & -wipLanes, suspendedLanes >= rootHasPendingCommit || 32 === suspendedLanes && 0 !== (rootHasPendingCommit & 4194048)) ? wipLanes : nextLanes;
      }
      __name(getNextLanes, "getNextLanes");
      function checkIfRootIsPrerendering(root, renderLanes2) {
        return 0 === (root.pendingLanes & ~(root.suspendedLanes & ~root.pingedLanes) & renderLanes2);
      }
      __name(checkIfRootIsPrerendering, "checkIfRootIsPrerendering");
      function computeExpirationTime(lane, currentTime) {
        switch (lane) {
          case 1:
          case 2:
          case 4:
          case 8:
          case 64:
            return currentTime + 250;
          case 16:
          case 32:
          case 128:
          case 256:
          case 512:
          case 1024:
          case 2048:
          case 4096:
          case 8192:
          case 16384:
          case 32768:
          case 65536:
          case 131072:
          case 262144:
          case 524288:
          case 1048576:
          case 2097152:
            return currentTime + 5e3;
          case 4194304:
          case 8388608:
          case 16777216:
          case 33554432:
            return -1;
          case 67108864:
          case 134217728:
          case 268435456:
          case 536870912:
          case 1073741824:
            return -1;
          default:
            return -1;
        }
      }
      __name(computeExpirationTime, "computeExpirationTime");
      function claimNextTransitionLane() {
        var lane = nextTransitionLane;
        nextTransitionLane <<= 1;
        0 === (nextTransitionLane & 4194048) && (nextTransitionLane = 256);
        return lane;
      }
      __name(claimNextTransitionLane, "claimNextTransitionLane");
      function claimNextRetryLane() {
        var lane = nextRetryLane;
        nextRetryLane <<= 1;
        0 === (nextRetryLane & 62914560) && (nextRetryLane = 4194304);
        return lane;
      }
      __name(claimNextRetryLane, "claimNextRetryLane");
      function createLaneMap(initial) {
        for (var laneMap = [], i = 0; 31 > i; i++) laneMap.push(initial);
        return laneMap;
      }
      __name(createLaneMap, "createLaneMap");
      function markRootUpdated$1(root, updateLane) {
        root.pendingLanes |= updateLane;
        268435456 !== updateLane && (root.suspendedLanes = 0, root.pingedLanes = 0, root.warmLanes = 0);
      }
      __name(markRootUpdated$1, "markRootUpdated$1");
      function markRootFinished(root, finishedLanes, remainingLanes, spawnedLane, updatedLanes, suspendedRetryLanes) {
        var previouslyPendingLanes = root.pendingLanes;
        root.pendingLanes = remainingLanes;
        root.suspendedLanes = 0;
        root.pingedLanes = 0;
        root.warmLanes = 0;
        root.expiredLanes &= remainingLanes;
        root.entangledLanes &= remainingLanes;
        root.errorRecoveryDisabledLanes &= remainingLanes;
        root.shellSuspendCounter = 0;
        var entanglements = root.entanglements, expirationTimes = root.expirationTimes, hiddenUpdates = root.hiddenUpdates;
        for (remainingLanes = previouslyPendingLanes & ~remainingLanes; 0 < remainingLanes; ) {
          var index$5 = 31 - clz32(remainingLanes), lane = 1 << index$5;
          entanglements[index$5] = 0;
          expirationTimes[index$5] = -1;
          var hiddenUpdatesForLane = hiddenUpdates[index$5];
          if (null !== hiddenUpdatesForLane)
            for (hiddenUpdates[index$5] = null, index$5 = 0; index$5 < hiddenUpdatesForLane.length; index$5++) {
              var update2 = hiddenUpdatesForLane[index$5];
              null !== update2 && (update2.lane &= -536870913);
            }
          remainingLanes &= ~lane;
        }
        0 !== spawnedLane && markSpawnedDeferredLane(root, spawnedLane, 0);
        0 !== suspendedRetryLanes && 0 === updatedLanes && 0 !== root.tag && (root.suspendedLanes |= suspendedRetryLanes & ~(previouslyPendingLanes & ~finishedLanes));
      }
      __name(markRootFinished, "markRootFinished");
      function markSpawnedDeferredLane(root, spawnedLane, entangledLanes) {
        root.pendingLanes |= spawnedLane;
        root.suspendedLanes &= ~spawnedLane;
        var spawnedLaneIndex = 31 - clz32(spawnedLane);
        root.entangledLanes |= spawnedLane;
        root.entanglements[spawnedLaneIndex] = root.entanglements[spawnedLaneIndex] | 1073741824 | entangledLanes & 4194090;
      }
      __name(markSpawnedDeferredLane, "markSpawnedDeferredLane");
      function markRootEntangled(root, entangledLanes) {
        var rootEntangledLanes = root.entangledLanes |= entangledLanes;
        for (root = root.entanglements; rootEntangledLanes; ) {
          var index$6 = 31 - clz32(rootEntangledLanes), lane = 1 << index$6;
          lane & entangledLanes | root[index$6] & entangledLanes && (root[index$6] |= entangledLanes);
          rootEntangledLanes &= ~lane;
        }
      }
      __name(markRootEntangled, "markRootEntangled");
      function getBumpedLaneForHydrationByLane(lane) {
        switch (lane) {
          case 2:
            lane = 1;
            break;
          case 8:
            lane = 4;
            break;
          case 32:
            lane = 16;
            break;
          case 256:
          case 512:
          case 1024:
          case 2048:
          case 4096:
          case 8192:
          case 16384:
          case 32768:
          case 65536:
          case 131072:
          case 262144:
          case 524288:
          case 1048576:
          case 2097152:
          case 4194304:
          case 8388608:
          case 16777216:
          case 33554432:
            lane = 128;
            break;
          case 268435456:
            lane = 134217728;
            break;
          default:
            lane = 0;
        }
        return lane;
      }
      __name(getBumpedLaneForHydrationByLane, "getBumpedLaneForHydrationByLane");
      function lanesToEventPriority(lanes) {
        lanes &= -lanes;
        return 2 < lanes ? 8 < lanes ? 0 !== (lanes & 134217727) ? 32 : 268435456 : 8 : 2;
      }
      __name(lanesToEventPriority, "lanesToEventPriority");
      function setIsStrictModeForDevtools(newIsStrictMode) {
        "function" === typeof log && unstable_setDisableYieldValue(newIsStrictMode);
        if (injectedHook && "function" === typeof injectedHook.setStrictMode)
          try {
            injectedHook.setStrictMode(rendererID, newIsStrictMode);
          } catch (err) {
          }
      }
      __name(setIsStrictModeForDevtools, "setIsStrictModeForDevtools");
      function describeBuiltInComponentFrame(name3) {
        if (void 0 === prefix)
          try {
            throw Error();
          } catch (x) {
            var match2 = x.stack.trim().match(/\n( *(at )?)/);
            prefix = match2 && match2[1] || "";
            suffix = -1 < x.stack.indexOf("\n    at") ? " (<anonymous>)" : -1 < x.stack.indexOf("@") ? "@unknown:0:0" : "";
          }
        return "\n" + prefix + name3 + suffix;
      }
      __name(describeBuiltInComponentFrame, "describeBuiltInComponentFrame");
      function describeNativeComponentFrame(fn, construct) {
        if (!fn || reentry) return "";
        reentry = true;
        var previousPrepareStackTrace = Error.prepareStackTrace;
        Error.prepareStackTrace = void 0;
        try {
          var RunInRootFrame = {
            DetermineComponentFrameRoot: /* @__PURE__ */ __name(function() {
              try {
                if (construct) {
                  var Fake = /* @__PURE__ */ __name(function() {
                    throw Error();
                  }, "Fake");
                  Object.defineProperty(Fake.prototype, "props", {
                    set: /* @__PURE__ */ __name(function() {
                      throw Error();
                    }, "set")
                  });
                  if ("object" === typeof Reflect && Reflect.construct) {
                    try {
                      Reflect.construct(Fake, []);
                    } catch (x) {
                      var control = x;
                    }
                    Reflect.construct(fn, [], Fake);
                  } else {
                    try {
                      Fake.call();
                    } catch (x$8) {
                      control = x$8;
                    }
                    fn.call(Fake.prototype);
                  }
                } else {
                  try {
                    throw Error();
                  } catch (x$9) {
                    control = x$9;
                  }
                  (Fake = fn()) && "function" === typeof Fake.catch && Fake.catch(function() {
                  });
                }
              } catch (sample) {
                if (sample && control && "string" === typeof sample.stack)
                  return [sample.stack, control.stack];
              }
              return [null, null];
            }, "DetermineComponentFrameRoot")
          };
          RunInRootFrame.DetermineComponentFrameRoot.displayName = "DetermineComponentFrameRoot";
          var namePropDescriptor = Object.getOwnPropertyDescriptor(
            RunInRootFrame.DetermineComponentFrameRoot,
            "name"
          );
          namePropDescriptor && namePropDescriptor.configurable && Object.defineProperty(
            RunInRootFrame.DetermineComponentFrameRoot,
            "name",
            { value: "DetermineComponentFrameRoot" }
          );
          var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), sampleStack = _RunInRootFrame$Deter[0], controlStack = _RunInRootFrame$Deter[1];
          if (sampleStack && controlStack) {
            var sampleLines = sampleStack.split("\n"), controlLines = controlStack.split("\n");
            for (namePropDescriptor = RunInRootFrame = 0; RunInRootFrame < sampleLines.length && !sampleLines[RunInRootFrame].includes("DetermineComponentFrameRoot"); )
              RunInRootFrame++;
            for (; namePropDescriptor < controlLines.length && !controlLines[namePropDescriptor].includes(
              "DetermineComponentFrameRoot"
            ); )
              namePropDescriptor++;
            if (RunInRootFrame === sampleLines.length || namePropDescriptor === controlLines.length)
              for (RunInRootFrame = sampleLines.length - 1, namePropDescriptor = controlLines.length - 1; 1 <= RunInRootFrame && 0 <= namePropDescriptor && sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]; )
                namePropDescriptor--;
            for (; 1 <= RunInRootFrame && 0 <= namePropDescriptor; RunInRootFrame--, namePropDescriptor--)
              if (sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) {
                if (1 !== RunInRootFrame || 1 !== namePropDescriptor) {
                  do
                    if (RunInRootFrame--, namePropDescriptor--, 0 > namePropDescriptor || sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) {
                      var frame = "\n" + sampleLines[RunInRootFrame].replace(" at new ", " at ");
                      fn.displayName && frame.includes("<anonymous>") && (frame = frame.replace("<anonymous>", fn.displayName));
                      return frame;
                    }
                  while (1 <= RunInRootFrame && 0 <= namePropDescriptor);
                }
                break;
              }
          }
        } finally {
          reentry = false, Error.prepareStackTrace = previousPrepareStackTrace;
        }
        return (previousPrepareStackTrace = fn ? fn.displayName || fn.name : "") ? describeBuiltInComponentFrame(previousPrepareStackTrace) : "";
      }
      __name(describeNativeComponentFrame, "describeNativeComponentFrame");
      function describeFiber(fiber) {
        switch (fiber.tag) {
          case 26:
          case 27:
          case 5:
            return describeBuiltInComponentFrame(fiber.type);
          case 16:
            return describeBuiltInComponentFrame("Lazy");
          case 13:
            return describeBuiltInComponentFrame("Suspense");
          case 19:
            return describeBuiltInComponentFrame("SuspenseList");
          case 0:
          case 15:
            return describeNativeComponentFrame(fiber.type, false);
          case 11:
            return describeNativeComponentFrame(fiber.type.render, false);
          case 1:
            return describeNativeComponentFrame(fiber.type, true);
          case 31:
            return describeBuiltInComponentFrame("Activity");
          default:
            return "";
        }
      }
      __name(describeFiber, "describeFiber");
      function getStackByFiberInDevAndProd(workInProgress2) {
        try {
          var info = "";
          do
            info += describeFiber(workInProgress2), workInProgress2 = workInProgress2.return;
          while (workInProgress2);
          return info;
        } catch (x) {
          return "\nError generating stack: " + x.message + "\n" + x.stack;
        }
      }
      __name(getStackByFiberInDevAndProd, "getStackByFiberInDevAndProd");
      function createCapturedValueAtFiber(value, source2) {
        if ("object" === typeof value && null !== value) {
          var existing = CapturedStacks.get(value);
          if (void 0 !== existing) return existing;
          source2 = {
            value,
            source: source2,
            stack: getStackByFiberInDevAndProd(source2)
          };
          CapturedStacks.set(value, source2);
          return source2;
        }
        return {
          value,
          source: source2,
          stack: getStackByFiberInDevAndProd(source2)
        };
      }
      __name(createCapturedValueAtFiber, "createCapturedValueAtFiber");
      function pushTreeFork(workInProgress2, totalChildren) {
        forkStack[forkStackIndex++] = treeForkCount;
        forkStack[forkStackIndex++] = treeForkProvider;
        treeForkProvider = workInProgress2;
        treeForkCount = totalChildren;
      }
      __name(pushTreeFork, "pushTreeFork");
      function pushTreeId(workInProgress2, totalChildren, index) {
        idStack[idStackIndex++] = treeContextId;
        idStack[idStackIndex++] = treeContextOverflow;
        idStack[idStackIndex++] = treeContextProvider;
        treeContextProvider = workInProgress2;
        var baseIdWithLeadingBit = treeContextId;
        workInProgress2 = treeContextOverflow;
        var baseLength = 32 - clz32(baseIdWithLeadingBit) - 1;
        baseIdWithLeadingBit &= ~(1 << baseLength);
        index += 1;
        var length = 32 - clz32(totalChildren) + baseLength;
        if (30 < length) {
          var numberOfOverflowBits = baseLength - baseLength % 5;
          length = (baseIdWithLeadingBit & (1 << numberOfOverflowBits) - 1).toString(32);
          baseIdWithLeadingBit >>= numberOfOverflowBits;
          baseLength -= numberOfOverflowBits;
          treeContextId = 1 << 32 - clz32(totalChildren) + baseLength | index << baseLength | baseIdWithLeadingBit;
          treeContextOverflow = length + workInProgress2;
        } else
          treeContextId = 1 << length | index << baseLength | baseIdWithLeadingBit, treeContextOverflow = workInProgress2;
      }
      __name(pushTreeId, "pushTreeId");
      function pushMaterializedTreeId(workInProgress2) {
        null !== workInProgress2.return && (pushTreeFork(workInProgress2, 1), pushTreeId(workInProgress2, 1, 0));
      }
      __name(pushMaterializedTreeId, "pushMaterializedTreeId");
      function popTreeContext(workInProgress2) {
        for (; workInProgress2 === treeForkProvider; )
          treeForkProvider = forkStack[--forkStackIndex], forkStack[forkStackIndex] = null, treeForkCount = forkStack[--forkStackIndex], forkStack[forkStackIndex] = null;
        for (; workInProgress2 === treeContextProvider; )
          treeContextProvider = idStack[--idStackIndex], idStack[idStackIndex] = null, treeContextOverflow = idStack[--idStackIndex], idStack[idStackIndex] = null, treeContextId = idStack[--idStackIndex], idStack[idStackIndex] = null;
      }
      __name(popTreeContext, "popTreeContext");
      function pushHostContainer(fiber, nextRootInstance) {
        push2(rootInstanceStackCursor, nextRootInstance);
        push2(contextFiberStackCursor, fiber);
        push2(contextStackCursor, null);
        fiber = getRootHostContext(nextRootInstance);
        pop(contextStackCursor);
        push2(contextStackCursor, fiber);
      }
      __name(pushHostContainer, "pushHostContainer");
      function popHostContainer() {
        pop(contextStackCursor);
        pop(contextFiberStackCursor);
        pop(rootInstanceStackCursor);
      }
      __name(popHostContainer, "popHostContainer");
      function pushHostContext(fiber) {
        null !== fiber.memoizedState && push2(hostTransitionProviderCursor, fiber);
        var context2 = contextStackCursor.current, nextContext = getChildHostContext(context2, fiber.type);
        context2 !== nextContext && (push2(contextFiberStackCursor, fiber), push2(contextStackCursor, nextContext));
      }
      __name(pushHostContext, "pushHostContext");
      function popHostContext(fiber) {
        contextFiberStackCursor.current === fiber && (pop(contextStackCursor), pop(contextFiberStackCursor));
        hostTransitionProviderCursor.current === fiber && (pop(hostTransitionProviderCursor), isPrimaryRenderer ? HostTransitionContext._currentValue = NotPendingTransition : HostTransitionContext._currentValue2 = NotPendingTransition);
      }
      __name(popHostContext, "popHostContext");
      function throwOnHydrationMismatch(fiber) {
        var error = Error(formatProdErrorMessage(418, ""));
        queueHydrationError(createCapturedValueAtFiber(error, fiber));
        throw HydrationMismatchException;
      }
      __name(throwOnHydrationMismatch, "throwOnHydrationMismatch");
      function prepareToHydrateHostInstance(fiber, hostContext) {
        if (!supportsHydration) throw Error(formatProdErrorMessage(175));
        hydrateInstance(
          fiber.stateNode,
          fiber.type,
          fiber.memoizedProps,
          hostContext,
          fiber
        ) || throwOnHydrationMismatch(fiber);
      }
      __name(prepareToHydrateHostInstance, "prepareToHydrateHostInstance");
      function popToNextHostParent(fiber) {
        for (hydrationParentFiber = fiber.return; hydrationParentFiber; )
          switch (hydrationParentFiber.tag) {
            case 5:
            case 13:
              rootOrSingletonContext = false;
              return;
            case 27:
            case 3:
              rootOrSingletonContext = true;
              return;
            default:
              hydrationParentFiber = hydrationParentFiber.return;
          }
      }
      __name(popToNextHostParent, "popToNextHostParent");
      function popHydrationState(fiber) {
        if (!supportsHydration || fiber !== hydrationParentFiber) return false;
        if (!isHydrating) return popToNextHostParent(fiber), isHydrating = true, false;
        var tag2 = fiber.tag;
        supportsSingletons ? 3 !== tag2 && 27 !== tag2 && (5 !== tag2 || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps)) && nextHydratableInstance && throwOnHydrationMismatch(fiber) : 3 !== tag2 && (5 !== tag2 || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps)) && nextHydratableInstance && throwOnHydrationMismatch(fiber);
        popToNextHostParent(fiber);
        if (13 === tag2) {
          if (!supportsHydration) throw Error(formatProdErrorMessage(316));
          fiber = fiber.memoizedState;
          fiber = null !== fiber ? fiber.dehydrated : null;
          if (!fiber) throw Error(formatProdErrorMessage(317));
          nextHydratableInstance = getNextHydratableInstanceAfterSuspenseInstance(fiber);
        } else
          nextHydratableInstance = supportsSingletons && 27 === tag2 ? getNextHydratableSiblingAfterSingleton(
            fiber.type,
            nextHydratableInstance
          ) : hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
        return true;
      }
      __name(popHydrationState, "popHydrationState");
      function resetHydrationState() {
        supportsHydration && (nextHydratableInstance = hydrationParentFiber = null, isHydrating = false);
      }
      __name(resetHydrationState, "resetHydrationState");
      function upgradeHydrationErrorsToRecoverable() {
        var queuedErrors = hydrationErrors;
        null !== queuedErrors && (null === workInProgressRootRecoverableErrors ? workInProgressRootRecoverableErrors = queuedErrors : workInProgressRootRecoverableErrors.push.apply(
          workInProgressRootRecoverableErrors,
          queuedErrors
        ), hydrationErrors = null);
        return queuedErrors;
      }
      __name(upgradeHydrationErrorsToRecoverable, "upgradeHydrationErrorsToRecoverable");
      function queueHydrationError(error) {
        null === hydrationErrors ? hydrationErrors = [error] : hydrationErrors.push(error);
      }
      __name(queueHydrationError, "queueHydrationError");
      function is(x, y) {
        return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y;
      }
      __name(is, "is");
      function pushProvider(providerFiber, context2, nextValue) {
        isPrimaryRenderer ? (push2(valueCursor, context2._currentValue), context2._currentValue = nextValue) : (push2(valueCursor, context2._currentValue2), context2._currentValue2 = nextValue);
      }
      __name(pushProvider, "pushProvider");
      function popProvider(context2) {
        var currentValue = valueCursor.current;
        isPrimaryRenderer ? context2._currentValue = currentValue : context2._currentValue2 = currentValue;
        pop(valueCursor);
      }
      __name(popProvider, "popProvider");
      function scheduleContextWorkOnParentPath(parent, renderLanes2, propagationRoot) {
        for (; null !== parent; ) {
          var alternate = parent.alternate;
          (parent.childLanes & renderLanes2) !== renderLanes2 ? (parent.childLanes |= renderLanes2, null !== alternate && (alternate.childLanes |= renderLanes2)) : null !== alternate && (alternate.childLanes & renderLanes2) !== renderLanes2 && (alternate.childLanes |= renderLanes2);
          if (parent === propagationRoot) break;
          parent = parent.return;
        }
      }
      __name(scheduleContextWorkOnParentPath, "scheduleContextWorkOnParentPath");
      function propagateContextChanges(workInProgress2, contexts, renderLanes2, forcePropagateEntireTree) {
        var fiber = workInProgress2.child;
        null !== fiber && (fiber.return = workInProgress2);
        for (; null !== fiber; ) {
          var list3 = fiber.dependencies;
          if (null !== list3) {
            var nextFiber = fiber.child;
            list3 = list3.firstContext;
            a: for (; null !== list3; ) {
              var dependency = list3;
              list3 = fiber;
              for (var i = 0; i < contexts.length; i++)
                if (dependency.context === contexts[i]) {
                  list3.lanes |= renderLanes2;
                  dependency = list3.alternate;
                  null !== dependency && (dependency.lanes |= renderLanes2);
                  scheduleContextWorkOnParentPath(
                    list3.return,
                    renderLanes2,
                    workInProgress2
                  );
                  forcePropagateEntireTree || (nextFiber = null);
                  break a;
                }
              list3 = dependency.next;
            }
          } else if (18 === fiber.tag) {
            nextFiber = fiber.return;
            if (null === nextFiber) throw Error(formatProdErrorMessage(341));
            nextFiber.lanes |= renderLanes2;
            list3 = nextFiber.alternate;
            null !== list3 && (list3.lanes |= renderLanes2);
            scheduleContextWorkOnParentPath(nextFiber, renderLanes2, workInProgress2);
            nextFiber = null;
          } else nextFiber = fiber.child;
          if (null !== nextFiber) nextFiber.return = fiber;
          else
            for (nextFiber = fiber; null !== nextFiber; ) {
              if (nextFiber === workInProgress2) {
                nextFiber = null;
                break;
              }
              fiber = nextFiber.sibling;
              if (null !== fiber) {
                fiber.return = nextFiber.return;
                nextFiber = fiber;
                break;
              }
              nextFiber = nextFiber.return;
            }
          fiber = nextFiber;
        }
      }
      __name(propagateContextChanges, "propagateContextChanges");
      function propagateParentContextChanges(current, workInProgress2, renderLanes2, forcePropagateEntireTree) {
        current = null;
        for (var parent = workInProgress2, isInsidePropagationBailout = false; null !== parent; ) {
          if (!isInsidePropagationBailout) {
            if (0 !== (parent.flags & 524288)) isInsidePropagationBailout = true;
            else if (0 !== (parent.flags & 262144)) break;
          }
          if (10 === parent.tag) {
            var currentParent = parent.alternate;
            if (null === currentParent) throw Error(formatProdErrorMessage(387));
            currentParent = currentParent.memoizedProps;
            if (null !== currentParent) {
              var context2 = parent.type;
              objectIs(parent.pendingProps.value, currentParent.value) || (null !== current ? current.push(context2) : current = [context2]);
            }
          } else if (parent === hostTransitionProviderCursor.current) {
            currentParent = parent.alternate;
            if (null === currentParent) throw Error(formatProdErrorMessage(387));
            currentParent.memoizedState.memoizedState !== parent.memoizedState.memoizedState && (null !== current ? current.push(HostTransitionContext) : current = [HostTransitionContext]);
          }
          parent = parent.return;
        }
        null !== current && propagateContextChanges(
          workInProgress2,
          current,
          renderLanes2,
          forcePropagateEntireTree
        );
        workInProgress2.flags |= 262144;
      }
      __name(propagateParentContextChanges, "propagateParentContextChanges");
      function checkIfContextChanged(currentDependencies) {
        for (currentDependencies = currentDependencies.firstContext; null !== currentDependencies; ) {
          var context2 = currentDependencies.context;
          if (!objectIs(
            isPrimaryRenderer ? context2._currentValue : context2._currentValue2,
            currentDependencies.memoizedValue
          ))
            return true;
          currentDependencies = currentDependencies.next;
        }
        return false;
      }
      __name(checkIfContextChanged, "checkIfContextChanged");
      function prepareToReadContext(workInProgress2) {
        currentlyRenderingFiber$1 = workInProgress2;
        lastContextDependency = null;
        workInProgress2 = workInProgress2.dependencies;
        null !== workInProgress2 && (workInProgress2.firstContext = null);
      }
      __name(prepareToReadContext, "prepareToReadContext");
      function readContext(context2) {
        return readContextForConsumer(currentlyRenderingFiber$1, context2);
      }
      __name(readContext, "readContext");
      function readContextDuringReconciliation(consumer, context2) {
        null === currentlyRenderingFiber$1 && prepareToReadContext(consumer);
        return readContextForConsumer(consumer, context2);
      }
      __name(readContextDuringReconciliation, "readContextDuringReconciliation");
      function readContextForConsumer(consumer, context2) {
        var value = isPrimaryRenderer ? context2._currentValue : context2._currentValue2;
        context2 = { context: context2, memoizedValue: value, next: null };
        if (null === lastContextDependency) {
          if (null === consumer) throw Error(formatProdErrorMessage(308));
          lastContextDependency = context2;
          consumer.dependencies = { lanes: 0, firstContext: context2 };
          consumer.flags |= 524288;
        } else lastContextDependency = lastContextDependency.next = context2;
        return value;
      }
      __name(readContextForConsumer, "readContextForConsumer");
      function createCache() {
        return {
          controller: new AbortControllerLocal(),
          data: /* @__PURE__ */ new Map(),
          refCount: 0
        };
      }
      __name(createCache, "createCache");
      function releaseCache(cache5) {
        cache5.refCount--;
        0 === cache5.refCount && scheduleCallback$2(NormalPriority, function() {
          cache5.controller.abort();
        });
      }
      __name(releaseCache, "releaseCache");
      function ensureRootIsScheduled(root) {
        root !== lastScheduledRoot && null === root.next && (null === lastScheduledRoot ? firstScheduledRoot = lastScheduledRoot = root : lastScheduledRoot = lastScheduledRoot.next = root);
        mightHavePendingSyncWork = true;
        didScheduleMicrotask || (didScheduleMicrotask = true, scheduleImmediateRootScheduleTask());
      }
      __name(ensureRootIsScheduled, "ensureRootIsScheduled");
      function flushSyncWorkAcrossRoots_impl(syncTransitionLanes, onlyLegacy) {
        if (!isFlushingWork && mightHavePendingSyncWork) {
          isFlushingWork = true;
          do {
            var didPerformSomeWork = false;
            for (var root = firstScheduledRoot; null !== root; ) {
              if (!onlyLegacy)
                if (0 !== syncTransitionLanes) {
                  var pendingLanes = root.pendingLanes;
                  if (0 === pendingLanes) var JSCompiler_inline_result = 0;
                  else {
                    var suspendedLanes = root.suspendedLanes, pingedLanes = root.pingedLanes;
                    JSCompiler_inline_result = (1 << 31 - clz32(42 | syncTransitionLanes) + 1) - 1;
                    JSCompiler_inline_result &= pendingLanes & ~(suspendedLanes & ~pingedLanes);
                    JSCompiler_inline_result = JSCompiler_inline_result & 201326741 ? JSCompiler_inline_result & 201326741 | 1 : JSCompiler_inline_result ? JSCompiler_inline_result | 2 : 0;
                  }
                  0 !== JSCompiler_inline_result && (didPerformSomeWork = true, performSyncWorkOnRoot(root, JSCompiler_inline_result));
                } else
                  JSCompiler_inline_result = workInProgressRootRenderLanes, JSCompiler_inline_result = getNextLanes(
                    root,
                    root === workInProgressRoot ? JSCompiler_inline_result : 0,
                    null !== root.cancelPendingCommit || root.timeoutHandle !== noTimeout
                  ), 0 === (JSCompiler_inline_result & 3) || checkIfRootIsPrerendering(root, JSCompiler_inline_result) || (didPerformSomeWork = true, performSyncWorkOnRoot(root, JSCompiler_inline_result));
              root = root.next;
            }
          } while (didPerformSomeWork);
          isFlushingWork = false;
        }
      }
      __name(flushSyncWorkAcrossRoots_impl, "flushSyncWorkAcrossRoots_impl");
      function processRootScheduleInImmediateTask() {
        processRootScheduleInMicrotask();
      }
      __name(processRootScheduleInImmediateTask, "processRootScheduleInImmediateTask");
      function processRootScheduleInMicrotask() {
        mightHavePendingSyncWork = didScheduleMicrotask = false;
        var syncTransitionLanes = 0;
        0 !== currentEventTransitionLane && (shouldAttemptEagerTransition() && (syncTransitionLanes = currentEventTransitionLane), currentEventTransitionLane = 0);
        for (var currentTime = now(), prev = null, root = firstScheduledRoot; null !== root; ) {
          var next = root.next, nextLanes = scheduleTaskForRootDuringMicrotask(root, currentTime);
          if (0 === nextLanes)
            root.next = null, null === prev ? firstScheduledRoot = next : prev.next = next, null === next && (lastScheduledRoot = prev);
          else if (prev = root, 0 !== syncTransitionLanes || 0 !== (nextLanes & 3))
            mightHavePendingSyncWork = true;
          root = next;
        }
        flushSyncWorkAcrossRoots_impl(syncTransitionLanes, false);
      }
      __name(processRootScheduleInMicrotask, "processRootScheduleInMicrotask");
      function scheduleTaskForRootDuringMicrotask(root, currentTime) {
        for (var suspendedLanes = root.suspendedLanes, pingedLanes = root.pingedLanes, expirationTimes = root.expirationTimes, lanes = root.pendingLanes & -62914561; 0 < lanes; ) {
          var index$3 = 31 - clz32(lanes), lane = 1 << index$3, expirationTime = expirationTimes[index$3];
          if (-1 === expirationTime) {
            if (0 === (lane & suspendedLanes) || 0 !== (lane & pingedLanes))
              expirationTimes[index$3] = computeExpirationTime(lane, currentTime);
          } else expirationTime <= currentTime && (root.expiredLanes |= lane);
          lanes &= ~lane;
        }
        currentTime = workInProgressRoot;
        suspendedLanes = workInProgressRootRenderLanes;
        suspendedLanes = getNextLanes(
          root,
          root === currentTime ? suspendedLanes : 0,
          null !== root.cancelPendingCommit || root.timeoutHandle !== noTimeout
        );
        pingedLanes = root.callbackNode;
        if (0 === suspendedLanes || root === currentTime && (2 === workInProgressSuspendedReason || 9 === workInProgressSuspendedReason) || null !== root.cancelPendingCommit)
          return null !== pingedLanes && null !== pingedLanes && cancelCallback$1(pingedLanes), root.callbackNode = null, root.callbackPriority = 0;
        if (0 === (suspendedLanes & 3) || checkIfRootIsPrerendering(root, suspendedLanes)) {
          currentTime = suspendedLanes & -suspendedLanes;
          if (currentTime === root.callbackPriority) return currentTime;
          null !== pingedLanes && cancelCallback$1(pingedLanes);
          switch (lanesToEventPriority(suspendedLanes)) {
            case 2:
            case 8:
              suspendedLanes = UserBlockingPriority;
              break;
            case 32:
              suspendedLanes = NormalPriority$1;
              break;
            case 268435456:
              suspendedLanes = IdlePriority;
              break;
            default:
              suspendedLanes = NormalPriority$1;
          }
          pingedLanes = performWorkOnRootViaSchedulerTask.bind(null, root);
          suspendedLanes = scheduleCallback$3(suspendedLanes, pingedLanes);
          root.callbackPriority = currentTime;
          root.callbackNode = suspendedLanes;
          return currentTime;
        }
        null !== pingedLanes && null !== pingedLanes && cancelCallback$1(pingedLanes);
        root.callbackPriority = 2;
        root.callbackNode = null;
        return 2;
      }
      __name(scheduleTaskForRootDuringMicrotask, "scheduleTaskForRootDuringMicrotask");
      function performWorkOnRootViaSchedulerTask(root, didTimeout) {
        if (0 !== pendingEffectsStatus && 5 !== pendingEffectsStatus)
          return root.callbackNode = null, root.callbackPriority = 0, null;
        var originalCallbackNode = root.callbackNode;
        if (flushPendingEffects(true) && root.callbackNode !== originalCallbackNode)
          return null;
        var workInProgressRootRenderLanes$jscomp$0 = workInProgressRootRenderLanes;
        workInProgressRootRenderLanes$jscomp$0 = getNextLanes(
          root,
          root === workInProgressRoot ? workInProgressRootRenderLanes$jscomp$0 : 0,
          null !== root.cancelPendingCommit || root.timeoutHandle !== noTimeout
        );
        if (0 === workInProgressRootRenderLanes$jscomp$0) return null;
        performWorkOnRoot(root, workInProgressRootRenderLanes$jscomp$0, didTimeout);
        scheduleTaskForRootDuringMicrotask(root, now());
        return null != root.callbackNode && root.callbackNode === originalCallbackNode ? performWorkOnRootViaSchedulerTask.bind(null, root) : null;
      }
      __name(performWorkOnRootViaSchedulerTask, "performWorkOnRootViaSchedulerTask");
      function performSyncWorkOnRoot(root, lanes) {
        if (flushPendingEffects()) return null;
        performWorkOnRoot(root, lanes, true);
      }
      __name(performSyncWorkOnRoot, "performSyncWorkOnRoot");
      function scheduleImmediateRootScheduleTask() {
        supportsMicrotasks ? scheduleMicrotask(function() {
          0 !== (executionContext & 6) ? scheduleCallback$3(
            ImmediatePriority,
            processRootScheduleInImmediateTask
          ) : processRootScheduleInMicrotask();
        }) : scheduleCallback$3(
          ImmediatePriority,
          processRootScheduleInImmediateTask
        );
      }
      __name(scheduleImmediateRootScheduleTask, "scheduleImmediateRootScheduleTask");
      function requestTransitionLane() {
        0 === currentEventTransitionLane && (currentEventTransitionLane = claimNextTransitionLane());
        return currentEventTransitionLane;
      }
      __name(requestTransitionLane, "requestTransitionLane");
      function entangleAsyncAction(transition, thenable) {
        if (null === currentEntangledListeners) {
          var entangledListeners = currentEntangledListeners = [];
          currentEntangledPendingCount = 0;
          currentEntangledLane = requestTransitionLane();
          currentEntangledActionThenable = {
            status: "pending",
            value: void 0,
            then: /* @__PURE__ */ __name(function(resolve24) {
              entangledListeners.push(resolve24);
            }, "then")
          };
        }
        currentEntangledPendingCount++;
        thenable.then(pingEngtangledActionScope, pingEngtangledActionScope);
        return thenable;
      }
      __name(entangleAsyncAction, "entangleAsyncAction");
      function pingEngtangledActionScope() {
        if (0 === --currentEntangledPendingCount && null !== currentEntangledListeners) {
          null !== currentEntangledActionThenable && (currentEntangledActionThenable.status = "fulfilled");
          var listeners = currentEntangledListeners;
          currentEntangledListeners = null;
          currentEntangledLane = 0;
          currentEntangledActionThenable = null;
          for (var i = 0; i < listeners.length; i++) (0, listeners[i])();
        }
      }
      __name(pingEngtangledActionScope, "pingEngtangledActionScope");
      function chainThenableValue(thenable, result) {
        var listeners = [], thenableWithOverride = {
          status: "pending",
          value: null,
          reason: null,
          then: /* @__PURE__ */ __name(function(resolve24) {
            listeners.push(resolve24);
          }, "then")
        };
        thenable.then(
          function() {
            thenableWithOverride.status = "fulfilled";
            thenableWithOverride.value = result;
            for (var i = 0; i < listeners.length; i++) (0, listeners[i])(result);
          },
          function(error) {
            thenableWithOverride.status = "rejected";
            thenableWithOverride.reason = error;
            for (error = 0; error < listeners.length; error++)
              (0, listeners[error])(void 0);
          }
        );
        return thenableWithOverride;
      }
      __name(chainThenableValue, "chainThenableValue");
      function peekCacheFromPool() {
        var cacheResumedFromPreviousRender = resumedCache.current;
        return null !== cacheResumedFromPreviousRender ? cacheResumedFromPreviousRender : workInProgressRoot.pooledCache;
      }
      __name(peekCacheFromPool, "peekCacheFromPool");
      function pushTransition(offscreenWorkInProgress, prevCachePool) {
        null === prevCachePool ? push2(resumedCache, resumedCache.current) : push2(resumedCache, prevCachePool.pool);
      }
      __name(pushTransition, "pushTransition");
      function getSuspendedCache() {
        var cacheFromPool = peekCacheFromPool();
        return null === cacheFromPool ? null : {
          parent: isPrimaryRenderer ? CacheContext._currentValue : CacheContext._currentValue2,
          pool: cacheFromPool
        };
      }
      __name(getSuspendedCache, "getSuspendedCache");
      function shallowEqual(objA, objB) {
        if (objectIs(objA, objB)) return true;
        if ("object" !== typeof objA || null === objA || "object" !== typeof objB || null === objB)
          return false;
        var keysA = Object.keys(objA), keysB = Object.keys(objB);
        if (keysA.length !== keysB.length) return false;
        for (keysB = 0; keysB < keysA.length; keysB++) {
          var currentKey = keysA[keysB];
          if (!hasOwnProperty2.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey]))
            return false;
        }
        return true;
      }
      __name(shallowEqual, "shallowEqual");
      function isThenableResolved(thenable) {
        thenable = thenable.status;
        return "fulfilled" === thenable || "rejected" === thenable;
      }
      __name(isThenableResolved, "isThenableResolved");
      function noop$1() {
      }
      __name(noop$1, "noop$1");
      function trackUsedThenable(thenableState2, thenable, index) {
        index = thenableState2[index];
        void 0 === index ? thenableState2.push(thenable) : index !== thenable && (thenable.then(noop$1, noop$1), thenable = index);
        switch (thenable.status) {
          case "fulfilled":
            return thenable.value;
          case "rejected":
            throw thenableState2 = thenable.reason, checkIfUseWrappedInAsyncCatch(thenableState2), thenableState2;
          default:
            if ("string" === typeof thenable.status) thenable.then(noop$1, noop$1);
            else {
              thenableState2 = workInProgressRoot;
              if (null !== thenableState2 && 100 < thenableState2.shellSuspendCounter)
                throw Error(formatProdErrorMessage(482));
              thenableState2 = thenable;
              thenableState2.status = "pending";
              thenableState2.then(
                function(fulfilledValue) {
                  if ("pending" === thenable.status) {
                    var fulfilledThenable = thenable;
                    fulfilledThenable.status = "fulfilled";
                    fulfilledThenable.value = fulfilledValue;
                  }
                },
                function(error) {
                  if ("pending" === thenable.status) {
                    var rejectedThenable = thenable;
                    rejectedThenable.status = "rejected";
                    rejectedThenable.reason = error;
                  }
                }
              );
            }
            switch (thenable.status) {
              case "fulfilled":
                return thenable.value;
              case "rejected":
                throw thenableState2 = thenable.reason, checkIfUseWrappedInAsyncCatch(thenableState2), thenableState2;
            }
            suspendedThenable = thenable;
            throw SuspenseException;
        }
      }
      __name(trackUsedThenable, "trackUsedThenable");
      function getSuspendedThenable() {
        if (null === suspendedThenable) throw Error(formatProdErrorMessage(459));
        var thenable = suspendedThenable;
        suspendedThenable = null;
        return thenable;
      }
      __name(getSuspendedThenable, "getSuspendedThenable");
      function checkIfUseWrappedInAsyncCatch(rejectedReason) {
        if (rejectedReason === SuspenseException || rejectedReason === SuspenseActionException)
          throw Error(formatProdErrorMessage(483));
      }
      __name(checkIfUseWrappedInAsyncCatch, "checkIfUseWrappedInAsyncCatch");
      function finishQueueingConcurrentUpdates() {
        for (var endIndex = concurrentQueuesIndex, i = concurrentlyUpdatedLanes = concurrentQueuesIndex = 0; i < endIndex; ) {
          var fiber = concurrentQueues[i];
          concurrentQueues[i++] = null;
          var queue = concurrentQueues[i];
          concurrentQueues[i++] = null;
          var update2 = concurrentQueues[i];
          concurrentQueues[i++] = null;
          var lane = concurrentQueues[i];
          concurrentQueues[i++] = null;
          if (null !== queue && null !== update2) {
            var pending = queue.pending;
            null === pending ? update2.next = update2 : (update2.next = pending.next, pending.next = update2);
            queue.pending = update2;
          }
          0 !== lane && markUpdateLaneFromFiberToRoot(fiber, update2, lane);
        }
      }
      __name(finishQueueingConcurrentUpdates, "finishQueueingConcurrentUpdates");
      function enqueueUpdate$1(fiber, queue, update2, lane) {
        concurrentQueues[concurrentQueuesIndex++] = fiber;
        concurrentQueues[concurrentQueuesIndex++] = queue;
        concurrentQueues[concurrentQueuesIndex++] = update2;
        concurrentQueues[concurrentQueuesIndex++] = lane;
        concurrentlyUpdatedLanes |= lane;
        fiber.lanes |= lane;
        fiber = fiber.alternate;
        null !== fiber && (fiber.lanes |= lane);
      }
      __name(enqueueUpdate$1, "enqueueUpdate$1");
      function enqueueConcurrentHookUpdate(fiber, queue, update2, lane) {
        enqueueUpdate$1(fiber, queue, update2, lane);
        return getRootForUpdatedFiber(fiber);
      }
      __name(enqueueConcurrentHookUpdate, "enqueueConcurrentHookUpdate");
      function enqueueConcurrentRenderForLane(fiber, lane) {
        enqueueUpdate$1(fiber, null, null, lane);
        return getRootForUpdatedFiber(fiber);
      }
      __name(enqueueConcurrentRenderForLane, "enqueueConcurrentRenderForLane");
      function markUpdateLaneFromFiberToRoot(sourceFiber, update2, lane) {
        sourceFiber.lanes |= lane;
        var alternate = sourceFiber.alternate;
        null !== alternate && (alternate.lanes |= lane);
        for (var isHidden2 = false, parent = sourceFiber.return; null !== parent; )
          parent.childLanes |= lane, alternate = parent.alternate, null !== alternate && (alternate.childLanes |= lane), 22 === parent.tag && (sourceFiber = parent.stateNode, null === sourceFiber || sourceFiber._visibility & 1 || (isHidden2 = true)), sourceFiber = parent, parent = parent.return;
        return 3 === sourceFiber.tag ? (parent = sourceFiber.stateNode, isHidden2 && null !== update2 && (isHidden2 = 31 - clz32(lane), sourceFiber = parent.hiddenUpdates, alternate = sourceFiber[isHidden2], null === alternate ? sourceFiber[isHidden2] = [update2] : alternate.push(update2), update2.lane = lane | 536870912), parent) : null;
      }
      __name(markUpdateLaneFromFiberToRoot, "markUpdateLaneFromFiberToRoot");
      function getRootForUpdatedFiber(sourceFiber) {
        if (50 < nestedUpdateCount)
          throw nestedUpdateCount = 0, rootWithNestedUpdates = null, Error(formatProdErrorMessage(185));
        for (var parent = sourceFiber.return; null !== parent; )
          sourceFiber = parent, parent = sourceFiber.return;
        return 3 === sourceFiber.tag ? sourceFiber.stateNode : null;
      }
      __name(getRootForUpdatedFiber, "getRootForUpdatedFiber");
      function initializeUpdateQueue(fiber) {
        fiber.updateQueue = {
          baseState: fiber.memoizedState,
          firstBaseUpdate: null,
          lastBaseUpdate: null,
          shared: { pending: null, lanes: 0, hiddenCallbacks: null },
          callbacks: null
        };
      }
      __name(initializeUpdateQueue, "initializeUpdateQueue");
      function cloneUpdateQueue(current, workInProgress2) {
        current = current.updateQueue;
        workInProgress2.updateQueue === current && (workInProgress2.updateQueue = {
          baseState: current.baseState,
          firstBaseUpdate: current.firstBaseUpdate,
          lastBaseUpdate: current.lastBaseUpdate,
          shared: current.shared,
          callbacks: null
        });
      }
      __name(cloneUpdateQueue, "cloneUpdateQueue");
      function createUpdate(lane) {
        return { lane, tag: 0, payload: null, callback: null, next: null };
      }
      __name(createUpdate, "createUpdate");
      function enqueueUpdate(fiber, update2, lane) {
        var updateQueue = fiber.updateQueue;
        if (null === updateQueue) return null;
        updateQueue = updateQueue.shared;
        if (0 !== (executionContext & 2)) {
          var pending = updateQueue.pending;
          null === pending ? update2.next = update2 : (update2.next = pending.next, pending.next = update2);
          updateQueue.pending = update2;
          update2 = getRootForUpdatedFiber(fiber);
          markUpdateLaneFromFiberToRoot(fiber, null, lane);
          return update2;
        }
        enqueueUpdate$1(fiber, updateQueue, update2, lane);
        return getRootForUpdatedFiber(fiber);
      }
      __name(enqueueUpdate, "enqueueUpdate");
      function entangleTransitions(root, fiber, lane) {
        fiber = fiber.updateQueue;
        if (null !== fiber && (fiber = fiber.shared, 0 !== (lane & 4194048))) {
          var queueLanes = fiber.lanes;
          queueLanes &= root.pendingLanes;
          lane |= queueLanes;
          fiber.lanes = lane;
          markRootEntangled(root, lane);
        }
      }
      __name(entangleTransitions, "entangleTransitions");
      function enqueueCapturedUpdate(workInProgress2, capturedUpdate) {
        var queue = workInProgress2.updateQueue, current = workInProgress2.alternate;
        if (null !== current && (current = current.updateQueue, queue === current)) {
          var newFirst = null, newLast = null;
          queue = queue.firstBaseUpdate;
          if (null !== queue) {
            do {
              var clone = {
                lane: queue.lane,
                tag: queue.tag,
                payload: queue.payload,
                callback: null,
                next: null
              };
              null === newLast ? newFirst = newLast = clone : newLast = newLast.next = clone;
              queue = queue.next;
            } while (null !== queue);
            null === newLast ? newFirst = newLast = capturedUpdate : newLast = newLast.next = capturedUpdate;
          } else newFirst = newLast = capturedUpdate;
          queue = {
            baseState: current.baseState,
            firstBaseUpdate: newFirst,
            lastBaseUpdate: newLast,
            shared: current.shared,
            callbacks: current.callbacks
          };
          workInProgress2.updateQueue = queue;
          return;
        }
        workInProgress2 = queue.lastBaseUpdate;
        null === workInProgress2 ? queue.firstBaseUpdate = capturedUpdate : workInProgress2.next = capturedUpdate;
        queue.lastBaseUpdate = capturedUpdate;
      }
      __name(enqueueCapturedUpdate, "enqueueCapturedUpdate");
      function suspendIfUpdateReadFromEntangledAsyncAction() {
        if (didReadFromEntangledAsyncAction) {
          var entangledActionThenable = currentEntangledActionThenable;
          if (null !== entangledActionThenable) throw entangledActionThenable;
        }
      }
      __name(suspendIfUpdateReadFromEntangledAsyncAction, "suspendIfUpdateReadFromEntangledAsyncAction");
      function processUpdateQueue(workInProgress$jscomp$0, props, instance$jscomp$0, renderLanes2) {
        didReadFromEntangledAsyncAction = false;
        var queue = workInProgress$jscomp$0.updateQueue;
        hasForceUpdate = false;
        var firstBaseUpdate = queue.firstBaseUpdate, lastBaseUpdate = queue.lastBaseUpdate, pendingQueue = queue.shared.pending;
        if (null !== pendingQueue) {
          queue.shared.pending = null;
          var lastPendingUpdate = pendingQueue, firstPendingUpdate = lastPendingUpdate.next;
          lastPendingUpdate.next = null;
          null === lastBaseUpdate ? firstBaseUpdate = firstPendingUpdate : lastBaseUpdate.next = firstPendingUpdate;
          lastBaseUpdate = lastPendingUpdate;
          var current = workInProgress$jscomp$0.alternate;
          null !== current && (current = current.updateQueue, pendingQueue = current.lastBaseUpdate, pendingQueue !== lastBaseUpdate && (null === pendingQueue ? current.firstBaseUpdate = firstPendingUpdate : pendingQueue.next = firstPendingUpdate, current.lastBaseUpdate = lastPendingUpdate));
        }
        if (null !== firstBaseUpdate) {
          var newState = queue.baseState;
          lastBaseUpdate = 0;
          current = firstPendingUpdate = lastPendingUpdate = null;
          pendingQueue = firstBaseUpdate;
          do {
            var updateLane = pendingQueue.lane & -536870913, isHiddenUpdate = updateLane !== pendingQueue.lane;
            if (isHiddenUpdate ? (workInProgressRootRenderLanes & updateLane) === updateLane : (renderLanes2 & updateLane) === updateLane) {
              0 !== updateLane && updateLane === currentEntangledLane && (didReadFromEntangledAsyncAction = true);
              null !== current && (current = current.next = {
                lane: 0,
                tag: pendingQueue.tag,
                payload: pendingQueue.payload,
                callback: null,
                next: null
              });
              a: {
                var workInProgress2 = workInProgress$jscomp$0, update2 = pendingQueue;
                updateLane = props;
                var instance = instance$jscomp$0;
                switch (update2.tag) {
                  case 1:
                    workInProgress2 = update2.payload;
                    if ("function" === typeof workInProgress2) {
                      newState = workInProgress2.call(
                        instance,
                        newState,
                        updateLane
                      );
                      break a;
                    }
                    newState = workInProgress2;
                    break a;
                  case 3:
                    workInProgress2.flags = workInProgress2.flags & -65537 | 128;
                  case 0:
                    workInProgress2 = update2.payload;
                    updateLane = "function" === typeof workInProgress2 ? workInProgress2.call(instance, newState, updateLane) : workInProgress2;
                    if (null === updateLane || void 0 === updateLane) break a;
                    newState = assign({}, newState, updateLane);
                    break a;
                  case 2:
                    hasForceUpdate = true;
                }
              }
              updateLane = pendingQueue.callback;
              null !== updateLane && (workInProgress$jscomp$0.flags |= 64, isHiddenUpdate && (workInProgress$jscomp$0.flags |= 8192), isHiddenUpdate = queue.callbacks, null === isHiddenUpdate ? queue.callbacks = [updateLane] : isHiddenUpdate.push(updateLane));
            } else
              isHiddenUpdate = {
                lane: updateLane,
                tag: pendingQueue.tag,
                payload: pendingQueue.payload,
                callback: pendingQueue.callback,
                next: null
              }, null === current ? (firstPendingUpdate = current = isHiddenUpdate, lastPendingUpdate = newState) : current = current.next = isHiddenUpdate, lastBaseUpdate |= updateLane;
            pendingQueue = pendingQueue.next;
            if (null === pendingQueue)
              if (pendingQueue = queue.shared.pending, null === pendingQueue)
                break;
              else
                isHiddenUpdate = pendingQueue, pendingQueue = isHiddenUpdate.next, isHiddenUpdate.next = null, queue.lastBaseUpdate = isHiddenUpdate, queue.shared.pending = null;
          } while (1);
          null === current && (lastPendingUpdate = newState);
          queue.baseState = lastPendingUpdate;
          queue.firstBaseUpdate = firstPendingUpdate;
          queue.lastBaseUpdate = current;
          null === firstBaseUpdate && (queue.shared.lanes = 0);
          workInProgressRootSkippedLanes |= lastBaseUpdate;
          workInProgress$jscomp$0.lanes = lastBaseUpdate;
          workInProgress$jscomp$0.memoizedState = newState;
        }
      }
      __name(processUpdateQueue, "processUpdateQueue");
      function callCallback(callback, context2) {
        if ("function" !== typeof callback)
          throw Error(formatProdErrorMessage(191, callback));
        callback.call(context2);
      }
      __name(callCallback, "callCallback");
      function commitCallbacks(updateQueue, context2) {
        var callbacks = updateQueue.callbacks;
        if (null !== callbacks)
          for (updateQueue.callbacks = null, updateQueue = 0; updateQueue < callbacks.length; updateQueue++)
            callCallback(callbacks[updateQueue], context2);
      }
      __name(commitCallbacks, "commitCallbacks");
      function pushHiddenContext(fiber, context2) {
        fiber = entangledRenderLanes;
        push2(prevEntangledRenderLanesCursor, fiber);
        push2(currentTreeHiddenStackCursor, context2);
        entangledRenderLanes = fiber | context2.baseLanes;
      }
      __name(pushHiddenContext, "pushHiddenContext");
      function reuseHiddenContextOnStack() {
        push2(prevEntangledRenderLanesCursor, entangledRenderLanes);
        push2(currentTreeHiddenStackCursor, currentTreeHiddenStackCursor.current);
      }
      __name(reuseHiddenContextOnStack, "reuseHiddenContextOnStack");
      function popHiddenContext() {
        entangledRenderLanes = prevEntangledRenderLanesCursor.current;
        pop(currentTreeHiddenStackCursor);
        pop(prevEntangledRenderLanesCursor);
      }
      __name(popHiddenContext, "popHiddenContext");
      function throwInvalidHookError() {
        throw Error(formatProdErrorMessage(321));
      }
      __name(throwInvalidHookError, "throwInvalidHookError");
      function areHookInputsEqual(nextDeps, prevDeps) {
        if (null === prevDeps) return false;
        for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++)
          if (!objectIs(nextDeps[i], prevDeps[i])) return false;
        return true;
      }
      __name(areHookInputsEqual, "areHookInputsEqual");
      function renderWithHooks(current, workInProgress2, Component, props, secondArg, nextRenderLanes) {
        renderLanes = nextRenderLanes;
        currentlyRenderingFiber = workInProgress2;
        workInProgress2.memoizedState = null;
        workInProgress2.updateQueue = null;
        workInProgress2.lanes = 0;
        ReactSharedInternals.H = null === current || null === current.memoizedState ? HooksDispatcherOnMount : HooksDispatcherOnUpdate;
        shouldDoubleInvokeUserFnsInHooksDEV = false;
        nextRenderLanes = Component(props, secondArg);
        shouldDoubleInvokeUserFnsInHooksDEV = false;
        didScheduleRenderPhaseUpdateDuringThisPass && (nextRenderLanes = renderWithHooksAgain(
          workInProgress2,
          Component,
          props,
          secondArg
        ));
        finishRenderingHooks(current);
        return nextRenderLanes;
      }
      __name(renderWithHooks, "renderWithHooks");
      function finishRenderingHooks(current) {
        ReactSharedInternals.H = ContextOnlyDispatcher;
        var didRenderTooFewHooks = null !== currentHook && null !== currentHook.next;
        renderLanes = 0;
        workInProgressHook = currentHook = currentlyRenderingFiber = null;
        didScheduleRenderPhaseUpdate = false;
        thenableIndexCounter$1 = 0;
        thenableState$1 = null;
        if (didRenderTooFewHooks) throw Error(formatProdErrorMessage(300));
        null === current || didReceiveUpdate || (current = current.dependencies, null !== current && checkIfContextChanged(current) && (didReceiveUpdate = true));
      }
      __name(finishRenderingHooks, "finishRenderingHooks");
      function renderWithHooksAgain(workInProgress2, Component, props, secondArg) {
        currentlyRenderingFiber = workInProgress2;
        var numberOfReRenders = 0;
        do {
          didScheduleRenderPhaseUpdateDuringThisPass && (thenableState$1 = null);
          thenableIndexCounter$1 = 0;
          didScheduleRenderPhaseUpdateDuringThisPass = false;
          if (25 <= numberOfReRenders) throw Error(formatProdErrorMessage(301));
          numberOfReRenders += 1;
          workInProgressHook = currentHook = null;
          if (null != workInProgress2.updateQueue) {
            var children = workInProgress2.updateQueue;
            children.lastEffect = null;
            children.events = null;
            children.stores = null;
            null != children.memoCache && (children.memoCache.index = 0);
          }
          ReactSharedInternals.H = HooksDispatcherOnRerender;
          children = Component(props, secondArg);
        } while (didScheduleRenderPhaseUpdateDuringThisPass);
        return children;
      }
      __name(renderWithHooksAgain, "renderWithHooksAgain");
      function TransitionAwareHostComponent() {
        var dispatcher = ReactSharedInternals.H, maybeThenable = dispatcher.useState()[0];
        maybeThenable = "function" === typeof maybeThenable.then ? useThenable(maybeThenable) : maybeThenable;
        dispatcher = dispatcher.useState()[0];
        (null !== currentHook ? currentHook.memoizedState : null) !== dispatcher && (currentlyRenderingFiber.flags |= 1024);
        return maybeThenable;
      }
      __name(TransitionAwareHostComponent, "TransitionAwareHostComponent");
      function checkDidRenderIdHook() {
        var didRenderIdHook = 0 !== localIdCounter;
        localIdCounter = 0;
        return didRenderIdHook;
      }
      __name(checkDidRenderIdHook, "checkDidRenderIdHook");
      function bailoutHooks(current, workInProgress2, lanes) {
        workInProgress2.updateQueue = current.updateQueue;
        workInProgress2.flags &= -2053;
        current.lanes &= ~lanes;
      }
      __name(bailoutHooks, "bailoutHooks");
      function resetHooksOnUnwind(workInProgress2) {
        if (didScheduleRenderPhaseUpdate) {
          for (workInProgress2 = workInProgress2.memoizedState; null !== workInProgress2; ) {
            var queue = workInProgress2.queue;
            null !== queue && (queue.pending = null);
            workInProgress2 = workInProgress2.next;
          }
          didScheduleRenderPhaseUpdate = false;
        }
        renderLanes = 0;
        workInProgressHook = currentHook = currentlyRenderingFiber = null;
        didScheduleRenderPhaseUpdateDuringThisPass = false;
        thenableIndexCounter$1 = localIdCounter = 0;
        thenableState$1 = null;
      }
      __name(resetHooksOnUnwind, "resetHooksOnUnwind");
      function mountWorkInProgressHook() {
        var hook = {
          memoizedState: null,
          baseState: null,
          baseQueue: null,
          queue: null,
          next: null
        };
        null === workInProgressHook ? currentlyRenderingFiber.memoizedState = workInProgressHook = hook : workInProgressHook = workInProgressHook.next = hook;
        return workInProgressHook;
      }
      __name(mountWorkInProgressHook, "mountWorkInProgressHook");
      function updateWorkInProgressHook() {
        if (null === currentHook) {
          var nextCurrentHook = currentlyRenderingFiber.alternate;
          nextCurrentHook = null !== nextCurrentHook ? nextCurrentHook.memoizedState : null;
        } else nextCurrentHook = currentHook.next;
        var nextWorkInProgressHook = null === workInProgressHook ? currentlyRenderingFiber.memoizedState : workInProgressHook.next;
        if (null !== nextWorkInProgressHook)
          workInProgressHook = nextWorkInProgressHook, currentHook = nextCurrentHook;
        else {
          if (null === nextCurrentHook) {
            if (null === currentlyRenderingFiber.alternate)
              throw Error(formatProdErrorMessage(467));
            throw Error(formatProdErrorMessage(310));
          }
          currentHook = nextCurrentHook;
          nextCurrentHook = {
            memoizedState: currentHook.memoizedState,
            baseState: currentHook.baseState,
            baseQueue: currentHook.baseQueue,
            queue: currentHook.queue,
            next: null
          };
          null === workInProgressHook ? currentlyRenderingFiber.memoizedState = workInProgressHook = nextCurrentHook : workInProgressHook = workInProgressHook.next = nextCurrentHook;
        }
        return workInProgressHook;
      }
      __name(updateWorkInProgressHook, "updateWorkInProgressHook");
      function createFunctionComponentUpdateQueue() {
        return { lastEffect: null, events: null, stores: null, memoCache: null };
      }
      __name(createFunctionComponentUpdateQueue, "createFunctionComponentUpdateQueue");
      function useThenable(thenable) {
        var index = thenableIndexCounter$1;
        thenableIndexCounter$1 += 1;
        null === thenableState$1 && (thenableState$1 = []);
        thenable = trackUsedThenable(thenableState$1, thenable, index);
        index = currentlyRenderingFiber;
        null === (null === workInProgressHook ? index.memoizedState : workInProgressHook.next) && (index = index.alternate, ReactSharedInternals.H = null === index || null === index.memoizedState ? HooksDispatcherOnMount : HooksDispatcherOnUpdate);
        return thenable;
      }
      __name(useThenable, "useThenable");
      function use2(usable) {
        if (null !== usable && "object" === typeof usable) {
          if ("function" === typeof usable.then) return useThenable(usable);
          if (usable.$$typeof === REACT_CONTEXT_TYPE) return readContext(usable);
        }
        throw Error(formatProdErrorMessage(438, String(usable)));
      }
      __name(use2, "use");
      function useMemoCache(size) {
        var memoCache = null, updateQueue = currentlyRenderingFiber.updateQueue;
        null !== updateQueue && (memoCache = updateQueue.memoCache);
        if (null == memoCache) {
          var current = currentlyRenderingFiber.alternate;
          null !== current && (current = current.updateQueue, null !== current && (current = current.memoCache, null != current && (memoCache = {
            data: current.data.map(function(array) {
              return array.slice();
            }),
            index: 0
          })));
        }
        null == memoCache && (memoCache = { data: [], index: 0 });
        null === updateQueue && (updateQueue = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = updateQueue);
        updateQueue.memoCache = memoCache;
        updateQueue = memoCache.data[memoCache.index];
        if (void 0 === updateQueue)
          for (updateQueue = memoCache.data[memoCache.index] = Array(size), current = 0; current < size; current++)
            updateQueue[current] = REACT_MEMO_CACHE_SENTINEL;
        memoCache.index++;
        return updateQueue;
      }
      __name(useMemoCache, "useMemoCache");
      function basicStateReducer(state, action) {
        return "function" === typeof action ? action(state) : action;
      }
      __name(basicStateReducer, "basicStateReducer");
      function updateReducer(reducer) {
        var hook = updateWorkInProgressHook();
        return updateReducerImpl(hook, currentHook, reducer);
      }
      __name(updateReducer, "updateReducer");
      function updateReducerImpl(hook, current, reducer) {
        var queue = hook.queue;
        if (null === queue) throw Error(formatProdErrorMessage(311));
        queue.lastRenderedReducer = reducer;
        var baseQueue = hook.baseQueue, pendingQueue = queue.pending;
        if (null !== pendingQueue) {
          if (null !== baseQueue) {
            var baseFirst = baseQueue.next;
            baseQueue.next = pendingQueue.next;
            pendingQueue.next = baseFirst;
          }
          current.baseQueue = baseQueue = pendingQueue;
          queue.pending = null;
        }
        pendingQueue = hook.baseState;
        if (null === baseQueue) hook.memoizedState = pendingQueue;
        else {
          current = baseQueue.next;
          var newBaseQueueFirst = baseFirst = null, newBaseQueueLast = null, update2 = current, didReadFromEntangledAsyncAction$23 = false;
          do {
            var updateLane = update2.lane & -536870913;
            if (updateLane !== update2.lane ? (workInProgressRootRenderLanes & updateLane) === updateLane : (renderLanes & updateLane) === updateLane) {
              var revertLane = update2.revertLane;
              if (0 === revertLane)
                null !== newBaseQueueLast && (newBaseQueueLast = newBaseQueueLast.next = {
                  lane: 0,
                  revertLane: 0,
                  action: update2.action,
                  hasEagerState: update2.hasEagerState,
                  eagerState: update2.eagerState,
                  next: null
                }), updateLane === currentEntangledLane && (didReadFromEntangledAsyncAction$23 = true);
              else if ((renderLanes & revertLane) === revertLane) {
                update2 = update2.next;
                revertLane === currentEntangledLane && (didReadFromEntangledAsyncAction$23 = true);
                continue;
              } else
                updateLane = {
                  lane: 0,
                  revertLane: update2.revertLane,
                  action: update2.action,
                  hasEagerState: update2.hasEagerState,
                  eagerState: update2.eagerState,
                  next: null
                }, null === newBaseQueueLast ? (newBaseQueueFirst = newBaseQueueLast = updateLane, baseFirst = pendingQueue) : newBaseQueueLast = newBaseQueueLast.next = updateLane, currentlyRenderingFiber.lanes |= revertLane, workInProgressRootSkippedLanes |= revertLane;
              updateLane = update2.action;
              shouldDoubleInvokeUserFnsInHooksDEV && reducer(pendingQueue, updateLane);
              pendingQueue = update2.hasEagerState ? update2.eagerState : reducer(pendingQueue, updateLane);
            } else
              revertLane = {
                lane: updateLane,
                revertLane: update2.revertLane,
                action: update2.action,
                hasEagerState: update2.hasEagerState,
                eagerState: update2.eagerState,
                next: null
              }, null === newBaseQueueLast ? (newBaseQueueFirst = newBaseQueueLast = revertLane, baseFirst = pendingQueue) : newBaseQueueLast = newBaseQueueLast.next = revertLane, currentlyRenderingFiber.lanes |= updateLane, workInProgressRootSkippedLanes |= updateLane;
            update2 = update2.next;
          } while (null !== update2 && update2 !== current);
          null === newBaseQueueLast ? baseFirst = pendingQueue : newBaseQueueLast.next = newBaseQueueFirst;
          if (!objectIs(pendingQueue, hook.memoizedState) && (didReceiveUpdate = true, didReadFromEntangledAsyncAction$23 && (reducer = currentEntangledActionThenable, null !== reducer)))
            throw reducer;
          hook.memoizedState = pendingQueue;
          hook.baseState = baseFirst;
          hook.baseQueue = newBaseQueueLast;
          queue.lastRenderedState = pendingQueue;
        }
        null === baseQueue && (queue.lanes = 0);
        return [hook.memoizedState, queue.dispatch];
      }
      __name(updateReducerImpl, "updateReducerImpl");
      function rerenderReducer(reducer) {
        var hook = updateWorkInProgressHook(), queue = hook.queue;
        if (null === queue) throw Error(formatProdErrorMessage(311));
        queue.lastRenderedReducer = reducer;
        var dispatch = queue.dispatch, lastRenderPhaseUpdate = queue.pending, newState = hook.memoizedState;
        if (null !== lastRenderPhaseUpdate) {
          queue.pending = null;
          var update2 = lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
          do
            newState = reducer(newState, update2.action), update2 = update2.next;
          while (update2 !== lastRenderPhaseUpdate);
          objectIs(newState, hook.memoizedState) || (didReceiveUpdate = true);
          hook.memoizedState = newState;
          null === hook.baseQueue && (hook.baseState = newState);
          queue.lastRenderedState = newState;
        }
        return [newState, dispatch];
      }
      __name(rerenderReducer, "rerenderReducer");
      function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
        var fiber = currentlyRenderingFiber, hook = updateWorkInProgressHook(), isHydrating$jscomp$0 = isHydrating;
        if (isHydrating$jscomp$0) {
          if (void 0 === getServerSnapshot)
            throw Error(formatProdErrorMessage(407));
          getServerSnapshot = getServerSnapshot();
        } else getServerSnapshot = getSnapshot();
        var snapshotChanged = !objectIs(
          (currentHook || hook).memoizedState,
          getServerSnapshot
        );
        snapshotChanged && (hook.memoizedState = getServerSnapshot, didReceiveUpdate = true);
        hook = hook.queue;
        var create3 = subscribeToStore.bind(null, fiber, hook, subscribe);
        updateEffectImpl(2048, 8, create3, [subscribe]);
        if (hook.getSnapshot !== getSnapshot || snapshotChanged || null !== workInProgressHook && workInProgressHook.memoizedState.tag & 1) {
          fiber.flags |= 2048;
          pushSimpleEffect(
            9,
            createEffectInstance(),
            updateStoreInstance.bind(
              null,
              fiber,
              hook,
              getServerSnapshot,
              getSnapshot
            ),
            null
          );
          if (null === workInProgressRoot) throw Error(formatProdErrorMessage(349));
          isHydrating$jscomp$0 || 0 !== (renderLanes & 124) || pushStoreConsistencyCheck(fiber, getSnapshot, getServerSnapshot);
        }
        return getServerSnapshot;
      }
      __name(updateSyncExternalStore, "updateSyncExternalStore");
      function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) {
        fiber.flags |= 16384;
        fiber = { getSnapshot, value: renderedSnapshot };
        getSnapshot = currentlyRenderingFiber.updateQueue;
        null === getSnapshot ? (getSnapshot = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = getSnapshot, getSnapshot.stores = [fiber]) : (renderedSnapshot = getSnapshot.stores, null === renderedSnapshot ? getSnapshot.stores = [fiber] : renderedSnapshot.push(fiber));
      }
      __name(pushStoreConsistencyCheck, "pushStoreConsistencyCheck");
      function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) {
        inst.value = nextSnapshot;
        inst.getSnapshot = getSnapshot;
        checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);
      }
      __name(updateStoreInstance, "updateStoreInstance");
      function subscribeToStore(fiber, inst, subscribe) {
        return subscribe(function() {
          checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);
        });
      }
      __name(subscribeToStore, "subscribeToStore");
      function checkIfSnapshotChanged(inst) {
        var latestGetSnapshot = inst.getSnapshot;
        inst = inst.value;
        try {
          var nextValue = latestGetSnapshot();
          return !objectIs(inst, nextValue);
        } catch (error) {
          return true;
        }
      }
      __name(checkIfSnapshotChanged, "checkIfSnapshotChanged");
      function forceStoreRerender(fiber) {
        var root = enqueueConcurrentRenderForLane(fiber, 2);
        null !== root && scheduleUpdateOnFiber(root, fiber, 2);
      }
      __name(forceStoreRerender, "forceStoreRerender");
      function mountStateImpl(initialState2) {
        var hook = mountWorkInProgressHook();
        if ("function" === typeof initialState2) {
          var initialStateInitializer = initialState2;
          initialState2 = initialStateInitializer();
          if (shouldDoubleInvokeUserFnsInHooksDEV) {
            setIsStrictModeForDevtools(true);
            try {
              initialStateInitializer();
            } finally {
              setIsStrictModeForDevtools(false);
            }
          }
        }
        hook.memoizedState = hook.baseState = initialState2;
        hook.queue = {
          pending: null,
          lanes: 0,
          dispatch: null,
          lastRenderedReducer: basicStateReducer,
          lastRenderedState: initialState2
        };
        return hook;
      }
      __name(mountStateImpl, "mountStateImpl");
      function updateOptimisticImpl(hook, current, passthrough, reducer) {
        hook.baseState = passthrough;
        return updateReducerImpl(
          hook,
          currentHook,
          "function" === typeof reducer ? reducer : basicStateReducer
        );
      }
      __name(updateOptimisticImpl, "updateOptimisticImpl");
      function dispatchActionState(fiber, actionQueue, setPendingState, setState, payload) {
        if (isRenderPhaseUpdate(fiber)) throw Error(formatProdErrorMessage(485));
        fiber = actionQueue.action;
        if (null !== fiber) {
          var actionNode = {
            payload,
            action: fiber,
            next: null,
            isTransition: true,
            status: "pending",
            value: null,
            reason: null,
            listeners: [],
            then: /* @__PURE__ */ __name(function(listener) {
              actionNode.listeners.push(listener);
            }, "then")
          };
          null !== ReactSharedInternals.T ? setPendingState(true) : actionNode.isTransition = false;
          setState(actionNode);
          setPendingState = actionQueue.pending;
          null === setPendingState ? (actionNode.next = actionQueue.pending = actionNode, runActionStateAction(actionQueue, actionNode)) : (actionNode.next = setPendingState.next, actionQueue.pending = setPendingState.next = actionNode);
        }
      }
      __name(dispatchActionState, "dispatchActionState");
      function runActionStateAction(actionQueue, node) {
        var action = node.action, payload = node.payload, prevState = actionQueue.state;
        if (node.isTransition) {
          var prevTransition = ReactSharedInternals.T, currentTransition = {};
          ReactSharedInternals.T = currentTransition;
          try {
            var returnValue = action(prevState, payload), onStartTransitionFinish = ReactSharedInternals.S;
            null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
            handleActionReturnValue(actionQueue, node, returnValue);
          } catch (error) {
            onActionError(actionQueue, node, error);
          } finally {
            ReactSharedInternals.T = prevTransition;
          }
        } else
          try {
            prevTransition = action(prevState, payload), handleActionReturnValue(actionQueue, node, prevTransition);
          } catch (error$27) {
            onActionError(actionQueue, node, error$27);
          }
      }
      __name(runActionStateAction, "runActionStateAction");
      function handleActionReturnValue(actionQueue, node, returnValue) {
        null !== returnValue && "object" === typeof returnValue && "function" === typeof returnValue.then ? returnValue.then(
          function(nextState) {
            onActionSuccess(actionQueue, node, nextState);
          },
          function(error) {
            return onActionError(actionQueue, node, error);
          }
        ) : onActionSuccess(actionQueue, node, returnValue);
      }
      __name(handleActionReturnValue, "handleActionReturnValue");
      function onActionSuccess(actionQueue, actionNode, nextState) {
        actionNode.status = "fulfilled";
        actionNode.value = nextState;
        notifyActionListeners(actionNode);
        actionQueue.state = nextState;
        actionNode = actionQueue.pending;
        null !== actionNode && (nextState = actionNode.next, nextState === actionNode ? actionQueue.pending = null : (nextState = nextState.next, actionNode.next = nextState, runActionStateAction(actionQueue, nextState)));
      }
      __name(onActionSuccess, "onActionSuccess");
      function onActionError(actionQueue, actionNode, error) {
        var last2 = actionQueue.pending;
        actionQueue.pending = null;
        if (null !== last2) {
          last2 = last2.next;
          do
            actionNode.status = "rejected", actionNode.reason = error, notifyActionListeners(actionNode), actionNode = actionNode.next;
          while (actionNode !== last2);
        }
        actionQueue.action = null;
      }
      __name(onActionError, "onActionError");
      function notifyActionListeners(actionNode) {
        actionNode = actionNode.listeners;
        for (var i = 0; i < actionNode.length; i++) (0, actionNode[i])();
      }
      __name(notifyActionListeners, "notifyActionListeners");
      function actionStateReducer(oldState, newState) {
        return newState;
      }
      __name(actionStateReducer, "actionStateReducer");
      function mountActionState(action, initialStateProp) {
        if (isHydrating) {
          var ssrFormState = workInProgressRoot.formState;
          if (null !== ssrFormState) {
            a: {
              var JSCompiler_inline_result = currentlyRenderingFiber;
              if (isHydrating) {
                if (nextHydratableInstance) {
                  var markerInstance = canHydrateFormStateMarker(
                    nextHydratableInstance,
                    rootOrSingletonContext
                  );
                  if (markerInstance) {
                    nextHydratableInstance = getNextHydratableSibling(markerInstance);
                    JSCompiler_inline_result = isFormStateMarkerMatching(markerInstance);
                    break a;
                  }
                }
                throwOnHydrationMismatch(JSCompiler_inline_result);
              }
              JSCompiler_inline_result = false;
            }
            JSCompiler_inline_result && (initialStateProp = ssrFormState[0]);
          }
        }
        ssrFormState = mountWorkInProgressHook();
        ssrFormState.memoizedState = ssrFormState.baseState = initialStateProp;
        JSCompiler_inline_result = {
          pending: null,
          lanes: 0,
          dispatch: null,
          lastRenderedReducer: actionStateReducer,
          lastRenderedState: initialStateProp
        };
        ssrFormState.queue = JSCompiler_inline_result;
        ssrFormState = dispatchSetState.bind(
          null,
          currentlyRenderingFiber,
          JSCompiler_inline_result
        );
        JSCompiler_inline_result.dispatch = ssrFormState;
        JSCompiler_inline_result = mountStateImpl(false);
        var setPendingState = dispatchOptimisticSetState.bind(
          null,
          currentlyRenderingFiber,
          false,
          JSCompiler_inline_result.queue
        );
        JSCompiler_inline_result = mountWorkInProgressHook();
        markerInstance = {
          state: initialStateProp,
          dispatch: null,
          action,
          pending: null
        };
        JSCompiler_inline_result.queue = markerInstance;
        ssrFormState = dispatchActionState.bind(
          null,
          currentlyRenderingFiber,
          markerInstance,
          setPendingState,
          ssrFormState
        );
        markerInstance.dispatch = ssrFormState;
        JSCompiler_inline_result.memoizedState = action;
        return [initialStateProp, ssrFormState, false];
      }
      __name(mountActionState, "mountActionState");
      function updateActionState(action) {
        var stateHook = updateWorkInProgressHook();
        return updateActionStateImpl(stateHook, currentHook, action);
      }
      __name(updateActionState, "updateActionState");
      function updateActionStateImpl(stateHook, currentStateHook, action) {
        currentStateHook = updateReducerImpl(
          stateHook,
          currentStateHook,
          actionStateReducer
        )[0];
        stateHook = updateReducer(basicStateReducer)[0];
        if ("object" === typeof currentStateHook && null !== currentStateHook && "function" === typeof currentStateHook.then)
          try {
            var state = useThenable(currentStateHook);
          } catch (x) {
            if (x === SuspenseException) throw SuspenseActionException;
            throw x;
          }
        else state = currentStateHook;
        currentStateHook = updateWorkInProgressHook();
        var actionQueue = currentStateHook.queue, dispatch = actionQueue.dispatch;
        action !== currentStateHook.memoizedState && (currentlyRenderingFiber.flags |= 2048, pushSimpleEffect(
          9,
          createEffectInstance(),
          actionStateActionEffect.bind(null, actionQueue, action),
          null
        ));
        return [state, dispatch, stateHook];
      }
      __name(updateActionStateImpl, "updateActionStateImpl");
      function actionStateActionEffect(actionQueue, action) {
        actionQueue.action = action;
      }
      __name(actionStateActionEffect, "actionStateActionEffect");
      function rerenderActionState(action) {
        var stateHook = updateWorkInProgressHook(), currentStateHook = currentHook;
        if (null !== currentStateHook)
          return updateActionStateImpl(stateHook, currentStateHook, action);
        updateWorkInProgressHook();
        stateHook = stateHook.memoizedState;
        currentStateHook = updateWorkInProgressHook();
        var dispatch = currentStateHook.queue.dispatch;
        currentStateHook.memoizedState = action;
        return [stateHook, dispatch, false];
      }
      __name(rerenderActionState, "rerenderActionState");
      function pushSimpleEffect(tag2, inst, create3, createDeps) {
        tag2 = {
          tag: tag2,
          create: create3,
          deps: createDeps,
          inst,
          next: null
        };
        inst = currentlyRenderingFiber.updateQueue;
        null === inst && (inst = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = inst);
        create3 = inst.lastEffect;
        null === create3 ? inst.lastEffect = tag2.next = tag2 : (createDeps = create3.next, create3.next = tag2, tag2.next = createDeps, inst.lastEffect = tag2);
        return tag2;
      }
      __name(pushSimpleEffect, "pushSimpleEffect");
      function createEffectInstance() {
        return { destroy: void 0, resource: void 0 };
      }
      __name(createEffectInstance, "createEffectInstance");
      function updateRef() {
        return updateWorkInProgressHook().memoizedState;
      }
      __name(updateRef, "updateRef");
      function mountEffectImpl(fiberFlags, hookFlags, create3, createDeps) {
        var hook = mountWorkInProgressHook();
        createDeps = void 0 === createDeps ? null : createDeps;
        currentlyRenderingFiber.flags |= fiberFlags;
        hook.memoizedState = pushSimpleEffect(
          1 | hookFlags,
          createEffectInstance(),
          create3,
          createDeps
        );
      }
      __name(mountEffectImpl, "mountEffectImpl");
      function updateEffectImpl(fiberFlags, hookFlags, create3, deps) {
        var hook = updateWorkInProgressHook();
        deps = void 0 === deps ? null : deps;
        var inst = hook.memoizedState.inst;
        null !== currentHook && null !== deps && areHookInputsEqual(deps, currentHook.memoizedState.deps) ? hook.memoizedState = pushSimpleEffect(hookFlags, inst, create3, deps) : (currentlyRenderingFiber.flags |= fiberFlags, hook.memoizedState = pushSimpleEffect(
          1 | hookFlags,
          inst,
          create3,
          deps
        ));
      }
      __name(updateEffectImpl, "updateEffectImpl");
      function mountEffect(create3, createDeps) {
        mountEffectImpl(8390656, 8, create3, createDeps);
      }
      __name(mountEffect, "mountEffect");
      function updateEffect(create3, createDeps) {
        updateEffectImpl(2048, 8, create3, createDeps);
      }
      __name(updateEffect, "updateEffect");
      function updateInsertionEffect(create3, deps) {
        return updateEffectImpl(4, 2, create3, deps);
      }
      __name(updateInsertionEffect, "updateInsertionEffect");
      function updateLayoutEffect(create3, deps) {
        return updateEffectImpl(4, 4, create3, deps);
      }
      __name(updateLayoutEffect, "updateLayoutEffect");
      function imperativeHandleEffect(create3, ref) {
        if ("function" === typeof ref) {
          create3 = create3();
          var refCleanup = ref(create3);
          return function() {
            "function" === typeof refCleanup ? refCleanup() : ref(null);
          };
        }
        if (null !== ref && void 0 !== ref)
          return create3 = create3(), ref.current = create3, function() {
            ref.current = null;
          };
      }
      __name(imperativeHandleEffect, "imperativeHandleEffect");
      function updateImperativeHandle(ref, create3, deps) {
        deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null;
        updateEffectImpl(
          4,
          4,
          imperativeHandleEffect.bind(null, create3, ref),
          deps
        );
      }
      __name(updateImperativeHandle, "updateImperativeHandle");
      function mountDebugValue() {
      }
      __name(mountDebugValue, "mountDebugValue");
      function updateCallback(callback, deps) {
        var hook = updateWorkInProgressHook();
        deps = void 0 === deps ? null : deps;
        var prevState = hook.memoizedState;
        if (null !== deps && areHookInputsEqual(deps, prevState[1]))
          return prevState[0];
        hook.memoizedState = [callback, deps];
        return callback;
      }
      __name(updateCallback, "updateCallback");
      function updateMemo(nextCreate, deps) {
        var hook = updateWorkInProgressHook();
        deps = void 0 === deps ? null : deps;
        var prevState = hook.memoizedState;
        if (null !== deps && areHookInputsEqual(deps, prevState[1]))
          return prevState[0];
        prevState = nextCreate();
        if (shouldDoubleInvokeUserFnsInHooksDEV) {
          setIsStrictModeForDevtools(true);
          try {
            nextCreate();
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
        hook.memoizedState = [prevState, deps];
        return prevState;
      }
      __name(updateMemo, "updateMemo");
      function mountDeferredValueImpl(hook, value, initialValue) {
        if (void 0 === initialValue || 0 !== (renderLanes & 1073741824))
          return hook.memoizedState = value;
        hook.memoizedState = initialValue;
        hook = requestDeferredLane();
        currentlyRenderingFiber.lanes |= hook;
        workInProgressRootSkippedLanes |= hook;
        return initialValue;
      }
      __name(mountDeferredValueImpl, "mountDeferredValueImpl");
      function updateDeferredValueImpl(hook, prevValue, value, initialValue) {
        if (objectIs(value, prevValue)) return value;
        if (null !== currentTreeHiddenStackCursor.current)
          return hook = mountDeferredValueImpl(hook, value, initialValue), objectIs(hook, prevValue) || (didReceiveUpdate = true), hook;
        if (0 === (renderLanes & 42))
          return didReceiveUpdate = true, hook.memoizedState = value;
        hook = requestDeferredLane();
        currentlyRenderingFiber.lanes |= hook;
        workInProgressRootSkippedLanes |= hook;
        return prevValue;
      }
      __name(updateDeferredValueImpl, "updateDeferredValueImpl");
      function startTransition(fiber, queue, pendingState, finishedState, callback) {
        var previousPriority = getCurrentUpdatePriority();
        setCurrentUpdatePriority(
          0 !== previousPriority && 8 > previousPriority ? previousPriority : 8
        );
        var prevTransition = ReactSharedInternals.T, currentTransition = {};
        ReactSharedInternals.T = currentTransition;
        dispatchOptimisticSetState(fiber, false, queue, pendingState);
        try {
          var returnValue = callback(), onStartTransitionFinish = ReactSharedInternals.S;
          null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
          if (null !== returnValue && "object" === typeof returnValue && "function" === typeof returnValue.then) {
            var thenableForFinishedState = chainThenableValue(
              returnValue,
              finishedState
            );
            dispatchSetStateInternal(
              fiber,
              queue,
              thenableForFinishedState,
              requestUpdateLane(fiber)
            );
          } else
            dispatchSetStateInternal(
              fiber,
              queue,
              finishedState,
              requestUpdateLane(fiber)
            );
        } catch (error) {
          dispatchSetStateInternal(
            fiber,
            queue,
            { then: /* @__PURE__ */ __name(function() {
            }, "then"), status: "rejected", reason: error },
            requestUpdateLane()
          );
        } finally {
          setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = prevTransition;
        }
      }
      __name(startTransition, "startTransition");
      function ensureFormComponentIsStateful(formFiber) {
        var existingStateHook = formFiber.memoizedState;
        if (null !== existingStateHook) return existingStateHook;
        existingStateHook = {
          memoizedState: NotPendingTransition,
          baseState: NotPendingTransition,
          baseQueue: null,
          queue: {
            pending: null,
            lanes: 0,
            dispatch: null,
            lastRenderedReducer: basicStateReducer,
            lastRenderedState: NotPendingTransition
          },
          next: null
        };
        var initialResetState = {};
        existingStateHook.next = {
          memoizedState: initialResetState,
          baseState: initialResetState,
          baseQueue: null,
          queue: {
            pending: null,
            lanes: 0,
            dispatch: null,
            lastRenderedReducer: basicStateReducer,
            lastRenderedState: initialResetState
          },
          next: null
        };
        formFiber.memoizedState = existingStateHook;
        formFiber = formFiber.alternate;
        null !== formFiber && (formFiber.memoizedState = existingStateHook);
        return existingStateHook;
      }
      __name(ensureFormComponentIsStateful, "ensureFormComponentIsStateful");
      function useHostTransitionStatus() {
        return readContext(HostTransitionContext);
      }
      __name(useHostTransitionStatus, "useHostTransitionStatus");
      function updateId() {
        return updateWorkInProgressHook().memoizedState;
      }
      __name(updateId, "updateId");
      function updateRefresh() {
        return updateWorkInProgressHook().memoizedState;
      }
      __name(updateRefresh, "updateRefresh");
      function refreshCache(fiber) {
        for (var provider = fiber.return; null !== provider; ) {
          switch (provider.tag) {
            case 24:
            case 3:
              var lane = requestUpdateLane();
              fiber = createUpdate(lane);
              var root = enqueueUpdate(provider, fiber, lane);
              null !== root && (scheduleUpdateOnFiber(root, provider, lane), entangleTransitions(root, provider, lane));
              provider = { cache: createCache() };
              fiber.payload = provider;
              return;
          }
          provider = provider.return;
        }
      }
      __name(refreshCache, "refreshCache");
      function dispatchReducerAction(fiber, queue, action) {
        var lane = requestUpdateLane();
        action = {
          lane,
          revertLane: 0,
          action,
          hasEagerState: false,
          eagerState: null,
          next: null
        };
        isRenderPhaseUpdate(fiber) ? enqueueRenderPhaseUpdate(queue, action) : (action = enqueueConcurrentHookUpdate(fiber, queue, action, lane), null !== action && (scheduleUpdateOnFiber(action, fiber, lane), entangleTransitionUpdate(action, queue, lane)));
      }
      __name(dispatchReducerAction, "dispatchReducerAction");
      function dispatchSetState(fiber, queue, action) {
        var lane = requestUpdateLane();
        dispatchSetStateInternal(fiber, queue, action, lane);
      }
      __name(dispatchSetState, "dispatchSetState");
      function dispatchSetStateInternal(fiber, queue, action, lane) {
        var update2 = {
          lane,
          revertLane: 0,
          action,
          hasEagerState: false,
          eagerState: null,
          next: null
        };
        if (isRenderPhaseUpdate(fiber)) enqueueRenderPhaseUpdate(queue, update2);
        else {
          var alternate = fiber.alternate;
          if (0 === fiber.lanes && (null === alternate || 0 === alternate.lanes) && (alternate = queue.lastRenderedReducer, null !== alternate))
            try {
              var currentState = queue.lastRenderedState, eagerState = alternate(currentState, action);
              update2.hasEagerState = true;
              update2.eagerState = eagerState;
              if (objectIs(eagerState, currentState))
                return enqueueUpdate$1(fiber, queue, update2, 0), null === workInProgressRoot && finishQueueingConcurrentUpdates(), false;
            } catch (error) {
            } finally {
            }
          action = enqueueConcurrentHookUpdate(fiber, queue, update2, lane);
          if (null !== action)
            return scheduleUpdateOnFiber(action, fiber, lane), entangleTransitionUpdate(action, queue, lane), true;
        }
        return false;
      }
      __name(dispatchSetStateInternal, "dispatchSetStateInternal");
      function dispatchOptimisticSetState(fiber, throwIfDuringRender, queue, action) {
        action = {
          lane: 2,
          revertLane: requestTransitionLane(),
          action,
          hasEagerState: false,
          eagerState: null,
          next: null
        };
        if (isRenderPhaseUpdate(fiber)) {
          if (throwIfDuringRender) throw Error(formatProdErrorMessage(479));
        } else
          throwIfDuringRender = enqueueConcurrentHookUpdate(
            fiber,
            queue,
            action,
            2
          ), null !== throwIfDuringRender && scheduleUpdateOnFiber(throwIfDuringRender, fiber, 2);
      }
      __name(dispatchOptimisticSetState, "dispatchOptimisticSetState");
      function isRenderPhaseUpdate(fiber) {
        var alternate = fiber.alternate;
        return fiber === currentlyRenderingFiber || null !== alternate && alternate === currentlyRenderingFiber;
      }
      __name(isRenderPhaseUpdate, "isRenderPhaseUpdate");
      function enqueueRenderPhaseUpdate(queue, update2) {
        didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
        var pending = queue.pending;
        null === pending ? update2.next = update2 : (update2.next = pending.next, pending.next = update2);
        queue.pending = update2;
      }
      __name(enqueueRenderPhaseUpdate, "enqueueRenderPhaseUpdate");
      function entangleTransitionUpdate(root, queue, lane) {
        if (0 !== (lane & 4194048)) {
          var queueLanes = queue.lanes;
          queueLanes &= root.pendingLanes;
          lane |= queueLanes;
          queue.lanes = lane;
          markRootEntangled(root, lane);
        }
      }
      __name(entangleTransitionUpdate, "entangleTransitionUpdate");
      function unwrapThenable(thenable) {
        var index = thenableIndexCounter;
        thenableIndexCounter += 1;
        null === thenableState && (thenableState = []);
        return trackUsedThenable(thenableState, thenable, index);
      }
      __name(unwrapThenable, "unwrapThenable");
      function coerceRef(workInProgress2, element) {
        element = element.props.ref;
        workInProgress2.ref = void 0 !== element ? element : null;
      }
      __name(coerceRef, "coerceRef");
      function throwOnInvalidObjectType(returnFiber, newChild) {
        if (newChild.$$typeof === REACT_LEGACY_ELEMENT_TYPE)
          throw Error(formatProdErrorMessage(525));
        returnFiber = Object.prototype.toString.call(newChild);
        throw Error(
          formatProdErrorMessage(
            31,
            "[object Object]" === returnFiber ? "object with keys {" + Object.keys(newChild).join(", ") + "}" : returnFiber
          )
        );
      }
      __name(throwOnInvalidObjectType, "throwOnInvalidObjectType");
      function resolveLazy(lazyType2) {
        var init = lazyType2._init;
        return init(lazyType2._payload);
      }
      __name(resolveLazy, "resolveLazy");
      function createChildReconciler(shouldTrackSideEffects) {
        function deleteChild(returnFiber, childToDelete) {
          if (shouldTrackSideEffects) {
            var deletions = returnFiber.deletions;
            null === deletions ? (returnFiber.deletions = [childToDelete], returnFiber.flags |= 16) : deletions.push(childToDelete);
          }
        }
        __name(deleteChild, "deleteChild");
        function deleteRemainingChildren(returnFiber, currentFirstChild) {
          if (!shouldTrackSideEffects) return null;
          for (; null !== currentFirstChild; )
            deleteChild(returnFiber, currentFirstChild), currentFirstChild = currentFirstChild.sibling;
          return null;
        }
        __name(deleteRemainingChildren, "deleteRemainingChildren");
        function mapRemainingChildren(currentFirstChild) {
          for (var existingChildren = /* @__PURE__ */ new Map(); null !== currentFirstChild; )
            null !== currentFirstChild.key ? existingChildren.set(currentFirstChild.key, currentFirstChild) : existingChildren.set(currentFirstChild.index, currentFirstChild), currentFirstChild = currentFirstChild.sibling;
          return existingChildren;
        }
        __name(mapRemainingChildren, "mapRemainingChildren");
        function useFiber(fiber, pendingProps) {
          fiber = createWorkInProgress(fiber, pendingProps);
          fiber.index = 0;
          fiber.sibling = null;
          return fiber;
        }
        __name(useFiber, "useFiber");
        function placeChild(newFiber, lastPlacedIndex, newIndex) {
          newFiber.index = newIndex;
          if (!shouldTrackSideEffects)
            return newFiber.flags |= 1048576, lastPlacedIndex;
          newIndex = newFiber.alternate;
          if (null !== newIndex)
            return newIndex = newIndex.index, newIndex < lastPlacedIndex ? (newFiber.flags |= 67108866, lastPlacedIndex) : newIndex;
          newFiber.flags |= 67108866;
          return lastPlacedIndex;
        }
        __name(placeChild, "placeChild");
        function placeSingleChild(newFiber) {
          shouldTrackSideEffects && null === newFiber.alternate && (newFiber.flags |= 67108866);
          return newFiber;
        }
        __name(placeSingleChild, "placeSingleChild");
        function updateTextNode(returnFiber, current, textContent2, lanes) {
          if (null === current || 6 !== current.tag)
            return current = createFiberFromText(textContent2, returnFiber.mode, lanes), current.return = returnFiber, current;
          current = useFiber(current, textContent2);
          current.return = returnFiber;
          return current;
        }
        __name(updateTextNode, "updateTextNode");
        function updateElement(returnFiber, current, element, lanes) {
          var elementType = element.type;
          if (elementType === REACT_FRAGMENT_TYPE)
            return updateFragment(
              returnFiber,
              current,
              element.props.children,
              lanes,
              element.key
            );
          if (null !== current && (current.elementType === elementType || "object" === typeof elementType && null !== elementType && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current.type))
            return current = useFiber(current, element.props), coerceRef(current, element), current.return = returnFiber, current;
          current = createFiberFromTypeAndProps(
            element.type,
            element.key,
            element.props,
            null,
            returnFiber.mode,
            lanes
          );
          coerceRef(current, element);
          current.return = returnFiber;
          return current;
        }
        __name(updateElement, "updateElement");
        function updatePortal(returnFiber, current, portal, lanes) {
          if (null === current || 4 !== current.tag || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation)
            return current = createFiberFromPortal(portal, returnFiber.mode, lanes), current.return = returnFiber, current;
          current = useFiber(current, portal.children || []);
          current.return = returnFiber;
          return current;
        }
        __name(updatePortal, "updatePortal");
        function updateFragment(returnFiber, current, fragment, lanes, key) {
          if (null === current || 7 !== current.tag)
            return current = createFiberFromFragment(
              fragment,
              returnFiber.mode,
              lanes,
              key
            ), current.return = returnFiber, current;
          current = useFiber(current, fragment);
          current.return = returnFiber;
          return current;
        }
        __name(updateFragment, "updateFragment");
        function createChild(returnFiber, newChild, lanes) {
          if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
            return newChild = createFiberFromText(
              "" + newChild,
              returnFiber.mode,
              lanes
            ), newChild.return = returnFiber, newChild;
          if ("object" === typeof newChild && null !== newChild) {
            switch (newChild.$$typeof) {
              case REACT_ELEMENT_TYPE:
                return lanes = createFiberFromTypeAndProps(
                  newChild.type,
                  newChild.key,
                  newChild.props,
                  null,
                  returnFiber.mode,
                  lanes
                ), coerceRef(lanes, newChild), lanes.return = returnFiber, lanes;
              case REACT_PORTAL_TYPE:
                return newChild = createFiberFromPortal(
                  newChild,
                  returnFiber.mode,
                  lanes
                ), newChild.return = returnFiber, newChild;
              case REACT_LAZY_TYPE:
                var init = newChild._init;
                newChild = init(newChild._payload);
                return createChild(returnFiber, newChild, lanes);
            }
            if (isArrayImpl(newChild) || getIteratorFn(newChild))
              return newChild = createFiberFromFragment(
                newChild,
                returnFiber.mode,
                lanes,
                null
              ), newChild.return = returnFiber, newChild;
            if ("function" === typeof newChild.then)
              return createChild(returnFiber, unwrapThenable(newChild), lanes);
            if (newChild.$$typeof === REACT_CONTEXT_TYPE)
              return createChild(
                returnFiber,
                readContextDuringReconciliation(returnFiber, newChild),
                lanes
              );
            throwOnInvalidObjectType(returnFiber, newChild);
          }
          return null;
        }
        __name(createChild, "createChild");
        function updateSlot(returnFiber, oldFiber, newChild, lanes) {
          var key = null !== oldFiber ? oldFiber.key : null;
          if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
            return null !== key ? null : updateTextNode(returnFiber, oldFiber, "" + newChild, lanes);
          if ("object" === typeof newChild && null !== newChild) {
            switch (newChild.$$typeof) {
              case REACT_ELEMENT_TYPE:
                return newChild.key === key ? updateElement(returnFiber, oldFiber, newChild, lanes) : null;
              case REACT_PORTAL_TYPE:
                return newChild.key === key ? updatePortal(returnFiber, oldFiber, newChild, lanes) : null;
              case REACT_LAZY_TYPE:
                return key = newChild._init, newChild = key(newChild._payload), updateSlot(returnFiber, oldFiber, newChild, lanes);
            }
            if (isArrayImpl(newChild) || getIteratorFn(newChild))
              return null !== key ? null : updateFragment(returnFiber, oldFiber, newChild, lanes, null);
            if ("function" === typeof newChild.then)
              return updateSlot(
                returnFiber,
                oldFiber,
                unwrapThenable(newChild),
                lanes
              );
            if (newChild.$$typeof === REACT_CONTEXT_TYPE)
              return updateSlot(
                returnFiber,
                oldFiber,
                readContextDuringReconciliation(returnFiber, newChild),
                lanes
              );
            throwOnInvalidObjectType(returnFiber, newChild);
          }
          return null;
        }
        __name(updateSlot, "updateSlot");
        function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) {
          if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
            return existingChildren = existingChildren.get(newIdx) || null, updateTextNode(returnFiber, existingChildren, "" + newChild, lanes);
          if ("object" === typeof newChild && null !== newChild) {
            switch (newChild.$$typeof) {
              case REACT_ELEMENT_TYPE:
                return existingChildren = existingChildren.get(
                  null === newChild.key ? newIdx : newChild.key
                ) || null, updateElement(returnFiber, existingChildren, newChild, lanes);
              case REACT_PORTAL_TYPE:
                return existingChildren = existingChildren.get(
                  null === newChild.key ? newIdx : newChild.key
                ) || null, updatePortal(returnFiber, existingChildren, newChild, lanes);
              case REACT_LAZY_TYPE:
                var init = newChild._init;
                newChild = init(newChild._payload);
                return updateFromMap(
                  existingChildren,
                  returnFiber,
                  newIdx,
                  newChild,
                  lanes
                );
            }
            if (isArrayImpl(newChild) || getIteratorFn(newChild))
              return existingChildren = existingChildren.get(newIdx) || null, updateFragment(returnFiber, existingChildren, newChild, lanes, null);
            if ("function" === typeof newChild.then)
              return updateFromMap(
                existingChildren,
                returnFiber,
                newIdx,
                unwrapThenable(newChild),
                lanes
              );
            if (newChild.$$typeof === REACT_CONTEXT_TYPE)
              return updateFromMap(
                existingChildren,
                returnFiber,
                newIdx,
                readContextDuringReconciliation(returnFiber, newChild),
                lanes
              );
            throwOnInvalidObjectType(returnFiber, newChild);
          }
          return null;
        }
        __name(updateFromMap, "updateFromMap");
        function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
          for (var resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, newIdx = currentFirstChild = 0, nextOldFiber = null; null !== oldFiber && newIdx < newChildren.length; newIdx++) {
            oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling;
            var newFiber = updateSlot(
              returnFiber,
              oldFiber,
              newChildren[newIdx],
              lanes
            );
            if (null === newFiber) {
              null === oldFiber && (oldFiber = nextOldFiber);
              break;
            }
            shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber);
            currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
            null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber;
            previousNewFiber = newFiber;
            oldFiber = nextOldFiber;
          }
          if (newIdx === newChildren.length)
            return deleteRemainingChildren(returnFiber, oldFiber), isHydrating && pushTreeFork(returnFiber, newIdx), resultingFirstChild;
          if (null === oldFiber) {
            for (; newIdx < newChildren.length; newIdx++)
              oldFiber = createChild(returnFiber, newChildren[newIdx], lanes), null !== oldFiber && (currentFirstChild = placeChild(
                oldFiber,
                currentFirstChild,
                newIdx
              ), null === previousNewFiber ? resultingFirstChild = oldFiber : previousNewFiber.sibling = oldFiber, previousNewFiber = oldFiber);
            isHydrating && pushTreeFork(returnFiber, newIdx);
            return resultingFirstChild;
          }
          for (oldFiber = mapRemainingChildren(oldFiber); newIdx < newChildren.length; newIdx++)
            nextOldFiber = updateFromMap(
              oldFiber,
              returnFiber,
              newIdx,
              newChildren[newIdx],
              lanes
            ), null !== nextOldFiber && (shouldTrackSideEffects && null !== nextOldFiber.alternate && oldFiber.delete(
              null === nextOldFiber.key ? newIdx : nextOldFiber.key
            ), currentFirstChild = placeChild(
              nextOldFiber,
              currentFirstChild,
              newIdx
            ), null === previousNewFiber ? resultingFirstChild = nextOldFiber : previousNewFiber.sibling = nextOldFiber, previousNewFiber = nextOldFiber);
          shouldTrackSideEffects && oldFiber.forEach(function(child) {
            return deleteChild(returnFiber, child);
          });
          isHydrating && pushTreeFork(returnFiber, newIdx);
          return resultingFirstChild;
        }
        __name(reconcileChildrenArray, "reconcileChildrenArray");
        function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildren, lanes) {
          if (null == newChildren) throw Error(formatProdErrorMessage(151));
          for (var resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, newIdx = currentFirstChild = 0, nextOldFiber = null, step = newChildren.next(); null !== oldFiber && !step.done; newIdx++, step = newChildren.next()) {
            oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling;
            var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);
            if (null === newFiber) {
              null === oldFiber && (oldFiber = nextOldFiber);
              break;
            }
            shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber);
            currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
            null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber;
            previousNewFiber = newFiber;
            oldFiber = nextOldFiber;
          }
          if (step.done)
            return deleteRemainingChildren(returnFiber, oldFiber), isHydrating && pushTreeFork(returnFiber, newIdx), resultingFirstChild;
          if (null === oldFiber) {
            for (; !step.done; newIdx++, step = newChildren.next())
              step = createChild(returnFiber, step.value, lanes), null !== step && (currentFirstChild = placeChild(
                step,
                currentFirstChild,
                newIdx
              ), null === previousNewFiber ? resultingFirstChild = step : previousNewFiber.sibling = step, previousNewFiber = step);
            isHydrating && pushTreeFork(returnFiber, newIdx);
            return resultingFirstChild;
          }
          for (oldFiber = mapRemainingChildren(oldFiber); !step.done; newIdx++, step = newChildren.next())
            step = updateFromMap(
              oldFiber,
              returnFiber,
              newIdx,
              step.value,
              lanes
            ), null !== step && (shouldTrackSideEffects && null !== step.alternate && oldFiber.delete(null === step.key ? newIdx : step.key), currentFirstChild = placeChild(step, currentFirstChild, newIdx), null === previousNewFiber ? resultingFirstChild = step : previousNewFiber.sibling = step, previousNewFiber = step);
          shouldTrackSideEffects && oldFiber.forEach(function(child) {
            return deleteChild(returnFiber, child);
          });
          isHydrating && pushTreeFork(returnFiber, newIdx);
          return resultingFirstChild;
        }
        __name(reconcileChildrenIterator, "reconcileChildrenIterator");
        function reconcileChildFibersImpl(returnFiber, currentFirstChild, newChild, lanes) {
          "object" === typeof newChild && null !== newChild && newChild.type === REACT_FRAGMENT_TYPE && null === newChild.key && (newChild = newChild.props.children);
          if ("object" === typeof newChild && null !== newChild) {
            switch (newChild.$$typeof) {
              case REACT_ELEMENT_TYPE:
                a: {
                  for (var key = newChild.key; null !== currentFirstChild; ) {
                    if (currentFirstChild.key === key) {
                      key = newChild.type;
                      if (key === REACT_FRAGMENT_TYPE) {
                        if (7 === currentFirstChild.tag) {
                          deleteRemainingChildren(
                            returnFiber,
                            currentFirstChild.sibling
                          );
                          lanes = useFiber(
                            currentFirstChild,
                            newChild.props.children
                          );
                          lanes.return = returnFiber;
                          returnFiber = lanes;
                          break a;
                        }
                      } else if (currentFirstChild.elementType === key || "object" === typeof key && null !== key && key.$$typeof === REACT_LAZY_TYPE && resolveLazy(key) === currentFirstChild.type) {
                        deleteRemainingChildren(
                          returnFiber,
                          currentFirstChild.sibling
                        );
                        lanes = useFiber(currentFirstChild, newChild.props);
                        coerceRef(lanes, newChild);
                        lanes.return = returnFiber;
                        returnFiber = lanes;
                        break a;
                      }
                      deleteRemainingChildren(returnFiber, currentFirstChild);
                      break;
                    } else deleteChild(returnFiber, currentFirstChild);
                    currentFirstChild = currentFirstChild.sibling;
                  }
                  newChild.type === REACT_FRAGMENT_TYPE ? (lanes = createFiberFromFragment(
                    newChild.props.children,
                    returnFiber.mode,
                    lanes,
                    newChild.key
                  ), lanes.return = returnFiber, returnFiber = lanes) : (lanes = createFiberFromTypeAndProps(
                    newChild.type,
                    newChild.key,
                    newChild.props,
                    null,
                    returnFiber.mode,
                    lanes
                  ), coerceRef(lanes, newChild), lanes.return = returnFiber, returnFiber = lanes);
                }
                return placeSingleChild(returnFiber);
              case REACT_PORTAL_TYPE:
                a: {
                  for (key = newChild.key; null !== currentFirstChild; ) {
                    if (currentFirstChild.key === key)
                      if (4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === newChild.containerInfo && currentFirstChild.stateNode.implementation === newChild.implementation) {
                        deleteRemainingChildren(
                          returnFiber,
                          currentFirstChild.sibling
                        );
                        lanes = useFiber(
                          currentFirstChild,
                          newChild.children || []
                        );
                        lanes.return = returnFiber;
                        returnFiber = lanes;
                        break a;
                      } else {
                        deleteRemainingChildren(returnFiber, currentFirstChild);
                        break;
                      }
                    else deleteChild(returnFiber, currentFirstChild);
                    currentFirstChild = currentFirstChild.sibling;
                  }
                  lanes = createFiberFromPortal(newChild, returnFiber.mode, lanes);
                  lanes.return = returnFiber;
                  returnFiber = lanes;
                }
                return placeSingleChild(returnFiber);
              case REACT_LAZY_TYPE:
                return key = newChild._init, newChild = key(newChild._payload), reconcileChildFibersImpl(
                  returnFiber,
                  currentFirstChild,
                  newChild,
                  lanes
                );
            }
            if (isArrayImpl(newChild))
              return reconcileChildrenArray(
                returnFiber,
                currentFirstChild,
                newChild,
                lanes
              );
            if (getIteratorFn(newChild)) {
              key = getIteratorFn(newChild);
              if ("function" !== typeof key)
                throw Error(formatProdErrorMessage(150));
              newChild = key.call(newChild);
              return reconcileChildrenIterator(
                returnFiber,
                currentFirstChild,
                newChild,
                lanes
              );
            }
            if ("function" === typeof newChild.then)
              return reconcileChildFibersImpl(
                returnFiber,
                currentFirstChild,
                unwrapThenable(newChild),
                lanes
              );
            if (newChild.$$typeof === REACT_CONTEXT_TYPE)
              return reconcileChildFibersImpl(
                returnFiber,
                currentFirstChild,
                readContextDuringReconciliation(returnFiber, newChild),
                lanes
              );
            throwOnInvalidObjectType(returnFiber, newChild);
          }
          return "string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild ? (newChild = "" + newChild, null !== currentFirstChild && 6 === currentFirstChild.tag ? (deleteRemainingChildren(returnFiber, currentFirstChild.sibling), lanes = useFiber(currentFirstChild, newChild), lanes.return = returnFiber, returnFiber = lanes) : (deleteRemainingChildren(returnFiber, currentFirstChild), lanes = createFiberFromText(newChild, returnFiber.mode, lanes), lanes.return = returnFiber, returnFiber = lanes), placeSingleChild(returnFiber)) : deleteRemainingChildren(returnFiber, currentFirstChild);
        }
        __name(reconcileChildFibersImpl, "reconcileChildFibersImpl");
        return function(returnFiber, currentFirstChild, newChild, lanes) {
          try {
            thenableIndexCounter = 0;
            var firstChildFiber = reconcileChildFibersImpl(
              returnFiber,
              currentFirstChild,
              newChild,
              lanes
            );
            thenableState = null;
            return firstChildFiber;
          } catch (x) {
            if (x === SuspenseException || x === SuspenseActionException) throw x;
            var fiber = createFiber(29, x, null, returnFiber.mode);
            fiber.lanes = lanes;
            fiber.return = returnFiber;
            return fiber;
          } finally {
          }
        };
      }
      __name(createChildReconciler, "createChildReconciler");
      function pushPrimaryTreeSuspenseHandler(handler) {
        var current = handler.alternate;
        push2(suspenseStackCursor, suspenseStackCursor.current & 1);
        push2(suspenseHandlerStackCursor, handler);
        null === shellBoundary && (null === current || null !== currentTreeHiddenStackCursor.current ? shellBoundary = handler : null !== current.memoizedState && (shellBoundary = handler));
      }
      __name(pushPrimaryTreeSuspenseHandler, "pushPrimaryTreeSuspenseHandler");
      function pushOffscreenSuspenseHandler(fiber) {
        if (22 === fiber.tag) {
          if (push2(suspenseStackCursor, suspenseStackCursor.current), push2(suspenseHandlerStackCursor, fiber), null === shellBoundary) {
            var current = fiber.alternate;
            null !== current && null !== current.memoizedState && (shellBoundary = fiber);
          }
        } else reuseSuspenseHandlerOnStack(fiber);
      }
      __name(pushOffscreenSuspenseHandler, "pushOffscreenSuspenseHandler");
      function reuseSuspenseHandlerOnStack() {
        push2(suspenseStackCursor, suspenseStackCursor.current);
        push2(suspenseHandlerStackCursor, suspenseHandlerStackCursor.current);
      }
      __name(reuseSuspenseHandlerOnStack, "reuseSuspenseHandlerOnStack");
      function popSuspenseHandler(fiber) {
        pop(suspenseHandlerStackCursor);
        shellBoundary === fiber && (shellBoundary = null);
        pop(suspenseStackCursor);
      }
      __name(popSuspenseHandler, "popSuspenseHandler");
      function findFirstSuspended(row) {
        for (var node = row; null !== node; ) {
          if (13 === node.tag) {
            var state = node.memoizedState;
            if (null !== state && (state = state.dehydrated, null === state || isSuspenseInstancePending(state) || isSuspenseInstanceFallback(state)))
              return node;
          } else if (19 === node.tag && void 0 !== node.memoizedProps.revealOrder) {
            if (0 !== (node.flags & 128)) return node;
          } else if (null !== node.child) {
            node.child.return = node;
            node = node.child;
            continue;
          }
          if (node === row) break;
          for (; null === node.sibling; ) {
            if (null === node.return || node.return === row) return null;
            node = node.return;
          }
          node.sibling.return = node.return;
          node = node.sibling;
        }
        return null;
      }
      __name(findFirstSuspended, "findFirstSuspended");
      function applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, nextProps) {
        ctor = workInProgress2.memoizedState;
        getDerivedStateFromProps = getDerivedStateFromProps(nextProps, ctor);
        getDerivedStateFromProps = null === getDerivedStateFromProps || void 0 === getDerivedStateFromProps ? ctor : assign({}, ctor, getDerivedStateFromProps);
        workInProgress2.memoizedState = getDerivedStateFromProps;
        0 === workInProgress2.lanes && (workInProgress2.updateQueue.baseState = getDerivedStateFromProps);
      }
      __name(applyDerivedStateFromProps, "applyDerivedStateFromProps");
      function checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) {
        workInProgress2 = workInProgress2.stateNode;
        return "function" === typeof workInProgress2.shouldComponentUpdate ? workInProgress2.shouldComponentUpdate(newProps, newState, nextContext) : ctor.prototype && ctor.prototype.isPureReactComponent ? !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState) : true;
      }
      __name(checkShouldComponentUpdate, "checkShouldComponentUpdate");
      function callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext) {
        workInProgress2 = instance.state;
        "function" === typeof instance.componentWillReceiveProps && instance.componentWillReceiveProps(newProps, nextContext);
        "function" === typeof instance.UNSAFE_componentWillReceiveProps && instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
        instance.state !== workInProgress2 && classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
      }
      __name(callComponentWillReceiveProps, "callComponentWillReceiveProps");
      function resolveClassComponentProps(Component, baseProps) {
        var newProps = baseProps;
        if ("ref" in baseProps) {
          newProps = {};
          for (var propName in baseProps)
            "ref" !== propName && (newProps[propName] = baseProps[propName]);
        }
        if (Component = Component.defaultProps) {
          newProps === baseProps && (newProps = assign({}, newProps));
          for (var propName$57 in Component)
            void 0 === newProps[propName$57] && (newProps[propName$57] = Component[propName$57]);
        }
        return newProps;
      }
      __name(resolveClassComponentProps, "resolveClassComponentProps");
      function logUncaughtError(root, errorInfo) {
        try {
          var onUncaughtError = root.onUncaughtError;
          onUncaughtError(errorInfo.value, { componentStack: errorInfo.stack });
        } catch (e2) {
          setTimeout(function() {
            throw e2;
          });
        }
      }
      __name(logUncaughtError, "logUncaughtError");
      function logCaughtError(root, boundary, errorInfo) {
        try {
          var onCaughtError = root.onCaughtError;
          onCaughtError(errorInfo.value, {
            componentStack: errorInfo.stack,
            errorBoundary: 1 === boundary.tag ? boundary.stateNode : null
          });
        } catch (e2) {
          setTimeout(function() {
            throw e2;
          });
        }
      }
      __name(logCaughtError, "logCaughtError");
      function createRootErrorUpdate(root, errorInfo, lane) {
        lane = createUpdate(lane);
        lane.tag = 3;
        lane.payload = { element: null };
        lane.callback = function() {
          logUncaughtError(root, errorInfo);
        };
        return lane;
      }
      __name(createRootErrorUpdate, "createRootErrorUpdate");
      function createClassErrorUpdate(lane) {
        lane = createUpdate(lane);
        lane.tag = 3;
        return lane;
      }
      __name(createClassErrorUpdate, "createClassErrorUpdate");
      function initializeClassErrorUpdate(update2, root, fiber, errorInfo) {
        var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
        if ("function" === typeof getDerivedStateFromError) {
          var error = errorInfo.value;
          update2.payload = function() {
            return getDerivedStateFromError(error);
          };
          update2.callback = function() {
            logCaughtError(root, fiber, errorInfo);
          };
        }
        var inst = fiber.stateNode;
        null !== inst && "function" === typeof inst.componentDidCatch && (update2.callback = function() {
          logCaughtError(root, fiber, errorInfo);
          "function" !== typeof getDerivedStateFromError && (null === legacyErrorBoundariesThatAlreadyFailed ? legacyErrorBoundariesThatAlreadyFailed = /* @__PURE__ */ new Set([this]) : legacyErrorBoundariesThatAlreadyFailed.add(this));
          var stack = errorInfo.stack;
          this.componentDidCatch(errorInfo.value, {
            componentStack: null !== stack ? stack : ""
          });
        });
      }
      __name(initializeClassErrorUpdate, "initializeClassErrorUpdate");
      function throwException(root, returnFiber, sourceFiber, value, rootRenderLanes) {
        sourceFiber.flags |= 32768;
        if (null !== value && "object" === typeof value && "function" === typeof value.then) {
          returnFiber = sourceFiber.alternate;
          null !== returnFiber && propagateParentContextChanges(
            returnFiber,
            sourceFiber,
            rootRenderLanes,
            true
          );
          sourceFiber = suspenseHandlerStackCursor.current;
          if (null !== sourceFiber) {
            switch (sourceFiber.tag) {
              case 13:
                return null === shellBoundary ? renderDidSuspendDelayIfPossible() : null === sourceFiber.alternate && 0 === workInProgressRootExitStatus && (workInProgressRootExitStatus = 3), sourceFiber.flags &= -257, sourceFiber.flags |= 65536, sourceFiber.lanes = rootRenderLanes, value === noopSuspenseyCommitThenable ? sourceFiber.flags |= 16384 : (returnFiber = sourceFiber.updateQueue, null === returnFiber ? sourceFiber.updateQueue = /* @__PURE__ */ new Set([value]) : returnFiber.add(value), attachPingListener(root, value, rootRenderLanes)), false;
              case 22:
                return sourceFiber.flags |= 65536, value === noopSuspenseyCommitThenable ? sourceFiber.flags |= 16384 : (returnFiber = sourceFiber.updateQueue, null === returnFiber ? (returnFiber = {
                  transitions: null,
                  markerInstances: null,
                  retryQueue: /* @__PURE__ */ new Set([value])
                }, sourceFiber.updateQueue = returnFiber) : (sourceFiber = returnFiber.retryQueue, null === sourceFiber ? returnFiber.retryQueue = /* @__PURE__ */ new Set([value]) : sourceFiber.add(value)), attachPingListener(root, value, rootRenderLanes)), false;
            }
            throw Error(formatProdErrorMessage(435, sourceFiber.tag));
          }
          attachPingListener(root, value, rootRenderLanes);
          renderDidSuspendDelayIfPossible();
          return false;
        }
        if (isHydrating)
          return returnFiber = suspenseHandlerStackCursor.current, null !== returnFiber ? (0 === (returnFiber.flags & 65536) && (returnFiber.flags |= 256), returnFiber.flags |= 65536, returnFiber.lanes = rootRenderLanes, value !== HydrationMismatchException && (root = Error(formatProdErrorMessage(422), { cause: value }), queueHydrationError(
            createCapturedValueAtFiber(root, sourceFiber)
          ))) : (value !== HydrationMismatchException && (returnFiber = Error(formatProdErrorMessage(423), {
            cause: value
          }), queueHydrationError(
            createCapturedValueAtFiber(returnFiber, sourceFiber)
          )), root = root.current.alternate, root.flags |= 65536, rootRenderLanes &= -rootRenderLanes, root.lanes |= rootRenderLanes, value = createCapturedValueAtFiber(value, sourceFiber), rootRenderLanes = createRootErrorUpdate(
            root.stateNode,
            value,
            rootRenderLanes
          ), enqueueCapturedUpdate(root, rootRenderLanes), 4 !== workInProgressRootExitStatus && (workInProgressRootExitStatus = 2)), false;
        var wrapperError = Error(formatProdErrorMessage(520), { cause: value });
        wrapperError = createCapturedValueAtFiber(wrapperError, sourceFiber);
        null === workInProgressRootConcurrentErrors ? workInProgressRootConcurrentErrors = [wrapperError] : workInProgressRootConcurrentErrors.push(wrapperError);
        4 !== workInProgressRootExitStatus && (workInProgressRootExitStatus = 2);
        if (null === returnFiber) return true;
        value = createCapturedValueAtFiber(value, sourceFiber);
        sourceFiber = returnFiber;
        do {
          switch (sourceFiber.tag) {
            case 3:
              return sourceFiber.flags |= 65536, root = rootRenderLanes & -rootRenderLanes, sourceFiber.lanes |= root, root = createRootErrorUpdate(sourceFiber.stateNode, value, root), enqueueCapturedUpdate(sourceFiber, root), false;
            case 1:
              if (returnFiber = sourceFiber.type, wrapperError = sourceFiber.stateNode, 0 === (sourceFiber.flags & 128) && ("function" === typeof returnFiber.getDerivedStateFromError || null !== wrapperError && "function" === typeof wrapperError.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(
                wrapperError
              ))))
                return sourceFiber.flags |= 65536, rootRenderLanes &= -rootRenderLanes, sourceFiber.lanes |= rootRenderLanes, rootRenderLanes = createClassErrorUpdate(rootRenderLanes), initializeClassErrorUpdate(
                  rootRenderLanes,
                  root,
                  sourceFiber,
                  value
                ), enqueueCapturedUpdate(sourceFiber, rootRenderLanes), false;
          }
          sourceFiber = sourceFiber.return;
        } while (null !== sourceFiber);
        return false;
      }
      __name(throwException, "throwException");
      function reconcileChildren(current, workInProgress2, nextChildren, renderLanes2) {
        workInProgress2.child = null === current ? mountChildFibers(workInProgress2, null, nextChildren, renderLanes2) : reconcileChildFibers(
          workInProgress2,
          current.child,
          nextChildren,
          renderLanes2
        );
      }
      __name(reconcileChildren, "reconcileChildren");
      function updateForwardRef(current, workInProgress2, Component, nextProps, renderLanes2) {
        Component = Component.render;
        var ref = workInProgress2.ref;
        if ("ref" in nextProps) {
          var propsWithoutRef = {};
          for (var key in nextProps)
            "ref" !== key && (propsWithoutRef[key] = nextProps[key]);
        } else propsWithoutRef = nextProps;
        prepareToReadContext(workInProgress2);
        nextProps = renderWithHooks(
          current,
          workInProgress2,
          Component,
          propsWithoutRef,
          ref,
          renderLanes2
        );
        key = checkDidRenderIdHook();
        if (null !== current && !didReceiveUpdate)
          return bailoutHooks(current, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
        isHydrating && key && pushMaterializedTreeId(workInProgress2);
        workInProgress2.flags |= 1;
        reconcileChildren(current, workInProgress2, nextProps, renderLanes2);
        return workInProgress2.child;
      }
      __name(updateForwardRef, "updateForwardRef");
      function updateMemoComponent(current, workInProgress2, Component, nextProps, renderLanes2) {
        if (null === current) {
          var type = Component.type;
          if ("function" === typeof type && !shouldConstruct(type) && void 0 === type.defaultProps && null === Component.compare)
            return workInProgress2.tag = 15, workInProgress2.type = type, updateSimpleMemoComponent(
              current,
              workInProgress2,
              type,
              nextProps,
              renderLanes2
            );
          current = createFiberFromTypeAndProps(
            Component.type,
            null,
            nextProps,
            workInProgress2,
            workInProgress2.mode,
            renderLanes2
          );
          current.ref = workInProgress2.ref;
          current.return = workInProgress2;
          return workInProgress2.child = current;
        }
        type = current.child;
        if (!checkScheduledUpdateOrContext(current, renderLanes2)) {
          var prevProps = type.memoizedProps;
          Component = Component.compare;
          Component = null !== Component ? Component : shallowEqual;
          if (Component(prevProps, nextProps) && current.ref === workInProgress2.ref)
            return bailoutOnAlreadyFinishedWork(
              current,
              workInProgress2,
              renderLanes2
            );
        }
        workInProgress2.flags |= 1;
        current = createWorkInProgress(type, nextProps);
        current.ref = workInProgress2.ref;
        current.return = workInProgress2;
        return workInProgress2.child = current;
      }
      __name(updateMemoComponent, "updateMemoComponent");
      function updateSimpleMemoComponent(current, workInProgress2, Component, nextProps, renderLanes2) {
        if (null !== current) {
          var prevProps = current.memoizedProps;
          if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress2.ref)
            if (didReceiveUpdate = false, workInProgress2.pendingProps = nextProps = prevProps, checkScheduledUpdateOrContext(current, renderLanes2))
              0 !== (current.flags & 131072) && (didReceiveUpdate = true);
            else
              return workInProgress2.lanes = current.lanes, bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
        }
        return updateFunctionComponent(
          current,
          workInProgress2,
          Component,
          nextProps,
          renderLanes2
        );
      }
      __name(updateSimpleMemoComponent, "updateSimpleMemoComponent");
      function updateOffscreenComponent(current, workInProgress2, renderLanes2) {
        var nextProps = workInProgress2.pendingProps, nextChildren = nextProps.children, prevState = null !== current ? current.memoizedState : null;
        if ("hidden" === nextProps.mode) {
          if (0 !== (workInProgress2.flags & 128)) {
            nextProps = null !== prevState ? prevState.baseLanes | renderLanes2 : renderLanes2;
            if (null !== current) {
              nextChildren = workInProgress2.child = current.child;
              for (prevState = 0; null !== nextChildren; )
                prevState = prevState | nextChildren.lanes | nextChildren.childLanes, nextChildren = nextChildren.sibling;
              workInProgress2.childLanes = prevState & ~nextProps;
            } else workInProgress2.childLanes = 0, workInProgress2.child = null;
            return deferHiddenOffscreenComponent(
              current,
              workInProgress2,
              nextProps,
              renderLanes2
            );
          }
          if (0 !== (renderLanes2 & 536870912))
            workInProgress2.memoizedState = { baseLanes: 0, cachePool: null }, null !== current && pushTransition(
              workInProgress2,
              null !== prevState ? prevState.cachePool : null
            ), null !== prevState ? pushHiddenContext(workInProgress2, prevState) : reuseHiddenContextOnStack(), pushOffscreenSuspenseHandler(workInProgress2);
          else
            return workInProgress2.lanes = workInProgress2.childLanes = 536870912, deferHiddenOffscreenComponent(
              current,
              workInProgress2,
              null !== prevState ? prevState.baseLanes | renderLanes2 : renderLanes2,
              renderLanes2
            );
        } else
          null !== prevState ? (pushTransition(workInProgress2, prevState.cachePool), pushHiddenContext(workInProgress2, prevState), reuseSuspenseHandlerOnStack(workInProgress2), workInProgress2.memoizedState = null) : (null !== current && pushTransition(workInProgress2, null), reuseHiddenContextOnStack(), reuseSuspenseHandlerOnStack(workInProgress2));
        reconcileChildren(current, workInProgress2, nextChildren, renderLanes2);
        return workInProgress2.child;
      }
      __name(updateOffscreenComponent, "updateOffscreenComponent");
      function deferHiddenOffscreenComponent(current, workInProgress2, nextBaseLanes, renderLanes2) {
        var JSCompiler_inline_result = peekCacheFromPool();
        JSCompiler_inline_result = null === JSCompiler_inline_result ? null : {
          parent: isPrimaryRenderer ? CacheContext._currentValue : CacheContext._currentValue2,
          pool: JSCompiler_inline_result
        };
        workInProgress2.memoizedState = {
          baseLanes: nextBaseLanes,
          cachePool: JSCompiler_inline_result
        };
        null !== current && pushTransition(workInProgress2, null);
        reuseHiddenContextOnStack();
        pushOffscreenSuspenseHandler(workInProgress2);
        null !== current && propagateParentContextChanges(current, workInProgress2, renderLanes2, true);
        return null;
      }
      __name(deferHiddenOffscreenComponent, "deferHiddenOffscreenComponent");
      function markRef(current, workInProgress2) {
        var ref = workInProgress2.ref;
        if (null === ref)
          null !== current && null !== current.ref && (workInProgress2.flags |= 4194816);
        else {
          if ("function" !== typeof ref && "object" !== typeof ref)
            throw Error(formatProdErrorMessage(284));
          if (null === current || current.ref !== ref)
            workInProgress2.flags |= 4194816;
        }
      }
      __name(markRef, "markRef");
      function updateFunctionComponent(current, workInProgress2, Component, nextProps, renderLanes2) {
        prepareToReadContext(workInProgress2);
        Component = renderWithHooks(
          current,
          workInProgress2,
          Component,
          nextProps,
          void 0,
          renderLanes2
        );
        nextProps = checkDidRenderIdHook();
        if (null !== current && !didReceiveUpdate)
          return bailoutHooks(current, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
        isHydrating && nextProps && pushMaterializedTreeId(workInProgress2);
        workInProgress2.flags |= 1;
        reconcileChildren(current, workInProgress2, Component, renderLanes2);
        return workInProgress2.child;
      }
      __name(updateFunctionComponent, "updateFunctionComponent");
      function replayFunctionComponent(current, workInProgress2, nextProps, Component, secondArg, renderLanes2) {
        prepareToReadContext(workInProgress2);
        workInProgress2.updateQueue = null;
        nextProps = renderWithHooksAgain(
          workInProgress2,
          Component,
          nextProps,
          secondArg
        );
        finishRenderingHooks(current);
        Component = checkDidRenderIdHook();
        if (null !== current && !didReceiveUpdate)
          return bailoutHooks(current, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
        isHydrating && Component && pushMaterializedTreeId(workInProgress2);
        workInProgress2.flags |= 1;
        reconcileChildren(current, workInProgress2, nextProps, renderLanes2);
        return workInProgress2.child;
      }
      __name(replayFunctionComponent, "replayFunctionComponent");
      function updateClassComponent(current, workInProgress2, Component, nextProps, renderLanes2) {
        prepareToReadContext(workInProgress2);
        if (null === workInProgress2.stateNode) {
          var context2 = emptyContextObject, contextType = Component.contextType;
          "object" === typeof contextType && null !== contextType && (context2 = readContext(contextType));
          context2 = new Component(nextProps, context2);
          workInProgress2.memoizedState = null !== context2.state && void 0 !== context2.state ? context2.state : null;
          context2.updater = classComponentUpdater;
          workInProgress2.stateNode = context2;
          context2._reactInternals = workInProgress2;
          context2 = workInProgress2.stateNode;
          context2.props = nextProps;
          context2.state = workInProgress2.memoizedState;
          context2.refs = {};
          initializeUpdateQueue(workInProgress2);
          contextType = Component.contextType;
          context2.context = "object" === typeof contextType && null !== contextType ? readContext(contextType) : emptyContextObject;
          context2.state = workInProgress2.memoizedState;
          contextType = Component.getDerivedStateFromProps;
          "function" === typeof contextType && (applyDerivedStateFromProps(
            workInProgress2,
            Component,
            contextType,
            nextProps
          ), context2.state = workInProgress2.memoizedState);
          "function" === typeof Component.getDerivedStateFromProps || "function" === typeof context2.getSnapshotBeforeUpdate || "function" !== typeof context2.UNSAFE_componentWillMount && "function" !== typeof context2.componentWillMount || (contextType = context2.state, "function" === typeof context2.componentWillMount && context2.componentWillMount(), "function" === typeof context2.UNSAFE_componentWillMount && context2.UNSAFE_componentWillMount(), contextType !== context2.state && classComponentUpdater.enqueueReplaceState(
            context2,
            context2.state,
            null
          ), processUpdateQueue(workInProgress2, nextProps, context2, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction(), context2.state = workInProgress2.memoizedState);
          "function" === typeof context2.componentDidMount && (workInProgress2.flags |= 4194308);
          nextProps = true;
        } else if (null === current) {
          context2 = workInProgress2.stateNode;
          var unresolvedOldProps = workInProgress2.memoizedProps, oldProps = resolveClassComponentProps(Component, unresolvedOldProps);
          context2.props = oldProps;
          var oldContext = context2.context, contextType$jscomp$0 = Component.contextType;
          contextType = emptyContextObject;
          "object" === typeof contextType$jscomp$0 && null !== contextType$jscomp$0 && (contextType = readContext(contextType$jscomp$0));
          var getDerivedStateFromProps = Component.getDerivedStateFromProps;
          contextType$jscomp$0 = "function" === typeof getDerivedStateFromProps || "function" === typeof context2.getSnapshotBeforeUpdate;
          unresolvedOldProps = workInProgress2.pendingProps !== unresolvedOldProps;
          contextType$jscomp$0 || "function" !== typeof context2.UNSAFE_componentWillReceiveProps && "function" !== typeof context2.componentWillReceiveProps || (unresolvedOldProps || oldContext !== contextType) && callComponentWillReceiveProps(
            workInProgress2,
            context2,
            nextProps,
            contextType
          );
          hasForceUpdate = false;
          var oldState = workInProgress2.memoizedState;
          context2.state = oldState;
          processUpdateQueue(workInProgress2, nextProps, context2, renderLanes2);
          suspendIfUpdateReadFromEntangledAsyncAction();
          oldContext = workInProgress2.memoizedState;
          unresolvedOldProps || oldState !== oldContext || hasForceUpdate ? ("function" === typeof getDerivedStateFromProps && (applyDerivedStateFromProps(
            workInProgress2,
            Component,
            getDerivedStateFromProps,
            nextProps
          ), oldContext = workInProgress2.memoizedState), (oldProps = hasForceUpdate || checkShouldComponentUpdate(
            workInProgress2,
            Component,
            oldProps,
            nextProps,
            oldState,
            oldContext,
            contextType
          )) ? (contextType$jscomp$0 || "function" !== typeof context2.UNSAFE_componentWillMount && "function" !== typeof context2.componentWillMount || ("function" === typeof context2.componentWillMount && context2.componentWillMount(), "function" === typeof context2.UNSAFE_componentWillMount && context2.UNSAFE_componentWillMount()), "function" === typeof context2.componentDidMount && (workInProgress2.flags |= 4194308)) : ("function" === typeof context2.componentDidMount && (workInProgress2.flags |= 4194308), workInProgress2.memoizedProps = nextProps, workInProgress2.memoizedState = oldContext), context2.props = nextProps, context2.state = oldContext, context2.context = contextType, nextProps = oldProps) : ("function" === typeof context2.componentDidMount && (workInProgress2.flags |= 4194308), nextProps = false);
        } else {
          context2 = workInProgress2.stateNode;
          cloneUpdateQueue(current, workInProgress2);
          contextType = workInProgress2.memoizedProps;
          contextType$jscomp$0 = resolveClassComponentProps(Component, contextType);
          context2.props = contextType$jscomp$0;
          getDerivedStateFromProps = workInProgress2.pendingProps;
          oldState = context2.context;
          oldContext = Component.contextType;
          oldProps = emptyContextObject;
          "object" === typeof oldContext && null !== oldContext && (oldProps = readContext(oldContext));
          unresolvedOldProps = Component.getDerivedStateFromProps;
          (oldContext = "function" === typeof unresolvedOldProps || "function" === typeof context2.getSnapshotBeforeUpdate) || "function" !== typeof context2.UNSAFE_componentWillReceiveProps && "function" !== typeof context2.componentWillReceiveProps || (contextType !== getDerivedStateFromProps || oldState !== oldProps) && callComponentWillReceiveProps(
            workInProgress2,
            context2,
            nextProps,
            oldProps
          );
          hasForceUpdate = false;
          oldState = workInProgress2.memoizedState;
          context2.state = oldState;
          processUpdateQueue(workInProgress2, nextProps, context2, renderLanes2);
          suspendIfUpdateReadFromEntangledAsyncAction();
          var newState = workInProgress2.memoizedState;
          contextType !== getDerivedStateFromProps || oldState !== newState || hasForceUpdate || null !== current && null !== current.dependencies && checkIfContextChanged(current.dependencies) ? ("function" === typeof unresolvedOldProps && (applyDerivedStateFromProps(
            workInProgress2,
            Component,
            unresolvedOldProps,
            nextProps
          ), newState = workInProgress2.memoizedState), (contextType$jscomp$0 = hasForceUpdate || checkShouldComponentUpdate(
            workInProgress2,
            Component,
            contextType$jscomp$0,
            nextProps,
            oldState,
            newState,
            oldProps
          ) || null !== current && null !== current.dependencies && checkIfContextChanged(current.dependencies)) ? (oldContext || "function" !== typeof context2.UNSAFE_componentWillUpdate && "function" !== typeof context2.componentWillUpdate || ("function" === typeof context2.componentWillUpdate && context2.componentWillUpdate(nextProps, newState, oldProps), "function" === typeof context2.UNSAFE_componentWillUpdate && context2.UNSAFE_componentWillUpdate(
            nextProps,
            newState,
            oldProps
          )), "function" === typeof context2.componentDidUpdate && (workInProgress2.flags |= 4), "function" === typeof context2.getSnapshotBeforeUpdate && (workInProgress2.flags |= 1024)) : ("function" !== typeof context2.componentDidUpdate || contextType === current.memoizedProps && oldState === current.memoizedState || (workInProgress2.flags |= 4), "function" !== typeof context2.getSnapshotBeforeUpdate || contextType === current.memoizedProps && oldState === current.memoizedState || (workInProgress2.flags |= 1024), workInProgress2.memoizedProps = nextProps, workInProgress2.memoizedState = newState), context2.props = nextProps, context2.state = newState, context2.context = oldProps, nextProps = contextType$jscomp$0) : ("function" !== typeof context2.componentDidUpdate || contextType === current.memoizedProps && oldState === current.memoizedState || (workInProgress2.flags |= 4), "function" !== typeof context2.getSnapshotBeforeUpdate || contextType === current.memoizedProps && oldState === current.memoizedState || (workInProgress2.flags |= 1024), nextProps = false);
        }
        context2 = nextProps;
        markRef(current, workInProgress2);
        nextProps = 0 !== (workInProgress2.flags & 128);
        context2 || nextProps ? (context2 = workInProgress2.stateNode, Component = nextProps && "function" !== typeof Component.getDerivedStateFromError ? null : context2.render(), workInProgress2.flags |= 1, null !== current && nextProps ? (workInProgress2.child = reconcileChildFibers(
          workInProgress2,
          current.child,
          null,
          renderLanes2
        ), workInProgress2.child = reconcileChildFibers(
          workInProgress2,
          null,
          Component,
          renderLanes2
        )) : reconcileChildren(current, workInProgress2, Component, renderLanes2), workInProgress2.memoizedState = context2.state, current = workInProgress2.child) : current = bailoutOnAlreadyFinishedWork(
          current,
          workInProgress2,
          renderLanes2
        );
        return current;
      }
      __name(updateClassComponent, "updateClassComponent");
      function mountHostRootWithoutHydrating(current, workInProgress2, nextChildren, renderLanes2) {
        resetHydrationState();
        workInProgress2.flags |= 256;
        reconcileChildren(current, workInProgress2, nextChildren, renderLanes2);
        return workInProgress2.child;
      }
      __name(mountHostRootWithoutHydrating, "mountHostRootWithoutHydrating");
      function mountSuspenseOffscreenState(renderLanes2) {
        return { baseLanes: renderLanes2, cachePool: getSuspendedCache() };
      }
      __name(mountSuspenseOffscreenState, "mountSuspenseOffscreenState");
      function getRemainingWorkInPrimaryTree(current, primaryTreeDidDefer, renderLanes2) {
        current = null !== current ? current.childLanes & ~renderLanes2 : 0;
        primaryTreeDidDefer && (current |= workInProgressDeferredLane);
        return current;
      }
      __name(getRemainingWorkInPrimaryTree, "getRemainingWorkInPrimaryTree");
      function updateSuspenseComponent(current, workInProgress2, renderLanes2) {
        var nextProps = workInProgress2.pendingProps, showFallback = false, didSuspend = 0 !== (workInProgress2.flags & 128), JSCompiler_temp;
        (JSCompiler_temp = didSuspend) || (JSCompiler_temp = null !== current && null === current.memoizedState ? false : 0 !== (suspenseStackCursor.current & 2));
        JSCompiler_temp && (showFallback = true, workInProgress2.flags &= -129);
        JSCompiler_temp = 0 !== (workInProgress2.flags & 32);
        workInProgress2.flags &= -33;
        if (null === current) {
          if (isHydrating) {
            showFallback ? pushPrimaryTreeSuspenseHandler(workInProgress2) : reuseSuspenseHandlerOnStack(workInProgress2);
            if (isHydrating) {
              var nextInstance = nextHydratableInstance, JSCompiler_temp$jscomp$0;
              if (JSCompiler_temp$jscomp$0 = nextInstance)
                nextInstance = canHydrateSuspenseInstance(
                  nextInstance,
                  rootOrSingletonContext
                ), null !== nextInstance ? (workInProgress2.memoizedState = {
                  dehydrated: nextInstance,
                  treeContext: null !== treeContextProvider ? { id: treeContextId, overflow: treeContextOverflow } : null,
                  retryLane: 536870912,
                  hydrationErrors: null
                }, JSCompiler_temp$jscomp$0 = createFiber(18, null, null, 0), JSCompiler_temp$jscomp$0.stateNode = nextInstance, JSCompiler_temp$jscomp$0.return = workInProgress2, workInProgress2.child = JSCompiler_temp$jscomp$0, hydrationParentFiber = workInProgress2, nextHydratableInstance = null, JSCompiler_temp$jscomp$0 = true) : JSCompiler_temp$jscomp$0 = false;
              JSCompiler_temp$jscomp$0 || throwOnHydrationMismatch(workInProgress2);
            }
            nextInstance = workInProgress2.memoizedState;
            if (null !== nextInstance && (nextInstance = nextInstance.dehydrated, null !== nextInstance))
              return isSuspenseInstanceFallback(nextInstance) ? workInProgress2.lanes = 32 : workInProgress2.lanes = 536870912, null;
            popSuspenseHandler(workInProgress2);
          }
          nextInstance = nextProps.children;
          nextProps = nextProps.fallback;
          if (showFallback)
            return reuseSuspenseHandlerOnStack(workInProgress2), showFallback = workInProgress2.mode, nextInstance = mountWorkInProgressOffscreenFiber(
              { mode: "hidden", children: nextInstance },
              showFallback
            ), nextProps = createFiberFromFragment(
              nextProps,
              showFallback,
              renderLanes2,
              null
            ), nextInstance.return = workInProgress2, nextProps.return = workInProgress2, nextInstance.sibling = nextProps, workInProgress2.child = nextInstance, showFallback = workInProgress2.child, showFallback.memoizedState = mountSuspenseOffscreenState(renderLanes2), showFallback.childLanes = getRemainingWorkInPrimaryTree(
              current,
              JSCompiler_temp,
              renderLanes2
            ), workInProgress2.memoizedState = SUSPENDED_MARKER, nextProps;
          pushPrimaryTreeSuspenseHandler(workInProgress2);
          return mountSuspensePrimaryChildren(workInProgress2, nextInstance);
        }
        JSCompiler_temp$jscomp$0 = current.memoizedState;
        if (null !== JSCompiler_temp$jscomp$0 && (nextInstance = JSCompiler_temp$jscomp$0.dehydrated, null !== nextInstance)) {
          if (didSuspend)
            workInProgress2.flags & 256 ? (pushPrimaryTreeSuspenseHandler(workInProgress2), workInProgress2.flags &= -257, workInProgress2 = retrySuspenseComponentWithoutHydrating(
              current,
              workInProgress2,
              renderLanes2
            )) : null !== workInProgress2.memoizedState ? (reuseSuspenseHandlerOnStack(workInProgress2), workInProgress2.child = current.child, workInProgress2.flags |= 128, workInProgress2 = null) : (reuseSuspenseHandlerOnStack(workInProgress2), showFallback = nextProps.fallback, nextInstance = workInProgress2.mode, nextProps = mountWorkInProgressOffscreenFiber(
              { mode: "visible", children: nextProps.children },
              nextInstance
            ), showFallback = createFiberFromFragment(
              showFallback,
              nextInstance,
              renderLanes2,
              null
            ), showFallback.flags |= 2, nextProps.return = workInProgress2, showFallback.return = workInProgress2, nextProps.sibling = showFallback, workInProgress2.child = nextProps, reconcileChildFibers(
              workInProgress2,
              current.child,
              null,
              renderLanes2
            ), nextProps = workInProgress2.child, nextProps.memoizedState = mountSuspenseOffscreenState(renderLanes2), nextProps.childLanes = getRemainingWorkInPrimaryTree(
              current,
              JSCompiler_temp,
              renderLanes2
            ), workInProgress2.memoizedState = SUSPENDED_MARKER, workInProgress2 = showFallback);
          else if (pushPrimaryTreeSuspenseHandler(workInProgress2), isSuspenseInstanceFallback(nextInstance))
            JSCompiler_temp = getSuspenseInstanceFallbackErrorDetails(nextInstance).digest, nextProps = Error(formatProdErrorMessage(419)), nextProps.stack = "", nextProps.digest = JSCompiler_temp, queueHydrationError({ value: nextProps, source: null, stack: null }), workInProgress2 = retrySuspenseComponentWithoutHydrating(
              current,
              workInProgress2,
              renderLanes2
            );
          else if (didReceiveUpdate || propagateParentContextChanges(
            current,
            workInProgress2,
            renderLanes2,
            false
          ), JSCompiler_temp = 0 !== (renderLanes2 & current.childLanes), didReceiveUpdate || JSCompiler_temp) {
            JSCompiler_temp = workInProgressRoot;
            if (null !== JSCompiler_temp && (nextProps = renderLanes2 & -renderLanes2, nextProps = 0 !== (nextProps & 42) ? 1 : getBumpedLaneForHydrationByLane(nextProps), nextProps = 0 !== (nextProps & (JSCompiler_temp.suspendedLanes | renderLanes2)) ? 0 : nextProps, 0 !== nextProps && nextProps !== JSCompiler_temp$jscomp$0.retryLane))
              throw JSCompiler_temp$jscomp$0.retryLane = nextProps, enqueueConcurrentRenderForLane(current, nextProps), scheduleUpdateOnFiber(JSCompiler_temp, current, nextProps), SelectiveHydrationException;
            isSuspenseInstancePending(nextInstance) || renderDidSuspendDelayIfPossible();
            workInProgress2 = retrySuspenseComponentWithoutHydrating(
              current,
              workInProgress2,
              renderLanes2
            );
          } else
            isSuspenseInstancePending(nextInstance) ? (workInProgress2.flags |= 192, workInProgress2.child = current.child, workInProgress2 = null) : (current = JSCompiler_temp$jscomp$0.treeContext, supportsHydration && (nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(nextInstance), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, rootOrSingletonContext = false, null !== current && (idStack[idStackIndex++] = treeContextId, idStack[idStackIndex++] = treeContextOverflow, idStack[idStackIndex++] = treeContextProvider, treeContextId = current.id, treeContextOverflow = current.overflow, treeContextProvider = workInProgress2)), workInProgress2 = mountSuspensePrimaryChildren(
              workInProgress2,
              nextProps.children
            ), workInProgress2.flags |= 4096);
          return workInProgress2;
        }
        if (showFallback)
          return reuseSuspenseHandlerOnStack(workInProgress2), showFallback = nextProps.fallback, nextInstance = workInProgress2.mode, JSCompiler_temp$jscomp$0 = current.child, didSuspend = JSCompiler_temp$jscomp$0.sibling, nextProps = createWorkInProgress(JSCompiler_temp$jscomp$0, {
            mode: "hidden",
            children: nextProps.children
          }), nextProps.subtreeFlags = JSCompiler_temp$jscomp$0.subtreeFlags & 65011712, null !== didSuspend ? showFallback = createWorkInProgress(didSuspend, showFallback) : (showFallback = createFiberFromFragment(
            showFallback,
            nextInstance,
            renderLanes2,
            null
          ), showFallback.flags |= 2), showFallback.return = workInProgress2, nextProps.return = workInProgress2, nextProps.sibling = showFallback, workInProgress2.child = nextProps, nextProps = showFallback, showFallback = workInProgress2.child, nextInstance = current.child.memoizedState, null === nextInstance ? nextInstance = mountSuspenseOffscreenState(renderLanes2) : (JSCompiler_temp$jscomp$0 = nextInstance.cachePool, null !== JSCompiler_temp$jscomp$0 ? (didSuspend = isPrimaryRenderer ? CacheContext._currentValue : CacheContext._currentValue2, JSCompiler_temp$jscomp$0 = JSCompiler_temp$jscomp$0.parent !== didSuspend ? { parent: didSuspend, pool: didSuspend } : JSCompiler_temp$jscomp$0) : JSCompiler_temp$jscomp$0 = getSuspendedCache(), nextInstance = {
            baseLanes: nextInstance.baseLanes | renderLanes2,
            cachePool: JSCompiler_temp$jscomp$0
          }), showFallback.memoizedState = nextInstance, showFallback.childLanes = getRemainingWorkInPrimaryTree(
            current,
            JSCompiler_temp,
            renderLanes2
          ), workInProgress2.memoizedState = SUSPENDED_MARKER, nextProps;
        pushPrimaryTreeSuspenseHandler(workInProgress2);
        renderLanes2 = current.child;
        current = renderLanes2.sibling;
        renderLanes2 = createWorkInProgress(renderLanes2, {
          mode: "visible",
          children: nextProps.children
        });
        renderLanes2.return = workInProgress2;
        renderLanes2.sibling = null;
        null !== current && (JSCompiler_temp = workInProgress2.deletions, null === JSCompiler_temp ? (workInProgress2.deletions = [current], workInProgress2.flags |= 16) : JSCompiler_temp.push(current));
        workInProgress2.child = renderLanes2;
        workInProgress2.memoizedState = null;
        return renderLanes2;
      }
      __name(updateSuspenseComponent, "updateSuspenseComponent");
      function mountSuspensePrimaryChildren(workInProgress2, primaryChildren) {
        primaryChildren = mountWorkInProgressOffscreenFiber(
          { mode: "visible", children: primaryChildren },
          workInProgress2.mode
        );
        primaryChildren.return = workInProgress2;
        return workInProgress2.child = primaryChildren;
      }
      __name(mountSuspensePrimaryChildren, "mountSuspensePrimaryChildren");
      function mountWorkInProgressOffscreenFiber(offscreenProps, mode) {
        offscreenProps = createFiber(22, offscreenProps, null, mode);
        offscreenProps.lanes = 0;
        offscreenProps.stateNode = {
          _visibility: 1,
          _pendingMarkers: null,
          _retryCache: null,
          _transitions: null
        };
        return offscreenProps;
      }
      __name(mountWorkInProgressOffscreenFiber, "mountWorkInProgressOffscreenFiber");
      function retrySuspenseComponentWithoutHydrating(current, workInProgress2, renderLanes2) {
        reconcileChildFibers(workInProgress2, current.child, null, renderLanes2);
        current = mountSuspensePrimaryChildren(
          workInProgress2,
          workInProgress2.pendingProps.children
        );
        current.flags |= 2;
        workInProgress2.memoizedState = null;
        return current;
      }
      __name(retrySuspenseComponentWithoutHydrating, "retrySuspenseComponentWithoutHydrating");
      function scheduleSuspenseWorkOnFiber(fiber, renderLanes2, propagationRoot) {
        fiber.lanes |= renderLanes2;
        var alternate = fiber.alternate;
        null !== alternate && (alternate.lanes |= renderLanes2);
        scheduleContextWorkOnParentPath(fiber.return, renderLanes2, propagationRoot);
      }
      __name(scheduleSuspenseWorkOnFiber, "scheduleSuspenseWorkOnFiber");
      function initSuspenseListRenderState(workInProgress2, isBackwards, tail, lastContentRow, tailMode) {
        var renderState = workInProgress2.memoizedState;
        null === renderState ? workInProgress2.memoizedState = {
          isBackwards,
          rendering: null,
          renderingStartTime: 0,
          last: lastContentRow,
          tail,
          tailMode
        } : (renderState.isBackwards = isBackwards, renderState.rendering = null, renderState.renderingStartTime = 0, renderState.last = lastContentRow, renderState.tail = tail, renderState.tailMode = tailMode);
      }
      __name(initSuspenseListRenderState, "initSuspenseListRenderState");
      function updateSuspenseListComponent(current, workInProgress2, renderLanes2) {
        var nextProps = workInProgress2.pendingProps, revealOrder = nextProps.revealOrder, tailMode = nextProps.tail;
        reconcileChildren(current, workInProgress2, nextProps.children, renderLanes2);
        nextProps = suspenseStackCursor.current;
        if (0 !== (nextProps & 2))
          nextProps = nextProps & 1 | 2, workInProgress2.flags |= 128;
        else {
          if (null !== current && 0 !== (current.flags & 128))
            a: for (current = workInProgress2.child; null !== current; ) {
              if (13 === current.tag)
                null !== current.memoizedState && scheduleSuspenseWorkOnFiber(current, renderLanes2, workInProgress2);
              else if (19 === current.tag)
                scheduleSuspenseWorkOnFiber(current, renderLanes2, workInProgress2);
              else if (null !== current.child) {
                current.child.return = current;
                current = current.child;
                continue;
              }
              if (current === workInProgress2) break a;
              for (; null === current.sibling; ) {
                if (null === current.return || current.return === workInProgress2)
                  break a;
                current = current.return;
              }
              current.sibling.return = current.return;
              current = current.sibling;
            }
          nextProps &= 1;
        }
        push2(suspenseStackCursor, nextProps);
        switch (revealOrder) {
          case "forwards":
            renderLanes2 = workInProgress2.child;
            for (revealOrder = null; null !== renderLanes2; )
              current = renderLanes2.alternate, null !== current && null === findFirstSuspended(current) && (revealOrder = renderLanes2), renderLanes2 = renderLanes2.sibling;
            renderLanes2 = revealOrder;
            null === renderLanes2 ? (revealOrder = workInProgress2.child, workInProgress2.child = null) : (revealOrder = renderLanes2.sibling, renderLanes2.sibling = null);
            initSuspenseListRenderState(
              workInProgress2,
              false,
              revealOrder,
              renderLanes2,
              tailMode
            );
            break;
          case "backwards":
            renderLanes2 = null;
            revealOrder = workInProgress2.child;
            for (workInProgress2.child = null; null !== revealOrder; ) {
              current = revealOrder.alternate;
              if (null !== current && null === findFirstSuspended(current)) {
                workInProgress2.child = revealOrder;
                break;
              }
              current = revealOrder.sibling;
              revealOrder.sibling = renderLanes2;
              renderLanes2 = revealOrder;
              revealOrder = current;
            }
            initSuspenseListRenderState(
              workInProgress2,
              true,
              renderLanes2,
              null,
              tailMode
            );
            break;
          case "together":
            initSuspenseListRenderState(workInProgress2, false, null, null, void 0);
            break;
          default:
            workInProgress2.memoizedState = null;
        }
        return workInProgress2.child;
      }
      __name(updateSuspenseListComponent, "updateSuspenseListComponent");
      function bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2) {
        null !== current && (workInProgress2.dependencies = current.dependencies);
        workInProgressRootSkippedLanes |= workInProgress2.lanes;
        if (0 === (renderLanes2 & workInProgress2.childLanes))
          if (null !== current) {
            if (propagateParentContextChanges(
              current,
              workInProgress2,
              renderLanes2,
              false
            ), 0 === (renderLanes2 & workInProgress2.childLanes))
              return null;
          } else return null;
        if (null !== current && workInProgress2.child !== current.child)
          throw Error(formatProdErrorMessage(153));
        if (null !== workInProgress2.child) {
          current = workInProgress2.child;
          renderLanes2 = createWorkInProgress(current, current.pendingProps);
          workInProgress2.child = renderLanes2;
          for (renderLanes2.return = workInProgress2; null !== current.sibling; )
            current = current.sibling, renderLanes2 = renderLanes2.sibling = createWorkInProgress(current, current.pendingProps), renderLanes2.return = workInProgress2;
          renderLanes2.sibling = null;
        }
        return workInProgress2.child;
      }
      __name(bailoutOnAlreadyFinishedWork, "bailoutOnAlreadyFinishedWork");
      function checkScheduledUpdateOrContext(current, renderLanes2) {
        if (0 !== (current.lanes & renderLanes2)) return true;
        current = current.dependencies;
        return null !== current && checkIfContextChanged(current) ? true : false;
      }
      __name(checkScheduledUpdateOrContext, "checkScheduledUpdateOrContext");
      function attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress2, renderLanes2) {
        switch (workInProgress2.tag) {
          case 3:
            pushHostContainer(
              workInProgress2,
              workInProgress2.stateNode.containerInfo
            );
            pushProvider(workInProgress2, CacheContext, current.memoizedState.cache);
            resetHydrationState();
            break;
          case 27:
          case 5:
            pushHostContext(workInProgress2);
            break;
          case 4:
            pushHostContainer(
              workInProgress2,
              workInProgress2.stateNode.containerInfo
            );
            break;
          case 10:
            pushProvider(
              workInProgress2,
              workInProgress2.type,
              workInProgress2.memoizedProps.value
            );
            break;
          case 13:
            var state = workInProgress2.memoizedState;
            if (null !== state) {
              if (null !== state.dehydrated)
                return pushPrimaryTreeSuspenseHandler(workInProgress2), workInProgress2.flags |= 128, null;
              if (0 !== (renderLanes2 & workInProgress2.child.childLanes))
                return updateSuspenseComponent(
                  current,
                  workInProgress2,
                  renderLanes2
                );
              pushPrimaryTreeSuspenseHandler(workInProgress2);
              current = bailoutOnAlreadyFinishedWork(
                current,
                workInProgress2,
                renderLanes2
              );
              return null !== current ? current.sibling : null;
            }
            pushPrimaryTreeSuspenseHandler(workInProgress2);
            break;
          case 19:
            var didSuspendBefore = 0 !== (current.flags & 128);
            state = 0 !== (renderLanes2 & workInProgress2.childLanes);
            state || (propagateParentContextChanges(
              current,
              workInProgress2,
              renderLanes2,
              false
            ), state = 0 !== (renderLanes2 & workInProgress2.childLanes));
            if (didSuspendBefore) {
              if (state)
                return updateSuspenseListComponent(
                  current,
                  workInProgress2,
                  renderLanes2
                );
              workInProgress2.flags |= 128;
            }
            didSuspendBefore = workInProgress2.memoizedState;
            null !== didSuspendBefore && (didSuspendBefore.rendering = null, didSuspendBefore.tail = null, didSuspendBefore.lastEffect = null);
            push2(suspenseStackCursor, suspenseStackCursor.current);
            if (state) break;
            else return null;
          case 22:
          case 23:
            return workInProgress2.lanes = 0, updateOffscreenComponent(current, workInProgress2, renderLanes2);
          case 24:
            pushProvider(workInProgress2, CacheContext, current.memoizedState.cache);
        }
        return bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
      }
      __name(attemptEarlyBailoutIfNoScheduledUpdate, "attemptEarlyBailoutIfNoScheduledUpdate");
      function beginWork(current, workInProgress2, renderLanes2) {
        if (null !== current)
          if (current.memoizedProps !== workInProgress2.pendingProps)
            didReceiveUpdate = true;
          else {
            if (!checkScheduledUpdateOrContext(current, renderLanes2) && 0 === (workInProgress2.flags & 128))
              return didReceiveUpdate = false, attemptEarlyBailoutIfNoScheduledUpdate(
                current,
                workInProgress2,
                renderLanes2
              );
            didReceiveUpdate = 0 !== (current.flags & 131072) ? true : false;
          }
        else
          didReceiveUpdate = false, isHydrating && 0 !== (workInProgress2.flags & 1048576) && pushTreeId(workInProgress2, treeForkCount, workInProgress2.index);
        workInProgress2.lanes = 0;
        switch (workInProgress2.tag) {
          case 16:
            a: {
              current = workInProgress2.pendingProps;
              var lazyComponent = workInProgress2.elementType, init = lazyComponent._init;
              lazyComponent = init(lazyComponent._payload);
              workInProgress2.type = lazyComponent;
              if ("function" === typeof lazyComponent)
                shouldConstruct(lazyComponent) ? (current = resolveClassComponentProps(lazyComponent, current), workInProgress2.tag = 1, workInProgress2 = updateClassComponent(
                  null,
                  workInProgress2,
                  lazyComponent,
                  current,
                  renderLanes2
                )) : (workInProgress2.tag = 0, workInProgress2 = updateFunctionComponent(
                  null,
                  workInProgress2,
                  lazyComponent,
                  current,
                  renderLanes2
                ));
              else {
                if (void 0 !== lazyComponent && null !== lazyComponent) {
                  if (init = lazyComponent.$$typeof, init === REACT_FORWARD_REF_TYPE) {
                    workInProgress2.tag = 11;
                    workInProgress2 = updateForwardRef(
                      null,
                      workInProgress2,
                      lazyComponent,
                      current,
                      renderLanes2
                    );
                    break a;
                  } else if (init === REACT_MEMO_TYPE) {
                    workInProgress2.tag = 14;
                    workInProgress2 = updateMemoComponent(
                      null,
                      workInProgress2,
                      lazyComponent,
                      current,
                      renderLanes2
                    );
                    break a;
                  }
                }
                workInProgress2 = getComponentNameFromType(lazyComponent) || lazyComponent;
                throw Error(formatProdErrorMessage(306, workInProgress2, ""));
              }
            }
            return workInProgress2;
          case 0:
            return updateFunctionComponent(
              current,
              workInProgress2,
              workInProgress2.type,
              workInProgress2.pendingProps,
              renderLanes2
            );
          case 1:
            return lazyComponent = workInProgress2.type, init = resolveClassComponentProps(
              lazyComponent,
              workInProgress2.pendingProps
            ), updateClassComponent(
              current,
              workInProgress2,
              lazyComponent,
              init,
              renderLanes2
            );
          case 3:
            a: {
              pushHostContainer(
                workInProgress2,
                workInProgress2.stateNode.containerInfo
              );
              if (null === current) throw Error(formatProdErrorMessage(387));
              var nextProps = workInProgress2.pendingProps;
              init = workInProgress2.memoizedState;
              lazyComponent = init.element;
              cloneUpdateQueue(current, workInProgress2);
              processUpdateQueue(workInProgress2, nextProps, null, renderLanes2);
              var nextState = workInProgress2.memoizedState;
              nextProps = nextState.cache;
              pushProvider(workInProgress2, CacheContext, nextProps);
              nextProps !== init.cache && propagateContextChanges(
                workInProgress2,
                [CacheContext],
                renderLanes2,
                true
              );
              suspendIfUpdateReadFromEntangledAsyncAction();
              nextProps = nextState.element;
              if (supportsHydration && init.isDehydrated)
                if (init = {
                  element: nextProps,
                  isDehydrated: false,
                  cache: nextState.cache
                }, workInProgress2.updateQueue.baseState = init, workInProgress2.memoizedState = init, workInProgress2.flags & 256) {
                  workInProgress2 = mountHostRootWithoutHydrating(
                    current,
                    workInProgress2,
                    nextProps,
                    renderLanes2
                  );
                  break a;
                } else if (nextProps !== lazyComponent) {
                  lazyComponent = createCapturedValueAtFiber(
                    Error(formatProdErrorMessage(424)),
                    workInProgress2
                  );
                  queueHydrationError(lazyComponent);
                  workInProgress2 = mountHostRootWithoutHydrating(
                    current,
                    workInProgress2,
                    nextProps,
                    renderLanes2
                  );
                  break a;
                } else
                  for (supportsHydration && (nextHydratableInstance = getFirstHydratableChildWithinContainer(
                    workInProgress2.stateNode.containerInfo
                  ), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, rootOrSingletonContext = true), renderLanes2 = mountChildFibers(
                    workInProgress2,
                    null,
                    nextProps,
                    renderLanes2
                  ), workInProgress2.child = renderLanes2; renderLanes2; )
                    renderLanes2.flags = renderLanes2.flags & -3 | 4096, renderLanes2 = renderLanes2.sibling;
              else {
                resetHydrationState();
                if (nextProps === lazyComponent) {
                  workInProgress2 = bailoutOnAlreadyFinishedWork(
                    current,
                    workInProgress2,
                    renderLanes2
                  );
                  break a;
                }
                reconcileChildren(current, workInProgress2, nextProps, renderLanes2);
              }
              workInProgress2 = workInProgress2.child;
            }
            return workInProgress2;
          case 26:
            if (supportsResources)
              return markRef(current, workInProgress2), null === current ? (renderLanes2 = getResource(
                workInProgress2.type,
                null,
                workInProgress2.pendingProps,
                null
              )) ? workInProgress2.memoizedState = renderLanes2 : isHydrating || (workInProgress2.stateNode = createHoistableInstance(
                workInProgress2.type,
                workInProgress2.pendingProps,
                rootInstanceStackCursor.current,
                workInProgress2
              )) : workInProgress2.memoizedState = getResource(
                workInProgress2.type,
                current.memoizedProps,
                workInProgress2.pendingProps,
                current.memoizedState
              ), null;
          case 27:
            if (supportsSingletons)
              return pushHostContext(workInProgress2), null === current && supportsSingletons && isHydrating && (lazyComponent = workInProgress2.stateNode = resolveSingletonInstance(
                workInProgress2.type,
                workInProgress2.pendingProps,
                rootInstanceStackCursor.current,
                contextStackCursor.current,
                false
              ), hydrationParentFiber = workInProgress2, rootOrSingletonContext = true, nextHydratableInstance = getFirstHydratableChildWithinSingleton(
                workInProgress2.type,
                lazyComponent,
                nextHydratableInstance
              )), reconcileChildren(
                current,
                workInProgress2,
                workInProgress2.pendingProps.children,
                renderLanes2
              ), markRef(current, workInProgress2), null === current && (workInProgress2.flags |= 4194304), workInProgress2.child;
          case 5:
            if (null === current && isHydrating) {
              validateHydratableInstance(
                workInProgress2.type,
                workInProgress2.pendingProps,
                contextStackCursor.current
              );
              if (init = lazyComponent = nextHydratableInstance)
                lazyComponent = canHydrateInstance(
                  lazyComponent,
                  workInProgress2.type,
                  workInProgress2.pendingProps,
                  rootOrSingletonContext
                ), null !== lazyComponent ? (workInProgress2.stateNode = lazyComponent, hydrationParentFiber = workInProgress2, nextHydratableInstance = getFirstHydratableChild(lazyComponent), rootOrSingletonContext = false, init = true) : init = false;
              init || throwOnHydrationMismatch(workInProgress2);
            }
            pushHostContext(workInProgress2);
            init = workInProgress2.type;
            nextProps = workInProgress2.pendingProps;
            nextState = null !== current ? current.memoizedProps : null;
            lazyComponent = nextProps.children;
            shouldSetTextContent(init, nextProps) ? lazyComponent = null : null !== nextState && shouldSetTextContent(init, nextState) && (workInProgress2.flags |= 32);
            null !== workInProgress2.memoizedState && (init = renderWithHooks(
              current,
              workInProgress2,
              TransitionAwareHostComponent,
              null,
              null,
              renderLanes2
            ), isPrimaryRenderer ? HostTransitionContext._currentValue = init : HostTransitionContext._currentValue2 = init);
            markRef(current, workInProgress2);
            reconcileChildren(current, workInProgress2, lazyComponent, renderLanes2);
            return workInProgress2.child;
          case 6:
            if (null === current && isHydrating) {
              validateHydratableTextInstance(
                workInProgress2.pendingProps,
                contextStackCursor.current
              );
              if (current = renderLanes2 = nextHydratableInstance)
                renderLanes2 = canHydrateTextInstance(
                  renderLanes2,
                  workInProgress2.pendingProps,
                  rootOrSingletonContext
                ), null !== renderLanes2 ? (workInProgress2.stateNode = renderLanes2, hydrationParentFiber = workInProgress2, nextHydratableInstance = null, current = true) : current = false;
              current || throwOnHydrationMismatch(workInProgress2);
            }
            return null;
          case 13:
            return updateSuspenseComponent(current, workInProgress2, renderLanes2);
          case 4:
            return pushHostContainer(
              workInProgress2,
              workInProgress2.stateNode.containerInfo
            ), lazyComponent = workInProgress2.pendingProps, null === current ? workInProgress2.child = reconcileChildFibers(
              workInProgress2,
              null,
              lazyComponent,
              renderLanes2
            ) : reconcileChildren(
              current,
              workInProgress2,
              lazyComponent,
              renderLanes2
            ), workInProgress2.child;
          case 11:
            return updateForwardRef(
              current,
              workInProgress2,
              workInProgress2.type,
              workInProgress2.pendingProps,
              renderLanes2
            );
          case 7:
            return reconcileChildren(
              current,
              workInProgress2,
              workInProgress2.pendingProps,
              renderLanes2
            ), workInProgress2.child;
          case 8:
            return reconcileChildren(
              current,
              workInProgress2,
              workInProgress2.pendingProps.children,
              renderLanes2
            ), workInProgress2.child;
          case 12:
            return reconcileChildren(
              current,
              workInProgress2,
              workInProgress2.pendingProps.children,
              renderLanes2
            ), workInProgress2.child;
          case 10:
            return lazyComponent = workInProgress2.pendingProps, pushProvider(
              workInProgress2,
              workInProgress2.type,
              lazyComponent.value
            ), reconcileChildren(
              current,
              workInProgress2,
              lazyComponent.children,
              renderLanes2
            ), workInProgress2.child;
          case 9:
            return init = workInProgress2.type._context, lazyComponent = workInProgress2.pendingProps.children, prepareToReadContext(workInProgress2), init = readContext(init), lazyComponent = lazyComponent(init), workInProgress2.flags |= 1, reconcileChildren(
              current,
              workInProgress2,
              lazyComponent,
              renderLanes2
            ), workInProgress2.child;
          case 14:
            return updateMemoComponent(
              current,
              workInProgress2,
              workInProgress2.type,
              workInProgress2.pendingProps,
              renderLanes2
            );
          case 15:
            return updateSimpleMemoComponent(
              current,
              workInProgress2,
              workInProgress2.type,
              workInProgress2.pendingProps,
              renderLanes2
            );
          case 19:
            return updateSuspenseListComponent(
              current,
              workInProgress2,
              renderLanes2
            );
          case 31:
            return lazyComponent = workInProgress2.pendingProps, renderLanes2 = workInProgress2.mode, lazyComponent = {
              mode: lazyComponent.mode,
              children: lazyComponent.children
            }, null === current ? (renderLanes2 = mountWorkInProgressOffscreenFiber(
              lazyComponent,
              renderLanes2
            ), renderLanes2.ref = workInProgress2.ref, workInProgress2.child = renderLanes2, renderLanes2.return = workInProgress2, workInProgress2 = renderLanes2) : (renderLanes2 = createWorkInProgress(
              current.child,
              lazyComponent
            ), renderLanes2.ref = workInProgress2.ref, workInProgress2.child = renderLanes2, renderLanes2.return = workInProgress2, workInProgress2 = renderLanes2), workInProgress2;
          case 22:
            return updateOffscreenComponent(current, workInProgress2, renderLanes2);
          case 24:
            return prepareToReadContext(workInProgress2), lazyComponent = readContext(CacheContext), null === current ? (init = peekCacheFromPool(), null === init && (init = workInProgressRoot, nextProps = createCache(), init.pooledCache = nextProps, nextProps.refCount++, null !== nextProps && (init.pooledCacheLanes |= renderLanes2), init = nextProps), workInProgress2.memoizedState = {
              parent: lazyComponent,
              cache: init
            }, initializeUpdateQueue(workInProgress2), pushProvider(workInProgress2, CacheContext, init)) : (0 !== (current.lanes & renderLanes2) && (cloneUpdateQueue(current, workInProgress2), processUpdateQueue(workInProgress2, null, null, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction()), init = current.memoizedState, nextProps = workInProgress2.memoizedState, init.parent !== lazyComponent ? (init = { parent: lazyComponent, cache: lazyComponent }, workInProgress2.memoizedState = init, 0 === workInProgress2.lanes && (workInProgress2.memoizedState = workInProgress2.updateQueue.baseState = init), pushProvider(workInProgress2, CacheContext, lazyComponent)) : (lazyComponent = nextProps.cache, pushProvider(workInProgress2, CacheContext, lazyComponent), lazyComponent !== init.cache && propagateContextChanges(
              workInProgress2,
              [CacheContext],
              renderLanes2,
              true
            ))), reconcileChildren(
              current,
              workInProgress2,
              workInProgress2.pendingProps.children,
              renderLanes2
            ), workInProgress2.child;
          case 29:
            throw workInProgress2.pendingProps;
        }
        throw Error(formatProdErrorMessage(156, workInProgress2.tag));
      }
      __name(beginWork, "beginWork");
      function markUpdate(workInProgress2) {
        workInProgress2.flags |= 4;
      }
      __name(markUpdate, "markUpdate");
      function doesRequireClone(current, completedWork) {
        if (null !== current && current.child === completedWork.child) return false;
        if (0 !== (completedWork.flags & 16)) return true;
        for (current = completedWork.child; null !== current; ) {
          if (0 !== (current.flags & 13878) || 0 !== (current.subtreeFlags & 13878))
            return true;
          current = current.sibling;
        }
        return false;
      }
      __name(doesRequireClone, "doesRequireClone");
      function appendAllChildren(parent, workInProgress2, needsVisibilityToggle, isHidden2) {
        if (supportsMutation)
          for (needsVisibilityToggle = workInProgress2.child; null !== needsVisibilityToggle; ) {
            if (5 === needsVisibilityToggle.tag || 6 === needsVisibilityToggle.tag)
              appendInitialChild(parent, needsVisibilityToggle.stateNode);
            else if (!(4 === needsVisibilityToggle.tag || supportsSingletons && 27 === needsVisibilityToggle.tag) && null !== needsVisibilityToggle.child) {
              needsVisibilityToggle.child.return = needsVisibilityToggle;
              needsVisibilityToggle = needsVisibilityToggle.child;
              continue;
            }
            if (needsVisibilityToggle === workInProgress2) break;
            for (; null === needsVisibilityToggle.sibling; ) {
              if (null === needsVisibilityToggle.return || needsVisibilityToggle.return === workInProgress2)
                return;
              needsVisibilityToggle = needsVisibilityToggle.return;
            }
            needsVisibilityToggle.sibling.return = needsVisibilityToggle.return;
            needsVisibilityToggle = needsVisibilityToggle.sibling;
          }
        else if (supportsPersistence)
          for (var node$93 = workInProgress2.child; null !== node$93; ) {
            if (5 === node$93.tag) {
              var instance = node$93.stateNode;
              needsVisibilityToggle && isHidden2 && (instance = cloneHiddenInstance(
                instance,
                node$93.type,
                node$93.memoizedProps
              ));
              appendInitialChild(parent, instance);
            } else if (6 === node$93.tag)
              instance = node$93.stateNode, needsVisibilityToggle && isHidden2 && (instance = cloneHiddenTextInstance(
                instance,
                node$93.memoizedProps
              )), appendInitialChild(parent, instance);
            else if (4 !== node$93.tag) {
              if (22 === node$93.tag && null !== node$93.memoizedState)
                instance = node$93.child, null !== instance && (instance.return = node$93), appendAllChildren(parent, node$93, true, true);
              else if (null !== node$93.child) {
                node$93.child.return = node$93;
                node$93 = node$93.child;
                continue;
              }
            }
            if (node$93 === workInProgress2) break;
            for (; null === node$93.sibling; ) {
              if (null === node$93.return || node$93.return === workInProgress2)
                return;
              node$93 = node$93.return;
            }
            node$93.sibling.return = node$93.return;
            node$93 = node$93.sibling;
          }
      }
      __name(appendAllChildren, "appendAllChildren");
      function appendAllChildrenToContainer(containerChildSet, workInProgress2, needsVisibilityToggle, isHidden2) {
        var hasOffscreenComponentChild = false;
        if (supportsPersistence)
          for (var node = workInProgress2.child; null !== node; ) {
            if (5 === node.tag) {
              var instance = node.stateNode;
              needsVisibilityToggle && isHidden2 && (instance = cloneHiddenInstance(
                instance,
                node.type,
                node.memoizedProps
              ));
              appendChildToContainerChildSet(containerChildSet, instance);
            } else if (6 === node.tag)
              instance = node.stateNode, needsVisibilityToggle && isHidden2 && (instance = cloneHiddenTextInstance(
                instance,
                node.memoizedProps
              )), appendChildToContainerChildSet(containerChildSet, instance);
            else if (4 !== node.tag) {
              if (22 === node.tag && null !== node.memoizedState)
                hasOffscreenComponentChild = node.child, null !== hasOffscreenComponentChild && (hasOffscreenComponentChild.return = node), appendAllChildrenToContainer(containerChildSet, node, true, true), hasOffscreenComponentChild = true;
              else if (null !== node.child) {
                node.child.return = node;
                node = node.child;
                continue;
              }
            }
            if (node === workInProgress2) break;
            for (; null === node.sibling; ) {
              if (null === node.return || node.return === workInProgress2)
                return hasOffscreenComponentChild;
              node = node.return;
            }
            node.sibling.return = node.return;
            node = node.sibling;
          }
        return hasOffscreenComponentChild;
      }
      __name(appendAllChildrenToContainer, "appendAllChildrenToContainer");
      function updateHostContainer(current, workInProgress2) {
        if (supportsPersistence && doesRequireClone(current, workInProgress2)) {
          current = workInProgress2.stateNode;
          var container = current.containerInfo, newChildSet = createContainerChildSet();
          appendAllChildrenToContainer(newChildSet, workInProgress2, false, false);
          current.pendingChildren = newChildSet;
          markUpdate(workInProgress2);
          finalizeContainerChildren(container, newChildSet);
        }
      }
      __name(updateHostContainer, "updateHostContainer");
      function updateHostComponent(current, workInProgress2, type, newProps) {
        if (supportsMutation)
          current.memoizedProps !== newProps && markUpdate(workInProgress2);
        else if (supportsPersistence) {
          var currentInstance = current.stateNode, oldProps$96 = current.memoizedProps;
          if ((current = doesRequireClone(current, workInProgress2)) || oldProps$96 !== newProps) {
            var currentHostContext = contextStackCursor.current;
            oldProps$96 = cloneInstance(
              currentInstance,
              type,
              oldProps$96,
              newProps,
              !current,
              null
            );
            oldProps$96 === currentInstance ? workInProgress2.stateNode = currentInstance : (finalizeInitialChildren(
              oldProps$96,
              type,
              newProps,
              currentHostContext
            ) && markUpdate(workInProgress2), workInProgress2.stateNode = oldProps$96, current ? appendAllChildren(oldProps$96, workInProgress2, false, false) : markUpdate(workInProgress2));
          } else workInProgress2.stateNode = currentInstance;
        }
      }
      __name(updateHostComponent, "updateHostComponent");
      function preloadInstanceAndSuspendIfNeeded(workInProgress2, type, props) {
        if (maySuspendCommit(type, props)) {
          if (workInProgress2.flags |= 16777216, !preloadInstance(type, props))
            if (shouldRemainOnPreviousScreen()) workInProgress2.flags |= 8192;
            else
              throw suspendedThenable = noopSuspenseyCommitThenable, SuspenseyCommitException;
        } else workInProgress2.flags &= -16777217;
      }
      __name(preloadInstanceAndSuspendIfNeeded, "preloadInstanceAndSuspendIfNeeded");
      function preloadResourceAndSuspendIfNeeded(workInProgress2, resource) {
        if (mayResourceSuspendCommit(resource)) {
          if (workInProgress2.flags |= 16777216, !preloadResource(resource))
            if (shouldRemainOnPreviousScreen()) workInProgress2.flags |= 8192;
            else
              throw suspendedThenable = noopSuspenseyCommitThenable, SuspenseyCommitException;
        } else workInProgress2.flags &= -16777217;
      }
      __name(preloadResourceAndSuspendIfNeeded, "preloadResourceAndSuspendIfNeeded");
      function scheduleRetryEffect(workInProgress2, retryQueue) {
        null !== retryQueue && (workInProgress2.flags |= 4);
        workInProgress2.flags & 16384 && (retryQueue = 22 !== workInProgress2.tag ? claimNextRetryLane() : 536870912, workInProgress2.lanes |= retryQueue, workInProgressSuspendedRetryLanes |= retryQueue);
      }
      __name(scheduleRetryEffect, "scheduleRetryEffect");
      function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
        if (!isHydrating)
          switch (renderState.tailMode) {
            case "hidden":
              hasRenderedATailFallback = renderState.tail;
              for (var lastTailNode = null; null !== hasRenderedATailFallback; )
                null !== hasRenderedATailFallback.alternate && (lastTailNode = hasRenderedATailFallback), hasRenderedATailFallback = hasRenderedATailFallback.sibling;
              null === lastTailNode ? renderState.tail = null : lastTailNode.sibling = null;
              break;
            case "collapsed":
              lastTailNode = renderState.tail;
              for (var lastTailNode$98 = null; null !== lastTailNode; )
                null !== lastTailNode.alternate && (lastTailNode$98 = lastTailNode), lastTailNode = lastTailNode.sibling;
              null === lastTailNode$98 ? hasRenderedATailFallback || null === renderState.tail ? renderState.tail = null : renderState.tail.sibling = null : lastTailNode$98.sibling = null;
          }
      }
      __name(cutOffTailIfNeeded, "cutOffTailIfNeeded");
      function bubbleProperties(completedWork) {
        var didBailout = null !== completedWork.alternate && completedWork.alternate.child === completedWork.child, newChildLanes = 0, subtreeFlags = 0;
        if (didBailout)
          for (var child$99 = completedWork.child; null !== child$99; )
            newChildLanes |= child$99.lanes | child$99.childLanes, subtreeFlags |= child$99.subtreeFlags & 65011712, subtreeFlags |= child$99.flags & 65011712, child$99.return = completedWork, child$99 = child$99.sibling;
        else
          for (child$99 = completedWork.child; null !== child$99; )
            newChildLanes |= child$99.lanes | child$99.childLanes, subtreeFlags |= child$99.subtreeFlags, subtreeFlags |= child$99.flags, child$99.return = completedWork, child$99 = child$99.sibling;
        completedWork.subtreeFlags |= subtreeFlags;
        completedWork.childLanes = newChildLanes;
        return didBailout;
      }
      __name(bubbleProperties, "bubbleProperties");
      function completeWork(current, workInProgress2, renderLanes2) {
        var newProps = workInProgress2.pendingProps;
        popTreeContext(workInProgress2);
        switch (workInProgress2.tag) {
          case 31:
          case 16:
          case 15:
          case 0:
          case 11:
          case 7:
          case 8:
          case 12:
          case 9:
          case 14:
            return bubbleProperties(workInProgress2), null;
          case 1:
            return bubbleProperties(workInProgress2), null;
          case 3:
            renderLanes2 = workInProgress2.stateNode;
            newProps = null;
            null !== current && (newProps = current.memoizedState.cache);
            workInProgress2.memoizedState.cache !== newProps && (workInProgress2.flags |= 2048);
            popProvider(CacheContext);
            popHostContainer();
            renderLanes2.pendingContext && (renderLanes2.context = renderLanes2.pendingContext, renderLanes2.pendingContext = null);
            if (null === current || null === current.child)
              popHydrationState(workInProgress2) ? markUpdate(workInProgress2) : null === current || current.memoizedState.isDehydrated && 0 === (workInProgress2.flags & 256) || (workInProgress2.flags |= 1024, upgradeHydrationErrorsToRecoverable());
            updateHostContainer(current, workInProgress2);
            bubbleProperties(workInProgress2);
            return null;
          case 26:
            if (supportsResources) {
              renderLanes2 = workInProgress2.type;
              var nextResource = workInProgress2.memoizedState;
              null === current ? (markUpdate(workInProgress2), null !== nextResource ? (bubbleProperties(workInProgress2), preloadResourceAndSuspendIfNeeded(
                workInProgress2,
                nextResource
              )) : (bubbleProperties(workInProgress2), preloadInstanceAndSuspendIfNeeded(
                workInProgress2,
                renderLanes2,
                newProps
              ))) : nextResource ? nextResource !== current.memoizedState ? (markUpdate(workInProgress2), bubbleProperties(workInProgress2), preloadResourceAndSuspendIfNeeded(
                workInProgress2,
                nextResource
              )) : (bubbleProperties(workInProgress2), workInProgress2.flags &= -16777217) : (supportsMutation ? current.memoizedProps !== newProps && markUpdate(workInProgress2) : updateHostComponent(
                current,
                workInProgress2,
                renderLanes2,
                newProps
              ), bubbleProperties(workInProgress2), preloadInstanceAndSuspendIfNeeded(
                workInProgress2,
                renderLanes2,
                newProps
              ));
              return null;
            }
          case 27:
            if (supportsSingletons) {
              popHostContext(workInProgress2);
              renderLanes2 = rootInstanceStackCursor.current;
              nextResource = workInProgress2.type;
              if (null !== current && null != workInProgress2.stateNode)
                supportsMutation ? current.memoizedProps !== newProps && markUpdate(workInProgress2) : updateHostComponent(
                  current,
                  workInProgress2,
                  nextResource,
                  newProps
                );
              else {
                if (!newProps) {
                  if (null === workInProgress2.stateNode)
                    throw Error(formatProdErrorMessage(166));
                  bubbleProperties(workInProgress2);
                  return null;
                }
                current = contextStackCursor.current;
                popHydrationState(workInProgress2) ? prepareToHydrateHostInstance(workInProgress2, current) : (current = resolveSingletonInstance(
                  nextResource,
                  newProps,
                  renderLanes2,
                  current,
                  true
                ), workInProgress2.stateNode = current, markUpdate(workInProgress2));
              }
              bubbleProperties(workInProgress2);
              return null;
            }
          case 5:
            popHostContext(workInProgress2);
            renderLanes2 = workInProgress2.type;
            if (null !== current && null != workInProgress2.stateNode)
              updateHostComponent(current, workInProgress2, renderLanes2, newProps);
            else {
              if (!newProps) {
                if (null === workInProgress2.stateNode)
                  throw Error(formatProdErrorMessage(166));
                bubbleProperties(workInProgress2);
                return null;
              }
              current = contextStackCursor.current;
              popHydrationState(workInProgress2) ? prepareToHydrateHostInstance(workInProgress2, current) : (nextResource = createInstance2(
                renderLanes2,
                newProps,
                rootInstanceStackCursor.current,
                current,
                workInProgress2
              ), appendAllChildren(nextResource, workInProgress2, false, false), workInProgress2.stateNode = nextResource, finalizeInitialChildren(
                nextResource,
                renderLanes2,
                newProps,
                current
              ) && markUpdate(workInProgress2));
            }
            bubbleProperties(workInProgress2);
            preloadInstanceAndSuspendIfNeeded(
              workInProgress2,
              workInProgress2.type,
              workInProgress2.pendingProps
            );
            return null;
          case 6:
            if (current && null != workInProgress2.stateNode)
              renderLanes2 = current.memoizedProps, supportsMutation ? renderLanes2 !== newProps && markUpdate(workInProgress2) : supportsPersistence && (renderLanes2 !== newProps ? (workInProgress2.stateNode = createTextInstance(
                newProps,
                rootInstanceStackCursor.current,
                contextStackCursor.current,
                workInProgress2
              ), markUpdate(workInProgress2)) : workInProgress2.stateNode = current.stateNode);
            else {
              if ("string" !== typeof newProps && null === workInProgress2.stateNode)
                throw Error(formatProdErrorMessage(166));
              current = rootInstanceStackCursor.current;
              renderLanes2 = contextStackCursor.current;
              if (popHydrationState(workInProgress2)) {
                if (!supportsHydration) throw Error(formatProdErrorMessage(176));
                current = workInProgress2.stateNode;
                renderLanes2 = workInProgress2.memoizedProps;
                newProps = null;
                nextResource = hydrationParentFiber;
                if (null !== nextResource)
                  switch (nextResource.tag) {
                    case 27:
                    case 5:
                      newProps = nextResource.memoizedProps;
                  }
                hydrateTextInstance(
                  current,
                  renderLanes2,
                  workInProgress2,
                  newProps
                ) || throwOnHydrationMismatch(workInProgress2);
              } else
                workInProgress2.stateNode = createTextInstance(
                  newProps,
                  current,
                  renderLanes2,
                  workInProgress2
                );
            }
            bubbleProperties(workInProgress2);
            return null;
          case 13:
            newProps = workInProgress2.memoizedState;
            if (null === current || null !== current.memoizedState && null !== current.memoizedState.dehydrated) {
              nextResource = popHydrationState(workInProgress2);
              if (null !== newProps && null !== newProps.dehydrated) {
                if (null === current) {
                  if (!nextResource) throw Error(formatProdErrorMessage(318));
                  if (!supportsHydration) throw Error(formatProdErrorMessage(344));
                  nextResource = workInProgress2.memoizedState;
                  nextResource = null !== nextResource ? nextResource.dehydrated : null;
                  if (!nextResource) throw Error(formatProdErrorMessage(317));
                  hydrateSuspenseInstance(nextResource, workInProgress2);
                } else
                  resetHydrationState(), 0 === (workInProgress2.flags & 128) && (workInProgress2.memoizedState = null), workInProgress2.flags |= 4;
                bubbleProperties(workInProgress2);
                nextResource = false;
              } else
                nextResource = upgradeHydrationErrorsToRecoverable(), null !== current && null !== current.memoizedState && (current.memoizedState.hydrationErrors = nextResource), nextResource = true;
              if (!nextResource) {
                if (workInProgress2.flags & 256)
                  return popSuspenseHandler(workInProgress2), workInProgress2;
                popSuspenseHandler(workInProgress2);
                return null;
              }
            }
            popSuspenseHandler(workInProgress2);
            if (0 !== (workInProgress2.flags & 128))
              return workInProgress2.lanes = renderLanes2, workInProgress2;
            renderLanes2 = null !== newProps;
            current = null !== current && null !== current.memoizedState;
            if (renderLanes2) {
              newProps = workInProgress2.child;
              nextResource = null;
              null !== newProps.alternate && null !== newProps.alternate.memoizedState && null !== newProps.alternate.memoizedState.cachePool && (nextResource = newProps.alternate.memoizedState.cachePool.pool);
              var cache$113 = null;
              null !== newProps.memoizedState && null !== newProps.memoizedState.cachePool && (cache$113 = newProps.memoizedState.cachePool.pool);
              cache$113 !== nextResource && (newProps.flags |= 2048);
            }
            renderLanes2 !== current && renderLanes2 && (workInProgress2.child.flags |= 8192);
            scheduleRetryEffect(workInProgress2, workInProgress2.updateQueue);
            bubbleProperties(workInProgress2);
            return null;
          case 4:
            return popHostContainer(), updateHostContainer(current, workInProgress2), null === current && preparePortalMount(workInProgress2.stateNode.containerInfo), bubbleProperties(workInProgress2), null;
          case 10:
            return popProvider(workInProgress2.type), bubbleProperties(workInProgress2), null;
          case 19:
            pop(suspenseStackCursor);
            nextResource = workInProgress2.memoizedState;
            if (null === nextResource)
              return bubbleProperties(workInProgress2), null;
            newProps = 0 !== (workInProgress2.flags & 128);
            cache$113 = nextResource.rendering;
            if (null === cache$113)
              if (newProps) cutOffTailIfNeeded(nextResource, false);
              else {
                if (0 !== workInProgressRootExitStatus || null !== current && 0 !== (current.flags & 128))
                  for (current = workInProgress2.child; null !== current; ) {
                    cache$113 = findFirstSuspended(current);
                    if (null !== cache$113) {
                      workInProgress2.flags |= 128;
                      cutOffTailIfNeeded(nextResource, false);
                      current = cache$113.updateQueue;
                      workInProgress2.updateQueue = current;
                      scheduleRetryEffect(workInProgress2, current);
                      workInProgress2.subtreeFlags = 0;
                      current = renderLanes2;
                      for (renderLanes2 = workInProgress2.child; null !== renderLanes2; )
                        resetWorkInProgress(renderLanes2, current), renderLanes2 = renderLanes2.sibling;
                      push2(
                        suspenseStackCursor,
                        suspenseStackCursor.current & 1 | 2
                      );
                      return workInProgress2.child;
                    }
                    current = current.sibling;
                  }
                null !== nextResource.tail && now() > workInProgressRootRenderTargetTime && (workInProgress2.flags |= 128, newProps = true, cutOffTailIfNeeded(nextResource, false), workInProgress2.lanes = 4194304);
              }
            else {
              if (!newProps)
                if (current = findFirstSuspended(cache$113), null !== current) {
                  if (workInProgress2.flags |= 128, newProps = true, current = current.updateQueue, workInProgress2.updateQueue = current, scheduleRetryEffect(workInProgress2, current), cutOffTailIfNeeded(nextResource, true), null === nextResource.tail && "hidden" === nextResource.tailMode && !cache$113.alternate && !isHydrating)
                    return bubbleProperties(workInProgress2), null;
                } else
                  2 * now() - nextResource.renderingStartTime > workInProgressRootRenderTargetTime && 536870912 !== renderLanes2 && (workInProgress2.flags |= 128, newProps = true, cutOffTailIfNeeded(nextResource, false), workInProgress2.lanes = 4194304);
              nextResource.isBackwards ? (cache$113.sibling = workInProgress2.child, workInProgress2.child = cache$113) : (current = nextResource.last, null !== current ? current.sibling = cache$113 : workInProgress2.child = cache$113, nextResource.last = cache$113);
            }
            if (null !== nextResource.tail)
              return workInProgress2 = nextResource.tail, nextResource.rendering = workInProgress2, nextResource.tail = workInProgress2.sibling, nextResource.renderingStartTime = now(), workInProgress2.sibling = null, current = suspenseStackCursor.current, push2(
                suspenseStackCursor,
                newProps ? current & 1 | 2 : current & 1
              ), workInProgress2;
            bubbleProperties(workInProgress2);
            return null;
          case 22:
          case 23:
            return popSuspenseHandler(workInProgress2), popHiddenContext(), newProps = null !== workInProgress2.memoizedState, null !== current ? null !== current.memoizedState !== newProps && (workInProgress2.flags |= 8192) : newProps && (workInProgress2.flags |= 8192), newProps ? 0 !== (renderLanes2 & 536870912) && 0 === (workInProgress2.flags & 128) && (bubbleProperties(workInProgress2), workInProgress2.subtreeFlags & 6 && (workInProgress2.flags |= 8192)) : bubbleProperties(workInProgress2), renderLanes2 = workInProgress2.updateQueue, null !== renderLanes2 && scheduleRetryEffect(workInProgress2, renderLanes2.retryQueue), renderLanes2 = null, null !== current && null !== current.memoizedState && null !== current.memoizedState.cachePool && (renderLanes2 = current.memoizedState.cachePool.pool), newProps = null, null !== workInProgress2.memoizedState && null !== workInProgress2.memoizedState.cachePool && (newProps = workInProgress2.memoizedState.cachePool.pool), newProps !== renderLanes2 && (workInProgress2.flags |= 2048), null !== current && pop(resumedCache), null;
          case 24:
            return renderLanes2 = null, null !== current && (renderLanes2 = current.memoizedState.cache), workInProgress2.memoizedState.cache !== renderLanes2 && (workInProgress2.flags |= 2048), popProvider(CacheContext), bubbleProperties(workInProgress2), null;
          case 25:
            return null;
          case 30:
            return null;
        }
        throw Error(formatProdErrorMessage(156, workInProgress2.tag));
      }
      __name(completeWork, "completeWork");
      function unwindWork(current, workInProgress2) {
        popTreeContext(workInProgress2);
        switch (workInProgress2.tag) {
          case 1:
            return current = workInProgress2.flags, current & 65536 ? (workInProgress2.flags = current & -65537 | 128, workInProgress2) : null;
          case 3:
            return popProvider(CacheContext), popHostContainer(), current = workInProgress2.flags, 0 !== (current & 65536) && 0 === (current & 128) ? (workInProgress2.flags = current & -65537 | 128, workInProgress2) : null;
          case 26:
          case 27:
          case 5:
            return popHostContext(workInProgress2), null;
          case 13:
            popSuspenseHandler(workInProgress2);
            current = workInProgress2.memoizedState;
            if (null !== current && null !== current.dehydrated) {
              if (null === workInProgress2.alternate)
                throw Error(formatProdErrorMessage(340));
              resetHydrationState();
            }
            current = workInProgress2.flags;
            return current & 65536 ? (workInProgress2.flags = current & -65537 | 128, workInProgress2) : null;
          case 19:
            return pop(suspenseStackCursor), null;
          case 4:
            return popHostContainer(), null;
          case 10:
            return popProvider(workInProgress2.type), null;
          case 22:
          case 23:
            return popSuspenseHandler(workInProgress2), popHiddenContext(), null !== current && pop(resumedCache), current = workInProgress2.flags, current & 65536 ? (workInProgress2.flags = current & -65537 | 128, workInProgress2) : null;
          case 24:
            return popProvider(CacheContext), null;
          case 25:
            return null;
          default:
            return null;
        }
      }
      __name(unwindWork, "unwindWork");
      function unwindInterruptedWork(current, interruptedWork) {
        popTreeContext(interruptedWork);
        switch (interruptedWork.tag) {
          case 3:
            popProvider(CacheContext);
            popHostContainer();
            break;
          case 26:
          case 27:
          case 5:
            popHostContext(interruptedWork);
            break;
          case 4:
            popHostContainer();
            break;
          case 13:
            popSuspenseHandler(interruptedWork);
            break;
          case 19:
            pop(suspenseStackCursor);
            break;
          case 10:
            popProvider(interruptedWork.type);
            break;
          case 22:
          case 23:
            popSuspenseHandler(interruptedWork);
            popHiddenContext();
            null !== current && pop(resumedCache);
            break;
          case 24:
            popProvider(CacheContext);
        }
      }
      __name(unwindInterruptedWork, "unwindInterruptedWork");
      function commitHookEffectListMount(flags, finishedWork) {
        try {
          var updateQueue = finishedWork.updateQueue, lastEffect = null !== updateQueue ? updateQueue.lastEffect : null;
          if (null !== lastEffect) {
            var firstEffect = lastEffect.next;
            updateQueue = firstEffect;
            do {
              if ((updateQueue.tag & flags) === flags) {
                lastEffect = void 0;
                var create3 = updateQueue.create, inst = updateQueue.inst;
                lastEffect = create3();
                inst.destroy = lastEffect;
              }
              updateQueue = updateQueue.next;
            } while (updateQueue !== firstEffect);
          }
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      __name(commitHookEffectListMount, "commitHookEffectListMount");
      function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor$jscomp$0) {
        try {
          var updateQueue = finishedWork.updateQueue, lastEffect = null !== updateQueue ? updateQueue.lastEffect : null;
          if (null !== lastEffect) {
            var firstEffect = lastEffect.next;
            updateQueue = firstEffect;
            do {
              if ((updateQueue.tag & flags) === flags) {
                var inst = updateQueue.inst, destroy = inst.destroy;
                if (void 0 !== destroy) {
                  inst.destroy = void 0;
                  lastEffect = finishedWork;
                  var nearestMountedAncestor = nearestMountedAncestor$jscomp$0, destroy_ = destroy;
                  try {
                    destroy_();
                  } catch (error) {
                    captureCommitPhaseError(
                      lastEffect,
                      nearestMountedAncestor,
                      error
                    );
                  }
                }
              }
              updateQueue = updateQueue.next;
            } while (updateQueue !== firstEffect);
          }
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      __name(commitHookEffectListUnmount, "commitHookEffectListUnmount");
      function commitClassCallbacks(finishedWork) {
        var updateQueue = finishedWork.updateQueue;
        if (null !== updateQueue) {
          var instance = finishedWork.stateNode;
          try {
            commitCallbacks(updateQueue, instance);
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
        }
      }
      __name(commitClassCallbacks, "commitClassCallbacks");
      function safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance) {
        instance.props = resolveClassComponentProps(
          current.type,
          current.memoizedProps
        );
        instance.state = current.memoizedState;
        try {
          instance.componentWillUnmount();
        } catch (error) {
          captureCommitPhaseError(current, nearestMountedAncestor, error);
        }
      }
      __name(safelyCallComponentWillUnmount, "safelyCallComponentWillUnmount");
      function safelyAttachRef(current, nearestMountedAncestor) {
        try {
          var ref = current.ref;
          if (null !== ref) {
            switch (current.tag) {
              case 26:
              case 27:
              case 5:
                var instanceToUse = getPublicInstance(current.stateNode);
                break;
              case 30:
                instanceToUse = current.stateNode;
                break;
              default:
                instanceToUse = current.stateNode;
            }
            "function" === typeof ref ? current.refCleanup = ref(instanceToUse) : ref.current = instanceToUse;
          }
        } catch (error) {
          captureCommitPhaseError(current, nearestMountedAncestor, error);
        }
      }
      __name(safelyAttachRef, "safelyAttachRef");
      function safelyDetachRef(current, nearestMountedAncestor) {
        var ref = current.ref, refCleanup = current.refCleanup;
        if (null !== ref)
          if ("function" === typeof refCleanup)
            try {
              refCleanup();
            } catch (error) {
              captureCommitPhaseError(current, nearestMountedAncestor, error);
            } finally {
              current.refCleanup = null, current = current.alternate, null != current && (current.refCleanup = null);
            }
          else if ("function" === typeof ref)
            try {
              ref(null);
            } catch (error$129) {
              captureCommitPhaseError(current, nearestMountedAncestor, error$129);
            }
          else ref.current = null;
      }
      __name(safelyDetachRef, "safelyDetachRef");
      function commitHostMount(finishedWork) {
        var type = finishedWork.type, props = finishedWork.memoizedProps, instance = finishedWork.stateNode;
        try {
          commitMount(instance, type, props, finishedWork);
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      __name(commitHostMount, "commitHostMount");
      function commitHostUpdate(finishedWork, newProps, oldProps) {
        try {
          commitUpdate(
            finishedWork.stateNode,
            finishedWork.type,
            oldProps,
            newProps,
            finishedWork
          );
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      __name(commitHostUpdate, "commitHostUpdate");
      function isHostParent(fiber) {
        return 5 === fiber.tag || 3 === fiber.tag || (supportsResources ? 26 === fiber.tag : false) || (supportsSingletons ? 27 === fiber.tag && isSingletonScope(fiber.type) : false) || 4 === fiber.tag;
      }
      __name(isHostParent, "isHostParent");
      function getHostSibling(fiber) {
        a: for (; ; ) {
          for (; null === fiber.sibling; ) {
            if (null === fiber.return || isHostParent(fiber.return)) return null;
            fiber = fiber.return;
          }
          fiber.sibling.return = fiber.return;
          for (fiber = fiber.sibling; 5 !== fiber.tag && 6 !== fiber.tag && 18 !== fiber.tag; ) {
            if (supportsSingletons && 27 === fiber.tag && isSingletonScope(fiber.type))
              continue a;
            if (fiber.flags & 2) continue a;
            if (null === fiber.child || 4 === fiber.tag) continue a;
            else fiber.child.return = fiber, fiber = fiber.child;
          }
          if (!(fiber.flags & 2)) return fiber.stateNode;
        }
      }
      __name(getHostSibling, "getHostSibling");
      function insertOrAppendPlacementNodeIntoContainer(node, before, parent) {
        var tag2 = node.tag;
        if (5 === tag2 || 6 === tag2)
          node = node.stateNode, before ? insertInContainerBefore(parent, node, before) : appendChildToContainer(parent, node);
        else if (4 !== tag2 && (supportsSingletons && 27 === tag2 && isSingletonScope(node.type) && (parent = node.stateNode, before = null), node = node.child, null !== node))
          for (insertOrAppendPlacementNodeIntoContainer(node, before, parent), node = node.sibling; null !== node; )
            insertOrAppendPlacementNodeIntoContainer(node, before, parent), node = node.sibling;
      }
      __name(insertOrAppendPlacementNodeIntoContainer, "insertOrAppendPlacementNodeIntoContainer");
      function insertOrAppendPlacementNode(node, before, parent) {
        var tag2 = node.tag;
        if (5 === tag2 || 6 === tag2)
          node = node.stateNode, before ? insertBefore(parent, node, before) : appendChild(parent, node);
        else if (4 !== tag2 && (supportsSingletons && 27 === tag2 && isSingletonScope(node.type) && (parent = node.stateNode), node = node.child, null !== node))
          for (insertOrAppendPlacementNode(node, before, parent), node = node.sibling; null !== node; )
            insertOrAppendPlacementNode(node, before, parent), node = node.sibling;
      }
      __name(insertOrAppendPlacementNode, "insertOrAppendPlacementNode");
      function commitHostPortalContainerChildren(portal, finishedWork, pendingChildren) {
        portal = portal.containerInfo;
        try {
          replaceContainerChildren(portal, pendingChildren);
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      __name(commitHostPortalContainerChildren, "commitHostPortalContainerChildren");
      function commitHostSingletonAcquisition(finishedWork) {
        var singleton = finishedWork.stateNode, props = finishedWork.memoizedProps;
        try {
          acquireSingletonInstance(
            finishedWork.type,
            props,
            singleton,
            finishedWork
          );
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      __name(commitHostSingletonAcquisition, "commitHostSingletonAcquisition");
      function commitBeforeMutationEffects(root, firstChild) {
        prepareForCommit(root.containerInfo);
        for (nextEffect = firstChild; null !== nextEffect; )
          if (root = nextEffect, firstChild = root.child, 0 !== (root.subtreeFlags & 1024) && null !== firstChild)
            firstChild.return = root, nextEffect = firstChild;
          else
            for (; null !== nextEffect; ) {
              root = nextEffect;
              var current = root.alternate;
              firstChild = root.flags;
              switch (root.tag) {
                case 0:
                  break;
                case 11:
                case 15:
                  break;
                case 1:
                  if (0 !== (firstChild & 1024) && null !== current) {
                    firstChild = void 0;
                    var finishedWork = root, prevProps = current.memoizedProps;
                    current = current.memoizedState;
                    var instance = finishedWork.stateNode;
                    try {
                      var resolvedPrevProps = resolveClassComponentProps(
                        finishedWork.type,
                        prevProps,
                        finishedWork.elementType === finishedWork.type
                      );
                      firstChild = instance.getSnapshotBeforeUpdate(
                        resolvedPrevProps,
                        current
                      );
                      instance.__reactInternalSnapshotBeforeUpdate = firstChild;
                    } catch (error) {
                      captureCommitPhaseError(
                        finishedWork,
                        finishedWork.return,
                        error
                      );
                    }
                  }
                  break;
                case 3:
                  0 !== (firstChild & 1024) && supportsMutation && clearContainer(root.stateNode.containerInfo);
                  break;
                case 5:
                case 26:
                case 27:
                case 6:
                case 4:
                case 17:
                  break;
                default:
                  if (0 !== (firstChild & 1024))
                    throw Error(formatProdErrorMessage(163));
              }
              firstChild = root.sibling;
              if (null !== firstChild) {
                firstChild.return = root.return;
                nextEffect = firstChild;
                break;
              }
              nextEffect = root.return;
            }
      }
      __name(commitBeforeMutationEffects, "commitBeforeMutationEffects");
      function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork) {
        var flags = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            flags & 4 && commitHookEffectListMount(5, finishedWork);
            break;
          case 1:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            if (flags & 4)
              if (finishedRoot = finishedWork.stateNode, null === current)
                try {
                  finishedRoot.componentDidMount();
                } catch (error) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error);
                }
              else {
                var prevProps = resolveClassComponentProps(
                  finishedWork.type,
                  current.memoizedProps
                );
                current = current.memoizedState;
                try {
                  finishedRoot.componentDidUpdate(
                    prevProps,
                    current,
                    finishedRoot.__reactInternalSnapshotBeforeUpdate
                  );
                } catch (error$128) {
                  captureCommitPhaseError(
                    finishedWork,
                    finishedWork.return,
                    error$128
                  );
                }
              }
            flags & 64 && commitClassCallbacks(finishedWork);
            flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 3:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            if (flags & 64 && (finishedRoot = finishedWork.updateQueue, null !== finishedRoot)) {
              current = null;
              if (null !== finishedWork.child)
                switch (finishedWork.child.tag) {
                  case 27:
                  case 5:
                    current = getPublicInstance(finishedWork.child.stateNode);
                    break;
                  case 1:
                    current = finishedWork.child.stateNode;
                }
              try {
                commitCallbacks(finishedRoot, current);
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            }
            break;
          case 27:
            supportsSingletons && null === current && flags & 4 && commitHostSingletonAcquisition(finishedWork);
          case 26:
          case 5:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            null === current && flags & 4 && commitHostMount(finishedWork);
            flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 12:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            break;
          case 13:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
            flags & 64 && (finishedRoot = finishedWork.memoizedState, null !== finishedRoot && (finishedRoot = finishedRoot.dehydrated, null !== finishedRoot && (finishedWork = retryDehydratedSuspenseBoundary.bind(
              null,
              finishedWork
            ), registerSuspenseInstanceRetry(finishedRoot, finishedWork))));
            break;
          case 22:
            flags = null !== finishedWork.memoizedState || offscreenSubtreeIsHidden;
            if (!flags) {
              current = null !== current && null !== current.memoizedState || offscreenSubtreeWasHidden;
              prevProps = offscreenSubtreeIsHidden;
              var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
              offscreenSubtreeIsHidden = flags;
              (offscreenSubtreeWasHidden = current) && !prevOffscreenSubtreeWasHidden ? recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                0 !== (finishedWork.subtreeFlags & 8772)
              ) : recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
              offscreenSubtreeIsHidden = prevProps;
              offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
            }
            break;
          case 30:
            break;
          default:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
        }
      }
      __name(commitLayoutEffectOnFiber, "commitLayoutEffectOnFiber");
      function detachFiberAfterEffects(fiber) {
        var alternate = fiber.alternate;
        null !== alternate && (fiber.alternate = null, detachFiberAfterEffects(alternate));
        fiber.child = null;
        fiber.deletions = null;
        fiber.sibling = null;
        5 === fiber.tag && (alternate = fiber.stateNode, null !== alternate && detachDeletedInstance(alternate));
        fiber.stateNode = null;
        fiber.return = null;
        fiber.dependencies = null;
        fiber.memoizedProps = null;
        fiber.memoizedState = null;
        fiber.pendingProps = null;
        fiber.stateNode = null;
        fiber.updateQueue = null;
      }
      __name(detachFiberAfterEffects, "detachFiberAfterEffects");
      function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) {
        for (parent = parent.child; null !== parent; )
          commitDeletionEffectsOnFiber(
            finishedRoot,
            nearestMountedAncestor,
            parent
          ), parent = parent.sibling;
      }
      __name(recursivelyTraverseDeletionEffects, "recursivelyTraverseDeletionEffects");
      function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) {
        if (injectedHook && "function" === typeof injectedHook.onCommitFiberUnmount)
          try {
            injectedHook.onCommitFiberUnmount(rendererID, deletedFiber);
          } catch (err) {
          }
        switch (deletedFiber.tag) {
          case 26:
            if (supportsResources) {
              offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
              recursivelyTraverseDeletionEffects(
                finishedRoot,
                nearestMountedAncestor,
                deletedFiber
              );
              deletedFiber.memoizedState ? releaseResource(deletedFiber.memoizedState) : deletedFiber.stateNode && unmountHoistable(deletedFiber.stateNode);
              break;
            }
          case 27:
            if (supportsSingletons) {
              offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
              var prevHostParent = hostParent, prevHostParentIsContainer = hostParentIsContainer;
              isSingletonScope(deletedFiber.type) && (hostParent = deletedFiber.stateNode, hostParentIsContainer = false);
              recursivelyTraverseDeletionEffects(
                finishedRoot,
                nearestMountedAncestor,
                deletedFiber
              );
              releaseSingletonInstance(deletedFiber.stateNode);
              hostParent = prevHostParent;
              hostParentIsContainer = prevHostParentIsContainer;
              break;
            }
          case 5:
            offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
          case 6:
            if (supportsMutation) {
              if (prevHostParent = hostParent, prevHostParentIsContainer = hostParentIsContainer, hostParent = null, recursivelyTraverseDeletionEffects(
                finishedRoot,
                nearestMountedAncestor,
                deletedFiber
              ), hostParent = prevHostParent, hostParentIsContainer = prevHostParentIsContainer, null !== hostParent)
                if (hostParentIsContainer)
                  try {
                    removeChildFromContainer(hostParent, deletedFiber.stateNode);
                  } catch (error) {
                    captureCommitPhaseError(
                      deletedFiber,
                      nearestMountedAncestor,
                      error
                    );
                  }
                else
                  try {
                    removeChild(hostParent, deletedFiber.stateNode);
                  } catch (error) {
                    captureCommitPhaseError(
                      deletedFiber,
                      nearestMountedAncestor,
                      error
                    );
                  }
            } else
              recursivelyTraverseDeletionEffects(
                finishedRoot,
                nearestMountedAncestor,
                deletedFiber
              );
            break;
          case 18:
            supportsMutation && null !== hostParent && (hostParentIsContainer ? clearSuspenseBoundaryFromContainer(
              hostParent,
              deletedFiber.stateNode
            ) : clearSuspenseBoundary(hostParent, deletedFiber.stateNode));
            break;
          case 4:
            supportsMutation ? (prevHostParent = hostParent, prevHostParentIsContainer = hostParentIsContainer, hostParent = deletedFiber.stateNode.containerInfo, hostParentIsContainer = true, recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            ), hostParent = prevHostParent, hostParentIsContainer = prevHostParentIsContainer) : (supportsPersistence && commitHostPortalContainerChildren(
              deletedFiber.stateNode,
              deletedFiber,
              createContainerChildSet()
            ), recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            ));
            break;
          case 0:
          case 11:
          case 14:
          case 15:
            offscreenSubtreeWasHidden || commitHookEffectListUnmount(2, deletedFiber, nearestMountedAncestor);
            offscreenSubtreeWasHidden || commitHookEffectListUnmount(4, deletedFiber, nearestMountedAncestor);
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
            break;
          case 1:
            offscreenSubtreeWasHidden || (safelyDetachRef(deletedFiber, nearestMountedAncestor), prevHostParent = deletedFiber.stateNode, "function" === typeof prevHostParent.componentWillUnmount && safelyCallComponentWillUnmount(
              deletedFiber,
              nearestMountedAncestor,
              prevHostParent
            ));
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
            break;
          case 21:
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
            break;
          case 22:
            offscreenSubtreeWasHidden = (prevHostParent = offscreenSubtreeWasHidden) || null !== deletedFiber.memoizedState;
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
            offscreenSubtreeWasHidden = prevHostParent;
            break;
          default:
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
        }
      }
      __name(commitDeletionEffectsOnFiber, "commitDeletionEffectsOnFiber");
      function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
        if (supportsHydration && null === finishedWork.memoizedState && (finishedRoot = finishedWork.alternate, null !== finishedRoot && (finishedRoot = finishedRoot.memoizedState, null !== finishedRoot && (finishedRoot = finishedRoot.dehydrated, null !== finishedRoot))))
          try {
            commitHydratedSuspenseInstance(finishedRoot);
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
      }
      __name(commitSuspenseHydrationCallbacks, "commitSuspenseHydrationCallbacks");
      function getRetryCache(finishedWork) {
        switch (finishedWork.tag) {
          case 13:
          case 19:
            var retryCache = finishedWork.stateNode;
            null === retryCache && (retryCache = finishedWork.stateNode = new PossiblyWeakSet());
            return retryCache;
          case 22:
            return finishedWork = finishedWork.stateNode, retryCache = finishedWork._retryCache, null === retryCache && (retryCache = finishedWork._retryCache = new PossiblyWeakSet()), retryCache;
          default:
            throw Error(formatProdErrorMessage(435, finishedWork.tag));
        }
      }
      __name(getRetryCache, "getRetryCache");
      function attachSuspenseRetryListeners(finishedWork, wakeables) {
        var retryCache = getRetryCache(finishedWork);
        wakeables.forEach(function(wakeable) {
          var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);
          retryCache.has(wakeable) || (retryCache.add(wakeable), wakeable.then(retry, retry));
        });
      }
      __name(attachSuspenseRetryListeners, "attachSuspenseRetryListeners");
      function recursivelyTraverseMutationEffects(root$jscomp$0, parentFiber) {
        var deletions = parentFiber.deletions;
        if (null !== deletions)
          for (var i = 0; i < deletions.length; i++) {
            var childToDelete = deletions[i], root = root$jscomp$0, returnFiber = parentFiber;
            if (supportsMutation) {
              var parent = returnFiber;
              a: for (; null !== parent; ) {
                switch (parent.tag) {
                  case 27:
                    if (supportsSingletons) {
                      if (isSingletonScope(parent.type)) {
                        hostParent = parent.stateNode;
                        hostParentIsContainer = false;
                        break a;
                      }
                      break;
                    }
                  case 5:
                    hostParent = parent.stateNode;
                    hostParentIsContainer = false;
                    break a;
                  case 3:
                  case 4:
                    hostParent = parent.stateNode.containerInfo;
                    hostParentIsContainer = true;
                    break a;
                }
                parent = parent.return;
              }
              if (null === hostParent) throw Error(formatProdErrorMessage(160));
              commitDeletionEffectsOnFiber(root, returnFiber, childToDelete);
              hostParent = null;
              hostParentIsContainer = false;
            } else commitDeletionEffectsOnFiber(root, returnFiber, childToDelete);
            root = childToDelete.alternate;
            null !== root && (root.return = null);
            childToDelete.return = null;
          }
        if (parentFiber.subtreeFlags & 13878)
          for (parentFiber = parentFiber.child; null !== parentFiber; )
            commitMutationEffectsOnFiber(parentFiber, root$jscomp$0), parentFiber = parentFiber.sibling;
      }
      __name(recursivelyTraverseMutationEffects, "recursivelyTraverseMutationEffects");
      function commitMutationEffectsOnFiber(finishedWork, root) {
        var current = finishedWork.alternate, flags = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 14:
          case 15:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags & 4 && (commitHookEffectListUnmount(3, finishedWork, finishedWork.return), commitHookEffectListMount(3, finishedWork), commitHookEffectListUnmount(5, finishedWork, finishedWork.return));
            break;
          case 1:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
            flags & 64 && offscreenSubtreeIsHidden && (finishedWork = finishedWork.updateQueue, null !== finishedWork && (flags = finishedWork.callbacks, null !== flags && (current = finishedWork.shared.hiddenCallbacks, finishedWork.shared.hiddenCallbacks = null === current ? flags : current.concat(flags))));
            break;
          case 26:
            if (supportsResources) {
              var hoistableRoot = currentHoistableRoot;
              recursivelyTraverseMutationEffects(root, finishedWork);
              commitReconciliationEffects(finishedWork);
              flags & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
              if (flags & 4) {
                flags = null !== current ? current.memoizedState : null;
                var newResource = finishedWork.memoizedState;
                null === current ? null === newResource ? null === finishedWork.stateNode ? finishedWork.stateNode = hydrateHoistable(
                  hoistableRoot,
                  finishedWork.type,
                  finishedWork.memoizedProps,
                  finishedWork
                ) : mountHoistable(
                  hoistableRoot,
                  finishedWork.type,
                  finishedWork.stateNode
                ) : finishedWork.stateNode = acquireResource(
                  hoistableRoot,
                  newResource,
                  finishedWork.memoizedProps
                ) : flags !== newResource ? (null === flags ? null !== current.stateNode && unmountHoistable(current.stateNode) : releaseResource(flags), null === newResource ? mountHoistable(
                  hoistableRoot,
                  finishedWork.type,
                  finishedWork.stateNode
                ) : acquireResource(
                  hoistableRoot,
                  newResource,
                  finishedWork.memoizedProps
                )) : null === newResource && null !== finishedWork.stateNode && commitHostUpdate(
                  finishedWork,
                  finishedWork.memoizedProps,
                  current.memoizedProps
                );
              }
              break;
            }
          case 27:
            if (supportsSingletons) {
              recursivelyTraverseMutationEffects(root, finishedWork);
              commitReconciliationEffects(finishedWork);
              flags & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
              null !== current && flags & 4 && commitHostUpdate(
                finishedWork,
                finishedWork.memoizedProps,
                current.memoizedProps
              );
              break;
            }
          case 5:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
            if (supportsMutation) {
              if (finishedWork.flags & 32) {
                hoistableRoot = finishedWork.stateNode;
                try {
                  resetTextContent(hoistableRoot);
                } catch (error) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error);
                }
              }
              flags & 4 && null != finishedWork.stateNode && (hoistableRoot = finishedWork.memoizedProps, commitHostUpdate(
                finishedWork,
                hoistableRoot,
                null !== current ? current.memoizedProps : hoistableRoot
              ));
              flags & 1024 && (needsFormReset = true);
            }
            break;
          case 6:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            if (flags & 4 && supportsMutation) {
              if (null === finishedWork.stateNode)
                throw Error(formatProdErrorMessage(162));
              flags = finishedWork.memoizedProps;
              current = null !== current ? current.memoizedProps : flags;
              hoistableRoot = finishedWork.stateNode;
              try {
                commitTextUpdate(hoistableRoot, current, flags);
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            }
            break;
          case 3:
            supportsResources ? (prepareToCommitHoistables(), hoistableRoot = currentHoistableRoot, currentHoistableRoot = getHoistableRoot(root.containerInfo), recursivelyTraverseMutationEffects(root, finishedWork), currentHoistableRoot = hoistableRoot) : recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            if (flags & 4) {
              if (supportsMutation && supportsHydration && null !== current && current.memoizedState.isDehydrated)
                try {
                  commitHydratedContainer(root.containerInfo);
                } catch (error) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error);
                }
              if (supportsPersistence) {
                flags = root.containerInfo;
                current = root.pendingChildren;
                try {
                  replaceContainerChildren(flags, current);
                } catch (error) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error);
                }
              }
            }
            needsFormReset && (needsFormReset = false, recursivelyResetForms(finishedWork));
            break;
          case 4:
            supportsResources ? (current = currentHoistableRoot, currentHoistableRoot = getHoistableRoot(
              finishedWork.stateNode.containerInfo
            ), recursivelyTraverseMutationEffects(root, finishedWork), commitReconciliationEffects(finishedWork), currentHoistableRoot = current) : (recursivelyTraverseMutationEffects(root, finishedWork), commitReconciliationEffects(finishedWork));
            flags & 4 && supportsPersistence && commitHostPortalContainerChildren(
              finishedWork.stateNode,
              finishedWork,
              finishedWork.stateNode.pendingChildren
            );
            break;
          case 12:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            break;
          case 13:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            finishedWork.child.flags & 8192 && null !== finishedWork.memoizedState !== (null !== current && null !== current.memoizedState) && (globalMostRecentFallbackTime = now());
            flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
            break;
          case 22:
            hoistableRoot = null !== finishedWork.memoizedState;
            var wasHidden = null !== current && null !== current.memoizedState, prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
            offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || hoistableRoot;
            offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || wasHidden;
            recursivelyTraverseMutationEffects(root, finishedWork);
            offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
            offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
            commitReconciliationEffects(finishedWork);
            if (flags & 8192 && (root = finishedWork.stateNode, root._visibility = hoistableRoot ? root._visibility & -2 : root._visibility | 1, hoistableRoot && (null === current || wasHidden || offscreenSubtreeIsHidden || offscreenSubtreeWasHidden || recursivelyTraverseDisappearLayoutEffects(finishedWork)), supportsMutation)) {
              a: if (current = null, supportsMutation)
                for (root = finishedWork; ; ) {
                  if (5 === root.tag || supportsResources && 26 === root.tag) {
                    if (null === current) {
                      wasHidden = current = root;
                      try {
                        newResource = wasHidden.stateNode, hoistableRoot ? hideInstance(newResource) : unhideInstance(
                          wasHidden.stateNode,
                          wasHidden.memoizedProps
                        );
                      } catch (error) {
                        captureCommitPhaseError(wasHidden, wasHidden.return, error);
                      }
                    }
                  } else if (6 === root.tag) {
                    if (null === current) {
                      wasHidden = root;
                      try {
                        var instance = wasHidden.stateNode;
                        hoistableRoot ? hideTextInstance(instance) : unhideTextInstance(instance, wasHidden.memoizedProps);
                      } catch (error) {
                        captureCommitPhaseError(wasHidden, wasHidden.return, error);
                      }
                    }
                  } else if ((22 !== root.tag && 23 !== root.tag || null === root.memoizedState || root === finishedWork) && null !== root.child) {
                    root.child.return = root;
                    root = root.child;
                    continue;
                  }
                  if (root === finishedWork) break a;
                  for (; null === root.sibling; ) {
                    if (null === root.return || root.return === finishedWork)
                      break a;
                    current === root && (current = null);
                    root = root.return;
                  }
                  current === root && (current = null);
                  root.sibling.return = root.return;
                  root = root.sibling;
                }
            }
            flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (current = flags.retryQueue, null !== current && (flags.retryQueue = null, attachSuspenseRetryListeners(finishedWork, current))));
            break;
          case 19:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
            break;
          case 30:
            break;
          case 21:
            break;
          default:
            recursivelyTraverseMutationEffects(root, finishedWork), commitReconciliationEffects(finishedWork);
        }
      }
      __name(commitMutationEffectsOnFiber, "commitMutationEffectsOnFiber");
      function commitReconciliationEffects(finishedWork) {
        var flags = finishedWork.flags;
        if (flags & 2) {
          try {
            if (supportsMutation) {
              for (var hostParentFiber, parentFiber = finishedWork.return; null !== parentFiber; ) {
                if (isHostParent(parentFiber)) {
                  hostParentFiber = parentFiber;
                  break;
                }
                parentFiber = parentFiber.return;
              }
              if (null == hostParentFiber) throw Error(formatProdErrorMessage(160));
              switch (hostParentFiber.tag) {
                case 27:
                  if (supportsSingletons) {
                    var parent = hostParentFiber.stateNode, before = getHostSibling(finishedWork);
                    insertOrAppendPlacementNode(finishedWork, before, parent);
                    break;
                  }
                case 5:
                  var parent$130 = hostParentFiber.stateNode;
                  hostParentFiber.flags & 32 && (resetTextContent(parent$130), hostParentFiber.flags &= -33);
                  var before$131 = getHostSibling(finishedWork);
                  insertOrAppendPlacementNode(finishedWork, before$131, parent$130);
                  break;
                case 3:
                case 4:
                  var parent$132 = hostParentFiber.stateNode.containerInfo, before$133 = getHostSibling(finishedWork);
                  insertOrAppendPlacementNodeIntoContainer(
                    finishedWork,
                    before$133,
                    parent$132
                  );
                  break;
                default:
                  throw Error(formatProdErrorMessage(161));
              }
            }
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
          finishedWork.flags &= -3;
        }
        flags & 4096 && (finishedWork.flags &= -4097);
      }
      __name(commitReconciliationEffects, "commitReconciliationEffects");
      function recursivelyResetForms(parentFiber) {
        if (parentFiber.subtreeFlags & 1024)
          for (parentFiber = parentFiber.child; null !== parentFiber; ) {
            var fiber = parentFiber;
            recursivelyResetForms(fiber);
            5 === fiber.tag && fiber.flags & 1024 && resetFormInstance(fiber.stateNode);
            parentFiber = parentFiber.sibling;
          }
      }
      __name(recursivelyResetForms, "recursivelyResetForms");
      function recursivelyTraverseLayoutEffects(root, parentFiber) {
        if (parentFiber.subtreeFlags & 8772)
          for (parentFiber = parentFiber.child; null !== parentFiber; )
            commitLayoutEffectOnFiber(root, parentFiber.alternate, parentFiber), parentFiber = parentFiber.sibling;
      }
      __name(recursivelyTraverseLayoutEffects, "recursivelyTraverseLayoutEffects");
      function recursivelyTraverseDisappearLayoutEffects(parentFiber) {
        for (parentFiber = parentFiber.child; null !== parentFiber; ) {
          var finishedWork = parentFiber;
          switch (finishedWork.tag) {
            case 0:
            case 11:
            case 14:
            case 15:
              commitHookEffectListUnmount(4, finishedWork, finishedWork.return);
              recursivelyTraverseDisappearLayoutEffects(finishedWork);
              break;
            case 1:
              safelyDetachRef(finishedWork, finishedWork.return);
              var instance = finishedWork.stateNode;
              "function" === typeof instance.componentWillUnmount && safelyCallComponentWillUnmount(
                finishedWork,
                finishedWork.return,
                instance
              );
              recursivelyTraverseDisappearLayoutEffects(finishedWork);
              break;
            case 27:
              supportsSingletons && releaseSingletonInstance(finishedWork.stateNode);
            case 26:
            case 5:
              safelyDetachRef(finishedWork, finishedWork.return);
              recursivelyTraverseDisappearLayoutEffects(finishedWork);
              break;
            case 22:
              null === finishedWork.memoizedState && recursivelyTraverseDisappearLayoutEffects(finishedWork);
              break;
            case 30:
              recursivelyTraverseDisappearLayoutEffects(finishedWork);
              break;
            default:
              recursivelyTraverseDisappearLayoutEffects(finishedWork);
          }
          parentFiber = parentFiber.sibling;
        }
      }
      __name(recursivelyTraverseDisappearLayoutEffects, "recursivelyTraverseDisappearLayoutEffects");
      function recursivelyTraverseReappearLayoutEffects(finishedRoot$jscomp$0, parentFiber, includeWorkInProgressEffects) {
        includeWorkInProgressEffects = includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 8772);
        for (parentFiber = parentFiber.child; null !== parentFiber; ) {
          var current = parentFiber.alternate, finishedRoot = finishedRoot$jscomp$0, finishedWork = parentFiber, flags = finishedWork.flags;
          switch (finishedWork.tag) {
            case 0:
            case 11:
            case 15:
              recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                includeWorkInProgressEffects
              );
              commitHookEffectListMount(4, finishedWork);
              break;
            case 1:
              recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                includeWorkInProgressEffects
              );
              current = finishedWork;
              finishedRoot = current.stateNode;
              if ("function" === typeof finishedRoot.componentDidMount)
                try {
                  finishedRoot.componentDidMount();
                } catch (error) {
                  captureCommitPhaseError(current, current.return, error);
                }
              current = finishedWork;
              finishedRoot = current.updateQueue;
              if (null !== finishedRoot) {
                var instance = current.stateNode;
                try {
                  var hiddenCallbacks = finishedRoot.shared.hiddenCallbacks;
                  if (null !== hiddenCallbacks)
                    for (finishedRoot.shared.hiddenCallbacks = null, finishedRoot = 0; finishedRoot < hiddenCallbacks.length; finishedRoot++)
                      callCallback(hiddenCallbacks[finishedRoot], instance);
                } catch (error) {
                  captureCommitPhaseError(current, current.return, error);
                }
              }
              includeWorkInProgressEffects && flags & 64 && commitClassCallbacks(finishedWork);
              safelyAttachRef(finishedWork, finishedWork.return);
              break;
            case 27:
              supportsSingletons && commitHostSingletonAcquisition(finishedWork);
            case 26:
            case 5:
              recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                includeWorkInProgressEffects
              );
              includeWorkInProgressEffects && null === current && flags & 4 && commitHostMount(finishedWork);
              safelyAttachRef(finishedWork, finishedWork.return);
              break;
            case 12:
              recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                includeWorkInProgressEffects
              );
              break;
            case 13:
              recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                includeWorkInProgressEffects
              );
              includeWorkInProgressEffects && flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
              break;
            case 22:
              null === finishedWork.memoizedState && recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                includeWorkInProgressEffects
              );
              safelyAttachRef(finishedWork, finishedWork.return);
              break;
            case 30:
              break;
            default:
              recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                includeWorkInProgressEffects
              );
          }
          parentFiber = parentFiber.sibling;
        }
      }
      __name(recursivelyTraverseReappearLayoutEffects, "recursivelyTraverseReappearLayoutEffects");
      function commitOffscreenPassiveMountEffects(current, finishedWork) {
        var previousCache = null;
        null !== current && null !== current.memoizedState && null !== current.memoizedState.cachePool && (previousCache = current.memoizedState.cachePool.pool);
        current = null;
        null !== finishedWork.memoizedState && null !== finishedWork.memoizedState.cachePool && (current = finishedWork.memoizedState.cachePool.pool);
        current !== previousCache && (null != current && current.refCount++, null != previousCache && releaseCache(previousCache));
      }
      __name(commitOffscreenPassiveMountEffects, "commitOffscreenPassiveMountEffects");
      function commitCachePassiveMountEffect(current, finishedWork) {
        current = null;
        null !== finishedWork.alternate && (current = finishedWork.alternate.memoizedState.cache);
        finishedWork = finishedWork.memoizedState.cache;
        finishedWork !== current && (finishedWork.refCount++, null != current && releaseCache(current));
      }
      __name(commitCachePassiveMountEffect, "commitCachePassiveMountEffect");
      function recursivelyTraversePassiveMountEffects(root, parentFiber, committedLanes, committedTransitions) {
        if (parentFiber.subtreeFlags & 10256)
          for (parentFiber = parentFiber.child; null !== parentFiber; )
            commitPassiveMountOnFiber(
              root,
              parentFiber,
              committedLanes,
              committedTransitions
            ), parentFiber = parentFiber.sibling;
      }
      __name(recursivelyTraversePassiveMountEffects, "recursivelyTraversePassiveMountEffects");
      function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions) {
        var flags = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            flags & 2048 && commitHookEffectListMount(9, finishedWork);
            break;
          case 1:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            break;
          case 3:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            flags & 2048 && (finishedRoot = null, null !== finishedWork.alternate && (finishedRoot = finishedWork.alternate.memoizedState.cache), finishedWork = finishedWork.memoizedState.cache, finishedWork !== finishedRoot && (finishedWork.refCount++, null != finishedRoot && releaseCache(finishedRoot)));
            break;
          case 12:
            if (flags & 2048) {
              recursivelyTraversePassiveMountEffects(
                finishedRoot,
                finishedWork,
                committedLanes,
                committedTransitions
              );
              finishedRoot = finishedWork.stateNode;
              try {
                var _finishedWork$memoize2 = finishedWork.memoizedProps, id = _finishedWork$memoize2.id, onPostCommit = _finishedWork$memoize2.onPostCommit;
                "function" === typeof onPostCommit && onPostCommit(
                  id,
                  null === finishedWork.alternate ? "mount" : "update",
                  finishedRoot.passiveEffectDuration,
                  -0
                );
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            } else
              recursivelyTraversePassiveMountEffects(
                finishedRoot,
                finishedWork,
                committedLanes,
                committedTransitions
              );
            break;
          case 13:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            break;
          case 23:
            break;
          case 22:
            _finishedWork$memoize2 = finishedWork.stateNode;
            id = finishedWork.alternate;
            null !== finishedWork.memoizedState ? _finishedWork$memoize2._visibility & 2 ? recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            ) : recursivelyTraverseAtomicPassiveEffects(
              finishedRoot,
              finishedWork
            ) : _finishedWork$memoize2._visibility & 2 ? recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            ) : (_finishedWork$memoize2._visibility |= 2, recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              0 !== (finishedWork.subtreeFlags & 10256)
            ));
            flags & 2048 && commitOffscreenPassiveMountEffects(id, finishedWork);
            break;
          case 24:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
            break;
          default:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
        }
      }
      __name(commitPassiveMountOnFiber, "commitPassiveMountOnFiber");
      function recursivelyTraverseReconnectPassiveEffects(finishedRoot$jscomp$0, parentFiber, committedLanes$jscomp$0, committedTransitions$jscomp$0, includeWorkInProgressEffects) {
        includeWorkInProgressEffects = includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 10256);
        for (parentFiber = parentFiber.child; null !== parentFiber; ) {
          var finishedRoot = finishedRoot$jscomp$0, finishedWork = parentFiber, committedLanes = committedLanes$jscomp$0, committedTransitions = committedTransitions$jscomp$0, flags = finishedWork.flags;
          switch (finishedWork.tag) {
            case 0:
            case 11:
            case 15:
              recursivelyTraverseReconnectPassiveEffects(
                finishedRoot,
                finishedWork,
                committedLanes,
                committedTransitions,
                includeWorkInProgressEffects
              );
              commitHookEffectListMount(8, finishedWork);
              break;
            case 23:
              break;
            case 22:
              var instance = finishedWork.stateNode;
              null !== finishedWork.memoizedState ? instance._visibility & 2 ? recursivelyTraverseReconnectPassiveEffects(
                finishedRoot,
                finishedWork,
                committedLanes,
                committedTransitions,
                includeWorkInProgressEffects
              ) : recursivelyTraverseAtomicPassiveEffects(
                finishedRoot,
                finishedWork
              ) : (instance._visibility |= 2, recursivelyTraverseReconnectPassiveEffects(
                finishedRoot,
                finishedWork,
                committedLanes,
                committedTransitions,
                includeWorkInProgressEffects
              ));
              includeWorkInProgressEffects && flags & 2048 && commitOffscreenPassiveMountEffects(
                finishedWork.alternate,
                finishedWork
              );
              break;
            case 24:
              recursivelyTraverseReconnectPassiveEffects(
                finishedRoot,
                finishedWork,
                committedLanes,
                committedTransitions,
                includeWorkInProgressEffects
              );
              includeWorkInProgressEffects && flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
              break;
            default:
              recursivelyTraverseReconnectPassiveEffects(
                finishedRoot,
                finishedWork,
                committedLanes,
                committedTransitions,
                includeWorkInProgressEffects
              );
          }
          parentFiber = parentFiber.sibling;
        }
      }
      __name(recursivelyTraverseReconnectPassiveEffects, "recursivelyTraverseReconnectPassiveEffects");
      function recursivelyTraverseAtomicPassiveEffects(finishedRoot$jscomp$0, parentFiber) {
        if (parentFiber.subtreeFlags & 10256)
          for (parentFiber = parentFiber.child; null !== parentFiber; ) {
            var finishedRoot = finishedRoot$jscomp$0, finishedWork = parentFiber, flags = finishedWork.flags;
            switch (finishedWork.tag) {
              case 22:
                recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
                flags & 2048 && commitOffscreenPassiveMountEffects(
                  finishedWork.alternate,
                  finishedWork
                );
                break;
              case 24:
                recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
                flags & 2048 && commitCachePassiveMountEffect(
                  finishedWork.alternate,
                  finishedWork
                );
                break;
              default:
                recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
            }
            parentFiber = parentFiber.sibling;
          }
      }
      __name(recursivelyTraverseAtomicPassiveEffects, "recursivelyTraverseAtomicPassiveEffects");
      function recursivelyAccumulateSuspenseyCommit(parentFiber) {
        if (parentFiber.subtreeFlags & suspenseyCommitFlag)
          for (parentFiber = parentFiber.child; null !== parentFiber; )
            accumulateSuspenseyCommitOnFiber(parentFiber), parentFiber = parentFiber.sibling;
      }
      __name(recursivelyAccumulateSuspenseyCommit, "recursivelyAccumulateSuspenseyCommit");
      function accumulateSuspenseyCommitOnFiber(fiber) {
        switch (fiber.tag) {
          case 26:
            recursivelyAccumulateSuspenseyCommit(fiber);
            fiber.flags & suspenseyCommitFlag && (null !== fiber.memoizedState ? suspendResource(
              currentHoistableRoot,
              fiber.memoizedState,
              fiber.memoizedProps
            ) : suspendInstance(fiber.type, fiber.memoizedProps));
            break;
          case 5:
            recursivelyAccumulateSuspenseyCommit(fiber);
            fiber.flags & suspenseyCommitFlag && suspendInstance(fiber.type, fiber.memoizedProps);
            break;
          case 3:
          case 4:
            if (supportsResources) {
              var previousHoistableRoot = currentHoistableRoot;
              currentHoistableRoot = getHoistableRoot(
                fiber.stateNode.containerInfo
              );
              recursivelyAccumulateSuspenseyCommit(fiber);
              currentHoistableRoot = previousHoistableRoot;
            } else recursivelyAccumulateSuspenseyCommit(fiber);
            break;
          case 22:
            null === fiber.memoizedState && (previousHoistableRoot = fiber.alternate, null !== previousHoistableRoot && null !== previousHoistableRoot.memoizedState ? (previousHoistableRoot = suspenseyCommitFlag, suspenseyCommitFlag = 16777216, recursivelyAccumulateSuspenseyCommit(fiber), suspenseyCommitFlag = previousHoistableRoot) : recursivelyAccumulateSuspenseyCommit(fiber));
            break;
          default:
            recursivelyAccumulateSuspenseyCommit(fiber);
        }
      }
      __name(accumulateSuspenseyCommitOnFiber, "accumulateSuspenseyCommitOnFiber");
      function detachAlternateSiblings(parentFiber) {
        var previousFiber = parentFiber.alternate;
        if (null !== previousFiber && (parentFiber = previousFiber.child, null !== parentFiber)) {
          previousFiber.child = null;
          do
            previousFiber = parentFiber.sibling, parentFiber.sibling = null, parentFiber = previousFiber;
          while (null !== parentFiber);
        }
      }
      __name(detachAlternateSiblings, "detachAlternateSiblings");
      function recursivelyTraversePassiveUnmountEffects(parentFiber) {
        var deletions = parentFiber.deletions;
        if (0 !== (parentFiber.flags & 16)) {
          if (null !== deletions)
            for (var i = 0; i < deletions.length; i++) {
              var childToDelete = deletions[i];
              nextEffect = childToDelete;
              commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
                childToDelete,
                parentFiber
              );
            }
          detachAlternateSiblings(parentFiber);
        }
        if (parentFiber.subtreeFlags & 10256)
          for (parentFiber = parentFiber.child; null !== parentFiber; )
            commitPassiveUnmountOnFiber(parentFiber), parentFiber = parentFiber.sibling;
      }
      __name(recursivelyTraversePassiveUnmountEffects, "recursivelyTraversePassiveUnmountEffects");
      function commitPassiveUnmountOnFiber(finishedWork) {
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            recursivelyTraversePassiveUnmountEffects(finishedWork);
            finishedWork.flags & 2048 && commitHookEffectListUnmount(9, finishedWork, finishedWork.return);
            break;
          case 3:
            recursivelyTraversePassiveUnmountEffects(finishedWork);
            break;
          case 12:
            recursivelyTraversePassiveUnmountEffects(finishedWork);
            break;
          case 22:
            var instance = finishedWork.stateNode;
            null !== finishedWork.memoizedState && instance._visibility & 2 && (null === finishedWork.return || 13 !== finishedWork.return.tag) ? (instance._visibility &= -3, recursivelyTraverseDisconnectPassiveEffects(finishedWork)) : recursivelyTraversePassiveUnmountEffects(finishedWork);
            break;
          default:
            recursivelyTraversePassiveUnmountEffects(finishedWork);
        }
      }
      __name(commitPassiveUnmountOnFiber, "commitPassiveUnmountOnFiber");
      function recursivelyTraverseDisconnectPassiveEffects(parentFiber) {
        var deletions = parentFiber.deletions;
        if (0 !== (parentFiber.flags & 16)) {
          if (null !== deletions)
            for (var i = 0; i < deletions.length; i++) {
              var childToDelete = deletions[i];
              nextEffect = childToDelete;
              commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
                childToDelete,
                parentFiber
              );
            }
          detachAlternateSiblings(parentFiber);
        }
        for (parentFiber = parentFiber.child; null !== parentFiber; ) {
          deletions = parentFiber;
          switch (deletions.tag) {
            case 0:
            case 11:
            case 15:
              commitHookEffectListUnmount(8, deletions, deletions.return);
              recursivelyTraverseDisconnectPassiveEffects(deletions);
              break;
            case 22:
              i = deletions.stateNode;
              i._visibility & 2 && (i._visibility &= -3, recursivelyTraverseDisconnectPassiveEffects(deletions));
              break;
            default:
              recursivelyTraverseDisconnectPassiveEffects(deletions);
          }
          parentFiber = parentFiber.sibling;
        }
      }
      __name(recursivelyTraverseDisconnectPassiveEffects, "recursivelyTraverseDisconnectPassiveEffects");
      function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) {
        for (; null !== nextEffect; ) {
          var fiber = nextEffect;
          switch (fiber.tag) {
            case 0:
            case 11:
            case 15:
              commitHookEffectListUnmount(8, fiber, nearestMountedAncestor);
              break;
            case 23:
            case 22:
              if (null !== fiber.memoizedState && null !== fiber.memoizedState.cachePool) {
                var cache5 = fiber.memoizedState.cachePool.pool;
                null != cache5 && cache5.refCount++;
              }
              break;
            case 24:
              releaseCache(fiber.memoizedState.cache);
          }
          cache5 = fiber.child;
          if (null !== cache5) cache5.return = fiber, nextEffect = cache5;
          else
            a: for (fiber = deletedSubtreeRoot; null !== nextEffect; ) {
              cache5 = nextEffect;
              var sibling = cache5.sibling, returnFiber = cache5.return;
              detachFiberAfterEffects(cache5);
              if (cache5 === fiber) {
                nextEffect = null;
                break a;
              }
              if (null !== sibling) {
                sibling.return = returnFiber;
                nextEffect = sibling;
                break a;
              }
              nextEffect = returnFiber;
            }
        }
      }
      __name(commitPassiveUnmountEffectsInsideOfDeletedTree_begin, "commitPassiveUnmountEffectsInsideOfDeletedTree_begin");
      function findFiberRootForHostRoot(hostRoot) {
        var maybeFiber = getInstanceFromNode(hostRoot);
        if (null != maybeFiber) {
          if ("string" !== typeof maybeFiber.memoizedProps["data-testname"])
            throw Error(formatProdErrorMessage(364));
          return maybeFiber;
        }
        hostRoot = findFiberRoot(hostRoot);
        if (null === hostRoot) throw Error(formatProdErrorMessage(362));
        return hostRoot.stateNode.current;
      }
      __name(findFiberRootForHostRoot, "findFiberRootForHostRoot");
      function matchSelector(fiber$jscomp$0, selector) {
        var tag2 = fiber$jscomp$0.tag;
        switch (selector.$$typeof) {
          case COMPONENT_TYPE:
            if (fiber$jscomp$0.type === selector.value) return true;
            break;
          case HAS_PSEUDO_CLASS_TYPE:
            a: {
              selector = selector.value;
              fiber$jscomp$0 = [fiber$jscomp$0, 0];
              for (tag2 = 0; tag2 < fiber$jscomp$0.length; ) {
                var fiber = fiber$jscomp$0[tag2++], tag$jscomp$0 = fiber.tag, selectorIndex = fiber$jscomp$0[tag2++], selector$jscomp$0 = selector[selectorIndex];
                if (5 !== tag$jscomp$0 && 26 !== tag$jscomp$0 && 27 !== tag$jscomp$0 || !isHiddenSubtree(fiber)) {
                  for (; null != selector$jscomp$0 && matchSelector(fiber, selector$jscomp$0); )
                    selectorIndex++, selector$jscomp$0 = selector[selectorIndex];
                  if (selectorIndex === selector.length) {
                    selector = true;
                    break a;
                  } else
                    for (fiber = fiber.child; null !== fiber; )
                      fiber$jscomp$0.push(fiber, selectorIndex), fiber = fiber.sibling;
                }
              }
              selector = false;
            }
            return selector;
          case ROLE_TYPE:
            if ((5 === tag2 || 26 === tag2 || 27 === tag2) && matchAccessibilityRole(fiber$jscomp$0.stateNode, selector.value))
              return true;
            break;
          case TEXT_TYPE:
            if (5 === tag2 || 6 === tag2 || 26 === tag2 || 27 === tag2) {
              if (fiber$jscomp$0 = getTextContent(fiber$jscomp$0), null !== fiber$jscomp$0 && 0 <= fiber$jscomp$0.indexOf(selector.value))
                return true;
            }
            break;
          case TEST_NAME_TYPE:
            if (5 === tag2 || 26 === tag2 || 27 === tag2) {
              if (fiber$jscomp$0 = fiber$jscomp$0.memoizedProps["data-testname"], "string" === typeof fiber$jscomp$0 && fiber$jscomp$0.toLowerCase() === selector.value.toLowerCase())
                return true;
            }
            break;
          default:
            throw Error(formatProdErrorMessage(365));
        }
        return false;
      }
      __name(matchSelector, "matchSelector");
      function selectorToString(selector) {
        switch (selector.$$typeof) {
          case COMPONENT_TYPE:
            return "<" + (getComponentNameFromType(selector.value) || "Unknown") + ">";
          case HAS_PSEUDO_CLASS_TYPE:
            return ":has(" + (selectorToString(selector) || "") + ")";
          case ROLE_TYPE:
            return '[role="' + selector.value + '"]';
          case TEXT_TYPE:
            return '"' + selector.value + '"';
          case TEST_NAME_TYPE:
            return '[data-testname="' + selector.value + '"]';
          default:
            throw Error(formatProdErrorMessage(365));
        }
      }
      __name(selectorToString, "selectorToString");
      function findPaths(root, selectors) {
        var matchingFibers = [];
        root = [root, 0];
        for (var index = 0; index < root.length; ) {
          var fiber = root[index++], tag2 = fiber.tag, selectorIndex = root[index++], selector = selectors[selectorIndex];
          if (5 !== tag2 && 26 !== tag2 && 27 !== tag2 || !isHiddenSubtree(fiber)) {
            for (; null != selector && matchSelector(fiber, selector); )
              selectorIndex++, selector = selectors[selectorIndex];
            if (selectorIndex === selectors.length) matchingFibers.push(fiber);
            else
              for (fiber = fiber.child; null !== fiber; )
                root.push(fiber, selectorIndex), fiber = fiber.sibling;
          }
        }
        return matchingFibers;
      }
      __name(findPaths, "findPaths");
      function findAllNodes(hostRoot, selectors) {
        if (!supportsTestSelectors) throw Error(formatProdErrorMessage(363));
        hostRoot = findFiberRootForHostRoot(hostRoot);
        hostRoot = findPaths(hostRoot, selectors);
        selectors = [];
        hostRoot = Array.from(hostRoot);
        for (var index = 0; index < hostRoot.length; ) {
          var node = hostRoot[index++], tag2 = node.tag;
          if (5 === tag2 || 26 === tag2 || 27 === tag2)
            isHiddenSubtree(node) || selectors.push(node.stateNode);
          else
            for (node = node.child; null !== node; )
              hostRoot.push(node), node = node.sibling;
        }
        return selectors;
      }
      __name(findAllNodes, "findAllNodes");
      function requestUpdateLane() {
        if (0 !== (executionContext & 2) && 0 !== workInProgressRootRenderLanes)
          return workInProgressRootRenderLanes & -workInProgressRootRenderLanes;
        if (null !== ReactSharedInternals.T) {
          var actionScopeLane = currentEntangledLane;
          return 0 !== actionScopeLane ? actionScopeLane : requestTransitionLane();
        }
        return resolveUpdatePriority();
      }
      __name(requestUpdateLane, "requestUpdateLane");
      function requestDeferredLane() {
        0 === workInProgressDeferredLane && (workInProgressDeferredLane = 0 === (workInProgressRootRenderLanes & 536870912) || isHydrating ? claimNextTransitionLane() : 536870912);
        var suspenseHandler = suspenseHandlerStackCursor.current;
        null !== suspenseHandler && (suspenseHandler.flags |= 32);
        return workInProgressDeferredLane;
      }
      __name(requestDeferredLane, "requestDeferredLane");
      function scheduleUpdateOnFiber(root, fiber, lane) {
        if (root === workInProgressRoot && (2 === workInProgressSuspendedReason || 9 === workInProgressSuspendedReason) || null !== root.cancelPendingCommit)
          prepareFreshStack(root, 0), markRootSuspended(
            root,
            workInProgressRootRenderLanes,
            workInProgressDeferredLane,
            false
          );
        markRootUpdated$1(root, lane);
        if (0 === (executionContext & 2) || root !== workInProgressRoot)
          root === workInProgressRoot && (0 === (executionContext & 2) && (workInProgressRootInterleavedUpdatedLanes |= lane), 4 === workInProgressRootExitStatus && markRootSuspended(
            root,
            workInProgressRootRenderLanes,
            workInProgressDeferredLane,
            false
          )), ensureRootIsScheduled(root);
      }
      __name(scheduleUpdateOnFiber, "scheduleUpdateOnFiber");
      function performWorkOnRoot(root$jscomp$0, lanes, forceSync) {
        if (0 !== (executionContext & 6)) throw Error(formatProdErrorMessage(327));
        var shouldTimeSlice = !forceSync && 0 === (lanes & 124) && 0 === (lanes & root$jscomp$0.expiredLanes) || checkIfRootIsPrerendering(root$jscomp$0, lanes), exitStatus = shouldTimeSlice ? renderRootConcurrent(root$jscomp$0, lanes) : renderRootSync(root$jscomp$0, lanes, true), renderWasConcurrent = shouldTimeSlice;
        do {
          if (0 === exitStatus) {
            workInProgressRootIsPrerendering && !shouldTimeSlice && markRootSuspended(root$jscomp$0, lanes, 0, false);
            break;
          } else {
            forceSync = root$jscomp$0.current.alternate;
            if (renderWasConcurrent && !isRenderConsistentWithExternalStores(forceSync)) {
              exitStatus = renderRootSync(root$jscomp$0, lanes, false);
              renderWasConcurrent = false;
              continue;
            }
            if (2 === exitStatus) {
              renderWasConcurrent = lanes;
              if (root$jscomp$0.errorRecoveryDisabledLanes & renderWasConcurrent)
                var JSCompiler_inline_result = 0;
              else
                JSCompiler_inline_result = root$jscomp$0.pendingLanes & -536870913, JSCompiler_inline_result = 0 !== JSCompiler_inline_result ? JSCompiler_inline_result : JSCompiler_inline_result & 536870912 ? 536870912 : 0;
              if (0 !== JSCompiler_inline_result) {
                lanes = JSCompiler_inline_result;
                a: {
                  var root = root$jscomp$0;
                  exitStatus = workInProgressRootConcurrentErrors;
                  var wasRootDehydrated = supportsHydration && root.current.memoizedState.isDehydrated;
                  wasRootDehydrated && (prepareFreshStack(root, JSCompiler_inline_result).flags |= 256);
                  JSCompiler_inline_result = renderRootSync(
                    root,
                    JSCompiler_inline_result,
                    false
                  );
                  if (2 !== JSCompiler_inline_result) {
                    if (workInProgressRootDidAttachPingListener && !wasRootDehydrated) {
                      root.errorRecoveryDisabledLanes |= renderWasConcurrent;
                      workInProgressRootInterleavedUpdatedLanes |= renderWasConcurrent;
                      exitStatus = 4;
                      break a;
                    }
                    renderWasConcurrent = workInProgressRootRecoverableErrors;
                    workInProgressRootRecoverableErrors = exitStatus;
                    null !== renderWasConcurrent && (null === workInProgressRootRecoverableErrors ? workInProgressRootRecoverableErrors = renderWasConcurrent : workInProgressRootRecoverableErrors.push.apply(
                      workInProgressRootRecoverableErrors,
                      renderWasConcurrent
                    ));
                  }
                  exitStatus = JSCompiler_inline_result;
                }
                renderWasConcurrent = false;
                if (2 !== exitStatus) continue;
              }
            }
            if (1 === exitStatus) {
              prepareFreshStack(root$jscomp$0, 0);
              markRootSuspended(root$jscomp$0, lanes, 0, true);
              break;
            }
            a: {
              shouldTimeSlice = root$jscomp$0;
              renderWasConcurrent = exitStatus;
              switch (renderWasConcurrent) {
                case 0:
                case 1:
                  throw Error(formatProdErrorMessage(345));
                case 4:
                  if ((lanes & 4194048) !== lanes) break;
                case 6:
                  markRootSuspended(
                    shouldTimeSlice,
                    lanes,
                    workInProgressDeferredLane,
                    !workInProgressRootDidSkipSuspendedSiblings
                  );
                  break a;
                case 2:
                  workInProgressRootRecoverableErrors = null;
                  break;
                case 3:
                case 5:
                  break;
                default:
                  throw Error(formatProdErrorMessage(329));
              }
              if ((lanes & 62914560) === lanes && (exitStatus = globalMostRecentFallbackTime + 300 - now(), 10 < exitStatus)) {
                markRootSuspended(
                  shouldTimeSlice,
                  lanes,
                  workInProgressDeferredLane,
                  !workInProgressRootDidSkipSuspendedSiblings
                );
                if (0 !== getNextLanes(shouldTimeSlice, 0, true)) break a;
                shouldTimeSlice.timeoutHandle = scheduleTimeout(
                  commitRootWhenReady.bind(
                    null,
                    shouldTimeSlice,
                    forceSync,
                    workInProgressRootRecoverableErrors,
                    workInProgressTransitions,
                    workInProgressRootDidIncludeRecursiveRenderUpdate,
                    lanes,
                    workInProgressDeferredLane,
                    workInProgressRootInterleavedUpdatedLanes,
                    workInProgressSuspendedRetryLanes,
                    workInProgressRootDidSkipSuspendedSiblings,
                    renderWasConcurrent,
                    2,
                    -0,
                    0
                  ),
                  exitStatus
                );
                break a;
              }
              commitRootWhenReady(
                shouldTimeSlice,
                forceSync,
                workInProgressRootRecoverableErrors,
                workInProgressTransitions,
                workInProgressRootDidIncludeRecursiveRenderUpdate,
                lanes,
                workInProgressDeferredLane,
                workInProgressRootInterleavedUpdatedLanes,
                workInProgressSuspendedRetryLanes,
                workInProgressRootDidSkipSuspendedSiblings,
                renderWasConcurrent,
                0,
                -0,
                0
              );
            }
          }
          break;
        } while (1);
        ensureRootIsScheduled(root$jscomp$0);
      }
      __name(performWorkOnRoot, "performWorkOnRoot");
      function commitRootWhenReady(root, finishedWork, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, lanes, spawnedLane, updatedLanes, suspendedRetryLanes, didSkipSuspendedSiblings, exitStatus, suspendedCommitReason, completedRenderStartTime, completedRenderEndTime) {
        root.timeoutHandle = noTimeout;
        suspendedCommitReason = finishedWork.subtreeFlags;
        if (suspendedCommitReason & 8192 || 16785408 === (suspendedCommitReason & 16785408)) {
          if (startSuspendingCommit(), accumulateSuspenseyCommitOnFiber(finishedWork), suspendedCommitReason = waitForCommitToBeReady(), null !== suspendedCommitReason) {
            root.cancelPendingCommit = suspendedCommitReason(
              commitRoot.bind(
                null,
                root,
                finishedWork,
                lanes,
                recoverableErrors,
                transitions,
                didIncludeRenderPhaseUpdate,
                spawnedLane,
                updatedLanes,
                suspendedRetryLanes,
                exitStatus,
                1,
                completedRenderStartTime,
                completedRenderEndTime
              )
            );
            markRootSuspended(root, lanes, spawnedLane, !didSkipSuspendedSiblings);
            return;
          }
        }
        commitRoot(
          root,
          finishedWork,
          lanes,
          recoverableErrors,
          transitions,
          didIncludeRenderPhaseUpdate,
          spawnedLane,
          updatedLanes,
          suspendedRetryLanes
        );
      }
      __name(commitRootWhenReady, "commitRootWhenReady");
      function isRenderConsistentWithExternalStores(finishedWork) {
        for (var node = finishedWork; ; ) {
          var tag2 = node.tag;
          if ((0 === tag2 || 11 === tag2 || 15 === tag2) && node.flags & 16384 && (tag2 = node.updateQueue, null !== tag2 && (tag2 = tag2.stores, null !== tag2)))
            for (var i = 0; i < tag2.length; i++) {
              var check = tag2[i], getSnapshot = check.getSnapshot;
              check = check.value;
              try {
                if (!objectIs(getSnapshot(), check)) return false;
              } catch (error) {
                return false;
              }
            }
          tag2 = node.child;
          if (node.subtreeFlags & 16384 && null !== tag2)
            tag2.return = node, node = tag2;
          else {
            if (node === finishedWork) break;
            for (; null === node.sibling; ) {
              if (null === node.return || node.return === finishedWork) return true;
              node = node.return;
            }
            node.sibling.return = node.return;
            node = node.sibling;
          }
        }
        return true;
      }
      __name(isRenderConsistentWithExternalStores, "isRenderConsistentWithExternalStores");
      function markRootSuspended(root, suspendedLanes, spawnedLane, didAttemptEntireTree) {
        suspendedLanes &= ~workInProgressRootPingedLanes;
        suspendedLanes &= ~workInProgressRootInterleavedUpdatedLanes;
        root.suspendedLanes |= suspendedLanes;
        root.pingedLanes &= ~suspendedLanes;
        didAttemptEntireTree && (root.warmLanes |= suspendedLanes);
        didAttemptEntireTree = root.expirationTimes;
        for (var lanes = suspendedLanes; 0 < lanes; ) {
          var index$4 = 31 - clz32(lanes), lane = 1 << index$4;
          didAttemptEntireTree[index$4] = -1;
          lanes &= ~lane;
        }
        0 !== spawnedLane && markSpawnedDeferredLane(root, spawnedLane, suspendedLanes);
      }
      __name(markRootSuspended, "markRootSuspended");
      function flushSyncWork() {
        return 0 === (executionContext & 6) ? (flushSyncWorkAcrossRoots_impl(0, false), false) : true;
      }
      __name(flushSyncWork, "flushSyncWork");
      function resetWorkInProgressStack() {
        if (null !== workInProgress) {
          if (0 === workInProgressSuspendedReason)
            var interruptedWork = workInProgress.return;
          else
            interruptedWork = workInProgress, lastContextDependency = currentlyRenderingFiber$1 = null, resetHooksOnUnwind(interruptedWork), thenableState = null, thenableIndexCounter = 0, interruptedWork = workInProgress;
          for (; null !== interruptedWork; )
            unwindInterruptedWork(interruptedWork.alternate, interruptedWork), interruptedWork = interruptedWork.return;
          workInProgress = null;
        }
      }
      __name(resetWorkInProgressStack, "resetWorkInProgressStack");
      function prepareFreshStack(root, lanes) {
        var timeoutHandle = root.timeoutHandle;
        timeoutHandle !== noTimeout && (root.timeoutHandle = noTimeout, cancelTimeout(timeoutHandle));
        timeoutHandle = root.cancelPendingCommit;
        null !== timeoutHandle && (root.cancelPendingCommit = null, timeoutHandle());
        resetWorkInProgressStack();
        workInProgressRoot = root;
        workInProgress = timeoutHandle = createWorkInProgress(root.current, null);
        workInProgressRootRenderLanes = lanes;
        workInProgressSuspendedReason = 0;
        workInProgressThrownValue = null;
        workInProgressRootDidSkipSuspendedSiblings = false;
        workInProgressRootIsPrerendering = checkIfRootIsPrerendering(root, lanes);
        workInProgressRootDidAttachPingListener = false;
        workInProgressSuspendedRetryLanes = workInProgressDeferredLane = workInProgressRootPingedLanes = workInProgressRootInterleavedUpdatedLanes = workInProgressRootSkippedLanes = workInProgressRootExitStatus = 0;
        workInProgressRootRecoverableErrors = workInProgressRootConcurrentErrors = null;
        workInProgressRootDidIncludeRecursiveRenderUpdate = false;
        0 !== (lanes & 8) && (lanes |= lanes & 32);
        var allEntangledLanes = root.entangledLanes;
        if (0 !== allEntangledLanes)
          for (root = root.entanglements, allEntangledLanes &= lanes; 0 < allEntangledLanes; ) {
            var index$2 = 31 - clz32(allEntangledLanes), lane = 1 << index$2;
            lanes |= root[index$2];
            allEntangledLanes &= ~lane;
          }
        entangledRenderLanes = lanes;
        finishQueueingConcurrentUpdates();
        return timeoutHandle;
      }
      __name(prepareFreshStack, "prepareFreshStack");
      function handleThrow(root, thrownValue) {
        currentlyRenderingFiber = null;
        ReactSharedInternals.H = ContextOnlyDispatcher;
        thrownValue === SuspenseException || thrownValue === SuspenseActionException ? (thrownValue = getSuspendedThenable(), workInProgressSuspendedReason = 3) : thrownValue === SuspenseyCommitException ? (thrownValue = getSuspendedThenable(), workInProgressSuspendedReason = 4) : workInProgressSuspendedReason = thrownValue === SelectiveHydrationException ? 8 : null !== thrownValue && "object" === typeof thrownValue && "function" === typeof thrownValue.then ? 6 : 1;
        workInProgressThrownValue = thrownValue;
        null === workInProgress && (workInProgressRootExitStatus = 1, logUncaughtError(
          root,
          createCapturedValueAtFiber(thrownValue, root.current)
        ));
      }
      __name(handleThrow, "handleThrow");
      function shouldRemainOnPreviousScreen() {
        var handler = suspenseHandlerStackCursor.current;
        return null === handler ? true : (workInProgressRootRenderLanes & 4194048) === workInProgressRootRenderLanes ? null === shellBoundary ? true : false : (workInProgressRootRenderLanes & 62914560) === workInProgressRootRenderLanes || 0 !== (workInProgressRootRenderLanes & 536870912) ? handler === shellBoundary : false;
      }
      __name(shouldRemainOnPreviousScreen, "shouldRemainOnPreviousScreen");
      function pushDispatcher() {
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = ContextOnlyDispatcher;
        return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher;
      }
      __name(pushDispatcher, "pushDispatcher");
      function pushAsyncDispatcher() {
        var prevAsyncDispatcher = ReactSharedInternals.A;
        ReactSharedInternals.A = DefaultAsyncDispatcher;
        return prevAsyncDispatcher;
      }
      __name(pushAsyncDispatcher, "pushAsyncDispatcher");
      function renderDidSuspendDelayIfPossible() {
        workInProgressRootExitStatus = 4;
        workInProgressRootDidSkipSuspendedSiblings || (workInProgressRootRenderLanes & 4194048) !== workInProgressRootRenderLanes && null !== suspenseHandlerStackCursor.current || (workInProgressRootIsPrerendering = true);
        0 === (workInProgressRootSkippedLanes & 134217727) && 0 === (workInProgressRootInterleavedUpdatedLanes & 134217727) || null === workInProgressRoot || markRootSuspended(
          workInProgressRoot,
          workInProgressRootRenderLanes,
          workInProgressDeferredLane,
          false
        );
      }
      __name(renderDidSuspendDelayIfPossible, "renderDidSuspendDelayIfPossible");
      function renderRootSync(root, lanes, shouldYieldForPrerendering) {
        var prevExecutionContext = executionContext;
        executionContext |= 2;
        var prevDispatcher = pushDispatcher(), prevAsyncDispatcher = pushAsyncDispatcher();
        if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes)
          workInProgressTransitions = null, prepareFreshStack(root, lanes);
        lanes = false;
        var exitStatus = workInProgressRootExitStatus;
        a: do
          try {
            if (0 !== workInProgressSuspendedReason && null !== workInProgress) {
              var unitOfWork = workInProgress, thrownValue = workInProgressThrownValue;
              switch (workInProgressSuspendedReason) {
                case 8:
                  resetWorkInProgressStack();
                  exitStatus = 6;
                  break a;
                case 3:
                case 2:
                case 9:
                case 6:
                  null === suspenseHandlerStackCursor.current && (lanes = true);
                  var reason = workInProgressSuspendedReason;
                  workInProgressSuspendedReason = 0;
                  workInProgressThrownValue = null;
                  throwAndUnwindWorkLoop(root, unitOfWork, thrownValue, reason);
                  if (shouldYieldForPrerendering && workInProgressRootIsPrerendering) {
                    exitStatus = 0;
                    break a;
                  }
                  break;
                default:
                  reason = workInProgressSuspendedReason, workInProgressSuspendedReason = 0, workInProgressThrownValue = null, throwAndUnwindWorkLoop(root, unitOfWork, thrownValue, reason);
              }
            }
            workLoopSync();
            exitStatus = workInProgressRootExitStatus;
            break;
          } catch (thrownValue$155) {
            handleThrow(root, thrownValue$155);
          }
        while (1);
        lanes && root.shellSuspendCounter++;
        lastContextDependency = currentlyRenderingFiber$1 = null;
        executionContext = prevExecutionContext;
        ReactSharedInternals.H = prevDispatcher;
        ReactSharedInternals.A = prevAsyncDispatcher;
        null === workInProgress && (workInProgressRoot = null, workInProgressRootRenderLanes = 0, finishQueueingConcurrentUpdates());
        return exitStatus;
      }
      __name(renderRootSync, "renderRootSync");
      function workLoopSync() {
        for (; null !== workInProgress; ) performUnitOfWork(workInProgress);
      }
      __name(workLoopSync, "workLoopSync");
      function renderRootConcurrent(root, lanes) {
        var prevExecutionContext = executionContext;
        executionContext |= 2;
        var prevDispatcher = pushDispatcher(), prevAsyncDispatcher = pushAsyncDispatcher();
        workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes ? (workInProgressTransitions = null, workInProgressRootRenderTargetTime = now() + 500, prepareFreshStack(root, lanes)) : workInProgressRootIsPrerendering = checkIfRootIsPrerendering(
          root,
          lanes
        );
        a: do
          try {
            if (0 !== workInProgressSuspendedReason && null !== workInProgress) {
              lanes = workInProgress;
              var thrownValue = workInProgressThrownValue;
              b: switch (workInProgressSuspendedReason) {
                case 1:
                  workInProgressSuspendedReason = 0;
                  workInProgressThrownValue = null;
                  throwAndUnwindWorkLoop(root, lanes, thrownValue, 1);
                  break;
                case 2:
                case 9:
                  if (isThenableResolved(thrownValue)) {
                    workInProgressSuspendedReason = 0;
                    workInProgressThrownValue = null;
                    replaySuspendedUnitOfWork(lanes);
                    break;
                  }
                  lanes = /* @__PURE__ */ __name(function() {
                    2 !== workInProgressSuspendedReason && 9 !== workInProgressSuspendedReason || workInProgressRoot !== root || (workInProgressSuspendedReason = 7);
                    ensureRootIsScheduled(root);
                  }, "lanes");
                  thrownValue.then(lanes, lanes);
                  break a;
                case 3:
                  workInProgressSuspendedReason = 7;
                  break a;
                case 4:
                  workInProgressSuspendedReason = 5;
                  break a;
                case 7:
                  isThenableResolved(thrownValue) ? (workInProgressSuspendedReason = 0, workInProgressThrownValue = null, replaySuspendedUnitOfWork(lanes)) : (workInProgressSuspendedReason = 0, workInProgressThrownValue = null, throwAndUnwindWorkLoop(root, lanes, thrownValue, 7));
                  break;
                case 5:
                  var resource = null;
                  switch (workInProgress.tag) {
                    case 26:
                      resource = workInProgress.memoizedState;
                    case 5:
                    case 27:
                      var hostFiber = workInProgress, type = hostFiber.type, props = hostFiber.pendingProps;
                      if (resource ? preloadResource(resource) : preloadInstance(type, props)) {
                        workInProgressSuspendedReason = 0;
                        workInProgressThrownValue = null;
                        var sibling = hostFiber.sibling;
                        if (null !== sibling) workInProgress = sibling;
                        else {
                          var returnFiber = hostFiber.return;
                          null !== returnFiber ? (workInProgress = returnFiber, completeUnitOfWork(returnFiber)) : workInProgress = null;
                        }
                        break b;
                      }
                  }
                  workInProgressSuspendedReason = 0;
                  workInProgressThrownValue = null;
                  throwAndUnwindWorkLoop(root, lanes, thrownValue, 5);
                  break;
                case 6:
                  workInProgressSuspendedReason = 0;
                  workInProgressThrownValue = null;
                  throwAndUnwindWorkLoop(root, lanes, thrownValue, 6);
                  break;
                case 8:
                  resetWorkInProgressStack();
                  workInProgressRootExitStatus = 6;
                  break a;
                default:
                  throw Error(formatProdErrorMessage(462));
              }
            }
            workLoopConcurrentByScheduler();
            break;
          } catch (thrownValue$157) {
            handleThrow(root, thrownValue$157);
          }
        while (1);
        lastContextDependency = currentlyRenderingFiber$1 = null;
        ReactSharedInternals.H = prevDispatcher;
        ReactSharedInternals.A = prevAsyncDispatcher;
        executionContext = prevExecutionContext;
        if (null !== workInProgress) return 0;
        workInProgressRoot = null;
        workInProgressRootRenderLanes = 0;
        finishQueueingConcurrentUpdates();
        return workInProgressRootExitStatus;
      }
      __name(renderRootConcurrent, "renderRootConcurrent");
      function workLoopConcurrentByScheduler() {
        for (; null !== workInProgress && !shouldYield(); )
          performUnitOfWork(workInProgress);
      }
      __name(workLoopConcurrentByScheduler, "workLoopConcurrentByScheduler");
      function performUnitOfWork(unitOfWork) {
        var next = beginWork(
          unitOfWork.alternate,
          unitOfWork,
          entangledRenderLanes
        );
        unitOfWork.memoizedProps = unitOfWork.pendingProps;
        null === next ? completeUnitOfWork(unitOfWork) : workInProgress = next;
      }
      __name(performUnitOfWork, "performUnitOfWork");
      function replaySuspendedUnitOfWork(unitOfWork) {
        var next = unitOfWork;
        var current = next.alternate;
        switch (next.tag) {
          case 15:
          case 0:
            next = replayFunctionComponent(
              current,
              next,
              next.pendingProps,
              next.type,
              void 0,
              workInProgressRootRenderLanes
            );
            break;
          case 11:
            next = replayFunctionComponent(
              current,
              next,
              next.pendingProps,
              next.type.render,
              next.ref,
              workInProgressRootRenderLanes
            );
            break;
          case 5:
            resetHooksOnUnwind(next);
          default:
            unwindInterruptedWork(current, next), next = workInProgress = resetWorkInProgress(next, entangledRenderLanes), next = beginWork(current, next, entangledRenderLanes);
        }
        unitOfWork.memoizedProps = unitOfWork.pendingProps;
        null === next ? completeUnitOfWork(unitOfWork) : workInProgress = next;
      }
      __name(replaySuspendedUnitOfWork, "replaySuspendedUnitOfWork");
      function throwAndUnwindWorkLoop(root, unitOfWork, thrownValue, suspendedReason) {
        lastContextDependency = currentlyRenderingFiber$1 = null;
        resetHooksOnUnwind(unitOfWork);
        thenableState = null;
        thenableIndexCounter = 0;
        var returnFiber = unitOfWork.return;
        try {
          if (throwException(
            root,
            returnFiber,
            unitOfWork,
            thrownValue,
            workInProgressRootRenderLanes
          )) {
            workInProgressRootExitStatus = 1;
            logUncaughtError(
              root,
              createCapturedValueAtFiber(thrownValue, root.current)
            );
            workInProgress = null;
            return;
          }
        } catch (error) {
          if (null !== returnFiber) throw workInProgress = returnFiber, error;
          workInProgressRootExitStatus = 1;
          logUncaughtError(
            root,
            createCapturedValueAtFiber(thrownValue, root.current)
          );
          workInProgress = null;
          return;
        }
        if (unitOfWork.flags & 32768) {
          if (isHydrating || 1 === suspendedReason) root = true;
          else if (workInProgressRootIsPrerendering || 0 !== (workInProgressRootRenderLanes & 536870912))
            root = false;
          else if (workInProgressRootDidSkipSuspendedSiblings = root = true, 2 === suspendedReason || 9 === suspendedReason || 3 === suspendedReason || 6 === suspendedReason)
            suspendedReason = suspenseHandlerStackCursor.current, null !== suspendedReason && 13 === suspendedReason.tag && (suspendedReason.flags |= 16384);
          unwindUnitOfWork(unitOfWork, root);
        } else completeUnitOfWork(unitOfWork);
      }
      __name(throwAndUnwindWorkLoop, "throwAndUnwindWorkLoop");
      function completeUnitOfWork(unitOfWork) {
        var completedWork = unitOfWork;
        do {
          if (0 !== (completedWork.flags & 32768)) {
            unwindUnitOfWork(
              completedWork,
              workInProgressRootDidSkipSuspendedSiblings
            );
            return;
          }
          unitOfWork = completedWork.return;
          var next = completeWork(
            completedWork.alternate,
            completedWork,
            entangledRenderLanes
          );
          if (null !== next) {
            workInProgress = next;
            return;
          }
          completedWork = completedWork.sibling;
          if (null !== completedWork) {
            workInProgress = completedWork;
            return;
          }
          workInProgress = completedWork = unitOfWork;
        } while (null !== completedWork);
        0 === workInProgressRootExitStatus && (workInProgressRootExitStatus = 5);
      }
      __name(completeUnitOfWork, "completeUnitOfWork");
      function unwindUnitOfWork(unitOfWork, skipSiblings) {
        do {
          var next = unwindWork(unitOfWork.alternate, unitOfWork);
          if (null !== next) {
            next.flags &= 32767;
            workInProgress = next;
            return;
          }
          next = unitOfWork.return;
          null !== next && (next.flags |= 32768, next.subtreeFlags = 0, next.deletions = null);
          if (!skipSiblings && (unitOfWork = unitOfWork.sibling, null !== unitOfWork)) {
            workInProgress = unitOfWork;
            return;
          }
          workInProgress = unitOfWork = next;
        } while (null !== unitOfWork);
        workInProgressRootExitStatus = 6;
        workInProgress = null;
      }
      __name(unwindUnitOfWork, "unwindUnitOfWork");
      function commitRoot(root, finishedWork, lanes, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, spawnedLane, updatedLanes, suspendedRetryLanes) {
        root.cancelPendingCommit = null;
        do
          flushPendingEffects();
        while (0 !== pendingEffectsStatus);
        if (0 !== (executionContext & 6)) throw Error(formatProdErrorMessage(327));
        if (null !== finishedWork) {
          if (finishedWork === root.current)
            throw Error(formatProdErrorMessage(177));
          didIncludeRenderPhaseUpdate = finishedWork.lanes | finishedWork.childLanes;
          didIncludeRenderPhaseUpdate |= concurrentlyUpdatedLanes;
          markRootFinished(
            root,
            lanes,
            didIncludeRenderPhaseUpdate,
            spawnedLane,
            updatedLanes,
            suspendedRetryLanes
          );
          root === workInProgressRoot && (workInProgress = workInProgressRoot = null, workInProgressRootRenderLanes = 0);
          pendingFinishedWork = finishedWork;
          pendingEffectsRoot = root;
          pendingEffectsLanes = lanes;
          pendingEffectsRemainingLanes = didIncludeRenderPhaseUpdate;
          pendingPassiveTransitions = transitions;
          pendingRecoverableErrors = recoverableErrors;
          0 !== (finishedWork.subtreeFlags & 10256) || 0 !== (finishedWork.flags & 10256) ? (root.callbackNode = null, root.callbackPriority = 0, scheduleCallback(NormalPriority$1, function() {
            flushPassiveEffects(true);
            return null;
          })) : (root.callbackNode = null, root.callbackPriority = 0);
          recoverableErrors = 0 !== (finishedWork.flags & 13878);
          if (0 !== (finishedWork.subtreeFlags & 13878) || recoverableErrors) {
            recoverableErrors = ReactSharedInternals.T;
            ReactSharedInternals.T = null;
            transitions = getCurrentUpdatePriority();
            setCurrentUpdatePriority(2);
            spawnedLane = executionContext;
            executionContext |= 4;
            try {
              commitBeforeMutationEffects(root, finishedWork, lanes);
            } finally {
              executionContext = spawnedLane, setCurrentUpdatePriority(transitions), ReactSharedInternals.T = recoverableErrors;
            }
          }
          pendingEffectsStatus = 1;
          flushMutationEffects();
          flushLayoutEffects();
          flushSpawnedWork();
        }
      }
      __name(commitRoot, "commitRoot");
      function flushMutationEffects() {
        if (1 === pendingEffectsStatus) {
          pendingEffectsStatus = 0;
          var root = pendingEffectsRoot, finishedWork = pendingFinishedWork, rootMutationHasEffect = 0 !== (finishedWork.flags & 13878);
          if (0 !== (finishedWork.subtreeFlags & 13878) || rootMutationHasEffect) {
            rootMutationHasEffect = ReactSharedInternals.T;
            ReactSharedInternals.T = null;
            var previousPriority = getCurrentUpdatePriority();
            setCurrentUpdatePriority(2);
            var prevExecutionContext = executionContext;
            executionContext |= 4;
            try {
              commitMutationEffectsOnFiber(finishedWork, root), resetAfterCommit(root.containerInfo);
            } finally {
              executionContext = prevExecutionContext, setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = rootMutationHasEffect;
            }
          }
          root.current = finishedWork;
          pendingEffectsStatus = 2;
        }
      }
      __name(flushMutationEffects, "flushMutationEffects");
      function flushLayoutEffects() {
        if (2 === pendingEffectsStatus) {
          pendingEffectsStatus = 0;
          var root = pendingEffectsRoot, finishedWork = pendingFinishedWork, rootHasLayoutEffect = 0 !== (finishedWork.flags & 8772);
          if (0 !== (finishedWork.subtreeFlags & 8772) || rootHasLayoutEffect) {
            rootHasLayoutEffect = ReactSharedInternals.T;
            ReactSharedInternals.T = null;
            var previousPriority = getCurrentUpdatePriority();
            setCurrentUpdatePriority(2);
            var prevExecutionContext = executionContext;
            executionContext |= 4;
            try {
              commitLayoutEffectOnFiber(root, finishedWork.alternate, finishedWork);
            } finally {
              executionContext = prevExecutionContext, setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = rootHasLayoutEffect;
            }
          }
          pendingEffectsStatus = 3;
        }
      }
      __name(flushLayoutEffects, "flushLayoutEffects");
      function flushSpawnedWork() {
        if (4 === pendingEffectsStatus || 3 === pendingEffectsStatus) {
          pendingEffectsStatus = 0;
          requestPaint();
          var root = pendingEffectsRoot, finishedWork = pendingFinishedWork, lanes = pendingEffectsLanes, recoverableErrors = pendingRecoverableErrors;
          0 !== (finishedWork.subtreeFlags & 10256) || 0 !== (finishedWork.flags & 10256) ? pendingEffectsStatus = 5 : (pendingEffectsStatus = 0, pendingFinishedWork = pendingEffectsRoot = null, releaseRootPooledCache(root, root.pendingLanes));
          var remainingLanes = root.pendingLanes;
          0 === remainingLanes && (legacyErrorBoundariesThatAlreadyFailed = null);
          lanesToEventPriority(lanes);
          finishedWork = finishedWork.stateNode;
          if (injectedHook && "function" === typeof injectedHook.onCommitFiberRoot)
            try {
              injectedHook.onCommitFiberRoot(
                rendererID,
                finishedWork,
                void 0,
                128 === (finishedWork.current.flags & 128)
              );
            } catch (err) {
            }
          if (null !== recoverableErrors) {
            finishedWork = ReactSharedInternals.T;
            remainingLanes = getCurrentUpdatePriority();
            setCurrentUpdatePriority(2);
            ReactSharedInternals.T = null;
            try {
              for (var onRecoverableError = root.onRecoverableError, i = 0; i < recoverableErrors.length; i++) {
                var recoverableError = recoverableErrors[i];
                onRecoverableError(recoverableError.value, {
                  componentStack: recoverableError.stack
                });
              }
            } finally {
              ReactSharedInternals.T = finishedWork, setCurrentUpdatePriority(remainingLanes);
            }
          }
          0 !== (pendingEffectsLanes & 3) && flushPendingEffects();
          ensureRootIsScheduled(root);
          remainingLanes = root.pendingLanes;
          0 !== (lanes & 4194090) && 0 !== (remainingLanes & 42) ? root === rootWithNestedUpdates ? nestedUpdateCount++ : (nestedUpdateCount = 0, rootWithNestedUpdates = root) : nestedUpdateCount = 0;
          flushSyncWorkAcrossRoots_impl(0, false);
        }
      }
      __name(flushSpawnedWork, "flushSpawnedWork");
      function releaseRootPooledCache(root, remainingLanes) {
        0 === (root.pooledCacheLanes &= remainingLanes) && (remainingLanes = root.pooledCache, null != remainingLanes && (root.pooledCache = null, releaseCache(remainingLanes)));
      }
      __name(releaseRootPooledCache, "releaseRootPooledCache");
      function flushPendingEffects(wasDelayedCommit) {
        flushMutationEffects();
        flushLayoutEffects();
        flushSpawnedWork();
        return flushPassiveEffects(wasDelayedCommit);
      }
      __name(flushPendingEffects, "flushPendingEffects");
      function flushPassiveEffects() {
        if (5 !== pendingEffectsStatus) return false;
        var root = pendingEffectsRoot, remainingLanes = pendingEffectsRemainingLanes;
        pendingEffectsRemainingLanes = 0;
        var renderPriority = lanesToEventPriority(pendingEffectsLanes), priority = 32 > renderPriority ? 32 : renderPriority;
        renderPriority = ReactSharedInternals.T;
        var previousPriority = getCurrentUpdatePriority();
        try {
          setCurrentUpdatePriority(priority);
          ReactSharedInternals.T = null;
          priority = pendingPassiveTransitions;
          pendingPassiveTransitions = null;
          var root$jscomp$0 = pendingEffectsRoot, lanes = pendingEffectsLanes;
          pendingEffectsStatus = 0;
          pendingFinishedWork = pendingEffectsRoot = null;
          pendingEffectsLanes = 0;
          if (0 !== (executionContext & 6))
            throw Error(formatProdErrorMessage(331));
          var prevExecutionContext = executionContext;
          executionContext |= 4;
          commitPassiveUnmountOnFiber(root$jscomp$0.current);
          commitPassiveMountOnFiber(
            root$jscomp$0,
            root$jscomp$0.current,
            lanes,
            priority
          );
          executionContext = prevExecutionContext;
          flushSyncWorkAcrossRoots_impl(0, false);
          if (injectedHook && "function" === typeof injectedHook.onPostCommitFiberRoot)
            try {
              injectedHook.onPostCommitFiberRoot(rendererID, root$jscomp$0);
            } catch (err) {
            }
          return true;
        } finally {
          setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = renderPriority, releaseRootPooledCache(root, remainingLanes);
        }
      }
      __name(flushPassiveEffects, "flushPassiveEffects");
      function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
        sourceFiber = createCapturedValueAtFiber(error, sourceFiber);
        sourceFiber = createRootErrorUpdate(rootFiber.stateNode, sourceFiber, 2);
        rootFiber = enqueueUpdate(rootFiber, sourceFiber, 2);
        null !== rootFiber && (markRootUpdated$1(rootFiber, 2), ensureRootIsScheduled(rootFiber));
      }
      __name(captureCommitPhaseErrorOnRoot, "captureCommitPhaseErrorOnRoot");
      function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error) {
        if (3 === sourceFiber.tag)
          captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
        else
          for (; null !== nearestMountedAncestor; ) {
            if (3 === nearestMountedAncestor.tag) {
              captureCommitPhaseErrorOnRoot(
                nearestMountedAncestor,
                sourceFiber,
                error
              );
              break;
            } else if (1 === nearestMountedAncestor.tag) {
              var instance = nearestMountedAncestor.stateNode;
              if ("function" === typeof nearestMountedAncestor.type.getDerivedStateFromError || "function" === typeof instance.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(instance))) {
                sourceFiber = createCapturedValueAtFiber(error, sourceFiber);
                error = createClassErrorUpdate(2);
                instance = enqueueUpdate(nearestMountedAncestor, error, 2);
                null !== instance && (initializeClassErrorUpdate(
                  error,
                  instance,
                  nearestMountedAncestor,
                  sourceFiber
                ), markRootUpdated$1(instance, 2), ensureRootIsScheduled(instance));
                break;
              }
            }
            nearestMountedAncestor = nearestMountedAncestor.return;
          }
      }
      __name(captureCommitPhaseError, "captureCommitPhaseError");
      function attachPingListener(root, wakeable, lanes) {
        var pingCache = root.pingCache;
        if (null === pingCache) {
          pingCache = root.pingCache = new PossiblyWeakMap();
          var threadIDs = /* @__PURE__ */ new Set();
          pingCache.set(wakeable, threadIDs);
        } else
          threadIDs = pingCache.get(wakeable), void 0 === threadIDs && (threadIDs = /* @__PURE__ */ new Set(), pingCache.set(wakeable, threadIDs));
        threadIDs.has(lanes) || (workInProgressRootDidAttachPingListener = true, threadIDs.add(lanes), root = pingSuspendedRoot.bind(null, root, wakeable, lanes), wakeable.then(root, root));
      }
      __name(attachPingListener, "attachPingListener");
      function pingSuspendedRoot(root, wakeable, pingedLanes) {
        var pingCache = root.pingCache;
        null !== pingCache && pingCache.delete(wakeable);
        root.pingedLanes |= root.suspendedLanes & pingedLanes;
        root.warmLanes &= ~pingedLanes;
        workInProgressRoot === root && (workInProgressRootRenderLanes & pingedLanes) === pingedLanes && (4 === workInProgressRootExitStatus || 3 === workInProgressRootExitStatus && (workInProgressRootRenderLanes & 62914560) === workInProgressRootRenderLanes && 300 > now() - globalMostRecentFallbackTime ? 0 === (executionContext & 2) && prepareFreshStack(root, 0) : workInProgressRootPingedLanes |= pingedLanes, workInProgressSuspendedRetryLanes === workInProgressRootRenderLanes && (workInProgressSuspendedRetryLanes = 0));
        ensureRootIsScheduled(root);
      }
      __name(pingSuspendedRoot, "pingSuspendedRoot");
      function retryTimedOutBoundary(boundaryFiber, retryLane) {
        0 === retryLane && (retryLane = claimNextRetryLane());
        boundaryFiber = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);
        null !== boundaryFiber && (markRootUpdated$1(boundaryFiber, retryLane), ensureRootIsScheduled(boundaryFiber));
      }
      __name(retryTimedOutBoundary, "retryTimedOutBoundary");
      function retryDehydratedSuspenseBoundary(boundaryFiber) {
        var suspenseState = boundaryFiber.memoizedState, retryLane = 0;
        null !== suspenseState && (retryLane = suspenseState.retryLane);
        retryTimedOutBoundary(boundaryFiber, retryLane);
      }
      __name(retryDehydratedSuspenseBoundary, "retryDehydratedSuspenseBoundary");
      function resolveRetryWakeable(boundaryFiber, wakeable) {
        var retryLane = 0;
        switch (boundaryFiber.tag) {
          case 13:
            var retryCache = boundaryFiber.stateNode;
            var suspenseState = boundaryFiber.memoizedState;
            null !== suspenseState && (retryLane = suspenseState.retryLane);
            break;
          case 19:
            retryCache = boundaryFiber.stateNode;
            break;
          case 22:
            retryCache = boundaryFiber.stateNode._retryCache;
            break;
          default:
            throw Error(formatProdErrorMessage(314));
        }
        null !== retryCache && retryCache.delete(wakeable);
        retryTimedOutBoundary(boundaryFiber, retryLane);
      }
      __name(resolveRetryWakeable, "resolveRetryWakeable");
      function scheduleCallback(priorityLevel, callback) {
        return scheduleCallback$3(priorityLevel, callback);
      }
      __name(scheduleCallback, "scheduleCallback");
      function FiberNode(tag2, pendingProps, key, mode) {
        this.tag = tag2;
        this.key = key;
        this.sibling = this.child = this.return = this.stateNode = this.type = this.elementType = null;
        this.index = 0;
        this.refCleanup = this.ref = null;
        this.pendingProps = pendingProps;
        this.dependencies = this.memoizedState = this.updateQueue = this.memoizedProps = null;
        this.mode = mode;
        this.subtreeFlags = this.flags = 0;
        this.deletions = null;
        this.childLanes = this.lanes = 0;
        this.alternate = null;
      }
      __name(FiberNode, "FiberNode");
      function shouldConstruct(Component) {
        Component = Component.prototype;
        return !(!Component || !Component.isReactComponent);
      }
      __name(shouldConstruct, "shouldConstruct");
      function createWorkInProgress(current, pendingProps) {
        var workInProgress2 = current.alternate;
        null === workInProgress2 ? (workInProgress2 = createFiber(
          current.tag,
          pendingProps,
          current.key,
          current.mode
        ), workInProgress2.elementType = current.elementType, workInProgress2.type = current.type, workInProgress2.stateNode = current.stateNode, workInProgress2.alternate = current, current.alternate = workInProgress2) : (workInProgress2.pendingProps = pendingProps, workInProgress2.type = current.type, workInProgress2.flags = 0, workInProgress2.subtreeFlags = 0, workInProgress2.deletions = null);
        workInProgress2.flags = current.flags & 65011712;
        workInProgress2.childLanes = current.childLanes;
        workInProgress2.lanes = current.lanes;
        workInProgress2.child = current.child;
        workInProgress2.memoizedProps = current.memoizedProps;
        workInProgress2.memoizedState = current.memoizedState;
        workInProgress2.updateQueue = current.updateQueue;
        pendingProps = current.dependencies;
        workInProgress2.dependencies = null === pendingProps ? null : {
          lanes: pendingProps.lanes,
          firstContext: pendingProps.firstContext
        };
        workInProgress2.sibling = current.sibling;
        workInProgress2.index = current.index;
        workInProgress2.ref = current.ref;
        workInProgress2.refCleanup = current.refCleanup;
        return workInProgress2;
      }
      __name(createWorkInProgress, "createWorkInProgress");
      function resetWorkInProgress(workInProgress2, renderLanes2) {
        workInProgress2.flags &= 65011714;
        var current = workInProgress2.alternate;
        null === current ? (workInProgress2.childLanes = 0, workInProgress2.lanes = renderLanes2, workInProgress2.child = null, workInProgress2.subtreeFlags = 0, workInProgress2.memoizedProps = null, workInProgress2.memoizedState = null, workInProgress2.updateQueue = null, workInProgress2.dependencies = null, workInProgress2.stateNode = null) : (workInProgress2.childLanes = current.childLanes, workInProgress2.lanes = current.lanes, workInProgress2.child = current.child, workInProgress2.subtreeFlags = 0, workInProgress2.deletions = null, workInProgress2.memoizedProps = current.memoizedProps, workInProgress2.memoizedState = current.memoizedState, workInProgress2.updateQueue = current.updateQueue, workInProgress2.type = current.type, renderLanes2 = current.dependencies, workInProgress2.dependencies = null === renderLanes2 ? null : {
          lanes: renderLanes2.lanes,
          firstContext: renderLanes2.firstContext
        });
        return workInProgress2;
      }
      __name(resetWorkInProgress, "resetWorkInProgress");
      function createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes) {
        var fiberTag = 0;
        owner = type;
        if ("function" === typeof type) shouldConstruct(type) && (fiberTag = 1);
        else if ("string" === typeof type)
          fiberTag = supportsResources && supportsSingletons ? isHostHoistableType(type, pendingProps, contextStackCursor.current) ? 26 : isHostSingletonType(type) ? 27 : 5 : supportsResources ? isHostHoistableType(
            type,
            pendingProps,
            contextStackCursor.current
          ) ? 26 : 5 : supportsSingletons ? isHostSingletonType(type) ? 27 : 5 : 5;
        else
          a: switch (type) {
            case REACT_ACTIVITY_TYPE:
              return type = createFiber(31, pendingProps, key, mode), type.elementType = REACT_ACTIVITY_TYPE, type.lanes = lanes, type;
            case REACT_FRAGMENT_TYPE:
              return createFiberFromFragment(
                pendingProps.children,
                mode,
                lanes,
                key
              );
            case REACT_STRICT_MODE_TYPE:
              fiberTag = 8;
              mode |= 24;
              break;
            case REACT_PROFILER_TYPE:
              return type = createFiber(12, pendingProps, key, mode | 2), type.elementType = REACT_PROFILER_TYPE, type.lanes = lanes, type;
            case REACT_SUSPENSE_TYPE:
              return type = createFiber(13, pendingProps, key, mode), type.elementType = REACT_SUSPENSE_TYPE, type.lanes = lanes, type;
            case REACT_SUSPENSE_LIST_TYPE:
              return type = createFiber(19, pendingProps, key, mode), type.elementType = REACT_SUSPENSE_LIST_TYPE, type.lanes = lanes, type;
            default:
              if ("object" === typeof type && null !== type)
                switch (type.$$typeof) {
                  case REACT_PROVIDER_TYPE:
                  case REACT_CONTEXT_TYPE:
                    fiberTag = 10;
                    break a;
                  case REACT_CONSUMER_TYPE:
                    fiberTag = 9;
                    break a;
                  case REACT_FORWARD_REF_TYPE:
                    fiberTag = 11;
                    break a;
                  case REACT_MEMO_TYPE:
                    fiberTag = 14;
                    break a;
                  case REACT_LAZY_TYPE:
                    fiberTag = 16;
                    owner = null;
                    break a;
                }
              fiberTag = 29;
              pendingProps = Error(
                formatProdErrorMessage(
                  130,
                  null === type ? "null" : typeof type,
                  ""
                )
              );
              owner = null;
          }
        key = createFiber(fiberTag, pendingProps, key, mode);
        key.elementType = type;
        key.type = owner;
        key.lanes = lanes;
        return key;
      }
      __name(createFiberFromTypeAndProps, "createFiberFromTypeAndProps");
      function createFiberFromFragment(elements, mode, lanes, key) {
        elements = createFiber(7, elements, key, mode);
        elements.lanes = lanes;
        return elements;
      }
      __name(createFiberFromFragment, "createFiberFromFragment");
      function createFiberFromText(content, mode, lanes) {
        content = createFiber(6, content, null, mode);
        content.lanes = lanes;
        return content;
      }
      __name(createFiberFromText, "createFiberFromText");
      function createFiberFromPortal(portal, mode, lanes) {
        mode = createFiber(
          4,
          null !== portal.children ? portal.children : [],
          portal.key,
          mode
        );
        mode.lanes = lanes;
        mode.stateNode = {
          containerInfo: portal.containerInfo,
          pendingChildren: null,
          implementation: portal.implementation
        };
        return mode;
      }
      __name(createFiberFromPortal, "createFiberFromPortal");
      function FiberRootNode(containerInfo, tag2, hydrate, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, formState) {
        this.tag = 1;
        this.containerInfo = containerInfo;
        this.pingCache = this.current = this.pendingChildren = null;
        this.timeoutHandle = noTimeout;
        this.callbackNode = this.next = this.pendingContext = this.context = this.cancelPendingCommit = null;
        this.callbackPriority = 0;
        this.expirationTimes = createLaneMap(-1);
        this.entangledLanes = this.shellSuspendCounter = this.errorRecoveryDisabledLanes = this.expiredLanes = this.warmLanes = this.pingedLanes = this.suspendedLanes = this.pendingLanes = 0;
        this.entanglements = createLaneMap(0);
        this.hiddenUpdates = createLaneMap(null);
        this.identifierPrefix = identifierPrefix;
        this.onUncaughtError = onUncaughtError;
        this.onCaughtError = onCaughtError;
        this.onRecoverableError = onRecoverableError;
        this.pooledCache = null;
        this.pooledCacheLanes = 0;
        this.formState = formState;
        this.incompleteTransitions = /* @__PURE__ */ new Map();
      }
      __name(FiberRootNode, "FiberRootNode");
      function createFiberRoot(containerInfo, tag2, hydrate, initialChildren, hydrationCallbacks, isStrictMode, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, transitionCallbacks, formState) {
        containerInfo = new FiberRootNode(
          containerInfo,
          tag2,
          hydrate,
          identifierPrefix,
          onUncaughtError,
          onCaughtError,
          onRecoverableError,
          formState
        );
        tag2 = 1;
        true === isStrictMode && (tag2 |= 24);
        isStrictMode = createFiber(3, null, null, tag2);
        containerInfo.current = isStrictMode;
        isStrictMode.stateNode = containerInfo;
        tag2 = createCache();
        tag2.refCount++;
        containerInfo.pooledCache = tag2;
        tag2.refCount++;
        isStrictMode.memoizedState = {
          element: initialChildren,
          isDehydrated: hydrate,
          cache: tag2
        };
        initializeUpdateQueue(isStrictMode);
        return containerInfo;
      }
      __name(createFiberRoot, "createFiberRoot");
      function getContextForSubtree(parentComponent) {
        if (!parentComponent) return emptyContextObject;
        parentComponent = emptyContextObject;
        return parentComponent;
      }
      __name(getContextForSubtree, "getContextForSubtree");
      function findHostInstance(component) {
        var fiber = component._reactInternals;
        if (void 0 === fiber) {
          if ("function" === typeof component.render)
            throw Error(formatProdErrorMessage(188));
          component = Object.keys(component).join(",");
          throw Error(formatProdErrorMessage(268, component));
        }
        component = findCurrentFiberUsingSlowPath(fiber);
        component = null !== component ? findCurrentHostFiberImpl(component) : null;
        return null === component ? null : getPublicInstance(component.stateNode);
      }
      __name(findHostInstance, "findHostInstance");
      function updateContainerImpl(rootFiber, lane, element, container, parentComponent, callback) {
        parentComponent = getContextForSubtree(parentComponent);
        null === container.context ? container.context = parentComponent : container.pendingContext = parentComponent;
        container = createUpdate(lane);
        container.payload = { element };
        callback = void 0 === callback ? null : callback;
        null !== callback && (container.callback = callback);
        element = enqueueUpdate(rootFiber, container, lane);
        null !== element && (scheduleUpdateOnFiber(element, rootFiber, lane), entangleTransitions(element, rootFiber, lane));
      }
      __name(updateContainerImpl, "updateContainerImpl");
      function markRetryLaneImpl(fiber, retryLane) {
        fiber = fiber.memoizedState;
        if (null !== fiber && null !== fiber.dehydrated) {
          var a = fiber.retryLane;
          fiber.retryLane = 0 !== a && a < retryLane ? a : retryLane;
        }
      }
      __name(markRetryLaneImpl, "markRetryLaneImpl");
      function markRetryLaneIfNotHydrated(fiber, retryLane) {
        markRetryLaneImpl(fiber, retryLane);
        (fiber = fiber.alternate) && markRetryLaneImpl(fiber, retryLane);
      }
      __name(markRetryLaneIfNotHydrated, "markRetryLaneIfNotHydrated");
      var exports3 = {};
      "use strict";
      var React29 = require_react(), Scheduler2 = require_scheduler(), assign = Object.assign, REACT_LEGACY_ELEMENT_TYPE = Symbol.for("react.element"), REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_PROVIDER_TYPE = Symbol.for("react.provider"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy");
      Symbol.for("react.scope");
      var REACT_ACTIVITY_TYPE = Symbol.for("react.activity");
      Symbol.for("react.legacy_hidden");
      Symbol.for("react.tracing_marker");
      var REACT_MEMO_CACHE_SENTINEL = Symbol.for("react.memo_cache_sentinel");
      Symbol.for("react.view_transition");
      var MAYBE_ITERATOR_SYMBOL = Symbol.iterator, REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), isArrayImpl = Array.isArray, ReactSharedInternals = React29.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, rendererVersion = $$$config.rendererVersion, rendererPackageName = $$$config.rendererPackageName, extraDevToolsConfig = $$$config.extraDevToolsConfig, getPublicInstance = $$$config.getPublicInstance, getRootHostContext = $$$config.getRootHostContext, getChildHostContext = $$$config.getChildHostContext, prepareForCommit = $$$config.prepareForCommit, resetAfterCommit = $$$config.resetAfterCommit, createInstance2 = $$$config.createInstance;
      $$$config.cloneMutableInstance;
      var appendInitialChild = $$$config.appendInitialChild, finalizeInitialChildren = $$$config.finalizeInitialChildren, shouldSetTextContent = $$$config.shouldSetTextContent, createTextInstance = $$$config.createTextInstance;
      $$$config.cloneMutableTextInstance;
      var scheduleTimeout = $$$config.scheduleTimeout, cancelTimeout = $$$config.cancelTimeout, noTimeout = $$$config.noTimeout, isPrimaryRenderer = $$$config.isPrimaryRenderer;
      $$$config.warnsIfNotActing;
      var supportsMutation = $$$config.supportsMutation, supportsPersistence = $$$config.supportsPersistence, supportsHydration = $$$config.supportsHydration, getInstanceFromNode = $$$config.getInstanceFromNode;
      $$$config.beforeActiveInstanceBlur;
      var preparePortalMount = $$$config.preparePortalMount;
      $$$config.prepareScopeUpdate;
      $$$config.getInstanceFromScope;
      var setCurrentUpdatePriority = $$$config.setCurrentUpdatePriority, getCurrentUpdatePriority = $$$config.getCurrentUpdatePriority, resolveUpdatePriority = $$$config.resolveUpdatePriority;
      $$$config.trackSchedulerEvent;
      $$$config.resolveEventType;
      $$$config.resolveEventTimeStamp;
      var shouldAttemptEagerTransition = $$$config.shouldAttemptEagerTransition, detachDeletedInstance = $$$config.detachDeletedInstance;
      $$$config.requestPostPaintCallback;
      var maySuspendCommit = $$$config.maySuspendCommit, preloadInstance = $$$config.preloadInstance, startSuspendingCommit = $$$config.startSuspendingCommit, suspendInstance = $$$config.suspendInstance;
      $$$config.suspendOnActiveViewTransition;
      var waitForCommitToBeReady = $$$config.waitForCommitToBeReady, NotPendingTransition = $$$config.NotPendingTransition, HostTransitionContext = $$$config.HostTransitionContext, resetFormInstance = $$$config.resetFormInstance;
      $$$config.bindToConsole;
      var supportsMicrotasks = $$$config.supportsMicrotasks, scheduleMicrotask = $$$config.scheduleMicrotask, supportsTestSelectors = $$$config.supportsTestSelectors, findFiberRoot = $$$config.findFiberRoot, getBoundingRect = $$$config.getBoundingRect, getTextContent = $$$config.getTextContent, isHiddenSubtree = $$$config.isHiddenSubtree, matchAccessibilityRole = $$$config.matchAccessibilityRole, setFocusIfFocusable = $$$config.setFocusIfFocusable, setupIntersectionObserver = $$$config.setupIntersectionObserver, appendChild = $$$config.appendChild, appendChildToContainer = $$$config.appendChildToContainer, commitTextUpdate = $$$config.commitTextUpdate, commitMount = $$$config.commitMount, commitUpdate = $$$config.commitUpdate, insertBefore = $$$config.insertBefore, insertInContainerBefore = $$$config.insertInContainerBefore, removeChild = $$$config.removeChild, removeChildFromContainer = $$$config.removeChildFromContainer, resetTextContent = $$$config.resetTextContent, hideInstance = $$$config.hideInstance, hideTextInstance = $$$config.hideTextInstance, unhideInstance = $$$config.unhideInstance, unhideTextInstance = $$$config.unhideTextInstance;
      $$$config.cancelViewTransitionName;
      $$$config.cancelRootViewTransitionName;
      $$$config.restoreRootViewTransitionName;
      $$$config.cloneRootViewTransitionContainer;
      $$$config.removeRootViewTransitionClone;
      $$$config.measureClonedInstance;
      $$$config.hasInstanceChanged;
      $$$config.hasInstanceAffectedParent;
      $$$config.startViewTransition;
      $$$config.startGestureTransition;
      $$$config.stopGestureTransition;
      $$$config.getCurrentGestureOffset;
      $$$config.subscribeToGestureDirection;
      $$$config.createViewTransitionInstance;
      var clearContainer = $$$config.clearContainer;
      $$$config.createFragmentInstance;
      $$$config.updateFragmentInstanceFiber;
      $$$config.commitNewChildToFragmentInstance;
      $$$config.deleteChildFromFragmentInstance;
      var cloneInstance = $$$config.cloneInstance, createContainerChildSet = $$$config.createContainerChildSet, appendChildToContainerChildSet = $$$config.appendChildToContainerChildSet, finalizeContainerChildren = $$$config.finalizeContainerChildren, replaceContainerChildren = $$$config.replaceContainerChildren, cloneHiddenInstance = $$$config.cloneHiddenInstance, cloneHiddenTextInstance = $$$config.cloneHiddenTextInstance, isSuspenseInstancePending = $$$config.isSuspenseInstancePending, isSuspenseInstanceFallback = $$$config.isSuspenseInstanceFallback, getSuspenseInstanceFallbackErrorDetails = $$$config.getSuspenseInstanceFallbackErrorDetails, registerSuspenseInstanceRetry = $$$config.registerSuspenseInstanceRetry, canHydrateFormStateMarker = $$$config.canHydrateFormStateMarker, isFormStateMarkerMatching = $$$config.isFormStateMarkerMatching, getNextHydratableSibling = $$$config.getNextHydratableSibling, getNextHydratableSiblingAfterSingleton = $$$config.getNextHydratableSiblingAfterSingleton, getFirstHydratableChild = $$$config.getFirstHydratableChild, getFirstHydratableChildWithinContainer = $$$config.getFirstHydratableChildWithinContainer, getFirstHydratableChildWithinSuspenseInstance = $$$config.getFirstHydratableChildWithinSuspenseInstance, getFirstHydratableChildWithinSingleton = $$$config.getFirstHydratableChildWithinSingleton, canHydrateInstance = $$$config.canHydrateInstance, canHydrateTextInstance = $$$config.canHydrateTextInstance, canHydrateSuspenseInstance = $$$config.canHydrateSuspenseInstance, hydrateInstance = $$$config.hydrateInstance, hydrateTextInstance = $$$config.hydrateTextInstance, hydrateSuspenseInstance = $$$config.hydrateSuspenseInstance, getNextHydratableInstanceAfterSuspenseInstance = $$$config.getNextHydratableInstanceAfterSuspenseInstance, commitHydratedContainer = $$$config.commitHydratedContainer, commitHydratedSuspenseInstance = $$$config.commitHydratedSuspenseInstance, clearSuspenseBoundary = $$$config.clearSuspenseBoundary, clearSuspenseBoundaryFromContainer = $$$config.clearSuspenseBoundaryFromContainer, shouldDeleteUnhydratedTailInstances = $$$config.shouldDeleteUnhydratedTailInstances;
      $$$config.diffHydratedPropsForDevWarnings;
      $$$config.diffHydratedTextForDevWarnings;
      $$$config.describeHydratableInstanceForDevWarnings;
      var validateHydratableInstance = $$$config.validateHydratableInstance, validateHydratableTextInstance = $$$config.validateHydratableTextInstance, supportsResources = $$$config.supportsResources, isHostHoistableType = $$$config.isHostHoistableType, getHoistableRoot = $$$config.getHoistableRoot, getResource = $$$config.getResource, acquireResource = $$$config.acquireResource, releaseResource = $$$config.releaseResource, hydrateHoistable = $$$config.hydrateHoistable, mountHoistable = $$$config.mountHoistable, unmountHoistable = $$$config.unmountHoistable, createHoistableInstance = $$$config.createHoistableInstance, prepareToCommitHoistables = $$$config.prepareToCommitHoistables, mayResourceSuspendCommit = $$$config.mayResourceSuspendCommit, preloadResource = $$$config.preloadResource, suspendResource = $$$config.suspendResource, supportsSingletons = $$$config.supportsSingletons, resolveSingletonInstance = $$$config.resolveSingletonInstance, acquireSingletonInstance = $$$config.acquireSingletonInstance, releaseSingletonInstance = $$$config.releaseSingletonInstance, isHostSingletonType = $$$config.isHostSingletonType, isSingletonScope = $$$config.isSingletonScope, valueStack = [], index$jscomp$0 = -1, emptyContextObject = {}, clz32 = Math.clz32 ? Math.clz32 : clz32Fallback, log$1 = Math.log, LN2 = Math.LN2, nextTransitionLane = 256, nextRetryLane = 4194304, scheduleCallback$3 = Scheduler2.unstable_scheduleCallback, cancelCallback$1 = Scheduler2.unstable_cancelCallback, shouldYield = Scheduler2.unstable_shouldYield, requestPaint = Scheduler2.unstable_requestPaint, now = Scheduler2.unstable_now, ImmediatePriority = Scheduler2.unstable_ImmediatePriority, UserBlockingPriority = Scheduler2.unstable_UserBlockingPriority, NormalPriority$1 = Scheduler2.unstable_NormalPriority, IdlePriority = Scheduler2.unstable_IdlePriority, log = Scheduler2.log, unstable_setDisableYieldValue = Scheduler2.unstable_setDisableYieldValue, rendererID = null, injectedHook = null, prefix, suffix, reentry = false, CapturedStacks = /* @__PURE__ */ new WeakMap(), forkStack = [], forkStackIndex = 0, treeForkProvider = null, treeForkCount = 0, idStack = [], idStackIndex = 0, treeContextProvider = null, treeContextId = 1, treeContextOverflow = "", contextStackCursor = createCursor(null), contextFiberStackCursor = createCursor(null), rootInstanceStackCursor = createCursor(null), hostTransitionProviderCursor = createCursor(null), hydrationParentFiber = null, nextHydratableInstance = null, isHydrating = false, hydrationErrors = null, rootOrSingletonContext = false, HydrationMismatchException = Error(formatProdErrorMessage(519)), objectIs = "function" === typeof Object.is ? Object.is : is, valueCursor = createCursor(null), currentlyRenderingFiber$1 = null, lastContextDependency = null, AbortControllerLocal = "undefined" !== typeof AbortController ? AbortController : function() {
        var listeners = [], signal = this.signal = {
          aborted: false,
          addEventListener: /* @__PURE__ */ __name(function(type, listener) {
            listeners.push(listener);
          }, "addEventListener")
        };
        this.abort = function() {
          signal.aborted = true;
          listeners.forEach(function(listener) {
            return listener();
          });
        };
      }, scheduleCallback$2 = Scheduler2.unstable_scheduleCallback, NormalPriority = Scheduler2.unstable_NormalPriority, CacheContext = {
        $$typeof: REACT_CONTEXT_TYPE,
        Consumer: null,
        Provider: null,
        _currentValue: null,
        _currentValue2: null,
        _threadCount: 0
      }, firstScheduledRoot = null, lastScheduledRoot = null, didScheduleMicrotask = false, mightHavePendingSyncWork = false, isFlushingWork = false, currentEventTransitionLane = 0, currentEntangledListeners = null, currentEntangledPendingCount = 0, currentEntangledLane = 0, currentEntangledActionThenable = null, prevOnStartTransitionFinish = ReactSharedInternals.S;
      ReactSharedInternals.S = function(transition, returnValue) {
        "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && entangleAsyncAction(transition, returnValue);
        null !== prevOnStartTransitionFinish && prevOnStartTransitionFinish(transition, returnValue);
      };
      var resumedCache = createCursor(null), hasOwnProperty2 = Object.prototype.hasOwnProperty, SuspenseException = Error(formatProdErrorMessage(460)), SuspenseyCommitException = Error(formatProdErrorMessage(474)), SuspenseActionException = Error(formatProdErrorMessage(542)), noopSuspenseyCommitThenable = { then: /* @__PURE__ */ __name(function() {
      }, "then") }, suspendedThenable = null, concurrentQueues = [], concurrentQueuesIndex = 0, concurrentlyUpdatedLanes = 0, hasForceUpdate = false, didReadFromEntangledAsyncAction = false, currentTreeHiddenStackCursor = createCursor(null), prevEntangledRenderLanesCursor = createCursor(0), renderLanes = 0, currentlyRenderingFiber = null, currentHook = null, workInProgressHook = null, didScheduleRenderPhaseUpdate = false, didScheduleRenderPhaseUpdateDuringThisPass = false, shouldDoubleInvokeUserFnsInHooksDEV = false, localIdCounter = 0, thenableIndexCounter$1 = 0, thenableState$1 = null, globalClientIdCounter = 0, ContextOnlyDispatcher = {
        readContext,
        use: use2,
        useCallback: throwInvalidHookError,
        useContext: throwInvalidHookError,
        useEffect: throwInvalidHookError,
        useImperativeHandle: throwInvalidHookError,
        useLayoutEffect: throwInvalidHookError,
        useInsertionEffect: throwInvalidHookError,
        useMemo: throwInvalidHookError,
        useReducer: throwInvalidHookError,
        useRef: throwInvalidHookError,
        useState: throwInvalidHookError,
        useDebugValue: throwInvalidHookError,
        useDeferredValue: throwInvalidHookError,
        useTransition: throwInvalidHookError,
        useSyncExternalStore: throwInvalidHookError,
        useId: throwInvalidHookError,
        useHostTransitionStatus: throwInvalidHookError,
        useFormState: throwInvalidHookError,
        useActionState: throwInvalidHookError,
        useOptimistic: throwInvalidHookError,
        useMemoCache: throwInvalidHookError,
        useCacheRefresh: throwInvalidHookError
      }, HooksDispatcherOnMount = {
        readContext,
        use: use2,
        useCallback: /* @__PURE__ */ __name(function(callback, deps) {
          mountWorkInProgressHook().memoizedState = [
            callback,
            void 0 === deps ? null : deps
          ];
          return callback;
        }, "useCallback"),
        useContext: readContext,
        useEffect: mountEffect,
        useImperativeHandle: /* @__PURE__ */ __name(function(ref, create3, deps) {
          deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null;
          mountEffectImpl(
            4194308,
            4,
            imperativeHandleEffect.bind(null, create3, ref),
            deps
          );
        }, "useImperativeHandle"),
        useLayoutEffect: /* @__PURE__ */ __name(function(create3, deps) {
          return mountEffectImpl(4194308, 4, create3, deps);
        }, "useLayoutEffect"),
        useInsertionEffect: /* @__PURE__ */ __name(function(create3, deps) {
          mountEffectImpl(4, 2, create3, deps);
        }, "useInsertionEffect"),
        useMemo: /* @__PURE__ */ __name(function(nextCreate, deps) {
          var hook = mountWorkInProgressHook();
          deps = void 0 === deps ? null : deps;
          var nextValue = nextCreate();
          if (shouldDoubleInvokeUserFnsInHooksDEV) {
            setIsStrictModeForDevtools(true);
            try {
              nextCreate();
            } finally {
              setIsStrictModeForDevtools(false);
            }
          }
          hook.memoizedState = [nextValue, deps];
          return nextValue;
        }, "useMemo"),
        useReducer: /* @__PURE__ */ __name(function(reducer, initialArg, init) {
          var hook = mountWorkInProgressHook();
          if (void 0 !== init) {
            var initialState2 = init(initialArg);
            if (shouldDoubleInvokeUserFnsInHooksDEV) {
              setIsStrictModeForDevtools(true);
              try {
                init(initialArg);
              } finally {
                setIsStrictModeForDevtools(false);
              }
            }
          } else initialState2 = initialArg;
          hook.memoizedState = hook.baseState = initialState2;
          reducer = {
            pending: null,
            lanes: 0,
            dispatch: null,
            lastRenderedReducer: reducer,
            lastRenderedState: initialState2
          };
          hook.queue = reducer;
          reducer = reducer.dispatch = dispatchReducerAction.bind(
            null,
            currentlyRenderingFiber,
            reducer
          );
          return [hook.memoizedState, reducer];
        }, "useReducer"),
        useRef: /* @__PURE__ */ __name(function(initialValue) {
          var hook = mountWorkInProgressHook();
          initialValue = { current: initialValue };
          return hook.memoizedState = initialValue;
        }, "useRef"),
        useState: /* @__PURE__ */ __name(function(initialState2) {
          initialState2 = mountStateImpl(initialState2);
          var queue = initialState2.queue, dispatch = dispatchSetState.bind(
            null,
            currentlyRenderingFiber,
            queue
          );
          queue.dispatch = dispatch;
          return [initialState2.memoizedState, dispatch];
        }, "useState"),
        useDebugValue: mountDebugValue,
        useDeferredValue: /* @__PURE__ */ __name(function(value, initialValue) {
          var hook = mountWorkInProgressHook();
          return mountDeferredValueImpl(hook, value, initialValue);
        }, "useDeferredValue"),
        useTransition: /* @__PURE__ */ __name(function() {
          var stateHook = mountStateImpl(false);
          stateHook = startTransition.bind(
            null,
            currentlyRenderingFiber,
            stateHook.queue,
            true,
            false
          );
          mountWorkInProgressHook().memoizedState = stateHook;
          return [false, stateHook];
        }, "useTransition"),
        useSyncExternalStore: /* @__PURE__ */ __name(function(subscribe, getSnapshot, getServerSnapshot) {
          var fiber = currentlyRenderingFiber, hook = mountWorkInProgressHook();
          if (isHydrating) {
            if (void 0 === getServerSnapshot)
              throw Error(formatProdErrorMessage(407));
            getServerSnapshot = getServerSnapshot();
          } else {
            getServerSnapshot = getSnapshot();
            if (null === workInProgressRoot)
              throw Error(formatProdErrorMessage(349));
            0 !== (workInProgressRootRenderLanes & 124) || pushStoreConsistencyCheck(fiber, getSnapshot, getServerSnapshot);
          }
          hook.memoizedState = getServerSnapshot;
          var inst = { value: getServerSnapshot, getSnapshot };
          hook.queue = inst;
          mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [
            subscribe
          ]);
          fiber.flags |= 2048;
          pushSimpleEffect(
            9,
            createEffectInstance(),
            updateStoreInstance.bind(
              null,
              fiber,
              inst,
              getServerSnapshot,
              getSnapshot
            ),
            null
          );
          return getServerSnapshot;
        }, "useSyncExternalStore"),
        useId: /* @__PURE__ */ __name(function() {
          var hook = mountWorkInProgressHook(), identifierPrefix = workInProgressRoot.identifierPrefix;
          if (isHydrating) {
            var JSCompiler_inline_result = treeContextOverflow;
            var idWithLeadingBit = treeContextId;
            JSCompiler_inline_result = (idWithLeadingBit & ~(1 << 32 - clz32(idWithLeadingBit) - 1)).toString(32) + JSCompiler_inline_result;
            identifierPrefix = "\xAB" + identifierPrefix + "R" + JSCompiler_inline_result;
            JSCompiler_inline_result = localIdCounter++;
            0 < JSCompiler_inline_result && (identifierPrefix += "H" + JSCompiler_inline_result.toString(32));
            identifierPrefix += "\xBB";
          } else
            JSCompiler_inline_result = globalClientIdCounter++, identifierPrefix = "\xAB" + identifierPrefix + "r" + JSCompiler_inline_result.toString(32) + "\xBB";
          return hook.memoizedState = identifierPrefix;
        }, "useId"),
        useHostTransitionStatus,
        useFormState: mountActionState,
        useActionState: mountActionState,
        useOptimistic: /* @__PURE__ */ __name(function(passthrough) {
          var hook = mountWorkInProgressHook();
          hook.memoizedState = hook.baseState = passthrough;
          var queue = {
            pending: null,
            lanes: 0,
            dispatch: null,
            lastRenderedReducer: null,
            lastRenderedState: null
          };
          hook.queue = queue;
          hook = dispatchOptimisticSetState.bind(
            null,
            currentlyRenderingFiber,
            true,
            queue
          );
          queue.dispatch = hook;
          return [passthrough, hook];
        }, "useOptimistic"),
        useMemoCache,
        useCacheRefresh: /* @__PURE__ */ __name(function() {
          return mountWorkInProgressHook().memoizedState = refreshCache.bind(
            null,
            currentlyRenderingFiber
          );
        }, "useCacheRefresh")
      }, HooksDispatcherOnUpdate = {
        readContext,
        use: use2,
        useCallback: updateCallback,
        useContext: readContext,
        useEffect: updateEffect,
        useImperativeHandle: updateImperativeHandle,
        useInsertionEffect: updateInsertionEffect,
        useLayoutEffect: updateLayoutEffect,
        useMemo: updateMemo,
        useReducer: updateReducer,
        useRef: updateRef,
        useState: /* @__PURE__ */ __name(function() {
          return updateReducer(basicStateReducer);
        }, "useState"),
        useDebugValue: mountDebugValue,
        useDeferredValue: /* @__PURE__ */ __name(function(value, initialValue) {
          var hook = updateWorkInProgressHook();
          return updateDeferredValueImpl(
            hook,
            currentHook.memoizedState,
            value,
            initialValue
          );
        }, "useDeferredValue"),
        useTransition: /* @__PURE__ */ __name(function() {
          var booleanOrThenable = updateReducer(basicStateReducer)[0], start = updateWorkInProgressHook().memoizedState;
          return [
            "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
            start
          ];
        }, "useTransition"),
        useSyncExternalStore: updateSyncExternalStore,
        useId: updateId,
        useHostTransitionStatus,
        useFormState: updateActionState,
        useActionState: updateActionState,
        useOptimistic: /* @__PURE__ */ __name(function(passthrough, reducer) {
          var hook = updateWorkInProgressHook();
          return updateOptimisticImpl(hook, currentHook, passthrough, reducer);
        }, "useOptimistic"),
        useMemoCache,
        useCacheRefresh: updateRefresh
      }, HooksDispatcherOnRerender = {
        readContext,
        use: use2,
        useCallback: updateCallback,
        useContext: readContext,
        useEffect: updateEffect,
        useImperativeHandle: updateImperativeHandle,
        useInsertionEffect: updateInsertionEffect,
        useLayoutEffect: updateLayoutEffect,
        useMemo: updateMemo,
        useReducer: rerenderReducer,
        useRef: updateRef,
        useState: /* @__PURE__ */ __name(function() {
          return rerenderReducer(basicStateReducer);
        }, "useState"),
        useDebugValue: mountDebugValue,
        useDeferredValue: /* @__PURE__ */ __name(function(value, initialValue) {
          var hook = updateWorkInProgressHook();
          return null === currentHook ? mountDeferredValueImpl(hook, value, initialValue) : updateDeferredValueImpl(
            hook,
            currentHook.memoizedState,
            value,
            initialValue
          );
        }, "useDeferredValue"),
        useTransition: /* @__PURE__ */ __name(function() {
          var booleanOrThenable = rerenderReducer(basicStateReducer)[0], start = updateWorkInProgressHook().memoizedState;
          return [
            "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
            start
          ];
        }, "useTransition"),
        useSyncExternalStore: updateSyncExternalStore,
        useId: updateId,
        useHostTransitionStatus,
        useFormState: rerenderActionState,
        useActionState: rerenderActionState,
        useOptimistic: /* @__PURE__ */ __name(function(passthrough, reducer) {
          var hook = updateWorkInProgressHook();
          if (null !== currentHook)
            return updateOptimisticImpl(hook, currentHook, passthrough, reducer);
          hook.baseState = passthrough;
          return [passthrough, hook.queue.dispatch];
        }, "useOptimistic"),
        useMemoCache,
        useCacheRefresh: updateRefresh
      }, thenableState = null, thenableIndexCounter = 0, reconcileChildFibers = createChildReconciler(true), mountChildFibers = createChildReconciler(false), suspenseHandlerStackCursor = createCursor(null), shellBoundary = null, suspenseStackCursor = createCursor(0), classComponentUpdater = {
        enqueueSetState: /* @__PURE__ */ __name(function(inst, payload, callback) {
          inst = inst._reactInternals;
          var lane = requestUpdateLane(), update2 = createUpdate(lane);
          update2.payload = payload;
          void 0 !== callback && null !== callback && (update2.callback = callback);
          payload = enqueueUpdate(inst, update2, lane);
          null !== payload && (scheduleUpdateOnFiber(payload, inst, lane), entangleTransitions(payload, inst, lane));
        }, "enqueueSetState"),
        enqueueReplaceState: /* @__PURE__ */ __name(function(inst, payload, callback) {
          inst = inst._reactInternals;
          var lane = requestUpdateLane(), update2 = createUpdate(lane);
          update2.tag = 1;
          update2.payload = payload;
          void 0 !== callback && null !== callback && (update2.callback = callback);
          payload = enqueueUpdate(inst, update2, lane);
          null !== payload && (scheduleUpdateOnFiber(payload, inst, lane), entangleTransitions(payload, inst, lane));
        }, "enqueueReplaceState"),
        enqueueForceUpdate: /* @__PURE__ */ __name(function(inst, callback) {
          inst = inst._reactInternals;
          var lane = requestUpdateLane(), update2 = createUpdate(lane);
          update2.tag = 2;
          void 0 !== callback && null !== callback && (update2.callback = callback);
          callback = enqueueUpdate(inst, update2, lane);
          null !== callback && (scheduleUpdateOnFiber(callback, inst, lane), entangleTransitions(callback, inst, lane));
        }, "enqueueForceUpdate")
      }, reportGlobalError = "function" === typeof reportError ? reportError : function(error) {
        if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
          var event = new window.ErrorEvent("error", {
            bubbles: true,
            cancelable: true,
            message: "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error),
            error
          });
          if (!window.dispatchEvent(event)) return;
        } else if ("object" === typeof process && "function" === typeof process.emit) {
          process.emit("uncaughtException", error);
          return;
        }
        console.error(error);
      }, SelectiveHydrationException = Error(formatProdErrorMessage(461)), didReceiveUpdate = false, SUSPENDED_MARKER = {
        dehydrated: null,
        treeContext: null,
        retryLane: 0,
        hydrationErrors: null
      }, offscreenSubtreeIsHidden = false, offscreenSubtreeWasHidden = false, needsFormReset = false, PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set, nextEffect = null, hostParent = null, hostParentIsContainer = false, currentHoistableRoot = null, suspenseyCommitFlag = 8192, DefaultAsyncDispatcher = {
        getCacheForType: /* @__PURE__ */ __name(function(resourceType) {
          var cache5 = readContext(CacheContext), cacheForType = cache5.data.get(resourceType);
          void 0 === cacheForType && (cacheForType = resourceType(), cache5.data.set(resourceType, cacheForType));
          return cacheForType;
        }, "getCacheForType")
      }, COMPONENT_TYPE = 0, HAS_PSEUDO_CLASS_TYPE = 1, ROLE_TYPE = 2, TEST_NAME_TYPE = 3, TEXT_TYPE = 4;
      if ("function" === typeof Symbol && Symbol.for) {
        var symbolFor = Symbol.for;
        COMPONENT_TYPE = symbolFor("selector.component");
        HAS_PSEUDO_CLASS_TYPE = symbolFor("selector.has_pseudo_class");
        ROLE_TYPE = symbolFor("selector.role");
        TEST_NAME_TYPE = symbolFor("selector.test_id");
        TEXT_TYPE = symbolFor("selector.text");
      }
      var PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map, executionContext = 0, workInProgressRoot = null, workInProgress = null, workInProgressRootRenderLanes = 0, workInProgressSuspendedReason = 0, workInProgressThrownValue = null, workInProgressRootDidSkipSuspendedSiblings = false, workInProgressRootIsPrerendering = false, workInProgressRootDidAttachPingListener = false, entangledRenderLanes = 0, workInProgressRootExitStatus = 0, workInProgressRootSkippedLanes = 0, workInProgressRootInterleavedUpdatedLanes = 0, workInProgressRootPingedLanes = 0, workInProgressDeferredLane = 0, workInProgressSuspendedRetryLanes = 0, workInProgressRootConcurrentErrors = null, workInProgressRootRecoverableErrors = null, workInProgressRootDidIncludeRecursiveRenderUpdate = false, globalMostRecentFallbackTime = 0, workInProgressRootRenderTargetTime = Infinity, workInProgressTransitions = null, legacyErrorBoundariesThatAlreadyFailed = null, pendingEffectsStatus = 0, pendingEffectsRoot = null, pendingFinishedWork = null, pendingEffectsLanes = 0, pendingEffectsRemainingLanes = 0, pendingPassiveTransitions = null, pendingRecoverableErrors = null, nestedUpdateCount = 0, rootWithNestedUpdates = null;
      exports3.attemptContinuousHydration = function(fiber) {
        if (13 === fiber.tag) {
          var root = enqueueConcurrentRenderForLane(fiber, 67108864);
          null !== root && scheduleUpdateOnFiber(root, fiber, 67108864);
          markRetryLaneIfNotHydrated(fiber, 67108864);
        }
      };
      exports3.attemptHydrationAtCurrentPriority = function(fiber) {
        if (13 === fiber.tag) {
          var lane = requestUpdateLane();
          lane = getBumpedLaneForHydrationByLane(lane);
          var root = enqueueConcurrentRenderForLane(fiber, lane);
          null !== root && scheduleUpdateOnFiber(root, fiber, lane);
          markRetryLaneIfNotHydrated(fiber, lane);
        }
      };
      exports3.attemptSynchronousHydration = function(fiber) {
        switch (fiber.tag) {
          case 3:
            fiber = fiber.stateNode;
            if (fiber.current.memoizedState.isDehydrated) {
              var lanes = getHighestPriorityLanes(fiber.pendingLanes);
              if (0 !== lanes) {
                fiber.pendingLanes |= 2;
                for (fiber.entangledLanes |= 2; lanes; ) {
                  var lane = 1 << 31 - clz32(lanes);
                  fiber.entanglements[1] |= lane;
                  lanes &= ~lane;
                }
                ensureRootIsScheduled(fiber);
                0 === (executionContext & 6) && (workInProgressRootRenderTargetTime = now() + 500, flushSyncWorkAcrossRoots_impl(0, false));
              }
            }
            break;
          case 13:
            lanes = enqueueConcurrentRenderForLane(fiber, 2), null !== lanes && scheduleUpdateOnFiber(lanes, fiber, 2), flushSyncWork(), markRetryLaneIfNotHydrated(fiber, 2);
        }
      };
      exports3.batchedUpdates = function(fn, a) {
        return fn(a);
      };
      exports3.createComponentSelector = function(component) {
        return { $$typeof: COMPONENT_TYPE, value: component };
      };
      exports3.createContainer = function(containerInfo, tag2, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, transitionCallbacks) {
        return createFiberRoot(
          containerInfo,
          tag2,
          false,
          null,
          hydrationCallbacks,
          isStrictMode,
          identifierPrefix,
          onUncaughtError,
          onCaughtError,
          onRecoverableError,
          transitionCallbacks,
          null
        );
      };
      exports3.createHasPseudoClassSelector = function(selectors) {
        return { $$typeof: HAS_PSEUDO_CLASS_TYPE, value: selectors };
      };
      exports3.createHydrationContainer = function(initialChildren, callback, containerInfo, tag2, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, transitionCallbacks, formState) {
        initialChildren = createFiberRoot(
          containerInfo,
          tag2,
          true,
          initialChildren,
          hydrationCallbacks,
          isStrictMode,
          identifierPrefix,
          onUncaughtError,
          onCaughtError,
          onRecoverableError,
          transitionCallbacks,
          formState
        );
        initialChildren.context = getContextForSubtree(null);
        containerInfo = initialChildren.current;
        tag2 = requestUpdateLane();
        tag2 = getBumpedLaneForHydrationByLane(tag2);
        hydrationCallbacks = createUpdate(tag2);
        hydrationCallbacks.callback = void 0 !== callback && null !== callback ? callback : null;
        enqueueUpdate(containerInfo, hydrationCallbacks, tag2);
        callback = tag2;
        initialChildren.current.lanes = callback;
        markRootUpdated$1(initialChildren, callback);
        ensureRootIsScheduled(initialChildren);
        return initialChildren;
      };
      exports3.createPortal = function(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
        };
      };
      exports3.createRoleSelector = function(role) {
        return { $$typeof: ROLE_TYPE, value: role };
      };
      exports3.createTestNameSelector = function(id) {
        return { $$typeof: TEST_NAME_TYPE, value: id };
      };
      exports3.createTextSelector = function(text) {
        return { $$typeof: TEXT_TYPE, value: text };
      };
      exports3.defaultOnCaughtError = function(error) {
        console.error(error);
      };
      exports3.defaultOnRecoverableError = function(error) {
        reportGlobalError(error);
      };
      exports3.defaultOnUncaughtError = function(error) {
        reportGlobalError(error);
      };
      exports3.deferredUpdates = function(fn) {
        var prevTransition = ReactSharedInternals.T, previousPriority = getCurrentUpdatePriority();
        try {
          return setCurrentUpdatePriority(32), ReactSharedInternals.T = null, fn();
        } finally {
          setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = prevTransition;
        }
      };
      exports3.discreteUpdates = function(fn, a, b, c3, d) {
        var prevTransition = ReactSharedInternals.T, previousPriority = getCurrentUpdatePriority();
        try {
          return setCurrentUpdatePriority(2), ReactSharedInternals.T = null, fn(a, b, c3, d);
        } finally {
          setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = prevTransition, 0 === executionContext && (workInProgressRootRenderTargetTime = now() + 500);
        }
      };
      exports3.findAllNodes = findAllNodes;
      exports3.findBoundingRects = function(hostRoot, selectors) {
        if (!supportsTestSelectors) throw Error(formatProdErrorMessage(363));
        selectors = findAllNodes(hostRoot, selectors);
        hostRoot = [];
        for (var i = 0; i < selectors.length; i++)
          hostRoot.push(getBoundingRect(selectors[i]));
        for (selectors = hostRoot.length - 1; 0 < selectors; selectors--) {
          i = hostRoot[selectors];
          for (var targetLeft = i.x, targetRight = targetLeft + i.width, targetTop = i.y, targetBottom = targetTop + i.height, j = selectors - 1; 0 <= j; j--)
            if (selectors !== j) {
              var otherRect = hostRoot[j], otherLeft = otherRect.x, otherRight = otherLeft + otherRect.width, otherTop = otherRect.y, otherBottom = otherTop + otherRect.height;
              if (targetLeft >= otherLeft && targetTop >= otherTop && targetRight <= otherRight && targetBottom <= otherBottom) {
                hostRoot.splice(selectors, 1);
                break;
              } else if (!(targetLeft !== otherLeft || i.width !== otherRect.width || otherBottom < targetTop || otherTop > targetBottom)) {
                otherTop > targetTop && (otherRect.height += otherTop - targetTop, otherRect.y = targetTop);
                otherBottom < targetBottom && (otherRect.height = targetBottom - otherTop);
                hostRoot.splice(selectors, 1);
                break;
              } else if (!(targetTop !== otherTop || i.height !== otherRect.height || otherRight < targetLeft || otherLeft > targetRight)) {
                otherLeft > targetLeft && (otherRect.width += otherLeft - targetLeft, otherRect.x = targetLeft);
                otherRight < targetRight && (otherRect.width = targetRight - otherLeft);
                hostRoot.splice(selectors, 1);
                break;
              }
            }
        }
        return hostRoot;
      };
      exports3.findHostInstance = findHostInstance;
      exports3.findHostInstanceWithNoPortals = function(fiber) {
        fiber = findCurrentFiberUsingSlowPath(fiber);
        fiber = null !== fiber ? findCurrentHostFiberWithNoPortalsImpl(fiber) : null;
        return null === fiber ? null : getPublicInstance(fiber.stateNode);
      };
      exports3.findHostInstanceWithWarning = function(component) {
        return findHostInstance(component);
      };
      exports3.flushPassiveEffects = flushPendingEffects;
      exports3.flushSyncFromReconciler = function(fn) {
        var prevExecutionContext = executionContext;
        executionContext |= 1;
        var prevTransition = ReactSharedInternals.T, previousPriority = getCurrentUpdatePriority();
        try {
          if (setCurrentUpdatePriority(2), ReactSharedInternals.T = null, fn)
            return fn();
        } finally {
          setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = prevTransition, executionContext = prevExecutionContext, 0 === (executionContext & 6) && flushSyncWorkAcrossRoots_impl(0, false);
        }
      };
      exports3.flushSyncWork = flushSyncWork;
      exports3.focusWithin = function(hostRoot, selectors) {
        if (!supportsTestSelectors) throw Error(formatProdErrorMessage(363));
        hostRoot = findFiberRootForHostRoot(hostRoot);
        selectors = findPaths(hostRoot, selectors);
        selectors = Array.from(selectors);
        for (hostRoot = 0; hostRoot < selectors.length; ) {
          var fiber = selectors[hostRoot++], tag2 = fiber.tag;
          if (!isHiddenSubtree(fiber)) {
            if ((5 === tag2 || 26 === tag2 || 27 === tag2) && setFocusIfFocusable(fiber.stateNode))
              return true;
            for (fiber = fiber.child; null !== fiber; )
              selectors.push(fiber), fiber = fiber.sibling;
          }
        }
        return false;
      };
      exports3.getFindAllNodesFailureDescription = function(hostRoot, selectors) {
        if (!supportsTestSelectors) throw Error(formatProdErrorMessage(363));
        var maxSelectorIndex = 0, matchedNames = [];
        hostRoot = [findFiberRootForHostRoot(hostRoot), 0];
        for (var index = 0; index < hostRoot.length; ) {
          var fiber = hostRoot[index++], tag2 = fiber.tag, selectorIndex = hostRoot[index++], selector = selectors[selectorIndex];
          if (5 !== tag2 && 26 !== tag2 && 27 !== tag2 || !isHiddenSubtree(fiber)) {
            if (matchSelector(fiber, selector) && (matchedNames.push(selectorToString(selector)), selectorIndex++, selectorIndex > maxSelectorIndex && (maxSelectorIndex = selectorIndex)), selectorIndex < selectors.length)
              for (fiber = fiber.child; null !== fiber; )
                hostRoot.push(fiber, selectorIndex), fiber = fiber.sibling;
          }
        }
        if (maxSelectorIndex < selectors.length) {
          for (hostRoot = []; maxSelectorIndex < selectors.length; maxSelectorIndex++)
            hostRoot.push(selectorToString(selectors[maxSelectorIndex]));
          return "findAllNodes was able to match part of the selector:\n  " + (matchedNames.join(" > ") + "\n\nNo matching component was found for:\n  ") + hostRoot.join(" > ");
        }
        return null;
      };
      exports3.getPublicRootInstance = function(container) {
        container = container.current;
        if (!container.child) return null;
        switch (container.child.tag) {
          case 27:
          case 5:
            return getPublicInstance(container.child.stateNode);
          default:
            return container.child.stateNode;
        }
      };
      exports3.injectIntoDevTools = function() {
        var internals = {
          bundleType: 0,
          version: rendererVersion,
          rendererPackageName,
          currentDispatcherRef: ReactSharedInternals,
          reconcilerVersion: "19.1.0"
        };
        null !== extraDevToolsConfig && (internals.rendererConfig = extraDevToolsConfig);
        if ("undefined" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) internals = false;
        else {
          var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
          if (hook.isDisabled || !hook.supportsFiber) internals = true;
          else {
            try {
              rendererID = hook.inject(internals), injectedHook = hook;
            } catch (err) {
            }
            internals = hook.checkDCE ? true : false;
          }
        }
        return internals;
      };
      exports3.isAlreadyRendering = function() {
        return 0 !== (executionContext & 6);
      };
      exports3.observeVisibleRects = function(hostRoot, selectors, callback, options2) {
        if (!supportsTestSelectors) throw Error(formatProdErrorMessage(363));
        hostRoot = findAllNodes(hostRoot, selectors);
        var disconnect = setupIntersectionObserver(
          hostRoot,
          callback,
          options2
        ).disconnect;
        return {
          disconnect: /* @__PURE__ */ __name(function() {
            disconnect();
          }, "disconnect")
        };
      };
      exports3.shouldError = function() {
        return null;
      };
      exports3.shouldSuspend = function() {
        return false;
      };
      exports3.startHostTransition = function(formFiber, pendingState, action, formData) {
        if (5 !== formFiber.tag) throw Error(formatProdErrorMessage(476));
        var queue = ensureFormComponentIsStateful(formFiber).queue;
        startTransition(
          formFiber,
          queue,
          pendingState,
          NotPendingTransition,
          null === action ? noop6 : function() {
            var resetStateQueue = ensureFormComponentIsStateful(formFiber).next.queue;
            dispatchSetStateInternal(
              formFiber,
              resetStateQueue,
              {},
              requestUpdateLane()
            );
            return action(formData);
          }
        );
      };
      exports3.updateContainer = function(element, container, parentComponent, callback) {
        var current = container.current, lane = requestUpdateLane();
        updateContainerImpl(
          current,
          lane,
          element,
          container,
          parentComponent,
          callback
        );
        return lane;
      };
      exports3.updateContainerSync = function(element, container, parentComponent, callback) {
        updateContainerImpl(
          container.current,
          2,
          element,
          container,
          parentComponent,
          callback
        );
        return 2;
      };
      return exports3;
    };
    module2.exports.default = module2.exports;
    Object.defineProperty(module2.exports, "__esModule", { value: true });
  }
});

// node_modules/react-reconciler/cjs/react-reconciler.development.js
var require_react_reconciler_development = __commonJS({
  "node_modules/react-reconciler/cjs/react-reconciler.development.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    "production" !== process.env.NODE_ENV && (module2.exports = function($$$config) {
      function findHook(fiber, id) {
        for (fiber = fiber.memoizedState; null !== fiber && 0 < id; )
          fiber = fiber.next, id--;
        return fiber;
      }
      __name(findHook, "findHook");
      function copyWithSetImpl(obj, path108, index, value) {
        if (index >= path108.length) return value;
        var key = path108[index], updated = isArrayImpl(obj) ? obj.slice() : assign({}, obj);
        updated[key] = copyWithSetImpl(obj[key], path108, index + 1, value);
        return updated;
      }
      __name(copyWithSetImpl, "copyWithSetImpl");
      function copyWithRename(obj, oldPath, newPath) {
        if (oldPath.length !== newPath.length)
          console.warn("copyWithRename() expects paths of the same length");
        else {
          for (var i = 0; i < newPath.length - 1; i++)
            if (oldPath[i] !== newPath[i]) {
              console.warn(
                "copyWithRename() expects paths to be the same except for the deepest key"
              );
              return;
            }
          return copyWithRenameImpl(obj, oldPath, newPath, 0);
        }
      }
      __name(copyWithRename, "copyWithRename");
      function copyWithRenameImpl(obj, oldPath, newPath, index) {
        var oldKey = oldPath[index], updated = isArrayImpl(obj) ? obj.slice() : assign({}, obj);
        index + 1 === oldPath.length ? (updated[newPath[index]] = updated[oldKey], isArrayImpl(updated) ? updated.splice(oldKey, 1) : delete updated[oldKey]) : updated[oldKey] = copyWithRenameImpl(
          obj[oldKey],
          oldPath,
          newPath,
          index + 1
        );
        return updated;
      }
      __name(copyWithRenameImpl, "copyWithRenameImpl");
      function copyWithDeleteImpl(obj, path108, index) {
        var key = path108[index], updated = isArrayImpl(obj) ? obj.slice() : assign({}, obj);
        if (index + 1 === path108.length)
          return isArrayImpl(updated) ? updated.splice(key, 1) : delete updated[key], updated;
        updated[key] = copyWithDeleteImpl(obj[key], path108, index + 1);
        return updated;
      }
      __name(copyWithDeleteImpl, "copyWithDeleteImpl");
      function shouldSuspendImpl() {
        return false;
      }
      __name(shouldSuspendImpl, "shouldSuspendImpl");
      function shouldErrorImpl() {
        return null;
      }
      __name(shouldErrorImpl, "shouldErrorImpl");
      function createFiber(tag2, pendingProps, key, mode) {
        return new FiberNode(tag2, pendingProps, key, mode);
      }
      __name(createFiber, "createFiber");
      function scheduleRoot(root, element) {
        root.context === emptyContextObject && (updateContainerSync(element, root, null, null), flushSyncWork());
      }
      __name(scheduleRoot, "scheduleRoot");
      function scheduleRefresh(root, update2) {
        if (null !== resolveFamily) {
          var staleFamilies = update2.staleFamilies;
          update2 = update2.updatedFamilies;
          flushPendingEffects();
          scheduleFibersWithFamiliesRecursively(
            root.current,
            update2,
            staleFamilies
          );
          flushSyncWork();
        }
      }
      __name(scheduleRefresh, "scheduleRefresh");
      function setRefreshHandler(handler) {
        resolveFamily = handler;
      }
      __name(setRefreshHandler, "setRefreshHandler");
      function warnForMissingKey() {
      }
      __name(warnForMissingKey, "warnForMissingKey");
      function warnInvalidHookAccess() {
        console.error(
          "Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://react.dev/link/rules-of-hooks"
        );
      }
      __name(warnInvalidHookAccess, "warnInvalidHookAccess");
      function warnInvalidContextAccess() {
        console.error(
          "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."
        );
      }
      __name(warnInvalidContextAccess, "warnInvalidContextAccess");
      function noop6() {
      }
      __name(noop6, "noop");
      function setToSortedString(set) {
        var array = [];
        set.forEach(function(value) {
          array.push(value);
        });
        return array.sort().join(", ");
      }
      __name(setToSortedString, "setToSortedString");
      function getNearestMountedFiber(fiber) {
        var node = fiber, nearestMounted = fiber;
        if (fiber.alternate) for (; node.return; ) node = node.return;
        else {
          fiber = node;
          do
            node = fiber, 0 !== (node.flags & 4098) && (nearestMounted = node.return), fiber = node.return;
          while (fiber);
        }
        return 3 === node.tag ? nearestMounted : null;
      }
      __name(getNearestMountedFiber, "getNearestMountedFiber");
      function assertIsMounted(fiber) {
        if (getNearestMountedFiber(fiber) !== fiber)
          throw Error("Unable to find node on an unmounted component.");
      }
      __name(assertIsMounted, "assertIsMounted");
      function findCurrentFiberUsingSlowPath(fiber) {
        var alternate = fiber.alternate;
        if (!alternate) {
          alternate = getNearestMountedFiber(fiber);
          if (null === alternate)
            throw Error("Unable to find node on an unmounted component.");
          return alternate !== fiber ? null : fiber;
        }
        for (var a = fiber, b = alternate; ; ) {
          var parentA = a.return;
          if (null === parentA) break;
          var parentB = parentA.alternate;
          if (null === parentB) {
            b = parentA.return;
            if (null !== b) {
              a = b;
              continue;
            }
            break;
          }
          if (parentA.child === parentB.child) {
            for (parentB = parentA.child; parentB; ) {
              if (parentB === a) return assertIsMounted(parentA), fiber;
              if (parentB === b) return assertIsMounted(parentA), alternate;
              parentB = parentB.sibling;
            }
            throw Error("Unable to find node on an unmounted component.");
          }
          if (a.return !== b.return) a = parentA, b = parentB;
          else {
            for (var didFindChild = false, _child = parentA.child; _child; ) {
              if (_child === a) {
                didFindChild = true;
                a = parentA;
                b = parentB;
                break;
              }
              if (_child === b) {
                didFindChild = true;
                b = parentA;
                a = parentB;
                break;
              }
              _child = _child.sibling;
            }
            if (!didFindChild) {
              for (_child = parentB.child; _child; ) {
                if (_child === a) {
                  didFindChild = true;
                  a = parentB;
                  b = parentA;
                  break;
                }
                if (_child === b) {
                  didFindChild = true;
                  b = parentB;
                  a = parentA;
                  break;
                }
                _child = _child.sibling;
              }
              if (!didFindChild)
                throw Error(
                  "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue."
                );
            }
          }
          if (a.alternate !== b)
            throw Error(
              "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue."
            );
        }
        if (3 !== a.tag)
          throw Error("Unable to find node on an unmounted component.");
        return a.stateNode.current === a ? fiber : alternate;
      }
      __name(findCurrentFiberUsingSlowPath, "findCurrentFiberUsingSlowPath");
      function findCurrentHostFiber(parent) {
        parent = findCurrentFiberUsingSlowPath(parent);
        return null !== parent ? findCurrentHostFiberImpl(parent) : null;
      }
      __name(findCurrentHostFiber, "findCurrentHostFiber");
      function findCurrentHostFiberImpl(node) {
        var tag2 = node.tag;
        if (5 === tag2 || 26 === tag2 || 27 === tag2 || 6 === tag2) return node;
        for (node = node.child; null !== node; ) {
          tag2 = findCurrentHostFiberImpl(node);
          if (null !== tag2) return tag2;
          node = node.sibling;
        }
        return null;
      }
      __name(findCurrentHostFiberImpl, "findCurrentHostFiberImpl");
      function findCurrentHostFiberWithNoPortalsImpl(node) {
        var tag2 = node.tag;
        if (5 === tag2 || 26 === tag2 || 27 === tag2 || 6 === tag2) return node;
        for (node = node.child; null !== node; ) {
          if (4 !== node.tag && (tag2 = findCurrentHostFiberWithNoPortalsImpl(node), null !== tag2))
            return tag2;
          node = node.sibling;
        }
        return null;
      }
      __name(findCurrentHostFiberWithNoPortalsImpl, "findCurrentHostFiberWithNoPortalsImpl");
      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;
      }
      __name(getIteratorFn, "getIteratorFn");
      function getComponentNameFromType(type) {
        if (null == type) return null;
        if ("function" === typeof type)
          return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
        if ("string" === typeof type) return type;
        switch (type) {
          case REACT_FRAGMENT_TYPE:
            return "Fragment";
          case REACT_PROFILER_TYPE:
            return "Profiler";
          case REACT_STRICT_MODE_TYPE:
            return "StrictMode";
          case REACT_SUSPENSE_TYPE:
            return "Suspense";
          case REACT_SUSPENSE_LIST_TYPE:
            return "SuspenseList";
          case REACT_ACTIVITY_TYPE:
            return "Activity";
        }
        if ("object" === typeof type)
          switch ("number" === typeof type.tag && console.error(
            "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
          ), type.$$typeof) {
            case REACT_PORTAL_TYPE:
              return "Portal";
            case REACT_CONTEXT_TYPE:
              return (type.displayName || "Context") + ".Provider";
            case REACT_CONSUMER_TYPE:
              return (type._context.displayName || "Context") + ".Consumer";
            case REACT_FORWARD_REF_TYPE:
              var innerType = type.render;
              type = type.displayName;
              type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
              return type;
            case REACT_MEMO_TYPE:
              return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
            case REACT_LAZY_TYPE:
              innerType = type._payload;
              type = type._init;
              try {
                return getComponentNameFromType(type(innerType));
              } catch (x) {
              }
          }
        return null;
      }
      __name(getComponentNameFromType, "getComponentNameFromType");
      function getComponentNameFromFiber(fiber) {
        var type = fiber.type;
        switch (fiber.tag) {
          case 31:
            return "Activity";
          case 24:
            return "Cache";
          case 9:
            return (type._context.displayName || "Context") + ".Consumer";
          case 10:
            return (type.displayName || "Context") + ".Provider";
          case 18:
            return "DehydratedFragment";
          case 11:
            return fiber = type.render, fiber = fiber.displayName || fiber.name || "", type.displayName || ("" !== fiber ? "ForwardRef(" + fiber + ")" : "ForwardRef");
          case 7:
            return "Fragment";
          case 26:
          case 27:
          case 5:
            return type;
          case 4:
            return "Portal";
          case 3:
            return "Root";
          case 6:
            return "Text";
          case 16:
            return getComponentNameFromType(type);
          case 8:
            return type === REACT_STRICT_MODE_TYPE ? "StrictMode" : "Mode";
          case 22:
            return "Offscreen";
          case 12:
            return "Profiler";
          case 21:
            return "Scope";
          case 13:
            return "Suspense";
          case 19:
            return "SuspenseList";
          case 25:
            return "TracingMarker";
          case 1:
          case 0:
          case 14:
          case 15:
            if ("function" === typeof type)
              return type.displayName || type.name || null;
            if ("string" === typeof type) return type;
            break;
          case 29:
            type = fiber._debugInfo;
            if (null != type) {
              for (var i = type.length - 1; 0 <= i; i--)
                if ("string" === typeof type[i].name) return type[i].name;
            }
            if (null !== fiber.return)
              return getComponentNameFromFiber(fiber.return);
        }
        return null;
      }
      __name(getComponentNameFromFiber, "getComponentNameFromFiber");
      function createCursor(defaultValue) {
        return { current: defaultValue };
      }
      __name(createCursor, "createCursor");
      function pop(cursor, fiber) {
        0 > index$jscomp$0 ? console.error("Unexpected pop.") : (fiber !== fiberStack[index$jscomp$0] && console.error("Unexpected Fiber popped."), cursor.current = valueStack[index$jscomp$0], valueStack[index$jscomp$0] = null, fiberStack[index$jscomp$0] = null, index$jscomp$0--);
      }
      __name(pop, "pop");
      function push2(cursor, value, fiber) {
        index$jscomp$0++;
        valueStack[index$jscomp$0] = cursor.current;
        fiberStack[index$jscomp$0] = fiber;
        cursor.current = value;
      }
      __name(push2, "push");
      function clz32Fallback(x) {
        x >>>= 0;
        return 0 === x ? 32 : 31 - (log$1(x) / LN2 | 0) | 0;
      }
      __name(clz32Fallback, "clz32Fallback");
      function getLabelForLane(lane) {
        if (lane & 1) return "SyncHydrationLane";
        if (lane & 2) return "Sync";
        if (lane & 4) return "InputContinuousHydration";
        if (lane & 8) return "InputContinuous";
        if (lane & 16) return "DefaultHydration";
        if (lane & 32) return "Default";
        if (lane & 128) return "TransitionHydration";
        if (lane & 4194048) return "Transition";
        if (lane & 62914560) return "Retry";
        if (lane & 67108864) return "SelectiveHydration";
        if (lane & 134217728) return "IdleHydration";
        if (lane & 268435456) return "Idle";
        if (lane & 536870912) return "Offscreen";
        if (lane & 1073741824) return "Deferred";
      }
      __name(getLabelForLane, "getLabelForLane");
      function getHighestPriorityLanes(lanes) {
        var pendingSyncLanes = lanes & 42;
        if (0 !== pendingSyncLanes) return pendingSyncLanes;
        switch (lanes & -lanes) {
          case 1:
            return 1;
          case 2:
            return 2;
          case 4:
            return 4;
          case 8:
            return 8;
          case 16:
            return 16;
          case 32:
            return 32;
          case 64:
            return 64;
          case 128:
            return 128;
          case 256:
          case 512:
          case 1024:
          case 2048:
          case 4096:
          case 8192:
          case 16384:
          case 32768:
          case 65536:
          case 131072:
          case 262144:
          case 524288:
          case 1048576:
          case 2097152:
            return lanes & 4194048;
          case 4194304:
          case 8388608:
          case 16777216:
          case 33554432:
            return lanes & 62914560;
          case 67108864:
            return 67108864;
          case 134217728:
            return 134217728;
          case 268435456:
            return 268435456;
          case 536870912:
            return 536870912;
          case 1073741824:
            return 0;
          default:
            return console.error(
              "Should have found matching lanes. This is a bug in React."
            ), lanes;
        }
      }
      __name(getHighestPriorityLanes, "getHighestPriorityLanes");
      function getNextLanes(root, wipLanes, rootHasPendingCommit) {
        var pendingLanes = root.pendingLanes;
        if (0 === pendingLanes) return 0;
        var nextLanes = 0, suspendedLanes = root.suspendedLanes, pingedLanes = root.pingedLanes;
        root = root.warmLanes;
        var nonIdlePendingLanes = pendingLanes & 134217727;
        0 !== nonIdlePendingLanes ? (pendingLanes = nonIdlePendingLanes & ~suspendedLanes, 0 !== pendingLanes ? nextLanes = getHighestPriorityLanes(pendingLanes) : (pingedLanes &= nonIdlePendingLanes, 0 !== pingedLanes ? nextLanes = getHighestPriorityLanes(pingedLanes) : rootHasPendingCommit || (rootHasPendingCommit = nonIdlePendingLanes & ~root, 0 !== rootHasPendingCommit && (nextLanes = getHighestPriorityLanes(rootHasPendingCommit))))) : (nonIdlePendingLanes = pendingLanes & ~suspendedLanes, 0 !== nonIdlePendingLanes ? nextLanes = getHighestPriorityLanes(nonIdlePendingLanes) : 0 !== pingedLanes ? nextLanes = getHighestPriorityLanes(pingedLanes) : rootHasPendingCommit || (rootHasPendingCommit = pendingLanes & ~root, 0 !== rootHasPendingCommit && (nextLanes = getHighestPriorityLanes(rootHasPendingCommit))));
        return 0 === nextLanes ? 0 : 0 !== wipLanes && wipLanes !== nextLanes && 0 === (wipLanes & suspendedLanes) && (suspendedLanes = nextLanes & -nextLanes, rootHasPendingCommit = wipLanes & -wipLanes, suspendedLanes >= rootHasPendingCommit || 32 === suspendedLanes && 0 !== (rootHasPendingCommit & 4194048)) ? wipLanes : nextLanes;
      }
      __name(getNextLanes, "getNextLanes");
      function checkIfRootIsPrerendering(root, renderLanes2) {
        return 0 === (root.pendingLanes & ~(root.suspendedLanes & ~root.pingedLanes) & renderLanes2);
      }
      __name(checkIfRootIsPrerendering, "checkIfRootIsPrerendering");
      function computeExpirationTime(lane, currentTime) {
        switch (lane) {
          case 1:
          case 2:
          case 4:
          case 8:
          case 64:
            return currentTime + 250;
          case 16:
          case 32:
          case 128:
          case 256:
          case 512:
          case 1024:
          case 2048:
          case 4096:
          case 8192:
          case 16384:
          case 32768:
          case 65536:
          case 131072:
          case 262144:
          case 524288:
          case 1048576:
          case 2097152:
            return currentTime + 5e3;
          case 4194304:
          case 8388608:
          case 16777216:
          case 33554432:
            return -1;
          case 67108864:
          case 134217728:
          case 268435456:
          case 536870912:
          case 1073741824:
            return -1;
          default:
            return console.error(
              "Should have found matching lanes. This is a bug in React."
            ), -1;
        }
      }
      __name(computeExpirationTime, "computeExpirationTime");
      function claimNextTransitionLane() {
        var lane = nextTransitionLane;
        nextTransitionLane <<= 1;
        0 === (nextTransitionLane & 4194048) && (nextTransitionLane = 256);
        return lane;
      }
      __name(claimNextTransitionLane, "claimNextTransitionLane");
      function claimNextRetryLane() {
        var lane = nextRetryLane;
        nextRetryLane <<= 1;
        0 === (nextRetryLane & 62914560) && (nextRetryLane = 4194304);
        return lane;
      }
      __name(claimNextRetryLane, "claimNextRetryLane");
      function createLaneMap(initial) {
        for (var laneMap = [], i = 0; 31 > i; i++) laneMap.push(initial);
        return laneMap;
      }
      __name(createLaneMap, "createLaneMap");
      function markRootUpdated$1(root, updateLane) {
        root.pendingLanes |= updateLane;
        268435456 !== updateLane && (root.suspendedLanes = 0, root.pingedLanes = 0, root.warmLanes = 0);
      }
      __name(markRootUpdated$1, "markRootUpdated$1");
      function markRootFinished(root, finishedLanes, remainingLanes, spawnedLane, updatedLanes, suspendedRetryLanes) {
        var previouslyPendingLanes = root.pendingLanes;
        root.pendingLanes = remainingLanes;
        root.suspendedLanes = 0;
        root.pingedLanes = 0;
        root.warmLanes = 0;
        root.expiredLanes &= remainingLanes;
        root.entangledLanes &= remainingLanes;
        root.errorRecoveryDisabledLanes &= remainingLanes;
        root.shellSuspendCounter = 0;
        var entanglements = root.entanglements, expirationTimes = root.expirationTimes, hiddenUpdates = root.hiddenUpdates;
        for (remainingLanes = previouslyPendingLanes & ~remainingLanes; 0 < remainingLanes; ) {
          var index = 31 - clz32(remainingLanes), lane = 1 << index;
          entanglements[index] = 0;
          expirationTimes[index] = -1;
          var hiddenUpdatesForLane = hiddenUpdates[index];
          if (null !== hiddenUpdatesForLane)
            for (hiddenUpdates[index] = null, index = 0; index < hiddenUpdatesForLane.length; index++) {
              var update2 = hiddenUpdatesForLane[index];
              null !== update2 && (update2.lane &= -536870913);
            }
          remainingLanes &= ~lane;
        }
        0 !== spawnedLane && markSpawnedDeferredLane(root, spawnedLane, 0);
        0 !== suspendedRetryLanes && 0 === updatedLanes && 0 !== root.tag && (root.suspendedLanes |= suspendedRetryLanes & ~(previouslyPendingLanes & ~finishedLanes));
      }
      __name(markRootFinished, "markRootFinished");
      function markSpawnedDeferredLane(root, spawnedLane, entangledLanes) {
        root.pendingLanes |= spawnedLane;
        root.suspendedLanes &= ~spawnedLane;
        var spawnedLaneIndex = 31 - clz32(spawnedLane);
        root.entangledLanes |= spawnedLane;
        root.entanglements[spawnedLaneIndex] = root.entanglements[spawnedLaneIndex] | 1073741824 | entangledLanes & 4194090;
      }
      __name(markSpawnedDeferredLane, "markSpawnedDeferredLane");
      function markRootEntangled(root, entangledLanes) {
        var rootEntangledLanes = root.entangledLanes |= entangledLanes;
        for (root = root.entanglements; rootEntangledLanes; ) {
          var index = 31 - clz32(rootEntangledLanes), lane = 1 << index;
          lane & entangledLanes | root[index] & entangledLanes && (root[index] |= entangledLanes);
          rootEntangledLanes &= ~lane;
        }
      }
      __name(markRootEntangled, "markRootEntangled");
      function getBumpedLaneForHydrationByLane(lane) {
        switch (lane) {
          case 2:
            lane = 1;
            break;
          case 8:
            lane = 4;
            break;
          case 32:
            lane = 16;
            break;
          case 256:
          case 512:
          case 1024:
          case 2048:
          case 4096:
          case 8192:
          case 16384:
          case 32768:
          case 65536:
          case 131072:
          case 262144:
          case 524288:
          case 1048576:
          case 2097152:
          case 4194304:
          case 8388608:
          case 16777216:
          case 33554432:
            lane = 128;
            break;
          case 268435456:
            lane = 134217728;
            break;
          default:
            lane = 0;
        }
        return lane;
      }
      __name(getBumpedLaneForHydrationByLane, "getBumpedLaneForHydrationByLane");
      function addFiberToLanesMap(root, fiber, lanes) {
        if (isDevToolsPresent)
          for (root = root.pendingUpdatersLaneMap; 0 < lanes; ) {
            var index = 31 - clz32(lanes), lane = 1 << index;
            root[index].add(fiber);
            lanes &= ~lane;
          }
      }
      __name(addFiberToLanesMap, "addFiberToLanesMap");
      function movePendingFibersToMemoized(root, lanes) {
        if (isDevToolsPresent)
          for (var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap, memoizedUpdaters = root.memoizedUpdaters; 0 < lanes; ) {
            var index = 31 - clz32(lanes);
            root = 1 << index;
            index = pendingUpdatersLaneMap[index];
            0 < index.size && (index.forEach(function(fiber) {
              var alternate = fiber.alternate;
              null !== alternate && memoizedUpdaters.has(alternate) || memoizedUpdaters.add(fiber);
            }), index.clear());
            lanes &= ~root;
          }
      }
      __name(movePendingFibersToMemoized, "movePendingFibersToMemoized");
      function lanesToEventPriority(lanes) {
        lanes &= -lanes;
        return 2 < lanes ? 8 < lanes ? 0 !== (lanes & 134217727) ? 32 : 268435456 : 8 : 2;
      }
      __name(lanesToEventPriority, "lanesToEventPriority");
      function injectInternals(internals) {
        if ("undefined" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) return false;
        var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
        if (hook.isDisabled) return true;
        if (!hook.supportsFiber)
          return console.error(
            "The installed version of React DevTools is too old and will not work with the current version of React. Please update React DevTools. https://react.dev/link/react-devtools"
          ), true;
        try {
          rendererID = hook.inject(internals), injectedHook = hook;
        } catch (err) {
          console.error("React instrumentation encountered an error: %s.", err);
        }
        return hook.checkDCE ? true : false;
      }
      __name(injectInternals, "injectInternals");
      function setIsStrictModeForDevtools(newIsStrictMode) {
        "function" === typeof log && unstable_setDisableYieldValue(newIsStrictMode);
        if (injectedHook && "function" === typeof injectedHook.setStrictMode)
          try {
            injectedHook.setStrictMode(rendererID, newIsStrictMode);
          } catch (err) {
            hasLoggedError || (hasLoggedError = true, console.error(
              "React instrumentation encountered an error: %s",
              err
            ));
          }
      }
      __name(setIsStrictModeForDevtools, "setIsStrictModeForDevtools");
      function injectProfilingHooks(profilingHooks) {
        injectedProfilingHooks = profilingHooks;
      }
      __name(injectProfilingHooks, "injectProfilingHooks");
      function markCommitStopped() {
        null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markCommitStopped && injectedProfilingHooks.markCommitStopped();
      }
      __name(markCommitStopped, "markCommitStopped");
      function markComponentRenderStarted(fiber) {
        null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentRenderStarted && injectedProfilingHooks.markComponentRenderStarted(fiber);
      }
      __name(markComponentRenderStarted, "markComponentRenderStarted");
      function markComponentRenderStopped() {
        null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentRenderStopped && injectedProfilingHooks.markComponentRenderStopped();
      }
      __name(markComponentRenderStopped, "markComponentRenderStopped");
      function markRenderStarted(lanes) {
        null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markRenderStarted && injectedProfilingHooks.markRenderStarted(lanes);
      }
      __name(markRenderStarted, "markRenderStarted");
      function markRenderStopped() {
        null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markRenderStopped && injectedProfilingHooks.markRenderStopped();
      }
      __name(markRenderStopped, "markRenderStopped");
      function markStateUpdateScheduled(fiber, lane) {
        null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markStateUpdateScheduled && injectedProfilingHooks.markStateUpdateScheduled(fiber, lane);
      }
      __name(markStateUpdateScheduled, "markStateUpdateScheduled");
      function disabledLog() {
      }
      __name(disabledLog, "disabledLog");
      function disableLogs() {
        if (0 === disabledDepth) {
          prevLog = console.log;
          prevInfo = console.info;
          prevWarn = console.warn;
          prevError = console.error;
          prevGroup = console.group;
          prevGroupCollapsed = console.groupCollapsed;
          prevGroupEnd = console.groupEnd;
          var props = {
            configurable: true,
            enumerable: true,
            value: disabledLog,
            writable: true
          };
          Object.defineProperties(console, {
            info: props,
            log: props,
            warn: props,
            error: props,
            group: props,
            groupCollapsed: props,
            groupEnd: props
          });
        }
        disabledDepth++;
      }
      __name(disableLogs, "disableLogs");
      function reenableLogs() {
        disabledDepth--;
        if (0 === disabledDepth) {
          var props = { configurable: true, enumerable: true, writable: true };
          Object.defineProperties(console, {
            log: assign({}, props, { value: prevLog }),
            info: assign({}, props, { value: prevInfo }),
            warn: assign({}, props, { value: prevWarn }),
            error: assign({}, props, { value: prevError }),
            group: assign({}, props, { value: prevGroup }),
            groupCollapsed: assign({}, props, { value: prevGroupCollapsed }),
            groupEnd: assign({}, props, { value: prevGroupEnd })
          });
        }
        0 > disabledDepth && console.error(
          "disabledDepth fell below zero. This is a bug in React. Please file an issue."
        );
      }
      __name(reenableLogs, "reenableLogs");
      function describeBuiltInComponentFrame(name3) {
        if (void 0 === prefix)
          try {
            throw Error();
          } catch (x) {
            var match2 = x.stack.trim().match(/\n( *(at )?)/);
            prefix = match2 && match2[1] || "";
            suffix = -1 < x.stack.indexOf("\n    at") ? " (<anonymous>)" : -1 < x.stack.indexOf("@") ? "@unknown:0:0" : "";
          }
        return "\n" + prefix + name3 + suffix;
      }
      __name(describeBuiltInComponentFrame, "describeBuiltInComponentFrame");
      function describeNativeComponentFrame(fn, construct) {
        if (!fn || reentry) return "";
        var frame = componentFrameCache.get(fn);
        if (void 0 !== frame) return frame;
        reentry = true;
        frame = Error.prepareStackTrace;
        Error.prepareStackTrace = void 0;
        var previousDispatcher = null;
        previousDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = null;
        disableLogs();
        try {
          var RunInRootFrame = {
            DetermineComponentFrameRoot: /* @__PURE__ */ __name(function() {
              try {
                if (construct) {
                  var Fake = /* @__PURE__ */ __name(function() {
                    throw Error();
                  }, "Fake");
                  Object.defineProperty(Fake.prototype, "props", {
                    set: /* @__PURE__ */ __name(function() {
                      throw Error();
                    }, "set")
                  });
                  if ("object" === typeof Reflect && Reflect.construct) {
                    try {
                      Reflect.construct(Fake, []);
                    } catch (x) {
                      var control = x;
                    }
                    Reflect.construct(fn, [], Fake);
                  } else {
                    try {
                      Fake.call();
                    } catch (x$0) {
                      control = x$0;
                    }
                    fn.call(Fake.prototype);
                  }
                } else {
                  try {
                    throw Error();
                  } catch (x$1) {
                    control = x$1;
                  }
                  (Fake = fn()) && "function" === typeof Fake.catch && Fake.catch(function() {
                  });
                }
              } catch (sample) {
                if (sample && control && "string" === typeof sample.stack)
                  return [sample.stack, control.stack];
              }
              return [null, null];
            }, "DetermineComponentFrameRoot")
          };
          RunInRootFrame.DetermineComponentFrameRoot.displayName = "DetermineComponentFrameRoot";
          var namePropDescriptor = Object.getOwnPropertyDescriptor(
            RunInRootFrame.DetermineComponentFrameRoot,
            "name"
          );
          namePropDescriptor && namePropDescriptor.configurable && Object.defineProperty(
            RunInRootFrame.DetermineComponentFrameRoot,
            "name",
            { value: "DetermineComponentFrameRoot" }
          );
          var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), sampleStack = _RunInRootFrame$Deter[0], controlStack = _RunInRootFrame$Deter[1];
          if (sampleStack && controlStack) {
            var sampleLines = sampleStack.split("\n"), controlLines = controlStack.split("\n");
            for (_RunInRootFrame$Deter = namePropDescriptor = 0; namePropDescriptor < sampleLines.length && !sampleLines[namePropDescriptor].includes(
              "DetermineComponentFrameRoot"
            ); )
              namePropDescriptor++;
            for (; _RunInRootFrame$Deter < controlLines.length && !controlLines[_RunInRootFrame$Deter].includes(
              "DetermineComponentFrameRoot"
            ); )
              _RunInRootFrame$Deter++;
            if (namePropDescriptor === sampleLines.length || _RunInRootFrame$Deter === controlLines.length)
              for (namePropDescriptor = sampleLines.length - 1, _RunInRootFrame$Deter = controlLines.length - 1; 1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter && sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]; )
                _RunInRootFrame$Deter--;
            for (; 1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter; namePropDescriptor--, _RunInRootFrame$Deter--)
              if (sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]) {
                if (1 !== namePropDescriptor || 1 !== _RunInRootFrame$Deter) {
                  do
                    if (namePropDescriptor--, _RunInRootFrame$Deter--, 0 > _RunInRootFrame$Deter || sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]) {
                      var _frame = "\n" + sampleLines[namePropDescriptor].replace(
                        " at new ",
                        " at "
                      );
                      fn.displayName && _frame.includes("<anonymous>") && (_frame = _frame.replace("<anonymous>", fn.displayName));
                      "function" === typeof fn && componentFrameCache.set(fn, _frame);
                      return _frame;
                    }
                  while (1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter);
                }
                break;
              }
          }
        } finally {
          reentry = false, ReactSharedInternals.H = previousDispatcher, reenableLogs(), Error.prepareStackTrace = frame;
        }
        sampleLines = (sampleLines = fn ? fn.displayName || fn.name : "") ? describeBuiltInComponentFrame(sampleLines) : "";
        "function" === typeof fn && componentFrameCache.set(fn, sampleLines);
        return sampleLines;
      }
      __name(describeNativeComponentFrame, "describeNativeComponentFrame");
      function formatOwnerStack(error) {
        var prevPrepareStackTrace = Error.prepareStackTrace;
        Error.prepareStackTrace = void 0;
        error = error.stack;
        Error.prepareStackTrace = prevPrepareStackTrace;
        error.startsWith("Error: react-stack-top-frame\n") && (error = error.slice(29));
        prevPrepareStackTrace = error.indexOf("\n");
        -1 !== prevPrepareStackTrace && (error = error.slice(prevPrepareStackTrace + 1));
        prevPrepareStackTrace = error.indexOf("react-stack-bottom-frame");
        -1 !== prevPrepareStackTrace && (prevPrepareStackTrace = error.lastIndexOf(
          "\n",
          prevPrepareStackTrace
        ));
        if (-1 !== prevPrepareStackTrace)
          error = error.slice(0, prevPrepareStackTrace);
        else return "";
        return error;
      }
      __name(formatOwnerStack, "formatOwnerStack");
      function describeFiber(fiber) {
        switch (fiber.tag) {
          case 26:
          case 27:
          case 5:
            return describeBuiltInComponentFrame(fiber.type);
          case 16:
            return describeBuiltInComponentFrame("Lazy");
          case 13:
            return describeBuiltInComponentFrame("Suspense");
          case 19:
            return describeBuiltInComponentFrame("SuspenseList");
          case 0:
          case 15:
            return describeNativeComponentFrame(fiber.type, false);
          case 11:
            return describeNativeComponentFrame(fiber.type.render, false);
          case 1:
            return describeNativeComponentFrame(fiber.type, true);
          case 31:
            return describeBuiltInComponentFrame("Activity");
          default:
            return "";
        }
      }
      __name(describeFiber, "describeFiber");
      function getStackByFiberInDevAndProd(workInProgress2) {
        try {
          var info = "";
          do {
            info += describeFiber(workInProgress2);
            var debugInfo = workInProgress2._debugInfo;
            if (debugInfo)
              for (var i = debugInfo.length - 1; 0 <= i; i--) {
                var entry = debugInfo[i];
                if ("string" === typeof entry.name) {
                  var JSCompiler_temp_const = info, env7 = entry.env;
                  var JSCompiler_inline_result = describeBuiltInComponentFrame(
                    entry.name + (env7 ? " [" + env7 + "]" : "")
                  );
                  info = JSCompiler_temp_const + JSCompiler_inline_result;
                }
              }
            workInProgress2 = workInProgress2.return;
          } while (workInProgress2);
          return info;
        } catch (x) {
          return "\nError generating stack: " + x.message + "\n" + x.stack;
        }
      }
      __name(getStackByFiberInDevAndProd, "getStackByFiberInDevAndProd");
      function describeFunctionComponentFrameWithoutLineNumber(fn) {
        return (fn = fn ? fn.displayName || fn.name : "") ? describeBuiltInComponentFrame(fn) : "";
      }
      __name(describeFunctionComponentFrameWithoutLineNumber, "describeFunctionComponentFrameWithoutLineNumber");
      function createCapturedValueAtFiber(value, source2) {
        if ("object" === typeof value && null !== value) {
          var existing = CapturedStacks.get(value);
          if (void 0 !== existing) return existing;
          source2 = {
            value,
            source: source2,
            stack: getStackByFiberInDevAndProd(source2)
          };
          CapturedStacks.set(value, source2);
          return source2;
        }
        return {
          value,
          source: source2,
          stack: getStackByFiberInDevAndProd(source2)
        };
      }
      __name(createCapturedValueAtFiber, "createCapturedValueAtFiber");
      function pushTreeFork(workInProgress2, totalChildren) {
        warnIfNotHydrating();
        forkStack[forkStackIndex++] = treeForkCount;
        forkStack[forkStackIndex++] = treeForkProvider;
        treeForkProvider = workInProgress2;
        treeForkCount = totalChildren;
      }
      __name(pushTreeFork, "pushTreeFork");
      function pushTreeId(workInProgress2, totalChildren, index) {
        warnIfNotHydrating();
        idStack[idStackIndex++] = treeContextId;
        idStack[idStackIndex++] = treeContextOverflow;
        idStack[idStackIndex++] = treeContextProvider;
        treeContextProvider = workInProgress2;
        var baseIdWithLeadingBit = treeContextId;
        workInProgress2 = treeContextOverflow;
        var baseLength = 32 - clz32(baseIdWithLeadingBit) - 1;
        baseIdWithLeadingBit &= ~(1 << baseLength);
        index += 1;
        var length = 32 - clz32(totalChildren) + baseLength;
        if (30 < length) {
          var numberOfOverflowBits = baseLength - baseLength % 5;
          length = (baseIdWithLeadingBit & (1 << numberOfOverflowBits) - 1).toString(32);
          baseIdWithLeadingBit >>= numberOfOverflowBits;
          baseLength -= numberOfOverflowBits;
          treeContextId = 1 << 32 - clz32(totalChildren) + baseLength | index << baseLength | baseIdWithLeadingBit;
          treeContextOverflow = length + workInProgress2;
        } else
          treeContextId = 1 << length | index << baseLength | baseIdWithLeadingBit, treeContextOverflow = workInProgress2;
      }
      __name(pushTreeId, "pushTreeId");
      function pushMaterializedTreeId(workInProgress2) {
        warnIfNotHydrating();
        null !== workInProgress2.return && (pushTreeFork(workInProgress2, 1), pushTreeId(workInProgress2, 1, 0));
      }
      __name(pushMaterializedTreeId, "pushMaterializedTreeId");
      function popTreeContext(workInProgress2) {
        for (; workInProgress2 === treeForkProvider; )
          treeForkProvider = forkStack[--forkStackIndex], forkStack[forkStackIndex] = null, treeForkCount = forkStack[--forkStackIndex], forkStack[forkStackIndex] = null;
        for (; workInProgress2 === treeContextProvider; )
          treeContextProvider = idStack[--idStackIndex], idStack[idStackIndex] = null, treeContextOverflow = idStack[--idStackIndex], idStack[idStackIndex] = null, treeContextId = idStack[--idStackIndex], idStack[idStackIndex] = null;
      }
      __name(popTreeContext, "popTreeContext");
      function warnIfNotHydrating() {
        isHydrating || console.error(
          "Expected to be hydrating. This is a bug in React. Please file an issue."
        );
      }
      __name(warnIfNotHydrating, "warnIfNotHydrating");
      function requiredContext(c3) {
        null === c3 && console.error(
          "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue."
        );
        return c3;
      }
      __name(requiredContext, "requiredContext");
      function pushHostContainer(fiber, nextRootInstance) {
        push2(rootInstanceStackCursor, nextRootInstance, fiber);
        push2(contextFiberStackCursor, fiber, fiber);
        push2(contextStackCursor, null, fiber);
        nextRootInstance = getRootHostContext(nextRootInstance);
        pop(contextStackCursor, fiber);
        push2(contextStackCursor, nextRootInstance, fiber);
      }
      __name(pushHostContainer, "pushHostContainer");
      function popHostContainer(fiber) {
        pop(contextStackCursor, fiber);
        pop(contextFiberStackCursor, fiber);
        pop(rootInstanceStackCursor, fiber);
      }
      __name(popHostContainer, "popHostContainer");
      function getHostContext() {
        return requiredContext(contextStackCursor.current);
      }
      __name(getHostContext, "getHostContext");
      function pushHostContext(fiber) {
        null !== fiber.memoizedState && push2(hostTransitionProviderCursor, fiber, fiber);
        var context2 = requiredContext(contextStackCursor.current), nextContext = getChildHostContext(context2, fiber.type);
        context2 !== nextContext && (push2(contextFiberStackCursor, fiber, fiber), push2(contextStackCursor, nextContext, fiber));
      }
      __name(pushHostContext, "pushHostContext");
      function popHostContext(fiber) {
        contextFiberStackCursor.current === fiber && (pop(contextStackCursor, fiber), pop(contextFiberStackCursor, fiber));
        hostTransitionProviderCursor.current === fiber && (pop(hostTransitionProviderCursor, fiber), isPrimaryRenderer ? HostTransitionContext._currentValue = NotPendingTransition : HostTransitionContext._currentValue2 = NotPendingTransition);
      }
      __name(popHostContext, "popHostContext");
      function findNotableNode(node, indent) {
        return void 0 === node.serverProps && 0 === node.serverTail.length && 1 === node.children.length && 3 < node.distanceFromLeaf && node.distanceFromLeaf > 15 - indent ? findNotableNode(node.children[0], indent) : node;
      }
      __name(findNotableNode, "findNotableNode");
      function indentation(indent) {
        return "  " + "  ".repeat(indent);
      }
      __name(indentation, "indentation");
      function added(indent) {
        return "+ " + "  ".repeat(indent);
      }
      __name(added, "added");
      function removed(indent) {
        return "- " + "  ".repeat(indent);
      }
      __name(removed, "removed");
      function describeFiberType(fiber) {
        switch (fiber.tag) {
          case 26:
          case 27:
          case 5:
            return fiber.type;
          case 16:
            return "Lazy";
          case 13:
            return "Suspense";
          case 19:
            return "SuspenseList";
          case 0:
          case 15:
            return fiber = fiber.type, fiber.displayName || fiber.name || null;
          case 11:
            return fiber = fiber.type.render, fiber.displayName || fiber.name || null;
          case 1:
            return fiber = fiber.type, fiber.displayName || fiber.name || null;
          default:
            return null;
        }
      }
      __name(describeFiberType, "describeFiberType");
      function describeTextNode(content, maxLength) {
        return needsEscaping.test(content) ? (content = JSON.stringify(content), content.length > maxLength - 2 ? 8 > maxLength ? '{"..."}' : "{" + content.slice(0, maxLength - 7) + '..."}' : "{" + content + "}") : content.length > maxLength ? 5 > maxLength ? '{"..."}' : content.slice(0, maxLength - 3) + "..." : content;
      }
      __name(describeTextNode, "describeTextNode");
      function describeTextDiff(clientText, serverProps, indent) {
        var maxLength = 120 - 2 * indent;
        if (null === serverProps)
          return added(indent) + describeTextNode(clientText, maxLength) + "\n";
        if ("string" === typeof serverProps) {
          for (var firstDiff = 0; firstDiff < serverProps.length && firstDiff < clientText.length && serverProps.charCodeAt(firstDiff) === clientText.charCodeAt(firstDiff); firstDiff++) ;
          firstDiff > maxLength - 8 && 10 < firstDiff && (clientText = "..." + clientText.slice(firstDiff - 8), serverProps = "..." + serverProps.slice(firstDiff - 8));
          return added(indent) + describeTextNode(clientText, maxLength) + "\n" + removed(indent) + describeTextNode(serverProps, maxLength) + "\n";
        }
        return indentation(indent) + describeTextNode(clientText, maxLength) + "\n";
      }
      __name(describeTextDiff, "describeTextDiff");
      function objectName(object) {
        return Object.prototype.toString.call(object).replace(/^\[object (.*)\]$/, function(m, p0) {
          return p0;
        });
      }
      __name(objectName, "objectName");
      function describeValue(value, maxLength) {
        switch (typeof value) {
          case "string":
            return value = JSON.stringify(value), value.length > maxLength ? 5 > maxLength ? '"..."' : value.slice(0, maxLength - 4) + '..."' : value;
          case "object":
            if (null === value) return "null";
            if (isArrayImpl(value)) return "[...]";
            if (value.$$typeof === REACT_ELEMENT_TYPE)
              return (maxLength = getComponentNameFromType(value.type)) ? "<" + maxLength + ">" : "<...>";
            var name3 = objectName(value);
            if ("Object" === name3) {
              name3 = "";
              maxLength -= 2;
              for (var propName in value)
                if (value.hasOwnProperty(propName)) {
                  var jsonPropName = JSON.stringify(propName);
                  jsonPropName !== '"' + propName + '"' && (propName = jsonPropName);
                  maxLength -= propName.length - 2;
                  jsonPropName = describeValue(
                    value[propName],
                    15 > maxLength ? maxLength : 15
                  );
                  maxLength -= jsonPropName.length;
                  if (0 > maxLength) {
                    name3 += "" === name3 ? "..." : ", ...";
                    break;
                  }
                  name3 += ("" === name3 ? "" : ",") + propName + ":" + jsonPropName;
                }
              return "{" + name3 + "}";
            }
            return name3;
          case "function":
            return (maxLength = value.displayName || value.name) ? "function " + maxLength : "function";
          default:
            return String(value);
        }
      }
      __name(describeValue, "describeValue");
      function describePropValue(value, maxLength) {
        return "string" !== typeof value || needsEscaping.test(value) ? "{" + describeValue(value, maxLength - 2) + "}" : value.length > maxLength - 2 ? 5 > maxLength ? '"..."' : '"' + value.slice(0, maxLength - 5) + '..."' : '"' + value + '"';
      }
      __name(describePropValue, "describePropValue");
      function describeExpandedElement(type, props, rowPrefix) {
        var remainingRowLength = 120 - rowPrefix.length - type.length, properties = [], propName;
        for (propName in props)
          if (props.hasOwnProperty(propName) && "children" !== propName) {
            var propValue = describePropValue(
              props[propName],
              120 - rowPrefix.length - propName.length - 1
            );
            remainingRowLength -= propName.length + propValue.length + 2;
            properties.push(propName + "=" + propValue);
          }
        return 0 === properties.length ? rowPrefix + "<" + type + ">\n" : 0 < remainingRowLength ? rowPrefix + "<" + type + " " + properties.join(" ") + ">\n" : rowPrefix + "<" + type + "\n" + rowPrefix + "  " + properties.join("\n" + rowPrefix + "  ") + "\n" + rowPrefix + ">\n";
      }
      __name(describeExpandedElement, "describeExpandedElement");
      function describePropertiesDiff(clientObject, serverObject, indent) {
        var properties = "", remainingServerProperties = assign({}, serverObject), propName;
        for (propName in clientObject)
          if (clientObject.hasOwnProperty(propName)) {
            delete remainingServerProperties[propName];
            var maxLength = 120 - 2 * indent - propName.length - 2, clientPropValue = describeValue(clientObject[propName], maxLength);
            serverObject.hasOwnProperty(propName) ? (maxLength = describeValue(serverObject[propName], maxLength), properties += added(indent) + propName + ": " + clientPropValue + "\n", properties += removed(indent) + propName + ": " + maxLength + "\n") : properties += added(indent) + propName + ": " + clientPropValue + "\n";
          }
        for (var _propName in remainingServerProperties)
          remainingServerProperties.hasOwnProperty(_propName) && (clientObject = describeValue(
            remainingServerProperties[_propName],
            120 - 2 * indent - _propName.length - 2
          ), properties += removed(indent) + _propName + ": " + clientObject + "\n");
        return properties;
      }
      __name(describePropertiesDiff, "describePropertiesDiff");
      function describeElementDiff(type, clientProps, serverProps, indent) {
        var content = "", serverPropNames = /* @__PURE__ */ new Map();
        for (propName$jscomp$0 in serverProps)
          serverProps.hasOwnProperty(propName$jscomp$0) && serverPropNames.set(
            propName$jscomp$0.toLowerCase(),
            propName$jscomp$0
          );
        if (1 === serverPropNames.size && serverPropNames.has("children"))
          content += describeExpandedElement(
            type,
            clientProps,
            indentation(indent)
          );
        else {
          for (var _propName2 in clientProps)
            if (clientProps.hasOwnProperty(_propName2) && "children" !== _propName2) {
              var maxLength$jscomp$0 = 120 - 2 * (indent + 1) - _propName2.length - 1, serverPropName = serverPropNames.get(_propName2.toLowerCase());
              if (void 0 !== serverPropName) {
                serverPropNames.delete(_propName2.toLowerCase());
                var propName$jscomp$0 = clientProps[_propName2];
                serverPropName = serverProps[serverPropName];
                var clientPropValue = describePropValue(
                  propName$jscomp$0,
                  maxLength$jscomp$0
                );
                maxLength$jscomp$0 = describePropValue(
                  serverPropName,
                  maxLength$jscomp$0
                );
                "object" === typeof propName$jscomp$0 && null !== propName$jscomp$0 && "object" === typeof serverPropName && null !== serverPropName && "Object" === objectName(propName$jscomp$0) && "Object" === objectName(serverPropName) && (2 < Object.keys(propName$jscomp$0).length || 2 < Object.keys(serverPropName).length || -1 < clientPropValue.indexOf("...") || -1 < maxLength$jscomp$0.indexOf("...")) ? content += indentation(indent + 1) + _propName2 + "={{\n" + describePropertiesDiff(
                  propName$jscomp$0,
                  serverPropName,
                  indent + 2
                ) + indentation(indent + 1) + "}}\n" : (content += added(indent + 1) + _propName2 + "=" + clientPropValue + "\n", content += removed(indent + 1) + _propName2 + "=" + maxLength$jscomp$0 + "\n");
              } else
                content += indentation(indent + 1) + _propName2 + "=" + describePropValue(clientProps[_propName2], maxLength$jscomp$0) + "\n";
            }
          serverPropNames.forEach(function(propName) {
            if ("children" !== propName) {
              var maxLength = 120 - 2 * (indent + 1) - propName.length - 1;
              content += removed(indent + 1) + propName + "=" + describePropValue(serverProps[propName], maxLength) + "\n";
            }
          });
          content = "" === content ? indentation(indent) + "<" + type + ">\n" : indentation(indent) + "<" + type + "\n" + content + indentation(indent) + ">\n";
        }
        type = serverProps.children;
        clientProps = clientProps.children;
        if ("string" === typeof type || "number" === typeof type || "bigint" === typeof type) {
          serverPropNames = "";
          if ("string" === typeof clientProps || "number" === typeof clientProps || "bigint" === typeof clientProps)
            serverPropNames = "" + clientProps;
          content += describeTextDiff(serverPropNames, "" + type, indent + 1);
        } else if ("string" === typeof clientProps || "number" === typeof clientProps || "bigint" === typeof clientProps)
          content = null == type ? content + describeTextDiff("" + clientProps, null, indent + 1) : content + describeTextDiff("" + clientProps, void 0, indent + 1);
        return content;
      }
      __name(describeElementDiff, "describeElementDiff");
      function describeSiblingFiber(fiber, indent) {
        var type = describeFiberType(fiber);
        if (null === type) {
          type = "";
          for (fiber = fiber.child; fiber; )
            type += describeSiblingFiber(fiber, indent), fiber = fiber.sibling;
          return type;
        }
        return indentation(indent) + "<" + type + ">\n";
      }
      __name(describeSiblingFiber, "describeSiblingFiber");
      function describeNode(node, indent) {
        var skipToNode = findNotableNode(node, indent);
        if (skipToNode !== node && (1 !== node.children.length || node.children[0] !== skipToNode))
          return indentation(indent) + "...\n" + describeNode(skipToNode, indent + 1);
        skipToNode = "";
        var debugInfo = node.fiber._debugInfo;
        if (debugInfo)
          for (var i = 0; i < debugInfo.length; i++) {
            var serverComponentName = debugInfo[i].name;
            "string" === typeof serverComponentName && (skipToNode += indentation(indent) + "<" + serverComponentName + ">\n", indent++);
          }
        debugInfo = "";
        i = node.fiber.pendingProps;
        if (6 === node.fiber.tag)
          debugInfo = describeTextDiff(i, node.serverProps, indent), indent++;
        else if (serverComponentName = describeFiberType(node.fiber), null !== serverComponentName)
          if (void 0 === node.serverProps) {
            debugInfo = indent;
            var maxLength = 120 - 2 * debugInfo - serverComponentName.length - 2, content = "";
            for (propName in i)
              if (i.hasOwnProperty(propName) && "children" !== propName) {
                var propValue = describePropValue(i[propName], 15);
                maxLength -= propName.length + propValue.length + 2;
                if (0 > maxLength) {
                  content += " ...";
                  break;
                }
                content += " " + propName + "=" + propValue;
              }
            debugInfo = indentation(debugInfo) + "<" + serverComponentName + content + ">\n";
            indent++;
          } else
            null === node.serverProps ? (debugInfo = describeExpandedElement(
              serverComponentName,
              i,
              added(indent)
            ), indent++) : "string" === typeof node.serverProps ? console.error(
              "Should not have matched a non HostText fiber to a Text node. This is a bug in React."
            ) : (debugInfo = describeElementDiff(
              serverComponentName,
              i,
              node.serverProps,
              indent
            ), indent++);
        var propName = "";
        i = node.fiber.child;
        for (serverComponentName = 0; i && serverComponentName < node.children.length; )
          maxLength = node.children[serverComponentName], maxLength.fiber === i ? (propName += describeNode(maxLength, indent), serverComponentName++) : propName += describeSiblingFiber(i, indent), i = i.sibling;
        i && 0 < node.children.length && (propName += indentation(indent) + "...\n");
        i = node.serverTail;
        null === node.serverProps && indent--;
        for (node = 0; node < i.length; node++)
          serverComponentName = i[node], propName = "string" === typeof serverComponentName ? propName + (removed(indent) + describeTextNode(serverComponentName, 120 - 2 * indent) + "\n") : propName + describeExpandedElement(
            serverComponentName.type,
            serverComponentName.props,
            removed(indent)
          );
        return skipToNode + debugInfo + propName;
      }
      __name(describeNode, "describeNode");
      function describeDiff(rootNode) {
        try {
          return "\n\n" + describeNode(rootNode, 0);
        } catch (x) {
          return "";
        }
      }
      __name(describeDiff, "describeDiff");
      function getCurrentFiberStackInDev() {
        if (null === current) return "";
        var workInProgress2 = current;
        try {
          var info = "";
          6 === workInProgress2.tag && (workInProgress2 = workInProgress2.return);
          switch (workInProgress2.tag) {
            case 26:
            case 27:
            case 5:
              info += describeBuiltInComponentFrame(workInProgress2.type);
              break;
            case 13:
              info += describeBuiltInComponentFrame("Suspense");
              break;
            case 19:
              info += describeBuiltInComponentFrame("SuspenseList");
              break;
            case 31:
              info += describeBuiltInComponentFrame("Activity");
              break;
            case 30:
            case 0:
            case 15:
            case 1:
              workInProgress2._debugOwner || "" !== info || (info += describeFunctionComponentFrameWithoutLineNumber(
                workInProgress2.type
              ));
              break;
            case 11:
              workInProgress2._debugOwner || "" !== info || (info += describeFunctionComponentFrameWithoutLineNumber(
                workInProgress2.type.render
              ));
          }
          for (; workInProgress2; )
            if ("number" === typeof workInProgress2.tag) {
              var fiber = workInProgress2;
              workInProgress2 = fiber._debugOwner;
              var debugStack = fiber._debugStack;
              workInProgress2 && debugStack && ("string" !== typeof debugStack && (fiber._debugStack = debugStack = formatOwnerStack(debugStack)), "" !== debugStack && (info += "\n" + debugStack));
            } else if (null != workInProgress2.debugStack) {
              var ownerStack = workInProgress2.debugStack;
              (workInProgress2 = workInProgress2.owner) && ownerStack && (info += "\n" + formatOwnerStack(ownerStack));
            } else break;
          var JSCompiler_inline_result = info;
        } catch (x) {
          JSCompiler_inline_result = "\nError generating stack: " + x.message + "\n" + x.stack;
        }
        return JSCompiler_inline_result;
      }
      __name(getCurrentFiberStackInDev, "getCurrentFiberStackInDev");
      function runWithFiberInDEV(fiber, callback, arg0, arg1, arg2, arg3, arg4) {
        var previousFiber = current;
        setCurrentFiber(fiber);
        try {
          return null !== fiber && fiber._debugTask ? fiber._debugTask.run(
            callback.bind(null, arg0, arg1, arg2, arg3, arg4)
          ) : callback(arg0, arg1, arg2, arg3, arg4);
        } finally {
          setCurrentFiber(previousFiber);
        }
        throw Error(
          "runWithFiberInDEV should never be called in production. This is a bug in React."
        );
      }
      __name(runWithFiberInDEV, "runWithFiberInDEV");
      function setCurrentFiber(fiber) {
        ReactSharedInternals.getCurrentStack = null === fiber ? null : getCurrentFiberStackInDev;
        isRendering = false;
        current = fiber;
      }
      __name(setCurrentFiber, "setCurrentFiber");
      function buildHydrationDiffNode(fiber, distanceFromLeaf) {
        if (null === fiber.return) {
          if (null === hydrationDiffRootDEV)
            hydrationDiffRootDEV = {
              fiber,
              children: [],
              serverProps: void 0,
              serverTail: [],
              distanceFromLeaf
            };
          else {
            if (hydrationDiffRootDEV.fiber !== fiber)
              throw Error(
                "Saw multiple hydration diff roots in a pass. This is a bug in React."
              );
            hydrationDiffRootDEV.distanceFromLeaf > distanceFromLeaf && (hydrationDiffRootDEV.distanceFromLeaf = distanceFromLeaf);
          }
          return hydrationDiffRootDEV;
        }
        var siblings = buildHydrationDiffNode(
          fiber.return,
          distanceFromLeaf + 1
        ).children;
        if (0 < siblings.length && siblings[siblings.length - 1].fiber === fiber)
          return siblings = siblings[siblings.length - 1], siblings.distanceFromLeaf > distanceFromLeaf && (siblings.distanceFromLeaf = distanceFromLeaf), siblings;
        distanceFromLeaf = {
          fiber,
          children: [],
          serverProps: void 0,
          serverTail: [],
          distanceFromLeaf
        };
        siblings.push(distanceFromLeaf);
        return distanceFromLeaf;
      }
      __name(buildHydrationDiffNode, "buildHydrationDiffNode");
      function warnNonHydratedInstance(fiber, rejectedCandidate) {
        didSuspendOrErrorDEV || (fiber = buildHydrationDiffNode(fiber, 0), fiber.serverProps = null, null !== rejectedCandidate && (rejectedCandidate = describeHydratableInstanceForDevWarnings(rejectedCandidate), fiber.serverTail.push(rejectedCandidate)));
      }
      __name(warnNonHydratedInstance, "warnNonHydratedInstance");
      function throwOnHydrationMismatch(fiber) {
        var diff4 = "", diffRoot = hydrationDiffRootDEV;
        null !== diffRoot && (hydrationDiffRootDEV = null, diff4 = describeDiff(diffRoot));
        queueHydrationError(
          createCapturedValueAtFiber(
            Error(
              "Hydration failed because the server rendered HTML didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used:\n\n- A server/client branch `if (typeof window !== 'undefined')`.\n- Variable input such as `Date.now()` or `Math.random()` which changes each time it's called.\n- Date formatting in a user's locale which doesn't match the server.\n- External changing data without sending a snapshot of it along with the HTML.\n- Invalid HTML tag nesting.\n\nIt can also happen if the client has a browser extension installed which messes with the HTML before React loaded.\n\nhttps://react.dev/link/hydration-mismatch" + diff4
            ),
            fiber
          )
        );
        throw HydrationMismatchException;
      }
      __name(throwOnHydrationMismatch, "throwOnHydrationMismatch");
      function prepareToHydrateHostInstance(fiber, hostContext) {
        if (!supportsHydration)
          throw Error(
            "Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."
          );
        hydrateInstance(
          fiber.stateNode,
          fiber.type,
          fiber.memoizedProps,
          hostContext,
          fiber
        ) || throwOnHydrationMismatch(fiber);
      }
      __name(prepareToHydrateHostInstance, "prepareToHydrateHostInstance");
      function popToNextHostParent(fiber) {
        for (hydrationParentFiber = fiber.return; hydrationParentFiber; )
          switch (hydrationParentFiber.tag) {
            case 5:
            case 13:
              rootOrSingletonContext = false;
              return;
            case 27:
            case 3:
              rootOrSingletonContext = true;
              return;
            default:
              hydrationParentFiber = hydrationParentFiber.return;
          }
      }
      __name(popToNextHostParent, "popToNextHostParent");
      function popHydrationState(fiber) {
        if (!supportsHydration || fiber !== hydrationParentFiber) return false;
        if (!isHydrating)
          return popToNextHostParent(fiber), isHydrating = true, false;
        var tag2 = fiber.tag;
        supportsSingletons ? 3 !== tag2 && 27 !== tag2 && (5 !== tag2 || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps)) && nextHydratableInstance && (warnIfUnhydratedTailNodes(fiber), throwOnHydrationMismatch(fiber)) : 3 !== tag2 && (5 !== tag2 || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps)) && nextHydratableInstance && (warnIfUnhydratedTailNodes(fiber), throwOnHydrationMismatch(fiber));
        popToNextHostParent(fiber);
        if (13 === tag2) {
          if (!supportsHydration)
            throw Error(
              "Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."
            );
          fiber = fiber.memoizedState;
          fiber = null !== fiber ? fiber.dehydrated : null;
          if (!fiber)
            throw Error(
              "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue."
            );
          nextHydratableInstance = getNextHydratableInstanceAfterSuspenseInstance(fiber);
        } else
          nextHydratableInstance = supportsSingletons && 27 === tag2 ? getNextHydratableSiblingAfterSingleton(
            fiber.type,
            nextHydratableInstance
          ) : hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
        return true;
      }
      __name(popHydrationState, "popHydrationState");
      function warnIfUnhydratedTailNodes(fiber) {
        for (var nextInstance = nextHydratableInstance; nextInstance; ) {
          var diffNode = buildHydrationDiffNode(fiber, 0), description = describeHydratableInstanceForDevWarnings(nextInstance);
          diffNode.serverTail.push(description);
          nextInstance = "Suspense" === description.type ? getNextHydratableInstanceAfterSuspenseInstance(nextInstance) : getNextHydratableSibling(nextInstance);
        }
      }
      __name(warnIfUnhydratedTailNodes, "warnIfUnhydratedTailNodes");
      function resetHydrationState() {
        supportsHydration && (nextHydratableInstance = hydrationParentFiber = null, didSuspendOrErrorDEV = isHydrating = false);
      }
      __name(resetHydrationState, "resetHydrationState");
      function upgradeHydrationErrorsToRecoverable() {
        var queuedErrors = hydrationErrors;
        null !== queuedErrors && (null === workInProgressRootRecoverableErrors ? workInProgressRootRecoverableErrors = queuedErrors : workInProgressRootRecoverableErrors.push.apply(
          workInProgressRootRecoverableErrors,
          queuedErrors
        ), hydrationErrors = null);
        return queuedErrors;
      }
      __name(upgradeHydrationErrorsToRecoverable, "upgradeHydrationErrorsToRecoverable");
      function queueHydrationError(error) {
        null === hydrationErrors ? hydrationErrors = [error] : hydrationErrors.push(error);
      }
      __name(queueHydrationError, "queueHydrationError");
      function emitPendingHydrationWarnings() {
        var diffRoot = hydrationDiffRootDEV;
        if (null !== diffRoot) {
          hydrationDiffRootDEV = null;
          for (var diff4 = describeDiff(diffRoot); 0 < diffRoot.children.length; )
            diffRoot = diffRoot.children[0];
          runWithFiberInDEV(diffRoot.fiber, function() {
            console.error(
              "A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up. This can happen if a SSR-ed Client Component used:\n\n- A server/client branch `if (typeof window !== 'undefined')`.\n- Variable input such as `Date.now()` or `Math.random()` which changes each time it's called.\n- Date formatting in a user's locale which doesn't match the server.\n- External changing data without sending a snapshot of it along with the HTML.\n- Invalid HTML tag nesting.\n\nIt can also happen if the client has a browser extension installed which messes with the HTML before React loaded.\n\n%s%s",
              "https://react.dev/link/hydration-mismatch",
              diff4
            );
          });
        }
      }
      __name(emitPendingHydrationWarnings, "emitPendingHydrationWarnings");
      function is(x, y) {
        return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y;
      }
      __name(is, "is");
      function resetContextDependencies() {
        lastContextDependency = currentlyRenderingFiber$1 = null;
        isDisallowedContextReadInDEV = false;
      }
      __name(resetContextDependencies, "resetContextDependencies");
      function pushProvider(providerFiber, context2, nextValue) {
        isPrimaryRenderer ? (push2(valueCursor, context2._currentValue, providerFiber), context2._currentValue = nextValue, push2(rendererCursorDEV, context2._currentRenderer, providerFiber), void 0 !== context2._currentRenderer && null !== context2._currentRenderer && context2._currentRenderer !== rendererSigil && console.error(
          "Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."
        ), context2._currentRenderer = rendererSigil) : (push2(valueCursor, context2._currentValue2, providerFiber), context2._currentValue2 = nextValue, push2(renderer2CursorDEV, context2._currentRenderer2, providerFiber), void 0 !== context2._currentRenderer2 && null !== context2._currentRenderer2 && context2._currentRenderer2 !== rendererSigil && console.error(
          "Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."
        ), context2._currentRenderer2 = rendererSigil);
      }
      __name(pushProvider, "pushProvider");
      function popProvider(context2, providerFiber) {
        var currentValue = valueCursor.current;
        isPrimaryRenderer ? (context2._currentValue = currentValue, currentValue = rendererCursorDEV.current, pop(rendererCursorDEV, providerFiber), context2._currentRenderer = currentValue) : (context2._currentValue2 = currentValue, currentValue = renderer2CursorDEV.current, pop(renderer2CursorDEV, providerFiber), context2._currentRenderer2 = currentValue);
        pop(valueCursor, providerFiber);
      }
      __name(popProvider, "popProvider");
      function scheduleContextWorkOnParentPath(parent, renderLanes2, propagationRoot) {
        for (; null !== parent; ) {
          var alternate = parent.alternate;
          (parent.childLanes & renderLanes2) !== renderLanes2 ? (parent.childLanes |= renderLanes2, null !== alternate && (alternate.childLanes |= renderLanes2)) : null !== alternate && (alternate.childLanes & renderLanes2) !== renderLanes2 && (alternate.childLanes |= renderLanes2);
          if (parent === propagationRoot) break;
          parent = parent.return;
        }
        parent !== propagationRoot && console.error(
          "Expected to find the propagation root when scheduling context work. This error is likely caused by a bug in React. Please file an issue."
        );
      }
      __name(scheduleContextWorkOnParentPath, "scheduleContextWorkOnParentPath");
      function propagateContextChanges(workInProgress2, contexts, renderLanes2, forcePropagateEntireTree) {
        var fiber = workInProgress2.child;
        null !== fiber && (fiber.return = workInProgress2);
        for (; null !== fiber; ) {
          var list3 = fiber.dependencies;
          if (null !== list3) {
            var nextFiber = fiber.child;
            list3 = list3.firstContext;
            a: for (; null !== list3; ) {
              var dependency = list3;
              list3 = fiber;
              for (var i = 0; i < contexts.length; i++)
                if (dependency.context === contexts[i]) {
                  list3.lanes |= renderLanes2;
                  dependency = list3.alternate;
                  null !== dependency && (dependency.lanes |= renderLanes2);
                  scheduleContextWorkOnParentPath(
                    list3.return,
                    renderLanes2,
                    workInProgress2
                  );
                  forcePropagateEntireTree || (nextFiber = null);
                  break a;
                }
              list3 = dependency.next;
            }
          } else if (18 === fiber.tag) {
            nextFiber = fiber.return;
            if (null === nextFiber)
              throw Error(
                "We just came from a parent so we must have had a parent. This is a bug in React."
              );
            nextFiber.lanes |= renderLanes2;
            list3 = nextFiber.alternate;
            null !== list3 && (list3.lanes |= renderLanes2);
            scheduleContextWorkOnParentPath(
              nextFiber,
              renderLanes2,
              workInProgress2
            );
            nextFiber = null;
          } else nextFiber = fiber.child;
          if (null !== nextFiber) nextFiber.return = fiber;
          else
            for (nextFiber = fiber; null !== nextFiber; ) {
              if (nextFiber === workInProgress2) {
                nextFiber = null;
                break;
              }
              fiber = nextFiber.sibling;
              if (null !== fiber) {
                fiber.return = nextFiber.return;
                nextFiber = fiber;
                break;
              }
              nextFiber = nextFiber.return;
            }
          fiber = nextFiber;
        }
      }
      __name(propagateContextChanges, "propagateContextChanges");
      function propagateParentContextChanges(current2, workInProgress2, renderLanes2, forcePropagateEntireTree) {
        current2 = null;
        for (var parent = workInProgress2, isInsidePropagationBailout = false; null !== parent; ) {
          if (!isInsidePropagationBailout) {
            if (0 !== (parent.flags & 524288)) isInsidePropagationBailout = true;
            else if (0 !== (parent.flags & 262144)) break;
          }
          if (10 === parent.tag) {
            var currentParent = parent.alternate;
            if (null === currentParent)
              throw Error("Should have a current fiber. This is a bug in React.");
            currentParent = currentParent.memoizedProps;
            if (null !== currentParent) {
              var context2 = parent.type;
              objectIs(parent.pendingProps.value, currentParent.value) || (null !== current2 ? current2.push(context2) : current2 = [context2]);
            }
          } else if (parent === hostTransitionProviderCursor.current) {
            currentParent = parent.alternate;
            if (null === currentParent)
              throw Error("Should have a current fiber. This is a bug in React.");
            currentParent.memoizedState.memoizedState !== parent.memoizedState.memoizedState && (null !== current2 ? current2.push(HostTransitionContext) : current2 = [HostTransitionContext]);
          }
          parent = parent.return;
        }
        null !== current2 && propagateContextChanges(
          workInProgress2,
          current2,
          renderLanes2,
          forcePropagateEntireTree
        );
        workInProgress2.flags |= 262144;
      }
      __name(propagateParentContextChanges, "propagateParentContextChanges");
      function checkIfContextChanged(currentDependencies) {
        for (currentDependencies = currentDependencies.firstContext; null !== currentDependencies; ) {
          var context2 = currentDependencies.context;
          if (!objectIs(
            isPrimaryRenderer ? context2._currentValue : context2._currentValue2,
            currentDependencies.memoizedValue
          ))
            return true;
          currentDependencies = currentDependencies.next;
        }
        return false;
      }
      __name(checkIfContextChanged, "checkIfContextChanged");
      function prepareToReadContext(workInProgress2) {
        currentlyRenderingFiber$1 = workInProgress2;
        lastContextDependency = null;
        workInProgress2 = workInProgress2.dependencies;
        null !== workInProgress2 && (workInProgress2.firstContext = null);
      }
      __name(prepareToReadContext, "prepareToReadContext");
      function readContext(context2) {
        isDisallowedContextReadInDEV && console.error(
          "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."
        );
        return readContextForConsumer(currentlyRenderingFiber$1, context2);
      }
      __name(readContext, "readContext");
      function readContextDuringReconciliation(consumer, context2) {
        null === currentlyRenderingFiber$1 && prepareToReadContext(consumer);
        return readContextForConsumer(consumer, context2);
      }
      __name(readContextDuringReconciliation, "readContextDuringReconciliation");
      function readContextForConsumer(consumer, context2) {
        var value = isPrimaryRenderer ? context2._currentValue : context2._currentValue2;
        context2 = { context: context2, memoizedValue: value, next: null };
        if (null === lastContextDependency) {
          if (null === consumer)
            throw Error(
              "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."
            );
          lastContextDependency = context2;
          consumer.dependencies = {
            lanes: 0,
            firstContext: context2,
            _debugThenableState: null
          };
          consumer.flags |= 524288;
        } else lastContextDependency = lastContextDependency.next = context2;
        return value;
      }
      __name(readContextForConsumer, "readContextForConsumer");
      function createCache() {
        return {
          controller: new AbortControllerLocal(),
          data: /* @__PURE__ */ new Map(),
          refCount: 0
        };
      }
      __name(createCache, "createCache");
      function retainCache(cache5) {
        cache5.controller.signal.aborted && console.warn(
          "A cache instance was retained after it was already freed. This likely indicates a bug in React."
        );
        cache5.refCount++;
      }
      __name(retainCache, "retainCache");
      function releaseCache(cache5) {
        cache5.refCount--;
        0 > cache5.refCount && console.warn(
          "A cache instance was released after it was already freed. This likely indicates a bug in React."
        );
        0 === cache5.refCount && scheduleCallback$2(NormalPriority, function() {
          cache5.controller.abort();
        });
      }
      __name(releaseCache, "releaseCache");
      function pushNestedEffectDurations() {
        var prevEffectDuration = profilerEffectDuration;
        profilerEffectDuration = 0;
        return prevEffectDuration;
      }
      __name(pushNestedEffectDurations, "pushNestedEffectDurations");
      function popNestedEffectDurations(prevEffectDuration) {
        var elapsedTime = profilerEffectDuration;
        profilerEffectDuration = prevEffectDuration;
        return elapsedTime;
      }
      __name(popNestedEffectDurations, "popNestedEffectDurations");
      function bubbleNestedEffectDurations(prevEffectDuration) {
        var elapsedTime = profilerEffectDuration;
        profilerEffectDuration += prevEffectDuration;
        return elapsedTime;
      }
      __name(bubbleNestedEffectDurations, "bubbleNestedEffectDurations");
      function startProfilerTimer(fiber) {
        profilerStartTime = now();
        0 > fiber.actualStartTime && (fiber.actualStartTime = profilerStartTime);
      }
      __name(startProfilerTimer, "startProfilerTimer");
      function stopProfilerTimerIfRunningAndRecordDuration(fiber) {
        if (0 <= profilerStartTime) {
          var elapsedTime = now() - profilerStartTime;
          fiber.actualDuration += elapsedTime;
          fiber.selfBaseDuration = elapsedTime;
          profilerStartTime = -1;
        }
      }
      __name(stopProfilerTimerIfRunningAndRecordDuration, "stopProfilerTimerIfRunningAndRecordDuration");
      function stopProfilerTimerIfRunningAndRecordIncompleteDuration(fiber) {
        if (0 <= profilerStartTime) {
          var elapsedTime = now() - profilerStartTime;
          fiber.actualDuration += elapsedTime;
          profilerStartTime = -1;
        }
      }
      __name(stopProfilerTimerIfRunningAndRecordIncompleteDuration, "stopProfilerTimerIfRunningAndRecordIncompleteDuration");
      function recordEffectDuration() {
        if (0 <= profilerStartTime) {
          var elapsedTime = now() - profilerStartTime;
          profilerStartTime = -1;
          profilerEffectDuration += elapsedTime;
        }
      }
      __name(recordEffectDuration, "recordEffectDuration");
      function startEffectTimer() {
        profilerStartTime = now();
      }
      __name(startEffectTimer, "startEffectTimer");
      function transferActualDuration(fiber) {
        for (var child = fiber.child; child; )
          fiber.actualDuration += child.actualDuration, child = child.sibling;
      }
      __name(transferActualDuration, "transferActualDuration");
      function ensureRootIsScheduled(root) {
        root !== lastScheduledRoot && null === root.next && (null === lastScheduledRoot ? firstScheduledRoot = lastScheduledRoot = root : lastScheduledRoot = lastScheduledRoot.next = root);
        mightHavePendingSyncWork = true;
        null !== ReactSharedInternals.actQueue ? didScheduleMicrotask_act || (didScheduleMicrotask_act = true, scheduleImmediateRootScheduleTask()) : didScheduleMicrotask || (didScheduleMicrotask = true, scheduleImmediateRootScheduleTask());
      }
      __name(ensureRootIsScheduled, "ensureRootIsScheduled");
      function flushSyncWorkAcrossRoots_impl(syncTransitionLanes, onlyLegacy) {
        if (!isFlushingWork && mightHavePendingSyncWork) {
          isFlushingWork = true;
          do {
            var didPerformSomeWork = false;
            for (var root = firstScheduledRoot; null !== root; ) {
              if (!onlyLegacy)
                if (0 !== syncTransitionLanes) {
                  var pendingLanes = root.pendingLanes;
                  if (0 === pendingLanes) var nextLanes = 0;
                  else {
                    var suspendedLanes = root.suspendedLanes, pingedLanes = root.pingedLanes;
                    nextLanes = (1 << 31 - clz32(42 | syncTransitionLanes) + 1) - 1;
                    nextLanes &= pendingLanes & ~(suspendedLanes & ~pingedLanes);
                    nextLanes = nextLanes & 201326741 ? nextLanes & 201326741 | 1 : nextLanes ? nextLanes | 2 : 0;
                  }
                  0 !== nextLanes && (didPerformSomeWork = true, performSyncWorkOnRoot(root, nextLanes));
                } else
                  nextLanes = workInProgressRootRenderLanes, nextLanes = getNextLanes(
                    root,
                    root === workInProgressRoot ? nextLanes : 0,
                    null !== root.cancelPendingCommit || root.timeoutHandle !== noTimeout
                  ), 0 === (nextLanes & 3) || checkIfRootIsPrerendering(root, nextLanes) || (didPerformSomeWork = true, performSyncWorkOnRoot(root, nextLanes));
              root = root.next;
            }
          } while (didPerformSomeWork);
          isFlushingWork = false;
        }
      }
      __name(flushSyncWorkAcrossRoots_impl, "flushSyncWorkAcrossRoots_impl");
      function processRootScheduleInImmediateTask() {
        processRootScheduleInMicrotask();
      }
      __name(processRootScheduleInImmediateTask, "processRootScheduleInImmediateTask");
      function processRootScheduleInMicrotask() {
        mightHavePendingSyncWork = didScheduleMicrotask_act = didScheduleMicrotask = false;
        var syncTransitionLanes = 0;
        0 !== currentEventTransitionLane && (shouldAttemptEagerTransition() && (syncTransitionLanes = currentEventTransitionLane), currentEventTransitionLane = 0);
        for (var currentTime = now$1(), prev = null, root = firstScheduledRoot; null !== root; ) {
          var next = root.next, nextLanes = scheduleTaskForRootDuringMicrotask(root, currentTime);
          if (0 === nextLanes)
            root.next = null, null === prev ? firstScheduledRoot = next : prev.next = next, null === next && (lastScheduledRoot = prev);
          else if (prev = root, 0 !== syncTransitionLanes || 0 !== (nextLanes & 3))
            mightHavePendingSyncWork = true;
          root = next;
        }
        flushSyncWorkAcrossRoots_impl(syncTransitionLanes, false);
      }
      __name(processRootScheduleInMicrotask, "processRootScheduleInMicrotask");
      function scheduleTaskForRootDuringMicrotask(root, currentTime) {
        for (var suspendedLanes = root.suspendedLanes, pingedLanes = root.pingedLanes, expirationTimes = root.expirationTimes, lanes = root.pendingLanes & -62914561; 0 < lanes; ) {
          var index = 31 - clz32(lanes), lane = 1 << index, expirationTime = expirationTimes[index];
          if (-1 === expirationTime) {
            if (0 === (lane & suspendedLanes) || 0 !== (lane & pingedLanes))
              expirationTimes[index] = computeExpirationTime(lane, currentTime);
          } else expirationTime <= currentTime && (root.expiredLanes |= lane);
          lanes &= ~lane;
        }
        currentTime = workInProgressRoot;
        suspendedLanes = workInProgressRootRenderLanes;
        suspendedLanes = getNextLanes(
          root,
          root === currentTime ? suspendedLanes : 0,
          null !== root.cancelPendingCommit || root.timeoutHandle !== noTimeout
        );
        pingedLanes = root.callbackNode;
        if (0 === suspendedLanes || root === currentTime && (workInProgressSuspendedReason === SuspendedOnData || workInProgressSuspendedReason === SuspendedOnAction) || null !== root.cancelPendingCommit)
          return null !== pingedLanes && cancelCallback(pingedLanes), root.callbackNode = null, root.callbackPriority = 0;
        if (0 === (suspendedLanes & 3) || checkIfRootIsPrerendering(root, suspendedLanes)) {
          currentTime = suspendedLanes & -suspendedLanes;
          if (currentTime !== root.callbackPriority || null !== ReactSharedInternals.actQueue && pingedLanes !== fakeActCallbackNode$1)
            cancelCallback(pingedLanes);
          else return currentTime;
          switch (lanesToEventPriority(suspendedLanes)) {
            case 2:
            case 8:
              suspendedLanes = UserBlockingPriority;
              break;
            case 32:
              suspendedLanes = NormalPriority$1;
              break;
            case 268435456:
              suspendedLanes = IdlePriority;
              break;
            default:
              suspendedLanes = NormalPriority$1;
          }
          pingedLanes = performWorkOnRootViaSchedulerTask.bind(null, root);
          null !== ReactSharedInternals.actQueue ? (ReactSharedInternals.actQueue.push(pingedLanes), suspendedLanes = fakeActCallbackNode$1) : suspendedLanes = scheduleCallback$3(suspendedLanes, pingedLanes);
          root.callbackPriority = currentTime;
          root.callbackNode = suspendedLanes;
          return currentTime;
        }
        null !== pingedLanes && cancelCallback(pingedLanes);
        root.callbackPriority = 2;
        root.callbackNode = null;
        return 2;
      }
      __name(scheduleTaskForRootDuringMicrotask, "scheduleTaskForRootDuringMicrotask");
      function performWorkOnRootViaSchedulerTask(root, didTimeout) {
        nestedUpdateScheduled = currentUpdateIsNested = false;
        if (pendingEffectsStatus !== NO_PENDING_EFFECTS && pendingEffectsStatus !== PENDING_PASSIVE_PHASE)
          return root.callbackNode = null, root.callbackPriority = 0, null;
        var originalCallbackNode = root.callbackNode;
        if (flushPendingEffects(true) && root.callbackNode !== originalCallbackNode)
          return null;
        var workInProgressRootRenderLanes$jscomp$0 = workInProgressRootRenderLanes;
        workInProgressRootRenderLanes$jscomp$0 = getNextLanes(
          root,
          root === workInProgressRoot ? workInProgressRootRenderLanes$jscomp$0 : 0,
          null !== root.cancelPendingCommit || root.timeoutHandle !== noTimeout
        );
        if (0 === workInProgressRootRenderLanes$jscomp$0) return null;
        performWorkOnRoot(
          root,
          workInProgressRootRenderLanes$jscomp$0,
          didTimeout
        );
        scheduleTaskForRootDuringMicrotask(root, now$1());
        return null != root.callbackNode && root.callbackNode === originalCallbackNode ? performWorkOnRootViaSchedulerTask.bind(null, root) : null;
      }
      __name(performWorkOnRootViaSchedulerTask, "performWorkOnRootViaSchedulerTask");
      function performSyncWorkOnRoot(root, lanes) {
        if (flushPendingEffects()) return null;
        currentUpdateIsNested = nestedUpdateScheduled;
        nestedUpdateScheduled = false;
        performWorkOnRoot(root, lanes, true);
      }
      __name(performSyncWorkOnRoot, "performSyncWorkOnRoot");
      function cancelCallback(callbackNode) {
        callbackNode !== fakeActCallbackNode$1 && null !== callbackNode && cancelCallback$1(callbackNode);
      }
      __name(cancelCallback, "cancelCallback");
      function scheduleImmediateRootScheduleTask() {
        null !== ReactSharedInternals.actQueue && ReactSharedInternals.actQueue.push(function() {
          processRootScheduleInMicrotask();
          return null;
        });
        supportsMicrotasks ? scheduleMicrotask(function() {
          (executionContext & (RenderContext | CommitContext)) !== NoContext ? scheduleCallback$3(
            ImmediatePriority,
            processRootScheduleInImmediateTask
          ) : processRootScheduleInMicrotask();
        }) : scheduleCallback$3(
          ImmediatePriority,
          processRootScheduleInImmediateTask
        );
      }
      __name(scheduleImmediateRootScheduleTask, "scheduleImmediateRootScheduleTask");
      function requestTransitionLane() {
        0 === currentEventTransitionLane && (currentEventTransitionLane = claimNextTransitionLane());
        return currentEventTransitionLane;
      }
      __name(requestTransitionLane, "requestTransitionLane");
      function entangleAsyncAction(transition, thenable) {
        if (null === currentEntangledListeners) {
          var entangledListeners = currentEntangledListeners = [];
          currentEntangledPendingCount = 0;
          currentEntangledLane = requestTransitionLane();
          currentEntangledActionThenable = {
            status: "pending",
            value: void 0,
            then: /* @__PURE__ */ __name(function(resolve24) {
              entangledListeners.push(resolve24);
            }, "then")
          };
        }
        currentEntangledPendingCount++;
        thenable.then(pingEngtangledActionScope, pingEngtangledActionScope);
        return thenable;
      }
      __name(entangleAsyncAction, "entangleAsyncAction");
      function pingEngtangledActionScope() {
        if (0 === --currentEntangledPendingCount && null !== currentEntangledListeners) {
          null !== currentEntangledActionThenable && (currentEntangledActionThenable.status = "fulfilled");
          var listeners = currentEntangledListeners;
          currentEntangledListeners = null;
          currentEntangledLane = 0;
          currentEntangledActionThenable = null;
          for (var i = 0; i < listeners.length; i++) (0, listeners[i])();
        }
      }
      __name(pingEngtangledActionScope, "pingEngtangledActionScope");
      function chainThenableValue(thenable, result) {
        var listeners = [], thenableWithOverride = {
          status: "pending",
          value: null,
          reason: null,
          then: /* @__PURE__ */ __name(function(resolve24) {
            listeners.push(resolve24);
          }, "then")
        };
        thenable.then(
          function() {
            thenableWithOverride.status = "fulfilled";
            thenableWithOverride.value = result;
            for (var i = 0; i < listeners.length; i++) (0, listeners[i])(result);
          },
          function(error) {
            thenableWithOverride.status = "rejected";
            thenableWithOverride.reason = error;
            for (error = 0; error < listeners.length; error++)
              (0, listeners[error])(void 0);
          }
        );
        return thenableWithOverride;
      }
      __name(chainThenableValue, "chainThenableValue");
      function peekCacheFromPool() {
        var cacheResumedFromPreviousRender = resumedCache.current;
        return null !== cacheResumedFromPreviousRender ? cacheResumedFromPreviousRender : workInProgressRoot.pooledCache;
      }
      __name(peekCacheFromPool, "peekCacheFromPool");
      function pushTransition(offscreenWorkInProgress, prevCachePool) {
        null === prevCachePool ? push2(resumedCache, resumedCache.current, offscreenWorkInProgress) : push2(resumedCache, prevCachePool.pool, offscreenWorkInProgress);
      }
      __name(pushTransition, "pushTransition");
      function getSuspendedCache() {
        var cacheFromPool = peekCacheFromPool();
        return null === cacheFromPool ? null : {
          parent: isPrimaryRenderer ? CacheContext._currentValue : CacheContext._currentValue2,
          pool: cacheFromPool
        };
      }
      __name(getSuspendedCache, "getSuspendedCache");
      function shallowEqual(objA, objB) {
        if (objectIs(objA, objB)) return true;
        if ("object" !== typeof objA || null === objA || "object" !== typeof objB || null === objB)
          return false;
        var keysA = Object.keys(objA), keysB = Object.keys(objB);
        if (keysA.length !== keysB.length) return false;
        for (keysB = 0; keysB < keysA.length; keysB++) {
          var currentKey = keysA[keysB];
          if (!hasOwnProperty2.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey]))
            return false;
        }
        return true;
      }
      __name(shallowEqual, "shallowEqual");
      function createThenableState() {
        return { didWarnAboutUncachedPromise: false, thenables: [] };
      }
      __name(createThenableState, "createThenableState");
      function isThenableResolved(thenable) {
        thenable = thenable.status;
        return "fulfilled" === thenable || "rejected" === thenable;
      }
      __name(isThenableResolved, "isThenableResolved");
      function noop$1() {
      }
      __name(noop$1, "noop$1");
      function trackUsedThenable(thenableState2, thenable, index) {
        null !== ReactSharedInternals.actQueue && (ReactSharedInternals.didUsePromise = true);
        var trackedThenables = thenableState2.thenables;
        index = trackedThenables[index];
        void 0 === index ? trackedThenables.push(thenable) : index !== thenable && (thenableState2.didWarnAboutUncachedPromise || (thenableState2.didWarnAboutUncachedPromise = true, console.error(
          "A component was suspended by an uncached promise. Creating promises inside a Client Component or hook is not yet supported, except via a Suspense-compatible library or framework."
        )), thenable.then(noop$1, noop$1), thenable = index);
        switch (thenable.status) {
          case "fulfilled":
            return thenable.value;
          case "rejected":
            throw thenableState2 = thenable.reason, checkIfUseWrappedInAsyncCatch(thenableState2), thenableState2;
          default:
            if ("string" === typeof thenable.status)
              thenable.then(noop$1, noop$1);
            else {
              thenableState2 = workInProgressRoot;
              if (null !== thenableState2 && 100 < thenableState2.shellSuspendCounter)
                throw Error(
                  "An unknown Component is an async Client Component. Only Server Components can be async at the moment. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server."
                );
              thenableState2 = thenable;
              thenableState2.status = "pending";
              thenableState2.then(
                function(fulfilledValue) {
                  if ("pending" === thenable.status) {
                    var fulfilledThenable = thenable;
                    fulfilledThenable.status = "fulfilled";
                    fulfilledThenable.value = fulfilledValue;
                  }
                },
                function(error) {
                  if ("pending" === thenable.status) {
                    var rejectedThenable = thenable;
                    rejectedThenable.status = "rejected";
                    rejectedThenable.reason = error;
                  }
                }
              );
            }
            switch (thenable.status) {
              case "fulfilled":
                return thenable.value;
              case "rejected":
                throw thenableState2 = thenable.reason, checkIfUseWrappedInAsyncCatch(thenableState2), thenableState2;
            }
            suspendedThenable = thenable;
            needsToResetSuspendedThenableDEV = true;
            throw SuspenseException;
        }
      }
      __name(trackUsedThenable, "trackUsedThenable");
      function getSuspendedThenable() {
        if (null === suspendedThenable)
          throw Error(
            "Expected a suspended thenable. This is a bug in React. Please file an issue."
          );
        var thenable = suspendedThenable;
        suspendedThenable = null;
        needsToResetSuspendedThenableDEV = false;
        return thenable;
      }
      __name(getSuspendedThenable, "getSuspendedThenable");
      function checkIfUseWrappedInAsyncCatch(rejectedReason) {
        if (rejectedReason === SuspenseException || rejectedReason === SuspenseActionException)
          throw Error(
            "Hooks are not supported inside an async component. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server."
          );
      }
      __name(checkIfUseWrappedInAsyncCatch, "checkIfUseWrappedInAsyncCatch");
      function finishQueueingConcurrentUpdates() {
        for (var endIndex = concurrentQueuesIndex, i = concurrentlyUpdatedLanes = concurrentQueuesIndex = 0; i < endIndex; ) {
          var fiber = concurrentQueues[i];
          concurrentQueues[i++] = null;
          var queue = concurrentQueues[i];
          concurrentQueues[i++] = null;
          var update2 = concurrentQueues[i];
          concurrentQueues[i++] = null;
          var lane = concurrentQueues[i];
          concurrentQueues[i++] = null;
          if (null !== queue && null !== update2) {
            var pending = queue.pending;
            null === pending ? update2.next = update2 : (update2.next = pending.next, pending.next = update2);
            queue.pending = update2;
          }
          0 !== lane && markUpdateLaneFromFiberToRoot(fiber, update2, lane);
        }
      }
      __name(finishQueueingConcurrentUpdates, "finishQueueingConcurrentUpdates");
      function enqueueUpdate$1(fiber, queue, update2, lane) {
        concurrentQueues[concurrentQueuesIndex++] = fiber;
        concurrentQueues[concurrentQueuesIndex++] = queue;
        concurrentQueues[concurrentQueuesIndex++] = update2;
        concurrentQueues[concurrentQueuesIndex++] = lane;
        concurrentlyUpdatedLanes |= lane;
        fiber.lanes |= lane;
        fiber = fiber.alternate;
        null !== fiber && (fiber.lanes |= lane);
      }
      __name(enqueueUpdate$1, "enqueueUpdate$1");
      function enqueueConcurrentHookUpdate(fiber, queue, update2, lane) {
        enqueueUpdate$1(fiber, queue, update2, lane);
        return getRootForUpdatedFiber(fiber);
      }
      __name(enqueueConcurrentHookUpdate, "enqueueConcurrentHookUpdate");
      function enqueueConcurrentRenderForLane(fiber, lane) {
        enqueueUpdate$1(fiber, null, null, lane);
        return getRootForUpdatedFiber(fiber);
      }
      __name(enqueueConcurrentRenderForLane, "enqueueConcurrentRenderForLane");
      function markUpdateLaneFromFiberToRoot(sourceFiber, update2, lane) {
        sourceFiber.lanes |= lane;
        var alternate = sourceFiber.alternate;
        null !== alternate && (alternate.lanes |= lane);
        for (var isHidden2 = false, parent = sourceFiber.return; null !== parent; )
          parent.childLanes |= lane, alternate = parent.alternate, null !== alternate && (alternate.childLanes |= lane), 22 === parent.tag && (sourceFiber = parent.stateNode, null === sourceFiber || sourceFiber._visibility & 1 || (isHidden2 = true)), sourceFiber = parent, parent = parent.return;
        return 3 === sourceFiber.tag ? (parent = sourceFiber.stateNode, isHidden2 && null !== update2 && (isHidden2 = 31 - clz32(lane), sourceFiber = parent.hiddenUpdates, alternate = sourceFiber[isHidden2], null === alternate ? sourceFiber[isHidden2] = [update2] : alternate.push(update2), update2.lane = lane | 536870912), parent) : null;
      }
      __name(markUpdateLaneFromFiberToRoot, "markUpdateLaneFromFiberToRoot");
      function getRootForUpdatedFiber(sourceFiber) {
        if (nestedUpdateCount > NESTED_UPDATE_LIMIT)
          throw nestedPassiveUpdateCount = nestedUpdateCount = 0, rootWithPassiveNestedUpdates = rootWithNestedUpdates = null, Error(
            "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops."
          );
        nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT && (nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = null, console.error(
          "Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render."
        ));
        null === sourceFiber.alternate && 0 !== (sourceFiber.flags & 4098) && warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
        for (var node = sourceFiber, parent = node.return; null !== parent; )
          null === node.alternate && 0 !== (node.flags & 4098) && warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber), node = parent, parent = node.return;
        return 3 === node.tag ? node.stateNode : null;
      }
      __name(getRootForUpdatedFiber, "getRootForUpdatedFiber");
      function initializeUpdateQueue(fiber) {
        fiber.updateQueue = {
          baseState: fiber.memoizedState,
          firstBaseUpdate: null,
          lastBaseUpdate: null,
          shared: { pending: null, lanes: 0, hiddenCallbacks: null },
          callbacks: null
        };
      }
      __name(initializeUpdateQueue, "initializeUpdateQueue");
      function cloneUpdateQueue(current2, workInProgress2) {
        current2 = current2.updateQueue;
        workInProgress2.updateQueue === current2 && (workInProgress2.updateQueue = {
          baseState: current2.baseState,
          firstBaseUpdate: current2.firstBaseUpdate,
          lastBaseUpdate: current2.lastBaseUpdate,
          shared: current2.shared,
          callbacks: null
        });
      }
      __name(cloneUpdateQueue, "cloneUpdateQueue");
      function createUpdate(lane) {
        return {
          lane,
          tag: UpdateState,
          payload: null,
          callback: null,
          next: null
        };
      }
      __name(createUpdate, "createUpdate");
      function enqueueUpdate(fiber, update2, lane) {
        var updateQueue = fiber.updateQueue;
        if (null === updateQueue) return null;
        updateQueue = updateQueue.shared;
        if (currentlyProcessingQueue === updateQueue && !didWarnUpdateInsideUpdate) {
          var componentName2 = getComponentNameFromFiber(fiber);
          console.error(
            "An update (setState, replaceState, or forceUpdate) was scheduled from inside an update function. Update functions should be pure, with zero side-effects. Consider using componentDidUpdate or a callback.\n\nPlease update the following component: %s",
            componentName2
          );
          didWarnUpdateInsideUpdate = true;
        }
        if ((executionContext & RenderContext) !== NoContext)
          return componentName2 = updateQueue.pending, null === componentName2 ? update2.next = update2 : (update2.next = componentName2.next, componentName2.next = update2), updateQueue.pending = update2, update2 = getRootForUpdatedFiber(fiber), markUpdateLaneFromFiberToRoot(fiber, null, lane), update2;
        enqueueUpdate$1(fiber, updateQueue, update2, lane);
        return getRootForUpdatedFiber(fiber);
      }
      __name(enqueueUpdate, "enqueueUpdate");
      function entangleTransitions(root, fiber, lane) {
        fiber = fiber.updateQueue;
        if (null !== fiber && (fiber = fiber.shared, 0 !== (lane & 4194048))) {
          var queueLanes = fiber.lanes;
          queueLanes &= root.pendingLanes;
          lane |= queueLanes;
          fiber.lanes = lane;
          markRootEntangled(root, lane);
        }
      }
      __name(entangleTransitions, "entangleTransitions");
      function enqueueCapturedUpdate(workInProgress2, capturedUpdate) {
        var queue = workInProgress2.updateQueue, current2 = workInProgress2.alternate;
        if (null !== current2 && (current2 = current2.updateQueue, queue === current2)) {
          var newFirst = null, newLast = null;
          queue = queue.firstBaseUpdate;
          if (null !== queue) {
            do {
              var clone = {
                lane: queue.lane,
                tag: queue.tag,
                payload: queue.payload,
                callback: null,
                next: null
              };
              null === newLast ? newFirst = newLast = clone : newLast = newLast.next = clone;
              queue = queue.next;
            } while (null !== queue);
            null === newLast ? newFirst = newLast = capturedUpdate : newLast = newLast.next = capturedUpdate;
          } else newFirst = newLast = capturedUpdate;
          queue = {
            baseState: current2.baseState,
            firstBaseUpdate: newFirst,
            lastBaseUpdate: newLast,
            shared: current2.shared,
            callbacks: current2.callbacks
          };
          workInProgress2.updateQueue = queue;
          return;
        }
        workInProgress2 = queue.lastBaseUpdate;
        null === workInProgress2 ? queue.firstBaseUpdate = capturedUpdate : workInProgress2.next = capturedUpdate;
        queue.lastBaseUpdate = capturedUpdate;
      }
      __name(enqueueCapturedUpdate, "enqueueCapturedUpdate");
      function suspendIfUpdateReadFromEntangledAsyncAction() {
        if (didReadFromEntangledAsyncAction) {
          var entangledActionThenable = currentEntangledActionThenable;
          if (null !== entangledActionThenable) throw entangledActionThenable;
        }
      }
      __name(suspendIfUpdateReadFromEntangledAsyncAction, "suspendIfUpdateReadFromEntangledAsyncAction");
      function processUpdateQueue(workInProgress2, props, instance$jscomp$0, renderLanes2) {
        didReadFromEntangledAsyncAction = false;
        var queue = workInProgress2.updateQueue;
        hasForceUpdate = false;
        currentlyProcessingQueue = queue.shared;
        var firstBaseUpdate = queue.firstBaseUpdate, lastBaseUpdate = queue.lastBaseUpdate, pendingQueue = queue.shared.pending;
        if (null !== pendingQueue) {
          queue.shared.pending = null;
          var lastPendingUpdate = pendingQueue, firstPendingUpdate = lastPendingUpdate.next;
          lastPendingUpdate.next = null;
          null === lastBaseUpdate ? firstBaseUpdate = firstPendingUpdate : lastBaseUpdate.next = firstPendingUpdate;
          lastBaseUpdate = lastPendingUpdate;
          var current2 = workInProgress2.alternate;
          null !== current2 && (current2 = current2.updateQueue, pendingQueue = current2.lastBaseUpdate, pendingQueue !== lastBaseUpdate && (null === pendingQueue ? current2.firstBaseUpdate = firstPendingUpdate : pendingQueue.next = firstPendingUpdate, current2.lastBaseUpdate = lastPendingUpdate));
        }
        if (null !== firstBaseUpdate) {
          var newState = queue.baseState;
          lastBaseUpdate = 0;
          current2 = firstPendingUpdate = lastPendingUpdate = null;
          pendingQueue = firstBaseUpdate;
          do {
            var updateLane = pendingQueue.lane & -536870913, isHiddenUpdate = updateLane !== pendingQueue.lane;
            if (isHiddenUpdate ? (workInProgressRootRenderLanes & updateLane) === updateLane : (renderLanes2 & updateLane) === updateLane) {
              0 !== updateLane && updateLane === currentEntangledLane && (didReadFromEntangledAsyncAction = true);
              null !== current2 && (current2 = current2.next = {
                lane: 0,
                tag: pendingQueue.tag,
                payload: pendingQueue.payload,
                callback: null,
                next: null
              });
              a: {
                updateLane = workInProgress2;
                var partialState = pendingQueue;
                var nextProps = props, instance = instance$jscomp$0;
                switch (partialState.tag) {
                  case ReplaceState:
                    partialState = partialState.payload;
                    if ("function" === typeof partialState) {
                      isDisallowedContextReadInDEV = true;
                      var nextState = partialState.call(
                        instance,
                        newState,
                        nextProps
                      );
                      if (updateLane.mode & 8) {
                        setIsStrictModeForDevtools(true);
                        try {
                          partialState.call(instance, newState, nextProps);
                        } finally {
                          setIsStrictModeForDevtools(false);
                        }
                      }
                      isDisallowedContextReadInDEV = false;
                      newState = nextState;
                      break a;
                    }
                    newState = partialState;
                    break a;
                  case CaptureUpdate:
                    updateLane.flags = updateLane.flags & -65537 | 128;
                  case UpdateState:
                    nextState = partialState.payload;
                    if ("function" === typeof nextState) {
                      isDisallowedContextReadInDEV = true;
                      partialState = nextState.call(
                        instance,
                        newState,
                        nextProps
                      );
                      if (updateLane.mode & 8) {
                        setIsStrictModeForDevtools(true);
                        try {
                          nextState.call(instance, newState, nextProps);
                        } finally {
                          setIsStrictModeForDevtools(false);
                        }
                      }
                      isDisallowedContextReadInDEV = false;
                    } else partialState = nextState;
                    if (null === partialState || void 0 === partialState) break a;
                    newState = assign({}, newState, partialState);
                    break a;
                  case ForceUpdate:
                    hasForceUpdate = true;
                }
              }
              updateLane = pendingQueue.callback;
              null !== updateLane && (workInProgress2.flags |= 64, isHiddenUpdate && (workInProgress2.flags |= 8192), isHiddenUpdate = queue.callbacks, null === isHiddenUpdate ? queue.callbacks = [updateLane] : isHiddenUpdate.push(updateLane));
            } else
              isHiddenUpdate = {
                lane: updateLane,
                tag: pendingQueue.tag,
                payload: pendingQueue.payload,
                callback: pendingQueue.callback,
                next: null
              }, null === current2 ? (firstPendingUpdate = current2 = isHiddenUpdate, lastPendingUpdate = newState) : current2 = current2.next = isHiddenUpdate, lastBaseUpdate |= updateLane;
            pendingQueue = pendingQueue.next;
            if (null === pendingQueue)
              if (pendingQueue = queue.shared.pending, null === pendingQueue)
                break;
              else
                isHiddenUpdate = pendingQueue, pendingQueue = isHiddenUpdate.next, isHiddenUpdate.next = null, queue.lastBaseUpdate = isHiddenUpdate, queue.shared.pending = null;
          } while (1);
          null === current2 && (lastPendingUpdate = newState);
          queue.baseState = lastPendingUpdate;
          queue.firstBaseUpdate = firstPendingUpdate;
          queue.lastBaseUpdate = current2;
          null === firstBaseUpdate && (queue.shared.lanes = 0);
          workInProgressRootSkippedLanes |= lastBaseUpdate;
          workInProgress2.lanes = lastBaseUpdate;
          workInProgress2.memoizedState = newState;
        }
        currentlyProcessingQueue = null;
      }
      __name(processUpdateQueue, "processUpdateQueue");
      function callCallback(callback, context2) {
        if ("function" !== typeof callback)
          throw Error(
            "Invalid argument passed as callback. Expected a function. Instead received: " + callback
          );
        callback.call(context2);
      }
      __name(callCallback, "callCallback");
      function commitHiddenCallbacks(updateQueue, context2) {
        var hiddenCallbacks = updateQueue.shared.hiddenCallbacks;
        if (null !== hiddenCallbacks)
          for (updateQueue.shared.hiddenCallbacks = null, updateQueue = 0; updateQueue < hiddenCallbacks.length; updateQueue++)
            callCallback(hiddenCallbacks[updateQueue], context2);
      }
      __name(commitHiddenCallbacks, "commitHiddenCallbacks");
      function commitCallbacks(updateQueue, context2) {
        var callbacks = updateQueue.callbacks;
        if (null !== callbacks)
          for (updateQueue.callbacks = null, updateQueue = 0; updateQueue < callbacks.length; updateQueue++)
            callCallback(callbacks[updateQueue], context2);
      }
      __name(commitCallbacks, "commitCallbacks");
      function pushHiddenContext(fiber, context2) {
        var prevEntangledRenderLanes = entangledRenderLanes;
        push2(prevEntangledRenderLanesCursor, prevEntangledRenderLanes, fiber);
        push2(currentTreeHiddenStackCursor, context2, fiber);
        entangledRenderLanes = prevEntangledRenderLanes | context2.baseLanes;
      }
      __name(pushHiddenContext, "pushHiddenContext");
      function reuseHiddenContextOnStack(fiber) {
        push2(prevEntangledRenderLanesCursor, entangledRenderLanes, fiber);
        push2(
          currentTreeHiddenStackCursor,
          currentTreeHiddenStackCursor.current,
          fiber
        );
      }
      __name(reuseHiddenContextOnStack, "reuseHiddenContextOnStack");
      function popHiddenContext(fiber) {
        entangledRenderLanes = prevEntangledRenderLanesCursor.current;
        pop(currentTreeHiddenStackCursor, fiber);
        pop(prevEntangledRenderLanesCursor, fiber);
      }
      __name(popHiddenContext, "popHiddenContext");
      function mountHookTypesDev() {
        var hookName = currentHookNameInDev;
        null === hookTypesDev ? hookTypesDev = [hookName] : hookTypesDev.push(hookName);
      }
      __name(mountHookTypesDev, "mountHookTypesDev");
      function updateHookTypesDev() {
        var hookName = currentHookNameInDev;
        if (null !== hookTypesDev && (hookTypesUpdateIndexDev++, hookTypesDev[hookTypesUpdateIndexDev] !== hookName)) {
          var componentName2 = getComponentNameFromFiber(currentlyRenderingFiber);
          if (!didWarnAboutMismatchedHooksForComponent.has(componentName2) && (didWarnAboutMismatchedHooksForComponent.add(componentName2), null !== hookTypesDev)) {
            for (var table = "", i = 0; i <= hookTypesUpdateIndexDev; i++) {
              var oldHookName = hookTypesDev[i], newHookName = i === hookTypesUpdateIndexDev ? hookName : oldHookName;
              for (oldHookName = i + 1 + ". " + oldHookName; 30 > oldHookName.length; )
                oldHookName += " ";
              oldHookName += newHookName + "\n";
              table += oldHookName;
            }
            console.error(
              "React has detected a change in the order of Hooks called by %s. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://react.dev/link/rules-of-hooks\n\n   Previous render            Next render\n   ------------------------------------------------------\n%s   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
              componentName2,
              table
            );
          }
        }
      }
      __name(updateHookTypesDev, "updateHookTypesDev");
      function checkDepsAreArrayDev(deps) {
        void 0 === deps || null === deps || isArrayImpl(deps) || console.error(
          "%s received a final argument that is not an array (instead, received `%s`). When specified, the final argument must be an array.",
          currentHookNameInDev,
          typeof deps
        );
      }
      __name(checkDepsAreArrayDev, "checkDepsAreArrayDev");
      function warnOnUseFormStateInDev() {
        var componentName2 = getComponentNameFromFiber(currentlyRenderingFiber);
        didWarnAboutUseFormState.has(componentName2) || (didWarnAboutUseFormState.add(componentName2), console.error(
          "ReactDOM.useFormState has been renamed to React.useActionState. Please update %s to use React.useActionState.",
          componentName2
        ));
      }
      __name(warnOnUseFormStateInDev, "warnOnUseFormStateInDev");
      function throwInvalidHookError() {
        throw Error(
          "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
        );
      }
      __name(throwInvalidHookError, "throwInvalidHookError");
      function areHookInputsEqual(nextDeps, prevDeps) {
        if (ignorePreviousDependencies) return false;
        if (null === prevDeps)
          return console.error(
            "%s received a final argument during this render, but not during the previous render. Even though the final argument is optional, its type cannot change between renders.",
            currentHookNameInDev
          ), false;
        nextDeps.length !== prevDeps.length && console.error(
          "The final argument passed to %s changed size between renders. The order and size of this array must remain constant.\n\nPrevious: %s\nIncoming: %s",
          currentHookNameInDev,
          "[" + prevDeps.join(", ") + "]",
          "[" + nextDeps.join(", ") + "]"
        );
        for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++)
          if (!objectIs(nextDeps[i], prevDeps[i])) return false;
        return true;
      }
      __name(areHookInputsEqual, "areHookInputsEqual");
      function renderWithHooks(current2, workInProgress2, Component, props, secondArg, nextRenderLanes) {
        renderLanes = nextRenderLanes;
        currentlyRenderingFiber = workInProgress2;
        hookTypesDev = null !== current2 ? current2._debugHookTypes : null;
        hookTypesUpdateIndexDev = -1;
        ignorePreviousDependencies = null !== current2 && current2.type !== workInProgress2.type;
        if ("[object AsyncFunction]" === Object.prototype.toString.call(Component) || "[object AsyncGeneratorFunction]" === Object.prototype.toString.call(Component))
          nextRenderLanes = getComponentNameFromFiber(currentlyRenderingFiber), didWarnAboutAsyncClientComponent.has(nextRenderLanes) || (didWarnAboutAsyncClientComponent.add(nextRenderLanes), console.error(
            "%s is an async Client Component. Only Server Components can be async at the moment. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server.",
            null === nextRenderLanes ? "An unknown Component" : "<" + nextRenderLanes + ">"
          ));
        workInProgress2.memoizedState = null;
        workInProgress2.updateQueue = null;
        workInProgress2.lanes = 0;
        ReactSharedInternals.H = null !== current2 && null !== current2.memoizedState ? HooksDispatcherOnUpdateInDEV : null !== hookTypesDev ? HooksDispatcherOnMountWithHookTypesInDEV : HooksDispatcherOnMountInDEV;
        shouldDoubleInvokeUserFnsInHooksDEV = nextRenderLanes = (workInProgress2.mode & 8) !== NoMode;
        var children = callComponentInDEV(Component, props, secondArg);
        shouldDoubleInvokeUserFnsInHooksDEV = false;
        didScheduleRenderPhaseUpdateDuringThisPass && (children = renderWithHooksAgain(
          workInProgress2,
          Component,
          props,
          secondArg
        ));
        if (nextRenderLanes) {
          setIsStrictModeForDevtools(true);
          try {
            children = renderWithHooksAgain(
              workInProgress2,
              Component,
              props,
              secondArg
            );
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
        finishRenderingHooks(current2, workInProgress2);
        return children;
      }
      __name(renderWithHooks, "renderWithHooks");
      function finishRenderingHooks(current2, workInProgress2) {
        workInProgress2._debugHookTypes = hookTypesDev;
        null === workInProgress2.dependencies ? null !== thenableState$1 && (workInProgress2.dependencies = {
          lanes: 0,
          firstContext: null,
          _debugThenableState: thenableState$1
        }) : workInProgress2.dependencies._debugThenableState = thenableState$1;
        ReactSharedInternals.H = ContextOnlyDispatcher;
        var didRenderTooFewHooks = null !== currentHook && null !== currentHook.next;
        renderLanes = 0;
        hookTypesDev = currentHookNameInDev = workInProgressHook = currentHook = currentlyRenderingFiber = null;
        hookTypesUpdateIndexDev = -1;
        null !== current2 && (current2.flags & 65011712) !== (workInProgress2.flags & 65011712) && console.error(
          "Internal React error: Expected static flag was missing. Please notify the React team."
        );
        didScheduleRenderPhaseUpdate = false;
        thenableIndexCounter$1 = 0;
        thenableState$1 = null;
        if (didRenderTooFewHooks)
          throw Error(
            "Rendered fewer hooks than expected. This may be caused by an accidental early return statement."
          );
        null === current2 || didReceiveUpdate || (current2 = current2.dependencies, null !== current2 && checkIfContextChanged(current2) && (didReceiveUpdate = true));
        needsToResetSuspendedThenableDEV ? (needsToResetSuspendedThenableDEV = false, current2 = true) : current2 = false;
        current2 && (workInProgress2 = getComponentNameFromFiber(workInProgress2) || "Unknown", didWarnAboutUseWrappedInTryCatch.has(workInProgress2) || didWarnAboutAsyncClientComponent.has(workInProgress2) || (didWarnAboutUseWrappedInTryCatch.add(workInProgress2), console.error(
          "`use` was called from inside a try/catch block. This is not allowed and can lead to unexpected behavior. To handle errors triggered by `use`, wrap your component in a error boundary."
        )));
      }
      __name(finishRenderingHooks, "finishRenderingHooks");
      function renderWithHooksAgain(workInProgress2, Component, props, secondArg) {
        currentlyRenderingFiber = workInProgress2;
        var numberOfReRenders = 0;
        do {
          didScheduleRenderPhaseUpdateDuringThisPass && (thenableState$1 = null);
          thenableIndexCounter$1 = 0;
          didScheduleRenderPhaseUpdateDuringThisPass = false;
          if (numberOfReRenders >= RE_RENDER_LIMIT)
            throw Error(
              "Too many re-renders. React limits the number of renders to prevent an infinite loop."
            );
          numberOfReRenders += 1;
          ignorePreviousDependencies = false;
          workInProgressHook = currentHook = null;
          if (null != workInProgress2.updateQueue) {
            var children = workInProgress2.updateQueue;
            children.lastEffect = null;
            children.events = null;
            children.stores = null;
            null != children.memoCache && (children.memoCache.index = 0);
          }
          hookTypesUpdateIndexDev = -1;
          ReactSharedInternals.H = HooksDispatcherOnRerenderInDEV;
          children = callComponentInDEV(Component, props, secondArg);
        } while (didScheduleRenderPhaseUpdateDuringThisPass);
        return children;
      }
      __name(renderWithHooksAgain, "renderWithHooksAgain");
      function TransitionAwareHostComponent() {
        var dispatcher = ReactSharedInternals.H, maybeThenable = dispatcher.useState()[0];
        maybeThenable = "function" === typeof maybeThenable.then ? useThenable(maybeThenable) : maybeThenable;
        dispatcher = dispatcher.useState()[0];
        (null !== currentHook ? currentHook.memoizedState : null) !== dispatcher && (currentlyRenderingFiber.flags |= 1024);
        return maybeThenable;
      }
      __name(TransitionAwareHostComponent, "TransitionAwareHostComponent");
      function checkDidRenderIdHook() {
        var didRenderIdHook = 0 !== localIdCounter;
        localIdCounter = 0;
        return didRenderIdHook;
      }
      __name(checkDidRenderIdHook, "checkDidRenderIdHook");
      function bailoutHooks(current2, workInProgress2, lanes) {
        workInProgress2.updateQueue = current2.updateQueue;
        workInProgress2.flags = (workInProgress2.mode & 16) !== NoMode ? workInProgress2.flags & -402655237 : workInProgress2.flags & -2053;
        current2.lanes &= ~lanes;
      }
      __name(bailoutHooks, "bailoutHooks");
      function resetHooksOnUnwind(workInProgress2) {
        if (didScheduleRenderPhaseUpdate) {
          for (workInProgress2 = workInProgress2.memoizedState; null !== workInProgress2; ) {
            var queue = workInProgress2.queue;
            null !== queue && (queue.pending = null);
            workInProgress2 = workInProgress2.next;
          }
          didScheduleRenderPhaseUpdate = false;
        }
        renderLanes = 0;
        hookTypesDev = workInProgressHook = currentHook = currentlyRenderingFiber = null;
        hookTypesUpdateIndexDev = -1;
        currentHookNameInDev = null;
        didScheduleRenderPhaseUpdateDuringThisPass = false;
        thenableIndexCounter$1 = localIdCounter = 0;
        thenableState$1 = null;
      }
      __name(resetHooksOnUnwind, "resetHooksOnUnwind");
      function mountWorkInProgressHook() {
        var hook = {
          memoizedState: null,
          baseState: null,
          baseQueue: null,
          queue: null,
          next: null
        };
        null === workInProgressHook ? currentlyRenderingFiber.memoizedState = workInProgressHook = hook : workInProgressHook = workInProgressHook.next = hook;
        return workInProgressHook;
      }
      __name(mountWorkInProgressHook, "mountWorkInProgressHook");
      function updateWorkInProgressHook() {
        if (null === currentHook) {
          var nextCurrentHook = currentlyRenderingFiber.alternate;
          nextCurrentHook = null !== nextCurrentHook ? nextCurrentHook.memoizedState : null;
        } else nextCurrentHook = currentHook.next;
        var nextWorkInProgressHook = null === workInProgressHook ? currentlyRenderingFiber.memoizedState : workInProgressHook.next;
        if (null !== nextWorkInProgressHook)
          workInProgressHook = nextWorkInProgressHook, currentHook = nextCurrentHook;
        else {
          if (null === nextCurrentHook) {
            if (null === currentlyRenderingFiber.alternate)
              throw Error(
                "Update hook called on initial render. This is likely a bug in React. Please file an issue."
              );
            throw Error("Rendered more hooks than during the previous render.");
          }
          currentHook = nextCurrentHook;
          nextCurrentHook = {
            memoizedState: currentHook.memoizedState,
            baseState: currentHook.baseState,
            baseQueue: currentHook.baseQueue,
            queue: currentHook.queue,
            next: null
          };
          null === workInProgressHook ? currentlyRenderingFiber.memoizedState = workInProgressHook = nextCurrentHook : workInProgressHook = workInProgressHook.next = nextCurrentHook;
        }
        return workInProgressHook;
      }
      __name(updateWorkInProgressHook, "updateWorkInProgressHook");
      function createFunctionComponentUpdateQueue() {
        return { lastEffect: null, events: null, stores: null, memoCache: null };
      }
      __name(createFunctionComponentUpdateQueue, "createFunctionComponentUpdateQueue");
      function useThenable(thenable) {
        var index = thenableIndexCounter$1;
        thenableIndexCounter$1 += 1;
        null === thenableState$1 && (thenableState$1 = createThenableState());
        thenable = trackUsedThenable(thenableState$1, thenable, index);
        index = currentlyRenderingFiber;
        null === (null === workInProgressHook ? index.memoizedState : workInProgressHook.next) && (index = index.alternate, ReactSharedInternals.H = null !== index && null !== index.memoizedState ? HooksDispatcherOnUpdateInDEV : HooksDispatcherOnMountInDEV);
        return thenable;
      }
      __name(useThenable, "useThenable");
      function use2(usable) {
        if (null !== usable && "object" === typeof usable) {
          if ("function" === typeof usable.then) return useThenable(usable);
          if (usable.$$typeof === REACT_CONTEXT_TYPE) return readContext(usable);
        }
        throw Error("An unsupported type was passed to use(): " + String(usable));
      }
      __name(use2, "use");
      function useMemoCache(size) {
        var memoCache = null, updateQueue = currentlyRenderingFiber.updateQueue;
        null !== updateQueue && (memoCache = updateQueue.memoCache);
        if (null == memoCache) {
          var current2 = currentlyRenderingFiber.alternate;
          null !== current2 && (current2 = current2.updateQueue, null !== current2 && (current2 = current2.memoCache, null != current2 && (memoCache = {
            data: current2.data.map(function(array) {
              return array.slice();
            }),
            index: 0
          })));
        }
        null == memoCache && (memoCache = { data: [], index: 0 });
        null === updateQueue && (updateQueue = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = updateQueue);
        updateQueue.memoCache = memoCache;
        updateQueue = memoCache.data[memoCache.index];
        if (void 0 === updateQueue || ignorePreviousDependencies)
          for (updateQueue = memoCache.data[memoCache.index] = Array(size), current2 = 0; current2 < size; current2++)
            updateQueue[current2] = REACT_MEMO_CACHE_SENTINEL;
        else
          updateQueue.length !== size && console.error(
            "Expected a constant size argument for each invocation of useMemoCache. The previous cache was allocated with size %s but size %s was requested.",
            updateQueue.length,
            size
          );
        memoCache.index++;
        return updateQueue;
      }
      __name(useMemoCache, "useMemoCache");
      function basicStateReducer(state, action) {
        return "function" === typeof action ? action(state) : action;
      }
      __name(basicStateReducer, "basicStateReducer");
      function mountReducer(reducer, initialArg, init) {
        var hook = mountWorkInProgressHook();
        if (void 0 !== init) {
          var initialState2 = init(initialArg);
          if (shouldDoubleInvokeUserFnsInHooksDEV) {
            setIsStrictModeForDevtools(true);
            try {
              init(initialArg);
            } finally {
              setIsStrictModeForDevtools(false);
            }
          }
        } else initialState2 = initialArg;
        hook.memoizedState = hook.baseState = initialState2;
        reducer = {
          pending: null,
          lanes: 0,
          dispatch: null,
          lastRenderedReducer: reducer,
          lastRenderedState: initialState2
        };
        hook.queue = reducer;
        reducer = reducer.dispatch = dispatchReducerAction.bind(
          null,
          currentlyRenderingFiber,
          reducer
        );
        return [hook.memoizedState, reducer];
      }
      __name(mountReducer, "mountReducer");
      function updateReducer(reducer) {
        var hook = updateWorkInProgressHook();
        return updateReducerImpl(hook, currentHook, reducer);
      }
      __name(updateReducer, "updateReducer");
      function updateReducerImpl(hook, current2, reducer) {
        var queue = hook.queue;
        if (null === queue)
          throw Error(
            "Should have a queue. You are likely calling Hooks conditionally, which is not allowed. (https://react.dev/link/invalid-hook-call)"
          );
        queue.lastRenderedReducer = reducer;
        var baseQueue = hook.baseQueue, pendingQueue = queue.pending;
        if (null !== pendingQueue) {
          if (null !== baseQueue) {
            var baseFirst = baseQueue.next;
            baseQueue.next = pendingQueue.next;
            pendingQueue.next = baseFirst;
          }
          current2.baseQueue !== baseQueue && console.error(
            "Internal error: Expected work-in-progress queue to be a clone. This is a bug in React."
          );
          current2.baseQueue = baseQueue = pendingQueue;
          queue.pending = null;
        }
        pendingQueue = hook.baseState;
        if (null === baseQueue) hook.memoizedState = pendingQueue;
        else {
          current2 = baseQueue.next;
          var newBaseQueueFirst = baseFirst = null, newBaseQueueLast = null, update2 = current2, didReadFromEntangledAsyncAction2 = false;
          do {
            var updateLane = update2.lane & -536870913;
            if (updateLane !== update2.lane ? (workInProgressRootRenderLanes & updateLane) === updateLane : (renderLanes & updateLane) === updateLane) {
              var revertLane = update2.revertLane;
              if (0 === revertLane)
                null !== newBaseQueueLast && (newBaseQueueLast = newBaseQueueLast.next = {
                  lane: 0,
                  revertLane: 0,
                  action: update2.action,
                  hasEagerState: update2.hasEagerState,
                  eagerState: update2.eagerState,
                  next: null
                }), updateLane === currentEntangledLane && (didReadFromEntangledAsyncAction2 = true);
              else if ((renderLanes & revertLane) === revertLane) {
                update2 = update2.next;
                revertLane === currentEntangledLane && (didReadFromEntangledAsyncAction2 = true);
                continue;
              } else
                updateLane = {
                  lane: 0,
                  revertLane: update2.revertLane,
                  action: update2.action,
                  hasEagerState: update2.hasEagerState,
                  eagerState: update2.eagerState,
                  next: null
                }, null === newBaseQueueLast ? (newBaseQueueFirst = newBaseQueueLast = updateLane, baseFirst = pendingQueue) : newBaseQueueLast = newBaseQueueLast.next = updateLane, currentlyRenderingFiber.lanes |= revertLane, workInProgressRootSkippedLanes |= revertLane;
              updateLane = update2.action;
              shouldDoubleInvokeUserFnsInHooksDEV && reducer(pendingQueue, updateLane);
              pendingQueue = update2.hasEagerState ? update2.eagerState : reducer(pendingQueue, updateLane);
            } else
              revertLane = {
                lane: updateLane,
                revertLane: update2.revertLane,
                action: update2.action,
                hasEagerState: update2.hasEagerState,
                eagerState: update2.eagerState,
                next: null
              }, null === newBaseQueueLast ? (newBaseQueueFirst = newBaseQueueLast = revertLane, baseFirst = pendingQueue) : newBaseQueueLast = newBaseQueueLast.next = revertLane, currentlyRenderingFiber.lanes |= updateLane, workInProgressRootSkippedLanes |= updateLane;
            update2 = update2.next;
          } while (null !== update2 && update2 !== current2);
          null === newBaseQueueLast ? baseFirst = pendingQueue : newBaseQueueLast.next = newBaseQueueFirst;
          if (!objectIs(pendingQueue, hook.memoizedState) && (didReceiveUpdate = true, didReadFromEntangledAsyncAction2 && (reducer = currentEntangledActionThenable, null !== reducer)))
            throw reducer;
          hook.memoizedState = pendingQueue;
          hook.baseState = baseFirst;
          hook.baseQueue = newBaseQueueLast;
          queue.lastRenderedState = pendingQueue;
        }
        null === baseQueue && (queue.lanes = 0);
        return [hook.memoizedState, queue.dispatch];
      }
      __name(updateReducerImpl, "updateReducerImpl");
      function rerenderReducer(reducer) {
        var hook = updateWorkInProgressHook(), queue = hook.queue;
        if (null === queue)
          throw Error(
            "Should have a queue. You are likely calling Hooks conditionally, which is not allowed. (https://react.dev/link/invalid-hook-call)"
          );
        queue.lastRenderedReducer = reducer;
        var dispatch = queue.dispatch, lastRenderPhaseUpdate = queue.pending, newState = hook.memoizedState;
        if (null !== lastRenderPhaseUpdate) {
          queue.pending = null;
          var update2 = lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
          do
            newState = reducer(newState, update2.action), update2 = update2.next;
          while (update2 !== lastRenderPhaseUpdate);
          objectIs(newState, hook.memoizedState) || (didReceiveUpdate = true);
          hook.memoizedState = newState;
          null === hook.baseQueue && (hook.baseState = newState);
          queue.lastRenderedState = newState;
        }
        return [newState, dispatch];
      }
      __name(rerenderReducer, "rerenderReducer");
      function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
        var fiber = currentlyRenderingFiber, hook = mountWorkInProgressHook();
        if (isHydrating) {
          if (void 0 === getServerSnapshot)
            throw Error(
              "Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering."
            );
          var nextSnapshot = getServerSnapshot();
          didWarnUncachedGetSnapshot || nextSnapshot === getServerSnapshot() || (console.error(
            "The result of getServerSnapshot should be cached to avoid an infinite loop"
          ), didWarnUncachedGetSnapshot = true);
        } else {
          nextSnapshot = getSnapshot();
          didWarnUncachedGetSnapshot || (getServerSnapshot = getSnapshot(), objectIs(nextSnapshot, getServerSnapshot) || (console.error(
            "The result of getSnapshot should be cached to avoid an infinite loop"
          ), didWarnUncachedGetSnapshot = true));
          if (null === workInProgressRoot)
            throw Error(
              "Expected a work-in-progress root. This is a bug in React. Please file an issue."
            );
          0 !== (workInProgressRootRenderLanes & 124) || pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
        }
        hook.memoizedState = nextSnapshot;
        getServerSnapshot = { value: nextSnapshot, getSnapshot };
        hook.queue = getServerSnapshot;
        mountEffect(
          subscribeToStore.bind(null, fiber, getServerSnapshot, subscribe),
          [subscribe]
        );
        fiber.flags |= 2048;
        pushSimpleEffect(
          HasEffect | Passive,
          createEffectInstance(),
          updateStoreInstance.bind(
            null,
            fiber,
            getServerSnapshot,
            nextSnapshot,
            getSnapshot
          ),
          null
        );
        return nextSnapshot;
      }
      __name(mountSyncExternalStore, "mountSyncExternalStore");
      function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
        var fiber = currentlyRenderingFiber, hook = updateWorkInProgressHook(), isHydrating$jscomp$0 = isHydrating;
        if (isHydrating$jscomp$0) {
          if (void 0 === getServerSnapshot)
            throw Error(
              "Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering."
            );
          getServerSnapshot = getServerSnapshot();
        } else if (getServerSnapshot = getSnapshot(), !didWarnUncachedGetSnapshot) {
          var cachedSnapshot = getSnapshot();
          objectIs(getServerSnapshot, cachedSnapshot) || (console.error(
            "The result of getSnapshot should be cached to avoid an infinite loop"
          ), didWarnUncachedGetSnapshot = true);
        }
        if (cachedSnapshot = !objectIs(
          (currentHook || hook).memoizedState,
          getServerSnapshot
        ))
          hook.memoizedState = getServerSnapshot, didReceiveUpdate = true;
        hook = hook.queue;
        var create3 = subscribeToStore.bind(null, fiber, hook, subscribe);
        updateEffectImpl(2048, Passive, create3, [subscribe]);
        if (hook.getSnapshot !== getSnapshot || cachedSnapshot || null !== workInProgressHook && workInProgressHook.memoizedState.tag & HasEffect) {
          fiber.flags |= 2048;
          pushSimpleEffect(
            HasEffect | Passive,
            createEffectInstance(),
            updateStoreInstance.bind(
              null,
              fiber,
              hook,
              getServerSnapshot,
              getSnapshot
            ),
            null
          );
          if (null === workInProgressRoot)
            throw Error(
              "Expected a work-in-progress root. This is a bug in React. Please file an issue."
            );
          isHydrating$jscomp$0 || 0 !== (renderLanes & 124) || pushStoreConsistencyCheck(fiber, getSnapshot, getServerSnapshot);
        }
        return getServerSnapshot;
      }
      __name(updateSyncExternalStore, "updateSyncExternalStore");
      function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) {
        fiber.flags |= 16384;
        fiber = { getSnapshot, value: renderedSnapshot };
        getSnapshot = currentlyRenderingFiber.updateQueue;
        null === getSnapshot ? (getSnapshot = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = getSnapshot, getSnapshot.stores = [fiber]) : (renderedSnapshot = getSnapshot.stores, null === renderedSnapshot ? getSnapshot.stores = [fiber] : renderedSnapshot.push(fiber));
      }
      __name(pushStoreConsistencyCheck, "pushStoreConsistencyCheck");
      function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) {
        inst.value = nextSnapshot;
        inst.getSnapshot = getSnapshot;
        checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);
      }
      __name(updateStoreInstance, "updateStoreInstance");
      function subscribeToStore(fiber, inst, subscribe) {
        return subscribe(function() {
          checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);
        });
      }
      __name(subscribeToStore, "subscribeToStore");
      function checkIfSnapshotChanged(inst) {
        var latestGetSnapshot = inst.getSnapshot;
        inst = inst.value;
        try {
          var nextValue = latestGetSnapshot();
          return !objectIs(inst, nextValue);
        } catch (error) {
          return true;
        }
      }
      __name(checkIfSnapshotChanged, "checkIfSnapshotChanged");
      function forceStoreRerender(fiber) {
        var root = enqueueConcurrentRenderForLane(fiber, 2);
        null !== root && scheduleUpdateOnFiber(root, fiber, 2);
      }
      __name(forceStoreRerender, "forceStoreRerender");
      function mountStateImpl(initialState2) {
        var hook = mountWorkInProgressHook();
        if ("function" === typeof initialState2) {
          var initialStateInitializer = initialState2;
          initialState2 = initialStateInitializer();
          if (shouldDoubleInvokeUserFnsInHooksDEV) {
            setIsStrictModeForDevtools(true);
            try {
              initialStateInitializer();
            } finally {
              setIsStrictModeForDevtools(false);
            }
          }
        }
        hook.memoizedState = hook.baseState = initialState2;
        hook.queue = {
          pending: null,
          lanes: 0,
          dispatch: null,
          lastRenderedReducer: basicStateReducer,
          lastRenderedState: initialState2
        };
        return hook;
      }
      __name(mountStateImpl, "mountStateImpl");
      function mountState(initialState2) {
        initialState2 = mountStateImpl(initialState2);
        var queue = initialState2.queue, dispatch = dispatchSetState.bind(null, currentlyRenderingFiber, queue);
        queue.dispatch = dispatch;
        return [initialState2.memoizedState, dispatch];
      }
      __name(mountState, "mountState");
      function mountOptimistic(passthrough) {
        var hook = mountWorkInProgressHook();
        hook.memoizedState = hook.baseState = passthrough;
        var queue = {
          pending: null,
          lanes: 0,
          dispatch: null,
          lastRenderedReducer: null,
          lastRenderedState: null
        };
        hook.queue = queue;
        hook = dispatchOptimisticSetState.bind(
          null,
          currentlyRenderingFiber,
          true,
          queue
        );
        queue.dispatch = hook;
        return [passthrough, hook];
      }
      __name(mountOptimistic, "mountOptimistic");
      function updateOptimistic(passthrough, reducer) {
        var hook = updateWorkInProgressHook();
        return updateOptimisticImpl(hook, currentHook, passthrough, reducer);
      }
      __name(updateOptimistic, "updateOptimistic");
      function updateOptimisticImpl(hook, current2, passthrough, reducer) {
        hook.baseState = passthrough;
        return updateReducerImpl(
          hook,
          currentHook,
          "function" === typeof reducer ? reducer : basicStateReducer
        );
      }
      __name(updateOptimisticImpl, "updateOptimisticImpl");
      function rerenderOptimistic(passthrough, reducer) {
        var hook = updateWorkInProgressHook();
        if (null !== currentHook)
          return updateOptimisticImpl(hook, currentHook, passthrough, reducer);
        hook.baseState = passthrough;
        return [passthrough, hook.queue.dispatch];
      }
      __name(rerenderOptimistic, "rerenderOptimistic");
      function dispatchActionState(fiber, actionQueue, setPendingState, setState, payload) {
        if (isRenderPhaseUpdate(fiber))
          throw Error("Cannot update form state while rendering.");
        fiber = actionQueue.action;
        if (null !== fiber) {
          var actionNode = {
            payload,
            action: fiber,
            next: null,
            isTransition: true,
            status: "pending",
            value: null,
            reason: null,
            listeners: [],
            then: /* @__PURE__ */ __name(function(listener) {
              actionNode.listeners.push(listener);
            }, "then")
          };
          null !== ReactSharedInternals.T ? setPendingState(true) : actionNode.isTransition = false;
          setState(actionNode);
          setPendingState = actionQueue.pending;
          null === setPendingState ? (actionNode.next = actionQueue.pending = actionNode, runActionStateAction(actionQueue, actionNode)) : (actionNode.next = setPendingState.next, actionQueue.pending = setPendingState.next = actionNode);
        }
      }
      __name(dispatchActionState, "dispatchActionState");
      function runActionStateAction(actionQueue, node) {
        var action = node.action, payload = node.payload, prevState = actionQueue.state;
        if (node.isTransition) {
          var prevTransition = ReactSharedInternals.T, currentTransition = {};
          ReactSharedInternals.T = currentTransition;
          ReactSharedInternals.T._updatedFibers = /* @__PURE__ */ new Set();
          try {
            var returnValue = action(prevState, payload), onStartTransitionFinish = ReactSharedInternals.S;
            null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
            handleActionReturnValue(actionQueue, node, returnValue);
          } catch (error) {
            onActionError(actionQueue, node, error);
          } finally {
            ReactSharedInternals.T = prevTransition, null === prevTransition && currentTransition._updatedFibers && (actionQueue = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < actionQueue && console.warn(
              "Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."
            ));
          }
        } else
          try {
            currentTransition = action(prevState, payload), handleActionReturnValue(actionQueue, node, currentTransition);
          } catch (error$2) {
            onActionError(actionQueue, node, error$2);
          }
      }
      __name(runActionStateAction, "runActionStateAction");
      function handleActionReturnValue(actionQueue, node, returnValue) {
        null !== returnValue && "object" === typeof returnValue && "function" === typeof returnValue.then ? (returnValue.then(
          function(nextState) {
            onActionSuccess(actionQueue, node, nextState);
          },
          function(error) {
            return onActionError(actionQueue, node, error);
          }
        ), node.isTransition || console.error(
          "An async function with useActionState was called outside of a transition. This is likely not what you intended (for example, isPending will not update correctly). Either call the returned function inside startTransition, or pass it to an `action` or `formAction` prop."
        )) : onActionSuccess(actionQueue, node, returnValue);
      }
      __name(handleActionReturnValue, "handleActionReturnValue");
      function onActionSuccess(actionQueue, actionNode, nextState) {
        actionNode.status = "fulfilled";
        actionNode.value = nextState;
        notifyActionListeners(actionNode);
        actionQueue.state = nextState;
        actionNode = actionQueue.pending;
        null !== actionNode && (nextState = actionNode.next, nextState === actionNode ? actionQueue.pending = null : (nextState = nextState.next, actionNode.next = nextState, runActionStateAction(actionQueue, nextState)));
      }
      __name(onActionSuccess, "onActionSuccess");
      function onActionError(actionQueue, actionNode, error) {
        var last2 = actionQueue.pending;
        actionQueue.pending = null;
        if (null !== last2) {
          last2 = last2.next;
          do
            actionNode.status = "rejected", actionNode.reason = error, notifyActionListeners(actionNode), actionNode = actionNode.next;
          while (actionNode !== last2);
        }
        actionQueue.action = null;
      }
      __name(onActionError, "onActionError");
      function notifyActionListeners(actionNode) {
        actionNode = actionNode.listeners;
        for (var i = 0; i < actionNode.length; i++) (0, actionNode[i])();
      }
      __name(notifyActionListeners, "notifyActionListeners");
      function actionStateReducer(oldState, newState) {
        return newState;
      }
      __name(actionStateReducer, "actionStateReducer");
      function mountActionState(action, initialStateProp) {
        if (isHydrating) {
          var ssrFormState = workInProgressRoot.formState;
          if (null !== ssrFormState) {
            a: {
              var isMatching = currentlyRenderingFiber;
              if (isHydrating) {
                if (nextHydratableInstance) {
                  var markerInstance = canHydrateFormStateMarker(
                    nextHydratableInstance,
                    rootOrSingletonContext
                  );
                  if (markerInstance) {
                    nextHydratableInstance = getNextHydratableSibling(markerInstance);
                    isMatching = isFormStateMarkerMatching(markerInstance);
                    break a;
                  }
                }
                throwOnHydrationMismatch(isMatching);
              }
              isMatching = false;
            }
            isMatching && (initialStateProp = ssrFormState[0]);
          }
        }
        ssrFormState = mountWorkInProgressHook();
        ssrFormState.memoizedState = ssrFormState.baseState = initialStateProp;
        isMatching = {
          pending: null,
          lanes: 0,
          dispatch: null,
          lastRenderedReducer: actionStateReducer,
          lastRenderedState: initialStateProp
        };
        ssrFormState.queue = isMatching;
        ssrFormState = dispatchSetState.bind(
          null,
          currentlyRenderingFiber,
          isMatching
        );
        isMatching.dispatch = ssrFormState;
        isMatching = mountStateImpl(false);
        var setPendingState = dispatchOptimisticSetState.bind(
          null,
          currentlyRenderingFiber,
          false,
          isMatching.queue
        );
        isMatching = mountWorkInProgressHook();
        markerInstance = {
          state: initialStateProp,
          dispatch: null,
          action,
          pending: null
        };
        isMatching.queue = markerInstance;
        ssrFormState = dispatchActionState.bind(
          null,
          currentlyRenderingFiber,
          markerInstance,
          setPendingState,
          ssrFormState
        );
        markerInstance.dispatch = ssrFormState;
        isMatching.memoizedState = action;
        return [initialStateProp, ssrFormState, false];
      }
      __name(mountActionState, "mountActionState");
      function updateActionState(action) {
        var stateHook = updateWorkInProgressHook();
        return updateActionStateImpl(stateHook, currentHook, action);
      }
      __name(updateActionState, "updateActionState");
      function updateActionStateImpl(stateHook, currentStateHook, action) {
        currentStateHook = updateReducerImpl(
          stateHook,
          currentStateHook,
          actionStateReducer
        )[0];
        stateHook = updateReducer(basicStateReducer)[0];
        if ("object" === typeof currentStateHook && null !== currentStateHook && "function" === typeof currentStateHook.then)
          try {
            var state = useThenable(currentStateHook);
          } catch (x) {
            if (x === SuspenseException) throw SuspenseActionException;
            throw x;
          }
        else state = currentStateHook;
        currentStateHook = updateWorkInProgressHook();
        var actionQueue = currentStateHook.queue, dispatch = actionQueue.dispatch;
        action !== currentStateHook.memoizedState && (currentlyRenderingFiber.flags |= 2048, pushSimpleEffect(
          HasEffect | Passive,
          createEffectInstance(),
          actionStateActionEffect.bind(null, actionQueue, action),
          null
        ));
        return [state, dispatch, stateHook];
      }
      __name(updateActionStateImpl, "updateActionStateImpl");
      function actionStateActionEffect(actionQueue, action) {
        actionQueue.action = action;
      }
      __name(actionStateActionEffect, "actionStateActionEffect");
      function rerenderActionState(action) {
        var stateHook = updateWorkInProgressHook(), currentStateHook = currentHook;
        if (null !== currentStateHook)
          return updateActionStateImpl(stateHook, currentStateHook, action);
        updateWorkInProgressHook();
        stateHook = stateHook.memoizedState;
        currentStateHook = updateWorkInProgressHook();
        var dispatch = currentStateHook.queue.dispatch;
        currentStateHook.memoizedState = action;
        return [stateHook, dispatch, false];
      }
      __name(rerenderActionState, "rerenderActionState");
      function pushSimpleEffect(tag2, inst, create3, createDeps) {
        tag2 = {
          tag: tag2,
          create: create3,
          deps: createDeps,
          inst,
          next: null
        };
        inst = currentlyRenderingFiber.updateQueue;
        null === inst && (inst = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = inst);
        create3 = inst.lastEffect;
        null === create3 ? inst.lastEffect = tag2.next = tag2 : (createDeps = create3.next, create3.next = tag2, tag2.next = createDeps, inst.lastEffect = tag2);
        return tag2;
      }
      __name(pushSimpleEffect, "pushSimpleEffect");
      function createEffectInstance() {
        return { destroy: void 0, resource: void 0 };
      }
      __name(createEffectInstance, "createEffectInstance");
      function mountRef(initialValue) {
        var hook = mountWorkInProgressHook();
        initialValue = { current: initialValue };
        return hook.memoizedState = initialValue;
      }
      __name(mountRef, "mountRef");
      function mountEffectImpl(fiberFlags, hookFlags, create3, createDeps) {
        var hook = mountWorkInProgressHook();
        createDeps = void 0 === createDeps ? null : createDeps;
        currentlyRenderingFiber.flags |= fiberFlags;
        hook.memoizedState = pushSimpleEffect(
          HasEffect | hookFlags,
          createEffectInstance(),
          create3,
          createDeps
        );
      }
      __name(mountEffectImpl, "mountEffectImpl");
      function updateEffectImpl(fiberFlags, hookFlags, create3, deps) {
        var hook = updateWorkInProgressHook();
        deps = void 0 === deps ? null : deps;
        var inst = hook.memoizedState.inst;
        null !== currentHook && null !== deps && areHookInputsEqual(deps, currentHook.memoizedState.deps) ? hook.memoizedState = pushSimpleEffect(hookFlags, inst, create3, deps) : (currentlyRenderingFiber.flags |= fiberFlags, hook.memoizedState = pushSimpleEffect(
          HasEffect | hookFlags,
          inst,
          create3,
          deps
        ));
      }
      __name(updateEffectImpl, "updateEffectImpl");
      function mountEffect(create3, createDeps) {
        (currentlyRenderingFiber.mode & 16) !== NoMode && (currentlyRenderingFiber.mode & 64) === NoMode ? mountEffectImpl(276826112, Passive, create3, createDeps) : mountEffectImpl(8390656, Passive, create3, createDeps);
      }
      __name(mountEffect, "mountEffect");
      function mountLayoutEffect(create3, deps) {
        var fiberFlags = 4194308;
        (currentlyRenderingFiber.mode & 16) !== NoMode && (fiberFlags |= 134217728);
        return mountEffectImpl(fiberFlags, Layout, create3, deps);
      }
      __name(mountLayoutEffect, "mountLayoutEffect");
      function imperativeHandleEffect(create3, ref) {
        if ("function" === typeof ref) {
          create3 = create3();
          var refCleanup = ref(create3);
          return function() {
            "function" === typeof refCleanup ? refCleanup() : ref(null);
          };
        }
        if (null !== ref && void 0 !== ref)
          return ref.hasOwnProperty("current") || console.error(
            "Expected useImperativeHandle() first argument to either be a ref callback or React.createRef() object. Instead received: %s.",
            "an object with keys {" + Object.keys(ref).join(", ") + "}"
          ), create3 = create3(), ref.current = create3, function() {
            ref.current = null;
          };
      }
      __name(imperativeHandleEffect, "imperativeHandleEffect");
      function mountImperativeHandle(ref, create3, deps) {
        "function" !== typeof create3 && console.error(
          "Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.",
          null !== create3 ? typeof create3 : "null"
        );
        deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null;
        var fiberFlags = 4194308;
        (currentlyRenderingFiber.mode & 16) !== NoMode && (fiberFlags |= 134217728);
        mountEffectImpl(
          fiberFlags,
          Layout,
          imperativeHandleEffect.bind(null, create3, ref),
          deps
        );
      }
      __name(mountImperativeHandle, "mountImperativeHandle");
      function updateImperativeHandle(ref, create3, deps) {
        "function" !== typeof create3 && console.error(
          "Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.",
          null !== create3 ? typeof create3 : "null"
        );
        deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null;
        updateEffectImpl(
          4,
          Layout,
          imperativeHandleEffect.bind(null, create3, ref),
          deps
        );
      }
      __name(updateImperativeHandle, "updateImperativeHandle");
      function mountCallback(callback, deps) {
        mountWorkInProgressHook().memoizedState = [
          callback,
          void 0 === deps ? null : deps
        ];
        return callback;
      }
      __name(mountCallback, "mountCallback");
      function updateCallback(callback, deps) {
        var hook = updateWorkInProgressHook();
        deps = void 0 === deps ? null : deps;
        var prevState = hook.memoizedState;
        if (null !== deps && areHookInputsEqual(deps, prevState[1]))
          return prevState[0];
        hook.memoizedState = [callback, deps];
        return callback;
      }
      __name(updateCallback, "updateCallback");
      function mountMemo(nextCreate, deps) {
        var hook = mountWorkInProgressHook();
        deps = void 0 === deps ? null : deps;
        var nextValue = nextCreate();
        if (shouldDoubleInvokeUserFnsInHooksDEV) {
          setIsStrictModeForDevtools(true);
          try {
            nextCreate();
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
        hook.memoizedState = [nextValue, deps];
        return nextValue;
      }
      __name(mountMemo, "mountMemo");
      function updateMemo(nextCreate, deps) {
        var hook = updateWorkInProgressHook();
        deps = void 0 === deps ? null : deps;
        var prevState = hook.memoizedState;
        if (null !== deps && areHookInputsEqual(deps, prevState[1]))
          return prevState[0];
        prevState = nextCreate();
        if (shouldDoubleInvokeUserFnsInHooksDEV) {
          setIsStrictModeForDevtools(true);
          try {
            nextCreate();
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
        hook.memoizedState = [prevState, deps];
        return prevState;
      }
      __name(updateMemo, "updateMemo");
      function mountDeferredValue(value, initialValue) {
        var hook = mountWorkInProgressHook();
        return mountDeferredValueImpl(hook, value, initialValue);
      }
      __name(mountDeferredValue, "mountDeferredValue");
      function updateDeferredValue(value, initialValue) {
        var hook = updateWorkInProgressHook();
        return updateDeferredValueImpl(
          hook,
          currentHook.memoizedState,
          value,
          initialValue
        );
      }
      __name(updateDeferredValue, "updateDeferredValue");
      function rerenderDeferredValue(value, initialValue) {
        var hook = updateWorkInProgressHook();
        return null === currentHook ? mountDeferredValueImpl(hook, value, initialValue) : updateDeferredValueImpl(
          hook,
          currentHook.memoizedState,
          value,
          initialValue
        );
      }
      __name(rerenderDeferredValue, "rerenderDeferredValue");
      function mountDeferredValueImpl(hook, value, initialValue) {
        if (void 0 === initialValue || 0 !== (renderLanes & 1073741824))
          return hook.memoizedState = value;
        hook.memoizedState = initialValue;
        hook = requestDeferredLane();
        currentlyRenderingFiber.lanes |= hook;
        workInProgressRootSkippedLanes |= hook;
        return initialValue;
      }
      __name(mountDeferredValueImpl, "mountDeferredValueImpl");
      function updateDeferredValueImpl(hook, prevValue, value, initialValue) {
        if (objectIs(value, prevValue)) return value;
        if (null !== currentTreeHiddenStackCursor.current)
          return hook = mountDeferredValueImpl(hook, value, initialValue), objectIs(hook, prevValue) || (didReceiveUpdate = true), hook;
        if (0 === (renderLanes & 42))
          return didReceiveUpdate = true, hook.memoizedState = value;
        hook = requestDeferredLane();
        currentlyRenderingFiber.lanes |= hook;
        workInProgressRootSkippedLanes |= hook;
        return prevValue;
      }
      __name(updateDeferredValueImpl, "updateDeferredValueImpl");
      function startTransition(fiber, queue, pendingState, finishedState, callback) {
        var previousPriority = getCurrentUpdatePriority();
        setCurrentUpdatePriority(
          0 !== previousPriority && 8 > previousPriority ? previousPriority : 8
        );
        var prevTransition = ReactSharedInternals.T, currentTransition = {};
        ReactSharedInternals.T = currentTransition;
        dispatchOptimisticSetState(fiber, false, queue, pendingState);
        currentTransition._updatedFibers = /* @__PURE__ */ new Set();
        try {
          var returnValue = callback(), onStartTransitionFinish = ReactSharedInternals.S;
          null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
          if (null !== returnValue && "object" === typeof returnValue && "function" === typeof returnValue.then) {
            var thenableForFinishedState = chainThenableValue(
              returnValue,
              finishedState
            );
            dispatchSetStateInternal(
              fiber,
              queue,
              thenableForFinishedState,
              requestUpdateLane(fiber)
            );
          } else
            dispatchSetStateInternal(
              fiber,
              queue,
              finishedState,
              requestUpdateLane(fiber)
            );
        } catch (error) {
          dispatchSetStateInternal(
            fiber,
            queue,
            { then: /* @__PURE__ */ __name(function() {
            }, "then"), status: "rejected", reason: error },
            requestUpdateLane(fiber)
          );
        } finally {
          setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = prevTransition, null === prevTransition && currentTransition._updatedFibers && (fiber = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < fiber && console.warn(
            "Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."
          ));
        }
      }
      __name(startTransition, "startTransition");
      function ensureFormComponentIsStateful(formFiber) {
        var existingStateHook = formFiber.memoizedState;
        if (null !== existingStateHook) return existingStateHook;
        existingStateHook = {
          memoizedState: NotPendingTransition,
          baseState: NotPendingTransition,
          baseQueue: null,
          queue: {
            pending: null,
            lanes: 0,
            dispatch: null,
            lastRenderedReducer: basicStateReducer,
            lastRenderedState: NotPendingTransition
          },
          next: null
        };
        var initialResetState = {};
        existingStateHook.next = {
          memoizedState: initialResetState,
          baseState: initialResetState,
          baseQueue: null,
          queue: {
            pending: null,
            lanes: 0,
            dispatch: null,
            lastRenderedReducer: basicStateReducer,
            lastRenderedState: initialResetState
          },
          next: null
        };
        formFiber.memoizedState = existingStateHook;
        formFiber = formFiber.alternate;
        null !== formFiber && (formFiber.memoizedState = existingStateHook);
        return existingStateHook;
      }
      __name(ensureFormComponentIsStateful, "ensureFormComponentIsStateful");
      function mountTransition() {
        var stateHook = mountStateImpl(false);
        stateHook = startTransition.bind(
          null,
          currentlyRenderingFiber,
          stateHook.queue,
          true,
          false
        );
        mountWorkInProgressHook().memoizedState = stateHook;
        return [false, stateHook];
      }
      __name(mountTransition, "mountTransition");
      function updateTransition() {
        var booleanOrThenable = updateReducer(basicStateReducer)[0], start = updateWorkInProgressHook().memoizedState;
        return [
          "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
          start
        ];
      }
      __name(updateTransition, "updateTransition");
      function rerenderTransition() {
        var booleanOrThenable = rerenderReducer(basicStateReducer)[0], start = updateWorkInProgressHook().memoizedState;
        return [
          "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
          start
        ];
      }
      __name(rerenderTransition, "rerenderTransition");
      function useHostTransitionStatus() {
        return readContext(HostTransitionContext);
      }
      __name(useHostTransitionStatus, "useHostTransitionStatus");
      function mountId() {
        var hook = mountWorkInProgressHook(), identifierPrefix = workInProgressRoot.identifierPrefix;
        if (isHydrating) {
          var treeId = treeContextOverflow;
          var idWithLeadingBit = treeContextId;
          treeId = (idWithLeadingBit & ~(1 << 32 - clz32(idWithLeadingBit) - 1)).toString(32) + treeId;
          identifierPrefix = "\xAB" + identifierPrefix + "R" + treeId;
          treeId = localIdCounter++;
          0 < treeId && (identifierPrefix += "H" + treeId.toString(32));
          identifierPrefix += "\xBB";
        } else
          treeId = globalClientIdCounter++, identifierPrefix = "\xAB" + identifierPrefix + "r" + treeId.toString(32) + "\xBB";
        return hook.memoizedState = identifierPrefix;
      }
      __name(mountId, "mountId");
      function mountRefresh() {
        return mountWorkInProgressHook().memoizedState = refreshCache.bind(
          null,
          currentlyRenderingFiber
        );
      }
      __name(mountRefresh, "mountRefresh");
      function refreshCache(fiber, seedKey) {
        for (var provider = fiber.return; null !== provider; ) {
          switch (provider.tag) {
            case 24:
            case 3:
              var lane = requestUpdateLane(provider);
              fiber = createUpdate(lane);
              var root = enqueueUpdate(provider, fiber, lane);
              null !== root && (scheduleUpdateOnFiber(root, provider, lane), entangleTransitions(root, provider, lane));
              provider = createCache();
              null !== seedKey && void 0 !== seedKey && null !== root && console.error(
                "The seed argument is not enabled outside experimental channels."
              );
              fiber.payload = { cache: provider };
              return;
          }
          provider = provider.return;
        }
      }
      __name(refreshCache, "refreshCache");
      function dispatchReducerAction(fiber, queue, action) {
        var args = arguments;
        "function" === typeof args[3] && console.error(
          "State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect()."
        );
        args = requestUpdateLane(fiber);
        var update2 = {
          lane: args,
          revertLane: 0,
          action,
          hasEagerState: false,
          eagerState: null,
          next: null
        };
        isRenderPhaseUpdate(fiber) ? enqueueRenderPhaseUpdate(queue, update2) : (update2 = enqueueConcurrentHookUpdate(fiber, queue, update2, args), null !== update2 && (scheduleUpdateOnFiber(update2, fiber, args), entangleTransitionUpdate(update2, queue, args)));
        markStateUpdateScheduled(fiber, args);
      }
      __name(dispatchReducerAction, "dispatchReducerAction");
      function dispatchSetState(fiber, queue, action) {
        var args = arguments;
        "function" === typeof args[3] && console.error(
          "State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect()."
        );
        args = requestUpdateLane(fiber);
        dispatchSetStateInternal(fiber, queue, action, args);
        markStateUpdateScheduled(fiber, args);
      }
      __name(dispatchSetState, "dispatchSetState");
      function dispatchSetStateInternal(fiber, queue, action, lane) {
        var update2 = {
          lane,
          revertLane: 0,
          action,
          hasEagerState: false,
          eagerState: null,
          next: null
        };
        if (isRenderPhaseUpdate(fiber)) enqueueRenderPhaseUpdate(queue, update2);
        else {
          var alternate = fiber.alternate;
          if (0 === fiber.lanes && (null === alternate || 0 === alternate.lanes) && (alternate = queue.lastRenderedReducer, null !== alternate)) {
            var prevDispatcher = ReactSharedInternals.H;
            ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
            try {
              var currentState = queue.lastRenderedState, eagerState = alternate(currentState, action);
              update2.hasEagerState = true;
              update2.eagerState = eagerState;
              if (objectIs(eagerState, currentState))
                return enqueueUpdate$1(fiber, queue, update2, 0), null === workInProgressRoot && finishQueueingConcurrentUpdates(), false;
            } catch (error) {
            } finally {
              ReactSharedInternals.H = prevDispatcher;
            }
          }
          action = enqueueConcurrentHookUpdate(fiber, queue, update2, lane);
          if (null !== action)
            return scheduleUpdateOnFiber(action, fiber, lane), entangleTransitionUpdate(action, queue, lane), true;
        }
        return false;
      }
      __name(dispatchSetStateInternal, "dispatchSetStateInternal");
      function dispatchOptimisticSetState(fiber, throwIfDuringRender, queue, action) {
        null === ReactSharedInternals.T && 0 === currentEntangledLane && console.error(
          "An optimistic state update occurred outside a transition or action. To fix, move the update to an action, or wrap with startTransition."
        );
        action = {
          lane: 2,
          revertLane: requestTransitionLane(),
          action,
          hasEagerState: false,
          eagerState: null,
          next: null
        };
        if (isRenderPhaseUpdate(fiber)) {
          if (throwIfDuringRender)
            throw Error("Cannot update optimistic state while rendering.");
          console.error("Cannot call startTransition while rendering.");
        } else
          throwIfDuringRender = enqueueConcurrentHookUpdate(
            fiber,
            queue,
            action,
            2
          ), null !== throwIfDuringRender && scheduleUpdateOnFiber(throwIfDuringRender, fiber, 2);
        markStateUpdateScheduled(fiber, 2);
      }
      __name(dispatchOptimisticSetState, "dispatchOptimisticSetState");
      function isRenderPhaseUpdate(fiber) {
        var alternate = fiber.alternate;
        return fiber === currentlyRenderingFiber || null !== alternate && alternate === currentlyRenderingFiber;
      }
      __name(isRenderPhaseUpdate, "isRenderPhaseUpdate");
      function enqueueRenderPhaseUpdate(queue, update2) {
        didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
        var pending = queue.pending;
        null === pending ? update2.next = update2 : (update2.next = pending.next, pending.next = update2);
        queue.pending = update2;
      }
      __name(enqueueRenderPhaseUpdate, "enqueueRenderPhaseUpdate");
      function entangleTransitionUpdate(root, queue, lane) {
        if (0 !== (lane & 4194048)) {
          var queueLanes = queue.lanes;
          queueLanes &= root.pendingLanes;
          lane |= queueLanes;
          queue.lanes = lane;
          markRootEntangled(root, lane);
        }
      }
      __name(entangleTransitionUpdate, "entangleTransitionUpdate");
      function pushDebugInfo(debugInfo) {
        var previousDebugInfo = currentDebugInfo;
        null != debugInfo && (currentDebugInfo = null === previousDebugInfo ? debugInfo : previousDebugInfo.concat(debugInfo));
        return previousDebugInfo;
      }
      __name(pushDebugInfo, "pushDebugInfo");
      function validateFragmentProps(element, fiber, returnFiber) {
        for (var keys = Object.keys(element.props), i = 0; i < keys.length; i++) {
          var key = keys[i];
          if ("children" !== key && "key" !== key) {
            null === fiber && (fiber = createFiberFromElement(element, returnFiber.mode, 0), fiber._debugInfo = currentDebugInfo, fiber.return = returnFiber);
            runWithFiberInDEV(
              fiber,
              function(erroredKey) {
                console.error(
                  "Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",
                  erroredKey
                );
              },
              key
            );
            break;
          }
        }
      }
      __name(validateFragmentProps, "validateFragmentProps");
      function unwrapThenable(thenable) {
        var index = thenableIndexCounter;
        thenableIndexCounter += 1;
        null === thenableState && (thenableState = createThenableState());
        return trackUsedThenable(thenableState, thenable, index);
      }
      __name(unwrapThenable, "unwrapThenable");
      function coerceRef(workInProgress2, element) {
        element = element.props.ref;
        workInProgress2.ref = void 0 !== element ? element : null;
      }
      __name(coerceRef, "coerceRef");
      function throwOnInvalidObjectType(returnFiber, newChild) {
        if (newChild.$$typeof === REACT_LEGACY_ELEMENT_TYPE)
          throw Error(
            'A React Element from an older version of React was rendered. This is not supported. It can happen if:\n- Multiple copies of the "react" package is used.\n- A library pre-bundled an old copy of "react" or "react/jsx-runtime".\n- A compiler tries to "inline" JSX instead of using the runtime.'
          );
        returnFiber = Object.prototype.toString.call(newChild);
        throw Error(
          "Objects are not valid as a React child (found: " + ("[object Object]" === returnFiber ? "object with keys {" + Object.keys(newChild).join(", ") + "}" : returnFiber) + "). If you meant to render a collection of children, use an array instead."
        );
      }
      __name(throwOnInvalidObjectType, "throwOnInvalidObjectType");
      function warnOnFunctionType(returnFiber, invalidChild) {
        var parentName = getComponentNameFromFiber(returnFiber) || "Component";
        ownerHasFunctionTypeWarning[parentName] || (ownerHasFunctionTypeWarning[parentName] = true, invalidChild = invalidChild.displayName || invalidChild.name || "Component", 3 === returnFiber.tag ? console.error(
          "Functions are not valid as a React child. This may happen if you return %s instead of <%s /> from render. Or maybe you meant to call this function rather than return it.\n  root.render(%s)",
          invalidChild,
          invalidChild,
          invalidChild
        ) : console.error(
          "Functions are not valid as a React child. This may happen if you return %s instead of <%s /> from render. Or maybe you meant to call this function rather than return it.\n  <%s>{%s}</%s>",
          invalidChild,
          invalidChild,
          parentName,
          invalidChild,
          parentName
        ));
      }
      __name(warnOnFunctionType, "warnOnFunctionType");
      function warnOnSymbolType(returnFiber, invalidChild) {
        var parentName = getComponentNameFromFiber(returnFiber) || "Component";
        ownerHasSymbolTypeWarning[parentName] || (ownerHasSymbolTypeWarning[parentName] = true, invalidChild = String(invalidChild), 3 === returnFiber.tag ? console.error(
          "Symbols are not valid as a React child.\n  root.render(%s)",
          invalidChild
        ) : console.error(
          "Symbols are not valid as a React child.\n  <%s>%s</%s>",
          parentName,
          invalidChild,
          parentName
        ));
      }
      __name(warnOnSymbolType, "warnOnSymbolType");
      function createChildReconciler(shouldTrackSideEffects) {
        function deleteChild(returnFiber, childToDelete) {
          if (shouldTrackSideEffects) {
            var deletions = returnFiber.deletions;
            null === deletions ? (returnFiber.deletions = [childToDelete], returnFiber.flags |= 16) : deletions.push(childToDelete);
          }
        }
        __name(deleteChild, "deleteChild");
        function deleteRemainingChildren(returnFiber, currentFirstChild) {
          if (!shouldTrackSideEffects) return null;
          for (; null !== currentFirstChild; )
            deleteChild(returnFiber, currentFirstChild), currentFirstChild = currentFirstChild.sibling;
          return null;
        }
        __name(deleteRemainingChildren, "deleteRemainingChildren");
        function mapRemainingChildren(currentFirstChild) {
          for (var existingChildren = /* @__PURE__ */ new Map(); null !== currentFirstChild; )
            null !== currentFirstChild.key ? existingChildren.set(currentFirstChild.key, currentFirstChild) : existingChildren.set(currentFirstChild.index, currentFirstChild), currentFirstChild = currentFirstChild.sibling;
          return existingChildren;
        }
        __name(mapRemainingChildren, "mapRemainingChildren");
        function useFiber(fiber, pendingProps) {
          fiber = createWorkInProgress(fiber, pendingProps);
          fiber.index = 0;
          fiber.sibling = null;
          return fiber;
        }
        __name(useFiber, "useFiber");
        function placeChild(newFiber, lastPlacedIndex, newIndex) {
          newFiber.index = newIndex;
          if (!shouldTrackSideEffects)
            return newFiber.flags |= 1048576, lastPlacedIndex;
          newIndex = newFiber.alternate;
          if (null !== newIndex)
            return newIndex = newIndex.index, newIndex < lastPlacedIndex ? (newFiber.flags |= 67108866, lastPlacedIndex) : newIndex;
          newFiber.flags |= 67108866;
          return lastPlacedIndex;
        }
        __name(placeChild, "placeChild");
        function placeSingleChild(newFiber) {
          shouldTrackSideEffects && null === newFiber.alternate && (newFiber.flags |= 67108866);
          return newFiber;
        }
        __name(placeSingleChild, "placeSingleChild");
        function updateTextNode(returnFiber, current2, textContent2, lanes) {
          if (null === current2 || 6 !== current2.tag)
            return current2 = createFiberFromText(
              textContent2,
              returnFiber.mode,
              lanes
            ), current2.return = returnFiber, current2._debugOwner = returnFiber, current2._debugTask = returnFiber._debugTask, current2._debugInfo = currentDebugInfo, current2;
          current2 = useFiber(current2, textContent2);
          current2.return = returnFiber;
          current2._debugInfo = currentDebugInfo;
          return current2;
        }
        __name(updateTextNode, "updateTextNode");
        function updateElement(returnFiber, current2, element, lanes) {
          var elementType = element.type;
          if (elementType === REACT_FRAGMENT_TYPE)
            return current2 = updateFragment(
              returnFiber,
              current2,
              element.props.children,
              lanes,
              element.key
            ), validateFragmentProps(element, current2, returnFiber), current2;
          if (null !== current2 && (current2.elementType === elementType || isCompatibleFamilyForHotReloading(current2, element) || "object" === typeof elementType && null !== elementType && elementType.$$typeof === REACT_LAZY_TYPE && callLazyInitInDEV(elementType) === current2.type))
            return current2 = useFiber(current2, element.props), coerceRef(current2, element), current2.return = returnFiber, current2._debugOwner = element._owner, current2._debugInfo = currentDebugInfo, current2;
          current2 = createFiberFromElement(element, returnFiber.mode, lanes);
          coerceRef(current2, element);
          current2.return = returnFiber;
          current2._debugInfo = currentDebugInfo;
          return current2;
        }
        __name(updateElement, "updateElement");
        function updatePortal(returnFiber, current2, portal, lanes) {
          if (null === current2 || 4 !== current2.tag || current2.stateNode.containerInfo !== portal.containerInfo || current2.stateNode.implementation !== portal.implementation)
            return current2 = createFiberFromPortal(portal, returnFiber.mode, lanes), current2.return = returnFiber, current2._debugInfo = currentDebugInfo, current2;
          current2 = useFiber(current2, portal.children || []);
          current2.return = returnFiber;
          current2._debugInfo = currentDebugInfo;
          return current2;
        }
        __name(updatePortal, "updatePortal");
        function updateFragment(returnFiber, current2, fragment, lanes, key) {
          if (null === current2 || 7 !== current2.tag)
            return current2 = createFiberFromFragment(
              fragment,
              returnFiber.mode,
              lanes,
              key
            ), current2.return = returnFiber, current2._debugOwner = returnFiber, current2._debugTask = returnFiber._debugTask, current2._debugInfo = currentDebugInfo, current2;
          current2 = useFiber(current2, fragment);
          current2.return = returnFiber;
          current2._debugInfo = currentDebugInfo;
          return current2;
        }
        __name(updateFragment, "updateFragment");
        function createChild(returnFiber, newChild, lanes) {
          if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
            return newChild = createFiberFromText(
              "" + newChild,
              returnFiber.mode,
              lanes
            ), newChild.return = returnFiber, newChild._debugOwner = returnFiber, newChild._debugTask = returnFiber._debugTask, newChild._debugInfo = currentDebugInfo, newChild;
          if ("object" === typeof newChild && null !== newChild) {
            switch (newChild.$$typeof) {
              case REACT_ELEMENT_TYPE:
                return lanes = createFiberFromElement(
                  newChild,
                  returnFiber.mode,
                  lanes
                ), coerceRef(lanes, newChild), lanes.return = returnFiber, returnFiber = pushDebugInfo(newChild._debugInfo), lanes._debugInfo = currentDebugInfo, currentDebugInfo = returnFiber, lanes;
              case REACT_PORTAL_TYPE:
                return newChild = createFiberFromPortal(
                  newChild,
                  returnFiber.mode,
                  lanes
                ), newChild.return = returnFiber, newChild._debugInfo = currentDebugInfo, newChild;
              case REACT_LAZY_TYPE:
                var _prevDebugInfo = pushDebugInfo(newChild._debugInfo);
                newChild = callLazyInitInDEV(newChild);
                returnFiber = createChild(returnFiber, newChild, lanes);
                currentDebugInfo = _prevDebugInfo;
                return returnFiber;
            }
            if (isArrayImpl(newChild) || getIteratorFn(newChild))
              return lanes = createFiberFromFragment(
                newChild,
                returnFiber.mode,
                lanes,
                null
              ), lanes.return = returnFiber, lanes._debugOwner = returnFiber, lanes._debugTask = returnFiber._debugTask, returnFiber = pushDebugInfo(newChild._debugInfo), lanes._debugInfo = currentDebugInfo, currentDebugInfo = returnFiber, lanes;
            if ("function" === typeof newChild.then)
              return _prevDebugInfo = pushDebugInfo(newChild._debugInfo), returnFiber = createChild(
                returnFiber,
                unwrapThenable(newChild),
                lanes
              ), currentDebugInfo = _prevDebugInfo, returnFiber;
            if (newChild.$$typeof === REACT_CONTEXT_TYPE)
              return createChild(
                returnFiber,
                readContextDuringReconciliation(returnFiber, newChild),
                lanes
              );
            throwOnInvalidObjectType(returnFiber, newChild);
          }
          "function" === typeof newChild && warnOnFunctionType(returnFiber, newChild);
          "symbol" === typeof newChild && warnOnSymbolType(returnFiber, newChild);
          return null;
        }
        __name(createChild, "createChild");
        function updateSlot(returnFiber, oldFiber, newChild, lanes) {
          var key = null !== oldFiber ? oldFiber.key : null;
          if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
            return null !== key ? null : updateTextNode(returnFiber, oldFiber, "" + newChild, lanes);
          if ("object" === typeof newChild && null !== newChild) {
            switch (newChild.$$typeof) {
              case REACT_ELEMENT_TYPE:
                return newChild.key === key ? (key = pushDebugInfo(newChild._debugInfo), returnFiber = updateElement(
                  returnFiber,
                  oldFiber,
                  newChild,
                  lanes
                ), currentDebugInfo = key, returnFiber) : null;
              case REACT_PORTAL_TYPE:
                return newChild.key === key ? updatePortal(returnFiber, oldFiber, newChild, lanes) : null;
              case REACT_LAZY_TYPE:
                return key = pushDebugInfo(newChild._debugInfo), newChild = callLazyInitInDEV(newChild), returnFiber = updateSlot(
                  returnFiber,
                  oldFiber,
                  newChild,
                  lanes
                ), currentDebugInfo = key, returnFiber;
            }
            if (isArrayImpl(newChild) || getIteratorFn(newChild)) {
              if (null !== key) return null;
              key = pushDebugInfo(newChild._debugInfo);
              returnFiber = updateFragment(
                returnFiber,
                oldFiber,
                newChild,
                lanes,
                null
              );
              currentDebugInfo = key;
              return returnFiber;
            }
            if ("function" === typeof newChild.then)
              return key = pushDebugInfo(newChild._debugInfo), returnFiber = updateSlot(
                returnFiber,
                oldFiber,
                unwrapThenable(newChild),
                lanes
              ), currentDebugInfo = key, returnFiber;
            if (newChild.$$typeof === REACT_CONTEXT_TYPE)
              return updateSlot(
                returnFiber,
                oldFiber,
                readContextDuringReconciliation(returnFiber, newChild),
                lanes
              );
            throwOnInvalidObjectType(returnFiber, newChild);
          }
          "function" === typeof newChild && warnOnFunctionType(returnFiber, newChild);
          "symbol" === typeof newChild && warnOnSymbolType(returnFiber, newChild);
          return null;
        }
        __name(updateSlot, "updateSlot");
        function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) {
          if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
            return existingChildren = existingChildren.get(newIdx) || null, updateTextNode(returnFiber, existingChildren, "" + newChild, lanes);
          if ("object" === typeof newChild && null !== newChild) {
            switch (newChild.$$typeof) {
              case REACT_ELEMENT_TYPE:
                return newIdx = existingChildren.get(
                  null === newChild.key ? newIdx : newChild.key
                ) || null, existingChildren = pushDebugInfo(newChild._debugInfo), returnFiber = updateElement(
                  returnFiber,
                  newIdx,
                  newChild,
                  lanes
                ), currentDebugInfo = existingChildren, returnFiber;
              case REACT_PORTAL_TYPE:
                return existingChildren = existingChildren.get(
                  null === newChild.key ? newIdx : newChild.key
                ) || null, updatePortal(returnFiber, existingChildren, newChild, lanes);
              case REACT_LAZY_TYPE:
                var _prevDebugInfo7 = pushDebugInfo(newChild._debugInfo);
                newChild = callLazyInitInDEV(newChild);
                returnFiber = updateFromMap(
                  existingChildren,
                  returnFiber,
                  newIdx,
                  newChild,
                  lanes
                );
                currentDebugInfo = _prevDebugInfo7;
                return returnFiber;
            }
            if (isArrayImpl(newChild) || getIteratorFn(newChild))
              return newIdx = existingChildren.get(newIdx) || null, existingChildren = pushDebugInfo(newChild._debugInfo), returnFiber = updateFragment(
                returnFiber,
                newIdx,
                newChild,
                lanes,
                null
              ), currentDebugInfo = existingChildren, returnFiber;
            if ("function" === typeof newChild.then)
              return _prevDebugInfo7 = pushDebugInfo(newChild._debugInfo), returnFiber = updateFromMap(
                existingChildren,
                returnFiber,
                newIdx,
                unwrapThenable(newChild),
                lanes
              ), currentDebugInfo = _prevDebugInfo7, returnFiber;
            if (newChild.$$typeof === REACT_CONTEXT_TYPE)
              return updateFromMap(
                existingChildren,
                returnFiber,
                newIdx,
                readContextDuringReconciliation(returnFiber, newChild),
                lanes
              );
            throwOnInvalidObjectType(returnFiber, newChild);
          }
          "function" === typeof newChild && warnOnFunctionType(returnFiber, newChild);
          "symbol" === typeof newChild && warnOnSymbolType(returnFiber, newChild);
          return null;
        }
        __name(updateFromMap, "updateFromMap");
        function warnOnInvalidKey(returnFiber, workInProgress2, child, knownKeys) {
          if ("object" !== typeof child || null === child) return knownKeys;
          switch (child.$$typeof) {
            case REACT_ELEMENT_TYPE:
            case REACT_PORTAL_TYPE:
              warnForMissingKey(returnFiber, workInProgress2, child);
              var key = child.key;
              if ("string" !== typeof key) break;
              if (null === knownKeys) {
                knownKeys = /* @__PURE__ */ new Set();
                knownKeys.add(key);
                break;
              }
              if (!knownKeys.has(key)) {
                knownKeys.add(key);
                break;
              }
              runWithFiberInDEV(workInProgress2, function() {
                console.error(
                  "Encountered two children with the same key, `%s`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted \u2014 the behavior is unsupported and could change in a future version.",
                  key
                );
              });
              break;
            case REACT_LAZY_TYPE:
              child = callLazyInitInDEV(child), warnOnInvalidKey(returnFiber, workInProgress2, child, knownKeys);
          }
          return knownKeys;
        }
        __name(warnOnInvalidKey, "warnOnInvalidKey");
        function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
          for (var knownKeys = null, resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, newIdx = currentFirstChild = 0, nextOldFiber = null; null !== oldFiber && newIdx < newChildren.length; newIdx++) {
            oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling;
            var newFiber = updateSlot(
              returnFiber,
              oldFiber,
              newChildren[newIdx],
              lanes
            );
            if (null === newFiber) {
              null === oldFiber && (oldFiber = nextOldFiber);
              break;
            }
            knownKeys = warnOnInvalidKey(
              returnFiber,
              newFiber,
              newChildren[newIdx],
              knownKeys
            );
            shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber);
            currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
            null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber;
            previousNewFiber = newFiber;
            oldFiber = nextOldFiber;
          }
          if (newIdx === newChildren.length)
            return deleteRemainingChildren(returnFiber, oldFiber), isHydrating && pushTreeFork(returnFiber, newIdx), resultingFirstChild;
          if (null === oldFiber) {
            for (; newIdx < newChildren.length; newIdx++)
              oldFiber = createChild(returnFiber, newChildren[newIdx], lanes), null !== oldFiber && (knownKeys = warnOnInvalidKey(
                returnFiber,
                oldFiber,
                newChildren[newIdx],
                knownKeys
              ), currentFirstChild = placeChild(
                oldFiber,
                currentFirstChild,
                newIdx
              ), null === previousNewFiber ? resultingFirstChild = oldFiber : previousNewFiber.sibling = oldFiber, previousNewFiber = oldFiber);
            isHydrating && pushTreeFork(returnFiber, newIdx);
            return resultingFirstChild;
          }
          for (oldFiber = mapRemainingChildren(oldFiber); newIdx < newChildren.length; newIdx++)
            nextOldFiber = updateFromMap(
              oldFiber,
              returnFiber,
              newIdx,
              newChildren[newIdx],
              lanes
            ), null !== nextOldFiber && (knownKeys = warnOnInvalidKey(
              returnFiber,
              nextOldFiber,
              newChildren[newIdx],
              knownKeys
            ), shouldTrackSideEffects && null !== nextOldFiber.alternate && oldFiber.delete(
              null === nextOldFiber.key ? newIdx : nextOldFiber.key
            ), currentFirstChild = placeChild(
              nextOldFiber,
              currentFirstChild,
              newIdx
            ), null === previousNewFiber ? resultingFirstChild = nextOldFiber : previousNewFiber.sibling = nextOldFiber, previousNewFiber = nextOldFiber);
          shouldTrackSideEffects && oldFiber.forEach(function(child) {
            return deleteChild(returnFiber, child);
          });
          isHydrating && pushTreeFork(returnFiber, newIdx);
          return resultingFirstChild;
        }
        __name(reconcileChildrenArray, "reconcileChildrenArray");
        function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildren, lanes) {
          if (null == newChildren)
            throw Error("An iterable object provided no iterator.");
          for (var resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, newIdx = currentFirstChild = 0, nextOldFiber = null, knownKeys = null, step = newChildren.next(); null !== oldFiber && !step.done; newIdx++, step = newChildren.next()) {
            oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling;
            var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);
            if (null === newFiber) {
              null === oldFiber && (oldFiber = nextOldFiber);
              break;
            }
            knownKeys = warnOnInvalidKey(
              returnFiber,
              newFiber,
              step.value,
              knownKeys
            );
            shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber);
            currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
            null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber;
            previousNewFiber = newFiber;
            oldFiber = nextOldFiber;
          }
          if (step.done)
            return deleteRemainingChildren(returnFiber, oldFiber), isHydrating && pushTreeFork(returnFiber, newIdx), resultingFirstChild;
          if (null === oldFiber) {
            for (; !step.done; newIdx++, step = newChildren.next())
              oldFiber = createChild(returnFiber, step.value, lanes), null !== oldFiber && (knownKeys = warnOnInvalidKey(
                returnFiber,
                oldFiber,
                step.value,
                knownKeys
              ), currentFirstChild = placeChild(
                oldFiber,
                currentFirstChild,
                newIdx
              ), null === previousNewFiber ? resultingFirstChild = oldFiber : previousNewFiber.sibling = oldFiber, previousNewFiber = oldFiber);
            isHydrating && pushTreeFork(returnFiber, newIdx);
            return resultingFirstChild;
          }
          for (oldFiber = mapRemainingChildren(oldFiber); !step.done; newIdx++, step = newChildren.next())
            nextOldFiber = updateFromMap(
              oldFiber,
              returnFiber,
              newIdx,
              step.value,
              lanes
            ), null !== nextOldFiber && (knownKeys = warnOnInvalidKey(
              returnFiber,
              nextOldFiber,
              step.value,
              knownKeys
            ), shouldTrackSideEffects && null !== nextOldFiber.alternate && oldFiber.delete(
              null === nextOldFiber.key ? newIdx : nextOldFiber.key
            ), currentFirstChild = placeChild(
              nextOldFiber,
              currentFirstChild,
              newIdx
            ), null === previousNewFiber ? resultingFirstChild = nextOldFiber : previousNewFiber.sibling = nextOldFiber, previousNewFiber = nextOldFiber);
          shouldTrackSideEffects && oldFiber.forEach(function(child) {
            return deleteChild(returnFiber, child);
          });
          isHydrating && pushTreeFork(returnFiber, newIdx);
          return resultingFirstChild;
        }
        __name(reconcileChildrenIterator, "reconcileChildrenIterator");
        function reconcileChildFibersImpl(returnFiber, currentFirstChild, newChild, lanes) {
          "object" === typeof newChild && null !== newChild && newChild.type === REACT_FRAGMENT_TYPE && null === newChild.key && (validateFragmentProps(newChild, null, returnFiber), newChild = newChild.props.children);
          if ("object" === typeof newChild && null !== newChild) {
            switch (newChild.$$typeof) {
              case REACT_ELEMENT_TYPE:
                var prevDebugInfo = pushDebugInfo(newChild._debugInfo);
                a: {
                  for (var key = newChild.key; null !== currentFirstChild; ) {
                    if (currentFirstChild.key === key) {
                      key = newChild.type;
                      if (key === REACT_FRAGMENT_TYPE) {
                        if (7 === currentFirstChild.tag) {
                          deleteRemainingChildren(
                            returnFiber,
                            currentFirstChild.sibling
                          );
                          lanes = useFiber(
                            currentFirstChild,
                            newChild.props.children
                          );
                          lanes.return = returnFiber;
                          lanes._debugOwner = newChild._owner;
                          lanes._debugInfo = currentDebugInfo;
                          validateFragmentProps(newChild, lanes, returnFiber);
                          returnFiber = lanes;
                          break a;
                        }
                      } else if (currentFirstChild.elementType === key || isCompatibleFamilyForHotReloading(
                        currentFirstChild,
                        newChild
                      ) || "object" === typeof key && null !== key && key.$$typeof === REACT_LAZY_TYPE && callLazyInitInDEV(key) === currentFirstChild.type) {
                        deleteRemainingChildren(
                          returnFiber,
                          currentFirstChild.sibling
                        );
                        lanes = useFiber(currentFirstChild, newChild.props);
                        coerceRef(lanes, newChild);
                        lanes.return = returnFiber;
                        lanes._debugOwner = newChild._owner;
                        lanes._debugInfo = currentDebugInfo;
                        returnFiber = lanes;
                        break a;
                      }
                      deleteRemainingChildren(returnFiber, currentFirstChild);
                      break;
                    } else deleteChild(returnFiber, currentFirstChild);
                    currentFirstChild = currentFirstChild.sibling;
                  }
                  newChild.type === REACT_FRAGMENT_TYPE ? (lanes = createFiberFromFragment(
                    newChild.props.children,
                    returnFiber.mode,
                    lanes,
                    newChild.key
                  ), lanes.return = returnFiber, lanes._debugOwner = returnFiber, lanes._debugTask = returnFiber._debugTask, lanes._debugInfo = currentDebugInfo, validateFragmentProps(newChild, lanes, returnFiber), returnFiber = lanes) : (lanes = createFiberFromElement(
                    newChild,
                    returnFiber.mode,
                    lanes
                  ), coerceRef(lanes, newChild), lanes.return = returnFiber, lanes._debugInfo = currentDebugInfo, returnFiber = lanes);
                }
                returnFiber = placeSingleChild(returnFiber);
                currentDebugInfo = prevDebugInfo;
                return returnFiber;
              case REACT_PORTAL_TYPE:
                a: {
                  prevDebugInfo = newChild;
                  for (newChild = prevDebugInfo.key; null !== currentFirstChild; ) {
                    if (currentFirstChild.key === newChild)
                      if (4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === prevDebugInfo.containerInfo && currentFirstChild.stateNode.implementation === prevDebugInfo.implementation) {
                        deleteRemainingChildren(
                          returnFiber,
                          currentFirstChild.sibling
                        );
                        lanes = useFiber(
                          currentFirstChild,
                          prevDebugInfo.children || []
                        );
                        lanes.return = returnFiber;
                        returnFiber = lanes;
                        break a;
                      } else {
                        deleteRemainingChildren(returnFiber, currentFirstChild);
                        break;
                      }
                    else deleteChild(returnFiber, currentFirstChild);
                    currentFirstChild = currentFirstChild.sibling;
                  }
                  lanes = createFiberFromPortal(
                    prevDebugInfo,
                    returnFiber.mode,
                    lanes
                  );
                  lanes.return = returnFiber;
                  returnFiber = lanes;
                }
                return placeSingleChild(returnFiber);
              case REACT_LAZY_TYPE:
                return prevDebugInfo = pushDebugInfo(newChild._debugInfo), newChild = callLazyInitInDEV(newChild), returnFiber = reconcileChildFibersImpl(
                  returnFiber,
                  currentFirstChild,
                  newChild,
                  lanes
                ), currentDebugInfo = prevDebugInfo, returnFiber;
            }
            if (isArrayImpl(newChild))
              return prevDebugInfo = pushDebugInfo(newChild._debugInfo), returnFiber = reconcileChildrenArray(
                returnFiber,
                currentFirstChild,
                newChild,
                lanes
              ), currentDebugInfo = prevDebugInfo, returnFiber;
            if (getIteratorFn(newChild)) {
              prevDebugInfo = pushDebugInfo(newChild._debugInfo);
              key = getIteratorFn(newChild);
              if ("function" !== typeof key)
                throw Error(
                  "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue."
                );
              var newChildren = key.call(newChild);
              if (newChildren === newChild) {
                if (0 !== returnFiber.tag || "[object GeneratorFunction]" !== Object.prototype.toString.call(returnFiber.type) || "[object Generator]" !== Object.prototype.toString.call(newChildren))
                  didWarnAboutGenerators || console.error(
                    "Using Iterators as children is unsupported and will likely yield unexpected results because enumerating a generator mutates it. You may convert it to an array with `Array.from()` or the `[...spread]` operator before rendering. You can also use an Iterable that can iterate multiple times over the same items."
                  ), didWarnAboutGenerators = true;
              } else
                newChild.entries !== key || didWarnAboutMaps || (console.error(
                  "Using Maps as children is not supported. Use an array of keyed ReactElements instead."
                ), didWarnAboutMaps = true);
              returnFiber = reconcileChildrenIterator(
                returnFiber,
                currentFirstChild,
                newChildren,
                lanes
              );
              currentDebugInfo = prevDebugInfo;
              return returnFiber;
            }
            if ("function" === typeof newChild.then)
              return prevDebugInfo = pushDebugInfo(newChild._debugInfo), returnFiber = reconcileChildFibersImpl(
                returnFiber,
                currentFirstChild,
                unwrapThenable(newChild),
                lanes
              ), currentDebugInfo = prevDebugInfo, returnFiber;
            if (newChild.$$typeof === REACT_CONTEXT_TYPE)
              return reconcileChildFibersImpl(
                returnFiber,
                currentFirstChild,
                readContextDuringReconciliation(returnFiber, newChild),
                lanes
              );
            throwOnInvalidObjectType(returnFiber, newChild);
          }
          if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
            return prevDebugInfo = "" + newChild, null !== currentFirstChild && 6 === currentFirstChild.tag ? (deleteRemainingChildren(
              returnFiber,
              currentFirstChild.sibling
            ), lanes = useFiber(currentFirstChild, prevDebugInfo), lanes.return = returnFiber, returnFiber = lanes) : (deleteRemainingChildren(returnFiber, currentFirstChild), lanes = createFiberFromText(
              prevDebugInfo,
              returnFiber.mode,
              lanes
            ), lanes.return = returnFiber, lanes._debugOwner = returnFiber, lanes._debugTask = returnFiber._debugTask, lanes._debugInfo = currentDebugInfo, returnFiber = lanes), placeSingleChild(returnFiber);
          "function" === typeof newChild && warnOnFunctionType(returnFiber, newChild);
          "symbol" === typeof newChild && warnOnSymbolType(returnFiber, newChild);
          return deleteRemainingChildren(returnFiber, currentFirstChild);
        }
        __name(reconcileChildFibersImpl, "reconcileChildFibersImpl");
        return function(returnFiber, currentFirstChild, newChild, lanes) {
          var prevDebugInfo = currentDebugInfo;
          currentDebugInfo = null;
          try {
            thenableIndexCounter = 0;
            var firstChildFiber = reconcileChildFibersImpl(
              returnFiber,
              currentFirstChild,
              newChild,
              lanes
            );
            thenableState = null;
            return firstChildFiber;
          } catch (x) {
            if (x === SuspenseException || x === SuspenseActionException) throw x;
            var fiber = createFiber(29, x, null, returnFiber.mode);
            fiber.lanes = lanes;
            fiber.return = returnFiber;
            var debugInfo = fiber._debugInfo = currentDebugInfo;
            fiber._debugOwner = returnFiber._debugOwner;
            fiber._debugTask = returnFiber._debugTask;
            if (null != debugInfo) {
              for (var i = debugInfo.length - 1; 0 <= i; i--)
                if ("string" === typeof debugInfo[i].stack) {
                  fiber._debugOwner = debugInfo[i];
                  fiber._debugTask = debugInfo[i].debugTask;
                  break;
                }
            }
            return fiber;
          } finally {
            currentDebugInfo = prevDebugInfo;
          }
        };
      }
      __name(createChildReconciler, "createChildReconciler");
      function pushPrimaryTreeSuspenseHandler(handler) {
        var current2 = handler.alternate;
        push2(
          suspenseStackCursor,
          suspenseStackCursor.current & SubtreeSuspenseContextMask,
          handler
        );
        push2(suspenseHandlerStackCursor, handler, handler);
        null === shellBoundary && (null === current2 || null !== currentTreeHiddenStackCursor.current ? shellBoundary = handler : null !== current2.memoizedState && (shellBoundary = handler));
      }
      __name(pushPrimaryTreeSuspenseHandler, "pushPrimaryTreeSuspenseHandler");
      function pushOffscreenSuspenseHandler(fiber) {
        if (22 === fiber.tag) {
          if (push2(suspenseStackCursor, suspenseStackCursor.current, fiber), push2(suspenseHandlerStackCursor, fiber, fiber), null === shellBoundary) {
            var current2 = fiber.alternate;
            null !== current2 && null !== current2.memoizedState && (shellBoundary = fiber);
          }
        } else reuseSuspenseHandlerOnStack(fiber);
      }
      __name(pushOffscreenSuspenseHandler, "pushOffscreenSuspenseHandler");
      function reuseSuspenseHandlerOnStack(fiber) {
        push2(suspenseStackCursor, suspenseStackCursor.current, fiber);
        push2(
          suspenseHandlerStackCursor,
          suspenseHandlerStackCursor.current,
          fiber
        );
      }
      __name(reuseSuspenseHandlerOnStack, "reuseSuspenseHandlerOnStack");
      function popSuspenseHandler(fiber) {
        pop(suspenseHandlerStackCursor, fiber);
        shellBoundary === fiber && (shellBoundary = null);
        pop(suspenseStackCursor, fiber);
      }
      __name(popSuspenseHandler, "popSuspenseHandler");
      function findFirstSuspended(row) {
        for (var node = row; null !== node; ) {
          if (13 === node.tag) {
            var state = node.memoizedState;
            if (null !== state && (state = state.dehydrated, null === state || isSuspenseInstancePending(state) || isSuspenseInstanceFallback(state)))
              return node;
          } else if (19 === node.tag && void 0 !== node.memoizedProps.revealOrder) {
            if (0 !== (node.flags & 128)) return node;
          } else if (null !== node.child) {
            node.child.return = node;
            node = node.child;
            continue;
          }
          if (node === row) break;
          for (; null === node.sibling; ) {
            if (null === node.return || node.return === row) return null;
            node = node.return;
          }
          node.sibling.return = node.return;
          node = node.sibling;
        }
        return null;
      }
      __name(findFirstSuspended, "findFirstSuspended");
      function warnOnInvalidCallback(callback) {
        if (null !== callback && "function" !== typeof callback) {
          var key = String(callback);
          didWarnOnInvalidCallback.has(key) || (didWarnOnInvalidCallback.add(key), console.error(
            "Expected the last optional `callback` argument to be a function. Instead received: %s.",
            callback
          ));
        }
      }
      __name(warnOnInvalidCallback, "warnOnInvalidCallback");
      function applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, nextProps) {
        var prevState = workInProgress2.memoizedState, partialState = getDerivedStateFromProps(nextProps, prevState);
        if (workInProgress2.mode & 8) {
          setIsStrictModeForDevtools(true);
          try {
            partialState = getDerivedStateFromProps(nextProps, prevState);
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
        void 0 === partialState && (ctor = getComponentNameFromType(ctor) || "Component", didWarnAboutUndefinedDerivedState.has(ctor) || (didWarnAboutUndefinedDerivedState.add(ctor), console.error(
          "%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. You have returned undefined.",
          ctor
        )));
        prevState = null === partialState || void 0 === partialState ? prevState : assign({}, prevState, partialState);
        workInProgress2.memoizedState = prevState;
        0 === workInProgress2.lanes && (workInProgress2.updateQueue.baseState = prevState);
      }
      __name(applyDerivedStateFromProps, "applyDerivedStateFromProps");
      function checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) {
        var instance = workInProgress2.stateNode;
        if ("function" === typeof instance.shouldComponentUpdate) {
          oldProps = instance.shouldComponentUpdate(
            newProps,
            newState,
            nextContext
          );
          if (workInProgress2.mode & 8) {
            setIsStrictModeForDevtools(true);
            try {
              oldProps = instance.shouldComponentUpdate(
                newProps,
                newState,
                nextContext
              );
            } finally {
              setIsStrictModeForDevtools(false);
            }
          }
          void 0 === oldProps && console.error(
            "%s.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.",
            getComponentNameFromType(ctor) || "Component"
          );
          return oldProps;
        }
        return ctor.prototype && ctor.prototype.isPureReactComponent ? !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState) : true;
      }
      __name(checkShouldComponentUpdate, "checkShouldComponentUpdate");
      function callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext) {
        var oldState = instance.state;
        "function" === typeof instance.componentWillReceiveProps && instance.componentWillReceiveProps(newProps, nextContext);
        "function" === typeof instance.UNSAFE_componentWillReceiveProps && instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
        instance.state !== oldState && (workInProgress2 = getComponentNameFromFiber(workInProgress2) || "Component", didWarnAboutStateAssignmentForComponent.has(workInProgress2) || (didWarnAboutStateAssignmentForComponent.add(workInProgress2), console.error(
          "%s.componentWillReceiveProps(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.",
          workInProgress2
        )), classComponentUpdater.enqueueReplaceState(
          instance,
          instance.state,
          null
        ));
      }
      __name(callComponentWillReceiveProps, "callComponentWillReceiveProps");
      function resolveClassComponentProps(Component, baseProps) {
        var newProps = baseProps;
        if ("ref" in baseProps) {
          newProps = {};
          for (var propName in baseProps)
            "ref" !== propName && (newProps[propName] = baseProps[propName]);
        }
        if (Component = Component.defaultProps) {
          newProps === baseProps && (newProps = assign({}, newProps));
          for (var _propName in Component)
            void 0 === newProps[_propName] && (newProps[_propName] = Component[_propName]);
        }
        return newProps;
      }
      __name(resolveClassComponentProps, "resolveClassComponentProps");
      function logUncaughtError(root, errorInfo) {
        try {
          componentName = errorInfo.source ? getComponentNameFromFiber(errorInfo.source) : null;
          errorBoundaryName = null;
          var error = errorInfo.value;
          if (null !== ReactSharedInternals.actQueue)
            ReactSharedInternals.thrownErrors.push(error);
          else {
            var onUncaughtError = root.onUncaughtError;
            onUncaughtError(error, { componentStack: errorInfo.stack });
          }
        } catch (e2) {
          setTimeout(function() {
            throw e2;
          });
        }
      }
      __name(logUncaughtError, "logUncaughtError");
      function logCaughtError(root, boundary, errorInfo) {
        try {
          componentName = errorInfo.source ? getComponentNameFromFiber(errorInfo.source) : null;
          errorBoundaryName = getComponentNameFromFiber(boundary);
          var onCaughtError = root.onCaughtError;
          onCaughtError(errorInfo.value, {
            componentStack: errorInfo.stack,
            errorBoundary: 1 === boundary.tag ? boundary.stateNode : null
          });
        } catch (e2) {
          setTimeout(function() {
            throw e2;
          });
        }
      }
      __name(logCaughtError, "logCaughtError");
      function createRootErrorUpdate(root, errorInfo, lane) {
        lane = createUpdate(lane);
        lane.tag = CaptureUpdate;
        lane.payload = { element: null };
        lane.callback = function() {
          runWithFiberInDEV(errorInfo.source, logUncaughtError, root, errorInfo);
        };
        return lane;
      }
      __name(createRootErrorUpdate, "createRootErrorUpdate");
      function createClassErrorUpdate(lane) {
        lane = createUpdate(lane);
        lane.tag = CaptureUpdate;
        return lane;
      }
      __name(createClassErrorUpdate, "createClassErrorUpdate");
      function initializeClassErrorUpdate(update2, root, fiber, errorInfo) {
        var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
        if ("function" === typeof getDerivedStateFromError) {
          var error = errorInfo.value;
          update2.payload = function() {
            return getDerivedStateFromError(error);
          };
          update2.callback = function() {
            markFailedErrorBoundaryForHotReloading(fiber);
            runWithFiberInDEV(
              errorInfo.source,
              logCaughtError,
              root,
              fiber,
              errorInfo
            );
          };
        }
        var inst = fiber.stateNode;
        null !== inst && "function" === typeof inst.componentDidCatch && (update2.callback = function() {
          markFailedErrorBoundaryForHotReloading(fiber);
          runWithFiberInDEV(
            errorInfo.source,
            logCaughtError,
            root,
            fiber,
            errorInfo
          );
          "function" !== typeof getDerivedStateFromError && (null === legacyErrorBoundariesThatAlreadyFailed ? legacyErrorBoundariesThatAlreadyFailed = /* @__PURE__ */ new Set([this]) : legacyErrorBoundariesThatAlreadyFailed.add(this));
          callComponentDidCatchInDEV(this, errorInfo);
          "function" === typeof getDerivedStateFromError || 0 === (fiber.lanes & 2) && console.error(
            "%s: Error boundaries should implement getDerivedStateFromError(). In that method, return a state update to display an error message or fallback UI.",
            getComponentNameFromFiber(fiber) || "Unknown"
          );
        });
      }
      __name(initializeClassErrorUpdate, "initializeClassErrorUpdate");
      function throwException(root, returnFiber, sourceFiber, value, rootRenderLanes) {
        sourceFiber.flags |= 32768;
        isDevToolsPresent && restorePendingUpdaters(root, rootRenderLanes);
        if (null !== value && "object" === typeof value && "function" === typeof value.then) {
          returnFiber = sourceFiber.alternate;
          null !== returnFiber && propagateParentContextChanges(
            returnFiber,
            sourceFiber,
            rootRenderLanes,
            true
          );
          isHydrating && (didSuspendOrErrorDEV = true);
          sourceFiber = suspenseHandlerStackCursor.current;
          if (null !== sourceFiber) {
            switch (sourceFiber.tag) {
              case 13:
                return null === shellBoundary ? renderDidSuspendDelayIfPossible() : null === sourceFiber.alternate && workInProgressRootExitStatus === RootInProgress && (workInProgressRootExitStatus = RootSuspended), sourceFiber.flags &= -257, sourceFiber.flags |= 65536, sourceFiber.lanes = rootRenderLanes, value === noopSuspenseyCommitThenable ? sourceFiber.flags |= 16384 : (returnFiber = sourceFiber.updateQueue, null === returnFiber ? sourceFiber.updateQueue = /* @__PURE__ */ new Set([value]) : returnFiber.add(value), attachPingListener(root, value, rootRenderLanes)), false;
              case 22:
                return sourceFiber.flags |= 65536, value === noopSuspenseyCommitThenable ? sourceFiber.flags |= 16384 : (returnFiber = sourceFiber.updateQueue, null === returnFiber ? (returnFiber = {
                  transitions: null,
                  markerInstances: null,
                  retryQueue: /* @__PURE__ */ new Set([value])
                }, sourceFiber.updateQueue = returnFiber) : (sourceFiber = returnFiber.retryQueue, null === sourceFiber ? returnFiber.retryQueue = /* @__PURE__ */ new Set([value]) : sourceFiber.add(value)), attachPingListener(root, value, rootRenderLanes)), false;
            }
            throw Error(
              "Unexpected Suspense handler tag (" + sourceFiber.tag + "). This is a bug in React."
            );
          }
          attachPingListener(root, value, rootRenderLanes);
          renderDidSuspendDelayIfPossible();
          return false;
        }
        if (isHydrating)
          return didSuspendOrErrorDEV = true, returnFiber = suspenseHandlerStackCursor.current, null !== returnFiber ? (0 === (returnFiber.flags & 65536) && (returnFiber.flags |= 256), returnFiber.flags |= 65536, returnFiber.lanes = rootRenderLanes, value !== HydrationMismatchException && queueHydrationError(
            createCapturedValueAtFiber(
              Error(
                "There was an error while hydrating but React was able to recover by instead client rendering from the nearest Suspense boundary.",
                { cause: value }
              ),
              sourceFiber
            )
          )) : (value !== HydrationMismatchException && queueHydrationError(
            createCapturedValueAtFiber(
              Error(
                "There was an error while hydrating but React was able to recover by instead client rendering the entire root.",
                { cause: value }
              ),
              sourceFiber
            )
          ), root = root.current.alternate, root.flags |= 65536, rootRenderLanes &= -rootRenderLanes, root.lanes |= rootRenderLanes, value = createCapturedValueAtFiber(value, sourceFiber), rootRenderLanes = createRootErrorUpdate(
            root.stateNode,
            value,
            rootRenderLanes
          ), enqueueCapturedUpdate(root, rootRenderLanes), workInProgressRootExitStatus !== RootSuspendedWithDelay && (workInProgressRootExitStatus = RootErrored)), false;
        var error = createCapturedValueAtFiber(
          Error(
            "There was an error during concurrent rendering but React was able to recover by instead synchronously rendering the entire root.",
            { cause: value }
          ),
          sourceFiber
        );
        null === workInProgressRootConcurrentErrors ? workInProgressRootConcurrentErrors = [error] : workInProgressRootConcurrentErrors.push(error);
        workInProgressRootExitStatus !== RootSuspendedWithDelay && (workInProgressRootExitStatus = RootErrored);
        if (null === returnFiber) return true;
        value = createCapturedValueAtFiber(value, sourceFiber);
        sourceFiber = returnFiber;
        do {
          switch (sourceFiber.tag) {
            case 3:
              return sourceFiber.flags |= 65536, root = rootRenderLanes & -rootRenderLanes, sourceFiber.lanes |= root, root = createRootErrorUpdate(
                sourceFiber.stateNode,
                value,
                root
              ), enqueueCapturedUpdate(sourceFiber, root), false;
            case 1:
              if (returnFiber = sourceFiber.type, error = sourceFiber.stateNode, 0 === (sourceFiber.flags & 128) && ("function" === typeof returnFiber.getDerivedStateFromError || null !== error && "function" === typeof error.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(error))))
                return sourceFiber.flags |= 65536, rootRenderLanes &= -rootRenderLanes, sourceFiber.lanes |= rootRenderLanes, rootRenderLanes = createClassErrorUpdate(rootRenderLanes), initializeClassErrorUpdate(
                  rootRenderLanes,
                  root,
                  sourceFiber,
                  value
                ), enqueueCapturedUpdate(sourceFiber, rootRenderLanes), false;
          }
          sourceFiber = sourceFiber.return;
        } while (null !== sourceFiber);
        return false;
      }
      __name(throwException, "throwException");
      function reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2) {
        workInProgress2.child = null === current2 ? mountChildFibers(workInProgress2, null, nextChildren, renderLanes2) : reconcileChildFibers(
          workInProgress2,
          current2.child,
          nextChildren,
          renderLanes2
        );
      }
      __name(reconcileChildren, "reconcileChildren");
      function updateForwardRef(current2, workInProgress2, Component, nextProps, renderLanes2) {
        Component = Component.render;
        var ref = workInProgress2.ref;
        if ("ref" in nextProps) {
          var propsWithoutRef = {};
          for (var key in nextProps)
            "ref" !== key && (propsWithoutRef[key] = nextProps[key]);
        } else propsWithoutRef = nextProps;
        prepareToReadContext(workInProgress2);
        markComponentRenderStarted(workInProgress2);
        nextProps = renderWithHooks(
          current2,
          workInProgress2,
          Component,
          propsWithoutRef,
          ref,
          renderLanes2
        );
        key = checkDidRenderIdHook();
        markComponentRenderStopped();
        if (null !== current2 && !didReceiveUpdate)
          return bailoutHooks(current2, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
        isHydrating && key && pushMaterializedTreeId(workInProgress2);
        workInProgress2.flags |= 1;
        reconcileChildren(current2, workInProgress2, nextProps, renderLanes2);
        return workInProgress2.child;
      }
      __name(updateForwardRef, "updateForwardRef");
      function updateMemoComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
        if (null === current2) {
          var type = Component.type;
          if ("function" === typeof type && !shouldConstruct(type) && void 0 === type.defaultProps && null === Component.compare)
            return Component = resolveFunctionForHotReloading(type), workInProgress2.tag = 15, workInProgress2.type = Component, validateFunctionComponentInDev(workInProgress2, type), updateSimpleMemoComponent(
              current2,
              workInProgress2,
              Component,
              nextProps,
              renderLanes2
            );
          current2 = createFiberFromTypeAndProps(
            Component.type,
            null,
            nextProps,
            workInProgress2,
            workInProgress2.mode,
            renderLanes2
          );
          current2.ref = workInProgress2.ref;
          current2.return = workInProgress2;
          return workInProgress2.child = current2;
        }
        type = current2.child;
        if (!checkScheduledUpdateOrContext(current2, renderLanes2)) {
          var prevProps = type.memoizedProps;
          Component = Component.compare;
          Component = null !== Component ? Component : shallowEqual;
          if (Component(prevProps, nextProps) && current2.ref === workInProgress2.ref)
            return bailoutOnAlreadyFinishedWork(
              current2,
              workInProgress2,
              renderLanes2
            );
        }
        workInProgress2.flags |= 1;
        current2 = createWorkInProgress(type, nextProps);
        current2.ref = workInProgress2.ref;
        current2.return = workInProgress2;
        return workInProgress2.child = current2;
      }
      __name(updateMemoComponent, "updateMemoComponent");
      function updateSimpleMemoComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
        if (null !== current2) {
          var prevProps = current2.memoizedProps;
          if (shallowEqual(prevProps, nextProps) && current2.ref === workInProgress2.ref && workInProgress2.type === current2.type)
            if (didReceiveUpdate = false, workInProgress2.pendingProps = nextProps = prevProps, checkScheduledUpdateOrContext(current2, renderLanes2))
              0 !== (current2.flags & 131072) && (didReceiveUpdate = true);
            else
              return workInProgress2.lanes = current2.lanes, bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
        }
        return updateFunctionComponent(
          current2,
          workInProgress2,
          Component,
          nextProps,
          renderLanes2
        );
      }
      __name(updateSimpleMemoComponent, "updateSimpleMemoComponent");
      function updateOffscreenComponent(current2, workInProgress2, renderLanes2) {
        var nextProps = workInProgress2.pendingProps, nextChildren = nextProps.children, prevState = null !== current2 ? current2.memoizedState : null;
        if ("hidden" === nextProps.mode) {
          if (0 !== (workInProgress2.flags & 128)) {
            nextProps = null !== prevState ? prevState.baseLanes | renderLanes2 : renderLanes2;
            if (null !== current2) {
              nextChildren = workInProgress2.child = current2.child;
              for (prevState = 0; null !== nextChildren; )
                prevState = prevState | nextChildren.lanes | nextChildren.childLanes, nextChildren = nextChildren.sibling;
              workInProgress2.childLanes = prevState & ~nextProps;
            } else workInProgress2.childLanes = 0, workInProgress2.child = null;
            return deferHiddenOffscreenComponent(
              current2,
              workInProgress2,
              nextProps,
              renderLanes2
            );
          }
          if (0 !== (renderLanes2 & 536870912))
            workInProgress2.memoizedState = { baseLanes: 0, cachePool: null }, null !== current2 && pushTransition(
              workInProgress2,
              null !== prevState ? prevState.cachePool : null
            ), null !== prevState ? pushHiddenContext(workInProgress2, prevState) : reuseHiddenContextOnStack(workInProgress2), pushOffscreenSuspenseHandler(workInProgress2);
          else
            return workInProgress2.lanes = workInProgress2.childLanes = 536870912, deferHiddenOffscreenComponent(
              current2,
              workInProgress2,
              null !== prevState ? prevState.baseLanes | renderLanes2 : renderLanes2,
              renderLanes2
            );
        } else
          null !== prevState ? (pushTransition(workInProgress2, prevState.cachePool), pushHiddenContext(workInProgress2, prevState), reuseSuspenseHandlerOnStack(workInProgress2), workInProgress2.memoizedState = null) : (null !== current2 && pushTransition(workInProgress2, null), reuseHiddenContextOnStack(workInProgress2), reuseSuspenseHandlerOnStack(workInProgress2));
        reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
        return workInProgress2.child;
      }
      __name(updateOffscreenComponent, "updateOffscreenComponent");
      function deferHiddenOffscreenComponent(current2, workInProgress2, nextBaseLanes, renderLanes2) {
        var JSCompiler_inline_result = peekCacheFromPool();
        JSCompiler_inline_result = null === JSCompiler_inline_result ? null : {
          parent: isPrimaryRenderer ? CacheContext._currentValue : CacheContext._currentValue2,
          pool: JSCompiler_inline_result
        };
        workInProgress2.memoizedState = {
          baseLanes: nextBaseLanes,
          cachePool: JSCompiler_inline_result
        };
        null !== current2 && pushTransition(workInProgress2, null);
        reuseHiddenContextOnStack(workInProgress2);
        pushOffscreenSuspenseHandler(workInProgress2);
        null !== current2 && propagateParentContextChanges(current2, workInProgress2, renderLanes2, true);
        return null;
      }
      __name(deferHiddenOffscreenComponent, "deferHiddenOffscreenComponent");
      function markRef(current2, workInProgress2) {
        var ref = workInProgress2.ref;
        if (null === ref)
          null !== current2 && null !== current2.ref && (workInProgress2.flags |= 4194816);
        else {
          if ("function" !== typeof ref && "object" !== typeof ref)
            throw Error(
              "Expected ref to be a function, an object returned by React.createRef(), or undefined/null."
            );
          if (null === current2 || current2.ref !== ref)
            workInProgress2.flags |= 4194816;
        }
      }
      __name(markRef, "markRef");
      function updateFunctionComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
        if (Component.prototype && "function" === typeof Component.prototype.render) {
          var componentName2 = getComponentNameFromType(Component) || "Unknown";
          didWarnAboutBadClass[componentName2] || (console.error(
            "The <%s /> component appears to have a render method, but doesn't extend React.Component. This is likely to cause errors. Change %s to extend React.Component instead.",
            componentName2,
            componentName2
          ), didWarnAboutBadClass[componentName2] = true);
        }
        workInProgress2.mode & 8 && ReactStrictModeWarnings.recordLegacyContextWarning(
          workInProgress2,
          null
        );
        null === current2 && (validateFunctionComponentInDev(workInProgress2, workInProgress2.type), Component.contextTypes && (componentName2 = getComponentNameFromType(Component) || "Unknown", didWarnAboutContextTypes[componentName2] || (didWarnAboutContextTypes[componentName2] = true, console.error(
          "%s uses the legacy contextTypes API which was removed in React 19. Use React.createContext() with React.useContext() instead. (https://react.dev/link/legacy-context)",
          componentName2
        ))));
        prepareToReadContext(workInProgress2);
        markComponentRenderStarted(workInProgress2);
        Component = renderWithHooks(
          current2,
          workInProgress2,
          Component,
          nextProps,
          void 0,
          renderLanes2
        );
        nextProps = checkDidRenderIdHook();
        markComponentRenderStopped();
        if (null !== current2 && !didReceiveUpdate)
          return bailoutHooks(current2, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
        isHydrating && nextProps && pushMaterializedTreeId(workInProgress2);
        workInProgress2.flags |= 1;
        reconcileChildren(current2, workInProgress2, Component, renderLanes2);
        return workInProgress2.child;
      }
      __name(updateFunctionComponent, "updateFunctionComponent");
      function replayFunctionComponent(current2, workInProgress2, nextProps, Component, secondArg, renderLanes2) {
        prepareToReadContext(workInProgress2);
        markComponentRenderStarted(workInProgress2);
        hookTypesUpdateIndexDev = -1;
        ignorePreviousDependencies = null !== current2 && current2.type !== workInProgress2.type;
        workInProgress2.updateQueue = null;
        nextProps = renderWithHooksAgain(
          workInProgress2,
          Component,
          nextProps,
          secondArg
        );
        finishRenderingHooks(current2, workInProgress2);
        Component = checkDidRenderIdHook();
        markComponentRenderStopped();
        if (null !== current2 && !didReceiveUpdate)
          return bailoutHooks(current2, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
        isHydrating && Component && pushMaterializedTreeId(workInProgress2);
        workInProgress2.flags |= 1;
        reconcileChildren(current2, workInProgress2, nextProps, renderLanes2);
        return workInProgress2.child;
      }
      __name(replayFunctionComponent, "replayFunctionComponent");
      function updateClassComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
        switch (shouldErrorImpl(workInProgress2)) {
          case false:
            var _instance = workInProgress2.stateNode, state = new workInProgress2.type(
              workInProgress2.memoizedProps,
              _instance.context
            ).state;
            _instance.updater.enqueueSetState(_instance, state, null);
            break;
          case true:
            workInProgress2.flags |= 128;
            workInProgress2.flags |= 65536;
            _instance = Error("Simulated error coming from DevTools");
            var lane = renderLanes2 & -renderLanes2;
            workInProgress2.lanes |= lane;
            state = workInProgressRoot;
            if (null === state)
              throw Error(
                "Expected a work-in-progress root. This is a bug in React. Please file an issue."
              );
            lane = createClassErrorUpdate(lane);
            initializeClassErrorUpdate(
              lane,
              state,
              workInProgress2,
              createCapturedValueAtFiber(_instance, workInProgress2)
            );
            enqueueCapturedUpdate(workInProgress2, lane);
        }
        prepareToReadContext(workInProgress2);
        if (null === workInProgress2.stateNode) {
          state = emptyContextObject;
          _instance = Component.contextType;
          "contextType" in Component && null !== _instance && (void 0 === _instance || _instance.$$typeof !== REACT_CONTEXT_TYPE) && !didWarnAboutInvalidateContextType.has(Component) && (didWarnAboutInvalidateContextType.add(Component), lane = void 0 === _instance ? " However, it is set to undefined. This can be caused by a typo or by mixing up named and default imports. This can also happen due to a circular dependency, so try moving the createContext() call to a separate file." : "object" !== typeof _instance ? " However, it is set to a " + typeof _instance + "." : _instance.$$typeof === REACT_CONSUMER_TYPE ? " Did you accidentally pass the Context.Consumer instead?" : " However, it is set to an object with keys {" + Object.keys(_instance).join(", ") + "}.", console.error(
            "%s defines an invalid contextType. contextType should point to the Context object returned by React.createContext().%s",
            getComponentNameFromType(Component) || "Component",
            lane
          ));
          "object" === typeof _instance && null !== _instance && (state = readContext(_instance));
          _instance = new Component(nextProps, state);
          if (workInProgress2.mode & 8) {
            setIsStrictModeForDevtools(true);
            try {
              _instance = new Component(nextProps, state);
            } finally {
              setIsStrictModeForDevtools(false);
            }
          }
          state = workInProgress2.memoizedState = null !== _instance.state && void 0 !== _instance.state ? _instance.state : null;
          _instance.updater = classComponentUpdater;
          workInProgress2.stateNode = _instance;
          _instance._reactInternals = workInProgress2;
          _instance._reactInternalInstance = fakeInternalInstance;
          "function" === typeof Component.getDerivedStateFromProps && null === state && (state = getComponentNameFromType(Component) || "Component", didWarnAboutUninitializedState.has(state) || (didWarnAboutUninitializedState.add(state), console.error(
            "`%s` uses `getDerivedStateFromProps` but its initial state is %s. This is not recommended. Instead, define the initial state by assigning an object to `this.state` in the constructor of `%s`. This ensures that `getDerivedStateFromProps` arguments have a consistent shape.",
            state,
            null === _instance.state ? "null" : "undefined",
            state
          )));
          if ("function" === typeof Component.getDerivedStateFromProps || "function" === typeof _instance.getSnapshotBeforeUpdate) {
            var foundWillUpdateName = lane = state = null;
            "function" === typeof _instance.componentWillMount && true !== _instance.componentWillMount.__suppressDeprecationWarning ? state = "componentWillMount" : "function" === typeof _instance.UNSAFE_componentWillMount && (state = "UNSAFE_componentWillMount");
            "function" === typeof _instance.componentWillReceiveProps && true !== _instance.componentWillReceiveProps.__suppressDeprecationWarning ? lane = "componentWillReceiveProps" : "function" === typeof _instance.UNSAFE_componentWillReceiveProps && (lane = "UNSAFE_componentWillReceiveProps");
            "function" === typeof _instance.componentWillUpdate && true !== _instance.componentWillUpdate.__suppressDeprecationWarning ? foundWillUpdateName = "componentWillUpdate" : "function" === typeof _instance.UNSAFE_componentWillUpdate && (foundWillUpdateName = "UNSAFE_componentWillUpdate");
            if (null !== state || null !== lane || null !== foundWillUpdateName) {
              _instance = getComponentNameFromType(Component) || "Component";
              var newApiName = "function" === typeof Component.getDerivedStateFromProps ? "getDerivedStateFromProps()" : "getSnapshotBeforeUpdate()";
              didWarnAboutLegacyLifecyclesAndDerivedState.has(_instance) || (didWarnAboutLegacyLifecyclesAndDerivedState.add(_instance), console.error(
                "Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\nThe above lifecycles should be removed. Learn more about this warning here:\nhttps://react.dev/link/unsafe-component-lifecycles",
                _instance,
                newApiName,
                null !== state ? "\n  " + state : "",
                null !== lane ? "\n  " + lane : "",
                null !== foundWillUpdateName ? "\n  " + foundWillUpdateName : ""
              ));
            }
          }
          _instance = workInProgress2.stateNode;
          state = getComponentNameFromType(Component) || "Component";
          _instance.render || (Component.prototype && "function" === typeof Component.prototype.render ? console.error(
            "No `render` method found on the %s instance: did you accidentally return an object from the constructor?",
            state
          ) : console.error(
            "No `render` method found on the %s instance: you may have forgotten to define `render`.",
            state
          ));
          !_instance.getInitialState || _instance.getInitialState.isReactClassApproved || _instance.state || console.error(
            "getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?",
            state
          );
          _instance.getDefaultProps && !_instance.getDefaultProps.isReactClassApproved && console.error(
            "getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.",
            state
          );
          _instance.contextType && console.error(
            "contextType was defined as an instance property on %s. Use a static property to define contextType instead.",
            state
          );
          Component.childContextTypes && !didWarnAboutChildContextTypes.has(Component) && (didWarnAboutChildContextTypes.add(Component), console.error(
            "%s uses the legacy childContextTypes API which was removed in React 19. Use React.createContext() instead. (https://react.dev/link/legacy-context)",
            state
          ));
          Component.contextTypes && !didWarnAboutContextTypes$1.has(Component) && (didWarnAboutContextTypes$1.add(Component), console.error(
            "%s uses the legacy contextTypes API which was removed in React 19. Use React.createContext() with static contextType instead. (https://react.dev/link/legacy-context)",
            state
          ));
          "function" === typeof _instance.componentShouldUpdate && console.error(
            "%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.",
            state
          );
          Component.prototype && Component.prototype.isPureReactComponent && "undefined" !== typeof _instance.shouldComponentUpdate && console.error(
            "%s has a method called shouldComponentUpdate(). shouldComponentUpdate should not be used when extending React.PureComponent. Please extend React.Component if shouldComponentUpdate is used.",
            getComponentNameFromType(Component) || "A pure component"
          );
          "function" === typeof _instance.componentDidUnmount && console.error(
            "%s has a method called componentDidUnmount(). But there is no such lifecycle method. Did you mean componentWillUnmount()?",
            state
          );
          "function" === typeof _instance.componentDidReceiveProps && console.error(
            "%s has a method called componentDidReceiveProps(). But there is no such lifecycle method. If you meant to update the state in response to changing props, use componentWillReceiveProps(). If you meant to fetch data or run side-effects or mutations after React has updated the UI, use componentDidUpdate().",
            state
          );
          "function" === typeof _instance.componentWillRecieveProps && console.error(
            "%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?",
            state
          );
          "function" === typeof _instance.UNSAFE_componentWillRecieveProps && console.error(
            "%s has a method called UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?",
            state
          );
          lane = _instance.props !== nextProps;
          void 0 !== _instance.props && lane && console.error(
            "When calling super() in `%s`, make sure to pass up the same props that your component's constructor was passed.",
            state
          );
          _instance.defaultProps && console.error(
            "Setting defaultProps as an instance property on %s is not supported and will be ignored. Instead, define defaultProps as a static property on %s.",
            state,
            state
          );
          "function" !== typeof _instance.getSnapshotBeforeUpdate || "function" === typeof _instance.componentDidUpdate || didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(Component) || (didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(Component), console.error(
            "%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). This component defines getSnapshotBeforeUpdate() only.",
            getComponentNameFromType(Component)
          ));
          "function" === typeof _instance.getDerivedStateFromProps && console.error(
            "%s: getDerivedStateFromProps() is defined as an instance method and will be ignored. Instead, declare it as a static method.",
            state
          );
          "function" === typeof _instance.getDerivedStateFromError && console.error(
            "%s: getDerivedStateFromError() is defined as an instance method and will be ignored. Instead, declare it as a static method.",
            state
          );
          "function" === typeof Component.getSnapshotBeforeUpdate && console.error(
            "%s: getSnapshotBeforeUpdate() is defined as a static method and will be ignored. Instead, declare it as an instance method.",
            state
          );
          (lane = _instance.state) && ("object" !== typeof lane || isArrayImpl(lane)) && console.error("%s.state: must be set to an object or null", state);
          "function" === typeof _instance.getChildContext && "object" !== typeof Component.childContextTypes && console.error(
            "%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().",
            state
          );
          _instance = workInProgress2.stateNode;
          _instance.props = nextProps;
          _instance.state = workInProgress2.memoizedState;
          _instance.refs = {};
          initializeUpdateQueue(workInProgress2);
          state = Component.contextType;
          _instance.context = "object" === typeof state && null !== state ? readContext(state) : emptyContextObject;
          _instance.state === nextProps && (state = getComponentNameFromType(Component) || "Component", didWarnAboutDirectlyAssigningPropsToState.has(state) || (didWarnAboutDirectlyAssigningPropsToState.add(state), console.error(
            "%s: It is not recommended to assign props directly to state because updates to props won't be reflected in state. In most cases, it is better to use props directly.",
            state
          )));
          workInProgress2.mode & 8 && ReactStrictModeWarnings.recordLegacyContextWarning(
            workInProgress2,
            _instance
          );
          ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(
            workInProgress2,
            _instance
          );
          _instance.state = workInProgress2.memoizedState;
          state = Component.getDerivedStateFromProps;
          "function" === typeof state && (applyDerivedStateFromProps(
            workInProgress2,
            Component,
            state,
            nextProps
          ), _instance.state = workInProgress2.memoizedState);
          "function" === typeof Component.getDerivedStateFromProps || "function" === typeof _instance.getSnapshotBeforeUpdate || "function" !== typeof _instance.UNSAFE_componentWillMount && "function" !== typeof _instance.componentWillMount || (state = _instance.state, "function" === typeof _instance.componentWillMount && _instance.componentWillMount(), "function" === typeof _instance.UNSAFE_componentWillMount && _instance.UNSAFE_componentWillMount(), state !== _instance.state && (console.error(
            "%s.componentWillMount(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.",
            getComponentNameFromFiber(workInProgress2) || "Component"
          ), classComponentUpdater.enqueueReplaceState(
            _instance,
            _instance.state,
            null
          )), processUpdateQueue(workInProgress2, nextProps, _instance, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction(), _instance.state = workInProgress2.memoizedState);
          "function" === typeof _instance.componentDidMount && (workInProgress2.flags |= 4194308);
          (workInProgress2.mode & 16) !== NoMode && (workInProgress2.flags |= 134217728);
          _instance = true;
        } else if (null === current2) {
          _instance = workInProgress2.stateNode;
          var unresolvedOldProps = workInProgress2.memoizedProps;
          lane = resolveClassComponentProps(Component, unresolvedOldProps);
          _instance.props = lane;
          var oldContext = _instance.context;
          foundWillUpdateName = Component.contextType;
          state = emptyContextObject;
          "object" === typeof foundWillUpdateName && null !== foundWillUpdateName && (state = readContext(foundWillUpdateName));
          newApiName = Component.getDerivedStateFromProps;
          foundWillUpdateName = "function" === typeof newApiName || "function" === typeof _instance.getSnapshotBeforeUpdate;
          unresolvedOldProps = workInProgress2.pendingProps !== unresolvedOldProps;
          foundWillUpdateName || "function" !== typeof _instance.UNSAFE_componentWillReceiveProps && "function" !== typeof _instance.componentWillReceiveProps || (unresolvedOldProps || oldContext !== state) && callComponentWillReceiveProps(
            workInProgress2,
            _instance,
            nextProps,
            state
          );
          hasForceUpdate = false;
          var oldState = workInProgress2.memoizedState;
          _instance.state = oldState;
          processUpdateQueue(workInProgress2, nextProps, _instance, renderLanes2);
          suspendIfUpdateReadFromEntangledAsyncAction();
          oldContext = workInProgress2.memoizedState;
          unresolvedOldProps || oldState !== oldContext || hasForceUpdate ? ("function" === typeof newApiName && (applyDerivedStateFromProps(
            workInProgress2,
            Component,
            newApiName,
            nextProps
          ), oldContext = workInProgress2.memoizedState), (lane = hasForceUpdate || checkShouldComponentUpdate(
            workInProgress2,
            Component,
            lane,
            nextProps,
            oldState,
            oldContext,
            state
          )) ? (foundWillUpdateName || "function" !== typeof _instance.UNSAFE_componentWillMount && "function" !== typeof _instance.componentWillMount || ("function" === typeof _instance.componentWillMount && _instance.componentWillMount(), "function" === typeof _instance.UNSAFE_componentWillMount && _instance.UNSAFE_componentWillMount()), "function" === typeof _instance.componentDidMount && (workInProgress2.flags |= 4194308), (workInProgress2.mode & 16) !== NoMode && (workInProgress2.flags |= 134217728)) : ("function" === typeof _instance.componentDidMount && (workInProgress2.flags |= 4194308), (workInProgress2.mode & 16) !== NoMode && (workInProgress2.flags |= 134217728), workInProgress2.memoizedProps = nextProps, workInProgress2.memoizedState = oldContext), _instance.props = nextProps, _instance.state = oldContext, _instance.context = state, _instance = lane) : ("function" === typeof _instance.componentDidMount && (workInProgress2.flags |= 4194308), (workInProgress2.mode & 16) !== NoMode && (workInProgress2.flags |= 134217728), _instance = false);
        } else {
          _instance = workInProgress2.stateNode;
          cloneUpdateQueue(current2, workInProgress2);
          state = workInProgress2.memoizedProps;
          foundWillUpdateName = resolveClassComponentProps(Component, state);
          _instance.props = foundWillUpdateName;
          newApiName = workInProgress2.pendingProps;
          oldState = _instance.context;
          oldContext = Component.contextType;
          lane = emptyContextObject;
          "object" === typeof oldContext && null !== oldContext && (lane = readContext(oldContext));
          unresolvedOldProps = Component.getDerivedStateFromProps;
          (oldContext = "function" === typeof unresolvedOldProps || "function" === typeof _instance.getSnapshotBeforeUpdate) || "function" !== typeof _instance.UNSAFE_componentWillReceiveProps && "function" !== typeof _instance.componentWillReceiveProps || (state !== newApiName || oldState !== lane) && callComponentWillReceiveProps(
            workInProgress2,
            _instance,
            nextProps,
            lane
          );
          hasForceUpdate = false;
          oldState = workInProgress2.memoizedState;
          _instance.state = oldState;
          processUpdateQueue(workInProgress2, nextProps, _instance, renderLanes2);
          suspendIfUpdateReadFromEntangledAsyncAction();
          var newState = workInProgress2.memoizedState;
          state !== newApiName || oldState !== newState || hasForceUpdate || null !== current2 && null !== current2.dependencies && checkIfContextChanged(current2.dependencies) ? ("function" === typeof unresolvedOldProps && (applyDerivedStateFromProps(
            workInProgress2,
            Component,
            unresolvedOldProps,
            nextProps
          ), newState = workInProgress2.memoizedState), (foundWillUpdateName = hasForceUpdate || checkShouldComponentUpdate(
            workInProgress2,
            Component,
            foundWillUpdateName,
            nextProps,
            oldState,
            newState,
            lane
          ) || null !== current2 && null !== current2.dependencies && checkIfContextChanged(current2.dependencies)) ? (oldContext || "function" !== typeof _instance.UNSAFE_componentWillUpdate && "function" !== typeof _instance.componentWillUpdate || ("function" === typeof _instance.componentWillUpdate && _instance.componentWillUpdate(nextProps, newState, lane), "function" === typeof _instance.UNSAFE_componentWillUpdate && _instance.UNSAFE_componentWillUpdate(
            nextProps,
            newState,
            lane
          )), "function" === typeof _instance.componentDidUpdate && (workInProgress2.flags |= 4), "function" === typeof _instance.getSnapshotBeforeUpdate && (workInProgress2.flags |= 1024)) : ("function" !== typeof _instance.componentDidUpdate || state === current2.memoizedProps && oldState === current2.memoizedState || (workInProgress2.flags |= 4), "function" !== typeof _instance.getSnapshotBeforeUpdate || state === current2.memoizedProps && oldState === current2.memoizedState || (workInProgress2.flags |= 1024), workInProgress2.memoizedProps = nextProps, workInProgress2.memoizedState = newState), _instance.props = nextProps, _instance.state = newState, _instance.context = lane, _instance = foundWillUpdateName) : ("function" !== typeof _instance.componentDidUpdate || state === current2.memoizedProps && oldState === current2.memoizedState || (workInProgress2.flags |= 4), "function" !== typeof _instance.getSnapshotBeforeUpdate || state === current2.memoizedProps && oldState === current2.memoizedState || (workInProgress2.flags |= 1024), _instance = false);
        }
        lane = _instance;
        markRef(current2, workInProgress2);
        state = 0 !== (workInProgress2.flags & 128);
        if (lane || state) {
          lane = workInProgress2.stateNode;
          setCurrentFiber(workInProgress2);
          if (state && "function" !== typeof Component.getDerivedStateFromError)
            Component = null, profilerStartTime = -1;
          else {
            markComponentRenderStarted(workInProgress2);
            Component = callRenderInDEV(lane);
            if (workInProgress2.mode & 8) {
              setIsStrictModeForDevtools(true);
              try {
                callRenderInDEV(lane);
              } finally {
                setIsStrictModeForDevtools(false);
              }
            }
            markComponentRenderStopped();
          }
          workInProgress2.flags |= 1;
          null !== current2 && state ? (workInProgress2.child = reconcileChildFibers(
            workInProgress2,
            current2.child,
            null,
            renderLanes2
          ), workInProgress2.child = reconcileChildFibers(
            workInProgress2,
            null,
            Component,
            renderLanes2
          )) : reconcileChildren(current2, workInProgress2, Component, renderLanes2);
          workInProgress2.memoizedState = lane.state;
          current2 = workInProgress2.child;
        } else
          current2 = bailoutOnAlreadyFinishedWork(
            current2,
            workInProgress2,
            renderLanes2
          );
        renderLanes2 = workInProgress2.stateNode;
        _instance && renderLanes2.props !== nextProps && (didWarnAboutReassigningProps || console.error(
          "It looks like %s is reassigning its own `this.props` while rendering. This is not supported and can lead to confusing bugs.",
          getComponentNameFromFiber(workInProgress2) || "a component"
        ), didWarnAboutReassigningProps = true);
        return current2;
      }
      __name(updateClassComponent, "updateClassComponent");
      function mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2) {
        resetHydrationState();
        workInProgress2.flags |= 256;
        reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
        return workInProgress2.child;
      }
      __name(mountHostRootWithoutHydrating, "mountHostRootWithoutHydrating");
      function validateFunctionComponentInDev(workInProgress2, Component) {
        Component && Component.childContextTypes && console.error(
          "childContextTypes cannot be defined on a function component.\n  %s.childContextTypes = ...",
          Component.displayName || Component.name || "Component"
        );
        "function" === typeof Component.getDerivedStateFromProps && (workInProgress2 = getComponentNameFromType(Component) || "Unknown", didWarnAboutGetDerivedStateOnFunctionComponent[workInProgress2] || (console.error(
          "%s: Function components do not support getDerivedStateFromProps.",
          workInProgress2
        ), didWarnAboutGetDerivedStateOnFunctionComponent[workInProgress2] = true));
        "object" === typeof Component.contextType && null !== Component.contextType && (Component = getComponentNameFromType(Component) || "Unknown", didWarnAboutContextTypeOnFunctionComponent[Component] || (console.error(
          "%s: Function components do not support contextType.",
          Component
        ), didWarnAboutContextTypeOnFunctionComponent[Component] = true));
      }
      __name(validateFunctionComponentInDev, "validateFunctionComponentInDev");
      function mountSuspenseOffscreenState(renderLanes2) {
        return { baseLanes: renderLanes2, cachePool: getSuspendedCache() };
      }
      __name(mountSuspenseOffscreenState, "mountSuspenseOffscreenState");
      function getRemainingWorkInPrimaryTree(current2, primaryTreeDidDefer, renderLanes2) {
        current2 = null !== current2 ? current2.childLanes & ~renderLanes2 : 0;
        primaryTreeDidDefer && (current2 |= workInProgressDeferredLane);
        return current2;
      }
      __name(getRemainingWorkInPrimaryTree, "getRemainingWorkInPrimaryTree");
      function updateSuspenseComponent(current2, workInProgress2, renderLanes2) {
        var nextProps = workInProgress2.pendingProps;
        shouldSuspendImpl(workInProgress2) && (workInProgress2.flags |= 128);
        var showFallback = false, didSuspend = 0 !== (workInProgress2.flags & 128), JSCompiler_temp;
        (JSCompiler_temp = didSuspend) || (JSCompiler_temp = null !== current2 && null === current2.memoizedState ? false : 0 !== (suspenseStackCursor.current & ForceSuspenseFallback));
        JSCompiler_temp && (showFallback = true, workInProgress2.flags &= -129);
        JSCompiler_temp = 0 !== (workInProgress2.flags & 32);
        workInProgress2.flags &= -33;
        if (null === current2) {
          if (isHydrating) {
            showFallback ? pushPrimaryTreeSuspenseHandler(workInProgress2) : reuseSuspenseHandlerOnStack(workInProgress2);
            if (isHydrating) {
              var nextInstance = nextHydratableInstance, JSCompiler_temp$jscomp$0;
              (JSCompiler_temp$jscomp$0 = !nextInstance) || (JSCompiler_temp$jscomp$0 = canHydrateSuspenseInstance(
                nextInstance,
                rootOrSingletonContext
              ), null !== JSCompiler_temp$jscomp$0 ? (warnIfNotHydrating(), workInProgress2.memoizedState = {
                dehydrated: JSCompiler_temp$jscomp$0,
                treeContext: null !== treeContextProvider ? { id: treeContextId, overflow: treeContextOverflow } : null,
                retryLane: 536870912,
                hydrationErrors: null
              }, didSuspend = createFiber(18, null, null, NoMode), didSuspend.stateNode = JSCompiler_temp$jscomp$0, didSuspend.return = workInProgress2, workInProgress2.child = didSuspend, hydrationParentFiber = workInProgress2, nextHydratableInstance = null, JSCompiler_temp$jscomp$0 = true) : JSCompiler_temp$jscomp$0 = false, JSCompiler_temp$jscomp$0 = !JSCompiler_temp$jscomp$0);
              JSCompiler_temp$jscomp$0 && (warnNonHydratedInstance(workInProgress2, nextInstance), throwOnHydrationMismatch(workInProgress2));
            }
            nextInstance = workInProgress2.memoizedState;
            if (null !== nextInstance && (nextInstance = nextInstance.dehydrated, null !== nextInstance))
              return isSuspenseInstanceFallback(nextInstance) ? workInProgress2.lanes = 32 : workInProgress2.lanes = 536870912, null;
            popSuspenseHandler(workInProgress2);
          }
          nextInstance = nextProps.children;
          nextProps = nextProps.fallback;
          if (showFallback)
            return reuseSuspenseHandlerOnStack(workInProgress2), showFallback = workInProgress2.mode, nextInstance = mountWorkInProgressOffscreenFiber(
              { mode: "hidden", children: nextInstance },
              showFallback
            ), nextProps = createFiberFromFragment(
              nextProps,
              showFallback,
              renderLanes2,
              null
            ), nextInstance.return = workInProgress2, nextProps.return = workInProgress2, nextInstance.sibling = nextProps, workInProgress2.child = nextInstance, showFallback = workInProgress2.child, showFallback.memoizedState = mountSuspenseOffscreenState(renderLanes2), showFallback.childLanes = getRemainingWorkInPrimaryTree(
              current2,
              JSCompiler_temp,
              renderLanes2
            ), workInProgress2.memoizedState = SUSPENDED_MARKER, nextProps;
          pushPrimaryTreeSuspenseHandler(workInProgress2);
          return mountSuspensePrimaryChildren(workInProgress2, nextInstance);
        }
        JSCompiler_temp$jscomp$0 = current2.memoizedState;
        if (null !== JSCompiler_temp$jscomp$0 && (nextInstance = JSCompiler_temp$jscomp$0.dehydrated, null !== nextInstance)) {
          if (didSuspend)
            workInProgress2.flags & 256 ? (pushPrimaryTreeSuspenseHandler(workInProgress2), workInProgress2.flags &= -257, workInProgress2 = retrySuspenseComponentWithoutHydrating(
              current2,
              workInProgress2,
              renderLanes2
            )) : null !== workInProgress2.memoizedState ? (reuseSuspenseHandlerOnStack(workInProgress2), workInProgress2.child = current2.child, workInProgress2.flags |= 128, workInProgress2 = null) : (reuseSuspenseHandlerOnStack(workInProgress2), showFallback = nextProps.fallback, nextInstance = workInProgress2.mode, nextProps = mountWorkInProgressOffscreenFiber(
              { mode: "visible", children: nextProps.children },
              nextInstance
            ), showFallback = createFiberFromFragment(
              showFallback,
              nextInstance,
              renderLanes2,
              null
            ), showFallback.flags |= 2, nextProps.return = workInProgress2, showFallback.return = workInProgress2, nextProps.sibling = showFallback, workInProgress2.child = nextProps, reconcileChildFibers(
              workInProgress2,
              current2.child,
              null,
              renderLanes2
            ), nextProps = workInProgress2.child, nextProps.memoizedState = mountSuspenseOffscreenState(renderLanes2), nextProps.childLanes = getRemainingWorkInPrimaryTree(
              current2,
              JSCompiler_temp,
              renderLanes2
            ), workInProgress2.memoizedState = SUSPENDED_MARKER, workInProgress2 = showFallback);
          else if (pushPrimaryTreeSuspenseHandler(workInProgress2), isHydrating && console.error(
            "We should not be hydrating here. This is a bug in React. Please file a bug."
          ), isSuspenseInstanceFallback(nextInstance))
            nextInstance = getSuspenseInstanceFallbackErrorDetails(nextInstance), JSCompiler_temp = nextInstance.digest, showFallback = nextInstance.message, nextProps = nextInstance.stack, nextInstance = nextInstance.componentStack, showFallback = showFallback ? Error(showFallback) : Error(
              "The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering."
            ), showFallback.stack = nextProps || "", showFallback.digest = JSCompiler_temp, JSCompiler_temp = void 0 === nextInstance ? null : nextInstance, nextProps = {
              value: showFallback,
              source: null,
              stack: JSCompiler_temp
            }, "string" === typeof JSCompiler_temp && CapturedStacks.set(showFallback, nextProps), queueHydrationError(nextProps), workInProgress2 = retrySuspenseComponentWithoutHydrating(
              current2,
              workInProgress2,
              renderLanes2
            );
          else if (didReceiveUpdate || propagateParentContextChanges(
            current2,
            workInProgress2,
            renderLanes2,
            false
          ), JSCompiler_temp = 0 !== (renderLanes2 & current2.childLanes), didReceiveUpdate || JSCompiler_temp) {
            JSCompiler_temp = workInProgressRoot;
            if (null !== JSCompiler_temp && (nextProps = renderLanes2 & -renderLanes2, nextProps = 0 !== (nextProps & 42) ? 1 : getBumpedLaneForHydrationByLane(nextProps), nextProps = 0 !== (nextProps & (JSCompiler_temp.suspendedLanes | renderLanes2)) ? 0 : nextProps, 0 !== nextProps && nextProps !== JSCompiler_temp$jscomp$0.retryLane))
              throw JSCompiler_temp$jscomp$0.retryLane = nextProps, enqueueConcurrentRenderForLane(current2, nextProps), scheduleUpdateOnFiber(JSCompiler_temp, current2, nextProps), SelectiveHydrationException;
            isSuspenseInstancePending(nextInstance) || renderDidSuspendDelayIfPossible();
            workInProgress2 = retrySuspenseComponentWithoutHydrating(
              current2,
              workInProgress2,
              renderLanes2
            );
          } else
            isSuspenseInstancePending(nextInstance) ? (workInProgress2.flags |= 192, workInProgress2.child = current2.child, workInProgress2 = null) : (current2 = JSCompiler_temp$jscomp$0.treeContext, supportsHydration && (nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(nextInstance), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, didSuspendOrErrorDEV = false, hydrationDiffRootDEV = null, rootOrSingletonContext = false, null !== current2 && (warnIfNotHydrating(), idStack[idStackIndex++] = treeContextId, idStack[idStackIndex++] = treeContextOverflow, idStack[idStackIndex++] = treeContextProvider, treeContextId = current2.id, treeContextOverflow = current2.overflow, treeContextProvider = workInProgress2)), workInProgress2 = mountSuspensePrimaryChildren(
              workInProgress2,
              nextProps.children
            ), workInProgress2.flags |= 4096);
          return workInProgress2;
        }
        if (showFallback)
          return reuseSuspenseHandlerOnStack(workInProgress2), showFallback = nextProps.fallback, nextInstance = workInProgress2.mode, JSCompiler_temp$jscomp$0 = current2.child, didSuspend = JSCompiler_temp$jscomp$0.sibling, nextProps = createWorkInProgress(JSCompiler_temp$jscomp$0, {
            mode: "hidden",
            children: nextProps.children
          }), nextProps.subtreeFlags = JSCompiler_temp$jscomp$0.subtreeFlags & 65011712, null !== didSuspend ? showFallback = createWorkInProgress(didSuspend, showFallback) : (showFallback = createFiberFromFragment(
            showFallback,
            nextInstance,
            renderLanes2,
            null
          ), showFallback.flags |= 2), showFallback.return = workInProgress2, nextProps.return = workInProgress2, nextProps.sibling = showFallback, workInProgress2.child = nextProps, nextProps = showFallback, showFallback = workInProgress2.child, nextInstance = current2.child.memoizedState, null === nextInstance ? nextInstance = mountSuspenseOffscreenState(renderLanes2) : (JSCompiler_temp$jscomp$0 = nextInstance.cachePool, null !== JSCompiler_temp$jscomp$0 ? (didSuspend = isPrimaryRenderer ? CacheContext._currentValue : CacheContext._currentValue2, JSCompiler_temp$jscomp$0 = JSCompiler_temp$jscomp$0.parent !== didSuspend ? { parent: didSuspend, pool: didSuspend } : JSCompiler_temp$jscomp$0) : JSCompiler_temp$jscomp$0 = getSuspendedCache(), nextInstance = {
            baseLanes: nextInstance.baseLanes | renderLanes2,
            cachePool: JSCompiler_temp$jscomp$0
          }), showFallback.memoizedState = nextInstance, showFallback.childLanes = getRemainingWorkInPrimaryTree(
            current2,
            JSCompiler_temp,
            renderLanes2
          ), workInProgress2.memoizedState = SUSPENDED_MARKER, nextProps;
        pushPrimaryTreeSuspenseHandler(workInProgress2);
        renderLanes2 = current2.child;
        current2 = renderLanes2.sibling;
        renderLanes2 = createWorkInProgress(renderLanes2, {
          mode: "visible",
          children: nextProps.children
        });
        renderLanes2.return = workInProgress2;
        renderLanes2.sibling = null;
        null !== current2 && (JSCompiler_temp = workInProgress2.deletions, null === JSCompiler_temp ? (workInProgress2.deletions = [current2], workInProgress2.flags |= 16) : JSCompiler_temp.push(current2));
        workInProgress2.child = renderLanes2;
        workInProgress2.memoizedState = null;
        return renderLanes2;
      }
      __name(updateSuspenseComponent, "updateSuspenseComponent");
      function mountSuspensePrimaryChildren(workInProgress2, primaryChildren) {
        primaryChildren = mountWorkInProgressOffscreenFiber(
          { mode: "visible", children: primaryChildren },
          workInProgress2.mode
        );
        primaryChildren.return = workInProgress2;
        return workInProgress2.child = primaryChildren;
      }
      __name(mountSuspensePrimaryChildren, "mountSuspensePrimaryChildren");
      function mountWorkInProgressOffscreenFiber(offscreenProps, mode) {
        offscreenProps = createFiber(22, offscreenProps, null, mode);
        offscreenProps.lanes = 0;
        offscreenProps.stateNode = {
          _visibility: 1,
          _pendingMarkers: null,
          _retryCache: null,
          _transitions: null
        };
        return offscreenProps;
      }
      __name(mountWorkInProgressOffscreenFiber, "mountWorkInProgressOffscreenFiber");
      function retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2) {
        reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2);
        current2 = mountSuspensePrimaryChildren(
          workInProgress2,
          workInProgress2.pendingProps.children
        );
        current2.flags |= 2;
        workInProgress2.memoizedState = null;
        return current2;
      }
      __name(retrySuspenseComponentWithoutHydrating, "retrySuspenseComponentWithoutHydrating");
      function scheduleSuspenseWorkOnFiber(fiber, renderLanes2, propagationRoot) {
        fiber.lanes |= renderLanes2;
        var alternate = fiber.alternate;
        null !== alternate && (alternate.lanes |= renderLanes2);
        scheduleContextWorkOnParentPath(
          fiber.return,
          renderLanes2,
          propagationRoot
        );
      }
      __name(scheduleSuspenseWorkOnFiber, "scheduleSuspenseWorkOnFiber");
      function validateSuspenseListNestedChild(childSlot, index) {
        var isAnArray = isArrayImpl(childSlot);
        childSlot = !isAnArray && "function" === typeof getIteratorFn(childSlot);
        return isAnArray || childSlot ? (isAnArray = isAnArray ? "array" : "iterable", console.error(
          "A nested %s was passed to row #%s in <SuspenseList />. Wrap it in an additional SuspenseList to configure its revealOrder: <SuspenseList revealOrder=...> ... <SuspenseList revealOrder=...>{%s}</SuspenseList> ... </SuspenseList>",
          isAnArray,
          index,
          isAnArray
        ), false) : true;
      }
      __name(validateSuspenseListNestedChild, "validateSuspenseListNestedChild");
      function initSuspenseListRenderState(workInProgress2, isBackwards, tail, lastContentRow, tailMode) {
        var renderState = workInProgress2.memoizedState;
        null === renderState ? workInProgress2.memoizedState = {
          isBackwards,
          rendering: null,
          renderingStartTime: 0,
          last: lastContentRow,
          tail,
          tailMode
        } : (renderState.isBackwards = isBackwards, renderState.rendering = null, renderState.renderingStartTime = 0, renderState.last = lastContentRow, renderState.tail = tail, renderState.tailMode = tailMode);
      }
      __name(initSuspenseListRenderState, "initSuspenseListRenderState");
      function updateSuspenseListComponent(current2, workInProgress2, renderLanes2) {
        var nextProps = workInProgress2.pendingProps, revealOrder = nextProps.revealOrder, tailMode = nextProps.tail;
        nextProps = nextProps.children;
        if (void 0 !== revealOrder && "forwards" !== revealOrder && "backwards" !== revealOrder && "together" !== revealOrder && !didWarnAboutRevealOrder[revealOrder])
          if (didWarnAboutRevealOrder[revealOrder] = true, "string" === typeof revealOrder)
            switch (revealOrder.toLowerCase()) {
              case "together":
              case "forwards":
              case "backwards":
                console.error(
                  '"%s" is not a valid value for revealOrder on <SuspenseList />. Use lowercase "%s" instead.',
                  revealOrder,
                  revealOrder.toLowerCase()
                );
                break;
              case "forward":
              case "backward":
                console.error(
                  '"%s" is not a valid value for revealOrder on <SuspenseList />. React uses the -s suffix in the spelling. Use "%ss" instead.',
                  revealOrder,
                  revealOrder.toLowerCase()
                );
                break;
              default:
                console.error(
                  '"%s" is not a supported revealOrder on <SuspenseList />. Did you mean "together", "forwards" or "backwards"?',
                  revealOrder
                );
            }
          else
            console.error(
              '%s is not a supported value for revealOrder on <SuspenseList />. Did you mean "together", "forwards" or "backwards"?',
              revealOrder
            );
        void 0 === tailMode || didWarnAboutTailOptions[tailMode] || ("collapsed" !== tailMode && "hidden" !== tailMode ? (didWarnAboutTailOptions[tailMode] = true, console.error(
          '"%s" is not a supported value for tail on <SuspenseList />. Did you mean "collapsed" or "hidden"?',
          tailMode
        )) : "forwards" !== revealOrder && "backwards" !== revealOrder && (didWarnAboutTailOptions[tailMode] = true, console.error(
          '<SuspenseList tail="%s" /> is only valid if revealOrder is "forwards" or "backwards". Did you mean to specify revealOrder="forwards"?',
          tailMode
        )));
        a: if (("forwards" === revealOrder || "backwards" === revealOrder) && void 0 !== nextProps && null !== nextProps && false !== nextProps)
          if (isArrayImpl(nextProps))
            for (var i = 0; i < nextProps.length; i++) {
              if (!validateSuspenseListNestedChild(nextProps[i], i)) break a;
            }
          else if (i = getIteratorFn(nextProps), "function" === typeof i) {
            if (i = i.call(nextProps))
              for (var step = i.next(), _i = 0; !step.done; step = i.next()) {
                if (!validateSuspenseListNestedChild(step.value, _i)) break a;
                _i++;
              }
          } else
            console.error(
              'A single row was passed to a <SuspenseList revealOrder="%s" />. This is not useful since it needs multiple rows. Did you mean to pass multiple children or an array?',
              revealOrder
            );
        reconcileChildren(current2, workInProgress2, nextProps, renderLanes2);
        nextProps = suspenseStackCursor.current;
        if (0 !== (nextProps & ForceSuspenseFallback))
          nextProps = nextProps & SubtreeSuspenseContextMask | ForceSuspenseFallback, workInProgress2.flags |= 128;
        else {
          if (null !== current2 && 0 !== (current2.flags & 128))
            a: for (current2 = workInProgress2.child; null !== current2; ) {
              if (13 === current2.tag)
                null !== current2.memoizedState && scheduleSuspenseWorkOnFiber(
                  current2,
                  renderLanes2,
                  workInProgress2
                );
              else if (19 === current2.tag)
                scheduleSuspenseWorkOnFiber(current2, renderLanes2, workInProgress2);
              else if (null !== current2.child) {
                current2.child.return = current2;
                current2 = current2.child;
                continue;
              }
              if (current2 === workInProgress2) break a;
              for (; null === current2.sibling; ) {
                if (null === current2.return || current2.return === workInProgress2)
                  break a;
                current2 = current2.return;
              }
              current2.sibling.return = current2.return;
              current2 = current2.sibling;
            }
          nextProps &= SubtreeSuspenseContextMask;
        }
        push2(suspenseStackCursor, nextProps, workInProgress2);
        switch (revealOrder) {
          case "forwards":
            renderLanes2 = workInProgress2.child;
            for (revealOrder = null; null !== renderLanes2; )
              current2 = renderLanes2.alternate, null !== current2 && null === findFirstSuspended(current2) && (revealOrder = renderLanes2), renderLanes2 = renderLanes2.sibling;
            renderLanes2 = revealOrder;
            null === renderLanes2 ? (revealOrder = workInProgress2.child, workInProgress2.child = null) : (revealOrder = renderLanes2.sibling, renderLanes2.sibling = null);
            initSuspenseListRenderState(
              workInProgress2,
              false,
              revealOrder,
              renderLanes2,
              tailMode
            );
            break;
          case "backwards":
            renderLanes2 = null;
            revealOrder = workInProgress2.child;
            for (workInProgress2.child = null; null !== revealOrder; ) {
              current2 = revealOrder.alternate;
              if (null !== current2 && null === findFirstSuspended(current2)) {
                workInProgress2.child = revealOrder;
                break;
              }
              current2 = revealOrder.sibling;
              revealOrder.sibling = renderLanes2;
              renderLanes2 = revealOrder;
              revealOrder = current2;
            }
            initSuspenseListRenderState(
              workInProgress2,
              true,
              renderLanes2,
              null,
              tailMode
            );
            break;
          case "together":
            initSuspenseListRenderState(workInProgress2, false, null, null, void 0);
            break;
          default:
            workInProgress2.memoizedState = null;
        }
        return workInProgress2.child;
      }
      __name(updateSuspenseListComponent, "updateSuspenseListComponent");
      function bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2) {
        null !== current2 && (workInProgress2.dependencies = current2.dependencies);
        profilerStartTime = -1;
        workInProgressRootSkippedLanes |= workInProgress2.lanes;
        if (0 === (renderLanes2 & workInProgress2.childLanes))
          if (null !== current2) {
            if (propagateParentContextChanges(
              current2,
              workInProgress2,
              renderLanes2,
              false
            ), 0 === (renderLanes2 & workInProgress2.childLanes))
              return null;
          } else return null;
        if (null !== current2 && workInProgress2.child !== current2.child)
          throw Error("Resuming work not yet implemented.");
        if (null !== workInProgress2.child) {
          current2 = workInProgress2.child;
          renderLanes2 = createWorkInProgress(current2, current2.pendingProps);
          workInProgress2.child = renderLanes2;
          for (renderLanes2.return = workInProgress2; null !== current2.sibling; )
            current2 = current2.sibling, renderLanes2 = renderLanes2.sibling = createWorkInProgress(current2, current2.pendingProps), renderLanes2.return = workInProgress2;
          renderLanes2.sibling = null;
        }
        return workInProgress2.child;
      }
      __name(bailoutOnAlreadyFinishedWork, "bailoutOnAlreadyFinishedWork");
      function checkScheduledUpdateOrContext(current2, renderLanes2) {
        if (0 !== (current2.lanes & renderLanes2)) return true;
        current2 = current2.dependencies;
        return null !== current2 && checkIfContextChanged(current2) ? true : false;
      }
      __name(checkScheduledUpdateOrContext, "checkScheduledUpdateOrContext");
      function attemptEarlyBailoutIfNoScheduledUpdate(current2, workInProgress2, renderLanes2) {
        switch (workInProgress2.tag) {
          case 3:
            pushHostContainer(
              workInProgress2,
              workInProgress2.stateNode.containerInfo
            );
            pushProvider(
              workInProgress2,
              CacheContext,
              current2.memoizedState.cache
            );
            resetHydrationState();
            break;
          case 27:
          case 5:
            pushHostContext(workInProgress2);
            break;
          case 4:
            pushHostContainer(
              workInProgress2,
              workInProgress2.stateNode.containerInfo
            );
            break;
          case 10:
            pushProvider(
              workInProgress2,
              workInProgress2.type,
              workInProgress2.memoizedProps.value
            );
            break;
          case 12:
            0 !== (renderLanes2 & workInProgress2.childLanes) && (workInProgress2.flags |= 4);
            workInProgress2.flags |= 2048;
            var stateNode = workInProgress2.stateNode;
            stateNode.effectDuration = -0;
            stateNode.passiveEffectDuration = -0;
            break;
          case 13:
            stateNode = workInProgress2.memoizedState;
            if (null !== stateNode) {
              if (null !== stateNode.dehydrated)
                return pushPrimaryTreeSuspenseHandler(workInProgress2), workInProgress2.flags |= 128, null;
              if (0 !== (renderLanes2 & workInProgress2.child.childLanes))
                return updateSuspenseComponent(
                  current2,
                  workInProgress2,
                  renderLanes2
                );
              pushPrimaryTreeSuspenseHandler(workInProgress2);
              current2 = bailoutOnAlreadyFinishedWork(
                current2,
                workInProgress2,
                renderLanes2
              );
              return null !== current2 ? current2.sibling : null;
            }
            pushPrimaryTreeSuspenseHandler(workInProgress2);
            break;
          case 19:
            var didSuspendBefore = 0 !== (current2.flags & 128);
            stateNode = 0 !== (renderLanes2 & workInProgress2.childLanes);
            stateNode || (propagateParentContextChanges(
              current2,
              workInProgress2,
              renderLanes2,
              false
            ), stateNode = 0 !== (renderLanes2 & workInProgress2.childLanes));
            if (didSuspendBefore) {
              if (stateNode)
                return updateSuspenseListComponent(
                  current2,
                  workInProgress2,
                  renderLanes2
                );
              workInProgress2.flags |= 128;
            }
            didSuspendBefore = workInProgress2.memoizedState;
            null !== didSuspendBefore && (didSuspendBefore.rendering = null, didSuspendBefore.tail = null, didSuspendBefore.lastEffect = null);
            push2(
              suspenseStackCursor,
              suspenseStackCursor.current,
              workInProgress2
            );
            if (stateNode) break;
            else return null;
          case 22:
          case 23:
            return workInProgress2.lanes = 0, updateOffscreenComponent(current2, workInProgress2, renderLanes2);
          case 24:
            pushProvider(
              workInProgress2,
              CacheContext,
              current2.memoizedState.cache
            );
        }
        return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
      }
      __name(attemptEarlyBailoutIfNoScheduledUpdate, "attemptEarlyBailoutIfNoScheduledUpdate");
      function beginWork(current2, workInProgress2, renderLanes2) {
        if (workInProgress2._debugNeedsRemount && null !== current2) {
          renderLanes2 = createFiberFromTypeAndProps(
            workInProgress2.type,
            workInProgress2.key,
            workInProgress2.pendingProps,
            workInProgress2._debugOwner || null,
            workInProgress2.mode,
            workInProgress2.lanes
          );
          renderLanes2._debugStack = workInProgress2._debugStack;
          renderLanes2._debugTask = workInProgress2._debugTask;
          var returnFiber = workInProgress2.return;
          if (null === returnFiber) throw Error("Cannot swap the root fiber.");
          current2.alternate = null;
          workInProgress2.alternate = null;
          renderLanes2.index = workInProgress2.index;
          renderLanes2.sibling = workInProgress2.sibling;
          renderLanes2.return = workInProgress2.return;
          renderLanes2.ref = workInProgress2.ref;
          renderLanes2._debugInfo = workInProgress2._debugInfo;
          if (workInProgress2 === returnFiber.child)
            returnFiber.child = renderLanes2;
          else {
            var prevSibling = returnFiber.child;
            if (null === prevSibling)
              throw Error("Expected parent to have a child.");
            for (; prevSibling.sibling !== workInProgress2; )
              if (prevSibling = prevSibling.sibling, null === prevSibling)
                throw Error("Expected to find the previous sibling.");
            prevSibling.sibling = renderLanes2;
          }
          workInProgress2 = returnFiber.deletions;
          null === workInProgress2 ? (returnFiber.deletions = [current2], returnFiber.flags |= 16) : workInProgress2.push(current2);
          renderLanes2.flags |= 2;
          return renderLanes2;
        }
        if (null !== current2)
          if (current2.memoizedProps !== workInProgress2.pendingProps || workInProgress2.type !== current2.type)
            didReceiveUpdate = true;
          else {
            if (!checkScheduledUpdateOrContext(current2, renderLanes2) && 0 === (workInProgress2.flags & 128))
              return didReceiveUpdate = false, attemptEarlyBailoutIfNoScheduledUpdate(
                current2,
                workInProgress2,
                renderLanes2
              );
            didReceiveUpdate = 0 !== (current2.flags & 131072) ? true : false;
          }
        else {
          didReceiveUpdate = false;
          if (returnFiber = isHydrating)
            warnIfNotHydrating(), returnFiber = 0 !== (workInProgress2.flags & 1048576);
          returnFiber && (returnFiber = workInProgress2.index, warnIfNotHydrating(), pushTreeId(workInProgress2, treeForkCount, returnFiber));
        }
        workInProgress2.lanes = 0;
        switch (workInProgress2.tag) {
          case 16:
            a: if (returnFiber = workInProgress2.pendingProps, current2 = callLazyInitInDEV(workInProgress2.elementType), workInProgress2.type = current2, "function" === typeof current2)
              shouldConstruct(current2) ? (returnFiber = resolveClassComponentProps(
                current2,
                returnFiber
              ), workInProgress2.tag = 1, workInProgress2.type = current2 = resolveFunctionForHotReloading(current2), workInProgress2 = updateClassComponent(
                null,
                workInProgress2,
                current2,
                returnFiber,
                renderLanes2
              )) : (workInProgress2.tag = 0, validateFunctionComponentInDev(workInProgress2, current2), workInProgress2.type = current2 = resolveFunctionForHotReloading(current2), workInProgress2 = updateFunctionComponent(
                null,
                workInProgress2,
                current2,
                returnFiber,
                renderLanes2
              ));
            else {
              if (void 0 !== current2 && null !== current2) {
                if (prevSibling = current2.$$typeof, prevSibling === REACT_FORWARD_REF_TYPE) {
                  workInProgress2.tag = 11;
                  workInProgress2.type = current2 = resolveForwardRefForHotReloading(current2);
                  workInProgress2 = updateForwardRef(
                    null,
                    workInProgress2,
                    current2,
                    returnFiber,
                    renderLanes2
                  );
                  break a;
                } else if (prevSibling === REACT_MEMO_TYPE) {
                  workInProgress2.tag = 14;
                  workInProgress2 = updateMemoComponent(
                    null,
                    workInProgress2,
                    current2,
                    returnFiber,
                    renderLanes2
                  );
                  break a;
                }
              }
              workInProgress2 = "";
              null !== current2 && "object" === typeof current2 && current2.$$typeof === REACT_LAZY_TYPE && (workInProgress2 = " Did you wrap a component in React.lazy() more than once?");
              current2 = getComponentNameFromType(current2) || current2;
              throw Error(
                "Element type is invalid. Received a promise that resolves to: " + current2 + ". Lazy element type must resolve to a class or function." + workInProgress2
              );
            }
            return workInProgress2;
          case 0:
            return updateFunctionComponent(
              current2,
              workInProgress2,
              workInProgress2.type,
              workInProgress2.pendingProps,
              renderLanes2
            );
          case 1:
            return returnFiber = workInProgress2.type, prevSibling = resolveClassComponentProps(
              returnFiber,
              workInProgress2.pendingProps
            ), updateClassComponent(
              current2,
              workInProgress2,
              returnFiber,
              prevSibling,
              renderLanes2
            );
          case 3:
            a: {
              pushHostContainer(
                workInProgress2,
                workInProgress2.stateNode.containerInfo
              );
              if (null === current2)
                throw Error(
                  "Should have a current fiber. This is a bug in React."
                );
              var nextProps = workInProgress2.pendingProps;
              prevSibling = workInProgress2.memoizedState;
              returnFiber = prevSibling.element;
              cloneUpdateQueue(current2, workInProgress2);
              processUpdateQueue(workInProgress2, nextProps, null, renderLanes2);
              var nextState = workInProgress2.memoizedState;
              nextProps = nextState.cache;
              pushProvider(workInProgress2, CacheContext, nextProps);
              nextProps !== prevSibling.cache && propagateContextChanges(
                workInProgress2,
                [CacheContext],
                renderLanes2,
                true
              );
              suspendIfUpdateReadFromEntangledAsyncAction();
              nextProps = nextState.element;
              if (supportsHydration && prevSibling.isDehydrated)
                if (prevSibling = {
                  element: nextProps,
                  isDehydrated: false,
                  cache: nextState.cache
                }, workInProgress2.updateQueue.baseState = prevSibling, workInProgress2.memoizedState = prevSibling, workInProgress2.flags & 256) {
                  workInProgress2 = mountHostRootWithoutHydrating(
                    current2,
                    workInProgress2,
                    nextProps,
                    renderLanes2
                  );
                  break a;
                } else if (nextProps !== returnFiber) {
                  returnFiber = createCapturedValueAtFiber(
                    Error(
                      "This root received an early update, before anything was able hydrate. Switched the entire root to client rendering."
                    ),
                    workInProgress2
                  );
                  queueHydrationError(returnFiber);
                  workInProgress2 = mountHostRootWithoutHydrating(
                    current2,
                    workInProgress2,
                    nextProps,
                    renderLanes2
                  );
                  break a;
                } else
                  for (supportsHydration && (nextHydratableInstance = getFirstHydratableChildWithinContainer(
                    workInProgress2.stateNode.containerInfo
                  ), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, didSuspendOrErrorDEV = false, hydrationDiffRootDEV = null, rootOrSingletonContext = true), current2 = mountChildFibers(
                    workInProgress2,
                    null,
                    nextProps,
                    renderLanes2
                  ), workInProgress2.child = current2; current2; )
                    current2.flags = current2.flags & -3 | 4096, current2 = current2.sibling;
              else {
                resetHydrationState();
                if (nextProps === returnFiber) {
                  workInProgress2 = bailoutOnAlreadyFinishedWork(
                    current2,
                    workInProgress2,
                    renderLanes2
                  );
                  break a;
                }
                reconcileChildren(
                  current2,
                  workInProgress2,
                  nextProps,
                  renderLanes2
                );
              }
              workInProgress2 = workInProgress2.child;
            }
            return workInProgress2;
          case 26:
            if (supportsResources)
              return markRef(current2, workInProgress2), null === current2 ? (current2 = getResource(
                workInProgress2.type,
                null,
                workInProgress2.pendingProps,
                null
              )) ? workInProgress2.memoizedState = current2 : isHydrating || (workInProgress2.stateNode = createHoistableInstance(
                workInProgress2.type,
                workInProgress2.pendingProps,
                requiredContext(rootInstanceStackCursor.current),
                workInProgress2
              )) : workInProgress2.memoizedState = getResource(
                workInProgress2.type,
                current2.memoizedProps,
                workInProgress2.pendingProps,
                current2.memoizedState
              ), null;
          case 27:
            if (supportsSingletons)
              return pushHostContext(workInProgress2), null === current2 && supportsSingletons && isHydrating && (prevSibling = requiredContext(
                rootInstanceStackCursor.current
              ), returnFiber = getHostContext(), prevSibling = workInProgress2.stateNode = resolveSingletonInstance(
                workInProgress2.type,
                workInProgress2.pendingProps,
                prevSibling,
                returnFiber,
                false
              ), didSuspendOrErrorDEV || (returnFiber = diffHydratedPropsForDevWarnings(
                prevSibling,
                workInProgress2.type,
                workInProgress2.pendingProps,
                returnFiber
              ), null !== returnFiber && (buildHydrationDiffNode(workInProgress2, 0).serverProps = returnFiber)), hydrationParentFiber = workInProgress2, rootOrSingletonContext = true, nextHydratableInstance = getFirstHydratableChildWithinSingleton(
                workInProgress2.type,
                prevSibling,
                nextHydratableInstance
              )), reconcileChildren(
                current2,
                workInProgress2,
                workInProgress2.pendingProps.children,
                renderLanes2
              ), markRef(current2, workInProgress2), null === current2 && (workInProgress2.flags |= 4194304), workInProgress2.child;
          case 5:
            return null === current2 && isHydrating && (nextProps = getHostContext(), returnFiber = validateHydratableInstance(
              workInProgress2.type,
              workInProgress2.pendingProps,
              nextProps
            ), prevSibling = nextHydratableInstance, (nextState = !prevSibling) || (nextState = canHydrateInstance(
              prevSibling,
              workInProgress2.type,
              workInProgress2.pendingProps,
              rootOrSingletonContext
            ), null !== nextState ? (workInProgress2.stateNode = nextState, didSuspendOrErrorDEV || (nextProps = diffHydratedPropsForDevWarnings(
              nextState,
              workInProgress2.type,
              workInProgress2.pendingProps,
              nextProps
            ), null !== nextProps && (buildHydrationDiffNode(workInProgress2, 0).serverProps = nextProps)), hydrationParentFiber = workInProgress2, nextHydratableInstance = getFirstHydratableChild(nextState), rootOrSingletonContext = false, nextProps = true) : nextProps = false, nextState = !nextProps), nextState && (returnFiber && warnNonHydratedInstance(workInProgress2, prevSibling), throwOnHydrationMismatch(workInProgress2))), pushHostContext(workInProgress2), prevSibling = workInProgress2.type, nextProps = workInProgress2.pendingProps, nextState = null !== current2 ? current2.memoizedProps : null, returnFiber = nextProps.children, shouldSetTextContent(prevSibling, nextProps) ? returnFiber = null : null !== nextState && shouldSetTextContent(prevSibling, nextState) && (workInProgress2.flags |= 32), null !== workInProgress2.memoizedState && (prevSibling = renderWithHooks(
              current2,
              workInProgress2,
              TransitionAwareHostComponent,
              null,
              null,
              renderLanes2
            ), isPrimaryRenderer ? HostTransitionContext._currentValue = prevSibling : HostTransitionContext._currentValue2 = prevSibling), markRef(current2, workInProgress2), reconcileChildren(
              current2,
              workInProgress2,
              returnFiber,
              renderLanes2
            ), workInProgress2.child;
          case 6:
            return null === current2 && isHydrating && (current2 = workInProgress2.pendingProps, renderLanes2 = getHostContext(), current2 = validateHydratableTextInstance(current2, renderLanes2), renderLanes2 = nextHydratableInstance, (returnFiber = !renderLanes2) || (returnFiber = canHydrateTextInstance(
              renderLanes2,
              workInProgress2.pendingProps,
              rootOrSingletonContext
            ), null !== returnFiber ? (workInProgress2.stateNode = returnFiber, hydrationParentFiber = workInProgress2, nextHydratableInstance = null, returnFiber = true) : returnFiber = false, returnFiber = !returnFiber), returnFiber && (current2 && warnNonHydratedInstance(workInProgress2, renderLanes2), throwOnHydrationMismatch(workInProgress2))), null;
          case 13:
            return updateSuspenseComponent(current2, workInProgress2, renderLanes2);
          case 4:
            return pushHostContainer(
              workInProgress2,
              workInProgress2.stateNode.containerInfo
            ), returnFiber = workInProgress2.pendingProps, null === current2 ? workInProgress2.child = reconcileChildFibers(
              workInProgress2,
              null,
              returnFiber,
              renderLanes2
            ) : reconcileChildren(
              current2,
              workInProgress2,
              returnFiber,
              renderLanes2
            ), workInProgress2.child;
          case 11:
            return updateForwardRef(
              current2,
              workInProgress2,
              workInProgress2.type,
              workInProgress2.pendingProps,
              renderLanes2
            );
          case 7:
            return reconcileChildren(
              current2,
              workInProgress2,
              workInProgress2.pendingProps,
              renderLanes2
            ), workInProgress2.child;
          case 8:
            return reconcileChildren(
              current2,
              workInProgress2,
              workInProgress2.pendingProps.children,
              renderLanes2
            ), workInProgress2.child;
          case 12:
            return workInProgress2.flags |= 4, workInProgress2.flags |= 2048, returnFiber = workInProgress2.stateNode, returnFiber.effectDuration = -0, returnFiber.passiveEffectDuration = -0, reconcileChildren(
              current2,
              workInProgress2,
              workInProgress2.pendingProps.children,
              renderLanes2
            ), workInProgress2.child;
          case 10:
            return returnFiber = workInProgress2.type, prevSibling = workInProgress2.pendingProps, nextProps = prevSibling.value, "value" in prevSibling || hasWarnedAboutUsingNoValuePropOnContextProvider || (hasWarnedAboutUsingNoValuePropOnContextProvider = true, console.error(
              "The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?"
            )), pushProvider(workInProgress2, returnFiber, nextProps), reconcileChildren(
              current2,
              workInProgress2,
              prevSibling.children,
              renderLanes2
            ), workInProgress2.child;
          case 9:
            return prevSibling = workInProgress2.type._context, returnFiber = workInProgress2.pendingProps.children, "function" !== typeof returnFiber && console.error(
              "A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it."
            ), prepareToReadContext(workInProgress2), prevSibling = readContext(prevSibling), markComponentRenderStarted(workInProgress2), returnFiber = callComponentInDEV(
              returnFiber,
              prevSibling,
              void 0
            ), markComponentRenderStopped(), workInProgress2.flags |= 1, reconcileChildren(
              current2,
              workInProgress2,
              returnFiber,
              renderLanes2
            ), workInProgress2.child;
          case 14:
            return updateMemoComponent(
              current2,
              workInProgress2,
              workInProgress2.type,
              workInProgress2.pendingProps,
              renderLanes2
            );
          case 15:
            return updateSimpleMemoComponent(
              current2,
              workInProgress2,
              workInProgress2.type,
              workInProgress2.pendingProps,
              renderLanes2
            );
          case 19:
            return updateSuspenseListComponent(
              current2,
              workInProgress2,
              renderLanes2
            );
          case 31:
            return returnFiber = workInProgress2.pendingProps, renderLanes2 = workInProgress2.mode, returnFiber = {
              mode: returnFiber.mode,
              children: returnFiber.children
            }, null === current2 ? (current2 = mountWorkInProgressOffscreenFiber(
              returnFiber,
              renderLanes2
            ), current2.ref = workInProgress2.ref, workInProgress2.child = current2, current2.return = workInProgress2, workInProgress2 = current2) : (current2 = createWorkInProgress(current2.child, returnFiber), current2.ref = workInProgress2.ref, workInProgress2.child = current2, current2.return = workInProgress2, workInProgress2 = current2), workInProgress2;
          case 22:
            return updateOffscreenComponent(current2, workInProgress2, renderLanes2);
          case 24:
            return prepareToReadContext(workInProgress2), returnFiber = readContext(CacheContext), null === current2 ? (prevSibling = peekCacheFromPool(), null === prevSibling && (prevSibling = workInProgressRoot, nextProps = createCache(), prevSibling.pooledCache = nextProps, retainCache(nextProps), null !== nextProps && (prevSibling.pooledCacheLanes |= renderLanes2), prevSibling = nextProps), workInProgress2.memoizedState = {
              parent: returnFiber,
              cache: prevSibling
            }, initializeUpdateQueue(workInProgress2), pushProvider(workInProgress2, CacheContext, prevSibling)) : (0 !== (current2.lanes & renderLanes2) && (cloneUpdateQueue(current2, workInProgress2), processUpdateQueue(workInProgress2, null, null, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction()), prevSibling = current2.memoizedState, nextProps = workInProgress2.memoizedState, prevSibling.parent !== returnFiber ? (prevSibling = {
              parent: returnFiber,
              cache: returnFiber
            }, workInProgress2.memoizedState = prevSibling, 0 === workInProgress2.lanes && (workInProgress2.memoizedState = workInProgress2.updateQueue.baseState = prevSibling), pushProvider(workInProgress2, CacheContext, returnFiber)) : (returnFiber = nextProps.cache, pushProvider(workInProgress2, CacheContext, returnFiber), returnFiber !== prevSibling.cache && propagateContextChanges(
              workInProgress2,
              [CacheContext],
              renderLanes2,
              true
            ))), reconcileChildren(
              current2,
              workInProgress2,
              workInProgress2.pendingProps.children,
              renderLanes2
            ), workInProgress2.child;
          case 29:
            throw workInProgress2.pendingProps;
        }
        throw Error(
          "Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue."
        );
      }
      __name(beginWork, "beginWork");
      function markUpdate(workInProgress2) {
        workInProgress2.flags |= 4;
      }
      __name(markUpdate, "markUpdate");
      function doesRequireClone(current2, completedWork) {
        if (null !== current2 && current2.child === completedWork.child) return false;
        if (0 !== (completedWork.flags & 16)) return true;
        for (current2 = completedWork.child; null !== current2; ) {
          if (0 !== (current2.flags & 13878) || 0 !== (current2.subtreeFlags & 13878))
            return true;
          current2 = current2.sibling;
        }
        return false;
      }
      __name(doesRequireClone, "doesRequireClone");
      function appendAllChildren(parent, workInProgress2, needsVisibilityToggle, isHidden2) {
        if (supportsMutation)
          for (needsVisibilityToggle = workInProgress2.child; null !== needsVisibilityToggle; ) {
            if (5 === needsVisibilityToggle.tag || 6 === needsVisibilityToggle.tag)
              appendInitialChild(parent, needsVisibilityToggle.stateNode);
            else if (!(4 === needsVisibilityToggle.tag || supportsSingletons && 27 === needsVisibilityToggle.tag) && null !== needsVisibilityToggle.child) {
              needsVisibilityToggle.child.return = needsVisibilityToggle;
              needsVisibilityToggle = needsVisibilityToggle.child;
              continue;
            }
            if (needsVisibilityToggle === workInProgress2) break;
            for (; null === needsVisibilityToggle.sibling; ) {
              if (null === needsVisibilityToggle.return || needsVisibilityToggle.return === workInProgress2)
                return;
              needsVisibilityToggle = needsVisibilityToggle.return;
            }
            needsVisibilityToggle.sibling.return = needsVisibilityToggle.return;
            needsVisibilityToggle = needsVisibilityToggle.sibling;
          }
        else if (supportsPersistence)
          for (var _node = workInProgress2.child; null !== _node; ) {
            if (5 === _node.tag) {
              var instance = _node.stateNode;
              needsVisibilityToggle && isHidden2 && (instance = cloneHiddenInstance(
                instance,
                _node.type,
                _node.memoizedProps
              ));
              appendInitialChild(parent, instance);
            } else if (6 === _node.tag)
              instance = _node.stateNode, needsVisibilityToggle && isHidden2 && (instance = cloneHiddenTextInstance(
                instance,
                _node.memoizedProps
              )), appendInitialChild(parent, instance);
            else if (4 !== _node.tag) {
              if (22 === _node.tag && null !== _node.memoizedState)
                instance = _node.child, null !== instance && (instance.return = _node), appendAllChildren(parent, _node, true, true);
              else if (null !== _node.child) {
                _node.child.return = _node;
                _node = _node.child;
                continue;
              }
            }
            if (_node === workInProgress2) break;
            for (; null === _node.sibling; ) {
              if (null === _node.return || _node.return === workInProgress2)
                return;
              _node = _node.return;
            }
            _node.sibling.return = _node.return;
            _node = _node.sibling;
          }
      }
      __name(appendAllChildren, "appendAllChildren");
      function appendAllChildrenToContainer(containerChildSet, workInProgress2, needsVisibilityToggle, isHidden2) {
        var hasOffscreenComponentChild = false;
        if (supportsPersistence)
          for (var node = workInProgress2.child; null !== node; ) {
            if (5 === node.tag) {
              var instance = node.stateNode;
              needsVisibilityToggle && isHidden2 && (instance = cloneHiddenInstance(
                instance,
                node.type,
                node.memoizedProps
              ));
              appendChildToContainerChildSet(containerChildSet, instance);
            } else if (6 === node.tag)
              instance = node.stateNode, needsVisibilityToggle && isHidden2 && (instance = cloneHiddenTextInstance(
                instance,
                node.memoizedProps
              )), appendChildToContainerChildSet(containerChildSet, instance);
            else if (4 !== node.tag) {
              if (22 === node.tag && null !== node.memoizedState)
                hasOffscreenComponentChild = node.child, null !== hasOffscreenComponentChild && (hasOffscreenComponentChild.return = node), appendAllChildrenToContainer(containerChildSet, node, true, true), hasOffscreenComponentChild = true;
              else if (null !== node.child) {
                node.child.return = node;
                node = node.child;
                continue;
              }
            }
            if (node === workInProgress2) break;
            for (; null === node.sibling; ) {
              if (null === node.return || node.return === workInProgress2)
                return hasOffscreenComponentChild;
              node = node.return;
            }
            node.sibling.return = node.return;
            node = node.sibling;
          }
        return hasOffscreenComponentChild;
      }
      __name(appendAllChildrenToContainer, "appendAllChildrenToContainer");
      function updateHostContainer(current2, workInProgress2) {
        if (supportsPersistence && doesRequireClone(current2, workInProgress2)) {
          current2 = workInProgress2.stateNode;
          var container = current2.containerInfo, newChildSet = createContainerChildSet();
          appendAllChildrenToContainer(newChildSet, workInProgress2, false, false);
          current2.pendingChildren = newChildSet;
          markUpdate(workInProgress2);
          finalizeContainerChildren(container, newChildSet);
        }
      }
      __name(updateHostContainer, "updateHostContainer");
      function updateHostComponent(current2, workInProgress2, type, newProps) {
        if (supportsMutation)
          current2.memoizedProps !== newProps && markUpdate(workInProgress2);
        else if (supportsPersistence) {
          var currentInstance = current2.stateNode, _oldProps = current2.memoizedProps;
          if ((current2 = doesRequireClone(current2, workInProgress2)) || _oldProps !== newProps) {
            var currentHostContext = getHostContext();
            _oldProps = cloneInstance(
              currentInstance,
              type,
              _oldProps,
              newProps,
              !current2,
              null
            );
            _oldProps === currentInstance ? workInProgress2.stateNode = currentInstance : (finalizeInitialChildren(
              _oldProps,
              type,
              newProps,
              currentHostContext
            ) && markUpdate(workInProgress2), workInProgress2.stateNode = _oldProps, current2 ? appendAllChildren(_oldProps, workInProgress2, false, false) : markUpdate(workInProgress2));
          } else workInProgress2.stateNode = currentInstance;
        }
      }
      __name(updateHostComponent, "updateHostComponent");
      function preloadInstanceAndSuspendIfNeeded(workInProgress2, type, props) {
        if (maySuspendCommit(type, props)) {
          if (workInProgress2.flags |= 16777216, !preloadInstance(type, props))
            if (shouldRemainOnPreviousScreen()) workInProgress2.flags |= 8192;
            else
              throw suspendedThenable = noopSuspenseyCommitThenable, SuspenseyCommitException;
        } else workInProgress2.flags &= -16777217;
      }
      __name(preloadInstanceAndSuspendIfNeeded, "preloadInstanceAndSuspendIfNeeded");
      function preloadResourceAndSuspendIfNeeded(workInProgress2, resource) {
        if (mayResourceSuspendCommit(resource)) {
          if (workInProgress2.flags |= 16777216, !preloadResource(resource))
            if (shouldRemainOnPreviousScreen()) workInProgress2.flags |= 8192;
            else
              throw suspendedThenable = noopSuspenseyCommitThenable, SuspenseyCommitException;
        } else workInProgress2.flags &= -16777217;
      }
      __name(preloadResourceAndSuspendIfNeeded, "preloadResourceAndSuspendIfNeeded");
      function scheduleRetryEffect(workInProgress2, retryQueue) {
        null !== retryQueue && (workInProgress2.flags |= 4);
        workInProgress2.flags & 16384 && (retryQueue = 22 !== workInProgress2.tag ? claimNextRetryLane() : 536870912, workInProgress2.lanes |= retryQueue, workInProgressSuspendedRetryLanes |= retryQueue);
      }
      __name(scheduleRetryEffect, "scheduleRetryEffect");
      function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
        if (!isHydrating)
          switch (renderState.tailMode) {
            case "hidden":
              hasRenderedATailFallback = renderState.tail;
              for (var lastTailNode = null; null !== hasRenderedATailFallback; )
                null !== hasRenderedATailFallback.alternate && (lastTailNode = hasRenderedATailFallback), hasRenderedATailFallback = hasRenderedATailFallback.sibling;
              null === lastTailNode ? renderState.tail = null : lastTailNode.sibling = null;
              break;
            case "collapsed":
              lastTailNode = renderState.tail;
              for (var _lastTailNode = null; null !== lastTailNode; )
                null !== lastTailNode.alternate && (_lastTailNode = lastTailNode), lastTailNode = lastTailNode.sibling;
              null === _lastTailNode ? hasRenderedATailFallback || null === renderState.tail ? renderState.tail = null : renderState.tail.sibling = null : _lastTailNode.sibling = null;
          }
      }
      __name(cutOffTailIfNeeded, "cutOffTailIfNeeded");
      function bubbleProperties(completedWork) {
        var didBailout = null !== completedWork.alternate && completedWork.alternate.child === completedWork.child, newChildLanes = 0, subtreeFlags = 0;
        if (didBailout)
          if ((completedWork.mode & 2) !== NoMode) {
            for (var _treeBaseDuration = completedWork.selfBaseDuration, _child2 = completedWork.child; null !== _child2; )
              newChildLanes |= _child2.lanes | _child2.childLanes, subtreeFlags |= _child2.subtreeFlags & 65011712, subtreeFlags |= _child2.flags & 65011712, _treeBaseDuration += _child2.treeBaseDuration, _child2 = _child2.sibling;
            completedWork.treeBaseDuration = _treeBaseDuration;
          } else
            for (_treeBaseDuration = completedWork.child; null !== _treeBaseDuration; )
              newChildLanes |= _treeBaseDuration.lanes | _treeBaseDuration.childLanes, subtreeFlags |= _treeBaseDuration.subtreeFlags & 65011712, subtreeFlags |= _treeBaseDuration.flags & 65011712, _treeBaseDuration.return = completedWork, _treeBaseDuration = _treeBaseDuration.sibling;
        else if ((completedWork.mode & 2) !== NoMode) {
          _treeBaseDuration = completedWork.actualDuration;
          _child2 = completedWork.selfBaseDuration;
          for (var child = completedWork.child; null !== child; )
            newChildLanes |= child.lanes | child.childLanes, subtreeFlags |= child.subtreeFlags, subtreeFlags |= child.flags, _treeBaseDuration += child.actualDuration, _child2 += child.treeBaseDuration, child = child.sibling;
          completedWork.actualDuration = _treeBaseDuration;
          completedWork.treeBaseDuration = _child2;
        } else
          for (_treeBaseDuration = completedWork.child; null !== _treeBaseDuration; )
            newChildLanes |= _treeBaseDuration.lanes | _treeBaseDuration.childLanes, subtreeFlags |= _treeBaseDuration.subtreeFlags, subtreeFlags |= _treeBaseDuration.flags, _treeBaseDuration.return = completedWork, _treeBaseDuration = _treeBaseDuration.sibling;
        completedWork.subtreeFlags |= subtreeFlags;
        completedWork.childLanes = newChildLanes;
        return didBailout;
      }
      __name(bubbleProperties, "bubbleProperties");
      function completeWork(current2, workInProgress2, renderLanes2) {
        var newProps = workInProgress2.pendingProps;
        popTreeContext(workInProgress2);
        switch (workInProgress2.tag) {
          case 31:
          case 16:
          case 15:
          case 0:
          case 11:
          case 7:
          case 8:
          case 12:
          case 9:
          case 14:
            return bubbleProperties(workInProgress2), null;
          case 1:
            return bubbleProperties(workInProgress2), null;
          case 3:
            renderLanes2 = workInProgress2.stateNode;
            newProps = null;
            null !== current2 && (newProps = current2.memoizedState.cache);
            workInProgress2.memoizedState.cache !== newProps && (workInProgress2.flags |= 2048);
            popProvider(CacheContext, workInProgress2);
            popHostContainer(workInProgress2);
            renderLanes2.pendingContext && (renderLanes2.context = renderLanes2.pendingContext, renderLanes2.pendingContext = null);
            if (null === current2 || null === current2.child)
              popHydrationState(workInProgress2) ? (emitPendingHydrationWarnings(), markUpdate(workInProgress2)) : null === current2 || current2.memoizedState.isDehydrated && 0 === (workInProgress2.flags & 256) || (workInProgress2.flags |= 1024, upgradeHydrationErrorsToRecoverable());
            updateHostContainer(current2, workInProgress2);
            bubbleProperties(workInProgress2);
            return null;
          case 26:
            if (supportsResources) {
              renderLanes2 = workInProgress2.type;
              var nextResource = workInProgress2.memoizedState;
              null === current2 ? (markUpdate(workInProgress2), null !== nextResource ? (bubbleProperties(workInProgress2), preloadResourceAndSuspendIfNeeded(
                workInProgress2,
                nextResource
              )) : (bubbleProperties(workInProgress2), preloadInstanceAndSuspendIfNeeded(
                workInProgress2,
                renderLanes2,
                newProps
              ))) : nextResource ? nextResource !== current2.memoizedState ? (markUpdate(workInProgress2), bubbleProperties(workInProgress2), preloadResourceAndSuspendIfNeeded(
                workInProgress2,
                nextResource
              )) : (bubbleProperties(workInProgress2), workInProgress2.flags &= -16777217) : (supportsMutation ? current2.memoizedProps !== newProps && markUpdate(workInProgress2) : updateHostComponent(
                current2,
                workInProgress2,
                renderLanes2,
                newProps
              ), bubbleProperties(workInProgress2), preloadInstanceAndSuspendIfNeeded(
                workInProgress2,
                renderLanes2,
                newProps
              ));
              return null;
            }
          case 27:
            if (supportsSingletons) {
              popHostContext(workInProgress2);
              renderLanes2 = requiredContext(rootInstanceStackCursor.current);
              nextResource = workInProgress2.type;
              if (null !== current2 && null != workInProgress2.stateNode)
                supportsMutation ? current2.memoizedProps !== newProps && markUpdate(workInProgress2) : updateHostComponent(
                  current2,
                  workInProgress2,
                  nextResource,
                  newProps
                );
              else {
                if (!newProps) {
                  if (null === workInProgress2.stateNode)
                    throw Error(
                      "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."
                    );
                  bubbleProperties(workInProgress2);
                  return null;
                }
                current2 = getHostContext();
                popHydrationState(workInProgress2) ? prepareToHydrateHostInstance(workInProgress2, current2) : (current2 = resolveSingletonInstance(
                  nextResource,
                  newProps,
                  renderLanes2,
                  current2,
                  true
                ), workInProgress2.stateNode = current2, markUpdate(workInProgress2));
              }
              bubbleProperties(workInProgress2);
              return null;
            }
          case 5:
            popHostContext(workInProgress2);
            renderLanes2 = workInProgress2.type;
            if (null !== current2 && null != workInProgress2.stateNode)
              updateHostComponent(current2, workInProgress2, renderLanes2, newProps);
            else {
              if (!newProps) {
                if (null === workInProgress2.stateNode)
                  throw Error(
                    "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."
                  );
                bubbleProperties(workInProgress2);
                return null;
              }
              current2 = getHostContext();
              popHydrationState(workInProgress2) ? prepareToHydrateHostInstance(workInProgress2, current2) : (nextResource = requiredContext(
                rootInstanceStackCursor.current
              ), nextResource = createInstance2(
                renderLanes2,
                newProps,
                nextResource,
                current2,
                workInProgress2
              ), appendAllChildren(nextResource, workInProgress2, false, false), workInProgress2.stateNode = nextResource, finalizeInitialChildren(
                nextResource,
                renderLanes2,
                newProps,
                current2
              ) && markUpdate(workInProgress2));
            }
            bubbleProperties(workInProgress2);
            preloadInstanceAndSuspendIfNeeded(
              workInProgress2,
              workInProgress2.type,
              workInProgress2.pendingProps
            );
            return null;
          case 6:
            if (current2 && null != workInProgress2.stateNode)
              renderLanes2 = current2.memoizedProps, supportsMutation ? renderLanes2 !== newProps && markUpdate(workInProgress2) : supportsPersistence && (renderLanes2 !== newProps ? (current2 = requiredContext(
                rootInstanceStackCursor.current
              ), renderLanes2 = getHostContext(), workInProgress2.stateNode = createTextInstance(
                newProps,
                current2,
                renderLanes2,
                workInProgress2
              ), markUpdate(workInProgress2)) : workInProgress2.stateNode = current2.stateNode);
            else {
              if ("string" !== typeof newProps && null === workInProgress2.stateNode)
                throw Error(
                  "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."
                );
              current2 = requiredContext(rootInstanceStackCursor.current);
              renderLanes2 = getHostContext();
              if (popHydrationState(workInProgress2)) {
                if (!supportsHydration)
                  throw Error(
                    "Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."
                  );
                current2 = workInProgress2.stateNode;
                renderLanes2 = workInProgress2.memoizedProps;
                nextResource = !didSuspendOrErrorDEV;
                newProps = null;
                var returnFiber = hydrationParentFiber;
                if (null !== returnFiber)
                  switch (returnFiber.tag) {
                    case 3:
                      nextResource && (nextResource = diffHydratedTextForDevWarnings(
                        current2,
                        renderLanes2,
                        newProps
                      ), null !== nextResource && (buildHydrationDiffNode(workInProgress2, 0).serverProps = nextResource));
                      break;
                    case 27:
                    case 5:
                      newProps = returnFiber.memoizedProps, nextResource && (nextResource = diffHydratedTextForDevWarnings(
                        current2,
                        renderLanes2,
                        newProps
                      ), null !== nextResource && (buildHydrationDiffNode(
                        workInProgress2,
                        0
                      ).serverProps = nextResource));
                  }
                hydrateTextInstance(
                  current2,
                  renderLanes2,
                  workInProgress2,
                  newProps
                ) || throwOnHydrationMismatch(workInProgress2);
              } else
                workInProgress2.stateNode = createTextInstance(
                  newProps,
                  current2,
                  renderLanes2,
                  workInProgress2
                );
            }
            bubbleProperties(workInProgress2);
            return null;
          case 13:
            newProps = workInProgress2.memoizedState;
            if (null === current2 || null !== current2.memoizedState && null !== current2.memoizedState.dehydrated) {
              nextResource = popHydrationState(workInProgress2);
              if (null !== newProps && null !== newProps.dehydrated) {
                if (null === current2) {
                  if (!nextResource)
                    throw Error(
                      "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React."
                    );
                  if (!supportsHydration)
                    throw Error(
                      "Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."
                    );
                  nextResource = workInProgress2.memoizedState;
                  nextResource = null !== nextResource ? nextResource.dehydrated : null;
                  if (!nextResource)
                    throw Error(
                      "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue."
                    );
                  hydrateSuspenseInstance(nextResource, workInProgress2);
                  bubbleProperties(workInProgress2);
                  (workInProgress2.mode & 2) !== NoMode && null !== newProps && (nextResource = workInProgress2.child, null !== nextResource && (workInProgress2.treeBaseDuration -= nextResource.treeBaseDuration));
                } else
                  emitPendingHydrationWarnings(), resetHydrationState(), 0 === (workInProgress2.flags & 128) && (workInProgress2.memoizedState = null), workInProgress2.flags |= 4, bubbleProperties(workInProgress2), (workInProgress2.mode & 2) !== NoMode && null !== newProps && (nextResource = workInProgress2.child, null !== nextResource && (workInProgress2.treeBaseDuration -= nextResource.treeBaseDuration));
                nextResource = false;
              } else
                nextResource = upgradeHydrationErrorsToRecoverable(), null !== current2 && null !== current2.memoizedState && (current2.memoizedState.hydrationErrors = nextResource), nextResource = true;
              if (!nextResource) {
                if (workInProgress2.flags & 256)
                  return popSuspenseHandler(workInProgress2), workInProgress2;
                popSuspenseHandler(workInProgress2);
                return null;
              }
            }
            popSuspenseHandler(workInProgress2);
            if (0 !== (workInProgress2.flags & 128))
              return workInProgress2.lanes = renderLanes2, (workInProgress2.mode & 2) !== NoMode && transferActualDuration(workInProgress2), workInProgress2;
            renderLanes2 = null !== newProps;
            current2 = null !== current2 && null !== current2.memoizedState;
            renderLanes2 && (newProps = workInProgress2.child, nextResource = null, null !== newProps.alternate && null !== newProps.alternate.memoizedState && null !== newProps.alternate.memoizedState.cachePool && (nextResource = newProps.alternate.memoizedState.cachePool.pool), returnFiber = null, null !== newProps.memoizedState && null !== newProps.memoizedState.cachePool && (returnFiber = newProps.memoizedState.cachePool.pool), returnFiber !== nextResource && (newProps.flags |= 2048));
            renderLanes2 !== current2 && renderLanes2 && (workInProgress2.child.flags |= 8192);
            scheduleRetryEffect(workInProgress2, workInProgress2.updateQueue);
            bubbleProperties(workInProgress2);
            (workInProgress2.mode & 2) !== NoMode && renderLanes2 && (current2 = workInProgress2.child, null !== current2 && (workInProgress2.treeBaseDuration -= current2.treeBaseDuration));
            return null;
          case 4:
            return popHostContainer(workInProgress2), updateHostContainer(current2, workInProgress2), null === current2 && preparePortalMount(workInProgress2.stateNode.containerInfo), bubbleProperties(workInProgress2), null;
          case 10:
            return popProvider(workInProgress2.type, workInProgress2), bubbleProperties(workInProgress2), null;
          case 19:
            pop(suspenseStackCursor, workInProgress2);
            nextResource = workInProgress2.memoizedState;
            if (null === nextResource)
              return bubbleProperties(workInProgress2), null;
            newProps = 0 !== (workInProgress2.flags & 128);
            returnFiber = nextResource.rendering;
            if (null === returnFiber)
              if (newProps) cutOffTailIfNeeded(nextResource, false);
              else {
                if (workInProgressRootExitStatus !== RootInProgress || null !== current2 && 0 !== (current2.flags & 128))
                  for (current2 = workInProgress2.child; null !== current2; ) {
                    returnFiber = findFirstSuspended(current2);
                    if (null !== returnFiber) {
                      workInProgress2.flags |= 128;
                      cutOffTailIfNeeded(nextResource, false);
                      current2 = returnFiber.updateQueue;
                      workInProgress2.updateQueue = current2;
                      scheduleRetryEffect(workInProgress2, current2);
                      workInProgress2.subtreeFlags = 0;
                      current2 = renderLanes2;
                      for (renderLanes2 = workInProgress2.child; null !== renderLanes2; )
                        resetWorkInProgress(renderLanes2, current2), renderLanes2 = renderLanes2.sibling;
                      push2(
                        suspenseStackCursor,
                        suspenseStackCursor.current & SubtreeSuspenseContextMask | ForceSuspenseFallback,
                        workInProgress2
                      );
                      return workInProgress2.child;
                    }
                    current2 = current2.sibling;
                  }
                null !== nextResource.tail && now$1() > workInProgressRootRenderTargetTime && (workInProgress2.flags |= 128, newProps = true, cutOffTailIfNeeded(nextResource, false), workInProgress2.lanes = 4194304);
              }
            else {
              if (!newProps)
                if (current2 = findFirstSuspended(returnFiber), null !== current2) {
                  if (workInProgress2.flags |= 128, newProps = true, current2 = current2.updateQueue, workInProgress2.updateQueue = current2, scheduleRetryEffect(workInProgress2, current2), cutOffTailIfNeeded(nextResource, true), null === nextResource.tail && "hidden" === nextResource.tailMode && !returnFiber.alternate && !isHydrating)
                    return bubbleProperties(workInProgress2), null;
                } else
                  2 * now$1() - nextResource.renderingStartTime > workInProgressRootRenderTargetTime && 536870912 !== renderLanes2 && (workInProgress2.flags |= 128, newProps = true, cutOffTailIfNeeded(nextResource, false), workInProgress2.lanes = 4194304);
              nextResource.isBackwards ? (returnFiber.sibling = workInProgress2.child, workInProgress2.child = returnFiber) : (current2 = nextResource.last, null !== current2 ? current2.sibling = returnFiber : workInProgress2.child = returnFiber, nextResource.last = returnFiber);
            }
            if (null !== nextResource.tail)
              return current2 = nextResource.tail, nextResource.rendering = current2, nextResource.tail = current2.sibling, nextResource.renderingStartTime = now$1(), current2.sibling = null, renderLanes2 = suspenseStackCursor.current, renderLanes2 = newProps ? renderLanes2 & SubtreeSuspenseContextMask | ForceSuspenseFallback : renderLanes2 & SubtreeSuspenseContextMask, push2(suspenseStackCursor, renderLanes2, workInProgress2), current2;
            bubbleProperties(workInProgress2);
            return null;
          case 22:
          case 23:
            return popSuspenseHandler(workInProgress2), popHiddenContext(workInProgress2), newProps = null !== workInProgress2.memoizedState, null !== current2 ? null !== current2.memoizedState !== newProps && (workInProgress2.flags |= 8192) : newProps && (workInProgress2.flags |= 8192), newProps ? 0 !== (renderLanes2 & 536870912) && 0 === (workInProgress2.flags & 128) && (bubbleProperties(workInProgress2), workInProgress2.subtreeFlags & 6 && (workInProgress2.flags |= 8192)) : bubbleProperties(workInProgress2), renderLanes2 = workInProgress2.updateQueue, null !== renderLanes2 && scheduleRetryEffect(workInProgress2, renderLanes2.retryQueue), renderLanes2 = null, null !== current2 && null !== current2.memoizedState && null !== current2.memoizedState.cachePool && (renderLanes2 = current2.memoizedState.cachePool.pool), newProps = null, null !== workInProgress2.memoizedState && null !== workInProgress2.memoizedState.cachePool && (newProps = workInProgress2.memoizedState.cachePool.pool), newProps !== renderLanes2 && (workInProgress2.flags |= 2048), null !== current2 && pop(resumedCache, workInProgress2), null;
          case 24:
            return renderLanes2 = null, null !== current2 && (renderLanes2 = current2.memoizedState.cache), workInProgress2.memoizedState.cache !== renderLanes2 && (workInProgress2.flags |= 2048), popProvider(CacheContext, workInProgress2), bubbleProperties(workInProgress2), null;
          case 25:
            return null;
          case 30:
            return null;
        }
        throw Error(
          "Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue."
        );
      }
      __name(completeWork, "completeWork");
      function unwindWork(current2, workInProgress2) {
        popTreeContext(workInProgress2);
        switch (workInProgress2.tag) {
          case 1:
            return current2 = workInProgress2.flags, current2 & 65536 ? (workInProgress2.flags = current2 & -65537 | 128, (workInProgress2.mode & 2) !== NoMode && transferActualDuration(workInProgress2), workInProgress2) : null;
          case 3:
            return popProvider(CacheContext, workInProgress2), popHostContainer(workInProgress2), current2 = workInProgress2.flags, 0 !== (current2 & 65536) && 0 === (current2 & 128) ? (workInProgress2.flags = current2 & -65537 | 128, workInProgress2) : null;
          case 26:
          case 27:
          case 5:
            return popHostContext(workInProgress2), null;
          case 13:
            popSuspenseHandler(workInProgress2);
            current2 = workInProgress2.memoizedState;
            if (null !== current2 && null !== current2.dehydrated) {
              if (null === workInProgress2.alternate)
                throw Error(
                  "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue."
                );
              resetHydrationState();
            }
            current2 = workInProgress2.flags;
            return current2 & 65536 ? (workInProgress2.flags = current2 & -65537 | 128, (workInProgress2.mode & 2) !== NoMode && transferActualDuration(workInProgress2), workInProgress2) : null;
          case 19:
            return pop(suspenseStackCursor, workInProgress2), null;
          case 4:
            return popHostContainer(workInProgress2), null;
          case 10:
            return popProvider(workInProgress2.type, workInProgress2), null;
          case 22:
          case 23:
            return popSuspenseHandler(workInProgress2), popHiddenContext(workInProgress2), null !== current2 && pop(resumedCache, workInProgress2), current2 = workInProgress2.flags, current2 & 65536 ? (workInProgress2.flags = current2 & -65537 | 128, (workInProgress2.mode & 2) !== NoMode && transferActualDuration(workInProgress2), workInProgress2) : null;
          case 24:
            return popProvider(CacheContext, workInProgress2), null;
          case 25:
            return null;
          default:
            return null;
        }
      }
      __name(unwindWork, "unwindWork");
      function unwindInterruptedWork(current2, interruptedWork) {
        popTreeContext(interruptedWork);
        switch (interruptedWork.tag) {
          case 3:
            popProvider(CacheContext, interruptedWork);
            popHostContainer(interruptedWork);
            break;
          case 26:
          case 27:
          case 5:
            popHostContext(interruptedWork);
            break;
          case 4:
            popHostContainer(interruptedWork);
            break;
          case 13:
            popSuspenseHandler(interruptedWork);
            break;
          case 19:
            pop(suspenseStackCursor, interruptedWork);
            break;
          case 10:
            popProvider(interruptedWork.type, interruptedWork);
            break;
          case 22:
          case 23:
            popSuspenseHandler(interruptedWork);
            popHiddenContext(interruptedWork);
            null !== current2 && pop(resumedCache, interruptedWork);
            break;
          case 24:
            popProvider(CacheContext, interruptedWork);
        }
      }
      __name(unwindInterruptedWork, "unwindInterruptedWork");
      function shouldProfile(current2) {
        return (current2.mode & 2) !== NoMode;
      }
      __name(shouldProfile, "shouldProfile");
      function commitHookLayoutEffects(finishedWork, hookFlags) {
        shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListMount(hookFlags, finishedWork), recordEffectDuration()) : commitHookEffectListMount(hookFlags, finishedWork);
      }
      __name(commitHookLayoutEffects, "commitHookLayoutEffects");
      function commitHookLayoutUnmountEffects(finishedWork, nearestMountedAncestor, hookFlags) {
        shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListUnmount(
          hookFlags,
          finishedWork,
          nearestMountedAncestor
        ), recordEffectDuration()) : commitHookEffectListUnmount(
          hookFlags,
          finishedWork,
          nearestMountedAncestor
        );
      }
      __name(commitHookLayoutUnmountEffects, "commitHookLayoutUnmountEffects");
      function commitHookEffectListMount(flags, finishedWork) {
        try {
          var updateQueue = finishedWork.updateQueue, lastEffect = null !== updateQueue ? updateQueue.lastEffect : null;
          if (null !== lastEffect) {
            var firstEffect = lastEffect.next;
            updateQueue = firstEffect;
            do {
              if ((updateQueue.tag & flags) === flags && ((flags & Passive) !== NoFlags ? null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted && injectedProfilingHooks.markComponentPassiveEffectMountStarted(
                finishedWork
              ) : (flags & Layout) !== NoFlags && null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted && injectedProfilingHooks.markComponentLayoutEffectMountStarted(
                finishedWork
              ), lastEffect = void 0, (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = true), lastEffect = runWithFiberInDEV(
                finishedWork,
                callCreateInDEV,
                updateQueue
              ), (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = false), (flags & Passive) !== NoFlags ? null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped && injectedProfilingHooks.markComponentPassiveEffectMountStopped() : (flags & Layout) !== NoFlags && null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped && injectedProfilingHooks.markComponentLayoutEffectMountStopped(), void 0 !== lastEffect && "function" !== typeof lastEffect)) {
                var hookName = void 0;
                hookName = 0 !== (updateQueue.tag & Layout) ? "useLayoutEffect" : 0 !== (updateQueue.tag & Insertion) ? "useInsertionEffect" : "useEffect";
                var addendum = void 0;
                addendum = null === lastEffect ? " You returned null. If your effect does not require clean up, return undefined (or nothing)." : "function" === typeof lastEffect.then ? "\n\nIt looks like you wrote " + hookName + "(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:\n\n" + hookName + "(() => {\n  async function fetchData() {\n    // You can await here\n    const response = await MyAPI.getData(someId);\n    // ...\n  }\n  fetchData();\n}, [someId]); // Or [] if effect doesn't need props or state\n\nLearn more about data fetching with Hooks: https://react.dev/link/hooks-data-fetching" : " You returned: " + lastEffect;
                runWithFiberInDEV(
                  finishedWork,
                  function(n2, a) {
                    console.error(
                      "%s must not return anything besides a function, which is used for clean-up.%s",
                      n2,
                      a
                    );
                  },
                  hookName,
                  addendum
                );
              }
              updateQueue = updateQueue.next;
            } while (updateQueue !== firstEffect);
          }
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      __name(commitHookEffectListMount, "commitHookEffectListMount");
      function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) {
        try {
          var updateQueue = finishedWork.updateQueue, lastEffect = null !== updateQueue ? updateQueue.lastEffect : null;
          if (null !== lastEffect) {
            var firstEffect = lastEffect.next;
            updateQueue = firstEffect;
            do {
              if ((updateQueue.tag & flags) === flags) {
                var inst = updateQueue.inst, destroy = inst.destroy;
                void 0 !== destroy && (inst.destroy = void 0, (flags & Passive) !== NoFlags ? null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted && injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(
                  finishedWork
                ) : (flags & Layout) !== NoFlags && null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted && injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(
                  finishedWork
                ), (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = true), lastEffect = finishedWork, runWithFiberInDEV(
                  lastEffect,
                  callDestroyInDEV,
                  lastEffect,
                  nearestMountedAncestor,
                  destroy
                ), (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = false), (flags & Passive) !== NoFlags ? null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped && injectedProfilingHooks.markComponentPassiveEffectUnmountStopped() : (flags & Layout) !== NoFlags && null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped && injectedProfilingHooks.markComponentLayoutEffectUnmountStopped());
              }
              updateQueue = updateQueue.next;
            } while (updateQueue !== firstEffect);
          }
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      __name(commitHookEffectListUnmount, "commitHookEffectListUnmount");
      function commitHookPassiveMountEffects(finishedWork, hookFlags) {
        shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListMount(hookFlags, finishedWork), recordEffectDuration()) : commitHookEffectListMount(hookFlags, finishedWork);
      }
      __name(commitHookPassiveMountEffects, "commitHookPassiveMountEffects");
      function commitHookPassiveUnmountEffects(finishedWork, nearestMountedAncestor, hookFlags) {
        shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListUnmount(
          hookFlags,
          finishedWork,
          nearestMountedAncestor
        ), recordEffectDuration()) : commitHookEffectListUnmount(
          hookFlags,
          finishedWork,
          nearestMountedAncestor
        );
      }
      __name(commitHookPassiveUnmountEffects, "commitHookPassiveUnmountEffects");
      function commitClassCallbacks(finishedWork) {
        var updateQueue = finishedWork.updateQueue;
        if (null !== updateQueue) {
          var instance = finishedWork.stateNode;
          finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (instance.props !== finishedWork.memoizedProps && console.error(
            "Expected %s props to match memoized props before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.",
            getComponentNameFromFiber(finishedWork) || "instance"
          ), instance.state !== finishedWork.memoizedState && console.error(
            "Expected %s state to match memoized state before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.",
            getComponentNameFromFiber(finishedWork) || "instance"
          ));
          try {
            runWithFiberInDEV(
              finishedWork,
              commitCallbacks,
              updateQueue,
              instance
            );
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
        }
      }
      __name(commitClassCallbacks, "commitClassCallbacks");
      function callGetSnapshotBeforeUpdates(instance, prevProps, prevState) {
        return instance.getSnapshotBeforeUpdate(prevProps, prevState);
      }
      __name(callGetSnapshotBeforeUpdates, "callGetSnapshotBeforeUpdates");
      function commitClassSnapshot(finishedWork, current2) {
        var prevProps = current2.memoizedProps, prevState = current2.memoizedState;
        current2 = finishedWork.stateNode;
        finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (current2.props !== finishedWork.memoizedProps && console.error(
          "Expected %s props to match memoized props before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.",
          getComponentNameFromFiber(finishedWork) || "instance"
        ), current2.state !== finishedWork.memoizedState && console.error(
          "Expected %s state to match memoized state before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.",
          getComponentNameFromFiber(finishedWork) || "instance"
        ));
        try {
          var resolvedPrevProps = resolveClassComponentProps(
            finishedWork.type,
            prevProps,
            finishedWork.elementType === finishedWork.type
          );
          var snapshot = runWithFiberInDEV(
            finishedWork,
            callGetSnapshotBeforeUpdates,
            current2,
            resolvedPrevProps,
            prevState
          );
          prevProps = didWarnAboutUndefinedSnapshotBeforeUpdate;
          void 0 !== snapshot || prevProps.has(finishedWork.type) || (prevProps.add(finishedWork.type), runWithFiberInDEV(finishedWork, function() {
            console.error(
              "%s.getSnapshotBeforeUpdate(): A snapshot value (or null) must be returned. You have returned undefined.",
              getComponentNameFromFiber(finishedWork)
            );
          }));
          current2.__reactInternalSnapshotBeforeUpdate = snapshot;
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      __name(commitClassSnapshot, "commitClassSnapshot");
      function safelyCallComponentWillUnmount(current2, nearestMountedAncestor, instance) {
        instance.props = resolveClassComponentProps(
          current2.type,
          current2.memoizedProps
        );
        instance.state = current2.memoizedState;
        shouldProfile(current2) ? (startEffectTimer(), runWithFiberInDEV(
          current2,
          callComponentWillUnmountInDEV,
          current2,
          nearestMountedAncestor,
          instance
        ), recordEffectDuration()) : runWithFiberInDEV(
          current2,
          callComponentWillUnmountInDEV,
          current2,
          nearestMountedAncestor,
          instance
        );
      }
      __name(safelyCallComponentWillUnmount, "safelyCallComponentWillUnmount");
      function commitAttachRef(finishedWork) {
        var ref = finishedWork.ref;
        if (null !== ref) {
          switch (finishedWork.tag) {
            case 26:
            case 27:
            case 5:
              var instanceToUse = getPublicInstance(finishedWork.stateNode);
              break;
            case 30:
              instanceToUse = finishedWork.stateNode;
              break;
            default:
              instanceToUse = finishedWork.stateNode;
          }
          if ("function" === typeof ref)
            if (shouldProfile(finishedWork))
              try {
                startEffectTimer(), finishedWork.refCleanup = ref(instanceToUse);
              } finally {
                recordEffectDuration();
              }
            else finishedWork.refCleanup = ref(instanceToUse);
          else
            "string" === typeof ref ? console.error("String refs are no longer supported.") : ref.hasOwnProperty("current") || console.error(
              "Unexpected ref object provided for %s. Use either a ref-setter function or React.createRef().",
              getComponentNameFromFiber(finishedWork)
            ), ref.current = instanceToUse;
        }
      }
      __name(commitAttachRef, "commitAttachRef");
      function safelyAttachRef(current2, nearestMountedAncestor) {
        try {
          runWithFiberInDEV(current2, commitAttachRef, current2);
        } catch (error) {
          captureCommitPhaseError(current2, nearestMountedAncestor, error);
        }
      }
      __name(safelyAttachRef, "safelyAttachRef");
      function safelyDetachRef(current2, nearestMountedAncestor) {
        var ref = current2.ref, refCleanup = current2.refCleanup;
        if (null !== ref)
          if ("function" === typeof refCleanup)
            try {
              if (shouldProfile(current2))
                try {
                  startEffectTimer(), runWithFiberInDEV(current2, refCleanup);
                } finally {
                  recordEffectDuration(current2);
                }
              else runWithFiberInDEV(current2, refCleanup);
            } catch (error) {
              captureCommitPhaseError(current2, nearestMountedAncestor, error);
            } finally {
              current2.refCleanup = null, current2 = current2.alternate, null != current2 && (current2.refCleanup = null);
            }
          else if ("function" === typeof ref)
            try {
              if (shouldProfile(current2))
                try {
                  startEffectTimer(), runWithFiberInDEV(current2, ref, null);
                } finally {
                  recordEffectDuration(current2);
                }
              else runWithFiberInDEV(current2, ref, null);
            } catch (error$3) {
              captureCommitPhaseError(current2, nearestMountedAncestor, error$3);
            }
          else ref.current = null;
      }
      __name(safelyDetachRef, "safelyDetachRef");
      function commitProfiler(finishedWork, current2, commitStartTime2, effectDuration) {
        var _finishedWork$memoize = finishedWork.memoizedProps, id = _finishedWork$memoize.id, onCommit = _finishedWork$memoize.onCommit;
        _finishedWork$memoize = _finishedWork$memoize.onRender;
        current2 = null === current2 ? "mount" : "update";
        currentUpdateIsNested && (current2 = "nested-update");
        "function" === typeof _finishedWork$memoize && _finishedWork$memoize(
          id,
          current2,
          finishedWork.actualDuration,
          finishedWork.treeBaseDuration,
          finishedWork.actualStartTime,
          commitStartTime2
        );
        "function" === typeof onCommit && onCommit(
          finishedWork.memoizedProps.id,
          current2,
          effectDuration,
          commitStartTime2
        );
      }
      __name(commitProfiler, "commitProfiler");
      function commitProfilerPostCommitImpl(finishedWork, current2, commitStartTime2, passiveEffectDuration) {
        var _finishedWork$memoize2 = finishedWork.memoizedProps;
        finishedWork = _finishedWork$memoize2.id;
        _finishedWork$memoize2 = _finishedWork$memoize2.onPostCommit;
        current2 = null === current2 ? "mount" : "update";
        currentUpdateIsNested && (current2 = "nested-update");
        "function" === typeof _finishedWork$memoize2 && _finishedWork$memoize2(
          finishedWork,
          current2,
          passiveEffectDuration,
          commitStartTime2
        );
      }
      __name(commitProfilerPostCommitImpl, "commitProfilerPostCommitImpl");
      function commitHostMount(finishedWork) {
        var type = finishedWork.type, props = finishedWork.memoizedProps, instance = finishedWork.stateNode;
        try {
          runWithFiberInDEV(
            finishedWork,
            commitMount,
            instance,
            type,
            props,
            finishedWork
          );
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      __name(commitHostMount, "commitHostMount");
      function commitHostUpdate(finishedWork, newProps, oldProps) {
        try {
          runWithFiberInDEV(
            finishedWork,
            commitUpdate,
            finishedWork.stateNode,
            finishedWork.type,
            oldProps,
            newProps,
            finishedWork
          );
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      __name(commitHostUpdate, "commitHostUpdate");
      function isHostParent(fiber) {
        return 5 === fiber.tag || 3 === fiber.tag || (supportsResources ? 26 === fiber.tag : false) || (supportsSingletons ? 27 === fiber.tag && isSingletonScope(fiber.type) : false) || 4 === fiber.tag;
      }
      __name(isHostParent, "isHostParent");
      function getHostSibling(fiber) {
        a: for (; ; ) {
          for (; null === fiber.sibling; ) {
            if (null === fiber.return || isHostParent(fiber.return)) return null;
            fiber = fiber.return;
          }
          fiber.sibling.return = fiber.return;
          for (fiber = fiber.sibling; 5 !== fiber.tag && 6 !== fiber.tag && 18 !== fiber.tag; ) {
            if (supportsSingletons && 27 === fiber.tag && isSingletonScope(fiber.type))
              continue a;
            if (fiber.flags & 2) continue a;
            if (null === fiber.child || 4 === fiber.tag) continue a;
            else fiber.child.return = fiber, fiber = fiber.child;
          }
          if (!(fiber.flags & 2)) return fiber.stateNode;
        }
      }
      __name(getHostSibling, "getHostSibling");
      function insertOrAppendPlacementNodeIntoContainer(node, before, parent) {
        var tag2 = node.tag;
        if (5 === tag2 || 6 === tag2)
          node = node.stateNode, before ? insertInContainerBefore(parent, node, before) : appendChildToContainer(parent, node);
        else if (4 !== tag2 && (supportsSingletons && 27 === tag2 && isSingletonScope(node.type) && (parent = node.stateNode, before = null), node = node.child, null !== node))
          for (insertOrAppendPlacementNodeIntoContainer(node, before, parent), node = node.sibling; null !== node; )
            insertOrAppendPlacementNodeIntoContainer(node, before, parent), node = node.sibling;
      }
      __name(insertOrAppendPlacementNodeIntoContainer, "insertOrAppendPlacementNodeIntoContainer");
      function insertOrAppendPlacementNode(node, before, parent) {
        var tag2 = node.tag;
        if (5 === tag2 || 6 === tag2)
          node = node.stateNode, before ? insertBefore(parent, node, before) : appendChild(parent, node);
        else if (4 !== tag2 && (supportsSingletons && 27 === tag2 && isSingletonScope(node.type) && (parent = node.stateNode), node = node.child, null !== node))
          for (insertOrAppendPlacementNode(node, before, parent), node = node.sibling; null !== node; )
            insertOrAppendPlacementNode(node, before, parent), node = node.sibling;
      }
      __name(insertOrAppendPlacementNode, "insertOrAppendPlacementNode");
      function commitPlacement(finishedWork) {
        if (supportsMutation) {
          for (var hostParentFiber, parentFiber = finishedWork.return; null !== parentFiber; ) {
            if (isHostParent(parentFiber)) {
              hostParentFiber = parentFiber;
              break;
            }
            parentFiber = parentFiber.return;
          }
          if (null == hostParentFiber)
            throw Error(
              "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."
            );
          switch (hostParentFiber.tag) {
            case 27:
              if (supportsSingletons) {
                hostParentFiber = hostParentFiber.stateNode;
                parentFiber = getHostSibling(finishedWork);
                insertOrAppendPlacementNode(
                  finishedWork,
                  parentFiber,
                  hostParentFiber
                );
                break;
              }
            case 5:
              parentFiber = hostParentFiber.stateNode;
              hostParentFiber.flags & 32 && (resetTextContent(parentFiber), hostParentFiber.flags &= -33);
              hostParentFiber = getHostSibling(finishedWork);
              insertOrAppendPlacementNode(
                finishedWork,
                hostParentFiber,
                parentFiber
              );
              break;
            case 3:
            case 4:
              hostParentFiber = hostParentFiber.stateNode.containerInfo;
              parentFiber = getHostSibling(finishedWork);
              insertOrAppendPlacementNodeIntoContainer(
                finishedWork,
                parentFiber,
                hostParentFiber
              );
              break;
            default:
              throw Error(
                "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue."
              );
          }
        }
      }
      __name(commitPlacement, "commitPlacement");
      function commitHostPortalContainerChildren(portal, finishedWork, pendingChildren) {
        portal = portal.containerInfo;
        try {
          runWithFiberInDEV(
            finishedWork,
            replaceContainerChildren,
            portal,
            pendingChildren
          );
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      __name(commitHostPortalContainerChildren, "commitHostPortalContainerChildren");
      function commitHostSingletonAcquisition(finishedWork) {
        var singleton = finishedWork.stateNode, props = finishedWork.memoizedProps;
        try {
          runWithFiberInDEV(
            finishedWork,
            acquireSingletonInstance,
            finishedWork.type,
            props,
            singleton,
            finishedWork
          );
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      __name(commitHostSingletonAcquisition, "commitHostSingletonAcquisition");
      function commitBeforeMutationEffects(root, firstChild) {
        prepareForCommit(root.containerInfo);
        for (nextEffect = firstChild; null !== nextEffect; )
          if (root = nextEffect, firstChild = root.child, 0 !== (root.subtreeFlags & 1024) && null !== firstChild)
            firstChild.return = root, nextEffect = firstChild;
          else
            for (; null !== nextEffect; ) {
              firstChild = root = nextEffect;
              var current2 = firstChild.alternate, flags = firstChild.flags;
              switch (firstChild.tag) {
                case 0:
                  break;
                case 11:
                case 15:
                  break;
                case 1:
                  0 !== (flags & 1024) && null !== current2 && commitClassSnapshot(firstChild, current2);
                  break;
                case 3:
                  0 !== (flags & 1024) && supportsMutation && clearContainer(firstChild.stateNode.containerInfo);
                  break;
                case 5:
                case 26:
                case 27:
                case 6:
                case 4:
                case 17:
                  break;
                default:
                  if (0 !== (flags & 1024))
                    throw Error(
                      "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue."
                    );
              }
              firstChild = root.sibling;
              if (null !== firstChild) {
                firstChild.return = root.return;
                nextEffect = firstChild;
                break;
              }
              nextEffect = root.return;
            }
      }
      __name(commitBeforeMutationEffects, "commitBeforeMutationEffects");
      function commitLayoutEffectOnFiber(finishedRoot, current2, finishedWork) {
        var flags = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            flags & 4 && commitHookLayoutEffects(finishedWork, Layout | HasEffect);
            break;
          case 1:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            if (flags & 4)
              if (finishedRoot = finishedWork.stateNode, null === current2)
                finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (finishedRoot.props !== finishedWork.memoizedProps && console.error(
                  "Expected %s props to match memoized props before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.",
                  getComponentNameFromFiber(finishedWork) || "instance"
                ), finishedRoot.state !== finishedWork.memoizedState && console.error(
                  "Expected %s state to match memoized state before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.",
                  getComponentNameFromFiber(finishedWork) || "instance"
                )), shouldProfile(finishedWork) ? (startEffectTimer(), runWithFiberInDEV(
                  finishedWork,
                  callComponentDidMountInDEV,
                  finishedWork,
                  finishedRoot
                ), recordEffectDuration()) : runWithFiberInDEV(
                  finishedWork,
                  callComponentDidMountInDEV,
                  finishedWork,
                  finishedRoot
                );
              else {
                var prevProps = resolveClassComponentProps(
                  finishedWork.type,
                  current2.memoizedProps
                );
                current2 = current2.memoizedState;
                finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (finishedRoot.props !== finishedWork.memoizedProps && console.error(
                  "Expected %s props to match memoized props before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.",
                  getComponentNameFromFiber(finishedWork) || "instance"
                ), finishedRoot.state !== finishedWork.memoizedState && console.error(
                  "Expected %s state to match memoized state before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.",
                  getComponentNameFromFiber(finishedWork) || "instance"
                ));
                shouldProfile(finishedWork) ? (startEffectTimer(), runWithFiberInDEV(
                  finishedWork,
                  callComponentDidUpdateInDEV,
                  finishedWork,
                  finishedRoot,
                  prevProps,
                  current2,
                  finishedRoot.__reactInternalSnapshotBeforeUpdate
                ), recordEffectDuration()) : runWithFiberInDEV(
                  finishedWork,
                  callComponentDidUpdateInDEV,
                  finishedWork,
                  finishedRoot,
                  prevProps,
                  current2,
                  finishedRoot.__reactInternalSnapshotBeforeUpdate
                );
              }
            flags & 64 && commitClassCallbacks(finishedWork);
            flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 3:
            current2 = pushNestedEffectDurations();
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            if (flags & 64 && (flags = finishedWork.updateQueue, null !== flags)) {
              prevProps = null;
              if (null !== finishedWork.child)
                switch (finishedWork.child.tag) {
                  case 27:
                  case 5:
                    prevProps = getPublicInstance(finishedWork.child.stateNode);
                    break;
                  case 1:
                    prevProps = finishedWork.child.stateNode;
                }
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitCallbacks,
                  flags,
                  prevProps
                );
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            }
            finishedRoot.effectDuration += popNestedEffectDurations(current2);
            break;
          case 27:
            supportsSingletons && null === current2 && flags & 4 && commitHostSingletonAcquisition(finishedWork);
          case 26:
          case 5:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            null === current2 && flags & 4 && commitHostMount(finishedWork);
            flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 12:
            if (flags & 4) {
              flags = pushNestedEffectDurations();
              recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
              finishedRoot = finishedWork.stateNode;
              finishedRoot.effectDuration += bubbleNestedEffectDurations(flags);
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitProfiler,
                  finishedWork,
                  current2,
                  commitStartTime,
                  finishedRoot.effectDuration
                );
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            } else recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            break;
          case 13:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
            flags & 64 && (finishedRoot = finishedWork.memoizedState, null !== finishedRoot && (finishedRoot = finishedRoot.dehydrated, null !== finishedRoot && (finishedWork = retryDehydratedSuspenseBoundary.bind(
              null,
              finishedWork
            ), registerSuspenseInstanceRetry(finishedRoot, finishedWork))));
            break;
          case 22:
            flags = null !== finishedWork.memoizedState || offscreenSubtreeIsHidden;
            if (!flags) {
              current2 = null !== current2 && null !== current2.memoizedState || offscreenSubtreeWasHidden;
              prevProps = offscreenSubtreeIsHidden;
              var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
              offscreenSubtreeIsHidden = flags;
              (offscreenSubtreeWasHidden = current2) && !prevOffscreenSubtreeWasHidden ? recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                0 !== (finishedWork.subtreeFlags & 8772)
              ) : recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
              offscreenSubtreeIsHidden = prevProps;
              offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
            }
            break;
          case 30:
            break;
          default:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
        }
      }
      __name(commitLayoutEffectOnFiber, "commitLayoutEffectOnFiber");
      function detachFiberAfterEffects(fiber) {
        var alternate = fiber.alternate;
        null !== alternate && (fiber.alternate = null, detachFiberAfterEffects(alternate));
        fiber.child = null;
        fiber.deletions = null;
        fiber.sibling = null;
        5 === fiber.tag && (alternate = fiber.stateNode, null !== alternate && detachDeletedInstance(alternate));
        fiber.stateNode = null;
        fiber._debugOwner = null;
        fiber.return = null;
        fiber.dependencies = null;
        fiber.memoizedProps = null;
        fiber.memoizedState = null;
        fiber.pendingProps = null;
        fiber.stateNode = null;
        fiber.updateQueue = null;
      }
      __name(detachFiberAfterEffects, "detachFiberAfterEffects");
      function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) {
        for (parent = parent.child; null !== parent; )
          commitDeletionEffectsOnFiber(
            finishedRoot,
            nearestMountedAncestor,
            parent
          ), parent = parent.sibling;
      }
      __name(recursivelyTraverseDeletionEffects, "recursivelyTraverseDeletionEffects");
      function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) {
        if (injectedHook && "function" === typeof injectedHook.onCommitFiberUnmount)
          try {
            injectedHook.onCommitFiberUnmount(rendererID, deletedFiber);
          } catch (err) {
            hasLoggedError || (hasLoggedError = true, console.error(
              "React instrumentation encountered an error: %s",
              err
            ));
          }
        switch (deletedFiber.tag) {
          case 26:
            if (supportsResources) {
              offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
              recursivelyTraverseDeletionEffects(
                finishedRoot,
                nearestMountedAncestor,
                deletedFiber
              );
              deletedFiber.memoizedState ? releaseResource(deletedFiber.memoizedState) : deletedFiber.stateNode && unmountHoistable(deletedFiber.stateNode);
              break;
            }
          case 27:
            if (supportsSingletons) {
              offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
              var prevHostParent = hostParent, prevHostParentIsContainer = hostParentIsContainer;
              isSingletonScope(deletedFiber.type) && (hostParent = deletedFiber.stateNode, hostParentIsContainer = false);
              recursivelyTraverseDeletionEffects(
                finishedRoot,
                nearestMountedAncestor,
                deletedFiber
              );
              runWithFiberInDEV(
                deletedFiber,
                releaseSingletonInstance,
                deletedFiber.stateNode
              );
              hostParent = prevHostParent;
              hostParentIsContainer = prevHostParentIsContainer;
              break;
            }
          case 5:
            offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
          case 6:
            if (supportsMutation) {
              if (prevHostParent = hostParent, prevHostParentIsContainer = hostParentIsContainer, hostParent = null, recursivelyTraverseDeletionEffects(
                finishedRoot,
                nearestMountedAncestor,
                deletedFiber
              ), hostParent = prevHostParent, hostParentIsContainer = prevHostParentIsContainer, null !== hostParent)
                if (hostParentIsContainer)
                  try {
                    runWithFiberInDEV(
                      deletedFiber,
                      removeChildFromContainer,
                      hostParent,
                      deletedFiber.stateNode
                    );
                  } catch (error) {
                    captureCommitPhaseError(
                      deletedFiber,
                      nearestMountedAncestor,
                      error
                    );
                  }
                else
                  try {
                    runWithFiberInDEV(
                      deletedFiber,
                      removeChild,
                      hostParent,
                      deletedFiber.stateNode
                    );
                  } catch (error) {
                    captureCommitPhaseError(
                      deletedFiber,
                      nearestMountedAncestor,
                      error
                    );
                  }
            } else
              recursivelyTraverseDeletionEffects(
                finishedRoot,
                nearestMountedAncestor,
                deletedFiber
              );
            break;
          case 18:
            supportsMutation && null !== hostParent && (hostParentIsContainer ? clearSuspenseBoundaryFromContainer(
              hostParent,
              deletedFiber.stateNode
            ) : clearSuspenseBoundary(hostParent, deletedFiber.stateNode));
            break;
          case 4:
            supportsMutation ? (prevHostParent = hostParent, prevHostParentIsContainer = hostParentIsContainer, hostParent = deletedFiber.stateNode.containerInfo, hostParentIsContainer = true, recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            ), hostParent = prevHostParent, hostParentIsContainer = prevHostParentIsContainer) : (supportsPersistence && commitHostPortalContainerChildren(
              deletedFiber.stateNode,
              deletedFiber,
              createContainerChildSet()
            ), recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            ));
            break;
          case 0:
          case 11:
          case 14:
          case 15:
            offscreenSubtreeWasHidden || commitHookEffectListUnmount(
              Insertion,
              deletedFiber,
              nearestMountedAncestor
            );
            offscreenSubtreeWasHidden || commitHookLayoutUnmountEffects(
              deletedFiber,
              nearestMountedAncestor,
              Layout
            );
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
            break;
          case 1:
            offscreenSubtreeWasHidden || (safelyDetachRef(deletedFiber, nearestMountedAncestor), prevHostParent = deletedFiber.stateNode, "function" === typeof prevHostParent.componentWillUnmount && safelyCallComponentWillUnmount(
              deletedFiber,
              nearestMountedAncestor,
              prevHostParent
            ));
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
            break;
          case 21:
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
            break;
          case 22:
            offscreenSubtreeWasHidden = (prevHostParent = offscreenSubtreeWasHidden) || null !== deletedFiber.memoizedState;
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
            offscreenSubtreeWasHidden = prevHostParent;
            break;
          default:
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
        }
      }
      __name(commitDeletionEffectsOnFiber, "commitDeletionEffectsOnFiber");
      function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
        if (supportsHydration && null === finishedWork.memoizedState && (finishedRoot = finishedWork.alternate, null !== finishedRoot && (finishedRoot = finishedRoot.memoizedState, null !== finishedRoot && (finishedRoot = finishedRoot.dehydrated, null !== finishedRoot))))
          try {
            runWithFiberInDEV(
              finishedWork,
              commitHydratedSuspenseInstance,
              finishedRoot
            );
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
      }
      __name(commitSuspenseHydrationCallbacks, "commitSuspenseHydrationCallbacks");
      function getRetryCache(finishedWork) {
        switch (finishedWork.tag) {
          case 13:
          case 19:
            var retryCache = finishedWork.stateNode;
            null === retryCache && (retryCache = finishedWork.stateNode = new PossiblyWeakSet());
            return retryCache;
          case 22:
            return finishedWork = finishedWork.stateNode, retryCache = finishedWork._retryCache, null === retryCache && (retryCache = finishedWork._retryCache = new PossiblyWeakSet()), retryCache;
          default:
            throw Error(
              "Unexpected Suspense handler tag (" + finishedWork.tag + "). This is a bug in React."
            );
        }
      }
      __name(getRetryCache, "getRetryCache");
      function attachSuspenseRetryListeners(finishedWork, wakeables) {
        var retryCache = getRetryCache(finishedWork);
        wakeables.forEach(function(wakeable) {
          var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);
          if (!retryCache.has(wakeable)) {
            retryCache.add(wakeable);
            if (isDevToolsPresent)
              if (null !== inProgressLanes && null !== inProgressRoot)
                restorePendingUpdaters(inProgressRoot, inProgressLanes);
              else
                throw Error(
                  "Expected finished root and lanes to be set. This is a bug in React."
                );
            wakeable.then(retry, retry);
          }
        });
      }
      __name(attachSuspenseRetryListeners, "attachSuspenseRetryListeners");
      function recursivelyTraverseMutationEffects(root$jscomp$0, parentFiber) {
        var deletions = parentFiber.deletions;
        if (null !== deletions)
          for (var i = 0; i < deletions.length; i++) {
            var root = root$jscomp$0, returnFiber = parentFiber, deletedFiber = deletions[i];
            if (supportsMutation) {
              var parent = returnFiber;
              a: for (; null !== parent; ) {
                switch (parent.tag) {
                  case 27:
                    if (supportsSingletons) {
                      if (isSingletonScope(parent.type)) {
                        hostParent = parent.stateNode;
                        hostParentIsContainer = false;
                        break a;
                      }
                      break;
                    }
                  case 5:
                    hostParent = parent.stateNode;
                    hostParentIsContainer = false;
                    break a;
                  case 3:
                  case 4:
                    hostParent = parent.stateNode.containerInfo;
                    hostParentIsContainer = true;
                    break a;
                }
                parent = parent.return;
              }
              if (null === hostParent)
                throw Error(
                  "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."
                );
              commitDeletionEffectsOnFiber(root, returnFiber, deletedFiber);
              hostParent = null;
              hostParentIsContainer = false;
            } else commitDeletionEffectsOnFiber(root, returnFiber, deletedFiber);
            root = deletedFiber;
            returnFiber = root.alternate;
            null !== returnFiber && (returnFiber.return = null);
            root.return = null;
          }
        if (parentFiber.subtreeFlags & 13878)
          for (parentFiber = parentFiber.child; null !== parentFiber; )
            commitMutationEffectsOnFiber(parentFiber, root$jscomp$0), parentFiber = parentFiber.sibling;
      }
      __name(recursivelyTraverseMutationEffects, "recursivelyTraverseMutationEffects");
      function commitMutationEffectsOnFiber(finishedWork, root) {
        var current2 = finishedWork.alternate, flags = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 14:
          case 15:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags & 4 && (commitHookEffectListUnmount(
              Insertion | HasEffect,
              finishedWork,
              finishedWork.return
            ), commitHookEffectListMount(Insertion | HasEffect, finishedWork), commitHookLayoutUnmountEffects(
              finishedWork,
              finishedWork.return,
              Layout | HasEffect
            ));
            break;
          case 1:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags & 512 && (offscreenSubtreeWasHidden || null === current2 || safelyDetachRef(current2, current2.return));
            flags & 64 && offscreenSubtreeIsHidden && (finishedWork = finishedWork.updateQueue, null !== finishedWork && (flags = finishedWork.callbacks, null !== flags && (current2 = finishedWork.shared.hiddenCallbacks, finishedWork.shared.hiddenCallbacks = null === current2 ? flags : current2.concat(flags))));
            break;
          case 26:
            if (supportsResources) {
              var hoistableRoot = currentHoistableRoot;
              recursivelyTraverseMutationEffects(root, finishedWork);
              commitReconciliationEffects(finishedWork);
              flags & 512 && (offscreenSubtreeWasHidden || null === current2 || safelyDetachRef(current2, current2.return));
              flags & 4 && (flags = null !== current2 ? current2.memoizedState : null, root = finishedWork.memoizedState, null === current2 ? null === root ? null === finishedWork.stateNode ? finishedWork.stateNode = hydrateHoistable(
                hoistableRoot,
                finishedWork.type,
                finishedWork.memoizedProps,
                finishedWork
              ) : mountHoistable(
                hoistableRoot,
                finishedWork.type,
                finishedWork.stateNode
              ) : finishedWork.stateNode = acquireResource(
                hoistableRoot,
                root,
                finishedWork.memoizedProps
              ) : flags !== root ? (null === flags ? null !== current2.stateNode && unmountHoistable(current2.stateNode) : releaseResource(flags), null === root ? mountHoistable(
                hoistableRoot,
                finishedWork.type,
                finishedWork.stateNode
              ) : acquireResource(
                hoistableRoot,
                root,
                finishedWork.memoizedProps
              )) : null === root && null !== finishedWork.stateNode && commitHostUpdate(
                finishedWork,
                finishedWork.memoizedProps,
                current2.memoizedProps
              ));
              break;
            }
          case 27:
            if (supportsSingletons) {
              recursivelyTraverseMutationEffects(root, finishedWork);
              commitReconciliationEffects(finishedWork);
              flags & 512 && (offscreenSubtreeWasHidden || null === current2 || safelyDetachRef(current2, current2.return));
              null !== current2 && flags & 4 && commitHostUpdate(
                finishedWork,
                finishedWork.memoizedProps,
                current2.memoizedProps
              );
              break;
            }
          case 5:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags & 512 && (offscreenSubtreeWasHidden || null === current2 || safelyDetachRef(current2, current2.return));
            if (supportsMutation) {
              if (finishedWork.flags & 32) {
                root = finishedWork.stateNode;
                try {
                  runWithFiberInDEV(finishedWork, resetTextContent, root);
                } catch (error) {
                  captureCommitPhaseError(
                    finishedWork,
                    finishedWork.return,
                    error
                  );
                }
              }
              flags & 4 && null != finishedWork.stateNode && (root = finishedWork.memoizedProps, commitHostUpdate(
                finishedWork,
                root,
                null !== current2 ? current2.memoizedProps : root
              ));
              flags & 1024 && (needsFormReset = true, "form" !== finishedWork.type && console.error(
                "Unexpected host component type. Expected a form. This is a bug in React."
              ));
            }
            break;
          case 6:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            if (flags & 4 && supportsMutation) {
              if (null === finishedWork.stateNode)
                throw Error(
                  "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue."
                );
              flags = finishedWork.memoizedProps;
              current2 = null !== current2 ? current2.memoizedProps : flags;
              root = finishedWork.stateNode;
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitTextUpdate,
                  root,
                  current2,
                  flags
                );
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            }
            break;
          case 3:
            hoistableRoot = pushNestedEffectDurations();
            if (supportsResources) {
              prepareToCommitHoistables();
              var previousHoistableRoot = currentHoistableRoot;
              currentHoistableRoot = getHoistableRoot(root.containerInfo);
              recursivelyTraverseMutationEffects(root, finishedWork);
              currentHoistableRoot = previousHoistableRoot;
            } else recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            if (flags & 4) {
              if (supportsMutation && supportsHydration && null !== current2 && current2.memoizedState.isDehydrated)
                try {
                  runWithFiberInDEV(
                    finishedWork,
                    commitHydratedContainer,
                    root.containerInfo
                  );
                } catch (error) {
                  captureCommitPhaseError(
                    finishedWork,
                    finishedWork.return,
                    error
                  );
                }
              if (supportsPersistence) {
                flags = root.containerInfo;
                current2 = root.pendingChildren;
                try {
                  runWithFiberInDEV(
                    finishedWork,
                    replaceContainerChildren,
                    flags,
                    current2
                  );
                } catch (error) {
                  captureCommitPhaseError(
                    finishedWork,
                    finishedWork.return,
                    error
                  );
                }
              }
            }
            needsFormReset && (needsFormReset = false, recursivelyResetForms(finishedWork));
            root.effectDuration += popNestedEffectDurations(hoistableRoot);
            break;
          case 4:
            supportsResources ? (current2 = currentHoistableRoot, currentHoistableRoot = getHoistableRoot(
              finishedWork.stateNode.containerInfo
            ), recursivelyTraverseMutationEffects(root, finishedWork), commitReconciliationEffects(finishedWork), currentHoistableRoot = current2) : (recursivelyTraverseMutationEffects(root, finishedWork), commitReconciliationEffects(finishedWork));
            flags & 4 && supportsPersistence && commitHostPortalContainerChildren(
              finishedWork.stateNode,
              finishedWork,
              finishedWork.stateNode.pendingChildren
            );
            break;
          case 12:
            flags = pushNestedEffectDurations();
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            finishedWork.stateNode.effectDuration += bubbleNestedEffectDurations(flags);
            break;
          case 13:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            finishedWork.child.flags & 8192 && null !== finishedWork.memoizedState !== (null !== current2 && null !== current2.memoizedState) && (globalMostRecentFallbackTime = now$1());
            flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
            break;
          case 22:
            hoistableRoot = null !== finishedWork.memoizedState;
            var wasHidden = null !== current2 && null !== current2.memoizedState, prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
            offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || hoistableRoot;
            offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || wasHidden;
            recursivelyTraverseMutationEffects(root, finishedWork);
            offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
            offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
            commitReconciliationEffects(finishedWork);
            if (flags & 8192 && (root = finishedWork.stateNode, root._visibility = hoistableRoot ? root._visibility & -2 : root._visibility | 1, hoistableRoot && (null === current2 || wasHidden || offscreenSubtreeIsHidden || offscreenSubtreeWasHidden || recursivelyTraverseDisappearLayoutEffects(finishedWork)), supportsMutation)) {
              a: if (current2 = null, supportsMutation)
                for (root = finishedWork; ; ) {
                  if (5 === root.tag || supportsResources && 26 === root.tag) {
                    if (null === current2) {
                      wasHidden = current2 = root;
                      try {
                        previousHoistableRoot = wasHidden.stateNode, hoistableRoot ? runWithFiberInDEV(
                          wasHidden,
                          hideInstance,
                          previousHoistableRoot
                        ) : runWithFiberInDEV(
                          wasHidden,
                          unhideInstance,
                          wasHidden.stateNode,
                          wasHidden.memoizedProps
                        );
                      } catch (error) {
                        captureCommitPhaseError(
                          wasHidden,
                          wasHidden.return,
                          error
                        );
                      }
                    }
                  } else if (6 === root.tag) {
                    if (null === current2) {
                      wasHidden = root;
                      try {
                        var instance = wasHidden.stateNode;
                        hoistableRoot ? runWithFiberInDEV(
                          wasHidden,
                          hideTextInstance,
                          instance
                        ) : runWithFiberInDEV(
                          wasHidden,
                          unhideTextInstance,
                          instance,
                          wasHidden.memoizedProps
                        );
                      } catch (error) {
                        captureCommitPhaseError(
                          wasHidden,
                          wasHidden.return,
                          error
                        );
                      }
                    }
                  } else if ((22 !== root.tag && 23 !== root.tag || null === root.memoizedState || root === finishedWork) && null !== root.child) {
                    root.child.return = root;
                    root = root.child;
                    continue;
                  }
                  if (root === finishedWork) break a;
                  for (; null === root.sibling; ) {
                    if (null === root.return || root.return === finishedWork)
                      break a;
                    current2 === root && (current2 = null);
                    root = root.return;
                  }
                  current2 === root && (current2 = null);
                  root.sibling.return = root.return;
                  root = root.sibling;
                }
            }
            flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (current2 = flags.retryQueue, null !== current2 && (flags.retryQueue = null, attachSuspenseRetryListeners(finishedWork, current2))));
            break;
          case 19:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
            break;
          case 30:
            break;
          case 21:
            break;
          default:
            recursivelyTraverseMutationEffects(root, finishedWork), commitReconciliationEffects(finishedWork);
        }
      }
      __name(commitMutationEffectsOnFiber, "commitMutationEffectsOnFiber");
      function commitReconciliationEffects(finishedWork) {
        var flags = finishedWork.flags;
        if (flags & 2) {
          try {
            runWithFiberInDEV(finishedWork, commitPlacement, finishedWork);
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
          finishedWork.flags &= -3;
        }
        flags & 4096 && (finishedWork.flags &= -4097);
      }
      __name(commitReconciliationEffects, "commitReconciliationEffects");
      function recursivelyResetForms(parentFiber) {
        if (parentFiber.subtreeFlags & 1024)
          for (parentFiber = parentFiber.child; null !== parentFiber; ) {
            var fiber = parentFiber;
            recursivelyResetForms(fiber);
            5 === fiber.tag && fiber.flags & 1024 && resetFormInstance(fiber.stateNode);
            parentFiber = parentFiber.sibling;
          }
      }
      __name(recursivelyResetForms, "recursivelyResetForms");
      function recursivelyTraverseLayoutEffects(root, parentFiber) {
        if (parentFiber.subtreeFlags & 8772)
          for (parentFiber = parentFiber.child; null !== parentFiber; )
            commitLayoutEffectOnFiber(root, parentFiber.alternate, parentFiber), parentFiber = parentFiber.sibling;
      }
      __name(recursivelyTraverseLayoutEffects, "recursivelyTraverseLayoutEffects");
      function disappearLayoutEffects(finishedWork) {
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 14:
          case 15:
            commitHookLayoutUnmountEffects(
              finishedWork,
              finishedWork.return,
              Layout
            );
            recursivelyTraverseDisappearLayoutEffects(finishedWork);
            break;
          case 1:
            safelyDetachRef(finishedWork, finishedWork.return);
            var instance = finishedWork.stateNode;
            "function" === typeof instance.componentWillUnmount && safelyCallComponentWillUnmount(
              finishedWork,
              finishedWork.return,
              instance
            );
            recursivelyTraverseDisappearLayoutEffects(finishedWork);
            break;
          case 27:
            supportsSingletons && runWithFiberInDEV(
              finishedWork,
              releaseSingletonInstance,
              finishedWork.stateNode
            );
          case 26:
          case 5:
            safelyDetachRef(finishedWork, finishedWork.return);
            recursivelyTraverseDisappearLayoutEffects(finishedWork);
            break;
          case 22:
            null === finishedWork.memoizedState && recursivelyTraverseDisappearLayoutEffects(finishedWork);
            break;
          case 30:
            recursivelyTraverseDisappearLayoutEffects(finishedWork);
            break;
          default:
            recursivelyTraverseDisappearLayoutEffects(finishedWork);
        }
      }
      __name(disappearLayoutEffects, "disappearLayoutEffects");
      function recursivelyTraverseDisappearLayoutEffects(parentFiber) {
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          disappearLayoutEffects(parentFiber), parentFiber = parentFiber.sibling;
      }
      __name(recursivelyTraverseDisappearLayoutEffects, "recursivelyTraverseDisappearLayoutEffects");
      function reappearLayoutEffects(finishedRoot, current2, finishedWork, includeWorkInProgressEffects) {
        var flags = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            commitHookLayoutEffects(finishedWork, Layout);
            break;
          case 1:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            current2 = finishedWork.stateNode;
            "function" === typeof current2.componentDidMount && runWithFiberInDEV(
              finishedWork,
              callComponentDidMountInDEV,
              finishedWork,
              current2
            );
            current2 = finishedWork.updateQueue;
            if (null !== current2) {
              finishedRoot = finishedWork.stateNode;
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitHiddenCallbacks,
                  current2,
                  finishedRoot
                );
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            }
            includeWorkInProgressEffects && flags & 64 && commitClassCallbacks(finishedWork);
            safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 27:
            supportsSingletons && commitHostSingletonAcquisition(finishedWork);
          case 26:
          case 5:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            includeWorkInProgressEffects && null === current2 && flags & 4 && commitHostMount(finishedWork);
            safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 12:
            if (includeWorkInProgressEffects && flags & 4) {
              flags = pushNestedEffectDurations();
              recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                includeWorkInProgressEffects
              );
              includeWorkInProgressEffects = finishedWork.stateNode;
              includeWorkInProgressEffects.effectDuration += bubbleNestedEffectDurations(flags);
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitProfiler,
                  finishedWork,
                  current2,
                  commitStartTime,
                  includeWorkInProgressEffects.effectDuration
                );
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            } else
              recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                includeWorkInProgressEffects
              );
            break;
          case 13:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            includeWorkInProgressEffects && flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
            break;
          case 22:
            null === finishedWork.memoizedState && recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 30:
            break;
          default:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
        }
      }
      __name(reappearLayoutEffects, "reappearLayoutEffects");
      function recursivelyTraverseReappearLayoutEffects(finishedRoot, parentFiber, includeWorkInProgressEffects) {
        includeWorkInProgressEffects = includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 8772);
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          reappearLayoutEffects(
            finishedRoot,
            parentFiber.alternate,
            parentFiber,
            includeWorkInProgressEffects
          ), parentFiber = parentFiber.sibling;
      }
      __name(recursivelyTraverseReappearLayoutEffects, "recursivelyTraverseReappearLayoutEffects");
      function commitOffscreenPassiveMountEffects(current2, finishedWork) {
        var previousCache = null;
        null !== current2 && null !== current2.memoizedState && null !== current2.memoizedState.cachePool && (previousCache = current2.memoizedState.cachePool.pool);
        current2 = null;
        null !== finishedWork.memoizedState && null !== finishedWork.memoizedState.cachePool && (current2 = finishedWork.memoizedState.cachePool.pool);
        current2 !== previousCache && (null != current2 && retainCache(current2), null != previousCache && releaseCache(previousCache));
      }
      __name(commitOffscreenPassiveMountEffects, "commitOffscreenPassiveMountEffects");
      function commitCachePassiveMountEffect(current2, finishedWork) {
        current2 = null;
        null !== finishedWork.alternate && (current2 = finishedWork.alternate.memoizedState.cache);
        finishedWork = finishedWork.memoizedState.cache;
        finishedWork !== current2 && (retainCache(finishedWork), null != current2 && releaseCache(current2));
      }
      __name(commitCachePassiveMountEffect, "commitCachePassiveMountEffect");
      function recursivelyTraversePassiveMountEffects(root, parentFiber, committedLanes, committedTransitions) {
        if (parentFiber.subtreeFlags & 10256)
          for (parentFiber = parentFiber.child; null !== parentFiber; )
            commitPassiveMountOnFiber(
              root,
              parentFiber,
              committedLanes,
              committedTransitions
            ), parentFiber = parentFiber.sibling;
      }
      __name(recursivelyTraversePassiveMountEffects, "recursivelyTraversePassiveMountEffects");
      function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions) {
        var flags = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            flags & 2048 && commitHookPassiveMountEffects(finishedWork, Passive | HasEffect);
            break;
          case 1:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            break;
          case 3:
            var prevEffectDuration = pushNestedEffectDurations();
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            flags & 2048 && (committedLanes = null, null !== finishedWork.alternate && (committedLanes = finishedWork.alternate.memoizedState.cache), finishedWork = finishedWork.memoizedState.cache, finishedWork !== committedLanes && (retainCache(finishedWork), null != committedLanes && releaseCache(committedLanes)));
            finishedRoot.passiveEffectDuration += popNestedEffectDurations(prevEffectDuration);
            break;
          case 12:
            if (flags & 2048) {
              flags = pushNestedEffectDurations();
              recursivelyTraversePassiveMountEffects(
                finishedRoot,
                finishedWork,
                committedLanes,
                committedTransitions
              );
              finishedRoot = finishedWork.stateNode;
              finishedRoot.passiveEffectDuration += bubbleNestedEffectDurations(flags);
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitProfilerPostCommitImpl,
                  finishedWork,
                  finishedWork.alternate,
                  commitStartTime,
                  finishedRoot.passiveEffectDuration
                );
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            } else
              recursivelyTraversePassiveMountEffects(
                finishedRoot,
                finishedWork,
                committedLanes,
                committedTransitions
              );
            break;
          case 13:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            break;
          case 23:
            break;
          case 22:
            prevEffectDuration = finishedWork.stateNode;
            var _current = finishedWork.alternate;
            null !== finishedWork.memoizedState ? prevEffectDuration._visibility & 2 ? recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            ) : recursivelyTraverseAtomicPassiveEffects(
              finishedRoot,
              finishedWork
            ) : prevEffectDuration._visibility & 2 ? recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            ) : (prevEffectDuration._visibility |= 2, recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              0 !== (finishedWork.subtreeFlags & 10256)
            ));
            flags & 2048 && commitOffscreenPassiveMountEffects(_current, finishedWork);
            break;
          case 24:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
            break;
          default:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
        }
      }
      __name(commitPassiveMountOnFiber, "commitPassiveMountOnFiber");
      function recursivelyTraverseReconnectPassiveEffects(finishedRoot, parentFiber, committedLanes, committedTransitions, includeWorkInProgressEffects) {
        includeWorkInProgressEffects = includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 10256);
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          reconnectPassiveEffects(
            finishedRoot,
            parentFiber,
            committedLanes,
            committedTransitions,
            includeWorkInProgressEffects
          ), parentFiber = parentFiber.sibling;
      }
      __name(recursivelyTraverseReconnectPassiveEffects, "recursivelyTraverseReconnectPassiveEffects");
      function reconnectPassiveEffects(finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects) {
        var flags = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              includeWorkInProgressEffects
            );
            commitHookPassiveMountEffects(finishedWork, Passive);
            break;
          case 23:
            break;
          case 22:
            var _instance2 = finishedWork.stateNode;
            null !== finishedWork.memoizedState ? _instance2._visibility & 2 ? recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              includeWorkInProgressEffects
            ) : recursivelyTraverseAtomicPassiveEffects(
              finishedRoot,
              finishedWork
            ) : (_instance2._visibility |= 2, recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              includeWorkInProgressEffects
            ));
            includeWorkInProgressEffects && flags & 2048 && commitOffscreenPassiveMountEffects(
              finishedWork.alternate,
              finishedWork
            );
            break;
          case 24:
            recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              includeWorkInProgressEffects
            );
            includeWorkInProgressEffects && flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
            break;
          default:
            recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              includeWorkInProgressEffects
            );
        }
      }
      __name(reconnectPassiveEffects, "reconnectPassiveEffects");
      function recursivelyTraverseAtomicPassiveEffects(finishedRoot$jscomp$0, parentFiber) {
        if (parentFiber.subtreeFlags & 10256)
          for (parentFiber = parentFiber.child; null !== parentFiber; ) {
            var finishedRoot = finishedRoot$jscomp$0, finishedWork = parentFiber, flags = finishedWork.flags;
            switch (finishedWork.tag) {
              case 22:
                recursivelyTraverseAtomicPassiveEffects(
                  finishedRoot,
                  finishedWork
                );
                flags & 2048 && commitOffscreenPassiveMountEffects(
                  finishedWork.alternate,
                  finishedWork
                );
                break;
              case 24:
                recursivelyTraverseAtomicPassiveEffects(
                  finishedRoot,
                  finishedWork
                );
                flags & 2048 && commitCachePassiveMountEffect(
                  finishedWork.alternate,
                  finishedWork
                );
                break;
              default:
                recursivelyTraverseAtomicPassiveEffects(
                  finishedRoot,
                  finishedWork
                );
            }
            parentFiber = parentFiber.sibling;
          }
      }
      __name(recursivelyTraverseAtomicPassiveEffects, "recursivelyTraverseAtomicPassiveEffects");
      function recursivelyAccumulateSuspenseyCommit(parentFiber) {
        if (parentFiber.subtreeFlags & suspenseyCommitFlag)
          for (parentFiber = parentFiber.child; null !== parentFiber; )
            accumulateSuspenseyCommitOnFiber(parentFiber), parentFiber = parentFiber.sibling;
      }
      __name(recursivelyAccumulateSuspenseyCommit, "recursivelyAccumulateSuspenseyCommit");
      function accumulateSuspenseyCommitOnFiber(fiber) {
        switch (fiber.tag) {
          case 26:
            recursivelyAccumulateSuspenseyCommit(fiber);
            fiber.flags & suspenseyCommitFlag && (null !== fiber.memoizedState ? suspendResource(
              currentHoistableRoot,
              fiber.memoizedState,
              fiber.memoizedProps
            ) : suspendInstance(fiber.type, fiber.memoizedProps));
            break;
          case 5:
            recursivelyAccumulateSuspenseyCommit(fiber);
            fiber.flags & suspenseyCommitFlag && suspendInstance(fiber.type, fiber.memoizedProps);
            break;
          case 3:
          case 4:
            if (supportsResources) {
              var previousHoistableRoot = currentHoistableRoot;
              currentHoistableRoot = getHoistableRoot(
                fiber.stateNode.containerInfo
              );
              recursivelyAccumulateSuspenseyCommit(fiber);
              currentHoistableRoot = previousHoistableRoot;
            } else recursivelyAccumulateSuspenseyCommit(fiber);
            break;
          case 22:
            null === fiber.memoizedState && (previousHoistableRoot = fiber.alternate, null !== previousHoistableRoot && null !== previousHoistableRoot.memoizedState ? (previousHoistableRoot = suspenseyCommitFlag, suspenseyCommitFlag = 16777216, recursivelyAccumulateSuspenseyCommit(fiber), suspenseyCommitFlag = previousHoistableRoot) : recursivelyAccumulateSuspenseyCommit(fiber));
            break;
          default:
            recursivelyAccumulateSuspenseyCommit(fiber);
        }
      }
      __name(accumulateSuspenseyCommitOnFiber, "accumulateSuspenseyCommitOnFiber");
      function detachAlternateSiblings(parentFiber) {
        var previousFiber = parentFiber.alternate;
        if (null !== previousFiber && (parentFiber = previousFiber.child, null !== parentFiber)) {
          previousFiber.child = null;
          do
            previousFiber = parentFiber.sibling, parentFiber.sibling = null, parentFiber = previousFiber;
          while (null !== parentFiber);
        }
      }
      __name(detachAlternateSiblings, "detachAlternateSiblings");
      function recursivelyTraversePassiveUnmountEffects(parentFiber) {
        var deletions = parentFiber.deletions;
        if (0 !== (parentFiber.flags & 16)) {
          if (null !== deletions)
            for (var i = 0; i < deletions.length; i++) {
              var childToDelete = deletions[i];
              nextEffect = childToDelete;
              commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
                childToDelete,
                parentFiber
              );
            }
          detachAlternateSiblings(parentFiber);
        }
        if (parentFiber.subtreeFlags & 10256)
          for (parentFiber = parentFiber.child; null !== parentFiber; )
            commitPassiveUnmountOnFiber(parentFiber), parentFiber = parentFiber.sibling;
      }
      __name(recursivelyTraversePassiveUnmountEffects, "recursivelyTraversePassiveUnmountEffects");
      function commitPassiveUnmountOnFiber(finishedWork) {
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            recursivelyTraversePassiveUnmountEffects(finishedWork);
            finishedWork.flags & 2048 && commitHookPassiveUnmountEffects(
              finishedWork,
              finishedWork.return,
              Passive | HasEffect
            );
            break;
          case 3:
            var prevEffectDuration = pushNestedEffectDurations();
            recursivelyTraversePassiveUnmountEffects(finishedWork);
            finishedWork.stateNode.passiveEffectDuration += popNestedEffectDurations(prevEffectDuration);
            break;
          case 12:
            prevEffectDuration = pushNestedEffectDurations();
            recursivelyTraversePassiveUnmountEffects(finishedWork);
            finishedWork.stateNode.passiveEffectDuration += bubbleNestedEffectDurations(prevEffectDuration);
            break;
          case 22:
            prevEffectDuration = finishedWork.stateNode;
            null !== finishedWork.memoizedState && prevEffectDuration._visibility & 2 && (null === finishedWork.return || 13 !== finishedWork.return.tag) ? (prevEffectDuration._visibility &= -3, recursivelyTraverseDisconnectPassiveEffects(finishedWork)) : recursivelyTraversePassiveUnmountEffects(finishedWork);
            break;
          default:
            recursivelyTraversePassiveUnmountEffects(finishedWork);
        }
      }
      __name(commitPassiveUnmountOnFiber, "commitPassiveUnmountOnFiber");
      function recursivelyTraverseDisconnectPassiveEffects(parentFiber) {
        var deletions = parentFiber.deletions;
        if (0 !== (parentFiber.flags & 16)) {
          if (null !== deletions)
            for (var i = 0; i < deletions.length; i++) {
              var childToDelete = deletions[i];
              nextEffect = childToDelete;
              commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
                childToDelete,
                parentFiber
              );
            }
          detachAlternateSiblings(parentFiber);
        }
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          disconnectPassiveEffect(parentFiber), parentFiber = parentFiber.sibling;
      }
      __name(recursivelyTraverseDisconnectPassiveEffects, "recursivelyTraverseDisconnectPassiveEffects");
      function disconnectPassiveEffect(finishedWork) {
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            commitHookPassiveUnmountEffects(
              finishedWork,
              finishedWork.return,
              Passive
            );
            recursivelyTraverseDisconnectPassiveEffects(finishedWork);
            break;
          case 22:
            var instance = finishedWork.stateNode;
            instance._visibility & 2 && (instance._visibility &= -3, recursivelyTraverseDisconnectPassiveEffects(finishedWork));
            break;
          default:
            recursivelyTraverseDisconnectPassiveEffects(finishedWork);
        }
      }
      __name(disconnectPassiveEffect, "disconnectPassiveEffect");
      function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) {
        for (; null !== nextEffect; ) {
          var fiber = nextEffect, current2 = fiber;
          switch (current2.tag) {
            case 0:
            case 11:
            case 15:
              commitHookPassiveUnmountEffects(
                current2,
                nearestMountedAncestor,
                Passive
              );
              break;
            case 23:
            case 22:
              null !== current2.memoizedState && null !== current2.memoizedState.cachePool && (current2 = current2.memoizedState.cachePool.pool, null != current2 && retainCache(current2));
              break;
            case 24:
              releaseCache(current2.memoizedState.cache);
          }
          current2 = fiber.child;
          if (null !== current2) current2.return = fiber, nextEffect = current2;
          else
            a: for (fiber = deletedSubtreeRoot; null !== nextEffect; ) {
              current2 = nextEffect;
              var sibling = current2.sibling, returnFiber = current2.return;
              detachFiberAfterEffects(current2);
              if (current2 === fiber) {
                nextEffect = null;
                break a;
              }
              if (null !== sibling) {
                sibling.return = returnFiber;
                nextEffect = sibling;
                break a;
              }
              nextEffect = returnFiber;
            }
        }
      }
      __name(commitPassiveUnmountEffectsInsideOfDeletedTree_begin, "commitPassiveUnmountEffectsInsideOfDeletedTree_begin");
      function findFiberRootForHostRoot(hostRoot) {
        var maybeFiber = getInstanceFromNode(hostRoot);
        if (null != maybeFiber) {
          if ("string" !== typeof maybeFiber.memoizedProps["data-testname"])
            throw Error(
              "Invalid host root specified. Should be either a React container or a node with a testname attribute."
            );
          return maybeFiber;
        }
        hostRoot = findFiberRoot(hostRoot);
        if (null === hostRoot)
          throw Error(
            "Could not find React container within specified host subtree."
          );
        return hostRoot.stateNode.current;
      }
      __name(findFiberRootForHostRoot, "findFiberRootForHostRoot");
      function matchSelector(fiber$jscomp$0, selector) {
        var tag2 = fiber$jscomp$0.tag;
        switch (selector.$$typeof) {
          case COMPONENT_TYPE:
            if (fiber$jscomp$0.type === selector.value) return true;
            break;
          case HAS_PSEUDO_CLASS_TYPE:
            a: {
              selector = selector.value;
              fiber$jscomp$0 = [fiber$jscomp$0, 0];
              for (tag2 = 0; tag2 < fiber$jscomp$0.length; ) {
                var fiber = fiber$jscomp$0[tag2++], tag$jscomp$0 = fiber.tag, selectorIndex = fiber$jscomp$0[tag2++], selector$jscomp$0 = selector[selectorIndex];
                if (5 !== tag$jscomp$0 && 26 !== tag$jscomp$0 && 27 !== tag$jscomp$0 || !isHiddenSubtree(fiber)) {
                  for (; null != selector$jscomp$0 && matchSelector(fiber, selector$jscomp$0); )
                    selectorIndex++, selector$jscomp$0 = selector[selectorIndex];
                  if (selectorIndex === selector.length) {
                    selector = true;
                    break a;
                  } else
                    for (fiber = fiber.child; null !== fiber; )
                      fiber$jscomp$0.push(fiber, selectorIndex), fiber = fiber.sibling;
                }
              }
              selector = false;
            }
            return selector;
          case ROLE_TYPE:
            if ((5 === tag2 || 26 === tag2 || 27 === tag2) && matchAccessibilityRole(fiber$jscomp$0.stateNode, selector.value))
              return true;
            break;
          case TEXT_TYPE:
            if (5 === tag2 || 6 === tag2 || 26 === tag2 || 27 === tag2) {
              if (fiber$jscomp$0 = getTextContent(fiber$jscomp$0), null !== fiber$jscomp$0 && 0 <= fiber$jscomp$0.indexOf(selector.value))
                return true;
            }
            break;
          case TEST_NAME_TYPE:
            if (5 === tag2 || 26 === tag2 || 27 === tag2) {
              if (fiber$jscomp$0 = fiber$jscomp$0.memoizedProps["data-testname"], "string" === typeof fiber$jscomp$0 && fiber$jscomp$0.toLowerCase() === selector.value.toLowerCase())
                return true;
            }
            break;
          default:
            throw Error("Invalid selector type specified.");
        }
        return false;
      }
      __name(matchSelector, "matchSelector");
      function selectorToString(selector) {
        switch (selector.$$typeof) {
          case COMPONENT_TYPE:
            return "<" + (getComponentNameFromType(selector.value) || "Unknown") + ">";
          case HAS_PSEUDO_CLASS_TYPE:
            return ":has(" + (selectorToString(selector) || "") + ")";
          case ROLE_TYPE:
            return '[role="' + selector.value + '"]';
          case TEXT_TYPE:
            return '"' + selector.value + '"';
          case TEST_NAME_TYPE:
            return '[data-testname="' + selector.value + '"]';
          default:
            throw Error("Invalid selector type specified.");
        }
      }
      __name(selectorToString, "selectorToString");
      function findPaths(root, selectors) {
        var matchingFibers = [];
        root = [root, 0];
        for (var index = 0; index < root.length; ) {
          var fiber = root[index++], tag2 = fiber.tag, selectorIndex = root[index++], selector = selectors[selectorIndex];
          if (5 !== tag2 && 26 !== tag2 && 27 !== tag2 || !isHiddenSubtree(fiber)) {
            for (; null != selector && matchSelector(fiber, selector); )
              selectorIndex++, selector = selectors[selectorIndex];
            if (selectorIndex === selectors.length) matchingFibers.push(fiber);
            else
              for (fiber = fiber.child; null !== fiber; )
                root.push(fiber, selectorIndex), fiber = fiber.sibling;
          }
        }
        return matchingFibers;
      }
      __name(findPaths, "findPaths");
      function findAllNodes(hostRoot, selectors) {
        if (!supportsTestSelectors)
          throw Error("Test selector API is not supported by this renderer.");
        hostRoot = findFiberRootForHostRoot(hostRoot);
        hostRoot = findPaths(hostRoot, selectors);
        selectors = [];
        hostRoot = Array.from(hostRoot);
        for (var index = 0; index < hostRoot.length; ) {
          var node = hostRoot[index++], tag2 = node.tag;
          if (5 === tag2 || 26 === tag2 || 27 === tag2)
            isHiddenSubtree(node) || selectors.push(node.stateNode);
          else
            for (node = node.child; null !== node; )
              hostRoot.push(node), node = node.sibling;
        }
        return selectors;
      }
      __name(findAllNodes, "findAllNodes");
      function onCommitRoot() {
        supportsTestSelectors && commitHooks.forEach(function(commitHook) {
          return commitHook();
        });
      }
      __name(onCommitRoot, "onCommitRoot");
      function isConcurrentActEnvironment() {
        var isReactActEnvironmentGlobal = "undefined" !== typeof IS_REACT_ACT_ENVIRONMENT ? IS_REACT_ACT_ENVIRONMENT : void 0;
        isReactActEnvironmentGlobal || null === ReactSharedInternals.actQueue || console.error(
          "The current testing environment is not configured to support act(...)"
        );
        return isReactActEnvironmentGlobal;
      }
      __name(isConcurrentActEnvironment, "isConcurrentActEnvironment");
      function requestUpdateLane(fiber) {
        if ((executionContext & RenderContext) !== NoContext && 0 !== workInProgressRootRenderLanes)
          return workInProgressRootRenderLanes & -workInProgressRootRenderLanes;
        var transition = ReactSharedInternals.T;
        return null !== transition ? (transition._updatedFibers || (transition._updatedFibers = /* @__PURE__ */ new Set()), transition._updatedFibers.add(fiber), fiber = currentEntangledLane, 0 !== fiber ? fiber : requestTransitionLane()) : resolveUpdatePriority();
      }
      __name(requestUpdateLane, "requestUpdateLane");
      function requestDeferredLane() {
        0 === workInProgressDeferredLane && (workInProgressDeferredLane = 0 === (workInProgressRootRenderLanes & 536870912) || isHydrating ? claimNextTransitionLane() : 536870912);
        var suspenseHandler = suspenseHandlerStackCursor.current;
        null !== suspenseHandler && (suspenseHandler.flags |= 32);
        return workInProgressDeferredLane;
      }
      __name(requestDeferredLane, "requestDeferredLane");
      function scheduleUpdateOnFiber(root, fiber, lane) {
        isRunningInsertionEffect && console.error("useInsertionEffect must not schedule updates.");
        isFlushingPassiveEffects && (didScheduleUpdateDuringPassiveEffects = true);
        if (root === workInProgressRoot && (workInProgressSuspendedReason === SuspendedOnData || workInProgressSuspendedReason === SuspendedOnAction) || null !== root.cancelPendingCommit)
          prepareFreshStack(root, 0), markRootSuspended(
            root,
            workInProgressRootRenderLanes,
            workInProgressDeferredLane,
            false
          );
        markRootUpdated$1(root, lane);
        if (0 !== (executionContext & RenderContext) && root === workInProgressRoot) {
          if (isRendering)
            switch (fiber.tag) {
              case 0:
              case 11:
              case 15:
                root = workInProgress && getComponentNameFromFiber(workInProgress) || "Unknown";
                didWarnAboutUpdateInRenderForAnotherComponent.has(root) || (didWarnAboutUpdateInRenderForAnotherComponent.add(root), fiber = getComponentNameFromFiber(fiber) || "Unknown", console.error(
                  "Cannot update a component (`%s`) while rendering a different component (`%s`). To locate the bad setState() call inside `%s`, follow the stack trace as described in https://react.dev/link/setstate-in-render",
                  fiber,
                  root,
                  root
                ));
                break;
              case 1:
                didWarnAboutUpdateInRender || (console.error(
                  "Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state."
                ), didWarnAboutUpdateInRender = true);
            }
        } else
          isDevToolsPresent && addFiberToLanesMap(root, fiber, lane), warnIfUpdatesNotWrappedWithActDEV(fiber), root === workInProgressRoot && ((executionContext & RenderContext) === NoContext && (workInProgressRootInterleavedUpdatedLanes |= lane), workInProgressRootExitStatus === RootSuspendedWithDelay && markRootSuspended(
            root,
            workInProgressRootRenderLanes,
            workInProgressDeferredLane,
            false
          )), ensureRootIsScheduled(root);
      }
      __name(scheduleUpdateOnFiber, "scheduleUpdateOnFiber");
      function performWorkOnRoot(root, lanes, forceSync) {
        if ((executionContext & (RenderContext | CommitContext)) !== NoContext)
          throw Error("Should not already be working.");
        var shouldTimeSlice = !forceSync && 0 === (lanes & 124) && 0 === (lanes & root.expiredLanes) || checkIfRootIsPrerendering(root, lanes), exitStatus = shouldTimeSlice ? renderRootConcurrent(root, lanes) : renderRootSync(root, lanes, true), renderWasConcurrent = shouldTimeSlice;
        do {
          if (exitStatus === RootInProgress) {
            workInProgressRootIsPrerendering && !shouldTimeSlice && markRootSuspended(root, lanes, 0, false);
            break;
          } else {
            forceSync = root.current.alternate;
            if (renderWasConcurrent && !isRenderConsistentWithExternalStores(forceSync)) {
              exitStatus = renderRootSync(root, lanes, false);
              renderWasConcurrent = false;
              continue;
            }
            if (exitStatus === RootErrored) {
              renderWasConcurrent = lanes;
              if (root.errorRecoveryDisabledLanes & renderWasConcurrent)
                var errorRetryLanes = 0;
              else
                errorRetryLanes = root.pendingLanes & -536870913, errorRetryLanes = 0 !== errorRetryLanes ? errorRetryLanes : errorRetryLanes & 536870912 ? 536870912 : 0;
              if (0 !== errorRetryLanes) {
                lanes = errorRetryLanes;
                a: {
                  exitStatus = root;
                  var errorRetryLanes$jscomp$0 = errorRetryLanes;
                  errorRetryLanes = workInProgressRootConcurrentErrors;
                  var wasRootDehydrated = supportsHydration && exitStatus.current.memoizedState.isDehydrated;
                  wasRootDehydrated && (prepareFreshStack(
                    exitStatus,
                    errorRetryLanes$jscomp$0
                  ).flags |= 256);
                  errorRetryLanes$jscomp$0 = renderRootSync(
                    exitStatus,
                    errorRetryLanes$jscomp$0,
                    false
                  );
                  if (errorRetryLanes$jscomp$0 !== RootErrored) {
                    if (workInProgressRootDidAttachPingListener && !wasRootDehydrated) {
                      exitStatus.errorRecoveryDisabledLanes |= renderWasConcurrent;
                      workInProgressRootInterleavedUpdatedLanes |= renderWasConcurrent;
                      exitStatus = RootSuspendedWithDelay;
                      break a;
                    }
                    exitStatus = workInProgressRootRecoverableErrors;
                    workInProgressRootRecoverableErrors = errorRetryLanes;
                    null !== exitStatus && (null === workInProgressRootRecoverableErrors ? workInProgressRootRecoverableErrors = exitStatus : workInProgressRootRecoverableErrors.push.apply(
                      workInProgressRootRecoverableErrors,
                      exitStatus
                    ));
                  }
                  exitStatus = errorRetryLanes$jscomp$0;
                }
                renderWasConcurrent = false;
                if (exitStatus !== RootErrored) continue;
              }
            }
            if (exitStatus === RootFatalErrored) {
              prepareFreshStack(root, 0);
              markRootSuspended(root, lanes, 0, true);
              break;
            }
            a: {
              shouldTimeSlice = root;
              switch (exitStatus) {
                case RootInProgress:
                case RootFatalErrored:
                  throw Error("Root did not complete. This is a bug in React.");
                case RootSuspendedWithDelay:
                  if ((lanes & 4194048) !== lanes) break;
                case RootSuspendedAtTheShell:
                  markRootSuspended(
                    shouldTimeSlice,
                    lanes,
                    workInProgressDeferredLane,
                    !workInProgressRootDidSkipSuspendedSiblings
                  );
                  break a;
                case RootErrored:
                  workInProgressRootRecoverableErrors = null;
                  break;
                case RootSuspended:
                case RootCompleted:
                  break;
                default:
                  throw Error("Unknown root exit status.");
              }
              if (null !== ReactSharedInternals.actQueue)
                commitRoot(
                  shouldTimeSlice,
                  forceSync,
                  lanes,
                  workInProgressRootRecoverableErrors,
                  workInProgressTransitions,
                  workInProgressRootDidIncludeRecursiveRenderUpdate,
                  workInProgressDeferredLane,
                  workInProgressRootInterleavedUpdatedLanes,
                  workInProgressSuspendedRetryLanes
                );
              else {
                if ((lanes & 62914560) === lanes && (renderWasConcurrent = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now$1(), 10 < renderWasConcurrent)) {
                  markRootSuspended(
                    shouldTimeSlice,
                    lanes,
                    workInProgressDeferredLane,
                    !workInProgressRootDidSkipSuspendedSiblings
                  );
                  if (0 !== getNextLanes(shouldTimeSlice, 0, true)) break a;
                  shouldTimeSlice.timeoutHandle = scheduleTimeout(
                    commitRootWhenReady.bind(
                      null,
                      shouldTimeSlice,
                      forceSync,
                      workInProgressRootRecoverableErrors,
                      workInProgressTransitions,
                      workInProgressRootDidIncludeRecursiveRenderUpdate,
                      lanes,
                      workInProgressDeferredLane,
                      workInProgressRootInterleavedUpdatedLanes,
                      workInProgressSuspendedRetryLanes,
                      workInProgressRootDidSkipSuspendedSiblings,
                      exitStatus,
                      THROTTLED_COMMIT,
                      -0,
                      0
                    ),
                    renderWasConcurrent
                  );
                  break a;
                }
                commitRootWhenReady(
                  shouldTimeSlice,
                  forceSync,
                  workInProgressRootRecoverableErrors,
                  workInProgressTransitions,
                  workInProgressRootDidIncludeRecursiveRenderUpdate,
                  lanes,
                  workInProgressDeferredLane,
                  workInProgressRootInterleavedUpdatedLanes,
                  workInProgressSuspendedRetryLanes,
                  workInProgressRootDidSkipSuspendedSiblings,
                  exitStatus,
                  IMMEDIATE_COMMIT,
                  -0,
                  0
                );
              }
            }
          }
          break;
        } while (1);
        ensureRootIsScheduled(root);
      }
      __name(performWorkOnRoot, "performWorkOnRoot");
      function commitRootWhenReady(root, finishedWork, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, lanes, spawnedLane, updatedLanes, suspendedRetryLanes, didSkipSuspendedSiblings, exitStatus, suspendedCommitReason, completedRenderStartTime, completedRenderEndTime) {
        root.timeoutHandle = noTimeout;
        suspendedCommitReason = finishedWork.subtreeFlags;
        if (suspendedCommitReason & 8192 || 16785408 === (suspendedCommitReason & 16785408)) {
          if (startSuspendingCommit(), accumulateSuspenseyCommitOnFiber(finishedWork), suspendedCommitReason = waitForCommitToBeReady(), null !== suspendedCommitReason) {
            root.cancelPendingCommit = suspendedCommitReason(
              commitRoot.bind(
                null,
                root,
                finishedWork,
                lanes,
                recoverableErrors,
                transitions,
                didIncludeRenderPhaseUpdate,
                spawnedLane,
                updatedLanes,
                suspendedRetryLanes,
                exitStatus,
                SUSPENDED_COMMIT,
                completedRenderStartTime,
                completedRenderEndTime
              )
            );
            markRootSuspended(
              root,
              lanes,
              spawnedLane,
              !didSkipSuspendedSiblings
            );
            return;
          }
        }
        commitRoot(
          root,
          finishedWork,
          lanes,
          recoverableErrors,
          transitions,
          didIncludeRenderPhaseUpdate,
          spawnedLane,
          updatedLanes,
          suspendedRetryLanes
        );
      }
      __name(commitRootWhenReady, "commitRootWhenReady");
      function isRenderConsistentWithExternalStores(finishedWork) {
        for (var node = finishedWork; ; ) {
          var tag2 = node.tag;
          if ((0 === tag2 || 11 === tag2 || 15 === tag2) && node.flags & 16384 && (tag2 = node.updateQueue, null !== tag2 && (tag2 = tag2.stores, null !== tag2)))
            for (var i = 0; i < tag2.length; i++) {
              var check = tag2[i], getSnapshot = check.getSnapshot;
              check = check.value;
              try {
                if (!objectIs(getSnapshot(), check)) return false;
              } catch (error) {
                return false;
              }
            }
          tag2 = node.child;
          if (node.subtreeFlags & 16384 && null !== tag2)
            tag2.return = node, node = tag2;
          else {
            if (node === finishedWork) break;
            for (; null === node.sibling; ) {
              if (null === node.return || node.return === finishedWork) return true;
              node = node.return;
            }
            node.sibling.return = node.return;
            node = node.sibling;
          }
        }
        return true;
      }
      __name(isRenderConsistentWithExternalStores, "isRenderConsistentWithExternalStores");
      function markRootSuspended(root, suspendedLanes, spawnedLane, didAttemptEntireTree) {
        suspendedLanes &= ~workInProgressRootPingedLanes;
        suspendedLanes &= ~workInProgressRootInterleavedUpdatedLanes;
        root.suspendedLanes |= suspendedLanes;
        root.pingedLanes &= ~suspendedLanes;
        didAttemptEntireTree && (root.warmLanes |= suspendedLanes);
        didAttemptEntireTree = root.expirationTimes;
        for (var lanes = suspendedLanes; 0 < lanes; ) {
          var index = 31 - clz32(lanes), lane = 1 << index;
          didAttemptEntireTree[index] = -1;
          lanes &= ~lane;
        }
        0 !== spawnedLane && markSpawnedDeferredLane(root, spawnedLane, suspendedLanes);
      }
      __name(markRootSuspended, "markRootSuspended");
      function flushSyncWork() {
        return (executionContext & (RenderContext | CommitContext)) === NoContext ? (flushSyncWorkAcrossRoots_impl(0, false), false) : true;
      }
      __name(flushSyncWork, "flushSyncWork");
      function resetWorkInProgressStack() {
        if (null !== workInProgress) {
          if (workInProgressSuspendedReason === NotSuspended)
            var interruptedWork = workInProgress.return;
          else
            interruptedWork = workInProgress, resetContextDependencies(), resetHooksOnUnwind(interruptedWork), thenableState = null, thenableIndexCounter = 0, interruptedWork = workInProgress;
          for (; null !== interruptedWork; )
            unwindInterruptedWork(interruptedWork.alternate, interruptedWork), interruptedWork = interruptedWork.return;
          workInProgress = null;
        }
      }
      __name(resetWorkInProgressStack, "resetWorkInProgressStack");
      function prepareFreshStack(root, lanes) {
        var timeoutHandle = root.timeoutHandle;
        timeoutHandle !== noTimeout && (root.timeoutHandle = noTimeout, cancelTimeout(timeoutHandle));
        timeoutHandle = root.cancelPendingCommit;
        null !== timeoutHandle && (root.cancelPendingCommit = null, timeoutHandle());
        resetWorkInProgressStack();
        workInProgressRoot = root;
        workInProgress = timeoutHandle = createWorkInProgress(root.current, null);
        workInProgressRootRenderLanes = lanes;
        workInProgressSuspendedReason = NotSuspended;
        workInProgressThrownValue = null;
        workInProgressRootDidSkipSuspendedSiblings = false;
        workInProgressRootIsPrerendering = checkIfRootIsPrerendering(root, lanes);
        workInProgressRootDidAttachPingListener = false;
        workInProgressRootExitStatus = RootInProgress;
        workInProgressSuspendedRetryLanes = workInProgressDeferredLane = workInProgressRootPingedLanes = workInProgressRootInterleavedUpdatedLanes = workInProgressRootSkippedLanes = 0;
        workInProgressRootRecoverableErrors = workInProgressRootConcurrentErrors = null;
        workInProgressRootDidIncludeRecursiveRenderUpdate = false;
        0 !== (lanes & 8) && (lanes |= lanes & 32);
        var allEntangledLanes = root.entangledLanes;
        if (0 !== allEntangledLanes)
          for (root = root.entanglements, allEntangledLanes &= lanes; 0 < allEntangledLanes; ) {
            var index = 31 - clz32(allEntangledLanes), lane = 1 << index;
            lanes |= root[index];
            allEntangledLanes &= ~lane;
          }
        entangledRenderLanes = lanes;
        finishQueueingConcurrentUpdates();
        lanes = getCurrentTime();
        1e3 < lanes - lastResetTime && (ReactSharedInternals.recentlyCreatedOwnerStacks = 0, lastResetTime = lanes);
        ReactStrictModeWarnings.discardPendingWarnings();
        return timeoutHandle;
      }
      __name(prepareFreshStack, "prepareFreshStack");
      function handleThrow(root, thrownValue) {
        currentlyRenderingFiber = null;
        ReactSharedInternals.H = ContextOnlyDispatcher;
        ReactSharedInternals.getCurrentStack = null;
        isRendering = false;
        current = null;
        thrownValue === SuspenseException || thrownValue === SuspenseActionException ? (thrownValue = getSuspendedThenable(), workInProgressSuspendedReason = SuspendedOnImmediate) : thrownValue === SuspenseyCommitException ? (thrownValue = getSuspendedThenable(), workInProgressSuspendedReason = SuspendedOnInstance) : workInProgressSuspendedReason = thrownValue === SelectiveHydrationException ? SuspendedOnHydration : null !== thrownValue && "object" === typeof thrownValue && "function" === typeof thrownValue.then ? SuspendedOnDeprecatedThrowPromise : SuspendedOnError;
        workInProgressThrownValue = thrownValue;
        var erroredWork = workInProgress;
        if (null === erroredWork)
          workInProgressRootExitStatus = RootFatalErrored, logUncaughtError(
            root,
            createCapturedValueAtFiber(thrownValue, root.current)
          );
        else
          switch (erroredWork.mode & 2 && stopProfilerTimerIfRunningAndRecordDuration(erroredWork), markComponentRenderStopped(), workInProgressSuspendedReason) {
            case SuspendedOnError:
              null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentErrored && injectedProfilingHooks.markComponentErrored(
                erroredWork,
                thrownValue,
                workInProgressRootRenderLanes
              );
              break;
            case SuspendedOnData:
            case SuspendedOnAction:
            case SuspendedOnImmediate:
            case SuspendedOnDeprecatedThrowPromise:
            case SuspendedAndReadyToContinue:
              null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentSuspended && injectedProfilingHooks.markComponentSuspended(
                erroredWork,
                thrownValue,
                workInProgressRootRenderLanes
              );
          }
      }
      __name(handleThrow, "handleThrow");
      function shouldRemainOnPreviousScreen() {
        var handler = suspenseHandlerStackCursor.current;
        return null === handler ? true : (workInProgressRootRenderLanes & 4194048) === workInProgressRootRenderLanes ? null === shellBoundary ? true : false : (workInProgressRootRenderLanes & 62914560) === workInProgressRootRenderLanes || 0 !== (workInProgressRootRenderLanes & 536870912) ? handler === shellBoundary : false;
      }
      __name(shouldRemainOnPreviousScreen, "shouldRemainOnPreviousScreen");
      function pushDispatcher() {
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = ContextOnlyDispatcher;
        return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher;
      }
      __name(pushDispatcher, "pushDispatcher");
      function pushAsyncDispatcher() {
        var prevAsyncDispatcher = ReactSharedInternals.A;
        ReactSharedInternals.A = DefaultAsyncDispatcher;
        return prevAsyncDispatcher;
      }
      __name(pushAsyncDispatcher, "pushAsyncDispatcher");
      function renderDidSuspendDelayIfPossible() {
        workInProgressRootExitStatus = RootSuspendedWithDelay;
        workInProgressRootDidSkipSuspendedSiblings || (workInProgressRootRenderLanes & 4194048) !== workInProgressRootRenderLanes && null !== suspenseHandlerStackCursor.current || (workInProgressRootIsPrerendering = true);
        0 === (workInProgressRootSkippedLanes & 134217727) && 0 === (workInProgressRootInterleavedUpdatedLanes & 134217727) || null === workInProgressRoot || markRootSuspended(
          workInProgressRoot,
          workInProgressRootRenderLanes,
          workInProgressDeferredLane,
          false
        );
      }
      __name(renderDidSuspendDelayIfPossible, "renderDidSuspendDelayIfPossible");
      function renderRootSync(root, lanes, shouldYieldForPrerendering) {
        var prevExecutionContext = executionContext;
        executionContext |= RenderContext;
        var prevDispatcher = pushDispatcher(), prevAsyncDispatcher = pushAsyncDispatcher();
        if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) {
          if (isDevToolsPresent) {
            var memoizedUpdaters = root.memoizedUpdaters;
            0 < memoizedUpdaters.size && (restorePendingUpdaters(root, workInProgressRootRenderLanes), memoizedUpdaters.clear());
            movePendingFibersToMemoized(root, lanes);
          }
          workInProgressTransitions = null;
          prepareFreshStack(root, lanes);
        }
        markRenderStarted(lanes);
        lanes = false;
        memoizedUpdaters = workInProgressRootExitStatus;
        a: do
          try {
            if (workInProgressSuspendedReason !== NotSuspended && null !== workInProgress) {
              var unitOfWork = workInProgress, thrownValue = workInProgressThrownValue;
              switch (workInProgressSuspendedReason) {
                case SuspendedOnHydration:
                  resetWorkInProgressStack();
                  memoizedUpdaters = RootSuspendedAtTheShell;
                  break a;
                case SuspendedOnImmediate:
                case SuspendedOnData:
                case SuspendedOnAction:
                case SuspendedOnDeprecatedThrowPromise:
                  null === suspenseHandlerStackCursor.current && (lanes = true);
                  var reason = workInProgressSuspendedReason;
                  workInProgressSuspendedReason = NotSuspended;
                  workInProgressThrownValue = null;
                  throwAndUnwindWorkLoop(root, unitOfWork, thrownValue, reason);
                  if (shouldYieldForPrerendering && workInProgressRootIsPrerendering) {
                    memoizedUpdaters = RootInProgress;
                    break a;
                  }
                  break;
                default:
                  reason = workInProgressSuspendedReason, workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, throwAndUnwindWorkLoop(root, unitOfWork, thrownValue, reason);
              }
            }
            workLoopSync();
            memoizedUpdaters = workInProgressRootExitStatus;
            break;
          } catch (thrownValue$4) {
            handleThrow(root, thrownValue$4);
          }
        while (1);
        lanes && root.shellSuspendCounter++;
        resetContextDependencies();
        executionContext = prevExecutionContext;
        ReactSharedInternals.H = prevDispatcher;
        ReactSharedInternals.A = prevAsyncDispatcher;
        markRenderStopped();
        null === workInProgress && (workInProgressRoot = null, workInProgressRootRenderLanes = 0, finishQueueingConcurrentUpdates());
        return memoizedUpdaters;
      }
      __name(renderRootSync, "renderRootSync");
      function workLoopSync() {
        for (; null !== workInProgress; ) performUnitOfWork(workInProgress);
      }
      __name(workLoopSync, "workLoopSync");
      function renderRootConcurrent(root, lanes) {
        var prevExecutionContext = executionContext;
        executionContext |= RenderContext;
        var prevDispatcher = pushDispatcher(), prevAsyncDispatcher = pushAsyncDispatcher();
        if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) {
          if (isDevToolsPresent) {
            var memoizedUpdaters = root.memoizedUpdaters;
            0 < memoizedUpdaters.size && (restorePendingUpdaters(root, workInProgressRootRenderLanes), memoizedUpdaters.clear());
            movePendingFibersToMemoized(root, lanes);
          }
          workInProgressTransitions = null;
          workInProgressRootRenderTargetTime = now$1() + RENDER_TIMEOUT_MS;
          prepareFreshStack(root, lanes);
        } else
          workInProgressRootIsPrerendering = checkIfRootIsPrerendering(
            root,
            lanes
          );
        markRenderStarted(lanes);
        a: do
          try {
            if (workInProgressSuspendedReason !== NotSuspended && null !== workInProgress)
              b: switch (lanes = workInProgress, memoizedUpdaters = workInProgressThrownValue, workInProgressSuspendedReason) {
                case SuspendedOnError:
                  workInProgressSuspendedReason = NotSuspended;
                  workInProgressThrownValue = null;
                  throwAndUnwindWorkLoop(
                    root,
                    lanes,
                    memoizedUpdaters,
                    SuspendedOnError
                  );
                  break;
                case SuspendedOnData:
                case SuspendedOnAction:
                  if (isThenableResolved(memoizedUpdaters)) {
                    workInProgressSuspendedReason = NotSuspended;
                    workInProgressThrownValue = null;
                    replaySuspendedUnitOfWork(lanes);
                    break;
                  }
                  lanes = /* @__PURE__ */ __name(function() {
                    workInProgressSuspendedReason !== SuspendedOnData && workInProgressSuspendedReason !== SuspendedOnAction || workInProgressRoot !== root || (workInProgressSuspendedReason = SuspendedAndReadyToContinue);
                    ensureRootIsScheduled(root);
                  }, "lanes");
                  memoizedUpdaters.then(lanes, lanes);
                  break a;
                case SuspendedOnImmediate:
                  workInProgressSuspendedReason = SuspendedAndReadyToContinue;
                  break a;
                case SuspendedOnInstance:
                  workInProgressSuspendedReason = SuspendedOnInstanceAndReadyToContinue;
                  break a;
                case SuspendedAndReadyToContinue:
                  isThenableResolved(memoizedUpdaters) ? (workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, replaySuspendedUnitOfWork(lanes)) : (workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, throwAndUnwindWorkLoop(
                    root,
                    lanes,
                    memoizedUpdaters,
                    SuspendedAndReadyToContinue
                  ));
                  break;
                case SuspendedOnInstanceAndReadyToContinue:
                  var resource = null;
                  switch (workInProgress.tag) {
                    case 26:
                      resource = workInProgress.memoizedState;
                    case 5:
                    case 27:
                      var hostFiber = workInProgress, type = hostFiber.type, props = hostFiber.pendingProps;
                      if (resource ? preloadResource(resource) : preloadInstance(type, props)) {
                        workInProgressSuspendedReason = NotSuspended;
                        workInProgressThrownValue = null;
                        var sibling = hostFiber.sibling;
                        if (null !== sibling) workInProgress = sibling;
                        else {
                          var returnFiber = hostFiber.return;
                          null !== returnFiber ? (workInProgress = returnFiber, completeUnitOfWork(returnFiber)) : workInProgress = null;
                        }
                        break b;
                      }
                      break;
                    default:
                      console.error(
                        "Unexpected type of fiber triggered a suspensey commit. This is a bug in React."
                      );
                  }
                  workInProgressSuspendedReason = NotSuspended;
                  workInProgressThrownValue = null;
                  throwAndUnwindWorkLoop(
                    root,
                    lanes,
                    memoizedUpdaters,
                    SuspendedOnInstanceAndReadyToContinue
                  );
                  break;
                case SuspendedOnDeprecatedThrowPromise:
                  workInProgressSuspendedReason = NotSuspended;
                  workInProgressThrownValue = null;
                  throwAndUnwindWorkLoop(
                    root,
                    lanes,
                    memoizedUpdaters,
                    SuspendedOnDeprecatedThrowPromise
                  );
                  break;
                case SuspendedOnHydration:
                  resetWorkInProgressStack();
                  workInProgressRootExitStatus = RootSuspendedAtTheShell;
                  break a;
                default:
                  throw Error(
                    "Unexpected SuspendedReason. This is a bug in React."
                  );
              }
            null !== ReactSharedInternals.actQueue ? workLoopSync() : workLoopConcurrentByScheduler();
            break;
          } catch (thrownValue$5) {
            handleThrow(root, thrownValue$5);
          }
        while (1);
        resetContextDependencies();
        ReactSharedInternals.H = prevDispatcher;
        ReactSharedInternals.A = prevAsyncDispatcher;
        executionContext = prevExecutionContext;
        if (null !== workInProgress)
          return null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markRenderYielded && injectedProfilingHooks.markRenderYielded(), RootInProgress;
        markRenderStopped();
        workInProgressRoot = null;
        workInProgressRootRenderLanes = 0;
        finishQueueingConcurrentUpdates();
        return workInProgressRootExitStatus;
      }
      __name(renderRootConcurrent, "renderRootConcurrent");
      function workLoopConcurrentByScheduler() {
        for (; null !== workInProgress && !shouldYield(); )
          performUnitOfWork(workInProgress);
      }
      __name(workLoopConcurrentByScheduler, "workLoopConcurrentByScheduler");
      function performUnitOfWork(unitOfWork) {
        var current2 = unitOfWork.alternate;
        (unitOfWork.mode & 2) !== NoMode ? (startProfilerTimer(unitOfWork), current2 = runWithFiberInDEV(
          unitOfWork,
          beginWork,
          current2,
          unitOfWork,
          entangledRenderLanes
        ), stopProfilerTimerIfRunningAndRecordDuration(unitOfWork)) : current2 = runWithFiberInDEV(
          unitOfWork,
          beginWork,
          current2,
          unitOfWork,
          entangledRenderLanes
        );
        unitOfWork.memoizedProps = unitOfWork.pendingProps;
        null === current2 ? completeUnitOfWork(unitOfWork) : workInProgress = current2;
      }
      __name(performUnitOfWork, "performUnitOfWork");
      function replaySuspendedUnitOfWork(unitOfWork) {
        var next = runWithFiberInDEV(unitOfWork, replayBeginWork, unitOfWork);
        unitOfWork.memoizedProps = unitOfWork.pendingProps;
        null === next ? completeUnitOfWork(unitOfWork) : workInProgress = next;
      }
      __name(replaySuspendedUnitOfWork, "replaySuspendedUnitOfWork");
      function replayBeginWork(unitOfWork) {
        var current2 = unitOfWork.alternate, isProfilingMode = (unitOfWork.mode & 2) !== NoMode;
        isProfilingMode && startProfilerTimer(unitOfWork);
        switch (unitOfWork.tag) {
          case 15:
          case 0:
            current2 = replayFunctionComponent(
              current2,
              unitOfWork,
              unitOfWork.pendingProps,
              unitOfWork.type,
              void 0,
              workInProgressRootRenderLanes
            );
            break;
          case 11:
            current2 = replayFunctionComponent(
              current2,
              unitOfWork,
              unitOfWork.pendingProps,
              unitOfWork.type.render,
              unitOfWork.ref,
              workInProgressRootRenderLanes
            );
            break;
          case 5:
            resetHooksOnUnwind(unitOfWork);
          default:
            unwindInterruptedWork(current2, unitOfWork), unitOfWork = workInProgress = resetWorkInProgress(unitOfWork, entangledRenderLanes), current2 = beginWork(current2, unitOfWork, entangledRenderLanes);
        }
        isProfilingMode && stopProfilerTimerIfRunningAndRecordDuration(unitOfWork);
        return current2;
      }
      __name(replayBeginWork, "replayBeginWork");
      function throwAndUnwindWorkLoop(root, unitOfWork, thrownValue, suspendedReason) {
        resetContextDependencies();
        resetHooksOnUnwind(unitOfWork);
        thenableState = null;
        thenableIndexCounter = 0;
        var returnFiber = unitOfWork.return;
        try {
          if (throwException(
            root,
            returnFiber,
            unitOfWork,
            thrownValue,
            workInProgressRootRenderLanes
          )) {
            workInProgressRootExitStatus = RootFatalErrored;
            logUncaughtError(
              root,
              createCapturedValueAtFiber(thrownValue, root.current)
            );
            workInProgress = null;
            return;
          }
        } catch (error) {
          if (null !== returnFiber) throw workInProgress = returnFiber, error;
          workInProgressRootExitStatus = RootFatalErrored;
          logUncaughtError(
            root,
            createCapturedValueAtFiber(thrownValue, root.current)
          );
          workInProgress = null;
          return;
        }
        if (unitOfWork.flags & 32768) {
          if (isHydrating || suspendedReason === SuspendedOnError) root = true;
          else if (workInProgressRootIsPrerendering || 0 !== (workInProgressRootRenderLanes & 536870912))
            root = false;
          else if (workInProgressRootDidSkipSuspendedSiblings = root = true, suspendedReason === SuspendedOnData || suspendedReason === SuspendedOnAction || suspendedReason === SuspendedOnImmediate || suspendedReason === SuspendedOnDeprecatedThrowPromise)
            suspendedReason = suspenseHandlerStackCursor.current, null !== suspendedReason && 13 === suspendedReason.tag && (suspendedReason.flags |= 16384);
          unwindUnitOfWork(unitOfWork, root);
        } else completeUnitOfWork(unitOfWork);
      }
      __name(throwAndUnwindWorkLoop, "throwAndUnwindWorkLoop");
      function completeUnitOfWork(unitOfWork) {
        var completedWork = unitOfWork;
        do {
          if (0 !== (completedWork.flags & 32768)) {
            unwindUnitOfWork(
              completedWork,
              workInProgressRootDidSkipSuspendedSiblings
            );
            return;
          }
          var current2 = completedWork.alternate;
          unitOfWork = completedWork.return;
          startProfilerTimer(completedWork);
          current2 = runWithFiberInDEV(
            completedWork,
            completeWork,
            current2,
            completedWork,
            entangledRenderLanes
          );
          (completedWork.mode & 2) !== NoMode && stopProfilerTimerIfRunningAndRecordIncompleteDuration(completedWork);
          if (null !== current2) {
            workInProgress = current2;
            return;
          }
          completedWork = completedWork.sibling;
          if (null !== completedWork) {
            workInProgress = completedWork;
            return;
          }
          workInProgress = completedWork = unitOfWork;
        } while (null !== completedWork);
        workInProgressRootExitStatus === RootInProgress && (workInProgressRootExitStatus = RootCompleted);
      }
      __name(completeUnitOfWork, "completeUnitOfWork");
      function unwindUnitOfWork(unitOfWork, skipSiblings) {
        do {
          var next = unwindWork(unitOfWork.alternate, unitOfWork);
          if (null !== next) {
            next.flags &= 32767;
            workInProgress = next;
            return;
          }
          if ((unitOfWork.mode & 2) !== NoMode) {
            stopProfilerTimerIfRunningAndRecordIncompleteDuration(unitOfWork);
            next = unitOfWork.actualDuration;
            for (var child = unitOfWork.child; null !== child; )
              next += child.actualDuration, child = child.sibling;
            unitOfWork.actualDuration = next;
          }
          next = unitOfWork.return;
          null !== next && (next.flags |= 32768, next.subtreeFlags = 0, next.deletions = null);
          if (!skipSiblings && (unitOfWork = unitOfWork.sibling, null !== unitOfWork)) {
            workInProgress = unitOfWork;
            return;
          }
          workInProgress = unitOfWork = next;
        } while (null !== unitOfWork);
        workInProgressRootExitStatus = RootSuspendedAtTheShell;
        workInProgress = null;
      }
      __name(unwindUnitOfWork, "unwindUnitOfWork");
      function commitRoot(root, finishedWork, lanes, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, spawnedLane, updatedLanes, suspendedRetryLanes) {
        root.cancelPendingCommit = null;
        do
          flushPendingEffects();
        while (pendingEffectsStatus !== NO_PENDING_EFFECTS);
        ReactStrictModeWarnings.flushLegacyContextWarning();
        ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
        if ((executionContext & (RenderContext | CommitContext)) !== NoContext)
          throw Error("Should not already be working.");
        null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markCommitStarted && injectedProfilingHooks.markCommitStarted(lanes);
        if (null === finishedWork) markCommitStopped();
        else {
          0 === lanes && console.error(
            "finishedLanes should not be empty during a commit. This is a bug in React."
          );
          if (finishedWork === root.current)
            throw Error(
              "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue."
            );
          didIncludeRenderPhaseUpdate = finishedWork.lanes | finishedWork.childLanes;
          didIncludeRenderPhaseUpdate |= concurrentlyUpdatedLanes;
          markRootFinished(
            root,
            lanes,
            didIncludeRenderPhaseUpdate,
            spawnedLane,
            updatedLanes,
            suspendedRetryLanes
          );
          root === workInProgressRoot && (workInProgress = workInProgressRoot = null, workInProgressRootRenderLanes = 0);
          pendingFinishedWork = finishedWork;
          pendingEffectsRoot = root;
          pendingEffectsLanes = lanes;
          pendingEffectsRemainingLanes = didIncludeRenderPhaseUpdate;
          pendingPassiveTransitions = transitions;
          pendingRecoverableErrors = recoverableErrors;
          0 !== (finishedWork.subtreeFlags & 10256) || 0 !== (finishedWork.flags & 10256) ? (root.callbackNode = null, root.callbackPriority = 0, scheduleCallback(NormalPriority$1, function() {
            flushPassiveEffects(true);
            return null;
          })) : (root.callbackNode = null, root.callbackPriority = 0);
          commitStartTime = now();
          recoverableErrors = 0 !== (finishedWork.flags & 13878);
          if (0 !== (finishedWork.subtreeFlags & 13878) || recoverableErrors) {
            recoverableErrors = ReactSharedInternals.T;
            ReactSharedInternals.T = null;
            transitions = getCurrentUpdatePriority();
            setCurrentUpdatePriority(2);
            spawnedLane = executionContext;
            executionContext |= CommitContext;
            try {
              commitBeforeMutationEffects(root, finishedWork, lanes);
            } finally {
              executionContext = spawnedLane, setCurrentUpdatePriority(transitions), ReactSharedInternals.T = recoverableErrors;
            }
          }
          pendingEffectsStatus = PENDING_MUTATION_PHASE;
          flushMutationEffects();
          flushLayoutEffects();
          flushSpawnedWork();
        }
      }
      __name(commitRoot, "commitRoot");
      function flushMutationEffects() {
        if (pendingEffectsStatus === PENDING_MUTATION_PHASE) {
          pendingEffectsStatus = NO_PENDING_EFFECTS;
          var root = pendingEffectsRoot, finishedWork = pendingFinishedWork, lanes = pendingEffectsLanes, rootMutationHasEffect = 0 !== (finishedWork.flags & 13878);
          if (0 !== (finishedWork.subtreeFlags & 13878) || rootMutationHasEffect) {
            rootMutationHasEffect = ReactSharedInternals.T;
            ReactSharedInternals.T = null;
            var previousPriority = getCurrentUpdatePriority();
            setCurrentUpdatePriority(2);
            var prevExecutionContext = executionContext;
            executionContext |= CommitContext;
            try {
              inProgressLanes = lanes, inProgressRoot = root, commitMutationEffectsOnFiber(finishedWork, root), inProgressRoot = inProgressLanes = null, resetAfterCommit(root.containerInfo);
            } finally {
              executionContext = prevExecutionContext, setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = rootMutationHasEffect;
            }
          }
          root.current = finishedWork;
          pendingEffectsStatus = PENDING_LAYOUT_PHASE;
        }
      }
      __name(flushMutationEffects, "flushMutationEffects");
      function flushLayoutEffects() {
        if (pendingEffectsStatus === PENDING_LAYOUT_PHASE) {
          pendingEffectsStatus = NO_PENDING_EFFECTS;
          var root = pendingEffectsRoot, finishedWork = pendingFinishedWork, lanes = pendingEffectsLanes, rootHasLayoutEffect = 0 !== (finishedWork.flags & 8772);
          if (0 !== (finishedWork.subtreeFlags & 8772) || rootHasLayoutEffect) {
            rootHasLayoutEffect = ReactSharedInternals.T;
            ReactSharedInternals.T = null;
            var previousPriority = getCurrentUpdatePriority();
            setCurrentUpdatePriority(2);
            var prevExecutionContext = executionContext;
            executionContext |= CommitContext;
            try {
              null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markLayoutEffectsStarted && injectedProfilingHooks.markLayoutEffectsStarted(lanes), inProgressLanes = lanes, inProgressRoot = root, commitLayoutEffectOnFiber(
                root,
                finishedWork.alternate,
                finishedWork
              ), inProgressRoot = inProgressLanes = null, null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markLayoutEffectsStopped && injectedProfilingHooks.markLayoutEffectsStopped();
            } finally {
              executionContext = prevExecutionContext, setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = rootHasLayoutEffect;
            }
          }
          pendingEffectsStatus = PENDING_AFTER_MUTATION_PHASE;
        }
      }
      __name(flushLayoutEffects, "flushLayoutEffects");
      function flushSpawnedWork() {
        if (pendingEffectsStatus === PENDING_SPAWNED_WORK || pendingEffectsStatus === PENDING_AFTER_MUTATION_PHASE) {
          pendingEffectsStatus = NO_PENDING_EFFECTS;
          requestPaint();
          var root = pendingEffectsRoot, finishedWork = pendingFinishedWork, lanes = pendingEffectsLanes, recoverableErrors = pendingRecoverableErrors, rootDidHavePassiveEffects = 0 !== (finishedWork.subtreeFlags & 10256) || 0 !== (finishedWork.flags & 10256);
          rootDidHavePassiveEffects ? pendingEffectsStatus = PENDING_PASSIVE_PHASE : (pendingEffectsStatus = NO_PENDING_EFFECTS, pendingFinishedWork = pendingEffectsRoot = null, releaseRootPooledCache(root, root.pendingLanes), nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = null);
          var remainingLanes = root.pendingLanes;
          0 === remainingLanes && (legacyErrorBoundariesThatAlreadyFailed = null);
          rootDidHavePassiveEffects || commitDoubleInvokeEffectsInDEV(root);
          rootDidHavePassiveEffects = lanesToEventPriority(lanes);
          finishedWork = finishedWork.stateNode;
          if (injectedHook && "function" === typeof injectedHook.onCommitFiberRoot)
            try {
              var didError = 128 === (finishedWork.current.flags & 128);
              switch (rootDidHavePassiveEffects) {
                case 2:
                  var schedulerPriority = ImmediatePriority;
                  break;
                case 8:
                  schedulerPriority = UserBlockingPriority;
                  break;
                case 32:
                  schedulerPriority = NormalPriority$1;
                  break;
                case 268435456:
                  schedulerPriority = IdlePriority;
                  break;
                default:
                  schedulerPriority = NormalPriority$1;
              }
              injectedHook.onCommitFiberRoot(
                rendererID,
                finishedWork,
                schedulerPriority,
                didError
              );
            } catch (err) {
              hasLoggedError || (hasLoggedError = true, console.error(
                "React instrumentation encountered an error: %s",
                err
              ));
            }
          isDevToolsPresent && root.memoizedUpdaters.clear();
          onCommitRoot();
          if (null !== recoverableErrors) {
            didError = ReactSharedInternals.T;
            schedulerPriority = getCurrentUpdatePriority();
            setCurrentUpdatePriority(2);
            ReactSharedInternals.T = null;
            try {
              var onRecoverableError = root.onRecoverableError;
              for (finishedWork = 0; finishedWork < recoverableErrors.length; finishedWork++) {
                var recoverableError = recoverableErrors[finishedWork], errorInfo = makeErrorInfo(recoverableError.stack);
                runWithFiberInDEV(
                  recoverableError.source,
                  onRecoverableError,
                  recoverableError.value,
                  errorInfo
                );
              }
            } finally {
              ReactSharedInternals.T = didError, setCurrentUpdatePriority(schedulerPriority);
            }
          }
          0 !== (pendingEffectsLanes & 3) && flushPendingEffects();
          ensureRootIsScheduled(root);
          remainingLanes = root.pendingLanes;
          0 !== (lanes & 4194090) && 0 !== (remainingLanes & 42) ? (nestedUpdateScheduled = true, root === rootWithNestedUpdates ? nestedUpdateCount++ : (nestedUpdateCount = 0, rootWithNestedUpdates = root)) : nestedUpdateCount = 0;
          flushSyncWorkAcrossRoots_impl(0, false);
          markCommitStopped();
        }
      }
      __name(flushSpawnedWork, "flushSpawnedWork");
      function makeErrorInfo(componentStack) {
        componentStack = { componentStack };
        Object.defineProperty(componentStack, "digest", {
          get: /* @__PURE__ */ __name(function() {
            console.error(
              'You are accessing "digest" from the errorInfo object passed to onRecoverableError. This property is no longer provided as part of errorInfo but can be accessed as a property of the Error instance itself.'
            );
          }, "get")
        });
        return componentStack;
      }
      __name(makeErrorInfo, "makeErrorInfo");
      function releaseRootPooledCache(root, remainingLanes) {
        0 === (root.pooledCacheLanes &= remainingLanes) && (remainingLanes = root.pooledCache, null != remainingLanes && (root.pooledCache = null, releaseCache(remainingLanes)));
      }
      __name(releaseRootPooledCache, "releaseRootPooledCache");
      function flushPendingEffects(wasDelayedCommit) {
        flushMutationEffects();
        flushLayoutEffects();
        flushSpawnedWork();
        return flushPassiveEffects(wasDelayedCommit);
      }
      __name(flushPendingEffects, "flushPendingEffects");
      function flushPassiveEffects() {
        if (pendingEffectsStatus !== PENDING_PASSIVE_PHASE) return false;
        var root = pendingEffectsRoot, remainingLanes = pendingEffectsRemainingLanes;
        pendingEffectsRemainingLanes = 0;
        var renderPriority = lanesToEventPriority(pendingEffectsLanes), priority = 32 > renderPriority ? 32 : renderPriority;
        renderPriority = ReactSharedInternals.T;
        var previousPriority = getCurrentUpdatePriority();
        try {
          setCurrentUpdatePriority(priority);
          ReactSharedInternals.T = null;
          priority = pendingPassiveTransitions;
          pendingPassiveTransitions = null;
          var root$jscomp$0 = pendingEffectsRoot, lanes = pendingEffectsLanes;
          pendingEffectsStatus = NO_PENDING_EFFECTS;
          pendingFinishedWork = pendingEffectsRoot = null;
          pendingEffectsLanes = 0;
          if ((executionContext & (RenderContext | CommitContext)) !== NoContext)
            throw Error("Cannot flush passive effects while already rendering.");
          isFlushingPassiveEffects = true;
          didScheduleUpdateDuringPassiveEffects = false;
          null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markPassiveEffectsStarted && injectedProfilingHooks.markPassiveEffectsStarted(lanes);
          var prevExecutionContext = executionContext;
          executionContext |= CommitContext;
          commitPassiveUnmountOnFiber(root$jscomp$0.current);
          commitPassiveMountOnFiber(
            root$jscomp$0,
            root$jscomp$0.current,
            lanes,
            priority
          );
          null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markPassiveEffectsStopped && injectedProfilingHooks.markPassiveEffectsStopped();
          commitDoubleInvokeEffectsInDEV(root$jscomp$0);
          executionContext = prevExecutionContext;
          flushSyncWorkAcrossRoots_impl(0, false);
          didScheduleUpdateDuringPassiveEffects ? root$jscomp$0 === rootWithPassiveNestedUpdates ? nestedPassiveUpdateCount++ : (nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = root$jscomp$0) : nestedPassiveUpdateCount = 0;
          didScheduleUpdateDuringPassiveEffects = isFlushingPassiveEffects = false;
          if (injectedHook && "function" === typeof injectedHook.onPostCommitFiberRoot)
            try {
              injectedHook.onPostCommitFiberRoot(rendererID, root$jscomp$0);
            } catch (err) {
              hasLoggedError || (hasLoggedError = true, console.error(
                "React instrumentation encountered an error: %s",
                err
              ));
            }
          var stateNode = root$jscomp$0.current.stateNode;
          stateNode.effectDuration = 0;
          stateNode.passiveEffectDuration = 0;
          return true;
        } finally {
          setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = renderPriority, releaseRootPooledCache(root, remainingLanes);
        }
      }
      __name(flushPassiveEffects, "flushPassiveEffects");
      function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
        sourceFiber = createCapturedValueAtFiber(error, sourceFiber);
        sourceFiber = createRootErrorUpdate(rootFiber.stateNode, sourceFiber, 2);
        rootFiber = enqueueUpdate(rootFiber, sourceFiber, 2);
        null !== rootFiber && (markRootUpdated$1(rootFiber, 2), ensureRootIsScheduled(rootFiber));
      }
      __name(captureCommitPhaseErrorOnRoot, "captureCommitPhaseErrorOnRoot");
      function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error) {
        isRunningInsertionEffect = false;
        if (3 === sourceFiber.tag)
          captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
        else {
          for (; null !== nearestMountedAncestor; ) {
            if (3 === nearestMountedAncestor.tag) {
              captureCommitPhaseErrorOnRoot(
                nearestMountedAncestor,
                sourceFiber,
                error
              );
              return;
            }
            if (1 === nearestMountedAncestor.tag) {
              var instance = nearestMountedAncestor.stateNode;
              if ("function" === typeof nearestMountedAncestor.type.getDerivedStateFromError || "function" === typeof instance.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(instance))) {
                sourceFiber = createCapturedValueAtFiber(error, sourceFiber);
                error = createClassErrorUpdate(2);
                instance = enqueueUpdate(nearestMountedAncestor, error, 2);
                null !== instance && (initializeClassErrorUpdate(
                  error,
                  instance,
                  nearestMountedAncestor,
                  sourceFiber
                ), markRootUpdated$1(instance, 2), ensureRootIsScheduled(instance));
                return;
              }
            }
            nearestMountedAncestor = nearestMountedAncestor.return;
          }
          console.error(
            "Internal React error: Attempted to capture a commit phase error inside a detached tree. This indicates a bug in React. Potential causes include deleting the same fiber more than once, committing an already-finished tree, or an inconsistent return pointer.\n\nError message:\n\n%s",
            error
          );
        }
      }
      __name(captureCommitPhaseError, "captureCommitPhaseError");
      function attachPingListener(root, wakeable, lanes) {
        var pingCache = root.pingCache;
        if (null === pingCache) {
          pingCache = root.pingCache = new PossiblyWeakMap();
          var threadIDs = /* @__PURE__ */ new Set();
          pingCache.set(wakeable, threadIDs);
        } else
          threadIDs = pingCache.get(wakeable), void 0 === threadIDs && (threadIDs = /* @__PURE__ */ new Set(), pingCache.set(wakeable, threadIDs));
        threadIDs.has(lanes) || (workInProgressRootDidAttachPingListener = true, threadIDs.add(lanes), pingCache = pingSuspendedRoot.bind(null, root, wakeable, lanes), isDevToolsPresent && restorePendingUpdaters(root, lanes), wakeable.then(pingCache, pingCache));
      }
      __name(attachPingListener, "attachPingListener");
      function pingSuspendedRoot(root, wakeable, pingedLanes) {
        var pingCache = root.pingCache;
        null !== pingCache && pingCache.delete(wakeable);
        root.pingedLanes |= root.suspendedLanes & pingedLanes;
        root.warmLanes &= ~pingedLanes;
        isConcurrentActEnvironment() && null === ReactSharedInternals.actQueue && console.error(
          "A suspended resource finished loading inside a test, but the event was not wrapped in act(...).\n\nWhen testing, code that resolves suspended data should be wrapped into act(...):\n\nact(() => {\n  /* finish loading suspended data */\n});\n/* assert on the output */\n\nThis ensures that you're testing the behavior the user would see in the browser. Learn more at https://react.dev/link/wrap-tests-with-act"
        );
        workInProgressRoot === root && (workInProgressRootRenderLanes & pingedLanes) === pingedLanes && (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && (workInProgressRootRenderLanes & 62914560) === workInProgressRootRenderLanes && now$1() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS ? (executionContext & RenderContext) === NoContext && prepareFreshStack(root, 0) : workInProgressRootPingedLanes |= pingedLanes, workInProgressSuspendedRetryLanes === workInProgressRootRenderLanes && (workInProgressSuspendedRetryLanes = 0));
        ensureRootIsScheduled(root);
      }
      __name(pingSuspendedRoot, "pingSuspendedRoot");
      function retryTimedOutBoundary(boundaryFiber, retryLane) {
        0 === retryLane && (retryLane = claimNextRetryLane());
        boundaryFiber = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);
        null !== boundaryFiber && (markRootUpdated$1(boundaryFiber, retryLane), ensureRootIsScheduled(boundaryFiber));
      }
      __name(retryTimedOutBoundary, "retryTimedOutBoundary");
      function retryDehydratedSuspenseBoundary(boundaryFiber) {
        var suspenseState = boundaryFiber.memoizedState, retryLane = 0;
        null !== suspenseState && (retryLane = suspenseState.retryLane);
        retryTimedOutBoundary(boundaryFiber, retryLane);
      }
      __name(retryDehydratedSuspenseBoundary, "retryDehydratedSuspenseBoundary");
      function resolveRetryWakeable(boundaryFiber, wakeable) {
        var retryLane = 0;
        switch (boundaryFiber.tag) {
          case 13:
            var retryCache = boundaryFiber.stateNode;
            var suspenseState = boundaryFiber.memoizedState;
            null !== suspenseState && (retryLane = suspenseState.retryLane);
            break;
          case 19:
            retryCache = boundaryFiber.stateNode;
            break;
          case 22:
            retryCache = boundaryFiber.stateNode._retryCache;
            break;
          default:
            throw Error(
              "Pinged unknown suspense boundary type. This is probably a bug in React."
            );
        }
        null !== retryCache && retryCache.delete(wakeable);
        retryTimedOutBoundary(boundaryFiber, retryLane);
      }
      __name(resolveRetryWakeable, "resolveRetryWakeable");
      function recursivelyTraverseAndDoubleInvokeEffectsInDEV(root$jscomp$0, parentFiber, isInStrictMode) {
        if (0 !== (parentFiber.subtreeFlags & 67117056))
          for (parentFiber = parentFiber.child; null !== parentFiber; ) {
            var root = root$jscomp$0, fiber = parentFiber, isStrictModeFiber = fiber.type === REACT_STRICT_MODE_TYPE;
            isStrictModeFiber = isInStrictMode || isStrictModeFiber;
            22 !== fiber.tag ? fiber.flags & 67108864 ? isStrictModeFiber && runWithFiberInDEV(
              fiber,
              doubleInvokeEffectsOnFiber,
              root,
              fiber,
              (fiber.mode & 64) === NoMode
            ) : recursivelyTraverseAndDoubleInvokeEffectsInDEV(
              root,
              fiber,
              isStrictModeFiber
            ) : null === fiber.memoizedState && (isStrictModeFiber && fiber.flags & 8192 ? runWithFiberInDEV(
              fiber,
              doubleInvokeEffectsOnFiber,
              root,
              fiber
            ) : fiber.subtreeFlags & 67108864 && runWithFiberInDEV(
              fiber,
              recursivelyTraverseAndDoubleInvokeEffectsInDEV,
              root,
              fiber,
              isStrictModeFiber
            ));
            parentFiber = parentFiber.sibling;
          }
      }
      __name(recursivelyTraverseAndDoubleInvokeEffectsInDEV, "recursivelyTraverseAndDoubleInvokeEffectsInDEV");
      function doubleInvokeEffectsOnFiber(root, fiber) {
        var shouldDoubleInvokePassiveEffects = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : true;
        setIsStrictModeForDevtools(true);
        try {
          disappearLayoutEffects(fiber), shouldDoubleInvokePassiveEffects && disconnectPassiveEffect(fiber), reappearLayoutEffects(root, fiber.alternate, fiber, false), shouldDoubleInvokePassiveEffects && reconnectPassiveEffects(root, fiber, 0, null, false, 0);
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }
      __name(doubleInvokeEffectsOnFiber, "doubleInvokeEffectsOnFiber");
      function commitDoubleInvokeEffectsInDEV(root) {
        var doubleInvokeEffects = true;
        root.current.mode & 24 || (doubleInvokeEffects = false);
        recursivelyTraverseAndDoubleInvokeEffectsInDEV(
          root,
          root.current,
          doubleInvokeEffects
        );
      }
      __name(commitDoubleInvokeEffectsInDEV, "commitDoubleInvokeEffectsInDEV");
      function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) {
        if ((executionContext & RenderContext) === NoContext) {
          var tag2 = fiber.tag;
          if (3 === tag2 || 1 === tag2 || 0 === tag2 || 11 === tag2 || 14 === tag2 || 15 === tag2) {
            tag2 = getComponentNameFromFiber(fiber) || "ReactComponent";
            if (null !== didWarnStateUpdateForNotYetMountedComponent) {
              if (didWarnStateUpdateForNotYetMountedComponent.has(tag2)) return;
              didWarnStateUpdateForNotYetMountedComponent.add(tag2);
            } else didWarnStateUpdateForNotYetMountedComponent = /* @__PURE__ */ new Set([tag2]);
            runWithFiberInDEV(fiber, function() {
              console.error(
                "Can't perform a React state update on a component that hasn't mounted yet. This indicates that you have a side-effect in your render function that asynchronously later calls tries to update the component. Move this work to useEffect instead."
              );
            });
          }
        }
      }
      __name(warnAboutUpdateOnNotYetMountedFiberInDEV, "warnAboutUpdateOnNotYetMountedFiberInDEV");
      function restorePendingUpdaters(root, lanes) {
        isDevToolsPresent && root.memoizedUpdaters.forEach(function(schedulingFiber) {
          addFiberToLanesMap(root, schedulingFiber, lanes);
        });
      }
      __name(restorePendingUpdaters, "restorePendingUpdaters");
      function scheduleCallback(priorityLevel, callback) {
        var actQueue = ReactSharedInternals.actQueue;
        return null !== actQueue ? (actQueue.push(callback), fakeActCallbackNode) : scheduleCallback$3(priorityLevel, callback);
      }
      __name(scheduleCallback, "scheduleCallback");
      function warnIfUpdatesNotWrappedWithActDEV(fiber) {
        isConcurrentActEnvironment() && null === ReactSharedInternals.actQueue && runWithFiberInDEV(fiber, function() {
          console.error(
            "An update to %s inside a test was not wrapped in act(...).\n\nWhen testing, code that causes React state updates should be wrapped into act(...):\n\nact(() => {\n  /* fire events that update state */\n});\n/* assert on the output */\n\nThis ensures that you're testing the behavior the user would see in the browser. Learn more at https://react.dev/link/wrap-tests-with-act",
            getComponentNameFromFiber(fiber)
          );
        });
      }
      __name(warnIfUpdatesNotWrappedWithActDEV, "warnIfUpdatesNotWrappedWithActDEV");
      function resolveFunctionForHotReloading(type) {
        if (null === resolveFamily) return type;
        var family = resolveFamily(type);
        return void 0 === family ? type : family.current;
      }
      __name(resolveFunctionForHotReloading, "resolveFunctionForHotReloading");
      function resolveForwardRefForHotReloading(type) {
        if (null === resolveFamily) return type;
        var family = resolveFamily(type);
        return void 0 === family ? null !== type && void 0 !== type && "function" === typeof type.render && (family = resolveFunctionForHotReloading(type.render), type.render !== family) ? (family = { $$typeof: REACT_FORWARD_REF_TYPE, render: family }, void 0 !== type.displayName && (family.displayName = type.displayName), family) : type : family.current;
      }
      __name(resolveForwardRefForHotReloading, "resolveForwardRefForHotReloading");
      function isCompatibleFamilyForHotReloading(fiber, element) {
        if (null === resolveFamily) return false;
        var prevType = fiber.elementType;
        element = element.type;
        var needsCompareFamilies = false, $$typeofNextType = "object" === typeof element && null !== element ? element.$$typeof : null;
        switch (fiber.tag) {
          case 1:
            "function" === typeof element && (needsCompareFamilies = true);
            break;
          case 0:
            "function" === typeof element ? needsCompareFamilies = true : $$typeofNextType === REACT_LAZY_TYPE && (needsCompareFamilies = true);
            break;
          case 11:
            $$typeofNextType === REACT_FORWARD_REF_TYPE ? needsCompareFamilies = true : $$typeofNextType === REACT_LAZY_TYPE && (needsCompareFamilies = true);
            break;
          case 14:
          case 15:
            $$typeofNextType === REACT_MEMO_TYPE ? needsCompareFamilies = true : $$typeofNextType === REACT_LAZY_TYPE && (needsCompareFamilies = true);
            break;
          default:
            return false;
        }
        return needsCompareFamilies && (fiber = resolveFamily(prevType), void 0 !== fiber && fiber === resolveFamily(element)) ? true : false;
      }
      __name(isCompatibleFamilyForHotReloading, "isCompatibleFamilyForHotReloading");
      function markFailedErrorBoundaryForHotReloading(fiber) {
        null !== resolveFamily && "function" === typeof WeakSet && (null === failedBoundaries && (failedBoundaries = /* @__PURE__ */ new WeakSet()), failedBoundaries.add(fiber));
      }
      __name(markFailedErrorBoundaryForHotReloading, "markFailedErrorBoundaryForHotReloading");
      function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
        var alternate = fiber.alternate, child = fiber.child, sibling = fiber.sibling, tag2 = fiber.tag, type = fiber.type, candidateType = null;
        switch (tag2) {
          case 0:
          case 15:
          case 1:
            candidateType = type;
            break;
          case 11:
            candidateType = type.render;
        }
        if (null === resolveFamily)
          throw Error("Expected resolveFamily to be set during hot reload.");
        var needsRender = false;
        type = false;
        null !== candidateType && (candidateType = resolveFamily(candidateType), void 0 !== candidateType && (staleFamilies.has(candidateType) ? type = true : updatedFamilies.has(candidateType) && (1 === tag2 ? type = true : needsRender = true)));
        null !== failedBoundaries && (failedBoundaries.has(fiber) || null !== alternate && failedBoundaries.has(alternate)) && (type = true);
        type && (fiber._debugNeedsRemount = true);
        if (type || needsRender)
          alternate = enqueueConcurrentRenderForLane(fiber, 2), null !== alternate && scheduleUpdateOnFiber(alternate, fiber, 2);
        null === child || type || scheduleFibersWithFamiliesRecursively(
          child,
          updatedFamilies,
          staleFamilies
        );
        null !== sibling && scheduleFibersWithFamiliesRecursively(
          sibling,
          updatedFamilies,
          staleFamilies
        );
      }
      __name(scheduleFibersWithFamiliesRecursively, "scheduleFibersWithFamiliesRecursively");
      function FiberNode(tag2, pendingProps, key, mode) {
        this.tag = tag2;
        this.key = key;
        this.sibling = this.child = this.return = this.stateNode = this.type = this.elementType = null;
        this.index = 0;
        this.refCleanup = this.ref = null;
        this.pendingProps = pendingProps;
        this.dependencies = this.memoizedState = this.updateQueue = this.memoizedProps = null;
        this.mode = mode;
        this.subtreeFlags = this.flags = 0;
        this.deletions = null;
        this.childLanes = this.lanes = 0;
        this.alternate = null;
        this.actualDuration = -0;
        this.actualStartTime = -1.1;
        this.treeBaseDuration = this.selfBaseDuration = -0;
        this._debugTask = this._debugStack = this._debugOwner = this._debugInfo = null;
        this._debugNeedsRemount = false;
        this._debugHookTypes = null;
        hasBadMapPolyfill || "function" !== typeof Object.preventExtensions || Object.preventExtensions(this);
      }
      __name(FiberNode, "FiberNode");
      function shouldConstruct(Component) {
        Component = Component.prototype;
        return !(!Component || !Component.isReactComponent);
      }
      __name(shouldConstruct, "shouldConstruct");
      function createWorkInProgress(current2, pendingProps) {
        var workInProgress2 = current2.alternate;
        null === workInProgress2 ? (workInProgress2 = createFiber(
          current2.tag,
          pendingProps,
          current2.key,
          current2.mode
        ), workInProgress2.elementType = current2.elementType, workInProgress2.type = current2.type, workInProgress2.stateNode = current2.stateNode, workInProgress2._debugOwner = current2._debugOwner, workInProgress2._debugStack = current2._debugStack, workInProgress2._debugTask = current2._debugTask, workInProgress2._debugHookTypes = current2._debugHookTypes, workInProgress2.alternate = current2, current2.alternate = workInProgress2) : (workInProgress2.pendingProps = pendingProps, workInProgress2.type = current2.type, workInProgress2.flags = 0, workInProgress2.subtreeFlags = 0, workInProgress2.deletions = null, workInProgress2.actualDuration = -0, workInProgress2.actualStartTime = -1.1);
        workInProgress2.flags = current2.flags & 65011712;
        workInProgress2.childLanes = current2.childLanes;
        workInProgress2.lanes = current2.lanes;
        workInProgress2.child = current2.child;
        workInProgress2.memoizedProps = current2.memoizedProps;
        workInProgress2.memoizedState = current2.memoizedState;
        workInProgress2.updateQueue = current2.updateQueue;
        pendingProps = current2.dependencies;
        workInProgress2.dependencies = null === pendingProps ? null : {
          lanes: pendingProps.lanes,
          firstContext: pendingProps.firstContext,
          _debugThenableState: pendingProps._debugThenableState
        };
        workInProgress2.sibling = current2.sibling;
        workInProgress2.index = current2.index;
        workInProgress2.ref = current2.ref;
        workInProgress2.refCleanup = current2.refCleanup;
        workInProgress2.selfBaseDuration = current2.selfBaseDuration;
        workInProgress2.treeBaseDuration = current2.treeBaseDuration;
        workInProgress2._debugInfo = current2._debugInfo;
        workInProgress2._debugNeedsRemount = current2._debugNeedsRemount;
        switch (workInProgress2.tag) {
          case 0:
          case 15:
            workInProgress2.type = resolveFunctionForHotReloading(current2.type);
            break;
          case 1:
            workInProgress2.type = resolveFunctionForHotReloading(current2.type);
            break;
          case 11:
            workInProgress2.type = resolveForwardRefForHotReloading(current2.type);
        }
        return workInProgress2;
      }
      __name(createWorkInProgress, "createWorkInProgress");
      function resetWorkInProgress(workInProgress2, renderLanes2) {
        workInProgress2.flags &= 65011714;
        var current2 = workInProgress2.alternate;
        null === current2 ? (workInProgress2.childLanes = 0, workInProgress2.lanes = renderLanes2, workInProgress2.child = null, workInProgress2.subtreeFlags = 0, workInProgress2.memoizedProps = null, workInProgress2.memoizedState = null, workInProgress2.updateQueue = null, workInProgress2.dependencies = null, workInProgress2.stateNode = null, workInProgress2.selfBaseDuration = 0, workInProgress2.treeBaseDuration = 0) : (workInProgress2.childLanes = current2.childLanes, workInProgress2.lanes = current2.lanes, workInProgress2.child = current2.child, workInProgress2.subtreeFlags = 0, workInProgress2.deletions = null, workInProgress2.memoizedProps = current2.memoizedProps, workInProgress2.memoizedState = current2.memoizedState, workInProgress2.updateQueue = current2.updateQueue, workInProgress2.type = current2.type, renderLanes2 = current2.dependencies, workInProgress2.dependencies = null === renderLanes2 ? null : {
          lanes: renderLanes2.lanes,
          firstContext: renderLanes2.firstContext,
          _debugThenableState: renderLanes2._debugThenableState
        }, workInProgress2.selfBaseDuration = current2.selfBaseDuration, workInProgress2.treeBaseDuration = current2.treeBaseDuration);
        return workInProgress2;
      }
      __name(resetWorkInProgress, "resetWorkInProgress");
      function createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes) {
        var fiberTag = 0, resolvedType = type;
        if ("function" === typeof type)
          shouldConstruct(type) && (fiberTag = 1), resolvedType = resolveFunctionForHotReloading(resolvedType);
        else if ("string" === typeof type)
          supportsResources && supportsSingletons ? (fiberTag = getHostContext(), fiberTag = isHostHoistableType(type, pendingProps, fiberTag) ? 26 : isHostSingletonType(type) ? 27 : 5) : supportsResources ? (fiberTag = getHostContext(), fiberTag = isHostHoistableType(type, pendingProps, fiberTag) ? 26 : 5) : fiberTag = supportsSingletons ? isHostSingletonType(type) ? 27 : 5 : 5;
        else
          a: switch (type) {
            case REACT_ACTIVITY_TYPE:
              return key = createFiber(31, pendingProps, key, mode), key.elementType = REACT_ACTIVITY_TYPE, key.lanes = lanes, key;
            case REACT_FRAGMENT_TYPE:
              return createFiberFromFragment(
                pendingProps.children,
                mode,
                lanes,
                key
              );
            case REACT_STRICT_MODE_TYPE:
              fiberTag = 8;
              mode |= 24;
              break;
            case REACT_PROFILER_TYPE:
              return type = pendingProps, owner = mode, "string" !== typeof type.id && console.error(
                'Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.',
                typeof type.id
              ), key = createFiber(12, type, key, owner | 2), key.elementType = REACT_PROFILER_TYPE, key.lanes = lanes, key.stateNode = { effectDuration: 0, passiveEffectDuration: 0 }, key;
            case REACT_SUSPENSE_TYPE:
              return key = createFiber(13, pendingProps, key, mode), key.elementType = REACT_SUSPENSE_TYPE, key.lanes = lanes, key;
            case REACT_SUSPENSE_LIST_TYPE:
              return key = createFiber(19, pendingProps, key, mode), key.elementType = REACT_SUSPENSE_LIST_TYPE, key.lanes = lanes, key;
            default:
              if ("object" === typeof type && null !== type)
                switch (type.$$typeof) {
                  case REACT_PROVIDER_TYPE:
                  case REACT_CONTEXT_TYPE:
                    fiberTag = 10;
                    break a;
                  case REACT_CONSUMER_TYPE:
                    fiberTag = 9;
                    break a;
                  case REACT_FORWARD_REF_TYPE:
                    fiberTag = 11;
                    resolvedType = resolveForwardRefForHotReloading(resolvedType);
                    break a;
                  case REACT_MEMO_TYPE:
                    fiberTag = 14;
                    break a;
                  case REACT_LAZY_TYPE:
                    fiberTag = 16;
                    resolvedType = null;
                    break a;
                }
              resolvedType = "";
              if (void 0 === type || "object" === typeof type && null !== type && 0 === Object.keys(type).length)
                resolvedType += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
              null === type ? pendingProps = "null" : isArrayImpl(type) ? pendingProps = "array" : void 0 !== type && type.$$typeof === REACT_ELEMENT_TYPE ? (pendingProps = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />", resolvedType = " Did you accidentally export a JSX literal instead of a component?") : pendingProps = typeof type;
              fiberTag = owner ? "number" === typeof owner.tag ? getComponentNameFromFiber(owner) : "string" === typeof owner.name ? owner.name : null : null;
              fiberTag && (resolvedType += "\n\nCheck the render method of `" + fiberTag + "`.");
              fiberTag = 29;
              pendingProps = Error(
                "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + (pendingProps + "." + resolvedType)
              );
              resolvedType = null;
          }
        key = createFiber(fiberTag, pendingProps, key, mode);
        key.elementType = type;
        key.type = resolvedType;
        key.lanes = lanes;
        key._debugOwner = owner;
        return key;
      }
      __name(createFiberFromTypeAndProps, "createFiberFromTypeAndProps");
      function createFiberFromElement(element, mode, lanes) {
        mode = createFiberFromTypeAndProps(
          element.type,
          element.key,
          element.props,
          element._owner,
          mode,
          lanes
        );
        mode._debugOwner = element._owner;
        mode._debugStack = element._debugStack;
        mode._debugTask = element._debugTask;
        return mode;
      }
      __name(createFiberFromElement, "createFiberFromElement");
      function createFiberFromFragment(elements, mode, lanes, key) {
        elements = createFiber(7, elements, key, mode);
        elements.lanes = lanes;
        return elements;
      }
      __name(createFiberFromFragment, "createFiberFromFragment");
      function createFiberFromText(content, mode, lanes) {
        content = createFiber(6, content, null, mode);
        content.lanes = lanes;
        return content;
      }
      __name(createFiberFromText, "createFiberFromText");
      function createFiberFromPortal(portal, mode, lanes) {
        mode = createFiber(
          4,
          null !== portal.children ? portal.children : [],
          portal.key,
          mode
        );
        mode.lanes = lanes;
        mode.stateNode = {
          containerInfo: portal.containerInfo,
          pendingChildren: null,
          implementation: portal.implementation
        };
        return mode;
      }
      __name(createFiberFromPortal, "createFiberFromPortal");
      function FiberRootNode(containerInfo, tag2, hydrate, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, formState) {
        this.tag = 1;
        this.containerInfo = containerInfo;
        this.pingCache = this.current = this.pendingChildren = null;
        this.timeoutHandle = noTimeout;
        this.callbackNode = this.next = this.pendingContext = this.context = this.cancelPendingCommit = null;
        this.callbackPriority = 0;
        this.expirationTimes = createLaneMap(-1);
        this.entangledLanes = this.shellSuspendCounter = this.errorRecoveryDisabledLanes = this.expiredLanes = this.warmLanes = this.pingedLanes = this.suspendedLanes = this.pendingLanes = 0;
        this.entanglements = createLaneMap(0);
        this.hiddenUpdates = createLaneMap(null);
        this.identifierPrefix = identifierPrefix;
        this.onUncaughtError = onUncaughtError;
        this.onCaughtError = onCaughtError;
        this.onRecoverableError = onRecoverableError;
        this.pooledCache = null;
        this.pooledCacheLanes = 0;
        this.formState = formState;
        this.incompleteTransitions = /* @__PURE__ */ new Map();
        this.passiveEffectDuration = this.effectDuration = -0;
        this.memoizedUpdaters = /* @__PURE__ */ new Set();
        containerInfo = this.pendingUpdatersLaneMap = [];
        for (tag2 = 0; 31 > tag2; tag2++) containerInfo.push(/* @__PURE__ */ new Set());
        this._debugRootType = hydrate ? "hydrateRoot()" : "createRoot()";
      }
      __name(FiberRootNode, "FiberRootNode");
      function createFiberRoot(containerInfo, tag2, hydrate, initialChildren, hydrationCallbacks, isStrictMode, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, transitionCallbacks, formState) {
        containerInfo = new FiberRootNode(
          containerInfo,
          tag2,
          hydrate,
          identifierPrefix,
          onUncaughtError,
          onCaughtError,
          onRecoverableError,
          formState
        );
        tag2 = 1;
        true === isStrictMode && (tag2 |= 24);
        isDevToolsPresent && (tag2 |= 2);
        isStrictMode = createFiber(3, null, null, tag2);
        containerInfo.current = isStrictMode;
        isStrictMode.stateNode = containerInfo;
        tag2 = createCache();
        retainCache(tag2);
        containerInfo.pooledCache = tag2;
        retainCache(tag2);
        isStrictMode.memoizedState = {
          element: initialChildren,
          isDehydrated: hydrate,
          cache: tag2
        };
        initializeUpdateQueue(isStrictMode);
        return containerInfo;
      }
      __name(createFiberRoot, "createFiberRoot");
      function testStringCoercion(value) {
        return "" + value;
      }
      __name(testStringCoercion, "testStringCoercion");
      function getContextForSubtree(parentComponent) {
        if (!parentComponent) return emptyContextObject;
        parentComponent = emptyContextObject;
        return parentComponent;
      }
      __name(getContextForSubtree, "getContextForSubtree");
      function updateContainerSync(element, container, parentComponent, callback) {
        updateContainerImpl(
          container.current,
          2,
          element,
          container,
          parentComponent,
          callback
        );
        return 2;
      }
      __name(updateContainerSync, "updateContainerSync");
      function updateContainerImpl(rootFiber, lane, element, container, parentComponent, callback) {
        if (injectedHook && "function" === typeof injectedHook.onScheduleFiberRoot)
          try {
            injectedHook.onScheduleFiberRoot(rendererID, container, element);
          } catch (err) {
            hasLoggedError || (hasLoggedError = true, console.error(
              "React instrumentation encountered an error: %s",
              err
            ));
          }
        null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markRenderScheduled && injectedProfilingHooks.markRenderScheduled(lane);
        parentComponent = getContextForSubtree(parentComponent);
        null === container.context ? container.context = parentComponent : container.pendingContext = parentComponent;
        isRendering && null !== current && !didWarnAboutNestedUpdates && (didWarnAboutNestedUpdates = true, console.error(
          "Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate.\n\nCheck the render method of %s.",
          getComponentNameFromFiber(current) || "Unknown"
        ));
        container = createUpdate(lane);
        container.payload = { element };
        callback = void 0 === callback ? null : callback;
        null !== callback && ("function" !== typeof callback && console.error(
          "Expected the last optional `callback` argument to be a function. Instead received: %s.",
          callback
        ), container.callback = callback);
        element = enqueueUpdate(rootFiber, container, lane);
        null !== element && (scheduleUpdateOnFiber(element, rootFiber, lane), entangleTransitions(element, rootFiber, lane));
      }
      __name(updateContainerImpl, "updateContainerImpl");
      function markRetryLaneImpl(fiber, retryLane) {
        fiber = fiber.memoizedState;
        if (null !== fiber && null !== fiber.dehydrated) {
          var a = fiber.retryLane;
          fiber.retryLane = 0 !== a && a < retryLane ? a : retryLane;
        }
      }
      __name(markRetryLaneImpl, "markRetryLaneImpl");
      function markRetryLaneIfNotHydrated(fiber, retryLane) {
        markRetryLaneImpl(fiber, retryLane);
        (fiber = fiber.alternate) && markRetryLaneImpl(fiber, retryLane);
      }
      __name(markRetryLaneIfNotHydrated, "markRetryLaneIfNotHydrated");
      function getCurrentFiberForDevTools() {
        return current;
      }
      __name(getCurrentFiberForDevTools, "getCurrentFiberForDevTools");
      function getLaneLabelMap() {
        for (var map2 = /* @__PURE__ */ new Map(), lane = 1, index = 0; 31 > index; index++) {
          var label = getLabelForLane(lane);
          map2.set(lane, label);
          lane *= 2;
        }
        return map2;
      }
      __name(getLaneLabelMap, "getLaneLabelMap");
      var exports3 = {};
      "use strict";
      var React29 = require_react(), Scheduler2 = require_scheduler(), assign = Object.assign, REACT_LEGACY_ELEMENT_TYPE = Symbol.for("react.element"), REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_PROVIDER_TYPE = Symbol.for("react.provider"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy");
      Symbol.for("react.scope");
      var REACT_ACTIVITY_TYPE = Symbol.for("react.activity");
      Symbol.for("react.legacy_hidden");
      Symbol.for("react.tracing_marker");
      var REACT_MEMO_CACHE_SENTINEL = Symbol.for("react.memo_cache_sentinel");
      Symbol.for("react.view_transition");
      var MAYBE_ITERATOR_SYMBOL = Symbol.iterator, REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), isArrayImpl = Array.isArray, ReactSharedInternals = React29.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, rendererVersion = $$$config.rendererVersion, rendererPackageName = $$$config.rendererPackageName, extraDevToolsConfig = $$$config.extraDevToolsConfig, getPublicInstance = $$$config.getPublicInstance, getRootHostContext = $$$config.getRootHostContext, getChildHostContext = $$$config.getChildHostContext, prepareForCommit = $$$config.prepareForCommit, resetAfterCommit = $$$config.resetAfterCommit, createInstance2 = $$$config.createInstance;
      $$$config.cloneMutableInstance;
      var appendInitialChild = $$$config.appendInitialChild, finalizeInitialChildren = $$$config.finalizeInitialChildren, shouldSetTextContent = $$$config.shouldSetTextContent, createTextInstance = $$$config.createTextInstance;
      $$$config.cloneMutableTextInstance;
      var scheduleTimeout = $$$config.scheduleTimeout, cancelTimeout = $$$config.cancelTimeout, noTimeout = $$$config.noTimeout, isPrimaryRenderer = $$$config.isPrimaryRenderer;
      $$$config.warnsIfNotActing;
      var supportsMutation = $$$config.supportsMutation, supportsPersistence = $$$config.supportsPersistence, supportsHydration = $$$config.supportsHydration, getInstanceFromNode = $$$config.getInstanceFromNode;
      $$$config.beforeActiveInstanceBlur;
      var preparePortalMount = $$$config.preparePortalMount;
      $$$config.prepareScopeUpdate;
      $$$config.getInstanceFromScope;
      var setCurrentUpdatePriority = $$$config.setCurrentUpdatePriority, getCurrentUpdatePriority = $$$config.getCurrentUpdatePriority, resolveUpdatePriority = $$$config.resolveUpdatePriority;
      $$$config.trackSchedulerEvent;
      $$$config.resolveEventType;
      $$$config.resolveEventTimeStamp;
      var shouldAttemptEagerTransition = $$$config.shouldAttemptEagerTransition, detachDeletedInstance = $$$config.detachDeletedInstance;
      $$$config.requestPostPaintCallback;
      var maySuspendCommit = $$$config.maySuspendCommit, preloadInstance = $$$config.preloadInstance, startSuspendingCommit = $$$config.startSuspendingCommit, suspendInstance = $$$config.suspendInstance;
      $$$config.suspendOnActiveViewTransition;
      var waitForCommitToBeReady = $$$config.waitForCommitToBeReady, NotPendingTransition = $$$config.NotPendingTransition, HostTransitionContext = $$$config.HostTransitionContext, resetFormInstance = $$$config.resetFormInstance, bindToConsole = $$$config.bindToConsole, supportsMicrotasks = $$$config.supportsMicrotasks, scheduleMicrotask = $$$config.scheduleMicrotask, supportsTestSelectors = $$$config.supportsTestSelectors, findFiberRoot = $$$config.findFiberRoot, getBoundingRect = $$$config.getBoundingRect, getTextContent = $$$config.getTextContent, isHiddenSubtree = $$$config.isHiddenSubtree, matchAccessibilityRole = $$$config.matchAccessibilityRole, setFocusIfFocusable = $$$config.setFocusIfFocusable, setupIntersectionObserver = $$$config.setupIntersectionObserver, appendChild = $$$config.appendChild, appendChildToContainer = $$$config.appendChildToContainer, commitTextUpdate = $$$config.commitTextUpdate, commitMount = $$$config.commitMount, commitUpdate = $$$config.commitUpdate, insertBefore = $$$config.insertBefore, insertInContainerBefore = $$$config.insertInContainerBefore, removeChild = $$$config.removeChild, removeChildFromContainer = $$$config.removeChildFromContainer, resetTextContent = $$$config.resetTextContent, hideInstance = $$$config.hideInstance, hideTextInstance = $$$config.hideTextInstance, unhideInstance = $$$config.unhideInstance, unhideTextInstance = $$$config.unhideTextInstance;
      $$$config.cancelViewTransitionName;
      $$$config.cancelRootViewTransitionName;
      $$$config.restoreRootViewTransitionName;
      $$$config.cloneRootViewTransitionContainer;
      $$$config.removeRootViewTransitionClone;
      $$$config.measureClonedInstance;
      $$$config.hasInstanceChanged;
      $$$config.hasInstanceAffectedParent;
      $$$config.startViewTransition;
      $$$config.startGestureTransition;
      $$$config.stopGestureTransition;
      $$$config.getCurrentGestureOffset;
      $$$config.subscribeToGestureDirection;
      $$$config.createViewTransitionInstance;
      var clearContainer = $$$config.clearContainer;
      $$$config.createFragmentInstance;
      $$$config.updateFragmentInstanceFiber;
      $$$config.commitNewChildToFragmentInstance;
      $$$config.deleteChildFromFragmentInstance;
      var cloneInstance = $$$config.cloneInstance, createContainerChildSet = $$$config.createContainerChildSet, appendChildToContainerChildSet = $$$config.appendChildToContainerChildSet, finalizeContainerChildren = $$$config.finalizeContainerChildren, replaceContainerChildren = $$$config.replaceContainerChildren, cloneHiddenInstance = $$$config.cloneHiddenInstance, cloneHiddenTextInstance = $$$config.cloneHiddenTextInstance, isSuspenseInstancePending = $$$config.isSuspenseInstancePending, isSuspenseInstanceFallback = $$$config.isSuspenseInstanceFallback, getSuspenseInstanceFallbackErrorDetails = $$$config.getSuspenseInstanceFallbackErrorDetails, registerSuspenseInstanceRetry = $$$config.registerSuspenseInstanceRetry, canHydrateFormStateMarker = $$$config.canHydrateFormStateMarker, isFormStateMarkerMatching = $$$config.isFormStateMarkerMatching, getNextHydratableSibling = $$$config.getNextHydratableSibling, getNextHydratableSiblingAfterSingleton = $$$config.getNextHydratableSiblingAfterSingleton, getFirstHydratableChild = $$$config.getFirstHydratableChild, getFirstHydratableChildWithinContainer = $$$config.getFirstHydratableChildWithinContainer, getFirstHydratableChildWithinSuspenseInstance = $$$config.getFirstHydratableChildWithinSuspenseInstance, getFirstHydratableChildWithinSingleton = $$$config.getFirstHydratableChildWithinSingleton, canHydrateInstance = $$$config.canHydrateInstance, canHydrateTextInstance = $$$config.canHydrateTextInstance, canHydrateSuspenseInstance = $$$config.canHydrateSuspenseInstance, hydrateInstance = $$$config.hydrateInstance, hydrateTextInstance = $$$config.hydrateTextInstance, hydrateSuspenseInstance = $$$config.hydrateSuspenseInstance, getNextHydratableInstanceAfterSuspenseInstance = $$$config.getNextHydratableInstanceAfterSuspenseInstance, commitHydratedContainer = $$$config.commitHydratedContainer, commitHydratedSuspenseInstance = $$$config.commitHydratedSuspenseInstance, clearSuspenseBoundary = $$$config.clearSuspenseBoundary, clearSuspenseBoundaryFromContainer = $$$config.clearSuspenseBoundaryFromContainer, shouldDeleteUnhydratedTailInstances = $$$config.shouldDeleteUnhydratedTailInstances, diffHydratedPropsForDevWarnings = $$$config.diffHydratedPropsForDevWarnings, diffHydratedTextForDevWarnings = $$$config.diffHydratedTextForDevWarnings, describeHydratableInstanceForDevWarnings = $$$config.describeHydratableInstanceForDevWarnings, validateHydratableInstance = $$$config.validateHydratableInstance, validateHydratableTextInstance = $$$config.validateHydratableTextInstance, supportsResources = $$$config.supportsResources, isHostHoistableType = $$$config.isHostHoistableType, getHoistableRoot = $$$config.getHoistableRoot, getResource = $$$config.getResource, acquireResource = $$$config.acquireResource, releaseResource = $$$config.releaseResource, hydrateHoistable = $$$config.hydrateHoistable, mountHoistable = $$$config.mountHoistable, unmountHoistable = $$$config.unmountHoistable, createHoistableInstance = $$$config.createHoistableInstance, prepareToCommitHoistables = $$$config.prepareToCommitHoistables, mayResourceSuspendCommit = $$$config.mayResourceSuspendCommit, preloadResource = $$$config.preloadResource, suspendResource = $$$config.suspendResource, supportsSingletons = $$$config.supportsSingletons, resolveSingletonInstance = $$$config.resolveSingletonInstance, acquireSingletonInstance = $$$config.acquireSingletonInstance, releaseSingletonInstance = $$$config.releaseSingletonInstance, isHostSingletonType = $$$config.isHostSingletonType, isSingletonScope = $$$config.isSingletonScope, valueStack = [];
      var fiberStack = [];
      var index$jscomp$0 = -1, emptyContextObject = {};
      Object.freeze(emptyContextObject);
      var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback, log$1 = Math.log, LN2 = Math.LN2, nextTransitionLane = 256, nextRetryLane = 4194304, scheduleCallback$3 = Scheduler2.unstable_scheduleCallback, cancelCallback$1 = Scheduler2.unstable_cancelCallback, shouldYield = Scheduler2.unstable_shouldYield, requestPaint = Scheduler2.unstable_requestPaint, now$1 = Scheduler2.unstable_now, ImmediatePriority = Scheduler2.unstable_ImmediatePriority, UserBlockingPriority = Scheduler2.unstable_UserBlockingPriority, NormalPriority$1 = Scheduler2.unstable_NormalPriority, IdlePriority = Scheduler2.unstable_IdlePriority, log = Scheduler2.log, unstable_setDisableYieldValue = Scheduler2.unstable_setDisableYieldValue, rendererID = null, injectedHook = null, injectedProfilingHooks = null, hasLoggedError = false, isDevToolsPresent = "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__, disabledDepth = 0, prevLog, prevInfo, prevWarn, prevError, prevGroup, prevGroupCollapsed, prevGroupEnd;
      disabledLog.__reactDisabledLog = true;
      var prefix, suffix, reentry = false;
      var componentFrameCache = new ("function" === typeof WeakMap ? WeakMap : Map)();
      var CapturedStacks = /* @__PURE__ */ new WeakMap(), forkStack = [], forkStackIndex = 0, treeForkProvider = null, treeForkCount = 0, idStack = [], idStackIndex = 0, treeContextProvider = null, treeContextId = 1, treeContextOverflow = "", contextStackCursor = createCursor(null), contextFiberStackCursor = createCursor(null), rootInstanceStackCursor = createCursor(null), hostTransitionProviderCursor = createCursor(null), needsEscaping = /["'&<>\n\t]|^\s|\s$/, current = null, isRendering = false, hydrationParentFiber = null, nextHydratableInstance = null, isHydrating = false, didSuspendOrErrorDEV = false, hydrationDiffRootDEV = null, hydrationErrors = null, rootOrSingletonContext = false, HydrationMismatchException = Error(
        "Hydration Mismatch Exception: This is not a real error, and should not leak into userspace. If you're seeing this, it's likely a bug in React."
      ), lastResetTime = 0;
      if ("object" === typeof performance && "function" === typeof performance.now) {
        var localPerformance = performance;
        var getCurrentTime = /* @__PURE__ */ __name(function() {
          return localPerformance.now();
        }, "getCurrentTime");
      } else {
        var localDate = Date;
        getCurrentTime = /* @__PURE__ */ __name(function() {
          return localDate.now();
        }, "getCurrentTime");
      }
      var objectIs = "function" === typeof Object.is ? Object.is : is, NoMode = 0, valueCursor = createCursor(null);
      var rendererCursorDEV = createCursor(null);
      var renderer2CursorDEV = createCursor(null);
      var rendererSigil = {};
      var currentlyRenderingFiber$1 = null, lastContextDependency = null, isDisallowedContextReadInDEV = false, AbortControllerLocal = "undefined" !== typeof AbortController ? AbortController : function() {
        var listeners = [], signal = this.signal = {
          aborted: false,
          addEventListener: /* @__PURE__ */ __name(function(type, listener) {
            listeners.push(listener);
          }, "addEventListener")
        };
        this.abort = function() {
          signal.aborted = true;
          listeners.forEach(function(listener) {
            return listener();
          });
        };
      }, scheduleCallback$2 = Scheduler2.unstable_scheduleCallback, NormalPriority = Scheduler2.unstable_NormalPriority, CacheContext = {
        $$typeof: REACT_CONTEXT_TYPE,
        Consumer: null,
        Provider: null,
        _currentValue: null,
        _currentValue2: null,
        _threadCount: 0,
        _currentRenderer: null,
        _currentRenderer2: null
      }, now = Scheduler2.unstable_now, commitStartTime = -0, profilerStartTime = -1.1, profilerEffectDuration = -0, currentUpdateIsNested = false, nestedUpdateScheduled = false, firstScheduledRoot = null, lastScheduledRoot = null, didScheduleMicrotask = false, didScheduleMicrotask_act = false, mightHavePendingSyncWork = false, isFlushingWork = false, currentEventTransitionLane = 0, fakeActCallbackNode$1 = {}, currentEntangledListeners = null, currentEntangledPendingCount = 0, currentEntangledLane = 0, currentEntangledActionThenable = null, prevOnStartTransitionFinish = ReactSharedInternals.S;
      ReactSharedInternals.S = function(transition, returnValue) {
        "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && entangleAsyncAction(transition, returnValue);
        null !== prevOnStartTransitionFinish && prevOnStartTransitionFinish(transition, returnValue);
      };
      var resumedCache = createCursor(null), hasOwnProperty2 = Object.prototype.hasOwnProperty, ReactStrictModeWarnings = {
        recordUnsafeLifecycleWarnings: /* @__PURE__ */ __name(function() {
        }, "recordUnsafeLifecycleWarnings"),
        flushPendingUnsafeLifecycleWarnings: /* @__PURE__ */ __name(function() {
        }, "flushPendingUnsafeLifecycleWarnings"),
        recordLegacyContextWarning: /* @__PURE__ */ __name(function() {
        }, "recordLegacyContextWarning"),
        flushLegacyContextWarning: /* @__PURE__ */ __name(function() {
        }, "flushLegacyContextWarning"),
        discardPendingWarnings: /* @__PURE__ */ __name(function() {
        }, "discardPendingWarnings")
      }, pendingComponentWillMountWarnings = [], pendingUNSAFE_ComponentWillMountWarnings = [], pendingComponentWillReceivePropsWarnings = [], pendingUNSAFE_ComponentWillReceivePropsWarnings = [], pendingComponentWillUpdateWarnings = [], pendingUNSAFE_ComponentWillUpdateWarnings = [], didWarnAboutUnsafeLifecycles = /* @__PURE__ */ new Set();
      ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function(fiber, instance) {
        didWarnAboutUnsafeLifecycles.has(fiber.type) || ("function" === typeof instance.componentWillMount && true !== instance.componentWillMount.__suppressDeprecationWarning && pendingComponentWillMountWarnings.push(fiber), fiber.mode & 8 && "function" === typeof instance.UNSAFE_componentWillMount && pendingUNSAFE_ComponentWillMountWarnings.push(fiber), "function" === typeof instance.componentWillReceiveProps && true !== instance.componentWillReceiveProps.__suppressDeprecationWarning && pendingComponentWillReceivePropsWarnings.push(fiber), fiber.mode & 8 && "function" === typeof instance.UNSAFE_componentWillReceiveProps && pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber), "function" === typeof instance.componentWillUpdate && true !== instance.componentWillUpdate.__suppressDeprecationWarning && pendingComponentWillUpdateWarnings.push(fiber), fiber.mode & 8 && "function" === typeof instance.UNSAFE_componentWillUpdate && pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber));
      };
      ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function() {
        var componentWillMountUniqueNames = /* @__PURE__ */ new Set();
        0 < pendingComponentWillMountWarnings.length && (pendingComponentWillMountWarnings.forEach(function(fiber) {
          componentWillMountUniqueNames.add(
            getComponentNameFromFiber(fiber) || "Component"
          );
          didWarnAboutUnsafeLifecycles.add(fiber.type);
        }), pendingComponentWillMountWarnings = []);
        var UNSAFE_componentWillMountUniqueNames = /* @__PURE__ */ new Set();
        0 < pendingUNSAFE_ComponentWillMountWarnings.length && (pendingUNSAFE_ComponentWillMountWarnings.forEach(function(fiber) {
          UNSAFE_componentWillMountUniqueNames.add(
            getComponentNameFromFiber(fiber) || "Component"
          );
          didWarnAboutUnsafeLifecycles.add(fiber.type);
        }), pendingUNSAFE_ComponentWillMountWarnings = []);
        var componentWillReceivePropsUniqueNames = /* @__PURE__ */ new Set();
        0 < pendingComponentWillReceivePropsWarnings.length && (pendingComponentWillReceivePropsWarnings.forEach(function(fiber) {
          componentWillReceivePropsUniqueNames.add(
            getComponentNameFromFiber(fiber) || "Component"
          );
          didWarnAboutUnsafeLifecycles.add(fiber.type);
        }), pendingComponentWillReceivePropsWarnings = []);
        var UNSAFE_componentWillReceivePropsUniqueNames = /* @__PURE__ */ new Set();
        0 < pendingUNSAFE_ComponentWillReceivePropsWarnings.length && (pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(
          function(fiber) {
            UNSAFE_componentWillReceivePropsUniqueNames.add(
              getComponentNameFromFiber(fiber) || "Component"
            );
            didWarnAboutUnsafeLifecycles.add(fiber.type);
          }
        ), pendingUNSAFE_ComponentWillReceivePropsWarnings = []);
        var componentWillUpdateUniqueNames = /* @__PURE__ */ new Set();
        0 < pendingComponentWillUpdateWarnings.length && (pendingComponentWillUpdateWarnings.forEach(function(fiber) {
          componentWillUpdateUniqueNames.add(
            getComponentNameFromFiber(fiber) || "Component"
          );
          didWarnAboutUnsafeLifecycles.add(fiber.type);
        }), pendingComponentWillUpdateWarnings = []);
        var UNSAFE_componentWillUpdateUniqueNames = /* @__PURE__ */ new Set();
        0 < pendingUNSAFE_ComponentWillUpdateWarnings.length && (pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function(fiber) {
          UNSAFE_componentWillUpdateUniqueNames.add(
            getComponentNameFromFiber(fiber) || "Component"
          );
          didWarnAboutUnsafeLifecycles.add(fiber.type);
        }), pendingUNSAFE_ComponentWillUpdateWarnings = []);
        if (0 < UNSAFE_componentWillMountUniqueNames.size) {
          var sortedNames = setToSortedString(
            UNSAFE_componentWillMountUniqueNames
          );
          console.error(
            "Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move code with side effects to componentDidMount, and set initial state in the constructor.\n\nPlease update the following components: %s",
            sortedNames
          );
        }
        0 < UNSAFE_componentWillReceivePropsUniqueNames.size && (sortedNames = setToSortedString(
          UNSAFE_componentWillReceivePropsUniqueNames
        ), console.error(
          "Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://react.dev/link/derived-state\n\nPlease update the following components: %s",
          sortedNames
        ));
        0 < UNSAFE_componentWillUpdateUniqueNames.size && (sortedNames = setToSortedString(
          UNSAFE_componentWillUpdateUniqueNames
        ), console.error(
          "Using UNSAFE_componentWillUpdate in strict mode is not recommended and may indicate bugs in your code. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n\nPlease update the following components: %s",
          sortedNames
        ));
        0 < componentWillMountUniqueNames.size && (sortedNames = setToSortedString(componentWillMountUniqueNames), console.warn(
          "componentWillMount has been renamed, and is not recommended for use. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move code with side effects to componentDidMount, and set initial state in the constructor.\n* Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s",
          sortedNames
        ));
        0 < componentWillReceivePropsUniqueNames.size && (sortedNames = setToSortedString(
          componentWillReceivePropsUniqueNames
        ), console.warn(
          "componentWillReceiveProps has been renamed, and is not recommended for use. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://react.dev/link/derived-state\n* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s",
          sortedNames
        ));
        0 < componentWillUpdateUniqueNames.size && (sortedNames = setToSortedString(componentWillUpdateUniqueNames), console.warn(
          "componentWillUpdate has been renamed, and is not recommended for use. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s",
          sortedNames
        ));
      };
      var pendingLegacyContextWarning = /* @__PURE__ */ new Map(), didWarnAboutLegacyContext = /* @__PURE__ */ new Set();
      ReactStrictModeWarnings.recordLegacyContextWarning = function(fiber, instance) {
        var strictRoot = null;
        for (var node = fiber; null !== node; )
          node.mode & 8 && (strictRoot = node), node = node.return;
        null === strictRoot ? console.error(
          "Expected to find a StrictMode component in a strict mode tree. This error is likely caused by a bug in React. Please file an issue."
        ) : !didWarnAboutLegacyContext.has(fiber.type) && (node = pendingLegacyContextWarning.get(strictRoot), null != fiber.type.contextTypes || null != fiber.type.childContextTypes || null !== instance && "function" === typeof instance.getChildContext) && (void 0 === node && (node = [], pendingLegacyContextWarning.set(strictRoot, node)), node.push(fiber));
      };
      ReactStrictModeWarnings.flushLegacyContextWarning = function() {
        pendingLegacyContextWarning.forEach(function(fiberArray) {
          if (0 !== fiberArray.length) {
            var firstFiber = fiberArray[0], uniqueNames = /* @__PURE__ */ new Set();
            fiberArray.forEach(function(fiber) {
              uniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
              didWarnAboutLegacyContext.add(fiber.type);
            });
            var sortedNames = setToSortedString(uniqueNames);
            runWithFiberInDEV(firstFiber, function() {
              console.error(
                "Legacy context API has been detected within a strict-mode tree.\n\nThe old API will be supported in all 16.x releases, but applications using it should migrate to the new version.\n\nPlease update the following components: %s\n\nLearn more about this warning here: https://react.dev/link/legacy-context",
                sortedNames
              );
            });
          }
        });
      };
      ReactStrictModeWarnings.discardPendingWarnings = function() {
        pendingComponentWillMountWarnings = [];
        pendingUNSAFE_ComponentWillMountWarnings = [];
        pendingComponentWillReceivePropsWarnings = [];
        pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
        pendingComponentWillUpdateWarnings = [];
        pendingUNSAFE_ComponentWillUpdateWarnings = [];
        pendingLegacyContextWarning = /* @__PURE__ */ new Map();
      };
      var SuspenseException = Error(
        "Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`."
      ), SuspenseyCommitException = Error(
        "Suspense Exception: This is not a real error, and should not leak into userspace. If you're seeing this, it's likely a bug in React."
      ), SuspenseActionException = Error(
        "Suspense Exception: This is not a real error! It's an implementation detail of `useActionState` to interrupt the current render. You must either rethrow it immediately, or move the `useActionState` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary."
      ), noopSuspenseyCommitThenable = {
        then: /* @__PURE__ */ __name(function() {
          console.error(
            'Internal React error: A listener was unexpectedly attached to a "noop" thenable. This is a bug in React. Please file an issue.'
          );
        }, "then")
      }, suspendedThenable = null, needsToResetSuspendedThenableDEV = false, NoFlags = 0, HasEffect = 1, Insertion = 2, Layout = 4, Passive = 8, concurrentQueues = [], concurrentQueuesIndex = 0, concurrentlyUpdatedLanes = 0, UpdateState = 0, ReplaceState = 1, ForceUpdate = 2, CaptureUpdate = 3, hasForceUpdate = false;
      var didWarnUpdateInsideUpdate = false;
      var currentlyProcessingQueue = null;
      var didReadFromEntangledAsyncAction = false, currentTreeHiddenStackCursor = createCursor(null), prevEntangledRenderLanesCursor = createCursor(0), didWarnUncachedGetSnapshot;
      var didWarnAboutMismatchedHooksForComponent = /* @__PURE__ */ new Set();
      var didWarnAboutUseWrappedInTryCatch = /* @__PURE__ */ new Set();
      var didWarnAboutAsyncClientComponent = /* @__PURE__ */ new Set();
      var didWarnAboutUseFormState = /* @__PURE__ */ new Set();
      var renderLanes = 0, currentlyRenderingFiber = null, currentHook = null, workInProgressHook = null, didScheduleRenderPhaseUpdate = false, didScheduleRenderPhaseUpdateDuringThisPass = false, shouldDoubleInvokeUserFnsInHooksDEV = false, localIdCounter = 0, thenableIndexCounter$1 = 0, thenableState$1 = null, globalClientIdCounter = 0, RE_RENDER_LIMIT = 25, currentHookNameInDev = null, hookTypesDev = null, hookTypesUpdateIndexDev = -1, ignorePreviousDependencies = false, ContextOnlyDispatcher = {
        readContext,
        use: use2,
        useCallback: throwInvalidHookError,
        useContext: throwInvalidHookError,
        useEffect: throwInvalidHookError,
        useImperativeHandle: throwInvalidHookError,
        useLayoutEffect: throwInvalidHookError,
        useInsertionEffect: throwInvalidHookError,
        useMemo: throwInvalidHookError,
        useReducer: throwInvalidHookError,
        useRef: throwInvalidHookError,
        useState: throwInvalidHookError,
        useDebugValue: throwInvalidHookError,
        useDeferredValue: throwInvalidHookError,
        useTransition: throwInvalidHookError,
        useSyncExternalStore: throwInvalidHookError,
        useId: throwInvalidHookError,
        useHostTransitionStatus: throwInvalidHookError,
        useFormState: throwInvalidHookError,
        useActionState: throwInvalidHookError,
        useOptimistic: throwInvalidHookError,
        useMemoCache: throwInvalidHookError,
        useCacheRefresh: throwInvalidHookError
      }, HooksDispatcherOnMountInDEV = null, HooksDispatcherOnMountWithHookTypesInDEV = null, HooksDispatcherOnUpdateInDEV = null, HooksDispatcherOnRerenderInDEV = null, InvalidNestedHooksDispatcherOnMountInDEV = null, InvalidNestedHooksDispatcherOnUpdateInDEV = null, InvalidNestedHooksDispatcherOnRerenderInDEV = null;
      HooksDispatcherOnMountInDEV = {
        readContext: /* @__PURE__ */ __name(function(context2) {
          return readContext(context2);
        }, "readContext"),
        use: use2,
        useCallback: /* @__PURE__ */ __name(function(callback, deps) {
          currentHookNameInDev = "useCallback";
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          return mountCallback(callback, deps);
        }, "useCallback"),
        useContext: /* @__PURE__ */ __name(function(context2) {
          currentHookNameInDev = "useContext";
          mountHookTypesDev();
          return readContext(context2);
        }, "useContext"),
        useEffect: /* @__PURE__ */ __name(function(create3, createDeps) {
          currentHookNameInDev = "useEffect";
          mountHookTypesDev();
          checkDepsAreArrayDev(createDeps);
          return mountEffect(create3, createDeps);
        }, "useEffect"),
        useImperativeHandle: /* @__PURE__ */ __name(function(ref, create3, deps) {
          currentHookNameInDev = "useImperativeHandle";
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          return mountImperativeHandle(ref, create3, deps);
        }, "useImperativeHandle"),
        useInsertionEffect: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useInsertionEffect";
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          mountEffectImpl(4, Insertion, create3, deps);
        }, "useInsertionEffect"),
        useLayoutEffect: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useLayoutEffect";
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          return mountLayoutEffect(create3, deps);
        }, "useLayoutEffect"),
        useMemo: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useMemo";
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountMemo(create3, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useMemo"),
        useReducer: /* @__PURE__ */ __name(function(reducer, initialArg, init) {
          currentHookNameInDev = "useReducer";
          mountHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountReducer(reducer, initialArg, init);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useReducer"),
        useRef: /* @__PURE__ */ __name(function(initialValue) {
          currentHookNameInDev = "useRef";
          mountHookTypesDev();
          return mountRef(initialValue);
        }, "useRef"),
        useState: /* @__PURE__ */ __name(function(initialState2) {
          currentHookNameInDev = "useState";
          mountHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountState(initialState2);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useState"),
        useDebugValue: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useDebugValue";
          mountHookTypesDev();
        }, "useDebugValue"),
        useDeferredValue: /* @__PURE__ */ __name(function(value, initialValue) {
          currentHookNameInDev = "useDeferredValue";
          mountHookTypesDev();
          return mountDeferredValue(value, initialValue);
        }, "useDeferredValue"),
        useTransition: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useTransition";
          mountHookTypesDev();
          return mountTransition();
        }, "useTransition"),
        useSyncExternalStore: /* @__PURE__ */ __name(function(subscribe, getSnapshot, getServerSnapshot) {
          currentHookNameInDev = "useSyncExternalStore";
          mountHookTypesDev();
          return mountSyncExternalStore(
            subscribe,
            getSnapshot,
            getServerSnapshot
          );
        }, "useSyncExternalStore"),
        useId: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useId";
          mountHookTypesDev();
          return mountId();
        }, "useId"),
        useFormState: /* @__PURE__ */ __name(function(action, initialState2) {
          currentHookNameInDev = "useFormState";
          mountHookTypesDev();
          warnOnUseFormStateInDev();
          return mountActionState(action, initialState2);
        }, "useFormState"),
        useActionState: /* @__PURE__ */ __name(function(action, initialState2) {
          currentHookNameInDev = "useActionState";
          mountHookTypesDev();
          return mountActionState(action, initialState2);
        }, "useActionState"),
        useOptimistic: /* @__PURE__ */ __name(function(passthrough) {
          currentHookNameInDev = "useOptimistic";
          mountHookTypesDev();
          return mountOptimistic(passthrough);
        }, "useOptimistic"),
        useHostTransitionStatus,
        useMemoCache,
        useCacheRefresh: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useCacheRefresh";
          mountHookTypesDev();
          return mountRefresh();
        }, "useCacheRefresh")
      };
      HooksDispatcherOnMountWithHookTypesInDEV = {
        readContext: /* @__PURE__ */ __name(function(context2) {
          return readContext(context2);
        }, "readContext"),
        use: use2,
        useCallback: /* @__PURE__ */ __name(function(callback, deps) {
          currentHookNameInDev = "useCallback";
          updateHookTypesDev();
          return mountCallback(callback, deps);
        }, "useCallback"),
        useContext: /* @__PURE__ */ __name(function(context2) {
          currentHookNameInDev = "useContext";
          updateHookTypesDev();
          return readContext(context2);
        }, "useContext"),
        useEffect: /* @__PURE__ */ __name(function(create3, createDeps) {
          currentHookNameInDev = "useEffect";
          updateHookTypesDev();
          return mountEffect(create3, createDeps);
        }, "useEffect"),
        useImperativeHandle: /* @__PURE__ */ __name(function(ref, create3, deps) {
          currentHookNameInDev = "useImperativeHandle";
          updateHookTypesDev();
          return mountImperativeHandle(ref, create3, deps);
        }, "useImperativeHandle"),
        useInsertionEffect: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useInsertionEffect";
          updateHookTypesDev();
          mountEffectImpl(4, Insertion, create3, deps);
        }, "useInsertionEffect"),
        useLayoutEffect: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useLayoutEffect";
          updateHookTypesDev();
          return mountLayoutEffect(create3, deps);
        }, "useLayoutEffect"),
        useMemo: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useMemo";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountMemo(create3, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useMemo"),
        useReducer: /* @__PURE__ */ __name(function(reducer, initialArg, init) {
          currentHookNameInDev = "useReducer";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountReducer(reducer, initialArg, init);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useReducer"),
        useRef: /* @__PURE__ */ __name(function(initialValue) {
          currentHookNameInDev = "useRef";
          updateHookTypesDev();
          return mountRef(initialValue);
        }, "useRef"),
        useState: /* @__PURE__ */ __name(function(initialState2) {
          currentHookNameInDev = "useState";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountState(initialState2);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useState"),
        useDebugValue: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useDebugValue";
          updateHookTypesDev();
        }, "useDebugValue"),
        useDeferredValue: /* @__PURE__ */ __name(function(value, initialValue) {
          currentHookNameInDev = "useDeferredValue";
          updateHookTypesDev();
          return mountDeferredValue(value, initialValue);
        }, "useDeferredValue"),
        useTransition: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useTransition";
          updateHookTypesDev();
          return mountTransition();
        }, "useTransition"),
        useSyncExternalStore: /* @__PURE__ */ __name(function(subscribe, getSnapshot, getServerSnapshot) {
          currentHookNameInDev = "useSyncExternalStore";
          updateHookTypesDev();
          return mountSyncExternalStore(
            subscribe,
            getSnapshot,
            getServerSnapshot
          );
        }, "useSyncExternalStore"),
        useId: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useId";
          updateHookTypesDev();
          return mountId();
        }, "useId"),
        useActionState: /* @__PURE__ */ __name(function(action, initialState2) {
          currentHookNameInDev = "useActionState";
          updateHookTypesDev();
          return mountActionState(action, initialState2);
        }, "useActionState"),
        useFormState: /* @__PURE__ */ __name(function(action, initialState2) {
          currentHookNameInDev = "useFormState";
          updateHookTypesDev();
          warnOnUseFormStateInDev();
          return mountActionState(action, initialState2);
        }, "useFormState"),
        useOptimistic: /* @__PURE__ */ __name(function(passthrough) {
          currentHookNameInDev = "useOptimistic";
          updateHookTypesDev();
          return mountOptimistic(passthrough);
        }, "useOptimistic"),
        useHostTransitionStatus,
        useMemoCache,
        useCacheRefresh: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useCacheRefresh";
          updateHookTypesDev();
          return mountRefresh();
        }, "useCacheRefresh")
      };
      HooksDispatcherOnUpdateInDEV = {
        readContext: /* @__PURE__ */ __name(function(context2) {
          return readContext(context2);
        }, "readContext"),
        use: use2,
        useCallback: /* @__PURE__ */ __name(function(callback, deps) {
          currentHookNameInDev = "useCallback";
          updateHookTypesDev();
          return updateCallback(callback, deps);
        }, "useCallback"),
        useContext: /* @__PURE__ */ __name(function(context2) {
          currentHookNameInDev = "useContext";
          updateHookTypesDev();
          return readContext(context2);
        }, "useContext"),
        useEffect: /* @__PURE__ */ __name(function(create3, createDeps) {
          currentHookNameInDev = "useEffect";
          updateHookTypesDev();
          updateEffectImpl(2048, Passive, create3, createDeps);
        }, "useEffect"),
        useImperativeHandle: /* @__PURE__ */ __name(function(ref, create3, deps) {
          currentHookNameInDev = "useImperativeHandle";
          updateHookTypesDev();
          return updateImperativeHandle(ref, create3, deps);
        }, "useImperativeHandle"),
        useInsertionEffect: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useInsertionEffect";
          updateHookTypesDev();
          return updateEffectImpl(4, Insertion, create3, deps);
        }, "useInsertionEffect"),
        useLayoutEffect: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useLayoutEffect";
          updateHookTypesDev();
          return updateEffectImpl(4, Layout, create3, deps);
        }, "useLayoutEffect"),
        useMemo: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useMemo";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateMemo(create3, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useMemo"),
        useReducer: /* @__PURE__ */ __name(function(reducer, initialArg, init) {
          currentHookNameInDev = "useReducer";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateReducer(reducer, initialArg, init);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useReducer"),
        useRef: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useRef";
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        }, "useRef"),
        useState: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useState";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateReducer(basicStateReducer);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useState"),
        useDebugValue: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useDebugValue";
          updateHookTypesDev();
        }, "useDebugValue"),
        useDeferredValue: /* @__PURE__ */ __name(function(value, initialValue) {
          currentHookNameInDev = "useDeferredValue";
          updateHookTypesDev();
          return updateDeferredValue(value, initialValue);
        }, "useDeferredValue"),
        useTransition: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useTransition";
          updateHookTypesDev();
          return updateTransition();
        }, "useTransition"),
        useSyncExternalStore: /* @__PURE__ */ __name(function(subscribe, getSnapshot, getServerSnapshot) {
          currentHookNameInDev = "useSyncExternalStore";
          updateHookTypesDev();
          return updateSyncExternalStore(
            subscribe,
            getSnapshot,
            getServerSnapshot
          );
        }, "useSyncExternalStore"),
        useId: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useId";
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        }, "useId"),
        useFormState: /* @__PURE__ */ __name(function(action) {
          currentHookNameInDev = "useFormState";
          updateHookTypesDev();
          warnOnUseFormStateInDev();
          return updateActionState(action);
        }, "useFormState"),
        useActionState: /* @__PURE__ */ __name(function(action) {
          currentHookNameInDev = "useActionState";
          updateHookTypesDev();
          return updateActionState(action);
        }, "useActionState"),
        useOptimistic: /* @__PURE__ */ __name(function(passthrough, reducer) {
          currentHookNameInDev = "useOptimistic";
          updateHookTypesDev();
          return updateOptimistic(passthrough, reducer);
        }, "useOptimistic"),
        useHostTransitionStatus,
        useMemoCache,
        useCacheRefresh: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useCacheRefresh";
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        }, "useCacheRefresh")
      };
      HooksDispatcherOnRerenderInDEV = {
        readContext: /* @__PURE__ */ __name(function(context2) {
          return readContext(context2);
        }, "readContext"),
        use: use2,
        useCallback: /* @__PURE__ */ __name(function(callback, deps) {
          currentHookNameInDev = "useCallback";
          updateHookTypesDev();
          return updateCallback(callback, deps);
        }, "useCallback"),
        useContext: /* @__PURE__ */ __name(function(context2) {
          currentHookNameInDev = "useContext";
          updateHookTypesDev();
          return readContext(context2);
        }, "useContext"),
        useEffect: /* @__PURE__ */ __name(function(create3, createDeps) {
          currentHookNameInDev = "useEffect";
          updateHookTypesDev();
          updateEffectImpl(2048, Passive, create3, createDeps);
        }, "useEffect"),
        useImperativeHandle: /* @__PURE__ */ __name(function(ref, create3, deps) {
          currentHookNameInDev = "useImperativeHandle";
          updateHookTypesDev();
          return updateImperativeHandle(ref, create3, deps);
        }, "useImperativeHandle"),
        useInsertionEffect: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useInsertionEffect";
          updateHookTypesDev();
          return updateEffectImpl(4, Insertion, create3, deps);
        }, "useInsertionEffect"),
        useLayoutEffect: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useLayoutEffect";
          updateHookTypesDev();
          return updateEffectImpl(4, Layout, create3, deps);
        }, "useLayoutEffect"),
        useMemo: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useMemo";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnRerenderInDEV;
          try {
            return updateMemo(create3, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useMemo"),
        useReducer: /* @__PURE__ */ __name(function(reducer, initialArg, init) {
          currentHookNameInDev = "useReducer";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnRerenderInDEV;
          try {
            return rerenderReducer(reducer, initialArg, init);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useReducer"),
        useRef: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useRef";
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        }, "useRef"),
        useState: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useState";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnRerenderInDEV;
          try {
            return rerenderReducer(basicStateReducer);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useState"),
        useDebugValue: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useDebugValue";
          updateHookTypesDev();
        }, "useDebugValue"),
        useDeferredValue: /* @__PURE__ */ __name(function(value, initialValue) {
          currentHookNameInDev = "useDeferredValue";
          updateHookTypesDev();
          return rerenderDeferredValue(value, initialValue);
        }, "useDeferredValue"),
        useTransition: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useTransition";
          updateHookTypesDev();
          return rerenderTransition();
        }, "useTransition"),
        useSyncExternalStore: /* @__PURE__ */ __name(function(subscribe, getSnapshot, getServerSnapshot) {
          currentHookNameInDev = "useSyncExternalStore";
          updateHookTypesDev();
          return updateSyncExternalStore(
            subscribe,
            getSnapshot,
            getServerSnapshot
          );
        }, "useSyncExternalStore"),
        useId: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useId";
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        }, "useId"),
        useFormState: /* @__PURE__ */ __name(function(action) {
          currentHookNameInDev = "useFormState";
          updateHookTypesDev();
          warnOnUseFormStateInDev();
          return rerenderActionState(action);
        }, "useFormState"),
        useActionState: /* @__PURE__ */ __name(function(action) {
          currentHookNameInDev = "useActionState";
          updateHookTypesDev();
          return rerenderActionState(action);
        }, "useActionState"),
        useOptimistic: /* @__PURE__ */ __name(function(passthrough, reducer) {
          currentHookNameInDev = "useOptimistic";
          updateHookTypesDev();
          return rerenderOptimistic(passthrough, reducer);
        }, "useOptimistic"),
        useHostTransitionStatus,
        useMemoCache,
        useCacheRefresh: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useCacheRefresh";
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        }, "useCacheRefresh")
      };
      InvalidNestedHooksDispatcherOnMountInDEV = {
        readContext: /* @__PURE__ */ __name(function(context2) {
          warnInvalidContextAccess();
          return readContext(context2);
        }, "readContext"),
        use: /* @__PURE__ */ __name(function(usable) {
          warnInvalidHookAccess();
          return use2(usable);
        }, "use"),
        useCallback: /* @__PURE__ */ __name(function(callback, deps) {
          currentHookNameInDev = "useCallback";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountCallback(callback, deps);
        }, "useCallback"),
        useContext: /* @__PURE__ */ __name(function(context2) {
          currentHookNameInDev = "useContext";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return readContext(context2);
        }, "useContext"),
        useEffect: /* @__PURE__ */ __name(function(create3, createDeps) {
          currentHookNameInDev = "useEffect";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountEffect(create3, createDeps);
        }, "useEffect"),
        useImperativeHandle: /* @__PURE__ */ __name(function(ref, create3, deps) {
          currentHookNameInDev = "useImperativeHandle";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountImperativeHandle(ref, create3, deps);
        }, "useImperativeHandle"),
        useInsertionEffect: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useInsertionEffect";
          warnInvalidHookAccess();
          mountHookTypesDev();
          mountEffectImpl(4, Insertion, create3, deps);
        }, "useInsertionEffect"),
        useLayoutEffect: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useLayoutEffect";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountLayoutEffect(create3, deps);
        }, "useLayoutEffect"),
        useMemo: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useMemo";
          warnInvalidHookAccess();
          mountHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountMemo(create3, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useMemo"),
        useReducer: /* @__PURE__ */ __name(function(reducer, initialArg, init) {
          currentHookNameInDev = "useReducer";
          warnInvalidHookAccess();
          mountHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountReducer(reducer, initialArg, init);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useReducer"),
        useRef: /* @__PURE__ */ __name(function(initialValue) {
          currentHookNameInDev = "useRef";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountRef(initialValue);
        }, "useRef"),
        useState: /* @__PURE__ */ __name(function(initialState2) {
          currentHookNameInDev = "useState";
          warnInvalidHookAccess();
          mountHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountState(initialState2);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useState"),
        useDebugValue: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useDebugValue";
          warnInvalidHookAccess();
          mountHookTypesDev();
        }, "useDebugValue"),
        useDeferredValue: /* @__PURE__ */ __name(function(value, initialValue) {
          currentHookNameInDev = "useDeferredValue";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountDeferredValue(value, initialValue);
        }, "useDeferredValue"),
        useTransition: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useTransition";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountTransition();
        }, "useTransition"),
        useSyncExternalStore: /* @__PURE__ */ __name(function(subscribe, getSnapshot, getServerSnapshot) {
          currentHookNameInDev = "useSyncExternalStore";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountSyncExternalStore(
            subscribe,
            getSnapshot,
            getServerSnapshot
          );
        }, "useSyncExternalStore"),
        useId: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useId";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountId();
        }, "useId"),
        useFormState: /* @__PURE__ */ __name(function(action, initialState2) {
          currentHookNameInDev = "useFormState";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountActionState(action, initialState2);
        }, "useFormState"),
        useActionState: /* @__PURE__ */ __name(function(action, initialState2) {
          currentHookNameInDev = "useActionState";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountActionState(action, initialState2);
        }, "useActionState"),
        useOptimistic: /* @__PURE__ */ __name(function(passthrough) {
          currentHookNameInDev = "useOptimistic";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountOptimistic(passthrough);
        }, "useOptimistic"),
        useMemoCache: /* @__PURE__ */ __name(function(size) {
          warnInvalidHookAccess();
          return useMemoCache(size);
        }, "useMemoCache"),
        useHostTransitionStatus,
        useCacheRefresh: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useCacheRefresh";
          mountHookTypesDev();
          return mountRefresh();
        }, "useCacheRefresh")
      };
      InvalidNestedHooksDispatcherOnUpdateInDEV = {
        readContext: /* @__PURE__ */ __name(function(context2) {
          warnInvalidContextAccess();
          return readContext(context2);
        }, "readContext"),
        use: /* @__PURE__ */ __name(function(usable) {
          warnInvalidHookAccess();
          return use2(usable);
        }, "use"),
        useCallback: /* @__PURE__ */ __name(function(callback, deps) {
          currentHookNameInDev = "useCallback";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateCallback(callback, deps);
        }, "useCallback"),
        useContext: /* @__PURE__ */ __name(function(context2) {
          currentHookNameInDev = "useContext";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return readContext(context2);
        }, "useContext"),
        useEffect: /* @__PURE__ */ __name(function(create3, createDeps) {
          currentHookNameInDev = "useEffect";
          warnInvalidHookAccess();
          updateHookTypesDev();
          updateEffectImpl(2048, Passive, create3, createDeps);
        }, "useEffect"),
        useImperativeHandle: /* @__PURE__ */ __name(function(ref, create3, deps) {
          currentHookNameInDev = "useImperativeHandle";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateImperativeHandle(ref, create3, deps);
        }, "useImperativeHandle"),
        useInsertionEffect: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useInsertionEffect";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateEffectImpl(4, Insertion, create3, deps);
        }, "useInsertionEffect"),
        useLayoutEffect: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useLayoutEffect";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateEffectImpl(4, Layout, create3, deps);
        }, "useLayoutEffect"),
        useMemo: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useMemo";
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateMemo(create3, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useMemo"),
        useReducer: /* @__PURE__ */ __name(function(reducer, initialArg, init) {
          currentHookNameInDev = "useReducer";
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateReducer(reducer, initialArg, init);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useReducer"),
        useRef: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useRef";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        }, "useRef"),
        useState: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useState";
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateReducer(basicStateReducer);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useState"),
        useDebugValue: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useDebugValue";
          warnInvalidHookAccess();
          updateHookTypesDev();
        }, "useDebugValue"),
        useDeferredValue: /* @__PURE__ */ __name(function(value, initialValue) {
          currentHookNameInDev = "useDeferredValue";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateDeferredValue(value, initialValue);
        }, "useDeferredValue"),
        useTransition: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useTransition";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateTransition();
        }, "useTransition"),
        useSyncExternalStore: /* @__PURE__ */ __name(function(subscribe, getSnapshot, getServerSnapshot) {
          currentHookNameInDev = "useSyncExternalStore";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateSyncExternalStore(
            subscribe,
            getSnapshot,
            getServerSnapshot
          );
        }, "useSyncExternalStore"),
        useId: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useId";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        }, "useId"),
        useFormState: /* @__PURE__ */ __name(function(action) {
          currentHookNameInDev = "useFormState";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateActionState(action);
        }, "useFormState"),
        useActionState: /* @__PURE__ */ __name(function(action) {
          currentHookNameInDev = "useActionState";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateActionState(action);
        }, "useActionState"),
        useOptimistic: /* @__PURE__ */ __name(function(passthrough, reducer) {
          currentHookNameInDev = "useOptimistic";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateOptimistic(passthrough, reducer);
        }, "useOptimistic"),
        useMemoCache: /* @__PURE__ */ __name(function(size) {
          warnInvalidHookAccess();
          return useMemoCache(size);
        }, "useMemoCache"),
        useHostTransitionStatus,
        useCacheRefresh: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useCacheRefresh";
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        }, "useCacheRefresh")
      };
      InvalidNestedHooksDispatcherOnRerenderInDEV = {
        readContext: /* @__PURE__ */ __name(function(context2) {
          warnInvalidContextAccess();
          return readContext(context2);
        }, "readContext"),
        use: /* @__PURE__ */ __name(function(usable) {
          warnInvalidHookAccess();
          return use2(usable);
        }, "use"),
        useCallback: /* @__PURE__ */ __name(function(callback, deps) {
          currentHookNameInDev = "useCallback";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateCallback(callback, deps);
        }, "useCallback"),
        useContext: /* @__PURE__ */ __name(function(context2) {
          currentHookNameInDev = "useContext";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return readContext(context2);
        }, "useContext"),
        useEffect: /* @__PURE__ */ __name(function(create3, createDeps) {
          currentHookNameInDev = "useEffect";
          warnInvalidHookAccess();
          updateHookTypesDev();
          updateEffectImpl(2048, Passive, create3, createDeps);
        }, "useEffect"),
        useImperativeHandle: /* @__PURE__ */ __name(function(ref, create3, deps) {
          currentHookNameInDev = "useImperativeHandle";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateImperativeHandle(ref, create3, deps);
        }, "useImperativeHandle"),
        useInsertionEffect: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useInsertionEffect";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateEffectImpl(4, Insertion, create3, deps);
        }, "useInsertionEffect"),
        useLayoutEffect: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useLayoutEffect";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateEffectImpl(4, Layout, create3, deps);
        }, "useLayoutEffect"),
        useMemo: /* @__PURE__ */ __name(function(create3, deps) {
          currentHookNameInDev = "useMemo";
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateMemo(create3, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useMemo"),
        useReducer: /* @__PURE__ */ __name(function(reducer, initialArg, init) {
          currentHookNameInDev = "useReducer";
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return rerenderReducer(reducer, initialArg, init);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useReducer"),
        useRef: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useRef";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        }, "useRef"),
        useState: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useState";
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return rerenderReducer(basicStateReducer);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useState"),
        useDebugValue: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useDebugValue";
          warnInvalidHookAccess();
          updateHookTypesDev();
        }, "useDebugValue"),
        useDeferredValue: /* @__PURE__ */ __name(function(value, initialValue) {
          currentHookNameInDev = "useDeferredValue";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return rerenderDeferredValue(value, initialValue);
        }, "useDeferredValue"),
        useTransition: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useTransition";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return rerenderTransition();
        }, "useTransition"),
        useSyncExternalStore: /* @__PURE__ */ __name(function(subscribe, getSnapshot, getServerSnapshot) {
          currentHookNameInDev = "useSyncExternalStore";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateSyncExternalStore(
            subscribe,
            getSnapshot,
            getServerSnapshot
          );
        }, "useSyncExternalStore"),
        useId: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useId";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        }, "useId"),
        useFormState: /* @__PURE__ */ __name(function(action) {
          currentHookNameInDev = "useFormState";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return rerenderActionState(action);
        }, "useFormState"),
        useActionState: /* @__PURE__ */ __name(function(action) {
          currentHookNameInDev = "useActionState";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return rerenderActionState(action);
        }, "useActionState"),
        useOptimistic: /* @__PURE__ */ __name(function(passthrough, reducer) {
          currentHookNameInDev = "useOptimistic";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return rerenderOptimistic(passthrough, reducer);
        }, "useOptimistic"),
        useMemoCache: /* @__PURE__ */ __name(function(size) {
          warnInvalidHookAccess();
          return useMemoCache(size);
        }, "useMemoCache"),
        useHostTransitionStatus,
        useCacheRefresh: /* @__PURE__ */ __name(function() {
          currentHookNameInDev = "useCacheRefresh";
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        }, "useCacheRefresh")
      };
      var callComponent = {
        "react-stack-bottom-frame": /* @__PURE__ */ __name(function(Component, props, secondArg) {
          var wasRendering = isRendering;
          isRendering = true;
          try {
            return Component(props, secondArg);
          } finally {
            isRendering = wasRendering;
          }
        }, "react-stack-bottom-frame")
      }, callComponentInDEV = callComponent["react-stack-bottom-frame"].bind(callComponent), callRender = {
        "react-stack-bottom-frame": /* @__PURE__ */ __name(function(instance) {
          var wasRendering = isRendering;
          isRendering = true;
          try {
            return instance.render();
          } finally {
            isRendering = wasRendering;
          }
        }, "react-stack-bottom-frame")
      }, callRenderInDEV = callRender["react-stack-bottom-frame"].bind(callRender), callComponentDidMount = {
        "react-stack-bottom-frame": /* @__PURE__ */ __name(function(finishedWork, instance) {
          try {
            instance.componentDidMount();
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
        }, "react-stack-bottom-frame")
      }, callComponentDidMountInDEV = callComponentDidMount["react-stack-bottom-frame"].bind(callComponentDidMount), callComponentDidUpdate = {
        "react-stack-bottom-frame": /* @__PURE__ */ __name(function(finishedWork, instance, prevProps, prevState, snapshot) {
          try {
            instance.componentDidUpdate(prevProps, prevState, snapshot);
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
        }, "react-stack-bottom-frame")
      }, callComponentDidUpdateInDEV = callComponentDidUpdate["react-stack-bottom-frame"].bind(callComponentDidUpdate), callComponentDidCatch = {
        "react-stack-bottom-frame": /* @__PURE__ */ __name(function(instance, errorInfo) {
          var stack = errorInfo.stack;
          instance.componentDidCatch(errorInfo.value, {
            componentStack: null !== stack ? stack : ""
          });
        }, "react-stack-bottom-frame")
      }, callComponentDidCatchInDEV = callComponentDidCatch["react-stack-bottom-frame"].bind(callComponentDidCatch), callComponentWillUnmount = {
        "react-stack-bottom-frame": /* @__PURE__ */ __name(function(current2, nearestMountedAncestor, instance) {
          try {
            instance.componentWillUnmount();
          } catch (error) {
            captureCommitPhaseError(current2, nearestMountedAncestor, error);
          }
        }, "react-stack-bottom-frame")
      }, callComponentWillUnmountInDEV = callComponentWillUnmount["react-stack-bottom-frame"].bind(callComponentWillUnmount), callCreate = {
        "react-stack-bottom-frame": /* @__PURE__ */ __name(function(effect) {
          null != effect.resourceKind && console.error(
            "Expected only SimpleEffects when enableUseEffectCRUDOverload is disabled, got %s",
            effect.resourceKind
          );
          var create3 = effect.create;
          effect = effect.inst;
          create3 = create3();
          return effect.destroy = create3;
        }, "react-stack-bottom-frame")
      }, callCreateInDEV = callCreate["react-stack-bottom-frame"].bind(callCreate), callDestroy = {
        "react-stack-bottom-frame": /* @__PURE__ */ __name(function(current2, nearestMountedAncestor, destroy) {
          try {
            destroy();
          } catch (error) {
            captureCommitPhaseError(current2, nearestMountedAncestor, error);
          }
        }, "react-stack-bottom-frame")
      }, callDestroyInDEV = callDestroy["react-stack-bottom-frame"].bind(callDestroy), callLazyInit = {
        "react-stack-bottom-frame": /* @__PURE__ */ __name(function(lazy) {
          var init = lazy._init;
          return init(lazy._payload);
        }, "react-stack-bottom-frame")
      }, callLazyInitInDEV = callLazyInit["react-stack-bottom-frame"].bind(callLazyInit), thenableState = null, thenableIndexCounter = 0, currentDebugInfo = null, didWarnAboutMaps;
      var didWarnAboutGenerators = didWarnAboutMaps = false;
      var ownerHasKeyUseWarning = {};
      var ownerHasFunctionTypeWarning = {};
      var ownerHasSymbolTypeWarning = {};
      warnForMissingKey = /* @__PURE__ */ __name(function(returnFiber, workInProgress2, child) {
        if (null !== child && "object" === typeof child && child._store && (!child._store.validated && null == child.key || 2 === child._store.validated)) {
          if ("object" !== typeof child._store)
            throw Error(
              "React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue."
            );
          child._store.validated = 1;
          var componentName2 = getComponentNameFromFiber(returnFiber), componentKey = componentName2 || "null";
          if (!ownerHasKeyUseWarning[componentKey]) {
            ownerHasKeyUseWarning[componentKey] = true;
            child = child._owner;
            returnFiber = returnFiber._debugOwner;
            var currentComponentErrorInfo = "";
            returnFiber && "number" === typeof returnFiber.tag && (componentKey = getComponentNameFromFiber(returnFiber)) && (currentComponentErrorInfo = "\n\nCheck the render method of `" + componentKey + "`.");
            currentComponentErrorInfo || componentName2 && (currentComponentErrorInfo = "\n\nCheck the top-level render call using <" + componentName2 + ">.");
            var childOwnerAppendix = "";
            null != child && returnFiber !== child && (componentName2 = null, "number" === typeof child.tag ? componentName2 = getComponentNameFromFiber(child) : "string" === typeof child.name && (componentName2 = child.name), componentName2 && (childOwnerAppendix = " It was passed a child from " + componentName2 + "."));
            runWithFiberInDEV(workInProgress2, function() {
              console.error(
                'Each child in a list should have a unique "key" prop.%s%s See https://react.dev/link/warning-keys for more information.',
                currentComponentErrorInfo,
                childOwnerAppendix
              );
            });
          }
        }
      }, "warnForMissingKey");
      var reconcileChildFibers = createChildReconciler(true), mountChildFibers = createChildReconciler(false), suspenseHandlerStackCursor = createCursor(null), shellBoundary = null, SubtreeSuspenseContextMask = 1, ForceSuspenseFallback = 2, suspenseStackCursor = createCursor(0), fakeInternalInstance = {};
      var didWarnAboutStateAssignmentForComponent = /* @__PURE__ */ new Set();
      var didWarnAboutUninitializedState = /* @__PURE__ */ new Set();
      var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = /* @__PURE__ */ new Set();
      var didWarnAboutLegacyLifecyclesAndDerivedState = /* @__PURE__ */ new Set();
      var didWarnAboutDirectlyAssigningPropsToState = /* @__PURE__ */ new Set();
      var didWarnAboutUndefinedDerivedState = /* @__PURE__ */ new Set();
      var didWarnAboutContextTypes$1 = /* @__PURE__ */ new Set();
      var didWarnAboutChildContextTypes = /* @__PURE__ */ new Set();
      var didWarnAboutInvalidateContextType = /* @__PURE__ */ new Set();
      var didWarnOnInvalidCallback = /* @__PURE__ */ new Set();
      Object.freeze(fakeInternalInstance);
      var classComponentUpdater = {
        enqueueSetState: /* @__PURE__ */ __name(function(inst, payload, callback) {
          inst = inst._reactInternals;
          var lane = requestUpdateLane(inst), update2 = createUpdate(lane);
          update2.payload = payload;
          void 0 !== callback && null !== callback && (warnOnInvalidCallback(callback), update2.callback = callback);
          payload = enqueueUpdate(inst, update2, lane);
          null !== payload && (scheduleUpdateOnFiber(payload, inst, lane), entangleTransitions(payload, inst, lane));
          markStateUpdateScheduled(inst, lane);
        }, "enqueueSetState"),
        enqueueReplaceState: /* @__PURE__ */ __name(function(inst, payload, callback) {
          inst = inst._reactInternals;
          var lane = requestUpdateLane(inst), update2 = createUpdate(lane);
          update2.tag = ReplaceState;
          update2.payload = payload;
          void 0 !== callback && null !== callback && (warnOnInvalidCallback(callback), update2.callback = callback);
          payload = enqueueUpdate(inst, update2, lane);
          null !== payload && (scheduleUpdateOnFiber(payload, inst, lane), entangleTransitions(payload, inst, lane));
          markStateUpdateScheduled(inst, lane);
        }, "enqueueReplaceState"),
        enqueueForceUpdate: /* @__PURE__ */ __name(function(inst, callback) {
          inst = inst._reactInternals;
          var lane = requestUpdateLane(inst), update2 = createUpdate(lane);
          update2.tag = ForceUpdate;
          void 0 !== callback && null !== callback && (warnOnInvalidCallback(callback), update2.callback = callback);
          callback = enqueueUpdate(inst, update2, lane);
          null !== callback && (scheduleUpdateOnFiber(callback, inst, lane), entangleTransitions(callback, inst, lane));
          null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markForceUpdateScheduled && injectedProfilingHooks.markForceUpdateScheduled(inst, lane);
        }, "enqueueForceUpdate")
      }, reportGlobalError = "function" === typeof reportError ? reportError : function(error) {
        if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
          var event = new window.ErrorEvent("error", {
            bubbles: true,
            cancelable: true,
            message: "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error),
            error
          });
          if (!window.dispatchEvent(event)) return;
        } else if ("object" === typeof process && "function" === typeof process.emit) {
          process.emit("uncaughtException", error);
          return;
        }
        console.error(error);
      }, componentName = null, errorBoundaryName = null, SelectiveHydrationException = Error(
        "This is not a real error. It's an implementation detail of React's selective hydration feature. If this leaks into userspace, it's a bug in React. Please file an issue."
      ), didReceiveUpdate = false;
      var didWarnAboutBadClass = {};
      var didWarnAboutContextTypeOnFunctionComponent = {};
      var didWarnAboutContextTypes = {};
      var didWarnAboutGetDerivedStateOnFunctionComponent = {};
      var didWarnAboutReassigningProps = false;
      var didWarnAboutRevealOrder = {};
      var didWarnAboutTailOptions = {};
      var SUSPENDED_MARKER = {
        dehydrated: null,
        treeContext: null,
        retryLane: 0,
        hydrationErrors: null
      }, hasWarnedAboutUsingNoValuePropOnContextProvider = false, didWarnAboutUndefinedSnapshotBeforeUpdate = null;
      didWarnAboutUndefinedSnapshotBeforeUpdate = /* @__PURE__ */ new Set();
      var offscreenSubtreeIsHidden = false, offscreenSubtreeWasHidden = false, needsFormReset = false, PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set, nextEffect = null, inProgressLanes = null, inProgressRoot = null, hostParent = null, hostParentIsContainer = false, currentHoistableRoot = null, suspenseyCommitFlag = 8192, DefaultAsyncDispatcher = {
        getCacheForType: /* @__PURE__ */ __name(function(resourceType) {
          var cache5 = readContext(CacheContext), cacheForType = cache5.data.get(resourceType);
          void 0 === cacheForType && (cacheForType = resourceType(), cache5.data.set(resourceType, cacheForType));
          return cacheForType;
        }, "getCacheForType"),
        getOwner: /* @__PURE__ */ __name(function() {
          return current;
        }, "getOwner")
      }, COMPONENT_TYPE = 0, HAS_PSEUDO_CLASS_TYPE = 1, ROLE_TYPE = 2, TEST_NAME_TYPE = 3, TEXT_TYPE = 4;
      if ("function" === typeof Symbol && Symbol.for) {
        var symbolFor = Symbol.for;
        COMPONENT_TYPE = symbolFor("selector.component");
        HAS_PSEUDO_CLASS_TYPE = symbolFor("selector.has_pseudo_class");
        ROLE_TYPE = symbolFor("selector.role");
        TEST_NAME_TYPE = symbolFor("selector.test_id");
        TEXT_TYPE = symbolFor("selector.text");
      }
      var commitHooks = [], PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map, NoContext = 0, RenderContext = 2, CommitContext = 4, RootInProgress = 0, RootFatalErrored = 1, RootErrored = 2, RootSuspended = 3, RootSuspendedWithDelay = 4, RootSuspendedAtTheShell = 6, RootCompleted = 5, executionContext = NoContext, workInProgressRoot = null, workInProgress = null, workInProgressRootRenderLanes = 0, NotSuspended = 0, SuspendedOnError = 1, SuspendedOnData = 2, SuspendedOnImmediate = 3, SuspendedOnInstance = 4, SuspendedOnInstanceAndReadyToContinue = 5, SuspendedOnDeprecatedThrowPromise = 6, SuspendedAndReadyToContinue = 7, SuspendedOnHydration = 8, SuspendedOnAction = 9, workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, workInProgressRootDidSkipSuspendedSiblings = false, workInProgressRootIsPrerendering = false, workInProgressRootDidAttachPingListener = false, entangledRenderLanes = 0, workInProgressRootExitStatus = RootInProgress, workInProgressRootSkippedLanes = 0, workInProgressRootInterleavedUpdatedLanes = 0, workInProgressRootPingedLanes = 0, workInProgressDeferredLane = 0, workInProgressSuspendedRetryLanes = 0, workInProgressRootConcurrentErrors = null, workInProgressRootRecoverableErrors = null, workInProgressRootDidIncludeRecursiveRenderUpdate = false, globalMostRecentFallbackTime = 0, FALLBACK_THROTTLE_MS = 300, workInProgressRootRenderTargetTime = Infinity, RENDER_TIMEOUT_MS = 500, workInProgressTransitions = null, legacyErrorBoundariesThatAlreadyFailed = null, IMMEDIATE_COMMIT = 0, SUSPENDED_COMMIT = 1, THROTTLED_COMMIT = 2, NO_PENDING_EFFECTS = 0, PENDING_MUTATION_PHASE = 1, PENDING_LAYOUT_PHASE = 2, PENDING_AFTER_MUTATION_PHASE = 3, PENDING_SPAWNED_WORK = 4, PENDING_PASSIVE_PHASE = 5, pendingEffectsStatus = 0, pendingEffectsRoot = null, pendingFinishedWork = null, pendingEffectsLanes = 0, pendingEffectsRemainingLanes = 0, pendingPassiveTransitions = null, pendingRecoverableErrors = null, NESTED_UPDATE_LIMIT = 50, nestedUpdateCount = 0, rootWithNestedUpdates = null, isFlushingPassiveEffects = false, didScheduleUpdateDuringPassiveEffects = false, NESTED_PASSIVE_UPDATE_LIMIT = 50, nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = null, isRunningInsertionEffect = false, didWarnStateUpdateForNotYetMountedComponent = null, didWarnAboutUpdateInRender = false;
      var didWarnAboutUpdateInRenderForAnotherComponent = /* @__PURE__ */ new Set();
      var fakeActCallbackNode = {}, resolveFamily = null, failedBoundaries = null;
      var hasBadMapPolyfill = false;
      try {
        var nonExtensibleObject = Object.preventExtensions({});
        /* @__PURE__ */ new Map([[nonExtensibleObject, null]]);
        /* @__PURE__ */ new Set([nonExtensibleObject]);
      } catch (e2) {
        hasBadMapPolyfill = true;
      }
      var didWarnAboutNestedUpdates = false;
      var didWarnAboutFindNodeInStrictMode = {};
      var overrideHookState = null, overrideHookStateDeletePath = null, overrideHookStateRenamePath = null, overrideProps = null, overridePropsDeletePath = null, overridePropsRenamePath = null, scheduleUpdate = null, setErrorHandler = null, setSuspenseHandler = null;
      overrideHookState = /* @__PURE__ */ __name(function(fiber, id, path108, value) {
        id = findHook(fiber, id);
        null !== id && (path108 = copyWithSetImpl(id.memoizedState, path108, 0, value), id.memoizedState = path108, id.baseState = path108, fiber.memoizedProps = assign({}, fiber.memoizedProps), path108 = enqueueConcurrentRenderForLane(fiber, 2), null !== path108 && scheduleUpdateOnFiber(path108, fiber, 2));
      }, "overrideHookState");
      overrideHookStateDeletePath = /* @__PURE__ */ __name(function(fiber, id, path108) {
        id = findHook(fiber, id);
        null !== id && (path108 = copyWithDeleteImpl(id.memoizedState, path108, 0), id.memoizedState = path108, id.baseState = path108, fiber.memoizedProps = assign({}, fiber.memoizedProps), path108 = enqueueConcurrentRenderForLane(fiber, 2), null !== path108 && scheduleUpdateOnFiber(path108, fiber, 2));
      }, "overrideHookStateDeletePath");
      overrideHookStateRenamePath = /* @__PURE__ */ __name(function(fiber, id, oldPath, newPath) {
        id = findHook(fiber, id);
        null !== id && (oldPath = copyWithRename(id.memoizedState, oldPath, newPath), id.memoizedState = oldPath, id.baseState = oldPath, fiber.memoizedProps = assign({}, fiber.memoizedProps), oldPath = enqueueConcurrentRenderForLane(fiber, 2), null !== oldPath && scheduleUpdateOnFiber(oldPath, fiber, 2));
      }, "overrideHookStateRenamePath");
      overrideProps = /* @__PURE__ */ __name(function(fiber, path108, value) {
        fiber.pendingProps = copyWithSetImpl(fiber.memoizedProps, path108, 0, value);
        fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
        path108 = enqueueConcurrentRenderForLane(fiber, 2);
        null !== path108 && scheduleUpdateOnFiber(path108, fiber, 2);
      }, "overrideProps");
      overridePropsDeletePath = /* @__PURE__ */ __name(function(fiber, path108) {
        fiber.pendingProps = copyWithDeleteImpl(fiber.memoizedProps, path108, 0);
        fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
        path108 = enqueueConcurrentRenderForLane(fiber, 2);
        null !== path108 && scheduleUpdateOnFiber(path108, fiber, 2);
      }, "overridePropsDeletePath");
      overridePropsRenamePath = /* @__PURE__ */ __name(function(fiber, oldPath, newPath) {
        fiber.pendingProps = copyWithRename(
          fiber.memoizedProps,
          oldPath,
          newPath
        );
        fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
        oldPath = enqueueConcurrentRenderForLane(fiber, 2);
        null !== oldPath && scheduleUpdateOnFiber(oldPath, fiber, 2);
      }, "overridePropsRenamePath");
      scheduleUpdate = /* @__PURE__ */ __name(function(fiber) {
        var root = enqueueConcurrentRenderForLane(fiber, 2);
        null !== root && scheduleUpdateOnFiber(root, fiber, 2);
      }, "scheduleUpdate");
      setErrorHandler = /* @__PURE__ */ __name(function(newShouldErrorImpl) {
        shouldErrorImpl = newShouldErrorImpl;
      }, "setErrorHandler");
      setSuspenseHandler = /* @__PURE__ */ __name(function(newShouldSuspendImpl) {
        shouldSuspendImpl = newShouldSuspendImpl;
      }, "setSuspenseHandler");
      exports3.attemptContinuousHydration = function(fiber) {
        if (13 === fiber.tag) {
          var root = enqueueConcurrentRenderForLane(fiber, 67108864);
          null !== root && scheduleUpdateOnFiber(root, fiber, 67108864);
          markRetryLaneIfNotHydrated(fiber, 67108864);
        }
      };
      exports3.attemptHydrationAtCurrentPriority = function(fiber) {
        if (13 === fiber.tag) {
          var lane = requestUpdateLane(fiber);
          lane = getBumpedLaneForHydrationByLane(lane);
          var root = enqueueConcurrentRenderForLane(fiber, lane);
          null !== root && scheduleUpdateOnFiber(root, fiber, lane);
          markRetryLaneIfNotHydrated(fiber, lane);
        }
      };
      exports3.attemptSynchronousHydration = function(fiber) {
        switch (fiber.tag) {
          case 3:
            fiber = fiber.stateNode;
            if (fiber.current.memoizedState.isDehydrated) {
              var lanes = getHighestPriorityLanes(fiber.pendingLanes);
              if (0 !== lanes) {
                fiber.pendingLanes |= 2;
                for (fiber.entangledLanes |= 2; lanes; ) {
                  var lane = 1 << 31 - clz32(lanes);
                  fiber.entanglements[1] |= lane;
                  lanes &= ~lane;
                }
                ensureRootIsScheduled(fiber);
                (executionContext & (RenderContext | CommitContext)) === NoContext && (workInProgressRootRenderTargetTime = now$1() + RENDER_TIMEOUT_MS, flushSyncWorkAcrossRoots_impl(0, false));
              }
            }
            break;
          case 13:
            lanes = enqueueConcurrentRenderForLane(fiber, 2), null !== lanes && scheduleUpdateOnFiber(lanes, fiber, 2), flushSyncWork(), markRetryLaneIfNotHydrated(fiber, 2);
        }
      };
      exports3.batchedUpdates = function(fn, a) {
        return fn(a);
      };
      exports3.createComponentSelector = function(component) {
        return { $$typeof: COMPONENT_TYPE, value: component };
      };
      exports3.createContainer = function(containerInfo, tag2, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, transitionCallbacks) {
        return createFiberRoot(
          containerInfo,
          tag2,
          false,
          null,
          hydrationCallbacks,
          isStrictMode,
          identifierPrefix,
          onUncaughtError,
          onCaughtError,
          onRecoverableError,
          transitionCallbacks,
          null
        );
      };
      exports3.createHasPseudoClassSelector = function(selectors) {
        return { $$typeof: HAS_PSEUDO_CLASS_TYPE, value: selectors };
      };
      exports3.createHydrationContainer = function(initialChildren, callback, containerInfo, tag2, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, transitionCallbacks, formState) {
        initialChildren = createFiberRoot(
          containerInfo,
          tag2,
          true,
          initialChildren,
          hydrationCallbacks,
          isStrictMode,
          identifierPrefix,
          onUncaughtError,
          onCaughtError,
          onRecoverableError,
          transitionCallbacks,
          formState
        );
        initialChildren.context = getContextForSubtree(null);
        containerInfo = initialChildren.current;
        tag2 = requestUpdateLane(containerInfo);
        tag2 = getBumpedLaneForHydrationByLane(tag2);
        hydrationCallbacks = createUpdate(tag2);
        hydrationCallbacks.callback = void 0 !== callback && null !== callback ? callback : null;
        enqueueUpdate(containerInfo, hydrationCallbacks, tag2);
        callback = tag2;
        initialChildren.current.lanes = callback;
        markRootUpdated$1(initialChildren, callback);
        ensureRootIsScheduled(initialChildren);
        return initialChildren;
      };
      exports3.createPortal = function(children, containerInfo, implementation) {
        var key = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null;
        try {
          testStringCoercion(key);
          var JSCompiler_inline_result = false;
        } catch (e$6) {
          JSCompiler_inline_result = true;
        }
        JSCompiler_inline_result && (console.error(
          "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
          "function" === typeof Symbol && Symbol.toStringTag && key[Symbol.toStringTag] || key.constructor.name || "Object"
        ), testStringCoercion(key));
        return {
          $$typeof: REACT_PORTAL_TYPE,
          key: null == key ? null : "" + key,
          children,
          containerInfo,
          implementation
        };
      };
      exports3.createRoleSelector = function(role) {
        return { $$typeof: ROLE_TYPE, value: role };
      };
      exports3.createTestNameSelector = function(id) {
        return { $$typeof: TEST_NAME_TYPE, value: id };
      };
      exports3.createTextSelector = function(text) {
        return { $$typeof: TEXT_TYPE, value: text };
      };
      exports3.defaultOnCaughtError = function(error) {
        var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component." : "The above error occurred in one of your React components.", recreateMessage = "React will try to recreate this component tree from scratch using the error boundary you provided, " + ((errorBoundaryName || "Anonymous") + ".");
        "object" === typeof error && null !== error && "string" === typeof error.environmentName ? bindToConsole(
          "error",
          ["%o\n\n%s\n\n%s\n", error, componentNameMessage, recreateMessage],
          error.environmentName
        )() : console.error(
          "%o\n\n%s\n\n%s\n",
          error,
          componentNameMessage,
          recreateMessage
        );
      };
      exports3.defaultOnRecoverableError = function(error) {
        reportGlobalError(error);
      };
      exports3.defaultOnUncaughtError = function(error) {
        reportGlobalError(error);
        console.warn(
          "%s\n\n%s\n",
          componentName ? "An error occurred in the <" + componentName + "> component." : "An error occurred in one of your React components.",
          "Consider adding an error boundary to your tree to customize error handling behavior.\nVisit https://react.dev/link/error-boundaries to learn more about error boundaries."
        );
      };
      exports3.deferredUpdates = function(fn) {
        var prevTransition = ReactSharedInternals.T, previousPriority = getCurrentUpdatePriority();
        try {
          return setCurrentUpdatePriority(32), ReactSharedInternals.T = null, fn();
        } finally {
          setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = prevTransition;
        }
      };
      exports3.discreteUpdates = function(fn, a, b, c3, d) {
        var prevTransition = ReactSharedInternals.T, previousPriority = getCurrentUpdatePriority();
        try {
          return setCurrentUpdatePriority(2), ReactSharedInternals.T = null, fn(a, b, c3, d);
        } finally {
          setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = prevTransition, executionContext === NoContext && (workInProgressRootRenderTargetTime = now$1() + RENDER_TIMEOUT_MS);
        }
      };
      exports3.findAllNodes = findAllNodes;
      exports3.findBoundingRects = function(hostRoot, selectors) {
        if (!supportsTestSelectors)
          throw Error("Test selector API is not supported by this renderer.");
        selectors = findAllNodes(hostRoot, selectors);
        hostRoot = [];
        for (var i = 0; i < selectors.length; i++)
          hostRoot.push(getBoundingRect(selectors[i]));
        for (selectors = hostRoot.length - 1; 0 < selectors; selectors--) {
          i = hostRoot[selectors];
          for (var targetLeft = i.x, targetRight = targetLeft + i.width, targetTop = i.y, targetBottom = targetTop + i.height, j = selectors - 1; 0 <= j; j--)
            if (selectors !== j) {
              var otherRect = hostRoot[j], otherLeft = otherRect.x, otherRight = otherLeft + otherRect.width, otherTop = otherRect.y, otherBottom = otherTop + otherRect.height;
              if (targetLeft >= otherLeft && targetTop >= otherTop && targetRight <= otherRight && targetBottom <= otherBottom) {
                hostRoot.splice(selectors, 1);
                break;
              } else if (!(targetLeft !== otherLeft || i.width !== otherRect.width || otherBottom < targetTop || otherTop > targetBottom)) {
                otherTop > targetTop && (otherRect.height += otherTop - targetTop, otherRect.y = targetTop);
                otherBottom < targetBottom && (otherRect.height = targetBottom - otherTop);
                hostRoot.splice(selectors, 1);
                break;
              } else if (!(targetTop !== otherTop || i.height !== otherRect.height || otherRight < targetLeft || otherLeft > targetRight)) {
                otherLeft > targetLeft && (otherRect.width += otherLeft - targetLeft, otherRect.x = targetLeft);
                otherRight < targetRight && (otherRect.width = targetRight - otherLeft);
                hostRoot.splice(selectors, 1);
                break;
              }
            }
        }
        return hostRoot;
      };
      exports3.findHostInstance = function(component) {
        var fiber = component._reactInternals;
        if (void 0 === fiber) {
          if ("function" === typeof component.render)
            throw Error("Unable to find node on an unmounted component.");
          component = Object.keys(component).join(",");
          throw Error(
            "Argument appears to not be a ReactComponent. Keys: " + component
          );
        }
        component = findCurrentHostFiber(fiber);
        return null === component ? null : getPublicInstance(component.stateNode);
      };
      exports3.findHostInstanceWithNoPortals = function(fiber) {
        fiber = findCurrentFiberUsingSlowPath(fiber);
        fiber = null !== fiber ? findCurrentHostFiberWithNoPortalsImpl(fiber) : null;
        return null === fiber ? null : getPublicInstance(fiber.stateNode);
      };
      exports3.findHostInstanceWithWarning = function(component, methodName) {
        var fiber = component._reactInternals;
        if (void 0 === fiber) {
          if ("function" === typeof component.render)
            throw Error("Unable to find node on an unmounted component.");
          component = Object.keys(component).join(",");
          throw Error(
            "Argument appears to not be a ReactComponent. Keys: " + component
          );
        }
        component = findCurrentHostFiber(fiber);
        if (null === component) return null;
        if (component.mode & 8) {
          var componentName2 = getComponentNameFromFiber(fiber) || "Component";
          didWarnAboutFindNodeInStrictMode[componentName2] || (didWarnAboutFindNodeInStrictMode[componentName2] = true, runWithFiberInDEV(component, function() {
            fiber.mode & 8 ? console.error(
              "%s is deprecated in StrictMode. %s was passed an instance of %s which is inside StrictMode. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://react.dev/link/strict-mode-find-node",
              methodName,
              methodName,
              componentName2
            ) : console.error(
              "%s is deprecated in StrictMode. %s was passed an instance of %s which renders StrictMode children. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://react.dev/link/strict-mode-find-node",
              methodName,
              methodName,
              componentName2
            );
          }));
        }
        return getPublicInstance(component.stateNode);
      };
      exports3.flushPassiveEffects = flushPendingEffects;
      exports3.flushSyncFromReconciler = function(fn) {
        var prevExecutionContext = executionContext;
        executionContext |= 1;
        var prevTransition = ReactSharedInternals.T, previousPriority = getCurrentUpdatePriority();
        try {
          if (setCurrentUpdatePriority(2), ReactSharedInternals.T = null, fn)
            return fn();
        } finally {
          setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = prevTransition, executionContext = prevExecutionContext, (executionContext & (RenderContext | CommitContext)) === NoContext && flushSyncWorkAcrossRoots_impl(0, false);
        }
      };
      exports3.flushSyncWork = flushSyncWork;
      exports3.focusWithin = function(hostRoot, selectors) {
        if (!supportsTestSelectors)
          throw Error("Test selector API is not supported by this renderer.");
        hostRoot = findFiberRootForHostRoot(hostRoot);
        selectors = findPaths(hostRoot, selectors);
        selectors = Array.from(selectors);
        for (hostRoot = 0; hostRoot < selectors.length; ) {
          var fiber = selectors[hostRoot++], tag2 = fiber.tag;
          if (!isHiddenSubtree(fiber)) {
            if ((5 === tag2 || 26 === tag2 || 27 === tag2) && setFocusIfFocusable(fiber.stateNode))
              return true;
            for (fiber = fiber.child; null !== fiber; )
              selectors.push(fiber), fiber = fiber.sibling;
          }
        }
        return false;
      };
      exports3.getFindAllNodesFailureDescription = function(hostRoot, selectors) {
        if (!supportsTestSelectors)
          throw Error("Test selector API is not supported by this renderer.");
        var maxSelectorIndex = 0, matchedNames = [];
        hostRoot = [findFiberRootForHostRoot(hostRoot), 0];
        for (var index = 0; index < hostRoot.length; ) {
          var fiber = hostRoot[index++], tag2 = fiber.tag, selectorIndex = hostRoot[index++], selector = selectors[selectorIndex];
          if (5 !== tag2 && 26 !== tag2 && 27 !== tag2 || !isHiddenSubtree(fiber)) {
            if (matchSelector(fiber, selector) && (matchedNames.push(selectorToString(selector)), selectorIndex++, selectorIndex > maxSelectorIndex && (maxSelectorIndex = selectorIndex)), selectorIndex < selectors.length)
              for (fiber = fiber.child; null !== fiber; )
                hostRoot.push(fiber, selectorIndex), fiber = fiber.sibling;
          }
        }
        if (maxSelectorIndex < selectors.length) {
          for (hostRoot = []; maxSelectorIndex < selectors.length; maxSelectorIndex++)
            hostRoot.push(selectorToString(selectors[maxSelectorIndex]));
          return "findAllNodes was able to match part of the selector:\n  " + (matchedNames.join(" > ") + "\n\nNo matching component was found for:\n  ") + hostRoot.join(" > ");
        }
        return null;
      };
      exports3.getPublicRootInstance = function(container) {
        container = container.current;
        if (!container.child) return null;
        switch (container.child.tag) {
          case 27:
          case 5:
            return getPublicInstance(container.child.stateNode);
          default:
            return container.child.stateNode;
        }
      };
      exports3.injectIntoDevTools = function() {
        var internals = {
          bundleType: 1,
          version: rendererVersion,
          rendererPackageName,
          currentDispatcherRef: ReactSharedInternals,
          reconcilerVersion: "19.1.0"
        };
        null !== extraDevToolsConfig && (internals.rendererConfig = extraDevToolsConfig);
        internals.overrideHookState = overrideHookState;
        internals.overrideHookStateDeletePath = overrideHookStateDeletePath;
        internals.overrideHookStateRenamePath = overrideHookStateRenamePath;
        internals.overrideProps = overrideProps;
        internals.overridePropsDeletePath = overridePropsDeletePath;
        internals.overridePropsRenamePath = overridePropsRenamePath;
        internals.scheduleUpdate = scheduleUpdate;
        internals.setErrorHandler = setErrorHandler;
        internals.setSuspenseHandler = setSuspenseHandler;
        internals.scheduleRefresh = scheduleRefresh;
        internals.scheduleRoot = scheduleRoot;
        internals.setRefreshHandler = setRefreshHandler;
        internals.getCurrentFiber = getCurrentFiberForDevTools;
        internals.getLaneLabelMap = getLaneLabelMap;
        internals.injectProfilingHooks = injectProfilingHooks;
        return injectInternals(internals);
      };
      exports3.isAlreadyRendering = function() {
        return (executionContext & (RenderContext | CommitContext)) !== NoContext;
      };
      exports3.observeVisibleRects = function(hostRoot, selectors, callback, options2) {
        function commitHook() {
          var nextInstanceRoots = findAllNodes(hostRoot, selectors);
          instanceRoots.forEach(function(target) {
            0 > nextInstanceRoots.indexOf(target) && unobserve(target);
          });
          nextInstanceRoots.forEach(function(target) {
            0 > instanceRoots.indexOf(target) && observe(target);
          });
        }
        __name(commitHook, "commitHook");
        if (!supportsTestSelectors)
          throw Error("Test selector API is not supported by this renderer.");
        var instanceRoots = findAllNodes(hostRoot, selectors);
        callback = setupIntersectionObserver(instanceRoots, callback, options2);
        var disconnect = callback.disconnect, observe = callback.observe, unobserve = callback.unobserve;
        commitHooks.push(commitHook);
        return {
          disconnect: /* @__PURE__ */ __name(function() {
            var index = commitHooks.indexOf(commitHook);
            0 <= index && commitHooks.splice(index, 1);
            disconnect();
          }, "disconnect")
        };
      };
      exports3.shouldError = function(fiber) {
        return shouldErrorImpl(fiber);
      };
      exports3.shouldSuspend = function(fiber) {
        return shouldSuspendImpl(fiber);
      };
      exports3.startHostTransition = function(formFiber, pendingState, action, formData) {
        if (5 !== formFiber.tag)
          throw Error(
            "Expected the form instance to be a HostComponent. This is a bug in React."
          );
        var queue = ensureFormComponentIsStateful(formFiber).queue;
        startTransition(
          formFiber,
          queue,
          pendingState,
          NotPendingTransition,
          null === action ? noop6 : function() {
            null === ReactSharedInternals.T && console.error(
              "requestFormReset was called outside a transition or action. To fix, move to an action, or wrap with startTransition."
            );
            var resetStateQueue = ensureFormComponentIsStateful(formFiber).next.queue;
            dispatchSetStateInternal(
              formFiber,
              resetStateQueue,
              {},
              requestUpdateLane(formFiber)
            );
            return action(formData);
          }
        );
      };
      exports3.updateContainer = function(element, container, parentComponent, callback) {
        var current2 = container.current, lane = requestUpdateLane(current2);
        updateContainerImpl(
          current2,
          lane,
          element,
          container,
          parentComponent,
          callback
        );
        return lane;
      };
      exports3.updateContainerSync = updateContainerSync;
      return exports3;
    }, module2.exports.default = module2.exports, Object.defineProperty(module2.exports, "__esModule", { value: true }));
  }
});

// node_modules/react-reconciler/index.js
var require_react_reconciler = __commonJS({
  "node_modules/react-reconciler/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    if (process.env.NODE_ENV === "production") {
      module2.exports = require_react_reconciler_production();
    } else {
      module2.exports = require_react_reconciler_development();
    }
  }
});

// node_modules/ink/node_modules/emoji-regex/index.js
var require_emoji_regex2 = __commonJS({
  "node_modules/ink/node_modules/emoji-regex/index.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = () => {
      return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g;
    };
  }
});

// node_modules/cli-truncate/node_modules/emoji-regex/index.js
var require_emoji_regex3 = __commonJS({
  "node_modules/cli-truncate/node_modules/emoji-regex/index.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = () => {
      return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g;
    };
  }
});

// node_modules/ws/lib/constants.js
var require_constants2 = __commonJS({
  "node_modules/ws/lib/constants.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
    var hasBlob = typeof Blob !== "undefined";
    if (hasBlob) BINARY_TYPES.push("blob");
    module2.exports = {
      BINARY_TYPES,
      EMPTY_BUFFER: Buffer.alloc(0),
      GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
      hasBlob,
      kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
      kListener: Symbol("kListener"),
      kStatusCode: Symbol("status-code"),
      kWebSocket: Symbol("websocket"),
      NOOP: /* @__PURE__ */ __name(() => {
      }, "NOOP")
    };
  }
});

// node_modules/ws/lib/buffer-util.js
var require_buffer_util = __commonJS({
  "node_modules/ws/lib/buffer-util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { EMPTY_BUFFER } = require_constants2();
    var FastBuffer = Buffer[Symbol.species];
    function concat2(list3, totalLength) {
      if (list3.length === 0) return EMPTY_BUFFER;
      if (list3.length === 1) return list3[0];
      const target = Buffer.allocUnsafe(totalLength);
      let offset = 0;
      for (let i = 0; i < list3.length; i++) {
        const buf = list3[i];
        target.set(buf, offset);
        offset += buf.length;
      }
      if (offset < totalLength) {
        return new FastBuffer(target.buffer, target.byteOffset, offset);
      }
      return target;
    }
    __name(concat2, "concat");
    function _mask(source2, mask, output, offset, length) {
      for (let i = 0; i < length; i++) {
        output[offset + i] = source2[i] ^ mask[i & 3];
      }
    }
    __name(_mask, "_mask");
    function _unmask(buffer, mask) {
      for (let i = 0; i < buffer.length; i++) {
        buffer[i] ^= mask[i & 3];
      }
    }
    __name(_unmask, "_unmask");
    function toArrayBuffer(buf) {
      if (buf.length === buf.buffer.byteLength) {
        return buf.buffer;
      }
      return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
    }
    __name(toArrayBuffer, "toArrayBuffer");
    function toBuffer(data) {
      toBuffer.readOnly = true;
      if (Buffer.isBuffer(data)) return data;
      let buf;
      if (data instanceof ArrayBuffer) {
        buf = new FastBuffer(data);
      } else if (ArrayBuffer.isView(data)) {
        buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
      } else {
        buf = Buffer.from(data);
        toBuffer.readOnly = false;
      }
      return buf;
    }
    __name(toBuffer, "toBuffer");
    module2.exports = {
      concat: concat2,
      mask: _mask,
      toArrayBuffer,
      toBuffer,
      unmask: _unmask
    };
    if (!process.env.WS_NO_BUFFER_UTIL) {
      try {
        const bufferUtil = __require("bufferutil");
        module2.exports.mask = function(source2, mask, output, offset, length) {
          if (length < 48) _mask(source2, mask, output, offset, length);
          else bufferUtil.mask(source2, mask, output, offset, length);
        };
        module2.exports.unmask = function(buffer, mask) {
          if (buffer.length < 32) _unmask(buffer, mask);
          else bufferUtil.unmask(buffer, mask);
        };
      } catch (e2) {
      }
    }
  }
});

// node_modules/ws/lib/limiter.js
var require_limiter = __commonJS({
  "node_modules/ws/lib/limiter.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var kDone = Symbol("kDone");
    var kRun = Symbol("kRun");
    var Limiter = class {
      static {
        __name(this, "Limiter");
      }
      /**
       * Creates a new `Limiter`.
       *
       * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
       *     to run concurrently
       */
      constructor(concurrency) {
        this[kDone] = () => {
          this.pending--;
          this[kRun]();
        };
        this.concurrency = concurrency || Infinity;
        this.jobs = [];
        this.pending = 0;
      }
      /**
       * Adds a job to the queue.
       *
       * @param {Function} job The job to run
       * @public
       */
      add(job) {
        this.jobs.push(job);
        this[kRun]();
      }
      /**
       * Removes a job from the queue and runs it if possible.
       *
       * @private
       */
      [kRun]() {
        if (this.pending === this.concurrency) return;
        if (this.jobs.length) {
          const job = this.jobs.shift();
          this.pending++;
          job(this[kDone]);
        }
      }
    };
    module2.exports = Limiter;
  }
});

// node_modules/ws/lib/permessage-deflate.js
var require_permessage_deflate = __commonJS({
  "node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var zlib2 = __require("zlib");
    var bufferUtil = require_buffer_util();
    var Limiter = require_limiter();
    var { kStatusCode } = require_constants2();
    var FastBuffer = Buffer[Symbol.species];
    var TRAILER = Buffer.from([0, 0, 255, 255]);
    var kPerMessageDeflate = Symbol("permessage-deflate");
    var kTotalLength = Symbol("total-length");
    var kCallback = Symbol("callback");
    var kBuffers = Symbol("buffers");
    var kError = Symbol("error");
    var zlibLimiter;
    var PerMessageDeflate = class {
      static {
        __name(this, "PerMessageDeflate");
      }
      /**
       * Creates a PerMessageDeflate instance.
       *
       * @param {Object} [options] Configuration options
       * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
       *     for, or request, a custom client window size
       * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
       *     acknowledge disabling of client context takeover
       * @param {Number} [options.concurrencyLimit=10] The number of concurrent
       *     calls to zlib
       * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
       *     use of a custom server window size
       * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
       *     disabling of server context takeover
       * @param {Number} [options.threshold=1024] Size (in bytes) below which
       *     messages should not be compressed if context takeover is disabled
       * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
       *     deflate
       * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
       *     inflate
       * @param {Boolean} [isServer=false] Create the instance in either server or
       *     client mode
       * @param {Number} [maxPayload=0] The maximum allowed message length
       */
      constructor(options2, isServer, maxPayload) {
        this._maxPayload = maxPayload | 0;
        this._options = options2 || {};
        this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
        this._isServer = !!isServer;
        this._deflate = null;
        this._inflate = null;
        this.params = null;
        if (!zlibLimiter) {
          const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
          zlibLimiter = new Limiter(concurrency);
        }
      }
      /**
       * @type {String}
       */
      static get extensionName() {
        return "permessage-deflate";
      }
      /**
       * Create an extension negotiation offer.
       *
       * @return {Object} Extension parameters
       * @public
       */
      offer() {
        const params = {};
        if (this._options.serverNoContextTakeover) {
          params.server_no_context_takeover = true;
        }
        if (this._options.clientNoContextTakeover) {
          params.client_no_context_takeover = true;
        }
        if (this._options.serverMaxWindowBits) {
          params.server_max_window_bits = this._options.serverMaxWindowBits;
        }
        if (this._options.clientMaxWindowBits) {
          params.client_max_window_bits = this._options.clientMaxWindowBits;
        } else if (this._options.clientMaxWindowBits == null) {
          params.client_max_window_bits = true;
        }
        return params;
      }
      /**
       * Accept an extension negotiation offer/response.
       *
       * @param {Array} configurations The extension negotiation offers/reponse
       * @return {Object} Accepted configuration
       * @public
       */
      accept(configurations) {
        configurations = this.normalizeParams(configurations);
        this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
        return this.params;
      }
      /**
       * Releases all resources used by the extension.
       *
       * @public
       */
      cleanup() {
        if (this._inflate) {
          this._inflate.close();
          this._inflate = null;
        }
        if (this._deflate) {
          const callback = this._deflate[kCallback];
          this._deflate.close();
          this._deflate = null;
          if (callback) {
            callback(
              new Error(
                "The deflate stream was closed while data was being processed"
              )
            );
          }
        }
      }
      /**
       *  Accept an extension negotiation offer.
       *
       * @param {Array} offers The extension negotiation offers
       * @return {Object} Accepted configuration
       * @private
       */
      acceptAsServer(offers) {
        const opts = this._options;
        const accepted = offers.find((params) => {
          if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
            return false;
          }
          return true;
        });
        if (!accepted) {
          throw new Error("None of the extension offers can be accepted");
        }
        if (opts.serverNoContextTakeover) {
          accepted.server_no_context_takeover = true;
        }
        if (opts.clientNoContextTakeover) {
          accepted.client_no_context_takeover = true;
        }
        if (typeof opts.serverMaxWindowBits === "number") {
          accepted.server_max_window_bits = opts.serverMaxWindowBits;
        }
        if (typeof opts.clientMaxWindowBits === "number") {
          accepted.client_max_window_bits = opts.clientMaxWindowBits;
        } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
          delete accepted.client_max_window_bits;
        }
        return accepted;
      }
      /**
       * Accept the extension negotiation response.
       *
       * @param {Array} response The extension negotiation response
       * @return {Object} Accepted configuration
       * @private
       */
      acceptAsClient(response) {
        const params = response[0];
        if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
          throw new Error('Unexpected parameter "client_no_context_takeover"');
        }
        if (!params.client_max_window_bits) {
          if (typeof this._options.clientMaxWindowBits === "number") {
            params.client_max_window_bits = this._options.clientMaxWindowBits;
          }
        } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
          throw new Error(
            'Unexpected or invalid parameter "client_max_window_bits"'
          );
        }
        return params;
      }
      /**
       * Normalize parameters.
       *
       * @param {Array} configurations The extension negotiation offers/reponse
       * @return {Array} The offers/response with normalized parameters
       * @private
       */
      normalizeParams(configurations) {
        configurations.forEach((params) => {
          Object.keys(params).forEach((key) => {
            let value = params[key];
            if (value.length > 1) {
              throw new Error(`Parameter "${key}" must have only a single value`);
            }
            value = value[0];
            if (key === "client_max_window_bits") {
              if (value !== true) {
                const num = +value;
                if (!Number.isInteger(num) || num < 8 || num > 15) {
                  throw new TypeError(
                    `Invalid value for parameter "${key}": ${value}`
                  );
                }
                value = num;
              } else if (!this._isServer) {
                throw new TypeError(
                  `Invalid value for parameter "${key}": ${value}`
                );
              }
            } else if (key === "server_max_window_bits") {
              const num = +value;
              if (!Number.isInteger(num) || num < 8 || num > 15) {
                throw new TypeError(
                  `Invalid value for parameter "${key}": ${value}`
                );
              }
              value = num;
            } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
              if (value !== true) {
                throw new TypeError(
                  `Invalid value for parameter "${key}": ${value}`
                );
              }
            } else {
              throw new Error(`Unknown parameter "${key}"`);
            }
            params[key] = value;
          });
        });
        return configurations;
      }
      /**
       * Decompress data. Concurrency limited.
       *
       * @param {Buffer} data Compressed data
       * @param {Boolean} fin Specifies whether or not this is the last fragment
       * @param {Function} callback Callback
       * @public
       */
      decompress(data, fin, callback) {
        zlibLimiter.add((done) => {
          this._decompress(data, fin, (err, result) => {
            done();
            callback(err, result);
          });
        });
      }
      /**
       * Compress data. Concurrency limited.
       *
       * @param {(Buffer|String)} data Data to compress
       * @param {Boolean} fin Specifies whether or not this is the last fragment
       * @param {Function} callback Callback
       * @public
       */
      compress(data, fin, callback) {
        zlibLimiter.add((done) => {
          this._compress(data, fin, (err, result) => {
            done();
            callback(err, result);
          });
        });
      }
      /**
       * Decompress data.
       *
       * @param {Buffer} data Compressed data
       * @param {Boolean} fin Specifies whether or not this is the last fragment
       * @param {Function} callback Callback
       * @private
       */
      _decompress(data, fin, callback) {
        const endpoint = this._isServer ? "client" : "server";
        if (!this._inflate) {
          const key = `${endpoint}_max_window_bits`;
          const windowBits = typeof this.params[key] !== "number" ? zlib2.Z_DEFAULT_WINDOWBITS : this.params[key];
          this._inflate = zlib2.createInflateRaw({
            ...this._options.zlibInflateOptions,
            windowBits
          });
          this._inflate[kPerMessageDeflate] = this;
          this._inflate[kTotalLength] = 0;
          this._inflate[kBuffers] = [];
          this._inflate.on("error", inflateOnError);
          this._inflate.on("data", inflateOnData);
        }
        this._inflate[kCallback] = callback;
        this._inflate.write(data);
        if (fin) this._inflate.write(TRAILER);
        this._inflate.flush(() => {
          const err = this._inflate[kError];
          if (err) {
            this._inflate.close();
            this._inflate = null;
            callback(err);
            return;
          }
          const data2 = bufferUtil.concat(
            this._inflate[kBuffers],
            this._inflate[kTotalLength]
          );
          if (this._inflate._readableState.endEmitted) {
            this._inflate.close();
            this._inflate = null;
          } else {
            this._inflate[kTotalLength] = 0;
            this._inflate[kBuffers] = [];
            if (fin && this.params[`${endpoint}_no_context_takeover`]) {
              this._inflate.reset();
            }
          }
          callback(null, data2);
        });
      }
      /**
       * Compress data.
       *
       * @param {(Buffer|String)} data Data to compress
       * @param {Boolean} fin Specifies whether or not this is the last fragment
       * @param {Function} callback Callback
       * @private
       */
      _compress(data, fin, callback) {
        const endpoint = this._isServer ? "server" : "client";
        if (!this._deflate) {
          const key = `${endpoint}_max_window_bits`;
          const windowBits = typeof this.params[key] !== "number" ? zlib2.Z_DEFAULT_WINDOWBITS : this.params[key];
          this._deflate = zlib2.createDeflateRaw({
            ...this._options.zlibDeflateOptions,
            windowBits
          });
          this._deflate[kTotalLength] = 0;
          this._deflate[kBuffers] = [];
          this._deflate.on("data", deflateOnData);
        }
        this._deflate[kCallback] = callback;
        this._deflate.write(data);
        this._deflate.flush(zlib2.Z_SYNC_FLUSH, () => {
          if (!this._deflate) {
            return;
          }
          let data2 = bufferUtil.concat(
            this._deflate[kBuffers],
            this._deflate[kTotalLength]
          );
          if (fin) {
            data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
          }
          this._deflate[kCallback] = null;
          this._deflate[kTotalLength] = 0;
          this._deflate[kBuffers] = [];
          if (fin && this.params[`${endpoint}_no_context_takeover`]) {
            this._deflate.reset();
          }
          callback(null, data2);
        });
      }
    };
    module2.exports = PerMessageDeflate;
    function deflateOnData(chunk) {
      this[kBuffers].push(chunk);
      this[kTotalLength] += chunk.length;
    }
    __name(deflateOnData, "deflateOnData");
    function inflateOnData(chunk) {
      this[kTotalLength] += chunk.length;
      if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
        this[kBuffers].push(chunk);
        return;
      }
      this[kError] = new RangeError("Max payload size exceeded");
      this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
      this[kError][kStatusCode] = 1009;
      this.removeListener("data", inflateOnData);
      this.reset();
    }
    __name(inflateOnData, "inflateOnData");
    function inflateOnError(err) {
      this[kPerMessageDeflate]._inflate = null;
      if (this[kError]) {
        this[kCallback](this[kError]);
        return;
      }
      err[kStatusCode] = 1007;
      this[kCallback](err);
    }
    __name(inflateOnError, "inflateOnError");
  }
});

// node_modules/ws/lib/validation.js
var require_validation = __commonJS({
  "node_modules/ws/lib/validation.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { isUtf8 } = __require("buffer");
    var { hasBlob } = require_constants2();
    var tokenChars = [
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 0 - 15
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 16 - 31
      0,
      1,
      0,
      1,
      1,
      1,
      1,
      1,
      0,
      0,
      1,
      1,
      0,
      1,
      1,
      0,
      // 32 - 47
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      0,
      0,
      0,
      0,
      0,
      0,
      // 48 - 63
      0,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      // 64 - 79
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      0,
      0,
      0,
      1,
      1,
      // 80 - 95
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      // 96 - 111
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      0,
      1,
      0,
      1,
      0
      // 112 - 127
    ];
    function isValidStatusCode(code2) {
      return code2 >= 1e3 && code2 <= 1014 && code2 !== 1004 && code2 !== 1005 && code2 !== 1006 || code2 >= 3e3 && code2 <= 4999;
    }
    __name(isValidStatusCode, "isValidStatusCode");
    function _isValidUTF8(buf) {
      const len = buf.length;
      let i = 0;
      while (i < len) {
        if ((buf[i] & 128) === 0) {
          i++;
        } else if ((buf[i] & 224) === 192) {
          if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
            return false;
          }
          i += 2;
        } else if ((buf[i] & 240) === 224) {
          if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
          buf[i] === 237 && (buf[i + 1] & 224) === 160) {
            return false;
          }
          i += 3;
        } else if ((buf[i] & 248) === 240) {
          if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
          buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
            return false;
          }
          i += 4;
        } else {
          return false;
        }
      }
      return true;
    }
    __name(_isValidUTF8, "_isValidUTF8");
    function isBlob(value) {
      return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
    }
    __name(isBlob, "isBlob");
    module2.exports = {
      isBlob,
      isValidStatusCode,
      isValidUTF8: _isValidUTF8,
      tokenChars
    };
    if (isUtf8) {
      module2.exports.isValidUTF8 = function(buf) {
        return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
      };
    } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
      try {
        const isValidUTF8 = __require("utf-8-validate");
        module2.exports.isValidUTF8 = function(buf) {
          return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
        };
      } catch (e2) {
      }
    }
  }
});

// node_modules/ws/lib/receiver.js
var require_receiver = __commonJS({
  "node_modules/ws/lib/receiver.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Writable: Writable3 } = __require("stream");
    var PerMessageDeflate = require_permessage_deflate();
    var {
      BINARY_TYPES,
      EMPTY_BUFFER,
      kStatusCode,
      kWebSocket
    } = require_constants2();
    var { concat: concat2, toArrayBuffer, unmask } = require_buffer_util();
    var { isValidStatusCode, isValidUTF8 } = require_validation();
    var FastBuffer = Buffer[Symbol.species];
    var GET_INFO = 0;
    var GET_PAYLOAD_LENGTH_16 = 1;
    var GET_PAYLOAD_LENGTH_64 = 2;
    var GET_MASK = 3;
    var GET_DATA = 4;
    var INFLATING = 5;
    var DEFER_EVENT = 6;
    var Receiver2 = class extends Writable3 {
      static {
        __name(this, "Receiver");
      }
      /**
       * Creates a Receiver instance.
       *
       * @param {Object} [options] Options object
       * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
       *     any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
       *     multiple times in the same tick
       * @param {String} [options.binaryType=nodebuffer] The type for binary data
       * @param {Object} [options.extensions] An object containing the negotiated
       *     extensions
       * @param {Boolean} [options.isServer=false] Specifies whether to operate in
       *     client or server mode
       * @param {Number} [options.maxPayload=0] The maximum allowed message length
       * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
       *     not to skip UTF-8 validation for text and close messages
       */
      constructor(options2 = {}) {
        super();
        this._allowSynchronousEvents = options2.allowSynchronousEvents !== void 0 ? options2.allowSynchronousEvents : true;
        this._binaryType = options2.binaryType || BINARY_TYPES[0];
        this._extensions = options2.extensions || {};
        this._isServer = !!options2.isServer;
        this._maxPayload = options2.maxPayload | 0;
        this._skipUTF8Validation = !!options2.skipUTF8Validation;
        this[kWebSocket] = void 0;
        this._bufferedBytes = 0;
        this._buffers = [];
        this._compressed = false;
        this._payloadLength = 0;
        this._mask = void 0;
        this._fragmented = 0;
        this._masked = false;
        this._fin = false;
        this._opcode = 0;
        this._totalPayloadLength = 0;
        this._messageLength = 0;
        this._fragments = [];
        this._errored = false;
        this._loop = false;
        this._state = GET_INFO;
      }
      /**
       * Implements `Writable.prototype._write()`.
       *
       * @param {Buffer} chunk The chunk of data to write
       * @param {String} encoding The character encoding of `chunk`
       * @param {Function} cb Callback
       * @private
       */
      _write(chunk, encoding, cb) {
        if (this._opcode === 8 && this._state == GET_INFO) return cb();
        this._bufferedBytes += chunk.length;
        this._buffers.push(chunk);
        this.startLoop(cb);
      }
      /**
       * Consumes `n` bytes from the buffered data.
       *
       * @param {Number} n The number of bytes to consume
       * @return {Buffer} The consumed bytes
       * @private
       */
      consume(n2) {
        this._bufferedBytes -= n2;
        if (n2 === this._buffers[0].length) return this._buffers.shift();
        if (n2 < this._buffers[0].length) {
          const buf = this._buffers[0];
          this._buffers[0] = new FastBuffer(
            buf.buffer,
            buf.byteOffset + n2,
            buf.length - n2
          );
          return new FastBuffer(buf.buffer, buf.byteOffset, n2);
        }
        const dst = Buffer.allocUnsafe(n2);
        do {
          const buf = this._buffers[0];
          const offset = dst.length - n2;
          if (n2 >= buf.length) {
            dst.set(this._buffers.shift(), offset);
          } else {
            dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n2), offset);
            this._buffers[0] = new FastBuffer(
              buf.buffer,
              buf.byteOffset + n2,
              buf.length - n2
            );
          }
          n2 -= buf.length;
        } while (n2 > 0);
        return dst;
      }
      /**
       * Starts the parsing loop.
       *
       * @param {Function} cb Callback
       * @private
       */
      startLoop(cb) {
        this._loop = true;
        do {
          switch (this._state) {
            case GET_INFO:
              this.getInfo(cb);
              break;
            case GET_PAYLOAD_LENGTH_16:
              this.getPayloadLength16(cb);
              break;
            case GET_PAYLOAD_LENGTH_64:
              this.getPayloadLength64(cb);
              break;
            case GET_MASK:
              this.getMask();
              break;
            case GET_DATA:
              this.getData(cb);
              break;
            case INFLATING:
            case DEFER_EVENT:
              this._loop = false;
              return;
          }
        } while (this._loop);
        if (!this._errored) cb();
      }
      /**
       * Reads the first two bytes of a frame.
       *
       * @param {Function} cb Callback
       * @private
       */
      getInfo(cb) {
        if (this._bufferedBytes < 2) {
          this._loop = false;
          return;
        }
        const buf = this.consume(2);
        if ((buf[0] & 48) !== 0) {
          const error = this.createError(
            RangeError,
            "RSV2 and RSV3 must be clear",
            true,
            1002,
            "WS_ERR_UNEXPECTED_RSV_2_3"
          );
          cb(error);
          return;
        }
        const compressed = (buf[0] & 64) === 64;
        if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
          const error = this.createError(
            RangeError,
            "RSV1 must be clear",
            true,
            1002,
            "WS_ERR_UNEXPECTED_RSV_1"
          );
          cb(error);
          return;
        }
        this._fin = (buf[0] & 128) === 128;
        this._opcode = buf[0] & 15;
        this._payloadLength = buf[1] & 127;
        if (this._opcode === 0) {
          if (compressed) {
            const error = this.createError(
              RangeError,
              "RSV1 must be clear",
              true,
              1002,
              "WS_ERR_UNEXPECTED_RSV_1"
            );
            cb(error);
            return;
          }
          if (!this._fragmented) {
            const error = this.createError(
              RangeError,
              "invalid opcode 0",
              true,
              1002,
              "WS_ERR_INVALID_OPCODE"
            );
            cb(error);
            return;
          }
          this._opcode = this._fragmented;
        } else if (this._opcode === 1 || this._opcode === 2) {
          if (this._fragmented) {
            const error = this.createError(
              RangeError,
              `invalid opcode ${this._opcode}`,
              true,
              1002,
              "WS_ERR_INVALID_OPCODE"
            );
            cb(error);
            return;
          }
          this._compressed = compressed;
        } else if (this._opcode > 7 && this._opcode < 11) {
          if (!this._fin) {
            const error = this.createError(
              RangeError,
              "FIN must be set",
              true,
              1002,
              "WS_ERR_EXPECTED_FIN"
            );
            cb(error);
            return;
          }
          if (compressed) {
            const error = this.createError(
              RangeError,
              "RSV1 must be clear",
              true,
              1002,
              "WS_ERR_UNEXPECTED_RSV_1"
            );
            cb(error);
            return;
          }
          if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
            const error = this.createError(
              RangeError,
              `invalid payload length ${this._payloadLength}`,
              true,
              1002,
              "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
            );
            cb(error);
            return;
          }
        } else {
          const error = this.createError(
            RangeError,
            `invalid opcode ${this._opcode}`,
            true,
            1002,
            "WS_ERR_INVALID_OPCODE"
          );
          cb(error);
          return;
        }
        if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
        this._masked = (buf[1] & 128) === 128;
        if (this._isServer) {
          if (!this._masked) {
            const error = this.createError(
              RangeError,
              "MASK must be set",
              true,
              1002,
              "WS_ERR_EXPECTED_MASK"
            );
            cb(error);
            return;
          }
        } else if (this._masked) {
          const error = this.createError(
            RangeError,
            "MASK must be clear",
            true,
            1002,
            "WS_ERR_UNEXPECTED_MASK"
          );
          cb(error);
          return;
        }
        if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
        else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
        else this.haveLength(cb);
      }
      /**
       * Gets extended payload length (7+16).
       *
       * @param {Function} cb Callback
       * @private
       */
      getPayloadLength16(cb) {
        if (this._bufferedBytes < 2) {
          this._loop = false;
          return;
        }
        this._payloadLength = this.consume(2).readUInt16BE(0);
        this.haveLength(cb);
      }
      /**
       * Gets extended payload length (7+64).
       *
       * @param {Function} cb Callback
       * @private
       */
      getPayloadLength64(cb) {
        if (this._bufferedBytes < 8) {
          this._loop = false;
          return;
        }
        const buf = this.consume(8);
        const num = buf.readUInt32BE(0);
        if (num > Math.pow(2, 53 - 32) - 1) {
          const error = this.createError(
            RangeError,
            "Unsupported WebSocket frame: payload length > 2^53 - 1",
            false,
            1009,
            "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
          );
          cb(error);
          return;
        }
        this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
        this.haveLength(cb);
      }
      /**
       * Payload length has been read.
       *
       * @param {Function} cb Callback
       * @private
       */
      haveLength(cb) {
        if (this._payloadLength && this._opcode < 8) {
          this._totalPayloadLength += this._payloadLength;
          if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
            const error = this.createError(
              RangeError,
              "Max payload size exceeded",
              false,
              1009,
              "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
            );
            cb(error);
            return;
          }
        }
        if (this._masked) this._state = GET_MASK;
        else this._state = GET_DATA;
      }
      /**
       * Reads mask bytes.
       *
       * @private
       */
      getMask() {
        if (this._bufferedBytes < 4) {
          this._loop = false;
          return;
        }
        this._mask = this.consume(4);
        this._state = GET_DATA;
      }
      /**
       * Reads data bytes.
       *
       * @param {Function} cb Callback
       * @private
       */
      getData(cb) {
        let data = EMPTY_BUFFER;
        if (this._payloadLength) {
          if (this._bufferedBytes < this._payloadLength) {
            this._loop = false;
            return;
          }
          data = this.consume(this._payloadLength);
          if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
            unmask(data, this._mask);
          }
        }
        if (this._opcode > 7) {
          this.controlMessage(data, cb);
          return;
        }
        if (this._compressed) {
          this._state = INFLATING;
          this.decompress(data, cb);
          return;
        }
        if (data.length) {
          this._messageLength = this._totalPayloadLength;
          this._fragments.push(data);
        }
        this.dataMessage(cb);
      }
      /**
       * Decompresses data.
       *
       * @param {Buffer} data Compressed data
       * @param {Function} cb Callback
       * @private
       */
      decompress(data, cb) {
        const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
        perMessageDeflate.decompress(data, this._fin, (err, buf) => {
          if (err) return cb(err);
          if (buf.length) {
            this._messageLength += buf.length;
            if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
              const error = this.createError(
                RangeError,
                "Max payload size exceeded",
                false,
                1009,
                "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
              );
              cb(error);
              return;
            }
            this._fragments.push(buf);
          }
          this.dataMessage(cb);
          if (this._state === GET_INFO) this.startLoop(cb);
        });
      }
      /**
       * Handles a data message.
       *
       * @param {Function} cb Callback
       * @private
       */
      dataMessage(cb) {
        if (!this._fin) {
          this._state = GET_INFO;
          return;
        }
        const messageLength = this._messageLength;
        const fragments = this._fragments;
        this._totalPayloadLength = 0;
        this._messageLength = 0;
        this._fragmented = 0;
        this._fragments = [];
        if (this._opcode === 2) {
          let data;
          if (this._binaryType === "nodebuffer") {
            data = concat2(fragments, messageLength);
          } else if (this._binaryType === "arraybuffer") {
            data = toArrayBuffer(concat2(fragments, messageLength));
          } else if (this._binaryType === "blob") {
            data = new Blob(fragments);
          } else {
            data = fragments;
          }
          if (this._allowSynchronousEvents) {
            this.emit("message", data, true);
            this._state = GET_INFO;
          } else {
            this._state = DEFER_EVENT;
            setImmediate(() => {
              this.emit("message", data, true);
              this._state = GET_INFO;
              this.startLoop(cb);
            });
          }
        } else {
          const buf = concat2(fragments, messageLength);
          if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
            const error = this.createError(
              Error,
              "invalid UTF-8 sequence",
              true,
              1007,
              "WS_ERR_INVALID_UTF8"
            );
            cb(error);
            return;
          }
          if (this._state === INFLATING || this._allowSynchronousEvents) {
            this.emit("message", buf, false);
            this._state = GET_INFO;
          } else {
            this._state = DEFER_EVENT;
            setImmediate(() => {
              this.emit("message", buf, false);
              this._state = GET_INFO;
              this.startLoop(cb);
            });
          }
        }
      }
      /**
       * Handles a control message.
       *
       * @param {Buffer} data Data to handle
       * @return {(Error|RangeError|undefined)} A possible error
       * @private
       */
      controlMessage(data, cb) {
        if (this._opcode === 8) {
          if (data.length === 0) {
            this._loop = false;
            this.emit("conclude", 1005, EMPTY_BUFFER);
            this.end();
          } else {
            const code2 = data.readUInt16BE(0);
            if (!isValidStatusCode(code2)) {
              const error = this.createError(
                RangeError,
                `invalid status code ${code2}`,
                true,
                1002,
                "WS_ERR_INVALID_CLOSE_CODE"
              );
              cb(error);
              return;
            }
            const buf = new FastBuffer(
              data.buffer,
              data.byteOffset + 2,
              data.length - 2
            );
            if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
              const error = this.createError(
                Error,
                "invalid UTF-8 sequence",
                true,
                1007,
                "WS_ERR_INVALID_UTF8"
              );
              cb(error);
              return;
            }
            this._loop = false;
            this.emit("conclude", code2, buf);
            this.end();
          }
          this._state = GET_INFO;
          return;
        }
        if (this._allowSynchronousEvents) {
          this.emit(this._opcode === 9 ? "ping" : "pong", data);
          this._state = GET_INFO;
        } else {
          this._state = DEFER_EVENT;
          setImmediate(() => {
            this.emit(this._opcode === 9 ? "ping" : "pong", data);
            this._state = GET_INFO;
            this.startLoop(cb);
          });
        }
      }
      /**
       * Builds an error object.
       *
       * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
       * @param {String} message The error message
       * @param {Boolean} prefix Specifies whether or not to add a default prefix to
       *     `message`
       * @param {Number} statusCode The status code
       * @param {String} errorCode The exposed error code
       * @return {(Error|RangeError)} The error
       * @private
       */
      createError(ErrorCtor, message, prefix, statusCode, errorCode) {
        this._loop = false;
        this._errored = true;
        const err = new ErrorCtor(
          prefix ? `Invalid WebSocket frame: ${message}` : message
        );
        Error.captureStackTrace(err, this.createError);
        err.code = errorCode;
        err[kStatusCode] = statusCode;
        return err;
      }
    };
    module2.exports = Receiver2;
  }
});

// node_modules/ws/lib/sender.js
var require_sender = __commonJS({
  "node_modules/ws/lib/sender.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Duplex } = __require("stream");
    var { randomFillSync } = __require("crypto");
    var PerMessageDeflate = require_permessage_deflate();
    var { EMPTY_BUFFER, kWebSocket, NOOP: NOOP3 } = require_constants2();
    var { isBlob, isValidStatusCode } = require_validation();
    var { mask: applyMask, toBuffer } = require_buffer_util();
    var kByteLength = Symbol("kByteLength");
    var maskBuffer = Buffer.alloc(4);
    var RANDOM_POOL_SIZE = 8 * 1024;
    var randomPool;
    var randomPoolPointer = RANDOM_POOL_SIZE;
    var DEFAULT = 0;
    var DEFLATING = 1;
    var GET_BLOB_DATA = 2;
    var Sender2 = class _Sender {
      static {
        __name(this, "Sender");
      }
      /**
       * Creates a Sender instance.
       *
       * @param {Duplex} socket The connection socket
       * @param {Object} [extensions] An object containing the negotiated extensions
       * @param {Function} [generateMask] The function used to generate the masking
       *     key
       */
      constructor(socket, extensions, generateMask) {
        this._extensions = extensions || {};
        if (generateMask) {
          this._generateMask = generateMask;
          this._maskBuffer = Buffer.alloc(4);
        }
        this._socket = socket;
        this._firstFragment = true;
        this._compress = false;
        this._bufferedBytes = 0;
        this._queue = [];
        this._state = DEFAULT;
        this.onerror = NOOP3;
        this[kWebSocket] = void 0;
      }
      /**
       * Frames a piece of data according to the HyBi WebSocket protocol.
       *
       * @param {(Buffer|String)} data The data to frame
       * @param {Object} options Options object
       * @param {Boolean} [options.fin=false] Specifies whether or not to set the
       *     FIN bit
       * @param {Function} [options.generateMask] The function used to generate the
       *     masking key
       * @param {Boolean} [options.mask=false] Specifies whether or not to mask
       *     `data`
       * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
       *     key
       * @param {Number} options.opcode The opcode
       * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
       *     modified
       * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
       *     RSV1 bit
       * @return {(Buffer|String)[]} The framed data
       * @public
       */
      static frame(data, options2) {
        let mask;
        let merge3 = false;
        let offset = 2;
        let skipMasking = false;
        if (options2.mask) {
          mask = options2.maskBuffer || maskBuffer;
          if (options2.generateMask) {
            options2.generateMask(mask);
          } else {
            if (randomPoolPointer === RANDOM_POOL_SIZE) {
              if (randomPool === void 0) {
                randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
              }
              randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
              randomPoolPointer = 0;
            }
            mask[0] = randomPool[randomPoolPointer++];
            mask[1] = randomPool[randomPoolPointer++];
            mask[2] = randomPool[randomPoolPointer++];
            mask[3] = randomPool[randomPoolPointer++];
          }
          skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
          offset = 6;
        }
        let dataLength;
        if (typeof data === "string") {
          if ((!options2.mask || skipMasking) && options2[kByteLength] !== void 0) {
            dataLength = options2[kByteLength];
          } else {
            data = Buffer.from(data);
            dataLength = data.length;
          }
        } else {
          dataLength = data.length;
          merge3 = options2.mask && options2.readOnly && !skipMasking;
        }
        let payloadLength = dataLength;
        if (dataLength >= 65536) {
          offset += 8;
          payloadLength = 127;
        } else if (dataLength > 125) {
          offset += 2;
          payloadLength = 126;
        }
        const target = Buffer.allocUnsafe(merge3 ? dataLength + offset : offset);
        target[0] = options2.fin ? options2.opcode | 128 : options2.opcode;
        if (options2.rsv1) target[0] |= 64;
        target[1] = payloadLength;
        if (payloadLength === 126) {
          target.writeUInt16BE(dataLength, 2);
        } else if (payloadLength === 127) {
          target[2] = target[3] = 0;
          target.writeUIntBE(dataLength, 4, 6);
        }
        if (!options2.mask) return [target, data];
        target[1] |= 128;
        target[offset - 4] = mask[0];
        target[offset - 3] = mask[1];
        target[offset - 2] = mask[2];
        target[offset - 1] = mask[3];
        if (skipMasking) return [target, data];
        if (merge3) {
          applyMask(data, mask, target, offset, dataLength);
          return [target];
        }
        applyMask(data, mask, data, 0, dataLength);
        return [target, data];
      }
      /**
       * Sends a close message to the other peer.
       *
       * @param {Number} [code] The status code component of the body
       * @param {(String|Buffer)} [data] The message component of the body
       * @param {Boolean} [mask=false] Specifies whether or not to mask the message
       * @param {Function} [cb] Callback
       * @public
       */
      close(code2, data, mask, cb) {
        let buf;
        if (code2 === void 0) {
          buf = EMPTY_BUFFER;
        } else if (typeof code2 !== "number" || !isValidStatusCode(code2)) {
          throw new TypeError("First argument must be a valid error code number");
        } else if (data === void 0 || !data.length) {
          buf = Buffer.allocUnsafe(2);
          buf.writeUInt16BE(code2, 0);
        } else {
          const length = Buffer.byteLength(data);
          if (length > 123) {
            throw new RangeError("The message must not be greater than 123 bytes");
          }
          buf = Buffer.allocUnsafe(2 + length);
          buf.writeUInt16BE(code2, 0);
          if (typeof data === "string") {
            buf.write(data, 2);
          } else {
            buf.set(data, 2);
          }
        }
        const options2 = {
          [kByteLength]: buf.length,
          fin: true,
          generateMask: this._generateMask,
          mask,
          maskBuffer: this._maskBuffer,
          opcode: 8,
          readOnly: false,
          rsv1: false
        };
        if (this._state !== DEFAULT) {
          this.enqueue([this.dispatch, buf, false, options2, cb]);
        } else {
          this.sendFrame(_Sender.frame(buf, options2), cb);
        }
      }
      /**
       * Sends a ping message to the other peer.
       *
       * @param {*} data The message to send
       * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
       * @param {Function} [cb] Callback
       * @public
       */
      ping(data, mask, cb) {
        let byteLength;
        let readOnly;
        if (typeof data === "string") {
          byteLength = Buffer.byteLength(data);
          readOnly = false;
        } else if (isBlob(data)) {
          byteLength = data.size;
          readOnly = false;
        } else {
          data = toBuffer(data);
          byteLength = data.length;
          readOnly = toBuffer.readOnly;
        }
        if (byteLength > 125) {
          throw new RangeError("The data size must not be greater than 125 bytes");
        }
        const options2 = {
          [kByteLength]: byteLength,
          fin: true,
          generateMask: this._generateMask,
          mask,
          maskBuffer: this._maskBuffer,
          opcode: 9,
          readOnly,
          rsv1: false
        };
        if (isBlob(data)) {
          if (this._state !== DEFAULT) {
            this.enqueue([this.getBlobData, data, false, options2, cb]);
          } else {
            this.getBlobData(data, false, options2, cb);
          }
        } else if (this._state !== DEFAULT) {
          this.enqueue([this.dispatch, data, false, options2, cb]);
        } else {
          this.sendFrame(_Sender.frame(data, options2), cb);
        }
      }
      /**
       * Sends a pong message to the other peer.
       *
       * @param {*} data The message to send
       * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
       * @param {Function} [cb] Callback
       * @public
       */
      pong(data, mask, cb) {
        let byteLength;
        let readOnly;
        if (typeof data === "string") {
          byteLength = Buffer.byteLength(data);
          readOnly = false;
        } else if (isBlob(data)) {
          byteLength = data.size;
          readOnly = false;
        } else {
          data = toBuffer(data);
          byteLength = data.length;
          readOnly = toBuffer.readOnly;
        }
        if (byteLength > 125) {
          throw new RangeError("The data size must not be greater than 125 bytes");
        }
        const options2 = {
          [kByteLength]: byteLength,
          fin: true,
          generateMask: this._generateMask,
          mask,
          maskBuffer: this._maskBuffer,
          opcode: 10,
          readOnly,
          rsv1: false
        };
        if (isBlob(data)) {
          if (this._state !== DEFAULT) {
            this.enqueue([this.getBlobData, data, false, options2, cb]);
          } else {
            this.getBlobData(data, false, options2, cb);
          }
        } else if (this._state !== DEFAULT) {
          this.enqueue([this.dispatch, data, false, options2, cb]);
        } else {
          this.sendFrame(_Sender.frame(data, options2), cb);
        }
      }
      /**
       * Sends a data message to the other peer.
       *
       * @param {*} data The message to send
       * @param {Object} options Options object
       * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
       *     or text
       * @param {Boolean} [options.compress=false] Specifies whether or not to
       *     compress `data`
       * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
       *     last one
       * @param {Boolean} [options.mask=false] Specifies whether or not to mask
       *     `data`
       * @param {Function} [cb] Callback
       * @public
       */
      send(data, options2, cb) {
        const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
        let opcode = options2.binary ? 2 : 1;
        let rsv1 = options2.compress;
        let byteLength;
        let readOnly;
        if (typeof data === "string") {
          byteLength = Buffer.byteLength(data);
          readOnly = false;
        } else if (isBlob(data)) {
          byteLength = data.size;
          readOnly = false;
        } else {
          data = toBuffer(data);
          byteLength = data.length;
          readOnly = toBuffer.readOnly;
        }
        if (this._firstFragment) {
          this._firstFragment = false;
          if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
            rsv1 = byteLength >= perMessageDeflate._threshold;
          }
          this._compress = rsv1;
        } else {
          rsv1 = false;
          opcode = 0;
        }
        if (options2.fin) this._firstFragment = true;
        const opts = {
          [kByteLength]: byteLength,
          fin: options2.fin,
          generateMask: this._generateMask,
          mask: options2.mask,
          maskBuffer: this._maskBuffer,
          opcode,
          readOnly,
          rsv1
        };
        if (isBlob(data)) {
          if (this._state !== DEFAULT) {
            this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
          } else {
            this.getBlobData(data, this._compress, opts, cb);
          }
        } else if (this._state !== DEFAULT) {
          this.enqueue([this.dispatch, data, this._compress, opts, cb]);
        } else {
          this.dispatch(data, this._compress, opts, cb);
        }
      }
      /**
       * Gets the contents of a blob as binary data.
       *
       * @param {Blob} blob The blob
       * @param {Boolean} [compress=false] Specifies whether or not to compress
       *     the data
       * @param {Object} options Options object
       * @param {Boolean} [options.fin=false] Specifies whether or not to set the
       *     FIN bit
       * @param {Function} [options.generateMask] The function used to generate the
       *     masking key
       * @param {Boolean} [options.mask=false] Specifies whether or not to mask
       *     `data`
       * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
       *     key
       * @param {Number} options.opcode The opcode
       * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
       *     modified
       * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
       *     RSV1 bit
       * @param {Function} [cb] Callback
       * @private
       */
      getBlobData(blob, compress, options2, cb) {
        this._bufferedBytes += options2[kByteLength];
        this._state = GET_BLOB_DATA;
        blob.arrayBuffer().then((arrayBuffer) => {
          if (this._socket.destroyed) {
            const err = new Error(
              "The socket was closed while the blob was being read"
            );
            process.nextTick(callCallbacks, this, err, cb);
            return;
          }
          this._bufferedBytes -= options2[kByteLength];
          const data = toBuffer(arrayBuffer);
          if (!compress) {
            this._state = DEFAULT;
            this.sendFrame(_Sender.frame(data, options2), cb);
            this.dequeue();
          } else {
            this.dispatch(data, compress, options2, cb);
          }
        }).catch((err) => {
          process.nextTick(onError2, this, err, cb);
        });
      }
      /**
       * Dispatches a message.
       *
       * @param {(Buffer|String)} data The message to send
       * @param {Boolean} [compress=false] Specifies whether or not to compress
       *     `data`
       * @param {Object} options Options object
       * @param {Boolean} [options.fin=false] Specifies whether or not to set the
       *     FIN bit
       * @param {Function} [options.generateMask] The function used to generate the
       *     masking key
       * @param {Boolean} [options.mask=false] Specifies whether or not to mask
       *     `data`
       * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
       *     key
       * @param {Number} options.opcode The opcode
       * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
       *     modified
       * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
       *     RSV1 bit
       * @param {Function} [cb] Callback
       * @private
       */
      dispatch(data, compress, options2, cb) {
        if (!compress) {
          this.sendFrame(_Sender.frame(data, options2), cb);
          return;
        }
        const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
        this._bufferedBytes += options2[kByteLength];
        this._state = DEFLATING;
        perMessageDeflate.compress(data, options2.fin, (_, buf) => {
          if (this._socket.destroyed) {
            const err = new Error(
              "The socket was closed while data was being compressed"
            );
            callCallbacks(this, err, cb);
            return;
          }
          this._bufferedBytes -= options2[kByteLength];
          this._state = DEFAULT;
          options2.readOnly = false;
          this.sendFrame(_Sender.frame(buf, options2), cb);
          this.dequeue();
        });
      }
      /**
       * Executes queued send operations.
       *
       * @private
       */
      dequeue() {
        while (this._state === DEFAULT && this._queue.length) {
          const params = this._queue.shift();
          this._bufferedBytes -= params[3][kByteLength];
          Reflect.apply(params[0], this, params.slice(1));
        }
      }
      /**
       * Enqueues a send operation.
       *
       * @param {Array} params Send operation parameters.
       * @private
       */
      enqueue(params) {
        this._bufferedBytes += params[3][kByteLength];
        this._queue.push(params);
      }
      /**
       * Sends a frame.
       *
       * @param {(Buffer | String)[]} list The frame to send
       * @param {Function} [cb] Callback
       * @private
       */
      sendFrame(list3, cb) {
        if (list3.length === 2) {
          this._socket.cork();
          this._socket.write(list3[0]);
          this._socket.write(list3[1], cb);
          this._socket.uncork();
        } else {
          this._socket.write(list3[0], cb);
        }
      }
    };
    module2.exports = Sender2;
    function callCallbacks(sender, err, cb) {
      if (typeof cb === "function") cb(err);
      for (let i = 0; i < sender._queue.length; i++) {
        const params = sender._queue[i];
        const callback = params[params.length - 1];
        if (typeof callback === "function") callback(err);
      }
    }
    __name(callCallbacks, "callCallbacks");
    function onError2(sender, err, cb) {
      callCallbacks(sender, err, cb);
      sender.onerror(err);
    }
    __name(onError2, "onError");
  }
});

// node_modules/ws/lib/event-target.js
var require_event_target = __commonJS({
  "node_modules/ws/lib/event-target.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { kForOnEventAttribute, kListener } = require_constants2();
    var kCode = Symbol("kCode");
    var kData = Symbol("kData");
    var kError = Symbol("kError");
    var kMessage = Symbol("kMessage");
    var kReason = Symbol("kReason");
    var kTarget = Symbol("kTarget");
    var kType = Symbol("kType");
    var kWasClean = Symbol("kWasClean");
    var Event2 = class {
      static {
        __name(this, "Event");
      }
      /**
       * Create a new `Event`.
       *
       * @param {String} type The name of the event
       * @throws {TypeError} If the `type` argument is not specified
       */
      constructor(type) {
        this[kTarget] = null;
        this[kType] = type;
      }
      /**
       * @type {*}
       */
      get target() {
        return this[kTarget];
      }
      /**
       * @type {String}
       */
      get type() {
        return this[kType];
      }
    };
    Object.defineProperty(Event2.prototype, "target", { enumerable: true });
    Object.defineProperty(Event2.prototype, "type", { enumerable: true });
    var CloseEvent = class extends Event2 {
      static {
        __name(this, "CloseEvent");
      }
      /**
       * Create a new `CloseEvent`.
       *
       * @param {String} type The name of the event
       * @param {Object} [options] A dictionary object that allows for setting
       *     attributes via object members of the same name
       * @param {Number} [options.code=0] The status code explaining why the
       *     connection was closed
       * @param {String} [options.reason=''] A human-readable string explaining why
       *     the connection was closed
       * @param {Boolean} [options.wasClean=false] Indicates whether or not the
       *     connection was cleanly closed
       */
      constructor(type, options2 = {}) {
        super(type);
        this[kCode] = options2.code === void 0 ? 0 : options2.code;
        this[kReason] = options2.reason === void 0 ? "" : options2.reason;
        this[kWasClean] = options2.wasClean === void 0 ? false : options2.wasClean;
      }
      /**
       * @type {Number}
       */
      get code() {
        return this[kCode];
      }
      /**
       * @type {String}
       */
      get reason() {
        return this[kReason];
      }
      /**
       * @type {Boolean}
       */
      get wasClean() {
        return this[kWasClean];
      }
    };
    Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
    Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
    Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
    var ErrorEvent2 = class extends Event2 {
      static {
        __name(this, "ErrorEvent");
      }
      /**
       * Create a new `ErrorEvent`.
       *
       * @param {String} type The name of the event
       * @param {Object} [options] A dictionary object that allows for setting
       *     attributes via object members of the same name
       * @param {*} [options.error=null] The error that generated this event
       * @param {String} [options.message=''] The error message
       */
      constructor(type, options2 = {}) {
        super(type);
        this[kError] = options2.error === void 0 ? null : options2.error;
        this[kMessage] = options2.message === void 0 ? "" : options2.message;
      }
      /**
       * @type {*}
       */
      get error() {
        return this[kError];
      }
      /**
       * @type {String}
       */
      get message() {
        return this[kMessage];
      }
    };
    Object.defineProperty(ErrorEvent2.prototype, "error", { enumerable: true });
    Object.defineProperty(ErrorEvent2.prototype, "message", { enumerable: true });
    var MessageEvent2 = class extends Event2 {
      static {
        __name(this, "MessageEvent");
      }
      /**
       * Create a new `MessageEvent`.
       *
       * @param {String} type The name of the event
       * @param {Object} [options] A dictionary object that allows for setting
       *     attributes via object members of the same name
       * @param {*} [options.data=null] The message content
       */
      constructor(type, options2 = {}) {
        super(type);
        this[kData] = options2.data === void 0 ? null : options2.data;
      }
      /**
       * @type {*}
       */
      get data() {
        return this[kData];
      }
    };
    Object.defineProperty(MessageEvent2.prototype, "data", { enumerable: true });
    var EventTarget2 = {
      /**
       * Register an event listener.
       *
       * @param {String} type A string representing the event type to listen for
       * @param {(Function|Object)} handler The listener to add
       * @param {Object} [options] An options object specifies characteristics about
       *     the event listener
       * @param {Boolean} [options.once=false] A `Boolean` indicating that the
       *     listener should be invoked at most once after being added. If `true`,
       *     the listener would be automatically removed when invoked.
       * @public
       */
      addEventListener(type, handler, options2 = {}) {
        for (const listener of this.listeners(type)) {
          if (!options2[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
            return;
          }
        }
        let wrapper;
        if (type === "message") {
          wrapper = /* @__PURE__ */ __name(function onMessage(data, isBinary2) {
            const event = new MessageEvent2("message", {
              data: isBinary2 ? data : data.toString()
            });
            event[kTarget] = this;
            callListener(handler, this, event);
          }, "onMessage");
        } else if (type === "close") {
          wrapper = /* @__PURE__ */ __name(function onClose(code2, message) {
            const event = new CloseEvent("close", {
              code: code2,
              reason: message.toString(),
              wasClean: this._closeFrameReceived && this._closeFrameSent
            });
            event[kTarget] = this;
            callListener(handler, this, event);
          }, "onClose");
        } else if (type === "error") {
          wrapper = /* @__PURE__ */ __name(function onError2(error) {
            const event = new ErrorEvent2("error", {
              error,
              message: error.message
            });
            event[kTarget] = this;
            callListener(handler, this, event);
          }, "onError");
        } else if (type === "open") {
          wrapper = /* @__PURE__ */ __name(function onOpen() {
            const event = new Event2("open");
            event[kTarget] = this;
            callListener(handler, this, event);
          }, "onOpen");
        } else {
          return;
        }
        wrapper[kForOnEventAttribute] = !!options2[kForOnEventAttribute];
        wrapper[kListener] = handler;
        if (options2.once) {
          this.once(type, wrapper);
        } else {
          this.on(type, wrapper);
        }
      },
      /**
       * Remove an event listener.
       *
       * @param {String} type A string representing the event type to remove
       * @param {(Function|Object)} handler The listener to remove
       * @public
       */
      removeEventListener(type, handler) {
        for (const listener of this.listeners(type)) {
          if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
            this.removeListener(type, listener);
            break;
          }
        }
      }
    };
    module2.exports = {
      CloseEvent,
      ErrorEvent: ErrorEvent2,
      Event: Event2,
      EventTarget: EventTarget2,
      MessageEvent: MessageEvent2
    };
    function callListener(listener, thisArg, event) {
      if (typeof listener === "object" && listener.handleEvent) {
        listener.handleEvent.call(listener, event);
      } else {
        listener.call(thisArg, event);
      }
    }
    __name(callListener, "callListener");
  }
});

// node_modules/ws/lib/extension.js
var require_extension = __commonJS({
  "node_modules/ws/lib/extension.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { tokenChars } = require_validation();
    function push2(dest, name3, elem) {
      if (dest[name3] === void 0) dest[name3] = [elem];
      else dest[name3].push(elem);
    }
    __name(push2, "push");
    function parse12(header) {
      const offers = /* @__PURE__ */ Object.create(null);
      let params = /* @__PURE__ */ Object.create(null);
      let mustUnescape = false;
      let isEscaping = false;
      let inQuotes = false;
      let extensionName;
      let paramName;
      let start = -1;
      let code2 = -1;
      let end = -1;
      let i = 0;
      for (; i < header.length; i++) {
        code2 = header.charCodeAt(i);
        if (extensionName === void 0) {
          if (end === -1 && tokenChars[code2] === 1) {
            if (start === -1) start = i;
          } else if (i !== 0 && (code2 === 32 || code2 === 9)) {
            if (end === -1 && start !== -1) end = i;
          } else if (code2 === 59 || code2 === 44) {
            if (start === -1) {
              throw new SyntaxError(`Unexpected character at index ${i}`);
            }
            if (end === -1) end = i;
            const name3 = header.slice(start, end);
            if (code2 === 44) {
              push2(offers, name3, params);
              params = /* @__PURE__ */ Object.create(null);
            } else {
              extensionName = name3;
            }
            start = end = -1;
          } else {
            throw new SyntaxError(`Unexpected character at index ${i}`);
          }
        } else if (paramName === void 0) {
          if (end === -1 && tokenChars[code2] === 1) {
            if (start === -1) start = i;
          } else if (code2 === 32 || code2 === 9) {
            if (end === -1 && start !== -1) end = i;
          } else if (code2 === 59 || code2 === 44) {
            if (start === -1) {
              throw new SyntaxError(`Unexpected character at index ${i}`);
            }
            if (end === -1) end = i;
            push2(params, header.slice(start, end), true);
            if (code2 === 44) {
              push2(offers, extensionName, params);
              params = /* @__PURE__ */ Object.create(null);
              extensionName = void 0;
            }
            start = end = -1;
          } else if (code2 === 61 && start !== -1 && end === -1) {
            paramName = header.slice(start, i);
            start = end = -1;
          } else {
            throw new SyntaxError(`Unexpected character at index ${i}`);
          }
        } else {
          if (isEscaping) {
            if (tokenChars[code2] !== 1) {
              throw new SyntaxError(`Unexpected character at index ${i}`);
            }
            if (start === -1) start = i;
            else if (!mustUnescape) mustUnescape = true;
            isEscaping = false;
          } else if (inQuotes) {
            if (tokenChars[code2] === 1) {
              if (start === -1) start = i;
            } else if (code2 === 34 && start !== -1) {
              inQuotes = false;
              end = i;
            } else if (code2 === 92) {
              isEscaping = true;
            } else {
              throw new SyntaxError(`Unexpected character at index ${i}`);
            }
          } else if (code2 === 34 && header.charCodeAt(i - 1) === 61) {
            inQuotes = true;
          } else if (end === -1 && tokenChars[code2] === 1) {
            if (start === -1) start = i;
          } else if (start !== -1 && (code2 === 32 || code2 === 9)) {
            if (end === -1) end = i;
          } else if (code2 === 59 || code2 === 44) {
            if (start === -1) {
              throw new SyntaxError(`Unexpected character at index ${i}`);
            }
            if (end === -1) end = i;
            let value = header.slice(start, end);
            if (mustUnescape) {
              value = value.replace(/\\/g, "");
              mustUnescape = false;
            }
            push2(params, paramName, value);
            if (code2 === 44) {
              push2(offers, extensionName, params);
              params = /* @__PURE__ */ Object.create(null);
              extensionName = void 0;
            }
            paramName = void 0;
            start = end = -1;
          } else {
            throw new SyntaxError(`Unexpected character at index ${i}`);
          }
        }
      }
      if (start === -1 || inQuotes || code2 === 32 || code2 === 9) {
        throw new SyntaxError("Unexpected end of input");
      }
      if (end === -1) end = i;
      const token2 = header.slice(start, end);
      if (extensionName === void 0) {
        push2(offers, token2, params);
      } else {
        if (paramName === void 0) {
          push2(params, token2, true);
        } else if (mustUnescape) {
          push2(params, paramName, token2.replace(/\\/g, ""));
        } else {
          push2(params, paramName, token2);
        }
        push2(offers, extensionName, params);
      }
      return offers;
    }
    __name(parse12, "parse");
    function format4(extensions) {
      return Object.keys(extensions).map((extension) => {
        let configurations = extensions[extension];
        if (!Array.isArray(configurations)) configurations = [configurations];
        return configurations.map((params) => {
          return [extension].concat(
            Object.keys(params).map((k) => {
              let values = params[k];
              if (!Array.isArray(values)) values = [values];
              return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
            })
          ).join("; ");
        }).join(", ");
      }).join(", ");
    }
    __name(format4, "format");
    module2.exports = { format: format4, parse: parse12 };
  }
});

// node_modules/ws/lib/websocket.js
var require_websocket = __commonJS({
  "node_modules/ws/lib/websocket.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var EventEmitter10 = __require("events");
    var https4 = __require("https");
    var http4 = __require("http");
    var net2 = __require("net");
    var tls = __require("tls");
    var { randomBytes: randomBytes6, createHash: createHash6 } = __require("crypto");
    var { Duplex, Readable: Readable4 } = __require("stream");
    var { URL: URL6 } = __require("url");
    var PerMessageDeflate = require_permessage_deflate();
    var Receiver2 = require_receiver();
    var Sender2 = require_sender();
    var { isBlob } = require_validation();
    var {
      BINARY_TYPES,
      EMPTY_BUFFER,
      GUID,
      kForOnEventAttribute,
      kListener,
      kStatusCode,
      kWebSocket,
      NOOP: NOOP3
    } = require_constants2();
    var {
      EventTarget: { addEventListener, removeEventListener }
    } = require_event_target();
    var { format: format4, parse: parse12 } = require_extension();
    var { toBuffer } = require_buffer_util();
    var closeTimeout = 30 * 1e3;
    var kAborted = Symbol("kAborted");
    var protocolVersions = [8, 13];
    var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
    var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
    var WebSocket2 = class _WebSocket extends EventEmitter10 {
      static {
        __name(this, "WebSocket");
      }
      /**
       * Create a new `WebSocket`.
       *
       * @param {(String|URL)} address The URL to which to connect
       * @param {(String|String[])} [protocols] The subprotocols
       * @param {Object} [options] Connection options
       */
      constructor(address, protocols, options2) {
        super();
        this._binaryType = BINARY_TYPES[0];
        this._closeCode = 1006;
        this._closeFrameReceived = false;
        this._closeFrameSent = false;
        this._closeMessage = EMPTY_BUFFER;
        this._closeTimer = null;
        this._errorEmitted = false;
        this._extensions = {};
        this._paused = false;
        this._protocol = "";
        this._readyState = _WebSocket.CONNECTING;
        this._receiver = null;
        this._sender = null;
        this._socket = null;
        if (address !== null) {
          this._bufferedAmount = 0;
          this._isServer = false;
          this._redirects = 0;
          if (protocols === void 0) {
            protocols = [];
          } else if (!Array.isArray(protocols)) {
            if (typeof protocols === "object" && protocols !== null) {
              options2 = protocols;
              protocols = [];
            } else {
              protocols = [protocols];
            }
          }
          initAsClient(this, address, protocols, options2);
        } else {
          this._autoPong = options2.autoPong;
          this._isServer = true;
        }
      }
      /**
       * For historical reasons, the custom "nodebuffer" type is used by the default
       * instead of "blob".
       *
       * @type {String}
       */
      get binaryType() {
        return this._binaryType;
      }
      set binaryType(type) {
        if (!BINARY_TYPES.includes(type)) return;
        this._binaryType = type;
        if (this._receiver) this._receiver._binaryType = type;
      }
      /**
       * @type {Number}
       */
      get bufferedAmount() {
        if (!this._socket) return this._bufferedAmount;
        return this._socket._writableState.length + this._sender._bufferedBytes;
      }
      /**
       * @type {String}
       */
      get extensions() {
        return Object.keys(this._extensions).join();
      }
      /**
       * @type {Boolean}
       */
      get isPaused() {
        return this._paused;
      }
      /**
       * @type {Function}
       */
      /* istanbul ignore next */
      get onclose() {
        return null;
      }
      /**
       * @type {Function}
       */
      /* istanbul ignore next */
      get onerror() {
        return null;
      }
      /**
       * @type {Function}
       */
      /* istanbul ignore next */
      get onopen() {
        return null;
      }
      /**
       * @type {Function}
       */
      /* istanbul ignore next */
      get onmessage() {
        return null;
      }
      /**
       * @type {String}
       */
      get protocol() {
        return this._protocol;
      }
      /**
       * @type {Number}
       */
      get readyState() {
        return this._readyState;
      }
      /**
       * @type {String}
       */
      get url() {
        return this._url;
      }
      /**
       * Set up the socket and the internal resources.
       *
       * @param {Duplex} socket The network socket between the server and client
       * @param {Buffer} head The first packet of the upgraded stream
       * @param {Object} options Options object
       * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
       *     any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
       *     multiple times in the same tick
       * @param {Function} [options.generateMask] The function used to generate the
       *     masking key
       * @param {Number} [options.maxPayload=0] The maximum allowed message size
       * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
       *     not to skip UTF-8 validation for text and close messages
       * @private
       */
      setSocket(socket, head, options2) {
        const receiver = new Receiver2({
          allowSynchronousEvents: options2.allowSynchronousEvents,
          binaryType: this.binaryType,
          extensions: this._extensions,
          isServer: this._isServer,
          maxPayload: options2.maxPayload,
          skipUTF8Validation: options2.skipUTF8Validation
        });
        const sender = new Sender2(socket, this._extensions, options2.generateMask);
        this._receiver = receiver;
        this._sender = sender;
        this._socket = socket;
        receiver[kWebSocket] = this;
        sender[kWebSocket] = this;
        socket[kWebSocket] = this;
        receiver.on("conclude", receiverOnConclude);
        receiver.on("drain", receiverOnDrain);
        receiver.on("error", receiverOnError);
        receiver.on("message", receiverOnMessage);
        receiver.on("ping", receiverOnPing);
        receiver.on("pong", receiverOnPong);
        sender.onerror = senderOnError;
        if (socket.setTimeout) socket.setTimeout(0);
        if (socket.setNoDelay) socket.setNoDelay();
        if (head.length > 0) socket.unshift(head);
        socket.on("close", socketOnClose);
        socket.on("data", socketOnData);
        socket.on("end", socketOnEnd);
        socket.on("error", socketOnError);
        this._readyState = _WebSocket.OPEN;
        this.emit("open");
      }
      /**
       * Emit the `'close'` event.
       *
       * @private
       */
      emitClose() {
        if (!this._socket) {
          this._readyState = _WebSocket.CLOSED;
          this.emit("close", this._closeCode, this._closeMessage);
          return;
        }
        if (this._extensions[PerMessageDeflate.extensionName]) {
          this._extensions[PerMessageDeflate.extensionName].cleanup();
        }
        this._receiver.removeAllListeners();
        this._readyState = _WebSocket.CLOSED;
        this.emit("close", this._closeCode, this._closeMessage);
      }
      /**
       * Start a closing handshake.
       *
       *          +----------+   +-----------+   +----------+
       *     - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
       *    |     +----------+   +-----------+   +----------+     |
       *          +----------+   +-----------+         |
       * CLOSING  |ws.close()|<--|close frame|<--+-----+       CLOSING
       *          +----------+   +-----------+   |
       *    |           |                        |   +---+        |
       *                +------------------------+-->|fin| - - - -
       *    |         +---+                      |   +---+
       *     - - - - -|fin|<---------------------+
       *              +---+
       *
       * @param {Number} [code] Status code explaining why the connection is closing
       * @param {(String|Buffer)} [data] The reason why the connection is
       *     closing
       * @public
       */
      close(code2, data) {
        if (this.readyState === _WebSocket.CLOSED) return;
        if (this.readyState === _WebSocket.CONNECTING) {
          const msg = "WebSocket was closed before the connection was established";
          abortHandshake(this, this._req, msg);
          return;
        }
        if (this.readyState === _WebSocket.CLOSING) {
          if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
            this._socket.end();
          }
          return;
        }
        this._readyState = _WebSocket.CLOSING;
        this._sender.close(code2, data, !this._isServer, (err) => {
          if (err) return;
          this._closeFrameSent = true;
          if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
            this._socket.end();
          }
        });
        setCloseTimer(this);
      }
      /**
       * Pause the socket.
       *
       * @public
       */
      pause() {
        if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
          return;
        }
        this._paused = true;
        this._socket.pause();
      }
      /**
       * Send a ping.
       *
       * @param {*} [data] The data to send
       * @param {Boolean} [mask] Indicates whether or not to mask `data`
       * @param {Function} [cb] Callback which is executed when the ping is sent
       * @public
       */
      ping(data, mask, cb) {
        if (this.readyState === _WebSocket.CONNECTING) {
          throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
        }
        if (typeof data === "function") {
          cb = data;
          data = mask = void 0;
        } else if (typeof mask === "function") {
          cb = mask;
          mask = void 0;
        }
        if (typeof data === "number") data = data.toString();
        if (this.readyState !== _WebSocket.OPEN) {
          sendAfterClose(this, data, cb);
          return;
        }
        if (mask === void 0) mask = !this._isServer;
        this._sender.ping(data || EMPTY_BUFFER, mask, cb);
      }
      /**
       * Send a pong.
       *
       * @param {*} [data] The data to send
       * @param {Boolean} [mask] Indicates whether or not to mask `data`
       * @param {Function} [cb] Callback which is executed when the pong is sent
       * @public
       */
      pong(data, mask, cb) {
        if (this.readyState === _WebSocket.CONNECTING) {
          throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
        }
        if (typeof data === "function") {
          cb = data;
          data = mask = void 0;
        } else if (typeof mask === "function") {
          cb = mask;
          mask = void 0;
        }
        if (typeof data === "number") data = data.toString();
        if (this.readyState !== _WebSocket.OPEN) {
          sendAfterClose(this, data, cb);
          return;
        }
        if (mask === void 0) mask = !this._isServer;
        this._sender.pong(data || EMPTY_BUFFER, mask, cb);
      }
      /**
       * Resume the socket.
       *
       * @public
       */
      resume() {
        if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
          return;
        }
        this._paused = false;
        if (!this._receiver._writableState.needDrain) this._socket.resume();
      }
      /**
       * Send a data message.
       *
       * @param {*} data The message to send
       * @param {Object} [options] Options object
       * @param {Boolean} [options.binary] Specifies whether `data` is binary or
       *     text
       * @param {Boolean} [options.compress] Specifies whether or not to compress
       *     `data`
       * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
       *     last one
       * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
       * @param {Function} [cb] Callback which is executed when data is written out
       * @public
       */
      send(data, options2, cb) {
        if (this.readyState === _WebSocket.CONNECTING) {
          throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
        }
        if (typeof options2 === "function") {
          cb = options2;
          options2 = {};
        }
        if (typeof data === "number") data = data.toString();
        if (this.readyState !== _WebSocket.OPEN) {
          sendAfterClose(this, data, cb);
          return;
        }
        const opts = {
          binary: typeof data !== "string",
          mask: !this._isServer,
          compress: true,
          fin: true,
          ...options2
        };
        if (!this._extensions[PerMessageDeflate.extensionName]) {
          opts.compress = false;
        }
        this._sender.send(data || EMPTY_BUFFER, opts, cb);
      }
      /**
       * Forcibly close the connection.
       *
       * @public
       */
      terminate() {
        if (this.readyState === _WebSocket.CLOSED) return;
        if (this.readyState === _WebSocket.CONNECTING) {
          const msg = "WebSocket was closed before the connection was established";
          abortHandshake(this, this._req, msg);
          return;
        }
        if (this._socket) {
          this._readyState = _WebSocket.CLOSING;
          this._socket.destroy();
        }
      }
    };
    Object.defineProperty(WebSocket2, "CONNECTING", {
      enumerable: true,
      value: readyStates.indexOf("CONNECTING")
    });
    Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
      enumerable: true,
      value: readyStates.indexOf("CONNECTING")
    });
    Object.defineProperty(WebSocket2, "OPEN", {
      enumerable: true,
      value: readyStates.indexOf("OPEN")
    });
    Object.defineProperty(WebSocket2.prototype, "OPEN", {
      enumerable: true,
      value: readyStates.indexOf("OPEN")
    });
    Object.defineProperty(WebSocket2, "CLOSING", {
      enumerable: true,
      value: readyStates.indexOf("CLOSING")
    });
    Object.defineProperty(WebSocket2.prototype, "CLOSING", {
      enumerable: true,
      value: readyStates.indexOf("CLOSING")
    });
    Object.defineProperty(WebSocket2, "CLOSED", {
      enumerable: true,
      value: readyStates.indexOf("CLOSED")
    });
    Object.defineProperty(WebSocket2.prototype, "CLOSED", {
      enumerable: true,
      value: readyStates.indexOf("CLOSED")
    });
    [
      "binaryType",
      "bufferedAmount",
      "extensions",
      "isPaused",
      "protocol",
      "readyState",
      "url"
    ].forEach((property) => {
      Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
    });
    ["open", "error", "close", "message"].forEach((method) => {
      Object.defineProperty(WebSocket2.prototype, `on${method}`, {
        enumerable: true,
        get() {
          for (const listener of this.listeners(method)) {
            if (listener[kForOnEventAttribute]) return listener[kListener];
          }
          return null;
        },
        set(handler) {
          for (const listener of this.listeners(method)) {
            if (listener[kForOnEventAttribute]) {
              this.removeListener(method, listener);
              break;
            }
          }
          if (typeof handler !== "function") return;
          this.addEventListener(method, handler, {
            [kForOnEventAttribute]: true
          });
        }
      });
    });
    WebSocket2.prototype.addEventListener = addEventListener;
    WebSocket2.prototype.removeEventListener = removeEventListener;
    module2.exports = WebSocket2;
    function initAsClient(websocket, address, protocols, options2) {
      const opts = {
        allowSynchronousEvents: true,
        autoPong: true,
        protocolVersion: protocolVersions[1],
        maxPayload: 100 * 1024 * 1024,
        skipUTF8Validation: false,
        perMessageDeflate: true,
        followRedirects: false,
        maxRedirects: 10,
        ...options2,
        socketPath: void 0,
        hostname: void 0,
        protocol: void 0,
        timeout: void 0,
        method: "GET",
        host: void 0,
        path: void 0,
        port: void 0
      };
      websocket._autoPong = opts.autoPong;
      if (!protocolVersions.includes(opts.protocolVersion)) {
        throw new RangeError(
          `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
        );
      }
      let parsedUrl;
      if (address instanceof URL6) {
        parsedUrl = address;
      } else {
        try {
          parsedUrl = new URL6(address);
        } catch (e2) {
          throw new SyntaxError(`Invalid URL: ${address}`);
        }
      }
      if (parsedUrl.protocol === "http:") {
        parsedUrl.protocol = "ws:";
      } else if (parsedUrl.protocol === "https:") {
        parsedUrl.protocol = "wss:";
      }
      websocket._url = parsedUrl.href;
      const isSecure = parsedUrl.protocol === "wss:";
      const isIpcUrl = parsedUrl.protocol === "ws+unix:";
      let invalidUrlMessage;
      if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
        invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
      } else if (isIpcUrl && !parsedUrl.pathname) {
        invalidUrlMessage = "The URL's pathname is empty";
      } else if (parsedUrl.hash) {
        invalidUrlMessage = "The URL contains a fragment identifier";
      }
      if (invalidUrlMessage) {
        const err = new SyntaxError(invalidUrlMessage);
        if (websocket._redirects === 0) {
          throw err;
        } else {
          emitErrorAndClose(websocket, err);
          return;
        }
      }
      const defaultPort = isSecure ? 443 : 80;
      const key = randomBytes6(16).toString("base64");
      const request4 = isSecure ? https4.request : http4.request;
      const protocolSet = /* @__PURE__ */ new Set();
      let perMessageDeflate;
      opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
      opts.defaultPort = opts.defaultPort || defaultPort;
      opts.port = parsedUrl.port || defaultPort;
      opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
      opts.headers = {
        ...opts.headers,
        "Sec-WebSocket-Version": opts.protocolVersion,
        "Sec-WebSocket-Key": key,
        Connection: "Upgrade",
        Upgrade: "websocket"
      };
      opts.path = parsedUrl.pathname + parsedUrl.search;
      opts.timeout = opts.handshakeTimeout;
      if (opts.perMessageDeflate) {
        perMessageDeflate = new PerMessageDeflate(
          opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
          false,
          opts.maxPayload
        );
        opts.headers["Sec-WebSocket-Extensions"] = format4({
          [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
        });
      }
      if (protocols.length) {
        for (const protocol of protocols) {
          if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
            throw new SyntaxError(
              "An invalid or duplicated subprotocol was specified"
            );
          }
          protocolSet.add(protocol);
        }
        opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
      }
      if (opts.origin) {
        if (opts.protocolVersion < 13) {
          opts.headers["Sec-WebSocket-Origin"] = opts.origin;
        } else {
          opts.headers.Origin = opts.origin;
        }
      }
      if (parsedUrl.username || parsedUrl.password) {
        opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
      }
      if (isIpcUrl) {
        const parts = opts.path.split(":");
        opts.socketPath = parts[0];
        opts.path = parts[1];
      }
      let req;
      if (opts.followRedirects) {
        if (websocket._redirects === 0) {
          websocket._originalIpc = isIpcUrl;
          websocket._originalSecure = isSecure;
          websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
          const headers = options2 && options2.headers;
          options2 = { ...options2, headers: {} };
          if (headers) {
            for (const [key2, value] of Object.entries(headers)) {
              options2.headers[key2.toLowerCase()] = value;
            }
          }
        } else if (websocket.listenerCount("redirect") === 0) {
          const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
          if (!isSameHost || websocket._originalSecure && !isSecure) {
            delete opts.headers.authorization;
            delete opts.headers.cookie;
            if (!isSameHost) delete opts.headers.host;
            opts.auth = void 0;
          }
        }
        if (opts.auth && !options2.headers.authorization) {
          options2.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
        }
        req = websocket._req = request4(opts);
        if (websocket._redirects) {
          websocket.emit("redirect", websocket.url, req);
        }
      } else {
        req = websocket._req = request4(opts);
      }
      if (opts.timeout) {
        req.on("timeout", () => {
          abortHandshake(websocket, req, "Opening handshake has timed out");
        });
      }
      req.on("error", (err) => {
        if (req === null || req[kAborted]) return;
        req = websocket._req = null;
        emitErrorAndClose(websocket, err);
      });
      req.on("response", (res) => {
        const location = res.headers.location;
        const statusCode = res.statusCode;
        if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
          if (++websocket._redirects > opts.maxRedirects) {
            abortHandshake(websocket, req, "Maximum redirects exceeded");
            return;
          }
          req.abort();
          let addr;
          try {
            addr = new URL6(location, address);
          } catch (e2) {
            const err = new SyntaxError(`Invalid URL: ${location}`);
            emitErrorAndClose(websocket, err);
            return;
          }
          initAsClient(websocket, addr, protocols, options2);
        } else if (!websocket.emit("unexpected-response", req, res)) {
          abortHandshake(
            websocket,
            req,
            `Unexpected server response: ${res.statusCode}`
          );
        }
      });
      req.on("upgrade", (res, socket, head) => {
        websocket.emit("upgrade", res);
        if (websocket.readyState !== WebSocket2.CONNECTING) return;
        req = websocket._req = null;
        const upgrade = res.headers.upgrade;
        if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
          abortHandshake(websocket, socket, "Invalid Upgrade header");
          return;
        }
        const digest = createHash6("sha1").update(key + GUID).digest("base64");
        if (res.headers["sec-websocket-accept"] !== digest) {
          abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
          return;
        }
        const serverProt = res.headers["sec-websocket-protocol"];
        let protError;
        if (serverProt !== void 0) {
          if (!protocolSet.size) {
            protError = "Server sent a subprotocol but none was requested";
          } else if (!protocolSet.has(serverProt)) {
            protError = "Server sent an invalid subprotocol";
          }
        } else if (protocolSet.size) {
          protError = "Server sent no subprotocol";
        }
        if (protError) {
          abortHandshake(websocket, socket, protError);
          return;
        }
        if (serverProt) websocket._protocol = serverProt;
        const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
        if (secWebSocketExtensions !== void 0) {
          if (!perMessageDeflate) {
            const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
            abortHandshake(websocket, socket, message);
            return;
          }
          let extensions;
          try {
            extensions = parse12(secWebSocketExtensions);
          } catch (err) {
            const message = "Invalid Sec-WebSocket-Extensions header";
            abortHandshake(websocket, socket, message);
            return;
          }
          const extensionNames = Object.keys(extensions);
          if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
            const message = "Server indicated an extension that was not requested";
            abortHandshake(websocket, socket, message);
            return;
          }
          try {
            perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
          } catch (err) {
            const message = "Invalid Sec-WebSocket-Extensions header";
            abortHandshake(websocket, socket, message);
            return;
          }
          websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
        }
        websocket.setSocket(socket, head, {
          allowSynchronousEvents: opts.allowSynchronousEvents,
          generateMask: opts.generateMask,
          maxPayload: opts.maxPayload,
          skipUTF8Validation: opts.skipUTF8Validation
        });
      });
      if (opts.finishRequest) {
        opts.finishRequest(req, websocket);
      } else {
        req.end();
      }
    }
    __name(initAsClient, "initAsClient");
    function emitErrorAndClose(websocket, err) {
      websocket._readyState = WebSocket2.CLOSING;
      websocket._errorEmitted = true;
      websocket.emit("error", err);
      websocket.emitClose();
    }
    __name(emitErrorAndClose, "emitErrorAndClose");
    function netConnect(options2) {
      options2.path = options2.socketPath;
      return net2.connect(options2);
    }
    __name(netConnect, "netConnect");
    function tlsConnect(options2) {
      options2.path = void 0;
      if (!options2.servername && options2.servername !== "") {
        options2.servername = net2.isIP(options2.host) ? "" : options2.host;
      }
      return tls.connect(options2);
    }
    __name(tlsConnect, "tlsConnect");
    function abortHandshake(websocket, stream2, message) {
      websocket._readyState = WebSocket2.CLOSING;
      const err = new Error(message);
      Error.captureStackTrace(err, abortHandshake);
      if (stream2.setHeader) {
        stream2[kAborted] = true;
        stream2.abort();
        if (stream2.socket && !stream2.socket.destroyed) {
          stream2.socket.destroy();
        }
        process.nextTick(emitErrorAndClose, websocket, err);
      } else {
        stream2.destroy(err);
        stream2.once("error", websocket.emit.bind(websocket, "error"));
        stream2.once("close", websocket.emitClose.bind(websocket));
      }
    }
    __name(abortHandshake, "abortHandshake");
    function sendAfterClose(websocket, data, cb) {
      if (data) {
        const length = isBlob(data) ? data.size : toBuffer(data).length;
        if (websocket._socket) websocket._sender._bufferedBytes += length;
        else websocket._bufferedAmount += length;
      }
      if (cb) {
        const err = new Error(
          `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
        );
        process.nextTick(cb, err);
      }
    }
    __name(sendAfterClose, "sendAfterClose");
    function receiverOnConclude(code2, reason) {
      const websocket = this[kWebSocket];
      websocket._closeFrameReceived = true;
      websocket._closeMessage = reason;
      websocket._closeCode = code2;
      if (websocket._socket[kWebSocket] === void 0) return;
      websocket._socket.removeListener("data", socketOnData);
      process.nextTick(resume, websocket._socket);
      if (code2 === 1005) websocket.close();
      else websocket.close(code2, reason);
    }
    __name(receiverOnConclude, "receiverOnConclude");
    function receiverOnDrain() {
      const websocket = this[kWebSocket];
      if (!websocket.isPaused) websocket._socket.resume();
    }
    __name(receiverOnDrain, "receiverOnDrain");
    function receiverOnError(err) {
      const websocket = this[kWebSocket];
      if (websocket._socket[kWebSocket] !== void 0) {
        websocket._socket.removeListener("data", socketOnData);
        process.nextTick(resume, websocket._socket);
        websocket.close(err[kStatusCode]);
      }
      if (!websocket._errorEmitted) {
        websocket._errorEmitted = true;
        websocket.emit("error", err);
      }
    }
    __name(receiverOnError, "receiverOnError");
    function receiverOnFinish() {
      this[kWebSocket].emitClose();
    }
    __name(receiverOnFinish, "receiverOnFinish");
    function receiverOnMessage(data, isBinary2) {
      this[kWebSocket].emit("message", data, isBinary2);
    }
    __name(receiverOnMessage, "receiverOnMessage");
    function receiverOnPing(data) {
      const websocket = this[kWebSocket];
      if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP3);
      websocket.emit("ping", data);
    }
    __name(receiverOnPing, "receiverOnPing");
    function receiverOnPong(data) {
      this[kWebSocket].emit("pong", data);
    }
    __name(receiverOnPong, "receiverOnPong");
    function resume(stream2) {
      stream2.resume();
    }
    __name(resume, "resume");
    function senderOnError(err) {
      const websocket = this[kWebSocket];
      if (websocket.readyState === WebSocket2.CLOSED) return;
      if (websocket.readyState === WebSocket2.OPEN) {
        websocket._readyState = WebSocket2.CLOSING;
        setCloseTimer(websocket);
      }
      this._socket.end();
      if (!websocket._errorEmitted) {
        websocket._errorEmitted = true;
        websocket.emit("error", err);
      }
    }
    __name(senderOnError, "senderOnError");
    function setCloseTimer(websocket) {
      websocket._closeTimer = setTimeout(
        websocket._socket.destroy.bind(websocket._socket),
        closeTimeout
      );
    }
    __name(setCloseTimer, "setCloseTimer");
    function socketOnClose() {
      const websocket = this[kWebSocket];
      this.removeListener("close", socketOnClose);
      this.removeListener("data", socketOnData);
      this.removeListener("end", socketOnEnd);
      websocket._readyState = WebSocket2.CLOSING;
      let chunk;
      if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) {
        websocket._receiver.write(chunk);
      }
      websocket._receiver.end();
      this[kWebSocket] = void 0;
      clearTimeout(websocket._closeTimer);
      if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
        websocket.emitClose();
      } else {
        websocket._receiver.on("error", receiverOnFinish);
        websocket._receiver.on("finish", receiverOnFinish);
      }
    }
    __name(socketOnClose, "socketOnClose");
    function socketOnData(chunk) {
      if (!this[kWebSocket]._receiver.write(chunk)) {
        this.pause();
      }
    }
    __name(socketOnData, "socketOnData");
    function socketOnEnd() {
      const websocket = this[kWebSocket];
      websocket._readyState = WebSocket2.CLOSING;
      websocket._receiver.end();
      this.end();
    }
    __name(socketOnEnd, "socketOnEnd");
    function socketOnError() {
      const websocket = this[kWebSocket];
      this.removeListener("error", socketOnError);
      this.on("error", NOOP3);
      if (websocket) {
        websocket._readyState = WebSocket2.CLOSING;
        this.destroy();
      }
    }
    __name(socketOnError, "socketOnError");
  }
});

// node_modules/ws/lib/stream.js
var require_stream = __commonJS({
  "node_modules/ws/lib/stream.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var WebSocket2 = require_websocket();
    var { Duplex } = __require("stream");
    function emitClose(stream2) {
      stream2.emit("close");
    }
    __name(emitClose, "emitClose");
    function duplexOnEnd() {
      if (!this.destroyed && this._writableState.finished) {
        this.destroy();
      }
    }
    __name(duplexOnEnd, "duplexOnEnd");
    function duplexOnError(err) {
      this.removeListener("error", duplexOnError);
      this.destroy();
      if (this.listenerCount("error") === 0) {
        this.emit("error", err);
      }
    }
    __name(duplexOnError, "duplexOnError");
    function createWebSocketStream2(ws2, options2) {
      let terminateOnDestroy = true;
      const duplex = new Duplex({
        ...options2,
        autoDestroy: false,
        emitClose: false,
        objectMode: false,
        writableObjectMode: false
      });
      ws2.on("message", /* @__PURE__ */ __name(function message(msg, isBinary2) {
        const data = !isBinary2 && duplex._readableState.objectMode ? msg.toString() : msg;
        if (!duplex.push(data)) ws2.pause();
      }, "message"));
      ws2.once("error", /* @__PURE__ */ __name(function error(err) {
        if (duplex.destroyed) return;
        terminateOnDestroy = false;
        duplex.destroy(err);
      }, "error"));
      ws2.once("close", /* @__PURE__ */ __name(function close() {
        if (duplex.destroyed) return;
        duplex.push(null);
      }, "close"));
      duplex._destroy = function(err, callback) {
        if (ws2.readyState === ws2.CLOSED) {
          callback(err);
          process.nextTick(emitClose, duplex);
          return;
        }
        let called = false;
        ws2.once("error", /* @__PURE__ */ __name(function error(err2) {
          called = true;
          callback(err2);
        }, "error"));
        ws2.once("close", /* @__PURE__ */ __name(function close() {
          if (!called) callback(err);
          process.nextTick(emitClose, duplex);
        }, "close"));
        if (terminateOnDestroy) ws2.terminate();
      };
      duplex._final = function(callback) {
        if (ws2.readyState === ws2.CONNECTING) {
          ws2.once("open", /* @__PURE__ */ __name(function open3() {
            duplex._final(callback);
          }, "open"));
          return;
        }
        if (ws2._socket === null) return;
        if (ws2._socket._writableState.finished) {
          callback();
          if (duplex._readableState.endEmitted) duplex.destroy();
        } else {
          ws2._socket.once("finish", /* @__PURE__ */ __name(function finish() {
            callback();
          }, "finish"));
          ws2.close();
        }
      };
      duplex._read = function() {
        if (ws2.isPaused) ws2.resume();
      };
      duplex._write = function(chunk, encoding, callback) {
        if (ws2.readyState === ws2.CONNECTING) {
          ws2.once("open", /* @__PURE__ */ __name(function open3() {
            duplex._write(chunk, encoding, callback);
          }, "open"));
          return;
        }
        ws2.send(chunk, callback);
      };
      duplex.on("end", duplexOnEnd);
      duplex.on("error", duplexOnError);
      return duplex;
    }
    __name(createWebSocketStream2, "createWebSocketStream");
    module2.exports = createWebSocketStream2;
  }
});

// node_modules/ws/lib/subprotocol.js
var require_subprotocol = __commonJS({
  "node_modules/ws/lib/subprotocol.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { tokenChars } = require_validation();
    function parse12(header) {
      const protocols = /* @__PURE__ */ new Set();
      let start = -1;
      let end = -1;
      let i = 0;
      for (i; i < header.length; i++) {
        const code2 = header.charCodeAt(i);
        if (end === -1 && tokenChars[code2] === 1) {
          if (start === -1) start = i;
        } else if (i !== 0 && (code2 === 32 || code2 === 9)) {
          if (end === -1 && start !== -1) end = i;
        } else if (code2 === 44) {
          if (start === -1) {
            throw new SyntaxError(`Unexpected character at index ${i}`);
          }
          if (end === -1) end = i;
          const protocol2 = header.slice(start, end);
          if (protocols.has(protocol2)) {
            throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
          }
          protocols.add(protocol2);
          start = end = -1;
        } else {
          throw new SyntaxError(`Unexpected character at index ${i}`);
        }
      }
      if (start === -1 || end !== -1) {
        throw new SyntaxError("Unexpected end of input");
      }
      const protocol = header.slice(start, i);
      if (protocols.has(protocol)) {
        throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
      }
      protocols.add(protocol);
      return protocols;
    }
    __name(parse12, "parse");
    module2.exports = { parse: parse12 };
  }
});

// node_modules/ws/lib/websocket-server.js
var require_websocket_server = __commonJS({
  "node_modules/ws/lib/websocket-server.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var EventEmitter10 = __require("events");
    var http4 = __require("http");
    var { Duplex } = __require("stream");
    var { createHash: createHash6 } = __require("crypto");
    var extension = require_extension();
    var PerMessageDeflate = require_permessage_deflate();
    var subprotocol = require_subprotocol();
    var WebSocket2 = require_websocket();
    var { GUID, kWebSocket } = require_constants2();
    var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
    var RUNNING = 0;
    var CLOSING = 1;
    var CLOSED2 = 2;
    var WebSocketServer2 = class extends EventEmitter10 {
      static {
        __name(this, "WebSocketServer");
      }
      /**
       * Create a `WebSocketServer` instance.
       *
       * @param {Object} options Configuration options
       * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
       *     any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
       *     multiple times in the same tick
       * @param {Boolean} [options.autoPong=true] Specifies whether or not to
       *     automatically send a pong in response to a ping
       * @param {Number} [options.backlog=511] The maximum length of the queue of
       *     pending connections
       * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
       *     track clients
       * @param {Function} [options.handleProtocols] A hook to handle protocols
       * @param {String} [options.host] The hostname where to bind the server
       * @param {Number} [options.maxPayload=104857600] The maximum allowed message
       *     size
       * @param {Boolean} [options.noServer=false] Enable no server mode
       * @param {String} [options.path] Accept only connections matching this path
       * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
       *     permessage-deflate
       * @param {Number} [options.port] The port where to bind the server
       * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
       *     server to use
       * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
       *     not to skip UTF-8 validation for text and close messages
       * @param {Function} [options.verifyClient] A hook to reject connections
       * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
       *     class to use. It must be the `WebSocket` class or class that extends it
       * @param {Function} [callback] A listener for the `listening` event
       */
      constructor(options2, callback) {
        super();
        options2 = {
          allowSynchronousEvents: true,
          autoPong: true,
          maxPayload: 100 * 1024 * 1024,
          skipUTF8Validation: false,
          perMessageDeflate: false,
          handleProtocols: null,
          clientTracking: true,
          verifyClient: null,
          noServer: false,
          backlog: null,
          // use default (511 as implemented in net.js)
          server: null,
          host: null,
          path: null,
          port: null,
          WebSocket: WebSocket2,
          ...options2
        };
        if (options2.port == null && !options2.server && !options2.noServer || options2.port != null && (options2.server || options2.noServer) || options2.server && options2.noServer) {
          throw new TypeError(
            'One and only one of the "port", "server", or "noServer" options must be specified'
          );
        }
        if (options2.port != null) {
          this._server = http4.createServer((req, res) => {
            const body = http4.STATUS_CODES[426];
            res.writeHead(426, {
              "Content-Length": body.length,
              "Content-Type": "text/plain"
            });
            res.end(body);
          });
          this._server.listen(
            options2.port,
            options2.host,
            options2.backlog,
            callback
          );
        } else if (options2.server) {
          this._server = options2.server;
        }
        if (this._server) {
          const emitConnection = this.emit.bind(this, "connection");
          this._removeListeners = addListeners(this._server, {
            listening: this.emit.bind(this, "listening"),
            error: this.emit.bind(this, "error"),
            upgrade: /* @__PURE__ */ __name((req, socket, head) => {
              this.handleUpgrade(req, socket, head, emitConnection);
            }, "upgrade")
          });
        }
        if (options2.perMessageDeflate === true) options2.perMessageDeflate = {};
        if (options2.clientTracking) {
          this.clients = /* @__PURE__ */ new Set();
          this._shouldEmitClose = false;
        }
        this.options = options2;
        this._state = RUNNING;
      }
      /**
       * Returns the bound address, the address family name, and port of the server
       * as reported by the operating system if listening on an IP socket.
       * If the server is listening on a pipe or UNIX domain socket, the name is
       * returned as a string.
       *
       * @return {(Object|String|null)} The address of the server
       * @public
       */
      address() {
        if (this.options.noServer) {
          throw new Error('The server is operating in "noServer" mode');
        }
        if (!this._server) return null;
        return this._server.address();
      }
      /**
       * Stop the server from accepting new connections and emit the `'close'` event
       * when all existing connections are closed.
       *
       * @param {Function} [cb] A one-time listener for the `'close'` event
       * @public
       */
      close(cb) {
        if (this._state === CLOSED2) {
          if (cb) {
            this.once("close", () => {
              cb(new Error("The server is not running"));
            });
          }
          process.nextTick(emitClose, this);
          return;
        }
        if (cb) this.once("close", cb);
        if (this._state === CLOSING) return;
        this._state = CLOSING;
        if (this.options.noServer || this.options.server) {
          if (this._server) {
            this._removeListeners();
            this._removeListeners = this._server = null;
          }
          if (this.clients) {
            if (!this.clients.size) {
              process.nextTick(emitClose, this);
            } else {
              this._shouldEmitClose = true;
            }
          } else {
            process.nextTick(emitClose, this);
          }
        } else {
          const server = this._server;
          this._removeListeners();
          this._removeListeners = this._server = null;
          server.close(() => {
            emitClose(this);
          });
        }
      }
      /**
       * See if a given request should be handled by this server instance.
       *
       * @param {http.IncomingMessage} req Request object to inspect
       * @return {Boolean} `true` if the request is valid, else `false`
       * @public
       */
      shouldHandle(req) {
        if (this.options.path) {
          const index = req.url.indexOf("?");
          const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
          if (pathname !== this.options.path) return false;
        }
        return true;
      }
      /**
       * Handle a HTTP Upgrade request.
       *
       * @param {http.IncomingMessage} req The request object
       * @param {Duplex} socket The network socket between the server and client
       * @param {Buffer} head The first packet of the upgraded stream
       * @param {Function} cb Callback
       * @public
       */
      handleUpgrade(req, socket, head, cb) {
        socket.on("error", socketOnError);
        const key = req.headers["sec-websocket-key"];
        const upgrade = req.headers.upgrade;
        const version2 = +req.headers["sec-websocket-version"];
        if (req.method !== "GET") {
          const message = "Invalid HTTP method";
          abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
          return;
        }
        if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
          const message = "Invalid Upgrade header";
          abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
          return;
        }
        if (key === void 0 || !keyRegex.test(key)) {
          const message = "Missing or invalid Sec-WebSocket-Key header";
          abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
          return;
        }
        if (version2 !== 13 && version2 !== 8) {
          const message = "Missing or invalid Sec-WebSocket-Version header";
          abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
            "Sec-WebSocket-Version": "13, 8"
          });
          return;
        }
        if (!this.shouldHandle(req)) {
          abortHandshake(socket, 400);
          return;
        }
        const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
        let protocols = /* @__PURE__ */ new Set();
        if (secWebSocketProtocol !== void 0) {
          try {
            protocols = subprotocol.parse(secWebSocketProtocol);
          } catch (err) {
            const message = "Invalid Sec-WebSocket-Protocol header";
            abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
            return;
          }
        }
        const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
        const extensions = {};
        if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
          const perMessageDeflate = new PerMessageDeflate(
            this.options.perMessageDeflate,
            true,
            this.options.maxPayload
          );
          try {
            const offers = extension.parse(secWebSocketExtensions);
            if (offers[PerMessageDeflate.extensionName]) {
              perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
              extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
            }
          } catch (err) {
            const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
            abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
            return;
          }
        }
        if (this.options.verifyClient) {
          const info = {
            origin: req.headers[`${version2 === 8 ? "sec-websocket-origin" : "origin"}`],
            secure: !!(req.socket.authorized || req.socket.encrypted),
            req
          };
          if (this.options.verifyClient.length === 2) {
            this.options.verifyClient(info, (verified, code2, message, headers) => {
              if (!verified) {
                return abortHandshake(socket, code2 || 401, message, headers);
              }
              this.completeUpgrade(
                extensions,
                key,
                protocols,
                req,
                socket,
                head,
                cb
              );
            });
            return;
          }
          if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
        }
        this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
      }
      /**
       * Upgrade the connection to WebSocket.
       *
       * @param {Object} extensions The accepted extensions
       * @param {String} key The value of the `Sec-WebSocket-Key` header
       * @param {Set} protocols The subprotocols
       * @param {http.IncomingMessage} req The request object
       * @param {Duplex} socket The network socket between the server and client
       * @param {Buffer} head The first packet of the upgraded stream
       * @param {Function} cb Callback
       * @throws {Error} If called more than once with the same socket
       * @private
       */
      completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
        if (!socket.readable || !socket.writable) return socket.destroy();
        if (socket[kWebSocket]) {
          throw new Error(
            "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
          );
        }
        if (this._state > RUNNING) return abortHandshake(socket, 503);
        const digest = createHash6("sha1").update(key + GUID).digest("base64");
        const headers = [
          "HTTP/1.1 101 Switching Protocols",
          "Upgrade: websocket",
          "Connection: Upgrade",
          `Sec-WebSocket-Accept: ${digest}`
        ];
        const ws2 = new this.options.WebSocket(null, void 0, this.options);
        if (protocols.size) {
          const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
          if (protocol) {
            headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
            ws2._protocol = protocol;
          }
        }
        if (extensions[PerMessageDeflate.extensionName]) {
          const params = extensions[PerMessageDeflate.extensionName].params;
          const value = extension.format({
            [PerMessageDeflate.extensionName]: [params]
          });
          headers.push(`Sec-WebSocket-Extensions: ${value}`);
          ws2._extensions = extensions;
        }
        this.emit("headers", headers, req);
        socket.write(headers.concat("\r\n").join("\r\n"));
        socket.removeListener("error", socketOnError);
        ws2.setSocket(socket, head, {
          allowSynchronousEvents: this.options.allowSynchronousEvents,
          maxPayload: this.options.maxPayload,
          skipUTF8Validation: this.options.skipUTF8Validation
        });
        if (this.clients) {
          this.clients.add(ws2);
          ws2.on("close", () => {
            this.clients.delete(ws2);
            if (this._shouldEmitClose && !this.clients.size) {
              process.nextTick(emitClose, this);
            }
          });
        }
        cb(ws2, req);
      }
    };
    module2.exports = WebSocketServer2;
    function addListeners(server, map2) {
      for (const event of Object.keys(map2)) server.on(event, map2[event]);
      return /* @__PURE__ */ __name(function removeListeners() {
        for (const event of Object.keys(map2)) {
          server.removeListener(event, map2[event]);
        }
      }, "removeListeners");
    }
    __name(addListeners, "addListeners");
    function emitClose(server) {
      server._state = CLOSED2;
      server.emit("close");
    }
    __name(emitClose, "emitClose");
    function socketOnError() {
      this.destroy();
    }
    __name(socketOnError, "socketOnError");
    function abortHandshake(socket, code2, message, headers) {
      message = message || http4.STATUS_CODES[code2];
      headers = {
        Connection: "close",
        "Content-Type": "text/html",
        "Content-Length": Buffer.byteLength(message),
        ...headers
      };
      socket.once("finish", socket.destroy);
      socket.end(
        `HTTP/1.1 ${code2} ${http4.STATUS_CODES[code2]}\r
` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
      );
    }
    __name(abortHandshake, "abortHandshake");
    function abortHandshakeOrEmitwsClientError(server, req, socket, code2, message, headers) {
      if (server.listenerCount("wsClientError")) {
        const err = new Error(message);
        Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
        server.emit("wsClientError", err, socket, req);
      } else {
        abortHandshake(socket, code2, message, headers);
      }
    }
    __name(abortHandshakeOrEmitwsClientError, "abortHandshakeOrEmitwsClientError");
  }
});

// node_modules/ws/wrapper.mjs
var import_stream, import_receiver, import_sender, import_websocket, import_websocket_server, wrapper_default;
var init_wrapper = __esm({
  "node_modules/ws/wrapper.mjs"() {
    init_esbuild_shims();
    import_stream = __toESM(require_stream(), 1);
    import_receiver = __toESM(require_receiver(), 1);
    import_sender = __toESM(require_sender(), 1);
    import_websocket = __toESM(require_websocket(), 1);
    import_websocket_server = __toESM(require_websocket_server(), 1);
    wrapper_default = import_websocket.default;
  }
});

// node_modules/ink/build/devtools-window-polyfill.js
var customGlobal;
var init_devtools_window_polyfill = __esm({
  "node_modules/ink/build/devtools-window-polyfill.js"() {
    init_esbuild_shims();
    init_wrapper();
    customGlobal = globalThis;
    customGlobal.WebSocket ||= wrapper_default;
    customGlobal.window ||= globalThis;
    customGlobal.self ||= globalThis;
    customGlobal.window.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = [
      {
        // ComponentFilterElementType
        type: 1,
        // ElementTypeHostComponent
        value: 7,
        isEnabled: true
      },
      {
        // ComponentFilterDisplayName
        type: 2,
        value: "InternalApp",
        isEnabled: true,
        isValid: true
      },
      {
        // ComponentFilterDisplayName
        type: 2,
        value: "InternalAppContext",
        isEnabled: true,
        isValid: true
      },
      {
        // ComponentFilterDisplayName
        type: 2,
        value: "InternalStdoutContext",
        isEnabled: true,
        isValid: true
      },
      {
        // ComponentFilterDisplayName
        type: 2,
        value: "InternalStderrContext",
        isEnabled: true,
        isValid: true
      },
      {
        // ComponentFilterDisplayName
        type: 2,
        value: "InternalStdinContext",
        isEnabled: true,
        isValid: true
      },
      {
        // ComponentFilterDisplayName
        type: 2,
        value: "InternalFocusContext",
        isEnabled: true,
        isValid: true
      }
    ];
  }
});

// node_modules/react-devtools-core/dist/backend.js
var require_backend = __commonJS({
  "node_modules/react-devtools-core/dist/backend.js"(exports2, module2) {
    init_esbuild_shims();
    (/* @__PURE__ */ __name(function webpackUniversalModuleDefinition(root, factory) {
      if (typeof exports2 === "object" && typeof module2 === "object")
        module2.exports = factory();
      else if (typeof define === "function" && define.amd)
        define([], factory);
      else if (typeof exports2 === "object")
        exports2["ReactDevToolsBackend"] = factory();
      else
        root["ReactDevToolsBackend"] = factory();
    }, "webpackUniversalModuleDefinition"))(self, () => {
      return (
        /******/
        (() => {
          var __webpack_modules__ = {
            /***/
            602: (
              /***/
              (__unused_webpack_module, exports3, __webpack_require__2) => {
                "use strict";
                var __webpack_unused_export__;
                function _typeof2(obj) {
                  "@babel/helpers - typeof";
                  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                    _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                      return typeof obj2;
                    }, "_typeof");
                  } else {
                    _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                      return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                    }, "_typeof");
                  }
                  return _typeof2(obj);
                }
                __name(_typeof2, "_typeof");
                var k = __webpack_require__2(206), p = __webpack_require__2(189), q = Object.assign, w = p.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, x = [], y = null;
                function z() {
                  if (null === y) {
                    var a = /* @__PURE__ */ new Map();
                    try {
                      A.useContext({
                        _currentValue: null
                      }), A.useState(null), A.useReducer(function(c3) {
                        return c3;
                      }, null), A.useRef(null), "function" === typeof A.useCacheRefresh && A.useCacheRefresh(), A.useLayoutEffect(function() {
                      }), A.useInsertionEffect(function() {
                      }), A.useEffect(function() {
                      }), A.useImperativeHandle(void 0, function() {
                        return null;
                      }), A.useDebugValue(null), A.useCallback(function() {
                      }), A.useMemo(function() {
                        return null;
                      }), "function" === typeof A.useMemoCache && A.useMemoCache(0);
                    } finally {
                      var b = x;
                      x = [];
                    }
                    for (var e2 = 0; e2 < b.length; e2++) {
                      var g = b[e2];
                      a.set(g.primitive, k.parse(g.stackError));
                    }
                    y = a;
                  }
                  return y;
                }
                __name(z, "z");
                var B = null;
                function C() {
                  var a = B;
                  null !== a && (B = a.next);
                  return a;
                }
                __name(C, "C");
                var A = {
                  use: /* @__PURE__ */ __name(function use2() {
                    throw Error("Support for `use` not yet implemented in react-debug-tools.");
                  }, "use"),
                  readContext: /* @__PURE__ */ __name(function readContext(a) {
                    return a._currentValue;
                  }, "readContext"),
                  useCacheRefresh: /* @__PURE__ */ __name(function useCacheRefresh() {
                    var a = C();
                    x.push({
                      primitive: "CacheRefresh",
                      stackError: Error(),
                      value: null !== a ? a.memoizedState : function() {
                      }
                    });
                    return function() {
                    };
                  }, "useCacheRefresh"),
                  useCallback: /* @__PURE__ */ __name(function useCallback52(a) {
                    var b = C();
                    x.push({
                      primitive: "Callback",
                      stackError: Error(),
                      value: null !== b ? b.memoizedState[0] : a
                    });
                    return a;
                  }, "useCallback"),
                  useContext: /* @__PURE__ */ __name(function useContext22(a) {
                    x.push({
                      primitive: "Context",
                      stackError: Error(),
                      value: a._currentValue
                    });
                    return a._currentValue;
                  }, "useContext"),
                  useEffect: /* @__PURE__ */ __name(function useEffect57(a) {
                    C();
                    x.push({
                      primitive: "Effect",
                      stackError: Error(),
                      value: a
                    });
                  }, "useEffect"),
                  useImperativeHandle: /* @__PURE__ */ __name(function useImperativeHandle(a) {
                    C();
                    var b = void 0;
                    null !== a && "object" === _typeof2(a) && (b = a.current);
                    x.push({
                      primitive: "ImperativeHandle",
                      stackError: Error(),
                      value: b
                    });
                  }, "useImperativeHandle"),
                  useDebugValue: /* @__PURE__ */ __name(function useDebugValue(a, b) {
                    x.push({
                      primitive: "DebugValue",
                      stackError: Error(),
                      value: "function" === typeof b ? b(a) : a
                    });
                  }, "useDebugValue"),
                  useLayoutEffect: /* @__PURE__ */ __name(function useLayoutEffect3(a) {
                    C();
                    x.push({
                      primitive: "LayoutEffect",
                      stackError: Error(),
                      value: a
                    });
                  }, "useLayoutEffect"),
                  useInsertionEffect: /* @__PURE__ */ __name(function useInsertionEffect(a) {
                    C();
                    x.push({
                      primitive: "InsertionEffect",
                      stackError: Error(),
                      value: a
                    });
                  }, "useInsertionEffect"),
                  useMemo: /* @__PURE__ */ __name(function useMemo24(a) {
                    var b = C();
                    a = null !== b ? b.memoizedState[0] : a();
                    x.push({
                      primitive: "Memo",
                      stackError: Error(),
                      value: a
                    });
                    return a;
                  }, "useMemo"),
                  useMemoCache: /* @__PURE__ */ __name(function useMemoCache() {
                    return [];
                  }, "useMemoCache"),
                  useReducer: /* @__PURE__ */ __name(function useReducer8(a, b, e2) {
                    a = C();
                    b = null !== a ? a.memoizedState : void 0 !== e2 ? e2(b) : b;
                    x.push({
                      primitive: "Reducer",
                      stackError: Error(),
                      value: b
                    });
                    return [b, function() {
                    }];
                  }, "useReducer"),
                  useRef: /* @__PURE__ */ __name(function useRef21(a) {
                    var b = C();
                    a = null !== b ? b.memoizedState : {
                      current: a
                    };
                    x.push({
                      primitive: "Ref",
                      stackError: Error(),
                      value: a.current
                    });
                    return a;
                  }, "useRef"),
                  useState: /* @__PURE__ */ __name(function useState65(a) {
                    var b = C();
                    a = null !== b ? b.memoizedState : "function" === typeof a ? a() : a;
                    x.push({
                      primitive: "State",
                      stackError: Error(),
                      value: a
                    });
                    return [a, function() {
                    }];
                  }, "useState"),
                  useTransition: /* @__PURE__ */ __name(function useTransition2() {
                    C();
                    C();
                    x.push({
                      primitive: "Transition",
                      stackError: Error(),
                      value: void 0
                    });
                    return [false, function() {
                    }];
                  }, "useTransition"),
                  useSyncExternalStore: /* @__PURE__ */ __name(function useSyncExternalStore2(a, b) {
                    C();
                    C();
                    a = b();
                    x.push({
                      primitive: "SyncExternalStore",
                      stackError: Error(),
                      value: a
                    });
                    return a;
                  }, "useSyncExternalStore"),
                  useDeferredValue: /* @__PURE__ */ __name(function useDeferredValue(a) {
                    var b = C();
                    x.push({
                      primitive: "DeferredValue",
                      stackError: Error(),
                      value: null !== b ? b.memoizedState : a
                    });
                    return a;
                  }, "useDeferredValue"),
                  useId: /* @__PURE__ */ __name(function useId2() {
                    var a = C();
                    a = null !== a ? a.memoizedState : "";
                    x.push({
                      primitive: "Id",
                      stackError: Error(),
                      value: a
                    });
                    return a;
                  }, "useId")
                }, D = {
                  get: /* @__PURE__ */ __name(function get3(a, b) {
                    if (a.hasOwnProperty(b)) return a[b];
                    a = Error("Missing method in Dispatcher: " + b);
                    a.name = "ReactDebugToolsUnsupportedHookError";
                    throw a;
                  }, "get")
                }, E = "undefined" === typeof Proxy ? A : new Proxy(A, D), F = 0;
                function G(a, b, e2) {
                  var g = b[e2].source, c3 = 0;
                  a: for (; c3 < a.length; c3++) {
                    if (a[c3].source === g) {
                      for (var h = e2 + 1, r3 = c3 + 1; h < b.length && r3 < a.length; h++, r3++) {
                        if (a[r3].source !== b[h].source) continue a;
                      }
                      return c3;
                    }
                  }
                  return -1;
                }
                __name(G, "G");
                function H(a, b) {
                  if (!a) return false;
                  b = "use" + b;
                  return a.length < b.length ? false : a.lastIndexOf(b) === a.length - b.length;
                }
                __name(H, "H");
                function I2(a, b, e2) {
                  for (var g = [], c3 = null, h = g, r3 = 0, t2 = [], v = 0; v < b.length; v++) {
                    var u = b[v];
                    var d = a;
                    var l2 = k.parse(u.stackError);
                    b: {
                      var m = l2, n2 = G(m, d, F);
                      if (-1 !== n2) d = n2;
                      else {
                        for (var f = 0; f < d.length && 5 > f; f++) {
                          if (n2 = G(m, d, f), -1 !== n2) {
                            F = f;
                            d = n2;
                            break b;
                          }
                        }
                        d = -1;
                      }
                    }
                    b: {
                      m = l2;
                      n2 = z().get(u.primitive);
                      if (void 0 !== n2) for (f = 0; f < n2.length && f < m.length; f++) {
                        if (n2[f].source !== m[f].source) {
                          f < m.length - 1 && H(m[f].functionName, u.primitive) && f++;
                          f < m.length - 1 && H(m[f].functionName, u.primitive) && f++;
                          m = f;
                          break b;
                        }
                      }
                      m = -1;
                    }
                    l2 = -1 === d || -1 === m || 2 > d - m ? null : l2.slice(m, d - 1);
                    if (null !== l2) {
                      d = 0;
                      if (null !== c3) {
                        for (; d < l2.length && d < c3.length && l2[l2.length - d - 1].source === c3[c3.length - d - 1].source; ) {
                          d++;
                        }
                        for (c3 = c3.length - 1; c3 > d; c3--) {
                          h = t2.pop();
                        }
                      }
                      for (c3 = l2.length - d - 1; 1 <= c3; c3--) {
                        d = [], m = l2[c3], (n2 = l2[c3 - 1].functionName) ? (f = n2.lastIndexOf("."), -1 === f && (f = 0), "use" === n2.slice(f, f + 3) && (f += 3), n2 = n2.slice(f)) : n2 = "", n2 = {
                          id: null,
                          isStateEditable: false,
                          name: n2,
                          value: void 0,
                          subHooks: d
                        }, e2 && (n2.hookSource = {
                          lineNumber: m.lineNumber,
                          columnNumber: m.columnNumber,
                          functionName: m.functionName,
                          fileName: m.fileName
                        }), h.push(n2), t2.push(h), h = d;
                      }
                      c3 = l2;
                    }
                    d = u.primitive;
                    u = {
                      id: "Context" === d || "DebugValue" === d ? null : r3++,
                      isStateEditable: "Reducer" === d || "State" === d,
                      name: d,
                      value: u.value,
                      subHooks: []
                    };
                    e2 && (d = {
                      lineNumber: null,
                      functionName: null,
                      fileName: null,
                      columnNumber: null
                    }, l2 && 1 <= l2.length && (l2 = l2[0], d.lineNumber = l2.lineNumber, d.functionName = l2.functionName, d.fileName = l2.fileName, d.columnNumber = l2.columnNumber), u.hookSource = d);
                    h.push(u);
                  }
                  J(g, null);
                  return g;
                }
                __name(I2, "I");
                function J(a, b) {
                  for (var e2 = [], g = 0; g < a.length; g++) {
                    var c3 = a[g];
                    "DebugValue" === c3.name && 0 === c3.subHooks.length ? (a.splice(g, 1), g--, e2.push(c3)) : J(c3.subHooks, c3);
                  }
                  null !== b && (1 === e2.length ? b.value = e2[0].value : 1 < e2.length && (b.value = e2.map(function(h) {
                    return h.value;
                  })));
                }
                __name(J, "J");
                function K(a) {
                  if (a instanceof Error && "ReactDebugToolsUnsupportedHookError" === a.name) throw a;
                  var b = Error("Error rendering inspected component", {
                    cause: a
                  });
                  b.name = "ReactDebugToolsRenderError";
                  b.cause = a;
                  throw b;
                }
                __name(K, "K");
                function L(a, b, e2) {
                  var g = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : false;
                  null == e2 && (e2 = w.ReactCurrentDispatcher);
                  var c3 = e2.current;
                  e2.current = E;
                  try {
                    var h = Error();
                    a(b);
                  } catch (t2) {
                    K(t2);
                  } finally {
                    var r3 = x;
                    x = [];
                    e2.current = c3;
                  }
                  c3 = k.parse(h);
                  return I2(c3, r3, g);
                }
                __name(L, "L");
                function M(a) {
                  a.forEach(function(b, e2) {
                    return e2._currentValue = b;
                  });
                }
                __name(M, "M");
                __webpack_unused_export__ = L;
                exports3.inspectHooksOfFiber = function(a, b) {
                  var e2 = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : false;
                  null == b && (b = w.ReactCurrentDispatcher);
                  if (0 !== a.tag && 15 !== a.tag && 11 !== a.tag) throw Error("Unknown Fiber. Needs to be a function component to inspect hooks.");
                  z();
                  var g = a.type, c3 = a.memoizedProps;
                  if (g !== a.elementType && g && g.defaultProps) {
                    c3 = q({}, c3);
                    var h = g.defaultProps;
                    for (r3 in h) {
                      void 0 === c3[r3] && (c3[r3] = h[r3]);
                    }
                  }
                  B = a.memoizedState;
                  var r3 = /* @__PURE__ */ new Map();
                  try {
                    for (h = a; h; ) {
                      if (10 === h.tag) {
                        var t2 = h.type._context;
                        r3.has(t2) || (r3.set(t2, t2._currentValue), t2._currentValue = h.memoizedProps.value);
                      }
                      h = h.return;
                    }
                    if (11 === a.tag) {
                      var v = g.render;
                      g = c3;
                      var u = a.ref;
                      t2 = b;
                      var d = t2.current;
                      t2.current = E;
                      try {
                        var l2 = Error();
                        v(g, u);
                      } catch (f) {
                        K(f);
                      } finally {
                        var m = x;
                        x = [];
                        t2.current = d;
                      }
                      var n2 = k.parse(l2);
                      return I2(n2, m, e2);
                    }
                    return L(g, c3, b, e2);
                  } finally {
                    B = null, M(r3);
                  }
                };
              }
            ),
            /***/
            987: (
              /***/
              (module3, __unused_webpack_exports, __webpack_require__2) => {
                "use strict";
                if (true) {
                  module3.exports = __webpack_require__2(602);
                } else {
                }
              }
            ),
            /***/
            9: (
              /***/
              (__unused_webpack_module, exports3) => {
                "use strict";
                var __webpack_unused_export__;
                function _typeof2(obj) {
                  "@babel/helpers - typeof";
                  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                    _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                      return typeof obj2;
                    }, "_typeof");
                  } else {
                    _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                      return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                    }, "_typeof");
                  }
                  return _typeof2(obj);
                }
                __name(_typeof2, "_typeof");
                var b = Symbol.for("react.element"), c3 = Symbol.for("react.portal"), d = Symbol.for("react.fragment"), e2 = Symbol.for("react.strict_mode"), f = Symbol.for("react.profiler"), g = Symbol.for("react.provider"), h = Symbol.for("react.context"), k = Symbol.for("react.server_context"), l2 = Symbol.for("react.forward_ref"), m = Symbol.for("react.suspense"), n2 = Symbol.for("react.suspense_list"), p = Symbol.for("react.memo"), q = Symbol.for("react.lazy"), t2 = Symbol.for("react.offscreen"), u = Symbol.for("react.cache"), v = Symbol.for("react.client.reference");
                function w(a) {
                  if ("object" === _typeof2(a) && null !== a) {
                    var r3 = a.$$typeof;
                    switch (r3) {
                      case b:
                        switch (a = a.type, a) {
                          case d:
                          case f:
                          case e2:
                          case m:
                          case n2:
                            return a;
                          default:
                            switch (a = a && a.$$typeof, a) {
                              case k:
                              case h:
                              case l2:
                              case q:
                              case p:
                              case g:
                                return a;
                              default:
                                return r3;
                            }
                        }
                      case c3:
                        return r3;
                    }
                  }
                }
                __name(w, "w");
                exports3.ContextConsumer = h;
                exports3.ContextProvider = g;
                __webpack_unused_export__ = b;
                exports3.ForwardRef = l2;
                exports3.Fragment = d;
                exports3.Lazy = q;
                exports3.Memo = p;
                exports3.Portal = c3;
                exports3.Profiler = f;
                exports3.StrictMode = e2;
                exports3.Suspense = m;
                __webpack_unused_export__ = n2;
                __webpack_unused_export__ = /* @__PURE__ */ __name(function() {
                  return false;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function() {
                  return false;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a) {
                  return w(a) === h;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a) {
                  return w(a) === g;
                }, "__webpack_unused_export__");
                exports3.isElement = function(a) {
                  return "object" === _typeof2(a) && null !== a && a.$$typeof === b;
                };
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a) {
                  return w(a) === l2;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a) {
                  return w(a) === d;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a) {
                  return w(a) === q;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a) {
                  return w(a) === p;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a) {
                  return w(a) === c3;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a) {
                  return w(a) === f;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a) {
                  return w(a) === e2;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a) {
                  return w(a) === m;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a) {
                  return w(a) === n2;
                }, "__webpack_unused_export__");
                __webpack_unused_export__ = /* @__PURE__ */ __name(function(a) {
                  return "string" === typeof a || "function" === typeof a || a === d || a === f || a === e2 || a === m || a === n2 || a === t2 || a === u || "object" === _typeof2(a) && null !== a && (a.$$typeof === q || a.$$typeof === p || a.$$typeof === g || a.$$typeof === h || a.$$typeof === l2 || a.$$typeof === v || void 0 !== a.getModuleId) ? true : false;
                }, "__webpack_unused_export__");
                exports3.typeOf = w;
              }
            ),
            /***/
            550: (
              /***/
              (module3, __unused_webpack_exports, __webpack_require__2) => {
                "use strict";
                if (true) {
                  module3.exports = __webpack_require__2(9);
                } else {
                }
              }
            ),
            /***/
            978: (
              /***/
              (__unused_webpack_module, exports3) => {
                "use strict";
                function _typeof2(obj) {
                  "@babel/helpers - typeof";
                  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                    _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                      return typeof obj2;
                    }, "_typeof");
                  } else {
                    _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                      return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                    }, "_typeof");
                  }
                  return _typeof2(obj);
                }
                __name(_typeof2, "_typeof");
                var l2 = Symbol.for("react.element"), n2 = Symbol.for("react.portal"), p = Symbol.for("react.fragment"), q = Symbol.for("react.strict_mode"), r3 = Symbol.for("react.profiler"), t2 = Symbol.for("react.provider"), u = Symbol.for("react.context"), v = Symbol.for("react.server_context"), w = Symbol.for("react.forward_ref"), x = Symbol.for("react.suspense"), y = Symbol.for("react.suspense_list"), z = Symbol.for("react.memo"), A = Symbol.for("react.lazy"), aa = Symbol.for("react.debug_trace_mode"), ba = Symbol.for("react.offscreen"), ca = Symbol.for("react.cache"), B = Symbol.for("react.default_value"), da = Symbol.for("react.postpone"), C = Symbol.iterator;
                function ea(a) {
                  if (null === a || "object" !== _typeof2(a)) return null;
                  a = C && a[C] || a["@@iterator"];
                  return "function" === typeof a ? a : null;
                }
                __name(ea, "ea");
                var D = {
                  isMounted: /* @__PURE__ */ __name(function isMounted() {
                    return false;
                  }, "isMounted"),
                  enqueueForceUpdate: /* @__PURE__ */ __name(function enqueueForceUpdate() {
                  }, "enqueueForceUpdate"),
                  enqueueReplaceState: /* @__PURE__ */ __name(function enqueueReplaceState() {
                  }, "enqueueReplaceState"),
                  enqueueSetState: /* @__PURE__ */ __name(function enqueueSetState() {
                  }, "enqueueSetState")
                }, E = Object.assign, F = {};
                function G(a, b, c3) {
                  this.props = a;
                  this.context = b;
                  this.refs = F;
                  this.updater = c3 || D;
                }
                __name(G, "G");
                G.prototype.isReactComponent = {};
                G.prototype.setState = function(a, b) {
                  if ("object" !== _typeof2(a) && "function" !== typeof a && null != a) throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");
                  this.updater.enqueueSetState(this, a, b, "setState");
                };
                G.prototype.forceUpdate = function(a) {
                  this.updater.enqueueForceUpdate(this, a, "forceUpdate");
                };
                function H() {
                }
                __name(H, "H");
                H.prototype = G.prototype;
                function I2(a, b, c3) {
                  this.props = a;
                  this.context = b;
                  this.refs = F;
                  this.updater = c3 || D;
                }
                __name(I2, "I");
                var J = I2.prototype = new H();
                J.constructor = I2;
                E(J, G.prototype);
                J.isPureReactComponent = true;
                var K = Array.isArray, L = Object.prototype.hasOwnProperty, M = {
                  current: null
                }, N = {
                  key: true,
                  ref: true,
                  __self: true,
                  __source: true
                };
                function O(a, b, c3) {
                  var d, e2 = {}, f = null, g = null;
                  if (null != b) for (d in void 0 !== b.ref && (g = b.ref), void 0 !== b.key && (f = "" + b.key), b) {
                    L.call(b, d) && !N.hasOwnProperty(d) && (e2[d] = b[d]);
                  }
                  var h = arguments.length - 2;
                  if (1 === h) e2.children = c3;
                  else if (1 < h) {
                    for (var k = Array(h), m = 0; m < h; m++) {
                      k[m] = arguments[m + 2];
                    }
                    e2.children = k;
                  }
                  if (a && a.defaultProps) for (d in h = a.defaultProps, h) {
                    void 0 === e2[d] && (e2[d] = h[d]);
                  }
                  return {
                    $$typeof: l2,
                    type: a,
                    key: f,
                    ref: g,
                    props: e2,
                    _owner: M.current
                  };
                }
                __name(O, "O");
                function fa(a, b) {
                  return {
                    $$typeof: l2,
                    type: a.type,
                    key: b,
                    ref: a.ref,
                    props: a.props,
                    _owner: a._owner
                  };
                }
                __name(fa, "fa");
                function P(a) {
                  return "object" === _typeof2(a) && null !== a && a.$$typeof === l2;
                }
                __name(P, "P");
                function escape7(a) {
                  var b = {
                    "=": "=0",
                    ":": "=2"
                  };
                  return "$" + a.replace(/[=:]/g, function(c3) {
                    return b[c3];
                  });
                }
                __name(escape7, "escape");
                var Q = /\/+/g;
                function R(a, b) {
                  return "object" === _typeof2(a) && null !== a && null != a.key ? escape7("" + a.key) : b.toString(36);
                }
                __name(R, "R");
                function S(a, b, c3, d, e2) {
                  var f = _typeof2(a);
                  if ("undefined" === f || "boolean" === f) a = null;
                  var g = false;
                  if (null === a) g = true;
                  else switch (f) {
                    case "string":
                    case "number":
                      g = true;
                      break;
                    case "object":
                      switch (a.$$typeof) {
                        case l2:
                        case n2:
                          g = true;
                      }
                  }
                  if (g) return g = a, e2 = e2(g), a = "" === d ? "." + R(g, 0) : d, K(e2) ? (c3 = "", null != a && (c3 = a.replace(Q, "$&/") + "/"), S(e2, b, c3, "", function(m) {
                    return m;
                  })) : null != e2 && (P(e2) && (e2 = fa(e2, c3 + (!e2.key || g && g.key === e2.key ? "" : ("" + e2.key).replace(Q, "$&/") + "/") + a)), b.push(e2)), 1;
                  g = 0;
                  d = "" === d ? "." : d + ":";
                  if (K(a)) for (var h = 0; h < a.length; h++) {
                    f = a[h];
                    var k = d + R(f, h);
                    g += S(f, b, c3, k, e2);
                  }
                  else if (k = ea(a), "function" === typeof k) for (a = k.call(a), h = 0; !(f = a.next()).done; ) {
                    f = f.value, k = d + R(f, h++), g += S(f, b, c3, k, e2);
                  }
                  else if ("object" === f) throw b = String(a), Error("Objects are not valid as a React child (found: " + ("[object Object]" === b ? "object with keys {" + Object.keys(a).join(", ") + "}" : b) + "). If you meant to render a collection of children, use an array instead.");
                  return g;
                }
                __name(S, "S");
                function T(a, b, c3) {
                  if (null == a) return a;
                  var d = [], e2 = 0;
                  S(a, d, "", "", function(f) {
                    return b.call(c3, f, e2++);
                  });
                  return d;
                }
                __name(T, "T");
                function ha(a) {
                  if (-1 === a._status) {
                    var b = a._result;
                    b = b();
                    b.then(function(c3) {
                      if (0 === a._status || -1 === a._status) a._status = 1, a._result = c3;
                    }, function(c3) {
                      if (0 === a._status || -1 === a._status) a._status = 2, a._result = c3;
                    });
                    -1 === a._status && (a._status = 0, a._result = b);
                  }
                  if (1 === a._status) return a._result.default;
                  throw a._result;
                }
                __name(ha, "ha");
                var U = {
                  current: null
                };
                function ia() {
                  return /* @__PURE__ */ new WeakMap();
                }
                __name(ia, "ia");
                function V2() {
                  return {
                    s: 0,
                    v: void 0,
                    o: null,
                    p: null
                  };
                }
                __name(V2, "V");
                var W = {
                  current: null
                };
                function X(a, b) {
                  return W.current.useOptimistic(a, b);
                }
                __name(X, "X");
                var Y = {
                  transition: null
                }, Z = {}, ja = {
                  ReactCurrentDispatcher: W,
                  ReactCurrentCache: U,
                  ReactCurrentBatchConfig: Y,
                  ReactCurrentOwner: M,
                  ContextRegistry: Z
                };
                exports3.Children = {
                  map: T,
                  forEach: /* @__PURE__ */ __name(function forEach2(a, b, c3) {
                    T(a, function() {
                      b.apply(this, arguments);
                    }, c3);
                  }, "forEach"),
                  count: /* @__PURE__ */ __name(function count(a) {
                    var b = 0;
                    T(a, function() {
                      b++;
                    });
                    return b;
                  }, "count"),
                  toArray: /* @__PURE__ */ __name(function toArray(a) {
                    return T(a, function(b) {
                      return b;
                    }) || [];
                  }, "toArray"),
                  only: /* @__PURE__ */ __name(function only(a) {
                    if (!P(a)) throw Error("React.Children.only expected to receive a single React element child.");
                    return a;
                  }, "only")
                };
                exports3.Component = G;
                exports3.Fragment = p;
                exports3.Profiler = r3;
                exports3.PureComponent = I2;
                exports3.StrictMode = q;
                exports3.Suspense = x;
                exports3.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ja;
                exports3.cache = function(a) {
                  return function() {
                    var b = U.current;
                    if (!b) return a.apply(null, arguments);
                    var c3 = b.getCacheForType(ia);
                    b = c3.get(a);
                    void 0 === b && (b = V2(), c3.set(a, b));
                    c3 = 0;
                    for (var d = arguments.length; c3 < d; c3++) {
                      var e2 = arguments[c3];
                      if ("function" === typeof e2 || "object" === _typeof2(e2) && null !== e2) {
                        var f = b.o;
                        null === f && (b.o = f = /* @__PURE__ */ new WeakMap());
                        b = f.get(e2);
                        void 0 === b && (b = V2(), f.set(e2, b));
                      } else f = b.p, null === f && (b.p = f = /* @__PURE__ */ new Map()), b = f.get(e2), void 0 === b && (b = V2(), f.set(e2, b));
                    }
                    if (1 === b.s) return b.v;
                    if (2 === b.s) throw b.v;
                    try {
                      var g = a.apply(null, arguments);
                      c3 = b;
                      c3.s = 1;
                      return c3.v = g;
                    } catch (h) {
                      throw g = b, g.s = 2, g.v = h, h;
                    }
                  };
                };
                exports3.cloneElement = function(a, b, c3) {
                  if (null === a || void 0 === a) throw Error("React.cloneElement(...): The argument must be a React element, but you passed " + a + ".");
                  var d = E({}, a.props), e2 = a.key, f = a.ref, g = a._owner;
                  if (null != b) {
                    void 0 !== b.ref && (f = b.ref, g = M.current);
                    void 0 !== b.key && (e2 = "" + b.key);
                    if (a.type && a.type.defaultProps) var h = a.type.defaultProps;
                    for (k in b) {
                      L.call(b, k) && !N.hasOwnProperty(k) && (d[k] = void 0 === b[k] && void 0 !== h ? h[k] : b[k]);
                    }
                  }
                  var k = arguments.length - 2;
                  if (1 === k) d.children = c3;
                  else if (1 < k) {
                    h = Array(k);
                    for (var m = 0; m < k; m++) {
                      h[m] = arguments[m + 2];
                    }
                    d.children = h;
                  }
                  return {
                    $$typeof: l2,
                    type: a.type,
                    key: e2,
                    ref: f,
                    props: d,
                    _owner: g
                  };
                };
                exports3.createContext = function(a) {
                  a = {
                    $$typeof: u,
                    _currentValue: a,
                    _currentValue2: a,
                    _threadCount: 0,
                    Provider: null,
                    Consumer: null,
                    _defaultValue: null,
                    _globalName: null
                  };
                  a.Provider = {
                    $$typeof: t2,
                    _context: a
                  };
                  return a.Consumer = a;
                };
                exports3.createElement = O;
                exports3.createFactory = function(a) {
                  var b = O.bind(null, a);
                  b.type = a;
                  return b;
                };
                exports3.createRef = function() {
                  return {
                    current: null
                  };
                };
                exports3.createServerContext = function(a, b) {
                  var c3 = true;
                  if (!Z[a]) {
                    c3 = false;
                    var d = {
                      $$typeof: v,
                      _currentValue: b,
                      _currentValue2: b,
                      _defaultValue: b,
                      _threadCount: 0,
                      Provider: null,
                      Consumer: null,
                      _globalName: a
                    };
                    d.Provider = {
                      $$typeof: t2,
                      _context: d
                    };
                    Z[a] = d;
                  }
                  d = Z[a];
                  if (d._defaultValue === B) d._defaultValue = b, d._currentValue === B && (d._currentValue = b), d._currentValue2 === B && (d._currentValue2 = b);
                  else if (c3) throw Error("ServerContext: " + a + " already defined");
                  return d;
                };
                exports3.experimental_useEffectEvent = function(a) {
                  return W.current.useEffectEvent(a);
                };
                exports3.experimental_useOptimistic = function(a, b) {
                  return X(a, b);
                };
                exports3.forwardRef = function(a) {
                  return {
                    $$typeof: w,
                    render: a
                  };
                };
                exports3.isValidElement = P;
                exports3.lazy = function(a) {
                  return {
                    $$typeof: A,
                    _payload: {
                      _status: -1,
                      _result: a
                    },
                    _init: ha
                  };
                };
                exports3.memo = function(a, b) {
                  return {
                    $$typeof: z,
                    type: a,
                    compare: void 0 === b ? null : b
                  };
                };
                exports3.startTransition = function(a) {
                  var b = Y.transition;
                  Y.transition = {};
                  try {
                    a();
                  } finally {
                    Y.transition = b;
                  }
                };
                exports3.unstable_Cache = ca;
                exports3.unstable_DebugTracingMode = aa;
                exports3.unstable_Offscreen = ba;
                exports3.unstable_SuspenseList = y;
                exports3.unstable_act = function() {
                  throw Error("act(...) is not supported in production builds of React.");
                };
                exports3.unstable_getCacheForType = function(a) {
                  var b = U.current;
                  return b ? b.getCacheForType(a) : a();
                };
                exports3.unstable_getCacheSignal = function() {
                  var a = U.current;
                  return a ? a.getCacheSignal() : (a = new AbortController(), a.abort(Error("This CacheSignal was requested outside React which means that it is immediately aborted.")), a.signal);
                };
                exports3.unstable_postpone = function(a) {
                  a = Error(a);
                  a.$$typeof = da;
                  throw a;
                };
                exports3.unstable_useCacheRefresh = function() {
                  return W.current.useCacheRefresh();
                };
                exports3.unstable_useMemoCache = function(a) {
                  return W.current.useMemoCache(a);
                };
                exports3.use = function(a) {
                  return W.current.use(a);
                };
                exports3.useCallback = function(a, b) {
                  return W.current.useCallback(a, b);
                };
                exports3.useContext = function(a) {
                  return W.current.useContext(a);
                };
                exports3.useDebugValue = function() {
                };
                exports3.useDeferredValue = function(a, b) {
                  return W.current.useDeferredValue(a, b);
                };
                exports3.useEffect = function(a, b) {
                  return W.current.useEffect(a, b);
                };
                exports3.useId = function() {
                  return W.current.useId();
                };
                exports3.useImperativeHandle = function(a, b, c3) {
                  return W.current.useImperativeHandle(a, b, c3);
                };
                exports3.useInsertionEffect = function(a, b) {
                  return W.current.useInsertionEffect(a, b);
                };
                exports3.useLayoutEffect = function(a, b) {
                  return W.current.useLayoutEffect(a, b);
                };
                exports3.useMemo = function(a, b) {
                  return W.current.useMemo(a, b);
                };
                exports3.useOptimistic = X;
                exports3.useReducer = function(a, b, c3) {
                  return W.current.useReducer(a, b, c3);
                };
                exports3.useRef = function(a) {
                  return W.current.useRef(a);
                };
                exports3.useState = function(a) {
                  return W.current.useState(a);
                };
                exports3.useSyncExternalStore = function(a, b, c3) {
                  return W.current.useSyncExternalStore(a, b, c3);
                };
                exports3.useTransition = function() {
                  return W.current.useTransition();
                };
                exports3.version = "18.3.0-experimental-51ffd3564-20231025";
              }
            ),
            /***/
            189: (
              /***/
              (module3, __unused_webpack_exports, __webpack_require__2) => {
                "use strict";
                if (true) {
                  module3.exports = __webpack_require__2(978);
                } else {
                }
              }
            ),
            /***/
            206: (
              /***/
              function(module3, exports3, __webpack_require__2) {
                var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;
                function _typeof2(obj) {
                  "@babel/helpers - typeof";
                  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                    _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                      return typeof obj2;
                    }, "_typeof");
                  } else {
                    _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                      return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                    }, "_typeof");
                  }
                  return _typeof2(obj);
                }
                __name(_typeof2, "_typeof");
                (function(root, factory) {
                  "use strict";
                  if (true) {
                    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__2(430)], __WEBPACK_AMD_DEFINE_FACTORY__ = factory, __WEBPACK_AMD_DEFINE_RESULT__ = typeof __WEBPACK_AMD_DEFINE_FACTORY__ === "function" ? __WEBPACK_AMD_DEFINE_FACTORY__.apply(exports3, __WEBPACK_AMD_DEFINE_ARRAY__) : __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__ !== void 0 && (module3.exports = __WEBPACK_AMD_DEFINE_RESULT__));
                  } else {
                  }
                })(this, /* @__PURE__ */ __name(function ErrorStackParser(StackFrame) {
                  "use strict";
                  var FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\S+:\d+/;
                  var CHROME_IE_STACK_REGEXP = /^\s*at .*(\S+:\d+|\(native\))/m;
                  var SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\[native code])?$/;
                  return {
                    /**
                     * Given an Error object, extract the most information from it.
                     *
                     * @param {Error} error object
                     * @return {Array} of StackFrames
                     */
                    parse: /* @__PURE__ */ __name(function ErrorStackParser$$parse(error) {
                      if (typeof error.stacktrace !== "undefined" || typeof error["opera#sourceloc"] !== "undefined") {
                        return this.parseOpera(error);
                      } else if (error.stack && error.stack.match(CHROME_IE_STACK_REGEXP)) {
                        return this.parseV8OrIE(error);
                      } else if (error.stack) {
                        return this.parseFFOrSafari(error);
                      } else {
                        throw new Error("Cannot parse given Error object");
                      }
                    }, "ErrorStackParser$$parse"),
                    // Separate line and column numbers from a string of the form: (URI:Line:Column)
                    extractLocation: /* @__PURE__ */ __name(function ErrorStackParser$$extractLocation(urlLike) {
                      if (urlLike.indexOf(":") === -1) {
                        return [urlLike];
                      }
                      var regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/;
                      var parts = regExp.exec(urlLike.replace(/[()]/g, ""));
                      return [parts[1], parts[2] || void 0, parts[3] || void 0];
                    }, "ErrorStackParser$$extractLocation"),
                    parseV8OrIE: /* @__PURE__ */ __name(function ErrorStackParser$$parseV8OrIE(error) {
                      var filtered = error.stack.split("\n").filter(function(line) {
                        return !!line.match(CHROME_IE_STACK_REGEXP);
                      }, this);
                      return filtered.map(function(line) {
                        if (line.indexOf("(eval ") > -1) {
                          line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(\),.*$)/g, "");
                        }
                        var sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(");
                        var location = sanitizedLine.match(/ (\((.+):(\d+):(\d+)\)$)/);
                        sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine;
                        var tokens = sanitizedLine.split(/\s+/).slice(1);
                        var locationParts = this.extractLocation(location ? location[1] : tokens.pop());
                        var functionName = tokens.join(" ") || void 0;
                        var fileName = ["eval", "<anonymous>"].indexOf(locationParts[0]) > -1 ? void 0 : locationParts[0];
                        return new StackFrame({
                          functionName,
                          fileName,
                          lineNumber: locationParts[1],
                          columnNumber: locationParts[2],
                          source: line
                        });
                      }, this);
                    }, "ErrorStackParser$$parseV8OrIE"),
                    parseFFOrSafari: /* @__PURE__ */ __name(function ErrorStackParser$$parseFFOrSafari(error) {
                      var filtered = error.stack.split("\n").filter(function(line) {
                        return !line.match(SAFARI_NATIVE_CODE_REGEXP);
                      }, this);
                      return filtered.map(function(line) {
                        if (line.indexOf(" > eval") > -1) {
                          line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1");
                        }
                        if (line.indexOf("@") === -1 && line.indexOf(":") === -1) {
                          return new StackFrame({
                            functionName: line
                          });
                        } else {
                          var functionNameRegex = /((.*".+"[^@]*)?[^@]*)(?:@)/;
                          var matches = line.match(functionNameRegex);
                          var functionName = matches && matches[1] ? matches[1] : void 0;
                          var locationParts = this.extractLocation(line.replace(functionNameRegex, ""));
                          return new StackFrame({
                            functionName,
                            fileName: locationParts[0],
                            lineNumber: locationParts[1],
                            columnNumber: locationParts[2],
                            source: line
                          });
                        }
                      }, this);
                    }, "ErrorStackParser$$parseFFOrSafari"),
                    parseOpera: /* @__PURE__ */ __name(function ErrorStackParser$$parseOpera(e2) {
                      if (!e2.stacktrace || e2.message.indexOf("\n") > -1 && e2.message.split("\n").length > e2.stacktrace.split("\n").length) {
                        return this.parseOpera9(e2);
                      } else if (!e2.stack) {
                        return this.parseOpera10(e2);
                      } else {
                        return this.parseOpera11(e2);
                      }
                    }, "ErrorStackParser$$parseOpera"),
                    parseOpera9: /* @__PURE__ */ __name(function ErrorStackParser$$parseOpera9(e2) {
                      var lineRE = /Line (\d+).*script (?:in )?(\S+)/i;
                      var lines = e2.message.split("\n");
                      var result = [];
                      for (var i = 2, len = lines.length; i < len; i += 2) {
                        var match2 = lineRE.exec(lines[i]);
                        if (match2) {
                          result.push(new StackFrame({
                            fileName: match2[2],
                            lineNumber: match2[1],
                            source: lines[i]
                          }));
                        }
                      }
                      return result;
                    }, "ErrorStackParser$$parseOpera9"),
                    parseOpera10: /* @__PURE__ */ __name(function ErrorStackParser$$parseOpera10(e2) {
                      var lineRE = /Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i;
                      var lines = e2.stacktrace.split("\n");
                      var result = [];
                      for (var i = 0, len = lines.length; i < len; i += 2) {
                        var match2 = lineRE.exec(lines[i]);
                        if (match2) {
                          result.push(new StackFrame({
                            functionName: match2[3] || void 0,
                            fileName: match2[2],
                            lineNumber: match2[1],
                            source: lines[i]
                          }));
                        }
                      }
                      return result;
                    }, "ErrorStackParser$$parseOpera10"),
                    // Opera 10.65+ Error.stack very similar to FF/Safari
                    parseOpera11: /* @__PURE__ */ __name(function ErrorStackParser$$parseOpera11(error) {
                      var filtered = error.stack.split("\n").filter(function(line) {
                        return !!line.match(FIREFOX_SAFARI_STACK_REGEXP) && !line.match(/^Error created at/);
                      }, this);
                      return filtered.map(function(line) {
                        var tokens = line.split("@");
                        var locationParts = this.extractLocation(tokens.pop());
                        var functionCall = tokens.shift() || "";
                        var functionName = functionCall.replace(/<anonymous function(: (\w+))?>/, "$2").replace(/\([^)]*\)/g, "") || void 0;
                        var argsRaw;
                        if (functionCall.match(/\(([^)]*)\)/)) {
                          argsRaw = functionCall.replace(/^[^(]+\(([^)]*)\)$/, "$1");
                        }
                        var args = argsRaw === void 0 || argsRaw === "[arguments not available]" ? void 0 : argsRaw.split(",");
                        return new StackFrame({
                          functionName,
                          args,
                          fileName: locationParts[0],
                          lineNumber: locationParts[1],
                          columnNumber: locationParts[2],
                          source: line
                        });
                      }, this);
                    }, "ErrorStackParser$$parseOpera11")
                  };
                }, "ErrorStackParser"));
              }
            ),
            /***/
            172: (
              /***/
              (module3) => {
                function _typeof2(obj) {
                  "@babel/helpers - typeof";
                  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                    _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                      return typeof obj2;
                    }, "_typeof");
                  } else {
                    _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                      return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                    }, "_typeof");
                  }
                  return _typeof2(obj);
                }
                __name(_typeof2, "_typeof");
                var FUNC_ERROR_TEXT = "Expected a function";
                var NAN2 = 0 / 0;
                var symbolTag = "[object Symbol]";
                var reTrim = /^\s+|\s+$/g;
                var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
                var reIsBinary = /^0b[01]+$/i;
                var reIsOctal = /^0o[0-7]+$/i;
                var freeParseInt = parseInt;
                var freeGlobal = (typeof globalThis === "undefined" ? "undefined" : _typeof2(globalThis)) == "object" && globalThis && globalThis.Object === Object && globalThis;
                var freeSelf = (typeof self === "undefined" ? "undefined" : _typeof2(self)) == "object" && self && self.Object === Object && self;
                var root = freeGlobal || freeSelf || Function("return this")();
                var objectProto = Object.prototype;
                var objectToString2 = objectProto.toString;
                var nativeMax = Math.max, nativeMin = Math.min;
                var now = /* @__PURE__ */ __name(function now2() {
                  return root.Date.now();
                }, "now");
                function debounce3(func, wait, options2) {
                  var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
                  if (typeof func != "function") {
                    throw new TypeError(FUNC_ERROR_TEXT);
                  }
                  wait = toNumber2(wait) || 0;
                  if (isObject3(options2)) {
                    leading = !!options2.leading;
                    maxing = "maxWait" in options2;
                    maxWait = maxing ? nativeMax(toNumber2(options2.maxWait) || 0, wait) : maxWait;
                    trailing = "trailing" in options2 ? !!options2.trailing : trailing;
                  }
                  function invokeFunc(time) {
                    var args = lastArgs, thisArg = lastThis;
                    lastArgs = lastThis = void 0;
                    lastInvokeTime = time;
                    result = func.apply(thisArg, args);
                    return result;
                  }
                  __name(invokeFunc, "invokeFunc");
                  function leadingEdge(time) {
                    lastInvokeTime = time;
                    timerId = setTimeout(timerExpired, wait);
                    return leading ? invokeFunc(time) : result;
                  }
                  __name(leadingEdge, "leadingEdge");
                  function remainingWait(time) {
                    var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result2 = wait - timeSinceLastCall;
                    return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2;
                  }
                  __name(remainingWait, "remainingWait");
                  function shouldInvoke(time) {
                    var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
                    return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
                  }
                  __name(shouldInvoke, "shouldInvoke");
                  function timerExpired() {
                    var time = now();
                    if (shouldInvoke(time)) {
                      return trailingEdge(time);
                    }
                    timerId = setTimeout(timerExpired, remainingWait(time));
                  }
                  __name(timerExpired, "timerExpired");
                  function trailingEdge(time) {
                    timerId = void 0;
                    if (trailing && lastArgs) {
                      return invokeFunc(time);
                    }
                    lastArgs = lastThis = void 0;
                    return result;
                  }
                  __name(trailingEdge, "trailingEdge");
                  function cancel() {
                    if (timerId !== void 0) {
                      clearTimeout(timerId);
                    }
                    lastInvokeTime = 0;
                    lastArgs = lastCallTime = lastThis = timerId = void 0;
                  }
                  __name(cancel, "cancel");
                  function flush() {
                    return timerId === void 0 ? result : trailingEdge(now());
                  }
                  __name(flush, "flush");
                  function debounced() {
                    var time = now(), isInvoking = shouldInvoke(time);
                    lastArgs = arguments;
                    lastThis = this;
                    lastCallTime = time;
                    if (isInvoking) {
                      if (timerId === void 0) {
                        return leadingEdge(lastCallTime);
                      }
                      if (maxing) {
                        timerId = setTimeout(timerExpired, wait);
                        return invokeFunc(lastCallTime);
                      }
                    }
                    if (timerId === void 0) {
                      timerId = setTimeout(timerExpired, wait);
                    }
                    return result;
                  }
                  __name(debounced, "debounced");
                  debounced.cancel = cancel;
                  debounced.flush = flush;
                  return debounced;
                }
                __name(debounce3, "debounce");
                function throttle2(func, wait, options2) {
                  var leading = true, trailing = true;
                  if (typeof func != "function") {
                    throw new TypeError(FUNC_ERROR_TEXT);
                  }
                  if (isObject3(options2)) {
                    leading = "leading" in options2 ? !!options2.leading : leading;
                    trailing = "trailing" in options2 ? !!options2.trailing : trailing;
                  }
                  return debounce3(func, wait, {
                    "leading": leading,
                    "maxWait": wait,
                    "trailing": trailing
                  });
                }
                __name(throttle2, "throttle");
                function isObject3(value) {
                  var type = _typeof2(value);
                  return !!value && (type == "object" || type == "function");
                }
                __name(isObject3, "isObject");
                function isObjectLike(value) {
                  return !!value && _typeof2(value) == "object";
                }
                __name(isObjectLike, "isObjectLike");
                function isSymbol(value) {
                  return _typeof2(value) == "symbol" || isObjectLike(value) && objectToString2.call(value) == symbolTag;
                }
                __name(isSymbol, "isSymbol");
                function toNumber2(value) {
                  if (typeof value == "number") {
                    return value;
                  }
                  if (isSymbol(value)) {
                    return NAN2;
                  }
                  if (isObject3(value)) {
                    var other2 = typeof value.valueOf == "function" ? value.valueOf() : value;
                    value = isObject3(other2) ? other2 + "" : other2;
                  }
                  if (typeof value != "string") {
                    return value === 0 ? value : +value;
                  }
                  value = value.replace(reTrim, "");
                  var isBinary2 = reIsBinary.test(value);
                  return isBinary2 || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary2 ? 2 : 8) : reIsBadHex.test(value) ? NAN2 : +value;
                }
                __name(toNumber2, "toNumber");
                module3.exports = throttle2;
              }
            ),
            /***/
            730: (
              /***/
              (module3, __unused_webpack_exports, __webpack_require__2) => {
                "use strict";
                var process51 = __webpack_require__2(169);
                module3.exports = LRUCache2;
                var Map2 = __webpack_require__2(307);
                var util4 = __webpack_require__2(82);
                var Yallist2 = __webpack_require__2(695);
                var hasSymbol = typeof Symbol === "function" && process51.env._nodeLRUCacheForceNoSymbol !== "1";
                var makeSymbol;
                if (hasSymbol) {
                  makeSymbol = /* @__PURE__ */ __name(function makeSymbol2(key) {
                    return Symbol(key);
                  }, "makeSymbol");
                } else {
                  makeSymbol = /* @__PURE__ */ __name(function makeSymbol2(key) {
                    return "_" + key;
                  }, "makeSymbol");
                }
                var MAX2 = makeSymbol("max");
                var LENGTH = makeSymbol("length");
                var LENGTH_CALCULATOR = makeSymbol("lengthCalculator");
                var ALLOW_STALE = makeSymbol("allowStale");
                var MAX_AGE = makeSymbol("maxAge");
                var DISPOSE = makeSymbol("dispose");
                var NO_DISPOSE_ON_SET = makeSymbol("noDisposeOnSet");
                var LRU_LIST = makeSymbol("lruList");
                var CACHE = makeSymbol("cache");
                function naiveLength() {
                  return 1;
                }
                __name(naiveLength, "naiveLength");
                function LRUCache2(options2) {
                  if (!(this instanceof LRUCache2)) {
                    return new LRUCache2(options2);
                  }
                  if (typeof options2 === "number") {
                    options2 = {
                      max: options2
                    };
                  }
                  if (!options2) {
                    options2 = {};
                  }
                  var max = this[MAX2] = options2.max;
                  if (!max || !(typeof max === "number") || max <= 0) {
                    this[MAX2] = Infinity;
                  }
                  var lc = options2.length || naiveLength;
                  if (typeof lc !== "function") {
                    lc = naiveLength;
                  }
                  this[LENGTH_CALCULATOR] = lc;
                  this[ALLOW_STALE] = options2.stale || false;
                  this[MAX_AGE] = options2.maxAge || 0;
                  this[DISPOSE] = options2.dispose;
                  this[NO_DISPOSE_ON_SET] = options2.noDisposeOnSet || false;
                  this.reset();
                }
                __name(LRUCache2, "LRUCache");
                Object.defineProperty(LRUCache2.prototype, "max", {
                  set: /* @__PURE__ */ __name(function set(mL) {
                    if (!mL || !(typeof mL === "number") || mL <= 0) {
                      mL = Infinity;
                    }
                    this[MAX2] = mL;
                    trim(this);
                  }, "set"),
                  get: /* @__PURE__ */ __name(function get4() {
                    return this[MAX2];
                  }, "get"),
                  enumerable: true
                });
                Object.defineProperty(LRUCache2.prototype, "allowStale", {
                  set: /* @__PURE__ */ __name(function set(allowStale) {
                    this[ALLOW_STALE] = !!allowStale;
                  }, "set"),
                  get: /* @__PURE__ */ __name(function get4() {
                    return this[ALLOW_STALE];
                  }, "get"),
                  enumerable: true
                });
                Object.defineProperty(LRUCache2.prototype, "maxAge", {
                  set: /* @__PURE__ */ __name(function set(mA) {
                    if (!mA || !(typeof mA === "number") || mA < 0) {
                      mA = 0;
                    }
                    this[MAX_AGE] = mA;
                    trim(this);
                  }, "set"),
                  get: /* @__PURE__ */ __name(function get4() {
                    return this[MAX_AGE];
                  }, "get"),
                  enumerable: true
                });
                Object.defineProperty(LRUCache2.prototype, "lengthCalculator", {
                  set: /* @__PURE__ */ __name(function set(lC) {
                    if (typeof lC !== "function") {
                      lC = naiveLength;
                    }
                    if (lC !== this[LENGTH_CALCULATOR]) {
                      this[LENGTH_CALCULATOR] = lC;
                      this[LENGTH] = 0;
                      this[LRU_LIST].forEach(function(hit) {
                        hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);
                        this[LENGTH] += hit.length;
                      }, this);
                    }
                    trim(this);
                  }, "set"),
                  get: /* @__PURE__ */ __name(function get4() {
                    return this[LENGTH_CALCULATOR];
                  }, "get"),
                  enumerable: true
                });
                Object.defineProperty(LRUCache2.prototype, "length", {
                  get: /* @__PURE__ */ __name(function get4() {
                    return this[LENGTH];
                  }, "get"),
                  enumerable: true
                });
                Object.defineProperty(LRUCache2.prototype, "itemCount", {
                  get: /* @__PURE__ */ __name(function get4() {
                    return this[LRU_LIST].length;
                  }, "get"),
                  enumerable: true
                });
                LRUCache2.prototype.rforEach = function(fn, thisp) {
                  thisp = thisp || this;
                  for (var walker = this[LRU_LIST].tail; walker !== null; ) {
                    var prev = walker.prev;
                    forEachStep(this, fn, walker, thisp);
                    walker = prev;
                  }
                };
                function forEachStep(self2, fn, node, thisp) {
                  var hit = node.value;
                  if (isStale(self2, hit)) {
                    del(self2, node);
                    if (!self2[ALLOW_STALE]) {
                      hit = void 0;
                    }
                  }
                  if (hit) {
                    fn.call(thisp, hit.value, hit.key, self2);
                  }
                }
                __name(forEachStep, "forEachStep");
                LRUCache2.prototype.forEach = function(fn, thisp) {
                  thisp = thisp || this;
                  for (var walker = this[LRU_LIST].head; walker !== null; ) {
                    var next = walker.next;
                    forEachStep(this, fn, walker, thisp);
                    walker = next;
                  }
                };
                LRUCache2.prototype.keys = function() {
                  return this[LRU_LIST].toArray().map(function(k) {
                    return k.key;
                  }, this);
                };
                LRUCache2.prototype.values = function() {
                  return this[LRU_LIST].toArray().map(function(k) {
                    return k.value;
                  }, this);
                };
                LRUCache2.prototype.reset = function() {
                  if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) {
                    this[LRU_LIST].forEach(function(hit) {
                      this[DISPOSE](hit.key, hit.value);
                    }, this);
                  }
                  this[CACHE] = new Map2();
                  this[LRU_LIST] = new Yallist2();
                  this[LENGTH] = 0;
                };
                LRUCache2.prototype.dump = function() {
                  return this[LRU_LIST].map(function(hit) {
                    if (!isStale(this, hit)) {
                      return {
                        k: hit.key,
                        v: hit.value,
                        e: hit.now + (hit.maxAge || 0)
                      };
                    }
                  }, this).toArray().filter(function(h) {
                    return h;
                  });
                };
                LRUCache2.prototype.dumpLru = function() {
                  return this[LRU_LIST];
                };
                LRUCache2.prototype.inspect = function(n2, opts) {
                  var str2 = "LRUCache {";
                  var extras = false;
                  var as = this[ALLOW_STALE];
                  if (as) {
                    str2 += "\n  allowStale: true";
                    extras = true;
                  }
                  var max = this[MAX2];
                  if (max && max !== Infinity) {
                    if (extras) {
                      str2 += ",";
                    }
                    str2 += "\n  max: " + util4.inspect(max, opts);
                    extras = true;
                  }
                  var maxAge = this[MAX_AGE];
                  if (maxAge) {
                    if (extras) {
                      str2 += ",";
                    }
                    str2 += "\n  maxAge: " + util4.inspect(maxAge, opts);
                    extras = true;
                  }
                  var lc = this[LENGTH_CALCULATOR];
                  if (lc && lc !== naiveLength) {
                    if (extras) {
                      str2 += ",";
                    }
                    str2 += "\n  length: " + util4.inspect(this[LENGTH], opts);
                    extras = true;
                  }
                  var didFirst = false;
                  this[LRU_LIST].forEach(function(item) {
                    if (didFirst) {
                      str2 += ",\n  ";
                    } else {
                      if (extras) {
                        str2 += ",\n";
                      }
                      didFirst = true;
                      str2 += "\n  ";
                    }
                    var key = util4.inspect(item.key).split("\n").join("\n  ");
                    var val = {
                      value: item.value
                    };
                    if (item.maxAge !== maxAge) {
                      val.maxAge = item.maxAge;
                    }
                    if (lc !== naiveLength) {
                      val.length = item.length;
                    }
                    if (isStale(this, item)) {
                      val.stale = true;
                    }
                    val = util4.inspect(val, opts).split("\n").join("\n  ");
                    str2 += key + " => " + val;
                  });
                  if (didFirst || extras) {
                    str2 += "\n";
                  }
                  str2 += "}";
                  return str2;
                };
                LRUCache2.prototype.set = function(key, value, maxAge) {
                  maxAge = maxAge || this[MAX_AGE];
                  var now = maxAge ? Date.now() : 0;
                  var len = this[LENGTH_CALCULATOR](value, key);
                  if (this[CACHE].has(key)) {
                    if (len > this[MAX2]) {
                      del(this, this[CACHE].get(key));
                      return false;
                    }
                    var node = this[CACHE].get(key);
                    var item = node.value;
                    if (this[DISPOSE]) {
                      if (!this[NO_DISPOSE_ON_SET]) {
                        this[DISPOSE](key, item.value);
                      }
                    }
                    item.now = now;
                    item.maxAge = maxAge;
                    item.value = value;
                    this[LENGTH] += len - item.length;
                    item.length = len;
                    this.get(key);
                    trim(this);
                    return true;
                  }
                  var hit = new Entry(key, value, len, now, maxAge);
                  if (hit.length > this[MAX2]) {
                    if (this[DISPOSE]) {
                      this[DISPOSE](key, value);
                    }
                    return false;
                  }
                  this[LENGTH] += hit.length;
                  this[LRU_LIST].unshift(hit);
                  this[CACHE].set(key, this[LRU_LIST].head);
                  trim(this);
                  return true;
                };
                LRUCache2.prototype.has = function(key) {
                  if (!this[CACHE].has(key)) return false;
                  var hit = this[CACHE].get(key).value;
                  if (isStale(this, hit)) {
                    return false;
                  }
                  return true;
                };
                LRUCache2.prototype.get = function(key) {
                  return get3(this, key, true);
                };
                LRUCache2.prototype.peek = function(key) {
                  return get3(this, key, false);
                };
                LRUCache2.prototype.pop = function() {
                  var node = this[LRU_LIST].tail;
                  if (!node) return null;
                  del(this, node);
                  return node.value;
                };
                LRUCache2.prototype.del = function(key) {
                  del(this, this[CACHE].get(key));
                };
                LRUCache2.prototype.load = function(arr) {
                  this.reset();
                  var now = Date.now();
                  for (var l2 = arr.length - 1; l2 >= 0; l2--) {
                    var hit = arr[l2];
                    var expiresAt = hit.e || 0;
                    if (expiresAt === 0) {
                      this.set(hit.k, hit.v);
                    } else {
                      var maxAge = expiresAt - now;
                      if (maxAge > 0) {
                        this.set(hit.k, hit.v, maxAge);
                      }
                    }
                  }
                };
                LRUCache2.prototype.prune = function() {
                  var self2 = this;
                  this[CACHE].forEach(function(value, key) {
                    get3(self2, key, false);
                  });
                };
                function get3(self2, key, doUse) {
                  var node = self2[CACHE].get(key);
                  if (node) {
                    var hit = node.value;
                    if (isStale(self2, hit)) {
                      del(self2, node);
                      if (!self2[ALLOW_STALE]) hit = void 0;
                    } else {
                      if (doUse) {
                        self2[LRU_LIST].unshiftNode(node);
                      }
                    }
                    if (hit) hit = hit.value;
                  }
                  return hit;
                }
                __name(get3, "get");
                function isStale(self2, hit) {
                  if (!hit || !hit.maxAge && !self2[MAX_AGE]) {
                    return false;
                  }
                  var stale = false;
                  var diff4 = Date.now() - hit.now;
                  if (hit.maxAge) {
                    stale = diff4 > hit.maxAge;
                  } else {
                    stale = self2[MAX_AGE] && diff4 > self2[MAX_AGE];
                  }
                  return stale;
                }
                __name(isStale, "isStale");
                function trim(self2) {
                  if (self2[LENGTH] > self2[MAX2]) {
                    for (var walker = self2[LRU_LIST].tail; self2[LENGTH] > self2[MAX2] && walker !== null; ) {
                      var prev = walker.prev;
                      del(self2, walker);
                      walker = prev;
                    }
                  }
                }
                __name(trim, "trim");
                function del(self2, node) {
                  if (node) {
                    var hit = node.value;
                    if (self2[DISPOSE]) {
                      self2[DISPOSE](hit.key, hit.value);
                    }
                    self2[LENGTH] -= hit.length;
                    self2[CACHE].delete(hit.key);
                    self2[LRU_LIST].removeNode(node);
                  }
                }
                __name(del, "del");
                function Entry(key, value, length, now, maxAge) {
                  this.key = key;
                  this.value = value;
                  this.length = length;
                  this.now = now;
                  this.maxAge = maxAge || 0;
                }
                __name(Entry, "Entry");
              }
            ),
            /***/
            169: (
              /***/
              (module3) => {
                var process51 = module3.exports = {};
                var cachedSetTimeout;
                var cachedClearTimeout;
                function defaultSetTimout() {
                  throw new Error("setTimeout has not been defined");
                }
                __name(defaultSetTimout, "defaultSetTimout");
                function defaultClearTimeout() {
                  throw new Error("clearTimeout has not been defined");
                }
                __name(defaultClearTimeout, "defaultClearTimeout");
                (function() {
                  try {
                    if (typeof setTimeout === "function") {
                      cachedSetTimeout = setTimeout;
                    } else {
                      cachedSetTimeout = defaultSetTimout;
                    }
                  } catch (e2) {
                    cachedSetTimeout = defaultSetTimout;
                  }
                  try {
                    if (typeof clearTimeout === "function") {
                      cachedClearTimeout = clearTimeout;
                    } else {
                      cachedClearTimeout = defaultClearTimeout;
                    }
                  } catch (e2) {
                    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 (e2) {
                    try {
                      return cachedSetTimeout.call(null, fun, 0);
                    } catch (e3) {
                      return cachedSetTimeout.call(this, fun, 0);
                    }
                  }
                }
                __name(runTimeout, "runTimeout");
                function runClearTimeout(marker) {
                  if (cachedClearTimeout === clearTimeout) {
                    return clearTimeout(marker);
                  }
                  if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
                    cachedClearTimeout = clearTimeout;
                    return clearTimeout(marker);
                  }
                  try {
                    return cachedClearTimeout(marker);
                  } catch (e2) {
                    try {
                      return cachedClearTimeout.call(null, marker);
                    } catch (e3) {
                      return cachedClearTimeout.call(this, marker);
                    }
                  }
                }
                __name(runClearTimeout, "runClearTimeout");
                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();
                  }
                }
                __name(cleanUpNextTick, "cleanUpNextTick");
                function drainQueue() {
                  if (draining) {
                    return;
                  }
                  var timeout2 = runTimeout(cleanUpNextTick);
                  draining = true;
                  var len = queue.length;
                  while (len) {
                    currentQueue = queue;
                    queue = [];
                    while (++queueIndex < len) {
                      if (currentQueue) {
                        currentQueue[queueIndex].run();
                      }
                    }
                    queueIndex = -1;
                    len = queue.length;
                  }
                  currentQueue = null;
                  draining = false;
                  runClearTimeout(timeout2);
                }
                __name(drainQueue, "drainQueue");
                process51.nextTick = function(fun) {
                  var args = new Array(arguments.length - 1);
                  if (arguments.length > 1) {
                    for (var i = 1; i < arguments.length; i++) {
                      args[i - 1] = arguments[i];
                    }
                  }
                  queue.push(new Item(fun, args));
                  if (queue.length === 1 && !draining) {
                    runTimeout(drainQueue);
                  }
                };
                function Item(fun, array) {
                  this.fun = fun;
                  this.array = array;
                }
                __name(Item, "Item");
                Item.prototype.run = function() {
                  this.fun.apply(null, this.array);
                };
                process51.title = "browser";
                process51.browser = true;
                process51.env = {};
                process51.argv = [];
                process51.version = "";
                process51.versions = {};
                function noop6() {
                }
                __name(noop6, "noop");
                process51.on = noop6;
                process51.addListener = noop6;
                process51.once = noop6;
                process51.off = noop6;
                process51.removeListener = noop6;
                process51.removeAllListeners = noop6;
                process51.emit = noop6;
                process51.prependListener = noop6;
                process51.prependOnceListener = noop6;
                process51.listeners = function(name3) {
                  return [];
                };
                process51.binding = function(name3) {
                  throw new Error("process.binding is not supported");
                };
                process51.cwd = function() {
                  return "/";
                };
                process51.chdir = function(dir) {
                  throw new Error("process.chdir is not supported");
                };
                process51.umask = function() {
                  return 0;
                };
              }
            ),
            /***/
            307: (
              /***/
              (module3, __unused_webpack_exports, __webpack_require__2) => {
                var process51 = __webpack_require__2(169);
                if (process51.env.npm_package_name === "pseudomap" && process51.env.npm_lifecycle_script === "test") process51.env.TEST_PSEUDOMAP = "true";
                if (typeof Map === "function" && !process51.env.TEST_PSEUDOMAP) {
                  module3.exports = Map;
                } else {
                  module3.exports = __webpack_require__2(761);
                }
              }
            ),
            /***/
            761: (
              /***/
              (module3) => {
                var hasOwnProperty2 = Object.prototype.hasOwnProperty;
                module3.exports = PseudoMap;
                function PseudoMap(set2) {
                  if (!(this instanceof PseudoMap))
                    throw new TypeError("Constructor PseudoMap requires 'new'");
                  this.clear();
                  if (set2) {
                    if (set2 instanceof PseudoMap || typeof Map === "function" && set2 instanceof Map) set2.forEach(function(value, key) {
                      this.set(key, value);
                    }, this);
                    else if (Array.isArray(set2)) set2.forEach(function(kv) {
                      this.set(kv[0], kv[1]);
                    }, this);
                    else throw new TypeError("invalid argument");
                  }
                }
                __name(PseudoMap, "PseudoMap");
                PseudoMap.prototype.forEach = function(fn, thisp) {
                  thisp = thisp || this;
                  Object.keys(this._data).forEach(function(k) {
                    if (k !== "size") fn.call(thisp, this._data[k].value, this._data[k].key);
                  }, this);
                };
                PseudoMap.prototype.has = function(k) {
                  return !!find(this._data, k);
                };
                PseudoMap.prototype.get = function(k) {
                  var res = find(this._data, k);
                  return res && res.value;
                };
                PseudoMap.prototype.set = function(k, v) {
                  set(this._data, k, v);
                };
                PseudoMap.prototype.delete = function(k) {
                  var res = find(this._data, k);
                  if (res) {
                    delete this._data[res._index];
                    this._data.size--;
                  }
                };
                PseudoMap.prototype.clear = function() {
                  var data = /* @__PURE__ */ Object.create(null);
                  data.size = 0;
                  Object.defineProperty(this, "_data", {
                    value: data,
                    enumerable: false,
                    configurable: true,
                    writable: false
                  });
                };
                Object.defineProperty(PseudoMap.prototype, "size", {
                  get: /* @__PURE__ */ __name(function get3() {
                    return this._data.size;
                  }, "get"),
                  set: /* @__PURE__ */ __name(function set2(n2) {
                  }, "set"),
                  enumerable: true,
                  configurable: true
                });
                PseudoMap.prototype.values = PseudoMap.prototype.keys = PseudoMap.prototype.entries = function() {
                  throw new Error("iterators are not implemented in this version");
                };
                function same(a, b) {
                  return a === b || a !== a && b !== b;
                }
                __name(same, "same");
                function Entry(k, v, i) {
                  this.key = k;
                  this.value = v;
                  this._index = i;
                }
                __name(Entry, "Entry");
                function find(data, k) {
                  for (var i = 0, s2 = "_" + k, key = s2; hasOwnProperty2.call(data, key); key = s2 + i++) {
                    if (same(data[key].key, k)) return data[key];
                  }
                }
                __name(find, "find");
                function set(data, k, v) {
                  for (var i = 0, s2 = "_" + k, key = s2; hasOwnProperty2.call(data, key); key = s2 + i++) {
                    if (same(data[key].key, k)) {
                      data[key].value = v;
                      return;
                    }
                  }
                  data.size++;
                  data[key] = new Entry(k, v, key);
                }
                __name(set, "set");
              }
            ),
            /***/
            430: (
              /***/
              function(module3, exports3) {
                var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;
                function _typeof2(obj) {
                  "@babel/helpers - typeof";
                  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                    _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                      return typeof obj2;
                    }, "_typeof");
                  } else {
                    _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                      return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                    }, "_typeof");
                  }
                  return _typeof2(obj);
                }
                __name(_typeof2, "_typeof");
                (function(root, factory) {
                  "use strict";
                  if (true) {
                    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = factory, __WEBPACK_AMD_DEFINE_RESULT__ = typeof __WEBPACK_AMD_DEFINE_FACTORY__ === "function" ? __WEBPACK_AMD_DEFINE_FACTORY__.apply(exports3, __WEBPACK_AMD_DEFINE_ARRAY__) : __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__ !== void 0 && (module3.exports = __WEBPACK_AMD_DEFINE_RESULT__));
                  } else {
                  }
                })(this, function() {
                  "use strict";
                  function _isNumber(n2) {
                    return !isNaN(parseFloat(n2)) && isFinite(n2);
                  }
                  __name(_isNumber, "_isNumber");
                  function _capitalize(str2) {
                    return str2.charAt(0).toUpperCase() + str2.substring(1);
                  }
                  __name(_capitalize, "_capitalize");
                  function _getter(p) {
                    return function() {
                      return this[p];
                    };
                  }
                  __name(_getter, "_getter");
                  var booleanProps = ["isConstructor", "isEval", "isNative", "isToplevel"];
                  var numericProps = ["columnNumber", "lineNumber"];
                  var stringProps = ["fileName", "functionName", "source"];
                  var arrayProps = ["args"];
                  var props = booleanProps.concat(numericProps, stringProps, arrayProps);
                  function StackFrame(obj) {
                    if (!obj) return;
                    for (var i2 = 0; i2 < props.length; i2++) {
                      if (obj[props[i2]] !== void 0) {
                        this["set" + _capitalize(props[i2])](obj[props[i2]]);
                      }
                    }
                  }
                  __name(StackFrame, "StackFrame");
                  StackFrame.prototype = {
                    getArgs: /* @__PURE__ */ __name(function getArgs() {
                      return this.args;
                    }, "getArgs"),
                    setArgs: /* @__PURE__ */ __name(function setArgs(v) {
                      if (Object.prototype.toString.call(v) !== "[object Array]") {
                        throw new TypeError("Args must be an Array");
                      }
                      this.args = v;
                    }, "setArgs"),
                    getEvalOrigin: /* @__PURE__ */ __name(function getEvalOrigin() {
                      return this.evalOrigin;
                    }, "getEvalOrigin"),
                    setEvalOrigin: /* @__PURE__ */ __name(function setEvalOrigin(v) {
                      if (v instanceof StackFrame) {
                        this.evalOrigin = v;
                      } else if (v instanceof Object) {
                        this.evalOrigin = new StackFrame(v);
                      } else {
                        throw new TypeError("Eval Origin must be an Object or StackFrame");
                      }
                    }, "setEvalOrigin"),
                    toString: /* @__PURE__ */ __name(function toString() {
                      var fileName = this.getFileName() || "";
                      var lineNumber = this.getLineNumber() || "";
                      var columnNumber = this.getColumnNumber() || "";
                      var functionName = this.getFunctionName() || "";
                      if (this.getIsEval()) {
                        if (fileName) {
                          return "[eval] (" + fileName + ":" + lineNumber + ":" + columnNumber + ")";
                        }
                        return "[eval]:" + lineNumber + ":" + columnNumber;
                      }
                      if (functionName) {
                        return functionName + " (" + fileName + ":" + lineNumber + ":" + columnNumber + ")";
                      }
                      return fileName + ":" + lineNumber + ":" + columnNumber;
                    }, "toString")
                  };
                  StackFrame.fromString = /* @__PURE__ */ __name(function StackFrame$$fromString(str2) {
                    var argsStartIndex = str2.indexOf("(");
                    var argsEndIndex = str2.lastIndexOf(")");
                    var functionName = str2.substring(0, argsStartIndex);
                    var args = str2.substring(argsStartIndex + 1, argsEndIndex).split(",");
                    var locationString = str2.substring(argsEndIndex + 1);
                    if (locationString.indexOf("@") === 0) {
                      var parts = /@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(locationString, "");
                      var fileName = parts[1];
                      var lineNumber = parts[2];
                      var columnNumber = parts[3];
                    }
                    return new StackFrame({
                      functionName,
                      args: args || void 0,
                      fileName,
                      lineNumber: lineNumber || void 0,
                      columnNumber: columnNumber || void 0
                    });
                  }, "StackFrame$$fromString");
                  for (var i = 0; i < booleanProps.length; i++) {
                    StackFrame.prototype["get" + _capitalize(booleanProps[i])] = _getter(booleanProps[i]);
                    StackFrame.prototype["set" + _capitalize(booleanProps[i])] = /* @__PURE__ */ function(p) {
                      return function(v) {
                        this[p] = Boolean(v);
                      };
                    }(booleanProps[i]);
                  }
                  for (var j = 0; j < numericProps.length; j++) {
                    StackFrame.prototype["get" + _capitalize(numericProps[j])] = _getter(numericProps[j]);
                    StackFrame.prototype["set" + _capitalize(numericProps[j])] = /* @__PURE__ */ function(p) {
                      return function(v) {
                        if (!_isNumber(v)) {
                          throw new TypeError(p + " must be a Number");
                        }
                        this[p] = Number(v);
                      };
                    }(numericProps[j]);
                  }
                  for (var k = 0; k < stringProps.length; k++) {
                    StackFrame.prototype["get" + _capitalize(stringProps[k])] = _getter(stringProps[k]);
                    StackFrame.prototype["set" + _capitalize(stringProps[k])] = /* @__PURE__ */ function(p) {
                      return function(v) {
                        this[p] = String(v);
                      };
                    }(stringProps[k]);
                  }
                  return StackFrame;
                });
              }
            ),
            /***/
            718: (
              /***/
              (module3) => {
                if (typeof Object.create === "function") {
                  module3.exports = /* @__PURE__ */ __name(function inherits(ctor, superCtor) {
                    ctor.super_ = superCtor;
                    ctor.prototype = Object.create(superCtor.prototype, {
                      constructor: {
                        value: ctor,
                        enumerable: false,
                        writable: true,
                        configurable: true
                      }
                    });
                  }, "inherits");
                } else {
                  module3.exports = /* @__PURE__ */ __name(function inherits(ctor, superCtor) {
                    ctor.super_ = superCtor;
                    var TempCtor = /* @__PURE__ */ __name(function TempCtor2() {
                    }, "TempCtor");
                    TempCtor.prototype = superCtor.prototype;
                    ctor.prototype = new TempCtor();
                    ctor.prototype.constructor = ctor;
                  }, "inherits");
                }
              }
            ),
            /***/
            715: (
              /***/
              (module3) => {
                function _typeof2(obj) {
                  "@babel/helpers - typeof";
                  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                    _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                      return typeof obj2;
                    }, "_typeof");
                  } else {
                    _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                      return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                    }, "_typeof");
                  }
                  return _typeof2(obj);
                }
                __name(_typeof2, "_typeof");
                module3.exports = /* @__PURE__ */ __name(function isBuffer(arg) {
                  return arg && _typeof2(arg) === "object" && typeof arg.copy === "function" && typeof arg.fill === "function" && typeof arg.readUInt8 === "function";
                }, "isBuffer");
              }
            ),
            /***/
            82: (
              /***/
              (__unused_webpack_module, exports3, __webpack_require__2) => {
                var process51 = __webpack_require__2(169);
                function _typeof2(obj) {
                  "@babel/helpers - typeof";
                  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                    _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                      return typeof obj2;
                    }, "_typeof");
                  } else {
                    _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                      return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                    }, "_typeof");
                  }
                  return _typeof2(obj);
                }
                __name(_typeof2, "_typeof");
                var formatRegExp = /%[sdj%]/g;
                exports3.format = function(f) {
                  if (!isString2(f)) {
                    var objects = [];
                    for (var i = 0; i < arguments.length; i++) {
                      objects.push(inspect2(arguments[i]));
                    }
                    return objects.join(" ");
                  }
                  var i = 1;
                  var args = arguments;
                  var len = args.length;
                  var str2 = String(f).replace(formatRegExp, function(x2) {
                    if (x2 === "%%") return "%";
                    if (i >= len) return x2;
                    switch (x2) {
                      case "%s":
                        return String(args[i++]);
                      case "%d":
                        return Number(args[i++]);
                      case "%j":
                        try {
                          return JSON.stringify(args[i++]);
                        } catch (_) {
                          return "[Circular]";
                        }
                      default:
                        return x2;
                    }
                  });
                  for (var x = args[i]; i < len; x = args[++i]) {
                    if (isNull(x) || !isObject3(x)) {
                      str2 += " " + x;
                    } else {
                      str2 += " " + inspect2(x);
                    }
                  }
                  return str2;
                };
                exports3.deprecate = function(fn, msg) {
                  if (isUndefined2(globalThis.process)) {
                    return function() {
                      return exports3.deprecate(fn, msg).apply(this, arguments);
                    };
                  }
                  if (process51.noDeprecation === true) {
                    return fn;
                  }
                  var warned2 = false;
                  function deprecated() {
                    if (!warned2) {
                      if (process51.throwDeprecation) {
                        throw new Error(msg);
                      } else if (process51.traceDeprecation) {
                        console.trace(msg);
                      } else {
                        console.error(msg);
                      }
                      warned2 = true;
                    }
                    return fn.apply(this, arguments);
                  }
                  __name(deprecated, "deprecated");
                  return deprecated;
                };
                var debugs = {};
                var debugEnviron;
                exports3.debuglog = function(set) {
                  if (isUndefined2(debugEnviron)) debugEnviron = process51.env.NODE_DEBUG || "";
                  set = set.toUpperCase();
                  if (!debugs[set]) {
                    if (new RegExp("\\b" + set + "\\b", "i").test(debugEnviron)) {
                      var pid = process51.pid;
                      debugs[set] = function() {
                        var msg = exports3.format.apply(exports3, arguments);
                        console.error("%s %d: %s", set, pid, msg);
                      };
                    } else {
                      debugs[set] = function() {
                      };
                    }
                  }
                  return debugs[set];
                };
                function inspect2(obj, opts) {
                  var ctx = {
                    seen: [],
                    stylize: stylizeNoColor
                  };
                  if (arguments.length >= 3) ctx.depth = arguments[2];
                  if (arguments.length >= 4) ctx.colors = arguments[3];
                  if (isBoolean2(opts)) {
                    ctx.showHidden = opts;
                  } else if (opts) {
                    exports3._extend(ctx, opts);
                  }
                  if (isUndefined2(ctx.showHidden)) ctx.showHidden = false;
                  if (isUndefined2(ctx.depth)) ctx.depth = 2;
                  if (isUndefined2(ctx.colors)) ctx.colors = false;
                  if (isUndefined2(ctx.customInspect)) ctx.customInspect = true;
                  if (ctx.colors) ctx.stylize = stylizeWithColor;
                  return formatValue2(ctx, obj, ctx.depth);
                }
                __name(inspect2, "inspect");
                exports3.inspect = inspect2;
                inspect2.colors = {
                  "bold": [1, 22],
                  "italic": [3, 23],
                  "underline": [4, 24],
                  "inverse": [7, 27],
                  "white": [37, 39],
                  "grey": [90, 39],
                  "black": [30, 39],
                  "blue": [34, 39],
                  "cyan": [36, 39],
                  "green": [32, 39],
                  "magenta": [35, 39],
                  "red": [31, 39],
                  "yellow": [33, 39]
                };
                inspect2.styles = {
                  "special": "cyan",
                  "number": "yellow",
                  "boolean": "yellow",
                  "undefined": "grey",
                  "null": "bold",
                  "string": "green",
                  "date": "magenta",
                  // "name": intentionally not styling
                  "regexp": "red"
                };
                function stylizeWithColor(str2, styleType) {
                  var style = inspect2.styles[styleType];
                  if (style) {
                    return "\x1B[" + inspect2.colors[style][0] + "m" + str2 + "\x1B[" + inspect2.colors[style][1] + "m";
                  } else {
                    return str2;
                  }
                }
                __name(stylizeWithColor, "stylizeWithColor");
                function stylizeNoColor(str2, styleType) {
                  return str2;
                }
                __name(stylizeNoColor, "stylizeNoColor");
                function arrayToHash(array) {
                  var hash = {};
                  array.forEach(function(val, idx) {
                    hash[val] = true;
                  });
                  return hash;
                }
                __name(arrayToHash, "arrayToHash");
                function formatValue2(ctx, value, recurseTimes) {
                  if (ctx.customInspect && value && isFunction3(value.inspect) && // Filter out the util module, it's inspect function is special
                  value.inspect !== exports3.inspect && // Also filter out any prototype objects using the circular check.
                  !(value.constructor && value.constructor.prototype === value)) {
                    var ret = value.inspect(recurseTimes, ctx);
                    if (!isString2(ret)) {
                      ret = formatValue2(ctx, ret, recurseTimes);
                    }
                    return ret;
                  }
                  var primitive = formatPrimitive(ctx, value);
                  if (primitive) {
                    return primitive;
                  }
                  var keys = Object.keys(value);
                  var visibleKeys = arrayToHash(keys);
                  if (ctx.showHidden) {
                    keys = Object.getOwnPropertyNames(value);
                  }
                  if (isError(value) && (keys.indexOf("message") >= 0 || keys.indexOf("description") >= 0)) {
                    return formatError(value);
                  }
                  if (keys.length === 0) {
                    if (isFunction3(value)) {
                      var name3 = value.name ? ": " + value.name : "";
                      return ctx.stylize("[Function" + name3 + "]", "special");
                    }
                    if (isRegExp(value)) {
                      return ctx.stylize(RegExp.prototype.toString.call(value), "regexp");
                    }
                    if (isDate(value)) {
                      return ctx.stylize(Date.prototype.toString.call(value), "date");
                    }
                    if (isError(value)) {
                      return formatError(value);
                    }
                  }
                  var base = "", array = false, braces = ["{", "}"];
                  if (isArray2(value)) {
                    array = true;
                    braces = ["[", "]"];
                  }
                  if (isFunction3(value)) {
                    var n2 = value.name ? ": " + value.name : "";
                    base = " [Function" + n2 + "]";
                  }
                  if (isRegExp(value)) {
                    base = " " + RegExp.prototype.toString.call(value);
                  }
                  if (isDate(value)) {
                    base = " " + Date.prototype.toUTCString.call(value);
                  }
                  if (isError(value)) {
                    base = " " + formatError(value);
                  }
                  if (keys.length === 0 && (!array || value.length == 0)) {
                    return braces[0] + base + braces[1];
                  }
                  if (recurseTimes < 0) {
                    if (isRegExp(value)) {
                      return ctx.stylize(RegExp.prototype.toString.call(value), "regexp");
                    } else {
                      return ctx.stylize("[Object]", "special");
                    }
                  }
                  ctx.seen.push(value);
                  var output;
                  if (array) {
                    output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
                  } else {
                    output = keys.map(function(key) {
                      return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
                    });
                  }
                  ctx.seen.pop();
                  return reduceToSingleString(output, base, braces);
                }
                __name(formatValue2, "formatValue");
                function formatPrimitive(ctx, value) {
                  if (isUndefined2(value)) return ctx.stylize("undefined", "undefined");
                  if (isString2(value)) {
                    var simple = "'" + JSON.stringify(value).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, '"') + "'";
                    return ctx.stylize(simple, "string");
                  }
                  if (isNumber3(value)) return ctx.stylize("" + value, "number");
                  if (isBoolean2(value)) return ctx.stylize("" + value, "boolean");
                  if (isNull(value)) return ctx.stylize("null", "null");
                }
                __name(formatPrimitive, "formatPrimitive");
                function formatError(value) {
                  return "[" + Error.prototype.toString.call(value) + "]";
                }
                __name(formatError, "formatError");
                function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
                  var output = [];
                  for (var i = 0, l2 = value.length; i < l2; ++i) {
                    if (hasOwnProperty2(value, String(i))) {
                      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true));
                    } else {
                      output.push("");
                    }
                  }
                  keys.forEach(function(key) {
                    if (!key.match(/^\d+$/)) {
                      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true));
                    }
                  });
                  return output;
                }
                __name(formatArray, "formatArray");
                function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
                  var name3, str2, desc2;
                  desc2 = Object.getOwnPropertyDescriptor(value, key) || {
                    value: value[key]
                  };
                  if (desc2.get) {
                    if (desc2.set) {
                      str2 = ctx.stylize("[Getter/Setter]", "special");
                    } else {
                      str2 = ctx.stylize("[Getter]", "special");
                    }
                  } else {
                    if (desc2.set) {
                      str2 = ctx.stylize("[Setter]", "special");
                    }
                  }
                  if (!hasOwnProperty2(visibleKeys, key)) {
                    name3 = "[" + key + "]";
                  }
                  if (!str2) {
                    if (ctx.seen.indexOf(desc2.value) < 0) {
                      if (isNull(recurseTimes)) {
                        str2 = formatValue2(ctx, desc2.value, null);
                      } else {
                        str2 = formatValue2(ctx, desc2.value, recurseTimes - 1);
                      }
                      if (str2.indexOf("\n") > -1) {
                        if (array) {
                          str2 = str2.split("\n").map(function(line) {
                            return "  " + line;
                          }).join("\n").substr(2);
                        } else {
                          str2 = "\n" + str2.split("\n").map(function(line) {
                            return "   " + line;
                          }).join("\n");
                        }
                      }
                    } else {
                      str2 = ctx.stylize("[Circular]", "special");
                    }
                  }
                  if (isUndefined2(name3)) {
                    if (array && key.match(/^\d+$/)) {
                      return str2;
                    }
                    name3 = JSON.stringify("" + key);
                    if (name3.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
                      name3 = name3.substr(1, name3.length - 2);
                      name3 = ctx.stylize(name3, "name");
                    } else {
                      name3 = name3.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'");
                      name3 = ctx.stylize(name3, "string");
                    }
                  }
                  return name3 + ": " + str2;
                }
                __name(formatProperty, "formatProperty");
                function reduceToSingleString(output, base, braces) {
                  var numLinesEst = 0;
                  var length = output.reduce(function(prev, cur) {
                    numLinesEst++;
                    if (cur.indexOf("\n") >= 0) numLinesEst++;
                    return prev + cur.replace(/\u001b\[\d\d?m/g, "").length + 1;
                  }, 0);
                  if (length > 60) {
                    return braces[0] + (base === "" ? "" : base + "\n ") + " " + output.join(",\n  ") + " " + braces[1];
                  }
                  return braces[0] + base + " " + output.join(", ") + " " + braces[1];
                }
                __name(reduceToSingleString, "reduceToSingleString");
                function isArray2(ar) {
                  return Array.isArray(ar);
                }
                __name(isArray2, "isArray");
                exports3.isArray = isArray2;
                function isBoolean2(arg) {
                  return typeof arg === "boolean";
                }
                __name(isBoolean2, "isBoolean");
                exports3.isBoolean = isBoolean2;
                function isNull(arg) {
                  return arg === null;
                }
                __name(isNull, "isNull");
                exports3.isNull = isNull;
                function isNullOrUndefined(arg) {
                  return arg == null;
                }
                __name(isNullOrUndefined, "isNullOrUndefined");
                exports3.isNullOrUndefined = isNullOrUndefined;
                function isNumber3(arg) {
                  return typeof arg === "number";
                }
                __name(isNumber3, "isNumber");
                exports3.isNumber = isNumber3;
                function isString2(arg) {
                  return typeof arg === "string";
                }
                __name(isString2, "isString");
                exports3.isString = isString2;
                function isSymbol(arg) {
                  return _typeof2(arg) === "symbol";
                }
                __name(isSymbol, "isSymbol");
                exports3.isSymbol = isSymbol;
                function isUndefined2(arg) {
                  return arg === void 0;
                }
                __name(isUndefined2, "isUndefined");
                exports3.isUndefined = isUndefined2;
                function isRegExp(re2) {
                  return isObject3(re2) && objectToString2(re2) === "[object RegExp]";
                }
                __name(isRegExp, "isRegExp");
                exports3.isRegExp = isRegExp;
                function isObject3(arg) {
                  return _typeof2(arg) === "object" && arg !== null;
                }
                __name(isObject3, "isObject");
                exports3.isObject = isObject3;
                function isDate(d) {
                  return isObject3(d) && objectToString2(d) === "[object Date]";
                }
                __name(isDate, "isDate");
                exports3.isDate = isDate;
                function isError(e2) {
                  return isObject3(e2) && (objectToString2(e2) === "[object Error]" || e2 instanceof Error);
                }
                __name(isError, "isError");
                exports3.isError = isError;
                function isFunction3(arg) {
                  return typeof arg === "function";
                }
                __name(isFunction3, "isFunction");
                exports3.isFunction = isFunction3;
                function isPrimitive(arg) {
                  return arg === null || typeof arg === "boolean" || typeof arg === "number" || typeof arg === "string" || _typeof2(arg) === "symbol" || // ES6 symbol
                  typeof arg === "undefined";
                }
                __name(isPrimitive, "isPrimitive");
                exports3.isPrimitive = isPrimitive;
                exports3.isBuffer = __webpack_require__2(715);
                function objectToString2(o2) {
                  return Object.prototype.toString.call(o2);
                }
                __name(objectToString2, "objectToString");
                function pad(n2) {
                  return n2 < 10 ? "0" + n2.toString(10) : n2.toString(10);
                }
                __name(pad, "pad");
                var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
                function timestamp() {
                  var d = /* @__PURE__ */ new Date();
                  var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(":");
                  return [d.getDate(), months[d.getMonth()], time].join(" ");
                }
                __name(timestamp, "timestamp");
                exports3.log = function() {
                  console.log("%s - %s", timestamp(), exports3.format.apply(exports3, arguments));
                };
                exports3.inherits = __webpack_require__2(718);
                exports3._extend = function(origin, add) {
                  if (!add || !isObject3(add)) return origin;
                  var keys = Object.keys(add);
                  var i = keys.length;
                  while (i--) {
                    origin[keys[i]] = add[keys[i]];
                  }
                  return origin;
                };
                function hasOwnProperty2(obj, prop) {
                  return Object.prototype.hasOwnProperty.call(obj, prop);
                }
                __name(hasOwnProperty2, "hasOwnProperty");
              }
            ),
            /***/
            695: (
              /***/
              (module3) => {
                module3.exports = Yallist2;
                Yallist2.Node = Node4;
                Yallist2.create = Yallist2;
                function Yallist2(list3) {
                  var self2 = this;
                  if (!(self2 instanceof Yallist2)) {
                    self2 = new Yallist2();
                  }
                  self2.tail = null;
                  self2.head = null;
                  self2.length = 0;
                  if (list3 && typeof list3.forEach === "function") {
                    list3.forEach(function(item) {
                      self2.push(item);
                    });
                  } else if (arguments.length > 0) {
                    for (var i = 0, l2 = arguments.length; i < l2; i++) {
                      self2.push(arguments[i]);
                    }
                  }
                  return self2;
                }
                __name(Yallist2, "Yallist");
                Yallist2.prototype.removeNode = function(node) {
                  if (node.list !== this) {
                    throw new Error("removing node which does not belong to this list");
                  }
                  var next = node.next;
                  var prev = node.prev;
                  if (next) {
                    next.prev = prev;
                  }
                  if (prev) {
                    prev.next = next;
                  }
                  if (node === this.head) {
                    this.head = next;
                  }
                  if (node === this.tail) {
                    this.tail = prev;
                  }
                  node.list.length--;
                  node.next = null;
                  node.prev = null;
                  node.list = null;
                };
                Yallist2.prototype.unshiftNode = function(node) {
                  if (node === this.head) {
                    return;
                  }
                  if (node.list) {
                    node.list.removeNode(node);
                  }
                  var head = this.head;
                  node.list = this;
                  node.next = head;
                  if (head) {
                    head.prev = node;
                  }
                  this.head = node;
                  if (!this.tail) {
                    this.tail = node;
                  }
                  this.length++;
                };
                Yallist2.prototype.pushNode = function(node) {
                  if (node === this.tail) {
                    return;
                  }
                  if (node.list) {
                    node.list.removeNode(node);
                  }
                  var tail = this.tail;
                  node.list = this;
                  node.prev = tail;
                  if (tail) {
                    tail.next = node;
                  }
                  this.tail = node;
                  if (!this.head) {
                    this.head = node;
                  }
                  this.length++;
                };
                Yallist2.prototype.push = function() {
                  for (var i = 0, l2 = arguments.length; i < l2; i++) {
                    push2(this, arguments[i]);
                  }
                  return this.length;
                };
                Yallist2.prototype.unshift = function() {
                  for (var i = 0, l2 = arguments.length; i < l2; i++) {
                    unshift2(this, arguments[i]);
                  }
                  return this.length;
                };
                Yallist2.prototype.pop = function() {
                  if (!this.tail) {
                    return void 0;
                  }
                  var res = this.tail.value;
                  this.tail = this.tail.prev;
                  if (this.tail) {
                    this.tail.next = null;
                  } else {
                    this.head = null;
                  }
                  this.length--;
                  return res;
                };
                Yallist2.prototype.shift = function() {
                  if (!this.head) {
                    return void 0;
                  }
                  var res = this.head.value;
                  this.head = this.head.next;
                  if (this.head) {
                    this.head.prev = null;
                  } else {
                    this.tail = null;
                  }
                  this.length--;
                  return res;
                };
                Yallist2.prototype.forEach = function(fn, thisp) {
                  thisp = thisp || this;
                  for (var walker = this.head, i = 0; walker !== null; i++) {
                    fn.call(thisp, walker.value, i, this);
                    walker = walker.next;
                  }
                };
                Yallist2.prototype.forEachReverse = function(fn, thisp) {
                  thisp = thisp || this;
                  for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
                    fn.call(thisp, walker.value, i, this);
                    walker = walker.prev;
                  }
                };
                Yallist2.prototype.get = function(n2) {
                  for (var i = 0, walker = this.head; walker !== null && i < n2; i++) {
                    walker = walker.next;
                  }
                  if (i === n2 && walker !== null) {
                    return walker.value;
                  }
                };
                Yallist2.prototype.getReverse = function(n2) {
                  for (var i = 0, walker = this.tail; walker !== null && i < n2; i++) {
                    walker = walker.prev;
                  }
                  if (i === n2 && walker !== null) {
                    return walker.value;
                  }
                };
                Yallist2.prototype.map = function(fn, thisp) {
                  thisp = thisp || this;
                  var res = new Yallist2();
                  for (var walker = this.head; walker !== null; ) {
                    res.push(fn.call(thisp, walker.value, this));
                    walker = walker.next;
                  }
                  return res;
                };
                Yallist2.prototype.mapReverse = function(fn, thisp) {
                  thisp = thisp || this;
                  var res = new Yallist2();
                  for (var walker = this.tail; walker !== null; ) {
                    res.push(fn.call(thisp, walker.value, this));
                    walker = walker.prev;
                  }
                  return res;
                };
                Yallist2.prototype.reduce = function(fn, initial) {
                  var acc;
                  var walker = this.head;
                  if (arguments.length > 1) {
                    acc = initial;
                  } else if (this.head) {
                    walker = this.head.next;
                    acc = this.head.value;
                  } else {
                    throw new TypeError("Reduce of empty list with no initial value");
                  }
                  for (var i = 0; walker !== null; i++) {
                    acc = fn(acc, walker.value, i);
                    walker = walker.next;
                  }
                  return acc;
                };
                Yallist2.prototype.reduceReverse = function(fn, initial) {
                  var acc;
                  var walker = this.tail;
                  if (arguments.length > 1) {
                    acc = initial;
                  } else if (this.tail) {
                    walker = this.tail.prev;
                    acc = this.tail.value;
                  } else {
                    throw new TypeError("Reduce of empty list with no initial value");
                  }
                  for (var i = this.length - 1; walker !== null; i--) {
                    acc = fn(acc, walker.value, i);
                    walker = walker.prev;
                  }
                  return acc;
                };
                Yallist2.prototype.toArray = function() {
                  var arr = new Array(this.length);
                  for (var i = 0, walker = this.head; walker !== null; i++) {
                    arr[i] = walker.value;
                    walker = walker.next;
                  }
                  return arr;
                };
                Yallist2.prototype.toArrayReverse = function() {
                  var arr = new Array(this.length);
                  for (var i = 0, walker = this.tail; walker !== null; i++) {
                    arr[i] = walker.value;
                    walker = walker.prev;
                  }
                  return arr;
                };
                Yallist2.prototype.slice = function(from, to) {
                  to = to || this.length;
                  if (to < 0) {
                    to += this.length;
                  }
                  from = from || 0;
                  if (from < 0) {
                    from += this.length;
                  }
                  var ret = new Yallist2();
                  if (to < from || to < 0) {
                    return ret;
                  }
                  if (from < 0) {
                    from = 0;
                  }
                  if (to > this.length) {
                    to = this.length;
                  }
                  for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
                    walker = walker.next;
                  }
                  for (; walker !== null && i < to; i++, walker = walker.next) {
                    ret.push(walker.value);
                  }
                  return ret;
                };
                Yallist2.prototype.sliceReverse = function(from, to) {
                  to = to || this.length;
                  if (to < 0) {
                    to += this.length;
                  }
                  from = from || 0;
                  if (from < 0) {
                    from += this.length;
                  }
                  var ret = new Yallist2();
                  if (to < from || to < 0) {
                    return ret;
                  }
                  if (from < 0) {
                    from = 0;
                  }
                  if (to > this.length) {
                    to = this.length;
                  }
                  for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
                    walker = walker.prev;
                  }
                  for (; walker !== null && i > from; i--, walker = walker.prev) {
                    ret.push(walker.value);
                  }
                  return ret;
                };
                Yallist2.prototype.reverse = function() {
                  var head = this.head;
                  var tail = this.tail;
                  for (var walker = head; walker !== null; walker = walker.prev) {
                    var p = walker.prev;
                    walker.prev = walker.next;
                    walker.next = p;
                  }
                  this.head = tail;
                  this.tail = head;
                  return this;
                };
                function push2(self2, item) {
                  self2.tail = new Node4(item, self2.tail, null, self2);
                  if (!self2.head) {
                    self2.head = self2.tail;
                  }
                  self2.length++;
                }
                __name(push2, "push");
                function unshift2(self2, item) {
                  self2.head = new Node4(item, null, self2.head, self2);
                  if (!self2.tail) {
                    self2.tail = self2.head;
                  }
                  self2.length++;
                }
                __name(unshift2, "unshift");
                function Node4(value, prev, next, list3) {
                  if (!(this instanceof Node4)) {
                    return new Node4(value, prev, next, list3);
                  }
                  this.list = list3;
                  this.value = value;
                  if (prev) {
                    prev.next = this;
                    this.prev = prev;
                  } else {
                    this.prev = null;
                  }
                  if (next) {
                    next.prev = this;
                    this.next = next;
                  } else {
                    this.next = null;
                  }
                }
                __name(Node4, "Node");
              }
            )
            /******/
          };
          var __webpack_module_cache__ = {};
          function __webpack_require__(moduleId) {
            var cachedModule = __webpack_module_cache__[moduleId];
            if (cachedModule !== void 0) {
              return cachedModule.exports;
            }
            var module3 = __webpack_module_cache__[moduleId] = {
              /******/
              // no module.id needed
              /******/
              // no module.loaded needed
              /******/
              exports: {}
              /******/
            };
            __webpack_modules__[moduleId].call(module3.exports, module3, module3.exports, __webpack_require__);
            return module3.exports;
          }
          __name(__webpack_require__, "__webpack_require__");
          (() => {
            __webpack_require__.n = (module3) => {
              var getter = module3 && module3.__esModule ? (
                /******/
                () => module3["default"]
              ) : (
                /******/
                () => module3
              );
              __webpack_require__.d(getter, { a: getter });
              return getter;
            };
          })();
          (() => {
            __webpack_require__.d = (exports3, definition) => {
              for (var key in definition) {
                if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports3, key)) {
                  Object.defineProperty(exports3, key, { enumerable: true, get: definition[key] });
                }
              }
            };
          })();
          (() => {
            __webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
          })();
          (() => {
            __webpack_require__.r = (exports3) => {
              if (typeof Symbol !== "undefined" && Symbol.toStringTag) {
                Object.defineProperty(exports3, Symbol.toStringTag, { value: "Module" });
              }
              Object.defineProperty(exports3, "__esModule", { value: true });
            };
          })();
          var __webpack_exports__ = {};
          (() => {
            "use strict";
            __webpack_require__.r(__webpack_exports__);
            __webpack_require__.d(__webpack_exports__, {
              "connectToDevTools": /* @__PURE__ */ __name(() => (
                /* binding */
                connectToDevTools
              ), "connectToDevTools")
            });
            ;
            function _classCallCheck(instance, Constructor) {
              if (!(instance instanceof Constructor)) {
                throw new TypeError("Cannot call a class as a function");
              }
            }
            __name(_classCallCheck, "_classCallCheck");
            function _defineProperties(target, props) {
              for (var i = 0; i < props.length; i++) {
                var descriptor2 = props[i];
                descriptor2.enumerable = descriptor2.enumerable || false;
                descriptor2.configurable = true;
                if ("value" in descriptor2) descriptor2.writable = true;
                Object.defineProperty(target, descriptor2.key, descriptor2);
              }
            }
            __name(_defineProperties, "_defineProperties");
            function _createClass(Constructor, protoProps, staticProps) {
              if (protoProps) _defineProperties(Constructor.prototype, protoProps);
              if (staticProps) _defineProperties(Constructor, staticProps);
              return Constructor;
            }
            __name(_createClass, "_createClass");
            function _defineProperty2(obj, key, value) {
              if (key in obj) {
                Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
              } else {
                obj[key] = value;
              }
              return obj;
            }
            __name(_defineProperty2, "_defineProperty");
            var EventEmitter10 = /* @__PURE__ */ function() {
              function EventEmitter11() {
                _classCallCheck(this, EventEmitter11);
                _defineProperty2(this, "listenersMap", /* @__PURE__ */ new Map());
              }
              __name(EventEmitter11, "EventEmitter");
              _createClass(EventEmitter11, [{
                key: "addListener",
                value: /* @__PURE__ */ __name(function addListener(event, listener) {
                  var listeners = this.listenersMap.get(event);
                  if (listeners === void 0) {
                    this.listenersMap.set(event, [listener]);
                  } else {
                    var index = listeners.indexOf(listener);
                    if (index < 0) {
                      listeners.push(listener);
                    }
                  }
                }, "addListener")
              }, {
                key: "emit",
                value: /* @__PURE__ */ __name(function emit(event) {
                  var listeners = this.listenersMap.get(event);
                  if (listeners !== void 0) {
                    for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                      args[_key - 1] = arguments[_key];
                    }
                    if (listeners.length === 1) {
                      var listener = listeners[0];
                      listener.apply(null, args);
                    } else {
                      var didThrow = false;
                      var caughtError = null;
                      var clonedListeners = Array.from(listeners);
                      for (var i = 0; i < clonedListeners.length; i++) {
                        var _listener = clonedListeners[i];
                        try {
                          _listener.apply(null, args);
                        } catch (error) {
                          if (caughtError === null) {
                            didThrow = true;
                            caughtError = error;
                          }
                        }
                      }
                      if (didThrow) {
                        throw caughtError;
                      }
                    }
                  }
                }, "emit")
              }, {
                key: "removeAllListeners",
                value: /* @__PURE__ */ __name(function removeAllListeners() {
                  this.listenersMap.clear();
                }, "removeAllListeners")
              }, {
                key: "removeListener",
                value: /* @__PURE__ */ __name(function removeListener(event, listener) {
                  var listeners = this.listenersMap.get(event);
                  if (listeners !== void 0) {
                    var index = listeners.indexOf(listener);
                    if (index >= 0) {
                      listeners.splice(index, 1);
                    }
                  }
                }, "removeListener")
              }]);
              return EventEmitter11;
            }();
            var lodash_throttle = __webpack_require__(172);
            var lodash_throttle_default = /* @__PURE__ */ __webpack_require__.n(lodash_throttle);
            ;
            var CHROME_WEBSTORE_EXTENSION_ID = "fmkadmapgofadopljbjfkapdkoienihi";
            var INTERNAL_EXTENSION_ID = "dnjnjgbfilfphmojnmhliehogmojhclc";
            var LOCAL_EXTENSION_ID = "ikiahnapldjmdmpkmfhjdjilojjhgcbf";
            var __DEBUG__ = false;
            var __PERFORMANCE_PROFILE__ = false;
            var TREE_OPERATION_ADD = 1;
            var TREE_OPERATION_REMOVE = 2;
            var TREE_OPERATION_REORDER_CHILDREN = 3;
            var TREE_OPERATION_UPDATE_TREE_BASE_DURATION = 4;
            var TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS = 5;
            var TREE_OPERATION_REMOVE_ROOT = 6;
            var TREE_OPERATION_SET_SUBTREE_MODE = 7;
            var PROFILING_FLAG_BASIC_SUPPORT = 1;
            var PROFILING_FLAG_TIMELINE_SUPPORT = 2;
            var LOCAL_STORAGE_DEFAULT_TAB_KEY = "React::DevTools::defaultTab";
            var constants_LOCAL_STORAGE_COMPONENT_FILTER_PREFERENCES_KEY = "React::DevTools::componentFilters";
            var SESSION_STORAGE_LAST_SELECTION_KEY = "React::DevTools::lastSelection";
            var constants_LOCAL_STORAGE_OPEN_IN_EDITOR_URL = "React::DevTools::openInEditorUrl";
            var LOCAL_STORAGE_OPEN_IN_EDITOR_URL_PRESET = "React::DevTools::openInEditorUrlPreset";
            var LOCAL_STORAGE_PARSE_HOOK_NAMES_KEY = "React::DevTools::parseHookNames";
            var SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY = "React::DevTools::recordChangeDescriptions";
            var SESSION_STORAGE_RELOAD_AND_PROFILE_KEY = "React::DevTools::reloadAndProfile";
            var constants_LOCAL_STORAGE_SHOULD_BREAK_ON_CONSOLE_ERRORS = "React::DevTools::breakOnConsoleErrors";
            var LOCAL_STORAGE_BROWSER_THEME = "React::DevTools::theme";
            var constants_LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY = "React::DevTools::appendComponentStack";
            var constants_LOCAL_STORAGE_SHOW_INLINE_WARNINGS_AND_ERRORS_KEY = "React::DevTools::showInlineWarningsAndErrors";
            var LOCAL_STORAGE_TRACE_UPDATES_ENABLED_KEY = "React::DevTools::traceUpdatesEnabled";
            var constants_LOCAL_STORAGE_HIDE_CONSOLE_LOGS_IN_STRICT_MODE = "React::DevTools::hideConsoleLogsInStrictMode";
            var LOCAL_STORAGE_SUPPORTS_PROFILING_KEY = "React::DevTools::supportsProfiling";
            var PROFILER_EXPORT_VERSION = 5;
            ;
            function storage_localStorageGetItem(key) {
              try {
                return localStorage.getItem(key);
              } catch (error) {
                return null;
              }
            }
            __name(storage_localStorageGetItem, "storage_localStorageGetItem");
            function localStorageRemoveItem(key) {
              try {
                localStorage.removeItem(key);
              } catch (error) {
              }
            }
            __name(localStorageRemoveItem, "localStorageRemoveItem");
            function storage_localStorageSetItem(key, value) {
              try {
                return localStorage.setItem(key, value);
              } catch (error) {
              }
            }
            __name(storage_localStorageSetItem, "storage_localStorageSetItem");
            function sessionStorageGetItem(key) {
              try {
                return sessionStorage.getItem(key);
              } catch (error) {
                return null;
              }
            }
            __name(sessionStorageGetItem, "sessionStorageGetItem");
            function sessionStorageRemoveItem(key) {
              try {
                sessionStorage.removeItem(key);
              } catch (error) {
              }
            }
            __name(sessionStorageRemoveItem, "sessionStorageRemoveItem");
            function sessionStorageSetItem(key, value) {
              try {
                return sessionStorage.setItem(key, value);
              } catch (error) {
              }
            }
            __name(sessionStorageSetItem, "sessionStorageSetItem");
            ;
            var simpleIsEqual = /* @__PURE__ */ __name(function simpleIsEqual2(a, b) {
              return a === b;
            }, "simpleIsEqual");
            function esm(resultFn) {
              var isEqual = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : simpleIsEqual;
              var lastThis = void 0;
              var lastArgs = [];
              var lastResult = void 0;
              var calledOnce = false;
              var isNewArgEqualToLast = /* @__PURE__ */ __name(function isNewArgEqualToLast2(newArg, index) {
                return isEqual(newArg, lastArgs[index]);
              }, "isNewArgEqualToLast");
              var result = /* @__PURE__ */ __name(function result2() {
                for (var _len = arguments.length, newArgs = Array(_len), _key = 0; _key < _len; _key++) {
                  newArgs[_key] = arguments[_key];
                }
                if (calledOnce && lastThis === this && newArgs.length === lastArgs.length && newArgs.every(isNewArgEqualToLast)) {
                  return lastResult;
                }
                calledOnce = true;
                lastThis = this;
                lastArgs = newArgs;
                lastResult = resultFn.apply(this, newArgs);
                return lastResult;
              }, "result");
              return result;
            }
            __name(esm, "esm");
            ;
            function getOwnerWindow(node) {
              if (!node.ownerDocument) {
                return null;
              }
              return node.ownerDocument.defaultView;
            }
            __name(getOwnerWindow, "getOwnerWindow");
            function getOwnerIframe(node) {
              var nodeWindow = getOwnerWindow(node);
              if (nodeWindow) {
                return nodeWindow.frameElement;
              }
              return null;
            }
            __name(getOwnerIframe, "getOwnerIframe");
            function getBoundingClientRectWithBorderOffset(node) {
              var dimensions = getElementDimensions(node);
              return mergeRectOffsets([node.getBoundingClientRect(), {
                top: dimensions.borderTop,
                left: dimensions.borderLeft,
                bottom: dimensions.borderBottom,
                right: dimensions.borderRight,
                // This width and height won't get used by mergeRectOffsets (since this
                // is not the first rect in the array), but we set them so that this
                // object type checks as a ClientRect.
                width: 0,
                height: 0
              }]);
            }
            __name(getBoundingClientRectWithBorderOffset, "getBoundingClientRectWithBorderOffset");
            function mergeRectOffsets(rects) {
              return rects.reduce(function(previousRect, rect) {
                if (previousRect == null) {
                  return rect;
                }
                return {
                  top: previousRect.top + rect.top,
                  left: previousRect.left + rect.left,
                  width: previousRect.width,
                  height: previousRect.height,
                  bottom: previousRect.bottom + rect.bottom,
                  right: previousRect.right + rect.right
                };
              });
            }
            __name(mergeRectOffsets, "mergeRectOffsets");
            function getNestedBoundingClientRect(node, boundaryWindow) {
              var ownerIframe = getOwnerIframe(node);
              if (ownerIframe && ownerIframe !== boundaryWindow) {
                var rects = [node.getBoundingClientRect()];
                var currentIframe = ownerIframe;
                var onlyOneMore = false;
                while (currentIframe) {
                  var rect = getBoundingClientRectWithBorderOffset(currentIframe);
                  rects.push(rect);
                  currentIframe = getOwnerIframe(currentIframe);
                  if (onlyOneMore) {
                    break;
                  }
                  if (currentIframe && getOwnerWindow(currentIframe) === boundaryWindow) {
                    onlyOneMore = true;
                  }
                }
                return mergeRectOffsets(rects);
              } else {
                return node.getBoundingClientRect();
              }
            }
            __name(getNestedBoundingClientRect, "getNestedBoundingClientRect");
            function getElementDimensions(domElement) {
              var calculatedStyle = window.getComputedStyle(domElement);
              return {
                borderLeft: parseInt(calculatedStyle.borderLeftWidth, 10),
                borderRight: parseInt(calculatedStyle.borderRightWidth, 10),
                borderTop: parseInt(calculatedStyle.borderTopWidth, 10),
                borderBottom: parseInt(calculatedStyle.borderBottomWidth, 10),
                marginLeft: parseInt(calculatedStyle.marginLeft, 10),
                marginRight: parseInt(calculatedStyle.marginRight, 10),
                marginTop: parseInt(calculatedStyle.marginTop, 10),
                marginBottom: parseInt(calculatedStyle.marginBottom, 10),
                paddingLeft: parseInt(calculatedStyle.paddingLeft, 10),
                paddingRight: parseInt(calculatedStyle.paddingRight, 10),
                paddingTop: parseInt(calculatedStyle.paddingTop, 10),
                paddingBottom: parseInt(calculatedStyle.paddingBottom, 10)
              };
            }
            __name(getElementDimensions, "getElementDimensions");
            ;
            function Overlay_classCallCheck(instance, Constructor) {
              if (!(instance instanceof Constructor)) {
                throw new TypeError("Cannot call a class as a function");
              }
            }
            __name(Overlay_classCallCheck, "Overlay_classCallCheck");
            function Overlay_defineProperties(target, props) {
              for (var i = 0; i < props.length; i++) {
                var descriptor2 = props[i];
                descriptor2.enumerable = descriptor2.enumerable || false;
                descriptor2.configurable = true;
                if ("value" in descriptor2) descriptor2.writable = true;
                Object.defineProperty(target, descriptor2.key, descriptor2);
              }
            }
            __name(Overlay_defineProperties, "Overlay_defineProperties");
            function Overlay_createClass(Constructor, protoProps, staticProps) {
              if (protoProps) Overlay_defineProperties(Constructor.prototype, protoProps);
              if (staticProps) Overlay_defineProperties(Constructor, staticProps);
              return Constructor;
            }
            __name(Overlay_createClass, "Overlay_createClass");
            var Overlay_assign = Object.assign;
            var OverlayRect = /* @__PURE__ */ function() {
              function OverlayRect2(doc, container) {
                Overlay_classCallCheck(this, OverlayRect2);
                this.node = doc.createElement("div");
                this.border = doc.createElement("div");
                this.padding = doc.createElement("div");
                this.content = doc.createElement("div");
                this.border.style.borderColor = overlayStyles.border;
                this.padding.style.borderColor = overlayStyles.padding;
                this.content.style.backgroundColor = overlayStyles.background;
                Overlay_assign(this.node.style, {
                  borderColor: overlayStyles.margin,
                  pointerEvents: "none",
                  position: "fixed"
                });
                this.node.style.zIndex = "10000000";
                this.node.appendChild(this.border);
                this.border.appendChild(this.padding);
                this.padding.appendChild(this.content);
                container.appendChild(this.node);
              }
              __name(OverlayRect2, "OverlayRect");
              Overlay_createClass(OverlayRect2, [{
                key: "remove",
                value: /* @__PURE__ */ __name(function remove2() {
                  if (this.node.parentNode) {
                    this.node.parentNode.removeChild(this.node);
                  }
                }, "remove")
              }, {
                key: "update",
                value: /* @__PURE__ */ __name(function update2(box, dims) {
                  boxWrap(dims, "margin", this.node);
                  boxWrap(dims, "border", this.border);
                  boxWrap(dims, "padding", this.padding);
                  Overlay_assign(this.content.style, {
                    height: box.height - dims.borderTop - dims.borderBottom - dims.paddingTop - dims.paddingBottom + "px",
                    width: box.width - dims.borderLeft - dims.borderRight - dims.paddingLeft - dims.paddingRight + "px"
                  });
                  Overlay_assign(this.node.style, {
                    top: box.top - dims.marginTop + "px",
                    left: box.left - dims.marginLeft + "px"
                  });
                }, "update")
              }]);
              return OverlayRect2;
            }();
            var OverlayTip = /* @__PURE__ */ function() {
              function OverlayTip2(doc, container) {
                Overlay_classCallCheck(this, OverlayTip2);
                this.tip = doc.createElement("div");
                Overlay_assign(this.tip.style, {
                  display: "flex",
                  flexFlow: "row nowrap",
                  backgroundColor: "#333740",
                  borderRadius: "2px",
                  fontFamily: '"SFMono-Regular", Consolas, "Liberation Mono", Menlo, Courier, monospace',
                  fontWeight: "bold",
                  padding: "3px 5px",
                  pointerEvents: "none",
                  position: "fixed",
                  fontSize: "12px",
                  whiteSpace: "nowrap"
                });
                this.nameSpan = doc.createElement("span");
                this.tip.appendChild(this.nameSpan);
                Overlay_assign(this.nameSpan.style, {
                  color: "#ee78e6",
                  borderRight: "1px solid #aaaaaa",
                  paddingRight: "0.5rem",
                  marginRight: "0.5rem"
                });
                this.dimSpan = doc.createElement("span");
                this.tip.appendChild(this.dimSpan);
                Overlay_assign(this.dimSpan.style, {
                  color: "#d7d7d7"
                });
                this.tip.style.zIndex = "10000000";
                container.appendChild(this.tip);
              }
              __name(OverlayTip2, "OverlayTip");
              Overlay_createClass(OverlayTip2, [{
                key: "remove",
                value: /* @__PURE__ */ __name(function remove2() {
                  if (this.tip.parentNode) {
                    this.tip.parentNode.removeChild(this.tip);
                  }
                }, "remove")
              }, {
                key: "updateText",
                value: /* @__PURE__ */ __name(function updateText(name3, width, height) {
                  this.nameSpan.textContent = name3;
                  this.dimSpan.textContent = Math.round(width) + "px \xD7 " + Math.round(height) + "px";
                }, "updateText")
              }, {
                key: "updatePosition",
                value: /* @__PURE__ */ __name(function updatePosition(dims, bounds) {
                  var tipRect = this.tip.getBoundingClientRect();
                  var tipPos = findTipPos(dims, bounds, {
                    width: tipRect.width,
                    height: tipRect.height
                  });
                  Overlay_assign(this.tip.style, tipPos.style);
                }, "updatePosition")
              }]);
              return OverlayTip2;
            }();
            var Overlay = /* @__PURE__ */ function() {
              function Overlay2(agent2) {
                Overlay_classCallCheck(this, Overlay2);
                var currentWindow = window.__REACT_DEVTOOLS_TARGET_WINDOW__ || window;
                this.window = currentWindow;
                var tipBoundsWindow = window.__REACT_DEVTOOLS_TARGET_WINDOW__ || window;
                this.tipBoundsWindow = tipBoundsWindow;
                var doc = currentWindow.document;
                this.container = doc.createElement("div");
                this.container.style.zIndex = "10000000";
                this.tip = new OverlayTip(doc, this.container);
                this.rects = [];
                this.agent = agent2;
                doc.body.appendChild(this.container);
              }
              __name(Overlay2, "Overlay");
              Overlay_createClass(Overlay2, [{
                key: "remove",
                value: /* @__PURE__ */ __name(function remove2() {
                  this.tip.remove();
                  this.rects.forEach(function(rect) {
                    rect.remove();
                  });
                  this.rects.length = 0;
                  if (this.container.parentNode) {
                    this.container.parentNode.removeChild(this.container);
                  }
                }, "remove")
              }, {
                key: "inspect",
                value: /* @__PURE__ */ __name(function inspect2(nodes, name3) {
                  var _this = this;
                  var elements = nodes.filter(function(node2) {
                    return node2.nodeType === Node.ELEMENT_NODE;
                  });
                  while (this.rects.length > elements.length) {
                    var rect = this.rects.pop();
                    rect.remove();
                  }
                  if (elements.length === 0) {
                    return;
                  }
                  while (this.rects.length < elements.length) {
                    this.rects.push(new OverlayRect(this.window.document, this.container));
                  }
                  var outerBox = {
                    top: Number.POSITIVE_INFINITY,
                    right: Number.NEGATIVE_INFINITY,
                    bottom: Number.NEGATIVE_INFINITY,
                    left: Number.POSITIVE_INFINITY
                  };
                  elements.forEach(function(element, index) {
                    var box = getNestedBoundingClientRect(element, _this.window);
                    var dims = getElementDimensions(element);
                    outerBox.top = Math.min(outerBox.top, box.top - dims.marginTop);
                    outerBox.right = Math.max(outerBox.right, box.left + box.width + dims.marginRight);
                    outerBox.bottom = Math.max(outerBox.bottom, box.top + box.height + dims.marginBottom);
                    outerBox.left = Math.min(outerBox.left, box.left - dims.marginLeft);
                    var rect2 = _this.rects[index];
                    rect2.update(box, dims);
                  });
                  if (!name3) {
                    name3 = elements[0].nodeName.toLowerCase();
                    var node = elements[0];
                    var rendererInterface = this.agent.getBestMatchingRendererInterface(node);
                    if (rendererInterface) {
                      var id = rendererInterface.getFiberIDForNative(node, true);
                      if (id) {
                        var ownerName = rendererInterface.getDisplayNameForFiberID(id, true);
                        if (ownerName) {
                          name3 += " (in " + ownerName + ")";
                        }
                      }
                    }
                  }
                  this.tip.updateText(name3, outerBox.right - outerBox.left, outerBox.bottom - outerBox.top);
                  var tipBounds = getNestedBoundingClientRect(this.tipBoundsWindow.document.documentElement, this.window);
                  this.tip.updatePosition({
                    top: outerBox.top,
                    left: outerBox.left,
                    height: outerBox.bottom - outerBox.top,
                    width: outerBox.right - outerBox.left
                  }, {
                    top: tipBounds.top + this.tipBoundsWindow.scrollY,
                    left: tipBounds.left + this.tipBoundsWindow.scrollX,
                    height: this.tipBoundsWindow.innerHeight,
                    width: this.tipBoundsWindow.innerWidth
                  });
                }, "inspect")
              }]);
              return Overlay2;
            }();
            function findTipPos(dims, bounds, tipSize) {
              var tipHeight = Math.max(tipSize.height, 20);
              var tipWidth = Math.max(tipSize.width, 60);
              var margin = 5;
              var top2;
              if (dims.top + dims.height + tipHeight <= bounds.top + bounds.height) {
                if (dims.top + dims.height < bounds.top + 0) {
                  top2 = bounds.top + margin;
                } else {
                  top2 = dims.top + dims.height + margin;
                }
              } else if (dims.top - tipHeight <= bounds.top + bounds.height) {
                if (dims.top - tipHeight - margin < bounds.top + margin) {
                  top2 = bounds.top + margin;
                } else {
                  top2 = dims.top - tipHeight - margin;
                }
              } else {
                top2 = bounds.top + bounds.height - tipHeight - margin;
              }
              var left3 = dims.left + margin;
              if (dims.left < bounds.left) {
                left3 = bounds.left + margin;
              }
              if (dims.left + tipWidth > bounds.left + bounds.width) {
                left3 = bounds.left + bounds.width - tipWidth - margin;
              }
              top2 += "px";
              left3 += "px";
              return {
                style: {
                  top: top2,
                  left: left3
                }
              };
            }
            __name(findTipPos, "findTipPos");
            function boxWrap(dims, what, node) {
              Overlay_assign(node.style, {
                borderTopWidth: dims[what + "Top"] + "px",
                borderLeftWidth: dims[what + "Left"] + "px",
                borderRightWidth: dims[what + "Right"] + "px",
                borderBottomWidth: dims[what + "Bottom"] + "px",
                borderStyle: "solid"
              });
            }
            __name(boxWrap, "boxWrap");
            var overlayStyles = {
              background: "rgba(120, 170, 210, 0.7)",
              padding: "rgba(77, 200, 0, 0.3)",
              margin: "rgba(255, 155, 0, 0.3)",
              border: "rgba(255, 200, 50, 0.3)"
            };
            ;
            var SHOW_DURATION = 2e3;
            var timeoutID = null;
            var overlay = null;
            function hideOverlay(agent2) {
              if (window.document == null) {
                agent2.emit("hideNativeHighlight");
                return;
              }
              timeoutID = null;
              if (overlay !== null) {
                overlay.remove();
                overlay = null;
              }
            }
            __name(hideOverlay, "hideOverlay");
            function showOverlay(elements, componentName, agent2, hideAfterTimeout) {
              if (window.document == null) {
                if (elements != null && elements[0] != null) {
                  agent2.emit("showNativeHighlight", elements[0]);
                }
                return;
              }
              if (timeoutID !== null) {
                clearTimeout(timeoutID);
              }
              if (elements == null) {
                return;
              }
              if (overlay === null) {
                overlay = new Overlay(agent2);
              }
              overlay.inspect(elements, componentName);
              if (hideAfterTimeout) {
                timeoutID = setTimeout(function() {
                  return hideOverlay(agent2);
                }, SHOW_DURATION);
              }
            }
            __name(showOverlay, "showOverlay");
            ;
            var iframesListeningTo = /* @__PURE__ */ new Set();
            function setupHighlighter(bridge, agent2) {
              bridge.addListener("clearNativeElementHighlight", clearNativeElementHighlight);
              bridge.addListener("highlightNativeElement", highlightNativeElement);
              bridge.addListener("shutdown", stopInspectingNative);
              bridge.addListener("startInspectingNative", startInspectingNative);
              bridge.addListener("stopInspectingNative", stopInspectingNative);
              function startInspectingNative() {
                registerListenersOnWindow(window);
              }
              __name(startInspectingNative, "startInspectingNative");
              function registerListenersOnWindow(window2) {
                if (window2 && typeof window2.addEventListener === "function") {
                  window2.addEventListener("click", onClick, true);
                  window2.addEventListener("mousedown", onMouseEvent, true);
                  window2.addEventListener("mouseover", onMouseEvent, true);
                  window2.addEventListener("mouseup", onMouseEvent, true);
                  window2.addEventListener("pointerdown", onPointerDown, true);
                  window2.addEventListener("pointermove", onPointerMove, true);
                  window2.addEventListener("pointerup", onPointerUp, true);
                } else {
                  agent2.emit("startInspectingNative");
                }
              }
              __name(registerListenersOnWindow, "registerListenersOnWindow");
              function stopInspectingNative() {
                hideOverlay(agent2);
                removeListenersOnWindow(window);
                iframesListeningTo.forEach(function(frame) {
                  try {
                    removeListenersOnWindow(frame.contentWindow);
                  } catch (error) {
                  }
                });
                iframesListeningTo = /* @__PURE__ */ new Set();
              }
              __name(stopInspectingNative, "stopInspectingNative");
              function removeListenersOnWindow(window2) {
                if (window2 && typeof window2.removeEventListener === "function") {
                  window2.removeEventListener("click", onClick, true);
                  window2.removeEventListener("mousedown", onMouseEvent, true);
                  window2.removeEventListener("mouseover", onMouseEvent, true);
                  window2.removeEventListener("mouseup", onMouseEvent, true);
                  window2.removeEventListener("pointerdown", onPointerDown, true);
                  window2.removeEventListener("pointermove", onPointerMove, true);
                  window2.removeEventListener("pointerup", onPointerUp, true);
                } else {
                  agent2.emit("stopInspectingNative");
                }
              }
              __name(removeListenersOnWindow, "removeListenersOnWindow");
              function clearNativeElementHighlight() {
                hideOverlay(agent2);
              }
              __name(clearNativeElementHighlight, "clearNativeElementHighlight");
              function highlightNativeElement(_ref) {
                var displayName = _ref.displayName, hideAfterTimeout = _ref.hideAfterTimeout, id = _ref.id, openNativeElementsPanel = _ref.openNativeElementsPanel, rendererID = _ref.rendererID, scrollIntoView = _ref.scrollIntoView;
                var renderer2 = agent2.rendererInterfaces[rendererID];
                if (renderer2 == null) {
                  console.warn('Invalid renderer id "'.concat(rendererID, '" for element "').concat(id, '"'));
                  hideOverlay(agent2);
                  return;
                }
                if (!renderer2.hasFiberWithId(id)) {
                  hideOverlay(agent2);
                  return;
                }
                var nodes = renderer2.findNativeNodesForFiberID(id);
                if (nodes != null && nodes[0] != null) {
                  var node = nodes[0];
                  if (scrollIntoView && typeof node.scrollIntoView === "function") {
                    node.scrollIntoView({
                      block: "nearest",
                      inline: "nearest"
                    });
                  }
                  showOverlay(nodes, displayName, agent2, hideAfterTimeout);
                  if (openNativeElementsPanel) {
                    window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0 = node;
                    bridge.send("syncSelectionToNativeElementsPanel");
                  }
                } else {
                  hideOverlay(agent2);
                }
              }
              __name(highlightNativeElement, "highlightNativeElement");
              function onClick(event) {
                event.preventDefault();
                event.stopPropagation();
                stopInspectingNative();
                bridge.send("stopInspectingNative", true);
              }
              __name(onClick, "onClick");
              function onMouseEvent(event) {
                event.preventDefault();
                event.stopPropagation();
              }
              __name(onMouseEvent, "onMouseEvent");
              function onPointerDown(event) {
                event.preventDefault();
                event.stopPropagation();
                selectFiberForNode(getEventTarget(event));
              }
              __name(onPointerDown, "onPointerDown");
              var lastHoveredNode = null;
              function onPointerMove(event) {
                event.preventDefault();
                event.stopPropagation();
                var target = getEventTarget(event);
                if (lastHoveredNode === target) return;
                lastHoveredNode = target;
                if (target.tagName === "IFRAME") {
                  var iframe = target;
                  try {
                    if (!iframesListeningTo.has(iframe)) {
                      var _window = iframe.contentWindow;
                      registerListenersOnWindow(_window);
                      iframesListeningTo.add(iframe);
                    }
                  } catch (error) {
                  }
                }
                showOverlay([target], null, agent2, false);
                selectFiberForNode(target);
              }
              __name(onPointerMove, "onPointerMove");
              function onPointerUp(event) {
                event.preventDefault();
                event.stopPropagation();
              }
              __name(onPointerUp, "onPointerUp");
              var selectFiberForNode = lodash_throttle_default()(
                esm(function(node) {
                  var id = agent2.getIDForNode(node);
                  if (id !== null) {
                    bridge.send("selectFiber", id);
                  }
                }),
                200,
                // Don't change the selection in the very first 200ms
                // because those are usually unintentional as you lift the cursor.
                {
                  leading: false
                }
              );
              function getEventTarget(event) {
                if (event.composed) {
                  return event.composedPath()[0];
                }
                return event.target;
              }
              __name(getEventTarget, "getEventTarget");
            }
            __name(setupHighlighter, "setupHighlighter");
            ;
            var OUTLINE_COLOR = "#f0f0f0";
            var COLORS = ["#37afa9", "#63b19e", "#80b393", "#97b488", "#abb67d", "#beb771", "#cfb965", "#dfba57", "#efbb49", "#febc38"];
            var canvas = null;
            function draw(nodeToData2, agent2) {
              if (window.document == null) {
                var nodesToDraw = [];
                iterateNodes(nodeToData2, function(_, color, node) {
                  nodesToDraw.push({
                    node,
                    color
                  });
                });
                agent2.emit("drawTraceUpdates", nodesToDraw);
                return;
              }
              if (canvas === null) {
                initialize();
              }
              var canvasFlow = canvas;
              canvasFlow.width = window.innerWidth;
              canvasFlow.height = window.innerHeight;
              var context2 = canvasFlow.getContext("2d");
              context2.clearRect(0, 0, canvasFlow.width, canvasFlow.height);
              iterateNodes(nodeToData2, function(rect, color) {
                if (rect !== null) {
                  drawBorder(context2, rect, color);
                }
              });
            }
            __name(draw, "draw");
            function iterateNodes(nodeToData2, execute) {
              nodeToData2.forEach(function(_ref, node) {
                var count = _ref.count, rect = _ref.rect;
                var colorIndex = Math.min(COLORS.length - 1, count - 1);
                var color = COLORS[colorIndex];
                execute(rect, color, node);
              });
            }
            __name(iterateNodes, "iterateNodes");
            function drawBorder(context2, rect, color) {
              var height = rect.height, left3 = rect.left, top2 = rect.top, width = rect.width;
              context2.lineWidth = 1;
              context2.strokeStyle = OUTLINE_COLOR;
              context2.strokeRect(left3 - 1, top2 - 1, width + 2, height + 2);
              context2.lineWidth = 1;
              context2.strokeStyle = OUTLINE_COLOR;
              context2.strokeRect(left3 + 1, top2 + 1, width - 1, height - 1);
              context2.strokeStyle = color;
              context2.setLineDash([0]);
              context2.lineWidth = 1;
              context2.strokeRect(left3, top2, width - 1, height - 1);
              context2.setLineDash([0]);
            }
            __name(drawBorder, "drawBorder");
            function destroy(agent2) {
              if (window.document == null) {
                agent2.emit("disableTraceUpdates");
                return;
              }
              if (canvas !== null) {
                if (canvas.parentNode != null) {
                  canvas.parentNode.removeChild(canvas);
                }
                canvas = null;
              }
            }
            __name(destroy, "destroy");
            function initialize() {
              canvas = window.document.createElement("canvas");
              canvas.style.cssText = "\n    xx-background-color: red;\n    xx-opacity: 0.5;\n    bottom: 0;\n    left: 0;\n    pointer-events: none;\n    position: fixed;\n    right: 0;\n    top: 0;\n    z-index: 1000000000;\n  ";
              var root = window.document.documentElement;
              root.insertBefore(canvas, root.firstChild);
            }
            __name(initialize, "initialize");
            ;
            function _typeof2(obj) {
              "@babel/helpers - typeof";
              if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return typeof obj2;
                }, "_typeof");
              } else {
                _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                }, "_typeof");
              }
              return _typeof2(obj);
            }
            __name(_typeof2, "_typeof");
            var DISPLAY_DURATION = 250;
            var MAX_DISPLAY_DURATION = 3e3;
            var REMEASUREMENT_AFTER_DURATION = 250;
            var getCurrentTime = (
              // $FlowFixMe[method-unbinding]
              (typeof performance === "undefined" ? "undefined" : _typeof2(performance)) === "object" && typeof performance.now === "function" ? function() {
                return performance.now();
              } : function() {
                return Date.now();
              }
            );
            var nodeToData = /* @__PURE__ */ new Map();
            var agent = null;
            var drawAnimationFrameID = null;
            var isEnabled2 = false;
            var redrawTimeoutID = null;
            function TraceUpdates_initialize(injectedAgent) {
              agent = injectedAgent;
              agent.addListener("traceUpdates", traceUpdates);
            }
            __name(TraceUpdates_initialize, "TraceUpdates_initialize");
            function toggleEnabled(value) {
              isEnabled2 = value;
              if (!isEnabled2) {
                nodeToData.clear();
                if (drawAnimationFrameID !== null) {
                  cancelAnimationFrame(drawAnimationFrameID);
                  drawAnimationFrameID = null;
                }
                if (redrawTimeoutID !== null) {
                  clearTimeout(redrawTimeoutID);
                  redrawTimeoutID = null;
                }
                destroy(agent);
              }
            }
            __name(toggleEnabled, "toggleEnabled");
            function traceUpdates(nodes) {
              if (!isEnabled2) {
                return;
              }
              nodes.forEach(function(node) {
                var data = nodeToData.get(node);
                var now = getCurrentTime();
                var lastMeasuredAt = data != null ? data.lastMeasuredAt : 0;
                var rect = data != null ? data.rect : null;
                if (rect === null || lastMeasuredAt + REMEASUREMENT_AFTER_DURATION < now) {
                  lastMeasuredAt = now;
                  rect = measureNode(node);
                }
                nodeToData.set(node, {
                  count: data != null ? data.count + 1 : 1,
                  expirationTime: data != null ? Math.min(now + MAX_DISPLAY_DURATION, data.expirationTime + DISPLAY_DURATION) : now + DISPLAY_DURATION,
                  lastMeasuredAt,
                  rect
                });
              });
              if (redrawTimeoutID !== null) {
                clearTimeout(redrawTimeoutID);
                redrawTimeoutID = null;
              }
              if (drawAnimationFrameID === null) {
                drawAnimationFrameID = requestAnimationFrame(prepareToDraw);
              }
            }
            __name(traceUpdates, "traceUpdates");
            function prepareToDraw() {
              drawAnimationFrameID = null;
              redrawTimeoutID = null;
              var now = getCurrentTime();
              var earliestExpiration = Number.MAX_VALUE;
              nodeToData.forEach(function(data, node) {
                if (data.expirationTime < now) {
                  nodeToData.delete(node);
                } else {
                  earliestExpiration = Math.min(earliestExpiration, data.expirationTime);
                }
              });
              draw(nodeToData, agent);
              if (earliestExpiration !== Number.MAX_VALUE) {
                redrawTimeoutID = setTimeout(prepareToDraw, earliestExpiration - now);
              }
            }
            __name(prepareToDraw, "prepareToDraw");
            function measureNode(node) {
              if (!node || typeof node.getBoundingClientRect !== "function") {
                return null;
              }
              var currentWindow = window.__REACT_DEVTOOLS_TARGET_WINDOW__ || window;
              return getNestedBoundingClientRect(node, currentWindow);
            }
            __name(measureNode, "measureNode");
            ;
            function esm_typeof(obj) {
              "@babel/helpers - typeof";
              if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                esm_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return typeof obj2;
                }, "_typeof");
              } else {
                esm_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                }, "_typeof");
              }
              return esm_typeof(obj);
            }
            __name(esm_typeof, "esm_typeof");
            function _slicedToArray(arr, i) {
              return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray2(arr, i) || _nonIterableRest();
            }
            __name(_slicedToArray, "_slicedToArray");
            function _nonIterableRest() {
              throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
            }
            __name(_nonIterableRest, "_nonIterableRest");
            function _unsupportedIterableToArray2(o2, minLen) {
              if (!o2) return;
              if (typeof o2 === "string") return _arrayLikeToArray2(o2, minLen);
              var n2 = Object.prototype.toString.call(o2).slice(8, -1);
              if (n2 === "Object" && o2.constructor) n2 = o2.constructor.name;
              if (n2 === "Map" || n2 === "Set") return Array.from(o2);
              if (n2 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n2)) return _arrayLikeToArray2(o2, minLen);
            }
            __name(_unsupportedIterableToArray2, "_unsupportedIterableToArray");
            function _arrayLikeToArray2(arr, len) {
              if (len == null || len > arr.length) len = arr.length;
              for (var i = 0, arr2 = new Array(len); i < len; i++) {
                arr2[i] = arr[i];
              }
              return arr2;
            }
            __name(_arrayLikeToArray2, "_arrayLikeToArray");
            function _iterableToArrayLimit(arr, i) {
              if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
              var _arr = [];
              var _n = true;
              var _d = false;
              var _e = void 0;
              try {
                for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
                  _arr.push(_s.value);
                  if (i && _arr.length === i) break;
                }
              } catch (err) {
                _d = true;
                _e = err;
              } finally {
                try {
                  if (!_n && _i["return"] != null) _i["return"]();
                } finally {
                  if (_d) throw _e;
                }
              }
              return _arr;
            }
            __name(_iterableToArrayLimit, "_iterableToArrayLimit");
            function _arrayWithHoles(arr) {
              if (Array.isArray(arr)) return arr;
            }
            __name(_arrayWithHoles, "_arrayWithHoles");
            var compareVersions = /* @__PURE__ */ __name(function compareVersions2(v12, v2) {
              var n1 = validateAndParse(v12);
              var n2 = validateAndParse(v2);
              var p1 = n1.pop();
              var p2 = n2.pop();
              var r3 = compareSegments(n1, n2);
              if (r3 !== 0) return r3;
              if (p1 && p2) {
                return compareSegments(p1.split("."), p2.split("."));
              } else if (p1 || p2) {
                return p1 ? -1 : 1;
              }
              return 0;
            }, "compareVersions");
            var validate4 = /* @__PURE__ */ __name(function validate5(version2) {
              return typeof version2 === "string" && /^[v\d]/.test(version2) && semver3.test(version2);
            }, "validate");
            var compare = /* @__PURE__ */ __name(function compare2(v12, v2, operator2) {
              assertValidOperator(operator2);
              var res = compareVersions(v12, v2);
              return operatorResMap[operator2].includes(res);
            }, "compare");
            var satisfies = /* @__PURE__ */ __name(function satisfies2(version2, range) {
              var m = range.match(/^([<>=~^]+)/);
              var op = m ? m[1] : "=";
              if (op !== "^" && op !== "~") return compare(version2, range, op);
              var _validateAndParse = validateAndParse(version2), _validateAndParse2 = _slicedToArray(_validateAndParse, 5), v12 = _validateAndParse2[0], v2 = _validateAndParse2[1], v32 = _validateAndParse2[2], vp = _validateAndParse2[4];
              var _validateAndParse3 = validateAndParse(range), _validateAndParse4 = _slicedToArray(_validateAndParse3, 5), r1 = _validateAndParse4[0], r22 = _validateAndParse4[1], r3 = _validateAndParse4[2], rp = _validateAndParse4[4];
              var v = [v12, v2, v32];
              var r4 = [r1, r22 !== null && r22 !== void 0 ? r22 : "x", r3 !== null && r3 !== void 0 ? r3 : "x"];
              if (rp) {
                if (!vp) return false;
                if (compareSegments(v, r4) !== 0) return false;
                if (compareSegments(vp.split("."), rp.split(".")) === -1) return false;
              }
              var nonZero = r4.findIndex(function(v6) {
                return v6 !== "0";
              }) + 1;
              var i = op === "~" ? 2 : nonZero > 1 ? nonZero : 1;
              if (compareSegments(v.slice(0, i), r4.slice(0, i)) !== 0) return false;
              if (compareSegments(v.slice(i), r4.slice(i)) === -1) return false;
              return true;
            }, "satisfies");
            var semver3 = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
            var validateAndParse = /* @__PURE__ */ __name(function validateAndParse2(version2) {
              if (typeof version2 !== "string") {
                throw new TypeError("Invalid argument expected string");
              }
              var match2 = version2.match(semver3);
              if (!match2) {
                throw new Error("Invalid argument not valid semver ('".concat(version2, "' received)"));
              }
              match2.shift();
              return match2;
            }, "validateAndParse");
            var isWildcard = /* @__PURE__ */ __name(function isWildcard2(s2) {
              return s2 === "*" || s2 === "x" || s2 === "X";
            }, "isWildcard");
            var tryParse = /* @__PURE__ */ __name(function tryParse2(v) {
              var n2 = parseInt(v, 10);
              return isNaN(n2) ? v : n2;
            }, "tryParse");
            var forceType = /* @__PURE__ */ __name(function forceType2(a, b) {
              return esm_typeof(a) !== esm_typeof(b) ? [String(a), String(b)] : [a, b];
            }, "forceType");
            var compareStrings = /* @__PURE__ */ __name(function compareStrings2(a, b) {
              if (isWildcard(a) || isWildcard(b)) return 0;
              var _forceType = forceType(tryParse(a), tryParse(b)), _forceType2 = _slicedToArray(_forceType, 2), ap = _forceType2[0], bp = _forceType2[1];
              if (ap > bp) return 1;
              if (ap < bp) return -1;
              return 0;
            }, "compareStrings");
            var compareSegments = /* @__PURE__ */ __name(function compareSegments2(a, b) {
              for (var i = 0; i < Math.max(a.length, b.length); i++) {
                var r3 = compareStrings(a[i] || "0", b[i] || "0");
                if (r3 !== 0) return r3;
              }
              return 0;
            }, "compareSegments");
            var operatorResMap = {
              ">": [1],
              ">=": [0, 1],
              "=": [0],
              "<=": [-1, 0],
              "<": [-1]
            };
            var allowedOperators = Object.keys(operatorResMap);
            var assertValidOperator = /* @__PURE__ */ __name(function assertValidOperator2(op) {
              if (typeof op !== "string") {
                throw new TypeError("Invalid operator type, expected string but got ".concat(esm_typeof(op)));
              }
              if (allowedOperators.indexOf(op) === -1) {
                throw new Error("Invalid operator, expected one of ".concat(allowedOperators.join("|")));
              }
            }, "assertValidOperator");
            var lru_cache = __webpack_require__(730);
            var lru_cache_default = /* @__PURE__ */ __webpack_require__.n(lru_cache);
            var react_is = __webpack_require__(550);
            ;
            function ReactSymbols_typeof(obj) {
              "@babel/helpers - typeof";
              if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                ReactSymbols_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return typeof obj2;
                }, "_typeof");
              } else {
                ReactSymbols_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                }, "_typeof");
              }
              return ReactSymbols_typeof(obj);
            }
            __name(ReactSymbols_typeof, "ReactSymbols_typeof");
            var REACT_ELEMENT_TYPE = Symbol.for("react.element");
            var REACT_PORTAL_TYPE = Symbol.for("react.portal");
            var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
            var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode");
            var REACT_PROFILER_TYPE = Symbol.for("react.profiler");
            var REACT_PROVIDER_TYPE = Symbol.for("react.provider");
            var REACT_CONTEXT_TYPE = Symbol.for("react.context");
            var REACT_SERVER_CONTEXT_TYPE = Symbol.for("react.server_context");
            var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
            var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense");
            var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list");
            var REACT_MEMO_TYPE = Symbol.for("react.memo");
            var REACT_LAZY_TYPE = Symbol.for("react.lazy");
            var REACT_SCOPE_TYPE = Symbol.for("react.scope");
            var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for("react.debug_trace_mode");
            var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen");
            var REACT_LEGACY_HIDDEN_TYPE = Symbol.for("react.legacy_hidden");
            var REACT_CACHE_TYPE = Symbol.for("react.cache");
            var REACT_TRACING_MARKER_TYPE = Symbol.for("react.tracing_marker");
            var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for("react.default_value");
            var REACT_MEMO_CACHE_SENTINEL = Symbol.for("react.memo_cache_sentinel");
            var REACT_POSTPONE_TYPE = Symbol.for("react.postpone");
            var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
            var FAUX_ITERATOR_SYMBOL = "@@iterator";
            function getIteratorFn(maybeIterable) {
              if (maybeIterable === null || ReactSymbols_typeof(maybeIterable) !== "object") {
                return null;
              }
              var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
              if (typeof maybeIterator === "function") {
                return maybeIterator;
              }
              return null;
            }
            __name(getIteratorFn, "getIteratorFn");
            ;
            var types_ElementTypeClass = 1;
            var ElementTypeContext = 2;
            var types_ElementTypeFunction = 5;
            var types_ElementTypeForwardRef = 6;
            var ElementTypeHostComponent = 7;
            var types_ElementTypeMemo = 8;
            var ElementTypeOtherOrUnknown = 9;
            var ElementTypeProfiler = 10;
            var ElementTypeRoot = 11;
            var ElementTypeSuspense = 12;
            var ElementTypeSuspenseList = 13;
            var ElementTypeTracingMarker = 14;
            var ComponentFilterElementType = 1;
            var ComponentFilterDisplayName = 2;
            var ComponentFilterLocation = 3;
            var ComponentFilterHOC = 4;
            var StrictMode = 1;
            ;
            var isArray2 = Array.isArray;
            const src_isArray = isArray2;
            ;
            var process51 = __webpack_require__(169);
            function utils_typeof(obj) {
              "@babel/helpers - typeof";
              if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                utils_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return typeof obj2;
                }, "_typeof");
              } else {
                utils_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                }, "_typeof");
              }
              return utils_typeof(obj);
            }
            __name(utils_typeof, "utils_typeof");
            function _toConsumableArray2(arr) {
              return _arrayWithoutHoles2(arr) || _iterableToArray2(arr) || utils_unsupportedIterableToArray(arr) || _nonIterableSpread2();
            }
            __name(_toConsumableArray2, "_toConsumableArray");
            function _nonIterableSpread2() {
              throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
            }
            __name(_nonIterableSpread2, "_nonIterableSpread");
            function utils_unsupportedIterableToArray(o2, minLen) {
              if (!o2) return;
              if (typeof o2 === "string") return utils_arrayLikeToArray(o2, minLen);
              var n2 = Object.prototype.toString.call(o2).slice(8, -1);
              if (n2 === "Object" && o2.constructor) n2 = o2.constructor.name;
              if (n2 === "Map" || n2 === "Set") return Array.from(o2);
              if (n2 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n2)) return utils_arrayLikeToArray(o2, minLen);
            }
            __name(utils_unsupportedIterableToArray, "utils_unsupportedIterableToArray");
            function _iterableToArray2(iter) {
              if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
            }
            __name(_iterableToArray2, "_iterableToArray");
            function _arrayWithoutHoles2(arr) {
              if (Array.isArray(arr)) return utils_arrayLikeToArray(arr);
            }
            __name(_arrayWithoutHoles2, "_arrayWithoutHoles");
            function utils_arrayLikeToArray(arr, len) {
              if (len == null || len > arr.length) len = arr.length;
              for (var i = 0, arr2 = new Array(len); i < len; i++) {
                arr2[i] = arr[i];
              }
              return arr2;
            }
            __name(utils_arrayLikeToArray, "utils_arrayLikeToArray");
            var utils_hasOwnProperty = Object.prototype.hasOwnProperty;
            var cachedDisplayNames = /* @__PURE__ */ new WeakMap();
            var encodedStringCache = new (lru_cache_default())({
              max: 1e3
            });
            function alphaSortKeys(a, b) {
              if (a.toString() > b.toString()) {
                return 1;
              } else if (b.toString() > a.toString()) {
                return -1;
              } else {
                return 0;
              }
            }
            __name(alphaSortKeys, "alphaSortKeys");
            function getAllEnumerableKeys(obj) {
              var keys = /* @__PURE__ */ new Set();
              var current = obj;
              var _loop = /* @__PURE__ */ __name(function _loop2() {
                var currentKeys = [].concat(_toConsumableArray2(Object.keys(current)), _toConsumableArray2(Object.getOwnPropertySymbols(current)));
                var descriptors = Object.getOwnPropertyDescriptors(current);
                currentKeys.forEach(function(key) {
                  if (descriptors[key].enumerable) {
                    keys.add(key);
                  }
                });
                current = Object.getPrototypeOf(current);
              }, "_loop");
              while (current != null) {
                _loop();
              }
              return keys;
            }
            __name(getAllEnumerableKeys, "getAllEnumerableKeys");
            function getWrappedDisplayName(outerType, innerType, wrapperName, fallbackName) {
              var displayName = outerType.displayName;
              return displayName || "".concat(wrapperName, "(").concat(getDisplayName(innerType, fallbackName), ")");
            }
            __name(getWrappedDisplayName, "getWrappedDisplayName");
            function getDisplayName(type) {
              var fallbackName = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "Anonymous";
              var nameFromCache = cachedDisplayNames.get(type);
              if (nameFromCache != null) {
                return nameFromCache;
              }
              var displayName = fallbackName;
              if (typeof type.displayName === "string") {
                displayName = type.displayName;
              } else if (typeof type.name === "string" && type.name !== "") {
                displayName = type.name;
              }
              cachedDisplayNames.set(type, displayName);
              return displayName;
            }
            __name(getDisplayName, "getDisplayName");
            var uidCounter = 0;
            function getUID() {
              return ++uidCounter;
            }
            __name(getUID, "getUID");
            function utfDecodeString(array) {
              var string = "";
              for (var i = 0; i < array.length; i++) {
                var char = array[i];
                string += String.fromCodePoint(char);
              }
              return string;
            }
            __name(utfDecodeString, "utfDecodeString");
            function surrogatePairToCodePoint(charCode1, charCode2) {
              return ((charCode1 & 1023) << 10) + (charCode2 & 1023) + 65536;
            }
            __name(surrogatePairToCodePoint, "surrogatePairToCodePoint");
            function utfEncodeString(string) {
              var cached = encodedStringCache.get(string);
              if (cached !== void 0) {
                return cached;
              }
              var encoded = [];
              var i = 0;
              var charCode;
              while (i < string.length) {
                charCode = string.charCodeAt(i);
                if ((charCode & 63488) === 55296) {
                  encoded.push(surrogatePairToCodePoint(charCode, string.charCodeAt(++i)));
                } else {
                  encoded.push(charCode);
                }
                ++i;
              }
              encodedStringCache.set(string, encoded);
              return encoded;
            }
            __name(utfEncodeString, "utfEncodeString");
            function printOperationsArray(operations) {
              var rendererID = operations[0];
              var rootID = operations[1];
              var logs2 = ["operations for renderer:".concat(rendererID, " and root:").concat(rootID)];
              var i = 2;
              var stringTable = [
                null
                // ID = 0 corresponds to the null string.
              ];
              var stringTableSize = operations[i++];
              var stringTableEnd = i + stringTableSize;
              while (i < stringTableEnd) {
                var nextLength = operations[i++];
                var nextString = utfDecodeString(operations.slice(i, i + nextLength));
                stringTable.push(nextString);
                i += nextLength;
              }
              while (i < operations.length) {
                var operation = operations[i];
                switch (operation) {
                  case TREE_OPERATION_ADD: {
                    var _id = operations[i + 1];
                    var type = operations[i + 2];
                    i += 3;
                    if (type === ElementTypeRoot) {
                      logs2.push("Add new root node ".concat(_id));
                      i++;
                      i++;
                      i++;
                      i++;
                    } else {
                      var parentID = operations[i];
                      i++;
                      i++;
                      var displayNameStringID = operations[i];
                      var displayName = stringTable[displayNameStringID];
                      i++;
                      i++;
                      logs2.push("Add node ".concat(_id, " (").concat(displayName || "null", ") as child of ").concat(parentID));
                    }
                    break;
                  }
                  case TREE_OPERATION_REMOVE: {
                    var removeLength = operations[i + 1];
                    i += 2;
                    for (var removeIndex = 0; removeIndex < removeLength; removeIndex++) {
                      var _id2 = operations[i];
                      i += 1;
                      logs2.push("Remove node ".concat(_id2));
                    }
                    break;
                  }
                  case TREE_OPERATION_REMOVE_ROOT: {
                    i += 1;
                    logs2.push("Remove root ".concat(rootID));
                    break;
                  }
                  case TREE_OPERATION_SET_SUBTREE_MODE: {
                    var _id3 = operations[i + 1];
                    var mode = operations[i + 1];
                    i += 3;
                    logs2.push("Mode ".concat(mode, " set for subtree with root ").concat(_id3));
                    break;
                  }
                  case TREE_OPERATION_REORDER_CHILDREN: {
                    var _id4 = operations[i + 1];
                    var numChildren = operations[i + 2];
                    i += 3;
                    var children = operations.slice(i, i + numChildren);
                    i += numChildren;
                    logs2.push("Re-order node ".concat(_id4, " children ").concat(children.join(",")));
                    break;
                  }
                  case TREE_OPERATION_UPDATE_TREE_BASE_DURATION:
                    i += 3;
                    break;
                  case TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS:
                    var id = operations[i + 1];
                    var numErrors = operations[i + 2];
                    var numWarnings = operations[i + 3];
                    i += 4;
                    logs2.push("Node ".concat(id, " has ").concat(numErrors, " errors and ").concat(numWarnings, " warnings"));
                    break;
                  default:
                    throw Error('Unsupported Bridge operation "'.concat(operation, '"'));
                }
              }
              console.log(logs2.join("\n  "));
            }
            __name(printOperationsArray, "printOperationsArray");
            function getDefaultComponentFilters() {
              return [{
                type: ComponentFilterElementType,
                value: ElementTypeHostComponent,
                isEnabled: true
              }];
            }
            __name(getDefaultComponentFilters, "getDefaultComponentFilters");
            function getSavedComponentFilters() {
              try {
                var raw2 = localStorageGetItem(LOCAL_STORAGE_COMPONENT_FILTER_PREFERENCES_KEY);
                if (raw2 != null) {
                  return JSON.parse(raw2);
                }
              } catch (error) {
              }
              return getDefaultComponentFilters();
            }
            __name(getSavedComponentFilters, "getSavedComponentFilters");
            function setSavedComponentFilters(componentFilters) {
              localStorageSetItem(LOCAL_STORAGE_COMPONENT_FILTER_PREFERENCES_KEY, JSON.stringify(componentFilters));
            }
            __name(setSavedComponentFilters, "setSavedComponentFilters");
            function parseBool(s2) {
              if (s2 === "true") {
                return true;
              }
              if (s2 === "false") {
                return false;
              }
            }
            __name(parseBool, "parseBool");
            function castBool(v) {
              if (v === true || v === false) {
                return v;
              }
            }
            __name(castBool, "castBool");
            function castBrowserTheme(v) {
              if (v === "light" || v === "dark" || v === "auto") {
                return v;
              }
            }
            __name(castBrowserTheme, "castBrowserTheme");
            function getAppendComponentStack() {
              var _parseBool;
              var raw2 = localStorageGetItem(LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY);
              return (_parseBool = parseBool(raw2)) !== null && _parseBool !== void 0 ? _parseBool : true;
            }
            __name(getAppendComponentStack, "getAppendComponentStack");
            function getBreakOnConsoleErrors() {
              var _parseBool2;
              var raw2 = localStorageGetItem(LOCAL_STORAGE_SHOULD_BREAK_ON_CONSOLE_ERRORS);
              return (_parseBool2 = parseBool(raw2)) !== null && _parseBool2 !== void 0 ? _parseBool2 : false;
            }
            __name(getBreakOnConsoleErrors, "getBreakOnConsoleErrors");
            function getHideConsoleLogsInStrictMode() {
              var _parseBool3;
              var raw2 = localStorageGetItem(LOCAL_STORAGE_HIDE_CONSOLE_LOGS_IN_STRICT_MODE);
              return (_parseBool3 = parseBool(raw2)) !== null && _parseBool3 !== void 0 ? _parseBool3 : false;
            }
            __name(getHideConsoleLogsInStrictMode, "getHideConsoleLogsInStrictMode");
            function getShowInlineWarningsAndErrors() {
              var _parseBool4;
              var raw2 = localStorageGetItem(LOCAL_STORAGE_SHOW_INLINE_WARNINGS_AND_ERRORS_KEY);
              return (_parseBool4 = parseBool(raw2)) !== null && _parseBool4 !== void 0 ? _parseBool4 : true;
            }
            __name(getShowInlineWarningsAndErrors, "getShowInlineWarningsAndErrors");
            function getDefaultOpenInEditorURL() {
              return typeof process51.env.EDITOR_URL === "string" ? process51.env.EDITOR_URL : "";
            }
            __name(getDefaultOpenInEditorURL, "getDefaultOpenInEditorURL");
            function getOpenInEditorURL() {
              try {
                var raw2 = localStorageGetItem(LOCAL_STORAGE_OPEN_IN_EDITOR_URL);
                if (raw2 != null) {
                  return JSON.parse(raw2);
                }
              } catch (error) {
              }
              return getDefaultOpenInEditorURL();
            }
            __name(getOpenInEditorURL, "getOpenInEditorURL");
            function separateDisplayNameAndHOCs(displayName, type) {
              if (displayName === null) {
                return [null, null];
              }
              var hocDisplayNames = null;
              switch (type) {
                case ElementTypeClass:
                case ElementTypeForwardRef:
                case ElementTypeFunction:
                case ElementTypeMemo:
                  if (displayName.indexOf("(") >= 0) {
                    var matches = displayName.match(/[^()]+/g);
                    if (matches != null) {
                      displayName = matches.pop();
                      hocDisplayNames = matches;
                    }
                  }
                  break;
                default:
                  break;
              }
              return [displayName, hocDisplayNames];
            }
            __name(separateDisplayNameAndHOCs, "separateDisplayNameAndHOCs");
            function shallowDiffers(prev, next) {
              for (var attribute in prev) {
                if (!(attribute in next)) {
                  return true;
                }
              }
              for (var _attribute in next) {
                if (prev[_attribute] !== next[_attribute]) {
                  return true;
                }
              }
              return false;
            }
            __name(shallowDiffers, "shallowDiffers");
            function utils_getInObject(object, path108) {
              return path108.reduce(function(reduced, attr) {
                if (reduced) {
                  if (utils_hasOwnProperty.call(reduced, attr)) {
                    return reduced[attr];
                  }
                  if (typeof reduced[Symbol.iterator] === "function") {
                    return Array.from(reduced)[attr];
                  }
                }
                return null;
              }, object);
            }
            __name(utils_getInObject, "utils_getInObject");
            function deletePathInObject(object, path108) {
              var length = path108.length;
              var last2 = path108[length - 1];
              if (object != null) {
                var parent = utils_getInObject(object, path108.slice(0, length - 1));
                if (parent) {
                  if (src_isArray(parent)) {
                    parent.splice(last2, 1);
                  } else {
                    delete parent[last2];
                  }
                }
              }
            }
            __name(deletePathInObject, "deletePathInObject");
            function renamePathInObject(object, oldPath, newPath) {
              var length = oldPath.length;
              if (object != null) {
                var parent = utils_getInObject(object, oldPath.slice(0, length - 1));
                if (parent) {
                  var lastOld = oldPath[length - 1];
                  var lastNew = newPath[length - 1];
                  parent[lastNew] = parent[lastOld];
                  if (src_isArray(parent)) {
                    parent.splice(lastOld, 1);
                  } else {
                    delete parent[lastOld];
                  }
                }
              }
            }
            __name(renamePathInObject, "renamePathInObject");
            function utils_setInObject(object, path108, value) {
              var length = path108.length;
              var last2 = path108[length - 1];
              if (object != null) {
                var parent = utils_getInObject(object, path108.slice(0, length - 1));
                if (parent) {
                  parent[last2] = value;
                }
              }
            }
            __name(utils_setInObject, "utils_setInObject");
            function getDataType(data) {
              if (data === null) {
                return "null";
              } else if (data === void 0) {
                return "undefined";
              }
              if ((0, react_is.isElement)(data)) {
                return "react_element";
              }
              if (typeof HTMLElement !== "undefined" && data instanceof HTMLElement) {
                return "html_element";
              }
              var type = utils_typeof(data);
              switch (type) {
                case "bigint":
                  return "bigint";
                case "boolean":
                  return "boolean";
                case "function":
                  return "function";
                case "number":
                  if (Number.isNaN(data)) {
                    return "nan";
                  } else if (!Number.isFinite(data)) {
                    return "infinity";
                  } else {
                    return "number";
                  }
                case "object":
                  if (src_isArray(data)) {
                    return "array";
                  } else if (ArrayBuffer.isView(data)) {
                    return utils_hasOwnProperty.call(data.constructor, "BYTES_PER_ELEMENT") ? "typed_array" : "data_view";
                  } else if (data.constructor && data.constructor.name === "ArrayBuffer") {
                    return "array_buffer";
                  } else if (typeof data[Symbol.iterator] === "function") {
                    var iterator = data[Symbol.iterator]();
                    if (!iterator) {
                    } else {
                      return iterator === data ? "opaque_iterator" : "iterator";
                    }
                  } else if (data.constructor && data.constructor.name === "RegExp") {
                    return "regexp";
                  } else {
                    var toStringValue = Object.prototype.toString.call(data);
                    if (toStringValue === "[object Date]") {
                      return "date";
                    } else if (toStringValue === "[object HTMLAllCollection]") {
                      return "html_all_collection";
                    }
                  }
                  if (!isPlainObject2(data)) {
                    return "class_instance";
                  }
                  return "object";
                case "string":
                  return "string";
                case "symbol":
                  return "symbol";
                case "undefined":
                  if (
                    // $FlowFixMe[method-unbinding]
                    Object.prototype.toString.call(data) === "[object HTMLAllCollection]"
                  ) {
                    return "html_all_collection";
                  }
                  return "undefined";
                default:
                  return "unknown";
              }
            }
            __name(getDataType, "getDataType");
            function getDisplayNameForReactElement(element) {
              var elementType = (0, react_is.typeOf)(element);
              switch (elementType) {
                case react_is.ContextConsumer:
                  return "ContextConsumer";
                case react_is.ContextProvider:
                  return "ContextProvider";
                case react_is.ForwardRef:
                  return "ForwardRef";
                case react_is.Fragment:
                  return "Fragment";
                case react_is.Lazy:
                  return "Lazy";
                case react_is.Memo:
                  return "Memo";
                case react_is.Portal:
                  return "Portal";
                case react_is.Profiler:
                  return "Profiler";
                case react_is.StrictMode:
                  return "StrictMode";
                case react_is.Suspense:
                  return "Suspense";
                case REACT_SUSPENSE_LIST_TYPE:
                  return "SuspenseList";
                case REACT_TRACING_MARKER_TYPE:
                  return "TracingMarker";
                default:
                  var type = element.type;
                  if (typeof type === "string") {
                    return type;
                  } else if (typeof type === "function") {
                    return getDisplayName(type, "Anonymous");
                  } else if (type != null) {
                    return "NotImplementedInDevtools";
                  } else {
                    return "Element";
                  }
              }
            }
            __name(getDisplayNameForReactElement, "getDisplayNameForReactElement");
            var MAX_PREVIEW_STRING_LENGTH = 50;
            function truncateForDisplay(string) {
              var length = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : MAX_PREVIEW_STRING_LENGTH;
              if (string.length > length) {
                return string.slice(0, length) + "\u2026";
              } else {
                return string;
              }
            }
            __name(truncateForDisplay, "truncateForDisplay");
            function formatDataForPreview(data, showFormattedValue) {
              if (data != null && utils_hasOwnProperty.call(data, meta.type)) {
                return showFormattedValue ? data[meta.preview_long] : data[meta.preview_short];
              }
              var type = getDataType(data);
              switch (type) {
                case "html_element":
                  return "<".concat(truncateForDisplay(data.tagName.toLowerCase()), " />");
                case "function":
                  return truncateForDisplay("\u0192 ".concat(typeof data.name === "function" ? "" : data.name, "() {}"));
                case "string":
                  return '"'.concat(data, '"');
                case "bigint":
                  return truncateForDisplay(data.toString() + "n");
                case "regexp":
                  return truncateForDisplay(data.toString());
                case "symbol":
                  return truncateForDisplay(data.toString());
                case "react_element":
                  return "<".concat(truncateForDisplay(getDisplayNameForReactElement(data) || "Unknown"), " />");
                case "array_buffer":
                  return "ArrayBuffer(".concat(data.byteLength, ")");
                case "data_view":
                  return "DataView(".concat(data.buffer.byteLength, ")");
                case "array":
                  if (showFormattedValue) {
                    var formatted = "";
                    for (var i = 0; i < data.length; i++) {
                      if (i > 0) {
                        formatted += ", ";
                      }
                      formatted += formatDataForPreview(data[i], false);
                      if (formatted.length > MAX_PREVIEW_STRING_LENGTH) {
                        break;
                      }
                    }
                    return "[".concat(truncateForDisplay(formatted), "]");
                  } else {
                    var length = utils_hasOwnProperty.call(data, meta.size) ? data[meta.size] : data.length;
                    return "Array(".concat(length, ")");
                  }
                case "typed_array":
                  var shortName = "".concat(data.constructor.name, "(").concat(data.length, ")");
                  if (showFormattedValue) {
                    var _formatted = "";
                    for (var _i = 0; _i < data.length; _i++) {
                      if (_i > 0) {
                        _formatted += ", ";
                      }
                      _formatted += data[_i];
                      if (_formatted.length > MAX_PREVIEW_STRING_LENGTH) {
                        break;
                      }
                    }
                    return "".concat(shortName, " [").concat(truncateForDisplay(_formatted), "]");
                  } else {
                    return shortName;
                  }
                case "iterator":
                  var name3 = data.constructor.name;
                  if (showFormattedValue) {
                    var array = Array.from(data);
                    var _formatted2 = "";
                    for (var _i2 = 0; _i2 < array.length; _i2++) {
                      var entryOrEntries = array[_i2];
                      if (_i2 > 0) {
                        _formatted2 += ", ";
                      }
                      if (src_isArray(entryOrEntries)) {
                        var key = formatDataForPreview(entryOrEntries[0], true);
                        var value = formatDataForPreview(entryOrEntries[1], false);
                        _formatted2 += "".concat(key, " => ").concat(value);
                      } else {
                        _formatted2 += formatDataForPreview(entryOrEntries, false);
                      }
                      if (_formatted2.length > MAX_PREVIEW_STRING_LENGTH) {
                        break;
                      }
                    }
                    return "".concat(name3, "(").concat(data.size, ") {").concat(truncateForDisplay(_formatted2), "}");
                  } else {
                    return "".concat(name3, "(").concat(data.size, ")");
                  }
                case "opaque_iterator": {
                  return data[Symbol.toStringTag];
                }
                case "date":
                  return data.toString();
                case "class_instance":
                  return data.constructor.name;
                case "object":
                  if (showFormattedValue) {
                    var keys = Array.from(getAllEnumerableKeys(data)).sort(alphaSortKeys);
                    var _formatted3 = "";
                    for (var _i3 = 0; _i3 < keys.length; _i3++) {
                      var _key = keys[_i3];
                      if (_i3 > 0) {
                        _formatted3 += ", ";
                      }
                      _formatted3 += "".concat(_key.toString(), ": ").concat(formatDataForPreview(data[_key], false));
                      if (_formatted3.length > MAX_PREVIEW_STRING_LENGTH) {
                        break;
                      }
                    }
                    return "{".concat(truncateForDisplay(_formatted3), "}");
                  } else {
                    return "{\u2026}";
                  }
                case "boolean":
                case "number":
                case "infinity":
                case "nan":
                case "null":
                case "undefined":
                  return data;
                default:
                  try {
                    return truncateForDisplay(String(data));
                  } catch (error) {
                    return "unserializable";
                  }
              }
            }
            __name(formatDataForPreview, "formatDataForPreview");
            var isPlainObject2 = /* @__PURE__ */ __name(function isPlainObject3(object) {
              var objectPrototype = Object.getPrototypeOf(object);
              if (!objectPrototype) return true;
              var objectParentPrototype = Object.getPrototypeOf(objectPrototype);
              return !objectParentPrototype;
            }, "isPlainObject");
            ;
            function ownKeys2(object, enumerableOnly) {
              var keys = Object.keys(object);
              if (Object.getOwnPropertySymbols) {
                var symbols = Object.getOwnPropertySymbols(object);
                if (enumerableOnly) symbols = symbols.filter(function(sym) {
                  return Object.getOwnPropertyDescriptor(object, sym).enumerable;
                });
                keys.push.apply(keys, symbols);
              }
              return keys;
            }
            __name(ownKeys2, "ownKeys");
            function _objectSpread(target) {
              for (var i = 1; i < arguments.length; i++) {
                var source2 = arguments[i] != null ? arguments[i] : {};
                if (i % 2) {
                  ownKeys2(Object(source2), true).forEach(function(key) {
                    hydration_defineProperty(target, key, source2[key]);
                  });
                } else if (Object.getOwnPropertyDescriptors) {
                  Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
                } else {
                  ownKeys2(Object(source2)).forEach(function(key) {
                    Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
                  });
                }
              }
              return target;
            }
            __name(_objectSpread, "_objectSpread");
            function hydration_defineProperty(obj, key, value) {
              if (key in obj) {
                Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
              } else {
                obj[key] = value;
              }
              return obj;
            }
            __name(hydration_defineProperty, "hydration_defineProperty");
            var meta = {
              inspectable: Symbol("inspectable"),
              inspected: Symbol("inspected"),
              name: Symbol("name"),
              preview_long: Symbol("preview_long"),
              preview_short: Symbol("preview_short"),
              readonly: Symbol("readonly"),
              size: Symbol("size"),
              type: Symbol("type"),
              unserializable: Symbol("unserializable")
            };
            var LEVEL_THRESHOLD = 2;
            function createDehydrated(type, inspectable, data, cleaned, path108) {
              cleaned.push(path108);
              var dehydrated = {
                inspectable,
                type,
                preview_long: formatDataForPreview(data, true),
                preview_short: formatDataForPreview(data, false),
                name: !data.constructor || data.constructor.name === "Object" ? "" : data.constructor.name
              };
              if (type === "array" || type === "typed_array") {
                dehydrated.size = data.length;
              } else if (type === "object") {
                dehydrated.size = Object.keys(data).length;
              }
              if (type === "iterator" || type === "typed_array") {
                dehydrated.readonly = true;
              }
              return dehydrated;
            }
            __name(createDehydrated, "createDehydrated");
            function dehydrate(data, cleaned, unserializable, path108, isPathAllowed) {
              var level = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : 0;
              var type = getDataType(data);
              var isPathAllowedCheck;
              switch (type) {
                case "html_element":
                  cleaned.push(path108);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: data.tagName,
                    type
                  };
                case "function":
                  cleaned.push(path108);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: typeof data.name === "function" || !data.name ? "function" : data.name,
                    type
                  };
                case "string":
                  isPathAllowedCheck = isPathAllowed(path108);
                  if (isPathAllowedCheck) {
                    return data;
                  } else {
                    return data.length <= 500 ? data : data.slice(0, 500) + "...";
                  }
                case "bigint":
                  cleaned.push(path108);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: data.toString(),
                    type
                  };
                case "symbol":
                  cleaned.push(path108);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: data.toString(),
                    type
                  };
                // React Elements aren't very inspector-friendly,
                // and often contain private fields or circular references.
                case "react_element":
                  cleaned.push(path108);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: getDisplayNameForReactElement(data) || "Unknown",
                    type
                  };
                // ArrayBuffers error if you try to inspect them.
                case "array_buffer":
                case "data_view":
                  cleaned.push(path108);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: type === "data_view" ? "DataView" : "ArrayBuffer",
                    size: data.byteLength,
                    type
                  };
                case "array":
                  isPathAllowedCheck = isPathAllowed(path108);
                  if (level >= LEVEL_THRESHOLD && !isPathAllowedCheck) {
                    return createDehydrated(type, true, data, cleaned, path108);
                  }
                  return data.map(function(item, i) {
                    return dehydrate(item, cleaned, unserializable, path108.concat([i]), isPathAllowed, isPathAllowedCheck ? 1 : level + 1);
                  });
                case "html_all_collection":
                case "typed_array":
                case "iterator":
                  isPathAllowedCheck = isPathAllowed(path108);
                  if (level >= LEVEL_THRESHOLD && !isPathAllowedCheck) {
                    return createDehydrated(type, true, data, cleaned, path108);
                  } else {
                    var unserializableValue = {
                      unserializable: true,
                      type,
                      readonly: true,
                      size: type === "typed_array" ? data.length : void 0,
                      preview_short: formatDataForPreview(data, false),
                      preview_long: formatDataForPreview(data, true),
                      name: !data.constructor || data.constructor.name === "Object" ? "" : data.constructor.name
                    };
                    Array.from(data).forEach(function(item, i) {
                      return unserializableValue[i] = dehydrate(item, cleaned, unserializable, path108.concat([i]), isPathAllowed, isPathAllowedCheck ? 1 : level + 1);
                    });
                    unserializable.push(path108);
                    return unserializableValue;
                  }
                case "opaque_iterator":
                  cleaned.push(path108);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: data[Symbol.toStringTag],
                    type
                  };
                case "date":
                  cleaned.push(path108);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: data.toString(),
                    type
                  };
                case "regexp":
                  cleaned.push(path108);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: data.toString(),
                    type
                  };
                case "object":
                  isPathAllowedCheck = isPathAllowed(path108);
                  if (level >= LEVEL_THRESHOLD && !isPathAllowedCheck) {
                    return createDehydrated(type, true, data, cleaned, path108);
                  } else {
                    var object = {};
                    getAllEnumerableKeys(data).forEach(function(key) {
                      var name3 = key.toString();
                      object[name3] = dehydrate(data[key], cleaned, unserializable, path108.concat([name3]), isPathAllowed, isPathAllowedCheck ? 1 : level + 1);
                    });
                    return object;
                  }
                case "class_instance":
                  isPathAllowedCheck = isPathAllowed(path108);
                  if (level >= LEVEL_THRESHOLD && !isPathAllowedCheck) {
                    return createDehydrated(type, true, data, cleaned, path108);
                  }
                  var value = {
                    unserializable: true,
                    type,
                    readonly: true,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: data.constructor.name
                  };
                  getAllEnumerableKeys(data).forEach(function(key) {
                    var keyAsString = key.toString();
                    value[keyAsString] = dehydrate(data[key], cleaned, unserializable, path108.concat([keyAsString]), isPathAllowed, isPathAllowedCheck ? 1 : level + 1);
                  });
                  unserializable.push(path108);
                  return value;
                case "infinity":
                case "nan":
                case "undefined":
                  cleaned.push(path108);
                  return {
                    type
                  };
                default:
                  return data;
              }
            }
            __name(dehydrate, "dehydrate");
            function fillInPath(object, data, path108, value) {
              var target = getInObject(object, path108);
              if (target != null) {
                if (!target[meta.unserializable]) {
                  delete target[meta.inspectable];
                  delete target[meta.inspected];
                  delete target[meta.name];
                  delete target[meta.preview_long];
                  delete target[meta.preview_short];
                  delete target[meta.readonly];
                  delete target[meta.size];
                  delete target[meta.type];
                }
              }
              if (value !== null && data.unserializable.length > 0) {
                var unserializablePath = data.unserializable[0];
                var isMatch = unserializablePath.length === path108.length;
                for (var i = 0; i < path108.length; i++) {
                  if (path108[i] !== unserializablePath[i]) {
                    isMatch = false;
                    break;
                  }
                }
                if (isMatch) {
                  upgradeUnserializable(value, value);
                }
              }
              setInObject(object, path108, value);
            }
            __name(fillInPath, "fillInPath");
            function hydrate(object, cleaned, unserializable) {
              cleaned.forEach(function(path108) {
                var length = path108.length;
                var last2 = path108[length - 1];
                var parent = getInObject(object, path108.slice(0, length - 1));
                if (!parent || !parent.hasOwnProperty(last2)) {
                  return;
                }
                var value = parent[last2];
                if (!value) {
                  return;
                } else if (value.type === "infinity") {
                  parent[last2] = Infinity;
                } else if (value.type === "nan") {
                  parent[last2] = NaN;
                } else if (value.type === "undefined") {
                  parent[last2] = void 0;
                } else {
                  var replaced = {};
                  replaced[meta.inspectable] = !!value.inspectable;
                  replaced[meta.inspected] = false;
                  replaced[meta.name] = value.name;
                  replaced[meta.preview_long] = value.preview_long;
                  replaced[meta.preview_short] = value.preview_short;
                  replaced[meta.size] = value.size;
                  replaced[meta.readonly] = !!value.readonly;
                  replaced[meta.type] = value.type;
                  parent[last2] = replaced;
                }
              });
              unserializable.forEach(function(path108) {
                var length = path108.length;
                var last2 = path108[length - 1];
                var parent = getInObject(object, path108.slice(0, length - 1));
                if (!parent || !parent.hasOwnProperty(last2)) {
                  return;
                }
                var node = parent[last2];
                var replacement = _objectSpread({}, node);
                upgradeUnserializable(replacement, node);
                parent[last2] = replacement;
              });
              return object;
            }
            __name(hydrate, "hydrate");
            function upgradeUnserializable(destination, source2) {
              var _Object$definePropert;
              Object.defineProperties(destination, (_Object$definePropert = {}, hydration_defineProperty(_Object$definePropert, meta.inspected, {
                configurable: true,
                enumerable: false,
                value: !!source2.inspected
              }), hydration_defineProperty(_Object$definePropert, meta.name, {
                configurable: true,
                enumerable: false,
                value: source2.name
              }), hydration_defineProperty(_Object$definePropert, meta.preview_long, {
                configurable: true,
                enumerable: false,
                value: source2.preview_long
              }), hydration_defineProperty(_Object$definePropert, meta.preview_short, {
                configurable: true,
                enumerable: false,
                value: source2.preview_short
              }), hydration_defineProperty(_Object$definePropert, meta.size, {
                configurable: true,
                enumerable: false,
                value: source2.size
              }), hydration_defineProperty(_Object$definePropert, meta.readonly, {
                configurable: true,
                enumerable: false,
                value: !!source2.readonly
              }), hydration_defineProperty(_Object$definePropert, meta.type, {
                configurable: true,
                enumerable: false,
                value: source2.type
              }), hydration_defineProperty(_Object$definePropert, meta.unserializable, {
                configurable: true,
                enumerable: false,
                value: !!source2.unserializable
              }), _Object$definePropert));
              delete destination.inspected;
              delete destination.name;
              delete destination.preview_long;
              delete destination.preview_short;
              delete destination.size;
              delete destination.readonly;
              delete destination.type;
              delete destination.unserializable;
            }
            __name(upgradeUnserializable, "upgradeUnserializable");
            ;
            var isArrayImpl = Array.isArray;
            function isArray_isArray(a) {
              return isArrayImpl(a);
            }
            __name(isArray_isArray, "isArray_isArray");
            const shared_isArray = isArray_isArray;
            ;
            function utils_toConsumableArray(arr) {
              return utils_arrayWithoutHoles(arr) || utils_iterableToArray(arr) || backend_utils_unsupportedIterableToArray(arr) || utils_nonIterableSpread();
            }
            __name(utils_toConsumableArray, "utils_toConsumableArray");
            function utils_nonIterableSpread() {
              throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
            }
            __name(utils_nonIterableSpread, "utils_nonIterableSpread");
            function backend_utils_unsupportedIterableToArray(o2, minLen) {
              if (!o2) return;
              if (typeof o2 === "string") return backend_utils_arrayLikeToArray(o2, minLen);
              var n2 = Object.prototype.toString.call(o2).slice(8, -1);
              if (n2 === "Object" && o2.constructor) n2 = o2.constructor.name;
              if (n2 === "Map" || n2 === "Set") return Array.from(o2);
              if (n2 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n2)) return backend_utils_arrayLikeToArray(o2, minLen);
            }
            __name(backend_utils_unsupportedIterableToArray, "backend_utils_unsupportedIterableToArray");
            function utils_iterableToArray(iter) {
              if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
            }
            __name(utils_iterableToArray, "utils_iterableToArray");
            function utils_arrayWithoutHoles(arr) {
              if (Array.isArray(arr)) return backend_utils_arrayLikeToArray(arr);
            }
            __name(utils_arrayWithoutHoles, "utils_arrayWithoutHoles");
            function backend_utils_arrayLikeToArray(arr, len) {
              if (len == null || len > arr.length) len = arr.length;
              for (var i = 0, arr2 = new Array(len); i < len; i++) {
                arr2[i] = arr[i];
              }
              return arr2;
            }
            __name(backend_utils_arrayLikeToArray, "backend_utils_arrayLikeToArray");
            function backend_utils_typeof(obj) {
              "@babel/helpers - typeof";
              if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                backend_utils_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return typeof obj2;
                }, "_typeof");
              } else {
                backend_utils_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                }, "_typeof");
              }
              return backend_utils_typeof(obj);
            }
            __name(backend_utils_typeof, "backend_utils_typeof");
            function utils_ownKeys(object, enumerableOnly) {
              var keys = Object.keys(object);
              if (Object.getOwnPropertySymbols) {
                var symbols = Object.getOwnPropertySymbols(object);
                if (enumerableOnly) symbols = symbols.filter(function(sym) {
                  return Object.getOwnPropertyDescriptor(object, sym).enumerable;
                });
                keys.push.apply(keys, symbols);
              }
              return keys;
            }
            __name(utils_ownKeys, "utils_ownKeys");
            function utils_objectSpread(target) {
              for (var i = 1; i < arguments.length; i++) {
                var source2 = arguments[i] != null ? arguments[i] : {};
                if (i % 2) {
                  utils_ownKeys(Object(source2), true).forEach(function(key) {
                    utils_defineProperty(target, key, source2[key]);
                  });
                } else if (Object.getOwnPropertyDescriptors) {
                  Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
                } else {
                  utils_ownKeys(Object(source2)).forEach(function(key) {
                    Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
                  });
                }
              }
              return target;
            }
            __name(utils_objectSpread, "utils_objectSpread");
            function utils_defineProperty(obj, key, value) {
              if (key in obj) {
                Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
              } else {
                obj[key] = value;
              }
              return obj;
            }
            __name(utils_defineProperty, "utils_defineProperty");
            var FIRST_DEVTOOLS_BACKEND_LOCKSTEP_VER = "999.9.9";
            function hasAssignedBackend(version2) {
              if (version2 == null || version2 === "") {
                return false;
              }
              return gte(version2, FIRST_DEVTOOLS_BACKEND_LOCKSTEP_VER);
            }
            __name(hasAssignedBackend, "hasAssignedBackend");
            function cleanForBridge(data, isPathAllowed) {
              var path108 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : [];
              if (data !== null) {
                var cleanedPaths = [];
                var unserializablePaths = [];
                var cleanedData = dehydrate(data, cleanedPaths, unserializablePaths, path108, isPathAllowed);
                return {
                  data: cleanedData,
                  cleaned: cleanedPaths,
                  unserializable: unserializablePaths
                };
              } else {
                return null;
              }
            }
            __name(cleanForBridge, "cleanForBridge");
            function copyWithDelete(obj, path108) {
              var index = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 0;
              var key = path108[index];
              var updated = shared_isArray(obj) ? obj.slice() : utils_objectSpread({}, obj);
              if (index + 1 === path108.length) {
                if (shared_isArray(updated)) {
                  updated.splice(key, 1);
                } else {
                  delete updated[key];
                }
              } else {
                updated[key] = copyWithDelete(obj[key], path108, index + 1);
              }
              return updated;
            }
            __name(copyWithDelete, "copyWithDelete");
            function copyWithRename(obj, oldPath, newPath) {
              var index = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0;
              var oldKey = oldPath[index];
              var updated = shared_isArray(obj) ? obj.slice() : utils_objectSpread({}, obj);
              if (index + 1 === oldPath.length) {
                var newKey = newPath[index];
                updated[newKey] = updated[oldKey];
                if (shared_isArray(updated)) {
                  updated.splice(oldKey, 1);
                } else {
                  delete updated[oldKey];
                }
              } else {
                updated[oldKey] = copyWithRename(obj[oldKey], oldPath, newPath, index + 1);
              }
              return updated;
            }
            __name(copyWithRename, "copyWithRename");
            function copyWithSet(obj, path108, value) {
              var index = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0;
              if (index >= path108.length) {
                return value;
              }
              var key = path108[index];
              var updated = shared_isArray(obj) ? obj.slice() : utils_objectSpread({}, obj);
              updated[key] = copyWithSet(obj[key], path108, value, index + 1);
              return updated;
            }
            __name(copyWithSet, "copyWithSet");
            function getEffectDurations(root) {
              var effectDuration = null;
              var passiveEffectDuration = null;
              var hostRoot = root.current;
              if (hostRoot != null) {
                var stateNode = hostRoot.stateNode;
                if (stateNode != null) {
                  effectDuration = stateNode.effectDuration != null ? stateNode.effectDuration : null;
                  passiveEffectDuration = stateNode.passiveEffectDuration != null ? stateNode.passiveEffectDuration : null;
                }
              }
              return {
                effectDuration,
                passiveEffectDuration
              };
            }
            __name(getEffectDurations, "getEffectDurations");
            function serializeToString(data) {
              if (data === void 0) {
                return "undefined";
              }
              var cache5 = /* @__PURE__ */ new Set();
              return JSON.stringify(data, function(key, value) {
                if (backend_utils_typeof(value) === "object" && value !== null) {
                  if (cache5.has(value)) {
                    return;
                  }
                  cache5.add(value);
                }
                if (typeof value === "bigint") {
                  return value.toString() + "n";
                }
                return value;
              }, 2);
            }
            __name(serializeToString, "serializeToString");
            function formatWithStyles(inputArgs, style) {
              if (inputArgs === void 0 || inputArgs === null || inputArgs.length === 0 || // Matches any of %c but not %%c
              typeof inputArgs[0] === "string" && inputArgs[0].match(/([^%]|^)(%c)/g) || style === void 0) {
                return inputArgs;
              }
              var REGEXP = /([^%]|^)((%%)*)(%([oOdisf]))/g;
              if (typeof inputArgs[0] === "string" && inputArgs[0].match(REGEXP)) {
                return ["%c".concat(inputArgs[0]), style].concat(utils_toConsumableArray(inputArgs.slice(1)));
              } else {
                var firstArg = inputArgs.reduce(function(formatStr, elem, i) {
                  if (i > 0) {
                    formatStr += " ";
                  }
                  switch (backend_utils_typeof(elem)) {
                    case "string":
                    case "boolean":
                    case "symbol":
                      return formatStr += "%s";
                    case "number":
                      var formatting = Number.isInteger(elem) ? "%i" : "%f";
                      return formatStr += formatting;
                    default:
                      return formatStr += "%o";
                  }
                }, "%c");
                return [firstArg, style].concat(utils_toConsumableArray(inputArgs));
              }
            }
            __name(formatWithStyles, "formatWithStyles");
            function format4(maybeMessage) {
              for (var _len = arguments.length, inputArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                inputArgs[_key - 1] = arguments[_key];
              }
              var args = inputArgs.slice();
              var formatted = String(maybeMessage);
              if (typeof maybeMessage === "string") {
                if (args.length) {
                  var REGEXP = /(%?)(%([jds]))/g;
                  formatted = formatted.replace(REGEXP, function(match2, escaped, ptn, flag) {
                    var arg = args.shift();
                    switch (flag) {
                      case "s":
                        arg += "";
                        break;
                      case "d":
                      case "i":
                        arg = parseInt(arg, 10).toString();
                        break;
                      case "f":
                        arg = parseFloat(arg).toString();
                        break;
                    }
                    if (!escaped) {
                      return arg;
                    }
                    args.unshift(arg);
                    return match2;
                  });
                }
              }
              if (args.length) {
                for (var i = 0; i < args.length; i++) {
                  formatted += " " + String(args[i]);
                }
              }
              formatted = formatted.replace(/%{2,2}/g, "%");
              return String(formatted);
            }
            __name(format4, "format");
            function isSynchronousXHRSupported() {
              return !!(window.document && window.document.featurePolicy && window.document.featurePolicy.allowsFeature("sync-xhr"));
            }
            __name(isSynchronousXHRSupported, "isSynchronousXHRSupported");
            function gt() {
              var a = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
              var b = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
              return compareVersions(a, b) === 1;
            }
            __name(gt, "gt");
            function gte() {
              var a = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
              var b = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
              return compareVersions(a, b) > -1;
            }
            __name(gte, "gte");
            var react_debug_tools = __webpack_require__(987);
            ;
            var CONCURRENT_MODE_NUMBER = 60111;
            var CONCURRENT_MODE_SYMBOL_STRING = "Symbol(react.concurrent_mode)";
            var CONTEXT_NUMBER = 60110;
            var CONTEXT_SYMBOL_STRING = "Symbol(react.context)";
            var SERVER_CONTEXT_SYMBOL_STRING = "Symbol(react.server_context)";
            var DEPRECATED_ASYNC_MODE_SYMBOL_STRING = "Symbol(react.async_mode)";
            var ELEMENT_NUMBER = 60103;
            var ELEMENT_SYMBOL_STRING = "Symbol(react.element)";
            var DEBUG_TRACING_MODE_NUMBER = 60129;
            var DEBUG_TRACING_MODE_SYMBOL_STRING = "Symbol(react.debug_trace_mode)";
            var ReactSymbols_FORWARD_REF_NUMBER = 60112;
            var ReactSymbols_FORWARD_REF_SYMBOL_STRING = "Symbol(react.forward_ref)";
            var FRAGMENT_NUMBER = 60107;
            var FRAGMENT_SYMBOL_STRING = "Symbol(react.fragment)";
            var ReactSymbols_LAZY_NUMBER = 60116;
            var ReactSymbols_LAZY_SYMBOL_STRING = "Symbol(react.lazy)";
            var ReactSymbols_MEMO_NUMBER = 60115;
            var ReactSymbols_MEMO_SYMBOL_STRING = "Symbol(react.memo)";
            var PORTAL_NUMBER = 60106;
            var PORTAL_SYMBOL_STRING = "Symbol(react.portal)";
            var PROFILER_NUMBER = 60114;
            var PROFILER_SYMBOL_STRING = "Symbol(react.profiler)";
            var PROVIDER_NUMBER = 60109;
            var PROVIDER_SYMBOL_STRING = "Symbol(react.provider)";
            var SCOPE_NUMBER = 60119;
            var SCOPE_SYMBOL_STRING = "Symbol(react.scope)";
            var STRICT_MODE_NUMBER = 60108;
            var STRICT_MODE_SYMBOL_STRING = "Symbol(react.strict_mode)";
            var ReactSymbols_SUSPENSE_NUMBER = 60113;
            var ReactSymbols_SUSPENSE_SYMBOL_STRING = "Symbol(react.suspense)";
            var ReactSymbols_SUSPENSE_LIST_NUMBER = 60120;
            var ReactSymbols_SUSPENSE_LIST_SYMBOL_STRING = "Symbol(react.suspense_list)";
            var SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED_SYMBOL_STRING = "Symbol(react.server_context.defaultValue)";
            ;
            var consoleManagedByDevToolsDuringStrictMode = false;
            var enableLogger = false;
            var enableStyleXFeatures = false;
            var isInternalFacebookBuild = false;
            null;
            ;
            function is(x, y) {
              return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y;
            }
            __name(is, "is");
            var objectIs = (
              // $FlowFixMe[method-unbinding]
              typeof Object.is === "function" ? Object.is : is
            );
            const shared_objectIs = objectIs;
            ;
            var hasOwnProperty_hasOwnProperty = Object.prototype.hasOwnProperty;
            const shared_hasOwnProperty = hasOwnProperty_hasOwnProperty;
            ;
            var cachedStyleNameToValueMap = /* @__PURE__ */ new Map();
            function getStyleXData(data) {
              var sources = /* @__PURE__ */ new Set();
              var resolvedStyles = {};
              crawlData(data, sources, resolvedStyles);
              return {
                sources: Array.from(sources).sort(),
                resolvedStyles
              };
            }
            __name(getStyleXData, "getStyleXData");
            function crawlData(data, sources, resolvedStyles) {
              if (data == null) {
                return;
              }
              if (src_isArray(data)) {
                data.forEach(function(entry) {
                  if (entry == null) {
                    return;
                  }
                  if (src_isArray(entry)) {
                    crawlData(entry, sources, resolvedStyles);
                  } else {
                    crawlObjectProperties(entry, sources, resolvedStyles);
                  }
                });
              } else {
                crawlObjectProperties(data, sources, resolvedStyles);
              }
              resolvedStyles = Object.fromEntries(Object.entries(resolvedStyles).sort());
            }
            __name(crawlData, "crawlData");
            function crawlObjectProperties(entry, sources, resolvedStyles) {
              var keys = Object.keys(entry);
              keys.forEach(function(key) {
                var value = entry[key];
                if (typeof value === "string") {
                  if (key === value) {
                    sources.add(key);
                  } else {
                    var propertyValue = getPropertyValueForStyleName(value);
                    if (propertyValue != null) {
                      resolvedStyles[key] = propertyValue;
                    }
                  }
                } else {
                  var nestedStyle = {};
                  resolvedStyles[key] = nestedStyle;
                  crawlData([value], sources, nestedStyle);
                }
              });
            }
            __name(crawlObjectProperties, "crawlObjectProperties");
            function getPropertyValueForStyleName(styleName) {
              if (cachedStyleNameToValueMap.has(styleName)) {
                return cachedStyleNameToValueMap.get(styleName);
              }
              for (var styleSheetIndex = 0; styleSheetIndex < document.styleSheets.length; styleSheetIndex++) {
                var styleSheet = document.styleSheets[styleSheetIndex];
                var rules = null;
                try {
                  rules = styleSheet.cssRules;
                } catch (_e) {
                  continue;
                }
                for (var ruleIndex = 0; ruleIndex < rules.length; ruleIndex++) {
                  if (!(rules[ruleIndex] instanceof CSSStyleRule)) {
                    continue;
                  }
                  var rule = rules[ruleIndex];
                  var cssText = rule.cssText, selectorText = rule.selectorText, style = rule.style;
                  if (selectorText != null) {
                    if (selectorText.startsWith(".".concat(styleName))) {
                      var match2 = cssText.match(/{ *([a-z\-]+):/);
                      if (match2 !== null) {
                        var property = match2[1];
                        var value = style.getPropertyValue(property);
                        cachedStyleNameToValueMap.set(styleName, value);
                        return value;
                      } else {
                        return null;
                      }
                    }
                  }
                }
              }
              return null;
            }
            __name(getPropertyValueForStyleName, "getPropertyValueForStyleName");
            ;
            var CHANGE_LOG_URL = "https://github.com/facebook/react/blob/main/packages/react-devtools/CHANGELOG.md";
            var UNSUPPORTED_VERSION_URL = "https://reactjs.org/blog/2019/08/15/new-react-devtools.html#how-do-i-get-the-old-version-back";
            var REACT_DEVTOOLS_WORKPLACE_URL = "https://fburl.com/react-devtools-workplace-group";
            var THEME_STYLES = {
              light: {
                "--color-attribute-name": "#ef6632",
                "--color-attribute-name-not-editable": "#23272f",
                "--color-attribute-name-inverted": "rgba(255, 255, 255, 0.7)",
                "--color-attribute-value": "#1a1aa6",
                "--color-attribute-value-inverted": "#ffffff",
                "--color-attribute-editable-value": "#1a1aa6",
                "--color-background": "#ffffff",
                "--color-background-hover": "rgba(0, 136, 250, 0.1)",
                "--color-background-inactive": "#e5e5e5",
                "--color-background-invalid": "#fff0f0",
                "--color-background-selected": "#0088fa",
                "--color-button-background": "#ffffff",
                "--color-button-background-focus": "#ededed",
                "--color-button": "#5f6673",
                "--color-button-disabled": "#cfd1d5",
                "--color-button-active": "#0088fa",
                "--color-button-focus": "#23272f",
                "--color-button-hover": "#23272f",
                "--color-border": "#eeeeee",
                "--color-commit-did-not-render-fill": "#cfd1d5",
                "--color-commit-did-not-render-fill-text": "#000000",
                "--color-commit-did-not-render-pattern": "#cfd1d5",
                "--color-commit-did-not-render-pattern-text": "#333333",
                "--color-commit-gradient-0": "#37afa9",
                "--color-commit-gradient-1": "#63b19e",
                "--color-commit-gradient-2": "#80b393",
                "--color-commit-gradient-3": "#97b488",
                "--color-commit-gradient-4": "#abb67d",
                "--color-commit-gradient-5": "#beb771",
                "--color-commit-gradient-6": "#cfb965",
                "--color-commit-gradient-7": "#dfba57",
                "--color-commit-gradient-8": "#efbb49",
                "--color-commit-gradient-9": "#febc38",
                "--color-commit-gradient-text": "#000000",
                "--color-component-name": "#6a51b2",
                "--color-component-name-inverted": "#ffffff",
                "--color-component-badge-background": "rgba(0, 0, 0, 0.1)",
                "--color-component-badge-background-inverted": "rgba(255, 255, 255, 0.25)",
                "--color-component-badge-count": "#777d88",
                "--color-component-badge-count-inverted": "rgba(255, 255, 255, 0.7)",
                "--color-console-error-badge-text": "#ffffff",
                "--color-console-error-background": "#fff0f0",
                "--color-console-error-border": "#ffd6d6",
                "--color-console-error-icon": "#eb3941",
                "--color-console-error-text": "#fe2e31",
                "--color-console-warning-badge-text": "#000000",
                "--color-console-warning-background": "#fffbe5",
                "--color-console-warning-border": "#fff5c1",
                "--color-console-warning-icon": "#f4bd00",
                "--color-console-warning-text": "#64460c",
                "--color-context-background": "rgba(0,0,0,.9)",
                "--color-context-background-hover": "rgba(255, 255, 255, 0.1)",
                "--color-context-background-selected": "#178fb9",
                "--color-context-border": "#3d424a",
                "--color-context-text": "#ffffff",
                "--color-context-text-selected": "#ffffff",
                "--color-dim": "#777d88",
                "--color-dimmer": "#cfd1d5",
                "--color-dimmest": "#eff0f1",
                "--color-error-background": "hsl(0, 100%, 97%)",
                "--color-error-border": "hsl(0, 100%, 92%)",
                "--color-error-text": "#ff0000",
                "--color-expand-collapse-toggle": "#777d88",
                "--color-link": "#0000ff",
                "--color-modal-background": "rgba(255, 255, 255, 0.75)",
                "--color-bridge-version-npm-background": "#eff0f1",
                "--color-bridge-version-npm-text": "#000000",
                "--color-bridge-version-number": "#0088fa",
                "--color-primitive-hook-badge-background": "#e5e5e5",
                "--color-primitive-hook-badge-text": "#5f6673",
                "--color-record-active": "#fc3a4b",
                "--color-record-hover": "#3578e5",
                "--color-record-inactive": "#0088fa",
                "--color-resize-bar": "#eeeeee",
                "--color-resize-bar-active": "#dcdcdc",
                "--color-resize-bar-border": "#d1d1d1",
                "--color-resize-bar-dot": "#333333",
                "--color-timeline-internal-module": "#d1d1d1",
                "--color-timeline-internal-module-hover": "#c9c9c9",
                "--color-timeline-internal-module-text": "#444",
                "--color-timeline-native-event": "#ccc",
                "--color-timeline-native-event-hover": "#aaa",
                "--color-timeline-network-primary": "#fcf3dc",
                "--color-timeline-network-primary-hover": "#f0e7d1",
                "--color-timeline-network-secondary": "#efc457",
                "--color-timeline-network-secondary-hover": "#e3ba52",
                "--color-timeline-priority-background": "#f6f6f6",
                "--color-timeline-priority-border": "#eeeeee",
                "--color-timeline-user-timing": "#c9cacd",
                "--color-timeline-user-timing-hover": "#93959a",
                "--color-timeline-react-idle": "#d3e5f6",
                "--color-timeline-react-idle-hover": "#c3d9ef",
                "--color-timeline-react-render": "#9fc3f3",
                "--color-timeline-react-render-hover": "#83afe9",
                "--color-timeline-react-render-text": "#11365e",
                "--color-timeline-react-commit": "#c88ff0",
                "--color-timeline-react-commit-hover": "#b281d6",
                "--color-timeline-react-commit-text": "#3e2c4a",
                "--color-timeline-react-layout-effects": "#b281d6",
                "--color-timeline-react-layout-effects-hover": "#9d71bd",
                "--color-timeline-react-layout-effects-text": "#3e2c4a",
                "--color-timeline-react-passive-effects": "#b281d6",
                "--color-timeline-react-passive-effects-hover": "#9d71bd",
                "--color-timeline-react-passive-effects-text": "#3e2c4a",
                "--color-timeline-react-schedule": "#9fc3f3",
                "--color-timeline-react-schedule-hover": "#2683E2",
                "--color-timeline-react-suspense-rejected": "#f1cc14",
                "--color-timeline-react-suspense-rejected-hover": "#ffdf37",
                "--color-timeline-react-suspense-resolved": "#a6e59f",
                "--color-timeline-react-suspense-resolved-hover": "#89d281",
                "--color-timeline-react-suspense-unresolved": "#c9cacd",
                "--color-timeline-react-suspense-unresolved-hover": "#93959a",
                "--color-timeline-thrown-error": "#ee1638",
                "--color-timeline-thrown-error-hover": "#da1030",
                "--color-timeline-text-color": "#000000",
                "--color-timeline-text-dim-color": "#ccc",
                "--color-timeline-react-work-border": "#eeeeee",
                "--color-search-match": "yellow",
                "--color-search-match-current": "#f7923b",
                "--color-selected-tree-highlight-active": "rgba(0, 136, 250, 0.1)",
                "--color-selected-tree-highlight-inactive": "rgba(0, 0, 0, 0.05)",
                "--color-scroll-caret": "rgba(150, 150, 150, 0.5)",
                "--color-tab-selected-border": "#0088fa",
                "--color-text": "#000000",
                "--color-text-invalid": "#ff0000",
                "--color-text-selected": "#ffffff",
                "--color-toggle-background-invalid": "#fc3a4b",
                "--color-toggle-background-on": "#0088fa",
                "--color-toggle-background-off": "#cfd1d5",
                "--color-toggle-text": "#ffffff",
                "--color-warning-background": "#fb3655",
                "--color-warning-background-hover": "#f82042",
                "--color-warning-text-color": "#ffffff",
                "--color-warning-text-color-inverted": "#fd4d69",
                // The styles below should be kept in sync with 'root.css'
                // They are repeated there because they're used by e.g. tooltips or context menus
                // which get rendered outside of the DOM subtree (where normal theme/styles are written).
                "--color-scroll-thumb": "#c2c2c2",
                "--color-scroll-track": "#fafafa",
                "--color-tooltip-background": "rgba(0, 0, 0, 0.9)",
                "--color-tooltip-text": "#ffffff"
              },
              dark: {
                "--color-attribute-name": "#9d87d2",
                "--color-attribute-name-not-editable": "#ededed",
                "--color-attribute-name-inverted": "#282828",
                "--color-attribute-value": "#cedae0",
                "--color-attribute-value-inverted": "#ffffff",
                "--color-attribute-editable-value": "yellow",
                "--color-background": "#282c34",
                "--color-background-hover": "rgba(255, 255, 255, 0.1)",
                "--color-background-inactive": "#3d424a",
                "--color-background-invalid": "#5c0000",
                "--color-background-selected": "#178fb9",
                "--color-button-background": "#282c34",
                "--color-button-background-focus": "#3d424a",
                "--color-button": "#afb3b9",
                "--color-button-active": "#61dafb",
                "--color-button-disabled": "#4f5766",
                "--color-button-focus": "#a2e9fc",
                "--color-button-hover": "#ededed",
                "--color-border": "#3d424a",
                "--color-commit-did-not-render-fill": "#777d88",
                "--color-commit-did-not-render-fill-text": "#000000",
                "--color-commit-did-not-render-pattern": "#666c77",
                "--color-commit-did-not-render-pattern-text": "#ffffff",
                "--color-commit-gradient-0": "#37afa9",
                "--color-commit-gradient-1": "#63b19e",
                "--color-commit-gradient-2": "#80b393",
                "--color-commit-gradient-3": "#97b488",
                "--color-commit-gradient-4": "#abb67d",
                "--color-commit-gradient-5": "#beb771",
                "--color-commit-gradient-6": "#cfb965",
                "--color-commit-gradient-7": "#dfba57",
                "--color-commit-gradient-8": "#efbb49",
                "--color-commit-gradient-9": "#febc38",
                "--color-commit-gradient-text": "#000000",
                "--color-component-name": "#61dafb",
                "--color-component-name-inverted": "#282828",
                "--color-component-badge-background": "rgba(255, 255, 255, 0.25)",
                "--color-component-badge-background-inverted": "rgba(0, 0, 0, 0.25)",
                "--color-component-badge-count": "#8f949d",
                "--color-component-badge-count-inverted": "rgba(255, 255, 255, 0.7)",
                "--color-console-error-badge-text": "#000000",
                "--color-console-error-background": "#290000",
                "--color-console-error-border": "#5c0000",
                "--color-console-error-icon": "#eb3941",
                "--color-console-error-text": "#fc7f7f",
                "--color-console-warning-badge-text": "#000000",
                "--color-console-warning-background": "#332b00",
                "--color-console-warning-border": "#665500",
                "--color-console-warning-icon": "#f4bd00",
                "--color-console-warning-text": "#f5f2ed",
                "--color-context-background": "rgba(255,255,255,.95)",
                "--color-context-background-hover": "rgba(0, 136, 250, 0.1)",
                "--color-context-background-selected": "#0088fa",
                "--color-context-border": "#eeeeee",
                "--color-context-text": "#000000",
                "--color-context-text-selected": "#ffffff",
                "--color-dim": "#8f949d",
                "--color-dimmer": "#777d88",
                "--color-dimmest": "#4f5766",
                "--color-error-background": "#200",
                "--color-error-border": "#900",
                "--color-error-text": "#f55",
                "--color-expand-collapse-toggle": "#8f949d",
                "--color-link": "#61dafb",
                "--color-modal-background": "rgba(0, 0, 0, 0.75)",
                "--color-bridge-version-npm-background": "rgba(0, 0, 0, 0.25)",
                "--color-bridge-version-npm-text": "#ffffff",
                "--color-bridge-version-number": "yellow",
                "--color-primitive-hook-badge-background": "rgba(0, 0, 0, 0.25)",
                "--color-primitive-hook-badge-text": "rgba(255, 255, 255, 0.7)",
                "--color-record-active": "#fc3a4b",
                "--color-record-hover": "#a2e9fc",
                "--color-record-inactive": "#61dafb",
                "--color-resize-bar": "#282c34",
                "--color-resize-bar-active": "#31363f",
                "--color-resize-bar-border": "#3d424a",
                "--color-resize-bar-dot": "#cfd1d5",
                "--color-timeline-internal-module": "#303542",
                "--color-timeline-internal-module-hover": "#363b4a",
                "--color-timeline-internal-module-text": "#7f8899",
                "--color-timeline-native-event": "#b2b2b2",
                "--color-timeline-native-event-hover": "#949494",
                "--color-timeline-network-primary": "#fcf3dc",
                "--color-timeline-network-primary-hover": "#e3dbc5",
                "--color-timeline-network-secondary": "#efc457",
                "--color-timeline-network-secondary-hover": "#d6af4d",
                "--color-timeline-priority-background": "#1d2129",
                "--color-timeline-priority-border": "#282c34",
                "--color-timeline-user-timing": "#c9cacd",
                "--color-timeline-user-timing-hover": "#93959a",
                "--color-timeline-react-idle": "#3d485b",
                "--color-timeline-react-idle-hover": "#465269",
                "--color-timeline-react-render": "#2683E2",
                "--color-timeline-react-render-hover": "#1a76d4",
                "--color-timeline-react-render-text": "#11365e",
                "--color-timeline-react-commit": "#731fad",
                "--color-timeline-react-commit-hover": "#611b94",
                "--color-timeline-react-commit-text": "#e5c1ff",
                "--color-timeline-react-layout-effects": "#611b94",
                "--color-timeline-react-layout-effects-hover": "#51167a",
                "--color-timeline-react-layout-effects-text": "#e5c1ff",
                "--color-timeline-react-passive-effects": "#611b94",
                "--color-timeline-react-passive-effects-hover": "#51167a",
                "--color-timeline-react-passive-effects-text": "#e5c1ff",
                "--color-timeline-react-schedule": "#2683E2",
                "--color-timeline-react-schedule-hover": "#1a76d4",
                "--color-timeline-react-suspense-rejected": "#f1cc14",
                "--color-timeline-react-suspense-rejected-hover": "#e4c00f",
                "--color-timeline-react-suspense-resolved": "#a6e59f",
                "--color-timeline-react-suspense-resolved-hover": "#89d281",
                "--color-timeline-react-suspense-unresolved": "#c9cacd",
                "--color-timeline-react-suspense-unresolved-hover": "#93959a",
                "--color-timeline-thrown-error": "#fb3655",
                "--color-timeline-thrown-error-hover": "#f82042",
                "--color-timeline-text-color": "#282c34",
                "--color-timeline-text-dim-color": "#555b66",
                "--color-timeline-react-work-border": "#3d424a",
                "--color-search-match": "yellow",
                "--color-search-match-current": "#f7923b",
                "--color-selected-tree-highlight-active": "rgba(23, 143, 185, 0.15)",
                "--color-selected-tree-highlight-inactive": "rgba(255, 255, 255, 0.05)",
                "--color-scroll-caret": "#4f5766",
                "--color-shadow": "rgba(0, 0, 0, 0.5)",
                "--color-tab-selected-border": "#178fb9",
                "--color-text": "#ffffff",
                "--color-text-invalid": "#ff8080",
                "--color-text-selected": "#ffffff",
                "--color-toggle-background-invalid": "#fc3a4b",
                "--color-toggle-background-on": "#178fb9",
                "--color-toggle-background-off": "#777d88",
                "--color-toggle-text": "#ffffff",
                "--color-warning-background": "#ee1638",
                "--color-warning-background-hover": "#da1030",
                "--color-warning-text-color": "#ffffff",
                "--color-warning-text-color-inverted": "#ee1638",
                // The styles below should be kept in sync with 'root.css'
                // They are repeated there because they're used by e.g. tooltips or context menus
                // which get rendered outside of the DOM subtree (where normal theme/styles are written).
                "--color-scroll-thumb": "#afb3b9",
                "--color-scroll-track": "#313640",
                "--color-tooltip-background": "rgba(255, 255, 255, 0.95)",
                "--color-tooltip-text": "#000000"
              },
              compact: {
                "--font-size-monospace-small": "9px",
                "--font-size-monospace-normal": "11px",
                "--font-size-monospace-large": "15px",
                "--font-size-sans-small": "10px",
                "--font-size-sans-normal": "12px",
                "--font-size-sans-large": "14px",
                "--line-height-data": "18px"
              },
              comfortable: {
                "--font-size-monospace-small": "10px",
                "--font-size-monospace-normal": "13px",
                "--font-size-monospace-large": "17px",
                "--font-size-sans-small": "12px",
                "--font-size-sans-normal": "14px",
                "--font-size-sans-large": "16px",
                "--line-height-data": "22px"
              }
            };
            var COMFORTABLE_LINE_HEIGHT = parseInt(THEME_STYLES.comfortable["--line-height-data"], 10);
            var COMPACT_LINE_HEIGHT = parseInt(THEME_STYLES.compact["--line-height-data"], 10);
            ;
            var REACT_TOTAL_NUM_LANES = 31;
            var SCHEDULING_PROFILER_VERSION = 1;
            var SNAPSHOT_MAX_HEIGHT = 60;
            ;
            function DevToolsConsolePatching_ownKeys(object, enumerableOnly) {
              var keys = Object.keys(object);
              if (Object.getOwnPropertySymbols) {
                var symbols = Object.getOwnPropertySymbols(object);
                if (enumerableOnly) symbols = symbols.filter(function(sym) {
                  return Object.getOwnPropertyDescriptor(object, sym).enumerable;
                });
                keys.push.apply(keys, symbols);
              }
              return keys;
            }
            __name(DevToolsConsolePatching_ownKeys, "DevToolsConsolePatching_ownKeys");
            function DevToolsConsolePatching_objectSpread(target) {
              for (var i = 1; i < arguments.length; i++) {
                var source2 = arguments[i] != null ? arguments[i] : {};
                if (i % 2) {
                  DevToolsConsolePatching_ownKeys(Object(source2), true).forEach(function(key) {
                    DevToolsConsolePatching_defineProperty(target, key, source2[key]);
                  });
                } else if (Object.getOwnPropertyDescriptors) {
                  Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
                } else {
                  DevToolsConsolePatching_ownKeys(Object(source2)).forEach(function(key) {
                    Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
                  });
                }
              }
              return target;
            }
            __name(DevToolsConsolePatching_objectSpread, "DevToolsConsolePatching_objectSpread");
            function DevToolsConsolePatching_defineProperty(obj, key, value) {
              if (key in obj) {
                Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
              } else {
                obj[key] = value;
              }
              return obj;
            }
            __name(DevToolsConsolePatching_defineProperty, "DevToolsConsolePatching_defineProperty");
            var disabledDepth = 0;
            var prevLog;
            var prevInfo;
            var prevWarn;
            var prevError;
            var prevGroup;
            var prevGroupCollapsed;
            var prevGroupEnd;
            function disabledLog() {
            }
            __name(disabledLog, "disabledLog");
            disabledLog.__reactDisabledLog = true;
            function disableLogs() {
              if (disabledDepth === 0) {
                prevLog = console.log;
                prevInfo = console.info;
                prevWarn = console.warn;
                prevError = console.error;
                prevGroup = console.group;
                prevGroupCollapsed = console.groupCollapsed;
                prevGroupEnd = console.groupEnd;
                var props = {
                  configurable: true,
                  enumerable: true,
                  value: disabledLog,
                  writable: true
                };
                Object.defineProperties(console, {
                  info: props,
                  log: props,
                  warn: props,
                  error: props,
                  group: props,
                  groupCollapsed: props,
                  groupEnd: props
                });
              }
              disabledDepth++;
            }
            __name(disableLogs, "disableLogs");
            function reenableLogs() {
              disabledDepth--;
              if (disabledDepth === 0) {
                var props = {
                  configurable: true,
                  enumerable: true,
                  writable: true
                };
                Object.defineProperties(console, {
                  log: DevToolsConsolePatching_objectSpread(DevToolsConsolePatching_objectSpread({}, props), {}, {
                    value: prevLog
                  }),
                  info: DevToolsConsolePatching_objectSpread(DevToolsConsolePatching_objectSpread({}, props), {}, {
                    value: prevInfo
                  }),
                  warn: DevToolsConsolePatching_objectSpread(DevToolsConsolePatching_objectSpread({}, props), {}, {
                    value: prevWarn
                  }),
                  error: DevToolsConsolePatching_objectSpread(DevToolsConsolePatching_objectSpread({}, props), {}, {
                    value: prevError
                  }),
                  group: DevToolsConsolePatching_objectSpread(DevToolsConsolePatching_objectSpread({}, props), {}, {
                    value: prevGroup
                  }),
                  groupCollapsed: DevToolsConsolePatching_objectSpread(DevToolsConsolePatching_objectSpread({}, props), {}, {
                    value: prevGroupCollapsed
                  }),
                  groupEnd: DevToolsConsolePatching_objectSpread(DevToolsConsolePatching_objectSpread({}, props), {}, {
                    value: prevGroupEnd
                  })
                });
              }
              if (disabledDepth < 0) {
                console.error("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
              }
            }
            __name(reenableLogs, "reenableLogs");
            ;
            function DevToolsComponentStackFrame_typeof(obj) {
              "@babel/helpers - typeof";
              if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                DevToolsComponentStackFrame_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return typeof obj2;
                }, "_typeof");
              } else {
                DevToolsComponentStackFrame_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                }, "_typeof");
              }
              return DevToolsComponentStackFrame_typeof(obj);
            }
            __name(DevToolsComponentStackFrame_typeof, "DevToolsComponentStackFrame_typeof");
            var prefix;
            function describeBuiltInComponentFrame(name3, ownerFn) {
              if (prefix === void 0) {
                try {
                  throw Error();
                } catch (x) {
                  var match2 = x.stack.trim().match(/\n( *(at )?)/);
                  prefix = match2 && match2[1] || "";
                }
              }
              return "\n" + prefix + name3;
            }
            __name(describeBuiltInComponentFrame, "describeBuiltInComponentFrame");
            var reentry = false;
            var componentFrameCache;
            if (false) {
              var PossiblyWeakMap;
            }
            function describeNativeComponentFrame(fn, construct, currentDispatcherRef) {
              if (!fn || reentry) {
                return "";
              }
              if (false) {
                var frame;
              }
              var control;
              var previousPrepareStackTrace = Error.prepareStackTrace;
              Error.prepareStackTrace = void 0;
              reentry = true;
              var previousDispatcher = currentDispatcherRef.current;
              currentDispatcherRef.current = null;
              disableLogs();
              try {
                if (construct) {
                  var Fake = /* @__PURE__ */ __name(function Fake2() {
                    throw Error();
                  }, "Fake");
                  Object.defineProperty(Fake.prototype, "props", {
                    set: /* @__PURE__ */ __name(function set() {
                      throw Error();
                    }, "set")
                  });
                  if ((typeof Reflect === "undefined" ? "undefined" : DevToolsComponentStackFrame_typeof(Reflect)) === "object" && Reflect.construct) {
                    try {
                      Reflect.construct(Fake, []);
                    } catch (x) {
                      control = x;
                    }
                    Reflect.construct(fn, [], Fake);
                  } else {
                    try {
                      Fake.call();
                    } catch (x) {
                      control = x;
                    }
                    fn.call(Fake.prototype);
                  }
                } else {
                  try {
                    throw Error();
                  } catch (x) {
                    control = x;
                  }
                  fn();
                }
              } catch (sample) {
                if (sample && control && typeof sample.stack === "string") {
                  var sampleLines = sample.stack.split("\n");
                  var controlLines = control.stack.split("\n");
                  var s2 = sampleLines.length - 1;
                  var c3 = controlLines.length - 1;
                  while (s2 >= 1 && c3 >= 0 && sampleLines[s2] !== controlLines[c3]) {
                    c3--;
                  }
                  for (; s2 >= 1 && c3 >= 0; s2--, c3--) {
                    if (sampleLines[s2] !== controlLines[c3]) {
                      if (s2 !== 1 || c3 !== 1) {
                        do {
                          s2--;
                          c3--;
                          if (c3 < 0 || sampleLines[s2] !== controlLines[c3]) {
                            var _frame = "\n" + sampleLines[s2].replace(" at new ", " at ");
                            if (false) {
                            }
                            return _frame;
                          }
                        } while (s2 >= 1 && c3 >= 0);
                      }
                      break;
                    }
                  }
                }
              } finally {
                reentry = false;
                Error.prepareStackTrace = previousPrepareStackTrace;
                currentDispatcherRef.current = previousDispatcher;
                reenableLogs();
              }
              var name3 = fn ? fn.displayName || fn.name : "";
              var syntheticFrame = name3 ? describeBuiltInComponentFrame(name3) : "";
              if (false) {
              }
              return syntheticFrame;
            }
            __name(describeNativeComponentFrame, "describeNativeComponentFrame");
            function describeClassComponentFrame(ctor, ownerFn, currentDispatcherRef) {
              return describeNativeComponentFrame(ctor, true, currentDispatcherRef);
            }
            __name(describeClassComponentFrame, "describeClassComponentFrame");
            function describeFunctionComponentFrame(fn, ownerFn, currentDispatcherRef) {
              return describeNativeComponentFrame(fn, false, currentDispatcherRef);
            }
            __name(describeFunctionComponentFrame, "describeFunctionComponentFrame");
            function shouldConstruct(Component) {
              var prototype = Component.prototype;
              return !!(prototype && prototype.isReactComponent);
            }
            __name(shouldConstruct, "shouldConstruct");
            function describeUnknownElementTypeFrameInDEV(type, ownerFn, currentDispatcherRef) {
              if (true) {
                return "";
              }
              if (type == null) {
                return "";
              }
              if (typeof type === "function") {
                return describeNativeComponentFrame(type, shouldConstruct(type), currentDispatcherRef);
              }
              if (typeof type === "string") {
                return describeBuiltInComponentFrame(type, ownerFn);
              }
              switch (type) {
                case SUSPENSE_NUMBER:
                case SUSPENSE_SYMBOL_STRING:
                  return describeBuiltInComponentFrame("Suspense", ownerFn);
                case SUSPENSE_LIST_NUMBER:
                case SUSPENSE_LIST_SYMBOL_STRING:
                  return describeBuiltInComponentFrame("SuspenseList", ownerFn);
              }
              if (DevToolsComponentStackFrame_typeof(type) === "object") {
                switch (type.$$typeof) {
                  case FORWARD_REF_NUMBER:
                  case FORWARD_REF_SYMBOL_STRING:
                    return describeFunctionComponentFrame(type.render, ownerFn, currentDispatcherRef);
                  case MEMO_NUMBER:
                  case MEMO_SYMBOL_STRING:
                    return describeUnknownElementTypeFrameInDEV(type.type, ownerFn, currentDispatcherRef);
                  case LAZY_NUMBER:
                  case LAZY_SYMBOL_STRING: {
                    var lazyComponent = type;
                    var payload = lazyComponent._payload;
                    var init = lazyComponent._init;
                    try {
                      return describeUnknownElementTypeFrameInDEV(init(payload), ownerFn, currentDispatcherRef);
                    } catch (x) {
                    }
                  }
                }
              }
              return "";
            }
            __name(describeUnknownElementTypeFrameInDEV, "describeUnknownElementTypeFrameInDEV");
            ;
            function describeFiber(workTagMap, workInProgress, currentDispatcherRef) {
              var HostComponent = workTagMap.HostComponent, LazyComponent = workTagMap.LazyComponent, SuspenseComponent = workTagMap.SuspenseComponent, SuspenseListComponent = workTagMap.SuspenseListComponent, FunctionComponent = workTagMap.FunctionComponent, IndeterminateComponent = workTagMap.IndeterminateComponent, SimpleMemoComponent = workTagMap.SimpleMemoComponent, ForwardRef = workTagMap.ForwardRef, ClassComponent = workTagMap.ClassComponent;
              var owner = false ? 0 : null;
              switch (workInProgress.tag) {
                case HostComponent:
                  return describeBuiltInComponentFrame(workInProgress.type, owner);
                case LazyComponent:
                  return describeBuiltInComponentFrame("Lazy", owner);
                case SuspenseComponent:
                  return describeBuiltInComponentFrame("Suspense", owner);
                case SuspenseListComponent:
                  return describeBuiltInComponentFrame("SuspenseList", owner);
                case FunctionComponent:
                case IndeterminateComponent:
                case SimpleMemoComponent:
                  return describeFunctionComponentFrame(workInProgress.type, owner, currentDispatcherRef);
                case ForwardRef:
                  return describeFunctionComponentFrame(workInProgress.type.render, owner, currentDispatcherRef);
                case ClassComponent:
                  return describeClassComponentFrame(workInProgress.type, owner, currentDispatcherRef);
                default:
                  return "";
              }
            }
            __name(describeFiber, "describeFiber");
            function getStackByFiberInDevAndProd(workTagMap, workInProgress, currentDispatcherRef) {
              try {
                var info = "";
                var node = workInProgress;
                do {
                  info += describeFiber(workTagMap, node, currentDispatcherRef);
                  node = node.return;
                } while (node);
                return info;
              } catch (x) {
                return "\nError generating stack: " + x.message + "\n" + x.stack;
              }
            }
            __name(getStackByFiberInDevAndProd, "getStackByFiberInDevAndProd");
            ;
            function profilingHooks_slicedToArray(arr, i) {
              return profilingHooks_arrayWithHoles(arr) || profilingHooks_iterableToArrayLimit(arr, i) || profilingHooks_unsupportedIterableToArray(arr, i) || profilingHooks_nonIterableRest();
            }
            __name(profilingHooks_slicedToArray, "profilingHooks_slicedToArray");
            function profilingHooks_nonIterableRest() {
              throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
            }
            __name(profilingHooks_nonIterableRest, "profilingHooks_nonIterableRest");
            function profilingHooks_unsupportedIterableToArray(o2, minLen) {
              if (!o2) return;
              if (typeof o2 === "string") return profilingHooks_arrayLikeToArray(o2, minLen);
              var n2 = Object.prototype.toString.call(o2).slice(8, -1);
              if (n2 === "Object" && o2.constructor) n2 = o2.constructor.name;
              if (n2 === "Map" || n2 === "Set") return Array.from(o2);
              if (n2 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n2)) return profilingHooks_arrayLikeToArray(o2, minLen);
            }
            __name(profilingHooks_unsupportedIterableToArray, "profilingHooks_unsupportedIterableToArray");
            function profilingHooks_arrayLikeToArray(arr, len) {
              if (len == null || len > arr.length) len = arr.length;
              for (var i = 0, arr2 = new Array(len); i < len; i++) {
                arr2[i] = arr[i];
              }
              return arr2;
            }
            __name(profilingHooks_arrayLikeToArray, "profilingHooks_arrayLikeToArray");
            function profilingHooks_iterableToArrayLimit(arr, i) {
              if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
              var _arr = [];
              var _n = true;
              var _d = false;
              var _e = void 0;
              try {
                for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
                  _arr.push(_s.value);
                  if (i && _arr.length === i) break;
                }
              } catch (err) {
                _d = true;
                _e = err;
              } finally {
                try {
                  if (!_n && _i["return"] != null) _i["return"]();
                } finally {
                  if (_d) throw _e;
                }
              }
              return _arr;
            }
            __name(profilingHooks_iterableToArrayLimit, "profilingHooks_iterableToArrayLimit");
            function profilingHooks_arrayWithHoles(arr) {
              if (Array.isArray(arr)) return arr;
            }
            __name(profilingHooks_arrayWithHoles, "profilingHooks_arrayWithHoles");
            function profilingHooks_typeof(obj) {
              "@babel/helpers - typeof";
              if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                profilingHooks_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return typeof obj2;
                }, "_typeof");
              } else {
                profilingHooks_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                }, "_typeof");
              }
              return profilingHooks_typeof(obj);
            }
            __name(profilingHooks_typeof, "profilingHooks_typeof");
            var TIME_OFFSET = 10;
            var performanceTarget = null;
            var supportsUserTiming = typeof performance !== "undefined" && // $FlowFixMe[method-unbinding]
            typeof performance.mark === "function" && // $FlowFixMe[method-unbinding]
            typeof performance.clearMarks === "function";
            var supportsUserTimingV3 = false;
            if (supportsUserTiming) {
              var CHECK_V3_MARK = "__v3";
              var markOptions = {};
              Object.defineProperty(markOptions, "startTime", {
                get: /* @__PURE__ */ __name(function get3() {
                  supportsUserTimingV3 = true;
                  return 0;
                }, "get"),
                set: /* @__PURE__ */ __name(function set() {
                }, "set")
              });
              try {
                performance.mark(CHECK_V3_MARK, markOptions);
              } catch (error) {
              } finally {
                performance.clearMarks(CHECK_V3_MARK);
              }
            }
            if (supportsUserTimingV3) {
              performanceTarget = performance;
            }
            var profilingHooks_getCurrentTime = (
              // $FlowFixMe[method-unbinding]
              (typeof performance === "undefined" ? "undefined" : profilingHooks_typeof(performance)) === "object" && typeof performance.now === "function" ? function() {
                return performance.now();
              } : function() {
                return Date.now();
              }
            );
            function setPerformanceMock_ONLY_FOR_TESTING(performanceMock) {
              performanceTarget = performanceMock;
              supportsUserTiming = performanceMock !== null;
              supportsUserTimingV3 = performanceMock !== null;
            }
            __name(setPerformanceMock_ONLY_FOR_TESTING, "setPerformanceMock_ONLY_FOR_TESTING");
            function createProfilingHooks(_ref) {
              var getDisplayNameForFiber = _ref.getDisplayNameForFiber, getIsProfiling = _ref.getIsProfiling, getLaneLabelMap = _ref.getLaneLabelMap, workTagMap = _ref.workTagMap, currentDispatcherRef = _ref.currentDispatcherRef, reactVersion = _ref.reactVersion;
              var currentBatchUID = 0;
              var currentReactComponentMeasure = null;
              var currentReactMeasuresStack = [];
              var currentTimelineData = null;
              var currentFiberStacks = /* @__PURE__ */ new Map();
              var isProfiling = false;
              var nextRenderShouldStartNewBatch = false;
              function getRelativeTime() {
                var currentTime = profilingHooks_getCurrentTime();
                if (currentTimelineData) {
                  if (currentTimelineData.startTime === 0) {
                    currentTimelineData.startTime = currentTime - TIME_OFFSET;
                  }
                  return currentTime - currentTimelineData.startTime;
                }
                return 0;
              }
              __name(getRelativeTime, "getRelativeTime");
              function getInternalModuleRanges() {
                if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.getInternalModuleRanges === "function") {
                  var ranges2 = __REACT_DEVTOOLS_GLOBAL_HOOK__.getInternalModuleRanges();
                  if (shared_isArray(ranges2)) {
                    return ranges2;
                  }
                }
                return null;
              }
              __name(getInternalModuleRanges, "getInternalModuleRanges");
              function getTimelineData() {
                return currentTimelineData;
              }
              __name(getTimelineData, "getTimelineData");
              function laneToLanesArray(lanes) {
                var lanesArray = [];
                var lane = 1;
                for (var index = 0; index < REACT_TOTAL_NUM_LANES; index++) {
                  if (lane & lanes) {
                    lanesArray.push(lane);
                  }
                  lane *= 2;
                }
                return lanesArray;
              }
              __name(laneToLanesArray, "laneToLanesArray");
              var laneToLabelMap = typeof getLaneLabelMap === "function" ? getLaneLabelMap() : null;
              function markMetadata() {
                markAndClear("--react-version-".concat(reactVersion));
                markAndClear("--profiler-version-".concat(SCHEDULING_PROFILER_VERSION));
                var ranges2 = getInternalModuleRanges();
                if (ranges2) {
                  for (var i = 0; i < ranges2.length; i++) {
                    var range = ranges2[i];
                    if (shared_isArray(range) && range.length === 2) {
                      var _ranges$i = profilingHooks_slicedToArray(ranges2[i], 2), startStackFrame = _ranges$i[0], stopStackFrame = _ranges$i[1];
                      markAndClear("--react-internal-module-start-".concat(startStackFrame));
                      markAndClear("--react-internal-module-stop-".concat(stopStackFrame));
                    }
                  }
                }
                if (laneToLabelMap != null) {
                  var labels = Array.from(laneToLabelMap.values()).join(",");
                  markAndClear("--react-lane-labels-".concat(labels));
                }
              }
              __name(markMetadata, "markMetadata");
              function markAndClear(markName) {
                performanceTarget.mark(markName);
                performanceTarget.clearMarks(markName);
              }
              __name(markAndClear, "markAndClear");
              function recordReactMeasureStarted(type, lanes) {
                var depth = 0;
                if (currentReactMeasuresStack.length > 0) {
                  var top2 = currentReactMeasuresStack[currentReactMeasuresStack.length - 1];
                  depth = top2.type === "render-idle" ? top2.depth : top2.depth + 1;
                }
                var lanesArray = laneToLanesArray(lanes);
                var reactMeasure = {
                  type,
                  batchUID: currentBatchUID,
                  depth,
                  lanes: lanesArray,
                  timestamp: getRelativeTime(),
                  duration: 0
                };
                currentReactMeasuresStack.push(reactMeasure);
                if (currentTimelineData) {
                  var _currentTimelineData = currentTimelineData, batchUIDToMeasuresMap = _currentTimelineData.batchUIDToMeasuresMap, laneToReactMeasureMap = _currentTimelineData.laneToReactMeasureMap;
                  var reactMeasures = batchUIDToMeasuresMap.get(currentBatchUID);
                  if (reactMeasures != null) {
                    reactMeasures.push(reactMeasure);
                  } else {
                    batchUIDToMeasuresMap.set(currentBatchUID, [reactMeasure]);
                  }
                  lanesArray.forEach(function(lane) {
                    reactMeasures = laneToReactMeasureMap.get(lane);
                    if (reactMeasures) {
                      reactMeasures.push(reactMeasure);
                    }
                  });
                }
              }
              __name(recordReactMeasureStarted, "recordReactMeasureStarted");
              function recordReactMeasureCompleted(type) {
                var currentTime = getRelativeTime();
                if (currentReactMeasuresStack.length === 0) {
                  console.error('Unexpected type "%s" completed at %sms while currentReactMeasuresStack is empty.', type, currentTime);
                  return;
                }
                var top2 = currentReactMeasuresStack.pop();
                if (top2.type !== type) {
                  console.error('Unexpected type "%s" completed at %sms before "%s" completed.', type, currentTime, top2.type);
                }
                top2.duration = currentTime - top2.timestamp;
                if (currentTimelineData) {
                  currentTimelineData.duration = getRelativeTime() + TIME_OFFSET;
                }
              }
              __name(recordReactMeasureCompleted, "recordReactMeasureCompleted");
              function markCommitStarted(lanes) {
                if (isProfiling) {
                  recordReactMeasureStarted("commit", lanes);
                  nextRenderShouldStartNewBatch = true;
                }
                if (supportsUserTimingV3) {
                  markAndClear("--commit-start-".concat(lanes));
                  markMetadata();
                }
              }
              __name(markCommitStarted, "markCommitStarted");
              function markCommitStopped() {
                if (isProfiling) {
                  recordReactMeasureCompleted("commit");
                  recordReactMeasureCompleted("render-idle");
                }
                if (supportsUserTimingV3) {
                  markAndClear("--commit-stop");
                }
              }
              __name(markCommitStopped, "markCommitStopped");
              function markComponentRenderStarted(fiber) {
                if (isProfiling || supportsUserTimingV3) {
                  var componentName = getDisplayNameForFiber(fiber) || "Unknown";
                  if (isProfiling) {
                    if (isProfiling) {
                      currentReactComponentMeasure = {
                        componentName,
                        duration: 0,
                        timestamp: getRelativeTime(),
                        type: "render",
                        warning: null
                      };
                    }
                  }
                  if (supportsUserTimingV3) {
                    markAndClear("--component-render-start-".concat(componentName));
                  }
                }
              }
              __name(markComponentRenderStarted, "markComponentRenderStarted");
              function markComponentRenderStopped() {
                if (isProfiling) {
                  if (currentReactComponentMeasure) {
                    if (currentTimelineData) {
                      currentTimelineData.componentMeasures.push(currentReactComponentMeasure);
                    }
                    currentReactComponentMeasure.duration = // $FlowFixMe[incompatible-use] found when upgrading Flow
                    getRelativeTime() - currentReactComponentMeasure.timestamp;
                    currentReactComponentMeasure = null;
                  }
                }
                if (supportsUserTimingV3) {
                  markAndClear("--component-render-stop");
                }
              }
              __name(markComponentRenderStopped, "markComponentRenderStopped");
              function markComponentLayoutEffectMountStarted(fiber) {
                if (isProfiling || supportsUserTimingV3) {
                  var componentName = getDisplayNameForFiber(fiber) || "Unknown";
                  if (isProfiling) {
                    if (isProfiling) {
                      currentReactComponentMeasure = {
                        componentName,
                        duration: 0,
                        timestamp: getRelativeTime(),
                        type: "layout-effect-mount",
                        warning: null
                      };
                    }
                  }
                  if (supportsUserTimingV3) {
                    markAndClear("--component-layout-effect-mount-start-".concat(componentName));
                  }
                }
              }
              __name(markComponentLayoutEffectMountStarted, "markComponentLayoutEffectMountStarted");
              function markComponentLayoutEffectMountStopped() {
                if (isProfiling) {
                  if (currentReactComponentMeasure) {
                    if (currentTimelineData) {
                      currentTimelineData.componentMeasures.push(currentReactComponentMeasure);
                    }
                    currentReactComponentMeasure.duration = // $FlowFixMe[incompatible-use] found when upgrading Flow
                    getRelativeTime() - currentReactComponentMeasure.timestamp;
                    currentReactComponentMeasure = null;
                  }
                }
                if (supportsUserTimingV3) {
                  markAndClear("--component-layout-effect-mount-stop");
                }
              }
              __name(markComponentLayoutEffectMountStopped, "markComponentLayoutEffectMountStopped");
              function markComponentLayoutEffectUnmountStarted(fiber) {
                if (isProfiling || supportsUserTimingV3) {
                  var componentName = getDisplayNameForFiber(fiber) || "Unknown";
                  if (isProfiling) {
                    if (isProfiling) {
                      currentReactComponentMeasure = {
                        componentName,
                        duration: 0,
                        timestamp: getRelativeTime(),
                        type: "layout-effect-unmount",
                        warning: null
                      };
                    }
                  }
                  if (supportsUserTimingV3) {
                    markAndClear("--component-layout-effect-unmount-start-".concat(componentName));
                  }
                }
              }
              __name(markComponentLayoutEffectUnmountStarted, "markComponentLayoutEffectUnmountStarted");
              function markComponentLayoutEffectUnmountStopped() {
                if (isProfiling) {
                  if (currentReactComponentMeasure) {
                    if (currentTimelineData) {
                      currentTimelineData.componentMeasures.push(currentReactComponentMeasure);
                    }
                    currentReactComponentMeasure.duration = // $FlowFixMe[incompatible-use] found when upgrading Flow
                    getRelativeTime() - currentReactComponentMeasure.timestamp;
                    currentReactComponentMeasure = null;
                  }
                }
                if (supportsUserTimingV3) {
                  markAndClear("--component-layout-effect-unmount-stop");
                }
              }
              __name(markComponentLayoutEffectUnmountStopped, "markComponentLayoutEffectUnmountStopped");
              function markComponentPassiveEffectMountStarted(fiber) {
                if (isProfiling || supportsUserTimingV3) {
                  var componentName = getDisplayNameForFiber(fiber) || "Unknown";
                  if (isProfiling) {
                    if (isProfiling) {
                      currentReactComponentMeasure = {
                        componentName,
                        duration: 0,
                        timestamp: getRelativeTime(),
                        type: "passive-effect-mount",
                        warning: null
                      };
                    }
                  }
                  if (supportsUserTimingV3) {
                    markAndClear("--component-passive-effect-mount-start-".concat(componentName));
                  }
                }
              }
              __name(markComponentPassiveEffectMountStarted, "markComponentPassiveEffectMountStarted");
              function markComponentPassiveEffectMountStopped() {
                if (isProfiling) {
                  if (currentReactComponentMeasure) {
                    if (currentTimelineData) {
                      currentTimelineData.componentMeasures.push(currentReactComponentMeasure);
                    }
                    currentReactComponentMeasure.duration = // $FlowFixMe[incompatible-use] found when upgrading Flow
                    getRelativeTime() - currentReactComponentMeasure.timestamp;
                    currentReactComponentMeasure = null;
                  }
                }
                if (supportsUserTimingV3) {
                  markAndClear("--component-passive-effect-mount-stop");
                }
              }
              __name(markComponentPassiveEffectMountStopped, "markComponentPassiveEffectMountStopped");
              function markComponentPassiveEffectUnmountStarted(fiber) {
                if (isProfiling || supportsUserTimingV3) {
                  var componentName = getDisplayNameForFiber(fiber) || "Unknown";
                  if (isProfiling) {
                    if (isProfiling) {
                      currentReactComponentMeasure = {
                        componentName,
                        duration: 0,
                        timestamp: getRelativeTime(),
                        type: "passive-effect-unmount",
                        warning: null
                      };
                    }
                  }
                  if (supportsUserTimingV3) {
                    markAndClear("--component-passive-effect-unmount-start-".concat(componentName));
                  }
                }
              }
              __name(markComponentPassiveEffectUnmountStarted, "markComponentPassiveEffectUnmountStarted");
              function markComponentPassiveEffectUnmountStopped() {
                if (isProfiling) {
                  if (currentReactComponentMeasure) {
                    if (currentTimelineData) {
                      currentTimelineData.componentMeasures.push(currentReactComponentMeasure);
                    }
                    currentReactComponentMeasure.duration = // $FlowFixMe[incompatible-use] found when upgrading Flow
                    getRelativeTime() - currentReactComponentMeasure.timestamp;
                    currentReactComponentMeasure = null;
                  }
                }
                if (supportsUserTimingV3) {
                  markAndClear("--component-passive-effect-unmount-stop");
                }
              }
              __name(markComponentPassiveEffectUnmountStopped, "markComponentPassiveEffectUnmountStopped");
              function markComponentErrored(fiber, thrownValue, lanes) {
                if (isProfiling || supportsUserTimingV3) {
                  var componentName = getDisplayNameForFiber(fiber) || "Unknown";
                  var phase = fiber.alternate === null ? "mount" : "update";
                  var message = "";
                  if (thrownValue !== null && profilingHooks_typeof(thrownValue) === "object" && typeof thrownValue.message === "string") {
                    message = thrownValue.message;
                  } else if (typeof thrownValue === "string") {
                    message = thrownValue;
                  }
                  if (isProfiling) {
                    if (currentTimelineData) {
                      currentTimelineData.thrownErrors.push({
                        componentName,
                        message,
                        phase,
                        timestamp: getRelativeTime(),
                        type: "thrown-error"
                      });
                    }
                  }
                  if (supportsUserTimingV3) {
                    markAndClear("--error-".concat(componentName, "-").concat(phase, "-").concat(message));
                  }
                }
              }
              __name(markComponentErrored, "markComponentErrored");
              var PossiblyWeakMap2 = typeof WeakMap === "function" ? WeakMap : Map;
              var wakeableIDs = new PossiblyWeakMap2();
              var wakeableID = 0;
              function getWakeableID(wakeable) {
                if (!wakeableIDs.has(wakeable)) {
                  wakeableIDs.set(wakeable, wakeableID++);
                }
                return wakeableIDs.get(wakeable);
              }
              __name(getWakeableID, "getWakeableID");
              function markComponentSuspended(fiber, wakeable, lanes) {
                if (isProfiling || supportsUserTimingV3) {
                  var eventType = wakeableIDs.has(wakeable) ? "resuspend" : "suspend";
                  var id = getWakeableID(wakeable);
                  var componentName = getDisplayNameForFiber(fiber) || "Unknown";
                  var phase = fiber.alternate === null ? "mount" : "update";
                  var displayName = wakeable.displayName || "";
                  var suspenseEvent = null;
                  if (isProfiling) {
                    suspenseEvent = {
                      componentName,
                      depth: 0,
                      duration: 0,
                      id: "".concat(id),
                      phase,
                      promiseName: displayName,
                      resolution: "unresolved",
                      timestamp: getRelativeTime(),
                      type: "suspense",
                      warning: null
                    };
                    if (currentTimelineData) {
                      currentTimelineData.suspenseEvents.push(suspenseEvent);
                    }
                  }
                  if (supportsUserTimingV3) {
                    markAndClear("--suspense-".concat(eventType, "-").concat(id, "-").concat(componentName, "-").concat(phase, "-").concat(lanes, "-").concat(displayName));
                  }
                  wakeable.then(function() {
                    if (suspenseEvent) {
                      suspenseEvent.duration = getRelativeTime() - suspenseEvent.timestamp;
                      suspenseEvent.resolution = "resolved";
                    }
                    if (supportsUserTimingV3) {
                      markAndClear("--suspense-resolved-".concat(id, "-").concat(componentName));
                    }
                  }, function() {
                    if (suspenseEvent) {
                      suspenseEvent.duration = getRelativeTime() - suspenseEvent.timestamp;
                      suspenseEvent.resolution = "rejected";
                    }
                    if (supportsUserTimingV3) {
                      markAndClear("--suspense-rejected-".concat(id, "-").concat(componentName));
                    }
                  });
                }
              }
              __name(markComponentSuspended, "markComponentSuspended");
              function markLayoutEffectsStarted(lanes) {
                if (isProfiling) {
                  recordReactMeasureStarted("layout-effects", lanes);
                }
                if (supportsUserTimingV3) {
                  markAndClear("--layout-effects-start-".concat(lanes));
                }
              }
              __name(markLayoutEffectsStarted, "markLayoutEffectsStarted");
              function markLayoutEffectsStopped() {
                if (isProfiling) {
                  recordReactMeasureCompleted("layout-effects");
                }
                if (supportsUserTimingV3) {
                  markAndClear("--layout-effects-stop");
                }
              }
              __name(markLayoutEffectsStopped, "markLayoutEffectsStopped");
              function markPassiveEffectsStarted(lanes) {
                if (isProfiling) {
                  recordReactMeasureStarted("passive-effects", lanes);
                }
                if (supportsUserTimingV3) {
                  markAndClear("--passive-effects-start-".concat(lanes));
                }
              }
              __name(markPassiveEffectsStarted, "markPassiveEffectsStarted");
              function markPassiveEffectsStopped() {
                if (isProfiling) {
                  recordReactMeasureCompleted("passive-effects");
                }
                if (supportsUserTimingV3) {
                  markAndClear("--passive-effects-stop");
                }
              }
              __name(markPassiveEffectsStopped, "markPassiveEffectsStopped");
              function markRenderStarted(lanes) {
                if (isProfiling) {
                  if (nextRenderShouldStartNewBatch) {
                    nextRenderShouldStartNewBatch = false;
                    currentBatchUID++;
                  }
                  if (currentReactMeasuresStack.length === 0 || currentReactMeasuresStack[currentReactMeasuresStack.length - 1].type !== "render-idle") {
                    recordReactMeasureStarted("render-idle", lanes);
                  }
                  recordReactMeasureStarted("render", lanes);
                }
                if (supportsUserTimingV3) {
                  markAndClear("--render-start-".concat(lanes));
                }
              }
              __name(markRenderStarted, "markRenderStarted");
              function markRenderYielded() {
                if (isProfiling) {
                  recordReactMeasureCompleted("render");
                }
                if (supportsUserTimingV3) {
                  markAndClear("--render-yield");
                }
              }
              __name(markRenderYielded, "markRenderYielded");
              function markRenderStopped() {
                if (isProfiling) {
                  recordReactMeasureCompleted("render");
                }
                if (supportsUserTimingV3) {
                  markAndClear("--render-stop");
                }
              }
              __name(markRenderStopped, "markRenderStopped");
              function markRenderScheduled(lane) {
                if (isProfiling) {
                  if (currentTimelineData) {
                    currentTimelineData.schedulingEvents.push({
                      lanes: laneToLanesArray(lane),
                      timestamp: getRelativeTime(),
                      type: "schedule-render",
                      warning: null
                    });
                  }
                }
                if (supportsUserTimingV3) {
                  markAndClear("--schedule-render-".concat(lane));
                }
              }
              __name(markRenderScheduled, "markRenderScheduled");
              function markForceUpdateScheduled(fiber, lane) {
                if (isProfiling || supportsUserTimingV3) {
                  var componentName = getDisplayNameForFiber(fiber) || "Unknown";
                  if (isProfiling) {
                    if (currentTimelineData) {
                      currentTimelineData.schedulingEvents.push({
                        componentName,
                        lanes: laneToLanesArray(lane),
                        timestamp: getRelativeTime(),
                        type: "schedule-force-update",
                        warning: null
                      });
                    }
                  }
                  if (supportsUserTimingV3) {
                    markAndClear("--schedule-forced-update-".concat(lane, "-").concat(componentName));
                  }
                }
              }
              __name(markForceUpdateScheduled, "markForceUpdateScheduled");
              function getParentFibers(fiber) {
                var parents = [];
                var parent = fiber;
                while (parent !== null) {
                  parents.push(parent);
                  parent = parent.return;
                }
                return parents;
              }
              __name(getParentFibers, "getParentFibers");
              function markStateUpdateScheduled(fiber, lane) {
                if (isProfiling || supportsUserTimingV3) {
                  var componentName = getDisplayNameForFiber(fiber) || "Unknown";
                  if (isProfiling) {
                    if (currentTimelineData) {
                      var event = {
                        componentName,
                        // Store the parent fibers so we can post process
                        // them after we finish profiling
                        lanes: laneToLanesArray(lane),
                        timestamp: getRelativeTime(),
                        type: "schedule-state-update",
                        warning: null
                      };
                      currentFiberStacks.set(event, getParentFibers(fiber));
                      currentTimelineData.schedulingEvents.push(event);
                    }
                  }
                  if (supportsUserTimingV3) {
                    markAndClear("--schedule-state-update-".concat(lane, "-").concat(componentName));
                  }
                }
              }
              __name(markStateUpdateScheduled, "markStateUpdateScheduled");
              function toggleProfilingStatus(value) {
                if (isProfiling !== value) {
                  isProfiling = value;
                  if (isProfiling) {
                    var internalModuleSourceToRanges = /* @__PURE__ */ new Map();
                    if (supportsUserTimingV3) {
                      var ranges2 = getInternalModuleRanges();
                      if (ranges2) {
                        for (var i = 0; i < ranges2.length; i++) {
                          var range = ranges2[i];
                          if (shared_isArray(range) && range.length === 2) {
                            var _ranges$i2 = profilingHooks_slicedToArray(ranges2[i], 2), startStackFrame = _ranges$i2[0], stopStackFrame = _ranges$i2[1];
                            markAndClear("--react-internal-module-start-".concat(startStackFrame));
                            markAndClear("--react-internal-module-stop-".concat(stopStackFrame));
                          }
                        }
                      }
                    }
                    var laneToReactMeasureMap = /* @__PURE__ */ new Map();
                    var lane = 1;
                    for (var index = 0; index < REACT_TOTAL_NUM_LANES; index++) {
                      laneToReactMeasureMap.set(lane, []);
                      lane *= 2;
                    }
                    currentBatchUID = 0;
                    currentReactComponentMeasure = null;
                    currentReactMeasuresStack = [];
                    currentFiberStacks = /* @__PURE__ */ new Map();
                    currentTimelineData = {
                      // Session wide metadata; only collected once.
                      internalModuleSourceToRanges,
                      laneToLabelMap: laneToLabelMap || /* @__PURE__ */ new Map(),
                      reactVersion,
                      // Data logged by React during profiling session.
                      componentMeasures: [],
                      schedulingEvents: [],
                      suspenseEvents: [],
                      thrownErrors: [],
                      // Data inferred based on what React logs.
                      batchUIDToMeasuresMap: /* @__PURE__ */ new Map(),
                      duration: 0,
                      laneToReactMeasureMap,
                      startTime: 0,
                      // Data only available in Chrome profiles.
                      flamechart: [],
                      nativeEvents: [],
                      networkMeasures: [],
                      otherUserTimingMarks: [],
                      snapshots: [],
                      snapshotHeight: 0
                    };
                    nextRenderShouldStartNewBatch = true;
                  } else {
                    if (currentTimelineData !== null) {
                      currentTimelineData.schedulingEvents.forEach(function(event) {
                        if (event.type === "schedule-state-update") {
                          var fiberStack = currentFiberStacks.get(event);
                          if (fiberStack && currentDispatcherRef != null) {
                            event.componentStack = fiberStack.reduce(function(trace2, fiber) {
                              return trace2 + describeFiber(workTagMap, fiber, currentDispatcherRef);
                            }, "");
                          }
                        }
                      });
                    }
                    currentFiberStacks.clear();
                  }
                }
              }
              __name(toggleProfilingStatus, "toggleProfilingStatus");
              return {
                getTimelineData,
                profilingHooks: {
                  markCommitStarted,
                  markCommitStopped,
                  markComponentRenderStarted,
                  markComponentRenderStopped,
                  markComponentPassiveEffectMountStarted,
                  markComponentPassiveEffectMountStopped,
                  markComponentPassiveEffectUnmountStarted,
                  markComponentPassiveEffectUnmountStopped,
                  markComponentLayoutEffectMountStarted,
                  markComponentLayoutEffectMountStopped,
                  markComponentLayoutEffectUnmountStarted,
                  markComponentLayoutEffectUnmountStopped,
                  markComponentErrored,
                  markComponentSuspended,
                  markLayoutEffectsStarted,
                  markLayoutEffectsStopped,
                  markPassiveEffectsStarted,
                  markPassiveEffectsStopped,
                  markRenderStarted,
                  markRenderYielded,
                  markRenderStopped,
                  markRenderScheduled,
                  markForceUpdateScheduled,
                  markStateUpdateScheduled
                },
                toggleProfilingStatus
              };
            }
            __name(createProfilingHooks, "createProfilingHooks");
            ;
            function _objectWithoutProperties(source2, excluded) {
              if (source2 == null) return {};
              var target = _objectWithoutPropertiesLoose(source2, excluded);
              var key, i;
              if (Object.getOwnPropertySymbols) {
                var sourceSymbolKeys = Object.getOwnPropertySymbols(source2);
                for (i = 0; i < sourceSymbolKeys.length; i++) {
                  key = sourceSymbolKeys[i];
                  if (excluded.indexOf(key) >= 0) continue;
                  if (!Object.prototype.propertyIsEnumerable.call(source2, key)) continue;
                  target[key] = source2[key];
                }
              }
              return target;
            }
            __name(_objectWithoutProperties, "_objectWithoutProperties");
            function _objectWithoutPropertiesLoose(source2, excluded) {
              if (source2 == null) return {};
              var target = {};
              var sourceKeys = Object.keys(source2);
              var key, i;
              for (i = 0; i < sourceKeys.length; i++) {
                key = sourceKeys[i];
                if (excluded.indexOf(key) >= 0) continue;
                target[key] = source2[key];
              }
              return target;
            }
            __name(_objectWithoutPropertiesLoose, "_objectWithoutPropertiesLoose");
            function renderer_ownKeys(object, enumerableOnly) {
              var keys = Object.keys(object);
              if (Object.getOwnPropertySymbols) {
                var symbols = Object.getOwnPropertySymbols(object);
                if (enumerableOnly) symbols = symbols.filter(function(sym) {
                  return Object.getOwnPropertyDescriptor(object, sym).enumerable;
                });
                keys.push.apply(keys, symbols);
              }
              return keys;
            }
            __name(renderer_ownKeys, "renderer_ownKeys");
            function renderer_objectSpread(target) {
              for (var i = 1; i < arguments.length; i++) {
                var source2 = arguments[i] != null ? arguments[i] : {};
                if (i % 2) {
                  renderer_ownKeys(Object(source2), true).forEach(function(key) {
                    renderer_defineProperty(target, key, source2[key]);
                  });
                } else if (Object.getOwnPropertyDescriptors) {
                  Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
                } else {
                  renderer_ownKeys(Object(source2)).forEach(function(key) {
                    Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
                  });
                }
              }
              return target;
            }
            __name(renderer_objectSpread, "renderer_objectSpread");
            function renderer_defineProperty(obj, key, value) {
              if (key in obj) {
                Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
              } else {
                obj[key] = value;
              }
              return obj;
            }
            __name(renderer_defineProperty, "renderer_defineProperty");
            function renderer_slicedToArray(arr, i) {
              return renderer_arrayWithHoles(arr) || renderer_iterableToArrayLimit(arr, i) || renderer_unsupportedIterableToArray(arr, i) || renderer_nonIterableRest();
            }
            __name(renderer_slicedToArray, "renderer_slicedToArray");
            function renderer_nonIterableRest() {
              throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
            }
            __name(renderer_nonIterableRest, "renderer_nonIterableRest");
            function renderer_iterableToArrayLimit(arr, i) {
              if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
              var _arr = [];
              var _n = true;
              var _d = false;
              var _e = void 0;
              try {
                for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
                  _arr.push(_s.value);
                  if (i && _arr.length === i) break;
                }
              } catch (err) {
                _d = true;
                _e = err;
              } finally {
                try {
                  if (!_n && _i["return"] != null) _i["return"]();
                } finally {
                  if (_d) throw _e;
                }
              }
              return _arr;
            }
            __name(renderer_iterableToArrayLimit, "renderer_iterableToArrayLimit");
            function renderer_arrayWithHoles(arr) {
              if (Array.isArray(arr)) return arr;
            }
            __name(renderer_arrayWithHoles, "renderer_arrayWithHoles");
            function renderer_toConsumableArray(arr) {
              return renderer_arrayWithoutHoles(arr) || renderer_iterableToArray(arr) || renderer_unsupportedIterableToArray(arr) || renderer_nonIterableSpread();
            }
            __name(renderer_toConsumableArray, "renderer_toConsumableArray");
            function renderer_nonIterableSpread() {
              throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
            }
            __name(renderer_nonIterableSpread, "renderer_nonIterableSpread");
            function renderer_iterableToArray(iter) {
              if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
            }
            __name(renderer_iterableToArray, "renderer_iterableToArray");
            function renderer_arrayWithoutHoles(arr) {
              if (Array.isArray(arr)) return renderer_arrayLikeToArray(arr);
            }
            __name(renderer_arrayWithoutHoles, "renderer_arrayWithoutHoles");
            function _createForOfIteratorHelper(o2, allowArrayLike) {
              var it;
              if (typeof Symbol === "undefined" || o2[Symbol.iterator] == null) {
                if (Array.isArray(o2) || (it = renderer_unsupportedIterableToArray(o2)) || allowArrayLike && o2 && typeof o2.length === "number") {
                  if (it) o2 = it;
                  var i = 0;
                  var F = /* @__PURE__ */ __name(function F2() {
                  }, "F");
                  return { s: F, n: /* @__PURE__ */ __name(function n2() {
                    if (i >= o2.length) return { done: true };
                    return { done: false, value: o2[i++] };
                  }, "n"), e: /* @__PURE__ */ __name(function e2(_e2) {
                    throw _e2;
                  }, "e"), f: F };
                }
                throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
              }
              var normalCompletion = true, didErr = false, err;
              return { s: /* @__PURE__ */ __name(function s2() {
                it = o2[Symbol.iterator]();
              }, "s"), n: /* @__PURE__ */ __name(function n2() {
                var step = it.next();
                normalCompletion = step.done;
                return step;
              }, "n"), e: /* @__PURE__ */ __name(function e2(_e3) {
                didErr = true;
                err = _e3;
              }, "e"), f: /* @__PURE__ */ __name(function f() {
                try {
                  if (!normalCompletion && it.return != null) it.return();
                } finally {
                  if (didErr) throw err;
                }
              }, "f") };
            }
            __name(_createForOfIteratorHelper, "_createForOfIteratorHelper");
            function renderer_unsupportedIterableToArray(o2, minLen) {
              if (!o2) return;
              if (typeof o2 === "string") return renderer_arrayLikeToArray(o2, minLen);
              var n2 = Object.prototype.toString.call(o2).slice(8, -1);
              if (n2 === "Object" && o2.constructor) n2 = o2.constructor.name;
              if (n2 === "Map" || n2 === "Set") return Array.from(o2);
              if (n2 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n2)) return renderer_arrayLikeToArray(o2, minLen);
            }
            __name(renderer_unsupportedIterableToArray, "renderer_unsupportedIterableToArray");
            function renderer_arrayLikeToArray(arr, len) {
              if (len == null || len > arr.length) len = arr.length;
              for (var i = 0, arr2 = new Array(len); i < len; i++) {
                arr2[i] = arr[i];
              }
              return arr2;
            }
            __name(renderer_arrayLikeToArray, "renderer_arrayLikeToArray");
            function renderer_typeof(obj) {
              "@babel/helpers - typeof";
              if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                renderer_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return typeof obj2;
                }, "_typeof");
              } else {
                renderer_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                }, "_typeof");
              }
              return renderer_typeof(obj);
            }
            __name(renderer_typeof, "renderer_typeof");
            function getFiberFlags(fiber) {
              return fiber.flags !== void 0 ? fiber.flags : fiber.effectTag;
            }
            __name(getFiberFlags, "getFiberFlags");
            var renderer_getCurrentTime = (
              // $FlowFixMe[method-unbinding]
              (typeof performance === "undefined" ? "undefined" : renderer_typeof(performance)) === "object" && typeof performance.now === "function" ? function() {
                return performance.now();
              } : function() {
                return Date.now();
              }
            );
            function getInternalReactConstants(version2) {
              var ReactPriorityLevels = {
                ImmediatePriority: 99,
                UserBlockingPriority: 98,
                NormalPriority: 97,
                LowPriority: 96,
                IdlePriority: 95,
                NoPriority: 90
              };
              if (gt(version2, "17.0.2")) {
                ReactPriorityLevels = {
                  ImmediatePriority: 1,
                  UserBlockingPriority: 2,
                  NormalPriority: 3,
                  LowPriority: 4,
                  IdlePriority: 5,
                  NoPriority: 0
                };
              }
              var StrictModeBits = 0;
              if (gte(version2, "18.0.0-alpha")) {
                StrictModeBits = 24;
              } else if (gte(version2, "16.9.0")) {
                StrictModeBits = 1;
              } else if (gte(version2, "16.3.0")) {
                StrictModeBits = 2;
              }
              var ReactTypeOfWork = null;
              if (gt(version2, "17.0.1")) {
                ReactTypeOfWork = {
                  CacheComponent: 24,
                  // Experimental
                  ClassComponent: 1,
                  ContextConsumer: 9,
                  ContextProvider: 10,
                  CoroutineComponent: -1,
                  // Removed
                  CoroutineHandlerPhase: -1,
                  // Removed
                  DehydratedSuspenseComponent: 18,
                  // Behind a flag
                  ForwardRef: 11,
                  Fragment: 7,
                  FunctionComponent: 0,
                  HostComponent: 5,
                  HostPortal: 4,
                  HostRoot: 3,
                  HostHoistable: 26,
                  // In reality, 18.2+. But doesn't hurt to include it here
                  HostSingleton: 27,
                  // Same as above
                  HostText: 6,
                  IncompleteClassComponent: 17,
                  IndeterminateComponent: 2,
                  LazyComponent: 16,
                  LegacyHiddenComponent: 23,
                  MemoComponent: 14,
                  Mode: 8,
                  OffscreenComponent: 22,
                  // Experimental
                  Profiler: 12,
                  ScopeComponent: 21,
                  // Experimental
                  SimpleMemoComponent: 15,
                  SuspenseComponent: 13,
                  SuspenseListComponent: 19,
                  // Experimental
                  TracingMarkerComponent: 25,
                  // Experimental - This is technically in 18 but we don't
                  // want to fork again so we're adding it here instead
                  YieldComponent: -1
                  // Removed
                };
              } else if (gte(version2, "17.0.0-alpha")) {
                ReactTypeOfWork = {
                  CacheComponent: -1,
                  // Doesn't exist yet
                  ClassComponent: 1,
                  ContextConsumer: 9,
                  ContextProvider: 10,
                  CoroutineComponent: -1,
                  // Removed
                  CoroutineHandlerPhase: -1,
                  // Removed
                  DehydratedSuspenseComponent: 18,
                  // Behind a flag
                  ForwardRef: 11,
                  Fragment: 7,
                  FunctionComponent: 0,
                  HostComponent: 5,
                  HostPortal: 4,
                  HostRoot: 3,
                  HostHoistable: -1,
                  // Doesn't exist yet
                  HostSingleton: -1,
                  // Doesn't exist yet
                  HostText: 6,
                  IncompleteClassComponent: 17,
                  IndeterminateComponent: 2,
                  LazyComponent: 16,
                  LegacyHiddenComponent: 24,
                  MemoComponent: 14,
                  Mode: 8,
                  OffscreenComponent: 23,
                  // Experimental
                  Profiler: 12,
                  ScopeComponent: 21,
                  // Experimental
                  SimpleMemoComponent: 15,
                  SuspenseComponent: 13,
                  SuspenseListComponent: 19,
                  // Experimental
                  TracingMarkerComponent: -1,
                  // Doesn't exist yet
                  YieldComponent: -1
                  // Removed
                };
              } else if (gte(version2, "16.6.0-beta.0")) {
                ReactTypeOfWork = {
                  CacheComponent: -1,
                  // Doesn't exist yet
                  ClassComponent: 1,
                  ContextConsumer: 9,
                  ContextProvider: 10,
                  CoroutineComponent: -1,
                  // Removed
                  CoroutineHandlerPhase: -1,
                  // Removed
                  DehydratedSuspenseComponent: 18,
                  // Behind a flag
                  ForwardRef: 11,
                  Fragment: 7,
                  FunctionComponent: 0,
                  HostComponent: 5,
                  HostPortal: 4,
                  HostRoot: 3,
                  HostHoistable: -1,
                  // Doesn't exist yet
                  HostSingleton: -1,
                  // Doesn't exist yet
                  HostText: 6,
                  IncompleteClassComponent: 17,
                  IndeterminateComponent: 2,
                  LazyComponent: 16,
                  LegacyHiddenComponent: -1,
                  MemoComponent: 14,
                  Mode: 8,
                  OffscreenComponent: -1,
                  // Experimental
                  Profiler: 12,
                  ScopeComponent: -1,
                  // Experimental
                  SimpleMemoComponent: 15,
                  SuspenseComponent: 13,
                  SuspenseListComponent: 19,
                  // Experimental
                  TracingMarkerComponent: -1,
                  // Doesn't exist yet
                  YieldComponent: -1
                  // Removed
                };
              } else if (gte(version2, "16.4.3-alpha")) {
                ReactTypeOfWork = {
                  CacheComponent: -1,
                  // Doesn't exist yet
                  ClassComponent: 2,
                  ContextConsumer: 11,
                  ContextProvider: 12,
                  CoroutineComponent: -1,
                  // Removed
                  CoroutineHandlerPhase: -1,
                  // Removed
                  DehydratedSuspenseComponent: -1,
                  // Doesn't exist yet
                  ForwardRef: 13,
                  Fragment: 9,
                  FunctionComponent: 0,
                  HostComponent: 7,
                  HostPortal: 6,
                  HostRoot: 5,
                  HostHoistable: -1,
                  // Doesn't exist yet
                  HostSingleton: -1,
                  // Doesn't exist yet
                  HostText: 8,
                  IncompleteClassComponent: -1,
                  // Doesn't exist yet
                  IndeterminateComponent: 4,
                  LazyComponent: -1,
                  // Doesn't exist yet
                  LegacyHiddenComponent: -1,
                  MemoComponent: -1,
                  // Doesn't exist yet
                  Mode: 10,
                  OffscreenComponent: -1,
                  // Experimental
                  Profiler: 15,
                  ScopeComponent: -1,
                  // Experimental
                  SimpleMemoComponent: -1,
                  // Doesn't exist yet
                  SuspenseComponent: 16,
                  SuspenseListComponent: -1,
                  // Doesn't exist yet
                  TracingMarkerComponent: -1,
                  // Doesn't exist yet
                  YieldComponent: -1
                  // Removed
                };
              } else {
                ReactTypeOfWork = {
                  CacheComponent: -1,
                  // Doesn't exist yet
                  ClassComponent: 2,
                  ContextConsumer: 12,
                  ContextProvider: 13,
                  CoroutineComponent: 7,
                  CoroutineHandlerPhase: 8,
                  DehydratedSuspenseComponent: -1,
                  // Doesn't exist yet
                  ForwardRef: 14,
                  Fragment: 10,
                  FunctionComponent: 1,
                  HostComponent: 5,
                  HostPortal: 4,
                  HostRoot: 3,
                  HostHoistable: -1,
                  // Doesn't exist yet
                  HostSingleton: -1,
                  // Doesn't exist yet
                  HostText: 6,
                  IncompleteClassComponent: -1,
                  // Doesn't exist yet
                  IndeterminateComponent: 0,
                  LazyComponent: -1,
                  // Doesn't exist yet
                  LegacyHiddenComponent: -1,
                  MemoComponent: -1,
                  // Doesn't exist yet
                  Mode: 11,
                  OffscreenComponent: -1,
                  // Experimental
                  Profiler: 15,
                  ScopeComponent: -1,
                  // Experimental
                  SimpleMemoComponent: -1,
                  // Doesn't exist yet
                  SuspenseComponent: 16,
                  SuspenseListComponent: -1,
                  // Doesn't exist yet
                  TracingMarkerComponent: -1,
                  // Doesn't exist yet
                  YieldComponent: 9
                };
              }
              function getTypeSymbol(type) {
                var symbolOrNumber = renderer_typeof(type) === "object" && type !== null ? type.$$typeof : type;
                return renderer_typeof(symbolOrNumber) === "symbol" ? (
                  // $FlowFixMe[incompatible-return] `toString()` doesn't match the type signature?
                  symbolOrNumber.toString()
                ) : symbolOrNumber;
              }
              __name(getTypeSymbol, "getTypeSymbol");
              var _ReactTypeOfWork = ReactTypeOfWork, CacheComponent = _ReactTypeOfWork.CacheComponent, ClassComponent = _ReactTypeOfWork.ClassComponent, IncompleteClassComponent = _ReactTypeOfWork.IncompleteClassComponent, FunctionComponent = _ReactTypeOfWork.FunctionComponent, IndeterminateComponent = _ReactTypeOfWork.IndeterminateComponent, ForwardRef = _ReactTypeOfWork.ForwardRef, HostRoot = _ReactTypeOfWork.HostRoot, HostHoistable = _ReactTypeOfWork.HostHoistable, HostSingleton = _ReactTypeOfWork.HostSingleton, HostComponent = _ReactTypeOfWork.HostComponent, HostPortal = _ReactTypeOfWork.HostPortal, HostText = _ReactTypeOfWork.HostText, Fragment14 = _ReactTypeOfWork.Fragment, LazyComponent = _ReactTypeOfWork.LazyComponent, LegacyHiddenComponent = _ReactTypeOfWork.LegacyHiddenComponent, MemoComponent = _ReactTypeOfWork.MemoComponent, OffscreenComponent = _ReactTypeOfWork.OffscreenComponent, Profiler = _ReactTypeOfWork.Profiler, ScopeComponent = _ReactTypeOfWork.ScopeComponent, SimpleMemoComponent = _ReactTypeOfWork.SimpleMemoComponent, SuspenseComponent = _ReactTypeOfWork.SuspenseComponent, SuspenseListComponent = _ReactTypeOfWork.SuspenseListComponent, TracingMarkerComponent = _ReactTypeOfWork.TracingMarkerComponent;
              function resolveFiberType(type) {
                var typeSymbol = getTypeSymbol(type);
                switch (typeSymbol) {
                  case ReactSymbols_MEMO_NUMBER:
                  case ReactSymbols_MEMO_SYMBOL_STRING:
                    return resolveFiberType(type.type);
                  case ReactSymbols_FORWARD_REF_NUMBER:
                  case ReactSymbols_FORWARD_REF_SYMBOL_STRING:
                    return type.render;
                  default:
                    return type;
                }
              }
              __name(resolveFiberType, "resolveFiberType");
              function getDisplayNameForFiber(fiber) {
                var elementType = fiber.elementType, type = fiber.type, tag2 = fiber.tag;
                var resolvedType = type;
                if (renderer_typeof(type) === "object" && type !== null) {
                  resolvedType = resolveFiberType(type);
                }
                var resolvedContext = null;
                switch (tag2) {
                  case CacheComponent:
                    return "Cache";
                  case ClassComponent:
                  case IncompleteClassComponent:
                    return getDisplayName(resolvedType);
                  case FunctionComponent:
                  case IndeterminateComponent:
                    return getDisplayName(resolvedType);
                  case ForwardRef:
                    return getWrappedDisplayName(elementType, resolvedType, "ForwardRef", "Anonymous");
                  case HostRoot:
                    var fiberRoot = fiber.stateNode;
                    if (fiberRoot != null && fiberRoot._debugRootType !== null) {
                      return fiberRoot._debugRootType;
                    }
                    return null;
                  case HostComponent:
                  case HostSingleton:
                  case HostHoistable:
                    return type;
                  case HostPortal:
                  case HostText:
                    return null;
                  case Fragment14:
                    return "Fragment";
                  case LazyComponent:
                    return "Lazy";
                  case MemoComponent:
                  case SimpleMemoComponent:
                    return getWrappedDisplayName(elementType, resolvedType, "Memo", "Anonymous");
                  case SuspenseComponent:
                    return "Suspense";
                  case LegacyHiddenComponent:
                    return "LegacyHidden";
                  case OffscreenComponent:
                    return "Offscreen";
                  case ScopeComponent:
                    return "Scope";
                  case SuspenseListComponent:
                    return "SuspenseList";
                  case Profiler:
                    return "Profiler";
                  case TracingMarkerComponent:
                    return "TracingMarker";
                  default:
                    var typeSymbol = getTypeSymbol(type);
                    switch (typeSymbol) {
                      case CONCURRENT_MODE_NUMBER:
                      case CONCURRENT_MODE_SYMBOL_STRING:
                      case DEPRECATED_ASYNC_MODE_SYMBOL_STRING:
                        return null;
                      case PROVIDER_NUMBER:
                      case PROVIDER_SYMBOL_STRING:
                        resolvedContext = fiber.type._context || fiber.type.context;
                        return "".concat(resolvedContext.displayName || "Context", ".Provider");
                      case CONTEXT_NUMBER:
                      case CONTEXT_SYMBOL_STRING:
                      case SERVER_CONTEXT_SYMBOL_STRING:
                        resolvedContext = fiber.type._context || fiber.type;
                        return "".concat(resolvedContext.displayName || "Context", ".Consumer");
                      case STRICT_MODE_NUMBER:
                      case STRICT_MODE_SYMBOL_STRING:
                        return null;
                      case PROFILER_NUMBER:
                      case PROFILER_SYMBOL_STRING:
                        return "Profiler(".concat(fiber.memoizedProps.id, ")");
                      case SCOPE_NUMBER:
                      case SCOPE_SYMBOL_STRING:
                        return "Scope";
                      default:
                        return null;
                    }
                }
              }
              __name(getDisplayNameForFiber, "getDisplayNameForFiber");
              return {
                getDisplayNameForFiber,
                getTypeSymbol,
                ReactPriorityLevels,
                ReactTypeOfWork,
                StrictModeBits
              };
            }
            __name(getInternalReactConstants, "getInternalReactConstants");
            var fiberToIDMap = /* @__PURE__ */ new Map();
            var idToArbitraryFiberMap = /* @__PURE__ */ new Map();
            function attach(hook2, rendererID, renderer2, global2) {
              var version2 = renderer2.reconcilerVersion || renderer2.version;
              var _getInternalReactCons = getInternalReactConstants(version2), getDisplayNameForFiber = _getInternalReactCons.getDisplayNameForFiber, getTypeSymbol = _getInternalReactCons.getTypeSymbol, ReactPriorityLevels = _getInternalReactCons.ReactPriorityLevels, ReactTypeOfWork = _getInternalReactCons.ReactTypeOfWork, StrictModeBits = _getInternalReactCons.StrictModeBits;
              var CacheComponent = ReactTypeOfWork.CacheComponent, ClassComponent = ReactTypeOfWork.ClassComponent, ContextConsumer = ReactTypeOfWork.ContextConsumer, DehydratedSuspenseComponent = ReactTypeOfWork.DehydratedSuspenseComponent, ForwardRef = ReactTypeOfWork.ForwardRef, Fragment14 = ReactTypeOfWork.Fragment, FunctionComponent = ReactTypeOfWork.FunctionComponent, HostRoot = ReactTypeOfWork.HostRoot, HostHoistable = ReactTypeOfWork.HostHoistable, HostSingleton = ReactTypeOfWork.HostSingleton, HostPortal = ReactTypeOfWork.HostPortal, HostComponent = ReactTypeOfWork.HostComponent, HostText = ReactTypeOfWork.HostText, IncompleteClassComponent = ReactTypeOfWork.IncompleteClassComponent, IndeterminateComponent = ReactTypeOfWork.IndeterminateComponent, LegacyHiddenComponent = ReactTypeOfWork.LegacyHiddenComponent, MemoComponent = ReactTypeOfWork.MemoComponent, OffscreenComponent = ReactTypeOfWork.OffscreenComponent, SimpleMemoComponent = ReactTypeOfWork.SimpleMemoComponent, SuspenseComponent = ReactTypeOfWork.SuspenseComponent, SuspenseListComponent = ReactTypeOfWork.SuspenseListComponent, TracingMarkerComponent = ReactTypeOfWork.TracingMarkerComponent;
              var ImmediatePriority = ReactPriorityLevels.ImmediatePriority, UserBlockingPriority = ReactPriorityLevels.UserBlockingPriority, NormalPriority = ReactPriorityLevels.NormalPriority, LowPriority = ReactPriorityLevels.LowPriority, IdlePriority = ReactPriorityLevels.IdlePriority, NoPriority = ReactPriorityLevels.NoPriority;
              var getLaneLabelMap = renderer2.getLaneLabelMap, injectProfilingHooks = renderer2.injectProfilingHooks, overrideHookState = renderer2.overrideHookState, overrideHookStateDeletePath = renderer2.overrideHookStateDeletePath, overrideHookStateRenamePath = renderer2.overrideHookStateRenamePath, overrideProps = renderer2.overrideProps, overridePropsDeletePath = renderer2.overridePropsDeletePath, overridePropsRenamePath = renderer2.overridePropsRenamePath, scheduleRefresh = renderer2.scheduleRefresh, setErrorHandler = renderer2.setErrorHandler, setSuspenseHandler = renderer2.setSuspenseHandler, scheduleUpdate = renderer2.scheduleUpdate;
              var supportsTogglingError = typeof setErrorHandler === "function" && typeof scheduleUpdate === "function";
              var supportsTogglingSuspense = typeof setSuspenseHandler === "function" && typeof scheduleUpdate === "function";
              if (typeof scheduleRefresh === "function") {
                renderer2.scheduleRefresh = function() {
                  try {
                    hook2.emit("fastRefreshScheduled");
                  } finally {
                    return scheduleRefresh.apply(void 0, arguments);
                  }
                };
              }
              var getTimelineData = null;
              var toggleProfilingStatus = null;
              if (typeof injectProfilingHooks === "function") {
                var response = createProfilingHooks({
                  getDisplayNameForFiber,
                  getIsProfiling: /* @__PURE__ */ __name(function getIsProfiling() {
                    return isProfiling;
                  }, "getIsProfiling"),
                  getLaneLabelMap,
                  currentDispatcherRef: renderer2.currentDispatcherRef,
                  workTagMap: ReactTypeOfWork,
                  reactVersion: version2
                });
                injectProfilingHooks(response.profilingHooks);
                getTimelineData = response.getTimelineData;
                toggleProfilingStatus = response.toggleProfilingStatus;
              }
              var fibersWithChangedErrorOrWarningCounts = /* @__PURE__ */ new Set();
              var pendingFiberToErrorsMap = /* @__PURE__ */ new Map();
              var pendingFiberToWarningsMap = /* @__PURE__ */ new Map();
              var fiberIDToErrorsMap = /* @__PURE__ */ new Map();
              var fiberIDToWarningsMap = /* @__PURE__ */ new Map();
              function clearErrorsAndWarnings() {
                var _iterator = _createForOfIteratorHelper(fiberIDToErrorsMap.keys()), _step;
                try {
                  for (_iterator.s(); !(_step = _iterator.n()).done; ) {
                    var id = _step.value;
                    var _fiber = idToArbitraryFiberMap.get(id);
                    if (_fiber != null) {
                      fibersWithChangedErrorOrWarningCounts.add(_fiber);
                      updateMostRecentlyInspectedElementIfNecessary(id);
                    }
                  }
                } catch (err) {
                  _iterator.e(err);
                } finally {
                  _iterator.f();
                }
                var _iterator2 = _createForOfIteratorHelper(fiberIDToWarningsMap.keys()), _step2;
                try {
                  for (_iterator2.s(); !(_step2 = _iterator2.n()).done; ) {
                    var _id = _step2.value;
                    var _fiber2 = idToArbitraryFiberMap.get(_id);
                    if (_fiber2 != null) {
                      fibersWithChangedErrorOrWarningCounts.add(_fiber2);
                      updateMostRecentlyInspectedElementIfNecessary(_id);
                    }
                  }
                } catch (err) {
                  _iterator2.e(err);
                } finally {
                  _iterator2.f();
                }
                fiberIDToErrorsMap.clear();
                fiberIDToWarningsMap.clear();
                flushPendingEvents();
              }
              __name(clearErrorsAndWarnings, "clearErrorsAndWarnings");
              function clearMessageCountHelper(fiberID, pendingFiberToMessageCountMap, fiberIDToMessageCountMap) {
                var fiber = idToArbitraryFiberMap.get(fiberID);
                if (fiber != null) {
                  pendingFiberToErrorsMap.delete(fiber);
                  if (fiberIDToMessageCountMap.has(fiberID)) {
                    fiberIDToMessageCountMap.delete(fiberID);
                    fibersWithChangedErrorOrWarningCounts.add(fiber);
                    flushPendingEvents();
                    updateMostRecentlyInspectedElementIfNecessary(fiberID);
                  } else {
                    fibersWithChangedErrorOrWarningCounts.delete(fiber);
                  }
                }
              }
              __name(clearMessageCountHelper, "clearMessageCountHelper");
              function clearErrorsForFiberID(fiberID) {
                clearMessageCountHelper(fiberID, pendingFiberToErrorsMap, fiberIDToErrorsMap);
              }
              __name(clearErrorsForFiberID, "clearErrorsForFiberID");
              function clearWarningsForFiberID(fiberID) {
                clearMessageCountHelper(fiberID, pendingFiberToWarningsMap, fiberIDToWarningsMap);
              }
              __name(clearWarningsForFiberID, "clearWarningsForFiberID");
              function updateMostRecentlyInspectedElementIfNecessary(fiberID) {
                if (mostRecentlyInspectedElement !== null && mostRecentlyInspectedElement.id === fiberID) {
                  hasElementUpdatedSinceLastInspected = true;
                }
              }
              __name(updateMostRecentlyInspectedElementIfNecessary, "updateMostRecentlyInspectedElementIfNecessary");
              function onErrorOrWarning(fiber, type, args) {
                if (type === "error") {
                  var maybeID = getFiberIDUnsafe(fiber);
                  if (maybeID != null && forceErrorForFiberIDs.get(maybeID) === true) {
                    return;
                  }
                }
                var message = format4.apply(void 0, renderer_toConsumableArray(args));
                if (__DEBUG__) {
                  debug3("onErrorOrWarning", fiber, null, "".concat(type, ': "').concat(message, '"'));
                }
                fibersWithChangedErrorOrWarningCounts.add(fiber);
                var fiberMap = type === "error" ? pendingFiberToErrorsMap : pendingFiberToWarningsMap;
                var messageMap = fiberMap.get(fiber);
                if (messageMap != null) {
                  var count = messageMap.get(message) || 0;
                  messageMap.set(message, count + 1);
                } else {
                  fiberMap.set(fiber, /* @__PURE__ */ new Map([[message, 1]]));
                }
                flushPendingErrorsAndWarningsAfterDelay();
              }
              __name(onErrorOrWarning, "onErrorOrWarning");
              registerRenderer(renderer2, onErrorOrWarning);
              patchConsoleUsingWindowValues();
              var debug3 = /* @__PURE__ */ __name(function debug4(name3, fiber, parentFiber) {
                var extraString = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : "";
                if (__DEBUG__) {
                  var displayName = fiber.tag + ":" + (getDisplayNameForFiber(fiber) || "null");
                  var maybeID = getFiberIDUnsafe(fiber) || "<no id>";
                  var parentDisplayName = parentFiber ? parentFiber.tag + ":" + (getDisplayNameForFiber(parentFiber) || "null") : "";
                  var maybeParentID = parentFiber ? getFiberIDUnsafe(parentFiber) || "<no-id>" : "";
                  console.groupCollapsed("[renderer] %c".concat(name3, " %c").concat(displayName, " (").concat(maybeID, ") %c").concat(parentFiber ? "".concat(parentDisplayName, " (").concat(maybeParentID, ")") : "", " %c").concat(extraString), "color: red; font-weight: bold;", "color: blue;", "color: purple;", "color: black;");
                  console.log(new Error().stack.split("\n").slice(1).join("\n"));
                  console.groupEnd();
                }
              }, "debug");
              var hideElementsWithDisplayNames = /* @__PURE__ */ new Set();
              var hideElementsWithPaths = /* @__PURE__ */ new Set();
              var hideElementsWithTypes = /* @__PURE__ */ new Set();
              var traceUpdatesEnabled = false;
              var traceUpdatesForNodes = /* @__PURE__ */ new Set();
              function applyComponentFilters(componentFilters) {
                hideElementsWithTypes.clear();
                hideElementsWithDisplayNames.clear();
                hideElementsWithPaths.clear();
                componentFilters.forEach(function(componentFilter) {
                  if (!componentFilter.isEnabled) {
                    return;
                  }
                  switch (componentFilter.type) {
                    case ComponentFilterDisplayName:
                      if (componentFilter.isValid && componentFilter.value !== "") {
                        hideElementsWithDisplayNames.add(new RegExp(componentFilter.value, "i"));
                      }
                      break;
                    case ComponentFilterElementType:
                      hideElementsWithTypes.add(componentFilter.value);
                      break;
                    case ComponentFilterLocation:
                      if (componentFilter.isValid && componentFilter.value !== "") {
                        hideElementsWithPaths.add(new RegExp(componentFilter.value, "i"));
                      }
                      break;
                    case ComponentFilterHOC:
                      hideElementsWithDisplayNames.add(new RegExp("\\("));
                      break;
                    default:
                      console.warn('Invalid component filter type "'.concat(componentFilter.type, '"'));
                      break;
                  }
                });
              }
              __name(applyComponentFilters, "applyComponentFilters");
              if (window.__REACT_DEVTOOLS_COMPONENT_FILTERS__ != null) {
                applyComponentFilters(window.__REACT_DEVTOOLS_COMPONENT_FILTERS__);
              } else {
                applyComponentFilters(getDefaultComponentFilters());
              }
              function updateComponentFilters(componentFilters) {
                if (isProfiling) {
                  throw Error("Cannot modify filter preferences while profiling");
                }
                hook2.getFiberRoots(rendererID).forEach(function(root) {
                  currentRootID = getOrGenerateFiberID(root.current);
                  pushOperation(TREE_OPERATION_REMOVE_ROOT);
                  flushPendingEvents(root);
                  currentRootID = -1;
                });
                applyComponentFilters(componentFilters);
                rootDisplayNameCounter.clear();
                hook2.getFiberRoots(rendererID).forEach(function(root) {
                  currentRootID = getOrGenerateFiberID(root.current);
                  setRootPseudoKey(currentRootID, root.current);
                  mountFiberRecursively(root.current, null, false, false);
                  flushPendingEvents(root);
                  currentRootID = -1;
                });
                reevaluateErrorsAndWarnings();
                flushPendingEvents();
              }
              __name(updateComponentFilters, "updateComponentFilters");
              function shouldFilterFiber(fiber) {
                var _debugSource = fiber._debugSource, tag2 = fiber.tag, type = fiber.type, key = fiber.key;
                switch (tag2) {
                  case DehydratedSuspenseComponent:
                    return true;
                  case HostPortal:
                  case HostText:
                  case LegacyHiddenComponent:
                  case OffscreenComponent:
                    return true;
                  case HostRoot:
                    return false;
                  case Fragment14:
                    return key === null;
                  default:
                    var typeSymbol = getTypeSymbol(type);
                    switch (typeSymbol) {
                      case CONCURRENT_MODE_NUMBER:
                      case CONCURRENT_MODE_SYMBOL_STRING:
                      case DEPRECATED_ASYNC_MODE_SYMBOL_STRING:
                      case STRICT_MODE_NUMBER:
                      case STRICT_MODE_SYMBOL_STRING:
                        return true;
                      default:
                        break;
                    }
                }
                var elementType = getElementTypeForFiber(fiber);
                if (hideElementsWithTypes.has(elementType)) {
                  return true;
                }
                if (hideElementsWithDisplayNames.size > 0) {
                  var displayName = getDisplayNameForFiber(fiber);
                  if (displayName != null) {
                    var _iterator3 = _createForOfIteratorHelper(hideElementsWithDisplayNames), _step3;
                    try {
                      for (_iterator3.s(); !(_step3 = _iterator3.n()).done; ) {
                        var displayNameRegExp = _step3.value;
                        if (displayNameRegExp.test(displayName)) {
                          return true;
                        }
                      }
                    } catch (err) {
                      _iterator3.e(err);
                    } finally {
                      _iterator3.f();
                    }
                  }
                }
                if (_debugSource != null && hideElementsWithPaths.size > 0) {
                  var fileName = _debugSource.fileName;
                  var _iterator4 = _createForOfIteratorHelper(hideElementsWithPaths), _step4;
                  try {
                    for (_iterator4.s(); !(_step4 = _iterator4.n()).done; ) {
                      var pathRegExp = _step4.value;
                      if (pathRegExp.test(fileName)) {
                        return true;
                      }
                    }
                  } catch (err) {
                    _iterator4.e(err);
                  } finally {
                    _iterator4.f();
                  }
                }
                return false;
              }
              __name(shouldFilterFiber, "shouldFilterFiber");
              function getElementTypeForFiber(fiber) {
                var type = fiber.type, tag2 = fiber.tag;
                switch (tag2) {
                  case ClassComponent:
                  case IncompleteClassComponent:
                    return types_ElementTypeClass;
                  case FunctionComponent:
                  case IndeterminateComponent:
                    return types_ElementTypeFunction;
                  case ForwardRef:
                    return types_ElementTypeForwardRef;
                  case HostRoot:
                    return ElementTypeRoot;
                  case HostComponent:
                  case HostHoistable:
                  case HostSingleton:
                    return ElementTypeHostComponent;
                  case HostPortal:
                  case HostText:
                  case Fragment14:
                    return ElementTypeOtherOrUnknown;
                  case MemoComponent:
                  case SimpleMemoComponent:
                    return types_ElementTypeMemo;
                  case SuspenseComponent:
                    return ElementTypeSuspense;
                  case SuspenseListComponent:
                    return ElementTypeSuspenseList;
                  case TracingMarkerComponent:
                    return ElementTypeTracingMarker;
                  default:
                    var typeSymbol = getTypeSymbol(type);
                    switch (typeSymbol) {
                      case CONCURRENT_MODE_NUMBER:
                      case CONCURRENT_MODE_SYMBOL_STRING:
                      case DEPRECATED_ASYNC_MODE_SYMBOL_STRING:
                        return ElementTypeOtherOrUnknown;
                      case PROVIDER_NUMBER:
                      case PROVIDER_SYMBOL_STRING:
                        return ElementTypeContext;
                      case CONTEXT_NUMBER:
                      case CONTEXT_SYMBOL_STRING:
                        return ElementTypeContext;
                      case STRICT_MODE_NUMBER:
                      case STRICT_MODE_SYMBOL_STRING:
                        return ElementTypeOtherOrUnknown;
                      case PROFILER_NUMBER:
                      case PROFILER_SYMBOL_STRING:
                        return ElementTypeProfiler;
                      default:
                        return ElementTypeOtherOrUnknown;
                    }
                }
              }
              __name(getElementTypeForFiber, "getElementTypeForFiber");
              var idToTreeBaseDurationMap = /* @__PURE__ */ new Map();
              var idToRootMap = /* @__PURE__ */ new Map();
              var currentRootID = -1;
              function getOrGenerateFiberID(fiber) {
                var id = null;
                if (fiberToIDMap.has(fiber)) {
                  id = fiberToIDMap.get(fiber);
                } else {
                  var _alternate = fiber.alternate;
                  if (_alternate !== null && fiberToIDMap.has(_alternate)) {
                    id = fiberToIDMap.get(_alternate);
                  }
                }
                var didGenerateID = false;
                if (id === null) {
                  didGenerateID = true;
                  id = getUID();
                }
                var refinedID = id;
                if (!fiberToIDMap.has(fiber)) {
                  fiberToIDMap.set(fiber, refinedID);
                  idToArbitraryFiberMap.set(refinedID, fiber);
                }
                var alternate = fiber.alternate;
                if (alternate !== null) {
                  if (!fiberToIDMap.has(alternate)) {
                    fiberToIDMap.set(alternate, refinedID);
                  }
                }
                if (__DEBUG__) {
                  if (didGenerateID) {
                    debug3("getOrGenerateFiberID()", fiber, fiber.return, "Generated a new UID");
                  }
                }
                return refinedID;
              }
              __name(getOrGenerateFiberID, "getOrGenerateFiberID");
              function getFiberIDThrows(fiber) {
                var maybeID = getFiberIDUnsafe(fiber);
                if (maybeID !== null) {
                  return maybeID;
                }
                throw Error('Could not find ID for Fiber "'.concat(getDisplayNameForFiber(fiber) || "", '"'));
              }
              __name(getFiberIDThrows, "getFiberIDThrows");
              function getFiberIDUnsafe(fiber) {
                if (fiberToIDMap.has(fiber)) {
                  return fiberToIDMap.get(fiber);
                } else {
                  var alternate = fiber.alternate;
                  if (alternate !== null && fiberToIDMap.has(alternate)) {
                    return fiberToIDMap.get(alternate);
                  }
                }
                return null;
              }
              __name(getFiberIDUnsafe, "getFiberIDUnsafe");
              function untrackFiberID(fiber) {
                if (__DEBUG__) {
                  debug3("untrackFiberID()", fiber, fiber.return, "schedule after delay");
                }
                untrackFibersSet.add(fiber);
                var alternate = fiber.alternate;
                if (alternate !== null) {
                  untrackFibersSet.add(alternate);
                }
                if (untrackFibersTimeoutID === null) {
                  untrackFibersTimeoutID = setTimeout(untrackFibers, 1e3);
                }
              }
              __name(untrackFiberID, "untrackFiberID");
              var untrackFibersSet = /* @__PURE__ */ new Set();
              var untrackFibersTimeoutID = null;
              function untrackFibers() {
                if (untrackFibersTimeoutID !== null) {
                  clearTimeout(untrackFibersTimeoutID);
                  untrackFibersTimeoutID = null;
                }
                untrackFibersSet.forEach(function(fiber) {
                  var fiberID = getFiberIDUnsafe(fiber);
                  if (fiberID !== null) {
                    idToArbitraryFiberMap.delete(fiberID);
                    clearErrorsForFiberID(fiberID);
                    clearWarningsForFiberID(fiberID);
                  }
                  fiberToIDMap.delete(fiber);
                  var alternate = fiber.alternate;
                  if (alternate !== null) {
                    fiberToIDMap.delete(alternate);
                  }
                  if (forceErrorForFiberIDs.has(fiberID)) {
                    forceErrorForFiberIDs.delete(fiberID);
                    if (forceErrorForFiberIDs.size === 0 && setErrorHandler != null) {
                      setErrorHandler(shouldErrorFiberAlwaysNull);
                    }
                  }
                });
                untrackFibersSet.clear();
              }
              __name(untrackFibers, "untrackFibers");
              function getChangeDescription(prevFiber, nextFiber) {
                switch (getElementTypeForFiber(nextFiber)) {
                  case types_ElementTypeClass:
                  case types_ElementTypeFunction:
                  case types_ElementTypeMemo:
                  case types_ElementTypeForwardRef:
                    if (prevFiber === null) {
                      return {
                        context: null,
                        didHooksChange: false,
                        isFirstMount: true,
                        props: null,
                        state: null
                      };
                    } else {
                      var data = {
                        context: getContextChangedKeys(nextFiber),
                        didHooksChange: false,
                        isFirstMount: false,
                        props: getChangedKeys(prevFiber.memoizedProps, nextFiber.memoizedProps),
                        state: getChangedKeys(prevFiber.memoizedState, nextFiber.memoizedState)
                      };
                      var indices = getChangedHooksIndices(prevFiber.memoizedState, nextFiber.memoizedState);
                      data.hooks = indices;
                      data.didHooksChange = indices !== null && indices.length > 0;
                      return data;
                    }
                  default:
                    return null;
                }
              }
              __name(getChangeDescription, "getChangeDescription");
              function updateContextsForFiber(fiber) {
                switch (getElementTypeForFiber(fiber)) {
                  case types_ElementTypeClass:
                  case types_ElementTypeForwardRef:
                  case types_ElementTypeFunction:
                  case types_ElementTypeMemo:
                    if (idToContextsMap !== null) {
                      var id = getFiberIDThrows(fiber);
                      var contexts = getContextsForFiber(fiber);
                      if (contexts !== null) {
                        idToContextsMap.set(id, contexts);
                      }
                    }
                    break;
                  default:
                    break;
                }
              }
              __name(updateContextsForFiber, "updateContextsForFiber");
              var NO_CONTEXT = {};
              function getContextsForFiber(fiber) {
                var legacyContext = NO_CONTEXT;
                var modernContext = NO_CONTEXT;
                switch (getElementTypeForFiber(fiber)) {
                  case types_ElementTypeClass:
                    var instance = fiber.stateNode;
                    if (instance != null) {
                      if (instance.constructor && instance.constructor.contextType != null) {
                        modernContext = instance.context;
                      } else {
                        legacyContext = instance.context;
                        if (legacyContext && Object.keys(legacyContext).length === 0) {
                          legacyContext = NO_CONTEXT;
                        }
                      }
                    }
                    return [legacyContext, modernContext];
                  case types_ElementTypeForwardRef:
                  case types_ElementTypeFunction:
                  case types_ElementTypeMemo:
                    var dependencies = fiber.dependencies;
                    if (dependencies && dependencies.firstContext) {
                      modernContext = dependencies.firstContext;
                    }
                    return [legacyContext, modernContext];
                  default:
                    return null;
                }
              }
              __name(getContextsForFiber, "getContextsForFiber");
              function crawlToInitializeContextsMap(fiber) {
                var id = getFiberIDUnsafe(fiber);
                if (id !== null) {
                  updateContextsForFiber(fiber);
                  var current = fiber.child;
                  while (current !== null) {
                    crawlToInitializeContextsMap(current);
                    current = current.sibling;
                  }
                }
              }
              __name(crawlToInitializeContextsMap, "crawlToInitializeContextsMap");
              function getContextChangedKeys(fiber) {
                if (idToContextsMap !== null) {
                  var id = getFiberIDThrows(fiber);
                  var prevContexts = idToContextsMap.has(id) ? (
                    // $FlowFixMe[incompatible-use] found when upgrading Flow
                    idToContextsMap.get(id)
                  ) : null;
                  var nextContexts = getContextsForFiber(fiber);
                  if (prevContexts == null || nextContexts == null) {
                    return null;
                  }
                  var _prevContexts = renderer_slicedToArray(prevContexts, 2), prevLegacyContext = _prevContexts[0], prevModernContext = _prevContexts[1];
                  var _nextContexts = renderer_slicedToArray(nextContexts, 2), nextLegacyContext = _nextContexts[0], nextModernContext = _nextContexts[1];
                  switch (getElementTypeForFiber(fiber)) {
                    case types_ElementTypeClass:
                      if (prevContexts && nextContexts) {
                        if (nextLegacyContext !== NO_CONTEXT) {
                          return getChangedKeys(prevLegacyContext, nextLegacyContext);
                        } else if (nextModernContext !== NO_CONTEXT) {
                          return prevModernContext !== nextModernContext;
                        }
                      }
                      break;
                    case types_ElementTypeForwardRef:
                    case types_ElementTypeFunction:
                    case types_ElementTypeMemo:
                      if (nextModernContext !== NO_CONTEXT) {
                        var prevContext = prevModernContext;
                        var nextContext = nextModernContext;
                        while (prevContext && nextContext) {
                          if (!shared_objectIs(prevContext.memoizedValue, nextContext.memoizedValue)) {
                            return true;
                          }
                          prevContext = prevContext.next;
                          nextContext = nextContext.next;
                        }
                        return false;
                      }
                      break;
                    default:
                      break;
                  }
                }
                return null;
              }
              __name(getContextChangedKeys, "getContextChangedKeys");
              function isHookThatCanScheduleUpdate(hookObject) {
                var queue = hookObject.queue;
                if (!queue) {
                  return false;
                }
                var boundHasOwnProperty = shared_hasOwnProperty.bind(queue);
                if (boundHasOwnProperty("pending")) {
                  return true;
                }
                return boundHasOwnProperty("value") && boundHasOwnProperty("getSnapshot") && typeof queue.getSnapshot === "function";
              }
              __name(isHookThatCanScheduleUpdate, "isHookThatCanScheduleUpdate");
              function didStatefulHookChange(prev, next) {
                var prevMemoizedState = prev.memoizedState;
                var nextMemoizedState = next.memoizedState;
                if (isHookThatCanScheduleUpdate(prev)) {
                  return prevMemoizedState !== nextMemoizedState;
                }
                return false;
              }
              __name(didStatefulHookChange, "didStatefulHookChange");
              function getChangedHooksIndices(prev, next) {
                if (prev == null || next == null) {
                  return null;
                }
                var indices = [];
                var index = 0;
                if (next.hasOwnProperty("baseState") && next.hasOwnProperty("memoizedState") && next.hasOwnProperty("next") && next.hasOwnProperty("queue")) {
                  while (next !== null) {
                    if (didStatefulHookChange(prev, next)) {
                      indices.push(index);
                    }
                    next = next.next;
                    prev = prev.next;
                    index++;
                  }
                }
                return indices;
              }
              __name(getChangedHooksIndices, "getChangedHooksIndices");
              function getChangedKeys(prev, next) {
                if (prev == null || next == null) {
                  return null;
                }
                if (next.hasOwnProperty("baseState") && next.hasOwnProperty("memoizedState") && next.hasOwnProperty("next") && next.hasOwnProperty("queue")) {
                  return null;
                }
                var keys = new Set([].concat(renderer_toConsumableArray(Object.keys(prev)), renderer_toConsumableArray(Object.keys(next))));
                var changedKeys = [];
                var _iterator5 = _createForOfIteratorHelper(keys), _step5;
                try {
                  for (_iterator5.s(); !(_step5 = _iterator5.n()).done; ) {
                    var key = _step5.value;
                    if (prev[key] !== next[key]) {
                      changedKeys.push(key);
                    }
                  }
                } catch (err) {
                  _iterator5.e(err);
                } finally {
                  _iterator5.f();
                }
                return changedKeys;
              }
              __name(getChangedKeys, "getChangedKeys");
              function didFiberRender(prevFiber, nextFiber) {
                switch (nextFiber.tag) {
                  case ClassComponent:
                  case FunctionComponent:
                  case ContextConsumer:
                  case MemoComponent:
                  case SimpleMemoComponent:
                  case ForwardRef:
                    var PerformedWork = 1;
                    return (getFiberFlags(nextFiber) & PerformedWork) === PerformedWork;
                  // Note: ContextConsumer only gets PerformedWork effect in 16.3.3+
                  // so it won't get highlighted with React 16.3.0 to 16.3.2.
                  default:
                    return prevFiber.memoizedProps !== nextFiber.memoizedProps || prevFiber.memoizedState !== nextFiber.memoizedState || prevFiber.ref !== nextFiber.ref;
                }
              }
              __name(didFiberRender, "didFiberRender");
              var pendingOperations = [];
              var pendingRealUnmountedIDs = [];
              var pendingSimulatedUnmountedIDs = [];
              var pendingOperationsQueue = [];
              var pendingStringTable = /* @__PURE__ */ new Map();
              var pendingStringTableLength = 0;
              var pendingUnmountedRootID = null;
              function pushOperation(op) {
                if (false) {
                }
                pendingOperations.push(op);
              }
              __name(pushOperation, "pushOperation");
              function shouldBailoutWithPendingOperations() {
                if (isProfiling) {
                  if (currentCommitProfilingMetadata != null && currentCommitProfilingMetadata.durations.length > 0) {
                    return false;
                  }
                }
                return pendingOperations.length === 0 && pendingRealUnmountedIDs.length === 0 && pendingSimulatedUnmountedIDs.length === 0 && pendingUnmountedRootID === null;
              }
              __name(shouldBailoutWithPendingOperations, "shouldBailoutWithPendingOperations");
              function flushOrQueueOperations(operations) {
                if (shouldBailoutWithPendingOperations()) {
                  return;
                }
                if (pendingOperationsQueue !== null) {
                  pendingOperationsQueue.push(operations);
                } else {
                  hook2.emit("operations", operations);
                }
              }
              __name(flushOrQueueOperations, "flushOrQueueOperations");
              var flushPendingErrorsAndWarningsAfterDelayTimeoutID = null;
              function clearPendingErrorsAndWarningsAfterDelay() {
                if (flushPendingErrorsAndWarningsAfterDelayTimeoutID !== null) {
                  clearTimeout(flushPendingErrorsAndWarningsAfterDelayTimeoutID);
                  flushPendingErrorsAndWarningsAfterDelayTimeoutID = null;
                }
              }
              __name(clearPendingErrorsAndWarningsAfterDelay, "clearPendingErrorsAndWarningsAfterDelay");
              function flushPendingErrorsAndWarningsAfterDelay() {
                clearPendingErrorsAndWarningsAfterDelay();
                flushPendingErrorsAndWarningsAfterDelayTimeoutID = setTimeout(function() {
                  flushPendingErrorsAndWarningsAfterDelayTimeoutID = null;
                  if (pendingOperations.length > 0) {
                    return;
                  }
                  recordPendingErrorsAndWarnings();
                  if (shouldBailoutWithPendingOperations()) {
                    return;
                  }
                  var operations = new Array(3 + pendingOperations.length);
                  operations[0] = rendererID;
                  operations[1] = currentRootID;
                  operations[2] = 0;
                  for (var j = 0; j < pendingOperations.length; j++) {
                    operations[3 + j] = pendingOperations[j];
                  }
                  flushOrQueueOperations(operations);
                  pendingOperations.length = 0;
                }, 1e3);
              }
              __name(flushPendingErrorsAndWarningsAfterDelay, "flushPendingErrorsAndWarningsAfterDelay");
              function reevaluateErrorsAndWarnings() {
                fibersWithChangedErrorOrWarningCounts.clear();
                fiberIDToErrorsMap.forEach(function(countMap, fiberID) {
                  var fiber = idToArbitraryFiberMap.get(fiberID);
                  if (fiber != null) {
                    fibersWithChangedErrorOrWarningCounts.add(fiber);
                  }
                });
                fiberIDToWarningsMap.forEach(function(countMap, fiberID) {
                  var fiber = idToArbitraryFiberMap.get(fiberID);
                  if (fiber != null) {
                    fibersWithChangedErrorOrWarningCounts.add(fiber);
                  }
                });
                recordPendingErrorsAndWarnings();
              }
              __name(reevaluateErrorsAndWarnings, "reevaluateErrorsAndWarnings");
              function mergeMapsAndGetCountHelper(fiber, fiberID, pendingFiberToMessageCountMap, fiberIDToMessageCountMap) {
                var newCount = 0;
                var messageCountMap = fiberIDToMessageCountMap.get(fiberID);
                var pendingMessageCountMap = pendingFiberToMessageCountMap.get(fiber);
                if (pendingMessageCountMap != null) {
                  if (messageCountMap == null) {
                    messageCountMap = pendingMessageCountMap;
                    fiberIDToMessageCountMap.set(fiberID, pendingMessageCountMap);
                  } else {
                    var refinedMessageCountMap = messageCountMap;
                    pendingMessageCountMap.forEach(function(pendingCount, message) {
                      var previousCount = refinedMessageCountMap.get(message) || 0;
                      refinedMessageCountMap.set(message, previousCount + pendingCount);
                    });
                  }
                }
                if (!shouldFilterFiber(fiber)) {
                  if (messageCountMap != null) {
                    messageCountMap.forEach(function(count) {
                      newCount += count;
                    });
                  }
                }
                pendingFiberToMessageCountMap.delete(fiber);
                return newCount;
              }
              __name(mergeMapsAndGetCountHelper, "mergeMapsAndGetCountHelper");
              function recordPendingErrorsAndWarnings() {
                clearPendingErrorsAndWarningsAfterDelay();
                fibersWithChangedErrorOrWarningCounts.forEach(function(fiber) {
                  var fiberID = getFiberIDUnsafe(fiber);
                  if (fiberID === null) {
                  } else {
                    var errorCount = mergeMapsAndGetCountHelper(fiber, fiberID, pendingFiberToErrorsMap, fiberIDToErrorsMap);
                    var warningCount = mergeMapsAndGetCountHelper(fiber, fiberID, pendingFiberToWarningsMap, fiberIDToWarningsMap);
                    pushOperation(TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS);
                    pushOperation(fiberID);
                    pushOperation(errorCount);
                    pushOperation(warningCount);
                  }
                  pendingFiberToErrorsMap.delete(fiber);
                  pendingFiberToWarningsMap.delete(fiber);
                });
                fibersWithChangedErrorOrWarningCounts.clear();
              }
              __name(recordPendingErrorsAndWarnings, "recordPendingErrorsAndWarnings");
              function flushPendingEvents(root) {
                recordPendingErrorsAndWarnings();
                if (shouldBailoutWithPendingOperations()) {
                  return;
                }
                var numUnmountIDs = pendingRealUnmountedIDs.length + pendingSimulatedUnmountedIDs.length + (pendingUnmountedRootID === null ? 0 : 1);
                var operations = new Array(
                  // Identify which renderer this update is coming from.
                  2 + // [rendererID, rootFiberID]
                  // How big is the string table?
                  1 + // [stringTableLength]
                  // Then goes the actual string table.
                  pendingStringTableLength + // All unmounts are batched in a single message.
                  // [TREE_OPERATION_REMOVE, removedIDLength, ...ids]
                  (numUnmountIDs > 0 ? 2 + numUnmountIDs : 0) + // Regular operations
                  pendingOperations.length
                );
                var i = 0;
                operations[i++] = rendererID;
                operations[i++] = currentRootID;
                operations[i++] = pendingStringTableLength;
                pendingStringTable.forEach(function(entry, stringKey) {
                  var encodedString = entry.encodedString;
                  var length = encodedString.length;
                  operations[i++] = length;
                  for (var j2 = 0; j2 < length; j2++) {
                    operations[i + j2] = encodedString[j2];
                  }
                  i += length;
                });
                if (numUnmountIDs > 0) {
                  operations[i++] = TREE_OPERATION_REMOVE;
                  operations[i++] = numUnmountIDs;
                  for (var j = pendingRealUnmountedIDs.length - 1; j >= 0; j--) {
                    operations[i++] = pendingRealUnmountedIDs[j];
                  }
                  for (var _j = 0; _j < pendingSimulatedUnmountedIDs.length; _j++) {
                    operations[i + _j] = pendingSimulatedUnmountedIDs[_j];
                  }
                  i += pendingSimulatedUnmountedIDs.length;
                  if (pendingUnmountedRootID !== null) {
                    operations[i] = pendingUnmountedRootID;
                    i++;
                  }
                }
                for (var _j2 = 0; _j2 < pendingOperations.length; _j2++) {
                  operations[i + _j2] = pendingOperations[_j2];
                }
                i += pendingOperations.length;
                flushOrQueueOperations(operations);
                pendingOperations.length = 0;
                pendingRealUnmountedIDs.length = 0;
                pendingSimulatedUnmountedIDs.length = 0;
                pendingUnmountedRootID = null;
                pendingStringTable.clear();
                pendingStringTableLength = 0;
              }
              __name(flushPendingEvents, "flushPendingEvents");
              function getStringID(string) {
                if (string === null) {
                  return 0;
                }
                var existingEntry = pendingStringTable.get(string);
                if (existingEntry !== void 0) {
                  return existingEntry.id;
                }
                var id = pendingStringTable.size + 1;
                var encodedString = utfEncodeString(string);
                pendingStringTable.set(string, {
                  encodedString,
                  id
                });
                pendingStringTableLength += encodedString.length + 1;
                return id;
              }
              __name(getStringID, "getStringID");
              function recordMount(fiber, parentFiber) {
                var isRoot = fiber.tag === HostRoot;
                var id = getOrGenerateFiberID(fiber);
                if (__DEBUG__) {
                  debug3("recordMount()", fiber, parentFiber);
                }
                var hasOwnerMetadata = fiber.hasOwnProperty("_debugOwner");
                var isProfilingSupported = fiber.hasOwnProperty("treeBaseDuration");
                var profilingFlags = 0;
                if (isProfilingSupported) {
                  profilingFlags = PROFILING_FLAG_BASIC_SUPPORT;
                  if (typeof injectProfilingHooks === "function") {
                    profilingFlags |= PROFILING_FLAG_TIMELINE_SUPPORT;
                  }
                }
                if (isRoot) {
                  pushOperation(TREE_OPERATION_ADD);
                  pushOperation(id);
                  pushOperation(ElementTypeRoot);
                  pushOperation((fiber.mode & StrictModeBits) !== 0 ? 1 : 0);
                  pushOperation(profilingFlags);
                  pushOperation(StrictModeBits !== 0 ? 1 : 0);
                  pushOperation(hasOwnerMetadata ? 1 : 0);
                  if (isProfiling) {
                    if (displayNamesByRootID !== null) {
                      displayNamesByRootID.set(id, getDisplayNameForRoot(fiber));
                    }
                  }
                } else {
                  var key = fiber.key;
                  var displayName = getDisplayNameForFiber(fiber);
                  var elementType = getElementTypeForFiber(fiber);
                  var _debugOwner = fiber._debugOwner;
                  var ownerID = _debugOwner != null ? getOrGenerateFiberID(_debugOwner) : 0;
                  var parentID = parentFiber ? getFiberIDThrows(parentFiber) : 0;
                  var displayNameStringID = getStringID(displayName);
                  var keyString = key === null ? null : String(key);
                  var keyStringID = getStringID(keyString);
                  pushOperation(TREE_OPERATION_ADD);
                  pushOperation(id);
                  pushOperation(elementType);
                  pushOperation(parentID);
                  pushOperation(ownerID);
                  pushOperation(displayNameStringID);
                  pushOperation(keyStringID);
                  if ((fiber.mode & StrictModeBits) !== 0 && (parentFiber.mode & StrictModeBits) === 0) {
                    pushOperation(TREE_OPERATION_SET_SUBTREE_MODE);
                    pushOperation(id);
                    pushOperation(StrictMode);
                  }
                }
                if (isProfilingSupported) {
                  idToRootMap.set(id, currentRootID);
                  recordProfilingDurations(fiber);
                }
              }
              __name(recordMount, "recordMount");
              function recordUnmount(fiber, isSimulated) {
                if (__DEBUG__) {
                  debug3("recordUnmount()", fiber, null, isSimulated ? "unmount is simulated" : "");
                }
                if (trackedPathMatchFiber !== null) {
                  if (fiber === trackedPathMatchFiber || fiber === trackedPathMatchFiber.alternate) {
                    setTrackedPath(null);
                  }
                }
                var unsafeID = getFiberIDUnsafe(fiber);
                if (unsafeID === null) {
                  return;
                }
                var id = unsafeID;
                var isRoot = fiber.tag === HostRoot;
                if (isRoot) {
                  pendingUnmountedRootID = id;
                } else if (!shouldFilterFiber(fiber)) {
                  if (isSimulated) {
                    pendingSimulatedUnmountedIDs.push(id);
                  } else {
                    pendingRealUnmountedIDs.push(id);
                  }
                }
                if (!fiber._debugNeedsRemount) {
                  untrackFiberID(fiber);
                  var isProfilingSupported = fiber.hasOwnProperty("treeBaseDuration");
                  if (isProfilingSupported) {
                    idToRootMap.delete(id);
                    idToTreeBaseDurationMap.delete(id);
                  }
                }
              }
              __name(recordUnmount, "recordUnmount");
              function mountFiberRecursively(firstChild, parentFiber, traverseSiblings, traceNearestHostComponentUpdate) {
                var fiber = firstChild;
                while (fiber !== null) {
                  getOrGenerateFiberID(fiber);
                  if (__DEBUG__) {
                    debug3("mountFiberRecursively()", fiber, parentFiber);
                  }
                  var mightSiblingsBeOnTrackedPath = updateTrackedPathStateBeforeMount(fiber);
                  var shouldIncludeInTree = !shouldFilterFiber(fiber);
                  if (shouldIncludeInTree) {
                    recordMount(fiber, parentFiber);
                  }
                  if (traceUpdatesEnabled) {
                    if (traceNearestHostComponentUpdate) {
                      var elementType = getElementTypeForFiber(fiber);
                      if (elementType === ElementTypeHostComponent) {
                        traceUpdatesForNodes.add(fiber.stateNode);
                        traceNearestHostComponentUpdate = false;
                      }
                    }
                  }
                  var isSuspense = fiber.tag === ReactTypeOfWork.SuspenseComponent;
                  if (isSuspense) {
                    var isTimedOut = fiber.memoizedState !== null;
                    if (isTimedOut) {
                      var primaryChildFragment = fiber.child;
                      var fallbackChildFragment = primaryChildFragment ? primaryChildFragment.sibling : null;
                      var fallbackChild = fallbackChildFragment ? fallbackChildFragment.child : null;
                      if (fallbackChild !== null) {
                        mountFiberRecursively(fallbackChild, shouldIncludeInTree ? fiber : parentFiber, true, traceNearestHostComponentUpdate);
                      }
                    } else {
                      var primaryChild = null;
                      var areSuspenseChildrenConditionallyWrapped = OffscreenComponent === -1;
                      if (areSuspenseChildrenConditionallyWrapped) {
                        primaryChild = fiber.child;
                      } else if (fiber.child !== null) {
                        primaryChild = fiber.child.child;
                      }
                      if (primaryChild !== null) {
                        mountFiberRecursively(primaryChild, shouldIncludeInTree ? fiber : parentFiber, true, traceNearestHostComponentUpdate);
                      }
                    }
                  } else {
                    if (fiber.child !== null) {
                      mountFiberRecursively(fiber.child, shouldIncludeInTree ? fiber : parentFiber, true, traceNearestHostComponentUpdate);
                    }
                  }
                  updateTrackedPathStateAfterMount(mightSiblingsBeOnTrackedPath);
                  fiber = traverseSiblings ? fiber.sibling : null;
                }
              }
              __name(mountFiberRecursively, "mountFiberRecursively");
              function unmountFiberChildrenRecursively(fiber) {
                if (__DEBUG__) {
                  debug3("unmountFiberChildrenRecursively()", fiber);
                }
                var isTimedOutSuspense = fiber.tag === ReactTypeOfWork.SuspenseComponent && fiber.memoizedState !== null;
                var child = fiber.child;
                if (isTimedOutSuspense) {
                  var primaryChildFragment = fiber.child;
                  var fallbackChildFragment = primaryChildFragment ? primaryChildFragment.sibling : null;
                  child = fallbackChildFragment ? fallbackChildFragment.child : null;
                }
                while (child !== null) {
                  if (child.return !== null) {
                    unmountFiberChildrenRecursively(child);
                    recordUnmount(child, true);
                  }
                  child = child.sibling;
                }
              }
              __name(unmountFiberChildrenRecursively, "unmountFiberChildrenRecursively");
              function recordProfilingDurations(fiber) {
                var id = getFiberIDThrows(fiber);
                var actualDuration = fiber.actualDuration, treeBaseDuration = fiber.treeBaseDuration;
                idToTreeBaseDurationMap.set(id, treeBaseDuration || 0);
                if (isProfiling) {
                  var alternate = fiber.alternate;
                  if (alternate == null || treeBaseDuration !== alternate.treeBaseDuration) {
                    var convertedTreeBaseDuration = Math.floor((treeBaseDuration || 0) * 1e3);
                    pushOperation(TREE_OPERATION_UPDATE_TREE_BASE_DURATION);
                    pushOperation(id);
                    pushOperation(convertedTreeBaseDuration);
                  }
                  if (alternate == null || didFiberRender(alternate, fiber)) {
                    if (actualDuration != null) {
                      var selfDuration = actualDuration;
                      var child = fiber.child;
                      while (child !== null) {
                        selfDuration -= child.actualDuration || 0;
                        child = child.sibling;
                      }
                      var metadata = currentCommitProfilingMetadata;
                      metadata.durations.push(id, actualDuration, selfDuration);
                      metadata.maxActualDuration = Math.max(metadata.maxActualDuration, actualDuration);
                      if (recordChangeDescriptions) {
                        var changeDescription = getChangeDescription(alternate, fiber);
                        if (changeDescription !== null) {
                          if (metadata.changeDescriptions !== null) {
                            metadata.changeDescriptions.set(id, changeDescription);
                          }
                        }
                        updateContextsForFiber(fiber);
                      }
                    }
                  }
                }
              }
              __name(recordProfilingDurations, "recordProfilingDurations");
              function recordResetChildren(fiber, childSet) {
                if (__DEBUG__) {
                  debug3("recordResetChildren()", childSet, fiber);
                }
                var nextChildren = [];
                var child = childSet;
                while (child !== null) {
                  findReorderedChildrenRecursively(child, nextChildren);
                  child = child.sibling;
                }
                var numChildren = nextChildren.length;
                if (numChildren < 2) {
                  return;
                }
                pushOperation(TREE_OPERATION_REORDER_CHILDREN);
                pushOperation(getFiberIDThrows(fiber));
                pushOperation(numChildren);
                for (var i = 0; i < nextChildren.length; i++) {
                  pushOperation(nextChildren[i]);
                }
              }
              __name(recordResetChildren, "recordResetChildren");
              function findReorderedChildrenRecursively(fiber, nextChildren) {
                if (!shouldFilterFiber(fiber)) {
                  nextChildren.push(getFiberIDThrows(fiber));
                } else {
                  var child = fiber.child;
                  var isTimedOutSuspense = fiber.tag === SuspenseComponent && fiber.memoizedState !== null;
                  if (isTimedOutSuspense) {
                    var primaryChildFragment = fiber.child;
                    var fallbackChildFragment = primaryChildFragment ? primaryChildFragment.sibling : null;
                    var fallbackChild = fallbackChildFragment ? fallbackChildFragment.child : null;
                    if (fallbackChild !== null) {
                      child = fallbackChild;
                    }
                  }
                  while (child !== null) {
                    findReorderedChildrenRecursively(child, nextChildren);
                    child = child.sibling;
                  }
                }
              }
              __name(findReorderedChildrenRecursively, "findReorderedChildrenRecursively");
              function updateFiberRecursively(nextFiber, prevFiber, parentFiber, traceNearestHostComponentUpdate) {
                var id = getOrGenerateFiberID(nextFiber);
                if (__DEBUG__) {
                  debug3("updateFiberRecursively()", nextFiber, parentFiber);
                }
                if (traceUpdatesEnabled) {
                  var elementType = getElementTypeForFiber(nextFiber);
                  if (traceNearestHostComponentUpdate) {
                    if (elementType === ElementTypeHostComponent) {
                      traceUpdatesForNodes.add(nextFiber.stateNode);
                      traceNearestHostComponentUpdate = false;
                    }
                  } else {
                    if (elementType === types_ElementTypeFunction || elementType === types_ElementTypeClass || elementType === ElementTypeContext || elementType === types_ElementTypeMemo || elementType === types_ElementTypeForwardRef) {
                      traceNearestHostComponentUpdate = didFiberRender(prevFiber, nextFiber);
                    }
                  }
                }
                if (mostRecentlyInspectedElement !== null && mostRecentlyInspectedElement.id === id && didFiberRender(prevFiber, nextFiber)) {
                  hasElementUpdatedSinceLastInspected = true;
                }
                var shouldIncludeInTree = !shouldFilterFiber(nextFiber);
                var isSuspense = nextFiber.tag === SuspenseComponent;
                var shouldResetChildren = false;
                var prevDidTimeout = isSuspense && prevFiber.memoizedState !== null;
                var nextDidTimeOut = isSuspense && nextFiber.memoizedState !== null;
                if (prevDidTimeout && nextDidTimeOut) {
                  var nextFiberChild = nextFiber.child;
                  var nextFallbackChildSet = nextFiberChild ? nextFiberChild.sibling : null;
                  var prevFiberChild = prevFiber.child;
                  var prevFallbackChildSet = prevFiberChild ? prevFiberChild.sibling : null;
                  if (prevFallbackChildSet == null && nextFallbackChildSet != null) {
                    mountFiberRecursively(nextFallbackChildSet, shouldIncludeInTree ? nextFiber : parentFiber, true, traceNearestHostComponentUpdate);
                    shouldResetChildren = true;
                  }
                  if (nextFallbackChildSet != null && prevFallbackChildSet != null && updateFiberRecursively(nextFallbackChildSet, prevFallbackChildSet, nextFiber, traceNearestHostComponentUpdate)) {
                    shouldResetChildren = true;
                  }
                } else if (prevDidTimeout && !nextDidTimeOut) {
                  var nextPrimaryChildSet = nextFiber.child;
                  if (nextPrimaryChildSet !== null) {
                    mountFiberRecursively(nextPrimaryChildSet, shouldIncludeInTree ? nextFiber : parentFiber, true, traceNearestHostComponentUpdate);
                  }
                  shouldResetChildren = true;
                } else if (!prevDidTimeout && nextDidTimeOut) {
                  unmountFiberChildrenRecursively(prevFiber);
                  var _nextFiberChild = nextFiber.child;
                  var _nextFallbackChildSet = _nextFiberChild ? _nextFiberChild.sibling : null;
                  if (_nextFallbackChildSet != null) {
                    mountFiberRecursively(_nextFallbackChildSet, shouldIncludeInTree ? nextFiber : parentFiber, true, traceNearestHostComponentUpdate);
                    shouldResetChildren = true;
                  }
                } else {
                  if (nextFiber.child !== prevFiber.child) {
                    var nextChild = nextFiber.child;
                    var prevChildAtSameIndex = prevFiber.child;
                    while (nextChild) {
                      if (nextChild.alternate) {
                        var prevChild = nextChild.alternate;
                        if (updateFiberRecursively(nextChild, prevChild, shouldIncludeInTree ? nextFiber : parentFiber, traceNearestHostComponentUpdate)) {
                          shouldResetChildren = true;
                        }
                        if (prevChild !== prevChildAtSameIndex) {
                          shouldResetChildren = true;
                        }
                      } else {
                        mountFiberRecursively(nextChild, shouldIncludeInTree ? nextFiber : parentFiber, false, traceNearestHostComponentUpdate);
                        shouldResetChildren = true;
                      }
                      nextChild = nextChild.sibling;
                      if (!shouldResetChildren && prevChildAtSameIndex !== null) {
                        prevChildAtSameIndex = prevChildAtSameIndex.sibling;
                      }
                    }
                    if (prevChildAtSameIndex !== null) {
                      shouldResetChildren = true;
                    }
                  } else {
                    if (traceUpdatesEnabled) {
                      if (traceNearestHostComponentUpdate) {
                        var hostFibers = findAllCurrentHostFibers(getFiberIDThrows(nextFiber));
                        hostFibers.forEach(function(hostFiber) {
                          traceUpdatesForNodes.add(hostFiber.stateNode);
                        });
                      }
                    }
                  }
                }
                if (shouldIncludeInTree) {
                  var isProfilingSupported = nextFiber.hasOwnProperty("treeBaseDuration");
                  if (isProfilingSupported) {
                    recordProfilingDurations(nextFiber);
                  }
                }
                if (shouldResetChildren) {
                  if (shouldIncludeInTree) {
                    var nextChildSet = nextFiber.child;
                    if (nextDidTimeOut) {
                      var _nextFiberChild2 = nextFiber.child;
                      nextChildSet = _nextFiberChild2 ? _nextFiberChild2.sibling : null;
                    }
                    if (nextChildSet != null) {
                      recordResetChildren(nextFiber, nextChildSet);
                    }
                    return false;
                  } else {
                    return true;
                  }
                } else {
                  return false;
                }
              }
              __name(updateFiberRecursively, "updateFiberRecursively");
              function cleanup() {
              }
              __name(cleanup, "cleanup");
              function rootSupportsProfiling(root) {
                if (root.memoizedInteractions != null) {
                  return true;
                } else if (root.current != null && root.current.hasOwnProperty("treeBaseDuration")) {
                  return true;
                } else {
                  return false;
                }
              }
              __name(rootSupportsProfiling, "rootSupportsProfiling");
              function flushInitialOperations() {
                var localPendingOperationsQueue = pendingOperationsQueue;
                pendingOperationsQueue = null;
                if (localPendingOperationsQueue !== null && localPendingOperationsQueue.length > 0) {
                  localPendingOperationsQueue.forEach(function(operations) {
                    hook2.emit("operations", operations);
                  });
                } else {
                  if (trackedPath !== null) {
                    mightBeOnTrackedPath = true;
                  }
                  hook2.getFiberRoots(rendererID).forEach(function(root) {
                    currentRootID = getOrGenerateFiberID(root.current);
                    setRootPseudoKey(currentRootID, root.current);
                    if (isProfiling && rootSupportsProfiling(root)) {
                      currentCommitProfilingMetadata = {
                        changeDescriptions: recordChangeDescriptions ? /* @__PURE__ */ new Map() : null,
                        durations: [],
                        commitTime: renderer_getCurrentTime() - profilingStartTime,
                        maxActualDuration: 0,
                        priorityLevel: null,
                        updaters: getUpdatersList(root),
                        effectDuration: null,
                        passiveEffectDuration: null
                      };
                    }
                    mountFiberRecursively(root.current, null, false, false);
                    flushPendingEvents(root);
                    currentRootID = -1;
                  });
                }
              }
              __name(flushInitialOperations, "flushInitialOperations");
              function getUpdatersList(root) {
                return root.memoizedUpdaters != null ? Array.from(root.memoizedUpdaters).filter(function(fiber) {
                  return getFiberIDUnsafe(fiber) !== null;
                }).map(fiberToSerializedElement) : null;
              }
              __name(getUpdatersList, "getUpdatersList");
              function handleCommitFiberUnmount(fiber) {
                if (!untrackFibersSet.has(fiber)) {
                  recordUnmount(fiber, false);
                }
              }
              __name(handleCommitFiberUnmount, "handleCommitFiberUnmount");
              function handlePostCommitFiberRoot(root) {
                if (isProfiling && rootSupportsProfiling(root)) {
                  if (currentCommitProfilingMetadata !== null) {
                    var _getEffectDurations = getEffectDurations(root), effectDuration = _getEffectDurations.effectDuration, passiveEffectDuration = _getEffectDurations.passiveEffectDuration;
                    currentCommitProfilingMetadata.effectDuration = effectDuration;
                    currentCommitProfilingMetadata.passiveEffectDuration = passiveEffectDuration;
                  }
                }
              }
              __name(handlePostCommitFiberRoot, "handlePostCommitFiberRoot");
              function handleCommitFiberRoot(root, priorityLevel) {
                var current = root.current;
                var alternate = current.alternate;
                untrackFibers();
                currentRootID = getOrGenerateFiberID(current);
                if (trackedPath !== null) {
                  mightBeOnTrackedPath = true;
                }
                if (traceUpdatesEnabled) {
                  traceUpdatesForNodes.clear();
                }
                var isProfilingSupported = rootSupportsProfiling(root);
                if (isProfiling && isProfilingSupported) {
                  currentCommitProfilingMetadata = {
                    changeDescriptions: recordChangeDescriptions ? /* @__PURE__ */ new Map() : null,
                    durations: [],
                    commitTime: renderer_getCurrentTime() - profilingStartTime,
                    maxActualDuration: 0,
                    priorityLevel: priorityLevel == null ? null : formatPriorityLevel(priorityLevel),
                    updaters: getUpdatersList(root),
                    // Initialize to null; if new enough React version is running,
                    // these values will be read during separate handlePostCommitFiberRoot() call.
                    effectDuration: null,
                    passiveEffectDuration: null
                  };
                }
                if (alternate) {
                  var wasMounted = alternate.memoizedState != null && alternate.memoizedState.element != null && // A dehydrated root is not considered mounted
                  alternate.memoizedState.isDehydrated !== true;
                  var isMounted = current.memoizedState != null && current.memoizedState.element != null && // A dehydrated root is not considered mounted
                  current.memoizedState.isDehydrated !== true;
                  if (!wasMounted && isMounted) {
                    setRootPseudoKey(currentRootID, current);
                    mountFiberRecursively(current, null, false, false);
                  } else if (wasMounted && isMounted) {
                    updateFiberRecursively(current, alternate, null, false);
                  } else if (wasMounted && !isMounted) {
                    removeRootPseudoKey(currentRootID);
                    recordUnmount(current, false);
                  }
                } else {
                  setRootPseudoKey(currentRootID, current);
                  mountFiberRecursively(current, null, false, false);
                }
                if (isProfiling && isProfilingSupported) {
                  if (!shouldBailoutWithPendingOperations()) {
                    var commitProfilingMetadata = rootToCommitProfilingMetadataMap.get(currentRootID);
                    if (commitProfilingMetadata != null) {
                      commitProfilingMetadata.push(currentCommitProfilingMetadata);
                    } else {
                      rootToCommitProfilingMetadataMap.set(currentRootID, [currentCommitProfilingMetadata]);
                    }
                  }
                }
                flushPendingEvents(root);
                if (traceUpdatesEnabled) {
                  hook2.emit("traceUpdates", traceUpdatesForNodes);
                }
                currentRootID = -1;
              }
              __name(handleCommitFiberRoot, "handleCommitFiberRoot");
              function findAllCurrentHostFibers(id) {
                var fibers = [];
                var fiber = findCurrentFiberUsingSlowPathById(id);
                if (!fiber) {
                  return fibers;
                }
                var node = fiber;
                while (true) {
                  if (node.tag === HostComponent || node.tag === HostText) {
                    fibers.push(node);
                  } else if (node.child) {
                    node.child.return = node;
                    node = node.child;
                    continue;
                  }
                  if (node === fiber) {
                    return fibers;
                  }
                  while (!node.sibling) {
                    if (!node.return || node.return === fiber) {
                      return fibers;
                    }
                    node = node.return;
                  }
                  node.sibling.return = node.return;
                  node = node.sibling;
                }
                return fibers;
              }
              __name(findAllCurrentHostFibers, "findAllCurrentHostFibers");
              function findNativeNodesForFiberID(id) {
                try {
                  var _fiber3 = findCurrentFiberUsingSlowPathById(id);
                  if (_fiber3 === null) {
                    return null;
                  }
                  var hostFibers = findAllCurrentHostFibers(id);
                  return hostFibers.map(function(hostFiber) {
                    return hostFiber.stateNode;
                  }).filter(Boolean);
                } catch (err) {
                  return null;
                }
              }
              __name(findNativeNodesForFiberID, "findNativeNodesForFiberID");
              function getDisplayNameForFiberID(id) {
                var fiber = idToArbitraryFiberMap.get(id);
                return fiber != null ? getDisplayNameForFiber(fiber) : null;
              }
              __name(getDisplayNameForFiberID, "getDisplayNameForFiberID");
              function getFiberForNative(hostInstance) {
                return renderer2.findFiberByHostInstance(hostInstance);
              }
              __name(getFiberForNative, "getFiberForNative");
              function getFiberIDForNative(hostInstance) {
                var findNearestUnfilteredAncestor = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
                var fiber = renderer2.findFiberByHostInstance(hostInstance);
                if (fiber != null) {
                  if (findNearestUnfilteredAncestor) {
                    while (fiber !== null && shouldFilterFiber(fiber)) {
                      fiber = fiber.return;
                    }
                  }
                  return getFiberIDThrows(fiber);
                }
                return null;
              }
              __name(getFiberIDForNative, "getFiberIDForNative");
              function assertIsMounted(fiber) {
                if (getNearestMountedFiber(fiber) !== fiber) {
                  throw new Error("Unable to find node on an unmounted component.");
                }
              }
              __name(assertIsMounted, "assertIsMounted");
              function getNearestMountedFiber(fiber) {
                var node = fiber;
                var nearestMounted = fiber;
                if (!fiber.alternate) {
                  var nextNode = node;
                  do {
                    node = nextNode;
                    var Placement = 2;
                    var Hydrating = 4096;
                    if ((node.flags & (Placement | Hydrating)) !== 0) {
                      nearestMounted = node.return;
                    }
                    nextNode = node.return;
                  } while (nextNode);
                } else {
                  while (node.return) {
                    node = node.return;
                  }
                }
                if (node.tag === HostRoot) {
                  return nearestMounted;
                }
                return null;
              }
              __name(getNearestMountedFiber, "getNearestMountedFiber");
              function findCurrentFiberUsingSlowPathById(id) {
                var fiber = idToArbitraryFiberMap.get(id);
                if (fiber == null) {
                  console.warn('Could not find Fiber with id "'.concat(id, '"'));
                  return null;
                }
                var alternate = fiber.alternate;
                if (!alternate) {
                  var nearestMounted = getNearestMountedFiber(fiber);
                  if (nearestMounted === null) {
                    throw new Error("Unable to find node on an unmounted component.");
                  }
                  if (nearestMounted !== fiber) {
                    return null;
                  }
                  return fiber;
                }
                var a = fiber;
                var b = alternate;
                while (true) {
                  var parentA = a.return;
                  if (parentA === null) {
                    break;
                  }
                  var parentB = parentA.alternate;
                  if (parentB === null) {
                    var nextParent = parentA.return;
                    if (nextParent !== null) {
                      a = b = nextParent;
                      continue;
                    }
                    break;
                  }
                  if (parentA.child === parentB.child) {
                    var child = parentA.child;
                    while (child) {
                      if (child === a) {
                        assertIsMounted(parentA);
                        return fiber;
                      }
                      if (child === b) {
                        assertIsMounted(parentA);
                        return alternate;
                      }
                      child = child.sibling;
                    }
                    throw new Error("Unable to find node on an unmounted component.");
                  }
                  if (a.return !== b.return) {
                    a = parentA;
                    b = parentB;
                  } else {
                    var didFindChild = false;
                    var _child = parentA.child;
                    while (_child) {
                      if (_child === a) {
                        didFindChild = true;
                        a = parentA;
                        b = parentB;
                        break;
                      }
                      if (_child === b) {
                        didFindChild = true;
                        b = parentA;
                        a = parentB;
                        break;
                      }
                      _child = _child.sibling;
                    }
                    if (!didFindChild) {
                      _child = parentB.child;
                      while (_child) {
                        if (_child === a) {
                          didFindChild = true;
                          a = parentB;
                          b = parentA;
                          break;
                        }
                        if (_child === b) {
                          didFindChild = true;
                          b = parentB;
                          a = parentA;
                          break;
                        }
                        _child = _child.sibling;
                      }
                      if (!didFindChild) {
                        throw new Error("Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.");
                      }
                    }
                  }
                  if (a.alternate !== b) {
                    throw new Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue.");
                  }
                }
                if (a.tag !== HostRoot) {
                  throw new Error("Unable to find node on an unmounted component.");
                }
                if (a.stateNode.current === a) {
                  return fiber;
                }
                return alternate;
              }
              __name(findCurrentFiberUsingSlowPathById, "findCurrentFiberUsingSlowPathById");
              function prepareViewAttributeSource(id, path108) {
                if (isMostRecentlyInspectedElement(id)) {
                  window.$attribute = utils_getInObject(mostRecentlyInspectedElement, path108);
                }
              }
              __name(prepareViewAttributeSource, "prepareViewAttributeSource");
              function prepareViewElementSource(id) {
                var fiber = idToArbitraryFiberMap.get(id);
                if (fiber == null) {
                  console.warn('Could not find Fiber with id "'.concat(id, '"'));
                  return;
                }
                var elementType = fiber.elementType, tag2 = fiber.tag, type = fiber.type;
                switch (tag2) {
                  case ClassComponent:
                  case IncompleteClassComponent:
                  case IndeterminateComponent:
                  case FunctionComponent:
                    global2.$type = type;
                    break;
                  case ForwardRef:
                    global2.$type = type.render;
                    break;
                  case MemoComponent:
                  case SimpleMemoComponent:
                    global2.$type = elementType != null && elementType.type != null ? elementType.type : type;
                    break;
                  default:
                    global2.$type = null;
                    break;
                }
              }
              __name(prepareViewElementSource, "prepareViewElementSource");
              function fiberToSerializedElement(fiber) {
                return {
                  displayName: getDisplayNameForFiber(fiber) || "Anonymous",
                  id: getFiberIDThrows(fiber),
                  key: fiber.key,
                  type: getElementTypeForFiber(fiber)
                };
              }
              __name(fiberToSerializedElement, "fiberToSerializedElement");
              function getOwnersList(id) {
                var fiber = findCurrentFiberUsingSlowPathById(id);
                if (fiber == null) {
                  return null;
                }
                var _debugOwner = fiber._debugOwner;
                var owners = [fiberToSerializedElement(fiber)];
                if (_debugOwner) {
                  var owner = _debugOwner;
                  while (owner !== null) {
                    owners.unshift(fiberToSerializedElement(owner));
                    owner = owner._debugOwner || null;
                  }
                }
                return owners;
              }
              __name(getOwnersList, "getOwnersList");
              function getInstanceAndStyle(id) {
                var instance = null;
                var style = null;
                var fiber = findCurrentFiberUsingSlowPathById(id);
                if (fiber !== null) {
                  instance = fiber.stateNode;
                  if (fiber.memoizedProps !== null) {
                    style = fiber.memoizedProps.style;
                  }
                }
                return {
                  instance,
                  style
                };
              }
              __name(getInstanceAndStyle, "getInstanceAndStyle");
              function isErrorBoundary(fiber) {
                var tag2 = fiber.tag, type = fiber.type;
                switch (tag2) {
                  case ClassComponent:
                  case IncompleteClassComponent:
                    var instance = fiber.stateNode;
                    return typeof type.getDerivedStateFromError === "function" || instance !== null && typeof instance.componentDidCatch === "function";
                  default:
                    return false;
                }
              }
              __name(isErrorBoundary, "isErrorBoundary");
              function getNearestErrorBoundaryID(fiber) {
                var parent = fiber.return;
                while (parent !== null) {
                  if (isErrorBoundary(parent)) {
                    return getFiberIDUnsafe(parent);
                  }
                  parent = parent.return;
                }
                return null;
              }
              __name(getNearestErrorBoundaryID, "getNearestErrorBoundaryID");
              function inspectElementRaw(id) {
                var fiber = findCurrentFiberUsingSlowPathById(id);
                if (fiber == null) {
                  return null;
                }
                var _debugOwner = fiber._debugOwner, _debugSource = fiber._debugSource, stateNode = fiber.stateNode, key = fiber.key, memoizedProps = fiber.memoizedProps, memoizedState = fiber.memoizedState, dependencies = fiber.dependencies, tag2 = fiber.tag, type = fiber.type;
                var elementType = getElementTypeForFiber(fiber);
                var usesHooks = (tag2 === FunctionComponent || tag2 === SimpleMemoComponent || tag2 === ForwardRef) && (!!memoizedState || !!dependencies);
                var showState = !usesHooks && tag2 !== CacheComponent;
                var typeSymbol = getTypeSymbol(type);
                var canViewSource = false;
                var context2 = null;
                if (tag2 === ClassComponent || tag2 === FunctionComponent || tag2 === IncompleteClassComponent || tag2 === IndeterminateComponent || tag2 === MemoComponent || tag2 === ForwardRef || tag2 === SimpleMemoComponent) {
                  canViewSource = true;
                  if (stateNode && stateNode.context != null) {
                    var shouldHideContext = elementType === types_ElementTypeClass && !(type.contextTypes || type.contextType);
                    if (!shouldHideContext) {
                      context2 = stateNode.context;
                    }
                  }
                } else if (typeSymbol === CONTEXT_NUMBER || typeSymbol === CONTEXT_SYMBOL_STRING) {
                  var consumerResolvedContext = type._context || type;
                  context2 = consumerResolvedContext._currentValue || null;
                  var _current = fiber.return;
                  while (_current !== null) {
                    var currentType = _current.type;
                    var currentTypeSymbol = getTypeSymbol(currentType);
                    if (currentTypeSymbol === PROVIDER_NUMBER || currentTypeSymbol === PROVIDER_SYMBOL_STRING) {
                      var providerResolvedContext = currentType._context || currentType.context;
                      if (providerResolvedContext === consumerResolvedContext) {
                        context2 = _current.memoizedProps.value;
                        break;
                      }
                    }
                    _current = _current.return;
                  }
                }
                var hasLegacyContext = false;
                if (context2 !== null) {
                  hasLegacyContext = !!type.contextTypes;
                  context2 = {
                    value: context2
                  };
                }
                var owners = null;
                if (_debugOwner) {
                  owners = [];
                  var owner = _debugOwner;
                  while (owner !== null) {
                    owners.push(fiberToSerializedElement(owner));
                    owner = owner._debugOwner || null;
                  }
                }
                var isTimedOutSuspense = tag2 === SuspenseComponent && memoizedState !== null;
                var hooks = null;
                if (usesHooks) {
                  var originalConsoleMethods = {};
                  for (var method2 in console) {
                    try {
                      originalConsoleMethods[method2] = console[method2];
                      console[method2] = function() {
                      };
                    } catch (error) {
                    }
                  }
                  try {
                    hooks = (0, react_debug_tools.inspectHooksOfFiber)(
                      fiber,
                      renderer2.currentDispatcherRef,
                      true
                      // Include source location info for hooks
                    );
                  } finally {
                    for (var _method in originalConsoleMethods) {
                      try {
                        console[_method] = originalConsoleMethods[_method];
                      } catch (error) {
                      }
                    }
                  }
                }
                var rootType = null;
                var current = fiber;
                while (current.return !== null) {
                  current = current.return;
                }
                var fiberRoot = current.stateNode;
                if (fiberRoot != null && fiberRoot._debugRootType !== null) {
                  rootType = fiberRoot._debugRootType;
                }
                var errors = fiberIDToErrorsMap.get(id) || /* @__PURE__ */ new Map();
                var warnings = fiberIDToWarningsMap.get(id) || /* @__PURE__ */ new Map();
                var isErrored = false;
                var targetErrorBoundaryID;
                if (isErrorBoundary(fiber)) {
                  var DidCapture = 128;
                  isErrored = (fiber.flags & DidCapture) !== 0 || forceErrorForFiberIDs.get(id) === true;
                  targetErrorBoundaryID = isErrored ? id : getNearestErrorBoundaryID(fiber);
                } else {
                  targetErrorBoundaryID = getNearestErrorBoundaryID(fiber);
                }
                var plugins = {
                  stylex: null
                };
                if (enableStyleXFeatures) {
                  if (memoizedProps != null && memoizedProps.hasOwnProperty("xstyle")) {
                    plugins.stylex = getStyleXData(memoizedProps.xstyle);
                  }
                }
                return {
                  id,
                  // Does the current renderer support editable hooks and function props?
                  canEditHooks: typeof overrideHookState === "function",
                  canEditFunctionProps: typeof overrideProps === "function",
                  // Does the current renderer support advanced editing interface?
                  canEditHooksAndDeletePaths: typeof overrideHookStateDeletePath === "function",
                  canEditHooksAndRenamePaths: typeof overrideHookStateRenamePath === "function",
                  canEditFunctionPropsDeletePaths: typeof overridePropsDeletePath === "function",
                  canEditFunctionPropsRenamePaths: typeof overridePropsRenamePath === "function",
                  canToggleError: supportsTogglingError && targetErrorBoundaryID != null,
                  // Is this error boundary in error state.
                  isErrored,
                  targetErrorBoundaryID,
                  canToggleSuspense: supportsTogglingSuspense && // If it's showing the real content, we can always flip fallback.
                  (!isTimedOutSuspense || // If it's showing fallback because we previously forced it to,
                  // allow toggling it back to remove the fallback override.
                  forceFallbackForSuspenseIDs.has(id)),
                  // Can view component source location.
                  canViewSource,
                  // Does the component have legacy context attached to it.
                  hasLegacyContext,
                  key: key != null ? key : null,
                  displayName: getDisplayNameForFiber(fiber),
                  type: elementType,
                  // Inspectable properties.
                  // TODO Review sanitization approach for the below inspectable values.
                  context: context2,
                  hooks,
                  props: memoizedProps,
                  state: showState ? memoizedState : null,
                  errors: Array.from(errors.entries()),
                  warnings: Array.from(warnings.entries()),
                  // List of owners
                  owners,
                  // Location of component in source code.
                  source: _debugSource || null,
                  rootType,
                  rendererPackageName: renderer2.rendererPackageName,
                  rendererVersion: renderer2.version,
                  plugins
                };
              }
              __name(inspectElementRaw, "inspectElementRaw");
              var mostRecentlyInspectedElement = null;
              var hasElementUpdatedSinceLastInspected = false;
              var currentlyInspectedPaths = {};
              function isMostRecentlyInspectedElement(id) {
                return mostRecentlyInspectedElement !== null && mostRecentlyInspectedElement.id === id;
              }
              __name(isMostRecentlyInspectedElement, "isMostRecentlyInspectedElement");
              function isMostRecentlyInspectedElementCurrent(id) {
                return isMostRecentlyInspectedElement(id) && !hasElementUpdatedSinceLastInspected;
              }
              __name(isMostRecentlyInspectedElementCurrent, "isMostRecentlyInspectedElementCurrent");
              function mergeInspectedPaths(path108) {
                var current = currentlyInspectedPaths;
                path108.forEach(function(key) {
                  if (!current[key]) {
                    current[key] = {};
                  }
                  current = current[key];
                });
              }
              __name(mergeInspectedPaths, "mergeInspectedPaths");
              function createIsPathAllowed(key, secondaryCategory) {
                return /* @__PURE__ */ __name(function isPathAllowed(path108) {
                  switch (secondaryCategory) {
                    case "hooks":
                      if (path108.length === 1) {
                        return true;
                      }
                      if (path108[path108.length - 2] === "hookSource" && path108[path108.length - 1] === "fileName") {
                        return true;
                      }
                      if (path108[path108.length - 1] === "subHooks" || path108[path108.length - 2] === "subHooks") {
                        return true;
                      }
                      break;
                    default:
                      break;
                  }
                  var current = key === null ? currentlyInspectedPaths : currentlyInspectedPaths[key];
                  if (!current) {
                    return false;
                  }
                  for (var i = 0; i < path108.length; i++) {
                    current = current[path108[i]];
                    if (!current) {
                      return false;
                    }
                  }
                  return true;
                }, "isPathAllowed");
              }
              __name(createIsPathAllowed, "createIsPathAllowed");
              function updateSelectedElement(inspectedElement) {
                var hooks = inspectedElement.hooks, id = inspectedElement.id, props = inspectedElement.props;
                var fiber = idToArbitraryFiberMap.get(id);
                if (fiber == null) {
                  console.warn('Could not find Fiber with id "'.concat(id, '"'));
                  return;
                }
                var elementType = fiber.elementType, stateNode = fiber.stateNode, tag2 = fiber.tag, type = fiber.type;
                switch (tag2) {
                  case ClassComponent:
                  case IncompleteClassComponent:
                  case IndeterminateComponent:
                    global2.$r = stateNode;
                    break;
                  case FunctionComponent:
                    global2.$r = {
                      hooks,
                      props,
                      type
                    };
                    break;
                  case ForwardRef:
                    global2.$r = {
                      hooks,
                      props,
                      type: type.render
                    };
                    break;
                  case MemoComponent:
                  case SimpleMemoComponent:
                    global2.$r = {
                      hooks,
                      props,
                      type: elementType != null && elementType.type != null ? elementType.type : type
                    };
                    break;
                  default:
                    global2.$r = null;
                    break;
                }
              }
              __name(updateSelectedElement, "updateSelectedElement");
              function storeAsGlobal(id, path108, count) {
                if (isMostRecentlyInspectedElement(id)) {
                  var value = utils_getInObject(mostRecentlyInspectedElement, path108);
                  var key = "$reactTemp".concat(count);
                  window[key] = value;
                  console.log(key);
                  console.log(value);
                }
              }
              __name(storeAsGlobal, "storeAsGlobal");
              function getSerializedElementValueByPath(id, path108) {
                if (isMostRecentlyInspectedElement(id)) {
                  var valueToCopy = utils_getInObject(mostRecentlyInspectedElement, path108);
                  return serializeToString(valueToCopy);
                }
              }
              __name(getSerializedElementValueByPath, "getSerializedElementValueByPath");
              function inspectElement(requestID, id, path108, forceFullData) {
                if (path108 !== null) {
                  mergeInspectedPaths(path108);
                }
                if (isMostRecentlyInspectedElement(id) && !forceFullData) {
                  if (!hasElementUpdatedSinceLastInspected) {
                    if (path108 !== null) {
                      var secondaryCategory = null;
                      if (path108[0] === "hooks") {
                        secondaryCategory = "hooks";
                      }
                      return {
                        id,
                        responseID: requestID,
                        type: "hydrated-path",
                        path: path108,
                        value: cleanForBridge(utils_getInObject(mostRecentlyInspectedElement, path108), createIsPathAllowed(null, secondaryCategory), path108)
                      };
                    } else {
                      return {
                        id,
                        responseID: requestID,
                        type: "no-change"
                      };
                    }
                  }
                } else {
                  currentlyInspectedPaths = {};
                }
                hasElementUpdatedSinceLastInspected = false;
                try {
                  mostRecentlyInspectedElement = inspectElementRaw(id);
                } catch (error) {
                  if (error.name === "ReactDebugToolsRenderError") {
                    var message = "Error rendering inspected element.";
                    var stack;
                    console.error(message + "\n\n", error);
                    if (error.cause != null) {
                      var _fiber4 = findCurrentFiberUsingSlowPathById(id);
                      var componentName = _fiber4 != null ? getDisplayNameForFiber(_fiber4) : null;
                      console.error("React DevTools encountered an error while trying to inspect hooks. This is most likely caused by an error in current inspected component" + (componentName != null ? ': "'.concat(componentName, '".') : ".") + "\nThe error thrown in the component is: \n\n", error.cause);
                      if (error.cause instanceof Error) {
                        message = error.cause.message || message;
                        stack = error.cause.stack;
                      }
                    }
                    return {
                      type: "error",
                      errorType: "user",
                      id,
                      responseID: requestID,
                      message,
                      stack
                    };
                  }
                  if (error.name === "ReactDebugToolsUnsupportedHookError") {
                    return {
                      type: "error",
                      errorType: "unknown-hook",
                      id,
                      responseID: requestID,
                      message: "Unsupported hook in the react-debug-tools package: " + error.message
                    };
                  }
                  console.error("Error inspecting element.\n\n", error);
                  return {
                    type: "error",
                    errorType: "uncaught",
                    id,
                    responseID: requestID,
                    message: error.message,
                    stack: error.stack
                  };
                }
                if (mostRecentlyInspectedElement === null) {
                  return {
                    id,
                    responseID: requestID,
                    type: "not-found"
                  };
                }
                updateSelectedElement(mostRecentlyInspectedElement);
                var cleanedInspectedElement = renderer_objectSpread({}, mostRecentlyInspectedElement);
                cleanedInspectedElement.context = cleanForBridge(cleanedInspectedElement.context, createIsPathAllowed("context", null));
                cleanedInspectedElement.hooks = cleanForBridge(cleanedInspectedElement.hooks, createIsPathAllowed("hooks", "hooks"));
                cleanedInspectedElement.props = cleanForBridge(cleanedInspectedElement.props, createIsPathAllowed("props", null));
                cleanedInspectedElement.state = cleanForBridge(cleanedInspectedElement.state, createIsPathAllowed("state", null));
                return {
                  id,
                  responseID: requestID,
                  type: "full-data",
                  // $FlowFixMe[prop-missing] found when upgrading Flow
                  value: cleanedInspectedElement
                };
              }
              __name(inspectElement, "inspectElement");
              function logElementToConsole(id) {
                var result = isMostRecentlyInspectedElementCurrent(id) ? mostRecentlyInspectedElement : inspectElementRaw(id);
                if (result === null) {
                  console.warn('Could not find Fiber with id "'.concat(id, '"'));
                  return;
                }
                var supportsGroup = typeof console.groupCollapsed === "function";
                if (supportsGroup) {
                  console.groupCollapsed(
                    "[Click to expand] %c<".concat(result.displayName || "Component", " />"),
                    // --dom-tag-name-color is the CSS variable Chrome styles HTML elements with in the console.
                    "color: var(--dom-tag-name-color); font-weight: normal;"
                  );
                }
                if (result.props !== null) {
                  console.log("Props:", result.props);
                }
                if (result.state !== null) {
                  console.log("State:", result.state);
                }
                if (result.hooks !== null) {
                  console.log("Hooks:", result.hooks);
                }
                var nativeNodes = findNativeNodesForFiberID(id);
                if (nativeNodes !== null) {
                  console.log("Nodes:", nativeNodes);
                }
                if (result.source !== null) {
                  console.log("Location:", result.source);
                }
                if (window.chrome || /firefox/i.test(navigator.userAgent)) {
                  console.log("Right-click any value to save it as a global variable for further inspection.");
                }
                if (supportsGroup) {
                  console.groupEnd();
                }
              }
              __name(logElementToConsole, "logElementToConsole");
              function deletePath(type, id, hookID, path108) {
                var fiber = findCurrentFiberUsingSlowPathById(id);
                if (fiber !== null) {
                  var instance = fiber.stateNode;
                  switch (type) {
                    case "context":
                      path108 = path108.slice(1);
                      switch (fiber.tag) {
                        case ClassComponent:
                          if (path108.length === 0) {
                          } else {
                            deletePathInObject(instance.context, path108);
                          }
                          instance.forceUpdate();
                          break;
                        case FunctionComponent:
                          break;
                      }
                      break;
                    case "hooks":
                      if (typeof overrideHookStateDeletePath === "function") {
                        overrideHookStateDeletePath(fiber, hookID, path108);
                      }
                      break;
                    case "props":
                      if (instance === null) {
                        if (typeof overridePropsDeletePath === "function") {
                          overridePropsDeletePath(fiber, path108);
                        }
                      } else {
                        fiber.pendingProps = copyWithDelete(instance.props, path108);
                        instance.forceUpdate();
                      }
                      break;
                    case "state":
                      deletePathInObject(instance.state, path108);
                      instance.forceUpdate();
                      break;
                  }
                }
              }
              __name(deletePath, "deletePath");
              function renamePath(type, id, hookID, oldPath, newPath) {
                var fiber = findCurrentFiberUsingSlowPathById(id);
                if (fiber !== null) {
                  var instance = fiber.stateNode;
                  switch (type) {
                    case "context":
                      oldPath = oldPath.slice(1);
                      newPath = newPath.slice(1);
                      switch (fiber.tag) {
                        case ClassComponent:
                          if (oldPath.length === 0) {
                          } else {
                            renamePathInObject(instance.context, oldPath, newPath);
                          }
                          instance.forceUpdate();
                          break;
                        case FunctionComponent:
                          break;
                      }
                      break;
                    case "hooks":
                      if (typeof overrideHookStateRenamePath === "function") {
                        overrideHookStateRenamePath(fiber, hookID, oldPath, newPath);
                      }
                      break;
                    case "props":
                      if (instance === null) {
                        if (typeof overridePropsRenamePath === "function") {
                          overridePropsRenamePath(fiber, oldPath, newPath);
                        }
                      } else {
                        fiber.pendingProps = copyWithRename(instance.props, oldPath, newPath);
                        instance.forceUpdate();
                      }
                      break;
                    case "state":
                      renamePathInObject(instance.state, oldPath, newPath);
                      instance.forceUpdate();
                      break;
                  }
                }
              }
              __name(renamePath, "renamePath");
              function overrideValueAtPath(type, id, hookID, path108, value) {
                var fiber = findCurrentFiberUsingSlowPathById(id);
                if (fiber !== null) {
                  var instance = fiber.stateNode;
                  switch (type) {
                    case "context":
                      path108 = path108.slice(1);
                      switch (fiber.tag) {
                        case ClassComponent:
                          if (path108.length === 0) {
                            instance.context = value;
                          } else {
                            utils_setInObject(instance.context, path108, value);
                          }
                          instance.forceUpdate();
                          break;
                        case FunctionComponent:
                          break;
                      }
                      break;
                    case "hooks":
                      if (typeof overrideHookState === "function") {
                        overrideHookState(fiber, hookID, path108, value);
                      }
                      break;
                    case "props":
                      switch (fiber.tag) {
                        case ClassComponent:
                          fiber.pendingProps = copyWithSet(instance.props, path108, value);
                          instance.forceUpdate();
                          break;
                        default:
                          if (typeof overrideProps === "function") {
                            overrideProps(fiber, path108, value);
                          }
                          break;
                      }
                      break;
                    case "state":
                      switch (fiber.tag) {
                        case ClassComponent:
                          utils_setInObject(instance.state, path108, value);
                          instance.forceUpdate();
                          break;
                      }
                      break;
                  }
                }
              }
              __name(overrideValueAtPath, "overrideValueAtPath");
              var currentCommitProfilingMetadata = null;
              var displayNamesByRootID = null;
              var idToContextsMap = null;
              var initialTreeBaseDurationsMap = null;
              var initialIDToRootMap = null;
              var isProfiling = false;
              var profilingStartTime = 0;
              var recordChangeDescriptions = false;
              var rootToCommitProfilingMetadataMap = null;
              function getProfilingData() {
                var dataForRoots = [];
                if (rootToCommitProfilingMetadataMap === null) {
                  throw Error("getProfilingData() called before any profiling data was recorded");
                }
                rootToCommitProfilingMetadataMap.forEach(function(commitProfilingMetadata, rootID) {
                  var commitData = [];
                  var initialTreeBaseDurations = [];
                  var displayName = displayNamesByRootID !== null && displayNamesByRootID.get(rootID) || "Unknown";
                  if (initialTreeBaseDurationsMap != null) {
                    initialTreeBaseDurationsMap.forEach(function(treeBaseDuration, id) {
                      if (initialIDToRootMap != null && initialIDToRootMap.get(id) === rootID) {
                        initialTreeBaseDurations.push([id, treeBaseDuration]);
                      }
                    });
                  }
                  commitProfilingMetadata.forEach(function(commitProfilingData, commitIndex) {
                    var changeDescriptions = commitProfilingData.changeDescriptions, durations = commitProfilingData.durations, effectDuration = commitProfilingData.effectDuration, maxActualDuration = commitProfilingData.maxActualDuration, passiveEffectDuration = commitProfilingData.passiveEffectDuration, priorityLevel = commitProfilingData.priorityLevel, commitTime = commitProfilingData.commitTime, updaters = commitProfilingData.updaters;
                    var fiberActualDurations = [];
                    var fiberSelfDurations = [];
                    for (var i = 0; i < durations.length; i += 3) {
                      var fiberID = durations[i];
                      fiberActualDurations.push([fiberID, durations[i + 1]]);
                      fiberSelfDurations.push([fiberID, durations[i + 2]]);
                    }
                    commitData.push({
                      changeDescriptions: changeDescriptions !== null ? Array.from(changeDescriptions.entries()) : null,
                      duration: maxActualDuration,
                      effectDuration,
                      fiberActualDurations,
                      fiberSelfDurations,
                      passiveEffectDuration,
                      priorityLevel,
                      timestamp: commitTime,
                      updaters
                    });
                  });
                  dataForRoots.push({
                    commitData,
                    displayName,
                    initialTreeBaseDurations,
                    rootID
                  });
                });
                var timelineData = null;
                if (typeof getTimelineData === "function") {
                  var currentTimelineData = getTimelineData();
                  if (currentTimelineData) {
                    var batchUIDToMeasuresMap = currentTimelineData.batchUIDToMeasuresMap, internalModuleSourceToRanges = currentTimelineData.internalModuleSourceToRanges, laneToLabelMap = currentTimelineData.laneToLabelMap, laneToReactMeasureMap = currentTimelineData.laneToReactMeasureMap, rest = _objectWithoutProperties(currentTimelineData, ["batchUIDToMeasuresMap", "internalModuleSourceToRanges", "laneToLabelMap", "laneToReactMeasureMap"]);
                    timelineData = renderer_objectSpread(renderer_objectSpread({}, rest), {}, {
                      // Most of the data is safe to parse as-is,
                      // but we need to convert the nested Arrays back to Maps.
                      // Most of the data is safe to serialize as-is,
                      // but we need to convert the Maps to nested Arrays.
                      batchUIDToMeasuresKeyValueArray: Array.from(batchUIDToMeasuresMap.entries()),
                      internalModuleSourceToRanges: Array.from(internalModuleSourceToRanges.entries()),
                      laneToLabelKeyValueArray: Array.from(laneToLabelMap.entries()),
                      laneToReactMeasureKeyValueArray: Array.from(laneToReactMeasureMap.entries())
                    });
                  }
                }
                return {
                  dataForRoots,
                  rendererID,
                  timelineData
                };
              }
              __name(getProfilingData, "getProfilingData");
              function startProfiling(shouldRecordChangeDescriptions) {
                if (isProfiling) {
                  return;
                }
                recordChangeDescriptions = shouldRecordChangeDescriptions;
                displayNamesByRootID = /* @__PURE__ */ new Map();
                initialTreeBaseDurationsMap = new Map(idToTreeBaseDurationMap);
                initialIDToRootMap = new Map(idToRootMap);
                idToContextsMap = /* @__PURE__ */ new Map();
                hook2.getFiberRoots(rendererID).forEach(function(root) {
                  var rootID = getFiberIDThrows(root.current);
                  displayNamesByRootID.set(rootID, getDisplayNameForRoot(root.current));
                  if (shouldRecordChangeDescriptions) {
                    crawlToInitializeContextsMap(root.current);
                  }
                });
                isProfiling = true;
                profilingStartTime = renderer_getCurrentTime();
                rootToCommitProfilingMetadataMap = /* @__PURE__ */ new Map();
                if (toggleProfilingStatus !== null) {
                  toggleProfilingStatus(true);
                }
              }
              __name(startProfiling, "startProfiling");
              function stopProfiling() {
                isProfiling = false;
                recordChangeDescriptions = false;
                if (toggleProfilingStatus !== null) {
                  toggleProfilingStatus(false);
                }
              }
              __name(stopProfiling, "stopProfiling");
              if (sessionStorageGetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY) === "true") {
                startProfiling(sessionStorageGetItem(SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY) === "true");
              }
              function shouldErrorFiberAlwaysNull() {
                return null;
              }
              __name(shouldErrorFiberAlwaysNull, "shouldErrorFiberAlwaysNull");
              var forceErrorForFiberIDs = /* @__PURE__ */ new Map();
              function shouldErrorFiberAccordingToMap(fiber) {
                if (typeof setErrorHandler !== "function") {
                  throw new Error("Expected overrideError() to not get called for earlier React versions.");
                }
                var id = getFiberIDUnsafe(fiber);
                if (id === null) {
                  return null;
                }
                var status = null;
                if (forceErrorForFiberIDs.has(id)) {
                  status = forceErrorForFiberIDs.get(id);
                  if (status === false) {
                    forceErrorForFiberIDs.delete(id);
                    if (forceErrorForFiberIDs.size === 0) {
                      setErrorHandler(shouldErrorFiberAlwaysNull);
                    }
                  }
                }
                return status;
              }
              __name(shouldErrorFiberAccordingToMap, "shouldErrorFiberAccordingToMap");
              function overrideError(id, forceError) {
                if (typeof setErrorHandler !== "function" || typeof scheduleUpdate !== "function") {
                  throw new Error("Expected overrideError() to not get called for earlier React versions.");
                }
                forceErrorForFiberIDs.set(id, forceError);
                if (forceErrorForFiberIDs.size === 1) {
                  setErrorHandler(shouldErrorFiberAccordingToMap);
                }
                var fiber = idToArbitraryFiberMap.get(id);
                if (fiber != null) {
                  scheduleUpdate(fiber);
                }
              }
              __name(overrideError, "overrideError");
              function shouldSuspendFiberAlwaysFalse() {
                return false;
              }
              __name(shouldSuspendFiberAlwaysFalse, "shouldSuspendFiberAlwaysFalse");
              var forceFallbackForSuspenseIDs = /* @__PURE__ */ new Set();
              function shouldSuspendFiberAccordingToSet(fiber) {
                var maybeID = getFiberIDUnsafe(fiber);
                return maybeID !== null && forceFallbackForSuspenseIDs.has(maybeID);
              }
              __name(shouldSuspendFiberAccordingToSet, "shouldSuspendFiberAccordingToSet");
              function overrideSuspense(id, forceFallback) {
                if (typeof setSuspenseHandler !== "function" || typeof scheduleUpdate !== "function") {
                  throw new Error("Expected overrideSuspense() to not get called for earlier React versions.");
                }
                if (forceFallback) {
                  forceFallbackForSuspenseIDs.add(id);
                  if (forceFallbackForSuspenseIDs.size === 1) {
                    setSuspenseHandler(shouldSuspendFiberAccordingToSet);
                  }
                } else {
                  forceFallbackForSuspenseIDs.delete(id);
                  if (forceFallbackForSuspenseIDs.size === 0) {
                    setSuspenseHandler(shouldSuspendFiberAlwaysFalse);
                  }
                }
                var fiber = idToArbitraryFiberMap.get(id);
                if (fiber != null) {
                  scheduleUpdate(fiber);
                }
              }
              __name(overrideSuspense, "overrideSuspense");
              var trackedPath = null;
              var trackedPathMatchFiber = null;
              var trackedPathMatchDepth = -1;
              var mightBeOnTrackedPath = false;
              function setTrackedPath(path108) {
                if (path108 === null) {
                  trackedPathMatchFiber = null;
                  trackedPathMatchDepth = -1;
                  mightBeOnTrackedPath = false;
                }
                trackedPath = path108;
              }
              __name(setTrackedPath, "setTrackedPath");
              function updateTrackedPathStateBeforeMount(fiber) {
                if (trackedPath === null || !mightBeOnTrackedPath) {
                  return false;
                }
                var returnFiber = fiber.return;
                var returnAlternate = returnFiber !== null ? returnFiber.alternate : null;
                if (trackedPathMatchFiber === returnFiber || trackedPathMatchFiber === returnAlternate && returnAlternate !== null) {
                  var actualFrame = getPathFrame(fiber);
                  var expectedFrame = trackedPath[trackedPathMatchDepth + 1];
                  if (expectedFrame === void 0) {
                    throw new Error("Expected to see a frame at the next depth.");
                  }
                  if (actualFrame.index === expectedFrame.index && actualFrame.key === expectedFrame.key && actualFrame.displayName === expectedFrame.displayName) {
                    trackedPathMatchFiber = fiber;
                    trackedPathMatchDepth++;
                    if (trackedPathMatchDepth === trackedPath.length - 1) {
                      mightBeOnTrackedPath = false;
                    } else {
                      mightBeOnTrackedPath = true;
                    }
                    return false;
                  }
                }
                mightBeOnTrackedPath = false;
                return true;
              }
              __name(updateTrackedPathStateBeforeMount, "updateTrackedPathStateBeforeMount");
              function updateTrackedPathStateAfterMount(mightSiblingsBeOnTrackedPath) {
                mightBeOnTrackedPath = mightSiblingsBeOnTrackedPath;
              }
              __name(updateTrackedPathStateAfterMount, "updateTrackedPathStateAfterMount");
              var rootPseudoKeys = /* @__PURE__ */ new Map();
              var rootDisplayNameCounter = /* @__PURE__ */ new Map();
              function setRootPseudoKey(id, fiber) {
                var name3 = getDisplayNameForRoot(fiber);
                var counter = rootDisplayNameCounter.get(name3) || 0;
                rootDisplayNameCounter.set(name3, counter + 1);
                var pseudoKey = "".concat(name3, ":").concat(counter);
                rootPseudoKeys.set(id, pseudoKey);
              }
              __name(setRootPseudoKey, "setRootPseudoKey");
              function removeRootPseudoKey(id) {
                var pseudoKey = rootPseudoKeys.get(id);
                if (pseudoKey === void 0) {
                  throw new Error("Expected root pseudo key to be known.");
                }
                var name3 = pseudoKey.slice(0, pseudoKey.lastIndexOf(":"));
                var counter = rootDisplayNameCounter.get(name3);
                if (counter === void 0) {
                  throw new Error("Expected counter to be known.");
                }
                if (counter > 1) {
                  rootDisplayNameCounter.set(name3, counter - 1);
                } else {
                  rootDisplayNameCounter.delete(name3);
                }
                rootPseudoKeys.delete(id);
              }
              __name(removeRootPseudoKey, "removeRootPseudoKey");
              function getDisplayNameForRoot(fiber) {
                var preferredDisplayName = null;
                var fallbackDisplayName = null;
                var child = fiber.child;
                for (var i = 0; i < 3; i++) {
                  if (child === null) {
                    break;
                  }
                  var displayName = getDisplayNameForFiber(child);
                  if (displayName !== null) {
                    if (typeof child.type === "function") {
                      preferredDisplayName = displayName;
                    } else if (fallbackDisplayName === null) {
                      fallbackDisplayName = displayName;
                    }
                  }
                  if (preferredDisplayName !== null) {
                    break;
                  }
                  child = child.child;
                }
                return preferredDisplayName || fallbackDisplayName || "Anonymous";
              }
              __name(getDisplayNameForRoot, "getDisplayNameForRoot");
              function getPathFrame(fiber) {
                var key = fiber.key;
                var displayName = getDisplayNameForFiber(fiber);
                var index = fiber.index;
                switch (fiber.tag) {
                  case HostRoot:
                    var id = getFiberIDThrows(fiber);
                    var pseudoKey = rootPseudoKeys.get(id);
                    if (pseudoKey === void 0) {
                      throw new Error("Expected mounted root to have known pseudo key.");
                    }
                    displayName = pseudoKey;
                    break;
                  case HostComponent:
                    displayName = fiber.type;
                    break;
                  default:
                    break;
                }
                return {
                  displayName,
                  key,
                  index
                };
              }
              __name(getPathFrame, "getPathFrame");
              function getPathForElement(id) {
                var fiber = idToArbitraryFiberMap.get(id);
                if (fiber == null) {
                  return null;
                }
                var keyPath = [];
                while (fiber !== null) {
                  keyPath.push(getPathFrame(fiber));
                  fiber = fiber.return;
                }
                keyPath.reverse();
                return keyPath;
              }
              __name(getPathForElement, "getPathForElement");
              function getBestMatchForTrackedPath() {
                if (trackedPath === null) {
                  return null;
                }
                if (trackedPathMatchFiber === null) {
                  return null;
                }
                var fiber = trackedPathMatchFiber;
                while (fiber !== null && shouldFilterFiber(fiber)) {
                  fiber = fiber.return;
                }
                if (fiber === null) {
                  return null;
                }
                return {
                  id: getFiberIDThrows(fiber),
                  // $FlowFixMe[incompatible-use] found when upgrading Flow
                  isFullMatch: trackedPathMatchDepth === trackedPath.length - 1
                };
              }
              __name(getBestMatchForTrackedPath, "getBestMatchForTrackedPath");
              var formatPriorityLevel = /* @__PURE__ */ __name(function formatPriorityLevel2(priorityLevel) {
                if (priorityLevel == null) {
                  return "Unknown";
                }
                switch (priorityLevel) {
                  case ImmediatePriority:
                    return "Immediate";
                  case UserBlockingPriority:
                    return "User-Blocking";
                  case NormalPriority:
                    return "Normal";
                  case LowPriority:
                    return "Low";
                  case IdlePriority:
                    return "Idle";
                  case NoPriority:
                  default:
                    return "Unknown";
                }
              }, "formatPriorityLevel");
              function setTraceUpdatesEnabled(isEnabled3) {
                traceUpdatesEnabled = isEnabled3;
              }
              __name(setTraceUpdatesEnabled, "setTraceUpdatesEnabled");
              function hasFiberWithId(id) {
                return idToArbitraryFiberMap.has(id);
              }
              __name(hasFiberWithId, "hasFiberWithId");
              return {
                cleanup,
                clearErrorsAndWarnings,
                clearErrorsForFiberID,
                clearWarningsForFiberID,
                getSerializedElementValueByPath,
                deletePath,
                findNativeNodesForFiberID,
                flushInitialOperations,
                getBestMatchForTrackedPath,
                getDisplayNameForFiberID,
                getFiberForNative,
                getFiberIDForNative,
                getInstanceAndStyle,
                getOwnersList,
                getPathForElement,
                getProfilingData,
                handleCommitFiberRoot,
                handleCommitFiberUnmount,
                handlePostCommitFiberRoot,
                hasFiberWithId,
                inspectElement,
                logElementToConsole,
                patchConsoleForStrictMode: patchForStrictMode,
                prepareViewAttributeSource,
                prepareViewElementSource,
                overrideError,
                overrideSuspense,
                overrideValueAtPath,
                renamePath,
                renderer: renderer2,
                setTraceUpdatesEnabled,
                setTrackedPath,
                startProfiling,
                stopProfiling,
                storeAsGlobal,
                unpatchConsoleForStrictMode: unpatchForStrictMode,
                updateComponentFilters
              };
            }
            __name(attach, "attach");
            ;
            function console_toConsumableArray(arr) {
              return console_arrayWithoutHoles(arr) || console_iterableToArray(arr) || console_unsupportedIterableToArray(arr) || console_nonIterableSpread();
            }
            __name(console_toConsumableArray, "console_toConsumableArray");
            function console_nonIterableSpread() {
              throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
            }
            __name(console_nonIterableSpread, "console_nonIterableSpread");
            function console_iterableToArray(iter) {
              if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
            }
            __name(console_iterableToArray, "console_iterableToArray");
            function console_arrayWithoutHoles(arr) {
              if (Array.isArray(arr)) return console_arrayLikeToArray(arr);
            }
            __name(console_arrayWithoutHoles, "console_arrayWithoutHoles");
            function console_createForOfIteratorHelper(o2, allowArrayLike) {
              var it;
              if (typeof Symbol === "undefined" || o2[Symbol.iterator] == null) {
                if (Array.isArray(o2) || (it = console_unsupportedIterableToArray(o2)) || allowArrayLike && o2 && typeof o2.length === "number") {
                  if (it) o2 = it;
                  var i = 0;
                  var F = /* @__PURE__ */ __name(function F2() {
                  }, "F");
                  return { s: F, n: /* @__PURE__ */ __name(function n2() {
                    if (i >= o2.length) return { done: true };
                    return { done: false, value: o2[i++] };
                  }, "n"), e: /* @__PURE__ */ __name(function e2(_e) {
                    throw _e;
                  }, "e"), f: F };
                }
                throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
              }
              var normalCompletion = true, didErr = false, err;
              return { s: /* @__PURE__ */ __name(function s2() {
                it = o2[Symbol.iterator]();
              }, "s"), n: /* @__PURE__ */ __name(function n2() {
                var step = it.next();
                normalCompletion = step.done;
                return step;
              }, "n"), e: /* @__PURE__ */ __name(function e2(_e2) {
                didErr = true;
                err = _e2;
              }, "e"), f: /* @__PURE__ */ __name(function f() {
                try {
                  if (!normalCompletion && it.return != null) it.return();
                } finally {
                  if (didErr) throw err;
                }
              }, "f") };
            }
            __name(console_createForOfIteratorHelper, "console_createForOfIteratorHelper");
            function console_unsupportedIterableToArray(o2, minLen) {
              if (!o2) return;
              if (typeof o2 === "string") return console_arrayLikeToArray(o2, minLen);
              var n2 = Object.prototype.toString.call(o2).slice(8, -1);
              if (n2 === "Object" && o2.constructor) n2 = o2.constructor.name;
              if (n2 === "Map" || n2 === "Set") return Array.from(o2);
              if (n2 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n2)) return console_arrayLikeToArray(o2, minLen);
            }
            __name(console_unsupportedIterableToArray, "console_unsupportedIterableToArray");
            function console_arrayLikeToArray(arr, len) {
              if (len == null || len > arr.length) len = arr.length;
              for (var i = 0, arr2 = new Array(len); i < len; i++) {
                arr2[i] = arr[i];
              }
              return arr2;
            }
            __name(console_arrayLikeToArray, "console_arrayLikeToArray");
            var OVERRIDE_CONSOLE_METHODS = ["error", "trace", "warn"];
            var DIMMED_NODE_CONSOLE_COLOR = "\x1B[2m%s\x1B[0m";
            var PREFIX_REGEX = /\s{4}(in|at)\s{1}/;
            var ROW_COLUMN_NUMBER_REGEX = /:\d+:\d+(\n|$)/;
            function isStringComponentStack(text) {
              return PREFIX_REGEX.test(text) || ROW_COLUMN_NUMBER_REGEX.test(text);
            }
            __name(isStringComponentStack, "isStringComponentStack");
            var STYLE_DIRECTIVE_REGEX = /^%c/;
            function isStrictModeOverride(args, method2) {
              return args.length >= 2 && STYLE_DIRECTIVE_REGEX.test(args[0]) && args[1] === "color: ".concat(getConsoleColor(method2) || "");
            }
            __name(isStrictModeOverride, "isStrictModeOverride");
            function getConsoleColor(method2) {
              switch (method2) {
                case "warn":
                  return consoleSettingsRef.browserTheme === "light" ? "rgba(250, 180, 50, 0.75)" : "rgba(250, 180, 50, 0.5)";
                case "error":
                  return consoleSettingsRef.browserTheme === "light" ? "rgba(250, 123, 130, 0.75)" : "rgba(250, 123, 130, 0.5)";
                case "log":
                default:
                  return consoleSettingsRef.browserTheme === "light" ? "rgba(125, 125, 125, 0.75)" : "rgba(125, 125, 125, 0.5)";
              }
            }
            __name(getConsoleColor, "getConsoleColor");
            var injectedRenderers = /* @__PURE__ */ new Map();
            var targetConsole = console;
            var targetConsoleMethods = {};
            for (var method in console) {
              targetConsoleMethods[method] = console[method];
            }
            var unpatchFn = null;
            var isNode3 = false;
            try {
              isNode3 = void 0 === globalThis;
            } catch (error) {
            }
            function dangerous_setTargetConsoleForTesting(targetConsoleForTesting) {
              targetConsole = targetConsoleForTesting;
              targetConsoleMethods = {};
              for (var _method in targetConsole) {
                targetConsoleMethods[_method] = console[_method];
              }
            }
            __name(dangerous_setTargetConsoleForTesting, "dangerous_setTargetConsoleForTesting");
            function registerRenderer(renderer2, onErrorOrWarning) {
              var currentDispatcherRef = renderer2.currentDispatcherRef, getCurrentFiber = renderer2.getCurrentFiber, findFiberByHostInstance = renderer2.findFiberByHostInstance, version2 = renderer2.version;
              if (typeof findFiberByHostInstance !== "function") {
                return;
              }
              if (currentDispatcherRef != null && typeof getCurrentFiber === "function") {
                var _getInternalReactCons = getInternalReactConstants(version2), ReactTypeOfWork = _getInternalReactCons.ReactTypeOfWork;
                injectedRenderers.set(renderer2, {
                  currentDispatcherRef,
                  getCurrentFiber,
                  workTagMap: ReactTypeOfWork,
                  onErrorOrWarning
                });
              }
            }
            __name(registerRenderer, "registerRenderer");
            var consoleSettingsRef = {
              appendComponentStack: false,
              breakOnConsoleErrors: false,
              showInlineWarningsAndErrors: false,
              hideConsoleLogsInStrictMode: false,
              browserTheme: "dark"
            };
            function patch(_ref) {
              var appendComponentStack = _ref.appendComponentStack, breakOnConsoleErrors = _ref.breakOnConsoleErrors, showInlineWarningsAndErrors = _ref.showInlineWarningsAndErrors, hideConsoleLogsInStrictMode = _ref.hideConsoleLogsInStrictMode, browserTheme = _ref.browserTheme;
              consoleSettingsRef.appendComponentStack = appendComponentStack;
              consoleSettingsRef.breakOnConsoleErrors = breakOnConsoleErrors;
              consoleSettingsRef.showInlineWarningsAndErrors = showInlineWarningsAndErrors;
              consoleSettingsRef.hideConsoleLogsInStrictMode = hideConsoleLogsInStrictMode;
              consoleSettingsRef.browserTheme = browserTheme;
              if (appendComponentStack || breakOnConsoleErrors || showInlineWarningsAndErrors) {
                if (unpatchFn !== null) {
                  return;
                }
                var originalConsoleMethods = {};
                unpatchFn = /* @__PURE__ */ __name(function unpatchFn2() {
                  for (var _method2 in originalConsoleMethods) {
                    try {
                      targetConsole[_method2] = originalConsoleMethods[_method2];
                    } catch (error) {
                    }
                  }
                }, "unpatchFn");
                OVERRIDE_CONSOLE_METHODS.forEach(function(method2) {
                  try {
                    var originalMethod = originalConsoleMethods[method2] = targetConsole[method2].__REACT_DEVTOOLS_ORIGINAL_METHOD__ ? targetConsole[method2].__REACT_DEVTOOLS_ORIGINAL_METHOD__ : targetConsole[method2];
                    var overrideMethod = /* @__PURE__ */ __name(function overrideMethod2() {
                      var shouldAppendWarningStack = false;
                      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                        args[_key] = arguments[_key];
                      }
                      if (method2 !== "log") {
                        if (consoleSettingsRef.appendComponentStack) {
                          var lastArg = args.length > 0 ? args[args.length - 1] : null;
                          var alreadyHasComponentStack = typeof lastArg === "string" && isStringComponentStack(lastArg);
                          shouldAppendWarningStack = !alreadyHasComponentStack;
                        }
                      }
                      var shouldShowInlineWarningsAndErrors = consoleSettingsRef.showInlineWarningsAndErrors && (method2 === "error" || method2 === "warn");
                      var _iterator = console_createForOfIteratorHelper(injectedRenderers.values()), _step;
                      try {
                        for (_iterator.s(); !(_step = _iterator.n()).done; ) {
                          var _step$value = _step.value, currentDispatcherRef = _step$value.currentDispatcherRef, getCurrentFiber = _step$value.getCurrentFiber, onErrorOrWarning = _step$value.onErrorOrWarning, workTagMap = _step$value.workTagMap;
                          var current = getCurrentFiber();
                          if (current != null) {
                            try {
                              if (shouldShowInlineWarningsAndErrors) {
                                if (typeof onErrorOrWarning === "function") {
                                  onErrorOrWarning(
                                    current,
                                    method2,
                                    // Copy args before we mutate them (e.g. adding the component stack)
                                    args.slice()
                                  );
                                }
                              }
                              if (shouldAppendWarningStack) {
                                var componentStack = getStackByFiberInDevAndProd(workTagMap, current, currentDispatcherRef);
                                if (componentStack !== "") {
                                  if (isStrictModeOverride(args, method2)) {
                                    args[0] = "".concat(args[0], " %s");
                                    args.push(componentStack);
                                  } else {
                                    args.push(componentStack);
                                  }
                                }
                              }
                            } catch (error) {
                              setTimeout(function() {
                                throw error;
                              }, 0);
                            } finally {
                              break;
                            }
                          }
                        }
                      } catch (err) {
                        _iterator.e(err);
                      } finally {
                        _iterator.f();
                      }
                      if (consoleSettingsRef.breakOnConsoleErrors) {
                        debugger;
                      }
                      originalMethod.apply(void 0, args);
                    }, "overrideMethod");
                    overrideMethod.__REACT_DEVTOOLS_ORIGINAL_METHOD__ = originalMethod;
                    originalMethod.__REACT_DEVTOOLS_OVERRIDE_METHOD__ = overrideMethod;
                    targetConsole[method2] = overrideMethod;
                  } catch (error) {
                  }
                });
              } else {
                unpatch();
              }
            }
            __name(patch, "patch");
            function unpatch() {
              if (unpatchFn !== null) {
                unpatchFn();
                unpatchFn = null;
              }
            }
            __name(unpatch, "unpatch");
            var unpatchForStrictModeFn = null;
            function patchForStrictMode() {
              if (consoleManagedByDevToolsDuringStrictMode) {
                var overrideConsoleMethods = ["error", "group", "groupCollapsed", "info", "log", "trace", "warn"];
                if (unpatchForStrictModeFn !== null) {
                  return;
                }
                var originalConsoleMethods = {};
                unpatchForStrictModeFn = /* @__PURE__ */ __name(function unpatchForStrictModeFn2() {
                  for (var _method3 in originalConsoleMethods) {
                    try {
                      targetConsole[_method3] = originalConsoleMethods[_method3];
                    } catch (error) {
                    }
                  }
                }, "unpatchForStrictModeFn");
                overrideConsoleMethods.forEach(function(method2) {
                  try {
                    var originalMethod = originalConsoleMethods[method2] = targetConsole[method2].__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ ? targetConsole[method2].__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ : targetConsole[method2];
                    var overrideMethod = /* @__PURE__ */ __name(function overrideMethod2() {
                      if (!consoleSettingsRef.hideConsoleLogsInStrictMode) {
                        for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
                          args[_key2] = arguments[_key2];
                        }
                        if (isNode3) {
                          originalMethod(DIMMED_NODE_CONSOLE_COLOR, format4.apply(void 0, args));
                        } else {
                          var color = getConsoleColor(method2);
                          if (color) {
                            originalMethod.apply(void 0, console_toConsumableArray(formatWithStyles(args, "color: ".concat(color))));
                          } else {
                            throw Error("Console color is not defined");
                          }
                        }
                      }
                    }, "overrideMethod");
                    overrideMethod.__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ = originalMethod;
                    originalMethod.__REACT_DEVTOOLS_STRICT_MODE_OVERRIDE_METHOD__ = overrideMethod;
                    targetConsole[method2] = overrideMethod;
                  } catch (error) {
                  }
                });
              }
            }
            __name(patchForStrictMode, "patchForStrictMode");
            function unpatchForStrictMode() {
              if (consoleManagedByDevToolsDuringStrictMode) {
                if (unpatchForStrictModeFn !== null) {
                  unpatchForStrictModeFn();
                  unpatchForStrictModeFn = null;
                }
              }
            }
            __name(unpatchForStrictMode, "unpatchForStrictMode");
            function patchConsoleUsingWindowValues() {
              var _castBool, _castBool2, _castBool3, _castBool4, _castBrowserTheme;
              var appendComponentStack = (_castBool = castBool(window.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__)) !== null && _castBool !== void 0 ? _castBool : true;
              var breakOnConsoleErrors = (_castBool2 = castBool(window.__REACT_DEVTOOLS_BREAK_ON_CONSOLE_ERRORS__)) !== null && _castBool2 !== void 0 ? _castBool2 : false;
              var showInlineWarningsAndErrors = (_castBool3 = castBool(window.__REACT_DEVTOOLS_SHOW_INLINE_WARNINGS_AND_ERRORS__)) !== null && _castBool3 !== void 0 ? _castBool3 : true;
              var hideConsoleLogsInStrictMode = (_castBool4 = castBool(window.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__)) !== null && _castBool4 !== void 0 ? _castBool4 : false;
              var browserTheme = (_castBrowserTheme = castBrowserTheme(window.__REACT_DEVTOOLS_BROWSER_THEME__)) !== null && _castBrowserTheme !== void 0 ? _castBrowserTheme : "dark";
              patch({
                appendComponentStack,
                breakOnConsoleErrors,
                showInlineWarningsAndErrors,
                hideConsoleLogsInStrictMode,
                browserTheme
              });
            }
            __name(patchConsoleUsingWindowValues, "patchConsoleUsingWindowValues");
            function writeConsolePatchSettingsToWindow(settings) {
              window.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = settings.appendComponentStack;
              window.__REACT_DEVTOOLS_BREAK_ON_CONSOLE_ERRORS__ = settings.breakOnConsoleErrors;
              window.__REACT_DEVTOOLS_SHOW_INLINE_WARNINGS_AND_ERRORS__ = settings.showInlineWarningsAndErrors;
              window.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ = settings.hideConsoleLogsInStrictMode;
              window.__REACT_DEVTOOLS_BROWSER_THEME__ = settings.browserTheme;
            }
            __name(writeConsolePatchSettingsToWindow, "writeConsolePatchSettingsToWindow");
            function installConsoleFunctionsToWindow() {
              window.__REACT_DEVTOOLS_CONSOLE_FUNCTIONS__ = {
                patchConsoleUsingWindowValues,
                registerRendererWithConsole: registerRenderer
              };
            }
            __name(installConsoleFunctionsToWindow, "installConsoleFunctionsToWindow");
            ;
            function bridge_typeof(obj) {
              "@babel/helpers - typeof";
              if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                bridge_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return typeof obj2;
                }, "_typeof");
              } else {
                bridge_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                }, "_typeof");
              }
              return bridge_typeof(obj);
            }
            __name(bridge_typeof, "bridge_typeof");
            function bridge_toConsumableArray(arr) {
              return bridge_arrayWithoutHoles(arr) || bridge_iterableToArray(arr) || bridge_unsupportedIterableToArray(arr) || bridge_nonIterableSpread();
            }
            __name(bridge_toConsumableArray, "bridge_toConsumableArray");
            function bridge_nonIterableSpread() {
              throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
            }
            __name(bridge_nonIterableSpread, "bridge_nonIterableSpread");
            function bridge_unsupportedIterableToArray(o2, minLen) {
              if (!o2) return;
              if (typeof o2 === "string") return bridge_arrayLikeToArray(o2, minLen);
              var n2 = Object.prototype.toString.call(o2).slice(8, -1);
              if (n2 === "Object" && o2.constructor) n2 = o2.constructor.name;
              if (n2 === "Map" || n2 === "Set") return Array.from(o2);
              if (n2 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n2)) return bridge_arrayLikeToArray(o2, minLen);
            }
            __name(bridge_unsupportedIterableToArray, "bridge_unsupportedIterableToArray");
            function bridge_iterableToArray(iter) {
              if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
            }
            __name(bridge_iterableToArray, "bridge_iterableToArray");
            function bridge_arrayWithoutHoles(arr) {
              if (Array.isArray(arr)) return bridge_arrayLikeToArray(arr);
            }
            __name(bridge_arrayWithoutHoles, "bridge_arrayWithoutHoles");
            function bridge_arrayLikeToArray(arr, len) {
              if (len == null || len > arr.length) len = arr.length;
              for (var i = 0, arr2 = new Array(len); i < len; i++) {
                arr2[i] = arr[i];
              }
              return arr2;
            }
            __name(bridge_arrayLikeToArray, "bridge_arrayLikeToArray");
            function bridge_classCallCheck(instance, Constructor) {
              if (!(instance instanceof Constructor)) {
                throw new TypeError("Cannot call a class as a function");
              }
            }
            __name(bridge_classCallCheck, "bridge_classCallCheck");
            function bridge_defineProperties(target, props) {
              for (var i = 0; i < props.length; i++) {
                var descriptor2 = props[i];
                descriptor2.enumerable = descriptor2.enumerable || false;
                descriptor2.configurable = true;
                if ("value" in descriptor2) descriptor2.writable = true;
                Object.defineProperty(target, descriptor2.key, descriptor2);
              }
            }
            __name(bridge_defineProperties, "bridge_defineProperties");
            function bridge_createClass(Constructor, protoProps, staticProps) {
              if (protoProps) bridge_defineProperties(Constructor.prototype, protoProps);
              if (staticProps) bridge_defineProperties(Constructor, staticProps);
              return Constructor;
            }
            __name(bridge_createClass, "bridge_createClass");
            function _inherits(subClass, superClass) {
              if (typeof superClass !== "function" && superClass !== null) {
                throw new TypeError("Super expression must either be null or a function");
              }
              subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
              if (superClass) _setPrototypeOf(subClass, superClass);
            }
            __name(_inherits, "_inherits");
            function _setPrototypeOf(o2, p) {
              _setPrototypeOf = Object.setPrototypeOf || /* @__PURE__ */ __name(function _setPrototypeOf2(o3, p2) {
                o3.__proto__ = p2;
                return o3;
              }, "_setPrototypeOf");
              return _setPrototypeOf(o2, p);
            }
            __name(_setPrototypeOf, "_setPrototypeOf");
            function _createSuper(Derived) {
              var hasNativeReflectConstruct = _isNativeReflectConstruct();
              return /* @__PURE__ */ __name(function _createSuperInternal() {
                var Super = _getPrototypeOf(Derived), result;
                if (hasNativeReflectConstruct) {
                  var NewTarget = _getPrototypeOf(this).constructor;
                  result = Reflect.construct(Super, arguments, NewTarget);
                } else {
                  result = Super.apply(this, arguments);
                }
                return _possibleConstructorReturn(this, result);
              }, "_createSuperInternal");
            }
            __name(_createSuper, "_createSuper");
            function _possibleConstructorReturn(self2, call) {
              if (call && (bridge_typeof(call) === "object" || typeof call === "function")) {
                return call;
              }
              return _assertThisInitialized(self2);
            }
            __name(_possibleConstructorReturn, "_possibleConstructorReturn");
            function _assertThisInitialized(self2) {
              if (self2 === void 0) {
                throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
              }
              return self2;
            }
            __name(_assertThisInitialized, "_assertThisInitialized");
            function _isNativeReflectConstruct() {
              if (typeof Reflect === "undefined" || !Reflect.construct) return false;
              if (Reflect.construct.sham) return false;
              if (typeof Proxy === "function") return true;
              try {
                Date.prototype.toString.call(Reflect.construct(Date, [], function() {
                }));
                return true;
              } catch (e2) {
                return false;
              }
            }
            __name(_isNativeReflectConstruct, "_isNativeReflectConstruct");
            function _getPrototypeOf(o2) {
              _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : /* @__PURE__ */ __name(function _getPrototypeOf2(o3) {
                return o3.__proto__ || Object.getPrototypeOf(o3);
              }, "_getPrototypeOf");
              return _getPrototypeOf(o2);
            }
            __name(_getPrototypeOf, "_getPrototypeOf");
            function bridge_defineProperty(obj, key, value) {
              if (key in obj) {
                Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
              } else {
                obj[key] = value;
              }
              return obj;
            }
            __name(bridge_defineProperty, "bridge_defineProperty");
            var BATCH_DURATION = 100;
            var BRIDGE_PROTOCOL = [
              // This version technically never existed,
              // but a backwards breaking change was added in 4.11,
              // so the safest guess to downgrade the frontend would be to version 4.10.
              {
                version: 0,
                minNpmVersion: '"<4.11.0"',
                maxNpmVersion: '"<4.11.0"'
              },
              // Versions 4.11.x – 4.12.x contained the backwards breaking change,
              // but we didn't add the "fix" of checking the protocol version until 4.13,
              // so we don't recommend downgrading to 4.11 or 4.12.
              {
                version: 1,
                minNpmVersion: "4.13.0",
                maxNpmVersion: "4.21.0"
              },
              // Version 2 adds a StrictMode-enabled and supports-StrictMode bits to add-root operation.
              {
                version: 2,
                minNpmVersion: "4.22.0",
                maxNpmVersion: null
              }
            ];
            var currentBridgeProtocol = BRIDGE_PROTOCOL[BRIDGE_PROTOCOL.length - 1];
            var Bridge = /* @__PURE__ */ function(_EventEmitter) {
              _inherits(Bridge2, _EventEmitter);
              var _super = _createSuper(Bridge2);
              function Bridge2(wall) {
                var _this;
                bridge_classCallCheck(this, Bridge2);
                _this = _super.call(this);
                bridge_defineProperty(_assertThisInitialized(_this), "_isShutdown", false);
                bridge_defineProperty(_assertThisInitialized(_this), "_messageQueue", []);
                bridge_defineProperty(_assertThisInitialized(_this), "_timeoutID", null);
                bridge_defineProperty(_assertThisInitialized(_this), "_wallUnlisten", null);
                bridge_defineProperty(_assertThisInitialized(_this), "_flush", function() {
                  if (_this._timeoutID !== null) {
                    clearTimeout(_this._timeoutID);
                    _this._timeoutID = null;
                  }
                  if (_this._messageQueue.length) {
                    for (var i = 0; i < _this._messageQueue.length; i += 2) {
                      var _this$_wall;
                      (_this$_wall = _this._wall).send.apply(_this$_wall, [_this._messageQueue[i]].concat(bridge_toConsumableArray(_this._messageQueue[i + 1])));
                    }
                    _this._messageQueue.length = 0;
                    _this._timeoutID = setTimeout(_this._flush, BATCH_DURATION);
                  }
                });
                bridge_defineProperty(_assertThisInitialized(_this), "overrideValueAtPath", function(_ref) {
                  var id = _ref.id, path108 = _ref.path, rendererID = _ref.rendererID, type = _ref.type, value = _ref.value;
                  switch (type) {
                    case "context":
                      _this.send("overrideContext", {
                        id,
                        path: path108,
                        rendererID,
                        wasForwarded: true,
                        value
                      });
                      break;
                    case "hooks":
                      _this.send("overrideHookState", {
                        id,
                        path: path108,
                        rendererID,
                        wasForwarded: true,
                        value
                      });
                      break;
                    case "props":
                      _this.send("overrideProps", {
                        id,
                        path: path108,
                        rendererID,
                        wasForwarded: true,
                        value
                      });
                      break;
                    case "state":
                      _this.send("overrideState", {
                        id,
                        path: path108,
                        rendererID,
                        wasForwarded: true,
                        value
                      });
                      break;
                  }
                });
                _this._wall = wall;
                _this._wallUnlisten = wall.listen(function(message) {
                  if (message && message.event) {
                    _assertThisInitialized(_this).emit(message.event, message.payload);
                  }
                }) || null;
                _this.addListener("overrideValueAtPath", _this.overrideValueAtPath);
                return _this;
              }
              __name(Bridge2, "Bridge");
              bridge_createClass(Bridge2, [{
                key: "send",
                value: /* @__PURE__ */ __name(function send(event) {
                  if (this._isShutdown) {
                    console.warn('Cannot send message "'.concat(event, '" through a Bridge that has been shutdown.'));
                    return;
                  }
                  for (var _len = arguments.length, payload = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                    payload[_key - 1] = arguments[_key];
                  }
                  this._messageQueue.push(event, payload);
                  if (!this._timeoutID) {
                    this._timeoutID = setTimeout(this._flush, 0);
                  }
                }, "send")
              }, {
                key: "shutdown",
                value: /* @__PURE__ */ __name(function shutdown() {
                  if (this._isShutdown) {
                    console.warn("Bridge was already shutdown.");
                    return;
                  }
                  this.emit("shutdown");
                  this.send("shutdown");
                  this._isShutdown = true;
                  this.addListener = function() {
                  };
                  this.emit = function() {
                  };
                  this.removeAllListeners();
                  var wallUnlisten = this._wallUnlisten;
                  if (wallUnlisten) {
                    wallUnlisten();
                  }
                  do {
                    this._flush();
                  } while (this._messageQueue.length);
                  if (this._timeoutID !== null) {
                    clearTimeout(this._timeoutID);
                    this._timeoutID = null;
                  }
                }, "shutdown")
              }, {
                key: "wall",
                get: /* @__PURE__ */ __name(function get3() {
                  return this._wall;
                }, "get")
              }]);
              return Bridge2;
            }(EventEmitter10);
            const src_bridge = Bridge;
            ;
            function agent_typeof(obj) {
              "@babel/helpers - typeof";
              if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                agent_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return typeof obj2;
                }, "_typeof");
              } else {
                agent_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                }, "_typeof");
              }
              return agent_typeof(obj);
            }
            __name(agent_typeof, "agent_typeof");
            function agent_classCallCheck(instance, Constructor) {
              if (!(instance instanceof Constructor)) {
                throw new TypeError("Cannot call a class as a function");
              }
            }
            __name(agent_classCallCheck, "agent_classCallCheck");
            function agent_defineProperties(target, props) {
              for (var i = 0; i < props.length; i++) {
                var descriptor2 = props[i];
                descriptor2.enumerable = descriptor2.enumerable || false;
                descriptor2.configurable = true;
                if ("value" in descriptor2) descriptor2.writable = true;
                Object.defineProperty(target, descriptor2.key, descriptor2);
              }
            }
            __name(agent_defineProperties, "agent_defineProperties");
            function agent_createClass(Constructor, protoProps, staticProps) {
              if (protoProps) agent_defineProperties(Constructor.prototype, protoProps);
              if (staticProps) agent_defineProperties(Constructor, staticProps);
              return Constructor;
            }
            __name(agent_createClass, "agent_createClass");
            function agent_inherits(subClass, superClass) {
              if (typeof superClass !== "function" && superClass !== null) {
                throw new TypeError("Super expression must either be null or a function");
              }
              subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
              if (superClass) agent_setPrototypeOf(subClass, superClass);
            }
            __name(agent_inherits, "agent_inherits");
            function agent_setPrototypeOf(o2, p) {
              agent_setPrototypeOf = Object.setPrototypeOf || /* @__PURE__ */ __name(function _setPrototypeOf2(o3, p2) {
                o3.__proto__ = p2;
                return o3;
              }, "_setPrototypeOf");
              return agent_setPrototypeOf(o2, p);
            }
            __name(agent_setPrototypeOf, "agent_setPrototypeOf");
            function agent_createSuper(Derived) {
              var hasNativeReflectConstruct = agent_isNativeReflectConstruct();
              return /* @__PURE__ */ __name(function _createSuperInternal() {
                var Super = agent_getPrototypeOf(Derived), result;
                if (hasNativeReflectConstruct) {
                  var NewTarget = agent_getPrototypeOf(this).constructor;
                  result = Reflect.construct(Super, arguments, NewTarget);
                } else {
                  result = Super.apply(this, arguments);
                }
                return agent_possibleConstructorReturn(this, result);
              }, "_createSuperInternal");
            }
            __name(agent_createSuper, "agent_createSuper");
            function agent_possibleConstructorReturn(self2, call) {
              if (call && (agent_typeof(call) === "object" || typeof call === "function")) {
                return call;
              }
              return agent_assertThisInitialized(self2);
            }
            __name(agent_possibleConstructorReturn, "agent_possibleConstructorReturn");
            function agent_assertThisInitialized(self2) {
              if (self2 === void 0) {
                throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
              }
              return self2;
            }
            __name(agent_assertThisInitialized, "agent_assertThisInitialized");
            function agent_isNativeReflectConstruct() {
              if (typeof Reflect === "undefined" || !Reflect.construct) return false;
              if (Reflect.construct.sham) return false;
              if (typeof Proxy === "function") return true;
              try {
                Date.prototype.toString.call(Reflect.construct(Date, [], function() {
                }));
                return true;
              } catch (e2) {
                return false;
              }
            }
            __name(agent_isNativeReflectConstruct, "agent_isNativeReflectConstruct");
            function agent_getPrototypeOf(o2) {
              agent_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : /* @__PURE__ */ __name(function _getPrototypeOf2(o3) {
                return o3.__proto__ || Object.getPrototypeOf(o3);
              }, "_getPrototypeOf");
              return agent_getPrototypeOf(o2);
            }
            __name(agent_getPrototypeOf, "agent_getPrototypeOf");
            function agent_defineProperty(obj, key, value) {
              if (key in obj) {
                Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
              } else {
                obj[key] = value;
              }
              return obj;
            }
            __name(agent_defineProperty, "agent_defineProperty");
            var debug2 = /* @__PURE__ */ __name(function debug3(methodName) {
              if (__DEBUG__) {
                var _console;
                for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                  args[_key - 1] = arguments[_key];
                }
                (_console = console).log.apply(_console, ["%cAgent %c".concat(methodName), "color: purple; font-weight: bold;", "font-weight: bold;"].concat(args));
              }
            }, "debug");
            var Agent3 = /* @__PURE__ */ function(_EventEmitter) {
              agent_inherits(Agent4, _EventEmitter);
              var _super = agent_createSuper(Agent4);
              function Agent4(bridge) {
                var _this;
                agent_classCallCheck(this, Agent4);
                _this = _super.call(this);
                agent_defineProperty(agent_assertThisInitialized(_this), "_isProfiling", false);
                agent_defineProperty(agent_assertThisInitialized(_this), "_recordChangeDescriptions", false);
                agent_defineProperty(agent_assertThisInitialized(_this), "_rendererInterfaces", {});
                agent_defineProperty(agent_assertThisInitialized(_this), "_persistedSelection", null);
                agent_defineProperty(agent_assertThisInitialized(_this), "_persistedSelectionMatch", null);
                agent_defineProperty(agent_assertThisInitialized(_this), "_traceUpdatesEnabled", false);
                agent_defineProperty(agent_assertThisInitialized(_this), "clearErrorsAndWarnings", function(_ref) {
                  var rendererID = _ref.rendererID;
                  var renderer2 = _this._rendererInterfaces[rendererID];
                  if (renderer2 == null) {
                    console.warn('Invalid renderer id "'.concat(rendererID, '"'));
                  } else {
                    renderer2.clearErrorsAndWarnings();
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "clearErrorsForFiberID", function(_ref2) {
                  var id = _ref2.id, rendererID = _ref2.rendererID;
                  var renderer2 = _this._rendererInterfaces[rendererID];
                  if (renderer2 == null) {
                    console.warn('Invalid renderer id "'.concat(rendererID, '"'));
                  } else {
                    renderer2.clearErrorsForFiberID(id);
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "clearWarningsForFiberID", function(_ref3) {
                  var id = _ref3.id, rendererID = _ref3.rendererID;
                  var renderer2 = _this._rendererInterfaces[rendererID];
                  if (renderer2 == null) {
                    console.warn('Invalid renderer id "'.concat(rendererID, '"'));
                  } else {
                    renderer2.clearWarningsForFiberID(id);
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "copyElementPath", function(_ref4) {
                  var id = _ref4.id, path108 = _ref4.path, rendererID = _ref4.rendererID;
                  var renderer2 = _this._rendererInterfaces[rendererID];
                  if (renderer2 == null) {
                    console.warn('Invalid renderer id "'.concat(rendererID, '" for element "').concat(id, '"'));
                  } else {
                    var value = renderer2.getSerializedElementValueByPath(id, path108);
                    if (value != null) {
                      _this._bridge.send("saveToClipboard", value);
                    } else {
                      console.warn('Unable to obtain serialized value for element "'.concat(id, '"'));
                    }
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "deletePath", function(_ref5) {
                  var hookID = _ref5.hookID, id = _ref5.id, path108 = _ref5.path, rendererID = _ref5.rendererID, type = _ref5.type;
                  var renderer2 = _this._rendererInterfaces[rendererID];
                  if (renderer2 == null) {
                    console.warn('Invalid renderer id "'.concat(rendererID, '" for element "').concat(id, '"'));
                  } else {
                    renderer2.deletePath(type, id, hookID, path108);
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "getBackendVersion", function() {
                  var version2 = "4.28.5-ef8a840bd";
                  if (version2) {
                    _this._bridge.send("backendVersion", version2);
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "getBridgeProtocol", function() {
                  _this._bridge.send("bridgeProtocol", currentBridgeProtocol);
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "getProfilingData", function(_ref6) {
                  var rendererID = _ref6.rendererID;
                  var renderer2 = _this._rendererInterfaces[rendererID];
                  if (renderer2 == null) {
                    console.warn('Invalid renderer id "'.concat(rendererID, '"'));
                  }
                  _this._bridge.send("profilingData", renderer2.getProfilingData());
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "getProfilingStatus", function() {
                  _this._bridge.send("profilingStatus", _this._isProfiling);
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "getOwnersList", function(_ref7) {
                  var id = _ref7.id, rendererID = _ref7.rendererID;
                  var renderer2 = _this._rendererInterfaces[rendererID];
                  if (renderer2 == null) {
                    console.warn('Invalid renderer id "'.concat(rendererID, '" for element "').concat(id, '"'));
                  } else {
                    var owners = renderer2.getOwnersList(id);
                    _this._bridge.send("ownersList", {
                      id,
                      owners
                    });
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "inspectElement", function(_ref8) {
                  var forceFullData = _ref8.forceFullData, id = _ref8.id, path108 = _ref8.path, rendererID = _ref8.rendererID, requestID = _ref8.requestID;
                  var renderer2 = _this._rendererInterfaces[rendererID];
                  if (renderer2 == null) {
                    console.warn('Invalid renderer id "'.concat(rendererID, '" for element "').concat(id, '"'));
                  } else {
                    _this._bridge.send("inspectedElement", renderer2.inspectElement(requestID, id, path108, forceFullData));
                    if (_this._persistedSelectionMatch === null || _this._persistedSelectionMatch.id !== id) {
                      _this._persistedSelection = null;
                      _this._persistedSelectionMatch = null;
                      renderer2.setTrackedPath(null);
                      _this._throttledPersistSelection(rendererID, id);
                    }
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "logElementToConsole", function(_ref9) {
                  var id = _ref9.id, rendererID = _ref9.rendererID;
                  var renderer2 = _this._rendererInterfaces[rendererID];
                  if (renderer2 == null) {
                    console.warn('Invalid renderer id "'.concat(rendererID, '" for element "').concat(id, '"'));
                  } else {
                    renderer2.logElementToConsole(id);
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "overrideError", function(_ref10) {
                  var id = _ref10.id, rendererID = _ref10.rendererID, forceError = _ref10.forceError;
                  var renderer2 = _this._rendererInterfaces[rendererID];
                  if (renderer2 == null) {
                    console.warn('Invalid renderer id "'.concat(rendererID, '" for element "').concat(id, '"'));
                  } else {
                    renderer2.overrideError(id, forceError);
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "overrideSuspense", function(_ref11) {
                  var id = _ref11.id, rendererID = _ref11.rendererID, forceFallback = _ref11.forceFallback;
                  var renderer2 = _this._rendererInterfaces[rendererID];
                  if (renderer2 == null) {
                    console.warn('Invalid renderer id "'.concat(rendererID, '" for element "').concat(id, '"'));
                  } else {
                    renderer2.overrideSuspense(id, forceFallback);
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "overrideValueAtPath", function(_ref12) {
                  var hookID = _ref12.hookID, id = _ref12.id, path108 = _ref12.path, rendererID = _ref12.rendererID, type = _ref12.type, value = _ref12.value;
                  var renderer2 = _this._rendererInterfaces[rendererID];
                  if (renderer2 == null) {
                    console.warn('Invalid renderer id "'.concat(rendererID, '" for element "').concat(id, '"'));
                  } else {
                    renderer2.overrideValueAtPath(type, id, hookID, path108, value);
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "overrideContext", function(_ref13) {
                  var id = _ref13.id, path108 = _ref13.path, rendererID = _ref13.rendererID, wasForwarded = _ref13.wasForwarded, value = _ref13.value;
                  if (!wasForwarded) {
                    _this.overrideValueAtPath({
                      id,
                      path: path108,
                      rendererID,
                      type: "context",
                      value
                    });
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "overrideHookState", function(_ref14) {
                  var id = _ref14.id, hookID = _ref14.hookID, path108 = _ref14.path, rendererID = _ref14.rendererID, wasForwarded = _ref14.wasForwarded, value = _ref14.value;
                  if (!wasForwarded) {
                    _this.overrideValueAtPath({
                      id,
                      path: path108,
                      rendererID,
                      type: "hooks",
                      value
                    });
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "overrideProps", function(_ref15) {
                  var id = _ref15.id, path108 = _ref15.path, rendererID = _ref15.rendererID, wasForwarded = _ref15.wasForwarded, value = _ref15.value;
                  if (!wasForwarded) {
                    _this.overrideValueAtPath({
                      id,
                      path: path108,
                      rendererID,
                      type: "props",
                      value
                    });
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "overrideState", function(_ref16) {
                  var id = _ref16.id, path108 = _ref16.path, rendererID = _ref16.rendererID, wasForwarded = _ref16.wasForwarded, value = _ref16.value;
                  if (!wasForwarded) {
                    _this.overrideValueAtPath({
                      id,
                      path: path108,
                      rendererID,
                      type: "state",
                      value
                    });
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "reloadAndProfile", function(recordChangeDescriptions) {
                  sessionStorageSetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY, "true");
                  sessionStorageSetItem(SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY, recordChangeDescriptions ? "true" : "false");
                  _this._bridge.send("reloadAppForProfiling");
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "renamePath", function(_ref17) {
                  var hookID = _ref17.hookID, id = _ref17.id, newPath = _ref17.newPath, oldPath = _ref17.oldPath, rendererID = _ref17.rendererID, type = _ref17.type;
                  var renderer2 = _this._rendererInterfaces[rendererID];
                  if (renderer2 == null) {
                    console.warn('Invalid renderer id "'.concat(rendererID, '" for element "').concat(id, '"'));
                  } else {
                    renderer2.renamePath(type, id, hookID, oldPath, newPath);
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "setTraceUpdatesEnabled", function(traceUpdatesEnabled) {
                  _this._traceUpdatesEnabled = traceUpdatesEnabled;
                  toggleEnabled(traceUpdatesEnabled);
                  for (var rendererID in _this._rendererInterfaces) {
                    var renderer2 = _this._rendererInterfaces[rendererID];
                    renderer2.setTraceUpdatesEnabled(traceUpdatesEnabled);
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "syncSelectionFromNativeElementsPanel", function() {
                  var target = window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0;
                  if (target == null) {
                    return;
                  }
                  _this.selectNode(target);
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "shutdown", function() {
                  _this.emit("shutdown");
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "startProfiling", function(recordChangeDescriptions) {
                  _this._recordChangeDescriptions = recordChangeDescriptions;
                  _this._isProfiling = true;
                  for (var rendererID in _this._rendererInterfaces) {
                    var renderer2 = _this._rendererInterfaces[rendererID];
                    renderer2.startProfiling(recordChangeDescriptions);
                  }
                  _this._bridge.send("profilingStatus", _this._isProfiling);
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "stopProfiling", function() {
                  _this._isProfiling = false;
                  _this._recordChangeDescriptions = false;
                  for (var rendererID in _this._rendererInterfaces) {
                    var renderer2 = _this._rendererInterfaces[rendererID];
                    renderer2.stopProfiling();
                  }
                  _this._bridge.send("profilingStatus", _this._isProfiling);
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "stopInspectingNative", function(selected) {
                  _this._bridge.send("stopInspectingNative", selected);
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "storeAsGlobal", function(_ref18) {
                  var count = _ref18.count, id = _ref18.id, path108 = _ref18.path, rendererID = _ref18.rendererID;
                  var renderer2 = _this._rendererInterfaces[rendererID];
                  if (renderer2 == null) {
                    console.warn('Invalid renderer id "'.concat(rendererID, '" for element "').concat(id, '"'));
                  } else {
                    renderer2.storeAsGlobal(id, path108, count);
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "updateConsolePatchSettings", function(_ref19) {
                  var appendComponentStack = _ref19.appendComponentStack, breakOnConsoleErrors = _ref19.breakOnConsoleErrors, showInlineWarningsAndErrors = _ref19.showInlineWarningsAndErrors, hideConsoleLogsInStrictMode = _ref19.hideConsoleLogsInStrictMode, browserTheme = _ref19.browserTheme;
                  patch({
                    appendComponentStack,
                    breakOnConsoleErrors,
                    showInlineWarningsAndErrors,
                    hideConsoleLogsInStrictMode,
                    browserTheme
                  });
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "updateComponentFilters", function(componentFilters) {
                  for (var rendererID in _this._rendererInterfaces) {
                    var renderer2 = _this._rendererInterfaces[rendererID];
                    renderer2.updateComponentFilters(componentFilters);
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "viewAttributeSource", function(_ref20) {
                  var id = _ref20.id, path108 = _ref20.path, rendererID = _ref20.rendererID;
                  var renderer2 = _this._rendererInterfaces[rendererID];
                  if (renderer2 == null) {
                    console.warn('Invalid renderer id "'.concat(rendererID, '" for element "').concat(id, '"'));
                  } else {
                    renderer2.prepareViewAttributeSource(id, path108);
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "viewElementSource", function(_ref21) {
                  var id = _ref21.id, rendererID = _ref21.rendererID;
                  var renderer2 = _this._rendererInterfaces[rendererID];
                  if (renderer2 == null) {
                    console.warn('Invalid renderer id "'.concat(rendererID, '" for element "').concat(id, '"'));
                  } else {
                    renderer2.prepareViewElementSource(id);
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "onTraceUpdates", function(nodes) {
                  _this.emit("traceUpdates", nodes);
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "onFastRefreshScheduled", function() {
                  if (__DEBUG__) {
                    debug2("onFastRefreshScheduled");
                  }
                  _this._bridge.send("fastRefreshScheduled");
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "onHookOperations", function(operations) {
                  if (__DEBUG__) {
                    debug2("onHookOperations", "(".concat(operations.length, ") [").concat(operations.join(", "), "]"));
                  }
                  _this._bridge.send("operations", operations);
                  if (_this._persistedSelection !== null) {
                    var rendererID = operations[0];
                    if (_this._persistedSelection.rendererID === rendererID) {
                      var renderer2 = _this._rendererInterfaces[rendererID];
                      if (renderer2 == null) {
                        console.warn('Invalid renderer id "'.concat(rendererID, '"'));
                      } else {
                        var prevMatch = _this._persistedSelectionMatch;
                        var nextMatch = renderer2.getBestMatchForTrackedPath();
                        _this._persistedSelectionMatch = nextMatch;
                        var prevMatchID = prevMatch !== null ? prevMatch.id : null;
                        var nextMatchID = nextMatch !== null ? nextMatch.id : null;
                        if (prevMatchID !== nextMatchID) {
                          if (nextMatchID !== null) {
                            _this._bridge.send("selectFiber", nextMatchID);
                          }
                        }
                        if (nextMatch !== null && nextMatch.isFullMatch) {
                          _this._persistedSelection = null;
                          _this._persistedSelectionMatch = null;
                          renderer2.setTrackedPath(null);
                        }
                      }
                    }
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "_throttledPersistSelection", lodash_throttle_default()(function(rendererID, id) {
                  var renderer2 = _this._rendererInterfaces[rendererID];
                  var path108 = renderer2 != null ? renderer2.getPathForElement(id) : null;
                  if (path108 !== null) {
                    sessionStorageSetItem(SESSION_STORAGE_LAST_SELECTION_KEY, JSON.stringify({
                      rendererID,
                      path: path108
                    }));
                  } else {
                    sessionStorageRemoveItem(SESSION_STORAGE_LAST_SELECTION_KEY);
                  }
                }, 1e3));
                if (sessionStorageGetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY) === "true") {
                  _this._recordChangeDescriptions = sessionStorageGetItem(SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY) === "true";
                  _this._isProfiling = true;
                  sessionStorageRemoveItem(SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY);
                  sessionStorageRemoveItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY);
                }
                var persistedSelectionString = sessionStorageGetItem(SESSION_STORAGE_LAST_SELECTION_KEY);
                if (persistedSelectionString != null) {
                  _this._persistedSelection = JSON.parse(persistedSelectionString);
                }
                _this._bridge = bridge;
                bridge.addListener("clearErrorsAndWarnings", _this.clearErrorsAndWarnings);
                bridge.addListener("clearErrorsForFiberID", _this.clearErrorsForFiberID);
                bridge.addListener("clearWarningsForFiberID", _this.clearWarningsForFiberID);
                bridge.addListener("copyElementPath", _this.copyElementPath);
                bridge.addListener("deletePath", _this.deletePath);
                bridge.addListener("getBackendVersion", _this.getBackendVersion);
                bridge.addListener("getBridgeProtocol", _this.getBridgeProtocol);
                bridge.addListener("getProfilingData", _this.getProfilingData);
                bridge.addListener("getProfilingStatus", _this.getProfilingStatus);
                bridge.addListener("getOwnersList", _this.getOwnersList);
                bridge.addListener("inspectElement", _this.inspectElement);
                bridge.addListener("logElementToConsole", _this.logElementToConsole);
                bridge.addListener("overrideError", _this.overrideError);
                bridge.addListener("overrideSuspense", _this.overrideSuspense);
                bridge.addListener("overrideValueAtPath", _this.overrideValueAtPath);
                bridge.addListener("reloadAndProfile", _this.reloadAndProfile);
                bridge.addListener("renamePath", _this.renamePath);
                bridge.addListener("setTraceUpdatesEnabled", _this.setTraceUpdatesEnabled);
                bridge.addListener("startProfiling", _this.startProfiling);
                bridge.addListener("stopProfiling", _this.stopProfiling);
                bridge.addListener("storeAsGlobal", _this.storeAsGlobal);
                bridge.addListener("syncSelectionFromNativeElementsPanel", _this.syncSelectionFromNativeElementsPanel);
                bridge.addListener("shutdown", _this.shutdown);
                bridge.addListener("updateConsolePatchSettings", _this.updateConsolePatchSettings);
                bridge.addListener("updateComponentFilters", _this.updateComponentFilters);
                bridge.addListener("viewAttributeSource", _this.viewAttributeSource);
                bridge.addListener("viewElementSource", _this.viewElementSource);
                bridge.addListener("overrideContext", _this.overrideContext);
                bridge.addListener("overrideHookState", _this.overrideHookState);
                bridge.addListener("overrideProps", _this.overrideProps);
                bridge.addListener("overrideState", _this.overrideState);
                if (_this._isProfiling) {
                  bridge.send("profilingStatus", true);
                }
                var _version = "4.28.5-ef8a840bd";
                if (_version) {
                  _this._bridge.send("backendVersion", _version);
                }
                _this._bridge.send("bridgeProtocol", currentBridgeProtocol);
                var isBackendStorageAPISupported = false;
                try {
                  localStorage.getItem("test");
                  isBackendStorageAPISupported = true;
                } catch (error) {
                }
                bridge.send("isBackendStorageAPISupported", isBackendStorageAPISupported);
                bridge.send("isSynchronousXHRSupported", isSynchronousXHRSupported());
                setupHighlighter(bridge, agent_assertThisInitialized(_this));
                TraceUpdates_initialize(agent_assertThisInitialized(_this));
                return _this;
              }
              __name(Agent4, "Agent");
              agent_createClass(Agent4, [{
                key: "getInstanceAndStyle",
                value: /* @__PURE__ */ __name(function getInstanceAndStyle(_ref22) {
                  var id = _ref22.id, rendererID = _ref22.rendererID;
                  var renderer2 = this._rendererInterfaces[rendererID];
                  if (renderer2 == null) {
                    console.warn('Invalid renderer id "'.concat(rendererID, '"'));
                    return null;
                  }
                  return renderer2.getInstanceAndStyle(id);
                }, "getInstanceAndStyle")
              }, {
                key: "getBestMatchingRendererInterface",
                value: /* @__PURE__ */ __name(function getBestMatchingRendererInterface(node) {
                  var bestMatch = null;
                  for (var rendererID in this._rendererInterfaces) {
                    var renderer2 = this._rendererInterfaces[rendererID];
                    var fiber = renderer2.getFiberForNative(node);
                    if (fiber !== null) {
                      if (fiber.stateNode === node) {
                        return renderer2;
                      } else if (bestMatch === null) {
                        bestMatch = renderer2;
                      }
                    }
                  }
                  return bestMatch;
                }, "getBestMatchingRendererInterface")
              }, {
                key: "getIDForNode",
                value: /* @__PURE__ */ __name(function getIDForNode(node) {
                  var rendererInterface = this.getBestMatchingRendererInterface(node);
                  if (rendererInterface != null) {
                    try {
                      return rendererInterface.getFiberIDForNative(node, true);
                    } catch (error) {
                    }
                  }
                  return null;
                }, "getIDForNode")
              }, {
                key: "selectNode",
                value: /* @__PURE__ */ __name(function selectNode(target) {
                  var id = this.getIDForNode(target);
                  if (id !== null) {
                    this._bridge.send("selectFiber", id);
                  }
                }, "selectNode")
              }, {
                key: "setRendererInterface",
                value: /* @__PURE__ */ __name(function setRendererInterface(rendererID, rendererInterface) {
                  this._rendererInterfaces[rendererID] = rendererInterface;
                  if (this._isProfiling) {
                    rendererInterface.startProfiling(this._recordChangeDescriptions);
                  }
                  rendererInterface.setTraceUpdatesEnabled(this._traceUpdatesEnabled);
                  var selection = this._persistedSelection;
                  if (selection !== null && selection.rendererID === rendererID) {
                    rendererInterface.setTrackedPath(selection.path);
                  }
                }, "setRendererInterface")
              }, {
                key: "onUnsupportedRenderer",
                value: /* @__PURE__ */ __name(function onUnsupportedRenderer(rendererID) {
                  this._bridge.send("unsupportedRendererVersion", rendererID);
                }, "onUnsupportedRenderer")
              }, {
                key: "rendererInterfaces",
                get: /* @__PURE__ */ __name(function get3() {
                  return this._rendererInterfaces;
                }, "get")
              }]);
              return Agent4;
            }(EventEmitter10);
            ;
            function hook_typeof(obj) {
              "@babel/helpers - typeof";
              if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                hook_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return typeof obj2;
                }, "_typeof");
              } else {
                hook_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                }, "_typeof");
              }
              return hook_typeof(obj);
            }
            __name(hook_typeof, "hook_typeof");
            function hook_toConsumableArray(arr) {
              return hook_arrayWithoutHoles(arr) || hook_iterableToArray(arr) || hook_unsupportedIterableToArray(arr) || hook_nonIterableSpread();
            }
            __name(hook_toConsumableArray, "hook_toConsumableArray");
            function hook_nonIterableSpread() {
              throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
            }
            __name(hook_nonIterableSpread, "hook_nonIterableSpread");
            function hook_unsupportedIterableToArray(o2, minLen) {
              if (!o2) return;
              if (typeof o2 === "string") return hook_arrayLikeToArray(o2, minLen);
              var n2 = Object.prototype.toString.call(o2).slice(8, -1);
              if (n2 === "Object" && o2.constructor) n2 = o2.constructor.name;
              if (n2 === "Map" || n2 === "Set") return Array.from(o2);
              if (n2 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n2)) return hook_arrayLikeToArray(o2, minLen);
            }
            __name(hook_unsupportedIterableToArray, "hook_unsupportedIterableToArray");
            function hook_iterableToArray(iter) {
              if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
            }
            __name(hook_iterableToArray, "hook_iterableToArray");
            function hook_arrayWithoutHoles(arr) {
              if (Array.isArray(arr)) return hook_arrayLikeToArray(arr);
            }
            __name(hook_arrayWithoutHoles, "hook_arrayWithoutHoles");
            function hook_arrayLikeToArray(arr, len) {
              if (len == null || len > arr.length) len = arr.length;
              for (var i = 0, arr2 = new Array(len); i < len; i++) {
                arr2[i] = arr[i];
              }
              return arr2;
            }
            __name(hook_arrayLikeToArray, "hook_arrayLikeToArray");
            function installHook(target) {
              if (target.hasOwnProperty("__REACT_DEVTOOLS_GLOBAL_HOOK__")) {
                return null;
              }
              var targetConsole2 = console;
              var targetConsoleMethods2 = {};
              for (var method2 in console) {
                targetConsoleMethods2[method2] = console[method2];
              }
              function dangerous_setTargetConsoleForTesting2(targetConsoleForTesting) {
                targetConsole2 = targetConsoleForTesting;
                targetConsoleMethods2 = {};
                for (var _method in targetConsole2) {
                  targetConsoleMethods2[_method] = console[_method];
                }
              }
              __name(dangerous_setTargetConsoleForTesting2, "dangerous_setTargetConsoleForTesting");
              function detectReactBuildType(renderer2) {
                try {
                  if (typeof renderer2.version === "string") {
                    if (renderer2.bundleType > 0) {
                      return "development";
                    }
                    return "production";
                  }
                  var _toString = Function.prototype.toString;
                  if (renderer2.Mount && renderer2.Mount._renderNewRootComponent) {
                    var renderRootCode = _toString.call(renderer2.Mount._renderNewRootComponent);
                    if (renderRootCode.indexOf("function") !== 0) {
                      return "production";
                    }
                    if (renderRootCode.indexOf("storedMeasure") !== -1) {
                      return "development";
                    }
                    if (renderRootCode.indexOf("should be a pure function") !== -1) {
                      if (renderRootCode.indexOf("NODE_ENV") !== -1) {
                        return "development";
                      }
                      if (renderRootCode.indexOf("development") !== -1) {
                        return "development";
                      }
                      if (renderRootCode.indexOf("true") !== -1) {
                        return "development";
                      }
                      if (
                        // 0.13 to 15
                        renderRootCode.indexOf("nextElement") !== -1 || // 0.12
                        renderRootCode.indexOf("nextComponent") !== -1
                      ) {
                        return "unminified";
                      } else {
                        return "development";
                      }
                    }
                    if (
                      // 0.13 to 15
                      renderRootCode.indexOf("nextElement") !== -1 || // 0.12
                      renderRootCode.indexOf("nextComponent") !== -1
                    ) {
                      return "unminified";
                    }
                    return "outdated";
                  }
                } catch (err) {
                }
                return "production";
              }
              __name(detectReactBuildType, "detectReactBuildType");
              function checkDCE(fn) {
                try {
                  var _toString2 = Function.prototype.toString;
                  var code2 = _toString2.call(fn);
                  if (code2.indexOf("^_^") > -1) {
                    hasDetectedBadDCE = true;
                    setTimeout(function() {
                      throw new Error("React is running in production mode, but dead code elimination has not been applied. Read how to correctly configure React for production: https://reactjs.org/link/perf-use-production-build");
                    });
                  }
                } catch (err) {
                }
              }
              __name(checkDCE, "checkDCE");
              function formatWithStyles2(inputArgs, style) {
                if (inputArgs === void 0 || inputArgs === null || inputArgs.length === 0 || // Matches any of %c but not %%c
                typeof inputArgs[0] === "string" && inputArgs[0].match(/([^%]|^)(%c)/g) || style === void 0) {
                  return inputArgs;
                }
                var REGEXP = /([^%]|^)((%%)*)(%([oOdisf]))/g;
                if (typeof inputArgs[0] === "string" && inputArgs[0].match(REGEXP)) {
                  return ["%c".concat(inputArgs[0]), style].concat(hook_toConsumableArray(inputArgs.slice(1)));
                } else {
                  var firstArg = inputArgs.reduce(function(formatStr, elem, i) {
                    if (i > 0) {
                      formatStr += " ";
                    }
                    switch (hook_typeof(elem)) {
                      case "string":
                      case "boolean":
                      case "symbol":
                        return formatStr += "%s";
                      case "number":
                        var formatting = Number.isInteger(elem) ? "%i" : "%f";
                        return formatStr += formatting;
                      default:
                        return formatStr += "%o";
                    }
                  }, "%c");
                  return [firstArg, style].concat(hook_toConsumableArray(inputArgs));
                }
              }
              __name(formatWithStyles2, "formatWithStyles");
              var unpatchFn2 = null;
              function patchConsoleForInitialRenderInStrictMode(_ref) {
                var hideConsoleLogsInStrictMode = _ref.hideConsoleLogsInStrictMode, browserTheme = _ref.browserTheme;
                var overrideConsoleMethods = ["error", "group", "groupCollapsed", "info", "log", "trace", "warn"];
                if (unpatchFn2 !== null) {
                  return;
                }
                var originalConsoleMethods = {};
                unpatchFn2 = /* @__PURE__ */ __name(function unpatchFn3() {
                  for (var _method2 in originalConsoleMethods) {
                    try {
                      targetConsole2[_method2] = originalConsoleMethods[_method2];
                    } catch (error) {
                    }
                  }
                }, "unpatchFn");
                overrideConsoleMethods.forEach(function(method3) {
                  try {
                    var originalMethod = originalConsoleMethods[method3] = targetConsole2[method3].__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ ? targetConsole2[method3].__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ : targetConsole2[method3];
                    var overrideMethod = /* @__PURE__ */ __name(function overrideMethod2() {
                      if (!hideConsoleLogsInStrictMode) {
                        var color;
                        switch (method3) {
                          case "warn":
                            color = browserTheme === "light" ? "rgba(250, 180, 50, 0.75)" : "rgba(250, 180, 50, 0.5)";
                            break;
                          case "error":
                            color = browserTheme === "light" ? "rgba(250, 123, 130, 0.75)" : "rgba(250, 123, 130, 0.5)";
                            break;
                          case "log":
                          default:
                            color = browserTheme === "light" ? "rgba(125, 125, 125, 0.75)" : "rgba(125, 125, 125, 0.5)";
                            break;
                        }
                        if (color) {
                          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                            args[_key] = arguments[_key];
                          }
                          originalMethod.apply(void 0, hook_toConsumableArray(formatWithStyles2(args, "color: ".concat(color))));
                        } else {
                          throw Error("Console color is not defined");
                        }
                      }
                    }, "overrideMethod");
                    overrideMethod.__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ = originalMethod;
                    originalMethod.__REACT_DEVTOOLS_STRICT_MODE_OVERRIDE_METHOD__ = overrideMethod;
                    targetConsole2[method3] = overrideMethod;
                  } catch (error) {
                  }
                });
              }
              __name(patchConsoleForInitialRenderInStrictMode, "patchConsoleForInitialRenderInStrictMode");
              function unpatchConsoleForInitialRenderInStrictMode() {
                if (unpatchFn2 !== null) {
                  unpatchFn2();
                  unpatchFn2 = null;
                }
              }
              __name(unpatchConsoleForInitialRenderInStrictMode, "unpatchConsoleForInitialRenderInStrictMode");
              var uidCounter2 = 0;
              function inject(renderer2) {
                var id = ++uidCounter2;
                renderers.set(id, renderer2);
                var reactBuildType = hasDetectedBadDCE ? "deadcode" : detectReactBuildType(renderer2);
                if (target.hasOwnProperty("__REACT_DEVTOOLS_CONSOLE_FUNCTIONS__")) {
                  var _target$__REACT_DEVTO = target.__REACT_DEVTOOLS_CONSOLE_FUNCTIONS__, registerRendererWithConsole = _target$__REACT_DEVTO.registerRendererWithConsole, patchConsoleUsingWindowValues2 = _target$__REACT_DEVTO.patchConsoleUsingWindowValues;
                  if (typeof registerRendererWithConsole === "function" && typeof patchConsoleUsingWindowValues2 === "function") {
                    registerRendererWithConsole(renderer2);
                    patchConsoleUsingWindowValues2();
                  }
                }
                var attach2 = target.__REACT_DEVTOOLS_ATTACH__;
                if (typeof attach2 === "function") {
                  var rendererInterface = attach2(hook2, id, renderer2, target);
                  hook2.rendererInterfaces.set(id, rendererInterface);
                }
                hook2.emit("renderer", {
                  id,
                  renderer: renderer2,
                  reactBuildType
                });
                return id;
              }
              __name(inject, "inject");
              var hasDetectedBadDCE = false;
              function sub(event, fn) {
                hook2.on(event, fn);
                return function() {
                  return hook2.off(event, fn);
                };
              }
              __name(sub, "sub");
              function on(event, fn) {
                if (!listeners[event]) {
                  listeners[event] = [];
                }
                listeners[event].push(fn);
              }
              __name(on, "on");
              function off(event, fn) {
                if (!listeners[event]) {
                  return;
                }
                var index = listeners[event].indexOf(fn);
                if (index !== -1) {
                  listeners[event].splice(index, 1);
                }
                if (!listeners[event].length) {
                  delete listeners[event];
                }
              }
              __name(off, "off");
              function emit(event, data) {
                if (listeners[event]) {
                  listeners[event].map(function(fn) {
                    return fn(data);
                  });
                }
              }
              __name(emit, "emit");
              function getFiberRoots(rendererID) {
                var roots = fiberRoots;
                if (!roots[rendererID]) {
                  roots[rendererID] = /* @__PURE__ */ new Set();
                }
                return roots[rendererID];
              }
              __name(getFiberRoots, "getFiberRoots");
              function onCommitFiberUnmount(rendererID, fiber) {
                var rendererInterface = rendererInterfaces.get(rendererID);
                if (rendererInterface != null) {
                  rendererInterface.handleCommitFiberUnmount(fiber);
                }
              }
              __name(onCommitFiberUnmount, "onCommitFiberUnmount");
              function onCommitFiberRoot(rendererID, root, priorityLevel) {
                var mountedRoots = hook2.getFiberRoots(rendererID);
                var current = root.current;
                var isKnownRoot = mountedRoots.has(root);
                var isUnmounting = current.memoizedState == null || current.memoizedState.element == null;
                if (!isKnownRoot && !isUnmounting) {
                  mountedRoots.add(root);
                } else if (isKnownRoot && isUnmounting) {
                  mountedRoots.delete(root);
                }
                var rendererInterface = rendererInterfaces.get(rendererID);
                if (rendererInterface != null) {
                  rendererInterface.handleCommitFiberRoot(root, priorityLevel);
                }
              }
              __name(onCommitFiberRoot, "onCommitFiberRoot");
              function onPostCommitFiberRoot(rendererID, root) {
                var rendererInterface = rendererInterfaces.get(rendererID);
                if (rendererInterface != null) {
                  rendererInterface.handlePostCommitFiberRoot(root);
                }
              }
              __name(onPostCommitFiberRoot, "onPostCommitFiberRoot");
              function setStrictMode(rendererID, isStrictMode) {
                var rendererInterface = rendererInterfaces.get(rendererID);
                if (rendererInterface != null) {
                  if (isStrictMode) {
                    rendererInterface.patchConsoleForStrictMode();
                  } else {
                    rendererInterface.unpatchConsoleForStrictMode();
                  }
                } else {
                  if (isStrictMode) {
                    var hideConsoleLogsInStrictMode = window.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ === true;
                    var browserTheme = window.__REACT_DEVTOOLS_BROWSER_THEME__;
                    patchConsoleForInitialRenderInStrictMode({
                      hideConsoleLogsInStrictMode,
                      browserTheme
                    });
                  } else {
                    unpatchConsoleForInitialRenderInStrictMode();
                  }
                }
              }
              __name(setStrictMode, "setStrictMode");
              var openModuleRangesStack = [];
              var moduleRanges = [];
              function getTopStackFrameString(error) {
                var frames = error.stack.split("\n");
                var frame = frames.length > 1 ? frames[1] : null;
                return frame;
              }
              __name(getTopStackFrameString, "getTopStackFrameString");
              function getInternalModuleRanges() {
                return moduleRanges;
              }
              __name(getInternalModuleRanges, "getInternalModuleRanges");
              function registerInternalModuleStart(error) {
                var startStackFrame = getTopStackFrameString(error);
                if (startStackFrame !== null) {
                  openModuleRangesStack.push(startStackFrame);
                }
              }
              __name(registerInternalModuleStart, "registerInternalModuleStart");
              function registerInternalModuleStop(error) {
                if (openModuleRangesStack.length > 0) {
                  var startStackFrame = openModuleRangesStack.pop();
                  var stopStackFrame = getTopStackFrameString(error);
                  if (stopStackFrame !== null) {
                    moduleRanges.push([startStackFrame, stopStackFrame]);
                  }
                }
              }
              __name(registerInternalModuleStop, "registerInternalModuleStop");
              var fiberRoots = {};
              var rendererInterfaces = /* @__PURE__ */ new Map();
              var listeners = {};
              var renderers = /* @__PURE__ */ new Map();
              var backends = /* @__PURE__ */ new Map();
              var hook2 = {
                rendererInterfaces,
                listeners,
                backends,
                // Fast Refresh for web relies on this.
                renderers,
                emit,
                getFiberRoots,
                inject,
                on,
                off,
                sub,
                // This is a legacy flag.
                // React v16 checks the hook for this to ensure DevTools is new enough.
                supportsFiber: true,
                // React calls these methods.
                checkDCE,
                onCommitFiberUnmount,
                onCommitFiberRoot,
                onPostCommitFiberRoot,
                setStrictMode,
                // Schedule Profiler runtime helpers.
                // These internal React modules to report their own boundaries
                // which in turn enables the profiler to dim or filter internal frames.
                getInternalModuleRanges,
                registerInternalModuleStart,
                registerInternalModuleStop
              };
              if (false) {
              }
              Object.defineProperty(target, "__REACT_DEVTOOLS_GLOBAL_HOOK__", {
                // This property needs to be configurable for the test environment,
                // else we won't be able to delete and recreate it between tests.
                configurable: false,
                enumerable: false,
                get: /* @__PURE__ */ __name(function get3() {
                  return hook2;
                }, "get")
              });
              return hook2;
            }
            __name(installHook, "installHook");
            ;
            function decorate(object, attr, fn) {
              var old = object[attr];
              object[attr] = function(instance) {
                return fn.call(this, old, arguments);
              };
              return old;
            }
            __name(decorate, "decorate");
            function decorateMany(source2, fns) {
              var olds = {};
              for (var name3 in fns) {
                olds[name3] = decorate(source2, name3, fns[name3]);
              }
              return olds;
            }
            __name(decorateMany, "decorateMany");
            function restoreMany(source2, olds) {
              for (var name3 in olds) {
                source2[name3] = olds[name3];
              }
            }
            __name(restoreMany, "restoreMany");
            function forceUpdate(instance) {
              if (typeof instance.forceUpdate === "function") {
                instance.forceUpdate();
              } else if (instance.updater != null && typeof instance.updater.enqueueForceUpdate === "function") {
                instance.updater.enqueueForceUpdate(this, function() {
                }, "forceUpdate");
              }
            }
            __name(forceUpdate, "forceUpdate");
            ;
            function legacy_renderer_ownKeys(object, enumerableOnly) {
              var keys = Object.keys(object);
              if (Object.getOwnPropertySymbols) {
                var symbols = Object.getOwnPropertySymbols(object);
                if (enumerableOnly) symbols = symbols.filter(function(sym) {
                  return Object.getOwnPropertyDescriptor(object, sym).enumerable;
                });
                keys.push.apply(keys, symbols);
              }
              return keys;
            }
            __name(legacy_renderer_ownKeys, "legacy_renderer_ownKeys");
            function legacy_renderer_objectSpread(target) {
              for (var i = 1; i < arguments.length; i++) {
                var source2 = arguments[i] != null ? arguments[i] : {};
                if (i % 2) {
                  legacy_renderer_ownKeys(Object(source2), true).forEach(function(key) {
                    legacy_renderer_defineProperty(target, key, source2[key]);
                  });
                } else if (Object.getOwnPropertyDescriptors) {
                  Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
                } else {
                  legacy_renderer_ownKeys(Object(source2)).forEach(function(key) {
                    Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
                  });
                }
              }
              return target;
            }
            __name(legacy_renderer_objectSpread, "legacy_renderer_objectSpread");
            function legacy_renderer_defineProperty(obj, key, value) {
              if (key in obj) {
                Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
              } else {
                obj[key] = value;
              }
              return obj;
            }
            __name(legacy_renderer_defineProperty, "legacy_renderer_defineProperty");
            function legacy_renderer_typeof(obj) {
              "@babel/helpers - typeof";
              if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                legacy_renderer_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return typeof obj2;
                }, "_typeof");
              } else {
                legacy_renderer_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                }, "_typeof");
              }
              return legacy_renderer_typeof(obj);
            }
            __name(legacy_renderer_typeof, "legacy_renderer_typeof");
            function getData(internalInstance) {
              var displayName = null;
              var key = null;
              if (internalInstance._currentElement != null) {
                if (internalInstance._currentElement.key) {
                  key = String(internalInstance._currentElement.key);
                }
                var elementType = internalInstance._currentElement.type;
                if (typeof elementType === "string") {
                  displayName = elementType;
                } else if (typeof elementType === "function") {
                  displayName = getDisplayName(elementType);
                }
              }
              return {
                displayName,
                key
              };
            }
            __name(getData, "getData");
            function getElementType(internalInstance) {
              if (internalInstance._currentElement != null) {
                var elementType = internalInstance._currentElement.type;
                if (typeof elementType === "function") {
                  var publicInstance = internalInstance.getPublicInstance();
                  if (publicInstance !== null) {
                    return types_ElementTypeClass;
                  } else {
                    return types_ElementTypeFunction;
                  }
                } else if (typeof elementType === "string") {
                  return ElementTypeHostComponent;
                }
              }
              return ElementTypeOtherOrUnknown;
            }
            __name(getElementType, "getElementType");
            function getChildren(internalInstance) {
              var children = [];
              if (legacy_renderer_typeof(internalInstance) !== "object") {
              } else if (internalInstance._currentElement === null || internalInstance._currentElement === false) {
              } else if (internalInstance._renderedComponent) {
                var child = internalInstance._renderedComponent;
                if (getElementType(child) !== ElementTypeOtherOrUnknown) {
                  children.push(child);
                }
              } else if (internalInstance._renderedChildren) {
                var renderedChildren = internalInstance._renderedChildren;
                for (var name3 in renderedChildren) {
                  var _child = renderedChildren[name3];
                  if (getElementType(_child) !== ElementTypeOtherOrUnknown) {
                    children.push(_child);
                  }
                }
              }
              return children;
            }
            __name(getChildren, "getChildren");
            function renderer_attach(hook2, rendererID, renderer2, global2) {
              var idToInternalInstanceMap = /* @__PURE__ */ new Map();
              var internalInstanceToIDMap = /* @__PURE__ */ new WeakMap();
              var internalInstanceToRootIDMap = /* @__PURE__ */ new WeakMap();
              var getInternalIDForNative = null;
              var findNativeNodeForInternalID;
              var getFiberForNative = /* @__PURE__ */ __name(function getFiberForNative2(node) {
                return null;
              }, "getFiberForNative");
              if (renderer2.ComponentTree) {
                getInternalIDForNative = /* @__PURE__ */ __name(function getInternalIDForNative2(node, findNearestUnfilteredAncestor) {
                  var internalInstance = renderer2.ComponentTree.getClosestInstanceFromNode(node);
                  return internalInstanceToIDMap.get(internalInstance) || null;
                }, "getInternalIDForNative");
                findNativeNodeForInternalID = /* @__PURE__ */ __name(function findNativeNodeForInternalID2(id) {
                  var internalInstance = idToInternalInstanceMap.get(id);
                  return renderer2.ComponentTree.getNodeFromInstance(internalInstance);
                }, "findNativeNodeForInternalID");
                getFiberForNative = /* @__PURE__ */ __name(function getFiberForNative2(node) {
                  return renderer2.ComponentTree.getClosestInstanceFromNode(node);
                }, "getFiberForNative");
              } else if (renderer2.Mount.getID && renderer2.Mount.getNode) {
                getInternalIDForNative = /* @__PURE__ */ __name(function getInternalIDForNative2(node, findNearestUnfilteredAncestor) {
                  return null;
                }, "getInternalIDForNative");
                findNativeNodeForInternalID = /* @__PURE__ */ __name(function findNativeNodeForInternalID2(id) {
                  return null;
                }, "findNativeNodeForInternalID");
              }
              function getDisplayNameForFiberID(id) {
                var internalInstance = idToInternalInstanceMap.get(id);
                return internalInstance ? getData(internalInstance).displayName : null;
              }
              __name(getDisplayNameForFiberID, "getDisplayNameForFiberID");
              function getID(internalInstance) {
                if (legacy_renderer_typeof(internalInstance) !== "object" || internalInstance === null) {
                  throw new Error("Invalid internal instance: " + internalInstance);
                }
                if (!internalInstanceToIDMap.has(internalInstance)) {
                  var _id = getUID();
                  internalInstanceToIDMap.set(internalInstance, _id);
                  idToInternalInstanceMap.set(_id, internalInstance);
                }
                return internalInstanceToIDMap.get(internalInstance);
              }
              __name(getID, "getID");
              function areEqualArrays(a, b) {
                if (a.length !== b.length) {
                  return false;
                }
                for (var i = 0; i < a.length; i++) {
                  if (a[i] !== b[i]) {
                    return false;
                  }
                }
                return true;
              }
              __name(areEqualArrays, "areEqualArrays");
              var parentIDStack = [];
              var oldReconcilerMethods = null;
              if (renderer2.Reconciler) {
                oldReconcilerMethods = decorateMany(renderer2.Reconciler, {
                  mountComponent: /* @__PURE__ */ __name(function mountComponent(fn, args) {
                    var internalInstance = args[0];
                    var hostContainerInfo = args[3];
                    if (getElementType(internalInstance) === ElementTypeOtherOrUnknown) {
                      return fn.apply(this, args);
                    }
                    if (hostContainerInfo._topLevelWrapper === void 0) {
                      return fn.apply(this, args);
                    }
                    var id = getID(internalInstance);
                    var parentID = parentIDStack.length > 0 ? parentIDStack[parentIDStack.length - 1] : 0;
                    recordMount(internalInstance, id, parentID);
                    parentIDStack.push(id);
                    internalInstanceToRootIDMap.set(internalInstance, getID(hostContainerInfo._topLevelWrapper));
                    try {
                      var result = fn.apply(this, args);
                      parentIDStack.pop();
                      return result;
                    } catch (err) {
                      parentIDStack = [];
                      throw err;
                    } finally {
                      if (parentIDStack.length === 0) {
                        var rootID = internalInstanceToRootIDMap.get(internalInstance);
                        if (rootID === void 0) {
                          throw new Error("Expected to find root ID.");
                        }
                        flushPendingEvents(rootID);
                      }
                    }
                  }, "mountComponent"),
                  performUpdateIfNecessary: /* @__PURE__ */ __name(function performUpdateIfNecessary(fn, args) {
                    var internalInstance = args[0];
                    if (getElementType(internalInstance) === ElementTypeOtherOrUnknown) {
                      return fn.apply(this, args);
                    }
                    var id = getID(internalInstance);
                    parentIDStack.push(id);
                    var prevChildren = getChildren(internalInstance);
                    try {
                      var result = fn.apply(this, args);
                      var nextChildren = getChildren(internalInstance);
                      if (!areEqualArrays(prevChildren, nextChildren)) {
                        recordReorder(internalInstance, id, nextChildren);
                      }
                      parentIDStack.pop();
                      return result;
                    } catch (err) {
                      parentIDStack = [];
                      throw err;
                    } finally {
                      if (parentIDStack.length === 0) {
                        var rootID = internalInstanceToRootIDMap.get(internalInstance);
                        if (rootID === void 0) {
                          throw new Error("Expected to find root ID.");
                        }
                        flushPendingEvents(rootID);
                      }
                    }
                  }, "performUpdateIfNecessary"),
                  receiveComponent: /* @__PURE__ */ __name(function receiveComponent(fn, args) {
                    var internalInstance = args[0];
                    if (getElementType(internalInstance) === ElementTypeOtherOrUnknown) {
                      return fn.apply(this, args);
                    }
                    var id = getID(internalInstance);
                    parentIDStack.push(id);
                    var prevChildren = getChildren(internalInstance);
                    try {
                      var result = fn.apply(this, args);
                      var nextChildren = getChildren(internalInstance);
                      if (!areEqualArrays(prevChildren, nextChildren)) {
                        recordReorder(internalInstance, id, nextChildren);
                      }
                      parentIDStack.pop();
                      return result;
                    } catch (err) {
                      parentIDStack = [];
                      throw err;
                    } finally {
                      if (parentIDStack.length === 0) {
                        var rootID = internalInstanceToRootIDMap.get(internalInstance);
                        if (rootID === void 0) {
                          throw new Error("Expected to find root ID.");
                        }
                        flushPendingEvents(rootID);
                      }
                    }
                  }, "receiveComponent"),
                  unmountComponent: /* @__PURE__ */ __name(function unmountComponent(fn, args) {
                    var internalInstance = args[0];
                    if (getElementType(internalInstance) === ElementTypeOtherOrUnknown) {
                      return fn.apply(this, args);
                    }
                    var id = getID(internalInstance);
                    parentIDStack.push(id);
                    try {
                      var result = fn.apply(this, args);
                      parentIDStack.pop();
                      recordUnmount(internalInstance, id);
                      return result;
                    } catch (err) {
                      parentIDStack = [];
                      throw err;
                    } finally {
                      if (parentIDStack.length === 0) {
                        var rootID = internalInstanceToRootIDMap.get(internalInstance);
                        if (rootID === void 0) {
                          throw new Error("Expected to find root ID.");
                        }
                        flushPendingEvents(rootID);
                      }
                    }
                  }, "unmountComponent")
                });
              }
              function cleanup() {
                if (oldReconcilerMethods !== null) {
                  if (renderer2.Component) {
                    restoreMany(renderer2.Component.Mixin, oldReconcilerMethods);
                  } else {
                    restoreMany(renderer2.Reconciler, oldReconcilerMethods);
                  }
                }
                oldReconcilerMethods = null;
              }
              __name(cleanup, "cleanup");
              function recordMount(internalInstance, id, parentID) {
                var isRoot = parentID === 0;
                if (__DEBUG__) {
                  console.log("%crecordMount()", "color: green; font-weight: bold;", id, getData(internalInstance).displayName);
                }
                if (isRoot) {
                  var hasOwnerMetadata = internalInstance._currentElement != null && internalInstance._currentElement._owner != null;
                  pushOperation(TREE_OPERATION_ADD);
                  pushOperation(id);
                  pushOperation(ElementTypeRoot);
                  pushOperation(0);
                  pushOperation(0);
                  pushOperation(0);
                  pushOperation(hasOwnerMetadata ? 1 : 0);
                } else {
                  var type = getElementType(internalInstance);
                  var _getData = getData(internalInstance), displayName = _getData.displayName, key = _getData.key;
                  var ownerID = internalInstance._currentElement != null && internalInstance._currentElement._owner != null ? getID(internalInstance._currentElement._owner) : 0;
                  var displayNameStringID = getStringID(displayName);
                  var keyStringID = getStringID(key);
                  pushOperation(TREE_OPERATION_ADD);
                  pushOperation(id);
                  pushOperation(type);
                  pushOperation(parentID);
                  pushOperation(ownerID);
                  pushOperation(displayNameStringID);
                  pushOperation(keyStringID);
                }
              }
              __name(recordMount, "recordMount");
              function recordReorder(internalInstance, id, nextChildren) {
                pushOperation(TREE_OPERATION_REORDER_CHILDREN);
                pushOperation(id);
                var nextChildIDs = nextChildren.map(getID);
                pushOperation(nextChildIDs.length);
                for (var i = 0; i < nextChildIDs.length; i++) {
                  pushOperation(nextChildIDs[i]);
                }
              }
              __name(recordReorder, "recordReorder");
              function recordUnmount(internalInstance, id) {
                pendingUnmountedIDs.push(id);
                idToInternalInstanceMap.delete(id);
              }
              __name(recordUnmount, "recordUnmount");
              function crawlAndRecordInitialMounts(id, parentID, rootID) {
                if (__DEBUG__) {
                  console.group("crawlAndRecordInitialMounts() id:", id);
                }
                var internalInstance = idToInternalInstanceMap.get(id);
                if (internalInstance != null) {
                  internalInstanceToRootIDMap.set(internalInstance, rootID);
                  recordMount(internalInstance, id, parentID);
                  getChildren(internalInstance).forEach(function(child) {
                    return crawlAndRecordInitialMounts(getID(child), id, rootID);
                  });
                }
                if (__DEBUG__) {
                  console.groupEnd();
                }
              }
              __name(crawlAndRecordInitialMounts, "crawlAndRecordInitialMounts");
              function flushInitialOperations() {
                var roots = renderer2.Mount._instancesByReactRootID || renderer2.Mount._instancesByContainerID;
                for (var key in roots) {
                  var internalInstance = roots[key];
                  var _id2 = getID(internalInstance);
                  crawlAndRecordInitialMounts(_id2, 0, _id2);
                  flushPendingEvents(_id2);
                }
              }
              __name(flushInitialOperations, "flushInitialOperations");
              var pendingOperations = [];
              var pendingStringTable = /* @__PURE__ */ new Map();
              var pendingUnmountedIDs = [];
              var pendingStringTableLength = 0;
              var pendingUnmountedRootID = null;
              function flushPendingEvents(rootID) {
                if (pendingOperations.length === 0 && pendingUnmountedIDs.length === 0 && pendingUnmountedRootID === null) {
                  return;
                }
                var numUnmountIDs = pendingUnmountedIDs.length + (pendingUnmountedRootID === null ? 0 : 1);
                var operations = new Array(
                  // Identify which renderer this update is coming from.
                  2 + // [rendererID, rootFiberID]
                  // How big is the string table?
                  1 + // [stringTableLength]
                  // Then goes the actual string table.
                  pendingStringTableLength + // All unmounts are batched in a single message.
                  // [TREE_OPERATION_REMOVE, removedIDLength, ...ids]
                  (numUnmountIDs > 0 ? 2 + numUnmountIDs : 0) + // Mount operations
                  pendingOperations.length
                );
                var i = 0;
                operations[i++] = rendererID;
                operations[i++] = rootID;
                operations[i++] = pendingStringTableLength;
                pendingStringTable.forEach(function(value, key) {
                  operations[i++] = key.length;
                  var encodedKey = utfEncodeString(key);
                  for (var j2 = 0; j2 < encodedKey.length; j2++) {
                    operations[i + j2] = encodedKey[j2];
                  }
                  i += key.length;
                });
                if (numUnmountIDs > 0) {
                  operations[i++] = TREE_OPERATION_REMOVE;
                  operations[i++] = numUnmountIDs;
                  for (var j = 0; j < pendingUnmountedIDs.length; j++) {
                    operations[i++] = pendingUnmountedIDs[j];
                  }
                  if (pendingUnmountedRootID !== null) {
                    operations[i] = pendingUnmountedRootID;
                    i++;
                  }
                }
                for (var _j = 0; _j < pendingOperations.length; _j++) {
                  operations[i + _j] = pendingOperations[_j];
                }
                i += pendingOperations.length;
                if (__DEBUG__) {
                  printOperationsArray(operations);
                }
                hook2.emit("operations", operations);
                pendingOperations.length = 0;
                pendingUnmountedIDs = [];
                pendingUnmountedRootID = null;
                pendingStringTable.clear();
                pendingStringTableLength = 0;
              }
              __name(flushPendingEvents, "flushPendingEvents");
              function pushOperation(op) {
                if (false) {
                }
                pendingOperations.push(op);
              }
              __name(pushOperation, "pushOperation");
              function getStringID(str2) {
                if (str2 === null) {
                  return 0;
                }
                var existingID = pendingStringTable.get(str2);
                if (existingID !== void 0) {
                  return existingID;
                }
                var stringID = pendingStringTable.size + 1;
                pendingStringTable.set(str2, stringID);
                pendingStringTableLength += str2.length + 1;
                return stringID;
              }
              __name(getStringID, "getStringID");
              var currentlyInspectedElementID = null;
              var currentlyInspectedPaths = {};
              function mergeInspectedPaths(path108) {
                var current = currentlyInspectedPaths;
                path108.forEach(function(key) {
                  if (!current[key]) {
                    current[key] = {};
                  }
                  current = current[key];
                });
              }
              __name(mergeInspectedPaths, "mergeInspectedPaths");
              function createIsPathAllowed(key) {
                return /* @__PURE__ */ __name(function isPathAllowed(path108) {
                  var current = currentlyInspectedPaths[key];
                  if (!current) {
                    return false;
                  }
                  for (var i = 0; i < path108.length; i++) {
                    current = current[path108[i]];
                    if (!current) {
                      return false;
                    }
                  }
                  return true;
                }, "isPathAllowed");
              }
              __name(createIsPathAllowed, "createIsPathAllowed");
              function getInstanceAndStyle(id) {
                var instance = null;
                var style = null;
                var internalInstance = idToInternalInstanceMap.get(id);
                if (internalInstance != null) {
                  instance = internalInstance._instance || null;
                  var element = internalInstance._currentElement;
                  if (element != null && element.props != null) {
                    style = element.props.style || null;
                  }
                }
                return {
                  instance,
                  style
                };
              }
              __name(getInstanceAndStyle, "getInstanceAndStyle");
              function updateSelectedElement(id) {
                var internalInstance = idToInternalInstanceMap.get(id);
                if (internalInstance == null) {
                  console.warn('Could not find instance with id "'.concat(id, '"'));
                  return;
                }
                switch (getElementType(internalInstance)) {
                  case types_ElementTypeClass:
                    global2.$r = internalInstance._instance;
                    break;
                  case types_ElementTypeFunction:
                    var element = internalInstance._currentElement;
                    if (element == null) {
                      console.warn('Could not find element with id "'.concat(id, '"'));
                      return;
                    }
                    global2.$r = {
                      props: element.props,
                      type: element.type
                    };
                    break;
                  default:
                    global2.$r = null;
                    break;
                }
              }
              __name(updateSelectedElement, "updateSelectedElement");
              function storeAsGlobal(id, path108, count) {
                var inspectedElement = inspectElementRaw(id);
                if (inspectedElement !== null) {
                  var value = utils_getInObject(inspectedElement, path108);
                  var key = "$reactTemp".concat(count);
                  window[key] = value;
                  console.log(key);
                  console.log(value);
                }
              }
              __name(storeAsGlobal, "storeAsGlobal");
              function getSerializedElementValueByPath(id, path108) {
                var inspectedElement = inspectElementRaw(id);
                if (inspectedElement !== null) {
                  var valueToCopy = utils_getInObject(inspectedElement, path108);
                  return serializeToString(valueToCopy);
                }
              }
              __name(getSerializedElementValueByPath, "getSerializedElementValueByPath");
              function inspectElement(requestID, id, path108, forceFullData) {
                if (forceFullData || currentlyInspectedElementID !== id) {
                  currentlyInspectedElementID = id;
                  currentlyInspectedPaths = {};
                }
                var inspectedElement = inspectElementRaw(id);
                if (inspectedElement === null) {
                  return {
                    id,
                    responseID: requestID,
                    type: "not-found"
                  };
                }
                if (path108 !== null) {
                  mergeInspectedPaths(path108);
                }
                updateSelectedElement(id);
                inspectedElement.context = cleanForBridge(inspectedElement.context, createIsPathAllowed("context"));
                inspectedElement.props = cleanForBridge(inspectedElement.props, createIsPathAllowed("props"));
                inspectedElement.state = cleanForBridge(inspectedElement.state, createIsPathAllowed("state"));
                return {
                  id,
                  responseID: requestID,
                  type: "full-data",
                  value: inspectedElement
                };
              }
              __name(inspectElement, "inspectElement");
              function inspectElementRaw(id) {
                var internalInstance = idToInternalInstanceMap.get(id);
                if (internalInstance == null) {
                  return null;
                }
                var _getData2 = getData(internalInstance), displayName = _getData2.displayName, key = _getData2.key;
                var type = getElementType(internalInstance);
                var context2 = null;
                var owners = null;
                var props = null;
                var state = null;
                var source2 = null;
                var element = internalInstance._currentElement;
                if (element !== null) {
                  props = element.props;
                  source2 = element._source != null ? element._source : null;
                  var owner = element._owner;
                  if (owner) {
                    owners = [];
                    while (owner != null) {
                      owners.push({
                        displayName: getData(owner).displayName || "Unknown",
                        id: getID(owner),
                        key: element.key,
                        type: getElementType(owner)
                      });
                      if (owner._currentElement) {
                        owner = owner._currentElement._owner;
                      }
                    }
                  }
                }
                var publicInstance = internalInstance._instance;
                if (publicInstance != null) {
                  context2 = publicInstance.context || null;
                  state = publicInstance.state || null;
                }
                var errors = [];
                var warnings = [];
                return {
                  id,
                  // Does the current renderer support editable hooks and function props?
                  canEditHooks: false,
                  canEditFunctionProps: false,
                  // Does the current renderer support advanced editing interface?
                  canEditHooksAndDeletePaths: false,
                  canEditHooksAndRenamePaths: false,
                  canEditFunctionPropsDeletePaths: false,
                  canEditFunctionPropsRenamePaths: false,
                  // Toggle error boundary did not exist in legacy versions
                  canToggleError: false,
                  isErrored: false,
                  targetErrorBoundaryID: null,
                  // Suspense did not exist in legacy versions
                  canToggleSuspense: false,
                  // Can view component source location.
                  canViewSource: type === types_ElementTypeClass || type === types_ElementTypeFunction,
                  // Only legacy context exists in legacy versions.
                  hasLegacyContext: true,
                  displayName,
                  type,
                  key: key != null ? key : null,
                  // Inspectable properties.
                  context: context2,
                  hooks: null,
                  props,
                  state,
                  errors,
                  warnings,
                  // List of owners
                  owners,
                  // Location of component in source code.
                  source: source2,
                  rootType: null,
                  rendererPackageName: null,
                  rendererVersion: null,
                  plugins: {
                    stylex: null
                  }
                };
              }
              __name(inspectElementRaw, "inspectElementRaw");
              function logElementToConsole(id) {
                var result = inspectElementRaw(id);
                if (result === null) {
                  console.warn('Could not find element with id "'.concat(id, '"'));
                  return;
                }
                var supportsGroup = typeof console.groupCollapsed === "function";
                if (supportsGroup) {
                  console.groupCollapsed(
                    "[Click to expand] %c<".concat(result.displayName || "Component", " />"),
                    // --dom-tag-name-color is the CSS variable Chrome styles HTML elements with in the console.
                    "color: var(--dom-tag-name-color); font-weight: normal;"
                  );
                }
                if (result.props !== null) {
                  console.log("Props:", result.props);
                }
                if (result.state !== null) {
                  console.log("State:", result.state);
                }
                if (result.context !== null) {
                  console.log("Context:", result.context);
                }
                var nativeNode = findNativeNodeForInternalID(id);
                if (nativeNode !== null) {
                  console.log("Node:", nativeNode);
                }
                if (window.chrome || /firefox/i.test(navigator.userAgent)) {
                  console.log("Right-click any value to save it as a global variable for further inspection.");
                }
                if (supportsGroup) {
                  console.groupEnd();
                }
              }
              __name(logElementToConsole, "logElementToConsole");
              function prepareViewAttributeSource(id, path108) {
                var inspectedElement = inspectElementRaw(id);
                if (inspectedElement !== null) {
                  window.$attribute = utils_getInObject(inspectedElement, path108);
                }
              }
              __name(prepareViewAttributeSource, "prepareViewAttributeSource");
              function prepareViewElementSource(id) {
                var internalInstance = idToInternalInstanceMap.get(id);
                if (internalInstance == null) {
                  console.warn('Could not find instance with id "'.concat(id, '"'));
                  return;
                }
                var element = internalInstance._currentElement;
                if (element == null) {
                  console.warn('Could not find element with id "'.concat(id, '"'));
                  return;
                }
                global2.$type = element.type;
              }
              __name(prepareViewElementSource, "prepareViewElementSource");
              function deletePath(type, id, hookID, path108) {
                var internalInstance = idToInternalInstanceMap.get(id);
                if (internalInstance != null) {
                  var publicInstance = internalInstance._instance;
                  if (publicInstance != null) {
                    switch (type) {
                      case "context":
                        deletePathInObject(publicInstance.context, path108);
                        forceUpdate(publicInstance);
                        break;
                      case "hooks":
                        throw new Error("Hooks not supported by this renderer");
                      case "props":
                        var element = internalInstance._currentElement;
                        internalInstance._currentElement = legacy_renderer_objectSpread(legacy_renderer_objectSpread({}, element), {}, {
                          props: copyWithDelete(element.props, path108)
                        });
                        forceUpdate(publicInstance);
                        break;
                      case "state":
                        deletePathInObject(publicInstance.state, path108);
                        forceUpdate(publicInstance);
                        break;
                    }
                  }
                }
              }
              __name(deletePath, "deletePath");
              function renamePath(type, id, hookID, oldPath, newPath) {
                var internalInstance = idToInternalInstanceMap.get(id);
                if (internalInstance != null) {
                  var publicInstance = internalInstance._instance;
                  if (publicInstance != null) {
                    switch (type) {
                      case "context":
                        renamePathInObject(publicInstance.context, oldPath, newPath);
                        forceUpdate(publicInstance);
                        break;
                      case "hooks":
                        throw new Error("Hooks not supported by this renderer");
                      case "props":
                        var element = internalInstance._currentElement;
                        internalInstance._currentElement = legacy_renderer_objectSpread(legacy_renderer_objectSpread({}, element), {}, {
                          props: copyWithRename(element.props, oldPath, newPath)
                        });
                        forceUpdate(publicInstance);
                        break;
                      case "state":
                        renamePathInObject(publicInstance.state, oldPath, newPath);
                        forceUpdate(publicInstance);
                        break;
                    }
                  }
                }
              }
              __name(renamePath, "renamePath");
              function overrideValueAtPath(type, id, hookID, path108, value) {
                var internalInstance = idToInternalInstanceMap.get(id);
                if (internalInstance != null) {
                  var publicInstance = internalInstance._instance;
                  if (publicInstance != null) {
                    switch (type) {
                      case "context":
                        utils_setInObject(publicInstance.context, path108, value);
                        forceUpdate(publicInstance);
                        break;
                      case "hooks":
                        throw new Error("Hooks not supported by this renderer");
                      case "props":
                        var element = internalInstance._currentElement;
                        internalInstance._currentElement = legacy_renderer_objectSpread(legacy_renderer_objectSpread({}, element), {}, {
                          props: copyWithSet(element.props, path108, value)
                        });
                        forceUpdate(publicInstance);
                        break;
                      case "state":
                        utils_setInObject(publicInstance.state, path108, value);
                        forceUpdate(publicInstance);
                        break;
                    }
                  }
                }
              }
              __name(overrideValueAtPath, "overrideValueAtPath");
              var getProfilingData = /* @__PURE__ */ __name(function getProfilingData2() {
                throw new Error("getProfilingData not supported by this renderer");
              }, "getProfilingData");
              var handleCommitFiberRoot = /* @__PURE__ */ __name(function handleCommitFiberRoot2() {
                throw new Error("handleCommitFiberRoot not supported by this renderer");
              }, "handleCommitFiberRoot");
              var handleCommitFiberUnmount = /* @__PURE__ */ __name(function handleCommitFiberUnmount2() {
                throw new Error("handleCommitFiberUnmount not supported by this renderer");
              }, "handleCommitFiberUnmount");
              var handlePostCommitFiberRoot = /* @__PURE__ */ __name(function handlePostCommitFiberRoot2() {
                throw new Error("handlePostCommitFiberRoot not supported by this renderer");
              }, "handlePostCommitFiberRoot");
              var overrideError = /* @__PURE__ */ __name(function overrideError2() {
                throw new Error("overrideError not supported by this renderer");
              }, "overrideError");
              var overrideSuspense = /* @__PURE__ */ __name(function overrideSuspense2() {
                throw new Error("overrideSuspense not supported by this renderer");
              }, "overrideSuspense");
              var startProfiling = /* @__PURE__ */ __name(function startProfiling2() {
              }, "startProfiling");
              var stopProfiling = /* @__PURE__ */ __name(function stopProfiling2() {
              }, "stopProfiling");
              function getBestMatchForTrackedPath() {
                return null;
              }
              __name(getBestMatchForTrackedPath, "getBestMatchForTrackedPath");
              function getPathForElement(id) {
                return null;
              }
              __name(getPathForElement, "getPathForElement");
              function updateComponentFilters(componentFilters) {
              }
              __name(updateComponentFilters, "updateComponentFilters");
              function setTraceUpdatesEnabled(enabled) {
              }
              __name(setTraceUpdatesEnabled, "setTraceUpdatesEnabled");
              function setTrackedPath(path108) {
              }
              __name(setTrackedPath, "setTrackedPath");
              function getOwnersList(id) {
                return null;
              }
              __name(getOwnersList, "getOwnersList");
              function clearErrorsAndWarnings() {
              }
              __name(clearErrorsAndWarnings, "clearErrorsAndWarnings");
              function clearErrorsForFiberID(id) {
              }
              __name(clearErrorsForFiberID, "clearErrorsForFiberID");
              function clearWarningsForFiberID(id) {
              }
              __name(clearWarningsForFiberID, "clearWarningsForFiberID");
              function patchConsoleForStrictMode() {
              }
              __name(patchConsoleForStrictMode, "patchConsoleForStrictMode");
              function unpatchConsoleForStrictMode() {
              }
              __name(unpatchConsoleForStrictMode, "unpatchConsoleForStrictMode");
              function hasFiberWithId(id) {
                return idToInternalInstanceMap.has(id);
              }
              __name(hasFiberWithId, "hasFiberWithId");
              return {
                clearErrorsAndWarnings,
                clearErrorsForFiberID,
                clearWarningsForFiberID,
                cleanup,
                getSerializedElementValueByPath,
                deletePath,
                flushInitialOperations,
                getBestMatchForTrackedPath,
                getDisplayNameForFiberID,
                getFiberForNative,
                getFiberIDForNative: getInternalIDForNative,
                getInstanceAndStyle,
                findNativeNodesForFiberID: /* @__PURE__ */ __name(function findNativeNodesForFiberID(id) {
                  var nativeNode = findNativeNodeForInternalID(id);
                  return nativeNode == null ? null : [nativeNode];
                }, "findNativeNodesForFiberID"),
                getOwnersList,
                getPathForElement,
                getProfilingData,
                handleCommitFiberRoot,
                handleCommitFiberUnmount,
                handlePostCommitFiberRoot,
                hasFiberWithId,
                inspectElement,
                logElementToConsole,
                overrideError,
                overrideSuspense,
                overrideValueAtPath,
                renamePath,
                patchConsoleForStrictMode,
                prepareViewAttributeSource,
                prepareViewElementSource,
                renderer: renderer2,
                setTraceUpdatesEnabled,
                setTrackedPath,
                startProfiling,
                stopProfiling,
                storeAsGlobal,
                unpatchConsoleForStrictMode,
                updateComponentFilters
              };
            }
            __name(renderer_attach, "renderer_attach");
            ;
            function isMatchingRender(version2) {
              return !hasAssignedBackend(version2);
            }
            __name(isMatchingRender, "isMatchingRender");
            function initBackend(hook2, agent2, global2) {
              if (hook2 == null) {
                return function() {
                };
              }
              var subs = [
                hook2.sub("renderer-attached", function(_ref) {
                  var id = _ref.id, renderer2 = _ref.renderer, rendererInterface = _ref.rendererInterface;
                  agent2.setRendererInterface(id, rendererInterface);
                  rendererInterface.flushInitialOperations();
                }),
                hook2.sub("unsupported-renderer-version", function(id) {
                  agent2.onUnsupportedRenderer(id);
                }),
                hook2.sub("fastRefreshScheduled", agent2.onFastRefreshScheduled),
                hook2.sub("operations", agent2.onHookOperations),
                hook2.sub("traceUpdates", agent2.onTraceUpdates)
                // TODO Add additional subscriptions required for profiling mode
              ];
              var attachRenderer = /* @__PURE__ */ __name(function attachRenderer2(id, renderer2) {
                if (!isMatchingRender(renderer2.reconcilerVersion || renderer2.version)) {
                  return;
                }
                var rendererInterface = hook2.rendererInterfaces.get(id);
                if (rendererInterface == null) {
                  if (typeof renderer2.findFiberByHostInstance === "function") {
                    rendererInterface = attach(hook2, id, renderer2, global2);
                  } else if (renderer2.ComponentTree) {
                    rendererInterface = renderer_attach(hook2, id, renderer2, global2);
                  } else {
                  }
                  if (rendererInterface != null) {
                    hook2.rendererInterfaces.set(id, rendererInterface);
                  }
                }
                if (rendererInterface != null) {
                  hook2.emit("renderer-attached", {
                    id,
                    renderer: renderer2,
                    rendererInterface
                  });
                } else {
                  hook2.emit("unsupported-renderer-version", id);
                }
              }, "attachRenderer");
              hook2.renderers.forEach(function(renderer2, id) {
                attachRenderer(id, renderer2);
              });
              subs.push(hook2.sub("renderer", function(_ref2) {
                var id = _ref2.id, renderer2 = _ref2.renderer;
                attachRenderer(id, renderer2);
              }));
              hook2.emit("react-devtools", agent2);
              hook2.reactDevtoolsAgent = agent2;
              var onAgentShutdown = /* @__PURE__ */ __name(function onAgentShutdown2() {
                subs.forEach(function(fn) {
                  return fn();
                });
                hook2.rendererInterfaces.forEach(function(rendererInterface) {
                  rendererInterface.cleanup();
                });
                hook2.reactDevtoolsAgent = null;
              }, "onAgentShutdown");
              agent2.addListener("shutdown", onAgentShutdown);
              subs.push(function() {
                agent2.removeListener("shutdown", onAgentShutdown);
              });
              return function() {
                subs.forEach(function(fn) {
                  return fn();
                });
              };
            }
            __name(initBackend, "initBackend");
            ;
            function resolveBoxStyle(prefix2, style) {
              var hasParts = false;
              var result = {
                bottom: 0,
                left: 0,
                right: 0,
                top: 0
              };
              var styleForAll = style[prefix2];
              if (styleForAll != null) {
                for (var _i = 0, _Object$keys = Object.keys(result); _i < _Object$keys.length; _i++) {
                  var key = _Object$keys[_i];
                  result[key] = styleForAll;
                }
                hasParts = true;
              }
              var styleForHorizontal = style[prefix2 + "Horizontal"];
              if (styleForHorizontal != null) {
                result.left = styleForHorizontal;
                result.right = styleForHorizontal;
                hasParts = true;
              } else {
                var styleForLeft = style[prefix2 + "Left"];
                if (styleForLeft != null) {
                  result.left = styleForLeft;
                  hasParts = true;
                }
                var styleForRight = style[prefix2 + "Right"];
                if (styleForRight != null) {
                  result.right = styleForRight;
                  hasParts = true;
                }
                var styleForEnd = style[prefix2 + "End"];
                if (styleForEnd != null) {
                  result.right = styleForEnd;
                  hasParts = true;
                }
                var styleForStart = style[prefix2 + "Start"];
                if (styleForStart != null) {
                  result.left = styleForStart;
                  hasParts = true;
                }
              }
              var styleForVertical = style[prefix2 + "Vertical"];
              if (styleForVertical != null) {
                result.bottom = styleForVertical;
                result.top = styleForVertical;
                hasParts = true;
              } else {
                var styleForBottom = style[prefix2 + "Bottom"];
                if (styleForBottom != null) {
                  result.bottom = styleForBottom;
                  hasParts = true;
                }
                var styleForTop = style[prefix2 + "Top"];
                if (styleForTop != null) {
                  result.top = styleForTop;
                  hasParts = true;
                }
              }
              return hasParts ? result : null;
            }
            __name(resolveBoxStyle, "resolveBoxStyle");
            ;
            function setupNativeStyleEditor_typeof(obj) {
              "@babel/helpers - typeof";
              if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                setupNativeStyleEditor_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return typeof obj2;
                }, "_typeof");
              } else {
                setupNativeStyleEditor_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                }, "_typeof");
              }
              return setupNativeStyleEditor_typeof(obj);
            }
            __name(setupNativeStyleEditor_typeof, "setupNativeStyleEditor_typeof");
            function setupNativeStyleEditor_defineProperty(obj, key, value) {
              if (key in obj) {
                Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
              } else {
                obj[key] = value;
              }
              return obj;
            }
            __name(setupNativeStyleEditor_defineProperty, "setupNativeStyleEditor_defineProperty");
            function setupNativeStyleEditor(bridge, agent2, resolveNativeStyle, validAttributes) {
              bridge.addListener("NativeStyleEditor_measure", function(_ref) {
                var id = _ref.id, rendererID = _ref.rendererID;
                measureStyle(agent2, bridge, resolveNativeStyle, id, rendererID);
              });
              bridge.addListener("NativeStyleEditor_renameAttribute", function(_ref2) {
                var id = _ref2.id, rendererID = _ref2.rendererID, oldName = _ref2.oldName, newName = _ref2.newName, value = _ref2.value;
                renameStyle(agent2, id, rendererID, oldName, newName, value);
                setTimeout(function() {
                  return measureStyle(agent2, bridge, resolveNativeStyle, id, rendererID);
                });
              });
              bridge.addListener("NativeStyleEditor_setValue", function(_ref3) {
                var id = _ref3.id, rendererID = _ref3.rendererID, name3 = _ref3.name, value = _ref3.value;
                setStyle2(agent2, id, rendererID, name3, value);
                setTimeout(function() {
                  return measureStyle(agent2, bridge, resolveNativeStyle, id, rendererID);
                });
              });
              bridge.send("isNativeStyleEditorSupported", {
                isSupported: true,
                validAttributes
              });
            }
            __name(setupNativeStyleEditor, "setupNativeStyleEditor");
            var EMPTY_BOX_STYLE = {
              top: 0,
              left: 0,
              right: 0,
              bottom: 0
            };
            var componentIDToStyleOverrides = /* @__PURE__ */ new Map();
            function measureStyle(agent2, bridge, resolveNativeStyle, id, rendererID) {
              var data = agent2.getInstanceAndStyle({
                id,
                rendererID
              });
              if (!data || !data.style) {
                bridge.send("NativeStyleEditor_styleAndLayout", {
                  id,
                  layout: null,
                  style: null
                });
                return;
              }
              var instance = data.instance, style = data.style;
              var resolvedStyle = resolveNativeStyle(style);
              var styleOverrides = componentIDToStyleOverrides.get(id);
              if (styleOverrides != null) {
                resolvedStyle = Object.assign({}, resolvedStyle, styleOverrides);
              }
              if (!instance || typeof instance.measure !== "function") {
                bridge.send("NativeStyleEditor_styleAndLayout", {
                  id,
                  layout: null,
                  style: resolvedStyle || null
                });
                return;
              }
              instance.measure(function(x, y, width, height, left3, top2) {
                if (typeof x !== "number") {
                  bridge.send("NativeStyleEditor_styleAndLayout", {
                    id,
                    layout: null,
                    style: resolvedStyle || null
                  });
                  return;
                }
                var margin = resolvedStyle != null && resolveBoxStyle("margin", resolvedStyle) || EMPTY_BOX_STYLE;
                var padding = resolvedStyle != null && resolveBoxStyle("padding", resolvedStyle) || EMPTY_BOX_STYLE;
                bridge.send("NativeStyleEditor_styleAndLayout", {
                  id,
                  layout: {
                    x,
                    y,
                    width,
                    height,
                    left: left3,
                    top: top2,
                    margin,
                    padding
                  },
                  style: resolvedStyle || null
                });
              });
            }
            __name(measureStyle, "measureStyle");
            function shallowClone(object) {
              var cloned = {};
              for (var n2 in object) {
                cloned[n2] = object[n2];
              }
              return cloned;
            }
            __name(shallowClone, "shallowClone");
            function renameStyle(agent2, id, rendererID, oldName, newName, value) {
              var _ref4;
              var data = agent2.getInstanceAndStyle({
                id,
                rendererID
              });
              if (!data || !data.style) {
                return;
              }
              var instance = data.instance, style = data.style;
              var newStyle = newName ? (_ref4 = {}, setupNativeStyleEditor_defineProperty(_ref4, oldName, void 0), setupNativeStyleEditor_defineProperty(_ref4, newName, value), _ref4) : setupNativeStyleEditor_defineProperty({}, oldName, void 0);
              var customStyle;
              if (instance !== null && typeof instance.setNativeProps === "function") {
                var styleOverrides = componentIDToStyleOverrides.get(id);
                if (!styleOverrides) {
                  componentIDToStyleOverrides.set(id, newStyle);
                } else {
                  Object.assign(styleOverrides, newStyle);
                }
                instance.setNativeProps({
                  style: newStyle
                });
              } else if (src_isArray(style)) {
                var lastIndex = style.length - 1;
                if (setupNativeStyleEditor_typeof(style[lastIndex]) === "object" && !src_isArray(style[lastIndex])) {
                  customStyle = shallowClone(style[lastIndex]);
                  delete customStyle[oldName];
                  if (newName) {
                    customStyle[newName] = value;
                  } else {
                    customStyle[oldName] = void 0;
                  }
                  agent2.overrideValueAtPath({
                    type: "props",
                    id,
                    rendererID,
                    path: ["style", lastIndex],
                    value: customStyle
                  });
                } else {
                  agent2.overrideValueAtPath({
                    type: "props",
                    id,
                    rendererID,
                    path: ["style"],
                    value: style.concat([newStyle])
                  });
                }
              } else if (setupNativeStyleEditor_typeof(style) === "object") {
                customStyle = shallowClone(style);
                delete customStyle[oldName];
                if (newName) {
                  customStyle[newName] = value;
                } else {
                  customStyle[oldName] = void 0;
                }
                agent2.overrideValueAtPath({
                  type: "props",
                  id,
                  rendererID,
                  path: ["style"],
                  value: customStyle
                });
              } else {
                agent2.overrideValueAtPath({
                  type: "props",
                  id,
                  rendererID,
                  path: ["style"],
                  value: [style, newStyle]
                });
              }
              agent2.emit("hideNativeHighlight");
            }
            __name(renameStyle, "renameStyle");
            function setStyle2(agent2, id, rendererID, name3, value) {
              var data = agent2.getInstanceAndStyle({
                id,
                rendererID
              });
              if (!data || !data.style) {
                return;
              }
              var instance = data.instance, style = data.style;
              var newStyle = setupNativeStyleEditor_defineProperty({}, name3, value);
              if (instance !== null && typeof instance.setNativeProps === "function") {
                var styleOverrides = componentIDToStyleOverrides.get(id);
                if (!styleOverrides) {
                  componentIDToStyleOverrides.set(id, newStyle);
                } else {
                  Object.assign(styleOverrides, newStyle);
                }
                instance.setNativeProps({
                  style: newStyle
                });
              } else if (src_isArray(style)) {
                var lastLength = style.length - 1;
                if (setupNativeStyleEditor_typeof(style[lastLength]) === "object" && !src_isArray(style[lastLength])) {
                  agent2.overrideValueAtPath({
                    type: "props",
                    id,
                    rendererID,
                    path: ["style", lastLength, name3],
                    value
                  });
                } else {
                  agent2.overrideValueAtPath({
                    type: "props",
                    id,
                    rendererID,
                    path: ["style"],
                    value: style.concat([newStyle])
                  });
                }
              } else {
                agent2.overrideValueAtPath({
                  type: "props",
                  id,
                  rendererID,
                  path: ["style"],
                  value: [style, newStyle]
                });
              }
              agent2.emit("hideNativeHighlight");
            }
            __name(setStyle2, "setStyle");
            ;
            function initializeUsingCachedSettings(devToolsSettingsManager) {
              initializeConsolePatchSettings(devToolsSettingsManager);
            }
            __name(initializeUsingCachedSettings, "initializeUsingCachedSettings");
            function initializeConsolePatchSettings(devToolsSettingsManager) {
              if (devToolsSettingsManager.getConsolePatchSettings == null) {
                return;
              }
              var consolePatchSettingsString = devToolsSettingsManager.getConsolePatchSettings();
              if (consolePatchSettingsString == null) {
                return;
              }
              var parsedConsolePatchSettings = parseConsolePatchSettings(consolePatchSettingsString);
              if (parsedConsolePatchSettings == null) {
                return;
              }
              writeConsolePatchSettingsToWindow(parsedConsolePatchSettings);
            }
            __name(initializeConsolePatchSettings, "initializeConsolePatchSettings");
            function parseConsolePatchSettings(consolePatchSettingsString) {
              var _castBool, _castBool2, _castBool3, _castBool4, _castBrowserTheme;
              var parsedValue = JSON.parse(consolePatchSettingsString !== null && consolePatchSettingsString !== void 0 ? consolePatchSettingsString : "{}");
              var appendComponentStack = parsedValue.appendComponentStack, breakOnConsoleErrors = parsedValue.breakOnConsoleErrors, showInlineWarningsAndErrors = parsedValue.showInlineWarningsAndErrors, hideConsoleLogsInStrictMode = parsedValue.hideConsoleLogsInStrictMode, browserTheme = parsedValue.browserTheme;
              return {
                appendComponentStack: (_castBool = castBool(appendComponentStack)) !== null && _castBool !== void 0 ? _castBool : true,
                breakOnConsoleErrors: (_castBool2 = castBool(breakOnConsoleErrors)) !== null && _castBool2 !== void 0 ? _castBool2 : false,
                showInlineWarningsAndErrors: (_castBool3 = castBool(showInlineWarningsAndErrors)) !== null && _castBool3 !== void 0 ? _castBool3 : true,
                hideConsoleLogsInStrictMode: (_castBool4 = castBool(hideConsoleLogsInStrictMode)) !== null && _castBool4 !== void 0 ? _castBool4 : false,
                browserTheme: (_castBrowserTheme = castBrowserTheme(browserTheme)) !== null && _castBrowserTheme !== void 0 ? _castBrowserTheme : "dark"
              };
            }
            __name(parseConsolePatchSettings, "parseConsolePatchSettings");
            function cacheConsolePatchSettings(devToolsSettingsManager, value) {
              if (devToolsSettingsManager.setConsolePatchSettings == null) {
                return;
              }
              devToolsSettingsManager.setConsolePatchSettings(JSON.stringify(value));
            }
            __name(cacheConsolePatchSettings, "cacheConsolePatchSettings");
            ;
            installConsoleFunctionsToWindow();
            installHook(window);
            var hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
            var savedComponentFilters = getDefaultComponentFilters();
            function backend_debug(methodName) {
              if (__DEBUG__) {
                var _console;
                for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                  args[_key - 1] = arguments[_key];
                }
                (_console = console).log.apply(_console, ["%c[core/backend] %c".concat(methodName), "color: teal; font-weight: bold;", "font-weight: bold;"].concat(args));
              }
            }
            __name(backend_debug, "backend_debug");
            function connectToDevTools(options2) {
              if (hook == null) {
                return;
              }
              var _ref = options2 || {}, _ref$host = _ref.host, host = _ref$host === void 0 ? "localhost" : _ref$host, nativeStyleEditorValidAttributes = _ref.nativeStyleEditorValidAttributes, _ref$useHttps = _ref.useHttps, useHttps = _ref$useHttps === void 0 ? false : _ref$useHttps, _ref$port = _ref.port, port = _ref$port === void 0 ? 8097 : _ref$port, websocket = _ref.websocket, _ref$resolveRNStyle = _ref.resolveRNStyle, resolveRNStyle = _ref$resolveRNStyle === void 0 ? null : _ref$resolveRNStyle, _ref$retryConnectionD = _ref.retryConnectionDelay, retryConnectionDelay = _ref$retryConnectionD === void 0 ? 2e3 : _ref$retryConnectionD, _ref$isAppActive = _ref.isAppActive, isAppActive = _ref$isAppActive === void 0 ? function() {
                return true;
              } : _ref$isAppActive, devToolsSettingsManager = _ref.devToolsSettingsManager;
              var protocol = useHttps ? "wss" : "ws";
              var retryTimeoutID = null;
              function scheduleRetry() {
                if (retryTimeoutID === null) {
                  retryTimeoutID = setTimeout(function() {
                    return connectToDevTools(options2);
                  }, retryConnectionDelay);
                }
              }
              __name(scheduleRetry, "scheduleRetry");
              if (devToolsSettingsManager != null) {
                try {
                  initializeUsingCachedSettings(devToolsSettingsManager);
                } catch (e2) {
                  console.error(e2);
                }
              }
              if (!isAppActive()) {
                scheduleRetry();
                return;
              }
              var bridge = null;
              var messageListeners = [];
              var uri = protocol + "://" + host + ":" + port;
              var ws2 = websocket ? websocket : new window.WebSocket(uri);
              ws2.onclose = handleClose;
              ws2.onerror = handleFailed;
              ws2.onmessage = handleMessage;
              ws2.onopen = function() {
                bridge = new src_bridge({
                  listen: /* @__PURE__ */ __name(function listen(fn) {
                    messageListeners.push(fn);
                    return function() {
                      var index = messageListeners.indexOf(fn);
                      if (index >= 0) {
                        messageListeners.splice(index, 1);
                      }
                    };
                  }, "listen"),
                  send: /* @__PURE__ */ __name(function send(event, payload, transferable) {
                    if (ws2.readyState === ws2.OPEN) {
                      if (__DEBUG__) {
                        backend_debug("wall.send()", event, payload);
                      }
                      ws2.send(JSON.stringify({
                        event,
                        payload
                      }));
                    } else {
                      if (__DEBUG__) {
                        backend_debug("wall.send()", "Shutting down bridge because of closed WebSocket connection");
                      }
                      if (bridge !== null) {
                        bridge.shutdown();
                      }
                      scheduleRetry();
                    }
                  }, "send")
                });
                bridge.addListener("updateComponentFilters", function(componentFilters) {
                  savedComponentFilters = componentFilters;
                });
                if (devToolsSettingsManager != null && bridge != null) {
                  bridge.addListener("updateConsolePatchSettings", function(consolePatchSettings) {
                    return cacheConsolePatchSettings(devToolsSettingsManager, consolePatchSettings);
                  });
                }
                if (window.__REACT_DEVTOOLS_COMPONENT_FILTERS__ == null) {
                  bridge.send("overrideComponentFilters", savedComponentFilters);
                }
                var agent2 = new Agent3(bridge);
                agent2.addListener("shutdown", function() {
                  hook.emit("shutdown");
                });
                initBackend(hook, agent2, window);
                if (resolveRNStyle != null || hook.resolveRNStyle != null) {
                  setupNativeStyleEditor(
                    // $FlowFixMe[incompatible-call] found when upgrading Flow
                    bridge,
                    agent2,
                    resolveRNStyle || hook.resolveRNStyle,
                    nativeStyleEditorValidAttributes || hook.nativeStyleEditorValidAttributes || null
                  );
                } else {
                  var lazyResolveRNStyle;
                  var lazyNativeStyleEditorValidAttributes;
                  var initAfterTick = /* @__PURE__ */ __name(function initAfterTick2() {
                    if (bridge !== null) {
                      setupNativeStyleEditor(bridge, agent2, lazyResolveRNStyle, lazyNativeStyleEditorValidAttributes);
                    }
                  }, "initAfterTick");
                  if (!hook.hasOwnProperty("resolveRNStyle")) {
                    Object.defineProperty(hook, "resolveRNStyle", {
                      enumerable: false,
                      get: /* @__PURE__ */ __name(function get3() {
                        return lazyResolveRNStyle;
                      }, "get"),
                      set: /* @__PURE__ */ __name(function set(value) {
                        lazyResolveRNStyle = value;
                        initAfterTick();
                      }, "set")
                    });
                  }
                  if (!hook.hasOwnProperty("nativeStyleEditorValidAttributes")) {
                    Object.defineProperty(hook, "nativeStyleEditorValidAttributes", {
                      enumerable: false,
                      get: /* @__PURE__ */ __name(function get3() {
                        return lazyNativeStyleEditorValidAttributes;
                      }, "get"),
                      set: /* @__PURE__ */ __name(function set(value) {
                        lazyNativeStyleEditorValidAttributes = value;
                        initAfterTick();
                      }, "set")
                    });
                  }
                }
              };
              function handleClose() {
                if (__DEBUG__) {
                  backend_debug("WebSocket.onclose");
                }
                if (bridge !== null) {
                  bridge.emit("shutdown");
                }
                scheduleRetry();
              }
              __name(handleClose, "handleClose");
              function handleFailed() {
                if (__DEBUG__) {
                  backend_debug("WebSocket.onerror");
                }
                scheduleRetry();
              }
              __name(handleFailed, "handleFailed");
              function handleMessage(event) {
                var data;
                try {
                  if (typeof event.data === "string") {
                    data = JSON.parse(event.data);
                    if (__DEBUG__) {
                      backend_debug("WebSocket.onmessage", data);
                    }
                  } else {
                    throw Error();
                  }
                } catch (e2) {
                  console.error("[React DevTools] Failed to parse JSON: " + event.data);
                  return;
                }
                messageListeners.forEach(function(fn) {
                  try {
                    fn(data);
                  } catch (error) {
                    console.log("[React DevTools] Error calling listener", data);
                    console.log("error:", error);
                    throw error;
                  }
                });
              }
              __name(handleMessage, "handleMessage");
            }
            __name(connectToDevTools, "connectToDevTools");
          })();
          return __webpack_exports__;
        })()
      );
    });
  }
});

// node_modules/ink/build/devtools.js
var devtools_exports = {};
var import_react_devtools_core;
var init_devtools = __esm({
  "node_modules/ink/build/devtools.js"() {
    init_esbuild_shims();
    init_devtools_window_polyfill();
    import_react_devtools_core = __toESM(require_backend(), 1);
    import_react_devtools_core.default.connectToDevTools();
  }
});

// node_modules/cli-boxes/boxes.json
var require_boxes = __commonJS({
  "node_modules/cli-boxes/boxes.json"(exports2, module2) {
    module2.exports = {
      single: {
        topLeft: "\u250C",
        top: "\u2500",
        topRight: "\u2510",
        right: "\u2502",
        bottomRight: "\u2518",
        bottom: "\u2500",
        bottomLeft: "\u2514",
        left: "\u2502"
      },
      double: {
        topLeft: "\u2554",
        top: "\u2550",
        topRight: "\u2557",
        right: "\u2551",
        bottomRight: "\u255D",
        bottom: "\u2550",
        bottomLeft: "\u255A",
        left: "\u2551"
      },
      round: {
        topLeft: "\u256D",
        top: "\u2500",
        topRight: "\u256E",
        right: "\u2502",
        bottomRight: "\u256F",
        bottom: "\u2500",
        bottomLeft: "\u2570",
        left: "\u2502"
      },
      bold: {
        topLeft: "\u250F",
        top: "\u2501",
        topRight: "\u2513",
        right: "\u2503",
        bottomRight: "\u251B",
        bottom: "\u2501",
        bottomLeft: "\u2517",
        left: "\u2503"
      },
      singleDouble: {
        topLeft: "\u2553",
        top: "\u2500",
        topRight: "\u2556",
        right: "\u2551",
        bottomRight: "\u255C",
        bottom: "\u2500",
        bottomLeft: "\u2559",
        left: "\u2551"
      },
      doubleSingle: {
        topLeft: "\u2552",
        top: "\u2550",
        topRight: "\u2555",
        right: "\u2502",
        bottomRight: "\u255B",
        bottom: "\u2550",
        bottomLeft: "\u2558",
        left: "\u2502"
      },
      classic: {
        topLeft: "+",
        top: "-",
        topRight: "+",
        right: "|",
        bottomRight: "+",
        bottom: "-",
        bottomLeft: "+",
        left: "|"
      },
      arrow: {
        topLeft: "\u2198",
        top: "\u2193",
        topRight: "\u2199",
        right: "\u2190",
        bottomRight: "\u2196",
        bottom: "\u2191",
        bottomLeft: "\u2197",
        left: "\u2192"
      }
    };
  }
});

// node_modules/cli-boxes/index.js
var require_cli_boxes = __commonJS({
  "node_modules/cli-boxes/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var cliBoxes3 = require_boxes();
    module2.exports = cliBoxes3;
    module2.exports.default = cliBoxes3;
  }
});

// node_modules/mimic-fn/index.js
var require_mimic_fn = __commonJS({
  "node_modules/mimic-fn/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var mimicFn = /* @__PURE__ */ __name((to, from) => {
      for (const prop of Reflect.ownKeys(from)) {
        Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
      }
      return to;
    }, "mimicFn");
    module2.exports = mimicFn;
    module2.exports.default = mimicFn;
  }
});

// node_modules/onetime/index.js
var require_onetime = __commonJS({
  "node_modules/onetime/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var mimicFn = require_mimic_fn();
    var calledFunctions = /* @__PURE__ */ new WeakMap();
    var onetime2 = /* @__PURE__ */ __name((function_, options2 = {}) => {
      if (typeof function_ !== "function") {
        throw new TypeError("Expected a function");
      }
      let returnValue;
      let callCount = 0;
      const functionName = function_.displayName || function_.name || "<anonymous>";
      const onetime3 = /* @__PURE__ */ __name(function(...arguments_) {
        calledFunctions.set(onetime3, ++callCount);
        if (callCount === 1) {
          returnValue = function_.apply(this, arguments_);
          function_ = null;
        } else if (options2.throw === true) {
          throw new Error(`Function \`${functionName}\` can only be called once`);
        }
        return returnValue;
      }, "onetime");
      mimicFn(onetime3, function_);
      calledFunctions.set(onetime3, callCount);
      return onetime3;
    }, "onetime");
    module2.exports = onetime2;
    module2.exports.default = onetime2;
    module2.exports.callCount = (function_) => {
      if (!calledFunctions.has(function_)) {
        throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
      }
      return calledFunctions.get(function_);
    };
  }
});

// node_modules/restore-cursor/node_modules/signal-exit/signals.js
var require_signals2 = __commonJS({
  "node_modules/restore-cursor/node_modules/signal-exit/signals.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = [
      "SIGABRT",
      "SIGALRM",
      "SIGHUP",
      "SIGINT",
      "SIGTERM"
    ];
    if (process.platform !== "win32") {
      module2.exports.push(
        "SIGVTALRM",
        "SIGXCPU",
        "SIGXFSZ",
        "SIGUSR2",
        "SIGTRAP",
        "SIGSYS",
        "SIGQUIT",
        "SIGIOT"
        // should detect profiler and enable/disable accordingly.
        // see #21
        // 'SIGPROF'
      );
    }
    if (process.platform === "linux") {
      module2.exports.push(
        "SIGIO",
        "SIGPOLL",
        "SIGPWR",
        "SIGSTKFLT",
        "SIGUNUSED"
      );
    }
  }
});

// node_modules/restore-cursor/node_modules/signal-exit/index.js
var require_signal_exit2 = __commonJS({
  "node_modules/restore-cursor/node_modules/signal-exit/index.js"(exports2, module2) {
    init_esbuild_shims();
    var process51 = globalThis.process;
    var processOk = /* @__PURE__ */ __name(function(process52) {
      return process52 && typeof process52 === "object" && typeof process52.removeListener === "function" && typeof process52.emit === "function" && typeof process52.reallyExit === "function" && typeof process52.listeners === "function" && typeof process52.kill === "function" && typeof process52.pid === "number" && typeof process52.on === "function";
    }, "processOk");
    if (!processOk(process51)) {
      module2.exports = function() {
        return function() {
        };
      };
    } else {
      assert3 = __require("assert");
      signals = require_signals2();
      isWin = /^win/i.test(process51.platform);
      EE3 = __require("events");
      if (typeof EE3 !== "function") {
        EE3 = EE3.EventEmitter;
      }
      if (process51.__signal_exit_emitter__) {
        emitter = process51.__signal_exit_emitter__;
      } else {
        emitter = process51.__signal_exit_emitter__ = new EE3();
        emitter.count = 0;
        emitter.emitted = {};
      }
      if (!emitter.infinite) {
        emitter.setMaxListeners(Infinity);
        emitter.infinite = true;
      }
      module2.exports = function(cb, opts) {
        if (!processOk(globalThis.process)) {
          return function() {
          };
        }
        assert3.equal(typeof cb, "function", "a callback must be provided for exit handler");
        if (loaded === false) {
          load();
        }
        var ev = "exit";
        if (opts && opts.alwaysLast) {
          ev = "afterexit";
        }
        var remove2 = /* @__PURE__ */ __name(function() {
          emitter.removeListener(ev, cb);
          if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) {
            unload();
          }
        }, "remove");
        emitter.on(ev, cb);
        return remove2;
      };
      unload = /* @__PURE__ */ __name(function unload2() {
        if (!loaded || !processOk(globalThis.process)) {
          return;
        }
        loaded = false;
        signals.forEach(function(sig) {
          try {
            process51.removeListener(sig, sigListeners[sig]);
          } catch (er) {
          }
        });
        process51.emit = originalProcessEmit;
        process51.reallyExit = originalProcessReallyExit;
        emitter.count -= 1;
      }, "unload");
      module2.exports.unload = unload;
      emit = /* @__PURE__ */ __name(function emit2(event, code2, signal) {
        if (emitter.emitted[event]) {
          return;
        }
        emitter.emitted[event] = true;
        emitter.emit(event, code2, signal);
      }, "emit");
      sigListeners = {};
      signals.forEach(function(sig) {
        sigListeners[sig] = /* @__PURE__ */ __name(function listener() {
          if (!processOk(globalThis.process)) {
            return;
          }
          var listeners = process51.listeners(sig);
          if (listeners.length === emitter.count) {
            unload();
            emit("exit", null, sig);
            emit("afterexit", null, sig);
            if (isWin && sig === "SIGHUP") {
              sig = "SIGINT";
            }
            process51.kill(process51.pid, sig);
          }
        }, "listener");
      });
      module2.exports.signals = function() {
        return signals;
      };
      loaded = false;
      load = /* @__PURE__ */ __name(function load2() {
        if (loaded || !processOk(globalThis.process)) {
          return;
        }
        loaded = true;
        emitter.count += 1;
        signals = signals.filter(function(sig) {
          try {
            process51.on(sig, sigListeners[sig]);
            return true;
          } catch (er) {
            return false;
          }
        });
        process51.emit = processEmit;
        process51.reallyExit = processReallyExit;
      }, "load");
      module2.exports.load = load;
      originalProcessReallyExit = process51.reallyExit;
      processReallyExit = /* @__PURE__ */ __name(function processReallyExit2(code2) {
        if (!processOk(globalThis.process)) {
          return;
        }
        process51.exitCode = code2 || /* istanbul ignore next */
        0;
        emit("exit", process51.exitCode, null);
        emit("afterexit", process51.exitCode, null);
        originalProcessReallyExit.call(process51, process51.exitCode);
      }, "processReallyExit");
      originalProcessEmit = process51.emit;
      processEmit = /* @__PURE__ */ __name(function processEmit2(ev, arg) {
        if (ev === "exit" && processOk(globalThis.process)) {
          if (arg !== void 0) {
            process51.exitCode = arg;
          }
          var ret = originalProcessEmit.apply(this, arguments);
          emit("exit", process51.exitCode, null);
          emit("afterexit", process51.exitCode, null);
          return ret;
        } else {
          return originalProcessEmit.apply(this, arguments);
        }
      }, "processEmit");
    }
    var assert3;
    var signals;
    var isWin;
    var EE3;
    var emitter;
    var unload;
    var emit;
    var sigListeners;
    var loaded;
    var load;
    var originalProcessReallyExit;
    var processReallyExit;
    var originalProcessEmit;
    var processEmit;
  }
});

// node_modules/stack-utils/node_modules/escape-string-regexp/index.js
var require_escape_string_regexp = __commonJS({
  "node_modules/stack-utils/node_modules/escape-string-regexp/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var matchOperatorsRegex = /[|\\{}()[\]^$+*?.-]/g;
    module2.exports = (string) => {
      if (typeof string !== "string") {
        throw new TypeError("Expected a string");
      }
      return string.replace(matchOperatorsRegex, "\\$&");
    };
  }
});

// node_modules/stack-utils/index.js
var require_stack_utils = __commonJS({
  "node_modules/stack-utils/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var escapeStringRegexp = require_escape_string_regexp();
    var cwd7 = typeof process === "object" && process && typeof process.cwd === "function" ? process.cwd() : ".";
    var natives = [].concat(
      __require("module").builtinModules,
      "bootstrap_node",
      "node"
    ).map((n2) => new RegExp(`(?:\\((?:node:)?${n2}(?:\\.js)?:\\d+:\\d+\\)$|^\\s*at (?:node:)?${n2}(?:\\.js)?:\\d+:\\d+$)`));
    natives.push(
      /\((?:node:)?internal\/[^:]+:\d+:\d+\)$/,
      /\s*at (?:node:)?internal\/[^:]+:\d+:\d+$/,
      /\/\.node-spawn-wrap-\w+-\w+\/node:\d+:\d+\)?$/
    );
    var StackUtils2 = class _StackUtils {
      static {
        __name(this, "StackUtils");
      }
      constructor(opts) {
        opts = {
          ignoredPackages: [],
          ...opts
        };
        if ("internals" in opts === false) {
          opts.internals = _StackUtils.nodeInternals();
        }
        if ("cwd" in opts === false) {
          opts.cwd = cwd7;
        }
        this._cwd = opts.cwd.replace(/\\/g, "/");
        this._internals = [].concat(
          opts.internals,
          ignoredPackagesRegExp(opts.ignoredPackages)
        );
        this._wrapCallSite = opts.wrapCallSite || false;
      }
      static nodeInternals() {
        return [...natives];
      }
      clean(stack, indent = 0) {
        indent = " ".repeat(indent);
        if (!Array.isArray(stack)) {
          stack = stack.split("\n");
        }
        if (!/^\s*at /.test(stack[0]) && /^\s*at /.test(stack[1])) {
          stack = stack.slice(1);
        }
        let outdent = false;
        let lastNonAtLine = null;
        const result = [];
        stack.forEach((st) => {
          st = st.replace(/\\/g, "/");
          if (this._internals.some((internal) => internal.test(st))) {
            return;
          }
          const isAtLine = /^\s*at /.test(st);
          if (outdent) {
            st = st.trimEnd().replace(/^(\s+)at /, "$1");
          } else {
            st = st.trim();
            if (isAtLine) {
              st = st.slice(3);
            }
          }
          st = st.replace(`${this._cwd}/`, "");
          if (st) {
            if (isAtLine) {
              if (lastNonAtLine) {
                result.push(lastNonAtLine);
                lastNonAtLine = null;
              }
              result.push(st);
            } else {
              outdent = true;
              lastNonAtLine = st;
            }
          }
        });
        return result.map((line) => `${indent}${line}
`).join("");
      }
      captureString(limit2, fn = this.captureString) {
        if (typeof limit2 === "function") {
          fn = limit2;
          limit2 = Infinity;
        }
        const { stackTraceLimit } = Error;
        if (limit2) {
          Error.stackTraceLimit = limit2;
        }
        const obj = {};
        Error.captureStackTrace(obj, fn);
        const { stack } = obj;
        Error.stackTraceLimit = stackTraceLimit;
        return this.clean(stack);
      }
      capture(limit2, fn = this.capture) {
        if (typeof limit2 === "function") {
          fn = limit2;
          limit2 = Infinity;
        }
        const { prepareStackTrace, stackTraceLimit } = Error;
        Error.prepareStackTrace = (obj2, site) => {
          if (this._wrapCallSite) {
            return site.map(this._wrapCallSite);
          }
          return site;
        };
        if (limit2) {
          Error.stackTraceLimit = limit2;
        }
        const obj = {};
        Error.captureStackTrace(obj, fn);
        const { stack } = obj;
        Object.assign(Error, { prepareStackTrace, stackTraceLimit });
        return stack;
      }
      at(fn = this.at) {
        const [site] = this.capture(1, fn);
        if (!site) {
          return {};
        }
        const res = {
          line: site.getLineNumber(),
          column: site.getColumnNumber()
        };
        setFile(res, site.getFileName(), this._cwd);
        if (site.isConstructor()) {
          Object.defineProperty(res, "constructor", {
            value: true,
            configurable: true
          });
        }
        if (site.isEval()) {
          res.evalOrigin = site.getEvalOrigin();
        }
        if (site.isNative()) {
          res.native = true;
        }
        let typename;
        try {
          typename = site.getTypeName();
        } catch (_) {
        }
        if (typename && typename !== "Object" && typename !== "[object Object]") {
          res.type = typename;
        }
        const fname = site.getFunctionName();
        if (fname) {
          res.function = fname;
        }
        const meth = site.getMethodName();
        if (meth && fname !== meth) {
          res.method = meth;
        }
        return res;
      }
      parseLine(line) {
        const match2 = line && line.match(re2);
        if (!match2) {
          return null;
        }
        const ctor = match2[1] === "new";
        let fname = match2[2];
        const evalOrigin = match2[3];
        const evalFile = match2[4];
        const evalLine = Number(match2[5]);
        const evalCol = Number(match2[6]);
        let file = match2[7];
        const lnum = match2[8];
        const col = match2[9];
        const native = match2[10] === "native";
        const closeParen = match2[11] === ")";
        let method;
        const res = {};
        if (lnum) {
          res.line = Number(lnum);
        }
        if (col) {
          res.column = Number(col);
        }
        if (closeParen && file) {
          let closes = 0;
          for (let i = file.length - 1; i > 0; i--) {
            if (file.charAt(i) === ")") {
              closes++;
            } else if (file.charAt(i) === "(" && file.charAt(i - 1) === " ") {
              closes--;
              if (closes === -1 && file.charAt(i - 1) === " ") {
                const before = file.slice(0, i - 1);
                const after = file.slice(i + 1);
                file = after;
                fname += ` (${before}`;
                break;
              }
            }
          }
        }
        if (fname) {
          const methodMatch = fname.match(methodRe);
          if (methodMatch) {
            fname = methodMatch[1];
            method = methodMatch[2];
          }
        }
        setFile(res, file, this._cwd);
        if (ctor) {
          Object.defineProperty(res, "constructor", {
            value: true,
            configurable: true
          });
        }
        if (evalOrigin) {
          res.evalOrigin = evalOrigin;
          res.evalLine = evalLine;
          res.evalColumn = evalCol;
          res.evalFile = evalFile && evalFile.replace(/\\/g, "/");
        }
        if (native) {
          res.native = true;
        }
        if (fname) {
          res.function = fname;
        }
        if (method && fname !== method) {
          res.method = method;
        }
        return res;
      }
    };
    function setFile(result, filename, cwd8) {
      if (filename) {
        filename = filename.replace(/\\/g, "/");
        if (filename.startsWith(`${cwd8}/`)) {
          filename = filename.slice(cwd8.length + 1);
        }
        result.file = filename;
      }
    }
    __name(setFile, "setFile");
    function ignoredPackagesRegExp(ignoredPackages) {
      if (ignoredPackages.length === 0) {
        return [];
      }
      const packages = ignoredPackages.map((mod2) => escapeStringRegexp(mod2));
      return new RegExp(`[/\\\\]node_modules[/\\\\](?:${packages.join("|")})[/\\\\][^:]+:\\d+:\\d+`);
    }
    __name(ignoredPackagesRegExp, "ignoredPackagesRegExp");
    var re2 = new RegExp(
      "^(?:\\s*at )?(?:(new) )?(?:(.*?) \\()?(?:eval at ([^ ]+) \\((.+?):(\\d+):(\\d+)\\), )?(?:(.+?):(\\d+):(\\d+)|(native))(\\)?)$"
    );
    var methodRe = /^(.*?) \[as (.*?)\]$/;
    module2.exports = StackUtils2;
  }
});

// node_modules/undici/lib/core/symbols.js
var require_symbols = __commonJS({
  "node_modules/undici/lib/core/symbols.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      kClose: Symbol("close"),
      kDestroy: Symbol("destroy"),
      kDispatch: Symbol("dispatch"),
      kUrl: Symbol("url"),
      kWriting: Symbol("writing"),
      kResuming: Symbol("resuming"),
      kQueue: Symbol("queue"),
      kConnect: Symbol("connect"),
      kConnecting: Symbol("connecting"),
      kKeepAliveDefaultTimeout: Symbol("default keep alive timeout"),
      kKeepAliveMaxTimeout: Symbol("max keep alive timeout"),
      kKeepAliveTimeoutThreshold: Symbol("keep alive timeout threshold"),
      kKeepAliveTimeoutValue: Symbol("keep alive timeout"),
      kKeepAlive: Symbol("keep alive"),
      kHeadersTimeout: Symbol("headers timeout"),
      kBodyTimeout: Symbol("body timeout"),
      kServerName: Symbol("server name"),
      kLocalAddress: Symbol("local address"),
      kHost: Symbol("host"),
      kNoRef: Symbol("no ref"),
      kBodyUsed: Symbol("used"),
      kBody: Symbol("abstracted request body"),
      kRunning: Symbol("running"),
      kBlocking: Symbol("blocking"),
      kPending: Symbol("pending"),
      kSize: Symbol("size"),
      kBusy: Symbol("busy"),
      kQueued: Symbol("queued"),
      kFree: Symbol("free"),
      kConnected: Symbol("connected"),
      kClosed: Symbol("closed"),
      kNeedDrain: Symbol("need drain"),
      kReset: Symbol("reset"),
      kDestroyed: Symbol.for("nodejs.stream.destroyed"),
      kResume: Symbol("resume"),
      kOnError: Symbol("on error"),
      kMaxHeadersSize: Symbol("max headers size"),
      kRunningIdx: Symbol("running index"),
      kPendingIdx: Symbol("pending index"),
      kError: Symbol("error"),
      kClients: Symbol("clients"),
      kClient: Symbol("client"),
      kParser: Symbol("parser"),
      kOnDestroyed: Symbol("destroy callbacks"),
      kPipelining: Symbol("pipelining"),
      kSocket: Symbol("socket"),
      kHostHeader: Symbol("host header"),
      kConnector: Symbol("connector"),
      kStrictContentLength: Symbol("strict content length"),
      kMaxRedirections: Symbol("maxRedirections"),
      kMaxRequests: Symbol("maxRequestsPerClient"),
      kProxy: Symbol("proxy agent options"),
      kCounter: Symbol("socket request counter"),
      kMaxResponseSize: Symbol("max response size"),
      kHTTP2Session: Symbol("http2Session"),
      kHTTP2SessionState: Symbol("http2Session state"),
      kRetryHandlerDefaultRetry: Symbol("retry agent default retry"),
      kConstruct: Symbol("constructable"),
      kListeners: Symbol("listeners"),
      kHTTPContext: Symbol("http context"),
      kMaxConcurrentStreams: Symbol("max concurrent streams"),
      kNoProxyAgent: Symbol("no proxy agent"),
      kHttpProxyAgent: Symbol("http proxy agent"),
      kHttpsProxyAgent: Symbol("https proxy agent")
    };
  }
});

// node_modules/undici/lib/util/timers.js
var require_timers = __commonJS({
  "node_modules/undici/lib/util/timers.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var fastNow = 0;
    var RESOLUTION_MS = 1e3;
    var TICK_MS = (RESOLUTION_MS >> 1) - 1;
    var fastNowTimeout;
    var kFastTimer = Symbol("kFastTimer");
    var fastTimers = [];
    var NOT_IN_LIST = -2;
    var TO_BE_CLEARED = -1;
    var PENDING2 = 0;
    var ACTIVE = 1;
    function onTick() {
      fastNow += TICK_MS;
      let idx = 0;
      let len = fastTimers.length;
      while (idx < len) {
        const timer = fastTimers[idx];
        if (timer._state === PENDING2) {
          timer._idleStart = fastNow - TICK_MS;
          timer._state = ACTIVE;
        } else if (timer._state === ACTIVE && fastNow >= timer._idleStart + timer._idleTimeout) {
          timer._state = TO_BE_CLEARED;
          timer._idleStart = -1;
          timer._onTimeout(timer._timerArg);
        }
        if (timer._state === TO_BE_CLEARED) {
          timer._state = NOT_IN_LIST;
          if (--len !== 0) {
            fastTimers[idx] = fastTimers[len];
          }
        } else {
          ++idx;
        }
      }
      fastTimers.length = len;
      if (fastTimers.length !== 0) {
        refreshTimeout();
      }
    }
    __name(onTick, "onTick");
    function refreshTimeout() {
      if (fastNowTimeout?.refresh) {
        fastNowTimeout.refresh();
      } else {
        clearTimeout(fastNowTimeout);
        fastNowTimeout = setTimeout(onTick, TICK_MS);
        fastNowTimeout?.unref();
      }
    }
    __name(refreshTimeout, "refreshTimeout");
    var FastTimer = class {
      static {
        __name(this, "FastTimer");
      }
      [kFastTimer] = true;
      /**
       * The state of the timer, which can be one of the following:
       * - NOT_IN_LIST (-2)
       * - TO_BE_CLEARED (-1)
       * - PENDING (0)
       * - ACTIVE (1)
       *
       * @type {-2|-1|0|1}
       * @private
       */
      _state = NOT_IN_LIST;
      /**
       * The number of milliseconds to wait before calling the callback.
       *
       * @type {number}
       * @private
       */
      _idleTimeout = -1;
      /**
       * The time in milliseconds when the timer was started. This value is used to
       * calculate when the timer should expire.
       *
       * @type {number}
       * @default -1
       * @private
       */
      _idleStart = -1;
      /**
       * The function to be executed when the timer expires.
       * @type {Function}
       * @private
       */
      _onTimeout;
      /**
       * The argument to be passed to the callback when the timer expires.
       *
       * @type {*}
       * @private
       */
      _timerArg;
      /**
       * @constructor
       * @param {Function} callback A function to be executed after the timer
       * expires.
       * @param {number} delay The time, in milliseconds that the timer should wait
       * before the specified function or code is executed.
       * @param {*} arg
       */
      constructor(callback, delay4, arg) {
        this._onTimeout = callback;
        this._idleTimeout = delay4;
        this._timerArg = arg;
        this.refresh();
      }
      /**
       * Sets the timer's start time to the current time, and reschedules the timer
       * to call its callback at the previously specified duration adjusted to the
       * current time.
       * Using this on a timer that has already called its callback will reactivate
       * the timer.
       *
       * @returns {void}
       */
      refresh() {
        if (this._state === NOT_IN_LIST) {
          fastTimers.push(this);
        }
        if (!fastNowTimeout || fastTimers.length === 1) {
          refreshTimeout();
        }
        this._state = PENDING2;
      }
      /**
       * The `clear` method cancels the timer, preventing it from executing.
       *
       * @returns {void}
       * @private
       */
      clear() {
        this._state = TO_BE_CLEARED;
        this._idleStart = -1;
      }
    };
    module2.exports = {
      /**
       * The setTimeout() method sets a timer which executes a function once the
       * timer expires.
       * @param {Function} callback A function to be executed after the timer
       * expires.
       * @param {number} delay The time, in milliseconds that the timer should
       * wait before the specified function or code is executed.
       * @param {*} [arg] An optional argument to be passed to the callback function
       * when the timer expires.
       * @returns {NodeJS.Timeout|FastTimer}
       */
      setTimeout(callback, delay4, arg) {
        return delay4 <= RESOLUTION_MS ? setTimeout(callback, delay4, arg) : new FastTimer(callback, delay4, arg);
      },
      /**
       * The clearTimeout method cancels an instantiated Timer previously created
       * by calling setTimeout.
       *
       * @param {NodeJS.Timeout|FastTimer} timeout
       */
      clearTimeout(timeout2) {
        if (timeout2[kFastTimer]) {
          timeout2.clear();
        } else {
          clearTimeout(timeout2);
        }
      },
      /**
       * The setFastTimeout() method sets a fastTimer which executes a function once
       * the timer expires.
       * @param {Function} callback A function to be executed after the timer
       * expires.
       * @param {number} delay The time, in milliseconds that the timer should
       * wait before the specified function or code is executed.
       * @param {*} [arg] An optional argument to be passed to the callback function
       * when the timer expires.
       * @returns {FastTimer}
       */
      setFastTimeout(callback, delay4, arg) {
        return new FastTimer(callback, delay4, arg);
      },
      /**
       * The clearTimeout method cancels an instantiated FastTimer previously
       * created by calling setFastTimeout.
       *
       * @param {FastTimer} timeout
       */
      clearFastTimeout(timeout2) {
        timeout2.clear();
      },
      /**
       * The now method returns the value of the internal fast timer clock.
       *
       * @returns {number}
       */
      now() {
        return fastNow;
      },
      /**
       * Trigger the onTick function to process the fastTimers array.
       * Exported for testing purposes only.
       * Marking as deprecated to discourage any use outside of testing.
       * @deprecated
       * @param {number} [delay=0] The delay in milliseconds to add to the now value.
       */
      tick(delay4 = 0) {
        fastNow += delay4 - RESOLUTION_MS + 1;
        onTick();
        onTick();
      },
      /**
       * Reset FastTimers.
       * Exported for testing purposes only.
       * Marking as deprecated to discourage any use outside of testing.
       * @deprecated
       */
      reset() {
        fastNow = 0;
        fastTimers.length = 0;
        clearTimeout(fastNowTimeout);
        fastNowTimeout = null;
      },
      /**
       * Exporting for testing purposes only.
       * Marking as deprecated to discourage any use outside of testing.
       * @deprecated
       */
      kFastTimer
    };
  }
});

// node_modules/undici/lib/core/errors.js
var require_errors = __commonJS({
  "node_modules/undici/lib/core/errors.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var UndiciError = class extends Error {
      static {
        __name(this, "UndiciError");
      }
      constructor(message, options2) {
        super(message, options2);
        this.name = "UndiciError";
        this.code = "UND_ERR";
      }
    };
    var ConnectTimeoutError = class extends UndiciError {
      static {
        __name(this, "ConnectTimeoutError");
      }
      constructor(message) {
        super(message);
        this.name = "ConnectTimeoutError";
        this.message = message || "Connect Timeout Error";
        this.code = "UND_ERR_CONNECT_TIMEOUT";
      }
    };
    var HeadersTimeoutError = class extends UndiciError {
      static {
        __name(this, "HeadersTimeoutError");
      }
      constructor(message) {
        super(message);
        this.name = "HeadersTimeoutError";
        this.message = message || "Headers Timeout Error";
        this.code = "UND_ERR_HEADERS_TIMEOUT";
      }
    };
    var HeadersOverflowError = class extends UndiciError {
      static {
        __name(this, "HeadersOverflowError");
      }
      constructor(message) {
        super(message);
        this.name = "HeadersOverflowError";
        this.message = message || "Headers Overflow Error";
        this.code = "UND_ERR_HEADERS_OVERFLOW";
      }
    };
    var BodyTimeoutError = class extends UndiciError {
      static {
        __name(this, "BodyTimeoutError");
      }
      constructor(message) {
        super(message);
        this.name = "BodyTimeoutError";
        this.message = message || "Body Timeout Error";
        this.code = "UND_ERR_BODY_TIMEOUT";
      }
    };
    var ResponseStatusCodeError = class extends UndiciError {
      static {
        __name(this, "ResponseStatusCodeError");
      }
      constructor(message, statusCode, headers, body) {
        super(message);
        this.name = "ResponseStatusCodeError";
        this.message = message || "Response Status Code Error";
        this.code = "UND_ERR_RESPONSE_STATUS_CODE";
        this.body = body;
        this.status = statusCode;
        this.statusCode = statusCode;
        this.headers = headers;
      }
    };
    var InvalidArgumentError = class extends UndiciError {
      static {
        __name(this, "InvalidArgumentError");
      }
      constructor(message) {
        super(message);
        this.name = "InvalidArgumentError";
        this.message = message || "Invalid Argument Error";
        this.code = "UND_ERR_INVALID_ARG";
      }
    };
    var InvalidReturnValueError = class extends UndiciError {
      static {
        __name(this, "InvalidReturnValueError");
      }
      constructor(message) {
        super(message);
        this.name = "InvalidReturnValueError";
        this.message = message || "Invalid Return Value Error";
        this.code = "UND_ERR_INVALID_RETURN_VALUE";
      }
    };
    var AbortError2 = class extends UndiciError {
      static {
        __name(this, "AbortError");
      }
      constructor(message) {
        super(message);
        this.name = "AbortError";
        this.message = message || "The operation was aborted";
      }
    };
    var RequestAbortedError = class extends AbortError2 {
      static {
        __name(this, "RequestAbortedError");
      }
      constructor(message) {
        super(message);
        this.name = "AbortError";
        this.message = message || "Request aborted";
        this.code = "UND_ERR_ABORTED";
      }
    };
    var InformationalError = class extends UndiciError {
      static {
        __name(this, "InformationalError");
      }
      constructor(message) {
        super(message);
        this.name = "InformationalError";
        this.message = message || "Request information";
        this.code = "UND_ERR_INFO";
      }
    };
    var RequestContentLengthMismatchError = class extends UndiciError {
      static {
        __name(this, "RequestContentLengthMismatchError");
      }
      constructor(message) {
        super(message);
        this.name = "RequestContentLengthMismatchError";
        this.message = message || "Request body length does not match content-length header";
        this.code = "UND_ERR_REQ_CONTENT_LENGTH_MISMATCH";
      }
    };
    var ResponseContentLengthMismatchError = class extends UndiciError {
      static {
        __name(this, "ResponseContentLengthMismatchError");
      }
      constructor(message) {
        super(message);
        this.name = "ResponseContentLengthMismatchError";
        this.message = message || "Response body length does not match content-length header";
        this.code = "UND_ERR_RES_CONTENT_LENGTH_MISMATCH";
      }
    };
    var ClientDestroyedError = class extends UndiciError {
      static {
        __name(this, "ClientDestroyedError");
      }
      constructor(message) {
        super(message);
        this.name = "ClientDestroyedError";
        this.message = message || "The client is destroyed";
        this.code = "UND_ERR_DESTROYED";
      }
    };
    var ClientClosedError = class extends UndiciError {
      static {
        __name(this, "ClientClosedError");
      }
      constructor(message) {
        super(message);
        this.name = "ClientClosedError";
        this.message = message || "The client is closed";
        this.code = "UND_ERR_CLOSED";
      }
    };
    var SocketError = class extends UndiciError {
      static {
        __name(this, "SocketError");
      }
      constructor(message, socket) {
        super(message);
        this.name = "SocketError";
        this.message = message || "Socket error";
        this.code = "UND_ERR_SOCKET";
        this.socket = socket;
      }
    };
    var NotSupportedError = class extends UndiciError {
      static {
        __name(this, "NotSupportedError");
      }
      constructor(message) {
        super(message);
        this.name = "NotSupportedError";
        this.message = message || "Not supported error";
        this.code = "UND_ERR_NOT_SUPPORTED";
      }
    };
    var BalancedPoolMissingUpstreamError = class extends UndiciError {
      static {
        __name(this, "BalancedPoolMissingUpstreamError");
      }
      constructor(message) {
        super(message);
        this.name = "MissingUpstreamError";
        this.message = message || "No upstream has been added to the BalancedPool";
        this.code = "UND_ERR_BPL_MISSING_UPSTREAM";
      }
    };
    var HTTPParserError = class extends Error {
      static {
        __name(this, "HTTPParserError");
      }
      constructor(message, code2, data) {
        super(message);
        this.name = "HTTPParserError";
        this.code = code2 ? `HPE_${code2}` : void 0;
        this.data = data ? data.toString() : void 0;
      }
    };
    var ResponseExceededMaxSizeError = class extends UndiciError {
      static {
        __name(this, "ResponseExceededMaxSizeError");
      }
      constructor(message) {
        super(message);
        this.name = "ResponseExceededMaxSizeError";
        this.message = message || "Response content exceeded max size";
        this.code = "UND_ERR_RES_EXCEEDED_MAX_SIZE";
      }
    };
    var RequestRetryError = class extends UndiciError {
      static {
        __name(this, "RequestRetryError");
      }
      constructor(message, code2, { headers, data }) {
        super(message);
        this.name = "RequestRetryError";
        this.message = message || "Request retry error";
        this.code = "UND_ERR_REQ_RETRY";
        this.statusCode = code2;
        this.data = data;
        this.headers = headers;
      }
    };
    var ResponseError = class extends UndiciError {
      static {
        __name(this, "ResponseError");
      }
      constructor(message, code2, { headers, body }) {
        super(message);
        this.name = "ResponseError";
        this.message = message || "Response error";
        this.code = "UND_ERR_RESPONSE";
        this.statusCode = code2;
        this.body = body;
        this.headers = headers;
      }
    };
    var SecureProxyConnectionError = class extends UndiciError {
      static {
        __name(this, "SecureProxyConnectionError");
      }
      constructor(cause, message, options2 = {}) {
        super(message, { cause, ...options2 });
        this.name = "SecureProxyConnectionError";
        this.message = message || "Secure Proxy Connection failed";
        this.code = "UND_ERR_PRX_TLS";
        this.cause = cause;
      }
    };
    module2.exports = {
      AbortError: AbortError2,
      HTTPParserError,
      UndiciError,
      HeadersTimeoutError,
      HeadersOverflowError,
      BodyTimeoutError,
      RequestContentLengthMismatchError,
      ConnectTimeoutError,
      ResponseStatusCodeError,
      InvalidArgumentError,
      InvalidReturnValueError,
      RequestAbortedError,
      ClientDestroyedError,
      ClientClosedError,
      InformationalError,
      SocketError,
      NotSupportedError,
      ResponseContentLengthMismatchError,
      BalancedPoolMissingUpstreamError,
      ResponseExceededMaxSizeError,
      RequestRetryError,
      ResponseError,
      SecureProxyConnectionError
    };
  }
});

// node_modules/undici/lib/core/constants.js
var require_constants3 = __commonJS({
  "node_modules/undici/lib/core/constants.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var wellknownHeaderNames = (
      /** @type {const} */
      [
        "Accept",
        "Accept-Encoding",
        "Accept-Language",
        "Accept-Ranges",
        "Access-Control-Allow-Credentials",
        "Access-Control-Allow-Headers",
        "Access-Control-Allow-Methods",
        "Access-Control-Allow-Origin",
        "Access-Control-Expose-Headers",
        "Access-Control-Max-Age",
        "Access-Control-Request-Headers",
        "Access-Control-Request-Method",
        "Age",
        "Allow",
        "Alt-Svc",
        "Alt-Used",
        "Authorization",
        "Cache-Control",
        "Clear-Site-Data",
        "Connection",
        "Content-Disposition",
        "Content-Encoding",
        "Content-Language",
        "Content-Length",
        "Content-Location",
        "Content-Range",
        "Content-Security-Policy",
        "Content-Security-Policy-Report-Only",
        "Content-Type",
        "Cookie",
        "Cross-Origin-Embedder-Policy",
        "Cross-Origin-Opener-Policy",
        "Cross-Origin-Resource-Policy",
        "Date",
        "Device-Memory",
        "Downlink",
        "ECT",
        "ETag",
        "Expect",
        "Expect-CT",
        "Expires",
        "Forwarded",
        "From",
        "Host",
        "If-Match",
        "If-Modified-Since",
        "If-None-Match",
        "If-Range",
        "If-Unmodified-Since",
        "Keep-Alive",
        "Last-Modified",
        "Link",
        "Location",
        "Max-Forwards",
        "Origin",
        "Permissions-Policy",
        "Pragma",
        "Proxy-Authenticate",
        "Proxy-Authorization",
        "RTT",
        "Range",
        "Referer",
        "Referrer-Policy",
        "Refresh",
        "Retry-After",
        "Sec-WebSocket-Accept",
        "Sec-WebSocket-Extensions",
        "Sec-WebSocket-Key",
        "Sec-WebSocket-Protocol",
        "Sec-WebSocket-Version",
        "Server",
        "Server-Timing",
        "Service-Worker-Allowed",
        "Service-Worker-Navigation-Preload",
        "Set-Cookie",
        "SourceMap",
        "Strict-Transport-Security",
        "Supports-Loading-Mode",
        "TE",
        "Timing-Allow-Origin",
        "Trailer",
        "Transfer-Encoding",
        "Upgrade",
        "Upgrade-Insecure-Requests",
        "User-Agent",
        "Vary",
        "Via",
        "WWW-Authenticate",
        "X-Content-Type-Options",
        "X-DNS-Prefetch-Control",
        "X-Frame-Options",
        "X-Permitted-Cross-Domain-Policies",
        "X-Powered-By",
        "X-Requested-With",
        "X-XSS-Protection"
      ]
    );
    var headerNameLowerCasedRecord = {};
    Object.setPrototypeOf(headerNameLowerCasedRecord, null);
    var wellknownHeaderNameBuffers = {};
    Object.setPrototypeOf(wellknownHeaderNameBuffers, null);
    function getHeaderNameAsBuffer(header) {
      let buffer = wellknownHeaderNameBuffers[header];
      if (buffer === void 0) {
        buffer = Buffer.from(header);
      }
      return buffer;
    }
    __name(getHeaderNameAsBuffer, "getHeaderNameAsBuffer");
    for (let i = 0; i < wellknownHeaderNames.length; ++i) {
      const key = wellknownHeaderNames[i];
      const lowerCasedKey = key.toLowerCase();
      headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = lowerCasedKey;
    }
    module2.exports = {
      wellknownHeaderNames,
      headerNameLowerCasedRecord,
      getHeaderNameAsBuffer
    };
  }
});

// node_modules/undici/lib/core/tree.js
var require_tree = __commonJS({
  "node_modules/undici/lib/core/tree.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      wellknownHeaderNames,
      headerNameLowerCasedRecord
    } = require_constants3();
    var TstNode = class _TstNode {
      static {
        __name(this, "TstNode");
      }
      /** @type {any} */
      value = null;
      /** @type {null | TstNode} */
      left = null;
      /** @type {null | TstNode} */
      middle = null;
      /** @type {null | TstNode} */
      right = null;
      /** @type {number} */
      code;
      /**
       * @param {string} key
       * @param {any} value
       * @param {number} index
       */
      constructor(key, value, index) {
        if (index === void 0 || index >= key.length) {
          throw new TypeError("Unreachable");
        }
        const code2 = this.code = key.charCodeAt(index);
        if (code2 > 127) {
          throw new TypeError("key must be ascii string");
        }
        if (key.length !== ++index) {
          this.middle = new _TstNode(key, value, index);
        } else {
          this.value = value;
        }
      }
      /**
       * @param {string} key
       * @param {any} value
       * @returns {void}
       */
      add(key, value) {
        const length = key.length;
        if (length === 0) {
          throw new TypeError("Unreachable");
        }
        let index = 0;
        let node = this;
        while (true) {
          const code2 = key.charCodeAt(index);
          if (code2 > 127) {
            throw new TypeError("key must be ascii string");
          }
          if (node.code === code2) {
            if (length === ++index) {
              node.value = value;
              break;
            } else if (node.middle !== null) {
              node = node.middle;
            } else {
              node.middle = new _TstNode(key, value, index);
              break;
            }
          } else if (node.code < code2) {
            if (node.left !== null) {
              node = node.left;
            } else {
              node.left = new _TstNode(key, value, index);
              break;
            }
          } else if (node.right !== null) {
            node = node.right;
          } else {
            node.right = new _TstNode(key, value, index);
            break;
          }
        }
      }
      /**
       * @param {Uint8Array} key
       * @returns {TstNode | null}
       */
      search(key) {
        const keylength = key.length;
        let index = 0;
        let node = this;
        while (node !== null && index < keylength) {
          let code2 = key[index];
          if (code2 <= 90 && code2 >= 65) {
            code2 |= 32;
          }
          while (node !== null) {
            if (code2 === node.code) {
              if (keylength === ++index) {
                return node;
              }
              node = node.middle;
              break;
            }
            node = node.code < code2 ? node.left : node.right;
          }
        }
        return null;
      }
    };
    var TernarySearchTree = class {
      static {
        __name(this, "TernarySearchTree");
      }
      /** @type {TstNode | null} */
      node = null;
      /**
       * @param {string} key
       * @param {any} value
       * @returns {void}
       * */
      insert(key, value) {
        if (this.node === null) {
          this.node = new TstNode(key, value, 0);
        } else {
          this.node.add(key, value);
        }
      }
      /**
       * @param {Uint8Array} key
       * @returns {any}
       */
      lookup(key) {
        return this.node?.search(key)?.value ?? null;
      }
    };
    var tree = new TernarySearchTree();
    for (let i = 0; i < wellknownHeaderNames.length; ++i) {
      const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]];
      tree.insert(key, key);
    }
    module2.exports = {
      TernarySearchTree,
      tree
    };
  }
});

// node_modules/undici/lib/core/util.js
var require_util = __commonJS({
  "node_modules/undici/lib/core/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert3 = __require("node:assert");
    var { kDestroyed, kBodyUsed, kListeners, kBody } = require_symbols();
    var { IncomingMessage } = __require("node:http");
    var stream2 = __require("node:stream");
    var net2 = __require("node:net");
    var { stringify: stringify5 } = __require("node:querystring");
    var { EventEmitter: EE3 } = __require("node:events");
    var timers = require_timers();
    var { InvalidArgumentError, ConnectTimeoutError } = require_errors();
    var { headerNameLowerCasedRecord } = require_constants3();
    var { tree } = require_tree();
    var [nodeMajor, nodeMinor] = process.versions.node.split(".", 2).map((v) => Number(v));
    var BodyAsyncIterable = class {
      static {
        __name(this, "BodyAsyncIterable");
      }
      constructor(body) {
        this[kBody] = body;
        this[kBodyUsed] = false;
      }
      async *[Symbol.asyncIterator]() {
        assert3(!this[kBodyUsed], "disturbed");
        this[kBodyUsed] = true;
        yield* this[kBody];
      }
    };
    function noop6() {
    }
    __name(noop6, "noop");
    function wrapRequestBody(body) {
      if (isStream2(body)) {
        if (bodyLength(body) === 0) {
          body.on("data", function() {
            assert3(false);
          });
        }
        if (typeof body.readableDidRead !== "boolean") {
          body[kBodyUsed] = false;
          EE3.prototype.on.call(body, "data", function() {
            this[kBodyUsed] = true;
          });
        }
        return body;
      } else if (body && typeof body.pipeTo === "function") {
        return new BodyAsyncIterable(body);
      } else if (body && typeof body !== "string" && !ArrayBuffer.isView(body) && isIterable(body)) {
        return new BodyAsyncIterable(body);
      } else {
        return body;
      }
    }
    __name(wrapRequestBody, "wrapRequestBody");
    function isStream2(obj) {
      return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj.on === "function";
    }
    __name(isStream2, "isStream");
    function isBlobLike2(object) {
      if (object === null) {
        return false;
      } else if (object instanceof Blob) {
        return true;
      } else if (typeof object !== "object") {
        return false;
      } else {
        const sTag = object[Symbol.toStringTag];
        return (sTag === "Blob" || sTag === "File") && ("stream" in object && typeof object.stream === "function" || "arrayBuffer" in object && typeof object.arrayBuffer === "function");
      }
    }
    __name(isBlobLike2, "isBlobLike");
    function pathHasQueryOrFragment(url2) {
      return url2.includes("?") || url2.includes("#");
    }
    __name(pathHasQueryOrFragment, "pathHasQueryOrFragment");
    function serializePathWithQuery(url2, queryParams) {
      if (pathHasQueryOrFragment(url2)) {
        throw new Error('Query params cannot be passed when url already contains "?" or "#".');
      }
      const stringified = stringify5(queryParams);
      if (stringified) {
        url2 += "?" + stringified;
      }
      return url2;
    }
    __name(serializePathWithQuery, "serializePathWithQuery");
    function isValidPort(port) {
      const value = parseInt(port, 10);
      return value === Number(port) && value >= 0 && value <= 65535;
    }
    __name(isValidPort, "isValidPort");
    function isHttpOrHttpsPrefixed(value) {
      return value != null && value[0] === "h" && value[1] === "t" && value[2] === "t" && value[3] === "p" && (value[4] === ":" || value[4] === "s" && value[5] === ":");
    }
    __name(isHttpOrHttpsPrefixed, "isHttpOrHttpsPrefixed");
    function parseURL(url2) {
      if (typeof url2 === "string") {
        url2 = new URL(url2);
        if (!isHttpOrHttpsPrefixed(url2.origin || url2.protocol)) {
          throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
        }
        return url2;
      }
      if (!url2 || typeof url2 !== "object") {
        throw new InvalidArgumentError("Invalid URL: The URL argument must be a non-null object.");
      }
      if (!(url2 instanceof URL)) {
        if (url2.port != null && url2.port !== "" && isValidPort(url2.port) === false) {
          throw new InvalidArgumentError("Invalid URL: port must be a valid integer or a string representation of an integer.");
        }
        if (url2.path != null && typeof url2.path !== "string") {
          throw new InvalidArgumentError("Invalid URL path: the path must be a string or null/undefined.");
        }
        if (url2.pathname != null && typeof url2.pathname !== "string") {
          throw new InvalidArgumentError("Invalid URL pathname: the pathname must be a string or null/undefined.");
        }
        if (url2.hostname != null && typeof url2.hostname !== "string") {
          throw new InvalidArgumentError("Invalid URL hostname: the hostname must be a string or null/undefined.");
        }
        if (url2.origin != null && typeof url2.origin !== "string") {
          throw new InvalidArgumentError("Invalid URL origin: the origin must be a string or null/undefined.");
        }
        if (!isHttpOrHttpsPrefixed(url2.origin || url2.protocol)) {
          throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
        }
        const port = url2.port != null ? url2.port : url2.protocol === "https:" ? 443 : 80;
        let origin = url2.origin != null ? url2.origin : `${url2.protocol || ""}//${url2.hostname || ""}:${port}`;
        let path108 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
        if (origin[origin.length - 1] === "/") {
          origin = origin.slice(0, origin.length - 1);
        }
        if (path108 && path108[0] !== "/") {
          path108 = `/${path108}`;
        }
        return new URL(`${origin}${path108}`);
      }
      if (!isHttpOrHttpsPrefixed(url2.origin || url2.protocol)) {
        throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
      }
      return url2;
    }
    __name(parseURL, "parseURL");
    function parseOrigin(url2) {
      url2 = parseURL(url2);
      if (url2.pathname !== "/" || url2.search || url2.hash) {
        throw new InvalidArgumentError("invalid url");
      }
      return url2;
    }
    __name(parseOrigin, "parseOrigin");
    function getHostname(host) {
      if (host[0] === "[") {
        const idx2 = host.indexOf("]");
        assert3(idx2 !== -1);
        return host.substring(1, idx2);
      }
      const idx = host.indexOf(":");
      if (idx === -1) return host;
      return host.substring(0, idx);
    }
    __name(getHostname, "getHostname");
    function getServerName(host) {
      if (!host) {
        return null;
      }
      assert3(typeof host === "string");
      const servername = getHostname(host);
      if (net2.isIP(servername)) {
        return "";
      }
      return servername;
    }
    __name(getServerName, "getServerName");
    function deepClone(obj) {
      return JSON.parse(JSON.stringify(obj));
    }
    __name(deepClone, "deepClone");
    function isAsyncIterable2(obj) {
      return !!(obj != null && typeof obj[Symbol.asyncIterator] === "function");
    }
    __name(isAsyncIterable2, "isAsyncIterable");
    function isIterable(obj) {
      return !!(obj != null && (typeof obj[Symbol.iterator] === "function" || typeof obj[Symbol.asyncIterator] === "function"));
    }
    __name(isIterable, "isIterable");
    function bodyLength(body) {
      if (body == null) {
        return 0;
      } else if (isStream2(body)) {
        const state = body._readableState;
        return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) ? state.length : null;
      } else if (isBlobLike2(body)) {
        return body.size != null ? body.size : null;
      } else if (isBuffer(body)) {
        return body.byteLength;
      }
      return null;
    }
    __name(bodyLength, "bodyLength");
    function isDestroyed(body) {
      return body && !!(body.destroyed || body[kDestroyed] || stream2.isDestroyed?.(body));
    }
    __name(isDestroyed, "isDestroyed");
    function destroy(stream3, err) {
      if (stream3 == null || !isStream2(stream3) || isDestroyed(stream3)) {
        return;
      }
      if (typeof stream3.destroy === "function") {
        if (Object.getPrototypeOf(stream3).constructor === IncomingMessage) {
          stream3.socket = null;
        }
        stream3.destroy(err);
      } else if (err) {
        queueMicrotask(() => {
          stream3.emit("error", err);
        });
      }
      if (stream3.destroyed !== true) {
        stream3[kDestroyed] = true;
      }
    }
    __name(destroy, "destroy");
    var KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/;
    function parseKeepAliveTimeout(val) {
      const m = val.match(KEEPALIVE_TIMEOUT_EXPR);
      return m ? parseInt(m[1], 10) * 1e3 : null;
    }
    __name(parseKeepAliveTimeout, "parseKeepAliveTimeout");
    function headerNameToString(value) {
      return typeof value === "string" ? headerNameLowerCasedRecord[value] ?? value.toLowerCase() : tree.lookup(value) ?? value.toString("latin1").toLowerCase();
    }
    __name(headerNameToString, "headerNameToString");
    function bufferToLowerCasedHeaderName(value) {
      return tree.lookup(value) ?? value.toString("latin1").toLowerCase();
    }
    __name(bufferToLowerCasedHeaderName, "bufferToLowerCasedHeaderName");
    function parseHeaders(headers, obj) {
      if (obj === void 0) obj = {};
      for (let i = 0; i < headers.length; i += 2) {
        const key = headerNameToString(headers[i]);
        let val = obj[key];
        if (val) {
          if (typeof val === "string") {
            val = [val];
            obj[key] = val;
          }
          val.push(headers[i + 1].toString("utf8"));
        } else {
          const headersValue = headers[i + 1];
          if (typeof headersValue === "string") {
            obj[key] = headersValue;
          } else {
            obj[key] = Array.isArray(headersValue) ? headersValue.map((x) => x.toString("utf8")) : headersValue.toString("utf8");
          }
        }
      }
      if ("content-length" in obj && "content-disposition" in obj) {
        obj["content-disposition"] = Buffer.from(obj["content-disposition"]).toString("latin1");
      }
      return obj;
    }
    __name(parseHeaders, "parseHeaders");
    function parseRawHeaders(headers) {
      const headersLength = headers.length;
      const ret = new Array(headersLength);
      let hasContentLength = false;
      let contentDispositionIdx = -1;
      let key;
      let val;
      let kLen = 0;
      for (let n2 = 0; n2 < headersLength; n2 += 2) {
        key = headers[n2];
        val = headers[n2 + 1];
        typeof key !== "string" && (key = key.toString());
        typeof val !== "string" && (val = val.toString("utf8"));
        kLen = key.length;
        if (kLen === 14 && key[7] === "-" && (key === "content-length" || key.toLowerCase() === "content-length")) {
          hasContentLength = true;
        } else if (kLen === 19 && key[7] === "-" && (key === "content-disposition" || key.toLowerCase() === "content-disposition")) {
          contentDispositionIdx = n2 + 1;
        }
        ret[n2] = key;
        ret[n2 + 1] = val;
      }
      if (hasContentLength && contentDispositionIdx !== -1) {
        ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString("latin1");
      }
      return ret;
    }
    __name(parseRawHeaders, "parseRawHeaders");
    function encodeRawHeaders(headers) {
      if (!Array.isArray(headers)) {
        throw new TypeError("expected headers to be an array");
      }
      return headers.map((x) => Buffer.from(x));
    }
    __name(encodeRawHeaders, "encodeRawHeaders");
    function isBuffer(buffer) {
      return buffer instanceof Uint8Array || Buffer.isBuffer(buffer);
    }
    __name(isBuffer, "isBuffer");
    function assertRequestHandler(handler, method, upgrade) {
      if (!handler || typeof handler !== "object") {
        throw new InvalidArgumentError("handler must be an object");
      }
      if (typeof handler.onRequestStart === "function") {
        return;
      }
      if (typeof handler.onConnect !== "function") {
        throw new InvalidArgumentError("invalid onConnect method");
      }
      if (typeof handler.onError !== "function") {
        throw new InvalidArgumentError("invalid onError method");
      }
      if (typeof handler.onBodySent !== "function" && handler.onBodySent !== void 0) {
        throw new InvalidArgumentError("invalid onBodySent method");
      }
      if (upgrade || method === "CONNECT") {
        if (typeof handler.onUpgrade !== "function") {
          throw new InvalidArgumentError("invalid onUpgrade method");
        }
      } else {
        if (typeof handler.onHeaders !== "function") {
          throw new InvalidArgumentError("invalid onHeaders method");
        }
        if (typeof handler.onData !== "function") {
          throw new InvalidArgumentError("invalid onData method");
        }
        if (typeof handler.onComplete !== "function") {
          throw new InvalidArgumentError("invalid onComplete method");
        }
      }
    }
    __name(assertRequestHandler, "assertRequestHandler");
    function isDisturbed(body) {
      return !!(body && (stream2.isDisturbed(body) || body[kBodyUsed]));
    }
    __name(isDisturbed, "isDisturbed");
    function getSocketInfo(socket) {
      return {
        localAddress: socket.localAddress,
        localPort: socket.localPort,
        remoteAddress: socket.remoteAddress,
        remotePort: socket.remotePort,
        remoteFamily: socket.remoteFamily,
        timeout: socket.timeout,
        bytesWritten: socket.bytesWritten,
        bytesRead: socket.bytesRead
      };
    }
    __name(getSocketInfo, "getSocketInfo");
    function ReadableStreamFrom2(iterable) {
      let iterator;
      return new ReadableStream(
        {
          async start() {
            iterator = iterable[Symbol.asyncIterator]();
          },
          pull(controller) {
            async function pull() {
              const { done, value } = await iterator.next();
              if (done) {
                queueMicrotask(() => {
                  controller.close();
                  controller.byobRequest?.respond(0);
                });
              } else {
                const buf = Buffer.isBuffer(value) ? value : Buffer.from(value);
                if (buf.byteLength) {
                  controller.enqueue(new Uint8Array(buf));
                } else {
                  return await pull();
                }
              }
            }
            __name(pull, "pull");
            return pull();
          },
          async cancel() {
            await iterator.return();
          },
          type: "bytes"
        }
      );
    }
    __name(ReadableStreamFrom2, "ReadableStreamFrom");
    function isFormDataLike(object) {
      return object && typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && object[Symbol.toStringTag] === "FormData";
    }
    __name(isFormDataLike, "isFormDataLike");
    function addAbortListener(signal, listener) {
      if ("addEventListener" in signal) {
        signal.addEventListener("abort", listener, { once: true });
        return () => signal.removeEventListener("abort", listener);
      }
      signal.once("abort", listener);
      return () => signal.removeListener("abort", listener);
    }
    __name(addAbortListener, "addAbortListener");
    function isTokenCharCode(c3) {
      switch (c3) {
        case 34:
        case 40:
        case 41:
        case 44:
        case 47:
        case 58:
        case 59:
        case 60:
        case 61:
        case 62:
        case 63:
        case 64:
        case 91:
        case 92:
        case 93:
        case 123:
        case 125:
          return false;
        default:
          return c3 >= 33 && c3 <= 126;
      }
    }
    __name(isTokenCharCode, "isTokenCharCode");
    function isValidHTTPToken(characters) {
      if (characters.length === 0) {
        return false;
      }
      for (let i = 0; i < characters.length; ++i) {
        if (!isTokenCharCode(characters.charCodeAt(i))) {
          return false;
        }
      }
      return true;
    }
    __name(isValidHTTPToken, "isValidHTTPToken");
    var headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
    function isValidHeaderValue(characters) {
      return !headerCharRegex.test(characters);
    }
    __name(isValidHeaderValue, "isValidHeaderValue");
    var rangeHeaderRegex = /^bytes (\d+)-(\d+)\/(\d+)?$/;
    function parseRangeHeader(range) {
      if (range == null || range === "") return { start: 0, end: null, size: null };
      const m = range ? range.match(rangeHeaderRegex) : null;
      return m ? {
        start: parseInt(m[1]),
        end: m[2] ? parseInt(m[2]) : null,
        size: m[3] ? parseInt(m[3]) : null
      } : null;
    }
    __name(parseRangeHeader, "parseRangeHeader");
    function addListener(obj, name3, listener) {
      const listeners = obj[kListeners] ??= [];
      listeners.push([name3, listener]);
      obj.on(name3, listener);
      return obj;
    }
    __name(addListener, "addListener");
    function removeAllListeners(obj) {
      if (obj[kListeners] != null) {
        for (const [name3, listener] of obj[kListeners]) {
          obj.removeListener(name3, listener);
        }
        obj[kListeners] = null;
      }
      return obj;
    }
    __name(removeAllListeners, "removeAllListeners");
    function errorRequest(client, request4, err) {
      try {
        request4.onError(err);
        assert3(request4.aborted);
      } catch (err2) {
        client.emit("error", err2);
      }
    }
    __name(errorRequest, "errorRequest");
    var setupConnectTimeout = process.platform === "win32" ? (socketWeakRef, opts) => {
      if (!opts.timeout) {
        return noop6;
      }
      let s1 = null;
      let s2 = null;
      const fastTimer = timers.setFastTimeout(() => {
        s1 = setImmediate(() => {
          s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts));
        });
      }, opts.timeout);
      return () => {
        timers.clearFastTimeout(fastTimer);
        clearImmediate(s1);
        clearImmediate(s2);
      };
    } : (socketWeakRef, opts) => {
      if (!opts.timeout) {
        return noop6;
      }
      let s1 = null;
      const fastTimer = timers.setFastTimeout(() => {
        s1 = setImmediate(() => {
          onConnectTimeout(socketWeakRef.deref(), opts);
        });
      }, opts.timeout);
      return () => {
        timers.clearFastTimeout(fastTimer);
        clearImmediate(s1);
      };
    };
    function onConnectTimeout(socket, opts) {
      if (socket == null) {
        return;
      }
      let message = "Connect Timeout Error";
      if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) {
        message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(", ")},`;
      } else {
        message += ` (attempted address: ${opts.hostname}:${opts.port},`;
      }
      message += ` timeout: ${opts.timeout}ms)`;
      destroy(socket, new ConnectTimeoutError(message));
    }
    __name(onConnectTimeout, "onConnectTimeout");
    var kEnumerableProperty = /* @__PURE__ */ Object.create(null);
    kEnumerableProperty.enumerable = true;
    var normalizedMethodRecordsBase = {
      delete: "DELETE",
      DELETE: "DELETE",
      get: "GET",
      GET: "GET",
      head: "HEAD",
      HEAD: "HEAD",
      options: "OPTIONS",
      OPTIONS: "OPTIONS",
      post: "POST",
      POST: "POST",
      put: "PUT",
      PUT: "PUT"
    };
    var normalizedMethodRecords = {
      ...normalizedMethodRecordsBase,
      patch: "patch",
      PATCH: "PATCH"
    };
    Object.setPrototypeOf(normalizedMethodRecordsBase, null);
    Object.setPrototypeOf(normalizedMethodRecords, null);
    module2.exports = {
      kEnumerableProperty,
      isDisturbed,
      isBlobLike: isBlobLike2,
      parseOrigin,
      parseURL,
      getServerName,
      isStream: isStream2,
      isIterable,
      isAsyncIterable: isAsyncIterable2,
      isDestroyed,
      headerNameToString,
      bufferToLowerCasedHeaderName,
      addListener,
      removeAllListeners,
      errorRequest,
      parseRawHeaders,
      encodeRawHeaders,
      parseHeaders,
      parseKeepAliveTimeout,
      destroy,
      bodyLength,
      deepClone,
      ReadableStreamFrom: ReadableStreamFrom2,
      isBuffer,
      assertRequestHandler,
      getSocketInfo,
      isFormDataLike,
      pathHasQueryOrFragment,
      serializePathWithQuery,
      addAbortListener,
      isValidHTTPToken,
      isValidHeaderValue,
      isTokenCharCode,
      parseRangeHeader,
      normalizedMethodRecordsBase,
      normalizedMethodRecords,
      isValidPort,
      isHttpOrHttpsPrefixed,
      nodeMajor,
      nodeMinor,
      safeHTTPMethods: Object.freeze(["GET", "HEAD", "OPTIONS", "TRACE"]),
      wrapRequestBody,
      setupConnectTimeout
    };
  }
});

// node_modules/undici/lib/util/stats.js
var require_stats = __commonJS({
  "node_modules/undici/lib/util/stats.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      kConnected,
      kPending,
      kRunning,
      kSize,
      kFree,
      kQueued
    } = require_symbols();
    var ClientStats = class {
      static {
        __name(this, "ClientStats");
      }
      constructor(client) {
        this.connected = client[kConnected];
        this.pending = client[kPending];
        this.running = client[kRunning];
        this.size = client[kSize];
      }
    };
    var PoolStats = class {
      static {
        __name(this, "PoolStats");
      }
      constructor(pool) {
        this.connected = pool[kConnected];
        this.free = pool[kFree];
        this.pending = pool[kPending];
        this.queued = pool[kQueued];
        this.running = pool[kRunning];
        this.size = pool[kSize];
      }
    };
    module2.exports = { ClientStats, PoolStats };
  }
});

// node_modules/undici/lib/core/diagnostics.js
var require_diagnostics = __commonJS({
  "node_modules/undici/lib/core/diagnostics.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var diagnosticsChannel = __require("node:diagnostics_channel");
    var util4 = __require("node:util");
    var undiciDebugLog = util4.debuglog("undici");
    var fetchDebuglog = util4.debuglog("fetch");
    var websocketDebuglog = util4.debuglog("websocket");
    var channels = {
      // Client
      beforeConnect: diagnosticsChannel.channel("undici:client:beforeConnect"),
      connected: diagnosticsChannel.channel("undici:client:connected"),
      connectError: diagnosticsChannel.channel("undici:client:connectError"),
      sendHeaders: diagnosticsChannel.channel("undici:client:sendHeaders"),
      // Request
      create: diagnosticsChannel.channel("undici:request:create"),
      bodySent: diagnosticsChannel.channel("undici:request:bodySent"),
      bodyChunkSent: diagnosticsChannel.channel("undici:request:bodyChunkSent"),
      bodyChunkReceived: diagnosticsChannel.channel("undici:request:bodyChunkReceived"),
      headers: diagnosticsChannel.channel("undici:request:headers"),
      trailers: diagnosticsChannel.channel("undici:request:trailers"),
      error: diagnosticsChannel.channel("undici:request:error"),
      // WebSocket
      open: diagnosticsChannel.channel("undici:websocket:open"),
      close: diagnosticsChannel.channel("undici:websocket:close"),
      socketError: diagnosticsChannel.channel("undici:websocket:socket_error"),
      ping: diagnosticsChannel.channel("undici:websocket:ping"),
      pong: diagnosticsChannel.channel("undici:websocket:pong")
    };
    var isTrackingClientEvents = false;
    function trackClientEvents(debugLog = undiciDebugLog) {
      if (isTrackingClientEvents) {
        return;
      }
      isTrackingClientEvents = true;
      diagnosticsChannel.subscribe(
        "undici:client:beforeConnect",
        (evt) => {
          const {
            connectParams: { version: version2, protocol, port, host }
          } = evt;
          debugLog(
            "connecting to %s%s using %s%s",
            host,
            port ? `:${port}` : "",
            protocol,
            version2
          );
        }
      );
      diagnosticsChannel.subscribe(
        "undici:client:connected",
        (evt) => {
          const {
            connectParams: { version: version2, protocol, port, host }
          } = evt;
          debugLog(
            "connected to %s%s using %s%s",
            host,
            port ? `:${port}` : "",
            protocol,
            version2
          );
        }
      );
      diagnosticsChannel.subscribe(
        "undici:client:connectError",
        (evt) => {
          const {
            connectParams: { version: version2, protocol, port, host },
            error
          } = evt;
          debugLog(
            "connection to %s%s using %s%s errored - %s",
            host,
            port ? `:${port}` : "",
            protocol,
            version2,
            error.message
          );
        }
      );
      diagnosticsChannel.subscribe(
        "undici:client:sendHeaders",
        (evt) => {
          const {
            request: { method, path: path108, origin }
          } = evt;
          debugLog("sending request to %s %s%s", method, origin, path108);
        }
      );
    }
    __name(trackClientEvents, "trackClientEvents");
    var isTrackingRequestEvents = false;
    function trackRequestEvents(debugLog = undiciDebugLog) {
      if (isTrackingRequestEvents) {
        return;
      }
      isTrackingRequestEvents = true;
      diagnosticsChannel.subscribe(
        "undici:request:headers",
        (evt) => {
          const {
            request: { method, path: path108, origin },
            response: { statusCode }
          } = evt;
          debugLog(
            "received response to %s %s%s - HTTP %d",
            method,
            origin,
            path108,
            statusCode
          );
        }
      );
      diagnosticsChannel.subscribe(
        "undici:request:trailers",
        (evt) => {
          const {
            request: { method, path: path108, origin }
          } = evt;
          debugLog("trailers received from %s %s%s", method, origin, path108);
        }
      );
      diagnosticsChannel.subscribe(
        "undici:request:error",
        (evt) => {
          const {
            request: { method, path: path108, origin },
            error
          } = evt;
          debugLog(
            "request to %s %s%s errored - %s",
            method,
            origin,
            path108,
            error.message
          );
        }
      );
    }
    __name(trackRequestEvents, "trackRequestEvents");
    var isTrackingWebSocketEvents = false;
    function trackWebSocketEvents(debugLog = websocketDebuglog) {
      if (isTrackingWebSocketEvents) {
        return;
      }
      isTrackingWebSocketEvents = true;
      diagnosticsChannel.subscribe(
        "undici:websocket:open",
        (evt) => {
          const {
            address: { address, port }
          } = evt;
          debugLog("connection opened %s%s", address, port ? `:${port}` : "");
        }
      );
      diagnosticsChannel.subscribe(
        "undici:websocket:close",
        (evt) => {
          const { websocket, code: code2, reason } = evt;
          debugLog(
            "closed connection to %s - %s %s",
            websocket.url,
            code2,
            reason
          );
        }
      );
      diagnosticsChannel.subscribe(
        "undici:websocket:socket_error",
        (err) => {
          debugLog("connection errored - %s", err.message);
        }
      );
      diagnosticsChannel.subscribe(
        "undici:websocket:ping",
        (evt) => {
          debugLog("ping received");
        }
      );
      diagnosticsChannel.subscribe(
        "undici:websocket:pong",
        (evt) => {
          debugLog("pong received");
        }
      );
    }
    __name(trackWebSocketEvents, "trackWebSocketEvents");
    if (undiciDebugLog.enabled || fetchDebuglog.enabled) {
      trackClientEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog);
      trackRequestEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog);
    }
    if (websocketDebuglog.enabled) {
      trackClientEvents(undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog);
      trackWebSocketEvents(websocketDebuglog);
    }
    module2.exports = {
      channels
    };
  }
});

// node_modules/undici/lib/core/request.js
var require_request = __commonJS({
  "node_modules/undici/lib/core/request.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      InvalidArgumentError,
      NotSupportedError
    } = require_errors();
    var assert3 = __require("node:assert");
    var {
      isValidHTTPToken,
      isValidHeaderValue,
      isStream: isStream2,
      destroy,
      isBuffer,
      isFormDataLike,
      isIterable,
      isBlobLike: isBlobLike2,
      serializePathWithQuery,
      assertRequestHandler,
      getServerName,
      normalizedMethodRecords
    } = require_util();
    var { channels } = require_diagnostics();
    var { headerNameLowerCasedRecord } = require_constants3();
    var invalidPathRegex = /[^\u0021-\u00ff]/;
    var kHandler = Symbol("handler");
    var Request2 = class {
      static {
        __name(this, "Request");
      }
      constructor(origin, {
        path: path108,
        method,
        body,
        headers,
        query,
        idempotent,
        blocking,
        upgrade,
        headersTimeout,
        bodyTimeout,
        reset,
        expectContinue,
        servername,
        throwOnError,
        maxRedirections
      }, handler) {
        if (typeof path108 !== "string") {
          throw new InvalidArgumentError("path must be a string");
        } else if (path108[0] !== "/" && !(path108.startsWith("http://") || path108.startsWith("https://")) && method !== "CONNECT") {
          throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
        } else if (invalidPathRegex.test(path108)) {
          throw new InvalidArgumentError("invalid request path");
        }
        if (typeof method !== "string") {
          throw new InvalidArgumentError("method must be a string");
        } else if (normalizedMethodRecords[method] === void 0 && !isValidHTTPToken(method)) {
          throw new InvalidArgumentError("invalid request method");
        }
        if (upgrade && typeof upgrade !== "string") {
          throw new InvalidArgumentError("upgrade must be a string");
        }
        if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
          throw new InvalidArgumentError("invalid headersTimeout");
        }
        if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
          throw new InvalidArgumentError("invalid bodyTimeout");
        }
        if (reset != null && typeof reset !== "boolean") {
          throw new InvalidArgumentError("invalid reset");
        }
        if (expectContinue != null && typeof expectContinue !== "boolean") {
          throw new InvalidArgumentError("invalid expectContinue");
        }
        if (throwOnError != null) {
          throw new InvalidArgumentError("invalid throwOnError");
        }
        if (maxRedirections != null && maxRedirections !== 0) {
          throw new InvalidArgumentError("maxRedirections is not supported, use the redirect interceptor");
        }
        this.headersTimeout = headersTimeout;
        this.bodyTimeout = bodyTimeout;
        this.method = method;
        this.abort = null;
        if (body == null) {
          this.body = null;
        } else if (isStream2(body)) {
          this.body = body;
          const rState = this.body._readableState;
          if (!rState || !rState.autoDestroy) {
            this.endHandler = /* @__PURE__ */ __name(function autoDestroy() {
              destroy(this);
            }, "autoDestroy");
            this.body.on("end", this.endHandler);
          }
          this.errorHandler = (err) => {
            if (this.abort) {
              this.abort(err);
            } else {
              this.error = err;
            }
          };
          this.body.on("error", this.errorHandler);
        } else if (isBuffer(body)) {
          this.body = body.byteLength ? body : null;
        } else if (ArrayBuffer.isView(body)) {
          this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null;
        } else if (body instanceof ArrayBuffer) {
          this.body = body.byteLength ? Buffer.from(body) : null;
        } else if (typeof body === "string") {
          this.body = body.length ? Buffer.from(body) : null;
        } else if (isFormDataLike(body) || isIterable(body) || isBlobLike2(body)) {
          this.body = body;
        } else {
          throw new InvalidArgumentError("body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable");
        }
        this.completed = false;
        this.aborted = false;
        this.upgrade = upgrade || null;
        this.path = query ? serializePathWithQuery(path108, query) : path108;
        this.origin = origin;
        this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
        this.blocking = blocking ?? this.method !== "HEAD";
        this.reset = reset == null ? null : reset;
        this.host = null;
        this.contentLength = null;
        this.contentType = null;
        this.headers = [];
        this.expectContinue = expectContinue != null ? expectContinue : false;
        if (Array.isArray(headers)) {
          if (headers.length % 2 !== 0) {
            throw new InvalidArgumentError("headers array must be even");
          }
          for (let i = 0; i < headers.length; i += 2) {
            processHeader(this, headers[i], headers[i + 1]);
          }
        } else if (headers && typeof headers === "object") {
          if (headers[Symbol.iterator]) {
            for (const header of headers) {
              if (!Array.isArray(header) || header.length !== 2) {
                throw new InvalidArgumentError("headers must be in key-value pair format");
              }
              processHeader(this, header[0], header[1]);
            }
          } else {
            const keys = Object.keys(headers);
            for (let i = 0; i < keys.length; ++i) {
              processHeader(this, keys[i], headers[keys[i]]);
            }
          }
        } else if (headers != null) {
          throw new InvalidArgumentError("headers must be an object or an array");
        }
        assertRequestHandler(handler, method, upgrade);
        this.servername = servername || getServerName(this.host) || null;
        this[kHandler] = handler;
        if (channels.create.hasSubscribers) {
          channels.create.publish({ request: this });
        }
      }
      onBodySent(chunk) {
        if (channels.bodyChunkSent.hasSubscribers) {
          channels.bodyChunkSent.publish({ request: this, chunk });
        }
        if (this[kHandler].onBodySent) {
          try {
            return this[kHandler].onBodySent(chunk);
          } catch (err) {
            this.abort(err);
          }
        }
      }
      onRequestSent() {
        if (channels.bodySent.hasSubscribers) {
          channels.bodySent.publish({ request: this });
        }
        if (this[kHandler].onRequestSent) {
          try {
            return this[kHandler].onRequestSent();
          } catch (err) {
            this.abort(err);
          }
        }
      }
      onConnect(abort) {
        assert3(!this.aborted);
        assert3(!this.completed);
        if (this.error) {
          abort(this.error);
        } else {
          this.abort = abort;
          return this[kHandler].onConnect(abort);
        }
      }
      onResponseStarted() {
        return this[kHandler].onResponseStarted?.();
      }
      onHeaders(statusCode, headers, resume, statusText) {
        assert3(!this.aborted);
        assert3(!this.completed);
        if (channels.headers.hasSubscribers) {
          channels.headers.publish({ request: this, response: { statusCode, headers, statusText } });
        }
        try {
          return this[kHandler].onHeaders(statusCode, headers, resume, statusText);
        } catch (err) {
          this.abort(err);
        }
      }
      onData(chunk) {
        assert3(!this.aborted);
        assert3(!this.completed);
        if (channels.bodyChunkReceived.hasSubscribers) {
          channels.bodyChunkReceived.publish({ request: this, chunk });
        }
        try {
          return this[kHandler].onData(chunk);
        } catch (err) {
          this.abort(err);
          return false;
        }
      }
      onUpgrade(statusCode, headers, socket) {
        assert3(!this.aborted);
        assert3(!this.completed);
        return this[kHandler].onUpgrade(statusCode, headers, socket);
      }
      onComplete(trailers) {
        this.onFinally();
        assert3(!this.aborted);
        assert3(!this.completed);
        this.completed = true;
        if (channels.trailers.hasSubscribers) {
          channels.trailers.publish({ request: this, trailers });
        }
        try {
          return this[kHandler].onComplete(trailers);
        } catch (err) {
          this.onError(err);
        }
      }
      onError(error) {
        this.onFinally();
        if (channels.error.hasSubscribers) {
          channels.error.publish({ request: this, error });
        }
        if (this.aborted) {
          return;
        }
        this.aborted = true;
        return this[kHandler].onError(error);
      }
      onFinally() {
        if (this.errorHandler) {
          this.body.off("error", this.errorHandler);
          this.errorHandler = null;
        }
        if (this.endHandler) {
          this.body.off("end", this.endHandler);
          this.endHandler = null;
        }
      }
      addHeader(key, value) {
        processHeader(this, key, value);
        return this;
      }
    };
    function processHeader(request4, key, val) {
      if (val && (typeof val === "object" && !Array.isArray(val))) {
        throw new InvalidArgumentError(`invalid ${key} header`);
      } else if (val === void 0) {
        return;
      }
      let headerName = headerNameLowerCasedRecord[key];
      if (headerName === void 0) {
        headerName = key.toLowerCase();
        if (headerNameLowerCasedRecord[headerName] === void 0 && !isValidHTTPToken(headerName)) {
          throw new InvalidArgumentError("invalid header key");
        }
      }
      if (Array.isArray(val)) {
        const arr = [];
        for (let i = 0; i < val.length; i++) {
          if (typeof val[i] === "string") {
            if (!isValidHeaderValue(val[i])) {
              throw new InvalidArgumentError(`invalid ${key} header`);
            }
            arr.push(val[i]);
          } else if (val[i] === null) {
            arr.push("");
          } else if (typeof val[i] === "object") {
            throw new InvalidArgumentError(`invalid ${key} header`);
          } else {
            arr.push(`${val[i]}`);
          }
        }
        val = arr;
      } else if (typeof val === "string") {
        if (!isValidHeaderValue(val)) {
          throw new InvalidArgumentError(`invalid ${key} header`);
        }
      } else if (val === null) {
        val = "";
      } else {
        val = `${val}`;
      }
      if (request4.host === null && headerName === "host") {
        if (typeof val !== "string") {
          throw new InvalidArgumentError("invalid host header");
        }
        request4.host = val;
      } else if (request4.contentLength === null && headerName === "content-length") {
        request4.contentLength = parseInt(val, 10);
        if (!Number.isFinite(request4.contentLength)) {
          throw new InvalidArgumentError("invalid content-length header");
        }
      } else if (request4.contentType === null && headerName === "content-type") {
        request4.contentType = val;
        request4.headers.push(key, val);
      } else if (headerName === "transfer-encoding" || headerName === "keep-alive" || headerName === "upgrade") {
        throw new InvalidArgumentError(`invalid ${headerName} header`);
      } else if (headerName === "connection") {
        const value = typeof val === "string" ? val.toLowerCase() : null;
        if (value !== "close" && value !== "keep-alive") {
          throw new InvalidArgumentError("invalid connection header");
        }
        if (value === "close") {
          request4.reset = true;
        }
      } else if (headerName === "expect") {
        throw new NotSupportedError("expect header not supported");
      } else {
        request4.headers.push(key, val);
      }
    }
    __name(processHeader, "processHeader");
    module2.exports = Request2;
  }
});

// node_modules/undici/lib/handler/wrap-handler.js
var require_wrap_handler = __commonJS({
  "node_modules/undici/lib/handler/wrap-handler.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { InvalidArgumentError } = require_errors();
    module2.exports = class WrapHandler {
      static {
        __name(this, "WrapHandler");
      }
      #handler;
      constructor(handler) {
        this.#handler = handler;
      }
      static wrap(handler) {
        return handler.onRequestStart ? handler : new WrapHandler(handler);
      }
      // Unwrap Interface
      onConnect(abort, context2) {
        return this.#handler.onConnect?.(abort, context2);
      }
      onHeaders(statusCode, rawHeaders, resume, statusMessage) {
        return this.#handler.onHeaders?.(statusCode, rawHeaders, resume, statusMessage);
      }
      onUpgrade(statusCode, rawHeaders, socket) {
        return this.#handler.onUpgrade?.(statusCode, rawHeaders, socket);
      }
      onData(data) {
        return this.#handler.onData?.(data);
      }
      onComplete(trailers) {
        return this.#handler.onComplete?.(trailers);
      }
      onError(err) {
        if (!this.#handler.onError) {
          throw err;
        }
        return this.#handler.onError?.(err);
      }
      // Wrap Interface
      onRequestStart(controller, context2) {
        this.#handler.onConnect?.((reason) => controller.abort(reason), context2);
      }
      onRequestUpgrade(controller, statusCode, headers, socket) {
        const rawHeaders = [];
        for (const [key, val] of Object.entries(headers)) {
          rawHeaders.push(Buffer.from(key), Array.isArray(val) ? val.map((v) => Buffer.from(v)) : Buffer.from(val));
        }
        this.#handler.onUpgrade?.(statusCode, rawHeaders, socket);
      }
      onResponseStart(controller, statusCode, headers, statusMessage) {
        const rawHeaders = [];
        for (const [key, val] of Object.entries(headers)) {
          rawHeaders.push(Buffer.from(key), Array.isArray(val) ? val.map((v) => Buffer.from(v)) : Buffer.from(val));
        }
        if (this.#handler.onHeaders?.(statusCode, rawHeaders, () => controller.resume(), statusMessage) === false) {
          controller.pause();
        }
      }
      onResponseData(controller, data) {
        if (this.#handler.onData?.(data) === false) {
          controller.pause();
        }
      }
      onResponseEnd(controller, trailers) {
        const rawTrailers = [];
        for (const [key, val] of Object.entries(trailers)) {
          rawTrailers.push(Buffer.from(key), Array.isArray(val) ? val.map((v) => Buffer.from(v)) : Buffer.from(val));
        }
        this.#handler.onComplete?.(rawTrailers);
      }
      onResponseError(controller, err) {
        if (!this.#handler.onError) {
          throw new InvalidArgumentError("invalid onError method");
        }
        this.#handler.onError?.(err);
      }
    };
  }
});

// node_modules/undici/lib/dispatcher/dispatcher.js
var require_dispatcher = __commonJS({
  "node_modules/undici/lib/dispatcher/dispatcher.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var EventEmitter10 = __require("node:events");
    var WrapHandler = require_wrap_handler();
    var wrapInterceptor = /* @__PURE__ */ __name((dispatch) => (opts, handler) => dispatch(opts, WrapHandler.wrap(handler)), "wrapInterceptor");
    var Dispatcher = class extends EventEmitter10 {
      static {
        __name(this, "Dispatcher");
      }
      dispatch() {
        throw new Error("not implemented");
      }
      close() {
        throw new Error("not implemented");
      }
      destroy() {
        throw new Error("not implemented");
      }
      compose(...args) {
        const interceptors = Array.isArray(args[0]) ? args[0] : args;
        let dispatch = this.dispatch.bind(this);
        for (const interceptor of interceptors) {
          if (interceptor == null) {
            continue;
          }
          if (typeof interceptor !== "function") {
            throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`);
          }
          dispatch = interceptor(dispatch);
          dispatch = wrapInterceptor(dispatch);
          if (dispatch == null || typeof dispatch !== "function" || dispatch.length !== 2) {
            throw new TypeError("invalid interceptor");
          }
        }
        return new Proxy(this, {
          get: /* @__PURE__ */ __name((target, key) => key === "dispatch" ? dispatch : target[key], "get")
        });
      }
    };
    module2.exports = Dispatcher;
  }
});

// node_modules/undici/lib/handler/unwrap-handler.js
var require_unwrap_handler = __commonJS({
  "node_modules/undici/lib/handler/unwrap-handler.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { parseHeaders } = require_util();
    var { InvalidArgumentError } = require_errors();
    var kResume = Symbol("resume");
    var UnwrapController = class {
      static {
        __name(this, "UnwrapController");
      }
      #paused = false;
      #reason = null;
      #aborted = false;
      #abort;
      [kResume] = null;
      constructor(abort) {
        this.#abort = abort;
      }
      pause() {
        this.#paused = true;
      }
      resume() {
        if (this.#paused) {
          this.#paused = false;
          this[kResume]?.();
        }
      }
      abort(reason) {
        if (!this.#aborted) {
          this.#aborted = true;
          this.#reason = reason;
          this.#abort(reason);
        }
      }
      get aborted() {
        return this.#aborted;
      }
      get reason() {
        return this.#reason;
      }
      get paused() {
        return this.#paused;
      }
    };
    module2.exports = class UnwrapHandler {
      static {
        __name(this, "UnwrapHandler");
      }
      #handler;
      #controller;
      constructor(handler) {
        this.#handler = handler;
      }
      static unwrap(handler) {
        return !handler.onRequestStart ? handler : new UnwrapHandler(handler);
      }
      onConnect(abort, context2) {
        this.#controller = new UnwrapController(abort);
        this.#handler.onRequestStart?.(this.#controller, context2);
      }
      onUpgrade(statusCode, rawHeaders, socket) {
        this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders(rawHeaders), socket);
      }
      onHeaders(statusCode, rawHeaders, resume, statusMessage) {
        this.#controller[kResume] = resume;
        this.#handler.onResponseStart?.(this.#controller, statusCode, parseHeaders(rawHeaders), statusMessage);
        return !this.#controller.paused;
      }
      onData(data) {
        this.#handler.onResponseData?.(this.#controller, data);
        return !this.#controller.paused;
      }
      onComplete(rawTrailers) {
        this.#handler.onResponseEnd?.(this.#controller, parseHeaders(rawTrailers));
      }
      onError(err) {
        if (!this.#handler.onResponseError) {
          throw new InvalidArgumentError("invalid onError method");
        }
        this.#handler.onResponseError?.(this.#controller, err);
      }
    };
  }
});

// node_modules/undici/lib/dispatcher/dispatcher-base.js
var require_dispatcher_base = __commonJS({
  "node_modules/undici/lib/dispatcher/dispatcher-base.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Dispatcher = require_dispatcher();
    var UnwrapHandler = require_unwrap_handler();
    var {
      ClientDestroyedError,
      ClientClosedError,
      InvalidArgumentError
    } = require_errors();
    var { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = require_symbols();
    var kOnDestroyed = Symbol("onDestroyed");
    var kOnClosed = Symbol("onClosed");
    var DispatcherBase = class extends Dispatcher {
      static {
        __name(this, "DispatcherBase");
      }
      constructor() {
        super();
        this[kDestroyed] = false;
        this[kOnDestroyed] = null;
        this[kClosed] = false;
        this[kOnClosed] = [];
      }
      get destroyed() {
        return this[kDestroyed];
      }
      get closed() {
        return this[kClosed];
      }
      close(callback) {
        if (callback === void 0) {
          return new Promise((resolve24, reject) => {
            this.close((err, data) => {
              return err ? reject(err) : resolve24(data);
            });
          });
        }
        if (typeof callback !== "function") {
          throw new InvalidArgumentError("invalid callback");
        }
        if (this[kDestroyed]) {
          queueMicrotask(() => callback(new ClientDestroyedError(), null));
          return;
        }
        if (this[kClosed]) {
          if (this[kOnClosed]) {
            this[kOnClosed].push(callback);
          } else {
            queueMicrotask(() => callback(null, null));
          }
          return;
        }
        this[kClosed] = true;
        this[kOnClosed].push(callback);
        const onClosed = /* @__PURE__ */ __name(() => {
          const callbacks = this[kOnClosed];
          this[kOnClosed] = null;
          for (let i = 0; i < callbacks.length; i++) {
            callbacks[i](null, null);
          }
        }, "onClosed");
        this[kClose]().then(() => this.destroy()).then(() => {
          queueMicrotask(onClosed);
        });
      }
      destroy(err, callback) {
        if (typeof err === "function") {
          callback = err;
          err = null;
        }
        if (callback === void 0) {
          return new Promise((resolve24, reject) => {
            this.destroy(err, (err2, data) => {
              return err2 ? (
                /* istanbul ignore next: should never error */
                reject(err2)
              ) : resolve24(data);
            });
          });
        }
        if (typeof callback !== "function") {
          throw new InvalidArgumentError("invalid callback");
        }
        if (this[kDestroyed]) {
          if (this[kOnDestroyed]) {
            this[kOnDestroyed].push(callback);
          } else {
            queueMicrotask(() => callback(null, null));
          }
          return;
        }
        if (!err) {
          err = new ClientDestroyedError();
        }
        this[kDestroyed] = true;
        this[kOnDestroyed] = this[kOnDestroyed] || [];
        this[kOnDestroyed].push(callback);
        const onDestroyed = /* @__PURE__ */ __name(() => {
          const callbacks = this[kOnDestroyed];
          this[kOnDestroyed] = null;
          for (let i = 0; i < callbacks.length; i++) {
            callbacks[i](null, null);
          }
        }, "onDestroyed");
        this[kDestroy](err).then(() => {
          queueMicrotask(onDestroyed);
        });
      }
      dispatch(opts, handler) {
        if (!handler || typeof handler !== "object") {
          throw new InvalidArgumentError("handler must be an object");
        }
        handler = UnwrapHandler.unwrap(handler);
        try {
          if (!opts || typeof opts !== "object") {
            throw new InvalidArgumentError("opts must be an object.");
          }
          if (this[kDestroyed] || this[kOnDestroyed]) {
            throw new ClientDestroyedError();
          }
          if (this[kClosed]) {
            throw new ClientClosedError();
          }
          return this[kDispatch](opts, handler);
        } catch (err) {
          if (typeof handler.onError !== "function") {
            throw err;
          }
          handler.onError(err);
          return false;
        }
      }
    };
    module2.exports = DispatcherBase;
  }
});

// node_modules/undici/lib/core/connect.js
var require_connect = __commonJS({
  "node_modules/undici/lib/core/connect.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var net2 = __require("node:net");
    var assert3 = __require("node:assert");
    var util4 = require_util();
    var { InvalidArgumentError } = require_errors();
    var tls;
    var SessionCache = class WeakSessionCache {
      static {
        __name(this, "WeakSessionCache");
      }
      constructor(maxCachedSessions) {
        this._maxCachedSessions = maxCachedSessions;
        this._sessionCache = /* @__PURE__ */ new Map();
        this._sessionRegistry = new FinalizationRegistry((key) => {
          if (this._sessionCache.size < this._maxCachedSessions) {
            return;
          }
          const ref = this._sessionCache.get(key);
          if (ref !== void 0 && ref.deref() === void 0) {
            this._sessionCache.delete(key);
          }
        });
      }
      get(sessionKey) {
        const ref = this._sessionCache.get(sessionKey);
        return ref ? ref.deref() : null;
      }
      set(sessionKey, session) {
        if (this._maxCachedSessions === 0) {
          return;
        }
        this._sessionCache.set(sessionKey, new WeakRef(session));
        this._sessionRegistry.register(session, sessionKey);
      }
    };
    function buildConnector({ allowH2, maxCachedSessions, socketPath, timeout: timeout2, session: customSession, ...opts }) {
      if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {
        throw new InvalidArgumentError("maxCachedSessions must be a positive integer or zero");
      }
      const options2 = { path: socketPath, ...opts };
      const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions);
      timeout2 = timeout2 == null ? 1e4 : timeout2;
      allowH2 = allowH2 != null ? allowH2 : false;
      return /* @__PURE__ */ __name(function connect({ hostname: hostname3, host, protocol, port, servername, localAddress, httpSocket }, callback) {
        let socket;
        if (protocol === "https:") {
          if (!tls) {
            tls = __require("node:tls");
          }
          servername = servername || options2.servername || util4.getServerName(host) || null;
          const sessionKey = servername || hostname3;
          assert3(sessionKey);
          const session = customSession || sessionCache.get(sessionKey) || null;
          port = port || 443;
          socket = tls.connect({
            highWaterMark: 16384,
            // TLS in node can't have bigger HWM anyway...
            ...options2,
            servername,
            session,
            localAddress,
            ALPNProtocols: allowH2 ? ["http/1.1", "h2"] : ["http/1.1"],
            socket: httpSocket,
            // upgrade socket connection
            port,
            host: hostname3
          });
          socket.on("session", function(session2) {
            sessionCache.set(sessionKey, session2);
          });
        } else {
          assert3(!httpSocket, "httpSocket can only be sent on TLS update");
          port = port || 80;
          socket = net2.connect({
            highWaterMark: 64 * 1024,
            // Same as nodejs fs streams.
            ...options2,
            localAddress,
            port,
            host: hostname3
          });
        }
        if (options2.keepAlive == null || options2.keepAlive) {
          const keepAliveInitialDelay = options2.keepAliveInitialDelay === void 0 ? 6e4 : options2.keepAliveInitialDelay;
          socket.setKeepAlive(true, keepAliveInitialDelay);
        }
        const clearConnectTimeout = util4.setupConnectTimeout(new WeakRef(socket), { timeout: timeout2, hostname: hostname3, port });
        socket.setNoDelay(true).once(protocol === "https:" ? "secureConnect" : "connect", function() {
          queueMicrotask(clearConnectTimeout);
          if (callback) {
            const cb = callback;
            callback = null;
            cb(null, this);
          }
        }).on("error", function(err) {
          queueMicrotask(clearConnectTimeout);
          if (callback) {
            const cb = callback;
            callback = null;
            cb(err);
          }
        });
        return socket;
      }, "connect");
    }
    __name(buildConnector, "buildConnector");
    module2.exports = buildConnector;
  }
});

// node_modules/undici/lib/llhttp/utils.js
var require_utils = __commonJS({
  "node_modules/undici/lib/llhttp/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.enumToMap = enumToMap;
    function enumToMap(obj, filter4 = [], exceptions = []) {
      const emptyFilter = (filter4?.length ?? 0) === 0;
      const emptyExceptions = (exceptions?.length ?? 0) === 0;
      return Object.fromEntries(Object.entries(obj).filter(([, value]) => {
        return typeof value === "number" && (emptyFilter || filter4.includes(value)) && (emptyExceptions || !exceptions.includes(value));
      }));
    }
    __name(enumToMap, "enumToMap");
  }
});

// node_modules/undici/lib/llhttp/constants.js
var require_constants4 = __commonJS({
  "node_modules/undici/lib/llhttp/constants.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SPECIAL_HEADERS = exports2.MINOR = exports2.MAJOR = exports2.HTAB_SP_VCHAR_OBS_TEXT = exports2.QUOTED_STRING = exports2.CONNECTION_TOKEN_CHARS = exports2.HEADER_CHARS = exports2.TOKEN = exports2.HEX = exports2.URL_CHAR = exports2.USERINFO_CHARS = exports2.MARK = exports2.ALPHANUM = exports2.NUM = exports2.HEX_MAP = exports2.NUM_MAP = exports2.ALPHA = exports2.STATUSES_HTTP = exports2.H_METHOD_MAP = exports2.METHOD_MAP = exports2.METHODS_RTSP = exports2.METHODS_ICE = exports2.METHODS_HTTP = exports2.HEADER_STATE = exports2.FINISH = exports2.STATUSES = exports2.METHODS = exports2.LENIENT_FLAGS = exports2.FLAGS = exports2.TYPE = exports2.ERROR = void 0;
    var utils_1 = require_utils();
    exports2.ERROR = {
      OK: 0,
      INTERNAL: 1,
      STRICT: 2,
      CR_EXPECTED: 25,
      LF_EXPECTED: 3,
      UNEXPECTED_CONTENT_LENGTH: 4,
      UNEXPECTED_SPACE: 30,
      CLOSED_CONNECTION: 5,
      INVALID_METHOD: 6,
      INVALID_URL: 7,
      INVALID_CONSTANT: 8,
      INVALID_VERSION: 9,
      INVALID_HEADER_TOKEN: 10,
      INVALID_CONTENT_LENGTH: 11,
      INVALID_CHUNK_SIZE: 12,
      INVALID_STATUS: 13,
      INVALID_EOF_STATE: 14,
      INVALID_TRANSFER_ENCODING: 15,
      CB_MESSAGE_BEGIN: 16,
      CB_HEADERS_COMPLETE: 17,
      CB_MESSAGE_COMPLETE: 18,
      CB_CHUNK_HEADER: 19,
      CB_CHUNK_COMPLETE: 20,
      PAUSED: 21,
      PAUSED_UPGRADE: 22,
      PAUSED_H2_UPGRADE: 23,
      USER: 24,
      CB_URL_COMPLETE: 26,
      CB_STATUS_COMPLETE: 27,
      CB_METHOD_COMPLETE: 32,
      CB_VERSION_COMPLETE: 33,
      CB_HEADER_FIELD_COMPLETE: 28,
      CB_HEADER_VALUE_COMPLETE: 29,
      CB_CHUNK_EXTENSION_NAME_COMPLETE: 34,
      CB_CHUNK_EXTENSION_VALUE_COMPLETE: 35,
      CB_RESET: 31,
      CB_PROTOCOL_COMPLETE: 38
    };
    exports2.TYPE = {
      BOTH: 0,
      // default
      REQUEST: 1,
      RESPONSE: 2
    };
    exports2.FLAGS = {
      CONNECTION_KEEP_ALIVE: 1 << 0,
      CONNECTION_CLOSE: 1 << 1,
      CONNECTION_UPGRADE: 1 << 2,
      CHUNKED: 1 << 3,
      UPGRADE: 1 << 4,
      CONTENT_LENGTH: 1 << 5,
      SKIPBODY: 1 << 6,
      TRAILING: 1 << 7,
      // 1 << 8 is unused
      TRANSFER_ENCODING: 1 << 9
    };
    exports2.LENIENT_FLAGS = {
      HEADERS: 1 << 0,
      CHUNKED_LENGTH: 1 << 1,
      KEEP_ALIVE: 1 << 2,
      TRANSFER_ENCODING: 1 << 3,
      VERSION: 1 << 4,
      DATA_AFTER_CLOSE: 1 << 5,
      OPTIONAL_LF_AFTER_CR: 1 << 6,
      OPTIONAL_CRLF_AFTER_CHUNK: 1 << 7,
      OPTIONAL_CR_BEFORE_LF: 1 << 8,
      SPACES_AFTER_CHUNK_SIZE: 1 << 9
    };
    exports2.METHODS = {
      "DELETE": 0,
      "GET": 1,
      "HEAD": 2,
      "POST": 3,
      "PUT": 4,
      /* pathological */
      "CONNECT": 5,
      "OPTIONS": 6,
      "TRACE": 7,
      /* WebDAV */
      "COPY": 8,
      "LOCK": 9,
      "MKCOL": 10,
      "MOVE": 11,
      "PROPFIND": 12,
      "PROPPATCH": 13,
      "SEARCH": 14,
      "UNLOCK": 15,
      "BIND": 16,
      "REBIND": 17,
      "UNBIND": 18,
      "ACL": 19,
      /* subversion */
      "REPORT": 20,
      "MKACTIVITY": 21,
      "CHECKOUT": 22,
      "MERGE": 23,
      /* upnp */
      "M-SEARCH": 24,
      "NOTIFY": 25,
      "SUBSCRIBE": 26,
      "UNSUBSCRIBE": 27,
      /* RFC-5789 */
      "PATCH": 28,
      "PURGE": 29,
      /* CalDAV */
      "MKCALENDAR": 30,
      /* RFC-2068, section 19.6.1.2 */
      "LINK": 31,
      "UNLINK": 32,
      /* icecast */
      "SOURCE": 33,
      /* RFC-7540, section 11.6 */
      "PRI": 34,
      /* RFC-2326 RTSP */
      "DESCRIBE": 35,
      "ANNOUNCE": 36,
      "SETUP": 37,
      "PLAY": 38,
      "PAUSE": 39,
      "TEARDOWN": 40,
      "GET_PARAMETER": 41,
      "SET_PARAMETER": 42,
      "REDIRECT": 43,
      "RECORD": 44,
      /* RAOP */
      "FLUSH": 45,
      /* DRAFT https://www.ietf.org/archive/id/draft-ietf-httpbis-safe-method-w-body-02.html */
      "QUERY": 46
    };
    exports2.STATUSES = {
      CONTINUE: 100,
      SWITCHING_PROTOCOLS: 101,
      PROCESSING: 102,
      EARLY_HINTS: 103,
      RESPONSE_IS_STALE: 110,
      // Unofficial
      REVALIDATION_FAILED: 111,
      // Unofficial
      DISCONNECTED_OPERATION: 112,
      // Unofficial
      HEURISTIC_EXPIRATION: 113,
      // Unofficial
      MISCELLANEOUS_WARNING: 199,
      // Unofficial
      OK: 200,
      CREATED: 201,
      ACCEPTED: 202,
      NON_AUTHORITATIVE_INFORMATION: 203,
      NO_CONTENT: 204,
      RESET_CONTENT: 205,
      PARTIAL_CONTENT: 206,
      MULTI_STATUS: 207,
      ALREADY_REPORTED: 208,
      TRANSFORMATION_APPLIED: 214,
      // Unofficial
      IM_USED: 226,
      MISCELLANEOUS_PERSISTENT_WARNING: 299,
      // Unofficial
      MULTIPLE_CHOICES: 300,
      MOVED_PERMANENTLY: 301,
      FOUND: 302,
      SEE_OTHER: 303,
      NOT_MODIFIED: 304,
      USE_PROXY: 305,
      SWITCH_PROXY: 306,
      // No longer used
      TEMPORARY_REDIRECT: 307,
      PERMANENT_REDIRECT: 308,
      BAD_REQUEST: 400,
      UNAUTHORIZED: 401,
      PAYMENT_REQUIRED: 402,
      FORBIDDEN: 403,
      NOT_FOUND: 404,
      METHOD_NOT_ALLOWED: 405,
      NOT_ACCEPTABLE: 406,
      PROXY_AUTHENTICATION_REQUIRED: 407,
      REQUEST_TIMEOUT: 408,
      CONFLICT: 409,
      GONE: 410,
      LENGTH_REQUIRED: 411,
      PRECONDITION_FAILED: 412,
      PAYLOAD_TOO_LARGE: 413,
      URI_TOO_LONG: 414,
      UNSUPPORTED_MEDIA_TYPE: 415,
      RANGE_NOT_SATISFIABLE: 416,
      EXPECTATION_FAILED: 417,
      IM_A_TEAPOT: 418,
      PAGE_EXPIRED: 419,
      // Unofficial
      ENHANCE_YOUR_CALM: 420,
      // Unofficial
      MISDIRECTED_REQUEST: 421,
      UNPROCESSABLE_ENTITY: 422,
      LOCKED: 423,
      FAILED_DEPENDENCY: 424,
      TOO_EARLY: 425,
      UPGRADE_REQUIRED: 426,
      PRECONDITION_REQUIRED: 428,
      TOO_MANY_REQUESTS: 429,
      REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL: 430,
      // Unofficial
      REQUEST_HEADER_FIELDS_TOO_LARGE: 431,
      LOGIN_TIMEOUT: 440,
      // Unofficial
      NO_RESPONSE: 444,
      // Unofficial
      RETRY_WITH: 449,
      // Unofficial
      BLOCKED_BY_PARENTAL_CONTROL: 450,
      // Unofficial
      UNAVAILABLE_FOR_LEGAL_REASONS: 451,
      CLIENT_CLOSED_LOAD_BALANCED_REQUEST: 460,
      // Unofficial
      INVALID_X_FORWARDED_FOR: 463,
      // Unofficial
      REQUEST_HEADER_TOO_LARGE: 494,
      // Unofficial
      SSL_CERTIFICATE_ERROR: 495,
      // Unofficial
      SSL_CERTIFICATE_REQUIRED: 496,
      // Unofficial
      HTTP_REQUEST_SENT_TO_HTTPS_PORT: 497,
      // Unofficial
      INVALID_TOKEN: 498,
      // Unofficial
      CLIENT_CLOSED_REQUEST: 499,
      // Unofficial
      INTERNAL_SERVER_ERROR: 500,
      NOT_IMPLEMENTED: 501,
      BAD_GATEWAY: 502,
      SERVICE_UNAVAILABLE: 503,
      GATEWAY_TIMEOUT: 504,
      HTTP_VERSION_NOT_SUPPORTED: 505,
      VARIANT_ALSO_NEGOTIATES: 506,
      INSUFFICIENT_STORAGE: 507,
      LOOP_DETECTED: 508,
      BANDWIDTH_LIMIT_EXCEEDED: 509,
      NOT_EXTENDED: 510,
      NETWORK_AUTHENTICATION_REQUIRED: 511,
      WEB_SERVER_UNKNOWN_ERROR: 520,
      // Unofficial
      WEB_SERVER_IS_DOWN: 521,
      // Unofficial
      CONNECTION_TIMEOUT: 522,
      // Unofficial
      ORIGIN_IS_UNREACHABLE: 523,
      // Unofficial
      TIMEOUT_OCCURED: 524,
      // Unofficial
      SSL_HANDSHAKE_FAILED: 525,
      // Unofficial
      INVALID_SSL_CERTIFICATE: 526,
      // Unofficial
      RAILGUN_ERROR: 527,
      // Unofficial
      SITE_IS_OVERLOADED: 529,
      // Unofficial
      SITE_IS_FROZEN: 530,
      // Unofficial
      IDENTITY_PROVIDER_AUTHENTICATION_ERROR: 561,
      // Unofficial
      NETWORK_READ_TIMEOUT: 598,
      // Unofficial
      NETWORK_CONNECT_TIMEOUT: 599
      // Unofficial
    };
    exports2.FINISH = {
      SAFE: 0,
      SAFE_WITH_CB: 1,
      UNSAFE: 2
    };
    exports2.HEADER_STATE = {
      GENERAL: 0,
      CONNECTION: 1,
      CONTENT_LENGTH: 2,
      TRANSFER_ENCODING: 3,
      UPGRADE: 4,
      CONNECTION_KEEP_ALIVE: 5,
      CONNECTION_CLOSE: 6,
      CONNECTION_UPGRADE: 7,
      TRANSFER_ENCODING_CHUNKED: 8
    };
    exports2.METHODS_HTTP = [
      exports2.METHODS.DELETE,
      exports2.METHODS.GET,
      exports2.METHODS.HEAD,
      exports2.METHODS.POST,
      exports2.METHODS.PUT,
      exports2.METHODS.CONNECT,
      exports2.METHODS.OPTIONS,
      exports2.METHODS.TRACE,
      exports2.METHODS.COPY,
      exports2.METHODS.LOCK,
      exports2.METHODS.MKCOL,
      exports2.METHODS.MOVE,
      exports2.METHODS.PROPFIND,
      exports2.METHODS.PROPPATCH,
      exports2.METHODS.SEARCH,
      exports2.METHODS.UNLOCK,
      exports2.METHODS.BIND,
      exports2.METHODS.REBIND,
      exports2.METHODS.UNBIND,
      exports2.METHODS.ACL,
      exports2.METHODS.REPORT,
      exports2.METHODS.MKACTIVITY,
      exports2.METHODS.CHECKOUT,
      exports2.METHODS.MERGE,
      exports2.METHODS["M-SEARCH"],
      exports2.METHODS.NOTIFY,
      exports2.METHODS.SUBSCRIBE,
      exports2.METHODS.UNSUBSCRIBE,
      exports2.METHODS.PATCH,
      exports2.METHODS.PURGE,
      exports2.METHODS.MKCALENDAR,
      exports2.METHODS.LINK,
      exports2.METHODS.UNLINK,
      exports2.METHODS.PRI,
      // TODO(indutny): should we allow it with HTTP?
      exports2.METHODS.SOURCE,
      exports2.METHODS.QUERY
    ];
    exports2.METHODS_ICE = [
      exports2.METHODS.SOURCE
    ];
    exports2.METHODS_RTSP = [
      exports2.METHODS.OPTIONS,
      exports2.METHODS.DESCRIBE,
      exports2.METHODS.ANNOUNCE,
      exports2.METHODS.SETUP,
      exports2.METHODS.PLAY,
      exports2.METHODS.PAUSE,
      exports2.METHODS.TEARDOWN,
      exports2.METHODS.GET_PARAMETER,
      exports2.METHODS.SET_PARAMETER,
      exports2.METHODS.REDIRECT,
      exports2.METHODS.RECORD,
      exports2.METHODS.FLUSH,
      // For AirPlay
      exports2.METHODS.GET,
      exports2.METHODS.POST
    ];
    exports2.METHOD_MAP = (0, utils_1.enumToMap)(exports2.METHODS);
    exports2.H_METHOD_MAP = Object.fromEntries(Object.entries(exports2.METHODS).filter(([k]) => k.startsWith("H")));
    exports2.STATUSES_HTTP = [
      exports2.STATUSES.CONTINUE,
      exports2.STATUSES.SWITCHING_PROTOCOLS,
      exports2.STATUSES.PROCESSING,
      exports2.STATUSES.EARLY_HINTS,
      exports2.STATUSES.RESPONSE_IS_STALE,
      exports2.STATUSES.REVALIDATION_FAILED,
      exports2.STATUSES.DISCONNECTED_OPERATION,
      exports2.STATUSES.HEURISTIC_EXPIRATION,
      exports2.STATUSES.MISCELLANEOUS_WARNING,
      exports2.STATUSES.OK,
      exports2.STATUSES.CREATED,
      exports2.STATUSES.ACCEPTED,
      exports2.STATUSES.NON_AUTHORITATIVE_INFORMATION,
      exports2.STATUSES.NO_CONTENT,
      exports2.STATUSES.RESET_CONTENT,
      exports2.STATUSES.PARTIAL_CONTENT,
      exports2.STATUSES.MULTI_STATUS,
      exports2.STATUSES.ALREADY_REPORTED,
      exports2.STATUSES.TRANSFORMATION_APPLIED,
      exports2.STATUSES.IM_USED,
      exports2.STATUSES.MISCELLANEOUS_PERSISTENT_WARNING,
      exports2.STATUSES.MULTIPLE_CHOICES,
      exports2.STATUSES.MOVED_PERMANENTLY,
      exports2.STATUSES.FOUND,
      exports2.STATUSES.SEE_OTHER,
      exports2.STATUSES.NOT_MODIFIED,
      exports2.STATUSES.USE_PROXY,
      exports2.STATUSES.SWITCH_PROXY,
      exports2.STATUSES.TEMPORARY_REDIRECT,
      exports2.STATUSES.PERMANENT_REDIRECT,
      exports2.STATUSES.BAD_REQUEST,
      exports2.STATUSES.UNAUTHORIZED,
      exports2.STATUSES.PAYMENT_REQUIRED,
      exports2.STATUSES.FORBIDDEN,
      exports2.STATUSES.NOT_FOUND,
      exports2.STATUSES.METHOD_NOT_ALLOWED,
      exports2.STATUSES.NOT_ACCEPTABLE,
      exports2.STATUSES.PROXY_AUTHENTICATION_REQUIRED,
      exports2.STATUSES.REQUEST_TIMEOUT,
      exports2.STATUSES.CONFLICT,
      exports2.STATUSES.GONE,
      exports2.STATUSES.LENGTH_REQUIRED,
      exports2.STATUSES.PRECONDITION_FAILED,
      exports2.STATUSES.PAYLOAD_TOO_LARGE,
      exports2.STATUSES.URI_TOO_LONG,
      exports2.STATUSES.UNSUPPORTED_MEDIA_TYPE,
      exports2.STATUSES.RANGE_NOT_SATISFIABLE,
      exports2.STATUSES.EXPECTATION_FAILED,
      exports2.STATUSES.IM_A_TEAPOT,
      exports2.STATUSES.PAGE_EXPIRED,
      exports2.STATUSES.ENHANCE_YOUR_CALM,
      exports2.STATUSES.MISDIRECTED_REQUEST,
      exports2.STATUSES.UNPROCESSABLE_ENTITY,
      exports2.STATUSES.LOCKED,
      exports2.STATUSES.FAILED_DEPENDENCY,
      exports2.STATUSES.TOO_EARLY,
      exports2.STATUSES.UPGRADE_REQUIRED,
      exports2.STATUSES.PRECONDITION_REQUIRED,
      exports2.STATUSES.TOO_MANY_REQUESTS,
      exports2.STATUSES.REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL,
      exports2.STATUSES.REQUEST_HEADER_FIELDS_TOO_LARGE,
      exports2.STATUSES.LOGIN_TIMEOUT,
      exports2.STATUSES.NO_RESPONSE,
      exports2.STATUSES.RETRY_WITH,
      exports2.STATUSES.BLOCKED_BY_PARENTAL_CONTROL,
      exports2.STATUSES.UNAVAILABLE_FOR_LEGAL_REASONS,
      exports2.STATUSES.CLIENT_CLOSED_LOAD_BALANCED_REQUEST,
      exports2.STATUSES.INVALID_X_FORWARDED_FOR,
      exports2.STATUSES.REQUEST_HEADER_TOO_LARGE,
      exports2.STATUSES.SSL_CERTIFICATE_ERROR,
      exports2.STATUSES.SSL_CERTIFICATE_REQUIRED,
      exports2.STATUSES.HTTP_REQUEST_SENT_TO_HTTPS_PORT,
      exports2.STATUSES.INVALID_TOKEN,
      exports2.STATUSES.CLIENT_CLOSED_REQUEST,
      exports2.STATUSES.INTERNAL_SERVER_ERROR,
      exports2.STATUSES.NOT_IMPLEMENTED,
      exports2.STATUSES.BAD_GATEWAY,
      exports2.STATUSES.SERVICE_UNAVAILABLE,
      exports2.STATUSES.GATEWAY_TIMEOUT,
      exports2.STATUSES.HTTP_VERSION_NOT_SUPPORTED,
      exports2.STATUSES.VARIANT_ALSO_NEGOTIATES,
      exports2.STATUSES.INSUFFICIENT_STORAGE,
      exports2.STATUSES.LOOP_DETECTED,
      exports2.STATUSES.BANDWIDTH_LIMIT_EXCEEDED,
      exports2.STATUSES.NOT_EXTENDED,
      exports2.STATUSES.NETWORK_AUTHENTICATION_REQUIRED,
      exports2.STATUSES.WEB_SERVER_UNKNOWN_ERROR,
      exports2.STATUSES.WEB_SERVER_IS_DOWN,
      exports2.STATUSES.CONNECTION_TIMEOUT,
      exports2.STATUSES.ORIGIN_IS_UNREACHABLE,
      exports2.STATUSES.TIMEOUT_OCCURED,
      exports2.STATUSES.SSL_HANDSHAKE_FAILED,
      exports2.STATUSES.INVALID_SSL_CERTIFICATE,
      exports2.STATUSES.RAILGUN_ERROR,
      exports2.STATUSES.SITE_IS_OVERLOADED,
      exports2.STATUSES.SITE_IS_FROZEN,
      exports2.STATUSES.IDENTITY_PROVIDER_AUTHENTICATION_ERROR,
      exports2.STATUSES.NETWORK_READ_TIMEOUT,
      exports2.STATUSES.NETWORK_CONNECT_TIMEOUT
    ];
    exports2.ALPHA = [];
    for (let i = "A".charCodeAt(0); i <= "Z".charCodeAt(0); i++) {
      exports2.ALPHA.push(String.fromCharCode(i));
      exports2.ALPHA.push(String.fromCharCode(i + 32));
    }
    exports2.NUM_MAP = {
      0: 0,
      1: 1,
      2: 2,
      3: 3,
      4: 4,
      5: 5,
      6: 6,
      7: 7,
      8: 8,
      9: 9
    };
    exports2.HEX_MAP = {
      0: 0,
      1: 1,
      2: 2,
      3: 3,
      4: 4,
      5: 5,
      6: 6,
      7: 7,
      8: 8,
      9: 9,
      A: 10,
      B: 11,
      C: 12,
      D: 13,
      E: 14,
      F: 15,
      a: 10,
      b: 11,
      c: 12,
      d: 13,
      e: 14,
      f: 15
    };
    exports2.NUM = [
      "0",
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9"
    ];
    exports2.ALPHANUM = exports2.ALPHA.concat(exports2.NUM);
    exports2.MARK = ["-", "_", ".", "!", "~", "*", "'", "(", ")"];
    exports2.USERINFO_CHARS = exports2.ALPHANUM.concat(exports2.MARK).concat(["%", ";", ":", "&", "=", "+", "$", ","]);
    exports2.URL_CHAR = [
      "!",
      '"',
      "$",
      "%",
      "&",
      "'",
      "(",
      ")",
      "*",
      "+",
      ",",
      "-",
      ".",
      "/",
      ":",
      ";",
      "<",
      "=",
      ">",
      "@",
      "[",
      "\\",
      "]",
      "^",
      "_",
      "`",
      "{",
      "|",
      "}",
      "~"
    ].concat(exports2.ALPHANUM);
    exports2.HEX = exports2.NUM.concat(["a", "b", "c", "d", "e", "f", "A", "B", "C", "D", "E", "F"]);
    exports2.TOKEN = [
      "!",
      "#",
      "$",
      "%",
      "&",
      "'",
      "*",
      "+",
      "-",
      ".",
      "^",
      "_",
      "`",
      "|",
      "~"
    ].concat(exports2.ALPHANUM);
    exports2.HEADER_CHARS = ["	"];
    for (let i = 32; i <= 255; i++) {
      if (i !== 127) {
        exports2.HEADER_CHARS.push(i);
      }
    }
    exports2.CONNECTION_TOKEN_CHARS = exports2.HEADER_CHARS.filter((c3) => c3 !== 44);
    exports2.QUOTED_STRING = ["	", " "];
    for (let i = 33; i <= 255; i++) {
      if (i !== 34 && i !== 92) {
        exports2.QUOTED_STRING.push(i);
      }
    }
    exports2.HTAB_SP_VCHAR_OBS_TEXT = ["	", " "];
    for (let i = 33; i <= 126; i++) {
      exports2.HTAB_SP_VCHAR_OBS_TEXT.push(i);
    }
    for (let i = 128; i <= 255; i++) {
      exports2.HTAB_SP_VCHAR_OBS_TEXT.push(i);
    }
    exports2.MAJOR = exports2.NUM_MAP;
    exports2.MINOR = exports2.MAJOR;
    exports2.SPECIAL_HEADERS = {
      "connection": exports2.HEADER_STATE.CONNECTION,
      "content-length": exports2.HEADER_STATE.CONTENT_LENGTH,
      "proxy-connection": exports2.HEADER_STATE.CONNECTION,
      "transfer-encoding": exports2.HEADER_STATE.TRANSFER_ENCODING,
      "upgrade": exports2.HEADER_STATE.UPGRADE
    };
    exports2.default = {
      ERROR: exports2.ERROR,
      TYPE: exports2.TYPE,
      FLAGS: exports2.FLAGS,
      LENIENT_FLAGS: exports2.LENIENT_FLAGS,
      METHODS: exports2.METHODS,
      STATUSES: exports2.STATUSES,
      FINISH: exports2.FINISH,
      HEADER_STATE: exports2.HEADER_STATE,
      ALPHA: exports2.ALPHA,
      NUM_MAP: exports2.NUM_MAP,
      HEX_MAP: exports2.HEX_MAP,
      NUM: exports2.NUM,
      ALPHANUM: exports2.ALPHANUM,
      MARK: exports2.MARK,
      USERINFO_CHARS: exports2.USERINFO_CHARS,
      URL_CHAR: exports2.URL_CHAR,
      HEX: exports2.HEX,
      TOKEN: exports2.TOKEN,
      HEADER_CHARS: exports2.HEADER_CHARS,
      CONNECTION_TOKEN_CHARS: exports2.CONNECTION_TOKEN_CHARS,
      QUOTED_STRING: exports2.QUOTED_STRING,
      HTAB_SP_VCHAR_OBS_TEXT: exports2.HTAB_SP_VCHAR_OBS_TEXT,
      MAJOR: exports2.MAJOR,
      MINOR: exports2.MINOR,
      SPECIAL_HEADERS: exports2.SPECIAL_HEADERS,
      METHODS_HTTP: exports2.METHODS_HTTP,
      METHODS_ICE: exports2.METHODS_ICE,
      METHODS_RTSP: exports2.METHODS_RTSP,
      METHOD_MAP: exports2.METHOD_MAP,
      H_METHOD_MAP: exports2.H_METHOD_MAP,
      STATUSES_HTTP: exports2.STATUSES_HTTP
    };
  }
});

// node_modules/undici/lib/llhttp/llhttp-wasm.js
var require_llhttp_wasm = __commonJS({
  "node_modules/undici/lib/llhttp/llhttp-wasm.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Buffer: Buffer5 } = __require("node:buffer");
    var wasmBase64 = " ";
    var wasmBuffer;
    Object.defineProperty(module2, "exports", {
      get: /* @__PURE__ */ __name(() => {
        return wasmBuffer ? wasmBuffer : wasmBuffer = Buffer5.from(wasmBase64, "base64");
      }, "get")
    });
  }
});

// node_modules/undici/lib/llhttp/llhttp_simd-wasm.js
var require_llhttp_simd_wasm = __commonJS({
  "node_modules/undici/lib/llhttp/llhttp_simd-wasm.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Buffer: Buffer5 } = __require("node:buffer");
    var wasmBase64 = " ";
    var wasmBuffer;
    Object.defineProperty(module2, "exports", {
      get: /* @__PURE__ */ __name(() => {
        return wasmBuffer ? wasmBuffer : wasmBuffer = Buffer5.from(wasmBase64, "base64");
      }, "get")
    });
  }
});

// node_modules/undici/lib/web/fetch/constants.js
var require_constants5 = __commonJS({
  "node_modules/undici/lib/web/fetch/constants.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var corsSafeListedMethods = (
      /** @type {const} */
      ["GET", "HEAD", "POST"]
    );
    var corsSafeListedMethodsSet = new Set(corsSafeListedMethods);
    var nullBodyStatus = (
      /** @type {const} */
      [101, 204, 205, 304]
    );
    var redirectStatus = (
      /** @type {const} */
      [301, 302, 303, 307, 308]
    );
    var redirectStatusSet = new Set(redirectStatus);
    var badPorts = (
      /** @type {const} */
      [
        "1",
        "7",
        "9",
        "11",
        "13",
        "15",
        "17",
        "19",
        "20",
        "21",
        "22",
        "23",
        "25",
        "37",
        "42",
        "43",
        "53",
        "69",
        "77",
        "79",
        "87",
        "95",
        "101",
        "102",
        "103",
        "104",
        "109",
        "110",
        "111",
        "113",
        "115",
        "117",
        "119",
        "123",
        "135",
        "137",
        "139",
        "143",
        "161",
        "179",
        "389",
        "427",
        "465",
        "512",
        "513",
        "514",
        "515",
        "526",
        "530",
        "531",
        "532",
        "540",
        "548",
        "554",
        "556",
        "563",
        "587",
        "601",
        "636",
        "989",
        "990",
        "993",
        "995",
        "1719",
        "1720",
        "1723",
        "2049",
        "3659",
        "4045",
        "4190",
        "5060",
        "5061",
        "6000",
        "6566",
        "6665",
        "6666",
        "6667",
        "6668",
        "6669",
        "6679",
        "6697",
        "10080"
      ]
    );
    var badPortsSet = new Set(badPorts);
    var referrerPolicyTokens = (
      /** @type {const} */
      [
        "no-referrer",
        "no-referrer-when-downgrade",
        "same-origin",
        "origin",
        "strict-origin",
        "origin-when-cross-origin",
        "strict-origin-when-cross-origin",
        "unsafe-url"
      ]
    );
    var referrerPolicy = (
      /** @type {const} */
      [
        "",
        ...referrerPolicyTokens
      ]
    );
    var referrerPolicyTokensSet = new Set(referrerPolicyTokens);
    var requestRedirect = (
      /** @type {const} */
      ["follow", "manual", "error"]
    );
    var safeMethods = (
      /** @type {const} */
      ["GET", "HEAD", "OPTIONS", "TRACE"]
    );
    var safeMethodsSet = new Set(safeMethods);
    var requestMode = (
      /** @type {const} */
      ["navigate", "same-origin", "no-cors", "cors"]
    );
    var requestCredentials = (
      /** @type {const} */
      ["omit", "same-origin", "include"]
    );
    var requestCache = (
      /** @type {const} */
      [
        "default",
        "no-store",
        "reload",
        "no-cache",
        "force-cache",
        "only-if-cached"
      ]
    );
    var requestBodyHeader = (
      /** @type {const} */
      [
        "content-encoding",
        "content-language",
        "content-location",
        "content-type",
        // See https://github.com/nodejs/undici/issues/2021
        // 'Content-Length' is a forbidden header name, which is typically
        // removed in the Headers implementation. However, undici doesn't
        // filter out headers, so we add it here.
        "content-length"
      ]
    );
    var requestDuplex = (
      /** @type {const} */
      [
        "half"
      ]
    );
    var forbiddenMethods = (
      /** @type {const} */
      ["CONNECT", "TRACE", "TRACK"]
    );
    var forbiddenMethodsSet = new Set(forbiddenMethods);
    var subresource = (
      /** @type {const} */
      [
        "audio",
        "audioworklet",
        "font",
        "image",
        "manifest",
        "paintworklet",
        "script",
        "style",
        "track",
        "video",
        "xslt",
        ""
      ]
    );
    var subresourceSet = new Set(subresource);
    module2.exports = {
      subresource,
      forbiddenMethods,
      requestBodyHeader,
      referrerPolicy,
      requestRedirect,
      requestMode,
      requestCredentials,
      requestCache,
      redirectStatus,
      corsSafeListedMethods,
      nullBodyStatus,
      safeMethods,
      badPorts,
      requestDuplex,
      subresourceSet,
      badPortsSet,
      redirectStatusSet,
      corsSafeListedMethodsSet,
      safeMethodsSet,
      forbiddenMethodsSet,
      referrerPolicyTokens: referrerPolicyTokensSet
    };
  }
});

// node_modules/undici/lib/web/fetch/global.js
var require_global = __commonJS({
  "node_modules/undici/lib/web/fetch/global.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var globalOrigin = Symbol.for("undici.globalOrigin.1");
    function getGlobalOrigin() {
      return globalThis[globalOrigin];
    }
    __name(getGlobalOrigin, "getGlobalOrigin");
    function setGlobalOrigin(newOrigin) {
      if (newOrigin === void 0) {
        Object.defineProperty(globalThis, globalOrigin, {
          value: void 0,
          writable: true,
          enumerable: false,
          configurable: false
        });
        return;
      }
      const parsedURL = new URL(newOrigin);
      if (parsedURL.protocol !== "http:" && parsedURL.protocol !== "https:") {
        throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`);
      }
      Object.defineProperty(globalThis, globalOrigin, {
        value: parsedURL,
        writable: true,
        enumerable: false,
        configurable: false
      });
    }
    __name(setGlobalOrigin, "setGlobalOrigin");
    module2.exports = {
      getGlobalOrigin,
      setGlobalOrigin
    };
  }
});

// node_modules/undici/lib/web/fetch/data-url.js
var require_data_url = __commonJS({
  "node_modules/undici/lib/web/fetch/data-url.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert3 = __require("node:assert");
    var encoder = new TextEncoder();
    var HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+\-.^_|~A-Za-z0-9]+$/;
    var HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/;
    var ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g;
    var HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/;
    function dataURLProcessor(dataURL) {
      assert3(dataURL.protocol === "data:");
      let input = URLSerializer(dataURL, true);
      input = input.slice(5);
      const position = { position: 0 };
      let mimeType = collectASequenceOfCodePointsFast(
        ",",
        input,
        position
      );
      const mimeTypeLength = mimeType.length;
      mimeType = removeASCIIWhitespace(mimeType, true, true);
      if (position.position >= input.length) {
        return "failure";
      }
      position.position++;
      const encodedBody = input.slice(mimeTypeLength + 1);
      let body = stringPercentDecode(encodedBody);
      if (/;(\u0020){0,}base64$/i.test(mimeType)) {
        const stringBody = isomorphicDecode(body);
        body = forgivingBase64(stringBody);
        if (body === "failure") {
          return "failure";
        }
        mimeType = mimeType.slice(0, -6);
        mimeType = mimeType.replace(/(\u0020)+$/, "");
        mimeType = mimeType.slice(0, -1);
      }
      if (mimeType.startsWith(";")) {
        mimeType = "text/plain" + mimeType;
      }
      let mimeTypeRecord = parseMIMEType(mimeType);
      if (mimeTypeRecord === "failure") {
        mimeTypeRecord = parseMIMEType("text/plain;charset=US-ASCII");
      }
      return { mimeType: mimeTypeRecord, body };
    }
    __name(dataURLProcessor, "dataURLProcessor");
    function URLSerializer(url2, excludeFragment = false) {
      if (!excludeFragment) {
        return url2.href;
      }
      const href = url2.href;
      const hashLength = url2.hash.length;
      const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength);
      if (!hashLength && href.endsWith("#")) {
        return serialized.slice(0, -1);
      }
      return serialized;
    }
    __name(URLSerializer, "URLSerializer");
    function collectASequenceOfCodePoints(condition, input, position) {
      let result = "";
      while (position.position < input.length && condition(input[position.position])) {
        result += input[position.position];
        position.position++;
      }
      return result;
    }
    __name(collectASequenceOfCodePoints, "collectASequenceOfCodePoints");
    function collectASequenceOfCodePointsFast(char, input, position) {
      const idx = input.indexOf(char, position.position);
      const start = position.position;
      if (idx === -1) {
        position.position = input.length;
        return input.slice(start);
      }
      position.position = idx;
      return input.slice(start, position.position);
    }
    __name(collectASequenceOfCodePointsFast, "collectASequenceOfCodePointsFast");
    function stringPercentDecode(input) {
      const bytes = encoder.encode(input);
      return percentDecode(bytes);
    }
    __name(stringPercentDecode, "stringPercentDecode");
    function isHexCharByte(byte) {
      return byte >= 48 && byte <= 57 || byte >= 65 && byte <= 70 || byte >= 97 && byte <= 102;
    }
    __name(isHexCharByte, "isHexCharByte");
    function hexByteToNumber(byte) {
      return (
        // 0-9
        byte >= 48 && byte <= 57 ? byte - 48 : (byte & 223) - 55
      );
    }
    __name(hexByteToNumber, "hexByteToNumber");
    function percentDecode(input) {
      const length = input.length;
      const output = new Uint8Array(length);
      let j = 0;
      for (let i = 0; i < length; ++i) {
        const byte = input[i];
        if (byte !== 37) {
          output[j++] = byte;
        } else if (byte === 37 && !(isHexCharByte(input[i + 1]) && isHexCharByte(input[i + 2]))) {
          output[j++] = 37;
        } else {
          output[j++] = hexByteToNumber(input[i + 1]) << 4 | hexByteToNumber(input[i + 2]);
          i += 2;
        }
      }
      return length === j ? output : output.subarray(0, j);
    }
    __name(percentDecode, "percentDecode");
    function parseMIMEType(input) {
      input = removeHTTPWhitespace(input, true, true);
      const position = { position: 0 };
      const type = collectASequenceOfCodePointsFast(
        "/",
        input,
        position
      );
      if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) {
        return "failure";
      }
      if (position.position >= input.length) {
        return "failure";
      }
      position.position++;
      let subtype = collectASequenceOfCodePointsFast(
        ";",
        input,
        position
      );
      subtype = removeHTTPWhitespace(subtype, false, true);
      if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) {
        return "failure";
      }
      const typeLowercase = type.toLowerCase();
      const subtypeLowercase = subtype.toLowerCase();
      const mimeType = {
        type: typeLowercase,
        subtype: subtypeLowercase,
        /** @type {Map<string, string>} */
        parameters: /* @__PURE__ */ new Map(),
        // https://mimesniff.spec.whatwg.org/#mime-type-essence
        essence: `${typeLowercase}/${subtypeLowercase}`
      };
      while (position.position < input.length) {
        position.position++;
        collectASequenceOfCodePoints(
          // https://fetch.spec.whatwg.org/#http-whitespace
          (char) => HTTP_WHITESPACE_REGEX.test(char),
          input,
          position
        );
        let parameterName = collectASequenceOfCodePoints(
          (char) => char !== ";" && char !== "=",
          input,
          position
        );
        parameterName = parameterName.toLowerCase();
        if (position.position < input.length) {
          if (input[position.position] === ";") {
            continue;
          }
          position.position++;
        }
        if (position.position >= input.length) {
          break;
        }
        let parameterValue = null;
        if (input[position.position] === '"') {
          parameterValue = collectAnHTTPQuotedString(input, position, true);
          collectASequenceOfCodePointsFast(
            ";",
            input,
            position
          );
        } else {
          parameterValue = collectASequenceOfCodePointsFast(
            ";",
            input,
            position
          );
          parameterValue = removeHTTPWhitespace(parameterValue, false, true);
          if (parameterValue.length === 0) {
            continue;
          }
        }
        if (parameterName.length !== 0 && HTTP_TOKEN_CODEPOINTS.test(parameterName) && (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && !mimeType.parameters.has(parameterName)) {
          mimeType.parameters.set(parameterName, parameterValue);
        }
      }
      return mimeType;
    }
    __name(parseMIMEType, "parseMIMEType");
    function forgivingBase64(data) {
      data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, "");
      let dataLength = data.length;
      if (dataLength % 4 === 0) {
        if (data.charCodeAt(dataLength - 1) === 61) {
          --dataLength;
          if (data.charCodeAt(dataLength - 1) === 61) {
            --dataLength;
          }
        }
      }
      if (dataLength % 4 === 1) {
        return "failure";
      }
      if (/[^+/0-9A-Za-z]/.test(data.length === dataLength ? data : data.substring(0, dataLength))) {
        return "failure";
      }
      const buffer = Buffer.from(data, "base64");
      return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
    }
    __name(forgivingBase64, "forgivingBase64");
    function collectAnHTTPQuotedString(input, position, extractValue = false) {
      const positionStart = position.position;
      let value = "";
      assert3(input[position.position] === '"');
      position.position++;
      while (true) {
        value += collectASequenceOfCodePoints(
          (char) => char !== '"' && char !== "\\",
          input,
          position
        );
        if (position.position >= input.length) {
          break;
        }
        const quoteOrBackslash = input[position.position];
        position.position++;
        if (quoteOrBackslash === "\\") {
          if (position.position >= input.length) {
            value += "\\";
            break;
          }
          value += input[position.position];
          position.position++;
        } else {
          assert3(quoteOrBackslash === '"');
          break;
        }
      }
      if (extractValue) {
        return value;
      }
      return input.slice(positionStart, position.position);
    }
    __name(collectAnHTTPQuotedString, "collectAnHTTPQuotedString");
    function serializeAMimeType(mimeType) {
      assert3(mimeType !== "failure");
      const { parameters, essence } = mimeType;
      let serialization = essence;
      for (let [name3, value] of parameters.entries()) {
        serialization += ";";
        serialization += name3;
        serialization += "=";
        if (!HTTP_TOKEN_CODEPOINTS.test(value)) {
          value = value.replace(/(\\|")/g, "\\$1");
          value = '"' + value;
          value += '"';
        }
        serialization += value;
      }
      return serialization;
    }
    __name(serializeAMimeType, "serializeAMimeType");
    function isHTTPWhiteSpace(char) {
      return char === 13 || char === 10 || char === 9 || char === 32;
    }
    __name(isHTTPWhiteSpace, "isHTTPWhiteSpace");
    function removeHTTPWhitespace(str2, leading = true, trailing = true) {
      return removeChars(str2, leading, trailing, isHTTPWhiteSpace);
    }
    __name(removeHTTPWhitespace, "removeHTTPWhitespace");
    function isASCIIWhitespace(char) {
      return char === 13 || char === 10 || char === 9 || char === 12 || char === 32;
    }
    __name(isASCIIWhitespace, "isASCIIWhitespace");
    function removeASCIIWhitespace(str2, leading = true, trailing = true) {
      return removeChars(str2, leading, trailing, isASCIIWhitespace);
    }
    __name(removeASCIIWhitespace, "removeASCIIWhitespace");
    function removeChars(str2, leading, trailing, predicate) {
      let lead = 0;
      let trail = str2.length - 1;
      if (leading) {
        while (lead < str2.length && predicate(str2.charCodeAt(lead))) lead++;
      }
      if (trailing) {
        while (trail > 0 && predicate(str2.charCodeAt(trail))) trail--;
      }
      return lead === 0 && trail === str2.length - 1 ? str2 : str2.slice(lead, trail + 1);
    }
    __name(removeChars, "removeChars");
    function isomorphicDecode(input) {
      const length = input.length;
      if ((2 << 15) - 1 > length) {
        return String.fromCharCode.apply(null, input);
      }
      let result = "";
      let i = 0;
      let addition = (2 << 15) - 1;
      while (i < length) {
        if (i + addition > length) {
          addition = length - i;
        }
        result += String.fromCharCode.apply(null, input.subarray(i, i += addition));
      }
      return result;
    }
    __name(isomorphicDecode, "isomorphicDecode");
    function minimizeSupportedMimeType(mimeType) {
      switch (mimeType.essence) {
        case "application/ecmascript":
        case "application/javascript":
        case "application/x-ecmascript":
        case "application/x-javascript":
        case "text/ecmascript":
        case "text/javascript":
        case "text/javascript1.0":
        case "text/javascript1.1":
        case "text/javascript1.2":
        case "text/javascript1.3":
        case "text/javascript1.4":
        case "text/javascript1.5":
        case "text/jscript":
        case "text/livescript":
        case "text/x-ecmascript":
        case "text/x-javascript":
          return "text/javascript";
        case "application/json":
        case "text/json":
          return "application/json";
        case "image/svg+xml":
          return "image/svg+xml";
        case "text/xml":
        case "application/xml":
          return "application/xml";
      }
      if (mimeType.subtype.endsWith("+json")) {
        return "application/json";
      }
      if (mimeType.subtype.endsWith("+xml")) {
        return "application/xml";
      }
      return "";
    }
    __name(minimizeSupportedMimeType, "minimizeSupportedMimeType");
    module2.exports = {
      dataURLProcessor,
      URLSerializer,
      collectASequenceOfCodePoints,
      collectASequenceOfCodePointsFast,
      stringPercentDecode,
      parseMIMEType,
      collectAnHTTPQuotedString,
      serializeAMimeType,
      removeChars,
      removeHTTPWhitespace,
      minimizeSupportedMimeType,
      HTTP_TOKEN_CODEPOINTS,
      isomorphicDecode
    };
  }
});

// node_modules/undici/lib/web/webidl/index.js
var require_webidl = __commonJS({
  "node_modules/undici/lib/web/webidl/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { types: types3, inspect: inspect2 } = __require("node:util");
    var { markAsUncloneable } = __require("node:worker_threads");
    var UNDEFINED = 1;
    var BOOLEAN = 2;
    var STRING = 3;
    var SYMBOL = 4;
    var NUMBER = 5;
    var BIGINT = 6;
    var NULL3 = 7;
    var OBJECT = 8;
    var FunctionPrototypeSymbolHasInstance = Function.call.bind(Function.prototype[Symbol.hasInstance]);
    var webidl = {
      converters: {},
      util: {},
      errors: {},
      is: {}
    };
    webidl.errors.exception = function(message) {
      return new TypeError(`${message.header}: ${message.message}`);
    };
    webidl.errors.conversionFailed = function(opts) {
      const plural = opts.types.length === 1 ? "" : " one of";
      const message = `${opts.argument} could not be converted to${plural}: ${opts.types.join(", ")}.`;
      return webidl.errors.exception({
        header: opts.prefix,
        message
      });
    };
    webidl.errors.invalidArgument = function(context2) {
      return webidl.errors.exception({
        header: context2.prefix,
        message: `"${context2.value}" is an invalid ${context2.type}.`
      });
    };
    webidl.brandCheck = function(V2, I2) {
      if (!FunctionPrototypeSymbolHasInstance(I2, V2)) {
        const err = new TypeError("Illegal invocation");
        err.code = "ERR_INVALID_THIS";
        throw err;
      }
    };
    webidl.brandCheckMultiple = function(List2) {
      const prototypes = List2.map((c3) => webidl.util.MakeTypeAssertion(c3));
      return (V2) => {
        if (prototypes.every((typeCheck) => !typeCheck(V2))) {
          const err = new TypeError("Illegal invocation");
          err.code = "ERR_INVALID_THIS";
          throw err;
        }
      };
    };
    webidl.argumentLengthCheck = function({ length }, min, ctx) {
      if (length < min) {
        throw webidl.errors.exception({
          message: `${min} argument${min !== 1 ? "s" : ""} required, but${length ? " only" : ""} ${length} found.`,
          header: ctx
        });
      }
    };
    webidl.illegalConstructor = function() {
      throw webidl.errors.exception({
        header: "TypeError",
        message: "Illegal constructor"
      });
    };
    webidl.util.MakeTypeAssertion = function(I2) {
      return (O) => FunctionPrototypeSymbolHasInstance(I2, O);
    };
    webidl.util.Type = function(V2) {
      switch (typeof V2) {
        case "undefined":
          return UNDEFINED;
        case "boolean":
          return BOOLEAN;
        case "string":
          return STRING;
        case "symbol":
          return SYMBOL;
        case "number":
          return NUMBER;
        case "bigint":
          return BIGINT;
        case "function":
        case "object": {
          if (V2 === null) {
            return NULL3;
          }
          return OBJECT;
        }
      }
    };
    webidl.util.Types = {
      UNDEFINED,
      BOOLEAN,
      STRING,
      SYMBOL,
      NUMBER,
      BIGINT,
      NULL: NULL3,
      OBJECT
    };
    webidl.util.TypeValueToString = function(o2) {
      switch (webidl.util.Type(o2)) {
        case UNDEFINED:
          return "Undefined";
        case BOOLEAN:
          return "Boolean";
        case STRING:
          return "String";
        case SYMBOL:
          return "Symbol";
        case NUMBER:
          return "Number";
        case BIGINT:
          return "BigInt";
        case NULL3:
          return "Null";
        case OBJECT:
          return "Object";
      }
    };
    webidl.util.markAsUncloneable = markAsUncloneable || (() => {
    });
    webidl.util.ConvertToInt = function(V2, bitLength, signedness, opts) {
      let upperBound;
      let lowerBound;
      if (bitLength === 64) {
        upperBound = Math.pow(2, 53) - 1;
        if (signedness === "unsigned") {
          lowerBound = 0;
        } else {
          lowerBound = Math.pow(-2, 53) + 1;
        }
      } else if (signedness === "unsigned") {
        lowerBound = 0;
        upperBound = Math.pow(2, bitLength) - 1;
      } else {
        lowerBound = Math.pow(-2, bitLength) - 1;
        upperBound = Math.pow(2, bitLength - 1) - 1;
      }
      let x = Number(V2);
      if (x === 0) {
        x = 0;
      }
      if (opts?.enforceRange === true) {
        if (Number.isNaN(x) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY) {
          throw webidl.errors.exception({
            header: "Integer conversion",
            message: `Could not convert ${webidl.util.Stringify(V2)} to an integer.`
          });
        }
        x = webidl.util.IntegerPart(x);
        if (x < lowerBound || x > upperBound) {
          throw webidl.errors.exception({
            header: "Integer conversion",
            message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`
          });
        }
        return x;
      }
      if (!Number.isNaN(x) && opts?.clamp === true) {
        x = Math.min(Math.max(x, lowerBound), upperBound);
        if (Math.floor(x) % 2 === 0) {
          x = Math.floor(x);
        } else {
          x = Math.ceil(x);
        }
        return x;
      }
      if (Number.isNaN(x) || x === 0 && Object.is(0, x) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY) {
        return 0;
      }
      x = webidl.util.IntegerPart(x);
      x = x % Math.pow(2, bitLength);
      if (signedness === "signed" && x >= Math.pow(2, bitLength) - 1) {
        return x - Math.pow(2, bitLength);
      }
      return x;
    };
    webidl.util.IntegerPart = function(n2) {
      const r3 = Math.floor(Math.abs(n2));
      if (n2 < 0) {
        return -1 * r3;
      }
      return r3;
    };
    webidl.util.Stringify = function(V2) {
      const type = webidl.util.Type(V2);
      switch (type) {
        case SYMBOL:
          return `Symbol(${V2.description})`;
        case OBJECT:
          return inspect2(V2);
        case STRING:
          return `"${V2}"`;
        case BIGINT:
          return `${V2}n`;
        default:
          return `${V2}`;
      }
    };
    webidl.sequenceConverter = function(converter) {
      return (V2, prefix, argument, Iterable) => {
        if (webidl.util.Type(V2) !== OBJECT) {
          throw webidl.errors.exception({
            header: prefix,
            message: `${argument} (${webidl.util.Stringify(V2)}) is not iterable.`
          });
        }
        const method = typeof Iterable === "function" ? Iterable() : V2?.[Symbol.iterator]?.();
        const seq = [];
        let index = 0;
        if (method === void 0 || typeof method.next !== "function") {
          throw webidl.errors.exception({
            header: prefix,
            message: `${argument} is not iterable.`
          });
        }
        while (true) {
          const { done, value } = method.next();
          if (done) {
            break;
          }
          seq.push(converter(value, prefix, `${argument}[${index++}]`));
        }
        return seq;
      };
    };
    webidl.recordConverter = function(keyConverter, valueConverter) {
      return (O, prefix, argument) => {
        if (webidl.util.Type(O) !== OBJECT) {
          throw webidl.errors.exception({
            header: prefix,
            message: `${argument} ("${webidl.util.TypeValueToString(O)}") is not an Object.`
          });
        }
        const result = {};
        if (!types3.isProxy(O)) {
          const keys2 = [...Object.getOwnPropertyNames(O), ...Object.getOwnPropertySymbols(O)];
          for (const key of keys2) {
            const keyName2 = webidl.util.Stringify(key);
            const typedKey = keyConverter(key, prefix, `Key ${keyName2} in ${argument}`);
            const typedValue = valueConverter(O[key], prefix, `${argument}[${keyName2}]`);
            result[typedKey] = typedValue;
          }
          return result;
        }
        const keys = Reflect.ownKeys(O);
        for (const key of keys) {
          const desc2 = Reflect.getOwnPropertyDescriptor(O, key);
          if (desc2?.enumerable) {
            const typedKey = keyConverter(key, prefix, argument);
            const typedValue = valueConverter(O[key], prefix, argument);
            result[typedKey] = typedValue;
          }
        }
        return result;
      };
    };
    webidl.interfaceConverter = function(TypeCheck, name3) {
      return (V2, prefix, argument) => {
        if (!TypeCheck(V2)) {
          throw webidl.errors.exception({
            header: prefix,
            message: `Expected ${argument} ("${webidl.util.Stringify(V2)}") to be an instance of ${name3}.`
          });
        }
        return V2;
      };
    };
    webidl.dictionaryConverter = function(converters) {
      return (dictionary, prefix, argument) => {
        const dict = {};
        if (dictionary != null && webidl.util.Type(dictionary) !== OBJECT) {
          throw webidl.errors.exception({
            header: prefix,
            message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`
          });
        }
        for (const options2 of converters) {
          const { key, defaultValue, required, converter } = options2;
          if (required === true) {
            if (dictionary == null || !Object.hasOwn(dictionary, key)) {
              throw webidl.errors.exception({
                header: prefix,
                message: `Missing required key "${key}".`
              });
            }
          }
          let value = dictionary?.[key];
          const hasDefault = defaultValue !== void 0;
          if (hasDefault && value === void 0) {
            value = defaultValue();
          }
          if (required || hasDefault || value !== void 0) {
            value = converter(value, prefix, `${argument}.${key}`);
            if (options2.allowedValues && !options2.allowedValues.includes(value)) {
              throw webidl.errors.exception({
                header: prefix,
                message: `${value} is not an accepted type. Expected one of ${options2.allowedValues.join(", ")}.`
              });
            }
            dict[key] = value;
          }
        }
        return dict;
      };
    };
    webidl.nullableConverter = function(converter) {
      return (V2, prefix, argument) => {
        if (V2 === null) {
          return V2;
        }
        return converter(V2, prefix, argument);
      };
    };
    webidl.is.USVString = function(value) {
      return typeof value === "string" && value.isWellFormed();
    };
    webidl.is.ReadableStream = webidl.util.MakeTypeAssertion(ReadableStream);
    webidl.is.Blob = webidl.util.MakeTypeAssertion(Blob);
    webidl.is.URLSearchParams = webidl.util.MakeTypeAssertion(URLSearchParams);
    webidl.is.File = webidl.util.MakeTypeAssertion(File);
    webidl.is.URL = webidl.util.MakeTypeAssertion(URL);
    webidl.is.AbortSignal = webidl.util.MakeTypeAssertion(AbortSignal);
    webidl.is.MessagePort = webidl.util.MakeTypeAssertion(MessagePort);
    webidl.converters.DOMString = function(V2, prefix, argument, opts) {
      if (V2 === null && opts?.legacyNullToEmptyString) {
        return "";
      }
      if (typeof V2 === "symbol") {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} is a symbol, which cannot be converted to a DOMString.`
        });
      }
      return String(V2);
    };
    webidl.converters.ByteString = function(V2, prefix, argument) {
      if (typeof V2 === "symbol") {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} is a symbol, which cannot be converted to a ByteString.`
        });
      }
      const x = String(V2);
      for (let index = 0; index < x.length; index++) {
        if (x.charCodeAt(index) > 255) {
          throw new TypeError(
            `Cannot convert argument to a ByteString because the character at index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.`
          );
        }
      }
      return x;
    };
    webidl.converters.USVString = function(value) {
      if (typeof value === "string") {
        return value.toWellFormed();
      }
      return `${value}`.toWellFormed();
    };
    webidl.converters.boolean = function(V2) {
      const x = Boolean(V2);
      return x;
    };
    webidl.converters.any = function(V2) {
      return V2;
    };
    webidl.converters["long long"] = function(V2, prefix, argument) {
      const x = webidl.util.ConvertToInt(V2, 64, "signed", void 0, prefix, argument);
      return x;
    };
    webidl.converters["unsigned long long"] = function(V2, prefix, argument) {
      const x = webidl.util.ConvertToInt(V2, 64, "unsigned", void 0, prefix, argument);
      return x;
    };
    webidl.converters["unsigned long"] = function(V2, prefix, argument) {
      const x = webidl.util.ConvertToInt(V2, 32, "unsigned", void 0, prefix, argument);
      return x;
    };
    webidl.converters["unsigned short"] = function(V2, prefix, argument, opts) {
      const x = webidl.util.ConvertToInt(V2, 16, "unsigned", opts, prefix, argument);
      return x;
    };
    webidl.converters.ArrayBuffer = function(V2, prefix, argument, opts) {
      if (webidl.util.Type(V2) !== OBJECT || !types3.isAnyArrayBuffer(V2)) {
        throw webidl.errors.conversionFailed({
          prefix,
          argument: `${argument} ("${webidl.util.Stringify(V2)}")`,
          types: ["ArrayBuffer"]
        });
      }
      if (opts?.allowShared === false && types3.isSharedArrayBuffer(V2)) {
        throw webidl.errors.exception({
          header: "ArrayBuffer",
          message: "SharedArrayBuffer is not allowed."
        });
      }
      if (V2.resizable || V2.growable) {
        throw webidl.errors.exception({
          header: "ArrayBuffer",
          message: "Received a resizable ArrayBuffer."
        });
      }
      return V2;
    };
    webidl.converters.TypedArray = function(V2, T, prefix, name3, opts) {
      if (webidl.util.Type(V2) !== OBJECT || !types3.isTypedArray(V2) || V2.constructor.name !== T.name) {
        throw webidl.errors.conversionFailed({
          prefix,
          argument: `${name3} ("${webidl.util.Stringify(V2)}")`,
          types: [T.name]
        });
      }
      if (opts?.allowShared === false && types3.isSharedArrayBuffer(V2.buffer)) {
        throw webidl.errors.exception({
          header: "ArrayBuffer",
          message: "SharedArrayBuffer is not allowed."
        });
      }
      if (V2.buffer.resizable || V2.buffer.growable) {
        throw webidl.errors.exception({
          header: "ArrayBuffer",
          message: "Received a resizable ArrayBuffer."
        });
      }
      return V2;
    };
    webidl.converters.DataView = function(V2, prefix, name3, opts) {
      if (webidl.util.Type(V2) !== OBJECT || !types3.isDataView(V2)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${name3} is not a DataView.`
        });
      }
      if (opts?.allowShared === false && types3.isSharedArrayBuffer(V2.buffer)) {
        throw webidl.errors.exception({
          header: "ArrayBuffer",
          message: "SharedArrayBuffer is not allowed."
        });
      }
      if (V2.buffer.resizable || V2.buffer.growable) {
        throw webidl.errors.exception({
          header: "ArrayBuffer",
          message: "Received a resizable ArrayBuffer."
        });
      }
      return V2;
    };
    webidl.converters["sequence<ByteString>"] = webidl.sequenceConverter(
      webidl.converters.ByteString
    );
    webidl.converters["sequence<sequence<ByteString>>"] = webidl.sequenceConverter(
      webidl.converters["sequence<ByteString>"]
    );
    webidl.converters["record<ByteString, ByteString>"] = webidl.recordConverter(
      webidl.converters.ByteString,
      webidl.converters.ByteString
    );
    webidl.converters.Blob = webidl.interfaceConverter(webidl.is.Blob, "Blob");
    webidl.converters.AbortSignal = webidl.interfaceConverter(
      webidl.is.AbortSignal,
      "AbortSignal"
    );
    module2.exports = {
      webidl
    };
  }
});

// node_modules/undici/lib/web/fetch/util.js
var require_util2 = __commonJS({
  "node_modules/undici/lib/web/fetch/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Transform: Transform2 } = __require("node:stream");
    var zlib2 = __require("node:zlib");
    var { redirectStatusSet, referrerPolicyTokens, badPortsSet } = require_constants5();
    var { getGlobalOrigin } = require_global();
    var { collectASequenceOfCodePoints, collectAnHTTPQuotedString, removeChars, parseMIMEType } = require_data_url();
    var { performance: performance2 } = __require("node:perf_hooks");
    var { ReadableStreamFrom: ReadableStreamFrom2, isValidHTTPToken, normalizedMethodRecordsBase } = require_util();
    var assert3 = __require("node:assert");
    var { isUint8Array } = __require("node:util/types");
    var { webidl } = require_webidl();
    function responseURL(response) {
      const urlList = response.urlList;
      const length = urlList.length;
      return length === 0 ? null : urlList[length - 1].toString();
    }
    __name(responseURL, "responseURL");
    function responseLocationURL(response, requestFragment) {
      if (!redirectStatusSet.has(response.status)) {
        return null;
      }
      let location = response.headersList.get("location", true);
      if (location !== null && isValidHeaderValue(location)) {
        if (!isValidEncodedURL(location)) {
          location = normalizeBinaryStringToUtf8(location);
        }
        location = new URL(location, responseURL(response));
      }
      if (location && !location.hash) {
        location.hash = requestFragment;
      }
      return location;
    }
    __name(responseLocationURL, "responseLocationURL");
    function isValidEncodedURL(url2) {
      for (let i = 0; i < url2.length; ++i) {
        const code2 = url2.charCodeAt(i);
        if (code2 > 126 || // Non-US-ASCII + DEL
        code2 < 32) {
          return false;
        }
      }
      return true;
    }
    __name(isValidEncodedURL, "isValidEncodedURL");
    function normalizeBinaryStringToUtf8(value) {
      return Buffer.from(value, "binary").toString("utf8");
    }
    __name(normalizeBinaryStringToUtf8, "normalizeBinaryStringToUtf8");
    function requestCurrentURL(request4) {
      return request4.urlList[request4.urlList.length - 1];
    }
    __name(requestCurrentURL, "requestCurrentURL");
    function requestBadPort(request4) {
      const url2 = requestCurrentURL(request4);
      if (urlIsHttpHttpsScheme(url2) && badPortsSet.has(url2.port)) {
        return "blocked";
      }
      return "allowed";
    }
    __name(requestBadPort, "requestBadPort");
    function isErrorLike(object) {
      return object instanceof Error || (object?.constructor?.name === "Error" || object?.constructor?.name === "DOMException");
    }
    __name(isErrorLike, "isErrorLike");
    function isValidReasonPhrase(statusText) {
      for (let i = 0; i < statusText.length; ++i) {
        const c3 = statusText.charCodeAt(i);
        if (!(c3 === 9 || // HTAB
        c3 >= 32 && c3 <= 126 || // SP / VCHAR
        c3 >= 128 && c3 <= 255)) {
          return false;
        }
      }
      return true;
    }
    __name(isValidReasonPhrase, "isValidReasonPhrase");
    var isValidHeaderName = isValidHTTPToken;
    function isValidHeaderValue(potentialValue) {
      return (potentialValue[0] === "	" || potentialValue[0] === " " || potentialValue[potentialValue.length - 1] === "	" || potentialValue[potentialValue.length - 1] === " " || potentialValue.includes("\n") || potentialValue.includes("\r") || potentialValue.includes("\0")) === false;
    }
    __name(isValidHeaderValue, "isValidHeaderValue");
    function parseReferrerPolicy(actualResponse) {
      const policyHeader = (actualResponse.headersList.get("referrer-policy", true) ?? "").split(",");
      let policy = "";
      if (policyHeader.length) {
        for (let i = policyHeader.length; i !== 0; i--) {
          const token2 = policyHeader[i - 1].trim();
          if (referrerPolicyTokens.has(token2)) {
            policy = token2;
            break;
          }
        }
      }
      return policy;
    }
    __name(parseReferrerPolicy, "parseReferrerPolicy");
    function setRequestReferrerPolicyOnRedirect(request4, actualResponse) {
      const policy = parseReferrerPolicy(actualResponse);
      if (policy !== "") {
        request4.referrerPolicy = policy;
      }
    }
    __name(setRequestReferrerPolicyOnRedirect, "setRequestReferrerPolicyOnRedirect");
    function crossOriginResourcePolicyCheck() {
      return "allowed";
    }
    __name(crossOriginResourcePolicyCheck, "crossOriginResourcePolicyCheck");
    function corsCheck() {
      return "success";
    }
    __name(corsCheck, "corsCheck");
    function TAOCheck() {
      return "success";
    }
    __name(TAOCheck, "TAOCheck");
    function appendFetchMetadata(httpRequest) {
      let header = null;
      header = httpRequest.mode;
      httpRequest.headersList.set("sec-fetch-mode", header, true);
    }
    __name(appendFetchMetadata, "appendFetchMetadata");
    function appendRequestOriginHeader(request4) {
      let serializedOrigin = request4.origin;
      if (serializedOrigin === "client" || serializedOrigin === void 0) {
        return;
      }
      if (request4.responseTainting === "cors" || request4.mode === "websocket") {
        request4.headersList.append("origin", serializedOrigin, true);
      } else if (request4.method !== "GET" && request4.method !== "HEAD") {
        switch (request4.referrerPolicy) {
          case "no-referrer":
            serializedOrigin = null;
            break;
          case "no-referrer-when-downgrade":
          case "strict-origin":
          case "strict-origin-when-cross-origin":
            if (request4.origin && urlHasHttpsScheme(request4.origin) && !urlHasHttpsScheme(requestCurrentURL(request4))) {
              serializedOrigin = null;
            }
            break;
          case "same-origin":
            if (!sameOrigin(request4, requestCurrentURL(request4))) {
              serializedOrigin = null;
            }
            break;
          default:
        }
        request4.headersList.append("origin", serializedOrigin, true);
      }
    }
    __name(appendRequestOriginHeader, "appendRequestOriginHeader");
    function coarsenTime(timestamp, crossOriginIsolatedCapability) {
      return timestamp;
    }
    __name(coarsenTime, "coarsenTime");
    function clampAndCoarsenConnectionTimingInfo(connectionTimingInfo, defaultStartTime, crossOriginIsolatedCapability) {
      if (!connectionTimingInfo?.startTime || connectionTimingInfo.startTime < defaultStartTime) {
        return {
          domainLookupStartTime: defaultStartTime,
          domainLookupEndTime: defaultStartTime,
          connectionStartTime: defaultStartTime,
          connectionEndTime: defaultStartTime,
          secureConnectionStartTime: defaultStartTime,
          ALPNNegotiatedProtocol: connectionTimingInfo?.ALPNNegotiatedProtocol
        };
      }
      return {
        domainLookupStartTime: coarsenTime(connectionTimingInfo.domainLookupStartTime, crossOriginIsolatedCapability),
        domainLookupEndTime: coarsenTime(connectionTimingInfo.domainLookupEndTime, crossOriginIsolatedCapability),
        connectionStartTime: coarsenTime(connectionTimingInfo.connectionStartTime, crossOriginIsolatedCapability),
        connectionEndTime: coarsenTime(connectionTimingInfo.connectionEndTime, crossOriginIsolatedCapability),
        secureConnectionStartTime: coarsenTime(connectionTimingInfo.secureConnectionStartTime, crossOriginIsolatedCapability),
        ALPNNegotiatedProtocol: connectionTimingInfo.ALPNNegotiatedProtocol
      };
    }
    __name(clampAndCoarsenConnectionTimingInfo, "clampAndCoarsenConnectionTimingInfo");
    function coarsenedSharedCurrentTime(crossOriginIsolatedCapability) {
      return coarsenTime(performance2.now(), crossOriginIsolatedCapability);
    }
    __name(coarsenedSharedCurrentTime, "coarsenedSharedCurrentTime");
    function createOpaqueTimingInfo(timingInfo) {
      return {
        startTime: timingInfo.startTime ?? 0,
        redirectStartTime: 0,
        redirectEndTime: 0,
        postRedirectStartTime: timingInfo.startTime ?? 0,
        finalServiceWorkerStartTime: 0,
        finalNetworkResponseStartTime: 0,
        finalNetworkRequestStartTime: 0,
        endTime: 0,
        encodedBodySize: 0,
        decodedBodySize: 0,
        finalConnectionTimingInfo: null
      };
    }
    __name(createOpaqueTimingInfo, "createOpaqueTimingInfo");
    function makePolicyContainer() {
      return {
        referrerPolicy: "strict-origin-when-cross-origin"
      };
    }
    __name(makePolicyContainer, "makePolicyContainer");
    function clonePolicyContainer(policyContainer) {
      return {
        referrerPolicy: policyContainer.referrerPolicy
      };
    }
    __name(clonePolicyContainer, "clonePolicyContainer");
    function determineRequestsReferrer(request4) {
      const policy = request4.referrerPolicy;
      assert3(policy);
      let referrerSource = null;
      if (request4.referrer === "client") {
        const globalOrigin = getGlobalOrigin();
        if (!globalOrigin || globalOrigin.origin === "null") {
          return "no-referrer";
        }
        referrerSource = new URL(globalOrigin);
      } else if (webidl.is.URL(request4.referrer)) {
        referrerSource = request4.referrer;
      }
      let referrerURL = stripURLForReferrer(referrerSource);
      const referrerOrigin = stripURLForReferrer(referrerSource, true);
      if (referrerURL.toString().length > 4096) {
        referrerURL = referrerOrigin;
      }
      switch (policy) {
        case "no-referrer":
          return "no-referrer";
        case "origin":
          if (referrerOrigin != null) {
            return referrerOrigin;
          }
          return stripURLForReferrer(referrerSource, true);
        case "unsafe-url":
          return referrerURL;
        case "strict-origin": {
          const currentURL = requestCurrentURL(request4);
          if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
            return "no-referrer";
          }
          return referrerOrigin;
        }
        case "strict-origin-when-cross-origin": {
          const currentURL = requestCurrentURL(request4);
          if (sameOrigin(referrerURL, currentURL)) {
            return referrerURL;
          }
          if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
            return "no-referrer";
          }
          return referrerOrigin;
        }
        case "same-origin":
          if (sameOrigin(request4, referrerURL)) {
            return referrerURL;
          }
          return "no-referrer";
        case "origin-when-cross-origin":
          if (sameOrigin(request4, referrerURL)) {
            return referrerURL;
          }
          return referrerOrigin;
        case "no-referrer-when-downgrade": {
          const currentURL = requestCurrentURL(request4);
          if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
            return "no-referrer";
          }
          return referrerOrigin;
        }
      }
    }
    __name(determineRequestsReferrer, "determineRequestsReferrer");
    function stripURLForReferrer(url2, originOnly = false) {
      assert3(webidl.is.URL(url2));
      url2 = new URL(url2);
      if (urlIsLocal(url2)) {
        return "no-referrer";
      }
      url2.username = "";
      url2.password = "";
      url2.hash = "";
      if (originOnly === true) {
        url2.pathname = "";
        url2.search = "";
      }
      return url2;
    }
    __name(stripURLForReferrer, "stripURLForReferrer");
    var potentialleTrustworthyIPv4RegExp = new RegExp("^(?:(?:127\\.)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){2}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9]))$");
    var potentialleTrustworthyIPv6RegExp = new RegExp("^(?:(?:(?:0{1,4}):){7}(?:(?:0{0,3}1))|(?:(?:0{1,4}):){1,6}(?::(?:0{0,3}1))|(?:::(?:0{0,3}1))|)$");
    function isOriginIPPotentiallyTrustworthy(origin) {
      if (origin.includes(":")) {
        if (origin[0] === "[" && origin[origin.length - 1] === "]") {
          origin = origin.slice(1, -1);
        }
        return potentialleTrustworthyIPv6RegExp.test(origin);
      }
      return potentialleTrustworthyIPv4RegExp.test(origin);
    }
    __name(isOriginIPPotentiallyTrustworthy, "isOriginIPPotentiallyTrustworthy");
    function isOriginPotentiallyTrustworthy(origin) {
      if (origin == null || origin === "null") {
        return false;
      }
      origin = new URL(origin);
      if (origin.protocol === "https:" || origin.protocol === "wss:") {
        return true;
      }
      if (isOriginIPPotentiallyTrustworthy(origin.hostname)) {
        return true;
      }
      if (origin.hostname === "localhost" || origin.hostname === "localhost.") {
        return true;
      }
      if (origin.hostname.endsWith(".localhost") || origin.hostname.endsWith(".localhost.")) {
        return true;
      }
      if (origin.protocol === "file:") {
        return true;
      }
      return false;
    }
    __name(isOriginPotentiallyTrustworthy, "isOriginPotentiallyTrustworthy");
    function isURLPotentiallyTrustworthy(url2) {
      if (!webidl.is.URL(url2)) {
        return false;
      }
      if (url2.href === "about:blank" || url2.href === "about:srcdoc") {
        return true;
      }
      if (url2.protocol === "data:") return true;
      if (url2.protocol === "blob:") return true;
      return isOriginPotentiallyTrustworthy(url2.origin);
    }
    __name(isURLPotentiallyTrustworthy, "isURLPotentiallyTrustworthy");
    function tryUpgradeRequestToAPotentiallyTrustworthyURL(request4) {
    }
    __name(tryUpgradeRequestToAPotentiallyTrustworthyURL, "tryUpgradeRequestToAPotentiallyTrustworthyURL");
    function sameOrigin(A, B) {
      if (A.origin === B.origin && A.origin === "null") {
        return true;
      }
      if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {
        return true;
      }
      return false;
    }
    __name(sameOrigin, "sameOrigin");
    function isAborted2(fetchParams) {
      return fetchParams.controller.state === "aborted";
    }
    __name(isAborted2, "isAborted");
    function isCancelled(fetchParams) {
      return fetchParams.controller.state === "aborted" || fetchParams.controller.state === "terminated";
    }
    __name(isCancelled, "isCancelled");
    function normalizeMethod(method) {
      return normalizedMethodRecordsBase[method.toLowerCase()] ?? method;
    }
    __name(normalizeMethod, "normalizeMethod");
    function serializeJavascriptValueToJSONString(value) {
      const result = JSON.stringify(value);
      if (result === void 0) {
        throw new TypeError("Value is not JSON serializable");
      }
      assert3(typeof result === "string");
      return result;
    }
    __name(serializeJavascriptValueToJSONString, "serializeJavascriptValueToJSONString");
    var esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));
    function createIterator(name3, kInternalIterator, keyIndex = 0, valueIndex = 1) {
      class FastIterableIterator {
        static {
          __name(this, "FastIterableIterator");
        }
        /** @type {any} */
        #target;
        /** @type {'key' | 'value' | 'key+value'} */
        #kind;
        /** @type {number} */
        #index;
        /**
         * @see https://webidl.spec.whatwg.org/#dfn-default-iterator-object
         * @param {unknown} target
         * @param {'key' | 'value' | 'key+value'} kind
         */
        constructor(target, kind) {
          this.#target = target;
          this.#kind = kind;
          this.#index = 0;
        }
        next() {
          if (typeof this !== "object" || this === null || !(#target in this)) {
            throw new TypeError(
              `'next' called on an object that does not implement interface ${name3} Iterator.`
            );
          }
          const index = this.#index;
          const values = kInternalIterator(this.#target);
          const len = values.length;
          if (index >= len) {
            return {
              value: void 0,
              done: true
            };
          }
          const { [keyIndex]: key, [valueIndex]: value } = values[index];
          this.#index = index + 1;
          let result;
          switch (this.#kind) {
            case "key":
              result = key;
              break;
            case "value":
              result = value;
              break;
            case "key+value":
              result = [key, value];
              break;
          }
          return {
            value: result,
            done: false
          };
        }
      }
      delete FastIterableIterator.prototype.constructor;
      Object.setPrototypeOf(FastIterableIterator.prototype, esIteratorPrototype);
      Object.defineProperties(FastIterableIterator.prototype, {
        [Symbol.toStringTag]: {
          writable: false,
          enumerable: false,
          configurable: true,
          value: `${name3} Iterator`
        },
        next: { writable: true, enumerable: true, configurable: true }
      });
      return function(target, kind) {
        return new FastIterableIterator(target, kind);
      };
    }
    __name(createIterator, "createIterator");
    function iteratorMixin(name3, object, kInternalIterator, keyIndex = 0, valueIndex = 1) {
      const makeIterator = createIterator(name3, kInternalIterator, keyIndex, valueIndex);
      const properties = {
        keys: {
          writable: true,
          enumerable: true,
          configurable: true,
          value: /* @__PURE__ */ __name(function keys() {
            webidl.brandCheck(this, object);
            return makeIterator(this, "key");
          }, "keys")
        },
        values: {
          writable: true,
          enumerable: true,
          configurable: true,
          value: /* @__PURE__ */ __name(function values() {
            webidl.brandCheck(this, object);
            return makeIterator(this, "value");
          }, "values")
        },
        entries: {
          writable: true,
          enumerable: true,
          configurable: true,
          value: /* @__PURE__ */ __name(function entries() {
            webidl.brandCheck(this, object);
            return makeIterator(this, "key+value");
          }, "entries")
        },
        forEach: {
          writable: true,
          enumerable: true,
          configurable: true,
          value: /* @__PURE__ */ __name(function forEach2(callbackfn, thisArg = globalThis) {
            webidl.brandCheck(this, object);
            webidl.argumentLengthCheck(arguments, 1, `${name3}.forEach`);
            if (typeof callbackfn !== "function") {
              throw new TypeError(
                `Failed to execute 'forEach' on '${name3}': parameter 1 is not of type 'Function'.`
              );
            }
            for (const { 0: key, 1: value } of makeIterator(this, "key+value")) {
              callbackfn.call(thisArg, value, key, this);
            }
          }, "forEach")
        }
      };
      return Object.defineProperties(object.prototype, {
        ...properties,
        [Symbol.iterator]: {
          writable: true,
          enumerable: false,
          configurable: true,
          value: properties.entries.value
        }
      });
    }
    __name(iteratorMixin, "iteratorMixin");
    function fullyReadBody(body, processBody, processBodyError) {
      const successSteps = processBody;
      const errorSteps = processBodyError;
      try {
        const reader = body.stream.getReader();
        readAllBytes(reader, successSteps, errorSteps);
      } catch (e2) {
        errorSteps(e2);
      }
    }
    __name(fullyReadBody, "fullyReadBody");
    function readableStreamClose(controller) {
      try {
        controller.close();
        controller.byobRequest?.respond(0);
      } catch (err) {
        if (!err.message.includes("Controller is already closed") && !err.message.includes("ReadableStream is already closed")) {
          throw err;
        }
      }
    }
    __name(readableStreamClose, "readableStreamClose");
    var invalidIsomorphicEncodeValueRegex = /[^\x00-\xFF]/;
    function isomorphicEncode(input) {
      assert3(!invalidIsomorphicEncodeValueRegex.test(input));
      return input;
    }
    __name(isomorphicEncode, "isomorphicEncode");
    async function readAllBytes(reader, successSteps, failureSteps) {
      try {
        const bytes = [];
        let byteLength = 0;
        do {
          const { done, value: chunk } = await reader.read();
          if (done) {
            successSteps(Buffer.concat(bytes, byteLength));
            return;
          }
          if (!isUint8Array(chunk)) {
            failureSteps(new TypeError("Received non-Uint8Array chunk"));
            return;
          }
          bytes.push(chunk);
          byteLength += chunk.length;
        } while (true);
      } catch (e2) {
        failureSteps(e2);
      }
    }
    __name(readAllBytes, "readAllBytes");
    function urlIsLocal(url2) {
      assert3("protocol" in url2);
      const protocol = url2.protocol;
      return protocol === "about:" || protocol === "blob:" || protocol === "data:";
    }
    __name(urlIsLocal, "urlIsLocal");
    function urlHasHttpsScheme(url2) {
      return typeof url2 === "string" && url2[5] === ":" && url2[0] === "h" && url2[1] === "t" && url2[2] === "t" && url2[3] === "p" && url2[4] === "s" || url2.protocol === "https:";
    }
    __name(urlHasHttpsScheme, "urlHasHttpsScheme");
    function urlIsHttpHttpsScheme(url2) {
      assert3("protocol" in url2);
      const protocol = url2.protocol;
      return protocol === "http:" || protocol === "https:";
    }
    __name(urlIsHttpHttpsScheme, "urlIsHttpHttpsScheme");
    function simpleRangeHeaderValue(value, allowWhitespace) {
      const data = value;
      if (!data.startsWith("bytes")) {
        return "failure";
      }
      const position = { position: 5 };
      if (allowWhitespace) {
        collectASequenceOfCodePoints(
          (char) => char === "	" || char === " ",
          data,
          position
        );
      }
      if (data.charCodeAt(position.position) !== 61) {
        return "failure";
      }
      position.position++;
      if (allowWhitespace) {
        collectASequenceOfCodePoints(
          (char) => char === "	" || char === " ",
          data,
          position
        );
      }
      const rangeStart = collectASequenceOfCodePoints(
        (char) => {
          const code2 = char.charCodeAt(0);
          return code2 >= 48 && code2 <= 57;
        },
        data,
        position
      );
      const rangeStartValue = rangeStart.length ? Number(rangeStart) : null;
      if (allowWhitespace) {
        collectASequenceOfCodePoints(
          (char) => char === "	" || char === " ",
          data,
          position
        );
      }
      if (data.charCodeAt(position.position) !== 45) {
        return "failure";
      }
      position.position++;
      if (allowWhitespace) {
        collectASequenceOfCodePoints(
          (char) => char === "	" || char === " ",
          data,
          position
        );
      }
      const rangeEnd = collectASequenceOfCodePoints(
        (char) => {
          const code2 = char.charCodeAt(0);
          return code2 >= 48 && code2 <= 57;
        },
        data,
        position
      );
      const rangeEndValue = rangeEnd.length ? Number(rangeEnd) : null;
      if (position.position < data.length) {
        return "failure";
      }
      if (rangeEndValue === null && rangeStartValue === null) {
        return "failure";
      }
      if (rangeStartValue > rangeEndValue) {
        return "failure";
      }
      return { rangeStartValue, rangeEndValue };
    }
    __name(simpleRangeHeaderValue, "simpleRangeHeaderValue");
    function buildContentRange(rangeStart, rangeEnd, fullLength) {
      let contentRange = "bytes ";
      contentRange += isomorphicEncode(`${rangeStart}`);
      contentRange += "-";
      contentRange += isomorphicEncode(`${rangeEnd}`);
      contentRange += "/";
      contentRange += isomorphicEncode(`${fullLength}`);
      return contentRange;
    }
    __name(buildContentRange, "buildContentRange");
    var InflateStream = class extends Transform2 {
      static {
        __name(this, "InflateStream");
      }
      #zlibOptions;
      /** @param {zlib.ZlibOptions} [zlibOptions] */
      constructor(zlibOptions) {
        super();
        this.#zlibOptions = zlibOptions;
      }
      _transform(chunk, encoding, callback) {
        if (!this._inflateStream) {
          if (chunk.length === 0) {
            callback();
            return;
          }
          this._inflateStream = (chunk[0] & 15) === 8 ? zlib2.createInflate(this.#zlibOptions) : zlib2.createInflateRaw(this.#zlibOptions);
          this._inflateStream.on("data", this.push.bind(this));
          this._inflateStream.on("end", () => this.push(null));
          this._inflateStream.on("error", (err) => this.destroy(err));
        }
        this._inflateStream.write(chunk, encoding, callback);
      }
      _final(callback) {
        if (this._inflateStream) {
          this._inflateStream.end();
          this._inflateStream = null;
        }
        callback();
      }
    };
    function createInflate(zlibOptions) {
      return new InflateStream(zlibOptions);
    }
    __name(createInflate, "createInflate");
    function extractMimeType(headers) {
      let charset = null;
      let essence = null;
      let mimeType = null;
      const values = getDecodeSplit("content-type", headers);
      if (values === null) {
        return "failure";
      }
      for (const value of values) {
        const temporaryMimeType = parseMIMEType(value);
        if (temporaryMimeType === "failure" || temporaryMimeType.essence === "*/*") {
          continue;
        }
        mimeType = temporaryMimeType;
        if (mimeType.essence !== essence) {
          charset = null;
          if (mimeType.parameters.has("charset")) {
            charset = mimeType.parameters.get("charset");
          }
          essence = mimeType.essence;
        } else if (!mimeType.parameters.has("charset") && charset !== null) {
          mimeType.parameters.set("charset", charset);
        }
      }
      if (mimeType == null) {
        return "failure";
      }
      return mimeType;
    }
    __name(extractMimeType, "extractMimeType");
    function gettingDecodingSplitting(value) {
      const input = value;
      const position = { position: 0 };
      const values = [];
      let temporaryValue = "";
      while (position.position < input.length) {
        temporaryValue += collectASequenceOfCodePoints(
          (char) => char !== '"' && char !== ",",
          input,
          position
        );
        if (position.position < input.length) {
          if (input.charCodeAt(position.position) === 34) {
            temporaryValue += collectAnHTTPQuotedString(
              input,
              position
            );
            if (position.position < input.length) {
              continue;
            }
          } else {
            assert3(input.charCodeAt(position.position) === 44);
            position.position++;
          }
        }
        temporaryValue = removeChars(temporaryValue, true, true, (char) => char === 9 || char === 32);
        values.push(temporaryValue);
        temporaryValue = "";
      }
      return values;
    }
    __name(gettingDecodingSplitting, "gettingDecodingSplitting");
    function getDecodeSplit(name3, list3) {
      const value = list3.get(name3, true);
      if (value === null) {
        return null;
      }
      return gettingDecodingSplitting(value);
    }
    __name(getDecodeSplit, "getDecodeSplit");
    var textDecoder = new TextDecoder();
    function utf8DecodeBytes(buffer) {
      if (buffer.length === 0) {
        return "";
      }
      if (buffer[0] === 239 && buffer[1] === 187 && buffer[2] === 191) {
        buffer = buffer.subarray(3);
      }
      const output = textDecoder.decode(buffer);
      return output;
    }
    __name(utf8DecodeBytes, "utf8DecodeBytes");
    var EnvironmentSettingsObjectBase = class {
      static {
        __name(this, "EnvironmentSettingsObjectBase");
      }
      get baseUrl() {
        return getGlobalOrigin();
      }
      get origin() {
        return this.baseUrl?.origin;
      }
      policyContainer = makePolicyContainer();
    };
    var EnvironmentSettingsObject = class {
      static {
        __name(this, "EnvironmentSettingsObject");
      }
      settingsObject = new EnvironmentSettingsObjectBase();
    };
    var environmentSettingsObject = new EnvironmentSettingsObject();
    module2.exports = {
      isAborted: isAborted2,
      isCancelled,
      isValidEncodedURL,
      ReadableStreamFrom: ReadableStreamFrom2,
      tryUpgradeRequestToAPotentiallyTrustworthyURL,
      clampAndCoarsenConnectionTimingInfo,
      coarsenedSharedCurrentTime,
      determineRequestsReferrer,
      makePolicyContainer,
      clonePolicyContainer,
      appendFetchMetadata,
      appendRequestOriginHeader,
      TAOCheck,
      corsCheck,
      crossOriginResourcePolicyCheck,
      createOpaqueTimingInfo,
      setRequestReferrerPolicyOnRedirect,
      isValidHTTPToken,
      requestBadPort,
      requestCurrentURL,
      responseURL,
      responseLocationURL,
      isURLPotentiallyTrustworthy,
      isValidReasonPhrase,
      sameOrigin,
      normalizeMethod,
      serializeJavascriptValueToJSONString,
      iteratorMixin,
      createIterator,
      isValidHeaderName,
      isValidHeaderValue,
      isErrorLike,
      fullyReadBody,
      readableStreamClose,
      isomorphicEncode,
      urlIsLocal,
      urlHasHttpsScheme,
      urlIsHttpHttpsScheme,
      readAllBytes,
      simpleRangeHeaderValue,
      buildContentRange,
      createInflate,
      extractMimeType,
      getDecodeSplit,
      utf8DecodeBytes,
      environmentSettingsObject,
      isOriginIPPotentiallyTrustworthy
    };
  }
});

// node_modules/undici/lib/web/fetch/formdata.js
var require_formdata = __commonJS({
  "node_modules/undici/lib/web/fetch/formdata.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { iteratorMixin } = require_util2();
    var { kEnumerableProperty } = require_util();
    var { webidl } = require_webidl();
    var nodeUtil = __require("node:util");
    var FormData2 = class _FormData {
      static {
        __name(this, "FormData");
      }
      #state = [];
      constructor(form = void 0) {
        webidl.util.markAsUncloneable(this);
        if (form !== void 0) {
          throw webidl.errors.conversionFailed({
            prefix: "FormData constructor",
            argument: "Argument 1",
            types: ["undefined"]
          });
        }
      }
      append(name3, value, filename = void 0) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.append";
        webidl.argumentLengthCheck(arguments, 2, prefix);
        name3 = webidl.converters.USVString(name3);
        if (arguments.length === 3 || webidl.is.Blob(value)) {
          value = webidl.converters.Blob(value, prefix, "value");
          if (filename !== void 0) {
            filename = webidl.converters.USVString(filename);
          }
        } else {
          value = webidl.converters.USVString(value);
        }
        const entry = makeEntry(name3, value, filename);
        this.#state.push(entry);
      }
      delete(name3) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.delete";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name3 = webidl.converters.USVString(name3);
        this.#state = this.#state.filter((entry) => entry.name !== name3);
      }
      get(name3) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.get";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name3 = webidl.converters.USVString(name3);
        const idx = this.#state.findIndex((entry) => entry.name === name3);
        if (idx === -1) {
          return null;
        }
        return this.#state[idx].value;
      }
      getAll(name3) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.getAll";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name3 = webidl.converters.USVString(name3);
        return this.#state.filter((entry) => entry.name === name3).map((entry) => entry.value);
      }
      has(name3) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.has";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name3 = webidl.converters.USVString(name3);
        return this.#state.findIndex((entry) => entry.name === name3) !== -1;
      }
      set(name3, value, filename = void 0) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.set";
        webidl.argumentLengthCheck(arguments, 2, prefix);
        name3 = webidl.converters.USVString(name3);
        if (arguments.length === 3 || webidl.is.Blob(value)) {
          value = webidl.converters.Blob(value, prefix, "value");
          if (filename !== void 0) {
            filename = webidl.converters.USVString(filename);
          }
        } else {
          value = webidl.converters.USVString(value);
        }
        const entry = makeEntry(name3, value, filename);
        const idx = this.#state.findIndex((entry2) => entry2.name === name3);
        if (idx !== -1) {
          this.#state = [
            ...this.#state.slice(0, idx),
            entry,
            ...this.#state.slice(idx + 1).filter((entry2) => entry2.name !== name3)
          ];
        } else {
          this.#state.push(entry);
        }
      }
      [nodeUtil.inspect.custom](depth, options2) {
        const state = this.#state.reduce((a, b) => {
          if (a[b.name]) {
            if (Array.isArray(a[b.name])) {
              a[b.name].push(b.value);
            } else {
              a[b.name] = [a[b.name], b.value];
            }
          } else {
            a[b.name] = b.value;
          }
          return a;
        }, { __proto__: null });
        options2.depth ??= depth;
        options2.colors ??= true;
        const output = nodeUtil.formatWithOptions(options2, state);
        return `FormData ${output.slice(output.indexOf("]") + 2)}`;
      }
      /**
       * @param {FormData} formData
       */
      static getFormDataState(formData) {
        return formData.#state;
      }
      /**
       * @param {FormData} formData
       * @param {any[]} newState
       */
      static setFormDataState(formData, newState) {
        formData.#state = newState;
      }
    };
    var { getFormDataState, setFormDataState } = FormData2;
    Reflect.deleteProperty(FormData2, "getFormDataState");
    Reflect.deleteProperty(FormData2, "setFormDataState");
    iteratorMixin("FormData", FormData2, getFormDataState, "name", "value");
    Object.defineProperties(FormData2.prototype, {
      append: kEnumerableProperty,
      delete: kEnumerableProperty,
      get: kEnumerableProperty,
      getAll: kEnumerableProperty,
      has: kEnumerableProperty,
      set: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "FormData",
        configurable: true
      }
    });
    function makeEntry(name3, value, filename) {
      if (typeof value === "string") {
      } else {
        if (!webidl.is.File(value)) {
          value = new File([value], "blob", { type: value.type });
        }
        if (filename !== void 0) {
          const options2 = {
            type: value.type,
            lastModified: value.lastModified
          };
          value = new File([value], filename, options2);
        }
      }
      return { name: name3, value };
    }
    __name(makeEntry, "makeEntry");
    webidl.is.FormData = webidl.util.MakeTypeAssertion(FormData2);
    module2.exports = { FormData: FormData2, makeEntry, setFormDataState };
  }
});

// node_modules/undici/lib/web/fetch/formdata-parser.js
var require_formdata_parser = __commonJS({
  "node_modules/undici/lib/web/fetch/formdata-parser.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { bufferToLowerCasedHeaderName } = require_util();
    var { utf8DecodeBytes } = require_util2();
    var { HTTP_TOKEN_CODEPOINTS, isomorphicDecode } = require_data_url();
    var { makeEntry } = require_formdata();
    var { webidl } = require_webidl();
    var assert3 = __require("node:assert");
    var formDataNameBuffer = Buffer.from('form-data; name="');
    var filenameBuffer = Buffer.from("filename");
    var dd = Buffer.from("--");
    var ddcrlf = Buffer.from("--\r\n");
    function isAsciiString(chars) {
      for (let i = 0; i < chars.length; ++i) {
        if ((chars.charCodeAt(i) & ~127) !== 0) {
          return false;
        }
      }
      return true;
    }
    __name(isAsciiString, "isAsciiString");
    function validateBoundary(boundary) {
      const length = boundary.length;
      if (length < 27 || length > 70) {
        return false;
      }
      for (let i = 0; i < length; ++i) {
        const cp2 = boundary.charCodeAt(i);
        if (!(cp2 >= 48 && cp2 <= 57 || cp2 >= 65 && cp2 <= 90 || cp2 >= 97 && cp2 <= 122 || cp2 === 39 || cp2 === 45 || cp2 === 95)) {
          return false;
        }
      }
      return true;
    }
    __name(validateBoundary, "validateBoundary");
    function multipartFormDataParser(input, mimeType) {
      assert3(mimeType !== "failure" && mimeType.essence === "multipart/form-data");
      const boundaryString = mimeType.parameters.get("boundary");
      if (boundaryString === void 0) {
        throw parsingError("missing boundary in content-type header");
      }
      const boundary = Buffer.from(`--${boundaryString}`, "utf8");
      const entryList = [];
      const position = { position: 0 };
      while (input[position.position] === 13 && input[position.position + 1] === 10) {
        position.position += 2;
      }
      let trailing = input.length;
      while (input[trailing - 1] === 10 && input[trailing - 2] === 13) {
        trailing -= 2;
      }
      if (trailing !== input.length) {
        input = input.subarray(0, trailing);
      }
      while (true) {
        if (input.subarray(position.position, position.position + boundary.length).equals(boundary)) {
          position.position += boundary.length;
        } else {
          throw parsingError("expected a value starting with -- and the boundary");
        }
        if (position.position === input.length - 2 && bufferStartsWith(input, dd, position) || position.position === input.length - 4 && bufferStartsWith(input, ddcrlf, position)) {
          return entryList;
        }
        if (input[position.position] !== 13 || input[position.position + 1] !== 10) {
          throw parsingError("expected CRLF");
        }
        position.position += 2;
        const result = parseMultipartFormDataHeaders(input, position);
        let { name: name3, filename, contentType, encoding } = result;
        position.position += 2;
        let body;
        {
          const boundaryIndex = input.indexOf(boundary.subarray(2), position.position);
          if (boundaryIndex === -1) {
            throw parsingError("expected boundary after body");
          }
          body = input.subarray(position.position, boundaryIndex - 4);
          position.position += body.length;
          if (encoding === "base64") {
            body = Buffer.from(body.toString(), "base64");
          }
        }
        if (input[position.position] !== 13 || input[position.position + 1] !== 10) {
          throw parsingError("expected CRLF");
        } else {
          position.position += 2;
        }
        let value;
        if (filename !== null) {
          contentType ??= "text/plain";
          if (!isAsciiString(contentType)) {
            contentType = "";
          }
          value = new File([body], filename, { type: contentType });
        } else {
          value = utf8DecodeBytes(Buffer.from(body));
        }
        assert3(webidl.is.USVString(name3));
        assert3(typeof value === "string" && webidl.is.USVString(value) || webidl.is.File(value));
        entryList.push(makeEntry(name3, value, filename));
      }
    }
    __name(multipartFormDataParser, "multipartFormDataParser");
    function parseMultipartFormDataHeaders(input, position) {
      let name3 = null;
      let filename = null;
      let contentType = null;
      let encoding = null;
      while (true) {
        if (input[position.position] === 13 && input[position.position + 1] === 10) {
          if (name3 === null) {
            throw parsingError("header name is null");
          }
          return { name: name3, filename, contentType, encoding };
        }
        let headerName = collectASequenceOfBytes(
          (char) => char !== 10 && char !== 13 && char !== 58,
          input,
          position
        );
        headerName = removeChars(headerName, true, true, (char) => char === 9 || char === 32);
        if (!HTTP_TOKEN_CODEPOINTS.test(headerName.toString())) {
          throw parsingError("header name does not match the field-name token production");
        }
        if (input[position.position] !== 58) {
          throw parsingError("expected :");
        }
        position.position++;
        collectASequenceOfBytes(
          (char) => char === 32 || char === 9,
          input,
          position
        );
        switch (bufferToLowerCasedHeaderName(headerName)) {
          case "content-disposition": {
            name3 = filename = null;
            if (!bufferStartsWith(input, formDataNameBuffer, position)) {
              throw parsingError('expected form-data; name=" for content-disposition header');
            }
            position.position += 17;
            name3 = parseMultipartFormDataName(input, position);
            if (input[position.position] === 59 && input[position.position + 1] === 32) {
              const at = { position: position.position + 2 };
              if (bufferStartsWith(input, filenameBuffer, at)) {
                if (input[at.position + 8] === 42) {
                  at.position += 10;
                  collectASequenceOfBytes(
                    (char) => char === 32 || char === 9,
                    input,
                    at
                  );
                  const headerValue = collectASequenceOfBytes(
                    (char) => char !== 32 && char !== 13 && char !== 10,
                    // ' ' or CRLF
                    input,
                    at
                  );
                  if (headerValue[0] !== 117 && headerValue[0] !== 85 || // u or U
                  headerValue[1] !== 116 && headerValue[1] !== 84 || // t or T
                  headerValue[2] !== 102 && headerValue[2] !== 70 || // f or F
                  headerValue[3] !== 45 || // -
                  headerValue[4] !== 56) {
                    throw parsingError("unknown encoding, expected utf-8''");
                  }
                  filename = decodeURIComponent(new TextDecoder().decode(headerValue.subarray(7)));
                  position.position = at.position;
                } else {
                  position.position += 11;
                  collectASequenceOfBytes(
                    (char) => char === 32 || char === 9,
                    input,
                    position
                  );
                  position.position++;
                  filename = parseMultipartFormDataName(input, position);
                }
              }
            }
            break;
          }
          case "content-type": {
            let headerValue = collectASequenceOfBytes(
              (char) => char !== 10 && char !== 13,
              input,
              position
            );
            headerValue = removeChars(headerValue, false, true, (char) => char === 9 || char === 32);
            contentType = isomorphicDecode(headerValue);
            break;
          }
          case "content-transfer-encoding": {
            let headerValue = collectASequenceOfBytes(
              (char) => char !== 10 && char !== 13,
              input,
              position
            );
            headerValue = removeChars(headerValue, false, true, (char) => char === 9 || char === 32);
            encoding = isomorphicDecode(headerValue);
            break;
          }
          default: {
            collectASequenceOfBytes(
              (char) => char !== 10 && char !== 13,
              input,
              position
            );
          }
        }
        if (input[position.position] !== 13 && input[position.position + 1] !== 10) {
          throw parsingError("expected CRLF");
        } else {
          position.position += 2;
        }
      }
    }
    __name(parseMultipartFormDataHeaders, "parseMultipartFormDataHeaders");
    function parseMultipartFormDataName(input, position) {
      assert3(input[position.position - 1] === 34);
      let name3 = collectASequenceOfBytes(
        (char) => char !== 10 && char !== 13 && char !== 34,
        input,
        position
      );
      if (input[position.position] !== 34) {
        throw parsingError('expected "');
      } else {
        position.position++;
      }
      name3 = new TextDecoder().decode(name3).replace(/%0A/ig, "\n").replace(/%0D/ig, "\r").replace(/%22/g, '"');
      return name3;
    }
    __name(parseMultipartFormDataName, "parseMultipartFormDataName");
    function collectASequenceOfBytes(condition, input, position) {
      let start = position.position;
      while (start < input.length && condition(input[start])) {
        ++start;
      }
      return input.subarray(position.position, position.position = start);
    }
    __name(collectASequenceOfBytes, "collectASequenceOfBytes");
    function removeChars(buf, leading, trailing, predicate) {
      let lead = 0;
      let trail = buf.length - 1;
      if (leading) {
        while (lead < buf.length && predicate(buf[lead])) lead++;
      }
      if (trailing) {
        while (trail > 0 && predicate(buf[trail])) trail--;
      }
      return lead === 0 && trail === buf.length - 1 ? buf : buf.subarray(lead, trail + 1);
    }
    __name(removeChars, "removeChars");
    function bufferStartsWith(buffer, start, position) {
      if (buffer.length < start.length) {
        return false;
      }
      for (let i = 0; i < start.length; i++) {
        if (start[i] !== buffer[position.position + i]) {
          return false;
        }
      }
      return true;
    }
    __name(bufferStartsWith, "bufferStartsWith");
    function parsingError(cause) {
      return new TypeError("Failed to parse body as FormData.", { cause: new TypeError(cause) });
    }
    __name(parsingError, "parsingError");
    module2.exports = {
      multipartFormDataParser,
      validateBoundary
    };
  }
});

// node_modules/undici/lib/util/promise.js
var require_promise = __commonJS({
  "node_modules/undici/lib/util/promise.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    function createDeferredPromise() {
      let res;
      let rej;
      const promise = new Promise((resolve24, reject) => {
        res = resolve24;
        rej = reject;
      });
      return { promise, resolve: res, reject: rej };
    }
    __name(createDeferredPromise, "createDeferredPromise");
    module2.exports = {
      createDeferredPromise
    };
  }
});

// node_modules/undici/lib/web/fetch/body.js
var require_body = __commonJS({
  "node_modules/undici/lib/web/fetch/body.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var util4 = require_util();
    var {
      ReadableStreamFrom: ReadableStreamFrom2,
      readableStreamClose,
      fullyReadBody,
      extractMimeType,
      utf8DecodeBytes
    } = require_util2();
    var { FormData: FormData2, setFormDataState } = require_formdata();
    var { webidl } = require_webidl();
    var assert3 = __require("node:assert");
    var { isErrored, isDisturbed } = __require("node:stream");
    var { isArrayBuffer } = __require("node:util/types");
    var { serializeAMimeType } = require_data_url();
    var { multipartFormDataParser } = require_formdata_parser();
    var { createDeferredPromise } = require_promise();
    var random2;
    try {
      const crypto18 = __require("node:crypto");
      random2 = /* @__PURE__ */ __name((max) => crypto18.randomInt(0, max), "random");
    } catch {
      random2 = /* @__PURE__ */ __name((max) => Math.floor(Math.random() * max), "random");
    }
    var textEncoder = new TextEncoder();
    function noop6() {
    }
    __name(noop6, "noop");
    var streamRegistry = new FinalizationRegistry((weakRef) => {
      const stream2 = weakRef.deref();
      if (stream2 && !stream2.locked && !isDisturbed(stream2) && !isErrored(stream2)) {
        stream2.cancel("Response object has been garbage collected").catch(noop6);
      }
    });
    function extractBody(object, keepalive = false) {
      let stream2 = null;
      if (webidl.is.ReadableStream(object)) {
        stream2 = object;
      } else if (webidl.is.Blob(object)) {
        stream2 = object.stream();
      } else {
        stream2 = new ReadableStream({
          async pull(controller) {
            const buffer = typeof source2 === "string" ? textEncoder.encode(source2) : source2;
            if (buffer.byteLength) {
              controller.enqueue(buffer);
            }
            queueMicrotask(() => readableStreamClose(controller));
          },
          start() {
          },
          type: "bytes"
        });
      }
      assert3(webidl.is.ReadableStream(stream2));
      let action = null;
      let source2 = null;
      let length = null;
      let type = null;
      if (typeof object === "string") {
        source2 = object;
        type = "text/plain;charset=UTF-8";
      } else if (webidl.is.URLSearchParams(object)) {
        source2 = object.toString();
        type = "application/x-www-form-urlencoded;charset=UTF-8";
      } else if (isArrayBuffer(object)) {
        source2 = new Uint8Array(object.slice());
      } else if (ArrayBuffer.isView(object)) {
        source2 = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength));
      } else if (webidl.is.FormData(object)) {
        const boundary = `----formdata-undici-0${`${random2(1e11)}`.padStart(11, "0")}`;
        const prefix = `--${boundary}\r
Content-Disposition: form-data`;
        const formdataEscape = /* @__PURE__ */ __name((str2) => str2.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"), "formdataEscape");
        const normalizeLinefeeds = /* @__PURE__ */ __name((value) => value.replace(/\r?\n|\r/g, "\r\n"), "normalizeLinefeeds");
        const blobParts = [];
        const rn = new Uint8Array([13, 10]);
        length = 0;
        let hasUnknownSizeValue = false;
        for (const [name3, value] of object) {
          if (typeof value === "string") {
            const chunk2 = textEncoder.encode(prefix + `; name="${formdataEscape(normalizeLinefeeds(name3))}"\r
\r
${normalizeLinefeeds(value)}\r
`);
            blobParts.push(chunk2);
            length += chunk2.byteLength;
          } else {
            const chunk2 = textEncoder.encode(`${prefix}; name="${formdataEscape(normalizeLinefeeds(name3))}"` + (value.name ? `; filename="${formdataEscape(value.name)}"` : "") + `\r
Content-Type: ${value.type || "application/octet-stream"}\r
\r
`);
            blobParts.push(chunk2, value, rn);
            if (typeof value.size === "number") {
              length += chunk2.byteLength + value.size + rn.byteLength;
            } else {
              hasUnknownSizeValue = true;
            }
          }
        }
        const chunk = textEncoder.encode(`--${boundary}--\r
`);
        blobParts.push(chunk);
        length += chunk.byteLength;
        if (hasUnknownSizeValue) {
          length = null;
        }
        source2 = object;
        action = /* @__PURE__ */ __name(async function* () {
          for (const part of blobParts) {
            if (part.stream) {
              yield* part.stream();
            } else {
              yield part;
            }
          }
        }, "action");
        type = `multipart/form-data; boundary=${boundary}`;
      } else if (webidl.is.Blob(object)) {
        source2 = object;
        length = object.size;
        if (object.type) {
          type = object.type;
        }
      } else if (typeof object[Symbol.asyncIterator] === "function") {
        if (keepalive) {
          throw new TypeError("keepalive");
        }
        if (util4.isDisturbed(object) || object.locked) {
          throw new TypeError(
            "Response body object should not be disturbed or locked"
          );
        }
        stream2 = webidl.is.ReadableStream(object) ? object : ReadableStreamFrom2(object);
      }
      if (typeof source2 === "string" || util4.isBuffer(source2)) {
        length = Buffer.byteLength(source2);
      }
      if (action != null) {
        let iterator;
        stream2 = new ReadableStream({
          async start() {
            iterator = action(object)[Symbol.asyncIterator]();
          },
          async pull(controller) {
            const { value, done } = await iterator.next();
            if (done) {
              queueMicrotask(() => {
                controller.close();
                controller.byobRequest?.respond(0);
              });
            } else {
              if (!isErrored(stream2)) {
                const buffer = new Uint8Array(value);
                if (buffer.byteLength) {
                  controller.enqueue(buffer);
                }
              }
            }
            return controller.desiredSize > 0;
          },
          async cancel(reason) {
            await iterator.return();
          },
          type: "bytes"
        });
      }
      const body = { stream: stream2, source: source2, length };
      return [body, type];
    }
    __name(extractBody, "extractBody");
    function safelyExtractBody(object, keepalive = false) {
      if (webidl.is.ReadableStream(object)) {
        assert3(!util4.isDisturbed(object), "The body has already been consumed.");
        assert3(!object.locked, "The stream is locked.");
      }
      return extractBody(object, keepalive);
    }
    __name(safelyExtractBody, "safelyExtractBody");
    function cloneBody(body) {
      const { 0: out1, 1: out2 } = body.stream.tee();
      body.stream = out1;
      return {
        stream: out2,
        length: body.length,
        source: body.source
      };
    }
    __name(cloneBody, "cloneBody");
    function throwIfAborted(state) {
      if (state.aborted) {
        throw new DOMException("The operation was aborted.", "AbortError");
      }
    }
    __name(throwIfAborted, "throwIfAborted");
    function bodyMixinMethods(instance, getInternalState) {
      const methods = {
        blob() {
          return consumeBody(this, (bytes) => {
            let mimeType = bodyMimeType(getInternalState(this));
            if (mimeType === null) {
              mimeType = "";
            } else if (mimeType) {
              mimeType = serializeAMimeType(mimeType);
            }
            return new Blob([bytes], { type: mimeType });
          }, instance, getInternalState);
        },
        arrayBuffer() {
          return consumeBody(this, (bytes) => {
            return new Uint8Array(bytes).buffer;
          }, instance, getInternalState);
        },
        text() {
          return consumeBody(this, utf8DecodeBytes, instance, getInternalState);
        },
        json() {
          return consumeBody(this, parseJSONFromBytes, instance, getInternalState);
        },
        formData() {
          return consumeBody(this, (value) => {
            const mimeType = bodyMimeType(getInternalState(this));
            if (mimeType !== null) {
              switch (mimeType.essence) {
                case "multipart/form-data": {
                  const parsed = multipartFormDataParser(value, mimeType);
                  const fd = new FormData2();
                  setFormDataState(fd, parsed);
                  return fd;
                }
                case "application/x-www-form-urlencoded": {
                  const entries = new URLSearchParams(value.toString());
                  const fd = new FormData2();
                  for (const [name3, value2] of entries) {
                    fd.append(name3, value2);
                  }
                  return fd;
                }
              }
            }
            throw new TypeError(
              'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".'
            );
          }, instance, getInternalState);
        },
        bytes() {
          return consumeBody(this, (bytes) => {
            return new Uint8Array(bytes);
          }, instance, getInternalState);
        }
      };
      return methods;
    }
    __name(bodyMixinMethods, "bodyMixinMethods");
    function mixinBody(prototype, getInternalState) {
      Object.assign(prototype.prototype, bodyMixinMethods(prototype, getInternalState));
    }
    __name(mixinBody, "mixinBody");
    async function consumeBody(object, convertBytesToJSValue, instance, getInternalState) {
      webidl.brandCheck(object, instance);
      const state = getInternalState(object);
      if (bodyUnusable(state)) {
        throw new TypeError("Body is unusable: Body has already been read");
      }
      throwIfAborted(state);
      const promise = createDeferredPromise();
      const errorSteps = /* @__PURE__ */ __name((error) => promise.reject(error), "errorSteps");
      const successSteps = /* @__PURE__ */ __name((data) => {
        try {
          promise.resolve(convertBytesToJSValue(data));
        } catch (e2) {
          errorSteps(e2);
        }
      }, "successSteps");
      if (state.body == null) {
        successSteps(Buffer.allocUnsafe(0));
        return promise.promise;
      }
      fullyReadBody(state.body, successSteps, errorSteps);
      return promise.promise;
    }
    __name(consumeBody, "consumeBody");
    function bodyUnusable(object) {
      const body = object.body;
      return body != null && (body.stream.locked || util4.isDisturbed(body.stream));
    }
    __name(bodyUnusable, "bodyUnusable");
    function parseJSONFromBytes(bytes) {
      return JSON.parse(utf8DecodeBytes(bytes));
    }
    __name(parseJSONFromBytes, "parseJSONFromBytes");
    function bodyMimeType(requestOrResponse) {
      const headers = requestOrResponse.headersList;
      const mimeType = extractMimeType(headers);
      if (mimeType === "failure") {
        return null;
      }
      return mimeType;
    }
    __name(bodyMimeType, "bodyMimeType");
    module2.exports = {
      extractBody,
      safelyExtractBody,
      cloneBody,
      mixinBody,
      streamRegistry,
      bodyUnusable
    };
  }
});

// node_modules/undici/lib/dispatcher/client-h1.js
var require_client_h1 = __commonJS({
  "node_modules/undici/lib/dispatcher/client-h1.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert3 = __require("node:assert");
    var util4 = require_util();
    var { channels } = require_diagnostics();
    var timers = require_timers();
    var {
      RequestContentLengthMismatchError,
      ResponseContentLengthMismatchError,
      RequestAbortedError,
      HeadersTimeoutError,
      HeadersOverflowError,
      SocketError,
      InformationalError,
      BodyTimeoutError,
      HTTPParserError,
      ResponseExceededMaxSizeError
    } = require_errors();
    var {
      kUrl,
      kReset: kReset2,
      kClient,
      kParser,
      kBlocking,
      kRunning,
      kPending,
      kSize,
      kWriting,
      kQueue,
      kNoRef,
      kKeepAliveDefaultTimeout,
      kHostHeader,
      kPendingIdx,
      kRunningIdx,
      kError,
      kPipelining,
      kSocket,
      kKeepAliveTimeoutValue,
      kMaxHeadersSize,
      kKeepAliveMaxTimeout,
      kKeepAliveTimeoutThreshold,
      kHeadersTimeout,
      kBodyTimeout,
      kStrictContentLength,
      kMaxRequests,
      kCounter,
      kMaxResponseSize,
      kOnError,
      kResume,
      kHTTPContext,
      kClosed
    } = require_symbols();
    var constants4 = require_constants4();
    var EMPTY_BUF = Buffer.alloc(0);
    var FastBuffer = Buffer[Symbol.species];
    var removeAllListeners = util4.removeAllListeners;
    var extractBody;
    function lazyllhttp() {
      const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0;
      let mod2;
      try {
        mod2 = new WebAssembly.Module(require_llhttp_simd_wasm());
      } catch {
        mod2 = new WebAssembly.Module(llhttpWasmData || require_llhttp_wasm());
      }
      return new WebAssembly.Instance(mod2, {
        env: {
          /**
           * @param {number} p
           * @param {number} at
           * @param {number} len
           * @returns {number}
           */
          wasm_on_url: /* @__PURE__ */ __name((p, at, len) => {
            return 0;
          }, "wasm_on_url"),
          /**
           * @param {number} p
           * @param {number} at
           * @param {number} len
           * @returns {number}
           */
          wasm_on_status: /* @__PURE__ */ __name((p, at, len) => {
            assert3(currentParser.ptr === p);
            const start = at - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len));
          }, "wasm_on_status"),
          /**
           * @param {number} p
           * @returns {number}
           */
          wasm_on_message_begin: /* @__PURE__ */ __name((p) => {
            assert3(currentParser.ptr === p);
            return currentParser.onMessageBegin();
          }, "wasm_on_message_begin"),
          /**
           * @param {number} p
           * @param {number} at
           * @param {number} len
           * @returns {number}
           */
          wasm_on_header_field: /* @__PURE__ */ __name((p, at, len) => {
            assert3(currentParser.ptr === p);
            const start = at - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len));
          }, "wasm_on_header_field"),
          /**
           * @param {number} p
           * @param {number} at
           * @param {number} len
           * @returns {number}
           */
          wasm_on_header_value: /* @__PURE__ */ __name((p, at, len) => {
            assert3(currentParser.ptr === p);
            const start = at - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len));
          }, "wasm_on_header_value"),
          /**
           * @param {number} p
           * @param {number} statusCode
           * @param {0|1} upgrade
           * @param {0|1} shouldKeepAlive
           * @returns {number}
           */
          wasm_on_headers_complete: /* @__PURE__ */ __name((p, statusCode, upgrade, shouldKeepAlive) => {
            assert3(currentParser.ptr === p);
            return currentParser.onHeadersComplete(statusCode, upgrade === 1, shouldKeepAlive === 1);
          }, "wasm_on_headers_complete"),
          /**
           * @param {number} p
           * @param {number} at
           * @param {number} len
           * @returns {number}
           */
          wasm_on_body: /* @__PURE__ */ __name((p, at, len) => {
            assert3(currentParser.ptr === p);
            const start = at - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len));
          }, "wasm_on_body"),
          /**
           * @param {number} p
           * @returns {number}
           */
          wasm_on_message_complete: /* @__PURE__ */ __name((p) => {
            assert3(currentParser.ptr === p);
            return currentParser.onMessageComplete();
          }, "wasm_on_message_complete")
        }
      });
    }
    __name(lazyllhttp, "lazyllhttp");
    var llhttpInstance = null;
    var currentParser = null;
    var currentBufferRef = null;
    var currentBufferSize = 0;
    var currentBufferPtr = null;
    var USE_NATIVE_TIMER = 0;
    var USE_FAST_TIMER = 1;
    var TIMEOUT_HEADERS = 2 | USE_FAST_TIMER;
    var TIMEOUT_BODY = 4 | USE_FAST_TIMER;
    var TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER;
    var Parser4 = class {
      static {
        __name(this, "Parser");
      }
      /**
         * @param {import('./client.js')} client
         * @param {import('net').Socket} socket
         * @param {*} llhttp
         */
      constructor(client, socket, { exports: exports3 }) {
        this.llhttp = exports3;
        this.ptr = this.llhttp.llhttp_alloc(constants4.TYPE.RESPONSE);
        this.client = client;
        this.socket = socket;
        this.timeout = null;
        this.timeoutValue = null;
        this.timeoutType = null;
        this.statusCode = 0;
        this.statusText = "";
        this.upgrade = false;
        this.headers = [];
        this.headersSize = 0;
        this.headersMaxSize = client[kMaxHeadersSize];
        this.shouldKeepAlive = false;
        this.paused = false;
        this.resume = this.resume.bind(this);
        this.bytesRead = 0;
        this.keepAlive = "";
        this.contentLength = "";
        this.connection = "";
        this.maxResponseSize = client[kMaxResponseSize];
      }
      setTimeout(delay4, type) {
        if (delay4 !== this.timeoutValue || type & USE_FAST_TIMER ^ this.timeoutType & USE_FAST_TIMER) {
          if (this.timeout) {
            timers.clearTimeout(this.timeout);
            this.timeout = null;
          }
          if (delay4) {
            if (type & USE_FAST_TIMER) {
              this.timeout = timers.setFastTimeout(onParserTimeout, delay4, new WeakRef(this));
            } else {
              this.timeout = setTimeout(onParserTimeout, delay4, new WeakRef(this));
              this.timeout?.unref();
            }
          }
          this.timeoutValue = delay4;
        } else if (this.timeout) {
          if (this.timeout.refresh) {
            this.timeout.refresh();
          }
        }
        this.timeoutType = type;
      }
      resume() {
        if (this.socket.destroyed || !this.paused) {
          return;
        }
        assert3(this.ptr != null);
        assert3(currentParser === null);
        this.llhttp.llhttp_resume(this.ptr);
        assert3(this.timeoutType === TIMEOUT_BODY);
        if (this.timeout) {
          if (this.timeout.refresh) {
            this.timeout.refresh();
          }
        }
        this.paused = false;
        this.execute(this.socket.read() || EMPTY_BUF);
        this.readMore();
      }
      readMore() {
        while (!this.paused && this.ptr) {
          const chunk = this.socket.read();
          if (chunk === null) {
            break;
          }
          this.execute(chunk);
        }
      }
      /**
       * @param {Buffer} chunk
       */
      execute(chunk) {
        assert3(currentParser === null);
        assert3(this.ptr != null);
        assert3(!this.paused);
        const { socket, llhttp } = this;
        if (chunk.length > currentBufferSize) {
          if (currentBufferPtr) {
            llhttp.free(currentBufferPtr);
          }
          currentBufferSize = Math.ceil(chunk.length / 4096) * 4096;
          currentBufferPtr = llhttp.malloc(currentBufferSize);
        }
        new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(chunk);
        try {
          let ret;
          try {
            currentBufferRef = chunk;
            currentParser = this;
            ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, chunk.length);
          } catch (err) {
            throw err;
          } finally {
            currentParser = null;
            currentBufferRef = null;
          }
          if (ret !== constants4.ERROR.OK) {
            const data = chunk.subarray(llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr);
            if (ret === constants4.ERROR.PAUSED_UPGRADE) {
              this.onUpgrade(data);
            } else if (ret === constants4.ERROR.PAUSED) {
              this.paused = true;
              socket.unshift(data);
            } else {
              const ptr = llhttp.llhttp_get_error_reason(this.ptr);
              let message = "";
              if (ptr) {
                const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0);
                message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")";
              }
              throw new HTTPParserError(message, constants4.ERROR[ret], data);
            }
          }
        } catch (err) {
          util4.destroy(socket, err);
        }
      }
      destroy() {
        assert3(currentParser === null);
        assert3(this.ptr != null);
        this.llhttp.llhttp_free(this.ptr);
        this.ptr = null;
        this.timeout && timers.clearTimeout(this.timeout);
        this.timeout = null;
        this.timeoutValue = null;
        this.timeoutType = null;
        this.paused = false;
      }
      /**
       * @param {Buffer} buf
       * @returns {0}
       */
      onStatus(buf) {
        this.statusText = buf.toString();
        return 0;
      }
      /**
       * @returns {0|-1}
       */
      onMessageBegin() {
        const { socket, client } = this;
        if (socket.destroyed) {
          return -1;
        }
        const request4 = client[kQueue][client[kRunningIdx]];
        if (!request4) {
          return -1;
        }
        request4.onResponseStarted();
        return 0;
      }
      /**
       * @param {Buffer} buf
       * @returns {number}
       */
      onHeaderField(buf) {
        const len = this.headers.length;
        if ((len & 1) === 0) {
          this.headers.push(buf);
        } else {
          this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]);
        }
        this.trackHeader(buf.length);
        return 0;
      }
      /**
       * @param {Buffer} buf
       * @returns {number}
       */
      onHeaderValue(buf) {
        let len = this.headers.length;
        if ((len & 1) === 1) {
          this.headers.push(buf);
          len += 1;
        } else {
          this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]);
        }
        const key = this.headers[len - 2];
        if (key.length === 10) {
          const headerName = util4.bufferToLowerCasedHeaderName(key);
          if (headerName === "keep-alive") {
            this.keepAlive += buf.toString();
          } else if (headerName === "connection") {
            this.connection += buf.toString();
          }
        } else if (key.length === 14 && util4.bufferToLowerCasedHeaderName(key) === "content-length") {
          this.contentLength += buf.toString();
        }
        this.trackHeader(buf.length);
        return 0;
      }
      /**
       * @param {number} len
       */
      trackHeader(len) {
        this.headersSize += len;
        if (this.headersSize >= this.headersMaxSize) {
          util4.destroy(this.socket, new HeadersOverflowError());
        }
      }
      /**
       * @param {Buffer} head
       */
      onUpgrade(head) {
        const { upgrade, client, socket, headers, statusCode } = this;
        assert3(upgrade);
        assert3(client[kSocket] === socket);
        assert3(!socket.destroyed);
        assert3(!this.paused);
        assert3((headers.length & 1) === 0);
        const request4 = client[kQueue][client[kRunningIdx]];
        assert3(request4);
        assert3(request4.upgrade || request4.method === "CONNECT");
        this.statusCode = 0;
        this.statusText = "";
        this.shouldKeepAlive = false;
        this.headers = [];
        this.headersSize = 0;
        socket.unshift(head);
        socket[kParser].destroy();
        socket[kParser] = null;
        socket[kClient] = null;
        socket[kError] = null;
        removeAllListeners(socket);
        client[kSocket] = null;
        client[kHTTPContext] = null;
        client[kQueue][client[kRunningIdx]++] = null;
        client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade"));
        try {
          request4.onUpgrade(statusCode, headers, socket);
        } catch (err) {
          util4.destroy(socket, err);
        }
        client[kResume]();
      }
      /**
       * @param {number} statusCode
       * @param {boolean} upgrade
       * @param {boolean} shouldKeepAlive
       * @returns {number}
       */
      onHeadersComplete(statusCode, upgrade, shouldKeepAlive) {
        const { client, socket, headers, statusText } = this;
        if (socket.destroyed) {
          return -1;
        }
        const request4 = client[kQueue][client[kRunningIdx]];
        if (!request4) {
          return -1;
        }
        assert3(!this.upgrade);
        assert3(this.statusCode < 200);
        if (statusCode === 100) {
          util4.destroy(socket, new SocketError("bad response", util4.getSocketInfo(socket)));
          return -1;
        }
        if (upgrade && !request4.upgrade) {
          util4.destroy(socket, new SocketError("bad upgrade", util4.getSocketInfo(socket)));
          return -1;
        }
        assert3(this.timeoutType === TIMEOUT_HEADERS);
        this.statusCode = statusCode;
        this.shouldKeepAlive = shouldKeepAlive || // Override llhttp value which does not allow keepAlive for HEAD.
        request4.method === "HEAD" && !socket[kReset2] && this.connection.toLowerCase() === "keep-alive";
        if (this.statusCode >= 200) {
          const bodyTimeout = request4.bodyTimeout != null ? request4.bodyTimeout : client[kBodyTimeout];
          this.setTimeout(bodyTimeout, TIMEOUT_BODY);
        } else if (this.timeout) {
          if (this.timeout.refresh) {
            this.timeout.refresh();
          }
        }
        if (request4.method === "CONNECT") {
          assert3(client[kRunning] === 1);
          this.upgrade = true;
          return 2;
        }
        if (upgrade) {
          assert3(client[kRunning] === 1);
          this.upgrade = true;
          return 2;
        }
        assert3((this.headers.length & 1) === 0);
        this.headers = [];
        this.headersSize = 0;
        if (this.shouldKeepAlive && client[kPipelining]) {
          const keepAliveTimeout = this.keepAlive ? util4.parseKeepAliveTimeout(this.keepAlive) : null;
          if (keepAliveTimeout != null) {
            const timeout2 = Math.min(
              keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
              client[kKeepAliveMaxTimeout]
            );
            if (timeout2 <= 0) {
              socket[kReset2] = true;
            } else {
              client[kKeepAliveTimeoutValue] = timeout2;
            }
          } else {
            client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout];
          }
        } else {
          socket[kReset2] = true;
        }
        const pause = request4.onHeaders(statusCode, headers, this.resume, statusText) === false;
        if (request4.aborted) {
          return -1;
        }
        if (request4.method === "HEAD") {
          return 1;
        }
        if (statusCode < 200) {
          return 1;
        }
        if (socket[kBlocking]) {
          socket[kBlocking] = false;
          client[kResume]();
        }
        return pause ? constants4.ERROR.PAUSED : 0;
      }
      /**
       * @param {Buffer} buf
       * @returns {number}
       */
      onBody(buf) {
        const { client, socket, statusCode, maxResponseSize } = this;
        if (socket.destroyed) {
          return -1;
        }
        const request4 = client[kQueue][client[kRunningIdx]];
        assert3(request4);
        assert3(this.timeoutType === TIMEOUT_BODY);
        if (this.timeout) {
          if (this.timeout.refresh) {
            this.timeout.refresh();
          }
        }
        assert3(statusCode >= 200);
        if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
          util4.destroy(socket, new ResponseExceededMaxSizeError());
          return -1;
        }
        this.bytesRead += buf.length;
        if (request4.onData(buf) === false) {
          return constants4.ERROR.PAUSED;
        }
        return 0;
      }
      /**
       * @returns {number}
       */
      onMessageComplete() {
        const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this;
        if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
          return -1;
        }
        if (upgrade) {
          return 0;
        }
        assert3(statusCode >= 100);
        assert3((this.headers.length & 1) === 0);
        const request4 = client[kQueue][client[kRunningIdx]];
        assert3(request4);
        this.statusCode = 0;
        this.statusText = "";
        this.bytesRead = 0;
        this.contentLength = "";
        this.keepAlive = "";
        this.connection = "";
        this.headers = [];
        this.headersSize = 0;
        if (statusCode < 200) {
          return 0;
        }
        if (request4.method !== "HEAD" && contentLength && bytesRead !== parseInt(contentLength, 10)) {
          util4.destroy(socket, new ResponseContentLengthMismatchError());
          return -1;
        }
        request4.onComplete(headers);
        client[kQueue][client[kRunningIdx]++] = null;
        if (socket[kWriting]) {
          assert3(client[kRunning] === 0);
          util4.destroy(socket, new InformationalError("reset"));
          return constants4.ERROR.PAUSED;
        } else if (!shouldKeepAlive) {
          util4.destroy(socket, new InformationalError("reset"));
          return constants4.ERROR.PAUSED;
        } else if (socket[kReset2] && client[kRunning] === 0) {
          util4.destroy(socket, new InformationalError("reset"));
          return constants4.ERROR.PAUSED;
        } else if (client[kPipelining] == null || client[kPipelining] === 1) {
          setImmediate(client[kResume]);
        } else {
          client[kResume]();
        }
        return 0;
      }
    };
    function onParserTimeout(parser6) {
      const { socket, timeoutType, client, paused } = parser6.deref();
      if (timeoutType === TIMEOUT_HEADERS) {
        if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
          assert3(!paused, "cannot be paused while waiting for headers");
          util4.destroy(socket, new HeadersTimeoutError());
        }
      } else if (timeoutType === TIMEOUT_BODY) {
        if (!paused) {
          util4.destroy(socket, new BodyTimeoutError());
        }
      } else if (timeoutType === TIMEOUT_KEEP_ALIVE) {
        assert3(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]);
        util4.destroy(socket, new InformationalError("socket idle timeout"));
      }
    }
    __name(onParserTimeout, "onParserTimeout");
    async function connectH1(client, socket) {
      client[kSocket] = socket;
      if (!llhttpInstance) {
        llhttpInstance = lazyllhttp();
      }
      if (socket.errored) {
        throw socket.errored;
      }
      if (socket.destroyed) {
        throw new SocketError("destroyed");
      }
      socket[kNoRef] = false;
      socket[kWriting] = false;
      socket[kReset2] = false;
      socket[kBlocking] = false;
      socket[kParser] = new Parser4(client, socket, llhttpInstance);
      util4.addListener(socket, "error", onHttpSocketError);
      util4.addListener(socket, "readable", onHttpSocketReadable);
      util4.addListener(socket, "end", onHttpSocketEnd);
      util4.addListener(socket, "close", onHttpSocketClose);
      socket[kClosed] = false;
      socket.on("close", onSocketClose);
      return {
        version: "h1",
        defaultPipelining: 1,
        write(request4) {
          return writeH1(client, request4);
        },
        resume() {
          resumeH1(client);
        },
        /**
         * @param {Error|undefined} err
         * @param {() => void} callback
         */
        destroy(err, callback) {
          if (socket[kClosed]) {
            queueMicrotask(callback);
          } else {
            socket.on("close", callback);
            socket.destroy(err);
          }
        },
        /**
         * @returns {boolean}
         */
        get destroyed() {
          return socket.destroyed;
        },
        /**
         * @param {import('../core/request.js')} request
         * @returns {boolean}
         */
        busy(request4) {
          if (socket[kWriting] || socket[kReset2] || socket[kBlocking]) {
            return true;
          }
          if (request4) {
            if (client[kRunning] > 0 && !request4.idempotent) {
              return true;
            }
            if (client[kRunning] > 0 && (request4.upgrade || request4.method === "CONNECT")) {
              return true;
            }
            if (client[kRunning] > 0 && util4.bodyLength(request4.body) !== 0 && (util4.isStream(request4.body) || util4.isAsyncIterable(request4.body) || util4.isFormDataLike(request4.body))) {
              return true;
            }
          }
          return false;
        }
      };
    }
    __name(connectH1, "connectH1");
    function onHttpSocketError(err) {
      assert3(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
      const parser6 = this[kParser];
      if (err.code === "ECONNRESET" && parser6.statusCode && !parser6.shouldKeepAlive) {
        parser6.onMessageComplete();
        return;
      }
      this[kError] = err;
      this[kClient][kOnError](err);
    }
    __name(onHttpSocketError, "onHttpSocketError");
    function onHttpSocketReadable() {
      this[kParser]?.readMore();
    }
    __name(onHttpSocketReadable, "onHttpSocketReadable");
    function onHttpSocketEnd() {
      const parser6 = this[kParser];
      if (parser6.statusCode && !parser6.shouldKeepAlive) {
        parser6.onMessageComplete();
        return;
      }
      util4.destroy(this, new SocketError("other side closed", util4.getSocketInfo(this)));
    }
    __name(onHttpSocketEnd, "onHttpSocketEnd");
    function onHttpSocketClose() {
      const parser6 = this[kParser];
      if (parser6) {
        if (!this[kError] && parser6.statusCode && !parser6.shouldKeepAlive) {
          parser6.onMessageComplete();
        }
        this[kParser].destroy();
        this[kParser] = null;
      }
      const err = this[kError] || new SocketError("closed", util4.getSocketInfo(this));
      const client = this[kClient];
      client[kSocket] = null;
      client[kHTTPContext] = null;
      if (client.destroyed) {
        assert3(client[kPending] === 0);
        const requests = client[kQueue].splice(client[kRunningIdx]);
        for (let i = 0; i < requests.length; i++) {
          const request4 = requests[i];
          util4.errorRequest(client, request4, err);
        }
      } else if (client[kRunning] > 0 && err.code !== "UND_ERR_INFO") {
        const request4 = client[kQueue][client[kRunningIdx]];
        client[kQueue][client[kRunningIdx]++] = null;
        util4.errorRequest(client, request4, err);
      }
      client[kPendingIdx] = client[kRunningIdx];
      assert3(client[kRunning] === 0);
      client.emit("disconnect", client[kUrl], [client], err);
      client[kResume]();
    }
    __name(onHttpSocketClose, "onHttpSocketClose");
    function onSocketClose() {
      this[kClosed] = true;
    }
    __name(onSocketClose, "onSocketClose");
    function resumeH1(client) {
      const socket = client[kSocket];
      if (socket && !socket.destroyed) {
        if (client[kSize] === 0) {
          if (!socket[kNoRef] && socket.unref) {
            socket.unref();
            socket[kNoRef] = true;
          }
        } else if (socket[kNoRef] && socket.ref) {
          socket.ref();
          socket[kNoRef] = false;
        }
        if (client[kSize] === 0) {
          if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
            socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE);
          }
        } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
          if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
            const request4 = client[kQueue][client[kRunningIdx]];
            const headersTimeout = request4.headersTimeout != null ? request4.headersTimeout : client[kHeadersTimeout];
            socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS);
          }
        }
      }
    }
    __name(resumeH1, "resumeH1");
    function shouldSendContentLength(method) {
      return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
    }
    __name(shouldSendContentLength, "shouldSendContentLength");
    function writeH1(client, request4) {
      const { method, path: path108, host, upgrade, blocking, reset } = request4;
      let { body, headers, contentLength } = request4;
      const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
      if (util4.isFormDataLike(body)) {
        if (!extractBody) {
          extractBody = require_body().extractBody;
        }
        const [bodyStream, contentType] = extractBody(body);
        if (request4.contentType == null) {
          headers.push("content-type", contentType);
        }
        body = bodyStream.stream;
        contentLength = bodyStream.length;
      } else if (util4.isBlobLike(body) && request4.contentType == null && body.type) {
        headers.push("content-type", body.type);
      }
      if (body && typeof body.read === "function") {
        body.read(0);
      }
      const bodyLength = util4.bodyLength(body);
      contentLength = bodyLength ?? contentLength;
      if (contentLength === null) {
        contentLength = request4.contentLength;
      }
      if (contentLength === 0 && !expectsPayload) {
        contentLength = null;
      }
      if (shouldSendContentLength(method) && contentLength > 0 && request4.contentLength !== null && request4.contentLength !== contentLength) {
        if (client[kStrictContentLength]) {
          util4.errorRequest(client, request4, new RequestContentLengthMismatchError());
          return false;
        }
        process.emitWarning(new RequestContentLengthMismatchError());
      }
      const socket = client[kSocket];
      const abort = /* @__PURE__ */ __name((err) => {
        if (request4.aborted || request4.completed) {
          return;
        }
        util4.errorRequest(client, request4, err || new RequestAbortedError());
        util4.destroy(body);
        util4.destroy(socket, new InformationalError("aborted"));
      }, "abort");
      try {
        request4.onConnect(abort);
      } catch (err) {
        util4.errorRequest(client, request4, err);
      }
      if (request4.aborted) {
        return false;
      }
      if (method === "HEAD") {
        socket[kReset2] = true;
      }
      if (upgrade || method === "CONNECT") {
        socket[kReset2] = true;
      }
      if (reset != null) {
        socket[kReset2] = reset;
      }
      if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
        socket[kReset2] = true;
      }
      if (blocking) {
        socket[kBlocking] = true;
      }
      let header = `${method} ${path108} HTTP/1.1\r
`;
      if (typeof host === "string") {
        header += `host: ${host}\r
`;
      } else {
        header += client[kHostHeader];
      }
      if (upgrade) {
        header += `connection: upgrade\r
upgrade: ${upgrade}\r
`;
      } else if (client[kPipelining] && !socket[kReset2]) {
        header += "connection: keep-alive\r\n";
      } else {
        header += "connection: close\r\n";
      }
      if (Array.isArray(headers)) {
        for (let n2 = 0; n2 < headers.length; n2 += 2) {
          const key = headers[n2 + 0];
          const val = headers[n2 + 1];
          if (Array.isArray(val)) {
            for (let i = 0; i < val.length; i++) {
              header += `${key}: ${val[i]}\r
`;
            }
          } else {
            header += `${key}: ${val}\r
`;
          }
        }
      }
      if (channels.sendHeaders.hasSubscribers) {
        channels.sendHeaders.publish({ request: request4, headers: header, socket });
      }
      if (!body || bodyLength === 0) {
        writeBuffer(abort, null, client, request4, socket, contentLength, header, expectsPayload);
      } else if (util4.isBuffer(body)) {
        writeBuffer(abort, body, client, request4, socket, contentLength, header, expectsPayload);
      } else if (util4.isBlobLike(body)) {
        if (typeof body.stream === "function") {
          writeIterable(abort, body.stream(), client, request4, socket, contentLength, header, expectsPayload);
        } else {
          writeBlob(abort, body, client, request4, socket, contentLength, header, expectsPayload);
        }
      } else if (util4.isStream(body)) {
        writeStream(abort, body, client, request4, socket, contentLength, header, expectsPayload);
      } else if (util4.isIterable(body)) {
        writeIterable(abort, body, client, request4, socket, contentLength, header, expectsPayload);
      } else {
        assert3(false);
      }
      return true;
    }
    __name(writeH1, "writeH1");
    function writeStream(abort, body, client, request4, socket, contentLength, header, expectsPayload) {
      assert3(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
      let finished = false;
      const writer = new AsyncWriter({ abort, socket, request: request4, contentLength, client, expectsPayload, header });
      const onData = /* @__PURE__ */ __name(function(chunk) {
        if (finished) {
          return;
        }
        try {
          if (!writer.write(chunk) && this.pause) {
            this.pause();
          }
        } catch (err) {
          util4.destroy(this, err);
        }
      }, "onData");
      const onDrain = /* @__PURE__ */ __name(function() {
        if (finished) {
          return;
        }
        if (body.resume) {
          body.resume();
        }
      }, "onDrain");
      const onClose = /* @__PURE__ */ __name(function() {
        queueMicrotask(() => {
          body.removeListener("error", onFinished);
        });
        if (!finished) {
          const err = new RequestAbortedError();
          queueMicrotask(() => onFinished(err));
        }
      }, "onClose");
      const onFinished = /* @__PURE__ */ __name(function(err) {
        if (finished) {
          return;
        }
        finished = true;
        assert3(socket.destroyed || socket[kWriting] && client[kRunning] <= 1);
        socket.off("drain", onDrain).off("error", onFinished);
        body.removeListener("data", onData).removeListener("end", onFinished).removeListener("close", onClose);
        if (!err) {
          try {
            writer.end();
          } catch (er) {
            err = er;
          }
        }
        writer.destroy(err);
        if (err && (err.code !== "UND_ERR_INFO" || err.message !== "reset")) {
          util4.destroy(body, err);
        } else {
          util4.destroy(body);
        }
      }, "onFinished");
      body.on("data", onData).on("end", onFinished).on("error", onFinished).on("close", onClose);
      if (body.resume) {
        body.resume();
      }
      socket.on("drain", onDrain).on("error", onFinished);
      if (body.errorEmitted ?? body.errored) {
        setImmediate(onFinished, body.errored);
      } else if (body.endEmitted ?? body.readableEnded) {
        setImmediate(onFinished, null);
      }
      if (body.closeEmitted ?? body.closed) {
        setImmediate(onClose);
      }
    }
    __name(writeStream, "writeStream");
    function writeBuffer(abort, body, client, request4, socket, contentLength, header, expectsPayload) {
      try {
        if (!body) {
          if (contentLength === 0) {
            socket.write(`${header}content-length: 0\r
\r
`, "latin1");
          } else {
            assert3(contentLength === null, "no body must not have content length");
            socket.write(`${header}\r
`, "latin1");
          }
        } else if (util4.isBuffer(body)) {
          assert3(contentLength === body.byteLength, "buffer body must have content length");
          socket.cork();
          socket.write(`${header}content-length: ${contentLength}\r
\r
`, "latin1");
          socket.write(body);
          socket.uncork();
          request4.onBodySent(body);
          if (!expectsPayload && request4.reset !== false) {
            socket[kReset2] = true;
          }
        }
        request4.onRequestSent();
        client[kResume]();
      } catch (err) {
        abort(err);
      }
    }
    __name(writeBuffer, "writeBuffer");
    async function writeBlob(abort, body, client, request4, socket, contentLength, header, expectsPayload) {
      assert3(contentLength === body.size, "blob body must have content length");
      try {
        if (contentLength != null && contentLength !== body.size) {
          throw new RequestContentLengthMismatchError();
        }
        const buffer = Buffer.from(await body.arrayBuffer());
        socket.cork();
        socket.write(`${header}content-length: ${contentLength}\r
\r
`, "latin1");
        socket.write(buffer);
        socket.uncork();
        request4.onBodySent(buffer);
        request4.onRequestSent();
        if (!expectsPayload && request4.reset !== false) {
          socket[kReset2] = true;
        }
        client[kResume]();
      } catch (err) {
        abort(err);
      }
    }
    __name(writeBlob, "writeBlob");
    async function writeIterable(abort, body, client, request4, socket, contentLength, header, expectsPayload) {
      assert3(contentLength !== 0 || client[kRunning] === 0, "iterator body cannot be pipelined");
      let callback = null;
      function onDrain() {
        if (callback) {
          const cb = callback;
          callback = null;
          cb();
        }
      }
      __name(onDrain, "onDrain");
      const waitForDrain = /* @__PURE__ */ __name(() => new Promise((resolve24, reject) => {
        assert3(callback === null);
        if (socket[kError]) {
          reject(socket[kError]);
        } else {
          callback = resolve24;
        }
      }), "waitForDrain");
      socket.on("close", onDrain).on("drain", onDrain);
      const writer = new AsyncWriter({ abort, socket, request: request4, contentLength, client, expectsPayload, header });
      try {
        for await (const chunk of body) {
          if (socket[kError]) {
            throw socket[kError];
          }
          if (!writer.write(chunk)) {
            await waitForDrain();
          }
        }
        writer.end();
      } catch (err) {
        writer.destroy(err);
      } finally {
        socket.off("close", onDrain).off("drain", onDrain);
      }
    }
    __name(writeIterable, "writeIterable");
    var AsyncWriter = class {
      static {
        __name(this, "AsyncWriter");
      }
      /**
       *
       * @param {object} arg
       * @param {AbortCallback} arg.abort
       * @param {import('net').Socket} arg.socket
       * @param {import('../core/request.js')} arg.request
       * @param {number} arg.contentLength
       * @param {import('./client.js')} arg.client
       * @param {boolean} arg.expectsPayload
       * @param {string} arg.header
       */
      constructor({ abort, socket, request: request4, contentLength, client, expectsPayload, header }) {
        this.socket = socket;
        this.request = request4;
        this.contentLength = contentLength;
        this.client = client;
        this.bytesWritten = 0;
        this.expectsPayload = expectsPayload;
        this.header = header;
        this.abort = abort;
        socket[kWriting] = true;
      }
      /**
       * @param {Buffer} chunk
       * @returns
       */
      write(chunk) {
        const { socket, request: request4, contentLength, client, bytesWritten, expectsPayload, header } = this;
        if (socket[kError]) {
          throw socket[kError];
        }
        if (socket.destroyed) {
          return false;
        }
        const len = Buffer.byteLength(chunk);
        if (!len) {
          return true;
        }
        if (contentLength !== null && bytesWritten + len > contentLength) {
          if (client[kStrictContentLength]) {
            throw new RequestContentLengthMismatchError();
          }
          process.emitWarning(new RequestContentLengthMismatchError());
        }
        socket.cork();
        if (bytesWritten === 0) {
          if (!expectsPayload && request4.reset !== false) {
            socket[kReset2] = true;
          }
          if (contentLength === null) {
            socket.write(`${header}transfer-encoding: chunked\r
`, "latin1");
          } else {
            socket.write(`${header}content-length: ${contentLength}\r
\r
`, "latin1");
          }
        }
        if (contentLength === null) {
          socket.write(`\r
${len.toString(16)}\r
`, "latin1");
        }
        this.bytesWritten += len;
        const ret = socket.write(chunk);
        socket.uncork();
        request4.onBodySent(chunk);
        if (!ret) {
          if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
            if (socket[kParser].timeout.refresh) {
              socket[kParser].timeout.refresh();
            }
          }
        }
        return ret;
      }
      /**
       * @returns {void}
       */
      end() {
        const { socket, contentLength, client, bytesWritten, expectsPayload, header, request: request4 } = this;
        request4.onRequestSent();
        socket[kWriting] = false;
        if (socket[kError]) {
          throw socket[kError];
        }
        if (socket.destroyed) {
          return;
        }
        if (bytesWritten === 0) {
          if (expectsPayload) {
            socket.write(`${header}content-length: 0\r
\r
`, "latin1");
          } else {
            socket.write(`${header}\r
`, "latin1");
          }
        } else if (contentLength === null) {
          socket.write("\r\n0\r\n\r\n", "latin1");
        }
        if (contentLength !== null && bytesWritten !== contentLength) {
          if (client[kStrictContentLength]) {
            throw new RequestContentLengthMismatchError();
          } else {
            process.emitWarning(new RequestContentLengthMismatchError());
          }
        }
        if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
          if (socket[kParser].timeout.refresh) {
            socket[kParser].timeout.refresh();
          }
        }
        client[kResume]();
      }
      /**
       * @param {Error} [err]
       * @returns {void}
       */
      destroy(err) {
        const { socket, client, abort } = this;
        socket[kWriting] = false;
        if (err) {
          assert3(client[kRunning] <= 1, "pipeline should only contain this request");
          abort(err);
        }
      }
    };
    module2.exports = connectH1;
  }
});

// node_modules/undici/lib/dispatcher/client-h2.js
var require_client_h2 = __commonJS({
  "node_modules/undici/lib/dispatcher/client-h2.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert3 = __require("node:assert");
    var { pipeline } = __require("node:stream");
    var util4 = require_util();
    var {
      RequestContentLengthMismatchError,
      RequestAbortedError,
      SocketError,
      InformationalError
    } = require_errors();
    var {
      kUrl,
      kReset: kReset2,
      kClient,
      kRunning,
      kPending,
      kQueue,
      kPendingIdx,
      kRunningIdx,
      kError,
      kSocket,
      kStrictContentLength,
      kOnError,
      kMaxConcurrentStreams,
      kHTTP2Session,
      kResume,
      kSize,
      kHTTPContext,
      kClosed,
      kBodyTimeout
    } = require_symbols();
    var { channels } = require_diagnostics();
    var kOpenStreams = Symbol("open streams");
    var extractBody;
    var http22;
    try {
      http22 = __require("node:http2");
    } catch {
      http22 = { constants: {} };
    }
    var {
      constants: {
        HTTP2_HEADER_AUTHORITY,
        HTTP2_HEADER_METHOD,
        HTTP2_HEADER_PATH,
        HTTP2_HEADER_SCHEME,
        HTTP2_HEADER_CONTENT_LENGTH,
        HTTP2_HEADER_EXPECT,
        HTTP2_HEADER_STATUS
      }
    } = http22;
    function parseH2Headers(headers) {
      const result = [];
      for (const [name3, value] of Object.entries(headers)) {
        if (Array.isArray(value)) {
          for (const subvalue of value) {
            result.push(Buffer.from(name3), Buffer.from(subvalue));
          }
        } else {
          result.push(Buffer.from(name3), Buffer.from(value));
        }
      }
      return result;
    }
    __name(parseH2Headers, "parseH2Headers");
    async function connectH2(client, socket) {
      client[kSocket] = socket;
      const session = http22.connect(client[kUrl], {
        createConnection: /* @__PURE__ */ __name(() => socket, "createConnection"),
        peerMaxConcurrentStreams: client[kMaxConcurrentStreams],
        settings: {
          // TODO(metcoder95): add support for PUSH
          enablePush: false
        }
      });
      session[kOpenStreams] = 0;
      session[kClient] = client;
      session[kSocket] = socket;
      session[kHTTP2Session] = null;
      util4.addListener(session, "error", onHttp2SessionError);
      util4.addListener(session, "frameError", onHttp2FrameError);
      util4.addListener(session, "end", onHttp2SessionEnd);
      util4.addListener(session, "goaway", onHttp2SessionGoAway);
      util4.addListener(session, "close", onHttp2SessionClose);
      session.unref();
      client[kHTTP2Session] = session;
      socket[kHTTP2Session] = session;
      util4.addListener(socket, "error", onHttp2SocketError);
      util4.addListener(socket, "end", onHttp2SocketEnd);
      util4.addListener(socket, "close", onHttp2SocketClose);
      socket[kClosed] = false;
      socket.on("close", onSocketClose);
      return {
        version: "h2",
        defaultPipelining: Infinity,
        write(request4) {
          return writeH2(client, request4);
        },
        resume() {
          resumeH2(client);
        },
        destroy(err, callback) {
          if (socket[kClosed]) {
            queueMicrotask(callback);
          } else {
            socket.destroy(err).on("close", callback);
          }
        },
        get destroyed() {
          return socket.destroyed;
        },
        busy() {
          return false;
        }
      };
    }
    __name(connectH2, "connectH2");
    function resumeH2(client) {
      const socket = client[kSocket];
      if (socket?.destroyed === false) {
        if (client[kSize] === 0 || client[kMaxConcurrentStreams] === 0) {
          socket.unref();
          client[kHTTP2Session].unref();
        } else {
          socket.ref();
          client[kHTTP2Session].ref();
        }
      }
    }
    __name(resumeH2, "resumeH2");
    function onHttp2SessionError(err) {
      assert3(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
      this[kSocket][kError] = err;
      this[kClient][kOnError](err);
    }
    __name(onHttp2SessionError, "onHttp2SessionError");
    function onHttp2FrameError(type, code2, id) {
      if (id === 0) {
        const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code2}`);
        this[kSocket][kError] = err;
        this[kClient][kOnError](err);
      }
    }
    __name(onHttp2FrameError, "onHttp2FrameError");
    function onHttp2SessionEnd() {
      const err = new SocketError("other side closed", util4.getSocketInfo(this[kSocket]));
      this.destroy(err);
      util4.destroy(this[kSocket], err);
    }
    __name(onHttp2SessionEnd, "onHttp2SessionEnd");
    function onHttp2SessionGoAway(errorCode) {
      const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util4.getSocketInfo(this[kSocket]));
      const client = this[kClient];
      client[kSocket] = null;
      client[kHTTPContext] = null;
      this.close();
      this[kHTTP2Session] = null;
      util4.destroy(this[kSocket], err);
      if (client[kRunningIdx] < client[kQueue].length) {
        const request4 = client[kQueue][client[kRunningIdx]];
        client[kQueue][client[kRunningIdx]++] = null;
        util4.errorRequest(client, request4, err);
        client[kPendingIdx] = client[kRunningIdx];
      }
      assert3(client[kRunning] === 0);
      client.emit("disconnect", client[kUrl], [client], err);
      client.emit("connectionError", client[kUrl], [client], err);
      client[kResume]();
    }
    __name(onHttp2SessionGoAway, "onHttp2SessionGoAway");
    function onHttp2SessionClose() {
      const { [kClient]: client } = this;
      const { [kSocket]: socket } = client;
      const err = this[kSocket][kError] || this[kError] || new SocketError("closed", util4.getSocketInfo(socket));
      client[kSocket] = null;
      client[kHTTPContext] = null;
      if (client.destroyed) {
        assert3(client[kPending] === 0);
        const requests = client[kQueue].splice(client[kRunningIdx]);
        for (let i = 0; i < requests.length; i++) {
          const request4 = requests[i];
          util4.errorRequest(client, request4, err);
        }
      }
    }
    __name(onHttp2SessionClose, "onHttp2SessionClose");
    function onHttp2SocketClose() {
      const err = this[kError] || new SocketError("closed", util4.getSocketInfo(this));
      const client = this[kHTTP2Session][kClient];
      client[kSocket] = null;
      client[kHTTPContext] = null;
      if (this[kHTTP2Session] !== null) {
        this[kHTTP2Session].destroy(err);
      }
      client[kPendingIdx] = client[kRunningIdx];
      assert3(client[kRunning] === 0);
      client.emit("disconnect", client[kUrl], [client], err);
      client[kResume]();
    }
    __name(onHttp2SocketClose, "onHttp2SocketClose");
    function onHttp2SocketError(err) {
      assert3(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
      this[kError] = err;
      this[kClient][kOnError](err);
    }
    __name(onHttp2SocketError, "onHttp2SocketError");
    function onHttp2SocketEnd() {
      util4.destroy(this, new SocketError("other side closed", util4.getSocketInfo(this)));
    }
    __name(onHttp2SocketEnd, "onHttp2SocketEnd");
    function onSocketClose() {
      this[kClosed] = true;
    }
    __name(onSocketClose, "onSocketClose");
    function shouldSendContentLength(method) {
      return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
    }
    __name(shouldSendContentLength, "shouldSendContentLength");
    function writeH2(client, request4) {
      const requestTimeout = request4.bodyTimeout ?? client[kBodyTimeout];
      const session = client[kHTTP2Session];
      const { method, path: path108, host, upgrade, expectContinue, signal, headers: reqHeaders } = request4;
      let { body } = request4;
      if (upgrade) {
        util4.errorRequest(client, request4, new Error("Upgrade not supported for H2"));
        return false;
      }
      const headers = {};
      for (let n2 = 0; n2 < reqHeaders.length; n2 += 2) {
        const key = reqHeaders[n2 + 0];
        const val = reqHeaders[n2 + 1];
        if (Array.isArray(val)) {
          for (let i = 0; i < val.length; i++) {
            if (headers[key]) {
              headers[key] += `, ${val[i]}`;
            } else {
              headers[key] = val[i];
            }
          }
        } else if (headers[key]) {
          headers[key] += `, ${val}`;
        } else {
          headers[key] = val;
        }
      }
      let stream2 = null;
      const { hostname: hostname3, port } = client[kUrl];
      headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname3}${port ? `:${port}` : ""}`;
      headers[HTTP2_HEADER_METHOD] = method;
      const abort = /* @__PURE__ */ __name((err) => {
        if (request4.aborted || request4.completed) {
          return;
        }
        err = err || new RequestAbortedError();
        util4.errorRequest(client, request4, err);
        if (stream2 != null) {
          stream2.removeAllListeners("data");
          stream2.close();
          client[kOnError](err);
          client[kResume]();
        }
        util4.destroy(body, err);
      }, "abort");
      try {
        request4.onConnect(abort);
      } catch (err) {
        util4.errorRequest(client, request4, err);
      }
      if (request4.aborted) {
        return false;
      }
      if (method === "CONNECT") {
        session.ref();
        stream2 = session.request(headers, { endStream: false, signal });
        if (!stream2.pending) {
          request4.onUpgrade(null, null, stream2);
          ++session[kOpenStreams];
          client[kQueue][client[kRunningIdx]++] = null;
        } else {
          stream2.once("ready", () => {
            request4.onUpgrade(null, null, stream2);
            ++session[kOpenStreams];
            client[kQueue][client[kRunningIdx]++] = null;
          });
        }
        stream2.once("close", () => {
          session[kOpenStreams] -= 1;
          if (session[kOpenStreams] === 0) session.unref();
        });
        stream2.setTimeout(requestTimeout);
        return true;
      }
      headers[HTTP2_HEADER_PATH] = path108;
      headers[HTTP2_HEADER_SCHEME] = "https";
      const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
      if (body && typeof body.read === "function") {
        body.read(0);
      }
      let contentLength = util4.bodyLength(body);
      if (util4.isFormDataLike(body)) {
        extractBody ??= require_body().extractBody;
        const [bodyStream, contentType] = extractBody(body);
        headers["content-type"] = contentType;
        body = bodyStream.stream;
        contentLength = bodyStream.length;
      }
      if (contentLength == null) {
        contentLength = request4.contentLength;
      }
      if (contentLength === 0 || !expectsPayload) {
        contentLength = null;
      }
      if (shouldSendContentLength(method) && contentLength > 0 && request4.contentLength != null && request4.contentLength !== contentLength) {
        if (client[kStrictContentLength]) {
          util4.errorRequest(client, request4, new RequestContentLengthMismatchError());
          return false;
        }
        process.emitWarning(new RequestContentLengthMismatchError());
      }
      if (contentLength != null) {
        assert3(body, "no body must not have content length");
        headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`;
      }
      session.ref();
      if (channels.sendHeaders.hasSubscribers) {
        let header = "";
        for (const key in headers) {
          header += `${key}: ${headers[key]}\r
`;
        }
        channels.sendHeaders.publish({ request: request4, headers: header, socket: session[kSocket] });
      }
      const shouldEndStream = method === "GET" || method === "HEAD" || body === null;
      if (expectContinue) {
        headers[HTTP2_HEADER_EXPECT] = "100-continue";
        stream2 = session.request(headers, { endStream: shouldEndStream, signal });
        stream2.once("continue", writeBodyH2);
      } else {
        stream2 = session.request(headers, {
          endStream: shouldEndStream,
          signal
        });
        writeBodyH2();
      }
      ++session[kOpenStreams];
      stream2.setTimeout(requestTimeout);
      stream2.once("response", (headers2) => {
        const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
        request4.onResponseStarted();
        if (request4.aborted) {
          stream2.removeAllListeners("data");
          return;
        }
        if (request4.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream2.resume.bind(stream2), "") === false) {
          stream2.pause();
        }
      });
      stream2.on("data", (chunk) => {
        if (request4.onData(chunk) === false) {
          stream2.pause();
        }
      });
      stream2.once("end", (err) => {
        stream2.removeAllListeners("data");
        if (stream2.state?.state == null || stream2.state.state < 6) {
          if (!request4.aborted && !request4.completed) {
            request4.onComplete({});
          }
          client[kQueue][client[kRunningIdx]++] = null;
          client[kResume]();
        } else {
          --session[kOpenStreams];
          if (session[kOpenStreams] === 0) {
            session.unref();
          }
          abort(err ?? new InformationalError("HTTP/2: stream half-closed (remote)"));
          client[kQueue][client[kRunningIdx]++] = null;
          client[kPendingIdx] = client[kRunningIdx];
          client[kResume]();
        }
      });
      stream2.once("close", () => {
        stream2.removeAllListeners("data");
        session[kOpenStreams] -= 1;
        if (session[kOpenStreams] === 0) {
          session.unref();
        }
      });
      stream2.once("error", function(err) {
        stream2.removeAllListeners("data");
        abort(err);
      });
      stream2.once("frameError", (type, code2) => {
        stream2.removeAllListeners("data");
        abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code2}`));
      });
      stream2.on("aborted", () => {
        stream2.removeAllListeners("data");
      });
      stream2.on("timeout", () => {
        const err = new InformationalError(`HTTP/2: "stream timeout after ${requestTimeout}"`);
        stream2.removeAllListeners("data");
        session[kOpenStreams] -= 1;
        if (session[kOpenStreams] === 0) {
          session.unref();
        }
        abort(err);
      });
      stream2.once("trailers", (trailers) => {
        if (request4.aborted || request4.completed) {
          return;
        }
        request4.onComplete(trailers);
      });
      return true;
      function writeBodyH2() {
        if (!body || contentLength === 0) {
          writeBuffer(
            abort,
            stream2,
            null,
            client,
            request4,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else if (util4.isBuffer(body)) {
          writeBuffer(
            abort,
            stream2,
            body,
            client,
            request4,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else if (util4.isBlobLike(body)) {
          if (typeof body.stream === "function") {
            writeIterable(
              abort,
              stream2,
              body.stream(),
              client,
              request4,
              client[kSocket],
              contentLength,
              expectsPayload
            );
          } else {
            writeBlob(
              abort,
              stream2,
              body,
              client,
              request4,
              client[kSocket],
              contentLength,
              expectsPayload
            );
          }
        } else if (util4.isStream(body)) {
          writeStream(
            abort,
            client[kSocket],
            expectsPayload,
            stream2,
            body,
            client,
            request4,
            contentLength
          );
        } else if (util4.isIterable(body)) {
          writeIterable(
            abort,
            stream2,
            body,
            client,
            request4,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else {
          assert3(false);
        }
      }
      __name(writeBodyH2, "writeBodyH2");
    }
    __name(writeH2, "writeH2");
    function writeBuffer(abort, h2stream, body, client, request4, socket, contentLength, expectsPayload) {
      try {
        if (body != null && util4.isBuffer(body)) {
          assert3(contentLength === body.byteLength, "buffer body must have content length");
          h2stream.cork();
          h2stream.write(body);
          h2stream.uncork();
          h2stream.end();
          request4.onBodySent(body);
        }
        if (!expectsPayload) {
          socket[kReset2] = true;
        }
        request4.onRequestSent();
        client[kResume]();
      } catch (error) {
        abort(error);
      }
    }
    __name(writeBuffer, "writeBuffer");
    function writeStream(abort, socket, expectsPayload, h2stream, body, client, request4, contentLength) {
      assert3(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
      const pipe = pipeline(
        body,
        h2stream,
        (err) => {
          if (err) {
            util4.destroy(pipe, err);
            abort(err);
          } else {
            util4.removeAllListeners(pipe);
            request4.onRequestSent();
            if (!expectsPayload) {
              socket[kReset2] = true;
            }
            client[kResume]();
          }
        }
      );
      util4.addListener(pipe, "data", onPipeData);
      function onPipeData(chunk) {
        request4.onBodySent(chunk);
      }
      __name(onPipeData, "onPipeData");
    }
    __name(writeStream, "writeStream");
    async function writeBlob(abort, h2stream, body, client, request4, socket, contentLength, expectsPayload) {
      assert3(contentLength === body.size, "blob body must have content length");
      try {
        if (contentLength != null && contentLength !== body.size) {
          throw new RequestContentLengthMismatchError();
        }
        const buffer = Buffer.from(await body.arrayBuffer());
        h2stream.cork();
        h2stream.write(buffer);
        h2stream.uncork();
        h2stream.end();
        request4.onBodySent(buffer);
        request4.onRequestSent();
        if (!expectsPayload) {
          socket[kReset2] = true;
        }
        client[kResume]();
      } catch (err) {
        abort(err);
      }
    }
    __name(writeBlob, "writeBlob");
    async function writeIterable(abort, h2stream, body, client, request4, socket, contentLength, expectsPayload) {
      assert3(contentLength !== 0 || client[kRunning] === 0, "iterator body cannot be pipelined");
      let callback = null;
      function onDrain() {
        if (callback) {
          const cb = callback;
          callback = null;
          cb();
        }
      }
      __name(onDrain, "onDrain");
      const waitForDrain = /* @__PURE__ */ __name(() => new Promise((resolve24, reject) => {
        assert3(callback === null);
        if (socket[kError]) {
          reject(socket[kError]);
        } else {
          callback = resolve24;
        }
      }), "waitForDrain");
      h2stream.on("close", onDrain).on("drain", onDrain);
      try {
        for await (const chunk of body) {
          if (socket[kError]) {
            throw socket[kError];
          }
          const res = h2stream.write(chunk);
          request4.onBodySent(chunk);
          if (!res) {
            await waitForDrain();
          }
        }
        h2stream.end();
        request4.onRequestSent();
        if (!expectsPayload) {
          socket[kReset2] = true;
        }
        client[kResume]();
      } catch (err) {
        abort(err);
      } finally {
        h2stream.off("close", onDrain).off("drain", onDrain);
      }
    }
    __name(writeIterable, "writeIterable");
    module2.exports = connectH2;
  }
});

// node_modules/undici/lib/dispatcher/client.js
var require_client = __commonJS({
  "node_modules/undici/lib/dispatcher/client.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert3 = __require("node:assert");
    var net2 = __require("node:net");
    var http4 = __require("node:http");
    var util4 = require_util();
    var { ClientStats } = require_stats();
    var { channels } = require_diagnostics();
    var Request2 = require_request();
    var DispatcherBase = require_dispatcher_base();
    var {
      InvalidArgumentError,
      InformationalError,
      ClientDestroyedError
    } = require_errors();
    var buildConnector = require_connect();
    var {
      kUrl,
      kServerName,
      kClient,
      kBusy,
      kConnect,
      kResuming,
      kRunning,
      kPending,
      kSize,
      kQueue,
      kConnected,
      kConnecting,
      kNeedDrain,
      kKeepAliveDefaultTimeout,
      kHostHeader,
      kPendingIdx,
      kRunningIdx,
      kError,
      kPipelining,
      kKeepAliveTimeoutValue,
      kMaxHeadersSize,
      kKeepAliveMaxTimeout,
      kKeepAliveTimeoutThreshold,
      kHeadersTimeout,
      kBodyTimeout,
      kStrictContentLength,
      kConnector,
      kMaxRequests,
      kCounter,
      kClose,
      kDestroy,
      kDispatch,
      kLocalAddress,
      kMaxResponseSize,
      kOnError,
      kHTTPContext,
      kMaxConcurrentStreams,
      kResume
    } = require_symbols();
    var connectH1 = require_client_h1();
    var connectH2 = require_client_h2();
    var kClosedResolve = Symbol("kClosedResolve");
    var getDefaultNodeMaxHeaderSize = http4 && http4.maxHeaderSize && Number.isInteger(http4.maxHeaderSize) && http4.maxHeaderSize > 0 ? () => http4.maxHeaderSize : () => {
      throw new InvalidArgumentError("http module not available or http.maxHeaderSize invalid");
    };
    var noop6 = /* @__PURE__ */ __name(() => {
    }, "noop");
    function getPipelining(client) {
      return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1;
    }
    __name(getPipelining, "getPipelining");
    var Client2 = class extends DispatcherBase {
      static {
        __name(this, "Client");
      }
      /**
       *
       * @param {string|URL} url
       * @param {import('../../types/client.js').Client.Options} options
       */
      constructor(url2, {
        maxHeaderSize,
        headersTimeout,
        socketTimeout,
        requestTimeout,
        connectTimeout,
        bodyTimeout,
        idleTimeout,
        keepAlive,
        keepAliveTimeout,
        maxKeepAliveTimeout,
        keepAliveMaxTimeout,
        keepAliveTimeoutThreshold,
        socketPath,
        pipelining,
        tls,
        strictContentLength,
        maxCachedSessions,
        connect: connect2,
        maxRequestsPerClient,
        localAddress,
        maxResponseSize,
        autoSelectFamily,
        autoSelectFamilyAttemptTimeout,
        // h2
        maxConcurrentStreams,
        allowH2
      } = {}) {
        if (keepAlive !== void 0) {
          throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead");
        }
        if (socketTimeout !== void 0) {
          throw new InvalidArgumentError("unsupported socketTimeout, use headersTimeout & bodyTimeout instead");
        }
        if (requestTimeout !== void 0) {
          throw new InvalidArgumentError("unsupported requestTimeout, use headersTimeout & bodyTimeout instead");
        }
        if (idleTimeout !== void 0) {
          throw new InvalidArgumentError("unsupported idleTimeout, use keepAliveTimeout instead");
        }
        if (maxKeepAliveTimeout !== void 0) {
          throw new InvalidArgumentError("unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead");
        }
        if (maxHeaderSize != null) {
          if (!Number.isInteger(maxHeaderSize) || maxHeaderSize < 1) {
            throw new InvalidArgumentError("invalid maxHeaderSize");
          }
        } else {
          maxHeaderSize = getDefaultNodeMaxHeaderSize();
        }
        if (socketPath != null && typeof socketPath !== "string") {
          throw new InvalidArgumentError("invalid socketPath");
        }
        if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
          throw new InvalidArgumentError("invalid connectTimeout");
        }
        if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
          throw new InvalidArgumentError("invalid keepAliveTimeout");
        }
        if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
          throw new InvalidArgumentError("invalid keepAliveMaxTimeout");
        }
        if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
          throw new InvalidArgumentError("invalid keepAliveTimeoutThreshold");
        }
        if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
          throw new InvalidArgumentError("headersTimeout must be a positive integer or zero");
        }
        if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
          throw new InvalidArgumentError("bodyTimeout must be a positive integer or zero");
        }
        if (connect2 != null && typeof connect2 !== "function" && typeof connect2 !== "object") {
          throw new InvalidArgumentError("connect must be a function or an object");
        }
        if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
          throw new InvalidArgumentError("maxRequestsPerClient must be a positive number");
        }
        if (localAddress != null && (typeof localAddress !== "string" || net2.isIP(localAddress) === 0)) {
          throw new InvalidArgumentError("localAddress must be valid string IP address");
        }
        if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
          throw new InvalidArgumentError("maxResponseSize must be a positive number");
        }
        if (autoSelectFamilyAttemptTimeout != null && (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)) {
          throw new InvalidArgumentError("autoSelectFamilyAttemptTimeout must be a positive number");
        }
        if (allowH2 != null && typeof allowH2 !== "boolean") {
          throw new InvalidArgumentError("allowH2 must be a valid boolean value");
        }
        if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== "number" || maxConcurrentStreams < 1)) {
          throw new InvalidArgumentError("maxConcurrentStreams must be a positive integer, greater than 0");
        }
        super();
        if (typeof connect2 !== "function") {
          connect2 = buildConnector({
            ...tls,
            maxCachedSessions,
            allowH2,
            socketPath,
            timeout: connectTimeout,
            ...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
            ...connect2
          });
        }
        this[kUrl] = util4.parseOrigin(url2);
        this[kConnector] = connect2;
        this[kPipelining] = pipelining != null ? pipelining : 1;
        this[kMaxHeadersSize] = maxHeaderSize;
        this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout;
        this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 6e5 : keepAliveMaxTimeout;
        this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold;
        this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout];
        this[kServerName] = null;
        this[kLocalAddress] = localAddress != null ? localAddress : null;
        this[kResuming] = 0;
        this[kNeedDrain] = 0;
        this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ""}\r
`;
        this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 3e5;
        this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 3e5;
        this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength;
        this[kMaxRequests] = maxRequestsPerClient;
        this[kClosedResolve] = null;
        this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1;
        this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100;
        this[kHTTPContext] = null;
        this[kQueue] = [];
        this[kRunningIdx] = 0;
        this[kPendingIdx] = 0;
        this[kResume] = (sync2) => resume(this, sync2);
        this[kOnError] = (err) => onError2(this, err);
      }
      get pipelining() {
        return this[kPipelining];
      }
      set pipelining(value) {
        this[kPipelining] = value;
        this[kResume](true);
      }
      get stats() {
        return new ClientStats(this);
      }
      get [kPending]() {
        return this[kQueue].length - this[kPendingIdx];
      }
      get [kRunning]() {
        return this[kPendingIdx] - this[kRunningIdx];
      }
      get [kSize]() {
        return this[kQueue].length - this[kRunningIdx];
      }
      get [kConnected]() {
        return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed;
      }
      get [kBusy]() {
        return Boolean(
          this[kHTTPContext]?.busy(null) || this[kSize] >= (getPipelining(this) || 1) || this[kPending] > 0
        );
      }
      /* istanbul ignore: only used for test */
      [kConnect](cb) {
        connect(this);
        this.once("connect", cb);
      }
      [kDispatch](opts, handler) {
        const origin = opts.origin || this[kUrl].origin;
        const request4 = new Request2(origin, opts, handler);
        this[kQueue].push(request4);
        if (this[kResuming]) {
        } else if (util4.bodyLength(request4.body) == null && util4.isIterable(request4.body)) {
          this[kResuming] = 1;
          queueMicrotask(() => resume(this));
        } else {
          this[kResume](true);
        }
        if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
          this[kNeedDrain] = 2;
        }
        return this[kNeedDrain] < 2;
      }
      async [kClose]() {
        return new Promise((resolve24) => {
          if (this[kSize]) {
            this[kClosedResolve] = resolve24;
          } else {
            resolve24(null);
          }
        });
      }
      async [kDestroy](err) {
        return new Promise((resolve24) => {
          const requests = this[kQueue].splice(this[kPendingIdx]);
          for (let i = 0; i < requests.length; i++) {
            const request4 = requests[i];
            util4.errorRequest(this, request4, err);
          }
          const callback = /* @__PURE__ */ __name(() => {
            if (this[kClosedResolve]) {
              this[kClosedResolve]();
              this[kClosedResolve] = null;
            }
            resolve24(null);
          }, "callback");
          if (this[kHTTPContext]) {
            this[kHTTPContext].destroy(err, callback);
            this[kHTTPContext] = null;
          } else {
            queueMicrotask(callback);
          }
          this[kResume]();
        });
      }
    };
    function onError2(client, err) {
      if (client[kRunning] === 0 && err.code !== "UND_ERR_INFO" && err.code !== "UND_ERR_SOCKET") {
        assert3(client[kPendingIdx] === client[kRunningIdx]);
        const requests = client[kQueue].splice(client[kRunningIdx]);
        for (let i = 0; i < requests.length; i++) {
          const request4 = requests[i];
          util4.errorRequest(client, request4, err);
        }
        assert3(client[kSize] === 0);
      }
    }
    __name(onError2, "onError");
    async function connect(client) {
      assert3(!client[kConnecting]);
      assert3(!client[kHTTPContext]);
      let { host, hostname: hostname3, protocol, port } = client[kUrl];
      if (hostname3[0] === "[") {
        const idx = hostname3.indexOf("]");
        assert3(idx !== -1);
        const ip = hostname3.substring(1, idx);
        assert3(net2.isIPv6(ip));
        hostname3 = ip;
      }
      client[kConnecting] = true;
      if (channels.beforeConnect.hasSubscribers) {
        channels.beforeConnect.publish({
          connectParams: {
            host,
            hostname: hostname3,
            protocol,
            port,
            version: client[kHTTPContext]?.version,
            servername: client[kServerName],
            localAddress: client[kLocalAddress]
          },
          connector: client[kConnector]
        });
      }
      try {
        const socket = await new Promise((resolve24, reject) => {
          client[kConnector]({
            host,
            hostname: hostname3,
            protocol,
            port,
            servername: client[kServerName],
            localAddress: client[kLocalAddress]
          }, (err, socket2) => {
            if (err) {
              reject(err);
            } else {
              resolve24(socket2);
            }
          });
        });
        if (client.destroyed) {
          util4.destroy(socket.on("error", noop6), new ClientDestroyedError());
          return;
        }
        assert3(socket);
        try {
          client[kHTTPContext] = socket.alpnProtocol === "h2" ? await connectH2(client, socket) : await connectH1(client, socket);
        } catch (err) {
          socket.destroy().on("error", noop6);
          throw err;
        }
        client[kConnecting] = false;
        socket[kCounter] = 0;
        socket[kMaxRequests] = client[kMaxRequests];
        socket[kClient] = client;
        socket[kError] = null;
        if (channels.connected.hasSubscribers) {
          channels.connected.publish({
            connectParams: {
              host,
              hostname: hostname3,
              protocol,
              port,
              version: client[kHTTPContext]?.version,
              servername: client[kServerName],
              localAddress: client[kLocalAddress]
            },
            connector: client[kConnector],
            socket
          });
        }
        client.emit("connect", client[kUrl], [client]);
      } catch (err) {
        if (client.destroyed) {
          return;
        }
        client[kConnecting] = false;
        if (channels.connectError.hasSubscribers) {
          channels.connectError.publish({
            connectParams: {
              host,
              hostname: hostname3,
              protocol,
              port,
              version: client[kHTTPContext]?.version,
              servername: client[kServerName],
              localAddress: client[kLocalAddress]
            },
            connector: client[kConnector],
            error: err
          });
        }
        if (err.code === "ERR_TLS_CERT_ALTNAME_INVALID") {
          assert3(client[kRunning] === 0);
          while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
            const request4 = client[kQueue][client[kPendingIdx]++];
            util4.errorRequest(client, request4, err);
          }
        } else {
          onError2(client, err);
        }
        client.emit("connectionError", client[kUrl], [client], err);
      }
      client[kResume]();
    }
    __name(connect, "connect");
    function emitDrain(client) {
      client[kNeedDrain] = 0;
      client.emit("drain", client[kUrl], [client]);
    }
    __name(emitDrain, "emitDrain");
    function resume(client, sync2) {
      if (client[kResuming] === 2) {
        return;
      }
      client[kResuming] = 2;
      _resume(client, sync2);
      client[kResuming] = 0;
      if (client[kRunningIdx] > 256) {
        client[kQueue].splice(0, client[kRunningIdx]);
        client[kPendingIdx] -= client[kRunningIdx];
        client[kRunningIdx] = 0;
      }
    }
    __name(resume, "resume");
    function _resume(client, sync2) {
      while (true) {
        if (client.destroyed) {
          assert3(client[kPending] === 0);
          return;
        }
        if (client[kClosedResolve] && !client[kSize]) {
          client[kClosedResolve]();
          client[kClosedResolve] = null;
          return;
        }
        if (client[kHTTPContext]) {
          client[kHTTPContext].resume();
        }
        if (client[kBusy]) {
          client[kNeedDrain] = 2;
        } else if (client[kNeedDrain] === 2) {
          if (sync2) {
            client[kNeedDrain] = 1;
            queueMicrotask(() => emitDrain(client));
          } else {
            emitDrain(client);
          }
          continue;
        }
        if (client[kPending] === 0) {
          return;
        }
        if (client[kRunning] >= (getPipelining(client) || 1)) {
          return;
        }
        const request4 = client[kQueue][client[kPendingIdx]];
        if (client[kUrl].protocol === "https:" && client[kServerName] !== request4.servername) {
          if (client[kRunning] > 0) {
            return;
          }
          client[kServerName] = request4.servername;
          client[kHTTPContext]?.destroy(new InformationalError("servername changed"), () => {
            client[kHTTPContext] = null;
            resume(client);
          });
        }
        if (client[kConnecting]) {
          return;
        }
        if (!client[kHTTPContext]) {
          connect(client);
          return;
        }
        if (client[kHTTPContext].destroyed) {
          return;
        }
        if (client[kHTTPContext].busy(request4)) {
          return;
        }
        if (!request4.aborted && client[kHTTPContext].write(request4)) {
          client[kPendingIdx]++;
        } else {
          client[kQueue].splice(client[kPendingIdx], 1);
        }
      }
    }
    __name(_resume, "_resume");
    module2.exports = Client2;
  }
});

// node_modules/undici/lib/dispatcher/fixed-queue.js
var require_fixed_queue = __commonJS({
  "node_modules/undici/lib/dispatcher/fixed-queue.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var kSize = 2048;
    var kMask = kSize - 1;
    var FixedCircularBuffer = class {
      static {
        __name(this, "FixedCircularBuffer");
      }
      constructor() {
        this.bottom = 0;
        this.top = 0;
        this.list = new Array(kSize).fill(void 0);
        this.next = null;
      }
      /**
       * @returns {boolean}
       */
      isEmpty() {
        return this.top === this.bottom;
      }
      /**
       * @returns {boolean}
       */
      isFull() {
        return (this.top + 1 & kMask) === this.bottom;
      }
      /**
       * @param {T} data
       * @returns {void}
       */
      push(data) {
        this.list[this.top] = data;
        this.top = this.top + 1 & kMask;
      }
      /**
       * @returns {T|null}
       */
      shift() {
        const nextItem = this.list[this.bottom];
        if (nextItem === void 0) {
          return null;
        }
        this.list[this.bottom] = void 0;
        this.bottom = this.bottom + 1 & kMask;
        return nextItem;
      }
    };
    module2.exports = class FixedQueue {
      static {
        __name(this, "FixedQueue");
      }
      constructor() {
        this.head = this.tail = new FixedCircularBuffer();
      }
      /**
       * @returns {boolean}
       */
      isEmpty() {
        return this.head.isEmpty();
      }
      /**
       * @param {T} data
       */
      push(data) {
        if (this.head.isFull()) {
          this.head = this.head.next = new FixedCircularBuffer();
        }
        this.head.push(data);
      }
      /**
       * @returns {T|null}
       */
      shift() {
        const tail = this.tail;
        const next = tail.shift();
        if (tail.isEmpty() && tail.next !== null) {
          this.tail = tail.next;
          tail.next = null;
        }
        return next;
      }
    };
  }
});

// node_modules/undici/lib/dispatcher/pool-base.js
var require_pool_base = __commonJS({
  "node_modules/undici/lib/dispatcher/pool-base.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { PoolStats } = require_stats();
    var DispatcherBase = require_dispatcher_base();
    var FixedQueue = require_fixed_queue();
    var { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require_symbols();
    var kClients = Symbol("clients");
    var kNeedDrain = Symbol("needDrain");
    var kQueue = Symbol("queue");
    var kClosedResolve = Symbol("closed resolve");
    var kOnDrain = Symbol("onDrain");
    var kOnConnect = Symbol("onConnect");
    var kOnDisconnect = Symbol("onDisconnect");
    var kOnConnectionError = Symbol("onConnectionError");
    var kGetDispatcher = Symbol("get dispatcher");
    var kAddClient = Symbol("add client");
    var kRemoveClient = Symbol("remove client");
    var PoolBase = class extends DispatcherBase {
      static {
        __name(this, "PoolBase");
      }
      constructor() {
        super();
        this[kQueue] = new FixedQueue();
        this[kClients] = [];
        this[kQueued] = 0;
        const pool = this;
        this[kOnDrain] = /* @__PURE__ */ __name(function onDrain(origin, targets) {
          const queue = pool[kQueue];
          let needDrain = false;
          while (!needDrain) {
            const item = queue.shift();
            if (!item) {
              break;
            }
            pool[kQueued]--;
            needDrain = !this.dispatch(item.opts, item.handler);
          }
          this[kNeedDrain] = needDrain;
          if (!this[kNeedDrain] && pool[kNeedDrain]) {
            pool[kNeedDrain] = false;
            pool.emit("drain", origin, [pool, ...targets]);
          }
          if (pool[kClosedResolve] && queue.isEmpty()) {
            Promise.all(pool[kClients].map((c3) => c3.close())).then(pool[kClosedResolve]);
          }
        }, "onDrain");
        this[kOnConnect] = (origin, targets) => {
          pool.emit("connect", origin, [pool, ...targets]);
        };
        this[kOnDisconnect] = (origin, targets, err) => {
          pool.emit("disconnect", origin, [pool, ...targets], err);
        };
        this[kOnConnectionError] = (origin, targets, err) => {
          pool.emit("connectionError", origin, [pool, ...targets], err);
        };
      }
      get [kBusy]() {
        return this[kNeedDrain];
      }
      get [kConnected]() {
        return this[kClients].filter((client) => client[kConnected]).length;
      }
      get [kFree]() {
        return this[kClients].filter((client) => client[kConnected] && !client[kNeedDrain]).length;
      }
      get [kPending]() {
        let ret = this[kQueued];
        for (const { [kPending]: pending } of this[kClients]) {
          ret += pending;
        }
        return ret;
      }
      get [kRunning]() {
        let ret = 0;
        for (const { [kRunning]: running } of this[kClients]) {
          ret += running;
        }
        return ret;
      }
      get [kSize]() {
        let ret = this[kQueued];
        for (const { [kSize]: size } of this[kClients]) {
          ret += size;
        }
        return ret;
      }
      get stats() {
        return new PoolStats(this);
      }
      async [kClose]() {
        if (this[kQueue].isEmpty()) {
          await Promise.all(this[kClients].map((c3) => c3.close()));
        } else {
          await new Promise((resolve24) => {
            this[kClosedResolve] = resolve24;
          });
        }
      }
      async [kDestroy](err) {
        while (true) {
          const item = this[kQueue].shift();
          if (!item) {
            break;
          }
          item.handler.onError(err);
        }
        await Promise.all(this[kClients].map((c3) => c3.destroy(err)));
      }
      [kDispatch](opts, handler) {
        const dispatcher = this[kGetDispatcher]();
        if (!dispatcher) {
          this[kNeedDrain] = true;
          this[kQueue].push({ opts, handler });
          this[kQueued]++;
        } else if (!dispatcher.dispatch(opts, handler)) {
          dispatcher[kNeedDrain] = true;
          this[kNeedDrain] = !this[kGetDispatcher]();
        }
        return !this[kNeedDrain];
      }
      [kAddClient](client) {
        client.on("drain", this[kOnDrain]).on("connect", this[kOnConnect]).on("disconnect", this[kOnDisconnect]).on("connectionError", this[kOnConnectionError]);
        this[kClients].push(client);
        if (this[kNeedDrain]) {
          queueMicrotask(() => {
            if (this[kNeedDrain]) {
              this[kOnDrain](client[kUrl], [this, client]);
            }
          });
        }
        return this;
      }
      [kRemoveClient](client) {
        client.close(() => {
          const idx = this[kClients].indexOf(client);
          if (idx !== -1) {
            this[kClients].splice(idx, 1);
          }
        });
        this[kNeedDrain] = this[kClients].some((dispatcher) => !dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true);
      }
    };
    module2.exports = {
      PoolBase,
      kClients,
      kNeedDrain,
      kAddClient,
      kRemoveClient,
      kGetDispatcher
    };
  }
});

// node_modules/undici/lib/dispatcher/pool.js
var require_pool = __commonJS({
  "node_modules/undici/lib/dispatcher/pool.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      PoolBase,
      kClients,
      kNeedDrain,
      kAddClient,
      kGetDispatcher,
      kRemoveClient
    } = require_pool_base();
    var Client2 = require_client();
    var {
      InvalidArgumentError
    } = require_errors();
    var util4 = require_util();
    var { kUrl } = require_symbols();
    var buildConnector = require_connect();
    var kOptions = Symbol("options");
    var kConnections = Symbol("connections");
    var kFactory = Symbol("factory");
    function defaultFactory(origin, opts) {
      return new Client2(origin, opts);
    }
    __name(defaultFactory, "defaultFactory");
    var Pool = class extends PoolBase {
      static {
        __name(this, "Pool");
      }
      constructor(origin, {
        connections,
        factory = defaultFactory,
        connect,
        connectTimeout,
        tls,
        maxCachedSessions,
        socketPath,
        autoSelectFamily,
        autoSelectFamilyAttemptTimeout,
        allowH2,
        clientTtl,
        ...options2
      } = {}) {
        if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
          throw new InvalidArgumentError("invalid connections");
        }
        if (typeof factory !== "function") {
          throw new InvalidArgumentError("factory must be a function.");
        }
        if (connect != null && typeof connect !== "function" && typeof connect !== "object") {
          throw new InvalidArgumentError("connect must be a function or an object");
        }
        super();
        if (typeof connect !== "function") {
          connect = buildConnector({
            ...tls,
            maxCachedSessions,
            allowH2,
            socketPath,
            timeout: connectTimeout,
            ...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
            ...connect
          });
        }
        this[kConnections] = connections || null;
        this[kUrl] = util4.parseOrigin(origin);
        this[kOptions] = { ...util4.deepClone(options2), connect, allowH2, clientTtl };
        this[kOptions].interceptors = options2.interceptors ? { ...options2.interceptors } : void 0;
        this[kFactory] = factory;
        this.on("connect", (origin2, targets) => {
          if (clientTtl != null && clientTtl > 0) {
            for (const target of targets) {
              Object.assign(target, { ttl: Date.now() });
            }
          }
        });
        this.on("connectionError", (origin2, targets, error) => {
          for (const target of targets) {
            const idx = this[kClients].indexOf(target);
            if (idx !== -1) {
              this[kClients].splice(idx, 1);
            }
          }
        });
      }
      [kGetDispatcher]() {
        const clientTtlOption = this[kOptions].clientTtl;
        for (const client of this[kClients]) {
          if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && Date.now() - client.ttl > clientTtlOption) {
            this[kRemoveClient](client);
          } else if (!client[kNeedDrain]) {
            return client;
          }
        }
        if (!this[kConnections] || this[kClients].length < this[kConnections]) {
          const dispatcher = this[kFactory](this[kUrl], this[kOptions]);
          this[kAddClient](dispatcher);
          return dispatcher;
        }
      }
    };
    module2.exports = Pool;
  }
});

// node_modules/undici/lib/dispatcher/balanced-pool.js
var require_balanced_pool = __commonJS({
  "node_modules/undici/lib/dispatcher/balanced-pool.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      BalancedPoolMissingUpstreamError,
      InvalidArgumentError
    } = require_errors();
    var {
      PoolBase,
      kClients,
      kNeedDrain,
      kAddClient,
      kRemoveClient,
      kGetDispatcher
    } = require_pool_base();
    var Pool = require_pool();
    var { kUrl } = require_symbols();
    var { parseOrigin } = require_util();
    var kFactory = Symbol("factory");
    var kOptions = Symbol("options");
    var kGreatestCommonDivisor = Symbol("kGreatestCommonDivisor");
    var kCurrentWeight = Symbol("kCurrentWeight");
    var kIndex = Symbol("kIndex");
    var kWeight = Symbol("kWeight");
    var kMaxWeightPerServer = Symbol("kMaxWeightPerServer");
    var kErrorPenalty = Symbol("kErrorPenalty");
    function getGreatestCommonDivisor(a, b) {
      if (a === 0) return b;
      while (b !== 0) {
        const t2 = b;
        b = a % b;
        a = t2;
      }
      return a;
    }
    __name(getGreatestCommonDivisor, "getGreatestCommonDivisor");
    function defaultFactory(origin, opts) {
      return new Pool(origin, opts);
    }
    __name(defaultFactory, "defaultFactory");
    var BalancedPool = class extends PoolBase {
      static {
        __name(this, "BalancedPool");
      }
      constructor(upstreams = [], { factory = defaultFactory, ...opts } = {}) {
        if (typeof factory !== "function") {
          throw new InvalidArgumentError("factory must be a function.");
        }
        super();
        this[kOptions] = opts;
        this[kIndex] = -1;
        this[kCurrentWeight] = 0;
        this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100;
        this[kErrorPenalty] = this[kOptions].errorPenalty || 15;
        if (!Array.isArray(upstreams)) {
          upstreams = [upstreams];
        }
        this[kFactory] = factory;
        for (const upstream of upstreams) {
          this.addUpstream(upstream);
        }
        this._updateBalancedPoolStats();
      }
      addUpstream(upstream) {
        const upstreamOrigin = parseOrigin(upstream).origin;
        if (this[kClients].find((pool2) => pool2[kUrl].origin === upstreamOrigin && pool2.closed !== true && pool2.destroyed !== true)) {
          return this;
        }
        const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]));
        this[kAddClient](pool);
        pool.on("connect", () => {
          pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]);
        });
        pool.on("connectionError", () => {
          pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]);
          this._updateBalancedPoolStats();
        });
        pool.on("disconnect", (...args) => {
          const err = args[2];
          if (err && err.code === "UND_ERR_SOCKET") {
            pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]);
            this._updateBalancedPoolStats();
          }
        });
        for (const client of this[kClients]) {
          client[kWeight] = this[kMaxWeightPerServer];
        }
        this._updateBalancedPoolStats();
        return this;
      }
      _updateBalancedPoolStats() {
        let result = 0;
        for (let i = 0; i < this[kClients].length; i++) {
          result = getGreatestCommonDivisor(this[kClients][i][kWeight], result);
        }
        this[kGreatestCommonDivisor] = result;
      }
      removeUpstream(upstream) {
        const upstreamOrigin = parseOrigin(upstream).origin;
        const pool = this[kClients].find((pool2) => pool2[kUrl].origin === upstreamOrigin && pool2.closed !== true && pool2.destroyed !== true);
        if (pool) {
          this[kRemoveClient](pool);
        }
        return this;
      }
      get upstreams() {
        return this[kClients].filter((dispatcher) => dispatcher.closed !== true && dispatcher.destroyed !== true).map((p) => p[kUrl].origin);
      }
      [kGetDispatcher]() {
        if (this[kClients].length === 0) {
          throw new BalancedPoolMissingUpstreamError();
        }
        const dispatcher = this[kClients].find((dispatcher2) => !dispatcher2[kNeedDrain] && dispatcher2.closed !== true && dispatcher2.destroyed !== true);
        if (!dispatcher) {
          return;
        }
        const allClientsBusy = this[kClients].map((pool) => pool[kNeedDrain]).reduce((a, b) => a && b, true);
        if (allClientsBusy) {
          return;
        }
        let counter = 0;
        let maxWeightIndex = this[kClients].findIndex((pool) => !pool[kNeedDrain]);
        while (counter++ < this[kClients].length) {
          this[kIndex] = (this[kIndex] + 1) % this[kClients].length;
          const pool = this[kClients][this[kIndex]];
          if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {
            maxWeightIndex = this[kIndex];
          }
          if (this[kIndex] === 0) {
            this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor];
            if (this[kCurrentWeight] <= 0) {
              this[kCurrentWeight] = this[kMaxWeightPerServer];
            }
          }
          if (pool[kWeight] >= this[kCurrentWeight] && !pool[kNeedDrain]) {
            return pool;
          }
        }
        this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight];
        this[kIndex] = maxWeightIndex;
        return this[kClients][maxWeightIndex];
      }
    };
    module2.exports = BalancedPool;
  }
});

// node_modules/undici/lib/dispatcher/agent.js
var require_agent = __commonJS({
  "node_modules/undici/lib/dispatcher/agent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { InvalidArgumentError } = require_errors();
    var { kClients, kRunning, kClose, kDestroy, kDispatch, kUrl } = require_symbols();
    var DispatcherBase = require_dispatcher_base();
    var Pool = require_pool();
    var Client2 = require_client();
    var util4 = require_util();
    var kOnConnect = Symbol("onConnect");
    var kOnDisconnect = Symbol("onDisconnect");
    var kOnConnectionError = Symbol("onConnectionError");
    var kOnDrain = Symbol("onDrain");
    var kFactory = Symbol("factory");
    var kOptions = Symbol("options");
    function defaultFactory(origin, opts) {
      return opts && opts.connections === 1 ? new Client2(origin, opts) : new Pool(origin, opts);
    }
    __name(defaultFactory, "defaultFactory");
    var Agent3 = class extends DispatcherBase {
      static {
        __name(this, "Agent");
      }
      constructor({ factory = defaultFactory, connect, ...options2 } = {}) {
        if (typeof factory !== "function") {
          throw new InvalidArgumentError("factory must be a function.");
        }
        if (connect != null && typeof connect !== "function" && typeof connect !== "object") {
          throw new InvalidArgumentError("connect must be a function or an object");
        }
        super();
        if (connect && typeof connect !== "function") {
          connect = { ...connect };
        }
        this[kOptions] = { ...util4.deepClone(options2), connect };
        this[kFactory] = factory;
        this[kClients] = /* @__PURE__ */ new Map();
        this[kOnDrain] = (origin, targets) => {
          this.emit("drain", origin, [this, ...targets]);
        };
        this[kOnConnect] = (origin, targets) => {
          this.emit("connect", origin, [this, ...targets]);
        };
        this[kOnDisconnect] = (origin, targets, err) => {
          this.emit("disconnect", origin, [this, ...targets], err);
        };
        this[kOnConnectionError] = (origin, targets, err) => {
          this.emit("connectionError", origin, [this, ...targets], err);
        };
      }
      get [kRunning]() {
        let ret = 0;
        for (const { dispatcher } of this[kClients].values()) {
          ret += dispatcher[kRunning];
        }
        return ret;
      }
      [kDispatch](opts, handler) {
        let key;
        if (opts.origin && (typeof opts.origin === "string" || opts.origin instanceof URL)) {
          key = String(opts.origin);
        } else {
          throw new InvalidArgumentError("opts.origin must be a non-empty string or URL.");
        }
        const result = this[kClients].get(key);
        let dispatcher = result && result.dispatcher;
        if (!dispatcher) {
          const closeClientIfUnused = /* @__PURE__ */ __name((connected) => {
            const result2 = this[kClients].get(key);
            if (result2) {
              if (connected) result2.count -= 1;
              if (result2.count <= 0) {
                this[kClients].delete(key);
                result2.dispatcher.close();
              }
            }
          }, "closeClientIfUnused");
          dispatcher = this[kFactory](opts.origin, this[kOptions]).on("drain", this[kOnDrain]).on("connect", (origin, targets) => {
            const result2 = this[kClients].get(key);
            if (result2) {
              result2.count += 1;
            }
            this[kOnConnect](origin, targets);
          }).on("disconnect", (origin, targets, err) => {
            closeClientIfUnused(true);
            this[kOnDisconnect](origin, targets, err);
          }).on("connectionError", (origin, targets, err) => {
            closeClientIfUnused(false);
            this[kOnConnectionError](origin, targets, err);
          });
          this[kClients].set(key, { count: 0, dispatcher });
        }
        return dispatcher.dispatch(opts, handler);
      }
      async [kClose]() {
        const closePromises = [];
        for (const { dispatcher } of this[kClients].values()) {
          closePromises.push(dispatcher.close());
        }
        this[kClients].clear();
        await Promise.all(closePromises);
      }
      async [kDestroy](err) {
        const destroyPromises = [];
        for (const { dispatcher } of this[kClients].values()) {
          destroyPromises.push(dispatcher.destroy(err));
        }
        this[kClients].clear();
        await Promise.all(destroyPromises);
      }
      get stats() {
        const allClientStats = {};
        for (const { dispatcher } of this[kClients].values()) {
          if (dispatcher.stats) {
            allClientStats[dispatcher[kUrl].origin] = dispatcher.stats;
          }
        }
        return allClientStats;
      }
    };
    module2.exports = Agent3;
  }
});

// node_modules/undici/lib/dispatcher/proxy-agent.js
var require_proxy_agent = __commonJS({
  "node_modules/undici/lib/dispatcher/proxy-agent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { kProxy, kClose, kDestroy, kDispatch } = require_symbols();
    var Agent3 = require_agent();
    var Pool = require_pool();
    var DispatcherBase = require_dispatcher_base();
    var { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require_errors();
    var buildConnector = require_connect();
    var Client2 = require_client();
    var kAgent = Symbol("proxy agent");
    var kClient = Symbol("proxy client");
    var kProxyHeaders = Symbol("proxy headers");
    var kRequestTls = Symbol("request tls settings");
    var kProxyTls = Symbol("proxy tls settings");
    var kConnectEndpoint = Symbol("connect endpoint function");
    var kTunnelProxy = Symbol("tunnel proxy");
    function defaultProtocolPort(protocol) {
      return protocol === "https:" ? 443 : 80;
    }
    __name(defaultProtocolPort, "defaultProtocolPort");
    function defaultFactory(origin, opts) {
      return new Pool(origin, opts);
    }
    __name(defaultFactory, "defaultFactory");
    var noop6 = /* @__PURE__ */ __name(() => {
    }, "noop");
    function defaultAgentFactory(origin, opts) {
      if (opts.connections === 1) {
        return new Client2(origin, opts);
      }
      return new Pool(origin, opts);
    }
    __name(defaultAgentFactory, "defaultAgentFactory");
    var Http1ProxyWrapper = class extends DispatcherBase {
      static {
        __name(this, "Http1ProxyWrapper");
      }
      #client;
      constructor(proxyUrl, { headers = {}, connect, factory }) {
        super();
        if (!proxyUrl) {
          throw new InvalidArgumentError("Proxy URL is mandatory");
        }
        this[kProxyHeaders] = headers;
        if (factory) {
          this.#client = factory(proxyUrl, { connect });
        } else {
          this.#client = new Client2(proxyUrl, { connect });
        }
      }
      [kDispatch](opts, handler) {
        const onHeaders = handler.onHeaders;
        handler.onHeaders = function(statusCode, data, resume) {
          if (statusCode === 407) {
            if (typeof handler.onError === "function") {
              handler.onError(new InvalidArgumentError("Proxy Authentication Required (407)"));
            }
            return;
          }
          if (onHeaders) onHeaders.call(this, statusCode, data, resume);
        };
        const {
          origin,
          path: path108 = "/",
          headers = {}
        } = opts;
        opts.path = origin + path108;
        if (!("host" in headers) && !("Host" in headers)) {
          const { host } = new URL(origin);
          headers.host = host;
        }
        opts.headers = { ...this[kProxyHeaders], ...headers };
        return this.#client[kDispatch](opts, handler);
      }
      async [kClose]() {
        return this.#client.close();
      }
      async [kDestroy](err) {
        return this.#client.destroy(err);
      }
    };
    var ProxyAgent5 = class extends DispatcherBase {
      static {
        __name(this, "ProxyAgent");
      }
      constructor(opts) {
        if (!opts || typeof opts === "object" && !(opts instanceof URL) && !opts.uri) {
          throw new InvalidArgumentError("Proxy uri is mandatory");
        }
        const { clientFactory = defaultFactory } = opts;
        if (typeof clientFactory !== "function") {
          throw new InvalidArgumentError("Proxy opts.clientFactory must be a function.");
        }
        const { proxyTunnel = true } = opts;
        super();
        const url2 = this.#getUrl(opts);
        const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url2;
        this[kProxy] = { uri: href, protocol };
        this[kRequestTls] = opts.requestTls;
        this[kProxyTls] = opts.proxyTls;
        this[kProxyHeaders] = opts.headers || {};
        this[kTunnelProxy] = proxyTunnel;
        if (opts.auth && opts.token) {
          throw new InvalidArgumentError("opts.auth cannot be used in combination with opts.token");
        } else if (opts.auth) {
          this[kProxyHeaders]["proxy-authorization"] = `Basic ${opts.auth}`;
        } else if (opts.token) {
          this[kProxyHeaders]["proxy-authorization"] = opts.token;
        } else if (username && password) {
          this[kProxyHeaders]["proxy-authorization"] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString("base64")}`;
        }
        const connect = buildConnector({ ...opts.proxyTls });
        this[kConnectEndpoint] = buildConnector({ ...opts.requestTls });
        const agentFactory = opts.factory || defaultAgentFactory;
        const factory = /* @__PURE__ */ __name((origin2, options2) => {
          const { protocol: protocol2 } = new URL(origin2);
          if (!this[kTunnelProxy] && protocol2 === "http:" && this[kProxy].protocol === "http:") {
            return new Http1ProxyWrapper(this[kProxy].uri, {
              headers: this[kProxyHeaders],
              connect,
              factory: agentFactory
            });
          }
          return agentFactory(origin2, options2);
        }, "factory");
        this[kClient] = clientFactory(url2, { connect });
        this[kAgent] = new Agent3({
          ...opts,
          factory,
          connect: /* @__PURE__ */ __name(async (opts2, callback) => {
            let requestedPath = opts2.host;
            if (!opts2.port) {
              requestedPath += `:${defaultProtocolPort(opts2.protocol)}`;
            }
            try {
              const { socket, statusCode } = await this[kClient].connect({
                origin,
                port,
                path: requestedPath,
                signal: opts2.signal,
                headers: {
                  ...this[kProxyHeaders],
                  host: opts2.host,
                  ...opts2.connections == null || opts2.connections > 0 ? { "proxy-connection": "keep-alive" } : {}
                },
                servername: this[kProxyTls]?.servername || proxyHostname
              });
              if (statusCode !== 200) {
                socket.on("error", noop6).destroy();
                callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`));
              }
              if (opts2.protocol !== "https:") {
                callback(null, socket);
                return;
              }
              let servername;
              if (this[kRequestTls]) {
                servername = this[kRequestTls].servername;
              } else {
                servername = opts2.servername;
              }
              this[kConnectEndpoint]({ ...opts2, servername, httpSocket: socket }, callback);
            } catch (err) {
              if (err.code === "ERR_TLS_CERT_ALTNAME_INVALID") {
                callback(new SecureProxyConnectionError(err));
              } else {
                callback(err);
              }
            }
          }, "connect")
        });
      }
      dispatch(opts, handler) {
        const headers = buildHeaders2(opts.headers);
        throwIfProxyAuthIsSent(headers);
        if (headers && !("host" in headers) && !("Host" in headers)) {
          const { host } = new URL(opts.origin);
          headers.host = host;
        }
        return this[kAgent].dispatch(
          {
            ...opts,
            headers
          },
          handler
        );
      }
      /**
       * @param {import('../../types/proxy-agent').ProxyAgent.Options | string | URL} opts
       * @returns {URL}
       */
      #getUrl(opts) {
        if (typeof opts === "string") {
          return new URL(opts);
        } else if (opts instanceof URL) {
          return opts;
        } else {
          return new URL(opts.uri);
        }
      }
      async [kClose]() {
        await this[kAgent].close();
        await this[kClient].close();
      }
      async [kDestroy]() {
        await this[kAgent].destroy();
        await this[kClient].destroy();
      }
    };
    function buildHeaders2(headers) {
      if (Array.isArray(headers)) {
        const headersPair = {};
        for (let i = 0; i < headers.length; i += 2) {
          headersPair[headers[i]] = headers[i + 1];
        }
        return headersPair;
      }
      return headers;
    }
    __name(buildHeaders2, "buildHeaders");
    function throwIfProxyAuthIsSent(headers) {
      const existProxyAuth = headers && Object.keys(headers).find((key) => key.toLowerCase() === "proxy-authorization");
      if (existProxyAuth) {
        throw new InvalidArgumentError("Proxy-Authorization should be sent in ProxyAgent constructor");
      }
    }
    __name(throwIfProxyAuthIsSent, "throwIfProxyAuthIsSent");
    module2.exports = ProxyAgent5;
  }
});

// node_modules/undici/lib/dispatcher/env-http-proxy-agent.js
var require_env_http_proxy_agent = __commonJS({
  "node_modules/undici/lib/dispatcher/env-http-proxy-agent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DispatcherBase = require_dispatcher_base();
    var { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = require_symbols();
    var ProxyAgent5 = require_proxy_agent();
    var Agent3 = require_agent();
    var DEFAULT_PORTS = {
      "http:": 80,
      "https:": 443
    };
    var EnvHttpProxyAgent2 = class extends DispatcherBase {
      static {
        __name(this, "EnvHttpProxyAgent");
      }
      #noProxyValue = null;
      #noProxyEntries = null;
      #opts = null;
      constructor(opts = {}) {
        super();
        this.#opts = opts;
        const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts;
        this[kNoProxyAgent] = new Agent3(agentOpts);
        const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY;
        if (HTTP_PROXY) {
          this[kHttpProxyAgent] = new ProxyAgent5({ ...agentOpts, uri: HTTP_PROXY });
        } else {
          this[kHttpProxyAgent] = this[kNoProxyAgent];
        }
        const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY;
        if (HTTPS_PROXY) {
          this[kHttpsProxyAgent] = new ProxyAgent5({ ...agentOpts, uri: HTTPS_PROXY });
        } else {
          this[kHttpsProxyAgent] = this[kHttpProxyAgent];
        }
        this.#parseNoProxy();
      }
      [kDispatch](opts, handler) {
        const url2 = new URL(opts.origin);
        const agent = this.#getProxyAgentForUrl(url2);
        return agent.dispatch(opts, handler);
      }
      async [kClose]() {
        await this[kNoProxyAgent].close();
        if (!this[kHttpProxyAgent][kClosed]) {
          await this[kHttpProxyAgent].close();
        }
        if (!this[kHttpsProxyAgent][kClosed]) {
          await this[kHttpsProxyAgent].close();
        }
      }
      async [kDestroy](err) {
        await this[kNoProxyAgent].destroy(err);
        if (!this[kHttpProxyAgent][kDestroyed]) {
          await this[kHttpProxyAgent].destroy(err);
        }
        if (!this[kHttpsProxyAgent][kDestroyed]) {
          await this[kHttpsProxyAgent].destroy(err);
        }
      }
      #getProxyAgentForUrl(url2) {
        let { protocol, host: hostname3, port } = url2;
        hostname3 = hostname3.replace(/:\d*$/, "").toLowerCase();
        port = Number.parseInt(port, 10) || DEFAULT_PORTS[protocol] || 0;
        if (!this.#shouldProxy(hostname3, port)) {
          return this[kNoProxyAgent];
        }
        if (protocol === "https:") {
          return this[kHttpsProxyAgent];
        }
        return this[kHttpProxyAgent];
      }
      #shouldProxy(hostname3, port) {
        if (this.#noProxyChanged) {
          this.#parseNoProxy();
        }
        if (this.#noProxyEntries.length === 0) {
          return true;
        }
        if (this.#noProxyValue === "*") {
          return false;
        }
        for (let i = 0; i < this.#noProxyEntries.length; i++) {
          const entry = this.#noProxyEntries[i];
          if (entry.port && entry.port !== port) {
            continue;
          }
          if (!/^[.*]/.test(entry.hostname)) {
            if (hostname3 === entry.hostname) {
              return false;
            }
          } else {
            if (hostname3.endsWith(entry.hostname.replace(/^\*/, ""))) {
              return false;
            }
          }
        }
        return true;
      }
      #parseNoProxy() {
        const noProxyValue = this.#opts.noProxy ?? this.#noProxyEnv;
        const noProxySplit = noProxyValue.split(/[,\s]/);
        const noProxyEntries = [];
        for (let i = 0; i < noProxySplit.length; i++) {
          const entry = noProxySplit[i];
          if (!entry) {
            continue;
          }
          const parsed = entry.match(/^(.+):(\d+)$/);
          noProxyEntries.push({
            hostname: (parsed ? parsed[1] : entry).toLowerCase(),
            port: parsed ? Number.parseInt(parsed[2], 10) : 0
          });
        }
        this.#noProxyValue = noProxyValue;
        this.#noProxyEntries = noProxyEntries;
      }
      get #noProxyChanged() {
        if (this.#opts.noProxy !== void 0) {
          return false;
        }
        return this.#noProxyValue !== this.#noProxyEnv;
      }
      get #noProxyEnv() {
        return process.env.no_proxy ?? process.env.NO_PROXY ?? "";
      }
    };
    module2.exports = EnvHttpProxyAgent2;
  }
});

// node_modules/undici/lib/handler/retry-handler.js
var require_retry_handler = __commonJS({
  "node_modules/undici/lib/handler/retry-handler.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert3 = __require("node:assert");
    var { kRetryHandlerDefaultRetry } = require_symbols();
    var { RequestRetryError } = require_errors();
    var WrapHandler = require_wrap_handler();
    var {
      isDisturbed,
      parseRangeHeader,
      wrapRequestBody
    } = require_util();
    function calculateRetryAfterHeader(retryAfter) {
      const retryTime = new Date(retryAfter).getTime();
      return isNaN(retryTime) ? 0 : retryTime - Date.now();
    }
    __name(calculateRetryAfterHeader, "calculateRetryAfterHeader");
    var RetryHandler = class _RetryHandler {
      static {
        __name(this, "RetryHandler");
      }
      constructor(opts, { dispatch, handler }) {
        const { retryOptions, ...dispatchOpts } = opts;
        const {
          // Retry scoped
          retry: retryFn,
          maxRetries,
          maxTimeout,
          minTimeout,
          timeoutFactor,
          // Response scoped
          methods,
          errorCodes,
          retryAfter,
          statusCodes,
          throwOnError
        } = retryOptions ?? {};
        this.error = null;
        this.dispatch = dispatch;
        this.handler = WrapHandler.wrap(handler);
        this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) };
        this.retryOpts = {
          throwOnError: throwOnError ?? true,
          retry: retryFn ?? _RetryHandler[kRetryHandlerDefaultRetry],
          retryAfter: retryAfter ?? true,
          maxTimeout: maxTimeout ?? 30 * 1e3,
          // 30s,
          minTimeout: minTimeout ?? 500,
          // .5s
          timeoutFactor: timeoutFactor ?? 2,
          maxRetries: maxRetries ?? 5,
          // What errors we should retry
          methods: methods ?? ["GET", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"],
          // Indicates which errors to retry
          statusCodes: statusCodes ?? [500, 502, 503, 504, 429],
          // List of errors to retry
          errorCodes: errorCodes ?? [
            "ECONNRESET",
            "ECONNREFUSED",
            "ENOTFOUND",
            "ENETDOWN",
            "ENETUNREACH",
            "EHOSTDOWN",
            "EHOSTUNREACH",
            "EPIPE",
            "UND_ERR_SOCKET"
          ]
        };
        this.retryCount = 0;
        this.retryCountCheckpoint = 0;
        this.headersSent = false;
        this.start = 0;
        this.end = null;
        this.etag = null;
      }
      onResponseStartWithRetry(controller, statusCode, headers, statusMessage, err) {
        if (this.retryOpts.throwOnError) {
          if (this.retryOpts.statusCodes.includes(statusCode) === false) {
            this.headersSent = true;
            this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
          } else {
            this.error = err;
          }
          return;
        }
        if (isDisturbed(this.opts.body)) {
          this.headersSent = true;
          this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
          return;
        }
        function shouldRetry(passedErr) {
          if (passedErr) {
            this.headersSent = true;
            this.headersSent = true;
            this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
            controller.resume();
            return;
          }
          this.error = err;
          controller.resume();
        }
        __name(shouldRetry, "shouldRetry");
        controller.pause();
        this.retryOpts.retry(
          err,
          {
            state: { counter: this.retryCount },
            opts: { retryOptions: this.retryOpts, ...this.opts }
          },
          shouldRetry.bind(this)
        );
      }
      onRequestStart(controller, context2) {
        if (!this.headersSent) {
          this.handler.onRequestStart?.(controller, context2);
        }
      }
      onRequestUpgrade(controller, statusCode, headers, socket) {
        this.handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
      }
      static [kRetryHandlerDefaultRetry](err, { state, opts }, cb) {
        const { statusCode, code: code2, headers } = err;
        const { method, retryOptions } = opts;
        const {
          maxRetries,
          minTimeout,
          maxTimeout,
          timeoutFactor,
          statusCodes,
          errorCodes,
          methods
        } = retryOptions;
        const { counter } = state;
        if (code2 && code2 !== "UND_ERR_REQ_RETRY" && !errorCodes.includes(code2)) {
          cb(err);
          return;
        }
        if (Array.isArray(methods) && !methods.includes(method)) {
          cb(err);
          return;
        }
        if (statusCode != null && Array.isArray(statusCodes) && !statusCodes.includes(statusCode)) {
          cb(err);
          return;
        }
        if (counter > maxRetries) {
          cb(err);
          return;
        }
        let retryAfterHeader = headers?.["retry-after"];
        if (retryAfterHeader) {
          retryAfterHeader = Number(retryAfterHeader);
          retryAfterHeader = Number.isNaN(retryAfterHeader) ? calculateRetryAfterHeader(headers["retry-after"]) : retryAfterHeader * 1e3;
        }
        const retryTimeout = retryAfterHeader > 0 ? Math.min(retryAfterHeader, maxTimeout) : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout);
        setTimeout(() => cb(null), retryTimeout);
      }
      onResponseStart(controller, statusCode, headers, statusMessage) {
        this.error = null;
        this.retryCount += 1;
        if (statusCode >= 300) {
          const err = new RequestRetryError("Request failed", statusCode, {
            headers,
            data: {
              count: this.retryCount
            }
          });
          this.onResponseStartWithRetry(controller, statusCode, headers, statusMessage, err);
          return;
        }
        if (this.headersSent) {
          if (statusCode !== 206 && (this.start > 0 || statusCode !== 200)) {
            throw new RequestRetryError("server does not support the range header and the payload was partially consumed", statusCode, {
              headers,
              data: { count: this.retryCount }
            });
          }
          const contentRange = parseRangeHeader(headers["content-range"]);
          if (!contentRange) {
            throw new RequestRetryError("Content-Range mismatch", statusCode, {
              headers,
              data: { count: this.retryCount }
            });
          }
          if (this.etag != null && this.etag !== headers.etag) {
            throw new RequestRetryError("ETag mismatch", statusCode, {
              headers,
              data: { count: this.retryCount }
            });
          }
          const { start, size, end = size ? size - 1 : null } = contentRange;
          assert3(this.start === start, "content-range mismatch");
          assert3(this.end == null || this.end === end, "content-range mismatch");
          return;
        }
        if (this.end == null) {
          if (statusCode === 206) {
            const range = parseRangeHeader(headers["content-range"]);
            if (range == null) {
              this.headersSent = true;
              this.handler.onResponseStart?.(
                controller,
                statusCode,
                headers,
                statusMessage
              );
              return;
            }
            const { start, size, end = size ? size - 1 : null } = range;
            assert3(
              start != null && Number.isFinite(start),
              "content-range mismatch"
            );
            assert3(end != null && Number.isFinite(end), "invalid content-length");
            this.start = start;
            this.end = end;
          }
          if (this.end == null) {
            const contentLength = headers["content-length"];
            this.end = contentLength != null ? Number(contentLength) - 1 : null;
          }
          assert3(Number.isFinite(this.start));
          assert3(
            this.end == null || Number.isFinite(this.end),
            "invalid content-length"
          );
          this.resume = true;
          this.etag = headers.etag != null ? headers.etag : null;
          if (this.etag != null && this.etag[0] === "W" && this.etag[1] === "/") {
            this.etag = null;
          }
          this.headersSent = true;
          this.handler.onResponseStart?.(
            controller,
            statusCode,
            headers,
            statusMessage
          );
        } else {
          throw new RequestRetryError("Request failed", statusCode, {
            headers,
            data: { count: this.retryCount }
          });
        }
      }
      onResponseData(controller, chunk) {
        if (this.error) {
          return;
        }
        this.start += chunk.length;
        this.handler.onResponseData?.(controller, chunk);
      }
      onResponseEnd(controller, trailers) {
        if (this.error && this.retryOpts.throwOnError) {
          throw this.error;
        }
        if (!this.error) {
          this.retryCount = 0;
          return this.handler.onResponseEnd?.(controller, trailers);
        }
        this.retry(controller);
      }
      retry(controller) {
        if (this.start !== 0) {
          const headers = { range: `bytes=${this.start}-${this.end ?? ""}` };
          if (this.etag != null) {
            headers["if-match"] = this.etag;
          }
          this.opts = {
            ...this.opts,
            headers: {
              ...this.opts.headers,
              ...headers
            }
          };
        }
        try {
          this.retryCountCheckpoint = this.retryCount;
          this.dispatch(this.opts, this);
        } catch (err) {
          this.handler.onResponseError?.(controller, err);
        }
      }
      onResponseError(controller, err) {
        if (controller?.aborted || isDisturbed(this.opts.body)) {
          this.handler.onResponseError?.(controller, err);
          return;
        }
        function shouldRetry(returnedErr) {
          if (!returnedErr) {
            this.retry(controller);
            return;
          }
          this.handler?.onResponseError?.(controller, returnedErr);
        }
        __name(shouldRetry, "shouldRetry");
        if (this.retryCount - this.retryCountCheckpoint > 0) {
          this.retryCount = this.retryCountCheckpoint + (this.retryCount - this.retryCountCheckpoint);
        } else {
          this.retryCount += 1;
        }
        this.retryOpts.retry(
          err,
          {
            state: { counter: this.retryCount },
            opts: { retryOptions: this.retryOpts, ...this.opts }
          },
          shouldRetry.bind(this)
        );
      }
    };
    module2.exports = RetryHandler;
  }
});

// node_modules/undici/lib/dispatcher/retry-agent.js
var require_retry_agent = __commonJS({
  "node_modules/undici/lib/dispatcher/retry-agent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Dispatcher = require_dispatcher();
    var RetryHandler = require_retry_handler();
    var RetryAgent = class extends Dispatcher {
      static {
        __name(this, "RetryAgent");
      }
      #agent = null;
      #options = null;
      constructor(agent, options2 = {}) {
        super(options2);
        this.#agent = agent;
        this.#options = options2;
      }
      dispatch(opts, handler) {
        const retry = new RetryHandler({
          ...opts,
          retryOptions: this.#options
        }, {
          dispatch: this.#agent.dispatch.bind(this.#agent),
          handler
        });
        return this.#agent.dispatch(opts, retry);
      }
      close() {
        return this.#agent.close();
      }
      destroy() {
        return this.#agent.destroy();
      }
    };
    module2.exports = RetryAgent;
  }
});

// node_modules/undici/lib/dispatcher/h2c-client.js
var require_h2c_client = __commonJS({
  "node_modules/undici/lib/dispatcher/h2c-client.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { connect } = __require("node:net");
    var { kClose, kDestroy } = require_symbols();
    var { InvalidArgumentError } = require_errors();
    var util4 = require_util();
    var Client2 = require_client();
    var DispatcherBase = require_dispatcher_base();
    var H2CClient = class extends DispatcherBase {
      static {
        __name(this, "H2CClient");
      }
      #client = null;
      constructor(origin, clientOpts) {
        super();
        if (typeof origin === "string") {
          origin = new URL(origin);
        }
        if (origin.protocol !== "http:") {
          throw new InvalidArgumentError(
            "h2c-client: Only h2c protocol is supported"
          );
        }
        const { connect: connect2, maxConcurrentStreams, pipelining, ...opts } = clientOpts ?? {};
        let defaultMaxConcurrentStreams = 100;
        let defaultPipelining = 100;
        if (maxConcurrentStreams != null && Number.isInteger(maxConcurrentStreams) && maxConcurrentStreams > 0) {
          defaultMaxConcurrentStreams = maxConcurrentStreams;
        }
        if (pipelining != null && Number.isInteger(pipelining) && pipelining > 0) {
          defaultPipelining = pipelining;
        }
        if (defaultPipelining > defaultMaxConcurrentStreams) {
          throw new InvalidArgumentError(
            "h2c-client: pipelining cannot be greater than maxConcurrentStreams"
          );
        }
        this.#client = new Client2(origin, {
          ...opts,
          connect: this.#buildConnector(connect2),
          maxConcurrentStreams: defaultMaxConcurrentStreams,
          pipelining: defaultPipelining,
          allowH2: true
        });
      }
      #buildConnector(connectOpts) {
        return (opts, callback) => {
          const timeout2 = connectOpts?.connectOpts ?? 1e4;
          const { hostname: hostname3, port, pathname } = opts;
          const socket = connect({
            ...opts,
            host: hostname3,
            port,
            pathname
          });
          if (opts.keepAlive == null || opts.keepAlive) {
            const keepAliveInitialDelay = opts.keepAliveInitialDelay == null ? 6e4 : opts.keepAliveInitialDelay;
            socket.setKeepAlive(true, keepAliveInitialDelay);
          }
          socket.alpnProtocol = "h2";
          const clearConnectTimeout = util4.setupConnectTimeout(
            new WeakRef(socket),
            { timeout: timeout2, hostname: hostname3, port }
          );
          socket.setNoDelay(true).once("connect", function() {
            queueMicrotask(clearConnectTimeout);
            if (callback) {
              const cb = callback;
              callback = null;
              cb(null, this);
            }
          }).on("error", function(err) {
            queueMicrotask(clearConnectTimeout);
            if (callback) {
              const cb = callback;
              callback = null;
              cb(err);
            }
          });
          return socket;
        };
      }
      dispatch(opts, handler) {
        return this.#client.dispatch(opts, handler);
      }
      async [kClose]() {
        await this.#client.close();
      }
      async [kDestroy]() {
        await this.#client.destroy();
      }
    };
    module2.exports = H2CClient;
  }
});

// node_modules/undici/lib/api/readable.js
var require_readable = __commonJS({
  "node_modules/undici/lib/api/readable.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert3 = __require("node:assert");
    var { Readable: Readable4 } = __require("node:stream");
    var { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError: AbortError2 } = require_errors();
    var util4 = require_util();
    var { ReadableStreamFrom: ReadableStreamFrom2 } = require_util();
    var kConsume = Symbol("kConsume");
    var kReading = Symbol("kReading");
    var kBody = Symbol("kBody");
    var kAbort = Symbol("kAbort");
    var kContentType = Symbol("kContentType");
    var kContentLength = Symbol("kContentLength");
    var kUsed = Symbol("kUsed");
    var kBytesRead = Symbol("kBytesRead");
    var noop6 = /* @__PURE__ */ __name(() => {
    }, "noop");
    var BodyReadable = class extends Readable4 {
      static {
        __name(this, "BodyReadable");
      }
      /**
       * @param {object} opts
       * @param {(this: Readable, size: number) => void} opts.resume
       * @param {() => (void | null)} opts.abort
       * @param {string} [opts.contentType = '']
       * @param {number} [opts.contentLength]
       * @param {number} [opts.highWaterMark = 64 * 1024]
       */
      constructor({
        resume,
        abort,
        contentType = "",
        contentLength,
        highWaterMark = 64 * 1024
        // Same as nodejs fs streams.
      }) {
        super({
          autoDestroy: true,
          read: resume,
          highWaterMark
        });
        this._readableState.dataEmitted = false;
        this[kAbort] = abort;
        this[kConsume] = null;
        this[kBytesRead] = 0;
        this[kBody] = null;
        this[kUsed] = false;
        this[kContentType] = contentType;
        this[kContentLength] = Number.isFinite(contentLength) ? contentLength : null;
        this[kReading] = false;
      }
      /**
       * @param {Error|null} err
       * @param {(error:(Error|null)) => void} callback
       * @returns {void}
       */
      _destroy(err, callback) {
        if (!err && !this._readableState.endEmitted) {
          err = new RequestAbortedError();
        }
        if (err) {
          this[kAbort]();
        }
        if (!this[kUsed]) {
          setImmediate(callback, err);
        } else {
          callback(err);
        }
      }
      /**
       * @param {string|symbol} event
       * @param {(...args: any[]) => void} listener
       * @returns {this}
       */
      on(event, listener) {
        if (event === "data" || event === "readable") {
          this[kReading] = true;
          this[kUsed] = true;
        }
        return super.on(event, listener);
      }
      /**
       * @param {string|symbol} event
       * @param {(...args: any[]) => void} listener
       * @returns {this}
       */
      addListener(event, listener) {
        return this.on(event, listener);
      }
      /**
       * @param {string|symbol} event
       * @param {(...args: any[]) => void} listener
       * @returns {this}
       */
      off(event, listener) {
        const ret = super.off(event, listener);
        if (event === "data" || event === "readable") {
          this[kReading] = this.listenerCount("data") > 0 || this.listenerCount("readable") > 0;
        }
        return ret;
      }
      /**
       * @param {string|symbol} event
       * @param {(...args: any[]) => void} listener
       * @returns {this}
       */
      removeListener(event, listener) {
        return this.off(event, listener);
      }
      /**
       * @param {Buffer|null} chunk
       * @returns {boolean}
       */
      push(chunk) {
        if (chunk) {
          this[kBytesRead] += chunk.length;
          if (this[kConsume]) {
            consumePush(this[kConsume], chunk);
            return this[kReading] ? super.push(chunk) : true;
          }
        }
        return super.push(chunk);
      }
      /**
       * Consumes and returns the body as a string.
       *
       * @see https://fetch.spec.whatwg.org/#dom-body-text
       * @returns {Promise<string>}
       */
      text() {
        return consume(this, "text");
      }
      /**
       * Consumes and returns the body as a JavaScript Object.
       *
       * @see https://fetch.spec.whatwg.org/#dom-body-json
       * @returns {Promise<unknown>}
       */
      json() {
        return consume(this, "json");
      }
      /**
       * Consumes and returns the body as a Blob
       *
       * @see https://fetch.spec.whatwg.org/#dom-body-blob
       * @returns {Promise<Blob>}
       */
      blob() {
        return consume(this, "blob");
      }
      /**
       * Consumes and returns the body as an Uint8Array.
       *
       * @see https://fetch.spec.whatwg.org/#dom-body-bytes
       * @returns {Promise<Uint8Array>}
       */
      bytes() {
        return consume(this, "bytes");
      }
      /**
       * Consumes and returns the body as an ArrayBuffer.
       *
       * @see https://fetch.spec.whatwg.org/#dom-body-arraybuffer
       * @returns {Promise<ArrayBuffer>}
       */
      arrayBuffer() {
        return consume(this, "arrayBuffer");
      }
      /**
       * Not implemented
       *
       * @see https://fetch.spec.whatwg.org/#dom-body-formdata
       * @throws {NotSupportedError}
       */
      async formData() {
        throw new NotSupportedError();
      }
      /**
       * Returns true if the body is not null and the body has been consumed.
       * Otherwise, returns false.
       *
       * @see https://fetch.spec.whatwg.org/#dom-body-bodyused
       * @readonly
       * @returns {boolean}
       */
      get bodyUsed() {
        return util4.isDisturbed(this);
      }
      /**
       * @see https://fetch.spec.whatwg.org/#dom-body-body
       * @readonly
       * @returns {ReadableStream}
       */
      get body() {
        if (!this[kBody]) {
          this[kBody] = ReadableStreamFrom2(this);
          if (this[kConsume]) {
            this[kBody].getReader();
            assert3(this[kBody].locked);
          }
        }
        return this[kBody];
      }
      /**
       * Dumps the response body by reading `limit` number of bytes.
       * @param {object} opts
       * @param {number} [opts.limit = 131072] Number of bytes to read.
       * @param {AbortSignal} [opts.signal] An AbortSignal to cancel the dump.
       * @returns {Promise<null>}
       */
      async dump(opts) {
        const signal = opts?.signal;
        if (signal != null && (typeof signal !== "object" || !("aborted" in signal))) {
          throw new InvalidArgumentError("signal must be an AbortSignal");
        }
        const limit2 = opts?.limit && Number.isFinite(opts.limit) ? opts.limit : 128 * 1024;
        signal?.throwIfAborted();
        if (this._readableState.closeEmitted) {
          return null;
        }
        return await new Promise((resolve24, reject) => {
          if (this[kContentLength] && this[kContentLength] > limit2 || this[kBytesRead] > limit2) {
            this.destroy(new AbortError2());
          }
          if (signal) {
            const onAbort = /* @__PURE__ */ __name(() => {
              this.destroy(signal.reason ?? new AbortError2());
            }, "onAbort");
            signal.addEventListener("abort", onAbort);
            this.on("close", function() {
              signal.removeEventListener("abort", onAbort);
              if (signal.aborted) {
                reject(signal.reason ?? new AbortError2());
              } else {
                resolve24(null);
              }
            });
          } else {
            this.on("close", resolve24);
          }
          this.on("error", noop6).on("data", () => {
            if (this[kBytesRead] > limit2) {
              this.destroy();
            }
          }).resume();
        });
      }
      /**
       * @param {BufferEncoding} encoding
       * @returns {this}
       */
      setEncoding(encoding) {
        if (Buffer.isEncoding(encoding)) {
          this._readableState.encoding = encoding;
        }
        return this;
      }
    };
    function isLocked(bodyReadable) {
      return bodyReadable[kBody]?.locked === true || bodyReadable[kConsume] !== null;
    }
    __name(isLocked, "isLocked");
    function isUnusable(bodyReadable) {
      return util4.isDisturbed(bodyReadable) || isLocked(bodyReadable);
    }
    __name(isUnusable, "isUnusable");
    function consume(stream2, type) {
      assert3(!stream2[kConsume]);
      return new Promise((resolve24, reject) => {
        if (isUnusable(stream2)) {
          const rState = stream2._readableState;
          if (rState.destroyed && rState.closeEmitted === false) {
            stream2.on("error", reject).on("close", () => {
              reject(new TypeError("unusable"));
            });
          } else {
            reject(rState.errored ?? new TypeError("unusable"));
          }
        } else {
          queueMicrotask(() => {
            stream2[kConsume] = {
              type,
              stream: stream2,
              resolve: resolve24,
              reject,
              length: 0,
              body: []
            };
            stream2.on("error", function(err) {
              consumeFinish(this[kConsume], err);
            }).on("close", function() {
              if (this[kConsume].body !== null) {
                consumeFinish(this[kConsume], new RequestAbortedError());
              }
            });
            consumeStart(stream2[kConsume]);
          });
        }
      });
    }
    __name(consume, "consume");
    function consumeStart(consume2) {
      if (consume2.body === null) {
        return;
      }
      const { _readableState: state } = consume2.stream;
      if (state.bufferIndex) {
        const start = state.bufferIndex;
        const end = state.buffer.length;
        for (let n2 = start; n2 < end; n2++) {
          consumePush(consume2, state.buffer[n2]);
        }
      } else {
        for (const chunk of state.buffer) {
          consumePush(consume2, chunk);
        }
      }
      if (state.endEmitted) {
        consumeEnd(this[kConsume], this._readableState.encoding);
      } else {
        consume2.stream.on("end", function() {
          consumeEnd(this[kConsume], this._readableState.encoding);
        });
      }
      consume2.stream.resume();
      while (consume2.stream.read() != null) {
      }
    }
    __name(consumeStart, "consumeStart");
    function chunksDecode(chunks, length, encoding) {
      if (chunks.length === 0 || length === 0) {
        return "";
      }
      const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length);
      const bufferLength = buffer.length;
      const start = bufferLength > 2 && buffer[0] === 239 && buffer[1] === 187 && buffer[2] === 191 ? 3 : 0;
      if (!encoding || encoding === "utf8" || encoding === "utf-8") {
        return buffer.utf8Slice(start, bufferLength);
      } else {
        return buffer.subarray(start, bufferLength).toString(encoding);
      }
    }
    __name(chunksDecode, "chunksDecode");
    function chunksConcat(chunks, length) {
      if (chunks.length === 0 || length === 0) {
        return new Uint8Array(0);
      }
      if (chunks.length === 1) {
        return new Uint8Array(chunks[0]);
      }
      const buffer = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer);
      let offset = 0;
      for (let i = 0; i < chunks.length; ++i) {
        const chunk = chunks[i];
        buffer.set(chunk, offset);
        offset += chunk.length;
      }
      return buffer;
    }
    __name(chunksConcat, "chunksConcat");
    function consumeEnd(consume2, encoding) {
      const { type, body, resolve: resolve24, stream: stream2, length } = consume2;
      try {
        if (type === "text") {
          resolve24(chunksDecode(body, length, encoding));
        } else if (type === "json") {
          resolve24(JSON.parse(chunksDecode(body, length, encoding)));
        } else if (type === "arrayBuffer") {
          resolve24(chunksConcat(body, length).buffer);
        } else if (type === "blob") {
          resolve24(new Blob(body, { type: stream2[kContentType] }));
        } else if (type === "bytes") {
          resolve24(chunksConcat(body, length));
        }
        consumeFinish(consume2);
      } catch (err) {
        stream2.destroy(err);
      }
    }
    __name(consumeEnd, "consumeEnd");
    function consumePush(consume2, chunk) {
      consume2.length += chunk.length;
      consume2.body.push(chunk);
    }
    __name(consumePush, "consumePush");
    function consumeFinish(consume2, err) {
      if (consume2.body === null) {
        return;
      }
      if (err) {
        consume2.reject(err);
      } else {
        consume2.resolve();
      }
      consume2.type = null;
      consume2.stream = null;
      consume2.resolve = null;
      consume2.reject = null;
      consume2.length = 0;
      consume2.body = null;
    }
    __name(consumeFinish, "consumeFinish");
    module2.exports = {
      Readable: BodyReadable,
      chunksDecode
    };
  }
});

// node_modules/undici/lib/api/api-request.js
var require_api_request = __commonJS({
  "node_modules/undici/lib/api/api-request.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert3 = __require("node:assert");
    var { AsyncResource } = __require("node:async_hooks");
    var { Readable: Readable4 } = require_readable();
    var { InvalidArgumentError, RequestAbortedError } = require_errors();
    var util4 = require_util();
    function noop6() {
    }
    __name(noop6, "noop");
    var RequestHandler = class extends AsyncResource {
      static {
        __name(this, "RequestHandler");
      }
      constructor(opts, callback) {
        if (!opts || typeof opts !== "object") {
          throw new InvalidArgumentError("invalid opts");
        }
        const { signal, method, opaque, body, onInfo, responseHeaders, highWaterMark } = opts;
        try {
          if (typeof callback !== "function") {
            throw new InvalidArgumentError("invalid callback");
          }
          if (highWaterMark && (typeof highWaterMark !== "number" || highWaterMark < 0)) {
            throw new InvalidArgumentError("invalid highWaterMark");
          }
          if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
            throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
          }
          if (method === "CONNECT") {
            throw new InvalidArgumentError("invalid method");
          }
          if (onInfo && typeof onInfo !== "function") {
            throw new InvalidArgumentError("invalid onInfo callback");
          }
          super("UNDICI_REQUEST");
        } catch (err) {
          if (util4.isStream(body)) {
            util4.destroy(body.on("error", noop6), err);
          }
          throw err;
        }
        this.method = method;
        this.responseHeaders = responseHeaders || null;
        this.opaque = opaque || null;
        this.callback = callback;
        this.res = null;
        this.abort = null;
        this.body = body;
        this.trailers = {};
        this.context = null;
        this.onInfo = onInfo || null;
        this.highWaterMark = highWaterMark;
        this.reason = null;
        this.removeAbortListener = null;
        if (signal?.aborted) {
          this.reason = signal.reason ?? new RequestAbortedError();
        } else if (signal) {
          this.removeAbortListener = util4.addAbortListener(signal, () => {
            this.reason = signal.reason ?? new RequestAbortedError();
            if (this.res) {
              util4.destroy(this.res.on("error", noop6), this.reason);
            } else if (this.abort) {
              this.abort(this.reason);
            }
          });
        }
      }
      onConnect(abort, context2) {
        if (this.reason) {
          abort(this.reason);
          return;
        }
        assert3(this.callback);
        this.abort = abort;
        this.context = context2;
      }
      onHeaders(statusCode, rawHeaders, resume, statusMessage) {
        const { callback, opaque, abort, context: context2, responseHeaders, highWaterMark } = this;
        const headers = responseHeaders === "raw" ? util4.parseRawHeaders(rawHeaders) : util4.parseHeaders(rawHeaders);
        if (statusCode < 200) {
          if (this.onInfo) {
            this.onInfo({ statusCode, headers });
          }
          return;
        }
        const parsedHeaders = responseHeaders === "raw" ? util4.parseHeaders(rawHeaders) : headers;
        const contentType = parsedHeaders["content-type"];
        const contentLength = parsedHeaders["content-length"];
        const res = new Readable4({
          resume,
          abort,
          contentType,
          contentLength: this.method !== "HEAD" && contentLength ? Number(contentLength) : null,
          highWaterMark
        });
        if (this.removeAbortListener) {
          res.on("close", this.removeAbortListener);
          this.removeAbortListener = null;
        }
        this.callback = null;
        this.res = res;
        if (callback !== null) {
          this.runInAsyncScope(callback, null, null, {
            statusCode,
            headers,
            trailers: this.trailers,
            opaque,
            body: res,
            context: context2
          });
        }
      }
      onData(chunk) {
        return this.res.push(chunk);
      }
      onComplete(trailers) {
        util4.parseHeaders(trailers, this.trailers);
        this.res.push(null);
      }
      onError(err) {
        const { res, callback, body, opaque } = this;
        if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err, { opaque });
          });
        }
        if (res) {
          this.res = null;
          queueMicrotask(() => {
            util4.destroy(res.on("error", noop6), err);
          });
        }
        if (body) {
          this.body = null;
          if (util4.isStream(body)) {
            body.on("error", noop6);
            util4.destroy(body, err);
          }
        }
        if (this.removeAbortListener) {
          this.removeAbortListener();
          this.removeAbortListener = null;
        }
      }
    };
    function request4(opts, callback) {
      if (callback === void 0) {
        return new Promise((resolve24, reject) => {
          request4.call(this, opts, (err, data) => {
            return err ? reject(err) : resolve24(data);
          });
        });
      }
      try {
        const handler = new RequestHandler(opts, callback);
        this.dispatch(opts, handler);
      } catch (err) {
        if (typeof callback !== "function") {
          throw err;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err, { opaque }));
      }
    }
    __name(request4, "request");
    module2.exports = request4;
    module2.exports.RequestHandler = RequestHandler;
  }
});

// node_modules/undici/lib/api/abort-signal.js
var require_abort_signal = __commonJS({
  "node_modules/undici/lib/api/abort-signal.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { addAbortListener } = require_util();
    var { RequestAbortedError } = require_errors();
    var kListener = Symbol("kListener");
    var kSignal = Symbol("kSignal");
    function abort(self2) {
      if (self2.abort) {
        self2.abort(self2[kSignal]?.reason);
      } else {
        self2.reason = self2[kSignal]?.reason ?? new RequestAbortedError();
      }
      removeSignal(self2);
    }
    __name(abort, "abort");
    function addSignal(self2, signal) {
      self2.reason = null;
      self2[kSignal] = null;
      self2[kListener] = null;
      if (!signal) {
        return;
      }
      if (signal.aborted) {
        abort(self2);
        return;
      }
      self2[kSignal] = signal;
      self2[kListener] = () => {
        abort(self2);
      };
      addAbortListener(self2[kSignal], self2[kListener]);
    }
    __name(addSignal, "addSignal");
    function removeSignal(self2) {
      if (!self2[kSignal]) {
        return;
      }
      if ("removeEventListener" in self2[kSignal]) {
        self2[kSignal].removeEventListener("abort", self2[kListener]);
      } else {
        self2[kSignal].removeListener("abort", self2[kListener]);
      }
      self2[kSignal] = null;
      self2[kListener] = null;
    }
    __name(removeSignal, "removeSignal");
    module2.exports = {
      addSignal,
      removeSignal
    };
  }
});

// node_modules/undici/lib/api/api-stream.js
var require_api_stream = __commonJS({
  "node_modules/undici/lib/api/api-stream.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert3 = __require("node:assert");
    var { finished } = __require("node:stream");
    var { AsyncResource } = __require("node:async_hooks");
    var { InvalidArgumentError, InvalidReturnValueError } = require_errors();
    var util4 = require_util();
    var { addSignal, removeSignal } = require_abort_signal();
    function noop6() {
    }
    __name(noop6, "noop");
    var StreamHandler = class extends AsyncResource {
      static {
        __name(this, "StreamHandler");
      }
      constructor(opts, factory, callback) {
        if (!opts || typeof opts !== "object") {
          throw new InvalidArgumentError("invalid opts");
        }
        const { signal, method, opaque, body, onInfo, responseHeaders } = opts;
        try {
          if (typeof callback !== "function") {
            throw new InvalidArgumentError("invalid callback");
          }
          if (typeof factory !== "function") {
            throw new InvalidArgumentError("invalid factory");
          }
          if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
            throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
          }
          if (method === "CONNECT") {
            throw new InvalidArgumentError("invalid method");
          }
          if (onInfo && typeof onInfo !== "function") {
            throw new InvalidArgumentError("invalid onInfo callback");
          }
          super("UNDICI_STREAM");
        } catch (err) {
          if (util4.isStream(body)) {
            util4.destroy(body.on("error", noop6), err);
          }
          throw err;
        }
        this.responseHeaders = responseHeaders || null;
        this.opaque = opaque || null;
        this.factory = factory;
        this.callback = callback;
        this.res = null;
        this.abort = null;
        this.context = null;
        this.trailers = null;
        this.body = body;
        this.onInfo = onInfo || null;
        if (util4.isStream(body)) {
          body.on("error", (err) => {
            this.onError(err);
          });
        }
        addSignal(this, signal);
      }
      onConnect(abort, context2) {
        if (this.reason) {
          abort(this.reason);
          return;
        }
        assert3(this.callback);
        this.abort = abort;
        this.context = context2;
      }
      onHeaders(statusCode, rawHeaders, resume, statusMessage) {
        const { factory, opaque, context: context2, responseHeaders } = this;
        const headers = responseHeaders === "raw" ? util4.parseRawHeaders(rawHeaders) : util4.parseHeaders(rawHeaders);
        if (statusCode < 200) {
          if (this.onInfo) {
            this.onInfo({ statusCode, headers });
          }
          return;
        }
        this.factory = null;
        if (factory === null) {
          return;
        }
        const res = this.runInAsyncScope(factory, null, {
          statusCode,
          headers,
          opaque,
          context: context2
        });
        if (!res || typeof res.write !== "function" || typeof res.end !== "function" || typeof res.on !== "function") {
          throw new InvalidReturnValueError("expected Writable");
        }
        finished(res, { readable: false }, (err) => {
          const { callback, res: res2, opaque: opaque2, trailers, abort } = this;
          this.res = null;
          if (err || !res2?.readable) {
            util4.destroy(res2, err);
          }
          this.callback = null;
          this.runInAsyncScope(callback, null, err || null, { opaque: opaque2, trailers });
          if (err) {
            abort();
          }
        });
        res.on("drain", resume);
        this.res = res;
        const needDrain = res.writableNeedDrain !== void 0 ? res.writableNeedDrain : res._writableState?.needDrain;
        return needDrain !== true;
      }
      onData(chunk) {
        const { res } = this;
        return res ? res.write(chunk) : true;
      }
      onComplete(trailers) {
        const { res } = this;
        removeSignal(this);
        if (!res) {
          return;
        }
        this.trailers = util4.parseHeaders(trailers);
        res.end();
      }
      onError(err) {
        const { res, callback, opaque, body } = this;
        removeSignal(this);
        this.factory = null;
        if (res) {
          this.res = null;
          util4.destroy(res, err);
        } else if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err, { opaque });
          });
        }
        if (body) {
          this.body = null;
          util4.destroy(body, err);
        }
      }
    };
    function stream2(opts, factory, callback) {
      if (callback === void 0) {
        return new Promise((resolve24, reject) => {
          stream2.call(this, opts, factory, (err, data) => {
            return err ? reject(err) : resolve24(data);
          });
        });
      }
      try {
        const handler = new StreamHandler(opts, factory, callback);
        this.dispatch(opts, handler);
      } catch (err) {
        if (typeof callback !== "function") {
          throw err;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err, { opaque }));
      }
    }
    __name(stream2, "stream");
    module2.exports = stream2;
  }
});

// node_modules/undici/lib/api/api-pipeline.js
var require_api_pipeline = __commonJS({
  "node_modules/undici/lib/api/api-pipeline.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      Readable: Readable4,
      Duplex,
      PassThrough: PassThrough4
    } = __require("node:stream");
    var assert3 = __require("node:assert");
    var { AsyncResource } = __require("node:async_hooks");
    var {
      InvalidArgumentError,
      InvalidReturnValueError,
      RequestAbortedError
    } = require_errors();
    var util4 = require_util();
    var { addSignal, removeSignal } = require_abort_signal();
    function noop6() {
    }
    __name(noop6, "noop");
    var kResume = Symbol("resume");
    var PipelineRequest = class extends Readable4 {
      static {
        __name(this, "PipelineRequest");
      }
      constructor() {
        super({ autoDestroy: true });
        this[kResume] = null;
      }
      _read() {
        const { [kResume]: resume } = this;
        if (resume) {
          this[kResume] = null;
          resume();
        }
      }
      _destroy(err, callback) {
        this._read();
        callback(err);
      }
    };
    var PipelineResponse = class extends Readable4 {
      static {
        __name(this, "PipelineResponse");
      }
      constructor(resume) {
        super({ autoDestroy: true });
        this[kResume] = resume;
      }
      _read() {
        this[kResume]();
      }
      _destroy(err, callback) {
        if (!err && !this._readableState.endEmitted) {
          err = new RequestAbortedError();
        }
        callback(err);
      }
    };
    var PipelineHandler = class extends AsyncResource {
      static {
        __name(this, "PipelineHandler");
      }
      constructor(opts, handler) {
        if (!opts || typeof opts !== "object") {
          throw new InvalidArgumentError("invalid opts");
        }
        if (typeof handler !== "function") {
          throw new InvalidArgumentError("invalid handler");
        }
        const { signal, method, opaque, onInfo, responseHeaders } = opts;
        if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
          throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
        }
        if (method === "CONNECT") {
          throw new InvalidArgumentError("invalid method");
        }
        if (onInfo && typeof onInfo !== "function") {
          throw new InvalidArgumentError("invalid onInfo callback");
        }
        super("UNDICI_PIPELINE");
        this.opaque = opaque || null;
        this.responseHeaders = responseHeaders || null;
        this.handler = handler;
        this.abort = null;
        this.context = null;
        this.onInfo = onInfo || null;
        this.req = new PipelineRequest().on("error", noop6);
        this.ret = new Duplex({
          readableObjectMode: opts.objectMode,
          autoDestroy: true,
          read: /* @__PURE__ */ __name(() => {
            const { body } = this;
            if (body?.resume) {
              body.resume();
            }
          }, "read"),
          write: /* @__PURE__ */ __name((chunk, encoding, callback) => {
            const { req } = this;
            if (req.push(chunk, encoding) || req._readableState.destroyed) {
              callback();
            } else {
              req[kResume] = callback;
            }
          }, "write"),
          destroy: /* @__PURE__ */ __name((err, callback) => {
            const { body, req, res, ret, abort } = this;
            if (!err && !ret._readableState.endEmitted) {
              err = new RequestAbortedError();
            }
            if (abort && err) {
              abort();
            }
            util4.destroy(body, err);
            util4.destroy(req, err);
            util4.destroy(res, err);
            removeSignal(this);
            callback(err);
          }, "destroy")
        }).on("prefinish", () => {
          const { req } = this;
          req.push(null);
        });
        this.res = null;
        addSignal(this, signal);
      }
      onConnect(abort, context2) {
        const { res } = this;
        if (this.reason) {
          abort(this.reason);
          return;
        }
        assert3(!res, "pipeline cannot be retried");
        this.abort = abort;
        this.context = context2;
      }
      onHeaders(statusCode, rawHeaders, resume) {
        const { opaque, handler, context: context2 } = this;
        if (statusCode < 200) {
          if (this.onInfo) {
            const headers = this.responseHeaders === "raw" ? util4.parseRawHeaders(rawHeaders) : util4.parseHeaders(rawHeaders);
            this.onInfo({ statusCode, headers });
          }
          return;
        }
        this.res = new PipelineResponse(resume);
        let body;
        try {
          this.handler = null;
          const headers = this.responseHeaders === "raw" ? util4.parseRawHeaders(rawHeaders) : util4.parseHeaders(rawHeaders);
          body = this.runInAsyncScope(handler, null, {
            statusCode,
            headers,
            opaque,
            body: this.res,
            context: context2
          });
        } catch (err) {
          this.res.on("error", noop6);
          throw err;
        }
        if (!body || typeof body.on !== "function") {
          throw new InvalidReturnValueError("expected Readable");
        }
        body.on("data", (chunk) => {
          const { ret, body: body2 } = this;
          if (!ret.push(chunk) && body2.pause) {
            body2.pause();
          }
        }).on("error", (err) => {
          const { ret } = this;
          util4.destroy(ret, err);
        }).on("end", () => {
          const { ret } = this;
          ret.push(null);
        }).on("close", () => {
          const { ret } = this;
          if (!ret._readableState.ended) {
            util4.destroy(ret, new RequestAbortedError());
          }
        });
        this.body = body;
      }
      onData(chunk) {
        const { res } = this;
        return res.push(chunk);
      }
      onComplete(trailers) {
        const { res } = this;
        res.push(null);
      }
      onError(err) {
        const { ret } = this;
        this.handler = null;
        util4.destroy(ret, err);
      }
    };
    function pipeline(opts, handler) {
      try {
        const pipelineHandler = new PipelineHandler(opts, handler);
        this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler);
        return pipelineHandler.ret;
      } catch (err) {
        return new PassThrough4().destroy(err);
      }
    }
    __name(pipeline, "pipeline");
    module2.exports = pipeline;
  }
});

// node_modules/undici/lib/api/api-upgrade.js
var require_api_upgrade = __commonJS({
  "node_modules/undici/lib/api/api-upgrade.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { InvalidArgumentError, SocketError } = require_errors();
    var { AsyncResource } = __require("node:async_hooks");
    var assert3 = __require("node:assert");
    var util4 = require_util();
    var { addSignal, removeSignal } = require_abort_signal();
    var UpgradeHandler = class extends AsyncResource {
      static {
        __name(this, "UpgradeHandler");
      }
      constructor(opts, callback) {
        if (!opts || typeof opts !== "object") {
          throw new InvalidArgumentError("invalid opts");
        }
        if (typeof callback !== "function") {
          throw new InvalidArgumentError("invalid callback");
        }
        const { signal, opaque, responseHeaders } = opts;
        if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
          throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
        }
        super("UNDICI_UPGRADE");
        this.responseHeaders = responseHeaders || null;
        this.opaque = opaque || null;
        this.callback = callback;
        this.abort = null;
        this.context = null;
        addSignal(this, signal);
      }
      onConnect(abort, context2) {
        if (this.reason) {
          abort(this.reason);
          return;
        }
        assert3(this.callback);
        this.abort = abort;
        this.context = null;
      }
      onHeaders() {
        throw new SocketError("bad upgrade", null);
      }
      onUpgrade(statusCode, rawHeaders, socket) {
        assert3(statusCode === 101);
        const { callback, opaque, context: context2 } = this;
        removeSignal(this);
        this.callback = null;
        const headers = this.responseHeaders === "raw" ? util4.parseRawHeaders(rawHeaders) : util4.parseHeaders(rawHeaders);
        this.runInAsyncScope(callback, null, null, {
          headers,
          socket,
          opaque,
          context: context2
        });
      }
      onError(err) {
        const { callback, opaque } = this;
        removeSignal(this);
        if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err, { opaque });
          });
        }
      }
    };
    function upgrade(opts, callback) {
      if (callback === void 0) {
        return new Promise((resolve24, reject) => {
          upgrade.call(this, opts, (err, data) => {
            return err ? reject(err) : resolve24(data);
          });
        });
      }
      try {
        const upgradeHandler = new UpgradeHandler(opts, callback);
        const upgradeOpts = {
          ...opts,
          method: opts.method || "GET",
          upgrade: opts.protocol || "Websocket"
        };
        this.dispatch(upgradeOpts, upgradeHandler);
      } catch (err) {
        if (typeof callback !== "function") {
          throw err;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err, { opaque }));
      }
    }
    __name(upgrade, "upgrade");
    module2.exports = upgrade;
  }
});

// node_modules/undici/lib/api/api-connect.js
var require_api_connect = __commonJS({
  "node_modules/undici/lib/api/api-connect.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert3 = __require("node:assert");
    var { AsyncResource } = __require("node:async_hooks");
    var { InvalidArgumentError, SocketError } = require_errors();
    var util4 = require_util();
    var { addSignal, removeSignal } = require_abort_signal();
    var ConnectHandler = class extends AsyncResource {
      static {
        __name(this, "ConnectHandler");
      }
      constructor(opts, callback) {
        if (!opts || typeof opts !== "object") {
          throw new InvalidArgumentError("invalid opts");
        }
        if (typeof callback !== "function") {
          throw new InvalidArgumentError("invalid callback");
        }
        const { signal, opaque, responseHeaders } = opts;
        if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
          throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
        }
        super("UNDICI_CONNECT");
        this.opaque = opaque || null;
        this.responseHeaders = responseHeaders || null;
        this.callback = callback;
        this.abort = null;
        addSignal(this, signal);
      }
      onConnect(abort, context2) {
        if (this.reason) {
          abort(this.reason);
          return;
        }
        assert3(this.callback);
        this.abort = abort;
        this.context = context2;
      }
      onHeaders() {
        throw new SocketError("bad connect", null);
      }
      onUpgrade(statusCode, rawHeaders, socket) {
        const { callback, opaque, context: context2 } = this;
        removeSignal(this);
        this.callback = null;
        let headers = rawHeaders;
        if (headers != null) {
          headers = this.responseHeaders === "raw" ? util4.parseRawHeaders(rawHeaders) : util4.parseHeaders(rawHeaders);
        }
        this.runInAsyncScope(callback, null, null, {
          statusCode,
          headers,
          socket,
          opaque,
          context: context2
        });
      }
      onError(err) {
        const { callback, opaque } = this;
        removeSignal(this);
        if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err, { opaque });
          });
        }
      }
    };
    function connect(opts, callback) {
      if (callback === void 0) {
        return new Promise((resolve24, reject) => {
          connect.call(this, opts, (err, data) => {
            return err ? reject(err) : resolve24(data);
          });
        });
      }
      try {
        const connectHandler = new ConnectHandler(opts, callback);
        const connectOptions = { ...opts, method: "CONNECT" };
        this.dispatch(connectOptions, connectHandler);
      } catch (err) {
        if (typeof callback !== "function") {
          throw err;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err, { opaque }));
      }
    }
    __name(connect, "connect");
    module2.exports = connect;
  }
});

// node_modules/undici/lib/api/index.js
var require_api = __commonJS({
  "node_modules/undici/lib/api/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports.request = require_api_request();
    module2.exports.stream = require_api_stream();
    module2.exports.pipeline = require_api_pipeline();
    module2.exports.upgrade = require_api_upgrade();
    module2.exports.connect = require_api_connect();
  }
});

// node_modules/undici/lib/mock/mock-errors.js
var require_mock_errors = __commonJS({
  "node_modules/undici/lib/mock/mock-errors.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { UndiciError } = require_errors();
    var MockNotMatchedError = class extends UndiciError {
      static {
        __name(this, "MockNotMatchedError");
      }
      constructor(message) {
        super(message);
        this.name = "MockNotMatchedError";
        this.message = message || "The request does not match any registered mock dispatches";
        this.code = "UND_MOCK_ERR_MOCK_NOT_MATCHED";
      }
    };
    module2.exports = {
      MockNotMatchedError
    };
  }
});

// node_modules/undici/lib/mock/mock-symbols.js
var require_mock_symbols = __commonJS({
  "node_modules/undici/lib/mock/mock-symbols.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      kAgent: Symbol("agent"),
      kOptions: Symbol("options"),
      kFactory: Symbol("factory"),
      kDispatches: Symbol("dispatches"),
      kDispatchKey: Symbol("dispatch key"),
      kDefaultHeaders: Symbol("default headers"),
      kDefaultTrailers: Symbol("default trailers"),
      kContentLength: Symbol("content length"),
      kMockAgent: Symbol("mock agent"),
      kMockAgentSet: Symbol("mock agent set"),
      kMockAgentGet: Symbol("mock agent get"),
      kMockDispatch: Symbol("mock dispatch"),
      kClose: Symbol("close"),
      kOriginalClose: Symbol("original agent close"),
      kOriginalDispatch: Symbol("original dispatch"),
      kOrigin: Symbol("origin"),
      kIsMockActive: Symbol("is mock active"),
      kNetConnect: Symbol("net connect"),
      kGetNetConnect: Symbol("get net connect"),
      kConnected: Symbol("connected"),
      kIgnoreTrailingSlash: Symbol("ignore trailing slash"),
      kMockAgentMockCallHistoryInstance: Symbol("mock agent mock call history name"),
      kMockAgentRegisterCallHistory: Symbol("mock agent register mock call history"),
      kMockAgentAddCallHistoryLog: Symbol("mock agent add call history log"),
      kMockAgentIsCallHistoryEnabled: Symbol("mock agent is call history enabled"),
      kMockAgentAcceptsNonStandardSearchParameters: Symbol("mock agent accepts non standard search parameters"),
      kMockCallHistoryAddLog: Symbol("mock call history add log")
    };
  }
});

// node_modules/undici/lib/mock/mock-utils.js
var require_mock_utils = __commonJS({
  "node_modules/undici/lib/mock/mock-utils.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { MockNotMatchedError } = require_mock_errors();
    var {
      kDispatches,
      kMockAgent,
      kOriginalDispatch,
      kOrigin,
      kGetNetConnect
    } = require_mock_symbols();
    var { serializePathWithQuery } = require_util();
    var { STATUS_CODES } = __require("node:http");
    var {
      types: {
        isPromise: isPromise2
      }
    } = __require("node:util");
    var { InvalidArgumentError } = require_errors();
    function matchValue(match2, value) {
      if (typeof match2 === "string") {
        return match2 === value;
      }
      if (match2 instanceof RegExp) {
        return match2.test(value);
      }
      if (typeof match2 === "function") {
        return match2(value) === true;
      }
      return false;
    }
    __name(matchValue, "matchValue");
    function lowerCaseEntries(headers) {
      return Object.fromEntries(
        Object.entries(headers).map(([headerName, headerValue]) => {
          return [headerName.toLocaleLowerCase(), headerValue];
        })
      );
    }
    __name(lowerCaseEntries, "lowerCaseEntries");
    function getHeaderByName(headers, key) {
      if (Array.isArray(headers)) {
        for (let i = 0; i < headers.length; i += 2) {
          if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) {
            return headers[i + 1];
          }
        }
        return void 0;
      } else if (typeof headers.get === "function") {
        return headers.get(key);
      } else {
        return lowerCaseEntries(headers)[key.toLocaleLowerCase()];
      }
    }
    __name(getHeaderByName, "getHeaderByName");
    function buildHeadersFromArray(headers) {
      const clone = headers.slice();
      const entries = [];
      for (let index = 0; index < clone.length; index += 2) {
        entries.push([clone[index], clone[index + 1]]);
      }
      return Object.fromEntries(entries);
    }
    __name(buildHeadersFromArray, "buildHeadersFromArray");
    function matchHeaders(mockDispatch2, headers) {
      if (typeof mockDispatch2.headers === "function") {
        if (Array.isArray(headers)) {
          headers = buildHeadersFromArray(headers);
        }
        return mockDispatch2.headers(headers ? lowerCaseEntries(headers) : {});
      }
      if (typeof mockDispatch2.headers === "undefined") {
        return true;
      }
      if (typeof headers !== "object" || typeof mockDispatch2.headers !== "object") {
        return false;
      }
      for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch2.headers)) {
        const headerValue = getHeaderByName(headers, matchHeaderName);
        if (!matchValue(matchHeaderValue, headerValue)) {
          return false;
        }
      }
      return true;
    }
    __name(matchHeaders, "matchHeaders");
    function normalizeSearchParams(query) {
      if (typeof query !== "string") {
        return query;
      }
      const originalQp = new URLSearchParams(query);
      const normalizedQp = new URLSearchParams();
      for (let [key, value] of originalQp.entries()) {
        key = key.replace("[]", "");
        const valueRepresentsString = /^(['"]).*\1$/.test(value);
        if (valueRepresentsString) {
          normalizedQp.append(key, value);
          continue;
        }
        if (value.includes(",")) {
          const values = value.split(",");
          for (const v of values) {
            normalizedQp.append(key, v);
          }
          continue;
        }
        normalizedQp.append(key, value);
      }
      return normalizedQp;
    }
    __name(normalizeSearchParams, "normalizeSearchParams");
    function safeUrl(path108) {
      if (typeof path108 !== "string") {
        return path108;
      }
      const pathSegments = path108.split("?", 3);
      if (pathSegments.length !== 2) {
        return path108;
      }
      const qp = new URLSearchParams(pathSegments.pop());
      qp.sort();
      return [...pathSegments, qp.toString()].join("?");
    }
    __name(safeUrl, "safeUrl");
    function matchKey(mockDispatch2, { path: path108, method, body, headers }) {
      const pathMatch = matchValue(mockDispatch2.path, path108);
      const methodMatch = matchValue(mockDispatch2.method, method);
      const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
      const headersMatch = matchHeaders(mockDispatch2, headers);
      return pathMatch && methodMatch && bodyMatch && headersMatch;
    }
    __name(matchKey, "matchKey");
    function getResponseData(data) {
      if (Buffer.isBuffer(data)) {
        return data;
      } else if (data instanceof Uint8Array) {
        return data;
      } else if (data instanceof ArrayBuffer) {
        return data;
      } else if (typeof data === "object") {
        return JSON.stringify(data);
      } else if (data) {
        return data.toString();
      } else {
        return "";
      }
    }
    __name(getResponseData, "getResponseData");
    function getMockDispatch(mockDispatches, key) {
      const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path;
      const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
      const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath);
      let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path108, ignoreTrailingSlash }) => {
        return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path108)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path108), resolvedPath);
      });
      if (matchedMockDispatches.length === 0) {
        throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
      }
      matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method));
      if (matchedMockDispatches.length === 0) {
        throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}' on path '${resolvedPath}'`);
      }
      matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== "undefined" ? matchValue(body, key.body) : true);
      if (matchedMockDispatches.length === 0) {
        throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}' on path '${resolvedPath}'`);
      }
      matchedMockDispatches = matchedMockDispatches.filter((mockDispatch2) => matchHeaders(mockDispatch2, key.headers));
      if (matchedMockDispatches.length === 0) {
        const headers = typeof key.headers === "object" ? JSON.stringify(key.headers) : key.headers;
        throw new MockNotMatchedError(`Mock dispatch not matched for headers '${headers}' on path '${resolvedPath}'`);
      }
      return matchedMockDispatches[0];
    }
    __name(getMockDispatch, "getMockDispatch");
    function addMockDispatch(mockDispatches, key, data, opts) {
      const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false, ...opts };
      const replyData = typeof data === "function" ? { callback: data } : { ...data };
      const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } };
      mockDispatches.push(newMockDispatch);
      return newMockDispatch;
    }
    __name(addMockDispatch, "addMockDispatch");
    function deleteMockDispatch(mockDispatches, key) {
      const index = mockDispatches.findIndex((dispatch) => {
        if (!dispatch.consumed) {
          return false;
        }
        return matchKey(dispatch, key);
      });
      if (index !== -1) {
        mockDispatches.splice(index, 1);
      }
    }
    __name(deleteMockDispatch, "deleteMockDispatch");
    function removeTrailingSlash(path108) {
      while (path108.endsWith("/")) {
        path108 = path108.slice(0, -1);
      }
      if (path108.length === 0) {
        path108 = "/";
      }
      return path108;
    }
    __name(removeTrailingSlash, "removeTrailingSlash");
    function buildKey(opts) {
      const { path: path108, method, body, headers, query } = opts;
      return {
        path: path108,
        method,
        body,
        headers,
        query
      };
    }
    __name(buildKey, "buildKey");
    function generateKeyValues(data) {
      const keys = Object.keys(data);
      const result = [];
      for (let i = 0; i < keys.length; ++i) {
        const key = keys[i];
        const value = data[key];
        const name3 = Buffer.from(`${key}`);
        if (Array.isArray(value)) {
          for (let j = 0; j < value.length; ++j) {
            result.push(name3, Buffer.from(`${value[j]}`));
          }
        } else {
          result.push(name3, Buffer.from(`${value}`));
        }
      }
      return result;
    }
    __name(generateKeyValues, "generateKeyValues");
    function getStatusText2(statusCode) {
      return STATUS_CODES[statusCode] || "unknown";
    }
    __name(getStatusText2, "getStatusText");
    async function getResponse(body) {
      const buffers = [];
      for await (const data of body) {
        buffers.push(data);
      }
      return Buffer.concat(buffers).toString("utf8");
    }
    __name(getResponse, "getResponse");
    function mockDispatch(opts, handler) {
      const key = buildKey(opts);
      const mockDispatch2 = getMockDispatch(this[kDispatches], key);
      mockDispatch2.timesInvoked++;
      if (mockDispatch2.data.callback) {
        mockDispatch2.data = { ...mockDispatch2.data, ...mockDispatch2.data.callback(opts) };
      }
      const { data: { statusCode, data, headers, trailers, error }, delay: delay4, persist } = mockDispatch2;
      const { timesInvoked, times } = mockDispatch2;
      mockDispatch2.consumed = !persist && timesInvoked >= times;
      mockDispatch2.pending = timesInvoked < times;
      if (error !== null) {
        deleteMockDispatch(this[kDispatches], key);
        handler.onError(error);
        return true;
      }
      if (typeof delay4 === "number" && delay4 > 0) {
        setTimeout(() => {
          handleReply(this[kDispatches]);
        }, delay4);
      } else {
        handleReply(this[kDispatches]);
      }
      function handleReply(mockDispatches, _data = data) {
        const optsHeaders = Array.isArray(opts.headers) ? buildHeadersFromArray(opts.headers) : opts.headers;
        const body = typeof _data === "function" ? _data({ ...opts, headers: optsHeaders }) : _data;
        if (isPromise2(body)) {
          body.then((newData) => handleReply(mockDispatches, newData));
          return;
        }
        const responseData = getResponseData(body);
        const responseHeaders = generateKeyValues(headers);
        const responseTrailers = generateKeyValues(trailers);
        handler.onConnect?.((err) => handler.onError(err), null);
        handler.onHeaders?.(statusCode, responseHeaders, resume, getStatusText2(statusCode));
        handler.onData?.(Buffer.from(responseData));
        handler.onComplete?.(responseTrailers);
        deleteMockDispatch(mockDispatches, key);
      }
      __name(handleReply, "handleReply");
      function resume() {
      }
      __name(resume, "resume");
      return true;
    }
    __name(mockDispatch, "mockDispatch");
    function buildMockDispatch() {
      const agent = this[kMockAgent];
      const origin = this[kOrigin];
      const originalDispatch = this[kOriginalDispatch];
      return /* @__PURE__ */ __name(function dispatch(opts, handler) {
        if (agent.isMockActive) {
          try {
            mockDispatch.call(this, opts, handler);
          } catch (error) {
            if (error instanceof MockNotMatchedError) {
              const netConnect = agent[kGetNetConnect]();
              if (netConnect === false) {
                throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`);
              }
              if (checkNetConnect(netConnect, origin)) {
                originalDispatch.call(this, opts, handler);
              } else {
                throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`);
              }
            } else {
              throw error;
            }
          }
        } else {
          originalDispatch.call(this, opts, handler);
        }
      }, "dispatch");
    }
    __name(buildMockDispatch, "buildMockDispatch");
    function checkNetConnect(netConnect, origin) {
      const url2 = new URL(origin);
      if (netConnect === true) {
        return true;
      } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url2.host))) {
        return true;
      }
      return false;
    }
    __name(checkNetConnect, "checkNetConnect");
    function buildAndValidateMockOptions(opts) {
      if (opts) {
        const { agent, ...mockOptions } = opts;
        if ("enableCallHistory" in mockOptions && typeof mockOptions.enableCallHistory !== "boolean") {
          throw new InvalidArgumentError("options.enableCallHistory must to be a boolean");
        }
        if ("acceptNonStandardSearchParameters" in mockOptions && typeof mockOptions.acceptNonStandardSearchParameters !== "boolean") {
          throw new InvalidArgumentError("options.acceptNonStandardSearchParameters must to be a boolean");
        }
        return mockOptions;
      }
    }
    __name(buildAndValidateMockOptions, "buildAndValidateMockOptions");
    module2.exports = {
      getResponseData,
      getMockDispatch,
      addMockDispatch,
      deleteMockDispatch,
      buildKey,
      generateKeyValues,
      matchValue,
      getResponse,
      getStatusText: getStatusText2,
      mockDispatch,
      buildMockDispatch,
      checkNetConnect,
      buildAndValidateMockOptions,
      getHeaderByName,
      buildHeadersFromArray,
      normalizeSearchParams
    };
  }
});

// node_modules/undici/lib/mock/mock-interceptor.js
var require_mock_interceptor = __commonJS({
  "node_modules/undici/lib/mock/mock-interceptor.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { getResponseData, buildKey, addMockDispatch } = require_mock_utils();
    var {
      kDispatches,
      kDispatchKey,
      kDefaultHeaders,
      kDefaultTrailers,
      kContentLength,
      kMockDispatch,
      kIgnoreTrailingSlash
    } = require_mock_symbols();
    var { InvalidArgumentError } = require_errors();
    var { serializePathWithQuery } = require_util();
    var MockScope = class {
      static {
        __name(this, "MockScope");
      }
      constructor(mockDispatch) {
        this[kMockDispatch] = mockDispatch;
      }
      /**
       * Delay a reply by a set amount in ms.
       */
      delay(waitInMs) {
        if (typeof waitInMs !== "number" || !Number.isInteger(waitInMs) || waitInMs <= 0) {
          throw new InvalidArgumentError("waitInMs must be a valid integer > 0");
        }
        this[kMockDispatch].delay = waitInMs;
        return this;
      }
      /**
       * For a defined reply, never mark as consumed.
       */
      persist() {
        this[kMockDispatch].persist = true;
        return this;
      }
      /**
       * Allow one to define a reply for a set amount of matching requests.
       */
      times(repeatTimes) {
        if (typeof repeatTimes !== "number" || !Number.isInteger(repeatTimes) || repeatTimes <= 0) {
          throw new InvalidArgumentError("repeatTimes must be a valid integer > 0");
        }
        this[kMockDispatch].times = repeatTimes;
        return this;
      }
    };
    var MockInterceptor = class {
      static {
        __name(this, "MockInterceptor");
      }
      constructor(opts, mockDispatches) {
        if (typeof opts !== "object") {
          throw new InvalidArgumentError("opts must be an object");
        }
        if (typeof opts.path === "undefined") {
          throw new InvalidArgumentError("opts.path must be defined");
        }
        if (typeof opts.method === "undefined") {
          opts.method = "GET";
        }
        if (typeof opts.path === "string") {
          if (opts.query) {
            opts.path = serializePathWithQuery(opts.path, opts.query);
          } else {
            const parsedURL = new URL(opts.path, "data://");
            opts.path = parsedURL.pathname + parsedURL.search;
          }
        }
        if (typeof opts.method === "string") {
          opts.method = opts.method.toUpperCase();
        }
        this[kDispatchKey] = buildKey(opts);
        this[kDispatches] = mockDispatches;
        this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false;
        this[kDefaultHeaders] = {};
        this[kDefaultTrailers] = {};
        this[kContentLength] = false;
      }
      createMockScopeDispatchData({ statusCode, data, responseOptions }) {
        const responseData = getResponseData(data);
        const contentLength = this[kContentLength] ? { "content-length": responseData.length } : {};
        const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers };
        const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers };
        return { statusCode, data, headers, trailers };
      }
      validateReplyParameters(replyParameters) {
        if (typeof replyParameters.statusCode === "undefined") {
          throw new InvalidArgumentError("statusCode must be defined");
        }
        if (typeof replyParameters.responseOptions !== "object" || replyParameters.responseOptions === null) {
          throw new InvalidArgumentError("responseOptions must be an object");
        }
      }
      /**
       * Mock an undici request with a defined reply.
       */
      reply(replyOptionsCallbackOrStatusCode) {
        if (typeof replyOptionsCallbackOrStatusCode === "function") {
          const wrappedDefaultsCallback = /* @__PURE__ */ __name((opts) => {
            const resolvedData = replyOptionsCallbackOrStatusCode(opts);
            if (typeof resolvedData !== "object" || resolvedData === null) {
              throw new InvalidArgumentError("reply options callback must return an object");
            }
            const replyParameters2 = { data: "", responseOptions: {}, ...resolvedData };
            this.validateReplyParameters(replyParameters2);
            return {
              ...this.createMockScopeDispatchData(replyParameters2)
            };
          }, "wrappedDefaultsCallback");
          const newMockDispatch2 = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] });
          return new MockScope(newMockDispatch2);
        }
        const replyParameters = {
          statusCode: replyOptionsCallbackOrStatusCode,
          data: arguments[1] === void 0 ? "" : arguments[1],
          responseOptions: arguments[2] === void 0 ? {} : arguments[2]
        };
        this.validateReplyParameters(replyParameters);
        const dispatchData = this.createMockScopeDispatchData(replyParameters);
        const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] });
        return new MockScope(newMockDispatch);
      }
      /**
       * Mock an undici request with a defined error.
       */
      replyWithError(error) {
        if (typeof error === "undefined") {
          throw new InvalidArgumentError("error must be defined");
        }
        const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] });
        return new MockScope(newMockDispatch);
      }
      /**
       * Set default reply headers on the interceptor for subsequent replies
       */
      defaultReplyHeaders(headers) {
        if (typeof headers === "undefined") {
          throw new InvalidArgumentError("headers must be defined");
        }
        this[kDefaultHeaders] = headers;
        return this;
      }
      /**
       * Set default reply trailers on the interceptor for subsequent replies
       */
      defaultReplyTrailers(trailers) {
        if (typeof trailers === "undefined") {
          throw new InvalidArgumentError("trailers must be defined");
        }
        this[kDefaultTrailers] = trailers;
        return this;
      }
      /**
       * Set reply content length header for replies on the interceptor
       */
      replyContentLength() {
        this[kContentLength] = true;
        return this;
      }
    };
    module2.exports.MockInterceptor = MockInterceptor;
    module2.exports.MockScope = MockScope;
  }
});

// node_modules/undici/lib/mock/mock-client.js
var require_mock_client = __commonJS({
  "node_modules/undici/lib/mock/mock-client.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { promisify: promisify10 } = __require("node:util");
    var Client2 = require_client();
    var { buildMockDispatch } = require_mock_utils();
    var {
      kDispatches,
      kMockAgent,
      kClose,
      kOriginalClose,
      kOrigin,
      kOriginalDispatch,
      kConnected,
      kIgnoreTrailingSlash
    } = require_mock_symbols();
    var { MockInterceptor } = require_mock_interceptor();
    var Symbols = require_symbols();
    var { InvalidArgumentError } = require_errors();
    var MockClient = class extends Client2 {
      static {
        __name(this, "MockClient");
      }
      constructor(origin, opts) {
        if (!opts || !opts.agent || typeof opts.agent.dispatch !== "function") {
          throw new InvalidArgumentError("Argument opts.agent must implement Agent");
        }
        super(origin, opts);
        this[kMockAgent] = opts.agent;
        this[kOrigin] = origin;
        this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false;
        this[kDispatches] = [];
        this[kConnected] = 1;
        this[kOriginalDispatch] = this.dispatch;
        this[kOriginalClose] = this.close.bind(this);
        this.dispatch = buildMockDispatch.call(this);
        this.close = this[kClose];
      }
      get [Symbols.kConnected]() {
        return this[kConnected];
      }
      /**
       * Sets up the base interceptor for mocking replies from undici.
       */
      intercept(opts) {
        return new MockInterceptor(
          opts && { ignoreTrailingSlash: this[kIgnoreTrailingSlash], ...opts },
          this[kDispatches]
        );
      }
      cleanMocks() {
        this[kDispatches] = [];
      }
      async [kClose]() {
        await promisify10(this[kOriginalClose])();
        this[kConnected] = 0;
        this[kMockAgent][Symbols.kClients].delete(this[kOrigin]);
      }
    };
    module2.exports = MockClient;
  }
});

// node_modules/undici/lib/mock/mock-call-history.js
var require_mock_call_history = __commonJS({
  "node_modules/undici/lib/mock/mock-call-history.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { kMockCallHistoryAddLog } = require_mock_symbols();
    var { InvalidArgumentError } = require_errors();
    function handleFilterCallsWithOptions(criteria, options2, handler, store) {
      switch (options2.operator) {
        case "OR":
          store.push(...handler(criteria));
          return store;
        case "AND":
          return handler.call({ logs: store }, criteria);
        default:
          throw new InvalidArgumentError("options.operator must to be a case insensitive string equal to 'OR' or 'AND'");
      }
    }
    __name(handleFilterCallsWithOptions, "handleFilterCallsWithOptions");
    function buildAndValidateFilterCallsOptions(options2 = {}) {
      const finalOptions = {};
      if ("operator" in options2) {
        if (typeof options2.operator !== "string" || options2.operator.toUpperCase() !== "OR" && options2.operator.toUpperCase() !== "AND") {
          throw new InvalidArgumentError("options.operator must to be a case insensitive string equal to 'OR' or 'AND'");
        }
        return {
          ...finalOptions,
          operator: options2.operator.toUpperCase()
        };
      }
      return finalOptions;
    }
    __name(buildAndValidateFilterCallsOptions, "buildAndValidateFilterCallsOptions");
    function makeFilterCalls(parameterName) {
      return (parameterValue) => {
        if (typeof parameterValue === "string" || parameterValue == null) {
          return this.logs.filter((log) => {
            return log[parameterName] === parameterValue;
          });
        }
        if (parameterValue instanceof RegExp) {
          return this.logs.filter((log) => {
            return parameterValue.test(log[parameterName]);
          });
        }
        throw new InvalidArgumentError(`${parameterName} parameter should be one of string, regexp, undefined or null`);
      };
    }
    __name(makeFilterCalls, "makeFilterCalls");
    function computeUrlWithMaybeSearchParameters(requestInit) {
      try {
        const url2 = new URL(requestInit.path, requestInit.origin);
        if (url2.search.length !== 0) {
          return url2;
        }
        url2.search = new URLSearchParams(requestInit.query).toString();
        return url2;
      } catch (error) {
        throw new InvalidArgumentError("An error occurred when computing MockCallHistoryLog.url", { cause: error });
      }
    }
    __name(computeUrlWithMaybeSearchParameters, "computeUrlWithMaybeSearchParameters");
    var MockCallHistoryLog = class {
      static {
        __name(this, "MockCallHistoryLog");
      }
      constructor(requestInit = {}) {
        this.body = requestInit.body;
        this.headers = requestInit.headers;
        this.method = requestInit.method;
        const url2 = computeUrlWithMaybeSearchParameters(requestInit);
        this.fullUrl = url2.toString();
        this.origin = url2.origin;
        this.path = url2.pathname;
        this.searchParams = Object.fromEntries(url2.searchParams);
        this.protocol = url2.protocol;
        this.host = url2.host;
        this.port = url2.port;
        this.hash = url2.hash;
      }
      toMap() {
        return /* @__PURE__ */ new Map(
          [
            ["protocol", this.protocol],
            ["host", this.host],
            ["port", this.port],
            ["origin", this.origin],
            ["path", this.path],
            ["hash", this.hash],
            ["searchParams", this.searchParams],
            ["fullUrl", this.fullUrl],
            ["method", this.method],
            ["body", this.body],
            ["headers", this.headers]
          ]
        );
      }
      toString() {
        const options2 = { betweenKeyValueSeparator: "->", betweenPairSeparator: "|" };
        let result = "";
        this.toMap().forEach((value, key) => {
          if (typeof value === "string" || value === void 0 || value === null) {
            result = `${result}${key}${options2.betweenKeyValueSeparator}${value}${options2.betweenPairSeparator}`;
          }
          if (typeof value === "object" && value !== null || Array.isArray(value)) {
            result = `${result}${key}${options2.betweenKeyValueSeparator}${JSON.stringify(value)}${options2.betweenPairSeparator}`;
          }
        });
        return result.slice(0, -1);
      }
    };
    var MockCallHistory = class {
      static {
        __name(this, "MockCallHistory");
      }
      logs = [];
      calls() {
        return this.logs;
      }
      firstCall() {
        return this.logs.at(0);
      }
      lastCall() {
        return this.logs.at(-1);
      }
      nthCall(number) {
        if (typeof number !== "number") {
          throw new InvalidArgumentError("nthCall must be called with a number");
        }
        if (!Number.isInteger(number)) {
          throw new InvalidArgumentError("nthCall must be called with an integer");
        }
        if (Math.sign(number) !== 1) {
          throw new InvalidArgumentError("nthCall must be called with a positive value. use firstCall or lastCall instead");
        }
        return this.logs.at(number - 1);
      }
      filterCalls(criteria, options2) {
        if (this.logs.length === 0) {
          return this.logs;
        }
        if (typeof criteria === "function") {
          return this.logs.filter(criteria);
        }
        if (criteria instanceof RegExp) {
          return this.logs.filter((log) => {
            return criteria.test(log.toString());
          });
        }
        if (typeof criteria === "object" && criteria !== null) {
          if (Object.keys(criteria).length === 0) {
            return this.logs;
          }
          const finalOptions = { operator: "OR", ...buildAndValidateFilterCallsOptions(options2) };
          let maybeDuplicatedLogsFiltered = [];
          if ("protocol" in criteria) {
            maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.protocol, finalOptions, this.filterCallsByProtocol, maybeDuplicatedLogsFiltered);
          }
          if ("host" in criteria) {
            maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.host, finalOptions, this.filterCallsByHost, maybeDuplicatedLogsFiltered);
          }
          if ("port" in criteria) {
            maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.port, finalOptions, this.filterCallsByPort, maybeDuplicatedLogsFiltered);
          }
          if ("origin" in criteria) {
            maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.origin, finalOptions, this.filterCallsByOrigin, maybeDuplicatedLogsFiltered);
          }
          if ("path" in criteria) {
            maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.path, finalOptions, this.filterCallsByPath, maybeDuplicatedLogsFiltered);
          }
          if ("hash" in criteria) {
            maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.hash, finalOptions, this.filterCallsByHash, maybeDuplicatedLogsFiltered);
          }
          if ("fullUrl" in criteria) {
            maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.fullUrl, finalOptions, this.filterCallsByFullUrl, maybeDuplicatedLogsFiltered);
          }
          if ("method" in criteria) {
            maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.method, finalOptions, this.filterCallsByMethod, maybeDuplicatedLogsFiltered);
          }
          const uniqLogsFiltered = [...new Set(maybeDuplicatedLogsFiltered)];
          return uniqLogsFiltered;
        }
        throw new InvalidArgumentError("criteria parameter should be one of function, regexp, or object");
      }
      filterCallsByProtocol = makeFilterCalls.call(this, "protocol");
      filterCallsByHost = makeFilterCalls.call(this, "host");
      filterCallsByPort = makeFilterCalls.call(this, "port");
      filterCallsByOrigin = makeFilterCalls.call(this, "origin");
      filterCallsByPath = makeFilterCalls.call(this, "path");
      filterCallsByHash = makeFilterCalls.call(this, "hash");
      filterCallsByFullUrl = makeFilterCalls.call(this, "fullUrl");
      filterCallsByMethod = makeFilterCalls.call(this, "method");
      clear() {
        this.logs = [];
      }
      [kMockCallHistoryAddLog](requestInit) {
        const log = new MockCallHistoryLog(requestInit);
        this.logs.push(log);
        return log;
      }
      *[Symbol.iterator]() {
        for (const log of this.calls()) {
          yield log;
        }
      }
    };
    module2.exports.MockCallHistory = MockCallHistory;
    module2.exports.MockCallHistoryLog = MockCallHistoryLog;
  }
});

// node_modules/undici/lib/mock/mock-pool.js
var require_mock_pool = __commonJS({
  "node_modules/undici/lib/mock/mock-pool.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { promisify: promisify10 } = __require("node:util");
    var Pool = require_pool();
    var { buildMockDispatch } = require_mock_utils();
    var {
      kDispatches,
      kMockAgent,
      kClose,
      kOriginalClose,
      kOrigin,
      kOriginalDispatch,
      kConnected,
      kIgnoreTrailingSlash
    } = require_mock_symbols();
    var { MockInterceptor } = require_mock_interceptor();
    var Symbols = require_symbols();
    var { InvalidArgumentError } = require_errors();
    var MockPool = class extends Pool {
      static {
        __name(this, "MockPool");
      }
      constructor(origin, opts) {
        if (!opts || !opts.agent || typeof opts.agent.dispatch !== "function") {
          throw new InvalidArgumentError("Argument opts.agent must implement Agent");
        }
        super(origin, opts);
        this[kMockAgent] = opts.agent;
        this[kOrigin] = origin;
        this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false;
        this[kDispatches] = [];
        this[kConnected] = 1;
        this[kOriginalDispatch] = this.dispatch;
        this[kOriginalClose] = this.close.bind(this);
        this.dispatch = buildMockDispatch.call(this);
        this.close = this[kClose];
      }
      get [Symbols.kConnected]() {
        return this[kConnected];
      }
      /**
       * Sets up the base interceptor for mocking replies from undici.
       */
      intercept(opts) {
        return new MockInterceptor(
          opts && { ignoreTrailingSlash: this[kIgnoreTrailingSlash], ...opts },
          this[kDispatches]
        );
      }
      cleanMocks() {
        this[kDispatches] = [];
      }
      async [kClose]() {
        await promisify10(this[kOriginalClose])();
        this[kConnected] = 0;
        this[kMockAgent][Symbols.kClients].delete(this[kOrigin]);
      }
    };
    module2.exports = MockPool;
  }
});

// node_modules/undici/lib/mock/pending-interceptors-formatter.js
var require_pending_interceptors_formatter = __commonJS({
  "node_modules/undici/lib/mock/pending-interceptors-formatter.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Transform: Transform2 } = __require("node:stream");
    var { Console } = __require("node:console");
    var PERSISTENT = process.versions.icu ? "\u2705" : "Y ";
    var NOT_PERSISTENT = process.versions.icu ? "\u274C" : "N ";
    module2.exports = class PendingInterceptorsFormatter {
      static {
        __name(this, "PendingInterceptorsFormatter");
      }
      constructor({ disableColors } = {}) {
        this.transform = new Transform2({
          transform(chunk, _enc, cb) {
            cb(null, chunk);
          }
        });
        this.logger = new Console({
          stdout: this.transform,
          inspectOptions: {
            colors: !disableColors && !process.env.CI
          }
        });
      }
      format(pendingInterceptors) {
        const withPrettyHeaders = pendingInterceptors.map(
          ({ method, path: path108, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
            Method: method,
            Origin: origin,
            Path: path108,
            "Status code": statusCode,
            Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
            Invocations: timesInvoked,
            Remaining: persist ? Infinity : times - timesInvoked
          })
        );
        this.logger.table(withPrettyHeaders);
        return this.transform.read().toString();
      }
    };
  }
});

// node_modules/undici/lib/mock/mock-agent.js
var require_mock_agent = __commonJS({
  "node_modules/undici/lib/mock/mock-agent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { kClients } = require_symbols();
    var Agent3 = require_agent();
    var {
      kAgent,
      kMockAgentSet,
      kMockAgentGet,
      kDispatches,
      kIsMockActive,
      kNetConnect,
      kGetNetConnect,
      kOptions,
      kFactory,
      kMockAgentRegisterCallHistory,
      kMockAgentIsCallHistoryEnabled,
      kMockAgentAddCallHistoryLog,
      kMockAgentMockCallHistoryInstance,
      kMockAgentAcceptsNonStandardSearchParameters,
      kMockCallHistoryAddLog,
      kIgnoreTrailingSlash
    } = require_mock_symbols();
    var MockClient = require_mock_client();
    var MockPool = require_mock_pool();
    var { matchValue, normalizeSearchParams, buildAndValidateMockOptions } = require_mock_utils();
    var { InvalidArgumentError, UndiciError } = require_errors();
    var Dispatcher = require_dispatcher();
    var PendingInterceptorsFormatter = require_pending_interceptors_formatter();
    var { MockCallHistory } = require_mock_call_history();
    var MockAgent = class extends Dispatcher {
      static {
        __name(this, "MockAgent");
      }
      constructor(opts) {
        super(opts);
        const mockOptions = buildAndValidateMockOptions(opts);
        this[kNetConnect] = true;
        this[kIsMockActive] = true;
        this[kMockAgentIsCallHistoryEnabled] = mockOptions?.enableCallHistory ?? false;
        this[kMockAgentAcceptsNonStandardSearchParameters] = mockOptions?.acceptNonStandardSearchParameters ?? false;
        this[kIgnoreTrailingSlash] = mockOptions?.ignoreTrailingSlash ?? false;
        if (opts?.agent && typeof opts.agent.dispatch !== "function") {
          throw new InvalidArgumentError("Argument opts.agent must implement Agent");
        }
        const agent = opts?.agent ? opts.agent : new Agent3(opts);
        this[kAgent] = agent;
        this[kClients] = agent[kClients];
        this[kOptions] = mockOptions;
        if (this[kMockAgentIsCallHistoryEnabled]) {
          this[kMockAgentRegisterCallHistory]();
        }
      }
      get(origin) {
        const originKey = this[kIgnoreTrailingSlash] ? origin.replace(/\/$/, "") : origin;
        let dispatcher = this[kMockAgentGet](originKey);
        if (!dispatcher) {
          dispatcher = this[kFactory](originKey);
          this[kMockAgentSet](originKey, dispatcher);
        }
        return dispatcher;
      }
      dispatch(opts, handler) {
        this.get(opts.origin);
        this[kMockAgentAddCallHistoryLog](opts);
        const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
        const dispatchOpts = { ...opts };
        if (acceptNonStandardSearchParameters && dispatchOpts.path) {
          const [path108, searchParams] = dispatchOpts.path.split("?");
          const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
          dispatchOpts.path = `${path108}?${normalizedSearchParams}`;
        }
        return this[kAgent].dispatch(dispatchOpts, handler);
      }
      async close() {
        this.clearCallHistory();
        await this[kAgent].close();
        this[kClients].clear();
      }
      deactivate() {
        this[kIsMockActive] = false;
      }
      activate() {
        this[kIsMockActive] = true;
      }
      enableNetConnect(matcher) {
        if (typeof matcher === "string" || typeof matcher === "function" || matcher instanceof RegExp) {
          if (Array.isArray(this[kNetConnect])) {
            this[kNetConnect].push(matcher);
          } else {
            this[kNetConnect] = [matcher];
          }
        } else if (typeof matcher === "undefined") {
          this[kNetConnect] = true;
        } else {
          throw new InvalidArgumentError("Unsupported matcher. Must be one of String|Function|RegExp.");
        }
      }
      disableNetConnect() {
        this[kNetConnect] = false;
      }
      enableCallHistory() {
        this[kMockAgentIsCallHistoryEnabled] = true;
        return this;
      }
      disableCallHistory() {
        this[kMockAgentIsCallHistoryEnabled] = false;
        return this;
      }
      getCallHistory() {
        return this[kMockAgentMockCallHistoryInstance];
      }
      clearCallHistory() {
        if (this[kMockAgentMockCallHistoryInstance] !== void 0) {
          this[kMockAgentMockCallHistoryInstance].clear();
        }
      }
      // This is required to bypass issues caused by using global symbols - see:
      // https://github.com/nodejs/undici/issues/1447
      get isMockActive() {
        return this[kIsMockActive];
      }
      [kMockAgentRegisterCallHistory]() {
        if (this[kMockAgentMockCallHistoryInstance] === void 0) {
          this[kMockAgentMockCallHistoryInstance] = new MockCallHistory();
        }
      }
      [kMockAgentAddCallHistoryLog](opts) {
        if (this[kMockAgentIsCallHistoryEnabled]) {
          this[kMockAgentRegisterCallHistory]();
          this[kMockAgentMockCallHistoryInstance][kMockCallHistoryAddLog](opts);
        }
      }
      [kMockAgentSet](origin, dispatcher) {
        this[kClients].set(origin, { count: 0, dispatcher });
      }
      [kFactory](origin) {
        const mockOptions = Object.assign({ agent: this }, this[kOptions]);
        return this[kOptions] && this[kOptions].connections === 1 ? new MockClient(origin, mockOptions) : new MockPool(origin, mockOptions);
      }
      [kMockAgentGet](origin) {
        const result = this[kClients].get(origin);
        if (result?.dispatcher) {
          return result.dispatcher;
        }
        if (typeof origin !== "string") {
          const dispatcher = this[kFactory]("http://localhost:9999");
          this[kMockAgentSet](origin, dispatcher);
          return dispatcher;
        }
        for (const [keyMatcher, result2] of Array.from(this[kClients])) {
          if (result2 && typeof keyMatcher !== "string" && matchValue(keyMatcher, origin)) {
            const dispatcher = this[kFactory](origin);
            this[kMockAgentSet](origin, dispatcher);
            dispatcher[kDispatches] = result2.dispatcher[kDispatches];
            return dispatcher;
          }
        }
      }
      [kGetNetConnect]() {
        return this[kNetConnect];
      }
      pendingInterceptors() {
        const mockAgentClients = this[kClients];
        return Array.from(mockAgentClients.entries()).flatMap(([origin, result]) => result.dispatcher[kDispatches].map((dispatch) => ({ ...dispatch, origin }))).filter(({ pending }) => pending);
      }
      assertNoPendingInterceptors({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
        const pending = this.pendingInterceptors();
        if (pending.length === 0) {
          return;
        }
        throw new UndiciError(
          pending.length === 1 ? `1 interceptor is pending:

${pendingInterceptorsFormatter.format(pending)}`.trim() : `${pending.length} interceptors are pending:

${pendingInterceptorsFormatter.format(pending)}`.trim()
        );
      }
    };
    module2.exports = MockAgent;
  }
});

// node_modules/undici/lib/mock/snapshot-utils.js
var require_snapshot_utils = __commonJS({
  "node_modules/undici/lib/mock/snapshot-utils.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { InvalidArgumentError } = require_errors();
    function createHeaderFilters(matchOptions = {}) {
      const { ignoreHeaders = [], excludeHeaders = [], matchHeaders = [], caseSensitive = false } = matchOptions;
      return {
        ignore: new Set(ignoreHeaders.map((header) => caseSensitive ? header : header.toLowerCase())),
        exclude: new Set(excludeHeaders.map((header) => caseSensitive ? header : header.toLowerCase())),
        match: new Set(matchHeaders.map((header) => caseSensitive ? header : header.toLowerCase()))
      };
    }
    __name(createHeaderFilters, "createHeaderFilters");
    var crypto18;
    try {
      crypto18 = __require("node:crypto");
    } catch {
    }
    var hashId = crypto18?.hash ? (value) => crypto18.hash("sha256", value, "base64url") : (value) => Buffer.from(value).toString("base64url");
    function isUndiciHeaders(headers) {
      return Array.isArray(headers) && (headers.length & 1) === 0;
    }
    __name(isUndiciHeaders, "isUndiciHeaders");
    function isUrlExcludedFactory(excludePatterns = []) {
      if (excludePatterns.length === 0) {
        return () => false;
      }
      return /* @__PURE__ */ __name(function isUrlExcluded(url2) {
        let urlLowerCased;
        for (const pattern of excludePatterns) {
          if (typeof pattern === "string") {
            if (!urlLowerCased) {
              urlLowerCased = url2.toLowerCase();
            }
            if (urlLowerCased.includes(pattern.toLowerCase())) {
              return true;
            }
          } else if (pattern instanceof RegExp) {
            if (pattern.test(url2)) {
              return true;
            }
          }
        }
        return false;
      }, "isUrlExcluded");
    }
    __name(isUrlExcludedFactory, "isUrlExcludedFactory");
    function normalizeHeaders(headers) {
      const normalizedHeaders = {};
      if (!headers) return normalizedHeaders;
      if (isUndiciHeaders(headers)) {
        for (let i = 0; i < headers.length; i += 2) {
          const key = headers[i];
          const value = headers[i + 1];
          if (key && value !== void 0) {
            const keyStr = Buffer.isBuffer(key) ? key.toString() : key;
            const valueStr = Buffer.isBuffer(value) ? value.toString() : value;
            normalizedHeaders[keyStr.toLowerCase()] = valueStr;
          }
        }
        return normalizedHeaders;
      }
      if (headers && typeof headers === "object") {
        for (const [key, value] of Object.entries(headers)) {
          if (key && typeof key === "string") {
            normalizedHeaders[key.toLowerCase()] = Array.isArray(value) ? value.join(", ") : String(value);
          }
        }
      }
      return normalizedHeaders;
    }
    __name(normalizeHeaders, "normalizeHeaders");
    var validSnapshotModes = (
      /** @type {const} */
      ["record", "playback", "update"]
    );
    function validateSnapshotMode(mode) {
      if (!validSnapshotModes.includes(mode)) {
        throw new InvalidArgumentError(`Invalid snapshot mode: ${mode}. Must be one of: ${validSnapshotModes.join(", ")}`);
      }
    }
    __name(validateSnapshotMode, "validateSnapshotMode");
    module2.exports = {
      createHeaderFilters,
      hashId,
      isUndiciHeaders,
      normalizeHeaders,
      isUrlExcludedFactory,
      validateSnapshotMode
    };
  }
});

// node_modules/undici/lib/mock/snapshot-recorder.js
var require_snapshot_recorder = __commonJS({
  "node_modules/undici/lib/mock/snapshot-recorder.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { writeFile: writeFile12, readFile: readFile11, mkdir: mkdir11 } = __require("node:fs/promises");
    var { dirname: dirname22, resolve: resolve24 } = __require("node:path");
    var { setTimeout: setTimeout2, clearTimeout: clearTimeout2 } = __require("node:timers");
    var { InvalidArgumentError, UndiciError } = require_errors();
    var { hashId, isUrlExcludedFactory, normalizeHeaders, createHeaderFilters } = require_snapshot_utils();
    function formatRequestKey(opts, headerFilters, matchOptions = {}) {
      const url2 = new URL(opts.path, opts.origin);
      const normalized2 = opts._normalizedHeaders || normalizeHeaders(opts.headers);
      if (!opts._normalizedHeaders) {
        opts._normalizedHeaders = normalized2;
      }
      return {
        method: opts.method || "GET",
        url: matchOptions.matchQuery !== false ? url2.toString() : `${url2.origin}${url2.pathname}`,
        headers: filterHeadersForMatching(normalized2, headerFilters, matchOptions),
        body: matchOptions.matchBody !== false && opts.body ? String(opts.body) : ""
      };
    }
    __name(formatRequestKey, "formatRequestKey");
    function filterHeadersForMatching(headers, headerFilters, matchOptions = {}) {
      if (!headers || typeof headers !== "object") return {};
      const {
        caseSensitive = false
      } = matchOptions;
      const filtered = {};
      const { ignore: ignore4, exclude, match: match2 } = headerFilters;
      for (const [key, value] of Object.entries(headers)) {
        const headerKey = caseSensitive ? key : key.toLowerCase();
        if (exclude.has(headerKey)) continue;
        if (ignore4.has(headerKey)) continue;
        if (match2.size !== 0) {
          if (!match2.has(headerKey)) continue;
        }
        filtered[headerKey] = value;
      }
      return filtered;
    }
    __name(filterHeadersForMatching, "filterHeadersForMatching");
    function filterHeadersForStorage(headers, headerFilters, matchOptions = {}) {
      if (!headers || typeof headers !== "object") return {};
      const {
        caseSensitive = false
      } = matchOptions;
      const filtered = {};
      const { exclude: excludeSet } = headerFilters;
      for (const [key, value] of Object.entries(headers)) {
        const headerKey = caseSensitive ? key : key.toLowerCase();
        if (excludeSet.has(headerKey)) continue;
        filtered[headerKey] = value;
      }
      return filtered;
    }
    __name(filterHeadersForStorage, "filterHeadersForStorage");
    function createRequestHash(formattedRequest) {
      const parts = [
        formattedRequest.method,
        formattedRequest.url
      ];
      if (formattedRequest.headers && typeof formattedRequest.headers === "object") {
        const headerKeys = Object.keys(formattedRequest.headers).sort();
        for (const key of headerKeys) {
          const values = Array.isArray(formattedRequest.headers[key]) ? formattedRequest.headers[key] : [formattedRequest.headers[key]];
          parts.push(key);
          for (const value of values.sort()) {
            parts.push(String(value));
          }
        }
      }
      parts.push(formattedRequest.body);
      const content = parts.join("|");
      return hashId(content);
    }
    __name(createRequestHash, "createRequestHash");
    var SnapshotRecorder = class {
      static {
        __name(this, "SnapshotRecorder");
      }
      /** @type {NodeJS.Timeout | null} */
      #flushTimeout;
      /** @type {import('./snapshot-utils').IsUrlExcluded} */
      #isUrlExcluded;
      /** @type {Map<string, SnapshotEntry>} */
      #snapshots = /* @__PURE__ */ new Map();
      /** @type {string|undefined} */
      #snapshotPath;
      /** @type {number} */
      #maxSnapshots = Infinity;
      /** @type {boolean} */
      #autoFlush = false;
      /** @type {import('./snapshot-utils').HeaderFilters} */
      #headerFilters;
      /**
       * Creates a new SnapshotRecorder instance
       * @param {SnapshotRecorderOptions&SnapshotRecorderMatchOptions} [options={}] - Configuration options for the recorder
       */
      constructor(options2 = {}) {
        this.#snapshotPath = options2.snapshotPath;
        this.#maxSnapshots = options2.maxSnapshots || Infinity;
        this.#autoFlush = options2.autoFlush || false;
        this.flushInterval = options2.flushInterval || 3e4;
        this._flushTimer = null;
        this.matchOptions = {
          matchHeaders: options2.matchHeaders || [],
          // empty means match all headers
          ignoreHeaders: options2.ignoreHeaders || [],
          excludeHeaders: options2.excludeHeaders || [],
          matchBody: options2.matchBody !== false,
          // default: true
          matchQuery: options2.matchQuery !== false,
          // default: true
          caseSensitive: options2.caseSensitive || false
        };
        this.#headerFilters = createHeaderFilters(this.matchOptions);
        this.shouldRecord = options2.shouldRecord || (() => true);
        this.shouldPlayback = options2.shouldPlayback || (() => true);
        this.#isUrlExcluded = isUrlExcludedFactory(options2.excludeUrls);
        if (this.#autoFlush && this.#snapshotPath) {
          this.#startAutoFlush();
        }
      }
      /**
       * Records a request-response interaction
       * @param {SnapshotRequestOptions} requestOpts - Request options
       * @param {SnapshotEntryResponse} response - Response data to record
       * @return {Promise<void>} - Resolves when the recording is complete
       */
      async record(requestOpts, response) {
        if (!this.shouldRecord(requestOpts)) {
          return;
        }
        const url2 = new URL(requestOpts.path, requestOpts.origin).toString();
        if (this.#isUrlExcluded(url2)) {
          return;
        }
        const request4 = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions);
        const hash = createRequestHash(request4);
        const normalizedHeaders = normalizeHeaders(response.headers);
        const responseData = {
          statusCode: response.statusCode,
          headers: filterHeadersForStorage(normalizedHeaders, this.#headerFilters, this.matchOptions),
          body: Buffer.isBuffer(response.body) ? response.body.toString("base64") : Buffer.from(String(response.body || "")).toString("base64"),
          trailers: response.trailers
        };
        if (this.#snapshots.size >= this.#maxSnapshots && !this.#snapshots.has(hash)) {
          const oldestKey = this.#snapshots.keys().next().value;
          this.#snapshots.delete(oldestKey);
        }
        const existingSnapshot = this.#snapshots.get(hash);
        if (existingSnapshot && existingSnapshot.responses) {
          existingSnapshot.responses.push(responseData);
          existingSnapshot.timestamp = (/* @__PURE__ */ new Date()).toISOString();
        } else {
          this.#snapshots.set(hash, {
            request: request4,
            responses: [responseData],
            // Always store as array for consistency
            callCount: 0,
            timestamp: (/* @__PURE__ */ new Date()).toISOString()
          });
        }
        if (this.#autoFlush && this.#snapshotPath) {
          this.#scheduleFlush();
        }
      }
      /**
       * Finds a matching snapshot for the given request
       * Returns the appropriate response based on call count for sequential responses
       *
       * @param {SnapshotRequestOptions} requestOpts - Request options to match
       * @returns {SnapshotEntry&Record<'response', SnapshotEntryResponse>|undefined} - Matching snapshot response or undefined if not found
       */
      findSnapshot(requestOpts) {
        if (!this.shouldPlayback(requestOpts)) {
          return void 0;
        }
        const url2 = new URL(requestOpts.path, requestOpts.origin).toString();
        if (this.#isUrlExcluded(url2)) {
          return void 0;
        }
        const request4 = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions);
        const hash = createRequestHash(request4);
        const snapshot = this.#snapshots.get(hash);
        if (!snapshot) return void 0;
        const currentCallCount = snapshot.callCount || 0;
        const responseIndex = Math.min(currentCallCount, snapshot.responses.length - 1);
        snapshot.callCount = currentCallCount + 1;
        return {
          ...snapshot,
          response: snapshot.responses[responseIndex]
        };
      }
      /**
       * Loads snapshots from file
       * @param {string} [filePath] - Optional file path to load snapshots from
       * @return {Promise<void>} - Resolves when snapshots are loaded
       */
      async loadSnapshots(filePath) {
        const path108 = filePath || this.#snapshotPath;
        if (!path108) {
          throw new InvalidArgumentError("Snapshot path is required");
        }
        try {
          const data = await readFile11(resolve24(path108), "utf8");
          const parsed = JSON.parse(data);
          if (Array.isArray(parsed)) {
            this.#snapshots.clear();
            for (const { hash, snapshot } of parsed) {
              this.#snapshots.set(hash, snapshot);
            }
          } else {
            this.#snapshots = new Map(Object.entries(parsed));
          }
        } catch (error) {
          if (error.code === "ENOENT") {
            this.#snapshots.clear();
          } else {
            throw new UndiciError(`Failed to load snapshots from ${path108}`, { cause: error });
          }
        }
      }
      /**
       * Saves snapshots to file
       *
       * @param {string} [filePath] - Optional file path to save snapshots
       * @returns {Promise<void>} - Resolves when snapshots are saved
       */
      async saveSnapshots(filePath) {
        const path108 = filePath || this.#snapshotPath;
        if (!path108) {
          throw new InvalidArgumentError("Snapshot path is required");
        }
        const resolvedPath = resolve24(path108);
        await mkdir11(dirname22(resolvedPath), { recursive: true });
        const data = Array.from(this.#snapshots.entries()).map(([hash, snapshot]) => ({
          hash,
          snapshot
        }));
        await writeFile12(resolvedPath, JSON.stringify(data, null, 2), { flush: true });
      }
      /**
       * Clears all recorded snapshots
       * @returns {void}
       */
      clear() {
        this.#snapshots.clear();
      }
      /**
       * Gets all recorded snapshots
       * @return {Array<SnapshotEntry>} - Array of all recorded snapshots
       */
      getSnapshots() {
        return Array.from(this.#snapshots.values());
      }
      /**
       * Gets snapshot count
       * @return {number} - Number of recorded snapshots
       */
      size() {
        return this.#snapshots.size;
      }
      /**
       * Resets call counts for all snapshots (useful for test cleanup)
       * @returns {void}
       */
      resetCallCounts() {
        for (const snapshot of this.#snapshots.values()) {
          snapshot.callCount = 0;
        }
      }
      /**
       * Deletes a specific snapshot by request options
       * @param {SnapshotRequestOptions} requestOpts - Request options to match
       * @returns {boolean} - True if snapshot was deleted, false if not found
       */
      deleteSnapshot(requestOpts) {
        const request4 = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions);
        const hash = createRequestHash(request4);
        return this.#snapshots.delete(hash);
      }
      /**
       * Gets information about a specific snapshot
       * @param {SnapshotRequestOptions} requestOpts - Request options to match
       * @returns {SnapshotInfo|null} - Snapshot information or null if not found
       */
      getSnapshotInfo(requestOpts) {
        const request4 = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions);
        const hash = createRequestHash(request4);
        const snapshot = this.#snapshots.get(hash);
        if (!snapshot) return null;
        return {
          hash,
          request: snapshot.request,
          responseCount: snapshot.responses ? snapshot.responses.length : snapshot.response ? 1 : 0,
          // .response for legacy snapshots
          callCount: snapshot.callCount || 0,
          timestamp: snapshot.timestamp
        };
      }
      /**
       * Replaces all snapshots with new data (full replacement)
       * @param {Array<{hash: string; snapshot: SnapshotEntry}>|Record<string, SnapshotEntry>} snapshotData - New snapshot data to replace existing ones
       * @returns {void}
       */
      replaceSnapshots(snapshotData) {
        this.#snapshots.clear();
        if (Array.isArray(snapshotData)) {
          for (const { hash, snapshot } of snapshotData) {
            this.#snapshots.set(hash, snapshot);
          }
        } else if (snapshotData && typeof snapshotData === "object") {
          this.#snapshots = new Map(Object.entries(snapshotData));
        }
      }
      /**
       * Starts the auto-flush timer
       * @returns {void}
       */
      #startAutoFlush() {
        return this.#scheduleFlush();
      }
      /**
       * Stops the auto-flush timer
       * @returns {void}
       */
      #stopAutoFlush() {
        if (this.#flushTimeout) {
          clearTimeout2(this.#flushTimeout);
          this.saveSnapshots().catch(() => {
          });
          this.#flushTimeout = null;
        }
      }
      /**
       * Schedules a flush (debounced to avoid excessive writes)
       */
      #scheduleFlush() {
        this.#flushTimeout = setTimeout2(() => {
          this.saveSnapshots().catch(() => {
          });
          if (this.#autoFlush) {
            this.#flushTimeout?.refresh();
          } else {
            this.#flushTimeout = null;
          }
        }, 1e3);
      }
      /**
       * Cleanup method to stop timers
       * @returns {void}
       */
      destroy() {
        this.#stopAutoFlush();
        if (this.#flushTimeout) {
          clearTimeout2(this.#flushTimeout);
          this.#flushTimeout = null;
        }
      }
      /**
       * Async close method that saves all recordings and performs cleanup
       * @returns {Promise<void>}
       */
      async close() {
        if (this.#snapshotPath && this.#snapshots.size !== 0) {
          await this.saveSnapshots();
        }
        this.destroy();
      }
    };
    module2.exports = { SnapshotRecorder, formatRequestKey, createRequestHash, filterHeadersForMatching, filterHeadersForStorage, createHeaderFilters };
  }
});

// node_modules/undici/lib/mock/snapshot-agent.js
var require_snapshot_agent = __commonJS({
  "node_modules/undici/lib/mock/snapshot-agent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Agent3 = require_agent();
    var MockAgent = require_mock_agent();
    var { SnapshotRecorder } = require_snapshot_recorder();
    var WrapHandler = require_wrap_handler();
    var { InvalidArgumentError, UndiciError } = require_errors();
    var { validateSnapshotMode } = require_snapshot_utils();
    var kSnapshotRecorder = Symbol("kSnapshotRecorder");
    var kSnapshotMode = Symbol("kSnapshotMode");
    var kSnapshotPath = Symbol("kSnapshotPath");
    var kSnapshotLoaded = Symbol("kSnapshotLoaded");
    var kRealAgent = Symbol("kRealAgent");
    var warningEmitted = false;
    var SnapshotAgent = class extends MockAgent {
      static {
        __name(this, "SnapshotAgent");
      }
      constructor(opts = {}) {
        if (!warningEmitted) {
          process.emitWarning(
            "SnapshotAgent is experimental and subject to change",
            "ExperimentalWarning"
          );
          warningEmitted = true;
        }
        const {
          mode = "record",
          snapshotPath = null,
          ...mockAgentOpts
        } = opts;
        super(mockAgentOpts);
        validateSnapshotMode(mode);
        if ((mode === "playback" || mode === "update") && !snapshotPath) {
          throw new InvalidArgumentError(`snapshotPath is required when mode is '${mode}'`);
        }
        this[kSnapshotMode] = mode;
        this[kSnapshotPath] = snapshotPath;
        this[kSnapshotRecorder] = new SnapshotRecorder({
          snapshotPath: this[kSnapshotPath],
          mode: this[kSnapshotMode],
          maxSnapshots: opts.maxSnapshots,
          autoFlush: opts.autoFlush,
          flushInterval: opts.flushInterval,
          matchHeaders: opts.matchHeaders,
          ignoreHeaders: opts.ignoreHeaders,
          excludeHeaders: opts.excludeHeaders,
          matchBody: opts.matchBody,
          matchQuery: opts.matchQuery,
          caseSensitive: opts.caseSensitive,
          shouldRecord: opts.shouldRecord,
          shouldPlayback: opts.shouldPlayback,
          excludeUrls: opts.excludeUrls
        });
        this[kSnapshotLoaded] = false;
        if (this[kSnapshotMode] === "record" || this[kSnapshotMode] === "update") {
          this[kRealAgent] = new Agent3(opts);
        }
        if ((this[kSnapshotMode] === "playback" || this[kSnapshotMode] === "update") && this[kSnapshotPath]) {
          this.loadSnapshots().catch(() => {
          });
        }
      }
      dispatch(opts, handler) {
        handler = WrapHandler.wrap(handler);
        const mode = this[kSnapshotMode];
        if (mode === "playback" || mode === "update") {
          if (!this[kSnapshotLoaded]) {
            return this.#asyncDispatch(opts, handler);
          }
          const snapshot = this[kSnapshotRecorder].findSnapshot(opts);
          if (snapshot) {
            return this.#replaySnapshot(snapshot, handler);
          } else if (mode === "update") {
            return this.#recordAndReplay(opts, handler);
          } else {
            const error = new UndiciError(`No snapshot found for ${opts.method || "GET"} ${opts.path}`);
            if (handler.onError) {
              handler.onError(error);
              return;
            }
            throw error;
          }
        } else if (mode === "record") {
          return this.#recordAndReplay(opts, handler);
        }
      }
      /**
       * Async version of dispatch for when we need to load snapshots first
       */
      async #asyncDispatch(opts, handler) {
        await this.loadSnapshots();
        return this.dispatch(opts, handler);
      }
      /**
       * Records a real request and replays the response
       */
      #recordAndReplay(opts, handler) {
        const responseData = {
          statusCode: null,
          headers: {},
          trailers: {},
          body: []
        };
        const self2 = this;
        const recordingHandler = {
          onRequestStart(controller, context2) {
            return handler.onRequestStart(controller, { ...context2, history: this.history });
          },
          onRequestUpgrade(controller, statusCode, headers, socket) {
            return handler.onRequestUpgrade(controller, statusCode, headers, socket);
          },
          onResponseStart(controller, statusCode, headers, statusMessage) {
            responseData.statusCode = statusCode;
            responseData.headers = headers;
            return handler.onResponseStart(controller, statusCode, headers, statusMessage);
          },
          onResponseData(controller, chunk) {
            responseData.body.push(chunk);
            return handler.onResponseData(controller, chunk);
          },
          onResponseEnd(controller, trailers) {
            responseData.trailers = trailers;
            const responseBody = Buffer.concat(responseData.body);
            self2[kSnapshotRecorder].record(opts, {
              statusCode: responseData.statusCode,
              headers: responseData.headers,
              body: responseBody,
              trailers: responseData.trailers
            }).then(() => {
              handler.onResponseEnd(controller, trailers);
            }).catch((error) => {
              handler.onResponseError(controller, error);
            });
          }
        };
        const agent = this[kRealAgent];
        return agent.dispatch(opts, recordingHandler);
      }
      /**
       * Replays a recorded response
       *
       * @param {Object} snapshot - The recorded snapshot to replay.
       * @param {Object} handler - The handler to call with the response data.
       * @returns {void}
       */
      #replaySnapshot(snapshot, handler) {
        try {
          const { response } = snapshot;
          const controller = {
            pause() {
            },
            resume() {
            },
            abort(reason) {
              this.aborted = true;
              this.reason = reason;
            },
            aborted: false,
            paused: false
          };
          handler.onRequestStart(controller);
          handler.onResponseStart(controller, response.statusCode, response.headers);
          const body = Buffer.from(response.body, "base64");
          handler.onResponseData(controller, body);
          handler.onResponseEnd(controller, response.trailers);
        } catch (error) {
          handler.onError?.(error);
        }
      }
      /**
       * Loads snapshots from file
       *
       * @param {string} [filePath] - Optional file path to load snapshots from.
       * @returns {Promise<void>} - Resolves when snapshots are loaded.
       */
      async loadSnapshots(filePath) {
        await this[kSnapshotRecorder].loadSnapshots(filePath || this[kSnapshotPath]);
        this[kSnapshotLoaded] = true;
        if (this[kSnapshotMode] === "playback") {
          this.#setupMockInterceptors();
        }
      }
      /**
       * Saves snapshots to file
       *
       * @param {string} [filePath] - Optional file path to save snapshots to.
       * @returns {Promise<void>} - Resolves when snapshots are saved.
       */
      async saveSnapshots(filePath) {
        return this[kSnapshotRecorder].saveSnapshots(filePath || this[kSnapshotPath]);
      }
      /**
       * Sets up MockAgent interceptors based on recorded snapshots.
       *
       * This method creates MockAgent interceptors for each recorded snapshot,
       * allowing the SnapshotAgent to fall back to MockAgent's standard intercept
       * mechanism in playback mode. Each interceptor is configured to persist
       * (remain active for multiple requests) and responds with the recorded
       * response data.
       *
       * Called automatically when loading snapshots in playback mode.
       *
       * @returns {void}
       */
      #setupMockInterceptors() {
        for (const snapshot of this[kSnapshotRecorder].getSnapshots()) {
          const { request: request4, responses, response } = snapshot;
          const url2 = new URL(request4.url);
          const mockPool = this.get(url2.origin);
          const responseData = responses ? responses[0] : response;
          if (!responseData) continue;
          mockPool.intercept({
            path: url2.pathname + url2.search,
            method: request4.method,
            headers: request4.headers,
            body: request4.body
          }).reply(responseData.statusCode, responseData.body, {
            headers: responseData.headers,
            trailers: responseData.trailers
          }).persist();
        }
      }
      /**
       * Gets the snapshot recorder
       * @return {SnapshotRecorder} - The snapshot recorder instance
       */
      getRecorder() {
        return this[kSnapshotRecorder];
      }
      /**
       * Gets the current mode
       * @return {import('./snapshot-utils').SnapshotMode} - The current snapshot mode
       */
      getMode() {
        return this[kSnapshotMode];
      }
      /**
       * Clears all snapshots
       * @returns {void}
       */
      clearSnapshots() {
        this[kSnapshotRecorder].clear();
      }
      /**
       * Resets call counts for all snapshots (useful for test cleanup)
       * @returns {void}
       */
      resetCallCounts() {
        this[kSnapshotRecorder].resetCallCounts();
      }
      /**
       * Deletes a specific snapshot by request options
       * @param {import('./snapshot-recorder').SnapshotRequestOptions} requestOpts - Request options to identify the snapshot
       * @return {Promise<boolean>} - Returns true if the snapshot was deleted, false if not found
       */
      deleteSnapshot(requestOpts) {
        return this[kSnapshotRecorder].deleteSnapshot(requestOpts);
      }
      /**
       * Gets information about a specific snapshot
       * @returns {import('./snapshot-recorder').SnapshotInfo|null} - Snapshot information or null if not found
       */
      getSnapshotInfo(requestOpts) {
        return this[kSnapshotRecorder].getSnapshotInfo(requestOpts);
      }
      /**
       * Replaces all snapshots with new data (full replacement)
       * @param {Array<{hash: string; snapshot: import('./snapshot-recorder').SnapshotEntryshotEntry}>|Record<string, import('./snapshot-recorder').SnapshotEntry>} snapshotData - New snapshot data to replace existing snapshots
       * @returns {void}
       */
      replaceSnapshots(snapshotData) {
        this[kSnapshotRecorder].replaceSnapshots(snapshotData);
      }
      /**
       * Closes the agent, saving snapshots and cleaning up resources.
       *
       * @returns {Promise<void>}
       */
      async close() {
        await this[kSnapshotRecorder].close();
        await this[kRealAgent]?.close();
        await super.close();
      }
    };
    module2.exports = SnapshotAgent;
  }
});

// node_modules/undici/lib/global.js
var require_global2 = __commonJS({
  "node_modules/undici/lib/global.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var globalDispatcher = Symbol.for("undici.globalDispatcher.1");
    var { InvalidArgumentError } = require_errors();
    var Agent3 = require_agent();
    if (getGlobalDispatcher() === void 0) {
      setGlobalDispatcher3(new Agent3());
    }
    function setGlobalDispatcher3(agent) {
      if (!agent || typeof agent.dispatch !== "function") {
        throw new InvalidArgumentError("Argument agent must implement Agent");
      }
      Object.defineProperty(globalThis, globalDispatcher, {
        value: agent,
        writable: true,
        enumerable: false,
        configurable: false
      });
    }
    __name(setGlobalDispatcher3, "setGlobalDispatcher");
    function getGlobalDispatcher() {
      return globalThis[globalDispatcher];
    }
    __name(getGlobalDispatcher, "getGlobalDispatcher");
    module2.exports = {
      setGlobalDispatcher: setGlobalDispatcher3,
      getGlobalDispatcher
    };
  }
});

// node_modules/undici/lib/handler/decorator-handler.js
var require_decorator_handler = __commonJS({
  "node_modules/undici/lib/handler/decorator-handler.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert3 = __require("node:assert");
    var WrapHandler = require_wrap_handler();
    module2.exports = class DecoratorHandler {
      static {
        __name(this, "DecoratorHandler");
      }
      #handler;
      #onCompleteCalled = false;
      #onErrorCalled = false;
      #onResponseStartCalled = false;
      constructor(handler) {
        if (typeof handler !== "object" || handler === null) {
          throw new TypeError("handler must be an object");
        }
        this.#handler = WrapHandler.wrap(handler);
      }
      onRequestStart(...args) {
        this.#handler.onRequestStart?.(...args);
      }
      onRequestUpgrade(...args) {
        assert3(!this.#onCompleteCalled);
        assert3(!this.#onErrorCalled);
        return this.#handler.onRequestUpgrade?.(...args);
      }
      onResponseStart(...args) {
        assert3(!this.#onCompleteCalled);
        assert3(!this.#onErrorCalled);
        assert3(!this.#onResponseStartCalled);
        this.#onResponseStartCalled = true;
        return this.#handler.onResponseStart?.(...args);
      }
      onResponseData(...args) {
        assert3(!this.#onCompleteCalled);
        assert3(!this.#onErrorCalled);
        return this.#handler.onResponseData?.(...args);
      }
      onResponseEnd(...args) {
        assert3(!this.#onCompleteCalled);
        assert3(!this.#onErrorCalled);
        this.#onCompleteCalled = true;
        return this.#handler.onResponseEnd?.(...args);
      }
      onResponseError(...args) {
        this.#onErrorCalled = true;
        return this.#handler.onResponseError?.(...args);
      }
      /**
       * @deprecated
       */
      onBodySent() {
      }
    };
  }
});

// node_modules/undici/lib/handler/redirect-handler.js
var require_redirect_handler = __commonJS({
  "node_modules/undici/lib/handler/redirect-handler.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var util4 = require_util();
    var { kBodyUsed } = require_symbols();
    var assert3 = __require("node:assert");
    var { InvalidArgumentError } = require_errors();
    var EE3 = __require("node:events");
    var redirectableStatusCodes = [300, 301, 302, 303, 307, 308];
    var kBody = Symbol("body");
    var noop6 = /* @__PURE__ */ __name(() => {
    }, "noop");
    var BodyAsyncIterable = class {
      static {
        __name(this, "BodyAsyncIterable");
      }
      constructor(body) {
        this[kBody] = body;
        this[kBodyUsed] = false;
      }
      async *[Symbol.asyncIterator]() {
        assert3(!this[kBodyUsed], "disturbed");
        this[kBodyUsed] = true;
        yield* this[kBody];
      }
    };
    var RedirectHandler = class _RedirectHandler {
      static {
        __name(this, "RedirectHandler");
      }
      static buildDispatch(dispatcher, maxRedirections) {
        if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
          throw new InvalidArgumentError("maxRedirections must be a positive number");
        }
        const dispatch = dispatcher.dispatch.bind(dispatcher);
        return (opts, originalHandler) => dispatch(opts, new _RedirectHandler(dispatch, maxRedirections, opts, originalHandler));
      }
      constructor(dispatch, maxRedirections, opts, handler) {
        if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
          throw new InvalidArgumentError("maxRedirections must be a positive number");
        }
        this.dispatch = dispatch;
        this.location = null;
        const { maxRedirections: _, ...cleanOpts } = opts;
        this.opts = cleanOpts;
        this.maxRedirections = maxRedirections;
        this.handler = handler;
        this.history = [];
        if (util4.isStream(this.opts.body)) {
          if (util4.bodyLength(this.opts.body) === 0) {
            this.opts.body.on("data", function() {
              assert3(false);
            });
          }
          if (typeof this.opts.body.readableDidRead !== "boolean") {
            this.opts.body[kBodyUsed] = false;
            EE3.prototype.on.call(this.opts.body, "data", function() {
              this[kBodyUsed] = true;
            });
          }
        } else if (this.opts.body && typeof this.opts.body.pipeTo === "function") {
          this.opts.body = new BodyAsyncIterable(this.opts.body);
        } else if (this.opts.body && typeof this.opts.body !== "string" && !ArrayBuffer.isView(this.opts.body) && util4.isIterable(this.opts.body) && !util4.isFormDataLike(this.opts.body)) {
          this.opts.body = new BodyAsyncIterable(this.opts.body);
        }
      }
      onRequestStart(controller, context2) {
        this.handler.onRequestStart?.(controller, { ...context2, history: this.history });
      }
      onRequestUpgrade(controller, statusCode, headers, socket) {
        this.handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
      }
      onResponseStart(controller, statusCode, headers, statusMessage) {
        if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) {
          throw new Error("max redirects");
        }
        if ((statusCode === 301 || statusCode === 302) && this.opts.method === "POST") {
          this.opts.method = "GET";
          if (util4.isStream(this.opts.body)) {
            util4.destroy(this.opts.body.on("error", noop6));
          }
          this.opts.body = null;
        }
        if (statusCode === 303 && this.opts.method !== "HEAD") {
          this.opts.method = "GET";
          if (util4.isStream(this.opts.body)) {
            util4.destroy(this.opts.body.on("error", noop6));
          }
          this.opts.body = null;
        }
        this.location = this.history.length >= this.maxRedirections || util4.isDisturbed(this.opts.body) || redirectableStatusCodes.indexOf(statusCode) === -1 ? null : headers.location;
        if (this.opts.origin) {
          this.history.push(new URL(this.opts.path, this.opts.origin));
        }
        if (!this.location) {
          this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
          return;
        }
        const { origin, pathname, search } = util4.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
        const path108 = search ? `${pathname}${search}` : pathname;
        const redirectUrlString = `${origin}${path108}`;
        for (const historyUrl of this.history) {
          if (historyUrl.toString() === redirectUrlString) {
            throw new InvalidArgumentError(`Redirect loop detected. Cannot redirect to ${origin}. This typically happens when using a Client or Pool with cross-origin redirects. Use an Agent for cross-origin redirects.`);
          }
        }
        this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
        this.opts.path = path108;
        this.opts.origin = origin;
        this.opts.query = null;
      }
      onResponseData(controller, chunk) {
        if (this.location) {
        } else {
          this.handler.onResponseData?.(controller, chunk);
        }
      }
      onResponseEnd(controller, trailers) {
        if (this.location) {
          this.dispatch(this.opts, this);
        } else {
          this.handler.onResponseEnd(controller, trailers);
        }
      }
      onResponseError(controller, error) {
        this.handler.onResponseError?.(controller, error);
      }
    };
    function shouldRemoveHeader(header, removeContent, unknownOrigin) {
      if (header.length === 4) {
        return util4.headerNameToString(header) === "host";
      }
      if (removeContent && util4.headerNameToString(header).startsWith("content-")) {
        return true;
      }
      if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {
        const name3 = util4.headerNameToString(header);
        return name3 === "authorization" || name3 === "cookie" || name3 === "proxy-authorization";
      }
      return false;
    }
    __name(shouldRemoveHeader, "shouldRemoveHeader");
    function cleanRequestHeaders(headers, removeContent, unknownOrigin) {
      const ret = [];
      if (Array.isArray(headers)) {
        for (let i = 0; i < headers.length; i += 2) {
          if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) {
            ret.push(headers[i], headers[i + 1]);
          }
        }
      } else if (headers && typeof headers === "object") {
        const entries = typeof headers[Symbol.iterator] === "function" ? headers : Object.entries(headers);
        for (const [key, value] of entries) {
          if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
            ret.push(key, value);
          }
        }
      } else {
        assert3(headers == null, "headers must be an object or an array");
      }
      return ret;
    }
    __name(cleanRequestHeaders, "cleanRequestHeaders");
    module2.exports = RedirectHandler;
  }
});

// node_modules/undici/lib/interceptor/redirect.js
var require_redirect = __commonJS({
  "node_modules/undici/lib/interceptor/redirect.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var RedirectHandler = require_redirect_handler();
    function createRedirectInterceptor({ maxRedirections: defaultMaxRedirections } = {}) {
      return (dispatch) => {
        return /* @__PURE__ */ __name(function Intercept(opts, handler) {
          const { maxRedirections = defaultMaxRedirections, ...rest } = opts;
          if (maxRedirections == null || maxRedirections === 0) {
            return dispatch(opts, handler);
          }
          const dispatchOpts = { ...rest };
          const redirectHandler = new RedirectHandler(dispatch, maxRedirections, dispatchOpts, handler);
          return dispatch(dispatchOpts, redirectHandler);
        }, "Intercept");
      };
    }
    __name(createRedirectInterceptor, "createRedirectInterceptor");
    module2.exports = createRedirectInterceptor;
  }
});

// node_modules/undici/lib/interceptor/response-error.js
var require_response_error = __commonJS({
  "node_modules/undici/lib/interceptor/response-error.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var DecoratorHandler = require_decorator_handler();
    var { ResponseError } = require_errors();
    var ResponseErrorHandler = class extends DecoratorHandler {
      static {
        __name(this, "ResponseErrorHandler");
      }
      #statusCode;
      #contentType;
      #decoder;
      #headers;
      #body;
      constructor(_opts, { handler }) {
        super(handler);
      }
      #checkContentType(contentType) {
        return (this.#contentType ?? "").indexOf(contentType) === 0;
      }
      onRequestStart(controller, context2) {
        this.#statusCode = 0;
        this.#contentType = null;
        this.#decoder = null;
        this.#headers = null;
        this.#body = "";
        return super.onRequestStart(controller, context2);
      }
      onResponseStart(controller, statusCode, headers, statusMessage) {
        this.#statusCode = statusCode;
        this.#headers = headers;
        this.#contentType = headers["content-type"];
        if (this.#statusCode < 400) {
          return super.onResponseStart(controller, statusCode, headers, statusMessage);
        }
        if (this.#checkContentType("application/json") || this.#checkContentType("text/plain")) {
          this.#decoder = new TextDecoder("utf-8");
        }
      }
      onResponseData(controller, chunk) {
        if (this.#statusCode < 400) {
          return super.onResponseData(controller, chunk);
        }
        this.#body += this.#decoder?.decode(chunk, { stream: true }) ?? "";
      }
      onResponseEnd(controller, trailers) {
        if (this.#statusCode >= 400) {
          this.#body += this.#decoder?.decode(void 0, { stream: false }) ?? "";
          if (this.#checkContentType("application/json")) {
            try {
              this.#body = JSON.parse(this.#body);
            } catch {
            }
          }
          let err;
          const stackTraceLimit = Error.stackTraceLimit;
          Error.stackTraceLimit = 0;
          try {
            err = new ResponseError("Response Error", this.#statusCode, {
              body: this.#body,
              headers: this.#headers
            });
          } finally {
            Error.stackTraceLimit = stackTraceLimit;
          }
          super.onResponseError(controller, err);
        } else {
          super.onResponseEnd(controller, trailers);
        }
      }
      onResponseError(controller, err) {
        super.onResponseError(controller, err);
      }
    };
    module2.exports = () => {
      return (dispatch) => {
        return /* @__PURE__ */ __name(function Intercept(opts, handler) {
          return dispatch(opts, new ResponseErrorHandler(opts, { handler }));
        }, "Intercept");
      };
    };
  }
});

// node_modules/undici/lib/interceptor/retry.js
var require_retry = __commonJS({
  "node_modules/undici/lib/interceptor/retry.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var RetryHandler = require_retry_handler();
    module2.exports = (globalOpts) => {
      return (dispatch) => {
        return /* @__PURE__ */ __name(function retryInterceptor(opts, handler) {
          return dispatch(
            opts,
            new RetryHandler(
              { ...opts, retryOptions: { ...globalOpts, ...opts.retryOptions } },
              {
                handler,
                dispatch
              }
            )
          );
        }, "retryInterceptor");
      };
    };
  }
});

// node_modules/undici/lib/interceptor/dump.js
var require_dump = __commonJS({
  "node_modules/undici/lib/interceptor/dump.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { InvalidArgumentError, RequestAbortedError } = require_errors();
    var DecoratorHandler = require_decorator_handler();
    var DumpHandler = class extends DecoratorHandler {
      static {
        __name(this, "DumpHandler");
      }
      #maxSize = 1024 * 1024;
      #dumped = false;
      #size = 0;
      #controller = null;
      aborted = false;
      reason = false;
      constructor({ maxSize, signal }, handler) {
        if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) {
          throw new InvalidArgumentError("maxSize must be a number greater than 0");
        }
        super(handler);
        this.#maxSize = maxSize ?? this.#maxSize;
      }
      #abort(reason) {
        this.aborted = true;
        this.reason = reason;
      }
      onRequestStart(controller, context2) {
        controller.abort = this.#abort.bind(this);
        this.#controller = controller;
        return super.onRequestStart(controller, context2);
      }
      onResponseStart(controller, statusCode, headers, statusMessage) {
        const contentLength = headers["content-length"];
        if (contentLength != null && contentLength > this.#maxSize) {
          throw new RequestAbortedError(
            `Response size (${contentLength}) larger than maxSize (${this.#maxSize})`
          );
        }
        if (this.aborted === true) {
          return true;
        }
        return super.onResponseStart(controller, statusCode, headers, statusMessage);
      }
      onResponseError(controller, err) {
        if (this.#dumped) {
          return;
        }
        err = this.#controller?.reason ?? err;
        super.onResponseError(controller, err);
      }
      onResponseData(controller, chunk) {
        this.#size = this.#size + chunk.length;
        if (this.#size >= this.#maxSize) {
          this.#dumped = true;
          if (this.aborted === true) {
            super.onResponseError(controller, this.reason);
          } else {
            super.onResponseEnd(controller, {});
          }
        }
        return true;
      }
      onResponseEnd(controller, trailers) {
        if (this.#dumped) {
          return;
        }
        if (this.#controller.aborted === true) {
          super.onResponseError(controller, this.reason);
          return;
        }
        super.onResponseEnd(controller, trailers);
      }
    };
    function createDumpInterceptor({ maxSize: defaultMaxSize } = {
      maxSize: 1024 * 1024
    }) {
      return (dispatch) => {
        return /* @__PURE__ */ __name(function Intercept(opts, handler) {
          const { dumpMaxSize = defaultMaxSize } = opts;
          const dumpHandler = new DumpHandler({ maxSize: dumpMaxSize, signal: opts.signal }, handler);
          return dispatch(opts, dumpHandler);
        }, "Intercept");
      };
    }
    __name(createDumpInterceptor, "createDumpInterceptor");
    module2.exports = createDumpInterceptor;
  }
});

// node_modules/undici/lib/interceptor/dns.js
var require_dns = __commonJS({
  "node_modules/undici/lib/interceptor/dns.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { isIP } = __require("node:net");
    var { lookup } = __require("node:dns");
    var DecoratorHandler = require_decorator_handler();
    var { InvalidArgumentError, InformationalError } = require_errors();
    var maxInt = Math.pow(2, 31) - 1;
    var DNSInstance = class {
      static {
        __name(this, "DNSInstance");
      }
      #maxTTL = 0;
      #maxItems = 0;
      #records = /* @__PURE__ */ new Map();
      dualStack = true;
      affinity = null;
      lookup = null;
      pick = null;
      constructor(opts) {
        this.#maxTTL = opts.maxTTL;
        this.#maxItems = opts.maxItems;
        this.dualStack = opts.dualStack;
        this.affinity = opts.affinity;
        this.lookup = opts.lookup ?? this.#defaultLookup;
        this.pick = opts.pick ?? this.#defaultPick;
      }
      get full() {
        return this.#records.size === this.#maxItems;
      }
      runLookup(origin, opts, cb) {
        const ips = this.#records.get(origin.hostname);
        if (ips == null && this.full) {
          cb(null, origin);
          return;
        }
        const newOpts = {
          affinity: this.affinity,
          dualStack: this.dualStack,
          lookup: this.lookup,
          pick: this.pick,
          ...opts.dns,
          maxTTL: this.#maxTTL,
          maxItems: this.#maxItems
        };
        if (ips == null) {
          this.lookup(origin, newOpts, (err, addresses) => {
            if (err || addresses == null || addresses.length === 0) {
              cb(err ?? new InformationalError("No DNS entries found"));
              return;
            }
            this.setRecords(origin, addresses);
            const records = this.#records.get(origin.hostname);
            const ip = this.pick(
              origin,
              records,
              newOpts.affinity
            );
            let port;
            if (typeof ip.port === "number") {
              port = `:${ip.port}`;
            } else if (origin.port !== "") {
              port = `:${origin.port}`;
            } else {
              port = "";
            }
            cb(
              null,
              new URL(`${origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`)
            );
          });
        } else {
          const ip = this.pick(
            origin,
            ips,
            newOpts.affinity
          );
          if (ip == null) {
            this.#records.delete(origin.hostname);
            this.runLookup(origin, opts, cb);
            return;
          }
          let port;
          if (typeof ip.port === "number") {
            port = `:${ip.port}`;
          } else if (origin.port !== "") {
            port = `:${origin.port}`;
          } else {
            port = "";
          }
          cb(
            null,
            new URL(`${origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`)
          );
        }
      }
      #defaultLookup(origin, opts, cb) {
        lookup(
          origin.hostname,
          {
            all: true,
            family: this.dualStack === false ? this.affinity : 0,
            order: "ipv4first"
          },
          (err, addresses) => {
            if (err) {
              return cb(err);
            }
            const results = /* @__PURE__ */ new Map();
            for (const addr of addresses) {
              results.set(`${addr.address}:${addr.family}`, addr);
            }
            cb(null, results.values());
          }
        );
      }
      #defaultPick(origin, hostnameRecords, affinity) {
        let ip = null;
        const { records, offset } = hostnameRecords;
        let family;
        if (this.dualStack) {
          if (affinity == null) {
            if (offset == null || offset === maxInt) {
              hostnameRecords.offset = 0;
              affinity = 4;
            } else {
              hostnameRecords.offset++;
              affinity = (hostnameRecords.offset & 1) === 1 ? 6 : 4;
            }
          }
          if (records[affinity] != null && records[affinity].ips.length > 0) {
            family = records[affinity];
          } else {
            family = records[affinity === 4 ? 6 : 4];
          }
        } else {
          family = records[affinity];
        }
        if (family == null || family.ips.length === 0) {
          return ip;
        }
        if (family.offset == null || family.offset === maxInt) {
          family.offset = 0;
        } else {
          family.offset++;
        }
        const position = family.offset % family.ips.length;
        ip = family.ips[position] ?? null;
        if (ip == null) {
          return ip;
        }
        if (Date.now() - ip.timestamp > ip.ttl) {
          family.ips.splice(position, 1);
          return this.pick(origin, hostnameRecords, affinity);
        }
        return ip;
      }
      pickFamily(origin, ipFamily) {
        const records = this.#records.get(origin.hostname)?.records;
        if (!records) {
          return null;
        }
        const family = records[ipFamily];
        if (!family) {
          return null;
        }
        if (family.offset == null || family.offset === maxInt) {
          family.offset = 0;
        } else {
          family.offset++;
        }
        const position = family.offset % family.ips.length;
        const ip = family.ips[position] ?? null;
        if (ip == null) {
          return ip;
        }
        if (Date.now() - ip.timestamp > ip.ttl) {
          family.ips.splice(position, 1);
        }
        return ip;
      }
      setRecords(origin, addresses) {
        const timestamp = Date.now();
        const records = { records: { 4: null, 6: null } };
        for (const record of addresses) {
          record.timestamp = timestamp;
          if (typeof record.ttl === "number") {
            record.ttl = Math.min(record.ttl, this.#maxTTL);
          } else {
            record.ttl = this.#maxTTL;
          }
          const familyRecords = records.records[record.family] ?? { ips: [] };
          familyRecords.ips.push(record);
          records.records[record.family] = familyRecords;
        }
        this.#records.set(origin.hostname, records);
      }
      deleteRecords(origin) {
        this.#records.delete(origin.hostname);
      }
      getHandler(meta, opts) {
        return new DNSDispatchHandler(this, meta, opts);
      }
    };
    var DNSDispatchHandler = class extends DecoratorHandler {
      static {
        __name(this, "DNSDispatchHandler");
      }
      #state = null;
      #opts = null;
      #dispatch = null;
      #origin = null;
      #controller = null;
      #newOrigin = null;
      #firstTry = true;
      constructor(state, { origin, handler, dispatch, newOrigin }, opts) {
        super(handler);
        this.#origin = origin;
        this.#newOrigin = newOrigin;
        this.#opts = { ...opts };
        this.#state = state;
        this.#dispatch = dispatch;
      }
      onResponseError(controller, err) {
        switch (err.code) {
          case "ETIMEDOUT":
          case "ECONNREFUSED": {
            if (this.#state.dualStack) {
              if (!this.#firstTry) {
                super.onResponseError(controller, err);
                return;
              }
              this.#firstTry = false;
              const otherFamily = this.#newOrigin.hostname[0] === "[" ? 4 : 6;
              const ip = this.#state.pickFamily(this.#origin, otherFamily);
              if (ip == null) {
                super.onResponseError(controller, err);
                return;
              }
              let port;
              if (typeof ip.port === "number") {
                port = `:${ip.port}`;
              } else if (this.#origin.port !== "") {
                port = `:${this.#origin.port}`;
              } else {
                port = "";
              }
              const dispatchOpts = {
                ...this.#opts,
                origin: `${this.#origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`
              };
              this.#dispatch(dispatchOpts, this);
              return;
            }
            super.onResponseError(controller, err);
            break;
          }
          case "ENOTFOUND":
            this.#state.deleteRecords(this.#origin);
            super.onResponseError(controller, err);
            break;
          default:
            super.onResponseError(controller, err);
            break;
        }
      }
    };
    module2.exports = (interceptorOpts) => {
      if (interceptorOpts?.maxTTL != null && (typeof interceptorOpts?.maxTTL !== "number" || interceptorOpts?.maxTTL < 0)) {
        throw new InvalidArgumentError("Invalid maxTTL. Must be a positive number");
      }
      if (interceptorOpts?.maxItems != null && (typeof interceptorOpts?.maxItems !== "number" || interceptorOpts?.maxItems < 1)) {
        throw new InvalidArgumentError(
          "Invalid maxItems. Must be a positive number and greater than zero"
        );
      }
      if (interceptorOpts?.affinity != null && interceptorOpts?.affinity !== 4 && interceptorOpts?.affinity !== 6) {
        throw new InvalidArgumentError("Invalid affinity. Must be either 4 or 6");
      }
      if (interceptorOpts?.dualStack != null && typeof interceptorOpts?.dualStack !== "boolean") {
        throw new InvalidArgumentError("Invalid dualStack. Must be a boolean");
      }
      if (interceptorOpts?.lookup != null && typeof interceptorOpts?.lookup !== "function") {
        throw new InvalidArgumentError("Invalid lookup. Must be a function");
      }
      if (interceptorOpts?.pick != null && typeof interceptorOpts?.pick !== "function") {
        throw new InvalidArgumentError("Invalid pick. Must be a function");
      }
      const dualStack = interceptorOpts?.dualStack ?? true;
      let affinity;
      if (dualStack) {
        affinity = interceptorOpts?.affinity ?? null;
      } else {
        affinity = interceptorOpts?.affinity ?? 4;
      }
      const opts = {
        maxTTL: interceptorOpts?.maxTTL ?? 1e4,
        // Expressed in ms
        lookup: interceptorOpts?.lookup ?? null,
        pick: interceptorOpts?.pick ?? null,
        dualStack,
        affinity,
        maxItems: interceptorOpts?.maxItems ?? Infinity
      };
      const instance = new DNSInstance(opts);
      return (dispatch) => {
        return /* @__PURE__ */ __name(function dnsInterceptor(origDispatchOpts, handler) {
          const origin = origDispatchOpts.origin.constructor === URL ? origDispatchOpts.origin : new URL(origDispatchOpts.origin);
          if (isIP(origin.hostname) !== 0) {
            return dispatch(origDispatchOpts, handler);
          }
          instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => {
            if (err) {
              return handler.onResponseError(null, err);
            }
            const dispatchOpts = {
              ...origDispatchOpts,
              servername: origin.hostname,
              // For SNI on TLS
              origin: newOrigin.origin,
              headers: {
                host: origin.host,
                ...origDispatchOpts.headers
              }
            };
            dispatch(
              dispatchOpts,
              instance.getHandler(
                { origin, dispatch, handler, newOrigin },
                origDispatchOpts
              )
            );
          });
          return true;
        }, "dnsInterceptor");
      };
    };
  }
});

// node_modules/undici/lib/util/cache.js
var require_cache = __commonJS({
  "node_modules/undici/lib/util/cache.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      safeHTTPMethods,
      pathHasQueryOrFragment
    } = require_util();
    var { serializePathWithQuery } = require_util();
    function makeCacheKey(opts) {
      if (!opts.origin) {
        throw new Error("opts.origin is undefined");
      }
      let fullPath = opts.path || "/";
      if (opts.query && !pathHasQueryOrFragment(opts.path)) {
        fullPath = serializePathWithQuery(fullPath, opts.query);
      }
      return {
        origin: opts.origin.toString(),
        method: opts.method,
        path: fullPath,
        headers: opts.headers
      };
    }
    __name(makeCacheKey, "makeCacheKey");
    function normalizeHeaders(opts) {
      let headers;
      if (opts.headers == null) {
        headers = {};
      } else if (typeof opts.headers[Symbol.iterator] === "function") {
        headers = {};
        for (const x of opts.headers) {
          if (!Array.isArray(x)) {
            throw new Error("opts.headers is not a valid header map");
          }
          const [key, val] = x;
          if (typeof key !== "string" || typeof val !== "string") {
            throw new Error("opts.headers is not a valid header map");
          }
          headers[key.toLowerCase()] = val;
        }
      } else if (typeof opts.headers === "object") {
        headers = {};
        for (const key of Object.keys(opts.headers)) {
          headers[key.toLowerCase()] = opts.headers[key];
        }
      } else {
        throw new Error("opts.headers is not an object");
      }
      return headers;
    }
    __name(normalizeHeaders, "normalizeHeaders");
    function assertCacheKey(key) {
      if (typeof key !== "object") {
        throw new TypeError(`expected key to be object, got ${typeof key}`);
      }
      for (const property of ["origin", "method", "path"]) {
        if (typeof key[property] !== "string") {
          throw new TypeError(`expected key.${property} to be string, got ${typeof key[property]}`);
        }
      }
      if (key.headers !== void 0 && typeof key.headers !== "object") {
        throw new TypeError(`expected headers to be object, got ${typeof key}`);
      }
    }
    __name(assertCacheKey, "assertCacheKey");
    function assertCacheValue(value) {
      if (typeof value !== "object") {
        throw new TypeError(`expected value to be object, got ${typeof value}`);
      }
      for (const property of ["statusCode", "cachedAt", "staleAt", "deleteAt"]) {
        if (typeof value[property] !== "number") {
          throw new TypeError(`expected value.${property} to be number, got ${typeof value[property]}`);
        }
      }
      if (typeof value.statusMessage !== "string") {
        throw new TypeError(`expected value.statusMessage to be string, got ${typeof value.statusMessage}`);
      }
      if (value.headers != null && typeof value.headers !== "object") {
        throw new TypeError(`expected value.rawHeaders to be object, got ${typeof value.headers}`);
      }
      if (value.vary !== void 0 && typeof value.vary !== "object") {
        throw new TypeError(`expected value.vary to be object, got ${typeof value.vary}`);
      }
      if (value.etag !== void 0 && typeof value.etag !== "string") {
        throw new TypeError(`expected value.etag to be string, got ${typeof value.etag}`);
      }
    }
    __name(assertCacheValue, "assertCacheValue");
    function parseCacheControlHeader(header) {
      const output = {};
      let directives;
      if (Array.isArray(header)) {
        directives = [];
        for (const directive of header) {
          directives.push(...directive.split(","));
        }
      } else {
        directives = header.split(",");
      }
      for (let i = 0; i < directives.length; i++) {
        const directive = directives[i].toLowerCase();
        const keyValueDelimiter = directive.indexOf("=");
        let key;
        let value;
        if (keyValueDelimiter !== -1) {
          key = directive.substring(0, keyValueDelimiter).trimStart();
          value = directive.substring(keyValueDelimiter + 1);
        } else {
          key = directive.trim();
        }
        switch (key) {
          case "min-fresh":
          case "max-stale":
          case "max-age":
          case "s-maxage":
          case "stale-while-revalidate":
          case "stale-if-error": {
            if (value === void 0 || value[0] === " ") {
              continue;
            }
            if (value.length >= 2 && value[0] === '"' && value[value.length - 1] === '"') {
              value = value.substring(1, value.length - 1);
            }
            const parsedValue = parseInt(value, 10);
            if (parsedValue !== parsedValue) {
              continue;
            }
            if (key === "max-age" && key in output && output[key] >= parsedValue) {
              continue;
            }
            output[key] = parsedValue;
            break;
          }
          case "private":
          case "no-cache": {
            if (value) {
              if (value[0] === '"') {
                const headers = [value.substring(1)];
                let foundEndingQuote = value[value.length - 1] === '"';
                if (!foundEndingQuote) {
                  for (let j = i + 1; j < directives.length; j++) {
                    const nextPart = directives[j];
                    const nextPartLength = nextPart.length;
                    headers.push(nextPart.trim());
                    if (nextPartLength !== 0 && nextPart[nextPartLength - 1] === '"') {
                      foundEndingQuote = true;
                      break;
                    }
                  }
                }
                if (foundEndingQuote) {
                  let lastHeader = headers[headers.length - 1];
                  if (lastHeader[lastHeader.length - 1] === '"') {
                    lastHeader = lastHeader.substring(0, lastHeader.length - 1);
                    headers[headers.length - 1] = lastHeader;
                  }
                  if (key in output) {
                    output[key] = output[key].concat(headers);
                  } else {
                    output[key] = headers;
                  }
                }
              } else {
                if (key in output) {
                  output[key] = output[key].concat(value);
                } else {
                  output[key] = [value];
                }
              }
              break;
            }
          }
          // eslint-disable-next-line no-fallthrough
          case "public":
          case "no-store":
          case "must-revalidate":
          case "proxy-revalidate":
          case "immutable":
          case "no-transform":
          case "must-understand":
          case "only-if-cached":
            if (value) {
              continue;
            }
            output[key] = true;
            break;
          default:
            continue;
        }
      }
      return output;
    }
    __name(parseCacheControlHeader, "parseCacheControlHeader");
    function parseVaryHeader(varyHeader, headers) {
      if (typeof varyHeader === "string" && varyHeader.includes("*")) {
        return headers;
      }
      const output = (
        /** @type {Record<string, string | string[] | null>} */
        {}
      );
      const varyingHeaders = typeof varyHeader === "string" ? varyHeader.split(",") : varyHeader;
      for (const header of varyingHeaders) {
        const trimmedHeader = header.trim().toLowerCase();
        output[trimmedHeader] = headers[trimmedHeader] ?? null;
      }
      return output;
    }
    __name(parseVaryHeader, "parseVaryHeader");
    function isEtagUsable(etag) {
      if (etag.length <= 2) {
        return false;
      }
      if (etag[0] === '"' && etag[etag.length - 1] === '"') {
        return !(etag[1] === '"' || etag.startsWith('"W/'));
      }
      if (etag.startsWith('W/"') && etag[etag.length - 1] === '"') {
        return etag.length !== 4;
      }
      return false;
    }
    __name(isEtagUsable, "isEtagUsable");
    function assertCacheStore(store, name3 = "CacheStore") {
      if (typeof store !== "object" || store === null) {
        throw new TypeError(`expected type of ${name3} to be a CacheStore, got ${store === null ? "null" : typeof store}`);
      }
      for (const fn of ["get", "createWriteStream", "delete"]) {
        if (typeof store[fn] !== "function") {
          throw new TypeError(`${name3} needs to have a \`${fn}()\` function`);
        }
      }
    }
    __name(assertCacheStore, "assertCacheStore");
    function assertCacheMethods(methods, name3 = "CacheMethods") {
      if (!Array.isArray(methods)) {
        throw new TypeError(`expected type of ${name3} needs to be an array, got ${methods === null ? "null" : typeof methods}`);
      }
      if (methods.length === 0) {
        throw new TypeError(`${name3} needs to have at least one method`);
      }
      for (const method of methods) {
        if (!safeHTTPMethods.includes(method)) {
          throw new TypeError(`element of ${name3}-array needs to be one of following values: ${safeHTTPMethods.join(", ")}, got ${method}`);
        }
      }
    }
    __name(assertCacheMethods, "assertCacheMethods");
    module2.exports = {
      makeCacheKey,
      normalizeHeaders,
      assertCacheKey,
      assertCacheValue,
      parseCacheControlHeader,
      parseVaryHeader,
      isEtagUsable,
      assertCacheMethods,
      assertCacheStore
    };
  }
});

// node_modules/undici/lib/util/date.js
var require_date = __commonJS({
  "node_modules/undici/lib/util/date.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var IMF_DAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
    var IMF_SPACES = [4, 7, 11, 16, 25];
    var IMF_MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
    var IMF_COLONS = [19, 22];
    var ASCTIME_SPACES = [3, 7, 10, 19];
    var RFC850_DAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
    function parseHttpDate(date, now) {
      date = date.toLowerCase();
      switch (date[3]) {
        case ",":
          return parseImfDate(date);
        case " ":
          return parseAscTimeDate(date);
        default:
          return parseRfc850Date(date, now);
      }
    }
    __name(parseHttpDate, "parseHttpDate");
    function parseImfDate(date) {
      if (date.length !== 29) {
        return void 0;
      }
      if (!date.endsWith("gmt")) {
        return void 0;
      }
      for (const spaceInx of IMF_SPACES) {
        if (date[spaceInx] !== " ") {
          return void 0;
        }
      }
      for (const colonIdx of IMF_COLONS) {
        if (date[colonIdx] !== ":") {
          return void 0;
        }
      }
      const dayName = date.substring(0, 3);
      if (!IMF_DAYS.includes(dayName)) {
        return void 0;
      }
      const dayString = date.substring(5, 7);
      const day = Number.parseInt(dayString);
      if (isNaN(day) || day < 10 && dayString[0] !== "0") {
        return void 0;
      }
      const month = date.substring(8, 11);
      const monthIdx = IMF_MONTHS.indexOf(month);
      if (monthIdx === -1) {
        return void 0;
      }
      const year = Number.parseInt(date.substring(12, 16));
      if (isNaN(year)) {
        return void 0;
      }
      const hourString = date.substring(17, 19);
      const hour = Number.parseInt(hourString);
      if (isNaN(hour) || hour < 10 && hourString[0] !== "0") {
        return void 0;
      }
      const minuteString = date.substring(20, 22);
      const minute = Number.parseInt(minuteString);
      if (isNaN(minute) || minute < 10 && minuteString[0] !== "0") {
        return void 0;
      }
      const secondString = date.substring(23, 25);
      const second = Number.parseInt(secondString);
      if (isNaN(second) || second < 10 && secondString[0] !== "0") {
        return void 0;
      }
      return new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
    }
    __name(parseImfDate, "parseImfDate");
    function parseAscTimeDate(date) {
      if (date.length !== 24) {
        return void 0;
      }
      for (const spaceIdx of ASCTIME_SPACES) {
        if (date[spaceIdx] !== " ") {
          return void 0;
        }
      }
      const dayName = date.substring(0, 3);
      if (!IMF_DAYS.includes(dayName)) {
        return void 0;
      }
      const month = date.substring(4, 7);
      const monthIdx = IMF_MONTHS.indexOf(month);
      if (monthIdx === -1) {
        return void 0;
      }
      const dayString = date.substring(8, 10);
      const day = Number.parseInt(dayString);
      if (isNaN(day) || day < 10 && dayString[0] !== " ") {
        return void 0;
      }
      const hourString = date.substring(11, 13);
      const hour = Number.parseInt(hourString);
      if (isNaN(hour) || hour < 10 && hourString[0] !== "0") {
        return void 0;
      }
      const minuteString = date.substring(14, 16);
      const minute = Number.parseInt(minuteString);
      if (isNaN(minute) || minute < 10 && minuteString[0] !== "0") {
        return void 0;
      }
      const secondString = date.substring(17, 19);
      const second = Number.parseInt(secondString);
      if (isNaN(second) || second < 10 && secondString[0] !== "0") {
        return void 0;
      }
      const year = Number.parseInt(date.substring(20, 24));
      if (isNaN(year)) {
        return void 0;
      }
      return new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
    }
    __name(parseAscTimeDate, "parseAscTimeDate");
    function parseRfc850Date(date, now = /* @__PURE__ */ new Date()) {
      if (!date.endsWith("gmt")) {
        return void 0;
      }
      const commaIndex = date.indexOf(",");
      if (commaIndex === -1) {
        return void 0;
      }
      if (date.length - commaIndex - 1 !== 23) {
        return void 0;
      }
      const dayName = date.substring(0, commaIndex);
      if (!RFC850_DAYS.includes(dayName)) {
        return void 0;
      }
      if (date[commaIndex + 1] !== " " || date[commaIndex + 4] !== "-" || date[commaIndex + 8] !== "-" || date[commaIndex + 11] !== " " || date[commaIndex + 14] !== ":" || date[commaIndex + 17] !== ":" || date[commaIndex + 20] !== " ") {
        return void 0;
      }
      const dayString = date.substring(commaIndex + 2, commaIndex + 4);
      const day = Number.parseInt(dayString);
      if (isNaN(day) || day < 10 && dayString[0] !== "0") {
        return void 0;
      }
      const month = date.substring(commaIndex + 5, commaIndex + 8);
      const monthIdx = IMF_MONTHS.indexOf(month);
      if (monthIdx === -1) {
        return void 0;
      }
      let year = Number.parseInt(date.substring(commaIndex + 9, commaIndex + 11));
      if (isNaN(year)) {
        return void 0;
      }
      const currentYear = now.getUTCFullYear();
      const currentDecade = currentYear % 100;
      const currentCentury = Math.floor(currentYear / 100);
      if (year > currentDecade && year - currentDecade >= 50) {
        year += (currentCentury - 1) * 100;
      } else {
        year += currentCentury * 100;
      }
      const hourString = date.substring(commaIndex + 12, commaIndex + 14);
      const hour = Number.parseInt(hourString);
      if (isNaN(hour) || hour < 10 && hourString[0] !== "0") {
        return void 0;
      }
      const minuteString = date.substring(commaIndex + 15, commaIndex + 17);
      const minute = Number.parseInt(minuteString);
      if (isNaN(minute) || minute < 10 && minuteString[0] !== "0") {
        return void 0;
      }
      const secondString = date.substring(commaIndex + 18, commaIndex + 20);
      const second = Number.parseInt(secondString);
      if (isNaN(second) || second < 10 && secondString[0] !== "0") {
        return void 0;
      }
      return new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
    }
    __name(parseRfc850Date, "parseRfc850Date");
    module2.exports = {
      parseHttpDate
    };
  }
});

// node_modules/undici/lib/handler/cache-handler.js
var require_cache_handler = __commonJS({
  "node_modules/undici/lib/handler/cache-handler.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var util4 = require_util();
    var {
      parseCacheControlHeader,
      parseVaryHeader,
      isEtagUsable
    } = require_cache();
    var { parseHttpDate } = require_date();
    function noop6() {
    }
    __name(noop6, "noop");
    var HEURISTICALLY_CACHEABLE_STATUS_CODES = [
      200,
      203,
      204,
      206,
      300,
      301,
      308,
      404,
      405,
      410,
      414,
      501
    ];
    var NOT_UNDERSTOOD_STATUS_CODES = [
      206,
      304
    ];
    var MAX_RESPONSE_AGE = 2147483647e3;
    var CacheHandler = class {
      static {
        __name(this, "CacheHandler");
      }
      /**
       * @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
       */
      #cacheKey;
      /**
       * @type {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions['type']}
       */
      #cacheType;
      /**
       * @type {number | undefined}
       */
      #cacheByDefault;
      /**
       * @type {import('../../types/cache-interceptor.d.ts').default.CacheStore}
       */
      #store;
      /**
       * @type {import('../../types/dispatcher.d.ts').default.DispatchHandler}
       */
      #handler;
      /**
       * @type {import('node:stream').Writable | undefined}
       */
      #writeStream;
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} opts
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey
       * @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler
       */
      constructor({ store, type, cacheByDefault }, cacheKey, handler) {
        this.#store = store;
        this.#cacheType = type;
        this.#cacheByDefault = cacheByDefault;
        this.#cacheKey = cacheKey;
        this.#handler = handler;
      }
      onRequestStart(controller, context2) {
        this.#writeStream?.destroy();
        this.#writeStream = void 0;
        this.#handler.onRequestStart?.(controller, context2);
      }
      onRequestUpgrade(controller, statusCode, headers, socket) {
        this.#handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
      }
      /**
       * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
       * @param {number} statusCode
       * @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders
       * @param {string} statusMessage
       */
      onResponseStart(controller, statusCode, resHeaders, statusMessage) {
        const downstreamOnHeaders = /* @__PURE__ */ __name(() => this.#handler.onResponseStart?.(
          controller,
          statusCode,
          resHeaders,
          statusMessage
        ), "downstreamOnHeaders");
        if (!util4.safeHTTPMethods.includes(this.#cacheKey.method) && statusCode >= 200 && statusCode <= 399) {
          try {
            this.#store.delete(this.#cacheKey)?.catch?.(noop6);
          } catch {
          }
          return downstreamOnHeaders();
        }
        const cacheControlHeader = resHeaders["cache-control"];
        const heuristicallyCacheable = resHeaders["last-modified"] && HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode);
        if (!cacheControlHeader && !resHeaders["expires"] && !heuristicallyCacheable && !this.#cacheByDefault) {
          return downstreamOnHeaders();
        }
        const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {};
        if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives)) {
          return downstreamOnHeaders();
        }
        const now = Date.now();
        const resAge = resHeaders.age ? getAge(resHeaders.age) : void 0;
        if (resAge && resAge >= MAX_RESPONSE_AGE) {
          return downstreamOnHeaders();
        }
        const resDate = typeof resHeaders.date === "string" ? parseHttpDate(resHeaders.date) : void 0;
        const staleAt = determineStaleAt(this.#cacheType, now, resAge, resHeaders, resDate, cacheControlDirectives) ?? this.#cacheByDefault;
        if (staleAt === void 0 || resAge && resAge > staleAt) {
          return downstreamOnHeaders();
        }
        const baseTime = resDate ? resDate.getTime() : now;
        const absoluteStaleAt = staleAt + baseTime;
        if (now >= absoluteStaleAt) {
          return downstreamOnHeaders();
        }
        let varyDirectives;
        if (this.#cacheKey.headers && resHeaders.vary) {
          varyDirectives = parseVaryHeader(resHeaders.vary, this.#cacheKey.headers);
          if (!varyDirectives) {
            return downstreamOnHeaders();
          }
        }
        const deleteAt = determineDeleteAt(baseTime, cacheControlDirectives, absoluteStaleAt);
        const strippedHeaders = stripNecessaryHeaders(resHeaders, cacheControlDirectives);
        const value = {
          statusCode,
          statusMessage,
          headers: strippedHeaders,
          vary: varyDirectives,
          cacheControlDirectives,
          cachedAt: resAge ? now - resAge : now,
          staleAt: absoluteStaleAt,
          deleteAt
        };
        if (typeof resHeaders.etag === "string" && isEtagUsable(resHeaders.etag)) {
          value.etag = resHeaders.etag;
        }
        this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value);
        if (!this.#writeStream) {
          return downstreamOnHeaders();
        }
        const handler = this;
        this.#writeStream.on("drain", () => controller.resume()).on("error", function() {
          handler.#writeStream = void 0;
          handler.#store.delete(handler.#cacheKey);
        }).on("close", function() {
          if (handler.#writeStream === this) {
            handler.#writeStream = void 0;
          }
          controller.resume();
        });
        return downstreamOnHeaders();
      }
      onResponseData(controller, chunk) {
        if (this.#writeStream?.write(chunk) === false) {
          controller.pause();
        }
        this.#handler.onResponseData?.(controller, chunk);
      }
      onResponseEnd(controller, trailers) {
        this.#writeStream?.end();
        this.#handler.onResponseEnd?.(controller, trailers);
      }
      onResponseError(controller, err) {
        this.#writeStream?.destroy(err);
        this.#writeStream = void 0;
        this.#handler.onResponseError?.(controller, err);
      }
    };
    function canCacheResponse(cacheType, statusCode, resHeaders, cacheControlDirectives) {
      if (statusCode < 200 || NOT_UNDERSTOOD_STATUS_CODES.includes(statusCode)) {
        return false;
      }
      if (!HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode) && !resHeaders["expires"] && !cacheControlDirectives.public && cacheControlDirectives["max-age"] === void 0 && // RFC 9111: a private response directive, if the cache is not shared
      !(cacheControlDirectives.private && cacheType === "private") && !(cacheControlDirectives["s-maxage"] !== void 0 && cacheType === "shared")) {
        return false;
      }
      if (cacheControlDirectives["no-store"]) {
        return false;
      }
      if (cacheType === "shared" && cacheControlDirectives.private === true) {
        return false;
      }
      if (resHeaders.vary?.includes("*")) {
        return false;
      }
      if (resHeaders.authorization) {
        if (!cacheControlDirectives.public || typeof resHeaders.authorization !== "string") {
          return false;
        }
        if (Array.isArray(cacheControlDirectives["no-cache"]) && cacheControlDirectives["no-cache"].includes("authorization")) {
          return false;
        }
        if (Array.isArray(cacheControlDirectives["private"]) && cacheControlDirectives["private"].includes("authorization")) {
          return false;
        }
      }
      return true;
    }
    __name(canCacheResponse, "canCacheResponse");
    function getAge(ageHeader) {
      const age = parseInt(Array.isArray(ageHeader) ? ageHeader[0] : ageHeader);
      return isNaN(age) ? void 0 : age * 1e3;
    }
    __name(getAge, "getAge");
    function determineStaleAt(cacheType, now, age, resHeaders, responseDate, cacheControlDirectives) {
      if (cacheType === "shared") {
        const sMaxAge = cacheControlDirectives["s-maxage"];
        if (sMaxAge !== void 0) {
          return sMaxAge > 0 ? sMaxAge * 1e3 : void 0;
        }
      }
      const maxAge = cacheControlDirectives["max-age"];
      if (maxAge !== void 0) {
        return maxAge > 0 ? maxAge * 1e3 : void 0;
      }
      if (typeof resHeaders.expires === "string") {
        const expiresDate = parseHttpDate(resHeaders.expires);
        if (expiresDate) {
          if (now >= expiresDate.getTime()) {
            return void 0;
          }
          if (responseDate) {
            if (responseDate >= expiresDate) {
              return void 0;
            }
            if (age !== void 0 && age > expiresDate - responseDate) {
              return void 0;
            }
          }
          return expiresDate.getTime() - now;
        }
      }
      if (typeof resHeaders["last-modified"] === "string") {
        const lastModified = new Date(resHeaders["last-modified"]);
        if (isValidDate(lastModified)) {
          if (lastModified.getTime() >= now) {
            return void 0;
          }
          const responseAge = now - lastModified.getTime();
          return responseAge * 0.1;
        }
      }
      if (cacheControlDirectives.immutable) {
        return 31536e3;
      }
      return void 0;
    }
    __name(determineStaleAt, "determineStaleAt");
    function determineDeleteAt(now, cacheControlDirectives, staleAt) {
      let staleWhileRevalidate = -Infinity;
      let staleIfError = -Infinity;
      let immutable = -Infinity;
      if (cacheControlDirectives["stale-while-revalidate"]) {
        staleWhileRevalidate = staleAt + cacheControlDirectives["stale-while-revalidate"] * 1e3;
      }
      if (cacheControlDirectives["stale-if-error"]) {
        staleIfError = staleAt + cacheControlDirectives["stale-if-error"] * 1e3;
      }
      if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity) {
        immutable = now + 31536e6;
      }
      return Math.max(staleAt, staleWhileRevalidate, staleIfError, immutable);
    }
    __name(determineDeleteAt, "determineDeleteAt");
    function stripNecessaryHeaders(resHeaders, cacheControlDirectives) {
      const headersToRemove = [
        "connection",
        "proxy-authenticate",
        "proxy-authentication-info",
        "proxy-authorization",
        "proxy-connection",
        "te",
        "transfer-encoding",
        "upgrade",
        // We'll add age back when serving it
        "age"
      ];
      if (resHeaders["connection"]) {
        if (Array.isArray(resHeaders["connection"])) {
          headersToRemove.push(...resHeaders["connection"].map((header) => header.trim()));
        } else {
          headersToRemove.push(...resHeaders["connection"].split(",").map((header) => header.trim()));
        }
      }
      if (Array.isArray(cacheControlDirectives["no-cache"])) {
        headersToRemove.push(...cacheControlDirectives["no-cache"]);
      }
      if (Array.isArray(cacheControlDirectives["private"])) {
        headersToRemove.push(...cacheControlDirectives["private"]);
      }
      let strippedHeaders;
      for (const headerName of headersToRemove) {
        if (resHeaders[headerName]) {
          strippedHeaders ??= { ...resHeaders };
          delete strippedHeaders[headerName];
        }
      }
      return strippedHeaders ?? resHeaders;
    }
    __name(stripNecessaryHeaders, "stripNecessaryHeaders");
    function isValidDate(date) {
      return date instanceof Date && Number.isFinite(date.valueOf());
    }
    __name(isValidDate, "isValidDate");
    module2.exports = CacheHandler;
  }
});

// node_modules/undici/lib/cache/memory-cache-store.js
var require_memory_cache_store = __commonJS({
  "node_modules/undici/lib/cache/memory-cache-store.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Writable: Writable3 } = __require("node:stream");
    var { EventEmitter: EventEmitter10 } = __require("node:events");
    var { assertCacheKey, assertCacheValue } = require_cache();
    var MemoryCacheStore = class extends EventEmitter10 {
      static {
        __name(this, "MemoryCacheStore");
      }
      #maxCount = 1024;
      #maxSize = 104857600;
      // 100MB
      #maxEntrySize = 5242880;
      // 5MB
      #size = 0;
      #count = 0;
      #entries = /* @__PURE__ */ new Map();
      #hasEmittedMaxSizeEvent = false;
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.MemoryCacheStoreOpts | undefined} [opts]
       */
      constructor(opts) {
        super();
        if (opts) {
          if (typeof opts !== "object") {
            throw new TypeError("MemoryCacheStore options must be an object");
          }
          if (opts.maxCount !== void 0) {
            if (typeof opts.maxCount !== "number" || !Number.isInteger(opts.maxCount) || opts.maxCount < 0) {
              throw new TypeError("MemoryCacheStore options.maxCount must be a non-negative integer");
            }
            this.#maxCount = opts.maxCount;
          }
          if (opts.maxSize !== void 0) {
            if (typeof opts.maxSize !== "number" || !Number.isInteger(opts.maxSize) || opts.maxSize < 0) {
              throw new TypeError("MemoryCacheStore options.maxSize must be a non-negative integer");
            }
            this.#maxSize = opts.maxSize;
          }
          if (opts.maxEntrySize !== void 0) {
            if (typeof opts.maxEntrySize !== "number" || !Number.isInteger(opts.maxEntrySize) || opts.maxEntrySize < 0) {
              throw new TypeError("MemoryCacheStore options.maxEntrySize must be a non-negative integer");
            }
            this.#maxEntrySize = opts.maxEntrySize;
          }
        }
      }
      /**
       * Get the current size of the cache in bytes
       * @returns {number} The current size of the cache in bytes
       */
      get size() {
        return this.#size;
      }
      /**
       * Check if the cache is full (either max size or max count reached)
       * @returns {boolean} True if the cache is full, false otherwise
       */
      isFull() {
        return this.#size >= this.#maxSize || this.#count >= this.#maxCount;
      }
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} req
       * @returns {import('../../types/cache-interceptor.d.ts').default.GetResult | undefined}
       */
      get(key) {
        assertCacheKey(key);
        const topLevelKey = `${key.origin}:${key.path}`;
        const now = Date.now();
        const entries = this.#entries.get(topLevelKey);
        const entry = entries ? findEntry(key, entries, now) : null;
        return entry == null ? void 0 : {
          statusMessage: entry.statusMessage,
          statusCode: entry.statusCode,
          headers: entry.headers,
          body: entry.body,
          vary: entry.vary ? entry.vary : void 0,
          etag: entry.etag,
          cacheControlDirectives: entry.cacheControlDirectives,
          cachedAt: entry.cachedAt,
          staleAt: entry.staleAt,
          deleteAt: entry.deleteAt
        };
      }
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} val
       * @returns {Writable | undefined}
       */
      createWriteStream(key, val) {
        assertCacheKey(key);
        assertCacheValue(val);
        const topLevelKey = `${key.origin}:${key.path}`;
        const store = this;
        const entry = { ...key, ...val, body: [], size: 0 };
        return new Writable3({
          write(chunk, encoding, callback) {
            if (typeof chunk === "string") {
              chunk = Buffer.from(chunk, encoding);
            }
            entry.size += chunk.byteLength;
            if (entry.size >= store.#maxEntrySize) {
              this.destroy();
            } else {
              entry.body.push(chunk);
            }
            callback(null);
          },
          final(callback) {
            let entries = store.#entries.get(topLevelKey);
            if (!entries) {
              entries = [];
              store.#entries.set(topLevelKey, entries);
            }
            const previousEntry = findEntry(key, entries, Date.now());
            if (previousEntry) {
              const index = entries.indexOf(previousEntry);
              entries.splice(index, 1, entry);
              store.#size -= previousEntry.size;
            } else {
              entries.push(entry);
              store.#count += 1;
            }
            store.#size += entry.size;
            if (store.#size > store.#maxSize || store.#count > store.#maxCount) {
              if (!store.#hasEmittedMaxSizeEvent) {
                store.emit("maxSizeExceeded", {
                  size: store.#size,
                  maxSize: store.#maxSize,
                  count: store.#count,
                  maxCount: store.#maxCount
                });
                store.#hasEmittedMaxSizeEvent = true;
              }
              for (const [key2, entries2] of store.#entries) {
                for (const entry2 of entries2.splice(0, entries2.length / 2)) {
                  store.#size -= entry2.size;
                  store.#count -= 1;
                }
                if (entries2.length === 0) {
                  store.#entries.delete(key2);
                }
              }
              if (store.#size < store.#maxSize && store.#count < store.#maxCount) {
                store.#hasEmittedMaxSizeEvent = false;
              }
            }
            callback(null);
          }
        });
      }
      /**
       * @param {CacheKey} key
       */
      delete(key) {
        if (typeof key !== "object") {
          throw new TypeError(`expected key to be object, got ${typeof key}`);
        }
        const topLevelKey = `${key.origin}:${key.path}`;
        for (const entry of this.#entries.get(topLevelKey) ?? []) {
          this.#size -= entry.size;
          this.#count -= 1;
        }
        this.#entries.delete(topLevelKey);
      }
    };
    function findEntry(key, entries, now) {
      return entries.find((entry) => entry.deleteAt > now && entry.method === key.method && (entry.vary == null || Object.keys(entry.vary).every((headerName) => {
        if (entry.vary[headerName] === null) {
          return key.headers[headerName] === void 0;
        }
        return entry.vary[headerName] === key.headers[headerName];
      })));
    }
    __name(findEntry, "findEntry");
    module2.exports = MemoryCacheStore;
  }
});

// node_modules/undici/lib/handler/cache-revalidation-handler.js
var require_cache_revalidation_handler = __commonJS({
  "node_modules/undici/lib/handler/cache-revalidation-handler.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert3 = __require("node:assert");
    var CacheRevalidationHandler = class {
      static {
        __name(this, "CacheRevalidationHandler");
      }
      #successful = false;
      /**
       * @type {((boolean, any) => void) | null}
       */
      #callback;
      /**
       * @type {(import('../../types/dispatcher.d.ts').default.DispatchHandler)}
       */
      #handler;
      #context;
      /**
       * @type {boolean}
       */
      #allowErrorStatusCodes;
      /**
       * @param {(boolean) => void} callback Function to call if the cached value is valid
       * @param {import('../../types/dispatcher.d.ts').default.DispatchHandlers} handler
       * @param {boolean} allowErrorStatusCodes
       */
      constructor(callback, handler, allowErrorStatusCodes) {
        if (typeof callback !== "function") {
          throw new TypeError("callback must be a function");
        }
        this.#callback = callback;
        this.#handler = handler;
        this.#allowErrorStatusCodes = allowErrorStatusCodes;
      }
      onRequestStart(_, context2) {
        this.#successful = false;
        this.#context = context2;
      }
      onRequestUpgrade(controller, statusCode, headers, socket) {
        this.#handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
      }
      onResponseStart(controller, statusCode, headers, statusMessage) {
        assert3(this.#callback != null);
        this.#successful = statusCode === 304 || this.#allowErrorStatusCodes && statusCode >= 500 && statusCode <= 504;
        this.#callback(this.#successful, this.#context);
        this.#callback = null;
        if (this.#successful) {
          return true;
        }
        this.#handler.onRequestStart?.(controller, this.#context);
        this.#handler.onResponseStart?.(
          controller,
          statusCode,
          headers,
          statusMessage
        );
      }
      onResponseData(controller, chunk) {
        if (this.#successful) {
          return;
        }
        return this.#handler.onResponseData?.(controller, chunk);
      }
      onResponseEnd(controller, trailers) {
        if (this.#successful) {
          return;
        }
        this.#handler.onResponseEnd?.(controller, trailers);
      }
      onResponseError(controller, err) {
        if (this.#successful) {
          return;
        }
        if (this.#callback) {
          this.#callback(false);
          this.#callback = null;
        }
        if (typeof this.#handler.onResponseError === "function") {
          this.#handler.onResponseError(controller, err);
        } else {
          throw err;
        }
      }
    };
    module2.exports = CacheRevalidationHandler;
  }
});

// node_modules/undici/lib/interceptor/cache.js
var require_cache2 = __commonJS({
  "node_modules/undici/lib/interceptor/cache.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert3 = __require("node:assert");
    var { Readable: Readable4 } = __require("node:stream");
    var util4 = require_util();
    var CacheHandler = require_cache_handler();
    var MemoryCacheStore = require_memory_cache_store();
    var CacheRevalidationHandler = require_cache_revalidation_handler();
    var { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader } = require_cache();
    var { AbortError: AbortError2 } = require_errors();
    function needsRevalidation(result, cacheControlDirectives) {
      if (cacheControlDirectives?.["no-cache"]) {
        return true;
      }
      if (result.cacheControlDirectives?.["no-cache"] && !Array.isArray(result.cacheControlDirectives["no-cache"])) {
        return true;
      }
      const now = Date.now();
      if (now > result.staleAt) {
        if (cacheControlDirectives?.["max-stale"]) {
          const gracePeriod = result.staleAt + cacheControlDirectives["max-stale"] * 1e3;
          return now > gracePeriod;
        }
        return true;
      }
      if (cacheControlDirectives?.["min-fresh"]) {
        const timeLeftTillStale = result.staleAt - now;
        const threshold = cacheControlDirectives["min-fresh"] * 1e3;
        return timeLeftTillStale <= threshold;
      }
      return false;
    }
    __name(needsRevalidation, "needsRevalidation");
    function handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl) {
      if (reqCacheControl?.["only-if-cached"]) {
        let aborted = false;
        try {
          if (typeof handler.onConnect === "function") {
            handler.onConnect(() => {
              aborted = true;
            });
            if (aborted) {
              return;
            }
          }
          if (typeof handler.onHeaders === "function") {
            handler.onHeaders(504, [], () => {
            }, "Gateway Timeout");
            if (aborted) {
              return;
            }
          }
          if (typeof handler.onComplete === "function") {
            handler.onComplete([]);
          }
        } catch (err) {
          if (typeof handler.onError === "function") {
            handler.onError(err);
          }
        }
        return true;
      }
      return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
    }
    __name(handleUncachedResponse, "handleUncachedResponse");
    function sendCachedValue(handler, opts, result, age, context2, isStale) {
      const stream2 = util4.isStream(result.body) ? result.body : Readable4.from(result.body ?? []);
      assert3(!stream2.destroyed, "stream should not be destroyed");
      assert3(!stream2.readableDidRead, "stream should not be readableDidRead");
      const controller = {
        resume() {
          stream2.resume();
        },
        pause() {
          stream2.pause();
        },
        get paused() {
          return stream2.isPaused();
        },
        get aborted() {
          return stream2.destroyed;
        },
        get reason() {
          return stream2.errored;
        },
        abort(reason) {
          stream2.destroy(reason ?? new AbortError2());
        }
      };
      stream2.on("error", function(err) {
        if (!this.readableEnded) {
          if (typeof handler.onResponseError === "function") {
            handler.onResponseError(controller, err);
          } else {
            throw err;
          }
        }
      }).on("close", function() {
        if (!this.errored) {
          handler.onResponseEnd?.(controller, {});
        }
      });
      handler.onRequestStart?.(controller, context2);
      if (stream2.destroyed) {
        return;
      }
      const headers = { ...result.headers, age: String(age) };
      if (isStale) {
        headers.warning = '110 - "response is stale"';
      }
      handler.onResponseStart?.(controller, result.statusCode, headers, result.statusMessage);
      if (opts.method === "HEAD") {
        stream2.destroy();
      } else {
        stream2.on("data", function(chunk) {
          handler.onResponseData?.(controller, chunk);
        });
      }
    }
    __name(sendCachedValue, "sendCachedValue");
    function handleResult2(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl, result) {
      if (!result) {
        return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl);
      }
      const now = Date.now();
      if (now > result.deleteAt) {
        return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
      }
      const age = Math.round((now - result.cachedAt) / 1e3);
      if (reqCacheControl?.["max-age"] && age >= reqCacheControl["max-age"]) {
        return dispatch(opts, handler);
      }
      if (needsRevalidation(result, reqCacheControl)) {
        if (util4.isStream(opts.body) && util4.bodyLength(opts.body) !== 0) {
          return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
        }
        let withinStaleIfErrorThreshold = false;
        const staleIfErrorExpiry = result.cacheControlDirectives["stale-if-error"] ?? reqCacheControl?.["stale-if-error"];
        if (staleIfErrorExpiry) {
          withinStaleIfErrorThreshold = now < result.staleAt + staleIfErrorExpiry * 1e3;
        }
        let headers = {
          ...opts.headers,
          "if-modified-since": new Date(result.cachedAt).toUTCString()
        };
        if (result.etag) {
          headers["if-none-match"] = result.etag;
        }
        if (result.vary) {
          headers = {
            ...headers,
            ...result.vary
          };
        }
        return dispatch(
          {
            ...opts,
            headers
          },
          new CacheRevalidationHandler(
            (success, context2) => {
              if (success) {
                sendCachedValue(handler, opts, result, age, context2, true);
              } else if (util4.isStream(result.body)) {
                result.body.on("error", () => {
                }).destroy();
              }
            },
            new CacheHandler(globalOpts, cacheKey, handler),
            withinStaleIfErrorThreshold
          )
        );
      }
      if (util4.isStream(opts.body)) {
        opts.body.on("error", () => {
        }).destroy();
      }
      sendCachedValue(handler, opts, result, age, null, false);
    }
    __name(handleResult2, "handleResult");
    module2.exports = (opts = {}) => {
      const {
        store = new MemoryCacheStore(),
        methods = ["GET"],
        cacheByDefault = void 0,
        type = "shared"
      } = opts;
      if (typeof opts !== "object" || opts === null) {
        throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? "null" : typeof opts}`);
      }
      assertCacheStore(store, "opts.store");
      assertCacheMethods(methods, "opts.methods");
      if (typeof cacheByDefault !== "undefined" && typeof cacheByDefault !== "number") {
        throw new TypeError(`expected opts.cacheByDefault to be number or undefined, got ${typeof cacheByDefault}`);
      }
      if (typeof type !== "undefined" && type !== "shared" && type !== "private") {
        throw new TypeError(`expected opts.type to be shared, private, or undefined, got ${typeof type}`);
      }
      const globalOpts = {
        store,
        methods,
        cacheByDefault,
        type
      };
      const safeMethodsToNotCache = util4.safeHTTPMethods.filter((method) => methods.includes(method) === false);
      return (dispatch) => {
        return (opts2, handler) => {
          if (!opts2.origin || safeMethodsToNotCache.includes(opts2.method)) {
            return dispatch(opts2, handler);
          }
          opts2 = {
            ...opts2,
            headers: normalizeHeaders(opts2)
          };
          const reqCacheControl = opts2.headers?.["cache-control"] ? parseCacheControlHeader(opts2.headers["cache-control"]) : void 0;
          if (reqCacheControl?.["no-store"]) {
            return dispatch(opts2, handler);
          }
          const cacheKey = makeCacheKey(opts2);
          const result = store.get(cacheKey);
          if (result && typeof result.then === "function") {
            result.then((result2) => {
              handleResult2(
                dispatch,
                globalOpts,
                cacheKey,
                handler,
                opts2,
                reqCacheControl,
                result2
              );
            });
          } else {
            handleResult2(
              dispatch,
              globalOpts,
              cacheKey,
              handler,
              opts2,
              reqCacheControl,
              result
            );
          }
          return true;
        };
      };
    };
  }
});

// node_modules/undici/lib/interceptor/decompress.js
var require_decompress = __commonJS({
  "node_modules/undici/lib/interceptor/decompress.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress } = __require("node:zlib");
    var { pipeline } = __require("node:stream");
    var DecoratorHandler = require_decorator_handler();
    var supportedEncodings = {
      gzip: createGunzip,
      "x-gzip": createGunzip,
      br: createBrotliDecompress,
      deflate: createInflate,
      compress: createInflate,
      "x-compress": createInflate,
      ...createZstdDecompress ? { zstd: createZstdDecompress } : {}
    };
    var defaultSkipStatusCodes = (
      /** @type {const} */
      [204, 304]
    );
    var warningEmitted = (
      /** @type {boolean} */
      false
    );
    var DecompressHandler = class extends DecoratorHandler {
      static {
        __name(this, "DecompressHandler");
      }
      /** @type {Transform[]} */
      #decompressors = [];
      /** @type {NodeJS.WritableStream&NodeJS.ReadableStream|null} */
      #pipelineStream;
      /** @type {Readonly<number[]>} */
      #skipStatusCodes;
      /** @type {boolean} */
      #skipErrorResponses;
      constructor(handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true } = {}) {
        super(handler);
        this.#skipStatusCodes = skipStatusCodes;
        this.#skipErrorResponses = skipErrorResponses;
      }
      /**
       * Determines if decompression should be skipped based on encoding and status code
       * @param {string} contentEncoding - Content-Encoding header value
       * @param {number} statusCode - HTTP status code of the response
       * @returns {boolean} - True if decompression should be skipped
       */
      #shouldSkipDecompression(contentEncoding, statusCode) {
        if (!contentEncoding || statusCode < 200) return true;
        if (this.#skipStatusCodes.includes(statusCode)) return true;
        if (this.#skipErrorResponses && statusCode >= 400) return true;
        return false;
      }
      /**
       * Creates a chain of decompressors for multiple content encodings
       *
       * @param {string} encodings - Comma-separated list of content encodings
       * @returns {Array<DecompressorStream>} - Array of decompressor streams
       */
      #createDecompressionChain(encodings) {
        const parts = encodings.split(",");
        const decompressors = [];
        for (let i = parts.length - 1; i >= 0; i--) {
          const encoding = parts[i].trim();
          if (!encoding) continue;
          if (!supportedEncodings[encoding]) {
            decompressors.length = 0;
            return decompressors;
          }
          decompressors.push(supportedEncodings[encoding]());
        }
        return decompressors;
      }
      /**
       * Sets up event handlers for a decompressor stream using readable events
       * @param {DecompressorStream} decompressor - The decompressor stream
       * @param {Controller} controller - The controller to coordinate with
       * @returns {void}
       */
      #setupDecompressorEvents(decompressor, controller) {
        decompressor.on("readable", () => {
          let chunk;
          while ((chunk = decompressor.read()) !== null) {
            const result = super.onResponseData(controller, chunk);
            if (result === false) {
              break;
            }
          }
        });
        decompressor.on("error", (error) => {
          super.onResponseError(controller, error);
        });
      }
      /**
       * Sets up event handling for a single decompressor
       * @param {Controller} controller - The controller to handle events
       * @returns {void}
       */
      #setupSingleDecompressor(controller) {
        const decompressor = this.#decompressors[0];
        this.#setupDecompressorEvents(decompressor, controller);
        decompressor.on("end", () => {
          super.onResponseEnd(controller, {});
        });
      }
      /**
       * Sets up event handling for multiple chained decompressors using pipeline
       * @param {Controller} controller - The controller to handle events
       * @returns {void}
       */
      #setupMultipleDecompressors(controller) {
        const lastDecompressor = this.#decompressors[this.#decompressors.length - 1];
        this.#setupDecompressorEvents(lastDecompressor, controller);
        this.#pipelineStream = pipeline(this.#decompressors, (err) => {
          if (err) {
            super.onResponseError(controller, err);
            return;
          }
          super.onResponseEnd(controller, {});
        });
      }
      /**
       * Cleans up decompressor references to prevent memory leaks
       * @returns {void}
       */
      #cleanupDecompressors() {
        this.#decompressors.length = 0;
        this.#pipelineStream = null;
      }
      /**
       * @param {Controller} controller
       * @param {number} statusCode
       * @param {Record<string, string | string[] | undefined>} headers
       * @param {string} statusMessage
       * @returns {void}
       */
      onResponseStart(controller, statusCode, headers, statusMessage) {
        const contentEncoding = headers["content-encoding"];
        if (this.#shouldSkipDecompression(contentEncoding, statusCode)) {
          return super.onResponseStart(controller, statusCode, headers, statusMessage);
        }
        const decompressors = this.#createDecompressionChain(contentEncoding.toLowerCase());
        if (decompressors.length === 0) {
          this.#cleanupDecompressors();
          return super.onResponseStart(controller, statusCode, headers, statusMessage);
        }
        this.#decompressors = decompressors;
        const { "content-encoding": _, "content-length": __, ...newHeaders } = headers;
        if (this.#decompressors.length === 1) {
          this.#setupSingleDecompressor(controller);
        } else {
          this.#setupMultipleDecompressors(controller);
        }
        super.onResponseStart(controller, statusCode, newHeaders, statusMessage);
      }
      /**
       * @param {Controller} controller
       * @param {Buffer} chunk
       * @returns {void}
       */
      onResponseData(controller, chunk) {
        if (this.#decompressors.length > 0) {
          this.#decompressors[0].write(chunk);
          return;
        }
        super.onResponseData(controller, chunk);
      }
      /**
       * @param {Controller} controller
       * @param {Record<string, string | string[]> | undefined} trailers
       * @returns {void}
       */
      onResponseEnd(controller, trailers) {
        if (this.#decompressors.length > 0) {
          this.#decompressors[0].end();
          this.#cleanupDecompressors();
          return;
        }
        super.onResponseEnd(controller, trailers);
      }
      /**
       * @param {Controller} controller
       * @param {Error} err
       * @returns {void}
       */
      onResponseError(controller, err) {
        if (this.#decompressors.length > 0) {
          for (const decompressor of this.#decompressors) {
            decompressor.destroy(err);
          }
          this.#cleanupDecompressors();
        }
        super.onResponseError(controller, err);
      }
    };
    function createDecompressInterceptor(options2 = {}) {
      if (!warningEmitted) {
        process.emitWarning(
          "DecompressInterceptor is experimental and subject to change",
          "ExperimentalWarning"
        );
        warningEmitted = true;
      }
      return (dispatch) => {
        return (opts, handler) => {
          const decompressHandler = new DecompressHandler(handler, options2);
          return dispatch(opts, decompressHandler);
        };
      };
    }
    __name(createDecompressInterceptor, "createDecompressInterceptor");
    module2.exports = createDecompressInterceptor;
  }
});

// node_modules/undici/lib/cache/sqlite-cache-store.js
var require_sqlite_cache_store = __commonJS({
  "node_modules/undici/lib/cache/sqlite-cache-store.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Writable: Writable3 } = __require("node:stream");
    var { assertCacheKey, assertCacheValue } = require_cache();
    var DatabaseSync;
    var VERSION3 = 3;
    var MAX_ENTRY_SIZE = 2 * 1e3 * 1e3 * 1e3;
    module2.exports = class SqliteCacheStore {
      static {
        __name(this, "SqliteCacheStore");
      }
      #maxEntrySize = MAX_ENTRY_SIZE;
      #maxCount = Infinity;
      /**
       * @type {import('node:sqlite').DatabaseSync}
       */
      #db;
      /**
       * @type {import('node:sqlite').StatementSync}
       */
      #getValuesQuery;
      /**
       * @type {import('node:sqlite').StatementSync}
       */
      #updateValueQuery;
      /**
       * @type {import('node:sqlite').StatementSync}
       */
      #insertValueQuery;
      /**
       * @type {import('node:sqlite').StatementSync}
       */
      #deleteExpiredValuesQuery;
      /**
       * @type {import('node:sqlite').StatementSync}
       */
      #deleteByUrlQuery;
      /**
       * @type {import('node:sqlite').StatementSync}
       */
      #countEntriesQuery;
      /**
       * @type {import('node:sqlite').StatementSync | null}
       */
      #deleteOldValuesQuery;
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.SqliteCacheStoreOpts | undefined} opts
       */
      constructor(opts) {
        if (opts) {
          if (typeof opts !== "object") {
            throw new TypeError("SqliteCacheStore options must be an object");
          }
          if (opts.maxEntrySize !== void 0) {
            if (typeof opts.maxEntrySize !== "number" || !Number.isInteger(opts.maxEntrySize) || opts.maxEntrySize < 0) {
              throw new TypeError("SqliteCacheStore options.maxEntrySize must be a non-negative integer");
            }
            if (opts.maxEntrySize > MAX_ENTRY_SIZE) {
              throw new TypeError("SqliteCacheStore options.maxEntrySize must be less than 2gb");
            }
            this.#maxEntrySize = opts.maxEntrySize;
          }
          if (opts.maxCount !== void 0) {
            if (typeof opts.maxCount !== "number" || !Number.isInteger(opts.maxCount) || opts.maxCount < 0) {
              throw new TypeError("SqliteCacheStore options.maxCount must be a non-negative integer");
            }
            this.#maxCount = opts.maxCount;
          }
        }
        if (!DatabaseSync) {
          DatabaseSync = __require("node:sqlite").DatabaseSync;
        }
        this.#db = new DatabaseSync(opts?.location ?? ":memory:");
        this.#db.exec(`
      PRAGMA journal_mode = WAL;
      PRAGMA synchronous = NORMAL;
      PRAGMA temp_store = memory;
      PRAGMA optimize;

      CREATE TABLE IF NOT EXISTS cacheInterceptorV${VERSION3} (
        -- Data specific to us
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        url TEXT NOT NULL,
        method TEXT NOT NULL,

        -- Data returned to the interceptor
        body BUF NULL,
        deleteAt INTEGER NOT NULL,
        statusCode INTEGER NOT NULL,
        statusMessage TEXT NOT NULL,
        headers TEXT NULL,
        cacheControlDirectives TEXT NULL,
        etag TEXT NULL,
        vary TEXT NULL,
        cachedAt INTEGER NOT NULL,
        staleAt INTEGER NOT NULL
      );

      CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION3}_getValuesQuery ON cacheInterceptorV${VERSION3}(url, method, deleteAt);
      CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION3}_deleteByUrlQuery ON cacheInterceptorV${VERSION3}(deleteAt);
    `);
        this.#getValuesQuery = this.#db.prepare(`
      SELECT
        id,
        body,
        deleteAt,
        statusCode,
        statusMessage,
        headers,
        etag,
        cacheControlDirectives,
        vary,
        cachedAt,
        staleAt
      FROM cacheInterceptorV${VERSION3}
      WHERE
        url = ?
        AND method = ?
      ORDER BY
        deleteAt ASC
    `);
        this.#updateValueQuery = this.#db.prepare(`
      UPDATE cacheInterceptorV${VERSION3} SET
        body = ?,
        deleteAt = ?,
        statusCode = ?,
        statusMessage = ?,
        headers = ?,
        etag = ?,
        cacheControlDirectives = ?,
        cachedAt = ?,
        staleAt = ?
      WHERE
        id = ?
    `);
        this.#insertValueQuery = this.#db.prepare(`
      INSERT INTO cacheInterceptorV${VERSION3} (
        url,
        method,
        body,
        deleteAt,
        statusCode,
        statusMessage,
        headers,
        etag,
        cacheControlDirectives,
        vary,
        cachedAt,
        staleAt
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `);
        this.#deleteByUrlQuery = this.#db.prepare(
          `DELETE FROM cacheInterceptorV${VERSION3} WHERE url = ?`
        );
        this.#countEntriesQuery = this.#db.prepare(
          `SELECT COUNT(*) AS total FROM cacheInterceptorV${VERSION3}`
        );
        this.#deleteExpiredValuesQuery = this.#db.prepare(
          `DELETE FROM cacheInterceptorV${VERSION3} WHERE deleteAt <= ?`
        );
        this.#deleteOldValuesQuery = this.#maxCount === Infinity ? null : this.#db.prepare(`
        DELETE FROM cacheInterceptorV${VERSION3}
        WHERE id IN (
          SELECT
            id
          FROM cacheInterceptorV${VERSION3}
          ORDER BY cachedAt DESC
          LIMIT ?
        )
      `);
      }
      close() {
        this.#db.close();
      }
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
       * @returns {(import('../../types/cache-interceptor.d.ts').default.GetResult & { body?: Buffer }) | undefined}
       */
      get(key) {
        assertCacheKey(key);
        const value = this.#findValue(key);
        return value ? {
          body: value.body ? Buffer.from(value.body.buffer, value.body.byteOffset, value.body.byteLength) : void 0,
          statusCode: value.statusCode,
          statusMessage: value.statusMessage,
          headers: value.headers ? JSON.parse(value.headers) : void 0,
          etag: value.etag ? value.etag : void 0,
          vary: value.vary ? JSON.parse(value.vary) : void 0,
          cacheControlDirectives: value.cacheControlDirectives ? JSON.parse(value.cacheControlDirectives) : void 0,
          cachedAt: value.cachedAt,
          staleAt: value.staleAt,
          deleteAt: value.deleteAt
        } : void 0;
      }
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue & { body: null | Buffer | Array<Buffer>}} value
       */
      set(key, value) {
        assertCacheKey(key);
        const url2 = this.#makeValueUrl(key);
        const body = Array.isArray(value.body) ? Buffer.concat(value.body) : value.body;
        const size = body?.byteLength;
        if (size && size > this.#maxEntrySize) {
          return;
        }
        const existingValue = this.#findValue(key, true);
        if (existingValue) {
          this.#updateValueQuery.run(
            body,
            value.deleteAt,
            value.statusCode,
            value.statusMessage,
            value.headers ? JSON.stringify(value.headers) : null,
            value.etag ? value.etag : null,
            value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null,
            value.cachedAt,
            value.staleAt,
            existingValue.id
          );
        } else {
          this.#prune();
          this.#insertValueQuery.run(
            url2,
            key.method,
            body,
            value.deleteAt,
            value.statusCode,
            value.statusMessage,
            value.headers ? JSON.stringify(value.headers) : null,
            value.etag ? value.etag : null,
            value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null,
            value.vary ? JSON.stringify(value.vary) : null,
            value.cachedAt,
            value.staleAt
          );
        }
      }
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} value
       * @returns {Writable | undefined}
       */
      createWriteStream(key, value) {
        assertCacheKey(key);
        assertCacheValue(value);
        let size = 0;
        const body = [];
        const store = this;
        return new Writable3({
          decodeStrings: true,
          write(chunk, encoding, callback) {
            size += chunk.byteLength;
            if (size < store.#maxEntrySize) {
              body.push(chunk);
            } else {
              this.destroy();
            }
            callback();
          },
          final(callback) {
            store.set(key, { ...value, body });
            callback();
          }
        });
      }
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
       */
      delete(key) {
        if (typeof key !== "object") {
          throw new TypeError(`expected key to be object, got ${typeof key}`);
        }
        this.#deleteByUrlQuery.run(this.#makeValueUrl(key));
      }
      #prune() {
        if (Number.isFinite(this.#maxCount) && this.size <= this.#maxCount) {
          return 0;
        }
        {
          const removed = this.#deleteExpiredValuesQuery.run(Date.now()).changes;
          if (removed) {
            return removed;
          }
        }
        {
          const removed = this.#deleteOldValuesQuery?.run(Math.max(Math.floor(this.#maxCount * 0.1), 1)).changes;
          if (removed) {
            return removed;
          }
        }
        return 0;
      }
      /**
       * Counts the number of rows in the cache
       * @returns {Number}
       */
      get size() {
        const { total } = this.#countEntriesQuery.get();
        return total;
      }
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
       * @returns {string}
       */
      #makeValueUrl(key) {
        return `${key.origin}/${key.path}`;
      }
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
       * @param {boolean} [canBeExpired=false]
       * @returns {SqliteStoreValue | undefined}
       */
      #findValue(key, canBeExpired = false) {
        const url2 = this.#makeValueUrl(key);
        const { headers, method } = key;
        const values = this.#getValuesQuery.all(url2, method);
        if (values.length === 0) {
          return void 0;
        }
        const now = Date.now();
        for (const value of values) {
          if (now >= value.deleteAt && !canBeExpired) {
            return void 0;
          }
          let matches = true;
          if (value.vary) {
            const vary = JSON.parse(value.vary);
            for (const header in vary) {
              if (!headerValueEquals(headers[header], vary[header])) {
                matches = false;
                break;
              }
            }
          }
          if (matches) {
            return value;
          }
        }
        return void 0;
      }
    };
    function headerValueEquals(lhs, rhs) {
      if (lhs == null && rhs == null) {
        return true;
      }
      if (lhs == null && rhs != null || lhs != null && rhs == null) {
        return false;
      }
      if (Array.isArray(lhs) && Array.isArray(rhs)) {
        if (lhs.length !== rhs.length) {
          return false;
        }
        return lhs.every((x, i) => x === rhs[i]);
      }
      return lhs === rhs;
    }
    __name(headerValueEquals, "headerValueEquals");
  }
});

// node_modules/undici/lib/web/fetch/headers.js
var require_headers = __commonJS({
  "node_modules/undici/lib/web/fetch/headers.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { kConstruct } = require_symbols();
    var { kEnumerableProperty } = require_util();
    var {
      iteratorMixin,
      isValidHeaderName,
      isValidHeaderValue
    } = require_util2();
    var { webidl } = require_webidl();
    var assert3 = __require("node:assert");
    var util4 = __require("node:util");
    function isHTTPWhiteSpaceCharCode(code2) {
      return code2 === 10 || code2 === 13 || code2 === 9 || code2 === 32;
    }
    __name(isHTTPWhiteSpaceCharCode, "isHTTPWhiteSpaceCharCode");
    function headerValueNormalize(potentialValue) {
      let i = 0;
      let j = potentialValue.length;
      while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j;
      while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i;
      return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j);
    }
    __name(headerValueNormalize, "headerValueNormalize");
    function fill(headers, object) {
      if (Array.isArray(object)) {
        for (let i = 0; i < object.length; ++i) {
          const header = object[i];
          if (header.length !== 2) {
            throw webidl.errors.exception({
              header: "Headers constructor",
              message: `expected name/value pair to be length 2, found ${header.length}.`
            });
          }
          appendHeader(headers, header[0], header[1]);
        }
      } else if (typeof object === "object" && object !== null) {
        const keys = Object.keys(object);
        for (let i = 0; i < keys.length; ++i) {
          appendHeader(headers, keys[i], object[keys[i]]);
        }
      } else {
        throw webidl.errors.conversionFailed({
          prefix: "Headers constructor",
          argument: "Argument 1",
          types: ["sequence<sequence<ByteString>>", "record<ByteString, ByteString>"]
        });
      }
    }
    __name(fill, "fill");
    function appendHeader(headers, name3, value) {
      value = headerValueNormalize(value);
      if (!isValidHeaderName(name3)) {
        throw webidl.errors.invalidArgument({
          prefix: "Headers.append",
          value: name3,
          type: "header name"
        });
      } else if (!isValidHeaderValue(value)) {
        throw webidl.errors.invalidArgument({
          prefix: "Headers.append",
          value,
          type: "header value"
        });
      }
      if (getHeadersGuard(headers) === "immutable") {
        throw new TypeError("immutable");
      }
      return getHeadersList(headers).append(name3, value, false);
    }
    __name(appendHeader, "appendHeader");
    function headersListSortAndCombine(target) {
      const headersList = getHeadersList(target);
      if (!headersList) {
        return [];
      }
      if (headersList.sortedMap) {
        return headersList.sortedMap;
      }
      const headers = [];
      const names = headersList.toSortedArray();
      const cookies = headersList.cookies;
      if (cookies === null || cookies.length === 1) {
        return headersList.sortedMap = names;
      }
      for (let i = 0; i < names.length; ++i) {
        const { 0: name3, 1: value } = names[i];
        if (name3 === "set-cookie") {
          for (let j = 0; j < cookies.length; ++j) {
            headers.push([name3, cookies[j]]);
          }
        } else {
          headers.push([name3, value]);
        }
      }
      return headersList.sortedMap = headers;
    }
    __name(headersListSortAndCombine, "headersListSortAndCombine");
    function compareHeaderName(a, b) {
      return a[0] < b[0] ? -1 : 1;
    }
    __name(compareHeaderName, "compareHeaderName");
    var HeadersList = class _HeadersList {
      static {
        __name(this, "HeadersList");
      }
      /** @type {[string, string][]|null} */
      cookies = null;
      sortedMap;
      headersMap;
      constructor(init) {
        if (init instanceof _HeadersList) {
          this.headersMap = new Map(init.headersMap);
          this.sortedMap = init.sortedMap;
          this.cookies = init.cookies === null ? null : [...init.cookies];
        } else {
          this.headersMap = new Map(init);
          this.sortedMap = null;
        }
      }
      /**
       * @see https://fetch.spec.whatwg.org/#header-list-contains
       * @param {string} name
       * @param {boolean} isLowerCase
       */
      contains(name3, isLowerCase) {
        return this.headersMap.has(isLowerCase ? name3 : name3.toLowerCase());
      }
      clear() {
        this.headersMap.clear();
        this.sortedMap = null;
        this.cookies = null;
      }
      /**
       * @see https://fetch.spec.whatwg.org/#concept-header-list-append
       * @param {string} name
       * @param {string} value
       * @param {boolean} isLowerCase
       */
      append(name3, value, isLowerCase) {
        this.sortedMap = null;
        const lowercaseName = isLowerCase ? name3 : name3.toLowerCase();
        const exists2 = this.headersMap.get(lowercaseName);
        if (exists2) {
          const delimiter2 = lowercaseName === "cookie" ? "; " : ", ";
          this.headersMap.set(lowercaseName, {
            name: exists2.name,
            value: `${exists2.value}${delimiter2}${value}`
          });
        } else {
          this.headersMap.set(lowercaseName, { name: name3, value });
        }
        if (lowercaseName === "set-cookie") {
          (this.cookies ??= []).push(value);
        }
      }
      /**
       * @see https://fetch.spec.whatwg.org/#concept-header-list-set
       * @param {string} name
       * @param {string} value
       * @param {boolean} isLowerCase
       */
      set(name3, value, isLowerCase) {
        this.sortedMap = null;
        const lowercaseName = isLowerCase ? name3 : name3.toLowerCase();
        if (lowercaseName === "set-cookie") {
          this.cookies = [value];
        }
        this.headersMap.set(lowercaseName, { name: name3, value });
      }
      /**
       * @see https://fetch.spec.whatwg.org/#concept-header-list-delete
       * @param {string} name
       * @param {boolean} isLowerCase
       */
      delete(name3, isLowerCase) {
        this.sortedMap = null;
        if (!isLowerCase) name3 = name3.toLowerCase();
        if (name3 === "set-cookie") {
          this.cookies = null;
        }
        this.headersMap.delete(name3);
      }
      /**
       * @see https://fetch.spec.whatwg.org/#concept-header-list-get
       * @param {string} name
       * @param {boolean} isLowerCase
       * @returns {string | null}
       */
      get(name3, isLowerCase) {
        return this.headersMap.get(isLowerCase ? name3 : name3.toLowerCase())?.value ?? null;
      }
      *[Symbol.iterator]() {
        for (const { 0: name3, 1: { value } } of this.headersMap) {
          yield [name3, value];
        }
      }
      get entries() {
        const headers = {};
        if (this.headersMap.size !== 0) {
          for (const { name: name3, value } of this.headersMap.values()) {
            headers[name3] = value;
          }
        }
        return headers;
      }
      rawValues() {
        return this.headersMap.values();
      }
      get entriesList() {
        const headers = [];
        if (this.headersMap.size !== 0) {
          for (const { 0: lowerName, 1: { name: name3, value } } of this.headersMap) {
            if (lowerName === "set-cookie") {
              for (const cookie of this.cookies) {
                headers.push([name3, cookie]);
              }
            } else {
              headers.push([name3, value]);
            }
          }
        }
        return headers;
      }
      // https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-set
      toSortedArray() {
        const size = this.headersMap.size;
        const array = new Array(size);
        if (size <= 32) {
          if (size === 0) {
            return array;
          }
          const iterator = this.headersMap[Symbol.iterator]();
          const firstValue = iterator.next().value;
          array[0] = [firstValue[0], firstValue[1].value];
          assert3(firstValue[1].value !== null);
          for (let i = 1, j = 0, right3 = 0, left3 = 0, pivot = 0, x, value; i < size; ++i) {
            value = iterator.next().value;
            x = array[i] = [value[0], value[1].value];
            assert3(x[1] !== null);
            left3 = 0;
            right3 = i;
            while (left3 < right3) {
              pivot = left3 + (right3 - left3 >> 1);
              if (array[pivot][0] <= x[0]) {
                left3 = pivot + 1;
              } else {
                right3 = pivot;
              }
            }
            if (i !== pivot) {
              j = i;
              while (j > left3) {
                array[j] = array[--j];
              }
              array[left3] = x;
            }
          }
          if (!iterator.next().done) {
            throw new TypeError("Unreachable");
          }
          return array;
        } else {
          let i = 0;
          for (const { 0: name3, 1: { value } } of this.headersMap) {
            array[i++] = [name3, value];
            assert3(value !== null);
          }
          return array.sort(compareHeaderName);
        }
      }
    };
    var Headers2 = class _Headers {
      static {
        __name(this, "Headers");
      }
      #guard;
      /**
       * @type {HeadersList}
       */
      #headersList;
      /**
       * @param {HeadersInit|Symbol} [init]
       * @returns
       */
      constructor(init = void 0) {
        webidl.util.markAsUncloneable(this);
        if (init === kConstruct) {
          return;
        }
        this.#headersList = new HeadersList();
        this.#guard = "none";
        if (init !== void 0) {
          init = webidl.converters.HeadersInit(init, "Headers constructor", "init");
          fill(this, init);
        }
      }
      // https://fetch.spec.whatwg.org/#dom-headers-append
      append(name3, value) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 2, "Headers.append");
        const prefix = "Headers.append";
        name3 = webidl.converters.ByteString(name3, prefix, "name");
        value = webidl.converters.ByteString(value, prefix, "value");
        return appendHeader(this, name3, value);
      }
      // https://fetch.spec.whatwg.org/#dom-headers-delete
      delete(name3) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 1, "Headers.delete");
        const prefix = "Headers.delete";
        name3 = webidl.converters.ByteString(name3, prefix, "name");
        if (!isValidHeaderName(name3)) {
          throw webidl.errors.invalidArgument({
            prefix: "Headers.delete",
            value: name3,
            type: "header name"
          });
        }
        if (this.#guard === "immutable") {
          throw new TypeError("immutable");
        }
        if (!this.#headersList.contains(name3, false)) {
          return;
        }
        this.#headersList.delete(name3, false);
      }
      // https://fetch.spec.whatwg.org/#dom-headers-get
      get(name3) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 1, "Headers.get");
        const prefix = "Headers.get";
        name3 = webidl.converters.ByteString(name3, prefix, "name");
        if (!isValidHeaderName(name3)) {
          throw webidl.errors.invalidArgument({
            prefix,
            value: name3,
            type: "header name"
          });
        }
        return this.#headersList.get(name3, false);
      }
      // https://fetch.spec.whatwg.org/#dom-headers-has
      has(name3) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 1, "Headers.has");
        const prefix = "Headers.has";
        name3 = webidl.converters.ByteString(name3, prefix, "name");
        if (!isValidHeaderName(name3)) {
          throw webidl.errors.invalidArgument({
            prefix,
            value: name3,
            type: "header name"
          });
        }
        return this.#headersList.contains(name3, false);
      }
      // https://fetch.spec.whatwg.org/#dom-headers-set
      set(name3, value) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 2, "Headers.set");
        const prefix = "Headers.set";
        name3 = webidl.converters.ByteString(name3, prefix, "name");
        value = webidl.converters.ByteString(value, prefix, "value");
        value = headerValueNormalize(value);
        if (!isValidHeaderName(name3)) {
          throw webidl.errors.invalidArgument({
            prefix,
            value: name3,
            type: "header name"
          });
        } else if (!isValidHeaderValue(value)) {
          throw webidl.errors.invalidArgument({
            prefix,
            value,
            type: "header value"
          });
        }
        if (this.#guard === "immutable") {
          throw new TypeError("immutable");
        }
        this.#headersList.set(name3, value, false);
      }
      // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie
      getSetCookie() {
        webidl.brandCheck(this, _Headers);
        const list3 = this.#headersList.cookies;
        if (list3) {
          return [...list3];
        }
        return [];
      }
      [util4.inspect.custom](depth, options2) {
        options2.depth ??= depth;
        return `Headers ${util4.formatWithOptions(options2, this.#headersList.entries)}`;
      }
      static getHeadersGuard(o2) {
        return o2.#guard;
      }
      static setHeadersGuard(o2, guard) {
        o2.#guard = guard;
      }
      /**
       * @param {Headers} o
       */
      static getHeadersList(o2) {
        return o2.#headersList;
      }
      /**
       * @param {Headers} target
       * @param {HeadersList} list
       */
      static setHeadersList(target, list3) {
        target.#headersList = list3;
      }
    };
    var { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers2;
    Reflect.deleteProperty(Headers2, "getHeadersGuard");
    Reflect.deleteProperty(Headers2, "setHeadersGuard");
    Reflect.deleteProperty(Headers2, "getHeadersList");
    Reflect.deleteProperty(Headers2, "setHeadersList");
    iteratorMixin("Headers", Headers2, headersListSortAndCombine, 0, 1);
    Object.defineProperties(Headers2.prototype, {
      append: kEnumerableProperty,
      delete: kEnumerableProperty,
      get: kEnumerableProperty,
      has: kEnumerableProperty,
      set: kEnumerableProperty,
      getSetCookie: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "Headers",
        configurable: true
      },
      [util4.inspect.custom]: {
        enumerable: false
      }
    });
    webidl.converters.HeadersInit = function(V2, prefix, argument) {
      if (webidl.util.Type(V2) === webidl.util.Types.OBJECT) {
        const iterator = Reflect.get(V2, Symbol.iterator);
        if (!util4.types.isProxy(V2) && iterator === Headers2.prototype.entries) {
          try {
            return getHeadersList(V2).entriesList;
          } catch {
          }
        }
        if (typeof iterator === "function") {
          return webidl.converters["sequence<sequence<ByteString>>"](V2, prefix, argument, iterator.bind(V2));
        }
        return webidl.converters["record<ByteString, ByteString>"](V2, prefix, argument);
      }
      throw webidl.errors.conversionFailed({
        prefix: "Headers constructor",
        argument: "Argument 1",
        types: ["sequence<sequence<ByteString>>", "record<ByteString, ByteString>"]
      });
    };
    module2.exports = {
      fill,
      // for test.
      compareHeaderName,
      Headers: Headers2,
      HeadersList,
      getHeadersGuard,
      setHeadersGuard,
      setHeadersList,
      getHeadersList
    };
  }
});

// node_modules/undici/lib/web/fetch/response.js
var require_response = __commonJS({
  "node_modules/undici/lib/web/fetch/response.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Headers: Headers2, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = require_headers();
    var { extractBody, cloneBody, mixinBody, streamRegistry, bodyUnusable } = require_body();
    var util4 = require_util();
    var nodeUtil = __require("node:util");
    var { kEnumerableProperty } = util4;
    var {
      isValidReasonPhrase,
      isCancelled,
      isAborted: isAborted2,
      serializeJavascriptValueToJSONString,
      isErrorLike,
      isomorphicEncode,
      environmentSettingsObject: relevantRealm
    } = require_util2();
    var {
      redirectStatusSet,
      nullBodyStatus
    } = require_constants5();
    var { webidl } = require_webidl();
    var { URLSerializer } = require_data_url();
    var { kConstruct } = require_symbols();
    var assert3 = __require("node:assert");
    var { isArrayBuffer } = nodeUtil.types;
    var textEncoder = new TextEncoder("utf-8");
    var Response2 = class _Response {
      static {
        __name(this, "Response");
      }
      /** @type {Headers} */
      #headers;
      #state;
      // Creates network error Response.
      static error() {
        const responseObject = fromInnerResponse(makeNetworkError(), "immutable");
        return responseObject;
      }
      // https://fetch.spec.whatwg.org/#dom-response-json
      static json(data, init = void 0) {
        webidl.argumentLengthCheck(arguments, 1, "Response.json");
        if (init !== null) {
          init = webidl.converters.ResponseInit(init);
        }
        const bytes = textEncoder.encode(
          serializeJavascriptValueToJSONString(data)
        );
        const body = extractBody(bytes);
        const responseObject = fromInnerResponse(makeResponse({}), "response");
        initializeResponse(responseObject, init, { body: body[0], type: "application/json" });
        return responseObject;
      }
      // Creates a redirect Response that redirects to url with status status.
      static redirect(url2, status = 302) {
        webidl.argumentLengthCheck(arguments, 1, "Response.redirect");
        url2 = webidl.converters.USVString(url2);
        status = webidl.converters["unsigned short"](status);
        let parsedURL;
        try {
          parsedURL = new URL(url2, relevantRealm.settingsObject.baseUrl);
        } catch (err) {
          throw new TypeError(`Failed to parse URL from ${url2}`, { cause: err });
        }
        if (!redirectStatusSet.has(status)) {
          throw new RangeError(`Invalid status code ${status}`);
        }
        const responseObject = fromInnerResponse(makeResponse({}), "immutable");
        responseObject.#state.status = status;
        const value = isomorphicEncode(URLSerializer(parsedURL));
        responseObject.#state.headersList.append("location", value, true);
        return responseObject;
      }
      // https://fetch.spec.whatwg.org/#dom-response
      constructor(body = null, init = void 0) {
        webidl.util.markAsUncloneable(this);
        if (body === kConstruct) {
          return;
        }
        if (body !== null) {
          body = webidl.converters.BodyInit(body);
        }
        init = webidl.converters.ResponseInit(init);
        this.#state = makeResponse({});
        this.#headers = new Headers2(kConstruct);
        setHeadersGuard(this.#headers, "response");
        setHeadersList(this.#headers, this.#state.headersList);
        let bodyWithType = null;
        if (body != null) {
          const [extractedBody, type] = extractBody(body);
          bodyWithType = { body: extractedBody, type };
        }
        initializeResponse(this, init, bodyWithType);
      }
      // Returns response’s type, e.g., "cors".
      get type() {
        webidl.brandCheck(this, _Response);
        return this.#state.type;
      }
      // Returns response’s URL, if it has one; otherwise the empty string.
      get url() {
        webidl.brandCheck(this, _Response);
        const urlList = this.#state.urlList;
        const url2 = urlList[urlList.length - 1] ?? null;
        if (url2 === null) {
          return "";
        }
        return URLSerializer(url2, true);
      }
      // Returns whether response was obtained through a redirect.
      get redirected() {
        webidl.brandCheck(this, _Response);
        return this.#state.urlList.length > 1;
      }
      // Returns response’s status.
      get status() {
        webidl.brandCheck(this, _Response);
        return this.#state.status;
      }
      // Returns whether response’s status is an ok status.
      get ok() {
        webidl.brandCheck(this, _Response);
        return this.#state.status >= 200 && this.#state.status <= 299;
      }
      // Returns response’s status message.
      get statusText() {
        webidl.brandCheck(this, _Response);
        return this.#state.statusText;
      }
      // Returns response’s headers as Headers.
      get headers() {
        webidl.brandCheck(this, _Response);
        return this.#headers;
      }
      get body() {
        webidl.brandCheck(this, _Response);
        return this.#state.body ? this.#state.body.stream : null;
      }
      get bodyUsed() {
        webidl.brandCheck(this, _Response);
        return !!this.#state.body && util4.isDisturbed(this.#state.body.stream);
      }
      // Returns a clone of response.
      clone() {
        webidl.brandCheck(this, _Response);
        if (bodyUnusable(this.#state)) {
          throw webidl.errors.exception({
            header: "Response.clone",
            message: "Body has already been consumed."
          });
        }
        const clonedResponse = cloneResponse(this.#state);
        if (this.#state.body?.stream) {
          streamRegistry.register(this, new WeakRef(this.#state.body.stream));
        }
        return fromInnerResponse(clonedResponse, getHeadersGuard(this.#headers));
      }
      [nodeUtil.inspect.custom](depth, options2) {
        if (options2.depth === null) {
          options2.depth = 2;
        }
        options2.colors ??= true;
        const properties = {
          status: this.status,
          statusText: this.statusText,
          headers: this.headers,
          body: this.body,
          bodyUsed: this.bodyUsed,
          ok: this.ok,
          redirected: this.redirected,
          type: this.type,
          url: this.url
        };
        return `Response ${nodeUtil.formatWithOptions(options2, properties)}`;
      }
      /**
       * @param {Response} response
       */
      static getResponseHeaders(response) {
        return response.#headers;
      }
      /**
       * @param {Response} response
       * @param {Headers} newHeaders
       */
      static setResponseHeaders(response, newHeaders) {
        response.#headers = newHeaders;
      }
      /**
       * @param {Response} response
       */
      static getResponseState(response) {
        return response.#state;
      }
      /**
       * @param {Response} response
       * @param {any} newState
       */
      static setResponseState(response, newState) {
        response.#state = newState;
      }
    };
    var { getResponseHeaders, setResponseHeaders, getResponseState, setResponseState } = Response2;
    Reflect.deleteProperty(Response2, "getResponseHeaders");
    Reflect.deleteProperty(Response2, "setResponseHeaders");
    Reflect.deleteProperty(Response2, "getResponseState");
    Reflect.deleteProperty(Response2, "setResponseState");
    mixinBody(Response2, getResponseState);
    Object.defineProperties(Response2.prototype, {
      type: kEnumerableProperty,
      url: kEnumerableProperty,
      status: kEnumerableProperty,
      ok: kEnumerableProperty,
      redirected: kEnumerableProperty,
      statusText: kEnumerableProperty,
      headers: kEnumerableProperty,
      clone: kEnumerableProperty,
      body: kEnumerableProperty,
      bodyUsed: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "Response",
        configurable: true
      }
    });
    Object.defineProperties(Response2, {
      json: kEnumerableProperty,
      redirect: kEnumerableProperty,
      error: kEnumerableProperty
    });
    function cloneResponse(response) {
      if (response.internalResponse) {
        return filterResponse(
          cloneResponse(response.internalResponse),
          response.type
        );
      }
      const newResponse = makeResponse({ ...response, body: null });
      if (response.body != null) {
        newResponse.body = cloneBody(response.body);
      }
      return newResponse;
    }
    __name(cloneResponse, "cloneResponse");
    function makeResponse(init) {
      return {
        aborted: false,
        rangeRequested: false,
        timingAllowPassed: false,
        requestIncludesCredentials: false,
        type: "default",
        status: 200,
        timingInfo: null,
        cacheState: "",
        statusText: "",
        ...init,
        headersList: init?.headersList ? new HeadersList(init?.headersList) : new HeadersList(),
        urlList: init?.urlList ? [...init.urlList] : []
      };
    }
    __name(makeResponse, "makeResponse");
    function makeNetworkError(reason) {
      const isError = isErrorLike(reason);
      return makeResponse({
        type: "error",
        status: 0,
        error: isError ? reason : new Error(reason ? String(reason) : reason),
        aborted: reason && reason.name === "AbortError"
      });
    }
    __name(makeNetworkError, "makeNetworkError");
    function isNetworkError(response) {
      return (
        // A network error is a response whose type is "error",
        response.type === "error" && // status is 0
        response.status === 0
      );
    }
    __name(isNetworkError, "isNetworkError");
    function makeFilteredResponse(response, state) {
      state = {
        internalResponse: response,
        ...state
      };
      return new Proxy(response, {
        get(target, p) {
          return p in state ? state[p] : target[p];
        },
        set(target, p, value) {
          assert3(!(p in state));
          target[p] = value;
          return true;
        }
      });
    }
    __name(makeFilteredResponse, "makeFilteredResponse");
    function filterResponse(response, type) {
      if (type === "basic") {
        return makeFilteredResponse(response, {
          type: "basic",
          headersList: response.headersList
        });
      } else if (type === "cors") {
        return makeFilteredResponse(response, {
          type: "cors",
          headersList: response.headersList
        });
      } else if (type === "opaque") {
        return makeFilteredResponse(response, {
          type: "opaque",
          urlList: Object.freeze([]),
          status: 0,
          statusText: "",
          body: null
        });
      } else if (type === "opaqueredirect") {
        return makeFilteredResponse(response, {
          type: "opaqueredirect",
          status: 0,
          statusText: "",
          headersList: [],
          body: null
        });
      } else {
        assert3(false);
      }
    }
    __name(filterResponse, "filterResponse");
    function makeAppropriateNetworkError(fetchParams, err = null) {
      assert3(isCancelled(fetchParams));
      return isAborted2(fetchParams) ? makeNetworkError(Object.assign(new DOMException("The operation was aborted.", "AbortError"), { cause: err })) : makeNetworkError(Object.assign(new DOMException("Request was cancelled."), { cause: err }));
    }
    __name(makeAppropriateNetworkError, "makeAppropriateNetworkError");
    function initializeResponse(response, init, body) {
      if (init.status !== null && (init.status < 200 || init.status > 599)) {
        throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.');
      }
      if ("statusText" in init && init.statusText != null) {
        if (!isValidReasonPhrase(String(init.statusText))) {
          throw new TypeError("Invalid statusText");
        }
      }
      if ("status" in init && init.status != null) {
        getResponseState(response).status = init.status;
      }
      if ("statusText" in init && init.statusText != null) {
        getResponseState(response).statusText = init.statusText;
      }
      if ("headers" in init && init.headers != null) {
        fill(getResponseHeaders(response), init.headers);
      }
      if (body) {
        if (nullBodyStatus.includes(response.status)) {
          throw webidl.errors.exception({
            header: "Response constructor",
            message: `Invalid response status code ${response.status}`
          });
        }
        getResponseState(response).body = body.body;
        if (body.type != null && !getResponseState(response).headersList.contains("content-type", true)) {
          getResponseState(response).headersList.append("content-type", body.type, true);
        }
      }
    }
    __name(initializeResponse, "initializeResponse");
    function fromInnerResponse(innerResponse, guard) {
      const response = new Response2(kConstruct);
      setResponseState(response, innerResponse);
      const headers = new Headers2(kConstruct);
      setResponseHeaders(response, headers);
      setHeadersList(headers, innerResponse.headersList);
      setHeadersGuard(headers, guard);
      if (innerResponse.body?.stream) {
        streamRegistry.register(response, new WeakRef(innerResponse.body.stream));
      }
      return response;
    }
    __name(fromInnerResponse, "fromInnerResponse");
    webidl.converters.XMLHttpRequestBodyInit = function(V2, prefix, name3) {
      if (typeof V2 === "string") {
        return webidl.converters.USVString(V2, prefix, name3);
      }
      if (webidl.is.Blob(V2)) {
        return V2;
      }
      if (ArrayBuffer.isView(V2) || isArrayBuffer(V2)) {
        return V2;
      }
      if (webidl.is.FormData(V2)) {
        return V2;
      }
      if (webidl.is.URLSearchParams(V2)) {
        return V2;
      }
      return webidl.converters.DOMString(V2, prefix, name3);
    };
    webidl.converters.BodyInit = function(V2, prefix, argument) {
      if (webidl.is.ReadableStream(V2)) {
        return V2;
      }
      if (V2?.[Symbol.asyncIterator]) {
        return V2;
      }
      return webidl.converters.XMLHttpRequestBodyInit(V2, prefix, argument);
    };
    webidl.converters.ResponseInit = webidl.dictionaryConverter([
      {
        key: "status",
        converter: webidl.converters["unsigned short"],
        defaultValue: /* @__PURE__ */ __name(() => 200, "defaultValue")
      },
      {
        key: "statusText",
        converter: webidl.converters.ByteString,
        defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
      },
      {
        key: "headers",
        converter: webidl.converters.HeadersInit
      }
    ]);
    webidl.is.Response = webidl.util.MakeTypeAssertion(Response2);
    module2.exports = {
      isNetworkError,
      makeNetworkError,
      makeResponse,
      makeAppropriateNetworkError,
      filterResponse,
      Response: Response2,
      cloneResponse,
      fromInnerResponse,
      getResponseState
    };
  }
});

// node_modules/undici/lib/web/fetch/request.js
var require_request2 = __commonJS({
  "node_modules/undici/lib/web/fetch/request.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { extractBody, mixinBody, cloneBody, bodyUnusable } = require_body();
    var { Headers: Headers2, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = require_headers();
    var util4 = require_util();
    var nodeUtil = __require("node:util");
    var {
      isValidHTTPToken,
      sameOrigin,
      environmentSettingsObject
    } = require_util2();
    var {
      forbiddenMethodsSet,
      corsSafeListedMethodsSet,
      referrerPolicy,
      requestRedirect,
      requestMode,
      requestCredentials,
      requestCache,
      requestDuplex
    } = require_constants5();
    var { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util4;
    var { webidl } = require_webidl();
    var { URLSerializer } = require_data_url();
    var { kConstruct } = require_symbols();
    var assert3 = __require("node:assert");
    var { getMaxListeners, setMaxListeners, defaultMaxListeners } = __require("node:events");
    var kAbortController = Symbol("abortController");
    var requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {
      signal.removeEventListener("abort", abort);
    });
    var dependentControllerMap = /* @__PURE__ */ new WeakMap();
    var abortSignalHasEventHandlerLeakWarning;
    try {
      abortSignalHasEventHandlerLeakWarning = getMaxListeners(new AbortController().signal) > 0;
    } catch {
      abortSignalHasEventHandlerLeakWarning = false;
    }
    function buildAbort(acRef) {
      return abort;
      function abort() {
        const ac = acRef.deref();
        if (ac !== void 0) {
          requestFinalizer.unregister(abort);
          this.removeEventListener("abort", abort);
          ac.abort(this.reason);
          const controllerList = dependentControllerMap.get(ac.signal);
          if (controllerList !== void 0) {
            if (controllerList.size !== 0) {
              for (const ref of controllerList) {
                const ctrl = ref.deref();
                if (ctrl !== void 0) {
                  ctrl.abort(this.reason);
                }
              }
              controllerList.clear();
            }
            dependentControllerMap.delete(ac.signal);
          }
        }
      }
      __name(abort, "abort");
    }
    __name(buildAbort, "buildAbort");
    var patchMethodWarning = false;
    var Request2 = class _Request {
      static {
        __name(this, "Request");
      }
      /** @type {AbortSignal} */
      #signal;
      /** @type {import('../../dispatcher/dispatcher')} */
      #dispatcher;
      /** @type {Headers} */
      #headers;
      #state;
      // https://fetch.spec.whatwg.org/#dom-request
      constructor(input, init = void 0) {
        webidl.util.markAsUncloneable(this);
        if (input === kConstruct) {
          return;
        }
        const prefix = "Request constructor";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        input = webidl.converters.RequestInfo(input);
        init = webidl.converters.RequestInit(init);
        let request4 = null;
        let fallbackMode = null;
        const baseUrl = environmentSettingsObject.settingsObject.baseUrl;
        let signal = null;
        if (typeof input === "string") {
          this.#dispatcher = init.dispatcher;
          let parsedURL;
          try {
            parsedURL = new URL(input, baseUrl);
          } catch (err) {
            throw new TypeError("Failed to parse URL from " + input, { cause: err });
          }
          if (parsedURL.username || parsedURL.password) {
            throw new TypeError(
              "Request cannot be constructed from a URL that includes credentials: " + input
            );
          }
          request4 = makeRequest({ urlList: [parsedURL] });
          fallbackMode = "cors";
        } else {
          assert3(webidl.is.Request(input));
          request4 = input.#state;
          signal = input.#signal;
          this.#dispatcher = init.dispatcher || input.#dispatcher;
        }
        const origin = environmentSettingsObject.settingsObject.origin;
        let window2 = "client";
        if (request4.window?.constructor?.name === "EnvironmentSettingsObject" && sameOrigin(request4.window, origin)) {
          window2 = request4.window;
        }
        if (init.window != null) {
          throw new TypeError(`'window' option '${window2}' must be null`);
        }
        if ("window" in init) {
          window2 = "no-window";
        }
        request4 = makeRequest({
          // URL request’s URL.
          // undici implementation note: this is set as the first item in request's urlList in makeRequest
          // method request’s method.
          method: request4.method,
          // header list A copy of request’s header list.
          // undici implementation note: headersList is cloned in makeRequest
          headersList: request4.headersList,
          // unsafe-request flag Set.
          unsafeRequest: request4.unsafeRequest,
          // client This’s relevant settings object.
          client: environmentSettingsObject.settingsObject,
          // window window.
          window: window2,
          // priority request’s priority.
          priority: request4.priority,
          // origin request’s origin. The propagation of the origin is only significant for navigation requests
          // being handled by a service worker. In this scenario a request can have an origin that is different
          // from the current client.
          origin: request4.origin,
          // referrer request’s referrer.
          referrer: request4.referrer,
          // referrer policy request’s referrer policy.
          referrerPolicy: request4.referrerPolicy,
          // mode request’s mode.
          mode: request4.mode,
          // credentials mode request’s credentials mode.
          credentials: request4.credentials,
          // cache mode request’s cache mode.
          cache: request4.cache,
          // redirect mode request’s redirect mode.
          redirect: request4.redirect,
          // integrity metadata request’s integrity metadata.
          integrity: request4.integrity,
          // keepalive request’s keepalive.
          keepalive: request4.keepalive,
          // reload-navigation flag request’s reload-navigation flag.
          reloadNavigation: request4.reloadNavigation,
          // history-navigation flag request’s history-navigation flag.
          historyNavigation: request4.historyNavigation,
          // URL list A clone of request’s URL list.
          urlList: [...request4.urlList]
        });
        const initHasKey = Object.keys(init).length !== 0;
        if (initHasKey) {
          if (request4.mode === "navigate") {
            request4.mode = "same-origin";
          }
          request4.reloadNavigation = false;
          request4.historyNavigation = false;
          request4.origin = "client";
          request4.referrer = "client";
          request4.referrerPolicy = "";
          request4.url = request4.urlList[request4.urlList.length - 1];
          request4.urlList = [request4.url];
        }
        if (init.referrer !== void 0) {
          const referrer = init.referrer;
          if (referrer === "") {
            request4.referrer = "no-referrer";
          } else {
            let parsedReferrer;
            try {
              parsedReferrer = new URL(referrer, baseUrl);
            } catch (err) {
              throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err });
            }
            if (parsedReferrer.protocol === "about:" && parsedReferrer.hostname === "client" || origin && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl)) {
              request4.referrer = "client";
            } else {
              request4.referrer = parsedReferrer;
            }
          }
        }
        if (init.referrerPolicy !== void 0) {
          request4.referrerPolicy = init.referrerPolicy;
        }
        let mode;
        if (init.mode !== void 0) {
          mode = init.mode;
        } else {
          mode = fallbackMode;
        }
        if (mode === "navigate") {
          throw webidl.errors.exception({
            header: "Request constructor",
            message: "invalid request mode navigate."
          });
        }
        if (mode != null) {
          request4.mode = mode;
        }
        if (init.credentials !== void 0) {
          request4.credentials = init.credentials;
        }
        if (init.cache !== void 0) {
          request4.cache = init.cache;
        }
        if (request4.cache === "only-if-cached" && request4.mode !== "same-origin") {
          throw new TypeError(
            "'only-if-cached' can be set only with 'same-origin' mode"
          );
        }
        if (init.redirect !== void 0) {
          request4.redirect = init.redirect;
        }
        if (init.integrity != null) {
          request4.integrity = String(init.integrity);
        }
        if (init.keepalive !== void 0) {
          request4.keepalive = Boolean(init.keepalive);
        }
        if (init.method !== void 0) {
          let method = init.method;
          const mayBeNormalized = normalizedMethodRecords[method];
          if (mayBeNormalized !== void 0) {
            request4.method = mayBeNormalized;
          } else {
            if (!isValidHTTPToken(method)) {
              throw new TypeError(`'${method}' is not a valid HTTP method.`);
            }
            const upperCase = method.toUpperCase();
            if (forbiddenMethodsSet.has(upperCase)) {
              throw new TypeError(`'${method}' HTTP method is unsupported.`);
            }
            method = normalizedMethodRecordsBase[upperCase] ?? method;
            request4.method = method;
          }
          if (!patchMethodWarning && request4.method === "patch") {
            process.emitWarning("Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.", {
              code: "UNDICI-FETCH-patch"
            });
            patchMethodWarning = true;
          }
        }
        if (init.signal !== void 0) {
          signal = init.signal;
        }
        this.#state = request4;
        const ac = new AbortController();
        this.#signal = ac.signal;
        if (signal != null) {
          if (signal.aborted) {
            ac.abort(signal.reason);
          } else {
            this[kAbortController] = ac;
            const acRef = new WeakRef(ac);
            const abort = buildAbort(acRef);
            if (abortSignalHasEventHandlerLeakWarning && getMaxListeners(signal) === defaultMaxListeners) {
              setMaxListeners(1500, signal);
            }
            util4.addAbortListener(signal, abort);
            requestFinalizer.register(ac, { signal, abort }, abort);
          }
        }
        this.#headers = new Headers2(kConstruct);
        setHeadersList(this.#headers, request4.headersList);
        setHeadersGuard(this.#headers, "request");
        if (mode === "no-cors") {
          if (!corsSafeListedMethodsSet.has(request4.method)) {
            throw new TypeError(
              `'${request4.method} is unsupported in no-cors mode.`
            );
          }
          setHeadersGuard(this.#headers, "request-no-cors");
        }
        if (initHasKey) {
          const headersList = getHeadersList(this.#headers);
          const headers = init.headers !== void 0 ? init.headers : new HeadersList(headersList);
          headersList.clear();
          if (headers instanceof HeadersList) {
            for (const { name: name3, value } of headers.rawValues()) {
              headersList.append(name3, value, false);
            }
            headersList.cookies = headers.cookies;
          } else {
            fillHeaders(this.#headers, headers);
          }
        }
        const inputBody = webidl.is.Request(input) ? input.#state.body : null;
        if ((init.body != null || inputBody != null) && (request4.method === "GET" || request4.method === "HEAD")) {
          throw new TypeError("Request with GET/HEAD method cannot have body.");
        }
        let initBody = null;
        if (init.body != null) {
          const [extractedBody, contentType] = extractBody(
            init.body,
            request4.keepalive
          );
          initBody = extractedBody;
          if (contentType && !getHeadersList(this.#headers).contains("content-type", true)) {
            this.#headers.append("content-type", contentType, true);
          }
        }
        const inputOrInitBody = initBody ?? inputBody;
        if (inputOrInitBody != null && inputOrInitBody.source == null) {
          if (initBody != null && init.duplex == null) {
            throw new TypeError("RequestInit: duplex option is required when sending a body.");
          }
          if (request4.mode !== "same-origin" && request4.mode !== "cors") {
            throw new TypeError(
              'If request is made from ReadableStream, mode should be "same-origin" or "cors"'
            );
          }
          request4.useCORSPreflightFlag = true;
        }
        let finalBody = inputOrInitBody;
        if (initBody == null && inputBody != null) {
          if (bodyUnusable(input.#state)) {
            throw new TypeError(
              "Cannot construct a Request with a Request object that has already been used."
            );
          }
          const identityTransform = new TransformStream();
          inputBody.stream.pipeThrough(identityTransform);
          finalBody = {
            source: inputBody.source,
            length: inputBody.length,
            stream: identityTransform.readable
          };
        }
        this.#state.body = finalBody;
      }
      // Returns request’s HTTP method, which is "GET" by default.
      get method() {
        webidl.brandCheck(this, _Request);
        return this.#state.method;
      }
      // Returns the URL of request as a string.
      get url() {
        webidl.brandCheck(this, _Request);
        return URLSerializer(this.#state.url);
      }
      // Returns a Headers object consisting of the headers associated with request.
      // Note that headers added in the network layer by the user agent will not
      // be accounted for in this object, e.g., the "Host" header.
      get headers() {
        webidl.brandCheck(this, _Request);
        return this.#headers;
      }
      // Returns the kind of resource requested by request, e.g., "document"
      // or "script".
      get destination() {
        webidl.brandCheck(this, _Request);
        return this.#state.destination;
      }
      // Returns the referrer of request. Its value can be a same-origin URL if
      // explicitly set in init, the empty string to indicate no referrer, and
      // "about:client" when defaulting to the global’s default. This is used
      // during fetching to determine the value of the `Referer` header of the
      // request being made.
      get referrer() {
        webidl.brandCheck(this, _Request);
        if (this.#state.referrer === "no-referrer") {
          return "";
        }
        if (this.#state.referrer === "client") {
          return "about:client";
        }
        return this.#state.referrer.toString();
      }
      // Returns the referrer policy associated with request.
      // This is used during fetching to compute the value of the request’s
      // referrer.
      get referrerPolicy() {
        webidl.brandCheck(this, _Request);
        return this.#state.referrerPolicy;
      }
      // Returns the mode associated with request, which is a string indicating
      // whether the request will use CORS, or will be restricted to same-origin
      // URLs.
      get mode() {
        webidl.brandCheck(this, _Request);
        return this.#state.mode;
      }
      // Returns the credentials mode associated with request,
      // which is a string indicating whether credentials will be sent with the
      // request always, never, or only when sent to a same-origin URL.
      get credentials() {
        webidl.brandCheck(this, _Request);
        return this.#state.credentials;
      }
      // Returns the cache mode associated with request,
      // which is a string indicating how the request will
      // interact with the browser’s cache when fetching.
      get cache() {
        webidl.brandCheck(this, _Request);
        return this.#state.cache;
      }
      // Returns the redirect mode associated with request,
      // which is a string indicating how redirects for the
      // request will be handled during fetching. A request
      // will follow redirects by default.
      get redirect() {
        webidl.brandCheck(this, _Request);
        return this.#state.redirect;
      }
      // Returns request’s subresource integrity metadata, which is a
      // cryptographic hash of the resource being fetched. Its value
      // consists of multiple hashes separated by whitespace. [SRI]
      get integrity() {
        webidl.brandCheck(this, _Request);
        return this.#state.integrity;
      }
      // Returns a boolean indicating whether or not request can outlive the
      // global in which it was created.
      get keepalive() {
        webidl.brandCheck(this, _Request);
        return this.#state.keepalive;
      }
      // Returns a boolean indicating whether or not request is for a reload
      // navigation.
      get isReloadNavigation() {
        webidl.brandCheck(this, _Request);
        return this.#state.reloadNavigation;
      }
      // Returns a boolean indicating whether or not request is for a history
      // navigation (a.k.a. back-forward navigation).
      get isHistoryNavigation() {
        webidl.brandCheck(this, _Request);
        return this.#state.historyNavigation;
      }
      // Returns the signal associated with request, which is an AbortSignal
      // object indicating whether or not request has been aborted, and its
      // abort event handler.
      get signal() {
        webidl.brandCheck(this, _Request);
        return this.#signal;
      }
      get body() {
        webidl.brandCheck(this, _Request);
        return this.#state.body ? this.#state.body.stream : null;
      }
      get bodyUsed() {
        webidl.brandCheck(this, _Request);
        return !!this.#state.body && util4.isDisturbed(this.#state.body.stream);
      }
      get duplex() {
        webidl.brandCheck(this, _Request);
        return "half";
      }
      // Returns a clone of request.
      clone() {
        webidl.brandCheck(this, _Request);
        if (bodyUnusable(this.#state)) {
          throw new TypeError("unusable");
        }
        const clonedRequest = cloneRequest(this.#state);
        const ac = new AbortController();
        if (this.signal.aborted) {
          ac.abort(this.signal.reason);
        } else {
          let list3 = dependentControllerMap.get(this.signal);
          if (list3 === void 0) {
            list3 = /* @__PURE__ */ new Set();
            dependentControllerMap.set(this.signal, list3);
          }
          const acRef = new WeakRef(ac);
          list3.add(acRef);
          util4.addAbortListener(
            ac.signal,
            buildAbort(acRef)
          );
        }
        return fromInnerRequest(clonedRequest, this.#dispatcher, ac.signal, getHeadersGuard(this.#headers));
      }
      [nodeUtil.inspect.custom](depth, options2) {
        if (options2.depth === null) {
          options2.depth = 2;
        }
        options2.colors ??= true;
        const properties = {
          method: this.method,
          url: this.url,
          headers: this.headers,
          destination: this.destination,
          referrer: this.referrer,
          referrerPolicy: this.referrerPolicy,
          mode: this.mode,
          credentials: this.credentials,
          cache: this.cache,
          redirect: this.redirect,
          integrity: this.integrity,
          keepalive: this.keepalive,
          isReloadNavigation: this.isReloadNavigation,
          isHistoryNavigation: this.isHistoryNavigation,
          signal: this.signal
        };
        return `Request ${nodeUtil.formatWithOptions(options2, properties)}`;
      }
      /**
       * @param {Request} request
       * @param {AbortSignal} newSignal
       */
      static setRequestSignal(request4, newSignal) {
        request4.#signal = newSignal;
        return request4;
      }
      /**
       * @param {Request} request
       */
      static getRequestDispatcher(request4) {
        return request4.#dispatcher;
      }
      /**
       * @param {Request} request
       * @param {import('../../dispatcher/dispatcher')} newDispatcher
       */
      static setRequestDispatcher(request4, newDispatcher) {
        request4.#dispatcher = newDispatcher;
      }
      /**
       * @param {Request} request
       * @param {Headers} newHeaders
       */
      static setRequestHeaders(request4, newHeaders) {
        request4.#headers = newHeaders;
      }
      /**
       * @param {Request} request
       */
      static getRequestState(request4) {
        return request4.#state;
      }
      /**
       * @param {Request} request
       * @param {any} newState
       */
      static setRequestState(request4, newState) {
        request4.#state = newState;
      }
    };
    var { setRequestSignal, getRequestDispatcher, setRequestDispatcher, setRequestHeaders, getRequestState, setRequestState } = Request2;
    Reflect.deleteProperty(Request2, "setRequestSignal");
    Reflect.deleteProperty(Request2, "getRequestDispatcher");
    Reflect.deleteProperty(Request2, "setRequestDispatcher");
    Reflect.deleteProperty(Request2, "setRequestHeaders");
    Reflect.deleteProperty(Request2, "getRequestState");
    Reflect.deleteProperty(Request2, "setRequestState");
    mixinBody(Request2, getRequestState);
    function makeRequest(init) {
      return {
        method: init.method ?? "GET",
        localURLsOnly: init.localURLsOnly ?? false,
        unsafeRequest: init.unsafeRequest ?? false,
        body: init.body ?? null,
        client: init.client ?? null,
        reservedClient: init.reservedClient ?? null,
        replacesClientId: init.replacesClientId ?? "",
        window: init.window ?? "client",
        keepalive: init.keepalive ?? false,
        serviceWorkers: init.serviceWorkers ?? "all",
        initiator: init.initiator ?? "",
        destination: init.destination ?? "",
        priority: init.priority ?? null,
        origin: init.origin ?? "client",
        policyContainer: init.policyContainer ?? "client",
        referrer: init.referrer ?? "client",
        referrerPolicy: init.referrerPolicy ?? "",
        mode: init.mode ?? "no-cors",
        useCORSPreflightFlag: init.useCORSPreflightFlag ?? false,
        credentials: init.credentials ?? "same-origin",
        useCredentials: init.useCredentials ?? false,
        cache: init.cache ?? "default",
        redirect: init.redirect ?? "follow",
        integrity: init.integrity ?? "",
        cryptoGraphicsNonceMetadata: init.cryptoGraphicsNonceMetadata ?? "",
        parserMetadata: init.parserMetadata ?? "",
        reloadNavigation: init.reloadNavigation ?? false,
        historyNavigation: init.historyNavigation ?? false,
        userActivation: init.userActivation ?? false,
        taintedOrigin: init.taintedOrigin ?? false,
        redirectCount: init.redirectCount ?? 0,
        responseTainting: init.responseTainting ?? "basic",
        preventNoCacheCacheControlHeaderModification: init.preventNoCacheCacheControlHeaderModification ?? false,
        done: init.done ?? false,
        timingAllowFailed: init.timingAllowFailed ?? false,
        urlList: init.urlList,
        url: init.urlList[0],
        headersList: init.headersList ? new HeadersList(init.headersList) : new HeadersList()
      };
    }
    __name(makeRequest, "makeRequest");
    function cloneRequest(request4) {
      const newRequest = makeRequest({ ...request4, body: null });
      if (request4.body != null) {
        newRequest.body = cloneBody(request4.body);
      }
      return newRequest;
    }
    __name(cloneRequest, "cloneRequest");
    function fromInnerRequest(innerRequest, dispatcher, signal, guard) {
      const request4 = new Request2(kConstruct);
      setRequestState(request4, innerRequest);
      setRequestDispatcher(request4, dispatcher);
      setRequestSignal(request4, signal);
      const headers = new Headers2(kConstruct);
      setRequestHeaders(request4, headers);
      setHeadersList(headers, innerRequest.headersList);
      setHeadersGuard(headers, guard);
      return request4;
    }
    __name(fromInnerRequest, "fromInnerRequest");
    Object.defineProperties(Request2.prototype, {
      method: kEnumerableProperty,
      url: kEnumerableProperty,
      headers: kEnumerableProperty,
      redirect: kEnumerableProperty,
      clone: kEnumerableProperty,
      signal: kEnumerableProperty,
      duplex: kEnumerableProperty,
      destination: kEnumerableProperty,
      body: kEnumerableProperty,
      bodyUsed: kEnumerableProperty,
      isHistoryNavigation: kEnumerableProperty,
      isReloadNavigation: kEnumerableProperty,
      keepalive: kEnumerableProperty,
      integrity: kEnumerableProperty,
      cache: kEnumerableProperty,
      credentials: kEnumerableProperty,
      attribute: kEnumerableProperty,
      referrerPolicy: kEnumerableProperty,
      referrer: kEnumerableProperty,
      mode: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "Request",
        configurable: true
      }
    });
    webidl.is.Request = webidl.util.MakeTypeAssertion(Request2);
    webidl.converters.RequestInfo = function(V2) {
      if (typeof V2 === "string") {
        return webidl.converters.USVString(V2);
      }
      if (webidl.is.Request(V2)) {
        return V2;
      }
      return webidl.converters.USVString(V2);
    };
    webidl.converters.RequestInit = webidl.dictionaryConverter([
      {
        key: "method",
        converter: webidl.converters.ByteString
      },
      {
        key: "headers",
        converter: webidl.converters.HeadersInit
      },
      {
        key: "body",
        converter: webidl.nullableConverter(
          webidl.converters.BodyInit
        )
      },
      {
        key: "referrer",
        converter: webidl.converters.USVString
      },
      {
        key: "referrerPolicy",
        converter: webidl.converters.DOMString,
        // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy
        allowedValues: referrerPolicy
      },
      {
        key: "mode",
        converter: webidl.converters.DOMString,
        // https://fetch.spec.whatwg.org/#concept-request-mode
        allowedValues: requestMode
      },
      {
        key: "credentials",
        converter: webidl.converters.DOMString,
        // https://fetch.spec.whatwg.org/#requestcredentials
        allowedValues: requestCredentials
      },
      {
        key: "cache",
        converter: webidl.converters.DOMString,
        // https://fetch.spec.whatwg.org/#requestcache
        allowedValues: requestCache
      },
      {
        key: "redirect",
        converter: webidl.converters.DOMString,
        // https://fetch.spec.whatwg.org/#requestredirect
        allowedValues: requestRedirect
      },
      {
        key: "integrity",
        converter: webidl.converters.DOMString
      },
      {
        key: "keepalive",
        converter: webidl.converters.boolean
      },
      {
        key: "signal",
        converter: webidl.nullableConverter(
          (signal) => webidl.converters.AbortSignal(
            signal,
            "RequestInit",
            "signal"
          )
        )
      },
      {
        key: "window",
        converter: webidl.converters.any
      },
      {
        key: "duplex",
        converter: webidl.converters.DOMString,
        allowedValues: requestDuplex
      },
      {
        key: "dispatcher",
        // undici specific option
        converter: webidl.converters.any
      }
    ]);
    module2.exports = {
      Request: Request2,
      makeRequest,
      fromInnerRequest,
      cloneRequest,
      getRequestDispatcher,
      getRequestState
    };
  }
});

// node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js
var require_subresource_integrity = __commonJS({
  "node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert3 = __require("node:assert");
    var validSRIHashAlgorithmTokenSet = /* @__PURE__ */ new Map([["sha256", 0], ["sha384", 1], ["sha512", 2]]);
    var crypto18;
    try {
      crypto18 = __require("node:crypto");
      const cryptoHashes = crypto18.getHashes();
      if (cryptoHashes.length === 0) {
        validSRIHashAlgorithmTokenSet.clear();
      }
      for (const algorithm of validSRIHashAlgorithmTokenSet.keys()) {
        if (cryptoHashes.includes(algorithm) === false) {
          validSRIHashAlgorithmTokenSet.delete(algorithm);
        }
      }
    } catch {
      validSRIHashAlgorithmTokenSet.clear();
    }
    var getSRIHashAlgorithmIndex = (
      /** @type {GetSRIHashAlgorithmIndex} */
      Map.prototype.get.bind(
        validSRIHashAlgorithmTokenSet
      )
    );
    var isValidSRIHashAlgorithm = (
      /** @type {IsValidSRIHashAlgorithm} */
      Map.prototype.has.bind(validSRIHashAlgorithmTokenSet)
    );
    var bytesMatch = crypto18 === void 0 || validSRIHashAlgorithmTokenSet.size === 0 ? () => true : (bytes, metadataList) => {
      const parsedMetadata = parseMetadata(metadataList);
      if (parsedMetadata.length === 0) {
        return true;
      }
      const metadata = getStrongestMetadata(parsedMetadata);
      for (const item of metadata) {
        const algorithm = item.alg;
        const expectedValue = item.val;
        const actualValue = applyAlgorithmToBytes(algorithm, bytes);
        if (caseSensitiveMatch(actualValue, expectedValue)) {
          return true;
        }
      }
      return false;
    };
    function getStrongestMetadata(metadataList) {
      const result = [];
      let strongest = null;
      for (const item of metadataList) {
        assert3(isValidSRIHashAlgorithm(item.alg), "Invalid SRI hash algorithm token");
        if (result.length === 0) {
          result.push(item);
          strongest = item;
          continue;
        }
        const currentAlgorithm = (
          /** @type {Metadata} */
          strongest.alg
        );
        const currentAlgorithmIndex = getSRIHashAlgorithmIndex(currentAlgorithm);
        const newAlgorithm = item.alg;
        const newAlgorithmIndex = getSRIHashAlgorithmIndex(newAlgorithm);
        if (newAlgorithmIndex < currentAlgorithmIndex) {
          continue;
        } else if (newAlgorithmIndex > currentAlgorithmIndex) {
          strongest = item;
          result[0] = item;
          result.length = 1;
        } else {
          result.push(item);
        }
      }
      return result;
    }
    __name(getStrongestMetadata, "getStrongestMetadata");
    function parseMetadata(metadata) {
      const result = [];
      for (const item of metadata.split(" ")) {
        const expressionAndOptions = item.split("?", 1);
        const algorithmExpression = expressionAndOptions[0];
        let base64Value = "";
        const algorithmAndValue = [algorithmExpression.slice(0, 6), algorithmExpression.slice(7)];
        const algorithm = algorithmAndValue[0];
        if (!isValidSRIHashAlgorithm(algorithm)) {
          continue;
        }
        if (algorithmAndValue[1]) {
          base64Value = algorithmAndValue[1];
        }
        const metadata2 = {
          alg: algorithm,
          val: base64Value
        };
        result.push(metadata2);
      }
      return result;
    }
    __name(parseMetadata, "parseMetadata");
    var applyAlgorithmToBytes = /* @__PURE__ */ __name((algorithm, bytes) => {
      return crypto18.hash(algorithm, bytes, "base64");
    }, "applyAlgorithmToBytes");
    function caseSensitiveMatch(actualValue, expectedValue) {
      let actualValueLength = actualValue.length;
      if (actualValueLength !== 0 && actualValue[actualValueLength - 1] === "=") {
        actualValueLength -= 1;
      }
      if (actualValueLength !== 0 && actualValue[actualValueLength - 1] === "=") {
        actualValueLength -= 1;
      }
      let expectedValueLength = expectedValue.length;
      if (expectedValueLength !== 0 && expectedValue[expectedValueLength - 1] === "=") {
        expectedValueLength -= 1;
      }
      if (expectedValueLength !== 0 && expectedValue[expectedValueLength - 1] === "=") {
        expectedValueLength -= 1;
      }
      if (actualValueLength !== expectedValueLength) {
        return false;
      }
      for (let i = 0; i < actualValueLength; ++i) {
        if (actualValue[i] === expectedValue[i] || actualValue[i] === "+" && expectedValue[i] === "-" || actualValue[i] === "/" && expectedValue[i] === "_") {
          continue;
        }
        return false;
      }
      return true;
    }
    __name(caseSensitiveMatch, "caseSensitiveMatch");
    module2.exports = {
      applyAlgorithmToBytes,
      bytesMatch,
      caseSensitiveMatch,
      isValidSRIHashAlgorithm,
      getStrongestMetadata,
      parseMetadata
    };
  }
});

// node_modules/undici/lib/web/fetch/index.js
var require_fetch = __commonJS({
  "node_modules/undici/lib/web/fetch/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      makeNetworkError,
      makeAppropriateNetworkError,
      filterResponse,
      makeResponse,
      fromInnerResponse,
      getResponseState
    } = require_response();
    var { HeadersList } = require_headers();
    var { Request: Request2, cloneRequest, getRequestDispatcher, getRequestState } = require_request2();
    var zlib2 = __require("node:zlib");
    var {
      makePolicyContainer,
      clonePolicyContainer,
      requestBadPort,
      TAOCheck,
      appendRequestOriginHeader,
      responseLocationURL,
      requestCurrentURL,
      setRequestReferrerPolicyOnRedirect,
      tryUpgradeRequestToAPotentiallyTrustworthyURL,
      createOpaqueTimingInfo,
      appendFetchMetadata,
      corsCheck,
      crossOriginResourcePolicyCheck,
      determineRequestsReferrer,
      coarsenedSharedCurrentTime,
      sameOrigin,
      isCancelled,
      isAborted: isAborted2,
      isErrorLike,
      fullyReadBody,
      readableStreamClose,
      isomorphicEncode,
      urlIsLocal,
      urlIsHttpHttpsScheme,
      urlHasHttpsScheme,
      clampAndCoarsenConnectionTimingInfo,
      simpleRangeHeaderValue,
      buildContentRange,
      createInflate,
      extractMimeType
    } = require_util2();
    var assert3 = __require("node:assert");
    var { safelyExtractBody, extractBody } = require_body();
    var {
      redirectStatusSet,
      nullBodyStatus,
      safeMethodsSet,
      requestBodyHeader,
      subresourceSet
    } = require_constants5();
    var EE3 = __require("node:events");
    var { Readable: Readable4, pipeline, finished, isErrored, isReadable: isReadable2 } = __require("node:stream");
    var { addAbortListener, bufferToLowerCasedHeaderName } = require_util();
    var { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require_data_url();
    var { getGlobalDispatcher } = require_global2();
    var { webidl } = require_webidl();
    var { STATUS_CODES } = __require("node:http");
    var { bytesMatch } = require_subresource_integrity();
    var { createDeferredPromise } = require_promise();
    var GET_OR_HEAD = ["GET", "HEAD"];
    var defaultUserAgent = typeof __UNDICI_IS_NODE__ !== "undefined" || typeof esbuildDetection !== "undefined" ? "node" : "undici";
    var resolveObjectURL;
    var Fetch = class extends EE3 {
      static {
        __name(this, "Fetch");
      }
      constructor(dispatcher) {
        super();
        this.dispatcher = dispatcher;
        this.connection = null;
        this.dump = false;
        this.state = "ongoing";
      }
      terminate(reason) {
        if (this.state !== "ongoing") {
          return;
        }
        this.state = "terminated";
        this.connection?.destroy(reason);
        this.emit("terminated", reason);
      }
      // https://fetch.spec.whatwg.org/#fetch-controller-abort
      abort(error) {
        if (this.state !== "ongoing") {
          return;
        }
        this.state = "aborted";
        if (!error) {
          error = new DOMException("The operation was aborted.", "AbortError");
        }
        this.serializedAbortReason = error;
        this.connection?.destroy(error);
        this.emit("terminated", error);
      }
    };
    function handleFetchDone(response) {
      finalizeAndReportTiming(response, "fetch");
    }
    __name(handleFetchDone, "handleFetchDone");
    function fetch2(input, init = void 0) {
      webidl.argumentLengthCheck(arguments, 1, "globalThis.fetch");
      let p = createDeferredPromise();
      let requestObject;
      try {
        requestObject = new Request2(input, init);
      } catch (e2) {
        p.reject(e2);
        return p.promise;
      }
      const request4 = getRequestState(requestObject);
      if (requestObject.signal.aborted) {
        abortFetch(p, request4, null, requestObject.signal.reason);
        return p.promise;
      }
      const globalObject = request4.client.globalObject;
      if (globalObject?.constructor?.name === "ServiceWorkerGlobalScope") {
        request4.serviceWorkers = "none";
      }
      let responseObject = null;
      let locallyAborted = false;
      let controller = null;
      addAbortListener(
        requestObject.signal,
        () => {
          locallyAborted = true;
          assert3(controller != null);
          controller.abort(requestObject.signal.reason);
          const realResponse = responseObject?.deref();
          abortFetch(p, request4, realResponse, requestObject.signal.reason);
        }
      );
      const processResponse = /* @__PURE__ */ __name((response) => {
        if (locallyAborted) {
          return;
        }
        if (response.aborted) {
          abortFetch(p, request4, responseObject, controller.serializedAbortReason);
          return;
        }
        if (response.type === "error") {
          p.reject(new TypeError("fetch failed", { cause: response.error }));
          return;
        }
        responseObject = new WeakRef(fromInnerResponse(response, "immutable"));
        p.resolve(responseObject.deref());
        p = null;
      }, "processResponse");
      controller = fetching({
        request: request4,
        processResponseEndOfBody: handleFetchDone,
        processResponse,
        dispatcher: getRequestDispatcher(requestObject)
        // undici
      });
      return p.promise;
    }
    __name(fetch2, "fetch");
    function finalizeAndReportTiming(response, initiatorType = "other") {
      if (response.type === "error" && response.aborted) {
        return;
      }
      if (!response.urlList?.length) {
        return;
      }
      const originalURL = response.urlList[0];
      let timingInfo = response.timingInfo;
      let cacheState = response.cacheState;
      if (!urlIsHttpHttpsScheme(originalURL)) {
        return;
      }
      if (timingInfo === null) {
        return;
      }
      if (!response.timingAllowPassed) {
        timingInfo = createOpaqueTimingInfo({
          startTime: timingInfo.startTime
        });
        cacheState = "";
      }
      timingInfo.endTime = coarsenedSharedCurrentTime();
      response.timingInfo = timingInfo;
      markResourceTiming(
        timingInfo,
        originalURL.href,
        initiatorType,
        globalThis,
        cacheState,
        "",
        // bodyType
        response.status
      );
    }
    __name(finalizeAndReportTiming, "finalizeAndReportTiming");
    var markResourceTiming = performance.markResourceTiming;
    function abortFetch(p, request4, responseObject, error) {
      if (p) {
        p.reject(error);
      }
      if (request4.body?.stream != null && isReadable2(request4.body.stream)) {
        request4.body.stream.cancel(error).catch((err) => {
          if (err.code === "ERR_INVALID_STATE") {
            return;
          }
          throw err;
        });
      }
      if (responseObject == null) {
        return;
      }
      const response = getResponseState(responseObject);
      if (response.body?.stream != null && isReadable2(response.body.stream)) {
        response.body.stream.cancel(error).catch((err) => {
          if (err.code === "ERR_INVALID_STATE") {
            return;
          }
          throw err;
        });
      }
    }
    __name(abortFetch, "abortFetch");
    function fetching({
      request: request4,
      processRequestBodyChunkLength,
      processRequestEndOfBody,
      processResponse,
      processResponseEndOfBody,
      processResponseConsumeBody,
      useParallelQueue = false,
      dispatcher = getGlobalDispatcher()
      // undici
    }) {
      assert3(dispatcher);
      let taskDestination = null;
      let crossOriginIsolatedCapability = false;
      if (request4.client != null) {
        taskDestination = request4.client.globalObject;
        crossOriginIsolatedCapability = request4.client.crossOriginIsolatedCapability;
      }
      const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability);
      const timingInfo = createOpaqueTimingInfo({
        startTime: currentTime
      });
      const fetchParams = {
        controller: new Fetch(dispatcher),
        request: request4,
        timingInfo,
        processRequestBodyChunkLength,
        processRequestEndOfBody,
        processResponse,
        processResponseConsumeBody,
        processResponseEndOfBody,
        taskDestination,
        crossOriginIsolatedCapability
      };
      assert3(!request4.body || request4.body.stream);
      if (request4.window === "client") {
        request4.window = request4.client?.globalObject?.constructor?.name === "Window" ? request4.client : "no-window";
      }
      if (request4.origin === "client") {
        request4.origin = request4.client.origin;
      }
      if (request4.policyContainer === "client") {
        if (request4.client != null) {
          request4.policyContainer = clonePolicyContainer(
            request4.client.policyContainer
          );
        } else {
          request4.policyContainer = makePolicyContainer();
        }
      }
      if (!request4.headersList.contains("accept", true)) {
        const value = "*/*";
        request4.headersList.append("accept", value, true);
      }
      if (!request4.headersList.contains("accept-language", true)) {
        request4.headersList.append("accept-language", "*", true);
      }
      if (request4.priority === null) {
      }
      if (subresourceSet.has(request4.destination)) {
      }
      mainFetch(fetchParams, false);
      return fetchParams.controller;
    }
    __name(fetching, "fetching");
    async function mainFetch(fetchParams, recursive) {
      try {
        const request4 = fetchParams.request;
        let response = null;
        if (request4.localURLsOnly && !urlIsLocal(requestCurrentURL(request4))) {
          response = makeNetworkError("local URLs only");
        }
        tryUpgradeRequestToAPotentiallyTrustworthyURL(request4);
        if (requestBadPort(request4) === "blocked") {
          response = makeNetworkError("bad port");
        }
        if (request4.referrerPolicy === "") {
          request4.referrerPolicy = request4.policyContainer.referrerPolicy;
        }
        if (request4.referrer !== "no-referrer") {
          request4.referrer = determineRequestsReferrer(request4);
        }
        if (response === null) {
          const currentURL = requestCurrentURL(request4);
          if (
            // - request’s current URL’s origin is same origin with request’s origin,
            //   and request’s response tainting is "basic"
            sameOrigin(currentURL, request4.url) && request4.responseTainting === "basic" || // request’s current URL’s scheme is "data"
            currentURL.protocol === "data:" || // - request’s mode is "navigate" or "websocket"
            (request4.mode === "navigate" || request4.mode === "websocket")
          ) {
            request4.responseTainting = "basic";
            response = await schemeFetch(fetchParams);
          } else if (request4.mode === "same-origin") {
            response = makeNetworkError('request mode cannot be "same-origin"');
          } else if (request4.mode === "no-cors") {
            if (request4.redirect !== "follow") {
              response = makeNetworkError(
                'redirect mode cannot be "follow" for "no-cors" request'
              );
            } else {
              request4.responseTainting = "opaque";
              response = await schemeFetch(fetchParams);
            }
          } else if (!urlIsHttpHttpsScheme(requestCurrentURL(request4))) {
            response = makeNetworkError("URL scheme must be a HTTP(S) scheme");
          } else {
            request4.responseTainting = "cors";
            response = await httpFetch(fetchParams);
          }
        }
        if (recursive) {
          return response;
        }
        if (response.status !== 0 && !response.internalResponse) {
          if (request4.responseTainting === "cors") {
          }
          if (request4.responseTainting === "basic") {
            response = filterResponse(response, "basic");
          } else if (request4.responseTainting === "cors") {
            response = filterResponse(response, "cors");
          } else if (request4.responseTainting === "opaque") {
            response = filterResponse(response, "opaque");
          } else {
            assert3(false);
          }
        }
        let internalResponse = response.status === 0 ? response : response.internalResponse;
        if (internalResponse.urlList.length === 0) {
          internalResponse.urlList.push(...request4.urlList);
        }
        if (!request4.timingAllowFailed) {
          response.timingAllowPassed = true;
        }
        if (response.type === "opaque" && internalResponse.status === 206 && internalResponse.rangeRequested && !request4.headers.contains("range", true)) {
          response = internalResponse = makeNetworkError();
        }
        if (response.status !== 0 && (request4.method === "HEAD" || request4.method === "CONNECT" || nullBodyStatus.includes(internalResponse.status))) {
          internalResponse.body = null;
          fetchParams.controller.dump = true;
        }
        if (request4.integrity) {
          const processBodyError = /* @__PURE__ */ __name((reason) => fetchFinale(fetchParams, makeNetworkError(reason)), "processBodyError");
          if (request4.responseTainting === "opaque" || response.body == null) {
            processBodyError(response.error);
            return;
          }
          const processBody = /* @__PURE__ */ __name((bytes) => {
            if (!bytesMatch(bytes, request4.integrity)) {
              processBodyError("integrity mismatch");
              return;
            }
            response.body = safelyExtractBody(bytes)[0];
            fetchFinale(fetchParams, response);
          }, "processBody");
          fullyReadBody(response.body, processBody, processBodyError);
        } else {
          fetchFinale(fetchParams, response);
        }
      } catch (err) {
        fetchParams.controller.terminate(err);
      }
    }
    __name(mainFetch, "mainFetch");
    function schemeFetch(fetchParams) {
      if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
        return Promise.resolve(makeAppropriateNetworkError(fetchParams));
      }
      const { request: request4 } = fetchParams;
      const { protocol: scheme } = requestCurrentURL(request4);
      switch (scheme) {
        case "about:": {
          return Promise.resolve(makeNetworkError("about scheme is not supported"));
        }
        case "blob:": {
          if (!resolveObjectURL) {
            resolveObjectURL = __require("node:buffer").resolveObjectURL;
          }
          const blobURLEntry = requestCurrentURL(request4);
          if (blobURLEntry.search.length !== 0) {
            return Promise.resolve(makeNetworkError("NetworkError when attempting to fetch resource."));
          }
          const blob = resolveObjectURL(blobURLEntry.toString());
          if (request4.method !== "GET" || !webidl.is.Blob(blob)) {
            return Promise.resolve(makeNetworkError("invalid method"));
          }
          const response = makeResponse();
          const fullLength = blob.size;
          const serializedFullLength = isomorphicEncode(`${fullLength}`);
          const type = blob.type;
          if (!request4.headersList.contains("range", true)) {
            const bodyWithType = extractBody(blob);
            response.statusText = "OK";
            response.body = bodyWithType[0];
            response.headersList.set("content-length", serializedFullLength, true);
            response.headersList.set("content-type", type, true);
          } else {
            response.rangeRequested = true;
            const rangeHeader = request4.headersList.get("range", true);
            const rangeValue = simpleRangeHeaderValue(rangeHeader, true);
            if (rangeValue === "failure") {
              return Promise.resolve(makeNetworkError("failed to fetch the data URL"));
            }
            let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue;
            if (rangeStart === null) {
              rangeStart = fullLength - rangeEnd;
              rangeEnd = rangeStart + rangeEnd - 1;
            } else {
              if (rangeStart >= fullLength) {
                return Promise.resolve(makeNetworkError("Range start is greater than the blob's size."));
              }
              if (rangeEnd === null || rangeEnd >= fullLength) {
                rangeEnd = fullLength - 1;
              }
            }
            const slicedBlob = blob.slice(rangeStart, rangeEnd, type);
            const slicedBodyWithType = extractBody(slicedBlob);
            response.body = slicedBodyWithType[0];
            const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`);
            const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength);
            response.status = 206;
            response.statusText = "Partial Content";
            response.headersList.set("content-length", serializedSlicedLength, true);
            response.headersList.set("content-type", type, true);
            response.headersList.set("content-range", contentRange, true);
          }
          return Promise.resolve(response);
        }
        case "data:": {
          const currentURL = requestCurrentURL(request4);
          const dataURLStruct = dataURLProcessor(currentURL);
          if (dataURLStruct === "failure") {
            return Promise.resolve(makeNetworkError("failed to fetch the data URL"));
          }
          const mimeType = serializeAMimeType(dataURLStruct.mimeType);
          return Promise.resolve(makeResponse({
            statusText: "OK",
            headersList: [
              ["content-type", { name: "Content-Type", value: mimeType }]
            ],
            body: safelyExtractBody(dataURLStruct.body)[0]
          }));
        }
        case "file:": {
          return Promise.resolve(makeNetworkError("not implemented... yet..."));
        }
        case "http:":
        case "https:": {
          return httpFetch(fetchParams).catch((err) => makeNetworkError(err));
        }
        default: {
          return Promise.resolve(makeNetworkError("unknown scheme"));
        }
      }
    }
    __name(schemeFetch, "schemeFetch");
    function finalizeResponse2(fetchParams, response) {
      fetchParams.request.done = true;
      if (fetchParams.processResponseDone != null) {
        queueMicrotask(() => fetchParams.processResponseDone(response));
      }
    }
    __name(finalizeResponse2, "finalizeResponse");
    function fetchFinale(fetchParams, response) {
      let timingInfo = fetchParams.timingInfo;
      const processResponseEndOfBody = /* @__PURE__ */ __name(() => {
        const unsafeEndTime = Date.now();
        if (fetchParams.request.destination === "document") {
          fetchParams.controller.fullTimingInfo = timingInfo;
        }
        fetchParams.controller.reportTimingSteps = () => {
          if (!urlIsHttpHttpsScheme(fetchParams.request.url)) {
            return;
          }
          timingInfo.endTime = unsafeEndTime;
          let cacheState = response.cacheState;
          const bodyInfo = response.bodyInfo;
          if (!response.timingAllowPassed) {
            timingInfo = createOpaqueTimingInfo(timingInfo);
            cacheState = "";
          }
          let responseStatus = 0;
          if (fetchParams.request.mode !== "navigator" || !response.hasCrossOriginRedirects) {
            responseStatus = response.status;
            const mimeType = extractMimeType(response.headersList);
            if (mimeType !== "failure") {
              bodyInfo.contentType = minimizeSupportedMimeType(mimeType);
            }
          }
          if (fetchParams.request.initiatorType != null) {
            markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus);
          }
        };
        const processResponseEndOfBodyTask = /* @__PURE__ */ __name(() => {
          fetchParams.request.done = true;
          if (fetchParams.processResponseEndOfBody != null) {
            queueMicrotask(() => fetchParams.processResponseEndOfBody(response));
          }
          if (fetchParams.request.initiatorType != null) {
            fetchParams.controller.reportTimingSteps();
          }
        }, "processResponseEndOfBodyTask");
        queueMicrotask(() => processResponseEndOfBodyTask());
      }, "processResponseEndOfBody");
      if (fetchParams.processResponse != null) {
        queueMicrotask(() => {
          fetchParams.processResponse(response);
          fetchParams.processResponse = null;
        });
      }
      const internalResponse = response.type === "error" ? response : response.internalResponse ?? response;
      if (internalResponse.body == null) {
        processResponseEndOfBody();
      } else {
        finished(internalResponse.body.stream, () => {
          processResponseEndOfBody();
        });
      }
    }
    __name(fetchFinale, "fetchFinale");
    async function httpFetch(fetchParams) {
      const request4 = fetchParams.request;
      let response = null;
      let actualResponse = null;
      const timingInfo = fetchParams.timingInfo;
      if (request4.serviceWorkers === "all") {
      }
      if (response === null) {
        if (request4.redirect === "follow") {
          request4.serviceWorkers = "none";
        }
        actualResponse = response = await httpNetworkOrCacheFetch(fetchParams);
        if (request4.responseTainting === "cors" && corsCheck(request4, response) === "failure") {
          return makeNetworkError("cors failure");
        }
        if (TAOCheck(request4, response) === "failure") {
          request4.timingAllowFailed = true;
        }
      }
      if ((request4.responseTainting === "opaque" || response.type === "opaque") && crossOriginResourcePolicyCheck(
        request4.origin,
        request4.client,
        request4.destination,
        actualResponse
      ) === "blocked") {
        return makeNetworkError("blocked");
      }
      if (redirectStatusSet.has(actualResponse.status)) {
        if (request4.redirect !== "manual") {
          fetchParams.controller.connection.destroy(void 0, false);
        }
        if (request4.redirect === "error") {
          response = makeNetworkError("unexpected redirect");
        } else if (request4.redirect === "manual") {
          response = actualResponse;
        } else if (request4.redirect === "follow") {
          response = await httpRedirectFetch(fetchParams, response);
        } else {
          assert3(false);
        }
      }
      response.timingInfo = timingInfo;
      return response;
    }
    __name(httpFetch, "httpFetch");
    function httpRedirectFetch(fetchParams, response) {
      const request4 = fetchParams.request;
      const actualResponse = response.internalResponse ? response.internalResponse : response;
      let locationURL;
      try {
        locationURL = responseLocationURL(
          actualResponse,
          requestCurrentURL(request4).hash
        );
        if (locationURL == null) {
          return response;
        }
      } catch (err) {
        return Promise.resolve(makeNetworkError(err));
      }
      if (!urlIsHttpHttpsScheme(locationURL)) {
        return Promise.resolve(makeNetworkError("URL scheme must be a HTTP(S) scheme"));
      }
      if (request4.redirectCount === 20) {
        return Promise.resolve(makeNetworkError("redirect count exceeded"));
      }
      request4.redirectCount += 1;
      if (request4.mode === "cors" && (locationURL.username || locationURL.password) && !sameOrigin(request4, locationURL)) {
        return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'));
      }
      if (request4.responseTainting === "cors" && (locationURL.username || locationURL.password)) {
        return Promise.resolve(makeNetworkError(
          'URL cannot contain credentials for request mode "cors"'
        ));
      }
      if (actualResponse.status !== 303 && request4.body != null && request4.body.source == null) {
        return Promise.resolve(makeNetworkError());
      }
      if ([301, 302].includes(actualResponse.status) && request4.method === "POST" || actualResponse.status === 303 && !GET_OR_HEAD.includes(request4.method)) {
        request4.method = "GET";
        request4.body = null;
        for (const headerName of requestBodyHeader) {
          request4.headersList.delete(headerName);
        }
      }
      if (!sameOrigin(requestCurrentURL(request4), locationURL)) {
        request4.headersList.delete("authorization", true);
        request4.headersList.delete("proxy-authorization", true);
        request4.headersList.delete("cookie", true);
        request4.headersList.delete("host", true);
      }
      if (request4.body != null) {
        assert3(request4.body.source != null);
        request4.body = safelyExtractBody(request4.body.source)[0];
      }
      const timingInfo = fetchParams.timingInfo;
      timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
      if (timingInfo.redirectStartTime === 0) {
        timingInfo.redirectStartTime = timingInfo.startTime;
      }
      request4.urlList.push(locationURL);
      setRequestReferrerPolicyOnRedirect(request4, actualResponse);
      return mainFetch(fetchParams, true);
    }
    __name(httpRedirectFetch, "httpRedirectFetch");
    async function httpNetworkOrCacheFetch(fetchParams, isAuthenticationFetch = false, isNewConnectionFetch = false) {
      const request4 = fetchParams.request;
      let httpFetchParams = null;
      let httpRequest = null;
      let response = null;
      const httpCache = null;
      const revalidatingFlag = false;
      if (request4.window === "no-window" && request4.redirect === "error") {
        httpFetchParams = fetchParams;
        httpRequest = request4;
      } else {
        httpRequest = cloneRequest(request4);
        httpFetchParams = { ...fetchParams };
        httpFetchParams.request = httpRequest;
      }
      const includeCredentials = request4.credentials === "include" || request4.credentials === "same-origin" && request4.responseTainting === "basic";
      const contentLength = httpRequest.body ? httpRequest.body.length : null;
      let contentLengthHeaderValue = null;
      if (httpRequest.body == null && ["POST", "PUT"].includes(httpRequest.method)) {
        contentLengthHeaderValue = "0";
      }
      if (contentLength != null) {
        contentLengthHeaderValue = isomorphicEncode(`${contentLength}`);
      }
      if (contentLengthHeaderValue != null) {
        httpRequest.headersList.append("content-length", contentLengthHeaderValue, true);
      }
      if (contentLength != null && httpRequest.keepalive) {
      }
      if (webidl.is.URL(httpRequest.referrer)) {
        httpRequest.headersList.append("referer", isomorphicEncode(httpRequest.referrer.href), true);
      }
      appendRequestOriginHeader(httpRequest);
      appendFetchMetadata(httpRequest);
      if (!httpRequest.headersList.contains("user-agent", true)) {
        httpRequest.headersList.append("user-agent", defaultUserAgent, true);
      }
      if (httpRequest.cache === "default" && (httpRequest.headersList.contains("if-modified-since", true) || httpRequest.headersList.contains("if-none-match", true) || httpRequest.headersList.contains("if-unmodified-since", true) || httpRequest.headersList.contains("if-match", true) || httpRequest.headersList.contains("if-range", true))) {
        httpRequest.cache = "no-store";
      }
      if (httpRequest.cache === "no-cache" && !httpRequest.preventNoCacheCacheControlHeaderModification && !httpRequest.headersList.contains("cache-control", true)) {
        httpRequest.headersList.append("cache-control", "max-age=0", true);
      }
      if (httpRequest.cache === "no-store" || httpRequest.cache === "reload") {
        if (!httpRequest.headersList.contains("pragma", true)) {
          httpRequest.headersList.append("pragma", "no-cache", true);
        }
        if (!httpRequest.headersList.contains("cache-control", true)) {
          httpRequest.headersList.append("cache-control", "no-cache", true);
        }
      }
      if (httpRequest.headersList.contains("range", true)) {
        httpRequest.headersList.append("accept-encoding", "identity", true);
      }
      if (!httpRequest.headersList.contains("accept-encoding", true)) {
        if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
          httpRequest.headersList.append("accept-encoding", "br, gzip, deflate", true);
        } else {
          httpRequest.headersList.append("accept-encoding", "gzip, deflate", true);
        }
      }
      httpRequest.headersList.delete("host", true);
      if (includeCredentials) {
      }
      if (httpCache == null) {
        httpRequest.cache = "no-store";
      }
      if (httpRequest.cache !== "no-store" && httpRequest.cache !== "reload") {
      }
      if (response == null) {
        if (httpRequest.cache === "only-if-cached") {
          return makeNetworkError("only if cached");
        }
        const forwardResponse = await httpNetworkFetch(
          httpFetchParams,
          includeCredentials,
          isNewConnectionFetch
        );
        if (!safeMethodsSet.has(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399) {
        }
        if (revalidatingFlag && forwardResponse.status === 304) {
        }
        if (response == null) {
          response = forwardResponse;
        }
      }
      response.urlList = [...httpRequest.urlList];
      if (httpRequest.headersList.contains("range", true)) {
        response.rangeRequested = true;
      }
      response.requestIncludesCredentials = includeCredentials;
      if (response.status === 407) {
        if (request4.window === "no-window") {
          return makeNetworkError();
        }
        if (isCancelled(fetchParams)) {
          return makeAppropriateNetworkError(fetchParams);
        }
        return makeNetworkError("proxy authentication required");
      }
      if (
        // response’s status is 421
        response.status === 421 && // isNewConnectionFetch is false
        !isNewConnectionFetch && // request’s body is null, or request’s body is non-null and request’s body’s source is non-null
        (request4.body == null || request4.body.source != null)
      ) {
        if (isCancelled(fetchParams)) {
          return makeAppropriateNetworkError(fetchParams);
        }
        fetchParams.controller.connection.destroy();
        response = await httpNetworkOrCacheFetch(
          fetchParams,
          isAuthenticationFetch,
          true
        );
      }
      if (isAuthenticationFetch) {
      }
      return response;
    }
    __name(httpNetworkOrCacheFetch, "httpNetworkOrCacheFetch");
    async function httpNetworkFetch(fetchParams, includeCredentials = false, forceNewConnection = false) {
      assert3(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed);
      fetchParams.controller.connection = {
        abort: null,
        destroyed: false,
        destroy(err, abort = true) {
          if (!this.destroyed) {
            this.destroyed = true;
            if (abort) {
              this.abort?.(err ?? new DOMException("The operation was aborted.", "AbortError"));
            }
          }
        }
      };
      const request4 = fetchParams.request;
      let response = null;
      const timingInfo = fetchParams.timingInfo;
      const httpCache = null;
      if (httpCache == null) {
        request4.cache = "no-store";
      }
      const newConnection = forceNewConnection ? "yes" : "no";
      if (request4.mode === "websocket") {
      } else {
      }
      let requestBody = null;
      if (request4.body == null && fetchParams.processRequestEndOfBody) {
        queueMicrotask(() => fetchParams.processRequestEndOfBody());
      } else if (request4.body != null) {
        const processBodyChunk = /* @__PURE__ */ __name(async function* (bytes) {
          if (isCancelled(fetchParams)) {
            return;
          }
          yield bytes;
          fetchParams.processRequestBodyChunkLength?.(bytes.byteLength);
        }, "processBodyChunk");
        const processEndOfBody = /* @__PURE__ */ __name(() => {
          if (isCancelled(fetchParams)) {
            return;
          }
          if (fetchParams.processRequestEndOfBody) {
            fetchParams.processRequestEndOfBody();
          }
        }, "processEndOfBody");
        const processBodyError = /* @__PURE__ */ __name((e2) => {
          if (isCancelled(fetchParams)) {
            return;
          }
          if (e2.name === "AbortError") {
            fetchParams.controller.abort();
          } else {
            fetchParams.controller.terminate(e2);
          }
        }, "processBodyError");
        requestBody = async function* () {
          try {
            for await (const bytes of request4.body.stream) {
              yield* processBodyChunk(bytes);
            }
            processEndOfBody();
          } catch (err) {
            processBodyError(err);
          }
        }();
      }
      try {
        const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody });
        if (socket) {
          response = makeResponse({ status, statusText, headersList, socket });
        } else {
          const iterator = body[Symbol.asyncIterator]();
          fetchParams.controller.next = () => iterator.next();
          response = makeResponse({ status, statusText, headersList });
        }
      } catch (err) {
        if (err.name === "AbortError") {
          fetchParams.controller.connection.destroy();
          return makeAppropriateNetworkError(fetchParams, err);
        }
        return makeNetworkError(err);
      }
      const pullAlgorithm = /* @__PURE__ */ __name(() => {
        return fetchParams.controller.resume();
      }, "pullAlgorithm");
      const cancelAlgorithm = /* @__PURE__ */ __name((reason) => {
        if (!isCancelled(fetchParams)) {
          fetchParams.controller.abort(reason);
        }
      }, "cancelAlgorithm");
      const stream2 = new ReadableStream(
        {
          start(controller) {
            fetchParams.controller.controller = controller;
          },
          pull: pullAlgorithm,
          cancel: cancelAlgorithm,
          type: "bytes"
        }
      );
      response.body = { stream: stream2, source: null, length: null };
      if (!fetchParams.controller.resume) {
        fetchParams.controller.on("terminated", onAborted);
      }
      fetchParams.controller.resume = async () => {
        while (true) {
          let bytes;
          let isFailure;
          try {
            const { done, value } = await fetchParams.controller.next();
            if (isAborted2(fetchParams)) {
              break;
            }
            bytes = done ? void 0 : value;
          } catch (err) {
            if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
              bytes = void 0;
            } else {
              bytes = err;
              isFailure = true;
            }
          }
          if (bytes === void 0) {
            readableStreamClose(fetchParams.controller.controller);
            finalizeResponse2(fetchParams, response);
            return;
          }
          timingInfo.decodedBodySize += bytes?.byteLength ?? 0;
          if (isFailure) {
            fetchParams.controller.terminate(bytes);
            return;
          }
          const buffer = new Uint8Array(bytes);
          if (buffer.byteLength) {
            fetchParams.controller.controller.enqueue(buffer);
          }
          if (isErrored(stream2)) {
            fetchParams.controller.terminate();
            return;
          }
          if (fetchParams.controller.controller.desiredSize <= 0) {
            return;
          }
        }
      };
      function onAborted(reason) {
        if (isAborted2(fetchParams)) {
          response.aborted = true;
          if (isReadable2(stream2)) {
            fetchParams.controller.controller.error(
              fetchParams.controller.serializedAbortReason
            );
          }
        } else {
          if (isReadable2(stream2)) {
            fetchParams.controller.controller.error(new TypeError("terminated", {
              cause: isErrorLike(reason) ? reason : void 0
            }));
          }
        }
        fetchParams.controller.connection.destroy();
      }
      __name(onAborted, "onAborted");
      return response;
      function dispatch({ body }) {
        const url2 = requestCurrentURL(request4);
        const agent = fetchParams.controller.dispatcher;
        return new Promise((resolve24, reject) => agent.dispatch(
          {
            path: url2.pathname + url2.search,
            origin: url2.origin,
            method: request4.method,
            body: agent.isMockActive ? request4.body && (request4.body.source || request4.body.stream) : body,
            headers: request4.headersList.entries,
            maxRedirections: 0,
            upgrade: request4.mode === "websocket" ? "websocket" : void 0
          },
          {
            body: null,
            abort: null,
            onConnect(abort) {
              const { connection } = fetchParams.controller;
              timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(void 0, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability);
              if (connection.destroyed) {
                abort(new DOMException("The operation was aborted.", "AbortError"));
              } else {
                fetchParams.controller.on("terminated", abort);
                this.abort = connection.abort = abort;
              }
              timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
            },
            onResponseStarted() {
              timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
            },
            onHeaders(status, rawHeaders, resume, statusText) {
              if (status < 200) {
                return false;
              }
              let codings = [];
              const headersList = new HeadersList();
              for (let i = 0; i < rawHeaders.length; i += 2) {
                headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString("latin1"), true);
              }
              const contentEncoding = headersList.get("content-encoding", true);
              if (contentEncoding) {
                codings = contentEncoding.toLowerCase().split(",").map((x) => x.trim());
              }
              const location = headersList.get("location", true);
              this.body = new Readable4({ read: resume });
              const decoders = [];
              const willFollow = location && request4.redirect === "follow" && redirectStatusSet.has(status);
              if (codings.length !== 0 && request4.method !== "HEAD" && request4.method !== "CONNECT" && !nullBodyStatus.includes(status) && !willFollow) {
                for (let i = codings.length - 1; i >= 0; --i) {
                  const coding = codings[i];
                  if (coding === "x-gzip" || coding === "gzip") {
                    decoders.push(zlib2.createGunzip({
                      // Be less strict when decoding compressed responses, since sometimes
                      // servers send slightly invalid responses that are still accepted
                      // by common browsers.
                      // Always using Z_SYNC_FLUSH is what cURL does.
                      flush: zlib2.constants.Z_SYNC_FLUSH,
                      finishFlush: zlib2.constants.Z_SYNC_FLUSH
                    }));
                  } else if (coding === "deflate") {
                    decoders.push(createInflate({
                      flush: zlib2.constants.Z_SYNC_FLUSH,
                      finishFlush: zlib2.constants.Z_SYNC_FLUSH
                    }));
                  } else if (coding === "br") {
                    decoders.push(zlib2.createBrotliDecompress({
                      flush: zlib2.constants.BROTLI_OPERATION_FLUSH,
                      finishFlush: zlib2.constants.BROTLI_OPERATION_FLUSH
                    }));
                  } else if (coding === "zstd" && typeof zlib2.createZstdDecompress === "function") {
                    decoders.push(zlib2.createZstdDecompress({
                      flush: zlib2.constants.ZSTD_e_continue,
                      finishFlush: zlib2.constants.ZSTD_e_end
                    }));
                  } else {
                    decoders.length = 0;
                    break;
                  }
                }
              }
              const onError2 = this.onError.bind(this);
              resolve24({
                status,
                statusText,
                headersList,
                body: decoders.length ? pipeline(this.body, ...decoders, (err) => {
                  if (err) {
                    this.onError(err);
                  }
                }).on("error", onError2) : this.body.on("error", onError2)
              });
              return true;
            },
            onData(chunk) {
              if (fetchParams.controller.dump) {
                return;
              }
              const bytes = chunk;
              timingInfo.encodedBodySize += bytes.byteLength;
              return this.body.push(bytes);
            },
            onComplete() {
              if (this.abort) {
                fetchParams.controller.off("terminated", this.abort);
              }
              fetchParams.controller.ended = true;
              this.body.push(null);
            },
            onError(error) {
              if (this.abort) {
                fetchParams.controller.off("terminated", this.abort);
              }
              this.body?.destroy(error);
              fetchParams.controller.terminate(error);
              reject(error);
            },
            onUpgrade(status, rawHeaders, socket) {
              if (status !== 101) {
                return;
              }
              const headersList = new HeadersList();
              for (let i = 0; i < rawHeaders.length; i += 2) {
                headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString("latin1"), true);
              }
              resolve24({
                status,
                statusText: STATUS_CODES[status],
                headersList,
                socket
              });
              return true;
            }
          }
        ));
      }
      __name(dispatch, "dispatch");
    }
    __name(httpNetworkFetch, "httpNetworkFetch");
    module2.exports = {
      fetch: fetch2,
      Fetch,
      fetching,
      finalizeAndReportTiming
    };
  }
});

// node_modules/undici/lib/web/cache/util.js
var require_util3 = __commonJS({
  "node_modules/undici/lib/web/cache/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert3 = __require("node:assert");
    var { URLSerializer } = require_data_url();
    var { isValidHeaderName } = require_util2();
    function urlEquals(A, B, excludeFragment = false) {
      const serializedA = URLSerializer(A, excludeFragment);
      const serializedB = URLSerializer(B, excludeFragment);
      return serializedA === serializedB;
    }
    __name(urlEquals, "urlEquals");
    function getFieldValues(header) {
      assert3(header !== null);
      const values = [];
      for (let value of header.split(",")) {
        value = value.trim();
        if (isValidHeaderName(value)) {
          values.push(value);
        }
      }
      return values;
    }
    __name(getFieldValues, "getFieldValues");
    module2.exports = {
      urlEquals,
      getFieldValues
    };
  }
});

// node_modules/undici/lib/web/cache/cache.js
var require_cache3 = __commonJS({
  "node_modules/undici/lib/web/cache/cache.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var assert3 = __require("node:assert");
    var { kConstruct } = require_symbols();
    var { urlEquals, getFieldValues } = require_util3();
    var { kEnumerableProperty, isDisturbed } = require_util();
    var { webidl } = require_webidl();
    var { cloneResponse, fromInnerResponse, getResponseState } = require_response();
    var { Request: Request2, fromInnerRequest, getRequestState } = require_request2();
    var { fetching } = require_fetch();
    var { urlIsHttpHttpsScheme, readAllBytes } = require_util2();
    var { createDeferredPromise } = require_promise();
    var Cache = class _Cache {
      static {
        __name(this, "Cache");
      }
      /**
       * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list
       * @type {requestResponseList}
       */
      #relevantRequestResponseList;
      constructor() {
        if (arguments[0] !== kConstruct) {
          webidl.illegalConstructor();
        }
        webidl.util.markAsUncloneable(this);
        this.#relevantRequestResponseList = arguments[1];
      }
      async match(request4, options2 = {}) {
        webidl.brandCheck(this, _Cache);
        const prefix = "Cache.match";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        request4 = webidl.converters.RequestInfo(request4);
        options2 = webidl.converters.CacheQueryOptions(options2, prefix, "options");
        const p = this.#internalMatchAll(request4, options2, 1);
        if (p.length === 0) {
          return;
        }
        return p[0];
      }
      async matchAll(request4 = void 0, options2 = {}) {
        webidl.brandCheck(this, _Cache);
        const prefix = "Cache.matchAll";
        if (request4 !== void 0) request4 = webidl.converters.RequestInfo(request4);
        options2 = webidl.converters.CacheQueryOptions(options2, prefix, "options");
        return this.#internalMatchAll(request4, options2);
      }
      async add(request4) {
        webidl.brandCheck(this, _Cache);
        const prefix = "Cache.add";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        request4 = webidl.converters.RequestInfo(request4);
        const requests = [request4];
        const responseArrayPromise = this.addAll(requests);
        return await responseArrayPromise;
      }
      async addAll(requests) {
        webidl.brandCheck(this, _Cache);
        const prefix = "Cache.addAll";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        const responsePromises = [];
        const requestList = [];
        for (let request4 of requests) {
          if (request4 === void 0) {
            throw webidl.errors.conversionFailed({
              prefix,
              argument: "Argument 1",
              types: ["undefined is not allowed"]
            });
          }
          request4 = webidl.converters.RequestInfo(request4);
          if (typeof request4 === "string") {
            continue;
          }
          const r3 = getRequestState(request4);
          if (!urlIsHttpHttpsScheme(r3.url) || r3.method !== "GET") {
            throw webidl.errors.exception({
              header: prefix,
              message: "Expected http/s scheme when method is not GET."
            });
          }
        }
        const fetchControllers = [];
        for (const request4 of requests) {
          const r3 = getRequestState(new Request2(request4));
          if (!urlIsHttpHttpsScheme(r3.url)) {
            throw webidl.errors.exception({
              header: prefix,
              message: "Expected http/s scheme."
            });
          }
          r3.initiator = "fetch";
          r3.destination = "subresource";
          requestList.push(r3);
          const responsePromise = createDeferredPromise();
          fetchControllers.push(fetching({
            request: r3,
            processResponse(response) {
              if (response.type === "error" || response.status === 206 || response.status < 200 || response.status > 299) {
                responsePromise.reject(webidl.errors.exception({
                  header: "Cache.addAll",
                  message: "Received an invalid status code or the request failed."
                }));
              } else if (response.headersList.contains("vary")) {
                const fieldValues = getFieldValues(response.headersList.get("vary"));
                for (const fieldValue of fieldValues) {
                  if (fieldValue === "*") {
                    responsePromise.reject(webidl.errors.exception({
                      header: "Cache.addAll",
                      message: "invalid vary field value"
                    }));
                    for (const controller of fetchControllers) {
                      controller.abort();
                    }
                    return;
                  }
                }
              }
            },
            processResponseEndOfBody(response) {
              if (response.aborted) {
                responsePromise.reject(new DOMException("aborted", "AbortError"));
                return;
              }
              responsePromise.resolve(response);
            }
          }));
          responsePromises.push(responsePromise.promise);
        }
        const p = Promise.all(responsePromises);
        const responses = await p;
        const operations = [];
        let index = 0;
        for (const response of responses) {
          const operation = {
            type: "put",
            // 7.3.2
            request: requestList[index],
            // 7.3.3
            response
            // 7.3.4
          };
          operations.push(operation);
          index++;
        }
        const cacheJobPromise = createDeferredPromise();
        let errorData = null;
        try {
          this.#batchCacheOperations(operations);
        } catch (e2) {
          errorData = e2;
        }
        queueMicrotask(() => {
          if (errorData === null) {
            cacheJobPromise.resolve(void 0);
          } else {
            cacheJobPromise.reject(errorData);
          }
        });
        return cacheJobPromise.promise;
      }
      async put(request4, response) {
        webidl.brandCheck(this, _Cache);
        const prefix = "Cache.put";
        webidl.argumentLengthCheck(arguments, 2, prefix);
        request4 = webidl.converters.RequestInfo(request4);
        response = webidl.converters.Response(response, prefix, "response");
        let innerRequest = null;
        if (webidl.is.Request(request4)) {
          innerRequest = getRequestState(request4);
        } else {
          innerRequest = getRequestState(new Request2(request4));
        }
        if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== "GET") {
          throw webidl.errors.exception({
            header: prefix,
            message: "Expected an http/s scheme when method is not GET"
          });
        }
        const innerResponse = getResponseState(response);
        if (innerResponse.status === 206) {
          throw webidl.errors.exception({
            header: prefix,
            message: "Got 206 status"
          });
        }
        if (innerResponse.headersList.contains("vary")) {
          const fieldValues = getFieldValues(innerResponse.headersList.get("vary"));
          for (const fieldValue of fieldValues) {
            if (fieldValue === "*") {
              throw webidl.errors.exception({
                header: prefix,
                message: "Got * vary field value"
              });
            }
          }
        }
        if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {
          throw webidl.errors.exception({
            header: prefix,
            message: "Response body is locked or disturbed"
          });
        }
        const clonedResponse = cloneResponse(innerResponse);
        const bodyReadPromise = createDeferredPromise();
        if (innerResponse.body != null) {
          const stream2 = innerResponse.body.stream;
          const reader = stream2.getReader();
          readAllBytes(reader, bodyReadPromise.resolve, bodyReadPromise.reject);
        } else {
          bodyReadPromise.resolve(void 0);
        }
        const operations = [];
        const operation = {
          type: "put",
          // 14.
          request: innerRequest,
          // 15.
          response: clonedResponse
          // 16.
        };
        operations.push(operation);
        const bytes = await bodyReadPromise.promise;
        if (clonedResponse.body != null) {
          clonedResponse.body.source = bytes;
        }
        const cacheJobPromise = createDeferredPromise();
        let errorData = null;
        try {
          this.#batchCacheOperations(operations);
        } catch (e2) {
          errorData = e2;
        }
        queueMicrotask(() => {
          if (errorData === null) {
            cacheJobPromise.resolve();
          } else {
            cacheJobPromise.reject(errorData);
          }
        });
        return cacheJobPromise.promise;
      }
      async delete(request4, options2 = {}) {
        webidl.brandCheck(this, _Cache);
        const prefix = "Cache.delete";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        request4 = webidl.converters.RequestInfo(request4);
        options2 = webidl.converters.CacheQueryOptions(options2, prefix, "options");
        let r3 = null;
        if (webidl.is.Request(request4)) {
          r3 = getRequestState(request4);
          if (r3.method !== "GET" && !options2.ignoreMethod) {
            return false;
          }
        } else {
          assert3(typeof request4 === "string");
          r3 = getRequestState(new Request2(request4));
        }
        const operations = [];
        const operation = {
          type: "delete",
          request: r3,
          options: options2
        };
        operations.push(operation);
        const cacheJobPromise = createDeferredPromise();
        let errorData = null;
        let requestResponses;
        try {
          requestResponses = this.#batchCacheOperations(operations);
        } catch (e2) {
          errorData = e2;
        }
        queueMicrotask(() => {
          if (errorData === null) {
            cacheJobPromise.resolve(!!requestResponses?.length);
          } else {
            cacheJobPromise.reject(errorData);
          }
        });
        return cacheJobPromise.promise;
      }
      /**
       * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys
       * @param {any} request
       * @param {import('../../../types/cache').CacheQueryOptions} options
       * @returns {Promise<readonly Request[]>}
       */
      async keys(request4 = void 0, options2 = {}) {
        webidl.brandCheck(this, _Cache);
        const prefix = "Cache.keys";
        if (request4 !== void 0) request4 = webidl.converters.RequestInfo(request4);
        options2 = webidl.converters.CacheQueryOptions(options2, prefix, "options");
        let r3 = null;
        if (request4 !== void 0) {
          if (webidl.is.Request(request4)) {
            r3 = getRequestState(request4);
            if (r3.method !== "GET" && !options2.ignoreMethod) {
              return [];
            }
          } else if (typeof request4 === "string") {
            r3 = getRequestState(new Request2(request4));
          }
        }
        const promise = createDeferredPromise();
        const requests = [];
        if (request4 === void 0) {
          for (const requestResponse of this.#relevantRequestResponseList) {
            requests.push(requestResponse[0]);
          }
        } else {
          const requestResponses = this.#queryCache(r3, options2);
          for (const requestResponse of requestResponses) {
            requests.push(requestResponse[0]);
          }
        }
        queueMicrotask(() => {
          const requestList = [];
          for (const request5 of requests) {
            const requestObject = fromInnerRequest(
              request5,
              void 0,
              new AbortController().signal,
              "immutable"
            );
            requestList.push(requestObject);
          }
          promise.resolve(Object.freeze(requestList));
        });
        return promise.promise;
      }
      /**
       * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm
       * @param {CacheBatchOperation[]} operations
       * @returns {requestResponseList}
       */
      #batchCacheOperations(operations) {
        const cache5 = this.#relevantRequestResponseList;
        const backupCache = [...cache5];
        const addedItems = [];
        const resultList = [];
        try {
          for (const operation of operations) {
            if (operation.type !== "delete" && operation.type !== "put") {
              throw webidl.errors.exception({
                header: "Cache.#batchCacheOperations",
                message: 'operation type does not match "delete" or "put"'
              });
            }
            if (operation.type === "delete" && operation.response != null) {
              throw webidl.errors.exception({
                header: "Cache.#batchCacheOperations",
                message: "delete operation should not have an associated response"
              });
            }
            if (this.#queryCache(operation.request, operation.options, addedItems).length) {
              throw new DOMException("???", "InvalidStateError");
            }
            let requestResponses;
            if (operation.type === "delete") {
              requestResponses = this.#queryCache(operation.request, operation.options);
              if (requestResponses.length === 0) {
                return [];
              }
              for (const requestResponse of requestResponses) {
                const idx = cache5.indexOf(requestResponse);
                assert3(idx !== -1);
                cache5.splice(idx, 1);
              }
            } else if (operation.type === "put") {
              if (operation.response == null) {
                throw webidl.errors.exception({
                  header: "Cache.#batchCacheOperations",
                  message: "put operation should have an associated response"
                });
              }
              const r3 = operation.request;
              if (!urlIsHttpHttpsScheme(r3.url)) {
                throw webidl.errors.exception({
                  header: "Cache.#batchCacheOperations",
                  message: "expected http or https scheme"
                });
              }
              if (r3.method !== "GET") {
                throw webidl.errors.exception({
                  header: "Cache.#batchCacheOperations",
                  message: "not get method"
                });
              }
              if (operation.options != null) {
                throw webidl.errors.exception({
                  header: "Cache.#batchCacheOperations",
                  message: "options must not be defined"
                });
              }
              requestResponses = this.#queryCache(operation.request);
              for (const requestResponse of requestResponses) {
                const idx = cache5.indexOf(requestResponse);
                assert3(idx !== -1);
                cache5.splice(idx, 1);
              }
              cache5.push([operation.request, operation.response]);
              addedItems.push([operation.request, operation.response]);
            }
            resultList.push([operation.request, operation.response]);
          }
          return resultList;
        } catch (e2) {
          this.#relevantRequestResponseList.length = 0;
          this.#relevantRequestResponseList = backupCache;
          throw e2;
        }
      }
      /**
       * @see https://w3c.github.io/ServiceWorker/#query-cache
       * @param {any} requestQuery
       * @param {import('../../../types/cache').CacheQueryOptions} options
       * @param {requestResponseList} targetStorage
       * @returns {requestResponseList}
       */
      #queryCache(requestQuery, options2, targetStorage) {
        const resultList = [];
        const storage = targetStorage ?? this.#relevantRequestResponseList;
        for (const requestResponse of storage) {
          const [cachedRequest, cachedResponse] = requestResponse;
          if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options2)) {
            resultList.push(requestResponse);
          }
        }
        return resultList;
      }
      /**
       * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm
       * @param {any} requestQuery
       * @param {any} request
       * @param {any | null} response
       * @param {import('../../../types/cache').CacheQueryOptions | undefined} options
       * @returns {boolean}
       */
      #requestMatchesCachedItem(requestQuery, request4, response = null, options2) {
        const queryURL = new URL(requestQuery.url);
        const cachedURL = new URL(request4.url);
        if (options2?.ignoreSearch) {
          cachedURL.search = "";
          queryURL.search = "";
        }
        if (!urlEquals(queryURL, cachedURL, true)) {
          return false;
        }
        if (response == null || options2?.ignoreVary || !response.headersList.contains("vary")) {
          return true;
        }
        const fieldValues = getFieldValues(response.headersList.get("vary"));
        for (const fieldValue of fieldValues) {
          if (fieldValue === "*") {
            return false;
          }
          const requestValue = request4.headersList.get(fieldValue);
          const queryValue = requestQuery.headersList.get(fieldValue);
          if (requestValue !== queryValue) {
            return false;
          }
        }
        return true;
      }
      #internalMatchAll(request4, options2, maxResponses = Infinity) {
        let r3 = null;
        if (request4 !== void 0) {
          if (webidl.is.Request(request4)) {
            r3 = getRequestState(request4);
            if (r3.method !== "GET" && !options2.ignoreMethod) {
              return [];
            }
          } else if (typeof request4 === "string") {
            r3 = getRequestState(new Request2(request4));
          }
        }
        const responses = [];
        if (request4 === void 0) {
          for (const requestResponse of this.#relevantRequestResponseList) {
            responses.push(requestResponse[1]);
          }
        } else {
          const requestResponses = this.#queryCache(r3, options2);
          for (const requestResponse of requestResponses) {
            responses.push(requestResponse[1]);
          }
        }
        const responseList = [];
        for (const response of responses) {
          const responseObject = fromInnerResponse(response, "immutable");
          responseList.push(responseObject.clone());
          if (responseList.length >= maxResponses) {
            break;
          }
        }
        return Object.freeze(responseList);
      }
    };
    Object.defineProperties(Cache.prototype, {
      [Symbol.toStringTag]: {
        value: "Cache",
        configurable: true
      },
      match: kEnumerableProperty,
      matchAll: kEnumerableProperty,
      add: kEnumerableProperty,
      addAll: kEnumerableProperty,
      put: kEnumerableProperty,
      delete: kEnumerableProperty,
      keys: kEnumerableProperty
    });
    var cacheQueryOptionConverters = [
      {
        key: "ignoreSearch",
        converter: webidl.converters.boolean,
        defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
      },
      {
        key: "ignoreMethod",
        converter: webidl.converters.boolean,
        defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
      },
      {
        key: "ignoreVary",
        converter: webidl.converters.boolean,
        defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
      }
    ];
    webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters);
    webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([
      ...cacheQueryOptionConverters,
      {
        key: "cacheName",
        converter: webidl.converters.DOMString
      }
    ]);
    webidl.converters.Response = webidl.interfaceConverter(
      webidl.is.Response,
      "Response"
    );
    webidl.converters["sequence<RequestInfo>"] = webidl.sequenceConverter(
      webidl.converters.RequestInfo
    );
    module2.exports = {
      Cache
    };
  }
});

// node_modules/undici/lib/web/cache/cachestorage.js
var require_cachestorage = __commonJS({
  "node_modules/undici/lib/web/cache/cachestorage.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Cache } = require_cache3();
    var { webidl } = require_webidl();
    var { kEnumerableProperty } = require_util();
    var { kConstruct } = require_symbols();
    var CacheStorage = class _CacheStorage {
      static {
        __name(this, "CacheStorage");
      }
      /**
       * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map
       * @type {Map<string, import('./cache').requestResponseList}
       */
      #caches = /* @__PURE__ */ new Map();
      constructor() {
        if (arguments[0] !== kConstruct) {
          webidl.illegalConstructor();
        }
        webidl.util.markAsUncloneable(this);
      }
      async match(request4, options2 = {}) {
        webidl.brandCheck(this, _CacheStorage);
        webidl.argumentLengthCheck(arguments, 1, "CacheStorage.match");
        request4 = webidl.converters.RequestInfo(request4);
        options2 = webidl.converters.MultiCacheQueryOptions(options2);
        if (options2.cacheName != null) {
          if (this.#caches.has(options2.cacheName)) {
            const cacheList = this.#caches.get(options2.cacheName);
            const cache5 = new Cache(kConstruct, cacheList);
            return await cache5.match(request4, options2);
          }
        } else {
          for (const cacheList of this.#caches.values()) {
            const cache5 = new Cache(kConstruct, cacheList);
            const response = await cache5.match(request4, options2);
            if (response !== void 0) {
              return response;
            }
          }
        }
      }
      /**
       * @see https://w3c.github.io/ServiceWorker/#cache-storage-has
       * @param {string} cacheName
       * @returns {Promise<boolean>}
       */
      async has(cacheName) {
        webidl.brandCheck(this, _CacheStorage);
        const prefix = "CacheStorage.has";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        cacheName = webidl.converters.DOMString(cacheName, prefix, "cacheName");
        return this.#caches.has(cacheName);
      }
      /**
       * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open
       * @param {string} cacheName
       * @returns {Promise<Cache>}
       */
      async open(cacheName) {
        webidl.brandCheck(this, _CacheStorage);
        const prefix = "CacheStorage.open";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        cacheName = webidl.converters.DOMString(cacheName, prefix, "cacheName");
        if (this.#caches.has(cacheName)) {
          const cache6 = this.#caches.get(cacheName);
          return new Cache(kConstruct, cache6);
        }
        const cache5 = [];
        this.#caches.set(cacheName, cache5);
        return new Cache(kConstruct, cache5);
      }
      /**
       * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
       * @param {string} cacheName
       * @returns {Promise<boolean>}
       */
      async delete(cacheName) {
        webidl.brandCheck(this, _CacheStorage);
        const prefix = "CacheStorage.delete";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        cacheName = webidl.converters.DOMString(cacheName, prefix, "cacheName");
        return this.#caches.delete(cacheName);
      }
      /**
       * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys
       * @returns {Promise<string[]>}
       */
      async keys() {
        webidl.brandCheck(this, _CacheStorage);
        const keys = this.#caches.keys();
        return [...keys];
      }
    };
    Object.defineProperties(CacheStorage.prototype, {
      [Symbol.toStringTag]: {
        value: "CacheStorage",
        configurable: true
      },
      match: kEnumerableProperty,
      has: kEnumerableProperty,
      open: kEnumerableProperty,
      delete: kEnumerableProperty,
      keys: kEnumerableProperty
    });
    module2.exports = {
      CacheStorage
    };
  }
});

// node_modules/undici/lib/web/cookies/constants.js
var require_constants6 = __commonJS({
  "node_modules/undici/lib/web/cookies/constants.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var maxAttributeValueSize = 1024;
    var maxNameValuePairSize = 4096;
    module2.exports = {
      maxAttributeValueSize,
      maxNameValuePairSize
    };
  }
});

// node_modules/undici/lib/web/cookies/util.js
var require_util4 = __commonJS({
  "node_modules/undici/lib/web/cookies/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    function isCTLExcludingHtab(value) {
      for (let i = 0; i < value.length; ++i) {
        const code2 = value.charCodeAt(i);
        if (code2 >= 0 && code2 <= 8 || code2 >= 10 && code2 <= 31 || code2 === 127) {
          return true;
        }
      }
      return false;
    }
    __name(isCTLExcludingHtab, "isCTLExcludingHtab");
    function validateCookieName(name3) {
      for (let i = 0; i < name3.length; ++i) {
        const code2 = name3.charCodeAt(i);
        if (code2 < 33 || // exclude CTLs (0-31), SP and HT
        code2 > 126 || // exclude non-ascii and DEL
        code2 === 34 || // "
        code2 === 40 || // (
        code2 === 41 || // )
        code2 === 60 || // <
        code2 === 62 || // >
        code2 === 64 || // @
        code2 === 44 || // ,
        code2 === 59 || // ;
        code2 === 58 || // :
        code2 === 92 || // \
        code2 === 47 || // /
        code2 === 91 || // [
        code2 === 93 || // ]
        code2 === 63 || // ?
        code2 === 61 || // =
        code2 === 123 || // {
        code2 === 125) {
          throw new Error("Invalid cookie name");
        }
      }
    }
    __name(validateCookieName, "validateCookieName");
    function validateCookieValue(value) {
      let len = value.length;
      let i = 0;
      if (value[0] === '"') {
        if (len === 1 || value[len - 1] !== '"') {
          throw new Error("Invalid cookie value");
        }
        --len;
        ++i;
      }
      while (i < len) {
        const code2 = value.charCodeAt(i++);
        if (code2 < 33 || // exclude CTLs (0-31)
        code2 > 126 || // non-ascii and DEL (127)
        code2 === 34 || // "
        code2 === 44 || // ,
        code2 === 59 || // ;
        code2 === 92) {
          throw new Error("Invalid cookie value");
        }
      }
    }
    __name(validateCookieValue, "validateCookieValue");
    function validateCookiePath(path108) {
      for (let i = 0; i < path108.length; ++i) {
        const code2 = path108.charCodeAt(i);
        if (code2 < 32 || // exclude CTLs (0-31)
        code2 === 127 || // DEL
        code2 === 59) {
          throw new Error("Invalid cookie path");
        }
      }
    }
    __name(validateCookiePath, "validateCookiePath");
    function validateCookieDomain(domain) {
      if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) {
        throw new Error("Invalid cookie domain");
      }
    }
    __name(validateCookieDomain, "validateCookieDomain");
    var IMFDays = [
      "Sun",
      "Mon",
      "Tue",
      "Wed",
      "Thu",
      "Fri",
      "Sat"
    ];
    var IMFMonths = [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec"
    ];
    var IMFPaddedNumbers = Array(61).fill(0).map((_, i) => i.toString().padStart(2, "0"));
    function toIMFDate(date) {
      if (typeof date === "number") {
        date = new Date(date);
      }
      return `${IMFDays[date.getUTCDay()]}, ${IMFPaddedNumbers[date.getUTCDate()]} ${IMFMonths[date.getUTCMonth()]} ${date.getUTCFullYear()} ${IMFPaddedNumbers[date.getUTCHours()]}:${IMFPaddedNumbers[date.getUTCMinutes()]}:${IMFPaddedNumbers[date.getUTCSeconds()]} GMT`;
    }
    __name(toIMFDate, "toIMFDate");
    function validateCookieMaxAge(maxAge) {
      if (maxAge < 0) {
        throw new Error("Invalid cookie max-age");
      }
    }
    __name(validateCookieMaxAge, "validateCookieMaxAge");
    function stringify5(cookie) {
      if (cookie.name.length === 0) {
        return null;
      }
      validateCookieName(cookie.name);
      validateCookieValue(cookie.value);
      const out = [`${cookie.name}=${cookie.value}`];
      if (cookie.name.startsWith("__Secure-")) {
        cookie.secure = true;
      }
      if (cookie.name.startsWith("__Host-")) {
        cookie.secure = true;
        cookie.domain = null;
        cookie.path = "/";
      }
      if (cookie.secure) {
        out.push("Secure");
      }
      if (cookie.httpOnly) {
        out.push("HttpOnly");
      }
      if (typeof cookie.maxAge === "number") {
        validateCookieMaxAge(cookie.maxAge);
        out.push(`Max-Age=${cookie.maxAge}`);
      }
      if (cookie.domain) {
        validateCookieDomain(cookie.domain);
        out.push(`Domain=${cookie.domain}`);
      }
      if (cookie.path) {
        validateCookiePath(cookie.path);
        out.push(`Path=${cookie.path}`);
      }
      if (cookie.expires && cookie.expires.toString() !== "Invalid Date") {
        out.push(`Expires=${toIMFDate(cookie.expires)}`);
      }
      if (cookie.sameSite) {
        out.push(`SameSite=${cookie.sameSite}`);
      }
      for (const part of cookie.unparsed) {
        if (!part.includes("=")) {
          throw new Error("Invalid unparsed");
        }
        const [key, ...value] = part.split("=");
        out.push(`${key.trim()}=${value.join("=")}`);
      }
      return out.join("; ");
    }
    __name(stringify5, "stringify");
    module2.exports = {
      isCTLExcludingHtab,
      validateCookieName,
      validateCookiePath,
      validateCookieValue,
      toIMFDate,
      stringify: stringify5
    };
  }
});

// node_modules/undici/lib/web/cookies/parse.js
var require_parse = __commonJS({
  "node_modules/undici/lib/web/cookies/parse.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { maxNameValuePairSize, maxAttributeValueSize } = require_constants6();
    var { isCTLExcludingHtab } = require_util4();
    var { collectASequenceOfCodePointsFast } = require_data_url();
    var assert3 = __require("node:assert");
    var { unescape: qsUnescape } = __require("node:querystring");
    function parseSetCookie(header) {
      if (isCTLExcludingHtab(header)) {
        return null;
      }
      let nameValuePair = "";
      let unparsedAttributes = "";
      let name3 = "";
      let value = "";
      if (header.includes(";")) {
        const position = { position: 0 };
        nameValuePair = collectASequenceOfCodePointsFast(";", header, position);
        unparsedAttributes = header.slice(position.position);
      } else {
        nameValuePair = header;
      }
      if (!nameValuePair.includes("=")) {
        value = nameValuePair;
      } else {
        const position = { position: 0 };
        name3 = collectASequenceOfCodePointsFast(
          "=",
          nameValuePair,
          position
        );
        value = nameValuePair.slice(position.position + 1);
      }
      name3 = name3.trim();
      value = value.trim();
      if (name3.length + value.length > maxNameValuePairSize) {
        return null;
      }
      return {
        name: name3,
        value: qsUnescape(value),
        ...parseUnparsedAttributes(unparsedAttributes)
      };
    }
    __name(parseSetCookie, "parseSetCookie");
    function parseUnparsedAttributes(unparsedAttributes, cookieAttributeList = {}) {
      if (unparsedAttributes.length === 0) {
        return cookieAttributeList;
      }
      assert3(unparsedAttributes[0] === ";");
      unparsedAttributes = unparsedAttributes.slice(1);
      let cookieAv = "";
      if (unparsedAttributes.includes(";")) {
        cookieAv = collectASequenceOfCodePointsFast(
          ";",
          unparsedAttributes,
          { position: 0 }
        );
        unparsedAttributes = unparsedAttributes.slice(cookieAv.length);
      } else {
        cookieAv = unparsedAttributes;
        unparsedAttributes = "";
      }
      let attributeName = "";
      let attributeValue = "";
      if (cookieAv.includes("=")) {
        const position = { position: 0 };
        attributeName = collectASequenceOfCodePointsFast(
          "=",
          cookieAv,
          position
        );
        attributeValue = cookieAv.slice(position.position + 1);
      } else {
        attributeName = cookieAv;
      }
      attributeName = attributeName.trim();
      attributeValue = attributeValue.trim();
      if (attributeValue.length > maxAttributeValueSize) {
        return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList);
      }
      const attributeNameLowercase = attributeName.toLowerCase();
      if (attributeNameLowercase === "expires") {
        const expiryTime = new Date(attributeValue);
        cookieAttributeList.expires = expiryTime;
      } else if (attributeNameLowercase === "max-age") {
        const charCode = attributeValue.charCodeAt(0);
        if ((charCode < 48 || charCode > 57) && attributeValue[0] !== "-") {
          return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList);
        }
        if (!/^\d+$/.test(attributeValue)) {
          return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList);
        }
        const deltaSeconds = Number(attributeValue);
        cookieAttributeList.maxAge = deltaSeconds;
      } else if (attributeNameLowercase === "domain") {
        let cookieDomain = attributeValue;
        if (cookieDomain[0] === ".") {
          cookieDomain = cookieDomain.slice(1);
        }
        cookieDomain = cookieDomain.toLowerCase();
        cookieAttributeList.domain = cookieDomain;
      } else if (attributeNameLowercase === "path") {
        let cookiePath = "";
        if (attributeValue.length === 0 || attributeValue[0] !== "/") {
          cookiePath = "/";
        } else {
          cookiePath = attributeValue;
        }
        cookieAttributeList.path = cookiePath;
      } else if (attributeNameLowercase === "secure") {
        cookieAttributeList.secure = true;
      } else if (attributeNameLowercase === "httponly") {
        cookieAttributeList.httpOnly = true;
      } else if (attributeNameLowercase === "samesite") {
        let enforcement = "Default";
        const attributeValueLowercase = attributeValue.toLowerCase();
        if (attributeValueLowercase.includes("none")) {
          enforcement = "None";
        }
        if (attributeValueLowercase.includes("strict")) {
          enforcement = "Strict";
        }
        if (attributeValueLowercase.includes("lax")) {
          enforcement = "Lax";
        }
        cookieAttributeList.sameSite = enforcement;
      } else {
        cookieAttributeList.unparsed ??= [];
        cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`);
      }
      return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList);
    }
    __name(parseUnparsedAttributes, "parseUnparsedAttributes");
    module2.exports = {
      parseSetCookie,
      parseUnparsedAttributes
    };
  }
});

// node_modules/undici/lib/web/cookies/index.js
var require_cookies = __commonJS({
  "node_modules/undici/lib/web/cookies/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { parseSetCookie } = require_parse();
    var { stringify: stringify5 } = require_util4();
    var { webidl } = require_webidl();
    var { Headers: Headers2 } = require_headers();
    var brandChecks = webidl.brandCheckMultiple([Headers2, globalThis.Headers].filter(Boolean));
    function getCookies(headers) {
      webidl.argumentLengthCheck(arguments, 1, "getCookies");
      brandChecks(headers);
      const cookie = headers.get("cookie");
      const out = {};
      if (!cookie) {
        return out;
      }
      for (const piece of cookie.split(";")) {
        const [name3, ...value] = piece.split("=");
        out[name3.trim()] = value.join("=");
      }
      return out;
    }
    __name(getCookies, "getCookies");
    function deleteCookie(headers, name3, attributes) {
      brandChecks(headers);
      const prefix = "deleteCookie";
      webidl.argumentLengthCheck(arguments, 2, prefix);
      name3 = webidl.converters.DOMString(name3, prefix, "name");
      attributes = webidl.converters.DeleteCookieAttributes(attributes);
      setCookie(headers, {
        name: name3,
        value: "",
        expires: /* @__PURE__ */ new Date(0),
        ...attributes
      });
    }
    __name(deleteCookie, "deleteCookie");
    function getSetCookies(headers) {
      webidl.argumentLengthCheck(arguments, 1, "getSetCookies");
      brandChecks(headers);
      const cookies = headers.getSetCookie();
      if (!cookies) {
        return [];
      }
      return cookies.map((pair) => parseSetCookie(pair));
    }
    __name(getSetCookies, "getSetCookies");
    function parseCookie(cookie) {
      cookie = webidl.converters.DOMString(cookie);
      return parseSetCookie(cookie);
    }
    __name(parseCookie, "parseCookie");
    function setCookie(headers, cookie) {
      webidl.argumentLengthCheck(arguments, 2, "setCookie");
      brandChecks(headers);
      cookie = webidl.converters.Cookie(cookie);
      const str2 = stringify5(cookie);
      if (str2) {
        headers.append("set-cookie", str2, true);
      }
    }
    __name(setCookie, "setCookie");
    webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([
      {
        converter: webidl.nullableConverter(webidl.converters.DOMString),
        key: "path",
        defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
      },
      {
        converter: webidl.nullableConverter(webidl.converters.DOMString),
        key: "domain",
        defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
      }
    ]);
    webidl.converters.Cookie = webidl.dictionaryConverter([
      {
        converter: webidl.converters.DOMString,
        key: "name"
      },
      {
        converter: webidl.converters.DOMString,
        key: "value"
      },
      {
        converter: webidl.nullableConverter((value) => {
          if (typeof value === "number") {
            return webidl.converters["unsigned long long"](value);
          }
          return new Date(value);
        }),
        key: "expires",
        defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
      },
      {
        converter: webidl.nullableConverter(webidl.converters["long long"]),
        key: "maxAge",
        defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
      },
      {
        converter: webidl.nullableConverter(webidl.converters.DOMString),
        key: "domain",
        defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
      },
      {
        converter: webidl.nullableConverter(webidl.converters.DOMString),
        key: "path",
        defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
      },
      {
        converter: webidl.nullableConverter(webidl.converters.boolean),
        key: "secure",
        defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
      },
      {
        converter: webidl.nullableConverter(webidl.converters.boolean),
        key: "httpOnly",
        defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
      },
      {
        converter: webidl.converters.USVString,
        key: "sameSite",
        allowedValues: ["Strict", "Lax", "None"]
      },
      {
        converter: webidl.sequenceConverter(webidl.converters.DOMString),
        key: "unparsed",
        defaultValue: /* @__PURE__ */ __name(() => new Array(0), "defaultValue")
      }
    ]);
    module2.exports = {
      getCookies,
      deleteCookie,
      getSetCookies,
      setCookie,
      parseCookie
    };
  }
});

// node_modules/undici/lib/web/websocket/events.js
var require_events = __commonJS({
  "node_modules/undici/lib/web/websocket/events.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { webidl } = require_webidl();
    var { kEnumerableProperty } = require_util();
    var { kConstruct } = require_symbols();
    var MessageEvent2 = class _MessageEvent extends Event {
      static {
        __name(this, "MessageEvent");
      }
      #eventInit;
      constructor(type, eventInitDict = {}) {
        if (type === kConstruct) {
          super(arguments[1], arguments[2]);
          webidl.util.markAsUncloneable(this);
          return;
        }
        const prefix = "MessageEvent constructor";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        type = webidl.converters.DOMString(type, prefix, "type");
        eventInitDict = webidl.converters.MessageEventInit(eventInitDict, prefix, "eventInitDict");
        super(type, eventInitDict);
        this.#eventInit = eventInitDict;
        webidl.util.markAsUncloneable(this);
      }
      get data() {
        webidl.brandCheck(this, _MessageEvent);
        return this.#eventInit.data;
      }
      get origin() {
        webidl.brandCheck(this, _MessageEvent);
        return this.#eventInit.origin;
      }
      get lastEventId() {
        webidl.brandCheck(this, _MessageEvent);
        return this.#eventInit.lastEventId;
      }
      get source() {
        webidl.brandCheck(this, _MessageEvent);
        return this.#eventInit.source;
      }
      get ports() {
        webidl.brandCheck(this, _MessageEvent);
        if (!Object.isFrozen(this.#eventInit.ports)) {
          Object.freeze(this.#eventInit.ports);
        }
        return this.#eventInit.ports;
      }
      initMessageEvent(type, bubbles = false, cancelable = false, data = null, origin = "", lastEventId = "", source2 = null, ports2 = []) {
        webidl.brandCheck(this, _MessageEvent);
        webidl.argumentLengthCheck(arguments, 1, "MessageEvent.initMessageEvent");
        return new _MessageEvent(type, {
          bubbles,
          cancelable,
          data,
          origin,
          lastEventId,
          source: source2,
          ports: ports2
        });
      }
      static createFastMessageEvent(type, init) {
        const messageEvent = new _MessageEvent(kConstruct, type, init);
        messageEvent.#eventInit = init;
        messageEvent.#eventInit.data ??= null;
        messageEvent.#eventInit.origin ??= "";
        messageEvent.#eventInit.lastEventId ??= "";
        messageEvent.#eventInit.source ??= null;
        messageEvent.#eventInit.ports ??= [];
        return messageEvent;
      }
    };
    var { createFastMessageEvent } = MessageEvent2;
    delete MessageEvent2.createFastMessageEvent;
    var CloseEvent = class _CloseEvent extends Event {
      static {
        __name(this, "CloseEvent");
      }
      #eventInit;
      constructor(type, eventInitDict = {}) {
        const prefix = "CloseEvent constructor";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        type = webidl.converters.DOMString(type, prefix, "type");
        eventInitDict = webidl.converters.CloseEventInit(eventInitDict);
        super(type, eventInitDict);
        this.#eventInit = eventInitDict;
        webidl.util.markAsUncloneable(this);
      }
      get wasClean() {
        webidl.brandCheck(this, _CloseEvent);
        return this.#eventInit.wasClean;
      }
      get code() {
        webidl.brandCheck(this, _CloseEvent);
        return this.#eventInit.code;
      }
      get reason() {
        webidl.brandCheck(this, _CloseEvent);
        return this.#eventInit.reason;
      }
    };
    var ErrorEvent2 = class _ErrorEvent extends Event {
      static {
        __name(this, "ErrorEvent");
      }
      #eventInit;
      constructor(type, eventInitDict) {
        const prefix = "ErrorEvent constructor";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        super(type, eventInitDict);
        webidl.util.markAsUncloneable(this);
        type = webidl.converters.DOMString(type, prefix, "type");
        eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {});
        this.#eventInit = eventInitDict;
      }
      get message() {
        webidl.brandCheck(this, _ErrorEvent);
        return this.#eventInit.message;
      }
      get filename() {
        webidl.brandCheck(this, _ErrorEvent);
        return this.#eventInit.filename;
      }
      get lineno() {
        webidl.brandCheck(this, _ErrorEvent);
        return this.#eventInit.lineno;
      }
      get colno() {
        webidl.brandCheck(this, _ErrorEvent);
        return this.#eventInit.colno;
      }
      get error() {
        webidl.brandCheck(this, _ErrorEvent);
        return this.#eventInit.error;
      }
    };
    Object.defineProperties(MessageEvent2.prototype, {
      [Symbol.toStringTag]: {
        value: "MessageEvent",
        configurable: true
      },
      data: kEnumerableProperty,
      origin: kEnumerableProperty,
      lastEventId: kEnumerableProperty,
      source: kEnumerableProperty,
      ports: kEnumerableProperty,
      initMessageEvent: kEnumerableProperty
    });
    Object.defineProperties(CloseEvent.prototype, {
      [Symbol.toStringTag]: {
        value: "CloseEvent",
        configurable: true
      },
      reason: kEnumerableProperty,
      code: kEnumerableProperty,
      wasClean: kEnumerableProperty
    });
    Object.defineProperties(ErrorEvent2.prototype, {
      [Symbol.toStringTag]: {
        value: "ErrorEvent",
        configurable: true
      },
      message: kEnumerableProperty,
      filename: kEnumerableProperty,
      lineno: kEnumerableProperty,
      colno: kEnumerableProperty,
      error: kEnumerableProperty
    });
    webidl.converters.MessagePort = webidl.interfaceConverter(
      webidl.is.MessagePort,
      "MessagePort"
    );
    webidl.converters["sequence<MessagePort>"] = webidl.sequenceConverter(
      webidl.converters.MessagePort
    );
    var eventInit = [
      {
        key: "bubbles",
        converter: webidl.converters.boolean,
        defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
      },
      {
        key: "cancelable",
        converter: webidl.converters.boolean,
        defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
      },
      {
        key: "composed",
        converter: webidl.converters.boolean,
        defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
      }
    ];
    webidl.converters.MessageEventInit = webidl.dictionaryConverter([
      ...eventInit,
      {
        key: "data",
        converter: webidl.converters.any,
        defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
      },
      {
        key: "origin",
        converter: webidl.converters.USVString,
        defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
      },
      {
        key: "lastEventId",
        converter: webidl.converters.DOMString,
        defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
      },
      {
        key: "source",
        // Node doesn't implement WindowProxy or ServiceWorker, so the only
        // valid value for source is a MessagePort.
        converter: webidl.nullableConverter(webidl.converters.MessagePort),
        defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
      },
      {
        key: "ports",
        converter: webidl.converters["sequence<MessagePort>"],
        defaultValue: /* @__PURE__ */ __name(() => new Array(0), "defaultValue")
      }
    ]);
    webidl.converters.CloseEventInit = webidl.dictionaryConverter([
      ...eventInit,
      {
        key: "wasClean",
        converter: webidl.converters.boolean,
        defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
      },
      {
        key: "code",
        converter: webidl.converters["unsigned short"],
        defaultValue: /* @__PURE__ */ __name(() => 0, "defaultValue")
      },
      {
        key: "reason",
        converter: webidl.converters.USVString,
        defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
      }
    ]);
    webidl.converters.ErrorEventInit = webidl.dictionaryConverter([
      ...eventInit,
      {
        key: "message",
        converter: webidl.converters.DOMString,
        defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
      },
      {
        key: "filename",
        converter: webidl.converters.USVString,
        defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
      },
      {
        key: "lineno",
        converter: webidl.converters["unsigned long"],
        defaultValue: /* @__PURE__ */ __name(() => 0, "defaultValue")
      },
      {
        key: "colno",
        converter: webidl.converters["unsigned long"],
        defaultValue: /* @__PURE__ */ __name(() => 0, "defaultValue")
      },
      {
        key: "error",
        converter: webidl.converters.any
      }
    ]);
    module2.exports = {
      MessageEvent: MessageEvent2,
      CloseEvent,
      ErrorEvent: ErrorEvent2,
      createFastMessageEvent
    };
  }
});

// node_modules/undici/lib/web/websocket/constants.js
var require_constants7 = __commonJS({
  "node_modules/undici/lib/web/websocket/constants.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var uid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    var staticPropertyDescriptors = {
      enumerable: true,
      writable: false,
      configurable: false
    };
    var states = {
      CONNECTING: 0,
      OPEN: 1,
      CLOSING: 2,
      CLOSED: 3
    };
    var sentCloseFrameState = {
      SENT: 1,
      RECEIVED: 2
    };
    var opcodes = {
      CONTINUATION: 0,
      TEXT: 1,
      BINARY: 2,
      CLOSE: 8,
      PING: 9,
      PONG: 10
    };
    var maxUnsigned16Bit = 65535;
    var parserStates = {
      INFO: 0,
      PAYLOADLENGTH_16: 2,
      PAYLOADLENGTH_64: 3,
      READ_DATA: 4
    };
    var emptyBuffer = Buffer.allocUnsafe(0);
    var sendHints = {
      text: 1,
      typedArray: 2,
      arrayBuffer: 3,
      blob: 4
    };
    module2.exports = {
      uid,
      sentCloseFrameState,
      staticPropertyDescriptors,
      states,
      opcodes,
      maxUnsigned16Bit,
      parserStates,
      emptyBuffer,
      sendHints
    };
  }
});

// node_modules/undici/lib/web/websocket/util.js
var require_util5 = __commonJS({
  "node_modules/undici/lib/web/websocket/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { states, opcodes } = require_constants7();
    var { isUtf8 } = __require("node:buffer");
    var { collectASequenceOfCodePointsFast, removeHTTPWhitespace } = require_data_url();
    function isConnecting(readyState) {
      return readyState === states.CONNECTING;
    }
    __name(isConnecting, "isConnecting");
    function isEstablished(readyState) {
      return readyState === states.OPEN;
    }
    __name(isEstablished, "isEstablished");
    function isClosing(readyState) {
      return readyState === states.CLOSING;
    }
    __name(isClosing, "isClosing");
    function isClosed(readyState) {
      return readyState === states.CLOSED;
    }
    __name(isClosed, "isClosed");
    function fireEvent(e2, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) {
      const event = eventFactory(e2, eventInitDict);
      target.dispatchEvent(event);
    }
    __name(fireEvent, "fireEvent");
    function websocketMessageReceived(handler, type, data) {
      handler.onMessage(type, data);
    }
    __name(websocketMessageReceived, "websocketMessageReceived");
    function toArrayBuffer(buffer) {
      if (buffer.byteLength === buffer.buffer.byteLength) {
        return buffer.buffer;
      }
      return new Uint8Array(buffer).buffer;
    }
    __name(toArrayBuffer, "toArrayBuffer");
    function isValidSubprotocol(protocol) {
      if (protocol.length === 0) {
        return false;
      }
      for (let i = 0; i < protocol.length; ++i) {
        const code2 = protocol.charCodeAt(i);
        if (code2 < 33 || // CTL, contains SP (0x20) and HT (0x09)
        code2 > 126 || code2 === 34 || // "
        code2 === 40 || // (
        code2 === 41 || // )
        code2 === 44 || // ,
        code2 === 47 || // /
        code2 === 58 || // :
        code2 === 59 || // ;
        code2 === 60 || // <
        code2 === 61 || // =
        code2 === 62 || // >
        code2 === 63 || // ?
        code2 === 64 || // @
        code2 === 91 || // [
        code2 === 92 || // \
        code2 === 93 || // ]
        code2 === 123 || // {
        code2 === 125) {
          return false;
        }
      }
      return true;
    }
    __name(isValidSubprotocol, "isValidSubprotocol");
    function isValidStatusCode(code2) {
      if (code2 >= 1e3 && code2 < 1015) {
        return code2 !== 1004 && // reserved
        code2 !== 1005 && // "MUST NOT be set as a status code"
        code2 !== 1006;
      }
      return code2 >= 3e3 && code2 <= 4999;
    }
    __name(isValidStatusCode, "isValidStatusCode");
    function isControlFrame(opcode) {
      return opcode === opcodes.CLOSE || opcode === opcodes.PING || opcode === opcodes.PONG;
    }
    __name(isControlFrame, "isControlFrame");
    function isContinuationFrame(opcode) {
      return opcode === opcodes.CONTINUATION;
    }
    __name(isContinuationFrame, "isContinuationFrame");
    function isTextBinaryFrame(opcode) {
      return opcode === opcodes.TEXT || opcode === opcodes.BINARY;
    }
    __name(isTextBinaryFrame, "isTextBinaryFrame");
    function isValidOpcode(opcode) {
      return isTextBinaryFrame(opcode) || isContinuationFrame(opcode) || isControlFrame(opcode);
    }
    __name(isValidOpcode, "isValidOpcode");
    function parseExtensions(extensions) {
      const position = { position: 0 };
      const extensionList = /* @__PURE__ */ new Map();
      while (position.position < extensions.length) {
        const pair = collectASequenceOfCodePointsFast(";", extensions, position);
        const [name3, value = ""] = pair.split("=", 2);
        extensionList.set(
          removeHTTPWhitespace(name3, true, false),
          removeHTTPWhitespace(value, false, true)
        );
        position.position++;
      }
      return extensionList;
    }
    __name(parseExtensions, "parseExtensions");
    function isValidClientWindowBits(value) {
      for (let i = 0; i < value.length; i++) {
        const byte = value.charCodeAt(i);
        if (byte < 48 || byte > 57) {
          return false;
        }
      }
      return true;
    }
    __name(isValidClientWindowBits, "isValidClientWindowBits");
    function getURLRecord(url2, baseURL) {
      let urlRecord;
      try {
        urlRecord = new URL(url2, baseURL);
      } catch (e2) {
        throw new DOMException(e2, "SyntaxError");
      }
      if (urlRecord.protocol === "http:") {
        urlRecord.protocol = "ws:";
      } else if (urlRecord.protocol === "https:") {
        urlRecord.protocol = "wss:";
      }
      if (urlRecord.protocol !== "ws:" && urlRecord.protocol !== "wss:") {
        throw new DOMException("expected a ws: or wss: url", "SyntaxError");
      }
      if (urlRecord.hash.length || urlRecord.href.endsWith("#")) {
        throw new DOMException("hash", "SyntaxError");
      }
      return urlRecord;
    }
    __name(getURLRecord, "getURLRecord");
    function validateCloseCodeAndReason(code2, reason) {
      if (code2 !== null) {
        if (code2 !== 1e3 && (code2 < 3e3 || code2 > 4999)) {
          throw new DOMException("invalid code", "InvalidAccessError");
        }
      }
      if (reason !== null) {
        const reasonBytesLength = Buffer.byteLength(reason);
        if (reasonBytesLength > 123) {
          throw new DOMException(`Reason must be less than 123 bytes; received ${reasonBytesLength}`, "SyntaxError");
        }
      }
    }
    __name(validateCloseCodeAndReason, "validateCloseCodeAndReason");
    var utf8Decode = (() => {
      if (typeof process.versions.icu === "string") {
        const fatalDecoder = new TextDecoder("utf-8", { fatal: true });
        return fatalDecoder.decode.bind(fatalDecoder);
      }
      return function(buffer) {
        if (isUtf8(buffer)) {
          return buffer.toString("utf-8");
        }
        throw new TypeError("Invalid utf-8 received.");
      };
    })();
    module2.exports = {
      isConnecting,
      isEstablished,
      isClosing,
      isClosed,
      fireEvent,
      isValidSubprotocol,
      isValidStatusCode,
      websocketMessageReceived,
      utf8Decode,
      isControlFrame,
      isContinuationFrame,
      isTextBinaryFrame,
      isValidOpcode,
      parseExtensions,
      isValidClientWindowBits,
      toArrayBuffer,
      getURLRecord,
      validateCloseCodeAndReason
    };
  }
});

// node_modules/undici/lib/web/websocket/frame.js
var require_frame = __commonJS({
  "node_modules/undici/lib/web/websocket/frame.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { maxUnsigned16Bit, opcodes } = require_constants7();
    var BUFFER_SIZE = 8 * 1024;
    var crypto18;
    var buffer = null;
    var bufIdx = BUFFER_SIZE;
    try {
      crypto18 = __require("node:crypto");
    } catch {
      crypto18 = {
        // not full compatibility, but minimum.
        randomFillSync: /* @__PURE__ */ __name(function randomFillSync(buffer2, _offset, _size2) {
          for (let i = 0; i < buffer2.length; ++i) {
            buffer2[i] = Math.random() * 255 | 0;
          }
          return buffer2;
        }, "randomFillSync")
      };
    }
    function generateMask() {
      if (bufIdx === BUFFER_SIZE) {
        bufIdx = 0;
        crypto18.randomFillSync(buffer ??= Buffer.allocUnsafeSlow(BUFFER_SIZE), 0, BUFFER_SIZE);
      }
      return [buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++]];
    }
    __name(generateMask, "generateMask");
    var WebsocketFrameSend = class {
      static {
        __name(this, "WebsocketFrameSend");
      }
      /**
       * @param {Buffer|undefined} data
       */
      constructor(data) {
        this.frameData = data;
      }
      createFrame(opcode) {
        const frameData = this.frameData;
        const maskKey = generateMask();
        const bodyLength = frameData?.byteLength ?? 0;
        let payloadLength = bodyLength;
        let offset = 6;
        if (bodyLength > maxUnsigned16Bit) {
          offset += 8;
          payloadLength = 127;
        } else if (bodyLength > 125) {
          offset += 2;
          payloadLength = 126;
        }
        const buffer2 = Buffer.allocUnsafe(bodyLength + offset);
        buffer2[0] = buffer2[1] = 0;
        buffer2[0] |= 128;
        buffer2[0] = (buffer2[0] & 240) + opcode;
        buffer2[offset - 4] = maskKey[0];
        buffer2[offset - 3] = maskKey[1];
        buffer2[offset - 2] = maskKey[2];
        buffer2[offset - 1] = maskKey[3];
        buffer2[1] = payloadLength;
        if (payloadLength === 126) {
          buffer2.writeUInt16BE(bodyLength, 2);
        } else if (payloadLength === 127) {
          buffer2[2] = buffer2[3] = 0;
          buffer2.writeUIntBE(bodyLength, 4, 6);
        }
        buffer2[1] |= 128;
        for (let i = 0; i < bodyLength; ++i) {
          buffer2[offset + i] = frameData[i] ^ maskKey[i & 3];
        }
        return buffer2;
      }
      /**
       * @param {Uint8Array} buffer
       */
      static createFastTextFrame(buffer2) {
        const maskKey = generateMask();
        const bodyLength = buffer2.length;
        for (let i = 0; i < bodyLength; ++i) {
          buffer2[i] ^= maskKey[i & 3];
        }
        let payloadLength = bodyLength;
        let offset = 6;
        if (bodyLength > maxUnsigned16Bit) {
          offset += 8;
          payloadLength = 127;
        } else if (bodyLength > 125) {
          offset += 2;
          payloadLength = 126;
        }
        const head = Buffer.allocUnsafeSlow(offset);
        head[0] = 128 | opcodes.TEXT;
        head[1] = payloadLength | 128;
        head[offset - 4] = maskKey[0];
        head[offset - 3] = maskKey[1];
        head[offset - 2] = maskKey[2];
        head[offset - 1] = maskKey[3];
        if (payloadLength === 126) {
          head.writeUInt16BE(bodyLength, 2);
        } else if (payloadLength === 127) {
          head[2] = head[3] = 0;
          head.writeUIntBE(bodyLength, 4, 6);
        }
        return [head, buffer2];
      }
    };
    module2.exports = {
      WebsocketFrameSend,
      generateMask
      // for benchmark
    };
  }
});

// node_modules/undici/lib/web/websocket/connection.js
var require_connection = __commonJS({
  "node_modules/undici/lib/web/websocket/connection.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = require_constants7();
    var { parseExtensions, isClosed, isClosing, isEstablished, validateCloseCodeAndReason } = require_util5();
    var { makeRequest } = require_request2();
    var { fetching } = require_fetch();
    var { Headers: Headers2, getHeadersList } = require_headers();
    var { getDecodeSplit } = require_util2();
    var { WebsocketFrameSend } = require_frame();
    var assert3 = __require("node:assert");
    var crypto18;
    try {
      crypto18 = __require("node:crypto");
    } catch {
    }
    function establishWebSocketConnection(url2, protocols, client, handler, options2) {
      const requestURL = url2;
      requestURL.protocol = url2.protocol === "ws:" ? "http:" : "https:";
      const request4 = makeRequest({
        urlList: [requestURL],
        client,
        serviceWorkers: "none",
        referrer: "no-referrer",
        mode: "websocket",
        credentials: "include",
        cache: "no-store",
        redirect: "error"
      });
      if (options2.headers) {
        const headersList = getHeadersList(new Headers2(options2.headers));
        request4.headersList = headersList;
      }
      const keyValue = crypto18.randomBytes(16).toString("base64");
      request4.headersList.append("sec-websocket-key", keyValue, true);
      request4.headersList.append("sec-websocket-version", "13", true);
      for (const protocol of protocols) {
        request4.headersList.append("sec-websocket-protocol", protocol, true);
      }
      const permessageDeflate = "permessage-deflate; client_max_window_bits";
      request4.headersList.append("sec-websocket-extensions", permessageDeflate, true);
      const controller = fetching({
        request: request4,
        useParallelQueue: true,
        dispatcher: options2.dispatcher,
        processResponse(response) {
          if (response.type === "error") {
            handler.readyState = states.CLOSED;
          }
          if (response.type === "error" || response.status !== 101) {
            failWebsocketConnection(handler, 1002, "Received network error or non-101 status code.", response.error);
            return;
          }
          if (protocols.length !== 0 && !response.headersList.get("Sec-WebSocket-Protocol")) {
            failWebsocketConnection(handler, 1002, "Server did not respond with sent protocols.");
            return;
          }
          if (response.headersList.get("Upgrade")?.toLowerCase() !== "websocket") {
            failWebsocketConnection(handler, 1002, 'Server did not set Upgrade header to "websocket".');
            return;
          }
          if (response.headersList.get("Connection")?.toLowerCase() !== "upgrade") {
            failWebsocketConnection(handler, 1002, 'Server did not set Connection header to "upgrade".');
            return;
          }
          const secWSAccept = response.headersList.get("Sec-WebSocket-Accept");
          const digest = crypto18.createHash("sha1").update(keyValue + uid).digest("base64");
          if (secWSAccept !== digest) {
            failWebsocketConnection(handler, 1002, "Incorrect hash received in Sec-WebSocket-Accept header.");
            return;
          }
          const secExtension = response.headersList.get("Sec-WebSocket-Extensions");
          let extensions;
          if (secExtension !== null) {
            extensions = parseExtensions(secExtension);
            if (!extensions.has("permessage-deflate")) {
              failWebsocketConnection(handler, 1002, "Sec-WebSocket-Extensions header does not match.");
              return;
            }
          }
          const secProtocol = response.headersList.get("Sec-WebSocket-Protocol");
          if (secProtocol !== null) {
            const requestProtocols = getDecodeSplit("sec-websocket-protocol", request4.headersList);
            if (!requestProtocols.includes(secProtocol)) {
              failWebsocketConnection(handler, 1002, "Protocol was not set in the opening handshake.");
              return;
            }
          }
          response.socket.on("data", handler.onSocketData);
          response.socket.on("close", handler.onSocketClose);
          response.socket.on("error", handler.onSocketError);
          handler.wasEverConnected = true;
          handler.onConnectionEstablished(response, extensions);
        }
      });
      return controller;
    }
    __name(establishWebSocketConnection, "establishWebSocketConnection");
    function closeWebSocketConnection(object, code2, reason, validate4 = false) {
      code2 ??= null;
      reason ??= "";
      if (validate4) validateCloseCodeAndReason(code2, reason);
      if (isClosed(object.readyState) || isClosing(object.readyState)) {
      } else if (!isEstablished(object.readyState)) {
        failWebsocketConnection(object);
        object.readyState = states.CLOSING;
      } else if (!object.closeState.has(sentCloseFrameState.SENT) && !object.closeState.has(sentCloseFrameState.RECEIVED)) {
        const frame = new WebsocketFrameSend();
        if (reason.length !== 0 && code2 === null) {
          code2 = 1e3;
        }
        assert3(code2 === null || Number.isInteger(code2));
        if (code2 === null && reason.length === 0) {
          frame.frameData = emptyBuffer;
        } else if (code2 !== null && reason === null) {
          frame.frameData = Buffer.allocUnsafe(2);
          frame.frameData.writeUInt16BE(code2, 0);
        } else if (code2 !== null && reason !== null) {
          frame.frameData = Buffer.allocUnsafe(2 + Buffer.byteLength(reason));
          frame.frameData.writeUInt16BE(code2, 0);
          frame.frameData.write(reason, 2, "utf-8");
        } else {
          frame.frameData = emptyBuffer;
        }
        object.socket.write(frame.createFrame(opcodes.CLOSE));
        object.closeState.add(sentCloseFrameState.SENT);
        object.readyState = states.CLOSING;
      } else {
        object.readyState = states.CLOSING;
      }
    }
    __name(closeWebSocketConnection, "closeWebSocketConnection");
    function failWebsocketConnection(handler, code2, reason, cause) {
      if (isEstablished(handler.readyState)) {
        closeWebSocketConnection(handler, code2, reason, false);
      }
      handler.controller.abort();
      if (handler.socket?.destroyed === false) {
        handler.socket.destroy();
      }
      handler.onFail(code2, reason, cause);
    }
    __name(failWebsocketConnection, "failWebsocketConnection");
    module2.exports = {
      establishWebSocketConnection,
      failWebsocketConnection,
      closeWebSocketConnection
    };
  }
});

// node_modules/undici/lib/web/websocket/permessage-deflate.js
var require_permessage_deflate2 = __commonJS({
  "node_modules/undici/lib/web/websocket/permessage-deflate.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { createInflateRaw, Z_DEFAULT_WINDOWBITS } = __require("node:zlib");
    var { isValidClientWindowBits } = require_util5();
    var tail = Buffer.from([0, 0, 255, 255]);
    var kBuffer = Symbol("kBuffer");
    var kLength = Symbol("kLength");
    var PerMessageDeflate = class {
      static {
        __name(this, "PerMessageDeflate");
      }
      /** @type {import('node:zlib').InflateRaw} */
      #inflate;
      #options = {};
      constructor(extensions) {
        this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover");
        this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits");
      }
      decompress(chunk, fin, callback) {
        if (!this.#inflate) {
          let windowBits = Z_DEFAULT_WINDOWBITS;
          if (this.#options.serverMaxWindowBits) {
            if (!isValidClientWindowBits(this.#options.serverMaxWindowBits)) {
              callback(new Error("Invalid server_max_window_bits"));
              return;
            }
            windowBits = Number.parseInt(this.#options.serverMaxWindowBits);
          }
          this.#inflate = createInflateRaw({ windowBits });
          this.#inflate[kBuffer] = [];
          this.#inflate[kLength] = 0;
          this.#inflate.on("data", (data) => {
            this.#inflate[kBuffer].push(data);
            this.#inflate[kLength] += data.length;
          });
          this.#inflate.on("error", (err) => {
            this.#inflate = null;
            callback(err);
          });
        }
        this.#inflate.write(chunk);
        if (fin) {
          this.#inflate.write(tail);
        }
        this.#inflate.flush(() => {
          const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]);
          this.#inflate[kBuffer].length = 0;
          this.#inflate[kLength] = 0;
          callback(null, full);
        });
      }
    };
    module2.exports = { PerMessageDeflate };
  }
});

// node_modules/undici/lib/web/websocket/receiver.js
var require_receiver2 = __commonJS({
  "node_modules/undici/lib/web/websocket/receiver.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Writable: Writable3 } = __require("node:stream");
    var assert3 = __require("node:assert");
    var { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = require_constants7();
    var {
      isValidStatusCode,
      isValidOpcode,
      websocketMessageReceived,
      utf8Decode,
      isControlFrame,
      isTextBinaryFrame,
      isContinuationFrame
    } = require_util5();
    var { failWebsocketConnection } = require_connection();
    var { WebsocketFrameSend } = require_frame();
    var { PerMessageDeflate } = require_permessage_deflate2();
    var ByteParser = class extends Writable3 {
      static {
        __name(this, "ByteParser");
      }
      #buffers = [];
      #fragmentsBytes = 0;
      #byteOffset = 0;
      #loop = false;
      #state = parserStates.INFO;
      #info = {};
      #fragments = [];
      /** @type {Map<string, PerMessageDeflate>} */
      #extensions;
      /** @type {import('./websocket').Handler} */
      #handler;
      constructor(handler, extensions) {
        super();
        this.#handler = handler;
        this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions;
        if (this.#extensions.has("permessage-deflate")) {
          this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions));
        }
      }
      /**
       * @param {Buffer} chunk
       * @param {() => void} callback
       */
      _write(chunk, _, callback) {
        this.#buffers.push(chunk);
        this.#byteOffset += chunk.length;
        this.#loop = true;
        this.run(callback);
      }
      /**
       * Runs whenever a new chunk is received.
       * Callback is called whenever there are no more chunks buffering,
       * or not enough bytes are buffered to parse.
       */
      run(callback) {
        while (this.#loop) {
          if (this.#state === parserStates.INFO) {
            if (this.#byteOffset < 2) {
              return callback();
            }
            const buffer = this.consume(2);
            const fin = (buffer[0] & 128) !== 0;
            const opcode = buffer[0] & 15;
            const masked = (buffer[1] & 128) === 128;
            const fragmented = !fin && opcode !== opcodes.CONTINUATION;
            const payloadLength = buffer[1] & 127;
            const rsv1 = buffer[0] & 64;
            const rsv2 = buffer[0] & 32;
            const rsv3 = buffer[0] & 16;
            if (!isValidOpcode(opcode)) {
              failWebsocketConnection(this.#handler, 1002, "Invalid opcode received");
              return callback();
            }
            if (masked) {
              failWebsocketConnection(this.#handler, 1002, "Frame cannot be masked");
              return callback();
            }
            if (rsv1 !== 0 && !this.#extensions.has("permessage-deflate")) {
              failWebsocketConnection(this.#handler, 1002, "Expected RSV1 to be clear.");
              return;
            }
            if (rsv2 !== 0 || rsv3 !== 0) {
              failWebsocketConnection(this.#handler, 1002, "RSV1, RSV2, RSV3 must be clear");
              return;
            }
            if (fragmented && !isTextBinaryFrame(opcode)) {
              failWebsocketConnection(this.#handler, 1002, "Invalid frame type was fragmented.");
              return;
            }
            if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) {
              failWebsocketConnection(this.#handler, 1002, "Expected continuation frame");
              return;
            }
            if (this.#info.fragmented && fragmented) {
              failWebsocketConnection(this.#handler, 1002, "Fragmented frame exceeded 125 bytes.");
              return;
            }
            if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) {
              failWebsocketConnection(this.#handler, 1002, "Control frame either too large or fragmented");
              return;
            }
            if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) {
              failWebsocketConnection(this.#handler, 1002, "Unexpected continuation frame");
              return;
            }
            if (payloadLength <= 125) {
              this.#info.payloadLength = payloadLength;
              this.#state = parserStates.READ_DATA;
            } else if (payloadLength === 126) {
              this.#state = parserStates.PAYLOADLENGTH_16;
            } else if (payloadLength === 127) {
              this.#state = parserStates.PAYLOADLENGTH_64;
            }
            if (isTextBinaryFrame(opcode)) {
              this.#info.binaryType = opcode;
              this.#info.compressed = rsv1 !== 0;
            }
            this.#info.opcode = opcode;
            this.#info.masked = masked;
            this.#info.fin = fin;
            this.#info.fragmented = fragmented;
          } else if (this.#state === parserStates.PAYLOADLENGTH_16) {
            if (this.#byteOffset < 2) {
              return callback();
            }
            const buffer = this.consume(2);
            this.#info.payloadLength = buffer.readUInt16BE(0);
            this.#state = parserStates.READ_DATA;
          } else if (this.#state === parserStates.PAYLOADLENGTH_64) {
            if (this.#byteOffset < 8) {
              return callback();
            }
            const buffer = this.consume(8);
            const upper = buffer.readUInt32BE(0);
            if (upper > 2 ** 31 - 1) {
              failWebsocketConnection(this.#handler, 1009, "Received payload length > 2^31 bytes.");
              return;
            }
            const lower = buffer.readUInt32BE(4);
            this.#info.payloadLength = (upper << 8) + lower;
            this.#state = parserStates.READ_DATA;
          } else if (this.#state === parserStates.READ_DATA) {
            if (this.#byteOffset < this.#info.payloadLength) {
              return callback();
            }
            const body = this.consume(this.#info.payloadLength);
            if (isControlFrame(this.#info.opcode)) {
              this.#loop = this.parseControlFrame(body);
              this.#state = parserStates.INFO;
            } else {
              if (!this.#info.compressed) {
                this.writeFragments(body);
                if (!this.#info.fragmented && this.#info.fin) {
                  websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
                }
                this.#state = parserStates.INFO;
              } else {
                this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error, data) => {
                  if (error) {
                    failWebsocketConnection(this.#handler, 1007, error.message);
                    return;
                  }
                  this.writeFragments(data);
                  if (!this.#info.fin) {
                    this.#state = parserStates.INFO;
                    this.#loop = true;
                    this.run(callback);
                    return;
                  }
                  websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
                  this.#loop = true;
                  this.#state = parserStates.INFO;
                  this.run(callback);
                });
                this.#loop = false;
                break;
              }
            }
          }
        }
      }
      /**
       * Take n bytes from the buffered Buffers
       * @param {number} n
       * @returns {Buffer}
       */
      consume(n2) {
        if (n2 > this.#byteOffset) {
          throw new Error("Called consume() before buffers satiated.");
        } else if (n2 === 0) {
          return emptyBuffer;
        }
        this.#byteOffset -= n2;
        const first2 = this.#buffers[0];
        if (first2.length > n2) {
          this.#buffers[0] = first2.subarray(n2, first2.length);
          return first2.subarray(0, n2);
        } else if (first2.length === n2) {
          return this.#buffers.shift();
        } else {
          let offset = 0;
          const buffer = Buffer.allocUnsafeSlow(n2);
          while (offset !== n2) {
            const next = this.#buffers[0];
            const length = next.length;
            if (length + offset === n2) {
              buffer.set(this.#buffers.shift(), offset);
              break;
            } else if (length + offset > n2) {
              buffer.set(next.subarray(0, n2 - offset), offset);
              this.#buffers[0] = next.subarray(n2 - offset);
              break;
            } else {
              buffer.set(this.#buffers.shift(), offset);
              offset += length;
            }
          }
          return buffer;
        }
      }
      writeFragments(fragment) {
        this.#fragmentsBytes += fragment.length;
        this.#fragments.push(fragment);
      }
      consumeFragments() {
        const fragments = this.#fragments;
        if (fragments.length === 1) {
          this.#fragmentsBytes = 0;
          return fragments.shift();
        }
        let offset = 0;
        const output = Buffer.allocUnsafeSlow(this.#fragmentsBytes);
        for (let i = 0; i < fragments.length; ++i) {
          const buffer = fragments[i];
          output.set(buffer, offset);
          offset += buffer.length;
        }
        this.#fragments = [];
        this.#fragmentsBytes = 0;
        return output;
      }
      parseCloseBody(data) {
        assert3(data.length !== 1);
        let code2;
        if (data.length >= 2) {
          code2 = data.readUInt16BE(0);
        }
        if (code2 !== void 0 && !isValidStatusCode(code2)) {
          return { code: 1002, reason: "Invalid status code", error: true };
        }
        let reason = data.subarray(2);
        if (reason[0] === 239 && reason[1] === 187 && reason[2] === 191) {
          reason = reason.subarray(3);
        }
        try {
          reason = utf8Decode(reason);
        } catch {
          return { code: 1007, reason: "Invalid UTF-8", error: true };
        }
        return { code: code2, reason, error: false };
      }
      /**
       * Parses control frames.
       * @param {Buffer} body
       */
      parseControlFrame(body) {
        const { opcode, payloadLength } = this.#info;
        if (opcode === opcodes.CLOSE) {
          if (payloadLength === 1) {
            failWebsocketConnection(this.#handler, 1002, "Received close frame with a 1-byte body.");
            return false;
          }
          this.#info.closeInfo = this.parseCloseBody(body);
          if (this.#info.closeInfo.error) {
            const { code: code2, reason } = this.#info.closeInfo;
            failWebsocketConnection(this.#handler, code2, reason);
            return false;
          }
          if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
            let body2 = emptyBuffer;
            if (this.#info.closeInfo.code) {
              body2 = Buffer.allocUnsafe(2);
              body2.writeUInt16BE(this.#info.closeInfo.code, 0);
            }
            const closeFrame = new WebsocketFrameSend(body2);
            this.#handler.socket.write(closeFrame.createFrame(opcodes.CLOSE));
            this.#handler.closeState.add(sentCloseFrameState.SENT);
          }
          this.#handler.readyState = states.CLOSING;
          this.#handler.closeState.add(sentCloseFrameState.RECEIVED);
          return false;
        } else if (opcode === opcodes.PING) {
          if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
            const frame = new WebsocketFrameSend(body);
            this.#handler.socket.write(frame.createFrame(opcodes.PONG));
            this.#handler.onPing(body);
          }
        } else if (opcode === opcodes.PONG) {
          this.#handler.onPong(body);
        }
        return true;
      }
      get closingInfo() {
        return this.#info.closeInfo;
      }
    };
    module2.exports = {
      ByteParser
    };
  }
});

// node_modules/undici/lib/web/websocket/sender.js
var require_sender2 = __commonJS({
  "node_modules/undici/lib/web/websocket/sender.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { WebsocketFrameSend } = require_frame();
    var { opcodes, sendHints } = require_constants7();
    var FixedQueue = require_fixed_queue();
    var SendQueue = class {
      static {
        __name(this, "SendQueue");
      }
      /**
       * @type {FixedQueue}
       */
      #queue = new FixedQueue();
      /**
       * @type {boolean}
       */
      #running = false;
      /** @type {import('node:net').Socket} */
      #socket;
      constructor(socket) {
        this.#socket = socket;
      }
      add(item, cb, hint) {
        if (hint !== sendHints.blob) {
          if (!this.#running) {
            if (hint === sendHints.text) {
              const { 0: head, 1: body } = WebsocketFrameSend.createFastTextFrame(item);
              this.#socket.cork();
              this.#socket.write(head);
              this.#socket.write(body, cb);
              this.#socket.uncork();
            } else {
              this.#socket.write(createFrame(item, hint), cb);
            }
          } else {
            const node2 = {
              promise: null,
              callback: cb,
              frame: createFrame(item, hint)
            };
            this.#queue.push(node2);
          }
          return;
        }
        const node = {
          promise: item.arrayBuffer().then((ab2) => {
            node.promise = null;
            node.frame = createFrame(ab2, hint);
          }),
          callback: cb,
          frame: null
        };
        this.#queue.push(node);
        if (!this.#running) {
          this.#run();
        }
      }
      async #run() {
        this.#running = true;
        const queue = this.#queue;
        while (!queue.isEmpty()) {
          const node = queue.shift();
          if (node.promise !== null) {
            await node.promise;
          }
          this.#socket.write(node.frame, node.callback);
          node.callback = node.frame = null;
        }
        this.#running = false;
      }
    };
    function createFrame(data, hint) {
      return new WebsocketFrameSend(toBuffer(data, hint)).createFrame(hint === sendHints.text ? opcodes.TEXT : opcodes.BINARY);
    }
    __name(createFrame, "createFrame");
    function toBuffer(data, hint) {
      switch (hint) {
        case sendHints.text:
        case sendHints.typedArray:
          return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
        case sendHints.arrayBuffer:
        case sendHints.blob:
          return new Uint8Array(data);
      }
    }
    __name(toBuffer, "toBuffer");
    module2.exports = { SendQueue };
  }
});

// node_modules/undici/lib/web/websocket/websocket.js
var require_websocket2 = __commonJS({
  "node_modules/undici/lib/web/websocket/websocket.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { isArrayBuffer } = __require("node:util/types");
    var { webidl } = require_webidl();
    var { URLSerializer } = require_data_url();
    var { environmentSettingsObject } = require_util2();
    var { staticPropertyDescriptors, states, sentCloseFrameState, sendHints, opcodes } = require_constants7();
    var {
      isConnecting,
      isEstablished,
      isClosing,
      isClosed,
      isValidSubprotocol,
      fireEvent,
      utf8Decode,
      toArrayBuffer,
      getURLRecord
    } = require_util5();
    var { establishWebSocketConnection, closeWebSocketConnection, failWebsocketConnection } = require_connection();
    var { ByteParser } = require_receiver2();
    var { kEnumerableProperty } = require_util();
    var { getGlobalDispatcher } = require_global2();
    var { ErrorEvent: ErrorEvent2, CloseEvent, createFastMessageEvent } = require_events();
    var { SendQueue } = require_sender2();
    var { WebsocketFrameSend } = require_frame();
    var { channels } = require_diagnostics();
    var WebSocket2 = class _WebSocket extends EventTarget {
      static {
        __name(this, "WebSocket");
      }
      #events = {
        open: null,
        error: null,
        close: null,
        message: null
      };
      #bufferedAmount = 0;
      #protocol = "";
      #extensions = "";
      /** @type {SendQueue} */
      #sendQueue;
      /** @type {Handler} */
      #handler = {
        onConnectionEstablished: /* @__PURE__ */ __name((response, extensions) => this.#onConnectionEstablished(response, extensions), "onConnectionEstablished"),
        onFail: /* @__PURE__ */ __name((code2, reason, cause) => this.#onFail(code2, reason, cause), "onFail"),
        onMessage: /* @__PURE__ */ __name((opcode, data) => this.#onMessage(opcode, data), "onMessage"),
        onParserError: /* @__PURE__ */ __name((err) => failWebsocketConnection(this.#handler, null, err.message), "onParserError"),
        onParserDrain: /* @__PURE__ */ __name(() => this.#onParserDrain(), "onParserDrain"),
        onSocketData: /* @__PURE__ */ __name((chunk) => {
          if (!this.#parser.write(chunk)) {
            this.#handler.socket.pause();
          }
        }, "onSocketData"),
        onSocketError: /* @__PURE__ */ __name((err) => {
          this.#handler.readyState = states.CLOSING;
          if (channels.socketError.hasSubscribers) {
            channels.socketError.publish(err);
          }
          this.#handler.socket.destroy();
        }, "onSocketError"),
        onSocketClose: /* @__PURE__ */ __name(() => this.#onSocketClose(), "onSocketClose"),
        onPing: /* @__PURE__ */ __name((body) => {
          if (channels.ping.hasSubscribers) {
            channels.ping.publish({
              payload: body,
              websocket: this
            });
          }
        }, "onPing"),
        onPong: /* @__PURE__ */ __name((body) => {
          if (channels.pong.hasSubscribers) {
            channels.pong.publish({
              payload: body,
              websocket: this
            });
          }
        }, "onPong"),
        readyState: states.CONNECTING,
        socket: null,
        closeState: /* @__PURE__ */ new Set(),
        controller: null,
        wasEverConnected: false
      };
      #url;
      #binaryType;
      /** @type {import('./receiver').ByteParser} */
      #parser;
      /**
       * @param {string} url
       * @param {string|string[]} protocols
       */
      constructor(url2, protocols = []) {
        super();
        webidl.util.markAsUncloneable(this);
        const prefix = "WebSocket constructor";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        const options2 = webidl.converters["DOMString or sequence<DOMString> or WebSocketInit"](protocols, prefix, "options");
        url2 = webidl.converters.USVString(url2);
        protocols = options2.protocols;
        const baseURL = environmentSettingsObject.settingsObject.baseUrl;
        const urlRecord = getURLRecord(url2, baseURL);
        if (typeof protocols === "string") {
          protocols = [protocols];
        }
        if (protocols.length !== new Set(protocols.map((p) => p.toLowerCase())).size) {
          throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
        }
        if (protocols.length > 0 && !protocols.every((p) => isValidSubprotocol(p))) {
          throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
        }
        this.#url = new URL(urlRecord.href);
        const client = environmentSettingsObject.settingsObject;
        this.#handler.controller = establishWebSocketConnection(
          urlRecord,
          protocols,
          client,
          this.#handler,
          options2
        );
        this.#handler.readyState = _WebSocket.CONNECTING;
        this.#binaryType = "blob";
      }
      /**
       * @see https://websockets.spec.whatwg.org/#dom-websocket-close
       * @param {number|undefined} code
       * @param {string|undefined} reason
       */
      close(code2 = void 0, reason = void 0) {
        webidl.brandCheck(this, _WebSocket);
        const prefix = "WebSocket.close";
        if (code2 !== void 0) {
          code2 = webidl.converters["unsigned short"](code2, prefix, "code", { clamp: true });
        }
        if (reason !== void 0) {
          reason = webidl.converters.USVString(reason);
        }
        code2 ??= null;
        reason ??= "";
        closeWebSocketConnection(this.#handler, code2, reason, true);
      }
      /**
       * @see https://websockets.spec.whatwg.org/#dom-websocket-send
       * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data
       */
      send(data) {
        webidl.brandCheck(this, _WebSocket);
        const prefix = "WebSocket.send";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        data = webidl.converters.WebSocketSendData(data, prefix, "data");
        if (isConnecting(this.#handler.readyState)) {
          throw new DOMException("Sent before connected.", "InvalidStateError");
        }
        if (!isEstablished(this.#handler.readyState) || isClosing(this.#handler.readyState)) {
          return;
        }
        if (typeof data === "string") {
          const buffer = Buffer.from(data);
          this.#bufferedAmount += buffer.byteLength;
          this.#sendQueue.add(buffer, () => {
            this.#bufferedAmount -= buffer.byteLength;
          }, sendHints.text);
        } else if (isArrayBuffer(data)) {
          this.#bufferedAmount += data.byteLength;
          this.#sendQueue.add(data, () => {
            this.#bufferedAmount -= data.byteLength;
          }, sendHints.arrayBuffer);
        } else if (ArrayBuffer.isView(data)) {
          this.#bufferedAmount += data.byteLength;
          this.#sendQueue.add(data, () => {
            this.#bufferedAmount -= data.byteLength;
          }, sendHints.typedArray);
        } else if (webidl.is.Blob(data)) {
          this.#bufferedAmount += data.size;
          this.#sendQueue.add(data, () => {
            this.#bufferedAmount -= data.size;
          }, sendHints.blob);
        }
      }
      get readyState() {
        webidl.brandCheck(this, _WebSocket);
        return this.#handler.readyState;
      }
      get bufferedAmount() {
        webidl.brandCheck(this, _WebSocket);
        return this.#bufferedAmount;
      }
      get url() {
        webidl.brandCheck(this, _WebSocket);
        return URLSerializer(this.#url);
      }
      get extensions() {
        webidl.brandCheck(this, _WebSocket);
        return this.#extensions;
      }
      get protocol() {
        webidl.brandCheck(this, _WebSocket);
        return this.#protocol;
      }
      get onopen() {
        webidl.brandCheck(this, _WebSocket);
        return this.#events.open;
      }
      set onopen(fn) {
        webidl.brandCheck(this, _WebSocket);
        if (this.#events.open) {
          this.removeEventListener("open", this.#events.open);
        }
        if (typeof fn === "function") {
          this.#events.open = fn;
          this.addEventListener("open", fn);
        } else {
          this.#events.open = null;
        }
      }
      get onerror() {
        webidl.brandCheck(this, _WebSocket);
        return this.#events.error;
      }
      set onerror(fn) {
        webidl.brandCheck(this, _WebSocket);
        if (this.#events.error) {
          this.removeEventListener("error", this.#events.error);
        }
        if (typeof fn === "function") {
          this.#events.error = fn;
          this.addEventListener("error", fn);
        } else {
          this.#events.error = null;
        }
      }
      get onclose() {
        webidl.brandCheck(this, _WebSocket);
        return this.#events.close;
      }
      set onclose(fn) {
        webidl.brandCheck(this, _WebSocket);
        if (this.#events.close) {
          this.removeEventListener("close", this.#events.close);
        }
        if (typeof fn === "function") {
          this.#events.close = fn;
          this.addEventListener("close", fn);
        } else {
          this.#events.close = null;
        }
      }
      get onmessage() {
        webidl.brandCheck(this, _WebSocket);
        return this.#events.message;
      }
      set onmessage(fn) {
        webidl.brandCheck(this, _WebSocket);
        if (this.#events.message) {
          this.removeEventListener("message", this.#events.message);
        }
        if (typeof fn === "function") {
          this.#events.message = fn;
          this.addEventListener("message", fn);
        } else {
          this.#events.message = null;
        }
      }
      get binaryType() {
        webidl.brandCheck(this, _WebSocket);
        return this.#binaryType;
      }
      set binaryType(type) {
        webidl.brandCheck(this, _WebSocket);
        if (type !== "blob" && type !== "arraybuffer") {
          this.#binaryType = "blob";
        } else {
          this.#binaryType = type;
        }
      }
      /**
       * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
       */
      #onConnectionEstablished(response, parsedExtensions) {
        this.#handler.socket = response.socket;
        const parser6 = new ByteParser(this.#handler, parsedExtensions);
        parser6.on("drain", () => this.#handler.onParserDrain());
        parser6.on("error", (err) => this.#handler.onParserError(err));
        this.#parser = parser6;
        this.#sendQueue = new SendQueue(response.socket);
        this.#handler.readyState = states.OPEN;
        const extensions = response.headersList.get("sec-websocket-extensions");
        if (extensions !== null) {
          this.#extensions = extensions;
        }
        const protocol = response.headersList.get("sec-websocket-protocol");
        if (protocol !== null) {
          this.#protocol = protocol;
        }
        fireEvent("open", this);
        if (channels.open.hasSubscribers) {
          const headers = response.headersList.entries;
          channels.open.publish({
            address: response.socket.address(),
            protocol: this.#protocol,
            extensions: this.#extensions,
            websocket: this,
            handshakeResponse: {
              status: response.status,
              statusText: response.statusText,
              headers
            }
          });
        }
      }
      #onFail(code2, reason, cause) {
        if (reason) {
          fireEvent("error", this, (type, init) => new ErrorEvent2(type, init), {
            error: new Error(reason, cause ? { cause } : void 0),
            message: reason
          });
        }
        if (!this.#handler.wasEverConnected) {
          this.#handler.readyState = states.CLOSED;
          fireEvent("close", this, (type, init) => new CloseEvent(type, init), {
            wasClean: false,
            code: code2,
            reason
          });
        }
      }
      #onMessage(type, data) {
        if (this.#handler.readyState !== states.OPEN) {
          return;
        }
        let dataForEvent;
        if (type === opcodes.TEXT) {
          try {
            dataForEvent = utf8Decode(data);
          } catch {
            failWebsocketConnection(this.#handler, 1007, "Received invalid UTF-8 in text frame.");
            return;
          }
        } else if (type === opcodes.BINARY) {
          if (this.#binaryType === "blob") {
            dataForEvent = new Blob([data]);
          } else {
            dataForEvent = toArrayBuffer(data);
          }
        }
        fireEvent("message", this, createFastMessageEvent, {
          origin: this.#url.origin,
          data: dataForEvent
        });
      }
      #onParserDrain() {
        this.#handler.socket.resume();
      }
      /**
       * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
       * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
       */
      #onSocketClose() {
        const wasClean = this.#handler.closeState.has(sentCloseFrameState.SENT) && this.#handler.closeState.has(sentCloseFrameState.RECEIVED);
        let code2 = 1005;
        let reason = "";
        const result = this.#parser.closingInfo;
        if (result && !result.error) {
          code2 = result.code ?? 1005;
          reason = result.reason;
        } else if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
          code2 = 1006;
        }
        this.#handler.readyState = states.CLOSED;
        fireEvent("close", this, (type, init) => new CloseEvent(type, init), {
          wasClean,
          code: code2,
          reason
        });
        if (channels.close.hasSubscribers) {
          channels.close.publish({
            websocket: this,
            code: code2,
            reason
          });
        }
      }
      /**
       * @param {WebSocket} ws
       * @param {Buffer|undefined} buffer
       */
      static ping(ws2, buffer) {
        if (Buffer.isBuffer(buffer)) {
          if (buffer.length > 125) {
            throw new TypeError("A PING frame cannot have a body larger than 125 bytes.");
          }
        } else if (buffer !== void 0) {
          throw new TypeError("Expected buffer payload");
        }
        const readyState = ws2.#handler.readyState;
        if (isEstablished(readyState) && !isClosing(readyState) && !isClosed(readyState)) {
          const frame = new WebsocketFrameSend(buffer);
          ws2.#handler.socket.write(frame.createFrame(opcodes.PING));
        }
      }
    };
    var { ping } = WebSocket2;
    Reflect.deleteProperty(WebSocket2, "ping");
    WebSocket2.CONNECTING = WebSocket2.prototype.CONNECTING = states.CONNECTING;
    WebSocket2.OPEN = WebSocket2.prototype.OPEN = states.OPEN;
    WebSocket2.CLOSING = WebSocket2.prototype.CLOSING = states.CLOSING;
    WebSocket2.CLOSED = WebSocket2.prototype.CLOSED = states.CLOSED;
    Object.defineProperties(WebSocket2.prototype, {
      CONNECTING: staticPropertyDescriptors,
      OPEN: staticPropertyDescriptors,
      CLOSING: staticPropertyDescriptors,
      CLOSED: staticPropertyDescriptors,
      url: kEnumerableProperty,
      readyState: kEnumerableProperty,
      bufferedAmount: kEnumerableProperty,
      onopen: kEnumerableProperty,
      onerror: kEnumerableProperty,
      onclose: kEnumerableProperty,
      close: kEnumerableProperty,
      onmessage: kEnumerableProperty,
      binaryType: kEnumerableProperty,
      send: kEnumerableProperty,
      extensions: kEnumerableProperty,
      protocol: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "WebSocket",
        writable: false,
        enumerable: false,
        configurable: true
      }
    });
    Object.defineProperties(WebSocket2, {
      CONNECTING: staticPropertyDescriptors,
      OPEN: staticPropertyDescriptors,
      CLOSING: staticPropertyDescriptors,
      CLOSED: staticPropertyDescriptors
    });
    webidl.converters["sequence<DOMString>"] = webidl.sequenceConverter(
      webidl.converters.DOMString
    );
    webidl.converters["DOMString or sequence<DOMString>"] = function(V2, prefix, argument) {
      if (webidl.util.Type(V2) === webidl.util.Types.OBJECT && Symbol.iterator in V2) {
        return webidl.converters["sequence<DOMString>"](V2);
      }
      return webidl.converters.DOMString(V2, prefix, argument);
    };
    webidl.converters.WebSocketInit = webidl.dictionaryConverter([
      {
        key: "protocols",
        converter: webidl.converters["DOMString or sequence<DOMString>"],
        defaultValue: /* @__PURE__ */ __name(() => new Array(0), "defaultValue")
      },
      {
        key: "dispatcher",
        converter: webidl.converters.any,
        defaultValue: /* @__PURE__ */ __name(() => getGlobalDispatcher(), "defaultValue")
      },
      {
        key: "headers",
        converter: webidl.nullableConverter(webidl.converters.HeadersInit)
      }
    ]);
    webidl.converters["DOMString or sequence<DOMString> or WebSocketInit"] = function(V2) {
      if (webidl.util.Type(V2) === webidl.util.Types.OBJECT && !(Symbol.iterator in V2)) {
        return webidl.converters.WebSocketInit(V2);
      }
      return { protocols: webidl.converters["DOMString or sequence<DOMString>"](V2) };
    };
    webidl.converters.WebSocketSendData = function(V2) {
      if (webidl.util.Type(V2) === webidl.util.Types.OBJECT) {
        if (webidl.is.Blob(V2)) {
          return V2;
        }
        if (ArrayBuffer.isView(V2) || isArrayBuffer(V2)) {
          return V2;
        }
      }
      return webidl.converters.USVString(V2);
    };
    module2.exports = {
      WebSocket: WebSocket2,
      ping
    };
  }
});

// node_modules/undici/lib/web/websocket/stream/websocketerror.js
var require_websocketerror = __commonJS({
  "node_modules/undici/lib/web/websocket/stream/websocketerror.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { webidl } = require_webidl();
    var { validateCloseCodeAndReason } = require_util5();
    var { kConstruct } = require_symbols();
    var { kEnumerableProperty } = require_util();
    var WebSocketError = class _WebSocketError extends DOMException {
      static {
        __name(this, "WebSocketError");
      }
      #closeCode;
      #reason;
      constructor(message = "", init = void 0) {
        message = webidl.converters.DOMString(message, "WebSocketError", "message");
        super(message, "WebSocketError");
        if (init === kConstruct) {
          return;
        } else if (init !== null) {
          init = webidl.converters.WebSocketCloseInfo(init);
        }
        let code2 = init.closeCode ?? null;
        const reason = init.reason ?? "";
        validateCloseCodeAndReason(code2, reason);
        if (reason.length !== 0 && code2 === null) {
          code2 = 1e3;
        }
        this.#closeCode = code2;
        this.#reason = reason;
      }
      get closeCode() {
        return this.#closeCode;
      }
      get reason() {
        return this.#reason;
      }
      /**
       * @param {string} message
       * @param {number|null} code
       * @param {string} reason
       */
      static createUnvalidatedWebSocketError(message, code2, reason) {
        const error = new _WebSocketError(message, kConstruct);
        error.#closeCode = code2;
        error.#reason = reason;
        return error;
      }
    };
    var { createUnvalidatedWebSocketError } = WebSocketError;
    delete WebSocketError.createUnvalidatedWebSocketError;
    Object.defineProperties(WebSocketError.prototype, {
      closeCode: kEnumerableProperty,
      reason: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "WebSocketError",
        writable: false,
        enumerable: false,
        configurable: true
      }
    });
    webidl.is.WebSocketError = webidl.util.MakeTypeAssertion(WebSocketError);
    module2.exports = { WebSocketError, createUnvalidatedWebSocketError };
  }
});

// node_modules/undici/lib/web/websocket/stream/websocketstream.js
var require_websocketstream = __commonJS({
  "node_modules/undici/lib/web/websocket/stream/websocketstream.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { createDeferredPromise } = require_promise();
    var { environmentSettingsObject } = require_util2();
    var { states, opcodes, sentCloseFrameState } = require_constants7();
    var { webidl } = require_webidl();
    var { getURLRecord, isValidSubprotocol, isEstablished, utf8Decode } = require_util5();
    var { establishWebSocketConnection, failWebsocketConnection, closeWebSocketConnection } = require_connection();
    var { isArrayBuffer } = __require("node:util/types");
    var { channels } = require_diagnostics();
    var { WebsocketFrameSend } = require_frame();
    var { ByteParser } = require_receiver2();
    var { WebSocketError, createUnvalidatedWebSocketError } = require_websocketerror();
    var { utf8DecodeBytes } = require_util2();
    var { kEnumerableProperty } = require_util();
    var emittedExperimentalWarning = false;
    var WebSocketStream = class {
      static {
        __name(this, "WebSocketStream");
      }
      // Each WebSocketStream object has an associated url , which is a URL record .
      /** @type {URL} */
      #url;
      // Each WebSocketStream object has an associated opened promise , which is a promise.
      /** @type {import('../../../util/promise').DeferredPromise} */
      #openedPromise;
      // Each WebSocketStream object has an associated closed promise , which is a promise.
      /** @type {import('../../../util/promise').DeferredPromise} */
      #closedPromise;
      // Each WebSocketStream object has an associated readable stream , which is a ReadableStream .
      /** @type {ReadableStream} */
      #readableStream;
      /** @type {ReadableStreamDefaultController} */
      #readableStreamController;
      // Each WebSocketStream object has an associated writable stream , which is a WritableStream .
      /** @type {WritableStream} */
      #writableStream;
      // Each WebSocketStream object has an associated boolean handshake aborted , which is initially false.
      #handshakeAborted = false;
      /** @type {import('../websocket').Handler} */
      #handler = {
        // https://whatpr.org/websockets/48/7b748d3...d5570f3.html#feedback-to-websocket-stream-from-the-protocol
        onConnectionEstablished: /* @__PURE__ */ __name((response, extensions) => this.#onConnectionEstablished(response, extensions), "onConnectionEstablished"),
        onFail: /* @__PURE__ */ __name((_code, _reason) => {
        }, "onFail"),
        onMessage: /* @__PURE__ */ __name((opcode, data) => this.#onMessage(opcode, data), "onMessage"),
        onParserError: /* @__PURE__ */ __name((err) => failWebsocketConnection(this.#handler, null, err.message), "onParserError"),
        onParserDrain: /* @__PURE__ */ __name(() => this.#handler.socket.resume(), "onParserDrain"),
        onSocketData: /* @__PURE__ */ __name((chunk) => {
          if (!this.#parser.write(chunk)) {
            this.#handler.socket.pause();
          }
        }, "onSocketData"),
        onSocketError: /* @__PURE__ */ __name((err) => {
          this.#handler.readyState = states.CLOSING;
          if (channels.socketError.hasSubscribers) {
            channels.socketError.publish(err);
          }
          this.#handler.socket.destroy();
        }, "onSocketError"),
        onSocketClose: /* @__PURE__ */ __name(() => this.#onSocketClose(), "onSocketClose"),
        onPing: /* @__PURE__ */ __name(() => {
        }, "onPing"),
        onPong: /* @__PURE__ */ __name(() => {
        }, "onPong"),
        readyState: states.CONNECTING,
        socket: null,
        closeState: /* @__PURE__ */ new Set(),
        controller: null,
        wasEverConnected: false
      };
      /** @type {import('../receiver').ByteParser} */
      #parser;
      constructor(url2, options2 = void 0) {
        if (!emittedExperimentalWarning) {
          process.emitWarning("WebSocketStream is experimental! Expect it to change at any time.", {
            code: "UNDICI-WSS"
          });
          emittedExperimentalWarning = true;
        }
        webidl.argumentLengthCheck(arguments, 1, "WebSocket");
        url2 = webidl.converters.USVString(url2);
        if (options2 !== null) {
          options2 = webidl.converters.WebSocketStreamOptions(options2);
        }
        const baseURL = environmentSettingsObject.settingsObject.baseUrl;
        const urlRecord = getURLRecord(url2, baseURL);
        const protocols = options2.protocols;
        if (protocols.length !== new Set(protocols.map((p) => p.toLowerCase())).size) {
          throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
        }
        if (protocols.length > 0 && !protocols.every((p) => isValidSubprotocol(p))) {
          throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
        }
        this.#url = urlRecord.toString();
        this.#openedPromise = createDeferredPromise();
        this.#closedPromise = createDeferredPromise();
        if (options2.signal != null) {
          const signal = options2.signal;
          if (signal.aborted) {
            this.#openedPromise.reject(signal.reason);
            this.#closedPromise.reject(signal.reason);
            return;
          }
          signal.addEventListener("abort", () => {
            if (!isEstablished(this.#handler.readyState)) {
              failWebsocketConnection(this.#handler);
              this.#handler.readyState = states.CLOSING;
              this.#openedPromise.reject(signal.reason);
              this.#closedPromise.reject(signal.reason);
              this.#handshakeAborted = true;
            }
          }, { once: true });
        }
        const client = environmentSettingsObject.settingsObject;
        this.#handler.controller = establishWebSocketConnection(
          urlRecord,
          protocols,
          client,
          this.#handler,
          options2
        );
      }
      // The url getter steps are to return this 's url , serialized .
      get url() {
        return this.#url.toString();
      }
      // The opened getter steps are to return this 's opened promise .
      get opened() {
        return this.#openedPromise.promise;
      }
      // The closed getter steps are to return this 's closed promise .
      get closed() {
        return this.#closedPromise.promise;
      }
      // The close( closeInfo ) method steps are:
      close(closeInfo = void 0) {
        if (closeInfo !== null) {
          closeInfo = webidl.converters.WebSocketCloseInfo(closeInfo);
        }
        const code2 = closeInfo.closeCode ?? null;
        const reason = closeInfo.reason;
        closeWebSocketConnection(this.#handler, code2, reason, true);
      }
      #write(chunk) {
        const promise = createDeferredPromise();
        let data = null;
        let opcode = null;
        if (ArrayBuffer.isView(chunk) || isArrayBuffer(chunk)) {
          data = new Uint8Array(ArrayBuffer.isView(chunk) ? new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength) : chunk);
          opcode = opcodes.BINARY;
        } else {
          let string;
          try {
            string = webidl.converters.DOMString(chunk);
          } catch (e2) {
            promise.reject(e2);
            return;
          }
          data = new TextEncoder().encode(string);
          opcode = opcodes.TEXT;
        }
        if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
          const frame = new WebsocketFrameSend(data);
          this.#handler.socket.write(frame.createFrame(opcode), () => {
            promise.resolve(void 0);
          });
        }
        return promise;
      }
      /** @type {import('../websocket').Handler['onConnectionEstablished']} */
      #onConnectionEstablished(response, parsedExtensions) {
        this.#handler.socket = response.socket;
        const parser6 = new ByteParser(this.#handler, parsedExtensions);
        parser6.on("drain", () => this.#handler.onParserDrain());
        parser6.on("error", (err) => this.#handler.onParserError(err));
        this.#parser = parser6;
        this.#handler.readyState = states.OPEN;
        const extensions = parsedExtensions ?? "";
        const protocol = response.headersList.get("sec-websocket-protocol") ?? "";
        const readable = new ReadableStream({
          start: /* @__PURE__ */ __name((controller) => {
            this.#readableStreamController = controller;
          }, "start"),
          pull(controller) {
            let chunk;
            while (controller.desiredSize > 0 && (chunk = response.socket.read()) !== null) {
              controller.enqueue(chunk);
            }
          },
          cancel: /* @__PURE__ */ __name((reason) => this.#cancel(reason), "cancel")
        });
        const writable = new WritableStream({
          write: /* @__PURE__ */ __name((chunk) => this.#write(chunk), "write"),
          close: /* @__PURE__ */ __name(() => closeWebSocketConnection(this.#handler, null, null), "close"),
          abort: /* @__PURE__ */ __name((reason) => this.#closeUsingReason(reason), "abort")
        });
        this.#readableStream = readable;
        this.#writableStream = writable;
        this.#openedPromise.resolve({
          extensions,
          protocol,
          readable,
          writable
        });
      }
      /** @type {import('../websocket').Handler['onMessage']} */
      #onMessage(type, data) {
        if (this.#handler.readyState !== states.OPEN) {
          return;
        }
        let chunk;
        if (type === opcodes.TEXT) {
          try {
            chunk = utf8Decode(data);
          } catch {
            failWebsocketConnection(this.#handler, "Received invalid UTF-8 in text frame.");
            return;
          }
        } else if (type === opcodes.BINARY) {
          chunk = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
        }
        this.#readableStreamController.enqueue(chunk);
      }
      /** @type {import('../websocket').Handler['onSocketClose']} */
      #onSocketClose() {
        const wasClean = this.#handler.closeState.has(sentCloseFrameState.SENT) && this.#handler.closeState.has(sentCloseFrameState.RECEIVED);
        this.#handler.readyState = states.CLOSED;
        if (this.#handshakeAborted) {
          return;
        }
        if (!this.#handler.wasEverConnected) {
          this.#openedPromise.reject(new WebSocketError("Socket never opened"));
        }
        const result = this.#parser.closingInfo;
        let code2 = result?.code ?? 1005;
        if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
          code2 = 1006;
        }
        const reason = result?.reason == null ? "" : utf8DecodeBytes(Buffer.from(result.reason));
        if (wasClean) {
          this.#readableStreamController.close();
          if (!this.#writableStream.locked) {
            this.#writableStream.abort(new DOMException("A closed WebSocketStream cannot be written to", "InvalidStateError"));
          }
          this.#closedPromise.resolve({
            closeCode: code2,
            reason
          });
        } else {
          const error = createUnvalidatedWebSocketError("unclean close", code2, reason);
          this.#readableStreamController.error(error);
          this.#writableStream.abort(error);
          this.#closedPromise.reject(error);
        }
      }
      #closeUsingReason(reason) {
        let code2 = null;
        let reasonString = "";
        if (webidl.is.WebSocketError(reason)) {
          code2 = reason.closeCode;
          reasonString = reason.reason;
        }
        closeWebSocketConnection(this.#handler, code2, reasonString);
      }
      //  To cancel a WebSocketStream stream given reason , close using reason giving stream and reason .
      #cancel(reason) {
        this.#closeUsingReason(reason);
      }
    };
    Object.defineProperties(WebSocketStream.prototype, {
      url: kEnumerableProperty,
      opened: kEnumerableProperty,
      closed: kEnumerableProperty,
      close: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "WebSocketStream",
        writable: false,
        enumerable: false,
        configurable: true
      }
    });
    webidl.converters.WebSocketStreamOptions = webidl.dictionaryConverter([
      {
        key: "protocols",
        converter: webidl.sequenceConverter(webidl.converters.USVString),
        defaultValue: /* @__PURE__ */ __name(() => [], "defaultValue")
      },
      {
        key: "signal",
        converter: webidl.nullableConverter(webidl.converters.AbortSignal),
        defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
      }
    ]);
    webidl.converters.WebSocketCloseInfo = webidl.dictionaryConverter([
      {
        key: "closeCode",
        converter: /* @__PURE__ */ __name((V2) => webidl.converters["unsigned short"](V2, { enforceRange: true }), "converter")
      },
      {
        key: "reason",
        converter: webidl.converters.USVString,
        defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
      }
    ]);
    module2.exports = { WebSocketStream };
  }
});

// node_modules/undici/lib/web/eventsource/util.js
var require_util6 = __commonJS({
  "node_modules/undici/lib/web/eventsource/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    function isValidLastEventId(value) {
      return value.indexOf("\0") === -1;
    }
    __name(isValidLastEventId, "isValidLastEventId");
    function isASCIINumber(value) {
      if (value.length === 0) return false;
      for (let i = 0; i < value.length; i++) {
        if (value.charCodeAt(i) < 48 || value.charCodeAt(i) > 57) return false;
      }
      return true;
    }
    __name(isASCIINumber, "isASCIINumber");
    function delay4(ms) {
      return new Promise((resolve24) => {
        setTimeout(resolve24, ms);
      });
    }
    __name(delay4, "delay");
    module2.exports = {
      isValidLastEventId,
      isASCIINumber,
      delay: delay4
    };
  }
});

// node_modules/undici/lib/web/eventsource/eventsource-stream.js
var require_eventsource_stream = __commonJS({
  "node_modules/undici/lib/web/eventsource/eventsource-stream.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { Transform: Transform2 } = __require("node:stream");
    var { isASCIINumber, isValidLastEventId } = require_util6();
    var BOM = [239, 187, 191];
    var LF = 10;
    var CR = 13;
    var COLON = 58;
    var SPACE = 32;
    var EventSourceStream = class extends Transform2 {
      static {
        __name(this, "EventSourceStream");
      }
      /**
       * @type {eventSourceSettings}
       */
      state;
      /**
       * Leading byte-order-mark check.
       * @type {boolean}
       */
      checkBOM = true;
      /**
       * @type {boolean}
       */
      crlfCheck = false;
      /**
       * @type {boolean}
       */
      eventEndCheck = false;
      /**
       * @type {Buffer|null}
       */
      buffer = null;
      pos = 0;
      event = {
        data: void 0,
        event: void 0,
        id: void 0,
        retry: void 0
      };
      /**
       * @param {object} options
       * @param {boolean} [options.readableObjectMode]
       * @param {eventSourceSettings} [options.eventSourceSettings]
       * @param {(chunk: any, encoding?: BufferEncoding | undefined) => boolean} [options.push]
       */
      constructor(options2 = {}) {
        options2.readableObjectMode = true;
        super(options2);
        this.state = options2.eventSourceSettings || {};
        if (options2.push) {
          this.push = options2.push;
        }
      }
      /**
       * @param {Buffer} chunk
       * @param {string} _encoding
       * @param {Function} callback
       * @returns {void}
       */
      _transform(chunk, _encoding, callback) {
        if (chunk.length === 0) {
          callback();
          return;
        }
        if (this.buffer) {
          this.buffer = Buffer.concat([this.buffer, chunk]);
        } else {
          this.buffer = chunk;
        }
        if (this.checkBOM) {
          switch (this.buffer.length) {
            case 1:
              if (this.buffer[0] === BOM[0]) {
                callback();
                return;
              }
              this.checkBOM = false;
              callback();
              return;
            case 2:
              if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) {
                callback();
                return;
              }
              this.checkBOM = false;
              break;
            case 3:
              if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) {
                this.buffer = Buffer.alloc(0);
                this.checkBOM = false;
                callback();
                return;
              }
              this.checkBOM = false;
              break;
            default:
              if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) {
                this.buffer = this.buffer.subarray(3);
              }
              this.checkBOM = false;
              break;
          }
        }
        while (this.pos < this.buffer.length) {
          if (this.eventEndCheck) {
            if (this.crlfCheck) {
              if (this.buffer[this.pos] === LF) {
                this.buffer = this.buffer.subarray(this.pos + 1);
                this.pos = 0;
                this.crlfCheck = false;
                continue;
              }
              this.crlfCheck = false;
            }
            if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
              if (this.buffer[this.pos] === CR) {
                this.crlfCheck = true;
              }
              this.buffer = this.buffer.subarray(this.pos + 1);
              this.pos = 0;
              if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) {
                this.processEvent(this.event);
              }
              this.clearEvent();
              continue;
            }
            this.eventEndCheck = false;
            continue;
          }
          if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
            if (this.buffer[this.pos] === CR) {
              this.crlfCheck = true;
            }
            this.parseLine(this.buffer.subarray(0, this.pos), this.event);
            this.buffer = this.buffer.subarray(this.pos + 1);
            this.pos = 0;
            this.eventEndCheck = true;
            continue;
          }
          this.pos++;
        }
        callback();
      }
      /**
       * @param {Buffer} line
       * @param {EventSourceStreamEvent} event
       */
      parseLine(line, event) {
        if (line.length === 0) {
          return;
        }
        const colonPosition = line.indexOf(COLON);
        if (colonPosition === 0) {
          return;
        }
        let field = "";
        let value = "";
        if (colonPosition !== -1) {
          field = line.subarray(0, colonPosition).toString("utf8");
          let valueStart = colonPosition + 1;
          if (line[valueStart] === SPACE) {
            ++valueStart;
          }
          value = line.subarray(valueStart).toString("utf8");
        } else {
          field = line.toString("utf8");
          value = "";
        }
        switch (field) {
          case "data":
            if (event[field] === void 0) {
              event[field] = value;
            } else {
              event[field] += `
${value}`;
            }
            break;
          case "retry":
            if (isASCIINumber(value)) {
              event[field] = value;
            }
            break;
          case "id":
            if (isValidLastEventId(value)) {
              event[field] = value;
            }
            break;
          case "event":
            if (value.length > 0) {
              event[field] = value;
            }
            break;
        }
      }
      /**
       * @param {EventSourceStreamEvent} event
       */
      processEvent(event) {
        if (event.retry && isASCIINumber(event.retry)) {
          this.state.reconnectionTime = parseInt(event.retry, 10);
        }
        if (event.id && isValidLastEventId(event.id)) {
          this.state.lastEventId = event.id;
        }
        if (event.data !== void 0) {
          this.push({
            type: event.event || "message",
            options: {
              data: event.data,
              lastEventId: this.state.lastEventId,
              origin: this.state.origin
            }
          });
        }
      }
      clearEvent() {
        this.event = {
          data: void 0,
          event: void 0,
          id: void 0,
          retry: void 0
        };
      }
    };
    module2.exports = {
      EventSourceStream
    };
  }
});

// node_modules/undici/lib/web/eventsource/eventsource.js
var require_eventsource = __commonJS({
  "node_modules/undici/lib/web/eventsource/eventsource.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { pipeline } = __require("node:stream");
    var { fetching } = require_fetch();
    var { makeRequest } = require_request2();
    var { webidl } = require_webidl();
    var { EventSourceStream } = require_eventsource_stream();
    var { parseMIMEType } = require_data_url();
    var { createFastMessageEvent } = require_events();
    var { isNetworkError } = require_response();
    var { delay: delay4 } = require_util6();
    var { kEnumerableProperty } = require_util();
    var { environmentSettingsObject } = require_util2();
    var experimentalWarned = false;
    var defaultReconnectionTime = 3e3;
    var CONNECTING = 0;
    var OPEN = 1;
    var CLOSED2 = 2;
    var ANONYMOUS = "anonymous";
    var USE_CREDENTIALS = "use-credentials";
    var EventSource2 = class _EventSource extends EventTarget {
      static {
        __name(this, "EventSource");
      }
      #events = {
        open: null,
        error: null,
        message: null
      };
      #url;
      #withCredentials = false;
      /**
       * @type {ReadyState}
       */
      #readyState = CONNECTING;
      #request = null;
      #controller = null;
      #dispatcher;
      /**
       * @type {import('./eventsource-stream').eventSourceSettings}
       */
      #state;
      /**
       * Creates a new EventSource object.
       * @param {string} url
       * @param {EventSourceInit} [eventSourceInitDict={}]
       * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface
       */
      constructor(url2, eventSourceInitDict = {}) {
        super();
        webidl.util.markAsUncloneable(this);
        const prefix = "EventSource constructor";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        if (!experimentalWarned) {
          experimentalWarned = true;
          process.emitWarning("EventSource is experimental, expect them to change at any time.", {
            code: "UNDICI-ES"
          });
        }
        url2 = webidl.converters.USVString(url2);
        eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, "eventSourceInitDict");
        this.#dispatcher = eventSourceInitDict.node.dispatcher || eventSourceInitDict.dispatcher;
        this.#state = {
          lastEventId: "",
          reconnectionTime: eventSourceInitDict.node.reconnectionTime
        };
        const settings = environmentSettingsObject;
        let urlRecord;
        try {
          urlRecord = new URL(url2, settings.settingsObject.baseUrl);
          this.#state.origin = urlRecord.origin;
        } catch (e2) {
          throw new DOMException(e2, "SyntaxError");
        }
        this.#url = urlRecord.href;
        let corsAttributeState = ANONYMOUS;
        if (eventSourceInitDict.withCredentials === true) {
          corsAttributeState = USE_CREDENTIALS;
          this.#withCredentials = true;
        }
        const initRequest = {
          redirect: "follow",
          keepalive: true,
          // @see https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes
          mode: "cors",
          credentials: corsAttributeState === "anonymous" ? "same-origin" : "omit",
          referrer: "no-referrer"
        };
        initRequest.client = environmentSettingsObject.settingsObject;
        initRequest.headersList = [["accept", { name: "accept", value: "text/event-stream" }]];
        initRequest.cache = "no-store";
        initRequest.initiator = "other";
        initRequest.urlList = [new URL(this.#url)];
        this.#request = makeRequest(initRequest);
        this.#connect();
      }
      /**
       * Returns the state of this EventSource object's connection. It can have the
       * values described below.
       * @returns {ReadyState}
       * @readonly
       */
      get readyState() {
        return this.#readyState;
      }
      /**
       * Returns the URL providing the event stream.
       * @readonly
       * @returns {string}
       */
      get url() {
        return this.#url;
      }
      /**
       * Returns a boolean indicating whether the EventSource object was
       * instantiated with CORS credentials set (true), or not (false, the default).
       */
      get withCredentials() {
        return this.#withCredentials;
      }
      #connect() {
        if (this.#readyState === CLOSED2) return;
        this.#readyState = CONNECTING;
        const fetchParams = {
          request: this.#request,
          dispatcher: this.#dispatcher
        };
        const processEventSourceEndOfBody = /* @__PURE__ */ __name((response) => {
          if (!isNetworkError(response)) {
            return this.#reconnect();
          }
        }, "processEventSourceEndOfBody");
        fetchParams.processResponseEndOfBody = processEventSourceEndOfBody;
        fetchParams.processResponse = (response) => {
          if (isNetworkError(response)) {
            if (response.aborted) {
              this.close();
              this.dispatchEvent(new Event("error"));
              return;
            } else {
              this.#reconnect();
              return;
            }
          }
          const contentType = response.headersList.get("content-type", true);
          const mimeType = contentType !== null ? parseMIMEType(contentType) : "failure";
          const contentTypeValid = mimeType !== "failure" && mimeType.essence === "text/event-stream";
          if (response.status !== 200 || contentTypeValid === false) {
            this.close();
            this.dispatchEvent(new Event("error"));
            return;
          }
          this.#readyState = OPEN;
          this.dispatchEvent(new Event("open"));
          this.#state.origin = response.urlList[response.urlList.length - 1].origin;
          const eventSourceStream = new EventSourceStream({
            eventSourceSettings: this.#state,
            push: /* @__PURE__ */ __name((event) => {
              this.dispatchEvent(createFastMessageEvent(
                event.type,
                event.options
              ));
            }, "push")
          });
          pipeline(
            response.body.stream,
            eventSourceStream,
            (error) => {
              if (error?.aborted === false) {
                this.close();
                this.dispatchEvent(new Event("error"));
              }
            }
          );
        };
        this.#controller = fetching(fetchParams);
      }
      /**
       * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model
       * @returns {Promise<void>}
       */
      async #reconnect() {
        if (this.#readyState === CLOSED2) return;
        this.#readyState = CONNECTING;
        this.dispatchEvent(new Event("error"));
        await delay4(this.#state.reconnectionTime);
        if (this.#readyState !== CONNECTING) return;
        if (this.#state.lastEventId.length) {
          this.#request.headersList.set("last-event-id", this.#state.lastEventId, true);
        }
        this.#connect();
      }
      /**
       * Closes the connection, if any, and sets the readyState attribute to
       * CLOSED.
       */
      close() {
        webidl.brandCheck(this, _EventSource);
        if (this.#readyState === CLOSED2) return;
        this.#readyState = CLOSED2;
        this.#controller.abort();
        this.#request = null;
      }
      get onopen() {
        return this.#events.open;
      }
      set onopen(fn) {
        if (this.#events.open) {
          this.removeEventListener("open", this.#events.open);
        }
        if (typeof fn === "function") {
          this.#events.open = fn;
          this.addEventListener("open", fn);
        } else {
          this.#events.open = null;
        }
      }
      get onmessage() {
        return this.#events.message;
      }
      set onmessage(fn) {
        if (this.#events.message) {
          this.removeEventListener("message", this.#events.message);
        }
        if (typeof fn === "function") {
          this.#events.message = fn;
          this.addEventListener("message", fn);
        } else {
          this.#events.message = null;
        }
      }
      get onerror() {
        return this.#events.error;
      }
      set onerror(fn) {
        if (this.#events.error) {
          this.removeEventListener("error", this.#events.error);
        }
        if (typeof fn === "function") {
          this.#events.error = fn;
          this.addEventListener("error", fn);
        } else {
          this.#events.error = null;
        }
      }
    };
    var constantsPropertyDescriptors = {
      CONNECTING: {
        __proto__: null,
        configurable: false,
        enumerable: true,
        value: CONNECTING,
        writable: false
      },
      OPEN: {
        __proto__: null,
        configurable: false,
        enumerable: true,
        value: OPEN,
        writable: false
      },
      CLOSED: {
        __proto__: null,
        configurable: false,
        enumerable: true,
        value: CLOSED2,
        writable: false
      }
    };
    Object.defineProperties(EventSource2, constantsPropertyDescriptors);
    Object.defineProperties(EventSource2.prototype, constantsPropertyDescriptors);
    Object.defineProperties(EventSource2.prototype, {
      close: kEnumerableProperty,
      onerror: kEnumerableProperty,
      onmessage: kEnumerableProperty,
      onopen: kEnumerableProperty,
      readyState: kEnumerableProperty,
      url: kEnumerableProperty,
      withCredentials: kEnumerableProperty
    });
    webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([
      {
        key: "withCredentials",
        converter: webidl.converters.boolean,
        defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
      },
      {
        key: "dispatcher",
        // undici only
        converter: webidl.converters.any
      },
      {
        key: "node",
        // undici only
        converter: webidl.dictionaryConverter([
          {
            key: "reconnectionTime",
            converter: webidl.converters["unsigned long"],
            defaultValue: /* @__PURE__ */ __name(() => defaultReconnectionTime, "defaultValue")
          },
          {
            key: "dispatcher",
            converter: webidl.converters.any
          }
        ]),
        defaultValue: /* @__PURE__ */ __name(() => ({}), "defaultValue")
      }
    ]);
    module2.exports = {
      EventSource: EventSource2,
      defaultReconnectionTime
    };
  }
});

// node_modules/undici/index.js
var require_undici = __commonJS({
  "node_modules/undici/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Client2 = require_client();
    var Dispatcher = require_dispatcher();
    var Pool = require_pool();
    var BalancedPool = require_balanced_pool();
    var Agent3 = require_agent();
    var ProxyAgent5 = require_proxy_agent();
    var EnvHttpProxyAgent2 = require_env_http_proxy_agent();
    var RetryAgent = require_retry_agent();
    var H2CClient = require_h2c_client();
    var errors = require_errors();
    var util4 = require_util();
    var { InvalidArgumentError } = errors;
    var api = require_api();
    var buildConnector = require_connect();
    var MockClient = require_mock_client();
    var { MockCallHistory, MockCallHistoryLog } = require_mock_call_history();
    var MockAgent = require_mock_agent();
    var MockPool = require_mock_pool();
    var SnapshotAgent = require_snapshot_agent();
    var mockErrors = require_mock_errors();
    var RetryHandler = require_retry_handler();
    var { getGlobalDispatcher, setGlobalDispatcher: setGlobalDispatcher3 } = require_global2();
    var DecoratorHandler = require_decorator_handler();
    var RedirectHandler = require_redirect_handler();
    Object.assign(Dispatcher.prototype, api);
    module2.exports.Dispatcher = Dispatcher;
    module2.exports.Client = Client2;
    module2.exports.Pool = Pool;
    module2.exports.BalancedPool = BalancedPool;
    module2.exports.Agent = Agent3;
    module2.exports.ProxyAgent = ProxyAgent5;
    module2.exports.EnvHttpProxyAgent = EnvHttpProxyAgent2;
    module2.exports.RetryAgent = RetryAgent;
    module2.exports.H2CClient = H2CClient;
    module2.exports.RetryHandler = RetryHandler;
    module2.exports.DecoratorHandler = DecoratorHandler;
    module2.exports.RedirectHandler = RedirectHandler;
    module2.exports.interceptors = {
      redirect: require_redirect(),
      responseError: require_response_error(),
      retry: require_retry(),
      dump: require_dump(),
      dns: require_dns(),
      cache: require_cache2(),
      decompress: require_decompress()
    };
    module2.exports.cacheStores = {
      MemoryCacheStore: require_memory_cache_store()
    };
    var SqliteCacheStore = require_sqlite_cache_store();
    module2.exports.cacheStores.SqliteCacheStore = SqliteCacheStore;
    module2.exports.buildConnector = buildConnector;
    module2.exports.errors = errors;
    module2.exports.util = {
      parseHeaders: util4.parseHeaders,
      headerNameToString: util4.headerNameToString
    };
    function makeDispatcher(fn) {
      return (url2, opts, handler) => {
        if (typeof opts === "function") {
          handler = opts;
          opts = null;
        }
        if (!url2 || typeof url2 !== "string" && typeof url2 !== "object" && !(url2 instanceof URL)) {
          throw new InvalidArgumentError("invalid url");
        }
        if (opts != null && typeof opts !== "object") {
          throw new InvalidArgumentError("invalid opts");
        }
        if (opts && opts.path != null) {
          if (typeof opts.path !== "string") {
            throw new InvalidArgumentError("invalid opts.path");
          }
          let path108 = opts.path;
          if (!opts.path.startsWith("/")) {
            path108 = `/${path108}`;
          }
          url2 = new URL(util4.parseOrigin(url2).origin + path108);
        } else {
          if (!opts) {
            opts = typeof url2 === "object" ? url2 : {};
          }
          url2 = util4.parseURL(url2);
        }
        const { agent, dispatcher = getGlobalDispatcher() } = opts;
        if (agent) {
          throw new InvalidArgumentError("unsupported opts.agent. Did you mean opts.client?");
        }
        return fn.call(dispatcher, {
          ...opts,
          origin: url2.origin,
          path: url2.search ? `${url2.pathname}${url2.search}` : url2.pathname,
          method: opts.method || (opts.body ? "PUT" : "GET")
        }, handler);
      };
    }
    __name(makeDispatcher, "makeDispatcher");
    module2.exports.setGlobalDispatcher = setGlobalDispatcher3;
    module2.exports.getGlobalDispatcher = getGlobalDispatcher;
    var fetchImpl = require_fetch().fetch;
    module2.exports.fetch = /* @__PURE__ */ __name(async function fetch2(init, options2 = void 0) {
      try {
        return await fetchImpl(init, options2);
      } catch (err) {
        if (err && typeof err === "object") {
          Error.captureStackTrace(err);
        }
        throw err;
      }
    }, "fetch");
    module2.exports.Headers = require_headers().Headers;
    module2.exports.Response = require_response().Response;
    module2.exports.Request = require_request2().Request;
    module2.exports.FormData = require_formdata().FormData;
    var { setGlobalOrigin, getGlobalOrigin } = require_global();
    module2.exports.setGlobalOrigin = setGlobalOrigin;
    module2.exports.getGlobalOrigin = getGlobalOrigin;
    var { CacheStorage } = require_cachestorage();
    var { kConstruct } = require_symbols();
    module2.exports.caches = new CacheStorage(kConstruct);
    var { deleteCookie, getCookies, getSetCookies, setCookie, parseCookie } = require_cookies();
    module2.exports.deleteCookie = deleteCookie;
    module2.exports.getCookies = getCookies;
    module2.exports.getSetCookies = getSetCookies;
    module2.exports.setCookie = setCookie;
    module2.exports.parseCookie = parseCookie;
    var { parseMIMEType, serializeAMimeType } = require_data_url();
    module2.exports.parseMIMEType = parseMIMEType;
    module2.exports.serializeAMimeType = serializeAMimeType;
    var { CloseEvent, ErrorEvent: ErrorEvent2, MessageEvent: MessageEvent2 } = require_events();
    var { WebSocket: WebSocket2, ping } = require_websocket2();
    module2.exports.WebSocket = WebSocket2;
    module2.exports.CloseEvent = CloseEvent;
    module2.exports.ErrorEvent = ErrorEvent2;
    module2.exports.MessageEvent = MessageEvent2;
    module2.exports.ping = ping;
    module2.exports.WebSocketStream = require_websocketstream().WebSocketStream;
    module2.exports.WebSocketError = require_websocketerror().WebSocketError;
    module2.exports.request = makeDispatcher(api.request);
    module2.exports.stream = makeDispatcher(api.stream);
    module2.exports.pipeline = makeDispatcher(api.pipeline);
    module2.exports.connect = makeDispatcher(api.connect);
    module2.exports.upgrade = makeDispatcher(api.upgrade);
    module2.exports.MockClient = MockClient;
    module2.exports.MockCallHistory = MockCallHistory;
    module2.exports.MockCallHistoryLog = MockCallHistoryLog;
    module2.exports.MockPool = MockPool;
    module2.exports.MockAgent = MockAgent;
    module2.exports.SnapshotAgent = SnapshotAgent;
    module2.exports.mockErrors = mockErrors;
    var { EventSource: EventSource2 } = require_eventsource();
    module2.exports.EventSource = EventSource2;
    function install() {
      globalThis.fetch = module2.exports.fetch;
      globalThis.Headers = module2.exports.Headers;
      globalThis.Response = module2.exports.Response;
      globalThis.Request = module2.exports.Request;
      globalThis.FormData = module2.exports.FormData;
      globalThis.WebSocket = module2.exports.WebSocket;
      globalThis.CloseEvent = module2.exports.CloseEvent;
      globalThis.ErrorEvent = module2.exports.ErrorEvent;
      globalThis.MessageEvent = module2.exports.MessageEvent;
      globalThis.EventSource = module2.exports.EventSource;
    }
    __name(install, "install");
    module2.exports.install = install;
  }
});

// packages/core/dist/src/utils/errorReporting.js
import fs2 from "node:fs/promises";
import os2 from "node:os";
import path from "node:path";
async function reportError2(error, baseMessage, context2, type = "general", reportingDir = os2.tmpdir()) {
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
  const reportFileName = `qwen-client-error-${type}-${timestamp}.json`;
  const reportPath = path.join(reportingDir, reportFileName);
  let errorToReport;
  if (error instanceof Error) {
    errorToReport = { message: error.message, stack: error.stack };
  } else if (typeof error === "object" && error !== null && "message" in error) {
    errorToReport = {
      message: String(error.message)
    };
  } else {
    errorToReport = { message: String(error) };
  }
  const reportContent = { error: errorToReport };
  if (context2) {
    reportContent.context = context2;
  }
  let stringifiedReportContent;
  try {
    stringifiedReportContent = JSON.stringify(reportContent, null, 2);
  } catch (stringifyError) {
    console.error(`${baseMessage} Could not stringify report content (likely due to context):`, stringifyError);
    console.error("Original error that triggered report generation:", error);
    if (context2) {
      console.error("Original context could not be stringified or included in report.");
    }
    try {
      const minimalReportContent = { error: errorToReport };
      stringifiedReportContent = JSON.stringify(minimalReportContent, null, 2);
      await fs2.writeFile(reportPath, stringifiedReportContent);
      console.error(`${baseMessage} Partial report (excluding context) available at: ${reportPath}`);
    } catch (minimalWriteError) {
      console.error(`${baseMessage} Failed to write even a minimal error report:`, minimalWriteError);
    }
    return;
  }
  try {
    await fs2.writeFile(reportPath, stringifiedReportContent);
    console.error(`${baseMessage} Full report available at: ${reportPath}`);
  } catch (writeError) {
    console.error(`${baseMessage} Additionally, failed to write detailed error report:`, writeError);
    console.error("Original error that triggered report generation:", error);
    if (context2) {
      try {
        console.error("Original context:", context2);
      } catch {
        try {
          console.error("Original context (stringified, truncated):", JSON.stringify(context2).substring(0, 1e3));
        } catch {
          console.error("Original context could not be logged or stringified.");
        }
      }
    }
  }
}
var init_errorReporting = __esm({
  "packages/core/dist/src/utils/errorReporting.js"() {
    "use strict";
    init_esbuild_shims();
    __name(reportError2, "reportError");
  }
});

// packages/core/dist/src/utils/errors.js
function isNodeError(error) {
  return error instanceof Error && "code" in error;
}
function getErrorMessage(error) {
  if (error instanceof Error) {
    return error.message;
  }
  try {
    return String(error);
  } catch {
    return "Failed to get error details";
  }
}
function toFriendlyError(error) {
  if (error && typeof error === "object" && "response" in error) {
    const gaxiosError = error;
    const data = parseResponseData(gaxiosError);
    if (data.error && data.error.message && data.error.code) {
      switch (data.error.code) {
        case 400:
          return new BadRequestError(data.error.message);
        case 401:
          return new UnauthorizedError(data.error.message);
        case 403:
          return new ForbiddenError(data.error.message);
        default:
      }
    }
  }
  return error;
}
function parseResponseData(error) {
  if (typeof error.response?.data === "string") {
    return JSON.parse(error.response?.data);
  }
  return error.response?.data;
}
var FatalError, FatalAuthenticationError, FatalInputError, FatalSandboxError, FatalConfigError, FatalTurnLimitedError, FatalToolExecutionError, FatalCancellationError, ForbiddenError, UnauthorizedError, BadRequestError;
var init_errors = __esm({
  "packages/core/dist/src/utils/errors.js"() {
    "use strict";
    init_esbuild_shims();
    __name(isNodeError, "isNodeError");
    __name(getErrorMessage, "getErrorMessage");
    FatalError = class extends Error {
      static {
        __name(this, "FatalError");
      }
      exitCode;
      constructor(message, exitCode) {
        super(message);
        this.exitCode = exitCode;
      }
    };
    FatalAuthenticationError = class extends FatalError {
      static {
        __name(this, "FatalAuthenticationError");
      }
      constructor(message) {
        super(message, 41);
      }
    };
    FatalInputError = class extends FatalError {
      static {
        __name(this, "FatalInputError");
      }
      constructor(message) {
        super(message, 42);
      }
    };
    FatalSandboxError = class extends FatalError {
      static {
        __name(this, "FatalSandboxError");
      }
      constructor(message) {
        super(message, 44);
      }
    };
    FatalConfigError = class extends FatalError {
      static {
        __name(this, "FatalConfigError");
      }
      constructor(message) {
        super(message, 52);
      }
    };
    FatalTurnLimitedError = class extends FatalError {
      static {
        __name(this, "FatalTurnLimitedError");
      }
      constructor(message) {
        super(message, 53);
      }
    };
    FatalToolExecutionError = class extends FatalError {
      static {
        __name(this, "FatalToolExecutionError");
      }
      constructor(message) {
        super(message, 54);
      }
    };
    FatalCancellationError = class extends FatalError {
      static {
        __name(this, "FatalCancellationError");
      }
      constructor(message) {
        super(message, 130);
      }
    };
    ForbiddenError = class extends Error {
      static {
        __name(this, "ForbiddenError");
      }
    };
    UnauthorizedError = class extends Error {
      static {
        __name(this, "UnauthorizedError");
      }
    };
    BadRequestError = class extends Error {
      static {
        __name(this, "BadRequestError");
      }
    };
    __name(toFriendlyError, "toFriendlyError");
    __name(parseResponseData, "parseResponseData");
  }
});

// node_modules/extend/index.js
var require_extend = __commonJS({
  "node_modules/extend/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var hasOwn2 = Object.prototype.hasOwnProperty;
    var toStr = Object.prototype.toString;
    var defineProperty2 = Object.defineProperty;
    var gOPD = Object.getOwnPropertyDescriptor;
    var isArray2 = /* @__PURE__ */ __name(function isArray3(arr) {
      if (typeof Array.isArray === "function") {
        return Array.isArray(arr);
      }
      return toStr.call(arr) === "[object Array]";
    }, "isArray");
    var isPlainObject2 = /* @__PURE__ */ __name(function isPlainObject3(obj) {
      if (!obj || toStr.call(obj) !== "[object Object]") {
        return false;
      }
      var hasOwnConstructor = hasOwn2.call(obj, "constructor");
      var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn2.call(obj.constructor.prototype, "isPrototypeOf");
      if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
        return false;
      }
      var key;
      for (key in obj) {
      }
      return typeof key === "undefined" || hasOwn2.call(obj, key);
    }, "isPlainObject");
    var setProperty2 = /* @__PURE__ */ __name(function setProperty3(target, options2) {
      if (defineProperty2 && options2.name === "__proto__") {
        defineProperty2(target, options2.name, {
          enumerable: true,
          configurable: true,
          value: options2.newValue,
          writable: true
        });
      } else {
        target[options2.name] = options2.newValue;
      }
    }, "setProperty");
    var getProperty2 = /* @__PURE__ */ __name(function getProperty3(obj, name3) {
      if (name3 === "__proto__") {
        if (!hasOwn2.call(obj, name3)) {
          return void 0;
        } else if (gOPD) {
          return gOPD(obj, name3).value;
        }
      }
      return obj[name3];
    }, "getProperty");
    module2.exports = /* @__PURE__ */ __name(function extend() {
      var options2, name3, src, copy, copyIsArray, clone;
      var target = arguments[0];
      var i = 1;
      var length = arguments.length;
      var deep = false;
      if (typeof target === "boolean") {
        deep = target;
        target = arguments[1] || {};
        i = 2;
      }
      if (target == null || typeof target !== "object" && typeof target !== "function") {
        target = {};
      }
      for (; i < length; ++i) {
        options2 = arguments[i];
        if (options2 != null) {
          for (name3 in options2) {
            src = getProperty2(target, name3);
            copy = getProperty2(options2, name3);
            if (target !== copy) {
              if (deep && copy && (isPlainObject2(copy) || (copyIsArray = isArray2(copy)))) {
                if (copyIsArray) {
                  copyIsArray = false;
                  clone = src && isArray2(src) ? src : [];
                } else {
                  clone = src && isPlainObject2(src) ? src : {};
                }
                setProperty2(target, { name: name3, newValue: extend(deep, clone, copy) });
              } else if (typeof copy !== "undefined") {
                setProperty2(target, { name: name3, newValue: copy });
              }
            }
          }
        }
      }
      return target;
    }, "extend");
  }
});

// node_modules/node-fetch/node_modules/webidl-conversions/lib/index.js
var require_lib = __commonJS({
  "node_modules/node-fetch/node_modules/webidl-conversions/lib/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var conversions = {};
    module2.exports = conversions;
    function sign(x) {
      return x < 0 ? -1 : 1;
    }
    __name(sign, "sign");
    function evenRound(x) {
      if (x % 1 === 0.5 && (x & 1) === 0) {
        return Math.floor(x);
      } else {
        return Math.round(x);
      }
    }
    __name(evenRound, "evenRound");
    function createNumberConversion(bitLength, typeOpts) {
      if (!typeOpts.unsigned) {
        --bitLength;
      }
      const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength);
      const upperBound = Math.pow(2, bitLength) - 1;
      const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength);
      const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1);
      return function(V2, opts) {
        if (!opts) opts = {};
        let x = +V2;
        if (opts.enforceRange) {
          if (!Number.isFinite(x)) {
            throw new TypeError("Argument is not a finite number");
          }
          x = sign(x) * Math.floor(Math.abs(x));
          if (x < lowerBound || x > upperBound) {
            throw new TypeError("Argument is not in byte range");
          }
          return x;
        }
        if (!isNaN(x) && opts.clamp) {
          x = evenRound(x);
          if (x < lowerBound) x = lowerBound;
          if (x > upperBound) x = upperBound;
          return x;
        }
        if (!Number.isFinite(x) || x === 0) {
          return 0;
        }
        x = sign(x) * Math.floor(Math.abs(x));
        x = x % moduloVal;
        if (!typeOpts.unsigned && x >= moduloBound) {
          return x - moduloVal;
        } else if (typeOpts.unsigned) {
          if (x < 0) {
            x += moduloVal;
          } else if (x === -0) {
            return 0;
          }
        }
        return x;
      };
    }
    __name(createNumberConversion, "createNumberConversion");
    conversions["void"] = function() {
      return void 0;
    };
    conversions["boolean"] = function(val) {
      return !!val;
    };
    conversions["byte"] = createNumberConversion(8, { unsigned: false });
    conversions["octet"] = createNumberConversion(8, { unsigned: true });
    conversions["short"] = createNumberConversion(16, { unsigned: false });
    conversions["unsigned short"] = createNumberConversion(16, { unsigned: true });
    conversions["long"] = createNumberConversion(32, { unsigned: false });
    conversions["unsigned long"] = createNumberConversion(32, { unsigned: true });
    conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 });
    conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 });
    conversions["double"] = function(V2) {
      const x = +V2;
      if (!Number.isFinite(x)) {
        throw new TypeError("Argument is not a finite floating-point value");
      }
      return x;
    };
    conversions["unrestricted double"] = function(V2) {
      const x = +V2;
      if (isNaN(x)) {
        throw new TypeError("Argument is NaN");
      }
      return x;
    };
    conversions["float"] = conversions["double"];
    conversions["unrestricted float"] = conversions["unrestricted double"];
    conversions["DOMString"] = function(V2, opts) {
      if (!opts) opts = {};
      if (opts.treatNullAsEmptyString && V2 === null) {
        return "";
      }
      return String(V2);
    };
    conversions["ByteString"] = function(V2, opts) {
      const x = String(V2);
      let c3 = void 0;
      for (let i = 0; (c3 = x.codePointAt(i)) !== void 0; ++i) {
        if (c3 > 255) {
          throw new TypeError("Argument is not a valid bytestring");
        }
      }
      return x;
    };
    conversions["USVString"] = function(V2) {
      const S = String(V2);
      const n2 = S.length;
      const U = [];
      for (let i = 0; i < n2; ++i) {
        const c3 = S.charCodeAt(i);
        if (c3 < 55296 || c3 > 57343) {
          U.push(String.fromCodePoint(c3));
        } else if (56320 <= c3 && c3 <= 57343) {
          U.push(String.fromCodePoint(65533));
        } else {
          if (i === n2 - 1) {
            U.push(String.fromCodePoint(65533));
          } else {
            const d = S.charCodeAt(i + 1);
            if (56320 <= d && d <= 57343) {
              const a = c3 & 1023;
              const b = d & 1023;
              U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b));
              ++i;
            } else {
              U.push(String.fromCodePoint(65533));
            }
          }
        }
      }
      return U.join("");
    };
    conversions["Date"] = function(V2, opts) {
      if (!(V2 instanceof Date)) {
        throw new TypeError("Argument is not a Date object");
      }
      if (isNaN(V2)) {
        return void 0;
      }
      return V2;
    };
    conversions["RegExp"] = function(V2, opts) {
      if (!(V2 instanceof RegExp)) {
        V2 = new RegExp(V2);
      }
      return V2;
    };
  }
});

// node_modules/node-fetch/node_modules/whatwg-url/lib/utils.js
var require_utils2 = __commonJS({
  "node_modules/node-fetch/node_modules/whatwg-url/lib/utils.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports.mixin = /* @__PURE__ */ __name(function mixin3(target, source2) {
      const keys = Object.getOwnPropertyNames(source2);
      for (let i = 0; i < keys.length; ++i) {
        Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source2, keys[i]));
      }
    }, "mixin");
    module2.exports.wrapperSymbol = Symbol("wrapper");
    module2.exports.implSymbol = Symbol("impl");
    module2.exports.wrapperForImpl = function(impl) {
      return impl[module2.exports.wrapperSymbol];
    };
    module2.exports.implForWrapper = function(wrapper) {
      return wrapper[module2.exports.implSymbol];
    };
  }
});

// node_modules/node-fetch/node_modules/tr46/lib/mappingTable.json
var require_mappingTable = __commonJS({
  "node_modules/node-fetch/node_modules/tr46/lib/mappingTable.json"(exports2, module2) {
    module2.exports = [[[0, 44], "disallowed_STD3_valid"], [[45, 46], "valid"], [[47, 47], "disallowed_STD3_valid"], [[48, 57], "valid"], [[58, 64], "disallowed_STD3_valid"], [[65, 65], "mapped", [97]], [[66, 66], "mapped", [98]], [[67, 67], "mapped", [99]], [[68, 68], "mapped", [100]], [[69, 69], "mapped", [101]], [[70, 70], "mapped", [102]], [[71, 71], "mapped", [103]], [[72, 72], "mapped", [104]], [[73, 73], "mapped", [105]], [[74, 74], "mapped", [106]], [[75, 75], "mapped", [107]], [[76, 76], "mapped", [108]], [[77, 77], "mapped", [109]], [[78, 78], "mapped", [110]], [[79, 79], "mapped", [111]], [[80, 80], "mapped", [112]], [[81, 81], "mapped", [113]], [[82, 82], "mapped", [114]], [[83, 83], "mapped", [115]], [[84, 84], "mapped", [116]], [[85, 85], "mapped", [117]], [[86, 86], "mapped", [118]], [[87, 87], "mapped", [119]], [[88, 88], "mapped", [120]], [[89, 89], "mapped", [121]], [[90, 90], "mapped", [122]], [[91, 96], "disallowed_STD3_valid"], [[97, 122], "valid"], [[123, 127], "disallowed_STD3_valid"], [[128, 159], "disallowed"], [[160, 160], "disallowed_STD3_mapped", [32]], [[161, 167], "valid", [], "NV8"], [[168, 168], "disallowed_STD3_mapped", [32, 776]], [[169, 169], "valid", [], "NV8"], [[170, 170], "mapped", [97]], [[171, 172], "valid", [], "NV8"], [[173, 173], "ignored"], [[174, 174], "valid", [], "NV8"], [[175, 175], "disallowed_STD3_mapped", [32, 772]], [[176, 177], "valid", [], "NV8"], [[178, 178], "mapped", [50]], [[179, 179], "mapped", [51]], [[180, 180], "disallowed_STD3_mapped", [32, 769]], [[181, 181], "mapped", [956]], [[182, 182], "valid", [], "NV8"], [[183, 183], "valid"], [[184, 184], "disallowed_STD3_mapped", [32, 807]], [[185, 185], "mapped", [49]], [[186, 186], "mapped", [111]], [[187, 187], "valid", [], "NV8"], [[188, 188], "mapped", [49, 8260, 52]], [[189, 189], "mapped", [49, 8260, 50]], [[190, 190], "mapped", [51, 8260, 52]], [[191, 191], "valid", [], "NV8"], [[192, 192], "mapped", [224]], [[193, 193], "mapped", [225]], [[194, 194], "mapped", [226]], [[195, 195], "mapped", [227]], [[196, 196], "mapped", [228]], [[197, 197], "mapped", [229]], [[198, 198], "mapped", [230]], [[199, 199], "mapped", [231]], [[200, 200], "mapped", [232]], [[201, 201], "mapped", [233]], [[202, 202], "mapped", [234]], [[203, 203], "mapped", [235]], [[204, 204], "mapped", [236]], [[205, 205], "mapped", [237]], [[206, 206], "mapped", [238]], [[207, 207], "mapped", [239]], [[208, 208], "mapped", [240]], [[209, 209], "mapped", [241]], [[210, 210], "mapped", [242]], [[211, 211], "mapped", [243]], [[212, 212], "mapped", [244]], [[213, 213], "mapped", [245]], [[214, 214], "mapped", [246]], [[215, 215], "valid", [], "NV8"], [[216, 216], "mapped", [248]], [[217, 217], "mapped", [249]], [[218, 218], "mapped", [250]], [[219, 219], "mapped", [251]], [[220, 220], "mapped", [252]], [[221, 221], "mapped", [253]], [[222, 222], "mapped", [254]], [[223, 223], "deviation", [115, 115]], [[224, 246], "valid"], [[247, 247], "valid", [], "NV8"], [[248, 255], "valid"], [[256, 256], "mapped", [257]], [[257, 257], "valid"], [[258, 258], "mapped", [259]], [[259, 259], "valid"], [[260, 260], "mapped", [261]], [[261, 261], "valid"], [[262, 262], "mapped", [263]], [[263, 263], "valid"], [[264, 264], "mapped", [265]], [[265, 265], "valid"], [[266, 266], "mapped", [267]], [[267, 267], "valid"], [[268, 268], "mapped", [269]], [[269, 269], "valid"], [[270, 270], "mapped", [271]], [[271, 271], "valid"], [[272, 272], "mapped", [273]], [[273, 273], "valid"], [[274, 274], "mapped", [275]], [[275, 275], "valid"], [[276, 276], "mapped", [277]], [[277, 277], "valid"], [[278, 278], "mapped", [279]], [[279, 279], "valid"], [[280, 280], "mapped", [281]], [[281, 281], "valid"], [[282, 282], "mapped", [283]], [[283, 283], "valid"], [[284, 284], "mapped", [285]], [[285, 285], "valid"], [[286, 286], "mapped", [287]], [[287, 287], "valid"], [[288, 288], "mapped", [289]], [[289, 289], "valid"], [[290, 290], "mapped", [291]], [[291, 291], "valid"], [[292, 292], "mapped", [293]], [[293, 293], "valid"], [[294, 294], "mapped", [295]], [[295, 295], "valid"], [[296, 296], "mapped", [297]], [[297, 297], "valid"], [[298, 298], "mapped", [299]], [[299, 299], "valid"], [[300, 300], "mapped", [301]], [[301, 301], "valid"], [[302, 302], "mapped", [303]], [[303, 303], "valid"], [[304, 304], "mapped", [105, 775]], [[305, 305], "valid"], [[306, 307], "mapped", [105, 106]], [[308, 308], "mapped", [309]], [[309, 309], "valid"], [[310, 310], "mapped", [311]], [[311, 312], "valid"], [[313, 313], "mapped", [314]], [[314, 314], "valid"], [[315, 315], "mapped", [316]], [[316, 316], "valid"], [[317, 317], "mapped", [318]], [[318, 318], "valid"], [[319, 320], "mapped", [108, 183]], [[321, 321], "mapped", [322]], [[322, 322], "valid"], [[323, 323], "mapped", [324]], [[324, 324], "valid"], [[325, 325], "mapped", [326]], [[326, 326], "valid"], [[327, 327], "mapped", [328]], [[328, 328], "valid"], [[329, 329], "mapped", [700, 110]], [[330, 330], "mapped", [331]], [[331, 331], "valid"], [[332, 332], "mapped", [333]], [[333, 333], "valid"], [[334, 334], "mapped", [335]], [[335, 335], "valid"], [[336, 336], "mapped", [337]], [[337, 337], "valid"], [[338, 338], "mapped", [339]], [[339, 339], "valid"], [[340, 340], "mapped", [341]], [[341, 341], "valid"], [[342, 342], "mapped", [343]], [[343, 343], "valid"], [[344, 344], "mapped", [345]], [[345, 345], "valid"], [[346, 346], "mapped", [347]], [[347, 347], "valid"], [[348, 348], "mapped", [349]], [[349, 349], "valid"], [[350, 350], "mapped", [351]], [[351, 351], "valid"], [[352, 352], "mapped", [353]], [[353, 353], "valid"], [[354, 354], "mapped", [355]], [[355, 355], "valid"], [[356, 356], "mapped", [357]], [[357, 357], "valid"], [[358, 358], "mapped", [359]], [[359, 359], "valid"], [[360, 360], "mapped", [361]], [[361, 361], "valid"], [[362, 362], "mapped", [363]], [[363, 363], "valid"], [[364, 364], "mapped", [365]], [[365, 365], "valid"], [[366, 366], "mapped", [367]], [[367, 367], "valid"], [[368, 368], "mapped", [369]], [[369, 369], "valid"], [[370, 370], "mapped", [371]], [[371, 371], "valid"], [[372, 372], "mapped", [373]], [[373, 373], "valid"], [[374, 374], "mapped", [375]], [[375, 375], "valid"], [[376, 376], "mapped", [255]], [[377, 377], "mapped", [378]], [[378, 378], "valid"], [[379, 379], "mapped", [380]], [[380, 380], "valid"], [[381, 381], "mapped", [382]], [[382, 382], "valid"], [[383, 383], "mapped", [115]], [[384, 384], "valid"], [[385, 385], "mapped", [595]], [[386, 386], "mapped", [387]], [[387, 387], "valid"], [[388, 388], "mapped", [389]], [[389, 389], "valid"], [[390, 390], "mapped", [596]], [[391, 391], "mapped", [392]], [[392, 392], "valid"], [[393, 393], "mapped", [598]], [[394, 394], "mapped", [599]], [[395, 395], "mapped", [396]], [[396, 397], "valid"], [[398, 398], "mapped", [477]], [[399, 399], "mapped", [601]], [[400, 400], "mapped", [603]], [[401, 401], "mapped", [402]], [[402, 402], "valid"], [[403, 403], "mapped", [608]], [[404, 404], "mapped", [611]], [[405, 405], "valid"], [[406, 406], "mapped", [617]], [[407, 407], "mapped", [616]], [[408, 408], "mapped", [409]], [[409, 411], "valid"], [[412, 412], "mapped", [623]], [[413, 413], "mapped", [626]], [[414, 414], "valid"], [[415, 415], "mapped", [629]], [[416, 416], "mapped", [417]], [[417, 417], "valid"], [[418, 418], "mapped", [419]], [[419, 419], "valid"], [[420, 420], "mapped", [421]], [[421, 421], "valid"], [[422, 422], "mapped", [640]], [[423, 423], "mapped", [424]], [[424, 424], "valid"], [[425, 425], "mapped", [643]], [[426, 427], "valid"], [[428, 428], "mapped", [429]], [[429, 429], "valid"], [[430, 430], "mapped", [648]], [[431, 431], "mapped", [432]], [[432, 432], "valid"], [[433, 433], "mapped", [650]], [[434, 434], "mapped", [651]], [[435, 435], "mapped", [436]], [[436, 436], "valid"], [[437, 437], "mapped", [438]], [[438, 438], "valid"], [[439, 439], "mapped", [658]], [[440, 440], "mapped", [441]], [[441, 443], "valid"], [[444, 444], "mapped", [445]], [[445, 451], "valid"], [[452, 454], "mapped", [100, 382]], [[455, 457], "mapped", [108, 106]], [[458, 460], "mapped", [110, 106]], [[461, 461], "mapped", [462]], [[462, 462], "valid"], [[463, 463], "mapped", [464]], [[464, 464], "valid"], [[465, 465], "mapped", [466]], [[466, 466], "valid"], [[467, 467], "mapped", [468]], [[468, 468], "valid"], [[469, 469], "mapped", [470]], [[470, 470], "valid"], [[471, 471], "mapped", [472]], [[472, 472], "valid"], [[473, 473], "mapped", [474]], [[474, 474], "valid"], [[475, 475], "mapped", [476]], [[476, 477], "valid"], [[478, 478], "mapped", [479]], [[479, 479], "valid"], [[480, 480], "mapped", [481]], [[481, 481], "valid"], [[482, 482], "mapped", [483]], [[483, 483], "valid"], [[484, 484], "mapped", [485]], [[485, 485], "valid"], [[486, 486], "mapped", [487]], [[487, 487], "valid"], [[488, 488], "mapped", [489]], [[489, 489], "valid"], [[490, 490], "mapped", [491]], [[491, 491], "valid"], [[492, 492], "mapped", [493]], [[493, 493], "valid"], [[494, 494], "mapped", [495]], [[495, 496], "valid"], [[497, 499], "mapped", [100, 122]], [[500, 500], "mapped", [501]], [[501, 501], "valid"], [[502, 502], "mapped", [405]], [[503, 503], "mapped", [447]], [[504, 504], "mapped", [505]], [[505, 505], "valid"], [[506, 506], "mapped", [507]], [[507, 507], "valid"], [[508, 508], "mapped", [509]], [[509, 509], "valid"], [[510, 510], "mapped", [511]], [[511, 511], "valid"], [[512, 512], "mapped", [513]], [[513, 513], "valid"], [[514, 514], "mapped", [515]], [[515, 515], "valid"], [[516, 516], "mapped", [517]], [[517, 517], "valid"], [[518, 518], "mapped", [519]], [[519, 519], "valid"], [[520, 520], "mapped", [521]], [[521, 521], "valid"], [[522, 522], "mapped", [523]], [[523, 523], "valid"], [[524, 524], "mapped", [525]], [[525, 525], "valid"], [[526, 526], "mapped", [527]], [[527, 527], "valid"], [[528, 528], "mapped", [529]], [[529, 529], "valid"], [[530, 530], "mapped", [531]], [[531, 531], "valid"], [[532, 532], "mapped", [533]], [[533, 533], "valid"], [[534, 534], "mapped", [535]], [[535, 535], "valid"], [[536, 536], "mapped", [537]], [[537, 537], "valid"], [[538, 538], "mapped", [539]], [[539, 539], "valid"], [[540, 540], "mapped", [541]], [[541, 541], "valid"], [[542, 542], "mapped", [543]], [[543, 543], "valid"], [[544, 544], "mapped", [414]], [[545, 545], "valid"], [[546, 546], "mapped", [547]], [[547, 547], "valid"], [[548, 548], "mapped", [549]], [[549, 549], "valid"], [[550, 550], "mapped", [551]], [[551, 551], "valid"], [[552, 552], "mapped", [553]], [[553, 553], "valid"], [[554, 554], "mapped", [555]], [[555, 555], "valid"], [[556, 556], "mapped", [557]], [[557, 557], "valid"], [[558, 558], "mapped", [559]], [[559, 559], "valid"], [[560, 560], "mapped", [561]], [[561, 561], "valid"], [[562, 562], "mapped", [563]], [[563, 563], "valid"], [[564, 566], "valid"], [[567, 569], "valid"], [[570, 570], "mapped", [11365]], [[571, 571], "mapped", [572]], [[572, 572], "valid"], [[573, 573], "mapped", [410]], [[574, 574], "mapped", [11366]], [[575, 576], "valid"], [[577, 577], "mapped", [578]], [[578, 578], "valid"], [[579, 579], "mapped", [384]], [[580, 580], "mapped", [649]], [[581, 581], "mapped", [652]], [[582, 582], "mapped", [583]], [[583, 583], "valid"], [[584, 584], "mapped", [585]], [[585, 585], "valid"], [[586, 586], "mapped", [587]], [[587, 587], "valid"], [[588, 588], "mapped", [589]], [[589, 589], "valid"], [[590, 590], "mapped", [591]], [[591, 591], "valid"], [[592, 680], "valid"], [[681, 685], "valid"], [[686, 687], "valid"], [[688, 688], "mapped", [104]], [[689, 689], "mapped", [614]], [[690, 690], "mapped", [106]], [[691, 691], "mapped", [114]], [[692, 692], "mapped", [633]], [[693, 693], "mapped", [635]], [[694, 694], "mapped", [641]], [[695, 695], "mapped", [119]], [[696, 696], "mapped", [121]], [[697, 705], "valid"], [[706, 709], "valid", [], "NV8"], [[710, 721], "valid"], [[722, 727], "valid", [], "NV8"], [[728, 728], "disallowed_STD3_mapped", [32, 774]], [[729, 729], "disallowed_STD3_mapped", [32, 775]], [[730, 730], "disallowed_STD3_mapped", [32, 778]], [[731, 731], "disallowed_STD3_mapped", [32, 808]], [[732, 732], "disallowed_STD3_mapped", [32, 771]], [[733, 733], "disallowed_STD3_mapped", [32, 779]], [[734, 734], "valid", [], "NV8"], [[735, 735], "valid", [], "NV8"], [[736, 736], "mapped", [611]], [[737, 737], "mapped", [108]], [[738, 738], "mapped", [115]], [[739, 739], "mapped", [120]], [[740, 740], "mapped", [661]], [[741, 745], "valid", [], "NV8"], [[746, 747], "valid", [], "NV8"], [[748, 748], "valid"], [[749, 749], "valid", [], "NV8"], [[750, 750], "valid"], [[751, 767], "valid", [], "NV8"], [[768, 831], "valid"], [[832, 832], "mapped", [768]], [[833, 833], "mapped", [769]], [[834, 834], "valid"], [[835, 835], "mapped", [787]], [[836, 836], "mapped", [776, 769]], [[837, 837], "mapped", [953]], [[838, 846], "valid"], [[847, 847], "ignored"], [[848, 855], "valid"], [[856, 860], "valid"], [[861, 863], "valid"], [[864, 865], "valid"], [[866, 866], "valid"], [[867, 879], "valid"], [[880, 880], "mapped", [881]], [[881, 881], "valid"], [[882, 882], "mapped", [883]], [[883, 883], "valid"], [[884, 884], "mapped", [697]], [[885, 885], "valid"], [[886, 886], "mapped", [887]], [[887, 887], "valid"], [[888, 889], "disallowed"], [[890, 890], "disallowed_STD3_mapped", [32, 953]], [[891, 893], "valid"], [[894, 894], "disallowed_STD3_mapped", [59]], [[895, 895], "mapped", [1011]], [[896, 899], "disallowed"], [[900, 900], "disallowed_STD3_mapped", [32, 769]], [[901, 901], "disallowed_STD3_mapped", [32, 776, 769]], [[902, 902], "mapped", [940]], [[903, 903], "mapped", [183]], [[904, 904], "mapped", [941]], [[905, 905], "mapped", [942]], [[906, 906], "mapped", [943]], [[907, 907], "disallowed"], [[908, 908], "mapped", [972]], [[909, 909], "disallowed"], [[910, 910], "mapped", [973]], [[911, 911], "mapped", [974]], [[912, 912], "valid"], [[913, 913], "mapped", [945]], [[914, 914], "mapped", [946]], [[915, 915], "mapped", [947]], [[916, 916], "mapped", [948]], [[917, 917], "mapped", [949]], [[918, 918], "mapped", [950]], [[919, 919], "mapped", [951]], [[920, 920], "mapped", [952]], [[921, 921], "mapped", [953]], [[922, 922], "mapped", [954]], [[923, 923], "mapped", [955]], [[924, 924], "mapped", [956]], [[925, 925], "mapped", [957]], [[926, 926], "mapped", [958]], [[927, 927], "mapped", [959]], [[928, 928], "mapped", [960]], [[929, 929], "mapped", [961]], [[930, 930], "disallowed"], [[931, 931], "mapped", [963]], [[932, 932], "mapped", [964]], [[933, 933], "mapped", [965]], [[934, 934], "mapped", [966]], [[935, 935], "mapped", [967]], [[936, 936], "mapped", [968]], [[937, 937], "mapped", [969]], [[938, 938], "mapped", [970]], [[939, 939], "mapped", [971]], [[940, 961], "valid"], [[962, 962], "deviation", [963]], [[963, 974], "valid"], [[975, 975], "mapped", [983]], [[976, 976], "mapped", [946]], [[977, 977], "mapped", [952]], [[978, 978], "mapped", [965]], [[979, 979], "mapped", [973]], [[980, 980], "mapped", [971]], [[981, 981], "mapped", [966]], [[982, 982], "mapped", [960]], [[983, 983], "valid"], [[984, 984], "mapped", [985]], [[985, 985], "valid"], [[986, 986], "mapped", [987]], [[987, 987], "valid"], [[988, 988], "mapped", [989]], [[989, 989], "valid"], [[990, 990], "mapped", [991]], [[991, 991], "valid"], [[992, 992], "mapped", [993]], [[993, 993], "valid"], [[994, 994], "mapped", [995]], [[995, 995], "valid"], [[996, 996], "mapped", [997]], [[997, 997], "valid"], [[998, 998], "mapped", [999]], [[999, 999], "valid"], [[1e3, 1e3], "mapped", [1001]], [[1001, 1001], "valid"], [[1002, 1002], "mapped", [1003]], [[1003, 1003], "valid"], [[1004, 1004], "mapped", [1005]], [[1005, 1005], "valid"], [[1006, 1006], "mapped", [1007]], [[1007, 1007], "valid"], [[1008, 1008], "mapped", [954]], [[1009, 1009], "mapped", [961]], [[1010, 1010], "mapped", [963]], [[1011, 1011], "valid"], [[1012, 1012], "mapped", [952]], [[1013, 1013], "mapped", [949]], [[1014, 1014], "valid", [], "NV8"], [[1015, 1015], "mapped", [1016]], [[1016, 1016], "valid"], [[1017, 1017], "mapped", [963]], [[1018, 1018], "mapped", [1019]], [[1019, 1019], "valid"], [[1020, 1020], "valid"], [[1021, 1021], "mapped", [891]], [[1022, 1022], "mapped", [892]], [[1023, 1023], "mapped", [893]], [[1024, 1024], "mapped", [1104]], [[1025, 1025], "mapped", [1105]], [[1026, 1026], "mapped", [1106]], [[1027, 1027], "mapped", [1107]], [[1028, 1028], "mapped", [1108]], [[1029, 1029], "mapped", [1109]], [[1030, 1030], "mapped", [1110]], [[1031, 1031], "mapped", [1111]], [[1032, 1032], "mapped", [1112]], [[1033, 1033], "mapped", [1113]], [[1034, 1034], "mapped", [1114]], [[1035, 1035], "mapped", [1115]], [[1036, 1036], "mapped", [1116]], [[1037, 1037], "mapped", [1117]], [[1038, 1038], "mapped", [1118]], [[1039, 1039], "mapped", [1119]], [[1040, 1040], "mapped", [1072]], [[1041, 1041], "mapped", [1073]], [[1042, 1042], "mapped", [1074]], [[1043, 1043], "mapped", [1075]], [[1044, 1044], "mapped", [1076]], [[1045, 1045], "mapped", [1077]], [[1046, 1046], "mapped", [1078]], [[1047, 1047], "mapped", [1079]], [[1048, 1048], "mapped", [1080]], [[1049, 1049], "mapped", [1081]], [[1050, 1050], "mapped", [1082]], [[1051, 1051], "mapped", [1083]], [[1052, 1052], "mapped", [1084]], [[1053, 1053], "mapped", [1085]], [[1054, 1054], "mapped", [1086]], [[1055, 1055], "mapped", [1087]], [[1056, 1056], "mapped", [1088]], [[1057, 1057], "mapped", [1089]], [[1058, 1058], "mapped", [1090]], [[1059, 1059], "mapped", [1091]], [[1060, 1060], "mapped", [1092]], [[1061, 1061], "mapped", [1093]], [[1062, 1062], "mapped", [1094]], [[1063, 1063], "mapped", [1095]], [[1064, 1064], "mapped", [1096]], [[1065, 1065], "mapped", [1097]], [[1066, 1066], "mapped", [1098]], [[1067, 1067], "mapped", [1099]], [[1068, 1068], "mapped", [1100]], [[1069, 1069], "mapped", [1101]], [[1070, 1070], "mapped", [1102]], [[1071, 1071], "mapped", [1103]], [[1072, 1103], "valid"], [[1104, 1104], "valid"], [[1105, 1116], "valid"], [[1117, 1117], "valid"], [[1118, 1119], "valid"], [[1120, 1120], "mapped", [1121]], [[1121, 1121], "valid"], [[1122, 1122], "mapped", [1123]], [[1123, 1123], "valid"], [[1124, 1124], "mapped", [1125]], [[1125, 1125], "valid"], [[1126, 1126], "mapped", [1127]], [[1127, 1127], "valid"], [[1128, 1128], "mapped", [1129]], [[1129, 1129], "valid"], [[1130, 1130], "mapped", [1131]], [[1131, 1131], "valid"], [[1132, 1132], "mapped", [1133]], [[1133, 1133], "valid"], [[1134, 1134], "mapped", [1135]], [[1135, 1135], "valid"], [[1136, 1136], "mapped", [1137]], [[1137, 1137], "valid"], [[1138, 1138], "mapped", [1139]], [[1139, 1139], "valid"], [[1140, 1140], "mapped", [1141]], [[1141, 1141], "valid"], [[1142, 1142], "mapped", [1143]], [[1143, 1143], "valid"], [[1144, 1144], "mapped", [1145]], [[1145, 1145], "valid"], [[1146, 1146], "mapped", [1147]], [[1147, 1147], "valid"], [[1148, 1148], "mapped", [1149]], [[1149, 1149], "valid"], [[1150, 1150], "mapped", [1151]], [[1151, 1151], "valid"], [[1152, 1152], "mapped", [1153]], [[1153, 1153], "valid"], [[1154, 1154], "valid", [], "NV8"], [[1155, 1158], "valid"], [[1159, 1159], "valid"], [[1160, 1161], "valid", [], "NV8"], [[1162, 1162], "mapped", [1163]], [[1163, 1163], "valid"], [[1164, 1164], "mapped", [1165]], [[1165, 1165], "valid"], [[1166, 1166], "mapped", [1167]], [[1167, 1167], "valid"], [[1168, 1168], "mapped", [1169]], [[1169, 1169], "valid"], [[1170, 1170], "mapped", [1171]], [[1171, 1171], "valid"], [[1172, 1172], "mapped", [1173]], [[1173, 1173], "valid"], [[1174, 1174], "mapped", [1175]], [[1175, 1175], "valid"], [[1176, 1176], "mapped", [1177]], [[1177, 1177], "valid"], [[1178, 1178], "mapped", [1179]], [[1179, 1179], "valid"], [[1180, 1180], "mapped", [1181]], [[1181, 1181], "valid"], [[1182, 1182], "mapped", [1183]], [[1183, 1183], "valid"], [[1184, 1184], "mapped", [1185]], [[1185, 1185], "valid"], [[1186, 1186], "mapped", [1187]], [[1187, 1187], "valid"], [[1188, 1188], "mapped", [1189]], [[1189, 1189], "valid"], [[1190, 1190], "mapped", [1191]], [[1191, 1191], "valid"], [[1192, 1192], "mapped", [1193]], [[1193, 1193], "valid"], [[1194, 1194], "mapped", [1195]], [[1195, 1195], "valid"], [[1196, 1196], "mapped", [1197]], [[1197, 1197], "valid"], [[1198, 1198], "mapped", [1199]], [[1199, 1199], "valid"], [[1200, 1200], "mapped", [1201]], [[1201, 1201], "valid"], [[1202, 1202], "mapped", [1203]], [[1203, 1203], "valid"], [[1204, 1204], "mapped", [1205]], [[1205, 1205], "valid"], [[1206, 1206], "mapped", [1207]], [[1207, 1207], "valid"], [[1208, 1208], "mapped", [1209]], [[1209, 1209], "valid"], [[1210, 1210], "mapped", [1211]], [[1211, 1211], "valid"], [[1212, 1212], "mapped", [1213]], [[1213, 1213], "valid"], [[1214, 1214], "mapped", [1215]], [[1215, 1215], "valid"], [[1216, 1216], "disallowed"], [[1217, 1217], "mapped", [1218]], [[1218, 1218], "valid"], [[1219, 1219], "mapped", [1220]], [[1220, 1220], "valid"], [[1221, 1221], "mapped", [1222]], [[1222, 1222], "valid"], [[1223, 1223], "mapped", [1224]], [[1224, 1224], "valid"], [[1225, 1225], "mapped", [1226]], [[1226, 1226], "valid"], [[1227, 1227], "mapped", [1228]], [[1228, 1228], "valid"], [[1229, 1229], "mapped", [1230]], [[1230, 1230], "valid"], [[1231, 1231], "valid"], [[1232, 1232], "mapped", [1233]], [[1233, 1233], "valid"], [[1234, 1234], "mapped", [1235]], [[1235, 1235], "valid"], [[1236, 1236], "mapped", [1237]], [[1237, 1237], "valid"], [[1238, 1238], "mapped", [1239]], [[1239, 1239], "valid"], [[1240, 1240], "mapped", [1241]], [[1241, 1241], "valid"], [[1242, 1242], "mapped", [1243]], [[1243, 1243], "valid"], [[1244, 1244], "mapped", [1245]], [[1245, 1245], "valid"], [[1246, 1246], "mapped", [1247]], [[1247, 1247], "valid"], [[1248, 1248], "mapped", [1249]], [[1249, 1249], "valid"], [[1250, 1250], "mapped", [1251]], [[1251, 1251], "valid"], [[1252, 1252], "mapped", [1253]], [[1253, 1253], "valid"], [[1254, 1254], "mapped", [1255]], [[1255, 1255], "valid"], [[1256, 1256], "mapped", [1257]], [[1257, 1257], "valid"], [[1258, 1258], "mapped", [1259]], [[1259, 1259], "valid"], [[1260, 1260], "mapped", [1261]], [[1261, 1261], "valid"], [[1262, 1262], "mapped", [1263]], [[1263, 1263], "valid"], [[1264, 1264], "mapped", [1265]], [[1265, 1265], "valid"], [[1266, 1266], "mapped", [1267]], [[1267, 1267], "valid"], [[1268, 1268], "mapped", [1269]], [[1269, 1269], "valid"], [[1270, 1270], "mapped", [1271]], [[1271, 1271], "valid"], [[1272, 1272], "mapped", [1273]], [[1273, 1273], "valid"], [[1274, 1274], "mapped", [1275]], [[1275, 1275], "valid"], [[1276, 1276], "mapped", [1277]], [[1277, 1277], "valid"], [[1278, 1278], "mapped", [1279]], [[1279, 1279], "valid"], [[1280, 1280], "mapped", [1281]], [[1281, 1281], "valid"], [[1282, 1282], "mapped", [1283]], [[1283, 1283], "valid"], [[1284, 1284], "mapped", [1285]], [[1285, 1285], "valid"], [[1286, 1286], "mapped", [1287]], [[1287, 1287], "valid"], [[1288, 1288], "mapped", [1289]], [[1289, 1289], "valid"], [[1290, 1290], "mapped", [1291]], [[1291, 1291], "valid"], [[1292, 1292], "mapped", [1293]], [[1293, 1293], "valid"], [[1294, 1294], "mapped", [1295]], [[1295, 1295], "valid"], [[1296, 1296], "mapped", [1297]], [[1297, 1297], "valid"], [[1298, 1298], "mapped", [1299]], [[1299, 1299], "valid"], [[1300, 1300], "mapped", [1301]], [[1301, 1301], "valid"], [[1302, 1302], "mapped", [1303]], [[1303, 1303], "valid"], [[1304, 1304], "mapped", [1305]], [[1305, 1305], "valid"], [[1306, 1306], "mapped", [1307]], [[1307, 1307], "valid"], [[1308, 1308], "mapped", [1309]], [[1309, 1309], "valid"], [[1310, 1310], "mapped", [1311]], [[1311, 1311], "valid"], [[1312, 1312], "mapped", [1313]], [[1313, 1313], "valid"], [[1314, 1314], "mapped", [1315]], [[1315, 1315], "valid"], [[1316, 1316], "mapped", [1317]], [[1317, 1317], "valid"], [[1318, 1318], "mapped", [1319]], [[1319, 1319], "valid"], [[1320, 1320], "mapped", [1321]], [[1321, 1321], "valid"], [[1322, 1322], "mapped", [1323]], [[1323, 1323], "valid"], [[1324, 1324], "mapped", [1325]], [[1325, 1325], "valid"], [[1326, 1326], "mapped", [1327]], [[1327, 1327], "valid"], [[1328, 1328], "disallowed"], [[1329, 1329], "mapped", [1377]], [[1330, 1330], "mapped", [1378]], [[1331, 1331], "mapped", [1379]], [[1332, 1332], "mapped", [1380]], [[1333, 1333], "mapped", [1381]], [[1334, 1334], "mapped", [1382]], [[1335, 1335], "mapped", [1383]], [[1336, 1336], "mapped", [1384]], [[1337, 1337], "mapped", [1385]], [[1338, 1338], "mapped", [1386]], [[1339, 1339], "mapped", [1387]], [[1340, 1340], "mapped", [1388]], [[1341, 1341], "mapped", [1389]], [[1342, 1342], "mapped", [1390]], [[1343, 1343], "mapped", [1391]], [[1344, 1344], "mapped", [1392]], [[1345, 1345], "mapped", [1393]], [[1346, 1346], "mapped", [1394]], [[1347, 1347], "mapped", [1395]], [[1348, 1348], "mapped", [1396]], [[1349, 1349], "mapped", [1397]], [[1350, 1350], "mapped", [1398]], [[1351, 1351], "mapped", [1399]], [[1352, 1352], "mapped", [1400]], [[1353, 1353], "mapped", [1401]], [[1354, 1354], "mapped", [1402]], [[1355, 1355], "mapped", [1403]], [[1356, 1356], "mapped", [1404]], [[1357, 1357], "mapped", [1405]], [[1358, 1358], "mapped", [1406]], [[1359, 1359], "mapped", [1407]], [[1360, 1360], "mapped", [1408]], [[1361, 1361], "mapped", [1409]], [[1362, 1362], "mapped", [1410]], [[1363, 1363], "mapped", [1411]], [[1364, 1364], "mapped", [1412]], [[1365, 1365], "mapped", [1413]], [[1366, 1366], "mapped", [1414]], [[1367, 1368], "disallowed"], [[1369, 1369], "valid"], [[1370, 1375], "valid", [], "NV8"], [[1376, 1376], "disallowed"], [[1377, 1414], "valid"], [[1415, 1415], "mapped", [1381, 1410]], [[1416, 1416], "disallowed"], [[1417, 1417], "valid", [], "NV8"], [[1418, 1418], "valid", [], "NV8"], [[1419, 1420], "disallowed"], [[1421, 1422], "valid", [], "NV8"], [[1423, 1423], "valid", [], "NV8"], [[1424, 1424], "disallowed"], [[1425, 1441], "valid"], [[1442, 1442], "valid"], [[1443, 1455], "valid"], [[1456, 1465], "valid"], [[1466, 1466], "valid"], [[1467, 1469], "valid"], [[1470, 1470], "valid", [], "NV8"], [[1471, 1471], "valid"], [[1472, 1472], "valid", [], "NV8"], [[1473, 1474], "valid"], [[1475, 1475], "valid", [], "NV8"], [[1476, 1476], "valid"], [[1477, 1477], "valid"], [[1478, 1478], "valid", [], "NV8"], [[1479, 1479], "valid"], [[1480, 1487], "disallowed"], [[1488, 1514], "valid"], [[1515, 1519], "disallowed"], [[1520, 1524], "valid"], [[1525, 1535], "disallowed"], [[1536, 1539], "disallowed"], [[1540, 1540], "disallowed"], [[1541, 1541], "disallowed"], [[1542, 1546], "valid", [], "NV8"], [[1547, 1547], "valid", [], "NV8"], [[1548, 1548], "valid", [], "NV8"], [[1549, 1551], "valid", [], "NV8"], [[1552, 1557], "valid"], [[1558, 1562], "valid"], [[1563, 1563], "valid", [], "NV8"], [[1564, 1564], "disallowed"], [[1565, 1565], "disallowed"], [[1566, 1566], "valid", [], "NV8"], [[1567, 1567], "valid", [], "NV8"], [[1568, 1568], "valid"], [[1569, 1594], "valid"], [[1595, 1599], "valid"], [[1600, 1600], "valid", [], "NV8"], [[1601, 1618], "valid"], [[1619, 1621], "valid"], [[1622, 1624], "valid"], [[1625, 1630], "valid"], [[1631, 1631], "valid"], [[1632, 1641], "valid"], [[1642, 1645], "valid", [], "NV8"], [[1646, 1647], "valid"], [[1648, 1652], "valid"], [[1653, 1653], "mapped", [1575, 1652]], [[1654, 1654], "mapped", [1608, 1652]], [[1655, 1655], "mapped", [1735, 1652]], [[1656, 1656], "mapped", [1610, 1652]], [[1657, 1719], "valid"], [[1720, 1721], "valid"], [[1722, 1726], "valid"], [[1727, 1727], "valid"], [[1728, 1742], "valid"], [[1743, 1743], "valid"], [[1744, 1747], "valid"], [[1748, 1748], "valid", [], "NV8"], [[1749, 1756], "valid"], [[1757, 1757], "disallowed"], [[1758, 1758], "valid", [], "NV8"], [[1759, 1768], "valid"], [[1769, 1769], "valid", [], "NV8"], [[1770, 1773], "valid"], [[1774, 1775], "valid"], [[1776, 1785], "valid"], [[1786, 1790], "valid"], [[1791, 1791], "valid"], [[1792, 1805], "valid", [], "NV8"], [[1806, 1806], "disallowed"], [[1807, 1807], "disallowed"], [[1808, 1836], "valid"], [[1837, 1839], "valid"], [[1840, 1866], "valid"], [[1867, 1868], "disallowed"], [[1869, 1871], "valid"], [[1872, 1901], "valid"], [[1902, 1919], "valid"], [[1920, 1968], "valid"], [[1969, 1969], "valid"], [[1970, 1983], "disallowed"], [[1984, 2037], "valid"], [[2038, 2042], "valid", [], "NV8"], [[2043, 2047], "disallowed"], [[2048, 2093], "valid"], [[2094, 2095], "disallowed"], [[2096, 2110], "valid", [], "NV8"], [[2111, 2111], "disallowed"], [[2112, 2139], "valid"], [[2140, 2141], "disallowed"], [[2142, 2142], "valid", [], "NV8"], [[2143, 2207], "disallowed"], [[2208, 2208], "valid"], [[2209, 2209], "valid"], [[2210, 2220], "valid"], [[2221, 2226], "valid"], [[2227, 2228], "valid"], [[2229, 2274], "disallowed"], [[2275, 2275], "valid"], [[2276, 2302], "valid"], [[2303, 2303], "valid"], [[2304, 2304], "valid"], [[2305, 2307], "valid"], [[2308, 2308], "valid"], [[2309, 2361], "valid"], [[2362, 2363], "valid"], [[2364, 2381], "valid"], [[2382, 2382], "valid"], [[2383, 2383], "valid"], [[2384, 2388], "valid"], [[2389, 2389], "valid"], [[2390, 2391], "valid"], [[2392, 2392], "mapped", [2325, 2364]], [[2393, 2393], "mapped", [2326, 2364]], [[2394, 2394], "mapped", [2327, 2364]], [[2395, 2395], "mapped", [2332, 2364]], [[2396, 2396], "mapped", [2337, 2364]], [[2397, 2397], "mapped", [2338, 2364]], [[2398, 2398], "mapped", [2347, 2364]], [[2399, 2399], "mapped", [2351, 2364]], [[2400, 2403], "valid"], [[2404, 2405], "valid", [], "NV8"], [[2406, 2415], "valid"], [[2416, 2416], "valid", [], "NV8"], [[2417, 2418], "valid"], [[2419, 2423], "valid"], [[2424, 2424], "valid"], [[2425, 2426], "valid"], [[2427, 2428], "valid"], [[2429, 2429], "valid"], [[2430, 2431], "valid"], [[2432, 2432], "valid"], [[2433, 2435], "valid"], [[2436, 2436], "disallowed"], [[2437, 2444], "valid"], [[2445, 2446], "disallowed"], [[2447, 2448], "valid"], [[2449, 2450], "disallowed"], [[2451, 2472], "valid"], [[2473, 2473], "disallowed"], [[2474, 2480], "valid"], [[2481, 2481], "disallowed"], [[2482, 2482], "valid"], [[2483, 2485], "disallowed"], [[2486, 2489], "valid"], [[2490, 2491], "disallowed"], [[2492, 2492], "valid"], [[2493, 2493], "valid"], [[2494, 2500], "valid"], [[2501, 2502], "disallowed"], [[2503, 2504], "valid"], [[2505, 2506], "disallowed"], [[2507, 2509], "valid"], [[2510, 2510], "valid"], [[2511, 2518], "disallowed"], [[2519, 2519], "valid"], [[2520, 2523], "disallowed"], [[2524, 2524], "mapped", [2465, 2492]], [[2525, 2525], "mapped", [2466, 2492]], [[2526, 2526], "disallowed"], [[2527, 2527], "mapped", [2479, 2492]], [[2528, 2531], "valid"], [[2532, 2533], "disallowed"], [[2534, 2545], "valid"], [[2546, 2554], "valid", [], "NV8"], [[2555, 2555], "valid", [], "NV8"], [[2556, 2560], "disallowed"], [[2561, 2561], "valid"], [[2562, 2562], "valid"], [[2563, 2563], "valid"], [[2564, 2564], "disallowed"], [[2565, 2570], "valid"], [[2571, 2574], "disallowed"], [[2575, 2576], "valid"], [[2577, 2578], "disallowed"], [[2579, 2600], "valid"], [[2601, 2601], "disallowed"], [[2602, 2608], "valid"], [[2609, 2609], "disallowed"], [[2610, 2610], "valid"], [[2611, 2611], "mapped", [2610, 2620]], [[2612, 2612], "disallowed"], [[2613, 2613], "valid"], [[2614, 2614], "mapped", [2616, 2620]], [[2615, 2615], "disallowed"], [[2616, 2617], "valid"], [[2618, 2619], "disallowed"], [[2620, 2620], "valid"], [[2621, 2621], "disallowed"], [[2622, 2626], "valid"], [[2627, 2630], "disallowed"], [[2631, 2632], "valid"], [[2633, 2634], "disallowed"], [[2635, 2637], "valid"], [[2638, 2640], "disallowed"], [[2641, 2641], "valid"], [[2642, 2648], "disallowed"], [[2649, 2649], "mapped", [2582, 2620]], [[2650, 2650], "mapped", [2583, 2620]], [[2651, 2651], "mapped", [2588, 2620]], [[2652, 2652], "valid"], [[2653, 2653], "disallowed"], [[2654, 2654], "mapped", [2603, 2620]], [[2655, 2661], "disallowed"], [[2662, 2676], "valid"], [[2677, 2677], "valid"], [[2678, 2688], "disallowed"], [[2689, 2691], "valid"], [[2692, 2692], "disallowed"], [[2693, 2699], "valid"], [[2700, 2700], "valid"], [[2701, 2701], "valid"], [[2702, 2702], "disallowed"], [[2703, 2705], "valid"], [[2706, 2706], "disallowed"], [[2707, 2728], "valid"], [[2729, 2729], "disallowed"], [[2730, 2736], "valid"], [[2737, 2737], "disallowed"], [[2738, 2739], "valid"], [[2740, 2740], "disallowed"], [[2741, 2745], "valid"], [[2746, 2747], "disallowed"], [[2748, 2757], "valid"], [[2758, 2758], "disallowed"], [[2759, 2761], "valid"], [[2762, 2762], "disallowed"], [[2763, 2765], "valid"], [[2766, 2767], "disallowed"], [[2768, 2768], "valid"], [[2769, 2783], "disallowed"], [[2784, 2784], "valid"], [[2785, 2787], "valid"], [[2788, 2789], "disallowed"], [[2790, 2799], "valid"], [[2800, 2800], "valid", [], "NV8"], [[2801, 2801], "valid", [], "NV8"], [[2802, 2808], "disallowed"], [[2809, 2809], "valid"], [[2810, 2816], "disallowed"], [[2817, 2819], "valid"], [[2820, 2820], "disallowed"], [[2821, 2828], "valid"], [[2829, 2830], "disallowed"], [[2831, 2832], "valid"], [[2833, 2834], "disallowed"], [[2835, 2856], "valid"], [[2857, 2857], "disallowed"], [[2858, 2864], "valid"], [[2865, 2865], "disallowed"], [[2866, 2867], "valid"], [[2868, 2868], "disallowed"], [[2869, 2869], "valid"], [[2870, 2873], "valid"], [[2874, 2875], "disallowed"], [[2876, 2883], "valid"], [[2884, 2884], "valid"], [[2885, 2886], "disallowed"], [[2887, 2888], "valid"], [[2889, 2890], "disallowed"], [[2891, 2893], "valid"], [[2894, 2901], "disallowed"], [[2902, 2903], "valid"], [[2904, 2907], "disallowed"], [[2908, 2908], "mapped", [2849, 2876]], [[2909, 2909], "mapped", [2850, 2876]], [[2910, 2910], "disallowed"], [[2911, 2913], "valid"], [[2914, 2915], "valid"], [[2916, 2917], "disallowed"], [[2918, 2927], "valid"], [[2928, 2928], "valid", [], "NV8"], [[2929, 2929], "valid"], [[2930, 2935], "valid", [], "NV8"], [[2936, 2945], "disallowed"], [[2946, 2947], "valid"], [[2948, 2948], "disallowed"], [[2949, 2954], "valid"], [[2955, 2957], "disallowed"], [[2958, 2960], "valid"], [[2961, 2961], "disallowed"], [[2962, 2965], "valid"], [[2966, 2968], "disallowed"], [[2969, 2970], "valid"], [[2971, 2971], "disallowed"], [[2972, 2972], "valid"], [[2973, 2973], "disallowed"], [[2974, 2975], "valid"], [[2976, 2978], "disallowed"], [[2979, 2980], "valid"], [[2981, 2983], "disallowed"], [[2984, 2986], "valid"], [[2987, 2989], "disallowed"], [[2990, 2997], "valid"], [[2998, 2998], "valid"], [[2999, 3001], "valid"], [[3002, 3005], "disallowed"], [[3006, 3010], "valid"], [[3011, 3013], "disallowed"], [[3014, 3016], "valid"], [[3017, 3017], "disallowed"], [[3018, 3021], "valid"], [[3022, 3023], "disallowed"], [[3024, 3024], "valid"], [[3025, 3030], "disallowed"], [[3031, 3031], "valid"], [[3032, 3045], "disallowed"], [[3046, 3046], "valid"], [[3047, 3055], "valid"], [[3056, 3058], "valid", [], "NV8"], [[3059, 3066], "valid", [], "NV8"], [[3067, 3071], "disallowed"], [[3072, 3072], "valid"], [[3073, 3075], "valid"], [[3076, 3076], "disallowed"], [[3077, 3084], "valid"], [[3085, 3085], "disallowed"], [[3086, 3088], "valid"], [[3089, 3089], "disallowed"], [[3090, 3112], "valid"], [[3113, 3113], "disallowed"], [[3114, 3123], "valid"], [[3124, 3124], "valid"], [[3125, 3129], "valid"], [[3130, 3132], "disallowed"], [[3133, 3133], "valid"], [[3134, 3140], "valid"], [[3141, 3141], "disallowed"], [[3142, 3144], "valid"], [[3145, 3145], "disallowed"], [[3146, 3149], "valid"], [[3150, 3156], "disallowed"], [[3157, 3158], "valid"], [[3159, 3159], "disallowed"], [[3160, 3161], "valid"], [[3162, 3162], "valid"], [[3163, 3167], "disallowed"], [[3168, 3169], "valid"], [[3170, 3171], "valid"], [[3172, 3173], "disallowed"], [[3174, 3183], "valid"], [[3184, 3191], "disallowed"], [[3192, 3199], "valid", [], "NV8"], [[3200, 3200], "disallowed"], [[3201, 3201], "valid"], [[3202, 3203], "valid"], [[3204, 3204], "disallowed"], [[3205, 3212], "valid"], [[3213, 3213], "disallowed"], [[3214, 3216], "valid"], [[3217, 3217], "disallowed"], [[3218, 3240], "valid"], [[3241, 3241], "disallowed"], [[3242, 3251], "valid"], [[3252, 3252], "disallowed"], [[3253, 3257], "valid"], [[3258, 3259], "disallowed"], [[3260, 3261], "valid"], [[3262, 3268], "valid"], [[3269, 3269], "disallowed"], [[3270, 3272], "valid"], [[3273, 3273], "disallowed"], [[3274, 3277], "valid"], [[3278, 3284], "disallowed"], [[3285, 3286], "valid"], [[3287, 3293], "disallowed"], [[3294, 3294], "valid"], [[3295, 3295], "disallowed"], [[3296, 3297], "valid"], [[3298, 3299], "valid"], [[3300, 3301], "disallowed"], [[3302, 3311], "valid"], [[3312, 3312], "disallowed"], [[3313, 3314], "valid"], [[3315, 3328], "disallowed"], [[3329, 3329], "valid"], [[3330, 3331], "valid"], [[3332, 3332], "disallowed"], [[3333, 3340], "valid"], [[3341, 3341], "disallowed"], [[3342, 3344], "valid"], [[3345, 3345], "disallowed"], [[3346, 3368], "valid"], [[3369, 3369], "valid"], [[3370, 3385], "valid"], [[3386, 3386], "valid"], [[3387, 3388], "disallowed"], [[3389, 3389], "valid"], [[3390, 3395], "valid"], [[3396, 3396], "valid"], [[3397, 3397], "disallowed"], [[3398, 3400], "valid"], [[3401, 3401], "disallowed"], [[3402, 3405], "valid"], [[3406, 3406], "valid"], [[3407, 3414], "disallowed"], [[3415, 3415], "valid"], [[3416, 3422], "disallowed"], [[3423, 3423], "valid"], [[3424, 3425], "valid"], [[3426, 3427], "valid"], [[3428, 3429], "disallowed"], [[3430, 3439], "valid"], [[3440, 3445], "valid", [], "NV8"], [[3446, 3448], "disallowed"], [[3449, 3449], "valid", [], "NV8"], [[3450, 3455], "valid"], [[3456, 3457], "disallowed"], [[3458, 3459], "valid"], [[3460, 3460], "disallowed"], [[3461, 3478], "valid"], [[3479, 3481], "disallowed"], [[3482, 3505], "valid"], [[3506, 3506], "disallowed"], [[3507, 3515], "valid"], [[3516, 3516], "disallowed"], [[3517, 3517], "valid"], [[3518, 3519], "disallowed"], [[3520, 3526], "valid"], [[3527, 3529], "disallowed"], [[3530, 3530], "valid"], [[3531, 3534], "disallowed"], [[3535, 3540], "valid"], [[3541, 3541], "disallowed"], [[3542, 3542], "valid"], [[3543, 3543], "disallowed"], [[3544, 3551], "valid"], [[3552, 3557], "disallowed"], [[3558, 3567], "valid"], [[3568, 3569], "disallowed"], [[3570, 3571], "valid"], [[3572, 3572], "valid", [], "NV8"], [[3573, 3584], "disallowed"], [[3585, 3634], "valid"], [[3635, 3635], "mapped", [3661, 3634]], [[3636, 3642], "valid"], [[3643, 3646], "disallowed"], [[3647, 3647], "valid", [], "NV8"], [[3648, 3662], "valid"], [[3663, 3663], "valid", [], "NV8"], [[3664, 3673], "valid"], [[3674, 3675], "valid", [], "NV8"], [[3676, 3712], "disallowed"], [[3713, 3714], "valid"], [[3715, 3715], "disallowed"], [[3716, 3716], "valid"], [[3717, 3718], "disallowed"], [[3719, 3720], "valid"], [[3721, 3721], "disallowed"], [[3722, 3722], "valid"], [[3723, 3724], "disallowed"], [[3725, 3725], "valid"], [[3726, 3731], "disallowed"], [[3732, 3735], "valid"], [[3736, 3736], "disallowed"], [[3737, 3743], "valid"], [[3744, 3744], "disallowed"], [[3745, 3747], "valid"], [[3748, 3748], "disallowed"], [[3749, 3749], "valid"], [[3750, 3750], "disallowed"], [[3751, 3751], "valid"], [[3752, 3753], "disallowed"], [[3754, 3755], "valid"], [[3756, 3756], "disallowed"], [[3757, 3762], "valid"], [[3763, 3763], "mapped", [3789, 3762]], [[3764, 3769], "valid"], [[3770, 3770], "disallowed"], [[3771, 3773], "valid"], [[3774, 3775], "disallowed"], [[3776, 3780], "valid"], [[3781, 3781], "disallowed"], [[3782, 3782], "valid"], [[3783, 3783], "disallowed"], [[3784, 3789], "valid"], [[3790, 3791], "disallowed"], [[3792, 3801], "valid"], [[3802, 3803], "disallowed"], [[3804, 3804], "mapped", [3755, 3737]], [[3805, 3805], "mapped", [3755, 3745]], [[3806, 3807], "valid"], [[3808, 3839], "disallowed"], [[3840, 3840], "valid"], [[3841, 3850], "valid", [], "NV8"], [[3851, 3851], "valid"], [[3852, 3852], "mapped", [3851]], [[3853, 3863], "valid", [], "NV8"], [[3864, 3865], "valid"], [[3866, 3871], "valid", [], "NV8"], [[3872, 3881], "valid"], [[3882, 3892], "valid", [], "NV8"], [[3893, 3893], "valid"], [[3894, 3894], "valid", [], "NV8"], [[3895, 3895], "valid"], [[3896, 3896], "valid", [], "NV8"], [[3897, 3897], "valid"], [[3898, 3901], "valid", [], "NV8"], [[3902, 3906], "valid"], [[3907, 3907], "mapped", [3906, 4023]], [[3908, 3911], "valid"], [[3912, 3912], "disallowed"], [[3913, 3916], "valid"], [[3917, 3917], "mapped", [3916, 4023]], [[3918, 3921], "valid"], [[3922, 3922], "mapped", [3921, 4023]], [[3923, 3926], "valid"], [[3927, 3927], "mapped", [3926, 4023]], [[3928, 3931], "valid"], [[3932, 3932], "mapped", [3931, 4023]], [[3933, 3944], "valid"], [[3945, 3945], "mapped", [3904, 4021]], [[3946, 3946], "valid"], [[3947, 3948], "valid"], [[3949, 3952], "disallowed"], [[3953, 3954], "valid"], [[3955, 3955], "mapped", [3953, 3954]], [[3956, 3956], "valid"], [[3957, 3957], "mapped", [3953, 3956]], [[3958, 3958], "mapped", [4018, 3968]], [[3959, 3959], "mapped", [4018, 3953, 3968]], [[3960, 3960], "mapped", [4019, 3968]], [[3961, 3961], "mapped", [4019, 3953, 3968]], [[3962, 3968], "valid"], [[3969, 3969], "mapped", [3953, 3968]], [[3970, 3972], "valid"], [[3973, 3973], "valid", [], "NV8"], [[3974, 3979], "valid"], [[3980, 3983], "valid"], [[3984, 3986], "valid"], [[3987, 3987], "mapped", [3986, 4023]], [[3988, 3989], "valid"], [[3990, 3990], "valid"], [[3991, 3991], "valid"], [[3992, 3992], "disallowed"], [[3993, 3996], "valid"], [[3997, 3997], "mapped", [3996, 4023]], [[3998, 4001], "valid"], [[4002, 4002], "mapped", [4001, 4023]], [[4003, 4006], "valid"], [[4007, 4007], "mapped", [4006, 4023]], [[4008, 4011], "valid"], [[4012, 4012], "mapped", [4011, 4023]], [[4013, 4013], "valid"], [[4014, 4016], "valid"], [[4017, 4023], "valid"], [[4024, 4024], "valid"], [[4025, 4025], "mapped", [3984, 4021]], [[4026, 4028], "valid"], [[4029, 4029], "disallowed"], [[4030, 4037], "valid", [], "NV8"], [[4038, 4038], "valid"], [[4039, 4044], "valid", [], "NV8"], [[4045, 4045], "disallowed"], [[4046, 4046], "valid", [], "NV8"], [[4047, 4047], "valid", [], "NV8"], [[4048, 4049], "valid", [], "NV8"], [[4050, 4052], "valid", [], "NV8"], [[4053, 4056], "valid", [], "NV8"], [[4057, 4058], "valid", [], "NV8"], [[4059, 4095], "disallowed"], [[4096, 4129], "valid"], [[4130, 4130], "valid"], [[4131, 4135], "valid"], [[4136, 4136], "valid"], [[4137, 4138], "valid"], [[4139, 4139], "valid"], [[4140, 4146], "valid"], [[4147, 4149], "valid"], [[4150, 4153], "valid"], [[4154, 4159], "valid"], [[4160, 4169], "valid"], [[4170, 4175], "valid", [], "NV8"], [[4176, 4185], "valid"], [[4186, 4249], "valid"], [[4250, 4253], "valid"], [[4254, 4255], "valid", [], "NV8"], [[4256, 4293], "disallowed"], [[4294, 4294], "disallowed"], [[4295, 4295], "mapped", [11559]], [[4296, 4300], "disallowed"], [[4301, 4301], "mapped", [11565]], [[4302, 4303], "disallowed"], [[4304, 4342], "valid"], [[4343, 4344], "valid"], [[4345, 4346], "valid"], [[4347, 4347], "valid", [], "NV8"], [[4348, 4348], "mapped", [4316]], [[4349, 4351], "valid"], [[4352, 4441], "valid", [], "NV8"], [[4442, 4446], "valid", [], "NV8"], [[4447, 4448], "disallowed"], [[4449, 4514], "valid", [], "NV8"], [[4515, 4519], "valid", [], "NV8"], [[4520, 4601], "valid", [], "NV8"], [[4602, 4607], "valid", [], "NV8"], [[4608, 4614], "valid"], [[4615, 4615], "valid"], [[4616, 4678], "valid"], [[4679, 4679], "valid"], [[4680, 4680], "valid"], [[4681, 4681], "disallowed"], [[4682, 4685], "valid"], [[4686, 4687], "disallowed"], [[4688, 4694], "valid"], [[4695, 4695], "disallowed"], [[4696, 4696], "valid"], [[4697, 4697], "disallowed"], [[4698, 4701], "valid"], [[4702, 4703], "disallowed"], [[4704, 4742], "valid"], [[4743, 4743], "valid"], [[4744, 4744], "valid"], [[4745, 4745], "disallowed"], [[4746, 4749], "valid"], [[4750, 4751], "disallowed"], [[4752, 4782], "valid"], [[4783, 4783], "valid"], [[4784, 4784], "valid"], [[4785, 4785], "disallowed"], [[4786, 4789], "valid"], [[4790, 4791], "disallowed"], [[4792, 4798], "valid"], [[4799, 4799], "disallowed"], [[4800, 4800], "valid"], [[4801, 4801], "disallowed"], [[4802, 4805], "valid"], [[4806, 4807], "disallowed"], [[4808, 4814], "valid"], [[4815, 4815], "valid"], [[4816, 4822], "valid"], [[4823, 4823], "disallowed"], [[4824, 4846], "valid"], [[4847, 4847], "valid"], [[4848, 4878], "valid"], [[4879, 4879], "valid"], [[4880, 4880], "valid"], [[4881, 4881], "disallowed"], [[4882, 4885], "valid"], [[4886, 4887], "disallowed"], [[4888, 4894], "valid"], [[4895, 4895], "valid"], [[4896, 4934], "valid"], [[4935, 4935], "valid"], [[4936, 4954], "valid"], [[4955, 4956], "disallowed"], [[4957, 4958], "valid"], [[4959, 4959], "valid"], [[4960, 4960], "valid", [], "NV8"], [[4961, 4988], "valid", [], "NV8"], [[4989, 4991], "disallowed"], [[4992, 5007], "valid"], [[5008, 5017], "valid", [], "NV8"], [[5018, 5023], "disallowed"], [[5024, 5108], "valid"], [[5109, 5109], "valid"], [[5110, 5111], "disallowed"], [[5112, 5112], "mapped", [5104]], [[5113, 5113], "mapped", [5105]], [[5114, 5114], "mapped", [5106]], [[5115, 5115], "mapped", [5107]], [[5116, 5116], "mapped", [5108]], [[5117, 5117], "mapped", [5109]], [[5118, 5119], "disallowed"], [[5120, 5120], "valid", [], "NV8"], [[5121, 5740], "valid"], [[5741, 5742], "valid", [], "NV8"], [[5743, 5750], "valid"], [[5751, 5759], "valid"], [[5760, 5760], "disallowed"], [[5761, 5786], "valid"], [[5787, 5788], "valid", [], "NV8"], [[5789, 5791], "disallowed"], [[5792, 5866], "valid"], [[5867, 5872], "valid", [], "NV8"], [[5873, 5880], "valid"], [[5881, 5887], "disallowed"], [[5888, 5900], "valid"], [[5901, 5901], "disallowed"], [[5902, 5908], "valid"], [[5909, 5919], "disallowed"], [[5920, 5940], "valid"], [[5941, 5942], "valid", [], "NV8"], [[5943, 5951], "disallowed"], [[5952, 5971], "valid"], [[5972, 5983], "disallowed"], [[5984, 5996], "valid"], [[5997, 5997], "disallowed"], [[5998, 6e3], "valid"], [[6001, 6001], "disallowed"], [[6002, 6003], "valid"], [[6004, 6015], "disallowed"], [[6016, 6067], "valid"], [[6068, 6069], "disallowed"], [[6070, 6099], "valid"], [[6100, 6102], "valid", [], "NV8"], [[6103, 6103], "valid"], [[6104, 6107], "valid", [], "NV8"], [[6108, 6108], "valid"], [[6109, 6109], "valid"], [[6110, 6111], "disallowed"], [[6112, 6121], "valid"], [[6122, 6127], "disallowed"], [[6128, 6137], "valid", [], "NV8"], [[6138, 6143], "disallowed"], [[6144, 6149], "valid", [], "NV8"], [[6150, 6150], "disallowed"], [[6151, 6154], "valid", [], "NV8"], [[6155, 6157], "ignored"], [[6158, 6158], "disallowed"], [[6159, 6159], "disallowed"], [[6160, 6169], "valid"], [[6170, 6175], "disallowed"], [[6176, 6263], "valid"], [[6264, 6271], "disallowed"], [[6272, 6313], "valid"], [[6314, 6314], "valid"], [[6315, 6319], "disallowed"], [[6320, 6389], "valid"], [[6390, 6399], "disallowed"], [[6400, 6428], "valid"], [[6429, 6430], "valid"], [[6431, 6431], "disallowed"], [[6432, 6443], "valid"], [[6444, 6447], "disallowed"], [[6448, 6459], "valid"], [[6460, 6463], "disallowed"], [[6464, 6464], "valid", [], "NV8"], [[6465, 6467], "disallowed"], [[6468, 6469], "valid", [], "NV8"], [[6470, 6509], "valid"], [[6510, 6511], "disallowed"], [[6512, 6516], "valid"], [[6517, 6527], "disallowed"], [[6528, 6569], "valid"], [[6570, 6571], "valid"], [[6572, 6575], "disallowed"], [[6576, 6601], "valid"], [[6602, 6607], "disallowed"], [[6608, 6617], "valid"], [[6618, 6618], "valid", [], "XV8"], [[6619, 6621], "disallowed"], [[6622, 6623], "valid", [], "NV8"], [[6624, 6655], "valid", [], "NV8"], [[6656, 6683], "valid"], [[6684, 6685], "disallowed"], [[6686, 6687], "valid", [], "NV8"], [[6688, 6750], "valid"], [[6751, 6751], "disallowed"], [[6752, 6780], "valid"], [[6781, 6782], "disallowed"], [[6783, 6793], "valid"], [[6794, 6799], "disallowed"], [[6800, 6809], "valid"], [[6810, 6815], "disallowed"], [[6816, 6822], "valid", [], "NV8"], [[6823, 6823], "valid"], [[6824, 6829], "valid", [], "NV8"], [[6830, 6831], "disallowed"], [[6832, 6845], "valid"], [[6846, 6846], "valid", [], "NV8"], [[6847, 6911], "disallowed"], [[6912, 6987], "valid"], [[6988, 6991], "disallowed"], [[6992, 7001], "valid"], [[7002, 7018], "valid", [], "NV8"], [[7019, 7027], "valid"], [[7028, 7036], "valid", [], "NV8"], [[7037, 7039], "disallowed"], [[7040, 7082], "valid"], [[7083, 7085], "valid"], [[7086, 7097], "valid"], [[7098, 7103], "valid"], [[7104, 7155], "valid"], [[7156, 7163], "disallowed"], [[7164, 7167], "valid", [], "NV8"], [[7168, 7223], "valid"], [[7224, 7226], "disallowed"], [[7227, 7231], "valid", [], "NV8"], [[7232, 7241], "valid"], [[7242, 7244], "disallowed"], [[7245, 7293], "valid"], [[7294, 7295], "valid", [], "NV8"], [[7296, 7359], "disallowed"], [[7360, 7367], "valid", [], "NV8"], [[7368, 7375], "disallowed"], [[7376, 7378], "valid"], [[7379, 7379], "valid", [], "NV8"], [[7380, 7410], "valid"], [[7411, 7414], "valid"], [[7415, 7415], "disallowed"], [[7416, 7417], "valid"], [[7418, 7423], "disallowed"], [[7424, 7467], "valid"], [[7468, 7468], "mapped", [97]], [[7469, 7469], "mapped", [230]], [[7470, 7470], "mapped", [98]], [[7471, 7471], "valid"], [[7472, 7472], "mapped", [100]], [[7473, 7473], "mapped", [101]], [[7474, 7474], "mapped", [477]], [[7475, 7475], "mapped", [103]], [[7476, 7476], "mapped", [104]], [[7477, 7477], "mapped", [105]], [[7478, 7478], "mapped", [106]], [[7479, 7479], "mapped", [107]], [[7480, 7480], "mapped", [108]], [[7481, 7481], "mapped", [109]], [[7482, 7482], "mapped", [110]], [[7483, 7483], "valid"], [[7484, 7484], "mapped", [111]], [[7485, 7485], "mapped", [547]], [[7486, 7486], "mapped", [112]], [[7487, 7487], "mapped", [114]], [[7488, 7488], "mapped", [116]], [[7489, 7489], "mapped", [117]], [[7490, 7490], "mapped", [119]], [[7491, 7491], "mapped", [97]], [[7492, 7492], "mapped", [592]], [[7493, 7493], "mapped", [593]], [[7494, 7494], "mapped", [7426]], [[7495, 7495], "mapped", [98]], [[7496, 7496], "mapped", [100]], [[7497, 7497], "mapped", [101]], [[7498, 7498], "mapped", [601]], [[7499, 7499], "mapped", [603]], [[7500, 7500], "mapped", [604]], [[7501, 7501], "mapped", [103]], [[7502, 7502], "valid"], [[7503, 7503], "mapped", [107]], [[7504, 7504], "mapped", [109]], [[7505, 7505], "mapped", [331]], [[7506, 7506], "mapped", [111]], [[7507, 7507], "mapped", [596]], [[7508, 7508], "mapped", [7446]], [[7509, 7509], "mapped", [7447]], [[7510, 7510], "mapped", [112]], [[7511, 7511], "mapped", [116]], [[7512, 7512], "mapped", [117]], [[7513, 7513], "mapped", [7453]], [[7514, 7514], "mapped", [623]], [[7515, 7515], "mapped", [118]], [[7516, 7516], "mapped", [7461]], [[7517, 7517], "mapped", [946]], [[7518, 7518], "mapped", [947]], [[7519, 7519], "mapped", [948]], [[7520, 7520], "mapped", [966]], [[7521, 7521], "mapped", [967]], [[7522, 7522], "mapped", [105]], [[7523, 7523], "mapped", [114]], [[7524, 7524], "mapped", [117]], [[7525, 7525], "mapped", [118]], [[7526, 7526], "mapped", [946]], [[7527, 7527], "mapped", [947]], [[7528, 7528], "mapped", [961]], [[7529, 7529], "mapped", [966]], [[7530, 7530], "mapped", [967]], [[7531, 7531], "valid"], [[7532, 7543], "valid"], [[7544, 7544], "mapped", [1085]], [[7545, 7578], "valid"], [[7579, 7579], "mapped", [594]], [[7580, 7580], "mapped", [99]], [[7581, 7581], "mapped", [597]], [[7582, 7582], "mapped", [240]], [[7583, 7583], "mapped", [604]], [[7584, 7584], "mapped", [102]], [[7585, 7585], "mapped", [607]], [[7586, 7586], "mapped", [609]], [[7587, 7587], "mapped", [613]], [[7588, 7588], "mapped", [616]], [[7589, 7589], "mapped", [617]], [[7590, 7590], "mapped", [618]], [[7591, 7591], "mapped", [7547]], [[7592, 7592], "mapped", [669]], [[7593, 7593], "mapped", [621]], [[7594, 7594], "mapped", [7557]], [[7595, 7595], "mapped", [671]], [[7596, 7596], "mapped", [625]], [[7597, 7597], "mapped", [624]], [[7598, 7598], "mapped", [626]], [[7599, 7599], "mapped", [627]], [[7600, 7600], "mapped", [628]], [[7601, 7601], "mapped", [629]], [[7602, 7602], "mapped", [632]], [[7603, 7603], "mapped", [642]], [[7604, 7604], "mapped", [643]], [[7605, 7605], "mapped", [427]], [[7606, 7606], "mapped", [649]], [[7607, 7607], "mapped", [650]], [[7608, 7608], "mapped", [7452]], [[7609, 7609], "mapped", [651]], [[7610, 7610], "mapped", [652]], [[7611, 7611], "mapped", [122]], [[7612, 7612], "mapped", [656]], [[7613, 7613], "mapped", [657]], [[7614, 7614], "mapped", [658]], [[7615, 7615], "mapped", [952]], [[7616, 7619], "valid"], [[7620, 7626], "valid"], [[7627, 7654], "valid"], [[7655, 7669], "valid"], [[7670, 7675], "disallowed"], [[7676, 7676], "valid"], [[7677, 7677], "valid"], [[7678, 7679], "valid"], [[7680, 7680], "mapped", [7681]], [[7681, 7681], "valid"], [[7682, 7682], "mapped", [7683]], [[7683, 7683], "valid"], [[7684, 7684], "mapped", [7685]], [[7685, 7685], "valid"], [[7686, 7686], "mapped", [7687]], [[7687, 7687], "valid"], [[7688, 7688], "mapped", [7689]], [[7689, 7689], "valid"], [[7690, 7690], "mapped", [7691]], [[7691, 7691], "valid"], [[7692, 7692], "mapped", [7693]], [[7693, 7693], "valid"], [[7694, 7694], "mapped", [7695]], [[7695, 7695], "valid"], [[7696, 7696], "mapped", [7697]], [[7697, 7697], "valid"], [[7698, 7698], "mapped", [7699]], [[7699, 7699], "valid"], [[7700, 7700], "mapped", [7701]], [[7701, 7701], "valid"], [[7702, 7702], "mapped", [7703]], [[7703, 7703], "valid"], [[7704, 7704], "mapped", [7705]], [[7705, 7705], "valid"], [[7706, 7706], "mapped", [7707]], [[7707, 7707], "valid"], [[7708, 7708], "mapped", [7709]], [[7709, 7709], "valid"], [[7710, 7710], "mapped", [7711]], [[7711, 7711], "valid"], [[7712, 7712], "mapped", [7713]], [[7713, 7713], "valid"], [[7714, 7714], "mapped", [7715]], [[7715, 7715], "valid"], [[7716, 7716], "mapped", [7717]], [[7717, 7717], "valid"], [[7718, 7718], "mapped", [7719]], [[7719, 7719], "valid"], [[7720, 7720], "mapped", [7721]], [[7721, 7721], "valid"], [[7722, 7722], "mapped", [7723]], [[7723, 7723], "valid"], [[7724, 7724], "mapped", [7725]], [[7725, 7725], "valid"], [[7726, 7726], "mapped", [7727]], [[7727, 7727], "valid"], [[7728, 7728], "mapped", [7729]], [[7729, 7729], "valid"], [[7730, 7730], "mapped", [7731]], [[7731, 7731], "valid"], [[7732, 7732], "mapped", [7733]], [[7733, 7733], "valid"], [[7734, 7734], "mapped", [7735]], [[7735, 7735], "valid"], [[7736, 7736], "mapped", [7737]], [[7737, 7737], "valid"], [[7738, 7738], "mapped", [7739]], [[7739, 7739], "valid"], [[7740, 7740], "mapped", [7741]], [[7741, 7741], "valid"], [[7742, 7742], "mapped", [7743]], [[7743, 7743], "valid"], [[7744, 7744], "mapped", [7745]], [[7745, 7745], "valid"], [[7746, 7746], "mapped", [7747]], [[7747, 7747], "valid"], [[7748, 7748], "mapped", [7749]], [[7749, 7749], "valid"], [[7750, 7750], "mapped", [7751]], [[7751, 7751], "valid"], [[7752, 7752], "mapped", [7753]], [[7753, 7753], "valid"], [[7754, 7754], "mapped", [7755]], [[7755, 7755], "valid"], [[7756, 7756], "mapped", [7757]], [[7757, 7757], "valid"], [[7758, 7758], "mapped", [7759]], [[7759, 7759], "valid"], [[7760, 7760], "mapped", [7761]], [[7761, 7761], "valid"], [[7762, 7762], "mapped", [7763]], [[7763, 7763], "valid"], [[7764, 7764], "mapped", [7765]], [[7765, 7765], "valid"], [[7766, 7766], "mapped", [7767]], [[7767, 7767], "valid"], [[7768, 7768], "mapped", [7769]], [[7769, 7769], "valid"], [[7770, 7770], "mapped", [7771]], [[7771, 7771], "valid"], [[7772, 7772], "mapped", [7773]], [[7773, 7773], "valid"], [[7774, 7774], "mapped", [7775]], [[7775, 7775], "valid"], [[7776, 7776], "mapped", [7777]], [[7777, 7777], "valid"], [[7778, 7778], "mapped", [7779]], [[7779, 7779], "valid"], [[7780, 7780], "mapped", [7781]], [[7781, 7781], "valid"], [[7782, 7782], "mapped", [7783]], [[7783, 7783], "valid"], [[7784, 7784], "mapped", [7785]], [[7785, 7785], "valid"], [[7786, 7786], "mapped", [7787]], [[7787, 7787], "valid"], [[7788, 7788], "mapped", [7789]], [[7789, 7789], "valid"], [[7790, 7790], "mapped", [7791]], [[7791, 7791], "valid"], [[7792, 7792], "mapped", [7793]], [[7793, 7793], "valid"], [[7794, 7794], "mapped", [7795]], [[7795, 7795], "valid"], [[7796, 7796], "mapped", [7797]], [[7797, 7797], "valid"], [[7798, 7798], "mapped", [7799]], [[7799, 7799], "valid"], [[7800, 7800], "mapped", [7801]], [[7801, 7801], "valid"], [[7802, 7802], "mapped", [7803]], [[7803, 7803], "valid"], [[7804, 7804], "mapped", [7805]], [[7805, 7805], "valid"], [[7806, 7806], "mapped", [7807]], [[7807, 7807], "valid"], [[7808, 7808], "mapped", [7809]], [[7809, 7809], "valid"], [[7810, 7810], "mapped", [7811]], [[7811, 7811], "valid"], [[7812, 7812], "mapped", [7813]], [[7813, 7813], "valid"], [[7814, 7814], "mapped", [7815]], [[7815, 7815], "valid"], [[7816, 7816], "mapped", [7817]], [[7817, 7817], "valid"], [[7818, 7818], "mapped", [7819]], [[7819, 7819], "valid"], [[7820, 7820], "mapped", [7821]], [[7821, 7821], "valid"], [[7822, 7822], "mapped", [7823]], [[7823, 7823], "valid"], [[7824, 7824], "mapped", [7825]], [[7825, 7825], "valid"], [[7826, 7826], "mapped", [7827]], [[7827, 7827], "valid"], [[7828, 7828], "mapped", [7829]], [[7829, 7833], "valid"], [[7834, 7834], "mapped", [97, 702]], [[7835, 7835], "mapped", [7777]], [[7836, 7837], "valid"], [[7838, 7838], "mapped", [115, 115]], [[7839, 7839], "valid"], [[7840, 7840], "mapped", [7841]], [[7841, 7841], "valid"], [[7842, 7842], "mapped", [7843]], [[7843, 7843], "valid"], [[7844, 7844], "mapped", [7845]], [[7845, 7845], "valid"], [[7846, 7846], "mapped", [7847]], [[7847, 7847], "valid"], [[7848, 7848], "mapped", [7849]], [[7849, 7849], "valid"], [[7850, 7850], "mapped", [7851]], [[7851, 7851], "valid"], [[7852, 7852], "mapped", [7853]], [[7853, 7853], "valid"], [[7854, 7854], "mapped", [7855]], [[7855, 7855], "valid"], [[7856, 7856], "mapped", [7857]], [[7857, 7857], "valid"], [[7858, 7858], "mapped", [7859]], [[7859, 7859], "valid"], [[7860, 7860], "mapped", [7861]], [[7861, 7861], "valid"], [[7862, 7862], "mapped", [7863]], [[7863, 7863], "valid"], [[7864, 7864], "mapped", [7865]], [[7865, 7865], "valid"], [[7866, 7866], "mapped", [7867]], [[7867, 7867], "valid"], [[7868, 7868], "mapped", [7869]], [[7869, 7869], "valid"], [[7870, 7870], "mapped", [7871]], [[7871, 7871], "valid"], [[7872, 7872], "mapped", [7873]], [[7873, 7873], "valid"], [[7874, 7874], "mapped", [7875]], [[7875, 7875], "valid"], [[7876, 7876], "mapped", [7877]], [[7877, 7877], "valid"], [[7878, 7878], "mapped", [7879]], [[7879, 7879], "valid"], [[7880, 7880], "mapped", [7881]], [[7881, 7881], "valid"], [[7882, 7882], "mapped", [7883]], [[7883, 7883], "valid"], [[7884, 7884], "mapped", [7885]], [[7885, 7885], "valid"], [[7886, 7886], "mapped", [7887]], [[7887, 7887], "valid"], [[7888, 7888], "mapped", [7889]], [[7889, 7889], "valid"], [[7890, 7890], "mapped", [7891]], [[7891, 7891], "valid"], [[7892, 7892], "mapped", [7893]], [[7893, 7893], "valid"], [[7894, 7894], "mapped", [7895]], [[7895, 7895], "valid"], [[7896, 7896], "mapped", [7897]], [[7897, 7897], "valid"], [[7898, 7898], "mapped", [7899]], [[7899, 7899], "valid"], [[7900, 7900], "mapped", [7901]], [[7901, 7901], "valid"], [[7902, 7902], "mapped", [7903]], [[7903, 7903], "valid"], [[7904, 7904], "mapped", [7905]], [[7905, 7905], "valid"], [[7906, 7906], "mapped", [7907]], [[7907, 7907], "valid"], [[7908, 7908], "mapped", [7909]], [[7909, 7909], "valid"], [[7910, 7910], "mapped", [7911]], [[7911, 7911], "valid"], [[7912, 7912], "mapped", [7913]], [[7913, 7913], "valid"], [[7914, 7914], "mapped", [7915]], [[7915, 7915], "valid"], [[7916, 7916], "mapped", [7917]], [[7917, 7917], "valid"], [[7918, 7918], "mapped", [7919]], [[7919, 7919], "valid"], [[7920, 7920], "mapped", [7921]], [[7921, 7921], "valid"], [[7922, 7922], "mapped", [7923]], [[7923, 7923], "valid"], [[7924, 7924], "mapped", [7925]], [[7925, 7925], "valid"], [[7926, 7926], "mapped", [7927]], [[7927, 7927], "valid"], [[7928, 7928], "mapped", [7929]], [[7929, 7929], "valid"], [[7930, 7930], "mapped", [7931]], [[7931, 7931], "valid"], [[7932, 7932], "mapped", [7933]], [[7933, 7933], "valid"], [[7934, 7934], "mapped", [7935]], [[7935, 7935], "valid"], [[7936, 7943], "valid"], [[7944, 7944], "mapped", [7936]], [[7945, 7945], "mapped", [7937]], [[7946, 7946], "mapped", [7938]], [[7947, 7947], "mapped", [7939]], [[7948, 7948], "mapped", [7940]], [[7949, 7949], "mapped", [7941]], [[7950, 7950], "mapped", [7942]], [[7951, 7951], "mapped", [7943]], [[7952, 7957], "valid"], [[7958, 7959], "disallowed"], [[7960, 7960], "mapped", [7952]], [[7961, 7961], "mapped", [7953]], [[7962, 7962], "mapped", [7954]], [[7963, 7963], "mapped", [7955]], [[7964, 7964], "mapped", [7956]], [[7965, 7965], "mapped", [7957]], [[7966, 7967], "disallowed"], [[7968, 7975], "valid"], [[7976, 7976], "mapped", [7968]], [[7977, 7977], "mapped", [7969]], [[7978, 7978], "mapped", [7970]], [[7979, 7979], "mapped", [7971]], [[7980, 7980], "mapped", [7972]], [[7981, 7981], "mapped", [7973]], [[7982, 7982], "mapped", [7974]], [[7983, 7983], "mapped", [7975]], [[7984, 7991], "valid"], [[7992, 7992], "mapped", [7984]], [[7993, 7993], "mapped", [7985]], [[7994, 7994], "mapped", [7986]], [[7995, 7995], "mapped", [7987]], [[7996, 7996], "mapped", [7988]], [[7997, 7997], "mapped", [7989]], [[7998, 7998], "mapped", [7990]], [[7999, 7999], "mapped", [7991]], [[8e3, 8005], "valid"], [[8006, 8007], "disallowed"], [[8008, 8008], "mapped", [8e3]], [[8009, 8009], "mapped", [8001]], [[8010, 8010], "mapped", [8002]], [[8011, 8011], "mapped", [8003]], [[8012, 8012], "mapped", [8004]], [[8013, 8013], "mapped", [8005]], [[8014, 8015], "disallowed"], [[8016, 8023], "valid"], [[8024, 8024], "disallowed"], [[8025, 8025], "mapped", [8017]], [[8026, 8026], "disallowed"], [[8027, 8027], "mapped", [8019]], [[8028, 8028], "disallowed"], [[8029, 8029], "mapped", [8021]], [[8030, 8030], "disallowed"], [[8031, 8031], "mapped", [8023]], [[8032, 8039], "valid"], [[8040, 8040], "mapped", [8032]], [[8041, 8041], "mapped", [8033]], [[8042, 8042], "mapped", [8034]], [[8043, 8043], "mapped", [8035]], [[8044, 8044], "mapped", [8036]], [[8045, 8045], "mapped", [8037]], [[8046, 8046], "mapped", [8038]], [[8047, 8047], "mapped", [8039]], [[8048, 8048], "valid"], [[8049, 8049], "mapped", [940]], [[8050, 8050], "valid"], [[8051, 8051], "mapped", [941]], [[8052, 8052], "valid"], [[8053, 8053], "mapped", [942]], [[8054, 8054], "valid"], [[8055, 8055], "mapped", [943]], [[8056, 8056], "valid"], [[8057, 8057], "mapped", [972]], [[8058, 8058], "valid"], [[8059, 8059], "mapped", [973]], [[8060, 8060], "valid"], [[8061, 8061], "mapped", [974]], [[8062, 8063], "disallowed"], [[8064, 8064], "mapped", [7936, 953]], [[8065, 8065], "mapped", [7937, 953]], [[8066, 8066], "mapped", [7938, 953]], [[8067, 8067], "mapped", [7939, 953]], [[8068, 8068], "mapped", [7940, 953]], [[8069, 8069], "mapped", [7941, 953]], [[8070, 8070], "mapped", [7942, 953]], [[8071, 8071], "mapped", [7943, 953]], [[8072, 8072], "mapped", [7936, 953]], [[8073, 8073], "mapped", [7937, 953]], [[8074, 8074], "mapped", [7938, 953]], [[8075, 8075], "mapped", [7939, 953]], [[8076, 8076], "mapped", [7940, 953]], [[8077, 8077], "mapped", [7941, 953]], [[8078, 8078], "mapped", [7942, 953]], [[8079, 8079], "mapped", [7943, 953]], [[8080, 8080], "mapped", [7968, 953]], [[8081, 8081], "mapped", [7969, 953]], [[8082, 8082], "mapped", [7970, 953]], [[8083, 8083], "mapped", [7971, 953]], [[8084, 8084], "mapped", [7972, 953]], [[8085, 8085], "mapped", [7973, 953]], [[8086, 8086], "mapped", [7974, 953]], [[8087, 8087], "mapped", [7975, 953]], [[8088, 8088], "mapped", [7968, 953]], [[8089, 8089], "mapped", [7969, 953]], [[8090, 8090], "mapped", [7970, 953]], [[8091, 8091], "mapped", [7971, 953]], [[8092, 8092], "mapped", [7972, 953]], [[8093, 8093], "mapped", [7973, 953]], [[8094, 8094], "mapped", [7974, 953]], [[8095, 8095], "mapped", [7975, 953]], [[8096, 8096], "mapped", [8032, 953]], [[8097, 8097], "mapped", [8033, 953]], [[8098, 8098], "mapped", [8034, 953]], [[8099, 8099], "mapped", [8035, 953]], [[8100, 8100], "mapped", [8036, 953]], [[8101, 8101], "mapped", [8037, 953]], [[8102, 8102], "mapped", [8038, 953]], [[8103, 8103], "mapped", [8039, 953]], [[8104, 8104], "mapped", [8032, 953]], [[8105, 8105], "mapped", [8033, 953]], [[8106, 8106], "mapped", [8034, 953]], [[8107, 8107], "mapped", [8035, 953]], [[8108, 8108], "mapped", [8036, 953]], [[8109, 8109], "mapped", [8037, 953]], [[8110, 8110], "mapped", [8038, 953]], [[8111, 8111], "mapped", [8039, 953]], [[8112, 8113], "valid"], [[8114, 8114], "mapped", [8048, 953]], [[8115, 8115], "mapped", [945, 953]], [[8116, 8116], "mapped", [940, 953]], [[8117, 8117], "disallowed"], [[8118, 8118], "valid"], [[8119, 8119], "mapped", [8118, 953]], [[8120, 8120], "mapped", [8112]], [[8121, 8121], "mapped", [8113]], [[8122, 8122], "mapped", [8048]], [[8123, 8123], "mapped", [940]], [[8124, 8124], "mapped", [945, 953]], [[8125, 8125], "disallowed_STD3_mapped", [32, 787]], [[8126, 8126], "mapped", [953]], [[8127, 8127], "disallowed_STD3_mapped", [32, 787]], [[8128, 8128], "disallowed_STD3_mapped", [32, 834]], [[8129, 8129], "disallowed_STD3_mapped", [32, 776, 834]], [[8130, 8130], "mapped", [8052, 953]], [[8131, 8131], "mapped", [951, 953]], [[8132, 8132], "mapped", [942, 953]], [[8133, 8133], "disallowed"], [[8134, 8134], "valid"], [[8135, 8135], "mapped", [8134, 953]], [[8136, 8136], "mapped", [8050]], [[8137, 8137], "mapped", [941]], [[8138, 8138], "mapped", [8052]], [[8139, 8139], "mapped", [942]], [[8140, 8140], "mapped", [951, 953]], [[8141, 8141], "disallowed_STD3_mapped", [32, 787, 768]], [[8142, 8142], "disallowed_STD3_mapped", [32, 787, 769]], [[8143, 8143], "disallowed_STD3_mapped", [32, 787, 834]], [[8144, 8146], "valid"], [[8147, 8147], "mapped", [912]], [[8148, 8149], "disallowed"], [[8150, 8151], "valid"], [[8152, 8152], "mapped", [8144]], [[8153, 8153], "mapped", [8145]], [[8154, 8154], "mapped", [8054]], [[8155, 8155], "mapped", [943]], [[8156, 8156], "disallowed"], [[8157, 8157], "disallowed_STD3_mapped", [32, 788, 768]], [[8158, 8158], "disallowed_STD3_mapped", [32, 788, 769]], [[8159, 8159], "disallowed_STD3_mapped", [32, 788, 834]], [[8160, 8162], "valid"], [[8163, 8163], "mapped", [944]], [[8164, 8167], "valid"], [[8168, 8168], "mapped", [8160]], [[8169, 8169], "mapped", [8161]], [[8170, 8170], "mapped", [8058]], [[8171, 8171], "mapped", [973]], [[8172, 8172], "mapped", [8165]], [[8173, 8173], "disallowed_STD3_mapped", [32, 776, 768]], [[8174, 8174], "disallowed_STD3_mapped", [32, 776, 769]], [[8175, 8175], "disallowed_STD3_mapped", [96]], [[8176, 8177], "disallowed"], [[8178, 8178], "mapped", [8060, 953]], [[8179, 8179], "mapped", [969, 953]], [[8180, 8180], "mapped", [974, 953]], [[8181, 8181], "disallowed"], [[8182, 8182], "valid"], [[8183, 8183], "mapped", [8182, 953]], [[8184, 8184], "mapped", [8056]], [[8185, 8185], "mapped", [972]], [[8186, 8186], "mapped", [8060]], [[8187, 8187], "mapped", [974]], [[8188, 8188], "mapped", [969, 953]], [[8189, 8189], "disallowed_STD3_mapped", [32, 769]], [[8190, 8190], "disallowed_STD3_mapped", [32, 788]], [[8191, 8191], "disallowed"], [[8192, 8202], "disallowed_STD3_mapped", [32]], [[8203, 8203], "ignored"], [[8204, 8205], "deviation", []], [[8206, 8207], "disallowed"], [[8208, 8208], "valid", [], "NV8"], [[8209, 8209], "mapped", [8208]], [[8210, 8214], "valid", [], "NV8"], [[8215, 8215], "disallowed_STD3_mapped", [32, 819]], [[8216, 8227], "valid", [], "NV8"], [[8228, 8230], "disallowed"], [[8231, 8231], "valid", [], "NV8"], [[8232, 8238], "disallowed"], [[8239, 8239], "disallowed_STD3_mapped", [32]], [[8240, 8242], "valid", [], "NV8"], [[8243, 8243], "mapped", [8242, 8242]], [[8244, 8244], "mapped", [8242, 8242, 8242]], [[8245, 8245], "valid", [], "NV8"], [[8246, 8246], "mapped", [8245, 8245]], [[8247, 8247], "mapped", [8245, 8245, 8245]], [[8248, 8251], "valid", [], "NV8"], [[8252, 8252], "disallowed_STD3_mapped", [33, 33]], [[8253, 8253], "valid", [], "NV8"], [[8254, 8254], "disallowed_STD3_mapped", [32, 773]], [[8255, 8262], "valid", [], "NV8"], [[8263, 8263], "disallowed_STD3_mapped", [63, 63]], [[8264, 8264], "disallowed_STD3_mapped", [63, 33]], [[8265, 8265], "disallowed_STD3_mapped", [33, 63]], [[8266, 8269], "valid", [], "NV8"], [[8270, 8274], "valid", [], "NV8"], [[8275, 8276], "valid", [], "NV8"], [[8277, 8278], "valid", [], "NV8"], [[8279, 8279], "mapped", [8242, 8242, 8242, 8242]], [[8280, 8286], "valid", [], "NV8"], [[8287, 8287], "disallowed_STD3_mapped", [32]], [[8288, 8288], "ignored"], [[8289, 8291], "disallowed"], [[8292, 8292], "ignored"], [[8293, 8293], "disallowed"], [[8294, 8297], "disallowed"], [[8298, 8303], "disallowed"], [[8304, 8304], "mapped", [48]], [[8305, 8305], "mapped", [105]], [[8306, 8307], "disallowed"], [[8308, 8308], "mapped", [52]], [[8309, 8309], "mapped", [53]], [[8310, 8310], "mapped", [54]], [[8311, 8311], "mapped", [55]], [[8312, 8312], "mapped", [56]], [[8313, 8313], "mapped", [57]], [[8314, 8314], "disallowed_STD3_mapped", [43]], [[8315, 8315], "mapped", [8722]], [[8316, 8316], "disallowed_STD3_mapped", [61]], [[8317, 8317], "disallowed_STD3_mapped", [40]], [[8318, 8318], "disallowed_STD3_mapped", [41]], [[8319, 8319], "mapped", [110]], [[8320, 8320], "mapped", [48]], [[8321, 8321], "mapped", [49]], [[8322, 8322], "mapped", [50]], [[8323, 8323], "mapped", [51]], [[8324, 8324], "mapped", [52]], [[8325, 8325], "mapped", [53]], [[8326, 8326], "mapped", [54]], [[8327, 8327], "mapped", [55]], [[8328, 8328], "mapped", [56]], [[8329, 8329], "mapped", [57]], [[8330, 8330], "disallowed_STD3_mapped", [43]], [[8331, 8331], "mapped", [8722]], [[8332, 8332], "disallowed_STD3_mapped", [61]], [[8333, 8333], "disallowed_STD3_mapped", [40]], [[8334, 8334], "disallowed_STD3_mapped", [41]], [[8335, 8335], "disallowed"], [[8336, 8336], "mapped", [97]], [[8337, 8337], "mapped", [101]], [[8338, 8338], "mapped", [111]], [[8339, 8339], "mapped", [120]], [[8340, 8340], "mapped", [601]], [[8341, 8341], "mapped", [104]], [[8342, 8342], "mapped", [107]], [[8343, 8343], "mapped", [108]], [[8344, 8344], "mapped", [109]], [[8345, 8345], "mapped", [110]], [[8346, 8346], "mapped", [112]], [[8347, 8347], "mapped", [115]], [[8348, 8348], "mapped", [116]], [[8349, 8351], "disallowed"], [[8352, 8359], "valid", [], "NV8"], [[8360, 8360], "mapped", [114, 115]], [[8361, 8362], "valid", [], "NV8"], [[8363, 8363], "valid", [], "NV8"], [[8364, 8364], "valid", [], "NV8"], [[8365, 8367], "valid", [], "NV8"], [[8368, 8369], "valid", [], "NV8"], [[8370, 8373], "valid", [], "NV8"], [[8374, 8376], "valid", [], "NV8"], [[8377, 8377], "valid", [], "NV8"], [[8378, 8378], "valid", [], "NV8"], [[8379, 8381], "valid", [], "NV8"], [[8382, 8382], "valid", [], "NV8"], [[8383, 8399], "disallowed"], [[8400, 8417], "valid", [], "NV8"], [[8418, 8419], "valid", [], "NV8"], [[8420, 8426], "valid", [], "NV8"], [[8427, 8427], "valid", [], "NV8"], [[8428, 8431], "valid", [], "NV8"], [[8432, 8432], "valid", [], "NV8"], [[8433, 8447], "disallowed"], [[8448, 8448], "disallowed_STD3_mapped", [97, 47, 99]], [[8449, 8449], "disallowed_STD3_mapped", [97, 47, 115]], [[8450, 8450], "mapped", [99]], [[8451, 8451], "mapped", [176, 99]], [[8452, 8452], "valid", [], "NV8"], [[8453, 8453], "disallowed_STD3_mapped", [99, 47, 111]], [[8454, 8454], "disallowed_STD3_mapped", [99, 47, 117]], [[8455, 8455], "mapped", [603]], [[8456, 8456], "valid", [], "NV8"], [[8457, 8457], "mapped", [176, 102]], [[8458, 8458], "mapped", [103]], [[8459, 8462], "mapped", [104]], [[8463, 8463], "mapped", [295]], [[8464, 8465], "mapped", [105]], [[8466, 8467], "mapped", [108]], [[8468, 8468], "valid", [], "NV8"], [[8469, 8469], "mapped", [110]], [[8470, 8470], "mapped", [110, 111]], [[8471, 8472], "valid", [], "NV8"], [[8473, 8473], "mapped", [112]], [[8474, 8474], "mapped", [113]], [[8475, 8477], "mapped", [114]], [[8478, 8479], "valid", [], "NV8"], [[8480, 8480], "mapped", [115, 109]], [[8481, 8481], "mapped", [116, 101, 108]], [[8482, 8482], "mapped", [116, 109]], [[8483, 8483], "valid", [], "NV8"], [[8484, 8484], "mapped", [122]], [[8485, 8485], "valid", [], "NV8"], [[8486, 8486], "mapped", [969]], [[8487, 8487], "valid", [], "NV8"], [[8488, 8488], "mapped", [122]], [[8489, 8489], "valid", [], "NV8"], [[8490, 8490], "mapped", [107]], [[8491, 8491], "mapped", [229]], [[8492, 8492], "mapped", [98]], [[8493, 8493], "mapped", [99]], [[8494, 8494], "valid", [], "NV8"], [[8495, 8496], "mapped", [101]], [[8497, 8497], "mapped", [102]], [[8498, 8498], "disallowed"], [[8499, 8499], "mapped", [109]], [[8500, 8500], "mapped", [111]], [[8501, 8501], "mapped", [1488]], [[8502, 8502], "mapped", [1489]], [[8503, 8503], "mapped", [1490]], [[8504, 8504], "mapped", [1491]], [[8505, 8505], "mapped", [105]], [[8506, 8506], "valid", [], "NV8"], [[8507, 8507], "mapped", [102, 97, 120]], [[8508, 8508], "mapped", [960]], [[8509, 8510], "mapped", [947]], [[8511, 8511], "mapped", [960]], [[8512, 8512], "mapped", [8721]], [[8513, 8516], "valid", [], "NV8"], [[8517, 8518], "mapped", [100]], [[8519, 8519], "mapped", [101]], [[8520, 8520], "mapped", [105]], [[8521, 8521], "mapped", [106]], [[8522, 8523], "valid", [], "NV8"], [[8524, 8524], "valid", [], "NV8"], [[8525, 8525], "valid", [], "NV8"], [[8526, 8526], "valid"], [[8527, 8527], "valid", [], "NV8"], [[8528, 8528], "mapped", [49, 8260, 55]], [[8529, 8529], "mapped", [49, 8260, 57]], [[8530, 8530], "mapped", [49, 8260, 49, 48]], [[8531, 8531], "mapped", [49, 8260, 51]], [[8532, 8532], "mapped", [50, 8260, 51]], [[8533, 8533], "mapped", [49, 8260, 53]], [[8534, 8534], "mapped", [50, 8260, 53]], [[8535, 8535], "mapped", [51, 8260, 53]], [[8536, 8536], "mapped", [52, 8260, 53]], [[8537, 8537], "mapped", [49, 8260, 54]], [[8538, 8538], "mapped", [53, 8260, 54]], [[8539, 8539], "mapped", [49, 8260, 56]], [[8540, 8540], "mapped", [51, 8260, 56]], [[8541, 8541], "mapped", [53, 8260, 56]], [[8542, 8542], "mapped", [55, 8260, 56]], [[8543, 8543], "mapped", [49, 8260]], [[8544, 8544], "mapped", [105]], [[8545, 8545], "mapped", [105, 105]], [[8546, 8546], "mapped", [105, 105, 105]], [[8547, 8547], "mapped", [105, 118]], [[8548, 8548], "mapped", [118]], [[8549, 8549], "mapped", [118, 105]], [[8550, 8550], "mapped", [118, 105, 105]], [[8551, 8551], "mapped", [118, 105, 105, 105]], [[8552, 8552], "mapped", [105, 120]], [[8553, 8553], "mapped", [120]], [[8554, 8554], "mapped", [120, 105]], [[8555, 8555], "mapped", [120, 105, 105]], [[8556, 8556], "mapped", [108]], [[8557, 8557], "mapped", [99]], [[8558, 8558], "mapped", [100]], [[8559, 8559], "mapped", [109]], [[8560, 8560], "mapped", [105]], [[8561, 8561], "mapped", [105, 105]], [[8562, 8562], "mapped", [105, 105, 105]], [[8563, 8563], "mapped", [105, 118]], [[8564, 8564], "mapped", [118]], [[8565, 8565], "mapped", [118, 105]], [[8566, 8566], "mapped", [118, 105, 105]], [[8567, 8567], "mapped", [118, 105, 105, 105]], [[8568, 8568], "mapped", [105, 120]], [[8569, 8569], "mapped", [120]], [[8570, 8570], "mapped", [120, 105]], [[8571, 8571], "mapped", [120, 105, 105]], [[8572, 8572], "mapped", [108]], [[8573, 8573], "mapped", [99]], [[8574, 8574], "mapped", [100]], [[8575, 8575], "mapped", [109]], [[8576, 8578], "valid", [], "NV8"], [[8579, 8579], "disallowed"], [[8580, 8580], "valid"], [[8581, 8584], "valid", [], "NV8"], [[8585, 8585], "mapped", [48, 8260, 51]], [[8586, 8587], "valid", [], "NV8"], [[8588, 8591], "disallowed"], [[8592, 8682], "valid", [], "NV8"], [[8683, 8691], "valid", [], "NV8"], [[8692, 8703], "valid", [], "NV8"], [[8704, 8747], "valid", [], "NV8"], [[8748, 8748], "mapped", [8747, 8747]], [[8749, 8749], "mapped", [8747, 8747, 8747]], [[8750, 8750], "valid", [], "NV8"], [[8751, 8751], "mapped", [8750, 8750]], [[8752, 8752], "mapped", [8750, 8750, 8750]], [[8753, 8799], "valid", [], "NV8"], [[8800, 8800], "disallowed_STD3_valid"], [[8801, 8813], "valid", [], "NV8"], [[8814, 8815], "disallowed_STD3_valid"], [[8816, 8945], "valid", [], "NV8"], [[8946, 8959], "valid", [], "NV8"], [[8960, 8960], "valid", [], "NV8"], [[8961, 8961], "valid", [], "NV8"], [[8962, 9e3], "valid", [], "NV8"], [[9001, 9001], "mapped", [12296]], [[9002, 9002], "mapped", [12297]], [[9003, 9082], "valid", [], "NV8"], [[9083, 9083], "valid", [], "NV8"], [[9084, 9084], "valid", [], "NV8"], [[9085, 9114], "valid", [], "NV8"], [[9115, 9166], "valid", [], "NV8"], [[9167, 9168], "valid", [], "NV8"], [[9169, 9179], "valid", [], "NV8"], [[9180, 9191], "valid", [], "NV8"], [[9192, 9192], "valid", [], "NV8"], [[9193, 9203], "valid", [], "NV8"], [[9204, 9210], "valid", [], "NV8"], [[9211, 9215], "disallowed"], [[9216, 9252], "valid", [], "NV8"], [[9253, 9254], "valid", [], "NV8"], [[9255, 9279], "disallowed"], [[9280, 9290], "valid", [], "NV8"], [[9291, 9311], "disallowed"], [[9312, 9312], "mapped", [49]], [[9313, 9313], "mapped", [50]], [[9314, 9314], "mapped", [51]], [[9315, 9315], "mapped", [52]], [[9316, 9316], "mapped", [53]], [[9317, 9317], "mapped", [54]], [[9318, 9318], "mapped", [55]], [[9319, 9319], "mapped", [56]], [[9320, 9320], "mapped", [57]], [[9321, 9321], "mapped", [49, 48]], [[9322, 9322], "mapped", [49, 49]], [[9323, 9323], "mapped", [49, 50]], [[9324, 9324], "mapped", [49, 51]], [[9325, 9325], "mapped", [49, 52]], [[9326, 9326], "mapped", [49, 53]], [[9327, 9327], "mapped", [49, 54]], [[9328, 9328], "mapped", [49, 55]], [[9329, 9329], "mapped", [49, 56]], [[9330, 9330], "mapped", [49, 57]], [[9331, 9331], "mapped", [50, 48]], [[9332, 9332], "disallowed_STD3_mapped", [40, 49, 41]], [[9333, 9333], "disallowed_STD3_mapped", [40, 50, 41]], [[9334, 9334], "disallowed_STD3_mapped", [40, 51, 41]], [[9335, 9335], "disallowed_STD3_mapped", [40, 52, 41]], [[9336, 9336], "disallowed_STD3_mapped", [40, 53, 41]], [[9337, 9337], "disallowed_STD3_mapped", [40, 54, 41]], [[9338, 9338], "disallowed_STD3_mapped", [40, 55, 41]], [[9339, 9339], "disallowed_STD3_mapped", [40, 56, 41]], [[9340, 9340], "disallowed_STD3_mapped", [40, 57, 41]], [[9341, 9341], "disallowed_STD3_mapped", [40, 49, 48, 41]], [[9342, 9342], "disallowed_STD3_mapped", [40, 49, 49, 41]], [[9343, 9343], "disallowed_STD3_mapped", [40, 49, 50, 41]], [[9344, 9344], "disallowed_STD3_mapped", [40, 49, 51, 41]], [[9345, 9345], "disallowed_STD3_mapped", [40, 49, 52, 41]], [[9346, 9346], "disallowed_STD3_mapped", [40, 49, 53, 41]], [[9347, 9347], "disallowed_STD3_mapped", [40, 49, 54, 41]], [[9348, 9348], "disallowed_STD3_mapped", [40, 49, 55, 41]], [[9349, 9349], "disallowed_STD3_mapped", [40, 49, 56, 41]], [[9350, 9350], "disallowed_STD3_mapped", [40, 49, 57, 41]], [[9351, 9351], "disallowed_STD3_mapped", [40, 50, 48, 41]], [[9352, 9371], "disallowed"], [[9372, 9372], "disallowed_STD3_mapped", [40, 97, 41]], [[9373, 9373], "disallowed_STD3_mapped", [40, 98, 41]], [[9374, 9374], "disallowed_STD3_mapped", [40, 99, 41]], [[9375, 9375], "disallowed_STD3_mapped", [40, 100, 41]], [[9376, 9376], "disallowed_STD3_mapped", [40, 101, 41]], [[9377, 9377], "disallowed_STD3_mapped", [40, 102, 41]], [[9378, 9378], "disallowed_STD3_mapped", [40, 103, 41]], [[9379, 9379], "disallowed_STD3_mapped", [40, 104, 41]], [[9380, 9380], "disallowed_STD3_mapped", [40, 105, 41]], [[9381, 9381], "disallowed_STD3_mapped", [40, 106, 41]], [[9382, 9382], "disallowed_STD3_mapped", [40, 107, 41]], [[9383, 9383], "disallowed_STD3_mapped", [40, 108, 41]], [[9384, 9384], "disallowed_STD3_mapped", [40, 109, 41]], [[9385, 9385], "disallowed_STD3_mapped", [40, 110, 41]], [[9386, 9386], "disallowed_STD3_mapped", [40, 111, 41]], [[9387, 9387], "disallowed_STD3_mapped", [40, 112, 41]], [[9388, 9388], "disallowed_STD3_mapped", [40, 113, 41]], [[9389, 9389], "disallowed_STD3_mapped", [40, 114, 41]], [[9390, 9390], "disallowed_STD3_mapped", [40, 115, 41]], [[9391, 9391], "disallowed_STD3_mapped", [40, 116, 41]], [[9392, 9392], "disallowed_STD3_mapped", [40, 117, 41]], [[9393, 9393], "disallowed_STD3_mapped", [40, 118, 41]], [[9394, 9394], "disallowed_STD3_mapped", [40, 119, 41]], [[9395, 9395], "disallowed_STD3_mapped", [40, 120, 41]], [[9396, 9396], "disallowed_STD3_mapped", [40, 121, 41]], [[9397, 9397], "disallowed_STD3_mapped", [40, 122, 41]], [[9398, 9398], "mapped", [97]], [[9399, 9399], "mapped", [98]], [[9400, 9400], "mapped", [99]], [[9401, 9401], "mapped", [100]], [[9402, 9402], "mapped", [101]], [[9403, 9403], "mapped", [102]], [[9404, 9404], "mapped", [103]], [[9405, 9405], "mapped", [104]], [[9406, 9406], "mapped", [105]], [[9407, 9407], "mapped", [106]], [[9408, 9408], "mapped", [107]], [[9409, 9409], "mapped", [108]], [[9410, 9410], "mapped", [109]], [[9411, 9411], "mapped", [110]], [[9412, 9412], "mapped", [111]], [[9413, 9413], "mapped", [112]], [[9414, 9414], "mapped", [113]], [[9415, 9415], "mapped", [114]], [[9416, 9416], "mapped", [115]], [[9417, 9417], "mapped", [116]], [[9418, 9418], "mapped", [117]], [[9419, 9419], "mapped", [118]], [[9420, 9420], "mapped", [119]], [[9421, 9421], "mapped", [120]], [[9422, 9422], "mapped", [121]], [[9423, 9423], "mapped", [122]], [[9424, 9424], "mapped", [97]], [[9425, 9425], "mapped", [98]], [[9426, 9426], "mapped", [99]], [[9427, 9427], "mapped", [100]], [[9428, 9428], "mapped", [101]], [[9429, 9429], "mapped", [102]], [[9430, 9430], "mapped", [103]], [[9431, 9431], "mapped", [104]], [[9432, 9432], "mapped", [105]], [[9433, 9433], "mapped", [106]], [[9434, 9434], "mapped", [107]], [[9435, 9435], "mapped", [108]], [[9436, 9436], "mapped", [109]], [[9437, 9437], "mapped", [110]], [[9438, 9438], "mapped", [111]], [[9439, 9439], "mapped", [112]], [[9440, 9440], "mapped", [113]], [[9441, 9441], "mapped", [114]], [[9442, 9442], "mapped", [115]], [[9443, 9443], "mapped", [116]], [[9444, 9444], "mapped", [117]], [[9445, 9445], "mapped", [118]], [[9446, 9446], "mapped", [119]], [[9447, 9447], "mapped", [120]], [[9448, 9448], "mapped", [121]], [[9449, 9449], "mapped", [122]], [[9450, 9450], "mapped", [48]], [[9451, 9470], "valid", [], "NV8"], [[9471, 9471], "valid", [], "NV8"], [[9472, 9621], "valid", [], "NV8"], [[9622, 9631], "valid", [], "NV8"], [[9632, 9711], "valid", [], "NV8"], [[9712, 9719], "valid", [], "NV8"], [[9720, 9727], "valid", [], "NV8"], [[9728, 9747], "valid", [], "NV8"], [[9748, 9749], "valid", [], "NV8"], [[9750, 9751], "valid", [], "NV8"], [[9752, 9752], "valid", [], "NV8"], [[9753, 9753], "valid", [], "NV8"], [[9754, 9839], "valid", [], "NV8"], [[9840, 9841], "valid", [], "NV8"], [[9842, 9853], "valid", [], "NV8"], [[9854, 9855], "valid", [], "NV8"], [[9856, 9865], "valid", [], "NV8"], [[9866, 9873], "valid", [], "NV8"], [[9874, 9884], "valid", [], "NV8"], [[9885, 9885], "valid", [], "NV8"], [[9886, 9887], "valid", [], "NV8"], [[9888, 9889], "valid", [], "NV8"], [[9890, 9905], "valid", [], "NV8"], [[9906, 9906], "valid", [], "NV8"], [[9907, 9916], "valid", [], "NV8"], [[9917, 9919], "valid", [], "NV8"], [[9920, 9923], "valid", [], "NV8"], [[9924, 9933], "valid", [], "NV8"], [[9934, 9934], "valid", [], "NV8"], [[9935, 9953], "valid", [], "NV8"], [[9954, 9954], "valid", [], "NV8"], [[9955, 9955], "valid", [], "NV8"], [[9956, 9959], "valid", [], "NV8"], [[9960, 9983], "valid", [], "NV8"], [[9984, 9984], "valid", [], "NV8"], [[9985, 9988], "valid", [], "NV8"], [[9989, 9989], "valid", [], "NV8"], [[9990, 9993], "valid", [], "NV8"], [[9994, 9995], "valid", [], "NV8"], [[9996, 10023], "valid", [], "NV8"], [[10024, 10024], "valid", [], "NV8"], [[10025, 10059], "valid", [], "NV8"], [[10060, 10060], "valid", [], "NV8"], [[10061, 10061], "valid", [], "NV8"], [[10062, 10062], "valid", [], "NV8"], [[10063, 10066], "valid", [], "NV8"], [[10067, 10069], "valid", [], "NV8"], [[10070, 10070], "valid", [], "NV8"], [[10071, 10071], "valid", [], "NV8"], [[10072, 10078], "valid", [], "NV8"], [[10079, 10080], "valid", [], "NV8"], [[10081, 10087], "valid", [], "NV8"], [[10088, 10101], "valid", [], "NV8"], [[10102, 10132], "valid", [], "NV8"], [[10133, 10135], "valid", [], "NV8"], [[10136, 10159], "valid", [], "NV8"], [[10160, 10160], "valid", [], "NV8"], [[10161, 10174], "valid", [], "NV8"], [[10175, 10175], "valid", [], "NV8"], [[10176, 10182], "valid", [], "NV8"], [[10183, 10186], "valid", [], "NV8"], [[10187, 10187], "valid", [], "NV8"], [[10188, 10188], "valid", [], "NV8"], [[10189, 10189], "valid", [], "NV8"], [[10190, 10191], "valid", [], "NV8"], [[10192, 10219], "valid", [], "NV8"], [[10220, 10223], "valid", [], "NV8"], [[10224, 10239], "valid", [], "NV8"], [[10240, 10495], "valid", [], "NV8"], [[10496, 10763], "valid", [], "NV8"], [[10764, 10764], "mapped", [8747, 8747, 8747, 8747]], [[10765, 10867], "valid", [], "NV8"], [[10868, 10868], "disallowed_STD3_mapped", [58, 58, 61]], [[10869, 10869], "disallowed_STD3_mapped", [61, 61]], [[10870, 10870], "disallowed_STD3_mapped", [61, 61, 61]], [[10871, 10971], "valid", [], "NV8"], [[10972, 10972], "mapped", [10973, 824]], [[10973, 11007], "valid", [], "NV8"], [[11008, 11021], "valid", [], "NV8"], [[11022, 11027], "valid", [], "NV8"], [[11028, 11034], "valid", [], "NV8"], [[11035, 11039], "valid", [], "NV8"], [[11040, 11043], "valid", [], "NV8"], [[11044, 11084], "valid", [], "NV8"], [[11085, 11087], "valid", [], "NV8"], [[11088, 11092], "valid", [], "NV8"], [[11093, 11097], "valid", [], "NV8"], [[11098, 11123], "valid", [], "NV8"], [[11124, 11125], "disallowed"], [[11126, 11157], "valid", [], "NV8"], [[11158, 11159], "disallowed"], [[11160, 11193], "valid", [], "NV8"], [[11194, 11196], "disallowed"], [[11197, 11208], "valid", [], "NV8"], [[11209, 11209], "disallowed"], [[11210, 11217], "valid", [], "NV8"], [[11218, 11243], "disallowed"], [[11244, 11247], "valid", [], "NV8"], [[11248, 11263], "disallowed"], [[11264, 11264], "mapped", [11312]], [[11265, 11265], "mapped", [11313]], [[11266, 11266], "mapped", [11314]], [[11267, 11267], "mapped", [11315]], [[11268, 11268], "mapped", [11316]], [[11269, 11269], "mapped", [11317]], [[11270, 11270], "mapped", [11318]], [[11271, 11271], "mapped", [11319]], [[11272, 11272], "mapped", [11320]], [[11273, 11273], "mapped", [11321]], [[11274, 11274], "mapped", [11322]], [[11275, 11275], "mapped", [11323]], [[11276, 11276], "mapped", [11324]], [[11277, 11277], "mapped", [11325]], [[11278, 11278], "mapped", [11326]], [[11279, 11279], "mapped", [11327]], [[11280, 11280], "mapped", [11328]], [[11281, 11281], "mapped", [11329]], [[11282, 11282], "mapped", [11330]], [[11283, 11283], "mapped", [11331]], [[11284, 11284], "mapped", [11332]], [[11285, 11285], "mapped", [11333]], [[11286, 11286], "mapped", [11334]], [[11287, 11287], "mapped", [11335]], [[11288, 11288], "mapped", [11336]], [[11289, 11289], "mapped", [11337]], [[11290, 11290], "mapped", [11338]], [[11291, 11291], "mapped", [11339]], [[11292, 11292], "mapped", [11340]], [[11293, 11293], "mapped", [11341]], [[11294, 11294], "mapped", [11342]], [[11295, 11295], "mapped", [11343]], [[11296, 11296], "mapped", [11344]], [[11297, 11297], "mapped", [11345]], [[11298, 11298], "mapped", [11346]], [[11299, 11299], "mapped", [11347]], [[11300, 11300], "mapped", [11348]], [[11301, 11301], "mapped", [11349]], [[11302, 11302], "mapped", [11350]], [[11303, 11303], "mapped", [11351]], [[11304, 11304], "mapped", [11352]], [[11305, 11305], "mapped", [11353]], [[11306, 11306], "mapped", [11354]], [[11307, 11307], "mapped", [11355]], [[11308, 11308], "mapped", [11356]], [[11309, 11309], "mapped", [11357]], [[11310, 11310], "mapped", [11358]], [[11311, 11311], "disallowed"], [[11312, 11358], "valid"], [[11359, 11359], "disallowed"], [[11360, 11360], "mapped", [11361]], [[11361, 11361], "valid"], [[11362, 11362], "mapped", [619]], [[11363, 11363], "mapped", [7549]], [[11364, 11364], "mapped", [637]], [[11365, 11366], "valid"], [[11367, 11367], "mapped", [11368]], [[11368, 11368], "valid"], [[11369, 11369], "mapped", [11370]], [[11370, 11370], "valid"], [[11371, 11371], "mapped", [11372]], [[11372, 11372], "valid"], [[11373, 11373], "mapped", [593]], [[11374, 11374], "mapped", [625]], [[11375, 11375], "mapped", [592]], [[11376, 11376], "mapped", [594]], [[11377, 11377], "valid"], [[11378, 11378], "mapped", [11379]], [[11379, 11379], "valid"], [[11380, 11380], "valid"], [[11381, 11381], "mapped", [11382]], [[11382, 11383], "valid"], [[11384, 11387], "valid"], [[11388, 11388], "mapped", [106]], [[11389, 11389], "mapped", [118]], [[11390, 11390], "mapped", [575]], [[11391, 11391], "mapped", [576]], [[11392, 11392], "mapped", [11393]], [[11393, 11393], "valid"], [[11394, 11394], "mapped", [11395]], [[11395, 11395], "valid"], [[11396, 11396], "mapped", [11397]], [[11397, 11397], "valid"], [[11398, 11398], "mapped", [11399]], [[11399, 11399], "valid"], [[11400, 11400], "mapped", [11401]], [[11401, 11401], "valid"], [[11402, 11402], "mapped", [11403]], [[11403, 11403], "valid"], [[11404, 11404], "mapped", [11405]], [[11405, 11405], "valid"], [[11406, 11406], "mapped", [11407]], [[11407, 11407], "valid"], [[11408, 11408], "mapped", [11409]], [[11409, 11409], "valid"], [[11410, 11410], "mapped", [11411]], [[11411, 11411], "valid"], [[11412, 11412], "mapped", [11413]], [[11413, 11413], "valid"], [[11414, 11414], "mapped", [11415]], [[11415, 11415], "valid"], [[11416, 11416], "mapped", [11417]], [[11417, 11417], "valid"], [[11418, 11418], "mapped", [11419]], [[11419, 11419], "valid"], [[11420, 11420], "mapped", [11421]], [[11421, 11421], "valid"], [[11422, 11422], "mapped", [11423]], [[11423, 11423], "valid"], [[11424, 11424], "mapped", [11425]], [[11425, 11425], "valid"], [[11426, 11426], "mapped", [11427]], [[11427, 11427], "valid"], [[11428, 11428], "mapped", [11429]], [[11429, 11429], "valid"], [[11430, 11430], "mapped", [11431]], [[11431, 11431], "valid"], [[11432, 11432], "mapped", [11433]], [[11433, 11433], "valid"], [[11434, 11434], "mapped", [11435]], [[11435, 11435], "valid"], [[11436, 11436], "mapped", [11437]], [[11437, 11437], "valid"], [[11438, 11438], "mapped", [11439]], [[11439, 11439], "valid"], [[11440, 11440], "mapped", [11441]], [[11441, 11441], "valid"], [[11442, 11442], "mapped", [11443]], [[11443, 11443], "valid"], [[11444, 11444], "mapped", [11445]], [[11445, 11445], "valid"], [[11446, 11446], "mapped", [11447]], [[11447, 11447], "valid"], [[11448, 11448], "mapped", [11449]], [[11449, 11449], "valid"], [[11450, 11450], "mapped", [11451]], [[11451, 11451], "valid"], [[11452, 11452], "mapped", [11453]], [[11453, 11453], "valid"], [[11454, 11454], "mapped", [11455]], [[11455, 11455], "valid"], [[11456, 11456], "mapped", [11457]], [[11457, 11457], "valid"], [[11458, 11458], "mapped", [11459]], [[11459, 11459], "valid"], [[11460, 11460], "mapped", [11461]], [[11461, 11461], "valid"], [[11462, 11462], "mapped", [11463]], [[11463, 11463], "valid"], [[11464, 11464], "mapped", [11465]], [[11465, 11465], "valid"], [[11466, 11466], "mapped", [11467]], [[11467, 11467], "valid"], [[11468, 11468], "mapped", [11469]], [[11469, 11469], "valid"], [[11470, 11470], "mapped", [11471]], [[11471, 11471], "valid"], [[11472, 11472], "mapped", [11473]], [[11473, 11473], "valid"], [[11474, 11474], "mapped", [11475]], [[11475, 11475], "valid"], [[11476, 11476], "mapped", [11477]], [[11477, 11477], "valid"], [[11478, 11478], "mapped", [11479]], [[11479, 11479], "valid"], [[11480, 11480], "mapped", [11481]], [[11481, 11481], "valid"], [[11482, 11482], "mapped", [11483]], [[11483, 11483], "valid"], [[11484, 11484], "mapped", [11485]], [[11485, 11485], "valid"], [[11486, 11486], "mapped", [11487]], [[11487, 11487], "valid"], [[11488, 11488], "mapped", [11489]], [[11489, 11489], "valid"], [[11490, 11490], "mapped", [11491]], [[11491, 11492], "valid"], [[11493, 11498], "valid", [], "NV8"], [[11499, 11499], "mapped", [11500]], [[11500, 11500], "valid"], [[11501, 11501], "mapped", [11502]], [[11502, 11505], "valid"], [[11506, 11506], "mapped", [11507]], [[11507, 11507], "valid"], [[11508, 11512], "disallowed"], [[11513, 11519], "valid", [], "NV8"], [[11520, 11557], "valid"], [[11558, 11558], "disallowed"], [[11559, 11559], "valid"], [[11560, 11564], "disallowed"], [[11565, 11565], "valid"], [[11566, 11567], "disallowed"], [[11568, 11621], "valid"], [[11622, 11623], "valid"], [[11624, 11630], "disallowed"], [[11631, 11631], "mapped", [11617]], [[11632, 11632], "valid", [], "NV8"], [[11633, 11646], "disallowed"], [[11647, 11647], "valid"], [[11648, 11670], "valid"], [[11671, 11679], "disallowed"], [[11680, 11686], "valid"], [[11687, 11687], "disallowed"], [[11688, 11694], "valid"], [[11695, 11695], "disallowed"], [[11696, 11702], "valid"], [[11703, 11703], "disallowed"], [[11704, 11710], "valid"], [[11711, 11711], "disallowed"], [[11712, 11718], "valid"], [[11719, 11719], "disallowed"], [[11720, 11726], "valid"], [[11727, 11727], "disallowed"], [[11728, 11734], "valid"], [[11735, 11735], "disallowed"], [[11736, 11742], "valid"], [[11743, 11743], "disallowed"], [[11744, 11775], "valid"], [[11776, 11799], "valid", [], "NV8"], [[11800, 11803], "valid", [], "NV8"], [[11804, 11805], "valid", [], "NV8"], [[11806, 11822], "valid", [], "NV8"], [[11823, 11823], "valid"], [[11824, 11824], "valid", [], "NV8"], [[11825, 11825], "valid", [], "NV8"], [[11826, 11835], "valid", [], "NV8"], [[11836, 11842], "valid", [], "NV8"], [[11843, 11903], "disallowed"], [[11904, 11929], "valid", [], "NV8"], [[11930, 11930], "disallowed"], [[11931, 11934], "valid", [], "NV8"], [[11935, 11935], "mapped", [27597]], [[11936, 12018], "valid", [], "NV8"], [[12019, 12019], "mapped", [40863]], [[12020, 12031], "disallowed"], [[12032, 12032], "mapped", [19968]], [[12033, 12033], "mapped", [20008]], [[12034, 12034], "mapped", [20022]], [[12035, 12035], "mapped", [20031]], [[12036, 12036], "mapped", [20057]], [[12037, 12037], "mapped", [20101]], [[12038, 12038], "mapped", [20108]], [[12039, 12039], "mapped", [20128]], [[12040, 12040], "mapped", [20154]], [[12041, 12041], "mapped", [20799]], [[12042, 12042], "mapped", [20837]], [[12043, 12043], "mapped", [20843]], [[12044, 12044], "mapped", [20866]], [[12045, 12045], "mapped", [20886]], [[12046, 12046], "mapped", [20907]], [[12047, 12047], "mapped", [20960]], [[12048, 12048], "mapped", [20981]], [[12049, 12049], "mapped", [20992]], [[12050, 12050], "mapped", [21147]], [[12051, 12051], "mapped", [21241]], [[12052, 12052], "mapped", [21269]], [[12053, 12053], "mapped", [21274]], [[12054, 12054], "mapped", [21304]], [[12055, 12055], "mapped", [21313]], [[12056, 12056], "mapped", [21340]], [[12057, 12057], "mapped", [21353]], [[12058, 12058], "mapped", [21378]], [[12059, 12059], "mapped", [21430]], [[12060, 12060], "mapped", [21448]], [[12061, 12061], "mapped", [21475]], [[12062, 12062], "mapped", [22231]], [[12063, 12063], "mapped", [22303]], [[12064, 12064], "mapped", [22763]], [[12065, 12065], "mapped", [22786]], [[12066, 12066], "mapped", [22794]], [[12067, 12067], "mapped", [22805]], [[12068, 12068], "mapped", [22823]], [[12069, 12069], "mapped", [22899]], [[12070, 12070], "mapped", [23376]], [[12071, 12071], "mapped", [23424]], [[12072, 12072], "mapped", [23544]], [[12073, 12073], "mapped", [23567]], [[12074, 12074], "mapped", [23586]], [[12075, 12075], "mapped", [23608]], [[12076, 12076], "mapped", [23662]], [[12077, 12077], "mapped", [23665]], [[12078, 12078], "mapped", [24027]], [[12079, 12079], "mapped", [24037]], [[12080, 12080], "mapped", [24049]], [[12081, 12081], "mapped", [24062]], [[12082, 12082], "mapped", [24178]], [[12083, 12083], "mapped", [24186]], [[12084, 12084], "mapped", [24191]], [[12085, 12085], "mapped", [24308]], [[12086, 12086], "mapped", [24318]], [[12087, 12087], "mapped", [24331]], [[12088, 12088], "mapped", [24339]], [[12089, 12089], "mapped", [24400]], [[12090, 12090], "mapped", [24417]], [[12091, 12091], "mapped", [24435]], [[12092, 12092], "mapped", [24515]], [[12093, 12093], "mapped", [25096]], [[12094, 12094], "mapped", [25142]], [[12095, 12095], "mapped", [25163]], [[12096, 12096], "mapped", [25903]], [[12097, 12097], "mapped", [25908]], [[12098, 12098], "mapped", [25991]], [[12099, 12099], "mapped", [26007]], [[12100, 12100], "mapped", [26020]], [[12101, 12101], "mapped", [26041]], [[12102, 12102], "mapped", [26080]], [[12103, 12103], "mapped", [26085]], [[12104, 12104], "mapped", [26352]], [[12105, 12105], "mapped", [26376]], [[12106, 12106], "mapped", [26408]], [[12107, 12107], "mapped", [27424]], [[12108, 12108], "mapped", [27490]], [[12109, 12109], "mapped", [27513]], [[12110, 12110], "mapped", [27571]], [[12111, 12111], "mapped", [27595]], [[12112, 12112], "mapped", [27604]], [[12113, 12113], "mapped", [27611]], [[12114, 12114], "mapped", [27663]], [[12115, 12115], "mapped", [27668]], [[12116, 12116], "mapped", [27700]], [[12117, 12117], "mapped", [28779]], [[12118, 12118], "mapped", [29226]], [[12119, 12119], "mapped", [29238]], [[12120, 12120], "mapped", [29243]], [[12121, 12121], "mapped", [29247]], [[12122, 12122], "mapped", [29255]], [[12123, 12123], "mapped", [29273]], [[12124, 12124], "mapped", [29275]], [[12125, 12125], "mapped", [29356]], [[12126, 12126], "mapped", [29572]], [[12127, 12127], "mapped", [29577]], [[12128, 12128], "mapped", [29916]], [[12129, 12129], "mapped", [29926]], [[12130, 12130], "mapped", [29976]], [[12131, 12131], "mapped", [29983]], [[12132, 12132], "mapped", [29992]], [[12133, 12133], "mapped", [3e4]], [[12134, 12134], "mapped", [30091]], [[12135, 12135], "mapped", [30098]], [[12136, 12136], "mapped", [30326]], [[12137, 12137], "mapped", [30333]], [[12138, 12138], "mapped", [30382]], [[12139, 12139], "mapped", [30399]], [[12140, 12140], "mapped", [30446]], [[12141, 12141], "mapped", [30683]], [[12142, 12142], "mapped", [30690]], [[12143, 12143], "mapped", [30707]], [[12144, 12144], "mapped", [31034]], [[12145, 12145], "mapped", [31160]], [[12146, 12146], "mapped", [31166]], [[12147, 12147], "mapped", [31348]], [[12148, 12148], "mapped", [31435]], [[12149, 12149], "mapped", [31481]], [[12150, 12150], "mapped", [31859]], [[12151, 12151], "mapped", [31992]], [[12152, 12152], "mapped", [32566]], [[12153, 12153], "mapped", [32593]], [[12154, 12154], "mapped", [32650]], [[12155, 12155], "mapped", [32701]], [[12156, 12156], "mapped", [32769]], [[12157, 12157], "mapped", [32780]], [[12158, 12158], "mapped", [32786]], [[12159, 12159], "mapped", [32819]], [[12160, 12160], "mapped", [32895]], [[12161, 12161], "mapped", [32905]], [[12162, 12162], "mapped", [33251]], [[12163, 12163], "mapped", [33258]], [[12164, 12164], "mapped", [33267]], [[12165, 12165], "mapped", [33276]], [[12166, 12166], "mapped", [33292]], [[12167, 12167], "mapped", [33307]], [[12168, 12168], "mapped", [33311]], [[12169, 12169], "mapped", [33390]], [[12170, 12170], "mapped", [33394]], [[12171, 12171], "mapped", [33400]], [[12172, 12172], "mapped", [34381]], [[12173, 12173], "mapped", [34411]], [[12174, 12174], "mapped", [34880]], [[12175, 12175], "mapped", [34892]], [[12176, 12176], "mapped", [34915]], [[12177, 12177], "mapped", [35198]], [[12178, 12178], "mapped", [35211]], [[12179, 12179], "mapped", [35282]], [[12180, 12180], "mapped", [35328]], [[12181, 12181], "mapped", [35895]], [[12182, 12182], "mapped", [35910]], [[12183, 12183], "mapped", [35925]], [[12184, 12184], "mapped", [35960]], [[12185, 12185], "mapped", [35997]], [[12186, 12186], "mapped", [36196]], [[12187, 12187], "mapped", [36208]], [[12188, 12188], "mapped", [36275]], [[12189, 12189], "mapped", [36523]], [[12190, 12190], "mapped", [36554]], [[12191, 12191], "mapped", [36763]], [[12192, 12192], "mapped", [36784]], [[12193, 12193], "mapped", [36789]], [[12194, 12194], "mapped", [37009]], [[12195, 12195], "mapped", [37193]], [[12196, 12196], "mapped", [37318]], [[12197, 12197], "mapped", [37324]], [[12198, 12198], "mapped", [37329]], [[12199, 12199], "mapped", [38263]], [[12200, 12200], "mapped", [38272]], [[12201, 12201], "mapped", [38428]], [[12202, 12202], "mapped", [38582]], [[12203, 12203], "mapped", [38585]], [[12204, 12204], "mapped", [38632]], [[12205, 12205], "mapped", [38737]], [[12206, 12206], "mapped", [38750]], [[12207, 12207], "mapped", [38754]], [[12208, 12208], "mapped", [38761]], [[12209, 12209], "mapped", [38859]], [[12210, 12210], "mapped", [38893]], [[12211, 12211], "mapped", [38899]], [[12212, 12212], "mapped", [38913]], [[12213, 12213], "mapped", [39080]], [[12214, 12214], "mapped", [39131]], [[12215, 12215], "mapped", [39135]], [[12216, 12216], "mapped", [39318]], [[12217, 12217], "mapped", [39321]], [[12218, 12218], "mapped", [39340]], [[12219, 12219], "mapped", [39592]], [[12220, 12220], "mapped", [39640]], [[12221, 12221], "mapped", [39647]], [[12222, 12222], "mapped", [39717]], [[12223, 12223], "mapped", [39727]], [[12224, 12224], "mapped", [39730]], [[12225, 12225], "mapped", [39740]], [[12226, 12226], "mapped", [39770]], [[12227, 12227], "mapped", [40165]], [[12228, 12228], "mapped", [40565]], [[12229, 12229], "mapped", [40575]], [[12230, 12230], "mapped", [40613]], [[12231, 12231], "mapped", [40635]], [[12232, 12232], "mapped", [40643]], [[12233, 12233], "mapped", [40653]], [[12234, 12234], "mapped", [40657]], [[12235, 12235], "mapped", [40697]], [[12236, 12236], "mapped", [40701]], [[12237, 12237], "mapped", [40718]], [[12238, 12238], "mapped", [40723]], [[12239, 12239], "mapped", [40736]], [[12240, 12240], "mapped", [40763]], [[12241, 12241], "mapped", [40778]], [[12242, 12242], "mapped", [40786]], [[12243, 12243], "mapped", [40845]], [[12244, 12244], "mapped", [40860]], [[12245, 12245], "mapped", [40864]], [[12246, 12271], "disallowed"], [[12272, 12283], "disallowed"], [[12284, 12287], "disallowed"], [[12288, 12288], "disallowed_STD3_mapped", [32]], [[12289, 12289], "valid", [], "NV8"], [[12290, 12290], "mapped", [46]], [[12291, 12292], "valid", [], "NV8"], [[12293, 12295], "valid"], [[12296, 12329], "valid", [], "NV8"], [[12330, 12333], "valid"], [[12334, 12341], "valid", [], "NV8"], [[12342, 12342], "mapped", [12306]], [[12343, 12343], "valid", [], "NV8"], [[12344, 12344], "mapped", [21313]], [[12345, 12345], "mapped", [21316]], [[12346, 12346], "mapped", [21317]], [[12347, 12347], "valid", [], "NV8"], [[12348, 12348], "valid"], [[12349, 12349], "valid", [], "NV8"], [[12350, 12350], "valid", [], "NV8"], [[12351, 12351], "valid", [], "NV8"], [[12352, 12352], "disallowed"], [[12353, 12436], "valid"], [[12437, 12438], "valid"], [[12439, 12440], "disallowed"], [[12441, 12442], "valid"], [[12443, 12443], "disallowed_STD3_mapped", [32, 12441]], [[12444, 12444], "disallowed_STD3_mapped", [32, 12442]], [[12445, 12446], "valid"], [[12447, 12447], "mapped", [12424, 12426]], [[12448, 12448], "valid", [], "NV8"], [[12449, 12542], "valid"], [[12543, 12543], "mapped", [12467, 12488]], [[12544, 12548], "disallowed"], [[12549, 12588], "valid"], [[12589, 12589], "valid"], [[12590, 12592], "disallowed"], [[12593, 12593], "mapped", [4352]], [[12594, 12594], "mapped", [4353]], [[12595, 12595], "mapped", [4522]], [[12596, 12596], "mapped", [4354]], [[12597, 12597], "mapped", [4524]], [[12598, 12598], "mapped", [4525]], [[12599, 12599], "mapped", [4355]], [[12600, 12600], "mapped", [4356]], [[12601, 12601], "mapped", [4357]], [[12602, 12602], "mapped", [4528]], [[12603, 12603], "mapped", [4529]], [[12604, 12604], "mapped", [4530]], [[12605, 12605], "mapped", [4531]], [[12606, 12606], "mapped", [4532]], [[12607, 12607], "mapped", [4533]], [[12608, 12608], "mapped", [4378]], [[12609, 12609], "mapped", [4358]], [[12610, 12610], "mapped", [4359]], [[12611, 12611], "mapped", [4360]], [[12612, 12612], "mapped", [4385]], [[12613, 12613], "mapped", [4361]], [[12614, 12614], "mapped", [4362]], [[12615, 12615], "mapped", [4363]], [[12616, 12616], "mapped", [4364]], [[12617, 12617], "mapped", [4365]], [[12618, 12618], "mapped", [4366]], [[12619, 12619], "mapped", [4367]], [[12620, 12620], "mapped", [4368]], [[12621, 12621], "mapped", [4369]], [[12622, 12622], "mapped", [4370]], [[12623, 12623], "mapped", [4449]], [[12624, 12624], "mapped", [4450]], [[12625, 12625], "mapped", [4451]], [[12626, 12626], "mapped", [4452]], [[12627, 12627], "mapped", [4453]], [[12628, 12628], "mapped", [4454]], [[12629, 12629], "mapped", [4455]], [[12630, 12630], "mapped", [4456]], [[12631, 12631], "mapped", [4457]], [[12632, 12632], "mapped", [4458]], [[12633, 12633], "mapped", [4459]], [[12634, 12634], "mapped", [4460]], [[12635, 12635], "mapped", [4461]], [[12636, 12636], "mapped", [4462]], [[12637, 12637], "mapped", [4463]], [[12638, 12638], "mapped", [4464]], [[12639, 12639], "mapped", [4465]], [[12640, 12640], "mapped", [4466]], [[12641, 12641], "mapped", [4467]], [[12642, 12642], "mapped", [4468]], [[12643, 12643], "mapped", [4469]], [[12644, 12644], "disallowed"], [[12645, 12645], "mapped", [4372]], [[12646, 12646], "mapped", [4373]], [[12647, 12647], "mapped", [4551]], [[12648, 12648], "mapped", [4552]], [[12649, 12649], "mapped", [4556]], [[12650, 12650], "mapped", [4558]], [[12651, 12651], "mapped", [4563]], [[12652, 12652], "mapped", [4567]], [[12653, 12653], "mapped", [4569]], [[12654, 12654], "mapped", [4380]], [[12655, 12655], "mapped", [4573]], [[12656, 12656], "mapped", [4575]], [[12657, 12657], "mapped", [4381]], [[12658, 12658], "mapped", [4382]], [[12659, 12659], "mapped", [4384]], [[12660, 12660], "mapped", [4386]], [[12661, 12661], "mapped", [4387]], [[12662, 12662], "mapped", [4391]], [[12663, 12663], "mapped", [4393]], [[12664, 12664], "mapped", [4395]], [[12665, 12665], "mapped", [4396]], [[12666, 12666], "mapped", [4397]], [[12667, 12667], "mapped", [4398]], [[12668, 12668], "mapped", [4399]], [[12669, 12669], "mapped", [4402]], [[12670, 12670], "mapped", [4406]], [[12671, 12671], "mapped", [4416]], [[12672, 12672], "mapped", [4423]], [[12673, 12673], "mapped", [4428]], [[12674, 12674], "mapped", [4593]], [[12675, 12675], "mapped", [4594]], [[12676, 12676], "mapped", [4439]], [[12677, 12677], "mapped", [4440]], [[12678, 12678], "mapped", [4441]], [[12679, 12679], "mapped", [4484]], [[12680, 12680], "mapped", [4485]], [[12681, 12681], "mapped", [4488]], [[12682, 12682], "mapped", [4497]], [[12683, 12683], "mapped", [4498]], [[12684, 12684], "mapped", [4500]], [[12685, 12685], "mapped", [4510]], [[12686, 12686], "mapped", [4513]], [[12687, 12687], "disallowed"], [[12688, 12689], "valid", [], "NV8"], [[12690, 12690], "mapped", [19968]], [[12691, 12691], "mapped", [20108]], [[12692, 12692], "mapped", [19977]], [[12693, 12693], "mapped", [22235]], [[12694, 12694], "mapped", [19978]], [[12695, 12695], "mapped", [20013]], [[12696, 12696], "mapped", [19979]], [[12697, 12697], "mapped", [30002]], [[12698, 12698], "mapped", [20057]], [[12699, 12699], "mapped", [19993]], [[12700, 12700], "mapped", [19969]], [[12701, 12701], "mapped", [22825]], [[12702, 12702], "mapped", [22320]], [[12703, 12703], "mapped", [20154]], [[12704, 12727], "valid"], [[12728, 12730], "valid"], [[12731, 12735], "disallowed"], [[12736, 12751], "valid", [], "NV8"], [[12752, 12771], "valid", [], "NV8"], [[12772, 12783], "disallowed"], [[12784, 12799], "valid"], [[12800, 12800], "disallowed_STD3_mapped", [40, 4352, 41]], [[12801, 12801], "disallowed_STD3_mapped", [40, 4354, 41]], [[12802, 12802], "disallowed_STD3_mapped", [40, 4355, 41]], [[12803, 12803], "disallowed_STD3_mapped", [40, 4357, 41]], [[12804, 12804], "disallowed_STD3_mapped", [40, 4358, 41]], [[12805, 12805], "disallowed_STD3_mapped", [40, 4359, 41]], [[12806, 12806], "disallowed_STD3_mapped", [40, 4361, 41]], [[12807, 12807], "disallowed_STD3_mapped", [40, 4363, 41]], [[12808, 12808], "disallowed_STD3_mapped", [40, 4364, 41]], [[12809, 12809], "disallowed_STD3_mapped", [40, 4366, 41]], [[12810, 12810], "disallowed_STD3_mapped", [40, 4367, 41]], [[12811, 12811], "disallowed_STD3_mapped", [40, 4368, 41]], [[12812, 12812], "disallowed_STD3_mapped", [40, 4369, 41]], [[12813, 12813], "disallowed_STD3_mapped", [40, 4370, 41]], [[12814, 12814], "disallowed_STD3_mapped", [40, 44032, 41]], [[12815, 12815], "disallowed_STD3_mapped", [40, 45208, 41]], [[12816, 12816], "disallowed_STD3_mapped", [40, 45796, 41]], [[12817, 12817], "disallowed_STD3_mapped", [40, 46972, 41]], [[12818, 12818], "disallowed_STD3_mapped", [40, 47560, 41]], [[12819, 12819], "disallowed_STD3_mapped", [40, 48148, 41]], [[12820, 12820], "disallowed_STD3_mapped", [40, 49324, 41]], [[12821, 12821], "disallowed_STD3_mapped", [40, 50500, 41]], [[12822, 12822], "disallowed_STD3_mapped", [40, 51088, 41]], [[12823, 12823], "disallowed_STD3_mapped", [40, 52264, 41]], [[12824, 12824], "disallowed_STD3_mapped", [40, 52852, 41]], [[12825, 12825], "disallowed_STD3_mapped", [40, 53440, 41]], [[12826, 12826], "disallowed_STD3_mapped", [40, 54028, 41]], [[12827, 12827], "disallowed_STD3_mapped", [40, 54616, 41]], [[12828, 12828], "disallowed_STD3_mapped", [40, 51452, 41]], [[12829, 12829], "disallowed_STD3_mapped", [40, 50724, 51204, 41]], [[12830, 12830], "disallowed_STD3_mapped", [40, 50724, 54980, 41]], [[12831, 12831], "disallowed"], [[12832, 12832], "disallowed_STD3_mapped", [40, 19968, 41]], [[12833, 12833], "disallowed_STD3_mapped", [40, 20108, 41]], [[12834, 12834], "disallowed_STD3_mapped", [40, 19977, 41]], [[12835, 12835], "disallowed_STD3_mapped", [40, 22235, 41]], [[12836, 12836], "disallowed_STD3_mapped", [40, 20116, 41]], [[12837, 12837], "disallowed_STD3_mapped", [40, 20845, 41]], [[12838, 12838], "disallowed_STD3_mapped", [40, 19971, 41]], [[12839, 12839], "disallowed_STD3_mapped", [40, 20843, 41]], [[12840, 12840], "disallowed_STD3_mapped", [40, 20061, 41]], [[12841, 12841], "disallowed_STD3_mapped", [40, 21313, 41]], [[12842, 12842], "disallowed_STD3_mapped", [40, 26376, 41]], [[12843, 12843], "disallowed_STD3_mapped", [40, 28779, 41]], [[12844, 12844], "disallowed_STD3_mapped", [40, 27700, 41]], [[12845, 12845], "disallowed_STD3_mapped", [40, 26408, 41]], [[12846, 12846], "disallowed_STD3_mapped", [40, 37329, 41]], [[12847, 12847], "disallowed_STD3_mapped", [40, 22303, 41]], [[12848, 12848], "disallowed_STD3_mapped", [40, 26085, 41]], [[12849, 12849], "disallowed_STD3_mapped", [40, 26666, 41]], [[12850, 12850], "disallowed_STD3_mapped", [40, 26377, 41]], [[12851, 12851], "disallowed_STD3_mapped", [40, 31038, 41]], [[12852, 12852], "disallowed_STD3_mapped", [40, 21517, 41]], [[12853, 12853], "disallowed_STD3_mapped", [40, 29305, 41]], [[12854, 12854], "disallowed_STD3_mapped", [40, 36001, 41]], [[12855, 12855], "disallowed_STD3_mapped", [40, 31069, 41]], [[12856, 12856], "disallowed_STD3_mapped", [40, 21172, 41]], [[12857, 12857], "disallowed_STD3_mapped", [40, 20195, 41]], [[12858, 12858], "disallowed_STD3_mapped", [40, 21628, 41]], [[12859, 12859], "disallowed_STD3_mapped", [40, 23398, 41]], [[12860, 12860], "disallowed_STD3_mapped", [40, 30435, 41]], [[12861, 12861], "disallowed_STD3_mapped", [40, 20225, 41]], [[12862, 12862], "disallowed_STD3_mapped", [40, 36039, 41]], [[12863, 12863], "disallowed_STD3_mapped", [40, 21332, 41]], [[12864, 12864], "disallowed_STD3_mapped", [40, 31085, 41]], [[12865, 12865], "disallowed_STD3_mapped", [40, 20241, 41]], [[12866, 12866], "disallowed_STD3_mapped", [40, 33258, 41]], [[12867, 12867], "disallowed_STD3_mapped", [40, 33267, 41]], [[12868, 12868], "mapped", [21839]], [[12869, 12869], "mapped", [24188]], [[12870, 12870], "mapped", [25991]], [[12871, 12871], "mapped", [31631]], [[12872, 12879], "valid", [], "NV8"], [[12880, 12880], "mapped", [112, 116, 101]], [[12881, 12881], "mapped", [50, 49]], [[12882, 12882], "mapped", [50, 50]], [[12883, 12883], "mapped", [50, 51]], [[12884, 12884], "mapped", [50, 52]], [[12885, 12885], "mapped", [50, 53]], [[12886, 12886], "mapped", [50, 54]], [[12887, 12887], "mapped", [50, 55]], [[12888, 12888], "mapped", [50, 56]], [[12889, 12889], "mapped", [50, 57]], [[12890, 12890], "mapped", [51, 48]], [[12891, 12891], "mapped", [51, 49]], [[12892, 12892], "mapped", [51, 50]], [[12893, 12893], "mapped", [51, 51]], [[12894, 12894], "mapped", [51, 52]], [[12895, 12895], "mapped", [51, 53]], [[12896, 12896], "mapped", [4352]], [[12897, 12897], "mapped", [4354]], [[12898, 12898], "mapped", [4355]], [[12899, 12899], "mapped", [4357]], [[12900, 12900], "mapped", [4358]], [[12901, 12901], "mapped", [4359]], [[12902, 12902], "mapped", [4361]], [[12903, 12903], "mapped", [4363]], [[12904, 12904], "mapped", [4364]], [[12905, 12905], "mapped", [4366]], [[12906, 12906], "mapped", [4367]], [[12907, 12907], "mapped", [4368]], [[12908, 12908], "mapped", [4369]], [[12909, 12909], "mapped", [4370]], [[12910, 12910], "mapped", [44032]], [[12911, 12911], "mapped", [45208]], [[12912, 12912], "mapped", [45796]], [[12913, 12913], "mapped", [46972]], [[12914, 12914], "mapped", [47560]], [[12915, 12915], "mapped", [48148]], [[12916, 12916], "mapped", [49324]], [[12917, 12917], "mapped", [50500]], [[12918, 12918], "mapped", [51088]], [[12919, 12919], "mapped", [52264]], [[12920, 12920], "mapped", [52852]], [[12921, 12921], "mapped", [53440]], [[12922, 12922], "mapped", [54028]], [[12923, 12923], "mapped", [54616]], [[12924, 12924], "mapped", [52280, 44256]], [[12925, 12925], "mapped", [51452, 51032]], [[12926, 12926], "mapped", [50864]], [[12927, 12927], "valid", [], "NV8"], [[12928, 12928], "mapped", [19968]], [[12929, 12929], "mapped", [20108]], [[12930, 12930], "mapped", [19977]], [[12931, 12931], "mapped", [22235]], [[12932, 12932], "mapped", [20116]], [[12933, 12933], "mapped", [20845]], [[12934, 12934], "mapped", [19971]], [[12935, 12935], "mapped", [20843]], [[12936, 12936], "mapped", [20061]], [[12937, 12937], "mapped", [21313]], [[12938, 12938], "mapped", [26376]], [[12939, 12939], "mapped", [28779]], [[12940, 12940], "mapped", [27700]], [[12941, 12941], "mapped", [26408]], [[12942, 12942], "mapped", [37329]], [[12943, 12943], "mapped", [22303]], [[12944, 12944], "mapped", [26085]], [[12945, 12945], "mapped", [26666]], [[12946, 12946], "mapped", [26377]], [[12947, 12947], "mapped", [31038]], [[12948, 12948], "mapped", [21517]], [[12949, 12949], "mapped", [29305]], [[12950, 12950], "mapped", [36001]], [[12951, 12951], "mapped", [31069]], [[12952, 12952], "mapped", [21172]], [[12953, 12953], "mapped", [31192]], [[12954, 12954], "mapped", [30007]], [[12955, 12955], "mapped", [22899]], [[12956, 12956], "mapped", [36969]], [[12957, 12957], "mapped", [20778]], [[12958, 12958], "mapped", [21360]], [[12959, 12959], "mapped", [27880]], [[12960, 12960], "mapped", [38917]], [[12961, 12961], "mapped", [20241]], [[12962, 12962], "mapped", [20889]], [[12963, 12963], "mapped", [27491]], [[12964, 12964], "mapped", [19978]], [[12965, 12965], "mapped", [20013]], [[12966, 12966], "mapped", [19979]], [[12967, 12967], "mapped", [24038]], [[12968, 12968], "mapped", [21491]], [[12969, 12969], "mapped", [21307]], [[12970, 12970], "mapped", [23447]], [[12971, 12971], "mapped", [23398]], [[12972, 12972], "mapped", [30435]], [[12973, 12973], "mapped", [20225]], [[12974, 12974], "mapped", [36039]], [[12975, 12975], "mapped", [21332]], [[12976, 12976], "mapped", [22812]], [[12977, 12977], "mapped", [51, 54]], [[12978, 12978], "mapped", [51, 55]], [[12979, 12979], "mapped", [51, 56]], [[12980, 12980], "mapped", [51, 57]], [[12981, 12981], "mapped", [52, 48]], [[12982, 12982], "mapped", [52, 49]], [[12983, 12983], "mapped", [52, 50]], [[12984, 12984], "mapped", [52, 51]], [[12985, 12985], "mapped", [52, 52]], [[12986, 12986], "mapped", [52, 53]], [[12987, 12987], "mapped", [52, 54]], [[12988, 12988], "mapped", [52, 55]], [[12989, 12989], "mapped", [52, 56]], [[12990, 12990], "mapped", [52, 57]], [[12991, 12991], "mapped", [53, 48]], [[12992, 12992], "mapped", [49, 26376]], [[12993, 12993], "mapped", [50, 26376]], [[12994, 12994], "mapped", [51, 26376]], [[12995, 12995], "mapped", [52, 26376]], [[12996, 12996], "mapped", [53, 26376]], [[12997, 12997], "mapped", [54, 26376]], [[12998, 12998], "mapped", [55, 26376]], [[12999, 12999], "mapped", [56, 26376]], [[13e3, 13e3], "mapped", [57, 26376]], [[13001, 13001], "mapped", [49, 48, 26376]], [[13002, 13002], "mapped", [49, 49, 26376]], [[13003, 13003], "mapped", [49, 50, 26376]], [[13004, 13004], "mapped", [104, 103]], [[13005, 13005], "mapped", [101, 114, 103]], [[13006, 13006], "mapped", [101, 118]], [[13007, 13007], "mapped", [108, 116, 100]], [[13008, 13008], "mapped", [12450]], [[13009, 13009], "mapped", [12452]], [[13010, 13010], "mapped", [12454]], [[13011, 13011], "mapped", [12456]], [[13012, 13012], "mapped", [12458]], [[13013, 13013], "mapped", [12459]], [[13014, 13014], "mapped", [12461]], [[13015, 13015], "mapped", [12463]], [[13016, 13016], "mapped", [12465]], [[13017, 13017], "mapped", [12467]], [[13018, 13018], "mapped", [12469]], [[13019, 13019], "mapped", [12471]], [[13020, 13020], "mapped", [12473]], [[13021, 13021], "mapped", [12475]], [[13022, 13022], "mapped", [12477]], [[13023, 13023], "mapped", [12479]], [[13024, 13024], "mapped", [12481]], [[13025, 13025], "mapped", [12484]], [[13026, 13026], "mapped", [12486]], [[13027, 13027], "mapped", [12488]], [[13028, 13028], "mapped", [12490]], [[13029, 13029], "mapped", [12491]], [[13030, 13030], "mapped", [12492]], [[13031, 13031], "mapped", [12493]], [[13032, 13032], "mapped", [12494]], [[13033, 13033], "mapped", [12495]], [[13034, 13034], "mapped", [12498]], [[13035, 13035], "mapped", [12501]], [[13036, 13036], "mapped", [12504]], [[13037, 13037], "mapped", [12507]], [[13038, 13038], "mapped", [12510]], [[13039, 13039], "mapped", [12511]], [[13040, 13040], "mapped", [12512]], [[13041, 13041], "mapped", [12513]], [[13042, 13042], "mapped", [12514]], [[13043, 13043], "mapped", [12516]], [[13044, 13044], "mapped", [12518]], [[13045, 13045], "mapped", [12520]], [[13046, 13046], "mapped", [12521]], [[13047, 13047], "mapped", [12522]], [[13048, 13048], "mapped", [12523]], [[13049, 13049], "mapped", [12524]], [[13050, 13050], "mapped", [12525]], [[13051, 13051], "mapped", [12527]], [[13052, 13052], "mapped", [12528]], [[13053, 13053], "mapped", [12529]], [[13054, 13054], "mapped", [12530]], [[13055, 13055], "disallowed"], [[13056, 13056], "mapped", [12450, 12497, 12540, 12488]], [[13057, 13057], "mapped", [12450, 12523, 12501, 12449]], [[13058, 13058], "mapped", [12450, 12531, 12506, 12450]], [[13059, 13059], "mapped", [12450, 12540, 12523]], [[13060, 13060], "mapped", [12452, 12491, 12531, 12464]], [[13061, 13061], "mapped", [12452, 12531, 12481]], [[13062, 13062], "mapped", [12454, 12457, 12531]], [[13063, 13063], "mapped", [12456, 12473, 12463, 12540, 12489]], [[13064, 13064], "mapped", [12456, 12540, 12459, 12540]], [[13065, 13065], "mapped", [12458, 12531, 12473]], [[13066, 13066], "mapped", [12458, 12540, 12512]], [[13067, 13067], "mapped", [12459, 12452, 12522]], [[13068, 13068], "mapped", [12459, 12521, 12483, 12488]], [[13069, 13069], "mapped", [12459, 12525, 12522, 12540]], [[13070, 13070], "mapped", [12460, 12525, 12531]], [[13071, 13071], "mapped", [12460, 12531, 12510]], [[13072, 13072], "mapped", [12462, 12460]], [[13073, 13073], "mapped", [12462, 12491, 12540]], [[13074, 13074], "mapped", [12461, 12517, 12522, 12540]], [[13075, 13075], "mapped", [12462, 12523, 12480, 12540]], [[13076, 13076], "mapped", [12461, 12525]], [[13077, 13077], "mapped", [12461, 12525, 12464, 12521, 12512]], [[13078, 13078], "mapped", [12461, 12525, 12513, 12540, 12488, 12523]], [[13079, 13079], "mapped", [12461, 12525, 12527, 12483, 12488]], [[13080, 13080], "mapped", [12464, 12521, 12512]], [[13081, 13081], "mapped", [12464, 12521, 12512, 12488, 12531]], [[13082, 13082], "mapped", [12463, 12523, 12476, 12452, 12525]], [[13083, 13083], "mapped", [12463, 12525, 12540, 12493]], [[13084, 13084], "mapped", [12465, 12540, 12473]], [[13085, 13085], "mapped", [12467, 12523, 12490]], [[13086, 13086], "mapped", [12467, 12540, 12509]], [[13087, 13087], "mapped", [12469, 12452, 12463, 12523]], [[13088, 13088], "mapped", [12469, 12531, 12481, 12540, 12512]], [[13089, 13089], "mapped", [12471, 12522, 12531, 12464]], [[13090, 13090], "mapped", [12475, 12531, 12481]], [[13091, 13091], "mapped", [12475, 12531, 12488]], [[13092, 13092], "mapped", [12480, 12540, 12473]], [[13093, 13093], "mapped", [12487, 12471]], [[13094, 13094], "mapped", [12489, 12523]], [[13095, 13095], "mapped", [12488, 12531]], [[13096, 13096], "mapped", [12490, 12494]], [[13097, 13097], "mapped", [12494, 12483, 12488]], [[13098, 13098], "mapped", [12495, 12452, 12484]], [[13099, 13099], "mapped", [12497, 12540, 12475, 12531, 12488]], [[13100, 13100], "mapped", [12497, 12540, 12484]], [[13101, 13101], "mapped", [12496, 12540, 12524, 12523]], [[13102, 13102], "mapped", [12500, 12450, 12473, 12488, 12523]], [[13103, 13103], "mapped", [12500, 12463, 12523]], [[13104, 13104], "mapped", [12500, 12467]], [[13105, 13105], "mapped", [12499, 12523]], [[13106, 13106], "mapped", [12501, 12449, 12521, 12483, 12489]], [[13107, 13107], "mapped", [12501, 12451, 12540, 12488]], [[13108, 13108], "mapped", [12502, 12483, 12471, 12455, 12523]], [[13109, 13109], "mapped", [12501, 12521, 12531]], [[13110, 13110], "mapped", [12504, 12463, 12479, 12540, 12523]], [[13111, 13111], "mapped", [12506, 12477]], [[13112, 13112], "mapped", [12506, 12491, 12498]], [[13113, 13113], "mapped", [12504, 12523, 12484]], [[13114, 13114], "mapped", [12506, 12531, 12473]], [[13115, 13115], "mapped", [12506, 12540, 12472]], [[13116, 13116], "mapped", [12505, 12540, 12479]], [[13117, 13117], "mapped", [12509, 12452, 12531, 12488]], [[13118, 13118], "mapped", [12508, 12523, 12488]], [[13119, 13119], "mapped", [12507, 12531]], [[13120, 13120], "mapped", [12509, 12531, 12489]], [[13121, 13121], "mapped", [12507, 12540, 12523]], [[13122, 13122], "mapped", [12507, 12540, 12531]], [[13123, 13123], "mapped", [12510, 12452, 12463, 12525]], [[13124, 13124], "mapped", [12510, 12452, 12523]], [[13125, 13125], "mapped", [12510, 12483, 12495]], [[13126, 13126], "mapped", [12510, 12523, 12463]], [[13127, 13127], "mapped", [12510, 12531, 12471, 12519, 12531]], [[13128, 13128], "mapped", [12511, 12463, 12525, 12531]], [[13129, 13129], "mapped", [12511, 12522]], [[13130, 13130], "mapped", [12511, 12522, 12496, 12540, 12523]], [[13131, 13131], "mapped", [12513, 12460]], [[13132, 13132], "mapped", [12513, 12460, 12488, 12531]], [[13133, 13133], "mapped", [12513, 12540, 12488, 12523]], [[13134, 13134], "mapped", [12516, 12540, 12489]], [[13135, 13135], "mapped", [12516, 12540, 12523]], [[13136, 13136], "mapped", [12518, 12450, 12531]], [[13137, 13137], "mapped", [12522, 12483, 12488, 12523]], [[13138, 13138], "mapped", [12522, 12521]], [[13139, 13139], "mapped", [12523, 12500, 12540]], [[13140, 13140], "mapped", [12523, 12540, 12502, 12523]], [[13141, 13141], "mapped", [12524, 12512]], [[13142, 13142], "mapped", [12524, 12531, 12488, 12466, 12531]], [[13143, 13143], "mapped", [12527, 12483, 12488]], [[13144, 13144], "mapped", [48, 28857]], [[13145, 13145], "mapped", [49, 28857]], [[13146, 13146], "mapped", [50, 28857]], [[13147, 13147], "mapped", [51, 28857]], [[13148, 13148], "mapped", [52, 28857]], [[13149, 13149], "mapped", [53, 28857]], [[13150, 13150], "mapped", [54, 28857]], [[13151, 13151], "mapped", [55, 28857]], [[13152, 13152], "mapped", [56, 28857]], [[13153, 13153], "mapped", [57, 28857]], [[13154, 13154], "mapped", [49, 48, 28857]], [[13155, 13155], "mapped", [49, 49, 28857]], [[13156, 13156], "mapped", [49, 50, 28857]], [[13157, 13157], "mapped", [49, 51, 28857]], [[13158, 13158], "mapped", [49, 52, 28857]], [[13159, 13159], "mapped", [49, 53, 28857]], [[13160, 13160], "mapped", [49, 54, 28857]], [[13161, 13161], "mapped", [49, 55, 28857]], [[13162, 13162], "mapped", [49, 56, 28857]], [[13163, 13163], "mapped", [49, 57, 28857]], [[13164, 13164], "mapped", [50, 48, 28857]], [[13165, 13165], "mapped", [50, 49, 28857]], [[13166, 13166], "mapped", [50, 50, 28857]], [[13167, 13167], "mapped", [50, 51, 28857]], [[13168, 13168], "mapped", [50, 52, 28857]], [[13169, 13169], "mapped", [104, 112, 97]], [[13170, 13170], "mapped", [100, 97]], [[13171, 13171], "mapped", [97, 117]], [[13172, 13172], "mapped", [98, 97, 114]], [[13173, 13173], "mapped", [111, 118]], [[13174, 13174], "mapped", [112, 99]], [[13175, 13175], "mapped", [100, 109]], [[13176, 13176], "mapped", [100, 109, 50]], [[13177, 13177], "mapped", [100, 109, 51]], [[13178, 13178], "mapped", [105, 117]], [[13179, 13179], "mapped", [24179, 25104]], [[13180, 13180], "mapped", [26157, 21644]], [[13181, 13181], "mapped", [22823, 27491]], [[13182, 13182], "mapped", [26126, 27835]], [[13183, 13183], "mapped", [26666, 24335, 20250, 31038]], [[13184, 13184], "mapped", [112, 97]], [[13185, 13185], "mapped", [110, 97]], [[13186, 13186], "mapped", [956, 97]], [[13187, 13187], "mapped", [109, 97]], [[13188, 13188], "mapped", [107, 97]], [[13189, 13189], "mapped", [107, 98]], [[13190, 13190], "mapped", [109, 98]], [[13191, 13191], "mapped", [103, 98]], [[13192, 13192], "mapped", [99, 97, 108]], [[13193, 13193], "mapped", [107, 99, 97, 108]], [[13194, 13194], "mapped", [112, 102]], [[13195, 13195], "mapped", [110, 102]], [[13196, 13196], "mapped", [956, 102]], [[13197, 13197], "mapped", [956, 103]], [[13198, 13198], "mapped", [109, 103]], [[13199, 13199], "mapped", [107, 103]], [[13200, 13200], "mapped", [104, 122]], [[13201, 13201], "mapped", [107, 104, 122]], [[13202, 13202], "mapped", [109, 104, 122]], [[13203, 13203], "mapped", [103, 104, 122]], [[13204, 13204], "mapped", [116, 104, 122]], [[13205, 13205], "mapped", [956, 108]], [[13206, 13206], "mapped", [109, 108]], [[13207, 13207], "mapped", [100, 108]], [[13208, 13208], "mapped", [107, 108]], [[13209, 13209], "mapped", [102, 109]], [[13210, 13210], "mapped", [110, 109]], [[13211, 13211], "mapped", [956, 109]], [[13212, 13212], "mapped", [109, 109]], [[13213, 13213], "mapped", [99, 109]], [[13214, 13214], "mapped", [107, 109]], [[13215, 13215], "mapped", [109, 109, 50]], [[13216, 13216], "mapped", [99, 109, 50]], [[13217, 13217], "mapped", [109, 50]], [[13218, 13218], "mapped", [107, 109, 50]], [[13219, 13219], "mapped", [109, 109, 51]], [[13220, 13220], "mapped", [99, 109, 51]], [[13221, 13221], "mapped", [109, 51]], [[13222, 13222], "mapped", [107, 109, 51]], [[13223, 13223], "mapped", [109, 8725, 115]], [[13224, 13224], "mapped", [109, 8725, 115, 50]], [[13225, 13225], "mapped", [112, 97]], [[13226, 13226], "mapped", [107, 112, 97]], [[13227, 13227], "mapped", [109, 112, 97]], [[13228, 13228], "mapped", [103, 112, 97]], [[13229, 13229], "mapped", [114, 97, 100]], [[13230, 13230], "mapped", [114, 97, 100, 8725, 115]], [[13231, 13231], "mapped", [114, 97, 100, 8725, 115, 50]], [[13232, 13232], "mapped", [112, 115]], [[13233, 13233], "mapped", [110, 115]], [[13234, 13234], "mapped", [956, 115]], [[13235, 13235], "mapped", [109, 115]], [[13236, 13236], "mapped", [112, 118]], [[13237, 13237], "mapped", [110, 118]], [[13238, 13238], "mapped", [956, 118]], [[13239, 13239], "mapped", [109, 118]], [[13240, 13240], "mapped", [107, 118]], [[13241, 13241], "mapped", [109, 118]], [[13242, 13242], "mapped", [112, 119]], [[13243, 13243], "mapped", [110, 119]], [[13244, 13244], "mapped", [956, 119]], [[13245, 13245], "mapped", [109, 119]], [[13246, 13246], "mapped", [107, 119]], [[13247, 13247], "mapped", [109, 119]], [[13248, 13248], "mapped", [107, 969]], [[13249, 13249], "mapped", [109, 969]], [[13250, 13250], "disallowed"], [[13251, 13251], "mapped", [98, 113]], [[13252, 13252], "mapped", [99, 99]], [[13253, 13253], "mapped", [99, 100]], [[13254, 13254], "mapped", [99, 8725, 107, 103]], [[13255, 13255], "disallowed"], [[13256, 13256], "mapped", [100, 98]], [[13257, 13257], "mapped", [103, 121]], [[13258, 13258], "mapped", [104, 97]], [[13259, 13259], "mapped", [104, 112]], [[13260, 13260], "mapped", [105, 110]], [[13261, 13261], "mapped", [107, 107]], [[13262, 13262], "mapped", [107, 109]], [[13263, 13263], "mapped", [107, 116]], [[13264, 13264], "mapped", [108, 109]], [[13265, 13265], "mapped", [108, 110]], [[13266, 13266], "mapped", [108, 111, 103]], [[13267, 13267], "mapped", [108, 120]], [[13268, 13268], "mapped", [109, 98]], [[13269, 13269], "mapped", [109, 105, 108]], [[13270, 13270], "mapped", [109, 111, 108]], [[13271, 13271], "mapped", [112, 104]], [[13272, 13272], "disallowed"], [[13273, 13273], "mapped", [112, 112, 109]], [[13274, 13274], "mapped", [112, 114]], [[13275, 13275], "mapped", [115, 114]], [[13276, 13276], "mapped", [115, 118]], [[13277, 13277], "mapped", [119, 98]], [[13278, 13278], "mapped", [118, 8725, 109]], [[13279, 13279], "mapped", [97, 8725, 109]], [[13280, 13280], "mapped", [49, 26085]], [[13281, 13281], "mapped", [50, 26085]], [[13282, 13282], "mapped", [51, 26085]], [[13283, 13283], "mapped", [52, 26085]], [[13284, 13284], "mapped", [53, 26085]], [[13285, 13285], "mapped", [54, 26085]], [[13286, 13286], "mapped", [55, 26085]], [[13287, 13287], "mapped", [56, 26085]], [[13288, 13288], "mapped", [57, 26085]], [[13289, 13289], "mapped", [49, 48, 26085]], [[13290, 13290], "mapped", [49, 49, 26085]], [[13291, 13291], "mapped", [49, 50, 26085]], [[13292, 13292], "mapped", [49, 51, 26085]], [[13293, 13293], "mapped", [49, 52, 26085]], [[13294, 13294], "mapped", [49, 53, 26085]], [[13295, 13295], "mapped", [49, 54, 26085]], [[13296, 13296], "mapped", [49, 55, 26085]], [[13297, 13297], "mapped", [49, 56, 26085]], [[13298, 13298], "mapped", [49, 57, 26085]], [[13299, 13299], "mapped", [50, 48, 26085]], [[13300, 13300], "mapped", [50, 49, 26085]], [[13301, 13301], "mapped", [50, 50, 26085]], [[13302, 13302], "mapped", [50, 51, 26085]], [[13303, 13303], "mapped", [50, 52, 26085]], [[13304, 13304], "mapped", [50, 53, 26085]], [[13305, 13305], "mapped", [50, 54, 26085]], [[13306, 13306], "mapped", [50, 55, 26085]], [[13307, 13307], "mapped", [50, 56, 26085]], [[13308, 13308], "mapped", [50, 57, 26085]], [[13309, 13309], "mapped", [51, 48, 26085]], [[13310, 13310], "mapped", [51, 49, 26085]], [[13311, 13311], "mapped", [103, 97, 108]], [[13312, 19893], "valid"], [[19894, 19903], "disallowed"], [[19904, 19967], "valid", [], "NV8"], [[19968, 40869], "valid"], [[40870, 40891], "valid"], [[40892, 40899], "valid"], [[40900, 40907], "valid"], [[40908, 40908], "valid"], [[40909, 40917], "valid"], [[40918, 40959], "disallowed"], [[40960, 42124], "valid"], [[42125, 42127], "disallowed"], [[42128, 42145], "valid", [], "NV8"], [[42146, 42147], "valid", [], "NV8"], [[42148, 42163], "valid", [], "NV8"], [[42164, 42164], "valid", [], "NV8"], [[42165, 42176], "valid", [], "NV8"], [[42177, 42177], "valid", [], "NV8"], [[42178, 42180], "valid", [], "NV8"], [[42181, 42181], "valid", [], "NV8"], [[42182, 42182], "valid", [], "NV8"], [[42183, 42191], "disallowed"], [[42192, 42237], "valid"], [[42238, 42239], "valid", [], "NV8"], [[42240, 42508], "valid"], [[42509, 42511], "valid", [], "NV8"], [[42512, 42539], "valid"], [[42540, 42559], "disallowed"], [[42560, 42560], "mapped", [42561]], [[42561, 42561], "valid"], [[42562, 42562], "mapped", [42563]], [[42563, 42563], "valid"], [[42564, 42564], "mapped", [42565]], [[42565, 42565], "valid"], [[42566, 42566], "mapped", [42567]], [[42567, 42567], "valid"], [[42568, 42568], "mapped", [42569]], [[42569, 42569], "valid"], [[42570, 42570], "mapped", [42571]], [[42571, 42571], "valid"], [[42572, 42572], "mapped", [42573]], [[42573, 42573], "valid"], [[42574, 42574], "mapped", [42575]], [[42575, 42575], "valid"], [[42576, 42576], "mapped", [42577]], [[42577, 42577], "valid"], [[42578, 42578], "mapped", [42579]], [[42579, 42579], "valid"], [[42580, 42580], "mapped", [42581]], [[42581, 42581], "valid"], [[42582, 42582], "mapped", [42583]], [[42583, 42583], "valid"], [[42584, 42584], "mapped", [42585]], [[42585, 42585], "valid"], [[42586, 42586], "mapped", [42587]], [[42587, 42587], "valid"], [[42588, 42588], "mapped", [42589]], [[42589, 42589], "valid"], [[42590, 42590], "mapped", [42591]], [[42591, 42591], "valid"], [[42592, 42592], "mapped", [42593]], [[42593, 42593], "valid"], [[42594, 42594], "mapped", [42595]], [[42595, 42595], "valid"], [[42596, 42596], "mapped", [42597]], [[42597, 42597], "valid"], [[42598, 42598], "mapped", [42599]], [[42599, 42599], "valid"], [[42600, 42600], "mapped", [42601]], [[42601, 42601], "valid"], [[42602, 42602], "mapped", [42603]], [[42603, 42603], "valid"], [[42604, 42604], "mapped", [42605]], [[42605, 42607], "valid"], [[42608, 42611], "valid", [], "NV8"], [[42612, 42619], "valid"], [[42620, 42621], "valid"], [[42622, 42622], "valid", [], "NV8"], [[42623, 42623], "valid"], [[42624, 42624], "mapped", [42625]], [[42625, 42625], "valid"], [[42626, 42626], "mapped", [42627]], [[42627, 42627], "valid"], [[42628, 42628], "mapped", [42629]], [[42629, 42629], "valid"], [[42630, 42630], "mapped", [42631]], [[42631, 42631], "valid"], [[42632, 42632], "mapped", [42633]], [[42633, 42633], "valid"], [[42634, 42634], "mapped", [42635]], [[42635, 42635], "valid"], [[42636, 42636], "mapped", [42637]], [[42637, 42637], "valid"], [[42638, 42638], "mapped", [42639]], [[42639, 42639], "valid"], [[42640, 42640], "mapped", [42641]], [[42641, 42641], "valid"], [[42642, 42642], "mapped", [42643]], [[42643, 42643], "valid"], [[42644, 42644], "mapped", [42645]], [[42645, 42645], "valid"], [[42646, 42646], "mapped", [42647]], [[42647, 42647], "valid"], [[42648, 42648], "mapped", [42649]], [[42649, 42649], "valid"], [[42650, 42650], "mapped", [42651]], [[42651, 42651], "valid"], [[42652, 42652], "mapped", [1098]], [[42653, 42653], "mapped", [1100]], [[42654, 42654], "valid"], [[42655, 42655], "valid"], [[42656, 42725], "valid"], [[42726, 42735], "valid", [], "NV8"], [[42736, 42737], "valid"], [[42738, 42743], "valid", [], "NV8"], [[42744, 42751], "disallowed"], [[42752, 42774], "valid", [], "NV8"], [[42775, 42778], "valid"], [[42779, 42783], "valid"], [[42784, 42785], "valid", [], "NV8"], [[42786, 42786], "mapped", [42787]], [[42787, 42787], "valid"], [[42788, 42788], "mapped", [42789]], [[42789, 42789], "valid"], [[42790, 42790], "mapped", [42791]], [[42791, 42791], "valid"], [[42792, 42792], "mapped", [42793]], [[42793, 42793], "valid"], [[42794, 42794], "mapped", [42795]], [[42795, 42795], "valid"], [[42796, 42796], "mapped", [42797]], [[42797, 42797], "valid"], [[42798, 42798], "mapped", [42799]], [[42799, 42801], "valid"], [[42802, 42802], "mapped", [42803]], [[42803, 42803], "valid"], [[42804, 42804], "mapped", [42805]], [[42805, 42805], "valid"], [[42806, 42806], "mapped", [42807]], [[42807, 42807], "valid"], [[42808, 42808], "mapped", [42809]], [[42809, 42809], "valid"], [[42810, 42810], "mapped", [42811]], [[42811, 42811], "valid"], [[42812, 42812], "mapped", [42813]], [[42813, 42813], "valid"], [[42814, 42814], "mapped", [42815]], [[42815, 42815], "valid"], [[42816, 42816], "mapped", [42817]], [[42817, 42817], "valid"], [[42818, 42818], "mapped", [42819]], [[42819, 42819], "valid"], [[42820, 42820], "mapped", [42821]], [[42821, 42821], "valid"], [[42822, 42822], "mapped", [42823]], [[42823, 42823], "valid"], [[42824, 42824], "mapped", [42825]], [[42825, 42825], "valid"], [[42826, 42826], "mapped", [42827]], [[42827, 42827], "valid"], [[42828, 42828], "mapped", [42829]], [[42829, 42829], "valid"], [[42830, 42830], "mapped", [42831]], [[42831, 42831], "valid"], [[42832, 42832], "mapped", [42833]], [[42833, 42833], "valid"], [[42834, 42834], "mapped", [42835]], [[42835, 42835], "valid"], [[42836, 42836], "mapped", [42837]], [[42837, 42837], "valid"], [[42838, 42838], "mapped", [42839]], [[42839, 42839], "valid"], [[42840, 42840], "mapped", [42841]], [[42841, 42841], "valid"], [[42842, 42842], "mapped", [42843]], [[42843, 42843], "valid"], [[42844, 42844], "mapped", [42845]], [[42845, 42845], "valid"], [[42846, 42846], "mapped", [42847]], [[42847, 42847], "valid"], [[42848, 42848], "mapped", [42849]], [[42849, 42849], "valid"], [[42850, 42850], "mapped", [42851]], [[42851, 42851], "valid"], [[42852, 42852], "mapped", [42853]], [[42853, 42853], "valid"], [[42854, 42854], "mapped", [42855]], [[42855, 42855], "valid"], [[42856, 42856], "mapped", [42857]], [[42857, 42857], "valid"], [[42858, 42858], "mapped", [42859]], [[42859, 42859], "valid"], [[42860, 42860], "mapped", [42861]], [[42861, 42861], "valid"], [[42862, 42862], "mapped", [42863]], [[42863, 42863], "valid"], [[42864, 42864], "mapped", [42863]], [[42865, 42872], "valid"], [[42873, 42873], "mapped", [42874]], [[42874, 42874], "valid"], [[42875, 42875], "mapped", [42876]], [[42876, 42876], "valid"], [[42877, 42877], "mapped", [7545]], [[42878, 42878], "mapped", [42879]], [[42879, 42879], "valid"], [[42880, 42880], "mapped", [42881]], [[42881, 42881], "valid"], [[42882, 42882], "mapped", [42883]], [[42883, 42883], "valid"], [[42884, 42884], "mapped", [42885]], [[42885, 42885], "valid"], [[42886, 42886], "mapped", [42887]], [[42887, 42888], "valid"], [[42889, 42890], "valid", [], "NV8"], [[42891, 42891], "mapped", [42892]], [[42892, 42892], "valid"], [[42893, 42893], "mapped", [613]], [[42894, 42894], "valid"], [[42895, 42895], "valid"], [[42896, 42896], "mapped", [42897]], [[42897, 42897], "valid"], [[42898, 42898], "mapped", [42899]], [[42899, 42899], "valid"], [[42900, 42901], "valid"], [[42902, 42902], "mapped", [42903]], [[42903, 42903], "valid"], [[42904, 42904], "mapped", [42905]], [[42905, 42905], "valid"], [[42906, 42906], "mapped", [42907]], [[42907, 42907], "valid"], [[42908, 42908], "mapped", [42909]], [[42909, 42909], "valid"], [[42910, 42910], "mapped", [42911]], [[42911, 42911], "valid"], [[42912, 42912], "mapped", [42913]], [[42913, 42913], "valid"], [[42914, 42914], "mapped", [42915]], [[42915, 42915], "valid"], [[42916, 42916], "mapped", [42917]], [[42917, 42917], "valid"], [[42918, 42918], "mapped", [42919]], [[42919, 42919], "valid"], [[42920, 42920], "mapped", [42921]], [[42921, 42921], "valid"], [[42922, 42922], "mapped", [614]], [[42923, 42923], "mapped", [604]], [[42924, 42924], "mapped", [609]], [[42925, 42925], "mapped", [620]], [[42926, 42927], "disallowed"], [[42928, 42928], "mapped", [670]], [[42929, 42929], "mapped", [647]], [[42930, 42930], "mapped", [669]], [[42931, 42931], "mapped", [43859]], [[42932, 42932], "mapped", [42933]], [[42933, 42933], "valid"], [[42934, 42934], "mapped", [42935]], [[42935, 42935], "valid"], [[42936, 42998], "disallowed"], [[42999, 42999], "valid"], [[43e3, 43e3], "mapped", [295]], [[43001, 43001], "mapped", [339]], [[43002, 43002], "valid"], [[43003, 43007], "valid"], [[43008, 43047], "valid"], [[43048, 43051], "valid", [], "NV8"], [[43052, 43055], "disallowed"], [[43056, 43065], "valid", [], "NV8"], [[43066, 43071], "disallowed"], [[43072, 43123], "valid"], [[43124, 43127], "valid", [], "NV8"], [[43128, 43135], "disallowed"], [[43136, 43204], "valid"], [[43205, 43213], "disallowed"], [[43214, 43215], "valid", [], "NV8"], [[43216, 43225], "valid"], [[43226, 43231], "disallowed"], [[43232, 43255], "valid"], [[43256, 43258], "valid", [], "NV8"], [[43259, 43259], "valid"], [[43260, 43260], "valid", [], "NV8"], [[43261, 43261], "valid"], [[43262, 43263], "disallowed"], [[43264, 43309], "valid"], [[43310, 43311], "valid", [], "NV8"], [[43312, 43347], "valid"], [[43348, 43358], "disallowed"], [[43359, 43359], "valid", [], "NV8"], [[43360, 43388], "valid", [], "NV8"], [[43389, 43391], "disallowed"], [[43392, 43456], "valid"], [[43457, 43469], "valid", [], "NV8"], [[43470, 43470], "disallowed"], [[43471, 43481], "valid"], [[43482, 43485], "disallowed"], [[43486, 43487], "valid", [], "NV8"], [[43488, 43518], "valid"], [[43519, 43519], "disallowed"], [[43520, 43574], "valid"], [[43575, 43583], "disallowed"], [[43584, 43597], "valid"], [[43598, 43599], "disallowed"], [[43600, 43609], "valid"], [[43610, 43611], "disallowed"], [[43612, 43615], "valid", [], "NV8"], [[43616, 43638], "valid"], [[43639, 43641], "valid", [], "NV8"], [[43642, 43643], "valid"], [[43644, 43647], "valid"], [[43648, 43714], "valid"], [[43715, 43738], "disallowed"], [[43739, 43741], "valid"], [[43742, 43743], "valid", [], "NV8"], [[43744, 43759], "valid"], [[43760, 43761], "valid", [], "NV8"], [[43762, 43766], "valid"], [[43767, 43776], "disallowed"], [[43777, 43782], "valid"], [[43783, 43784], "disallowed"], [[43785, 43790], "valid"], [[43791, 43792], "disallowed"], [[43793, 43798], "valid"], [[43799, 43807], "disallowed"], [[43808, 43814], "valid"], [[43815, 43815], "disallowed"], [[43816, 43822], "valid"], [[43823, 43823], "disallowed"], [[43824, 43866], "valid"], [[43867, 43867], "valid", [], "NV8"], [[43868, 43868], "mapped", [42791]], [[43869, 43869], "mapped", [43831]], [[43870, 43870], "mapped", [619]], [[43871, 43871], "mapped", [43858]], [[43872, 43875], "valid"], [[43876, 43877], "valid"], [[43878, 43887], "disallowed"], [[43888, 43888], "mapped", [5024]], [[43889, 43889], "mapped", [5025]], [[43890, 43890], "mapped", [5026]], [[43891, 43891], "mapped", [5027]], [[43892, 43892], "mapped", [5028]], [[43893, 43893], "mapped", [5029]], [[43894, 43894], "mapped", [5030]], [[43895, 43895], "mapped", [5031]], [[43896, 43896], "mapped", [5032]], [[43897, 43897], "mapped", [5033]], [[43898, 43898], "mapped", [5034]], [[43899, 43899], "mapped", [5035]], [[43900, 43900], "mapped", [5036]], [[43901, 43901], "mapped", [5037]], [[43902, 43902], "mapped", [5038]], [[43903, 43903], "mapped", [5039]], [[43904, 43904], "mapped", [5040]], [[43905, 43905], "mapped", [5041]], [[43906, 43906], "mapped", [5042]], [[43907, 43907], "mapped", [5043]], [[43908, 43908], "mapped", [5044]], [[43909, 43909], "mapped", [5045]], [[43910, 43910], "mapped", [5046]], [[43911, 43911], "mapped", [5047]], [[43912, 43912], "mapped", [5048]], [[43913, 43913], "mapped", [5049]], [[43914, 43914], "mapped", [5050]], [[43915, 43915], "mapped", [5051]], [[43916, 43916], "mapped", [5052]], [[43917, 43917], "mapped", [5053]], [[43918, 43918], "mapped", [5054]], [[43919, 43919], "mapped", [5055]], [[43920, 43920], "mapped", [5056]], [[43921, 43921], "mapped", [5057]], [[43922, 43922], "mapped", [5058]], [[43923, 43923], "mapped", [5059]], [[43924, 43924], "mapped", [5060]], [[43925, 43925], "mapped", [5061]], [[43926, 43926], "mapped", [5062]], [[43927, 43927], "mapped", [5063]], [[43928, 43928], "mapped", [5064]], [[43929, 43929], "mapped", [5065]], [[43930, 43930], "mapped", [5066]], [[43931, 43931], "mapped", [5067]], [[43932, 43932], "mapped", [5068]], [[43933, 43933], "mapped", [5069]], [[43934, 43934], "mapped", [5070]], [[43935, 43935], "mapped", [5071]], [[43936, 43936], "mapped", [5072]], [[43937, 43937], "mapped", [5073]], [[43938, 43938], "mapped", [5074]], [[43939, 43939], "mapped", [5075]], [[43940, 43940], "mapped", [5076]], [[43941, 43941], "mapped", [5077]], [[43942, 43942], "mapped", [5078]], [[43943, 43943], "mapped", [5079]], [[43944, 43944], "mapped", [5080]], [[43945, 43945], "mapped", [5081]], [[43946, 43946], "mapped", [5082]], [[43947, 43947], "mapped", [5083]], [[43948, 43948], "mapped", [5084]], [[43949, 43949], "mapped", [5085]], [[43950, 43950], "mapped", [5086]], [[43951, 43951], "mapped", [5087]], [[43952, 43952], "mapped", [5088]], [[43953, 43953], "mapped", [5089]], [[43954, 43954], "mapped", [5090]], [[43955, 43955], "mapped", [5091]], [[43956, 43956], "mapped", [5092]], [[43957, 43957], "mapped", [5093]], [[43958, 43958], "mapped", [5094]], [[43959, 43959], "mapped", [5095]], [[43960, 43960], "mapped", [5096]], [[43961, 43961], "mapped", [5097]], [[43962, 43962], "mapped", [5098]], [[43963, 43963], "mapped", [5099]], [[43964, 43964], "mapped", [5100]], [[43965, 43965], "mapped", [5101]], [[43966, 43966], "mapped", [5102]], [[43967, 43967], "mapped", [5103]], [[43968, 44010], "valid"], [[44011, 44011], "valid", [], "NV8"], [[44012, 44013], "valid"], [[44014, 44015], "disallowed"], [[44016, 44025], "valid"], [[44026, 44031], "disallowed"], [[44032, 55203], "valid"], [[55204, 55215], "disallowed"], [[55216, 55238], "valid", [], "NV8"], [[55239, 55242], "disallowed"], [[55243, 55291], "valid", [], "NV8"], [[55292, 55295], "disallowed"], [[55296, 57343], "disallowed"], [[57344, 63743], "disallowed"], [[63744, 63744], "mapped", [35912]], [[63745, 63745], "mapped", [26356]], [[63746, 63746], "mapped", [36554]], [[63747, 63747], "mapped", [36040]], [[63748, 63748], "mapped", [28369]], [[63749, 63749], "mapped", [20018]], [[63750, 63750], "mapped", [21477]], [[63751, 63752], "mapped", [40860]], [[63753, 63753], "mapped", [22865]], [[63754, 63754], "mapped", [37329]], [[63755, 63755], "mapped", [21895]], [[63756, 63756], "mapped", [22856]], [[63757, 63757], "mapped", [25078]], [[63758, 63758], "mapped", [30313]], [[63759, 63759], "mapped", [32645]], [[63760, 63760], "mapped", [34367]], [[63761, 63761], "mapped", [34746]], [[63762, 63762], "mapped", [35064]], [[63763, 63763], "mapped", [37007]], [[63764, 63764], "mapped", [27138]], [[63765, 63765], "mapped", [27931]], [[63766, 63766], "mapped", [28889]], [[63767, 63767], "mapped", [29662]], [[63768, 63768], "mapped", [33853]], [[63769, 63769], "mapped", [37226]], [[63770, 63770], "mapped", [39409]], [[63771, 63771], "mapped", [20098]], [[63772, 63772], "mapped", [21365]], [[63773, 63773], "mapped", [27396]], [[63774, 63774], "mapped", [29211]], [[63775, 63775], "mapped", [34349]], [[63776, 63776], "mapped", [40478]], [[63777, 63777], "mapped", [23888]], [[63778, 63778], "mapped", [28651]], [[63779, 63779], "mapped", [34253]], [[63780, 63780], "mapped", [35172]], [[63781, 63781], "mapped", [25289]], [[63782, 63782], "mapped", [33240]], [[63783, 63783], "mapped", [34847]], [[63784, 63784], "mapped", [24266]], [[63785, 63785], "mapped", [26391]], [[63786, 63786], "mapped", [28010]], [[63787, 63787], "mapped", [29436]], [[63788, 63788], "mapped", [37070]], [[63789, 63789], "mapped", [20358]], [[63790, 63790], "mapped", [20919]], [[63791, 63791], "mapped", [21214]], [[63792, 63792], "mapped", [25796]], [[63793, 63793], "mapped", [27347]], [[63794, 63794], "mapped", [29200]], [[63795, 63795], "mapped", [30439]], [[63796, 63796], "mapped", [32769]], [[63797, 63797], "mapped", [34310]], [[63798, 63798], "mapped", [34396]], [[63799, 63799], "mapped", [36335]], [[63800, 63800], "mapped", [38706]], [[63801, 63801], "mapped", [39791]], [[63802, 63802], "mapped", [40442]], [[63803, 63803], "mapped", [30860]], [[63804, 63804], "mapped", [31103]], [[63805, 63805], "mapped", [32160]], [[63806, 63806], "mapped", [33737]], [[63807, 63807], "mapped", [37636]], [[63808, 63808], "mapped", [40575]], [[63809, 63809], "mapped", [35542]], [[63810, 63810], "mapped", [22751]], [[63811, 63811], "mapped", [24324]], [[63812, 63812], "mapped", [31840]], [[63813, 63813], "mapped", [32894]], [[63814, 63814], "mapped", [29282]], [[63815, 63815], "mapped", [30922]], [[63816, 63816], "mapped", [36034]], [[63817, 63817], "mapped", [38647]], [[63818, 63818], "mapped", [22744]], [[63819, 63819], "mapped", [23650]], [[63820, 63820], "mapped", [27155]], [[63821, 63821], "mapped", [28122]], [[63822, 63822], "mapped", [28431]], [[63823, 63823], "mapped", [32047]], [[63824, 63824], "mapped", [32311]], [[63825, 63825], "mapped", [38475]], [[63826, 63826], "mapped", [21202]], [[63827, 63827], "mapped", [32907]], [[63828, 63828], "mapped", [20956]], [[63829, 63829], "mapped", [20940]], [[63830, 63830], "mapped", [31260]], [[63831, 63831], "mapped", [32190]], [[63832, 63832], "mapped", [33777]], [[63833, 63833], "mapped", [38517]], [[63834, 63834], "mapped", [35712]], [[63835, 63835], "mapped", [25295]], [[63836, 63836], "mapped", [27138]], [[63837, 63837], "mapped", [35582]], [[63838, 63838], "mapped", [20025]], [[63839, 63839], "mapped", [23527]], [[63840, 63840], "mapped", [24594]], [[63841, 63841], "mapped", [29575]], [[63842, 63842], "mapped", [30064]], [[63843, 63843], "mapped", [21271]], [[63844, 63844], "mapped", [30971]], [[63845, 63845], "mapped", [20415]], [[63846, 63846], "mapped", [24489]], [[63847, 63847], "mapped", [19981]], [[63848, 63848], "mapped", [27852]], [[63849, 63849], "mapped", [25976]], [[63850, 63850], "mapped", [32034]], [[63851, 63851], "mapped", [21443]], [[63852, 63852], "mapped", [22622]], [[63853, 63853], "mapped", [30465]], [[63854, 63854], "mapped", [33865]], [[63855, 63855], "mapped", [35498]], [[63856, 63856], "mapped", [27578]], [[63857, 63857], "mapped", [36784]], [[63858, 63858], "mapped", [27784]], [[63859, 63859], "mapped", [25342]], [[63860, 63860], "mapped", [33509]], [[63861, 63861], "mapped", [25504]], [[63862, 63862], "mapped", [30053]], [[63863, 63863], "mapped", [20142]], [[63864, 63864], "mapped", [20841]], [[63865, 63865], "mapped", [20937]], [[63866, 63866], "mapped", [26753]], [[63867, 63867], "mapped", [31975]], [[63868, 63868], "mapped", [33391]], [[63869, 63869], "mapped", [35538]], [[63870, 63870], "mapped", [37327]], [[63871, 63871], "mapped", [21237]], [[63872, 63872], "mapped", [21570]], [[63873, 63873], "mapped", [22899]], [[63874, 63874], "mapped", [24300]], [[63875, 63875], "mapped", [26053]], [[63876, 63876], "mapped", [28670]], [[63877, 63877], "mapped", [31018]], [[63878, 63878], "mapped", [38317]], [[63879, 63879], "mapped", [39530]], [[63880, 63880], "mapped", [40599]], [[63881, 63881], "mapped", [40654]], [[63882, 63882], "mapped", [21147]], [[63883, 63883], "mapped", [26310]], [[63884, 63884], "mapped", [27511]], [[63885, 63885], "mapped", [36706]], [[63886, 63886], "mapped", [24180]], [[63887, 63887], "mapped", [24976]], [[63888, 63888], "mapped", [25088]], [[63889, 63889], "mapped", [25754]], [[63890, 63890], "mapped", [28451]], [[63891, 63891], "mapped", [29001]], [[63892, 63892], "mapped", [29833]], [[63893, 63893], "mapped", [31178]], [[63894, 63894], "mapped", [32244]], [[63895, 63895], "mapped", [32879]], [[63896, 63896], "mapped", [36646]], [[63897, 63897], "mapped", [34030]], [[63898, 63898], "mapped", [36899]], [[63899, 63899], "mapped", [37706]], [[63900, 63900], "mapped", [21015]], [[63901, 63901], "mapped", [21155]], [[63902, 63902], "mapped", [21693]], [[63903, 63903], "mapped", [28872]], [[63904, 63904], "mapped", [35010]], [[63905, 63905], "mapped", [35498]], [[63906, 63906], "mapped", [24265]], [[63907, 63907], "mapped", [24565]], [[63908, 63908], "mapped", [25467]], [[63909, 63909], "mapped", [27566]], [[63910, 63910], "mapped", [31806]], [[63911, 63911], "mapped", [29557]], [[63912, 63912], "mapped", [20196]], [[63913, 63913], "mapped", [22265]], [[63914, 63914], "mapped", [23527]], [[63915, 63915], "mapped", [23994]], [[63916, 63916], "mapped", [24604]], [[63917, 63917], "mapped", [29618]], [[63918, 63918], "mapped", [29801]], [[63919, 63919], "mapped", [32666]], [[63920, 63920], "mapped", [32838]], [[63921, 63921], "mapped", [37428]], [[63922, 63922], "mapped", [38646]], [[63923, 63923], "mapped", [38728]], [[63924, 63924], "mapped", [38936]], [[63925, 63925], "mapped", [20363]], [[63926, 63926], "mapped", [31150]], [[63927, 63927], "mapped", [37300]], [[63928, 63928], "mapped", [38584]], [[63929, 63929], "mapped", [24801]], [[63930, 63930], "mapped", [20102]], [[63931, 63931], "mapped", [20698]], [[63932, 63932], "mapped", [23534]], [[63933, 63933], "mapped", [23615]], [[63934, 63934], "mapped", [26009]], [[63935, 63935], "mapped", [27138]], [[63936, 63936], "mapped", [29134]], [[63937, 63937], "mapped", [30274]], [[63938, 63938], "mapped", [34044]], [[63939, 63939], "mapped", [36988]], [[63940, 63940], "mapped", [40845]], [[63941, 63941], "mapped", [26248]], [[63942, 63942], "mapped", [38446]], [[63943, 63943], "mapped", [21129]], [[63944, 63944], "mapped", [26491]], [[63945, 63945], "mapped", [26611]], [[63946, 63946], "mapped", [27969]], [[63947, 63947], "mapped", [28316]], [[63948, 63948], "mapped", [29705]], [[63949, 63949], "mapped", [30041]], [[63950, 63950], "mapped", [30827]], [[63951, 63951], "mapped", [32016]], [[63952, 63952], "mapped", [39006]], [[63953, 63953], "mapped", [20845]], [[63954, 63954], "mapped", [25134]], [[63955, 63955], "mapped", [38520]], [[63956, 63956], "mapped", [20523]], [[63957, 63957], "mapped", [23833]], [[63958, 63958], "mapped", [28138]], [[63959, 63959], "mapped", [36650]], [[63960, 63960], "mapped", [24459]], [[63961, 63961], "mapped", [24900]], [[63962, 63962], "mapped", [26647]], [[63963, 63963], "mapped", [29575]], [[63964, 63964], "mapped", [38534]], [[63965, 63965], "mapped", [21033]], [[63966, 63966], "mapped", [21519]], [[63967, 63967], "mapped", [23653]], [[63968, 63968], "mapped", [26131]], [[63969, 63969], "mapped", [26446]], [[63970, 63970], "mapped", [26792]], [[63971, 63971], "mapped", [27877]], [[63972, 63972], "mapped", [29702]], [[63973, 63973], "mapped", [30178]], [[63974, 63974], "mapped", [32633]], [[63975, 63975], "mapped", [35023]], [[63976, 63976], "mapped", [35041]], [[63977, 63977], "mapped", [37324]], [[63978, 63978], "mapped", [38626]], [[63979, 63979], "mapped", [21311]], [[63980, 63980], "mapped", [28346]], [[63981, 63981], "mapped", [21533]], [[63982, 63982], "mapped", [29136]], [[63983, 63983], "mapped", [29848]], [[63984, 63984], "mapped", [34298]], [[63985, 63985], "mapped", [38563]], [[63986, 63986], "mapped", [40023]], [[63987, 63987], "mapped", [40607]], [[63988, 63988], "mapped", [26519]], [[63989, 63989], "mapped", [28107]], [[63990, 63990], "mapped", [33256]], [[63991, 63991], "mapped", [31435]], [[63992, 63992], "mapped", [31520]], [[63993, 63993], "mapped", [31890]], [[63994, 63994], "mapped", [29376]], [[63995, 63995], "mapped", [28825]], [[63996, 63996], "mapped", [35672]], [[63997, 63997], "mapped", [20160]], [[63998, 63998], "mapped", [33590]], [[63999, 63999], "mapped", [21050]], [[64e3, 64e3], "mapped", [20999]], [[64001, 64001], "mapped", [24230]], [[64002, 64002], "mapped", [25299]], [[64003, 64003], "mapped", [31958]], [[64004, 64004], "mapped", [23429]], [[64005, 64005], "mapped", [27934]], [[64006, 64006], "mapped", [26292]], [[64007, 64007], "mapped", [36667]], [[64008, 64008], "mapped", [34892]], [[64009, 64009], "mapped", [38477]], [[64010, 64010], "mapped", [35211]], [[64011, 64011], "mapped", [24275]], [[64012, 64012], "mapped", [20800]], [[64013, 64013], "mapped", [21952]], [[64014, 64015], "valid"], [[64016, 64016], "mapped", [22618]], [[64017, 64017], "valid"], [[64018, 64018], "mapped", [26228]], [[64019, 64020], "valid"], [[64021, 64021], "mapped", [20958]], [[64022, 64022], "mapped", [29482]], [[64023, 64023], "mapped", [30410]], [[64024, 64024], "mapped", [31036]], [[64025, 64025], "mapped", [31070]], [[64026, 64026], "mapped", [31077]], [[64027, 64027], "mapped", [31119]], [[64028, 64028], "mapped", [38742]], [[64029, 64029], "mapped", [31934]], [[64030, 64030], "mapped", [32701]], [[64031, 64031], "valid"], [[64032, 64032], "mapped", [34322]], [[64033, 64033], "valid"], [[64034, 64034], "mapped", [35576]], [[64035, 64036], "valid"], [[64037, 64037], "mapped", [36920]], [[64038, 64038], "mapped", [37117]], [[64039, 64041], "valid"], [[64042, 64042], "mapped", [39151]], [[64043, 64043], "mapped", [39164]], [[64044, 64044], "mapped", [39208]], [[64045, 64045], "mapped", [40372]], [[64046, 64046], "mapped", [37086]], [[64047, 64047], "mapped", [38583]], [[64048, 64048], "mapped", [20398]], [[64049, 64049], "mapped", [20711]], [[64050, 64050], "mapped", [20813]], [[64051, 64051], "mapped", [21193]], [[64052, 64052], "mapped", [21220]], [[64053, 64053], "mapped", [21329]], [[64054, 64054], "mapped", [21917]], [[64055, 64055], "mapped", [22022]], [[64056, 64056], "mapped", [22120]], [[64057, 64057], "mapped", [22592]], [[64058, 64058], "mapped", [22696]], [[64059, 64059], "mapped", [23652]], [[64060, 64060], "mapped", [23662]], [[64061, 64061], "mapped", [24724]], [[64062, 64062], "mapped", [24936]], [[64063, 64063], "mapped", [24974]], [[64064, 64064], "mapped", [25074]], [[64065, 64065], "mapped", [25935]], [[64066, 64066], "mapped", [26082]], [[64067, 64067], "mapped", [26257]], [[64068, 64068], "mapped", [26757]], [[64069, 64069], "mapped", [28023]], [[64070, 64070], "mapped", [28186]], [[64071, 64071], "mapped", [28450]], [[64072, 64072], "mapped", [29038]], [[64073, 64073], "mapped", [29227]], [[64074, 64074], "mapped", [29730]], [[64075, 64075], "mapped", [30865]], [[64076, 64076], "mapped", [31038]], [[64077, 64077], "mapped", [31049]], [[64078, 64078], "mapped", [31048]], [[64079, 64079], "mapped", [31056]], [[64080, 64080], "mapped", [31062]], [[64081, 64081], "mapped", [31069]], [[64082, 64082], "mapped", [31117]], [[64083, 64083], "mapped", [31118]], [[64084, 64084], "mapped", [31296]], [[64085, 64085], "mapped", [31361]], [[64086, 64086], "mapped", [31680]], [[64087, 64087], "mapped", [32244]], [[64088, 64088], "mapped", [32265]], [[64089, 64089], "mapped", [32321]], [[64090, 64090], "mapped", [32626]], [[64091, 64091], "mapped", [32773]], [[64092, 64092], "mapped", [33261]], [[64093, 64094], "mapped", [33401]], [[64095, 64095], "mapped", [33879]], [[64096, 64096], "mapped", [35088]], [[64097, 64097], "mapped", [35222]], [[64098, 64098], "mapped", [35585]], [[64099, 64099], "mapped", [35641]], [[64100, 64100], "mapped", [36051]], [[64101, 64101], "mapped", [36104]], [[64102, 64102], "mapped", [36790]], [[64103, 64103], "mapped", [36920]], [[64104, 64104], "mapped", [38627]], [[64105, 64105], "mapped", [38911]], [[64106, 64106], "mapped", [38971]], [[64107, 64107], "mapped", [24693]], [[64108, 64108], "mapped", [148206]], [[64109, 64109], "mapped", [33304]], [[64110, 64111], "disallowed"], [[64112, 64112], "mapped", [20006]], [[64113, 64113], "mapped", [20917]], [[64114, 64114], "mapped", [20840]], [[64115, 64115], "mapped", [20352]], [[64116, 64116], "mapped", [20805]], [[64117, 64117], "mapped", [20864]], [[64118, 64118], "mapped", [21191]], [[64119, 64119], "mapped", [21242]], [[64120, 64120], "mapped", [21917]], [[64121, 64121], "mapped", [21845]], [[64122, 64122], "mapped", [21913]], [[64123, 64123], "mapped", [21986]], [[64124, 64124], "mapped", [22618]], [[64125, 64125], "mapped", [22707]], [[64126, 64126], "mapped", [22852]], [[64127, 64127], "mapped", [22868]], [[64128, 64128], "mapped", [23138]], [[64129, 64129], "mapped", [23336]], [[64130, 64130], "mapped", [24274]], [[64131, 64131], "mapped", [24281]], [[64132, 64132], "mapped", [24425]], [[64133, 64133], "mapped", [24493]], [[64134, 64134], "mapped", [24792]], [[64135, 64135], "mapped", [24910]], [[64136, 64136], "mapped", [24840]], [[64137, 64137], "mapped", [24974]], [[64138, 64138], "mapped", [24928]], [[64139, 64139], "mapped", [25074]], [[64140, 64140], "mapped", [25140]], [[64141, 64141], "mapped", [25540]], [[64142, 64142], "mapped", [25628]], [[64143, 64143], "mapped", [25682]], [[64144, 64144], "mapped", [25942]], [[64145, 64145], "mapped", [26228]], [[64146, 64146], "mapped", [26391]], [[64147, 64147], "mapped", [26395]], [[64148, 64148], "mapped", [26454]], [[64149, 64149], "mapped", [27513]], [[64150, 64150], "mapped", [27578]], [[64151, 64151], "mapped", [27969]], [[64152, 64152], "mapped", [28379]], [[64153, 64153], "mapped", [28363]], [[64154, 64154], "mapped", [28450]], [[64155, 64155], "mapped", [28702]], [[64156, 64156], "mapped", [29038]], [[64157, 64157], "mapped", [30631]], [[64158, 64158], "mapped", [29237]], [[64159, 64159], "mapped", [29359]], [[64160, 64160], "mapped", [29482]], [[64161, 64161], "mapped", [29809]], [[64162, 64162], "mapped", [29958]], [[64163, 64163], "mapped", [30011]], [[64164, 64164], "mapped", [30237]], [[64165, 64165], "mapped", [30239]], [[64166, 64166], "mapped", [30410]], [[64167, 64167], "mapped", [30427]], [[64168, 64168], "mapped", [30452]], [[64169, 64169], "mapped", [30538]], [[64170, 64170], "mapped", [30528]], [[64171, 64171], "mapped", [30924]], [[64172, 64172], "mapped", [31409]], [[64173, 64173], "mapped", [31680]], [[64174, 64174], "mapped", [31867]], [[64175, 64175], "mapped", [32091]], [[64176, 64176], "mapped", [32244]], [[64177, 64177], "mapped", [32574]], [[64178, 64178], "mapped", [32773]], [[64179, 64179], "mapped", [33618]], [[64180, 64180], "mapped", [33775]], [[64181, 64181], "mapped", [34681]], [[64182, 64182], "mapped", [35137]], [[64183, 64183], "mapped", [35206]], [[64184, 64184], "mapped", [35222]], [[64185, 64185], "mapped", [35519]], [[64186, 64186], "mapped", [35576]], [[64187, 64187], "mapped", [35531]], [[64188, 64188], "mapped", [35585]], [[64189, 64189], "mapped", [35582]], [[64190, 64190], "mapped", [35565]], [[64191, 64191], "mapped", [35641]], [[64192, 64192], "mapped", [35722]], [[64193, 64193], "mapped", [36104]], [[64194, 64194], "mapped", [36664]], [[64195, 64195], "mapped", [36978]], [[64196, 64196], "mapped", [37273]], [[64197, 64197], "mapped", [37494]], [[64198, 64198], "mapped", [38524]], [[64199, 64199], "mapped", [38627]], [[64200, 64200], "mapped", [38742]], [[64201, 64201], "mapped", [38875]], [[64202, 64202], "mapped", [38911]], [[64203, 64203], "mapped", [38923]], [[64204, 64204], "mapped", [38971]], [[64205, 64205], "mapped", [39698]], [[64206, 64206], "mapped", [40860]], [[64207, 64207], "mapped", [141386]], [[64208, 64208], "mapped", [141380]], [[64209, 64209], "mapped", [144341]], [[64210, 64210], "mapped", [15261]], [[64211, 64211], "mapped", [16408]], [[64212, 64212], "mapped", [16441]], [[64213, 64213], "mapped", [152137]], [[64214, 64214], "mapped", [154832]], [[64215, 64215], "mapped", [163539]], [[64216, 64216], "mapped", [40771]], [[64217, 64217], "mapped", [40846]], [[64218, 64255], "disallowed"], [[64256, 64256], "mapped", [102, 102]], [[64257, 64257], "mapped", [102, 105]], [[64258, 64258], "mapped", [102, 108]], [[64259, 64259], "mapped", [102, 102, 105]], [[64260, 64260], "mapped", [102, 102, 108]], [[64261, 64262], "mapped", [115, 116]], [[64263, 64274], "disallowed"], [[64275, 64275], "mapped", [1396, 1398]], [[64276, 64276], "mapped", [1396, 1381]], [[64277, 64277], "mapped", [1396, 1387]], [[64278, 64278], "mapped", [1406, 1398]], [[64279, 64279], "mapped", [1396, 1389]], [[64280, 64284], "disallowed"], [[64285, 64285], "mapped", [1497, 1460]], [[64286, 64286], "valid"], [[64287, 64287], "mapped", [1522, 1463]], [[64288, 64288], "mapped", [1506]], [[64289, 64289], "mapped", [1488]], [[64290, 64290], "mapped", [1491]], [[64291, 64291], "mapped", [1492]], [[64292, 64292], "mapped", [1499]], [[64293, 64293], "mapped", [1500]], [[64294, 64294], "mapped", [1501]], [[64295, 64295], "mapped", [1512]], [[64296, 64296], "mapped", [1514]], [[64297, 64297], "disallowed_STD3_mapped", [43]], [[64298, 64298], "mapped", [1513, 1473]], [[64299, 64299], "mapped", [1513, 1474]], [[64300, 64300], "mapped", [1513, 1468, 1473]], [[64301, 64301], "mapped", [1513, 1468, 1474]], [[64302, 64302], "mapped", [1488, 1463]], [[64303, 64303], "mapped", [1488, 1464]], [[64304, 64304], "mapped", [1488, 1468]], [[64305, 64305], "mapped", [1489, 1468]], [[64306, 64306], "mapped", [1490, 1468]], [[64307, 64307], "mapped", [1491, 1468]], [[64308, 64308], "mapped", [1492, 1468]], [[64309, 64309], "mapped", [1493, 1468]], [[64310, 64310], "mapped", [1494, 1468]], [[64311, 64311], "disallowed"], [[64312, 64312], "mapped", [1496, 1468]], [[64313, 64313], "mapped", [1497, 1468]], [[64314, 64314], "mapped", [1498, 1468]], [[64315, 64315], "mapped", [1499, 1468]], [[64316, 64316], "mapped", [1500, 1468]], [[64317, 64317], "disallowed"], [[64318, 64318], "mapped", [1502, 1468]], [[64319, 64319], "disallowed"], [[64320, 64320], "mapped", [1504, 1468]], [[64321, 64321], "mapped", [1505, 1468]], [[64322, 64322], "disallowed"], [[64323, 64323], "mapped", [1507, 1468]], [[64324, 64324], "mapped", [1508, 1468]], [[64325, 64325], "disallowed"], [[64326, 64326], "mapped", [1510, 1468]], [[64327, 64327], "mapped", [1511, 1468]], [[64328, 64328], "mapped", [1512, 1468]], [[64329, 64329], "mapped", [1513, 1468]], [[64330, 64330], "mapped", [1514, 1468]], [[64331, 64331], "mapped", [1493, 1465]], [[64332, 64332], "mapped", [1489, 1471]], [[64333, 64333], "mapped", [1499, 1471]], [[64334, 64334], "mapped", [1508, 1471]], [[64335, 64335], "mapped", [1488, 1500]], [[64336, 64337], "mapped", [1649]], [[64338, 64341], "mapped", [1659]], [[64342, 64345], "mapped", [1662]], [[64346, 64349], "mapped", [1664]], [[64350, 64353], "mapped", [1658]], [[64354, 64357], "mapped", [1663]], [[64358, 64361], "mapped", [1657]], [[64362, 64365], "mapped", [1700]], [[64366, 64369], "mapped", [1702]], [[64370, 64373], "mapped", [1668]], [[64374, 64377], "mapped", [1667]], [[64378, 64381], "mapped", [1670]], [[64382, 64385], "mapped", [1671]], [[64386, 64387], "mapped", [1677]], [[64388, 64389], "mapped", [1676]], [[64390, 64391], "mapped", [1678]], [[64392, 64393], "mapped", [1672]], [[64394, 64395], "mapped", [1688]], [[64396, 64397], "mapped", [1681]], [[64398, 64401], "mapped", [1705]], [[64402, 64405], "mapped", [1711]], [[64406, 64409], "mapped", [1715]], [[64410, 64413], "mapped", [1713]], [[64414, 64415], "mapped", [1722]], [[64416, 64419], "mapped", [1723]], [[64420, 64421], "mapped", [1728]], [[64422, 64425], "mapped", [1729]], [[64426, 64429], "mapped", [1726]], [[64430, 64431], "mapped", [1746]], [[64432, 64433], "mapped", [1747]], [[64434, 64449], "valid", [], "NV8"], [[64450, 64466], "disallowed"], [[64467, 64470], "mapped", [1709]], [[64471, 64472], "mapped", [1735]], [[64473, 64474], "mapped", [1734]], [[64475, 64476], "mapped", [1736]], [[64477, 64477], "mapped", [1735, 1652]], [[64478, 64479], "mapped", [1739]], [[64480, 64481], "mapped", [1733]], [[64482, 64483], "mapped", [1737]], [[64484, 64487], "mapped", [1744]], [[64488, 64489], "mapped", [1609]], [[64490, 64491], "mapped", [1574, 1575]], [[64492, 64493], "mapped", [1574, 1749]], [[64494, 64495], "mapped", [1574, 1608]], [[64496, 64497], "mapped", [1574, 1735]], [[64498, 64499], "mapped", [1574, 1734]], [[64500, 64501], "mapped", [1574, 1736]], [[64502, 64504], "mapped", [1574, 1744]], [[64505, 64507], "mapped", [1574, 1609]], [[64508, 64511], "mapped", [1740]], [[64512, 64512], "mapped", [1574, 1580]], [[64513, 64513], "mapped", [1574, 1581]], [[64514, 64514], "mapped", [1574, 1605]], [[64515, 64515], "mapped", [1574, 1609]], [[64516, 64516], "mapped", [1574, 1610]], [[64517, 64517], "mapped", [1576, 1580]], [[64518, 64518], "mapped", [1576, 1581]], [[64519, 64519], "mapped", [1576, 1582]], [[64520, 64520], "mapped", [1576, 1605]], [[64521, 64521], "mapped", [1576, 1609]], [[64522, 64522], "mapped", [1576, 1610]], [[64523, 64523], "mapped", [1578, 1580]], [[64524, 64524], "mapped", [1578, 1581]], [[64525, 64525], "mapped", [1578, 1582]], [[64526, 64526], "mapped", [1578, 1605]], [[64527, 64527], "mapped", [1578, 1609]], [[64528, 64528], "mapped", [1578, 1610]], [[64529, 64529], "mapped", [1579, 1580]], [[64530, 64530], "mapped", [1579, 1605]], [[64531, 64531], "mapped", [1579, 1609]], [[64532, 64532], "mapped", [1579, 1610]], [[64533, 64533], "mapped", [1580, 1581]], [[64534, 64534], "mapped", [1580, 1605]], [[64535, 64535], "mapped", [1581, 1580]], [[64536, 64536], "mapped", [1581, 1605]], [[64537, 64537], "mapped", [1582, 1580]], [[64538, 64538], "mapped", [1582, 1581]], [[64539, 64539], "mapped", [1582, 1605]], [[64540, 64540], "mapped", [1587, 1580]], [[64541, 64541], "mapped", [1587, 1581]], [[64542, 64542], "mapped", [1587, 1582]], [[64543, 64543], "mapped", [1587, 1605]], [[64544, 64544], "mapped", [1589, 1581]], [[64545, 64545], "mapped", [1589, 1605]], [[64546, 64546], "mapped", [1590, 1580]], [[64547, 64547], "mapped", [1590, 1581]], [[64548, 64548], "mapped", [1590, 1582]], [[64549, 64549], "mapped", [1590, 1605]], [[64550, 64550], "mapped", [1591, 1581]], [[64551, 64551], "mapped", [1591, 1605]], [[64552, 64552], "mapped", [1592, 1605]], [[64553, 64553], "mapped", [1593, 1580]], [[64554, 64554], "mapped", [1593, 1605]], [[64555, 64555], "mapped", [1594, 1580]], [[64556, 64556], "mapped", [1594, 1605]], [[64557, 64557], "mapped", [1601, 1580]], [[64558, 64558], "mapped", [1601, 1581]], [[64559, 64559], "mapped", [1601, 1582]], [[64560, 64560], "mapped", [1601, 1605]], [[64561, 64561], "mapped", [1601, 1609]], [[64562, 64562], "mapped", [1601, 1610]], [[64563, 64563], "mapped", [1602, 1581]], [[64564, 64564], "mapped", [1602, 1605]], [[64565, 64565], "mapped", [1602, 1609]], [[64566, 64566], "mapped", [1602, 1610]], [[64567, 64567], "mapped", [1603, 1575]], [[64568, 64568], "mapped", [1603, 1580]], [[64569, 64569], "mapped", [1603, 1581]], [[64570, 64570], "mapped", [1603, 1582]], [[64571, 64571], "mapped", [1603, 1604]], [[64572, 64572], "mapped", [1603, 1605]], [[64573, 64573], "mapped", [1603, 1609]], [[64574, 64574], "mapped", [1603, 1610]], [[64575, 64575], "mapped", [1604, 1580]], [[64576, 64576], "mapped", [1604, 1581]], [[64577, 64577], "mapped", [1604, 1582]], [[64578, 64578], "mapped", [1604, 1605]], [[64579, 64579], "mapped", [1604, 1609]], [[64580, 64580], "mapped", [1604, 1610]], [[64581, 64581], "mapped", [1605, 1580]], [[64582, 64582], "mapped", [1605, 1581]], [[64583, 64583], "mapped", [1605, 1582]], [[64584, 64584], "mapped", [1605, 1605]], [[64585, 64585], "mapped", [1605, 1609]], [[64586, 64586], "mapped", [1605, 1610]], [[64587, 64587], "mapped", [1606, 1580]], [[64588, 64588], "mapped", [1606, 1581]], [[64589, 64589], "mapped", [1606, 1582]], [[64590, 64590], "mapped", [1606, 1605]], [[64591, 64591], "mapped", [1606, 1609]], [[64592, 64592], "mapped", [1606, 1610]], [[64593, 64593], "mapped", [1607, 1580]], [[64594, 64594], "mapped", [1607, 1605]], [[64595, 64595], "mapped", [1607, 1609]], [[64596, 64596], "mapped", [1607, 1610]], [[64597, 64597], "mapped", [1610, 1580]], [[64598, 64598], "mapped", [1610, 1581]], [[64599, 64599], "mapped", [1610, 1582]], [[64600, 64600], "mapped", [1610, 1605]], [[64601, 64601], "mapped", [1610, 1609]], [[64602, 64602], "mapped", [1610, 1610]], [[64603, 64603], "mapped", [1584, 1648]], [[64604, 64604], "mapped", [1585, 1648]], [[64605, 64605], "mapped", [1609, 1648]], [[64606, 64606], "disallowed_STD3_mapped", [32, 1612, 1617]], [[64607, 64607], "disallowed_STD3_mapped", [32, 1613, 1617]], [[64608, 64608], "disallowed_STD3_mapped", [32, 1614, 1617]], [[64609, 64609], "disallowed_STD3_mapped", [32, 1615, 1617]], [[64610, 64610], "disallowed_STD3_mapped", [32, 1616, 1617]], [[64611, 64611], "disallowed_STD3_mapped", [32, 1617, 1648]], [[64612, 64612], "mapped", [1574, 1585]], [[64613, 64613], "mapped", [1574, 1586]], [[64614, 64614], "mapped", [1574, 1605]], [[64615, 64615], "mapped", [1574, 1606]], [[64616, 64616], "mapped", [1574, 1609]], [[64617, 64617], "mapped", [1574, 1610]], [[64618, 64618], "mapped", [1576, 1585]], [[64619, 64619], "mapped", [1576, 1586]], [[64620, 64620], "mapped", [1576, 1605]], [[64621, 64621], "mapped", [1576, 1606]], [[64622, 64622], "mapped", [1576, 1609]], [[64623, 64623], "mapped", [1576, 1610]], [[64624, 64624], "mapped", [1578, 1585]], [[64625, 64625], "mapped", [1578, 1586]], [[64626, 64626], "mapped", [1578, 1605]], [[64627, 64627], "mapped", [1578, 1606]], [[64628, 64628], "mapped", [1578, 1609]], [[64629, 64629], "mapped", [1578, 1610]], [[64630, 64630], "mapped", [1579, 1585]], [[64631, 64631], "mapped", [1579, 1586]], [[64632, 64632], "mapped", [1579, 1605]], [[64633, 64633], "mapped", [1579, 1606]], [[64634, 64634], "mapped", [1579, 1609]], [[64635, 64635], "mapped", [1579, 1610]], [[64636, 64636], "mapped", [1601, 1609]], [[64637, 64637], "mapped", [1601, 1610]], [[64638, 64638], "mapped", [1602, 1609]], [[64639, 64639], "mapped", [1602, 1610]], [[64640, 64640], "mapped", [1603, 1575]], [[64641, 64641], "mapped", [1603, 1604]], [[64642, 64642], "mapped", [1603, 1605]], [[64643, 64643], "mapped", [1603, 1609]], [[64644, 64644], "mapped", [1603, 1610]], [[64645, 64645], "mapped", [1604, 1605]], [[64646, 64646], "mapped", [1604, 1609]], [[64647, 64647], "mapped", [1604, 1610]], [[64648, 64648], "mapped", [1605, 1575]], [[64649, 64649], "mapped", [1605, 1605]], [[64650, 64650], "mapped", [1606, 1585]], [[64651, 64651], "mapped", [1606, 1586]], [[64652, 64652], "mapped", [1606, 1605]], [[64653, 64653], "mapped", [1606, 1606]], [[64654, 64654], "mapped", [1606, 1609]], [[64655, 64655], "mapped", [1606, 1610]], [[64656, 64656], "mapped", [1609, 1648]], [[64657, 64657], "mapped", [1610, 1585]], [[64658, 64658], "mapped", [1610, 1586]], [[64659, 64659], "mapped", [1610, 1605]], [[64660, 64660], "mapped", [1610, 1606]], [[64661, 64661], "mapped", [1610, 1609]], [[64662, 64662], "mapped", [1610, 1610]], [[64663, 64663], "mapped", [1574, 1580]], [[64664, 64664], "mapped", [1574, 1581]], [[64665, 64665], "mapped", [1574, 1582]], [[64666, 64666], "mapped", [1574, 1605]], [[64667, 64667], "mapped", [1574, 1607]], [[64668, 64668], "mapped", [1576, 1580]], [[64669, 64669], "mapped", [1576, 1581]], [[64670, 64670], "mapped", [1576, 1582]], [[64671, 64671], "mapped", [1576, 1605]], [[64672, 64672], "mapped", [1576, 1607]], [[64673, 64673], "mapped", [1578, 1580]], [[64674, 64674], "mapped", [1578, 1581]], [[64675, 64675], "mapped", [1578, 1582]], [[64676, 64676], "mapped", [1578, 1605]], [[64677, 64677], "mapped", [1578, 1607]], [[64678, 64678], "mapped", [1579, 1605]], [[64679, 64679], "mapped", [1580, 1581]], [[64680, 64680], "mapped", [1580, 1605]], [[64681, 64681], "mapped", [1581, 1580]], [[64682, 64682], "mapped", [1581, 1605]], [[64683, 64683], "mapped", [1582, 1580]], [[64684, 64684], "mapped", [1582, 1605]], [[64685, 64685], "mapped", [1587, 1580]], [[64686, 64686], "mapped", [1587, 1581]], [[64687, 64687], "mapped", [1587, 1582]], [[64688, 64688], "mapped", [1587, 1605]], [[64689, 64689], "mapped", [1589, 1581]], [[64690, 64690], "mapped", [1589, 1582]], [[64691, 64691], "mapped", [1589, 1605]], [[64692, 64692], "mapped", [1590, 1580]], [[64693, 64693], "mapped", [1590, 1581]], [[64694, 64694], "mapped", [1590, 1582]], [[64695, 64695], "mapped", [1590, 1605]], [[64696, 64696], "mapped", [1591, 1581]], [[64697, 64697], "mapped", [1592, 1605]], [[64698, 64698], "mapped", [1593, 1580]], [[64699, 64699], "mapped", [1593, 1605]], [[64700, 64700], "mapped", [1594, 1580]], [[64701, 64701], "mapped", [1594, 1605]], [[64702, 64702], "mapped", [1601, 1580]], [[64703, 64703], "mapped", [1601, 1581]], [[64704, 64704], "mapped", [1601, 1582]], [[64705, 64705], "mapped", [1601, 1605]], [[64706, 64706], "mapped", [1602, 1581]], [[64707, 64707], "mapped", [1602, 1605]], [[64708, 64708], "mapped", [1603, 1580]], [[64709, 64709], "mapped", [1603, 1581]], [[64710, 64710], "mapped", [1603, 1582]], [[64711, 64711], "mapped", [1603, 1604]], [[64712, 64712], "mapped", [1603, 1605]], [[64713, 64713], "mapped", [1604, 1580]], [[64714, 64714], "mapped", [1604, 1581]], [[64715, 64715], "mapped", [1604, 1582]], [[64716, 64716], "mapped", [1604, 1605]], [[64717, 64717], "mapped", [1604, 1607]], [[64718, 64718], "mapped", [1605, 1580]], [[64719, 64719], "mapped", [1605, 1581]], [[64720, 64720], "mapped", [1605, 1582]], [[64721, 64721], "mapped", [1605, 1605]], [[64722, 64722], "mapped", [1606, 1580]], [[64723, 64723], "mapped", [1606, 1581]], [[64724, 64724], "mapped", [1606, 1582]], [[64725, 64725], "mapped", [1606, 1605]], [[64726, 64726], "mapped", [1606, 1607]], [[64727, 64727], "mapped", [1607, 1580]], [[64728, 64728], "mapped", [1607, 1605]], [[64729, 64729], "mapped", [1607, 1648]], [[64730, 64730], "mapped", [1610, 1580]], [[64731, 64731], "mapped", [1610, 1581]], [[64732, 64732], "mapped", [1610, 1582]], [[64733, 64733], "mapped", [1610, 1605]], [[64734, 64734], "mapped", [1610, 1607]], [[64735, 64735], "mapped", [1574, 1605]], [[64736, 64736], "mapped", [1574, 1607]], [[64737, 64737], "mapped", [1576, 1605]], [[64738, 64738], "mapped", [1576, 1607]], [[64739, 64739], "mapped", [1578, 1605]], [[64740, 64740], "mapped", [1578, 1607]], [[64741, 64741], "mapped", [1579, 1605]], [[64742, 64742], "mapped", [1579, 1607]], [[64743, 64743], "mapped", [1587, 1605]], [[64744, 64744], "mapped", [1587, 1607]], [[64745, 64745], "mapped", [1588, 1605]], [[64746, 64746], "mapped", [1588, 1607]], [[64747, 64747], "mapped", [1603, 1604]], [[64748, 64748], "mapped", [1603, 1605]], [[64749, 64749], "mapped", [1604, 1605]], [[64750, 64750], "mapped", [1606, 1605]], [[64751, 64751], "mapped", [1606, 1607]], [[64752, 64752], "mapped", [1610, 1605]], [[64753, 64753], "mapped", [1610, 1607]], [[64754, 64754], "mapped", [1600, 1614, 1617]], [[64755, 64755], "mapped", [1600, 1615, 1617]], [[64756, 64756], "mapped", [1600, 1616, 1617]], [[64757, 64757], "mapped", [1591, 1609]], [[64758, 64758], "mapped", [1591, 1610]], [[64759, 64759], "mapped", [1593, 1609]], [[64760, 64760], "mapped", [1593, 1610]], [[64761, 64761], "mapped", [1594, 1609]], [[64762, 64762], "mapped", [1594, 1610]], [[64763, 64763], "mapped", [1587, 1609]], [[64764, 64764], "mapped", [1587, 1610]], [[64765, 64765], "mapped", [1588, 1609]], [[64766, 64766], "mapped", [1588, 1610]], [[64767, 64767], "mapped", [1581, 1609]], [[64768, 64768], "mapped", [1581, 1610]], [[64769, 64769], "mapped", [1580, 1609]], [[64770, 64770], "mapped", [1580, 1610]], [[64771, 64771], "mapped", [1582, 1609]], [[64772, 64772], "mapped", [1582, 1610]], [[64773, 64773], "mapped", [1589, 1609]], [[64774, 64774], "mapped", [1589, 1610]], [[64775, 64775], "mapped", [1590, 1609]], [[64776, 64776], "mapped", [1590, 1610]], [[64777, 64777], "mapped", [1588, 1580]], [[64778, 64778], "mapped", [1588, 1581]], [[64779, 64779], "mapped", [1588, 1582]], [[64780, 64780], "mapped", [1588, 1605]], [[64781, 64781], "mapped", [1588, 1585]], [[64782, 64782], "mapped", [1587, 1585]], [[64783, 64783], "mapped", [1589, 1585]], [[64784, 64784], "mapped", [1590, 1585]], [[64785, 64785], "mapped", [1591, 1609]], [[64786, 64786], "mapped", [1591, 1610]], [[64787, 64787], "mapped", [1593, 1609]], [[64788, 64788], "mapped", [1593, 1610]], [[64789, 64789], "mapped", [1594, 1609]], [[64790, 64790], "mapped", [1594, 1610]], [[64791, 64791], "mapped", [1587, 1609]], [[64792, 64792], "mapped", [1587, 1610]], [[64793, 64793], "mapped", [1588, 1609]], [[64794, 64794], "mapped", [1588, 1610]], [[64795, 64795], "mapped", [1581, 1609]], [[64796, 64796], "mapped", [1581, 1610]], [[64797, 64797], "mapped", [1580, 1609]], [[64798, 64798], "mapped", [1580, 1610]], [[64799, 64799], "mapped", [1582, 1609]], [[64800, 64800], "mapped", [1582, 1610]], [[64801, 64801], "mapped", [1589, 1609]], [[64802, 64802], "mapped", [1589, 1610]], [[64803, 64803], "mapped", [1590, 1609]], [[64804, 64804], "mapped", [1590, 1610]], [[64805, 64805], "mapped", [1588, 1580]], [[64806, 64806], "mapped", [1588, 1581]], [[64807, 64807], "mapped", [1588, 1582]], [[64808, 64808], "mapped", [1588, 1605]], [[64809, 64809], "mapped", [1588, 1585]], [[64810, 64810], "mapped", [1587, 1585]], [[64811, 64811], "mapped", [1589, 1585]], [[64812, 64812], "mapped", [1590, 1585]], [[64813, 64813], "mapped", [1588, 1580]], [[64814, 64814], "mapped", [1588, 1581]], [[64815, 64815], "mapped", [1588, 1582]], [[64816, 64816], "mapped", [1588, 1605]], [[64817, 64817], "mapped", [1587, 1607]], [[64818, 64818], "mapped", [1588, 1607]], [[64819, 64819], "mapped", [1591, 1605]], [[64820, 64820], "mapped", [1587, 1580]], [[64821, 64821], "mapped", [1587, 1581]], [[64822, 64822], "mapped", [1587, 1582]], [[64823, 64823], "mapped", [1588, 1580]], [[64824, 64824], "mapped", [1588, 1581]], [[64825, 64825], "mapped", [1588, 1582]], [[64826, 64826], "mapped", [1591, 1605]], [[64827, 64827], "mapped", [1592, 1605]], [[64828, 64829], "mapped", [1575, 1611]], [[64830, 64831], "valid", [], "NV8"], [[64832, 64847], "disallowed"], [[64848, 64848], "mapped", [1578, 1580, 1605]], [[64849, 64850], "mapped", [1578, 1581, 1580]], [[64851, 64851], "mapped", [1578, 1581, 1605]], [[64852, 64852], "mapped", [1578, 1582, 1605]], [[64853, 64853], "mapped", [1578, 1605, 1580]], [[64854, 64854], "mapped", [1578, 1605, 1581]], [[64855, 64855], "mapped", [1578, 1605, 1582]], [[64856, 64857], "mapped", [1580, 1605, 1581]], [[64858, 64858], "mapped", [1581, 1605, 1610]], [[64859, 64859], "mapped", [1581, 1605, 1609]], [[64860, 64860], "mapped", [1587, 1581, 1580]], [[64861, 64861], "mapped", [1587, 1580, 1581]], [[64862, 64862], "mapped", [1587, 1580, 1609]], [[64863, 64864], "mapped", [1587, 1605, 1581]], [[64865, 64865], "mapped", [1587, 1605, 1580]], [[64866, 64867], "mapped", [1587, 1605, 1605]], [[64868, 64869], "mapped", [1589, 1581, 1581]], [[64870, 64870], "mapped", [1589, 1605, 1605]], [[64871, 64872], "mapped", [1588, 1581, 1605]], [[64873, 64873], "mapped", [1588, 1580, 1610]], [[64874, 64875], "mapped", [1588, 1605, 1582]], [[64876, 64877], "mapped", [1588, 1605, 1605]], [[64878, 64878], "mapped", [1590, 1581, 1609]], [[64879, 64880], "mapped", [1590, 1582, 1605]], [[64881, 64882], "mapped", [1591, 1605, 1581]], [[64883, 64883], "mapped", [1591, 1605, 1605]], [[64884, 64884], "mapped", [1591, 1605, 1610]], [[64885, 64885], "mapped", [1593, 1580, 1605]], [[64886, 64887], "mapped", [1593, 1605, 1605]], [[64888, 64888], "mapped", [1593, 1605, 1609]], [[64889, 64889], "mapped", [1594, 1605, 1605]], [[64890, 64890], "mapped", [1594, 1605, 1610]], [[64891, 64891], "mapped", [1594, 1605, 1609]], [[64892, 64893], "mapped", [1601, 1582, 1605]], [[64894, 64894], "mapped", [1602, 1605, 1581]], [[64895, 64895], "mapped", [1602, 1605, 1605]], [[64896, 64896], "mapped", [1604, 1581, 1605]], [[64897, 64897], "mapped", [1604, 1581, 1610]], [[64898, 64898], "mapped", [1604, 1581, 1609]], [[64899, 64900], "mapped", [1604, 1580, 1580]], [[64901, 64902], "mapped", [1604, 1582, 1605]], [[64903, 64904], "mapped", [1604, 1605, 1581]], [[64905, 64905], "mapped", [1605, 1581, 1580]], [[64906, 64906], "mapped", [1605, 1581, 1605]], [[64907, 64907], "mapped", [1605, 1581, 1610]], [[64908, 64908], "mapped", [1605, 1580, 1581]], [[64909, 64909], "mapped", [1605, 1580, 1605]], [[64910, 64910], "mapped", [1605, 1582, 1580]], [[64911, 64911], "mapped", [1605, 1582, 1605]], [[64912, 64913], "disallowed"], [[64914, 64914], "mapped", [1605, 1580, 1582]], [[64915, 64915], "mapped", [1607, 1605, 1580]], [[64916, 64916], "mapped", [1607, 1605, 1605]], [[64917, 64917], "mapped", [1606, 1581, 1605]], [[64918, 64918], "mapped", [1606, 1581, 1609]], [[64919, 64920], "mapped", [1606, 1580, 1605]], [[64921, 64921], "mapped", [1606, 1580, 1609]], [[64922, 64922], "mapped", [1606, 1605, 1610]], [[64923, 64923], "mapped", [1606, 1605, 1609]], [[64924, 64925], "mapped", [1610, 1605, 1605]], [[64926, 64926], "mapped", [1576, 1582, 1610]], [[64927, 64927], "mapped", [1578, 1580, 1610]], [[64928, 64928], "mapped", [1578, 1580, 1609]], [[64929, 64929], "mapped", [1578, 1582, 1610]], [[64930, 64930], "mapped", [1578, 1582, 1609]], [[64931, 64931], "mapped", [1578, 1605, 1610]], [[64932, 64932], "mapped", [1578, 1605, 1609]], [[64933, 64933], "mapped", [1580, 1605, 1610]], [[64934, 64934], "mapped", [1580, 1581, 1609]], [[64935, 64935], "mapped", [1580, 1605, 1609]], [[64936, 64936], "mapped", [1587, 1582, 1609]], [[64937, 64937], "mapped", [1589, 1581, 1610]], [[64938, 64938], "mapped", [1588, 1581, 1610]], [[64939, 64939], "mapped", [1590, 1581, 1610]], [[64940, 64940], "mapped", [1604, 1580, 1610]], [[64941, 64941], "mapped", [1604, 1605, 1610]], [[64942, 64942], "mapped", [1610, 1581, 1610]], [[64943, 64943], "mapped", [1610, 1580, 1610]], [[64944, 64944], "mapped", [1610, 1605, 1610]], [[64945, 64945], "mapped", [1605, 1605, 1610]], [[64946, 64946], "mapped", [1602, 1605, 1610]], [[64947, 64947], "mapped", [1606, 1581, 1610]], [[64948, 64948], "mapped", [1602, 1605, 1581]], [[64949, 64949], "mapped", [1604, 1581, 1605]], [[64950, 64950], "mapped", [1593, 1605, 1610]], [[64951, 64951], "mapped", [1603, 1605, 1610]], [[64952, 64952], "mapped", [1606, 1580, 1581]], [[64953, 64953], "mapped", [1605, 1582, 1610]], [[64954, 64954], "mapped", [1604, 1580, 1605]], [[64955, 64955], "mapped", [1603, 1605, 1605]], [[64956, 64956], "mapped", [1604, 1580, 1605]], [[64957, 64957], "mapped", [1606, 1580, 1581]], [[64958, 64958], "mapped", [1580, 1581, 1610]], [[64959, 64959], "mapped", [1581, 1580, 1610]], [[64960, 64960], "mapped", [1605, 1580, 1610]], [[64961, 64961], "mapped", [1601, 1605, 1610]], [[64962, 64962], "mapped", [1576, 1581, 1610]], [[64963, 64963], "mapped", [1603, 1605, 1605]], [[64964, 64964], "mapped", [1593, 1580, 1605]], [[64965, 64965], "mapped", [1589, 1605, 1605]], [[64966, 64966], "mapped", [1587, 1582, 1610]], [[64967, 64967], "mapped", [1606, 1580, 1610]], [[64968, 64975], "disallowed"], [[64976, 65007], "disallowed"], [[65008, 65008], "mapped", [1589, 1604, 1746]], [[65009, 65009], "mapped", [1602, 1604, 1746]], [[65010, 65010], "mapped", [1575, 1604, 1604, 1607]], [[65011, 65011], "mapped", [1575, 1603, 1576, 1585]], [[65012, 65012], "mapped", [1605, 1581, 1605, 1583]], [[65013, 65013], "mapped", [1589, 1604, 1593, 1605]], [[65014, 65014], "mapped", [1585, 1587, 1608, 1604]], [[65015, 65015], "mapped", [1593, 1604, 1610, 1607]], [[65016, 65016], "mapped", [1608, 1587, 1604, 1605]], [[65017, 65017], "mapped", [1589, 1604, 1609]], [[65018, 65018], "disallowed_STD3_mapped", [1589, 1604, 1609, 32, 1575, 1604, 1604, 1607, 32, 1593, 1604, 1610, 1607, 32, 1608, 1587, 1604, 1605]], [[65019, 65019], "disallowed_STD3_mapped", [1580, 1604, 32, 1580, 1604, 1575, 1604, 1607]], [[65020, 65020], "mapped", [1585, 1740, 1575, 1604]], [[65021, 65021], "valid", [], "NV8"], [[65022, 65023], "disallowed"], [[65024, 65039], "ignored"], [[65040, 65040], "disallowed_STD3_mapped", [44]], [[65041, 65041], "mapped", [12289]], [[65042, 65042], "disallowed"], [[65043, 65043], "disallowed_STD3_mapped", [58]], [[65044, 65044], "disallowed_STD3_mapped", [59]], [[65045, 65045], "disallowed_STD3_mapped", [33]], [[65046, 65046], "disallowed_STD3_mapped", [63]], [[65047, 65047], "mapped", [12310]], [[65048, 65048], "mapped", [12311]], [[65049, 65049], "disallowed"], [[65050, 65055], "disallowed"], [[65056, 65059], "valid"], [[65060, 65062], "valid"], [[65063, 65069], "valid"], [[65070, 65071], "valid"], [[65072, 65072], "disallowed"], [[65073, 65073], "mapped", [8212]], [[65074, 65074], "mapped", [8211]], [[65075, 65076], "disallowed_STD3_mapped", [95]], [[65077, 65077], "disallowed_STD3_mapped", [40]], [[65078, 65078], "disallowed_STD3_mapped", [41]], [[65079, 65079], "disallowed_STD3_mapped", [123]], [[65080, 65080], "disallowed_STD3_mapped", [125]], [[65081, 65081], "mapped", [12308]], [[65082, 65082], "mapped", [12309]], [[65083, 65083], "mapped", [12304]], [[65084, 65084], "mapped", [12305]], [[65085, 65085], "mapped", [12298]], [[65086, 65086], "mapped", [12299]], [[65087, 65087], "mapped", [12296]], [[65088, 65088], "mapped", [12297]], [[65089, 65089], "mapped", [12300]], [[65090, 65090], "mapped", [12301]], [[65091, 65091], "mapped", [12302]], [[65092, 65092], "mapped", [12303]], [[65093, 65094], "valid", [], "NV8"], [[65095, 65095], "disallowed_STD3_mapped", [91]], [[65096, 65096], "disallowed_STD3_mapped", [93]], [[65097, 65100], "disallowed_STD3_mapped", [32, 773]], [[65101, 65103], "disallowed_STD3_mapped", [95]], [[65104, 65104], "disallowed_STD3_mapped", [44]], [[65105, 65105], "mapped", [12289]], [[65106, 65106], "disallowed"], [[65107, 65107], "disallowed"], [[65108, 65108], "disallowed_STD3_mapped", [59]], [[65109, 65109], "disallowed_STD3_mapped", [58]], [[65110, 65110], "disallowed_STD3_mapped", [63]], [[65111, 65111], "disallowed_STD3_mapped", [33]], [[65112, 65112], "mapped", [8212]], [[65113, 65113], "disallowed_STD3_mapped", [40]], [[65114, 65114], "disallowed_STD3_mapped", [41]], [[65115, 65115], "disallowed_STD3_mapped", [123]], [[65116, 65116], "disallowed_STD3_mapped", [125]], [[65117, 65117], "mapped", [12308]], [[65118, 65118], "mapped", [12309]], [[65119, 65119], "disallowed_STD3_mapped", [35]], [[65120, 65120], "disallowed_STD3_mapped", [38]], [[65121, 65121], "disallowed_STD3_mapped", [42]], [[65122, 65122], "disallowed_STD3_mapped", [43]], [[65123, 65123], "mapped", [45]], [[65124, 65124], "disallowed_STD3_mapped", [60]], [[65125, 65125], "disallowed_STD3_mapped", [62]], [[65126, 65126], "disallowed_STD3_mapped", [61]], [[65127, 65127], "disallowed"], [[65128, 65128], "disallowed_STD3_mapped", [92]], [[65129, 65129], "disallowed_STD3_mapped", [36]], [[65130, 65130], "disallowed_STD3_mapped", [37]], [[65131, 65131], "disallowed_STD3_mapped", [64]], [[65132, 65135], "disallowed"], [[65136, 65136], "disallowed_STD3_mapped", [32, 1611]], [[65137, 65137], "mapped", [1600, 1611]], [[65138, 65138], "disallowed_STD3_mapped", [32, 1612]], [[65139, 65139], "valid"], [[65140, 65140], "disallowed_STD3_mapped", [32, 1613]], [[65141, 65141], "disallowed"], [[65142, 65142], "disallowed_STD3_mapped", [32, 1614]], [[65143, 65143], "mapped", [1600, 1614]], [[65144, 65144], "disallowed_STD3_mapped", [32, 1615]], [[65145, 65145], "mapped", [1600, 1615]], [[65146, 65146], "disallowed_STD3_mapped", [32, 1616]], [[65147, 65147], "mapped", [1600, 1616]], [[65148, 65148], "disallowed_STD3_mapped", [32, 1617]], [[65149, 65149], "mapped", [1600, 1617]], [[65150, 65150], "disallowed_STD3_mapped", [32, 1618]], [[65151, 65151], "mapped", [1600, 1618]], [[65152, 65152], "mapped", [1569]], [[65153, 65154], "mapped", [1570]], [[65155, 65156], "mapped", [1571]], [[65157, 65158], "mapped", [1572]], [[65159, 65160], "mapped", [1573]], [[65161, 65164], "mapped", [1574]], [[65165, 65166], "mapped", [1575]], [[65167, 65170], "mapped", [1576]], [[65171, 65172], "mapped", [1577]], [[65173, 65176], "mapped", [1578]], [[65177, 65180], "mapped", [1579]], [[65181, 65184], "mapped", [1580]], [[65185, 65188], "mapped", [1581]], [[65189, 65192], "mapped", [1582]], [[65193, 65194], "mapped", [1583]], [[65195, 65196], "mapped", [1584]], [[65197, 65198], "mapped", [1585]], [[65199, 65200], "mapped", [1586]], [[65201, 65204], "mapped", [1587]], [[65205, 65208], "mapped", [1588]], [[65209, 65212], "mapped", [1589]], [[65213, 65216], "mapped", [1590]], [[65217, 65220], "mapped", [1591]], [[65221, 65224], "mapped", [1592]], [[65225, 65228], "mapped", [1593]], [[65229, 65232], "mapped", [1594]], [[65233, 65236], "mapped", [1601]], [[65237, 65240], "mapped", [1602]], [[65241, 65244], "mapped", [1603]], [[65245, 65248], "mapped", [1604]], [[65249, 65252], "mapped", [1605]], [[65253, 65256], "mapped", [1606]], [[65257, 65260], "mapped", [1607]], [[65261, 65262], "mapped", [1608]], [[65263, 65264], "mapped", [1609]], [[65265, 65268], "mapped", [1610]], [[65269, 65270], "mapped", [1604, 1570]], [[65271, 65272], "mapped", [1604, 1571]], [[65273, 65274], "mapped", [1604, 1573]], [[65275, 65276], "mapped", [1604, 1575]], [[65277, 65278], "disallowed"], [[65279, 65279], "ignored"], [[65280, 65280], "disallowed"], [[65281, 65281], "disallowed_STD3_mapped", [33]], [[65282, 65282], "disallowed_STD3_mapped", [34]], [[65283, 65283], "disallowed_STD3_mapped", [35]], [[65284, 65284], "disallowed_STD3_mapped", [36]], [[65285, 65285], "disallowed_STD3_mapped", [37]], [[65286, 65286], "disallowed_STD3_mapped", [38]], [[65287, 65287], "disallowed_STD3_mapped", [39]], [[65288, 65288], "disallowed_STD3_mapped", [40]], [[65289, 65289], "disallowed_STD3_mapped", [41]], [[65290, 65290], "disallowed_STD3_mapped", [42]], [[65291, 65291], "disallowed_STD3_mapped", [43]], [[65292, 65292], "disallowed_STD3_mapped", [44]], [[65293, 65293], "mapped", [45]], [[65294, 65294], "mapped", [46]], [[65295, 65295], "disallowed_STD3_mapped", [47]], [[65296, 65296], "mapped", [48]], [[65297, 65297], "mapped", [49]], [[65298, 65298], "mapped", [50]], [[65299, 65299], "mapped", [51]], [[65300, 65300], "mapped", [52]], [[65301, 65301], "mapped", [53]], [[65302, 65302], "mapped", [54]], [[65303, 65303], "mapped", [55]], [[65304, 65304], "mapped", [56]], [[65305, 65305], "mapped", [57]], [[65306, 65306], "disallowed_STD3_mapped", [58]], [[65307, 65307], "disallowed_STD3_mapped", [59]], [[65308, 65308], "disallowed_STD3_mapped", [60]], [[65309, 65309], "disallowed_STD3_mapped", [61]], [[65310, 65310], "disallowed_STD3_mapped", [62]], [[65311, 65311], "disallowed_STD3_mapped", [63]], [[65312, 65312], "disallowed_STD3_mapped", [64]], [[65313, 65313], "mapped", [97]], [[65314, 65314], "mapped", [98]], [[65315, 65315], "mapped", [99]], [[65316, 65316], "mapped", [100]], [[65317, 65317], "mapped", [101]], [[65318, 65318], "mapped", [102]], [[65319, 65319], "mapped", [103]], [[65320, 65320], "mapped", [104]], [[65321, 65321], "mapped", [105]], [[65322, 65322], "mapped", [106]], [[65323, 65323], "mapped", [107]], [[65324, 65324], "mapped", [108]], [[65325, 65325], "mapped", [109]], [[65326, 65326], "mapped", [110]], [[65327, 65327], "mapped", [111]], [[65328, 65328], "mapped", [112]], [[65329, 65329], "mapped", [113]], [[65330, 65330], "mapped", [114]], [[65331, 65331], "mapped", [115]], [[65332, 65332], "mapped", [116]], [[65333, 65333], "mapped", [117]], [[65334, 65334], "mapped", [118]], [[65335, 65335], "mapped", [119]], [[65336, 65336], "mapped", [120]], [[65337, 65337], "mapped", [121]], [[65338, 65338], "mapped", [122]], [[65339, 65339], "disallowed_STD3_mapped", [91]], [[65340, 65340], "disallowed_STD3_mapped", [92]], [[65341, 65341], "disallowed_STD3_mapped", [93]], [[65342, 65342], "disallowed_STD3_mapped", [94]], [[65343, 65343], "disallowed_STD3_mapped", [95]], [[65344, 65344], "disallowed_STD3_mapped", [96]], [[65345, 65345], "mapped", [97]], [[65346, 65346], "mapped", [98]], [[65347, 65347], "mapped", [99]], [[65348, 65348], "mapped", [100]], [[65349, 65349], "mapped", [101]], [[65350, 65350], "mapped", [102]], [[65351, 65351], "mapped", [103]], [[65352, 65352], "mapped", [104]], [[65353, 65353], "mapped", [105]], [[65354, 65354], "mapped", [106]], [[65355, 65355], "mapped", [107]], [[65356, 65356], "mapped", [108]], [[65357, 65357], "mapped", [109]], [[65358, 65358], "mapped", [110]], [[65359, 65359], "mapped", [111]], [[65360, 65360], "mapped", [112]], [[65361, 65361], "mapped", [113]], [[65362, 65362], "mapped", [114]], [[65363, 65363], "mapped", [115]], [[65364, 65364], "mapped", [116]], [[65365, 65365], "mapped", [117]], [[65366, 65366], "mapped", [118]], [[65367, 65367], "mapped", [119]], [[65368, 65368], "mapped", [120]], [[65369, 65369], "mapped", [121]], [[65370, 65370], "mapped", [122]], [[65371, 65371], "disallowed_STD3_mapped", [123]], [[65372, 65372], "disallowed_STD3_mapped", [124]], [[65373, 65373], "disallowed_STD3_mapped", [125]], [[65374, 65374], "disallowed_STD3_mapped", [126]], [[65375, 65375], "mapped", [10629]], [[65376, 65376], "mapped", [10630]], [[65377, 65377], "mapped", [46]], [[65378, 65378], "mapped", [12300]], [[65379, 65379], "mapped", [12301]], [[65380, 65380], "mapped", [12289]], [[65381, 65381], "mapped", [12539]], [[65382, 65382], "mapped", [12530]], [[65383, 65383], "mapped", [12449]], [[65384, 65384], "mapped", [12451]], [[65385, 65385], "mapped", [12453]], [[65386, 65386], "mapped", [12455]], [[65387, 65387], "mapped", [12457]], [[65388, 65388], "mapped", [12515]], [[65389, 65389], "mapped", [12517]], [[65390, 65390], "mapped", [12519]], [[65391, 65391], "mapped", [12483]], [[65392, 65392], "mapped", [12540]], [[65393, 65393], "mapped", [12450]], [[65394, 65394], "mapped", [12452]], [[65395, 65395], "mapped", [12454]], [[65396, 65396], "mapped", [12456]], [[65397, 65397], "mapped", [12458]], [[65398, 65398], "mapped", [12459]], [[65399, 65399], "mapped", [12461]], [[65400, 65400], "mapped", [12463]], [[65401, 65401], "mapped", [12465]], [[65402, 65402], "mapped", [12467]], [[65403, 65403], "mapped", [12469]], [[65404, 65404], "mapped", [12471]], [[65405, 65405], "mapped", [12473]], [[65406, 65406], "mapped", [12475]], [[65407, 65407], "mapped", [12477]], [[65408, 65408], "mapped", [12479]], [[65409, 65409], "mapped", [12481]], [[65410, 65410], "mapped", [12484]], [[65411, 65411], "mapped", [12486]], [[65412, 65412], "mapped", [12488]], [[65413, 65413], "mapped", [12490]], [[65414, 65414], "mapped", [12491]], [[65415, 65415], "mapped", [12492]], [[65416, 65416], "mapped", [12493]], [[65417, 65417], "mapped", [12494]], [[65418, 65418], "mapped", [12495]], [[65419, 65419], "mapped", [12498]], [[65420, 65420], "mapped", [12501]], [[65421, 65421], "mapped", [12504]], [[65422, 65422], "mapped", [12507]], [[65423, 65423], "mapped", [12510]], [[65424, 65424], "mapped", [12511]], [[65425, 65425], "mapped", [12512]], [[65426, 65426], "mapped", [12513]], [[65427, 65427], "mapped", [12514]], [[65428, 65428], "mapped", [12516]], [[65429, 65429], "mapped", [12518]], [[65430, 65430], "mapped", [12520]], [[65431, 65431], "mapped", [12521]], [[65432, 65432], "mapped", [12522]], [[65433, 65433], "mapped", [12523]], [[65434, 65434], "mapped", [12524]], [[65435, 65435], "mapped", [12525]], [[65436, 65436], "mapped", [12527]], [[65437, 65437], "mapped", [12531]], [[65438, 65438], "mapped", [12441]], [[65439, 65439], "mapped", [12442]], [[65440, 65440], "disallowed"], [[65441, 65441], "mapped", [4352]], [[65442, 65442], "mapped", [4353]], [[65443, 65443], "mapped", [4522]], [[65444, 65444], "mapped", [4354]], [[65445, 65445], "mapped", [4524]], [[65446, 65446], "mapped", [4525]], [[65447, 65447], "mapped", [4355]], [[65448, 65448], "mapped", [4356]], [[65449, 65449], "mapped", [4357]], [[65450, 65450], "mapped", [4528]], [[65451, 65451], "mapped", [4529]], [[65452, 65452], "mapped", [4530]], [[65453, 65453], "mapped", [4531]], [[65454, 65454], "mapped", [4532]], [[65455, 65455], "mapped", [4533]], [[65456, 65456], "mapped", [4378]], [[65457, 65457], "mapped", [4358]], [[65458, 65458], "mapped", [4359]], [[65459, 65459], "mapped", [4360]], [[65460, 65460], "mapped", [4385]], [[65461, 65461], "mapped", [4361]], [[65462, 65462], "mapped", [4362]], [[65463, 65463], "mapped", [4363]], [[65464, 65464], "mapped", [4364]], [[65465, 65465], "mapped", [4365]], [[65466, 65466], "mapped", [4366]], [[65467, 65467], "mapped", [4367]], [[65468, 65468], "mapped", [4368]], [[65469, 65469], "mapped", [4369]], [[65470, 65470], "mapped", [4370]], [[65471, 65473], "disallowed"], [[65474, 65474], "mapped", [4449]], [[65475, 65475], "mapped", [4450]], [[65476, 65476], "mapped", [4451]], [[65477, 65477], "mapped", [4452]], [[65478, 65478], "mapped", [4453]], [[65479, 65479], "mapped", [4454]], [[65480, 65481], "disallowed"], [[65482, 65482], "mapped", [4455]], [[65483, 65483], "mapped", [4456]], [[65484, 65484], "mapped", [4457]], [[65485, 65485], "mapped", [4458]], [[65486, 65486], "mapped", [4459]], [[65487, 65487], "mapped", [4460]], [[65488, 65489], "disallowed"], [[65490, 65490], "mapped", [4461]], [[65491, 65491], "mapped", [4462]], [[65492, 65492], "mapped", [4463]], [[65493, 65493], "mapped", [4464]], [[65494, 65494], "mapped", [4465]], [[65495, 65495], "mapped", [4466]], [[65496, 65497], "disallowed"], [[65498, 65498], "mapped", [4467]], [[65499, 65499], "mapped", [4468]], [[65500, 65500], "mapped", [4469]], [[65501, 65503], "disallowed"], [[65504, 65504], "mapped", [162]], [[65505, 65505], "mapped", [163]], [[65506, 65506], "mapped", [172]], [[65507, 65507], "disallowed_STD3_mapped", [32, 772]], [[65508, 65508], "mapped", [166]], [[65509, 65509], "mapped", [165]], [[65510, 65510], "mapped", [8361]], [[65511, 65511], "disallowed"], [[65512, 65512], "mapped", [9474]], [[65513, 65513], "mapped", [8592]], [[65514, 65514], "mapped", [8593]], [[65515, 65515], "mapped", [8594]], [[65516, 65516], "mapped", [8595]], [[65517, 65517], "mapped", [9632]], [[65518, 65518], "mapped", [9675]], [[65519, 65528], "disallowed"], [[65529, 65531], "disallowed"], [[65532, 65532], "disallowed"], [[65533, 65533], "disallowed"], [[65534, 65535], "disallowed"], [[65536, 65547], "valid"], [[65548, 65548], "disallowed"], [[65549, 65574], "valid"], [[65575, 65575], "disallowed"], [[65576, 65594], "valid"], [[65595, 65595], "disallowed"], [[65596, 65597], "valid"], [[65598, 65598], "disallowed"], [[65599, 65613], "valid"], [[65614, 65615], "disallowed"], [[65616, 65629], "valid"], [[65630, 65663], "disallowed"], [[65664, 65786], "valid"], [[65787, 65791], "disallowed"], [[65792, 65794], "valid", [], "NV8"], [[65795, 65798], "disallowed"], [[65799, 65843], "valid", [], "NV8"], [[65844, 65846], "disallowed"], [[65847, 65855], "valid", [], "NV8"], [[65856, 65930], "valid", [], "NV8"], [[65931, 65932], "valid", [], "NV8"], [[65933, 65935], "disallowed"], [[65936, 65947], "valid", [], "NV8"], [[65948, 65951], "disallowed"], [[65952, 65952], "valid", [], "NV8"], [[65953, 65999], "disallowed"], [[66e3, 66044], "valid", [], "NV8"], [[66045, 66045], "valid"], [[66046, 66175], "disallowed"], [[66176, 66204], "valid"], [[66205, 66207], "disallowed"], [[66208, 66256], "valid"], [[66257, 66271], "disallowed"], [[66272, 66272], "valid"], [[66273, 66299], "valid", [], "NV8"], [[66300, 66303], "disallowed"], [[66304, 66334], "valid"], [[66335, 66335], "valid"], [[66336, 66339], "valid", [], "NV8"], [[66340, 66351], "disallowed"], [[66352, 66368], "valid"], [[66369, 66369], "valid", [], "NV8"], [[66370, 66377], "valid"], [[66378, 66378], "valid", [], "NV8"], [[66379, 66383], "disallowed"], [[66384, 66426], "valid"], [[66427, 66431], "disallowed"], [[66432, 66461], "valid"], [[66462, 66462], "disallowed"], [[66463, 66463], "valid", [], "NV8"], [[66464, 66499], "valid"], [[66500, 66503], "disallowed"], [[66504, 66511], "valid"], [[66512, 66517], "valid", [], "NV8"], [[66518, 66559], "disallowed"], [[66560, 66560], "mapped", [66600]], [[66561, 66561], "mapped", [66601]], [[66562, 66562], "mapped", [66602]], [[66563, 66563], "mapped", [66603]], [[66564, 66564], "mapped", [66604]], [[66565, 66565], "mapped", [66605]], [[66566, 66566], "mapped", [66606]], [[66567, 66567], "mapped", [66607]], [[66568, 66568], "mapped", [66608]], [[66569, 66569], "mapped", [66609]], [[66570, 66570], "mapped", [66610]], [[66571, 66571], "mapped", [66611]], [[66572, 66572], "mapped", [66612]], [[66573, 66573], "mapped", [66613]], [[66574, 66574], "mapped", [66614]], [[66575, 66575], "mapped", [66615]], [[66576, 66576], "mapped", [66616]], [[66577, 66577], "mapped", [66617]], [[66578, 66578], "mapped", [66618]], [[66579, 66579], "mapped", [66619]], [[66580, 66580], "mapped", [66620]], [[66581, 66581], "mapped", [66621]], [[66582, 66582], "mapped", [66622]], [[66583, 66583], "mapped", [66623]], [[66584, 66584], "mapped", [66624]], [[66585, 66585], "mapped", [66625]], [[66586, 66586], "mapped", [66626]], [[66587, 66587], "mapped", [66627]], [[66588, 66588], "mapped", [66628]], [[66589, 66589], "mapped", [66629]], [[66590, 66590], "mapped", [66630]], [[66591, 66591], "mapped", [66631]], [[66592, 66592], "mapped", [66632]], [[66593, 66593], "mapped", [66633]], [[66594, 66594], "mapped", [66634]], [[66595, 66595], "mapped", [66635]], [[66596, 66596], "mapped", [66636]], [[66597, 66597], "mapped", [66637]], [[66598, 66598], "mapped", [66638]], [[66599, 66599], "mapped", [66639]], [[66600, 66637], "valid"], [[66638, 66717], "valid"], [[66718, 66719], "disallowed"], [[66720, 66729], "valid"], [[66730, 66815], "disallowed"], [[66816, 66855], "valid"], [[66856, 66863], "disallowed"], [[66864, 66915], "valid"], [[66916, 66926], "disallowed"], [[66927, 66927], "valid", [], "NV8"], [[66928, 67071], "disallowed"], [[67072, 67382], "valid"], [[67383, 67391], "disallowed"], [[67392, 67413], "valid"], [[67414, 67423], "disallowed"], [[67424, 67431], "valid"], [[67432, 67583], "disallowed"], [[67584, 67589], "valid"], [[67590, 67591], "disallowed"], [[67592, 67592], "valid"], [[67593, 67593], "disallowed"], [[67594, 67637], "valid"], [[67638, 67638], "disallowed"], [[67639, 67640], "valid"], [[67641, 67643], "disallowed"], [[67644, 67644], "valid"], [[67645, 67646], "disallowed"], [[67647, 67647], "valid"], [[67648, 67669], "valid"], [[67670, 67670], "disallowed"], [[67671, 67679], "valid", [], "NV8"], [[67680, 67702], "valid"], [[67703, 67711], "valid", [], "NV8"], [[67712, 67742], "valid"], [[67743, 67750], "disallowed"], [[67751, 67759], "valid", [], "NV8"], [[67760, 67807], "disallowed"], [[67808, 67826], "valid"], [[67827, 67827], "disallowed"], [[67828, 67829], "valid"], [[67830, 67834], "disallowed"], [[67835, 67839], "valid", [], "NV8"], [[67840, 67861], "valid"], [[67862, 67865], "valid", [], "NV8"], [[67866, 67867], "valid", [], "NV8"], [[67868, 67870], "disallowed"], [[67871, 67871], "valid", [], "NV8"], [[67872, 67897], "valid"], [[67898, 67902], "disallowed"], [[67903, 67903], "valid", [], "NV8"], [[67904, 67967], "disallowed"], [[67968, 68023], "valid"], [[68024, 68027], "disallowed"], [[68028, 68029], "valid", [], "NV8"], [[68030, 68031], "valid"], [[68032, 68047], "valid", [], "NV8"], [[68048, 68049], "disallowed"], [[68050, 68095], "valid", [], "NV8"], [[68096, 68099], "valid"], [[68100, 68100], "disallowed"], [[68101, 68102], "valid"], [[68103, 68107], "disallowed"], [[68108, 68115], "valid"], [[68116, 68116], "disallowed"], [[68117, 68119], "valid"], [[68120, 68120], "disallowed"], [[68121, 68147], "valid"], [[68148, 68151], "disallowed"], [[68152, 68154], "valid"], [[68155, 68158], "disallowed"], [[68159, 68159], "valid"], [[68160, 68167], "valid", [], "NV8"], [[68168, 68175], "disallowed"], [[68176, 68184], "valid", [], "NV8"], [[68185, 68191], "disallowed"], [[68192, 68220], "valid"], [[68221, 68223], "valid", [], "NV8"], [[68224, 68252], "valid"], [[68253, 68255], "valid", [], "NV8"], [[68256, 68287], "disallowed"], [[68288, 68295], "valid"], [[68296, 68296], "valid", [], "NV8"], [[68297, 68326], "valid"], [[68327, 68330], "disallowed"], [[68331, 68342], "valid", [], "NV8"], [[68343, 68351], "disallowed"], [[68352, 68405], "valid"], [[68406, 68408], "disallowed"], [[68409, 68415], "valid", [], "NV8"], [[68416, 68437], "valid"], [[68438, 68439], "disallowed"], [[68440, 68447], "valid", [], "NV8"], [[68448, 68466], "valid"], [[68467, 68471], "disallowed"], [[68472, 68479], "valid", [], "NV8"], [[68480, 68497], "valid"], [[68498, 68504], "disallowed"], [[68505, 68508], "valid", [], "NV8"], [[68509, 68520], "disallowed"], [[68521, 68527], "valid", [], "NV8"], [[68528, 68607], "disallowed"], [[68608, 68680], "valid"], [[68681, 68735], "disallowed"], [[68736, 68736], "mapped", [68800]], [[68737, 68737], "mapped", [68801]], [[68738, 68738], "mapped", [68802]], [[68739, 68739], "mapped", [68803]], [[68740, 68740], "mapped", [68804]], [[68741, 68741], "mapped", [68805]], [[68742, 68742], "mapped", [68806]], [[68743, 68743], "mapped", [68807]], [[68744, 68744], "mapped", [68808]], [[68745, 68745], "mapped", [68809]], [[68746, 68746], "mapped", [68810]], [[68747, 68747], "mapped", [68811]], [[68748, 68748], "mapped", [68812]], [[68749, 68749], "mapped", [68813]], [[68750, 68750], "mapped", [68814]], [[68751, 68751], "mapped", [68815]], [[68752, 68752], "mapped", [68816]], [[68753, 68753], "mapped", [68817]], [[68754, 68754], "mapped", [68818]], [[68755, 68755], "mapped", [68819]], [[68756, 68756], "mapped", [68820]], [[68757, 68757], "mapped", [68821]], [[68758, 68758], "mapped", [68822]], [[68759, 68759], "mapped", [68823]], [[68760, 68760], "mapped", [68824]], [[68761, 68761], "mapped", [68825]], [[68762, 68762], "mapped", [68826]], [[68763, 68763], "mapped", [68827]], [[68764, 68764], "mapped", [68828]], [[68765, 68765], "mapped", [68829]], [[68766, 68766], "mapped", [68830]], [[68767, 68767], "mapped", [68831]], [[68768, 68768], "mapped", [68832]], [[68769, 68769], "mapped", [68833]], [[68770, 68770], "mapped", [68834]], [[68771, 68771], "mapped", [68835]], [[68772, 68772], "mapped", [68836]], [[68773, 68773], "mapped", [68837]], [[68774, 68774], "mapped", [68838]], [[68775, 68775], "mapped", [68839]], [[68776, 68776], "mapped", [68840]], [[68777, 68777], "mapped", [68841]], [[68778, 68778], "mapped", [68842]], [[68779, 68779], "mapped", [68843]], [[68780, 68780], "mapped", [68844]], [[68781, 68781], "mapped", [68845]], [[68782, 68782], "mapped", [68846]], [[68783, 68783], "mapped", [68847]], [[68784, 68784], "mapped", [68848]], [[68785, 68785], "mapped", [68849]], [[68786, 68786], "mapped", [68850]], [[68787, 68799], "disallowed"], [[68800, 68850], "valid"], [[68851, 68857], "disallowed"], [[68858, 68863], "valid", [], "NV8"], [[68864, 69215], "disallowed"], [[69216, 69246], "valid", [], "NV8"], [[69247, 69631], "disallowed"], [[69632, 69702], "valid"], [[69703, 69709], "valid", [], "NV8"], [[69710, 69713], "disallowed"], [[69714, 69733], "valid", [], "NV8"], [[69734, 69743], "valid"], [[69744, 69758], "disallowed"], [[69759, 69759], "valid"], [[69760, 69818], "valid"], [[69819, 69820], "valid", [], "NV8"], [[69821, 69821], "disallowed"], [[69822, 69825], "valid", [], "NV8"], [[69826, 69839], "disallowed"], [[69840, 69864], "valid"], [[69865, 69871], "disallowed"], [[69872, 69881], "valid"], [[69882, 69887], "disallowed"], [[69888, 69940], "valid"], [[69941, 69941], "disallowed"], [[69942, 69951], "valid"], [[69952, 69955], "valid", [], "NV8"], [[69956, 69967], "disallowed"], [[69968, 70003], "valid"], [[70004, 70005], "valid", [], "NV8"], [[70006, 70006], "valid"], [[70007, 70015], "disallowed"], [[70016, 70084], "valid"], [[70085, 70088], "valid", [], "NV8"], [[70089, 70089], "valid", [], "NV8"], [[70090, 70092], "valid"], [[70093, 70093], "valid", [], "NV8"], [[70094, 70095], "disallowed"], [[70096, 70105], "valid"], [[70106, 70106], "valid"], [[70107, 70107], "valid", [], "NV8"], [[70108, 70108], "valid"], [[70109, 70111], "valid", [], "NV8"], [[70112, 70112], "disallowed"], [[70113, 70132], "valid", [], "NV8"], [[70133, 70143], "disallowed"], [[70144, 70161], "valid"], [[70162, 70162], "disallowed"], [[70163, 70199], "valid"], [[70200, 70205], "valid", [], "NV8"], [[70206, 70271], "disallowed"], [[70272, 70278], "valid"], [[70279, 70279], "disallowed"], [[70280, 70280], "valid"], [[70281, 70281], "disallowed"], [[70282, 70285], "valid"], [[70286, 70286], "disallowed"], [[70287, 70301], "valid"], [[70302, 70302], "disallowed"], [[70303, 70312], "valid"], [[70313, 70313], "valid", [], "NV8"], [[70314, 70319], "disallowed"], [[70320, 70378], "valid"], [[70379, 70383], "disallowed"], [[70384, 70393], "valid"], [[70394, 70399], "disallowed"], [[70400, 70400], "valid"], [[70401, 70403], "valid"], [[70404, 70404], "disallowed"], [[70405, 70412], "valid"], [[70413, 70414], "disallowed"], [[70415, 70416], "valid"], [[70417, 70418], "disallowed"], [[70419, 70440], "valid"], [[70441, 70441], "disallowed"], [[70442, 70448], "valid"], [[70449, 70449], "disallowed"], [[70450, 70451], "valid"], [[70452, 70452], "disallowed"], [[70453, 70457], "valid"], [[70458, 70459], "disallowed"], [[70460, 70468], "valid"], [[70469, 70470], "disallowed"], [[70471, 70472], "valid"], [[70473, 70474], "disallowed"], [[70475, 70477], "valid"], [[70478, 70479], "disallowed"], [[70480, 70480], "valid"], [[70481, 70486], "disallowed"], [[70487, 70487], "valid"], [[70488, 70492], "disallowed"], [[70493, 70499], "valid"], [[70500, 70501], "disallowed"], [[70502, 70508], "valid"], [[70509, 70511], "disallowed"], [[70512, 70516], "valid"], [[70517, 70783], "disallowed"], [[70784, 70853], "valid"], [[70854, 70854], "valid", [], "NV8"], [[70855, 70855], "valid"], [[70856, 70863], "disallowed"], [[70864, 70873], "valid"], [[70874, 71039], "disallowed"], [[71040, 71093], "valid"], [[71094, 71095], "disallowed"], [[71096, 71104], "valid"], [[71105, 71113], "valid", [], "NV8"], [[71114, 71127], "valid", [], "NV8"], [[71128, 71133], "valid"], [[71134, 71167], "disallowed"], [[71168, 71232], "valid"], [[71233, 71235], "valid", [], "NV8"], [[71236, 71236], "valid"], [[71237, 71247], "disallowed"], [[71248, 71257], "valid"], [[71258, 71295], "disallowed"], [[71296, 71351], "valid"], [[71352, 71359], "disallowed"], [[71360, 71369], "valid"], [[71370, 71423], "disallowed"], [[71424, 71449], "valid"], [[71450, 71452], "disallowed"], [[71453, 71467], "valid"], [[71468, 71471], "disallowed"], [[71472, 71481], "valid"], [[71482, 71487], "valid", [], "NV8"], [[71488, 71839], "disallowed"], [[71840, 71840], "mapped", [71872]], [[71841, 71841], "mapped", [71873]], [[71842, 71842], "mapped", [71874]], [[71843, 71843], "mapped", [71875]], [[71844, 71844], "mapped", [71876]], [[71845, 71845], "mapped", [71877]], [[71846, 71846], "mapped", [71878]], [[71847, 71847], "mapped", [71879]], [[71848, 71848], "mapped", [71880]], [[71849, 71849], "mapped", [71881]], [[71850, 71850], "mapped", [71882]], [[71851, 71851], "mapped", [71883]], [[71852, 71852], "mapped", [71884]], [[71853, 71853], "mapped", [71885]], [[71854, 71854], "mapped", [71886]], [[71855, 71855], "mapped", [71887]], [[71856, 71856], "mapped", [71888]], [[71857, 71857], "mapped", [71889]], [[71858, 71858], "mapped", [71890]], [[71859, 71859], "mapped", [71891]], [[71860, 71860], "mapped", [71892]], [[71861, 71861], "mapped", [71893]], [[71862, 71862], "mapped", [71894]], [[71863, 71863], "mapped", [71895]], [[71864, 71864], "mapped", [71896]], [[71865, 71865], "mapped", [71897]], [[71866, 71866], "mapped", [71898]], [[71867, 71867], "mapped", [71899]], [[71868, 71868], "mapped", [71900]], [[71869, 71869], "mapped", [71901]], [[71870, 71870], "mapped", [71902]], [[71871, 71871], "mapped", [71903]], [[71872, 71913], "valid"], [[71914, 71922], "valid", [], "NV8"], [[71923, 71934], "disallowed"], [[71935, 71935], "valid"], [[71936, 72383], "disallowed"], [[72384, 72440], "valid"], [[72441, 73727], "disallowed"], [[73728, 74606], "valid"], [[74607, 74648], "valid"], [[74649, 74649], "valid"], [[74650, 74751], "disallowed"], [[74752, 74850], "valid", [], "NV8"], [[74851, 74862], "valid", [], "NV8"], [[74863, 74863], "disallowed"], [[74864, 74867], "valid", [], "NV8"], [[74868, 74868], "valid", [], "NV8"], [[74869, 74879], "disallowed"], [[74880, 75075], "valid"], [[75076, 77823], "disallowed"], [[77824, 78894], "valid"], [[78895, 82943], "disallowed"], [[82944, 83526], "valid"], [[83527, 92159], "disallowed"], [[92160, 92728], "valid"], [[92729, 92735], "disallowed"], [[92736, 92766], "valid"], [[92767, 92767], "disallowed"], [[92768, 92777], "valid"], [[92778, 92781], "disallowed"], [[92782, 92783], "valid", [], "NV8"], [[92784, 92879], "disallowed"], [[92880, 92909], "valid"], [[92910, 92911], "disallowed"], [[92912, 92916], "valid"], [[92917, 92917], "valid", [], "NV8"], [[92918, 92927], "disallowed"], [[92928, 92982], "valid"], [[92983, 92991], "valid", [], "NV8"], [[92992, 92995], "valid"], [[92996, 92997], "valid", [], "NV8"], [[92998, 93007], "disallowed"], [[93008, 93017], "valid"], [[93018, 93018], "disallowed"], [[93019, 93025], "valid", [], "NV8"], [[93026, 93026], "disallowed"], [[93027, 93047], "valid"], [[93048, 93052], "disallowed"], [[93053, 93071], "valid"], [[93072, 93951], "disallowed"], [[93952, 94020], "valid"], [[94021, 94031], "disallowed"], [[94032, 94078], "valid"], [[94079, 94094], "disallowed"], [[94095, 94111], "valid"], [[94112, 110591], "disallowed"], [[110592, 110593], "valid"], [[110594, 113663], "disallowed"], [[113664, 113770], "valid"], [[113771, 113775], "disallowed"], [[113776, 113788], "valid"], [[113789, 113791], "disallowed"], [[113792, 113800], "valid"], [[113801, 113807], "disallowed"], [[113808, 113817], "valid"], [[113818, 113819], "disallowed"], [[113820, 113820], "valid", [], "NV8"], [[113821, 113822], "valid"], [[113823, 113823], "valid", [], "NV8"], [[113824, 113827], "ignored"], [[113828, 118783], "disallowed"], [[118784, 119029], "valid", [], "NV8"], [[119030, 119039], "disallowed"], [[119040, 119078], "valid", [], "NV8"], [[119079, 119080], "disallowed"], [[119081, 119081], "valid", [], "NV8"], [[119082, 119133], "valid", [], "NV8"], [[119134, 119134], "mapped", [119127, 119141]], [[119135, 119135], "mapped", [119128, 119141]], [[119136, 119136], "mapped", [119128, 119141, 119150]], [[119137, 119137], "mapped", [119128, 119141, 119151]], [[119138, 119138], "mapped", [119128, 119141, 119152]], [[119139, 119139], "mapped", [119128, 119141, 119153]], [[119140, 119140], "mapped", [119128, 119141, 119154]], [[119141, 119154], "valid", [], "NV8"], [[119155, 119162], "disallowed"], [[119163, 119226], "valid", [], "NV8"], [[119227, 119227], "mapped", [119225, 119141]], [[119228, 119228], "mapped", [119226, 119141]], [[119229, 119229], "mapped", [119225, 119141, 119150]], [[119230, 119230], "mapped", [119226, 119141, 119150]], [[119231, 119231], "mapped", [119225, 119141, 119151]], [[119232, 119232], "mapped", [119226, 119141, 119151]], [[119233, 119261], "valid", [], "NV8"], [[119262, 119272], "valid", [], "NV8"], [[119273, 119295], "disallowed"], [[119296, 119365], "valid", [], "NV8"], [[119366, 119551], "disallowed"], [[119552, 119638], "valid", [], "NV8"], [[119639, 119647], "disallowed"], [[119648, 119665], "valid", [], "NV8"], [[119666, 119807], "disallowed"], [[119808, 119808], "mapped", [97]], [[119809, 119809], "mapped", [98]], [[119810, 119810], "mapped", [99]], [[119811, 119811], "mapped", [100]], [[119812, 119812], "mapped", [101]], [[119813, 119813], "mapped", [102]], [[119814, 119814], "mapped", [103]], [[119815, 119815], "mapped", [104]], [[119816, 119816], "mapped", [105]], [[119817, 119817], "mapped", [106]], [[119818, 119818], "mapped", [107]], [[119819, 119819], "mapped", [108]], [[119820, 119820], "mapped", [109]], [[119821, 119821], "mapped", [110]], [[119822, 119822], "mapped", [111]], [[119823, 119823], "mapped", [112]], [[119824, 119824], "mapped", [113]], [[119825, 119825], "mapped", [114]], [[119826, 119826], "mapped", [115]], [[119827, 119827], "mapped", [116]], [[119828, 119828], "mapped", [117]], [[119829, 119829], "mapped", [118]], [[119830, 119830], "mapped", [119]], [[119831, 119831], "mapped", [120]], [[119832, 119832], "mapped", [121]], [[119833, 119833], "mapped", [122]], [[119834, 119834], "mapped", [97]], [[119835, 119835], "mapped", [98]], [[119836, 119836], "mapped", [99]], [[119837, 119837], "mapped", [100]], [[119838, 119838], "mapped", [101]], [[119839, 119839], "mapped", [102]], [[119840, 119840], "mapped", [103]], [[119841, 119841], "mapped", [104]], [[119842, 119842], "mapped", [105]], [[119843, 119843], "mapped", [106]], [[119844, 119844], "mapped", [107]], [[119845, 119845], "mapped", [108]], [[119846, 119846], "mapped", [109]], [[119847, 119847], "mapped", [110]], [[119848, 119848], "mapped", [111]], [[119849, 119849], "mapped", [112]], [[119850, 119850], "mapped", [113]], [[119851, 119851], "mapped", [114]], [[119852, 119852], "mapped", [115]], [[119853, 119853], "mapped", [116]], [[119854, 119854], "mapped", [117]], [[119855, 119855], "mapped", [118]], [[119856, 119856], "mapped", [119]], [[119857, 119857], "mapped", [120]], [[119858, 119858], "mapped", [121]], [[119859, 119859], "mapped", [122]], [[119860, 119860], "mapped", [97]], [[119861, 119861], "mapped", [98]], [[119862, 119862], "mapped", [99]], [[119863, 119863], "mapped", [100]], [[119864, 119864], "mapped", [101]], [[119865, 119865], "mapped", [102]], [[119866, 119866], "mapped", [103]], [[119867, 119867], "mapped", [104]], [[119868, 119868], "mapped", [105]], [[119869, 119869], "mapped", [106]], [[119870, 119870], "mapped", [107]], [[119871, 119871], "mapped", [108]], [[119872, 119872], "mapped", [109]], [[119873, 119873], "mapped", [110]], [[119874, 119874], "mapped", [111]], [[119875, 119875], "mapped", [112]], [[119876, 119876], "mapped", [113]], [[119877, 119877], "mapped", [114]], [[119878, 119878], "mapped", [115]], [[119879, 119879], "mapped", [116]], [[119880, 119880], "mapped", [117]], [[119881, 119881], "mapped", [118]], [[119882, 119882], "mapped", [119]], [[119883, 119883], "mapped", [120]], [[119884, 119884], "mapped", [121]], [[119885, 119885], "mapped", [122]], [[119886, 119886], "mapped", [97]], [[119887, 119887], "mapped", [98]], [[119888, 119888], "mapped", [99]], [[119889, 119889], "mapped", [100]], [[119890, 119890], "mapped", [101]], [[119891, 119891], "mapped", [102]], [[119892, 119892], "mapped", [103]], [[119893, 119893], "disallowed"], [[119894, 119894], "mapped", [105]], [[119895, 119895], "mapped", [106]], [[119896, 119896], "mapped", [107]], [[119897, 119897], "mapped", [108]], [[119898, 119898], "mapped", [109]], [[119899, 119899], "mapped", [110]], [[119900, 119900], "mapped", [111]], [[119901, 119901], "mapped", [112]], [[119902, 119902], "mapped", [113]], [[119903, 119903], "mapped", [114]], [[119904, 119904], "mapped", [115]], [[119905, 119905], "mapped", [116]], [[119906, 119906], "mapped", [117]], [[119907, 119907], "mapped", [118]], [[119908, 119908], "mapped", [119]], [[119909, 119909], "mapped", [120]], [[119910, 119910], "mapped", [121]], [[119911, 119911], "mapped", [122]], [[119912, 119912], "mapped", [97]], [[119913, 119913], "mapped", [98]], [[119914, 119914], "mapped", [99]], [[119915, 119915], "mapped", [100]], [[119916, 119916], "mapped", [101]], [[119917, 119917], "mapped", [102]], [[119918, 119918], "mapped", [103]], [[119919, 119919], "mapped", [104]], [[119920, 119920], "mapped", [105]], [[119921, 119921], "mapped", [106]], [[119922, 119922], "mapped", [107]], [[119923, 119923], "mapped", [108]], [[119924, 119924], "mapped", [109]], [[119925, 119925], "mapped", [110]], [[119926, 119926], "mapped", [111]], [[119927, 119927], "mapped", [112]], [[119928, 119928], "mapped", [113]], [[119929, 119929], "mapped", [114]], [[119930, 119930], "mapped", [115]], [[119931, 119931], "mapped", [116]], [[119932, 119932], "mapped", [117]], [[119933, 119933], "mapped", [118]], [[119934, 119934], "mapped", [119]], [[119935, 119935], "mapped", [120]], [[119936, 119936], "mapped", [121]], [[119937, 119937], "mapped", [122]], [[119938, 119938], "mapped", [97]], [[119939, 119939], "mapped", [98]], [[119940, 119940], "mapped", [99]], [[119941, 119941], "mapped", [100]], [[119942, 119942], "mapped", [101]], [[119943, 119943], "mapped", [102]], [[119944, 119944], "mapped", [103]], [[119945, 119945], "mapped", [104]], [[119946, 119946], "mapped", [105]], [[119947, 119947], "mapped", [106]], [[119948, 119948], "mapped", [107]], [[119949, 119949], "mapped", [108]], [[119950, 119950], "mapped", [109]], [[119951, 119951], "mapped", [110]], [[119952, 119952], "mapped", [111]], [[119953, 119953], "mapped", [112]], [[119954, 119954], "mapped", [113]], [[119955, 119955], "mapped", [114]], [[119956, 119956], "mapped", [115]], [[119957, 119957], "mapped", [116]], [[119958, 119958], "mapped", [117]], [[119959, 119959], "mapped", [118]], [[119960, 119960], "mapped", [119]], [[119961, 119961], "mapped", [120]], [[119962, 119962], "mapped", [121]], [[119963, 119963], "mapped", [122]], [[119964, 119964], "mapped", [97]], [[119965, 119965], "disallowed"], [[119966, 119966], "mapped", [99]], [[119967, 119967], "mapped", [100]], [[119968, 119969], "disallowed"], [[119970, 119970], "mapped", [103]], [[119971, 119972], "disallowed"], [[119973, 119973], "mapped", [106]], [[119974, 119974], "mapped", [107]], [[119975, 119976], "disallowed"], [[119977, 119977], "mapped", [110]], [[119978, 119978], "mapped", [111]], [[119979, 119979], "mapped", [112]], [[119980, 119980], "mapped", [113]], [[119981, 119981], "disallowed"], [[119982, 119982], "mapped", [115]], [[119983, 119983], "mapped", [116]], [[119984, 119984], "mapped", [117]], [[119985, 119985], "mapped", [118]], [[119986, 119986], "mapped", [119]], [[119987, 119987], "mapped", [120]], [[119988, 119988], "mapped", [121]], [[119989, 119989], "mapped", [122]], [[119990, 119990], "mapped", [97]], [[119991, 119991], "mapped", [98]], [[119992, 119992], "mapped", [99]], [[119993, 119993], "mapped", [100]], [[119994, 119994], "disallowed"], [[119995, 119995], "mapped", [102]], [[119996, 119996], "disallowed"], [[119997, 119997], "mapped", [104]], [[119998, 119998], "mapped", [105]], [[119999, 119999], "mapped", [106]], [[12e4, 12e4], "mapped", [107]], [[120001, 120001], "mapped", [108]], [[120002, 120002], "mapped", [109]], [[120003, 120003], "mapped", [110]], [[120004, 120004], "disallowed"], [[120005, 120005], "mapped", [112]], [[120006, 120006], "mapped", [113]], [[120007, 120007], "mapped", [114]], [[120008, 120008], "mapped", [115]], [[120009, 120009], "mapped", [116]], [[120010, 120010], "mapped", [117]], [[120011, 120011], "mapped", [118]], [[120012, 120012], "mapped", [119]], [[120013, 120013], "mapped", [120]], [[120014, 120014], "mapped", [121]], [[120015, 120015], "mapped", [122]], [[120016, 120016], "mapped", [97]], [[120017, 120017], "mapped", [98]], [[120018, 120018], "mapped", [99]], [[120019, 120019], "mapped", [100]], [[120020, 120020], "mapped", [101]], [[120021, 120021], "mapped", [102]], [[120022, 120022], "mapped", [103]], [[120023, 120023], "mapped", [104]], [[120024, 120024], "mapped", [105]], [[120025, 120025], "mapped", [106]], [[120026, 120026], "mapped", [107]], [[120027, 120027], "mapped", [108]], [[120028, 120028], "mapped", [109]], [[120029, 120029], "mapped", [110]], [[120030, 120030], "mapped", [111]], [[120031, 120031], "mapped", [112]], [[120032, 120032], "mapped", [113]], [[120033, 120033], "mapped", [114]], [[120034, 120034], "mapped", [115]], [[120035, 120035], "mapped", [116]], [[120036, 120036], "mapped", [117]], [[120037, 120037], "mapped", [118]], [[120038, 120038], "mapped", [119]], [[120039, 120039], "mapped", [120]], [[120040, 120040], "mapped", [121]], [[120041, 120041], "mapped", [122]], [[120042, 120042], "mapped", [97]], [[120043, 120043], "mapped", [98]], [[120044, 120044], "mapped", [99]], [[120045, 120045], "mapped", [100]], [[120046, 120046], "mapped", [101]], [[120047, 120047], "mapped", [102]], [[120048, 120048], "mapped", [103]], [[120049, 120049], "mapped", [104]], [[120050, 120050], "mapped", [105]], [[120051, 120051], "mapped", [106]], [[120052, 120052], "mapped", [107]], [[120053, 120053], "mapped", [108]], [[120054, 120054], "mapped", [109]], [[120055, 120055], "mapped", [110]], [[120056, 120056], "mapped", [111]], [[120057, 120057], "mapped", [112]], [[120058, 120058], "mapped", [113]], [[120059, 120059], "mapped", [114]], [[120060, 120060], "mapped", [115]], [[120061, 120061], "mapped", [116]], [[120062, 120062], "mapped", [117]], [[120063, 120063], "mapped", [118]], [[120064, 120064], "mapped", [119]], [[120065, 120065], "mapped", [120]], [[120066, 120066], "mapped", [121]], [[120067, 120067], "mapped", [122]], [[120068, 120068], "mapped", [97]], [[120069, 120069], "mapped", [98]], [[120070, 120070], "disallowed"], [[120071, 120071], "mapped", [100]], [[120072, 120072], "mapped", [101]], [[120073, 120073], "mapped", [102]], [[120074, 120074], "mapped", [103]], [[120075, 120076], "disallowed"], [[120077, 120077], "mapped", [106]], [[120078, 120078], "mapped", [107]], [[120079, 120079], "mapped", [108]], [[120080, 120080], "mapped", [109]], [[120081, 120081], "mapped", [110]], [[120082, 120082], "mapped", [111]], [[120083, 120083], "mapped", [112]], [[120084, 120084], "mapped", [113]], [[120085, 120085], "disallowed"], [[120086, 120086], "mapped", [115]], [[120087, 120087], "mapped", [116]], [[120088, 120088], "mapped", [117]], [[120089, 120089], "mapped", [118]], [[120090, 120090], "mapped", [119]], [[120091, 120091], "mapped", [120]], [[120092, 120092], "mapped", [121]], [[120093, 120093], "disallowed"], [[120094, 120094], "mapped", [97]], [[120095, 120095], "mapped", [98]], [[120096, 120096], "mapped", [99]], [[120097, 120097], "mapped", [100]], [[120098, 120098], "mapped", [101]], [[120099, 120099], "mapped", [102]], [[120100, 120100], "mapped", [103]], [[120101, 120101], "mapped", [104]], [[120102, 120102], "mapped", [105]], [[120103, 120103], "mapped", [106]], [[120104, 120104], "mapped", [107]], [[120105, 120105], "mapped", [108]], [[120106, 120106], "mapped", [109]], [[120107, 120107], "mapped", [110]], [[120108, 120108], "mapped", [111]], [[120109, 120109], "mapped", [112]], [[120110, 120110], "mapped", [113]], [[120111, 120111], "mapped", [114]], [[120112, 120112], "mapped", [115]], [[120113, 120113], "mapped", [116]], [[120114, 120114], "mapped", [117]], [[120115, 120115], "mapped", [118]], [[120116, 120116], "mapped", [119]], [[120117, 120117], "mapped", [120]], [[120118, 120118], "mapped", [121]], [[120119, 120119], "mapped", [122]], [[120120, 120120], "mapped", [97]], [[120121, 120121], "mapped", [98]], [[120122, 120122], "disallowed"], [[120123, 120123], "mapped", [100]], [[120124, 120124], "mapped", [101]], [[120125, 120125], "mapped", [102]], [[120126, 120126], "mapped", [103]], [[120127, 120127], "disallowed"], [[120128, 120128], "mapped", [105]], [[120129, 120129], "mapped", [106]], [[120130, 120130], "mapped", [107]], [[120131, 120131], "mapped", [108]], [[120132, 120132], "mapped", [109]], [[120133, 120133], "disallowed"], [[120134, 120134], "mapped", [111]], [[120135, 120137], "disallowed"], [[120138, 120138], "mapped", [115]], [[120139, 120139], "mapped", [116]], [[120140, 120140], "mapped", [117]], [[120141, 120141], "mapped", [118]], [[120142, 120142], "mapped", [119]], [[120143, 120143], "mapped", [120]], [[120144, 120144], "mapped", [121]], [[120145, 120145], "disallowed"], [[120146, 120146], "mapped", [97]], [[120147, 120147], "mapped", [98]], [[120148, 120148], "mapped", [99]], [[120149, 120149], "mapped", [100]], [[120150, 120150], "mapped", [101]], [[120151, 120151], "mapped", [102]], [[120152, 120152], "mapped", [103]], [[120153, 120153], "mapped", [104]], [[120154, 120154], "mapped", [105]], [[120155, 120155], "mapped", [106]], [[120156, 120156], "mapped", [107]], [[120157, 120157], "mapped", [108]], [[120158, 120158], "mapped", [109]], [[120159, 120159], "mapped", [110]], [[120160, 120160], "mapped", [111]], [[120161, 120161], "mapped", [112]], [[120162, 120162], "mapped", [113]], [[120163, 120163], "mapped", [114]], [[120164, 120164], "mapped", [115]], [[120165, 120165], "mapped", [116]], [[120166, 120166], "mapped", [117]], [[120167, 120167], "mapped", [118]], [[120168, 120168], "mapped", [119]], [[120169, 120169], "mapped", [120]], [[120170, 120170], "mapped", [121]], [[120171, 120171], "mapped", [122]], [[120172, 120172], "mapped", [97]], [[120173, 120173], "mapped", [98]], [[120174, 120174], "mapped", [99]], [[120175, 120175], "mapped", [100]], [[120176, 120176], "mapped", [101]], [[120177, 120177], "mapped", [102]], [[120178, 120178], "mapped", [103]], [[120179, 120179], "mapped", [104]], [[120180, 120180], "mapped", [105]], [[120181, 120181], "mapped", [106]], [[120182, 120182], "mapped", [107]], [[120183, 120183], "mapped", [108]], [[120184, 120184], "mapped", [109]], [[120185, 120185], "mapped", [110]], [[120186, 120186], "mapped", [111]], [[120187, 120187], "mapped", [112]], [[120188, 120188], "mapped", [113]], [[120189, 120189], "mapped", [114]], [[120190, 120190], "mapped", [115]], [[120191, 120191], "mapped", [116]], [[120192, 120192], "mapped", [117]], [[120193, 120193], "mapped", [118]], [[120194, 120194], "mapped", [119]], [[120195, 120195], "mapped", [120]], [[120196, 120196], "mapped", [121]], [[120197, 120197], "mapped", [122]], [[120198, 120198], "mapped", [97]], [[120199, 120199], "mapped", [98]], [[120200, 120200], "mapped", [99]], [[120201, 120201], "mapped", [100]], [[120202, 120202], "mapped", [101]], [[120203, 120203], "mapped", [102]], [[120204, 120204], "mapped", [103]], [[120205, 120205], "mapped", [104]], [[120206, 120206], "mapped", [105]], [[120207, 120207], "mapped", [106]], [[120208, 120208], "mapped", [107]], [[120209, 120209], "mapped", [108]], [[120210, 120210], "mapped", [109]], [[120211, 120211], "mapped", [110]], [[120212, 120212], "mapped", [111]], [[120213, 120213], "mapped", [112]], [[120214, 120214], "mapped", [113]], [[120215, 120215], "mapped", [114]], [[120216, 120216], "mapped", [115]], [[120217, 120217], "mapped", [116]], [[120218, 120218], "mapped", [117]], [[120219, 120219], "mapped", [118]], [[120220, 120220], "mapped", [119]], [[120221, 120221], "mapped", [120]], [[120222, 120222], "mapped", [121]], [[120223, 120223], "mapped", [122]], [[120224, 120224], "mapped", [97]], [[120225, 120225], "mapped", [98]], [[120226, 120226], "mapped", [99]], [[120227, 120227], "mapped", [100]], [[120228, 120228], "mapped", [101]], [[120229, 120229], "mapped", [102]], [[120230, 120230], "mapped", [103]], [[120231, 120231], "mapped", [104]], [[120232, 120232], "mapped", [105]], [[120233, 120233], "mapped", [106]], [[120234, 120234], "mapped", [107]], [[120235, 120235], "mapped", [108]], [[120236, 120236], "mapped", [109]], [[120237, 120237], "mapped", [110]], [[120238, 120238], "mapped", [111]], [[120239, 120239], "mapped", [112]], [[120240, 120240], "mapped", [113]], [[120241, 120241], "mapped", [114]], [[120242, 120242], "mapped", [115]], [[120243, 120243], "mapped", [116]], [[120244, 120244], "mapped", [117]], [[120245, 120245], "mapped", [118]], [[120246, 120246], "mapped", [119]], [[120247, 120247], "mapped", [120]], [[120248, 120248], "mapped", [121]], [[120249, 120249], "mapped", [122]], [[120250, 120250], "mapped", [97]], [[120251, 120251], "mapped", [98]], [[120252, 120252], "mapped", [99]], [[120253, 120253], "mapped", [100]], [[120254, 120254], "mapped", [101]], [[120255, 120255], "mapped", [102]], [[120256, 120256], "mapped", [103]], [[120257, 120257], "mapped", [104]], [[120258, 120258], "mapped", [105]], [[120259, 120259], "mapped", [106]], [[120260, 120260], "mapped", [107]], [[120261, 120261], "mapped", [108]], [[120262, 120262], "mapped", [109]], [[120263, 120263], "mapped", [110]], [[120264, 120264], "mapped", [111]], [[120265, 120265], "mapped", [112]], [[120266, 120266], "mapped", [113]], [[120267, 120267], "mapped", [114]], [[120268, 120268], "mapped", [115]], [[120269, 120269], "mapped", [116]], [[120270, 120270], "mapped", [117]], [[120271, 120271], "mapped", [118]], [[120272, 120272], "mapped", [119]], [[120273, 120273], "mapped", [120]], [[120274, 120274], "mapped", [121]], [[120275, 120275], "mapped", [122]], [[120276, 120276], "mapped", [97]], [[120277, 120277], "mapped", [98]], [[120278, 120278], "mapped", [99]], [[120279, 120279], "mapped", [100]], [[120280, 120280], "mapped", [101]], [[120281, 120281], "mapped", [102]], [[120282, 120282], "mapped", [103]], [[120283, 120283], "mapped", [104]], [[120284, 120284], "mapped", [105]], [[120285, 120285], "mapped", [106]], [[120286, 120286], "mapped", [107]], [[120287, 120287], "mapped", [108]], [[120288, 120288], "mapped", [109]], [[120289, 120289], "mapped", [110]], [[120290, 120290], "mapped", [111]], [[120291, 120291], "mapped", [112]], [[120292, 120292], "mapped", [113]], [[120293, 120293], "mapped", [114]], [[120294, 120294], "mapped", [115]], [[120295, 120295], "mapped", [116]], [[120296, 120296], "mapped", [117]], [[120297, 120297], "mapped", [118]], [[120298, 120298], "mapped", [119]], [[120299, 120299], "mapped", [120]], [[120300, 120300], "mapped", [121]], [[120301, 120301], "mapped", [122]], [[120302, 120302], "mapped", [97]], [[120303, 120303], "mapped", [98]], [[120304, 120304], "mapped", [99]], [[120305, 120305], "mapped", [100]], [[120306, 120306], "mapped", [101]], [[120307, 120307], "mapped", [102]], [[120308, 120308], "mapped", [103]], [[120309, 120309], "mapped", [104]], [[120310, 120310], "mapped", [105]], [[120311, 120311], "mapped", [106]], [[120312, 120312], "mapped", [107]], [[120313, 120313], "mapped", [108]], [[120314, 120314], "mapped", [109]], [[120315, 120315], "mapped", [110]], [[120316, 120316], "mapped", [111]], [[120317, 120317], "mapped", [112]], [[120318, 120318], "mapped", [113]], [[120319, 120319], "mapped", [114]], [[120320, 120320], "mapped", [115]], [[120321, 120321], "mapped", [116]], [[120322, 120322], "mapped", [117]], [[120323, 120323], "mapped", [118]], [[120324, 120324], "mapped", [119]], [[120325, 120325], "mapped", [120]], [[120326, 120326], "mapped", [121]], [[120327, 120327], "mapped", [122]], [[120328, 120328], "mapped", [97]], [[120329, 120329], "mapped", [98]], [[120330, 120330], "mapped", [99]], [[120331, 120331], "mapped", [100]], [[120332, 120332], "mapped", [101]], [[120333, 120333], "mapped", [102]], [[120334, 120334], "mapped", [103]], [[120335, 120335], "mapped", [104]], [[120336, 120336], "mapped", [105]], [[120337, 120337], "mapped", [106]], [[120338, 120338], "mapped", [107]], [[120339, 120339], "mapped", [108]], [[120340, 120340], "mapped", [109]], [[120341, 120341], "mapped", [110]], [[120342, 120342], "mapped", [111]], [[120343, 120343], "mapped", [112]], [[120344, 120344], "mapped", [113]], [[120345, 120345], "mapped", [114]], [[120346, 120346], "mapped", [115]], [[120347, 120347], "mapped", [116]], [[120348, 120348], "mapped", [117]], [[120349, 120349], "mapped", [118]], [[120350, 120350], "mapped", [119]], [[120351, 120351], "mapped", [120]], [[120352, 120352], "mapped", [121]], [[120353, 120353], "mapped", [122]], [[120354, 120354], "mapped", [97]], [[120355, 120355], "mapped", [98]], [[120356, 120356], "mapped", [99]], [[120357, 120357], "mapped", [100]], [[120358, 120358], "mapped", [101]], [[120359, 120359], "mapped", [102]], [[120360, 120360], "mapped", [103]], [[120361, 120361], "mapped", [104]], [[120362, 120362], "mapped", [105]], [[120363, 120363], "mapped", [106]], [[120364, 120364], "mapped", [107]], [[120365, 120365], "mapped", [108]], [[120366, 120366], "mapped", [109]], [[120367, 120367], "mapped", [110]], [[120368, 120368], "mapped", [111]], [[120369, 120369], "mapped", [112]], [[120370, 120370], "mapped", [113]], [[120371, 120371], "mapped", [114]], [[120372, 120372], "mapped", [115]], [[120373, 120373], "mapped", [116]], [[120374, 120374], "mapped", [117]], [[120375, 120375], "mapped", [118]], [[120376, 120376], "mapped", [119]], [[120377, 120377], "mapped", [120]], [[120378, 120378], "mapped", [121]], [[120379, 120379], "mapped", [122]], [[120380, 120380], "mapped", [97]], [[120381, 120381], "mapped", [98]], [[120382, 120382], "mapped", [99]], [[120383, 120383], "mapped", [100]], [[120384, 120384], "mapped", [101]], [[120385, 120385], "mapped", [102]], [[120386, 120386], "mapped", [103]], [[120387, 120387], "mapped", [104]], [[120388, 120388], "mapped", [105]], [[120389, 120389], "mapped", [106]], [[120390, 120390], "mapped", [107]], [[120391, 120391], "mapped", [108]], [[120392, 120392], "mapped", [109]], [[120393, 120393], "mapped", [110]], [[120394, 120394], "mapped", [111]], [[120395, 120395], "mapped", [112]], [[120396, 120396], "mapped", [113]], [[120397, 120397], "mapped", [114]], [[120398, 120398], "mapped", [115]], [[120399, 120399], "mapped", [116]], [[120400, 120400], "mapped", [117]], [[120401, 120401], "mapped", [118]], [[120402, 120402], "mapped", [119]], [[120403, 120403], "mapped", [120]], [[120404, 120404], "mapped", [121]], [[120405, 120405], "mapped", [122]], [[120406, 120406], "mapped", [97]], [[120407, 120407], "mapped", [98]], [[120408, 120408], "mapped", [99]], [[120409, 120409], "mapped", [100]], [[120410, 120410], "mapped", [101]], [[120411, 120411], "mapped", [102]], [[120412, 120412], "mapped", [103]], [[120413, 120413], "mapped", [104]], [[120414, 120414], "mapped", [105]], [[120415, 120415], "mapped", [106]], [[120416, 120416], "mapped", [107]], [[120417, 120417], "mapped", [108]], [[120418, 120418], "mapped", [109]], [[120419, 120419], "mapped", [110]], [[120420, 120420], "mapped", [111]], [[120421, 120421], "mapped", [112]], [[120422, 120422], "mapped", [113]], [[120423, 120423], "mapped", [114]], [[120424, 120424], "mapped", [115]], [[120425, 120425], "mapped", [116]], [[120426, 120426], "mapped", [117]], [[120427, 120427], "mapped", [118]], [[120428, 120428], "mapped", [119]], [[120429, 120429], "mapped", [120]], [[120430, 120430], "mapped", [121]], [[120431, 120431], "mapped", [122]], [[120432, 120432], "mapped", [97]], [[120433, 120433], "mapped", [98]], [[120434, 120434], "mapped", [99]], [[120435, 120435], "mapped", [100]], [[120436, 120436], "mapped", [101]], [[120437, 120437], "mapped", [102]], [[120438, 120438], "mapped", [103]], [[120439, 120439], "mapped", [104]], [[120440, 120440], "mapped", [105]], [[120441, 120441], "mapped", [106]], [[120442, 120442], "mapped", [107]], [[120443, 120443], "mapped", [108]], [[120444, 120444], "mapped", [109]], [[120445, 120445], "mapped", [110]], [[120446, 120446], "mapped", [111]], [[120447, 120447], "mapped", [112]], [[120448, 120448], "mapped", [113]], [[120449, 120449], "mapped", [114]], [[120450, 120450], "mapped", [115]], [[120451, 120451], "mapped", [116]], [[120452, 120452], "mapped", [117]], [[120453, 120453], "mapped", [118]], [[120454, 120454], "mapped", [119]], [[120455, 120455], "mapped", [120]], [[120456, 120456], "mapped", [121]], [[120457, 120457], "mapped", [122]], [[120458, 120458], "mapped", [97]], [[120459, 120459], "mapped", [98]], [[120460, 120460], "mapped", [99]], [[120461, 120461], "mapped", [100]], [[120462, 120462], "mapped", [101]], [[120463, 120463], "mapped", [102]], [[120464, 120464], "mapped", [103]], [[120465, 120465], "mapped", [104]], [[120466, 120466], "mapped", [105]], [[120467, 120467], "mapped", [106]], [[120468, 120468], "mapped", [107]], [[120469, 120469], "mapped", [108]], [[120470, 120470], "mapped", [109]], [[120471, 120471], "mapped", [110]], [[120472, 120472], "mapped", [111]], [[120473, 120473], "mapped", [112]], [[120474, 120474], "mapped", [113]], [[120475, 120475], "mapped", [114]], [[120476, 120476], "mapped", [115]], [[120477, 120477], "mapped", [116]], [[120478, 120478], "mapped", [117]], [[120479, 120479], "mapped", [118]], [[120480, 120480], "mapped", [119]], [[120481, 120481], "mapped", [120]], [[120482, 120482], "mapped", [121]], [[120483, 120483], "mapped", [122]], [[120484, 120484], "mapped", [305]], [[120485, 120485], "mapped", [567]], [[120486, 120487], "disallowed"], [[120488, 120488], "mapped", [945]], [[120489, 120489], "mapped", [946]], [[120490, 120490], "mapped", [947]], [[120491, 120491], "mapped", [948]], [[120492, 120492], "mapped", [949]], [[120493, 120493], "mapped", [950]], [[120494, 120494], "mapped", [951]], [[120495, 120495], "mapped", [952]], [[120496, 120496], "mapped", [953]], [[120497, 120497], "mapped", [954]], [[120498, 120498], "mapped", [955]], [[120499, 120499], "mapped", [956]], [[120500, 120500], "mapped", [957]], [[120501, 120501], "mapped", [958]], [[120502, 120502], "mapped", [959]], [[120503, 120503], "mapped", [960]], [[120504, 120504], "mapped", [961]], [[120505, 120505], "mapped", [952]], [[120506, 120506], "mapped", [963]], [[120507, 120507], "mapped", [964]], [[120508, 120508], "mapped", [965]], [[120509, 120509], "mapped", [966]], [[120510, 120510], "mapped", [967]], [[120511, 120511], "mapped", [968]], [[120512, 120512], "mapped", [969]], [[120513, 120513], "mapped", [8711]], [[120514, 120514], "mapped", [945]], [[120515, 120515], "mapped", [946]], [[120516, 120516], "mapped", [947]], [[120517, 120517], "mapped", [948]], [[120518, 120518], "mapped", [949]], [[120519, 120519], "mapped", [950]], [[120520, 120520], "mapped", [951]], [[120521, 120521], "mapped", [952]], [[120522, 120522], "mapped", [953]], [[120523, 120523], "mapped", [954]], [[120524, 120524], "mapped", [955]], [[120525, 120525], "mapped", [956]], [[120526, 120526], "mapped", [957]], [[120527, 120527], "mapped", [958]], [[120528, 120528], "mapped", [959]], [[120529, 120529], "mapped", [960]], [[120530, 120530], "mapped", [961]], [[120531, 120532], "mapped", [963]], [[120533, 120533], "mapped", [964]], [[120534, 120534], "mapped", [965]], [[120535, 120535], "mapped", [966]], [[120536, 120536], "mapped", [967]], [[120537, 120537], "mapped", [968]], [[120538, 120538], "mapped", [969]], [[120539, 120539], "mapped", [8706]], [[120540, 120540], "mapped", [949]], [[120541, 120541], "mapped", [952]], [[120542, 120542], "mapped", [954]], [[120543, 120543], "mapped", [966]], [[120544, 120544], "mapped", [961]], [[120545, 120545], "mapped", [960]], [[120546, 120546], "mapped", [945]], [[120547, 120547], "mapped", [946]], [[120548, 120548], "mapped", [947]], [[120549, 120549], "mapped", [948]], [[120550, 120550], "mapped", [949]], [[120551, 120551], "mapped", [950]], [[120552, 120552], "mapped", [951]], [[120553, 120553], "mapped", [952]], [[120554, 120554], "mapped", [953]], [[120555, 120555], "mapped", [954]], [[120556, 120556], "mapped", [955]], [[120557, 120557], "mapped", [956]], [[120558, 120558], "mapped", [957]], [[120559, 120559], "mapped", [958]], [[120560, 120560], "mapped", [959]], [[120561, 120561], "mapped", [960]], [[120562, 120562], "mapped", [961]], [[120563, 120563], "mapped", [952]], [[120564, 120564], "mapped", [963]], [[120565, 120565], "mapped", [964]], [[120566, 120566], "mapped", [965]], [[120567, 120567], "mapped", [966]], [[120568, 120568], "mapped", [967]], [[120569, 120569], "mapped", [968]], [[120570, 120570], "mapped", [969]], [[120571, 120571], "mapped", [8711]], [[120572, 120572], "mapped", [945]], [[120573, 120573], "mapped", [946]], [[120574, 120574], "mapped", [947]], [[120575, 120575], "mapped", [948]], [[120576, 120576], "mapped", [949]], [[120577, 120577], "mapped", [950]], [[120578, 120578], "mapped", [951]], [[120579, 120579], "mapped", [952]], [[120580, 120580], "mapped", [953]], [[120581, 120581], "mapped", [954]], [[120582, 120582], "mapped", [955]], [[120583, 120583], "mapped", [956]], [[120584, 120584], "mapped", [957]], [[120585, 120585], "mapped", [958]], [[120586, 120586], "mapped", [959]], [[120587, 120587], "mapped", [960]], [[120588, 120588], "mapped", [961]], [[120589, 120590], "mapped", [963]], [[120591, 120591], "mapped", [964]], [[120592, 120592], "mapped", [965]], [[120593, 120593], "mapped", [966]], [[120594, 120594], "mapped", [967]], [[120595, 120595], "mapped", [968]], [[120596, 120596], "mapped", [969]], [[120597, 120597], "mapped", [8706]], [[120598, 120598], "mapped", [949]], [[120599, 120599], "mapped", [952]], [[120600, 120600], "mapped", [954]], [[120601, 120601], "mapped", [966]], [[120602, 120602], "mapped", [961]], [[120603, 120603], "mapped", [960]], [[120604, 120604], "mapped", [945]], [[120605, 120605], "mapped", [946]], [[120606, 120606], "mapped", [947]], [[120607, 120607], "mapped", [948]], [[120608, 120608], "mapped", [949]], [[120609, 120609], "mapped", [950]], [[120610, 120610], "mapped", [951]], [[120611, 120611], "mapped", [952]], [[120612, 120612], "mapped", [953]], [[120613, 120613], "mapped", [954]], [[120614, 120614], "mapped", [955]], [[120615, 120615], "mapped", [956]], [[120616, 120616], "mapped", [957]], [[120617, 120617], "mapped", [958]], [[120618, 120618], "mapped", [959]], [[120619, 120619], "mapped", [960]], [[120620, 120620], "mapped", [961]], [[120621, 120621], "mapped", [952]], [[120622, 120622], "mapped", [963]], [[120623, 120623], "mapped", [964]], [[120624, 120624], "mapped", [965]], [[120625, 120625], "mapped", [966]], [[120626, 120626], "mapped", [967]], [[120627, 120627], "mapped", [968]], [[120628, 120628], "mapped", [969]], [[120629, 120629], "mapped", [8711]], [[120630, 120630], "mapped", [945]], [[120631, 120631], "mapped", [946]], [[120632, 120632], "mapped", [947]], [[120633, 120633], "mapped", [948]], [[120634, 120634], "mapped", [949]], [[120635, 120635], "mapped", [950]], [[120636, 120636], "mapped", [951]], [[120637, 120637], "mapped", [952]], [[120638, 120638], "mapped", [953]], [[120639, 120639], "mapped", [954]], [[120640, 120640], "mapped", [955]], [[120641, 120641], "mapped", [956]], [[120642, 120642], "mapped", [957]], [[120643, 120643], "mapped", [958]], [[120644, 120644], "mapped", [959]], [[120645, 120645], "mapped", [960]], [[120646, 120646], "mapped", [961]], [[120647, 120648], "mapped", [963]], [[120649, 120649], "mapped", [964]], [[120650, 120650], "mapped", [965]], [[120651, 120651], "mapped", [966]], [[120652, 120652], "mapped", [967]], [[120653, 120653], "mapped", [968]], [[120654, 120654], "mapped", [969]], [[120655, 120655], "mapped", [8706]], [[120656, 120656], "mapped", [949]], [[120657, 120657], "mapped", [952]], [[120658, 120658], "mapped", [954]], [[120659, 120659], "mapped", [966]], [[120660, 120660], "mapped", [961]], [[120661, 120661], "mapped", [960]], [[120662, 120662], "mapped", [945]], [[120663, 120663], "mapped", [946]], [[120664, 120664], "mapped", [947]], [[120665, 120665], "mapped", [948]], [[120666, 120666], "mapped", [949]], [[120667, 120667], "mapped", [950]], [[120668, 120668], "mapped", [951]], [[120669, 120669], "mapped", [952]], [[120670, 120670], "mapped", [953]], [[120671, 120671], "mapped", [954]], [[120672, 120672], "mapped", [955]], [[120673, 120673], "mapped", [956]], [[120674, 120674], "mapped", [957]], [[120675, 120675], "mapped", [958]], [[120676, 120676], "mapped", [959]], [[120677, 120677], "mapped", [960]], [[120678, 120678], "mapped", [961]], [[120679, 120679], "mapped", [952]], [[120680, 120680], "mapped", [963]], [[120681, 120681], "mapped", [964]], [[120682, 120682], "mapped", [965]], [[120683, 120683], "mapped", [966]], [[120684, 120684], "mapped", [967]], [[120685, 120685], "mapped", [968]], [[120686, 120686], "mapped", [969]], [[120687, 120687], "mapped", [8711]], [[120688, 120688], "mapped", [945]], [[120689, 120689], "mapped", [946]], [[120690, 120690], "mapped", [947]], [[120691, 120691], "mapped", [948]], [[120692, 120692], "mapped", [949]], [[120693, 120693], "mapped", [950]], [[120694, 120694], "mapped", [951]], [[120695, 120695], "mapped", [952]], [[120696, 120696], "mapped", [953]], [[120697, 120697], "mapped", [954]], [[120698, 120698], "mapped", [955]], [[120699, 120699], "mapped", [956]], [[120700, 120700], "mapped", [957]], [[120701, 120701], "mapped", [958]], [[120702, 120702], "mapped", [959]], [[120703, 120703], "mapped", [960]], [[120704, 120704], "mapped", [961]], [[120705, 120706], "mapped", [963]], [[120707, 120707], "mapped", [964]], [[120708, 120708], "mapped", [965]], [[120709, 120709], "mapped", [966]], [[120710, 120710], "mapped", [967]], [[120711, 120711], "mapped", [968]], [[120712, 120712], "mapped", [969]], [[120713, 120713], "mapped", [8706]], [[120714, 120714], "mapped", [949]], [[120715, 120715], "mapped", [952]], [[120716, 120716], "mapped", [954]], [[120717, 120717], "mapped", [966]], [[120718, 120718], "mapped", [961]], [[120719, 120719], "mapped", [960]], [[120720, 120720], "mapped", [945]], [[120721, 120721], "mapped", [946]], [[120722, 120722], "mapped", [947]], [[120723, 120723], "mapped", [948]], [[120724, 120724], "mapped", [949]], [[120725, 120725], "mapped", [950]], [[120726, 120726], "mapped", [951]], [[120727, 120727], "mapped", [952]], [[120728, 120728], "mapped", [953]], [[120729, 120729], "mapped", [954]], [[120730, 120730], "mapped", [955]], [[120731, 120731], "mapped", [956]], [[120732, 120732], "mapped", [957]], [[120733, 120733], "mapped", [958]], [[120734, 120734], "mapped", [959]], [[120735, 120735], "mapped", [960]], [[120736, 120736], "mapped", [961]], [[120737, 120737], "mapped", [952]], [[120738, 120738], "mapped", [963]], [[120739, 120739], "mapped", [964]], [[120740, 120740], "mapped", [965]], [[120741, 120741], "mapped", [966]], [[120742, 120742], "mapped", [967]], [[120743, 120743], "mapped", [968]], [[120744, 120744], "mapped", [969]], [[120745, 120745], "mapped", [8711]], [[120746, 120746], "mapped", [945]], [[120747, 120747], "mapped", [946]], [[120748, 120748], "mapped", [947]], [[120749, 120749], "mapped", [948]], [[120750, 120750], "mapped", [949]], [[120751, 120751], "mapped", [950]], [[120752, 120752], "mapped", [951]], [[120753, 120753], "mapped", [952]], [[120754, 120754], "mapped", [953]], [[120755, 120755], "mapped", [954]], [[120756, 120756], "mapped", [955]], [[120757, 120757], "mapped", [956]], [[120758, 120758], "mapped", [957]], [[120759, 120759], "mapped", [958]], [[120760, 120760], "mapped", [959]], [[120761, 120761], "mapped", [960]], [[120762, 120762], "mapped", [961]], [[120763, 120764], "mapped", [963]], [[120765, 120765], "mapped", [964]], [[120766, 120766], "mapped", [965]], [[120767, 120767], "mapped", [966]], [[120768, 120768], "mapped", [967]], [[120769, 120769], "mapped", [968]], [[120770, 120770], "mapped", [969]], [[120771, 120771], "mapped", [8706]], [[120772, 120772], "mapped", [949]], [[120773, 120773], "mapped", [952]], [[120774, 120774], "mapped", [954]], [[120775, 120775], "mapped", [966]], [[120776, 120776], "mapped", [961]], [[120777, 120777], "mapped", [960]], [[120778, 120779], "mapped", [989]], [[120780, 120781], "disallowed"], [[120782, 120782], "mapped", [48]], [[120783, 120783], "mapped", [49]], [[120784, 120784], "mapped", [50]], [[120785, 120785], "mapped", [51]], [[120786, 120786], "mapped", [52]], [[120787, 120787], "mapped", [53]], [[120788, 120788], "mapped", [54]], [[120789, 120789], "mapped", [55]], [[120790, 120790], "mapped", [56]], [[120791, 120791], "mapped", [57]], [[120792, 120792], "mapped", [48]], [[120793, 120793], "mapped", [49]], [[120794, 120794], "mapped", [50]], [[120795, 120795], "mapped", [51]], [[120796, 120796], "mapped", [52]], [[120797, 120797], "mapped", [53]], [[120798, 120798], "mapped", [54]], [[120799, 120799], "mapped", [55]], [[120800, 120800], "mapped", [56]], [[120801, 120801], "mapped", [57]], [[120802, 120802], "mapped", [48]], [[120803, 120803], "mapped", [49]], [[120804, 120804], "mapped", [50]], [[120805, 120805], "mapped", [51]], [[120806, 120806], "mapped", [52]], [[120807, 120807], "mapped", [53]], [[120808, 120808], "mapped", [54]], [[120809, 120809], "mapped", [55]], [[120810, 120810], "mapped", [56]], [[120811, 120811], "mapped", [57]], [[120812, 120812], "mapped", [48]], [[120813, 120813], "mapped", [49]], [[120814, 120814], "mapped", [50]], [[120815, 120815], "mapped", [51]], [[120816, 120816], "mapped", [52]], [[120817, 120817], "mapped", [53]], [[120818, 120818], "mapped", [54]], [[120819, 120819], "mapped", [55]], [[120820, 120820], "mapped", [56]], [[120821, 120821], "mapped", [57]], [[120822, 120822], "mapped", [48]], [[120823, 120823], "mapped", [49]], [[120824, 120824], "mapped", [50]], [[120825, 120825], "mapped", [51]], [[120826, 120826], "mapped", [52]], [[120827, 120827], "mapped", [53]], [[120828, 120828], "mapped", [54]], [[120829, 120829], "mapped", [55]], [[120830, 120830], "mapped", [56]], [[120831, 120831], "mapped", [57]], [[120832, 121343], "valid", [], "NV8"], [[121344, 121398], "valid"], [[121399, 121402], "valid", [], "NV8"], [[121403, 121452], "valid"], [[121453, 121460], "valid", [], "NV8"], [[121461, 121461], "valid"], [[121462, 121475], "valid", [], "NV8"], [[121476, 121476], "valid"], [[121477, 121483], "valid", [], "NV8"], [[121484, 121498], "disallowed"], [[121499, 121503], "valid"], [[121504, 121504], "disallowed"], [[121505, 121519], "valid"], [[121520, 124927], "disallowed"], [[124928, 125124], "valid"], [[125125, 125126], "disallowed"], [[125127, 125135], "valid", [], "NV8"], [[125136, 125142], "valid"], [[125143, 126463], "disallowed"], [[126464, 126464], "mapped", [1575]], [[126465, 126465], "mapped", [1576]], [[126466, 126466], "mapped", [1580]], [[126467, 126467], "mapped", [1583]], [[126468, 126468], "disallowed"], [[126469, 126469], "mapped", [1608]], [[126470, 126470], "mapped", [1586]], [[126471, 126471], "mapped", [1581]], [[126472, 126472], "mapped", [1591]], [[126473, 126473], "mapped", [1610]], [[126474, 126474], "mapped", [1603]], [[126475, 126475], "mapped", [1604]], [[126476, 126476], "mapped", [1605]], [[126477, 126477], "mapped", [1606]], [[126478, 126478], "mapped", [1587]], [[126479, 126479], "mapped", [1593]], [[126480, 126480], "mapped", [1601]], [[126481, 126481], "mapped", [1589]], [[126482, 126482], "mapped", [1602]], [[126483, 126483], "mapped", [1585]], [[126484, 126484], "mapped", [1588]], [[126485, 126485], "mapped", [1578]], [[126486, 126486], "mapped", [1579]], [[126487, 126487], "mapped", [1582]], [[126488, 126488], "mapped", [1584]], [[126489, 126489], "mapped", [1590]], [[126490, 126490], "mapped", [1592]], [[126491, 126491], "mapped", [1594]], [[126492, 126492], "mapped", [1646]], [[126493, 126493], "mapped", [1722]], [[126494, 126494], "mapped", [1697]], [[126495, 126495], "mapped", [1647]], [[126496, 126496], "disallowed"], [[126497, 126497], "mapped", [1576]], [[126498, 126498], "mapped", [1580]], [[126499, 126499], "disallowed"], [[126500, 126500], "mapped", [1607]], [[126501, 126502], "disallowed"], [[126503, 126503], "mapped", [1581]], [[126504, 126504], "disallowed"], [[126505, 126505], "mapped", [1610]], [[126506, 126506], "mapped", [1603]], [[126507, 126507], "mapped", [1604]], [[126508, 126508], "mapped", [1605]], [[126509, 126509], "mapped", [1606]], [[126510, 126510], "mapped", [1587]], [[126511, 126511], "mapped", [1593]], [[126512, 126512], "mapped", [1601]], [[126513, 126513], "mapped", [1589]], [[126514, 126514], "mapped", [1602]], [[126515, 126515], "disallowed"], [[126516, 126516], "mapped", [1588]], [[126517, 126517], "mapped", [1578]], [[126518, 126518], "mapped", [1579]], [[126519, 126519], "mapped", [1582]], [[126520, 126520], "disallowed"], [[126521, 126521], "mapped", [1590]], [[126522, 126522], "disallowed"], [[126523, 126523], "mapped", [1594]], [[126524, 126529], "disallowed"], [[126530, 126530], "mapped", [1580]], [[126531, 126534], "disallowed"], [[126535, 126535], "mapped", [1581]], [[126536, 126536], "disallowed"], [[126537, 126537], "mapped", [1610]], [[126538, 126538], "disallowed"], [[126539, 126539], "mapped", [1604]], [[126540, 126540], "disallowed"], [[126541, 126541], "mapped", [1606]], [[126542, 126542], "mapped", [1587]], [[126543, 126543], "mapped", [1593]], [[126544, 126544], "disallowed"], [[126545, 126545], "mapped", [1589]], [[126546, 126546], "mapped", [1602]], [[126547, 126547], "disallowed"], [[126548, 126548], "mapped", [1588]], [[126549, 126550], "disallowed"], [[126551, 126551], "mapped", [1582]], [[126552, 126552], "disallowed"], [[126553, 126553], "mapped", [1590]], [[126554, 126554], "disallowed"], [[126555, 126555], "mapped", [1594]], [[126556, 126556], "disallowed"], [[126557, 126557], "mapped", [1722]], [[126558, 126558], "disallowed"], [[126559, 126559], "mapped", [1647]], [[126560, 126560], "disallowed"], [[126561, 126561], "mapped", [1576]], [[126562, 126562], "mapped", [1580]], [[126563, 126563], "disallowed"], [[126564, 126564], "mapped", [1607]], [[126565, 126566], "disallowed"], [[126567, 126567], "mapped", [1581]], [[126568, 126568], "mapped", [1591]], [[126569, 126569], "mapped", [1610]], [[126570, 126570], "mapped", [1603]], [[126571, 126571], "disallowed"], [[126572, 126572], "mapped", [1605]], [[126573, 126573], "mapped", [1606]], [[126574, 126574], "mapped", [1587]], [[126575, 126575], "mapped", [1593]], [[126576, 126576], "mapped", [1601]], [[126577, 126577], "mapped", [1589]], [[126578, 126578], "mapped", [1602]], [[126579, 126579], "disallowed"], [[126580, 126580], "mapped", [1588]], [[126581, 126581], "mapped", [1578]], [[126582, 126582], "mapped", [1579]], [[126583, 126583], "mapped", [1582]], [[126584, 126584], "disallowed"], [[126585, 126585], "mapped", [1590]], [[126586, 126586], "mapped", [1592]], [[126587, 126587], "mapped", [1594]], [[126588, 126588], "mapped", [1646]], [[126589, 126589], "disallowed"], [[126590, 126590], "mapped", [1697]], [[126591, 126591], "disallowed"], [[126592, 126592], "mapped", [1575]], [[126593, 126593], "mapped", [1576]], [[126594, 126594], "mapped", [1580]], [[126595, 126595], "mapped", [1583]], [[126596, 126596], "mapped", [1607]], [[126597, 126597], "mapped", [1608]], [[126598, 126598], "mapped", [1586]], [[126599, 126599], "mapped", [1581]], [[126600, 126600], "mapped", [1591]], [[126601, 126601], "mapped", [1610]], [[126602, 126602], "disallowed"], [[126603, 126603], "mapped", [1604]], [[126604, 126604], "mapped", [1605]], [[126605, 126605], "mapped", [1606]], [[126606, 126606], "mapped", [1587]], [[126607, 126607], "mapped", [1593]], [[126608, 126608], "mapped", [1601]], [[126609, 126609], "mapped", [1589]], [[126610, 126610], "mapped", [1602]], [[126611, 126611], "mapped", [1585]], [[126612, 126612], "mapped", [1588]], [[126613, 126613], "mapped", [1578]], [[126614, 126614], "mapped", [1579]], [[126615, 126615], "mapped", [1582]], [[126616, 126616], "mapped", [1584]], [[126617, 126617], "mapped", [1590]], [[126618, 126618], "mapped", [1592]], [[126619, 126619], "mapped", [1594]], [[126620, 126624], "disallowed"], [[126625, 126625], "mapped", [1576]], [[126626, 126626], "mapped", [1580]], [[126627, 126627], "mapped", [1583]], [[126628, 126628], "disallowed"], [[126629, 126629], "mapped", [1608]], [[126630, 126630], "mapped", [1586]], [[126631, 126631], "mapped", [1581]], [[126632, 126632], "mapped", [1591]], [[126633, 126633], "mapped", [1610]], [[126634, 126634], "disallowed"], [[126635, 126635], "mapped", [1604]], [[126636, 126636], "mapped", [1605]], [[126637, 126637], "mapped", [1606]], [[126638, 126638], "mapped", [1587]], [[126639, 126639], "mapped", [1593]], [[126640, 126640], "mapped", [1601]], [[126641, 126641], "mapped", [1589]], [[126642, 126642], "mapped", [1602]], [[126643, 126643], "mapped", [1585]], [[126644, 126644], "mapped", [1588]], [[126645, 126645], "mapped", [1578]], [[126646, 126646], "mapped", [1579]], [[126647, 126647], "mapped", [1582]], [[126648, 126648], "mapped", [1584]], [[126649, 126649], "mapped", [1590]], [[126650, 126650], "mapped", [1592]], [[126651, 126651], "mapped", [1594]], [[126652, 126703], "disallowed"], [[126704, 126705], "valid", [], "NV8"], [[126706, 126975], "disallowed"], [[126976, 127019], "valid", [], "NV8"], [[127020, 127023], "disallowed"], [[127024, 127123], "valid", [], "NV8"], [[127124, 127135], "disallowed"], [[127136, 127150], "valid", [], "NV8"], [[127151, 127152], "disallowed"], [[127153, 127166], "valid", [], "NV8"], [[127167, 127167], "valid", [], "NV8"], [[127168, 127168], "disallowed"], [[127169, 127183], "valid", [], "NV8"], [[127184, 127184], "disallowed"], [[127185, 127199], "valid", [], "NV8"], [[127200, 127221], "valid", [], "NV8"], [[127222, 127231], "disallowed"], [[127232, 127232], "disallowed"], [[127233, 127233], "disallowed_STD3_mapped", [48, 44]], [[127234, 127234], "disallowed_STD3_mapped", [49, 44]], [[127235, 127235], "disallowed_STD3_mapped", [50, 44]], [[127236, 127236], "disallowed_STD3_mapped", [51, 44]], [[127237, 127237], "disallowed_STD3_mapped", [52, 44]], [[127238, 127238], "disallowed_STD3_mapped", [53, 44]], [[127239, 127239], "disallowed_STD3_mapped", [54, 44]], [[127240, 127240], "disallowed_STD3_mapped", [55, 44]], [[127241, 127241], "disallowed_STD3_mapped", [56, 44]], [[127242, 127242], "disallowed_STD3_mapped", [57, 44]], [[127243, 127244], "valid", [], "NV8"], [[127245, 127247], "disallowed"], [[127248, 127248], "disallowed_STD3_mapped", [40, 97, 41]], [[127249, 127249], "disallowed_STD3_mapped", [40, 98, 41]], [[127250, 127250], "disallowed_STD3_mapped", [40, 99, 41]], [[127251, 127251], "disallowed_STD3_mapped", [40, 100, 41]], [[127252, 127252], "disallowed_STD3_mapped", [40, 101, 41]], [[127253, 127253], "disallowed_STD3_mapped", [40, 102, 41]], [[127254, 127254], "disallowed_STD3_mapped", [40, 103, 41]], [[127255, 127255], "disallowed_STD3_mapped", [40, 104, 41]], [[127256, 127256], "disallowed_STD3_mapped", [40, 105, 41]], [[127257, 127257], "disallowed_STD3_mapped", [40, 106, 41]], [[127258, 127258], "disallowed_STD3_mapped", [40, 107, 41]], [[127259, 127259], "disallowed_STD3_mapped", [40, 108, 41]], [[127260, 127260], "disallowed_STD3_mapped", [40, 109, 41]], [[127261, 127261], "disallowed_STD3_mapped", [40, 110, 41]], [[127262, 127262], "disallowed_STD3_mapped", [40, 111, 41]], [[127263, 127263], "disallowed_STD3_mapped", [40, 112, 41]], [[127264, 127264], "disallowed_STD3_mapped", [40, 113, 41]], [[127265, 127265], "disallowed_STD3_mapped", [40, 114, 41]], [[127266, 127266], "disallowed_STD3_mapped", [40, 115, 41]], [[127267, 127267], "disallowed_STD3_mapped", [40, 116, 41]], [[127268, 127268], "disallowed_STD3_mapped", [40, 117, 41]], [[127269, 127269], "disallowed_STD3_mapped", [40, 118, 41]], [[127270, 127270], "disallowed_STD3_mapped", [40, 119, 41]], [[127271, 127271], "disallowed_STD3_mapped", [40, 120, 41]], [[127272, 127272], "disallowed_STD3_mapped", [40, 121, 41]], [[127273, 127273], "disallowed_STD3_mapped", [40, 122, 41]], [[127274, 127274], "mapped", [12308, 115, 12309]], [[127275, 127275], "mapped", [99]], [[127276, 127276], "mapped", [114]], [[127277, 127277], "mapped", [99, 100]], [[127278, 127278], "mapped", [119, 122]], [[127279, 127279], "disallowed"], [[127280, 127280], "mapped", [97]], [[127281, 127281], "mapped", [98]], [[127282, 127282], "mapped", [99]], [[127283, 127283], "mapped", [100]], [[127284, 127284], "mapped", [101]], [[127285, 127285], "mapped", [102]], [[127286, 127286], "mapped", [103]], [[127287, 127287], "mapped", [104]], [[127288, 127288], "mapped", [105]], [[127289, 127289], "mapped", [106]], [[127290, 127290], "mapped", [107]], [[127291, 127291], "mapped", [108]], [[127292, 127292], "mapped", [109]], [[127293, 127293], "mapped", [110]], [[127294, 127294], "mapped", [111]], [[127295, 127295], "mapped", [112]], [[127296, 127296], "mapped", [113]], [[127297, 127297], "mapped", [114]], [[127298, 127298], "mapped", [115]], [[127299, 127299], "mapped", [116]], [[127300, 127300], "mapped", [117]], [[127301, 127301], "mapped", [118]], [[127302, 127302], "mapped", [119]], [[127303, 127303], "mapped", [120]], [[127304, 127304], "mapped", [121]], [[127305, 127305], "mapped", [122]], [[127306, 127306], "mapped", [104, 118]], [[127307, 127307], "mapped", [109, 118]], [[127308, 127308], "mapped", [115, 100]], [[127309, 127309], "mapped", [115, 115]], [[127310, 127310], "mapped", [112, 112, 118]], [[127311, 127311], "mapped", [119, 99]], [[127312, 127318], "valid", [], "NV8"], [[127319, 127319], "valid", [], "NV8"], [[127320, 127326], "valid", [], "NV8"], [[127327, 127327], "valid", [], "NV8"], [[127328, 127337], "valid", [], "NV8"], [[127338, 127338], "mapped", [109, 99]], [[127339, 127339], "mapped", [109, 100]], [[127340, 127343], "disallowed"], [[127344, 127352], "valid", [], "NV8"], [[127353, 127353], "valid", [], "NV8"], [[127354, 127354], "valid", [], "NV8"], [[127355, 127356], "valid", [], "NV8"], [[127357, 127358], "valid", [], "NV8"], [[127359, 127359], "valid", [], "NV8"], [[127360, 127369], "valid", [], "NV8"], [[127370, 127373], "valid", [], "NV8"], [[127374, 127375], "valid", [], "NV8"], [[127376, 127376], "mapped", [100, 106]], [[127377, 127386], "valid", [], "NV8"], [[127387, 127461], "disallowed"], [[127462, 127487], "valid", [], "NV8"], [[127488, 127488], "mapped", [12411, 12363]], [[127489, 127489], "mapped", [12467, 12467]], [[127490, 127490], "mapped", [12469]], [[127491, 127503], "disallowed"], [[127504, 127504], "mapped", [25163]], [[127505, 127505], "mapped", [23383]], [[127506, 127506], "mapped", [21452]], [[127507, 127507], "mapped", [12487]], [[127508, 127508], "mapped", [20108]], [[127509, 127509], "mapped", [22810]], [[127510, 127510], "mapped", [35299]], [[127511, 127511], "mapped", [22825]], [[127512, 127512], "mapped", [20132]], [[127513, 127513], "mapped", [26144]], [[127514, 127514], "mapped", [28961]], [[127515, 127515], "mapped", [26009]], [[127516, 127516], "mapped", [21069]], [[127517, 127517], "mapped", [24460]], [[127518, 127518], "mapped", [20877]], [[127519, 127519], "mapped", [26032]], [[127520, 127520], "mapped", [21021]], [[127521, 127521], "mapped", [32066]], [[127522, 127522], "mapped", [29983]], [[127523, 127523], "mapped", [36009]], [[127524, 127524], "mapped", [22768]], [[127525, 127525], "mapped", [21561]], [[127526, 127526], "mapped", [28436]], [[127527, 127527], "mapped", [25237]], [[127528, 127528], "mapped", [25429]], [[127529, 127529], "mapped", [19968]], [[127530, 127530], "mapped", [19977]], [[127531, 127531], "mapped", [36938]], [[127532, 127532], "mapped", [24038]], [[127533, 127533], "mapped", [20013]], [[127534, 127534], "mapped", [21491]], [[127535, 127535], "mapped", [25351]], [[127536, 127536], "mapped", [36208]], [[127537, 127537], "mapped", [25171]], [[127538, 127538], "mapped", [31105]], [[127539, 127539], "mapped", [31354]], [[127540, 127540], "mapped", [21512]], [[127541, 127541], "mapped", [28288]], [[127542, 127542], "mapped", [26377]], [[127543, 127543], "mapped", [26376]], [[127544, 127544], "mapped", [30003]], [[127545, 127545], "mapped", [21106]], [[127546, 127546], "mapped", [21942]], [[127547, 127551], "disallowed"], [[127552, 127552], "mapped", [12308, 26412, 12309]], [[127553, 127553], "mapped", [12308, 19977, 12309]], [[127554, 127554], "mapped", [12308, 20108, 12309]], [[127555, 127555], "mapped", [12308, 23433, 12309]], [[127556, 127556], "mapped", [12308, 28857, 12309]], [[127557, 127557], "mapped", [12308, 25171, 12309]], [[127558, 127558], "mapped", [12308, 30423, 12309]], [[127559, 127559], "mapped", [12308, 21213, 12309]], [[127560, 127560], "mapped", [12308, 25943, 12309]], [[127561, 127567], "disallowed"], [[127568, 127568], "mapped", [24471]], [[127569, 127569], "mapped", [21487]], [[127570, 127743], "disallowed"], [[127744, 127776], "valid", [], "NV8"], [[127777, 127788], "valid", [], "NV8"], [[127789, 127791], "valid", [], "NV8"], [[127792, 127797], "valid", [], "NV8"], [[127798, 127798], "valid", [], "NV8"], [[127799, 127868], "valid", [], "NV8"], [[127869, 127869], "valid", [], "NV8"], [[127870, 127871], "valid", [], "NV8"], [[127872, 127891], "valid", [], "NV8"], [[127892, 127903], "valid", [], "NV8"], [[127904, 127940], "valid", [], "NV8"], [[127941, 127941], "valid", [], "NV8"], [[127942, 127946], "valid", [], "NV8"], [[127947, 127950], "valid", [], "NV8"], [[127951, 127955], "valid", [], "NV8"], [[127956, 127967], "valid", [], "NV8"], [[127968, 127984], "valid", [], "NV8"], [[127985, 127991], "valid", [], "NV8"], [[127992, 127999], "valid", [], "NV8"], [[128e3, 128062], "valid", [], "NV8"], [[128063, 128063], "valid", [], "NV8"], [[128064, 128064], "valid", [], "NV8"], [[128065, 128065], "valid", [], "NV8"], [[128066, 128247], "valid", [], "NV8"], [[128248, 128248], "valid", [], "NV8"], [[128249, 128252], "valid", [], "NV8"], [[128253, 128254], "valid", [], "NV8"], [[128255, 128255], "valid", [], "NV8"], [[128256, 128317], "valid", [], "NV8"], [[128318, 128319], "valid", [], "NV8"], [[128320, 128323], "valid", [], "NV8"], [[128324, 128330], "valid", [], "NV8"], [[128331, 128335], "valid", [], "NV8"], [[128336, 128359], "valid", [], "NV8"], [[128360, 128377], "valid", [], "NV8"], [[128378, 128378], "disallowed"], [[128379, 128419], "valid", [], "NV8"], [[128420, 128420], "disallowed"], [[128421, 128506], "valid", [], "NV8"], [[128507, 128511], "valid", [], "NV8"], [[128512, 128512], "valid", [], "NV8"], [[128513, 128528], "valid", [], "NV8"], [[128529, 128529], "valid", [], "NV8"], [[128530, 128532], "valid", [], "NV8"], [[128533, 128533], "valid", [], "NV8"], [[128534, 128534], "valid", [], "NV8"], [[128535, 128535], "valid", [], "NV8"], [[128536, 128536], "valid", [], "NV8"], [[128537, 128537], "valid", [], "NV8"], [[128538, 128538], "valid", [], "NV8"], [[128539, 128539], "valid", [], "NV8"], [[128540, 128542], "valid", [], "NV8"], [[128543, 128543], "valid", [], "NV8"], [[128544, 128549], "valid", [], "NV8"], [[128550, 128551], "valid", [], "NV8"], [[128552, 128555], "valid", [], "NV8"], [[128556, 128556], "valid", [], "NV8"], [[128557, 128557], "valid", [], "NV8"], [[128558, 128559], "valid", [], "NV8"], [[128560, 128563], "valid", [], "NV8"], [[128564, 128564], "valid", [], "NV8"], [[128565, 128576], "valid", [], "NV8"], [[128577, 128578], "valid", [], "NV8"], [[128579, 128580], "valid", [], "NV8"], [[128581, 128591], "valid", [], "NV8"], [[128592, 128639], "valid", [], "NV8"], [[128640, 128709], "valid", [], "NV8"], [[128710, 128719], "valid", [], "NV8"], [[128720, 128720], "valid", [], "NV8"], [[128721, 128735], "disallowed"], [[128736, 128748], "valid", [], "NV8"], [[128749, 128751], "disallowed"], [[128752, 128755], "valid", [], "NV8"], [[128756, 128767], "disallowed"], [[128768, 128883], "valid", [], "NV8"], [[128884, 128895], "disallowed"], [[128896, 128980], "valid", [], "NV8"], [[128981, 129023], "disallowed"], [[129024, 129035], "valid", [], "NV8"], [[129036, 129039], "disallowed"], [[129040, 129095], "valid", [], "NV8"], [[129096, 129103], "disallowed"], [[129104, 129113], "valid", [], "NV8"], [[129114, 129119], "disallowed"], [[129120, 129159], "valid", [], "NV8"], [[129160, 129167], "disallowed"], [[129168, 129197], "valid", [], "NV8"], [[129198, 129295], "disallowed"], [[129296, 129304], "valid", [], "NV8"], [[129305, 129407], "disallowed"], [[129408, 129412], "valid", [], "NV8"], [[129413, 129471], "disallowed"], [[129472, 129472], "valid", [], "NV8"], [[129473, 131069], "disallowed"], [[131070, 131071], "disallowed"], [[131072, 173782], "valid"], [[173783, 173823], "disallowed"], [[173824, 177972], "valid"], [[177973, 177983], "disallowed"], [[177984, 178205], "valid"], [[178206, 178207], "disallowed"], [[178208, 183969], "valid"], [[183970, 194559], "disallowed"], [[194560, 194560], "mapped", [20029]], [[194561, 194561], "mapped", [20024]], [[194562, 194562], "mapped", [20033]], [[194563, 194563], "mapped", [131362]], [[194564, 194564], "mapped", [20320]], [[194565, 194565], "mapped", [20398]], [[194566, 194566], "mapped", [20411]], [[194567, 194567], "mapped", [20482]], [[194568, 194568], "mapped", [20602]], [[194569, 194569], "mapped", [20633]], [[194570, 194570], "mapped", [20711]], [[194571, 194571], "mapped", [20687]], [[194572, 194572], "mapped", [13470]], [[194573, 194573], "mapped", [132666]], [[194574, 194574], "mapped", [20813]], [[194575, 194575], "mapped", [20820]], [[194576, 194576], "mapped", [20836]], [[194577, 194577], "mapped", [20855]], [[194578, 194578], "mapped", [132380]], [[194579, 194579], "mapped", [13497]], [[194580, 194580], "mapped", [20839]], [[194581, 194581], "mapped", [20877]], [[194582, 194582], "mapped", [132427]], [[194583, 194583], "mapped", [20887]], [[194584, 194584], "mapped", [20900]], [[194585, 194585], "mapped", [20172]], [[194586, 194586], "mapped", [20908]], [[194587, 194587], "mapped", [20917]], [[194588, 194588], "mapped", [168415]], [[194589, 194589], "mapped", [20981]], [[194590, 194590], "mapped", [20995]], [[194591, 194591], "mapped", [13535]], [[194592, 194592], "mapped", [21051]], [[194593, 194593], "mapped", [21062]], [[194594, 194594], "mapped", [21106]], [[194595, 194595], "mapped", [21111]], [[194596, 194596], "mapped", [13589]], [[194597, 194597], "mapped", [21191]], [[194598, 194598], "mapped", [21193]], [[194599, 194599], "mapped", [21220]], [[194600, 194600], "mapped", [21242]], [[194601, 194601], "mapped", [21253]], [[194602, 194602], "mapped", [21254]], [[194603, 194603], "mapped", [21271]], [[194604, 194604], "mapped", [21321]], [[194605, 194605], "mapped", [21329]], [[194606, 194606], "mapped", [21338]], [[194607, 194607], "mapped", [21363]], [[194608, 194608], "mapped", [21373]], [[194609, 194611], "mapped", [21375]], [[194612, 194612], "mapped", [133676]], [[194613, 194613], "mapped", [28784]], [[194614, 194614], "mapped", [21450]], [[194615, 194615], "mapped", [21471]], [[194616, 194616], "mapped", [133987]], [[194617, 194617], "mapped", [21483]], [[194618, 194618], "mapped", [21489]], [[194619, 194619], "mapped", [21510]], [[194620, 194620], "mapped", [21662]], [[194621, 194621], "mapped", [21560]], [[194622, 194622], "mapped", [21576]], [[194623, 194623], "mapped", [21608]], [[194624, 194624], "mapped", [21666]], [[194625, 194625], "mapped", [21750]], [[194626, 194626], "mapped", [21776]], [[194627, 194627], "mapped", [21843]], [[194628, 194628], "mapped", [21859]], [[194629, 194630], "mapped", [21892]], [[194631, 194631], "mapped", [21913]], [[194632, 194632], "mapped", [21931]], [[194633, 194633], "mapped", [21939]], [[194634, 194634], "mapped", [21954]], [[194635, 194635], "mapped", [22294]], [[194636, 194636], "mapped", [22022]], [[194637, 194637], "mapped", [22295]], [[194638, 194638], "mapped", [22097]], [[194639, 194639], "mapped", [22132]], [[194640, 194640], "mapped", [20999]], [[194641, 194641], "mapped", [22766]], [[194642, 194642], "mapped", [22478]], [[194643, 194643], "mapped", [22516]], [[194644, 194644], "mapped", [22541]], [[194645, 194645], "mapped", [22411]], [[194646, 194646], "mapped", [22578]], [[194647, 194647], "mapped", [22577]], [[194648, 194648], "mapped", [22700]], [[194649, 194649], "mapped", [136420]], [[194650, 194650], "mapped", [22770]], [[194651, 194651], "mapped", [22775]], [[194652, 194652], "mapped", [22790]], [[194653, 194653], "mapped", [22810]], [[194654, 194654], "mapped", [22818]], [[194655, 194655], "mapped", [22882]], [[194656, 194656], "mapped", [136872]], [[194657, 194657], "mapped", [136938]], [[194658, 194658], "mapped", [23020]], [[194659, 194659], "mapped", [23067]], [[194660, 194660], "mapped", [23079]], [[194661, 194661], "mapped", [23e3]], [[194662, 194662], "mapped", [23142]], [[194663, 194663], "mapped", [14062]], [[194664, 194664], "disallowed"], [[194665, 194665], "mapped", [23304]], [[194666, 194667], "mapped", [23358]], [[194668, 194668], "mapped", [137672]], [[194669, 194669], "mapped", [23491]], [[194670, 194670], "mapped", [23512]], [[194671, 194671], "mapped", [23527]], [[194672, 194672], "mapped", [23539]], [[194673, 194673], "mapped", [138008]], [[194674, 194674], "mapped", [23551]], [[194675, 194675], "mapped", [23558]], [[194676, 194676], "disallowed"], [[194677, 194677], "mapped", [23586]], [[194678, 194678], "mapped", [14209]], [[194679, 194679], "mapped", [23648]], [[194680, 194680], "mapped", [23662]], [[194681, 194681], "mapped", [23744]], [[194682, 194682], "mapped", [23693]], [[194683, 194683], "mapped", [138724]], [[194684, 194684], "mapped", [23875]], [[194685, 194685], "mapped", [138726]], [[194686, 194686], "mapped", [23918]], [[194687, 194687], "mapped", [23915]], [[194688, 194688], "mapped", [23932]], [[194689, 194689], "mapped", [24033]], [[194690, 194690], "mapped", [24034]], [[194691, 194691], "mapped", [14383]], [[194692, 194692], "mapped", [24061]], [[194693, 194693], "mapped", [24104]], [[194694, 194694], "mapped", [24125]], [[194695, 194695], "mapped", [24169]], [[194696, 194696], "mapped", [14434]], [[194697, 194697], "mapped", [139651]], [[194698, 194698], "mapped", [14460]], [[194699, 194699], "mapped", [24240]], [[194700, 194700], "mapped", [24243]], [[194701, 194701], "mapped", [24246]], [[194702, 194702], "mapped", [24266]], [[194703, 194703], "mapped", [172946]], [[194704, 194704], "mapped", [24318]], [[194705, 194706], "mapped", [140081]], [[194707, 194707], "mapped", [33281]], [[194708, 194709], "mapped", [24354]], [[194710, 194710], "mapped", [14535]], [[194711, 194711], "mapped", [144056]], [[194712, 194712], "mapped", [156122]], [[194713, 194713], "mapped", [24418]], [[194714, 194714], "mapped", [24427]], [[194715, 194715], "mapped", [14563]], [[194716, 194716], "mapped", [24474]], [[194717, 194717], "mapped", [24525]], [[194718, 194718], "mapped", [24535]], [[194719, 194719], "mapped", [24569]], [[194720, 194720], "mapped", [24705]], [[194721, 194721], "mapped", [14650]], [[194722, 194722], "mapped", [14620]], [[194723, 194723], "mapped", [24724]], [[194724, 194724], "mapped", [141012]], [[194725, 194725], "mapped", [24775]], [[194726, 194726], "mapped", [24904]], [[194727, 194727], "mapped", [24908]], [[194728, 194728], "mapped", [24910]], [[194729, 194729], "mapped", [24908]], [[194730, 194730], "mapped", [24954]], [[194731, 194731], "mapped", [24974]], [[194732, 194732], "mapped", [25010]], [[194733, 194733], "mapped", [24996]], [[194734, 194734], "mapped", [25007]], [[194735, 194735], "mapped", [25054]], [[194736, 194736], "mapped", [25074]], [[194737, 194737], "mapped", [25078]], [[194738, 194738], "mapped", [25104]], [[194739, 194739], "mapped", [25115]], [[194740, 194740], "mapped", [25181]], [[194741, 194741], "mapped", [25265]], [[194742, 194742], "mapped", [25300]], [[194743, 194743], "mapped", [25424]], [[194744, 194744], "mapped", [142092]], [[194745, 194745], "mapped", [25405]], [[194746, 194746], "mapped", [25340]], [[194747, 194747], "mapped", [25448]], [[194748, 194748], "mapped", [25475]], [[194749, 194749], "mapped", [25572]], [[194750, 194750], "mapped", [142321]], [[194751, 194751], "mapped", [25634]], [[194752, 194752], "mapped", [25541]], [[194753, 194753], "mapped", [25513]], [[194754, 194754], "mapped", [14894]], [[194755, 194755], "mapped", [25705]], [[194756, 194756], "mapped", [25726]], [[194757, 194757], "mapped", [25757]], [[194758, 194758], "mapped", [25719]], [[194759, 194759], "mapped", [14956]], [[194760, 194760], "mapped", [25935]], [[194761, 194761], "mapped", [25964]], [[194762, 194762], "mapped", [143370]], [[194763, 194763], "mapped", [26083]], [[194764, 194764], "mapped", [26360]], [[194765, 194765], "mapped", [26185]], [[194766, 194766], "mapped", [15129]], [[194767, 194767], "mapped", [26257]], [[194768, 194768], "mapped", [15112]], [[194769, 194769], "mapped", [15076]], [[194770, 194770], "mapped", [20882]], [[194771, 194771], "mapped", [20885]], [[194772, 194772], "mapped", [26368]], [[194773, 194773], "mapped", [26268]], [[194774, 194774], "mapped", [32941]], [[194775, 194775], "mapped", [17369]], [[194776, 194776], "mapped", [26391]], [[194777, 194777], "mapped", [26395]], [[194778, 194778], "mapped", [26401]], [[194779, 194779], "mapped", [26462]], [[194780, 194780], "mapped", [26451]], [[194781, 194781], "mapped", [144323]], [[194782, 194782], "mapped", [15177]], [[194783, 194783], "mapped", [26618]], [[194784, 194784], "mapped", [26501]], [[194785, 194785], "mapped", [26706]], [[194786, 194786], "mapped", [26757]], [[194787, 194787], "mapped", [144493]], [[194788, 194788], "mapped", [26766]], [[194789, 194789], "mapped", [26655]], [[194790, 194790], "mapped", [26900]], [[194791, 194791], "mapped", [15261]], [[194792, 194792], "mapped", [26946]], [[194793, 194793], "mapped", [27043]], [[194794, 194794], "mapped", [27114]], [[194795, 194795], "mapped", [27304]], [[194796, 194796], "mapped", [145059]], [[194797, 194797], "mapped", [27355]], [[194798, 194798], "mapped", [15384]], [[194799, 194799], "mapped", [27425]], [[194800, 194800], "mapped", [145575]], [[194801, 194801], "mapped", [27476]], [[194802, 194802], "mapped", [15438]], [[194803, 194803], "mapped", [27506]], [[194804, 194804], "mapped", [27551]], [[194805, 194805], "mapped", [27578]], [[194806, 194806], "mapped", [27579]], [[194807, 194807], "mapped", [146061]], [[194808, 194808], "mapped", [138507]], [[194809, 194809], "mapped", [146170]], [[194810, 194810], "mapped", [27726]], [[194811, 194811], "mapped", [146620]], [[194812, 194812], "mapped", [27839]], [[194813, 194813], "mapped", [27853]], [[194814, 194814], "mapped", [27751]], [[194815, 194815], "mapped", [27926]], [[194816, 194816], "mapped", [27966]], [[194817, 194817], "mapped", [28023]], [[194818, 194818], "mapped", [27969]], [[194819, 194819], "mapped", [28009]], [[194820, 194820], "mapped", [28024]], [[194821, 194821], "mapped", [28037]], [[194822, 194822], "mapped", [146718]], [[194823, 194823], "mapped", [27956]], [[194824, 194824], "mapped", [28207]], [[194825, 194825], "mapped", [28270]], [[194826, 194826], "mapped", [15667]], [[194827, 194827], "mapped", [28363]], [[194828, 194828], "mapped", [28359]], [[194829, 194829], "mapped", [147153]], [[194830, 194830], "mapped", [28153]], [[194831, 194831], "mapped", [28526]], [[194832, 194832], "mapped", [147294]], [[194833, 194833], "mapped", [147342]], [[194834, 194834], "mapped", [28614]], [[194835, 194835], "mapped", [28729]], [[194836, 194836], "mapped", [28702]], [[194837, 194837], "mapped", [28699]], [[194838, 194838], "mapped", [15766]], [[194839, 194839], "mapped", [28746]], [[194840, 194840], "mapped", [28797]], [[194841, 194841], "mapped", [28791]], [[194842, 194842], "mapped", [28845]], [[194843, 194843], "mapped", [132389]], [[194844, 194844], "mapped", [28997]], [[194845, 194845], "mapped", [148067]], [[194846, 194846], "mapped", [29084]], [[194847, 194847], "disallowed"], [[194848, 194848], "mapped", [29224]], [[194849, 194849], "mapped", [29237]], [[194850, 194850], "mapped", [29264]], [[194851, 194851], "mapped", [149e3]], [[194852, 194852], "mapped", [29312]], [[194853, 194853], "mapped", [29333]], [[194854, 194854], "mapped", [149301]], [[194855, 194855], "mapped", [149524]], [[194856, 194856], "mapped", [29562]], [[194857, 194857], "mapped", [29579]], [[194858, 194858], "mapped", [16044]], [[194859, 194859], "mapped", [29605]], [[194860, 194861], "mapped", [16056]], [[194862, 194862], "mapped", [29767]], [[194863, 194863], "mapped", [29788]], [[194864, 194864], "mapped", [29809]], [[194865, 194865], "mapped", [29829]], [[194866, 194866], "mapped", [29898]], [[194867, 194867], "mapped", [16155]], [[194868, 194868], "mapped", [29988]], [[194869, 194869], "mapped", [150582]], [[194870, 194870], "mapped", [30014]], [[194871, 194871], "mapped", [150674]], [[194872, 194872], "mapped", [30064]], [[194873, 194873], "mapped", [139679]], [[194874, 194874], "mapped", [30224]], [[194875, 194875], "mapped", [151457]], [[194876, 194876], "mapped", [151480]], [[194877, 194877], "mapped", [151620]], [[194878, 194878], "mapped", [16380]], [[194879, 194879], "mapped", [16392]], [[194880, 194880], "mapped", [30452]], [[194881, 194881], "mapped", [151795]], [[194882, 194882], "mapped", [151794]], [[194883, 194883], "mapped", [151833]], [[194884, 194884], "mapped", [151859]], [[194885, 194885], "mapped", [30494]], [[194886, 194887], "mapped", [30495]], [[194888, 194888], "mapped", [30538]], [[194889, 194889], "mapped", [16441]], [[194890, 194890], "mapped", [30603]], [[194891, 194891], "mapped", [16454]], [[194892, 194892], "mapped", [16534]], [[194893, 194893], "mapped", [152605]], [[194894, 194894], "mapped", [30798]], [[194895, 194895], "mapped", [30860]], [[194896, 194896], "mapped", [30924]], [[194897, 194897], "mapped", [16611]], [[194898, 194898], "mapped", [153126]], [[194899, 194899], "mapped", [31062]], [[194900, 194900], "mapped", [153242]], [[194901, 194901], "mapped", [153285]], [[194902, 194902], "mapped", [31119]], [[194903, 194903], "mapped", [31211]], [[194904, 194904], "mapped", [16687]], [[194905, 194905], "mapped", [31296]], [[194906, 194906], "mapped", [31306]], [[194907, 194907], "mapped", [31311]], [[194908, 194908], "mapped", [153980]], [[194909, 194910], "mapped", [154279]], [[194911, 194911], "disallowed"], [[194912, 194912], "mapped", [16898]], [[194913, 194913], "mapped", [154539]], [[194914, 194914], "mapped", [31686]], [[194915, 194915], "mapped", [31689]], [[194916, 194916], "mapped", [16935]], [[194917, 194917], "mapped", [154752]], [[194918, 194918], "mapped", [31954]], [[194919, 194919], "mapped", [17056]], [[194920, 194920], "mapped", [31976]], [[194921, 194921], "mapped", [31971]], [[194922, 194922], "mapped", [32e3]], [[194923, 194923], "mapped", [155526]], [[194924, 194924], "mapped", [32099]], [[194925, 194925], "mapped", [17153]], [[194926, 194926], "mapped", [32199]], [[194927, 194927], "mapped", [32258]], [[194928, 194928], "mapped", [32325]], [[194929, 194929], "mapped", [17204]], [[194930, 194930], "mapped", [156200]], [[194931, 194931], "mapped", [156231]], [[194932, 194932], "mapped", [17241]], [[194933, 194933], "mapped", [156377]], [[194934, 194934], "mapped", [32634]], [[194935, 194935], "mapped", [156478]], [[194936, 194936], "mapped", [32661]], [[194937, 194937], "mapped", [32762]], [[194938, 194938], "mapped", [32773]], [[194939, 194939], "mapped", [156890]], [[194940, 194940], "mapped", [156963]], [[194941, 194941], "mapped", [32864]], [[194942, 194942], "mapped", [157096]], [[194943, 194943], "mapped", [32880]], [[194944, 194944], "mapped", [144223]], [[194945, 194945], "mapped", [17365]], [[194946, 194946], "mapped", [32946]], [[194947, 194947], "mapped", [33027]], [[194948, 194948], "mapped", [17419]], [[194949, 194949], "mapped", [33086]], [[194950, 194950], "mapped", [23221]], [[194951, 194951], "mapped", [157607]], [[194952, 194952], "mapped", [157621]], [[194953, 194953], "mapped", [144275]], [[194954, 194954], "mapped", [144284]], [[194955, 194955], "mapped", [33281]], [[194956, 194956], "mapped", [33284]], [[194957, 194957], "mapped", [36766]], [[194958, 194958], "mapped", [17515]], [[194959, 194959], "mapped", [33425]], [[194960, 194960], "mapped", [33419]], [[194961, 194961], "mapped", [33437]], [[194962, 194962], "mapped", [21171]], [[194963, 194963], "mapped", [33457]], [[194964, 194964], "mapped", [33459]], [[194965, 194965], "mapped", [33469]], [[194966, 194966], "mapped", [33510]], [[194967, 194967], "mapped", [158524]], [[194968, 194968], "mapped", [33509]], [[194969, 194969], "mapped", [33565]], [[194970, 194970], "mapped", [33635]], [[194971, 194971], "mapped", [33709]], [[194972, 194972], "mapped", [33571]], [[194973, 194973], "mapped", [33725]], [[194974, 194974], "mapped", [33767]], [[194975, 194975], "mapped", [33879]], [[194976, 194976], "mapped", [33619]], [[194977, 194977], "mapped", [33738]], [[194978, 194978], "mapped", [33740]], [[194979, 194979], "mapped", [33756]], [[194980, 194980], "mapped", [158774]], [[194981, 194981], "mapped", [159083]], [[194982, 194982], "mapped", [158933]], [[194983, 194983], "mapped", [17707]], [[194984, 194984], "mapped", [34033]], [[194985, 194985], "mapped", [34035]], [[194986, 194986], "mapped", [34070]], [[194987, 194987], "mapped", [160714]], [[194988, 194988], "mapped", [34148]], [[194989, 194989], "mapped", [159532]], [[194990, 194990], "mapped", [17757]], [[194991, 194991], "mapped", [17761]], [[194992, 194992], "mapped", [159665]], [[194993, 194993], "mapped", [159954]], [[194994, 194994], "mapped", [17771]], [[194995, 194995], "mapped", [34384]], [[194996, 194996], "mapped", [34396]], [[194997, 194997], "mapped", [34407]], [[194998, 194998], "mapped", [34409]], [[194999, 194999], "mapped", [34473]], [[195e3, 195e3], "mapped", [34440]], [[195001, 195001], "mapped", [34574]], [[195002, 195002], "mapped", [34530]], [[195003, 195003], "mapped", [34681]], [[195004, 195004], "mapped", [34600]], [[195005, 195005], "mapped", [34667]], [[195006, 195006], "mapped", [34694]], [[195007, 195007], "disallowed"], [[195008, 195008], "mapped", [34785]], [[195009, 195009], "mapped", [34817]], [[195010, 195010], "mapped", [17913]], [[195011, 195011], "mapped", [34912]], [[195012, 195012], "mapped", [34915]], [[195013, 195013], "mapped", [161383]], [[195014, 195014], "mapped", [35031]], [[195015, 195015], "mapped", [35038]], [[195016, 195016], "mapped", [17973]], [[195017, 195017], "mapped", [35066]], [[195018, 195018], "mapped", [13499]], [[195019, 195019], "mapped", [161966]], [[195020, 195020], "mapped", [162150]], [[195021, 195021], "mapped", [18110]], [[195022, 195022], "mapped", [18119]], [[195023, 195023], "mapped", [35488]], [[195024, 195024], "mapped", [35565]], [[195025, 195025], "mapped", [35722]], [[195026, 195026], "mapped", [35925]], [[195027, 195027], "mapped", [162984]], [[195028, 195028], "mapped", [36011]], [[195029, 195029], "mapped", [36033]], [[195030, 195030], "mapped", [36123]], [[195031, 195031], "mapped", [36215]], [[195032, 195032], "mapped", [163631]], [[195033, 195033], "mapped", [133124]], [[195034, 195034], "mapped", [36299]], [[195035, 195035], "mapped", [36284]], [[195036, 195036], "mapped", [36336]], [[195037, 195037], "mapped", [133342]], [[195038, 195038], "mapped", [36564]], [[195039, 195039], "mapped", [36664]], [[195040, 195040], "mapped", [165330]], [[195041, 195041], "mapped", [165357]], [[195042, 195042], "mapped", [37012]], [[195043, 195043], "mapped", [37105]], [[195044, 195044], "mapped", [37137]], [[195045, 195045], "mapped", [165678]], [[195046, 195046], "mapped", [37147]], [[195047, 195047], "mapped", [37432]], [[195048, 195048], "mapped", [37591]], [[195049, 195049], "mapped", [37592]], [[195050, 195050], "mapped", [37500]], [[195051, 195051], "mapped", [37881]], [[195052, 195052], "mapped", [37909]], [[195053, 195053], "mapped", [166906]], [[195054, 195054], "mapped", [38283]], [[195055, 195055], "mapped", [18837]], [[195056, 195056], "mapped", [38327]], [[195057, 195057], "mapped", [167287]], [[195058, 195058], "mapped", [18918]], [[195059, 195059], "mapped", [38595]], [[195060, 195060], "mapped", [23986]], [[195061, 195061], "mapped", [38691]], [[195062, 195062], "mapped", [168261]], [[195063, 195063], "mapped", [168474]], [[195064, 195064], "mapped", [19054]], [[195065, 195065], "mapped", [19062]], [[195066, 195066], "mapped", [38880]], [[195067, 195067], "mapped", [168970]], [[195068, 195068], "mapped", [19122]], [[195069, 195069], "mapped", [169110]], [[195070, 195071], "mapped", [38923]], [[195072, 195072], "mapped", [38953]], [[195073, 195073], "mapped", [169398]], [[195074, 195074], "mapped", [39138]], [[195075, 195075], "mapped", [19251]], [[195076, 195076], "mapped", [39209]], [[195077, 195077], "mapped", [39335]], [[195078, 195078], "mapped", [39362]], [[195079, 195079], "mapped", [39422]], [[195080, 195080], "mapped", [19406]], [[195081, 195081], "mapped", [170800]], [[195082, 195082], "mapped", [39698]], [[195083, 195083], "mapped", [4e4]], [[195084, 195084], "mapped", [40189]], [[195085, 195085], "mapped", [19662]], [[195086, 195086], "mapped", [19693]], [[195087, 195087], "mapped", [40295]], [[195088, 195088], "mapped", [172238]], [[195089, 195089], "mapped", [19704]], [[195090, 195090], "mapped", [172293]], [[195091, 195091], "mapped", [172558]], [[195092, 195092], "mapped", [172689]], [[195093, 195093], "mapped", [40635]], [[195094, 195094], "mapped", [19798]], [[195095, 195095], "mapped", [40697]], [[195096, 195096], "mapped", [40702]], [[195097, 195097], "mapped", [40709]], [[195098, 195098], "mapped", [40719]], [[195099, 195099], "mapped", [40726]], [[195100, 195100], "mapped", [40763]], [[195101, 195101], "mapped", [173568]], [[195102, 196605], "disallowed"], [[196606, 196607], "disallowed"], [[196608, 262141], "disallowed"], [[262142, 262143], "disallowed"], [[262144, 327677], "disallowed"], [[327678, 327679], "disallowed"], [[327680, 393213], "disallowed"], [[393214, 393215], "disallowed"], [[393216, 458749], "disallowed"], [[458750, 458751], "disallowed"], [[458752, 524285], "disallowed"], [[524286, 524287], "disallowed"], [[524288, 589821], "disallowed"], [[589822, 589823], "disallowed"], [[589824, 655357], "disallowed"], [[655358, 655359], "disallowed"], [[655360, 720893], "disallowed"], [[720894, 720895], "disallowed"], [[720896, 786429], "disallowed"], [[786430, 786431], "disallowed"], [[786432, 851965], "disallowed"], [[851966, 851967], "disallowed"], [[851968, 917501], "disallowed"], [[917502, 917503], "disallowed"], [[917504, 917504], "disallowed"], [[917505, 917505], "disallowed"], [[917506, 917535], "disallowed"], [[917536, 917631], "disallowed"], [[917632, 917759], "disallowed"], [[917760, 917999], "ignored"], [[918e3, 983037], "disallowed"], [[983038, 983039], "disallowed"], [[983040, 1048573], "disallowed"], [[1048574, 1048575], "disallowed"], [[1048576, 1114109], "disallowed"], [[1114110, 1114111], "disallowed"]];
  }
});

// node_modules/node-fetch/node_modules/tr46/index.js
var require_tr46 = __commonJS({
  "node_modules/node-fetch/node_modules/tr46/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var punycode = __require("punycode");
    var mappingTable = require_mappingTable();
    var PROCESSING_OPTIONS = {
      TRANSITIONAL: 0,
      NONTRANSITIONAL: 1
    };
    function normalize10(str2) {
      return str2.split("\0").map(function(s2) {
        return s2.normalize("NFC");
      }).join("\0");
    }
    __name(normalize10, "normalize");
    function findStatus(val) {
      var start = 0;
      var end = mappingTable.length - 1;
      while (start <= end) {
        var mid = Math.floor((start + end) / 2);
        var target = mappingTable[mid];
        if (target[0][0] <= val && target[0][1] >= val) {
          return target;
        } else if (target[0][0] > val) {
          end = mid - 1;
        } else {
          start = mid + 1;
        }
      }
      return null;
    }
    __name(findStatus, "findStatus");
    var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
    function countSymbols(string) {
      return string.replace(regexAstralSymbols, "_").length;
    }
    __name(countSymbols, "countSymbols");
    function mapChars(domain_name, useSTD3, processing_option) {
      var hasError = false;
      var processed = "";
      var len = countSymbols(domain_name);
      for (var i = 0; i < len; ++i) {
        var codePoint = domain_name.codePointAt(i);
        var status = findStatus(codePoint);
        switch (status[1]) {
          case "disallowed":
            hasError = true;
            processed += String.fromCodePoint(codePoint);
            break;
          case "ignored":
            break;
          case "mapped":
            processed += String.fromCodePoint.apply(String, status[2]);
            break;
          case "deviation":
            if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) {
              processed += String.fromCodePoint.apply(String, status[2]);
            } else {
              processed += String.fromCodePoint(codePoint);
            }
            break;
          case "valid":
            processed += String.fromCodePoint(codePoint);
            break;
          case "disallowed_STD3_mapped":
            if (useSTD3) {
              hasError = true;
              processed += String.fromCodePoint(codePoint);
            } else {
              processed += String.fromCodePoint.apply(String, status[2]);
            }
            break;
          case "disallowed_STD3_valid":
            if (useSTD3) {
              hasError = true;
            }
            processed += String.fromCodePoint(codePoint);
            break;
        }
      }
      return {
        string: processed,
        error: hasError
      };
    }
    __name(mapChars, "mapChars");
    var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/;
    function validateLabel(label, processing_option) {
      if (label.substr(0, 4) === "xn--") {
        label = punycode.toUnicode(label);
        processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL;
      }
      var error = false;
      if (normalize10(label) !== label || label[3] === "-" && label[4] === "-" || label[0] === "-" || label[label.length - 1] === "-" || label.indexOf(".") !== -1 || label.search(combiningMarksRegex) === 0) {
        error = true;
      }
      var len = countSymbols(label);
      for (var i = 0; i < len; ++i) {
        var status = findStatus(label.codePointAt(i));
        if (processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid" || processing === PROCESSING_OPTIONS.NONTRANSITIONAL && status[1] !== "valid" && status[1] !== "deviation") {
          error = true;
          break;
        }
      }
      return {
        label,
        error
      };
    }
    __name(validateLabel, "validateLabel");
    function processing(domain_name, useSTD3, processing_option) {
      var result = mapChars(domain_name, useSTD3, processing_option);
      result.string = normalize10(result.string);
      var labels = result.string.split(".");
      for (var i = 0; i < labels.length; ++i) {
        try {
          var validation2 = validateLabel(labels[i]);
          labels[i] = validation2.label;
          result.error = result.error || validation2.error;
        } catch (e2) {
          result.error = true;
        }
      }
      return {
        string: labels.join("."),
        error: result.error
      };
    }
    __name(processing, "processing");
    module2.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) {
      var result = processing(domain_name, useSTD3, processing_option);
      var labels = result.string.split(".");
      labels = labels.map(function(l2) {
        try {
          return punycode.toASCII(l2);
        } catch (e2) {
          result.error = true;
          return l2;
        }
      });
      if (verifyDnsLength) {
        var total = labels.slice(0, labels.length - 1).join(".").length;
        if (total.length > 253 || total.length === 0) {
          result.error = true;
        }
        for (var i = 0; i < labels.length; ++i) {
          if (labels.length > 63 || labels.length === 0) {
            result.error = true;
            break;
          }
        }
      }
      if (result.error) return null;
      return labels.join(".");
    };
    module2.exports.toUnicode = function(domain_name, useSTD3) {
      var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL);
      return {
        domain: result.string,
        error: result.error
      };
    };
    module2.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS;
  }
});

// node_modules/node-fetch/node_modules/whatwg-url/lib/url-state-machine.js
var require_url_state_machine = __commonJS({
  "node_modules/node-fetch/node_modules/whatwg-url/lib/url-state-machine.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var punycode = __require("punycode");
    var tr46 = require_tr46();
    var specialSchemes = {
      ftp: 21,
      file: null,
      gopher: 70,
      http: 80,
      https: 443,
      ws: 80,
      wss: 443
    };
    var failure = Symbol("failure");
    function countSymbols(str2) {
      return punycode.ucs2.decode(str2).length;
    }
    __name(countSymbols, "countSymbols");
    function at(input, idx) {
      const c3 = input[idx];
      return isNaN(c3) ? void 0 : String.fromCodePoint(c3);
    }
    __name(at, "at");
    function isASCIIDigit(c3) {
      return c3 >= 48 && c3 <= 57;
    }
    __name(isASCIIDigit, "isASCIIDigit");
    function isASCIIAlpha2(c3) {
      return c3 >= 65 && c3 <= 90 || c3 >= 97 && c3 <= 122;
    }
    __name(isASCIIAlpha2, "isASCIIAlpha");
    function isASCIIAlphanumeric(c3) {
      return isASCIIAlpha2(c3) || isASCIIDigit(c3);
    }
    __name(isASCIIAlphanumeric, "isASCIIAlphanumeric");
    function isASCIIHex(c3) {
      return isASCIIDigit(c3) || c3 >= 65 && c3 <= 70 || c3 >= 97 && c3 <= 102;
    }
    __name(isASCIIHex, "isASCIIHex");
    function isSingleDot(buffer) {
      return buffer === "." || buffer.toLowerCase() === "%2e";
    }
    __name(isSingleDot, "isSingleDot");
    function isDoubleDot(buffer) {
      buffer = buffer.toLowerCase();
      return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e";
    }
    __name(isDoubleDot, "isDoubleDot");
    function isWindowsDriveLetterCodePoints(cp1, cp2) {
      return isASCIIAlpha2(cp1) && (cp2 === 58 || cp2 === 124);
    }
    __name(isWindowsDriveLetterCodePoints, "isWindowsDriveLetterCodePoints");
    function isWindowsDriveLetterString(string) {
      return string.length === 2 && isASCIIAlpha2(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|");
    }
    __name(isWindowsDriveLetterString, "isWindowsDriveLetterString");
    function isNormalizedWindowsDriveLetterString(string) {
      return string.length === 2 && isASCIIAlpha2(string.codePointAt(0)) && string[1] === ":";
    }
    __name(isNormalizedWindowsDriveLetterString, "isNormalizedWindowsDriveLetterString");
    function containsForbiddenHostCodePoint(string) {
      return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1;
    }
    __name(containsForbiddenHostCodePoint, "containsForbiddenHostCodePoint");
    function containsForbiddenHostCodePointExcludingPercent(string) {
      return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1;
    }
    __name(containsForbiddenHostCodePointExcludingPercent, "containsForbiddenHostCodePointExcludingPercent");
    function isSpecialScheme(scheme) {
      return specialSchemes[scheme] !== void 0;
    }
    __name(isSpecialScheme, "isSpecialScheme");
    function isSpecial(url2) {
      return isSpecialScheme(url2.scheme);
    }
    __name(isSpecial, "isSpecial");
    function defaultPort(scheme) {
      return specialSchemes[scheme];
    }
    __name(defaultPort, "defaultPort");
    function percentEncode(c3) {
      let hex = c3.toString(16).toUpperCase();
      if (hex.length === 1) {
        hex = "0" + hex;
      }
      return "%" + hex;
    }
    __name(percentEncode, "percentEncode");
    function utf8PercentEncode(c3) {
      const buf = new Buffer(c3);
      let str2 = "";
      for (let i = 0; i < buf.length; ++i) {
        str2 += percentEncode(buf[i]);
      }
      return str2;
    }
    __name(utf8PercentEncode, "utf8PercentEncode");
    function utf8PercentDecode(str2) {
      const input = new Buffer(str2);
      const output = [];
      for (let i = 0; i < input.length; ++i) {
        if (input[i] !== 37) {
          output.push(input[i]);
        } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) {
          output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16));
          i += 2;
        } else {
          output.push(input[i]);
        }
      }
      return new Buffer(output).toString();
    }
    __name(utf8PercentDecode, "utf8PercentDecode");
    function isC0ControlPercentEncode(c3) {
      return c3 <= 31 || c3 > 126;
    }
    __name(isC0ControlPercentEncode, "isC0ControlPercentEncode");
    var extraPathPercentEncodeSet = /* @__PURE__ */ new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]);
    function isPathPercentEncode(c3) {
      return isC0ControlPercentEncode(c3) || extraPathPercentEncodeSet.has(c3);
    }
    __name(isPathPercentEncode, "isPathPercentEncode");
    var extraUserinfoPercentEncodeSet = /* @__PURE__ */ new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]);
    function isUserinfoPercentEncode(c3) {
      return isPathPercentEncode(c3) || extraUserinfoPercentEncodeSet.has(c3);
    }
    __name(isUserinfoPercentEncode, "isUserinfoPercentEncode");
    function percentEncodeChar(c3, encodeSetPredicate) {
      const cStr = String.fromCodePoint(c3);
      if (encodeSetPredicate(c3)) {
        return utf8PercentEncode(cStr);
      }
      return cStr;
    }
    __name(percentEncodeChar, "percentEncodeChar");
    function parseIPv4Number(input) {
      let R = 10;
      if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") {
        input = input.substring(2);
        R = 16;
      } else if (input.length >= 2 && input.charAt(0) === "0") {
        input = input.substring(1);
        R = 8;
      }
      if (input === "") {
        return 0;
      }
      const regex3 = R === 10 ? /[^0-9]/ : R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/;
      if (regex3.test(input)) {
        return failure;
      }
      return parseInt(input, R);
    }
    __name(parseIPv4Number, "parseIPv4Number");
    function parseIPv4(input) {
      const parts = input.split(".");
      if (parts[parts.length - 1] === "") {
        if (parts.length > 1) {
          parts.pop();
        }
      }
      if (parts.length > 4) {
        return input;
      }
      const numbers = [];
      for (const part of parts) {
        if (part === "") {
          return input;
        }
        const n2 = parseIPv4Number(part);
        if (n2 === failure) {
          return input;
        }
        numbers.push(n2);
      }
      for (let i = 0; i < numbers.length - 1; ++i) {
        if (numbers[i] > 255) {
          return failure;
        }
      }
      if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) {
        return failure;
      }
      let ipv4 = numbers.pop();
      let counter = 0;
      for (const n2 of numbers) {
        ipv4 += n2 * Math.pow(256, 3 - counter);
        ++counter;
      }
      return ipv4;
    }
    __name(parseIPv4, "parseIPv4");
    function serializeIPv4(address) {
      let output = "";
      let n2 = address;
      for (let i = 1; i <= 4; ++i) {
        output = String(n2 % 256) + output;
        if (i !== 4) {
          output = "." + output;
        }
        n2 = Math.floor(n2 / 256);
      }
      return output;
    }
    __name(serializeIPv4, "serializeIPv4");
    function parseIPv6(input) {
      const address = [0, 0, 0, 0, 0, 0, 0, 0];
      let pieceIndex = 0;
      let compress = null;
      let pointer = 0;
      input = punycode.ucs2.decode(input);
      if (input[pointer] === 58) {
        if (input[pointer + 1] !== 58) {
          return failure;
        }
        pointer += 2;
        ++pieceIndex;
        compress = pieceIndex;
      }
      while (pointer < input.length) {
        if (pieceIndex === 8) {
          return failure;
        }
        if (input[pointer] === 58) {
          if (compress !== null) {
            return failure;
          }
          ++pointer;
          ++pieceIndex;
          compress = pieceIndex;
          continue;
        }
        let value = 0;
        let length = 0;
        while (length < 4 && isASCIIHex(input[pointer])) {
          value = value * 16 + parseInt(at(input, pointer), 16);
          ++pointer;
          ++length;
        }
        if (input[pointer] === 46) {
          if (length === 0) {
            return failure;
          }
          pointer -= length;
          if (pieceIndex > 6) {
            return failure;
          }
          let numbersSeen = 0;
          while (input[pointer] !== void 0) {
            let ipv4Piece = null;
            if (numbersSeen > 0) {
              if (input[pointer] === 46 && numbersSeen < 4) {
                ++pointer;
              } else {
                return failure;
              }
            }
            if (!isASCIIDigit(input[pointer])) {
              return failure;
            }
            while (isASCIIDigit(input[pointer])) {
              const number = parseInt(at(input, pointer));
              if (ipv4Piece === null) {
                ipv4Piece = number;
              } else if (ipv4Piece === 0) {
                return failure;
              } else {
                ipv4Piece = ipv4Piece * 10 + number;
              }
              if (ipv4Piece > 255) {
                return failure;
              }
              ++pointer;
            }
            address[pieceIndex] = address[pieceIndex] * 256 + ipv4Piece;
            ++numbersSeen;
            if (numbersSeen === 2 || numbersSeen === 4) {
              ++pieceIndex;
            }
          }
          if (numbersSeen !== 4) {
            return failure;
          }
          break;
        } else if (input[pointer] === 58) {
          ++pointer;
          if (input[pointer] === void 0) {
            return failure;
          }
        } else if (input[pointer] !== void 0) {
          return failure;
        }
        address[pieceIndex] = value;
        ++pieceIndex;
      }
      if (compress !== null) {
        let swaps = pieceIndex - compress;
        pieceIndex = 7;
        while (pieceIndex !== 0 && swaps > 0) {
          const temp = address[compress + swaps - 1];
          address[compress + swaps - 1] = address[pieceIndex];
          address[pieceIndex] = temp;
          --pieceIndex;
          --swaps;
        }
      } else if (compress === null && pieceIndex !== 8) {
        return failure;
      }
      return address;
    }
    __name(parseIPv6, "parseIPv6");
    function serializeIPv6(address) {
      let output = "";
      const seqResult = findLongestZeroSequence(address);
      const compress = seqResult.idx;
      let ignore0 = false;
      for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) {
        if (ignore0 && address[pieceIndex] === 0) {
          continue;
        } else if (ignore0) {
          ignore0 = false;
        }
        if (compress === pieceIndex) {
          const separator = pieceIndex === 0 ? "::" : ":";
          output += separator;
          ignore0 = true;
          continue;
        }
        output += address[pieceIndex].toString(16);
        if (pieceIndex !== 7) {
          output += ":";
        }
      }
      return output;
    }
    __name(serializeIPv6, "serializeIPv6");
    function parseHost(input, isSpecialArg) {
      if (input[0] === "[") {
        if (input[input.length - 1] !== "]") {
          return failure;
        }
        return parseIPv6(input.substring(1, input.length - 1));
      }
      if (!isSpecialArg) {
        return parseOpaqueHost(input);
      }
      const domain = utf8PercentDecode(input);
      const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false);
      if (asciiDomain === null) {
        return failure;
      }
      if (containsForbiddenHostCodePoint(asciiDomain)) {
        return failure;
      }
      const ipv4Host = parseIPv4(asciiDomain);
      if (typeof ipv4Host === "number" || ipv4Host === failure) {
        return ipv4Host;
      }
      return asciiDomain;
    }
    __name(parseHost, "parseHost");
    function parseOpaqueHost(input) {
      if (containsForbiddenHostCodePointExcludingPercent(input)) {
        return failure;
      }
      let output = "";
      const decoded = punycode.ucs2.decode(input);
      for (let i = 0; i < decoded.length; ++i) {
        output += percentEncodeChar(decoded[i], isC0ControlPercentEncode);
      }
      return output;
    }
    __name(parseOpaqueHost, "parseOpaqueHost");
    function findLongestZeroSequence(arr) {
      let maxIdx = null;
      let maxLen = 1;
      let currStart = null;
      let currLen = 0;
      for (let i = 0; i < arr.length; ++i) {
        if (arr[i] !== 0) {
          if (currLen > maxLen) {
            maxIdx = currStart;
            maxLen = currLen;
          }
          currStart = null;
          currLen = 0;
        } else {
          if (currStart === null) {
            currStart = i;
          }
          ++currLen;
        }
      }
      if (currLen > maxLen) {
        maxIdx = currStart;
        maxLen = currLen;
      }
      return {
        idx: maxIdx,
        len: maxLen
      };
    }
    __name(findLongestZeroSequence, "findLongestZeroSequence");
    function serializeHost(host) {
      if (typeof host === "number") {
        return serializeIPv4(host);
      }
      if (host instanceof Array) {
        return "[" + serializeIPv6(host) + "]";
      }
      return host;
    }
    __name(serializeHost, "serializeHost");
    function trimControlChars(url2) {
      return url2.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, "");
    }
    __name(trimControlChars, "trimControlChars");
    function trimTabAndNewline(url2) {
      return url2.replace(/\u0009|\u000A|\u000D/g, "");
    }
    __name(trimTabAndNewline, "trimTabAndNewline");
    function shortenPath2(url2) {
      const path108 = url2.path;
      if (path108.length === 0) {
        return;
      }
      if (url2.scheme === "file" && path108.length === 1 && isNormalizedWindowsDriveLetter(path108[0])) {
        return;
      }
      path108.pop();
    }
    __name(shortenPath2, "shortenPath");
    function includesCredentials(url2) {
      return url2.username !== "" || url2.password !== "";
    }
    __name(includesCredentials, "includesCredentials");
    function cannotHaveAUsernamePasswordPort(url2) {
      return url2.host === null || url2.host === "" || url2.cannotBeABaseURL || url2.scheme === "file";
    }
    __name(cannotHaveAUsernamePasswordPort, "cannotHaveAUsernamePasswordPort");
    function isNormalizedWindowsDriveLetter(string) {
      return /^[A-Za-z]:$/.test(string);
    }
    __name(isNormalizedWindowsDriveLetter, "isNormalizedWindowsDriveLetter");
    function URLStateMachine(input, base, encodingOverride, url2, stateOverride) {
      this.pointer = 0;
      this.input = input;
      this.base = base || null;
      this.encodingOverride = encodingOverride || "utf-8";
      this.stateOverride = stateOverride;
      this.url = url2;
      this.failure = false;
      this.parseError = false;
      if (!this.url) {
        this.url = {
          scheme: "",
          username: "",
          password: "",
          host: null,
          port: null,
          path: [],
          query: null,
          fragment: null,
          cannotBeABaseURL: false
        };
        const res2 = trimControlChars(this.input);
        if (res2 !== this.input) {
          this.parseError = true;
        }
        this.input = res2;
      }
      const res = trimTabAndNewline(this.input);
      if (res !== this.input) {
        this.parseError = true;
      }
      this.input = res;
      this.state = stateOverride || "scheme start";
      this.buffer = "";
      this.atFlag = false;
      this.arrFlag = false;
      this.passwordTokenSeenFlag = false;
      this.input = punycode.ucs2.decode(this.input);
      for (; this.pointer <= this.input.length; ++this.pointer) {
        const c3 = this.input[this.pointer];
        const cStr = isNaN(c3) ? void 0 : String.fromCodePoint(c3);
        const ret = this["parse " + this.state](c3, cStr);
        if (!ret) {
          break;
        } else if (ret === failure) {
          this.failure = true;
          break;
        }
      }
    }
    __name(URLStateMachine, "URLStateMachine");
    URLStateMachine.prototype["parse scheme start"] = /* @__PURE__ */ __name(function parseSchemeStart(c3, cStr) {
      if (isASCIIAlpha2(c3)) {
        this.buffer += cStr.toLowerCase();
        this.state = "scheme";
      } else if (!this.stateOverride) {
        this.state = "no scheme";
        --this.pointer;
      } else {
        this.parseError = true;
        return failure;
      }
      return true;
    }, "parseSchemeStart");
    URLStateMachine.prototype["parse scheme"] = /* @__PURE__ */ __name(function parseScheme(c3, cStr) {
      if (isASCIIAlphanumeric(c3) || c3 === 43 || c3 === 45 || c3 === 46) {
        this.buffer += cStr.toLowerCase();
      } else if (c3 === 58) {
        if (this.stateOverride) {
          if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) {
            return false;
          }
          if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) {
            return false;
          }
          if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") {
            return false;
          }
          if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) {
            return false;
          }
        }
        this.url.scheme = this.buffer;
        this.buffer = "";
        if (this.stateOverride) {
          return false;
        }
        if (this.url.scheme === "file") {
          if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) {
            this.parseError = true;
          }
          this.state = "file";
        } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) {
          this.state = "special relative or authority";
        } else if (isSpecial(this.url)) {
          this.state = "special authority slashes";
        } else if (this.input[this.pointer + 1] === 47) {
          this.state = "path or authority";
          ++this.pointer;
        } else {
          this.url.cannotBeABaseURL = true;
          this.url.path.push("");
          this.state = "cannot-be-a-base-URL path";
        }
      } else if (!this.stateOverride) {
        this.buffer = "";
        this.state = "no scheme";
        this.pointer = -1;
      } else {
        this.parseError = true;
        return failure;
      }
      return true;
    }, "parseScheme");
    URLStateMachine.prototype["parse no scheme"] = /* @__PURE__ */ __name(function parseNoScheme(c3) {
      if (this.base === null || this.base.cannotBeABaseURL && c3 !== 35) {
        return failure;
      } else if (this.base.cannotBeABaseURL && c3 === 35) {
        this.url.scheme = this.base.scheme;
        this.url.path = this.base.path.slice();
        this.url.query = this.base.query;
        this.url.fragment = "";
        this.url.cannotBeABaseURL = true;
        this.state = "fragment";
      } else if (this.base.scheme === "file") {
        this.state = "file";
        --this.pointer;
      } else {
        this.state = "relative";
        --this.pointer;
      }
      return true;
    }, "parseNoScheme");
    URLStateMachine.prototype["parse special relative or authority"] = /* @__PURE__ */ __name(function parseSpecialRelativeOrAuthority(c3) {
      if (c3 === 47 && this.input[this.pointer + 1] === 47) {
        this.state = "special authority ignore slashes";
        ++this.pointer;
      } else {
        this.parseError = true;
        this.state = "relative";
        --this.pointer;
      }
      return true;
    }, "parseSpecialRelativeOrAuthority");
    URLStateMachine.prototype["parse path or authority"] = /* @__PURE__ */ __name(function parsePathOrAuthority(c3) {
      if (c3 === 47) {
        this.state = "authority";
      } else {
        this.state = "path";
        --this.pointer;
      }
      return true;
    }, "parsePathOrAuthority");
    URLStateMachine.prototype["parse relative"] = /* @__PURE__ */ __name(function parseRelative(c3) {
      this.url.scheme = this.base.scheme;
      if (isNaN(c3)) {
        this.url.username = this.base.username;
        this.url.password = this.base.password;
        this.url.host = this.base.host;
        this.url.port = this.base.port;
        this.url.path = this.base.path.slice();
        this.url.query = this.base.query;
      } else if (c3 === 47) {
        this.state = "relative slash";
      } else if (c3 === 63) {
        this.url.username = this.base.username;
        this.url.password = this.base.password;
        this.url.host = this.base.host;
        this.url.port = this.base.port;
        this.url.path = this.base.path.slice();
        this.url.query = "";
        this.state = "query";
      } else if (c3 === 35) {
        this.url.username = this.base.username;
        this.url.password = this.base.password;
        this.url.host = this.base.host;
        this.url.port = this.base.port;
        this.url.path = this.base.path.slice();
        this.url.query = this.base.query;
        this.url.fragment = "";
        this.state = "fragment";
      } else if (isSpecial(this.url) && c3 === 92) {
        this.parseError = true;
        this.state = "relative slash";
      } else {
        this.url.username = this.base.username;
        this.url.password = this.base.password;
        this.url.host = this.base.host;
        this.url.port = this.base.port;
        this.url.path = this.base.path.slice(0, this.base.path.length - 1);
        this.state = "path";
        --this.pointer;
      }
      return true;
    }, "parseRelative");
    URLStateMachine.prototype["parse relative slash"] = /* @__PURE__ */ __name(function parseRelativeSlash(c3) {
      if (isSpecial(this.url) && (c3 === 47 || c3 === 92)) {
        if (c3 === 92) {
          this.parseError = true;
        }
        this.state = "special authority ignore slashes";
      } else if (c3 === 47) {
        this.state = "authority";
      } else {
        this.url.username = this.base.username;
        this.url.password = this.base.password;
        this.url.host = this.base.host;
        this.url.port = this.base.port;
        this.state = "path";
        --this.pointer;
      }
      return true;
    }, "parseRelativeSlash");
    URLStateMachine.prototype["parse special authority slashes"] = /* @__PURE__ */ __name(function parseSpecialAuthoritySlashes(c3) {
      if (c3 === 47 && this.input[this.pointer + 1] === 47) {
        this.state = "special authority ignore slashes";
        ++this.pointer;
      } else {
        this.parseError = true;
        this.state = "special authority ignore slashes";
        --this.pointer;
      }
      return true;
    }, "parseSpecialAuthoritySlashes");
    URLStateMachine.prototype["parse special authority ignore slashes"] = /* @__PURE__ */ __name(function parseSpecialAuthorityIgnoreSlashes(c3) {
      if (c3 !== 47 && c3 !== 92) {
        this.state = "authority";
        --this.pointer;
      } else {
        this.parseError = true;
      }
      return true;
    }, "parseSpecialAuthorityIgnoreSlashes");
    URLStateMachine.prototype["parse authority"] = /* @__PURE__ */ __name(function parseAuthority(c3, cStr) {
      if (c3 === 64) {
        this.parseError = true;
        if (this.atFlag) {
          this.buffer = "%40" + this.buffer;
        }
        this.atFlag = true;
        const len = countSymbols(this.buffer);
        for (let pointer = 0; pointer < len; ++pointer) {
          const codePoint = this.buffer.codePointAt(pointer);
          if (codePoint === 58 && !this.passwordTokenSeenFlag) {
            this.passwordTokenSeenFlag = true;
            continue;
          }
          const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode);
          if (this.passwordTokenSeenFlag) {
            this.url.password += encodedCodePoints;
          } else {
            this.url.username += encodedCodePoints;
          }
        }
        this.buffer = "";
      } else if (isNaN(c3) || c3 === 47 || c3 === 63 || c3 === 35 || isSpecial(this.url) && c3 === 92) {
        if (this.atFlag && this.buffer === "") {
          this.parseError = true;
          return failure;
        }
        this.pointer -= countSymbols(this.buffer) + 1;
        this.buffer = "";
        this.state = "host";
      } else {
        this.buffer += cStr;
      }
      return true;
    }, "parseAuthority");
    URLStateMachine.prototype["parse hostname"] = URLStateMachine.prototype["parse host"] = /* @__PURE__ */ __name(function parseHostName(c3, cStr) {
      if (this.stateOverride && this.url.scheme === "file") {
        --this.pointer;
        this.state = "file host";
      } else if (c3 === 58 && !this.arrFlag) {
        if (this.buffer === "") {
          this.parseError = true;
          return failure;
        }
        const host = parseHost(this.buffer, isSpecial(this.url));
        if (host === failure) {
          return failure;
        }
        this.url.host = host;
        this.buffer = "";
        this.state = "port";
        if (this.stateOverride === "hostname") {
          return false;
        }
      } else if (isNaN(c3) || c3 === 47 || c3 === 63 || c3 === 35 || isSpecial(this.url) && c3 === 92) {
        --this.pointer;
        if (isSpecial(this.url) && this.buffer === "") {
          this.parseError = true;
          return failure;
        } else if (this.stateOverride && this.buffer === "" && (includesCredentials(this.url) || this.url.port !== null)) {
          this.parseError = true;
          return false;
        }
        const host = parseHost(this.buffer, isSpecial(this.url));
        if (host === failure) {
          return failure;
        }
        this.url.host = host;
        this.buffer = "";
        this.state = "path start";
        if (this.stateOverride) {
          return false;
        }
      } else {
        if (c3 === 91) {
          this.arrFlag = true;
        } else if (c3 === 93) {
          this.arrFlag = false;
        }
        this.buffer += cStr;
      }
      return true;
    }, "parseHostName");
    URLStateMachine.prototype["parse port"] = /* @__PURE__ */ __name(function parsePort(c3, cStr) {
      if (isASCIIDigit(c3)) {
        this.buffer += cStr;
      } else if (isNaN(c3) || c3 === 47 || c3 === 63 || c3 === 35 || isSpecial(this.url) && c3 === 92 || this.stateOverride) {
        if (this.buffer !== "") {
          const port = parseInt(this.buffer);
          if (port > Math.pow(2, 16) - 1) {
            this.parseError = true;
            return failure;
          }
          this.url.port = port === defaultPort(this.url.scheme) ? null : port;
          this.buffer = "";
        }
        if (this.stateOverride) {
          return false;
        }
        this.state = "path start";
        --this.pointer;
      } else {
        this.parseError = true;
        return failure;
      }
      return true;
    }, "parsePort");
    var fileOtherwiseCodePoints = /* @__PURE__ */ new Set([47, 92, 63, 35]);
    URLStateMachine.prototype["parse file"] = /* @__PURE__ */ __name(function parseFile(c3) {
      this.url.scheme = "file";
      if (c3 === 47 || c3 === 92) {
        if (c3 === 92) {
          this.parseError = true;
        }
        this.state = "file slash";
      } else if (this.base !== null && this.base.scheme === "file") {
        if (isNaN(c3)) {
          this.url.host = this.base.host;
          this.url.path = this.base.path.slice();
          this.url.query = this.base.query;
        } else if (c3 === 63) {
          this.url.host = this.base.host;
          this.url.path = this.base.path.slice();
          this.url.query = "";
          this.state = "query";
        } else if (c3 === 35) {
          this.url.host = this.base.host;
          this.url.path = this.base.path.slice();
          this.url.query = this.base.query;
          this.url.fragment = "";
          this.state = "fragment";
        } else {
          if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points
          !isWindowsDriveLetterCodePoints(c3, this.input[this.pointer + 1]) || this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points
          !fileOtherwiseCodePoints.has(this.input[this.pointer + 2])) {
            this.url.host = this.base.host;
            this.url.path = this.base.path.slice();
            shortenPath2(this.url);
          } else {
            this.parseError = true;
          }
          this.state = "path";
          --this.pointer;
        }
      } else {
        this.state = "path";
        --this.pointer;
      }
      return true;
    }, "parseFile");
    URLStateMachine.prototype["parse file slash"] = /* @__PURE__ */ __name(function parseFileSlash(c3) {
      if (c3 === 47 || c3 === 92) {
        if (c3 === 92) {
          this.parseError = true;
        }
        this.state = "file host";
      } else {
        if (this.base !== null && this.base.scheme === "file") {
          if (isNormalizedWindowsDriveLetterString(this.base.path[0])) {
            this.url.path.push(this.base.path[0]);
          } else {
            this.url.host = this.base.host;
          }
        }
        this.state = "path";
        --this.pointer;
      }
      return true;
    }, "parseFileSlash");
    URLStateMachine.prototype["parse file host"] = /* @__PURE__ */ __name(function parseFileHost(c3, cStr) {
      if (isNaN(c3) || c3 === 47 || c3 === 92 || c3 === 63 || c3 === 35) {
        --this.pointer;
        if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) {
          this.parseError = true;
          this.state = "path";
        } else if (this.buffer === "") {
          this.url.host = "";
          if (this.stateOverride) {
            return false;
          }
          this.state = "path start";
        } else {
          let host = parseHost(this.buffer, isSpecial(this.url));
          if (host === failure) {
            return failure;
          }
          if (host === "localhost") {
            host = "";
          }
          this.url.host = host;
          if (this.stateOverride) {
            return false;
          }
          this.buffer = "";
          this.state = "path start";
        }
      } else {
        this.buffer += cStr;
      }
      return true;
    }, "parseFileHost");
    URLStateMachine.prototype["parse path start"] = /* @__PURE__ */ __name(function parsePathStart(c3) {
      if (isSpecial(this.url)) {
        if (c3 === 92) {
          this.parseError = true;
        }
        this.state = "path";
        if (c3 !== 47 && c3 !== 92) {
          --this.pointer;
        }
      } else if (!this.stateOverride && c3 === 63) {
        this.url.query = "";
        this.state = "query";
      } else if (!this.stateOverride && c3 === 35) {
        this.url.fragment = "";
        this.state = "fragment";
      } else if (c3 !== void 0) {
        this.state = "path";
        if (c3 !== 47) {
          --this.pointer;
        }
      }
      return true;
    }, "parsePathStart");
    URLStateMachine.prototype["parse path"] = /* @__PURE__ */ __name(function parsePath(c3) {
      if (isNaN(c3) || c3 === 47 || isSpecial(this.url) && c3 === 92 || !this.stateOverride && (c3 === 63 || c3 === 35)) {
        if (isSpecial(this.url) && c3 === 92) {
          this.parseError = true;
        }
        if (isDoubleDot(this.buffer)) {
          shortenPath2(this.url);
          if (c3 !== 47 && !(isSpecial(this.url) && c3 === 92)) {
            this.url.path.push("");
          }
        } else if (isSingleDot(this.buffer) && c3 !== 47 && !(isSpecial(this.url) && c3 === 92)) {
          this.url.path.push("");
        } else if (!isSingleDot(this.buffer)) {
          if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) {
            if (this.url.host !== "" && this.url.host !== null) {
              this.parseError = true;
              this.url.host = "";
            }
            this.buffer = this.buffer[0] + ":";
          }
          this.url.path.push(this.buffer);
        }
        this.buffer = "";
        if (this.url.scheme === "file" && (c3 === void 0 || c3 === 63 || c3 === 35)) {
          while (this.url.path.length > 1 && this.url.path[0] === "") {
            this.parseError = true;
            this.url.path.shift();
          }
        }
        if (c3 === 63) {
          this.url.query = "";
          this.state = "query";
        }
        if (c3 === 35) {
          this.url.fragment = "";
          this.state = "fragment";
        }
      } else {
        if (c3 === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
          this.parseError = true;
        }
        this.buffer += percentEncodeChar(c3, isPathPercentEncode);
      }
      return true;
    }, "parsePath");
    URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = /* @__PURE__ */ __name(function parseCannotBeABaseURLPath(c3) {
      if (c3 === 63) {
        this.url.query = "";
        this.state = "query";
      } else if (c3 === 35) {
        this.url.fragment = "";
        this.state = "fragment";
      } else {
        if (!isNaN(c3) && c3 !== 37) {
          this.parseError = true;
        }
        if (c3 === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
          this.parseError = true;
        }
        if (!isNaN(c3)) {
          this.url.path[0] = this.url.path[0] + percentEncodeChar(c3, isC0ControlPercentEncode);
        }
      }
      return true;
    }, "parseCannotBeABaseURLPath");
    URLStateMachine.prototype["parse query"] = /* @__PURE__ */ __name(function parseQuery(c3, cStr) {
      if (isNaN(c3) || !this.stateOverride && c3 === 35) {
        if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") {
          this.encodingOverride = "utf-8";
        }
        const buffer = new Buffer(this.buffer);
        for (let i = 0; i < buffer.length; ++i) {
          if (buffer[i] < 33 || buffer[i] > 126 || buffer[i] === 34 || buffer[i] === 35 || buffer[i] === 60 || buffer[i] === 62) {
            this.url.query += percentEncode(buffer[i]);
          } else {
            this.url.query += String.fromCodePoint(buffer[i]);
          }
        }
        this.buffer = "";
        if (c3 === 35) {
          this.url.fragment = "";
          this.state = "fragment";
        }
      } else {
        if (c3 === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
          this.parseError = true;
        }
        this.buffer += cStr;
      }
      return true;
    }, "parseQuery");
    URLStateMachine.prototype["parse fragment"] = /* @__PURE__ */ __name(function parseFragment(c3) {
      if (isNaN(c3)) {
      } else if (c3 === 0) {
        this.parseError = true;
      } else {
        if (c3 === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
          this.parseError = true;
        }
        this.url.fragment += percentEncodeChar(c3, isC0ControlPercentEncode);
      }
      return true;
    }, "parseFragment");
    function serializeURL(url2, excludeFragment) {
      let output = url2.scheme + ":";
      if (url2.host !== null) {
        output += "//";
        if (url2.username !== "" || url2.password !== "") {
          output += url2.username;
          if (url2.password !== "") {
            output += ":" + url2.password;
          }
          output += "@";
        }
        output += serializeHost(url2.host);
        if (url2.port !== null) {
          output += ":" + url2.port;
        }
      } else if (url2.host === null && url2.scheme === "file") {
        output += "//";
      }
      if (url2.cannotBeABaseURL) {
        output += url2.path[0];
      } else {
        for (const string of url2.path) {
          output += "/" + string;
        }
      }
      if (url2.query !== null) {
        output += "?" + url2.query;
      }
      if (!excludeFragment && url2.fragment !== null) {
        output += "#" + url2.fragment;
      }
      return output;
    }
    __name(serializeURL, "serializeURL");
    function serializeOrigin(tuple) {
      let result = tuple.scheme + "://";
      result += serializeHost(tuple.host);
      if (tuple.port !== null) {
        result += ":" + tuple.port;
      }
      return result;
    }
    __name(serializeOrigin, "serializeOrigin");
    module2.exports.serializeURL = serializeURL;
    module2.exports.serializeURLOrigin = function(url2) {
      switch (url2.scheme) {
        case "blob":
          try {
            return module2.exports.serializeURLOrigin(module2.exports.parseURL(url2.path[0]));
          } catch (e2) {
            return "null";
          }
        case "ftp":
        case "gopher":
        case "http":
        case "https":
        case "ws":
        case "wss":
          return serializeOrigin({
            scheme: url2.scheme,
            host: url2.host,
            port: url2.port
          });
        case "file":
          return "file://";
        default:
          return "null";
      }
    };
    module2.exports.basicURLParse = function(input, options2) {
      if (options2 === void 0) {
        options2 = {};
      }
      const usm = new URLStateMachine(input, options2.baseURL, options2.encodingOverride, options2.url, options2.stateOverride);
      if (usm.failure) {
        return "failure";
      }
      return usm.url;
    };
    module2.exports.setTheUsername = function(url2, username) {
      url2.username = "";
      const decoded = punycode.ucs2.decode(username);
      for (let i = 0; i < decoded.length; ++i) {
        url2.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode);
      }
    };
    module2.exports.setThePassword = function(url2, password) {
      url2.password = "";
      const decoded = punycode.ucs2.decode(password);
      for (let i = 0; i < decoded.length; ++i) {
        url2.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode);
      }
    };
    module2.exports.serializeHost = serializeHost;
    module2.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort;
    module2.exports.serializeInteger = function(integer) {
      return String(integer);
    };
    module2.exports.parseURL = function(input, options2) {
      if (options2 === void 0) {
        options2 = {};
      }
      return module2.exports.basicURLParse(input, { baseURL: options2.baseURL, encodingOverride: options2.encodingOverride });
    };
  }
});

// node_modules/node-fetch/node_modules/whatwg-url/lib/URL-impl.js
var require_URL_impl = __commonJS({
  "node_modules/node-fetch/node_modules/whatwg-url/lib/URL-impl.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var usm = require_url_state_machine();
    exports2.implementation = class URLImpl {
      static {
        __name(this, "URLImpl");
      }
      constructor(constructorArgs) {
        const url2 = constructorArgs[0];
        const base = constructorArgs[1];
        let parsedBase = null;
        if (base !== void 0) {
          parsedBase = usm.basicURLParse(base);
          if (parsedBase === "failure") {
            throw new TypeError("Invalid base URL");
          }
        }
        const parsedURL = usm.basicURLParse(url2, { baseURL: parsedBase });
        if (parsedURL === "failure") {
          throw new TypeError("Invalid URL");
        }
        this._url = parsedURL;
      }
      get href() {
        return usm.serializeURL(this._url);
      }
      set href(v) {
        const parsedURL = usm.basicURLParse(v);
        if (parsedURL === "failure") {
          throw new TypeError("Invalid URL");
        }
        this._url = parsedURL;
      }
      get origin() {
        return usm.serializeURLOrigin(this._url);
      }
      get protocol() {
        return this._url.scheme + ":";
      }
      set protocol(v) {
        usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" });
      }
      get username() {
        return this._url.username;
      }
      set username(v) {
        if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
          return;
        }
        usm.setTheUsername(this._url, v);
      }
      get password() {
        return this._url.password;
      }
      set password(v) {
        if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
          return;
        }
        usm.setThePassword(this._url, v);
      }
      get host() {
        const url2 = this._url;
        if (url2.host === null) {
          return "";
        }
        if (url2.port === null) {
          return usm.serializeHost(url2.host);
        }
        return usm.serializeHost(url2.host) + ":" + usm.serializeInteger(url2.port);
      }
      set host(v) {
        if (this._url.cannotBeABaseURL) {
          return;
        }
        usm.basicURLParse(v, { url: this._url, stateOverride: "host" });
      }
      get hostname() {
        if (this._url.host === null) {
          return "";
        }
        return usm.serializeHost(this._url.host);
      }
      set hostname(v) {
        if (this._url.cannotBeABaseURL) {
          return;
        }
        usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" });
      }
      get port() {
        if (this._url.port === null) {
          return "";
        }
        return usm.serializeInteger(this._url.port);
      }
      set port(v) {
        if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
          return;
        }
        if (v === "") {
          this._url.port = null;
        } else {
          usm.basicURLParse(v, { url: this._url, stateOverride: "port" });
        }
      }
      get pathname() {
        if (this._url.cannotBeABaseURL) {
          return this._url.path[0];
        }
        if (this._url.path.length === 0) {
          return "";
        }
        return "/" + this._url.path.join("/");
      }
      set pathname(v) {
        if (this._url.cannotBeABaseURL) {
          return;
        }
        this._url.path = [];
        usm.basicURLParse(v, { url: this._url, stateOverride: "path start" });
      }
      get search() {
        if (this._url.query === null || this._url.query === "") {
          return "";
        }
        return "?" + this._url.query;
      }
      set search(v) {
        const url2 = this._url;
        if (v === "") {
          url2.query = null;
          return;
        }
        const input = v[0] === "?" ? v.substring(1) : v;
        url2.query = "";
        usm.basicURLParse(input, { url: url2, stateOverride: "query" });
      }
      get hash() {
        if (this._url.fragment === null || this._url.fragment === "") {
          return "";
        }
        return "#" + this._url.fragment;
      }
      set hash(v) {
        if (v === "") {
          this._url.fragment = null;
          return;
        }
        const input = v[0] === "#" ? v.substring(1) : v;
        this._url.fragment = "";
        usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" });
      }
      toJSON() {
        return this.href;
      }
    };
  }
});

// node_modules/node-fetch/node_modules/whatwg-url/lib/URL.js
var require_URL = __commonJS({
  "node_modules/node-fetch/node_modules/whatwg-url/lib/URL.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var conversions = require_lib();
    var utils = require_utils2();
    var Impl = require_URL_impl();
    var impl = utils.implSymbol;
    function URL6(url2) {
      if (!this || this[impl] || !(this instanceof URL6)) {
        throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function.");
      }
      if (arguments.length < 1) {
        throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present.");
      }
      const args = [];
      for (let i = 0; i < arguments.length && i < 2; ++i) {
        args[i] = arguments[i];
      }
      args[0] = conversions["USVString"](args[0]);
      if (args[1] !== void 0) {
        args[1] = conversions["USVString"](args[1]);
      }
      module2.exports.setup(this, args);
    }
    __name(URL6, "URL");
    URL6.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
      if (!this || !module2.exports.is(this)) {
        throw new TypeError("Illegal invocation");
      }
      const args = [];
      for (let i = 0; i < arguments.length && i < 0; ++i) {
        args[i] = arguments[i];
      }
      return this[impl].toJSON.apply(this[impl], args);
    }, "toJSON");
    Object.defineProperty(URL6.prototype, "href", {
      get() {
        return this[impl].href;
      },
      set(V2) {
        V2 = conversions["USVString"](V2);
        this[impl].href = V2;
      },
      enumerable: true,
      configurable: true
    });
    URL6.prototype.toString = function() {
      if (!this || !module2.exports.is(this)) {
        throw new TypeError("Illegal invocation");
      }
      return this.href;
    };
    Object.defineProperty(URL6.prototype, "origin", {
      get() {
        return this[impl].origin;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL6.prototype, "protocol", {
      get() {
        return this[impl].protocol;
      },
      set(V2) {
        V2 = conversions["USVString"](V2);
        this[impl].protocol = V2;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL6.prototype, "username", {
      get() {
        return this[impl].username;
      },
      set(V2) {
        V2 = conversions["USVString"](V2);
        this[impl].username = V2;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL6.prototype, "password", {
      get() {
        return this[impl].password;
      },
      set(V2) {
        V2 = conversions["USVString"](V2);
        this[impl].password = V2;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL6.prototype, "host", {
      get() {
        return this[impl].host;
      },
      set(V2) {
        V2 = conversions["USVString"](V2);
        this[impl].host = V2;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL6.prototype, "hostname", {
      get() {
        return this[impl].hostname;
      },
      set(V2) {
        V2 = conversions["USVString"](V2);
        this[impl].hostname = V2;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL6.prototype, "port", {
      get() {
        return this[impl].port;
      },
      set(V2) {
        V2 = conversions["USVString"](V2);
        this[impl].port = V2;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL6.prototype, "pathname", {
      get() {
        return this[impl].pathname;
      },
      set(V2) {
        V2 = conversions["USVString"](V2);
        this[impl].pathname = V2;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL6.prototype, "search", {
      get() {
        return this[impl].search;
      },
      set(V2) {
        V2 = conversions["USVString"](V2);
        this[impl].search = V2;
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(URL6.prototype, "hash", {
      get() {
        return this[impl].hash;
      },
      set(V2) {
        V2 = conversions["USVString"](V2);
        this[impl].hash = V2;
      },
      enumerable: true,
      configurable: true
    });
    module2.exports = {
      is(obj) {
        return !!obj && obj[impl] instanceof Impl.implementation;
      },
      create(constructorArgs, privateData) {
        let obj = Object.create(URL6.prototype);
        this.setup(obj, constructorArgs, privateData);
        return obj;
      },
      setup(obj, constructorArgs, privateData) {
        if (!privateData) privateData = {};
        privateData.wrapper = obj;
        obj[impl] = new Impl.implementation(constructorArgs, privateData);
        obj[impl][utils.wrapperSymbol] = obj;
      },
      interface: URL6,
      expose: {
        Window: { URL: URL6 },
        Worker: { URL: URL6 }
      }
    };
  }
});

// node_modules/node-fetch/node_modules/whatwg-url/lib/public-api.js
var require_public_api = __commonJS({
  "node_modules/node-fetch/node_modules/whatwg-url/lib/public-api.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    exports2.URL = require_URL().interface;
    exports2.serializeURL = require_url_state_machine().serializeURL;
    exports2.serializeURLOrigin = require_url_state_machine().serializeURLOrigin;
    exports2.basicURLParse = require_url_state_machine().basicURLParse;
    exports2.setTheUsername = require_url_state_machine().setTheUsername;
    exports2.setThePassword = require_url_state_machine().setThePassword;
    exports2.serializeHost = require_url_state_machine().serializeHost;
    exports2.serializeInteger = require_url_state_machine().serializeInteger;
    exports2.parseURL = require_url_state_machine().parseURL;
  }
});

// node_modules/node-fetch/lib/index.js
var require_lib2 = __commonJS({
  "node_modules/node-fetch/lib/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    function _interopDefault(ex) {
      return ex && typeof ex === "object" && "default" in ex ? ex["default"] : ex;
    }
    __name(_interopDefault, "_interopDefault");
    var Stream4 = _interopDefault(__require("stream"));
    var http4 = _interopDefault(__require("http"));
    var Url = _interopDefault(__require("url"));
    var whatwgUrl = _interopDefault(require_public_api());
    var https4 = _interopDefault(__require("https"));
    var zlib2 = _interopDefault(__require("zlib"));
    var Readable4 = Stream4.Readable;
    var BUFFER3 = Symbol("buffer");
    var TYPE2 = Symbol("type");
    var Blob2 = class _Blob {
      static {
        __name(this, "Blob");
      }
      constructor() {
        this[TYPE2] = "";
        const blobParts = arguments[0];
        const options2 = arguments[1];
        const buffers = [];
        let size = 0;
        if (blobParts) {
          const a = blobParts;
          const length = Number(a.length);
          for (let i = 0; i < length; i++) {
            const element = a[i];
            let buffer;
            if (element instanceof Buffer) {
              buffer = element;
            } else if (ArrayBuffer.isView(element)) {
              buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
            } else if (element instanceof ArrayBuffer) {
              buffer = Buffer.from(element);
            } else if (element instanceof _Blob) {
              buffer = element[BUFFER3];
            } else {
              buffer = Buffer.from(typeof element === "string" ? element : String(element));
            }
            size += buffer.length;
            buffers.push(buffer);
          }
        }
        this[BUFFER3] = Buffer.concat(buffers);
        let type = options2 && options2.type !== void 0 && String(options2.type).toLowerCase();
        if (type && !/[^\u0020-\u007E]/.test(type)) {
          this[TYPE2] = type;
        }
      }
      get size() {
        return this[BUFFER3].length;
      }
      get type() {
        return this[TYPE2];
      }
      text() {
        return Promise.resolve(this[BUFFER3].toString());
      }
      arrayBuffer() {
        const buf = this[BUFFER3];
        const ab2 = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
        return Promise.resolve(ab2);
      }
      stream() {
        const readable = new Readable4();
        readable._read = function() {
        };
        readable.push(this[BUFFER3]);
        readable.push(null);
        return readable;
      }
      toString() {
        return "[object Blob]";
      }
      slice() {
        const size = this.size;
        const start = arguments[0];
        const end = arguments[1];
        let relativeStart, relativeEnd;
        if (start === void 0) {
          relativeStart = 0;
        } else if (start < 0) {
          relativeStart = Math.max(size + start, 0);
        } else {
          relativeStart = Math.min(start, size);
        }
        if (end === void 0) {
          relativeEnd = size;
        } else if (end < 0) {
          relativeEnd = Math.max(size + end, 0);
        } else {
          relativeEnd = Math.min(end, size);
        }
        const span = Math.max(relativeEnd - relativeStart, 0);
        const buffer = this[BUFFER3];
        const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
        const blob = new _Blob([], { type: arguments[2] });
        blob[BUFFER3] = slicedBuffer;
        return blob;
      }
    };
    Object.defineProperties(Blob2.prototype, {
      size: { enumerable: true },
      type: { enumerable: true },
      slice: { enumerable: true }
    });
    Object.defineProperty(Blob2.prototype, Symbol.toStringTag, {
      value: "Blob",
      writable: false,
      enumerable: false,
      configurable: true
    });
    function FetchError2(message, type, systemError) {
      Error.call(this, message);
      this.message = message;
      this.type = type;
      if (systemError) {
        this.code = this.errno = systemError.code;
      }
      Error.captureStackTrace(this, this.constructor);
    }
    __name(FetchError2, "FetchError");
    FetchError2.prototype = Object.create(Error.prototype);
    FetchError2.prototype.constructor = FetchError2;
    FetchError2.prototype.name = "FetchError";
    var convert2;
    try {
      convert2 = __require("encoding").convert;
    } catch (e2) {
    }
    var INTERNALS = Symbol("Body internals");
    var PassThrough4 = Stream4.PassThrough;
    function Body(body) {
      var _this = this;
      var _ref = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, _ref$size = _ref.size;
      let size = _ref$size === void 0 ? 0 : _ref$size;
      var _ref$timeout = _ref.timeout;
      let timeout2 = _ref$timeout === void 0 ? 0 : _ref$timeout;
      if (body == null) {
        body = null;
      } else if (isURLSearchParams(body)) {
        body = Buffer.from(body.toString());
      } else if (isBlob(body)) ;
      else if (Buffer.isBuffer(body)) ;
      else if (Object.prototype.toString.call(body) === "[object ArrayBuffer]") {
        body = Buffer.from(body);
      } else if (ArrayBuffer.isView(body)) {
        body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
      } else if (body instanceof Stream4) ;
      else {
        body = Buffer.from(String(body));
      }
      this[INTERNALS] = {
        body,
        disturbed: false,
        error: null
      };
      this.size = size;
      this.timeout = timeout2;
      if (body instanceof Stream4) {
        body.on("error", function(err) {
          const error = err.name === "AbortError" ? err : new FetchError2(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, "system", err);
          _this[INTERNALS].error = error;
        });
      }
    }
    __name(Body, "Body");
    Body.prototype = {
      get body() {
        return this[INTERNALS].body;
      },
      get bodyUsed() {
        return this[INTERNALS].disturbed;
      },
      /**
       * Decode response as ArrayBuffer
       *
       * @return  Promise
       */
      arrayBuffer() {
        return consumeBody.call(this).then(function(buf) {
          return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
        });
      },
      /**
       * Return raw response as Blob
       *
       * @return Promise
       */
      blob() {
        let ct = this.headers && this.headers.get("content-type") || "";
        return consumeBody.call(this).then(function(buf) {
          return Object.assign(
            // Prevent copying
            new Blob2([], {
              type: ct.toLowerCase()
            }),
            {
              [BUFFER3]: buf
            }
          );
        });
      },
      /**
       * Decode response as json
       *
       * @return  Promise
       */
      json() {
        var _this2 = this;
        return consumeBody.call(this).then(function(buffer) {
          try {
            return JSON.parse(buffer.toString());
          } catch (err) {
            return Body.Promise.reject(new FetchError2(`invalid json response body at ${_this2.url} reason: ${err.message}`, "invalid-json"));
          }
        });
      },
      /**
       * Decode response as text
       *
       * @return  Promise
       */
      text() {
        return consumeBody.call(this).then(function(buffer) {
          return buffer.toString();
        });
      },
      /**
       * Decode response as buffer (non-spec api)
       *
       * @return  Promise
       */
      buffer() {
        return consumeBody.call(this);
      },
      /**
       * Decode response as text, while automatically detecting the encoding and
       * trying to decode to UTF-8 (non-spec api)
       *
       * @return  Promise
       */
      textConverted() {
        var _this3 = this;
        return consumeBody.call(this).then(function(buffer) {
          return convertBody(buffer, _this3.headers);
        });
      }
    };
    Object.defineProperties(Body.prototype, {
      body: { enumerable: true },
      bodyUsed: { enumerable: true },
      arrayBuffer: { enumerable: true },
      blob: { enumerable: true },
      json: { enumerable: true },
      text: { enumerable: true }
    });
    Body.mixIn = function(proto3) {
      for (const name3 of Object.getOwnPropertyNames(Body.prototype)) {
        if (!(name3 in proto3)) {
          const desc2 = Object.getOwnPropertyDescriptor(Body.prototype, name3);
          Object.defineProperty(proto3, name3, desc2);
        }
      }
    };
    function consumeBody() {
      var _this4 = this;
      if (this[INTERNALS].disturbed) {
        return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
      }
      this[INTERNALS].disturbed = true;
      if (this[INTERNALS].error) {
        return Body.Promise.reject(this[INTERNALS].error);
      }
      let body = this.body;
      if (body === null) {
        return Body.Promise.resolve(Buffer.alloc(0));
      }
      if (isBlob(body)) {
        body = body.stream();
      }
      if (Buffer.isBuffer(body)) {
        return Body.Promise.resolve(body);
      }
      if (!(body instanceof Stream4)) {
        return Body.Promise.resolve(Buffer.alloc(0));
      }
      let accum = [];
      let accumBytes = 0;
      let abort = false;
      return new Body.Promise(function(resolve24, reject) {
        let resTimeout;
        if (_this4.timeout) {
          resTimeout = setTimeout(function() {
            abort = true;
            reject(new FetchError2(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, "body-timeout"));
          }, _this4.timeout);
        }
        body.on("error", function(err) {
          if (err.name === "AbortError") {
            abort = true;
            reject(err);
          } else {
            reject(new FetchError2(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, "system", err));
          }
        });
        body.on("data", function(chunk) {
          if (abort || chunk === null) {
            return;
          }
          if (_this4.size && accumBytes + chunk.length > _this4.size) {
            abort = true;
            reject(new FetchError2(`content size at ${_this4.url} over limit: ${_this4.size}`, "max-size"));
            return;
          }
          accumBytes += chunk.length;
          accum.push(chunk);
        });
        body.on("end", function() {
          if (abort) {
            return;
          }
          clearTimeout(resTimeout);
          try {
            resolve24(Buffer.concat(accum, accumBytes));
          } catch (err) {
            reject(new FetchError2(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, "system", err));
          }
        });
      });
    }
    __name(consumeBody, "consumeBody");
    function convertBody(buffer, headers) {
      if (typeof convert2 !== "function") {
        throw new Error("The package `encoding` must be installed to use the textConverted() function");
      }
      const ct = headers.get("content-type");
      let charset = "utf-8";
      let res, str2;
      if (ct) {
        res = /charset=([^;]*)/i.exec(ct);
      }
      str2 = buffer.slice(0, 1024).toString();
      if (!res && str2) {
        res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str2);
      }
      if (!res && str2) {
        res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str2);
        if (!res) {
          res = /<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(str2);
          if (res) {
            res.pop();
          }
        }
        if (res) {
          res = /charset=(.*)/i.exec(res.pop());
        }
      }
      if (!res && str2) {
        res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str2);
      }
      if (res) {
        charset = res.pop();
        if (charset === "gb2312" || charset === "gbk") {
          charset = "gb18030";
        }
      }
      return convert2(buffer, "UTF-8", charset).toString();
    }
    __name(convertBody, "convertBody");
    function isURLSearchParams(obj) {
      if (typeof obj !== "object" || typeof obj.append !== "function" || typeof obj.delete !== "function" || typeof obj.get !== "function" || typeof obj.getAll !== "function" || typeof obj.has !== "function" || typeof obj.set !== "function") {
        return false;
      }
      return obj.constructor.name === "URLSearchParams" || Object.prototype.toString.call(obj) === "[object URLSearchParams]" || typeof obj.sort === "function";
    }
    __name(isURLSearchParams, "isURLSearchParams");
    function isBlob(obj) {
      return typeof obj === "object" && typeof obj.arrayBuffer === "function" && typeof obj.type === "string" && typeof obj.stream === "function" && typeof obj.constructor === "function" && typeof obj.constructor.name === "string" && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]);
    }
    __name(isBlob, "isBlob");
    function clone(instance) {
      let p1, p2;
      let body = instance.body;
      if (instance.bodyUsed) {
        throw new Error("cannot clone body after it is used");
      }
      if (body instanceof Stream4 && typeof body.getBoundary !== "function") {
        p1 = new PassThrough4();
        p2 = new PassThrough4();
        body.pipe(p1);
        body.pipe(p2);
        instance[INTERNALS].body = p1;
        body = p2;
      }
      return body;
    }
    __name(clone, "clone");
    function extractContentType(body) {
      if (body === null) {
        return null;
      } else if (typeof body === "string") {
        return "text/plain;charset=UTF-8";
      } else if (isURLSearchParams(body)) {
        return "application/x-www-form-urlencoded;charset=UTF-8";
      } else if (isBlob(body)) {
        return body.type || null;
      } else if (Buffer.isBuffer(body)) {
        return null;
      } else if (Object.prototype.toString.call(body) === "[object ArrayBuffer]") {
        return null;
      } else if (ArrayBuffer.isView(body)) {
        return null;
      } else if (typeof body.getBoundary === "function") {
        return `multipart/form-data;boundary=${body.getBoundary()}`;
      } else if (body instanceof Stream4) {
        return null;
      } else {
        return "text/plain;charset=UTF-8";
      }
    }
    __name(extractContentType, "extractContentType");
    function getTotalBytes(instance) {
      const body = instance.body;
      if (body === null) {
        return 0;
      } else if (isBlob(body)) {
        return body.size;
      } else if (Buffer.isBuffer(body)) {
        return body.length;
      } else if (body && typeof body.getLengthSync === "function") {
        if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x
        body.hasKnownLength && body.hasKnownLength()) {
          return body.getLengthSync();
        }
        return null;
      } else {
        return null;
      }
    }
    __name(getTotalBytes, "getTotalBytes");
    function writeToStream(dest, instance) {
      const body = instance.body;
      if (body === null) {
        dest.end();
      } else if (isBlob(body)) {
        body.stream().pipe(dest);
      } else if (Buffer.isBuffer(body)) {
        dest.write(body);
        dest.end();
      } else {
        body.pipe(dest);
      }
    }
    __name(writeToStream, "writeToStream");
    Body.Promise = globalThis.Promise;
    var invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;
    var invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
    function validateName2(name3) {
      name3 = `${name3}`;
      if (invalidTokenRegex.test(name3) || name3 === "") {
        throw new TypeError(`${name3} is not a legal HTTP header name`);
      }
    }
    __name(validateName2, "validateName");
    function validateValue2(value) {
      value = `${value}`;
      if (invalidHeaderCharRegex.test(value)) {
        throw new TypeError(`${value} is not a legal HTTP header value`);
      }
    }
    __name(validateValue2, "validateValue");
    function find(map2, name3) {
      name3 = name3.toLowerCase();
      for (const key in map2) {
        if (key.toLowerCase() === name3) {
          return key;
        }
      }
      return void 0;
    }
    __name(find, "find");
    var MAP = Symbol("map");
    var Headers2 = class _Headers {
      static {
        __name(this, "Headers");
      }
      /**
       * Headers class
       *
       * @param   Object  headers  Response headers
       * @return  Void
       */
      constructor() {
        let init = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : void 0;
        this[MAP] = /* @__PURE__ */ Object.create(null);
        if (init instanceof _Headers) {
          const rawHeaders = init.raw();
          const headerNames = Object.keys(rawHeaders);
          for (const headerName of headerNames) {
            for (const value of rawHeaders[headerName]) {
              this.append(headerName, value);
            }
          }
          return;
        }
        if (init == null) ;
        else if (typeof init === "object") {
          const method = init[Symbol.iterator];
          if (method != null) {
            if (typeof method !== "function") {
              throw new TypeError("Header pairs must be iterable");
            }
            const pairs = [];
            for (const pair of init) {
              if (typeof pair !== "object" || typeof pair[Symbol.iterator] !== "function") {
                throw new TypeError("Each header pair must be iterable");
              }
              pairs.push(Array.from(pair));
            }
            for (const pair of pairs) {
              if (pair.length !== 2) {
                throw new TypeError("Each header pair must be a name/value tuple");
              }
              this.append(pair[0], pair[1]);
            }
          } else {
            for (const key of Object.keys(init)) {
              const value = init[key];
              this.append(key, value);
            }
          }
        } else {
          throw new TypeError("Provided initializer must be an object");
        }
      }
      /**
       * Return combined header value given name
       *
       * @param   String  name  Header name
       * @return  Mixed
       */
      get(name3) {
        name3 = `${name3}`;
        validateName2(name3);
        const key = find(this[MAP], name3);
        if (key === void 0) {
          return null;
        }
        return this[MAP][key].join(", ");
      }
      /**
       * Iterate over all headers
       *
       * @param   Function  callback  Executed for each item with parameters (value, name, thisArg)
       * @param   Boolean   thisArg   `this` context for callback function
       * @return  Void
       */
      forEach(callback) {
        let thisArg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : void 0;
        let pairs = getHeaders(this);
        let i = 0;
        while (i < pairs.length) {
          var _pairs$i = pairs[i];
          const name3 = _pairs$i[0], value = _pairs$i[1];
          callback.call(thisArg, value, name3, this);
          pairs = getHeaders(this);
          i++;
        }
      }
      /**
       * Overwrite header values given name
       *
       * @param   String  name   Header name
       * @param   String  value  Header value
       * @return  Void
       */
      set(name3, value) {
        name3 = `${name3}`;
        value = `${value}`;
        validateName2(name3);
        validateValue2(value);
        const key = find(this[MAP], name3);
        this[MAP][key !== void 0 ? key : name3] = [value];
      }
      /**
       * Append a value onto existing header
       *
       * @param   String  name   Header name
       * @param   String  value  Header value
       * @return  Void
       */
      append(name3, value) {
        name3 = `${name3}`;
        value = `${value}`;
        validateName2(name3);
        validateValue2(value);
        const key = find(this[MAP], name3);
        if (key !== void 0) {
          this[MAP][key].push(value);
        } else {
          this[MAP][name3] = [value];
        }
      }
      /**
       * Check for header name existence
       *
       * @param   String   name  Header name
       * @return  Boolean
       */
      has(name3) {
        name3 = `${name3}`;
        validateName2(name3);
        return find(this[MAP], name3) !== void 0;
      }
      /**
       * Delete all header values given name
       *
       * @param   String  name  Header name
       * @return  Void
       */
      delete(name3) {
        name3 = `${name3}`;
        validateName2(name3);
        const key = find(this[MAP], name3);
        if (key !== void 0) {
          delete this[MAP][key];
        }
      }
      /**
       * Return raw headers (non-spec api)
       *
       * @return  Object
       */
      raw() {
        return this[MAP];
      }
      /**
       * Get an iterator on keys.
       *
       * @return  Iterator
       */
      keys() {
        return createHeadersIterator(this, "key");
      }
      /**
       * Get an iterator on values.
       *
       * @return  Iterator
       */
      values() {
        return createHeadersIterator(this, "value");
      }
      /**
       * Get an iterator on entries.
       *
       * This is the default iterator of the Headers object.
       *
       * @return  Iterator
       */
      [Symbol.iterator]() {
        return createHeadersIterator(this, "key+value");
      }
    };
    Headers2.prototype.entries = Headers2.prototype[Symbol.iterator];
    Object.defineProperty(Headers2.prototype, Symbol.toStringTag, {
      value: "Headers",
      writable: false,
      enumerable: false,
      configurable: true
    });
    Object.defineProperties(Headers2.prototype, {
      get: { enumerable: true },
      forEach: { enumerable: true },
      set: { enumerable: true },
      append: { enumerable: true },
      has: { enumerable: true },
      delete: { enumerable: true },
      keys: { enumerable: true },
      values: { enumerable: true },
      entries: { enumerable: true }
    });
    function getHeaders(headers) {
      let kind = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "key+value";
      const keys = Object.keys(headers[MAP]).sort();
      return keys.map(kind === "key" ? function(k) {
        return k.toLowerCase();
      } : kind === "value" ? function(k) {
        return headers[MAP][k].join(", ");
      } : function(k) {
        return [k.toLowerCase(), headers[MAP][k].join(", ")];
      });
    }
    __name(getHeaders, "getHeaders");
    var INTERNAL = Symbol("internal");
    function createHeadersIterator(target, kind) {
      const iterator = Object.create(HeadersIteratorPrototype);
      iterator[INTERNAL] = {
        target,
        kind,
        index: 0
      };
      return iterator;
    }
    __name(createHeadersIterator, "createHeadersIterator");
    var HeadersIteratorPrototype = Object.setPrototypeOf({
      next() {
        if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
          throw new TypeError("Value of `this` is not a HeadersIterator");
        }
        var _INTERNAL = this[INTERNAL];
        const target = _INTERNAL.target, kind = _INTERNAL.kind, index = _INTERNAL.index;
        const values = getHeaders(target, kind);
        const len = values.length;
        if (index >= len) {
          return {
            value: void 0,
            done: true
          };
        }
        this[INTERNAL].index = index + 1;
        return {
          value: values[index],
          done: false
        };
      }
    }, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
    Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
      value: "HeadersIterator",
      writable: false,
      enumerable: false,
      configurable: true
    });
    function exportNodeCompatibleHeaders(headers) {
      const obj = Object.assign({ __proto__: null }, headers[MAP]);
      const hostHeaderKey = find(headers[MAP], "Host");
      if (hostHeaderKey !== void 0) {
        obj[hostHeaderKey] = obj[hostHeaderKey][0];
      }
      return obj;
    }
    __name(exportNodeCompatibleHeaders, "exportNodeCompatibleHeaders");
    function createHeadersLenient(obj) {
      const headers = new Headers2();
      for (const name3 of Object.keys(obj)) {
        if (invalidTokenRegex.test(name3)) {
          continue;
        }
        if (Array.isArray(obj[name3])) {
          for (const val of obj[name3]) {
            if (invalidHeaderCharRegex.test(val)) {
              continue;
            }
            if (headers[MAP][name3] === void 0) {
              headers[MAP][name3] = [val];
            } else {
              headers[MAP][name3].push(val);
            }
          }
        } else if (!invalidHeaderCharRegex.test(obj[name3])) {
          headers[MAP][name3] = [obj[name3]];
        }
      }
      return headers;
    }
    __name(createHeadersLenient, "createHeadersLenient");
    var INTERNALS$1 = Symbol("Response internals");
    var STATUS_CODES = http4.STATUS_CODES;
    var Response2 = class _Response {
      static {
        __name(this, "Response");
      }
      constructor() {
        let body = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : null;
        let opts = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
        Body.call(this, body, opts);
        const status = opts.status || 200;
        const headers = new Headers2(opts.headers);
        if (body != null && !headers.has("Content-Type")) {
          const contentType = extractContentType(body);
          if (contentType) {
            headers.append("Content-Type", contentType);
          }
        }
        this[INTERNALS$1] = {
          url: opts.url,
          status,
          statusText: opts.statusText || STATUS_CODES[status],
          headers,
          counter: opts.counter
        };
      }
      get url() {
        return this[INTERNALS$1].url || "";
      }
      get status() {
        return this[INTERNALS$1].status;
      }
      /**
       * Convenience property representing if the request ended normally
       */
      get ok() {
        return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
      }
      get redirected() {
        return this[INTERNALS$1].counter > 0;
      }
      get statusText() {
        return this[INTERNALS$1].statusText;
      }
      get headers() {
        return this[INTERNALS$1].headers;
      }
      /**
       * Clone this response
       *
       * @return  Response
       */
      clone() {
        return new _Response(clone(this), {
          url: this.url,
          status: this.status,
          statusText: this.statusText,
          headers: this.headers,
          ok: this.ok,
          redirected: this.redirected
        });
      }
    };
    Body.mixIn(Response2.prototype);
    Object.defineProperties(Response2.prototype, {
      url: { enumerable: true },
      status: { enumerable: true },
      ok: { enumerable: true },
      redirected: { enumerable: true },
      statusText: { enumerable: true },
      headers: { enumerable: true },
      clone: { enumerable: true }
    });
    Object.defineProperty(Response2.prototype, Symbol.toStringTag, {
      value: "Response",
      writable: false,
      enumerable: false,
      configurable: true
    });
    var INTERNALS$2 = Symbol("Request internals");
    var URL6 = Url.URL || whatwgUrl.URL;
    var parse_url = Url.parse;
    var format_url = Url.format;
    function parseURL(urlStr) {
      if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) {
        urlStr = new URL6(urlStr).toString();
      }
      return parse_url(urlStr);
    }
    __name(parseURL, "parseURL");
    var streamDestructionSupported = "destroy" in Stream4.Readable.prototype;
    function isRequest(input) {
      return typeof input === "object" && typeof input[INTERNALS$2] === "object";
    }
    __name(isRequest, "isRequest");
    function isAbortSignal(signal) {
      const proto3 = signal && typeof signal === "object" && Object.getPrototypeOf(signal);
      return !!(proto3 && proto3.constructor.name === "AbortSignal");
    }
    __name(isAbortSignal, "isAbortSignal");
    var Request2 = class _Request {
      static {
        __name(this, "Request");
      }
      constructor(input) {
        let init = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
        let parsedURL;
        if (!isRequest(input)) {
          if (input && input.href) {
            parsedURL = parseURL(input.href);
          } else {
            parsedURL = parseURL(`${input}`);
          }
          input = {};
        } else {
          parsedURL = parseURL(input.url);
        }
        let method = init.method || input.method || "GET";
        method = method.toUpperCase();
        if ((init.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) {
          throw new TypeError("Request with GET/HEAD method cannot have body");
        }
        let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
        Body.call(this, inputBody, {
          timeout: init.timeout || input.timeout || 0,
          size: init.size || input.size || 0
        });
        const headers = new Headers2(init.headers || input.headers || {});
        if (inputBody != null && !headers.has("Content-Type")) {
          const contentType = extractContentType(inputBody);
          if (contentType) {
            headers.append("Content-Type", contentType);
          }
        }
        let signal = isRequest(input) ? input.signal : null;
        if ("signal" in init) signal = init.signal;
        if (signal != null && !isAbortSignal(signal)) {
          throw new TypeError("Expected signal to be an instanceof AbortSignal");
        }
        this[INTERNALS$2] = {
          method,
          redirect: init.redirect || input.redirect || "follow",
          headers,
          parsedURL,
          signal
        };
        this.follow = init.follow !== void 0 ? init.follow : input.follow !== void 0 ? input.follow : 20;
        this.compress = init.compress !== void 0 ? init.compress : input.compress !== void 0 ? input.compress : true;
        this.counter = init.counter || input.counter || 0;
        this.agent = init.agent || input.agent;
      }
      get method() {
        return this[INTERNALS$2].method;
      }
      get url() {
        return format_url(this[INTERNALS$2].parsedURL);
      }
      get headers() {
        return this[INTERNALS$2].headers;
      }
      get redirect() {
        return this[INTERNALS$2].redirect;
      }
      get signal() {
        return this[INTERNALS$2].signal;
      }
      /**
       * Clone this request
       *
       * @return  Request
       */
      clone() {
        return new _Request(this);
      }
    };
    Body.mixIn(Request2.prototype);
    Object.defineProperty(Request2.prototype, Symbol.toStringTag, {
      value: "Request",
      writable: false,
      enumerable: false,
      configurable: true
    });
    Object.defineProperties(Request2.prototype, {
      method: { enumerable: true },
      url: { enumerable: true },
      headers: { enumerable: true },
      redirect: { enumerable: true },
      clone: { enumerable: true },
      signal: { enumerable: true }
    });
    function getNodeRequestOptions(request4) {
      const parsedURL = request4[INTERNALS$2].parsedURL;
      const headers = new Headers2(request4[INTERNALS$2].headers);
      if (!headers.has("Accept")) {
        headers.set("Accept", "*/*");
      }
      if (!parsedURL.protocol || !parsedURL.hostname) {
        throw new TypeError("Only absolute URLs are supported");
      }
      if (!/^https?:$/.test(parsedURL.protocol)) {
        throw new TypeError("Only HTTP(S) protocols are supported");
      }
      if (request4.signal && request4.body instanceof Stream4.Readable && !streamDestructionSupported) {
        throw new Error("Cancellation of streamed requests with AbortSignal is not supported in node < 8");
      }
      let contentLengthValue = null;
      if (request4.body == null && /^(POST|PUT)$/i.test(request4.method)) {
        contentLengthValue = "0";
      }
      if (request4.body != null) {
        const totalBytes = getTotalBytes(request4);
        if (typeof totalBytes === "number") {
          contentLengthValue = String(totalBytes);
        }
      }
      if (contentLengthValue) {
        headers.set("Content-Length", contentLengthValue);
      }
      if (!headers.has("User-Agent")) {
        headers.set("User-Agent", "node-fetch/1.0 (+https://github.com/bitinn/node-fetch)");
      }
      if (request4.compress && !headers.has("Accept-Encoding")) {
        headers.set("Accept-Encoding", "gzip,deflate");
      }
      let agent = request4.agent;
      if (typeof agent === "function") {
        agent = agent(parsedURL);
      }
      return Object.assign({}, parsedURL, {
        method: request4.method,
        headers: exportNodeCompatibleHeaders(headers),
        agent
      });
    }
    __name(getNodeRequestOptions, "getNodeRequestOptions");
    function AbortError2(message) {
      Error.call(this, message);
      this.type = "aborted";
      this.message = message;
      Error.captureStackTrace(this, this.constructor);
    }
    __name(AbortError2, "AbortError");
    AbortError2.prototype = Object.create(Error.prototype);
    AbortError2.prototype.constructor = AbortError2;
    AbortError2.prototype.name = "AbortError";
    var URL$1 = Url.URL || whatwgUrl.URL;
    var PassThrough$1 = Stream4.PassThrough;
    var isDomainOrSubdomain = /* @__PURE__ */ __name(function isDomainOrSubdomain2(destination, original) {
      const orig = new URL$1(original).hostname;
      const dest = new URL$1(destination).hostname;
      return orig === dest || orig[orig.length - dest.length - 1] === "." && orig.endsWith(dest);
    }, "isDomainOrSubdomain");
    var isSameProtocol = /* @__PURE__ */ __name(function isSameProtocol2(destination, original) {
      const orig = new URL$1(original).protocol;
      const dest = new URL$1(destination).protocol;
      return orig === dest;
    }, "isSameProtocol");
    function fetch2(url2, opts) {
      if (!fetch2.Promise) {
        throw new Error("native promise missing, set fetch.Promise to your favorite alternative");
      }
      Body.Promise = fetch2.Promise;
      return new fetch2.Promise(function(resolve24, reject) {
        const request4 = new Request2(url2, opts);
        const options2 = getNodeRequestOptions(request4);
        const send = (options2.protocol === "https:" ? https4 : http4).request;
        const signal = request4.signal;
        let response = null;
        const abort = /* @__PURE__ */ __name(function abort2() {
          let error = new AbortError2("The user aborted a request.");
          reject(error);
          if (request4.body && request4.body instanceof Stream4.Readable) {
            destroyStream(request4.body, error);
          }
          if (!response || !response.body) return;
          response.body.emit("error", error);
        }, "abort");
        if (signal && signal.aborted) {
          abort();
          return;
        }
        const abortAndFinalize = /* @__PURE__ */ __name(function abortAndFinalize2() {
          abort();
          finalize();
        }, "abortAndFinalize");
        const req = send(options2);
        let reqTimeout;
        if (signal) {
          signal.addEventListener("abort", abortAndFinalize);
        }
        function finalize() {
          req.abort();
          if (signal) signal.removeEventListener("abort", abortAndFinalize);
          clearTimeout(reqTimeout);
        }
        __name(finalize, "finalize");
        if (request4.timeout) {
          req.once("socket", function(socket) {
            reqTimeout = setTimeout(function() {
              reject(new FetchError2(`network timeout at: ${request4.url}`, "request-timeout"));
              finalize();
            }, request4.timeout);
          });
        }
        req.on("error", function(err) {
          reject(new FetchError2(`request to ${request4.url} failed, reason: ${err.message}`, "system", err));
          if (response && response.body) {
            destroyStream(response.body, err);
          }
          finalize();
        });
        fixResponseChunkedTransferBadEnding(req, function(err) {
          if (signal && signal.aborted) {
            return;
          }
          if (response && response.body) {
            destroyStream(response.body, err);
          }
        });
        if (parseInt(process.version.substring(1)) < 14) {
          req.on("socket", function(s2) {
            s2.addListener("close", function(hadError) {
              const hasDataListener = s2.listenerCount("data") > 0;
              if (response && hasDataListener && !hadError && !(signal && signal.aborted)) {
                const err = new Error("Premature close");
                err.code = "ERR_STREAM_PREMATURE_CLOSE";
                response.body.emit("error", err);
              }
            });
          });
        }
        req.on("response", function(res) {
          clearTimeout(reqTimeout);
          const headers = createHeadersLenient(res.headers);
          if (fetch2.isRedirect(res.statusCode)) {
            const location = headers.get("Location");
            let locationURL = null;
            try {
              locationURL = location === null ? null : new URL$1(location, request4.url).toString();
            } catch (err) {
              if (request4.redirect !== "manual") {
                reject(new FetchError2(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect"));
                finalize();
                return;
              }
            }
            switch (request4.redirect) {
              case "error":
                reject(new FetchError2(`uri requested responds with a redirect, redirect mode is set to error: ${request4.url}`, "no-redirect"));
                finalize();
                return;
              case "manual":
                if (locationURL !== null) {
                  try {
                    headers.set("Location", locationURL);
                  } catch (err) {
                    reject(err);
                  }
                }
                break;
              case "follow":
                if (locationURL === null) {
                  break;
                }
                if (request4.counter >= request4.follow) {
                  reject(new FetchError2(`maximum redirect reached at: ${request4.url}`, "max-redirect"));
                  finalize();
                  return;
                }
                const requestOpts = {
                  headers: new Headers2(request4.headers),
                  follow: request4.follow,
                  counter: request4.counter + 1,
                  agent: request4.agent,
                  compress: request4.compress,
                  method: request4.method,
                  body: request4.body,
                  signal: request4.signal,
                  timeout: request4.timeout,
                  size: request4.size
                };
                if (!isDomainOrSubdomain(request4.url, locationURL) || !isSameProtocol(request4.url, locationURL)) {
                  for (const name3 of ["authorization", "www-authenticate", "cookie", "cookie2"]) {
                    requestOpts.headers.delete(name3);
                  }
                }
                if (res.statusCode !== 303 && request4.body && getTotalBytes(request4) === null) {
                  reject(new FetchError2("Cannot follow redirect with body being a readable stream", "unsupported-redirect"));
                  finalize();
                  return;
                }
                if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request4.method === "POST") {
                  requestOpts.method = "GET";
                  requestOpts.body = void 0;
                  requestOpts.headers.delete("content-length");
                }
                resolve24(fetch2(new Request2(locationURL, requestOpts)));
                finalize();
                return;
            }
          }
          res.once("end", function() {
            if (signal) signal.removeEventListener("abort", abortAndFinalize);
          });
          let body = res.pipe(new PassThrough$1());
          const response_options = {
            url: request4.url,
            status: res.statusCode,
            statusText: res.statusMessage,
            headers,
            size: request4.size,
            timeout: request4.timeout,
            counter: request4.counter
          };
          const codings = headers.get("Content-Encoding");
          if (!request4.compress || request4.method === "HEAD" || codings === null || res.statusCode === 204 || res.statusCode === 304) {
            response = new Response2(body, response_options);
            resolve24(response);
            return;
          }
          const zlibOptions = {
            flush: zlib2.Z_SYNC_FLUSH,
            finishFlush: zlib2.Z_SYNC_FLUSH
          };
          if (codings == "gzip" || codings == "x-gzip") {
            body = body.pipe(zlib2.createGunzip(zlibOptions));
            response = new Response2(body, response_options);
            resolve24(response);
            return;
          }
          if (codings == "deflate" || codings == "x-deflate") {
            const raw2 = res.pipe(new PassThrough$1());
            raw2.once("data", function(chunk) {
              if ((chunk[0] & 15) === 8) {
                body = body.pipe(zlib2.createInflate());
              } else {
                body = body.pipe(zlib2.createInflateRaw());
              }
              response = new Response2(body, response_options);
              resolve24(response);
            });
            raw2.on("end", function() {
              if (!response) {
                response = new Response2(body, response_options);
                resolve24(response);
              }
            });
            return;
          }
          if (codings == "br" && typeof zlib2.createBrotliDecompress === "function") {
            body = body.pipe(zlib2.createBrotliDecompress());
            response = new Response2(body, response_options);
            resolve24(response);
            return;
          }
          response = new Response2(body, response_options);
          resolve24(response);
        });
        writeToStream(req, request4);
      });
    }
    __name(fetch2, "fetch");
    function fixResponseChunkedTransferBadEnding(request4, errorCallback) {
      let socket;
      request4.on("socket", function(s2) {
        socket = s2;
      });
      request4.on("response", function(response) {
        const headers = response.headers;
        if (headers["transfer-encoding"] === "chunked" && !headers["content-length"]) {
          response.once("close", function(hadError) {
            const hasDataListener = socket && socket.listenerCount("data") > 0;
            if (hasDataListener && !hadError) {
              const err = new Error("Premature close");
              err.code = "ERR_STREAM_PREMATURE_CLOSE";
              errorCallback(err);
            }
          });
        }
      });
    }
    __name(fixResponseChunkedTransferBadEnding, "fixResponseChunkedTransferBadEnding");
    function destroyStream(stream2, err) {
      if (stream2.destroy) {
        stream2.destroy(err);
      } else {
        stream2.emit("error", err);
        stream2.end();
      }
    }
    __name(destroyStream, "destroyStream");
    fetch2.isRedirect = function(code2) {
      return code2 === 301 || code2 === 302 || code2 === 303 || code2 === 307 || code2 === 308;
    };
    fetch2.Promise = globalThis.Promise;
    module2.exports = exports2 = fetch2;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.default = exports2;
    exports2.Headers = Headers2;
    exports2.Request = Request2;
    exports2.Response = Response2;
    exports2.FetchError = FetchError2;
    exports2.AbortError = AbortError2;
  }
});

// node_modules/is-stream/index.js
var require_is_stream = __commonJS({
  "node_modules/is-stream/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var isStream2 = /* @__PURE__ */ __name((stream2) => stream2 !== null && typeof stream2 === "object" && typeof stream2.pipe === "function", "isStream");
    isStream2.writable = (stream2) => isStream2(stream2) && stream2.writable !== false && typeof stream2._write === "function" && typeof stream2._writableState === "object";
    isStream2.readable = (stream2) => isStream2(stream2) && stream2.readable !== false && typeof stream2._read === "function" && typeof stream2._readableState === "object";
    isStream2.duplex = (stream2) => isStream2.writable(stream2) && isStream2.readable(stream2);
    isStream2.transform = (stream2) => isStream2.duplex(stream2) && typeof stream2._transform === "function";
    module2.exports = isStream2;
  }
});

// node_modules/gaxios/package.json
var require_package = __commonJS({
  "node_modules/gaxios/package.json"(exports2, module2) {
    module2.exports = {
      name: "gaxios",
      version: "6.7.1",
      description: "A simple common HTTP client specifically for Google APIs and services.",
      main: "build/src/index.js",
      types: "build/src/index.d.ts",
      files: [
        "build/src"
      ],
      scripts: {
        lint: "gts check",
        test: "c8 mocha build/test",
        "presystem-test": "npm run compile",
        "system-test": "mocha build/system-test --timeout 80000",
        compile: "tsc -p .",
        fix: "gts fix",
        prepare: "npm run compile",
        pretest: "npm run compile",
        webpack: "webpack",
        "prebrowser-test": "npm run compile",
        "browser-test": "node build/browser-test/browser-test-runner.js",
        docs: "compodoc src/",
        "docs-test": "linkinator docs",
        "predocs-test": "npm run docs",
        "samples-test": "cd samples/ && npm link ../ && npm test && cd ../",
        prelint: "cd samples; npm link ../; npm install",
        clean: "gts clean",
        precompile: "gts clean"
      },
      repository: "googleapis/gaxios",
      keywords: [
        "google"
      ],
      engines: {
        node: ">=14"
      },
      author: "Google, LLC",
      license: "Apache-2.0",
      devDependencies: {
        "@babel/plugin-proposal-private-methods": "^7.18.6",
        "@compodoc/compodoc": "1.1.19",
        "@types/cors": "^2.8.6",
        "@types/express": "^4.16.1",
        "@types/extend": "^3.0.1",
        "@types/mocha": "^9.0.0",
        "@types/multiparty": "0.0.36",
        "@types/mv": "^2.1.0",
        "@types/ncp": "^2.0.1",
        "@types/node": "^20.0.0",
        "@types/node-fetch": "^2.5.7",
        "@types/sinon": "^17.0.0",
        "@types/tmp": "0.2.6",
        "@types/uuid": "^10.0.0",
        "abort-controller": "^3.0.0",
        assert: "^2.0.0",
        browserify: "^17.0.0",
        c8: "^8.0.0",
        cheerio: "1.0.0-rc.10",
        cors: "^2.8.5",
        execa: "^5.0.0",
        express: "^4.16.4",
        "form-data": "^4.0.0",
        gts: "^5.0.0",
        "is-docker": "^2.0.0",
        karma: "^6.0.0",
        "karma-chrome-launcher": "^3.0.0",
        "karma-coverage": "^2.0.0",
        "karma-firefox-launcher": "^2.0.0",
        "karma-mocha": "^2.0.0",
        "karma-remap-coverage": "^0.1.5",
        "karma-sourcemap-loader": "^0.4.0",
        "karma-webpack": "5.0.0",
        linkinator: "^3.0.0",
        mocha: "^8.0.0",
        multiparty: "^4.2.1",
        mv: "^2.1.1",
        ncp: "^2.0.0",
        nock: "^13.0.0",
        "null-loader": "^4.0.0",
        puppeteer: "^19.0.0",
        sinon: "^18.0.0",
        "stream-browserify": "^3.0.0",
        tmp: "0.2.3",
        "ts-loader": "^8.0.0",
        typescript: "^5.1.6",
        webpack: "^5.35.0",
        "webpack-cli": "^4.0.0"
      },
      dependencies: {
        extend: "^3.0.2",
        "https-proxy-agent": "^7.0.1",
        "is-stream": "^2.0.0",
        "node-fetch": "^2.6.9",
        uuid: "^9.0.1"
      }
    };
  }
});

// node_modules/gaxios/build/src/util.js
var require_util7 = __commonJS({
  "node_modules/gaxios/build/src/util.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.pkg = void 0;
    exports2.pkg = require_package();
  }
});

// node_modules/gaxios/build/src/common.js
var require_common = __commonJS({
  "node_modules/gaxios/build/src/common.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
      return mod2 && mod2.__esModule ? mod2 : { "default": mod2 };
    };
    var _a6;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.GaxiosError = exports2.GAXIOS_ERROR_SYMBOL = void 0;
    exports2.defaultErrorRedactor = defaultErrorRedactor;
    var url_1 = __require("url");
    var util_1 = require_util7();
    var extend_1 = __importDefault(require_extend());
    exports2.GAXIOS_ERROR_SYMBOL = Symbol.for(`${util_1.pkg.name}-gaxios-error`);
    var GaxiosError = class _GaxiosError extends Error {
      static {
        __name(this, "GaxiosError");
      }
      /**
       * Support `instanceof` operator for `GaxiosError` across builds/duplicated files.
       *
       * @see {@link GAXIOS_ERROR_SYMBOL}
       * @see {@link GaxiosError[GAXIOS_ERROR_SYMBOL]}
       */
      static [(_a6 = exports2.GAXIOS_ERROR_SYMBOL, Symbol.hasInstance)](instance) {
        if (instance && typeof instance === "object" && exports2.GAXIOS_ERROR_SYMBOL in instance && instance[exports2.GAXIOS_ERROR_SYMBOL] === util_1.pkg.version) {
          return true;
        }
        return Function.prototype[Symbol.hasInstance].call(_GaxiosError, instance);
      }
      constructor(message, config, response, error) {
        var _b2;
        super(message);
        this.config = config;
        this.response = response;
        this.error = error;
        this[_a6] = util_1.pkg.version;
        this.config = (0, extend_1.default)(true, {}, config);
        if (this.response) {
          this.response.config = (0, extend_1.default)(true, {}, this.response.config);
        }
        if (this.response) {
          try {
            this.response.data = translateData(this.config.responseType, (_b2 = this.response) === null || _b2 === void 0 ? void 0 : _b2.data);
          } catch (_c2) {
          }
          this.status = this.response.status;
        }
        if (error && "code" in error && error.code) {
          this.code = error.code;
        }
        if (config.errorRedactor) {
          config.errorRedactor({
            config: this.config,
            response: this.response
          });
        }
      }
    };
    exports2.GaxiosError = GaxiosError;
    function translateData(responseType, data) {
      switch (responseType) {
        case "stream":
          return data;
        case "json":
          return JSON.parse(JSON.stringify(data));
        case "arraybuffer":
          return JSON.parse(Buffer.from(data).toString("utf8"));
        case "blob":
          return JSON.parse(data.text());
        default:
          return data;
      }
    }
    __name(translateData, "translateData");
    function defaultErrorRedactor(data) {
      const REDACT = "<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";
      function redactHeaders(headers) {
        if (!headers)
          return;
        for (const key of Object.keys(headers)) {
          if (/^authentication$/i.test(key)) {
            headers[key] = REDACT;
          }
          if (/^authorization$/i.test(key)) {
            headers[key] = REDACT;
          }
          if (/secret/i.test(key)) {
            headers[key] = REDACT;
          }
        }
      }
      __name(redactHeaders, "redactHeaders");
      function redactString(obj, key) {
        if (typeof obj === "object" && obj !== null && typeof obj[key] === "string") {
          const text = obj[key];
          if (/grant_type=/i.test(text) || /assertion=/i.test(text) || /secret/i.test(text)) {
            obj[key] = REDACT;
          }
        }
      }
      __name(redactString, "redactString");
      function redactObject(obj) {
        if (typeof obj === "object" && obj !== null) {
          if ("grant_type" in obj) {
            obj["grant_type"] = REDACT;
          }
          if ("assertion" in obj) {
            obj["assertion"] = REDACT;
          }
          if ("client_secret" in obj) {
            obj["client_secret"] = REDACT;
          }
        }
      }
      __name(redactObject, "redactObject");
      if (data.config) {
        redactHeaders(data.config.headers);
        redactString(data.config, "data");
        redactObject(data.config.data);
        redactString(data.config, "body");
        redactObject(data.config.body);
        try {
          const url2 = new url_1.URL("", data.config.url);
          if (url2.searchParams.has("token")) {
            url2.searchParams.set("token", REDACT);
          }
          if (url2.searchParams.has("client_secret")) {
            url2.searchParams.set("client_secret", REDACT);
          }
          data.config.url = url2.toString();
        } catch (_b2) {
        }
      }
      if (data.response) {
        defaultErrorRedactor({ config: data.response.config });
        redactHeaders(data.response.headers);
        redactString(data.response, "data");
        redactObject(data.response.data);
      }
      return data;
    }
    __name(defaultErrorRedactor, "defaultErrorRedactor");
  }
});

// node_modules/gaxios/build/src/retry.js
var require_retry2 = __commonJS({
  "node_modules/gaxios/build/src/retry.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRetryConfig = getRetryConfig;
    async function getRetryConfig(err) {
      let config = getConfig(err);
      if (!err || !err.config || !config && !err.config.retry) {
        return { shouldRetry: false };
      }
      config = config || {};
      config.currentRetryAttempt = config.currentRetryAttempt || 0;
      config.retry = config.retry === void 0 || config.retry === null ? 3 : config.retry;
      config.httpMethodsToRetry = config.httpMethodsToRetry || [
        "GET",
        "HEAD",
        "PUT",
        "OPTIONS",
        "DELETE"
      ];
      config.noResponseRetries = config.noResponseRetries === void 0 || config.noResponseRetries === null ? 2 : config.noResponseRetries;
      config.retryDelayMultiplier = config.retryDelayMultiplier ? config.retryDelayMultiplier : 2;
      config.timeOfFirstRequest = config.timeOfFirstRequest ? config.timeOfFirstRequest : Date.now();
      config.totalTimeout = config.totalTimeout ? config.totalTimeout : Number.MAX_SAFE_INTEGER;
      config.maxRetryDelay = config.maxRetryDelay ? config.maxRetryDelay : Number.MAX_SAFE_INTEGER;
      const retryRanges = [
        // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
        // 1xx - Retry (Informational, request still processing)
        // 2xx - Do not retry (Success)
        // 3xx - Do not retry (Redirect)
        // 4xx - Do not retry (Client errors)
        // 408 - Retry ("Request Timeout")
        // 429 - Retry ("Too Many Requests")
        // 5xx - Retry (Server errors)
        [100, 199],
        [408, 408],
        [429, 429],
        [500, 599]
      ];
      config.statusCodesToRetry = config.statusCodesToRetry || retryRanges;
      err.config.retryConfig = config;
      const shouldRetryFn = config.shouldRetry || shouldRetryRequest;
      if (!await shouldRetryFn(err)) {
        return { shouldRetry: false, config: err.config };
      }
      const delay4 = getNextRetryDelay(config);
      err.config.retryConfig.currentRetryAttempt += 1;
      const backoff = config.retryBackoff ? config.retryBackoff(err, delay4) : new Promise((resolve24) => {
        setTimeout(resolve24, delay4);
      });
      if (config.onRetryAttempt) {
        config.onRetryAttempt(err);
      }
      await backoff;
      return { shouldRetry: true, config: err.config };
    }
    __name(getRetryConfig, "getRetryConfig");
    function shouldRetryRequest(err) {
      var _a6;
      const config = getConfig(err);
      if (err.name === "AbortError" || ((_a6 = err.error) === null || _a6 === void 0 ? void 0 : _a6.name) === "AbortError") {
        return false;
      }
      if (!config || config.retry === 0) {
        return false;
      }
      if (!err.response && (config.currentRetryAttempt || 0) >= config.noResponseRetries) {
        return false;
      }
      if (!err.config.method || config.httpMethodsToRetry.indexOf(err.config.method.toUpperCase()) < 0) {
        return false;
      }
      if (err.response && err.response.status) {
        let isInRange = false;
        for (const [min, max] of config.statusCodesToRetry) {
          const status = err.response.status;
          if (status >= min && status <= max) {
            isInRange = true;
            break;
          }
        }
        if (!isInRange) {
          return false;
        }
      }
      config.currentRetryAttempt = config.currentRetryAttempt || 0;
      if (config.currentRetryAttempt >= config.retry) {
        return false;
      }
      return true;
    }
    __name(shouldRetryRequest, "shouldRetryRequest");
    function getConfig(err) {
      if (err && err.config && err.config.retryConfig) {
        return err.config.retryConfig;
      }
      return;
    }
    __name(getConfig, "getConfig");
    function getNextRetryDelay(config) {
      var _a6;
      const retryDelay = config.currentRetryAttempt ? 0 : (_a6 = config.retryDelay) !== null && _a6 !== void 0 ? _a6 : 100;
      const calculatedDelay = retryDelay + (Math.pow(config.retryDelayMultiplier, config.currentRetryAttempt) - 1) / 2 * 1e3;
      const maxAllowableDelay = config.totalTimeout - (Date.now() - config.timeOfFirstRequest);
      return Math.min(calculatedDelay, maxAllowableDelay, config.maxRetryDelay);
    }
    __name(getNextRetryDelay, "getNextRetryDelay");
  }
});

// node_modules/uuid/dist/esm-node/rng.js
import crypto2 from "crypto";
function rng() {
  if (poolPtr > rnds8Pool.length - 16) {
    crypto2.randomFillSync(rnds8Pool);
    poolPtr = 0;
  }
  return rnds8Pool.slice(poolPtr, poolPtr += 16);
}
var rnds8Pool, poolPtr;
var init_rng = __esm({
  "node_modules/uuid/dist/esm-node/rng.js"() {
    init_esbuild_shims();
    rnds8Pool = new Uint8Array(256);
    poolPtr = rnds8Pool.length;
    __name(rng, "rng");
  }
});

// node_modules/uuid/dist/esm-node/regex.js
var regex_default;
var init_regex = __esm({
  "node_modules/uuid/dist/esm-node/regex.js"() {
    init_esbuild_shims();
    regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
  }
});

// node_modules/uuid/dist/esm-node/validate.js
function validate2(uuid) {
  return typeof uuid === "string" && regex_default.test(uuid);
}
var validate_default;
var init_validate = __esm({
  "node_modules/uuid/dist/esm-node/validate.js"() {
    init_esbuild_shims();
    init_regex();
    __name(validate2, "validate");
    validate_default = validate2;
  }
});

// node_modules/uuid/dist/esm-node/stringify.js
function unsafeStringify(arr, offset = 0) {
  return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
}
function stringify(arr, offset = 0) {
  const uuid = unsafeStringify(arr, offset);
  if (!validate_default(uuid)) {
    throw TypeError("Stringified UUID is invalid");
  }
  return uuid;
}
var byteToHex, stringify_default;
var init_stringify = __esm({
  "node_modules/uuid/dist/esm-node/stringify.js"() {
    init_esbuild_shims();
    init_validate();
    byteToHex = [];
    for (let i = 0; i < 256; ++i) {
      byteToHex.push((i + 256).toString(16).slice(1));
    }
    __name(unsafeStringify, "unsafeStringify");
    __name(stringify, "stringify");
    stringify_default = stringify;
  }
});

// node_modules/uuid/dist/esm-node/v1.js
function v1(options2, buf, offset) {
  let i = buf && offset || 0;
  const b = buf || new Array(16);
  options2 = options2 || {};
  let node = options2.node || _nodeId;
  let clockseq = options2.clockseq !== void 0 ? options2.clockseq : _clockseq;
  if (node == null || clockseq == null) {
    const seedBytes = options2.random || (options2.rng || rng)();
    if (node == null) {
      node = _nodeId = [seedBytes[0] | 1, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
    }
    if (clockseq == null) {
      clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 16383;
    }
  }
  let msecs = options2.msecs !== void 0 ? options2.msecs : Date.now();
  let nsecs = options2.nsecs !== void 0 ? options2.nsecs : _lastNSecs + 1;
  const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 1e4;
  if (dt < 0 && options2.clockseq === void 0) {
    clockseq = clockseq + 1 & 16383;
  }
  if ((dt < 0 || msecs > _lastMSecs) && options2.nsecs === void 0) {
    nsecs = 0;
  }
  if (nsecs >= 1e4) {
    throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
  }
  _lastMSecs = msecs;
  _lastNSecs = nsecs;
  _clockseq = clockseq;
  msecs += 122192928e5;
  const tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296;
  b[i++] = tl >>> 24 & 255;
  b[i++] = tl >>> 16 & 255;
  b[i++] = tl >>> 8 & 255;
  b[i++] = tl & 255;
  const tmh = msecs / 4294967296 * 1e4 & 268435455;
  b[i++] = tmh >>> 8 & 255;
  b[i++] = tmh & 255;
  b[i++] = tmh >>> 24 & 15 | 16;
  b[i++] = tmh >>> 16 & 255;
  b[i++] = clockseq >>> 8 | 128;
  b[i++] = clockseq & 255;
  for (let n2 = 0; n2 < 6; ++n2) {
    b[i + n2] = node[n2];
  }
  return buf || unsafeStringify(b);
}
var _nodeId, _clockseq, _lastMSecs, _lastNSecs, v1_default;
var init_v1 = __esm({
  "node_modules/uuid/dist/esm-node/v1.js"() {
    init_esbuild_shims();
    init_rng();
    init_stringify();
    _lastMSecs = 0;
    _lastNSecs = 0;
    __name(v1, "v1");
    v1_default = v1;
  }
});

// node_modules/uuid/dist/esm-node/parse.js
function parse(uuid) {
  if (!validate_default(uuid)) {
    throw TypeError("Invalid UUID");
  }
  let v;
  const arr = new Uint8Array(16);
  arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
  arr[1] = v >>> 16 & 255;
  arr[2] = v >>> 8 & 255;
  arr[3] = v & 255;
  arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
  arr[5] = v & 255;
  arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
  arr[7] = v & 255;
  arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
  arr[9] = v & 255;
  arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 1099511627776 & 255;
  arr[11] = v / 4294967296 & 255;
  arr[12] = v >>> 24 & 255;
  arr[13] = v >>> 16 & 255;
  arr[14] = v >>> 8 & 255;
  arr[15] = v & 255;
  return arr;
}
var parse_default;
var init_parse = __esm({
  "node_modules/uuid/dist/esm-node/parse.js"() {
    init_esbuild_shims();
    init_validate();
    __name(parse, "parse");
    parse_default = parse;
  }
});

// node_modules/uuid/dist/esm-node/v35.js
function stringToBytes(str2) {
  str2 = unescape(encodeURIComponent(str2));
  const bytes = [];
  for (let i = 0; i < str2.length; ++i) {
    bytes.push(str2.charCodeAt(i));
  }
  return bytes;
}
function v35(name3, version2, hashfunc) {
  function generateUUID(value, namespace, buf, offset) {
    var _namespace;
    if (typeof value === "string") {
      value = stringToBytes(value);
    }
    if (typeof namespace === "string") {
      namespace = parse_default(namespace);
    }
    if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {
      throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");
    }
    let bytes = new Uint8Array(16 + value.length);
    bytes.set(namespace);
    bytes.set(value, namespace.length);
    bytes = hashfunc(bytes);
    bytes[6] = bytes[6] & 15 | version2;
    bytes[8] = bytes[8] & 63 | 128;
    if (buf) {
      offset = offset || 0;
      for (let i = 0; i < 16; ++i) {
        buf[offset + i] = bytes[i];
      }
      return buf;
    }
    return unsafeStringify(bytes);
  }
  __name(generateUUID, "generateUUID");
  try {
    generateUUID.name = name3;
  } catch (err) {
  }
  generateUUID.DNS = DNS;
  generateUUID.URL = URL2;
  return generateUUID;
}
var DNS, URL2;
var init_v35 = __esm({
  "node_modules/uuid/dist/esm-node/v35.js"() {
    init_esbuild_shims();
    init_stringify();
    init_parse();
    __name(stringToBytes, "stringToBytes");
    DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
    URL2 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
    __name(v35, "v35");
  }
});

// node_modules/uuid/dist/esm-node/md5.js
import crypto3 from "crypto";
function md5(bytes) {
  if (Array.isArray(bytes)) {
    bytes = Buffer.from(bytes);
  } else if (typeof bytes === "string") {
    bytes = Buffer.from(bytes, "utf8");
  }
  return crypto3.createHash("md5").update(bytes).digest();
}
var md5_default;
var init_md5 = __esm({
  "node_modules/uuid/dist/esm-node/md5.js"() {
    init_esbuild_shims();
    __name(md5, "md5");
    md5_default = md5;
  }
});

// node_modules/uuid/dist/esm-node/v3.js
var v3, v3_default;
var init_v3 = __esm({
  "node_modules/uuid/dist/esm-node/v3.js"() {
    init_esbuild_shims();
    init_v35();
    init_md5();
    v3 = v35("v3", 48, md5_default);
    v3_default = v3;
  }
});

// node_modules/uuid/dist/esm-node/native.js
import crypto4 from "crypto";
var native_default;
var init_native = __esm({
  "node_modules/uuid/dist/esm-node/native.js"() {
    init_esbuild_shims();
    native_default = {
      randomUUID: crypto4.randomUUID
    };
  }
});

// node_modules/uuid/dist/esm-node/v4.js
function v4(options2, buf, offset) {
  if (native_default.randomUUID && !buf && !options2) {
    return native_default.randomUUID();
  }
  options2 = options2 || {};
  const rnds = options2.random || (options2.rng || rng)();
  rnds[6] = rnds[6] & 15 | 64;
  rnds[8] = rnds[8] & 63 | 128;
  if (buf) {
    offset = offset || 0;
    for (let i = 0; i < 16; ++i) {
      buf[offset + i] = rnds[i];
    }
    return buf;
  }
  return unsafeStringify(rnds);
}
var v4_default;
var init_v4 = __esm({
  "node_modules/uuid/dist/esm-node/v4.js"() {
    init_esbuild_shims();
    init_native();
    init_rng();
    init_stringify();
    __name(v4, "v4");
    v4_default = v4;
  }
});

// node_modules/uuid/dist/esm-node/sha1.js
import crypto5 from "crypto";
function sha1(bytes) {
  if (Array.isArray(bytes)) {
    bytes = Buffer.from(bytes);
  } else if (typeof bytes === "string") {
    bytes = Buffer.from(bytes, "utf8");
  }
  return crypto5.createHash("sha1").update(bytes).digest();
}
var sha1_default;
var init_sha1 = __esm({
  "node_modules/uuid/dist/esm-node/sha1.js"() {
    init_esbuild_shims();
    __name(sha1, "sha1");
    sha1_default = sha1;
  }
});

// node_modules/uuid/dist/esm-node/v5.js
var v5, v5_default;
var init_v5 = __esm({
  "node_modules/uuid/dist/esm-node/v5.js"() {
    init_esbuild_shims();
    init_v35();
    init_sha1();
    v5 = v35("v5", 80, sha1_default);
    v5_default = v5;
  }
});

// node_modules/uuid/dist/esm-node/nil.js
var nil_default;
var init_nil = __esm({
  "node_modules/uuid/dist/esm-node/nil.js"() {
    init_esbuild_shims();
    nil_default = "00000000-0000-0000-0000-000000000000";
  }
});

// node_modules/uuid/dist/esm-node/version.js
function version(uuid) {
  if (!validate_default(uuid)) {
    throw TypeError("Invalid UUID");
  }
  return parseInt(uuid.slice(14, 15), 16);
}
var version_default;
var init_version = __esm({
  "node_modules/uuid/dist/esm-node/version.js"() {
    init_esbuild_shims();
    init_validate();
    __name(version, "version");
    version_default = version;
  }
});

// node_modules/uuid/dist/esm-node/index.js
var esm_node_exports = {};
__export(esm_node_exports, {
  NIL: () => nil_default,
  parse: () => parse_default,
  stringify: () => stringify_default,
  v1: () => v1_default,
  v3: () => v3_default,
  v4: () => v4_default,
  v5: () => v5_default,
  validate: () => validate_default,
  version: () => version_default
});
var init_esm_node = __esm({
  "node_modules/uuid/dist/esm-node/index.js"() {
    init_esbuild_shims();
    init_v1();
    init_v3();
    init_v4();
    init_v5();
    init_nil();
    init_version();
    init_validate();
    init_stringify();
    init_parse();
  }
});

// node_modules/gaxios/build/src/interceptor.js
var require_interceptor = __commonJS({
  "node_modules/gaxios/build/src/interceptor.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.GaxiosInterceptorManager = void 0;
    var GaxiosInterceptorManager = class extends Set {
      static {
        __name(this, "GaxiosInterceptorManager");
      }
    };
    exports2.GaxiosInterceptorManager = GaxiosInterceptorManager;
  }
});

// node_modules/ms/index.js
var require_ms = __commonJS({
  "node_modules/ms/index.js"(exports2, module2) {
    init_esbuild_shims();
    var s2 = 1e3;
    var m = s2 * 60;
    var h = m * 60;
    var d = h * 24;
    var w = d * 7;
    var y = d * 365.25;
    module2.exports = function(val, options2) {
      options2 = options2 || {};
      var type = typeof val;
      if (type === "string" && val.length > 0) {
        return parse12(val);
      } else if (type === "number" && isFinite(val)) {
        return options2.long ? fmtLong(val) : fmtShort(val);
      }
      throw new Error(
        "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
      );
    };
    function parse12(str2) {
      str2 = String(str2);
      if (str2.length > 100) {
        return;
      }
      var match2 = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
        str2
      );
      if (!match2) {
        return;
      }
      var n2 = parseFloat(match2[1]);
      var type = (match2[2] || "ms").toLowerCase();
      switch (type) {
        case "years":
        case "year":
        case "yrs":
        case "yr":
        case "y":
          return n2 * y;
        case "weeks":
        case "week":
        case "w":
          return n2 * w;
        case "days":
        case "day":
        case "d":
          return n2 * d;
        case "hours":
        case "hour":
        case "hrs":
        case "hr":
        case "h":
          return n2 * h;
        case "minutes":
        case "minute":
        case "mins":
        case "min":
        case "m":
          return n2 * m;
        case "seconds":
        case "second":
        case "secs":
        case "sec":
        case "s":
          return n2 * s2;
        case "milliseconds":
        case "millisecond":
        case "msecs":
        case "msec":
        case "ms":
          return n2;
        default:
          return void 0;
      }
    }
    __name(parse12, "parse");
    function fmtShort(ms) {
      var msAbs = Math.abs(ms);
      if (msAbs >= d) {
        return Math.round(ms / d) + "d";
      }
      if (msAbs >= h) {
        return Math.round(ms / h) + "h";
      }
      if (msAbs >= m) {
        return Math.round(ms / m) + "m";
      }
      if (msAbs >= s2) {
        return Math.round(ms / s2) + "s";
      }
      return ms + "ms";
    }
    __name(fmtShort, "fmtShort");
    function fmtLong(ms) {
      var msAbs = Math.abs(ms);
      if (msAbs >= d) {
        return plural(ms, msAbs, d, "day");
      }
      if (msAbs >= h) {
        return plural(ms, msAbs, h, "hour");
      }
      if (msAbs >= m) {
        return plural(ms, msAbs, m, "minute");
      }
      if (msAbs >= s2) {
        return plural(ms, msAbs, s2, "second");
      }
      return ms + " ms";
    }
    __name(fmtLong, "fmtLong");
    function plural(ms, msAbs, n2, name3) {
      var isPlural = msAbs >= n2 * 1.5;
      return Math.round(ms / n2) + " " + name3 + (isPlural ? "s" : "");
    }
    __name(plural, "plural");
  }
});

// node_modules/debug/src/common.js
var require_common2 = __commonJS({
  "node_modules/debug/src/common.js"(exports2, module2) {
    init_esbuild_shims();
    function setup(env7) {
      createDebug.debug = createDebug;
      createDebug.default = createDebug;
      createDebug.coerce = coerce2;
      createDebug.disable = disable;
      createDebug.enable = enable;
      createDebug.enabled = enabled;
      createDebug.humanize = require_ms();
      createDebug.destroy = destroy;
      Object.keys(env7).forEach((key) => {
        createDebug[key] = env7[key];
      });
      createDebug.names = [];
      createDebug.skips = [];
      createDebug.formatters = {};
      function selectColor(namespace) {
        let hash = 0;
        for (let i = 0; i < namespace.length; i++) {
          hash = (hash << 5) - hash + namespace.charCodeAt(i);
          hash |= 0;
        }
        return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
      }
      __name(selectColor, "selectColor");
      createDebug.selectColor = selectColor;
      function createDebug(namespace) {
        let prevTime;
        let enableOverride = null;
        let namespacesCache;
        let enabledCache;
        function debug2(...args) {
          if (!debug2.enabled) {
            return;
          }
          const self2 = debug2;
          const curr = Number(/* @__PURE__ */ new Date());
          const ms = curr - (prevTime || curr);
          self2.diff = ms;
          self2.prev = prevTime;
          self2.curr = curr;
          prevTime = curr;
          args[0] = createDebug.coerce(args[0]);
          if (typeof args[0] !== "string") {
            args.unshift("%O");
          }
          let index = 0;
          args[0] = args[0].replace(/%([a-zA-Z%])/g, (match2, format4) => {
            if (match2 === "%%") {
              return "%";
            }
            index++;
            const formatter = createDebug.formatters[format4];
            if (typeof formatter === "function") {
              const val = args[index];
              match2 = formatter.call(self2, val);
              args.splice(index, 1);
              index--;
            }
            return match2;
          });
          createDebug.formatArgs.call(self2, args);
          const logFn = self2.log || createDebug.log;
          logFn.apply(self2, args);
        }
        __name(debug2, "debug");
        debug2.namespace = namespace;
        debug2.useColors = createDebug.useColors();
        debug2.color = createDebug.selectColor(namespace);
        debug2.extend = extend;
        debug2.destroy = createDebug.destroy;
        Object.defineProperty(debug2, "enabled", {
          enumerable: true,
          configurable: false,
          get: /* @__PURE__ */ __name(() => {
            if (enableOverride !== null) {
              return enableOverride;
            }
            if (namespacesCache !== createDebug.namespaces) {
              namespacesCache = createDebug.namespaces;
              enabledCache = createDebug.enabled(namespace);
            }
            return enabledCache;
          }, "get"),
          set: /* @__PURE__ */ __name((v) => {
            enableOverride = v;
          }, "set")
        });
        if (typeof createDebug.init === "function") {
          createDebug.init(debug2);
        }
        return debug2;
      }
      __name(createDebug, "createDebug");
      function extend(namespace, delimiter2) {
        const newDebug = createDebug(this.namespace + (typeof delimiter2 === "undefined" ? ":" : delimiter2) + namespace);
        newDebug.log = this.log;
        return newDebug;
      }
      __name(extend, "extend");
      function enable(namespaces) {
        createDebug.save(namespaces);
        createDebug.namespaces = namespaces;
        createDebug.names = [];
        createDebug.skips = [];
        const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
        for (const ns of split) {
          if (ns[0] === "-") {
            createDebug.skips.push(ns.slice(1));
          } else {
            createDebug.names.push(ns);
          }
        }
      }
      __name(enable, "enable");
      function matchesTemplate(search, template) {
        let searchIndex = 0;
        let templateIndex = 0;
        let starIndex = -1;
        let matchIndex = 0;
        while (searchIndex < search.length) {
          if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
            if (template[templateIndex] === "*") {
              starIndex = templateIndex;
              matchIndex = searchIndex;
              templateIndex++;
            } else {
              searchIndex++;
              templateIndex++;
            }
          } else if (starIndex !== -1) {
            templateIndex = starIndex + 1;
            matchIndex++;
            searchIndex = matchIndex;
          } else {
            return false;
          }
        }
        while (templateIndex < template.length && template[templateIndex] === "*") {
          templateIndex++;
        }
        return templateIndex === template.length;
      }
      __name(matchesTemplate, "matchesTemplate");
      function disable() {
        const namespaces = [
          ...createDebug.names,
          ...createDebug.skips.map((namespace) => "-" + namespace)
        ].join(",");
        createDebug.enable("");
        return namespaces;
      }
      __name(disable, "disable");
      function enabled(name3) {
        for (const skip of createDebug.skips) {
          if (matchesTemplate(name3, skip)) {
            return false;
          }
        }
        for (const ns of createDebug.names) {
          if (matchesTemplate(name3, ns)) {
            return true;
          }
        }
        return false;
      }
      __name(enabled, "enabled");
      function coerce2(val) {
        if (val instanceof Error) {
          return val.stack || val.message;
        }
        return val;
      }
      __name(coerce2, "coerce");
      function destroy() {
        console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
      }
      __name(destroy, "destroy");
      createDebug.enable(createDebug.load());
      return createDebug;
    }
    __name(setup, "setup");
    module2.exports = setup;
  }
});

// node_modules/debug/src/browser.js
var require_browser = __commonJS({
  "node_modules/debug/src/browser.js"(exports2, module2) {
    init_esbuild_shims();
    exports2.formatArgs = formatArgs;
    exports2.save = save;
    exports2.load = load;
    exports2.useColors = useColors;
    exports2.storage = localstorage();
    exports2.destroy = /* @__PURE__ */ (() => {
      let warned2 = false;
      return () => {
        if (!warned2) {
          warned2 = true;
          console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
        }
      };
    })();
    exports2.colors = [
      "#0000CC",
      "#0000FF",
      "#0033CC",
      "#0033FF",
      "#0066CC",
      "#0066FF",
      "#0099CC",
      "#0099FF",
      "#00CC00",
      "#00CC33",
      "#00CC66",
      "#00CC99",
      "#00CCCC",
      "#00CCFF",
      "#3300CC",
      "#3300FF",
      "#3333CC",
      "#3333FF",
      "#3366CC",
      "#3366FF",
      "#3399CC",
      "#3399FF",
      "#33CC00",
      "#33CC33",
      "#33CC66",
      "#33CC99",
      "#33CCCC",
      "#33CCFF",
      "#6600CC",
      "#6600FF",
      "#6633CC",
      "#6633FF",
      "#66CC00",
      "#66CC33",
      "#9900CC",
      "#9900FF",
      "#9933CC",
      "#9933FF",
      "#99CC00",
      "#99CC33",
      "#CC0000",
      "#CC0033",
      "#CC0066",
      "#CC0099",
      "#CC00CC",
      "#CC00FF",
      "#CC3300",
      "#CC3333",
      "#CC3366",
      "#CC3399",
      "#CC33CC",
      "#CC33FF",
      "#CC6600",
      "#CC6633",
      "#CC9900",
      "#CC9933",
      "#CCCC00",
      "#CCCC33",
      "#FF0000",
      "#FF0033",
      "#FF0066",
      "#FF0099",
      "#FF00CC",
      "#FF00FF",
      "#FF3300",
      "#FF3333",
      "#FF3366",
      "#FF3399",
      "#FF33CC",
      "#FF33FF",
      "#FF6600",
      "#FF6633",
      "#FF9900",
      "#FF9933",
      "#FFCC00",
      "#FFCC33"
    ];
    function useColors() {
      if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
        return true;
      }
      if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
        return false;
      }
      let m;
      return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
      typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
      // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
      typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
      typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
    }
    __name(useColors, "useColors");
    function formatArgs(args) {
      args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff);
      if (!this.useColors) {
        return;
      }
      const c3 = "color: " + this.color;
      args.splice(1, 0, c3, "color: inherit");
      let index = 0;
      let lastC = 0;
      args[0].replace(/%[a-zA-Z%]/g, (match2) => {
        if (match2 === "%%") {
          return;
        }
        index++;
        if (match2 === "%c") {
          lastC = index;
        }
      });
      args.splice(lastC, 0, c3);
    }
    __name(formatArgs, "formatArgs");
    exports2.log = console.debug || console.log || (() => {
    });
    function save(namespaces) {
      try {
        if (namespaces) {
          exports2.storage.setItem("debug", namespaces);
        } else {
          exports2.storage.removeItem("debug");
        }
      } catch (error) {
      }
    }
    __name(save, "save");
    function load() {
      let r3;
      try {
        r3 = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG");
      } catch (error) {
      }
      if (!r3 && typeof process !== "undefined" && "env" in process) {
        r3 = process.env.DEBUG;
      }
      return r3;
    }
    __name(load, "load");
    function localstorage() {
      try {
        return localStorage;
      } catch (error) {
      }
    }
    __name(localstorage, "localstorage");
    module2.exports = require_common2()(exports2);
    var { formatters: formatters2 } = module2.exports;
    formatters2.j = function(v) {
      try {
        return JSON.stringify(v);
      } catch (error) {
        return "[UnexpectedJSONParseError]: " + error.message;
      }
    };
  }
});

// node_modules/supports-color/node_modules/has-flag/index.js
var require_has_flag = __commonJS({
  "node_modules/supports-color/node_modules/has-flag/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = (flag, argv) => {
      argv = argv || process.argv;
      const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
      const pos2 = argv.indexOf(prefix + flag);
      const terminatorPos = argv.indexOf("--");
      return pos2 !== -1 && (terminatorPos === -1 ? true : pos2 < terminatorPos);
    };
  }
});

// node_modules/supports-color/index.js
var require_supports_color = __commonJS({
  "node_modules/supports-color/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var os43 = __require("os");
    var hasFlag3 = require_has_flag();
    var env7 = process.env;
    var forceColor;
    if (hasFlag3("no-color") || hasFlag3("no-colors") || hasFlag3("color=false")) {
      forceColor = false;
    } else if (hasFlag3("color") || hasFlag3("colors") || hasFlag3("color=true") || hasFlag3("color=always")) {
      forceColor = true;
    }
    if ("FORCE_COLOR" in env7) {
      forceColor = env7.FORCE_COLOR.length === 0 || parseInt(env7.FORCE_COLOR, 10) !== 0;
    }
    function translateLevel3(level) {
      if (level === 0) {
        return false;
      }
      return {
        level,
        hasBasic: true,
        has256: level >= 2,
        has16m: level >= 3
      };
    }
    __name(translateLevel3, "translateLevel");
    function supportsColor3(stream2) {
      if (forceColor === false) {
        return 0;
      }
      if (hasFlag3("color=16m") || hasFlag3("color=full") || hasFlag3("color=truecolor")) {
        return 3;
      }
      if (hasFlag3("color=256")) {
        return 2;
      }
      if (stream2 && !stream2.isTTY && forceColor !== true) {
        return 0;
      }
      const min = forceColor ? 1 : 0;
      if (process.platform === "win32") {
        const osRelease = os43.release().split(".");
        if (Number(process.versions.node.split(".")[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
          return Number(osRelease[2]) >= 14931 ? 3 : 2;
        }
        return 1;
      }
      if ("CI" in env7) {
        if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some((sign) => sign in env7) || env7.CI_NAME === "codeship") {
          return 1;
        }
        return min;
      }
      if ("TEAMCITY_VERSION" in env7) {
        return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env7.TEAMCITY_VERSION) ? 1 : 0;
      }
      if (env7.COLORTERM === "truecolor") {
        return 3;
      }
      if ("TERM_PROGRAM" in env7) {
        const version2 = parseInt((env7.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
        switch (env7.TERM_PROGRAM) {
          case "iTerm.app":
            return version2 >= 3 ? 3 : 2;
          case "Apple_Terminal":
            return 2;
        }
      }
      if (/-256(color)?$/i.test(env7.TERM)) {
        return 2;
      }
      if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env7.TERM)) {
        return 1;
      }
      if ("COLORTERM" in env7) {
        return 1;
      }
      if (env7.TERM === "dumb") {
        return min;
      }
      return min;
    }
    __name(supportsColor3, "supportsColor");
    function getSupportLevel(stream2) {
      const level = supportsColor3(stream2);
      return translateLevel3(level);
    }
    __name(getSupportLevel, "getSupportLevel");
    module2.exports = {
      supportsColor: getSupportLevel,
      stdout: getSupportLevel(process.stdout),
      stderr: getSupportLevel(process.stderr)
    };
  }
});

// node_modules/debug/src/node.js
var require_node = __commonJS({
  "node_modules/debug/src/node.js"(exports2, module2) {
    init_esbuild_shims();
    var tty3 = __require("tty");
    var util4 = __require("util");
    exports2.init = init;
    exports2.log = log;
    exports2.formatArgs = formatArgs;
    exports2.save = save;
    exports2.load = load;
    exports2.useColors = useColors;
    exports2.destroy = util4.deprecate(
      () => {
      },
      "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."
    );
    exports2.colors = [6, 2, 3, 4, 5, 1];
    try {
      const supportsColor3 = require_supports_color();
      if (supportsColor3 && (supportsColor3.stderr || supportsColor3).level >= 2) {
        exports2.colors = [
          20,
          21,
          26,
          27,
          32,
          33,
          38,
          39,
          40,
          41,
          42,
          43,
          44,
          45,
          56,
          57,
          62,
          63,
          68,
          69,
          74,
          75,
          76,
          77,
          78,
          79,
          80,
          81,
          92,
          93,
          98,
          99,
          112,
          113,
          128,
          129,
          134,
          135,
          148,
          149,
          160,
          161,
          162,
          163,
          164,
          165,
          166,
          167,
          168,
          169,
          170,
          171,
          172,
          173,
          178,
          179,
          184,
          185,
          196,
          197,
          198,
          199,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          208,
          209,
          214,
          215,
          220,
          221
        ];
      }
    } catch (error) {
    }
    exports2.inspectOpts = Object.keys(process.env).filter((key) => {
      return /^debug_/i.test(key);
    }).reduce((obj, key) => {
      const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
        return k.toUpperCase();
      });
      let val = process.env[key];
      if (/^(yes|on|true|enabled)$/i.test(val)) {
        val = true;
      } else if (/^(no|off|false|disabled)$/i.test(val)) {
        val = false;
      } else if (val === "null") {
        val = null;
      } else {
        val = Number(val);
      }
      obj[prop] = val;
      return obj;
    }, {});
    function useColors() {
      return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty3.isatty(process.stderr.fd);
    }
    __name(useColors, "useColors");
    function formatArgs(args) {
      const { namespace: name3, useColors: useColors2 } = this;
      if (useColors2) {
        const c3 = this.color;
        const colorCode = "\x1B[3" + (c3 < 8 ? c3 : "8;5;" + c3);
        const prefix = `  ${colorCode};1m${name3} \x1B[0m`;
        args[0] = prefix + args[0].split("\n").join("\n" + prefix);
        args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m");
      } else {
        args[0] = getDate() + name3 + " " + args[0];
      }
    }
    __name(formatArgs, "formatArgs");
    function getDate() {
      if (exports2.inspectOpts.hideDate) {
        return "";
      }
      return (/* @__PURE__ */ new Date()).toISOString() + " ";
    }
    __name(getDate, "getDate");
    function log(...args) {
      return process.stderr.write(util4.formatWithOptions(exports2.inspectOpts, ...args) + "\n");
    }
    __name(log, "log");
    function save(namespaces) {
      if (namespaces) {
        process.env.DEBUG = namespaces;
      } else {
        delete process.env.DEBUG;
      }
    }
    __name(save, "save");
    function load() {
      return process.env.DEBUG;
    }
    __name(load, "load");
    function init(debug2) {
      debug2.inspectOpts = {};
      const keys = Object.keys(exports2.inspectOpts);
      for (let i = 0; i < keys.length; i++) {
        debug2.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]];
      }
    }
    __name(init, "init");
    module2.exports = require_common2()(exports2);
    var { formatters: formatters2 } = module2.exports;
    formatters2.o = function(v) {
      this.inspectOpts.colors = this.useColors;
      return util4.inspect(v, this.inspectOpts).split("\n").map((str2) => str2.trim()).join(" ");
    };
    formatters2.O = function(v) {
      this.inspectOpts.colors = this.useColors;
      return util4.inspect(v, this.inspectOpts);
    };
  }
});

// node_modules/debug/src/index.js
var require_src = __commonJS({
  "node_modules/debug/src/index.js"(exports2, module2) {
    init_esbuild_shims();
    if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) {
      module2.exports = require_browser();
    } else {
      module2.exports = require_node();
    }
  }
});

// node_modules/agent-base/dist/helpers.js
var require_helpers = __commonJS({
  "node_modules/agent-base/dist/helpers.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc2 = Object.getOwnPropertyDescriptor(m, k);
      if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m[k];
        }, "get") };
      }
      Object.defineProperty(o2, k2, desc2);
    } : function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o2[k2] = m[k];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v) {
      Object.defineProperty(o2, "default", { enumerable: true, value: v });
    } : function(o2, v) {
      o2["default"] = v;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod2) {
      if (mod2 && mod2.__esModule) return mod2;
      var result = {};
      if (mod2 != null) {
        for (var k in mod2) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod2, k)) __createBinding(result, mod2, k);
      }
      __setModuleDefault(result, mod2);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.req = exports2.json = exports2.toBuffer = void 0;
    var http4 = __importStar(__require("http"));
    var https4 = __importStar(__require("https"));
    async function toBuffer(stream2) {
      let length = 0;
      const chunks = [];
      for await (const chunk of stream2) {
        length += chunk.length;
        chunks.push(chunk);
      }
      return Buffer.concat(chunks, length);
    }
    __name(toBuffer, "toBuffer");
    exports2.toBuffer = toBuffer;
    async function json2(stream2) {
      const buf = await toBuffer(stream2);
      const str2 = buf.toString("utf8");
      try {
        return JSON.parse(str2);
      } catch (_err) {
        const err = _err;
        err.message += ` (input: ${str2})`;
        throw err;
      }
    }
    __name(json2, "json");
    exports2.json = json2;
    function req(url2, opts = {}) {
      const href = typeof url2 === "string" ? url2 : url2.href;
      const req2 = (href.startsWith("https:") ? https4 : http4).request(url2, opts);
      const promise = new Promise((resolve24, reject) => {
        req2.once("response", resolve24).once("error", reject).end();
      });
      req2.then = promise.then.bind(promise);
      return req2;
    }
    __name(req, "req");
    exports2.req = req;
  }
});

// node_modules/agent-base/dist/index.js
var require_dist = __commonJS({
  "node_modules/agent-base/dist/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc2 = Object.getOwnPropertyDescriptor(m, k);
      if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m[k];
        }, "get") };
      }
      Object.defineProperty(o2, k2, desc2);
    } : function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o2[k2] = m[k];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v) {
      Object.defineProperty(o2, "default", { enumerable: true, value: v });
    } : function(o2, v) {
      o2["default"] = v;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod2) {
      if (mod2 && mod2.__esModule) return mod2;
      var result = {};
      if (mod2 != null) {
        for (var k in mod2) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod2, k)) __createBinding(result, mod2, k);
      }
      __setModuleDefault(result, mod2);
      return result;
    };
    var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Agent = void 0;
    var net2 = __importStar(__require("net"));
    var http4 = __importStar(__require("http"));
    var https_1 = __require("https");
    __exportStar(require_helpers(), exports2);
    var INTERNAL = Symbol("AgentBaseInternalState");
    var Agent3 = class extends http4.Agent {
      static {
        __name(this, "Agent");
      }
      constructor(opts) {
        super(opts);
        this[INTERNAL] = {};
      }
      /**
       * Determine whether this is an `http` or `https` request.
       */
      isSecureEndpoint(options2) {
        if (options2) {
          if (typeof options2.secureEndpoint === "boolean") {
            return options2.secureEndpoint;
          }
          if (typeof options2.protocol === "string") {
            return options2.protocol === "https:";
          }
        }
        const { stack } = new Error();
        if (typeof stack !== "string")
          return false;
        return stack.split("\n").some((l2) => l2.indexOf("(https.js:") !== -1 || l2.indexOf("node:https:") !== -1);
      }
      // In order to support async signatures in `connect()` and Node's native
      // connection pooling in `http.Agent`, the array of sockets for each origin
      // has to be updated synchronously. This is so the length of the array is
      // accurate when `addRequest()` is next called. We achieve this by creating a
      // fake socket and adding it to `sockets[origin]` and incrementing
      // `totalSocketCount`.
      incrementSockets(name3) {
        if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) {
          return null;
        }
        if (!this.sockets[name3]) {
          this.sockets[name3] = [];
        }
        const fakeSocket = new net2.Socket({ writable: false });
        this.sockets[name3].push(fakeSocket);
        this.totalSocketCount++;
        return fakeSocket;
      }
      decrementSockets(name3, socket) {
        if (!this.sockets[name3] || socket === null) {
          return;
        }
        const sockets = this.sockets[name3];
        const index = sockets.indexOf(socket);
        if (index !== -1) {
          sockets.splice(index, 1);
          this.totalSocketCount--;
          if (sockets.length === 0) {
            delete this.sockets[name3];
          }
        }
      }
      // In order to properly update the socket pool, we need to call `getName()` on
      // the core `https.Agent` if it is a secureEndpoint.
      getName(options2) {
        const secureEndpoint = typeof options2.secureEndpoint === "boolean" ? options2.secureEndpoint : this.isSecureEndpoint(options2);
        if (secureEndpoint) {
          return https_1.Agent.prototype.getName.call(this, options2);
        }
        return super.getName(options2);
      }
      createSocket(req, options2, cb) {
        const connectOpts = {
          ...options2,
          secureEndpoint: this.isSecureEndpoint(options2)
        };
        const name3 = this.getName(connectOpts);
        const fakeSocket = this.incrementSockets(name3);
        Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => {
          this.decrementSockets(name3, fakeSocket);
          if (socket instanceof http4.Agent) {
            try {
              return socket.addRequest(req, connectOpts);
            } catch (err) {
              return cb(err);
            }
          }
          this[INTERNAL].currentSocket = socket;
          super.createSocket(req, options2, cb);
        }, (err) => {
          this.decrementSockets(name3, fakeSocket);
          cb(err);
        });
      }
      createConnection() {
        const socket = this[INTERNAL].currentSocket;
        this[INTERNAL].currentSocket = void 0;
        if (!socket) {
          throw new Error("No socket was returned in the `connect()` function");
        }
        return socket;
      }
      get defaultPort() {
        return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80);
      }
      set defaultPort(v) {
        if (this[INTERNAL]) {
          this[INTERNAL].defaultPort = v;
        }
      }
      get protocol() {
        return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:");
      }
      set protocol(v) {
        if (this[INTERNAL]) {
          this[INTERNAL].protocol = v;
        }
      }
    };
    exports2.Agent = Agent3;
  }
});

// node_modules/https-proxy-agent/dist/parse-proxy-response.js
var require_parse_proxy_response = __commonJS({
  "node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
      return mod2 && mod2.__esModule ? mod2 : { "default": mod2 };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.parseProxyResponse = void 0;
    var debug_1 = __importDefault(require_src());
    var debug2 = (0, debug_1.default)("https-proxy-agent:parse-proxy-response");
    function parseProxyResponse(socket) {
      return new Promise((resolve24, reject) => {
        let buffersLength = 0;
        const buffers = [];
        function read2() {
          const b = socket.read();
          if (b)
            ondata(b);
          else
            socket.once("readable", read2);
        }
        __name(read2, "read");
        function cleanup() {
          socket.removeListener("end", onend);
          socket.removeListener("error", onerror);
          socket.removeListener("readable", read2);
        }
        __name(cleanup, "cleanup");
        function onend() {
          cleanup();
          debug2("onend");
          reject(new Error("Proxy connection ended before receiving CONNECT response"));
        }
        __name(onend, "onend");
        function onerror(err) {
          cleanup();
          debug2("onerror %o", err);
          reject(err);
        }
        __name(onerror, "onerror");
        function ondata(b) {
          buffers.push(b);
          buffersLength += b.length;
          const buffered = Buffer.concat(buffers, buffersLength);
          const endOfHeaders = buffered.indexOf("\r\n\r\n");
          if (endOfHeaders === -1) {
            debug2("have not received end of HTTP headers yet...");
            read2();
            return;
          }
          const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split("\r\n");
          const firstLine = headerParts.shift();
          if (!firstLine) {
            socket.destroy();
            return reject(new Error("No header received from proxy CONNECT response"));
          }
          const firstLineParts = firstLine.split(" ");
          const statusCode = +firstLineParts[1];
          const statusText = firstLineParts.slice(2).join(" ");
          const headers = {};
          for (const header of headerParts) {
            if (!header)
              continue;
            const firstColon = header.indexOf(":");
            if (firstColon === -1) {
              socket.destroy();
              return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`));
            }
            const key = header.slice(0, firstColon).toLowerCase();
            const value = header.slice(firstColon + 1).trimStart();
            const current = headers[key];
            if (typeof current === "string") {
              headers[key] = [current, value];
            } else if (Array.isArray(current)) {
              current.push(value);
            } else {
              headers[key] = value;
            }
          }
          debug2("got proxy server response: %o %o", firstLine, headers);
          cleanup();
          resolve24({
            connect: {
              statusCode,
              statusText,
              headers
            },
            buffered
          });
        }
        __name(ondata, "ondata");
        socket.on("error", onerror);
        socket.on("end", onend);
        read2();
      });
    }
    __name(parseProxyResponse, "parseProxyResponse");
    exports2.parseProxyResponse = parseProxyResponse;
  }
});

// node_modules/https-proxy-agent/dist/index.js
var require_dist2 = __commonJS({
  "node_modules/https-proxy-agent/dist/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc2 = Object.getOwnPropertyDescriptor(m, k);
      if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m[k];
        }, "get") };
      }
      Object.defineProperty(o2, k2, desc2);
    } : function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o2[k2] = m[k];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v) {
      Object.defineProperty(o2, "default", { enumerable: true, value: v });
    } : function(o2, v) {
      o2["default"] = v;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod2) {
      if (mod2 && mod2.__esModule) return mod2;
      var result = {};
      if (mod2 != null) {
        for (var k in mod2) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod2, k)) __createBinding(result, mod2, k);
      }
      __setModuleDefault(result, mod2);
      return result;
    };
    var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
      return mod2 && mod2.__esModule ? mod2 : { "default": mod2 };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.HttpsProxyAgent = void 0;
    var net2 = __importStar(__require("net"));
    var tls = __importStar(__require("tls"));
    var assert_1 = __importDefault(__require("assert"));
    var debug_1 = __importDefault(require_src());
    var agent_base_1 = require_dist();
    var url_1 = __require("url");
    var parse_proxy_response_1 = require_parse_proxy_response();
    var debug2 = (0, debug_1.default)("https-proxy-agent");
    var setServernameFromNonIpHost = /* @__PURE__ */ __name((options2) => {
      if (options2.servername === void 0 && options2.host && !net2.isIP(options2.host)) {
        return {
          ...options2,
          servername: options2.host
        };
      }
      return options2;
    }, "setServernameFromNonIpHost");
    var HttpsProxyAgent3 = class extends agent_base_1.Agent {
      static {
        __name(this, "HttpsProxyAgent");
      }
      constructor(proxy, opts) {
        super(opts);
        this.options = { path: void 0 };
        this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy;
        this.proxyHeaders = opts?.headers ?? {};
        debug2("Creating new HttpsProxyAgent instance: %o", this.proxy.href);
        const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, "");
        const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80;
        this.connectOpts = {
          // Attempt to negotiate http/1.1 for proxy servers that support http/2
          ALPNProtocols: ["http/1.1"],
          ...opts ? omit(opts, "headers") : null,
          host,
          port
        };
      }
      /**
       * Called when the node-core HTTP client library is creating a
       * new HTTP request.
       */
      async connect(req, opts) {
        const { proxy } = this;
        if (!opts.host) {
          throw new TypeError('No "host" provided');
        }
        let socket;
        if (proxy.protocol === "https:") {
          debug2("Creating `tls.Socket`: %o", this.connectOpts);
          socket = tls.connect(setServernameFromNonIpHost(this.connectOpts));
        } else {
          debug2("Creating `net.Socket`: %o", this.connectOpts);
          socket = net2.connect(this.connectOpts);
        }
        const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders };
        const host = net2.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
        let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r
`;
        if (proxy.username || proxy.password) {
          const auth2 = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
          headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth2).toString("base64")}`;
        }
        headers.Host = `${host}:${opts.port}`;
        if (!headers["Proxy-Connection"]) {
          headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close";
        }
        for (const name3 of Object.keys(headers)) {
          payload += `${name3}: ${headers[name3]}\r
`;
        }
        const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket);
        socket.write(`${payload}\r
`);
        const { connect, buffered } = await proxyResponsePromise;
        req.emit("proxyConnect", connect);
        this.emit("proxyConnect", connect, req);
        if (connect.statusCode === 200) {
          req.once("socket", resume);
          if (opts.secureEndpoint) {
            debug2("Upgrading socket connection to TLS");
            return tls.connect({
              ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"),
              socket
            });
          }
          return socket;
        }
        socket.destroy();
        const fakeSocket = new net2.Socket({ writable: false });
        fakeSocket.readable = true;
        req.once("socket", (s2) => {
          debug2("Replaying proxy buffer for failed request");
          (0, assert_1.default)(s2.listenerCount("data") > 0);
          s2.push(buffered);
          s2.push(null);
        });
        return fakeSocket;
      }
    };
    HttpsProxyAgent3.protocols = ["http", "https"];
    exports2.HttpsProxyAgent = HttpsProxyAgent3;
    function resume(socket) {
      socket.resume();
    }
    __name(resume, "resume");
    function omit(obj, ...keys) {
      const ret = {};
      let key;
      for (key in obj) {
        if (!keys.includes(key)) {
          ret[key] = obj[key];
        }
      }
      return ret;
    }
    __name(omit, "omit");
  }
});

// node_modules/gaxios/build/src/gaxios.js
var require_gaxios = __commonJS({
  "node_modules/gaxios/build/src/gaxios.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc2 = Object.getOwnPropertyDescriptor(m, k);
      if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m[k];
        }, "get") };
      }
      Object.defineProperty(o2, k2, desc2);
    } : function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o2[k2] = m[k];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v) {
      Object.defineProperty(o2, "default", { enumerable: true, value: v });
    } : function(o2, v) {
      o2["default"] = v;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod2) {
      if (mod2 && mod2.__esModule) return mod2;
      var result = {};
      if (mod2 != null) {
        for (var k in mod2) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod2, k)) __createBinding(result, mod2, k);
      }
      __setModuleDefault(result, mod2);
      return result;
    };
    var __classPrivateFieldGet4 = exports2 && exports2.__classPrivateFieldGet || function(receiver, state, kind, f) {
      if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    };
    var __classPrivateFieldSet3 = exports2 && exports2.__classPrivateFieldSet || function(receiver, state, value, kind, f) {
      if (kind === "m") throw new TypeError("Private method is not writable");
      if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
      if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
      return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
    };
    var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
      return mod2 && mod2.__esModule ? mod2 : { "default": mod2 };
    };
    var _Gaxios_instances;
    var _a6;
    var _Gaxios_urlMayUseProxy;
    var _Gaxios_applyRequestInterceptors;
    var _Gaxios_applyResponseInterceptors;
    var _Gaxios_prepareRequest;
    var _Gaxios_proxyAgent;
    var _Gaxios_getProxyAgent;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Gaxios = void 0;
    var extend_1 = __importDefault(require_extend());
    var https_1 = __require("https");
    var node_fetch_1 = __importDefault(require_lib2());
    var querystring_1 = __importDefault(__require("querystring"));
    var is_stream_1 = __importDefault(require_is_stream());
    var url_1 = __require("url");
    var common_1 = require_common();
    var retry_1 = require_retry2();
    var stream_1 = __require("stream");
    var uuid_1 = (init_esm_node(), __toCommonJS(esm_node_exports));
    var interceptor_1 = require_interceptor();
    var fetch2 = hasFetch() ? window.fetch : node_fetch_1.default;
    function hasWindow() {
      return typeof window !== "undefined" && !!window;
    }
    __name(hasWindow, "hasWindow");
    function hasFetch() {
      return hasWindow() && !!window.fetch;
    }
    __name(hasFetch, "hasFetch");
    function hasBuffer() {
      return typeof Buffer !== "undefined";
    }
    __name(hasBuffer, "hasBuffer");
    function hasHeader(options2, header) {
      return !!getHeader(options2, header);
    }
    __name(hasHeader, "hasHeader");
    function getHeader(options2, header) {
      header = header.toLowerCase();
      for (const key of Object.keys((options2 === null || options2 === void 0 ? void 0 : options2.headers) || {})) {
        if (header === key.toLowerCase()) {
          return options2.headers[key];
        }
      }
      return void 0;
    }
    __name(getHeader, "getHeader");
    var Gaxios = class {
      static {
        __name(this, "Gaxios");
      }
      /**
       * The Gaxios class is responsible for making HTTP requests.
       * @param defaults The default set of options to be used for this instance.
       */
      constructor(defaults3) {
        _Gaxios_instances.add(this);
        this.agentCache = /* @__PURE__ */ new Map();
        this.defaults = defaults3 || {};
        this.interceptors = {
          request: new interceptor_1.GaxiosInterceptorManager(),
          response: new interceptor_1.GaxiosInterceptorManager()
        };
      }
      /**
       * Perform an HTTP request with the given options.
       * @param opts Set of HTTP options that will be used for this HTTP request.
       */
      async request(opts = {}) {
        opts = await __classPrivateFieldGet4(this, _Gaxios_instances, "m", _Gaxios_prepareRequest).call(this, opts);
        opts = await __classPrivateFieldGet4(this, _Gaxios_instances, "m", _Gaxios_applyRequestInterceptors).call(this, opts);
        return __classPrivateFieldGet4(this, _Gaxios_instances, "m", _Gaxios_applyResponseInterceptors).call(this, this._request(opts));
      }
      async _defaultAdapter(opts) {
        const fetchImpl = opts.fetchImplementation || fetch2;
        const res = await fetchImpl(opts.url, opts);
        const data = await this.getResponseData(opts, res);
        return this.translateResponse(opts, res, data);
      }
      /**
       * Internal, retryable version of the `request` method.
       * @param opts Set of HTTP options that will be used for this HTTP request.
       */
      async _request(opts = {}) {
        var _b2;
        try {
          let translatedResponse;
          if (opts.adapter) {
            translatedResponse = await opts.adapter(opts, this._defaultAdapter.bind(this));
          } else {
            translatedResponse = await this._defaultAdapter(opts);
          }
          if (!opts.validateStatus(translatedResponse.status)) {
            if (opts.responseType === "stream") {
              let response = "";
              await new Promise((resolve24) => {
                (translatedResponse === null || translatedResponse === void 0 ? void 0 : translatedResponse.data).on("data", (chunk) => {
                  response += chunk;
                });
                (translatedResponse === null || translatedResponse === void 0 ? void 0 : translatedResponse.data).on("end", resolve24);
              });
              translatedResponse.data = response;
            }
            throw new common_1.GaxiosError(`Request failed with status code ${translatedResponse.status}`, opts, translatedResponse);
          }
          return translatedResponse;
        } catch (e2) {
          const err = e2 instanceof common_1.GaxiosError ? e2 : new common_1.GaxiosError(e2.message, opts, void 0, e2);
          const { shouldRetry, config } = await (0, retry_1.getRetryConfig)(err);
          if (shouldRetry && config) {
            err.config.retryConfig.currentRetryAttempt = config.retryConfig.currentRetryAttempt;
            opts.retryConfig = (_b2 = err.config) === null || _b2 === void 0 ? void 0 : _b2.retryConfig;
            return this._request(opts);
          }
          throw err;
        }
      }
      async getResponseData(opts, res) {
        switch (opts.responseType) {
          case "stream":
            return res.body;
          case "json": {
            let data = await res.text();
            try {
              data = JSON.parse(data);
            } catch (_b2) {
            }
            return data;
          }
          case "arraybuffer":
            return res.arrayBuffer();
          case "blob":
            return res.blob();
          case "text":
            return res.text();
          default:
            return this.getResponseDataFromContentType(res);
        }
      }
      /**
       * By default, throw for any non-2xx status code
       * @param status status code from the HTTP response
       */
      validateStatus(status) {
        return status >= 200 && status < 300;
      }
      /**
       * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo)
       * @param params key value pars to encode
       */
      paramsSerializer(params) {
        return querystring_1.default.stringify(params);
      }
      translateResponse(opts, res, data) {
        const headers = {};
        res.headers.forEach((value, key) => {
          headers[key] = value;
        });
        return {
          config: opts,
          data,
          headers,
          status: res.status,
          statusText: res.statusText,
          // XMLHttpRequestLike
          request: {
            responseURL: res.url
          }
        };
      }
      /**
       * Attempts to parse a response by looking at the Content-Type header.
       * @param {FetchResponse} response the HTTP response.
       * @returns {Promise<any>} a promise that resolves to the response data.
       */
      async getResponseDataFromContentType(response) {
        let contentType = response.headers.get("Content-Type");
        if (contentType === null) {
          return response.text();
        }
        contentType = contentType.toLowerCase();
        if (contentType.includes("application/json")) {
          let data = await response.text();
          try {
            data = JSON.parse(data);
          } catch (_b2) {
          }
          return data;
        } else if (contentType.match(/^text\//)) {
          return response.text();
        } else {
          return response.blob();
        }
      }
      /**
       * Creates an async generator that yields the pieces of a multipart/related request body.
       * This implementation follows the spec: https://www.ietf.org/rfc/rfc2387.txt. However, recursive
       * multipart/related requests are not currently supported.
       *
       * @param {GaxioMultipartOptions[]} multipartOptions the pieces to turn into a multipart/related body.
       * @param {string} boundary the boundary string to be placed between each part.
       */
      async *getMultipartRequest(multipartOptions, boundary) {
        const finale = `--${boundary}--`;
        for (const currentPart of multipartOptions) {
          const partContentType = currentPart.headers["Content-Type"] || "application/octet-stream";
          const preamble = `--${boundary}\r
Content-Type: ${partContentType}\r
\r
`;
          yield preamble;
          if (typeof currentPart.content === "string") {
            yield currentPart.content;
          } else {
            yield* currentPart.content;
          }
          yield "\r\n";
        }
        yield finale;
      }
    };
    exports2.Gaxios = Gaxios;
    _a6 = Gaxios, _Gaxios_instances = /* @__PURE__ */ new WeakSet(), _Gaxios_urlMayUseProxy = /* @__PURE__ */ __name(function _Gaxios_urlMayUseProxy2(url2, noProxy = []) {
      var _b2, _c2;
      const candidate = new url_1.URL(url2);
      const noProxyList = [...noProxy];
      const noProxyEnvList = ((_c2 = (_b2 = process.env.NO_PROXY) !== null && _b2 !== void 0 ? _b2 : process.env.no_proxy) === null || _c2 === void 0 ? void 0 : _c2.split(",")) || [];
      for (const rule of noProxyEnvList) {
        noProxyList.push(rule.trim());
      }
      for (const rule of noProxyList) {
        if (rule instanceof RegExp) {
          if (rule.test(candidate.toString())) {
            return false;
          }
        } else if (rule instanceof url_1.URL) {
          if (rule.origin === candidate.origin) {
            return false;
          }
        } else if (rule.startsWith("*.") || rule.startsWith(".")) {
          const cleanedRule = rule.replace(/^\*\./, ".");
          if (candidate.hostname.endsWith(cleanedRule)) {
            return false;
          }
        } else if (rule === candidate.origin || rule === candidate.hostname || rule === candidate.href) {
          return false;
        }
      }
      return true;
    }, "_Gaxios_urlMayUseProxy"), _Gaxios_applyRequestInterceptors = /**
     * Applies the request interceptors. The request interceptors are applied after the
     * call to prepareRequest is completed.
     *
     * @param {GaxiosOptions} options The current set of options.
     *
     * @returns {Promise<GaxiosOptions>} Promise that resolves to the set of options or response after interceptors are applied.
     */
    /* @__PURE__ */ __name(async function _Gaxios_applyRequestInterceptors2(options2) {
      let promiseChain = Promise.resolve(options2);
      for (const interceptor of this.interceptors.request.values()) {
        if (interceptor) {
          promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected);
        }
      }
      return promiseChain;
    }, "_Gaxios_applyRequestInterceptors"), _Gaxios_applyResponseInterceptors = /**
     * Applies the response interceptors. The response interceptors are applied after the
     * call to request is made.
     *
     * @param {GaxiosOptions} options The current set of options.
     *
     * @returns {Promise<GaxiosOptions>} Promise that resolves to the set of options or response after interceptors are applied.
     */
    /* @__PURE__ */ __name(async function _Gaxios_applyResponseInterceptors2(response) {
      let promiseChain = Promise.resolve(response);
      for (const interceptor of this.interceptors.response.values()) {
        if (interceptor) {
          promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected);
        }
      }
      return promiseChain;
    }, "_Gaxios_applyResponseInterceptors"), _Gaxios_prepareRequest = /**
     * Validates the options, merges them with defaults, and prepare request.
     *
     * @param options The original options passed from the client.
     * @returns Prepared options, ready to make a request
     */
    /* @__PURE__ */ __name(async function _Gaxios_prepareRequest2(options2) {
      var _b2, _c2, _d, _e;
      const opts = (0, extend_1.default)(true, {}, this.defaults, options2);
      if (!opts.url) {
        throw new Error("URL is required.");
      }
      const baseUrl = opts.baseUrl || opts.baseURL;
      if (baseUrl) {
        opts.url = baseUrl.toString() + opts.url;
      }
      opts.paramsSerializer = opts.paramsSerializer || this.paramsSerializer;
      if (opts.params && Object.keys(opts.params).length > 0) {
        let additionalQueryParams = opts.paramsSerializer(opts.params);
        if (additionalQueryParams.startsWith("?")) {
          additionalQueryParams = additionalQueryParams.slice(1);
        }
        const prefix = opts.url.toString().includes("?") ? "&" : "?";
        opts.url = opts.url + prefix + additionalQueryParams;
      }
      if (typeof options2.maxContentLength === "number") {
        opts.size = options2.maxContentLength;
      }
      if (typeof options2.maxRedirects === "number") {
        opts.follow = options2.maxRedirects;
      }
      opts.headers = opts.headers || {};
      if (opts.multipart === void 0 && opts.data) {
        const isFormData = typeof FormData === "undefined" ? false : (opts === null || opts === void 0 ? void 0 : opts.data) instanceof FormData;
        if (is_stream_1.default.readable(opts.data)) {
          opts.body = opts.data;
        } else if (hasBuffer() && Buffer.isBuffer(opts.data)) {
          opts.body = opts.data;
          if (!hasHeader(opts, "Content-Type")) {
            opts.headers["Content-Type"] = "application/json";
          }
        } else if (typeof opts.data === "object") {
          if (!isFormData) {
            if (getHeader(opts, "content-type") === "application/x-www-form-urlencoded") {
              opts.body = opts.paramsSerializer(opts.data);
            } else {
              if (!hasHeader(opts, "Content-Type")) {
                opts.headers["Content-Type"] = "application/json";
              }
              opts.body = JSON.stringify(opts.data);
            }
          }
        } else {
          opts.body = opts.data;
        }
      } else if (opts.multipart && opts.multipart.length > 0) {
        const boundary = (0, uuid_1.v4)();
        opts.headers["Content-Type"] = `multipart/related; boundary=${boundary}`;
        const bodyStream = new stream_1.PassThrough();
        opts.body = bodyStream;
        (0, stream_1.pipeline)(this.getMultipartRequest(opts.multipart, boundary), bodyStream, () => {
        });
      }
      opts.validateStatus = opts.validateStatus || this.validateStatus;
      opts.responseType = opts.responseType || "unknown";
      if (!opts.headers["Accept"] && opts.responseType === "json") {
        opts.headers["Accept"] = "application/json";
      }
      opts.method = opts.method || "GET";
      const proxy = opts.proxy || ((_b2 = process === null || process === void 0 ? void 0 : process.env) === null || _b2 === void 0 ? void 0 : _b2.HTTPS_PROXY) || ((_c2 = process === null || process === void 0 ? void 0 : process.env) === null || _c2 === void 0 ? void 0 : _c2.https_proxy) || ((_d = process === null || process === void 0 ? void 0 : process.env) === null || _d === void 0 ? void 0 : _d.HTTP_PROXY) || ((_e = process === null || process === void 0 ? void 0 : process.env) === null || _e === void 0 ? void 0 : _e.http_proxy);
      const urlMayUseProxy = __classPrivateFieldGet4(this, _Gaxios_instances, "m", _Gaxios_urlMayUseProxy).call(this, opts.url, opts.noProxy);
      if (opts.agent) {
      } else if (proxy && urlMayUseProxy) {
        const HttpsProxyAgent3 = await __classPrivateFieldGet4(_a6, _a6, "m", _Gaxios_getProxyAgent).call(_a6);
        if (this.agentCache.has(proxy)) {
          opts.agent = this.agentCache.get(proxy);
        } else {
          opts.agent = new HttpsProxyAgent3(proxy, {
            cert: opts.cert,
            key: opts.key
          });
          this.agentCache.set(proxy, opts.agent);
        }
      } else if (opts.cert && opts.key) {
        if (this.agentCache.has(opts.key)) {
          opts.agent = this.agentCache.get(opts.key);
        } else {
          opts.agent = new https_1.Agent({
            cert: opts.cert,
            key: opts.key
          });
          this.agentCache.set(opts.key, opts.agent);
        }
      }
      if (typeof opts.errorRedactor !== "function" && opts.errorRedactor !== false) {
        opts.errorRedactor = common_1.defaultErrorRedactor;
      }
      return opts;
    }, "_Gaxios_prepareRequest"), _Gaxios_getProxyAgent = /* @__PURE__ */ __name(async function _Gaxios_getProxyAgent2() {
      __classPrivateFieldSet3(this, _a6, __classPrivateFieldGet4(this, _a6, "f", _Gaxios_proxyAgent) || (await Promise.resolve().then(() => __importStar(require_dist2()))).HttpsProxyAgent, "f", _Gaxios_proxyAgent);
      return __classPrivateFieldGet4(this, _a6, "f", _Gaxios_proxyAgent);
    }, "_Gaxios_getProxyAgent");
    _Gaxios_proxyAgent = { value: void 0 };
  }
});

// node_modules/gaxios/build/src/index.js
var require_src2 = __commonJS({
  "node_modules/gaxios/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc2 = Object.getOwnPropertyDescriptor(m, k);
      if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m[k];
        }, "get") };
      }
      Object.defineProperty(o2, k2, desc2);
    } : function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o2[k2] = m[k];
    });
    var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.instance = exports2.Gaxios = exports2.GaxiosError = void 0;
    exports2.request = request4;
    var gaxios_1 = require_gaxios();
    Object.defineProperty(exports2, "Gaxios", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return gaxios_1.Gaxios;
    }, "get") });
    var common_1 = require_common();
    Object.defineProperty(exports2, "GaxiosError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return common_1.GaxiosError;
    }, "get") });
    __exportStar(require_interceptor(), exports2);
    exports2.instance = new gaxios_1.Gaxios();
    async function request4(opts) {
      return exports2.instance.request(opts);
    }
    __name(request4, "request");
  }
});

// node_modules/bignumber.js/bignumber.js
var require_bignumber = __commonJS({
  "node_modules/bignumber.js/bignumber.js"(exports2, module2) {
    init_esbuild_shims();
    (function(globalObject) {
      "use strict";
      var BigNumber, isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, mathceil = Math.ceil, mathfloor = Math.floor, bignumberError = "[BigNumber Error] ", tooManyDigits = bignumberError + "Number primitive has more than 15 significant digits: ", BASE = 1e14, LOG_BASE = 14, MAX_SAFE_INTEGER = 9007199254740991, POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], SQRT_BASE = 1e7, MAX2 = 1e9;
      function clone(configObject) {
        var div, convertBase, parseNumeric, P = BigNumber2.prototype = { constructor: BigNumber2, toString: null, valueOf: null }, ONE = new BigNumber2(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = {
          prefix: "",
          groupSize: 3,
          secondaryGroupSize: 0,
          groupSeparator: ",",
          decimalSeparator: ".",
          fractionGroupSize: 0,
          fractionGroupSeparator: "\xA0",
          // non-breaking space
          suffix: ""
        }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true;
        function BigNumber2(v, b) {
          var alphabet, c3, caseChanged, e2, i, isNum, len, str2, x = this;
          if (!(x instanceof BigNumber2)) return new BigNumber2(v, b);
          if (b == null) {
            if (v && v._isBigNumber === true) {
              x.s = v.s;
              if (!v.c || v.e > MAX_EXP) {
                x.c = x.e = null;
              } else if (v.e < MIN_EXP) {
                x.c = [x.e = 0];
              } else {
                x.e = v.e;
                x.c = v.c.slice();
              }
              return;
            }
            if ((isNum = typeof v == "number") && v * 0 == 0) {
              x.s = 1 / v < 0 ? (v = -v, -1) : 1;
              if (v === ~~v) {
                for (e2 = 0, i = v; i >= 10; i /= 10, e2++) ;
                if (e2 > MAX_EXP) {
                  x.c = x.e = null;
                } else {
                  x.e = e2;
                  x.c = [v];
                }
                return;
              }
              str2 = String(v);
            } else {
              if (!isNumeric.test(str2 = String(v))) return parseNumeric(x, str2, isNum);
              x.s = str2.charCodeAt(0) == 45 ? (str2 = str2.slice(1), -1) : 1;
            }
            if ((e2 = str2.indexOf(".")) > -1) str2 = str2.replace(".", "");
            if ((i = str2.search(/e/i)) > 0) {
              if (e2 < 0) e2 = i;
              e2 += +str2.slice(i + 1);
              str2 = str2.substring(0, i);
            } else if (e2 < 0) {
              e2 = str2.length;
            }
          } else {
            intCheck(b, 2, ALPHABET.length, "Base");
            if (b == 10 && alphabetHasNormalDecimalDigits) {
              x = new BigNumber2(v);
              return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);
            }
            str2 = String(v);
            if (isNum = typeof v == "number") {
              if (v * 0 != 0) return parseNumeric(x, str2, isNum, b);
              x.s = 1 / v < 0 ? (str2 = str2.slice(1), -1) : 1;
              if (BigNumber2.DEBUG && str2.replace(/^0\.0*|\./, "").length > 15) {
                throw Error(tooManyDigits + v);
              }
            } else {
              x.s = str2.charCodeAt(0) === 45 ? (str2 = str2.slice(1), -1) : 1;
            }
            alphabet = ALPHABET.slice(0, b);
            e2 = i = 0;
            for (len = str2.length; i < len; i++) {
              if (alphabet.indexOf(c3 = str2.charAt(i)) < 0) {
                if (c3 == ".") {
                  if (i > e2) {
                    e2 = len;
                    continue;
                  }
                } else if (!caseChanged) {
                  if (str2 == str2.toUpperCase() && (str2 = str2.toLowerCase()) || str2 == str2.toLowerCase() && (str2 = str2.toUpperCase())) {
                    caseChanged = true;
                    i = -1;
                    e2 = 0;
                    continue;
                  }
                }
                return parseNumeric(x, String(v), isNum, b);
              }
            }
            isNum = false;
            str2 = convertBase(str2, b, 10, x.s);
            if ((e2 = str2.indexOf(".")) > -1) str2 = str2.replace(".", "");
            else e2 = str2.length;
          }
          for (i = 0; str2.charCodeAt(i) === 48; i++) ;
          for (len = str2.length; str2.charCodeAt(--len) === 48; ) ;
          if (str2 = str2.slice(i, ++len)) {
            len -= i;
            if (isNum && BigNumber2.DEBUG && len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {
              throw Error(tooManyDigits + x.s * v);
            }
            if ((e2 = e2 - i - 1) > MAX_EXP) {
              x.c = x.e = null;
            } else if (e2 < MIN_EXP) {
              x.c = [x.e = 0];
            } else {
              x.e = e2;
              x.c = [];
              i = (e2 + 1) % LOG_BASE;
              if (e2 < 0) i += LOG_BASE;
              if (i < len) {
                if (i) x.c.push(+str2.slice(0, i));
                for (len -= LOG_BASE; i < len; ) {
                  x.c.push(+str2.slice(i, i += LOG_BASE));
                }
                i = LOG_BASE - (str2 = str2.slice(i)).length;
              } else {
                i -= len;
              }
              for (; i--; str2 += "0") ;
              x.c.push(+str2);
            }
          } else {
            x.c = [x.e = 0];
          }
        }
        __name(BigNumber2, "BigNumber");
        BigNumber2.clone = clone;
        BigNumber2.ROUND_UP = 0;
        BigNumber2.ROUND_DOWN = 1;
        BigNumber2.ROUND_CEIL = 2;
        BigNumber2.ROUND_FLOOR = 3;
        BigNumber2.ROUND_HALF_UP = 4;
        BigNumber2.ROUND_HALF_DOWN = 5;
        BigNumber2.ROUND_HALF_EVEN = 6;
        BigNumber2.ROUND_HALF_CEIL = 7;
        BigNumber2.ROUND_HALF_FLOOR = 8;
        BigNumber2.EUCLID = 9;
        BigNumber2.config = BigNumber2.set = function(obj) {
          var p, v;
          if (obj != null) {
            if (typeof obj == "object") {
              if (obj.hasOwnProperty(p = "DECIMAL_PLACES")) {
                v = obj[p];
                intCheck(v, 0, MAX2, p);
                DECIMAL_PLACES = v;
              }
              if (obj.hasOwnProperty(p = "ROUNDING_MODE")) {
                v = obj[p];
                intCheck(v, 0, 8, p);
                ROUNDING_MODE = v;
              }
              if (obj.hasOwnProperty(p = "EXPONENTIAL_AT")) {
                v = obj[p];
                if (v && v.pop) {
                  intCheck(v[0], -MAX2, 0, p);
                  intCheck(v[1], 0, MAX2, p);
                  TO_EXP_NEG = v[0];
                  TO_EXP_POS = v[1];
                } else {
                  intCheck(v, -MAX2, MAX2, p);
                  TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);
                }
              }
              if (obj.hasOwnProperty(p = "RANGE")) {
                v = obj[p];
                if (v && v.pop) {
                  intCheck(v[0], -MAX2, -1, p);
                  intCheck(v[1], 1, MAX2, p);
                  MIN_EXP = v[0];
                  MAX_EXP = v[1];
                } else {
                  intCheck(v, -MAX2, MAX2, p);
                  if (v) {
                    MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);
                  } else {
                    throw Error(bignumberError + p + " cannot be zero: " + v);
                  }
                }
              }
              if (obj.hasOwnProperty(p = "CRYPTO")) {
                v = obj[p];
                if (v === !!v) {
                  if (v) {
                    if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) {
                      CRYPTO = v;
                    } else {
                      CRYPTO = !v;
                      throw Error(bignumberError + "crypto unavailable");
                    }
                  } else {
                    CRYPTO = v;
                  }
                } else {
                  throw Error(bignumberError + p + " not true or false: " + v);
                }
              }
              if (obj.hasOwnProperty(p = "MODULO_MODE")) {
                v = obj[p];
                intCheck(v, 0, 9, p);
                MODULO_MODE = v;
              }
              if (obj.hasOwnProperty(p = "POW_PRECISION")) {
                v = obj[p];
                intCheck(v, 0, MAX2, p);
                POW_PRECISION = v;
              }
              if (obj.hasOwnProperty(p = "FORMAT")) {
                v = obj[p];
                if (typeof v == "object") FORMAT = v;
                else throw Error(bignumberError + p + " not an object: " + v);
              }
              if (obj.hasOwnProperty(p = "ALPHABET")) {
                v = obj[p];
                if (typeof v == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) {
                  alphabetHasNormalDecimalDigits = v.slice(0, 10) == "0123456789";
                  ALPHABET = v;
                } else {
                  throw Error(bignumberError + p + " invalid: " + v);
                }
              }
            } else {
              throw Error(bignumberError + "Object expected: " + obj);
            }
          }
          return {
            DECIMAL_PLACES,
            ROUNDING_MODE,
            EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],
            RANGE: [MIN_EXP, MAX_EXP],
            CRYPTO,
            MODULO_MODE,
            POW_PRECISION,
            FORMAT,
            ALPHABET
          };
        };
        BigNumber2.isBigNumber = function(v) {
          if (!v || v._isBigNumber !== true) return false;
          if (!BigNumber2.DEBUG) return true;
          var i, n2, c3 = v.c, e2 = v.e, s2 = v.s;
          out: if ({}.toString.call(c3) == "[object Array]") {
            if ((s2 === 1 || s2 === -1) && e2 >= -MAX2 && e2 <= MAX2 && e2 === mathfloor(e2)) {
              if (c3[0] === 0) {
                if (e2 === 0 && c3.length === 1) return true;
                break out;
              }
              i = (e2 + 1) % LOG_BASE;
              if (i < 1) i += LOG_BASE;
              if (String(c3[0]).length == i) {
                for (i = 0; i < c3.length; i++) {
                  n2 = c3[i];
                  if (n2 < 0 || n2 >= BASE || n2 !== mathfloor(n2)) break out;
                }
                if (n2 !== 0) return true;
              }
            }
          } else if (c3 === null && e2 === null && (s2 === null || s2 === 1 || s2 === -1)) {
            return true;
          }
          throw Error(bignumberError + "Invalid BigNumber: " + v);
        };
        BigNumber2.maximum = BigNumber2.max = function() {
          return maxOrMin(arguments, -1);
        };
        BigNumber2.minimum = BigNumber2.min = function() {
          return maxOrMin(arguments, 1);
        };
        BigNumber2.random = function() {
          var pow2_53 = 9007199254740992;
          var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() {
            return mathfloor(Math.random() * pow2_53);
          } : function() {
            return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0);
          };
          return function(dp) {
            var a, b, e2, k, v, i = 0, c3 = [], rand = new BigNumber2(ONE);
            if (dp == null) dp = DECIMAL_PLACES;
            else intCheck(dp, 0, MAX2);
            k = mathceil(dp / LOG_BASE);
            if (CRYPTO) {
              if (crypto.getRandomValues) {
                a = crypto.getRandomValues(new Uint32Array(k *= 2));
                for (; i < k; ) {
                  v = a[i] * 131072 + (a[i + 1] >>> 11);
                  if (v >= 9e15) {
                    b = crypto.getRandomValues(new Uint32Array(2));
                    a[i] = b[0];
                    a[i + 1] = b[1];
                  } else {
                    c3.push(v % 1e14);
                    i += 2;
                  }
                }
                i = k / 2;
              } else if (crypto.randomBytes) {
                a = crypto.randomBytes(k *= 7);
                for (; i < k; ) {
                  v = (a[i] & 31) * 281474976710656 + a[i + 1] * 1099511627776 + a[i + 2] * 4294967296 + a[i + 3] * 16777216 + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];
                  if (v >= 9e15) {
                    crypto.randomBytes(7).copy(a, i);
                  } else {
                    c3.push(v % 1e14);
                    i += 7;
                  }
                }
                i = k / 7;
              } else {
                CRYPTO = false;
                throw Error(bignumberError + "crypto unavailable");
              }
            }
            if (!CRYPTO) {
              for (; i < k; ) {
                v = random53bitInt();
                if (v < 9e15) c3[i++] = v % 1e14;
              }
            }
            k = c3[--i];
            dp %= LOG_BASE;
            if (k && dp) {
              v = POWS_TEN[LOG_BASE - dp];
              c3[i] = mathfloor(k / v) * v;
            }
            for (; c3[i] === 0; c3.pop(), i--) ;
            if (i < 0) {
              c3 = [e2 = 0];
            } else {
              for (e2 = -1; c3[0] === 0; c3.splice(0, 1), e2 -= LOG_BASE) ;
              for (i = 1, v = c3[0]; v >= 10; v /= 10, i++) ;
              if (i < LOG_BASE) e2 -= LOG_BASE - i;
            }
            rand.e = e2;
            rand.c = c3;
            return rand;
          };
        }();
        BigNumber2.sum = function() {
          var i = 1, args = arguments, sum = new BigNumber2(args[0]);
          for (; i < args.length; ) sum = sum.plus(args[i++]);
          return sum;
        };
        convertBase = /* @__PURE__ */ function() {
          var decimal = "0123456789";
          function toBaseOut(str2, baseIn, baseOut, alphabet) {
            var j, arr = [0], arrL, i = 0, len = str2.length;
            for (; i < len; ) {
              for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) ;
              arr[0] += alphabet.indexOf(str2.charAt(i++));
              for (j = 0; j < arr.length; j++) {
                if (arr[j] > baseOut - 1) {
                  if (arr[j + 1] == null) arr[j + 1] = 0;
                  arr[j + 1] += arr[j] / baseOut | 0;
                  arr[j] %= baseOut;
                }
              }
            }
            return arr.reverse();
          }
          __name(toBaseOut, "toBaseOut");
          return function(str2, baseIn, baseOut, sign, callerIsToString) {
            var alphabet, d, e2, k, r3, x, xc, y, i = str2.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE;
            if (i >= 0) {
              k = POW_PRECISION;
              POW_PRECISION = 0;
              str2 = str2.replace(".", "");
              y = new BigNumber2(baseIn);
              x = y.pow(str2.length - i);
              POW_PRECISION = k;
              y.c = toBaseOut(
                toFixedPoint(coeffToString(x.c), x.e, "0"),
                10,
                baseOut,
                decimal
              );
              y.e = y.c.length;
            }
            xc = toBaseOut(str2, baseIn, baseOut, callerIsToString ? (alphabet = ALPHABET, decimal) : (alphabet = decimal, ALPHABET));
            e2 = k = xc.length;
            for (; xc[--k] == 0; xc.pop()) ;
            if (!xc[0]) return alphabet.charAt(0);
            if (i < 0) {
              --e2;
            } else {
              x.c = xc;
              x.e = e2;
              x.s = sign;
              x = div(x, y, dp, rm, baseOut);
              xc = x.c;
              r3 = x.r;
              e2 = x.e;
            }
            d = e2 + dp + 1;
            i = xc[d];
            k = baseOut / 2;
            r3 = r3 || d < 0 || xc[d + 1] != null;
            r3 = rm < 4 ? (i != null || r3) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : i > k || i == k && (rm == 4 || r3 || rm == 6 && xc[d - 1] & 1 || rm == (x.s < 0 ? 8 : 7));
            if (d < 1 || !xc[0]) {
              str2 = r3 ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0);
            } else {
              xc.length = d;
              if (r3) {
                for (--baseOut; ++xc[--d] > baseOut; ) {
                  xc[d] = 0;
                  if (!d) {
                    ++e2;
                    xc = [1].concat(xc);
                  }
                }
              }
              for (k = xc.length; !xc[--k]; ) ;
              for (i = 0, str2 = ""; i <= k; str2 += alphabet.charAt(xc[i++])) ;
              str2 = toFixedPoint(str2, e2, alphabet.charAt(0));
            }
            return str2;
          };
        }();
        div = /* @__PURE__ */ function() {
          function multiply(x, k, base) {
            var m, temp, xlo, xhi, carry = 0, i = x.length, klo = k % SQRT_BASE, khi = k / SQRT_BASE | 0;
            for (x = x.slice(); i--; ) {
              xlo = x[i] % SQRT_BASE;
              xhi = x[i] / SQRT_BASE | 0;
              m = khi * xlo + xhi * klo;
              temp = klo * xlo + m % SQRT_BASE * SQRT_BASE + carry;
              carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;
              x[i] = temp % base;
            }
            if (carry) x = [carry].concat(x);
            return x;
          }
          __name(multiply, "multiply");
          function compare2(a, b, aL, bL) {
            var i, cmp;
            if (aL != bL) {
              cmp = aL > bL ? 1 : -1;
            } else {
              for (i = cmp = 0; i < aL; i++) {
                if (a[i] != b[i]) {
                  cmp = a[i] > b[i] ? 1 : -1;
                  break;
                }
              }
            }
            return cmp;
          }
          __name(compare2, "compare");
          function subtract(a, b, aL, base) {
            var i = 0;
            for (; aL--; ) {
              a[aL] -= i;
              i = a[aL] < b[aL] ? 1 : 0;
              a[aL] = i * base + a[aL] - b[aL];
            }
            for (; !a[0] && a.length > 1; a.splice(0, 1)) ;
          }
          __name(subtract, "subtract");
          return function(x, y, dp, rm, base) {
            var cmp, e2, i, more, n2, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s2 = x.s == y.s ? 1 : -1, xc = x.c, yc = y.c;
            if (!xc || !xc[0] || !yc || !yc[0]) {
              return new BigNumber2(
                // Return NaN if either NaN, or both Infinity or 0.
                !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : (
                  // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
                  xc && xc[0] == 0 || !yc ? s2 * 0 : s2 / 0
                )
              );
            }
            q = new BigNumber2(s2);
            qc = q.c = [];
            e2 = x.e - y.e;
            s2 = dp + e2 + 1;
            if (!base) {
              base = BASE;
              e2 = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE);
              s2 = s2 / LOG_BASE | 0;
            }
            for (i = 0; yc[i] == (xc[i] || 0); i++) ;
            if (yc[i] > (xc[i] || 0)) e2--;
            if (s2 < 0) {
              qc.push(1);
              more = true;
            } else {
              xL = xc.length;
              yL = yc.length;
              i = 0;
              s2 += 2;
              n2 = mathfloor(base / (yc[0] + 1));
              if (n2 > 1) {
                yc = multiply(yc, n2, base);
                xc = multiply(xc, n2, base);
                yL = yc.length;
                xL = xc.length;
              }
              xi = yL;
              rem = xc.slice(0, yL);
              remL = rem.length;
              for (; remL < yL; rem[remL++] = 0) ;
              yz = yc.slice();
              yz = [0].concat(yz);
              yc0 = yc[0];
              if (yc[1] >= base / 2) yc0++;
              do {
                n2 = 0;
                cmp = compare2(yc, rem, yL, remL);
                if (cmp < 0) {
                  rem0 = rem[0];
                  if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);
                  n2 = mathfloor(rem0 / yc0);
                  if (n2 > 1) {
                    if (n2 >= base) n2 = base - 1;
                    prod = multiply(yc, n2, base);
                    prodL = prod.length;
                    remL = rem.length;
                    while (compare2(prod, rem, prodL, remL) == 1) {
                      n2--;
                      subtract(prod, yL < prodL ? yz : yc, prodL, base);
                      prodL = prod.length;
                      cmp = 1;
                    }
                  } else {
                    if (n2 == 0) {
                      cmp = n2 = 1;
                    }
                    prod = yc.slice();
                    prodL = prod.length;
                  }
                  if (prodL < remL) prod = [0].concat(prod);
                  subtract(rem, prod, remL, base);
                  remL = rem.length;
                  if (cmp == -1) {
                    while (compare2(yc, rem, yL, remL) < 1) {
                      n2++;
                      subtract(rem, yL < remL ? yz : yc, remL, base);
                      remL = rem.length;
                    }
                  }
                } else if (cmp === 0) {
                  n2++;
                  rem = [0];
                }
                qc[i++] = n2;
                if (rem[0]) {
                  rem[remL++] = xc[xi] || 0;
                } else {
                  rem = [xc[xi]];
                  remL = 1;
                }
              } while ((xi++ < xL || rem[0] != null) && s2--);
              more = rem[0] != null;
              if (!qc[0]) qc.splice(0, 1);
            }
            if (base == BASE) {
              for (i = 1, s2 = qc[0]; s2 >= 10; s2 /= 10, i++) ;
              round(q, dp + (q.e = i + e2 * LOG_BASE - 1) + 1, rm, more);
            } else {
              q.e = e2;
              q.r = +more;
            }
            return q;
          };
        }();
        function format4(n2, i, rm, id) {
          var c0, e2, ne, len, str2;
          if (rm == null) rm = ROUNDING_MODE;
          else intCheck(rm, 0, 8);
          if (!n2.c) return n2.toString();
          c0 = n2.c[0];
          ne = n2.e;
          if (i == null) {
            str2 = coeffToString(n2.c);
            str2 = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential(str2, ne) : toFixedPoint(str2, ne, "0");
          } else {
            n2 = round(new BigNumber2(n2), i, rm);
            e2 = n2.e;
            str2 = coeffToString(n2.c);
            len = str2.length;
            if (id == 1 || id == 2 && (i <= e2 || e2 <= TO_EXP_NEG)) {
              for (; len < i; str2 += "0", len++) ;
              str2 = toExponential(str2, e2);
            } else {
              i -= ne;
              str2 = toFixedPoint(str2, e2, "0");
              if (e2 + 1 > len) {
                if (--i > 0) for (str2 += "."; i--; str2 += "0") ;
              } else {
                i += e2 - len;
                if (i > 0) {
                  if (e2 + 1 == len) str2 += ".";
                  for (; i--; str2 += "0") ;
                }
              }
            }
          }
          return n2.s < 0 && c0 ? "-" + str2 : str2;
        }
        __name(format4, "format");
        function maxOrMin(args, n2) {
          var k, y, i = 1, x = new BigNumber2(args[0]);
          for (; i < args.length; i++) {
            y = new BigNumber2(args[i]);
            if (!y.s || (k = compare(x, y)) === n2 || k === 0 && x.s === n2) {
              x = y;
            }
          }
          return x;
        }
        __name(maxOrMin, "maxOrMin");
        function normalise(n2, c3, e2) {
          var i = 1, j = c3.length;
          for (; !c3[--j]; c3.pop()) ;
          for (j = c3[0]; j >= 10; j /= 10, i++) ;
          if ((e2 = i + e2 * LOG_BASE - 1) > MAX_EXP) {
            n2.c = n2.e = null;
          } else if (e2 < MIN_EXP) {
            n2.c = [n2.e = 0];
          } else {
            n2.e = e2;
            n2.c = c3;
          }
          return n2;
        }
        __name(normalise, "normalise");
        parseNumeric = /* @__PURE__ */ function() {
          var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
          return function(x, str2, isNum, b) {
            var base, s2 = isNum ? str2 : str2.replace(whitespaceOrPlus, "");
            if (isInfinityOrNaN.test(s2)) {
              x.s = isNaN(s2) ? null : s2 < 0 ? -1 : 1;
            } else {
              if (!isNum) {
                s2 = s2.replace(basePrefix, function(m, p1, p2) {
                  base = (p2 = p2.toLowerCase()) == "x" ? 16 : p2 == "b" ? 2 : 8;
                  return !b || b == base ? p1 : m;
                });
                if (b) {
                  base = b;
                  s2 = s2.replace(dotAfter, "$1").replace(dotBefore, "0.$1");
                }
                if (str2 != s2) return new BigNumber2(s2, base);
              }
              if (BigNumber2.DEBUG) {
                throw Error(bignumberError + "Not a" + (b ? " base " + b : "") + " number: " + str2);
              }
              x.s = null;
            }
            x.c = x.e = null;
          };
        }();
        function round(x, sd, rm, r3) {
          var d, i, j, k, n2, ni, rd, xc = x.c, pows10 = POWS_TEN;
          if (xc) {
            out: {
              for (d = 1, k = xc[0]; k >= 10; k /= 10, d++) ;
              i = sd - d;
              if (i < 0) {
                i += LOG_BASE;
                j = sd;
                n2 = xc[ni = 0];
                rd = mathfloor(n2 / pows10[d - j - 1] % 10);
              } else {
                ni = mathceil((i + 1) / LOG_BASE);
                if (ni >= xc.length) {
                  if (r3) {
                    for (; xc.length <= ni; xc.push(0)) ;
                    n2 = rd = 0;
                    d = 1;
                    i %= LOG_BASE;
                    j = i - LOG_BASE + 1;
                  } else {
                    break out;
                  }
                } else {
                  n2 = k = xc[ni];
                  for (d = 1; k >= 10; k /= 10, d++) ;
                  i %= LOG_BASE;
                  j = i - LOG_BASE + d;
                  rd = j < 0 ? 0 : mathfloor(n2 / pows10[d - j - 1] % 10);
                }
              }
              r3 = r3 || sd < 0 || // Are there any non-zero digits after the rounding digit?
              // The expression  n % pows10[d - j - 1]  returns all digits of n to the right
              // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
              xc[ni + 1] != null || (j < 0 ? n2 : n2 % pows10[d - j - 1]);
              r3 = rm < 4 ? (rd || r3) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r3 || rm == 6 && // Check whether the digit to the left of the rounding digit is odd.
              (i > 0 ? j > 0 ? n2 / pows10[d - j] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x.s < 0 ? 8 : 7));
              if (sd < 1 || !xc[0]) {
                xc.length = 0;
                if (r3) {
                  sd -= x.e + 1;
                  xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];
                  x.e = -sd || 0;
                } else {
                  xc[0] = x.e = 0;
                }
                return x;
              }
              if (i == 0) {
                xc.length = ni;
                k = 1;
                ni--;
              } else {
                xc.length = ni + 1;
                k = pows10[LOG_BASE - i];
                xc[ni] = j > 0 ? mathfloor(n2 / pows10[d - j] % pows10[j]) * k : 0;
              }
              if (r3) {
                for (; ; ) {
                  if (ni == 0) {
                    for (i = 1, j = xc[0]; j >= 10; j /= 10, i++) ;
                    j = xc[0] += k;
                    for (k = 1; j >= 10; j /= 10, k++) ;
                    if (i != k) {
                      x.e++;
                      if (xc[0] == BASE) xc[0] = 1;
                    }
                    break;
                  } else {
                    xc[ni] += k;
                    if (xc[ni] != BASE) break;
                    xc[ni--] = 0;
                    k = 1;
                  }
                }
              }
              for (i = xc.length; xc[--i] === 0; xc.pop()) ;
            }
            if (x.e > MAX_EXP) {
              x.c = x.e = null;
            } else if (x.e < MIN_EXP) {
              x.c = [x.e = 0];
            }
          }
          return x;
        }
        __name(round, "round");
        function valueOf(n2) {
          var str2, e2 = n2.e;
          if (e2 === null) return n2.toString();
          str2 = coeffToString(n2.c);
          str2 = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential(str2, e2) : toFixedPoint(str2, e2, "0");
          return n2.s < 0 ? "-" + str2 : str2;
        }
        __name(valueOf, "valueOf");
        P.absoluteValue = P.abs = function() {
          var x = new BigNumber2(this);
          if (x.s < 0) x.s = 1;
          return x;
        };
        P.comparedTo = function(y, b) {
          return compare(this, new BigNumber2(y, b));
        };
        P.decimalPlaces = P.dp = function(dp, rm) {
          var c3, n2, v, x = this;
          if (dp != null) {
            intCheck(dp, 0, MAX2);
            if (rm == null) rm = ROUNDING_MODE;
            else intCheck(rm, 0, 8);
            return round(new BigNumber2(x), dp + x.e + 1, rm);
          }
          if (!(c3 = x.c)) return null;
          n2 = ((v = c3.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;
          if (v = c3[v]) for (; v % 10 == 0; v /= 10, n2--) ;
          if (n2 < 0) n2 = 0;
          return n2;
        };
        P.dividedBy = P.div = function(y, b) {
          return div(this, new BigNumber2(y, b), DECIMAL_PLACES, ROUNDING_MODE);
        };
        P.dividedToIntegerBy = P.idiv = function(y, b) {
          return div(this, new BigNumber2(y, b), 0, 1);
        };
        P.exponentiatedBy = P.pow = function(n2, m) {
          var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, x = this;
          n2 = new BigNumber2(n2);
          if (n2.c && !n2.isInteger()) {
            throw Error(bignumberError + "Exponent not an integer: " + valueOf(n2));
          }
          if (m != null) m = new BigNumber2(m);
          nIsBig = n2.e > 14;
          if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n2.c || !n2.c[0]) {
            y = new BigNumber2(Math.pow(+valueOf(x), nIsBig ? n2.s * (2 - isOdd(n2)) : +valueOf(n2)));
            return m ? y.mod(m) : y;
          }
          nIsNeg = n2.s < 0;
          if (m) {
            if (m.c ? !m.c[0] : !m.s) return new BigNumber2(NaN);
            isModExp = !nIsNeg && x.isInteger() && m.isInteger();
            if (isModExp) x = x.mod(m);
          } else if (n2.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) {
            k = x.s < 0 && isOdd(n2) ? -0 : 0;
            if (x.e > -1) k = 1 / k;
            return new BigNumber2(nIsNeg ? 1 / k : k);
          } else if (POW_PRECISION) {
            k = mathceil(POW_PRECISION / LOG_BASE + 2);
          }
          if (nIsBig) {
            half = new BigNumber2(0.5);
            if (nIsNeg) n2.s = 1;
            nIsOdd = isOdd(n2);
          } else {
            i = Math.abs(+valueOf(n2));
            nIsOdd = i % 2;
          }
          y = new BigNumber2(ONE);
          for (; ; ) {
            if (nIsOdd) {
              y = y.times(x);
              if (!y.c) break;
              if (k) {
                if (y.c.length > k) y.c.length = k;
              } else if (isModExp) {
                y = y.mod(m);
              }
            }
            if (i) {
              i = mathfloor(i / 2);
              if (i === 0) break;
              nIsOdd = i % 2;
            } else {
              n2 = n2.times(half);
              round(n2, n2.e + 1, 1);
              if (n2.e > 14) {
                nIsOdd = isOdd(n2);
              } else {
                i = +valueOf(n2);
                if (i === 0) break;
                nIsOdd = i % 2;
              }
            }
            x = x.times(x);
            if (k) {
              if (x.c && x.c.length > k) x.c.length = k;
            } else if (isModExp) {
              x = x.mod(m);
            }
          }
          if (isModExp) return y;
          if (nIsNeg) y = ONE.div(y);
          return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y;
        };
        P.integerValue = function(rm) {
          var n2 = new BigNumber2(this);
          if (rm == null) rm = ROUNDING_MODE;
          else intCheck(rm, 0, 8);
          return round(n2, n2.e + 1, rm);
        };
        P.isEqualTo = P.eq = function(y, b) {
          return compare(this, new BigNumber2(y, b)) === 0;
        };
        P.isFinite = function() {
          return !!this.c;
        };
        P.isGreaterThan = P.gt = function(y, b) {
          return compare(this, new BigNumber2(y, b)) > 0;
        };
        P.isGreaterThanOrEqualTo = P.gte = function(y, b) {
          return (b = compare(this, new BigNumber2(y, b))) === 1 || b === 0;
        };
        P.isInteger = function() {
          return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;
        };
        P.isLessThan = P.lt = function(y, b) {
          return compare(this, new BigNumber2(y, b)) < 0;
        };
        P.isLessThanOrEqualTo = P.lte = function(y, b) {
          return (b = compare(this, new BigNumber2(y, b))) === -1 || b === 0;
        };
        P.isNaN = function() {
          return !this.s;
        };
        P.isNegative = function() {
          return this.s < 0;
        };
        P.isPositive = function() {
          return this.s > 0;
        };
        P.isZero = function() {
          return !!this.c && this.c[0] == 0;
        };
        P.minus = function(y, b) {
          var i, j, t2, xLTy, x = this, a = x.s;
          y = new BigNumber2(y, b);
          b = y.s;
          if (!a || !b) return new BigNumber2(NaN);
          if (a != b) {
            y.s = -b;
            return x.plus(y);
          }
          var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c;
          if (!xe || !ye) {
            if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber2(yc ? x : NaN);
            if (!xc[0] || !yc[0]) {
              return yc[0] ? (y.s = -b, y) : new BigNumber2(xc[0] ? x : (
                // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
                ROUNDING_MODE == 3 ? -0 : 0
              ));
            }
          }
          xe = bitFloor(xe);
          ye = bitFloor(ye);
          xc = xc.slice();
          if (a = xe - ye) {
            if (xLTy = a < 0) {
              a = -a;
              t2 = xc;
            } else {
              ye = xe;
              t2 = yc;
            }
            t2.reverse();
            for (b = a; b--; t2.push(0)) ;
            t2.reverse();
          } else {
            j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b;
            for (a = b = 0; b < j; b++) {
              if (xc[b] != yc[b]) {
                xLTy = xc[b] < yc[b];
                break;
              }
            }
          }
          if (xLTy) {
            t2 = xc;
            xc = yc;
            yc = t2;
            y.s = -y.s;
          }
          b = (j = yc.length) - (i = xc.length);
          if (b > 0) for (; b--; xc[i++] = 0) ;
          b = BASE - 1;
          for (; j > a; ) {
            if (xc[--j] < yc[j]) {
              for (i = j; i && !xc[--i]; xc[i] = b) ;
              --xc[i];
              xc[j] += BASE;
            }
            xc[j] -= yc[j];
          }
          for (; xc[0] == 0; xc.splice(0, 1), --ye) ;
          if (!xc[0]) {
            y.s = ROUNDING_MODE == 3 ? -1 : 1;
            y.c = [y.e = 0];
            return y;
          }
          return normalise(y, xc, ye);
        };
        P.modulo = P.mod = function(y, b) {
          var q, s2, x = this;
          y = new BigNumber2(y, b);
          if (!x.c || !y.s || y.c && !y.c[0]) {
            return new BigNumber2(NaN);
          } else if (!y.c || x.c && !x.c[0]) {
            return new BigNumber2(x);
          }
          if (MODULO_MODE == 9) {
            s2 = y.s;
            y.s = 1;
            q = div(x, y, 0, 3);
            y.s = s2;
            q.s *= s2;
          } else {
            q = div(x, y, 0, MODULO_MODE);
          }
          y = x.minus(q.times(y));
          if (!y.c[0] && MODULO_MODE == 1) y.s = x.s;
          return y;
        };
        P.multipliedBy = P.times = function(y, b) {
          var c3, e2, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x = this, xc = x.c, yc = (y = new BigNumber2(y, b)).c;
          if (!xc || !yc || !xc[0] || !yc[0]) {
            if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {
              y.c = y.e = y.s = null;
            } else {
              y.s *= x.s;
              if (!xc || !yc) {
                y.c = y.e = null;
              } else {
                y.c = [0];
                y.e = 0;
              }
            }
            return y;
          }
          e2 = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE);
          y.s *= x.s;
          xcL = xc.length;
          ycL = yc.length;
          if (xcL < ycL) {
            zc = xc;
            xc = yc;
            yc = zc;
            i = xcL;
            xcL = ycL;
            ycL = i;
          }
          for (i = xcL + ycL, zc = []; i--; zc.push(0)) ;
          base = BASE;
          sqrtBase = SQRT_BASE;
          for (i = ycL; --i >= 0; ) {
            c3 = 0;
            ylo = yc[i] % sqrtBase;
            yhi = yc[i] / sqrtBase | 0;
            for (k = xcL, j = i + k; j > i; ) {
              xlo = xc[--k] % sqrtBase;
              xhi = xc[k] / sqrtBase | 0;
              m = yhi * xlo + xhi * ylo;
              xlo = ylo * xlo + m % sqrtBase * sqrtBase + zc[j] + c3;
              c3 = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi;
              zc[j--] = xlo % base;
            }
            zc[j] = c3;
          }
          if (c3) {
            ++e2;
          } else {
            zc.splice(0, 1);
          }
          return normalise(y, zc, e2);
        };
        P.negated = function() {
          var x = new BigNumber2(this);
          x.s = -x.s || null;
          return x;
        };
        P.plus = function(y, b) {
          var t2, x = this, a = x.s;
          y = new BigNumber2(y, b);
          b = y.s;
          if (!a || !b) return new BigNumber2(NaN);
          if (a != b) {
            y.s = -b;
            return x.minus(y);
          }
          var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c;
          if (!xe || !ye) {
            if (!xc || !yc) return new BigNumber2(a / 0);
            if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber2(xc[0] ? x : a * 0);
          }
          xe = bitFloor(xe);
          ye = bitFloor(ye);
          xc = xc.slice();
          if (a = xe - ye) {
            if (a > 0) {
              ye = xe;
              t2 = yc;
            } else {
              a = -a;
              t2 = xc;
            }
            t2.reverse();
            for (; a--; t2.push(0)) ;
            t2.reverse();
          }
          a = xc.length;
          b = yc.length;
          if (a - b < 0) {
            t2 = yc;
            yc = xc;
            xc = t2;
            b = a;
          }
          for (a = 0; b; ) {
            a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0;
            xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;
          }
          if (a) {
            xc = [a].concat(xc);
            ++ye;
          }
          return normalise(y, xc, ye);
        };
        P.precision = P.sd = function(sd, rm) {
          var c3, n2, v, x = this;
          if (sd != null && sd !== !!sd) {
            intCheck(sd, 1, MAX2);
            if (rm == null) rm = ROUNDING_MODE;
            else intCheck(rm, 0, 8);
            return round(new BigNumber2(x), sd, rm);
          }
          if (!(c3 = x.c)) return null;
          v = c3.length - 1;
          n2 = v * LOG_BASE + 1;
          if (v = c3[v]) {
            for (; v % 10 == 0; v /= 10, n2--) ;
            for (v = c3[0]; v >= 10; v /= 10, n2++) ;
          }
          if (sd && x.e + 1 > n2) n2 = x.e + 1;
          return n2;
        };
        P.shiftedBy = function(k) {
          intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);
          return this.times("1e" + k);
        };
        P.squareRoot = P.sqrt = function() {
          var m, n2, r3, rep, t2, x = this, c3 = x.c, s2 = x.s, e2 = x.e, dp = DECIMAL_PLACES + 4, half = new BigNumber2("0.5");
          if (s2 !== 1 || !c3 || !c3[0]) {
            return new BigNumber2(!s2 || s2 < 0 && (!c3 || c3[0]) ? NaN : c3 ? x : 1 / 0);
          }
          s2 = Math.sqrt(+valueOf(x));
          if (s2 == 0 || s2 == 1 / 0) {
            n2 = coeffToString(c3);
            if ((n2.length + e2) % 2 == 0) n2 += "0";
            s2 = Math.sqrt(+n2);
            e2 = bitFloor((e2 + 1) / 2) - (e2 < 0 || e2 % 2);
            if (s2 == 1 / 0) {
              n2 = "5e" + e2;
            } else {
              n2 = s2.toExponential();
              n2 = n2.slice(0, n2.indexOf("e") + 1) + e2;
            }
            r3 = new BigNumber2(n2);
          } else {
            r3 = new BigNumber2(s2 + "");
          }
          if (r3.c[0]) {
            e2 = r3.e;
            s2 = e2 + dp;
            if (s2 < 3) s2 = 0;
            for (; ; ) {
              t2 = r3;
              r3 = half.times(t2.plus(div(x, t2, dp, 1)));
              if (coeffToString(t2.c).slice(0, s2) === (n2 = coeffToString(r3.c)).slice(0, s2)) {
                if (r3.e < e2) --s2;
                n2 = n2.slice(s2 - 3, s2 + 1);
                if (n2 == "9999" || !rep && n2 == "4999") {
                  if (!rep) {
                    round(t2, t2.e + DECIMAL_PLACES + 2, 0);
                    if (t2.times(t2).eq(x)) {
                      r3 = t2;
                      break;
                    }
                  }
                  dp += 4;
                  s2 += 4;
                  rep = 1;
                } else {
                  if (!+n2 || !+n2.slice(1) && n2.charAt(0) == "5") {
                    round(r3, r3.e + DECIMAL_PLACES + 2, 1);
                    m = !r3.times(r3).eq(x);
                  }
                  break;
                }
              }
            }
          }
          return round(r3, r3.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);
        };
        P.toExponential = function(dp, rm) {
          if (dp != null) {
            intCheck(dp, 0, MAX2);
            dp++;
          }
          return format4(this, dp, rm, 1);
        };
        P.toFixed = function(dp, rm) {
          if (dp != null) {
            intCheck(dp, 0, MAX2);
            dp = dp + this.e + 1;
          }
          return format4(this, dp, rm);
        };
        P.toFormat = function(dp, rm, format5) {
          var str2, x = this;
          if (format5 == null) {
            if (dp != null && rm && typeof rm == "object") {
              format5 = rm;
              rm = null;
            } else if (dp && typeof dp == "object") {
              format5 = dp;
              dp = rm = null;
            } else {
              format5 = FORMAT;
            }
          } else if (typeof format5 != "object") {
            throw Error(bignumberError + "Argument not an object: " + format5);
          }
          str2 = x.toFixed(dp, rm);
          if (x.c) {
            var i, arr = str2.split("."), g1 = +format5.groupSize, g2 = +format5.secondaryGroupSize, groupSeparator = format5.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length;
            if (g2) {
              i = g1;
              g1 = g2;
              g2 = i;
              len -= i;
            }
            if (g1 > 0 && len > 0) {
              i = len % g1 || g1;
              intPart = intDigits.substr(0, i);
              for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1);
              if (g2 > 0) intPart += groupSeparator + intDigits.slice(i);
              if (isNeg) intPart = "-" + intPart;
            }
            str2 = fractionPart ? intPart + (format5.decimalSeparator || "") + ((g2 = +format5.fractionGroupSize) ? fractionPart.replace(
              new RegExp("\\d{" + g2 + "}\\B", "g"),
              "$&" + (format5.fractionGroupSeparator || "")
            ) : fractionPart) : intPart;
          }
          return (format5.prefix || "") + str2 + (format5.suffix || "");
        };
        P.toFraction = function(md) {
          var d, d0, d1, d2, e2, exp, n2, n0, n1, q, r3, s2, x = this, xc = x.c;
          if (md != null) {
            n2 = new BigNumber2(md);
            if (!n2.isInteger() && (n2.c || n2.s !== 1) || n2.lt(ONE)) {
              throw Error(bignumberError + "Argument " + (n2.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n2));
            }
          }
          if (!xc) return new BigNumber2(x);
          d = new BigNumber2(ONE);
          n1 = d0 = new BigNumber2(ONE);
          d1 = n0 = new BigNumber2(ONE);
          s2 = coeffToString(xc);
          e2 = d.e = s2.length - x.e - 1;
          d.c[0] = POWS_TEN[(exp = e2 % LOG_BASE) < 0 ? LOG_BASE + exp : exp];
          md = !md || n2.comparedTo(d) > 0 ? e2 > 0 ? d : n1 : n2;
          exp = MAX_EXP;
          MAX_EXP = 1 / 0;
          n2 = new BigNumber2(s2);
          n0.c[0] = 0;
          for (; ; ) {
            q = div(n2, d, 0, 1);
            d2 = d0.plus(q.times(d1));
            if (d2.comparedTo(md) == 1) break;
            d0 = d1;
            d1 = d2;
            n1 = n0.plus(q.times(d2 = n1));
            n0 = d2;
            d = n2.minus(q.times(d2 = d));
            n2 = d2;
          }
          d2 = div(md.minus(d0), d1, 0, 1);
          n0 = n0.plus(d2.times(n1));
          d0 = d0.plus(d2.times(d1));
          n0.s = n1.s = x.s;
          e2 = e2 * 2;
          r3 = div(n1, d1, e2, ROUNDING_MODE).minus(x).abs().comparedTo(
            div(n0, d0, e2, ROUNDING_MODE).minus(x).abs()
          ) < 1 ? [n1, d1] : [n0, d0];
          MAX_EXP = exp;
          return r3;
        };
        P.toNumber = function() {
          return +valueOf(this);
        };
        P.toPrecision = function(sd, rm) {
          if (sd != null) intCheck(sd, 1, MAX2);
          return format4(this, sd, rm, 2);
        };
        P.toString = function(b) {
          var str2, n2 = this, s2 = n2.s, e2 = n2.e;
          if (e2 === null) {
            if (s2) {
              str2 = "Infinity";
              if (s2 < 0) str2 = "-" + str2;
            } else {
              str2 = "NaN";
            }
          } else {
            if (b == null) {
              str2 = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential(coeffToString(n2.c), e2) : toFixedPoint(coeffToString(n2.c), e2, "0");
            } else if (b === 10 && alphabetHasNormalDecimalDigits) {
              n2 = round(new BigNumber2(n2), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE);
              str2 = toFixedPoint(coeffToString(n2.c), n2.e, "0");
            } else {
              intCheck(b, 2, ALPHABET.length, "Base");
              str2 = convertBase(toFixedPoint(coeffToString(n2.c), e2, "0"), 10, b, s2, true);
            }
            if (s2 < 0 && n2.c[0]) str2 = "-" + str2;
          }
          return str2;
        };
        P.valueOf = P.toJSON = function() {
          return valueOf(this);
        };
        P._isBigNumber = true;
        if (configObject != null) BigNumber2.set(configObject);
        return BigNumber2;
      }
      __name(clone, "clone");
      function bitFloor(n2) {
        var i = n2 | 0;
        return n2 > 0 || n2 === i ? i : i - 1;
      }
      __name(bitFloor, "bitFloor");
      function coeffToString(a) {
        var s2, z, i = 1, j = a.length, r3 = a[0] + "";
        for (; i < j; ) {
          s2 = a[i++] + "";
          z = LOG_BASE - s2.length;
          for (; z--; s2 = "0" + s2) ;
          r3 += s2;
        }
        for (j = r3.length; r3.charCodeAt(--j) === 48; ) ;
        return r3.slice(0, j + 1 || 1);
      }
      __name(coeffToString, "coeffToString");
      function compare(x, y) {
        var a, b, xc = x.c, yc = y.c, i = x.s, j = y.s, k = x.e, l2 = y.e;
        if (!i || !j) return null;
        a = xc && !xc[0];
        b = yc && !yc[0];
        if (a || b) return a ? b ? 0 : -j : i;
        if (i != j) return i;
        a = i < 0;
        b = k == l2;
        if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1;
        if (!b) return k > l2 ^ a ? 1 : -1;
        j = (k = xc.length) < (l2 = yc.length) ? k : l2;
        for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1;
        return k == l2 ? 0 : k > l2 ^ a ? 1 : -1;
      }
      __name(compare, "compare");
      function intCheck(n2, min, max, name3) {
        if (n2 < min || n2 > max || n2 !== mathfloor(n2)) {
          throw Error(bignumberError + (name3 || "Argument") + (typeof n2 == "number" ? n2 < min || n2 > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n2));
        }
      }
      __name(intCheck, "intCheck");
      function isOdd(n2) {
        var k = n2.c.length - 1;
        return bitFloor(n2.e / LOG_BASE) == k && n2.c[k] % 2 != 0;
      }
      __name(isOdd, "isOdd");
      function toExponential(str2, e2) {
        return (str2.length > 1 ? str2.charAt(0) + "." + str2.slice(1) : str2) + (e2 < 0 ? "e" : "e+") + e2;
      }
      __name(toExponential, "toExponential");
      function toFixedPoint(str2, e2, z) {
        var len, zs;
        if (e2 < 0) {
          for (zs = z + "."; ++e2; zs += z) ;
          str2 = zs + str2;
        } else {
          len = str2.length;
          if (++e2 > len) {
            for (zs = z, e2 -= len; --e2; zs += z) ;
            str2 += zs;
          } else if (e2 < len) {
            str2 = str2.slice(0, e2) + "." + str2.slice(e2);
          }
        }
        return str2;
      }
      __name(toFixedPoint, "toFixedPoint");
      BigNumber = clone();
      BigNumber["default"] = BigNumber.BigNumber = BigNumber;
      if (typeof define == "function" && define.amd) {
        define(function() {
          return BigNumber;
        });
      } else if (typeof module2 != "undefined" && module2.exports) {
        module2.exports = BigNumber;
      } else {
        if (!globalObject) {
          globalObject = typeof self != "undefined" && self ? self : window;
        }
        globalObject.BigNumber = BigNumber;
      }
    })(exports2);
  }
});

// node_modules/json-bigint/lib/stringify.js
var require_stringify = __commonJS({
  "node_modules/json-bigint/lib/stringify.js"(exports2, module2) {
    init_esbuild_shims();
    var BigNumber = require_bignumber();
    var JSON2 = module2.exports;
    (function() {
      "use strict";
      function f(n2) {
        return n2 < 10 ? "0" + n2 : n2;
      }
      __name(f, "f");
      var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = {
        // table of character substitutions
        "\b": "\\b",
        "	": "\\t",
        "\n": "\\n",
        "\f": "\\f",
        "\r": "\\r",
        '"': '\\"',
        "\\": "\\\\"
      }, rep;
      function quote3(string) {
        escapable.lastIndex = 0;
        return escapable.test(string) ? '"' + string.replace(escapable, function(a) {
          var c3 = meta[a];
          return typeof c3 === "string" ? c3 : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
        }) + '"' : '"' + string + '"';
      }
      __name(quote3, "quote");
      function str2(key, holder) {
        var i, k, v, length, mind = gap, partial, value = holder[key], isBigNumber = value != null && (value instanceof BigNumber || BigNumber.isBigNumber(value));
        if (value && typeof value === "object" && typeof value.toJSON === "function") {
          value = value.toJSON(key);
        }
        if (typeof rep === "function") {
          value = rep.call(holder, key, value);
        }
        switch (typeof value) {
          case "string":
            if (isBigNumber) {
              return value;
            } else {
              return quote3(value);
            }
          case "number":
            return isFinite(value) ? String(value) : "null";
          case "boolean":
          case "null":
          case "bigint":
            return String(value);
          // If the type is 'object', we might be dealing with an object or an array or
          // null.
          case "object":
            if (!value) {
              return "null";
            }
            gap += indent;
            partial = [];
            if (Object.prototype.toString.apply(value) === "[object Array]") {
              length = value.length;
              for (i = 0; i < length; i += 1) {
                partial[i] = str2(i, value) || "null";
              }
              v = partial.length === 0 ? "[]" : gap ? "[\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "]" : "[" + partial.join(",") + "]";
              gap = mind;
              return v;
            }
            if (rep && typeof rep === "object") {
              length = rep.length;
              for (i = 0; i < length; i += 1) {
                if (typeof rep[i] === "string") {
                  k = rep[i];
                  v = str2(k, value);
                  if (v) {
                    partial.push(quote3(k) + (gap ? ": " : ":") + v);
                  }
                }
              }
            } else {
              Object.keys(value).forEach(function(k2) {
                var v2 = str2(k2, value);
                if (v2) {
                  partial.push(quote3(k2) + (gap ? ": " : ":") + v2);
                }
              });
            }
            v = partial.length === 0 ? "{}" : gap ? "{\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "}" : "{" + partial.join(",") + "}";
            gap = mind;
            return v;
        }
      }
      __name(str2, "str");
      if (typeof JSON2.stringify !== "function") {
        JSON2.stringify = function(value, replacer, space) {
          var i;
          gap = "";
          indent = "";
          if (typeof space === "number") {
            for (i = 0; i < space; i += 1) {
              indent += " ";
            }
          } else if (typeof space === "string") {
            indent = space;
          }
          rep = replacer;
          if (replacer && typeof replacer !== "function" && (typeof replacer !== "object" || typeof replacer.length !== "number")) {
            throw new Error("JSON.stringify");
          }
          return str2("", { "": value });
        };
      }
    })();
  }
});

// node_modules/json-bigint/lib/parse.js
var require_parse2 = __commonJS({
  "node_modules/json-bigint/lib/parse.js"(exports2, module2) {
    init_esbuild_shims();
    var BigNumber = null;
    var suspectProtoRx = /(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/;
    var suspectConstructorRx = /(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/;
    var json_parse = /* @__PURE__ */ __name(function(options2) {
      "use strict";
      var _options = {
        strict: false,
        // not being strict means do not generate syntax errors for "duplicate key"
        storeAsString: false,
        // toggles whether the values should be stored as BigNumber (default) or a string
        alwaysParseAsBig: false,
        // toggles whether all numbers should be Big
        useNativeBigInt: false,
        // toggles whether to use native BigInt instead of bignumber.js
        protoAction: "error",
        constructorAction: "error"
      };
      if (options2 !== void 0 && options2 !== null) {
        if (options2.strict === true) {
          _options.strict = true;
        }
        if (options2.storeAsString === true) {
          _options.storeAsString = true;
        }
        _options.alwaysParseAsBig = options2.alwaysParseAsBig === true ? options2.alwaysParseAsBig : false;
        _options.useNativeBigInt = options2.useNativeBigInt === true ? options2.useNativeBigInt : false;
        if (typeof options2.constructorAction !== "undefined") {
          if (options2.constructorAction === "error" || options2.constructorAction === "ignore" || options2.constructorAction === "preserve") {
            _options.constructorAction = options2.constructorAction;
          } else {
            throw new Error(
              `Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${options2.constructorAction}`
            );
          }
        }
        if (typeof options2.protoAction !== "undefined") {
          if (options2.protoAction === "error" || options2.protoAction === "ignore" || options2.protoAction === "preserve") {
            _options.protoAction = options2.protoAction;
          } else {
            throw new Error(
              `Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${options2.protoAction}`
            );
          }
        }
      }
      var at, ch, escapee = {
        '"': '"',
        "\\": "\\",
        "/": "/",
        b: "\b",
        f: "\f",
        n: "\n",
        r: "\r",
        t: "	"
      }, text, error = /* @__PURE__ */ __name(function(m) {
        throw {
          name: "SyntaxError",
          message: m,
          at,
          text
        };
      }, "error"), next = /* @__PURE__ */ __name(function(c3) {
        if (c3 && c3 !== ch) {
          error("Expected '" + c3 + "' instead of '" + ch + "'");
        }
        ch = text.charAt(at);
        at += 1;
        return ch;
      }, "next"), number = /* @__PURE__ */ __name(function() {
        var number2, string3 = "";
        if (ch === "-") {
          string3 = "-";
          next("-");
        }
        while (ch >= "0" && ch <= "9") {
          string3 += ch;
          next();
        }
        if (ch === ".") {
          string3 += ".";
          while (next() && ch >= "0" && ch <= "9") {
            string3 += ch;
          }
        }
        if (ch === "e" || ch === "E") {
          string3 += ch;
          next();
          if (ch === "-" || ch === "+") {
            string3 += ch;
            next();
          }
          while (ch >= "0" && ch <= "9") {
            string3 += ch;
            next();
          }
        }
        number2 = +string3;
        if (!isFinite(number2)) {
          error("Bad number");
        } else {
          if (BigNumber == null) BigNumber = require_bignumber();
          if (string3.length > 15)
            return _options.storeAsString ? string3 : _options.useNativeBigInt ? BigInt(string3) : new BigNumber(string3);
          else
            return !_options.alwaysParseAsBig ? number2 : _options.useNativeBigInt ? BigInt(number2) : new BigNumber(number2);
        }
      }, "number"), string = /* @__PURE__ */ __name(function() {
        var hex, i, string3 = "", uffff;
        if (ch === '"') {
          var startAt = at;
          while (next()) {
            if (ch === '"') {
              if (at - 1 > startAt) string3 += text.substring(startAt, at - 1);
              next();
              return string3;
            }
            if (ch === "\\") {
              if (at - 1 > startAt) string3 += text.substring(startAt, at - 1);
              next();
              if (ch === "u") {
                uffff = 0;
                for (i = 0; i < 4; i += 1) {
                  hex = parseInt(next(), 16);
                  if (!isFinite(hex)) {
                    break;
                  }
                  uffff = uffff * 16 + hex;
                }
                string3 += String.fromCharCode(uffff);
              } else if (typeof escapee[ch] === "string") {
                string3 += escapee[ch];
              } else {
                break;
              }
              startAt = at;
            }
          }
        }
        error("Bad string");
      }, "string"), white = /* @__PURE__ */ __name(function() {
        while (ch && ch <= " ") {
          next();
        }
      }, "white"), word = /* @__PURE__ */ __name(function() {
        switch (ch) {
          case "t":
            next("t");
            next("r");
            next("u");
            next("e");
            return true;
          case "f":
            next("f");
            next("a");
            next("l");
            next("s");
            next("e");
            return false;
          case "n":
            next("n");
            next("u");
            next("l");
            next("l");
            return null;
        }
        error("Unexpected '" + ch + "'");
      }, "word"), value, array = /* @__PURE__ */ __name(function() {
        var array2 = [];
        if (ch === "[") {
          next("[");
          white();
          if (ch === "]") {
            next("]");
            return array2;
          }
          while (ch) {
            array2.push(value());
            white();
            if (ch === "]") {
              next("]");
              return array2;
            }
            next(",");
            white();
          }
        }
        error("Bad array");
      }, "array"), object = /* @__PURE__ */ __name(function() {
        var key, object2 = /* @__PURE__ */ Object.create(null);
        if (ch === "{") {
          next("{");
          white();
          if (ch === "}") {
            next("}");
            return object2;
          }
          while (ch) {
            key = string();
            white();
            next(":");
            if (_options.strict === true && Object.hasOwnProperty.call(object2, key)) {
              error('Duplicate key "' + key + '"');
            }
            if (suspectProtoRx.test(key) === true) {
              if (_options.protoAction === "error") {
                error("Object contains forbidden prototype property");
              } else if (_options.protoAction === "ignore") {
                value();
              } else {
                object2[key] = value();
              }
            } else if (suspectConstructorRx.test(key) === true) {
              if (_options.constructorAction === "error") {
                error("Object contains forbidden constructor property");
              } else if (_options.constructorAction === "ignore") {
                value();
              } else {
                object2[key] = value();
              }
            } else {
              object2[key] = value();
            }
            white();
            if (ch === "}") {
              next("}");
              return object2;
            }
            next(",");
            white();
          }
        }
        error("Bad object");
      }, "object");
      value = /* @__PURE__ */ __name(function() {
        white();
        switch (ch) {
          case "{":
            return object();
          case "[":
            return array();
          case '"':
            return string();
          case "-":
            return number();
          default:
            return ch >= "0" && ch <= "9" ? number() : word();
        }
      }, "value");
      return function(source2, reviver) {
        var result;
        text = source2 + "";
        at = 0;
        ch = " ";
        result = value();
        white();
        if (ch) {
          error("Syntax error");
        }
        return typeof reviver === "function" ? (/* @__PURE__ */ __name(function walk(holder, key) {
          var k, v, value2 = holder[key];
          if (value2 && typeof value2 === "object") {
            Object.keys(value2).forEach(function(k2) {
              v = walk(value2, k2);
              if (v !== void 0) {
                value2[k2] = v;
              } else {
                delete value2[k2];
              }
            });
          }
          return reviver.call(holder, key, value2);
        }, "walk"))({ "": result }, "") : result;
      };
    }, "json_parse");
    module2.exports = json_parse;
  }
});

// node_modules/json-bigint/index.js
var require_json_bigint = __commonJS({
  "node_modules/json-bigint/index.js"(exports2, module2) {
    init_esbuild_shims();
    var json_stringify = require_stringify().stringify;
    var json_parse = require_parse2();
    module2.exports = function(options2) {
      return {
        parse: json_parse(options2),
        stringify: json_stringify
      };
    };
    module2.exports.parse = json_parse();
    module2.exports.stringify = json_stringify;
  }
});

// node_modules/gcp-metadata/build/src/gcp-residency.js
var require_gcp_residency = __commonJS({
  "node_modules/gcp-metadata/build/src/gcp-residency.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.GCE_LINUX_BIOS_PATHS = void 0;
    exports2.isGoogleCloudServerless = isGoogleCloudServerless;
    exports2.isGoogleComputeEngineLinux = isGoogleComputeEngineLinux;
    exports2.isGoogleComputeEngineMACAddress = isGoogleComputeEngineMACAddress;
    exports2.isGoogleComputeEngine = isGoogleComputeEngine;
    exports2.detectGCPResidency = detectGCPResidency;
    var fs_1 = __require("fs");
    var os_1 = __require("os");
    exports2.GCE_LINUX_BIOS_PATHS = {
      BIOS_DATE: "/sys/class/dmi/id/bios_date",
      BIOS_VENDOR: "/sys/class/dmi/id/bios_vendor"
    };
    var GCE_MAC_ADDRESS_REGEX = /^42:01/;
    function isGoogleCloudServerless() {
      const isGFEnvironment = process.env.CLOUD_RUN_JOB || process.env.FUNCTION_NAME || process.env.K_SERVICE;
      return !!isGFEnvironment;
    }
    __name(isGoogleCloudServerless, "isGoogleCloudServerless");
    function isGoogleComputeEngineLinux() {
      if ((0, os_1.platform)() !== "linux")
        return false;
      try {
        (0, fs_1.statSync)(exports2.GCE_LINUX_BIOS_PATHS.BIOS_DATE);
        const biosVendor = (0, fs_1.readFileSync)(exports2.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR, "utf8");
        return /Google/.test(biosVendor);
      } catch (_a6) {
        return false;
      }
    }
    __name(isGoogleComputeEngineLinux, "isGoogleComputeEngineLinux");
    function isGoogleComputeEngineMACAddress() {
      const interfaces = (0, os_1.networkInterfaces)();
      for (const item of Object.values(interfaces)) {
        if (!item)
          continue;
        for (const { mac } of item) {
          if (GCE_MAC_ADDRESS_REGEX.test(mac)) {
            return true;
          }
        }
      }
      return false;
    }
    __name(isGoogleComputeEngineMACAddress, "isGoogleComputeEngineMACAddress");
    function isGoogleComputeEngine() {
      return isGoogleComputeEngineLinux() || isGoogleComputeEngineMACAddress();
    }
    __name(isGoogleComputeEngine, "isGoogleComputeEngine");
    function detectGCPResidency() {
      return isGoogleCloudServerless() || isGoogleComputeEngine();
    }
    __name(detectGCPResidency, "detectGCPResidency");
  }
});

// node_modules/google-logging-utils/build/src/colours.js
var require_colours = __commonJS({
  "node_modules/google-logging-utils/build/src/colours.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Colours = void 0;
    var Colours = class _Colours {
      static {
        __name(this, "Colours");
      }
      /**
       * @param stream The stream (e.g. process.stderr)
       * @returns true if the stream should have colourization enabled
       */
      static isEnabled(stream2) {
        return stream2.isTTY && (typeof stream2.getColorDepth === "function" ? stream2.getColorDepth() > 2 : true);
      }
      static refresh() {
        _Colours.enabled = _Colours.isEnabled(process.stderr);
        if (!this.enabled) {
          _Colours.reset = "";
          _Colours.bright = "";
          _Colours.dim = "";
          _Colours.red = "";
          _Colours.green = "";
          _Colours.yellow = "";
          _Colours.blue = "";
          _Colours.magenta = "";
          _Colours.cyan = "";
          _Colours.white = "";
          _Colours.grey = "";
        } else {
          _Colours.reset = "\x1B[0m";
          _Colours.bright = "\x1B[1m";
          _Colours.dim = "\x1B[2m";
          _Colours.red = "\x1B[31m";
          _Colours.green = "\x1B[32m";
          _Colours.yellow = "\x1B[33m";
          _Colours.blue = "\x1B[34m";
          _Colours.magenta = "\x1B[35m";
          _Colours.cyan = "\x1B[36m";
          _Colours.white = "\x1B[37m";
          _Colours.grey = "\x1B[90m";
        }
      }
    };
    exports2.Colours = Colours;
    Colours.enabled = false;
    Colours.reset = "";
    Colours.bright = "";
    Colours.dim = "";
    Colours.red = "";
    Colours.green = "";
    Colours.yellow = "";
    Colours.blue = "";
    Colours.magenta = "";
    Colours.cyan = "";
    Colours.white = "";
    Colours.grey = "";
    Colours.refresh();
  }
});

// node_modules/google-logging-utils/build/src/logging-utils.js
var require_logging_utils = __commonJS({
  "node_modules/google-logging-utils/build/src/logging-utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc2 = Object.getOwnPropertyDescriptor(m, k);
      if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m[k];
        }, "get") };
      }
      Object.defineProperty(o2, k2, desc2);
    } : function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o2[k2] = m[k];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v) {
      Object.defineProperty(o2, "default", { enumerable: true, value: v });
    } : function(o2, v) {
      o2["default"] = v;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod2) {
      if (mod2 && mod2.__esModule) return mod2;
      var result = {};
      if (mod2 != null) {
        for (var k in mod2) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod2, k)) __createBinding(result, mod2, k);
      }
      __setModuleDefault(result, mod2);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.env = exports2.DebugLogBackendBase = exports2.placeholder = exports2.AdhocDebugLogger = exports2.LogSeverity = void 0;
    exports2.getNodeBackend = getNodeBackend;
    exports2.getDebugBackend = getDebugBackend;
    exports2.getStructuredBackend = getStructuredBackend;
    exports2.setBackend = setBackend;
    exports2.log = log;
    var node_events_1 = __require("node:events");
    var process51 = __importStar(__require("node:process"));
    var util4 = __importStar(__require("node:util"));
    var colours_1 = require_colours();
    var LogSeverity;
    (function(LogSeverity2) {
      LogSeverity2["DEFAULT"] = "DEFAULT";
      LogSeverity2["DEBUG"] = "DEBUG";
      LogSeverity2["INFO"] = "INFO";
      LogSeverity2["WARNING"] = "WARNING";
      LogSeverity2["ERROR"] = "ERROR";
    })(LogSeverity || (exports2.LogSeverity = LogSeverity = {}));
    var AdhocDebugLogger = class extends node_events_1.EventEmitter {
      static {
        __name(this, "AdhocDebugLogger");
      }
      /**
       * @param upstream The backend will pass a function that will be
       *   called whenever our logger function is invoked.
       */
      constructor(namespace, upstream) {
        super();
        this.namespace = namespace;
        this.upstream = upstream;
        this.func = Object.assign(this.invoke.bind(this), {
          // Also add an instance pointer back to us.
          instance: this,
          // And pull over the EventEmitter functionality.
          on: /* @__PURE__ */ __name((event, listener) => this.on(event, listener), "on")
        });
        this.func.debug = (...args) => this.invokeSeverity(LogSeverity.DEBUG, ...args);
        this.func.info = (...args) => this.invokeSeverity(LogSeverity.INFO, ...args);
        this.func.warn = (...args) => this.invokeSeverity(LogSeverity.WARNING, ...args);
        this.func.error = (...args) => this.invokeSeverity(LogSeverity.ERROR, ...args);
        this.func.sublog = (namespace2) => log(namespace2, this.func);
      }
      invoke(fields, ...args) {
        if (this.upstream) {
          this.upstream(fields, ...args);
        }
        this.emit("log", fields, args);
      }
      invokeSeverity(severity, ...args) {
        this.invoke({ severity }, ...args);
      }
    };
    exports2.AdhocDebugLogger = AdhocDebugLogger;
    exports2.placeholder = new AdhocDebugLogger("", () => {
    }).func;
    var DebugLogBackendBase = class {
      static {
        __name(this, "DebugLogBackendBase");
      }
      constructor() {
        var _a6;
        this.cached = /* @__PURE__ */ new Map();
        this.filters = [];
        this.filtersSet = false;
        let nodeFlag = (_a6 = process51.env[exports2.env.nodeEnables]) !== null && _a6 !== void 0 ? _a6 : "*";
        if (nodeFlag === "all") {
          nodeFlag = "*";
        }
        this.filters = nodeFlag.split(",");
      }
      log(namespace, fields, ...args) {
        try {
          if (!this.filtersSet) {
            this.setFilters();
            this.filtersSet = true;
          }
          let logger6 = this.cached.get(namespace);
          if (!logger6) {
            logger6 = this.makeLogger(namespace);
            this.cached.set(namespace, logger6);
          }
          logger6(fields, ...args);
        } catch (e2) {
          console.error(e2);
        }
      }
    };
    exports2.DebugLogBackendBase = DebugLogBackendBase;
    var NodeBackend = class extends DebugLogBackendBase {
      static {
        __name(this, "NodeBackend");
      }
      constructor() {
        super(...arguments);
        this.enabledRegexp = /.*/g;
      }
      isEnabled(namespace) {
        return this.enabledRegexp.test(namespace);
      }
      makeLogger(namespace) {
        if (!this.enabledRegexp.test(namespace)) {
          return () => {
          };
        }
        return (fields, ...args) => {
          var _a6;
          const nscolour = `${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`;
          const pid = `${colours_1.Colours.yellow}${process51.pid}${colours_1.Colours.reset}`;
          let level;
          switch (fields.severity) {
            case LogSeverity.ERROR:
              level = `${colours_1.Colours.red}${fields.severity}${colours_1.Colours.reset}`;
              break;
            case LogSeverity.INFO:
              level = `${colours_1.Colours.magenta}${fields.severity}${colours_1.Colours.reset}`;
              break;
            case LogSeverity.WARNING:
              level = `${colours_1.Colours.yellow}${fields.severity}${colours_1.Colours.reset}`;
              break;
            default:
              level = (_a6 = fields.severity) !== null && _a6 !== void 0 ? _a6 : LogSeverity.DEFAULT;
              break;
          }
          const msg = util4.formatWithOptions({ colors: colours_1.Colours.enabled }, ...args);
          const filteredFields = Object.assign({}, fields);
          delete filteredFields.severity;
          const fieldsJson = Object.getOwnPropertyNames(filteredFields).length ? JSON.stringify(filteredFields) : "";
          const fieldsColour = fieldsJson ? `${colours_1.Colours.grey}${fieldsJson}${colours_1.Colours.reset}` : "";
          console.error("%s [%s|%s] %s%s", pid, nscolour, level, msg, fieldsJson ? ` ${fieldsColour}` : "");
        };
      }
      // Regexp patterns below are from here:
      // https://github.com/nodejs/node/blob/c0aebed4b3395bd65d54b18d1fd00f071002ac20/lib/internal/util/debuglog.js#L36
      setFilters() {
        const totalFilters = this.filters.join(",");
        const regexp = totalFilters.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, ".*").replace(/,/g, "$|^");
        this.enabledRegexp = new RegExp(`^${regexp}$`, "i");
      }
    };
    function getNodeBackend() {
      return new NodeBackend();
    }
    __name(getNodeBackend, "getNodeBackend");
    var DebugBackend = class extends DebugLogBackendBase {
      static {
        __name(this, "DebugBackend");
      }
      constructor(pkg2) {
        super();
        this.debugPkg = pkg2;
      }
      makeLogger(namespace) {
        const debugLogger = this.debugPkg(namespace);
        return (fields, ...args) => {
          debugLogger(args[0], ...args.slice(1));
        };
      }
      setFilters() {
        var _a6;
        const existingFilters = (_a6 = process51.env["NODE_DEBUG"]) !== null && _a6 !== void 0 ? _a6 : "";
        process51.env["NODE_DEBUG"] = `${existingFilters}${existingFilters ? "," : ""}${this.filters.join(",")}`;
      }
    };
    function getDebugBackend(debugPkg) {
      return new DebugBackend(debugPkg);
    }
    __name(getDebugBackend, "getDebugBackend");
    var StructuredBackend = class extends DebugLogBackendBase {
      static {
        __name(this, "StructuredBackend");
      }
      constructor(upstream) {
        var _a6;
        super();
        this.upstream = (_a6 = upstream) !== null && _a6 !== void 0 ? _a6 : new NodeBackend();
      }
      makeLogger(namespace) {
        const debugLogger = this.upstream.makeLogger(namespace);
        return (fields, ...args) => {
          var _a6;
          const severity = (_a6 = fields.severity) !== null && _a6 !== void 0 ? _a6 : LogSeverity.INFO;
          const json2 = Object.assign({
            severity,
            message: util4.format(...args)
          }, fields);
          const jsonString = JSON.stringify(json2);
          debugLogger(fields, jsonString);
        };
      }
      setFilters() {
        this.upstream.setFilters();
      }
    };
    function getStructuredBackend(upstream) {
      return new StructuredBackend(upstream);
    }
    __name(getStructuredBackend, "getStructuredBackend");
    exports2.env = {
      /**
       * Filter wildcards specific to the Node syntax, and similar to the built-in
       * utils.debuglog() environment variable. If missing, disables logging.
       */
      nodeEnables: "GOOGLE_SDK_NODE_LOGGING"
    };
    var loggerCache = /* @__PURE__ */ new Map();
    var cachedBackend = void 0;
    function setBackend(backend) {
      cachedBackend = backend;
      loggerCache.clear();
    }
    __name(setBackend, "setBackend");
    function log(namespace, parent) {
      const enablesFlag = process51.env[exports2.env.nodeEnables];
      if (!enablesFlag) {
        return exports2.placeholder;
      }
      if (!namespace) {
        return exports2.placeholder;
      }
      if (parent) {
        namespace = `${parent.instance.namespace}:${namespace}`;
      }
      const existing = loggerCache.get(namespace);
      if (existing) {
        return existing.func;
      }
      if (cachedBackend === null) {
        return exports2.placeholder;
      } else if (cachedBackend === void 0) {
        cachedBackend = getNodeBackend();
      }
      const logger6 = (() => {
        let previousBackend = void 0;
        const newLogger = new AdhocDebugLogger(namespace, (fields, ...args) => {
          if (previousBackend !== cachedBackend) {
            if (cachedBackend === null) {
              return;
            } else if (cachedBackend === void 0) {
              cachedBackend = getNodeBackend();
            }
            previousBackend = cachedBackend;
          }
          cachedBackend === null || cachedBackend === void 0 ? void 0 : cachedBackend.log(namespace, fields, ...args);
        });
        return newLogger;
      })();
      loggerCache.set(namespace, logger6);
      return logger6.func;
    }
    __name(log, "log");
  }
});

// node_modules/google-logging-utils/build/src/index.js
var require_src3 = __commonJS({
  "node_modules/google-logging-utils/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc2 = Object.getOwnPropertyDescriptor(m, k);
      if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m[k];
        }, "get") };
      }
      Object.defineProperty(o2, k2, desc2);
    } : function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o2[k2] = m[k];
    });
    var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    __exportStar(require_logging_utils(), exports2);
  }
});

// node_modules/gcp-metadata/build/src/index.js
var require_src4 = __commonJS({
  "node_modules/gcp-metadata/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc2 = Object.getOwnPropertyDescriptor(m, k);
      if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m[k];
        }, "get") };
      }
      Object.defineProperty(o2, k2, desc2);
    } : function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o2[k2] = m[k];
    });
    var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.gcpResidencyCache = exports2.METADATA_SERVER_DETECTION = exports2.HEADERS = exports2.HEADER_VALUE = exports2.HEADER_NAME = exports2.SECONDARY_HOST_ADDRESS = exports2.HOST_ADDRESS = exports2.BASE_PATH = void 0;
    exports2.instance = instance;
    exports2.project = project;
    exports2.universe = universe;
    exports2.bulk = bulk;
    exports2.isAvailable = isAvailable;
    exports2.resetIsAvailableCache = resetIsAvailableCache;
    exports2.getGCPResidency = getGCPResidency;
    exports2.setGCPResidency = setGCPResidency;
    exports2.requestTimeout = requestTimeout;
    var gaxios_1 = require_src2();
    var jsonBigint = require_json_bigint();
    var gcp_residency_1 = require_gcp_residency();
    var logger6 = require_src3();
    exports2.BASE_PATH = "/computeMetadata/v1";
    exports2.HOST_ADDRESS = "http://169.254.169.254";
    exports2.SECONDARY_HOST_ADDRESS = "http://metadata.google.internal.";
    exports2.HEADER_NAME = "Metadata-Flavor";
    exports2.HEADER_VALUE = "Google";
    exports2.HEADERS = Object.freeze({ [exports2.HEADER_NAME]: exports2.HEADER_VALUE });
    var log = logger6.log("gcp metadata");
    exports2.METADATA_SERVER_DETECTION = Object.freeze({
      "assume-present": "don't try to ping the metadata server, but assume it's present",
      none: "don't try to ping the metadata server, but don't try to use it either",
      "bios-only": "treat the result of a BIOS probe as canonical (don't fall back to pinging)",
      "ping-only": "skip the BIOS probe, and go straight to pinging"
    });
    function getBaseUrl2(baseUrl) {
      if (!baseUrl) {
        baseUrl = process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST || exports2.HOST_ADDRESS;
      }
      if (!/^https?:\/\//.test(baseUrl)) {
        baseUrl = `http://${baseUrl}`;
      }
      return new URL(exports2.BASE_PATH, baseUrl).href;
    }
    __name(getBaseUrl2, "getBaseUrl");
    function validate4(options2) {
      Object.keys(options2).forEach((key) => {
        switch (key) {
          case "params":
          case "property":
          case "headers":
            break;
          case "qs":
            throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");
          default:
            throw new Error(`'${key}' is not a valid configuration option.`);
        }
      });
    }
    __name(validate4, "validate");
    async function metadataAccessor(type, options2 = {}, noResponseRetries = 3, fastFail = false) {
      let metadataKey = "";
      let params = {};
      let headers = {};
      if (typeof type === "object") {
        const metadataAccessor2 = type;
        metadataKey = metadataAccessor2.metadataKey;
        params = metadataAccessor2.params || params;
        headers = metadataAccessor2.headers || headers;
        noResponseRetries = metadataAccessor2.noResponseRetries || noResponseRetries;
        fastFail = metadataAccessor2.fastFail || fastFail;
      } else {
        metadataKey = type;
      }
      if (typeof options2 === "string") {
        metadataKey += `/${options2}`;
      } else {
        validate4(options2);
        if (options2.property) {
          metadataKey += `/${options2.property}`;
        }
        headers = options2.headers || headers;
        params = options2.params || params;
      }
      const requestMethod = fastFail ? fastFailMetadataRequest : gaxios_1.request;
      const req = {
        url: `${getBaseUrl2()}/${metadataKey}`,
        headers: { ...exports2.HEADERS, ...headers },
        retryConfig: { noResponseRetries },
        params,
        responseType: "text",
        timeout: requestTimeout()
      };
      log.info("instance request %j", req);
      const res = await requestMethod(req);
      log.info("instance metadata is %s", res.data);
      if (res.headers[exports2.HEADER_NAME.toLowerCase()] !== exports2.HEADER_VALUE) {
        throw new Error(`Invalid response from metadata service: incorrect ${exports2.HEADER_NAME} header. Expected '${exports2.HEADER_VALUE}', got ${res.headers[exports2.HEADER_NAME.toLowerCase()] ? `'${res.headers[exports2.HEADER_NAME.toLowerCase()]}'` : "no header"}`);
      }
      if (typeof res.data === "string") {
        try {
          return jsonBigint.parse(res.data);
        } catch (_a6) {
        }
      }
      return res.data;
    }
    __name(metadataAccessor, "metadataAccessor");
    async function fastFailMetadataRequest(options2) {
      var _a6;
      const secondaryOptions = {
        ...options2,
        url: (_a6 = options2.url) === null || _a6 === void 0 ? void 0 : _a6.toString().replace(getBaseUrl2(), getBaseUrl2(exports2.SECONDARY_HOST_ADDRESS))
      };
      let responded = false;
      const r1 = (0, gaxios_1.request)(options2).then((res) => {
        responded = true;
        return res;
      }).catch((err) => {
        if (responded) {
          return r22;
        } else {
          responded = true;
          throw err;
        }
      });
      const r22 = (0, gaxios_1.request)(secondaryOptions).then((res) => {
        responded = true;
        return res;
      }).catch((err) => {
        if (responded) {
          return r1;
        } else {
          responded = true;
          throw err;
        }
      });
      return Promise.race([r1, r22]);
    }
    __name(fastFailMetadataRequest, "fastFailMetadataRequest");
    function instance(options2) {
      return metadataAccessor("instance", options2);
    }
    __name(instance, "instance");
    function project(options2) {
      return metadataAccessor("project", options2);
    }
    __name(project, "project");
    function universe(options2) {
      return metadataAccessor("universe", options2);
    }
    __name(universe, "universe");
    async function bulk(properties) {
      const r3 = {};
      await Promise.all(properties.map((item) => {
        return (async () => {
          const res = await metadataAccessor(item);
          const key = item.metadataKey;
          r3[key] = res;
        })();
      }));
      return r3;
    }
    __name(bulk, "bulk");
    function detectGCPAvailableRetries() {
      return process.env.DETECT_GCP_RETRIES ? Number(process.env.DETECT_GCP_RETRIES) : 0;
    }
    __name(detectGCPAvailableRetries, "detectGCPAvailableRetries");
    var cachedIsAvailableResponse;
    async function isAvailable() {
      if (process.env.METADATA_SERVER_DETECTION) {
        const value = process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();
        if (!(value in exports2.METADATA_SERVER_DETECTION)) {
          throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${value}\`, but it should be \`${Object.keys(exports2.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);
        }
        switch (value) {
          case "assume-present":
            return true;
          case "none":
            return false;
          case "bios-only":
            return getGCPResidency();
          case "ping-only":
        }
      }
      try {
        if (cachedIsAvailableResponse === void 0) {
          cachedIsAvailableResponse = metadataAccessor(
            "instance",
            void 0,
            detectGCPAvailableRetries(),
            // If the default HOST_ADDRESS has been overridden, we should not
            // make an effort to try SECONDARY_HOST_ADDRESS (as we are likely in
            // a non-GCP environment):
            !(process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST)
          );
        }
        await cachedIsAvailableResponse;
        return true;
      } catch (e2) {
        const err = e2;
        if (process.env.DEBUG_AUTH) {
          console.info(err);
        }
        if (err.type === "request-timeout") {
          return false;
        }
        if (err.response && err.response.status === 404) {
          return false;
        } else {
          if (!(err.response && err.response.status === 404) && // A warning is emitted if we see an unexpected err.code, or err.code
          // is not populated:
          (!err.code || ![
            "EHOSTDOWN",
            "EHOSTUNREACH",
            "ENETUNREACH",
            "ENOENT",
            "ENOTFOUND",
            "ECONNREFUSED"
          ].includes(err.code))) {
            let code2 = "UNKNOWN";
            if (err.code)
              code2 = err.code;
            process.emitWarning(`received unexpected error = ${err.message} code = ${code2}`, "MetadataLookupWarning");
          }
          return false;
        }
      }
    }
    __name(isAvailable, "isAvailable");
    function resetIsAvailableCache() {
      cachedIsAvailableResponse = void 0;
    }
    __name(resetIsAvailableCache, "resetIsAvailableCache");
    exports2.gcpResidencyCache = null;
    function getGCPResidency() {
      if (exports2.gcpResidencyCache === null) {
        setGCPResidency();
      }
      return exports2.gcpResidencyCache;
    }
    __name(getGCPResidency, "getGCPResidency");
    function setGCPResidency(value = null) {
      exports2.gcpResidencyCache = value !== null ? value : (0, gcp_residency_1.detectGCPResidency)();
    }
    __name(setGCPResidency, "setGCPResidency");
    function requestTimeout() {
      return getGCPResidency() ? 0 : 3e3;
    }
    __name(requestTimeout, "requestTimeout");
    __exportStar(require_gcp_residency(), exports2);
  }
});

// node_modules/base64-js/index.js
var require_base64_js = __commonJS({
  "node_modules/base64-js/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    exports2.byteLength = byteLength;
    exports2.toByteArray = toByteArray;
    exports2.fromByteArray = fromByteArray;
    var lookup = [];
    var revLookup = [];
    var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
    var code2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for (i = 0, len = code2.length; i < len; ++i) {
      lookup[i] = code2[i];
      revLookup[code2.charCodeAt(i)] = i;
    }
    var i;
    var len;
    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];
    }
    __name(getLens, "getLens");
    function byteLength(b64) {
      var lens = getLens(b64);
      var validLen = lens[0];
      var placeHoldersLen = lens[1];
      return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
    }
    __name(byteLength, "byteLength");
    function _byteLength(b64, validLen, placeHoldersLen) {
      return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
    }
    __name(_byteLength, "_byteLength");
    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;
    }
    __name(toByteArray, "toByteArray");
    function tripletToBase64(num) {
      return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
    }
    __name(tripletToBase64, "tripletToBase64");
    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("");
    }
    __name(encodeChunk, "encodeChunk");
    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("");
    }
    __name(fromByteArray, "fromByteArray");
  }
});

// node_modules/google-auth-library/build/src/crypto/browser/crypto.js
var require_crypto = __commonJS({
  "node_modules/google-auth-library/build/src/crypto/browser/crypto.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BrowserCrypto = void 0;
    var base64js = require_base64_js();
    var crypto_1 = require_crypto3();
    var BrowserCrypto = class _BrowserCrypto {
      static {
        __name(this, "BrowserCrypto");
      }
      constructor() {
        if (typeof window === "undefined" || window.crypto === void 0 || window.crypto.subtle === void 0) {
          throw new Error("SubtleCrypto not found. Make sure it's an https:// website.");
        }
      }
      async sha256DigestBase64(str2) {
        const inputBuffer = new TextEncoder().encode(str2);
        const outputBuffer = await window.crypto.subtle.digest("SHA-256", inputBuffer);
        return base64js.fromByteArray(new Uint8Array(outputBuffer));
      }
      randomBytesBase64(count) {
        const array = new Uint8Array(count);
        window.crypto.getRandomValues(array);
        return base64js.fromByteArray(array);
      }
      static padBase64(base64) {
        while (base64.length % 4 !== 0) {
          base64 += "=";
        }
        return base64;
      }
      async verify(pubkey, data, signature) {
        const algo = {
          name: "RSASSA-PKCS1-v1_5",
          hash: { name: "SHA-256" }
        };
        const dataArray = new TextEncoder().encode(data);
        const signatureArray = base64js.toByteArray(_BrowserCrypto.padBase64(signature));
        const cryptoKey = await window.crypto.subtle.importKey("jwk", pubkey, algo, true, ["verify"]);
        const result = await window.crypto.subtle.verify(algo, cryptoKey, signatureArray, dataArray);
        return result;
      }
      async sign(privateKey, data) {
        const algo = {
          name: "RSASSA-PKCS1-v1_5",
          hash: { name: "SHA-256" }
        };
        const dataArray = new TextEncoder().encode(data);
        const cryptoKey = await window.crypto.subtle.importKey("jwk", privateKey, algo, true, ["sign"]);
        const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray);
        return base64js.fromByteArray(new Uint8Array(result));
      }
      decodeBase64StringUtf8(base64) {
        const uint8array = base64js.toByteArray(_BrowserCrypto.padBase64(base64));
        const result = new TextDecoder().decode(uint8array);
        return result;
      }
      encodeBase64StringUtf8(text) {
        const uint8array = new TextEncoder().encode(text);
        const result = base64js.fromByteArray(uint8array);
        return result;
      }
      /**
       * Computes the SHA-256 hash of the provided string.
       * @param str The plain text string to hash.
       * @return A promise that resolves with the SHA-256 hash of the provided
       *   string in hexadecimal encoding.
       */
      async sha256DigestHex(str2) {
        const inputBuffer = new TextEncoder().encode(str2);
        const outputBuffer = await window.crypto.subtle.digest("SHA-256", inputBuffer);
        return (0, crypto_1.fromArrayBufferToHex)(outputBuffer);
      }
      /**
       * Computes the HMAC hash of a message using the provided crypto key and the
       * SHA-256 algorithm.
       * @param key The secret crypto key in utf-8 or ArrayBuffer format.
       * @param msg The plain text message.
       * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer
       *   format.
       */
      async signWithHmacSha256(key, msg) {
        const rawKey = typeof key === "string" ? key : String.fromCharCode(...new Uint16Array(key));
        const enc = new TextEncoder();
        const cryptoKey = await window.crypto.subtle.importKey("raw", enc.encode(rawKey), {
          name: "HMAC",
          hash: {
            name: "SHA-256"
          }
        }, false, ["sign"]);
        return window.crypto.subtle.sign("HMAC", cryptoKey, enc.encode(msg));
      }
    };
    exports2.BrowserCrypto = BrowserCrypto;
  }
});

// node_modules/google-auth-library/build/src/crypto/node/crypto.js
var require_crypto2 = __commonJS({
  "node_modules/google-auth-library/build/src/crypto/node/crypto.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NodeCrypto = void 0;
    var crypto18 = __require("crypto");
    var NodeCrypto = class {
      static {
        __name(this, "NodeCrypto");
      }
      async sha256DigestBase64(str2) {
        return crypto18.createHash("sha256").update(str2).digest("base64");
      }
      randomBytesBase64(count) {
        return crypto18.randomBytes(count).toString("base64");
      }
      async verify(pubkey, data, signature) {
        const verifier = crypto18.createVerify("RSA-SHA256");
        verifier.update(data);
        verifier.end();
        return verifier.verify(pubkey, signature, "base64");
      }
      async sign(privateKey, data) {
        const signer = crypto18.createSign("RSA-SHA256");
        signer.update(data);
        signer.end();
        return signer.sign(privateKey, "base64");
      }
      decodeBase64StringUtf8(base64) {
        return Buffer.from(base64, "base64").toString("utf-8");
      }
      encodeBase64StringUtf8(text) {
        return Buffer.from(text, "utf-8").toString("base64");
      }
      /**
       * Computes the SHA-256 hash of the provided string.
       * @param str The plain text string to hash.
       * @return A promise that resolves with the SHA-256 hash of the provided
       *   string in hexadecimal encoding.
       */
      async sha256DigestHex(str2) {
        return crypto18.createHash("sha256").update(str2).digest("hex");
      }
      /**
       * Computes the HMAC hash of a message using the provided crypto key and the
       * SHA-256 algorithm.
       * @param key The secret crypto key in utf-8 or ArrayBuffer format.
       * @param msg The plain text message.
       * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer
       *   format.
       */
      async signWithHmacSha256(key, msg) {
        const cryptoKey = typeof key === "string" ? key : toBuffer(key);
        return toArrayBuffer(crypto18.createHmac("sha256", cryptoKey).update(msg).digest());
      }
    };
    exports2.NodeCrypto = NodeCrypto;
    function toArrayBuffer(buffer) {
      return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
    }
    __name(toArrayBuffer, "toArrayBuffer");
    function toBuffer(arrayBuffer) {
      return Buffer.from(arrayBuffer);
    }
    __name(toBuffer, "toBuffer");
  }
});

// node_modules/google-auth-library/build/src/crypto/crypto.js
var require_crypto3 = __commonJS({
  "node_modules/google-auth-library/build/src/crypto/crypto.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createCrypto = createCrypto;
    exports2.hasBrowserCrypto = hasBrowserCrypto;
    exports2.fromArrayBufferToHex = fromArrayBufferToHex;
    var crypto_1 = require_crypto();
    var crypto_2 = require_crypto2();
    function createCrypto() {
      if (hasBrowserCrypto()) {
        return new crypto_1.BrowserCrypto();
      }
      return new crypto_2.NodeCrypto();
    }
    __name(createCrypto, "createCrypto");
    function hasBrowserCrypto() {
      return typeof window !== "undefined" && typeof window.crypto !== "undefined" && typeof window.crypto.subtle !== "undefined";
    }
    __name(hasBrowserCrypto, "hasBrowserCrypto");
    function fromArrayBufferToHex(arrayBuffer) {
      const byteArray = Array.from(new Uint8Array(arrayBuffer));
      return byteArray.map((byte) => {
        return byte.toString(16).padStart(2, "0");
      }).join("");
    }
    __name(fromArrayBufferToHex, "fromArrayBufferToHex");
  }
});

// node_modules/google-auth-library/build/src/options.js
var require_options = __commonJS({
  "node_modules/google-auth-library/build/src/options.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validate = validate4;
    function validate4(options2) {
      const vpairs = [
        { invalid: "uri", expected: "url" },
        { invalid: "json", expected: "data" },
        { invalid: "qs", expected: "params" }
      ];
      for (const pair of vpairs) {
        if (options2[pair.invalid]) {
          const e2 = `'${pair.invalid}' is not a valid configuration option. Please use '${pair.expected}' instead. This library is using Axios for requests. Please see https://github.com/axios/axios to learn more about the valid request options.`;
          throw new Error(e2);
        }
      }
    }
    __name(validate4, "validate");
  }
});

// node_modules/google-auth-library/package.json
var require_package2 = __commonJS({
  "node_modules/google-auth-library/package.json"(exports2, module2) {
    module2.exports = {
      name: "google-auth-library",
      version: "9.15.1",
      author: "Google Inc.",
      description: "Google APIs Authentication Client Library for Node.js",
      engines: {
        node: ">=14"
      },
      main: "./build/src/index.js",
      types: "./build/src/index.d.ts",
      repository: "googleapis/google-auth-library-nodejs.git",
      keywords: [
        "google",
        "api",
        "google apis",
        "client",
        "client library"
      ],
      dependencies: {
        "base64-js": "^1.3.0",
        "ecdsa-sig-formatter": "^1.0.11",
        gaxios: "^6.1.1",
        "gcp-metadata": "^6.1.0",
        gtoken: "^7.0.0",
        jws: "^4.0.0"
      },
      devDependencies: {
        "@types/base64-js": "^1.2.5",
        "@types/chai": "^4.1.7",
        "@types/jws": "^3.1.0",
        "@types/mocha": "^9.0.0",
        "@types/mv": "^2.1.0",
        "@types/ncp": "^2.0.1",
        "@types/node": "^20.4.2",
        "@types/sinon": "^17.0.0",
        "assert-rejects": "^1.0.0",
        c8: "^8.0.0",
        chai: "^4.2.0",
        cheerio: "1.0.0-rc.12",
        codecov: "^3.0.2",
        "engine.io": "6.6.2",
        gts: "^5.0.0",
        "is-docker": "^2.0.0",
        jsdoc: "^4.0.0",
        "jsdoc-fresh": "^3.0.0",
        "jsdoc-region-tag": "^3.0.0",
        karma: "^6.0.0",
        "karma-chrome-launcher": "^3.0.0",
        "karma-coverage": "^2.0.0",
        "karma-firefox-launcher": "^2.0.0",
        "karma-mocha": "^2.0.0",
        "karma-sourcemap-loader": "^0.4.0",
        "karma-webpack": "5.0.0",
        keypair: "^1.0.4",
        linkinator: "^4.0.0",
        mocha: "^9.2.2",
        mv: "^2.1.1",
        ncp: "^2.0.0",
        nock: "^13.0.0",
        "null-loader": "^4.0.0",
        pdfmake: "0.2.12",
        puppeteer: "^21.0.0",
        sinon: "^18.0.0",
        "ts-loader": "^8.0.0",
        typescript: "^5.1.6",
        webpack: "^5.21.2",
        "webpack-cli": "^4.0.0"
      },
      files: [
        "build/src",
        "!build/src/**/*.map"
      ],
      scripts: {
        test: "c8 mocha build/test",
        clean: "gts clean",
        prepare: "npm run compile",
        lint: "gts check",
        compile: "tsc -p .",
        fix: "gts fix",
        pretest: "npm run compile -- --sourceMap",
        docs: "jsdoc -c .jsdoc.json",
        "samples-setup": "cd samples/ && npm link ../ && npm run setup && cd ../",
        "samples-test": "cd samples/ && npm link ../ && npm test && cd ../",
        "system-test": "mocha build/system-test --timeout 60000",
        "presystem-test": "npm run compile -- --sourceMap",
        webpack: "webpack",
        "browser-test": "karma start",
        "docs-test": "linkinator docs",
        "predocs-test": "npm run docs",
        prelint: "cd samples; npm link ../; npm install",
        precompile: "gts clean"
      },
      license: "Apache-2.0"
    };
  }
});

// node_modules/google-auth-library/build/src/transporters.js
var require_transporters = __commonJS({
  "node_modules/google-auth-library/build/src/transporters.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DefaultTransporter = void 0;
    var gaxios_1 = require_src2();
    var options_1 = require_options();
    var pkg2 = require_package2();
    var PRODUCT_NAME = "google-api-nodejs-client";
    var DefaultTransporter = class _DefaultTransporter {
      static {
        __name(this, "DefaultTransporter");
      }
      constructor() {
        this.instance = new gaxios_1.Gaxios();
      }
      /**
       * Configures request options before making a request.
       * @param opts GaxiosOptions options.
       * @return Configured options.
       */
      configure(opts = {}) {
        opts.headers = opts.headers || {};
        if (typeof window === "undefined") {
          const uaValue = opts.headers["User-Agent"];
          if (!uaValue) {
            opts.headers["User-Agent"] = _DefaultTransporter.USER_AGENT;
          } else if (!uaValue.includes(`${PRODUCT_NAME}/`)) {
            opts.headers["User-Agent"] = `${uaValue} ${_DefaultTransporter.USER_AGENT}`;
          }
          if (!opts.headers["x-goog-api-client"]) {
            const nodeVersion2 = process.version.replace(/^v/, "");
            opts.headers["x-goog-api-client"] = `gl-node/${nodeVersion2}`;
          }
        }
        return opts;
      }
      /**
       * Makes a request using Gaxios with given options.
       * @param opts GaxiosOptions options.
       * @param callback optional callback that contains GaxiosResponse object.
       * @return GaxiosPromise, assuming no callback is passed.
       */
      request(opts) {
        opts = this.configure(opts);
        (0, options_1.validate)(opts);
        return this.instance.request(opts).catch((e2) => {
          throw this.processError(e2);
        });
      }
      get defaults() {
        return this.instance.defaults;
      }
      set defaults(opts) {
        this.instance.defaults = opts;
      }
      /**
       * Changes the error to include details from the body.
       */
      processError(e2) {
        const res = e2.response;
        const err = e2;
        const body = res ? res.data : null;
        if (res && body && body.error && res.status !== 200) {
          if (typeof body.error === "string") {
            err.message = body.error;
            err.status = res.status;
          } else if (Array.isArray(body.error.errors)) {
            err.message = body.error.errors.map((err2) => err2.message).join("\n");
            err.code = body.error.code;
            err.errors = body.error.errors;
          } else {
            err.message = body.error.message;
            err.code = body.error.code;
          }
        } else if (res && res.status >= 400) {
          err.message = body;
          err.status = res.status;
        }
        return err;
      }
    };
    exports2.DefaultTransporter = DefaultTransporter;
    DefaultTransporter.USER_AGENT = `${PRODUCT_NAME}/${pkg2.version}`;
  }
});

// node_modules/safe-buffer/index.js
var require_safe_buffer = __commonJS({
  "node_modules/safe-buffer/index.js"(exports2, module2) {
    init_esbuild_shims();
    var buffer = __require("buffer");
    var Buffer5 = buffer.Buffer;
    function copyProps(src, dst) {
      for (var key in src) {
        dst[key] = src[key];
      }
    }
    __name(copyProps, "copyProps");
    if (Buffer5.from && Buffer5.alloc && Buffer5.allocUnsafe && Buffer5.allocUnsafeSlow) {
      module2.exports = buffer;
    } else {
      copyProps(buffer, exports2);
      exports2.Buffer = SafeBuffer;
    }
    function SafeBuffer(arg, encodingOrOffset, length) {
      return Buffer5(arg, encodingOrOffset, length);
    }
    __name(SafeBuffer, "SafeBuffer");
    SafeBuffer.prototype = Object.create(Buffer5.prototype);
    copyProps(Buffer5, SafeBuffer);
    SafeBuffer.from = function(arg, encodingOrOffset, length) {
      if (typeof arg === "number") {
        throw new TypeError("Argument must not be a number");
      }
      return Buffer5(arg, encodingOrOffset, length);
    };
    SafeBuffer.alloc = function(size, fill, encoding) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      var buf = Buffer5(size);
      if (fill !== void 0) {
        if (typeof encoding === "string") {
          buf.fill(fill, encoding);
        } else {
          buf.fill(fill);
        }
      } else {
        buf.fill(0);
      }
      return buf;
    };
    SafeBuffer.allocUnsafe = function(size) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      return Buffer5(size);
    };
    SafeBuffer.allocUnsafeSlow = function(size) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      return buffer.SlowBuffer(size);
    };
  }
});

// node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js
var require_param_bytes_for_alg = __commonJS({
  "node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    function getParamSize(keySize) {
      var result = (keySize / 8 | 0) + (keySize % 8 === 0 ? 0 : 1);
      return result;
    }
    __name(getParamSize, "getParamSize");
    var paramBytesForAlg = {
      ES256: getParamSize(256),
      ES384: getParamSize(384),
      ES512: getParamSize(521)
    };
    function getParamBytesForAlg(alg) {
      var paramBytes = paramBytesForAlg[alg];
      if (paramBytes) {
        return paramBytes;
      }
      throw new Error('Unknown algorithm "' + alg + '"');
    }
    __name(getParamBytesForAlg, "getParamBytesForAlg");
    module2.exports = getParamBytesForAlg;
  }
});

// node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js
var require_ecdsa_sig_formatter = __commonJS({
  "node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Buffer5 = require_safe_buffer().Buffer;
    var getParamBytesForAlg = require_param_bytes_for_alg();
    var MAX_OCTET = 128;
    var CLASS_UNIVERSAL = 0;
    var PRIMITIVE_BIT = 32;
    var TAG_SEQ = 16;
    var TAG_INT = 2;
    var ENCODED_TAG_SEQ = TAG_SEQ | PRIMITIVE_BIT | CLASS_UNIVERSAL << 6;
    var ENCODED_TAG_INT = TAG_INT | CLASS_UNIVERSAL << 6;
    function base64Url(base64) {
      return base64.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
    }
    __name(base64Url, "base64Url");
    function signatureAsBuffer(signature) {
      if (Buffer5.isBuffer(signature)) {
        return signature;
      } else if ("string" === typeof signature) {
        return Buffer5.from(signature, "base64");
      }
      throw new TypeError("ECDSA signature must be a Base64 string or a Buffer");
    }
    __name(signatureAsBuffer, "signatureAsBuffer");
    function derToJose(signature, alg) {
      signature = signatureAsBuffer(signature);
      var paramBytes = getParamBytesForAlg(alg);
      var maxEncodedParamLength = paramBytes + 1;
      var inputLength = signature.length;
      var offset = 0;
      if (signature[offset++] !== ENCODED_TAG_SEQ) {
        throw new Error('Could not find expected "seq"');
      }
      var seqLength = signature[offset++];
      if (seqLength === (MAX_OCTET | 1)) {
        seqLength = signature[offset++];
      }
      if (inputLength - offset < seqLength) {
        throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining');
      }
      if (signature[offset++] !== ENCODED_TAG_INT) {
        throw new Error('Could not find expected "int" for "r"');
      }
      var rLength = signature[offset++];
      if (inputLength - offset - 2 < rLength) {
        throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available');
      }
      if (maxEncodedParamLength < rLength) {
        throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable');
      }
      var rOffset = offset;
      offset += rLength;
      if (signature[offset++] !== ENCODED_TAG_INT) {
        throw new Error('Could not find expected "int" for "s"');
      }
      var sLength = signature[offset++];
      if (inputLength - offset !== sLength) {
        throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"');
      }
      if (maxEncodedParamLength < sLength) {
        throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable');
      }
      var sOffset = offset;
      offset += sLength;
      if (offset !== inputLength) {
        throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain');
      }
      var rPadding = paramBytes - rLength, sPadding = paramBytes - sLength;
      var dst = Buffer5.allocUnsafe(rPadding + rLength + sPadding + sLength);
      for (offset = 0; offset < rPadding; ++offset) {
        dst[offset] = 0;
      }
      signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength);
      offset = paramBytes;
      for (var o2 = offset; offset < o2 + sPadding; ++offset) {
        dst[offset] = 0;
      }
      signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength);
      dst = dst.toString("base64");
      dst = base64Url(dst);
      return dst;
    }
    __name(derToJose, "derToJose");
    function countPadding(buf, start, stop2) {
      var padding = 0;
      while (start + padding < stop2 && buf[start + padding] === 0) {
        ++padding;
      }
      var needsSign = buf[start + padding] >= MAX_OCTET;
      if (needsSign) {
        --padding;
      }
      return padding;
    }
    __name(countPadding, "countPadding");
    function joseToDer(signature, alg) {
      signature = signatureAsBuffer(signature);
      var paramBytes = getParamBytesForAlg(alg);
      var signatureBytes = signature.length;
      if (signatureBytes !== paramBytes * 2) {
        throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"');
      }
      var rPadding = countPadding(signature, 0, paramBytes);
      var sPadding = countPadding(signature, paramBytes, signature.length);
      var rLength = paramBytes - rPadding;
      var sLength = paramBytes - sPadding;
      var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength;
      var shortLength = rsBytes < MAX_OCTET;
      var dst = Buffer5.allocUnsafe((shortLength ? 2 : 3) + rsBytes);
      var offset = 0;
      dst[offset++] = ENCODED_TAG_SEQ;
      if (shortLength) {
        dst[offset++] = rsBytes;
      } else {
        dst[offset++] = MAX_OCTET | 1;
        dst[offset++] = rsBytes & 255;
      }
      dst[offset++] = ENCODED_TAG_INT;
      dst[offset++] = rLength;
      if (rPadding < 0) {
        dst[offset++] = 0;
        offset += signature.copy(dst, offset, 0, paramBytes);
      } else {
        offset += signature.copy(dst, offset, rPadding, paramBytes);
      }
      dst[offset++] = ENCODED_TAG_INT;
      dst[offset++] = sLength;
      if (sPadding < 0) {
        dst[offset++] = 0;
        signature.copy(dst, offset, paramBytes);
      } else {
        signature.copy(dst, offset, paramBytes + sPadding);
      }
      return dst;
    }
    __name(joseToDer, "joseToDer");
    module2.exports = {
      derToJose,
      joseToDer
    };
  }
});

// node_modules/google-auth-library/build/src/util.js
var require_util8 = __commonJS({
  "node_modules/google-auth-library/build/src/util.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __classPrivateFieldGet4 = exports2 && exports2.__classPrivateFieldGet || function(receiver, state, kind, f) {
      if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    };
    var _LRUCache_instances;
    var _LRUCache_cache;
    var _LRUCache_moveToEnd;
    var _LRUCache_evict;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LRUCache = void 0;
    exports2.snakeToCamel = snakeToCamel;
    exports2.originalOrCamelOptions = originalOrCamelOptions;
    function snakeToCamel(str2) {
      return str2.replace(/([_][^_])/g, (match2) => match2.slice(1).toUpperCase());
    }
    __name(snakeToCamel, "snakeToCamel");
    function originalOrCamelOptions(obj) {
      function get3(key) {
        var _a6;
        const o2 = obj || {};
        return (_a6 = o2[key]) !== null && _a6 !== void 0 ? _a6 : o2[snakeToCamel(key)];
      }
      __name(get3, "get");
      return { get: get3 };
    }
    __name(originalOrCamelOptions, "originalOrCamelOptions");
    var LRUCache2 = class {
      static {
        __name(this, "LRUCache");
      }
      constructor(options2) {
        _LRUCache_instances.add(this);
        _LRUCache_cache.set(this, /* @__PURE__ */ new Map());
        this.capacity = options2.capacity;
        this.maxAge = options2.maxAge;
      }
      /**
       * Add an item to the cache.
       *
       * @param key the key to upsert
       * @param value the value of the key
       */
      set(key, value) {
        __classPrivateFieldGet4(this, _LRUCache_instances, "m", _LRUCache_moveToEnd).call(this, key, value);
        __classPrivateFieldGet4(this, _LRUCache_instances, "m", _LRUCache_evict).call(this);
      }
      /**
       * Get an item from the cache.
       *
       * @param key the key to retrieve
       */
      get(key) {
        const item = __classPrivateFieldGet4(this, _LRUCache_cache, "f").get(key);
        if (!item)
          return;
        __classPrivateFieldGet4(this, _LRUCache_instances, "m", _LRUCache_moveToEnd).call(this, key, item.value);
        __classPrivateFieldGet4(this, _LRUCache_instances, "m", _LRUCache_evict).call(this);
        return item.value;
      }
    };
    exports2.LRUCache = LRUCache2;
    _LRUCache_cache = /* @__PURE__ */ new WeakMap(), _LRUCache_instances = /* @__PURE__ */ new WeakSet(), _LRUCache_moveToEnd = /* @__PURE__ */ __name(function _LRUCache_moveToEnd2(key, value) {
      __classPrivateFieldGet4(this, _LRUCache_cache, "f").delete(key);
      __classPrivateFieldGet4(this, _LRUCache_cache, "f").set(key, {
        value,
        lastAccessed: Date.now()
      });
    }, "_LRUCache_moveToEnd"), _LRUCache_evict = /* @__PURE__ */ __name(function _LRUCache_evict2() {
      const cutoffDate = this.maxAge ? Date.now() - this.maxAge : 0;
      let oldestItem = __classPrivateFieldGet4(this, _LRUCache_cache, "f").entries().next();
      while (!oldestItem.done && (__classPrivateFieldGet4(this, _LRUCache_cache, "f").size > this.capacity || // too many
      oldestItem.value[1].lastAccessed < cutoffDate)) {
        __classPrivateFieldGet4(this, _LRUCache_cache, "f").delete(oldestItem.value[0]);
        oldestItem = __classPrivateFieldGet4(this, _LRUCache_cache, "f").entries().next();
      }
    }, "_LRUCache_evict");
  }
});

// node_modules/google-auth-library/build/src/auth/authclient.js
var require_authclient = __commonJS({
  "node_modules/google-auth-library/build/src/auth/authclient.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AuthClient = exports2.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = exports2.DEFAULT_UNIVERSE = void 0;
    var events_1 = __require("events");
    var gaxios_1 = require_src2();
    var transporters_1 = require_transporters();
    var util_1 = require_util8();
    exports2.DEFAULT_UNIVERSE = "googleapis.com";
    exports2.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = 5 * 60 * 1e3;
    var AuthClient = class extends events_1.EventEmitter {
      static {
        __name(this, "AuthClient");
      }
      constructor(opts = {}) {
        var _a6, _b2, _c2, _d, _e;
        super();
        this.credentials = {};
        this.eagerRefreshThresholdMillis = exports2.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;
        this.forceRefreshOnFailure = false;
        this.universeDomain = exports2.DEFAULT_UNIVERSE;
        const options2 = (0, util_1.originalOrCamelOptions)(opts);
        this.apiKey = opts.apiKey;
        this.projectId = (_a6 = options2.get("project_id")) !== null && _a6 !== void 0 ? _a6 : null;
        this.quotaProjectId = options2.get("quota_project_id");
        this.credentials = (_b2 = options2.get("credentials")) !== null && _b2 !== void 0 ? _b2 : {};
        this.universeDomain = (_c2 = options2.get("universe_domain")) !== null && _c2 !== void 0 ? _c2 : exports2.DEFAULT_UNIVERSE;
        this.transporter = (_d = opts.transporter) !== null && _d !== void 0 ? _d : new transporters_1.DefaultTransporter();
        if (opts.transporterOptions) {
          this.transporter.defaults = opts.transporterOptions;
        }
        if (opts.eagerRefreshThresholdMillis) {
          this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis;
        }
        this.forceRefreshOnFailure = (_e = opts.forceRefreshOnFailure) !== null && _e !== void 0 ? _e : false;
      }
      /**
       * Return the {@link Gaxios `Gaxios`} instance from the {@link AuthClient.transporter}.
       *
       * @expiremental
       */
      get gaxios() {
        if (this.transporter instanceof gaxios_1.Gaxios) {
          return this.transporter;
        } else if (this.transporter instanceof transporters_1.DefaultTransporter) {
          return this.transporter.instance;
        } else if ("instance" in this.transporter && this.transporter.instance instanceof gaxios_1.Gaxios) {
          return this.transporter.instance;
        }
        return null;
      }
      /**
       * Sets the auth credentials.
       */
      setCredentials(credentials) {
        this.credentials = credentials;
      }
      /**
       * Append additional headers, e.g., x-goog-user-project, shared across the
       * classes inheriting AuthClient. This method should be used by any method
       * that overrides getRequestMetadataAsync(), which is a shared helper for
       * setting request information in both gRPC and HTTP API calls.
       *
       * @param headers object to append additional headers to.
       */
      addSharedMetadataHeaders(headers) {
        if (!headers["x-goog-user-project"] && // don't override a value the user sets.
        this.quotaProjectId) {
          headers["x-goog-user-project"] = this.quotaProjectId;
        }
        return headers;
      }
      /**
       * Retry config for Auth-related requests.
       *
       * @remarks
       *
       * This is not a part of the default {@link AuthClient.transporter transporter/gaxios}
       * config as some downstream APIs would prefer if customers explicitly enable retries,
       * such as GCS.
       */
      static get RETRY_CONFIG() {
        return {
          retry: true,
          retryConfig: {
            httpMethodsToRetry: ["GET", "PUT", "POST", "HEAD", "OPTIONS", "DELETE"]
          }
        };
      }
    };
    exports2.AuthClient = AuthClient;
  }
});

// node_modules/google-auth-library/build/src/auth/loginticket.js
var require_loginticket = __commonJS({
  "node_modules/google-auth-library/build/src/auth/loginticket.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LoginTicket = void 0;
    var LoginTicket = class {
      static {
        __name(this, "LoginTicket");
      }
      /**
       * Create a simple class to extract user ID from an ID Token
       *
       * @param {string} env Envelope of the jwt
       * @param {TokenPayload} pay Payload of the jwt
       * @constructor
       */
      constructor(env7, pay) {
        this.envelope = env7;
        this.payload = pay;
      }
      getEnvelope() {
        return this.envelope;
      }
      getPayload() {
        return this.payload;
      }
      /**
       * Create a simple class to extract user ID from an ID Token
       *
       * @return The user ID
       */
      getUserId() {
        const payload = this.getPayload();
        if (payload && payload.sub) {
          return payload.sub;
        }
        return null;
      }
      /**
       * Returns attributes from the login ticket.  This can contain
       * various information about the user session.
       *
       * @return The envelope and payload
       */
      getAttributes() {
        return { envelope: this.getEnvelope(), payload: this.getPayload() };
      }
    };
    exports2.LoginTicket = LoginTicket;
  }
});

// node_modules/google-auth-library/build/src/auth/oauth2client.js
var require_oauth2client = __commonJS({
  "node_modules/google-auth-library/build/src/auth/oauth2client.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OAuth2Client = exports2.ClientAuthentication = exports2.CertificateFormat = exports2.CodeChallengeMethod = void 0;
    var gaxios_1 = require_src2();
    var querystring = __require("querystring");
    var stream2 = __require("stream");
    var formatEcdsa = require_ecdsa_sig_formatter();
    var crypto_1 = require_crypto3();
    var authclient_1 = require_authclient();
    var loginticket_1 = require_loginticket();
    var CodeChallengeMethod2;
    (function(CodeChallengeMethod3) {
      CodeChallengeMethod3["Plain"] = "plain";
      CodeChallengeMethod3["S256"] = "S256";
    })(CodeChallengeMethod2 || (exports2.CodeChallengeMethod = CodeChallengeMethod2 = {}));
    var CertificateFormat;
    (function(CertificateFormat2) {
      CertificateFormat2["PEM"] = "PEM";
      CertificateFormat2["JWK"] = "JWK";
    })(CertificateFormat || (exports2.CertificateFormat = CertificateFormat = {}));
    var ClientAuthentication;
    (function(ClientAuthentication2) {
      ClientAuthentication2["ClientSecretPost"] = "ClientSecretPost";
      ClientAuthentication2["ClientSecretBasic"] = "ClientSecretBasic";
      ClientAuthentication2["None"] = "None";
    })(ClientAuthentication || (exports2.ClientAuthentication = ClientAuthentication = {}));
    var OAuth2Client2 = class _OAuth2Client extends authclient_1.AuthClient {
      static {
        __name(this, "OAuth2Client");
      }
      constructor(optionsOrClientId, clientSecret, redirectUri) {
        const opts = optionsOrClientId && typeof optionsOrClientId === "object" ? optionsOrClientId : { clientId: optionsOrClientId, clientSecret, redirectUri };
        super(opts);
        this.certificateCache = {};
        this.certificateExpiry = null;
        this.certificateCacheFormat = CertificateFormat.PEM;
        this.refreshTokenPromises = /* @__PURE__ */ new Map();
        this._clientId = opts.clientId;
        this._clientSecret = opts.clientSecret;
        this.redirectUri = opts.redirectUri;
        this.endpoints = {
          tokenInfoUrl: "https://oauth2.googleapis.com/tokeninfo",
          oauth2AuthBaseUrl: "https://accounts.google.com/o/oauth2/v2/auth",
          oauth2TokenUrl: "https://oauth2.googleapis.com/token",
          oauth2RevokeUrl: "https://oauth2.googleapis.com/revoke",
          oauth2FederatedSignonPemCertsUrl: "https://www.googleapis.com/oauth2/v1/certs",
          oauth2FederatedSignonJwkCertsUrl: "https://www.googleapis.com/oauth2/v3/certs",
          oauth2IapPublicKeyUrl: "https://www.gstatic.com/iap/verify/public_key",
          ...opts.endpoints
        };
        this.clientAuthentication = opts.clientAuthentication || ClientAuthentication.ClientSecretPost;
        this.issuers = opts.issuers || [
          "accounts.google.com",
          "https://accounts.google.com",
          this.universeDomain
        ];
      }
      /**
       * Generates URL for consent page landing.
       * @param opts Options.
       * @return URL to consent page.
       */
      generateAuthUrl(opts = {}) {
        if (opts.code_challenge_method && !opts.code_challenge) {
          throw new Error("If a code_challenge_method is provided, code_challenge must be included.");
        }
        opts.response_type = opts.response_type || "code";
        opts.client_id = opts.client_id || this._clientId;
        opts.redirect_uri = opts.redirect_uri || this.redirectUri;
        if (Array.isArray(opts.scope)) {
          opts.scope = opts.scope.join(" ");
        }
        const rootUrl = this.endpoints.oauth2AuthBaseUrl.toString();
        return rootUrl + "?" + querystring.stringify(opts);
      }
      generateCodeVerifier() {
        throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.");
      }
      /**
       * Convenience method to automatically generate a code_verifier, and its
       * resulting SHA256. If used, this must be paired with a S256
       * code_challenge_method.
       *
       * For a full example see:
       * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js
       */
      async generateCodeVerifierAsync() {
        const crypto18 = (0, crypto_1.createCrypto)();
        const randomString = crypto18.randomBytesBase64(96);
        const codeVerifier = randomString.replace(/\+/g, "~").replace(/=/g, "_").replace(/\//g, "-");
        const unencodedCodeChallenge = await crypto18.sha256DigestBase64(codeVerifier);
        const codeChallenge = unencodedCodeChallenge.split("=")[0].replace(/\+/g, "-").replace(/\//g, "_");
        return { codeVerifier, codeChallenge };
      }
      getToken(codeOrOptions, callback) {
        const options2 = typeof codeOrOptions === "string" ? { code: codeOrOptions } : codeOrOptions;
        if (callback) {
          this.getTokenAsync(options2).then((r3) => callback(null, r3.tokens, r3.res), (e2) => callback(e2, null, e2.response));
        } else {
          return this.getTokenAsync(options2);
        }
      }
      async getTokenAsync(options2) {
        const url2 = this.endpoints.oauth2TokenUrl.toString();
        const headers = {
          "Content-Type": "application/x-www-form-urlencoded"
        };
        const values = {
          client_id: options2.client_id || this._clientId,
          code_verifier: options2.codeVerifier,
          code: options2.code,
          grant_type: "authorization_code",
          redirect_uri: options2.redirect_uri || this.redirectUri
        };
        if (this.clientAuthentication === ClientAuthentication.ClientSecretBasic) {
          const basic = Buffer.from(`${this._clientId}:${this._clientSecret}`);
          headers["Authorization"] = `Basic ${basic.toString("base64")}`;
        }
        if (this.clientAuthentication === ClientAuthentication.ClientSecretPost) {
          values.client_secret = this._clientSecret;
        }
        const res = await this.transporter.request({
          ..._OAuth2Client.RETRY_CONFIG,
          method: "POST",
          url: url2,
          data: querystring.stringify(values),
          headers
        });
        const tokens = res.data;
        if (res.data && res.data.expires_in) {
          tokens.expiry_date = (/* @__PURE__ */ new Date()).getTime() + res.data.expires_in * 1e3;
          delete tokens.expires_in;
        }
        this.emit("tokens", tokens);
        return { tokens, res };
      }
      /**
       * Refreshes the access token.
       * @param refresh_token Existing refresh token.
       * @private
       */
      async refreshToken(refreshToken) {
        if (!refreshToken) {
          return this.refreshTokenNoCache(refreshToken);
        }
        if (this.refreshTokenPromises.has(refreshToken)) {
          return this.refreshTokenPromises.get(refreshToken);
        }
        const p = this.refreshTokenNoCache(refreshToken).then((r3) => {
          this.refreshTokenPromises.delete(refreshToken);
          return r3;
        }, (e2) => {
          this.refreshTokenPromises.delete(refreshToken);
          throw e2;
        });
        this.refreshTokenPromises.set(refreshToken, p);
        return p;
      }
      async refreshTokenNoCache(refreshToken) {
        var _a6;
        if (!refreshToken) {
          throw new Error("No refresh token is set.");
        }
        const url2 = this.endpoints.oauth2TokenUrl.toString();
        const data = {
          refresh_token: refreshToken,
          client_id: this._clientId,
          client_secret: this._clientSecret,
          grant_type: "refresh_token"
        };
        let res;
        try {
          res = await this.transporter.request({
            ..._OAuth2Client.RETRY_CONFIG,
            method: "POST",
            url: url2,
            data: querystring.stringify(data),
            headers: { "Content-Type": "application/x-www-form-urlencoded" }
          });
        } catch (e2) {
          if (e2 instanceof gaxios_1.GaxiosError && e2.message === "invalid_grant" && ((_a6 = e2.response) === null || _a6 === void 0 ? void 0 : _a6.data) && /ReAuth/i.test(e2.response.data.error_description)) {
            e2.message = JSON.stringify(e2.response.data);
          }
          throw e2;
        }
        const tokens = res.data;
        if (res.data && res.data.expires_in) {
          tokens.expiry_date = (/* @__PURE__ */ new Date()).getTime() + res.data.expires_in * 1e3;
          delete tokens.expires_in;
        }
        this.emit("tokens", tokens);
        return { tokens, res };
      }
      refreshAccessToken(callback) {
        if (callback) {
          this.refreshAccessTokenAsync().then((r3) => callback(null, r3.credentials, r3.res), callback);
        } else {
          return this.refreshAccessTokenAsync();
        }
      }
      async refreshAccessTokenAsync() {
        const r3 = await this.refreshToken(this.credentials.refresh_token);
        const tokens = r3.tokens;
        tokens.refresh_token = this.credentials.refresh_token;
        this.credentials = tokens;
        return { credentials: this.credentials, res: r3.res };
      }
      getAccessToken(callback) {
        if (callback) {
          this.getAccessTokenAsync().then((r3) => callback(null, r3.token, r3.res), callback);
        } else {
          return this.getAccessTokenAsync();
        }
      }
      async getAccessTokenAsync() {
        const shouldRefresh = !this.credentials.access_token || this.isTokenExpiring();
        if (shouldRefresh) {
          if (!this.credentials.refresh_token) {
            if (this.refreshHandler) {
              const refreshedAccessToken = await this.processAndValidateRefreshHandler();
              if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) {
                this.setCredentials(refreshedAccessToken);
                return { token: this.credentials.access_token };
              }
            } else {
              throw new Error("No refresh token or refresh handler callback is set.");
            }
          }
          const r3 = await this.refreshAccessTokenAsync();
          if (!r3.credentials || r3.credentials && !r3.credentials.access_token) {
            throw new Error("Could not refresh access token.");
          }
          return { token: r3.credentials.access_token, res: r3.res };
        } else {
          return { token: this.credentials.access_token };
        }
      }
      /**
       * The main authentication interface.  It takes an optional url which when
       * present is the endpoint being accessed, and returns a Promise which
       * resolves with authorization header fields.
       *
       * In OAuth2Client, the result has the form:
       * { Authorization: 'Bearer <access_token_value>' }
       * @param url The optional url being authorized
       */
      async getRequestHeaders(url2) {
        const headers = (await this.getRequestMetadataAsync(url2)).headers;
        return headers;
      }
      async getRequestMetadataAsync(url2) {
        const thisCreds = this.credentials;
        if (!thisCreds.access_token && !thisCreds.refresh_token && !this.apiKey && !this.refreshHandler) {
          throw new Error("No access, refresh token, API key or refresh handler callback is set.");
        }
        if (thisCreds.access_token && !this.isTokenExpiring()) {
          thisCreds.token_type = thisCreds.token_type || "Bearer";
          const headers2 = {
            Authorization: thisCreds.token_type + " " + thisCreds.access_token
          };
          return { headers: this.addSharedMetadataHeaders(headers2) };
        }
        if (this.refreshHandler) {
          const refreshedAccessToken = await this.processAndValidateRefreshHandler();
          if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) {
            this.setCredentials(refreshedAccessToken);
            const headers2 = {
              Authorization: "Bearer " + this.credentials.access_token
            };
            return { headers: this.addSharedMetadataHeaders(headers2) };
          }
        }
        if (this.apiKey) {
          return { headers: { "X-Goog-Api-Key": this.apiKey } };
        }
        let r3 = null;
        let tokens = null;
        try {
          r3 = await this.refreshToken(thisCreds.refresh_token);
          tokens = r3.tokens;
        } catch (err) {
          const e2 = err;
          if (e2.response && (e2.response.status === 403 || e2.response.status === 404)) {
            e2.message = `Could not refresh access token: ${e2.message}`;
          }
          throw e2;
        }
        const credentials = this.credentials;
        credentials.token_type = credentials.token_type || "Bearer";
        tokens.refresh_token = credentials.refresh_token;
        this.credentials = tokens;
        const headers = {
          Authorization: credentials.token_type + " " + tokens.access_token
        };
        return { headers: this.addSharedMetadataHeaders(headers), res: r3.res };
      }
      /**
       * Generates an URL to revoke the given token.
       * @param token The existing token to be revoked.
       *
       * @deprecated use instance method {@link OAuth2Client.getRevokeTokenURL}
       */
      static getRevokeTokenUrl(token2) {
        return new _OAuth2Client().getRevokeTokenURL(token2).toString();
      }
      /**
       * Generates a URL to revoke the given token.
       *
       * @param token The existing token to be revoked.
       */
      getRevokeTokenURL(token2) {
        const url2 = new URL(this.endpoints.oauth2RevokeUrl);
        url2.searchParams.append("token", token2);
        return url2;
      }
      revokeToken(token2, callback) {
        const opts = {
          ..._OAuth2Client.RETRY_CONFIG,
          url: this.getRevokeTokenURL(token2).toString(),
          method: "POST"
        };
        if (callback) {
          this.transporter.request(opts).then((r3) => callback(null, r3), callback);
        } else {
          return this.transporter.request(opts);
        }
      }
      revokeCredentials(callback) {
        if (callback) {
          this.revokeCredentialsAsync().then((res) => callback(null, res), callback);
        } else {
          return this.revokeCredentialsAsync();
        }
      }
      async revokeCredentialsAsync() {
        const token2 = this.credentials.access_token;
        this.credentials = {};
        if (token2) {
          return this.revokeToken(token2);
        } else {
          throw new Error("No access token to revoke.");
        }
      }
      request(opts, callback) {
        if (callback) {
          this.requestAsync(opts).then((r3) => callback(null, r3), (e2) => {
            return callback(e2, e2.response);
          });
        } else {
          return this.requestAsync(opts);
        }
      }
      async requestAsync(opts, reAuthRetried = false) {
        let r22;
        try {
          const r3 = await this.getRequestMetadataAsync(opts.url);
          opts.headers = opts.headers || {};
          if (r3.headers && r3.headers["x-goog-user-project"]) {
            opts.headers["x-goog-user-project"] = r3.headers["x-goog-user-project"];
          }
          if (r3.headers && r3.headers.Authorization) {
            opts.headers.Authorization = r3.headers.Authorization;
          }
          if (this.apiKey) {
            opts.headers["X-Goog-Api-Key"] = this.apiKey;
          }
          r22 = await this.transporter.request(opts);
        } catch (e2) {
          const res = e2.response;
          if (res) {
            const statusCode = res.status;
            const mayRequireRefresh = this.credentials && this.credentials.access_token && this.credentials.refresh_token && (!this.credentials.expiry_date || this.forceRefreshOnFailure);
            const mayRequireRefreshWithNoRefreshToken = this.credentials && this.credentials.access_token && !this.credentials.refresh_token && (!this.credentials.expiry_date || this.forceRefreshOnFailure) && this.refreshHandler;
            const isReadableStream = res.config.data instanceof stream2.Readable;
            const isAuthErr = statusCode === 401 || statusCode === 403;
            if (!reAuthRetried && isAuthErr && !isReadableStream && mayRequireRefresh) {
              await this.refreshAccessTokenAsync();
              return this.requestAsync(opts, true);
            } else if (!reAuthRetried && isAuthErr && !isReadableStream && mayRequireRefreshWithNoRefreshToken) {
              const refreshedAccessToken = await this.processAndValidateRefreshHandler();
              if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) {
                this.setCredentials(refreshedAccessToken);
              }
              return this.requestAsync(opts, true);
            }
          }
          throw e2;
        }
        return r22;
      }
      verifyIdToken(options2, callback) {
        if (callback && typeof callback !== "function") {
          throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");
        }
        if (callback) {
          this.verifyIdTokenAsync(options2).then((r3) => callback(null, r3), callback);
        } else {
          return this.verifyIdTokenAsync(options2);
        }
      }
      async verifyIdTokenAsync(options2) {
        if (!options2.idToken) {
          throw new Error("The verifyIdToken method requires an ID Token");
        }
        const response = await this.getFederatedSignonCertsAsync();
        const login = await this.verifySignedJwtWithCertsAsync(options2.idToken, response.certs, options2.audience, this.issuers, options2.maxExpiry);
        return login;
      }
      /**
       * Obtains information about the provisioned access token.  Especially useful
       * if you want to check the scopes that were provisioned to a given token.
       *
       * @param accessToken Required.  The Access Token for which you want to get
       * user info.
       */
      async getTokenInfo(accessToken) {
        const { data } = await this.transporter.request({
          ..._OAuth2Client.RETRY_CONFIG,
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            Authorization: `Bearer ${accessToken}`
          },
          url: this.endpoints.tokenInfoUrl.toString()
        });
        const info = Object.assign({
          expiry_date: (/* @__PURE__ */ new Date()).getTime() + data.expires_in * 1e3,
          scopes: data.scope.split(" ")
        }, data);
        delete info.expires_in;
        delete info.scope;
        return info;
      }
      getFederatedSignonCerts(callback) {
        if (callback) {
          this.getFederatedSignonCertsAsync().then((r3) => callback(null, r3.certs, r3.res), callback);
        } else {
          return this.getFederatedSignonCertsAsync();
        }
      }
      async getFederatedSignonCertsAsync() {
        const nowTime = (/* @__PURE__ */ new Date()).getTime();
        const format4 = (0, crypto_1.hasBrowserCrypto)() ? CertificateFormat.JWK : CertificateFormat.PEM;
        if (this.certificateExpiry && nowTime < this.certificateExpiry.getTime() && this.certificateCacheFormat === format4) {
          return { certs: this.certificateCache, format: format4 };
        }
        let res;
        let url2;
        switch (format4) {
          case CertificateFormat.PEM:
            url2 = this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();
            break;
          case CertificateFormat.JWK:
            url2 = this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();
            break;
          default:
            throw new Error(`Unsupported certificate format ${format4}`);
        }
        try {
          res = await this.transporter.request({
            ..._OAuth2Client.RETRY_CONFIG,
            url: url2
          });
        } catch (e2) {
          if (e2 instanceof Error) {
            e2.message = `Failed to retrieve verification certificates: ${e2.message}`;
          }
          throw e2;
        }
        const cacheControl = res ? res.headers["cache-control"] : void 0;
        let cacheAge = -1;
        if (cacheControl) {
          const pattern = new RegExp("max-age=([0-9]*)");
          const regexResult = pattern.exec(cacheControl);
          if (regexResult && regexResult.length === 2) {
            cacheAge = Number(regexResult[1]) * 1e3;
          }
        }
        let certificates = {};
        switch (format4) {
          case CertificateFormat.PEM:
            certificates = res.data;
            break;
          case CertificateFormat.JWK:
            for (const key of res.data.keys) {
              certificates[key.kid] = key;
            }
            break;
          default:
            throw new Error(`Unsupported certificate format ${format4}`);
        }
        const now = /* @__PURE__ */ new Date();
        this.certificateExpiry = cacheAge === -1 ? null : new Date(now.getTime() + cacheAge);
        this.certificateCache = certificates;
        this.certificateCacheFormat = format4;
        return { certs: certificates, format: format4, res };
      }
      getIapPublicKeys(callback) {
        if (callback) {
          this.getIapPublicKeysAsync().then((r3) => callback(null, r3.pubkeys, r3.res), callback);
        } else {
          return this.getIapPublicKeysAsync();
        }
      }
      async getIapPublicKeysAsync() {
        let res;
        const url2 = this.endpoints.oauth2IapPublicKeyUrl.toString();
        try {
          res = await this.transporter.request({
            ..._OAuth2Client.RETRY_CONFIG,
            url: url2
          });
        } catch (e2) {
          if (e2 instanceof Error) {
            e2.message = `Failed to retrieve verification certificates: ${e2.message}`;
          }
          throw e2;
        }
        return { pubkeys: res.data, res };
      }
      verifySignedJwtWithCerts() {
        throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.");
      }
      /**
       * Verify the id token is signed with the correct certificate
       * and is from the correct audience.
       * @param jwt The jwt to verify (The ID Token in this case).
       * @param certs The array of certs to test the jwt against.
       * @param requiredAudience The audience to test the jwt against.
       * @param issuers The allowed issuers of the jwt (Optional).
       * @param maxExpiry The max expiry the certificate can be (Optional).
       * @return Returns a promise resolving to LoginTicket on verification.
       */
      async verifySignedJwtWithCertsAsync(jwt, certs, requiredAudience, issuers, maxExpiry) {
        const crypto18 = (0, crypto_1.createCrypto)();
        if (!maxExpiry) {
          maxExpiry = _OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_;
        }
        const segments = jwt.split(".");
        if (segments.length !== 3) {
          throw new Error("Wrong number of segments in token: " + jwt);
        }
        const signed = segments[0] + "." + segments[1];
        let signature = segments[2];
        let envelope;
        let payload;
        try {
          envelope = JSON.parse(crypto18.decodeBase64StringUtf8(segments[0]));
        } catch (err) {
          if (err instanceof Error) {
            err.message = `Can't parse token envelope: ${segments[0]}': ${err.message}`;
          }
          throw err;
        }
        if (!envelope) {
          throw new Error("Can't parse token envelope: " + segments[0]);
        }
        try {
          payload = JSON.parse(crypto18.decodeBase64StringUtf8(segments[1]));
        } catch (err) {
          if (err instanceof Error) {
            err.message = `Can't parse token payload '${segments[0]}`;
          }
          throw err;
        }
        if (!payload) {
          throw new Error("Can't parse token payload: " + segments[1]);
        }
        if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) {
          throw new Error("No pem found for envelope: " + JSON.stringify(envelope));
        }
        const cert = certs[envelope.kid];
        if (envelope.alg === "ES256") {
          signature = formatEcdsa.joseToDer(signature, "ES256").toString("base64");
        }
        const verified = await crypto18.verify(cert, signed, signature);
        if (!verified) {
          throw new Error("Invalid token signature: " + jwt);
        }
        if (!payload.iat) {
          throw new Error("No issue time in token: " + JSON.stringify(payload));
        }
        if (!payload.exp) {
          throw new Error("No expiration time in token: " + JSON.stringify(payload));
        }
        const iat = Number(payload.iat);
        if (isNaN(iat))
          throw new Error("iat field using invalid format");
        const exp = Number(payload.exp);
        if (isNaN(exp))
          throw new Error("exp field using invalid format");
        const now = (/* @__PURE__ */ new Date()).getTime() / 1e3;
        if (exp >= now + maxExpiry) {
          throw new Error("Expiration time too far in future: " + JSON.stringify(payload));
        }
        const earliest = iat - _OAuth2Client.CLOCK_SKEW_SECS_;
        const latest = exp + _OAuth2Client.CLOCK_SKEW_SECS_;
        if (now < earliest) {
          throw new Error("Token used too early, " + now + " < " + earliest + ": " + JSON.stringify(payload));
        }
        if (now > latest) {
          throw new Error("Token used too late, " + now + " > " + latest + ": " + JSON.stringify(payload));
        }
        if (issuers && issuers.indexOf(payload.iss) < 0) {
          throw new Error("Invalid issuer, expected one of [" + issuers + "], but got " + payload.iss);
        }
        if (typeof requiredAudience !== "undefined" && requiredAudience !== null) {
          const aud = payload.aud;
          let audVerified = false;
          if (requiredAudience.constructor === Array) {
            audVerified = requiredAudience.indexOf(aud) > -1;
          } else {
            audVerified = aud === requiredAudience;
          }
          if (!audVerified) {
            throw new Error("Wrong recipient, payload audience != requiredAudience");
          }
        }
        return new loginticket_1.LoginTicket(envelope, payload);
      }
      /**
       * Returns a promise that resolves with AccessTokenResponse type if
       * refreshHandler is defined.
       * If not, nothing is returned.
       */
      async processAndValidateRefreshHandler() {
        if (this.refreshHandler) {
          const accessTokenResponse = await this.refreshHandler();
          if (!accessTokenResponse.access_token) {
            throw new Error("No access token is returned by the refreshHandler callback.");
          }
          return accessTokenResponse;
        }
        return;
      }
      /**
       * Returns true if a token is expired or will expire within
       * eagerRefreshThresholdMillismilliseconds.
       * If there is no expiry time, assumes the token is not expired or expiring.
       */
      isTokenExpiring() {
        const expiryDate = this.credentials.expiry_date;
        return expiryDate ? expiryDate <= (/* @__PURE__ */ new Date()).getTime() + this.eagerRefreshThresholdMillis : false;
      }
    };
    exports2.OAuth2Client = OAuth2Client2;
    OAuth2Client2.GOOGLE_TOKEN_INFO_URL = "https://oauth2.googleapis.com/tokeninfo";
    OAuth2Client2.CLOCK_SKEW_SECS_ = 300;
    OAuth2Client2.DEFAULT_MAX_TOKEN_LIFETIME_SECS_ = 86400;
  }
});

// node_modules/google-auth-library/build/src/auth/computeclient.js
var require_computeclient = __commonJS({
  "node_modules/google-auth-library/build/src/auth/computeclient.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Compute = void 0;
    var gaxios_1 = require_src2();
    var gcpMetadata = require_src4();
    var oauth2client_1 = require_oauth2client();
    var Compute2 = class extends oauth2client_1.OAuth2Client {
      static {
        __name(this, "Compute");
      }
      /**
       * Google Compute Engine service account credentials.
       *
       * Retrieve access token from the metadata server.
       * See: https://cloud.google.com/compute/docs/access/authenticate-workloads#applications
       */
      constructor(options2 = {}) {
        super(options2);
        this.credentials = { expiry_date: 1, refresh_token: "compute-placeholder" };
        this.serviceAccountEmail = options2.serviceAccountEmail || "default";
        this.scopes = Array.isArray(options2.scopes) ? options2.scopes : options2.scopes ? [options2.scopes] : [];
      }
      /**
       * Refreshes the access token.
       * @param refreshToken Unused parameter
       */
      async refreshTokenNoCache(refreshToken) {
        const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`;
        let data;
        try {
          const instanceOptions = {
            property: tokenPath
          };
          if (this.scopes.length > 0) {
            instanceOptions.params = {
              scopes: this.scopes.join(",")
            };
          }
          data = await gcpMetadata.instance(instanceOptions);
        } catch (e2) {
          if (e2 instanceof gaxios_1.GaxiosError) {
            e2.message = `Could not refresh access token: ${e2.message}`;
            this.wrapError(e2);
          }
          throw e2;
        }
        const tokens = data;
        if (data && data.expires_in) {
          tokens.expiry_date = (/* @__PURE__ */ new Date()).getTime() + data.expires_in * 1e3;
          delete tokens.expires_in;
        }
        this.emit("tokens", tokens);
        return { tokens, res: null };
      }
      /**
       * Fetches an ID token.
       * @param targetAudience the audience for the fetched ID token.
       */
      async fetchIdToken(targetAudience) {
        const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${targetAudience}`;
        let idToken;
        try {
          const instanceOptions = {
            property: idTokenPath
          };
          idToken = await gcpMetadata.instance(instanceOptions);
        } catch (e2) {
          if (e2 instanceof Error) {
            e2.message = `Could not fetch ID token: ${e2.message}`;
          }
          throw e2;
        }
        return idToken;
      }
      wrapError(e2) {
        const res = e2.response;
        if (res && res.status) {
          e2.status = res.status;
          if (res.status === 403) {
            e2.message = "A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: " + e2.message;
          } else if (res.status === 404) {
            e2.message = "A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: " + e2.message;
          }
        }
      }
    };
    exports2.Compute = Compute2;
  }
});

// node_modules/google-auth-library/build/src/auth/idtokenclient.js
var require_idtokenclient = __commonJS({
  "node_modules/google-auth-library/build/src/auth/idtokenclient.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.IdTokenClient = void 0;
    var oauth2client_1 = require_oauth2client();
    var IdTokenClient = class extends oauth2client_1.OAuth2Client {
      static {
        __name(this, "IdTokenClient");
      }
      /**
       * Google ID Token client
       *
       * Retrieve ID token from the metadata server.
       * See: https://cloud.google.com/docs/authentication/get-id-token#metadata-server
       */
      constructor(options2) {
        super(options2);
        this.targetAudience = options2.targetAudience;
        this.idTokenProvider = options2.idTokenProvider;
      }
      async getRequestMetadataAsync(url2) {
        if (!this.credentials.id_token || !this.credentials.expiry_date || this.isTokenExpiring()) {
          const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience);
          this.credentials = {
            id_token: idToken,
            expiry_date: this.getIdTokenExpiryDate(idToken)
          };
        }
        const headers = {
          Authorization: "Bearer " + this.credentials.id_token
        };
        return { headers };
      }
      getIdTokenExpiryDate(idToken) {
        const payloadB64 = idToken.split(".")[1];
        if (payloadB64) {
          const payload = JSON.parse(Buffer.from(payloadB64, "base64").toString("ascii"));
          return payload.exp * 1e3;
        }
      }
    };
    exports2.IdTokenClient = IdTokenClient;
  }
});

// node_modules/google-auth-library/build/src/auth/envDetect.js
var require_envDetect = __commonJS({
  "node_modules/google-auth-library/build/src/auth/envDetect.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.GCPEnv = void 0;
    exports2.clear = clear;
    exports2.getEnv = getEnv2;
    var gcpMetadata = require_src4();
    var GCPEnv;
    (function(GCPEnv2) {
      GCPEnv2["APP_ENGINE"] = "APP_ENGINE";
      GCPEnv2["KUBERNETES_ENGINE"] = "KUBERNETES_ENGINE";
      GCPEnv2["CLOUD_FUNCTIONS"] = "CLOUD_FUNCTIONS";
      GCPEnv2["COMPUTE_ENGINE"] = "COMPUTE_ENGINE";
      GCPEnv2["CLOUD_RUN"] = "CLOUD_RUN";
      GCPEnv2["NONE"] = "NONE";
    })(GCPEnv || (exports2.GCPEnv = GCPEnv = {}));
    var envPromise;
    function clear() {
      envPromise = void 0;
    }
    __name(clear, "clear");
    async function getEnv2() {
      if (envPromise) {
        return envPromise;
      }
      envPromise = getEnvMemoized();
      return envPromise;
    }
    __name(getEnv2, "getEnv");
    async function getEnvMemoized() {
      let env7 = GCPEnv.NONE;
      if (isAppEngine()) {
        env7 = GCPEnv.APP_ENGINE;
      } else if (isCloudFunction()) {
        env7 = GCPEnv.CLOUD_FUNCTIONS;
      } else if (await isComputeEngine()) {
        if (await isKubernetesEngine()) {
          env7 = GCPEnv.KUBERNETES_ENGINE;
        } else if (isCloudRun()) {
          env7 = GCPEnv.CLOUD_RUN;
        } else {
          env7 = GCPEnv.COMPUTE_ENGINE;
        }
      } else {
        env7 = GCPEnv.NONE;
      }
      return env7;
    }
    __name(getEnvMemoized, "getEnvMemoized");
    function isAppEngine() {
      return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME);
    }
    __name(isAppEngine, "isAppEngine");
    function isCloudFunction() {
      return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET);
    }
    __name(isCloudFunction, "isCloudFunction");
    function isCloudRun() {
      return !!process.env.K_CONFIGURATION;
    }
    __name(isCloudRun, "isCloudRun");
    async function isKubernetesEngine() {
      try {
        await gcpMetadata.instance("attributes/cluster-name");
        return true;
      } catch (e2) {
        return false;
      }
    }
    __name(isKubernetesEngine, "isKubernetesEngine");
    async function isComputeEngine() {
      return gcpMetadata.isAvailable();
    }
    __name(isComputeEngine, "isComputeEngine");
  }
});

// node_modules/jws/lib/data-stream.js
var require_data_stream = __commonJS({
  "node_modules/jws/lib/data-stream.js"(exports2, module2) {
    init_esbuild_shims();
    var Buffer5 = require_safe_buffer().Buffer;
    var Stream4 = __require("stream");
    var util4 = __require("util");
    function DataStream(data) {
      this.buffer = null;
      this.writable = true;
      this.readable = true;
      if (!data) {
        this.buffer = Buffer5.alloc(0);
        return this;
      }
      if (typeof data.pipe === "function") {
        this.buffer = Buffer5.alloc(0);
        data.pipe(this);
        return this;
      }
      if (data.length || typeof data === "object") {
        this.buffer = data;
        this.writable = false;
        process.nextTick(function() {
          this.emit("end", data);
          this.readable = false;
          this.emit("close");
        }.bind(this));
        return this;
      }
      throw new TypeError("Unexpected data type (" + typeof data + ")");
    }
    __name(DataStream, "DataStream");
    util4.inherits(DataStream, Stream4);
    DataStream.prototype.write = /* @__PURE__ */ __name(function write2(data) {
      this.buffer = Buffer5.concat([this.buffer, Buffer5.from(data)]);
      this.emit("data", data);
    }, "write");
    DataStream.prototype.end = /* @__PURE__ */ __name(function end(data) {
      if (data)
        this.write(data);
      this.emit("end", data);
      this.emit("close");
      this.writable = false;
      this.readable = false;
    }, "end");
    module2.exports = DataStream;
  }
});

// node_modules/buffer-equal-constant-time/index.js
var require_buffer_equal_constant_time = __commonJS({
  "node_modules/buffer-equal-constant-time/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Buffer5 = __require("buffer").Buffer;
    var SlowBuffer = __require("buffer").SlowBuffer;
    module2.exports = bufferEq;
    function bufferEq(a, b) {
      if (!Buffer5.isBuffer(a) || !Buffer5.isBuffer(b)) {
        return false;
      }
      if (a.length !== b.length) {
        return false;
      }
      var c3 = 0;
      for (var i = 0; i < a.length; i++) {
        c3 |= a[i] ^ b[i];
      }
      return c3 === 0;
    }
    __name(bufferEq, "bufferEq");
    bufferEq.install = function() {
      Buffer5.prototype.equal = SlowBuffer.prototype.equal = /* @__PURE__ */ __name(function equal(that) {
        return bufferEq(this, that);
      }, "equal");
    };
    var origBufEqual = Buffer5.prototype.equal;
    var origSlowBufEqual = SlowBuffer.prototype.equal;
    bufferEq.restore = function() {
      Buffer5.prototype.equal = origBufEqual;
      SlowBuffer.prototype.equal = origSlowBufEqual;
    };
  }
});

// node_modules/jwa/index.js
var require_jwa = __commonJS({
  "node_modules/jwa/index.js"(exports2, module2) {
    init_esbuild_shims();
    var Buffer5 = require_safe_buffer().Buffer;
    var crypto18 = __require("crypto");
    var formatEcdsa = require_ecdsa_sig_formatter();
    var util4 = __require("util");
    var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n  Supported algorithms are:\n  "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".';
    var MSG_INVALID_SECRET = "secret must be a string or buffer";
    var MSG_INVALID_VERIFIER_KEY = "key must be a string or a buffer";
    var MSG_INVALID_SIGNER_KEY = "key must be a string, a buffer or an object";
    var supportsKeyObjects = typeof crypto18.createPublicKey === "function";
    if (supportsKeyObjects) {
      MSG_INVALID_VERIFIER_KEY += " or a KeyObject";
      MSG_INVALID_SECRET += "or a KeyObject";
    }
    function checkIsPublicKey(key) {
      if (Buffer5.isBuffer(key)) {
        return;
      }
      if (typeof key === "string") {
        return;
      }
      if (!supportsKeyObjects) {
        throw typeError(MSG_INVALID_VERIFIER_KEY);
      }
      if (typeof key !== "object") {
        throw typeError(MSG_INVALID_VERIFIER_KEY);
      }
      if (typeof key.type !== "string") {
        throw typeError(MSG_INVALID_VERIFIER_KEY);
      }
      if (typeof key.asymmetricKeyType !== "string") {
        throw typeError(MSG_INVALID_VERIFIER_KEY);
      }
      if (typeof key.export !== "function") {
        throw typeError(MSG_INVALID_VERIFIER_KEY);
      }
    }
    __name(checkIsPublicKey, "checkIsPublicKey");
    function checkIsPrivateKey(key) {
      if (Buffer5.isBuffer(key)) {
        return;
      }
      if (typeof key === "string") {
        return;
      }
      if (typeof key === "object") {
        return;
      }
      throw typeError(MSG_INVALID_SIGNER_KEY);
    }
    __name(checkIsPrivateKey, "checkIsPrivateKey");
    function checkIsSecretKey(key) {
      if (Buffer5.isBuffer(key)) {
        return;
      }
      if (typeof key === "string") {
        return key;
      }
      if (!supportsKeyObjects) {
        throw typeError(MSG_INVALID_SECRET);
      }
      if (typeof key !== "object") {
        throw typeError(MSG_INVALID_SECRET);
      }
      if (key.type !== "secret") {
        throw typeError(MSG_INVALID_SECRET);
      }
      if (typeof key.export !== "function") {
        throw typeError(MSG_INVALID_SECRET);
      }
    }
    __name(checkIsSecretKey, "checkIsSecretKey");
    function fromBase64(base64) {
      return base64.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
    }
    __name(fromBase64, "fromBase64");
    function toBase64(base64url) {
      base64url = base64url.toString();
      var padding = 4 - base64url.length % 4;
      if (padding !== 4) {
        for (var i = 0; i < padding; ++i) {
          base64url += "=";
        }
      }
      return base64url.replace(/\-/g, "+").replace(/_/g, "/");
    }
    __name(toBase64, "toBase64");
    function typeError(template) {
      var args = [].slice.call(arguments, 1);
      var errMsg = util4.format.bind(util4, template).apply(null, args);
      return new TypeError(errMsg);
    }
    __name(typeError, "typeError");
    function bufferOrString(obj) {
      return Buffer5.isBuffer(obj) || typeof obj === "string";
    }
    __name(bufferOrString, "bufferOrString");
    function normalizeInput(thing) {
      if (!bufferOrString(thing))
        thing = JSON.stringify(thing);
      return thing;
    }
    __name(normalizeInput, "normalizeInput");
    function createHmacSigner(bits) {
      return /* @__PURE__ */ __name(function sign(thing, secret) {
        checkIsSecretKey(secret);
        thing = normalizeInput(thing);
        var hmac = crypto18.createHmac("sha" + bits, secret);
        var sig = (hmac.update(thing), hmac.digest("base64"));
        return fromBase64(sig);
      }, "sign");
    }
    __name(createHmacSigner, "createHmacSigner");
    var bufferEqual;
    var timingSafeEqual = "timingSafeEqual" in crypto18 ? /* @__PURE__ */ __name(function timingSafeEqual2(a, b) {
      if (a.byteLength !== b.byteLength) {
        return false;
      }
      return crypto18.timingSafeEqual(a, b);
    }, "timingSafeEqual") : /* @__PURE__ */ __name(function timingSafeEqual2(a, b) {
      if (!bufferEqual) {
        bufferEqual = require_buffer_equal_constant_time();
      }
      return bufferEqual(a, b);
    }, "timingSafeEqual");
    function createHmacVerifier(bits) {
      return /* @__PURE__ */ __name(function verify(thing, signature, secret) {
        var computedSig = createHmacSigner(bits)(thing, secret);
        return timingSafeEqual(Buffer5.from(signature), Buffer5.from(computedSig));
      }, "verify");
    }
    __name(createHmacVerifier, "createHmacVerifier");
    function createKeySigner(bits) {
      return /* @__PURE__ */ __name(function sign(thing, privateKey) {
        checkIsPrivateKey(privateKey);
        thing = normalizeInput(thing);
        var signer = crypto18.createSign("RSA-SHA" + bits);
        var sig = (signer.update(thing), signer.sign(privateKey, "base64"));
        return fromBase64(sig);
      }, "sign");
    }
    __name(createKeySigner, "createKeySigner");
    function createKeyVerifier(bits) {
      return /* @__PURE__ */ __name(function verify(thing, signature, publicKey) {
        checkIsPublicKey(publicKey);
        thing = normalizeInput(thing);
        signature = toBase64(signature);
        var verifier = crypto18.createVerify("RSA-SHA" + bits);
        verifier.update(thing);
        return verifier.verify(publicKey, signature, "base64");
      }, "verify");
    }
    __name(createKeyVerifier, "createKeyVerifier");
    function createPSSKeySigner(bits) {
      return /* @__PURE__ */ __name(function sign(thing, privateKey) {
        checkIsPrivateKey(privateKey);
        thing = normalizeInput(thing);
        var signer = crypto18.createSign("RSA-SHA" + bits);
        var sig = (signer.update(thing), signer.sign({
          key: privateKey,
          padding: crypto18.constants.RSA_PKCS1_PSS_PADDING,
          saltLength: crypto18.constants.RSA_PSS_SALTLEN_DIGEST
        }, "base64"));
        return fromBase64(sig);
      }, "sign");
    }
    __name(createPSSKeySigner, "createPSSKeySigner");
    function createPSSKeyVerifier(bits) {
      return /* @__PURE__ */ __name(function verify(thing, signature, publicKey) {
        checkIsPublicKey(publicKey);
        thing = normalizeInput(thing);
        signature = toBase64(signature);
        var verifier = crypto18.createVerify("RSA-SHA" + bits);
        verifier.update(thing);
        return verifier.verify({
          key: publicKey,
          padding: crypto18.constants.RSA_PKCS1_PSS_PADDING,
          saltLength: crypto18.constants.RSA_PSS_SALTLEN_DIGEST
        }, signature, "base64");
      }, "verify");
    }
    __name(createPSSKeyVerifier, "createPSSKeyVerifier");
    function createECDSASigner(bits) {
      var inner = createKeySigner(bits);
      return /* @__PURE__ */ __name(function sign() {
        var signature = inner.apply(null, arguments);
        signature = formatEcdsa.derToJose(signature, "ES" + bits);
        return signature;
      }, "sign");
    }
    __name(createECDSASigner, "createECDSASigner");
    function createECDSAVerifer(bits) {
      var inner = createKeyVerifier(bits);
      return /* @__PURE__ */ __name(function verify(thing, signature, publicKey) {
        signature = formatEcdsa.joseToDer(signature, "ES" + bits).toString("base64");
        var result = inner(thing, signature, publicKey);
        return result;
      }, "verify");
    }
    __name(createECDSAVerifer, "createECDSAVerifer");
    function createNoneSigner() {
      return /* @__PURE__ */ __name(function sign() {
        return "";
      }, "sign");
    }
    __name(createNoneSigner, "createNoneSigner");
    function createNoneVerifier() {
      return /* @__PURE__ */ __name(function verify(thing, signature) {
        return signature === "";
      }, "verify");
    }
    __name(createNoneVerifier, "createNoneVerifier");
    module2.exports = /* @__PURE__ */ __name(function jwa(algorithm) {
      var signerFactories = {
        hs: createHmacSigner,
        rs: createKeySigner,
        ps: createPSSKeySigner,
        es: createECDSASigner,
        none: createNoneSigner
      };
      var verifierFactories = {
        hs: createHmacVerifier,
        rs: createKeyVerifier,
        ps: createPSSKeyVerifier,
        es: createECDSAVerifer,
        none: createNoneVerifier
      };
      var match2 = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);
      if (!match2)
        throw typeError(MSG_INVALID_ALGORITHM, algorithm);
      var algo = (match2[1] || match2[3]).toLowerCase();
      var bits = match2[2];
      return {
        sign: signerFactories[algo](bits),
        verify: verifierFactories[algo](bits)
      };
    }, "jwa");
  }
});

// node_modules/jws/lib/tostring.js
var require_tostring = __commonJS({
  "node_modules/jws/lib/tostring.js"(exports2, module2) {
    init_esbuild_shims();
    var Buffer5 = __require("buffer").Buffer;
    module2.exports = /* @__PURE__ */ __name(function toString(obj) {
      if (typeof obj === "string")
        return obj;
      if (typeof obj === "number" || Buffer5.isBuffer(obj))
        return obj.toString();
      return JSON.stringify(obj);
    }, "toString");
  }
});

// node_modules/jws/lib/sign-stream.js
var require_sign_stream = __commonJS({
  "node_modules/jws/lib/sign-stream.js"(exports2, module2) {
    init_esbuild_shims();
    var Buffer5 = require_safe_buffer().Buffer;
    var DataStream = require_data_stream();
    var jwa = require_jwa();
    var Stream4 = __require("stream");
    var toString = require_tostring();
    var util4 = __require("util");
    function base64url(string, encoding) {
      return Buffer5.from(string, encoding).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
    }
    __name(base64url, "base64url");
    function jwsSecuredInput(header, payload, encoding) {
      encoding = encoding || "utf8";
      var encodedHeader = base64url(toString(header), "binary");
      var encodedPayload = base64url(toString(payload), encoding);
      return util4.format("%s.%s", encodedHeader, encodedPayload);
    }
    __name(jwsSecuredInput, "jwsSecuredInput");
    function jwsSign(opts) {
      var header = opts.header;
      var payload = opts.payload;
      var secretOrKey = opts.secret || opts.privateKey;
      var encoding = opts.encoding;
      var algo = jwa(header.alg);
      var securedInput = jwsSecuredInput(header, payload, encoding);
      var signature = algo.sign(securedInput, secretOrKey);
      return util4.format("%s.%s", securedInput, signature);
    }
    __name(jwsSign, "jwsSign");
    function SignStream(opts) {
      var secret = opts.secret || opts.privateKey || opts.key;
      var secretStream = new DataStream(secret);
      this.readable = true;
      this.header = opts.header;
      this.encoding = opts.encoding;
      this.secret = this.privateKey = this.key = secretStream;
      this.payload = new DataStream(opts.payload);
      this.secret.once("close", function() {
        if (!this.payload.writable && this.readable)
          this.sign();
      }.bind(this));
      this.payload.once("close", function() {
        if (!this.secret.writable && this.readable)
          this.sign();
      }.bind(this));
    }
    __name(SignStream, "SignStream");
    util4.inherits(SignStream, Stream4);
    SignStream.prototype.sign = /* @__PURE__ */ __name(function sign() {
      try {
        var signature = jwsSign({
          header: this.header,
          payload: this.payload.buffer,
          secret: this.secret.buffer,
          encoding: this.encoding
        });
        this.emit("done", signature);
        this.emit("data", signature);
        this.emit("end");
        this.readable = false;
        return signature;
      } catch (e2) {
        this.readable = false;
        this.emit("error", e2);
        this.emit("close");
      }
    }, "sign");
    SignStream.sign = jwsSign;
    module2.exports = SignStream;
  }
});

// node_modules/jws/lib/verify-stream.js
var require_verify_stream = __commonJS({
  "node_modules/jws/lib/verify-stream.js"(exports2, module2) {
    init_esbuild_shims();
    var Buffer5 = require_safe_buffer().Buffer;
    var DataStream = require_data_stream();
    var jwa = require_jwa();
    var Stream4 = __require("stream");
    var toString = require_tostring();
    var util4 = __require("util");
    var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;
    function isObject3(thing) {
      return Object.prototype.toString.call(thing) === "[object Object]";
    }
    __name(isObject3, "isObject");
    function safeJsonParse2(thing) {
      if (isObject3(thing))
        return thing;
      try {
        return JSON.parse(thing);
      } catch (e2) {
        return void 0;
      }
    }
    __name(safeJsonParse2, "safeJsonParse");
    function headerFromJWS(jwsSig) {
      var encodedHeader = jwsSig.split(".", 1)[0];
      return safeJsonParse2(Buffer5.from(encodedHeader, "base64").toString("binary"));
    }
    __name(headerFromJWS, "headerFromJWS");
    function securedInputFromJWS(jwsSig) {
      return jwsSig.split(".", 2).join(".");
    }
    __name(securedInputFromJWS, "securedInputFromJWS");
    function signatureFromJWS(jwsSig) {
      return jwsSig.split(".")[2];
    }
    __name(signatureFromJWS, "signatureFromJWS");
    function payloadFromJWS(jwsSig, encoding) {
      encoding = encoding || "utf8";
      var payload = jwsSig.split(".")[1];
      return Buffer5.from(payload, "base64").toString(encoding);
    }
    __name(payloadFromJWS, "payloadFromJWS");
    function isValidJws(string) {
      return JWS_REGEX.test(string) && !!headerFromJWS(string);
    }
    __name(isValidJws, "isValidJws");
    function jwsVerify(jwsSig, algorithm, secretOrKey) {
      if (!algorithm) {
        var err = new Error("Missing algorithm parameter for jws.verify");
        err.code = "MISSING_ALGORITHM";
        throw err;
      }
      jwsSig = toString(jwsSig);
      var signature = signatureFromJWS(jwsSig);
      var securedInput = securedInputFromJWS(jwsSig);
      var algo = jwa(algorithm);
      return algo.verify(securedInput, signature, secretOrKey);
    }
    __name(jwsVerify, "jwsVerify");
    function jwsDecode(jwsSig, opts) {
      opts = opts || {};
      jwsSig = toString(jwsSig);
      if (!isValidJws(jwsSig))
        return null;
      var header = headerFromJWS(jwsSig);
      if (!header)
        return null;
      var payload = payloadFromJWS(jwsSig);
      if (header.typ === "JWT" || opts.json)
        payload = JSON.parse(payload, opts.encoding);
      return {
        header,
        payload,
        signature: signatureFromJWS(jwsSig)
      };
    }
    __name(jwsDecode, "jwsDecode");
    function VerifyStream(opts) {
      opts = opts || {};
      var secretOrKey = opts.secret || opts.publicKey || opts.key;
      var secretStream = new DataStream(secretOrKey);
      this.readable = true;
      this.algorithm = opts.algorithm;
      this.encoding = opts.encoding;
      this.secret = this.publicKey = this.key = secretStream;
      this.signature = new DataStream(opts.signature);
      this.secret.once("close", function() {
        if (!this.signature.writable && this.readable)
          this.verify();
      }.bind(this));
      this.signature.once("close", function() {
        if (!this.secret.writable && this.readable)
          this.verify();
      }.bind(this));
    }
    __name(VerifyStream, "VerifyStream");
    util4.inherits(VerifyStream, Stream4);
    VerifyStream.prototype.verify = /* @__PURE__ */ __name(function verify() {
      try {
        var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer);
        var obj = jwsDecode(this.signature.buffer, this.encoding);
        this.emit("done", valid, obj);
        this.emit("data", valid);
        this.emit("end");
        this.readable = false;
        return valid;
      } catch (e2) {
        this.readable = false;
        this.emit("error", e2);
        this.emit("close");
      }
    }, "verify");
    VerifyStream.decode = jwsDecode;
    VerifyStream.isValid = isValidJws;
    VerifyStream.verify = jwsVerify;
    module2.exports = VerifyStream;
  }
});

// node_modules/jws/index.js
var require_jws = __commonJS({
  "node_modules/jws/index.js"(exports2) {
    init_esbuild_shims();
    var SignStream = require_sign_stream();
    var VerifyStream = require_verify_stream();
    var ALGORITHMS = [
      "HS256",
      "HS384",
      "HS512",
      "RS256",
      "RS384",
      "RS512",
      "PS256",
      "PS384",
      "PS512",
      "ES256",
      "ES384",
      "ES512"
    ];
    exports2.ALGORITHMS = ALGORITHMS;
    exports2.sign = SignStream.sign;
    exports2.verify = VerifyStream.verify;
    exports2.decode = VerifyStream.decode;
    exports2.isValid = VerifyStream.isValid;
    exports2.createSign = /* @__PURE__ */ __name(function createSign(opts) {
      return new SignStream(opts);
    }, "createSign");
    exports2.createVerify = /* @__PURE__ */ __name(function createVerify(opts) {
      return new VerifyStream(opts);
    }, "createVerify");
  }
});

// node_modules/gtoken/build/src/index.js
var require_src5 = __commonJS({
  "node_modules/gtoken/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __classPrivateFieldGet4 = exports2 && exports2.__classPrivateFieldGet || function(receiver, state, kind, f) {
      if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    };
    var __classPrivateFieldSet3 = exports2 && exports2.__classPrivateFieldSet || function(receiver, state, value, kind, f) {
      if (kind === "m") throw new TypeError("Private method is not writable");
      if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
      if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
      return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
    };
    var _GoogleToken_instances;
    var _GoogleToken_inFlightRequest;
    var _GoogleToken_getTokenAsync;
    var _GoogleToken_getTokenAsyncInner;
    var _GoogleToken_ensureEmail;
    var _GoogleToken_revokeTokenAsync;
    var _GoogleToken_configure;
    var _GoogleToken_requestToken;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.GoogleToken = void 0;
    var fs95 = __require("fs");
    var gaxios_1 = require_src2();
    var jws = require_jws();
    var path108 = __require("path");
    var util_1 = __require("util");
    var readFile11 = fs95.readFile ? (0, util_1.promisify)(fs95.readFile) : async () => {
      throw new ErrorWithCode("use key rather than keyFile.", "MISSING_CREDENTIALS");
    };
    var GOOGLE_TOKEN_URL = "https://www.googleapis.com/oauth2/v4/token";
    var GOOGLE_REVOKE_TOKEN_URL = "https://accounts.google.com/o/oauth2/revoke?token=";
    var ErrorWithCode = class extends Error {
      static {
        __name(this, "ErrorWithCode");
      }
      constructor(message, code2) {
        super(message);
        this.code = code2;
      }
    };
    var GoogleToken = class {
      static {
        __name(this, "GoogleToken");
      }
      get accessToken() {
        return this.rawToken ? this.rawToken.access_token : void 0;
      }
      get idToken() {
        return this.rawToken ? this.rawToken.id_token : void 0;
      }
      get tokenType() {
        return this.rawToken ? this.rawToken.token_type : void 0;
      }
      get refreshToken() {
        return this.rawToken ? this.rawToken.refresh_token : void 0;
      }
      /**
       * Create a GoogleToken.
       *
       * @param options  Configuration object.
       */
      constructor(options2) {
        _GoogleToken_instances.add(this);
        this.transporter = {
          request: /* @__PURE__ */ __name((opts) => (0, gaxios_1.request)(opts), "request")
        };
        _GoogleToken_inFlightRequest.set(this, void 0);
        __classPrivateFieldGet4(this, _GoogleToken_instances, "m", _GoogleToken_configure).call(this, options2);
      }
      /**
       * Returns whether the token has expired.
       *
       * @return true if the token has expired, false otherwise.
       */
      hasExpired() {
        const now = (/* @__PURE__ */ new Date()).getTime();
        if (this.rawToken && this.expiresAt) {
          return now >= this.expiresAt;
        } else {
          return true;
        }
      }
      /**
       * Returns whether the token will expire within eagerRefreshThresholdMillis
       *
       * @return true if the token will be expired within eagerRefreshThresholdMillis, false otherwise.
       */
      isTokenExpiring() {
        var _a6;
        const now = (/* @__PURE__ */ new Date()).getTime();
        const eagerRefreshThresholdMillis = (_a6 = this.eagerRefreshThresholdMillis) !== null && _a6 !== void 0 ? _a6 : 0;
        if (this.rawToken && this.expiresAt) {
          return this.expiresAt <= now + eagerRefreshThresholdMillis;
        } else {
          return true;
        }
      }
      getToken(callback, opts = {}) {
        if (typeof callback === "object") {
          opts = callback;
          callback = void 0;
        }
        opts = Object.assign({
          forceRefresh: false
        }, opts);
        if (callback) {
          const cb = callback;
          __classPrivateFieldGet4(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsync).call(this, opts).then((t2) => cb(null, t2), callback);
          return;
        }
        return __classPrivateFieldGet4(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsync).call(this, opts);
      }
      /**
       * Given a keyFile, extract the key and client email if available
       * @param keyFile Path to a json, pem, or p12 file that contains the key.
       * @returns an object with privateKey and clientEmail properties
       */
      async getCredentials(keyFile) {
        const ext2 = path108.extname(keyFile);
        switch (ext2) {
          case ".json": {
            const key = await readFile11(keyFile, "utf8");
            const body = JSON.parse(key);
            const privateKey = body.private_key;
            const clientEmail = body.client_email;
            if (!privateKey || !clientEmail) {
              throw new ErrorWithCode("private_key and client_email are required.", "MISSING_CREDENTIALS");
            }
            return { privateKey, clientEmail };
          }
          case ".der":
          case ".crt":
          case ".pem": {
            const privateKey = await readFile11(keyFile, "utf8");
            return { privateKey };
          }
          case ".p12":
          case ".pfx": {
            throw new ErrorWithCode("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.", "UNKNOWN_CERTIFICATE_TYPE");
          }
          default:
            throw new ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.", "UNKNOWN_CERTIFICATE_TYPE");
        }
      }
      revokeToken(callback) {
        if (callback) {
          __classPrivateFieldGet4(this, _GoogleToken_instances, "m", _GoogleToken_revokeTokenAsync).call(this).then(() => callback(), callback);
          return;
        }
        return __classPrivateFieldGet4(this, _GoogleToken_instances, "m", _GoogleToken_revokeTokenAsync).call(this);
      }
    };
    exports2.GoogleToken = GoogleToken;
    _GoogleToken_inFlightRequest = /* @__PURE__ */ new WeakMap(), _GoogleToken_instances = /* @__PURE__ */ new WeakSet(), _GoogleToken_getTokenAsync = /* @__PURE__ */ __name(async function _GoogleToken_getTokenAsync2(opts) {
      if (__classPrivateFieldGet4(this, _GoogleToken_inFlightRequest, "f") && !opts.forceRefresh) {
        return __classPrivateFieldGet4(this, _GoogleToken_inFlightRequest, "f");
      }
      try {
        return await __classPrivateFieldSet3(this, _GoogleToken_inFlightRequest, __classPrivateFieldGet4(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsyncInner).call(this, opts), "f");
      } finally {
        __classPrivateFieldSet3(this, _GoogleToken_inFlightRequest, void 0, "f");
      }
    }, "_GoogleToken_getTokenAsync"), _GoogleToken_getTokenAsyncInner = /* @__PURE__ */ __name(async function _GoogleToken_getTokenAsyncInner2(opts) {
      if (this.isTokenExpiring() === false && opts.forceRefresh === false) {
        return Promise.resolve(this.rawToken);
      }
      if (!this.key && !this.keyFile) {
        throw new Error("No key or keyFile set.");
      }
      if (!this.key && this.keyFile) {
        const creds = await this.getCredentials(this.keyFile);
        this.key = creds.privateKey;
        this.iss = creds.clientEmail || this.iss;
        if (!creds.clientEmail) {
          __classPrivateFieldGet4(this, _GoogleToken_instances, "m", _GoogleToken_ensureEmail).call(this);
        }
      }
      return __classPrivateFieldGet4(this, _GoogleToken_instances, "m", _GoogleToken_requestToken).call(this);
    }, "_GoogleToken_getTokenAsyncInner"), _GoogleToken_ensureEmail = /* @__PURE__ */ __name(function _GoogleToken_ensureEmail2() {
      if (!this.iss) {
        throw new ErrorWithCode("email is required.", "MISSING_CREDENTIALS");
      }
    }, "_GoogleToken_ensureEmail"), _GoogleToken_revokeTokenAsync = /* @__PURE__ */ __name(async function _GoogleToken_revokeTokenAsync2() {
      if (!this.accessToken) {
        throw new Error("No token to revoke.");
      }
      const url2 = GOOGLE_REVOKE_TOKEN_URL + this.accessToken;
      await this.transporter.request({
        url: url2,
        retry: true
      });
      __classPrivateFieldGet4(this, _GoogleToken_instances, "m", _GoogleToken_configure).call(this, {
        email: this.iss,
        sub: this.sub,
        key: this.key,
        keyFile: this.keyFile,
        scope: this.scope,
        additionalClaims: this.additionalClaims
      });
    }, "_GoogleToken_revokeTokenAsync"), _GoogleToken_configure = /* @__PURE__ */ __name(function _GoogleToken_configure2(options2 = {}) {
      this.keyFile = options2.keyFile;
      this.key = options2.key;
      this.rawToken = void 0;
      this.iss = options2.email || options2.iss;
      this.sub = options2.sub;
      this.additionalClaims = options2.additionalClaims;
      if (typeof options2.scope === "object") {
        this.scope = options2.scope.join(" ");
      } else {
        this.scope = options2.scope;
      }
      this.eagerRefreshThresholdMillis = options2.eagerRefreshThresholdMillis;
      if (options2.transporter) {
        this.transporter = options2.transporter;
      }
    }, "_GoogleToken_configure"), _GoogleToken_requestToken = /**
     * Request the token from Google.
     */
    /* @__PURE__ */ __name(async function _GoogleToken_requestToken2() {
      var _a6, _b2;
      const iat = Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3);
      const additionalClaims = this.additionalClaims || {};
      const payload = Object.assign({
        iss: this.iss,
        scope: this.scope,
        aud: GOOGLE_TOKEN_URL,
        exp: iat + 3600,
        iat,
        sub: this.sub
      }, additionalClaims);
      const signedJWT = jws.sign({
        header: { alg: "RS256" },
        payload,
        secret: this.key
      });
      try {
        const r3 = await this.transporter.request({
          method: "POST",
          url: GOOGLE_TOKEN_URL,
          data: {
            grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
            assertion: signedJWT
          },
          headers: { "Content-Type": "application/x-www-form-urlencoded" },
          responseType: "json",
          retryConfig: {
            httpMethodsToRetry: ["POST"]
          }
        });
        this.rawToken = r3.data;
        this.expiresAt = r3.data.expires_in === null || r3.data.expires_in === void 0 ? void 0 : (iat + r3.data.expires_in) * 1e3;
        return this.rawToken;
      } catch (e2) {
        this.rawToken = void 0;
        this.tokenExpires = void 0;
        const body = e2.response && ((_a6 = e2.response) === null || _a6 === void 0 ? void 0 : _a6.data) ? (_b2 = e2.response) === null || _b2 === void 0 ? void 0 : _b2.data : {};
        if (body.error) {
          const desc2 = body.error_description ? `: ${body.error_description}` : "";
          e2.message = `${body.error}${desc2}`;
        }
        throw e2;
      }
    }, "_GoogleToken_requestToken");
  }
});

// node_modules/google-auth-library/build/src/auth/jwtaccess.js
var require_jwtaccess = __commonJS({
  "node_modules/google-auth-library/build/src/auth/jwtaccess.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.JWTAccess = void 0;
    var jws = require_jws();
    var util_1 = require_util8();
    var DEFAULT_HEADER = {
      alg: "RS256",
      typ: "JWT"
    };
    var JWTAccess = class _JWTAccess {
      static {
        __name(this, "JWTAccess");
      }
      /**
       * JWTAccess service account credentials.
       *
       * Create a new access token by using the credential to create a new JWT token
       * that's recognized as the access token.
       *
       * @param email the service account email address.
       * @param key the private key that will be used to sign the token.
       * @param keyId the ID of the private key used to sign the token.
       */
      constructor(email, key, keyId, eagerRefreshThresholdMillis) {
        this.cache = new util_1.LRUCache({
          capacity: 500,
          maxAge: 60 * 60 * 1e3
        });
        this.email = email;
        this.key = key;
        this.keyId = keyId;
        this.eagerRefreshThresholdMillis = eagerRefreshThresholdMillis !== null && eagerRefreshThresholdMillis !== void 0 ? eagerRefreshThresholdMillis : 5 * 60 * 1e3;
      }
      /**
       * Ensures that we're caching a key appropriately, giving precedence to scopes vs. url
       *
       * @param url The URI being authorized.
       * @param scopes The scope or scopes being authorized
       * @returns A string that returns the cached key.
       */
      getCachedKey(url2, scopes) {
        let cacheKey = url2;
        if (scopes && Array.isArray(scopes) && scopes.length) {
          cacheKey = url2 ? `${url2}_${scopes.join("_")}` : `${scopes.join("_")}`;
        } else if (typeof scopes === "string") {
          cacheKey = url2 ? `${url2}_${scopes}` : scopes;
        }
        if (!cacheKey) {
          throw Error("Scopes or url must be provided");
        }
        return cacheKey;
      }
      /**
       * Get a non-expired access token, after refreshing if necessary.
       *
       * @param url The URI being authorized.
       * @param additionalClaims An object with a set of additional claims to
       * include in the payload.
       * @returns An object that includes the authorization header.
       */
      getRequestHeaders(url2, additionalClaims, scopes) {
        const key = this.getCachedKey(url2, scopes);
        const cachedToken = this.cache.get(key);
        const now = Date.now();
        if (cachedToken && cachedToken.expiration - now > this.eagerRefreshThresholdMillis) {
          return cachedToken.headers;
        }
        const iat = Math.floor(Date.now() / 1e3);
        const exp = _JWTAccess.getExpirationTime(iat);
        let defaultClaims;
        if (Array.isArray(scopes)) {
          scopes = scopes.join(" ");
        }
        if (scopes) {
          defaultClaims = {
            iss: this.email,
            sub: this.email,
            scope: scopes,
            exp,
            iat
          };
        } else {
          defaultClaims = {
            iss: this.email,
            sub: this.email,
            aud: url2,
            exp,
            iat
          };
        }
        if (additionalClaims) {
          for (const claim in defaultClaims) {
            if (additionalClaims[claim]) {
              throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`);
            }
          }
        }
        const header = this.keyId ? { ...DEFAULT_HEADER, kid: this.keyId } : DEFAULT_HEADER;
        const payload = Object.assign(defaultClaims, additionalClaims);
        const signedJWT = jws.sign({ header, payload, secret: this.key });
        const headers = { Authorization: `Bearer ${signedJWT}` };
        this.cache.set(key, {
          expiration: exp * 1e3,
          headers
        });
        return headers;
      }
      /**
       * Returns an expiration time for the JWT token.
       *
       * @param iat The issued at time for the JWT.
       * @returns An expiration time for the JWT.
       */
      static getExpirationTime(iat) {
        const exp = iat + 3600;
        return exp;
      }
      /**
       * Create a JWTAccess credentials instance using the given input options.
       * @param json The input object.
       */
      fromJSON(json2) {
        if (!json2) {
          throw new Error("Must pass in a JSON object containing the service account auth settings.");
        }
        if (!json2.client_email) {
          throw new Error("The incoming JSON object does not contain a client_email field");
        }
        if (!json2.private_key) {
          throw new Error("The incoming JSON object does not contain a private_key field");
        }
        this.email = json2.client_email;
        this.key = json2.private_key;
        this.keyId = json2.private_key_id;
        this.projectId = json2.project_id;
      }
      fromStream(inputStream, callback) {
        if (callback) {
          this.fromStreamAsync(inputStream).then(() => callback(), callback);
        } else {
          return this.fromStreamAsync(inputStream);
        }
      }
      fromStreamAsync(inputStream) {
        return new Promise((resolve24, reject) => {
          if (!inputStream) {
            reject(new Error("Must pass in a stream containing the service account auth settings."));
          }
          let s2 = "";
          inputStream.setEncoding("utf8").on("data", (chunk) => s2 += chunk).on("error", reject).on("end", () => {
            try {
              const data = JSON.parse(s2);
              this.fromJSON(data);
              resolve24();
            } catch (err) {
              reject(err);
            }
          });
        });
      }
    };
    exports2.JWTAccess = JWTAccess;
  }
});

// node_modules/google-auth-library/build/src/auth/jwtclient.js
var require_jwtclient = __commonJS({
  "node_modules/google-auth-library/build/src/auth/jwtclient.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.JWT = void 0;
    var gtoken_1 = require_src5();
    var jwtaccess_1 = require_jwtaccess();
    var oauth2client_1 = require_oauth2client();
    var authclient_1 = require_authclient();
    var JWT = class _JWT extends oauth2client_1.OAuth2Client {
      static {
        __name(this, "JWT");
      }
      constructor(optionsOrEmail, keyFile, key, scopes, subject, keyId) {
        const opts = optionsOrEmail && typeof optionsOrEmail === "object" ? optionsOrEmail : { email: optionsOrEmail, keyFile, key, keyId, scopes, subject };
        super(opts);
        this.email = opts.email;
        this.keyFile = opts.keyFile;
        this.key = opts.key;
        this.keyId = opts.keyId;
        this.scopes = opts.scopes;
        this.subject = opts.subject;
        this.additionalClaims = opts.additionalClaims;
        this.credentials = { refresh_token: "jwt-placeholder", expiry_date: 1 };
      }
      /**
       * Creates a copy of the credential with the specified scopes.
       * @param scopes List of requested scopes or a single scope.
       * @return The cloned instance.
       */
      createScoped(scopes) {
        const jwt = new _JWT(this);
        jwt.scopes = scopes;
        return jwt;
      }
      /**
       * Obtains the metadata to be sent with the request.
       *
       * @param url the URI being authorized.
       */
      async getRequestMetadataAsync(url2) {
        url2 = this.defaultServicePath ? `https://${this.defaultServicePath}/` : url2;
        const useSelfSignedJWT = !this.hasUserScopes() && url2 || this.useJWTAccessWithScope && this.hasAnyScopes() || this.universeDomain !== authclient_1.DEFAULT_UNIVERSE;
        if (this.subject && this.universeDomain !== authclient_1.DEFAULT_UNIVERSE) {
          throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${authclient_1.DEFAULT_UNIVERSE}`);
        }
        if (!this.apiKey && useSelfSignedJWT) {
          if (this.additionalClaims && this.additionalClaims.target_audience) {
            const { tokens } = await this.refreshToken();
            return {
              headers: this.addSharedMetadataHeaders({
                Authorization: `Bearer ${tokens.id_token}`
              })
            };
          } else {
            if (!this.access) {
              this.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId, this.eagerRefreshThresholdMillis);
            }
            let scopes;
            if (this.hasUserScopes()) {
              scopes = this.scopes;
            } else if (!url2) {
              scopes = this.defaultScopes;
            }
            const useScopes = this.useJWTAccessWithScope || this.universeDomain !== authclient_1.DEFAULT_UNIVERSE;
            const headers = await this.access.getRequestHeaders(
              url2 !== null && url2 !== void 0 ? url2 : void 0,
              this.additionalClaims,
              // Scopes take precedent over audience for signing,
              // so we only provide them if `useJWTAccessWithScope` is on or
              // if we are in a non-default universe
              useScopes ? scopes : void 0
            );
            return { headers: this.addSharedMetadataHeaders(headers) };
          }
        } else if (this.hasAnyScopes() || this.apiKey) {
          return super.getRequestMetadataAsync(url2);
        } else {
          return { headers: {} };
        }
      }
      /**
       * Fetches an ID token.
       * @param targetAudience the audience for the fetched ID token.
       */
      async fetchIdToken(targetAudience) {
        const gtoken = new gtoken_1.GoogleToken({
          iss: this.email,
          sub: this.subject,
          scope: this.scopes || this.defaultScopes,
          keyFile: this.keyFile,
          key: this.key,
          additionalClaims: { target_audience: targetAudience },
          transporter: this.transporter
        });
        await gtoken.getToken({
          forceRefresh: true
        });
        if (!gtoken.idToken) {
          throw new Error("Unknown error: Failed to fetch ID token");
        }
        return gtoken.idToken;
      }
      /**
       * Determine if there are currently scopes available.
       */
      hasUserScopes() {
        if (!this.scopes) {
          return false;
        }
        return this.scopes.length > 0;
      }
      /**
       * Are there any default or user scopes defined.
       */
      hasAnyScopes() {
        if (this.scopes && this.scopes.length > 0)
          return true;
        if (this.defaultScopes && this.defaultScopes.length > 0)
          return true;
        return false;
      }
      authorize(callback) {
        if (callback) {
          this.authorizeAsync().then((r3) => callback(null, r3), callback);
        } else {
          return this.authorizeAsync();
        }
      }
      async authorizeAsync() {
        const result = await this.refreshToken();
        if (!result) {
          throw new Error("No result returned");
        }
        this.credentials = result.tokens;
        this.credentials.refresh_token = "jwt-placeholder";
        this.key = this.gtoken.key;
        this.email = this.gtoken.iss;
        return result.tokens;
      }
      /**
       * Refreshes the access token.
       * @param refreshToken ignored
       * @private
       */
      async refreshTokenNoCache(refreshToken) {
        const gtoken = this.createGToken();
        const token2 = await gtoken.getToken({
          forceRefresh: this.isTokenExpiring()
        });
        const tokens = {
          access_token: token2.access_token,
          token_type: "Bearer",
          expiry_date: gtoken.expiresAt,
          id_token: gtoken.idToken
        };
        this.emit("tokens", tokens);
        return { res: null, tokens };
      }
      /**
       * Create a gToken if it doesn't already exist.
       */
      createGToken() {
        if (!this.gtoken) {
          this.gtoken = new gtoken_1.GoogleToken({
            iss: this.email,
            sub: this.subject,
            scope: this.scopes || this.defaultScopes,
            keyFile: this.keyFile,
            key: this.key,
            additionalClaims: this.additionalClaims,
            transporter: this.transporter
          });
        }
        return this.gtoken;
      }
      /**
       * Create a JWT credentials instance using the given input options.
       * @param json The input object.
       *
       * @remarks
       *
       * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}.
       */
      fromJSON(json2) {
        if (!json2) {
          throw new Error("Must pass in a JSON object containing the service account auth settings.");
        }
        if (!json2.client_email) {
          throw new Error("The incoming JSON object does not contain a client_email field");
        }
        if (!json2.private_key) {
          throw new Error("The incoming JSON object does not contain a private_key field");
        }
        this.email = json2.client_email;
        this.key = json2.private_key;
        this.keyId = json2.private_key_id;
        this.projectId = json2.project_id;
        this.quotaProjectId = json2.quota_project_id;
        this.universeDomain = json2.universe_domain || this.universeDomain;
      }
      fromStream(inputStream, callback) {
        if (callback) {
          this.fromStreamAsync(inputStream).then(() => callback(), callback);
        } else {
          return this.fromStreamAsync(inputStream);
        }
      }
      fromStreamAsync(inputStream) {
        return new Promise((resolve24, reject) => {
          if (!inputStream) {
            throw new Error("Must pass in a stream containing the service account auth settings.");
          }
          let s2 = "";
          inputStream.setEncoding("utf8").on("error", reject).on("data", (chunk) => s2 += chunk).on("end", () => {
            try {
              const data = JSON.parse(s2);
              this.fromJSON(data);
              resolve24();
            } catch (e2) {
              reject(e2);
            }
          });
        });
      }
      /**
       * Creates a JWT credentials instance using an API Key for authentication.
       * @param apiKey The API Key in string form.
       */
      fromAPIKey(apiKey) {
        if (typeof apiKey !== "string") {
          throw new Error("Must provide an API Key string.");
        }
        this.apiKey = apiKey;
      }
      /**
       * Using the key or keyFile on the JWT client, obtain an object that contains
       * the key and the client email.
       */
      async getCredentials() {
        if (this.key) {
          return { private_key: this.key, client_email: this.email };
        } else if (this.keyFile) {
          const gtoken = this.createGToken();
          const creds = await gtoken.getCredentials(this.keyFile);
          return { private_key: creds.privateKey, client_email: creds.clientEmail };
        }
        throw new Error("A key or a keyFile must be provided to getCredentials.");
      }
    };
    exports2.JWT = JWT;
  }
});

// node_modules/google-auth-library/build/src/auth/refreshclient.js
var require_refreshclient = __commonJS({
  "node_modules/google-auth-library/build/src/auth/refreshclient.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.UserRefreshClient = exports2.USER_REFRESH_ACCOUNT_TYPE = void 0;
    var oauth2client_1 = require_oauth2client();
    var querystring_1 = __require("querystring");
    exports2.USER_REFRESH_ACCOUNT_TYPE = "authorized_user";
    var UserRefreshClient = class _UserRefreshClient extends oauth2client_1.OAuth2Client {
      static {
        __name(this, "UserRefreshClient");
      }
      constructor(optionsOrClientId, clientSecret, refreshToken, eagerRefreshThresholdMillis, forceRefreshOnFailure) {
        const opts = optionsOrClientId && typeof optionsOrClientId === "object" ? optionsOrClientId : {
          clientId: optionsOrClientId,
          clientSecret,
          refreshToken,
          eagerRefreshThresholdMillis,
          forceRefreshOnFailure
        };
        super(opts);
        this._refreshToken = opts.refreshToken;
        this.credentials.refresh_token = opts.refreshToken;
      }
      /**
       * Refreshes the access token.
       * @param refreshToken An ignored refreshToken..
       * @param callback Optional callback.
       */
      async refreshTokenNoCache(refreshToken) {
        return super.refreshTokenNoCache(this._refreshToken);
      }
      async fetchIdToken(targetAudience) {
        const res = await this.transporter.request({
          ..._UserRefreshClient.RETRY_CONFIG,
          url: this.endpoints.oauth2TokenUrl,
          headers: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          method: "POST",
          data: (0, querystring_1.stringify)({
            client_id: this._clientId,
            client_secret: this._clientSecret,
            grant_type: "refresh_token",
            refresh_token: this._refreshToken,
            target_audience: targetAudience
          })
        });
        return res.data.id_token;
      }
      /**
       * Create a UserRefreshClient credentials instance using the given input
       * options.
       * @param json The input object.
       */
      fromJSON(json2) {
        if (!json2) {
          throw new Error("Must pass in a JSON object containing the user refresh token");
        }
        if (json2.type !== "authorized_user") {
          throw new Error('The incoming JSON object does not have the "authorized_user" type');
        }
        if (!json2.client_id) {
          throw new Error("The incoming JSON object does not contain a client_id field");
        }
        if (!json2.client_secret) {
          throw new Error("The incoming JSON object does not contain a client_secret field");
        }
        if (!json2.refresh_token) {
          throw new Error("The incoming JSON object does not contain a refresh_token field");
        }
        this._clientId = json2.client_id;
        this._clientSecret = json2.client_secret;
        this._refreshToken = json2.refresh_token;
        this.credentials.refresh_token = json2.refresh_token;
        this.quotaProjectId = json2.quota_project_id;
        this.universeDomain = json2.universe_domain || this.universeDomain;
      }
      fromStream(inputStream, callback) {
        if (callback) {
          this.fromStreamAsync(inputStream).then(() => callback(), callback);
        } else {
          return this.fromStreamAsync(inputStream);
        }
      }
      async fromStreamAsync(inputStream) {
        return new Promise((resolve24, reject) => {
          if (!inputStream) {
            return reject(new Error("Must pass in a stream containing the user refresh token."));
          }
          let s2 = "";
          inputStream.setEncoding("utf8").on("error", reject).on("data", (chunk) => s2 += chunk).on("end", () => {
            try {
              const data = JSON.parse(s2);
              this.fromJSON(data);
              return resolve24();
            } catch (err) {
              return reject(err);
            }
          });
        });
      }
      /**
       * Create a UserRefreshClient credentials instance using the given input
       * options.
       * @param json The input object.
       */
      static fromJSON(json2) {
        const client = new _UserRefreshClient();
        client.fromJSON(json2);
        return client;
      }
    };
    exports2.UserRefreshClient = UserRefreshClient;
  }
});

// node_modules/google-auth-library/build/src/auth/impersonated.js
var require_impersonated = __commonJS({
  "node_modules/google-auth-library/build/src/auth/impersonated.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Impersonated = exports2.IMPERSONATED_ACCOUNT_TYPE = void 0;
    var oauth2client_1 = require_oauth2client();
    var gaxios_1 = require_src2();
    var util_1 = require_util8();
    exports2.IMPERSONATED_ACCOUNT_TYPE = "impersonated_service_account";
    var Impersonated = class _Impersonated extends oauth2client_1.OAuth2Client {
      static {
        __name(this, "Impersonated");
      }
      /**
       * Impersonated service account credentials.
       *
       * Create a new access token by impersonating another service account.
       *
       * Impersonated Credentials allowing credentials issued to a user or
       * service account to impersonate another. The source project using
       * Impersonated Credentials must enable the "IAMCredentials" API.
       * Also, the target service account must grant the orginating principal
       * the "Service Account Token Creator" IAM role.
       *
       * @param {object} options - The configuration object.
       * @param {object} [options.sourceClient] the source credential used as to
       * acquire the impersonated credentials.
       * @param {string} [options.targetPrincipal] the service account to
       * impersonate.
       * @param {string[]} [options.delegates] the chained list of delegates
       * required to grant the final access_token. If set, the sequence of
       * identities must have "Service Account Token Creator" capability granted to
       * the preceding identity. For example, if set to [serviceAccountB,
       * serviceAccountC], the sourceCredential must have the Token Creator role on
       * serviceAccountB. serviceAccountB must have the Token Creator on
       * serviceAccountC. Finally, C must have Token Creator on target_principal.
       * If left unset, sourceCredential must have that role on targetPrincipal.
       * @param {string[]} [options.targetScopes] scopes to request during the
       * authorization grant.
       * @param {number} [options.lifetime] number of seconds the delegated
       * credential should be valid for up to 3600 seconds by default, or 43,200
       * seconds by extending the token's lifetime, see:
       * https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth
       * @param {string} [options.endpoint] api endpoint override.
       */
      constructor(options2 = {}) {
        var _a6, _b2, _c2, _d, _e, _f;
        super(options2);
        this.credentials = {
          expiry_date: 1,
          refresh_token: "impersonated-placeholder"
        };
        this.sourceClient = (_a6 = options2.sourceClient) !== null && _a6 !== void 0 ? _a6 : new oauth2client_1.OAuth2Client();
        this.targetPrincipal = (_b2 = options2.targetPrincipal) !== null && _b2 !== void 0 ? _b2 : "";
        this.delegates = (_c2 = options2.delegates) !== null && _c2 !== void 0 ? _c2 : [];
        this.targetScopes = (_d = options2.targetScopes) !== null && _d !== void 0 ? _d : [];
        this.lifetime = (_e = options2.lifetime) !== null && _e !== void 0 ? _e : 3600;
        const usingExplicitUniverseDomain = !!(0, util_1.originalOrCamelOptions)(options2).get("universe_domain");
        if (!usingExplicitUniverseDomain) {
          this.universeDomain = this.sourceClient.universeDomain;
        } else if (this.sourceClient.universeDomain !== this.universeDomain) {
          throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);
        }
        this.endpoint = (_f = options2.endpoint) !== null && _f !== void 0 ? _f : `https://iamcredentials.${this.universeDomain}`;
      }
      /**
       * Signs some bytes.
       *
       * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob Reference Documentation}
       * @param blobToSign String to sign.
       *
       * @returns A {@link SignBlobResponse} denoting the keyID and signedBlob in base64 string
       */
      async sign(blobToSign) {
        await this.sourceClient.getAccessToken();
        const name3 = `projects/-/serviceAccounts/${this.targetPrincipal}`;
        const u = `${this.endpoint}/v1/${name3}:signBlob`;
        const body = {
          delegates: this.delegates,
          payload: Buffer.from(blobToSign).toString("base64")
        };
        const res = await this.sourceClient.request({
          ..._Impersonated.RETRY_CONFIG,
          url: u,
          data: body,
          method: "POST"
        });
        return res.data;
      }
      /** The service account email to be impersonated. */
      getTargetPrincipal() {
        return this.targetPrincipal;
      }
      /**
       * Refreshes the access token.
       */
      async refreshToken() {
        var _a6, _b2, _c2, _d, _e, _f;
        try {
          await this.sourceClient.getAccessToken();
          const name3 = "projects/-/serviceAccounts/" + this.targetPrincipal;
          const u = `${this.endpoint}/v1/${name3}:generateAccessToken`;
          const body = {
            delegates: this.delegates,
            scope: this.targetScopes,
            lifetime: this.lifetime + "s"
          };
          const res = await this.sourceClient.request({
            ..._Impersonated.RETRY_CONFIG,
            url: u,
            data: body,
            method: "POST"
          });
          const tokenResponse = res.data;
          this.credentials.access_token = tokenResponse.accessToken;
          this.credentials.expiry_date = Date.parse(tokenResponse.expireTime);
          return {
            tokens: this.credentials,
            res
          };
        } catch (error) {
          if (!(error instanceof Error))
            throw error;
          let status = 0;
          let message = "";
          if (error instanceof gaxios_1.GaxiosError) {
            status = (_c2 = (_b2 = (_a6 = error === null || error === void 0 ? void 0 : error.response) === null || _a6 === void 0 ? void 0 : _a6.data) === null || _b2 === void 0 ? void 0 : _b2.error) === null || _c2 === void 0 ? void 0 : _c2.status;
            message = (_f = (_e = (_d = error === null || error === void 0 ? void 0 : error.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.error) === null || _f === void 0 ? void 0 : _f.message;
          }
          if (status && message) {
            error.message = `${status}: unable to impersonate: ${message}`;
            throw error;
          } else {
            error.message = `unable to impersonate: ${error}`;
            throw error;
          }
        }
      }
      /**
       * Generates an OpenID Connect ID token for a service account.
       *
       * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateIdToken Reference Documentation}
       *
       * @param targetAudience the audience for the fetched ID token.
       * @param options the for the request
       * @return an OpenID Connect ID token
       */
      async fetchIdToken(targetAudience, options2) {
        var _a6, _b2;
        await this.sourceClient.getAccessToken();
        const name3 = `projects/-/serviceAccounts/${this.targetPrincipal}`;
        const u = `${this.endpoint}/v1/${name3}:generateIdToken`;
        const body = {
          delegates: this.delegates,
          audience: targetAudience,
          includeEmail: (_a6 = options2 === null || options2 === void 0 ? void 0 : options2.includeEmail) !== null && _a6 !== void 0 ? _a6 : true,
          useEmailAzp: (_b2 = options2 === null || options2 === void 0 ? void 0 : options2.includeEmail) !== null && _b2 !== void 0 ? _b2 : true
        };
        const res = await this.sourceClient.request({
          ..._Impersonated.RETRY_CONFIG,
          url: u,
          data: body,
          method: "POST"
        });
        return res.data.token;
      }
    };
    exports2.Impersonated = Impersonated;
  }
});

// node_modules/google-auth-library/build/src/auth/oauth2common.js
var require_oauth2common = __commonJS({
  "node_modules/google-auth-library/build/src/auth/oauth2common.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OAuthClientAuthHandler = void 0;
    exports2.getErrorFromOAuthErrorResponse = getErrorFromOAuthErrorResponse;
    var querystring = __require("querystring");
    var crypto_1 = require_crypto3();
    var METHODS_SUPPORTING_REQUEST_BODY = ["PUT", "POST", "PATCH"];
    var OAuthClientAuthHandler = class {
      static {
        __name(this, "OAuthClientAuthHandler");
      }
      /**
       * Instantiates an OAuth client authentication handler.
       * @param clientAuthentication The client auth credentials.
       */
      constructor(clientAuthentication) {
        this.clientAuthentication = clientAuthentication;
        this.crypto = (0, crypto_1.createCrypto)();
      }
      /**
       * Applies client authentication on the OAuth request's headers or POST
       * body but does not process the request.
       * @param opts The GaxiosOptions whose headers or data are to be modified
       *   depending on the client authentication mechanism to be used.
       * @param bearerToken The optional bearer token to use for authentication.
       *   When this is used, no client authentication credentials are needed.
       */
      applyClientAuthenticationOptions(opts, bearerToken) {
        this.injectAuthenticatedHeaders(opts, bearerToken);
        if (!bearerToken) {
          this.injectAuthenticatedRequestBody(opts);
        }
      }
      /**
       * Applies client authentication on the request's header if either
       * basic authentication or bearer token authentication is selected.
       *
       * @param opts The GaxiosOptions whose headers or data are to be modified
       *   depending on the client authentication mechanism to be used.
       * @param bearerToken The optional bearer token to use for authentication.
       *   When this is used, no client authentication credentials are needed.
       */
      injectAuthenticatedHeaders(opts, bearerToken) {
        var _a6;
        if (bearerToken) {
          opts.headers = opts.headers || {};
          Object.assign(opts.headers, {
            Authorization: `Bearer ${bearerToken}}`
          });
        } else if (((_a6 = this.clientAuthentication) === null || _a6 === void 0 ? void 0 : _a6.confidentialClientType) === "basic") {
          opts.headers = opts.headers || {};
          const clientId = this.clientAuthentication.clientId;
          const clientSecret = this.clientAuthentication.clientSecret || "";
          const base64EncodedCreds = this.crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`);
          Object.assign(opts.headers, {
            Authorization: `Basic ${base64EncodedCreds}`
          });
        }
      }
      /**
       * Applies client authentication on the request's body if request-body
       * client authentication is selected.
       *
       * @param opts The GaxiosOptions whose headers or data are to be modified
       *   depending on the client authentication mechanism to be used.
       */
      injectAuthenticatedRequestBody(opts) {
        var _a6;
        if (((_a6 = this.clientAuthentication) === null || _a6 === void 0 ? void 0 : _a6.confidentialClientType) === "request-body") {
          const method = (opts.method || "GET").toUpperCase();
          if (METHODS_SUPPORTING_REQUEST_BODY.indexOf(method) !== -1) {
            let contentType;
            const headers = opts.headers || {};
            for (const key in headers) {
              if (key.toLowerCase() === "content-type" && headers[key]) {
                contentType = headers[key].toLowerCase();
                break;
              }
            }
            if (contentType === "application/x-www-form-urlencoded") {
              opts.data = opts.data || "";
              const data = querystring.parse(opts.data);
              Object.assign(data, {
                client_id: this.clientAuthentication.clientId,
                client_secret: this.clientAuthentication.clientSecret || ""
              });
              opts.data = querystring.stringify(data);
            } else if (contentType === "application/json") {
              opts.data = opts.data || {};
              Object.assign(opts.data, {
                client_id: this.clientAuthentication.clientId,
                client_secret: this.clientAuthentication.clientSecret || ""
              });
            } else {
              throw new Error(`${contentType} content-types are not supported with ${this.clientAuthentication.confidentialClientType} client authentication`);
            }
          } else {
            throw new Error(`${method} HTTP method does not support ${this.clientAuthentication.confidentialClientType} client authentication`);
          }
        }
      }
      /**
       * Retry config for Auth-related requests.
       *
       * @remarks
       *
       * This is not a part of the default {@link AuthClient.transporter transporter/gaxios}
       * config as some downstream APIs would prefer if customers explicitly enable retries,
       * such as GCS.
       */
      static get RETRY_CONFIG() {
        return {
          retry: true,
          retryConfig: {
            httpMethodsToRetry: ["GET", "PUT", "POST", "HEAD", "OPTIONS", "DELETE"]
          }
        };
      }
    };
    exports2.OAuthClientAuthHandler = OAuthClientAuthHandler;
    function getErrorFromOAuthErrorResponse(resp, err) {
      const errorCode = resp.error;
      const errorDescription = resp.error_description;
      const errorUri = resp.error_uri;
      let message = `Error code ${errorCode}`;
      if (typeof errorDescription !== "undefined") {
        message += `: ${errorDescription}`;
      }
      if (typeof errorUri !== "undefined") {
        message += ` - ${errorUri}`;
      }
      const newError = new Error(message);
      if (err) {
        const keys = Object.keys(err);
        if (err.stack) {
          keys.push("stack");
        }
        keys.forEach((key) => {
          if (key !== "message") {
            Object.defineProperty(newError, key, {
              // eslint-disable-next-line @typescript-eslint/no-explicit-any
              value: err[key],
              writable: false,
              enumerable: true
            });
          }
        });
      }
      return newError;
    }
    __name(getErrorFromOAuthErrorResponse, "getErrorFromOAuthErrorResponse");
  }
});

// node_modules/google-auth-library/build/src/auth/stscredentials.js
var require_stscredentials = __commonJS({
  "node_modules/google-auth-library/build/src/auth/stscredentials.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.StsCredentials = void 0;
    var gaxios_1 = require_src2();
    var querystring = __require("querystring");
    var transporters_1 = require_transporters();
    var oauth2common_1 = require_oauth2common();
    var StsCredentials = class _StsCredentials extends oauth2common_1.OAuthClientAuthHandler {
      static {
        __name(this, "StsCredentials");
      }
      /**
       * Initializes an STS credentials instance.
       * @param tokenExchangeEndpoint The token exchange endpoint.
       * @param clientAuthentication The client authentication credentials if
       *   available.
       */
      constructor(tokenExchangeEndpoint, clientAuthentication) {
        super(clientAuthentication);
        this.tokenExchangeEndpoint = tokenExchangeEndpoint;
        this.transporter = new transporters_1.DefaultTransporter();
      }
      /**
       * Exchanges the provided token for another type of token based on the
       * rfc8693 spec.
       * @param stsCredentialsOptions The token exchange options used to populate
       *   the token exchange request.
       * @param additionalHeaders Optional additional headers to pass along the
       *   request.
       * @param options Optional additional GCP-specific non-spec defined options
       *   to send with the request.
       *   Example: `&options=${encodeUriComponent(JSON.stringified(options))}`
       * @return A promise that resolves with the token exchange response containing
       *   the requested token and its expiration time.
       */
      async exchangeToken(stsCredentialsOptions, additionalHeaders, options2) {
        var _a6, _b2, _c2;
        const values = {
          grant_type: stsCredentialsOptions.grantType,
          resource: stsCredentialsOptions.resource,
          audience: stsCredentialsOptions.audience,
          scope: (_a6 = stsCredentialsOptions.scope) === null || _a6 === void 0 ? void 0 : _a6.join(" "),
          requested_token_type: stsCredentialsOptions.requestedTokenType,
          subject_token: stsCredentialsOptions.subjectToken,
          subject_token_type: stsCredentialsOptions.subjectTokenType,
          actor_token: (_b2 = stsCredentialsOptions.actingParty) === null || _b2 === void 0 ? void 0 : _b2.actorToken,
          actor_token_type: (_c2 = stsCredentialsOptions.actingParty) === null || _c2 === void 0 ? void 0 : _c2.actorTokenType,
          // Non-standard GCP-specific options.
          options: options2 && JSON.stringify(options2)
        };
        Object.keys(values).forEach((key) => {
          if (typeof values[key] === "undefined") {
            delete values[key];
          }
        });
        const headers = {
          "Content-Type": "application/x-www-form-urlencoded"
        };
        Object.assign(headers, additionalHeaders || {});
        const opts = {
          ..._StsCredentials.RETRY_CONFIG,
          url: this.tokenExchangeEndpoint.toString(),
          method: "POST",
          headers,
          data: querystring.stringify(values),
          responseType: "json"
        };
        this.applyClientAuthenticationOptions(opts);
        try {
          const response = await this.transporter.request(opts);
          const stsSuccessfulResponse = response.data;
          stsSuccessfulResponse.res = response;
          return stsSuccessfulResponse;
        } catch (error) {
          if (error instanceof gaxios_1.GaxiosError && error.response) {
            throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(
              error.response.data,
              // Preserve other fields from the original error.
              error
            );
          }
          throw error;
        }
      }
    };
    exports2.StsCredentials = StsCredentials;
  }
});

// node_modules/google-auth-library/build/src/auth/baseexternalclient.js
var require_baseexternalclient = __commonJS({
  "node_modules/google-auth-library/build/src/auth/baseexternalclient.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __classPrivateFieldGet4 = exports2 && exports2.__classPrivateFieldGet || function(receiver, state, kind, f) {
      if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    };
    var __classPrivateFieldSet3 = exports2 && exports2.__classPrivateFieldSet || function(receiver, state, value, kind, f) {
      if (kind === "m") throw new TypeError("Private method is not writable");
      if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
      if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
      return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
    };
    var _BaseExternalAccountClient_instances;
    var _BaseExternalAccountClient_pendingAccessToken;
    var _BaseExternalAccountClient_internalRefreshAccessTokenAsync;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BaseExternalAccountClient = exports2.DEFAULT_UNIVERSE = exports2.CLOUD_RESOURCE_MANAGER = exports2.EXTERNAL_ACCOUNT_TYPE = exports2.EXPIRATION_TIME_OFFSET = void 0;
    var stream2 = __require("stream");
    var authclient_1 = require_authclient();
    var sts = require_stscredentials();
    var util_1 = require_util8();
    var STS_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange";
    var STS_REQUEST_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
    var DEFAULT_OAUTH_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
    var DEFAULT_TOKEN_LIFESPAN = 3600;
    exports2.EXPIRATION_TIME_OFFSET = 5 * 60 * 1e3;
    exports2.EXTERNAL_ACCOUNT_TYPE = "external_account";
    exports2.CLOUD_RESOURCE_MANAGER = "https://cloudresourcemanager.googleapis.com/v1/projects/";
    var WORKFORCE_AUDIENCE_PATTERN = "//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+";
    var DEFAULT_TOKEN_URL = "https://sts.{universeDomain}/v1/token";
    var pkg2 = require_package2();
    var authclient_2 = require_authclient();
    Object.defineProperty(exports2, "DEFAULT_UNIVERSE", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return authclient_2.DEFAULT_UNIVERSE;
    }, "get") });
    var BaseExternalAccountClient = class _BaseExternalAccountClient extends authclient_1.AuthClient {
      static {
        __name(this, "BaseExternalAccountClient");
      }
      /**
       * Instantiate a BaseExternalAccountClient instance using the provided JSON
       * object loaded from an external account credentials file.
       * @param options The external account options object typically loaded
       *   from the external account JSON credential file. The camelCased options
       *   are aliases for the snake_cased options.
       * @param additionalOptions **DEPRECATED, all options are available in the
       *   `options` parameter.** Optional additional behavior customization options.
       *   These currently customize expiration threshold time and whether to retry
       *   on 401/403 API request errors.
       */
      constructor(options2, additionalOptions) {
        var _a6;
        super({ ...options2, ...additionalOptions });
        _BaseExternalAccountClient_instances.add(this);
        _BaseExternalAccountClient_pendingAccessToken.set(this, null);
        const opts = (0, util_1.originalOrCamelOptions)(options2);
        const type = opts.get("type");
        if (type && type !== exports2.EXTERNAL_ACCOUNT_TYPE) {
          throw new Error(`Expected "${exports2.EXTERNAL_ACCOUNT_TYPE}" type but received "${options2.type}"`);
        }
        const clientId = opts.get("client_id");
        const clientSecret = opts.get("client_secret");
        const tokenUrl = (_a6 = opts.get("token_url")) !== null && _a6 !== void 0 ? _a6 : DEFAULT_TOKEN_URL.replace("{universeDomain}", this.universeDomain);
        const subjectTokenType = opts.get("subject_token_type");
        const workforcePoolUserProject = opts.get("workforce_pool_user_project");
        const serviceAccountImpersonationUrl = opts.get("service_account_impersonation_url");
        const serviceAccountImpersonation = opts.get("service_account_impersonation");
        const serviceAccountImpersonationLifetime = (0, util_1.originalOrCamelOptions)(serviceAccountImpersonation).get("token_lifetime_seconds");
        this.cloudResourceManagerURL = new URL(opts.get("cloud_resource_manager_url") || `https://cloudresourcemanager.${this.universeDomain}/v1/projects/`);
        if (clientId) {
          this.clientAuth = {
            confidentialClientType: "basic",
            clientId,
            clientSecret
          };
        }
        this.stsCredential = new sts.StsCredentials(tokenUrl, this.clientAuth);
        this.scopes = opts.get("scopes") || [DEFAULT_OAUTH_SCOPE];
        this.cachedAccessToken = null;
        this.audience = opts.get("audience");
        this.subjectTokenType = subjectTokenType;
        this.workforcePoolUserProject = workforcePoolUserProject;
        const workforceAudiencePattern = new RegExp(WORKFORCE_AUDIENCE_PATTERN);
        if (this.workforcePoolUserProject && !this.audience.match(workforceAudiencePattern)) {
          throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");
        }
        this.serviceAccountImpersonationUrl = serviceAccountImpersonationUrl;
        this.serviceAccountImpersonationLifetime = serviceAccountImpersonationLifetime;
        if (this.serviceAccountImpersonationLifetime) {
          this.configLifetimeRequested = true;
        } else {
          this.configLifetimeRequested = false;
          this.serviceAccountImpersonationLifetime = DEFAULT_TOKEN_LIFESPAN;
        }
        this.projectNumber = this.getProjectNumber(this.audience);
        this.supplierContext = {
          audience: this.audience,
          subjectTokenType: this.subjectTokenType,
          transporter: this.transporter
        };
      }
      /** The service account email to be impersonated, if available. */
      getServiceAccountEmail() {
        var _a6;
        if (this.serviceAccountImpersonationUrl) {
          if (this.serviceAccountImpersonationUrl.length > 256) {
            throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);
          }
          const re2 = /serviceAccounts\/(?<email>[^:]+):generateAccessToken$/;
          const result = re2.exec(this.serviceAccountImpersonationUrl);
          return ((_a6 = result === null || result === void 0 ? void 0 : result.groups) === null || _a6 === void 0 ? void 0 : _a6.email) || null;
        }
        return null;
      }
      /**
       * Provides a mechanism to inject GCP access tokens directly.
       * When the provided credential expires, a new credential, using the
       * external account options, is retrieved.
       * @param credentials The Credentials object to set on the current client.
       */
      setCredentials(credentials) {
        super.setCredentials(credentials);
        this.cachedAccessToken = credentials;
      }
      /**
       * @return A promise that resolves with the current GCP access token
       *   response. If the current credential is expired, a new one is retrieved.
       */
      async getAccessToken() {
        if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) {
          await this.refreshAccessTokenAsync();
        }
        return {
          token: this.cachedAccessToken.access_token,
          res: this.cachedAccessToken.res
        };
      }
      /**
       * The main authentication interface. It takes an optional url which when
       * present is the endpoint being accessed, and returns a Promise which
       * resolves with authorization header fields.
       *
       * The result has the form:
       * { Authorization: 'Bearer <access_token_value>' }
       */
      async getRequestHeaders() {
        const accessTokenResponse = await this.getAccessToken();
        const headers = {
          Authorization: `Bearer ${accessTokenResponse.token}`
        };
        return this.addSharedMetadataHeaders(headers);
      }
      request(opts, callback) {
        if (callback) {
          this.requestAsync(opts).then((r3) => callback(null, r3), (e2) => {
            return callback(e2, e2.response);
          });
        } else {
          return this.requestAsync(opts);
        }
      }
      /**
       * @return A promise that resolves with the project ID corresponding to the
       *   current workload identity pool or current workforce pool if
       *   determinable. For workforce pool credential, it returns the project ID
       *   corresponding to the workforcePoolUserProject.
       *   This is introduced to match the current pattern of using the Auth
       *   library:
       *   const projectId = await auth.getProjectId();
       *   const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
       *   const res = await client.request({ url });
       *   The resource may not have permission
       *   (resourcemanager.projects.get) to call this API or the required
       *   scopes may not be selected:
       *   https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes
       */
      async getProjectId() {
        const projectNumber = this.projectNumber || this.workforcePoolUserProject;
        if (this.projectId) {
          return this.projectId;
        } else if (projectNumber) {
          const headers = await this.getRequestHeaders();
          const response = await this.transporter.request({
            ..._BaseExternalAccountClient.RETRY_CONFIG,
            headers,
            url: `${this.cloudResourceManagerURL.toString()}${projectNumber}`,
            responseType: "json"
          });
          this.projectId = response.data.projectId;
          return this.projectId;
        }
        return null;
      }
      /**
       * Authenticates the provided HTTP request, processes it and resolves with the
       * returned response.
       * @param opts The HTTP request options.
       * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure.
       * @return A promise that resolves with the successful response.
       */
      async requestAsync(opts, reAuthRetried = false) {
        let response;
        try {
          const requestHeaders = await this.getRequestHeaders();
          opts.headers = opts.headers || {};
          if (requestHeaders && requestHeaders["x-goog-user-project"]) {
            opts.headers["x-goog-user-project"] = requestHeaders["x-goog-user-project"];
          }
          if (requestHeaders && requestHeaders.Authorization) {
            opts.headers.Authorization = requestHeaders.Authorization;
          }
          response = await this.transporter.request(opts);
        } catch (e2) {
          const res = e2.response;
          if (res) {
            const statusCode = res.status;
            const isReadableStream = res.config.data instanceof stream2.Readable;
            const isAuthErr = statusCode === 401 || statusCode === 403;
            if (!reAuthRetried && isAuthErr && !isReadableStream && this.forceRefreshOnFailure) {
              await this.refreshAccessTokenAsync();
              return await this.requestAsync(opts, true);
            }
          }
          throw e2;
        }
        return response;
      }
      /**
       * Forces token refresh, even if unexpired tokens are currently cached.
       * External credentials are exchanged for GCP access tokens via the token
       * exchange endpoint and other settings provided in the client options
       * object.
       * If the service_account_impersonation_url is provided, an additional
       * step to exchange the external account GCP access token for a service
       * account impersonated token is performed.
       * @return A promise that resolves with the fresh GCP access tokens.
       */
      async refreshAccessTokenAsync() {
        __classPrivateFieldSet3(this, _BaseExternalAccountClient_pendingAccessToken, __classPrivateFieldGet4(this, _BaseExternalAccountClient_pendingAccessToken, "f") || __classPrivateFieldGet4(this, _BaseExternalAccountClient_instances, "m", _BaseExternalAccountClient_internalRefreshAccessTokenAsync).call(this), "f");
        try {
          return await __classPrivateFieldGet4(this, _BaseExternalAccountClient_pendingAccessToken, "f");
        } finally {
          __classPrivateFieldSet3(this, _BaseExternalAccountClient_pendingAccessToken, null, "f");
        }
      }
      /**
       * Returns the workload identity pool project number if it is determinable
       * from the audience resource name.
       * @param audience The STS audience used to determine the project number.
       * @return The project number associated with the workload identity pool, if
       *   this can be determined from the STS audience field. Otherwise, null is
       *   returned.
       */
      getProjectNumber(audience) {
        const match2 = audience.match(/\/projects\/([^/]+)/);
        if (!match2) {
          return null;
        }
        return match2[1];
      }
      /**
       * Exchanges an external account GCP access token for a service
       * account impersonated access token using iamcredentials
       * GenerateAccessToken API.
       * @param token The access token to exchange for a service account access
       *   token.
       * @return A promise that resolves with the service account impersonated
       *   credentials response.
       */
      async getImpersonatedAccessToken(token2) {
        const opts = {
          ..._BaseExternalAccountClient.RETRY_CONFIG,
          url: this.serviceAccountImpersonationUrl,
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token2}`
          },
          data: {
            scope: this.getScopesArray(),
            lifetime: this.serviceAccountImpersonationLifetime + "s"
          },
          responseType: "json"
        };
        const response = await this.transporter.request(opts);
        const successResponse = response.data;
        return {
          access_token: successResponse.accessToken,
          // Convert from ISO format to timestamp.
          expiry_date: new Date(successResponse.expireTime).getTime(),
          res: response
        };
      }
      /**
       * Returns whether the provided credentials are expired or not.
       * If there is no expiry time, assumes the token is not expired or expiring.
       * @param accessToken The credentials to check for expiration.
       * @return Whether the credentials are expired or not.
       */
      isExpired(accessToken) {
        const now = (/* @__PURE__ */ new Date()).getTime();
        return accessToken.expiry_date ? now >= accessToken.expiry_date - this.eagerRefreshThresholdMillis : false;
      }
      /**
       * @return The list of scopes for the requested GCP access token.
       */
      getScopesArray() {
        if (typeof this.scopes === "string") {
          return [this.scopes];
        }
        return this.scopes || [DEFAULT_OAUTH_SCOPE];
      }
      getMetricsHeaderValue() {
        const nodeVersion2 = process.version.replace(/^v/, "");
        const saImpersonation = this.serviceAccountImpersonationUrl !== void 0;
        const credentialSourceType = this.credentialSourceType ? this.credentialSourceType : "unknown";
        return `gl-node/${nodeVersion2} auth/${pkg2.version} google-byoid-sdk source/${credentialSourceType} sa-impersonation/${saImpersonation} config-lifetime/${this.configLifetimeRequested}`;
      }
    };
    exports2.BaseExternalAccountClient = BaseExternalAccountClient;
    _BaseExternalAccountClient_pendingAccessToken = /* @__PURE__ */ new WeakMap(), _BaseExternalAccountClient_instances = /* @__PURE__ */ new WeakSet(), _BaseExternalAccountClient_internalRefreshAccessTokenAsync = /* @__PURE__ */ __name(async function _BaseExternalAccountClient_internalRefreshAccessTokenAsync2() {
      const subjectToken = await this.retrieveSubjectToken();
      const stsCredentialsOptions = {
        grantType: STS_GRANT_TYPE,
        audience: this.audience,
        requestedTokenType: STS_REQUEST_TOKEN_TYPE,
        subjectToken,
        subjectTokenType: this.subjectTokenType,
        // generateAccessToken requires the provided access token to have
        // scopes:
        // https://www.googleapis.com/auth/iam or
        // https://www.googleapis.com/auth/cloud-platform
        // The new service account access token scopes will match the user
        // provided ones.
        scope: this.serviceAccountImpersonationUrl ? [DEFAULT_OAUTH_SCOPE] : this.getScopesArray()
      };
      const additionalOptions = !this.clientAuth && this.workforcePoolUserProject ? { userProject: this.workforcePoolUserProject } : void 0;
      const additionalHeaders = {
        "x-goog-api-client": this.getMetricsHeaderValue()
      };
      const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, additionalHeaders, additionalOptions);
      if (this.serviceAccountImpersonationUrl) {
        this.cachedAccessToken = await this.getImpersonatedAccessToken(stsResponse.access_token);
      } else if (stsResponse.expires_in) {
        this.cachedAccessToken = {
          access_token: stsResponse.access_token,
          expiry_date: (/* @__PURE__ */ new Date()).getTime() + stsResponse.expires_in * 1e3,
          res: stsResponse.res
        };
      } else {
        this.cachedAccessToken = {
          access_token: stsResponse.access_token,
          res: stsResponse.res
        };
      }
      this.credentials = {};
      Object.assign(this.credentials, this.cachedAccessToken);
      delete this.credentials.res;
      this.emit("tokens", {
        refresh_token: null,
        expiry_date: this.cachedAccessToken.expiry_date,
        access_token: this.cachedAccessToken.access_token,
        token_type: "Bearer",
        id_token: null
      });
      return this.cachedAccessToken;
    }, "_BaseExternalAccountClient_internalRefreshAccessTokenAsync");
  }
});

// node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js
var require_filesubjecttokensupplier = __commonJS({
  "node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var _a6;
    var _b2;
    var _c2;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.FileSubjectTokenSupplier = void 0;
    var util_1 = __require("util");
    var fs95 = __require("fs");
    var readFile11 = (0, util_1.promisify)((_a6 = fs95.readFile) !== null && _a6 !== void 0 ? _a6 : () => {
    });
    var realpath2 = (0, util_1.promisify)((_b2 = fs95.realpath) !== null && _b2 !== void 0 ? _b2 : () => {
    });
    var lstat4 = (0, util_1.promisify)((_c2 = fs95.lstat) !== null && _c2 !== void 0 ? _c2 : () => {
    });
    var FileSubjectTokenSupplier = class {
      static {
        __name(this, "FileSubjectTokenSupplier");
      }
      /**
       * Instantiates a new file based subject token supplier.
       * @param opts The file subject token supplier options to build the supplier
       *   with.
       */
      constructor(opts) {
        this.filePath = opts.filePath;
        this.formatType = opts.formatType;
        this.subjectTokenFieldName = opts.subjectTokenFieldName;
      }
      /**
       * Returns the subject token stored at the file specified in the constructor.
       * @param context {@link ExternalAccountSupplierContext} from the calling
       *   {@link IdentityPoolClient}, contains the requested audience and subject
       *   token type for the external account identity. Not used.
       */
      async getSubjectToken(context2) {
        let parsedFilePath = this.filePath;
        try {
          parsedFilePath = await realpath2(parsedFilePath);
          if (!(await lstat4(parsedFilePath)).isFile()) {
            throw new Error();
          }
        } catch (err) {
          if (err instanceof Error) {
            err.message = `The file at ${parsedFilePath} does not exist, or it is not a file. ${err.message}`;
          }
          throw err;
        }
        let subjectToken;
        const rawText = await readFile11(parsedFilePath, { encoding: "utf8" });
        if (this.formatType === "text") {
          subjectToken = rawText;
        } else if (this.formatType === "json" && this.subjectTokenFieldName) {
          const json2 = JSON.parse(rawText);
          subjectToken = json2[this.subjectTokenFieldName];
        }
        if (!subjectToken) {
          throw new Error("Unable to parse the subject_token from the credential_source file");
        }
        return subjectToken;
      }
    };
    exports2.FileSubjectTokenSupplier = FileSubjectTokenSupplier;
  }
});

// node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js
var require_urlsubjecttokensupplier = __commonJS({
  "node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.UrlSubjectTokenSupplier = void 0;
    var UrlSubjectTokenSupplier = class {
      static {
        __name(this, "UrlSubjectTokenSupplier");
      }
      /**
       * Instantiates a URL subject token supplier.
       * @param opts The URL subject token supplier options to build the supplier with.
       */
      constructor(opts) {
        this.url = opts.url;
        this.formatType = opts.formatType;
        this.subjectTokenFieldName = opts.subjectTokenFieldName;
        this.headers = opts.headers;
        this.additionalGaxiosOptions = opts.additionalGaxiosOptions;
      }
      /**
       * Sends a GET request to the URL provided in the constructor and resolves
       * with the returned external subject token.
       * @param context {@link ExternalAccountSupplierContext} from the calling
       *   {@link IdentityPoolClient}, contains the requested audience and subject
       *   token type for the external account identity. Not used.
       */
      async getSubjectToken(context2) {
        const opts = {
          ...this.additionalGaxiosOptions,
          url: this.url,
          method: "GET",
          headers: this.headers,
          responseType: this.formatType
        };
        let subjectToken;
        if (this.formatType === "text") {
          const response = await context2.transporter.request(opts);
          subjectToken = response.data;
        } else if (this.formatType === "json" && this.subjectTokenFieldName) {
          const response = await context2.transporter.request(opts);
          subjectToken = response.data[this.subjectTokenFieldName];
        }
        if (!subjectToken) {
          throw new Error("Unable to parse the subject_token from the credential_source URL");
        }
        return subjectToken;
      }
    };
    exports2.UrlSubjectTokenSupplier = UrlSubjectTokenSupplier;
  }
});

// node_modules/google-auth-library/build/src/auth/identitypoolclient.js
var require_identitypoolclient = __commonJS({
  "node_modules/google-auth-library/build/src/auth/identitypoolclient.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.IdentityPoolClient = void 0;
    var baseexternalclient_1 = require_baseexternalclient();
    var util_1 = require_util8();
    var filesubjecttokensupplier_1 = require_filesubjecttokensupplier();
    var urlsubjecttokensupplier_1 = require_urlsubjecttokensupplier();
    var IdentityPoolClient = class _IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient {
      static {
        __name(this, "IdentityPoolClient");
      }
      /**
       * Instantiate an IdentityPoolClient instance using the provided JSON
       * object loaded from an external account credentials file.
       * An error is thrown if the credential is not a valid file-sourced or
       * url-sourced credential or a workforce pool user project is provided
       * with a non workforce audience.
       * @param options The external account options object typically loaded
       *   from the external account JSON credential file. The camelCased options
       *   are aliases for the snake_cased options.
       * @param additionalOptions **DEPRECATED, all options are available in the
       *   `options` parameter.** Optional additional behavior customization options.
       *   These currently customize expiration threshold time and whether to retry
       *   on 401/403 API request errors.
       */
      constructor(options2, additionalOptions) {
        super(options2, additionalOptions);
        const opts = (0, util_1.originalOrCamelOptions)(options2);
        const credentialSource = opts.get("credential_source");
        const subjectTokenSupplier = opts.get("subject_token_supplier");
        if (!credentialSource && !subjectTokenSupplier) {
          throw new Error("A credential source or subject token supplier must be specified.");
        }
        if (credentialSource && subjectTokenSupplier) {
          throw new Error("Only one of credential source or subject token supplier can be specified.");
        }
        if (subjectTokenSupplier) {
          this.subjectTokenSupplier = subjectTokenSupplier;
          this.credentialSourceType = "programmatic";
        } else {
          const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource);
          const formatOpts = (0, util_1.originalOrCamelOptions)(credentialSourceOpts.get("format"));
          const formatType = formatOpts.get("type") || "text";
          const formatSubjectTokenFieldName = formatOpts.get("subject_token_field_name");
          if (formatType !== "json" && formatType !== "text") {
            throw new Error(`Invalid credential_source format "${formatType}"`);
          }
          if (formatType === "json" && !formatSubjectTokenFieldName) {
            throw new Error("Missing subject_token_field_name for JSON credential_source format");
          }
          const file = credentialSourceOpts.get("file");
          const url2 = credentialSourceOpts.get("url");
          const headers = credentialSourceOpts.get("headers");
          if (file && url2) {
            throw new Error('No valid Identity Pool "credential_source" provided, must be either file or url.');
          } else if (file && !url2) {
            this.credentialSourceType = "file";
            this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({
              filePath: file,
              formatType,
              subjectTokenFieldName: formatSubjectTokenFieldName
            });
          } else if (!file && url2) {
            this.credentialSourceType = "url";
            this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({
              url: url2,
              formatType,
              subjectTokenFieldName: formatSubjectTokenFieldName,
              headers,
              additionalGaxiosOptions: _IdentityPoolClient.RETRY_CONFIG
            });
          } else {
            throw new Error('No valid Identity Pool "credential_source" provided, must be either file or url.');
          }
        }
      }
      /**
       * Triggered when a external subject token is needed to be exchanged for a GCP
       * access token via GCP STS endpoint. Gets a subject token by calling
       * the configured {@link SubjectTokenSupplier}
       * @return A promise that resolves with the external subject token.
       */
      async retrieveSubjectToken() {
        return this.subjectTokenSupplier.getSubjectToken(this.supplierContext);
      }
    };
    exports2.IdentityPoolClient = IdentityPoolClient;
  }
});

// node_modules/google-auth-library/build/src/auth/awsrequestsigner.js
var require_awsrequestsigner = __commonJS({
  "node_modules/google-auth-library/build/src/auth/awsrequestsigner.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AwsRequestSigner = void 0;
    var crypto_1 = require_crypto3();
    var AWS_ALGORITHM = "AWS4-HMAC-SHA256";
    var AWS_REQUEST_TYPE = "aws4_request";
    var AwsRequestSigner = class {
      static {
        __name(this, "AwsRequestSigner");
      }
      /**
       * Instantiates an AWS API request signer used to send authenticated signed
       * requests to AWS APIs based on the AWS Signature Version 4 signing process.
       * This also provides a mechanism to generate the signed request without
       * sending it.
       * @param getCredentials A mechanism to retrieve AWS security credentials
       *   when needed.
       * @param region The AWS region to use.
       */
      constructor(getCredentials, region) {
        this.getCredentials = getCredentials;
        this.region = region;
        this.crypto = (0, crypto_1.createCrypto)();
      }
      /**
       * Generates the signed request for the provided HTTP request for calling
       * an AWS API. This follows the steps described at:
       * https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html
       * @param amzOptions The AWS request options that need to be signed.
       * @return A promise that resolves with the GaxiosOptions containing the
       *   signed HTTP request parameters.
       */
      async getRequestOptions(amzOptions) {
        if (!amzOptions.url) {
          throw new Error('"url" is required in "amzOptions"');
        }
        const requestPayloadData = typeof amzOptions.data === "object" ? JSON.stringify(amzOptions.data) : amzOptions.data;
        const url2 = amzOptions.url;
        const method = amzOptions.method || "GET";
        const requestPayload = amzOptions.body || requestPayloadData;
        const additionalAmzHeaders = amzOptions.headers;
        const awsSecurityCredentials = await this.getCredentials();
        const uri = new URL(url2);
        const headerMap = await generateAuthenticationHeaderMap({
          crypto: this.crypto,
          host: uri.host,
          canonicalUri: uri.pathname,
          canonicalQuerystring: uri.search.substr(1),
          method,
          region: this.region,
          securityCredentials: awsSecurityCredentials,
          requestPayload,
          additionalAmzHeaders
        });
        const headers = Object.assign(
          // Add x-amz-date if available.
          headerMap.amzDate ? { "x-amz-date": headerMap.amzDate } : {},
          {
            Authorization: headerMap.authorizationHeader,
            host: uri.host
          },
          additionalAmzHeaders || {}
        );
        if (awsSecurityCredentials.token) {
          Object.assign(headers, {
            "x-amz-security-token": awsSecurityCredentials.token
          });
        }
        const awsSignedReq = {
          url: url2,
          method,
          headers
        };
        if (typeof requestPayload !== "undefined") {
          awsSignedReq.body = requestPayload;
        }
        return awsSignedReq;
      }
    };
    exports2.AwsRequestSigner = AwsRequestSigner;
    async function sign(crypto18, key, msg) {
      return await crypto18.signWithHmacSha256(key, msg);
    }
    __name(sign, "sign");
    async function getSigningKey(crypto18, key, dateStamp, region, serviceName) {
      const kDate = await sign(crypto18, `AWS4${key}`, dateStamp);
      const kRegion = await sign(crypto18, kDate, region);
      const kService = await sign(crypto18, kRegion, serviceName);
      const kSigning = await sign(crypto18, kService, "aws4_request");
      return kSigning;
    }
    __name(getSigningKey, "getSigningKey");
    async function generateAuthenticationHeaderMap(options2) {
      const additionalAmzHeaders = options2.additionalAmzHeaders || {};
      const requestPayload = options2.requestPayload || "";
      const serviceName = options2.host.split(".")[0];
      const now = /* @__PURE__ */ new Date();
      const amzDate = now.toISOString().replace(/[-:]/g, "").replace(/\.[0-9]+/, "");
      const dateStamp = now.toISOString().replace(/[-]/g, "").replace(/T.*/, "");
      const reformattedAdditionalAmzHeaders = {};
      Object.keys(additionalAmzHeaders).forEach((key) => {
        reformattedAdditionalAmzHeaders[key.toLowerCase()] = additionalAmzHeaders[key];
      });
      if (options2.securityCredentials.token) {
        reformattedAdditionalAmzHeaders["x-amz-security-token"] = options2.securityCredentials.token;
      }
      const amzHeaders = Object.assign(
        {
          host: options2.host
        },
        // Previously the date was not fixed with x-amz- and could be provided manually.
        // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req
        reformattedAdditionalAmzHeaders.date ? {} : { "x-amz-date": amzDate },
        reformattedAdditionalAmzHeaders
      );
      let canonicalHeaders = "";
      const signedHeadersList = Object.keys(amzHeaders).sort();
      signedHeadersList.forEach((key) => {
        canonicalHeaders += `${key}:${amzHeaders[key]}
`;
      });
      const signedHeaders = signedHeadersList.join(";");
      const payloadHash = await options2.crypto.sha256DigestHex(requestPayload);
      const canonicalRequest = `${options2.method}
${options2.canonicalUri}
${options2.canonicalQuerystring}
${canonicalHeaders}
${signedHeaders}
${payloadHash}`;
      const credentialScope = `${dateStamp}/${options2.region}/${serviceName}/${AWS_REQUEST_TYPE}`;
      const stringToSign = `${AWS_ALGORITHM}
${amzDate}
${credentialScope}
` + await options2.crypto.sha256DigestHex(canonicalRequest);
      const signingKey = await getSigningKey(options2.crypto, options2.securityCredentials.secretAccessKey, dateStamp, options2.region, serviceName);
      const signature = await sign(options2.crypto, signingKey, stringToSign);
      const authorizationHeader = `${AWS_ALGORITHM} Credential=${options2.securityCredentials.accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${(0, crypto_1.fromArrayBufferToHex)(signature)}`;
      return {
        // Do not return x-amz-date if date is available.
        amzDate: reformattedAdditionalAmzHeaders.date ? void 0 : amzDate,
        authorizationHeader,
        canonicalQuerystring: options2.canonicalQuerystring
      };
    }
    __name(generateAuthenticationHeaderMap, "generateAuthenticationHeaderMap");
  }
});

// node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js
var require_defaultawssecuritycredentialssupplier = __commonJS({
  "node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __classPrivateFieldGet4 = exports2 && exports2.__classPrivateFieldGet || function(receiver, state, kind, f) {
      if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    };
    var _DefaultAwsSecurityCredentialsSupplier_instances;
    var _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken;
    var _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName;
    var _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials;
    var _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get;
    var _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DefaultAwsSecurityCredentialsSupplier = void 0;
    var DefaultAwsSecurityCredentialsSupplier = class {
      static {
        __name(this, "DefaultAwsSecurityCredentialsSupplier");
      }
      /**
       * Instantiates a new DefaultAwsSecurityCredentialsSupplier using information
       * from the credential_source stored in the ADC file.
       * @param opts The default aws security credentials supplier options object to
       *   build the supplier with.
       */
      constructor(opts) {
        _DefaultAwsSecurityCredentialsSupplier_instances.add(this);
        this.regionUrl = opts.regionUrl;
        this.securityCredentialsUrl = opts.securityCredentialsUrl;
        this.imdsV2SessionTokenUrl = opts.imdsV2SessionTokenUrl;
        this.additionalGaxiosOptions = opts.additionalGaxiosOptions;
      }
      /**
       * Returns the active AWS region. This first checks to see if the region
       * is available as an environment variable. If it is not, then the supplier
       * will call the region URL.
       * @param context {@link ExternalAccountSupplierContext} from the calling
       *   {@link AwsClient}, contains the requested audience and subject token type
       *   for the external account identity.
       * @return A promise that resolves with the AWS region string.
       */
      async getAwsRegion(context2) {
        if (__classPrivateFieldGet4(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get)) {
          return __classPrivateFieldGet4(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get);
        }
        const metadataHeaders = {};
        if (!__classPrivateFieldGet4(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get) && this.imdsV2SessionTokenUrl) {
          metadataHeaders["x-aws-ec2-metadata-token"] = await __classPrivateFieldGet4(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken).call(this, context2.transporter);
        }
        if (!this.regionUrl) {
          throw new Error('Unable to determine AWS region due to missing "options.credential_source.region_url"');
        }
        const opts = {
          ...this.additionalGaxiosOptions,
          url: this.regionUrl,
          method: "GET",
          responseType: "text",
          headers: metadataHeaders
        };
        const response = await context2.transporter.request(opts);
        return response.data.substr(0, response.data.length - 1);
      }
      /**
       * Returns AWS security credentials. This first checks to see if the credentials
       * is available as environment variables. If it is not, then the supplier
       * will call the security credentials URL.
       * @param context {@link ExternalAccountSupplierContext} from the calling
       *   {@link AwsClient}, contains the requested audience and subject token type
       *   for the external account identity.
       * @return A promise that resolves with the AWS security credentials.
       */
      async getAwsSecurityCredentials(context2) {
        if (__classPrivateFieldGet4(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get)) {
          return __classPrivateFieldGet4(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get);
        }
        const metadataHeaders = {};
        if (this.imdsV2SessionTokenUrl) {
          metadataHeaders["x-aws-ec2-metadata-token"] = await __classPrivateFieldGet4(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken).call(this, context2.transporter);
        }
        const roleName = await __classPrivateFieldGet4(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName).call(this, metadataHeaders, context2.transporter);
        const awsCreds = await __classPrivateFieldGet4(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials).call(this, roleName, metadataHeaders, context2.transporter);
        return {
          accessKeyId: awsCreds.AccessKeyId,
          secretAccessKey: awsCreds.SecretAccessKey,
          token: awsCreds.Token
        };
      }
    };
    exports2.DefaultAwsSecurityCredentialsSupplier = DefaultAwsSecurityCredentialsSupplier;
    _DefaultAwsSecurityCredentialsSupplier_instances = /* @__PURE__ */ new WeakSet(), _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken = /**
     * @param transporter The transporter to use for requests.
     * @return A promise that resolves with the IMDSv2 Session Token.
     */
    /* @__PURE__ */ __name(async function _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken2(transporter) {
      const opts = {
        ...this.additionalGaxiosOptions,
        url: this.imdsV2SessionTokenUrl,
        method: "PUT",
        responseType: "text",
        headers: { "x-aws-ec2-metadata-token-ttl-seconds": "300" }
      };
      const response = await transporter.request(opts);
      return response.data;
    }, "_DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken"), _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName = /**
     * @param headers The headers to be used in the metadata request.
     * @param transporter The transporter to use for requests.
     * @return A promise that resolves with the assigned role to the current
     *   AWS VM. This is needed for calling the security-credentials endpoint.
     */
    /* @__PURE__ */ __name(async function _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName2(headers, transporter) {
      if (!this.securityCredentialsUrl) {
        throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');
      }
      const opts = {
        ...this.additionalGaxiosOptions,
        url: this.securityCredentialsUrl,
        method: "GET",
        responseType: "text",
        headers
      };
      const response = await transporter.request(opts);
      return response.data;
    }, "_DefaultAwsSecurityCredentialsSupplier_getAwsRoleName"), _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials = /**
     * Retrieves the temporary AWS credentials by calling the security-credentials
     * endpoint as specified in the `credential_source` object.
     * @param roleName The role attached to the current VM.
     * @param headers The headers to be used in the metadata request.
     * @param transporter The transporter to use for requests.
     * @return A promise that resolves with the temporary AWS credentials
     *   needed for creating the GetCallerIdentity signed request.
     */
    /* @__PURE__ */ __name(async function _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials2(roleName, headers, transporter) {
      const response = await transporter.request({
        ...this.additionalGaxiosOptions,
        url: `${this.securityCredentialsUrl}/${roleName}`,
        responseType: "json",
        headers
      });
      return response.data;
    }, "_DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials"), _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get = /* @__PURE__ */ __name(function _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get2() {
      return process.env["AWS_REGION"] || process.env["AWS_DEFAULT_REGION"] || null;
    }, "_DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get"), _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get = /* @__PURE__ */ __name(function _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get2() {
      if (process.env["AWS_ACCESS_KEY_ID"] && process.env["AWS_SECRET_ACCESS_KEY"]) {
        return {
          accessKeyId: process.env["AWS_ACCESS_KEY_ID"],
          secretAccessKey: process.env["AWS_SECRET_ACCESS_KEY"],
          token: process.env["AWS_SESSION_TOKEN"]
        };
      }
      return null;
    }, "_DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get");
  }
});

// node_modules/google-auth-library/build/src/auth/awsclient.js
var require_awsclient = __commonJS({
  "node_modules/google-auth-library/build/src/auth/awsclient.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __classPrivateFieldGet4 = exports2 && exports2.__classPrivateFieldGet || function(receiver, state, kind, f) {
      if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    };
    var _a6;
    var _AwsClient_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AwsClient = void 0;
    var awsrequestsigner_1 = require_awsrequestsigner();
    var baseexternalclient_1 = require_baseexternalclient();
    var defaultawssecuritycredentialssupplier_1 = require_defaultawssecuritycredentialssupplier();
    var util_1 = require_util8();
    var AwsClient = class extends baseexternalclient_1.BaseExternalAccountClient {
      static {
        __name(this, "AwsClient");
      }
      /**
       * Instantiates an AwsClient instance using the provided JSON
       * object loaded from an external account credentials file.
       * An error is thrown if the credential is not a valid AWS credential.
       * @param options The external account options object typically loaded
       *   from the external account JSON credential file.
       * @param additionalOptions **DEPRECATED, all options are available in the
       *   `options` parameter.** Optional additional behavior customization options.
       *   These currently customize expiration threshold time and whether to retry
       *   on 401/403 API request errors.
       */
      constructor(options2, additionalOptions) {
        super(options2, additionalOptions);
        const opts = (0, util_1.originalOrCamelOptions)(options2);
        const credentialSource = opts.get("credential_source");
        const awsSecurityCredentialsSupplier = opts.get("aws_security_credentials_supplier");
        if (!credentialSource && !awsSecurityCredentialsSupplier) {
          throw new Error("A credential source or AWS security credentials supplier must be specified.");
        }
        if (credentialSource && awsSecurityCredentialsSupplier) {
          throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");
        }
        if (awsSecurityCredentialsSupplier) {
          this.awsSecurityCredentialsSupplier = awsSecurityCredentialsSupplier;
          this.regionalCredVerificationUrl = __classPrivateFieldGet4(_a6, _a6, "f", _AwsClient_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL);
          this.credentialSourceType = "programmatic";
        } else {
          const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource);
          this.environmentId = credentialSourceOpts.get("environment_id");
          const regionUrl = credentialSourceOpts.get("region_url");
          const securityCredentialsUrl = credentialSourceOpts.get("url");
          const imdsV2SessionTokenUrl = credentialSourceOpts.get("imdsv2_session_token_url");
          this.awsSecurityCredentialsSupplier = new defaultawssecuritycredentialssupplier_1.DefaultAwsSecurityCredentialsSupplier({
            regionUrl,
            securityCredentialsUrl,
            imdsV2SessionTokenUrl
          });
          this.regionalCredVerificationUrl = credentialSourceOpts.get("regional_cred_verification_url");
          this.credentialSourceType = "aws";
          this.validateEnvironmentId();
        }
        this.awsRequestSigner = null;
        this.region = "";
      }
      validateEnvironmentId() {
        var _b2;
        const match2 = (_b2 = this.environmentId) === null || _b2 === void 0 ? void 0 : _b2.match(/^(aws)(\d+)$/);
        if (!match2 || !this.regionalCredVerificationUrl) {
          throw new Error('No valid AWS "credential_source" provided');
        } else if (parseInt(match2[2], 10) !== 1) {
          throw new Error(`aws version "${match2[2]}" is not supported in the current build.`);
        }
      }
      /**
       * Triggered when an external subject token is needed to be exchanged for a
       * GCP access token via GCP STS endpoint. This will call the
       * {@link AwsSecurityCredentialsSupplier} to retrieve an AWS region and AWS
       * Security Credentials, then use them to create a signed AWS STS request that
       * can be exchanged for a GCP access token.
       * @return A promise that resolves with the external subject token.
       */
      async retrieveSubjectToken() {
        if (!this.awsRequestSigner) {
          this.region = await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext);
          this.awsRequestSigner = new awsrequestsigner_1.AwsRequestSigner(async () => {
            return this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext);
          }, this.region);
        }
        const options2 = await this.awsRequestSigner.getRequestOptions({
          ..._a6.RETRY_CONFIG,
          url: this.regionalCredVerificationUrl.replace("{region}", this.region),
          method: "POST"
        });
        const reformattedHeader = [];
        const extendedHeaders = Object.assign({
          // The full, canonical resource name of the workload identity pool
          // provider, with or without the HTTPS prefix.
          // Including this header as part of the signature is recommended to
          // ensure data integrity.
          "x-goog-cloud-target-resource": this.audience
        }, options2.headers);
        for (const key in extendedHeaders) {
          reformattedHeader.push({
            key,
            value: extendedHeaders[key]
          });
        }
        return encodeURIComponent(JSON.stringify({
          url: options2.url,
          method: options2.method,
          headers: reformattedHeader
        }));
      }
    };
    exports2.AwsClient = AwsClient;
    _a6 = AwsClient;
    _AwsClient_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL = { value: "https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15" };
    AwsClient.AWS_EC2_METADATA_IPV4_ADDRESS = "169.254.169.254";
    AwsClient.AWS_EC2_METADATA_IPV6_ADDRESS = "fd00:ec2::254";
  }
});

// node_modules/google-auth-library/build/src/auth/executable-response.js
var require_executable_response = __commonJS({
  "node_modules/google-auth-library/build/src/auth/executable-response.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InvalidSubjectTokenError = exports2.InvalidMessageFieldError = exports2.InvalidCodeFieldError = exports2.InvalidTokenTypeFieldError = exports2.InvalidExpirationTimeFieldError = exports2.InvalidSuccessFieldError = exports2.InvalidVersionFieldError = exports2.ExecutableResponseError = exports2.ExecutableResponse = void 0;
    var SAML_SUBJECT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:saml2";
    var OIDC_SUBJECT_TOKEN_TYPE1 = "urn:ietf:params:oauth:token-type:id_token";
    var OIDC_SUBJECT_TOKEN_TYPE2 = "urn:ietf:params:oauth:token-type:jwt";
    var ExecutableResponse = class {
      static {
        __name(this, "ExecutableResponse");
      }
      /**
       * Instantiates an ExecutableResponse instance using the provided JSON object
       * from the output of the executable.
       * @param responseJson Response from a 3rd party executable, loaded from a
       * run of the executable or a cached output file.
       */
      constructor(responseJson) {
        if (!responseJson.version) {
          throw new InvalidVersionFieldError("Executable response must contain a 'version' field.");
        }
        if (responseJson.success === void 0) {
          throw new InvalidSuccessFieldError("Executable response must contain a 'success' field.");
        }
        this.version = responseJson.version;
        this.success = responseJson.success;
        if (this.success) {
          this.expirationTime = responseJson.expiration_time;
          this.tokenType = responseJson.token_type;
          if (this.tokenType !== SAML_SUBJECT_TOKEN_TYPE && this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE1 && this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE2) {
            throw new InvalidTokenTypeFieldError(`Executable response must contain a 'token_type' field when successful and it must be one of ${OIDC_SUBJECT_TOKEN_TYPE1}, ${OIDC_SUBJECT_TOKEN_TYPE2}, or ${SAML_SUBJECT_TOKEN_TYPE}.`);
          }
          if (this.tokenType === SAML_SUBJECT_TOKEN_TYPE) {
            if (!responseJson.saml_response) {
              throw new InvalidSubjectTokenError(`Executable response must contain a 'saml_response' field when token_type=${SAML_SUBJECT_TOKEN_TYPE}.`);
            }
            this.subjectToken = responseJson.saml_response;
          } else {
            if (!responseJson.id_token) {
              throw new InvalidSubjectTokenError(`Executable response must contain a 'id_token' field when token_type=${OIDC_SUBJECT_TOKEN_TYPE1} or ${OIDC_SUBJECT_TOKEN_TYPE2}.`);
            }
            this.subjectToken = responseJson.id_token;
          }
        } else {
          if (!responseJson.code) {
            throw new InvalidCodeFieldError("Executable response must contain a 'code' field when unsuccessful.");
          }
          if (!responseJson.message) {
            throw new InvalidMessageFieldError("Executable response must contain a 'message' field when unsuccessful.");
          }
          this.errorCode = responseJson.code;
          this.errorMessage = responseJson.message;
        }
      }
      /**
       * @return A boolean representing if the response has a valid token. Returns
       * true when the response was successful and the token is not expired.
       */
      isValid() {
        return !this.isExpired() && this.success;
      }
      /**
       * @return A boolean representing if the response is expired. Returns true if the
       * provided timeout has passed.
       */
      isExpired() {
        return this.expirationTime !== void 0 && this.expirationTime < Math.round(Date.now() / 1e3);
      }
    };
    exports2.ExecutableResponse = ExecutableResponse;
    var ExecutableResponseError = class extends Error {
      static {
        __name(this, "ExecutableResponseError");
      }
      constructor(message) {
        super(message);
        Object.setPrototypeOf(this, new.target.prototype);
      }
    };
    exports2.ExecutableResponseError = ExecutableResponseError;
    var InvalidVersionFieldError = class extends ExecutableResponseError {
      static {
        __name(this, "InvalidVersionFieldError");
      }
    };
    exports2.InvalidVersionFieldError = InvalidVersionFieldError;
    var InvalidSuccessFieldError = class extends ExecutableResponseError {
      static {
        __name(this, "InvalidSuccessFieldError");
      }
    };
    exports2.InvalidSuccessFieldError = InvalidSuccessFieldError;
    var InvalidExpirationTimeFieldError = class extends ExecutableResponseError {
      static {
        __name(this, "InvalidExpirationTimeFieldError");
      }
    };
    exports2.InvalidExpirationTimeFieldError = InvalidExpirationTimeFieldError;
    var InvalidTokenTypeFieldError = class extends ExecutableResponseError {
      static {
        __name(this, "InvalidTokenTypeFieldError");
      }
    };
    exports2.InvalidTokenTypeFieldError = InvalidTokenTypeFieldError;
    var InvalidCodeFieldError = class extends ExecutableResponseError {
      static {
        __name(this, "InvalidCodeFieldError");
      }
    };
    exports2.InvalidCodeFieldError = InvalidCodeFieldError;
    var InvalidMessageFieldError = class extends ExecutableResponseError {
      static {
        __name(this, "InvalidMessageFieldError");
      }
    };
    exports2.InvalidMessageFieldError = InvalidMessageFieldError;
    var InvalidSubjectTokenError = class extends ExecutableResponseError {
      static {
        __name(this, "InvalidSubjectTokenError");
      }
    };
    exports2.InvalidSubjectTokenError = InvalidSubjectTokenError;
  }
});

// node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js
var require_pluggable_auth_handler = __commonJS({
  "node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PluggableAuthHandler = void 0;
    var pluggable_auth_client_1 = require_pluggable_auth_client();
    var executable_response_1 = require_executable_response();
    var childProcess3 = __require("child_process");
    var fs95 = __require("fs");
    var PluggableAuthHandler = class _PluggableAuthHandler {
      static {
        __name(this, "PluggableAuthHandler");
      }
      /**
       * Instantiates a PluggableAuthHandler instance using the provided
       * PluggableAuthHandlerOptions object.
       */
      constructor(options2) {
        if (!options2.command) {
          throw new Error("No command provided.");
        }
        this.commandComponents = _PluggableAuthHandler.parseCommand(options2.command);
        this.timeoutMillis = options2.timeoutMillis;
        if (!this.timeoutMillis) {
          throw new Error("No timeoutMillis provided.");
        }
        this.outputFile = options2.outputFile;
      }
      /**
       * Calls user provided executable to get a 3rd party subject token and
       * returns the response.
       * @param envMap a Map of additional Environment Variables required for
       *   the executable.
       * @return A promise that resolves with the executable response.
       */
      retrieveResponseFromExecutable(envMap) {
        return new Promise((resolve24, reject) => {
          const child = childProcess3.spawn(this.commandComponents[0], this.commandComponents.slice(1), {
            env: { ...process.env, ...Object.fromEntries(envMap) }
          });
          let output = "";
          child.stdout.on("data", (data) => {
            output += data;
          });
          child.stderr.on("data", (err) => {
            output += err;
          });
          const timeout2 = setTimeout(() => {
            child.removeAllListeners();
            child.kill();
            return reject(new Error("The executable failed to finish within the timeout specified."));
          }, this.timeoutMillis);
          child.on("close", (code2) => {
            clearTimeout(timeout2);
            if (code2 === 0) {
              try {
                const responseJson = JSON.parse(output);
                const response = new executable_response_1.ExecutableResponse(responseJson);
                return resolve24(response);
              } catch (error) {
                if (error instanceof executable_response_1.ExecutableResponseError) {
                  return reject(error);
                }
                return reject(new executable_response_1.ExecutableResponseError(`The executable returned an invalid response: ${output}`));
              }
            } else {
              return reject(new pluggable_auth_client_1.ExecutableError(output, code2.toString()));
            }
          });
        });
      }
      /**
       * Checks user provided output file for response from previous run of
       * executable and return the response if it exists, is formatted correctly, and is not expired.
       */
      async retrieveCachedResponse() {
        if (!this.outputFile || this.outputFile.length === 0) {
          return void 0;
        }
        let filePath;
        try {
          filePath = await fs95.promises.realpath(this.outputFile);
        } catch (_a6) {
          return void 0;
        }
        if (!(await fs95.promises.lstat(filePath)).isFile()) {
          return void 0;
        }
        const responseString = await fs95.promises.readFile(filePath, {
          encoding: "utf8"
        });
        if (responseString === "") {
          return void 0;
        }
        try {
          const responseJson = JSON.parse(responseString);
          const response = new executable_response_1.ExecutableResponse(responseJson);
          if (response.isValid()) {
            return new executable_response_1.ExecutableResponse(responseJson);
          }
          return void 0;
        } catch (error) {
          if (error instanceof executable_response_1.ExecutableResponseError) {
            throw error;
          }
          throw new executable_response_1.ExecutableResponseError(`The output file contained an invalid response: ${responseString}`);
        }
      }
      /**
       * Parses given command string into component array, splitting on spaces unless
       * spaces are between quotation marks.
       */
      static parseCommand(command2) {
        const components = command2.match(/(?:[^\s"]+|"[^"]*")+/g);
        if (!components) {
          throw new Error(`Provided command: "${command2}" could not be parsed.`);
        }
        for (let i = 0; i < components.length; i++) {
          if (components[i][0] === '"' && components[i].slice(-1) === '"') {
            components[i] = components[i].slice(1, -1);
          }
        }
        return components;
      }
    };
    exports2.PluggableAuthHandler = PluggableAuthHandler;
  }
});

// node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js
var require_pluggable_auth_client = __commonJS({
  "node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PluggableAuthClient = exports2.ExecutableError = void 0;
    var baseexternalclient_1 = require_baseexternalclient();
    var executable_response_1 = require_executable_response();
    var pluggable_auth_handler_1 = require_pluggable_auth_handler();
    var ExecutableError = class extends Error {
      static {
        __name(this, "ExecutableError");
      }
      constructor(message, code2) {
        super(`The executable failed with exit code: ${code2} and error message: ${message}.`);
        this.code = code2;
        Object.setPrototypeOf(this, new.target.prototype);
      }
    };
    exports2.ExecutableError = ExecutableError;
    var DEFAULT_EXECUTABLE_TIMEOUT_MILLIS = 30 * 1e3;
    var MINIMUM_EXECUTABLE_TIMEOUT_MILLIS = 5 * 1e3;
    var MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS = 120 * 1e3;
    var GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES = "GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES";
    var MAXIMUM_EXECUTABLE_VERSION = 1;
    var PluggableAuthClient = class extends baseexternalclient_1.BaseExternalAccountClient {
      static {
        __name(this, "PluggableAuthClient");
      }
      /**
       * Instantiates a PluggableAuthClient instance using the provided JSON
       * object loaded from an external account credentials file.
       * An error is thrown if the credential is not a valid pluggable auth credential.
       * @param options The external account options object typically loaded from
       *   the external account JSON credential file.
       * @param additionalOptions **DEPRECATED, all options are available in the
       *   `options` parameter.** Optional additional behavior customization options.
       *   These currently customize expiration threshold time and whether to retry
       *   on 401/403 API request errors.
       */
      constructor(options2, additionalOptions) {
        super(options2, additionalOptions);
        if (!options2.credential_source.executable) {
          throw new Error('No valid Pluggable Auth "credential_source" provided.');
        }
        this.command = options2.credential_source.executable.command;
        if (!this.command) {
          throw new Error('No valid Pluggable Auth "credential_source" provided.');
        }
        if (options2.credential_source.executable.timeout_millis === void 0) {
          this.timeoutMillis = DEFAULT_EXECUTABLE_TIMEOUT_MILLIS;
        } else {
          this.timeoutMillis = options2.credential_source.executable.timeout_millis;
          if (this.timeoutMillis < MINIMUM_EXECUTABLE_TIMEOUT_MILLIS || this.timeoutMillis > MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS) {
            throw new Error(`Timeout must be between ${MINIMUM_EXECUTABLE_TIMEOUT_MILLIS} and ${MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS} milliseconds.`);
          }
        }
        this.outputFile = options2.credential_source.executable.output_file;
        this.handler = new pluggable_auth_handler_1.PluggableAuthHandler({
          command: this.command,
          timeoutMillis: this.timeoutMillis,
          outputFile: this.outputFile
        });
        this.credentialSourceType = "executable";
      }
      /**
       * Triggered when an external subject token is needed to be exchanged for a
       * GCP access token via GCP STS endpoint.
       * This uses the `options.credential_source` object to figure out how
       * to retrieve the token using the current environment. In this case,
       * this calls a user provided executable which returns the subject token.
       * The logic is summarized as:
       * 1. Validated that the executable is allowed to run. The
       *    GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment must be set to
       *    1 for security reasons.
       * 2. If an output file is specified by the user, check the file location
       *    for a response. If the file exists and contains a valid response,
       *    return the subject token from the file.
       * 3. Call the provided executable and return response.
       * @return A promise that resolves with the external subject token.
       */
      async retrieveSubjectToken() {
        if (process.env[GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES] !== "1") {
          throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");
        }
        let executableResponse = void 0;
        if (this.outputFile) {
          executableResponse = await this.handler.retrieveCachedResponse();
        }
        if (!executableResponse) {
          const envMap = /* @__PURE__ */ new Map();
          envMap.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE", this.audience);
          envMap.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE", this.subjectTokenType);
          envMap.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE", "0");
          if (this.outputFile) {
            envMap.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE", this.outputFile);
          }
          const serviceAccountEmail = this.getServiceAccountEmail();
          if (serviceAccountEmail) {
            envMap.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL", serviceAccountEmail);
          }
          executableResponse = await this.handler.retrieveResponseFromExecutable(envMap);
        }
        if (executableResponse.version > MAXIMUM_EXECUTABLE_VERSION) {
          throw new Error(`Version of executable is not currently supported, maximum supported version is ${MAXIMUM_EXECUTABLE_VERSION}.`);
        }
        if (!executableResponse.success) {
          throw new ExecutableError(executableResponse.errorMessage, executableResponse.errorCode);
        }
        if (this.outputFile) {
          if (!executableResponse.expirationTime) {
            throw new executable_response_1.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");
          }
        }
        if (executableResponse.isExpired()) {
          throw new Error("Executable response is expired.");
        }
        return executableResponse.subjectToken;
      }
    };
    exports2.PluggableAuthClient = PluggableAuthClient;
  }
});

// node_modules/google-auth-library/build/src/auth/externalclient.js
var require_externalclient = __commonJS({
  "node_modules/google-auth-library/build/src/auth/externalclient.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ExternalAccountClient = void 0;
    var baseexternalclient_1 = require_baseexternalclient();
    var identitypoolclient_1 = require_identitypoolclient();
    var awsclient_1 = require_awsclient();
    var pluggable_auth_client_1 = require_pluggable_auth_client();
    var ExternalAccountClient = class {
      static {
        __name(this, "ExternalAccountClient");
      }
      constructor() {
        throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()");
      }
      /**
       * This static method will instantiate the
       * corresponding type of external account credential depending on the
       * underlying credential source.
       * @param options The external account options object typically loaded
       *   from the external account JSON credential file.
       * @param additionalOptions **DEPRECATED, all options are available in the
       *   `options` parameter.** Optional additional behavior customization options.
       *   These currently customize expiration threshold time and whether to retry
       *   on 401/403 API request errors.
       * @return A BaseExternalAccountClient instance or null if the options
       *   provided do not correspond to an external account credential.
       */
      static fromJSON(options2, additionalOptions) {
        var _a6, _b2;
        if (options2 && options2.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {
          if ((_a6 = options2.credential_source) === null || _a6 === void 0 ? void 0 : _a6.environment_id) {
            return new awsclient_1.AwsClient(options2, additionalOptions);
          } else if ((_b2 = options2.credential_source) === null || _b2 === void 0 ? void 0 : _b2.executable) {
            return new pluggable_auth_client_1.PluggableAuthClient(options2, additionalOptions);
          } else {
            return new identitypoolclient_1.IdentityPoolClient(options2, additionalOptions);
          }
        } else {
          return null;
        }
      }
    };
    exports2.ExternalAccountClient = ExternalAccountClient;
  }
});

// node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js
var require_externalAccountAuthorizedUserClient = __commonJS({
  "node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ExternalAccountAuthorizedUserClient = exports2.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = void 0;
    var authclient_1 = require_authclient();
    var oauth2common_1 = require_oauth2common();
    var gaxios_1 = require_src2();
    var stream2 = __require("stream");
    var baseexternalclient_1 = require_baseexternalclient();
    exports2.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = "external_account_authorized_user";
    var DEFAULT_TOKEN_URL = "https://sts.{universeDomain}/v1/oauthtoken";
    var ExternalAccountAuthorizedUserHandler = class _ExternalAccountAuthorizedUserHandler extends oauth2common_1.OAuthClientAuthHandler {
      static {
        __name(this, "ExternalAccountAuthorizedUserHandler");
      }
      /**
       * Initializes an ExternalAccountAuthorizedUserHandler instance.
       * @param url The URL of the token refresh endpoint.
       * @param transporter The transporter to use for the refresh request.
       * @param clientAuthentication The client authentication credentials to use
       *   for the refresh request.
       */
      constructor(url2, transporter, clientAuthentication) {
        super(clientAuthentication);
        this.url = url2;
        this.transporter = transporter;
      }
      /**
       * Requests a new access token from the token_url endpoint using the provided
       *   refresh token.
       * @param refreshToken The refresh token to use to generate a new access token.
       * @param additionalHeaders Optional additional headers to pass along the
       *   request.
       * @return A promise that resolves with the token refresh response containing
       *   the requested access token and its expiration time.
       */
      async refreshToken(refreshToken, additionalHeaders) {
        const values = new URLSearchParams({
          grant_type: "refresh_token",
          refresh_token: refreshToken
        });
        const headers = {
          "Content-Type": "application/x-www-form-urlencoded",
          ...additionalHeaders
        };
        const opts = {
          ..._ExternalAccountAuthorizedUserHandler.RETRY_CONFIG,
          url: this.url,
          method: "POST",
          headers,
          data: values.toString(),
          responseType: "json"
        };
        this.applyClientAuthenticationOptions(opts);
        try {
          const response = await this.transporter.request(opts);
          const tokenRefreshResponse = response.data;
          tokenRefreshResponse.res = response;
          return tokenRefreshResponse;
        } catch (error) {
          if (error instanceof gaxios_1.GaxiosError && error.response) {
            throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(
              error.response.data,
              // Preserve other fields from the original error.
              error
            );
          }
          throw error;
        }
      }
    };
    var ExternalAccountAuthorizedUserClient = class extends authclient_1.AuthClient {
      static {
        __name(this, "ExternalAccountAuthorizedUserClient");
      }
      /**
       * Instantiates an ExternalAccountAuthorizedUserClient instances using the
       * provided JSON object loaded from a credentials files.
       * An error is throws if the credential is not valid.
       * @param options The external account authorized user option object typically
       *   from the external accoutn authorized user JSON credential file.
       * @param additionalOptions **DEPRECATED, all options are available in the
       *   `options` parameter.** Optional additional behavior customization options.
       *   These currently customize expiration threshold time and whether to retry
       *   on 401/403 API request errors.
       */
      constructor(options2, additionalOptions) {
        var _a6;
        super({ ...options2, ...additionalOptions });
        if (options2.universe_domain) {
          this.universeDomain = options2.universe_domain;
        }
        this.refreshToken = options2.refresh_token;
        const clientAuth = {
          confidentialClientType: "basic",
          clientId: options2.client_id,
          clientSecret: options2.client_secret
        };
        this.externalAccountAuthorizedUserHandler = new ExternalAccountAuthorizedUserHandler((_a6 = options2.token_url) !== null && _a6 !== void 0 ? _a6 : DEFAULT_TOKEN_URL.replace("{universeDomain}", this.universeDomain), this.transporter, clientAuth);
        this.cachedAccessToken = null;
        this.quotaProjectId = options2.quota_project_id;
        if (typeof (additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.eagerRefreshThresholdMillis) !== "number") {
          this.eagerRefreshThresholdMillis = baseexternalclient_1.EXPIRATION_TIME_OFFSET;
        } else {
          this.eagerRefreshThresholdMillis = additionalOptions.eagerRefreshThresholdMillis;
        }
        this.forceRefreshOnFailure = !!(additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.forceRefreshOnFailure);
      }
      async getAccessToken() {
        if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) {
          await this.refreshAccessTokenAsync();
        }
        return {
          token: this.cachedAccessToken.access_token,
          res: this.cachedAccessToken.res
        };
      }
      async getRequestHeaders() {
        const accessTokenResponse = await this.getAccessToken();
        const headers = {
          Authorization: `Bearer ${accessTokenResponse.token}`
        };
        return this.addSharedMetadataHeaders(headers);
      }
      request(opts, callback) {
        if (callback) {
          this.requestAsync(opts).then((r3) => callback(null, r3), (e2) => {
            return callback(e2, e2.response);
          });
        } else {
          return this.requestAsync(opts);
        }
      }
      /**
       * Authenticates the provided HTTP request, processes it and resolves with the
       * returned response.
       * @param opts The HTTP request options.
       * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure.
       * @return A promise that resolves with the successful response.
       */
      async requestAsync(opts, reAuthRetried = false) {
        let response;
        try {
          const requestHeaders = await this.getRequestHeaders();
          opts.headers = opts.headers || {};
          if (requestHeaders && requestHeaders["x-goog-user-project"]) {
            opts.headers["x-goog-user-project"] = requestHeaders["x-goog-user-project"];
          }
          if (requestHeaders && requestHeaders.Authorization) {
            opts.headers.Authorization = requestHeaders.Authorization;
          }
          response = await this.transporter.request(opts);
        } catch (e2) {
          const res = e2.response;
          if (res) {
            const statusCode = res.status;
            const isReadableStream = res.config.data instanceof stream2.Readable;
            const isAuthErr = statusCode === 401 || statusCode === 403;
            if (!reAuthRetried && isAuthErr && !isReadableStream && this.forceRefreshOnFailure) {
              await this.refreshAccessTokenAsync();
              return await this.requestAsync(opts, true);
            }
          }
          throw e2;
        }
        return response;
      }
      /**
       * Forces token refresh, even if unexpired tokens are currently cached.
       * @return A promise that resolves with the refreshed credential.
       */
      async refreshAccessTokenAsync() {
        const refreshResponse = await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);
        this.cachedAccessToken = {
          access_token: refreshResponse.access_token,
          expiry_date: (/* @__PURE__ */ new Date()).getTime() + refreshResponse.expires_in * 1e3,
          res: refreshResponse.res
        };
        if (refreshResponse.refresh_token !== void 0) {
          this.refreshToken = refreshResponse.refresh_token;
        }
        return this.cachedAccessToken;
      }
      /**
       * Returns whether the provided credentials are expired or not.
       * If there is no expiry time, assumes the token is not expired or expiring.
       * @param credentials The credentials to check for expiration.
       * @return Whether the credentials are expired or not.
       */
      isExpired(credentials) {
        const now = (/* @__PURE__ */ new Date()).getTime();
        return credentials.expiry_date ? now >= credentials.expiry_date - this.eagerRefreshThresholdMillis : false;
      }
    };
    exports2.ExternalAccountAuthorizedUserClient = ExternalAccountAuthorizedUserClient;
  }
});

// node_modules/google-auth-library/build/src/auth/googleauth.js
var require_googleauth = __commonJS({
  "node_modules/google-auth-library/build/src/auth/googleauth.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __classPrivateFieldGet4 = exports2 && exports2.__classPrivateFieldGet || function(receiver, state, kind, f) {
      if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    };
    var __classPrivateFieldSet3 = exports2 && exports2.__classPrivateFieldSet || function(receiver, state, value, kind, f) {
      if (kind === "m") throw new TypeError("Private method is not writable");
      if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
      if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
      return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
    };
    var _GoogleAuth_instances;
    var _GoogleAuth_pendingAuthClient;
    var _GoogleAuth_prepareAndCacheClient;
    var _GoogleAuth_determineClient;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.GoogleAuth = exports2.GoogleAuthExceptionMessages = exports2.CLOUD_SDK_CLIENT_ID = void 0;
    var child_process_1 = __require("child_process");
    var fs95 = __require("fs");
    var gcpMetadata = require_src4();
    var os43 = __require("os");
    var path108 = __require("path");
    var crypto_1 = require_crypto3();
    var transporters_1 = require_transporters();
    var computeclient_1 = require_computeclient();
    var idtokenclient_1 = require_idtokenclient();
    var envDetect_1 = require_envDetect();
    var jwtclient_1 = require_jwtclient();
    var refreshclient_1 = require_refreshclient();
    var impersonated_1 = require_impersonated();
    var externalclient_1 = require_externalclient();
    var baseexternalclient_1 = require_baseexternalclient();
    var authclient_1 = require_authclient();
    var externalAccountAuthorizedUserClient_1 = require_externalAccountAuthorizedUserClient();
    var util_1 = require_util8();
    exports2.CLOUD_SDK_CLIENT_ID = "764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com";
    exports2.GoogleAuthExceptionMessages = {
      API_KEY_WITH_CREDENTIALS: "API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",
      NO_PROJECT_ID_FOUND: "Unable to detect a Project Id in the current environment. \nTo learn more about authentication and Google APIs, visit: \nhttps://cloud.google.com/docs/authentication/getting-started",
      NO_CREDENTIALS_FOUND: "Unable to find credentials in current environment. \nTo learn more about authentication and Google APIs, visit: \nhttps://cloud.google.com/docs/authentication/getting-started",
      NO_ADC_FOUND: "Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",
      NO_UNIVERSE_DOMAIN_FOUND: "Unable to detect a Universe Domain in the current environment.\nTo learn more about Universe Domain retrieval, visit: \nhttps://cloud.google.com/compute/docs/metadata/predefined-metadata-keys"
    };
    var GoogleAuth4 = class {
      static {
        __name(this, "GoogleAuth");
      }
      // Note:  this properly is only public to satisfy unit tests.
      // https://github.com/Microsoft/TypeScript/issues/5228
      get isGCE() {
        return this.checkIsGCE;
      }
      /**
       * Configuration is resolved in the following order of precedence:
       * - {@link GoogleAuthOptions.credentials `credentials`}
       * - {@link GoogleAuthOptions.keyFilename `keyFilename`}
       * - {@link GoogleAuthOptions.keyFile `keyFile`}
       *
       * {@link GoogleAuthOptions.clientOptions `clientOptions`} are passed to the
       * {@link AuthClient `AuthClient`s}.
       *
       * @param opts
       */
      constructor(opts = {}) {
        _GoogleAuth_instances.add(this);
        this.checkIsGCE = void 0;
        this.jsonContent = null;
        this.cachedCredential = null;
        _GoogleAuth_pendingAuthClient.set(this, null);
        this.clientOptions = {};
        this._cachedProjectId = opts.projectId || null;
        this.cachedCredential = opts.authClient || null;
        this.keyFilename = opts.keyFilename || opts.keyFile;
        this.scopes = opts.scopes;
        this.clientOptions = opts.clientOptions || {};
        this.jsonContent = opts.credentials || null;
        this.apiKey = opts.apiKey || this.clientOptions.apiKey || null;
        if (this.apiKey && (this.jsonContent || this.clientOptions.credentials)) {
          throw new RangeError(exports2.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);
        }
        if (opts.universeDomain) {
          this.clientOptions.universeDomain = opts.universeDomain;
        }
      }
      // GAPIC client libraries should always use self-signed JWTs. The following
      // variables are set on the JWT client in order to indicate the type of library,
      // and sign the JWT with the correct audience and scopes (if not supplied).
      setGapicJWTValues(client) {
        client.defaultServicePath = this.defaultServicePath;
        client.useJWTAccessWithScope = this.useJWTAccessWithScope;
        client.defaultScopes = this.defaultScopes;
      }
      getProjectId(callback) {
        if (callback) {
          this.getProjectIdAsync().then((r3) => callback(null, r3), callback);
        } else {
          return this.getProjectIdAsync();
        }
      }
      /**
       * A temporary method for internal `getProjectId` usages where `null` is
       * acceptable. In a future major release, `getProjectId` should return `null`
       * (as the `Promise<string | null>` base signature describes) and this private
       * method should be removed.
       *
       * @returns Promise that resolves with project id (or `null`)
       */
      async getProjectIdOptional() {
        try {
          return await this.getProjectId();
        } catch (e2) {
          if (e2 instanceof Error && e2.message === exports2.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND) {
            return null;
          } else {
            throw e2;
          }
        }
      }
      /**
       * A private method for finding and caching a projectId.
       *
       * Supports environments in order of precedence:
       * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable
       * - GOOGLE_APPLICATION_CREDENTIALS JSON file
       * - Cloud SDK: `gcloud config config-helper --format json`
       * - GCE project ID from metadata server
       *
       * @returns projectId
       */
      async findAndCacheProjectId() {
        let projectId = null;
        projectId || (projectId = await this.getProductionProjectId());
        projectId || (projectId = await this.getFileProjectId());
        projectId || (projectId = await this.getDefaultServiceProjectId());
        projectId || (projectId = await this.getGCEProjectId());
        projectId || (projectId = await this.getExternalAccountClientProjectId());
        if (projectId) {
          this._cachedProjectId = projectId;
          return projectId;
        } else {
          throw new Error(exports2.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND);
        }
      }
      async getProjectIdAsync() {
        if (this._cachedProjectId) {
          return this._cachedProjectId;
        }
        if (!this._findProjectIdPromise) {
          this._findProjectIdPromise = this.findAndCacheProjectId();
        }
        return this._findProjectIdPromise;
      }
      /**
       * Retrieves a universe domain from the metadata server via
       * {@link gcpMetadata.universe}.
       *
       * @returns a universe domain
       */
      async getUniverseDomainFromMetadataServer() {
        var _a6;
        let universeDomain;
        try {
          universeDomain = await gcpMetadata.universe("universe-domain");
          universeDomain || (universeDomain = authclient_1.DEFAULT_UNIVERSE);
        } catch (e2) {
          if (e2 && ((_a6 = e2 === null || e2 === void 0 ? void 0 : e2.response) === null || _a6 === void 0 ? void 0 : _a6.status) === 404) {
            universeDomain = authclient_1.DEFAULT_UNIVERSE;
          } else {
            throw e2;
          }
        }
        return universeDomain;
      }
      /**
       * Retrieves, caches, and returns the universe domain in the following order
       * of precedence:
       * - The universe domain in {@link GoogleAuth.clientOptions}
       * - An existing or ADC {@link AuthClient}'s universe domain
       * - {@link gcpMetadata.universe}, if {@link Compute} client
       *
       * @returns The universe domain
       */
      async getUniverseDomain() {
        let universeDomain = (0, util_1.originalOrCamelOptions)(this.clientOptions).get("universe_domain");
        try {
          universeDomain !== null && universeDomain !== void 0 ? universeDomain : universeDomain = (await this.getClient()).universeDomain;
        } catch (_a6) {
          universeDomain !== null && universeDomain !== void 0 ? universeDomain : universeDomain = authclient_1.DEFAULT_UNIVERSE;
        }
        return universeDomain;
      }
      /**
       * @returns Any scopes (user-specified or default scopes specified by the
       *   client library) that need to be set on the current Auth client.
       */
      getAnyScopes() {
        return this.scopes || this.defaultScopes;
      }
      getApplicationDefault(optionsOrCallback = {}, callback) {
        let options2;
        if (typeof optionsOrCallback === "function") {
          callback = optionsOrCallback;
        } else {
          options2 = optionsOrCallback;
        }
        if (callback) {
          this.getApplicationDefaultAsync(options2).then((r3) => callback(null, r3.credential, r3.projectId), callback);
        } else {
          return this.getApplicationDefaultAsync(options2);
        }
      }
      async getApplicationDefaultAsync(options2 = {}) {
        if (this.cachedCredential) {
          return await __classPrivateFieldGet4(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, this.cachedCredential, null);
        }
        let credential;
        credential = await this._tryGetApplicationCredentialsFromEnvironmentVariable(options2);
        if (credential) {
          if (credential instanceof jwtclient_1.JWT) {
            credential.scopes = this.scopes;
          } else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) {
            credential.scopes = this.getAnyScopes();
          }
          return await __classPrivateFieldGet4(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, credential);
        }
        credential = await this._tryGetApplicationCredentialsFromWellKnownFile(options2);
        if (credential) {
          if (credential instanceof jwtclient_1.JWT) {
            credential.scopes = this.scopes;
          } else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) {
            credential.scopes = this.getAnyScopes();
          }
          return await __classPrivateFieldGet4(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, credential);
        }
        if (await this._checkIsGCE()) {
          options2.scopes = this.getAnyScopes();
          return await __classPrivateFieldGet4(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, new computeclient_1.Compute(options2));
        }
        throw new Error(exports2.GoogleAuthExceptionMessages.NO_ADC_FOUND);
      }
      /**
       * Determines whether the auth layer is running on Google Compute Engine.
       * Checks for GCP Residency, then fallback to checking if metadata server
       * is available.
       *
       * @returns A promise that resolves with the boolean.
       * @api private
       */
      async _checkIsGCE() {
        if (this.checkIsGCE === void 0) {
          this.checkIsGCE = gcpMetadata.getGCPResidency() || await gcpMetadata.isAvailable();
        }
        return this.checkIsGCE;
      }
      /**
       * Attempts to load default credentials from the environment variable path..
       * @returns Promise that resolves with the OAuth2Client or null.
       * @api private
       */
      async _tryGetApplicationCredentialsFromEnvironmentVariable(options2) {
        const credentialsPath = process.env["GOOGLE_APPLICATION_CREDENTIALS"] || process.env["google_application_credentials"];
        if (!credentialsPath || credentialsPath.length === 0) {
          return null;
        }
        try {
          return this._getApplicationCredentialsFromFilePath(credentialsPath, options2);
        } catch (e2) {
          if (e2 instanceof Error) {
            e2.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e2.message}`;
          }
          throw e2;
        }
      }
      /**
       * Attempts to load default credentials from a well-known file location
       * @return Promise that resolves with the OAuth2Client or null.
       * @api private
       */
      async _tryGetApplicationCredentialsFromWellKnownFile(options2) {
        let location = null;
        if (this._isWindows()) {
          location = process.env["APPDATA"];
        } else {
          const home = process.env["HOME"];
          if (home) {
            location = path108.join(home, ".config");
          }
        }
        if (location) {
          location = path108.join(location, "gcloud", "application_default_credentials.json");
          if (!fs95.existsSync(location)) {
            location = null;
          }
        }
        if (!location) {
          return null;
        }
        const client = await this._getApplicationCredentialsFromFilePath(location, options2);
        return client;
      }
      /**
       * Attempts to load default credentials from a file at the given path..
       * @param filePath The path to the file to read.
       * @returns Promise that resolves with the OAuth2Client
       * @api private
       */
      async _getApplicationCredentialsFromFilePath(filePath, options2 = {}) {
        if (!filePath || filePath.length === 0) {
          throw new Error("The file path is invalid.");
        }
        try {
          filePath = fs95.realpathSync(filePath);
          if (!fs95.lstatSync(filePath).isFile()) {
            throw new Error();
          }
        } catch (err) {
          if (err instanceof Error) {
            err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`;
          }
          throw err;
        }
        const readStream = fs95.createReadStream(filePath);
        return this.fromStream(readStream, options2);
      }
      /**
       * Create a credentials instance using a given impersonated input options.
       * @param json The impersonated input object.
       * @returns JWT or UserRefresh Client with data
       */
      fromImpersonatedJSON(json2) {
        var _a6, _b2, _c2, _d;
        if (!json2) {
          throw new Error("Must pass in a JSON object containing an  impersonated refresh token");
        }
        if (json2.type !== impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {
          throw new Error(`The incoming JSON object does not have the "${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}" type`);
        }
        if (!json2.source_credentials) {
          throw new Error("The incoming JSON object does not contain a source_credentials field");
        }
        if (!json2.service_account_impersonation_url) {
          throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");
        }
        const sourceClient = this.fromJSON(json2.source_credentials);
        if (((_a6 = json2.service_account_impersonation_url) === null || _a6 === void 0 ? void 0 : _a6.length) > 256) {
          throw new RangeError(`Target principal is too long: ${json2.service_account_impersonation_url}`);
        }
        const targetPrincipal = (_c2 = (_b2 = /(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(json2.service_account_impersonation_url)) === null || _b2 === void 0 ? void 0 : _b2.groups) === null || _c2 === void 0 ? void 0 : _c2.target;
        if (!targetPrincipal) {
          throw new RangeError(`Cannot extract target principal from ${json2.service_account_impersonation_url}`);
        }
        const targetScopes = (_d = this.getAnyScopes()) !== null && _d !== void 0 ? _d : [];
        return new impersonated_1.Impersonated({
          ...json2,
          sourceClient,
          targetPrincipal,
          targetScopes: Array.isArray(targetScopes) ? targetScopes : [targetScopes]
        });
      }
      /**
       * Create a credentials instance using the given input options.
       * This client is not cached.
       *
       * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}.
       *
       * @param json The input object.
       * @param options The JWT or UserRefresh options for the client
       * @returns JWT or UserRefresh Client with data
       */
      fromJSON(json2, options2 = {}) {
        let client;
        const preferredUniverseDomain = (0, util_1.originalOrCamelOptions)(options2).get("universe_domain");
        if (json2.type === refreshclient_1.USER_REFRESH_ACCOUNT_TYPE) {
          client = new refreshclient_1.UserRefreshClient(options2);
          client.fromJSON(json2);
        } else if (json2.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {
          client = this.fromImpersonatedJSON(json2);
        } else if (json2.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {
          client = externalclient_1.ExternalAccountClient.fromJSON(json2, options2);
          client.scopes = this.getAnyScopes();
        } else if (json2.type === externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE) {
          client = new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient(json2, options2);
        } else {
          options2.scopes = this.scopes;
          client = new jwtclient_1.JWT(options2);
          this.setGapicJWTValues(client);
          client.fromJSON(json2);
        }
        if (preferredUniverseDomain) {
          client.universeDomain = preferredUniverseDomain;
        }
        return client;
      }
      /**
       * Return a JWT or UserRefreshClient from JavaScript object, caching both the
       * object used to instantiate and the client.
       * @param json The input object.
       * @param options The JWT or UserRefresh options for the client
       * @returns JWT or UserRefresh Client with data
       */
      _cacheClientFromJSON(json2, options2) {
        const client = this.fromJSON(json2, options2);
        this.jsonContent = json2;
        this.cachedCredential = client;
        return client;
      }
      fromStream(inputStream, optionsOrCallback = {}, callback) {
        let options2 = {};
        if (typeof optionsOrCallback === "function") {
          callback = optionsOrCallback;
        } else {
          options2 = optionsOrCallback;
        }
        if (callback) {
          this.fromStreamAsync(inputStream, options2).then((r3) => callback(null, r3), callback);
        } else {
          return this.fromStreamAsync(inputStream, options2);
        }
      }
      fromStreamAsync(inputStream, options2) {
        return new Promise((resolve24, reject) => {
          if (!inputStream) {
            throw new Error("Must pass in a stream containing the Google auth settings.");
          }
          const chunks = [];
          inputStream.setEncoding("utf8").on("error", reject).on("data", (chunk) => chunks.push(chunk)).on("end", () => {
            try {
              try {
                const data = JSON.parse(chunks.join(""));
                const r3 = this._cacheClientFromJSON(data, options2);
                return resolve24(r3);
              } catch (err) {
                if (!this.keyFilename)
                  throw err;
                const client = new jwtclient_1.JWT({
                  ...this.clientOptions,
                  keyFile: this.keyFilename
                });
                this.cachedCredential = client;
                this.setGapicJWTValues(client);
                return resolve24(client);
              }
            } catch (err) {
              return reject(err);
            }
          });
        });
      }
      /**
       * Create a credentials instance using the given API key string.
       * The created client is not cached. In order to create and cache it use the {@link GoogleAuth.getClient `getClient`} method after first providing an {@link GoogleAuth.apiKey `apiKey`}.
       *
       * @param apiKey The API key string
       * @param options An optional options object.
       * @returns A JWT loaded from the key
       */
      fromAPIKey(apiKey, options2 = {}) {
        return new jwtclient_1.JWT({ ...options2, apiKey });
      }
      /**
       * Determines whether the current operating system is Windows.
       * @api private
       */
      _isWindows() {
        const sys = os43.platform();
        if (sys && sys.length >= 3) {
          if (sys.substring(0, 3).toLowerCase() === "win") {
            return true;
          }
        }
        return false;
      }
      /**
       * Run the Google Cloud SDK command that prints the default project ID
       */
      async getDefaultServiceProjectId() {
        return new Promise((resolve24) => {
          (0, child_process_1.exec)("gcloud config config-helper --format json", (err, stdout) => {
            if (!err && stdout) {
              try {
                const projectId = JSON.parse(stdout).configuration.properties.core.project;
                resolve24(projectId);
                return;
              } catch (e2) {
              }
            }
            resolve24(null);
          });
        });
      }
      /**
       * Loads the project id from environment variables.
       * @api private
       */
      getProductionProjectId() {
        return process.env["GCLOUD_PROJECT"] || process.env["GOOGLE_CLOUD_PROJECT"] || process.env["gcloud_project"] || process.env["google_cloud_project"];
      }
      /**
       * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file.
       * @api private
       */
      async getFileProjectId() {
        if (this.cachedCredential) {
          return this.cachedCredential.projectId;
        }
        if (this.keyFilename) {
          const creds = await this.getClient();
          if (creds && creds.projectId) {
            return creds.projectId;
          }
        }
        const r3 = await this._tryGetApplicationCredentialsFromEnvironmentVariable();
        if (r3) {
          return r3.projectId;
        } else {
          return null;
        }
      }
      /**
       * Gets the project ID from external account client if available.
       */
      async getExternalAccountClientProjectId() {
        if (!this.jsonContent || this.jsonContent.type !== baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {
          return null;
        }
        const creds = await this.getClient();
        return await creds.getProjectId();
      }
      /**
       * Gets the Compute Engine project ID if it can be inferred.
       */
      async getGCEProjectId() {
        try {
          const r3 = await gcpMetadata.project("project-id");
          return r3;
        } catch (e2) {
          return null;
        }
      }
      getCredentials(callback) {
        if (callback) {
          this.getCredentialsAsync().then((r3) => callback(null, r3), callback);
        } else {
          return this.getCredentialsAsync();
        }
      }
      async getCredentialsAsync() {
        const client = await this.getClient();
        if (client instanceof impersonated_1.Impersonated) {
          return { client_email: client.getTargetPrincipal() };
        }
        if (client instanceof baseexternalclient_1.BaseExternalAccountClient) {
          const serviceAccountEmail = client.getServiceAccountEmail();
          if (serviceAccountEmail) {
            return {
              client_email: serviceAccountEmail,
              universe_domain: client.universeDomain
            };
          }
        }
        if (this.jsonContent) {
          return {
            client_email: this.jsonContent.client_email,
            private_key: this.jsonContent.private_key,
            universe_domain: this.jsonContent.universe_domain
          };
        }
        if (await this._checkIsGCE()) {
          const [client_email, universe_domain] = await Promise.all([
            gcpMetadata.instance("service-accounts/default/email"),
            this.getUniverseDomain()
          ]);
          return { client_email, universe_domain };
        }
        throw new Error(exports2.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND);
      }
      /**
       * Automatically obtain an {@link AuthClient `AuthClient`} based on the
       * provided configuration. If no options were passed, use Application
       * Default Credentials.
       */
      async getClient() {
        if (this.cachedCredential) {
          return this.cachedCredential;
        }
        __classPrivateFieldSet3(this, _GoogleAuth_pendingAuthClient, __classPrivateFieldGet4(this, _GoogleAuth_pendingAuthClient, "f") || __classPrivateFieldGet4(this, _GoogleAuth_instances, "m", _GoogleAuth_determineClient).call(this), "f");
        try {
          return await __classPrivateFieldGet4(this, _GoogleAuth_pendingAuthClient, "f");
        } finally {
          __classPrivateFieldSet3(this, _GoogleAuth_pendingAuthClient, null, "f");
        }
      }
      /**
       * Creates a client which will fetch an ID token for authorization.
       * @param targetAudience the audience for the fetched ID token.
       * @returns IdTokenClient for making HTTP calls authenticated with ID tokens.
       */
      async getIdTokenClient(targetAudience) {
        const client = await this.getClient();
        if (!("fetchIdToken" in client)) {
          throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");
        }
        return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client });
      }
      /**
       * Automatically obtain application default credentials, and return
       * an access token for making requests.
       */
      async getAccessToken() {
        const client = await this.getClient();
        return (await client.getAccessToken()).token;
      }
      /**
       * Obtain the HTTP headers that will provide authorization for a given
       * request.
       */
      async getRequestHeaders(url2) {
        const client = await this.getClient();
        return client.getRequestHeaders(url2);
      }
      /**
       * Obtain credentials for a request, then attach the appropriate headers to
       * the request options.
       * @param opts Axios or Request options on which to attach the headers
       */
      async authorizeRequest(opts) {
        opts = opts || {};
        const url2 = opts.url || opts.uri;
        const client = await this.getClient();
        const headers = await client.getRequestHeaders(url2);
        opts.headers = Object.assign(opts.headers || {}, headers);
        return opts;
      }
      /**
       * Automatically obtain application default credentials, and make an
       * HTTP request using the given options.
       * @param opts Axios request options for the HTTP request.
       */
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      async request(opts) {
        const client = await this.getClient();
        return client.request(opts);
      }
      /**
       * Determine the compute environment in which the code is running.
       */
      getEnv() {
        return (0, envDetect_1.getEnv)();
      }
      /**
       * Sign the given data with the current private key, or go out
       * to the IAM API to sign it.
       * @param data The data to be signed.
       * @param endpoint A custom endpoint to use.
       *
       * @example
       * ```
       * sign('data', 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/');
       * ```
       */
      async sign(data, endpoint) {
        const client = await this.getClient();
        const universe = await this.getUniverseDomain();
        endpoint = endpoint || `https://iamcredentials.${universe}/v1/projects/-/serviceAccounts/`;
        if (client instanceof impersonated_1.Impersonated) {
          const signed = await client.sign(data);
          return signed.signedBlob;
        }
        const crypto18 = (0, crypto_1.createCrypto)();
        if (client instanceof jwtclient_1.JWT && client.key) {
          const sign = await crypto18.sign(client.key, data);
          return sign;
        }
        const creds = await this.getCredentials();
        if (!creds.client_email) {
          throw new Error("Cannot sign data without `client_email`.");
        }
        return this.signBlob(crypto18, creds.client_email, data, endpoint);
      }
      async signBlob(crypto18, emailOrUniqueId, data, endpoint) {
        const url2 = new URL(endpoint + `${emailOrUniqueId}:signBlob`);
        const res = await this.request({
          method: "POST",
          url: url2.href,
          data: {
            payload: crypto18.encodeBase64StringUtf8(data)
          },
          retry: true,
          retryConfig: {
            httpMethodsToRetry: ["POST"]
          }
        });
        return res.data.signedBlob;
      }
    };
    exports2.GoogleAuth = GoogleAuth4;
    _GoogleAuth_pendingAuthClient = /* @__PURE__ */ new WeakMap(), _GoogleAuth_instances = /* @__PURE__ */ new WeakSet(), _GoogleAuth_prepareAndCacheClient = /* @__PURE__ */ __name(async function _GoogleAuth_prepareAndCacheClient2(credential, quotaProjectIdOverride = process.env["GOOGLE_CLOUD_QUOTA_PROJECT"] || null) {
      const projectId = await this.getProjectIdOptional();
      if (quotaProjectIdOverride) {
        credential.quotaProjectId = quotaProjectIdOverride;
      }
      this.cachedCredential = credential;
      return { credential, projectId };
    }, "_GoogleAuth_prepareAndCacheClient"), _GoogleAuth_determineClient = /* @__PURE__ */ __name(async function _GoogleAuth_determineClient2() {
      if (this.jsonContent) {
        return this._cacheClientFromJSON(this.jsonContent, this.clientOptions);
      } else if (this.keyFilename) {
        const filePath = path108.resolve(this.keyFilename);
        const stream2 = fs95.createReadStream(filePath);
        return await this.fromStreamAsync(stream2, this.clientOptions);
      } else if (this.apiKey) {
        const client = await this.fromAPIKey(this.apiKey, this.clientOptions);
        client.scopes = this.scopes;
        const { credential } = await __classPrivateFieldGet4(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, client);
        return credential;
      } else {
        const { credential } = await this.getApplicationDefaultAsync(this.clientOptions);
        return credential;
      }
    }, "_GoogleAuth_determineClient");
    GoogleAuth4.DefaultTransporter = transporters_1.DefaultTransporter;
  }
});

// node_modules/google-auth-library/build/src/auth/iam.js
var require_iam = __commonJS({
  "node_modules/google-auth-library/build/src/auth/iam.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.IAMAuth = void 0;
    var IAMAuth = class {
      static {
        __name(this, "IAMAuth");
      }
      /**
       * IAM credentials.
       *
       * @param selector the iam authority selector
       * @param token the token
       * @constructor
       */
      constructor(selector, token2) {
        this.selector = selector;
        this.token = token2;
        this.selector = selector;
        this.token = token2;
      }
      /**
       * Acquire the HTTP headers required to make an authenticated request.
       */
      getRequestHeaders() {
        return {
          "x-goog-iam-authority-selector": this.selector,
          "x-goog-iam-authorization-token": this.token
        };
      }
    };
    exports2.IAMAuth = IAMAuth;
  }
});

// node_modules/google-auth-library/build/src/auth/downscopedclient.js
var require_downscopedclient = __commonJS({
  "node_modules/google-auth-library/build/src/auth/downscopedclient.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DownscopedClient = exports2.EXPIRATION_TIME_OFFSET = exports2.MAX_ACCESS_BOUNDARY_RULES_COUNT = void 0;
    var stream2 = __require("stream");
    var authclient_1 = require_authclient();
    var sts = require_stscredentials();
    var STS_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange";
    var STS_REQUEST_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
    var STS_SUBJECT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
    exports2.MAX_ACCESS_BOUNDARY_RULES_COUNT = 10;
    exports2.EXPIRATION_TIME_OFFSET = 5 * 60 * 1e3;
    var DownscopedClient = class extends authclient_1.AuthClient {
      static {
        __name(this, "DownscopedClient");
      }
      /**
       * Instantiates a downscoped client object using the provided source
       * AuthClient and credential access boundary rules.
       * To downscope permissions of a source AuthClient, a Credential Access
       * Boundary that specifies which resources the new credential can access, as
       * well as an upper bound on the permissions that are available on each
       * resource, has to be defined. A downscoped client can then be instantiated
       * using the source AuthClient and the Credential Access Boundary.
       * @param authClient The source AuthClient to be downscoped based on the
       *   provided Credential Access Boundary rules.
       * @param credentialAccessBoundary The Credential Access Boundary which
       *   contains a list of access boundary rules. Each rule contains information
       *   on the resource that the rule applies to, the upper bound of the
       *   permissions that are available on that resource and an optional
       *   condition to further restrict permissions.
       * @param additionalOptions **DEPRECATED, set this in the provided `authClient`.**
       *   Optional additional behavior customization options.
       * @param quotaProjectId **DEPRECATED, set this in the provided `authClient`.**
       *   Optional quota project id for setting up in the x-goog-user-project header.
       */
      constructor(authClient, credentialAccessBoundary, additionalOptions, quotaProjectId) {
        super({ ...additionalOptions, quotaProjectId });
        this.authClient = authClient;
        this.credentialAccessBoundary = credentialAccessBoundary;
        if (credentialAccessBoundary.accessBoundary.accessBoundaryRules.length === 0) {
          throw new Error("At least one access boundary rule needs to be defined.");
        } else if (credentialAccessBoundary.accessBoundary.accessBoundaryRules.length > exports2.MAX_ACCESS_BOUNDARY_RULES_COUNT) {
          throw new Error(`The provided access boundary has more than ${exports2.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);
        }
        for (const rule of credentialAccessBoundary.accessBoundary.accessBoundaryRules) {
          if (rule.availablePermissions.length === 0) {
            throw new Error("At least one permission should be defined in access boundary rules.");
          }
        }
        this.stsCredential = new sts.StsCredentials(`https://sts.${this.universeDomain}/v1/token`);
        this.cachedDownscopedAccessToken = null;
      }
      /**
       * Provides a mechanism to inject Downscoped access tokens directly.
       * The expiry_date field is required to facilitate determination of the token
       * expiration which would make it easier for the token consumer to handle.
       * @param credentials The Credentials object to set on the current client.
       */
      setCredentials(credentials) {
        if (!credentials.expiry_date) {
          throw new Error("The access token expiry_date field is missing in the provided credentials.");
        }
        super.setCredentials(credentials);
        this.cachedDownscopedAccessToken = credentials;
      }
      async getAccessToken() {
        if (!this.cachedDownscopedAccessToken || this.isExpired(this.cachedDownscopedAccessToken)) {
          await this.refreshAccessTokenAsync();
        }
        return {
          token: this.cachedDownscopedAccessToken.access_token,
          expirationTime: this.cachedDownscopedAccessToken.expiry_date,
          res: this.cachedDownscopedAccessToken.res
        };
      }
      /**
       * The main authentication interface. It takes an optional url which when
       * present is the endpoint being accessed, and returns a Promise which
       * resolves with authorization header fields.
       *
       * The result has the form:
       * { Authorization: 'Bearer <access_token_value>' }
       */
      async getRequestHeaders() {
        const accessTokenResponse = await this.getAccessToken();
        const headers = {
          Authorization: `Bearer ${accessTokenResponse.token}`
        };
        return this.addSharedMetadataHeaders(headers);
      }
      request(opts, callback) {
        if (callback) {
          this.requestAsync(opts).then((r3) => callback(null, r3), (e2) => {
            return callback(e2, e2.response);
          });
        } else {
          return this.requestAsync(opts);
        }
      }
      /**
       * Authenticates the provided HTTP request, processes it and resolves with the
       * returned response.
       * @param opts The HTTP request options.
       * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure
       * @return A promise that resolves with the successful response.
       */
      async requestAsync(opts, reAuthRetried = false) {
        let response;
        try {
          const requestHeaders = await this.getRequestHeaders();
          opts.headers = opts.headers || {};
          if (requestHeaders && requestHeaders["x-goog-user-project"]) {
            opts.headers["x-goog-user-project"] = requestHeaders["x-goog-user-project"];
          }
          if (requestHeaders && requestHeaders.Authorization) {
            opts.headers.Authorization = requestHeaders.Authorization;
          }
          response = await this.transporter.request(opts);
        } catch (e2) {
          const res = e2.response;
          if (res) {
            const statusCode = res.status;
            const isReadableStream = res.config.data instanceof stream2.Readable;
            const isAuthErr = statusCode === 401 || statusCode === 403;
            if (!reAuthRetried && isAuthErr && !isReadableStream && this.forceRefreshOnFailure) {
              await this.refreshAccessTokenAsync();
              return await this.requestAsync(opts, true);
            }
          }
          throw e2;
        }
        return response;
      }
      /**
       * Forces token refresh, even if unexpired tokens are currently cached.
       * GCP access tokens are retrieved from authclient object/source credential.
       * Then GCP access tokens are exchanged for downscoped access tokens via the
       * token exchange endpoint.
       * @return A promise that resolves with the fresh downscoped access token.
       */
      async refreshAccessTokenAsync() {
        var _a6;
        const subjectToken = (await this.authClient.getAccessToken()).token;
        const stsCredentialsOptions = {
          grantType: STS_GRANT_TYPE,
          requestedTokenType: STS_REQUEST_TOKEN_TYPE,
          subjectToken,
          subjectTokenType: STS_SUBJECT_TOKEN_TYPE
        };
        const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, void 0, this.credentialAccessBoundary);
        const sourceCredExpireDate = ((_a6 = this.authClient.credentials) === null || _a6 === void 0 ? void 0 : _a6.expiry_date) || null;
        const expiryDate = stsResponse.expires_in ? (/* @__PURE__ */ new Date()).getTime() + stsResponse.expires_in * 1e3 : sourceCredExpireDate;
        this.cachedDownscopedAccessToken = {
          access_token: stsResponse.access_token,
          expiry_date: expiryDate,
          res: stsResponse.res
        };
        this.credentials = {};
        Object.assign(this.credentials, this.cachedDownscopedAccessToken);
        delete this.credentials.res;
        this.emit("tokens", {
          refresh_token: null,
          expiry_date: this.cachedDownscopedAccessToken.expiry_date,
          access_token: this.cachedDownscopedAccessToken.access_token,
          token_type: "Bearer",
          id_token: null
        });
        return this.cachedDownscopedAccessToken;
      }
      /**
       * Returns whether the provided credentials are expired or not.
       * If there is no expiry time, assumes the token is not expired or expiring.
       * @param downscopedAccessToken The credentials to check for expiration.
       * @return Whether the credentials are expired or not.
       */
      isExpired(downscopedAccessToken) {
        const now = (/* @__PURE__ */ new Date()).getTime();
        return downscopedAccessToken.expiry_date ? now >= downscopedAccessToken.expiry_date - this.eagerRefreshThresholdMillis : false;
      }
    };
    exports2.DownscopedClient = DownscopedClient;
  }
});

// node_modules/google-auth-library/build/src/auth/passthrough.js
var require_passthrough = __commonJS({
  "node_modules/google-auth-library/build/src/auth/passthrough.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PassThroughClient = void 0;
    var authclient_1 = require_authclient();
    var PassThroughClient = class extends authclient_1.AuthClient {
      static {
        __name(this, "PassThroughClient");
      }
      /**
       * Creates a request without any authentication headers or checks.
       *
       * @remarks
       *
       * In testing environments it may be useful to change the provided
       * {@link AuthClient.transporter} for any desired request overrides/handling.
       *
       * @param opts
       * @returns The response of the request.
       */
      async request(opts) {
        return this.transporter.request(opts);
      }
      /**
       * A required method of the base class.
       * Always will return an empty object.
       *
       * @returns {}
       */
      async getAccessToken() {
        return {};
      }
      /**
       * A required method of the base class.
       * Always will return an empty object.
       *
       * @returns {}
       */
      async getRequestHeaders() {
        return {};
      }
    };
    exports2.PassThroughClient = PassThroughClient;
    var a = new PassThroughClient();
    a.getAccessToken();
  }
});

// node_modules/google-auth-library/build/src/index.js
var require_src6 = __commonJS({
  "node_modules/google-auth-library/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.GoogleAuth = exports2.auth = exports2.DefaultTransporter = exports2.PassThroughClient = exports2.ExecutableError = exports2.PluggableAuthClient = exports2.DownscopedClient = exports2.BaseExternalAccountClient = exports2.ExternalAccountClient = exports2.IdentityPoolClient = exports2.AwsRequestSigner = exports2.AwsClient = exports2.UserRefreshClient = exports2.LoginTicket = exports2.ClientAuthentication = exports2.OAuth2Client = exports2.CodeChallengeMethod = exports2.Impersonated = exports2.JWT = exports2.JWTAccess = exports2.IdTokenClient = exports2.IAMAuth = exports2.GCPEnv = exports2.Compute = exports2.DEFAULT_UNIVERSE = exports2.AuthClient = exports2.gaxios = exports2.gcpMetadata = void 0;
    var googleauth_1 = require_googleauth();
    Object.defineProperty(exports2, "GoogleAuth", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return googleauth_1.GoogleAuth;
    }, "get") });
    exports2.gcpMetadata = require_src4();
    exports2.gaxios = require_src2();
    var authclient_1 = require_authclient();
    Object.defineProperty(exports2, "AuthClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return authclient_1.AuthClient;
    }, "get") });
    Object.defineProperty(exports2, "DEFAULT_UNIVERSE", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return authclient_1.DEFAULT_UNIVERSE;
    }, "get") });
    var computeclient_1 = require_computeclient();
    Object.defineProperty(exports2, "Compute", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return computeclient_1.Compute;
    }, "get") });
    var envDetect_1 = require_envDetect();
    Object.defineProperty(exports2, "GCPEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return envDetect_1.GCPEnv;
    }, "get") });
    var iam_1 = require_iam();
    Object.defineProperty(exports2, "IAMAuth", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return iam_1.IAMAuth;
    }, "get") });
    var idtokenclient_1 = require_idtokenclient();
    Object.defineProperty(exports2, "IdTokenClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return idtokenclient_1.IdTokenClient;
    }, "get") });
    var jwtaccess_1 = require_jwtaccess();
    Object.defineProperty(exports2, "JWTAccess", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return jwtaccess_1.JWTAccess;
    }, "get") });
    var jwtclient_1 = require_jwtclient();
    Object.defineProperty(exports2, "JWT", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return jwtclient_1.JWT;
    }, "get") });
    var impersonated_1 = require_impersonated();
    Object.defineProperty(exports2, "Impersonated", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return impersonated_1.Impersonated;
    }, "get") });
    var oauth2client_1 = require_oauth2client();
    Object.defineProperty(exports2, "CodeChallengeMethod", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return oauth2client_1.CodeChallengeMethod;
    }, "get") });
    Object.defineProperty(exports2, "OAuth2Client", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return oauth2client_1.OAuth2Client;
    }, "get") });
    Object.defineProperty(exports2, "ClientAuthentication", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return oauth2client_1.ClientAuthentication;
    }, "get") });
    var loginticket_1 = require_loginticket();
    Object.defineProperty(exports2, "LoginTicket", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return loginticket_1.LoginTicket;
    }, "get") });
    var refreshclient_1 = require_refreshclient();
    Object.defineProperty(exports2, "UserRefreshClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return refreshclient_1.UserRefreshClient;
    }, "get") });
    var awsclient_1 = require_awsclient();
    Object.defineProperty(exports2, "AwsClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return awsclient_1.AwsClient;
    }, "get") });
    var awsrequestsigner_1 = require_awsrequestsigner();
    Object.defineProperty(exports2, "AwsRequestSigner", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return awsrequestsigner_1.AwsRequestSigner;
    }, "get") });
    var identitypoolclient_1 = require_identitypoolclient();
    Object.defineProperty(exports2, "IdentityPoolClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return identitypoolclient_1.IdentityPoolClient;
    }, "get") });
    var externalclient_1 = require_externalclient();
    Object.defineProperty(exports2, "ExternalAccountClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return externalclient_1.ExternalAccountClient;
    }, "get") });
    var baseexternalclient_1 = require_baseexternalclient();
    Object.defineProperty(exports2, "BaseExternalAccountClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return baseexternalclient_1.BaseExternalAccountClient;
    }, "get") });
    var downscopedclient_1 = require_downscopedclient();
    Object.defineProperty(exports2, "DownscopedClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return downscopedclient_1.DownscopedClient;
    }, "get") });
    var pluggable_auth_client_1 = require_pluggable_auth_client();
    Object.defineProperty(exports2, "PluggableAuthClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return pluggable_auth_client_1.PluggableAuthClient;
    }, "get") });
    Object.defineProperty(exports2, "ExecutableError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return pluggable_auth_client_1.ExecutableError;
    }, "get") });
    var passthrough_1 = require_passthrough();
    Object.defineProperty(exports2, "PassThroughClient", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return passthrough_1.PassThroughClient;
    }, "get") });
    var transporters_1 = require_transporters();
    Object.defineProperty(exports2, "DefaultTransporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return transporters_1.DefaultTransporter;
    }, "get") });
    var auth2 = new googleauth_1.GoogleAuth();
    exports2.auth = auth2;
  }
});

// node_modules/@google/genai/dist/node/index.mjs
import { createWriteStream, writeFile } from "fs";
import { Readable } from "node:stream";
import * as fs3 from "fs/promises";
function getDefaultBaseUrls() {
  return {
    geminiUrl: _defaultBaseGeminiUrl,
    vertexUrl: _defaultBaseVertexUrl
  };
}
function getBaseUrl(httpOptions, vertexai, vertexBaseUrlFromEnv, geminiBaseUrlFromEnv) {
  var _a6, _b2;
  if (!(httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.baseUrl)) {
    const defaultBaseUrls = getDefaultBaseUrls();
    if (vertexai) {
      return (_a6 = defaultBaseUrls.vertexUrl) !== null && _a6 !== void 0 ? _a6 : vertexBaseUrlFromEnv;
    } else {
      return (_b2 = defaultBaseUrls.geminiUrl) !== null && _b2 !== void 0 ? _b2 : geminiBaseUrlFromEnv;
    }
  }
  return httpOptions.baseUrl;
}
function formatMap(templateString2, valueMap) {
  const regex3 = /\{([^}]+)\}/g;
  return templateString2.replace(regex3, (match2, key) => {
    if (Object.prototype.hasOwnProperty.call(valueMap, key)) {
      const value = valueMap[key];
      return value !== void 0 && value !== null ? String(value) : "";
    } else {
      throw new Error(`Key '${key}' not found in valueMap.`);
    }
  });
}
function setValueByPath(data, keys, value) {
  for (let i = 0; i < keys.length - 1; i++) {
    const key = keys[i];
    if (key.endsWith("[]")) {
      const keyName2 = key.slice(0, -2);
      if (!(keyName2 in data)) {
        if (Array.isArray(value)) {
          data[keyName2] = Array.from({ length: value.length }, () => ({}));
        } else {
          throw new Error(`Value must be a list given an array path ${key}`);
        }
      }
      if (Array.isArray(data[keyName2])) {
        const arrayData = data[keyName2];
        if (Array.isArray(value)) {
          for (let j = 0; j < arrayData.length; j++) {
            const entry = arrayData[j];
            setValueByPath(entry, keys.slice(i + 1), value[j]);
          }
        } else {
          for (const d of arrayData) {
            setValueByPath(d, keys.slice(i + 1), value);
          }
        }
      }
      return;
    } else if (key.endsWith("[0]")) {
      const keyName2 = key.slice(0, -3);
      if (!(keyName2 in data)) {
        data[keyName2] = [{}];
      }
      const arrayData = data[keyName2];
      setValueByPath(arrayData[0], keys.slice(i + 1), value);
      return;
    }
    if (!data[key] || typeof data[key] !== "object") {
      data[key] = {};
    }
    data = data[key];
  }
  const keyToSet = keys[keys.length - 1];
  const existingData = data[keyToSet];
  if (existingData !== void 0) {
    if (!value || typeof value === "object" && Object.keys(value).length === 0) {
      return;
    }
    if (value === existingData) {
      return;
    }
    if (typeof existingData === "object" && typeof value === "object" && existingData !== null && value !== null) {
      Object.assign(existingData, value);
    } else {
      throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`);
    }
  } else {
    data[keyToSet] = value;
  }
}
function getValueByPath(data, keys) {
  try {
    if (keys.length === 1 && keys[0] === "_self") {
      return data;
    }
    for (let i = 0; i < keys.length; i++) {
      if (typeof data !== "object" || data === null) {
        return void 0;
      }
      const key = keys[i];
      if (key.endsWith("[]")) {
        const keyName2 = key.slice(0, -2);
        if (keyName2 in data) {
          const arrayData = data[keyName2];
          if (!Array.isArray(arrayData)) {
            return void 0;
          }
          return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1)));
        } else {
          return void 0;
        }
      } else {
        data = data[key];
      }
    }
    return data;
  } catch (error) {
    if (error instanceof TypeError) {
      return void 0;
    }
    throw error;
  }
}
function tBytes$1(fromBytes) {
  if (typeof fromBytes !== "string") {
    throw new Error("fromImageBytes must be a string");
  }
  return fromBytes;
}
function createPartFromText(text) {
  return {
    text
  };
}
function _isPart(obj) {
  if (typeof obj === "object" && obj !== null) {
    return "fileData" in obj || "text" in obj || "functionCall" in obj || "functionResponse" in obj || "inlineData" in obj || "videoMetadata" in obj || "codeExecutionResult" in obj || "executableCode" in obj;
  }
  return false;
}
function _toParts(partOrString) {
  const parts = [];
  if (typeof partOrString === "string") {
    parts.push(createPartFromText(partOrString));
  } else if (_isPart(partOrString)) {
    parts.push(partOrString);
  } else if (Array.isArray(partOrString)) {
    if (partOrString.length === 0) {
      throw new Error("partOrString cannot be an empty array");
    }
    for (const part of partOrString) {
      if (typeof part === "string") {
        parts.push(createPartFromText(part));
      } else if (_isPart(part)) {
        parts.push(part);
      } else {
        throw new Error("element in PartUnion must be a Part object or string");
      }
    }
  } else {
    throw new Error("partOrString must be a Part object, string, or array");
  }
  return parts;
}
function createUserContent(partOrString) {
  return {
    role: "user",
    parts: _toParts(partOrString)
  };
}
function tModel(apiClient, model) {
  if (!model || typeof model !== "string") {
    throw new Error("model is required and must be a string");
  }
  if (apiClient.isVertexAI()) {
    if (model.startsWith("publishers/") || model.startsWith("projects/") || model.startsWith("models/")) {
      return model;
    } else if (model.indexOf("/") >= 0) {
      const parts = model.split("/", 2);
      return `publishers/${parts[0]}/models/${parts[1]}`;
    } else {
      return `publishers/google/models/${model}`;
    }
  } else {
    if (model.startsWith("models/") || model.startsWith("tunedModels/")) {
      return model;
    } else {
      return `models/${model}`;
    }
  }
}
function tCachesModel(apiClient, model) {
  const transformedModel = tModel(apiClient, model);
  if (!transformedModel) {
    return "";
  }
  if (transformedModel.startsWith("publishers/") && apiClient.isVertexAI()) {
    return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`;
  } else if (transformedModel.startsWith("models/") && apiClient.isVertexAI()) {
    return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`;
  } else {
    return transformedModel;
  }
}
function tBlobs(blobs) {
  if (Array.isArray(blobs)) {
    return blobs.map((blob) => tBlob(blob));
  } else {
    return [tBlob(blobs)];
  }
}
function tBlob(blob) {
  if (typeof blob === "object" && blob !== null) {
    return blob;
  }
  throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof blob}`);
}
function tImageBlob(blob) {
  const transformedBlob = tBlob(blob);
  if (transformedBlob.mimeType && transformedBlob.mimeType.startsWith("image/")) {
    return transformedBlob;
  }
  throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`);
}
function tAudioBlob(blob) {
  const transformedBlob = tBlob(blob);
  if (transformedBlob.mimeType && transformedBlob.mimeType.startsWith("audio/")) {
    return transformedBlob;
  }
  throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`);
}
function tPart(origin) {
  if (origin === null || origin === void 0) {
    throw new Error("PartUnion is required");
  }
  if (typeof origin === "object") {
    return origin;
  }
  if (typeof origin === "string") {
    return { text: origin };
  }
  throw new Error(`Unsupported part type: ${typeof origin}`);
}
function tParts(origin) {
  if (origin === null || origin === void 0 || Array.isArray(origin) && origin.length === 0) {
    throw new Error("PartListUnion is required");
  }
  if (Array.isArray(origin)) {
    return origin.map((item) => tPart(item));
  }
  return [tPart(origin)];
}
function _isContent(origin) {
  return origin !== null && origin !== void 0 && typeof origin === "object" && "parts" in origin && Array.isArray(origin.parts);
}
function _isFunctionCallPart(origin) {
  return origin !== null && origin !== void 0 && typeof origin === "object" && "functionCall" in origin;
}
function _isFunctionResponsePart(origin) {
  return origin !== null && origin !== void 0 && typeof origin === "object" && "functionResponse" in origin;
}
function tContent(origin) {
  if (origin === null || origin === void 0) {
    throw new Error("ContentUnion is required");
  }
  if (_isContent(origin)) {
    return origin;
  }
  return {
    role: "user",
    parts: tParts(origin)
  };
}
function tContentsForEmbed(apiClient, origin) {
  if (!origin) {
    return [];
  }
  if (apiClient.isVertexAI() && Array.isArray(origin)) {
    return origin.flatMap((item) => {
      const content = tContent(item);
      if (content.parts && content.parts.length > 0 && content.parts[0].text !== void 0) {
        return [content.parts[0].text];
      }
      return [];
    });
  } else if (apiClient.isVertexAI()) {
    const content = tContent(origin);
    if (content.parts && content.parts.length > 0 && content.parts[0].text !== void 0) {
      return [content.parts[0].text];
    }
    return [];
  }
  if (Array.isArray(origin)) {
    return origin.map((item) => tContent(item));
  }
  return [tContent(origin)];
}
function tContents(origin) {
  if (origin === null || origin === void 0 || Array.isArray(origin) && origin.length === 0) {
    throw new Error("contents are required");
  }
  if (!Array.isArray(origin)) {
    if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) {
      throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");
    }
    return [tContent(origin)];
  }
  const result = [];
  const accumulatedParts = [];
  const isContentArray = _isContent(origin[0]);
  for (const item of origin) {
    const isContent = _isContent(item);
    if (isContent != isContentArray) {
      throw new Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");
    }
    if (isContent) {
      result.push(item);
    } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) {
      throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");
    } else {
      accumulatedParts.push(item);
    }
  }
  if (!isContentArray) {
    result.push({ role: "user", parts: tParts(accumulatedParts) });
  }
  return result;
}
function flattenTypeArrayToAnyOf(typeList, resultingSchema) {
  if (typeList.includes("null")) {
    resultingSchema["nullable"] = true;
  }
  const listWithoutNull = typeList.filter((type) => type !== "null");
  if (listWithoutNull.length === 1) {
    resultingSchema["type"] = Object.values(Type).includes(listWithoutNull[0].toUpperCase()) ? listWithoutNull[0].toUpperCase() : Type.TYPE_UNSPECIFIED;
  } else {
    resultingSchema["anyOf"] = [];
    for (const i of listWithoutNull) {
      resultingSchema["anyOf"].push({
        "type": Object.values(Type).includes(i.toUpperCase()) ? i.toUpperCase() : Type.TYPE_UNSPECIFIED
      });
    }
  }
}
function processJsonSchema(_jsonSchema) {
  const genAISchema = {};
  const schemaFieldNames = ["items"];
  const listSchemaFieldNames = ["anyOf"];
  const dictSchemaFieldNames = ["properties"];
  if (_jsonSchema["type"] && _jsonSchema["anyOf"]) {
    throw new Error("type and anyOf cannot be both populated.");
  }
  const incomingAnyOf = _jsonSchema["anyOf"];
  if (incomingAnyOf != null && incomingAnyOf.length == 2) {
    if (incomingAnyOf[0]["type"] === "null") {
      genAISchema["nullable"] = true;
      _jsonSchema = incomingAnyOf[1];
    } else if (incomingAnyOf[1]["type"] === "null") {
      genAISchema["nullable"] = true;
      _jsonSchema = incomingAnyOf[0];
    }
  }
  if (_jsonSchema["type"] instanceof Array) {
    flattenTypeArrayToAnyOf(_jsonSchema["type"], genAISchema);
  }
  for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) {
    if (fieldValue == null) {
      continue;
    }
    if (fieldName == "type") {
      if (fieldValue === "null") {
        throw new Error("type: null can not be the only possible type for the field.");
      }
      if (fieldValue instanceof Array) {
        continue;
      }
      genAISchema["type"] = Object.values(Type).includes(fieldValue.toUpperCase()) ? fieldValue.toUpperCase() : Type.TYPE_UNSPECIFIED;
    } else if (schemaFieldNames.includes(fieldName)) {
      genAISchema[fieldName] = processJsonSchema(fieldValue);
    } else if (listSchemaFieldNames.includes(fieldName)) {
      const listSchemaFieldValue = [];
      for (const item of fieldValue) {
        if (item["type"] == "null") {
          genAISchema["nullable"] = true;
          continue;
        }
        listSchemaFieldValue.push(processJsonSchema(item));
      }
      genAISchema[fieldName] = listSchemaFieldValue;
    } else if (dictSchemaFieldNames.includes(fieldName)) {
      const dictSchemaFieldValue = {};
      for (const [key, value] of Object.entries(fieldValue)) {
        dictSchemaFieldValue[key] = processJsonSchema(value);
      }
      genAISchema[fieldName] = dictSchemaFieldValue;
    } else {
      if (fieldName === "additionalProperties") {
        continue;
      }
      genAISchema[fieldName] = fieldValue;
    }
  }
  return genAISchema;
}
function tSchema(schema) {
  return processJsonSchema(schema);
}
function tSpeechConfig(speechConfig) {
  if (typeof speechConfig === "object") {
    return speechConfig;
  } else if (typeof speechConfig === "string") {
    return {
      voiceConfig: {
        prebuiltVoiceConfig: {
          voiceName: speechConfig
        }
      }
    };
  } else {
    throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`);
  }
}
function tLiveSpeechConfig(speechConfig) {
  if ("multiSpeakerVoiceConfig" in speechConfig) {
    throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");
  }
  return speechConfig;
}
function tTool(tool) {
  if (tool.functionDeclarations) {
    for (const functionDeclaration of tool.functionDeclarations) {
      if (functionDeclaration.parameters) {
        if (!Object.keys(functionDeclaration.parameters).includes("$schema")) {
          functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters);
        } else {
          if (!functionDeclaration.parametersJsonSchema) {
            functionDeclaration.parametersJsonSchema = functionDeclaration.parameters;
            delete functionDeclaration.parameters;
          }
        }
      }
      if (functionDeclaration.response) {
        if (!Object.keys(functionDeclaration.response).includes("$schema")) {
          functionDeclaration.response = processJsonSchema(functionDeclaration.response);
        } else {
          if (!functionDeclaration.responseJsonSchema) {
            functionDeclaration.responseJsonSchema = functionDeclaration.response;
            delete functionDeclaration.response;
          }
        }
      }
    }
  }
  return tool;
}
function tTools(tools) {
  if (tools === void 0 || tools === null) {
    throw new Error("tools is required");
  }
  if (!Array.isArray(tools)) {
    throw new Error("tools is required and must be an array of Tools");
  }
  const result = [];
  for (const tool of tools) {
    result.push(tool);
  }
  return result;
}
function resourceName(client, resourceName2, resourcePrefix, splitsAfterPrefix = 1) {
  const shouldAppendPrefix = !resourceName2.startsWith(`${resourcePrefix}/`) && resourceName2.split("/").length === splitsAfterPrefix;
  if (client.isVertexAI()) {
    if (resourceName2.startsWith("projects/")) {
      return resourceName2;
    } else if (resourceName2.startsWith("locations/")) {
      return `projects/${client.getProject()}/${resourceName2}`;
    } else if (resourceName2.startsWith(`${resourcePrefix}/`)) {
      return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName2}`;
    } else if (shouldAppendPrefix) {
      return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName2}`;
    } else {
      return resourceName2;
    }
  }
  if (shouldAppendPrefix) {
    return `${resourcePrefix}/${resourceName2}`;
  }
  return resourceName2;
}
function tCachedContentName(apiClient, name3) {
  if (typeof name3 !== "string") {
    throw new Error("name must be a string");
  }
  return resourceName(apiClient, name3, "cachedContents");
}
function tTuningJobStatus(status) {
  switch (status) {
    case "STATE_UNSPECIFIED":
      return "JOB_STATE_UNSPECIFIED";
    case "CREATING":
      return "JOB_STATE_RUNNING";
    case "ACTIVE":
      return "JOB_STATE_SUCCEEDED";
    case "FAILED":
      return "JOB_STATE_FAILED";
    default:
      return status;
  }
}
function tBytes(fromImageBytes) {
  return tBytes$1(fromImageBytes);
}
function _isFile(origin) {
  return origin !== null && origin !== void 0 && typeof origin === "object" && "name" in origin;
}
function isGeneratedVideo(origin) {
  return origin !== null && origin !== void 0 && typeof origin === "object" && "video" in origin;
}
function isVideo(origin) {
  return origin !== null && origin !== void 0 && typeof origin === "object" && "uri" in origin;
}
function tFileName(fromName) {
  var _a6;
  let name3;
  if (_isFile(fromName)) {
    name3 = fromName.name;
  }
  if (isVideo(fromName)) {
    name3 = fromName.uri;
    if (name3 === void 0) {
      return void 0;
    }
  }
  if (isGeneratedVideo(fromName)) {
    name3 = (_a6 = fromName.video) === null || _a6 === void 0 ? void 0 : _a6.uri;
    if (name3 === void 0) {
      return void 0;
    }
  }
  if (typeof fromName === "string") {
    name3 = fromName;
  }
  if (name3 === void 0) {
    throw new Error("Could not extract file name from the provided input.");
  }
  if (name3.startsWith("https://")) {
    const suffix = name3.split("files/")[1];
    const match2 = suffix.match(/[a-z0-9]+/);
    if (match2 === null) {
      throw new Error(`Could not extract file name from URI ${name3}`);
    }
    name3 = match2[0];
  } else if (name3.startsWith("files/")) {
    name3 = name3.split("files/")[1];
  }
  return name3;
}
function tModelsUrl(apiClient, baseModels) {
  let res;
  if (apiClient.isVertexAI()) {
    res = baseModels ? "publishers/google/models" : "models";
  } else {
    res = baseModels ? "models" : "tunedModels";
  }
  return res;
}
function tExtractModels(response) {
  for (const key of ["models", "tunedModels", "publisherModels"]) {
    if (hasField(response, key)) {
      return response[key];
    }
  }
  return [];
}
function hasField(data, fieldName) {
  return data !== null && typeof data === "object" && fieldName in data;
}
function mcpToGeminiTool(mcpTool, config = {}) {
  const mcpToolSchema = mcpTool;
  const functionDeclaration = {
    name: mcpToolSchema["name"],
    description: mcpToolSchema["description"],
    parametersJsonSchema: mcpToolSchema["inputSchema"]
  };
  if (mcpToolSchema["outputSchema"]) {
    functionDeclaration["responseJsonSchema"] = mcpToolSchema["outputSchema"];
  }
  if (config.behavior) {
    functionDeclaration["behavior"] = config.behavior;
  }
  const geminiTool = {
    functionDeclarations: [
      functionDeclaration
    ]
  };
  return geminiTool;
}
function mcpToolsToGeminiTool(mcpTools, config = {}) {
  const functionDeclarations = [];
  const toolNames = /* @__PURE__ */ new Set();
  for (const mcpTool of mcpTools) {
    const mcpToolName = mcpTool.name;
    if (toolNames.has(mcpToolName)) {
      throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);
    }
    toolNames.add(mcpToolName);
    const geminiTool = mcpToGeminiTool(mcpTool, config);
    if (geminiTool.functionDeclarations) {
      functionDeclarations.push(...geminiTool.functionDeclarations);
    }
  }
  return { functionDeclarations };
}
function tBatchJobSource(apiClient, src) {
  if (typeof src !== "string" && !Array.isArray(src)) {
    if (apiClient && apiClient.isVertexAI()) {
      if (src.gcsUri && src.bigqueryUri) {
        throw new Error("Only one of `gcsUri` or `bigqueryUri` can be set.");
      } else if (!src.gcsUri && !src.bigqueryUri) {
        throw new Error("One of `gcsUri` or `bigqueryUri` must be set.");
      }
    } else {
      if (src.inlinedRequests && src.fileName) {
        throw new Error("Only one of `inlinedRequests` or `fileName` can be set.");
      } else if (!src.inlinedRequests && !src.fileName) {
        throw new Error("One of `inlinedRequests` or `fileName` must be set.");
      }
    }
    return src;
  } else if (Array.isArray(src)) {
    return { inlinedRequests: src };
  } else if (typeof src === "string") {
    if (src.startsWith("gs://")) {
      return {
        format: "jsonl",
        gcsUri: [src]
        // GCS URI is expected as an array
      };
    } else if (src.startsWith("bq://")) {
      return {
        format: "bigquery",
        bigqueryUri: src
      };
    } else if (src.startsWith("files/")) {
      return {
        fileName: src
      };
    }
  }
  throw new Error(`Unsupported source: ${src}`);
}
function tBatchJobDestination(dest) {
  if (typeof dest !== "string") {
    return dest;
  }
  const destString = dest;
  if (destString.startsWith("gs://")) {
    return {
      format: "jsonl",
      gcsUri: destString
    };
  } else if (destString.startsWith("bq://")) {
    return {
      format: "bigquery",
      bigqueryUri: destString
    };
  } else {
    throw new Error(`Unsupported destination: ${destString}`);
  }
}
function tBatchJobName(apiClient, name3) {
  const nameString = name3;
  if (!apiClient.isVertexAI()) {
    const mldevPattern = /batches\/[^/]+$/;
    if (mldevPattern.test(nameString)) {
      return nameString.split("/").pop();
    } else {
      throw new Error(`Invalid batch job name: ${nameString}.`);
    }
  }
  const vertexPattern = /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/;
  if (vertexPattern.test(nameString)) {
    return nameString.split("/").pop();
  } else if (/^\d+$/.test(nameString)) {
    return nameString;
  } else {
    throw new Error(`Invalid batch job name: ${nameString}.`);
  }
}
function tJobState(state) {
  const stateString = state;
  if (stateString === "BATCH_STATE_UNSPECIFIED") {
    return "JOB_STATE_UNSPECIFIED";
  } else if (stateString === "BATCH_STATE_PENDING") {
    return "JOB_STATE_PENDING";
  } else if (stateString === "BATCH_STATE_SUCCEEDED") {
    return "JOB_STATE_SUCCEEDED";
  } else if (stateString === "BATCH_STATE_FAILED") {
    return "JOB_STATE_FAILED";
  } else if (stateString === "BATCH_STATE_CANCELLED") {
    return "JOB_STATE_CANCELLED";
  } else {
    return stateString;
  }
}
function videoMetadataToMldev$4(fromObject) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobToMldev$4(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataToMldev$4(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromFileUri = getValueByPath(fromObject, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function partToMldev$4(fromObject) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataToMldev$4(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev$4(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev$4(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromCodeExecutionResult = getValueByPath(fromObject, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], fromFunctionCall);
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentToMldev$4(fromObject) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToMldev$4(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function schemaToMldev$1(fromObject) {
  const toObject = {};
  const fromAnyOf = getValueByPath(fromObject, ["anyOf"]);
  if (fromAnyOf != null) {
    setValueByPath(toObject, ["anyOf"], fromAnyOf);
  }
  const fromDefault = getValueByPath(fromObject, ["default"]);
  if (fromDefault != null) {
    setValueByPath(toObject, ["default"], fromDefault);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromEnum = getValueByPath(fromObject, ["enum"]);
  if (fromEnum != null) {
    setValueByPath(toObject, ["enum"], fromEnum);
  }
  const fromExample = getValueByPath(fromObject, ["example"]);
  if (fromExample != null) {
    setValueByPath(toObject, ["example"], fromExample);
  }
  const fromFormat = getValueByPath(fromObject, ["format"]);
  if (fromFormat != null) {
    setValueByPath(toObject, ["format"], fromFormat);
  }
  const fromItems = getValueByPath(fromObject, ["items"]);
  if (fromItems != null) {
    setValueByPath(toObject, ["items"], fromItems);
  }
  const fromMaxItems = getValueByPath(fromObject, ["maxItems"]);
  if (fromMaxItems != null) {
    setValueByPath(toObject, ["maxItems"], fromMaxItems);
  }
  const fromMaxLength = getValueByPath(fromObject, ["maxLength"]);
  if (fromMaxLength != null) {
    setValueByPath(toObject, ["maxLength"], fromMaxLength);
  }
  const fromMaxProperties = getValueByPath(fromObject, [
    "maxProperties"
  ]);
  if (fromMaxProperties != null) {
    setValueByPath(toObject, ["maxProperties"], fromMaxProperties);
  }
  const fromMaximum = getValueByPath(fromObject, ["maximum"]);
  if (fromMaximum != null) {
    setValueByPath(toObject, ["maximum"], fromMaximum);
  }
  const fromMinItems = getValueByPath(fromObject, ["minItems"]);
  if (fromMinItems != null) {
    setValueByPath(toObject, ["minItems"], fromMinItems);
  }
  const fromMinLength = getValueByPath(fromObject, ["minLength"]);
  if (fromMinLength != null) {
    setValueByPath(toObject, ["minLength"], fromMinLength);
  }
  const fromMinProperties = getValueByPath(fromObject, [
    "minProperties"
  ]);
  if (fromMinProperties != null) {
    setValueByPath(toObject, ["minProperties"], fromMinProperties);
  }
  const fromMinimum = getValueByPath(fromObject, ["minimum"]);
  if (fromMinimum != null) {
    setValueByPath(toObject, ["minimum"], fromMinimum);
  }
  const fromNullable = getValueByPath(fromObject, ["nullable"]);
  if (fromNullable != null) {
    setValueByPath(toObject, ["nullable"], fromNullable);
  }
  const fromPattern = getValueByPath(fromObject, ["pattern"]);
  if (fromPattern != null) {
    setValueByPath(toObject, ["pattern"], fromPattern);
  }
  const fromProperties = getValueByPath(fromObject, ["properties"]);
  if (fromProperties != null) {
    setValueByPath(toObject, ["properties"], fromProperties);
  }
  const fromPropertyOrdering = getValueByPath(fromObject, [
    "propertyOrdering"
  ]);
  if (fromPropertyOrdering != null) {
    setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering);
  }
  const fromRequired = getValueByPath(fromObject, ["required"]);
  if (fromRequired != null) {
    setValueByPath(toObject, ["required"], fromRequired);
  }
  const fromTitle = getValueByPath(fromObject, ["title"]);
  if (fromTitle != null) {
    setValueByPath(toObject, ["title"], fromTitle);
  }
  const fromType = getValueByPath(fromObject, ["type"]);
  if (fromType != null) {
    setValueByPath(toObject, ["type"], fromType);
  }
  return toObject;
}
function safetySettingToMldev$1(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["method"]) !== void 0) {
    throw new Error("method parameter is not supported in Gemini API.");
  }
  const fromCategory = getValueByPath(fromObject, ["category"]);
  if (fromCategory != null) {
    setValueByPath(toObject, ["category"], fromCategory);
  }
  const fromThreshold = getValueByPath(fromObject, ["threshold"]);
  if (fromThreshold != null) {
    setValueByPath(toObject, ["threshold"], fromThreshold);
  }
  return toObject;
}
function functionDeclarationToMldev$4(fromObject) {
  const toObject = {};
  const fromBehavior = getValueByPath(fromObject, ["behavior"]);
  if (fromBehavior != null) {
    setValueByPath(toObject, ["behavior"], fromBehavior);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  return toObject;
}
function intervalToMldev$4(fromObject) {
  const toObject = {};
  const fromStartTime = getValueByPath(fromObject, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  return toObject;
}
function googleSearchToMldev$4(fromObject) {
  const toObject = {};
  const fromTimeRangeFilter = getValueByPath(fromObject, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], intervalToMldev$4(fromTimeRangeFilter));
  }
  if (getValueByPath(fromObject, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  return toObject;
}
function dynamicRetrievalConfigToMldev$4(fromObject) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromDynamicThreshold = getValueByPath(fromObject, [
    "dynamicThreshold"
  ]);
  if (fromDynamicThreshold != null) {
    setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold);
  }
  return toObject;
}
function googleSearchRetrievalToMldev$4(fromObject) {
  const toObject = {};
  const fromDynamicRetrievalConfig = getValueByPath(fromObject, [
    "dynamicRetrievalConfig"
  ]);
  if (fromDynamicRetrievalConfig != null) {
    setValueByPath(toObject, ["dynamicRetrievalConfig"], dynamicRetrievalConfigToMldev$4(fromDynamicRetrievalConfig));
  }
  return toObject;
}
function urlContextToMldev$4() {
  const toObject = {};
  return toObject;
}
function toolComputerUseToMldev$4(fromObject) {
  const toObject = {};
  const fromEnvironment = getValueByPath(fromObject, ["environment"]);
  if (fromEnvironment != null) {
    setValueByPath(toObject, ["environment"], fromEnvironment);
  }
  return toObject;
}
function toolToMldev$4(fromObject) {
  const toObject = {};
  const fromFunctionDeclarations = getValueByPath(fromObject, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToMldev$4(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  if (getValueByPath(fromObject, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$4(fromGoogleSearch));
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], googleSearchRetrievalToMldev$4(fromGoogleSearchRetrieval));
  }
  if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["googleMaps"]) !== void 0) {
    throw new Error("googleMaps parameter is not supported in Gemini API.");
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], urlContextToMldev$4());
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], toolComputerUseToMldev$4(fromComputerUse));
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  return toObject;
}
function functionCallingConfigToMldev$2(fromObject) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromAllowedFunctionNames = getValueByPath(fromObject, [
    "allowedFunctionNames"
  ]);
  if (fromAllowedFunctionNames != null) {
    setValueByPath(toObject, ["allowedFunctionNames"], fromAllowedFunctionNames);
  }
  return toObject;
}
function latLngToMldev$2(fromObject) {
  const toObject = {};
  const fromLatitude = getValueByPath(fromObject, ["latitude"]);
  if (fromLatitude != null) {
    setValueByPath(toObject, ["latitude"], fromLatitude);
  }
  const fromLongitude = getValueByPath(fromObject, ["longitude"]);
  if (fromLongitude != null) {
    setValueByPath(toObject, ["longitude"], fromLongitude);
  }
  return toObject;
}
function retrievalConfigToMldev$2(fromObject) {
  const toObject = {};
  const fromLatLng = getValueByPath(fromObject, ["latLng"]);
  if (fromLatLng != null) {
    setValueByPath(toObject, ["latLng"], latLngToMldev$2(fromLatLng));
  }
  const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function toolConfigToMldev$2(fromObject) {
  const toObject = {};
  const fromFunctionCallingConfig = getValueByPath(fromObject, [
    "functionCallingConfig"
  ]);
  if (fromFunctionCallingConfig != null) {
    setValueByPath(toObject, ["functionCallingConfig"], functionCallingConfigToMldev$2(fromFunctionCallingConfig));
  }
  const fromRetrievalConfig = getValueByPath(fromObject, [
    "retrievalConfig"
  ]);
  if (fromRetrievalConfig != null) {
    setValueByPath(toObject, ["retrievalConfig"], retrievalConfigToMldev$2(fromRetrievalConfig));
  }
  return toObject;
}
function prebuiltVoiceConfigToMldev$3(fromObject) {
  const toObject = {};
  const fromVoiceName = getValueByPath(fromObject, ["voiceName"]);
  if (fromVoiceName != null) {
    setValueByPath(toObject, ["voiceName"], fromVoiceName);
  }
  return toObject;
}
function voiceConfigToMldev$3(fromObject) {
  const toObject = {};
  const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [
    "prebuiltVoiceConfig"
  ]);
  if (fromPrebuiltVoiceConfig != null) {
    setValueByPath(toObject, ["prebuiltVoiceConfig"], prebuiltVoiceConfigToMldev$3(fromPrebuiltVoiceConfig));
  }
  return toObject;
}
function speakerVoiceConfigToMldev$3(fromObject) {
  const toObject = {};
  const fromSpeaker = getValueByPath(fromObject, ["speaker"]);
  if (fromSpeaker != null) {
    setValueByPath(toObject, ["speaker"], fromSpeaker);
  }
  const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToMldev$3(fromVoiceConfig));
  }
  return toObject;
}
function multiSpeakerVoiceConfigToMldev$3(fromObject) {
  const toObject = {};
  const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [
    "speakerVoiceConfigs"
  ]);
  if (fromSpeakerVoiceConfigs != null) {
    let transformedList = fromSpeakerVoiceConfigs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return speakerVoiceConfigToMldev$3(item);
      });
    }
    setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList);
  }
  return toObject;
}
function speechConfigToMldev$3(fromObject) {
  const toObject = {};
  const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToMldev$3(fromVoiceConfig));
  }
  const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [
    "multiSpeakerVoiceConfig"
  ]);
  if (fromMultiSpeakerVoiceConfig != null) {
    setValueByPath(toObject, ["multiSpeakerVoiceConfig"], multiSpeakerVoiceConfigToMldev$3(fromMultiSpeakerVoiceConfig));
  }
  const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function thinkingConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromIncludeThoughts = getValueByPath(fromObject, [
    "includeThoughts"
  ]);
  if (fromIncludeThoughts != null) {
    setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts);
  }
  const fromThinkingBudget = getValueByPath(fromObject, [
    "thinkingBudget"
  ]);
  if (fromThinkingBudget != null) {
    setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget);
  }
  return toObject;
}
function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) {
  const toObject = {};
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], contentToMldev$4(tContent(fromSystemInstruction)));
  }
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromTopP = getValueByPath(fromObject, ["topP"]);
  if (fromTopP != null) {
    setValueByPath(toObject, ["topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (fromTopK != null) {
    setValueByPath(toObject, ["topK"], fromTopK);
  }
  const fromCandidateCount = getValueByPath(fromObject, [
    "candidateCount"
  ]);
  if (fromCandidateCount != null) {
    setValueByPath(toObject, ["candidateCount"], fromCandidateCount);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject, [
    "maxOutputTokens"
  ]);
  if (fromMaxOutputTokens != null) {
    setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromStopSequences = getValueByPath(fromObject, [
    "stopSequences"
  ]);
  if (fromStopSequences != null) {
    setValueByPath(toObject, ["stopSequences"], fromStopSequences);
  }
  const fromResponseLogprobs = getValueByPath(fromObject, [
    "responseLogprobs"
  ]);
  if (fromResponseLogprobs != null) {
    setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs);
  }
  const fromLogprobs = getValueByPath(fromObject, ["logprobs"]);
  if (fromLogprobs != null) {
    setValueByPath(toObject, ["logprobs"], fromLogprobs);
  }
  const fromPresencePenalty = getValueByPath(fromObject, [
    "presencePenalty"
  ]);
  if (fromPresencePenalty != null) {
    setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty);
  }
  const fromFrequencyPenalty = getValueByPath(fromObject, [
    "frequencyPenalty"
  ]);
  if (fromFrequencyPenalty != null) {
    setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (fromSeed != null) {
    setValueByPath(toObject, ["seed"], fromSeed);
  }
  const fromResponseMimeType = getValueByPath(fromObject, [
    "responseMimeType"
  ]);
  if (fromResponseMimeType != null) {
    setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType);
  }
  const fromResponseSchema = getValueByPath(fromObject, [
    "responseSchema"
  ]);
  if (fromResponseSchema != null) {
    setValueByPath(toObject, ["responseSchema"], schemaToMldev$1(tSchema(fromResponseSchema)));
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  if (getValueByPath(fromObject, ["routingConfig"]) !== void 0) {
    throw new Error("routingConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["modelSelectionConfig"]) !== void 0) {
    throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");
  }
  const fromSafetySettings = getValueByPath(fromObject, [
    "safetySettings"
  ]);
  if (parentObject !== void 0 && fromSafetySettings != null) {
    let transformedList = fromSafetySettings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return safetySettingToMldev$1(item);
      });
    }
    setValueByPath(parentObject, ["safetySettings"], transformedList);
  }
  const fromTools = getValueByPath(fromObject, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = tTools(fromTools);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToMldev$4(tTool(item));
      });
    }
    setValueByPath(parentObject, ["tools"], transformedList);
  }
  const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]);
  if (parentObject !== void 0 && fromToolConfig != null) {
    setValueByPath(parentObject, ["toolConfig"], toolConfigToMldev$2(fromToolConfig));
  }
  if (getValueByPath(fromObject, ["labels"]) !== void 0) {
    throw new Error("labels parameter is not supported in Gemini API.");
  }
  const fromCachedContent = getValueByPath(fromObject, [
    "cachedContent"
  ]);
  if (parentObject !== void 0 && fromCachedContent != null) {
    setValueByPath(parentObject, ["cachedContent"], tCachedContentName(apiClient, fromCachedContent));
  }
  const fromResponseModalities = getValueByPath(fromObject, [
    "responseModalities"
  ]);
  if (fromResponseModalities != null) {
    setValueByPath(toObject, ["responseModalities"], fromResponseModalities);
  }
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]);
  if (fromSpeechConfig != null) {
    setValueByPath(toObject, ["speechConfig"], speechConfigToMldev$3(tSpeechConfig(fromSpeechConfig)));
  }
  if (getValueByPath(fromObject, ["audioTimestamp"]) !== void 0) {
    throw new Error("audioTimestamp parameter is not supported in Gemini API.");
  }
  const fromThinkingConfig = getValueByPath(fromObject, [
    "thinkingConfig"
  ]);
  if (fromThinkingConfig != null) {
    setValueByPath(toObject, ["thinkingConfig"], thinkingConfigToMldev$1(fromThinkingConfig));
  }
  return toObject;
}
function inlinedRequestToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["request", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToMldev$4(item);
      });
    }
    setValueByPath(toObject, ["request", "contents"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["request", "generationConfig"], generateContentConfigToMldev$1(apiClient, fromConfig, toObject));
  }
  return toObject;
}
function batchJobSourceToMldev(apiClient, fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["format"]) !== void 0) {
    throw new Error("format parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["gcsUri"]) !== void 0) {
    throw new Error("gcsUri parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["bigqueryUri"]) !== void 0) {
    throw new Error("bigqueryUri parameter is not supported in Gemini API.");
  }
  const fromFileName = getValueByPath(fromObject, ["fileName"]);
  if (fromFileName != null) {
    setValueByPath(toObject, ["fileName"], fromFileName);
  }
  const fromInlinedRequests = getValueByPath(fromObject, [
    "inlinedRequests"
  ]);
  if (fromInlinedRequests != null) {
    let transformedList = fromInlinedRequests;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return inlinedRequestToMldev(apiClient, item);
      });
    }
    setValueByPath(toObject, ["requests", "requests"], transformedList);
  }
  return toObject;
}
function createBatchJobConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["batch", "displayName"], fromDisplayName);
  }
  if (getValueByPath(fromObject, ["dest"]) !== void 0) {
    throw new Error("dest parameter is not supported in Gemini API.");
  }
  return toObject;
}
function createBatchJobParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromSrc = getValueByPath(fromObject, ["src"]);
  if (fromSrc != null) {
    setValueByPath(toObject, ["batch", "inputConfig"], batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc)));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], createBatchJobConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function getBatchJobParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function cancelBatchJobParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function listBatchJobsConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  if (getValueByPath(fromObject, ["filter"]) !== void 0) {
    throw new Error("filter parameter is not supported in Gemini API.");
  }
  return toObject;
}
function listBatchJobsParametersToMldev(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], listBatchJobsConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function deleteBatchJobParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function batchJobSourceToVertex(fromObject) {
  const toObject = {};
  const fromFormat = getValueByPath(fromObject, ["format"]);
  if (fromFormat != null) {
    setValueByPath(toObject, ["instancesFormat"], fromFormat);
  }
  const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["gcsSource", "uris"], fromGcsUri);
  }
  const fromBigqueryUri = getValueByPath(fromObject, ["bigqueryUri"]);
  if (fromBigqueryUri != null) {
    setValueByPath(toObject, ["bigquerySource", "inputUri"], fromBigqueryUri);
  }
  if (getValueByPath(fromObject, ["fileName"]) !== void 0) {
    throw new Error("fileName parameter is not supported in Vertex AI.");
  }
  if (getValueByPath(fromObject, ["inlinedRequests"]) !== void 0) {
    throw new Error("inlinedRequests parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function batchJobDestinationToVertex(fromObject) {
  const toObject = {};
  const fromFormat = getValueByPath(fromObject, ["format"]);
  if (fromFormat != null) {
    setValueByPath(toObject, ["predictionsFormat"], fromFormat);
  }
  const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["gcsDestination", "outputUriPrefix"], fromGcsUri);
  }
  const fromBigqueryUri = getValueByPath(fromObject, ["bigqueryUri"]);
  if (fromBigqueryUri != null) {
    setValueByPath(toObject, ["bigqueryDestination", "outputUri"], fromBigqueryUri);
  }
  if (getValueByPath(fromObject, ["fileName"]) !== void 0) {
    throw new Error("fileName parameter is not supported in Vertex AI.");
  }
  if (getValueByPath(fromObject, ["inlinedResponses"]) !== void 0) {
    throw new Error("inlinedResponses parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function createBatchJobConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  const fromDest = getValueByPath(fromObject, ["dest"]);
  if (parentObject !== void 0 && fromDest != null) {
    setValueByPath(parentObject, ["outputConfig"], batchJobDestinationToVertex(tBatchJobDestination(fromDest)));
  }
  return toObject;
}
function createBatchJobParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], tModel(apiClient, fromModel));
  }
  const fromSrc = getValueByPath(fromObject, ["src"]);
  if (fromSrc != null) {
    setValueByPath(toObject, ["inputConfig"], batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc)));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], createBatchJobConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function getBatchJobParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function cancelBatchJobParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function listBatchJobsConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  const fromFilter = getValueByPath(fromObject, ["filter"]);
  if (parentObject !== void 0 && fromFilter != null) {
    setValueByPath(parentObject, ["_query", "filter"], fromFilter);
  }
  return toObject;
}
function listBatchJobsParametersToVertex(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], listBatchJobsConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function deleteBatchJobParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function videoMetadataFromMldev$2(fromObject) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobFromMldev$2(fromObject) {
  const toObject = {};
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataFromMldev$2(fromObject) {
  const toObject = {};
  const fromFileUri = getValueByPath(fromObject, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function partFromMldev$2(fromObject) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataFromMldev$2(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobFromMldev$2(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataFromMldev$2(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromCodeExecutionResult = getValueByPath(fromObject, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], fromFunctionCall);
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentFromMldev$2(fromObject) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partFromMldev$2(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function citationMetadataFromMldev$1(fromObject) {
  const toObject = {};
  const fromCitations = getValueByPath(fromObject, ["citationSources"]);
  if (fromCitations != null) {
    setValueByPath(toObject, ["citations"], fromCitations);
  }
  return toObject;
}
function urlMetadataFromMldev$2(fromObject) {
  const toObject = {};
  const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]);
  if (fromRetrievedUrl != null) {
    setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl);
  }
  const fromUrlRetrievalStatus = getValueByPath(fromObject, [
    "urlRetrievalStatus"
  ]);
  if (fromUrlRetrievalStatus != null) {
    setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus);
  }
  return toObject;
}
function urlContextMetadataFromMldev$2(fromObject) {
  const toObject = {};
  const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]);
  if (fromUrlMetadata != null) {
    let transformedList = fromUrlMetadata;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return urlMetadataFromMldev$2(item);
      });
    }
    setValueByPath(toObject, ["urlMetadata"], transformedList);
  }
  return toObject;
}
function candidateFromMldev$1(fromObject) {
  const toObject = {};
  const fromContent = getValueByPath(fromObject, ["content"]);
  if (fromContent != null) {
    setValueByPath(toObject, ["content"], contentFromMldev$2(fromContent));
  }
  const fromCitationMetadata = getValueByPath(fromObject, [
    "citationMetadata"
  ]);
  if (fromCitationMetadata != null) {
    setValueByPath(toObject, ["citationMetadata"], citationMetadataFromMldev$1(fromCitationMetadata));
  }
  const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]);
  if (fromTokenCount != null) {
    setValueByPath(toObject, ["tokenCount"], fromTokenCount);
  }
  const fromFinishReason = getValueByPath(fromObject, ["finishReason"]);
  if (fromFinishReason != null) {
    setValueByPath(toObject, ["finishReason"], fromFinishReason);
  }
  const fromUrlContextMetadata = getValueByPath(fromObject, [
    "urlContextMetadata"
  ]);
  if (fromUrlContextMetadata != null) {
    setValueByPath(toObject, ["urlContextMetadata"], urlContextMetadataFromMldev$2(fromUrlContextMetadata));
  }
  const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]);
  if (fromAvgLogprobs != null) {
    setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs);
  }
  const fromGroundingMetadata = getValueByPath(fromObject, [
    "groundingMetadata"
  ]);
  if (fromGroundingMetadata != null) {
    setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata);
  }
  const fromIndex = getValueByPath(fromObject, ["index"]);
  if (fromIndex != null) {
    setValueByPath(toObject, ["index"], fromIndex);
  }
  const fromLogprobsResult = getValueByPath(fromObject, [
    "logprobsResult"
  ]);
  if (fromLogprobsResult != null) {
    setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult);
  }
  const fromSafetyRatings = getValueByPath(fromObject, [
    "safetyRatings"
  ]);
  if (fromSafetyRatings != null) {
    setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings);
  }
  return toObject;
}
function generateContentResponseFromMldev$1(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromCandidates = getValueByPath(fromObject, ["candidates"]);
  if (fromCandidates != null) {
    let transformedList = fromCandidates;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return candidateFromMldev$1(item);
      });
    }
    setValueByPath(toObject, ["candidates"], transformedList);
  }
  const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]);
  if (fromModelVersion != null) {
    setValueByPath(toObject, ["modelVersion"], fromModelVersion);
  }
  const fromPromptFeedback = getValueByPath(fromObject, [
    "promptFeedback"
  ]);
  if (fromPromptFeedback != null) {
    setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback);
  }
  const fromResponseId = getValueByPath(fromObject, ["responseId"]);
  if (fromResponseId != null) {
    setValueByPath(toObject, ["responseId"], fromResponseId);
  }
  const fromUsageMetadata = getValueByPath(fromObject, [
    "usageMetadata"
  ]);
  if (fromUsageMetadata != null) {
    setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata);
  }
  return toObject;
}
function jobErrorFromMldev(fromObject) {
  const toObject = {};
  const fromDetails = getValueByPath(fromObject, ["details"]);
  if (fromDetails != null) {
    setValueByPath(toObject, ["details"], fromDetails);
  }
  const fromCode = getValueByPath(fromObject, ["code"]);
  if (fromCode != null) {
    setValueByPath(toObject, ["code"], fromCode);
  }
  const fromMessage = getValueByPath(fromObject, ["message"]);
  if (fromMessage != null) {
    setValueByPath(toObject, ["message"], fromMessage);
  }
  return toObject;
}
function inlinedResponseFromMldev(fromObject) {
  const toObject = {};
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], generateContentResponseFromMldev$1(fromResponse));
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], jobErrorFromMldev(fromError));
  }
  return toObject;
}
function batchJobDestinationFromMldev(fromObject) {
  const toObject = {};
  const fromFileName = getValueByPath(fromObject, ["responsesFile"]);
  if (fromFileName != null) {
    setValueByPath(toObject, ["fileName"], fromFileName);
  }
  const fromInlinedResponses = getValueByPath(fromObject, [
    "inlinedResponses",
    "inlinedResponses"
  ]);
  if (fromInlinedResponses != null) {
    let transformedList = fromInlinedResponses;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return inlinedResponseFromMldev(item);
      });
    }
    setValueByPath(toObject, ["inlinedResponses"], transformedList);
  }
  return toObject;
}
function batchJobFromMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject, [
    "metadata",
    "displayName"
  ]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromState = getValueByPath(fromObject, ["metadata", "state"]);
  if (fromState != null) {
    setValueByPath(toObject, ["state"], tJobState(fromState));
  }
  const fromCreateTime = getValueByPath(fromObject, [
    "metadata",
    "createTime"
  ]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromEndTime = getValueByPath(fromObject, [
    "metadata",
    "endTime"
  ]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  const fromUpdateTime = getValueByPath(fromObject, [
    "metadata",
    "updateTime"
  ]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromModel = getValueByPath(fromObject, ["metadata", "model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], fromModel);
  }
  const fromDest = getValueByPath(fromObject, ["metadata", "output"]);
  if (fromDest != null) {
    setValueByPath(toObject, ["dest"], batchJobDestinationFromMldev(fromDest));
  }
  return toObject;
}
function listBatchJobsResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromBatchJobs = getValueByPath(fromObject, ["operations"]);
  if (fromBatchJobs != null) {
    let transformedList = fromBatchJobs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return batchJobFromMldev(item);
      });
    }
    setValueByPath(toObject, ["batchJobs"], transformedList);
  }
  return toObject;
}
function deleteResourceJobFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDone = getValueByPath(fromObject, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], jobErrorFromMldev(fromError));
  }
  return toObject;
}
function jobErrorFromVertex(fromObject) {
  const toObject = {};
  const fromDetails = getValueByPath(fromObject, ["details"]);
  if (fromDetails != null) {
    setValueByPath(toObject, ["details"], fromDetails);
  }
  const fromCode = getValueByPath(fromObject, ["code"]);
  if (fromCode != null) {
    setValueByPath(toObject, ["code"], fromCode);
  }
  const fromMessage = getValueByPath(fromObject, ["message"]);
  if (fromMessage != null) {
    setValueByPath(toObject, ["message"], fromMessage);
  }
  return toObject;
}
function batchJobSourceFromVertex(fromObject) {
  const toObject = {};
  const fromFormat = getValueByPath(fromObject, ["instancesFormat"]);
  if (fromFormat != null) {
    setValueByPath(toObject, ["format"], fromFormat);
  }
  const fromGcsUri = getValueByPath(fromObject, ["gcsSource", "uris"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["gcsUri"], fromGcsUri);
  }
  const fromBigqueryUri = getValueByPath(fromObject, [
    "bigquerySource",
    "inputUri"
  ]);
  if (fromBigqueryUri != null) {
    setValueByPath(toObject, ["bigqueryUri"], fromBigqueryUri);
  }
  return toObject;
}
function batchJobDestinationFromVertex(fromObject) {
  const toObject = {};
  const fromFormat = getValueByPath(fromObject, ["predictionsFormat"]);
  if (fromFormat != null) {
    setValueByPath(toObject, ["format"], fromFormat);
  }
  const fromGcsUri = getValueByPath(fromObject, [
    "gcsDestination",
    "outputUriPrefix"
  ]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["gcsUri"], fromGcsUri);
  }
  const fromBigqueryUri = getValueByPath(fromObject, [
    "bigqueryDestination",
    "outputUri"
  ]);
  if (fromBigqueryUri != null) {
    setValueByPath(toObject, ["bigqueryUri"], fromBigqueryUri);
  }
  return toObject;
}
function batchJobFromVertex(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromState = getValueByPath(fromObject, ["state"]);
  if (fromState != null) {
    setValueByPath(toObject, ["state"], tJobState(fromState));
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], jobErrorFromVertex(fromError));
  }
  const fromCreateTime = getValueByPath(fromObject, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromStartTime = getValueByPath(fromObject, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], fromModel);
  }
  const fromSrc = getValueByPath(fromObject, ["inputConfig"]);
  if (fromSrc != null) {
    setValueByPath(toObject, ["src"], batchJobSourceFromVertex(fromSrc));
  }
  const fromDest = getValueByPath(fromObject, ["outputConfig"]);
  if (fromDest != null) {
    setValueByPath(toObject, ["dest"], batchJobDestinationFromVertex(fromDest));
  }
  return toObject;
}
function listBatchJobsResponseFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromBatchJobs = getValueByPath(fromObject, [
    "batchPredictionJobs"
  ]);
  if (fromBatchJobs != null) {
    let transformedList = fromBatchJobs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return batchJobFromVertex(item);
      });
    }
    setValueByPath(toObject, ["batchJobs"], transformedList);
  }
  return toObject;
}
function deleteResourceJobFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDone = getValueByPath(fromObject, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], jobErrorFromVertex(fromError));
  }
  return toObject;
}
function videoMetadataToMldev$3(fromObject) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobToMldev$3(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataToMldev$3(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromFileUri = getValueByPath(fromObject, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function partToMldev$3(fromObject) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataToMldev$3(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev$3(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev$3(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromCodeExecutionResult = getValueByPath(fromObject, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], fromFunctionCall);
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentToMldev$3(fromObject) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToMldev$3(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function functionDeclarationToMldev$3(fromObject) {
  const toObject = {};
  const fromBehavior = getValueByPath(fromObject, ["behavior"]);
  if (fromBehavior != null) {
    setValueByPath(toObject, ["behavior"], fromBehavior);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  return toObject;
}
function intervalToMldev$3(fromObject) {
  const toObject = {};
  const fromStartTime = getValueByPath(fromObject, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  return toObject;
}
function googleSearchToMldev$3(fromObject) {
  const toObject = {};
  const fromTimeRangeFilter = getValueByPath(fromObject, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], intervalToMldev$3(fromTimeRangeFilter));
  }
  if (getValueByPath(fromObject, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  return toObject;
}
function dynamicRetrievalConfigToMldev$3(fromObject) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromDynamicThreshold = getValueByPath(fromObject, [
    "dynamicThreshold"
  ]);
  if (fromDynamicThreshold != null) {
    setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold);
  }
  return toObject;
}
function googleSearchRetrievalToMldev$3(fromObject) {
  const toObject = {};
  const fromDynamicRetrievalConfig = getValueByPath(fromObject, [
    "dynamicRetrievalConfig"
  ]);
  if (fromDynamicRetrievalConfig != null) {
    setValueByPath(toObject, ["dynamicRetrievalConfig"], dynamicRetrievalConfigToMldev$3(fromDynamicRetrievalConfig));
  }
  return toObject;
}
function urlContextToMldev$3() {
  const toObject = {};
  return toObject;
}
function toolComputerUseToMldev$3(fromObject) {
  const toObject = {};
  const fromEnvironment = getValueByPath(fromObject, ["environment"]);
  if (fromEnvironment != null) {
    setValueByPath(toObject, ["environment"], fromEnvironment);
  }
  return toObject;
}
function toolToMldev$3(fromObject) {
  const toObject = {};
  const fromFunctionDeclarations = getValueByPath(fromObject, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToMldev$3(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  if (getValueByPath(fromObject, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$3(fromGoogleSearch));
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], googleSearchRetrievalToMldev$3(fromGoogleSearchRetrieval));
  }
  if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["googleMaps"]) !== void 0) {
    throw new Error("googleMaps parameter is not supported in Gemini API.");
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], urlContextToMldev$3());
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], toolComputerUseToMldev$3(fromComputerUse));
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  return toObject;
}
function functionCallingConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromAllowedFunctionNames = getValueByPath(fromObject, [
    "allowedFunctionNames"
  ]);
  if (fromAllowedFunctionNames != null) {
    setValueByPath(toObject, ["allowedFunctionNames"], fromAllowedFunctionNames);
  }
  return toObject;
}
function latLngToMldev$1(fromObject) {
  const toObject = {};
  const fromLatitude = getValueByPath(fromObject, ["latitude"]);
  if (fromLatitude != null) {
    setValueByPath(toObject, ["latitude"], fromLatitude);
  }
  const fromLongitude = getValueByPath(fromObject, ["longitude"]);
  if (fromLongitude != null) {
    setValueByPath(toObject, ["longitude"], fromLongitude);
  }
  return toObject;
}
function retrievalConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromLatLng = getValueByPath(fromObject, ["latLng"]);
  if (fromLatLng != null) {
    setValueByPath(toObject, ["latLng"], latLngToMldev$1(fromLatLng));
  }
  const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function toolConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromFunctionCallingConfig = getValueByPath(fromObject, [
    "functionCallingConfig"
  ]);
  if (fromFunctionCallingConfig != null) {
    setValueByPath(toObject, ["functionCallingConfig"], functionCallingConfigToMldev$1(fromFunctionCallingConfig));
  }
  const fromRetrievalConfig = getValueByPath(fromObject, [
    "retrievalConfig"
  ]);
  if (fromRetrievalConfig != null) {
    setValueByPath(toObject, ["retrievalConfig"], retrievalConfigToMldev$1(fromRetrievalConfig));
  }
  return toObject;
}
function createCachedContentConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromTtl = getValueByPath(fromObject, ["ttl"]);
  if (parentObject !== void 0 && fromTtl != null) {
    setValueByPath(parentObject, ["ttl"], fromTtl);
  }
  const fromExpireTime = getValueByPath(fromObject, ["expireTime"]);
  if (parentObject !== void 0 && fromExpireTime != null) {
    setValueByPath(parentObject, ["expireTime"], fromExpireTime);
  }
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (parentObject !== void 0 && fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToMldev$3(item);
      });
    }
    setValueByPath(parentObject, ["contents"], transformedList);
  }
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], contentToMldev$3(tContent(fromSystemInstruction)));
  }
  const fromTools = getValueByPath(fromObject, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = fromTools;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToMldev$3(item);
      });
    }
    setValueByPath(parentObject, ["tools"], transformedList);
  }
  const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]);
  if (parentObject !== void 0 && fromToolConfig != null) {
    setValueByPath(parentObject, ["toolConfig"], toolConfigToMldev$1(fromToolConfig));
  }
  if (getValueByPath(fromObject, ["kmsKeyName"]) !== void 0) {
    throw new Error("kmsKeyName parameter is not supported in Gemini API.");
  }
  return toObject;
}
function createCachedContentParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], tCachesModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], createCachedContentConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function getCachedContentParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function deleteCachedContentParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function updateCachedContentConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromTtl = getValueByPath(fromObject, ["ttl"]);
  if (parentObject !== void 0 && fromTtl != null) {
    setValueByPath(parentObject, ["ttl"], fromTtl);
  }
  const fromExpireTime = getValueByPath(fromObject, ["expireTime"]);
  if (parentObject !== void 0 && fromExpireTime != null) {
    setValueByPath(parentObject, ["expireTime"], fromExpireTime);
  }
  return toObject;
}
function updateCachedContentParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], updateCachedContentConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function listCachedContentsConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  return toObject;
}
function listCachedContentsParametersToMldev(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], listCachedContentsConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function videoMetadataToVertex$2(fromObject) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobToVertex$2(fromObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataToVertex$2(fromObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromFileUri = getValueByPath(fromObject, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function partToVertex$2(fromObject) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataToVertex$2(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToVertex$2(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToVertex$2(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromCodeExecutionResult = getValueByPath(fromObject, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], fromFunctionCall);
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentToVertex$2(fromObject) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToVertex$2(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function functionDeclarationToVertex$2(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["behavior"]) !== void 0) {
    throw new Error("behavior parameter is not supported in Vertex AI.");
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  return toObject;
}
function intervalToVertex$2(fromObject) {
  const toObject = {};
  const fromStartTime = getValueByPath(fromObject, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  return toObject;
}
function googleSearchToVertex$2(fromObject) {
  const toObject = {};
  const fromTimeRangeFilter = getValueByPath(fromObject, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], intervalToVertex$2(fromTimeRangeFilter));
  }
  const fromExcludeDomains = getValueByPath(fromObject, [
    "excludeDomains"
  ]);
  if (fromExcludeDomains != null) {
    setValueByPath(toObject, ["excludeDomains"], fromExcludeDomains);
  }
  return toObject;
}
function dynamicRetrievalConfigToVertex$2(fromObject) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromDynamicThreshold = getValueByPath(fromObject, [
    "dynamicThreshold"
  ]);
  if (fromDynamicThreshold != null) {
    setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold);
  }
  return toObject;
}
function googleSearchRetrievalToVertex$2(fromObject) {
  const toObject = {};
  const fromDynamicRetrievalConfig = getValueByPath(fromObject, [
    "dynamicRetrievalConfig"
  ]);
  if (fromDynamicRetrievalConfig != null) {
    setValueByPath(toObject, ["dynamicRetrievalConfig"], dynamicRetrievalConfigToVertex$2(fromDynamicRetrievalConfig));
  }
  return toObject;
}
function enterpriseWebSearchToVertex$2(fromObject) {
  const toObject = {};
  const fromExcludeDomains = getValueByPath(fromObject, [
    "excludeDomains"
  ]);
  if (fromExcludeDomains != null) {
    setValueByPath(toObject, ["excludeDomains"], fromExcludeDomains);
  }
  return toObject;
}
function apiKeyConfigToVertex$2(fromObject) {
  const toObject = {};
  const fromApiKeyString = getValueByPath(fromObject, ["apiKeyString"]);
  if (fromApiKeyString != null) {
    setValueByPath(toObject, ["apiKeyString"], fromApiKeyString);
  }
  return toObject;
}
function authConfigToVertex$2(fromObject) {
  const toObject = {};
  const fromApiKeyConfig = getValueByPath(fromObject, ["apiKeyConfig"]);
  if (fromApiKeyConfig != null) {
    setValueByPath(toObject, ["apiKeyConfig"], apiKeyConfigToVertex$2(fromApiKeyConfig));
  }
  const fromAuthType = getValueByPath(fromObject, ["authType"]);
  if (fromAuthType != null) {
    setValueByPath(toObject, ["authType"], fromAuthType);
  }
  const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [
    "googleServiceAccountConfig"
  ]);
  if (fromGoogleServiceAccountConfig != null) {
    setValueByPath(toObject, ["googleServiceAccountConfig"], fromGoogleServiceAccountConfig);
  }
  const fromHttpBasicAuthConfig = getValueByPath(fromObject, [
    "httpBasicAuthConfig"
  ]);
  if (fromHttpBasicAuthConfig != null) {
    setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig);
  }
  const fromOauthConfig = getValueByPath(fromObject, ["oauthConfig"]);
  if (fromOauthConfig != null) {
    setValueByPath(toObject, ["oauthConfig"], fromOauthConfig);
  }
  const fromOidcConfig = getValueByPath(fromObject, ["oidcConfig"]);
  if (fromOidcConfig != null) {
    setValueByPath(toObject, ["oidcConfig"], fromOidcConfig);
  }
  return toObject;
}
function googleMapsToVertex$2(fromObject) {
  const toObject = {};
  const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]);
  if (fromAuthConfig != null) {
    setValueByPath(toObject, ["authConfig"], authConfigToVertex$2(fromAuthConfig));
  }
  return toObject;
}
function urlContextToVertex$2() {
  const toObject = {};
  return toObject;
}
function toolComputerUseToVertex$2(fromObject) {
  const toObject = {};
  const fromEnvironment = getValueByPath(fromObject, ["environment"]);
  if (fromEnvironment != null) {
    setValueByPath(toObject, ["environment"], fromEnvironment);
  }
  return toObject;
}
function toolToVertex$2(fromObject) {
  const toObject = {};
  const fromFunctionDeclarations = getValueByPath(fromObject, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToVertex$2(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  const fromRetrieval = getValueByPath(fromObject, ["retrieval"]);
  if (fromRetrieval != null) {
    setValueByPath(toObject, ["retrieval"], fromRetrieval);
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToVertex$2(fromGoogleSearch));
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], googleSearchRetrievalToVertex$2(fromGoogleSearchRetrieval));
  }
  const fromEnterpriseWebSearch = getValueByPath(fromObject, [
    "enterpriseWebSearch"
  ]);
  if (fromEnterpriseWebSearch != null) {
    setValueByPath(toObject, ["enterpriseWebSearch"], enterpriseWebSearchToVertex$2(fromEnterpriseWebSearch));
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], googleMapsToVertex$2(fromGoogleMaps));
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], urlContextToVertex$2());
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], toolComputerUseToVertex$2(fromComputerUse));
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  return toObject;
}
function functionCallingConfigToVertex$1(fromObject) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromAllowedFunctionNames = getValueByPath(fromObject, [
    "allowedFunctionNames"
  ]);
  if (fromAllowedFunctionNames != null) {
    setValueByPath(toObject, ["allowedFunctionNames"], fromAllowedFunctionNames);
  }
  return toObject;
}
function latLngToVertex$1(fromObject) {
  const toObject = {};
  const fromLatitude = getValueByPath(fromObject, ["latitude"]);
  if (fromLatitude != null) {
    setValueByPath(toObject, ["latitude"], fromLatitude);
  }
  const fromLongitude = getValueByPath(fromObject, ["longitude"]);
  if (fromLongitude != null) {
    setValueByPath(toObject, ["longitude"], fromLongitude);
  }
  return toObject;
}
function retrievalConfigToVertex$1(fromObject) {
  const toObject = {};
  const fromLatLng = getValueByPath(fromObject, ["latLng"]);
  if (fromLatLng != null) {
    setValueByPath(toObject, ["latLng"], latLngToVertex$1(fromLatLng));
  }
  const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function toolConfigToVertex$1(fromObject) {
  const toObject = {};
  const fromFunctionCallingConfig = getValueByPath(fromObject, [
    "functionCallingConfig"
  ]);
  if (fromFunctionCallingConfig != null) {
    setValueByPath(toObject, ["functionCallingConfig"], functionCallingConfigToVertex$1(fromFunctionCallingConfig));
  }
  const fromRetrievalConfig = getValueByPath(fromObject, [
    "retrievalConfig"
  ]);
  if (fromRetrievalConfig != null) {
    setValueByPath(toObject, ["retrievalConfig"], retrievalConfigToVertex$1(fromRetrievalConfig));
  }
  return toObject;
}
function createCachedContentConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromTtl = getValueByPath(fromObject, ["ttl"]);
  if (parentObject !== void 0 && fromTtl != null) {
    setValueByPath(parentObject, ["ttl"], fromTtl);
  }
  const fromExpireTime = getValueByPath(fromObject, ["expireTime"]);
  if (parentObject !== void 0 && fromExpireTime != null) {
    setValueByPath(parentObject, ["expireTime"], fromExpireTime);
  }
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (parentObject !== void 0 && fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToVertex$2(item);
      });
    }
    setValueByPath(parentObject, ["contents"], transformedList);
  }
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], contentToVertex$2(tContent(fromSystemInstruction)));
  }
  const fromTools = getValueByPath(fromObject, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = fromTools;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToVertex$2(item);
      });
    }
    setValueByPath(parentObject, ["tools"], transformedList);
  }
  const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]);
  if (parentObject !== void 0 && fromToolConfig != null) {
    setValueByPath(parentObject, ["toolConfig"], toolConfigToVertex$1(fromToolConfig));
  }
  const fromKmsKeyName = getValueByPath(fromObject, ["kmsKeyName"]);
  if (parentObject !== void 0 && fromKmsKeyName != null) {
    setValueByPath(parentObject, ["encryption_spec", "kmsKeyName"], fromKmsKeyName);
  }
  return toObject;
}
function createCachedContentParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], tCachesModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], createCachedContentConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function getCachedContentParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function deleteCachedContentParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function updateCachedContentConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromTtl = getValueByPath(fromObject, ["ttl"]);
  if (parentObject !== void 0 && fromTtl != null) {
    setValueByPath(parentObject, ["ttl"], fromTtl);
  }
  const fromExpireTime = getValueByPath(fromObject, ["expireTime"]);
  if (parentObject !== void 0 && fromExpireTime != null) {
    setValueByPath(parentObject, ["expireTime"], fromExpireTime);
  }
  return toObject;
}
function updateCachedContentParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], updateCachedContentConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function listCachedContentsConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  return toObject;
}
function listCachedContentsParametersToVertex(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], listCachedContentsConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function cachedContentFromMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], fromModel);
  }
  const fromCreateTime = getValueByPath(fromObject, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromExpireTime = getValueByPath(fromObject, ["expireTime"]);
  if (fromExpireTime != null) {
    setValueByPath(toObject, ["expireTime"], fromExpireTime);
  }
  const fromUsageMetadata = getValueByPath(fromObject, [
    "usageMetadata"
  ]);
  if (fromUsageMetadata != null) {
    setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata);
  }
  return toObject;
}
function deleteCachedContentResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function listCachedContentsResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromCachedContents = getValueByPath(fromObject, [
    "cachedContents"
  ]);
  if (fromCachedContents != null) {
    let transformedList = fromCachedContents;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return cachedContentFromMldev(item);
      });
    }
    setValueByPath(toObject, ["cachedContents"], transformedList);
  }
  return toObject;
}
function cachedContentFromVertex(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], fromModel);
  }
  const fromCreateTime = getValueByPath(fromObject, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromExpireTime = getValueByPath(fromObject, ["expireTime"]);
  if (fromExpireTime != null) {
    setValueByPath(toObject, ["expireTime"], fromExpireTime);
  }
  const fromUsageMetadata = getValueByPath(fromObject, [
    "usageMetadata"
  ]);
  if (fromUsageMetadata != null) {
    setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata);
  }
  return toObject;
}
function deleteCachedContentResponseFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function listCachedContentsResponseFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromCachedContents = getValueByPath(fromObject, [
    "cachedContents"
  ]);
  if (fromCachedContents != null) {
    let transformedList = fromCachedContents;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return cachedContentFromVertex(item);
      });
    }
    setValueByPath(toObject, ["cachedContents"], transformedList);
  }
  return toObject;
}
function __values(o2) {
  var s2 = typeof Symbol === "function" && Symbol.iterator, m = s2 && o2[s2], i = 0;
  if (m) return m.call(o2);
  if (o2 && typeof o2.length === "number") return {
    next: /* @__PURE__ */ __name(function() {
      if (o2 && i >= o2.length) o2 = void 0;
      return { value: o2 && o2[i++], done: !o2 };
    }, "next")
  };
  throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __await(v) {
  return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var g = generator.apply(thisArg, _arguments || []), i, q = [];
  return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() {
    return this;
  }, i;
  function awaitReturn(f) {
    return function(v) {
      return Promise.resolve(v).then(f, reject);
    };
  }
  __name(awaitReturn, "awaitReturn");
  function verb(n2, f) {
    if (g[n2]) {
      i[n2] = function(v) {
        return new Promise(function(a, b) {
          q.push([n2, v, a, b]) > 1 || resume(n2, v);
        });
      };
      if (f) i[n2] = f(i[n2]);
    }
  }
  __name(verb, "verb");
  function resume(n2, v) {
    try {
      step(g[n2](v));
    } catch (e2) {
      settle(q[0][3], e2);
    }
  }
  __name(resume, "resume");
  function step(r3) {
    r3.value instanceof __await ? Promise.resolve(r3.value.v).then(fulfill, reject) : settle(q[0][2], r3);
  }
  __name(step, "step");
  function fulfill(value) {
    resume("next", value);
  }
  __name(fulfill, "fulfill");
  function reject(value) {
    resume("throw", value);
  }
  __name(reject, "reject");
  function settle(f, v) {
    if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
  }
  __name(settle, "settle");
}
function __asyncValues(o2) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var m = o2[Symbol.asyncIterator], i;
  return m ? m.call(o2) : (o2 = typeof __values === "function" ? __values(o2) : o2[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
    return this;
  }, i);
  function verb(n2) {
    i[n2] = o2[n2] && function(v) {
      return new Promise(function(resolve24, reject) {
        v = o2[n2](v), settle(resolve24, reject, v.done, v.value);
      });
    };
  }
  __name(verb, "verb");
  function settle(resolve24, reject, d, v) {
    Promise.resolve(v).then(function(v2) {
      resolve24({ value: v2, done: d });
    }, reject);
  }
  __name(settle, "settle");
}
function isValidResponse(response) {
  var _a6;
  if (response.candidates == void 0 || response.candidates.length === 0) {
    return false;
  }
  const content = (_a6 = response.candidates[0]) === null || _a6 === void 0 ? void 0 : _a6.content;
  if (content === void 0) {
    return false;
  }
  return isValidContent(content);
}
function isValidContent(content) {
  if (content.parts === void 0 || content.parts.length === 0) {
    return false;
  }
  for (const part of content.parts) {
    if (part === void 0 || Object.keys(part).length === 0) {
      return false;
    }
  }
  return true;
}
function validateHistory(history) {
  if (history.length === 0) {
    return;
  }
  for (const content of history) {
    if (content.role !== "user" && content.role !== "model") {
      throw new Error(`Role must be user or model, but got ${content.role}.`);
    }
  }
}
function extractCuratedHistory(comprehensiveHistory) {
  if (comprehensiveHistory === void 0 || comprehensiveHistory.length === 0) {
    return [];
  }
  const curatedHistory = [];
  const length = comprehensiveHistory.length;
  let i = 0;
  while (i < length) {
    if (comprehensiveHistory[i].role === "user") {
      curatedHistory.push(comprehensiveHistory[i]);
      i++;
    } else {
      const modelOutput = [];
      let isValid2 = true;
      while (i < length && comprehensiveHistory[i].role === "model") {
        modelOutput.push(comprehensiveHistory[i]);
        if (isValid2 && !isValidContent(comprehensiveHistory[i])) {
          isValid2 = false;
        }
        i++;
      }
      if (isValid2) {
        curatedHistory.push(...modelOutput);
      } else {
        curatedHistory.pop();
      }
    }
  }
  return curatedHistory;
}
function listFilesConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  return toObject;
}
function listFilesParametersToMldev(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], listFilesConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function fileStatusToMldev(fromObject) {
  const toObject = {};
  const fromDetails = getValueByPath(fromObject, ["details"]);
  if (fromDetails != null) {
    setValueByPath(toObject, ["details"], fromDetails);
  }
  const fromMessage = getValueByPath(fromObject, ["message"]);
  if (fromMessage != null) {
    setValueByPath(toObject, ["message"], fromMessage);
  }
  const fromCode = getValueByPath(fromObject, ["code"]);
  if (fromCode != null) {
    setValueByPath(toObject, ["code"], fromCode);
  }
  return toObject;
}
function fileToMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  const fromSizeBytes = getValueByPath(fromObject, ["sizeBytes"]);
  if (fromSizeBytes != null) {
    setValueByPath(toObject, ["sizeBytes"], fromSizeBytes);
  }
  const fromCreateTime = getValueByPath(fromObject, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromExpirationTime = getValueByPath(fromObject, [
    "expirationTime"
  ]);
  if (fromExpirationTime != null) {
    setValueByPath(toObject, ["expirationTime"], fromExpirationTime);
  }
  const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromSha256Hash = getValueByPath(fromObject, ["sha256Hash"]);
  if (fromSha256Hash != null) {
    setValueByPath(toObject, ["sha256Hash"], fromSha256Hash);
  }
  const fromUri = getValueByPath(fromObject, ["uri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["uri"], fromUri);
  }
  const fromDownloadUri = getValueByPath(fromObject, ["downloadUri"]);
  if (fromDownloadUri != null) {
    setValueByPath(toObject, ["downloadUri"], fromDownloadUri);
  }
  const fromState = getValueByPath(fromObject, ["state"]);
  if (fromState != null) {
    setValueByPath(toObject, ["state"], fromState);
  }
  const fromSource = getValueByPath(fromObject, ["source"]);
  if (fromSource != null) {
    setValueByPath(toObject, ["source"], fromSource);
  }
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fileStatusToMldev(fromError));
  }
  return toObject;
}
function createFileParametersToMldev(fromObject) {
  const toObject = {};
  const fromFile = getValueByPath(fromObject, ["file"]);
  if (fromFile != null) {
    setValueByPath(toObject, ["file"], fileToMldev(fromFile));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function getFileParametersToMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "file"], tFileName(fromName));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function deleteFileParametersToMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "file"], tFileName(fromName));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function fileStatusFromMldev(fromObject) {
  const toObject = {};
  const fromDetails = getValueByPath(fromObject, ["details"]);
  if (fromDetails != null) {
    setValueByPath(toObject, ["details"], fromDetails);
  }
  const fromMessage = getValueByPath(fromObject, ["message"]);
  if (fromMessage != null) {
    setValueByPath(toObject, ["message"], fromMessage);
  }
  const fromCode = getValueByPath(fromObject, ["code"]);
  if (fromCode != null) {
    setValueByPath(toObject, ["code"], fromCode);
  }
  return toObject;
}
function fileFromMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  const fromSizeBytes = getValueByPath(fromObject, ["sizeBytes"]);
  if (fromSizeBytes != null) {
    setValueByPath(toObject, ["sizeBytes"], fromSizeBytes);
  }
  const fromCreateTime = getValueByPath(fromObject, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromExpirationTime = getValueByPath(fromObject, [
    "expirationTime"
  ]);
  if (fromExpirationTime != null) {
    setValueByPath(toObject, ["expirationTime"], fromExpirationTime);
  }
  const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromSha256Hash = getValueByPath(fromObject, ["sha256Hash"]);
  if (fromSha256Hash != null) {
    setValueByPath(toObject, ["sha256Hash"], fromSha256Hash);
  }
  const fromUri = getValueByPath(fromObject, ["uri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["uri"], fromUri);
  }
  const fromDownloadUri = getValueByPath(fromObject, ["downloadUri"]);
  if (fromDownloadUri != null) {
    setValueByPath(toObject, ["downloadUri"], fromDownloadUri);
  }
  const fromState = getValueByPath(fromObject, ["state"]);
  if (fromState != null) {
    setValueByPath(toObject, ["state"], fromState);
  }
  const fromSource = getValueByPath(fromObject, ["source"]);
  if (fromSource != null) {
    setValueByPath(toObject, ["source"], fromSource);
  }
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fileStatusFromMldev(fromError));
  }
  return toObject;
}
function listFilesResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromFiles = getValueByPath(fromObject, ["files"]);
  if (fromFiles != null) {
    let transformedList = fromFiles;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return fileFromMldev(item);
      });
    }
    setValueByPath(toObject, ["files"], transformedList);
  }
  return toObject;
}
function createFileResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function deleteFileResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function prebuiltVoiceConfigToMldev$2(fromObject) {
  const toObject = {};
  const fromVoiceName = getValueByPath(fromObject, ["voiceName"]);
  if (fromVoiceName != null) {
    setValueByPath(toObject, ["voiceName"], fromVoiceName);
  }
  return toObject;
}
function voiceConfigToMldev$2(fromObject) {
  const toObject = {};
  const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [
    "prebuiltVoiceConfig"
  ]);
  if (fromPrebuiltVoiceConfig != null) {
    setValueByPath(toObject, ["prebuiltVoiceConfig"], prebuiltVoiceConfigToMldev$2(fromPrebuiltVoiceConfig));
  }
  return toObject;
}
function speakerVoiceConfigToMldev$2(fromObject) {
  const toObject = {};
  const fromSpeaker = getValueByPath(fromObject, ["speaker"]);
  if (fromSpeaker != null) {
    setValueByPath(toObject, ["speaker"], fromSpeaker);
  }
  const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToMldev$2(fromVoiceConfig));
  }
  return toObject;
}
function multiSpeakerVoiceConfigToMldev$2(fromObject) {
  const toObject = {};
  const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [
    "speakerVoiceConfigs"
  ]);
  if (fromSpeakerVoiceConfigs != null) {
    let transformedList = fromSpeakerVoiceConfigs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return speakerVoiceConfigToMldev$2(item);
      });
    }
    setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList);
  }
  return toObject;
}
function speechConfigToMldev$2(fromObject) {
  const toObject = {};
  const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToMldev$2(fromVoiceConfig));
  }
  const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [
    "multiSpeakerVoiceConfig"
  ]);
  if (fromMultiSpeakerVoiceConfig != null) {
    setValueByPath(toObject, ["multiSpeakerVoiceConfig"], multiSpeakerVoiceConfigToMldev$2(fromMultiSpeakerVoiceConfig));
  }
  const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function videoMetadataToMldev$2(fromObject) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobToMldev$2(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataToMldev$2(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromFileUri = getValueByPath(fromObject, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function partToMldev$2(fromObject) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataToMldev$2(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev$2(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev$2(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromCodeExecutionResult = getValueByPath(fromObject, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], fromFunctionCall);
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentToMldev$2(fromObject) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToMldev$2(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function functionDeclarationToMldev$2(fromObject) {
  const toObject = {};
  const fromBehavior = getValueByPath(fromObject, ["behavior"]);
  if (fromBehavior != null) {
    setValueByPath(toObject, ["behavior"], fromBehavior);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  return toObject;
}
function intervalToMldev$2(fromObject) {
  const toObject = {};
  const fromStartTime = getValueByPath(fromObject, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  return toObject;
}
function googleSearchToMldev$2(fromObject) {
  const toObject = {};
  const fromTimeRangeFilter = getValueByPath(fromObject, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], intervalToMldev$2(fromTimeRangeFilter));
  }
  if (getValueByPath(fromObject, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  return toObject;
}
function dynamicRetrievalConfigToMldev$2(fromObject) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromDynamicThreshold = getValueByPath(fromObject, [
    "dynamicThreshold"
  ]);
  if (fromDynamicThreshold != null) {
    setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold);
  }
  return toObject;
}
function googleSearchRetrievalToMldev$2(fromObject) {
  const toObject = {};
  const fromDynamicRetrievalConfig = getValueByPath(fromObject, [
    "dynamicRetrievalConfig"
  ]);
  if (fromDynamicRetrievalConfig != null) {
    setValueByPath(toObject, ["dynamicRetrievalConfig"], dynamicRetrievalConfigToMldev$2(fromDynamicRetrievalConfig));
  }
  return toObject;
}
function urlContextToMldev$2() {
  const toObject = {};
  return toObject;
}
function toolComputerUseToMldev$2(fromObject) {
  const toObject = {};
  const fromEnvironment = getValueByPath(fromObject, ["environment"]);
  if (fromEnvironment != null) {
    setValueByPath(toObject, ["environment"], fromEnvironment);
  }
  return toObject;
}
function toolToMldev$2(fromObject) {
  const toObject = {};
  const fromFunctionDeclarations = getValueByPath(fromObject, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToMldev$2(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  if (getValueByPath(fromObject, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$2(fromGoogleSearch));
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], googleSearchRetrievalToMldev$2(fromGoogleSearchRetrieval));
  }
  if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["googleMaps"]) !== void 0) {
    throw new Error("googleMaps parameter is not supported in Gemini API.");
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], urlContextToMldev$2());
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], toolComputerUseToMldev$2(fromComputerUse));
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  return toObject;
}
function sessionResumptionConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromHandle = getValueByPath(fromObject, ["handle"]);
  if (fromHandle != null) {
    setValueByPath(toObject, ["handle"], fromHandle);
  }
  if (getValueByPath(fromObject, ["transparent"]) !== void 0) {
    throw new Error("transparent parameter is not supported in Gemini API.");
  }
  return toObject;
}
function audioTranscriptionConfigToMldev$1() {
  const toObject = {};
  return toObject;
}
function automaticActivityDetectionToMldev$1(fromObject) {
  const toObject = {};
  const fromDisabled = getValueByPath(fromObject, ["disabled"]);
  if (fromDisabled != null) {
    setValueByPath(toObject, ["disabled"], fromDisabled);
  }
  const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [
    "startOfSpeechSensitivity"
  ]);
  if (fromStartOfSpeechSensitivity != null) {
    setValueByPath(toObject, ["startOfSpeechSensitivity"], fromStartOfSpeechSensitivity);
  }
  const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [
    "endOfSpeechSensitivity"
  ]);
  if (fromEndOfSpeechSensitivity != null) {
    setValueByPath(toObject, ["endOfSpeechSensitivity"], fromEndOfSpeechSensitivity);
  }
  const fromPrefixPaddingMs = getValueByPath(fromObject, [
    "prefixPaddingMs"
  ]);
  if (fromPrefixPaddingMs != null) {
    setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs);
  }
  const fromSilenceDurationMs = getValueByPath(fromObject, [
    "silenceDurationMs"
  ]);
  if (fromSilenceDurationMs != null) {
    setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs);
  }
  return toObject;
}
function realtimeInputConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromAutomaticActivityDetection = getValueByPath(fromObject, [
    "automaticActivityDetection"
  ]);
  if (fromAutomaticActivityDetection != null) {
    setValueByPath(toObject, ["automaticActivityDetection"], automaticActivityDetectionToMldev$1(fromAutomaticActivityDetection));
  }
  const fromActivityHandling = getValueByPath(fromObject, [
    "activityHandling"
  ]);
  if (fromActivityHandling != null) {
    setValueByPath(toObject, ["activityHandling"], fromActivityHandling);
  }
  const fromTurnCoverage = getValueByPath(fromObject, ["turnCoverage"]);
  if (fromTurnCoverage != null) {
    setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage);
  }
  return toObject;
}
function slidingWindowToMldev$1(fromObject) {
  const toObject = {};
  const fromTargetTokens = getValueByPath(fromObject, ["targetTokens"]);
  if (fromTargetTokens != null) {
    setValueByPath(toObject, ["targetTokens"], fromTargetTokens);
  }
  return toObject;
}
function contextWindowCompressionConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromTriggerTokens = getValueByPath(fromObject, [
    "triggerTokens"
  ]);
  if (fromTriggerTokens != null) {
    setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens);
  }
  const fromSlidingWindow = getValueByPath(fromObject, [
    "slidingWindow"
  ]);
  if (fromSlidingWindow != null) {
    setValueByPath(toObject, ["slidingWindow"], slidingWindowToMldev$1(fromSlidingWindow));
  }
  return toObject;
}
function proactivityConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromProactiveAudio = getValueByPath(fromObject, [
    "proactiveAudio"
  ]);
  if (fromProactiveAudio != null) {
    setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio);
  }
  return toObject;
}
function liveConnectConfigToMldev$1(fromObject, parentObject) {
  const toObject = {};
  const fromGenerationConfig = getValueByPath(fromObject, [
    "generationConfig"
  ]);
  if (parentObject !== void 0 && fromGenerationConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig"], fromGenerationConfig);
  }
  const fromResponseModalities = getValueByPath(fromObject, [
    "responseModalities"
  ]);
  if (parentObject !== void 0 && fromResponseModalities != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "responseModalities"], fromResponseModalities);
  }
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (parentObject !== void 0 && fromTemperature != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "temperature"], fromTemperature);
  }
  const fromTopP = getValueByPath(fromObject, ["topP"]);
  if (parentObject !== void 0 && fromTopP != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (parentObject !== void 0 && fromTopK != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "topK"], fromTopK);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject, [
    "maxOutputTokens"
  ]);
  if (parentObject !== void 0 && fromMaxOutputTokens != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (parentObject !== void 0 && fromMediaResolution != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "mediaResolution"], fromMediaResolution);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "seed"], fromSeed);
  }
  const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]);
  if (parentObject !== void 0 && fromSpeechConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "speechConfig"], speechConfigToMldev$2(tLiveSpeechConfig(fromSpeechConfig)));
  }
  const fromEnableAffectiveDialog = getValueByPath(fromObject, [
    "enableAffectiveDialog"
  ]);
  if (parentObject !== void 0 && fromEnableAffectiveDialog != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "enableAffectiveDialog"], fromEnableAffectiveDialog);
  }
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["setup", "systemInstruction"], contentToMldev$2(tContent(fromSystemInstruction)));
  }
  const fromTools = getValueByPath(fromObject, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = tTools(fromTools);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToMldev$2(tTool(item));
      });
    }
    setValueByPath(parentObject, ["setup", "tools"], transformedList);
  }
  const fromSessionResumption = getValueByPath(fromObject, [
    "sessionResumption"
  ]);
  if (parentObject !== void 0 && fromSessionResumption != null) {
    setValueByPath(parentObject, ["setup", "sessionResumption"], sessionResumptionConfigToMldev$1(fromSessionResumption));
  }
  const fromInputAudioTranscription = getValueByPath(fromObject, [
    "inputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromInputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "inputAudioTranscription"], audioTranscriptionConfigToMldev$1());
  }
  const fromOutputAudioTranscription = getValueByPath(fromObject, [
    "outputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromOutputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "outputAudioTranscription"], audioTranscriptionConfigToMldev$1());
  }
  const fromRealtimeInputConfig = getValueByPath(fromObject, [
    "realtimeInputConfig"
  ]);
  if (parentObject !== void 0 && fromRealtimeInputConfig != null) {
    setValueByPath(parentObject, ["setup", "realtimeInputConfig"], realtimeInputConfigToMldev$1(fromRealtimeInputConfig));
  }
  const fromContextWindowCompression = getValueByPath(fromObject, [
    "contextWindowCompression"
  ]);
  if (parentObject !== void 0 && fromContextWindowCompression != null) {
    setValueByPath(parentObject, ["setup", "contextWindowCompression"], contextWindowCompressionConfigToMldev$1(fromContextWindowCompression));
  }
  const fromProactivity = getValueByPath(fromObject, ["proactivity"]);
  if (parentObject !== void 0 && fromProactivity != null) {
    setValueByPath(parentObject, ["setup", "proactivity"], proactivityConfigToMldev$1(fromProactivity));
  }
  return toObject;
}
function liveConnectParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], liveConnectConfigToMldev$1(fromConfig, toObject));
  }
  return toObject;
}
function activityStartToMldev() {
  const toObject = {};
  return toObject;
}
function activityEndToMldev() {
  const toObject = {};
  return toObject;
}
function liveSendRealtimeInputParametersToMldev(fromObject) {
  const toObject = {};
  const fromMedia = getValueByPath(fromObject, ["media"]);
  if (fromMedia != null) {
    setValueByPath(toObject, ["mediaChunks"], tBlobs(fromMedia));
  }
  const fromAudio = getValueByPath(fromObject, ["audio"]);
  if (fromAudio != null) {
    setValueByPath(toObject, ["audio"], tAudioBlob(fromAudio));
  }
  const fromAudioStreamEnd = getValueByPath(fromObject, [
    "audioStreamEnd"
  ]);
  if (fromAudioStreamEnd != null) {
    setValueByPath(toObject, ["audioStreamEnd"], fromAudioStreamEnd);
  }
  const fromVideo = getValueByPath(fromObject, ["video"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], tImageBlob(fromVideo));
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromActivityStart = getValueByPath(fromObject, [
    "activityStart"
  ]);
  if (fromActivityStart != null) {
    setValueByPath(toObject, ["activityStart"], activityStartToMldev());
  }
  const fromActivityEnd = getValueByPath(fromObject, ["activityEnd"]);
  if (fromActivityEnd != null) {
    setValueByPath(toObject, ["activityEnd"], activityEndToMldev());
  }
  return toObject;
}
function weightedPromptToMldev(fromObject) {
  const toObject = {};
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromWeight = getValueByPath(fromObject, ["weight"]);
  if (fromWeight != null) {
    setValueByPath(toObject, ["weight"], fromWeight);
  }
  return toObject;
}
function liveMusicSetWeightedPromptsParametersToMldev(fromObject) {
  const toObject = {};
  const fromWeightedPrompts = getValueByPath(fromObject, [
    "weightedPrompts"
  ]);
  if (fromWeightedPrompts != null) {
    let transformedList = fromWeightedPrompts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return weightedPromptToMldev(item);
      });
    }
    setValueByPath(toObject, ["weightedPrompts"], transformedList);
  }
  return toObject;
}
function liveMusicGenerationConfigToMldev(fromObject) {
  const toObject = {};
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (fromTopK != null) {
    setValueByPath(toObject, ["topK"], fromTopK);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (fromSeed != null) {
    setValueByPath(toObject, ["seed"], fromSeed);
  }
  const fromGuidance = getValueByPath(fromObject, ["guidance"]);
  if (fromGuidance != null) {
    setValueByPath(toObject, ["guidance"], fromGuidance);
  }
  const fromBpm = getValueByPath(fromObject, ["bpm"]);
  if (fromBpm != null) {
    setValueByPath(toObject, ["bpm"], fromBpm);
  }
  const fromDensity = getValueByPath(fromObject, ["density"]);
  if (fromDensity != null) {
    setValueByPath(toObject, ["density"], fromDensity);
  }
  const fromBrightness = getValueByPath(fromObject, ["brightness"]);
  if (fromBrightness != null) {
    setValueByPath(toObject, ["brightness"], fromBrightness);
  }
  const fromScale = getValueByPath(fromObject, ["scale"]);
  if (fromScale != null) {
    setValueByPath(toObject, ["scale"], fromScale);
  }
  const fromMuteBass = getValueByPath(fromObject, ["muteBass"]);
  if (fromMuteBass != null) {
    setValueByPath(toObject, ["muteBass"], fromMuteBass);
  }
  const fromMuteDrums = getValueByPath(fromObject, ["muteDrums"]);
  if (fromMuteDrums != null) {
    setValueByPath(toObject, ["muteDrums"], fromMuteDrums);
  }
  const fromOnlyBassAndDrums = getValueByPath(fromObject, [
    "onlyBassAndDrums"
  ]);
  if (fromOnlyBassAndDrums != null) {
    setValueByPath(toObject, ["onlyBassAndDrums"], fromOnlyBassAndDrums);
  }
  const fromMusicGenerationMode = getValueByPath(fromObject, [
    "musicGenerationMode"
  ]);
  if (fromMusicGenerationMode != null) {
    setValueByPath(toObject, ["musicGenerationMode"], fromMusicGenerationMode);
  }
  return toObject;
}
function liveMusicSetConfigParametersToMldev(fromObject) {
  const toObject = {};
  const fromMusicGenerationConfig = getValueByPath(fromObject, [
    "musicGenerationConfig"
  ]);
  if (fromMusicGenerationConfig != null) {
    setValueByPath(toObject, ["musicGenerationConfig"], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig));
  }
  return toObject;
}
function liveMusicClientSetupToMldev(fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], fromModel);
  }
  return toObject;
}
function liveMusicClientContentToMldev(fromObject) {
  const toObject = {};
  const fromWeightedPrompts = getValueByPath(fromObject, [
    "weightedPrompts"
  ]);
  if (fromWeightedPrompts != null) {
    let transformedList = fromWeightedPrompts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return weightedPromptToMldev(item);
      });
    }
    setValueByPath(toObject, ["weightedPrompts"], transformedList);
  }
  return toObject;
}
function liveMusicClientMessageToMldev(fromObject) {
  const toObject = {};
  const fromSetup = getValueByPath(fromObject, ["setup"]);
  if (fromSetup != null) {
    setValueByPath(toObject, ["setup"], liveMusicClientSetupToMldev(fromSetup));
  }
  const fromClientContent = getValueByPath(fromObject, [
    "clientContent"
  ]);
  if (fromClientContent != null) {
    setValueByPath(toObject, ["clientContent"], liveMusicClientContentToMldev(fromClientContent));
  }
  const fromMusicGenerationConfig = getValueByPath(fromObject, [
    "musicGenerationConfig"
  ]);
  if (fromMusicGenerationConfig != null) {
    setValueByPath(toObject, ["musicGenerationConfig"], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig));
  }
  const fromPlaybackControl = getValueByPath(fromObject, [
    "playbackControl"
  ]);
  if (fromPlaybackControl != null) {
    setValueByPath(toObject, ["playbackControl"], fromPlaybackControl);
  }
  return toObject;
}
function prebuiltVoiceConfigToVertex$1(fromObject) {
  const toObject = {};
  const fromVoiceName = getValueByPath(fromObject, ["voiceName"]);
  if (fromVoiceName != null) {
    setValueByPath(toObject, ["voiceName"], fromVoiceName);
  }
  return toObject;
}
function voiceConfigToVertex$1(fromObject) {
  const toObject = {};
  const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [
    "prebuiltVoiceConfig"
  ]);
  if (fromPrebuiltVoiceConfig != null) {
    setValueByPath(toObject, ["prebuiltVoiceConfig"], prebuiltVoiceConfigToVertex$1(fromPrebuiltVoiceConfig));
  }
  return toObject;
}
function speechConfigToVertex$1(fromObject) {
  const toObject = {};
  const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToVertex$1(fromVoiceConfig));
  }
  if (getValueByPath(fromObject, ["multiSpeakerVoiceConfig"]) !== void 0) {
    throw new Error("multiSpeakerVoiceConfig parameter is not supported in Vertex AI.");
  }
  const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function videoMetadataToVertex$1(fromObject) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobToVertex$1(fromObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataToVertex$1(fromObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromFileUri = getValueByPath(fromObject, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function partToVertex$1(fromObject) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataToVertex$1(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToVertex$1(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToVertex$1(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromCodeExecutionResult = getValueByPath(fromObject, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], fromFunctionCall);
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentToVertex$1(fromObject) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToVertex$1(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function functionDeclarationToVertex$1(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["behavior"]) !== void 0) {
    throw new Error("behavior parameter is not supported in Vertex AI.");
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  return toObject;
}
function intervalToVertex$1(fromObject) {
  const toObject = {};
  const fromStartTime = getValueByPath(fromObject, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  return toObject;
}
function googleSearchToVertex$1(fromObject) {
  const toObject = {};
  const fromTimeRangeFilter = getValueByPath(fromObject, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], intervalToVertex$1(fromTimeRangeFilter));
  }
  const fromExcludeDomains = getValueByPath(fromObject, [
    "excludeDomains"
  ]);
  if (fromExcludeDomains != null) {
    setValueByPath(toObject, ["excludeDomains"], fromExcludeDomains);
  }
  return toObject;
}
function dynamicRetrievalConfigToVertex$1(fromObject) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromDynamicThreshold = getValueByPath(fromObject, [
    "dynamicThreshold"
  ]);
  if (fromDynamicThreshold != null) {
    setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold);
  }
  return toObject;
}
function googleSearchRetrievalToVertex$1(fromObject) {
  const toObject = {};
  const fromDynamicRetrievalConfig = getValueByPath(fromObject, [
    "dynamicRetrievalConfig"
  ]);
  if (fromDynamicRetrievalConfig != null) {
    setValueByPath(toObject, ["dynamicRetrievalConfig"], dynamicRetrievalConfigToVertex$1(fromDynamicRetrievalConfig));
  }
  return toObject;
}
function enterpriseWebSearchToVertex$1(fromObject) {
  const toObject = {};
  const fromExcludeDomains = getValueByPath(fromObject, [
    "excludeDomains"
  ]);
  if (fromExcludeDomains != null) {
    setValueByPath(toObject, ["excludeDomains"], fromExcludeDomains);
  }
  return toObject;
}
function apiKeyConfigToVertex$1(fromObject) {
  const toObject = {};
  const fromApiKeyString = getValueByPath(fromObject, ["apiKeyString"]);
  if (fromApiKeyString != null) {
    setValueByPath(toObject, ["apiKeyString"], fromApiKeyString);
  }
  return toObject;
}
function authConfigToVertex$1(fromObject) {
  const toObject = {};
  const fromApiKeyConfig = getValueByPath(fromObject, ["apiKeyConfig"]);
  if (fromApiKeyConfig != null) {
    setValueByPath(toObject, ["apiKeyConfig"], apiKeyConfigToVertex$1(fromApiKeyConfig));
  }
  const fromAuthType = getValueByPath(fromObject, ["authType"]);
  if (fromAuthType != null) {
    setValueByPath(toObject, ["authType"], fromAuthType);
  }
  const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [
    "googleServiceAccountConfig"
  ]);
  if (fromGoogleServiceAccountConfig != null) {
    setValueByPath(toObject, ["googleServiceAccountConfig"], fromGoogleServiceAccountConfig);
  }
  const fromHttpBasicAuthConfig = getValueByPath(fromObject, [
    "httpBasicAuthConfig"
  ]);
  if (fromHttpBasicAuthConfig != null) {
    setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig);
  }
  const fromOauthConfig = getValueByPath(fromObject, ["oauthConfig"]);
  if (fromOauthConfig != null) {
    setValueByPath(toObject, ["oauthConfig"], fromOauthConfig);
  }
  const fromOidcConfig = getValueByPath(fromObject, ["oidcConfig"]);
  if (fromOidcConfig != null) {
    setValueByPath(toObject, ["oidcConfig"], fromOidcConfig);
  }
  return toObject;
}
function googleMapsToVertex$1(fromObject) {
  const toObject = {};
  const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]);
  if (fromAuthConfig != null) {
    setValueByPath(toObject, ["authConfig"], authConfigToVertex$1(fromAuthConfig));
  }
  return toObject;
}
function urlContextToVertex$1() {
  const toObject = {};
  return toObject;
}
function toolComputerUseToVertex$1(fromObject) {
  const toObject = {};
  const fromEnvironment = getValueByPath(fromObject, ["environment"]);
  if (fromEnvironment != null) {
    setValueByPath(toObject, ["environment"], fromEnvironment);
  }
  return toObject;
}
function toolToVertex$1(fromObject) {
  const toObject = {};
  const fromFunctionDeclarations = getValueByPath(fromObject, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToVertex$1(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  const fromRetrieval = getValueByPath(fromObject, ["retrieval"]);
  if (fromRetrieval != null) {
    setValueByPath(toObject, ["retrieval"], fromRetrieval);
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToVertex$1(fromGoogleSearch));
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], googleSearchRetrievalToVertex$1(fromGoogleSearchRetrieval));
  }
  const fromEnterpriseWebSearch = getValueByPath(fromObject, [
    "enterpriseWebSearch"
  ]);
  if (fromEnterpriseWebSearch != null) {
    setValueByPath(toObject, ["enterpriseWebSearch"], enterpriseWebSearchToVertex$1(fromEnterpriseWebSearch));
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], googleMapsToVertex$1(fromGoogleMaps));
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], urlContextToVertex$1());
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], toolComputerUseToVertex$1(fromComputerUse));
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  return toObject;
}
function sessionResumptionConfigToVertex(fromObject) {
  const toObject = {};
  const fromHandle = getValueByPath(fromObject, ["handle"]);
  if (fromHandle != null) {
    setValueByPath(toObject, ["handle"], fromHandle);
  }
  const fromTransparent = getValueByPath(fromObject, ["transparent"]);
  if (fromTransparent != null) {
    setValueByPath(toObject, ["transparent"], fromTransparent);
  }
  return toObject;
}
function audioTranscriptionConfigToVertex() {
  const toObject = {};
  return toObject;
}
function automaticActivityDetectionToVertex(fromObject) {
  const toObject = {};
  const fromDisabled = getValueByPath(fromObject, ["disabled"]);
  if (fromDisabled != null) {
    setValueByPath(toObject, ["disabled"], fromDisabled);
  }
  const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [
    "startOfSpeechSensitivity"
  ]);
  if (fromStartOfSpeechSensitivity != null) {
    setValueByPath(toObject, ["startOfSpeechSensitivity"], fromStartOfSpeechSensitivity);
  }
  const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [
    "endOfSpeechSensitivity"
  ]);
  if (fromEndOfSpeechSensitivity != null) {
    setValueByPath(toObject, ["endOfSpeechSensitivity"], fromEndOfSpeechSensitivity);
  }
  const fromPrefixPaddingMs = getValueByPath(fromObject, [
    "prefixPaddingMs"
  ]);
  if (fromPrefixPaddingMs != null) {
    setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs);
  }
  const fromSilenceDurationMs = getValueByPath(fromObject, [
    "silenceDurationMs"
  ]);
  if (fromSilenceDurationMs != null) {
    setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs);
  }
  return toObject;
}
function realtimeInputConfigToVertex(fromObject) {
  const toObject = {};
  const fromAutomaticActivityDetection = getValueByPath(fromObject, [
    "automaticActivityDetection"
  ]);
  if (fromAutomaticActivityDetection != null) {
    setValueByPath(toObject, ["automaticActivityDetection"], automaticActivityDetectionToVertex(fromAutomaticActivityDetection));
  }
  const fromActivityHandling = getValueByPath(fromObject, [
    "activityHandling"
  ]);
  if (fromActivityHandling != null) {
    setValueByPath(toObject, ["activityHandling"], fromActivityHandling);
  }
  const fromTurnCoverage = getValueByPath(fromObject, ["turnCoverage"]);
  if (fromTurnCoverage != null) {
    setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage);
  }
  return toObject;
}
function slidingWindowToVertex(fromObject) {
  const toObject = {};
  const fromTargetTokens = getValueByPath(fromObject, ["targetTokens"]);
  if (fromTargetTokens != null) {
    setValueByPath(toObject, ["targetTokens"], fromTargetTokens);
  }
  return toObject;
}
function contextWindowCompressionConfigToVertex(fromObject) {
  const toObject = {};
  const fromTriggerTokens = getValueByPath(fromObject, [
    "triggerTokens"
  ]);
  if (fromTriggerTokens != null) {
    setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens);
  }
  const fromSlidingWindow = getValueByPath(fromObject, [
    "slidingWindow"
  ]);
  if (fromSlidingWindow != null) {
    setValueByPath(toObject, ["slidingWindow"], slidingWindowToVertex(fromSlidingWindow));
  }
  return toObject;
}
function proactivityConfigToVertex(fromObject) {
  const toObject = {};
  const fromProactiveAudio = getValueByPath(fromObject, [
    "proactiveAudio"
  ]);
  if (fromProactiveAudio != null) {
    setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio);
  }
  return toObject;
}
function liveConnectConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromGenerationConfig = getValueByPath(fromObject, [
    "generationConfig"
  ]);
  if (parentObject !== void 0 && fromGenerationConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig"], fromGenerationConfig);
  }
  const fromResponseModalities = getValueByPath(fromObject, [
    "responseModalities"
  ]);
  if (parentObject !== void 0 && fromResponseModalities != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "responseModalities"], fromResponseModalities);
  }
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (parentObject !== void 0 && fromTemperature != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "temperature"], fromTemperature);
  }
  const fromTopP = getValueByPath(fromObject, ["topP"]);
  if (parentObject !== void 0 && fromTopP != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (parentObject !== void 0 && fromTopK != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "topK"], fromTopK);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject, [
    "maxOutputTokens"
  ]);
  if (parentObject !== void 0 && fromMaxOutputTokens != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (parentObject !== void 0 && fromMediaResolution != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "mediaResolution"], fromMediaResolution);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "seed"], fromSeed);
  }
  const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]);
  if (parentObject !== void 0 && fromSpeechConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "speechConfig"], speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig)));
  }
  const fromEnableAffectiveDialog = getValueByPath(fromObject, [
    "enableAffectiveDialog"
  ]);
  if (parentObject !== void 0 && fromEnableAffectiveDialog != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "enableAffectiveDialog"], fromEnableAffectiveDialog);
  }
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["setup", "systemInstruction"], contentToVertex$1(tContent(fromSystemInstruction)));
  }
  const fromTools = getValueByPath(fromObject, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = tTools(fromTools);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToVertex$1(tTool(item));
      });
    }
    setValueByPath(parentObject, ["setup", "tools"], transformedList);
  }
  const fromSessionResumption = getValueByPath(fromObject, [
    "sessionResumption"
  ]);
  if (parentObject !== void 0 && fromSessionResumption != null) {
    setValueByPath(parentObject, ["setup", "sessionResumption"], sessionResumptionConfigToVertex(fromSessionResumption));
  }
  const fromInputAudioTranscription = getValueByPath(fromObject, [
    "inputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromInputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "inputAudioTranscription"], audioTranscriptionConfigToVertex());
  }
  const fromOutputAudioTranscription = getValueByPath(fromObject, [
    "outputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromOutputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "outputAudioTranscription"], audioTranscriptionConfigToVertex());
  }
  const fromRealtimeInputConfig = getValueByPath(fromObject, [
    "realtimeInputConfig"
  ]);
  if (parentObject !== void 0 && fromRealtimeInputConfig != null) {
    setValueByPath(parentObject, ["setup", "realtimeInputConfig"], realtimeInputConfigToVertex(fromRealtimeInputConfig));
  }
  const fromContextWindowCompression = getValueByPath(fromObject, [
    "contextWindowCompression"
  ]);
  if (parentObject !== void 0 && fromContextWindowCompression != null) {
    setValueByPath(parentObject, ["setup", "contextWindowCompression"], contextWindowCompressionConfigToVertex(fromContextWindowCompression));
  }
  const fromProactivity = getValueByPath(fromObject, ["proactivity"]);
  if (parentObject !== void 0 && fromProactivity != null) {
    setValueByPath(parentObject, ["setup", "proactivity"], proactivityConfigToVertex(fromProactivity));
  }
  return toObject;
}
function liveConnectParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], liveConnectConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function activityStartToVertex() {
  const toObject = {};
  return toObject;
}
function activityEndToVertex() {
  const toObject = {};
  return toObject;
}
function liveSendRealtimeInputParametersToVertex(fromObject) {
  const toObject = {};
  const fromMedia = getValueByPath(fromObject, ["media"]);
  if (fromMedia != null) {
    setValueByPath(toObject, ["mediaChunks"], tBlobs(fromMedia));
  }
  const fromAudio = getValueByPath(fromObject, ["audio"]);
  if (fromAudio != null) {
    setValueByPath(toObject, ["audio"], tAudioBlob(fromAudio));
  }
  const fromAudioStreamEnd = getValueByPath(fromObject, [
    "audioStreamEnd"
  ]);
  if (fromAudioStreamEnd != null) {
    setValueByPath(toObject, ["audioStreamEnd"], fromAudioStreamEnd);
  }
  const fromVideo = getValueByPath(fromObject, ["video"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], tImageBlob(fromVideo));
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromActivityStart = getValueByPath(fromObject, [
    "activityStart"
  ]);
  if (fromActivityStart != null) {
    setValueByPath(toObject, ["activityStart"], activityStartToVertex());
  }
  const fromActivityEnd = getValueByPath(fromObject, ["activityEnd"]);
  if (fromActivityEnd != null) {
    setValueByPath(toObject, ["activityEnd"], activityEndToVertex());
  }
  return toObject;
}
function liveServerSetupCompleteFromMldev() {
  const toObject = {};
  return toObject;
}
function videoMetadataFromMldev$1(fromObject) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobFromMldev$1(fromObject) {
  const toObject = {};
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataFromMldev$1(fromObject) {
  const toObject = {};
  const fromFileUri = getValueByPath(fromObject, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function partFromMldev$1(fromObject) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataFromMldev$1(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobFromMldev$1(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataFromMldev$1(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromCodeExecutionResult = getValueByPath(fromObject, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], fromFunctionCall);
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentFromMldev$1(fromObject) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partFromMldev$1(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function transcriptionFromMldev(fromObject) {
  const toObject = {};
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromFinished = getValueByPath(fromObject, ["finished"]);
  if (fromFinished != null) {
    setValueByPath(toObject, ["finished"], fromFinished);
  }
  return toObject;
}
function urlMetadataFromMldev$1(fromObject) {
  const toObject = {};
  const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]);
  if (fromRetrievedUrl != null) {
    setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl);
  }
  const fromUrlRetrievalStatus = getValueByPath(fromObject, [
    "urlRetrievalStatus"
  ]);
  if (fromUrlRetrievalStatus != null) {
    setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus);
  }
  return toObject;
}
function urlContextMetadataFromMldev$1(fromObject) {
  const toObject = {};
  const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]);
  if (fromUrlMetadata != null) {
    let transformedList = fromUrlMetadata;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return urlMetadataFromMldev$1(item);
      });
    }
    setValueByPath(toObject, ["urlMetadata"], transformedList);
  }
  return toObject;
}
function liveServerContentFromMldev(fromObject) {
  const toObject = {};
  const fromModelTurn = getValueByPath(fromObject, ["modelTurn"]);
  if (fromModelTurn != null) {
    setValueByPath(toObject, ["modelTurn"], contentFromMldev$1(fromModelTurn));
  }
  const fromTurnComplete = getValueByPath(fromObject, ["turnComplete"]);
  if (fromTurnComplete != null) {
    setValueByPath(toObject, ["turnComplete"], fromTurnComplete);
  }
  const fromInterrupted = getValueByPath(fromObject, ["interrupted"]);
  if (fromInterrupted != null) {
    setValueByPath(toObject, ["interrupted"], fromInterrupted);
  }
  const fromGroundingMetadata = getValueByPath(fromObject, [
    "groundingMetadata"
  ]);
  if (fromGroundingMetadata != null) {
    setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata);
  }
  const fromGenerationComplete = getValueByPath(fromObject, [
    "generationComplete"
  ]);
  if (fromGenerationComplete != null) {
    setValueByPath(toObject, ["generationComplete"], fromGenerationComplete);
  }
  const fromInputTranscription = getValueByPath(fromObject, [
    "inputTranscription"
  ]);
  if (fromInputTranscription != null) {
    setValueByPath(toObject, ["inputTranscription"], transcriptionFromMldev(fromInputTranscription));
  }
  const fromOutputTranscription = getValueByPath(fromObject, [
    "outputTranscription"
  ]);
  if (fromOutputTranscription != null) {
    setValueByPath(toObject, ["outputTranscription"], transcriptionFromMldev(fromOutputTranscription));
  }
  const fromUrlContextMetadata = getValueByPath(fromObject, [
    "urlContextMetadata"
  ]);
  if (fromUrlContextMetadata != null) {
    setValueByPath(toObject, ["urlContextMetadata"], urlContextMetadataFromMldev$1(fromUrlContextMetadata));
  }
  return toObject;
}
function functionCallFromMldev(fromObject) {
  const toObject = {};
  const fromId = getValueByPath(fromObject, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  return toObject;
}
function liveServerToolCallFromMldev(fromObject) {
  const toObject = {};
  const fromFunctionCalls = getValueByPath(fromObject, [
    "functionCalls"
  ]);
  if (fromFunctionCalls != null) {
    let transformedList = fromFunctionCalls;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionCallFromMldev(item);
      });
    }
    setValueByPath(toObject, ["functionCalls"], transformedList);
  }
  return toObject;
}
function liveServerToolCallCancellationFromMldev(fromObject) {
  const toObject = {};
  const fromIds = getValueByPath(fromObject, ["ids"]);
  if (fromIds != null) {
    setValueByPath(toObject, ["ids"], fromIds);
  }
  return toObject;
}
function modalityTokenCountFromMldev(fromObject) {
  const toObject = {};
  const fromModality = getValueByPath(fromObject, ["modality"]);
  if (fromModality != null) {
    setValueByPath(toObject, ["modality"], fromModality);
  }
  const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]);
  if (fromTokenCount != null) {
    setValueByPath(toObject, ["tokenCount"], fromTokenCount);
  }
  return toObject;
}
function usageMetadataFromMldev(fromObject) {
  const toObject = {};
  const fromPromptTokenCount = getValueByPath(fromObject, [
    "promptTokenCount"
  ]);
  if (fromPromptTokenCount != null) {
    setValueByPath(toObject, ["promptTokenCount"], fromPromptTokenCount);
  }
  const fromCachedContentTokenCount = getValueByPath(fromObject, [
    "cachedContentTokenCount"
  ]);
  if (fromCachedContentTokenCount != null) {
    setValueByPath(toObject, ["cachedContentTokenCount"], fromCachedContentTokenCount);
  }
  const fromResponseTokenCount = getValueByPath(fromObject, [
    "responseTokenCount"
  ]);
  if (fromResponseTokenCount != null) {
    setValueByPath(toObject, ["responseTokenCount"], fromResponseTokenCount);
  }
  const fromToolUsePromptTokenCount = getValueByPath(fromObject, [
    "toolUsePromptTokenCount"
  ]);
  if (fromToolUsePromptTokenCount != null) {
    setValueByPath(toObject, ["toolUsePromptTokenCount"], fromToolUsePromptTokenCount);
  }
  const fromThoughtsTokenCount = getValueByPath(fromObject, [
    "thoughtsTokenCount"
  ]);
  if (fromThoughtsTokenCount != null) {
    setValueByPath(toObject, ["thoughtsTokenCount"], fromThoughtsTokenCount);
  }
  const fromTotalTokenCount = getValueByPath(fromObject, [
    "totalTokenCount"
  ]);
  if (fromTotalTokenCount != null) {
    setValueByPath(toObject, ["totalTokenCount"], fromTotalTokenCount);
  }
  const fromPromptTokensDetails = getValueByPath(fromObject, [
    "promptTokensDetails"
  ]);
  if (fromPromptTokensDetails != null) {
    let transformedList = fromPromptTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modalityTokenCountFromMldev(item);
      });
    }
    setValueByPath(toObject, ["promptTokensDetails"], transformedList);
  }
  const fromCacheTokensDetails = getValueByPath(fromObject, [
    "cacheTokensDetails"
  ]);
  if (fromCacheTokensDetails != null) {
    let transformedList = fromCacheTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modalityTokenCountFromMldev(item);
      });
    }
    setValueByPath(toObject, ["cacheTokensDetails"], transformedList);
  }
  const fromResponseTokensDetails = getValueByPath(fromObject, [
    "responseTokensDetails"
  ]);
  if (fromResponseTokensDetails != null) {
    let transformedList = fromResponseTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modalityTokenCountFromMldev(item);
      });
    }
    setValueByPath(toObject, ["responseTokensDetails"], transformedList);
  }
  const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [
    "toolUsePromptTokensDetails"
  ]);
  if (fromToolUsePromptTokensDetails != null) {
    let transformedList = fromToolUsePromptTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modalityTokenCountFromMldev(item);
      });
    }
    setValueByPath(toObject, ["toolUsePromptTokensDetails"], transformedList);
  }
  return toObject;
}
function liveServerGoAwayFromMldev(fromObject) {
  const toObject = {};
  const fromTimeLeft = getValueByPath(fromObject, ["timeLeft"]);
  if (fromTimeLeft != null) {
    setValueByPath(toObject, ["timeLeft"], fromTimeLeft);
  }
  return toObject;
}
function liveServerSessionResumptionUpdateFromMldev(fromObject) {
  const toObject = {};
  const fromNewHandle = getValueByPath(fromObject, ["newHandle"]);
  if (fromNewHandle != null) {
    setValueByPath(toObject, ["newHandle"], fromNewHandle);
  }
  const fromResumable = getValueByPath(fromObject, ["resumable"]);
  if (fromResumable != null) {
    setValueByPath(toObject, ["resumable"], fromResumable);
  }
  const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [
    "lastConsumedClientMessageIndex"
  ]);
  if (fromLastConsumedClientMessageIndex != null) {
    setValueByPath(toObject, ["lastConsumedClientMessageIndex"], fromLastConsumedClientMessageIndex);
  }
  return toObject;
}
function liveServerMessageFromMldev(fromObject) {
  const toObject = {};
  const fromSetupComplete = getValueByPath(fromObject, [
    "setupComplete"
  ]);
  if (fromSetupComplete != null) {
    setValueByPath(toObject, ["setupComplete"], liveServerSetupCompleteFromMldev());
  }
  const fromServerContent = getValueByPath(fromObject, [
    "serverContent"
  ]);
  if (fromServerContent != null) {
    setValueByPath(toObject, ["serverContent"], liveServerContentFromMldev(fromServerContent));
  }
  const fromToolCall = getValueByPath(fromObject, ["toolCall"]);
  if (fromToolCall != null) {
    setValueByPath(toObject, ["toolCall"], liveServerToolCallFromMldev(fromToolCall));
  }
  const fromToolCallCancellation = getValueByPath(fromObject, [
    "toolCallCancellation"
  ]);
  if (fromToolCallCancellation != null) {
    setValueByPath(toObject, ["toolCallCancellation"], liveServerToolCallCancellationFromMldev(fromToolCallCancellation));
  }
  const fromUsageMetadata = getValueByPath(fromObject, [
    "usageMetadata"
  ]);
  if (fromUsageMetadata != null) {
    setValueByPath(toObject, ["usageMetadata"], usageMetadataFromMldev(fromUsageMetadata));
  }
  const fromGoAway = getValueByPath(fromObject, ["goAway"]);
  if (fromGoAway != null) {
    setValueByPath(toObject, ["goAway"], liveServerGoAwayFromMldev(fromGoAway));
  }
  const fromSessionResumptionUpdate = getValueByPath(fromObject, [
    "sessionResumptionUpdate"
  ]);
  if (fromSessionResumptionUpdate != null) {
    setValueByPath(toObject, ["sessionResumptionUpdate"], liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate));
  }
  return toObject;
}
function liveMusicServerSetupCompleteFromMldev() {
  const toObject = {};
  return toObject;
}
function weightedPromptFromMldev(fromObject) {
  const toObject = {};
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromWeight = getValueByPath(fromObject, ["weight"]);
  if (fromWeight != null) {
    setValueByPath(toObject, ["weight"], fromWeight);
  }
  return toObject;
}
function liveMusicClientContentFromMldev(fromObject) {
  const toObject = {};
  const fromWeightedPrompts = getValueByPath(fromObject, [
    "weightedPrompts"
  ]);
  if (fromWeightedPrompts != null) {
    let transformedList = fromWeightedPrompts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return weightedPromptFromMldev(item);
      });
    }
    setValueByPath(toObject, ["weightedPrompts"], transformedList);
  }
  return toObject;
}
function liveMusicGenerationConfigFromMldev(fromObject) {
  const toObject = {};
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (fromTopK != null) {
    setValueByPath(toObject, ["topK"], fromTopK);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (fromSeed != null) {
    setValueByPath(toObject, ["seed"], fromSeed);
  }
  const fromGuidance = getValueByPath(fromObject, ["guidance"]);
  if (fromGuidance != null) {
    setValueByPath(toObject, ["guidance"], fromGuidance);
  }
  const fromBpm = getValueByPath(fromObject, ["bpm"]);
  if (fromBpm != null) {
    setValueByPath(toObject, ["bpm"], fromBpm);
  }
  const fromDensity = getValueByPath(fromObject, ["density"]);
  if (fromDensity != null) {
    setValueByPath(toObject, ["density"], fromDensity);
  }
  const fromBrightness = getValueByPath(fromObject, ["brightness"]);
  if (fromBrightness != null) {
    setValueByPath(toObject, ["brightness"], fromBrightness);
  }
  const fromScale = getValueByPath(fromObject, ["scale"]);
  if (fromScale != null) {
    setValueByPath(toObject, ["scale"], fromScale);
  }
  const fromMuteBass = getValueByPath(fromObject, ["muteBass"]);
  if (fromMuteBass != null) {
    setValueByPath(toObject, ["muteBass"], fromMuteBass);
  }
  const fromMuteDrums = getValueByPath(fromObject, ["muteDrums"]);
  if (fromMuteDrums != null) {
    setValueByPath(toObject, ["muteDrums"], fromMuteDrums);
  }
  const fromOnlyBassAndDrums = getValueByPath(fromObject, [
    "onlyBassAndDrums"
  ]);
  if (fromOnlyBassAndDrums != null) {
    setValueByPath(toObject, ["onlyBassAndDrums"], fromOnlyBassAndDrums);
  }
  const fromMusicGenerationMode = getValueByPath(fromObject, [
    "musicGenerationMode"
  ]);
  if (fromMusicGenerationMode != null) {
    setValueByPath(toObject, ["musicGenerationMode"], fromMusicGenerationMode);
  }
  return toObject;
}
function liveMusicSourceMetadataFromMldev(fromObject) {
  const toObject = {};
  const fromClientContent = getValueByPath(fromObject, [
    "clientContent"
  ]);
  if (fromClientContent != null) {
    setValueByPath(toObject, ["clientContent"], liveMusicClientContentFromMldev(fromClientContent));
  }
  const fromMusicGenerationConfig = getValueByPath(fromObject, [
    "musicGenerationConfig"
  ]);
  if (fromMusicGenerationConfig != null) {
    setValueByPath(toObject, ["musicGenerationConfig"], liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig));
  }
  return toObject;
}
function audioChunkFromMldev(fromObject) {
  const toObject = {};
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  const fromSourceMetadata = getValueByPath(fromObject, [
    "sourceMetadata"
  ]);
  if (fromSourceMetadata != null) {
    setValueByPath(toObject, ["sourceMetadata"], liveMusicSourceMetadataFromMldev(fromSourceMetadata));
  }
  return toObject;
}
function liveMusicServerContentFromMldev(fromObject) {
  const toObject = {};
  const fromAudioChunks = getValueByPath(fromObject, ["audioChunks"]);
  if (fromAudioChunks != null) {
    let transformedList = fromAudioChunks;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return audioChunkFromMldev(item);
      });
    }
    setValueByPath(toObject, ["audioChunks"], transformedList);
  }
  return toObject;
}
function liveMusicFilteredPromptFromMldev(fromObject) {
  const toObject = {};
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromFilteredReason = getValueByPath(fromObject, [
    "filteredReason"
  ]);
  if (fromFilteredReason != null) {
    setValueByPath(toObject, ["filteredReason"], fromFilteredReason);
  }
  return toObject;
}
function liveMusicServerMessageFromMldev(fromObject) {
  const toObject = {};
  const fromSetupComplete = getValueByPath(fromObject, [
    "setupComplete"
  ]);
  if (fromSetupComplete != null) {
    setValueByPath(toObject, ["setupComplete"], liveMusicServerSetupCompleteFromMldev());
  }
  const fromServerContent = getValueByPath(fromObject, [
    "serverContent"
  ]);
  if (fromServerContent != null) {
    setValueByPath(toObject, ["serverContent"], liveMusicServerContentFromMldev(fromServerContent));
  }
  const fromFilteredPrompt = getValueByPath(fromObject, [
    "filteredPrompt"
  ]);
  if (fromFilteredPrompt != null) {
    setValueByPath(toObject, ["filteredPrompt"], liveMusicFilteredPromptFromMldev(fromFilteredPrompt));
  }
  return toObject;
}
function liveServerSetupCompleteFromVertex(fromObject) {
  const toObject = {};
  const fromSessionId = getValueByPath(fromObject, ["sessionId"]);
  if (fromSessionId != null) {
    setValueByPath(toObject, ["sessionId"], fromSessionId);
  }
  return toObject;
}
function videoMetadataFromVertex$1(fromObject) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobFromVertex$1(fromObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataFromVertex$1(fromObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromFileUri = getValueByPath(fromObject, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function partFromVertex$1(fromObject) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataFromVertex$1(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobFromVertex$1(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataFromVertex$1(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromCodeExecutionResult = getValueByPath(fromObject, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], fromFunctionCall);
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentFromVertex$1(fromObject) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partFromVertex$1(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function transcriptionFromVertex(fromObject) {
  const toObject = {};
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromFinished = getValueByPath(fromObject, ["finished"]);
  if (fromFinished != null) {
    setValueByPath(toObject, ["finished"], fromFinished);
  }
  return toObject;
}
function liveServerContentFromVertex(fromObject) {
  const toObject = {};
  const fromModelTurn = getValueByPath(fromObject, ["modelTurn"]);
  if (fromModelTurn != null) {
    setValueByPath(toObject, ["modelTurn"], contentFromVertex$1(fromModelTurn));
  }
  const fromTurnComplete = getValueByPath(fromObject, ["turnComplete"]);
  if (fromTurnComplete != null) {
    setValueByPath(toObject, ["turnComplete"], fromTurnComplete);
  }
  const fromInterrupted = getValueByPath(fromObject, ["interrupted"]);
  if (fromInterrupted != null) {
    setValueByPath(toObject, ["interrupted"], fromInterrupted);
  }
  const fromGroundingMetadata = getValueByPath(fromObject, [
    "groundingMetadata"
  ]);
  if (fromGroundingMetadata != null) {
    setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata);
  }
  const fromGenerationComplete = getValueByPath(fromObject, [
    "generationComplete"
  ]);
  if (fromGenerationComplete != null) {
    setValueByPath(toObject, ["generationComplete"], fromGenerationComplete);
  }
  const fromInputTranscription = getValueByPath(fromObject, [
    "inputTranscription"
  ]);
  if (fromInputTranscription != null) {
    setValueByPath(toObject, ["inputTranscription"], transcriptionFromVertex(fromInputTranscription));
  }
  const fromOutputTranscription = getValueByPath(fromObject, [
    "outputTranscription"
  ]);
  if (fromOutputTranscription != null) {
    setValueByPath(toObject, ["outputTranscription"], transcriptionFromVertex(fromOutputTranscription));
  }
  return toObject;
}
function functionCallFromVertex(fromObject) {
  const toObject = {};
  const fromArgs = getValueByPath(fromObject, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  return toObject;
}
function liveServerToolCallFromVertex(fromObject) {
  const toObject = {};
  const fromFunctionCalls = getValueByPath(fromObject, [
    "functionCalls"
  ]);
  if (fromFunctionCalls != null) {
    let transformedList = fromFunctionCalls;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionCallFromVertex(item);
      });
    }
    setValueByPath(toObject, ["functionCalls"], transformedList);
  }
  return toObject;
}
function liveServerToolCallCancellationFromVertex(fromObject) {
  const toObject = {};
  const fromIds = getValueByPath(fromObject, ["ids"]);
  if (fromIds != null) {
    setValueByPath(toObject, ["ids"], fromIds);
  }
  return toObject;
}
function modalityTokenCountFromVertex(fromObject) {
  const toObject = {};
  const fromModality = getValueByPath(fromObject, ["modality"]);
  if (fromModality != null) {
    setValueByPath(toObject, ["modality"], fromModality);
  }
  const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]);
  if (fromTokenCount != null) {
    setValueByPath(toObject, ["tokenCount"], fromTokenCount);
  }
  return toObject;
}
function usageMetadataFromVertex(fromObject) {
  const toObject = {};
  const fromPromptTokenCount = getValueByPath(fromObject, [
    "promptTokenCount"
  ]);
  if (fromPromptTokenCount != null) {
    setValueByPath(toObject, ["promptTokenCount"], fromPromptTokenCount);
  }
  const fromCachedContentTokenCount = getValueByPath(fromObject, [
    "cachedContentTokenCount"
  ]);
  if (fromCachedContentTokenCount != null) {
    setValueByPath(toObject, ["cachedContentTokenCount"], fromCachedContentTokenCount);
  }
  const fromResponseTokenCount = getValueByPath(fromObject, [
    "candidatesTokenCount"
  ]);
  if (fromResponseTokenCount != null) {
    setValueByPath(toObject, ["responseTokenCount"], fromResponseTokenCount);
  }
  const fromToolUsePromptTokenCount = getValueByPath(fromObject, [
    "toolUsePromptTokenCount"
  ]);
  if (fromToolUsePromptTokenCount != null) {
    setValueByPath(toObject, ["toolUsePromptTokenCount"], fromToolUsePromptTokenCount);
  }
  const fromThoughtsTokenCount = getValueByPath(fromObject, [
    "thoughtsTokenCount"
  ]);
  if (fromThoughtsTokenCount != null) {
    setValueByPath(toObject, ["thoughtsTokenCount"], fromThoughtsTokenCount);
  }
  const fromTotalTokenCount = getValueByPath(fromObject, [
    "totalTokenCount"
  ]);
  if (fromTotalTokenCount != null) {
    setValueByPath(toObject, ["totalTokenCount"], fromTotalTokenCount);
  }
  const fromPromptTokensDetails = getValueByPath(fromObject, [
    "promptTokensDetails"
  ]);
  if (fromPromptTokensDetails != null) {
    let transformedList = fromPromptTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modalityTokenCountFromVertex(item);
      });
    }
    setValueByPath(toObject, ["promptTokensDetails"], transformedList);
  }
  const fromCacheTokensDetails = getValueByPath(fromObject, [
    "cacheTokensDetails"
  ]);
  if (fromCacheTokensDetails != null) {
    let transformedList = fromCacheTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modalityTokenCountFromVertex(item);
      });
    }
    setValueByPath(toObject, ["cacheTokensDetails"], transformedList);
  }
  const fromResponseTokensDetails = getValueByPath(fromObject, [
    "candidatesTokensDetails"
  ]);
  if (fromResponseTokensDetails != null) {
    let transformedList = fromResponseTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modalityTokenCountFromVertex(item);
      });
    }
    setValueByPath(toObject, ["responseTokensDetails"], transformedList);
  }
  const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [
    "toolUsePromptTokensDetails"
  ]);
  if (fromToolUsePromptTokensDetails != null) {
    let transformedList = fromToolUsePromptTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modalityTokenCountFromVertex(item);
      });
    }
    setValueByPath(toObject, ["toolUsePromptTokensDetails"], transformedList);
  }
  const fromTrafficType = getValueByPath(fromObject, ["trafficType"]);
  if (fromTrafficType != null) {
    setValueByPath(toObject, ["trafficType"], fromTrafficType);
  }
  return toObject;
}
function liveServerGoAwayFromVertex(fromObject) {
  const toObject = {};
  const fromTimeLeft = getValueByPath(fromObject, ["timeLeft"]);
  if (fromTimeLeft != null) {
    setValueByPath(toObject, ["timeLeft"], fromTimeLeft);
  }
  return toObject;
}
function liveServerSessionResumptionUpdateFromVertex(fromObject) {
  const toObject = {};
  const fromNewHandle = getValueByPath(fromObject, ["newHandle"]);
  if (fromNewHandle != null) {
    setValueByPath(toObject, ["newHandle"], fromNewHandle);
  }
  const fromResumable = getValueByPath(fromObject, ["resumable"]);
  if (fromResumable != null) {
    setValueByPath(toObject, ["resumable"], fromResumable);
  }
  const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [
    "lastConsumedClientMessageIndex"
  ]);
  if (fromLastConsumedClientMessageIndex != null) {
    setValueByPath(toObject, ["lastConsumedClientMessageIndex"], fromLastConsumedClientMessageIndex);
  }
  return toObject;
}
function liveServerMessageFromVertex(fromObject) {
  const toObject = {};
  const fromSetupComplete = getValueByPath(fromObject, [
    "setupComplete"
  ]);
  if (fromSetupComplete != null) {
    setValueByPath(toObject, ["setupComplete"], liveServerSetupCompleteFromVertex(fromSetupComplete));
  }
  const fromServerContent = getValueByPath(fromObject, [
    "serverContent"
  ]);
  if (fromServerContent != null) {
    setValueByPath(toObject, ["serverContent"], liveServerContentFromVertex(fromServerContent));
  }
  const fromToolCall = getValueByPath(fromObject, ["toolCall"]);
  if (fromToolCall != null) {
    setValueByPath(toObject, ["toolCall"], liveServerToolCallFromVertex(fromToolCall));
  }
  const fromToolCallCancellation = getValueByPath(fromObject, [
    "toolCallCancellation"
  ]);
  if (fromToolCallCancellation != null) {
    setValueByPath(toObject, ["toolCallCancellation"], liveServerToolCallCancellationFromVertex(fromToolCallCancellation));
  }
  const fromUsageMetadata = getValueByPath(fromObject, [
    "usageMetadata"
  ]);
  if (fromUsageMetadata != null) {
    setValueByPath(toObject, ["usageMetadata"], usageMetadataFromVertex(fromUsageMetadata));
  }
  const fromGoAway = getValueByPath(fromObject, ["goAway"]);
  if (fromGoAway != null) {
    setValueByPath(toObject, ["goAway"], liveServerGoAwayFromVertex(fromGoAway));
  }
  const fromSessionResumptionUpdate = getValueByPath(fromObject, [
    "sessionResumptionUpdate"
  ]);
  if (fromSessionResumptionUpdate != null) {
    setValueByPath(toObject, ["sessionResumptionUpdate"], liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate));
  }
  return toObject;
}
function videoMetadataToMldev$1(fromObject) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobToMldev$1(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataToMldev$1(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromFileUri = getValueByPath(fromObject, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function partToMldev$1(fromObject) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataToMldev$1(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev$1(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev$1(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromCodeExecutionResult = getValueByPath(fromObject, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], fromFunctionCall);
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentToMldev$1(fromObject) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToMldev$1(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function schemaToMldev(fromObject) {
  const toObject = {};
  const fromAnyOf = getValueByPath(fromObject, ["anyOf"]);
  if (fromAnyOf != null) {
    setValueByPath(toObject, ["anyOf"], fromAnyOf);
  }
  const fromDefault = getValueByPath(fromObject, ["default"]);
  if (fromDefault != null) {
    setValueByPath(toObject, ["default"], fromDefault);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromEnum = getValueByPath(fromObject, ["enum"]);
  if (fromEnum != null) {
    setValueByPath(toObject, ["enum"], fromEnum);
  }
  const fromExample = getValueByPath(fromObject, ["example"]);
  if (fromExample != null) {
    setValueByPath(toObject, ["example"], fromExample);
  }
  const fromFormat = getValueByPath(fromObject, ["format"]);
  if (fromFormat != null) {
    setValueByPath(toObject, ["format"], fromFormat);
  }
  const fromItems = getValueByPath(fromObject, ["items"]);
  if (fromItems != null) {
    setValueByPath(toObject, ["items"], fromItems);
  }
  const fromMaxItems = getValueByPath(fromObject, ["maxItems"]);
  if (fromMaxItems != null) {
    setValueByPath(toObject, ["maxItems"], fromMaxItems);
  }
  const fromMaxLength = getValueByPath(fromObject, ["maxLength"]);
  if (fromMaxLength != null) {
    setValueByPath(toObject, ["maxLength"], fromMaxLength);
  }
  const fromMaxProperties = getValueByPath(fromObject, [
    "maxProperties"
  ]);
  if (fromMaxProperties != null) {
    setValueByPath(toObject, ["maxProperties"], fromMaxProperties);
  }
  const fromMaximum = getValueByPath(fromObject, ["maximum"]);
  if (fromMaximum != null) {
    setValueByPath(toObject, ["maximum"], fromMaximum);
  }
  const fromMinItems = getValueByPath(fromObject, ["minItems"]);
  if (fromMinItems != null) {
    setValueByPath(toObject, ["minItems"], fromMinItems);
  }
  const fromMinLength = getValueByPath(fromObject, ["minLength"]);
  if (fromMinLength != null) {
    setValueByPath(toObject, ["minLength"], fromMinLength);
  }
  const fromMinProperties = getValueByPath(fromObject, [
    "minProperties"
  ]);
  if (fromMinProperties != null) {
    setValueByPath(toObject, ["minProperties"], fromMinProperties);
  }
  const fromMinimum = getValueByPath(fromObject, ["minimum"]);
  if (fromMinimum != null) {
    setValueByPath(toObject, ["minimum"], fromMinimum);
  }
  const fromNullable = getValueByPath(fromObject, ["nullable"]);
  if (fromNullable != null) {
    setValueByPath(toObject, ["nullable"], fromNullable);
  }
  const fromPattern = getValueByPath(fromObject, ["pattern"]);
  if (fromPattern != null) {
    setValueByPath(toObject, ["pattern"], fromPattern);
  }
  const fromProperties = getValueByPath(fromObject, ["properties"]);
  if (fromProperties != null) {
    setValueByPath(toObject, ["properties"], fromProperties);
  }
  const fromPropertyOrdering = getValueByPath(fromObject, [
    "propertyOrdering"
  ]);
  if (fromPropertyOrdering != null) {
    setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering);
  }
  const fromRequired = getValueByPath(fromObject, ["required"]);
  if (fromRequired != null) {
    setValueByPath(toObject, ["required"], fromRequired);
  }
  const fromTitle = getValueByPath(fromObject, ["title"]);
  if (fromTitle != null) {
    setValueByPath(toObject, ["title"], fromTitle);
  }
  const fromType = getValueByPath(fromObject, ["type"]);
  if (fromType != null) {
    setValueByPath(toObject, ["type"], fromType);
  }
  return toObject;
}
function safetySettingToMldev(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["method"]) !== void 0) {
    throw new Error("method parameter is not supported in Gemini API.");
  }
  const fromCategory = getValueByPath(fromObject, ["category"]);
  if (fromCategory != null) {
    setValueByPath(toObject, ["category"], fromCategory);
  }
  const fromThreshold = getValueByPath(fromObject, ["threshold"]);
  if (fromThreshold != null) {
    setValueByPath(toObject, ["threshold"], fromThreshold);
  }
  return toObject;
}
function functionDeclarationToMldev$1(fromObject) {
  const toObject = {};
  const fromBehavior = getValueByPath(fromObject, ["behavior"]);
  if (fromBehavior != null) {
    setValueByPath(toObject, ["behavior"], fromBehavior);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  return toObject;
}
function intervalToMldev$1(fromObject) {
  const toObject = {};
  const fromStartTime = getValueByPath(fromObject, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  return toObject;
}
function googleSearchToMldev$1(fromObject) {
  const toObject = {};
  const fromTimeRangeFilter = getValueByPath(fromObject, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], intervalToMldev$1(fromTimeRangeFilter));
  }
  if (getValueByPath(fromObject, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  return toObject;
}
function dynamicRetrievalConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromDynamicThreshold = getValueByPath(fromObject, [
    "dynamicThreshold"
  ]);
  if (fromDynamicThreshold != null) {
    setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold);
  }
  return toObject;
}
function googleSearchRetrievalToMldev$1(fromObject) {
  const toObject = {};
  const fromDynamicRetrievalConfig = getValueByPath(fromObject, [
    "dynamicRetrievalConfig"
  ]);
  if (fromDynamicRetrievalConfig != null) {
    setValueByPath(toObject, ["dynamicRetrievalConfig"], dynamicRetrievalConfigToMldev$1(fromDynamicRetrievalConfig));
  }
  return toObject;
}
function urlContextToMldev$1() {
  const toObject = {};
  return toObject;
}
function toolComputerUseToMldev$1(fromObject) {
  const toObject = {};
  const fromEnvironment = getValueByPath(fromObject, ["environment"]);
  if (fromEnvironment != null) {
    setValueByPath(toObject, ["environment"], fromEnvironment);
  }
  return toObject;
}
function toolToMldev$1(fromObject) {
  const toObject = {};
  const fromFunctionDeclarations = getValueByPath(fromObject, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToMldev$1(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  if (getValueByPath(fromObject, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$1(fromGoogleSearch));
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], googleSearchRetrievalToMldev$1(fromGoogleSearchRetrieval));
  }
  if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["googleMaps"]) !== void 0) {
    throw new Error("googleMaps parameter is not supported in Gemini API.");
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], urlContextToMldev$1());
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], toolComputerUseToMldev$1(fromComputerUse));
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  return toObject;
}
function functionCallingConfigToMldev(fromObject) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromAllowedFunctionNames = getValueByPath(fromObject, [
    "allowedFunctionNames"
  ]);
  if (fromAllowedFunctionNames != null) {
    setValueByPath(toObject, ["allowedFunctionNames"], fromAllowedFunctionNames);
  }
  return toObject;
}
function latLngToMldev(fromObject) {
  const toObject = {};
  const fromLatitude = getValueByPath(fromObject, ["latitude"]);
  if (fromLatitude != null) {
    setValueByPath(toObject, ["latitude"], fromLatitude);
  }
  const fromLongitude = getValueByPath(fromObject, ["longitude"]);
  if (fromLongitude != null) {
    setValueByPath(toObject, ["longitude"], fromLongitude);
  }
  return toObject;
}
function retrievalConfigToMldev(fromObject) {
  const toObject = {};
  const fromLatLng = getValueByPath(fromObject, ["latLng"]);
  if (fromLatLng != null) {
    setValueByPath(toObject, ["latLng"], latLngToMldev(fromLatLng));
  }
  const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function toolConfigToMldev(fromObject) {
  const toObject = {};
  const fromFunctionCallingConfig = getValueByPath(fromObject, [
    "functionCallingConfig"
  ]);
  if (fromFunctionCallingConfig != null) {
    setValueByPath(toObject, ["functionCallingConfig"], functionCallingConfigToMldev(fromFunctionCallingConfig));
  }
  const fromRetrievalConfig = getValueByPath(fromObject, [
    "retrievalConfig"
  ]);
  if (fromRetrievalConfig != null) {
    setValueByPath(toObject, ["retrievalConfig"], retrievalConfigToMldev(fromRetrievalConfig));
  }
  return toObject;
}
function prebuiltVoiceConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromVoiceName = getValueByPath(fromObject, ["voiceName"]);
  if (fromVoiceName != null) {
    setValueByPath(toObject, ["voiceName"], fromVoiceName);
  }
  return toObject;
}
function voiceConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [
    "prebuiltVoiceConfig"
  ]);
  if (fromPrebuiltVoiceConfig != null) {
    setValueByPath(toObject, ["prebuiltVoiceConfig"], prebuiltVoiceConfigToMldev$1(fromPrebuiltVoiceConfig));
  }
  return toObject;
}
function speakerVoiceConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromSpeaker = getValueByPath(fromObject, ["speaker"]);
  if (fromSpeaker != null) {
    setValueByPath(toObject, ["speaker"], fromSpeaker);
  }
  const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToMldev$1(fromVoiceConfig));
  }
  return toObject;
}
function multiSpeakerVoiceConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [
    "speakerVoiceConfigs"
  ]);
  if (fromSpeakerVoiceConfigs != null) {
    let transformedList = fromSpeakerVoiceConfigs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return speakerVoiceConfigToMldev$1(item);
      });
    }
    setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList);
  }
  return toObject;
}
function speechConfigToMldev$1(fromObject) {
  const toObject = {};
  const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToMldev$1(fromVoiceConfig));
  }
  const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [
    "multiSpeakerVoiceConfig"
  ]);
  if (fromMultiSpeakerVoiceConfig != null) {
    setValueByPath(toObject, ["multiSpeakerVoiceConfig"], multiSpeakerVoiceConfigToMldev$1(fromMultiSpeakerVoiceConfig));
  }
  const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function thinkingConfigToMldev(fromObject) {
  const toObject = {};
  const fromIncludeThoughts = getValueByPath(fromObject, [
    "includeThoughts"
  ]);
  if (fromIncludeThoughts != null) {
    setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts);
  }
  const fromThinkingBudget = getValueByPath(fromObject, [
    "thinkingBudget"
  ]);
  if (fromThinkingBudget != null) {
    setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget);
  }
  return toObject;
}
function generateContentConfigToMldev(apiClient, fromObject, parentObject) {
  const toObject = {};
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], contentToMldev$1(tContent(fromSystemInstruction)));
  }
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromTopP = getValueByPath(fromObject, ["topP"]);
  if (fromTopP != null) {
    setValueByPath(toObject, ["topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (fromTopK != null) {
    setValueByPath(toObject, ["topK"], fromTopK);
  }
  const fromCandidateCount = getValueByPath(fromObject, [
    "candidateCount"
  ]);
  if (fromCandidateCount != null) {
    setValueByPath(toObject, ["candidateCount"], fromCandidateCount);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject, [
    "maxOutputTokens"
  ]);
  if (fromMaxOutputTokens != null) {
    setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromStopSequences = getValueByPath(fromObject, [
    "stopSequences"
  ]);
  if (fromStopSequences != null) {
    setValueByPath(toObject, ["stopSequences"], fromStopSequences);
  }
  const fromResponseLogprobs = getValueByPath(fromObject, [
    "responseLogprobs"
  ]);
  if (fromResponseLogprobs != null) {
    setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs);
  }
  const fromLogprobs = getValueByPath(fromObject, ["logprobs"]);
  if (fromLogprobs != null) {
    setValueByPath(toObject, ["logprobs"], fromLogprobs);
  }
  const fromPresencePenalty = getValueByPath(fromObject, [
    "presencePenalty"
  ]);
  if (fromPresencePenalty != null) {
    setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty);
  }
  const fromFrequencyPenalty = getValueByPath(fromObject, [
    "frequencyPenalty"
  ]);
  if (fromFrequencyPenalty != null) {
    setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (fromSeed != null) {
    setValueByPath(toObject, ["seed"], fromSeed);
  }
  const fromResponseMimeType = getValueByPath(fromObject, [
    "responseMimeType"
  ]);
  if (fromResponseMimeType != null) {
    setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType);
  }
  const fromResponseSchema = getValueByPath(fromObject, [
    "responseSchema"
  ]);
  if (fromResponseSchema != null) {
    setValueByPath(toObject, ["responseSchema"], schemaToMldev(tSchema(fromResponseSchema)));
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  if (getValueByPath(fromObject, ["routingConfig"]) !== void 0) {
    throw new Error("routingConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["modelSelectionConfig"]) !== void 0) {
    throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");
  }
  const fromSafetySettings = getValueByPath(fromObject, [
    "safetySettings"
  ]);
  if (parentObject !== void 0 && fromSafetySettings != null) {
    let transformedList = fromSafetySettings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return safetySettingToMldev(item);
      });
    }
    setValueByPath(parentObject, ["safetySettings"], transformedList);
  }
  const fromTools = getValueByPath(fromObject, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = tTools(fromTools);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToMldev$1(tTool(item));
      });
    }
    setValueByPath(parentObject, ["tools"], transformedList);
  }
  const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]);
  if (parentObject !== void 0 && fromToolConfig != null) {
    setValueByPath(parentObject, ["toolConfig"], toolConfigToMldev(fromToolConfig));
  }
  if (getValueByPath(fromObject, ["labels"]) !== void 0) {
    throw new Error("labels parameter is not supported in Gemini API.");
  }
  const fromCachedContent = getValueByPath(fromObject, [
    "cachedContent"
  ]);
  if (parentObject !== void 0 && fromCachedContent != null) {
    setValueByPath(parentObject, ["cachedContent"], tCachedContentName(apiClient, fromCachedContent));
  }
  const fromResponseModalities = getValueByPath(fromObject, [
    "responseModalities"
  ]);
  if (fromResponseModalities != null) {
    setValueByPath(toObject, ["responseModalities"], fromResponseModalities);
  }
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]);
  if (fromSpeechConfig != null) {
    setValueByPath(toObject, ["speechConfig"], speechConfigToMldev$1(tSpeechConfig(fromSpeechConfig)));
  }
  if (getValueByPath(fromObject, ["audioTimestamp"]) !== void 0) {
    throw new Error("audioTimestamp parameter is not supported in Gemini API.");
  }
  const fromThinkingConfig = getValueByPath(fromObject, [
    "thinkingConfig"
  ]);
  if (fromThinkingConfig != null) {
    setValueByPath(toObject, ["thinkingConfig"], thinkingConfigToMldev(fromThinkingConfig));
  }
  return toObject;
}
function generateContentParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToMldev$1(item);
      });
    }
    setValueByPath(toObject, ["contents"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["generationConfig"], generateContentConfigToMldev(apiClient, fromConfig, toObject));
  }
  return toObject;
}
function embedContentConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromTaskType = getValueByPath(fromObject, ["taskType"]);
  if (parentObject !== void 0 && fromTaskType != null) {
    setValueByPath(parentObject, ["requests[]", "taskType"], fromTaskType);
  }
  const fromTitle = getValueByPath(fromObject, ["title"]);
  if (parentObject !== void 0 && fromTitle != null) {
    setValueByPath(parentObject, ["requests[]", "title"], fromTitle);
  }
  const fromOutputDimensionality = getValueByPath(fromObject, [
    "outputDimensionality"
  ]);
  if (parentObject !== void 0 && fromOutputDimensionality != null) {
    setValueByPath(parentObject, ["requests[]", "outputDimensionality"], fromOutputDimensionality);
  }
  if (getValueByPath(fromObject, ["mimeType"]) !== void 0) {
    throw new Error("mimeType parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["autoTruncate"]) !== void 0) {
    throw new Error("autoTruncate parameter is not supported in Gemini API.");
  }
  return toObject;
}
function embedContentParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (fromContents != null) {
    setValueByPath(toObject, ["requests[]", "content"], tContentsForEmbed(apiClient, fromContents));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], embedContentConfigToMldev(fromConfig, toObject));
  }
  const fromModelForEmbedContent = getValueByPath(fromObject, ["model"]);
  if (fromModelForEmbedContent !== void 0) {
    setValueByPath(toObject, ["requests[]", "model"], tModel(apiClient, fromModelForEmbedContent));
  }
  return toObject;
}
function generateImagesConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["outputGcsUri"]) !== void 0) {
    throw new Error("outputGcsUri parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["negativePrompt"]) !== void 0) {
    throw new Error("negativePrompt parameter is not supported in Gemini API.");
  }
  const fromNumberOfImages = getValueByPath(fromObject, [
    "numberOfImages"
  ]);
  if (parentObject !== void 0 && fromNumberOfImages != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages);
  }
  const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]);
  if (parentObject !== void 0 && fromAspectRatio != null) {
    setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio);
  }
  const fromGuidanceScale = getValueByPath(fromObject, [
    "guidanceScale"
  ]);
  if (parentObject !== void 0 && fromGuidanceScale != null) {
    setValueByPath(parentObject, ["parameters", "guidanceScale"], fromGuidanceScale);
  }
  if (getValueByPath(fromObject, ["seed"]) !== void 0) {
    throw new Error("seed parameter is not supported in Gemini API.");
  }
  const fromSafetyFilterLevel = getValueByPath(fromObject, [
    "safetyFilterLevel"
  ]);
  if (parentObject !== void 0 && fromSafetyFilterLevel != null) {
    setValueByPath(parentObject, ["parameters", "safetySetting"], fromSafetyFilterLevel);
  }
  const fromPersonGeneration = getValueByPath(fromObject, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  const fromIncludeSafetyAttributes = getValueByPath(fromObject, [
    "includeSafetyAttributes"
  ]);
  if (parentObject !== void 0 && fromIncludeSafetyAttributes != null) {
    setValueByPath(parentObject, ["parameters", "includeSafetyAttributes"], fromIncludeSafetyAttributes);
  }
  const fromIncludeRaiReason = getValueByPath(fromObject, [
    "includeRaiReason"
  ]);
  if (parentObject !== void 0 && fromIncludeRaiReason != null) {
    setValueByPath(parentObject, ["parameters", "includeRaiReason"], fromIncludeRaiReason);
  }
  const fromLanguage = getValueByPath(fromObject, ["language"]);
  if (parentObject !== void 0 && fromLanguage != null) {
    setValueByPath(parentObject, ["parameters", "language"], fromLanguage);
  }
  const fromOutputMimeType = getValueByPath(fromObject, [
    "outputMimeType"
  ]);
  if (parentObject !== void 0 && fromOutputMimeType != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType);
  }
  const fromOutputCompressionQuality = getValueByPath(fromObject, [
    "outputCompressionQuality"
  ]);
  if (parentObject !== void 0 && fromOutputCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality);
  }
  if (getValueByPath(fromObject, ["addWatermark"]) !== void 0) {
    throw new Error("addWatermark parameter is not supported in Gemini API.");
  }
  const fromImageSize = getValueByPath(fromObject, ["imageSize"]);
  if (parentObject !== void 0 && fromImageSize != null) {
    setValueByPath(parentObject, ["parameters", "sampleImageSize"], fromImageSize);
  }
  if (getValueByPath(fromObject, ["enhancePrompt"]) !== void 0) {
    throw new Error("enhancePrompt parameter is not supported in Gemini API.");
  }
  return toObject;
}
function generateImagesParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromPrompt = getValueByPath(fromObject, ["prompt"]);
  if (fromPrompt != null) {
    setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], generateImagesConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function getModelParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function listModelsConfigToMldev(apiClient, fromObject, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  const fromFilter = getValueByPath(fromObject, ["filter"]);
  if (parentObject !== void 0 && fromFilter != null) {
    setValueByPath(parentObject, ["_query", "filter"], fromFilter);
  }
  const fromQueryBase = getValueByPath(fromObject, ["queryBase"]);
  if (parentObject !== void 0 && fromQueryBase != null) {
    setValueByPath(parentObject, ["_url", "models_url"], tModelsUrl(apiClient, fromQueryBase));
  }
  return toObject;
}
function listModelsParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], listModelsConfigToMldev(apiClient, fromConfig, toObject));
  }
  return toObject;
}
function updateModelConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (parentObject !== void 0 && fromDescription != null) {
    setValueByPath(parentObject, ["description"], fromDescription);
  }
  const fromDefaultCheckpointId = getValueByPath(fromObject, [
    "defaultCheckpointId"
  ]);
  if (parentObject !== void 0 && fromDefaultCheckpointId != null) {
    setValueByPath(parentObject, ["defaultCheckpointId"], fromDefaultCheckpointId);
  }
  return toObject;
}
function updateModelParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], updateModelConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function deleteModelParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function countTokensConfigToMldev(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["systemInstruction"]) !== void 0) {
    throw new Error("systemInstruction parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["tools"]) !== void 0) {
    throw new Error("tools parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["generationConfig"]) !== void 0) {
    throw new Error("generationConfig parameter is not supported in Gemini API.");
  }
  return toObject;
}
function countTokensParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToMldev$1(item);
      });
    }
    setValueByPath(toObject, ["contents"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], countTokensConfigToMldev(fromConfig));
  }
  return toObject;
}
function imageToMldev(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["gcsUri"]) !== void 0) {
    throw new Error("gcsUri parameter is not supported in Gemini API.");
  }
  const fromImageBytes = getValueByPath(fromObject, ["imageBytes"]);
  if (fromImageBytes != null) {
    setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromImageBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function generateVideosSourceToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromPrompt = getValueByPath(fromObject, ["prompt"]);
  if (parentObject !== void 0 && fromPrompt != null) {
    setValueByPath(parentObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (parentObject !== void 0 && fromImage != null) {
    setValueByPath(parentObject, ["instances[0]", "image"], imageToMldev(fromImage));
  }
  if (getValueByPath(fromObject, ["video"]) !== void 0) {
    throw new Error("video parameter is not supported in Gemini API.");
  }
  return toObject;
}
function generateVideosConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromNumberOfVideos = getValueByPath(fromObject, [
    "numberOfVideos"
  ]);
  if (parentObject !== void 0 && fromNumberOfVideos != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfVideos);
  }
  if (getValueByPath(fromObject, ["outputGcsUri"]) !== void 0) {
    throw new Error("outputGcsUri parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["fps"]) !== void 0) {
    throw new Error("fps parameter is not supported in Gemini API.");
  }
  const fromDurationSeconds = getValueByPath(fromObject, [
    "durationSeconds"
  ]);
  if (parentObject !== void 0 && fromDurationSeconds != null) {
    setValueByPath(parentObject, ["parameters", "durationSeconds"], fromDurationSeconds);
  }
  if (getValueByPath(fromObject, ["seed"]) !== void 0) {
    throw new Error("seed parameter is not supported in Gemini API.");
  }
  const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]);
  if (parentObject !== void 0 && fromAspectRatio != null) {
    setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio);
  }
  if (getValueByPath(fromObject, ["resolution"]) !== void 0) {
    throw new Error("resolution parameter is not supported in Gemini API.");
  }
  const fromPersonGeneration = getValueByPath(fromObject, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  if (getValueByPath(fromObject, ["pubsubTopic"]) !== void 0) {
    throw new Error("pubsubTopic parameter is not supported in Gemini API.");
  }
  const fromNegativePrompt = getValueByPath(fromObject, [
    "negativePrompt"
  ]);
  if (parentObject !== void 0 && fromNegativePrompt != null) {
    setValueByPath(parentObject, ["parameters", "negativePrompt"], fromNegativePrompt);
  }
  const fromEnhancePrompt = getValueByPath(fromObject, [
    "enhancePrompt"
  ]);
  if (parentObject !== void 0 && fromEnhancePrompt != null) {
    setValueByPath(parentObject, ["parameters", "enhancePrompt"], fromEnhancePrompt);
  }
  if (getValueByPath(fromObject, ["generateAudio"]) !== void 0) {
    throw new Error("generateAudio parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["lastFrame"]) !== void 0) {
    throw new Error("lastFrame parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["referenceImages"]) !== void 0) {
    throw new Error("referenceImages parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["compressionQuality"]) !== void 0) {
    throw new Error("compressionQuality parameter is not supported in Gemini API.");
  }
  return toObject;
}
function generateVideosParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromPrompt = getValueByPath(fromObject, ["prompt"]);
  if (fromPrompt != null) {
    setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["instances[0]", "image"], imageToMldev(fromImage));
  }
  if (getValueByPath(fromObject, ["video"]) !== void 0) {
    throw new Error("video parameter is not supported in Gemini API.");
  }
  const fromSource = getValueByPath(fromObject, ["source"]);
  if (fromSource != null) {
    setValueByPath(toObject, ["config"], generateVideosSourceToMldev(fromSource, toObject));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], generateVideosConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function videoMetadataToVertex(fromObject) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobToVertex(fromObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataToVertex(fromObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromFileUri = getValueByPath(fromObject, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function partToVertex(fromObject) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataToVertex(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToVertex(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToVertex(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromCodeExecutionResult = getValueByPath(fromObject, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], fromFunctionCall);
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentToVertex(fromObject) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToVertex(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function schemaToVertex(fromObject) {
  const toObject = {};
  const fromAnyOf = getValueByPath(fromObject, ["anyOf"]);
  if (fromAnyOf != null) {
    setValueByPath(toObject, ["anyOf"], fromAnyOf);
  }
  const fromDefault = getValueByPath(fromObject, ["default"]);
  if (fromDefault != null) {
    setValueByPath(toObject, ["default"], fromDefault);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromEnum = getValueByPath(fromObject, ["enum"]);
  if (fromEnum != null) {
    setValueByPath(toObject, ["enum"], fromEnum);
  }
  const fromExample = getValueByPath(fromObject, ["example"]);
  if (fromExample != null) {
    setValueByPath(toObject, ["example"], fromExample);
  }
  const fromFormat = getValueByPath(fromObject, ["format"]);
  if (fromFormat != null) {
    setValueByPath(toObject, ["format"], fromFormat);
  }
  const fromItems = getValueByPath(fromObject, ["items"]);
  if (fromItems != null) {
    setValueByPath(toObject, ["items"], fromItems);
  }
  const fromMaxItems = getValueByPath(fromObject, ["maxItems"]);
  if (fromMaxItems != null) {
    setValueByPath(toObject, ["maxItems"], fromMaxItems);
  }
  const fromMaxLength = getValueByPath(fromObject, ["maxLength"]);
  if (fromMaxLength != null) {
    setValueByPath(toObject, ["maxLength"], fromMaxLength);
  }
  const fromMaxProperties = getValueByPath(fromObject, [
    "maxProperties"
  ]);
  if (fromMaxProperties != null) {
    setValueByPath(toObject, ["maxProperties"], fromMaxProperties);
  }
  const fromMaximum = getValueByPath(fromObject, ["maximum"]);
  if (fromMaximum != null) {
    setValueByPath(toObject, ["maximum"], fromMaximum);
  }
  const fromMinItems = getValueByPath(fromObject, ["minItems"]);
  if (fromMinItems != null) {
    setValueByPath(toObject, ["minItems"], fromMinItems);
  }
  const fromMinLength = getValueByPath(fromObject, ["minLength"]);
  if (fromMinLength != null) {
    setValueByPath(toObject, ["minLength"], fromMinLength);
  }
  const fromMinProperties = getValueByPath(fromObject, [
    "minProperties"
  ]);
  if (fromMinProperties != null) {
    setValueByPath(toObject, ["minProperties"], fromMinProperties);
  }
  const fromMinimum = getValueByPath(fromObject, ["minimum"]);
  if (fromMinimum != null) {
    setValueByPath(toObject, ["minimum"], fromMinimum);
  }
  const fromNullable = getValueByPath(fromObject, ["nullable"]);
  if (fromNullable != null) {
    setValueByPath(toObject, ["nullable"], fromNullable);
  }
  const fromPattern = getValueByPath(fromObject, ["pattern"]);
  if (fromPattern != null) {
    setValueByPath(toObject, ["pattern"], fromPattern);
  }
  const fromProperties = getValueByPath(fromObject, ["properties"]);
  if (fromProperties != null) {
    setValueByPath(toObject, ["properties"], fromProperties);
  }
  const fromPropertyOrdering = getValueByPath(fromObject, [
    "propertyOrdering"
  ]);
  if (fromPropertyOrdering != null) {
    setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering);
  }
  const fromRequired = getValueByPath(fromObject, ["required"]);
  if (fromRequired != null) {
    setValueByPath(toObject, ["required"], fromRequired);
  }
  const fromTitle = getValueByPath(fromObject, ["title"]);
  if (fromTitle != null) {
    setValueByPath(toObject, ["title"], fromTitle);
  }
  const fromType = getValueByPath(fromObject, ["type"]);
  if (fromType != null) {
    setValueByPath(toObject, ["type"], fromType);
  }
  return toObject;
}
function modelSelectionConfigToVertex(fromObject) {
  const toObject = {};
  const fromFeatureSelectionPreference = getValueByPath(fromObject, [
    "featureSelectionPreference"
  ]);
  if (fromFeatureSelectionPreference != null) {
    setValueByPath(toObject, ["featureSelectionPreference"], fromFeatureSelectionPreference);
  }
  return toObject;
}
function safetySettingToVertex(fromObject) {
  const toObject = {};
  const fromMethod = getValueByPath(fromObject, ["method"]);
  if (fromMethod != null) {
    setValueByPath(toObject, ["method"], fromMethod);
  }
  const fromCategory = getValueByPath(fromObject, ["category"]);
  if (fromCategory != null) {
    setValueByPath(toObject, ["category"], fromCategory);
  }
  const fromThreshold = getValueByPath(fromObject, ["threshold"]);
  if (fromThreshold != null) {
    setValueByPath(toObject, ["threshold"], fromThreshold);
  }
  return toObject;
}
function functionDeclarationToVertex(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["behavior"]) !== void 0) {
    throw new Error("behavior parameter is not supported in Vertex AI.");
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  return toObject;
}
function intervalToVertex(fromObject) {
  const toObject = {};
  const fromStartTime = getValueByPath(fromObject, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  return toObject;
}
function googleSearchToVertex(fromObject) {
  const toObject = {};
  const fromTimeRangeFilter = getValueByPath(fromObject, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], intervalToVertex(fromTimeRangeFilter));
  }
  const fromExcludeDomains = getValueByPath(fromObject, [
    "excludeDomains"
  ]);
  if (fromExcludeDomains != null) {
    setValueByPath(toObject, ["excludeDomains"], fromExcludeDomains);
  }
  return toObject;
}
function dynamicRetrievalConfigToVertex(fromObject) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromDynamicThreshold = getValueByPath(fromObject, [
    "dynamicThreshold"
  ]);
  if (fromDynamicThreshold != null) {
    setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold);
  }
  return toObject;
}
function googleSearchRetrievalToVertex(fromObject) {
  const toObject = {};
  const fromDynamicRetrievalConfig = getValueByPath(fromObject, [
    "dynamicRetrievalConfig"
  ]);
  if (fromDynamicRetrievalConfig != null) {
    setValueByPath(toObject, ["dynamicRetrievalConfig"], dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig));
  }
  return toObject;
}
function enterpriseWebSearchToVertex(fromObject) {
  const toObject = {};
  const fromExcludeDomains = getValueByPath(fromObject, [
    "excludeDomains"
  ]);
  if (fromExcludeDomains != null) {
    setValueByPath(toObject, ["excludeDomains"], fromExcludeDomains);
  }
  return toObject;
}
function apiKeyConfigToVertex(fromObject) {
  const toObject = {};
  const fromApiKeyString = getValueByPath(fromObject, ["apiKeyString"]);
  if (fromApiKeyString != null) {
    setValueByPath(toObject, ["apiKeyString"], fromApiKeyString);
  }
  return toObject;
}
function authConfigToVertex(fromObject) {
  const toObject = {};
  const fromApiKeyConfig = getValueByPath(fromObject, ["apiKeyConfig"]);
  if (fromApiKeyConfig != null) {
    setValueByPath(toObject, ["apiKeyConfig"], apiKeyConfigToVertex(fromApiKeyConfig));
  }
  const fromAuthType = getValueByPath(fromObject, ["authType"]);
  if (fromAuthType != null) {
    setValueByPath(toObject, ["authType"], fromAuthType);
  }
  const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [
    "googleServiceAccountConfig"
  ]);
  if (fromGoogleServiceAccountConfig != null) {
    setValueByPath(toObject, ["googleServiceAccountConfig"], fromGoogleServiceAccountConfig);
  }
  const fromHttpBasicAuthConfig = getValueByPath(fromObject, [
    "httpBasicAuthConfig"
  ]);
  if (fromHttpBasicAuthConfig != null) {
    setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig);
  }
  const fromOauthConfig = getValueByPath(fromObject, ["oauthConfig"]);
  if (fromOauthConfig != null) {
    setValueByPath(toObject, ["oauthConfig"], fromOauthConfig);
  }
  const fromOidcConfig = getValueByPath(fromObject, ["oidcConfig"]);
  if (fromOidcConfig != null) {
    setValueByPath(toObject, ["oidcConfig"], fromOidcConfig);
  }
  return toObject;
}
function googleMapsToVertex(fromObject) {
  const toObject = {};
  const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]);
  if (fromAuthConfig != null) {
    setValueByPath(toObject, ["authConfig"], authConfigToVertex(fromAuthConfig));
  }
  return toObject;
}
function urlContextToVertex() {
  const toObject = {};
  return toObject;
}
function toolComputerUseToVertex(fromObject) {
  const toObject = {};
  const fromEnvironment = getValueByPath(fromObject, ["environment"]);
  if (fromEnvironment != null) {
    setValueByPath(toObject, ["environment"], fromEnvironment);
  }
  return toObject;
}
function toolToVertex(fromObject) {
  const toObject = {};
  const fromFunctionDeclarations = getValueByPath(fromObject, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToVertex(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  const fromRetrieval = getValueByPath(fromObject, ["retrieval"]);
  if (fromRetrieval != null) {
    setValueByPath(toObject, ["retrieval"], fromRetrieval);
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToVertex(fromGoogleSearch));
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], googleSearchRetrievalToVertex(fromGoogleSearchRetrieval));
  }
  const fromEnterpriseWebSearch = getValueByPath(fromObject, [
    "enterpriseWebSearch"
  ]);
  if (fromEnterpriseWebSearch != null) {
    setValueByPath(toObject, ["enterpriseWebSearch"], enterpriseWebSearchToVertex(fromEnterpriseWebSearch));
  }
  const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], googleMapsToVertex(fromGoogleMaps));
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], urlContextToVertex());
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], toolComputerUseToVertex(fromComputerUse));
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  return toObject;
}
function functionCallingConfigToVertex(fromObject) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromAllowedFunctionNames = getValueByPath(fromObject, [
    "allowedFunctionNames"
  ]);
  if (fromAllowedFunctionNames != null) {
    setValueByPath(toObject, ["allowedFunctionNames"], fromAllowedFunctionNames);
  }
  return toObject;
}
function latLngToVertex(fromObject) {
  const toObject = {};
  const fromLatitude = getValueByPath(fromObject, ["latitude"]);
  if (fromLatitude != null) {
    setValueByPath(toObject, ["latitude"], fromLatitude);
  }
  const fromLongitude = getValueByPath(fromObject, ["longitude"]);
  if (fromLongitude != null) {
    setValueByPath(toObject, ["longitude"], fromLongitude);
  }
  return toObject;
}
function retrievalConfigToVertex(fromObject) {
  const toObject = {};
  const fromLatLng = getValueByPath(fromObject, ["latLng"]);
  if (fromLatLng != null) {
    setValueByPath(toObject, ["latLng"], latLngToVertex(fromLatLng));
  }
  const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function toolConfigToVertex(fromObject) {
  const toObject = {};
  const fromFunctionCallingConfig = getValueByPath(fromObject, [
    "functionCallingConfig"
  ]);
  if (fromFunctionCallingConfig != null) {
    setValueByPath(toObject, ["functionCallingConfig"], functionCallingConfigToVertex(fromFunctionCallingConfig));
  }
  const fromRetrievalConfig = getValueByPath(fromObject, [
    "retrievalConfig"
  ]);
  if (fromRetrievalConfig != null) {
    setValueByPath(toObject, ["retrievalConfig"], retrievalConfigToVertex(fromRetrievalConfig));
  }
  return toObject;
}
function prebuiltVoiceConfigToVertex(fromObject) {
  const toObject = {};
  const fromVoiceName = getValueByPath(fromObject, ["voiceName"]);
  if (fromVoiceName != null) {
    setValueByPath(toObject, ["voiceName"], fromVoiceName);
  }
  return toObject;
}
function voiceConfigToVertex(fromObject) {
  const toObject = {};
  const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [
    "prebuiltVoiceConfig"
  ]);
  if (fromPrebuiltVoiceConfig != null) {
    setValueByPath(toObject, ["prebuiltVoiceConfig"], prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig));
  }
  return toObject;
}
function speechConfigToVertex(fromObject) {
  const toObject = {};
  const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToVertex(fromVoiceConfig));
  }
  if (getValueByPath(fromObject, ["multiSpeakerVoiceConfig"]) !== void 0) {
    throw new Error("multiSpeakerVoiceConfig parameter is not supported in Vertex AI.");
  }
  const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function thinkingConfigToVertex(fromObject) {
  const toObject = {};
  const fromIncludeThoughts = getValueByPath(fromObject, [
    "includeThoughts"
  ]);
  if (fromIncludeThoughts != null) {
    setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts);
  }
  const fromThinkingBudget = getValueByPath(fromObject, [
    "thinkingBudget"
  ]);
  if (fromThinkingBudget != null) {
    setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget);
  }
  return toObject;
}
function generateContentConfigToVertex(apiClient, fromObject, parentObject) {
  const toObject = {};
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], contentToVertex(tContent(fromSystemInstruction)));
  }
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromTopP = getValueByPath(fromObject, ["topP"]);
  if (fromTopP != null) {
    setValueByPath(toObject, ["topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (fromTopK != null) {
    setValueByPath(toObject, ["topK"], fromTopK);
  }
  const fromCandidateCount = getValueByPath(fromObject, [
    "candidateCount"
  ]);
  if (fromCandidateCount != null) {
    setValueByPath(toObject, ["candidateCount"], fromCandidateCount);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject, [
    "maxOutputTokens"
  ]);
  if (fromMaxOutputTokens != null) {
    setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromStopSequences = getValueByPath(fromObject, [
    "stopSequences"
  ]);
  if (fromStopSequences != null) {
    setValueByPath(toObject, ["stopSequences"], fromStopSequences);
  }
  const fromResponseLogprobs = getValueByPath(fromObject, [
    "responseLogprobs"
  ]);
  if (fromResponseLogprobs != null) {
    setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs);
  }
  const fromLogprobs = getValueByPath(fromObject, ["logprobs"]);
  if (fromLogprobs != null) {
    setValueByPath(toObject, ["logprobs"], fromLogprobs);
  }
  const fromPresencePenalty = getValueByPath(fromObject, [
    "presencePenalty"
  ]);
  if (fromPresencePenalty != null) {
    setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty);
  }
  const fromFrequencyPenalty = getValueByPath(fromObject, [
    "frequencyPenalty"
  ]);
  if (fromFrequencyPenalty != null) {
    setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (fromSeed != null) {
    setValueByPath(toObject, ["seed"], fromSeed);
  }
  const fromResponseMimeType = getValueByPath(fromObject, [
    "responseMimeType"
  ]);
  if (fromResponseMimeType != null) {
    setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType);
  }
  const fromResponseSchema = getValueByPath(fromObject, [
    "responseSchema"
  ]);
  if (fromResponseSchema != null) {
    setValueByPath(toObject, ["responseSchema"], schemaToVertex(tSchema(fromResponseSchema)));
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  const fromRoutingConfig = getValueByPath(fromObject, [
    "routingConfig"
  ]);
  if (fromRoutingConfig != null) {
    setValueByPath(toObject, ["routingConfig"], fromRoutingConfig);
  }
  const fromModelSelectionConfig = getValueByPath(fromObject, [
    "modelSelectionConfig"
  ]);
  if (fromModelSelectionConfig != null) {
    setValueByPath(toObject, ["modelConfig"], modelSelectionConfigToVertex(fromModelSelectionConfig));
  }
  const fromSafetySettings = getValueByPath(fromObject, [
    "safetySettings"
  ]);
  if (parentObject !== void 0 && fromSafetySettings != null) {
    let transformedList = fromSafetySettings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return safetySettingToVertex(item);
      });
    }
    setValueByPath(parentObject, ["safetySettings"], transformedList);
  }
  const fromTools = getValueByPath(fromObject, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = tTools(fromTools);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToVertex(tTool(item));
      });
    }
    setValueByPath(parentObject, ["tools"], transformedList);
  }
  const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]);
  if (parentObject !== void 0 && fromToolConfig != null) {
    setValueByPath(parentObject, ["toolConfig"], toolConfigToVertex(fromToolConfig));
  }
  const fromLabels = getValueByPath(fromObject, ["labels"]);
  if (parentObject !== void 0 && fromLabels != null) {
    setValueByPath(parentObject, ["labels"], fromLabels);
  }
  const fromCachedContent = getValueByPath(fromObject, [
    "cachedContent"
  ]);
  if (parentObject !== void 0 && fromCachedContent != null) {
    setValueByPath(parentObject, ["cachedContent"], tCachedContentName(apiClient, fromCachedContent));
  }
  const fromResponseModalities = getValueByPath(fromObject, [
    "responseModalities"
  ]);
  if (fromResponseModalities != null) {
    setValueByPath(toObject, ["responseModalities"], fromResponseModalities);
  }
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]);
  if (fromSpeechConfig != null) {
    setValueByPath(toObject, ["speechConfig"], speechConfigToVertex(tSpeechConfig(fromSpeechConfig)));
  }
  const fromAudioTimestamp = getValueByPath(fromObject, [
    "audioTimestamp"
  ]);
  if (fromAudioTimestamp != null) {
    setValueByPath(toObject, ["audioTimestamp"], fromAudioTimestamp);
  }
  const fromThinkingConfig = getValueByPath(fromObject, [
    "thinkingConfig"
  ]);
  if (fromThinkingConfig != null) {
    setValueByPath(toObject, ["thinkingConfig"], thinkingConfigToVertex(fromThinkingConfig));
  }
  return toObject;
}
function generateContentParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToVertex(item);
      });
    }
    setValueByPath(toObject, ["contents"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["generationConfig"], generateContentConfigToVertex(apiClient, fromConfig, toObject));
  }
  return toObject;
}
function embedContentConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromTaskType = getValueByPath(fromObject, ["taskType"]);
  if (parentObject !== void 0 && fromTaskType != null) {
    setValueByPath(parentObject, ["instances[]", "task_type"], fromTaskType);
  }
  const fromTitle = getValueByPath(fromObject, ["title"]);
  if (parentObject !== void 0 && fromTitle != null) {
    setValueByPath(parentObject, ["instances[]", "title"], fromTitle);
  }
  const fromOutputDimensionality = getValueByPath(fromObject, [
    "outputDimensionality"
  ]);
  if (parentObject !== void 0 && fromOutputDimensionality != null) {
    setValueByPath(parentObject, ["parameters", "outputDimensionality"], fromOutputDimensionality);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (parentObject !== void 0 && fromMimeType != null) {
    setValueByPath(parentObject, ["instances[]", "mimeType"], fromMimeType);
  }
  const fromAutoTruncate = getValueByPath(fromObject, ["autoTruncate"]);
  if (parentObject !== void 0 && fromAutoTruncate != null) {
    setValueByPath(parentObject, ["parameters", "autoTruncate"], fromAutoTruncate);
  }
  return toObject;
}
function embedContentParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (fromContents != null) {
    setValueByPath(toObject, ["instances[]", "content"], tContentsForEmbed(apiClient, fromContents));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], embedContentConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function generateImagesConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]);
  if (parentObject !== void 0 && fromOutputGcsUri != null) {
    setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri);
  }
  const fromNegativePrompt = getValueByPath(fromObject, [
    "negativePrompt"
  ]);
  if (parentObject !== void 0 && fromNegativePrompt != null) {
    setValueByPath(parentObject, ["parameters", "negativePrompt"], fromNegativePrompt);
  }
  const fromNumberOfImages = getValueByPath(fromObject, [
    "numberOfImages"
  ]);
  if (parentObject !== void 0 && fromNumberOfImages != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages);
  }
  const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]);
  if (parentObject !== void 0 && fromAspectRatio != null) {
    setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio);
  }
  const fromGuidanceScale = getValueByPath(fromObject, [
    "guidanceScale"
  ]);
  if (parentObject !== void 0 && fromGuidanceScale != null) {
    setValueByPath(parentObject, ["parameters", "guidanceScale"], fromGuidanceScale);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["parameters", "seed"], fromSeed);
  }
  const fromSafetyFilterLevel = getValueByPath(fromObject, [
    "safetyFilterLevel"
  ]);
  if (parentObject !== void 0 && fromSafetyFilterLevel != null) {
    setValueByPath(parentObject, ["parameters", "safetySetting"], fromSafetyFilterLevel);
  }
  const fromPersonGeneration = getValueByPath(fromObject, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  const fromIncludeSafetyAttributes = getValueByPath(fromObject, [
    "includeSafetyAttributes"
  ]);
  if (parentObject !== void 0 && fromIncludeSafetyAttributes != null) {
    setValueByPath(parentObject, ["parameters", "includeSafetyAttributes"], fromIncludeSafetyAttributes);
  }
  const fromIncludeRaiReason = getValueByPath(fromObject, [
    "includeRaiReason"
  ]);
  if (parentObject !== void 0 && fromIncludeRaiReason != null) {
    setValueByPath(parentObject, ["parameters", "includeRaiReason"], fromIncludeRaiReason);
  }
  const fromLanguage = getValueByPath(fromObject, ["language"]);
  if (parentObject !== void 0 && fromLanguage != null) {
    setValueByPath(parentObject, ["parameters", "language"], fromLanguage);
  }
  const fromOutputMimeType = getValueByPath(fromObject, [
    "outputMimeType"
  ]);
  if (parentObject !== void 0 && fromOutputMimeType != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType);
  }
  const fromOutputCompressionQuality = getValueByPath(fromObject, [
    "outputCompressionQuality"
  ]);
  if (parentObject !== void 0 && fromOutputCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality);
  }
  const fromAddWatermark = getValueByPath(fromObject, ["addWatermark"]);
  if (parentObject !== void 0 && fromAddWatermark != null) {
    setValueByPath(parentObject, ["parameters", "addWatermark"], fromAddWatermark);
  }
  const fromImageSize = getValueByPath(fromObject, ["imageSize"]);
  if (parentObject !== void 0 && fromImageSize != null) {
    setValueByPath(parentObject, ["parameters", "sampleImageSize"], fromImageSize);
  }
  const fromEnhancePrompt = getValueByPath(fromObject, [
    "enhancePrompt"
  ]);
  if (parentObject !== void 0 && fromEnhancePrompt != null) {
    setValueByPath(parentObject, ["parameters", "enhancePrompt"], fromEnhancePrompt);
  }
  return toObject;
}
function generateImagesParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromPrompt = getValueByPath(fromObject, ["prompt"]);
  if (fromPrompt != null) {
    setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], generateImagesConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function imageToVertex(fromObject) {
  const toObject = {};
  const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["gcsUri"], fromGcsUri);
  }
  const fromImageBytes = getValueByPath(fromObject, ["imageBytes"]);
  if (fromImageBytes != null) {
    setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromImageBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function maskReferenceConfigToVertex(fromObject) {
  const toObject = {};
  const fromMaskMode = getValueByPath(fromObject, ["maskMode"]);
  if (fromMaskMode != null) {
    setValueByPath(toObject, ["maskMode"], fromMaskMode);
  }
  const fromSegmentationClasses = getValueByPath(fromObject, [
    "segmentationClasses"
  ]);
  if (fromSegmentationClasses != null) {
    setValueByPath(toObject, ["maskClasses"], fromSegmentationClasses);
  }
  const fromMaskDilation = getValueByPath(fromObject, ["maskDilation"]);
  if (fromMaskDilation != null) {
    setValueByPath(toObject, ["dilation"], fromMaskDilation);
  }
  return toObject;
}
function controlReferenceConfigToVertex(fromObject) {
  const toObject = {};
  const fromControlType = getValueByPath(fromObject, ["controlType"]);
  if (fromControlType != null) {
    setValueByPath(toObject, ["controlType"], fromControlType);
  }
  const fromEnableControlImageComputation = getValueByPath(fromObject, [
    "enableControlImageComputation"
  ]);
  if (fromEnableControlImageComputation != null) {
    setValueByPath(toObject, ["computeControl"], fromEnableControlImageComputation);
  }
  return toObject;
}
function styleReferenceConfigToVertex(fromObject) {
  const toObject = {};
  const fromStyleDescription = getValueByPath(fromObject, [
    "styleDescription"
  ]);
  if (fromStyleDescription != null) {
    setValueByPath(toObject, ["styleDescription"], fromStyleDescription);
  }
  return toObject;
}
function subjectReferenceConfigToVertex(fromObject) {
  const toObject = {};
  const fromSubjectType = getValueByPath(fromObject, ["subjectType"]);
  if (fromSubjectType != null) {
    setValueByPath(toObject, ["subjectType"], fromSubjectType);
  }
  const fromSubjectDescription = getValueByPath(fromObject, [
    "subjectDescription"
  ]);
  if (fromSubjectDescription != null) {
    setValueByPath(toObject, ["subjectDescription"], fromSubjectDescription);
  }
  return toObject;
}
function referenceImageAPIInternalToVertex(fromObject) {
  const toObject = {};
  const fromReferenceImage = getValueByPath(fromObject, [
    "referenceImage"
  ]);
  if (fromReferenceImage != null) {
    setValueByPath(toObject, ["referenceImage"], imageToVertex(fromReferenceImage));
  }
  const fromReferenceId = getValueByPath(fromObject, ["referenceId"]);
  if (fromReferenceId != null) {
    setValueByPath(toObject, ["referenceId"], fromReferenceId);
  }
  const fromReferenceType = getValueByPath(fromObject, [
    "referenceType"
  ]);
  if (fromReferenceType != null) {
    setValueByPath(toObject, ["referenceType"], fromReferenceType);
  }
  const fromMaskImageConfig = getValueByPath(fromObject, [
    "maskImageConfig"
  ]);
  if (fromMaskImageConfig != null) {
    setValueByPath(toObject, ["maskImageConfig"], maskReferenceConfigToVertex(fromMaskImageConfig));
  }
  const fromControlImageConfig = getValueByPath(fromObject, [
    "controlImageConfig"
  ]);
  if (fromControlImageConfig != null) {
    setValueByPath(toObject, ["controlImageConfig"], controlReferenceConfigToVertex(fromControlImageConfig));
  }
  const fromStyleImageConfig = getValueByPath(fromObject, [
    "styleImageConfig"
  ]);
  if (fromStyleImageConfig != null) {
    setValueByPath(toObject, ["styleImageConfig"], styleReferenceConfigToVertex(fromStyleImageConfig));
  }
  const fromSubjectImageConfig = getValueByPath(fromObject, [
    "subjectImageConfig"
  ]);
  if (fromSubjectImageConfig != null) {
    setValueByPath(toObject, ["subjectImageConfig"], subjectReferenceConfigToVertex(fromSubjectImageConfig));
  }
  return toObject;
}
function editImageConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]);
  if (parentObject !== void 0 && fromOutputGcsUri != null) {
    setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri);
  }
  const fromNegativePrompt = getValueByPath(fromObject, [
    "negativePrompt"
  ]);
  if (parentObject !== void 0 && fromNegativePrompt != null) {
    setValueByPath(parentObject, ["parameters", "negativePrompt"], fromNegativePrompt);
  }
  const fromNumberOfImages = getValueByPath(fromObject, [
    "numberOfImages"
  ]);
  if (parentObject !== void 0 && fromNumberOfImages != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages);
  }
  const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]);
  if (parentObject !== void 0 && fromAspectRatio != null) {
    setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio);
  }
  const fromGuidanceScale = getValueByPath(fromObject, [
    "guidanceScale"
  ]);
  if (parentObject !== void 0 && fromGuidanceScale != null) {
    setValueByPath(parentObject, ["parameters", "guidanceScale"], fromGuidanceScale);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["parameters", "seed"], fromSeed);
  }
  const fromSafetyFilterLevel = getValueByPath(fromObject, [
    "safetyFilterLevel"
  ]);
  if (parentObject !== void 0 && fromSafetyFilterLevel != null) {
    setValueByPath(parentObject, ["parameters", "safetySetting"], fromSafetyFilterLevel);
  }
  const fromPersonGeneration = getValueByPath(fromObject, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  const fromIncludeSafetyAttributes = getValueByPath(fromObject, [
    "includeSafetyAttributes"
  ]);
  if (parentObject !== void 0 && fromIncludeSafetyAttributes != null) {
    setValueByPath(parentObject, ["parameters", "includeSafetyAttributes"], fromIncludeSafetyAttributes);
  }
  const fromIncludeRaiReason = getValueByPath(fromObject, [
    "includeRaiReason"
  ]);
  if (parentObject !== void 0 && fromIncludeRaiReason != null) {
    setValueByPath(parentObject, ["parameters", "includeRaiReason"], fromIncludeRaiReason);
  }
  const fromLanguage = getValueByPath(fromObject, ["language"]);
  if (parentObject !== void 0 && fromLanguage != null) {
    setValueByPath(parentObject, ["parameters", "language"], fromLanguage);
  }
  const fromOutputMimeType = getValueByPath(fromObject, [
    "outputMimeType"
  ]);
  if (parentObject !== void 0 && fromOutputMimeType != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType);
  }
  const fromOutputCompressionQuality = getValueByPath(fromObject, [
    "outputCompressionQuality"
  ]);
  if (parentObject !== void 0 && fromOutputCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality);
  }
  const fromAddWatermark = getValueByPath(fromObject, ["addWatermark"]);
  if (parentObject !== void 0 && fromAddWatermark != null) {
    setValueByPath(parentObject, ["parameters", "addWatermark"], fromAddWatermark);
  }
  const fromEditMode = getValueByPath(fromObject, ["editMode"]);
  if (parentObject !== void 0 && fromEditMode != null) {
    setValueByPath(parentObject, ["parameters", "editMode"], fromEditMode);
  }
  const fromBaseSteps = getValueByPath(fromObject, ["baseSteps"]);
  if (parentObject !== void 0 && fromBaseSteps != null) {
    setValueByPath(parentObject, ["parameters", "editConfig", "baseSteps"], fromBaseSteps);
  }
  return toObject;
}
function editImageParametersInternalToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromPrompt = getValueByPath(fromObject, ["prompt"]);
  if (fromPrompt != null) {
    setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromReferenceImages = getValueByPath(fromObject, [
    "referenceImages"
  ]);
  if (fromReferenceImages != null) {
    let transformedList = fromReferenceImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return referenceImageAPIInternalToVertex(item);
      });
    }
    setValueByPath(toObject, ["instances[0]", "referenceImages"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], editImageConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function upscaleImageAPIConfigInternalToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]);
  if (parentObject !== void 0 && fromOutputGcsUri != null) {
    setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri);
  }
  const fromIncludeRaiReason = getValueByPath(fromObject, [
    "includeRaiReason"
  ]);
  if (parentObject !== void 0 && fromIncludeRaiReason != null) {
    setValueByPath(parentObject, ["parameters", "includeRaiReason"], fromIncludeRaiReason);
  }
  const fromOutputMimeType = getValueByPath(fromObject, [
    "outputMimeType"
  ]);
  if (parentObject !== void 0 && fromOutputMimeType != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType);
  }
  const fromOutputCompressionQuality = getValueByPath(fromObject, [
    "outputCompressionQuality"
  ]);
  if (parentObject !== void 0 && fromOutputCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality);
  }
  const fromEnhanceInputImage = getValueByPath(fromObject, [
    "enhanceInputImage"
  ]);
  if (parentObject !== void 0 && fromEnhanceInputImage != null) {
    setValueByPath(parentObject, ["parameters", "upscaleConfig", "enhanceInputImage"], fromEnhanceInputImage);
  }
  const fromImagePreservationFactor = getValueByPath(fromObject, [
    "imagePreservationFactor"
  ]);
  if (parentObject !== void 0 && fromImagePreservationFactor != null) {
    setValueByPath(parentObject, ["parameters", "upscaleConfig", "imagePreservationFactor"], fromImagePreservationFactor);
  }
  const fromNumberOfImages = getValueByPath(fromObject, [
    "numberOfImages"
  ]);
  if (parentObject !== void 0 && fromNumberOfImages != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages);
  }
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (parentObject !== void 0 && fromMode != null) {
    setValueByPath(parentObject, ["parameters", "mode"], fromMode);
  }
  return toObject;
}
function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["instances[0]", "image"], imageToVertex(fromImage));
  }
  const fromUpscaleFactor = getValueByPath(fromObject, [
    "upscaleFactor"
  ]);
  if (fromUpscaleFactor != null) {
    setValueByPath(toObject, ["parameters", "upscaleConfig", "upscaleFactor"], fromUpscaleFactor);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], upscaleImageAPIConfigInternalToVertex(fromConfig, toObject));
  }
  return toObject;
}
function productImageToVertex(fromObject) {
  const toObject = {};
  const fromProductImage = getValueByPath(fromObject, ["productImage"]);
  if (fromProductImage != null) {
    setValueByPath(toObject, ["image"], imageToVertex(fromProductImage));
  }
  return toObject;
}
function recontextImageSourceToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromPrompt = getValueByPath(fromObject, ["prompt"]);
  if (parentObject !== void 0 && fromPrompt != null) {
    setValueByPath(parentObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromPersonImage = getValueByPath(fromObject, ["personImage"]);
  if (parentObject !== void 0 && fromPersonImage != null) {
    setValueByPath(parentObject, ["instances[0]", "personImage", "image"], imageToVertex(fromPersonImage));
  }
  const fromProductImages = getValueByPath(fromObject, [
    "productImages"
  ]);
  if (parentObject !== void 0 && fromProductImages != null) {
    let transformedList = fromProductImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return productImageToVertex(item);
      });
    }
    setValueByPath(parentObject, ["instances[0]", "productImages"], transformedList);
  }
  return toObject;
}
function recontextImageConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromNumberOfImages = getValueByPath(fromObject, [
    "numberOfImages"
  ]);
  if (parentObject !== void 0 && fromNumberOfImages != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages);
  }
  const fromBaseSteps = getValueByPath(fromObject, ["baseSteps"]);
  if (parentObject !== void 0 && fromBaseSteps != null) {
    setValueByPath(parentObject, ["parameters", "editConfig", "baseSteps"], fromBaseSteps);
  }
  const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]);
  if (parentObject !== void 0 && fromOutputGcsUri != null) {
    setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["parameters", "seed"], fromSeed);
  }
  const fromSafetyFilterLevel = getValueByPath(fromObject, [
    "safetyFilterLevel"
  ]);
  if (parentObject !== void 0 && fromSafetyFilterLevel != null) {
    setValueByPath(parentObject, ["parameters", "safetySetting"], fromSafetyFilterLevel);
  }
  const fromPersonGeneration = getValueByPath(fromObject, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  const fromAddWatermark = getValueByPath(fromObject, ["addWatermark"]);
  if (parentObject !== void 0 && fromAddWatermark != null) {
    setValueByPath(parentObject, ["parameters", "addWatermark"], fromAddWatermark);
  }
  const fromOutputMimeType = getValueByPath(fromObject, [
    "outputMimeType"
  ]);
  if (parentObject !== void 0 && fromOutputMimeType != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType);
  }
  const fromOutputCompressionQuality = getValueByPath(fromObject, [
    "outputCompressionQuality"
  ]);
  if (parentObject !== void 0 && fromOutputCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality);
  }
  const fromEnhancePrompt = getValueByPath(fromObject, [
    "enhancePrompt"
  ]);
  if (parentObject !== void 0 && fromEnhancePrompt != null) {
    setValueByPath(parentObject, ["parameters", "enhancePrompt"], fromEnhancePrompt);
  }
  return toObject;
}
function recontextImageParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromSource = getValueByPath(fromObject, ["source"]);
  if (fromSource != null) {
    setValueByPath(toObject, ["config"], recontextImageSourceToVertex(fromSource, toObject));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], recontextImageConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function scribbleImageToVertex(fromObject) {
  const toObject = {};
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["image"], imageToVertex(fromImage));
  }
  return toObject;
}
function segmentImageSourceToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromPrompt = getValueByPath(fromObject, ["prompt"]);
  if (parentObject !== void 0 && fromPrompt != null) {
    setValueByPath(parentObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (parentObject !== void 0 && fromImage != null) {
    setValueByPath(parentObject, ["instances[0]", "image"], imageToVertex(fromImage));
  }
  const fromScribbleImage = getValueByPath(fromObject, [
    "scribbleImage"
  ]);
  if (parentObject !== void 0 && fromScribbleImage != null) {
    setValueByPath(parentObject, ["instances[0]", "scribble"], scribbleImageToVertex(fromScribbleImage));
  }
  return toObject;
}
function segmentImageConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (parentObject !== void 0 && fromMode != null) {
    setValueByPath(parentObject, ["parameters", "mode"], fromMode);
  }
  const fromMaxPredictions = getValueByPath(fromObject, [
    "maxPredictions"
  ]);
  if (parentObject !== void 0 && fromMaxPredictions != null) {
    setValueByPath(parentObject, ["parameters", "maxPredictions"], fromMaxPredictions);
  }
  const fromConfidenceThreshold = getValueByPath(fromObject, [
    "confidenceThreshold"
  ]);
  if (parentObject !== void 0 && fromConfidenceThreshold != null) {
    setValueByPath(parentObject, ["parameters", "confidenceThreshold"], fromConfidenceThreshold);
  }
  const fromMaskDilation = getValueByPath(fromObject, ["maskDilation"]);
  if (parentObject !== void 0 && fromMaskDilation != null) {
    setValueByPath(parentObject, ["parameters", "maskDilation"], fromMaskDilation);
  }
  const fromBinaryColorThreshold = getValueByPath(fromObject, [
    "binaryColorThreshold"
  ]);
  if (parentObject !== void 0 && fromBinaryColorThreshold != null) {
    setValueByPath(parentObject, ["parameters", "binaryColorThreshold"], fromBinaryColorThreshold);
  }
  return toObject;
}
function segmentImageParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromSource = getValueByPath(fromObject, ["source"]);
  if (fromSource != null) {
    setValueByPath(toObject, ["config"], segmentImageSourceToVertex(fromSource, toObject));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], segmentImageConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function getModelParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function listModelsConfigToVertex(apiClient, fromObject, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  const fromFilter = getValueByPath(fromObject, ["filter"]);
  if (parentObject !== void 0 && fromFilter != null) {
    setValueByPath(parentObject, ["_query", "filter"], fromFilter);
  }
  const fromQueryBase = getValueByPath(fromObject, ["queryBase"]);
  if (parentObject !== void 0 && fromQueryBase != null) {
    setValueByPath(parentObject, ["_url", "models_url"], tModelsUrl(apiClient, fromQueryBase));
  }
  return toObject;
}
function listModelsParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], listModelsConfigToVertex(apiClient, fromConfig, toObject));
  }
  return toObject;
}
function updateModelConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (parentObject !== void 0 && fromDescription != null) {
    setValueByPath(parentObject, ["description"], fromDescription);
  }
  const fromDefaultCheckpointId = getValueByPath(fromObject, [
    "defaultCheckpointId"
  ]);
  if (parentObject !== void 0 && fromDefaultCheckpointId != null) {
    setValueByPath(parentObject, ["defaultCheckpointId"], fromDefaultCheckpointId);
  }
  return toObject;
}
function updateModelParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], updateModelConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function deleteModelParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function countTokensConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], contentToVertex(tContent(fromSystemInstruction)));
  }
  const fromTools = getValueByPath(fromObject, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = fromTools;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToVertex(item);
      });
    }
    setValueByPath(parentObject, ["tools"], transformedList);
  }
  const fromGenerationConfig = getValueByPath(fromObject, [
    "generationConfig"
  ]);
  if (parentObject !== void 0 && fromGenerationConfig != null) {
    setValueByPath(parentObject, ["generationConfig"], fromGenerationConfig);
  }
  return toObject;
}
function countTokensParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToVertex(item);
      });
    }
    setValueByPath(toObject, ["contents"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], countTokensConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function computeTokensParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToVertex(item);
      });
    }
    setValueByPath(toObject, ["contents"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function videoToVertex(fromObject) {
  const toObject = {};
  const fromUri = getValueByPath(fromObject, ["uri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["gcsUri"], fromUri);
  }
  const fromVideoBytes = getValueByPath(fromObject, ["videoBytes"]);
  if (fromVideoBytes != null) {
    setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromVideoBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function generateVideosSourceToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromPrompt = getValueByPath(fromObject, ["prompt"]);
  if (parentObject !== void 0 && fromPrompt != null) {
    setValueByPath(parentObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (parentObject !== void 0 && fromImage != null) {
    setValueByPath(parentObject, ["instances[0]", "image"], imageToVertex(fromImage));
  }
  const fromVideo = getValueByPath(fromObject, ["video"]);
  if (parentObject !== void 0 && fromVideo != null) {
    setValueByPath(parentObject, ["instances[0]", "video"], videoToVertex(fromVideo));
  }
  return toObject;
}
function videoGenerationReferenceImageToVertex(fromObject) {
  const toObject = {};
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["image"], imageToVertex(fromImage));
  }
  const fromReferenceType = getValueByPath(fromObject, [
    "referenceType"
  ]);
  if (fromReferenceType != null) {
    setValueByPath(toObject, ["referenceType"], fromReferenceType);
  }
  return toObject;
}
function generateVideosConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromNumberOfVideos = getValueByPath(fromObject, [
    "numberOfVideos"
  ]);
  if (parentObject !== void 0 && fromNumberOfVideos != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfVideos);
  }
  const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]);
  if (parentObject !== void 0 && fromOutputGcsUri != null) {
    setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri);
  }
  const fromFps = getValueByPath(fromObject, ["fps"]);
  if (parentObject !== void 0 && fromFps != null) {
    setValueByPath(parentObject, ["parameters", "fps"], fromFps);
  }
  const fromDurationSeconds = getValueByPath(fromObject, [
    "durationSeconds"
  ]);
  if (parentObject !== void 0 && fromDurationSeconds != null) {
    setValueByPath(parentObject, ["parameters", "durationSeconds"], fromDurationSeconds);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["parameters", "seed"], fromSeed);
  }
  const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]);
  if (parentObject !== void 0 && fromAspectRatio != null) {
    setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio);
  }
  const fromResolution = getValueByPath(fromObject, ["resolution"]);
  if (parentObject !== void 0 && fromResolution != null) {
    setValueByPath(parentObject, ["parameters", "resolution"], fromResolution);
  }
  const fromPersonGeneration = getValueByPath(fromObject, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  const fromPubsubTopic = getValueByPath(fromObject, ["pubsubTopic"]);
  if (parentObject !== void 0 && fromPubsubTopic != null) {
    setValueByPath(parentObject, ["parameters", "pubsubTopic"], fromPubsubTopic);
  }
  const fromNegativePrompt = getValueByPath(fromObject, [
    "negativePrompt"
  ]);
  if (parentObject !== void 0 && fromNegativePrompt != null) {
    setValueByPath(parentObject, ["parameters", "negativePrompt"], fromNegativePrompt);
  }
  const fromEnhancePrompt = getValueByPath(fromObject, [
    "enhancePrompt"
  ]);
  if (parentObject !== void 0 && fromEnhancePrompt != null) {
    setValueByPath(parentObject, ["parameters", "enhancePrompt"], fromEnhancePrompt);
  }
  const fromGenerateAudio = getValueByPath(fromObject, [
    "generateAudio"
  ]);
  if (parentObject !== void 0 && fromGenerateAudio != null) {
    setValueByPath(parentObject, ["parameters", "generateAudio"], fromGenerateAudio);
  }
  const fromLastFrame = getValueByPath(fromObject, ["lastFrame"]);
  if (parentObject !== void 0 && fromLastFrame != null) {
    setValueByPath(parentObject, ["instances[0]", "lastFrame"], imageToVertex(fromLastFrame));
  }
  const fromReferenceImages = getValueByPath(fromObject, [
    "referenceImages"
  ]);
  if (parentObject !== void 0 && fromReferenceImages != null) {
    let transformedList = fromReferenceImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return videoGenerationReferenceImageToVertex(item);
      });
    }
    setValueByPath(parentObject, ["instances[0]", "referenceImages"], transformedList);
  }
  const fromCompressionQuality = getValueByPath(fromObject, [
    "compressionQuality"
  ]);
  if (parentObject !== void 0 && fromCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "compressionQuality"], fromCompressionQuality);
  }
  return toObject;
}
function generateVideosParametersToVertex(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromPrompt = getValueByPath(fromObject, ["prompt"]);
  if (fromPrompt != null) {
    setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromImage = getValueByPath(fromObject, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["instances[0]", "image"], imageToVertex(fromImage));
  }
  const fromVideo = getValueByPath(fromObject, ["video"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["instances[0]", "video"], videoToVertex(fromVideo));
  }
  const fromSource = getValueByPath(fromObject, ["source"]);
  if (fromSource != null) {
    setValueByPath(toObject, ["config"], generateVideosSourceToVertex(fromSource, toObject));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], generateVideosConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function videoMetadataFromMldev(fromObject) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobFromMldev(fromObject) {
  const toObject = {};
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataFromMldev(fromObject) {
  const toObject = {};
  const fromFileUri = getValueByPath(fromObject, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function partFromMldev(fromObject) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataFromMldev(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobFromMldev(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataFromMldev(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromCodeExecutionResult = getValueByPath(fromObject, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], fromFunctionCall);
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentFromMldev(fromObject) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partFromMldev(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function citationMetadataFromMldev(fromObject) {
  const toObject = {};
  const fromCitations = getValueByPath(fromObject, ["citationSources"]);
  if (fromCitations != null) {
    setValueByPath(toObject, ["citations"], fromCitations);
  }
  return toObject;
}
function urlMetadataFromMldev(fromObject) {
  const toObject = {};
  const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]);
  if (fromRetrievedUrl != null) {
    setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl);
  }
  const fromUrlRetrievalStatus = getValueByPath(fromObject, [
    "urlRetrievalStatus"
  ]);
  if (fromUrlRetrievalStatus != null) {
    setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus);
  }
  return toObject;
}
function urlContextMetadataFromMldev(fromObject) {
  const toObject = {};
  const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]);
  if (fromUrlMetadata != null) {
    let transformedList = fromUrlMetadata;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return urlMetadataFromMldev(item);
      });
    }
    setValueByPath(toObject, ["urlMetadata"], transformedList);
  }
  return toObject;
}
function candidateFromMldev(fromObject) {
  const toObject = {};
  const fromContent = getValueByPath(fromObject, ["content"]);
  if (fromContent != null) {
    setValueByPath(toObject, ["content"], contentFromMldev(fromContent));
  }
  const fromCitationMetadata = getValueByPath(fromObject, [
    "citationMetadata"
  ]);
  if (fromCitationMetadata != null) {
    setValueByPath(toObject, ["citationMetadata"], citationMetadataFromMldev(fromCitationMetadata));
  }
  const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]);
  if (fromTokenCount != null) {
    setValueByPath(toObject, ["tokenCount"], fromTokenCount);
  }
  const fromFinishReason = getValueByPath(fromObject, ["finishReason"]);
  if (fromFinishReason != null) {
    setValueByPath(toObject, ["finishReason"], fromFinishReason);
  }
  const fromUrlContextMetadata = getValueByPath(fromObject, [
    "urlContextMetadata"
  ]);
  if (fromUrlContextMetadata != null) {
    setValueByPath(toObject, ["urlContextMetadata"], urlContextMetadataFromMldev(fromUrlContextMetadata));
  }
  const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]);
  if (fromAvgLogprobs != null) {
    setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs);
  }
  const fromGroundingMetadata = getValueByPath(fromObject, [
    "groundingMetadata"
  ]);
  if (fromGroundingMetadata != null) {
    setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata);
  }
  const fromIndex = getValueByPath(fromObject, ["index"]);
  if (fromIndex != null) {
    setValueByPath(toObject, ["index"], fromIndex);
  }
  const fromLogprobsResult = getValueByPath(fromObject, [
    "logprobsResult"
  ]);
  if (fromLogprobsResult != null) {
    setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult);
  }
  const fromSafetyRatings = getValueByPath(fromObject, [
    "safetyRatings"
  ]);
  if (fromSafetyRatings != null) {
    setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings);
  }
  return toObject;
}
function generateContentResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromCandidates = getValueByPath(fromObject, ["candidates"]);
  if (fromCandidates != null) {
    let transformedList = fromCandidates;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return candidateFromMldev(item);
      });
    }
    setValueByPath(toObject, ["candidates"], transformedList);
  }
  const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]);
  if (fromModelVersion != null) {
    setValueByPath(toObject, ["modelVersion"], fromModelVersion);
  }
  const fromPromptFeedback = getValueByPath(fromObject, [
    "promptFeedback"
  ]);
  if (fromPromptFeedback != null) {
    setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback);
  }
  const fromResponseId = getValueByPath(fromObject, ["responseId"]);
  if (fromResponseId != null) {
    setValueByPath(toObject, ["responseId"], fromResponseId);
  }
  const fromUsageMetadata = getValueByPath(fromObject, [
    "usageMetadata"
  ]);
  if (fromUsageMetadata != null) {
    setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata);
  }
  return toObject;
}
function contentEmbeddingFromMldev(fromObject) {
  const toObject = {};
  const fromValues = getValueByPath(fromObject, ["values"]);
  if (fromValues != null) {
    setValueByPath(toObject, ["values"], fromValues);
  }
  return toObject;
}
function embedContentMetadataFromMldev() {
  const toObject = {};
  return toObject;
}
function embedContentResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromEmbeddings = getValueByPath(fromObject, ["embeddings"]);
  if (fromEmbeddings != null) {
    let transformedList = fromEmbeddings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentEmbeddingFromMldev(item);
      });
    }
    setValueByPath(toObject, ["embeddings"], transformedList);
  }
  const fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], embedContentMetadataFromMldev());
  }
  return toObject;
}
function imageFromMldev(fromObject) {
  const toObject = {};
  const fromImageBytes = getValueByPath(fromObject, [
    "bytesBase64Encoded"
  ]);
  if (fromImageBytes != null) {
    setValueByPath(toObject, ["imageBytes"], tBytes(fromImageBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function safetyAttributesFromMldev(fromObject) {
  const toObject = {};
  const fromCategories = getValueByPath(fromObject, [
    "safetyAttributes",
    "categories"
  ]);
  if (fromCategories != null) {
    setValueByPath(toObject, ["categories"], fromCategories);
  }
  const fromScores = getValueByPath(fromObject, [
    "safetyAttributes",
    "scores"
  ]);
  if (fromScores != null) {
    setValueByPath(toObject, ["scores"], fromScores);
  }
  const fromContentType = getValueByPath(fromObject, ["contentType"]);
  if (fromContentType != null) {
    setValueByPath(toObject, ["contentType"], fromContentType);
  }
  return toObject;
}
function generatedImageFromMldev(fromObject) {
  const toObject = {};
  const fromImage = getValueByPath(fromObject, ["_self"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["image"], imageFromMldev(fromImage));
  }
  const fromRaiFilteredReason = getValueByPath(fromObject, [
    "raiFilteredReason"
  ]);
  if (fromRaiFilteredReason != null) {
    setValueByPath(toObject, ["raiFilteredReason"], fromRaiFilteredReason);
  }
  const fromSafetyAttributes = getValueByPath(fromObject, ["_self"]);
  if (fromSafetyAttributes != null) {
    setValueByPath(toObject, ["safetyAttributes"], safetyAttributesFromMldev(fromSafetyAttributes));
  }
  return toObject;
}
function generateImagesResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromGeneratedImages = getValueByPath(fromObject, [
    "predictions"
  ]);
  if (fromGeneratedImages != null) {
    let transformedList = fromGeneratedImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedImageFromMldev(item);
      });
    }
    setValueByPath(toObject, ["generatedImages"], transformedList);
  }
  const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [
    "positivePromptSafetyAttributes"
  ]);
  if (fromPositivePromptSafetyAttributes != null) {
    setValueByPath(toObject, ["positivePromptSafetyAttributes"], safetyAttributesFromMldev(fromPositivePromptSafetyAttributes));
  }
  return toObject;
}
function tunedModelInfoFromMldev(fromObject) {
  const toObject = {};
  const fromBaseModel = getValueByPath(fromObject, ["baseModel"]);
  if (fromBaseModel != null) {
    setValueByPath(toObject, ["baseModel"], fromBaseModel);
  }
  const fromCreateTime = getValueByPath(fromObject, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  return toObject;
}
function modelFromMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromVersion = getValueByPath(fromObject, ["version"]);
  if (fromVersion != null) {
    setValueByPath(toObject, ["version"], fromVersion);
  }
  const fromTunedModelInfo = getValueByPath(fromObject, ["_self"]);
  if (fromTunedModelInfo != null) {
    setValueByPath(toObject, ["tunedModelInfo"], tunedModelInfoFromMldev(fromTunedModelInfo));
  }
  const fromInputTokenLimit = getValueByPath(fromObject, [
    "inputTokenLimit"
  ]);
  if (fromInputTokenLimit != null) {
    setValueByPath(toObject, ["inputTokenLimit"], fromInputTokenLimit);
  }
  const fromOutputTokenLimit = getValueByPath(fromObject, [
    "outputTokenLimit"
  ]);
  if (fromOutputTokenLimit != null) {
    setValueByPath(toObject, ["outputTokenLimit"], fromOutputTokenLimit);
  }
  const fromSupportedActions = getValueByPath(fromObject, [
    "supportedGenerationMethods"
  ]);
  if (fromSupportedActions != null) {
    setValueByPath(toObject, ["supportedActions"], fromSupportedActions);
  }
  return toObject;
}
function listModelsResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromModels = getValueByPath(fromObject, ["_self"]);
  if (fromModels != null) {
    let transformedList = tExtractModels(fromModels);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modelFromMldev(item);
      });
    }
    setValueByPath(toObject, ["models"], transformedList);
  }
  return toObject;
}
function deleteModelResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function countTokensResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromTotalTokens = getValueByPath(fromObject, ["totalTokens"]);
  if (fromTotalTokens != null) {
    setValueByPath(toObject, ["totalTokens"], fromTotalTokens);
  }
  const fromCachedContentTokenCount = getValueByPath(fromObject, [
    "cachedContentTokenCount"
  ]);
  if (fromCachedContentTokenCount != null) {
    setValueByPath(toObject, ["cachedContentTokenCount"], fromCachedContentTokenCount);
  }
  return toObject;
}
function videoFromMldev(fromObject) {
  const toObject = {};
  const fromUri = getValueByPath(fromObject, ["video", "uri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["uri"], fromUri);
  }
  const fromVideoBytes = getValueByPath(fromObject, [
    "video",
    "encodedVideo"
  ]);
  if (fromVideoBytes != null) {
    setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["encoding"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function generatedVideoFromMldev(fromObject) {
  const toObject = {};
  const fromVideo = getValueByPath(fromObject, ["_self"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], videoFromMldev(fromVideo));
  }
  return toObject;
}
function generateVideosResponseFromMldev(fromObject) {
  const toObject = {};
  const fromGeneratedVideos = getValueByPath(fromObject, [
    "generatedSamples"
  ]);
  if (fromGeneratedVideos != null) {
    let transformedList = fromGeneratedVideos;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedVideoFromMldev(item);
      });
    }
    setValueByPath(toObject, ["generatedVideos"], transformedList);
  }
  const fromRaiMediaFilteredCount = getValueByPath(fromObject, [
    "raiMediaFilteredCount"
  ]);
  if (fromRaiMediaFilteredCount != null) {
    setValueByPath(toObject, ["raiMediaFilteredCount"], fromRaiMediaFilteredCount);
  }
  const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [
    "raiMediaFilteredReasons"
  ]);
  if (fromRaiMediaFilteredReasons != null) {
    setValueByPath(toObject, ["raiMediaFilteredReasons"], fromRaiMediaFilteredReasons);
  }
  return toObject;
}
function generateVideosOperationFromMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromDone = getValueByPath(fromObject, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  const fromResponse = getValueByPath(fromObject, [
    "response",
    "generateVideoResponse"
  ]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], generateVideosResponseFromMldev(fromResponse));
  }
  return toObject;
}
function videoMetadataFromVertex(fromObject) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobFromVertex(fromObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataFromVertex(fromObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromFileUri = getValueByPath(fromObject, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function partFromVertex(fromObject) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataFromVertex(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobFromVertex(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataFromVertex(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromCodeExecutionResult = getValueByPath(fromObject, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], fromFunctionCall);
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentFromVertex(fromObject) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partFromVertex(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function citationMetadataFromVertex(fromObject) {
  const toObject = {};
  const fromCitations = getValueByPath(fromObject, ["citations"]);
  if (fromCitations != null) {
    setValueByPath(toObject, ["citations"], fromCitations);
  }
  return toObject;
}
function urlMetadataFromVertex(fromObject) {
  const toObject = {};
  const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]);
  if (fromRetrievedUrl != null) {
    setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl);
  }
  const fromUrlRetrievalStatus = getValueByPath(fromObject, [
    "urlRetrievalStatus"
  ]);
  if (fromUrlRetrievalStatus != null) {
    setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus);
  }
  return toObject;
}
function urlContextMetadataFromVertex(fromObject) {
  const toObject = {};
  const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]);
  if (fromUrlMetadata != null) {
    let transformedList = fromUrlMetadata;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return urlMetadataFromVertex(item);
      });
    }
    setValueByPath(toObject, ["urlMetadata"], transformedList);
  }
  return toObject;
}
function candidateFromVertex(fromObject) {
  const toObject = {};
  const fromContent = getValueByPath(fromObject, ["content"]);
  if (fromContent != null) {
    setValueByPath(toObject, ["content"], contentFromVertex(fromContent));
  }
  const fromCitationMetadata = getValueByPath(fromObject, [
    "citationMetadata"
  ]);
  if (fromCitationMetadata != null) {
    setValueByPath(toObject, ["citationMetadata"], citationMetadataFromVertex(fromCitationMetadata));
  }
  const fromFinishMessage = getValueByPath(fromObject, [
    "finishMessage"
  ]);
  if (fromFinishMessage != null) {
    setValueByPath(toObject, ["finishMessage"], fromFinishMessage);
  }
  const fromFinishReason = getValueByPath(fromObject, ["finishReason"]);
  if (fromFinishReason != null) {
    setValueByPath(toObject, ["finishReason"], fromFinishReason);
  }
  const fromUrlContextMetadata = getValueByPath(fromObject, [
    "urlContextMetadata"
  ]);
  if (fromUrlContextMetadata != null) {
    setValueByPath(toObject, ["urlContextMetadata"], urlContextMetadataFromVertex(fromUrlContextMetadata));
  }
  const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]);
  if (fromAvgLogprobs != null) {
    setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs);
  }
  const fromGroundingMetadata = getValueByPath(fromObject, [
    "groundingMetadata"
  ]);
  if (fromGroundingMetadata != null) {
    setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata);
  }
  const fromIndex = getValueByPath(fromObject, ["index"]);
  if (fromIndex != null) {
    setValueByPath(toObject, ["index"], fromIndex);
  }
  const fromLogprobsResult = getValueByPath(fromObject, [
    "logprobsResult"
  ]);
  if (fromLogprobsResult != null) {
    setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult);
  }
  const fromSafetyRatings = getValueByPath(fromObject, [
    "safetyRatings"
  ]);
  if (fromSafetyRatings != null) {
    setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings);
  }
  return toObject;
}
function generateContentResponseFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromCandidates = getValueByPath(fromObject, ["candidates"]);
  if (fromCandidates != null) {
    let transformedList = fromCandidates;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return candidateFromVertex(item);
      });
    }
    setValueByPath(toObject, ["candidates"], transformedList);
  }
  const fromCreateTime = getValueByPath(fromObject, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]);
  if (fromModelVersion != null) {
    setValueByPath(toObject, ["modelVersion"], fromModelVersion);
  }
  const fromPromptFeedback = getValueByPath(fromObject, [
    "promptFeedback"
  ]);
  if (fromPromptFeedback != null) {
    setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback);
  }
  const fromResponseId = getValueByPath(fromObject, ["responseId"]);
  if (fromResponseId != null) {
    setValueByPath(toObject, ["responseId"], fromResponseId);
  }
  const fromUsageMetadata = getValueByPath(fromObject, [
    "usageMetadata"
  ]);
  if (fromUsageMetadata != null) {
    setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata);
  }
  return toObject;
}
function contentEmbeddingStatisticsFromVertex(fromObject) {
  const toObject = {};
  const fromTruncated = getValueByPath(fromObject, ["truncated"]);
  if (fromTruncated != null) {
    setValueByPath(toObject, ["truncated"], fromTruncated);
  }
  const fromTokenCount = getValueByPath(fromObject, ["token_count"]);
  if (fromTokenCount != null) {
    setValueByPath(toObject, ["tokenCount"], fromTokenCount);
  }
  return toObject;
}
function contentEmbeddingFromVertex(fromObject) {
  const toObject = {};
  const fromValues = getValueByPath(fromObject, ["values"]);
  if (fromValues != null) {
    setValueByPath(toObject, ["values"], fromValues);
  }
  const fromStatistics = getValueByPath(fromObject, ["statistics"]);
  if (fromStatistics != null) {
    setValueByPath(toObject, ["statistics"], contentEmbeddingStatisticsFromVertex(fromStatistics));
  }
  return toObject;
}
function embedContentMetadataFromVertex(fromObject) {
  const toObject = {};
  const fromBillableCharacterCount = getValueByPath(fromObject, [
    "billableCharacterCount"
  ]);
  if (fromBillableCharacterCount != null) {
    setValueByPath(toObject, ["billableCharacterCount"], fromBillableCharacterCount);
  }
  return toObject;
}
function embedContentResponseFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromEmbeddings = getValueByPath(fromObject, [
    "predictions[]",
    "embeddings"
  ]);
  if (fromEmbeddings != null) {
    let transformedList = fromEmbeddings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentEmbeddingFromVertex(item);
      });
    }
    setValueByPath(toObject, ["embeddings"], transformedList);
  }
  const fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], embedContentMetadataFromVertex(fromMetadata));
  }
  return toObject;
}
function imageFromVertex(fromObject) {
  const toObject = {};
  const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["gcsUri"], fromGcsUri);
  }
  const fromImageBytes = getValueByPath(fromObject, [
    "bytesBase64Encoded"
  ]);
  if (fromImageBytes != null) {
    setValueByPath(toObject, ["imageBytes"], tBytes(fromImageBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function safetyAttributesFromVertex(fromObject) {
  const toObject = {};
  const fromCategories = getValueByPath(fromObject, [
    "safetyAttributes",
    "categories"
  ]);
  if (fromCategories != null) {
    setValueByPath(toObject, ["categories"], fromCategories);
  }
  const fromScores = getValueByPath(fromObject, [
    "safetyAttributes",
    "scores"
  ]);
  if (fromScores != null) {
    setValueByPath(toObject, ["scores"], fromScores);
  }
  const fromContentType = getValueByPath(fromObject, ["contentType"]);
  if (fromContentType != null) {
    setValueByPath(toObject, ["contentType"], fromContentType);
  }
  return toObject;
}
function generatedImageFromVertex(fromObject) {
  const toObject = {};
  const fromImage = getValueByPath(fromObject, ["_self"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["image"], imageFromVertex(fromImage));
  }
  const fromRaiFilteredReason = getValueByPath(fromObject, [
    "raiFilteredReason"
  ]);
  if (fromRaiFilteredReason != null) {
    setValueByPath(toObject, ["raiFilteredReason"], fromRaiFilteredReason);
  }
  const fromSafetyAttributes = getValueByPath(fromObject, ["_self"]);
  if (fromSafetyAttributes != null) {
    setValueByPath(toObject, ["safetyAttributes"], safetyAttributesFromVertex(fromSafetyAttributes));
  }
  const fromEnhancedPrompt = getValueByPath(fromObject, ["prompt"]);
  if (fromEnhancedPrompt != null) {
    setValueByPath(toObject, ["enhancedPrompt"], fromEnhancedPrompt);
  }
  return toObject;
}
function generateImagesResponseFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromGeneratedImages = getValueByPath(fromObject, [
    "predictions"
  ]);
  if (fromGeneratedImages != null) {
    let transformedList = fromGeneratedImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedImageFromVertex(item);
      });
    }
    setValueByPath(toObject, ["generatedImages"], transformedList);
  }
  const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [
    "positivePromptSafetyAttributes"
  ]);
  if (fromPositivePromptSafetyAttributes != null) {
    setValueByPath(toObject, ["positivePromptSafetyAttributes"], safetyAttributesFromVertex(fromPositivePromptSafetyAttributes));
  }
  return toObject;
}
function editImageResponseFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromGeneratedImages = getValueByPath(fromObject, [
    "predictions"
  ]);
  if (fromGeneratedImages != null) {
    let transformedList = fromGeneratedImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedImageFromVertex(item);
      });
    }
    setValueByPath(toObject, ["generatedImages"], transformedList);
  }
  return toObject;
}
function upscaleImageResponseFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromGeneratedImages = getValueByPath(fromObject, [
    "predictions"
  ]);
  if (fromGeneratedImages != null) {
    let transformedList = fromGeneratedImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedImageFromVertex(item);
      });
    }
    setValueByPath(toObject, ["generatedImages"], transformedList);
  }
  return toObject;
}
function recontextImageResponseFromVertex(fromObject) {
  const toObject = {};
  const fromGeneratedImages = getValueByPath(fromObject, [
    "predictions"
  ]);
  if (fromGeneratedImages != null) {
    let transformedList = fromGeneratedImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedImageFromVertex(item);
      });
    }
    setValueByPath(toObject, ["generatedImages"], transformedList);
  }
  return toObject;
}
function entityLabelFromVertex(fromObject) {
  const toObject = {};
  const fromLabel = getValueByPath(fromObject, ["label"]);
  if (fromLabel != null) {
    setValueByPath(toObject, ["label"], fromLabel);
  }
  const fromScore = getValueByPath(fromObject, ["score"]);
  if (fromScore != null) {
    setValueByPath(toObject, ["score"], fromScore);
  }
  return toObject;
}
function generatedImageMaskFromVertex(fromObject) {
  const toObject = {};
  const fromMask = getValueByPath(fromObject, ["_self"]);
  if (fromMask != null) {
    setValueByPath(toObject, ["mask"], imageFromVertex(fromMask));
  }
  const fromLabels = getValueByPath(fromObject, ["labels"]);
  if (fromLabels != null) {
    let transformedList = fromLabels;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return entityLabelFromVertex(item);
      });
    }
    setValueByPath(toObject, ["labels"], transformedList);
  }
  return toObject;
}
function segmentImageResponseFromVertex(fromObject) {
  const toObject = {};
  const fromGeneratedMasks = getValueByPath(fromObject, ["predictions"]);
  if (fromGeneratedMasks != null) {
    let transformedList = fromGeneratedMasks;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedImageMaskFromVertex(item);
      });
    }
    setValueByPath(toObject, ["generatedMasks"], transformedList);
  }
  return toObject;
}
function endpointFromVertex(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["endpoint"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDeployedModelId = getValueByPath(fromObject, [
    "deployedModelId"
  ]);
  if (fromDeployedModelId != null) {
    setValueByPath(toObject, ["deployedModelId"], fromDeployedModelId);
  }
  return toObject;
}
function tunedModelInfoFromVertex(fromObject) {
  const toObject = {};
  const fromBaseModel = getValueByPath(fromObject, [
    "labels",
    "google-vertex-llm-tuning-base-model-id"
  ]);
  if (fromBaseModel != null) {
    setValueByPath(toObject, ["baseModel"], fromBaseModel);
  }
  const fromCreateTime = getValueByPath(fromObject, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  return toObject;
}
function checkpointFromVertex(fromObject) {
  const toObject = {};
  const fromCheckpointId = getValueByPath(fromObject, ["checkpointId"]);
  if (fromCheckpointId != null) {
    setValueByPath(toObject, ["checkpointId"], fromCheckpointId);
  }
  const fromEpoch = getValueByPath(fromObject, ["epoch"]);
  if (fromEpoch != null) {
    setValueByPath(toObject, ["epoch"], fromEpoch);
  }
  const fromStep = getValueByPath(fromObject, ["step"]);
  if (fromStep != null) {
    setValueByPath(toObject, ["step"], fromStep);
  }
  return toObject;
}
function modelFromVertex(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromVersion = getValueByPath(fromObject, ["versionId"]);
  if (fromVersion != null) {
    setValueByPath(toObject, ["version"], fromVersion);
  }
  const fromEndpoints = getValueByPath(fromObject, ["deployedModels"]);
  if (fromEndpoints != null) {
    let transformedList = fromEndpoints;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return endpointFromVertex(item);
      });
    }
    setValueByPath(toObject, ["endpoints"], transformedList);
  }
  const fromLabels = getValueByPath(fromObject, ["labels"]);
  if (fromLabels != null) {
    setValueByPath(toObject, ["labels"], fromLabels);
  }
  const fromTunedModelInfo = getValueByPath(fromObject, ["_self"]);
  if (fromTunedModelInfo != null) {
    setValueByPath(toObject, ["tunedModelInfo"], tunedModelInfoFromVertex(fromTunedModelInfo));
  }
  const fromDefaultCheckpointId = getValueByPath(fromObject, [
    "defaultCheckpointId"
  ]);
  if (fromDefaultCheckpointId != null) {
    setValueByPath(toObject, ["defaultCheckpointId"], fromDefaultCheckpointId);
  }
  const fromCheckpoints = getValueByPath(fromObject, ["checkpoints"]);
  if (fromCheckpoints != null) {
    let transformedList = fromCheckpoints;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return checkpointFromVertex(item);
      });
    }
    setValueByPath(toObject, ["checkpoints"], transformedList);
  }
  return toObject;
}
function listModelsResponseFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromModels = getValueByPath(fromObject, ["_self"]);
  if (fromModels != null) {
    let transformedList = tExtractModels(fromModels);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modelFromVertex(item);
      });
    }
    setValueByPath(toObject, ["models"], transformedList);
  }
  return toObject;
}
function deleteModelResponseFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function countTokensResponseFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromTotalTokens = getValueByPath(fromObject, ["totalTokens"]);
  if (fromTotalTokens != null) {
    setValueByPath(toObject, ["totalTokens"], fromTotalTokens);
  }
  return toObject;
}
function computeTokensResponseFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromTokensInfo = getValueByPath(fromObject, ["tokensInfo"]);
  if (fromTokensInfo != null) {
    setValueByPath(toObject, ["tokensInfo"], fromTokensInfo);
  }
  return toObject;
}
function videoFromVertex(fromObject) {
  const toObject = {};
  const fromUri = getValueByPath(fromObject, ["gcsUri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["uri"], fromUri);
  }
  const fromVideoBytes = getValueByPath(fromObject, [
    "bytesBase64Encoded"
  ]);
  if (fromVideoBytes != null) {
    setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes));
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function generatedVideoFromVertex(fromObject) {
  const toObject = {};
  const fromVideo = getValueByPath(fromObject, ["_self"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], videoFromVertex(fromVideo));
  }
  return toObject;
}
function generateVideosResponseFromVertex(fromObject) {
  const toObject = {};
  const fromGeneratedVideos = getValueByPath(fromObject, ["videos"]);
  if (fromGeneratedVideos != null) {
    let transformedList = fromGeneratedVideos;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedVideoFromVertex(item);
      });
    }
    setValueByPath(toObject, ["generatedVideos"], transformedList);
  }
  const fromRaiMediaFilteredCount = getValueByPath(fromObject, [
    "raiMediaFilteredCount"
  ]);
  if (fromRaiMediaFilteredCount != null) {
    setValueByPath(toObject, ["raiMediaFilteredCount"], fromRaiMediaFilteredCount);
  }
  const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [
    "raiMediaFilteredReasons"
  ]);
  if (fromRaiMediaFilteredReasons != null) {
    setValueByPath(toObject, ["raiMediaFilteredReasons"], fromRaiMediaFilteredReasons);
  }
  return toObject;
}
function generateVideosOperationFromVertex(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromDone = getValueByPath(fromObject, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], generateVideosResponseFromVertex(fromResponse));
  }
  return toObject;
}
async function throwErrorIfNotOK(response) {
  var _a6;
  if (response === void 0) {
    throw new Error("response is undefined");
  }
  if (!response.ok) {
    const status = response.status;
    let errorBody;
    if ((_a6 = response.headers.get("content-type")) === null || _a6 === void 0 ? void 0 : _a6.includes("application/json")) {
      errorBody = await response.json();
    } else {
      errorBody = {
        error: {
          message: await response.text(),
          code: response.status,
          status: response.statusText
        }
      };
    }
    const errorMessage = JSON.stringify(errorBody);
    if (status >= 400 && status < 600) {
      const apiError = new ApiError({
        message: errorMessage,
        status
      });
      throw apiError;
    }
    throw new Error(errorMessage);
  }
}
function includeExtraBodyToRequestInit(requestInit, extraBody) {
  if (!extraBody || Object.keys(extraBody).length === 0) {
    return;
  }
  if (requestInit.body instanceof Blob) {
    console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");
    return;
  }
  let currentBodyObject = {};
  if (typeof requestInit.body === "string" && requestInit.body.length > 0) {
    try {
      const parsedBody = JSON.parse(requestInit.body);
      if (typeof parsedBody === "object" && parsedBody !== null && !Array.isArray(parsedBody)) {
        currentBodyObject = parsedBody;
      } else {
        console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");
        return;
      }
    } catch (e2) {
      console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");
      return;
    }
  }
  function deepMerge2(target, source2) {
    const output = Object.assign({}, target);
    for (const key in source2) {
      if (Object.prototype.hasOwnProperty.call(source2, key)) {
        const sourceValue = source2[key];
        const targetValue = output[key];
        if (sourceValue && typeof sourceValue === "object" && !Array.isArray(sourceValue) && targetValue && typeof targetValue === "object" && !Array.isArray(targetValue)) {
          output[key] = deepMerge2(targetValue, sourceValue);
        } else {
          if (targetValue && sourceValue && typeof targetValue !== typeof sourceValue) {
            console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`);
          }
          output[key] = sourceValue;
        }
      }
    }
    return output;
  }
  __name(deepMerge2, "deepMerge");
  const mergedBody = deepMerge2(currentBodyObject, extraBody);
  requestInit.body = JSON.stringify(mergedBody);
}
function hasMcpToolUsage(tools) {
  for (const tool of tools) {
    if (isMcpCallableTool(tool)) {
      return true;
    }
    if (typeof tool === "object" && "inputSchema" in tool) {
      return true;
    }
  }
  return hasMcpToolUsageFromMcpToTool;
}
function setMcpUsageHeader(headers) {
  var _a6;
  const existingHeader = (_a6 = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a6 !== void 0 ? _a6 : "";
  headers[GOOGLE_API_CLIENT_HEADER] = (existingHeader + ` ${MCP_LABEL}`).trimStart();
}
function isMcpCallableTool(object) {
  return object !== null && typeof object === "object" && object instanceof McpCallableTool;
}
function listAllTools(mcpClient, maxTools = 100) {
  return __asyncGenerator(this, arguments, /* @__PURE__ */ __name(function* listAllTools_1() {
    let cursor = void 0;
    let numTools = 0;
    while (numTools < maxTools) {
      const t2 = yield __await(mcpClient.listTools({ cursor }));
      for (const tool of t2.tools) {
        yield yield __await(tool);
        numTools++;
      }
      if (!t2.nextCursor) {
        break;
      }
      cursor = t2.nextCursor;
    }
  }, "listAllTools_1"));
}
function isMcpClient(client) {
  return client !== null && typeof client === "object" && "listTools" in client && typeof client.listTools === "function";
}
function mcpToTool(...args) {
  hasMcpToolUsageFromMcpToTool = true;
  if (args.length === 0) {
    throw new Error("No MCP clients provided");
  }
  const maybeConfig = args[args.length - 1];
  if (isMcpClient(maybeConfig)) {
    return McpCallableTool.create(args, {});
  }
  return McpCallableTool.create(args.slice(0, args.length - 1), maybeConfig);
}
async function handleWebSocketMessage$1(apiClient, onmessage, event) {
  const serverMessage = new LiveMusicServerMessage();
  let data;
  if (event.data instanceof Blob) {
    data = JSON.parse(await event.data.text());
  } else {
    data = JSON.parse(event.data);
  }
  const response = liveMusicServerMessageFromMldev(data);
  Object.assign(serverMessage, response);
  onmessage(serverMessage);
}
function headersToMap$1(headers) {
  const headerMap = {};
  headers.forEach((value, key) => {
    headerMap[key] = value;
  });
  return headerMap;
}
function mapToHeaders$1(map2) {
  const headers = new Headers();
  for (const [key, value] of Object.entries(map2)) {
    headers.append(key, value);
  }
  return headers;
}
async function handleWebSocketMessage(apiClient, onmessage, event) {
  const serverMessage = new LiveServerMessage();
  let jsonData;
  if (event.data instanceof Blob) {
    jsonData = await event.data.text();
  } else if (event.data instanceof ArrayBuffer) {
    jsonData = new TextDecoder().decode(event.data);
  } else {
    jsonData = event.data;
  }
  const data = JSON.parse(jsonData);
  if (apiClient.isVertexAI()) {
    const resp = liveServerMessageFromVertex(data);
    Object.assign(serverMessage, resp);
  } else {
    const resp = liveServerMessageFromMldev(data);
    Object.assign(serverMessage, resp);
  }
  onmessage(serverMessage);
}
function headersToMap(headers) {
  const headerMap = {};
  headers.forEach((value, key) => {
    headerMap[key] = value;
  });
  return headerMap;
}
function mapToHeaders(map2) {
  const headers = new Headers();
  for (const [key, value] of Object.entries(map2)) {
    headers.append(key, value);
  }
  return headers;
}
function shouldDisableAfc(config) {
  var _a6, _b2, _c2;
  if ((_a6 = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a6 === void 0 ? void 0 : _a6.disable) {
    return true;
  }
  let callableToolsPresent = false;
  for (const tool of (_b2 = config === null || config === void 0 ? void 0 : config.tools) !== null && _b2 !== void 0 ? _b2 : []) {
    if (isCallableTool(tool)) {
      callableToolsPresent = true;
      break;
    }
  }
  if (!callableToolsPresent) {
    return true;
  }
  const maxCalls = (_c2 = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _c2 === void 0 ? void 0 : _c2.maximumRemoteCalls;
  if (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls)) || maxCalls == 0) {
    console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:", maxCalls);
    return true;
  }
  return false;
}
function isCallableTool(tool) {
  return "callTool" in tool && typeof tool.callTool === "function";
}
function hasCallableTools(params) {
  var _a6, _b2, _c2;
  return (_c2 = (_b2 = (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.tools) === null || _b2 === void 0 ? void 0 : _b2.some((tool) => isCallableTool(tool))) !== null && _c2 !== void 0 ? _c2 : false;
}
function hasNonCallableTools(params) {
  var _a6, _b2, _c2;
  return (_c2 = (_b2 = (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.tools) === null || _b2 === void 0 ? void 0 : _b2.some((tool) => !isCallableTool(tool))) !== null && _c2 !== void 0 ? _c2 : false;
}
function shouldAppendAfcHistory(config) {
  var _a6;
  return !((_a6 = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a6 === void 0 ? void 0 : _a6.ignoreCallHistory);
}
function getOperationParametersToMldev(fromObject) {
  const toObject = {};
  const fromOperationName = getValueByPath(fromObject, [
    "operationName"
  ]);
  if (fromOperationName != null) {
    setValueByPath(toObject, ["_url", "operationName"], fromOperationName);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function fetchPredictOperationParametersToVertex(fromObject) {
  const toObject = {};
  const fromOperationName = getValueByPath(fromObject, [
    "operationName"
  ]);
  if (fromOperationName != null) {
    setValueByPath(toObject, ["operationName"], fromOperationName);
  }
  const fromResourceName = getValueByPath(fromObject, ["resourceName"]);
  if (fromResourceName != null) {
    setValueByPath(toObject, ["_url", "resourceName"], fromResourceName);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function getOperationParametersToVertex(fromObject) {
  const toObject = {};
  const fromOperationName = getValueByPath(fromObject, [
    "operationName"
  ]);
  if (fromOperationName != null) {
    setValueByPath(toObject, ["_url", "operationName"], fromOperationName);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function prebuiltVoiceConfigToMldev(fromObject) {
  const toObject = {};
  const fromVoiceName = getValueByPath(fromObject, ["voiceName"]);
  if (fromVoiceName != null) {
    setValueByPath(toObject, ["voiceName"], fromVoiceName);
  }
  return toObject;
}
function voiceConfigToMldev(fromObject) {
  const toObject = {};
  const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [
    "prebuiltVoiceConfig"
  ]);
  if (fromPrebuiltVoiceConfig != null) {
    setValueByPath(toObject, ["prebuiltVoiceConfig"], prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig));
  }
  return toObject;
}
function speakerVoiceConfigToMldev(fromObject) {
  const toObject = {};
  const fromSpeaker = getValueByPath(fromObject, ["speaker"]);
  if (fromSpeaker != null) {
    setValueByPath(toObject, ["speaker"], fromSpeaker);
  }
  const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToMldev(fromVoiceConfig));
  }
  return toObject;
}
function multiSpeakerVoiceConfigToMldev(fromObject) {
  const toObject = {};
  const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [
    "speakerVoiceConfigs"
  ]);
  if (fromSpeakerVoiceConfigs != null) {
    let transformedList = fromSpeakerVoiceConfigs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return speakerVoiceConfigToMldev(item);
      });
    }
    setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList);
  }
  return toObject;
}
function speechConfigToMldev(fromObject) {
  const toObject = {};
  const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToMldev(fromVoiceConfig));
  }
  const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [
    "multiSpeakerVoiceConfig"
  ]);
  if (fromMultiSpeakerVoiceConfig != null) {
    setValueByPath(toObject, ["multiSpeakerVoiceConfig"], multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig));
  }
  const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function videoMetadataToMldev(fromObject) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobToMldev(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromData = getValueByPath(fromObject, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataToMldev(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromFileUri = getValueByPath(fromObject, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function partToMldev(fromObject) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataToMldev(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromCodeExecutionResult = getValueByPath(fromObject, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], fromFunctionCall);
  }
  const fromFunctionResponse = getValueByPath(fromObject, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentToMldev(fromObject) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToMldev(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function functionDeclarationToMldev(fromObject) {
  const toObject = {};
  const fromBehavior = getValueByPath(fromObject, ["behavior"]);
  if (fromBehavior != null) {
    setValueByPath(toObject, ["behavior"], fromBehavior);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  return toObject;
}
function intervalToMldev(fromObject) {
  const toObject = {};
  const fromStartTime = getValueByPath(fromObject, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  return toObject;
}
function googleSearchToMldev(fromObject) {
  const toObject = {};
  const fromTimeRangeFilter = getValueByPath(fromObject, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], intervalToMldev(fromTimeRangeFilter));
  }
  if (getValueByPath(fromObject, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  return toObject;
}
function dynamicRetrievalConfigToMldev(fromObject) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromDynamicThreshold = getValueByPath(fromObject, [
    "dynamicThreshold"
  ]);
  if (fromDynamicThreshold != null) {
    setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold);
  }
  return toObject;
}
function googleSearchRetrievalToMldev(fromObject) {
  const toObject = {};
  const fromDynamicRetrievalConfig = getValueByPath(fromObject, [
    "dynamicRetrievalConfig"
  ]);
  if (fromDynamicRetrievalConfig != null) {
    setValueByPath(toObject, ["dynamicRetrievalConfig"], dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig));
  }
  return toObject;
}
function urlContextToMldev() {
  const toObject = {};
  return toObject;
}
function toolComputerUseToMldev(fromObject) {
  const toObject = {};
  const fromEnvironment = getValueByPath(fromObject, ["environment"]);
  if (fromEnvironment != null) {
    setValueByPath(toObject, ["environment"], fromEnvironment);
  }
  return toObject;
}
function toolToMldev(fromObject) {
  const toObject = {};
  const fromFunctionDeclarations = getValueByPath(fromObject, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToMldev(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  if (getValueByPath(fromObject, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev(fromGoogleSearch));
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], googleSearchRetrievalToMldev(fromGoogleSearchRetrieval));
  }
  if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["googleMaps"]) !== void 0) {
    throw new Error("googleMaps parameter is not supported in Gemini API.");
  }
  const fromUrlContext = getValueByPath(fromObject, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], urlContextToMldev());
  }
  const fromComputerUse = getValueByPath(fromObject, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], toolComputerUseToMldev(fromComputerUse));
  }
  const fromCodeExecution = getValueByPath(fromObject, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  return toObject;
}
function sessionResumptionConfigToMldev(fromObject) {
  const toObject = {};
  const fromHandle = getValueByPath(fromObject, ["handle"]);
  if (fromHandle != null) {
    setValueByPath(toObject, ["handle"], fromHandle);
  }
  if (getValueByPath(fromObject, ["transparent"]) !== void 0) {
    throw new Error("transparent parameter is not supported in Gemini API.");
  }
  return toObject;
}
function audioTranscriptionConfigToMldev() {
  const toObject = {};
  return toObject;
}
function automaticActivityDetectionToMldev(fromObject) {
  const toObject = {};
  const fromDisabled = getValueByPath(fromObject, ["disabled"]);
  if (fromDisabled != null) {
    setValueByPath(toObject, ["disabled"], fromDisabled);
  }
  const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [
    "startOfSpeechSensitivity"
  ]);
  if (fromStartOfSpeechSensitivity != null) {
    setValueByPath(toObject, ["startOfSpeechSensitivity"], fromStartOfSpeechSensitivity);
  }
  const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [
    "endOfSpeechSensitivity"
  ]);
  if (fromEndOfSpeechSensitivity != null) {
    setValueByPath(toObject, ["endOfSpeechSensitivity"], fromEndOfSpeechSensitivity);
  }
  const fromPrefixPaddingMs = getValueByPath(fromObject, [
    "prefixPaddingMs"
  ]);
  if (fromPrefixPaddingMs != null) {
    setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs);
  }
  const fromSilenceDurationMs = getValueByPath(fromObject, [
    "silenceDurationMs"
  ]);
  if (fromSilenceDurationMs != null) {
    setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs);
  }
  return toObject;
}
function realtimeInputConfigToMldev(fromObject) {
  const toObject = {};
  const fromAutomaticActivityDetection = getValueByPath(fromObject, [
    "automaticActivityDetection"
  ]);
  if (fromAutomaticActivityDetection != null) {
    setValueByPath(toObject, ["automaticActivityDetection"], automaticActivityDetectionToMldev(fromAutomaticActivityDetection));
  }
  const fromActivityHandling = getValueByPath(fromObject, [
    "activityHandling"
  ]);
  if (fromActivityHandling != null) {
    setValueByPath(toObject, ["activityHandling"], fromActivityHandling);
  }
  const fromTurnCoverage = getValueByPath(fromObject, ["turnCoverage"]);
  if (fromTurnCoverage != null) {
    setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage);
  }
  return toObject;
}
function slidingWindowToMldev(fromObject) {
  const toObject = {};
  const fromTargetTokens = getValueByPath(fromObject, ["targetTokens"]);
  if (fromTargetTokens != null) {
    setValueByPath(toObject, ["targetTokens"], fromTargetTokens);
  }
  return toObject;
}
function contextWindowCompressionConfigToMldev(fromObject) {
  const toObject = {};
  const fromTriggerTokens = getValueByPath(fromObject, [
    "triggerTokens"
  ]);
  if (fromTriggerTokens != null) {
    setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens);
  }
  const fromSlidingWindow = getValueByPath(fromObject, [
    "slidingWindow"
  ]);
  if (fromSlidingWindow != null) {
    setValueByPath(toObject, ["slidingWindow"], slidingWindowToMldev(fromSlidingWindow));
  }
  return toObject;
}
function proactivityConfigToMldev(fromObject) {
  const toObject = {};
  const fromProactiveAudio = getValueByPath(fromObject, [
    "proactiveAudio"
  ]);
  if (fromProactiveAudio != null) {
    setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio);
  }
  return toObject;
}
function liveConnectConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromGenerationConfig = getValueByPath(fromObject, [
    "generationConfig"
  ]);
  if (parentObject !== void 0 && fromGenerationConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig"], fromGenerationConfig);
  }
  const fromResponseModalities = getValueByPath(fromObject, [
    "responseModalities"
  ]);
  if (parentObject !== void 0 && fromResponseModalities != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "responseModalities"], fromResponseModalities);
  }
  const fromTemperature = getValueByPath(fromObject, ["temperature"]);
  if (parentObject !== void 0 && fromTemperature != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "temperature"], fromTemperature);
  }
  const fromTopP = getValueByPath(fromObject, ["topP"]);
  if (parentObject !== void 0 && fromTopP != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject, ["topK"]);
  if (parentObject !== void 0 && fromTopK != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "topK"], fromTopK);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject, [
    "maxOutputTokens"
  ]);
  if (parentObject !== void 0 && fromMaxOutputTokens != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromMediaResolution = getValueByPath(fromObject, [
    "mediaResolution"
  ]);
  if (parentObject !== void 0 && fromMediaResolution != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "mediaResolution"], fromMediaResolution);
  }
  const fromSeed = getValueByPath(fromObject, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "seed"], fromSeed);
  }
  const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]);
  if (parentObject !== void 0 && fromSpeechConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "speechConfig"], speechConfigToMldev(tLiveSpeechConfig(fromSpeechConfig)));
  }
  const fromEnableAffectiveDialog = getValueByPath(fromObject, [
    "enableAffectiveDialog"
  ]);
  if (parentObject !== void 0 && fromEnableAffectiveDialog != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "enableAffectiveDialog"], fromEnableAffectiveDialog);
  }
  const fromSystemInstruction = getValueByPath(fromObject, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["setup", "systemInstruction"], contentToMldev(tContent(fromSystemInstruction)));
  }
  const fromTools = getValueByPath(fromObject, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = tTools(fromTools);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToMldev(tTool(item));
      });
    }
    setValueByPath(parentObject, ["setup", "tools"], transformedList);
  }
  const fromSessionResumption = getValueByPath(fromObject, [
    "sessionResumption"
  ]);
  if (parentObject !== void 0 && fromSessionResumption != null) {
    setValueByPath(parentObject, ["setup", "sessionResumption"], sessionResumptionConfigToMldev(fromSessionResumption));
  }
  const fromInputAudioTranscription = getValueByPath(fromObject, [
    "inputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromInputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "inputAudioTranscription"], audioTranscriptionConfigToMldev());
  }
  const fromOutputAudioTranscription = getValueByPath(fromObject, [
    "outputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromOutputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "outputAudioTranscription"], audioTranscriptionConfigToMldev());
  }
  const fromRealtimeInputConfig = getValueByPath(fromObject, [
    "realtimeInputConfig"
  ]);
  if (parentObject !== void 0 && fromRealtimeInputConfig != null) {
    setValueByPath(parentObject, ["setup", "realtimeInputConfig"], realtimeInputConfigToMldev(fromRealtimeInputConfig));
  }
  const fromContextWindowCompression = getValueByPath(fromObject, [
    "contextWindowCompression"
  ]);
  if (parentObject !== void 0 && fromContextWindowCompression != null) {
    setValueByPath(parentObject, ["setup", "contextWindowCompression"], contextWindowCompressionConfigToMldev(fromContextWindowCompression));
  }
  const fromProactivity = getValueByPath(fromObject, ["proactivity"]);
  if (parentObject !== void 0 && fromProactivity != null) {
    setValueByPath(parentObject, ["setup", "proactivity"], proactivityConfigToMldev(fromProactivity));
  }
  return toObject;
}
function liveConnectConstraintsToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], liveConnectConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) {
  const toObject = {};
  const fromExpireTime = getValueByPath(fromObject, ["expireTime"]);
  if (parentObject !== void 0 && fromExpireTime != null) {
    setValueByPath(parentObject, ["expireTime"], fromExpireTime);
  }
  const fromNewSessionExpireTime = getValueByPath(fromObject, [
    "newSessionExpireTime"
  ]);
  if (parentObject !== void 0 && fromNewSessionExpireTime != null) {
    setValueByPath(parentObject, ["newSessionExpireTime"], fromNewSessionExpireTime);
  }
  const fromUses = getValueByPath(fromObject, ["uses"]);
  if (parentObject !== void 0 && fromUses != null) {
    setValueByPath(parentObject, ["uses"], fromUses);
  }
  const fromLiveConnectConstraints = getValueByPath(fromObject, [
    "liveConnectConstraints"
  ]);
  if (parentObject !== void 0 && fromLiveConnectConstraints != null) {
    setValueByPath(parentObject, ["bidiGenerateContentSetup"], liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints));
  }
  const fromLockAdditionalFields = getValueByPath(fromObject, [
    "lockAdditionalFields"
  ]);
  if (parentObject !== void 0 && fromLockAdditionalFields != null) {
    setValueByPath(parentObject, ["fieldMask"], fromLockAdditionalFields);
  }
  return toObject;
}
function createAuthTokenParametersToMldev(apiClient, fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], createAuthTokenConfigToMldev(apiClient, fromConfig, toObject));
  }
  return toObject;
}
function authTokenFromMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  return toObject;
}
function getFieldMasks(setup) {
  const fields = [];
  for (const key in setup) {
    if (Object.prototype.hasOwnProperty.call(setup, key)) {
      const value = setup[key];
      if (typeof value === "object" && value != null && Object.keys(value).length > 0) {
        const field = Object.keys(value).map((kk) => `${key}.${kk}`);
        fields.push(...field);
      } else {
        fields.push(key);
      }
    }
  }
  return fields.join(",");
}
function convertBidiSetupToTokenSetup(requestDict, config) {
  let setupForMaskGeneration = null;
  const bidiGenerateContentSetupValue = requestDict["bidiGenerateContentSetup"];
  if (typeof bidiGenerateContentSetupValue === "object" && bidiGenerateContentSetupValue !== null && "setup" in bidiGenerateContentSetupValue) {
    const innerSetup = bidiGenerateContentSetupValue.setup;
    if (typeof innerSetup === "object" && innerSetup !== null) {
      requestDict["bidiGenerateContentSetup"] = innerSetup;
      setupForMaskGeneration = innerSetup;
    } else {
      delete requestDict["bidiGenerateContentSetup"];
    }
  } else if (bidiGenerateContentSetupValue !== void 0) {
    delete requestDict["bidiGenerateContentSetup"];
  }
  const preExistingFieldMask = requestDict["fieldMask"];
  if (setupForMaskGeneration) {
    const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration);
    if (Array.isArray(config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && (config === null || config === void 0 ? void 0 : config.lockAdditionalFields.length) === 0) {
      if (generatedMaskFromBidi) {
        requestDict["fieldMask"] = generatedMaskFromBidi;
      } else {
        delete requestDict["fieldMask"];
      }
    } else if ((config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && config.lockAdditionalFields.length > 0 && preExistingFieldMask !== null && Array.isArray(preExistingFieldMask) && preExistingFieldMask.length > 0) {
      const generationConfigFields = [
        "temperature",
        "topK",
        "topP",
        "maxOutputTokens",
        "responseModalities",
        "seed",
        "speechConfig"
      ];
      let mappedFieldsFromPreExisting = [];
      if (preExistingFieldMask.length > 0) {
        mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => {
          if (generationConfigFields.includes(field)) {
            return `generationConfig.${field}`;
          }
          return field;
        });
      }
      const finalMaskParts = [];
      if (generatedMaskFromBidi) {
        finalMaskParts.push(generatedMaskFromBidi);
      }
      if (mappedFieldsFromPreExisting.length > 0) {
        finalMaskParts.push(...mappedFieldsFromPreExisting);
      }
      if (finalMaskParts.length > 0) {
        requestDict["fieldMask"] = finalMaskParts.join(",");
      } else {
        delete requestDict["fieldMask"];
      }
    } else {
      delete requestDict["fieldMask"];
    }
  } else {
    if (preExistingFieldMask !== null && Array.isArray(preExistingFieldMask) && preExistingFieldMask.length > 0) {
      requestDict["fieldMask"] = preExistingFieldMask.join(",");
    } else {
      delete requestDict["fieldMask"];
    }
  }
  return requestDict;
}
function buildGoogleAuthOptions(googleAuthOptions) {
  let authOptions;
  if (!googleAuthOptions) {
    authOptions = {
      scopes: [REQUIRED_VERTEX_AI_SCOPE]
    };
    return authOptions;
  } else {
    authOptions = googleAuthOptions;
    if (!authOptions.scopes) {
      authOptions.scopes = [REQUIRED_VERTEX_AI_SCOPE];
      return authOptions;
    } else if (typeof authOptions.scopes === "string" && authOptions.scopes !== REQUIRED_VERTEX_AI_SCOPE || Array.isArray(authOptions.scopes) && authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE) < 0) {
      throw new Error(`Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`);
    }
    return authOptions;
  }
}
async function downloadFile(params, apiClient) {
  var _a6, _b2, _c2;
  const name3 = tFileName(params.file);
  if (name3 !== void 0) {
    return await apiClient.request({
      path: `files/${name3}:download`,
      httpMethod: "GET",
      queryParams: {
        "alt": "media"
      },
      httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
      abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
    });
  } else if (isGeneratedVideo(params.file)) {
    const videoBytes = (_c2 = params.file.video) === null || _c2 === void 0 ? void 0 : _c2.videoBytes;
    if (typeof videoBytes === "string") {
      return videoBytes;
    } else {
      throw new Error("Failed to download generated video, Uri or videoBytes not found.");
    }
  } else if (isVideo(params.file)) {
    const videoBytes = params.file.videoBytes;
    if (typeof videoBytes === "string") {
      return videoBytes;
    } else {
      throw new Error("Failed to download video, Uri or videoBytes not found.");
    }
  } else {
    throw new Error("Unsupported file type");
  }
}
function getTuningJobParametersToMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function listTuningJobsConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  const fromFilter = getValueByPath(fromObject, ["filter"]);
  if (parentObject !== void 0 && fromFilter != null) {
    setValueByPath(parentObject, ["_query", "filter"], fromFilter);
  }
  return toObject;
}
function listTuningJobsParametersToMldev(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], listTuningJobsConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function cancelTuningJobParametersToMldev(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function tuningExampleToMldev(fromObject) {
  const toObject = {};
  const fromTextInput = getValueByPath(fromObject, ["textInput"]);
  if (fromTextInput != null) {
    setValueByPath(toObject, ["textInput"], fromTextInput);
  }
  const fromOutput = getValueByPath(fromObject, ["output"]);
  if (fromOutput != null) {
    setValueByPath(toObject, ["output"], fromOutput);
  }
  return toObject;
}
function tuningDatasetToMldev(fromObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["gcsUri"]) !== void 0) {
    throw new Error("gcsUri parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["vertexDatasetResource"]) !== void 0) {
    throw new Error("vertexDatasetResource parameter is not supported in Gemini API.");
  }
  const fromExamples = getValueByPath(fromObject, ["examples"]);
  if (fromExamples != null) {
    let transformedList = fromExamples;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return tuningExampleToMldev(item);
      });
    }
    setValueByPath(toObject, ["examples", "examples"], transformedList);
  }
  return toObject;
}
function createTuningJobConfigToMldev(fromObject, parentObject) {
  const toObject = {};
  if (getValueByPath(fromObject, ["validationDataset"]) !== void 0) {
    throw new Error("validationDataset parameter is not supported in Gemini API.");
  }
  const fromTunedModelDisplayName = getValueByPath(fromObject, [
    "tunedModelDisplayName"
  ]);
  if (parentObject !== void 0 && fromTunedModelDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromTunedModelDisplayName);
  }
  if (getValueByPath(fromObject, ["description"]) !== void 0) {
    throw new Error("description parameter is not supported in Gemini API.");
  }
  const fromEpochCount = getValueByPath(fromObject, ["epochCount"]);
  if (parentObject !== void 0 && fromEpochCount != null) {
    setValueByPath(parentObject, ["tuningTask", "hyperparameters", "epochCount"], fromEpochCount);
  }
  const fromLearningRateMultiplier = getValueByPath(fromObject, [
    "learningRateMultiplier"
  ]);
  if (fromLearningRateMultiplier != null) {
    setValueByPath(toObject, ["tuningTask", "hyperparameters", "learningRateMultiplier"], fromLearningRateMultiplier);
  }
  if (getValueByPath(fromObject, ["exportLastCheckpointOnly"]) !== void 0) {
    throw new Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["preTunedModelCheckpointId"]) !== void 0) {
    throw new Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject, ["adapterSize"]) !== void 0) {
    throw new Error("adapterSize parameter is not supported in Gemini API.");
  }
  const fromBatchSize = getValueByPath(fromObject, ["batchSize"]);
  if (parentObject !== void 0 && fromBatchSize != null) {
    setValueByPath(parentObject, ["tuningTask", "hyperparameters", "batchSize"], fromBatchSize);
  }
  const fromLearningRate = getValueByPath(fromObject, ["learningRate"]);
  if (parentObject !== void 0 && fromLearningRate != null) {
    setValueByPath(parentObject, ["tuningTask", "hyperparameters", "learningRate"], fromLearningRate);
  }
  return toObject;
}
function createTuningJobParametersPrivateToMldev(fromObject) {
  const toObject = {};
  const fromBaseModel = getValueByPath(fromObject, ["baseModel"]);
  if (fromBaseModel != null) {
    setValueByPath(toObject, ["baseModel"], fromBaseModel);
  }
  const fromPreTunedModel = getValueByPath(fromObject, [
    "preTunedModel"
  ]);
  if (fromPreTunedModel != null) {
    setValueByPath(toObject, ["preTunedModel"], fromPreTunedModel);
  }
  const fromTrainingDataset = getValueByPath(fromObject, [
    "trainingDataset"
  ]);
  if (fromTrainingDataset != null) {
    setValueByPath(toObject, ["tuningTask", "trainingData"], tuningDatasetToMldev(fromTrainingDataset));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], createTuningJobConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function getTuningJobParametersToVertex(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function listTuningJobsConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  const fromFilter = getValueByPath(fromObject, ["filter"]);
  if (parentObject !== void 0 && fromFilter != null) {
    setValueByPath(parentObject, ["_query", "filter"], fromFilter);
  }
  return toObject;
}
function listTuningJobsParametersToVertex(fromObject) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], listTuningJobsConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function cancelTuningJobParametersToVertex(fromObject) {
  const toObject = {};
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function tuningDatasetToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]);
  if (parentObject !== void 0 && fromGcsUri != null) {
    setValueByPath(parentObject, ["supervisedTuningSpec", "trainingDatasetUri"], fromGcsUri);
  }
  const fromVertexDatasetResource = getValueByPath(fromObject, [
    "vertexDatasetResource"
  ]);
  if (parentObject !== void 0 && fromVertexDatasetResource != null) {
    setValueByPath(parentObject, ["supervisedTuningSpec", "trainingDatasetUri"], fromVertexDatasetResource);
  }
  if (getValueByPath(fromObject, ["examples"]) !== void 0) {
    throw new Error("examples parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function tuningValidationDatasetToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["validationDatasetUri"], fromGcsUri);
  }
  const fromVertexDatasetResource = getValueByPath(fromObject, [
    "vertexDatasetResource"
  ]);
  if (parentObject !== void 0 && fromVertexDatasetResource != null) {
    setValueByPath(parentObject, ["supervisedTuningSpec", "trainingDatasetUri"], fromVertexDatasetResource);
  }
  return toObject;
}
function createTuningJobConfigToVertex(fromObject, parentObject) {
  const toObject = {};
  const fromValidationDataset = getValueByPath(fromObject, [
    "validationDataset"
  ]);
  if (parentObject !== void 0 && fromValidationDataset != null) {
    setValueByPath(parentObject, ["supervisedTuningSpec"], tuningValidationDatasetToVertex(fromValidationDataset, toObject));
  }
  const fromTunedModelDisplayName = getValueByPath(fromObject, [
    "tunedModelDisplayName"
  ]);
  if (parentObject !== void 0 && fromTunedModelDisplayName != null) {
    setValueByPath(parentObject, ["tunedModelDisplayName"], fromTunedModelDisplayName);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (parentObject !== void 0 && fromDescription != null) {
    setValueByPath(parentObject, ["description"], fromDescription);
  }
  const fromEpochCount = getValueByPath(fromObject, ["epochCount"]);
  if (parentObject !== void 0 && fromEpochCount != null) {
    setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "epochCount"], fromEpochCount);
  }
  const fromLearningRateMultiplier = getValueByPath(fromObject, [
    "learningRateMultiplier"
  ]);
  if (parentObject !== void 0 && fromLearningRateMultiplier != null) {
    setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "learningRateMultiplier"], fromLearningRateMultiplier);
  }
  const fromExportLastCheckpointOnly = getValueByPath(fromObject, [
    "exportLastCheckpointOnly"
  ]);
  if (parentObject !== void 0 && fromExportLastCheckpointOnly != null) {
    setValueByPath(parentObject, ["supervisedTuningSpec", "exportLastCheckpointOnly"], fromExportLastCheckpointOnly);
  }
  const fromPreTunedModelCheckpointId = getValueByPath(fromObject, [
    "preTunedModelCheckpointId"
  ]);
  if (fromPreTunedModelCheckpointId != null) {
    setValueByPath(toObject, ["preTunedModel", "checkpointId"], fromPreTunedModelCheckpointId);
  }
  const fromAdapterSize = getValueByPath(fromObject, ["adapterSize"]);
  if (parentObject !== void 0 && fromAdapterSize != null) {
    setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "adapterSize"], fromAdapterSize);
  }
  if (getValueByPath(fromObject, ["batchSize"]) !== void 0) {
    throw new Error("batchSize parameter is not supported in Vertex AI.");
  }
  if (getValueByPath(fromObject, ["learningRate"]) !== void 0) {
    throw new Error("learningRate parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function createTuningJobParametersPrivateToVertex(fromObject) {
  const toObject = {};
  const fromBaseModel = getValueByPath(fromObject, ["baseModel"]);
  if (fromBaseModel != null) {
    setValueByPath(toObject, ["baseModel"], fromBaseModel);
  }
  const fromPreTunedModel = getValueByPath(fromObject, [
    "preTunedModel"
  ]);
  if (fromPreTunedModel != null) {
    setValueByPath(toObject, ["preTunedModel"], fromPreTunedModel);
  }
  const fromTrainingDataset = getValueByPath(fromObject, [
    "trainingDataset"
  ]);
  if (fromTrainingDataset != null) {
    setValueByPath(toObject, ["supervisedTuningSpec", "trainingDatasetUri"], tuningDatasetToVertex(fromTrainingDataset, toObject));
  }
  const fromConfig = getValueByPath(fromObject, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], createTuningJobConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function tunedModelFromMldev(fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["name"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], fromModel);
  }
  const fromEndpoint = getValueByPath(fromObject, ["name"]);
  if (fromEndpoint != null) {
    setValueByPath(toObject, ["endpoint"], fromEndpoint);
  }
  return toObject;
}
function tuningJobFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromState = getValueByPath(fromObject, ["state"]);
  if (fromState != null) {
    setValueByPath(toObject, ["state"], tTuningJobStatus(fromState));
  }
  const fromCreateTime = getValueByPath(fromObject, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromStartTime = getValueByPath(fromObject, [
    "tuningTask",
    "startTime"
  ]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject, [
    "tuningTask",
    "completeTime"
  ]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromBaseModel = getValueByPath(fromObject, ["baseModel"]);
  if (fromBaseModel != null) {
    setValueByPath(toObject, ["baseModel"], fromBaseModel);
  }
  const fromTunedModel = getValueByPath(fromObject, ["_self"]);
  if (fromTunedModel != null) {
    setValueByPath(toObject, ["tunedModel"], tunedModelFromMldev(fromTunedModel));
  }
  const fromCustomBaseModel = getValueByPath(fromObject, [
    "customBaseModel"
  ]);
  if (fromCustomBaseModel != null) {
    setValueByPath(toObject, ["customBaseModel"], fromCustomBaseModel);
  }
  const fromExperiment = getValueByPath(fromObject, ["experiment"]);
  if (fromExperiment != null) {
    setValueByPath(toObject, ["experiment"], fromExperiment);
  }
  const fromLabels = getValueByPath(fromObject, ["labels"]);
  if (fromLabels != null) {
    setValueByPath(toObject, ["labels"], fromLabels);
  }
  const fromOutputUri = getValueByPath(fromObject, ["outputUri"]);
  if (fromOutputUri != null) {
    setValueByPath(toObject, ["outputUri"], fromOutputUri);
  }
  const fromPipelineJob = getValueByPath(fromObject, ["pipelineJob"]);
  if (fromPipelineJob != null) {
    setValueByPath(toObject, ["pipelineJob"], fromPipelineJob);
  }
  const fromServiceAccount = getValueByPath(fromObject, [
    "serviceAccount"
  ]);
  if (fromServiceAccount != null) {
    setValueByPath(toObject, ["serviceAccount"], fromServiceAccount);
  }
  const fromTunedModelDisplayName = getValueByPath(fromObject, [
    "tunedModelDisplayName"
  ]);
  if (fromTunedModelDisplayName != null) {
    setValueByPath(toObject, ["tunedModelDisplayName"], fromTunedModelDisplayName);
  }
  return toObject;
}
function listTuningJobsResponseFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromTuningJobs = getValueByPath(fromObject, ["tunedModels"]);
  if (fromTuningJobs != null) {
    let transformedList = fromTuningJobs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return tuningJobFromMldev(item);
      });
    }
    setValueByPath(toObject, ["tuningJobs"], transformedList);
  }
  return toObject;
}
function tuningOperationFromMldev(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromMetadata = getValueByPath(fromObject, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromDone = getValueByPath(fromObject, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  return toObject;
}
function tunedModelCheckpointFromVertex(fromObject) {
  const toObject = {};
  const fromCheckpointId = getValueByPath(fromObject, ["checkpointId"]);
  if (fromCheckpointId != null) {
    setValueByPath(toObject, ["checkpointId"], fromCheckpointId);
  }
  const fromEpoch = getValueByPath(fromObject, ["epoch"]);
  if (fromEpoch != null) {
    setValueByPath(toObject, ["epoch"], fromEpoch);
  }
  const fromStep = getValueByPath(fromObject, ["step"]);
  if (fromStep != null) {
    setValueByPath(toObject, ["step"], fromStep);
  }
  const fromEndpoint = getValueByPath(fromObject, ["endpoint"]);
  if (fromEndpoint != null) {
    setValueByPath(toObject, ["endpoint"], fromEndpoint);
  }
  return toObject;
}
function tunedModelFromVertex(fromObject) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], fromModel);
  }
  const fromEndpoint = getValueByPath(fromObject, ["endpoint"]);
  if (fromEndpoint != null) {
    setValueByPath(toObject, ["endpoint"], fromEndpoint);
  }
  const fromCheckpoints = getValueByPath(fromObject, ["checkpoints"]);
  if (fromCheckpoints != null) {
    let transformedList = fromCheckpoints;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return tunedModelCheckpointFromVertex(item);
      });
    }
    setValueByPath(toObject, ["checkpoints"], transformedList);
  }
  return toObject;
}
function tuningJobFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromName = getValueByPath(fromObject, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromState = getValueByPath(fromObject, ["state"]);
  if (fromState != null) {
    setValueByPath(toObject, ["state"], tTuningJobStatus(fromState));
  }
  const fromCreateTime = getValueByPath(fromObject, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromStartTime = getValueByPath(fromObject, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromError = getValueByPath(fromObject, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  const fromDescription = getValueByPath(fromObject, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromBaseModel = getValueByPath(fromObject, ["baseModel"]);
  if (fromBaseModel != null) {
    setValueByPath(toObject, ["baseModel"], fromBaseModel);
  }
  const fromTunedModel = getValueByPath(fromObject, ["tunedModel"]);
  if (fromTunedModel != null) {
    setValueByPath(toObject, ["tunedModel"], tunedModelFromVertex(fromTunedModel));
  }
  const fromPreTunedModel = getValueByPath(fromObject, [
    "preTunedModel"
  ]);
  if (fromPreTunedModel != null) {
    setValueByPath(toObject, ["preTunedModel"], fromPreTunedModel);
  }
  const fromSupervisedTuningSpec = getValueByPath(fromObject, [
    "supervisedTuningSpec"
  ]);
  if (fromSupervisedTuningSpec != null) {
    setValueByPath(toObject, ["supervisedTuningSpec"], fromSupervisedTuningSpec);
  }
  const fromTuningDataStats = getValueByPath(fromObject, [
    "tuningDataStats"
  ]);
  if (fromTuningDataStats != null) {
    setValueByPath(toObject, ["tuningDataStats"], fromTuningDataStats);
  }
  const fromEncryptionSpec = getValueByPath(fromObject, [
    "encryptionSpec"
  ]);
  if (fromEncryptionSpec != null) {
    setValueByPath(toObject, ["encryptionSpec"], fromEncryptionSpec);
  }
  const fromPartnerModelTuningSpec = getValueByPath(fromObject, [
    "partnerModelTuningSpec"
  ]);
  if (fromPartnerModelTuningSpec != null) {
    setValueByPath(toObject, ["partnerModelTuningSpec"], fromPartnerModelTuningSpec);
  }
  const fromCustomBaseModel = getValueByPath(fromObject, [
    "customBaseModel"
  ]);
  if (fromCustomBaseModel != null) {
    setValueByPath(toObject, ["customBaseModel"], fromCustomBaseModel);
  }
  const fromExperiment = getValueByPath(fromObject, ["experiment"]);
  if (fromExperiment != null) {
    setValueByPath(toObject, ["experiment"], fromExperiment);
  }
  const fromLabels = getValueByPath(fromObject, ["labels"]);
  if (fromLabels != null) {
    setValueByPath(toObject, ["labels"], fromLabels);
  }
  const fromOutputUri = getValueByPath(fromObject, ["outputUri"]);
  if (fromOutputUri != null) {
    setValueByPath(toObject, ["outputUri"], fromOutputUri);
  }
  const fromPipelineJob = getValueByPath(fromObject, ["pipelineJob"]);
  if (fromPipelineJob != null) {
    setValueByPath(toObject, ["pipelineJob"], fromPipelineJob);
  }
  const fromServiceAccount = getValueByPath(fromObject, [
    "serviceAccount"
  ]);
  if (fromServiceAccount != null) {
    setValueByPath(toObject, ["serviceAccount"], fromServiceAccount);
  }
  const fromTunedModelDisplayName = getValueByPath(fromObject, [
    "tunedModelDisplayName"
  ]);
  if (fromTunedModelDisplayName != null) {
    setValueByPath(toObject, ["tunedModelDisplayName"], fromTunedModelDisplayName);
  }
  return toObject;
}
function listTuningJobsResponseFromVertex(fromObject) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromTuningJobs = getValueByPath(fromObject, ["tuningJobs"]);
  if (fromTuningJobs != null) {
    let transformedList = fromTuningJobs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return tuningJobFromVertex(item);
      });
    }
    setValueByPath(toObject, ["tuningJobs"], transformedList);
  }
  return toObject;
}
async function uploadBlob(file, uploadUrl, apiClient) {
  var _a6, _b2, _c2;
  let fileSize = 0;
  let offset = 0;
  let response = new HttpResponse(new Response());
  let uploadCommand = "upload";
  fileSize = file.size;
  while (offset < fileSize) {
    const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);
    const chunk = file.slice(offset, offset + chunkSize);
    if (offset + chunkSize >= fileSize) {
      uploadCommand += ", finalize";
    }
    let retryCount = 0;
    let currentDelayMs = INITIAL_RETRY_DELAY_MS;
    while (retryCount < MAX_RETRY_COUNT) {
      response = await apiClient.request({
        path: "",
        body: chunk,
        httpMethod: "POST",
        httpOptions: {
          apiVersion: "",
          baseUrl: uploadUrl,
          headers: {
            "X-Goog-Upload-Command": uploadCommand,
            "X-Goog-Upload-Offset": String(offset),
            "Content-Length": String(chunkSize)
          }
        }
      });
      if ((_a6 = response === null || response === void 0 ? void 0 : response.headers) === null || _a6 === void 0 ? void 0 : _a6[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {
        break;
      }
      retryCount++;
      await sleep(currentDelayMs);
      currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;
    }
    offset += chunkSize;
    if (((_b2 = response === null || response === void 0 ? void 0 : response.headers) === null || _b2 === void 0 ? void 0 : _b2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "active") {
      break;
    }
    if (fileSize <= offset) {
      throw new Error("All content has been uploaded, but the upload status is not finalized.");
    }
  }
  const responseJson = await (response === null || response === void 0 ? void 0 : response.json());
  if (((_c2 = response === null || response === void 0 ? void 0 : response.headers) === null || _c2 === void 0 ? void 0 : _c2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "final") {
    throw new Error("Failed to upload file: Upload status is not finalized.");
  }
  return responseJson["file"];
}
async function getBlobStat(file) {
  const fileStat = { size: file.size, type: file.type };
  return fileStat;
}
function sleep(ms) {
  return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
}
function getEnv(env7) {
  var _a6, _b2, _c2;
  return (_c2 = (_b2 = (_a6 = process === null || process === void 0 ? void 0 : process.env) === null || _a6 === void 0 ? void 0 : _a6[env7]) === null || _b2 === void 0 ? void 0 : _b2.trim()) !== null && _c2 !== void 0 ? _c2 : void 0;
}
function getBooleanEnv(env7) {
  return stringToBoolean(getEnv(env7));
}
function stringToBoolean(str2) {
  if (str2 === void 0) {
    return false;
  }
  return str2.toLowerCase() === "true";
}
function getApiKeyFromEnv() {
  const envGoogleApiKey = getEnv("GOOGLE_API_KEY");
  const envGeminiApiKey = getEnv("GEMINI_API_KEY");
  if (envGoogleApiKey && envGeminiApiKey) {
    console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.");
  }
  return envGoogleApiKey || envGeminiApiKey || void 0;
}
var import_google_auth_library, _defaultBaseGeminiUrl, _defaultBaseVertexUrl, BaseModule, Outcome, Language, Type, HarmCategory, HarmBlockMethod, HarmBlockThreshold, Mode, AuthType, ApiSpec, UrlRetrievalStatus, FinishReason, HarmProbability, HarmSeverity, BlockedReason, TrafficType, Modality, MediaResolution, JobState, TuningMode, AdapterSize, FeatureSelectionPreference, Behavior, DynamicRetrievalConfigMode, Environment, FunctionCallingConfigMode, SafetyFilterLevel, PersonGeneration, ImagePromptLanguage, MaskReferenceMode, ControlReferenceType, SubjectReferenceType, EditMode, SegmentMode, VideoGenerationReferenceType, VideoCompressionQuality, FileState, FileSource, MediaModality, StartSensitivity, EndSensitivity, ActivityHandling, TurnCoverage, FunctionResponseScheduling, Scale, MusicGenerationMode, LiveMusicPlaybackControl, HttpResponse, GenerateContentResponse, EmbedContentResponse, GenerateImagesResponse, EditImageResponse, UpscaleImageResponse, RecontextImageResponse, SegmentImageResponse, ListModelsResponse, DeleteModelResponse, CountTokensResponse, ComputeTokensResponse, GenerateVideosResponse, GenerateVideosOperation, ListTuningJobsResponse, DeleteCachedContentResponse, ListCachedContentsResponse, ListFilesResponse, CreateFileResponse, DeleteFileResponse, ListBatchJobsResponse, LiveServerMessage, LiveMusicServerMessage, PagedItem, Pager, Batches, Caches, Chats, Chat, ApiError, Files, CONTENT_TYPE_HEADER, SERVER_TIMEOUT_HEADER, USER_AGENT_HEADER, GOOGLE_API_CLIENT_HEADER, SDK_VERSION, LIBRARY_LABEL, VERTEX_AI_API_DEFAULT_VERSION, GOOGLE_AI_API_DEFAULT_VERSION, responseLineRE, ApiClient, MCP_LABEL, hasMcpToolUsageFromMcpToTool, McpCallableTool, LiveMusic, LiveMusicSession, FUNCTION_RESPONSE_REQUIRES_ID, Live, defaultLiveSendClientContentParamerters, Session, DEFAULT_MAX_REMOTE_CALLS, Models, Operations, Tokens, GOOGLE_API_KEY_HEADER, REQUIRED_VERTEX_AI_SCOPE, NodeAuth, NodeDownloader, NodeWebSocketFactory, NodeWebSocket, Tunings, MAX_CHUNK_SIZE, MAX_RETRY_COUNT, INITIAL_RETRY_DELAY_MS, DELAY_MULTIPLIER, X_GOOG_UPLOAD_STATUS_HEADER_FIELD, NodeUploader, LANGUAGE_LABEL_PREFIX, GoogleGenAI;
var init_node = __esm({
  "node_modules/@google/genai/dist/node/index.mjs"() {
    init_esbuild_shims();
    import_google_auth_library = __toESM(require_src6(), 1);
    init_wrapper();
    _defaultBaseGeminiUrl = void 0;
    _defaultBaseVertexUrl = void 0;
    __name(getDefaultBaseUrls, "getDefaultBaseUrls");
    __name(getBaseUrl, "getBaseUrl");
    BaseModule = class {
      static {
        __name(this, "BaseModule");
      }
    };
    __name(formatMap, "formatMap");
    __name(setValueByPath, "setValueByPath");
    __name(getValueByPath, "getValueByPath");
    __name(tBytes$1, "tBytes$1");
    (function(Outcome2) {
      Outcome2["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED";
      Outcome2["OUTCOME_OK"] = "OUTCOME_OK";
      Outcome2["OUTCOME_FAILED"] = "OUTCOME_FAILED";
      Outcome2["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED";
    })(Outcome || (Outcome = {}));
    (function(Language2) {
      Language2["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED";
      Language2["PYTHON"] = "PYTHON";
    })(Language || (Language = {}));
    (function(Type2) {
      Type2["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED";
      Type2["STRING"] = "STRING";
      Type2["NUMBER"] = "NUMBER";
      Type2["INTEGER"] = "INTEGER";
      Type2["BOOLEAN"] = "BOOLEAN";
      Type2["ARRAY"] = "ARRAY";
      Type2["OBJECT"] = "OBJECT";
      Type2["NULL"] = "NULL";
    })(Type || (Type = {}));
    (function(HarmCategory2) {
      HarmCategory2["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED";
      HarmCategory2["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH";
      HarmCategory2["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT";
      HarmCategory2["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT";
      HarmCategory2["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT";
      HarmCategory2["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY";
      HarmCategory2["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE";
      HarmCategory2["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT";
      HarmCategory2["HARM_CATEGORY_IMAGE_HARASSMENT"] = "HARM_CATEGORY_IMAGE_HARASSMENT";
      HarmCategory2["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT";
    })(HarmCategory || (HarmCategory = {}));
    (function(HarmBlockMethod2) {
      HarmBlockMethod2["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED";
      HarmBlockMethod2["SEVERITY"] = "SEVERITY";
      HarmBlockMethod2["PROBABILITY"] = "PROBABILITY";
    })(HarmBlockMethod || (HarmBlockMethod = {}));
    (function(HarmBlockThreshold2) {
      HarmBlockThreshold2["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED";
      HarmBlockThreshold2["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
      HarmBlockThreshold2["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
      HarmBlockThreshold2["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH";
      HarmBlockThreshold2["BLOCK_NONE"] = "BLOCK_NONE";
      HarmBlockThreshold2["OFF"] = "OFF";
    })(HarmBlockThreshold || (HarmBlockThreshold = {}));
    (function(Mode2) {
      Mode2["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
      Mode2["MODE_DYNAMIC"] = "MODE_DYNAMIC";
    })(Mode || (Mode = {}));
    (function(AuthType3) {
      AuthType3["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED";
      AuthType3["NO_AUTH"] = "NO_AUTH";
      AuthType3["API_KEY_AUTH"] = "API_KEY_AUTH";
      AuthType3["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH";
      AuthType3["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH";
      AuthType3["OAUTH"] = "OAUTH";
      AuthType3["OIDC_AUTH"] = "OIDC_AUTH";
    })(AuthType || (AuthType = {}));
    (function(ApiSpec2) {
      ApiSpec2["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED";
      ApiSpec2["SIMPLE_SEARCH"] = "SIMPLE_SEARCH";
      ApiSpec2["ELASTIC_SEARCH"] = "ELASTIC_SEARCH";
    })(ApiSpec || (ApiSpec = {}));
    (function(UrlRetrievalStatus2) {
      UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = "URL_RETRIEVAL_STATUS_UNSPECIFIED";
      UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_SUCCESS"] = "URL_RETRIEVAL_STATUS_SUCCESS";
      UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_ERROR"] = "URL_RETRIEVAL_STATUS_ERROR";
      UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_PAYWALL"] = "URL_RETRIEVAL_STATUS_PAYWALL";
      UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_UNSAFE"] = "URL_RETRIEVAL_STATUS_UNSAFE";
    })(UrlRetrievalStatus || (UrlRetrievalStatus = {}));
    (function(FinishReason2) {
      FinishReason2["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED";
      FinishReason2["STOP"] = "STOP";
      FinishReason2["MAX_TOKENS"] = "MAX_TOKENS";
      FinishReason2["SAFETY"] = "SAFETY";
      FinishReason2["RECITATION"] = "RECITATION";
      FinishReason2["LANGUAGE"] = "LANGUAGE";
      FinishReason2["OTHER"] = "OTHER";
      FinishReason2["BLOCKLIST"] = "BLOCKLIST";
      FinishReason2["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT";
      FinishReason2["SPII"] = "SPII";
      FinishReason2["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL";
      FinishReason2["IMAGE_SAFETY"] = "IMAGE_SAFETY";
      FinishReason2["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL";
    })(FinishReason || (FinishReason = {}));
    (function(HarmProbability2) {
      HarmProbability2["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED";
      HarmProbability2["NEGLIGIBLE"] = "NEGLIGIBLE";
      HarmProbability2["LOW"] = "LOW";
      HarmProbability2["MEDIUM"] = "MEDIUM";
      HarmProbability2["HIGH"] = "HIGH";
    })(HarmProbability || (HarmProbability = {}));
    (function(HarmSeverity2) {
      HarmSeverity2["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED";
      HarmSeverity2["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE";
      HarmSeverity2["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW";
      HarmSeverity2["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM";
      HarmSeverity2["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH";
    })(HarmSeverity || (HarmSeverity = {}));
    (function(BlockedReason2) {
      BlockedReason2["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED";
      BlockedReason2["SAFETY"] = "SAFETY";
      BlockedReason2["OTHER"] = "OTHER";
      BlockedReason2["BLOCKLIST"] = "BLOCKLIST";
      BlockedReason2["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT";
      BlockedReason2["IMAGE_SAFETY"] = "IMAGE_SAFETY";
    })(BlockedReason || (BlockedReason = {}));
    (function(TrafficType2) {
      TrafficType2["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED";
      TrafficType2["ON_DEMAND"] = "ON_DEMAND";
      TrafficType2["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT";
    })(TrafficType || (TrafficType = {}));
    (function(Modality2) {
      Modality2["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED";
      Modality2["TEXT"] = "TEXT";
      Modality2["IMAGE"] = "IMAGE";
      Modality2["AUDIO"] = "AUDIO";
    })(Modality || (Modality = {}));
    (function(MediaResolution2) {
      MediaResolution2["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED";
      MediaResolution2["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW";
      MediaResolution2["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM";
      MediaResolution2["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH";
    })(MediaResolution || (MediaResolution = {}));
    (function(JobState2) {
      JobState2["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED";
      JobState2["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED";
      JobState2["JOB_STATE_PENDING"] = "JOB_STATE_PENDING";
      JobState2["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING";
      JobState2["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED";
      JobState2["JOB_STATE_FAILED"] = "JOB_STATE_FAILED";
      JobState2["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING";
      JobState2["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED";
      JobState2["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED";
      JobState2["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED";
      JobState2["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING";
      JobState2["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED";
    })(JobState || (JobState = {}));
    (function(TuningMode2) {
      TuningMode2["TUNING_MODE_UNSPECIFIED"] = "TUNING_MODE_UNSPECIFIED";
      TuningMode2["TUNING_MODE_FULL"] = "TUNING_MODE_FULL";
      TuningMode2["TUNING_MODE_PEFT_ADAPTER"] = "TUNING_MODE_PEFT_ADAPTER";
    })(TuningMode || (TuningMode = {}));
    (function(AdapterSize2) {
      AdapterSize2["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED";
      AdapterSize2["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE";
      AdapterSize2["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO";
      AdapterSize2["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR";
      AdapterSize2["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT";
      AdapterSize2["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN";
      AdapterSize2["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO";
    })(AdapterSize || (AdapterSize = {}));
    (function(FeatureSelectionPreference2) {
      FeatureSelectionPreference2["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED";
      FeatureSelectionPreference2["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY";
      FeatureSelectionPreference2["BALANCED"] = "BALANCED";
      FeatureSelectionPreference2["PRIORITIZE_COST"] = "PRIORITIZE_COST";
    })(FeatureSelectionPreference || (FeatureSelectionPreference = {}));
    (function(Behavior2) {
      Behavior2["UNSPECIFIED"] = "UNSPECIFIED";
      Behavior2["BLOCKING"] = "BLOCKING";
      Behavior2["NON_BLOCKING"] = "NON_BLOCKING";
    })(Behavior || (Behavior = {}));
    (function(DynamicRetrievalConfigMode2) {
      DynamicRetrievalConfigMode2["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
      DynamicRetrievalConfigMode2["MODE_DYNAMIC"] = "MODE_DYNAMIC";
    })(DynamicRetrievalConfigMode || (DynamicRetrievalConfigMode = {}));
    (function(Environment2) {
      Environment2["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED";
      Environment2["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER";
    })(Environment || (Environment = {}));
    (function(FunctionCallingConfigMode2) {
      FunctionCallingConfigMode2["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
      FunctionCallingConfigMode2["AUTO"] = "AUTO";
      FunctionCallingConfigMode2["ANY"] = "ANY";
      FunctionCallingConfigMode2["NONE"] = "NONE";
      FunctionCallingConfigMode2["VALIDATED"] = "VALIDATED";
    })(FunctionCallingConfigMode || (FunctionCallingConfigMode = {}));
    (function(SafetyFilterLevel2) {
      SafetyFilterLevel2["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
      SafetyFilterLevel2["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
      SafetyFilterLevel2["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH";
      SafetyFilterLevel2["BLOCK_NONE"] = "BLOCK_NONE";
    })(SafetyFilterLevel || (SafetyFilterLevel = {}));
    (function(PersonGeneration2) {
      PersonGeneration2["DONT_ALLOW"] = "DONT_ALLOW";
      PersonGeneration2["ALLOW_ADULT"] = "ALLOW_ADULT";
      PersonGeneration2["ALLOW_ALL"] = "ALLOW_ALL";
    })(PersonGeneration || (PersonGeneration = {}));
    (function(ImagePromptLanguage2) {
      ImagePromptLanguage2["auto"] = "auto";
      ImagePromptLanguage2["en"] = "en";
      ImagePromptLanguage2["ja"] = "ja";
      ImagePromptLanguage2["ko"] = "ko";
      ImagePromptLanguage2["hi"] = "hi";
      ImagePromptLanguage2["zh"] = "zh";
      ImagePromptLanguage2["pt"] = "pt";
      ImagePromptLanguage2["es"] = "es";
    })(ImagePromptLanguage || (ImagePromptLanguage = {}));
    (function(MaskReferenceMode2) {
      MaskReferenceMode2["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT";
      MaskReferenceMode2["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED";
      MaskReferenceMode2["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND";
      MaskReferenceMode2["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND";
      MaskReferenceMode2["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC";
    })(MaskReferenceMode || (MaskReferenceMode = {}));
    (function(ControlReferenceType2) {
      ControlReferenceType2["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT";
      ControlReferenceType2["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY";
      ControlReferenceType2["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE";
      ControlReferenceType2["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH";
    })(ControlReferenceType || (ControlReferenceType = {}));
    (function(SubjectReferenceType2) {
      SubjectReferenceType2["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT";
      SubjectReferenceType2["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON";
      SubjectReferenceType2["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL";
      SubjectReferenceType2["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT";
    })(SubjectReferenceType || (SubjectReferenceType = {}));
    (function(EditMode2) {
      EditMode2["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT";
      EditMode2["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL";
      EditMode2["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION";
      EditMode2["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT";
      EditMode2["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING";
      EditMode2["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE";
      EditMode2["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP";
      EditMode2["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE";
    })(EditMode || (EditMode = {}));
    (function(SegmentMode2) {
      SegmentMode2["FOREGROUND"] = "FOREGROUND";
      SegmentMode2["BACKGROUND"] = "BACKGROUND";
      SegmentMode2["PROMPT"] = "PROMPT";
      SegmentMode2["SEMANTIC"] = "SEMANTIC";
      SegmentMode2["INTERACTIVE"] = "INTERACTIVE";
    })(SegmentMode || (SegmentMode = {}));
    (function(VideoGenerationReferenceType2) {
      VideoGenerationReferenceType2["ASSET"] = "ASSET";
      VideoGenerationReferenceType2["STYLE"] = "STYLE";
    })(VideoGenerationReferenceType || (VideoGenerationReferenceType = {}));
    (function(VideoCompressionQuality2) {
      VideoCompressionQuality2["OPTIMIZED"] = "OPTIMIZED";
      VideoCompressionQuality2["LOSSLESS"] = "LOSSLESS";
    })(VideoCompressionQuality || (VideoCompressionQuality = {}));
    (function(FileState2) {
      FileState2["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED";
      FileState2["PROCESSING"] = "PROCESSING";
      FileState2["ACTIVE"] = "ACTIVE";
      FileState2["FAILED"] = "FAILED";
    })(FileState || (FileState = {}));
    (function(FileSource2) {
      FileSource2["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED";
      FileSource2["UPLOADED"] = "UPLOADED";
      FileSource2["GENERATED"] = "GENERATED";
    })(FileSource || (FileSource = {}));
    (function(MediaModality2) {
      MediaModality2["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED";
      MediaModality2["TEXT"] = "TEXT";
      MediaModality2["IMAGE"] = "IMAGE";
      MediaModality2["VIDEO"] = "VIDEO";
      MediaModality2["AUDIO"] = "AUDIO";
      MediaModality2["DOCUMENT"] = "DOCUMENT";
    })(MediaModality || (MediaModality = {}));
    (function(StartSensitivity2) {
      StartSensitivity2["START_SENSITIVITY_UNSPECIFIED"] = "START_SENSITIVITY_UNSPECIFIED";
      StartSensitivity2["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH";
      StartSensitivity2["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW";
    })(StartSensitivity || (StartSensitivity = {}));
    (function(EndSensitivity2) {
      EndSensitivity2["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED";
      EndSensitivity2["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH";
      EndSensitivity2["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW";
    })(EndSensitivity || (EndSensitivity = {}));
    (function(ActivityHandling2) {
      ActivityHandling2["ACTIVITY_HANDLING_UNSPECIFIED"] = "ACTIVITY_HANDLING_UNSPECIFIED";
      ActivityHandling2["START_OF_ACTIVITY_INTERRUPTS"] = "START_OF_ACTIVITY_INTERRUPTS";
      ActivityHandling2["NO_INTERRUPTION"] = "NO_INTERRUPTION";
    })(ActivityHandling || (ActivityHandling = {}));
    (function(TurnCoverage2) {
      TurnCoverage2["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED";
      TurnCoverage2["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY";
      TurnCoverage2["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT";
    })(TurnCoverage || (TurnCoverage = {}));
    (function(FunctionResponseScheduling2) {
      FunctionResponseScheduling2["SCHEDULING_UNSPECIFIED"] = "SCHEDULING_UNSPECIFIED";
      FunctionResponseScheduling2["SILENT"] = "SILENT";
      FunctionResponseScheduling2["WHEN_IDLE"] = "WHEN_IDLE";
      FunctionResponseScheduling2["INTERRUPT"] = "INTERRUPT";
    })(FunctionResponseScheduling || (FunctionResponseScheduling = {}));
    (function(Scale2) {
      Scale2["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED";
      Scale2["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR";
      Scale2["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR";
      Scale2["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR";
      Scale2["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR";
      Scale2["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR";
      Scale2["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR";
      Scale2["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR";
      Scale2["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR";
      Scale2["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR";
      Scale2["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR";
      Scale2["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR";
      Scale2["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR";
    })(Scale || (Scale = {}));
    (function(MusicGenerationMode2) {
      MusicGenerationMode2["MUSIC_GENERATION_MODE_UNSPECIFIED"] = "MUSIC_GENERATION_MODE_UNSPECIFIED";
      MusicGenerationMode2["QUALITY"] = "QUALITY";
      MusicGenerationMode2["DIVERSITY"] = "DIVERSITY";
      MusicGenerationMode2["VOCALIZATION"] = "VOCALIZATION";
    })(MusicGenerationMode || (MusicGenerationMode = {}));
    (function(LiveMusicPlaybackControl2) {
      LiveMusicPlaybackControl2["PLAYBACK_CONTROL_UNSPECIFIED"] = "PLAYBACK_CONTROL_UNSPECIFIED";
      LiveMusicPlaybackControl2["PLAY"] = "PLAY";
      LiveMusicPlaybackControl2["PAUSE"] = "PAUSE";
      LiveMusicPlaybackControl2["STOP"] = "STOP";
      LiveMusicPlaybackControl2["RESET_CONTEXT"] = "RESET_CONTEXT";
    })(LiveMusicPlaybackControl || (LiveMusicPlaybackControl = {}));
    __name(createPartFromText, "createPartFromText");
    __name(_isPart, "_isPart");
    __name(_toParts, "_toParts");
    __name(createUserContent, "createUserContent");
    HttpResponse = class {
      static {
        __name(this, "HttpResponse");
      }
      constructor(response) {
        const headers = {};
        for (const pair of response.headers.entries()) {
          headers[pair[0]] = pair[1];
        }
        this.headers = headers;
        this.responseInternal = response;
      }
      json() {
        return this.responseInternal.json();
      }
    };
    GenerateContentResponse = class {
      static {
        __name(this, "GenerateContentResponse");
      }
      /**
       * Returns the concatenation of all text parts from the first candidate in the response.
       *
       * @remarks
       * If there are multiple candidates in the response, the text from the first
       * one will be returned.
       * If there are non-text parts in the response, the concatenation of all text
       * parts will be returned, and a warning will be logged.
       * If there are thought parts in the response, the concatenation of all text
       * parts excluding the thought parts will be returned.
       *
       * @example
       * ```ts
       * const response = await ai.models.generateContent({
       *   model: 'gemini-2.0-flash',
       *   contents:
       *     'Why is the sky blue?',
       * });
       *
       * console.debug(response.text);
       * ```
       */
      get text() {
        var _a6, _b2, _c2, _d, _e, _f, _g, _h;
        if (((_d = (_c2 = (_b2 = (_a6 = this.candidates) === null || _a6 === void 0 ? void 0 : _a6[0]) === null || _b2 === void 0 ? void 0 : _b2.content) === null || _c2 === void 0 ? void 0 : _c2.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) {
          return void 0;
        }
        if (this.candidates && this.candidates.length > 1) {
          console.warn("there are multiple candidates in the response, returning text from the first one.");
        }
        let text = "";
        let anyTextPartText = false;
        const nonTextParts = [];
        for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) {
          for (const [fieldName, fieldValue] of Object.entries(part)) {
            if (fieldName !== "text" && fieldName !== "thought" && (fieldValue !== null || fieldValue !== void 0)) {
              nonTextParts.push(fieldName);
            }
          }
          if (typeof part.text === "string") {
            if (typeof part.thought === "boolean" && part.thought) {
              continue;
            }
            anyTextPartText = true;
            text += part.text;
          }
        }
        if (nonTextParts.length > 0) {
          console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`);
        }
        return anyTextPartText ? text : void 0;
      }
      /**
       * Returns the concatenation of all inline data parts from the first candidate
       * in the response.
       *
       * @remarks
       * If there are multiple candidates in the response, the inline data from the
       * first one will be returned. If there are non-inline data parts in the
       * response, the concatenation of all inline data parts will be returned, and
       * a warning will be logged.
       */
      get data() {
        var _a6, _b2, _c2, _d, _e, _f, _g, _h;
        if (((_d = (_c2 = (_b2 = (_a6 = this.candidates) === null || _a6 === void 0 ? void 0 : _a6[0]) === null || _b2 === void 0 ? void 0 : _b2.content) === null || _c2 === void 0 ? void 0 : _c2.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) {
          return void 0;
        }
        if (this.candidates && this.candidates.length > 1) {
          console.warn("there are multiple candidates in the response, returning data from the first one.");
        }
        let data = "";
        const nonDataParts = [];
        for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) {
          for (const [fieldName, fieldValue] of Object.entries(part)) {
            if (fieldName !== "inlineData" && (fieldValue !== null || fieldValue !== void 0)) {
              nonDataParts.push(fieldName);
            }
          }
          if (part.inlineData && typeof part.inlineData.data === "string") {
            data += atob(part.inlineData.data);
          }
        }
        if (nonDataParts.length > 0) {
          console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`);
        }
        return data.length > 0 ? btoa(data) : void 0;
      }
      /**
       * Returns the function calls from the first candidate in the response.
       *
       * @remarks
       * If there are multiple candidates in the response, the function calls from
       * the first one will be returned.
       * If there are no function calls in the response, undefined will be returned.
       *
       * @example
       * ```ts
       * const controlLightFunctionDeclaration: FunctionDeclaration = {
       *   name: 'controlLight',
       *   parameters: {
       *   type: Type.OBJECT,
       *   description: 'Set the brightness and color temperature of a room light.',
       *   properties: {
       *     brightness: {
       *       type: Type.NUMBER,
       *       description:
       *         'Light level from 0 to 100. Zero is off and 100 is full brightness.',
       *     },
       *     colorTemperature: {
       *       type: Type.STRING,
       *       description:
       *         'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.',
       *     },
       *   },
       *   required: ['brightness', 'colorTemperature'],
       *  };
       *  const response = await ai.models.generateContent({
       *     model: 'gemini-2.0-flash',
       *     contents: 'Dim the lights so the room feels cozy and warm.',
       *     config: {
       *       tools: [{functionDeclarations: [controlLightFunctionDeclaration]}],
       *       toolConfig: {
       *         functionCallingConfig: {
       *           mode: FunctionCallingConfigMode.ANY,
       *           allowedFunctionNames: ['controlLight'],
       *         },
       *       },
       *     },
       *   });
       *  console.debug(JSON.stringify(response.functionCalls));
       * ```
       */
      get functionCalls() {
        var _a6, _b2, _c2, _d, _e, _f, _g, _h;
        if (((_d = (_c2 = (_b2 = (_a6 = this.candidates) === null || _a6 === void 0 ? void 0 : _a6[0]) === null || _b2 === void 0 ? void 0 : _b2.content) === null || _c2 === void 0 ? void 0 : _c2.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) {
          return void 0;
        }
        if (this.candidates && this.candidates.length > 1) {
          console.warn("there are multiple candidates in the response, returning function calls from the first one.");
        }
        const functionCalls = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.functionCall).map((part) => part.functionCall).filter((functionCall) => functionCall !== void 0);
        if ((functionCalls === null || functionCalls === void 0 ? void 0 : functionCalls.length) === 0) {
          return void 0;
        }
        return functionCalls;
      }
      /**
       * Returns the first executable code from the first candidate in the response.
       *
       * @remarks
       * If there are multiple candidates in the response, the executable code from
       * the first one will be returned.
       * If there are no executable code in the response, undefined will be
       * returned.
       *
       * @example
       * ```ts
       * const response = await ai.models.generateContent({
       *   model: 'gemini-2.0-flash',
       *   contents:
       *     'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'
       *   config: {
       *     tools: [{codeExecution: {}}],
       *   },
       * });
       *
       * console.debug(response.executableCode);
       * ```
       */
      get executableCode() {
        var _a6, _b2, _c2, _d, _e, _f, _g, _h, _j;
        if (((_d = (_c2 = (_b2 = (_a6 = this.candidates) === null || _a6 === void 0 ? void 0 : _a6[0]) === null || _b2 === void 0 ? void 0 : _b2.content) === null || _c2 === void 0 ? void 0 : _c2.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) {
          return void 0;
        }
        if (this.candidates && this.candidates.length > 1) {
          console.warn("there are multiple candidates in the response, returning executable code from the first one.");
        }
        const executableCode = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.executableCode).map((part) => part.executableCode).filter((executableCode2) => executableCode2 !== void 0);
        if ((executableCode === null || executableCode === void 0 ? void 0 : executableCode.length) === 0) {
          return void 0;
        }
        return (_j = executableCode === null || executableCode === void 0 ? void 0 : executableCode[0]) === null || _j === void 0 ? void 0 : _j.code;
      }
      /**
       * Returns the first code execution result from the first candidate in the response.
       *
       * @remarks
       * If there are multiple candidates in the response, the code execution result from
       * the first one will be returned.
       * If there are no code execution result in the response, undefined will be returned.
       *
       * @example
       * ```ts
       * const response = await ai.models.generateContent({
       *   model: 'gemini-2.0-flash',
       *   contents:
       *     'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'
       *   config: {
       *     tools: [{codeExecution: {}}],
       *   },
       * });
       *
       * console.debug(response.codeExecutionResult);
       * ```
       */
      get codeExecutionResult() {
        var _a6, _b2, _c2, _d, _e, _f, _g, _h, _j;
        if (((_d = (_c2 = (_b2 = (_a6 = this.candidates) === null || _a6 === void 0 ? void 0 : _a6[0]) === null || _b2 === void 0 ? void 0 : _b2.content) === null || _c2 === void 0 ? void 0 : _c2.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) {
          return void 0;
        }
        if (this.candidates && this.candidates.length > 1) {
          console.warn("there are multiple candidates in the response, returning code execution result from the first one.");
        }
        const codeExecutionResult = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.codeExecutionResult).map((part) => part.codeExecutionResult).filter((codeExecutionResult2) => codeExecutionResult2 !== void 0);
        if ((codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult.length) === 0) {
          return void 0;
        }
        return (_j = codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult[0]) === null || _j === void 0 ? void 0 : _j.output;
      }
    };
    EmbedContentResponse = class {
      static {
        __name(this, "EmbedContentResponse");
      }
    };
    GenerateImagesResponse = class {
      static {
        __name(this, "GenerateImagesResponse");
      }
    };
    EditImageResponse = class {
      static {
        __name(this, "EditImageResponse");
      }
    };
    UpscaleImageResponse = class {
      static {
        __name(this, "UpscaleImageResponse");
      }
    };
    RecontextImageResponse = class {
      static {
        __name(this, "RecontextImageResponse");
      }
    };
    SegmentImageResponse = class {
      static {
        __name(this, "SegmentImageResponse");
      }
    };
    ListModelsResponse = class {
      static {
        __name(this, "ListModelsResponse");
      }
    };
    DeleteModelResponse = class {
      static {
        __name(this, "DeleteModelResponse");
      }
    };
    CountTokensResponse = class {
      static {
        __name(this, "CountTokensResponse");
      }
    };
    ComputeTokensResponse = class {
      static {
        __name(this, "ComputeTokensResponse");
      }
    };
    GenerateVideosResponse = class {
      static {
        __name(this, "GenerateVideosResponse");
      }
    };
    GenerateVideosOperation = class _GenerateVideosOperation {
      static {
        __name(this, "GenerateVideosOperation");
      }
      /**
       * Instantiates an Operation of the same type as the one being called with the fields set from the API response.
       * @internal
       */
      _fromAPIResponse({ apiResponse, isVertexAI }) {
        const operation = new _GenerateVideosOperation();
        operation.name = apiResponse["name"];
        operation.metadata = apiResponse["metadata"];
        operation.done = apiResponse["done"];
        operation.error = apiResponse["error"];
        if (isVertexAI) {
          const response = apiResponse["response"];
          if (response) {
            const operationResponse = new GenerateVideosResponse();
            const responseVideos = response["videos"];
            operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => {
              return {
                video: {
                  uri: generatedVideo["gcsUri"],
                  videoBytes: generatedVideo["bytesBase64Encoded"] ? tBytes$1(generatedVideo["bytesBase64Encoded"]) : void 0,
                  mimeType: generatedVideo["mimeType"]
                }
              };
            });
            operationResponse.raiMediaFilteredCount = response["raiMediaFilteredCount"];
            operationResponse.raiMediaFilteredReasons = response["raiMediaFilteredReasons"];
            operation.response = operationResponse;
          }
        } else {
          const response = apiResponse["response"];
          if (response) {
            const operationResponse = new GenerateVideosResponse();
            const generatedVideoResponse = response["generateVideoResponse"];
            const responseVideos = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse["generatedSamples"];
            operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => {
              const video = generatedVideo["video"];
              return {
                video: {
                  uri: video === null || video === void 0 ? void 0 : video["uri"],
                  videoBytes: (video === null || video === void 0 ? void 0 : video["encodedVideo"]) ? tBytes$1(video === null || video === void 0 ? void 0 : video["encodedVideo"]) : void 0,
                  mimeType: generatedVideo["encoding"]
                }
              };
            });
            operationResponse.raiMediaFilteredCount = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse["raiMediaFilteredCount"];
            operationResponse.raiMediaFilteredReasons = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse["raiMediaFilteredReasons"];
            operation.response = operationResponse;
          }
        }
        return operation;
      }
    };
    ListTuningJobsResponse = class {
      static {
        __name(this, "ListTuningJobsResponse");
      }
    };
    DeleteCachedContentResponse = class {
      static {
        __name(this, "DeleteCachedContentResponse");
      }
    };
    ListCachedContentsResponse = class {
      static {
        __name(this, "ListCachedContentsResponse");
      }
    };
    ListFilesResponse = class {
      static {
        __name(this, "ListFilesResponse");
      }
    };
    CreateFileResponse = class {
      static {
        __name(this, "CreateFileResponse");
      }
    };
    DeleteFileResponse = class {
      static {
        __name(this, "DeleteFileResponse");
      }
    };
    ListBatchJobsResponse = class {
      static {
        __name(this, "ListBatchJobsResponse");
      }
    };
    LiveServerMessage = class {
      static {
        __name(this, "LiveServerMessage");
      }
      /**
       * Returns the concatenation of all text parts from the server content if present.
       *
       * @remarks
       * If there are non-text parts in the response, the concatenation of all text
       * parts will be returned, and a warning will be logged.
       */
      get text() {
        var _a6, _b2, _c2;
        let text = "";
        let anyTextPartFound = false;
        const nonTextParts = [];
        for (const part of (_c2 = (_b2 = (_a6 = this.serverContent) === null || _a6 === void 0 ? void 0 : _a6.modelTurn) === null || _b2 === void 0 ? void 0 : _b2.parts) !== null && _c2 !== void 0 ? _c2 : []) {
          for (const [fieldName, fieldValue] of Object.entries(part)) {
            if (fieldName !== "text" && fieldName !== "thought" && fieldValue !== null) {
              nonTextParts.push(fieldName);
            }
          }
          if (typeof part.text === "string") {
            if (typeof part.thought === "boolean" && part.thought) {
              continue;
            }
            anyTextPartFound = true;
            text += part.text;
          }
        }
        if (nonTextParts.length > 0) {
          console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`);
        }
        return anyTextPartFound ? text : void 0;
      }
      /**
       * Returns the concatenation of all inline data parts from the server content if present.
       *
       * @remarks
       * If there are non-inline data parts in the
       * response, the concatenation of all inline data parts will be returned, and
       * a warning will be logged.
       */
      get data() {
        var _a6, _b2, _c2;
        let data = "";
        const nonDataParts = [];
        for (const part of (_c2 = (_b2 = (_a6 = this.serverContent) === null || _a6 === void 0 ? void 0 : _a6.modelTurn) === null || _b2 === void 0 ? void 0 : _b2.parts) !== null && _c2 !== void 0 ? _c2 : []) {
          for (const [fieldName, fieldValue] of Object.entries(part)) {
            if (fieldName !== "inlineData" && fieldValue !== null) {
              nonDataParts.push(fieldName);
            }
          }
          if (part.inlineData && typeof part.inlineData.data === "string") {
            data += atob(part.inlineData.data);
          }
        }
        if (nonDataParts.length > 0) {
          console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`);
        }
        return data.length > 0 ? btoa(data) : void 0;
      }
    };
    LiveMusicServerMessage = class {
      static {
        __name(this, "LiveMusicServerMessage");
      }
      /**
       * Returns the first audio chunk from the server content, if present.
       *
       * @remarks
       * If there are no audio chunks in the response, undefined will be returned.
       */
      get audioChunk() {
        if (this.serverContent && this.serverContent.audioChunks && this.serverContent.audioChunks.length > 0) {
          return this.serverContent.audioChunks[0];
        }
        return void 0;
      }
    };
    __name(tModel, "tModel");
    __name(tCachesModel, "tCachesModel");
    __name(tBlobs, "tBlobs");
    __name(tBlob, "tBlob");
    __name(tImageBlob, "tImageBlob");
    __name(tAudioBlob, "tAudioBlob");
    __name(tPart, "tPart");
    __name(tParts, "tParts");
    __name(_isContent, "_isContent");
    __name(_isFunctionCallPart, "_isFunctionCallPart");
    __name(_isFunctionResponsePart, "_isFunctionResponsePart");
    __name(tContent, "tContent");
    __name(tContentsForEmbed, "tContentsForEmbed");
    __name(tContents, "tContents");
    __name(flattenTypeArrayToAnyOf, "flattenTypeArrayToAnyOf");
    __name(processJsonSchema, "processJsonSchema");
    __name(tSchema, "tSchema");
    __name(tSpeechConfig, "tSpeechConfig");
    __name(tLiveSpeechConfig, "tLiveSpeechConfig");
    __name(tTool, "tTool");
    __name(tTools, "tTools");
    __name(resourceName, "resourceName");
    __name(tCachedContentName, "tCachedContentName");
    __name(tTuningJobStatus, "tTuningJobStatus");
    __name(tBytes, "tBytes");
    __name(_isFile, "_isFile");
    __name(isGeneratedVideo, "isGeneratedVideo");
    __name(isVideo, "isVideo");
    __name(tFileName, "tFileName");
    __name(tModelsUrl, "tModelsUrl");
    __name(tExtractModels, "tExtractModels");
    __name(hasField, "hasField");
    __name(mcpToGeminiTool, "mcpToGeminiTool");
    __name(mcpToolsToGeminiTool, "mcpToolsToGeminiTool");
    __name(tBatchJobSource, "tBatchJobSource");
    __name(tBatchJobDestination, "tBatchJobDestination");
    __name(tBatchJobName, "tBatchJobName");
    __name(tJobState, "tJobState");
    __name(videoMetadataToMldev$4, "videoMetadataToMldev$4");
    __name(blobToMldev$4, "blobToMldev$4");
    __name(fileDataToMldev$4, "fileDataToMldev$4");
    __name(partToMldev$4, "partToMldev$4");
    __name(contentToMldev$4, "contentToMldev$4");
    __name(schemaToMldev$1, "schemaToMldev$1");
    __name(safetySettingToMldev$1, "safetySettingToMldev$1");
    __name(functionDeclarationToMldev$4, "functionDeclarationToMldev$4");
    __name(intervalToMldev$4, "intervalToMldev$4");
    __name(googleSearchToMldev$4, "googleSearchToMldev$4");
    __name(dynamicRetrievalConfigToMldev$4, "dynamicRetrievalConfigToMldev$4");
    __name(googleSearchRetrievalToMldev$4, "googleSearchRetrievalToMldev$4");
    __name(urlContextToMldev$4, "urlContextToMldev$4");
    __name(toolComputerUseToMldev$4, "toolComputerUseToMldev$4");
    __name(toolToMldev$4, "toolToMldev$4");
    __name(functionCallingConfigToMldev$2, "functionCallingConfigToMldev$2");
    __name(latLngToMldev$2, "latLngToMldev$2");
    __name(retrievalConfigToMldev$2, "retrievalConfigToMldev$2");
    __name(toolConfigToMldev$2, "toolConfigToMldev$2");
    __name(prebuiltVoiceConfigToMldev$3, "prebuiltVoiceConfigToMldev$3");
    __name(voiceConfigToMldev$3, "voiceConfigToMldev$3");
    __name(speakerVoiceConfigToMldev$3, "speakerVoiceConfigToMldev$3");
    __name(multiSpeakerVoiceConfigToMldev$3, "multiSpeakerVoiceConfigToMldev$3");
    __name(speechConfigToMldev$3, "speechConfigToMldev$3");
    __name(thinkingConfigToMldev$1, "thinkingConfigToMldev$1");
    __name(generateContentConfigToMldev$1, "generateContentConfigToMldev$1");
    __name(inlinedRequestToMldev, "inlinedRequestToMldev");
    __name(batchJobSourceToMldev, "batchJobSourceToMldev");
    __name(createBatchJobConfigToMldev, "createBatchJobConfigToMldev");
    __name(createBatchJobParametersToMldev, "createBatchJobParametersToMldev");
    __name(getBatchJobParametersToMldev, "getBatchJobParametersToMldev");
    __name(cancelBatchJobParametersToMldev, "cancelBatchJobParametersToMldev");
    __name(listBatchJobsConfigToMldev, "listBatchJobsConfigToMldev");
    __name(listBatchJobsParametersToMldev, "listBatchJobsParametersToMldev");
    __name(deleteBatchJobParametersToMldev, "deleteBatchJobParametersToMldev");
    __name(batchJobSourceToVertex, "batchJobSourceToVertex");
    __name(batchJobDestinationToVertex, "batchJobDestinationToVertex");
    __name(createBatchJobConfigToVertex, "createBatchJobConfigToVertex");
    __name(createBatchJobParametersToVertex, "createBatchJobParametersToVertex");
    __name(getBatchJobParametersToVertex, "getBatchJobParametersToVertex");
    __name(cancelBatchJobParametersToVertex, "cancelBatchJobParametersToVertex");
    __name(listBatchJobsConfigToVertex, "listBatchJobsConfigToVertex");
    __name(listBatchJobsParametersToVertex, "listBatchJobsParametersToVertex");
    __name(deleteBatchJobParametersToVertex, "deleteBatchJobParametersToVertex");
    __name(videoMetadataFromMldev$2, "videoMetadataFromMldev$2");
    __name(blobFromMldev$2, "blobFromMldev$2");
    __name(fileDataFromMldev$2, "fileDataFromMldev$2");
    __name(partFromMldev$2, "partFromMldev$2");
    __name(contentFromMldev$2, "contentFromMldev$2");
    __name(citationMetadataFromMldev$1, "citationMetadataFromMldev$1");
    __name(urlMetadataFromMldev$2, "urlMetadataFromMldev$2");
    __name(urlContextMetadataFromMldev$2, "urlContextMetadataFromMldev$2");
    __name(candidateFromMldev$1, "candidateFromMldev$1");
    __name(generateContentResponseFromMldev$1, "generateContentResponseFromMldev$1");
    __name(jobErrorFromMldev, "jobErrorFromMldev");
    __name(inlinedResponseFromMldev, "inlinedResponseFromMldev");
    __name(batchJobDestinationFromMldev, "batchJobDestinationFromMldev");
    __name(batchJobFromMldev, "batchJobFromMldev");
    __name(listBatchJobsResponseFromMldev, "listBatchJobsResponseFromMldev");
    __name(deleteResourceJobFromMldev, "deleteResourceJobFromMldev");
    __name(jobErrorFromVertex, "jobErrorFromVertex");
    __name(batchJobSourceFromVertex, "batchJobSourceFromVertex");
    __name(batchJobDestinationFromVertex, "batchJobDestinationFromVertex");
    __name(batchJobFromVertex, "batchJobFromVertex");
    __name(listBatchJobsResponseFromVertex, "listBatchJobsResponseFromVertex");
    __name(deleteResourceJobFromVertex, "deleteResourceJobFromVertex");
    (function(PagedItem2) {
      PagedItem2["PAGED_ITEM_BATCH_JOBS"] = "batchJobs";
      PagedItem2["PAGED_ITEM_MODELS"] = "models";
      PagedItem2["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs";
      PagedItem2["PAGED_ITEM_FILES"] = "files";
      PagedItem2["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents";
    })(PagedItem || (PagedItem = {}));
    Pager = class {
      static {
        __name(this, "Pager");
      }
      constructor(name3, request4, response, params) {
        this.pageInternal = [];
        this.paramsInternal = {};
        this.requestInternal = request4;
        this.init(name3, response, params);
      }
      init(name3, response, params) {
        var _a6, _b2;
        this.nameInternal = name3;
        this.pageInternal = response[this.nameInternal] || [];
        this.sdkHttpResponseInternal = response === null || response === void 0 ? void 0 : response.sdkHttpResponse;
        this.idxInternal = 0;
        let requestParams = { config: {} };
        if (!params || Object.keys(params).length === 0) {
          requestParams = { config: {} };
        } else if (typeof params === "object") {
          requestParams = Object.assign({}, params);
        } else {
          requestParams = params;
        }
        if (requestParams["config"]) {
          requestParams["config"]["pageToken"] = response["nextPageToken"];
        }
        this.paramsInternal = requestParams;
        this.pageInternalSize = (_b2 = (_a6 = requestParams["config"]) === null || _a6 === void 0 ? void 0 : _a6["pageSize"]) !== null && _b2 !== void 0 ? _b2 : this.pageInternal.length;
      }
      initNextPage(response) {
        this.init(this.nameInternal, response, this.paramsInternal);
      }
      /**
       * Returns the current page, which is a list of items.
       *
       * @remarks
       * The first page is retrieved when the pager is created. The returned list of
       * items could be a subset of the entire list.
       */
      get page() {
        return this.pageInternal;
      }
      /**
       * Returns the type of paged item (for example, ``batch_jobs``).
       */
      get name() {
        return this.nameInternal;
      }
      /**
       * Returns the length of the page fetched each time by this pager.
       *
       * @remarks
       * The number of items in the page is less than or equal to the page length.
       */
      get pageSize() {
        return this.pageInternalSize;
      }
      /**
       * Returns the headers of the API response.
       */
      get sdkHttpResponse() {
        return this.sdkHttpResponseInternal;
      }
      /**
       * Returns the parameters when making the API request for the next page.
       *
       * @remarks
       * Parameters contain a set of optional configs that can be
       * used to customize the API request. For example, the `pageToken` parameter
       * contains the token to request the next page.
       */
      get params() {
        return this.paramsInternal;
      }
      /**
       * Returns the total number of items in the current page.
       */
      get pageLength() {
        return this.pageInternal.length;
      }
      /**
       * Returns the item at the given index.
       */
      getItem(index) {
        return this.pageInternal[index];
      }
      /**
       * Returns an async iterator that support iterating through all items
       * retrieved from the API.
       *
       * @remarks
       * The iterator will automatically fetch the next page if there are more items
       * to fetch from the API.
       *
       * @example
       *
       * ```ts
       * const pager = await ai.files.list({config: {pageSize: 10}});
       * for await (const file of pager) {
       *   console.log(file.name);
       * }
       * ```
       */
      [Symbol.asyncIterator]() {
        return {
          next: /* @__PURE__ */ __name(async () => {
            if (this.idxInternal >= this.pageLength) {
              if (this.hasNextPage()) {
                await this.nextPage();
              } else {
                return { value: void 0, done: true };
              }
            }
            const item = this.getItem(this.idxInternal);
            this.idxInternal += 1;
            return { value: item, done: false };
          }, "next"),
          return: /* @__PURE__ */ __name(async () => {
            return { value: void 0, done: true };
          }, "return")
        };
      }
      /**
       * Fetches the next page of items. This makes a new API request.
       *
       * @throws {Error} If there are no more pages to fetch.
       *
       * @example
       *
       * ```ts
       * const pager = await ai.files.list({config: {pageSize: 10}});
       * let page = pager.page;
       * while (true) {
       *   for (const file of page) {
       *     console.log(file.name);
       *   }
       *   if (!pager.hasNextPage()) {
       *     break;
       *   }
       *   page = await pager.nextPage();
       * }
       * ```
       */
      async nextPage() {
        if (!this.hasNextPage()) {
          throw new Error("No more pages to fetch.");
        }
        const response = await this.requestInternal(this.params);
        this.initNextPage(response);
        return this.page;
      }
      /**
       * Returns true if there are more pages to fetch from the API.
       */
      hasNextPage() {
        var _a6;
        if (((_a6 = this.params["config"]) === null || _a6 === void 0 ? void 0 : _a6["pageToken"]) !== void 0) {
          return true;
        }
        return false;
      }
    };
    Batches = class extends BaseModule {
      static {
        __name(this, "Batches");
      }
      constructor(apiClient) {
        super();
        this.apiClient = apiClient;
        this.create = async (params) => {
          var _a6, _b2;
          if (this.apiClient.isVertexAI()) {
            const timestamp = Date.now();
            const timestampStr = timestamp.toString();
            if (Array.isArray(params.src)) {
              throw new Error("InlinedRequest[] is not supported in Vertex AI. Please use Google Cloud Storage URI or BigQuery URI instead.");
            }
            params.config = params.config || {};
            if (params.config.displayName === void 0) {
              params.config.displayName = "genaiBatchJob_${timestampStr}";
            }
            if (params.config.dest === void 0 && typeof params.src === "string") {
              if (params.src.startsWith("gs://") && params.src.endsWith(".jsonl")) {
                params.config.dest = `${params.src.slice(0, -6)}/dest`;
              } else if (params.src.startsWith("bq://")) {
                params.config.dest = `${params.src}_dest_${timestampStr}`;
              } else {
                throw new Error("Unsupported source:" + params.src);
              }
            }
          } else {
            if (Array.isArray(params.src) || typeof params.src !== "string" && params.src.inlinedRequests) {
              let path108 = "";
              let queryParams = {};
              const body = createBatchJobParametersToMldev(this.apiClient, params);
              path108 = formatMap("{model}:batchGenerateContent", body["_url"]);
              queryParams = body["_query"];
              const batch = body["batch"];
              const inputConfig = batch["inputConfig"];
              const requestsWrapper = inputConfig["requests"];
              const requests = requestsWrapper["requests"];
              const newRequests = [];
              for (const request4 of requests) {
                const requestDict = request4;
                if (requestDict["systemInstruction"]) {
                  const systemInstructionValue = requestDict["systemInstruction"];
                  delete requestDict["systemInstruction"];
                  const requestContent = requestDict["request"];
                  requestContent["systemInstruction"] = systemInstructionValue;
                  requestDict["request"] = requestContent;
                }
                newRequests.push(requestDict);
              }
              requestsWrapper["requests"] = newRequests;
              delete body["config"];
              delete body["_url"];
              delete body["_query"];
              const response = this.apiClient.request({
                path: path108,
                queryParams,
                body: JSON.stringify(body),
                httpMethod: "POST",
                httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
                abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
              }).then((httpResponse) => {
                return httpResponse.json();
              });
              return response.then((apiResponse) => {
                const resp = batchJobFromMldev(apiResponse);
                return resp;
              });
            }
          }
          return await this.createInternal(params);
        };
        this.list = async (params = {}) => {
          return new Pager(PagedItem.PAGED_ITEM_BATCH_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params);
        };
      }
      /**
       * Internal method to create batch job.
       *
       * @param params - The parameters for create batch job request.
       * @return The created batch job.
       *
       */
      async createInternal(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = createBatchJobParametersToVertex(this.apiClient, params);
          path108 = formatMap("batchPredictionJobs", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = batchJobFromVertex(apiResponse);
            return resp;
          });
        } else {
          const body = createBatchJobParametersToMldev(this.apiClient, params);
          path108 = formatMap("{model}:batchGenerateContent", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = batchJobFromMldev(apiResponse);
            return resp;
          });
        }
      }
      /**
       * Gets batch job configurations.
       *
       * @param params - The parameters for the get request.
       * @return The batch job.
       *
       * @example
       * ```ts
       * await ai.batches.get({name: '...'}); // The server-generated resource name.
       * ```
       */
      async get(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = getBatchJobParametersToVertex(this.apiClient, params);
          path108 = formatMap("batchPredictionJobs/{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = batchJobFromVertex(apiResponse);
            return resp;
          });
        } else {
          const body = getBatchJobParametersToMldev(this.apiClient, params);
          path108 = formatMap("batches/{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = batchJobFromMldev(apiResponse);
            return resp;
          });
        }
      }
      /**
       * Cancels a batch job.
       *
       * @param params - The parameters for the cancel request.
       * @return The empty response returned by the API.
       *
       * @example
       * ```ts
       * await ai.batches.cancel({name: '...'}); // The server-generated resource name.
       * ```
       */
      async cancel(params) {
        var _a6, _b2, _c2, _d;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = cancelBatchJobParametersToVertex(this.apiClient, params);
          path108 = formatMap("batchPredictionJobs/{name}:cancel", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          await this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          });
        } else {
          const body = cancelBatchJobParametersToMldev(this.apiClient, params);
          path108 = formatMap("batches/{name}:cancel", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          await this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          });
        }
      }
      async listInternal(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = listBatchJobsParametersToVertex(params);
          path108 = formatMap("batchPredictionJobs", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = listBatchJobsResponseFromVertex(apiResponse);
            const typedResp = new ListBatchJobsResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        } else {
          const body = listBatchJobsParametersToMldev(params);
          path108 = formatMap("batches", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = listBatchJobsResponseFromMldev(apiResponse);
            const typedResp = new ListBatchJobsResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        }
      }
      /**
       * Deletes a batch job.
       *
       * @param params - The parameters for the delete request.
       * @return The empty response returned by the API.
       *
       * @example
       * ```ts
       * await ai.batches.delete({name: '...'}); // The server-generated resource name.
       * ```
       */
      async delete(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = deleteBatchJobParametersToVertex(this.apiClient, params);
          path108 = formatMap("batchPredictionJobs/{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "DELETE",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = deleteResourceJobFromVertex(apiResponse);
            return resp;
          });
        } else {
          const body = deleteBatchJobParametersToMldev(this.apiClient, params);
          path108 = formatMap("batches/{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "DELETE",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = deleteResourceJobFromMldev(apiResponse);
            return resp;
          });
        }
      }
    };
    __name(videoMetadataToMldev$3, "videoMetadataToMldev$3");
    __name(blobToMldev$3, "blobToMldev$3");
    __name(fileDataToMldev$3, "fileDataToMldev$3");
    __name(partToMldev$3, "partToMldev$3");
    __name(contentToMldev$3, "contentToMldev$3");
    __name(functionDeclarationToMldev$3, "functionDeclarationToMldev$3");
    __name(intervalToMldev$3, "intervalToMldev$3");
    __name(googleSearchToMldev$3, "googleSearchToMldev$3");
    __name(dynamicRetrievalConfigToMldev$3, "dynamicRetrievalConfigToMldev$3");
    __name(googleSearchRetrievalToMldev$3, "googleSearchRetrievalToMldev$3");
    __name(urlContextToMldev$3, "urlContextToMldev$3");
    __name(toolComputerUseToMldev$3, "toolComputerUseToMldev$3");
    __name(toolToMldev$3, "toolToMldev$3");
    __name(functionCallingConfigToMldev$1, "functionCallingConfigToMldev$1");
    __name(latLngToMldev$1, "latLngToMldev$1");
    __name(retrievalConfigToMldev$1, "retrievalConfigToMldev$1");
    __name(toolConfigToMldev$1, "toolConfigToMldev$1");
    __name(createCachedContentConfigToMldev, "createCachedContentConfigToMldev");
    __name(createCachedContentParametersToMldev, "createCachedContentParametersToMldev");
    __name(getCachedContentParametersToMldev, "getCachedContentParametersToMldev");
    __name(deleteCachedContentParametersToMldev, "deleteCachedContentParametersToMldev");
    __name(updateCachedContentConfigToMldev, "updateCachedContentConfigToMldev");
    __name(updateCachedContentParametersToMldev, "updateCachedContentParametersToMldev");
    __name(listCachedContentsConfigToMldev, "listCachedContentsConfigToMldev");
    __name(listCachedContentsParametersToMldev, "listCachedContentsParametersToMldev");
    __name(videoMetadataToVertex$2, "videoMetadataToVertex$2");
    __name(blobToVertex$2, "blobToVertex$2");
    __name(fileDataToVertex$2, "fileDataToVertex$2");
    __name(partToVertex$2, "partToVertex$2");
    __name(contentToVertex$2, "contentToVertex$2");
    __name(functionDeclarationToVertex$2, "functionDeclarationToVertex$2");
    __name(intervalToVertex$2, "intervalToVertex$2");
    __name(googleSearchToVertex$2, "googleSearchToVertex$2");
    __name(dynamicRetrievalConfigToVertex$2, "dynamicRetrievalConfigToVertex$2");
    __name(googleSearchRetrievalToVertex$2, "googleSearchRetrievalToVertex$2");
    __name(enterpriseWebSearchToVertex$2, "enterpriseWebSearchToVertex$2");
    __name(apiKeyConfigToVertex$2, "apiKeyConfigToVertex$2");
    __name(authConfigToVertex$2, "authConfigToVertex$2");
    __name(googleMapsToVertex$2, "googleMapsToVertex$2");
    __name(urlContextToVertex$2, "urlContextToVertex$2");
    __name(toolComputerUseToVertex$2, "toolComputerUseToVertex$2");
    __name(toolToVertex$2, "toolToVertex$2");
    __name(functionCallingConfigToVertex$1, "functionCallingConfigToVertex$1");
    __name(latLngToVertex$1, "latLngToVertex$1");
    __name(retrievalConfigToVertex$1, "retrievalConfigToVertex$1");
    __name(toolConfigToVertex$1, "toolConfigToVertex$1");
    __name(createCachedContentConfigToVertex, "createCachedContentConfigToVertex");
    __name(createCachedContentParametersToVertex, "createCachedContentParametersToVertex");
    __name(getCachedContentParametersToVertex, "getCachedContentParametersToVertex");
    __name(deleteCachedContentParametersToVertex, "deleteCachedContentParametersToVertex");
    __name(updateCachedContentConfigToVertex, "updateCachedContentConfigToVertex");
    __name(updateCachedContentParametersToVertex, "updateCachedContentParametersToVertex");
    __name(listCachedContentsConfigToVertex, "listCachedContentsConfigToVertex");
    __name(listCachedContentsParametersToVertex, "listCachedContentsParametersToVertex");
    __name(cachedContentFromMldev, "cachedContentFromMldev");
    __name(deleteCachedContentResponseFromMldev, "deleteCachedContentResponseFromMldev");
    __name(listCachedContentsResponseFromMldev, "listCachedContentsResponseFromMldev");
    __name(cachedContentFromVertex, "cachedContentFromVertex");
    __name(deleteCachedContentResponseFromVertex, "deleteCachedContentResponseFromVertex");
    __name(listCachedContentsResponseFromVertex, "listCachedContentsResponseFromVertex");
    Caches = class extends BaseModule {
      static {
        __name(this, "Caches");
      }
      constructor(apiClient) {
        super();
        this.apiClient = apiClient;
        this.list = async (params = {}) => {
          return new Pager(PagedItem.PAGED_ITEM_CACHED_CONTENTS, (x) => this.listInternal(x), await this.listInternal(params), params);
        };
      }
      /**
       * Creates a cached contents resource.
       *
       * @remarks
       * Context caching is only supported for specific models. See [Gemini
       * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac)
       * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models)
       * for more information.
       *
       * @param params - The parameters for the create request.
       * @return The created cached content.
       *
       * @example
       * ```ts
       * const contents = ...; // Initialize the content to cache.
       * const response = await ai.caches.create({
       *   model: 'gemini-2.0-flash-001',
       *   config: {
       *    'contents': contents,
       *    'displayName': 'test cache',
       *    'systemInstruction': 'What is the sum of the two pdfs?',
       *    'ttl': '86400s',
       *  }
       * });
       * ```
       */
      async create(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = createCachedContentParametersToVertex(this.apiClient, params);
          path108 = formatMap("cachedContents", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = cachedContentFromVertex(apiResponse);
            return resp;
          });
        } else {
          const body = createCachedContentParametersToMldev(this.apiClient, params);
          path108 = formatMap("cachedContents", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = cachedContentFromMldev(apiResponse);
            return resp;
          });
        }
      }
      /**
       * Gets cached content configurations.
       *
       * @param params - The parameters for the get request.
       * @return The cached content.
       *
       * @example
       * ```ts
       * await ai.caches.get({name: '...'}); // The server-generated resource name.
       * ```
       */
      async get(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = getCachedContentParametersToVertex(this.apiClient, params);
          path108 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = cachedContentFromVertex(apiResponse);
            return resp;
          });
        } else {
          const body = getCachedContentParametersToMldev(this.apiClient, params);
          path108 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = cachedContentFromMldev(apiResponse);
            return resp;
          });
        }
      }
      /**
       * Deletes cached content.
       *
       * @param params - The parameters for the delete request.
       * @return The empty response returned by the API.
       *
       * @example
       * ```ts
       * await ai.caches.delete({name: '...'}); // The server-generated resource name.
       * ```
       */
      async delete(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = deleteCachedContentParametersToVertex(this.apiClient, params);
          path108 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "DELETE",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = deleteCachedContentResponseFromVertex(apiResponse);
            const typedResp = new DeleteCachedContentResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        } else {
          const body = deleteCachedContentParametersToMldev(this.apiClient, params);
          path108 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "DELETE",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = deleteCachedContentResponseFromMldev(apiResponse);
            const typedResp = new DeleteCachedContentResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        }
      }
      /**
       * Updates cached content configurations.
       *
       * @param params - The parameters for the update request.
       * @return The updated cached content.
       *
       * @example
       * ```ts
       * const response = await ai.caches.update({
       *   name: '...',  // The server-generated resource name.
       *   config: {'ttl': '7600s'}
       * });
       * ```
       */
      async update(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = updateCachedContentParametersToVertex(this.apiClient, params);
          path108 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "PATCH",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = cachedContentFromVertex(apiResponse);
            return resp;
          });
        } else {
          const body = updateCachedContentParametersToMldev(this.apiClient, params);
          path108 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "PATCH",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = cachedContentFromMldev(apiResponse);
            return resp;
          });
        }
      }
      async listInternal(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = listCachedContentsParametersToVertex(params);
          path108 = formatMap("cachedContents", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = listCachedContentsResponseFromVertex(apiResponse);
            const typedResp = new ListCachedContentsResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        } else {
          const body = listCachedContentsParametersToMldev(params);
          path108 = formatMap("cachedContents", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = listCachedContentsResponseFromMldev(apiResponse);
            const typedResp = new ListCachedContentsResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        }
      }
    };
    __name(__values, "__values");
    __name(__await, "__await");
    __name(__asyncGenerator, "__asyncGenerator");
    __name(__asyncValues, "__asyncValues");
    __name(isValidResponse, "isValidResponse");
    __name(isValidContent, "isValidContent");
    __name(validateHistory, "validateHistory");
    __name(extractCuratedHistory, "extractCuratedHistory");
    Chats = class {
      static {
        __name(this, "Chats");
      }
      constructor(modelsModule, apiClient) {
        this.modelsModule = modelsModule;
        this.apiClient = apiClient;
      }
      /**
       * Creates a new chat session.
       *
       * @remarks
       * The config in the params will be used for all requests within the chat
       * session unless overridden by a per-request `config` in
       * @see {@link types.SendMessageParameters#config}.
       *
       * @param params - Parameters for creating a chat session.
       * @returns A new chat session.
       *
       * @example
       * ```ts
       * const chat = ai.chats.create({
       *   model: 'gemini-2.0-flash'
       *   config: {
       *     temperature: 0.5,
       *     maxOutputTokens: 1024,
       *   }
       * });
       * ```
       */
      create(params) {
        return new Chat(
          this.apiClient,
          this.modelsModule,
          params.model,
          params.config,
          // Deep copy the history to avoid mutating the history outside of the
          // chat session.
          structuredClone(params.history)
        );
      }
    };
    Chat = class {
      static {
        __name(this, "Chat");
      }
      constructor(apiClient, modelsModule, model, config = {}, history = []) {
        this.apiClient = apiClient;
        this.modelsModule = modelsModule;
        this.model = model;
        this.config = config;
        this.history = history;
        this.sendPromise = Promise.resolve();
        validateHistory(history);
      }
      /**
       * Sends a message to the model and returns the response.
       *
       * @remarks
       * This method will wait for the previous message to be processed before
       * sending the next message.
       *
       * @see {@link Chat#sendMessageStream} for streaming method.
       * @param params - parameters for sending messages within a chat session.
       * @returns The model's response.
       *
       * @example
       * ```ts
       * const chat = ai.chats.create({model: 'gemini-2.0-flash'});
       * const response = await chat.sendMessage({
       *   message: 'Why is the sky blue?'
       * });
       * console.log(response.text);
       * ```
       */
      async sendMessage(params) {
        var _a6;
        await this.sendPromise;
        const inputContent = tContent(params.message);
        const responsePromise = this.modelsModule.generateContent({
          model: this.model,
          contents: this.getHistory(true).concat(inputContent),
          config: (_a6 = params.config) !== null && _a6 !== void 0 ? _a6 : this.config
        });
        this.sendPromise = (async () => {
          var _a7, _b2, _c2;
          const response = await responsePromise;
          const outputContent = (_b2 = (_a7 = response.candidates) === null || _a7 === void 0 ? void 0 : _a7[0]) === null || _b2 === void 0 ? void 0 : _b2.content;
          const fullAutomaticFunctionCallingHistory = response.automaticFunctionCallingHistory;
          const index = this.getHistory(true).length;
          let automaticFunctionCallingHistory = [];
          if (fullAutomaticFunctionCallingHistory != null) {
            automaticFunctionCallingHistory = (_c2 = fullAutomaticFunctionCallingHistory.slice(index)) !== null && _c2 !== void 0 ? _c2 : [];
          }
          const modelOutput = outputContent ? [outputContent] : [];
          this.recordHistory(inputContent, modelOutput, automaticFunctionCallingHistory);
          return;
        })();
        await this.sendPromise.catch(() => {
          this.sendPromise = Promise.resolve();
        });
        return responsePromise;
      }
      /**
       * Sends a message to the model and returns the response in chunks.
       *
       * @remarks
       * This method will wait for the previous message to be processed before
       * sending the next message.
       *
       * @see {@link Chat#sendMessage} for non-streaming method.
       * @param params - parameters for sending the message.
       * @return The model's response.
       *
       * @example
       * ```ts
       * const chat = ai.chats.create({model: 'gemini-2.0-flash'});
       * const response = await chat.sendMessageStream({
       *   message: 'Why is the sky blue?'
       * });
       * for await (const chunk of response) {
       *   console.log(chunk.text);
       * }
       * ```
       */
      async sendMessageStream(params) {
        var _a6;
        await this.sendPromise;
        const inputContent = tContent(params.message);
        const streamResponse2 = this.modelsModule.generateContentStream({
          model: this.model,
          contents: this.getHistory(true).concat(inputContent),
          config: (_a6 = params.config) !== null && _a6 !== void 0 ? _a6 : this.config
        });
        this.sendPromise = streamResponse2.then(() => void 0).catch(() => void 0);
        const response = await streamResponse2;
        const result = this.processStreamResponse(response, inputContent);
        return result;
      }
      /**
       * Returns the chat history.
       *
       * @remarks
       * The history is a list of contents alternating between user and model.
       *
       * There are two types of history:
       * - The `curated history` contains only the valid turns between user and
       * model, which will be included in the subsequent requests sent to the model.
       * - The `comprehensive history` contains all turns, including invalid or
       *   empty model outputs, providing a complete record of the history.
       *
       * The history is updated after receiving the response from the model,
       * for streaming response, it means receiving the last chunk of the response.
       *
       * The `comprehensive history` is returned by default. To get the `curated
       * history`, set the `curated` parameter to `true`.
       *
       * @param curated - whether to return the curated history or the comprehensive
       *     history.
       * @return History contents alternating between user and model for the entire
       *     chat session.
       */
      getHistory(curated = false) {
        const history = curated ? extractCuratedHistory(this.history) : this.history;
        return structuredClone(history);
      }
      processStreamResponse(streamResponse2, inputContent) {
        var _a6, _b2;
        return __asyncGenerator(this, arguments, /* @__PURE__ */ __name(function* processStreamResponse_1() {
          var _c2, e_1, _d, _e;
          const outputContent = [];
          try {
            for (var _f = true, streamResponse_1 = __asyncValues(streamResponse2), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _c2 = streamResponse_1_1.done, !_c2; _f = true) {
              _e = streamResponse_1_1.value;
              _f = false;
              const chunk = _e;
              if (isValidResponse(chunk)) {
                const content = (_b2 = (_a6 = chunk.candidates) === null || _a6 === void 0 ? void 0 : _a6[0]) === null || _b2 === void 0 ? void 0 : _b2.content;
                if (content !== void 0) {
                  outputContent.push(content);
                }
              }
              yield yield __await(chunk);
            }
          } catch (e_1_1) {
            e_1 = { error: e_1_1 };
          } finally {
            try {
              if (!_f && !_c2 && (_d = streamResponse_1.return)) yield __await(_d.call(streamResponse_1));
            } finally {
              if (e_1) throw e_1.error;
            }
          }
          this.recordHistory(inputContent, outputContent);
        }, "processStreamResponse_1"));
      }
      recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) {
        let outputContents = [];
        if (modelOutput.length > 0 && modelOutput.every((content) => content.role !== void 0)) {
          outputContents = modelOutput;
        } else {
          outputContents.push({
            role: "model",
            parts: []
          });
        }
        if (automaticFunctionCallingHistory && automaticFunctionCallingHistory.length > 0) {
          this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory));
        } else {
          this.history.push(userInput);
        }
        this.history.push(...outputContents);
      }
    };
    ApiError = class _ApiError extends Error {
      static {
        __name(this, "ApiError");
      }
      constructor(options2) {
        super(options2.message);
        this.name = "ApiError";
        this.status = options2.status;
        Object.setPrototypeOf(this, _ApiError.prototype);
      }
    };
    __name(listFilesConfigToMldev, "listFilesConfigToMldev");
    __name(listFilesParametersToMldev, "listFilesParametersToMldev");
    __name(fileStatusToMldev, "fileStatusToMldev");
    __name(fileToMldev, "fileToMldev");
    __name(createFileParametersToMldev, "createFileParametersToMldev");
    __name(getFileParametersToMldev, "getFileParametersToMldev");
    __name(deleteFileParametersToMldev, "deleteFileParametersToMldev");
    __name(fileStatusFromMldev, "fileStatusFromMldev");
    __name(fileFromMldev, "fileFromMldev");
    __name(listFilesResponseFromMldev, "listFilesResponseFromMldev");
    __name(createFileResponseFromMldev, "createFileResponseFromMldev");
    __name(deleteFileResponseFromMldev, "deleteFileResponseFromMldev");
    Files = class extends BaseModule {
      static {
        __name(this, "Files");
      }
      constructor(apiClient) {
        super();
        this.apiClient = apiClient;
        this.list = async (params = {}) => {
          return new Pager(PagedItem.PAGED_ITEM_FILES, (x) => this.listInternal(x), await this.listInternal(params), params);
        };
      }
      /**
       * Uploads a file asynchronously to the Gemini API.
       * This method is not available in Vertex AI.
       * Supported upload sources:
       * - Node.js: File path (string) or Blob object.
       * - Browser: Blob object (e.g., File).
       *
       * @remarks
       * The `mimeType` can be specified in the `config` parameter. If omitted:
       *  - For file path (string) inputs, the `mimeType` will be inferred from the
       *     file extension.
       *  - For Blob object inputs, the `mimeType` will be set to the Blob's `type`
       *     property.
       * Somex eamples for file extension to mimeType mapping:
       * .txt -> text/plain
       * .json -> application/json
       * .jpg  -> image/jpeg
       * .png -> image/png
       * .mp3 -> audio/mpeg
       * .mp4 -> video/mp4
       *
       * This section can contain multiple paragraphs and code examples.
       *
       * @param params - Optional parameters specified in the
       *        `types.UploadFileParameters` interface.
       *         @see {@link types.UploadFileParameters#config} for the optional
       *         config in the parameters.
       * @return A promise that resolves to a `types.File` object.
       * @throws An error if called on a Vertex AI client.
       * @throws An error if the `mimeType` is not provided and can not be inferred,
       * the `mimeType` can be provided in the `params.config` parameter.
       * @throws An error occurs if a suitable upload location cannot be established.
       *
       * @example
       * The following code uploads a file to Gemini API.
       *
       * ```ts
       * const file = await ai.files.upload({file: 'file.txt', config: {
       *   mimeType: 'text/plain',
       * }});
       * console.log(file.name);
       * ```
       */
      async upload(params) {
        if (this.apiClient.isVertexAI()) {
          throw new Error("Vertex AI does not support uploading files. You can share files through a GCS bucket.");
        }
        return this.apiClient.uploadFile(params.file, params.config).then((response) => {
          const file = fileFromMldev(response);
          return file;
        });
      }
      /**
       * Downloads a remotely stored file asynchronously to a location specified in
       * the `params` object. This method only works on Node environment, to
       * download files in the browser, use a browser compliant method like an <a>
       * tag.
       *
       * @param params - The parameters for the download request.
       *
       * @example
       * The following code downloads an example file named "files/mehozpxf877d" as
       * "file.txt".
       *
       * ```ts
       * await ai.files.download({file: file.name, downloadPath: 'file.txt'});
       * ```
       */
      async download(params) {
        await this.apiClient.downloadFile(params);
      }
      async listInternal(params) {
        var _a6, _b2;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = listFilesParametersToMldev(params);
          path108 = formatMap("files", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = listFilesResponseFromMldev(apiResponse);
            const typedResp = new ListFilesResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        }
      }
      async createInternal(params) {
        var _a6, _b2;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = createFileParametersToMldev(params);
          path108 = formatMap("upload/v1beta/files", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = createFileResponseFromMldev(apiResponse);
            const typedResp = new CreateFileResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        }
      }
      /**
       * Retrieves the file information from the service.
       *
       * @param params - The parameters for the get request
       * @return The Promise that resolves to the types.File object requested.
       *
       * @example
       * ```ts
       * const config: GetFileParameters = {
       *   name: fileName,
       * };
       * file = await ai.files.get(config);
       * console.log(file.name);
       * ```
       */
      async get(params) {
        var _a6, _b2;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = getFileParametersToMldev(params);
          path108 = formatMap("files/{file}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = fileFromMldev(apiResponse);
            return resp;
          });
        }
      }
      /**
       * Deletes a remotely stored file.
       *
       * @param params - The parameters for the delete request.
       * @return The DeleteFileResponse, the response for the delete method.
       *
       * @example
       * The following code deletes an example file named "files/mehozpxf877d".
       *
       * ```ts
       * await ai.files.delete({name: file.name});
       * ```
       */
      async delete(params) {
        var _a6, _b2;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = deleteFileParametersToMldev(params);
          path108 = formatMap("files/{file}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "DELETE",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = deleteFileResponseFromMldev(apiResponse);
            const typedResp = new DeleteFileResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        }
      }
    };
    __name(prebuiltVoiceConfigToMldev$2, "prebuiltVoiceConfigToMldev$2");
    __name(voiceConfigToMldev$2, "voiceConfigToMldev$2");
    __name(speakerVoiceConfigToMldev$2, "speakerVoiceConfigToMldev$2");
    __name(multiSpeakerVoiceConfigToMldev$2, "multiSpeakerVoiceConfigToMldev$2");
    __name(speechConfigToMldev$2, "speechConfigToMldev$2");
    __name(videoMetadataToMldev$2, "videoMetadataToMldev$2");
    __name(blobToMldev$2, "blobToMldev$2");
    __name(fileDataToMldev$2, "fileDataToMldev$2");
    __name(partToMldev$2, "partToMldev$2");
    __name(contentToMldev$2, "contentToMldev$2");
    __name(functionDeclarationToMldev$2, "functionDeclarationToMldev$2");
    __name(intervalToMldev$2, "intervalToMldev$2");
    __name(googleSearchToMldev$2, "googleSearchToMldev$2");
    __name(dynamicRetrievalConfigToMldev$2, "dynamicRetrievalConfigToMldev$2");
    __name(googleSearchRetrievalToMldev$2, "googleSearchRetrievalToMldev$2");
    __name(urlContextToMldev$2, "urlContextToMldev$2");
    __name(toolComputerUseToMldev$2, "toolComputerUseToMldev$2");
    __name(toolToMldev$2, "toolToMldev$2");
    __name(sessionResumptionConfigToMldev$1, "sessionResumptionConfigToMldev$1");
    __name(audioTranscriptionConfigToMldev$1, "audioTranscriptionConfigToMldev$1");
    __name(automaticActivityDetectionToMldev$1, "automaticActivityDetectionToMldev$1");
    __name(realtimeInputConfigToMldev$1, "realtimeInputConfigToMldev$1");
    __name(slidingWindowToMldev$1, "slidingWindowToMldev$1");
    __name(contextWindowCompressionConfigToMldev$1, "contextWindowCompressionConfigToMldev$1");
    __name(proactivityConfigToMldev$1, "proactivityConfigToMldev$1");
    __name(liveConnectConfigToMldev$1, "liveConnectConfigToMldev$1");
    __name(liveConnectParametersToMldev, "liveConnectParametersToMldev");
    __name(activityStartToMldev, "activityStartToMldev");
    __name(activityEndToMldev, "activityEndToMldev");
    __name(liveSendRealtimeInputParametersToMldev, "liveSendRealtimeInputParametersToMldev");
    __name(weightedPromptToMldev, "weightedPromptToMldev");
    __name(liveMusicSetWeightedPromptsParametersToMldev, "liveMusicSetWeightedPromptsParametersToMldev");
    __name(liveMusicGenerationConfigToMldev, "liveMusicGenerationConfigToMldev");
    __name(liveMusicSetConfigParametersToMldev, "liveMusicSetConfigParametersToMldev");
    __name(liveMusicClientSetupToMldev, "liveMusicClientSetupToMldev");
    __name(liveMusicClientContentToMldev, "liveMusicClientContentToMldev");
    __name(liveMusicClientMessageToMldev, "liveMusicClientMessageToMldev");
    __name(prebuiltVoiceConfigToVertex$1, "prebuiltVoiceConfigToVertex$1");
    __name(voiceConfigToVertex$1, "voiceConfigToVertex$1");
    __name(speechConfigToVertex$1, "speechConfigToVertex$1");
    __name(videoMetadataToVertex$1, "videoMetadataToVertex$1");
    __name(blobToVertex$1, "blobToVertex$1");
    __name(fileDataToVertex$1, "fileDataToVertex$1");
    __name(partToVertex$1, "partToVertex$1");
    __name(contentToVertex$1, "contentToVertex$1");
    __name(functionDeclarationToVertex$1, "functionDeclarationToVertex$1");
    __name(intervalToVertex$1, "intervalToVertex$1");
    __name(googleSearchToVertex$1, "googleSearchToVertex$1");
    __name(dynamicRetrievalConfigToVertex$1, "dynamicRetrievalConfigToVertex$1");
    __name(googleSearchRetrievalToVertex$1, "googleSearchRetrievalToVertex$1");
    __name(enterpriseWebSearchToVertex$1, "enterpriseWebSearchToVertex$1");
    __name(apiKeyConfigToVertex$1, "apiKeyConfigToVertex$1");
    __name(authConfigToVertex$1, "authConfigToVertex$1");
    __name(googleMapsToVertex$1, "googleMapsToVertex$1");
    __name(urlContextToVertex$1, "urlContextToVertex$1");
    __name(toolComputerUseToVertex$1, "toolComputerUseToVertex$1");
    __name(toolToVertex$1, "toolToVertex$1");
    __name(sessionResumptionConfigToVertex, "sessionResumptionConfigToVertex");
    __name(audioTranscriptionConfigToVertex, "audioTranscriptionConfigToVertex");
    __name(automaticActivityDetectionToVertex, "automaticActivityDetectionToVertex");
    __name(realtimeInputConfigToVertex, "realtimeInputConfigToVertex");
    __name(slidingWindowToVertex, "slidingWindowToVertex");
    __name(contextWindowCompressionConfigToVertex, "contextWindowCompressionConfigToVertex");
    __name(proactivityConfigToVertex, "proactivityConfigToVertex");
    __name(liveConnectConfigToVertex, "liveConnectConfigToVertex");
    __name(liveConnectParametersToVertex, "liveConnectParametersToVertex");
    __name(activityStartToVertex, "activityStartToVertex");
    __name(activityEndToVertex, "activityEndToVertex");
    __name(liveSendRealtimeInputParametersToVertex, "liveSendRealtimeInputParametersToVertex");
    __name(liveServerSetupCompleteFromMldev, "liveServerSetupCompleteFromMldev");
    __name(videoMetadataFromMldev$1, "videoMetadataFromMldev$1");
    __name(blobFromMldev$1, "blobFromMldev$1");
    __name(fileDataFromMldev$1, "fileDataFromMldev$1");
    __name(partFromMldev$1, "partFromMldev$1");
    __name(contentFromMldev$1, "contentFromMldev$1");
    __name(transcriptionFromMldev, "transcriptionFromMldev");
    __name(urlMetadataFromMldev$1, "urlMetadataFromMldev$1");
    __name(urlContextMetadataFromMldev$1, "urlContextMetadataFromMldev$1");
    __name(liveServerContentFromMldev, "liveServerContentFromMldev");
    __name(functionCallFromMldev, "functionCallFromMldev");
    __name(liveServerToolCallFromMldev, "liveServerToolCallFromMldev");
    __name(liveServerToolCallCancellationFromMldev, "liveServerToolCallCancellationFromMldev");
    __name(modalityTokenCountFromMldev, "modalityTokenCountFromMldev");
    __name(usageMetadataFromMldev, "usageMetadataFromMldev");
    __name(liveServerGoAwayFromMldev, "liveServerGoAwayFromMldev");
    __name(liveServerSessionResumptionUpdateFromMldev, "liveServerSessionResumptionUpdateFromMldev");
    __name(liveServerMessageFromMldev, "liveServerMessageFromMldev");
    __name(liveMusicServerSetupCompleteFromMldev, "liveMusicServerSetupCompleteFromMldev");
    __name(weightedPromptFromMldev, "weightedPromptFromMldev");
    __name(liveMusicClientContentFromMldev, "liveMusicClientContentFromMldev");
    __name(liveMusicGenerationConfigFromMldev, "liveMusicGenerationConfigFromMldev");
    __name(liveMusicSourceMetadataFromMldev, "liveMusicSourceMetadataFromMldev");
    __name(audioChunkFromMldev, "audioChunkFromMldev");
    __name(liveMusicServerContentFromMldev, "liveMusicServerContentFromMldev");
    __name(liveMusicFilteredPromptFromMldev, "liveMusicFilteredPromptFromMldev");
    __name(liveMusicServerMessageFromMldev, "liveMusicServerMessageFromMldev");
    __name(liveServerSetupCompleteFromVertex, "liveServerSetupCompleteFromVertex");
    __name(videoMetadataFromVertex$1, "videoMetadataFromVertex$1");
    __name(blobFromVertex$1, "blobFromVertex$1");
    __name(fileDataFromVertex$1, "fileDataFromVertex$1");
    __name(partFromVertex$1, "partFromVertex$1");
    __name(contentFromVertex$1, "contentFromVertex$1");
    __name(transcriptionFromVertex, "transcriptionFromVertex");
    __name(liveServerContentFromVertex, "liveServerContentFromVertex");
    __name(functionCallFromVertex, "functionCallFromVertex");
    __name(liveServerToolCallFromVertex, "liveServerToolCallFromVertex");
    __name(liveServerToolCallCancellationFromVertex, "liveServerToolCallCancellationFromVertex");
    __name(modalityTokenCountFromVertex, "modalityTokenCountFromVertex");
    __name(usageMetadataFromVertex, "usageMetadataFromVertex");
    __name(liveServerGoAwayFromVertex, "liveServerGoAwayFromVertex");
    __name(liveServerSessionResumptionUpdateFromVertex, "liveServerSessionResumptionUpdateFromVertex");
    __name(liveServerMessageFromVertex, "liveServerMessageFromVertex");
    __name(videoMetadataToMldev$1, "videoMetadataToMldev$1");
    __name(blobToMldev$1, "blobToMldev$1");
    __name(fileDataToMldev$1, "fileDataToMldev$1");
    __name(partToMldev$1, "partToMldev$1");
    __name(contentToMldev$1, "contentToMldev$1");
    __name(schemaToMldev, "schemaToMldev");
    __name(safetySettingToMldev, "safetySettingToMldev");
    __name(functionDeclarationToMldev$1, "functionDeclarationToMldev$1");
    __name(intervalToMldev$1, "intervalToMldev$1");
    __name(googleSearchToMldev$1, "googleSearchToMldev$1");
    __name(dynamicRetrievalConfigToMldev$1, "dynamicRetrievalConfigToMldev$1");
    __name(googleSearchRetrievalToMldev$1, "googleSearchRetrievalToMldev$1");
    __name(urlContextToMldev$1, "urlContextToMldev$1");
    __name(toolComputerUseToMldev$1, "toolComputerUseToMldev$1");
    __name(toolToMldev$1, "toolToMldev$1");
    __name(functionCallingConfigToMldev, "functionCallingConfigToMldev");
    __name(latLngToMldev, "latLngToMldev");
    __name(retrievalConfigToMldev, "retrievalConfigToMldev");
    __name(toolConfigToMldev, "toolConfigToMldev");
    __name(prebuiltVoiceConfigToMldev$1, "prebuiltVoiceConfigToMldev$1");
    __name(voiceConfigToMldev$1, "voiceConfigToMldev$1");
    __name(speakerVoiceConfigToMldev$1, "speakerVoiceConfigToMldev$1");
    __name(multiSpeakerVoiceConfigToMldev$1, "multiSpeakerVoiceConfigToMldev$1");
    __name(speechConfigToMldev$1, "speechConfigToMldev$1");
    __name(thinkingConfigToMldev, "thinkingConfigToMldev");
    __name(generateContentConfigToMldev, "generateContentConfigToMldev");
    __name(generateContentParametersToMldev, "generateContentParametersToMldev");
    __name(embedContentConfigToMldev, "embedContentConfigToMldev");
    __name(embedContentParametersToMldev, "embedContentParametersToMldev");
    __name(generateImagesConfigToMldev, "generateImagesConfigToMldev");
    __name(generateImagesParametersToMldev, "generateImagesParametersToMldev");
    __name(getModelParametersToMldev, "getModelParametersToMldev");
    __name(listModelsConfigToMldev, "listModelsConfigToMldev");
    __name(listModelsParametersToMldev, "listModelsParametersToMldev");
    __name(updateModelConfigToMldev, "updateModelConfigToMldev");
    __name(updateModelParametersToMldev, "updateModelParametersToMldev");
    __name(deleteModelParametersToMldev, "deleteModelParametersToMldev");
    __name(countTokensConfigToMldev, "countTokensConfigToMldev");
    __name(countTokensParametersToMldev, "countTokensParametersToMldev");
    __name(imageToMldev, "imageToMldev");
    __name(generateVideosSourceToMldev, "generateVideosSourceToMldev");
    __name(generateVideosConfigToMldev, "generateVideosConfigToMldev");
    __name(generateVideosParametersToMldev, "generateVideosParametersToMldev");
    __name(videoMetadataToVertex, "videoMetadataToVertex");
    __name(blobToVertex, "blobToVertex");
    __name(fileDataToVertex, "fileDataToVertex");
    __name(partToVertex, "partToVertex");
    __name(contentToVertex, "contentToVertex");
    __name(schemaToVertex, "schemaToVertex");
    __name(modelSelectionConfigToVertex, "modelSelectionConfigToVertex");
    __name(safetySettingToVertex, "safetySettingToVertex");
    __name(functionDeclarationToVertex, "functionDeclarationToVertex");
    __name(intervalToVertex, "intervalToVertex");
    __name(googleSearchToVertex, "googleSearchToVertex");
    __name(dynamicRetrievalConfigToVertex, "dynamicRetrievalConfigToVertex");
    __name(googleSearchRetrievalToVertex, "googleSearchRetrievalToVertex");
    __name(enterpriseWebSearchToVertex, "enterpriseWebSearchToVertex");
    __name(apiKeyConfigToVertex, "apiKeyConfigToVertex");
    __name(authConfigToVertex, "authConfigToVertex");
    __name(googleMapsToVertex, "googleMapsToVertex");
    __name(urlContextToVertex, "urlContextToVertex");
    __name(toolComputerUseToVertex, "toolComputerUseToVertex");
    __name(toolToVertex, "toolToVertex");
    __name(functionCallingConfigToVertex, "functionCallingConfigToVertex");
    __name(latLngToVertex, "latLngToVertex");
    __name(retrievalConfigToVertex, "retrievalConfigToVertex");
    __name(toolConfigToVertex, "toolConfigToVertex");
    __name(prebuiltVoiceConfigToVertex, "prebuiltVoiceConfigToVertex");
    __name(voiceConfigToVertex, "voiceConfigToVertex");
    __name(speechConfigToVertex, "speechConfigToVertex");
    __name(thinkingConfigToVertex, "thinkingConfigToVertex");
    __name(generateContentConfigToVertex, "generateContentConfigToVertex");
    __name(generateContentParametersToVertex, "generateContentParametersToVertex");
    __name(embedContentConfigToVertex, "embedContentConfigToVertex");
    __name(embedContentParametersToVertex, "embedContentParametersToVertex");
    __name(generateImagesConfigToVertex, "generateImagesConfigToVertex");
    __name(generateImagesParametersToVertex, "generateImagesParametersToVertex");
    __name(imageToVertex, "imageToVertex");
    __name(maskReferenceConfigToVertex, "maskReferenceConfigToVertex");
    __name(controlReferenceConfigToVertex, "controlReferenceConfigToVertex");
    __name(styleReferenceConfigToVertex, "styleReferenceConfigToVertex");
    __name(subjectReferenceConfigToVertex, "subjectReferenceConfigToVertex");
    __name(referenceImageAPIInternalToVertex, "referenceImageAPIInternalToVertex");
    __name(editImageConfigToVertex, "editImageConfigToVertex");
    __name(editImageParametersInternalToVertex, "editImageParametersInternalToVertex");
    __name(upscaleImageAPIConfigInternalToVertex, "upscaleImageAPIConfigInternalToVertex");
    __name(upscaleImageAPIParametersInternalToVertex, "upscaleImageAPIParametersInternalToVertex");
    __name(productImageToVertex, "productImageToVertex");
    __name(recontextImageSourceToVertex, "recontextImageSourceToVertex");
    __name(recontextImageConfigToVertex, "recontextImageConfigToVertex");
    __name(recontextImageParametersToVertex, "recontextImageParametersToVertex");
    __name(scribbleImageToVertex, "scribbleImageToVertex");
    __name(segmentImageSourceToVertex, "segmentImageSourceToVertex");
    __name(segmentImageConfigToVertex, "segmentImageConfigToVertex");
    __name(segmentImageParametersToVertex, "segmentImageParametersToVertex");
    __name(getModelParametersToVertex, "getModelParametersToVertex");
    __name(listModelsConfigToVertex, "listModelsConfigToVertex");
    __name(listModelsParametersToVertex, "listModelsParametersToVertex");
    __name(updateModelConfigToVertex, "updateModelConfigToVertex");
    __name(updateModelParametersToVertex, "updateModelParametersToVertex");
    __name(deleteModelParametersToVertex, "deleteModelParametersToVertex");
    __name(countTokensConfigToVertex, "countTokensConfigToVertex");
    __name(countTokensParametersToVertex, "countTokensParametersToVertex");
    __name(computeTokensParametersToVertex, "computeTokensParametersToVertex");
    __name(videoToVertex, "videoToVertex");
    __name(generateVideosSourceToVertex, "generateVideosSourceToVertex");
    __name(videoGenerationReferenceImageToVertex, "videoGenerationReferenceImageToVertex");
    __name(generateVideosConfigToVertex, "generateVideosConfigToVertex");
    __name(generateVideosParametersToVertex, "generateVideosParametersToVertex");
    __name(videoMetadataFromMldev, "videoMetadataFromMldev");
    __name(blobFromMldev, "blobFromMldev");
    __name(fileDataFromMldev, "fileDataFromMldev");
    __name(partFromMldev, "partFromMldev");
    __name(contentFromMldev, "contentFromMldev");
    __name(citationMetadataFromMldev, "citationMetadataFromMldev");
    __name(urlMetadataFromMldev, "urlMetadataFromMldev");
    __name(urlContextMetadataFromMldev, "urlContextMetadataFromMldev");
    __name(candidateFromMldev, "candidateFromMldev");
    __name(generateContentResponseFromMldev, "generateContentResponseFromMldev");
    __name(contentEmbeddingFromMldev, "contentEmbeddingFromMldev");
    __name(embedContentMetadataFromMldev, "embedContentMetadataFromMldev");
    __name(embedContentResponseFromMldev, "embedContentResponseFromMldev");
    __name(imageFromMldev, "imageFromMldev");
    __name(safetyAttributesFromMldev, "safetyAttributesFromMldev");
    __name(generatedImageFromMldev, "generatedImageFromMldev");
    __name(generateImagesResponseFromMldev, "generateImagesResponseFromMldev");
    __name(tunedModelInfoFromMldev, "tunedModelInfoFromMldev");
    __name(modelFromMldev, "modelFromMldev");
    __name(listModelsResponseFromMldev, "listModelsResponseFromMldev");
    __name(deleteModelResponseFromMldev, "deleteModelResponseFromMldev");
    __name(countTokensResponseFromMldev, "countTokensResponseFromMldev");
    __name(videoFromMldev, "videoFromMldev");
    __name(generatedVideoFromMldev, "generatedVideoFromMldev");
    __name(generateVideosResponseFromMldev, "generateVideosResponseFromMldev");
    __name(generateVideosOperationFromMldev, "generateVideosOperationFromMldev");
    __name(videoMetadataFromVertex, "videoMetadataFromVertex");
    __name(blobFromVertex, "blobFromVertex");
    __name(fileDataFromVertex, "fileDataFromVertex");
    __name(partFromVertex, "partFromVertex");
    __name(contentFromVertex, "contentFromVertex");
    __name(citationMetadataFromVertex, "citationMetadataFromVertex");
    __name(urlMetadataFromVertex, "urlMetadataFromVertex");
    __name(urlContextMetadataFromVertex, "urlContextMetadataFromVertex");
    __name(candidateFromVertex, "candidateFromVertex");
    __name(generateContentResponseFromVertex, "generateContentResponseFromVertex");
    __name(contentEmbeddingStatisticsFromVertex, "contentEmbeddingStatisticsFromVertex");
    __name(contentEmbeddingFromVertex, "contentEmbeddingFromVertex");
    __name(embedContentMetadataFromVertex, "embedContentMetadataFromVertex");
    __name(embedContentResponseFromVertex, "embedContentResponseFromVertex");
    __name(imageFromVertex, "imageFromVertex");
    __name(safetyAttributesFromVertex, "safetyAttributesFromVertex");
    __name(generatedImageFromVertex, "generatedImageFromVertex");
    __name(generateImagesResponseFromVertex, "generateImagesResponseFromVertex");
    __name(editImageResponseFromVertex, "editImageResponseFromVertex");
    __name(upscaleImageResponseFromVertex, "upscaleImageResponseFromVertex");
    __name(recontextImageResponseFromVertex, "recontextImageResponseFromVertex");
    __name(entityLabelFromVertex, "entityLabelFromVertex");
    __name(generatedImageMaskFromVertex, "generatedImageMaskFromVertex");
    __name(segmentImageResponseFromVertex, "segmentImageResponseFromVertex");
    __name(endpointFromVertex, "endpointFromVertex");
    __name(tunedModelInfoFromVertex, "tunedModelInfoFromVertex");
    __name(checkpointFromVertex, "checkpointFromVertex");
    __name(modelFromVertex, "modelFromVertex");
    __name(listModelsResponseFromVertex, "listModelsResponseFromVertex");
    __name(deleteModelResponseFromVertex, "deleteModelResponseFromVertex");
    __name(countTokensResponseFromVertex, "countTokensResponseFromVertex");
    __name(computeTokensResponseFromVertex, "computeTokensResponseFromVertex");
    __name(videoFromVertex, "videoFromVertex");
    __name(generatedVideoFromVertex, "generatedVideoFromVertex");
    __name(generateVideosResponseFromVertex, "generateVideosResponseFromVertex");
    __name(generateVideosOperationFromVertex, "generateVideosOperationFromVertex");
    CONTENT_TYPE_HEADER = "Content-Type";
    SERVER_TIMEOUT_HEADER = "X-Server-Timeout";
    USER_AGENT_HEADER = "User-Agent";
    GOOGLE_API_CLIENT_HEADER = "x-goog-api-client";
    SDK_VERSION = "1.16.0";
    LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;
    VERTEX_AI_API_DEFAULT_VERSION = "v1beta1";
    GOOGLE_AI_API_DEFAULT_VERSION = "v1beta";
    responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/;
    ApiClient = class {
      static {
        __name(this, "ApiClient");
      }
      constructor(opts) {
        var _a6, _b2;
        this.clientOptions = Object.assign(Object.assign({}, opts), { project: opts.project, location: opts.location, apiKey: opts.apiKey, vertexai: opts.vertexai });
        const initHttpOptions = {};
        if (this.clientOptions.vertexai) {
          initHttpOptions.apiVersion = (_a6 = this.clientOptions.apiVersion) !== null && _a6 !== void 0 ? _a6 : VERTEX_AI_API_DEFAULT_VERSION;
          initHttpOptions.baseUrl = this.baseUrlFromProjectLocation();
          this.normalizeAuthParameters();
        } else {
          initHttpOptions.apiVersion = (_b2 = this.clientOptions.apiVersion) !== null && _b2 !== void 0 ? _b2 : GOOGLE_AI_API_DEFAULT_VERSION;
          initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;
        }
        initHttpOptions.headers = this.getDefaultHeaders();
        this.clientOptions.httpOptions = initHttpOptions;
        if (opts.httpOptions) {
          this.clientOptions.httpOptions = this.patchHttpOptions(initHttpOptions, opts.httpOptions);
        }
      }
      /**
       * Determines the base URL for Vertex AI based on project and location.
       * Uses the global endpoint if location is 'global' or if project/location
       * are not specified (implying API key usage).
       * @private
       */
      baseUrlFromProjectLocation() {
        if (this.clientOptions.project && this.clientOptions.location && this.clientOptions.location !== "global") {
          return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;
        }
        return `https://aiplatform.googleapis.com/`;
      }
      /**
       * Normalizes authentication parameters for Vertex AI.
       * If project and location are provided, API key is cleared.
       * If project and location are not provided (implying API key usage),
       * project and location are cleared.
       * @private
       */
      normalizeAuthParameters() {
        if (this.clientOptions.project && this.clientOptions.location) {
          this.clientOptions.apiKey = void 0;
          return;
        }
        this.clientOptions.project = void 0;
        this.clientOptions.location = void 0;
      }
      isVertexAI() {
        var _a6;
        return (_a6 = this.clientOptions.vertexai) !== null && _a6 !== void 0 ? _a6 : false;
      }
      getProject() {
        return this.clientOptions.project;
      }
      getLocation() {
        return this.clientOptions.location;
      }
      getApiVersion() {
        if (this.clientOptions.httpOptions && this.clientOptions.httpOptions.apiVersion !== void 0) {
          return this.clientOptions.httpOptions.apiVersion;
        }
        throw new Error("API version is not set.");
      }
      getBaseUrl() {
        if (this.clientOptions.httpOptions && this.clientOptions.httpOptions.baseUrl !== void 0) {
          return this.clientOptions.httpOptions.baseUrl;
        }
        throw new Error("Base URL is not set.");
      }
      getRequestUrl() {
        return this.getRequestUrlInternal(this.clientOptions.httpOptions);
      }
      getHeaders() {
        if (this.clientOptions.httpOptions && this.clientOptions.httpOptions.headers !== void 0) {
          return this.clientOptions.httpOptions.headers;
        } else {
          throw new Error("Headers are not set.");
        }
      }
      getRequestUrlInternal(httpOptions) {
        if (!httpOptions || httpOptions.baseUrl === void 0 || httpOptions.apiVersion === void 0) {
          throw new Error("HTTP options are not correctly set.");
        }
        const baseUrl = httpOptions.baseUrl.endsWith("/") ? httpOptions.baseUrl.slice(0, -1) : httpOptions.baseUrl;
        const urlElement = [baseUrl];
        if (httpOptions.apiVersion && httpOptions.apiVersion !== "") {
          urlElement.push(httpOptions.apiVersion);
        }
        return urlElement.join("/");
      }
      getBaseResourcePath() {
        return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`;
      }
      getApiKey() {
        return this.clientOptions.apiKey;
      }
      getWebsocketBaseUrl() {
        const baseUrl = this.getBaseUrl();
        const urlParts = new URL(baseUrl);
        urlParts.protocol = urlParts.protocol == "http:" ? "ws" : "wss";
        return urlParts.toString();
      }
      setBaseUrl(url2) {
        if (this.clientOptions.httpOptions) {
          this.clientOptions.httpOptions.baseUrl = url2;
        } else {
          throw new Error("HTTP options are not correctly set.");
        }
      }
      constructUrl(path108, httpOptions, prependProjectLocation) {
        const urlElement = [this.getRequestUrlInternal(httpOptions)];
        if (prependProjectLocation) {
          urlElement.push(this.getBaseResourcePath());
        }
        if (path108 !== "") {
          urlElement.push(path108);
        }
        const url2 = new URL(`${urlElement.join("/")}`);
        return url2;
      }
      shouldPrependVertexProjectPath(request4) {
        if (this.clientOptions.apiKey) {
          return false;
        }
        if (!this.clientOptions.vertexai) {
          return false;
        }
        if (request4.path.startsWith("projects/")) {
          return false;
        }
        if (request4.httpMethod === "GET" && request4.path.startsWith("publishers/google/models")) {
          return false;
        }
        return true;
      }
      async request(request4) {
        let patchedHttpOptions = this.clientOptions.httpOptions;
        if (request4.httpOptions) {
          patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request4.httpOptions);
        }
        const prependProjectLocation = this.shouldPrependVertexProjectPath(request4);
        const url2 = this.constructUrl(request4.path, patchedHttpOptions, prependProjectLocation);
        if (request4.queryParams) {
          for (const [key, value] of Object.entries(request4.queryParams)) {
            url2.searchParams.append(key, String(value));
          }
        }
        let requestInit = {};
        if (request4.httpMethod === "GET") {
          if (request4.body && request4.body !== "{}") {
            throw new Error("Request body should be empty for GET request, but got non empty request body");
          }
        } else {
          requestInit.body = request4.body;
        }
        requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request4.abortSignal);
        return this.unaryApiCall(url2, requestInit, request4.httpMethod);
      }
      patchHttpOptions(baseHttpOptions, requestHttpOptions) {
        const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions));
        for (const [key, value] of Object.entries(requestHttpOptions)) {
          if (typeof value === "object") {
            patchedHttpOptions[key] = Object.assign(Object.assign({}, patchedHttpOptions[key]), value);
          } else if (value !== void 0) {
            patchedHttpOptions[key] = value;
          }
        }
        return patchedHttpOptions;
      }
      async requestStream(request4) {
        let patchedHttpOptions = this.clientOptions.httpOptions;
        if (request4.httpOptions) {
          patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request4.httpOptions);
        }
        const prependProjectLocation = this.shouldPrependVertexProjectPath(request4);
        const url2 = this.constructUrl(request4.path, patchedHttpOptions, prependProjectLocation);
        if (!url2.searchParams.has("alt") || url2.searchParams.get("alt") !== "sse") {
          url2.searchParams.set("alt", "sse");
        }
        let requestInit = {};
        requestInit.body = request4.body;
        requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request4.abortSignal);
        return this.streamApiCall(url2, requestInit, request4.httpMethod);
      }
      async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, abortSignal) {
        if (httpOptions && httpOptions.timeout || abortSignal) {
          const abortController = new AbortController();
          const signal = abortController.signal;
          if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) {
            const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout);
            if (timeoutHandle && typeof timeoutHandle.unref === "function") {
              timeoutHandle.unref();
            }
          }
          if (abortSignal) {
            abortSignal.addEventListener("abort", () => {
              abortController.abort();
            });
          }
          requestInit.signal = signal;
        }
        if (httpOptions && httpOptions.extraBody !== null) {
          includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody);
        }
        requestInit.headers = await this.getHeadersInternal(httpOptions);
        return requestInit;
      }
      async unaryApiCall(url2, requestInit, httpMethod) {
        return this.apiCall(url2.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })).then(async (response) => {
          await throwErrorIfNotOK(response);
          return new HttpResponse(response);
        }).catch((e2) => {
          if (e2 instanceof Error) {
            throw e2;
          } else {
            throw new Error(JSON.stringify(e2));
          }
        });
      }
      async streamApiCall(url2, requestInit, httpMethod) {
        return this.apiCall(url2.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })).then(async (response) => {
          await throwErrorIfNotOK(response);
          return this.processStreamResponse(response);
        }).catch((e2) => {
          if (e2 instanceof Error) {
            throw e2;
          } else {
            throw new Error(JSON.stringify(e2));
          }
        });
      }
      processStreamResponse(response) {
        var _a6;
        return __asyncGenerator(this, arguments, /* @__PURE__ */ __name(function* processStreamResponse_1() {
          const reader = (_a6 = response === null || response === void 0 ? void 0 : response.body) === null || _a6 === void 0 ? void 0 : _a6.getReader();
          const decoder = new TextDecoder("utf-8");
          if (!reader) {
            throw new Error("Response body is empty");
          }
          try {
            let buffer = "";
            while (true) {
              const { done, value } = yield __await(reader.read());
              if (done) {
                if (buffer.trim().length > 0) {
                  throw new Error("Incomplete JSON segment at the end");
                }
                break;
              }
              const chunkString = decoder.decode(value, { stream: true });
              try {
                const chunkJson = JSON.parse(chunkString);
                if ("error" in chunkJson) {
                  const errorJson = JSON.parse(JSON.stringify(chunkJson["error"]));
                  const status = errorJson["status"];
                  const code2 = errorJson["code"];
                  const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`;
                  if (code2 >= 400 && code2 < 600) {
                    const apiError = new ApiError({
                      message: errorMessage,
                      status: code2
                    });
                    throw apiError;
                  }
                }
              } catch (e2) {
                const error = e2;
                if (error.name === "ApiError") {
                  throw e2;
                }
              }
              buffer += chunkString;
              let match2 = buffer.match(responseLineRE);
              while (match2) {
                const processedChunkString = match2[1];
                try {
                  const partialResponse = new Response(processedChunkString, {
                    headers: response === null || response === void 0 ? void 0 : response.headers,
                    status: response === null || response === void 0 ? void 0 : response.status,
                    statusText: response === null || response === void 0 ? void 0 : response.statusText
                  });
                  yield yield __await(new HttpResponse(partialResponse));
                  buffer = buffer.slice(match2[0].length);
                  match2 = buffer.match(responseLineRE);
                } catch (e2) {
                  throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e2}`);
                }
              }
            }
          } finally {
            reader.releaseLock();
          }
        }, "processStreamResponse_1"));
      }
      async apiCall(url2, requestInit) {
        return fetch(url2, requestInit).catch((e2) => {
          throw new Error(`exception ${e2} sending request`);
        });
      }
      getDefaultHeaders() {
        const headers = {};
        const versionHeaderValue = LIBRARY_LABEL + " " + this.clientOptions.userAgentExtra;
        headers[USER_AGENT_HEADER] = versionHeaderValue;
        headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;
        headers[CONTENT_TYPE_HEADER] = "application/json";
        return headers;
      }
      async getHeadersInternal(httpOptions) {
        const headers = new Headers();
        if (httpOptions && httpOptions.headers) {
          for (const [key, value] of Object.entries(httpOptions.headers)) {
            headers.append(key, value);
          }
          if (httpOptions.timeout && httpOptions.timeout > 0) {
            headers.append(SERVER_TIMEOUT_HEADER, String(Math.ceil(httpOptions.timeout / 1e3)));
          }
        }
        await this.clientOptions.auth.addAuthHeaders(headers);
        return headers;
      }
      /**
       * Uploads a file asynchronously using Gemini API only, this is not supported
       * in Vertex AI.
       *
       * @param file The string path to the file to be uploaded or a Blob object.
       * @param config Optional parameters specified in the `UploadFileConfig`
       *     interface. @see {@link UploadFileConfig}
       * @return A promise that resolves to a `File` object.
       * @throws An error if called on a Vertex AI client.
       * @throws An error if the `mimeType` is not provided and can not be inferred,
       */
      async uploadFile(file, config) {
        var _a6;
        const fileToUpload = {};
        if (config != null) {
          fileToUpload.mimeType = config.mimeType;
          fileToUpload.name = config.name;
          fileToUpload.displayName = config.displayName;
        }
        if (fileToUpload.name && !fileToUpload.name.startsWith("files/")) {
          fileToUpload.name = `files/${fileToUpload.name}`;
        }
        const uploader = this.clientOptions.uploader;
        const fileStat = await uploader.stat(file);
        fileToUpload.sizeBytes = String(fileStat.size);
        const mimeType = (_a6 = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a6 !== void 0 ? _a6 : fileStat.type;
        if (mimeType === void 0 || mimeType === "") {
          throw new Error("Can not determine mimeType. Please provide mimeType in the config.");
        }
        fileToUpload.mimeType = mimeType;
        const uploadUrl = await this.fetchUploadUrl(fileToUpload, config);
        return uploader.upload(file, uploadUrl, this);
      }
      /**
       * Downloads a file asynchronously to the specified path.
       *
       * @params params - The parameters for the download request, see {@link
       * DownloadFileParameters}
       */
      async downloadFile(params) {
        const downloader = this.clientOptions.downloader;
        await downloader.download(params, this);
      }
      async fetchUploadUrl(file, config) {
        var _a6;
        let httpOptions = {};
        if (config === null || config === void 0 ? void 0 : config.httpOptions) {
          httpOptions = config.httpOptions;
        } else {
          httpOptions = {
            apiVersion: "",
            headers: {
              "Content-Type": "application/json",
              "X-Goog-Upload-Protocol": "resumable",
              "X-Goog-Upload-Command": "start",
              "X-Goog-Upload-Header-Content-Length": `${file.sizeBytes}`,
              "X-Goog-Upload-Header-Content-Type": `${file.mimeType}`
            }
          };
        }
        const body = {
          "file": file
        };
        const httpResponse = await this.request({
          path: formatMap("upload/v1beta/files", body["_url"]),
          body: JSON.stringify(body),
          httpMethod: "POST",
          httpOptions
        });
        if (!httpResponse || !(httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers)) {
          throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");
        }
        const uploadUrl = (_a6 = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a6 === void 0 ? void 0 : _a6["x-goog-upload-url"];
        if (uploadUrl === void 0) {
          throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");
        }
        return uploadUrl;
      }
    };
    __name(throwErrorIfNotOK, "throwErrorIfNotOK");
    __name(includeExtraBodyToRequestInit, "includeExtraBodyToRequestInit");
    MCP_LABEL = "mcp_used/unknown";
    hasMcpToolUsageFromMcpToTool = false;
    __name(hasMcpToolUsage, "hasMcpToolUsage");
    __name(setMcpUsageHeader, "setMcpUsageHeader");
    __name(isMcpCallableTool, "isMcpCallableTool");
    __name(listAllTools, "listAllTools");
    McpCallableTool = class _McpCallableTool {
      static {
        __name(this, "McpCallableTool");
      }
      constructor(mcpClients = [], config) {
        this.mcpTools = [];
        this.functionNameToMcpClient = {};
        this.mcpClients = mcpClients;
        this.config = config;
      }
      /**
       * Creates a McpCallableTool.
       */
      static create(mcpClients, config) {
        return new _McpCallableTool(mcpClients, config);
      }
      /**
       * Validates the function names are not duplicate and initialize the function
       * name to MCP client mapping.
       *
       * @throws {Error} if the MCP tools from the MCP clients have duplicate tool
       *     names.
       */
      async initialize() {
        var _a6, e_1, _b2, _c2;
        if (this.mcpTools.length > 0) {
          return;
        }
        const functionMap = {};
        const mcpTools = [];
        for (const mcpClient of this.mcpClients) {
          try {
            for (var _d = true, _e = (e_1 = void 0, __asyncValues(listAllTools(mcpClient))), _f; _f = await _e.next(), _a6 = _f.done, !_a6; _d = true) {
              _c2 = _f.value;
              _d = false;
              const mcpTool = _c2;
              mcpTools.push(mcpTool);
              const mcpToolName = mcpTool.name;
              if (functionMap[mcpToolName]) {
                throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);
              }
              functionMap[mcpToolName] = mcpClient;
            }
          } catch (e_1_1) {
            e_1 = { error: e_1_1 };
          } finally {
            try {
              if (!_d && !_a6 && (_b2 = _e.return)) await _b2.call(_e);
            } finally {
              if (e_1) throw e_1.error;
            }
          }
        }
        this.mcpTools = mcpTools;
        this.functionNameToMcpClient = functionMap;
      }
      async tool() {
        await this.initialize();
        return mcpToolsToGeminiTool(this.mcpTools, this.config);
      }
      async callTool(functionCalls) {
        await this.initialize();
        const functionCallResponseParts = [];
        for (const functionCall of functionCalls) {
          if (functionCall.name in this.functionNameToMcpClient) {
            const mcpClient = this.functionNameToMcpClient[functionCall.name];
            let requestOptions = void 0;
            if (this.config.timeout) {
              requestOptions = {
                timeout: this.config.timeout
              };
            }
            const callToolResponse = await mcpClient.callTool(
              {
                name: functionCall.name,
                arguments: functionCall.args
              },
              // Set the result schema to undefined to allow MCP to rely on the
              // default schema.
              void 0,
              requestOptions
            );
            functionCallResponseParts.push({
              functionResponse: {
                name: functionCall.name,
                response: callToolResponse.isError ? { error: callToolResponse } : callToolResponse
              }
            });
          }
        }
        return functionCallResponseParts;
      }
    };
    __name(isMcpClient, "isMcpClient");
    __name(mcpToTool, "mcpToTool");
    __name(handleWebSocketMessage$1, "handleWebSocketMessage$1");
    LiveMusic = class {
      static {
        __name(this, "LiveMusic");
      }
      constructor(apiClient, auth2, webSocketFactory) {
        this.apiClient = apiClient;
        this.auth = auth2;
        this.webSocketFactory = webSocketFactory;
      }
      /**
           Establishes a connection to the specified model and returns a
           LiveMusicSession object representing that connection.
      
           @experimental
      
           @remarks
      
           @param params - The parameters for establishing a connection to the model.
           @return A live session.
      
           @example
           ```ts
           let model = 'models/lyria-realtime-exp';
           const session = await ai.live.music.connect({
             model: model,
             callbacks: {
               onmessage: (e: MessageEvent) => {
                 console.log('Received message from the server: %s\n', debug(e.data));
               },
               onerror: (e: ErrorEvent) => {
                 console.log('Error occurred: %s\n', debug(e.error));
               },
               onclose: (e: CloseEvent) => {
                 console.log('Connection closed.');
               },
             },
           });
           ```
          */
      async connect(params) {
        var _a6, _b2;
        if (this.apiClient.isVertexAI()) {
          throw new Error("Live music is not supported for Vertex AI.");
        }
        console.warn("Live music generation is experimental and may change in future versions.");
        const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();
        const apiVersion = this.apiClient.getApiVersion();
        const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders());
        const apiKey = this.apiClient.getApiKey();
        const url2 = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`;
        let onopenResolve = /* @__PURE__ */ __name(() => {
        }, "onopenResolve");
        const onopenPromise = new Promise((resolve24) => {
          onopenResolve = resolve24;
        });
        const callbacks = params.callbacks;
        const onopenAwaitedCallback = /* @__PURE__ */ __name(function() {
          onopenResolve({});
        }, "onopenAwaitedCallback");
        const apiClient = this.apiClient;
        const websocketCallbacks = {
          onopen: onopenAwaitedCallback,
          onmessage: /* @__PURE__ */ __name((event) => {
            void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event);
          }, "onmessage"),
          onerror: (_a6 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a6 !== void 0 ? _a6 : function(e2) {
          },
          onclose: (_b2 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b2 !== void 0 ? _b2 : function(e2) {
          }
        };
        const conn = this.webSocketFactory.create(url2, headersToMap$1(headers), websocketCallbacks);
        conn.connect();
        await onopenPromise;
        const model = tModel(this.apiClient, params.model);
        const setup = liveMusicClientSetupToMldev({
          model
        });
        const clientMessage = liveMusicClientMessageToMldev({ setup });
        conn.send(JSON.stringify(clientMessage));
        return new LiveMusicSession(conn, this.apiClient);
      }
    };
    LiveMusicSession = class {
      static {
        __name(this, "LiveMusicSession");
      }
      constructor(conn, apiClient) {
        this.conn = conn;
        this.apiClient = apiClient;
      }
      /**
          Sets inputs to steer music generation. Updates the session's current
          weighted prompts.
      
          @param params - Contains one property, `weightedPrompts`.
      
            - `weightedPrompts` to send to the model; weights are normalized to
              sum to 1.0.
      
          @experimental
         */
      async setWeightedPrompts(params) {
        if (!params.weightedPrompts || Object.keys(params.weightedPrompts).length === 0) {
          throw new Error("Weighted prompts must be set and contain at least one entry.");
        }
        const setWeightedPromptsParameters = liveMusicSetWeightedPromptsParametersToMldev(params);
        const clientContent = liveMusicClientContentToMldev(setWeightedPromptsParameters);
        this.conn.send(JSON.stringify({ clientContent }));
      }
      /**
          Sets a configuration to the model. Updates the session's current
          music generation config.
      
          @param params - Contains one property, `musicGenerationConfig`.
      
            - `musicGenerationConfig` to set in the model. Passing an empty or
          undefined config to the model will reset the config to defaults.
      
          @experimental
         */
      async setMusicGenerationConfig(params) {
        if (!params.musicGenerationConfig) {
          params.musicGenerationConfig = {};
        }
        const setConfigParameters = liveMusicSetConfigParametersToMldev(params);
        const clientMessage = liveMusicClientMessageToMldev(setConfigParameters);
        this.conn.send(JSON.stringify(clientMessage));
      }
      sendPlaybackControl(playbackControl) {
        const clientMessage = liveMusicClientMessageToMldev({
          playbackControl
        });
        this.conn.send(JSON.stringify(clientMessage));
      }
      /**
       * Start the music stream.
       *
       * @experimental
       */
      play() {
        this.sendPlaybackControl(LiveMusicPlaybackControl.PLAY);
      }
      /**
       * Temporarily halt the music stream. Use `play` to resume from the current
       * position.
       *
       * @experimental
       */
      pause() {
        this.sendPlaybackControl(LiveMusicPlaybackControl.PAUSE);
      }
      /**
       * Stop the music stream and reset the state. Retains the current prompts
       * and config.
       *
       * @experimental
       */
      stop() {
        this.sendPlaybackControl(LiveMusicPlaybackControl.STOP);
      }
      /**
       * Resets the context of the music generation without stopping it.
       * Retains the current prompts and config.
       *
       * @experimental
       */
      resetContext() {
        this.sendPlaybackControl(LiveMusicPlaybackControl.RESET_CONTEXT);
      }
      /**
           Terminates the WebSocket connection.
      
           @experimental
         */
      close() {
        this.conn.close();
      }
    };
    __name(headersToMap$1, "headersToMap$1");
    __name(mapToHeaders$1, "mapToHeaders$1");
    FUNCTION_RESPONSE_REQUIRES_ID = "FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";
    __name(handleWebSocketMessage, "handleWebSocketMessage");
    Live = class {
      static {
        __name(this, "Live");
      }
      constructor(apiClient, auth2, webSocketFactory) {
        this.apiClient = apiClient;
        this.auth = auth2;
        this.webSocketFactory = webSocketFactory;
        this.music = new LiveMusic(this.apiClient, this.auth, this.webSocketFactory);
      }
      /**
           Establishes a connection to the specified model with the given
           configuration and returns a Session object representing that connection.
      
           @experimental Built-in MCP support is an experimental feature, may change in
           future versions.
      
           @remarks
      
           @param params - The parameters for establishing a connection to the model.
           @return A live session.
      
           @example
           ```ts
           let model: string;
           if (GOOGLE_GENAI_USE_VERTEXAI) {
             model = 'gemini-2.0-flash-live-preview-04-09';
           } else {
             model = 'gemini-live-2.5-flash-preview';
           }
           const session = await ai.live.connect({
             model: model,
             config: {
               responseModalities: [Modality.AUDIO],
             },
             callbacks: {
               onopen: () => {
                 console.log('Connected to the socket.');
               },
               onmessage: (e: MessageEvent) => {
                 console.log('Received message from the server: %s\n', debug(e.data));
               },
               onerror: (e: ErrorEvent) => {
                 console.log('Error occurred: %s\n', debug(e.error));
               },
               onclose: (e: CloseEvent) => {
                 console.log('Connection closed.');
               },
             },
           });
           ```
          */
      async connect(params) {
        var _a6, _b2, _c2, _d, _e, _f;
        if (params.config && params.config.httpOptions) {
          throw new Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");
        }
        const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();
        const apiVersion = this.apiClient.getApiVersion();
        let url2;
        const clientHeaders = this.apiClient.getHeaders();
        if (params.config && params.config.tools && hasMcpToolUsage(params.config.tools)) {
          setMcpUsageHeader(clientHeaders);
        }
        const headers = mapToHeaders(clientHeaders);
        if (this.apiClient.isVertexAI()) {
          url2 = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`;
          await this.auth.addAuthHeaders(headers);
        } else {
          const apiKey = this.apiClient.getApiKey();
          let method = "BidiGenerateContent";
          let keyName2 = "key";
          if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith("auth_tokens/")) {
            console.warn("Warning: Ephemeral token support is experimental and may change in future versions.");
            if (apiVersion !== "v1alpha") {
              console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection.");
            }
            method = "BidiGenerateContentConstrained";
            keyName2 = "access_token";
          }
          url2 = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName2}=${apiKey}`;
        }
        let onopenResolve = /* @__PURE__ */ __name(() => {
        }, "onopenResolve");
        const onopenPromise = new Promise((resolve24) => {
          onopenResolve = resolve24;
        });
        const callbacks = params.callbacks;
        const onopenAwaitedCallback = /* @__PURE__ */ __name(function() {
          var _a7;
          (_a7 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onopen) === null || _a7 === void 0 ? void 0 : _a7.call(callbacks);
          onopenResolve({});
        }, "onopenAwaitedCallback");
        const apiClient = this.apiClient;
        const websocketCallbacks = {
          onopen: onopenAwaitedCallback,
          onmessage: /* @__PURE__ */ __name((event) => {
            void handleWebSocketMessage(apiClient, callbacks.onmessage, event);
          }, "onmessage"),
          onerror: (_a6 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a6 !== void 0 ? _a6 : function(e2) {
          },
          onclose: (_b2 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b2 !== void 0 ? _b2 : function(e2) {
          }
        };
        const conn = this.webSocketFactory.create(url2, headersToMap(headers), websocketCallbacks);
        conn.connect();
        await onopenPromise;
        let transformedModel = tModel(this.apiClient, params.model);
        if (this.apiClient.isVertexAI() && transformedModel.startsWith("publishers/")) {
          const project = this.apiClient.getProject();
          const location = this.apiClient.getLocation();
          transformedModel = `projects/${project}/locations/${location}/` + transformedModel;
        }
        let clientMessage = {};
        if (this.apiClient.isVertexAI() && ((_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.responseModalities) === void 0) {
          if (params.config === void 0) {
            params.config = { responseModalities: [Modality.AUDIO] };
          } else {
            params.config.responseModalities = [Modality.AUDIO];
          }
        }
        if ((_d = params.config) === null || _d === void 0 ? void 0 : _d.generationConfig) {
          console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).");
        }
        const inputTools = (_f = (_e = params.config) === null || _e === void 0 ? void 0 : _e.tools) !== null && _f !== void 0 ? _f : [];
        const convertedTools = [];
        for (const tool of inputTools) {
          if (this.isCallableTool(tool)) {
            const callableTool = tool;
            convertedTools.push(await callableTool.tool());
          } else {
            convertedTools.push(tool);
          }
        }
        if (convertedTools.length > 0) {
          params.config.tools = convertedTools;
        }
        const liveConnectParameters = {
          model: transformedModel,
          config: params.config,
          callbacks: params.callbacks
        };
        if (this.apiClient.isVertexAI()) {
          clientMessage = liveConnectParametersToVertex(this.apiClient, liveConnectParameters);
        } else {
          clientMessage = liveConnectParametersToMldev(this.apiClient, liveConnectParameters);
        }
        delete clientMessage["config"];
        conn.send(JSON.stringify(clientMessage));
        return new Session(conn, this.apiClient);
      }
      // TODO: b/416041229 - Abstract this method to a common place.
      isCallableTool(tool) {
        return "callTool" in tool && typeof tool.callTool === "function";
      }
    };
    defaultLiveSendClientContentParamerters = {
      turnComplete: true
    };
    Session = class {
      static {
        __name(this, "Session");
      }
      constructor(conn, apiClient) {
        this.conn = conn;
        this.apiClient = apiClient;
      }
      tLiveClientContent(apiClient, params) {
        if (params.turns !== null && params.turns !== void 0) {
          let contents = [];
          try {
            contents = tContents(params.turns);
            if (apiClient.isVertexAI()) {
              contents = contents.map((item) => contentToVertex(item));
            } else {
              contents = contents.map((item) => contentToMldev$1(item));
            }
          } catch (_a6) {
            throw new Error(`Failed to parse client content "turns", type: '${typeof params.turns}'`);
          }
          return {
            clientContent: { turns: contents, turnComplete: params.turnComplete }
          };
        }
        return {
          clientContent: { turnComplete: params.turnComplete }
        };
      }
      tLiveClienttToolResponse(apiClient, params) {
        let functionResponses = [];
        if (params.functionResponses == null) {
          throw new Error("functionResponses is required.");
        }
        if (!Array.isArray(params.functionResponses)) {
          functionResponses = [params.functionResponses];
        } else {
          functionResponses = params.functionResponses;
        }
        if (functionResponses.length === 0) {
          throw new Error("functionResponses is required.");
        }
        for (const functionResponse of functionResponses) {
          if (typeof functionResponse !== "object" || functionResponse === null || !("name" in functionResponse) || !("response" in functionResponse)) {
            throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`);
          }
          if (!apiClient.isVertexAI() && !("id" in functionResponse)) {
            throw new Error(FUNCTION_RESPONSE_REQUIRES_ID);
          }
        }
        const clientMessage = {
          toolResponse: { functionResponses }
        };
        return clientMessage;
      }
      /**
          Send a message over the established connection.
      
          @param params - Contains two **optional** properties, `turns` and
              `turnComplete`.
      
            - `turns` will be converted to a `Content[]`
            - `turnComplete: true` [default] indicates that you are done sending
              content and expect a response. If `turnComplete: false`, the server
              will wait for additional messages before starting generation.
      
          @experimental
      
          @remarks
          There are two ways to send messages to the live API:
          `sendClientContent` and `sendRealtimeInput`.
      
          `sendClientContent` messages are added to the model context **in order**.
          Having a conversation using `sendClientContent` messages is roughly
          equivalent to using the `Chat.sendMessageStream`, except that the state of
          the `chat` history is stored on the API server instead of locally.
      
          Because of `sendClientContent`'s order guarantee, the model cannot respons
          as quickly to `sendClientContent` messages as to `sendRealtimeInput`
          messages. This makes the biggest difference when sending objects that have
          significant preprocessing time (typically images).
      
          The `sendClientContent` message sends a `Content[]`
          which has more options than the `Blob` sent by `sendRealtimeInput`.
      
          So the main use-cases for `sendClientContent` over `sendRealtimeInput` are:
      
          - Sending anything that can't be represented as a `Blob` (text,
          `sendClientContent({turns="Hello?"}`)).
          - Managing turns when not using audio input and voice activity detection.
            (`sendClientContent({turnComplete:true})` or the short form
          `sendClientContent()`)
          - Prefilling a conversation context
            ```
            sendClientContent({
                turns: [
                  Content({role:user, parts:...}),
                  Content({role:user, parts:...}),
                  ...
                ]
            })
            ```
          @experimental
         */
      sendClientContent(params) {
        params = Object.assign(Object.assign({}, defaultLiveSendClientContentParamerters), params);
        const clientMessage = this.tLiveClientContent(this.apiClient, params);
        this.conn.send(JSON.stringify(clientMessage));
      }
      /**
          Send a realtime message over the established connection.
      
          @param params - Contains one property, `media`.
      
            - `media` will be converted to a `Blob`
      
          @experimental
      
          @remarks
          Use `sendRealtimeInput` for realtime audio chunks and video frames (images).
      
          With `sendRealtimeInput` the api will respond to audio automatically
          based on voice activity detection (VAD).
      
          `sendRealtimeInput` is optimized for responsivness at the expense of
          deterministic ordering guarantees. Audio and video tokens are to the
          context when they become available.
      
          Note: The Call signature expects a `Blob` object, but only a subset
          of audio and image mimetypes are allowed.
         */
      sendRealtimeInput(params) {
        let clientMessage = {};
        if (this.apiClient.isVertexAI()) {
          clientMessage = {
            "realtimeInput": liveSendRealtimeInputParametersToVertex(params)
          };
        } else {
          clientMessage = {
            "realtimeInput": liveSendRealtimeInputParametersToMldev(params)
          };
        }
        this.conn.send(JSON.stringify(clientMessage));
      }
      /**
          Send a function response message over the established connection.
      
          @param params - Contains property `functionResponses`.
      
            - `functionResponses` will be converted to a `functionResponses[]`
      
          @remarks
          Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server.
      
          Use {@link types.LiveConnectConfig#tools} to configure the callable functions.
      
          @experimental
         */
      sendToolResponse(params) {
        if (params.functionResponses == null) {
          throw new Error("Tool response parameters are required.");
        }
        const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params);
        this.conn.send(JSON.stringify(clientMessage));
      }
      /**
           Terminates the WebSocket connection.
      
           @experimental
      
           @example
           ```ts
           let model: string;
           if (GOOGLE_GENAI_USE_VERTEXAI) {
             model = 'gemini-2.0-flash-live-preview-04-09';
           } else {
             model = 'gemini-live-2.5-flash-preview';
           }
           const session = await ai.live.connect({
             model: model,
             config: {
               responseModalities: [Modality.AUDIO],
             }
           });
      
           session.close();
           ```
         */
      close() {
        this.conn.close();
      }
    };
    __name(headersToMap, "headersToMap");
    __name(mapToHeaders, "mapToHeaders");
    DEFAULT_MAX_REMOTE_CALLS = 10;
    __name(shouldDisableAfc, "shouldDisableAfc");
    __name(isCallableTool, "isCallableTool");
    __name(hasCallableTools, "hasCallableTools");
    __name(hasNonCallableTools, "hasNonCallableTools");
    __name(shouldAppendAfcHistory, "shouldAppendAfcHistory");
    Models = class extends BaseModule {
      static {
        __name(this, "Models");
      }
      constructor(apiClient) {
        super();
        this.apiClient = apiClient;
        this.generateContent = async (params) => {
          var _a6, _b2, _c2, _d, _e;
          const transformedParams = await this.processParamsMaybeAddMcpUsage(params);
          this.maybeMoveToResponseJsonSchem(params);
          if (!hasCallableTools(params) || shouldDisableAfc(params.config)) {
            return await this.generateContentInternal(transformedParams);
          }
          if (hasNonCallableTools(params)) {
            throw new Error("Automatic function calling with CallableTools and Tools is not yet supported.");
          }
          let response;
          let functionResponseContent;
          const automaticFunctionCallingHistory = tContents(transformedParams.contents);
          const maxRemoteCalls = (_c2 = (_b2 = (_a6 = transformedParams.config) === null || _a6 === void 0 ? void 0 : _a6.automaticFunctionCalling) === null || _b2 === void 0 ? void 0 : _b2.maximumRemoteCalls) !== null && _c2 !== void 0 ? _c2 : DEFAULT_MAX_REMOTE_CALLS;
          let remoteCalls = 0;
          while (remoteCalls < maxRemoteCalls) {
            response = await this.generateContentInternal(transformedParams);
            if (!response.functionCalls || response.functionCalls.length === 0) {
              break;
            }
            const responseContent = response.candidates[0].content;
            const functionResponseParts = [];
            for (const tool of (_e = (_d = params.config) === null || _d === void 0 ? void 0 : _d.tools) !== null && _e !== void 0 ? _e : []) {
              if (isCallableTool(tool)) {
                const callableTool = tool;
                const parts = await callableTool.callTool(response.functionCalls);
                functionResponseParts.push(...parts);
              }
            }
            remoteCalls++;
            functionResponseContent = {
              role: "user",
              parts: functionResponseParts
            };
            transformedParams.contents = tContents(transformedParams.contents);
            transformedParams.contents.push(responseContent);
            transformedParams.contents.push(functionResponseContent);
            if (shouldAppendAfcHistory(transformedParams.config)) {
              automaticFunctionCallingHistory.push(responseContent);
              automaticFunctionCallingHistory.push(functionResponseContent);
            }
          }
          if (shouldAppendAfcHistory(transformedParams.config)) {
            response.automaticFunctionCallingHistory = automaticFunctionCallingHistory;
          }
          return response;
        };
        this.generateContentStream = async (params) => {
          this.maybeMoveToResponseJsonSchem(params);
          if (shouldDisableAfc(params.config)) {
            const transformedParams = await this.processParamsMaybeAddMcpUsage(params);
            return await this.generateContentStreamInternal(transformedParams);
          } else {
            return await this.processAfcStream(params);
          }
        };
        this.generateImages = async (params) => {
          return await this.generateImagesInternal(params).then((apiResponse) => {
            var _a6;
            let positivePromptSafetyAttributes;
            const generatedImages = [];
            if (apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.generatedImages) {
              for (const generatedImage of apiResponse.generatedImages) {
                if (generatedImage && (generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) && ((_a6 = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) === null || _a6 === void 0 ? void 0 : _a6.contentType) === "Positive Prompt") {
                  positivePromptSafetyAttributes = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes;
                } else {
                  generatedImages.push(generatedImage);
                }
              }
            }
            let response;
            if (positivePromptSafetyAttributes) {
              response = {
                generatedImages,
                positivePromptSafetyAttributes,
                sdkHttpResponse: apiResponse.sdkHttpResponse
              };
            } else {
              response = {
                generatedImages,
                sdkHttpResponse: apiResponse.sdkHttpResponse
              };
            }
            return response;
          });
        };
        this.list = async (params) => {
          var _a6;
          const defaultConfig = {
            queryBase: true
          };
          const actualConfig = Object.assign(Object.assign({}, defaultConfig), params === null || params === void 0 ? void 0 : params.config);
          const actualParams = {
            config: actualConfig
          };
          if (this.apiClient.isVertexAI()) {
            if (!actualParams.config.queryBase) {
              if ((_a6 = actualParams.config) === null || _a6 === void 0 ? void 0 : _a6.filter) {
                throw new Error("Filtering tuned models list for Vertex AI is not currently supported");
              } else {
                actualParams.config.filter = "labels.tune-type:*";
              }
            }
          }
          return new Pager(PagedItem.PAGED_ITEM_MODELS, (x) => this.listInternal(x), await this.listInternal(actualParams), actualParams);
        };
        this.editImage = async (params) => {
          const paramsInternal = {
            model: params.model,
            prompt: params.prompt,
            referenceImages: [],
            config: params.config
          };
          if (params.referenceImages) {
            if (params.referenceImages) {
              paramsInternal.referenceImages = params.referenceImages.map((img) => img.toReferenceImageAPI());
            }
          }
          return await this.editImageInternal(paramsInternal);
        };
        this.upscaleImage = async (params) => {
          let apiConfig = {
            numberOfImages: 1,
            mode: "upscale"
          };
          if (params.config) {
            apiConfig = Object.assign(Object.assign({}, apiConfig), params.config);
          }
          const apiParams = {
            model: params.model,
            image: params.image,
            upscaleFactor: params.upscaleFactor,
            config: apiConfig
          };
          return await this.upscaleImageInternal(apiParams);
        };
        this.generateVideos = async (params) => {
          if ((params.prompt || params.image || params.video) && params.source) {
            throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");
          }
          return await this.generateVideosInternal(params);
        };
      }
      /**
       * This logic is needed for GenerateContentConfig only.
       * Previously we made GenerateContentConfig.responseSchema field to accept
       * unknown. Since v1.9.0, we switch to use backend JSON schema support.
       * To maintain backward compatibility, we move the data that was treated as
       * JSON schema from the responseSchema field to the responseJsonSchema field.
       */
      maybeMoveToResponseJsonSchem(params) {
        if (params.config && params.config.responseSchema) {
          if (!params.config.responseJsonSchema) {
            if (Object.keys(params.config.responseSchema).includes("$schema")) {
              params.config.responseJsonSchema = params.config.responseSchema;
              delete params.config.responseSchema;
            }
          }
        }
        return;
      }
      /**
       * Transforms the CallableTools in the parameters to be simply Tools, it
       * copies the params into a new object and replaces the tools, it does not
       * modify the original params. Also sets the MCP usage header if there are
       * MCP tools in the parameters.
       */
      async processParamsMaybeAddMcpUsage(params) {
        var _a6, _b2, _c2;
        const tools = (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.tools;
        if (!tools) {
          return params;
        }
        const transformedTools = await Promise.all(tools.map(async (tool) => {
          if (isCallableTool(tool)) {
            const callableTool = tool;
            return await callableTool.tool();
          }
          return tool;
        }));
        const newParams = {
          model: params.model,
          contents: params.contents,
          config: Object.assign(Object.assign({}, params.config), { tools: transformedTools })
        };
        newParams.config.tools = transformedTools;
        if (params.config && params.config.tools && hasMcpToolUsage(params.config.tools)) {
          const headers = (_c2 = (_b2 = params.config.httpOptions) === null || _b2 === void 0 ? void 0 : _b2.headers) !== null && _c2 !== void 0 ? _c2 : {};
          let newHeaders = Object.assign({}, headers);
          if (Object.keys(newHeaders).length === 0) {
            newHeaders = this.apiClient.getDefaultHeaders();
          }
          setMcpUsageHeader(newHeaders);
          newParams.config.httpOptions = Object.assign(Object.assign({}, params.config.httpOptions), { headers: newHeaders });
        }
        return newParams;
      }
      async initAfcToolsMap(params) {
        var _a6, _b2, _c2;
        const afcTools = /* @__PURE__ */ new Map();
        for (const tool of (_b2 = (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.tools) !== null && _b2 !== void 0 ? _b2 : []) {
          if (isCallableTool(tool)) {
            const callableTool = tool;
            const toolDeclaration = await callableTool.tool();
            for (const declaration of (_c2 = toolDeclaration.functionDeclarations) !== null && _c2 !== void 0 ? _c2 : []) {
              if (!declaration.name) {
                throw new Error("Function declaration name is required.");
              }
              if (afcTools.has(declaration.name)) {
                throw new Error(`Duplicate tool declaration name: ${declaration.name}`);
              }
              afcTools.set(declaration.name, callableTool);
            }
          }
        }
        return afcTools;
      }
      async processAfcStream(params) {
        var _a6, _b2, _c2;
        const maxRemoteCalls = (_c2 = (_b2 = (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.automaticFunctionCalling) === null || _b2 === void 0 ? void 0 : _b2.maximumRemoteCalls) !== null && _c2 !== void 0 ? _c2 : DEFAULT_MAX_REMOTE_CALLS;
        let wereFunctionsCalled = false;
        let remoteCallCount = 0;
        const afcToolsMap = await this.initAfcToolsMap(params);
        return function(models, afcTools, params2) {
          var _a7, _b3;
          return __asyncGenerator(this, arguments, function* () {
            var _c3, e_1, _d, _e;
            while (remoteCallCount < maxRemoteCalls) {
              if (wereFunctionsCalled) {
                remoteCallCount++;
                wereFunctionsCalled = false;
              }
              const transformedParams = yield __await(models.processParamsMaybeAddMcpUsage(params2));
              const response = yield __await(models.generateContentStreamInternal(transformedParams));
              const functionResponses = [];
              const responseContents = [];
              try {
                for (var _f = true, response_1 = (e_1 = void 0, __asyncValues(response)), response_1_1; response_1_1 = yield __await(response_1.next()), _c3 = response_1_1.done, !_c3; _f = true) {
                  _e = response_1_1.value;
                  _f = false;
                  const chunk = _e;
                  yield yield __await(chunk);
                  if (chunk.candidates && ((_a7 = chunk.candidates[0]) === null || _a7 === void 0 ? void 0 : _a7.content)) {
                    responseContents.push(chunk.candidates[0].content);
                    for (const part of (_b3 = chunk.candidates[0].content.parts) !== null && _b3 !== void 0 ? _b3 : []) {
                      if (remoteCallCount < maxRemoteCalls && part.functionCall) {
                        if (!part.functionCall.name) {
                          throw new Error("Function call name was not returned by the model.");
                        }
                        if (!afcTools.has(part.functionCall.name)) {
                          throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`);
                        } else {
                          const responseParts = yield __await(afcTools.get(part.functionCall.name).callTool([part.functionCall]));
                          functionResponses.push(...responseParts);
                        }
                      }
                    }
                  }
                }
              } catch (e_1_1) {
                e_1 = { error: e_1_1 };
              } finally {
                try {
                  if (!_f && !_c3 && (_d = response_1.return)) yield __await(_d.call(response_1));
                } finally {
                  if (e_1) throw e_1.error;
                }
              }
              if (functionResponses.length > 0) {
                wereFunctionsCalled = true;
                const typedResponseChunk = new GenerateContentResponse();
                typedResponseChunk.candidates = [
                  {
                    content: {
                      role: "user",
                      parts: functionResponses
                    }
                  }
                ];
                yield yield __await(typedResponseChunk);
                const newContents = [];
                newContents.push(...responseContents);
                newContents.push({
                  role: "user",
                  parts: functionResponses
                });
                const updatedContents = tContents(params2.contents).concat(newContents);
                params2.contents = updatedContents;
              } else {
                break;
              }
            }
          });
        }(this, afcToolsMap, params);
      }
      async generateContentInternal(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = generateContentParametersToVertex(this.apiClient, params);
          path108 = formatMap("{model}:generateContent", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = generateContentResponseFromVertex(apiResponse);
            const typedResp = new GenerateContentResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        } else {
          const body = generateContentParametersToMldev(this.apiClient, params);
          path108 = formatMap("{model}:generateContent", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = generateContentResponseFromMldev(apiResponse);
            const typedResp = new GenerateContentResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        }
      }
      async generateContentStreamInternal(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = generateContentParametersToVertex(this.apiClient, params);
          path108 = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          const apiClient = this.apiClient;
          response = apiClient.requestStream({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          });
          return response.then(function(apiResponse) {
            return __asyncGenerator(this, arguments, function* () {
              var _a7, e_2, _b3, _c3;
              try {
                for (var _d2 = true, apiResponse_1 = __asyncValues(apiResponse), apiResponse_1_1; apiResponse_1_1 = yield __await(apiResponse_1.next()), _a7 = apiResponse_1_1.done, !_a7; _d2 = true) {
                  _c3 = apiResponse_1_1.value;
                  _d2 = false;
                  const chunk = _c3;
                  const resp = generateContentResponseFromVertex(yield __await(chunk.json()));
                  resp["sdkHttpResponse"] = {
                    headers: chunk.headers
                  };
                  const typedResp = new GenerateContentResponse();
                  Object.assign(typedResp, resp);
                  yield yield __await(typedResp);
                }
              } catch (e_2_1) {
                e_2 = { error: e_2_1 };
              } finally {
                try {
                  if (!_d2 && !_a7 && (_b3 = apiResponse_1.return)) yield __await(_b3.call(apiResponse_1));
                } finally {
                  if (e_2) throw e_2.error;
                }
              }
            });
          });
        } else {
          const body = generateContentParametersToMldev(this.apiClient, params);
          path108 = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          const apiClient = this.apiClient;
          response = apiClient.requestStream({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          });
          return response.then(function(apiResponse) {
            return __asyncGenerator(this, arguments, function* () {
              var _a7, e_3, _b3, _c3;
              try {
                for (var _d2 = true, apiResponse_2 = __asyncValues(apiResponse), apiResponse_2_1; apiResponse_2_1 = yield __await(apiResponse_2.next()), _a7 = apiResponse_2_1.done, !_a7; _d2 = true) {
                  _c3 = apiResponse_2_1.value;
                  _d2 = false;
                  const chunk = _c3;
                  const resp = generateContentResponseFromMldev(yield __await(chunk.json()));
                  resp["sdkHttpResponse"] = {
                    headers: chunk.headers
                  };
                  const typedResp = new GenerateContentResponse();
                  Object.assign(typedResp, resp);
                  yield yield __await(typedResp);
                }
              } catch (e_3_1) {
                e_3 = { error: e_3_1 };
              } finally {
                try {
                  if (!_d2 && !_a7 && (_b3 = apiResponse_2.return)) yield __await(_b3.call(apiResponse_2));
                } finally {
                  if (e_3) throw e_3.error;
                }
              }
            });
          });
        }
      }
      /**
       * Calculates embeddings for the given contents. Only text is supported.
       *
       * @param params - The parameters for embedding contents.
       * @return The response from the API.
       *
       * @example
       * ```ts
       * const response = await ai.models.embedContent({
       *  model: 'text-embedding-004',
       *  contents: [
       *    'What is your name?',
       *    'What is your favorite color?',
       *  ],
       *  config: {
       *    outputDimensionality: 64,
       *  },
       * });
       * console.log(response);
       * ```
       */
      async embedContent(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = embedContentParametersToVertex(this.apiClient, params);
          path108 = formatMap("{model}:predict", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = embedContentResponseFromVertex(apiResponse);
            const typedResp = new EmbedContentResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        } else {
          const body = embedContentParametersToMldev(this.apiClient, params);
          path108 = formatMap("{model}:batchEmbedContents", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = embedContentResponseFromMldev(apiResponse);
            const typedResp = new EmbedContentResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        }
      }
      /**
       * Generates an image based on a text description and configuration.
       *
       * @param params - The parameters for generating images.
       * @return The response from the API.
       *
       * @example
       * ```ts
       * const response = await ai.models.generateImages({
       *  model: 'imagen-3.0-generate-002',
       *  prompt: 'Robot holding a red skateboard',
       *  config: {
       *    numberOfImages: 1,
       *    includeRaiReason: true,
       *  },
       * });
       * console.log(response?.generatedImages?.[0]?.image?.imageBytes);
       * ```
       */
      async generateImagesInternal(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = generateImagesParametersToVertex(this.apiClient, params);
          path108 = formatMap("{model}:predict", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = generateImagesResponseFromVertex(apiResponse);
            const typedResp = new GenerateImagesResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        } else {
          const body = generateImagesParametersToMldev(this.apiClient, params);
          path108 = formatMap("{model}:predict", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = generateImagesResponseFromMldev(apiResponse);
            const typedResp = new GenerateImagesResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        }
      }
      async editImageInternal(params) {
        var _a6, _b2;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = editImageParametersInternalToVertex(this.apiClient, params);
          path108 = formatMap("{model}:predict", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = editImageResponseFromVertex(apiResponse);
            const typedResp = new EditImageResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        } else {
          throw new Error("This method is only supported by the Vertex AI.");
        }
      }
      async upscaleImageInternal(params) {
        var _a6, _b2;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = upscaleImageAPIParametersInternalToVertex(this.apiClient, params);
          path108 = formatMap("{model}:predict", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = upscaleImageResponseFromVertex(apiResponse);
            const typedResp = new UpscaleImageResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        } else {
          throw new Error("This method is only supported by the Vertex AI.");
        }
      }
      /**
       * Recontextualizes an image.
       *
       * There are two types of recontextualization currently supported:
       * 1) Imagen Product Recontext - Generate images of products in new scenes
       *    and contexts.
       * 2) Virtual Try-On: Generate images of persons modeling fashion products.
       *
       * @param params - The parameters for recontextualizing an image.
       * @return The response from the API.
       *
       * @example
       * ```ts
       * const response1 = await ai.models.recontextImage({
       *  model: 'imagen-product-recontext-preview-06-30',
       *  source: {
       *    prompt: 'In a modern kitchen setting.',
       *    productImages: [productImage],
       *  },
       *  config: {
       *    numberOfImages: 1,
       *  },
       * });
       * console.log(response1?.generatedImages?.[0]?.image?.imageBytes);
       *
       * const response2 = await ai.models.recontextImage({
       *  model: 'virtual-try-on-preview-08-04',
       *  source: {
       *    personImage: personImage,
       *    productImages: [productImage],
       *  },
       *  config: {
       *    numberOfImages: 1,
       *  },
       * });
       * console.log(response2?.generatedImages?.[0]?.image?.imageBytes);
       * ```
       */
      async recontextImage(params) {
        var _a6, _b2;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = recontextImageParametersToVertex(this.apiClient, params);
          path108 = formatMap("{model}:predict", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = recontextImageResponseFromVertex(apiResponse);
            const typedResp = new RecontextImageResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        } else {
          throw new Error("This method is only supported by the Vertex AI.");
        }
      }
      /**
       * Segments an image, creating a mask of a specified area.
       *
       * @param params - The parameters for segmenting an image.
       * @return The response from the API.
       *
       * @example
       * ```ts
       * const response = await ai.models.segmentImage({
       *  model: 'image-segmentation-001',
       *  source: {
       *    image: image,
       *  },
       *  config: {
       *    mode: 'foreground',
       *  },
       * });
       * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes);
       * ```
       */
      async segmentImage(params) {
        var _a6, _b2;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = segmentImageParametersToVertex(this.apiClient, params);
          path108 = formatMap("{model}:predict", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = segmentImageResponseFromVertex(apiResponse);
            const typedResp = new SegmentImageResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        } else {
          throw new Error("This method is only supported by the Vertex AI.");
        }
      }
      /**
       * Fetches information about a model by name.
       *
       * @example
       * ```ts
       * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'});
       * ```
       */
      async get(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = getModelParametersToVertex(this.apiClient, params);
          path108 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = modelFromVertex(apiResponse);
            return resp;
          });
        } else {
          const body = getModelParametersToMldev(this.apiClient, params);
          path108 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = modelFromMldev(apiResponse);
            return resp;
          });
        }
      }
      async listInternal(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = listModelsParametersToVertex(this.apiClient, params);
          path108 = formatMap("{models_url}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = listModelsResponseFromVertex(apiResponse);
            const typedResp = new ListModelsResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        } else {
          const body = listModelsParametersToMldev(this.apiClient, params);
          path108 = formatMap("{models_url}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = listModelsResponseFromMldev(apiResponse);
            const typedResp = new ListModelsResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        }
      }
      /**
       * Updates a tuned model by its name.
       *
       * @param params - The parameters for updating the model.
       * @return The response from the API.
       *
       * @example
       * ```ts
       * const response = await ai.models.update({
       *   model: 'tuned-model-name',
       *   config: {
       *     displayName: 'New display name',
       *     description: 'New description',
       *   },
       * });
       * ```
       */
      async update(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = updateModelParametersToVertex(this.apiClient, params);
          path108 = formatMap("{model}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "PATCH",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = modelFromVertex(apiResponse);
            return resp;
          });
        } else {
          const body = updateModelParametersToMldev(this.apiClient, params);
          path108 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "PATCH",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = modelFromMldev(apiResponse);
            return resp;
          });
        }
      }
      /**
       * Deletes a tuned model by its name.
       *
       * @param params - The parameters for deleting the model.
       * @return The response from the API.
       *
       * @example
       * ```ts
       * const response = await ai.models.delete({model: 'tuned-model-name'});
       * ```
       */
      async delete(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = deleteModelParametersToVertex(this.apiClient, params);
          path108 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "DELETE",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = deleteModelResponseFromVertex(apiResponse);
            const typedResp = new DeleteModelResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        } else {
          const body = deleteModelParametersToMldev(this.apiClient, params);
          path108 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "DELETE",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = deleteModelResponseFromMldev(apiResponse);
            const typedResp = new DeleteModelResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        }
      }
      /**
       * Counts the number of tokens in the given contents. Multimodal input is
       * supported for Gemini models.
       *
       * @param params - The parameters for counting tokens.
       * @return The response from the API.
       *
       * @example
       * ```ts
       * const response = await ai.models.countTokens({
       *  model: 'gemini-2.0-flash',
       *  contents: 'The quick brown fox jumps over the lazy dog.'
       * });
       * console.log(response);
       * ```
       */
      async countTokens(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = countTokensParametersToVertex(this.apiClient, params);
          path108 = formatMap("{model}:countTokens", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = countTokensResponseFromVertex(apiResponse);
            const typedResp = new CountTokensResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        } else {
          const body = countTokensParametersToMldev(this.apiClient, params);
          path108 = formatMap("{model}:countTokens", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = countTokensResponseFromMldev(apiResponse);
            const typedResp = new CountTokensResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        }
      }
      /**
       * Given a list of contents, returns a corresponding TokensInfo containing
       * the list of tokens and list of token ids.
       *
       * This method is not supported by the Gemini Developer API.
       *
       * @param params - The parameters for computing tokens.
       * @return The response from the API.
       *
       * @example
       * ```ts
       * const response = await ai.models.computeTokens({
       *  model: 'gemini-2.0-flash',
       *  contents: 'What is your name?'
       * });
       * console.log(response);
       * ```
       */
      async computeTokens(params) {
        var _a6, _b2;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = computeTokensParametersToVertex(this.apiClient, params);
          path108 = formatMap("{model}:computeTokens", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = computeTokensResponseFromVertex(apiResponse);
            const typedResp = new ComputeTokensResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        } else {
          throw new Error("This method is only supported by the Vertex AI.");
        }
      }
      /**
       *  Generates videos based on a text description and configuration.
       *
       * @param params - The parameters for generating videos.
       * @return A Promise<GenerateVideosOperation> which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.
       *
       * @example
       * ```ts
       * const operation = await ai.models.generateVideos({
       *  model: 'veo-2.0-generate-001',
       *  prompt: 'A neon hologram of a cat driving at top speed',
       *  config: {
       *    numberOfVideos: 1
       * });
       *
       * while (!operation.done) {
       *   await new Promise(resolve => setTimeout(resolve, 10000));
       *   operation = await ai.operations.getVideosOperation({operation: operation});
       * }
       *
       * console.log(operation.response?.generatedVideos?.[0]?.video?.uri);
       * ```
       */
      async generateVideosInternal(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = generateVideosParametersToVertex(this.apiClient, params);
          path108 = formatMap("{model}:predictLongRunning", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = generateVideosOperationFromVertex(apiResponse);
            const typedResp = new GenerateVideosOperation();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        } else {
          const body = generateVideosParametersToMldev(this.apiClient, params);
          path108 = formatMap("{model}:predictLongRunning", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = generateVideosOperationFromMldev(apiResponse);
            const typedResp = new GenerateVideosOperation();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        }
      }
    };
    __name(getOperationParametersToMldev, "getOperationParametersToMldev");
    __name(fetchPredictOperationParametersToVertex, "fetchPredictOperationParametersToVertex");
    __name(getOperationParametersToVertex, "getOperationParametersToVertex");
    Operations = class extends BaseModule {
      static {
        __name(this, "Operations");
      }
      constructor(apiClient) {
        super();
        this.apiClient = apiClient;
      }
      /**
       * Gets the status of a long-running operation.
       *
       * @param parameters The parameters for the get operation request.
       * @return The updated Operation object, with the latest status or result.
       */
      async getVideosOperation(parameters) {
        const operation = parameters.operation;
        const config = parameters.config;
        if (operation.name === void 0 || operation.name === "") {
          throw new Error("Operation name is required.");
        }
        if (this.apiClient.isVertexAI()) {
          const resourceName2 = operation.name.split("/operations/")[0];
          let httpOptions = void 0;
          if (config && "httpOptions" in config) {
            httpOptions = config.httpOptions;
          }
          const rawOperation = await this.fetchPredictVideosOperationInternal({
            operationName: operation.name,
            resourceName: resourceName2,
            config: { httpOptions }
          });
          return operation._fromAPIResponse({
            apiResponse: rawOperation,
            isVertexAI: true
          });
        } else {
          const rawOperation = await this.getVideosOperationInternal({
            operationName: operation.name,
            config
          });
          return operation._fromAPIResponse({
            apiResponse: rawOperation,
            isVertexAI: false
          });
        }
      }
      /**
       * Gets the status of a long-running operation.
       *
       * @param parameters The parameters for the get operation request.
       * @return The updated Operation object, with the latest status or result.
       */
      async get(parameters) {
        const operation = parameters.operation;
        const config = parameters.config;
        if (operation.name === void 0 || operation.name === "") {
          throw new Error("Operation name is required.");
        }
        if (this.apiClient.isVertexAI()) {
          const resourceName2 = operation.name.split("/operations/")[0];
          let httpOptions = void 0;
          if (config && "httpOptions" in config) {
            httpOptions = config.httpOptions;
          }
          const rawOperation = await this.fetchPredictVideosOperationInternal({
            operationName: operation.name,
            resourceName: resourceName2,
            config: { httpOptions }
          });
          return operation._fromAPIResponse({
            apiResponse: rawOperation,
            isVertexAI: true
          });
        } else {
          const rawOperation = await this.getVideosOperationInternal({
            operationName: operation.name,
            config
          });
          return operation._fromAPIResponse({
            apiResponse: rawOperation,
            isVertexAI: false
          });
        }
      }
      async getVideosOperationInternal(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = getOperationParametersToVertex(params);
          path108 = formatMap("{operationName}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response;
        } else {
          const body = getOperationParametersToMldev(params);
          path108 = formatMap("{operationName}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response;
        }
      }
      async fetchPredictVideosOperationInternal(params) {
        var _a6, _b2;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = fetchPredictOperationParametersToVertex(params);
          path108 = formatMap("{resourceName}:fetchPredictOperation", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response;
        } else {
          throw new Error("This method is only supported by the Vertex AI.");
        }
      }
    };
    __name(prebuiltVoiceConfigToMldev, "prebuiltVoiceConfigToMldev");
    __name(voiceConfigToMldev, "voiceConfigToMldev");
    __name(speakerVoiceConfigToMldev, "speakerVoiceConfigToMldev");
    __name(multiSpeakerVoiceConfigToMldev, "multiSpeakerVoiceConfigToMldev");
    __name(speechConfigToMldev, "speechConfigToMldev");
    __name(videoMetadataToMldev, "videoMetadataToMldev");
    __name(blobToMldev, "blobToMldev");
    __name(fileDataToMldev, "fileDataToMldev");
    __name(partToMldev, "partToMldev");
    __name(contentToMldev, "contentToMldev");
    __name(functionDeclarationToMldev, "functionDeclarationToMldev");
    __name(intervalToMldev, "intervalToMldev");
    __name(googleSearchToMldev, "googleSearchToMldev");
    __name(dynamicRetrievalConfigToMldev, "dynamicRetrievalConfigToMldev");
    __name(googleSearchRetrievalToMldev, "googleSearchRetrievalToMldev");
    __name(urlContextToMldev, "urlContextToMldev");
    __name(toolComputerUseToMldev, "toolComputerUseToMldev");
    __name(toolToMldev, "toolToMldev");
    __name(sessionResumptionConfigToMldev, "sessionResumptionConfigToMldev");
    __name(audioTranscriptionConfigToMldev, "audioTranscriptionConfigToMldev");
    __name(automaticActivityDetectionToMldev, "automaticActivityDetectionToMldev");
    __name(realtimeInputConfigToMldev, "realtimeInputConfigToMldev");
    __name(slidingWindowToMldev, "slidingWindowToMldev");
    __name(contextWindowCompressionConfigToMldev, "contextWindowCompressionConfigToMldev");
    __name(proactivityConfigToMldev, "proactivityConfigToMldev");
    __name(liveConnectConfigToMldev, "liveConnectConfigToMldev");
    __name(liveConnectConstraintsToMldev, "liveConnectConstraintsToMldev");
    __name(createAuthTokenConfigToMldev, "createAuthTokenConfigToMldev");
    __name(createAuthTokenParametersToMldev, "createAuthTokenParametersToMldev");
    __name(authTokenFromMldev, "authTokenFromMldev");
    __name(getFieldMasks, "getFieldMasks");
    __name(convertBidiSetupToTokenSetup, "convertBidiSetupToTokenSetup");
    Tokens = class extends BaseModule {
      static {
        __name(this, "Tokens");
      }
      constructor(apiClient) {
        super();
        this.apiClient = apiClient;
      }
      /**
       * Creates an ephemeral auth token resource.
       *
       * @experimental
       *
       * @remarks
       * Ephemeral auth tokens is only supported in the Gemini Developer API.
       * It can be used for the session connection to the Live constrained API.
       * Support in v1alpha only.
       *
       * @param params - The parameters for the create request.
       * @return The created auth token.
       *
       * @example
       * ```ts
       * const ai = new GoogleGenAI({
       *     apiKey: token.name,
       *     httpOptions: { apiVersion: 'v1alpha' }  // Support in v1alpha only.
       * });
       *
       * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig
       * // when using the token in Live API sessions. Each session connection can
       * // use a different configuration.
       * const config: CreateAuthTokenConfig = {
       *     uses: 3,
       *     expireTime: '2025-05-01T00:00:00Z',
       * }
       * const token = await ai.tokens.create(config);
       *
       * // Case 2: If LiveEphemeralParameters is set, lock all fields in
       * // LiveConnectConfig when using the token in Live API sessions. For
       * // example, changing `outputAudioTranscription` in the Live API
       * // connection will be ignored by the API.
       * const config: CreateAuthTokenConfig =
       *     uses: 3,
       *     expireTime: '2025-05-01T00:00:00Z',
       *     LiveEphemeralParameters: {
       *        model: 'gemini-2.0-flash-001',
       *        config: {
       *           'responseModalities': ['AUDIO'],
       *           'systemInstruction': 'Always answer in English.',
       *        }
       *     }
       * }
       * const token = await ai.tokens.create(config);
       *
       * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is
       * // set, lock LiveConnectConfig with set and additional fields (e.g.
       * // responseModalities, systemInstruction, temperature in this example) when
       * // using the token in Live API sessions.
       * const config: CreateAuthTokenConfig =
       *     uses: 3,
       *     expireTime: '2025-05-01T00:00:00Z',
       *     LiveEphemeralParameters: {
       *        model: 'gemini-2.0-flash-001',
       *        config: {
       *           'responseModalities': ['AUDIO'],
       *           'systemInstruction': 'Always answer in English.',
       *        }
       *     },
       *     lockAdditionalFields: ['temperature'],
       * }
       * const token = await ai.tokens.create(config);
       *
       * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is
       * // empty array, lock LiveConnectConfig with set fields (e.g.
       * // responseModalities, systemInstruction in this example) when using the
       * // token in Live API sessions.
       * const config: CreateAuthTokenConfig =
       *     uses: 3,
       *     expireTime: '2025-05-01T00:00:00Z',
       *     LiveEphemeralParameters: {
       *        model: 'gemini-2.0-flash-001',
       *        config: {
       *           'responseModalities': ['AUDIO'],
       *           'systemInstruction': 'Always answer in English.',
       *        }
       *     },
       *     lockAdditionalFields: [],
       * }
       * const token = await ai.tokens.create(config);
       * ```
       */
      async create(params) {
        var _a6, _b2;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");
        } else {
          const body = createAuthTokenParametersToMldev(this.apiClient, params);
          path108 = formatMap("auth_tokens", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          const transformedBody = convertBidiSetupToTokenSetup(body, params.config);
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(transformedBody),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json();
          });
          return response.then((apiResponse) => {
            const resp = authTokenFromMldev(apiResponse);
            return resp;
          });
        }
      }
    };
    GOOGLE_API_KEY_HEADER = "x-goog-api-key";
    REQUIRED_VERTEX_AI_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
    NodeAuth = class {
      static {
        __name(this, "NodeAuth");
      }
      constructor(opts) {
        if (opts.apiKey !== void 0) {
          this.apiKey = opts.apiKey;
          return;
        }
        const vertexAuthOptions = buildGoogleAuthOptions(opts.googleAuthOptions);
        this.googleAuth = new import_google_auth_library.GoogleAuth(vertexAuthOptions);
      }
      async addAuthHeaders(headers) {
        if (this.apiKey !== void 0) {
          if (this.apiKey.startsWith("auth_tokens/")) {
            throw new Error("Ephemeral tokens are only supported by the live API.");
          }
          this.addKeyHeader(headers);
          return;
        }
        return this.addGoogleAuthHeaders(headers);
      }
      addKeyHeader(headers) {
        if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {
          return;
        }
        if (this.apiKey === void 0) {
          throw new Error("Trying to set API key header but apiKey is not set");
        }
        headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);
      }
      async addGoogleAuthHeaders(headers) {
        if (this.googleAuth === void 0) {
          throw new Error("Trying to set google-auth headers but googleAuth is unset");
        }
        const authHeaders = await this.googleAuth.getRequestHeaders();
        for (const key in authHeaders) {
          if (headers.get(key) !== null) {
            continue;
          }
          headers.append(key, authHeaders[key]);
        }
      }
    };
    __name(buildGoogleAuthOptions, "buildGoogleAuthOptions");
    NodeDownloader = class {
      static {
        __name(this, "NodeDownloader");
      }
      async download(params, apiClient) {
        if (params.downloadPath) {
          const response = await downloadFile(params, apiClient);
          if (response instanceof HttpResponse) {
            const writer = createWriteStream(params.downloadPath);
            Readable.fromWeb(response.responseInternal.body).pipe(writer);
          } else {
            writeFile(params.downloadPath, response, { encoding: "base64" }, (error) => {
              if (error) {
                throw new Error(`Failed to write file to ${params.downloadPath}: ${error}`);
              }
            });
          }
        }
      }
    };
    __name(downloadFile, "downloadFile");
    NodeWebSocketFactory = class {
      static {
        __name(this, "NodeWebSocketFactory");
      }
      create(url2, headers, callbacks) {
        return new NodeWebSocket(url2, headers, callbacks);
      }
    };
    NodeWebSocket = class {
      static {
        __name(this, "NodeWebSocket");
      }
      constructor(url2, headers, callbacks) {
        this.url = url2;
        this.headers = headers;
        this.callbacks = callbacks;
      }
      connect() {
        this.ws = new import_websocket.default(this.url, { headers: this.headers });
        this.ws.onopen = this.callbacks.onopen;
        this.ws.onerror = this.callbacks.onerror;
        this.ws.onclose = this.callbacks.onclose;
        this.ws.onmessage = this.callbacks.onmessage;
      }
      send(message) {
        if (this.ws === void 0) {
          throw new Error("WebSocket is not connected");
        }
        this.ws.send(message);
      }
      close() {
        if (this.ws === void 0) {
          throw new Error("WebSocket is not connected");
        }
        this.ws.close();
      }
    };
    __name(getTuningJobParametersToMldev, "getTuningJobParametersToMldev");
    __name(listTuningJobsConfigToMldev, "listTuningJobsConfigToMldev");
    __name(listTuningJobsParametersToMldev, "listTuningJobsParametersToMldev");
    __name(cancelTuningJobParametersToMldev, "cancelTuningJobParametersToMldev");
    __name(tuningExampleToMldev, "tuningExampleToMldev");
    __name(tuningDatasetToMldev, "tuningDatasetToMldev");
    __name(createTuningJobConfigToMldev, "createTuningJobConfigToMldev");
    __name(createTuningJobParametersPrivateToMldev, "createTuningJobParametersPrivateToMldev");
    __name(getTuningJobParametersToVertex, "getTuningJobParametersToVertex");
    __name(listTuningJobsConfigToVertex, "listTuningJobsConfigToVertex");
    __name(listTuningJobsParametersToVertex, "listTuningJobsParametersToVertex");
    __name(cancelTuningJobParametersToVertex, "cancelTuningJobParametersToVertex");
    __name(tuningDatasetToVertex, "tuningDatasetToVertex");
    __name(tuningValidationDatasetToVertex, "tuningValidationDatasetToVertex");
    __name(createTuningJobConfigToVertex, "createTuningJobConfigToVertex");
    __name(createTuningJobParametersPrivateToVertex, "createTuningJobParametersPrivateToVertex");
    __name(tunedModelFromMldev, "tunedModelFromMldev");
    __name(tuningJobFromMldev, "tuningJobFromMldev");
    __name(listTuningJobsResponseFromMldev, "listTuningJobsResponseFromMldev");
    __name(tuningOperationFromMldev, "tuningOperationFromMldev");
    __name(tunedModelCheckpointFromVertex, "tunedModelCheckpointFromVertex");
    __name(tunedModelFromVertex, "tunedModelFromVertex");
    __name(tuningJobFromVertex, "tuningJobFromVertex");
    __name(listTuningJobsResponseFromVertex, "listTuningJobsResponseFromVertex");
    Tunings = class extends BaseModule {
      static {
        __name(this, "Tunings");
      }
      constructor(apiClient) {
        super();
        this.apiClient = apiClient;
        this.get = async (params) => {
          return await this.getInternal(params);
        };
        this.list = async (params = {}) => {
          return new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params);
        };
        this.tune = async (params) => {
          if (this.apiClient.isVertexAI()) {
            if (params.baseModel.startsWith("projects/")) {
              const preTunedModel = {
                tunedModelName: params.baseModel
              };
              const paramsPrivate = Object.assign(Object.assign({}, params), { preTunedModel });
              paramsPrivate.baseModel = void 0;
              return await this.tuneInternal(paramsPrivate);
            } else {
              const paramsPrivate = Object.assign({}, params);
              return await this.tuneInternal(paramsPrivate);
            }
          } else {
            const paramsPrivate = Object.assign({}, params);
            const operation = await this.tuneMldevInternal(paramsPrivate);
            let tunedModelName = "";
            if (operation["metadata"] !== void 0 && operation["metadata"]["tunedModel"] !== void 0) {
              tunedModelName = operation["metadata"]["tunedModel"];
            } else if (operation["name"] !== void 0 && operation["name"].includes("/operations/")) {
              tunedModelName = operation["name"].split("/operations/")[0];
            }
            const tuningJob = {
              name: tunedModelName,
              state: JobState.JOB_STATE_QUEUED
            };
            return tuningJob;
          }
        };
      }
      async getInternal(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = getTuningJobParametersToVertex(params);
          path108 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = tuningJobFromVertex(apiResponse);
            return resp;
          });
        } else {
          const body = getTuningJobParametersToMldev(params);
          path108 = formatMap("{name}", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = tuningJobFromMldev(apiResponse);
            return resp;
          });
        }
      }
      async listInternal(params) {
        var _a6, _b2, _c2, _d;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = listTuningJobsParametersToVertex(params);
          path108 = formatMap("tuningJobs", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = listTuningJobsResponseFromVertex(apiResponse);
            const typedResp = new ListTuningJobsResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        } else {
          const body = listTuningJobsParametersToMldev(params);
          path108 = formatMap("tunedModels", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "GET",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = listTuningJobsResponseFromMldev(apiResponse);
            const typedResp = new ListTuningJobsResponse();
            Object.assign(typedResp, resp);
            return typedResp;
          });
        }
      }
      /**
       * Cancels a tuning job.
       *
       * @param params - The parameters for the cancel request.
       * @return The empty response returned by the API.
       *
       * @example
       * ```ts
       * await ai.tunings.cancel({name: '...'}); // The server-generated resource name.
       * ```
       */
      async cancel(params) {
        var _a6, _b2, _c2, _d;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = cancelTuningJobParametersToVertex(params);
          path108 = formatMap("{name}:cancel", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          await this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          });
        } else {
          const body = cancelTuningJobParametersToMldev(params);
          path108 = formatMap("{name}:cancel", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          await this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
            abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal
          });
        }
      }
      async tuneInternal(params) {
        var _a6, _b2;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body = createTuningJobParametersPrivateToVertex(params);
          path108 = formatMap("tuningJobs", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = tuningJobFromVertex(apiResponse);
            return resp;
          });
        } else {
          throw new Error("This method is only supported by the Vertex AI.");
        }
      }
      async tuneMldevInternal(params) {
        var _a6, _b2;
        let response;
        let path108 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body = createTuningJobParametersPrivateToMldev(params);
          path108 = formatMap("tunedModels", body["_url"]);
          queryParams = body["_query"];
          delete body["config"];
          delete body["_url"];
          delete body["_query"];
          response = this.apiClient.request({
            path: path108,
            queryParams,
            body: JSON.stringify(body),
            httpMethod: "POST",
            httpOptions: (_a6 = params.config) === null || _a6 === void 0 ? void 0 : _a6.httpOptions,
            abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
          }).then((httpResponse) => {
            return httpResponse.json().then((jsonResponse) => {
              const response2 = jsonResponse;
              response2.sdkHttpResponse = {
                headers: httpResponse.headers
              };
              return response2;
            });
          });
          return response.then((apiResponse) => {
            const resp = tuningOperationFromMldev(apiResponse);
            return resp;
          });
        }
      }
    };
    MAX_CHUNK_SIZE = 1024 * 1024 * 8;
    MAX_RETRY_COUNT = 3;
    INITIAL_RETRY_DELAY_MS = 1e3;
    DELAY_MULTIPLIER = 2;
    X_GOOG_UPLOAD_STATUS_HEADER_FIELD = "x-goog-upload-status";
    __name(uploadBlob, "uploadBlob");
    __name(getBlobStat, "getBlobStat");
    __name(sleep, "sleep");
    NodeUploader = class {
      static {
        __name(this, "NodeUploader");
      }
      async stat(file) {
        const fileStat = { size: 0, type: void 0 };
        if (typeof file === "string") {
          const originalStat = await fs3.stat(file);
          fileStat.size = originalStat.size;
          fileStat.type = this.inferMimeType(file);
          return fileStat;
        } else {
          return await getBlobStat(file);
        }
      }
      async upload(file, uploadUrl, apiClient) {
        if (typeof file === "string") {
          return await this.uploadFileFromPath(file, uploadUrl, apiClient);
        } else {
          return uploadBlob(file, uploadUrl, apiClient);
        }
      }
      /**
       * Infers the MIME type of a file based on its extension.
       *
       * @param filePath The path to the file.
       * @returns The MIME type of the file, or undefined if it cannot be inferred.
       */
      inferMimeType(filePath) {
        const fileExtension = filePath.slice(filePath.lastIndexOf(".") + 1);
        const mimeTypes = {
          "aac": "audio/aac",
          "abw": "application/x-abiword",
          "arc": "application/x-freearc",
          "avi": "video/x-msvideo",
          "azw": "application/vnd.amazon.ebook",
          "bin": "application/octet-stream",
          "bmp": "image/bmp",
          "bz": "application/x-bzip",
          "bz2": "application/x-bzip2",
          "csh": "application/x-csh",
          "css": "text/css",
          "csv": "text/csv",
          "doc": "application/msword",
          "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
          "eot": "application/vnd.ms-fontobject",
          "epub": "application/epub+zip",
          "gz": "application/gzip",
          "gif": "image/gif",
          "htm": "text/html",
          "html": "text/html",
          "ico": "image/vnd.microsoft.icon",
          "ics": "text/calendar",
          "jar": "application/java-archive",
          "jpeg": "image/jpeg",
          "jpg": "image/jpeg",
          "js": "text/javascript",
          "json": "application/json",
          "jsonld": "application/ld+json",
          "kml": "application/vnd.google-earth.kml+xml",
          "kmz": "application/vnd.google-earth.kmz+xml",
          "mjs": "text/javascript",
          "mp3": "audio/mpeg",
          "mp4": "video/mp4",
          "mpeg": "video/mpeg",
          "mpkg": "application/vnd.apple.installer+xml",
          "odt": "application/vnd.oasis.opendocument.text",
          "oga": "audio/ogg",
          "ogv": "video/ogg",
          "ogx": "application/ogg",
          "opus": "audio/opus",
          "otf": "font/otf",
          "png": "image/png",
          "pdf": "application/pdf",
          "php": "application/x-httpd-php",
          "ppt": "application/vnd.ms-powerpoint",
          "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
          "rar": "application/vnd.rar",
          "rtf": "application/rtf",
          "sh": "application/x-sh",
          "svg": "image/svg+xml",
          "swf": "application/x-shockwave-flash",
          "tar": "application/x-tar",
          "tif": "image/tiff",
          "tiff": "image/tiff",
          "ts": "video/mp2t",
          "ttf": "font/ttf",
          "txt": "text/plain",
          "vsd": "application/vnd.visio",
          "wav": "audio/wav",
          "weba": "audio/webm",
          "webm": "video/webm",
          "webp": "image/webp",
          "woff": "font/woff",
          "woff2": "font/woff2",
          "xhtml": "application/xhtml+xml",
          "xls": "application/vnd.ms-excel",
          "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          "xml": "application/xml",
          "xul": "application/vnd.mozilla.xul+xml",
          "zip": "application/zip",
          "3gp": "video/3gpp",
          "3g2": "video/3gpp2",
          "7z": "application/x-7z-compressed"
        };
        const mimeType = mimeTypes[fileExtension.toLowerCase()];
        return mimeType;
      }
      async uploadFileFromPath(file, uploadUrl, apiClient) {
        var _a6, _b2, _c2;
        let fileSize = 0;
        let offset = 0;
        let response = new HttpResponse(new Response());
        let uploadCommand = "upload";
        let fileHandle;
        try {
          fileHandle = await fs3.open(file, "r");
          if (!fileHandle) {
            throw new Error(`Failed to open file`);
          }
          fileSize = (await fileHandle.stat()).size;
          while (offset < fileSize) {
            const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);
            if (offset + chunkSize >= fileSize) {
              uploadCommand += ", finalize";
            }
            const buffer = new Uint8Array(chunkSize);
            const { bytesRead } = await fileHandle.read(buffer, 0, chunkSize, offset);
            if (bytesRead !== chunkSize) {
              throw new Error(`Failed to read ${chunkSize} bytes from file at offset ${offset}. bytes actually read: ${bytesRead}`);
            }
            const chunk = new Blob([buffer]);
            let retryCount = 0;
            let currentDelayMs = INITIAL_RETRY_DELAY_MS;
            while (retryCount < MAX_RETRY_COUNT) {
              response = await apiClient.request({
                path: "",
                body: chunk,
                httpMethod: "POST",
                httpOptions: {
                  apiVersion: "",
                  baseUrl: uploadUrl,
                  headers: {
                    "X-Goog-Upload-Command": uploadCommand,
                    "X-Goog-Upload-Offset": String(offset),
                    "Content-Length": String(bytesRead)
                  }
                }
              });
              if ((_a6 = response === null || response === void 0 ? void 0 : response.headers) === null || _a6 === void 0 ? void 0 : _a6[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {
                break;
              }
              retryCount++;
              await sleep(currentDelayMs);
              currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;
            }
            offset += bytesRead;
            if (((_b2 = response === null || response === void 0 ? void 0 : response.headers) === null || _b2 === void 0 ? void 0 : _b2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "active") {
              break;
            }
            if (fileSize <= offset) {
              throw new Error("All content has been uploaded, but the upload status is not finalized.");
            }
          }
          const responseJson = await (response === null || response === void 0 ? void 0 : response.json());
          if (((_c2 = response === null || response === void 0 ? void 0 : response.headers) === null || _c2 === void 0 ? void 0 : _c2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "final") {
            throw new Error("Failed to upload file: Upload status is not finalized.");
          }
          return responseJson["file"];
        } finally {
          if (fileHandle) {
            await fileHandle.close();
          }
        }
      }
    };
    LANGUAGE_LABEL_PREFIX = "gl-node/";
    GoogleGenAI = class {
      static {
        __name(this, "GoogleGenAI");
      }
      constructor(options2) {
        var _a6, _b2, _c2, _d, _e, _f;
        if ((options2.project || options2.location) && options2.apiKey) {
          throw new Error("Project/location and API key are mutually exclusive in the client initializer.");
        }
        this.vertexai = (_b2 = (_a6 = options2.vertexai) !== null && _a6 !== void 0 ? _a6 : getBooleanEnv("GOOGLE_GENAI_USE_VERTEXAI")) !== null && _b2 !== void 0 ? _b2 : false;
        const envApiKey = getApiKeyFromEnv();
        const envProject = getEnv("GOOGLE_CLOUD_PROJECT");
        const envLocation = getEnv("GOOGLE_CLOUD_LOCATION");
        this.apiKey = (_c2 = options2.apiKey) !== null && _c2 !== void 0 ? _c2 : envApiKey;
        this.project = (_d = options2.project) !== null && _d !== void 0 ? _d : envProject;
        this.location = (_e = options2.location) !== null && _e !== void 0 ? _e : envLocation;
        if (options2.vertexai) {
          if ((_f = options2.googleAuthOptions) === null || _f === void 0 ? void 0 : _f.credentials) {
            console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable.");
            this.apiKey = void 0;
          }
          if ((envProject || envLocation) && options2.apiKey) {
            console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables.");
            this.project = void 0;
            this.location = void 0;
          } else if ((options2.project || options2.location) && envApiKey) {
            console.debug("The user provided project/location will take precedence over the API key from the environment variables.");
            this.apiKey = void 0;
          } else if ((envProject || envLocation) && envApiKey) {
            console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables.");
            this.apiKey = void 0;
          }
        }
        const baseUrl = getBaseUrl(options2.httpOptions, options2.vertexai, getEnv("GOOGLE_VERTEX_BASE_URL"), getEnv("GOOGLE_GEMINI_BASE_URL"));
        if (baseUrl) {
          if (options2.httpOptions) {
            options2.httpOptions.baseUrl = baseUrl;
          } else {
            options2.httpOptions = { baseUrl };
          }
        }
        this.apiVersion = options2.apiVersion;
        const auth2 = new NodeAuth({
          apiKey: this.apiKey,
          googleAuthOptions: options2.googleAuthOptions
        });
        this.apiClient = new ApiClient({
          auth: auth2,
          project: this.project,
          location: this.location,
          apiVersion: this.apiVersion,
          apiKey: this.apiKey,
          vertexai: this.vertexai,
          httpOptions: options2.httpOptions,
          userAgentExtra: LANGUAGE_LABEL_PREFIX + process.version,
          uploader: new NodeUploader(),
          downloader: new NodeDownloader()
        });
        this.models = new Models(this.apiClient);
        this.live = new Live(this.apiClient, auth2, new NodeWebSocketFactory());
        this.batches = new Batches(this.apiClient);
        this.chats = new Chats(this.models, this.apiClient);
        this.caches = new Caches(this.apiClient);
        this.files = new Files(this.apiClient);
        this.operations = new Operations(this.apiClient);
        this.authTokens = new Tokens(this.apiClient);
        this.tunings = new Tunings(this.apiClient);
      }
    };
    __name(getEnv, "getEnv");
    __name(getBooleanEnv, "getBooleanEnv");
    __name(stringToBoolean, "stringToBoolean");
    __name(getApiKeyFromEnv, "getApiKeyFromEnv");
  }
});

// node_modules/is-docker/index.js
import fs4 from "node:fs";
function hasDockerEnv() {
  try {
    fs4.statSync("/.dockerenv");
    return true;
  } catch {
    return false;
  }
}
function hasDockerCGroup() {
  try {
    return fs4.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
  } catch {
    return false;
  }
}
function isDocker() {
  if (isDockerCached === void 0) {
    isDockerCached = hasDockerEnv() || hasDockerCGroup();
  }
  return isDockerCached;
}
var isDockerCached;
var init_is_docker = __esm({
  "node_modules/is-docker/index.js"() {
    init_esbuild_shims();
    __name(hasDockerEnv, "hasDockerEnv");
    __name(hasDockerCGroup, "hasDockerCGroup");
    __name(isDocker, "isDocker");
  }
});

// node_modules/is-inside-container/index.js
import fs5 from "node:fs";
function isInsideContainer() {
  if (cachedResult === void 0) {
    cachedResult = hasContainerEnv() || isDocker();
  }
  return cachedResult;
}
var cachedResult, hasContainerEnv;
var init_is_inside_container = __esm({
  "node_modules/is-inside-container/index.js"() {
    init_esbuild_shims();
    init_is_docker();
    hasContainerEnv = /* @__PURE__ */ __name(() => {
      try {
        fs5.statSync("/run/.containerenv");
        return true;
      } catch {
        return false;
      }
    }, "hasContainerEnv");
    __name(isInsideContainer, "isInsideContainer");
  }
});

// node_modules/is-wsl/index.js
import process13 from "node:process";
import os3 from "node:os";
import fs6 from "node:fs";
var isWsl, is_wsl_default;
var init_is_wsl = __esm({
  "node_modules/is-wsl/index.js"() {
    init_esbuild_shims();
    init_is_inside_container();
    isWsl = /* @__PURE__ */ __name(() => {
      if (process13.platform !== "linux") {
        return false;
      }
      if (os3.release().toLowerCase().includes("microsoft")) {
        if (isInsideContainer()) {
          return false;
        }
        return true;
      }
      try {
        return fs6.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isInsideContainer() : false;
      } catch {
        return false;
      }
    }, "isWsl");
    is_wsl_default = process13.env.__IS_WSL_TEST__ ? isWsl : isWsl();
  }
});

// node_modules/define-lazy-prop/index.js
function defineLazyProperty(object, propertyName, valueGetter) {
  const define2 = /* @__PURE__ */ __name((value) => Object.defineProperty(object, propertyName, { value, enumerable: true, writable: true }), "define");
  Object.defineProperty(object, propertyName, {
    configurable: true,
    enumerable: true,
    get() {
      const result = valueGetter();
      define2(result);
      return result;
    },
    set(value) {
      define2(value);
    }
  });
  return object;
}
var init_define_lazy_prop = __esm({
  "node_modules/define-lazy-prop/index.js"() {
    init_esbuild_shims();
    __name(defineLazyProperty, "defineLazyProperty");
  }
});

// node_modules/default-browser-id/index.js
import { promisify } from "node:util";
import process14 from "node:process";
import { execFile } from "node:child_process";
async function defaultBrowserId() {
  if (process14.platform !== "darwin") {
    throw new Error("macOS only");
  }
  const { stdout } = await execFileAsync("defaults", ["read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers"]);
  const match2 = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout);
  return match2?.groups.id ?? "com.apple.Safari";
}
var execFileAsync;
var init_default_browser_id = __esm({
  "node_modules/default-browser-id/index.js"() {
    init_esbuild_shims();
    execFileAsync = promisify(execFile);
    __name(defaultBrowserId, "defaultBrowserId");
  }
});

// node_modules/run-applescript/index.js
import process15 from "node:process";
import { promisify as promisify2 } from "node:util";
import { execFile as execFile2, execFileSync } from "node:child_process";
async function runAppleScript(script, { humanReadableOutput = true } = {}) {
  if (process15.platform !== "darwin") {
    throw new Error("macOS only");
  }
  const outputArguments = humanReadableOutput ? [] : ["-ss"];
  const { stdout } = await execFileAsync2("osascript", ["-e", script, outputArguments]);
  return stdout.trim();
}
var execFileAsync2;
var init_run_applescript = __esm({
  "node_modules/run-applescript/index.js"() {
    init_esbuild_shims();
    execFileAsync2 = promisify2(execFile2);
    __name(runAppleScript, "runAppleScript");
  }
});

// node_modules/bundle-name/index.js
async function bundleName(bundleId) {
  return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
}
var init_bundle_name = __esm({
  "node_modules/bundle-name/index.js"() {
    init_esbuild_shims();
    init_run_applescript();
    __name(bundleName, "bundleName");
  }
});

// node_modules/default-browser/windows.js
import { promisify as promisify3 } from "node:util";
import { execFile as execFile3 } from "node:child_process";
async function defaultBrowser(_execFileAsync = execFileAsync3) {
  const { stdout } = await _execFileAsync("reg", [
    "QUERY",
    " HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
    "/v",
    "ProgId"
  ]);
  const match2 = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
  if (!match2) {
    throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
  }
  const { id } = match2.groups;
  const browser = windowsBrowserProgIds[id];
  if (!browser) {
    throw new UnknownBrowserError(`Unknown browser ID: ${id}`);
  }
  return browser;
}
var execFileAsync3, windowsBrowserProgIds, UnknownBrowserError;
var init_windows = __esm({
  "node_modules/default-browser/windows.js"() {
    init_esbuild_shims();
    execFileAsync3 = promisify3(execFile3);
    windowsBrowserProgIds = {
      AppXq0fevzme2pys62n3e0fbqa7peapykr8v: { name: "Edge", id: "com.microsoft.edge.old" },
      MSEdgeDHTML: { name: "Edge", id: "com.microsoft.edge" },
      // On macOS, it's "com.microsoft.edgemac"
      MSEdgeHTM: { name: "Edge", id: "com.microsoft.edge" },
      // Newer Edge/Win10 releases
      "IE.HTTP": { name: "Internet Explorer", id: "com.microsoft.ie" },
      FirefoxURL: { name: "Firefox", id: "org.mozilla.firefox" },
      ChromeHTML: { name: "Chrome", id: "com.google.chrome" },
      BraveHTML: { name: "Brave", id: "com.brave.Browser" },
      BraveBHTML: { name: "Brave Beta", id: "com.brave.Browser.beta" },
      BraveSSHTM: { name: "Brave Nightly", id: "com.brave.Browser.nightly" }
    };
    UnknownBrowserError = class extends Error {
      static {
        __name(this, "UnknownBrowserError");
      }
    };
    __name(defaultBrowser, "defaultBrowser");
  }
});

// node_modules/default-browser/index.js
import { promisify as promisify4 } from "node:util";
import process16 from "node:process";
import { execFile as execFile4 } from "node:child_process";
async function defaultBrowser2() {
  if (process16.platform === "darwin") {
    const id = await defaultBrowserId();
    const name3 = await bundleName(id);
    return { name: name3, id };
  }
  if (process16.platform === "linux") {
    const { stdout } = await execFileAsync4("xdg-mime", ["query", "default", "x-scheme-handler/http"]);
    const id = stdout.trim();
    const name3 = titleize(id.replace(/.desktop$/, "").replace("-", " "));
    return { name: name3, id };
  }
  if (process16.platform === "win32") {
    return defaultBrowser();
  }
  throw new Error("Only macOS, Linux, and Windows are supported");
}
var execFileAsync4, titleize;
var init_default_browser = __esm({
  "node_modules/default-browser/index.js"() {
    init_esbuild_shims();
    init_default_browser_id();
    init_bundle_name();
    init_windows();
    execFileAsync4 = promisify4(execFile4);
    titleize = /* @__PURE__ */ __name((string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase()), "titleize");
    __name(defaultBrowser2, "defaultBrowser");
  }
});

// node_modules/open/index.js
import process17 from "node:process";
import { Buffer as Buffer2 } from "node:buffer";
import path2 from "node:path";
import { fileURLToPath as fileURLToPath2 } from "node:url";
import util from "node:util";
import childProcess from "node:child_process";
import fs7, { constants as fsConstants } from "node:fs/promises";
async function getWindowsDefaultBrowserFromWsl() {
  const powershellPath = await getPowershellPathFromWsl();
  const rawCommand = '(Get-ItemProperty -Path "HKCU:\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice").ProgId';
  const encodedCommand = Buffer2.from(rawCommand, "utf16le").toString("base64");
  const { stdout } = await execFile5(
    powershellPath,
    [
      "-NoProfile",
      "-NonInteractive",
      "-ExecutionPolicy",
      "Bypass",
      "-EncodedCommand",
      encodedCommand
    ],
    { encoding: "utf8" }
  );
  const progId = stdout.trim();
  const browserMap = {
    ChromeHTML: "com.google.chrome",
    MSEdgeHTM: "com.microsoft.edge",
    FirefoxURL: "org.mozilla.firefox"
  };
  return browserMap[progId] ? { id: browserMap[progId] } : {};
}
function detectArchBinary(binary) {
  if (typeof binary === "string" || Array.isArray(binary)) {
    return binary;
  }
  const { [arch]: archBinary } = binary;
  if (!archBinary) {
    throw new Error(`${arch} is not supported`);
  }
  return archBinary;
}
function detectPlatformBinary({ [platform2]: platformBinary }, { wsl }) {
  if (wsl && is_wsl_default) {
    return detectArchBinary(wsl);
  }
  if (!platformBinary) {
    throw new Error(`${platform2} is not supported`);
  }
  return detectArchBinary(platformBinary);
}
var execFile5, __dirname2, localXdgOpenPath, platform2, arch, getWslDrivesMountPoint, getPowershellPathFromWsl, pTryEach, baseOpen, open2, apps, open_default;
var init_open = __esm({
  "node_modules/open/index.js"() {
    init_esbuild_shims();
    init_is_wsl();
    init_define_lazy_prop();
    init_default_browser();
    init_is_inside_container();
    execFile5 = util.promisify(childProcess.execFile);
    __dirname2 = path2.dirname(fileURLToPath2(import.meta.url));
    localXdgOpenPath = path2.join(__dirname2, "xdg-open");
    ({ platform: platform2, arch } = process17);
    getWslDrivesMountPoint = /* @__PURE__ */ (() => {
      const defaultMountPoint = "/mnt/";
      let mountPoint;
      return async function() {
        if (mountPoint) {
          return mountPoint;
        }
        const configFilePath2 = "/etc/wsl.conf";
        let isConfigFileExists = false;
        try {
          await fs7.access(configFilePath2, fsConstants.F_OK);
          isConfigFileExists = true;
        } catch {
        }
        if (!isConfigFileExists) {
          return defaultMountPoint;
        }
        const configContent = await fs7.readFile(configFilePath2, { encoding: "utf8" });
        const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
        if (!configMountPoint) {
          return defaultMountPoint;
        }
        mountPoint = configMountPoint.groups.mountPoint.trim();
        mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
        return mountPoint;
      };
    })();
    getPowershellPathFromWsl = /* @__PURE__ */ __name(async () => {
      const mountPoint = await getWslDrivesMountPoint();
      return `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
    }, "getPowershellPathFromWsl");
    __name(getWindowsDefaultBrowserFromWsl, "getWindowsDefaultBrowserFromWsl");
    pTryEach = /* @__PURE__ */ __name(async (array, mapper) => {
      let latestError;
      for (const item of array) {
        try {
          return await mapper(item);
        } catch (error) {
          latestError = error;
        }
      }
      throw latestError;
    }, "pTryEach");
    baseOpen = /* @__PURE__ */ __name(async (options2) => {
      options2 = {
        wait: false,
        background: false,
        newInstance: false,
        allowNonzeroExitCode: false,
        ...options2
      };
      if (Array.isArray(options2.app)) {
        return pTryEach(options2.app, (singleApp) => baseOpen({
          ...options2,
          app: singleApp
        }));
      }
      let { name: app, arguments: appArguments = [] } = options2.app ?? {};
      appArguments = [...appArguments];
      if (Array.isArray(app)) {
        return pTryEach(app, (appName) => baseOpen({
          ...options2,
          app: {
            name: appName,
            arguments: appArguments
          }
        }));
      }
      if (app === "browser" || app === "browserPrivate") {
        const ids = {
          "com.google.chrome": "chrome",
          "google-chrome.desktop": "chrome",
          "org.mozilla.firefox": "firefox",
          "firefox.desktop": "firefox",
          "com.microsoft.msedge": "edge",
          "com.microsoft.edge": "edge",
          "com.microsoft.edgemac": "edge",
          "microsoft-edge.desktop": "edge"
        };
        const flags = {
          chrome: "--incognito",
          firefox: "--private-window",
          edge: "--inPrivate"
        };
        const browser = is_wsl_default ? await getWindowsDefaultBrowserFromWsl() : await defaultBrowser2();
        if (browser.id in ids) {
          const browserName = ids[browser.id];
          if (app === "browserPrivate") {
            appArguments.push(flags[browserName]);
          }
          return baseOpen({
            ...options2,
            app: {
              name: apps[browserName],
              arguments: appArguments
            }
          });
        }
        throw new Error(`${browser.name} is not supported as a default browser`);
      }
      let command2;
      const cliArguments = [];
      const childProcessOptions = {};
      if (platform2 === "darwin") {
        command2 = "open";
        if (options2.wait) {
          cliArguments.push("--wait-apps");
        }
        if (options2.background) {
          cliArguments.push("--background");
        }
        if (options2.newInstance) {
          cliArguments.push("--new");
        }
        if (app) {
          cliArguments.push("-a", app);
        }
      } else if (platform2 === "win32" || is_wsl_default && !isInsideContainer() && !app) {
        command2 = is_wsl_default ? await getPowershellPathFromWsl() : `${process17.env.SYSTEMROOT || process17.env.windir || "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell`;
        cliArguments.push(
          "-NoProfile",
          "-NonInteractive",
          "-ExecutionPolicy",
          "Bypass",
          "-EncodedCommand"
        );
        if (!is_wsl_default) {
          childProcessOptions.windowsVerbatimArguments = true;
        }
        const encodedArguments = ["Start"];
        if (options2.wait) {
          encodedArguments.push("-Wait");
        }
        if (app) {
          encodedArguments.push(`"\`"${app}\`""`);
          if (options2.target) {
            appArguments.push(options2.target);
          }
        } else if (options2.target) {
          encodedArguments.push(`"${options2.target}"`);
        }
        if (appArguments.length > 0) {
          appArguments = appArguments.map((argument) => `"\`"${argument}\`""`);
          encodedArguments.push("-ArgumentList", appArguments.join(","));
        }
        options2.target = Buffer2.from(encodedArguments.join(" "), "utf16le").toString("base64");
      } else {
        if (app) {
          command2 = app;
        } else {
          const isBundled = !__dirname2 || __dirname2 === "/";
          let exeLocalXdgOpen = false;
          try {
            await fs7.access(localXdgOpenPath, fsConstants.X_OK);
            exeLocalXdgOpen = true;
          } catch {
          }
          const useSystemXdgOpen = process17.versions.electron ?? (platform2 === "android" || isBundled || !exeLocalXdgOpen);
          command2 = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath;
        }
        if (appArguments.length > 0) {
          cliArguments.push(...appArguments);
        }
        if (!options2.wait) {
          childProcessOptions.stdio = "ignore";
          childProcessOptions.detached = true;
        }
      }
      if (platform2 === "darwin" && appArguments.length > 0) {
        cliArguments.push("--args", ...appArguments);
      }
      if (options2.target) {
        cliArguments.push(options2.target);
      }
      const subprocess = childProcess.spawn(command2, cliArguments, childProcessOptions);
      if (options2.wait) {
        return new Promise((resolve24, reject) => {
          subprocess.once("error", reject);
          subprocess.once("close", (exitCode) => {
            if (!options2.allowNonzeroExitCode && exitCode > 0) {
              reject(new Error(`Exited with code ${exitCode}`));
              return;
            }
            resolve24(subprocess);
          });
        });
      }
      subprocess.unref();
      return subprocess;
    }, "baseOpen");
    open2 = /* @__PURE__ */ __name((target, options2) => {
      if (typeof target !== "string") {
        throw new TypeError("Expected a `target`");
      }
      return baseOpen({
        ...options2,
        target
      });
    }, "open");
    __name(detectArchBinary, "detectArchBinary");
    __name(detectPlatformBinary, "detectPlatformBinary");
    apps = {};
    defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
      darwin: "google chrome",
      win32: "chrome",
      linux: ["google-chrome", "google-chrome-stable", "chromium"]
    }, {
      wsl: {
        ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
        x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
      }
    }));
    defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
      darwin: "firefox",
      win32: "C:\\Program Files\\Mozilla Firefox\\firefox.exe",
      linux: "firefox"
    }, {
      wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe"
    }));
    defineLazyProperty(apps, "edge", () => detectPlatformBinary({
      darwin: "microsoft edge",
      win32: "msedge",
      linux: ["microsoft-edge", "microsoft-edge-dev"]
    }, {
      wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
    }));
    defineLazyProperty(apps, "browser", () => "browser");
    defineLazyProperty(apps, "browserPrivate", () => "browserPrivate");
    open_default = open2;
  }
});

// packages/core/dist/src/config/storage.js
import * as path3 from "node:path";
import * as os4 from "node:os";
import * as crypto6 from "node:crypto";
import * as fs8 from "node:fs";
var QWEN_DIR, GOOGLE_ACCOUNTS_FILENAME, OAUTH_FILE, TMP_DIR_NAME, BIN_DIR_NAME, Storage;
var init_storage = __esm({
  "packages/core/dist/src/config/storage.js"() {
    "use strict";
    init_esbuild_shims();
    QWEN_DIR = ".qwen";
    GOOGLE_ACCOUNTS_FILENAME = "google_accounts.json";
    OAUTH_FILE = "oauth_creds.json";
    TMP_DIR_NAME = "tmp";
    BIN_DIR_NAME = "bin";
    Storage = class _Storage {
      static {
        __name(this, "Storage");
      }
      targetDir;
      constructor(targetDir) {
        this.targetDir = targetDir;
      }
      static getGlobalQwenDir() {
        const homeDir = os4.homedir();
        if (!homeDir) {
          return path3.join(os4.tmpdir(), ".qwen");
        }
        return path3.join(homeDir, QWEN_DIR);
      }
      static getMcpOAuthTokensPath() {
        return path3.join(_Storage.getGlobalQwenDir(), "mcp-oauth-tokens.json");
      }
      static getGlobalSettingsPath() {
        return path3.join(_Storage.getGlobalQwenDir(), "settings.json");
      }
      static getInstallationIdPath() {
        return path3.join(_Storage.getGlobalQwenDir(), "installation_id");
      }
      static getGoogleAccountsPath() {
        return path3.join(_Storage.getGlobalQwenDir(), GOOGLE_ACCOUNTS_FILENAME);
      }
      static getUserCommandsDir() {
        return path3.join(_Storage.getGlobalQwenDir(), "commands");
      }
      static getGlobalMemoryFilePath() {
        return path3.join(_Storage.getGlobalQwenDir(), "memory.md");
      }
      static getGlobalTempDir() {
        return path3.join(_Storage.getGlobalQwenDir(), TMP_DIR_NAME);
      }
      static getGlobalBinDir() {
        return path3.join(_Storage.getGlobalQwenDir(), BIN_DIR_NAME);
      }
      getQwenDir() {
        return path3.join(this.targetDir, QWEN_DIR);
      }
      getProjectTempDir() {
        const hash = this.getFilePathHash(this.getProjectRoot());
        const tempDir = _Storage.getGlobalTempDir();
        return path3.join(tempDir, hash);
      }
      ensureProjectTempDirExists() {
        fs8.mkdirSync(this.getProjectTempDir(), { recursive: true });
      }
      static getOAuthCredsPath() {
        return path3.join(_Storage.getGlobalQwenDir(), OAUTH_FILE);
      }
      getProjectRoot() {
        return this.targetDir;
      }
      getFilePathHash(filePath) {
        return crypto6.createHash("sha256").update(filePath).digest("hex");
      }
      getHistoryDir() {
        const hash = this.getFilePathHash(this.getProjectRoot());
        const historyDir = path3.join(_Storage.getGlobalQwenDir(), "history");
        return path3.join(historyDir, hash);
      }
      getWorkspaceSettingsPath() {
        return path3.join(this.getQwenDir(), "settings.json");
      }
      getProjectCommandsDir() {
        return path3.join(this.getQwenDir(), "commands");
      }
      getProjectTempCheckpointsDir() {
        return path3.join(this.getProjectTempDir(), "checkpoints");
      }
      getExtensionsDir() {
        return path3.join(this.getQwenDir(), "extensions");
      }
      getExtensionsConfigPath() {
        return path3.join(this.getExtensionsDir(), "qwen-extension.json");
      }
      getHistoryFilePath() {
        return path3.join(this.getProjectTempDir(), "shell_history");
      }
    };
  }
});

// packages/core/dist/src/utils/userAccountManager.js
import path4 from "node:path";
import { promises as fsp, readFileSync as readFileSync2 } from "node:fs";
var UserAccountManager;
var init_userAccountManager = __esm({
  "packages/core/dist/src/utils/userAccountManager.js"() {
    "use strict";
    init_esbuild_shims();
    init_storage();
    UserAccountManager = class {
      static {
        __name(this, "UserAccountManager");
      }
      getGoogleAccountsCachePath() {
        return Storage.getGoogleAccountsPath();
      }
      /**
       * Parses and validates the string content of an accounts file.
       * @param content The raw string content from the file.
       * @returns A valid UserAccounts object.
       */
      parseAndValidateAccounts(content) {
        const defaultState = { active: null, old: [] };
        if (!content.trim()) {
          return defaultState;
        }
        const parsed = JSON.parse(content);
        if (typeof parsed !== "object" || parsed === null) {
          console.log("Invalid accounts file schema, starting fresh.");
          return defaultState;
        }
        const { active, old } = parsed;
        const isValid2 = (active === void 0 || active === null || typeof active === "string") && (old === void 0 || Array.isArray(old) && old.every((i) => typeof i === "string"));
        if (!isValid2) {
          console.log("Invalid accounts file schema, starting fresh.");
          return defaultState;
        }
        return {
          active: parsed.active ?? null,
          old: parsed.old ?? []
        };
      }
      readAccountsSync(filePath) {
        const defaultState = { active: null, old: [] };
        try {
          const content = readFileSync2(filePath, "utf-8");
          return this.parseAndValidateAccounts(content);
        } catch (error) {
          if (error instanceof Error && "code" in error && error.code === "ENOENT") {
            return defaultState;
          }
          console.log("Error during sync read of accounts, starting fresh.", error);
          return defaultState;
        }
      }
      async readAccounts(filePath) {
        const defaultState = { active: null, old: [] };
        try {
          const content = await fsp.readFile(filePath, "utf-8");
          return this.parseAndValidateAccounts(content);
        } catch (error) {
          if (error instanceof Error && "code" in error && error.code === "ENOENT") {
            return defaultState;
          }
          console.log("Could not parse accounts file, starting fresh.", error);
          return defaultState;
        }
      }
      async cacheGoogleAccount(email) {
        const filePath = this.getGoogleAccountsCachePath();
        await fsp.mkdir(path4.dirname(filePath), { recursive: true });
        const accounts = await this.readAccounts(filePath);
        if (accounts.active && accounts.active !== email) {
          if (!accounts.old.includes(accounts.active)) {
            accounts.old.push(accounts.active);
          }
        }
        accounts.old = accounts.old.filter((oldEmail) => oldEmail !== email);
        accounts.active = email;
        await fsp.writeFile(filePath, JSON.stringify(accounts, null, 2), "utf-8");
      }
      getCachedGoogleAccount() {
        const filePath = this.getGoogleAccountsCachePath();
        const accounts = this.readAccountsSync(filePath);
        return accounts.active;
      }
      getLifetimeGoogleAccounts() {
        const filePath = this.getGoogleAccountsCachePath();
        const accounts = this.readAccountsSync(filePath);
        const allAccounts = new Set(accounts.old);
        if (accounts.active) {
          allAccounts.add(accounts.active);
        }
        return allAccounts.size;
      }
      async clearCachedGoogleAccount() {
        const filePath = this.getGoogleAccountsCachePath();
        const accounts = await this.readAccounts(filePath);
        if (accounts.active) {
          if (!accounts.old.includes(accounts.active)) {
            accounts.old.push(accounts.active);
          }
          accounts.active = null;
        }
        await fsp.writeFile(filePath, JSON.stringify(accounts, null, 2), "utf-8");
      }
    };
  }
});

// packages/core/dist/src/mcp/token-storage/base-token-storage.js
var BaseTokenStorage;
var init_base_token_storage = __esm({
  "packages/core/dist/src/mcp/token-storage/base-token-storage.js"() {
    "use strict";
    init_esbuild_shims();
    BaseTokenStorage = class {
      static {
        __name(this, "BaseTokenStorage");
      }
      serviceName;
      constructor(serviceName) {
        this.serviceName = serviceName;
      }
      validateCredentials(credentials) {
        if (!credentials.serverName) {
          throw new Error("Server name is required");
        }
        if (!credentials.token) {
          throw new Error("Token is required");
        }
        if (!credentials.token.accessToken) {
          throw new Error("Access token is required");
        }
        if (!credentials.token.tokenType) {
          throw new Error("Token type is required");
        }
      }
      isTokenExpired(credentials) {
        if (!credentials.token.expiresAt) {
          return false;
        }
        const bufferMs = 5 * 60 * 1e3;
        return Date.now() > credentials.token.expiresAt - bufferMs;
      }
      sanitizeServerName(serverName) {
        return serverName.replace(/[^a-zA-Z0-9-_.]/g, "_");
      }
    };
  }
});

// packages/core/dist/src/mcp/token-storage/file-token-storage.js
import { promises as fs9 } from "node:fs";
import * as path5 from "node:path";
import * as os5 from "node:os";
import * as crypto7 from "node:crypto";
var FileTokenStorage;
var init_file_token_storage = __esm({
  "packages/core/dist/src/mcp/token-storage/file-token-storage.js"() {
    "use strict";
    init_esbuild_shims();
    init_base_token_storage();
    FileTokenStorage = class extends BaseTokenStorage {
      static {
        __name(this, "FileTokenStorage");
      }
      tokenFilePath;
      encryptionKey;
      constructor(serviceName) {
        super(serviceName);
        const configDir = path5.join(os5.homedir(), ".qwen");
        this.tokenFilePath = path5.join(configDir, "mcp-oauth-tokens-v2.json");
        this.encryptionKey = this.deriveEncryptionKey();
      }
      deriveEncryptionKey() {
        const salt = `${os5.hostname()}-${os5.userInfo().username}-qwen-code`;
        return crypto7.scryptSync("qwen-code-oauth", salt, 32);
      }
      encrypt(text) {
        const iv = crypto7.randomBytes(16);
        const cipher = crypto7.createCipheriv("aes-256-gcm", this.encryptionKey, iv);
        let encrypted = cipher.update(text, "utf8", "hex");
        encrypted += cipher.final("hex");
        const authTag = cipher.getAuthTag();
        return iv.toString("hex") + ":" + authTag.toString("hex") + ":" + encrypted;
      }
      decrypt(encryptedData) {
        const parts = encryptedData.split(":");
        if (parts.length !== 3) {
          throw new Error("Invalid encrypted data format");
        }
        const iv = Buffer.from(parts[0], "hex");
        const authTag = Buffer.from(parts[1], "hex");
        const encrypted = parts[2];
        const decipher = crypto7.createDecipheriv("aes-256-gcm", this.encryptionKey, iv);
        decipher.setAuthTag(authTag);
        let decrypted = decipher.update(encrypted, "hex", "utf8");
        decrypted += decipher.final("utf8");
        return decrypted;
      }
      async ensureDirectoryExists() {
        const dir = path5.dirname(this.tokenFilePath);
        await fs9.mkdir(dir, { recursive: true, mode: 448 });
      }
      async loadTokens() {
        try {
          const data = await fs9.readFile(this.tokenFilePath, "utf-8");
          const decrypted = this.decrypt(data);
          const tokens = JSON.parse(decrypted);
          return new Map(Object.entries(tokens));
        } catch (error) {
          const err = error;
          if (err.code === "ENOENT") {
            throw new Error("Token file does not exist");
          }
          if (err.message?.includes("Invalid encrypted data format") || err.message?.includes("Unsupported state or unable to authenticate data")) {
            throw new Error("Token file corrupted");
          }
          throw error;
        }
      }
      async saveTokens(tokens) {
        await this.ensureDirectoryExists();
        const data = Object.fromEntries(tokens);
        const json2 = JSON.stringify(data, null, 2);
        const encrypted = this.encrypt(json2);
        await fs9.writeFile(this.tokenFilePath, encrypted, { mode: 384 });
      }
      async getCredentials(serverName) {
        const tokens = await this.loadTokens();
        const credentials = tokens.get(serverName);
        if (!credentials) {
          return null;
        }
        if (this.isTokenExpired(credentials)) {
          return null;
        }
        return credentials;
      }
      async setCredentials(credentials) {
        this.validateCredentials(credentials);
        const tokens = await this.loadTokens();
        const updatedCredentials = {
          ...credentials,
          updatedAt: Date.now()
        };
        tokens.set(credentials.serverName, updatedCredentials);
        await this.saveTokens(tokens);
      }
      async deleteCredentials(serverName) {
        const tokens = await this.loadTokens();
        if (!tokens.has(serverName)) {
          throw new Error(`No credentials found for ${serverName}`);
        }
        tokens.delete(serverName);
        if (tokens.size === 0) {
          try {
            await fs9.unlink(this.tokenFilePath);
          } catch (error) {
            const err = error;
            if (err.code !== "ENOENT") {
              throw error;
            }
          }
        } else {
          await this.saveTokens(tokens);
        }
      }
      async listServers() {
        const tokens = await this.loadTokens();
        return Array.from(tokens.keys());
      }
      async getAllCredentials() {
        const tokens = await this.loadTokens();
        const result = /* @__PURE__ */ new Map();
        for (const [serverName, credentials] of tokens) {
          if (!this.isTokenExpired(credentials)) {
            result.set(serverName, credentials);
          }
        }
        return result;
      }
      async clearAll() {
        try {
          await fs9.unlink(this.tokenFilePath);
        } catch (error) {
          const err = error;
          if (err.code !== "ENOENT") {
            throw error;
          }
        }
      }
    };
  }
});

// packages/core/dist/src/mcp/token-storage/types.js
var TokenStorageType;
var init_types = __esm({
  "packages/core/dist/src/mcp/token-storage/types.js"() {
    "use strict";
    init_esbuild_shims();
    (function(TokenStorageType2) {
      TokenStorageType2["KEYCHAIN"] = "keychain";
      TokenStorageType2["ENCRYPTED_FILE"] = "encrypted_file";
    })(TokenStorageType || (TokenStorageType = {}));
  }
});

// packages/core/dist/src/mcp/token-storage/keychain-token-storage.js
var keychain_token_storage_exports = {};
__export(keychain_token_storage_exports, {
  KeychainTokenStorage: () => KeychainTokenStorage
});
import * as crypto8 from "node:crypto";
var KEYCHAIN_TEST_PREFIX, KeychainTokenStorage;
var init_keychain_token_storage = __esm({
  "packages/core/dist/src/mcp/token-storage/keychain-token-storage.js"() {
    "use strict";
    init_esbuild_shims();
    init_base_token_storage();
    KEYCHAIN_TEST_PREFIX = "__keychain_test__";
    KeychainTokenStorage = class extends BaseTokenStorage {
      static {
        __name(this, "KeychainTokenStorage");
      }
      keychainAvailable = null;
      keytarModule = null;
      keytarLoadAttempted = false;
      async getKeytar() {
        if (this.keytarLoadAttempted) {
          return this.keytarModule;
        }
        this.keytarLoadAttempted = true;
        try {
          const moduleName2 = "keytar";
          const module2 = await import(moduleName2);
          this.keytarModule = module2.default || module2;
        } catch (error) {
          console.error(error);
        }
        return this.keytarModule;
      }
      async getCredentials(serverName) {
        if (!await this.checkKeychainAvailability()) {
          throw new Error("Keychain is not available");
        }
        const keytar = await this.getKeytar();
        if (!keytar) {
          throw new Error("Keytar module not available");
        }
        try {
          const sanitizedName = this.sanitizeServerName(serverName);
          const data = await keytar.getPassword(this.serviceName, sanitizedName);
          if (!data) {
            return null;
          }
          const credentials = JSON.parse(data);
          if (this.isTokenExpired(credentials)) {
            return null;
          }
          return credentials;
        } catch (error) {
          if (error instanceof SyntaxError) {
            throw new Error(`Failed to parse stored credentials for ${serverName}`);
          }
          throw error;
        }
      }
      async setCredentials(credentials) {
        if (!await this.checkKeychainAvailability()) {
          throw new Error("Keychain is not available");
        }
        const keytar = await this.getKeytar();
        if (!keytar) {
          throw new Error("Keytar module not available");
        }
        this.validateCredentials(credentials);
        const sanitizedName = this.sanitizeServerName(credentials.serverName);
        const updatedCredentials = {
          ...credentials,
          updatedAt: Date.now()
        };
        const data = JSON.stringify(updatedCredentials);
        await keytar.setPassword(this.serviceName, sanitizedName, data);
      }
      async deleteCredentials(serverName) {
        if (!await this.checkKeychainAvailability()) {
          throw new Error("Keychain is not available");
        }
        const keytar = await this.getKeytar();
        if (!keytar) {
          throw new Error("Keytar module not available");
        }
        const sanitizedName = this.sanitizeServerName(serverName);
        const deleted = await keytar.deletePassword(this.serviceName, sanitizedName);
        if (!deleted) {
          throw new Error(`No credentials found for ${serverName}`);
        }
      }
      async listServers() {
        if (!await this.checkKeychainAvailability()) {
          throw new Error("Keychain is not available");
        }
        const keytar = await this.getKeytar();
        if (!keytar) {
          throw new Error("Keytar module not available");
        }
        try {
          const credentials = await keytar.findCredentials(this.serviceName);
          return credentials.filter((cred) => !cred.account.startsWith(KEYCHAIN_TEST_PREFIX)).map((cred) => cred.account);
        } catch (error) {
          console.error("Failed to list servers from keychain:", error);
          return [];
        }
      }
      async getAllCredentials() {
        if (!await this.checkKeychainAvailability()) {
          throw new Error("Keychain is not available");
        }
        const keytar = await this.getKeytar();
        if (!keytar) {
          throw new Error("Keytar module not available");
        }
        const result = /* @__PURE__ */ new Map();
        try {
          const credentials = (await keytar.findCredentials(this.serviceName)).filter((c3) => !c3.account.startsWith(KEYCHAIN_TEST_PREFIX));
          for (const cred of credentials) {
            try {
              const data = JSON.parse(cred.password);
              if (!this.isTokenExpired(data)) {
                result.set(cred.account, data);
              }
            } catch (error) {
              console.error(`Failed to parse credentials for ${cred.account}:`, error);
            }
          }
        } catch (error) {
          console.error("Failed to get all credentials from keychain:", error);
        }
        return result;
      }
      async clearAll() {
        if (!await this.checkKeychainAvailability()) {
          throw new Error("Keychain is not available");
        }
        const servers = this.keytarModule ? await this.keytarModule.findCredentials(this.serviceName).then((creds) => creds.map((c3) => c3.account)).catch((error) => {
          throw new Error(`Failed to list servers for clearing: ${error.message}`);
        }) : [];
        const errors = [];
        for (const server of servers) {
          try {
            await this.deleteCredentials(server);
          } catch (error) {
            errors.push(error);
          }
        }
        if (errors.length > 0) {
          throw new Error(`Failed to clear some credentials: ${errors.map((e2) => e2.message).join(", ")}`);
        }
      }
      // Checks whether or not a set-get-delete cycle with the keychain works.
      // Returns false if any operation fails.
      async checkKeychainAvailability() {
        if (this.keychainAvailable !== null) {
          return this.keychainAvailable;
        }
        try {
          const keytar = await this.getKeytar();
          if (!keytar) {
            this.keychainAvailable = false;
            return false;
          }
          const testAccount = `${KEYCHAIN_TEST_PREFIX}${crypto8.randomBytes(8).toString("hex")}`;
          const testPassword = "test";
          await keytar.setPassword(this.serviceName, testAccount, testPassword);
          const retrieved = await keytar.getPassword(this.serviceName, testAccount);
          const deleted = await keytar.deletePassword(this.serviceName, testAccount);
          const success = deleted && retrieved === testPassword;
          this.keychainAvailable = success;
          return success;
        } catch (_error) {
          this.keychainAvailable = false;
          return false;
        }
      }
      async isAvailable() {
        return this.checkKeychainAvailability();
      }
    };
  }
});

// packages/core/dist/src/mcp/token-storage/hybrid-token-storage.js
var FORCE_FILE_STORAGE_ENV_VAR, HybridTokenStorage;
var init_hybrid_token_storage = __esm({
  "packages/core/dist/src/mcp/token-storage/hybrid-token-storage.js"() {
    "use strict";
    init_esbuild_shims();
    init_base_token_storage();
    init_file_token_storage();
    init_types();
    FORCE_FILE_STORAGE_ENV_VAR = "GEMINI_FORCE_FILE_STORAGE";
    HybridTokenStorage = class extends BaseTokenStorage {
      static {
        __name(this, "HybridTokenStorage");
      }
      storage = null;
      storageType = null;
      storageInitPromise = null;
      constructor(serviceName) {
        super(serviceName);
      }
      async initializeStorage() {
        const forceFileStorage = process.env[FORCE_FILE_STORAGE_ENV_VAR] === "true";
        if (!forceFileStorage) {
          try {
            const { KeychainTokenStorage: KeychainTokenStorage2 } = await Promise.resolve().then(() => (init_keychain_token_storage(), keychain_token_storage_exports));
            const keychainStorage = new KeychainTokenStorage2(this.serviceName);
            const isAvailable = await keychainStorage.isAvailable();
            if (isAvailable) {
              this.storage = keychainStorage;
              this.storageType = TokenStorageType.KEYCHAIN;
              return this.storage;
            }
          } catch (_e) {
          }
        }
        this.storage = new FileTokenStorage(this.serviceName);
        this.storageType = TokenStorageType.ENCRYPTED_FILE;
        return this.storage;
      }
      async getStorage() {
        if (this.storage !== null) {
          return this.storage;
        }
        if (!this.storageInitPromise) {
          this.storageInitPromise = this.initializeStorage();
        }
        return await this.storageInitPromise;
      }
      async getCredentials(serverName) {
        const storage = await this.getStorage();
        return storage.getCredentials(serverName);
      }
      async setCredentials(credentials) {
        const storage = await this.getStorage();
        await storage.setCredentials(credentials);
      }
      async deleteCredentials(serverName) {
        const storage = await this.getStorage();
        await storage.deleteCredentials(serverName);
      }
      async listServers() {
        const storage = await this.getStorage();
        return storage.listServers();
      }
      async getAllCredentials() {
        const storage = await this.getStorage();
        return storage.getAllCredentials();
      }
      async clearAll() {
        const storage = await this.getStorage();
        await storage.clearAll();
      }
      async getStorageType() {
        await this.getStorage();
        return this.storageType;
      }
    };
  }
});

// packages/core/dist/src/code_assist/oauth-credential-storage.js
import * as path6 from "node:path";
import * as os6 from "node:os";
import { promises as fs10 } from "node:fs";
var import_google_auth_library2, QWEN_DIR2, KEYCHAIN_SERVICE_NAME, MAIN_ACCOUNT_KEY, OAuthCredentialStorage;
var init_oauth_credential_storage = __esm({
  "packages/core/dist/src/code_assist/oauth-credential-storage.js"() {
    "use strict";
    init_esbuild_shims();
    import_google_auth_library2 = __toESM(require_src6(), 1);
    init_hybrid_token_storage();
    init_storage();
    QWEN_DIR2 = ".qwen";
    KEYCHAIN_SERVICE_NAME = "qwen-code-oauth";
    MAIN_ACCOUNT_KEY = "main-account";
    OAuthCredentialStorage = class {
      static {
        __name(this, "OAuthCredentialStorage");
      }
      static storage = new HybridTokenStorage(KEYCHAIN_SERVICE_NAME);
      /**
       * Load cached OAuth credentials
       */
      static async loadCredentials() {
        try {
          const credentials = await this.storage.getCredentials(MAIN_ACCOUNT_KEY);
          if (credentials?.token) {
            const { accessToken, refreshToken, expiresAt, tokenType, scope } = credentials.token;
            const googleCreds = {
              access_token: accessToken,
              refresh_token: refreshToken || void 0,
              token_type: tokenType || void 0,
              scope: scope || void 0
            };
            if (expiresAt) {
              googleCreds.expiry_date = expiresAt;
            }
            return googleCreds;
          }
          return await this.migrateFromFileStorage();
        } catch (error) {
          console.error(error);
          throw new Error("Failed to load OAuth credentials");
        }
      }
      /**
       * Save OAuth credentials
       */
      static async saveCredentials(credentials) {
        if (!credentials.access_token) {
          throw new Error("Attempted to save credentials without an access token.");
        }
        const mcpCredentials = {
          serverName: MAIN_ACCOUNT_KEY,
          token: {
            accessToken: credentials.access_token,
            refreshToken: credentials.refresh_token || void 0,
            tokenType: credentials.token_type || "Bearer",
            scope: credentials.scope || void 0,
            expiresAt: credentials.expiry_date || void 0
          },
          updatedAt: Date.now()
        };
        await this.storage.setCredentials(mcpCredentials);
      }
      /**
       * Clear cached OAuth credentials
       */
      static async clearCredentials() {
        try {
          await this.storage.deleteCredentials(MAIN_ACCOUNT_KEY);
          const oldFilePath = path6.join(os6.homedir(), QWEN_DIR2, OAUTH_FILE);
          await fs10.rm(oldFilePath, { force: true }).catch(() => {
          });
        } catch (error) {
          console.error(error);
          throw new Error("Failed to clear OAuth credentials");
        }
      }
      /**
       * Migrate credentials from old file-based storage to keychain
       */
      static async migrateFromFileStorage() {
        const oldFilePath = path6.join(os6.homedir(), QWEN_DIR2, OAUTH_FILE);
        let credsJson;
        try {
          credsJson = await fs10.readFile(oldFilePath, "utf-8");
        } catch (error) {
          if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
            return null;
          }
          throw error;
        }
        const credentials = JSON.parse(credsJson);
        await this.saveCredentials(credentials);
        await fs10.rm(oldFilePath, { force: true }).catch(() => {
        });
        return credentials;
      }
    };
  }
});

// packages/core/dist/src/mcp/token-storage/index.js
var DEFAULT_SERVICE_NAME, FORCE_ENCRYPTED_FILE_ENV_VAR;
var init_token_storage = __esm({
  "packages/core/dist/src/mcp/token-storage/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_types();
    init_base_token_storage();
    init_file_token_storage();
    init_hybrid_token_storage();
    DEFAULT_SERVICE_NAME = "qwen-code-oauth";
    FORCE_ENCRYPTED_FILE_ENV_VAR = "QWEN_CODE_FORCE_ENCRYPTED_FILE_STORAGE";
  }
});

// packages/core/dist/src/qwen/qwenOAuth2.js
var qwenOAuth2_exports = {};
__export(qwenOAuth2_exports, {
  CredentialsClearRequiredError: () => CredentialsClearRequiredError,
  QwenOAuth2Client: () => QwenOAuth2Client,
  QwenOAuth2Event: () => QwenOAuth2Event,
  clearQwenCredentials: () => clearQwenCredentials,
  generateCodeChallenge: () => generateCodeChallenge,
  generateCodeVerifier: () => generateCodeVerifier,
  generatePKCEPair: () => generatePKCEPair,
  getQwenOAuthClient: () => getQwenOAuthClient,
  isDeviceAuthorizationSuccess: () => isDeviceAuthorizationSuccess,
  isDeviceTokenPending: () => isDeviceTokenPending,
  isDeviceTokenSuccess: () => isDeviceTokenSuccess,
  isErrorResponse: () => isErrorResponse,
  qwenOAuth2Events: () => qwenOAuth2Events
});
import crypto9 from "crypto";
import path7 from "node:path";
import { promises as fs11 } from "node:fs";
import * as os7 from "os";
import { EventEmitter as EventEmitter3 } from "events";
import { randomUUID } from "node:crypto";
function generateCodeVerifier() {
  return crypto9.randomBytes(32).toString("base64url");
}
function generateCodeChallenge(codeVerifier) {
  const hash = crypto9.createHash("sha256");
  hash.update(codeVerifier);
  return hash.digest("base64url");
}
function generatePKCEPair() {
  const codeVerifier = generateCodeVerifier();
  const codeChallenge = generateCodeChallenge(codeVerifier);
  return { code_verifier: codeVerifier, code_challenge: codeChallenge };
}
function objectToUrlEncoded(data) {
  return Object.keys(data).map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`).join("&");
}
function isDeviceAuthorizationSuccess(response) {
  return "device_code" in response;
}
function isDeviceTokenSuccess(response) {
  return "access_token" in response && response.access_token !== null && response.access_token !== void 0 && typeof response.access_token === "string" && response.access_token.length > 0;
}
function isDeviceTokenPending(response) {
  return "status" in response && response.status === "pending";
}
function isErrorResponse(response) {
  return "error" in response;
}
async function getQwenOAuthClient(config, options2) {
  const client = new QwenOAuth2Client();
  const sharedManager = SharedTokenManager.getInstance();
  try {
    const credentials = await sharedManager.getValidCredentials(client);
    client.setCredentials(credentials);
    return client;
  } catch (error) {
    if (error instanceof TokenManagerError) {
      switch (error.type) {
        case TokenError.NO_REFRESH_TOKEN:
          console.debug("No refresh token available, proceeding with device flow");
          break;
        case TokenError.REFRESH_FAILED:
          console.debug("Token refresh failed, proceeding with device flow");
          break;
        case TokenError.NETWORK_ERROR:
          console.warn("Network error during token refresh, trying device flow");
          break;
        default:
          console.warn("Token manager error:", error.message);
      }
    }
    if (await loadCachedQwenCredentials(client)) {
      const result2 = await authWithQwenDeviceFlow(client, config);
      if (!result2.success) {
        const errorMessage = result2.message || "Qwen OAuth authentication failed";
        throw new Error(errorMessage);
      }
      return client;
    }
    if (options2?.requireCachedCredentials) {
      throw new Error("No cached Qwen-OAuth credentials found. Please re-authenticate.");
    }
    const result = await authWithQwenDeviceFlow(client, config);
    if (!result.success) {
      if (result.reason === "timeout") {
        qwenOAuth2Events.emit(QwenOAuth2Event.AuthProgress, "timeout", "Authentication timed out. Please try again or select a different authentication method.");
      }
      const errorMessage = result.message || (() => {
        switch (result.reason) {
          case "timeout":
            return "Qwen OAuth authentication timed out";
          case "cancelled":
            return "Qwen OAuth authentication was cancelled by user";
          case "rate_limit":
            return "Too many request for Qwen OAuth authentication, please try again later.";
          case "error":
          default:
            return "Qwen OAuth authentication failed";
        }
      })();
      throw new Error(errorMessage);
    }
    return client;
  }
}
async function authWithQwenDeviceFlow(client, config) {
  let isCancelled = false;
  const cancelHandler = /* @__PURE__ */ __name(() => {
    isCancelled = true;
  }, "cancelHandler");
  qwenOAuth2Events.once(QwenOAuth2Event.AuthCancel, cancelHandler);
  try {
    const { code_verifier, code_challenge } = generatePKCEPair();
    const deviceAuth = await client.requestDeviceAuthorization({
      scope: QWEN_OAUTH_SCOPE,
      code_challenge,
      code_challenge_method: "S256"
    });
    if (!isDeviceAuthorizationSuccess(deviceAuth)) {
      const errorData = deviceAuth;
      throw new Error(`Device authorization failed: ${errorData?.error || "Unknown error"} - ${errorData?.error_description || "No details provided"}`);
    }
    qwenOAuth2Events.emit(QwenOAuth2Event.AuthUri, deviceAuth);
    const showFallbackMessage = /* @__PURE__ */ __name(() => {
      console.log("\n=== Qwen OAuth Device Authorization ===");
      console.log("Please visit the following URL in your browser to authorize:");
      console.log(`
${deviceAuth.verification_uri_complete}
`);
      console.log("Waiting for authorization to complete...\n");
    }, "showFallbackMessage");
    if (!config.isBrowserLaunchSuppressed()) {
      try {
        const childProcess3 = await open_default(deviceAuth.verification_uri_complete);
        if (childProcess3) {
          childProcess3.on("error", () => {
            console.debug("Failed to open browser. Visit this URL to authorize:");
            showFallbackMessage();
          });
        }
      } catch (_err) {
        showFallbackMessage();
      }
    } else {
      showFallbackMessage();
    }
    qwenOAuth2Events.emit(QwenOAuth2Event.AuthProgress, "polling", "Waiting for authorization...");
    console.debug("Waiting for authorization...\n");
    let pollInterval = 2e3;
    const maxAttempts = Math.ceil(deviceAuth.expires_in / (pollInterval / 1e3));
    for (let attempt = 0; attempt < maxAttempts; attempt++) {
      if (isCancelled) {
        const message = "Authentication cancelled by user.";
        console.debug("\n" + message);
        qwenOAuth2Events.emit(QwenOAuth2Event.AuthProgress, "error", message);
        return { success: false, reason: "cancelled", message };
      }
      try {
        console.debug("polling for token...");
        const tokenResponse = await client.pollDeviceToken({
          device_code: deviceAuth.device_code,
          code_verifier
        });
        if (isDeviceTokenSuccess(tokenResponse)) {
          const tokenData = tokenResponse;
          const credentials = {
            access_token: tokenData.access_token,
            // Safe to assert as non-null due to isDeviceTokenSuccess check
            refresh_token: tokenData.refresh_token || void 0,
            token_type: tokenData.token_type,
            resource_url: tokenData.resource_url,
            expiry_date: tokenData.expires_in ? Date.now() + tokenData.expires_in * 1e3 : void 0
          };
          client.setCredentials(credentials);
          await cacheQwenCredentials(credentials);
          qwenOAuth2Events.emit(QwenOAuth2Event.AuthProgress, "success", "Authentication successful! Access token obtained.");
          console.debug("Authentication successful! Access token obtained.");
          return { success: true };
        }
        if (isDeviceTokenPending(tokenResponse)) {
          const pendingData = tokenResponse;
          if (pendingData.slowDown) {
            pollInterval = Math.min(pollInterval * 1.5, 1e4);
            console.debug(`
Server requested to slow down, increasing poll interval to ${pollInterval}ms'`);
          } else {
            pollInterval = 2e3;
          }
          qwenOAuth2Events.emit(QwenOAuth2Event.AuthProgress, "polling", `Polling... (attempt ${attempt + 1}/${maxAttempts})`);
          await new Promise((resolve24) => {
            const checkInterval = 100;
            let elapsedTime = 0;
            const intervalId = setInterval(() => {
              elapsedTime += checkInterval;
              if (isCancelled) {
                clearInterval(intervalId);
                resolve24();
                return;
              }
              if (elapsedTime >= pollInterval) {
                clearInterval(intervalId);
                resolve24();
                return;
              }
            }, checkInterval);
          });
          if (isCancelled) {
            const message = "Authentication cancelled by user.";
            console.debug("\n" + message);
            qwenOAuth2Events.emit(QwenOAuth2Event.AuthProgress, "error", message);
            return { success: false, reason: "cancelled", message };
          }
          continue;
        }
        if (isErrorResponse(tokenResponse)) {
          const errorData = tokenResponse;
          throw new Error(`Token polling failed: ${errorData?.error || "Unknown error"} - ${errorData?.error_description || "No details provided"}`);
        }
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        const statusCode = error instanceof Error ? error.status : null;
        const handleError2 = /* @__PURE__ */ __name((reason, message2, eventType = "error") => {
          qwenOAuth2Events.emit(QwenOAuth2Event.AuthProgress, eventType, message2);
          console.error("\n" + message2);
          return { success: false, reason, message: message2 };
        }, "handleError");
        if (errorMessage.includes("Failed to cache credentials")) {
          return handleError2("error", errorMessage);
        }
        if (errorMessage.includes("401") || statusCode === 401) {
          return handleError2("error", "Device code expired or invalid, please restart the authorization process.");
        }
        if (errorMessage.includes("429") || statusCode === 429) {
          return handleError2("rate_limit", "Too many requests. The server is rate limiting our requests. Please select a different authentication method or try again later.", "rate_limit");
        }
        const message = `Error polling for token: ${errorMessage}`;
        qwenOAuth2Events.emit(QwenOAuth2Event.AuthProgress, "error", message);
        if (isCancelled) {
          const message2 = "Authentication cancelled by user.";
          return { success: false, reason: "cancelled", message: message2 };
        }
        await new Promise((resolve24) => setTimeout(resolve24, pollInterval));
      }
    }
    const timeoutMessage = "Authorization timeout, please restart the process.";
    qwenOAuth2Events.emit(QwenOAuth2Event.AuthProgress, "timeout", timeoutMessage);
    console.error("\n" + timeoutMessage);
    return { success: false, reason: "timeout", message: timeoutMessage };
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    const message = `Device authorization flow failed: ${errorMessage}`;
    console.error(message);
    return { success: false, reason: "error", message };
  } finally {
    qwenOAuth2Events.off(QwenOAuth2Event.AuthCancel, cancelHandler);
  }
}
async function loadCachedQwenCredentials(client) {
  try {
    const keyFile = getQwenCachedCredentialPath();
    const creds = await fs11.readFile(keyFile, "utf-8");
    const credentials = JSON.parse(creds);
    client.setCredentials(credentials);
    const { token: token2 } = await client.getAccessToken();
    if (!token2) {
      return false;
    }
    return true;
  } catch (_) {
    return false;
  }
}
async function cacheQwenCredentials(credentials) {
  const filePath = getQwenCachedCredentialPath();
  try {
    await fs11.mkdir(path7.dirname(filePath), { recursive: true });
    const credString = JSON.stringify(credentials, null, 2);
    await fs11.writeFile(filePath, credString);
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    const errorCode = error instanceof Error && "code" in error ? error.code : void 0;
    if (errorCode === "EACCES") {
      throw new Error(`Failed to cache credentials: Permission denied (EACCES). Current user has no permission to access \`${filePath}\`. Please check permissions.`);
    }
    throw new Error(`Failed to cache credentials: error when creating folder \`${path7.dirname(filePath)}\` and writing to \`${filePath}\`. ${errorMessage}. Please check permissions.`);
  }
}
async function clearQwenCredentials() {
  try {
    const filePath = getQwenCachedCredentialPath();
    await fs11.unlink(filePath);
    console.debug("Cached Qwen credentials cleared successfully.");
  } catch (error) {
    if (error instanceof Error && "code" in error && error.code === "ENOENT") {
      return;
    }
    console.warn("Warning: Failed to clear cached Qwen credentials:", error);
  }
}
function getQwenCachedCredentialPath() {
  return path7.join(os7.homedir(), QWEN_DIR3, QWEN_CREDENTIAL_FILENAME);
}
var QWEN_OAUTH_BASE_URL, QWEN_OAUTH_DEVICE_CODE_ENDPOINT, QWEN_OAUTH_TOKEN_ENDPOINT, QWEN_OAUTH_CLIENT_ID, QWEN_OAUTH_SCOPE, QWEN_OAUTH_GRANT_TYPE, QWEN_DIR3, QWEN_CREDENTIAL_FILENAME, CredentialsClearRequiredError, QwenOAuth2Client, QwenOAuth2Event, qwenOAuth2Events;
var init_qwenOAuth2 = __esm({
  "packages/core/dist/src/qwen/qwenOAuth2.js"() {
    "use strict";
    init_esbuild_shims();
    init_open();
    init_sharedTokenManager();
    QWEN_OAUTH_BASE_URL = "https://chat.qwen.ai";
    QWEN_OAUTH_DEVICE_CODE_ENDPOINT = `${QWEN_OAUTH_BASE_URL}/api/v1/oauth2/device/code`;
    QWEN_OAUTH_TOKEN_ENDPOINT = `${QWEN_OAUTH_BASE_URL}/api/v1/oauth2/token`;
    QWEN_OAUTH_CLIENT_ID = "f0304373b74a44d2b584a3fb70ca9e56";
    QWEN_OAUTH_SCOPE = "openid profile email model.completion";
    QWEN_OAUTH_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
    QWEN_DIR3 = ".qwen";
    QWEN_CREDENTIAL_FILENAME = "oauth_creds.json";
    __name(generateCodeVerifier, "generateCodeVerifier");
    __name(generateCodeChallenge, "generateCodeChallenge");
    __name(generatePKCEPair, "generatePKCEPair");
    __name(objectToUrlEncoded, "objectToUrlEncoded");
    CredentialsClearRequiredError = class extends Error {
      static {
        __name(this, "CredentialsClearRequiredError");
      }
      originalError;
      constructor(message, originalError) {
        super(message);
        this.originalError = originalError;
        this.name = "CredentialsClearRequiredError";
      }
    };
    __name(isDeviceAuthorizationSuccess, "isDeviceAuthorizationSuccess");
    __name(isDeviceTokenSuccess, "isDeviceTokenSuccess");
    __name(isDeviceTokenPending, "isDeviceTokenPending");
    __name(isErrorResponse, "isErrorResponse");
    QwenOAuth2Client = class {
      static {
        __name(this, "QwenOAuth2Client");
      }
      credentials = {};
      sharedManager;
      constructor() {
        this.sharedManager = SharedTokenManager.getInstance();
      }
      setCredentials(credentials) {
        this.credentials = credentials;
      }
      getCredentials() {
        return this.credentials;
      }
      async getAccessToken() {
        try {
          const credentials = await this.sharedManager.getValidCredentials(this);
          return { token: credentials.access_token };
        } catch (error) {
          console.warn("Failed to get access token from shared manager:", error);
          return { token: void 0 };
        }
      }
      async requestDeviceAuthorization(options2) {
        const bodyData = {
          client_id: QWEN_OAUTH_CLIENT_ID,
          scope: options2.scope,
          code_challenge: options2.code_challenge,
          code_challenge_method: options2.code_challenge_method
        };
        const response = await fetch(QWEN_OAUTH_DEVICE_CODE_ENDPOINT, {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            Accept: "application/json",
            "x-request-id": randomUUID()
          },
          body: objectToUrlEncoded(bodyData)
        });
        if (!response.ok) {
          const errorData = await response.text();
          throw new Error(`Device authorization failed: ${response.status} ${response.statusText}. Response: ${errorData}`);
        }
        const result = await response.json();
        console.debug("Device authorization result:", result);
        if (!isDeviceAuthorizationSuccess(result)) {
          const errorData = result;
          throw new Error(`Device authorization failed: ${errorData?.error || "Unknown error"} - ${errorData?.error_description || "No details provided"}`);
        }
        return result;
      }
      async pollDeviceToken(options2) {
        const bodyData = {
          grant_type: QWEN_OAUTH_GRANT_TYPE,
          client_id: QWEN_OAUTH_CLIENT_ID,
          device_code: options2.device_code,
          code_verifier: options2.code_verifier
        };
        const response = await fetch(QWEN_OAUTH_TOKEN_ENDPOINT, {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            Accept: "application/json"
          },
          body: objectToUrlEncoded(bodyData)
        });
        if (!response.ok) {
          const responseText = await response.text();
          let errorData = null;
          try {
            errorData = JSON.parse(responseText);
          } catch (_parseError) {
            const error2 = new Error(`Device token poll failed: ${response.status} ${response.statusText}. Response: ${responseText}`);
            error2.status = response.status;
            throw error2;
          }
          if (response.status === 400 && errorData.error === "authorization_pending") {
            return { status: "pending" };
          }
          if (response.status === 429 && errorData.error === "slow_down") {
            return {
              status: "pending",
              slowDown: true
            };
          }
          const error = new Error(`Device token poll failed: ${errorData.error || "Unknown error"} - ${errorData.error_description}`);
          error.status = response.status;
          throw error;
        }
        return await response.json();
      }
      async refreshAccessToken() {
        if (!this.credentials.refresh_token) {
          throw new Error("No refresh token available");
        }
        const bodyData = {
          grant_type: "refresh_token",
          refresh_token: this.credentials.refresh_token,
          client_id: QWEN_OAUTH_CLIENT_ID
        };
        const response = await fetch(QWEN_OAUTH_TOKEN_ENDPOINT, {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            Accept: "application/json"
          },
          body: objectToUrlEncoded(bodyData)
        });
        if (!response.ok) {
          const errorData = await response.text();
          if (response.status === 400) {
            await clearQwenCredentials();
            throw new CredentialsClearRequiredError("Refresh token expired or invalid. Please use '/auth' to re-authenticate.", { status: response.status, response: errorData });
          }
          throw new Error(`Token refresh failed: ${response.status} ${response.statusText}. Response: ${errorData}`);
        }
        const responseData = await response.json();
        if (isErrorResponse(responseData)) {
          const errorData = responseData;
          throw new Error(`Token refresh failed: ${errorData?.error || "Unknown error"} - ${errorData?.error_description || "No details provided"}`);
        }
        const tokenData = responseData;
        const tokens = {
          access_token: tokenData.access_token,
          token_type: tokenData.token_type,
          // Use new refresh token if provided, otherwise preserve existing one
          refresh_token: tokenData.refresh_token || this.credentials.refresh_token,
          resource_url: tokenData.resource_url,
          // Include resource_url if provided
          expiry_date: Date.now() + tokenData.expires_in * 1e3
        };
        this.setCredentials(tokens);
        return responseData;
      }
    };
    (function(QwenOAuth2Event2) {
      QwenOAuth2Event2["AuthUri"] = "auth-uri";
      QwenOAuth2Event2["AuthProgress"] = "auth-progress";
      QwenOAuth2Event2["AuthCancel"] = "auth-cancel";
    })(QwenOAuth2Event || (QwenOAuth2Event = {}));
    qwenOAuth2Events = new EventEmitter3();
    __name(getQwenOAuthClient, "getQwenOAuthClient");
    __name(authWithQwenDeviceFlow, "authWithQwenDeviceFlow");
    __name(loadCachedQwenCredentials, "loadCachedQwenCredentials");
    __name(cacheQwenCredentials, "cacheQwenCredentials");
    __name(clearQwenCredentials, "clearQwenCredentials");
    __name(getQwenCachedCredentialPath, "getQwenCachedCredentialPath");
  }
});

// packages/core/dist/src/qwen/sharedTokenManager.js
var sharedTokenManager_exports = {};
__export(sharedTokenManager_exports, {
  SharedTokenManager: () => SharedTokenManager,
  TokenError: () => TokenError,
  TokenManagerError: () => TokenManagerError
});
import path8 from "node:path";
import { promises as fs12, unlinkSync } from "node:fs";
import * as os8 from "os";
import { randomUUID as randomUUID2 } from "node:crypto";
function validateCredentials(data) {
  if (!data || typeof data !== "object") {
    throw new Error("Invalid credentials format");
  }
  const creds = data;
  const requiredFields = [
    "access_token",
    "refresh_token",
    "token_type"
  ];
  for (const field of requiredFields) {
    if (!creds[field] || typeof creds[field] !== "string") {
      throw new Error(`Invalid credentials: missing ${field}`);
    }
  }
  if (!creds.expiry_date || typeof creds.expiry_date !== "number") {
    throw new Error("Invalid credentials: missing expiry_date");
  }
  return creds;
}
var QWEN_DIR4, QWEN_CREDENTIAL_FILENAME2, QWEN_LOCK_FILENAME, TOKEN_REFRESH_BUFFER_MS, LOCK_TIMEOUT_MS, CACHE_CHECK_INTERVAL_MS, DEFAULT_LOCK_CONFIG, TokenError, TokenManagerError, SharedTokenManager;
var init_sharedTokenManager = __esm({
  "packages/core/dist/src/qwen/sharedTokenManager.js"() {
    "use strict";
    init_esbuild_shims();
    init_qwenOAuth2();
    QWEN_DIR4 = ".qwen";
    QWEN_CREDENTIAL_FILENAME2 = "oauth_creds.json";
    QWEN_LOCK_FILENAME = "oauth_creds.lock";
    TOKEN_REFRESH_BUFFER_MS = 30 * 1e3;
    LOCK_TIMEOUT_MS = 1e4;
    CACHE_CHECK_INTERVAL_MS = 5e3;
    DEFAULT_LOCK_CONFIG = {
      maxAttempts: 20,
      // Reduced from 50 to prevent excessive waiting
      attemptInterval: 100,
      // Reduced from 200ms to check more frequently
      maxInterval: 2e3
      // Maximum interval for exponential backoff
    };
    (function(TokenError2) {
      TokenError2["REFRESH_FAILED"] = "REFRESH_FAILED";
      TokenError2["NO_REFRESH_TOKEN"] = "NO_REFRESH_TOKEN";
      TokenError2["LOCK_TIMEOUT"] = "LOCK_TIMEOUT";
      TokenError2["FILE_ACCESS_ERROR"] = "FILE_ACCESS_ERROR";
      TokenError2["NETWORK_ERROR"] = "NETWORK_ERROR";
    })(TokenError || (TokenError = {}));
    TokenManagerError = class extends Error {
      static {
        __name(this, "TokenManagerError");
      }
      type;
      originalError;
      constructor(type, message, originalError) {
        super(message);
        this.type = type;
        this.originalError = originalError;
        this.name = "TokenManagerError";
      }
    };
    __name(validateCredentials, "validateCredentials");
    SharedTokenManager = class _SharedTokenManager {
      static {
        __name(this, "SharedTokenManager");
      }
      static instance = null;
      /**
       * In-memory cache for credentials and file state tracking
       */
      memoryCache = {
        credentials: null,
        fileModTime: 0,
        lastCheck: 0
      };
      /**
       * Promise tracking any ongoing token refresh operation
       */
      refreshPromise = null;
      /**
       * Promise tracking any ongoing file check operation to prevent concurrent checks
       */
      checkPromise = null;
      /**
       * Whether cleanup handlers have been registered
       */
      cleanupHandlersRegistered = false;
      /**
       * Reference to cleanup functions for proper removal
       */
      cleanupFunction = null;
      /**
       * Lock configuration for testing purposes
       */
      lockConfig = DEFAULT_LOCK_CONFIG;
      /**
       * Private constructor for singleton pattern
       */
      constructor() {
        this.registerCleanupHandlers();
      }
      /**
       * Get the singleton instance
       * @returns The shared token manager instance
       */
      static getInstance() {
        if (!_SharedTokenManager.instance) {
          _SharedTokenManager.instance = new _SharedTokenManager();
        }
        return _SharedTokenManager.instance;
      }
      /**
       * Set up handlers to clean up lock files when the process exits
       */
      registerCleanupHandlers() {
        if (this.cleanupHandlersRegistered) {
          return;
        }
        this.cleanupFunction = () => {
          try {
            const lockPath = this.getLockFilePath();
            unlinkSync(lockPath);
          } catch (_error) {
          }
        };
        process.on("exit", this.cleanupFunction);
        process.on("SIGINT", this.cleanupFunction);
        process.on("SIGTERM", this.cleanupFunction);
        process.on("uncaughtException", this.cleanupFunction);
        process.on("unhandledRejection", this.cleanupFunction);
        this.cleanupHandlersRegistered = true;
      }
      /**
       * Get valid OAuth credentials, refreshing them if necessary
       *
       * @param qwenClient - The OAuth2 client instance
       * @param forceRefresh - If true, refresh token even if current one is still valid
       * @returns Promise resolving to valid credentials
       * @throws TokenManagerError if unable to obtain valid credentials
       */
      async getValidCredentials(qwenClient, forceRefresh = false) {
        try {
          await this.checkAndReloadIfNeeded(qwenClient);
          if (!forceRefresh && this.memoryCache.credentials && this.isTokenValid(this.memoryCache.credentials)) {
            return this.memoryCache.credentials;
          }
          let currentRefreshPromise = this.refreshPromise;
          if (!currentRefreshPromise) {
            currentRefreshPromise = this.performTokenRefresh(qwenClient, forceRefresh);
            this.refreshPromise = currentRefreshPromise;
          }
          try {
            const result = await currentRefreshPromise;
            return result;
          } finally {
            if (this.refreshPromise === currentRefreshPromise) {
              this.refreshPromise = null;
            }
          }
        } catch (error) {
          if (error instanceof TokenManagerError) {
            throw error;
          }
          throw new TokenManagerError(TokenError.REFRESH_FAILED, `Failed to get valid credentials: ${error instanceof Error ? error.message : String(error)}`, error);
        }
      }
      /**
       * Check if the credentials file was updated by another process and reload if so
       * Uses promise-based locking to prevent concurrent file checks
       */
      async checkAndReloadIfNeeded(qwenClient) {
        if (this.checkPromise) {
          await this.checkPromise;
          return;
        }
        if (this.refreshPromise) {
          return;
        }
        const now = Date.now();
        if (now - this.memoryCache.lastCheck < CACHE_CHECK_INTERVAL_MS) {
          return;
        }
        this.checkPromise = this.performFileCheck(qwenClient, now);
        try {
          await this.checkPromise;
        } finally {
          this.checkPromise = null;
        }
      }
      /**
       * Utility method to add timeout to any promise operation
       * Properly cleans up the timeout when the promise completes
       */
      withTimeout(promise, timeoutMs, operationType = "Operation") {
        let timeoutId;
        return Promise.race([
          promise.finally(() => {
            if (timeoutId) {
              clearTimeout(timeoutId);
            }
          }),
          new Promise((_, reject) => {
            timeoutId = setTimeout(() => reject(new Error(`${operationType} timed out after ${timeoutMs}ms`)), timeoutMs);
          })
        ]);
      }
      /**
       * Perform the actual file check and reload operation
       * This is separated to enable proper promise-based synchronization
       */
      async performFileCheck(qwenClient, checkTime) {
        this.memoryCache.lastCheck = checkTime;
        try {
          const filePath = this.getCredentialFilePath();
          const stats = await this.withTimeout(fs12.stat(filePath), 3e3, "File operation");
          const fileModTime = stats.mtimeMs;
          if (fileModTime > this.memoryCache.fileModTime) {
            await this.reloadCredentialsFromFile(qwenClient);
            this.memoryCache.fileModTime = fileModTime;
          }
        } catch (error) {
          if (error instanceof Error && "code" in error && error.code !== "ENOENT") {
            this.updateCacheState(null, 0, checkTime);
            throw new TokenManagerError(TokenError.FILE_ACCESS_ERROR, `Failed to access credentials file: ${error.message}`, error);
          }
          this.memoryCache.fileModTime = 0;
        }
      }
      /**
       * Force a file check without time-based throttling (used during refresh operations)
       */
      async forceFileCheck(qwenClient) {
        try {
          const filePath = this.getCredentialFilePath();
          const stats = await fs12.stat(filePath);
          const fileModTime = stats.mtimeMs;
          if (fileModTime > this.memoryCache.fileModTime) {
            await this.reloadCredentialsFromFile(qwenClient);
            this.memoryCache.fileModTime = fileModTime;
            this.memoryCache.lastCheck = Date.now();
          }
        } catch (error) {
          if (error instanceof Error && "code" in error && error.code !== "ENOENT") {
            this.updateCacheState(null, 0);
            throw new TokenManagerError(TokenError.FILE_ACCESS_ERROR, `Failed to access credentials file during refresh: ${error.message}`, error);
          }
          this.memoryCache.fileModTime = 0;
        }
      }
      /**
       * Load credentials from the file system into memory cache and sync with qwenClient
       */
      async reloadCredentialsFromFile(qwenClient) {
        try {
          const filePath = this.getCredentialFilePath();
          const content = await fs12.readFile(filePath, "utf-8");
          const parsedData = JSON.parse(content);
          const credentials = validateCredentials(parsedData);
          const previousCredentials = this.memoryCache.credentials;
          this.memoryCache.credentials = credentials;
          try {
            if (qwenClient) {
              qwenClient.setCredentials(credentials);
            }
          } catch (clientError) {
            this.memoryCache.credentials = previousCredentials;
            throw clientError;
          }
        } catch (error) {
          if (error instanceof Error && error.message.includes("Invalid credentials")) {
            console.warn(`Failed to validate credentials file: ${error.message}`);
          }
          this.memoryCache.credentials = null;
        }
      }
      /**
       * Refresh the OAuth token using file locking to prevent concurrent refreshes
       *
       * @param qwenClient - The OAuth2 client instance
       * @param forceRefresh - If true, skip checking if token is already valid after getting lock
       * @returns Promise resolving to refreshed credentials
       * @throws TokenManagerError if refresh fails or lock cannot be acquired
       */
      async performTokenRefresh(qwenClient, forceRefresh = false) {
        const startTime = Date.now();
        const lockPath = this.getLockFilePath();
        try {
          const currentCredentials = qwenClient.getCredentials();
          if (!currentCredentials.refresh_token) {
            throw new TokenManagerError(TokenError.NO_REFRESH_TOKEN, "No refresh token available for token refresh");
          }
          await this.acquireLock(lockPath);
          const lockAcquisitionTime = Date.now() - startTime;
          if (lockAcquisitionTime > 5e3) {
            console.warn(`Token refresh lock acquisition took ${lockAcquisitionTime}ms`);
          }
          await this.forceFileCheck(qwenClient);
          if (!forceRefresh && this.memoryCache.credentials && this.isTokenValid(this.memoryCache.credentials)) {
            return this.memoryCache.credentials;
          }
          const response = await qwenClient.refreshAccessToken();
          const totalOperationTime = Date.now() - startTime;
          if (totalOperationTime > 1e4) {
            console.warn(`Token refresh operation took ${totalOperationTime}ms`);
          }
          if (!response || isErrorResponse(response)) {
            const errorData = response;
            throw new TokenManagerError(TokenError.REFRESH_FAILED, `Token refresh failed: ${errorData?.error || "Unknown error"} - ${errorData?.error_description || "No details provided"}`);
          }
          const tokenData = response;
          if (!tokenData.access_token) {
            throw new TokenManagerError(TokenError.REFRESH_FAILED, "Failed to refresh access token: no token returned");
          }
          const credentials = {
            access_token: tokenData.access_token,
            token_type: tokenData.token_type,
            refresh_token: tokenData.refresh_token || currentCredentials.refresh_token,
            resource_url: tokenData.resource_url,
            expiry_date: Date.now() + tokenData.expires_in * 1e3
          };
          this.memoryCache.credentials = credentials;
          qwenClient.setCredentials(credentials);
          await this.saveCredentialsToFile(credentials);
          return credentials;
        } catch (error) {
          if (error instanceof CredentialsClearRequiredError) {
            console.debug("SharedTokenManager: Clearing memory cache due to credentials clear requirement");
            this.memoryCache.credentials = null;
            this.memoryCache.fileModTime = 0;
            this.refreshPromise = null;
            throw new TokenManagerError(TokenError.REFRESH_FAILED, error.message, error);
          }
          if (error instanceof TokenManagerError) {
            throw error;
          }
          if (error instanceof Error && (error.message.includes("fetch") || error.message.includes("network") || error.message.includes("timeout"))) {
            throw new TokenManagerError(TokenError.NETWORK_ERROR, `Network error during token refresh: ${error.message}`, error);
          }
          throw new TokenManagerError(TokenError.REFRESH_FAILED, `Unexpected error during token refresh: ${error instanceof Error ? error.message : String(error)}`, error);
        } finally {
          await this.releaseLock(lockPath);
        }
      }
      /**
       * Save credentials to file and update the cached file modification time
       *
       * @param credentials - The credentials to save
       */
      async saveCredentialsToFile(credentials) {
        const filePath = this.getCredentialFilePath();
        const dirPath = path8.dirname(filePath);
        const tempPath = `${filePath}.tmp.${randomUUID2()}`;
        try {
          await this.withTimeout(fs12.mkdir(dirPath, { recursive: true, mode: 448 }), 5e3, "File operation");
        } catch (error) {
          throw new TokenManagerError(TokenError.FILE_ACCESS_ERROR, `Failed to create credentials directory: ${error instanceof Error ? error.message : String(error)}`, error);
        }
        const credString = JSON.stringify(credentials, null, 2);
        try {
          await this.withTimeout(fs12.writeFile(tempPath, credString, { mode: 384 }), 5e3, "File operation");
          await this.withTimeout(fs12.rename(tempPath, filePath), 5e3, "File operation");
          const stats = await this.withTimeout(fs12.stat(filePath), 5e3, "File operation");
          this.memoryCache.fileModTime = stats.mtimeMs;
        } catch (error) {
          try {
            await this.withTimeout(fs12.unlink(tempPath), 1e3, "File operation");
          } catch (_cleanupError) {
          }
          throw new TokenManagerError(TokenError.FILE_ACCESS_ERROR, `Failed to write credentials file: ${error instanceof Error ? error.message : String(error)}`, error);
        }
      }
      /**
       * Check if the token is valid and not expired
       *
       * @param credentials - The credentials to validate
       * @returns true if token is valid and not expired, false otherwise
       */
      isTokenValid(credentials) {
        if (!credentials.expiry_date || !credentials.access_token) {
          return false;
        }
        return Date.now() < credentials.expiry_date - TOKEN_REFRESH_BUFFER_MS;
      }
      /**
       * Get the full path to the credentials file
       *
       * @returns The absolute path to the credentials file
       */
      getCredentialFilePath() {
        return path8.join(os8.homedir(), QWEN_DIR4, QWEN_CREDENTIAL_FILENAME2);
      }
      /**
       * Get the full path to the lock file
       *
       * @returns The absolute path to the lock file
       */
      getLockFilePath() {
        return path8.join(os8.homedir(), QWEN_DIR4, QWEN_LOCK_FILENAME);
      }
      /**
       * Acquire a file lock to prevent other processes from refreshing tokens simultaneously
       *
       * @param lockPath - Path to the lock file
       * @throws TokenManagerError if lock cannot be acquired within timeout period
       */
      async acquireLock(lockPath) {
        const { maxAttempts, attemptInterval, maxInterval } = this.lockConfig;
        const lockId = randomUUID2();
        let currentInterval = attemptInterval;
        for (let attempt = 0; attempt < maxAttempts; attempt++) {
          try {
            await fs12.writeFile(lockPath, lockId, { flag: "wx" });
            return;
          } catch (error) {
            if (error.code === "EEXIST") {
              try {
                const stats = await fs12.stat(lockPath);
                const lockAge = Date.now() - stats.mtimeMs;
                if (lockAge > LOCK_TIMEOUT_MS) {
                  const tempPath = `${lockPath}.stale.${randomUUID2()}`;
                  try {
                    await fs12.rename(lockPath, tempPath);
                    await fs12.unlink(tempPath);
                    console.warn(`Removed stale lock file: ${lockPath} (age: ${lockAge}ms)`);
                    continue;
                  } catch (renameError) {
                    console.warn(`Failed to remove stale lock file ${lockPath}: ${renameError instanceof Error ? renameError.message : String(renameError)}`);
                  }
                }
              } catch (statError) {
                console.warn(`Failed to stat lock file ${lockPath}: ${statError instanceof Error ? statError.message : String(statError)}`);
              }
              await new Promise((resolve24) => setTimeout(resolve24, currentInterval));
              currentInterval = Math.min(currentInterval * 1.5, maxInterval);
            } else {
              throw new TokenManagerError(TokenError.FILE_ACCESS_ERROR, `Failed to create lock file: ${error instanceof Error ? error.message : String(error)}`, error);
            }
          }
        }
        throw new TokenManagerError(TokenError.LOCK_TIMEOUT, "Failed to acquire file lock for token refresh: timeout exceeded");
      }
      /**
       * Release the file lock
       *
       * @param lockPath - Path to the lock file
       */
      async releaseLock(lockPath) {
        try {
          await fs12.unlink(lockPath);
        } catch (error) {
          if (error.code !== "ENOENT") {
            console.warn(`Failed to release lock file ${lockPath}: ${error instanceof Error ? error.message : String(error)}`);
          }
        }
      }
      /**
       * Atomically update cache state to prevent inconsistent intermediate states
       * @param credentials - New credentials to cache
       * @param fileModTime - File modification time
       * @param lastCheck - Last check timestamp (optional, defaults to current time)
       */
      updateCacheState(credentials, fileModTime, lastCheck) {
        this.memoryCache = {
          credentials,
          fileModTime,
          lastCheck: lastCheck ?? Date.now()
        };
      }
      /**
       * Clear all cached data and reset the manager to initial state
       */
      clearCache() {
        this.updateCacheState(null, 0, 0);
        this.refreshPromise = null;
        this.checkPromise = null;
      }
      /**
       * Get the current cached credentials (may be expired)
       *
       * @returns The currently cached credentials or null
       */
      getCurrentCredentials() {
        return this.memoryCache.credentials;
      }
      /**
       * Check if there's an ongoing refresh operation
       *
       * @returns true if refresh is in progress, false otherwise
       */
      isRefreshInProgress() {
        return this.refreshPromise !== null;
      }
      /**
       * Set lock configuration for testing purposes
       * @param config - Lock configuration
       */
      setLockConfig(config) {
        this.lockConfig = { ...DEFAULT_LOCK_CONFIG, ...config };
      }
      /**
       * Clean up event listeners (primarily for testing)
       */
      cleanup() {
        if (this.cleanupFunction && this.cleanupHandlersRegistered) {
          this.cleanupFunction();
          process.removeListener("exit", this.cleanupFunction);
          process.removeListener("SIGINT", this.cleanupFunction);
          process.removeListener("SIGTERM", this.cleanupFunction);
          process.removeListener("uncaughtException", this.cleanupFunction);
          process.removeListener("unhandledRejection", this.cleanupFunction);
          this.cleanupHandlersRegistered = false;
          this.cleanupFunction = null;
        }
      }
      /**
       * Get a summary of the current state for debugging
       *
       * @returns Object containing current state information
       */
      getDebugInfo() {
        const hasCredentials = !!this.memoryCache.credentials;
        const credentialsExpired = hasCredentials ? !this.isTokenValid(this.memoryCache.credentials) : false;
        return {
          hasCredentials,
          credentialsExpired,
          isRefreshing: this.isRefreshInProgress(),
          cacheAge: Date.now() - this.memoryCache.lastCheck
        };
      }
    };
  }
});

// packages/core/dist/src/code_assist/oauth2.js
import crypto10 from "node:crypto";
import { promises as fs13 } from "node:fs";
import * as http from "node:http";
import * as net from "node:net";
import path9 from "node:path";
import readline from "node:readline";
import url from "node:url";
function getUseEncryptedStorageFlag() {
  return process.env[FORCE_ENCRYPTED_FILE_ENV_VAR] === "true";
}
async function initOauthClient(authType, config) {
  const client = new import_google_auth_library3.OAuth2Client({
    clientId: OAUTH_CLIENT_ID,
    clientSecret: OAUTH_CLIENT_SECRET,
    transporterOptions: {
      proxy: config.getProxy()
    }
  });
  const useEncryptedStorage = getUseEncryptedStorageFlag();
  if (process.env["GOOGLE_GENAI_USE_GCA"] && process.env["GOOGLE_CLOUD_ACCESS_TOKEN"]) {
    client.setCredentials({
      access_token: process.env["GOOGLE_CLOUD_ACCESS_TOKEN"]
    });
    await fetchAndCacheUserInfo(client);
    return client;
  }
  client.on("tokens", async (tokens) => {
    if (useEncryptedStorage) {
      await OAuthCredentialStorage.saveCredentials(tokens);
    } else {
      await cacheCredentials(tokens);
    }
  });
  if (await loadCachedCredentials(client)) {
    if (!userAccountManager.getCachedGoogleAccount()) {
      try {
        await fetchAndCacheUserInfo(client);
      } catch (error) {
        console.warn("Failed to fetch user info:", getErrorMessage(error));
      }
    }
    console.log("Loaded cached credentials.");
    return client;
  }
  if (authType === AuthType2.CLOUD_SHELL) {
    try {
      console.log("Attempting to authenticate via Cloud Shell VM's ADC.");
      const computeClient = new import_google_auth_library3.Compute({
        // We can leave this empty, since the metadata server will provide
        // the service account email.
      });
      await computeClient.getAccessToken();
      console.log("Authentication successful.");
      return computeClient;
    } catch (e2) {
      throw new Error(`Could not authenticate using Cloud Shell credentials. Please select a different authentication method or ensure you are in a properly configured environment. Error: ${getErrorMessage(e2)}`);
    }
  }
  if (config.isBrowserLaunchSuppressed()) {
    let success = false;
    const maxRetries = 2;
    for (let i = 0; !success && i < maxRetries; i++) {
      success = await authWithUserCode(client);
      if (!success) {
        console.error("\nFailed to authenticate with user code.", i === maxRetries - 1 ? "" : "Retrying...\n");
      }
    }
    if (!success) {
      throw new FatalAuthenticationError("Failed to authenticate with user code.");
    }
  } else {
    const webLogin = await authWithWeb(client);
    console.log(`

Code Assist login required.
Attempting to open authentication page in your browser.
Otherwise navigate to:

${webLogin.authUrl}

`);
    try {
      const childProcess3 = await open_default(webLogin.authUrl);
      childProcess3.on("error", (error) => {
        console.error("Failed to open browser automatically. Please try running again with NO_BROWSER=true set.");
        console.error("Browser error details:", getErrorMessage(error));
      });
    } catch (err) {
      console.error("An unexpected error occurred while trying to open the browser:", getErrorMessage(err), "\nThis might be due to browser compatibility issues or system configuration.", "\nPlease try running again with NO_BROWSER=true set for manual authentication.");
      throw new FatalAuthenticationError(`Failed to open browser: ${getErrorMessage(err)}`);
    }
    console.log("Waiting for authentication...");
    const authTimeout = 5 * 60 * 1e3;
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => {
        reject(new FatalAuthenticationError("Authentication timed out after 5 minutes. The browser tab may have gotten stuck in a loading state. Please try again or use NO_BROWSER=true for manual authentication."));
      }, authTimeout);
    });
    await Promise.race([webLogin.loginCompletePromise, timeoutPromise]);
  }
  return client;
}
async function getOauthClient(authType, config) {
  if (!oauthClientPromises.has(authType)) {
    oauthClientPromises.set(authType, initOauthClient(authType, config));
  }
  return oauthClientPromises.get(authType);
}
async function authWithUserCode(client) {
  const redirectUri = "https://codeassist.google.com/authcode";
  const codeVerifier = await client.generateCodeVerifierAsync();
  const state = crypto10.randomBytes(32).toString("hex");
  const authUrl = client.generateAuthUrl({
    redirect_uri: redirectUri,
    access_type: "offline",
    scope: OAUTH_SCOPE,
    code_challenge_method: import_google_auth_library3.CodeChallengeMethod.S256,
    code_challenge: codeVerifier.codeChallenge,
    state
  });
  console.log("Please visit the following URL to authorize the application:");
  console.log("");
  console.log(authUrl);
  console.log("");
  const code2 = await new Promise((resolve24) => {
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    rl.question("Enter the authorization code: ", (code3) => {
      rl.close();
      resolve24(code3.trim());
    });
  });
  if (!code2) {
    console.error("Authorization code is required.");
    return false;
  }
  try {
    const { tokens } = await client.getToken({
      code: code2,
      codeVerifier: codeVerifier.codeVerifier,
      redirect_uri: redirectUri
    });
    client.setCredentials(tokens);
  } catch (error) {
    console.error("Failed to authenticate with authorization code:", getErrorMessage(error));
    return false;
  }
  return true;
}
async function authWithWeb(client) {
  const port = await getAvailablePort();
  const host = process.env["OAUTH_CALLBACK_HOST"] || "localhost";
  const redirectUri = `http://localhost:${port}/oauth2callback`;
  const state = crypto10.randomBytes(32).toString("hex");
  const authUrl = client.generateAuthUrl({
    redirect_uri: redirectUri,
    access_type: "offline",
    scope: OAUTH_SCOPE,
    state
  });
  const loginCompletePromise = new Promise((resolve24, reject) => {
    const server = http.createServer(async (req, res) => {
      try {
        if (req.url.indexOf("/oauth2callback") === -1) {
          res.writeHead(HTTP_REDIRECT, { Location: SIGN_IN_FAILURE_URL });
          res.end();
          reject(new FatalAuthenticationError("OAuth callback not received. Unexpected request: " + req.url));
        }
        const qs = new url.URL(req.url, "http://localhost:3000").searchParams;
        if (qs.get("error")) {
          res.writeHead(HTTP_REDIRECT, { Location: SIGN_IN_FAILURE_URL });
          res.end();
          const errorCode = qs.get("error");
          const errorDescription = qs.get("error_description") || "No additional details provided";
          reject(new FatalAuthenticationError(`Google OAuth error: ${errorCode}. ${errorDescription}`));
        } else if (qs.get("state") !== state) {
          res.end("State mismatch. Possible CSRF attack");
          reject(new FatalAuthenticationError("OAuth state mismatch. Possible CSRF attack or browser session issue."));
        } else if (qs.get("code")) {
          try {
            const { tokens } = await client.getToken({
              code: qs.get("code"),
              redirect_uri: redirectUri
            });
            client.setCredentials(tokens);
            try {
              await fetchAndCacheUserInfo(client);
            } catch (error) {
              console.warn("Failed to retrieve Google Account ID during authentication:", getErrorMessage(error));
            }
            res.writeHead(HTTP_REDIRECT, { Location: SIGN_IN_SUCCESS_URL });
            res.end();
            resolve24();
          } catch (error) {
            res.writeHead(HTTP_REDIRECT, { Location: SIGN_IN_FAILURE_URL });
            res.end();
            reject(new FatalAuthenticationError(`Failed to exchange authorization code for tokens: ${getErrorMessage(error)}`));
          }
        } else {
          reject(new FatalAuthenticationError("No authorization code received from Google OAuth. Please try authenticating again."));
        }
      } catch (e2) {
        if (e2 instanceof FatalAuthenticationError) {
          reject(e2);
        } else {
          reject(new FatalAuthenticationError(`Unexpected error during OAuth authentication: ${getErrorMessage(e2)}`));
        }
      } finally {
        server.close();
      }
    });
    server.listen(port, host, () => {
    });
    server.on("error", (err) => {
      reject(new FatalAuthenticationError(`OAuth callback server error: ${getErrorMessage(err)}`));
    });
  });
  return {
    authUrl,
    loginCompletePromise
  };
}
function getAvailablePort() {
  return new Promise((resolve24, reject) => {
    let port = 0;
    try {
      const portStr = process.env["OAUTH_CALLBACK_PORT"];
      if (portStr) {
        port = parseInt(portStr, 10);
        if (isNaN(port) || port <= 0 || port > 65535) {
          return reject(new Error(`Invalid value for OAUTH_CALLBACK_PORT: "${portStr}"`));
        }
        return resolve24(port);
      }
      const server = net.createServer();
      server.listen(0, () => {
        const address = server.address();
        port = address.port;
      });
      server.on("listening", () => {
        server.close();
        server.unref();
      });
      server.on("error", (e2) => reject(e2));
      server.on("close", () => resolve24(port));
    } catch (e2) {
      reject(e2);
    }
  });
}
async function loadCachedCredentials(client) {
  const useEncryptedStorage = getUseEncryptedStorageFlag();
  if (useEncryptedStorage) {
    const credentials = await OAuthCredentialStorage.loadCredentials();
    if (credentials) {
      client.setCredentials(credentials);
      return true;
    }
    return false;
  }
  const pathsToTry = [
    Storage.getOAuthCredsPath(),
    process.env["GOOGLE_APPLICATION_CREDENTIALS"]
  ].filter((p) => !!p);
  for (const keyFile of pathsToTry) {
    try {
      const creds = await fs13.readFile(keyFile, "utf-8");
      client.setCredentials(JSON.parse(creds));
      const { token: token2 } = await client.getAccessToken();
      if (!token2) {
        continue;
      }
      await client.getTokenInfo(token2);
      return true;
    } catch (error) {
      console.debug(`Failed to load credentials from ${keyFile}:`, getErrorMessage(error));
    }
  }
  return false;
}
async function cacheCredentials(credentials) {
  const filePath = Storage.getOAuthCredsPath();
  await fs13.mkdir(path9.dirname(filePath), { recursive: true });
  const credString = JSON.stringify(credentials, null, 2);
  await fs13.writeFile(filePath, credString, { mode: 384 });
  try {
    await fs13.chmod(filePath, 384);
  } catch {
  }
}
function clearOauthClientCache() {
  oauthClientPromises.clear();
}
async function clearCachedCredentialFile() {
  try {
    const useEncryptedStorage = getUseEncryptedStorageFlag();
    if (useEncryptedStorage) {
      await OAuthCredentialStorage.clearCredentials();
    } else {
      await fs13.rm(Storage.getOAuthCredsPath(), { force: true });
    }
    await userAccountManager.clearCachedGoogleAccount();
    clearOauthClientCache();
    try {
      const { SharedTokenManager: SharedTokenManager2 } = await Promise.resolve().then(() => (init_sharedTokenManager(), sharedTokenManager_exports));
      const { clearQwenCredentials: clearQwenCredentials2 } = await Promise.resolve().then(() => (init_qwenOAuth2(), qwenOAuth2_exports));
      const sharedManager = SharedTokenManager2.getInstance();
      sharedManager.clearCache();
      await clearQwenCredentials2();
    } catch (qwenError) {
      console.debug("Could not clear Qwen credentials:", qwenError);
    }
  } catch (e2) {
    console.error("Failed to clear cached credentials:", e2);
  }
}
async function fetchAndCacheUserInfo(client) {
  try {
    const { token: token2 } = await client.getAccessToken();
    if (!token2) {
      return;
    }
    const response = await fetch("https://www.googleapis.com/oauth2/v2/userinfo", {
      headers: {
        Authorization: `Bearer ${token2}`
      }
    });
    if (!response.ok) {
      console.error("Failed to fetch user info:", response.status, response.statusText);
      return;
    }
    const userInfo2 = await response.json();
    await userAccountManager.cacheGoogleAccount(userInfo2.email);
  } catch (error) {
    console.error("Error retrieving user info:", error);
  }
}
var import_google_auth_library3, userAccountManager, OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OAUTH_SCOPE, HTTP_REDIRECT, SIGN_IN_SUCCESS_URL, SIGN_IN_FAILURE_URL, oauthClientPromises;
var init_oauth2 = __esm({
  "packages/core/dist/src/code_assist/oauth2.js"() {
    "use strict";
    init_esbuild_shims();
    import_google_auth_library3 = __toESM(require_src6(), 1);
    init_open();
    init_storage();
    init_contentGenerator();
    init_errors();
    init_userAccountManager();
    init_oauth_credential_storage();
    init_token_storage();
    userAccountManager = new UserAccountManager();
    OAUTH_CLIENT_ID = "681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com";
    OAUTH_CLIENT_SECRET = "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";
    OAUTH_SCOPE = [
      "https://www.googleapis.com/auth/cloud-platform",
      "https://www.googleapis.com/auth/userinfo.email",
      "https://www.googleapis.com/auth/userinfo.profile"
    ];
    HTTP_REDIRECT = 301;
    SIGN_IN_SUCCESS_URL = "https://developers.google.com/gemini-code-assist/auth_success_gemini";
    SIGN_IN_FAILURE_URL = "https://developers.google.com/gemini-code-assist/auth_failure_gemini";
    oauthClientPromises = /* @__PURE__ */ new Map();
    __name(getUseEncryptedStorageFlag, "getUseEncryptedStorageFlag");
    __name(initOauthClient, "initOauthClient");
    __name(getOauthClient, "getOauthClient");
    __name(authWithUserCode, "authWithUserCode");
    __name(authWithWeb, "authWithWeb");
    __name(getAvailablePort, "getAvailablePort");
    __name(loadCachedCredentials, "loadCachedCredentials");
    __name(cacheCredentials, "cacheCredentials");
    __name(clearOauthClientCache, "clearOauthClientCache");
    __name(clearCachedCredentialFile, "clearCachedCredentialFile");
    __name(fetchAndCacheUserInfo, "fetchAndCacheUserInfo");
  }
});

// packages/core/dist/src/code_assist/types.js
var IneligibleTierReasonCode, UserTierId, OnboardUserStatusCode;
var init_types2 = __esm({
  "packages/core/dist/src/code_assist/types.js"() {
    "use strict";
    init_esbuild_shims();
    (function(IneligibleTierReasonCode2) {
      IneligibleTierReasonCode2["DASHER_USER"] = "DASHER_USER";
      IneligibleTierReasonCode2["INELIGIBLE_ACCOUNT"] = "INELIGIBLE_ACCOUNT";
      IneligibleTierReasonCode2["NON_USER_ACCOUNT"] = "NON_USER_ACCOUNT";
      IneligibleTierReasonCode2["RESTRICTED_AGE"] = "RESTRICTED_AGE";
      IneligibleTierReasonCode2["RESTRICTED_NETWORK"] = "RESTRICTED_NETWORK";
      IneligibleTierReasonCode2["UNKNOWN"] = "UNKNOWN";
      IneligibleTierReasonCode2["UNKNOWN_LOCATION"] = "UNKNOWN_LOCATION";
      IneligibleTierReasonCode2["UNSUPPORTED_LOCATION"] = "UNSUPPORTED_LOCATION";
    })(IneligibleTierReasonCode || (IneligibleTierReasonCode = {}));
    (function(UserTierId2) {
      UserTierId2["FREE"] = "free-tier";
      UserTierId2["LEGACY"] = "legacy-tier";
      UserTierId2["STANDARD"] = "standard-tier";
    })(UserTierId || (UserTierId = {}));
    (function(OnboardUserStatusCode2) {
      OnboardUserStatusCode2["Default"] = "DEFAULT";
      OnboardUserStatusCode2["Notice"] = "NOTICE";
      OnboardUserStatusCode2["Warning"] = "WARNING";
      OnboardUserStatusCode2["Error"] = "ERROR";
    })(OnboardUserStatusCode || (OnboardUserStatusCode = {}));
  }
});

// packages/core/dist/src/code_assist/converter.js
function toCountTokenRequest(req) {
  return {
    request: {
      model: "models/" + req.model,
      contents: toContents(req.contents)
    }
  };
}
function fromCountTokenResponse(res) {
  return {
    totalTokens: res.totalTokens
  };
}
function toGenerateContentRequest(req, userPromptId, project, sessionId2) {
  return {
    model: req.model,
    project,
    user_prompt_id: userPromptId,
    request: toVertexGenerateContentRequest(req, sessionId2)
  };
}
function fromGenerateContentResponse(res) {
  const inres = res.response;
  const out = new GenerateContentResponse();
  out.candidates = inres.candidates;
  out.automaticFunctionCallingHistory = inres.automaticFunctionCallingHistory;
  out.promptFeedback = inres.promptFeedback;
  out.usageMetadata = inres.usageMetadata;
  out.modelVersion = inres.modelVersion;
  return out;
}
function toVertexGenerateContentRequest(req, sessionId2) {
  return {
    contents: toContents(req.contents),
    systemInstruction: maybeToContent(req.config?.systemInstruction),
    cachedContent: req.config?.cachedContent,
    tools: req.config?.tools,
    toolConfig: req.config?.toolConfig,
    labels: req.config?.labels,
    safetySettings: req.config?.safetySettings,
    generationConfig: toVertexGenerationConfig(req.config),
    session_id: sessionId2
  };
}
function toContents(contents) {
  if (Array.isArray(contents)) {
    return contents.map(toContent);
  }
  return [toContent(contents)];
}
function maybeToContent(content) {
  if (!content) {
    return void 0;
  }
  return toContent(content);
}
function toContent(content) {
  if (Array.isArray(content)) {
    return {
      role: "user",
      parts: toParts(content)
    };
  }
  if (typeof content === "string") {
    return {
      role: "user",
      parts: [{ text: content }]
    };
  }
  if ("parts" in content) {
    return {
      ...content,
      parts: content.parts ? toParts(content.parts.filter((p) => p != null)) : []
    };
  }
  return {
    role: "user",
    parts: [toPart(content)]
  };
}
function toParts(parts) {
  return parts.map(toPart);
}
function toPart(part) {
  if (typeof part === "string") {
    return { text: part };
  }
  if ("thought" in part && part.thought) {
    const thoughtText = `[Thought: ${part.thought}]`;
    const newPart = { ...part };
    delete newPart["thought"];
    const hasApiContent = "functionCall" in newPart || "functionResponse" in newPart || "inlineData" in newPart || "fileData" in newPart;
    if (hasApiContent) {
      return newPart;
    }
    const text = newPart.text;
    const existingText = text ? String(text) : "";
    const combinedText = existingText ? `${existingText}
${thoughtText}` : thoughtText;
    return {
      ...newPart,
      text: combinedText
    };
  }
  return part;
}
function toVertexGenerationConfig(config) {
  if (!config) {
    return void 0;
  }
  return {
    temperature: config.temperature,
    topP: config.topP,
    topK: config.topK,
    candidateCount: config.candidateCount,
    maxOutputTokens: config.maxOutputTokens,
    stopSequences: config.stopSequences,
    responseLogprobs: config.responseLogprobs,
    logprobs: config.logprobs,
    presencePenalty: config.presencePenalty,
    frequencyPenalty: config.frequencyPenalty,
    seed: config.seed,
    responseMimeType: config.responseMimeType,
    responseSchema: config.responseSchema,
    responseJsonSchema: config.responseJsonSchema,
    routingConfig: config.routingConfig,
    modelSelectionConfig: config.modelSelectionConfig,
    responseModalities: config.responseModalities,
    mediaResolution: config.mediaResolution,
    speechConfig: config.speechConfig,
    audioTimestamp: config.audioTimestamp,
    thinkingConfig: config.thinkingConfig
  };
}
var init_converter = __esm({
  "packages/core/dist/src/code_assist/converter.js"() {
    "use strict";
    init_esbuild_shims();
    init_node();
    __name(toCountTokenRequest, "toCountTokenRequest");
    __name(fromCountTokenResponse, "fromCountTokenResponse");
    __name(toGenerateContentRequest, "toGenerateContentRequest");
    __name(fromGenerateContentResponse, "fromGenerateContentResponse");
    __name(toVertexGenerateContentRequest, "toVertexGenerateContentRequest");
    __name(toContents, "toContents");
    __name(maybeToContent, "maybeToContent");
    __name(toContent, "toContent");
    __name(toParts, "toParts");
    __name(toPart, "toPart");
    __name(toVertexGenerationConfig, "toVertexGenerationConfig");
  }
});

// packages/core/dist/src/code_assist/server.js
import * as readline2 from "node:readline";
function isVpcScAffectedUser(error) {
  if (error && typeof error === "object" && "response" in error) {
    const gaxiosError = error;
    const response = gaxiosError.response?.data;
    if (Array.isArray(response?.error?.details)) {
      return response.error.details.some((detail) => detail.reason === "SECURITY_POLICY_VIOLATED");
    }
  }
  return false;
}
var CODE_ASSIST_ENDPOINT, CODE_ASSIST_API_VERSION, CodeAssistServer;
var init_server = __esm({
  "packages/core/dist/src/code_assist/server.js"() {
    "use strict";
    init_esbuild_shims();
    init_types2();
    init_converter();
    CODE_ASSIST_ENDPOINT = "https://localhost:0";
    CODE_ASSIST_API_VERSION = "v1internal";
    CodeAssistServer = class {
      static {
        __name(this, "CodeAssistServer");
      }
      client;
      projectId;
      httpOptions;
      sessionId;
      userTier;
      constructor(client, projectId, httpOptions = {}, sessionId2, userTier) {
        this.client = client;
        this.projectId = projectId;
        this.httpOptions = httpOptions;
        this.sessionId = sessionId2;
        this.userTier = userTier;
      }
      async generateContentStream(req, userPromptId) {
        const resps = await this.requestStreamingPost("streamGenerateContent", toGenerateContentRequest(req, userPromptId, this.projectId, this.sessionId), req.config?.abortSignal);
        return async function* () {
          for await (const resp of resps) {
            yield fromGenerateContentResponse(resp);
          }
        }();
      }
      async generateContent(req, userPromptId) {
        const resp = await this.requestPost("generateContent", toGenerateContentRequest(req, userPromptId, this.projectId, this.sessionId), req.config?.abortSignal);
        return fromGenerateContentResponse(resp);
      }
      async onboardUser(req) {
        return await this.requestPost("onboardUser", req);
      }
      async loadCodeAssist(req) {
        try {
          return await this.requestPost("loadCodeAssist", req);
        } catch (e2) {
          if (isVpcScAffectedUser(e2)) {
            return {
              currentTier: { id: UserTierId.STANDARD }
            };
          } else {
            throw e2;
          }
        }
      }
      async getCodeAssistGlobalUserSetting() {
        return await this.requestGet("getCodeAssistGlobalUserSetting");
      }
      async setCodeAssistGlobalUserSetting(req) {
        return await this.requestPost("setCodeAssistGlobalUserSetting", req);
      }
      async countTokens(req) {
        const resp = await this.requestPost("countTokens", toCountTokenRequest(req));
        return fromCountTokenResponse(resp);
      }
      async embedContent(_req) {
        throw Error();
      }
      async requestPost(method, req, signal) {
        const res = await this.client.request({
          url: this.getMethodUrl(method),
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            ...this.httpOptions.headers
          },
          responseType: "json",
          body: JSON.stringify(req),
          signal
        });
        return res.data;
      }
      async requestGet(method, signal) {
        const res = await this.client.request({
          url: this.getMethodUrl(method),
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            ...this.httpOptions.headers
          },
          responseType: "json",
          signal
        });
        return res.data;
      }
      async requestStreamingPost(method, req, signal) {
        const res = await this.client.request({
          url: this.getMethodUrl(method),
          method: "POST",
          params: {
            alt: "sse"
          },
          headers: {
            "Content-Type": "application/json",
            ...this.httpOptions.headers
          },
          responseType: "stream",
          body: JSON.stringify(req),
          signal
        });
        return async function* () {
          const rl = readline2.createInterface({
            input: res.data,
            crlfDelay: Infinity
            // Recognizes '\r\n' and '\n' as line breaks
          });
          let bufferedLines = [];
          for await (const line of rl) {
            if (line === "") {
              if (bufferedLines.length === 0) {
                continue;
              }
              yield JSON.parse(bufferedLines.join("\n"));
              bufferedLines = [];
            } else if (line.startsWith("data: ")) {
              bufferedLines.push(line.slice(6).trim());
            } else {
              throw new Error(`Unexpected line format in response: ${line}`);
            }
          }
        }();
      }
      getMethodUrl(method) {
        const endpoint = process.env["CODE_ASSIST_ENDPOINT"] ?? CODE_ASSIST_ENDPOINT;
        return `${endpoint}/${CODE_ASSIST_API_VERSION}:${method}`;
      }
    };
    __name(isVpcScAffectedUser, "isVpcScAffectedUser");
  }
});

// packages/core/dist/src/code_assist/setup.js
async function setupUser(client) {
  const projectId = process.env["GOOGLE_CLOUD_PROJECT"] || void 0;
  const caServer = new CodeAssistServer(client, projectId, {}, "", void 0);
  const coreClientMetadata = {
    ideType: "IDE_UNSPECIFIED",
    platform: "PLATFORM_UNSPECIFIED",
    pluginType: "GEMINI"
  };
  const loadRes = await caServer.loadCodeAssist({
    cloudaicompanionProject: projectId,
    metadata: {
      ...coreClientMetadata,
      duetProject: projectId
    }
  });
  if (loadRes.currentTier) {
    if (!loadRes.cloudaicompanionProject) {
      if (projectId) {
        return {
          projectId,
          userTier: loadRes.currentTier.id
        };
      }
      throw new ProjectIdRequiredError();
    }
    return {
      projectId: loadRes.cloudaicompanionProject,
      userTier: loadRes.currentTier.id
    };
  }
  const tier = getOnboardTier(loadRes);
  let onboardReq;
  if (tier.id === UserTierId.FREE) {
    onboardReq = {
      tierId: tier.id,
      cloudaicompanionProject: void 0,
      metadata: coreClientMetadata
    };
  } else {
    onboardReq = {
      tierId: tier.id,
      cloudaicompanionProject: projectId,
      metadata: {
        ...coreClientMetadata,
        duetProject: projectId
      }
    };
  }
  let lroRes = await caServer.onboardUser(onboardReq);
  while (!lroRes.done) {
    await new Promise((f) => setTimeout(f, 5e3));
    lroRes = await caServer.onboardUser(onboardReq);
  }
  if (!lroRes.response?.cloudaicompanionProject?.id) {
    if (projectId) {
      return {
        projectId,
        userTier: tier.id
      };
    }
    throw new ProjectIdRequiredError();
  }
  return {
    projectId: lroRes.response.cloudaicompanionProject.id,
    userTier: tier.id
  };
}
function getOnboardTier(res) {
  for (const tier of res.allowedTiers || []) {
    if (tier.isDefault) {
      return tier;
    }
  }
  return {
    name: "",
    description: "",
    id: UserTierId.LEGACY,
    userDefinedCloudaicompanionProject: true
  };
}
var ProjectIdRequiredError;
var init_setup = __esm({
  "packages/core/dist/src/code_assist/setup.js"() {
    "use strict";
    init_esbuild_shims();
    init_types2();
    init_server();
    ProjectIdRequiredError = class extends Error {
      static {
        __name(this, "ProjectIdRequiredError");
      }
      constructor() {
        super("This account requires setting the GOOGLE_CLOUD_PROJECT env var. See https://goo.gle/gemini-cli-auth-docs#workspace-gca");
      }
    };
    __name(setupUser, "setupUser");
    __name(getOnboardTier, "getOnboardTier");
  }
});

// packages/core/dist/src/utils/safeJsonStringify.js
function safeJsonStringify(obj, space) {
  const seen = /* @__PURE__ */ new WeakSet();
  return JSON.stringify(obj, (key, value) => {
    if (typeof value === "object" && value !== null) {
      if (seen.has(value)) {
        return "[Circular]";
      }
      seen.add(value);
    }
    return value;
  }, space);
}
var init_safeJsonStringify = __esm({
  "packages/core/dist/src/utils/safeJsonStringify.js"() {
    "use strict";
    init_esbuild_shims();
    __name(safeJsonStringify, "safeJsonStringify");
  }
});

// packages/core/dist/src/tools/tool-error.js
var ToolErrorType;
var init_tool_error = __esm({
  "packages/core/dist/src/tools/tool-error.js"() {
    "use strict";
    init_esbuild_shims();
    (function(ToolErrorType2) {
      ToolErrorType2["INVALID_TOOL_PARAMS"] = "invalid_tool_params";
      ToolErrorType2["UNKNOWN"] = "unknown";
      ToolErrorType2["UNHANDLED_EXCEPTION"] = "unhandled_exception";
      ToolErrorType2["TOOL_NOT_REGISTERED"] = "tool_not_registered";
      ToolErrorType2["EXECUTION_FAILED"] = "execution_failed";
      ToolErrorType2["FILE_NOT_FOUND"] = "file_not_found";
      ToolErrorType2["FILE_WRITE_FAILURE"] = "file_write_failure";
      ToolErrorType2["READ_CONTENT_FAILURE"] = "read_content_failure";
      ToolErrorType2["ATTEMPT_TO_CREATE_EXISTING_FILE"] = "attempt_to_create_existing_file";
      ToolErrorType2["FILE_TOO_LARGE"] = "file_too_large";
      ToolErrorType2["PERMISSION_DENIED"] = "permission_denied";
      ToolErrorType2["NO_SPACE_LEFT"] = "no_space_left";
      ToolErrorType2["TARGET_IS_DIRECTORY"] = "target_is_directory";
      ToolErrorType2["PATH_NOT_IN_WORKSPACE"] = "path_not_in_workspace";
      ToolErrorType2["SEARCH_PATH_NOT_FOUND"] = "search_path_not_found";
      ToolErrorType2["SEARCH_PATH_NOT_A_DIRECTORY"] = "search_path_not_a_directory";
      ToolErrorType2["EDIT_PREPARATION_FAILURE"] = "edit_preparation_failure";
      ToolErrorType2["EDIT_NO_OCCURRENCE_FOUND"] = "edit_no_occurrence_found";
      ToolErrorType2["EDIT_EXPECTED_OCCURRENCE_MISMATCH"] = "edit_expected_occurrence_mismatch";
      ToolErrorType2["EDIT_NO_CHANGE"] = "edit_no_change";
      ToolErrorType2["EDIT_NO_CHANGE_LLM_JUDGEMENT"] = "edit_no_change_llm_judgement";
      ToolErrorType2["GLOB_EXECUTION_ERROR"] = "glob_execution_error";
      ToolErrorType2["GREP_EXECUTION_ERROR"] = "grep_execution_error";
      ToolErrorType2["LS_EXECUTION_ERROR"] = "ls_execution_error";
      ToolErrorType2["PATH_IS_NOT_A_DIRECTORY"] = "path_is_not_a_directory";
      ToolErrorType2["MCP_TOOL_ERROR"] = "mcp_tool_error";
      ToolErrorType2["MEMORY_TOOL_EXECUTION_ERROR"] = "memory_tool_execution_error";
      ToolErrorType2["READ_MANY_FILES_SEARCH_ERROR"] = "read_many_files_search_error";
      ToolErrorType2["SHELL_EXECUTE_ERROR"] = "shell_execute_error";
      ToolErrorType2["DISCOVERED_TOOL_EXECUTION_ERROR"] = "discovered_tool_execution_error";
      ToolErrorType2["WEB_FETCH_NO_URL_IN_PROMPT"] = "web_fetch_no_url_in_prompt";
      ToolErrorType2["WEB_FETCH_FALLBACK_FAILED"] = "web_fetch_fallback_failed";
      ToolErrorType2["WEB_FETCH_PROCESSING_ERROR"] = "web_fetch_processing_error";
      ToolErrorType2["WEB_SEARCH_FAILED"] = "web_search_failed";
    })(ToolErrorType || (ToolErrorType = {}));
  }
});

// packages/core/node_modules/ajv/dist/compile/codegen/code.js
var require_code = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/codegen/code.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.regexpCode = exports2.getEsmExportName = exports2.getProperty = exports2.safeStringify = exports2.stringify = exports2.strConcat = exports2.addCodeArg = exports2.str = exports2._ = exports2.nil = exports2._Code = exports2.Name = exports2.IDENTIFIER = exports2._CodeOrName = void 0;
    var _CodeOrName = class {
      static {
        __name(this, "_CodeOrName");
      }
    };
    exports2._CodeOrName = _CodeOrName;
    exports2.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
    var Name = class extends _CodeOrName {
      static {
        __name(this, "Name");
      }
      constructor(s2) {
        super();
        if (!exports2.IDENTIFIER.test(s2))
          throw new Error("CodeGen: name must be a valid identifier");
        this.str = s2;
      }
      toString() {
        return this.str;
      }
      emptyStr() {
        return false;
      }
      get names() {
        return { [this.str]: 1 };
      }
    };
    exports2.Name = Name;
    var _Code = class extends _CodeOrName {
      static {
        __name(this, "_Code");
      }
      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 _a6;
        return (_a6 = this._str) !== null && _a6 !== void 0 ? _a6 : this._str = this._items.reduce((s2, c3) => `${s2}${c3}`, "");
      }
      get names() {
        var _a6;
        return (_a6 = this._names) !== null && _a6 !== void 0 ? _a6 : this._names = this._items.reduce((names, c3) => {
          if (c3 instanceof Name)
            names[c3.str] = (names[c3.str] || 0) + 1;
          return names;
        }, {});
      }
    };
    exports2._Code = _Code;
    exports2.nil = new _Code("");
    function _(strs, ...args) {
      const code2 = [strs[0]];
      let i = 0;
      while (i < args.length) {
        addCodeArg(code2, args[i]);
        code2.push(strs[++i]);
      }
      return new _Code(code2);
    }
    __name(_, "_");
    exports2._ = _;
    var plus = new _Code("+");
    function str2(strs, ...args) {
      const expr = [safeStringify(strs[0])];
      let i = 0;
      while (i < args.length) {
        expr.push(plus);
        addCodeArg(expr, args[i]);
        expr.push(plus, safeStringify(strs[++i]));
      }
      optimize(expr);
      return new _Code(expr);
    }
    __name(str2, "str");
    exports2.str = str2;
    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));
    }
    __name(addCodeArg, "addCodeArg");
    exports2.addCodeArg = addCodeArg;
    function optimize(expr) {
      let i = 1;
      while (i < expr.length - 1) {
        if (expr[i] === plus) {
          const res = mergeExprItems(expr[i - 1], expr[i + 1]);
          if (res !== void 0) {
            expr.splice(i - 1, 3, res);
            continue;
          }
          expr[i++] = "+";
        }
        i++;
      }
    }
    __name(optimize, "optimize");
    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;
    }
    __name(mergeExprItems, "mergeExprItems");
    function strConcat(c1, c22) {
      return c22.emptyStr() ? c1 : c1.emptyStr() ? c22 : str2`${c1}${c22}`;
    }
    __name(strConcat, "strConcat");
    exports2.strConcat = strConcat;
    function interpolate(x) {
      return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x);
    }
    __name(interpolate, "interpolate");
    function stringify5(x) {
      return new _Code(safeStringify(x));
    }
    __name(stringify5, "stringify");
    exports2.stringify = stringify5;
    function safeStringify(x) {
      return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
    }
    __name(safeStringify, "safeStringify");
    exports2.safeStringify = safeStringify;
    function getProperty2(key) {
      return typeof key == "string" && exports2.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`;
    }
    __name(getProperty2, "getProperty");
    exports2.getProperty = getProperty2;
    function getEsmExportName(key) {
      if (typeof key == "string" && exports2.IDENTIFIER.test(key)) {
        return new _Code(`${key}`);
      }
      throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
    }
    __name(getEsmExportName, "getEsmExportName");
    exports2.getEsmExportName = getEsmExportName;
    function regexpCode(rx) {
      return new _Code(rx.toString());
    }
    __name(regexpCode, "regexpCode");
    exports2.regexpCode = regexpCode;
  }
});

// packages/core/node_modules/ajv/dist/compile/codegen/scope.js
var require_scope = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/codegen/scope.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ValueScope = exports2.ValueScopeName = exports2.Scope = exports2.varKinds = exports2.UsedValueState = void 0;
    var code_1 = require_code();
    var ValueError = class extends Error {
      static {
        __name(this, "ValueError");
      }
      constructor(name3) {
        super(`CodeGen: "code" for ${name3} not defined`);
        this.value = name3.value;
      }
    };
    var UsedValueState;
    (function(UsedValueState2) {
      UsedValueState2[UsedValueState2["Started"] = 0] = "Started";
      UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed";
    })(UsedValueState || (exports2.UsedValueState = UsedValueState = {}));
    exports2.varKinds = {
      const: new code_1.Name("const"),
      let: new code_1.Name("let"),
      var: new code_1.Name("var")
    };
    var Scope = class {
      static {
        __name(this, "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 _a6, _b2;
        if (((_b2 = (_a6 = this._parent) === null || _a6 === void 0 ? void 0 : _a6._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 };
      }
    };
    exports2.Scope = Scope;
    var ValueScopeName = class extends code_1.Name {
      static {
        __name(this, "ValueScopeName");
      }
      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}]`;
      }
    };
    exports2.ValueScopeName = ValueScopeName;
    var line = (0, code_1._)`\n`;
    var ValueScope = class extends Scope {
      static {
        __name(this, "ValueScope");
      }
      constructor(opts) {
        super(opts);
        this._values = {};
        this._scope = opts.scope;
        this.opts = { ...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 _a6;
        if (value.ref === void 0)
          throw new Error("CodeGen: ref must be passed in value");
        const name3 = this.toName(nameOrPrefix);
        const { prefix } = name3;
        const valueKey = (_a6 = value.key) !== null && _a6 !== void 0 ? _a6 : 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, name3);
        const s2 = this._scope[prefix] || (this._scope[prefix] = []);
        const itemIndex = s2.length;
        s2[itemIndex] = value.ref;
        name3.setValue(value, { property: prefix, itemIndex });
        return name3;
      }
      getValue(prefix, keyOrRef) {
        const vs = this._values[prefix];
        if (!vs)
          return;
        return vs.get(keyOrRef);
      }
      scopeRefs(scopeName, values = this._values) {
        return this._reduceValues(values, (name3) => {
          if (name3.scopePath === void 0)
            throw new Error(`CodeGen: name "${name3}" has no value`);
          return (0, code_1._)`${scopeName}${name3.scopePath}`;
        });
      }
      scopeCode(values = this._values, usedValues, getCode) {
        return this._reduceValues(values, (name3) => {
          if (name3.value === void 0)
            throw new Error(`CodeGen: name "${name3}" has no value`);
          return name3.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((name3) => {
            if (nameSet.has(name3))
              return;
            nameSet.set(name3, UsedValueState.Started);
            let c3 = valueCode(name3);
            if (c3) {
              const def2 = this.opts.es5 ? exports2.varKinds.var : exports2.varKinds.const;
              code2 = (0, code_1._)`${code2}${def2} ${name3} = ${c3};${this.opts._n}`;
            } else if (c3 = getCode === null || getCode === void 0 ? void 0 : getCode(name3)) {
              code2 = (0, code_1._)`${code2}${c3}${this.opts._n}`;
            } else {
              throw new ValueError(name3);
            }
            nameSet.set(name3, UsedValueState.Completed);
          });
        }
        return code2;
      }
    };
    exports2.ValueScope = ValueScope;
  }
});

// packages/core/node_modules/ajv/dist/compile/codegen/index.js
var require_codegen = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/codegen/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.or = exports2.and = exports2.not = exports2.CodeGen = exports2.operators = exports2.varKinds = exports2.ValueScopeName = exports2.ValueScope = exports2.Scope = exports2.Name = exports2.regexpCode = exports2.stringify = exports2.getProperty = exports2.nil = exports2.strConcat = exports2.str = exports2._ = void 0;
    var code_1 = require_code();
    var scope_1 = require_scope();
    var code_2 = require_code();
    Object.defineProperty(exports2, "_", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return code_2._;
    }, "get") });
    Object.defineProperty(exports2, "str", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return code_2.str;
    }, "get") });
    Object.defineProperty(exports2, "strConcat", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return code_2.strConcat;
    }, "get") });
    Object.defineProperty(exports2, "nil", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return code_2.nil;
    }, "get") });
    Object.defineProperty(exports2, "getProperty", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return code_2.getProperty;
    }, "get") });
    Object.defineProperty(exports2, "stringify", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return code_2.stringify;
    }, "get") });
    Object.defineProperty(exports2, "regexpCode", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return code_2.regexpCode;
    }, "get") });
    Object.defineProperty(exports2, "Name", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return code_2.Name;
    }, "get") });
    var scope_2 = require_scope();
    Object.defineProperty(exports2, "Scope", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return scope_2.Scope;
    }, "get") });
    Object.defineProperty(exports2, "ValueScope", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return scope_2.ValueScope;
    }, "get") });
    Object.defineProperty(exports2, "ValueScopeName", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return scope_2.ValueScopeName;
    }, "get") });
    Object.defineProperty(exports2, "varKinds", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return scope_2.varKinds;
    }, "get") });
    exports2.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("+")
    };
    var Node4 = class {
      static {
        __name(this, "Node");
      }
      optimizeNodes() {
        return this;
      }
      optimizeNames(_names, _constants) {
        return this;
      }
    };
    var Def = class extends Node4 {
      static {
        __name(this, "Def");
      }
      constructor(varKind, name3, rhs) {
        super();
        this.varKind = varKind;
        this.name = name3;
        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(names, constants4) {
        if (!names[this.name.str])
          return;
        if (this.rhs)
          this.rhs = optimizeExpr(this.rhs, names, constants4);
        return this;
      }
      get names() {
        return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
      }
    };
    var Assign = class extends Node4 {
      static {
        __name(this, "Assign");
      }
      constructor(lhs, rhs, sideEffects) {
        super();
        this.lhs = lhs;
        this.rhs = rhs;
        this.sideEffects = sideEffects;
      }
      render({ _n }) {
        return `${this.lhs} = ${this.rhs};` + _n;
      }
      optimizeNames(names, constants4) {
        if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
          return;
        this.rhs = optimizeExpr(this.rhs, names, constants4);
        return this;
      }
      get names() {
        const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
        return addExprNames(names, this.rhs);
      }
    };
    var AssignOp = class extends Assign {
      static {
        __name(this, "AssignOp");
      }
      constructor(lhs, op, rhs, sideEffects) {
        super(lhs, rhs, sideEffects);
        this.op = op;
      }
      render({ _n }) {
        return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
      }
    };
    var Label = class extends Node4 {
      static {
        __name(this, "Label");
      }
      constructor(label) {
        super();
        this.label = label;
        this.names = {};
      }
      render({ _n }) {
        return `${this.label}:` + _n;
      }
    };
    var Break = class extends Node4 {
      static {
        __name(this, "Break");
      }
      constructor(label) {
        super();
        this.label = label;
        this.names = {};
      }
      render({ _n }) {
        const label = this.label ? ` ${this.label}` : "";
        return `break${label};` + _n;
      }
    };
    var Throw = class extends Node4 {
      static {
        __name(this, "Throw");
      }
      constructor(error) {
        super();
        this.error = error;
      }
      render({ _n }) {
        return `throw ${this.error};` + _n;
      }
      get names() {
        return this.error.names;
      }
    };
    var AnyCode = class extends Node4 {
      static {
        __name(this, "AnyCode");
      }
      constructor(code2) {
        super();
        this.code = code2;
      }
      render({ _n }) {
        return `${this.code};` + _n;
      }
      optimizeNodes() {
        return `${this.code}` ? this : void 0;
      }
      optimizeNames(names, constants4) {
        this.code = optimizeExpr(this.code, names, constants4);
        return this;
      }
      get names() {
        return this.code instanceof code_1._CodeOrName ? this.code.names : {};
      }
    };
    var ParentNode = class extends Node4 {
      static {
        __name(this, "ParentNode");
      }
      constructor(nodes = []) {
        super();
        this.nodes = nodes;
      }
      render(opts) {
        return this.nodes.reduce((code2, n2) => code2 + n2.render(opts), "");
      }
      optimizeNodes() {
        const { nodes } = this;
        let i = nodes.length;
        while (i--) {
          const n2 = nodes[i].optimizeNodes();
          if (Array.isArray(n2))
            nodes.splice(i, 1, ...n2);
          else if (n2)
            nodes[i] = n2;
          else
            nodes.splice(i, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      optimizeNames(names, constants4) {
        const { nodes } = this;
        let i = nodes.length;
        while (i--) {
          const n2 = nodes[i];
          if (n2.optimizeNames(names, constants4))
            continue;
          subtractNames(names, n2.names);
          nodes.splice(i, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      get names() {
        return this.nodes.reduce((names, n2) => addNames(names, n2.names), {});
      }
    };
    var BlockNode = class extends ParentNode {
      static {
        __name(this, "BlockNode");
      }
      render(opts) {
        return "{" + opts._n + super.render(opts) + "}" + opts._n;
      }
    };
    var Root2 = class extends ParentNode {
      static {
        __name(this, "Root");
      }
    };
    var Else = class extends BlockNode {
      static {
        __name(this, "Else");
      }
    };
    Else.kind = "else";
    var If = class _If extends BlockNode {
      static {
        __name(this, "If");
      }
      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 e2 = this.else;
        if (e2) {
          const ns = e2.optimizeNodes();
          e2 = this.else = Array.isArray(ns) ? new Else(ns) : ns;
        }
        if (e2) {
          if (cond === false)
            return e2 instanceof _If ? e2 : e2.nodes;
          if (this.nodes.length)
            return this;
          return new _If(not(cond), e2 instanceof _If ? [e2] : e2.nodes);
        }
        if (cond === false || !this.nodes.length)
          return void 0;
        return this;
      }
      optimizeNames(names, constants4) {
        var _a6;
        this.else = (_a6 = this.else) === null || _a6 === void 0 ? void 0 : _a6.optimizeNames(names, constants4);
        if (!(super.optimizeNames(names, constants4) || this.else))
          return;
        this.condition = optimizeExpr(this.condition, names, constants4);
        return this;
      }
      get names() {
        const names = super.names;
        addExprNames(names, this.condition);
        if (this.else)
          addNames(names, this.else.names);
        return names;
      }
    };
    If.kind = "if";
    var For = class extends BlockNode {
      static {
        __name(this, "For");
      }
    };
    For.kind = "for";
    var ForLoop = class extends For {
      static {
        __name(this, "ForLoop");
      }
      constructor(iteration) {
        super();
        this.iteration = iteration;
      }
      render(opts) {
        return `for(${this.iteration})` + super.render(opts);
      }
      optimizeNames(names, constants4) {
        if (!super.optimizeNames(names, constants4))
          return;
        this.iteration = optimizeExpr(this.iteration, names, constants4);
        return this;
      }
      get names() {
        return addNames(super.names, this.iteration.names);
      }
    };
    var ForRange = class extends For {
      static {
        __name(this, "ForRange");
      }
      constructor(varKind, name3, from, to) {
        super();
        this.varKind = varKind;
        this.name = name3;
        this.from = from;
        this.to = to;
      }
      render(opts) {
        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
        const { name: name3, from, to } = this;
        return `for(${varKind} ${name3}=${from}; ${name3}<${to}; ${name3}++)` + super.render(opts);
      }
      get names() {
        const names = addExprNames(super.names, this.from);
        return addExprNames(names, this.to);
      }
    };
    var ForIter = class extends For {
      static {
        __name(this, "ForIter");
      }
      constructor(loop, varKind, name3, iterable) {
        super();
        this.loop = loop;
        this.varKind = varKind;
        this.name = name3;
        this.iterable = iterable;
      }
      render(opts) {
        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
      }
      optimizeNames(names, constants4) {
        if (!super.optimizeNames(names, constants4))
          return;
        this.iterable = optimizeExpr(this.iterable, names, constants4);
        return this;
      }
      get names() {
        return addNames(super.names, this.iterable.names);
      }
    };
    var Func = class extends BlockNode {
      static {
        __name(this, "Func");
      }
      constructor(name3, args, async) {
        super();
        this.name = name3;
        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";
    var Return = class extends ParentNode {
      static {
        __name(this, "Return");
      }
      render(opts) {
        return "return " + super.render(opts);
      }
    };
    Return.kind = "return";
    var Try = class extends BlockNode {
      static {
        __name(this, "Try");
      }
      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 _a6, _b2;
        super.optimizeNodes();
        (_a6 = this.catch) === null || _a6 === void 0 ? void 0 : _a6.optimizeNodes();
        (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNodes();
        return this;
      }
      optimizeNames(names, constants4) {
        var _a6, _b2;
        super.optimizeNames(names, constants4);
        (_a6 = this.catch) === null || _a6 === void 0 ? void 0 : _a6.optimizeNames(names, constants4);
        (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNames(names, constants4);
        return this;
      }
      get names() {
        const names = super.names;
        if (this.catch)
          addNames(names, this.catch.names);
        if (this.finally)
          addNames(names, this.finally.names);
        return names;
      }
    };
    var Catch = class extends BlockNode {
      static {
        __name(this, "Catch");
      }
      constructor(error) {
        super();
        this.error = error;
      }
      render(opts) {
        return `catch(${this.error})` + super.render(opts);
      }
    };
    Catch.kind = "catch";
    var Finally = class extends BlockNode {
      static {
        __name(this, "Finally");
      }
      render(opts) {
        return "finally" + super.render(opts);
      }
    };
    Finally.kind = "finally";
    var CodeGen = class {
      static {
        __name(this, "CodeGen");
      }
      constructor(extScope, opts = {}) {
        this._values = {};
        this._blockStarts = [];
        this._constants = {};
        this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
        this._extScope = extScope;
        this._scope = new scope_1.Scope({ parent: extScope });
        this._nodes = [new Root2()];
      }
      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 name3 = this._extScope.value(prefixOrName, value);
        const vs = this._values[name3.prefix] || (this._values[name3.prefix] = /* @__PURE__ */ new Set());
        vs.add(name3);
        return name3;
      }
      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 name3 = this._scope.toName(nameOrPrefix);
        if (rhs !== void 0 && constant)
          this._constants[name3.str] = rhs;
        this._leafNode(new Def(varKind, name3, rhs));
        return name3;
      }
      // `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, exports2.operators.ADD, rhs));
      }
      // appends passed SafeExpr to code or executes Block
      code(c3) {
        if (typeof c3 == "function")
          c3();
        else if (c3 !== code_1.nil)
          this._leafNode(new AnyCode(c3));
        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 name3 = this._scope.toName(nameOrPrefix);
        return this._for(new ForRange(varKind, name3, from, to), () => forBody(name3));
      }
      // `for-of` statement (in es5 mode replace with a normal for loop)
      forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
        const name3 = 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`, (i) => {
            this.var(name3, (0, code_1._)`${arr}[${i}]`);
            forBody(name3);
          });
        }
        return this._for(new ForIter("of", varKind, name3, iterable), () => forBody(name3));
      }
      // `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 name3 = this._scope.toName(nameOrPrefix);
        return this._for(new ForIter("in", varKind, name3, obj), () => forBody(name3));
      }
      // 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 error = this.name("e");
          this._currNode = node.catch = new Catch(error);
          catchCode(error);
        }
        if (finallyCode) {
          this._currNode = node.finally = new Finally();
          this.code(finallyCode);
        }
        return this._endBlockNode(Catch, Finally);
      }
      // `throw` statement
      throw(error) {
        return this._leafNode(new Throw(error));
      }
      // 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 len = this._blockStarts.pop();
        if (len === void 0)
          throw new Error("CodeGen: not in self-balancing block");
        const toClose = this._nodes.length - len;
        if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) {
          throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
        }
        this._nodes.length = len;
        return this;
      }
      // `function` heading (or definition if funcBody is passed)
      func(name3, args = code_1.nil, async, funcBody) {
        this._blockNode(new Func(name3, args, async));
        if (funcBody)
          this.code(funcBody).endFunc();
        return this;
      }
      // end function definition
      endFunc() {
        return this._endBlockNode(Func);
      }
      optimize(n2 = 1) {
        while (n2-- > 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 n2 = this._currNode;
        if (n2 instanceof N1 || N2 && n2 instanceof N2) {
          this._nodes.pop();
          return this;
        }
        throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
      }
      _elseNode(node) {
        const n2 = this._currNode;
        if (!(n2 instanceof If)) {
          throw new Error('CodeGen: "else" without "if"');
        }
        this._currNode = n2.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;
      }
    };
    exports2.CodeGen = CodeGen;
    function addNames(names, from) {
      for (const n2 in from)
        names[n2] = (names[n2] || 0) + (from[n2] || 0);
      return names;
    }
    __name(addNames, "addNames");
    function addExprNames(names, from) {
      return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
    }
    __name(addExprNames, "addExprNames");
    function optimizeExpr(expr, names, constants4) {
      if (expr instanceof code_1.Name)
        return replaceName(expr);
      if (!canOptimize(expr))
        return expr;
      return new code_1._Code(expr._items.reduce((items, c3) => {
        if (c3 instanceof code_1.Name)
          c3 = replaceName(c3);
        if (c3 instanceof code_1._Code)
          items.push(...c3._items);
        else
          items.push(c3);
        return items;
      }, []));
      function replaceName(n2) {
        const c3 = constants4[n2.str];
        if (c3 === void 0 || names[n2.str] !== 1)
          return n2;
        delete names[n2.str];
        return c3;
      }
      __name(replaceName, "replaceName");
      function canOptimize(e2) {
        return e2 instanceof code_1._Code && e2._items.some((c3) => c3 instanceof code_1.Name && names[c3.str] === 1 && constants4[c3.str] !== void 0);
      }
      __name(canOptimize, "canOptimize");
    }
    __name(optimizeExpr, "optimizeExpr");
    function subtractNames(names, from) {
      for (const n2 in from)
        names[n2] = (names[n2] || 0) - (from[n2] || 0);
    }
    __name(subtractNames, "subtractNames");
    function not(x) {
      return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`;
    }
    __name(not, "not");
    exports2.not = not;
    var andCode = mappend(exports2.operators.AND);
    function and(...args) {
      return args.reduce(andCode);
    }
    __name(and, "and");
    exports2.and = and;
    var orCode = mappend(exports2.operators.OR);
    function or(...args) {
      return args.reduce(orCode);
    }
    __name(or, "or");
    exports2.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)}`;
    }
    __name(mappend, "mappend");
    function par(x) {
      return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`;
    }
    __name(par, "par");
  }
});

// packages/core/node_modules/ajv/dist/compile/util.js
var require_util9 = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/util.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.checkStrictMode = exports2.getErrorPath = exports2.Type = exports2.useFunc = exports2.setEvaluated = exports2.evaluatedPropsToName = exports2.mergeEvaluated = exports2.eachItem = exports2.unescapeJsonPointer = exports2.escapeJsonPointer = exports2.escapeFragment = exports2.unescapeFragment = exports2.schemaRefOrVal = exports2.schemaHasRulesButRef = exports2.schemaHasRules = exports2.checkUnknownRules = exports2.alwaysValidSchema = exports2.toHash = void 0;
    var codegen_1 = require_codegen();
    var code_1 = require_code();
    function toHash(arr) {
      const hash = {};
      for (const item of arr)
        hash[item] = true;
      return hash;
    }
    __name(toHash, "toHash");
    exports2.toHash = toHash;
    function alwaysValidSchema(it, schema) {
      if (typeof schema == "boolean")
        return schema;
      if (Object.keys(schema).length === 0)
        return true;
      checkUnknownRules(it, schema);
      return !schemaHasRules(schema, it.self.RULES.all);
    }
    __name(alwaysValidSchema, "alwaysValidSchema");
    exports2.alwaysValidSchema = alwaysValidSchema;
    function checkUnknownRules(it, schema = it.schema) {
      const { opts, self: self2 } = it;
      if (!opts.strictSchema)
        return;
      if (typeof schema === "boolean")
        return;
      const rules = self2.RULES.keywords;
      for (const key in schema) {
        if (!rules[key])
          checkStrictMode(it, `unknown keyword: "${key}"`);
      }
    }
    __name(checkUnknownRules, "checkUnknownRules");
    exports2.checkUnknownRules = checkUnknownRules;
    function schemaHasRules(schema, rules) {
      if (typeof schema == "boolean")
        return !schema;
      for (const key in schema)
        if (rules[key])
          return true;
      return false;
    }
    __name(schemaHasRules, "schemaHasRules");
    exports2.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;
    }
    __name(schemaHasRulesButRef, "schemaHasRulesButRef");
    exports2.schemaHasRulesButRef = schemaHasRulesButRef;
    function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $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)(keyword)}`;
    }
    __name(schemaRefOrVal, "schemaRefOrVal");
    exports2.schemaRefOrVal = schemaRefOrVal;
    function unescapeFragment(str2) {
      return unescapeJsonPointer(decodeURIComponent(str2));
    }
    __name(unescapeFragment, "unescapeFragment");
    exports2.unescapeFragment = unescapeFragment;
    function escapeFragment(str2) {
      return encodeURIComponent(escapeJsonPointer(str2));
    }
    __name(escapeFragment, "escapeFragment");
    exports2.escapeFragment = escapeFragment;
    function escapeJsonPointer(str2) {
      if (typeof str2 == "number")
        return `${str2}`;
      return str2.replace(/~/g, "~0").replace(/\//g, "~1");
    }
    __name(escapeJsonPointer, "escapeJsonPointer");
    exports2.escapeJsonPointer = escapeJsonPointer;
    function unescapeJsonPointer(str2) {
      return str2.replace(/~1/g, "/").replace(/~0/g, "~");
    }
    __name(unescapeJsonPointer, "unescapeJsonPointer");
    exports2.unescapeJsonPointer = unescapeJsonPointer;
    function eachItem(xs, f) {
      if (Array.isArray(xs)) {
        for (const x of xs)
          f(x);
      } else {
        f(xs);
      }
    }
    __name(eachItem, "eachItem");
    exports2.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;
      };
    }
    __name(makeMergeEvaluated, "makeMergeEvaluated");
    exports2.mergeEvaluated = {
      props: makeMergeEvaluated({
        mergeNames: /* @__PURE__ */ __name((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})`));
        }), "mergeNames"),
        mergeToName: /* @__PURE__ */ __name((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);
          }
        }), "mergeToName"),
        mergeValues: /* @__PURE__ */ __name((from, to) => from === true ? true : { ...from, ...to }, "mergeValues"),
        resultToName: evaluatedPropsToName
      }),
      items: makeMergeEvaluated({
        mergeNames: /* @__PURE__ */ __name((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}`)), "mergeNames"),
        mergeToName: /* @__PURE__ */ __name((gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), "mergeToName"),
        mergeValues: /* @__PURE__ */ __name((from, to) => from === true ? true : Math.max(from, to), "mergeValues"),
        resultToName: /* @__PURE__ */ __name((gen, items) => gen.var("items", items), "resultToName")
      })
    };
    function evaluatedPropsToName(gen, ps) {
      if (ps === true)
        return gen.var("props", true);
      const props = gen.var("props", (0, codegen_1._)`{}`);
      if (ps !== void 0)
        setEvaluated(gen, props, ps);
      return props;
    }
    __name(evaluatedPropsToName, "evaluatedPropsToName");
    exports2.evaluatedPropsToName = evaluatedPropsToName;
    function setEvaluated(gen, props, ps) {
      Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true));
    }
    __name(setEvaluated, "setEvaluated");
    exports2.setEvaluated = setEvaluated;
    var snippets = {};
    function useFunc(gen, f) {
      return gen.scopeValue("func", {
        ref: f,
        code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code))
      });
    }
    __name(useFunc, "useFunc");
    exports2.useFunc = useFunc;
    var Type2;
    (function(Type3) {
      Type3[Type3["Num"] = 0] = "Num";
      Type3[Type3["Str"] = 1] = "Str";
    })(Type2 || (exports2.Type = Type2 = {}));
    function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
      if (dataProp instanceof codegen_1.Name) {
        const isNumber3 = dataPropType === Type2.Num;
        return jsPropertySyntax ? isNumber3 ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber3 ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`;
      }
      return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
    }
    __name(getErrorPath, "getErrorPath");
    exports2.getErrorPath = getErrorPath;
    function checkStrictMode(it, msg, mode = it.opts.strictSchema) {
      if (!mode)
        return;
      msg = `strict mode: ${msg}`;
      if (mode === true)
        throw new Error(msg);
      it.self.logger.warn(msg);
    }
    __name(checkStrictMode, "checkStrictMode");
    exports2.checkStrictMode = checkStrictMode;
  }
});

// packages/core/node_modules/ajv/dist/compile/names.js
var require_names = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/names.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var names = {
      // 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")
    };
    exports2.default = names;
  }
});

// packages/core/node_modules/ajv/dist/compile/errors.js
var require_errors2 = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/errors.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.extendErrors = exports2.resetErrorsCount = exports2.reportExtraError = exports2.reportError = exports2.keyword$DataError = exports2.keywordError = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var names_1 = require_names();
    exports2.keywordError = {
      message: /* @__PURE__ */ __name(({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation`, "message")
    };
    exports2.keyword$DataError = {
      message: /* @__PURE__ */ __name(({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)`, "message")
    };
    function reportError3(cxt, error = exports2.keywordError, errorPaths, overrideAllErrors) {
      const { it } = cxt;
      const { gen, compositeRule, allErrors } = it;
      const errObj = errorObjectCode(cxt, error, errorPaths);
      if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) {
        addError(gen, errObj);
      } else {
        returnErrors(it, (0, codegen_1._)`[${errObj}]`);
      }
    }
    __name(reportError3, "reportError");
    exports2.reportError = reportError3;
    function reportExtraError(cxt, error = exports2.keywordError, errorPaths) {
      const { it } = cxt;
      const { gen, compositeRule, allErrors } = it;
      const errObj = errorObjectCode(cxt, error, errorPaths);
      addError(gen, errObj);
      if (!(compositeRule || allErrors)) {
        returnErrors(it, names_1.default.vErrors);
      }
    }
    __name(reportExtraError, "reportExtraError");
    exports2.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)));
    }
    __name(resetErrorsCount, "resetErrorsCount");
    exports2.resetErrorsCount = resetErrorsCount;
    function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) {
      if (errsCount === void 0)
        throw new Error("ajv implementation error");
      const err = gen.name("err");
      gen.forRange("i", errsCount, names_1.default.errors, (i) => {
        gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`);
        gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
        gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`);
        if (it.opts.verbose) {
          gen.assign((0, codegen_1._)`${err}.schema`, schemaValue);
          gen.assign((0, codegen_1._)`${err}.data`, data);
        }
      });
    }
    __name(extendErrors, "extendErrors");
    exports2.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}++`);
    }
    __name(addError, "addError");
    function returnErrors(it, errs) {
      const { gen, validateName: validateName2, schemaEnv } = it;
      if (schemaEnv.$async) {
        gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`);
      } else {
        gen.assign((0, codegen_1._)`${validateName2}.errors`, errs);
        gen.return(false);
      }
    }
    __name(returnErrors, "returnErrors");
    var 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, error, errorPaths) {
      const { createErrors } = cxt.it;
      if (createErrors === false)
        return (0, codegen_1._)`{}`;
      return errorObject(cxt, error, errorPaths);
    }
    __name(errorObjectCode, "errorObjectCode");
    function errorObject(cxt, error, errorPaths = {}) {
      const { gen, it } = cxt;
      const keyValues = [
        errorInstancePath(it, errorPaths),
        errorSchemaPath(cxt, errorPaths)
      ];
      extraErrorProps(cxt, error, keyValues);
      return gen.object(...keyValues);
    }
    __name(errorObject, "errorObject");
    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)];
    }
    __name(errorInstancePath, "errorInstancePath");
    function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
      let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`;
      if (schemaPath) {
        schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
      }
      return [E.schemaPath, schPath];
    }
    __name(errorSchemaPath, "errorSchemaPath");
    function extraErrorProps(cxt, { params, message }, keyValues) {
      const { keyword, data, schemaValue, it } = cxt;
      const { opts, propertyName, topSchemaRef, schemaPath } = it;
      keyValues.push([E.keyword, keyword], [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]);
    }
    __name(extraErrorProps, "extraErrorProps");
  }
});

// packages/core/node_modules/ajv/dist/compile/validate/boolSchema.js
var require_boolSchema = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.boolOrEmptySchema = exports2.topBoolOrEmptySchema = void 0;
    var errors_1 = require_errors2();
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var boolError = {
      message: "boolean schema is false"
    };
    function topBoolOrEmptySchema(it) {
      const { gen, schema, validateName: validateName2 } = it;
      if (schema === false) {
        falseSchemaError(it, false);
      } else if (typeof schema == "object" && schema.$async === true) {
        gen.return(names_1.default.data);
      } else {
        gen.assign((0, codegen_1._)`${validateName2}.errors`, null);
        gen.return(true);
      }
    }
    __name(topBoolOrEmptySchema, "topBoolOrEmptySchema");
    exports2.topBoolOrEmptySchema = topBoolOrEmptySchema;
    function boolOrEmptySchema(it, valid) {
      const { gen, schema } = it;
      if (schema === false) {
        gen.var(valid, false);
        falseSchemaError(it);
      } else {
        gen.var(valid, true);
      }
    }
    __name(boolOrEmptySchema, "boolOrEmptySchema");
    exports2.boolOrEmptySchema = boolOrEmptySchema;
    function falseSchemaError(it, overrideAllErrors) {
      const { gen, data } = it;
      const cxt = {
        gen,
        keyword: "false schema",
        data,
        schema: false,
        schemaCode: false,
        schemaValue: false,
        params: {},
        it
      };
      (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors);
    }
    __name(falseSchemaError, "falseSchemaError");
  }
});

// packages/core/node_modules/ajv/dist/compile/rules.js
var require_rules = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/rules.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRules = exports2.isJSONType = void 0;
    var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
    var jsonTypes = new Set(_jsonTypes);
    function isJSONType(x) {
      return typeof x == "string" && jsonTypes.has(x);
    }
    __name(isJSONType, "isJSONType");
    exports2.isJSONType = isJSONType;
    function getRules() {
      const groups = {
        number: { type: "number", rules: [] },
        string: { type: "string", rules: [] },
        array: { type: "array", rules: [] },
        object: { type: "object", rules: [] }
      };
      return {
        types: { ...groups, integer: true, boolean: true, null: true },
        rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
        post: { rules: [] },
        all: {},
        keywords: {}
      };
    }
    __name(getRules, "getRules");
    exports2.getRules = getRules;
  }
});

// packages/core/node_modules/ajv/dist/compile/validate/applicability.js
var require_applicability = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/validate/applicability.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.shouldUseRule = exports2.shouldUseGroup = exports2.schemaHasRulesForType = void 0;
    function schemaHasRulesForType({ schema, self: self2 }, type) {
      const group = self2.RULES.types[type];
      return group && group !== true && shouldUseGroup(schema, group);
    }
    __name(schemaHasRulesForType, "schemaHasRulesForType");
    exports2.schemaHasRulesForType = schemaHasRulesForType;
    function shouldUseGroup(schema, group) {
      return group.rules.some((rule) => shouldUseRule(schema, rule));
    }
    __name(shouldUseGroup, "shouldUseGroup");
    exports2.shouldUseGroup = shouldUseGroup;
    function shouldUseRule(schema, rule) {
      var _a6;
      return schema[rule.keyword] !== void 0 || ((_a6 = rule.definition.implements) === null || _a6 === void 0 ? void 0 : _a6.some((kwd) => schema[kwd] !== void 0));
    }
    __name(shouldUseRule, "shouldUseRule");
    exports2.shouldUseRule = shouldUseRule;
  }
});

// packages/core/node_modules/ajv/dist/compile/validate/dataType.js
var require_dataType = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/validate/dataType.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.reportTypeError = exports2.checkDataTypes = exports2.checkDataType = exports2.coerceAndCheckDataType = exports2.getJSONTypes = exports2.getSchemaTypes = exports2.DataType = void 0;
    var rules_1 = require_rules();
    var applicability_1 = require_applicability();
    var errors_1 = require_errors2();
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var DataType;
    (function(DataType2) {
      DataType2[DataType2["Correct"] = 0] = "Correct";
      DataType2[DataType2["Wrong"] = 1] = "Wrong";
    })(DataType || (exports2.DataType = DataType = {}));
    function getSchemaTypes(schema) {
      const types3 = getJSONTypes(schema.type);
      const hasNull = types3.includes("null");
      if (hasNull) {
        if (schema.nullable === false)
          throw new Error("type: null contradicts nullable: false");
      } else {
        if (!types3.length && schema.nullable !== void 0) {
          throw new Error('"nullable" cannot be used without "type"');
        }
        if (schema.nullable === true)
          types3.push("null");
      }
      return types3;
    }
    __name(getSchemaTypes, "getSchemaTypes");
    exports2.getSchemaTypes = getSchemaTypes;
    function getJSONTypes(ts) {
      const types3 = Array.isArray(ts) ? ts : ts ? [ts] : [];
      if (types3.every(rules_1.isJSONType))
        return types3;
      throw new Error("type must be JSONType or JSONType[]: " + types3.join(","));
    }
    __name(getJSONTypes, "getJSONTypes");
    exports2.getJSONTypes = getJSONTypes;
    function coerceAndCheckDataType(it, types3) {
      const { gen, data, opts } = it;
      const coerceTo = coerceToTypes(types3, opts.coerceTypes);
      const checkTypes = types3.length > 0 && !(coerceTo.length === 0 && types3.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types3[0]));
      if (checkTypes) {
        const wrongType = checkDataTypes(types3, data, opts.strictNumbers, DataType.Wrong);
        gen.if(wrongType, () => {
          if (coerceTo.length)
            coerceData(it, types3, coerceTo);
          else
            reportTypeError(it);
        });
      }
      return checkTypes;
    }
    __name(coerceAndCheckDataType, "coerceAndCheckDataType");
    exports2.coerceAndCheckDataType = coerceAndCheckDataType;
    var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]);
    function coerceToTypes(types3, coerceTypes) {
      return coerceTypes ? types3.filter((t2) => COERCIBLE.has(t2) || coerceTypes === "array" && t2 === "array") : [];
    }
    __name(coerceToTypes, "coerceToTypes");
    function coerceData(it, types3, coerceTo) {
      const { gen, data, opts } = it;
      const dataType = 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._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types3, data, opts.strictNumbers), () => gen.assign(coerced, data)));
      }
      gen.if((0, codegen_1._)`${coerced} !== undefined`);
      for (const t2 of coerceTo) {
        if (COERCIBLE.has(t2) || t2 === "array" && opts.coerceTypes === "array") {
          coerceSpecificType(t2);
        }
      }
      gen.else();
      reportTypeError(it);
      gen.endIf();
      gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {
        gen.assign(data, coerced);
        assignParentData(it, coerced);
      });
      function coerceSpecificType(t2) {
        switch (t2) {
          case "string":
            gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "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._)`${dataType} == "boolean" || ${data} === null
              || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`);
            return;
          case "integer":
            gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null
              || (${dataType} === "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._)`${dataType} === "string" || ${dataType} === "number"
              || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`);
        }
      }
      __name(coerceSpecificType, "coerceSpecificType");
    }
    __name(coerceData, "coerceData");
    function assignParentData({ gen, parentData, parentDataProperty }, expr) {
      gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr));
    }
    __name(assignParentData, "assignParentData");
    function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
      const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
      let cond;
      switch (dataType) {
        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} ${dataType}`;
      }
      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);
      }
      __name(numCond, "numCond");
    }
    __name(checkDataType, "checkDataType");
    exports2.checkDataType = checkDataType;
    function checkDataTypes(dataTypes, data, strictNums, correct) {
      if (dataTypes.length === 1) {
        return checkDataType(dataTypes[0], data, strictNums, correct);
      }
      let cond;
      const types3 = (0, util_1.toHash)(dataTypes);
      if (types3.array && types3.object) {
        const notObj = (0, codegen_1._)`typeof ${data} != "object"`;
        cond = types3.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`;
        delete types3.null;
        delete types3.array;
        delete types3.object;
      } else {
        cond = codegen_1.nil;
      }
      if (types3.number)
        delete types3.integer;
      for (const t2 in types3)
        cond = (0, codegen_1.and)(cond, checkDataType(t2, data, strictNums, correct));
      return cond;
    }
    __name(checkDataTypes, "checkDataTypes");
    exports2.checkDataTypes = checkDataTypes;
    var typeError = {
      message: /* @__PURE__ */ __name(({ schema }) => `must be ${schema}`, "message"),
      params: /* @__PURE__ */ __name(({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}`, "params")
    };
    function reportTypeError(it) {
      const cxt = getTypeErrorContext(it);
      (0, errors_1.reportError)(cxt, typeError);
    }
    __name(reportTypeError, "reportTypeError");
    exports2.reportTypeError = reportTypeError;
    function getTypeErrorContext(it) {
      const { gen, data, schema } = it;
      const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
      return {
        gen,
        keyword: "type",
        data,
        schema: schema.type,
        schemaCode,
        schemaValue: schemaCode,
        parentSchema: schema,
        params: {},
        it
      };
    }
    __name(getTypeErrorContext, "getTypeErrorContext");
  }
});

// packages/core/node_modules/ajv/dist/compile/validate/defaults.js
var require_defaults = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/validate/defaults.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.assignDefaults = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    function assignDefaults(it, ty) {
      const { properties, items } = it.schema;
      if (ty === "object" && properties) {
        for (const key in properties) {
          assignDefault(it, key, properties[key].default);
        }
      } else if (ty === "array" && Array.isArray(items)) {
        items.forEach((sch, i) => assignDefault(it, i, sch.default));
      }
    }
    __name(assignDefaults, "assignDefaults");
    exports2.assignDefaults = assignDefaults;
    function assignDefault(it, prop, defaultValue) {
      const { gen, compositeRule, data, opts } = it;
      if (defaultValue === void 0)
        return;
      const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`;
      if (compositeRule) {
        (0, util_1.checkStrictMode)(it, `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)}`);
    }
    __name(assignDefault, "assignDefault");
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/code.js
var require_code2 = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/code.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateUnion = exports2.validateArray = exports2.usePattern = exports2.callValidateCode = exports2.schemaProperties = exports2.allSchemaProperties = exports2.noPropertyInData = exports2.propertyInData = exports2.isOwnProperty = exports2.hasPropFunc = exports2.reportMissingProp = exports2.checkMissingProp = exports2.checkReportMissingProp = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var names_1 = require_names();
    var util_2 = require_util9();
    function checkReportMissingProp(cxt, prop) {
      const { gen, data, it } = cxt;
      gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
        cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true);
        cxt.error();
      });
    }
    __name(checkReportMissingProp, "checkReportMissingProp");
    exports2.checkReportMissingProp = checkReportMissingProp;
    function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
      return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`)));
    }
    __name(checkMissingProp, "checkMissingProp");
    exports2.checkMissingProp = checkMissingProp;
    function reportMissingProp(cxt, missing) {
      cxt.setParams({ missingProperty: missing }, true);
      cxt.error();
    }
    __name(reportMissingProp, "reportMissingProp");
    exports2.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`
      });
    }
    __name(hasPropFunc, "hasPropFunc");
    exports2.hasPropFunc = hasPropFunc;
    function isOwnProperty(gen, data, property) {
      return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`;
    }
    __name(isOwnProperty, "isOwnProperty");
    exports2.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;
    }
    __name(propertyInData, "propertyInData");
    exports2.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;
    }
    __name(noPropertyInData, "noPropertyInData");
    exports2.noPropertyInData = noPropertyInData;
    function allSchemaProperties(schemaMap) {
      return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
    }
    __name(allSchemaProperties, "allSchemaProperties");
    exports2.allSchemaProperties = allSchemaProperties;
    function schemaProperties(it, schemaMap) {
      return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
    }
    __name(schemaProperties, "schemaProperties");
    exports2.schemaProperties = schemaProperties;
    function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context2, 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, it.parentData],
        [names_1.default.parentDataProperty, it.parentDataProperty],
        [names_1.default.rootData, names_1.default.rootData]
      ];
      if (it.opts.dynamicRef)
        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
      const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
      return context2 !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context2}, ${args})` : (0, codegen_1._)`${func}(${args})`;
    }
    __name(callValidateCode, "callValidateCode");
    exports2.callValidateCode = callValidateCode;
    var newRegExp = (0, codegen_1._)`new RegExp`;
    function usePattern({ gen, it: { opts } }, pattern) {
      const u = opts.unicodeRegExp ? "u" : "";
      const { regExp } = opts.code;
      const rx = regExp(pattern, 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)}(${pattern}, ${u})`
      });
    }
    __name(usePattern, "usePattern");
    exports2.usePattern = usePattern;
    function validateArray(cxt) {
      const { gen, data, keyword, it } = cxt;
      const valid = gen.name("valid");
      if (it.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 len = gen.const("len", (0, codegen_1._)`${data}.length`);
        gen.forRange("i", 0, len, (i) => {
          cxt.subschema({
            keyword,
            dataProp: i,
            dataPropType: util_1.Type.Num
          }, valid);
          gen.if((0, codegen_1.not)(valid), notValid);
        });
      }
      __name(validateItems, "validateItems");
    }
    __name(validateArray, "validateArray");
    exports2.validateArray = validateArray;
    function validateUnion(cxt) {
      const { gen, schema, keyword, it } = cxt;
      if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
      const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));
      if (alwaysValid && !it.opts.unevaluated)
        return;
      const valid = gen.let("valid", false);
      const schValid = gen.name("_valid");
      gen.block(() => schema.forEach((_sch, i) => {
        const schCxt = cxt.subschema({
          keyword,
          schemaProp: i,
          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));
    }
    __name(validateUnion, "validateUnion");
    exports2.validateUnion = validateUnion;
  }
});

// packages/core/node_modules/ajv/dist/compile/validate/keyword.js
var require_keyword = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/validate/keyword.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateKeywordUsage = exports2.validSchemaType = exports2.funcKeywordCode = exports2.macroKeywordCode = void 0;
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var code_1 = require_code2();
    var errors_1 = require_errors2();
    function macroKeywordCode(cxt, def2) {
      const { gen, keyword, schema, parentSchema, it } = cxt;
      const macroSchema = def2.macro.call(it.self, schema, parentSchema, it);
      const schemaRef = useKeyword(gen, keyword, macroSchema);
      if (it.opts.validateSchema !== false)
        it.self.validateSchema(macroSchema, true);
      const valid = gen.name("valid");
      cxt.subschema({
        schema: macroSchema,
        schemaPath: codegen_1.nil,
        errSchemaPath: `${it.errSchemaPath}/${keyword}`,
        topSchemaRef: schemaRef,
        compositeRule: true
      }, valid);
      cxt.pass(valid, () => cxt.error(true));
    }
    __name(macroKeywordCode, "macroKeywordCode");
    exports2.macroKeywordCode = macroKeywordCode;
    function funcKeywordCode(cxt, def2) {
      var _a6;
      const { gen, keyword, schema, parentSchema, $data, it } = cxt;
      checkAsyncKeyword(it, def2);
      const validate4 = !$data && def2.compile ? def2.compile.call(it.self, schema, parentSchema, it) : def2.validate;
      const validateRef = useKeyword(gen, keyword, validate4);
      const valid = gen.let("valid");
      cxt.block$data(valid, validateKeyword);
      cxt.ok((_a6 = def2.valid) !== null && _a6 !== void 0 ? _a6 : valid);
      function validateKeyword() {
        if (def2.errors === false) {
          assignValid();
          if (def2.modifying)
            modifyData(cxt);
          reportErrs(() => cxt.error());
        } else {
          const ruleErrs = def2.async ? validateAsync() : validateSync();
          if (def2.modifying)
            modifyData(cxt);
          reportErrs(() => addErrs(cxt, ruleErrs));
        }
      }
      __name(validateKeyword, "validateKeyword");
      function validateAsync() {
        const ruleErrs = gen.let("ruleErrs", null);
        gen.try(() => assignValid((0, codegen_1._)`await `), (e2) => gen.assign(valid, false).if((0, codegen_1._)`${e2} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e2}.errors`), () => gen.throw(e2)));
        return ruleErrs;
      }
      __name(validateAsync, "validateAsync");
      function validateSync() {
        const validateErrs = (0, codegen_1._)`${validateRef}.errors`;
        gen.assign(validateErrs, null);
        assignValid(codegen_1.nil);
        return validateErrs;
      }
      __name(validateSync, "validateSync");
      function assignValid(_await = def2.async ? (0, codegen_1._)`await ` : codegen_1.nil) {
        const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
        const passSchema = !("compile" in def2 && !$data || def2.schema === false);
        gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def2.modifying);
      }
      __name(assignValid, "assignValid");
      function reportErrs(errors) {
        var _a7;
        gen.if((0, codegen_1.not)((_a7 = def2.valid) !== null && _a7 !== void 0 ? _a7 : valid), errors);
      }
      __name(reportErrs, "reportErrs");
    }
    __name(funcKeywordCode, "funcKeywordCode");
    exports2.funcKeywordCode = funcKeywordCode;
    function modifyData(cxt) {
      const { gen, data, it } = cxt;
      gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`));
    }
    __name(modifyData, "modifyData");
    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());
    }
    __name(addErrs, "addErrs");
    function checkAsyncKeyword({ schemaEnv }, def2) {
      if (def2.async && !schemaEnv.$async)
        throw new Error("async keyword in sync schema");
    }
    __name(checkAsyncKeyword, "checkAsyncKeyword");
    function useKeyword(gen, keyword, result) {
      if (result === void 0)
        throw new Error(`keyword "${keyword}" failed to compile`);
      return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
    }
    __name(useKeyword, "useKeyword");
    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");
    }
    __name(validSchemaType, "validSchemaType");
    exports2.validSchemaType = validSchemaType;
    function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def2, keyword) {
      if (Array.isArray(def2.keyword) ? !def2.keyword.includes(keyword) : def2.keyword !== keyword) {
        throw new Error("ajv implementation error");
      }
      const deps = def2.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 ${keyword}: ${deps.join(",")}`);
      }
      if (def2.validateSchema) {
        const valid = def2.validateSchema(schema[keyword]);
        if (!valid) {
          const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def2.validateSchema.errors);
          if (opts.validateSchema === "log")
            self2.logger.error(msg);
          else
            throw new Error(msg);
        }
      }
    }
    __name(validateKeywordUsage, "validateKeywordUsage");
    exports2.validateKeywordUsage = validateKeywordUsage;
  }
});

// packages/core/node_modules/ajv/dist/compile/validate/subschema.js
var require_subschema = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/validate/subschema.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.extendSubschemaMode = exports2.extendSubschemaData = exports2.getSubschema = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
      if (keyword !== void 0 && schema !== void 0) {
        throw new Error('both "keyword" and "schema" passed, only one allowed');
      }
      if (keyword !== void 0) {
        const sch = it.schema[keyword];
        return schemaProp === void 0 ? {
          schema: sch,
          schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
          errSchemaPath: `${it.errSchemaPath}/${keyword}`
        } : {
          schema: sch[schemaProp],
          schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
          errSchemaPath: `${it.errSchemaPath}/${keyword}/${(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');
    }
    __name(getSubschema, "getSubschema");
    exports2.getSubschema = getSubschema;
    function extendSubschemaData(subschema, it, { 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 } = it;
      if (dataProp !== void 0) {
        const { errorPath, dataPathArr, opts } = it;
        const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
        dataContextProps(nextData);
        subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
        subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`;
        subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
      }
      if (data !== void 0) {
        const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true);
        dataContextProps(nextData);
        if (propertyName !== void 0)
          subschema.propertyName = propertyName;
      }
      if (dataTypes)
        subschema.dataTypes = dataTypes;
      function dataContextProps(_nextData) {
        subschema.data = _nextData;
        subschema.dataLevel = it.dataLevel + 1;
        subschema.dataTypes = [];
        it.definedProperties = /* @__PURE__ */ new Set();
        subschema.parentData = it.data;
        subschema.dataNames = [...it.dataNames, _nextData];
      }
      __name(dataContextProps, "dataContextProps");
    }
    __name(extendSubschemaData, "extendSubschemaData");
    exports2.extendSubschemaData = extendSubschemaData;
    function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
      if (compositeRule !== void 0)
        subschema.compositeRule = compositeRule;
      if (createErrors !== void 0)
        subschema.createErrors = createErrors;
      if (allErrors !== void 0)
        subschema.allErrors = allErrors;
      subschema.jtdDiscriminator = jtdDiscriminator;
      subschema.jtdMetadata = jtdMetadata;
    }
    __name(extendSubschemaMode, "extendSubschemaMode");
    exports2.extendSubschemaMode = extendSubschemaMode;
  }
});

// node_modules/fast-deep-equal/index.js
var require_fast_deep_equal = __commonJS({
  "node_modules/fast-deep-equal/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function equal(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, i, keys;
        if (Array.isArray(a)) {
          length = a.length;
          if (length != b.length) return false;
          for (i = length; i-- !== 0; )
            if (!equal(a[i], b[i])) 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 (i = length; i-- !== 0; )
          if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
        for (i = length; i-- !== 0; ) {
          var key = keys[i];
          if (!equal(a[key], b[key])) return false;
        }
        return true;
      }
      return a !== a && b !== b;
    }, "equal");
  }
});

// node_modules/json-schema-traverse/index.js
var require_json_schema_traverse = __commonJS({
  "node_modules/json-schema-traverse/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var traverse = module2.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
    };
    traverse.arrayKeywords = {
      items: true,
      allOf: true,
      anyOf: true,
      oneOf: true
    };
    traverse.propsKeywords = {
      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 i = 0; i < sch.length; i++)
                _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i);
            }
          } 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);
      }
    }
    __name(_traverse, "_traverse");
    function escapeJsonPtr(str2) {
      return str2.replace(/~/g, "~0").replace(/\//g, "~1");
    }
    __name(escapeJsonPtr, "escapeJsonPtr");
  }
});

// packages/core/node_modules/ajv/dist/compile/resolve.js
var require_resolve = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/resolve.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getSchemaRefs = exports2.resolveUrl = exports2.normalizeId = exports2._getFullPath = exports2.getFullPath = exports2.inlineRef = void 0;
    var util_1 = require_util9();
    var equal = require_fast_deep_equal();
    var traverse = require_json_schema_traverse();
    var 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;
    }
    __name(inlineRef, "inlineRef");
    exports2.inlineRef = inlineRef;
    var 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;
    }
    __name(hasRef, "hasRef");
    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;
    }
    __name(countKeys, "countKeys");
    function getFullPath(resolver, id = "", normalize10) {
      if (normalize10 !== false)
        id = normalizeId(id);
      const p = resolver.parse(id);
      return _getFullPath(resolver, p);
    }
    __name(getFullPath, "getFullPath");
    exports2.getFullPath = getFullPath;
    function _getFullPath(resolver, p) {
      const serialized = resolver.serialize(p);
      return serialized.split("#")[0] + "#";
    }
    __name(_getFullPath, "_getFullPath");
    exports2._getFullPath = _getFullPath;
    var TRAILING_SLASH_HASH = /#\/?$/;
    function normalizeId(id) {
      return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
    }
    __name(normalizeId, "normalizeId");
    exports2.normalizeId = normalizeId;
    function resolveUrl(resolver, baseId, id) {
      id = normalizeId(id);
      return resolver.resolve(baseId, id);
    }
    __name(resolveUrl, "resolveUrl");
    exports2.resolveUrl = resolveUrl;
    var 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(ref) {
          const _resolve = this.opts.uriResolver.resolve;
          ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
          if (schemaRefs.has(ref))
            throw ambiguos(ref);
          schemaRefs.add(ref);
          let schOrRef = this.refs[ref];
          if (typeof schOrRef == "string")
            schOrRef = this.refs[schOrRef];
          if (typeof schOrRef == "object") {
            checkAmbiguosRef(sch, schOrRef.schema, ref);
          } else if (ref !== normalizeId(fullPath)) {
            if (ref[0] === "#") {
              checkAmbiguosRef(sch, localRefs[ref], ref);
              localRefs[ref] = sch;
            } else {
              this.refs[ref] = fullPath;
            }
          }
          return ref;
        }
        __name(addRef, "addRef");
        function addAnchor(anchor) {
          if (typeof anchor == "string") {
            if (!ANCHOR.test(anchor))
              throw new Error(`invalid anchor "${anchor}"`);
            addRef.call(this, `#${anchor}`);
          }
        }
        __name(addAnchor, "addAnchor");
      });
      return localRefs;
      function checkAmbiguosRef(sch1, sch2, ref) {
        if (sch2 !== void 0 && !equal(sch1, sch2))
          throw ambiguos(ref);
      }
      __name(checkAmbiguosRef, "checkAmbiguosRef");
      function ambiguos(ref) {
        return new Error(`reference "${ref}" resolves to more than one schema`);
      }
      __name(ambiguos, "ambiguos");
    }
    __name(getSchemaRefs, "getSchemaRefs");
    exports2.getSchemaRefs = getSchemaRefs;
  }
});

// packages/core/node_modules/ajv/dist/compile/validate/index.js
var require_validate = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/validate/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getData = exports2.KeywordCxt = exports2.validateFunctionCode = void 0;
    var boolSchema_1 = require_boolSchema();
    var dataType_1 = require_dataType();
    var applicability_1 = require_applicability();
    var dataType_2 = require_dataType();
    var defaults_1 = require_defaults();
    var keyword_1 = require_keyword();
    var subschema_1 = require_subschema();
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var resolve_1 = require_resolve();
    var util_1 = require_util9();
    var errors_1 = require_errors2();
    function validateFunctionCode(it) {
      if (isSchemaObj(it)) {
        checkKeywords(it);
        if (schemaCxtHasRules(it)) {
          topSchemaObjCode(it);
          return;
        }
      }
      validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
    }
    __name(validateFunctionCode, "validateFunctionCode");
    exports2.validateFunctionCode = validateFunctionCode;
    function validateFunction({ gen, validateName: validateName2, schema, schemaEnv, opts }, body) {
      if (opts.code.es5) {
        gen.func(validateName2, (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(validateName2, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
      }
    }
    __name(validateFunction, "validateFunction");
    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}}={}`;
    }
    __name(destructureValCxt, "destructureValCxt");
    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._)`{}`);
      });
    }
    __name(destructureValCxtES5, "destructureValCxtES5");
    function topSchemaObjCode(it) {
      const { schema, opts, gen } = it;
      validateFunction(it, () => {
        if (opts.$comment && schema.$comment)
          commentKeyword(it);
        checkNoDefault(it);
        gen.let(names_1.default.vErrors, null);
        gen.let(names_1.default.errors, 0);
        if (opts.unevaluated)
          resetEvaluated(it);
        typeAndKeywords(it);
        returnResults(it);
      });
      return;
    }
    __name(topSchemaObjCode, "topSchemaObjCode");
    function resetEvaluated(it) {
      const { gen, validateName: validateName2 } = it;
      it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName2}.evaluated`);
      gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`));
      gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`));
    }
    __name(resetEvaluated, "resetEvaluated");
    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;
    }
    __name(funcSourceUrl, "funcSourceUrl");
    function subschemaCode(it, valid) {
      if (isSchemaObj(it)) {
        checkKeywords(it);
        if (schemaCxtHasRules(it)) {
          subSchemaObjCode(it, valid);
          return;
        }
      }
      (0, boolSchema_1.boolOrEmptySchema)(it, valid);
    }
    __name(subschemaCode, "subschemaCode");
    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;
    }
    __name(schemaCxtHasRules, "schemaCxtHasRules");
    function isSchemaObj(it) {
      return typeof it.schema != "boolean";
    }
    __name(isSchemaObj, "isSchemaObj");
    function subSchemaObjCode(it, valid) {
      const { schema, gen, opts } = it;
      if (opts.$comment && schema.$comment)
        commentKeyword(it);
      updateContext(it);
      checkAsyncSchema(it);
      const errsCount = gen.const("_errs", names_1.default.errors);
      typeAndKeywords(it, errsCount);
      gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
    }
    __name(subSchemaObjCode, "subSchemaObjCode");
    function checkKeywords(it) {
      (0, util_1.checkUnknownRules)(it);
      checkRefsAndKeywords(it);
    }
    __name(checkKeywords, "checkKeywords");
    function typeAndKeywords(it, errsCount) {
      if (it.opts.jtd)
        return schemaKeywords(it, [], false, errsCount);
      const types3 = (0, dataType_1.getSchemaTypes)(it.schema);
      const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types3);
      schemaKeywords(it, types3, !checkedTypes, errsCount);
    }
    __name(typeAndKeywords, "typeAndKeywords");
    function checkRefsAndKeywords(it) {
      const { schema, errSchemaPath, opts, self: self2 } = it;
      if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) {
        self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
      }
    }
    __name(checkRefsAndKeywords, "checkRefsAndKeywords");
    function checkNoDefault(it) {
      const { schema, opts } = it;
      if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {
        (0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
      }
    }
    __name(checkNoDefault, "checkNoDefault");
    function updateContext(it) {
      const schId = it.schema[it.opts.schemaId];
      if (schId)
        it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
    }
    __name(updateContext, "updateContext");
    function checkAsyncSchema(it) {
      if (it.schema.$async && !it.schemaEnv.$async)
        throw new Error("async schema in sync schema");
    }
    __name(checkAsyncSchema, "checkAsyncSchema");
    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)`);
      }
    }
    __name(commentKeyword, "commentKeyword");
    function returnResults(it) {
      const { gen, schemaEnv, validateName: validateName2, ValidationError, opts } = it;
      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._)`${validateName2}.errors`, names_1.default.vErrors);
        if (opts.unevaluated)
          assignEvaluated(it);
        gen.return((0, codegen_1._)`${names_1.default.errors} === 0`);
      }
    }
    __name(returnResults, "returnResults");
    function assignEvaluated({ gen, evaluated, props, items }) {
      if (props instanceof codegen_1.Name)
        gen.assign((0, codegen_1._)`${evaluated}.props`, props);
      if (items instanceof codegen_1.Name)
        gen.assign((0, codegen_1._)`${evaluated}.items`, items);
    }
    __name(assignEvaluated, "assignEvaluated");
    function schemaKeywords(it, types3, typeErrors, errsCount) {
      const { gen, schema, data, allErrors, opts, self: self2 } = it;
      const { RULES } = self2;
      if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
        gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition));
        return;
      }
      if (!opts.jtd)
        checkStrictTypes(it, types3);
      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(it, group);
          if (types3.length === 1 && types3[0] === group.type && typeErrors) {
            gen.else();
            (0, dataType_2.reportTypeError)(it);
          }
          gen.endIf();
        } else {
          iterateKeywords(it, group);
        }
        if (!allErrors)
          gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);
      }
      __name(groupKeywords, "groupKeywords");
    }
    __name(schemaKeywords, "schemaKeywords");
    function iterateKeywords(it, group) {
      const { gen, schema, opts: { useDefaults } } = it;
      if (useDefaults)
        (0, defaults_1.assignDefaults)(it, group.type);
      gen.block(() => {
        for (const rule of group.rules) {
          if ((0, applicability_1.shouldUseRule)(schema, rule)) {
            keywordCode(it, rule.keyword, rule.definition, group.type);
          }
        }
      });
    }
    __name(iterateKeywords, "iterateKeywords");
    function checkStrictTypes(it, types3) {
      if (it.schemaEnv.meta || !it.opts.strictTypes)
        return;
      checkContextTypes(it, types3);
      if (!it.opts.allowUnionTypes)
        checkMultipleTypes(it, types3);
      checkKeywordTypes(it, it.dataTypes);
    }
    __name(checkStrictTypes, "checkStrictTypes");
    function checkContextTypes(it, types3) {
      if (!types3.length)
        return;
      if (!it.dataTypes.length) {
        it.dataTypes = types3;
        return;
      }
      types3.forEach((t2) => {
        if (!includesType(it.dataTypes, t2)) {
          strictTypesError(it, `type "${t2}" not allowed by context "${it.dataTypes.join(",")}"`);
        }
      });
      narrowSchemaTypes(it, types3);
    }
    __name(checkContextTypes, "checkContextTypes");
    function checkMultipleTypes(it, ts) {
      if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
        strictTypesError(it, "use allowUnionTypes to allow union type keyword");
      }
    }
    __name(checkMultipleTypes, "checkMultipleTypes");
    function checkKeywordTypes(it, ts) {
      const rules = it.self.RULES.all;
      for (const keyword in rules) {
        const rule = rules[keyword];
        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
          const { type } = rule.definition;
          if (type.length && !type.some((t2) => hasApplicableType(ts, t2))) {
            strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
          }
        }
      }
    }
    __name(checkKeywordTypes, "checkKeywordTypes");
    function hasApplicableType(schTs, kwdT) {
      return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer");
    }
    __name(hasApplicableType, "hasApplicableType");
    function includesType(ts, t2) {
      return ts.includes(t2) || t2 === "integer" && ts.includes("number");
    }
    __name(includesType, "includesType");
    function narrowSchemaTypes(it, withTypes) {
      const ts = [];
      for (const t2 of it.dataTypes) {
        if (includesType(withTypes, t2))
          ts.push(t2);
        else if (withTypes.includes("integer") && t2 === "number")
          ts.push("integer");
      }
      it.dataTypes = ts;
    }
    __name(narrowSchemaTypes, "narrowSchemaTypes");
    function strictTypesError(it, msg) {
      const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
      msg += ` at "${schemaPath}" (strictTypes)`;
      (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
    }
    __name(strictTypesError, "strictTypesError");
    var KeywordCxt = class {
      static {
        __name(this, "KeywordCxt");
      }
      constructor(it, def2, keyword) {
        (0, keyword_1.validateKeywordUsage)(it, def2, keyword);
        this.gen = it.gen;
        this.allErrors = it.allErrors;
        this.keyword = keyword;
        this.data = it.data;
        this.schema = it.schema[keyword];
        this.$data = def2.$data && it.opts.$data && this.schema && this.schema.$data;
        this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
        this.schemaType = def2.schemaType;
        this.parentSchema = it.schema;
        this.params = {};
        this.it = it;
        this.def = def2;
        if (this.$data) {
          this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
        } else {
          this.schemaCode = this.schemaValue;
          if (!(0, keyword_1.validSchemaType)(this.schema, def2.schemaType, def2.allowUndefined)) {
            throw new Error(`${keyword} value must be ${JSON.stringify(def2.schemaType)}`);
          }
        }
        if ("code" in def2 ? def2.trackErrors : def2.errors !== false) {
          this.errsCount = it.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(append2, errorParams, errorPaths) {
        if (errorParams) {
          this.setParams(errorParams);
          this._error(append2, errorPaths);
          this.setParams({});
          return;
        }
        this._error(append2, errorPaths);
      }
      _error(append2, errorPaths) {
        ;
        (append2 ? 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: def2 } = 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 || def2.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: def2, it } = 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, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
          }
          return codegen_1.nil;
        }
        __name(wrong$DataType, "wrong$DataType");
        function invalid$DataSchema() {
          if (def2.validateSchema) {
            const validateSchemaRef = gen.scopeValue("validate$data", { ref: def2.validateSchema });
            return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`;
          }
          return codegen_1.nil;
        }
        __name(invalid$DataSchema, "invalid$DataSchema");
      }
      subschema(appl, valid) {
        const subschema = (0, subschema_1.getSubschema)(this.it, appl);
        (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
        (0, subschema_1.extendSubschemaMode)(subschema, appl);
        const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 };
        subschemaCode(nextContext, valid);
        return nextContext;
      }
      mergeEvaluated(schemaCxt, toName) {
        const { it, gen } = this;
        if (!it.opts.unevaluated)
          return;
        if (it.props !== true && schemaCxt.props !== void 0) {
          it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
        }
        if (it.items !== true && schemaCxt.items !== void 0) {
          it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
        }
      }
      mergeValidEvaluated(schemaCxt, valid) {
        const { it, gen } = this;
        if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
          gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
          return true;
        }
      }
    };
    exports2.KeywordCxt = KeywordCxt;
    function keywordCode(it, keyword, def2, ruleType) {
      const cxt = new KeywordCxt(it, def2, keyword);
      if ("code" in def2) {
        def2.code(cxt, ruleType);
      } else if (cxt.$data && def2.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def2);
      } else if ("macro" in def2) {
        (0, keyword_1.macroKeywordCode)(cxt, def2);
      } else if (def2.compile || def2.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def2);
      }
    }
    __name(keywordCode, "keywordCode");
    var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
    var 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}`;
      }
      __name(errorMsg, "errorMsg");
    }
    __name(getData, "getData");
    exports2.getData = getData;
  }
});

// packages/core/node_modules/ajv/dist/runtime/validation_error.js
var require_validation_error = __commonJS({
  "packages/core/node_modules/ajv/dist/runtime/validation_error.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var ValidationError = class extends Error {
      static {
        __name(this, "ValidationError");
      }
      constructor(errors) {
        super("validation failed");
        this.errors = errors;
        this.ajv = this.validation = true;
      }
    };
    exports2.default = ValidationError;
  }
});

// packages/core/node_modules/ajv/dist/compile/ref_error.js
var require_ref_error = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/ref_error.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var resolve_1 = require_resolve();
    var MissingRefError = class extends Error {
      static {
        __name(this, "MissingRefError");
      }
      constructor(resolver, baseId, ref, msg) {
        super(msg || `can't resolve reference ${ref} from id ${baseId}`);
        this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);
        this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
      }
    };
    exports2.default = MissingRefError;
  }
});

// packages/core/node_modules/ajv/dist/compile/index.js
var require_compile = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.resolveSchema = exports2.getCompilingSchema = exports2.resolveRef = exports2.compileSchema = exports2.SchemaEnv = void 0;
    var codegen_1 = require_codegen();
    var validation_error_1 = require_validation_error();
    var names_1 = require_names();
    var resolve_1 = require_resolve();
    var util_1 = require_util9();
    var validate_1 = require_validate();
    var SchemaEnv = class {
      static {
        __name(this, "SchemaEnv");
      }
      constructor(env7) {
        var _a6;
        this.refs = {};
        this.dynamicAnchors = {};
        let schema;
        if (typeof env7.schema == "object")
          schema = env7.schema;
        this.schema = env7.schema;
        this.schemaId = env7.schemaId;
        this.root = env7.root || this;
        this.baseId = (_a6 = env7.baseId) !== null && _a6 !== void 0 ? _a6 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env7.schemaId || "$id"]);
        this.schemaPath = env7.schemaPath;
        this.localRefs = env7.localRefs;
        this.meta = env7.meta;
        this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
        this.refs = {};
      }
    };
    exports2.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 validateName2 = gen.scopeName("validate");
      sch.validateName = validateName2;
      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: validateName2,
        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 validate4 = makeValidate(this, this.scope.get());
        this.scope.value(validateName2, { ref: validate4 });
        validate4.errors = null;
        validate4.schema = sch.schema;
        validate4.schemaEnv = sch;
        if (sch.$async)
          validate4.$async = true;
        if (this.opts.code.source === true) {
          validate4.source = { validateName: validateName2, validateCode, scopeValues: gen._values };
        }
        if (this.opts.unevaluated) {
          const { props, items } = schemaCxt;
          validate4.evaluated = {
            props: props instanceof codegen_1.Name ? void 0 : props,
            items: items instanceof codegen_1.Name ? void 0 : items,
            dynamicProps: props instanceof codegen_1.Name,
            dynamicItems: items instanceof codegen_1.Name
          };
          if (validate4.source)
            validate4.source.evaluated = (0, codegen_1.stringify)(validate4.evaluated);
        }
        sch.validate = validate4;
        return sch;
      } catch (e2) {
        delete sch.validate;
        delete sch.validateName;
        if (sourceCode)
          this.logger.error("Error compiling schema, function code:", sourceCode);
        throw e2;
      } finally {
        this._compilations.delete(sch);
      }
    }
    __name(compileSchema, "compileSchema");
    exports2.compileSchema = compileSchema;
    function resolveRef(root, baseId, ref) {
      var _a6;
      ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
      const schOrFunc = root.refs[ref];
      if (schOrFunc)
        return schOrFunc;
      let _sch = resolve24.call(this, root, ref);
      if (_sch === void 0) {
        const schema = (_a6 = root.localRefs) === null || _a6 === void 0 ? void 0 : _a6[ref];
        const { schemaId } = this.opts;
        if (schema)
          _sch = new SchemaEnv({ schema, schemaId, root, baseId });
      }
      if (_sch === void 0)
        return;
      return root.refs[ref] = inlineOrCompile.call(this, _sch);
    }
    __name(resolveRef, "resolveRef");
    exports2.resolveRef = resolveRef;
    function inlineOrCompile(sch) {
      if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
        return sch.schema;
      return sch.validate ? sch : compileSchema.call(this, sch);
    }
    __name(inlineOrCompile, "inlineOrCompile");
    function getCompilingSchema(schEnv) {
      for (const sch of this._compilations) {
        if (sameSchemaEnv(sch, schEnv))
          return sch;
      }
    }
    __name(getCompilingSchema, "getCompilingSchema");
    exports2.getCompilingSchema = getCompilingSchema;
    function sameSchemaEnv(s1, s2) {
      return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
    }
    __name(sameSchemaEnv, "sameSchemaEnv");
    function resolve24(root, ref) {
      let sch;
      while (typeof (sch = this.refs[ref]) == "string")
        ref = sch;
      return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
    }
    __name(resolve24, "resolve");
    function resolveSchema(root, ref) {
      const p = this.opts.uriResolver.parse(ref);
      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 id = (0, resolve_1.normalizeId)(refPath);
      const schOrRef = this.refs[id] || this.schemas[id];
      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 (id === (0, resolve_1.normalizeId)(ref)) {
        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);
    }
    __name(resolveSchema, "resolveSchema");
    exports2.resolveSchema = resolveSchema;
    var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([
      "properties",
      "patternProperties",
      "enum",
      "dependencies",
      "definitions"
    ]);
    function getJsonPointer(parsedRef, { baseId, schema, root }) {
      var _a6;
      if (((_a6 = parsedRef.fragment) === null || _a6 === void 0 ? void 0 : _a6[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 env7;
      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);
        env7 = resolveSchema.call(this, root, $ref);
      }
      const { schemaId } = this.opts;
      env7 = env7 || new SchemaEnv({ schema, schemaId, root, baseId });
      if (env7.schema !== env7.root.schema)
        return env7;
      return void 0;
    }
    __name(getJsonPointer, "getJsonPointer");
  }
});

// packages/core/node_modules/ajv/dist/refs/data.json
var require_data = __commonJS({
  "packages/core/node_modules/ajv/dist/refs/data.json"(exports2, module2) {
    module2.exports = {
      $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
      description: "Meta-schema for $data reference (JSON AnySchema extension proposal)",
      type: "object",
      required: ["$data"],
      properties: {
        $data: {
          type: "string",
          anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }]
        }
      },
      additionalProperties: false
    };
  }
});

// node_modules/fast-uri/lib/scopedChars.js
var require_scopedChars = __commonJS({
  "node_modules/fast-uri/lib/scopedChars.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var HEX = {
      0: 0,
      1: 1,
      2: 2,
      3: 3,
      4: 4,
      5: 5,
      6: 6,
      7: 7,
      8: 8,
      9: 9,
      a: 10,
      A: 10,
      b: 11,
      B: 11,
      c: 12,
      C: 12,
      d: 13,
      D: 13,
      e: 14,
      E: 14,
      f: 15,
      F: 15
    };
    module2.exports = {
      HEX
    };
  }
});

// node_modules/fast-uri/lib/utils.js
var require_utils3 = __commonJS({
  "node_modules/fast-uri/lib/utils.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { HEX } = require_scopedChars();
    var IPV4_REG = /^(?:(?: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 normalizeIPv4(host) {
      if (findToken(host, ".") < 3) {
        return { host, isIPV4: false };
      }
      const matches = host.match(IPV4_REG) || [];
      const [address] = matches;
      if (address) {
        return { host: stripLeadingZeros(address, "."), isIPV4: true };
      } else {
        return { host, isIPV4: false };
      }
    }
    __name(normalizeIPv4, "normalizeIPv4");
    function stringArrayToHexStripped(input, keepZero = false) {
      let acc = "";
      let strip = true;
      for (const c3 of input) {
        if (HEX[c3] === void 0) return void 0;
        if (c3 !== "0" && strip === true) strip = false;
        if (!strip) acc += c3;
      }
      if (keepZero && acc.length === 0) acc = "0";
      return acc;
    }
    __name(stringArrayToHexStripped, "stringArrayToHexStripped");
    function getIPV6(input) {
      let tokenCount = 0;
      const output = { error: false, address: "", zone: "" };
      const address = [];
      const buffer = [];
      let isZone = false;
      let endipv6Encountered = false;
      let endIpv6 = false;
      function consume() {
        if (buffer.length) {
          if (isZone === false) {
            const hex = stringArrayToHexStripped(buffer);
            if (hex !== void 0) {
              address.push(hex);
            } else {
              output.error = true;
              return false;
            }
          }
          buffer.length = 0;
        }
        return true;
      }
      __name(consume, "consume");
      for (let i = 0; i < input.length; i++) {
        const cursor = input[i];
        if (cursor === "[" || cursor === "]") {
          continue;
        }
        if (cursor === ":") {
          if (endipv6Encountered === true) {
            endIpv6 = true;
          }
          if (!consume()) {
            break;
          }
          tokenCount++;
          address.push(":");
          if (tokenCount > 7) {
            output.error = true;
            break;
          }
          if (i - 1 >= 0 && input[i - 1] === ":") {
            endipv6Encountered = true;
          }
          continue;
        } else if (cursor === "%") {
          if (!consume()) {
            break;
          }
          isZone = true;
        } else {
          buffer.push(cursor);
          continue;
        }
      }
      if (buffer.length) {
        if (isZone) {
          output.zone = buffer.join("");
        } else if (endIpv6) {
          address.push(buffer.join(""));
        } else {
          address.push(stringArrayToHexStripped(buffer));
        }
      }
      output.address = address.join("");
      return output;
    }
    __name(getIPV6, "getIPV6");
    function normalizeIPv6(host) {
      if (findToken(host, ":") < 2) {
        return { host, isIPV6: false };
      }
      const ipv6 = getIPV6(host);
      if (!ipv6.error) {
        let newHost = ipv6.address;
        let escapedHost = ipv6.address;
        if (ipv6.zone) {
          newHost += "%" + ipv6.zone;
          escapedHost += "%25" + ipv6.zone;
        }
        return { host: newHost, escapedHost, isIPV6: true };
      } else {
        return { host, isIPV6: false };
      }
    }
    __name(normalizeIPv6, "normalizeIPv6");
    function stripLeadingZeros(str2, token2) {
      let out = "";
      let skip = true;
      const l2 = str2.length;
      for (let i = 0; i < l2; i++) {
        const c3 = str2[i];
        if (c3 === "0" && skip) {
          if (i + 1 <= l2 && str2[i + 1] === token2 || i + 1 === l2) {
            out += c3;
            skip = false;
          }
        } else {
          if (c3 === token2) {
            skip = true;
          } else {
            skip = false;
          }
          out += c3;
        }
      }
      return out;
    }
    __name(stripLeadingZeros, "stripLeadingZeros");
    function findToken(str2, token2) {
      let ind = 0;
      for (let i = 0; i < str2.length; i++) {
        if (str2[i] === token2) ind++;
      }
      return ind;
    }
    __name(findToken, "findToken");
    var RDS1 = /^\.\.?\//u;
    var RDS2 = /^\/\.(?:\/|$)/u;
    var RDS3 = /^\/\.\.(?:\/|$)/u;
    var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/u;
    function removeDotSegments(input) {
      const output = [];
      while (input.length) {
        if (input.match(RDS1)) {
          input = input.replace(RDS1, "");
        } else if (input.match(RDS2)) {
          input = input.replace(RDS2, "/");
        } else if (input.match(RDS3)) {
          input = input.replace(RDS3, "/");
          output.pop();
        } else if (input === "." || input === "..") {
          input = "";
        } else {
          const im = input.match(RDS5);
          if (im) {
            const s2 = im[0];
            input = input.slice(s2.length);
            output.push(s2);
          } else {
            throw new Error("Unexpected dot segment condition");
          }
        }
      }
      return output.join("");
    }
    __name(removeDotSegments, "removeDotSegments");
    function normalizeComponentEncoding(components, esc) {
      const func = esc !== true ? escape : unescape;
      if (components.scheme !== void 0) {
        components.scheme = func(components.scheme);
      }
      if (components.userinfo !== void 0) {
        components.userinfo = func(components.userinfo);
      }
      if (components.host !== void 0) {
        components.host = func(components.host);
      }
      if (components.path !== void 0) {
        components.path = func(components.path);
      }
      if (components.query !== void 0) {
        components.query = func(components.query);
      }
      if (components.fragment !== void 0) {
        components.fragment = func(components.fragment);
      }
      return components;
    }
    __name(normalizeComponentEncoding, "normalizeComponentEncoding");
    function recomposeAuthority(components) {
      const uriTokens = [];
      if (components.userinfo !== void 0) {
        uriTokens.push(components.userinfo);
        uriTokens.push("@");
      }
      if (components.host !== void 0) {
        let host = unescape(components.host);
        const ipV4res = normalizeIPv4(host);
        if (ipV4res.isIPV4) {
          host = ipV4res.host;
        } else {
          const ipV6res = normalizeIPv6(ipV4res.host);
          if (ipV6res.isIPV6 === true) {
            host = `[${ipV6res.escapedHost}]`;
          } else {
            host = components.host;
          }
        }
        uriTokens.push(host);
      }
      if (typeof components.port === "number" || typeof components.port === "string") {
        uriTokens.push(":");
        uriTokens.push(String(components.port));
      }
      return uriTokens.length ? uriTokens.join("") : void 0;
    }
    __name(recomposeAuthority, "recomposeAuthority");
    module2.exports = {
      recomposeAuthority,
      normalizeComponentEncoding,
      removeDotSegments,
      normalizeIPv4,
      normalizeIPv6,
      stringArrayToHexStripped
    };
  }
});

// node_modules/fast-uri/lib/schemes.js
var require_schemes = __commonJS({
  "node_modules/fast-uri/lib/schemes.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var UUID_REG = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu;
    var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;
    function isSecure(wsComponents) {
      return typeof wsComponents.secure === "boolean" ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss";
    }
    __name(isSecure, "isSecure");
    function httpParse(components) {
      if (!components.host) {
        components.error = components.error || "HTTP URIs must have a host.";
      }
      return components;
    }
    __name(httpParse, "httpParse");
    function httpSerialize(components) {
      const secure = String(components.scheme).toLowerCase() === "https";
      if (components.port === (secure ? 443 : 80) || components.port === "") {
        components.port = void 0;
      }
      if (!components.path) {
        components.path = "/";
      }
      return components;
    }
    __name(httpSerialize, "httpSerialize");
    function wsParse(wsComponents) {
      wsComponents.secure = isSecure(wsComponents);
      wsComponents.resourceName = (wsComponents.path || "/") + (wsComponents.query ? "?" + wsComponents.query : "");
      wsComponents.path = void 0;
      wsComponents.query = void 0;
      return wsComponents;
    }
    __name(wsParse, "wsParse");
    function wsSerialize(wsComponents) {
      if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") {
        wsComponents.port = void 0;
      }
      if (typeof wsComponents.secure === "boolean") {
        wsComponents.scheme = wsComponents.secure ? "wss" : "ws";
        wsComponents.secure = void 0;
      }
      if (wsComponents.resourceName) {
        const [path108, query] = wsComponents.resourceName.split("?");
        wsComponents.path = path108 && path108 !== "/" ? path108 : void 0;
        wsComponents.query = query;
        wsComponents.resourceName = void 0;
      }
      wsComponents.fragment = void 0;
      return wsComponents;
    }
    __name(wsSerialize, "wsSerialize");
    function urnParse(urnComponents, options2) {
      if (!urnComponents.path) {
        urnComponents.error = "URN can not be parsed";
        return urnComponents;
      }
      const matches = urnComponents.path.match(URN_REG);
      if (matches) {
        const scheme = options2.scheme || urnComponents.scheme || "urn";
        urnComponents.nid = matches[1].toLowerCase();
        urnComponents.nss = matches[2];
        const urnScheme = `${scheme}:${options2.nid || urnComponents.nid}`;
        const schemeHandler = SCHEMES[urnScheme];
        urnComponents.path = void 0;
        if (schemeHandler) {
          urnComponents = schemeHandler.parse(urnComponents, options2);
        }
      } else {
        urnComponents.error = urnComponents.error || "URN can not be parsed.";
      }
      return urnComponents;
    }
    __name(urnParse, "urnParse");
    function urnSerialize(urnComponents, options2) {
      const scheme = options2.scheme || urnComponents.scheme || "urn";
      const nid = urnComponents.nid.toLowerCase();
      const urnScheme = `${scheme}:${options2.nid || nid}`;
      const schemeHandler = SCHEMES[urnScheme];
      if (schemeHandler) {
        urnComponents = schemeHandler.serialize(urnComponents, options2);
      }
      const uriComponents = urnComponents;
      const nss = urnComponents.nss;
      uriComponents.path = `${nid || options2.nid}:${nss}`;
      options2.skipEscape = true;
      return uriComponents;
    }
    __name(urnSerialize, "urnSerialize");
    function urnuuidParse(urnComponents, options2) {
      const uuidComponents = urnComponents;
      uuidComponents.uuid = uuidComponents.nss;
      uuidComponents.nss = void 0;
      if (!options2.tolerant && (!uuidComponents.uuid || !UUID_REG.test(uuidComponents.uuid))) {
        uuidComponents.error = uuidComponents.error || "UUID is not valid.";
      }
      return uuidComponents;
    }
    __name(urnuuidParse, "urnuuidParse");
    function urnuuidSerialize(uuidComponents) {
      const urnComponents = uuidComponents;
      urnComponents.nss = (uuidComponents.uuid || "").toLowerCase();
      return urnComponents;
    }
    __name(urnuuidSerialize, "urnuuidSerialize");
    var http4 = {
      scheme: "http",
      domainHost: true,
      parse: httpParse,
      serialize: httpSerialize
    };
    var https4 = {
      scheme: "https",
      domainHost: http4.domainHost,
      parse: httpParse,
      serialize: httpSerialize
    };
    var ws2 = {
      scheme: "ws",
      domainHost: true,
      parse: wsParse,
      serialize: wsSerialize
    };
    var wss = {
      scheme: "wss",
      domainHost: ws2.domainHost,
      parse: ws2.parse,
      serialize: ws2.serialize
    };
    var urn = {
      scheme: "urn",
      parse: urnParse,
      serialize: urnSerialize,
      skipNormalize: true
    };
    var urnuuid = {
      scheme: "urn:uuid",
      parse: urnuuidParse,
      serialize: urnuuidSerialize,
      skipNormalize: true
    };
    var SCHEMES = {
      http: http4,
      https: https4,
      ws: ws2,
      wss,
      urn,
      "urn:uuid": urnuuid
    };
    module2.exports = SCHEMES;
  }
});

// node_modules/fast-uri/index.js
var require_fast_uri = __commonJS({
  "node_modules/fast-uri/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { normalizeIPv6, normalizeIPv4, removeDotSegments, recomposeAuthority, normalizeComponentEncoding } = require_utils3();
    var SCHEMES = require_schemes();
    function normalize10(uri, options2) {
      if (typeof uri === "string") {
        uri = serialize2(parse12(uri, options2), options2);
      } else if (typeof uri === "object") {
        uri = parse12(serialize2(uri, options2), options2);
      }
      return uri;
    }
    __name(normalize10, "normalize");
    function resolve24(baseURI, relativeURI, options2) {
      const schemelessOptions = Object.assign({ scheme: "null" }, options2);
      const resolved = resolveComponents(parse12(baseURI, schemelessOptions), parse12(relativeURI, schemelessOptions), schemelessOptions, true);
      return serialize2(resolved, { ...schemelessOptions, skipEscape: true });
    }
    __name(resolve24, "resolve");
    function resolveComponents(base, relative10, options2, skipNormalization) {
      const target = {};
      if (!skipNormalization) {
        base = parse12(serialize2(base, options2), options2);
        relative10 = parse12(serialize2(relative10, options2), options2);
      }
      options2 = options2 || {};
      if (!options2.tolerant && relative10.scheme) {
        target.scheme = relative10.scheme;
        target.userinfo = relative10.userinfo;
        target.host = relative10.host;
        target.port = relative10.port;
        target.path = removeDotSegments(relative10.path || "");
        target.query = relative10.query;
      } else {
        if (relative10.userinfo !== void 0 || relative10.host !== void 0 || relative10.port !== void 0) {
          target.userinfo = relative10.userinfo;
          target.host = relative10.host;
          target.port = relative10.port;
          target.path = removeDotSegments(relative10.path || "");
          target.query = relative10.query;
        } else {
          if (!relative10.path) {
            target.path = base.path;
            if (relative10.query !== void 0) {
              target.query = relative10.query;
            } else {
              target.query = base.query;
            }
          } else {
            if (relative10.path.charAt(0) === "/") {
              target.path = removeDotSegments(relative10.path);
            } else {
              if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) {
                target.path = "/" + relative10.path;
              } else if (!base.path) {
                target.path = relative10.path;
              } else {
                target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative10.path;
              }
              target.path = removeDotSegments(target.path);
            }
            target.query = relative10.query;
          }
          target.userinfo = base.userinfo;
          target.host = base.host;
          target.port = base.port;
        }
        target.scheme = base.scheme;
      }
      target.fragment = relative10.fragment;
      return target;
    }
    __name(resolveComponents, "resolveComponents");
    function equal(uriA, uriB, options2) {
      if (typeof uriA === "string") {
        uriA = unescape(uriA);
        uriA = serialize2(normalizeComponentEncoding(parse12(uriA, options2), true), { ...options2, skipEscape: true });
      } else if (typeof uriA === "object") {
        uriA = serialize2(normalizeComponentEncoding(uriA, true), { ...options2, skipEscape: true });
      }
      if (typeof uriB === "string") {
        uriB = unescape(uriB);
        uriB = serialize2(normalizeComponentEncoding(parse12(uriB, options2), true), { ...options2, skipEscape: true });
      } else if (typeof uriB === "object") {
        uriB = serialize2(normalizeComponentEncoding(uriB, true), { ...options2, skipEscape: true });
      }
      return uriA.toLowerCase() === uriB.toLowerCase();
    }
    __name(equal, "equal");
    function serialize2(cmpts, opts) {
      const components = {
        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 options2 = Object.assign({}, opts);
      const uriTokens = [];
      const schemeHandler = SCHEMES[(options2.scheme || components.scheme || "").toLowerCase()];
      if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options2);
      if (components.path !== void 0) {
        if (!options2.skipEscape) {
          components.path = escape(components.path);
          if (components.scheme !== void 0) {
            components.path = components.path.split("%3A").join(":");
          }
        } else {
          components.path = unescape(components.path);
        }
      }
      if (options2.reference !== "suffix" && components.scheme) {
        uriTokens.push(components.scheme, ":");
      }
      const authority = recomposeAuthority(components);
      if (authority !== void 0) {
        if (options2.reference !== "suffix") {
          uriTokens.push("//");
        }
        uriTokens.push(authority);
        if (components.path && components.path.charAt(0) !== "/") {
          uriTokens.push("/");
        }
      }
      if (components.path !== void 0) {
        let s2 = components.path;
        if (!options2.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
          s2 = removeDotSegments(s2);
        }
        if (authority === void 0) {
          s2 = s2.replace(/^\/\//u, "/%2F");
        }
        uriTokens.push(s2);
      }
      if (components.query !== void 0) {
        uriTokens.push("?", components.query);
      }
      if (components.fragment !== void 0) {
        uriTokens.push("#", components.fragment);
      }
      return uriTokens.join("");
    }
    __name(serialize2, "serialize");
    var hexLookUp = Array.from({ length: 127 }, (_v, k) => /[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(k)));
    function nonSimpleDomain(value) {
      let code2 = 0;
      for (let i = 0, len = value.length; i < len; ++i) {
        code2 = value.charCodeAt(i);
        if (code2 > 126 || hexLookUp[code2]) {
          return true;
        }
      }
      return false;
    }
    __name(nonSimpleDomain, "nonSimpleDomain");
    var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
    function parse12(uri, opts) {
      const options2 = Object.assign({}, opts);
      const parsed = {
        scheme: void 0,
        userinfo: void 0,
        host: "",
        port: void 0,
        path: "",
        query: void 0,
        fragment: void 0
      };
      const gotEncoding = uri.indexOf("%") !== -1;
      let isIP = false;
      if (options2.reference === "suffix") uri = (options2.scheme ? options2.scheme + ":" : "") + "//" + uri;
      const matches = uri.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 = normalizeIPv4(parsed.host);
          if (ipv4result.isIPV4 === false) {
            const ipv6result = normalizeIPv6(ipv4result.host);
            parsed.host = ipv6result.host.toLowerCase();
            isIP = ipv6result.isIPV6;
          } else {
            parsed.host = ipv4result.host;
            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 (options2.reference && options2.reference !== "suffix" && options2.reference !== parsed.reference) {
          parsed.error = parsed.error || "URI is not a " + options2.reference + " reference.";
        }
        const schemeHandler = SCHEMES[(options2.scheme || parsed.scheme || "").toLowerCase()];
        if (!options2.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
          if (parsed.host && (options2.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) {
            try {
              parsed.host = URL.domainToASCII(parsed.host.toLowerCase());
            } catch (e2) {
              parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e2;
            }
          }
        }
        if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
          if (gotEncoding && parsed.scheme !== void 0) {
            parsed.scheme = unescape(parsed.scheme);
          }
          if (gotEncoding && 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, options2);
        }
      } else {
        parsed.error = parsed.error || "URI can not be parsed.";
      }
      return parsed;
    }
    __name(parse12, "parse");
    var fastUri = {
      SCHEMES,
      normalize: normalize10,
      resolve: resolve24,
      resolveComponents,
      equal,
      serialize: serialize2,
      parse: parse12
    };
    module2.exports = fastUri;
    module2.exports.default = fastUri;
    module2.exports.fastUri = fastUri;
  }
});

// packages/core/node_modules/ajv/dist/runtime/uri.js
var require_uri = __commonJS({
  "packages/core/node_modules/ajv/dist/runtime/uri.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var uri = require_fast_uri();
    uri.code = 'require("ajv/dist/runtime/uri").default';
    exports2.default = uri;
  }
});

// packages/core/node_modules/ajv/dist/core.js
var require_core = __commonJS({
  "packages/core/node_modules/ajv/dist/core.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CodeGen = exports2.Name = exports2.nil = exports2.stringify = exports2.str = exports2._ = exports2.KeywordCxt = void 0;
    var validate_1 = require_validate();
    Object.defineProperty(exports2, "KeywordCxt", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return validate_1.KeywordCxt;
    }, "get") });
    var codegen_1 = require_codegen();
    Object.defineProperty(exports2, "_", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1._;
    }, "get") });
    Object.defineProperty(exports2, "str", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.str;
    }, "get") });
    Object.defineProperty(exports2, "stringify", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.stringify;
    }, "get") });
    Object.defineProperty(exports2, "nil", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.nil;
    }, "get") });
    Object.defineProperty(exports2, "Name", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.Name;
    }, "get") });
    Object.defineProperty(exports2, "CodeGen", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.CodeGen;
    }, "get") });
    var validation_error_1 = require_validation_error();
    var ref_error_1 = require_ref_error();
    var rules_1 = require_rules();
    var compile_1 = require_compile();
    var codegen_2 = require_codegen();
    var resolve_1 = require_resolve();
    var dataType_1 = require_dataType();
    var util_1 = require_util9();
    var $dataRefSchema = require_data();
    var uri_1 = require_uri();
    var defaultRegExp = /* @__PURE__ */ __name((str2, flags) => new RegExp(str2, flags), "defaultRegExp");
    defaultRegExp.code = "new RegExp";
    var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
    var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([
      "validate",
      "serialize",
      "parse",
      "wrapper",
      "root",
      "schema",
      "keyword",
      "pattern",
      "formats",
      "validate$data",
      "func",
      "obj",
      "Error"
    ]);
    var 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."
    };
    var deprecatedOptions = {
      ignoreKeywordsWithRef: "",
      jsPropertySyntax: "",
      unicode: '"minLength"/"maxLength" account for unicode characters by default.'
    };
    var MAX_EXPRESSION = 200;
    function requiredOptions(o2) {
      var _a6, _b2, _c2, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
      const s2 = o2.strict;
      const _optz = (_a6 = o2.code) === null || _a6 === void 0 ? void 0 : _a6.optimize;
      const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;
      const regExp = (_c2 = (_b2 = o2.code) === null || _b2 === void 0 ? void 0 : _b2.regExp) !== null && _c2 !== void 0 ? _c2 : defaultRegExp;
      const uriResolver = (_d = o2.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
      return {
        strictSchema: (_f = (_e = o2.strictSchema) !== null && _e !== void 0 ? _e : s2) !== null && _f !== void 0 ? _f : true,
        strictNumbers: (_h = (_g = o2.strictNumbers) !== null && _g !== void 0 ? _g : s2) !== null && _h !== void 0 ? _h : true,
        strictTypes: (_k = (_j = o2.strictTypes) !== null && _j !== void 0 ? _j : s2) !== null && _k !== void 0 ? _k : "log",
        strictTuples: (_m = (_l = o2.strictTuples) !== null && _l !== void 0 ? _l : s2) !== null && _m !== void 0 ? _m : "log",
        strictRequired: (_p = (_o = o2.strictRequired) !== null && _o !== void 0 ? _o : s2) !== null && _p !== void 0 ? _p : false,
        code: o2.code ? { ...o2.code, optimize, regExp } : { optimize, regExp },
        loopRequired: (_q = o2.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
        loopEnum: (_r = o2.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
        meta: (_s = o2.meta) !== null && _s !== void 0 ? _s : true,
        messages: (_t = o2.messages) !== null && _t !== void 0 ? _t : true,
        inlineRefs: (_u = o2.inlineRefs) !== null && _u !== void 0 ? _u : true,
        schemaId: (_v = o2.schemaId) !== null && _v !== void 0 ? _v : "$id",
        addUsedSchema: (_w = o2.addUsedSchema) !== null && _w !== void 0 ? _w : true,
        validateSchema: (_x = o2.validateSchema) !== null && _x !== void 0 ? _x : true,
        validateFormats: (_y = o2.validateFormats) !== null && _y !== void 0 ? _y : true,
        unicodeRegExp: (_z = o2.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
        int32range: (_0 = o2.int32range) !== null && _0 !== void 0 ? _0 : true,
        uriResolver
      };
    }
    __name(requiredOptions, "requiredOptions");
    var Ajv2 = class {
      static {
        __name(this, "Ajv");
      }
      constructor(opts = {}) {
        this.schemas = {};
        this.refs = {};
        this.formats = {};
        this._compilations = /* @__PURE__ */ new Set();
        this._loading = {};
        this._cache = /* @__PURE__ */ new Map();
        opts = this.opts = { ...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, schemaId } = this.opts;
        let _dataRefSchema = $dataRefSchema;
        if (schemaId === "id") {
          _dataRefSchema = { ...$dataRefSchema };
          _dataRefSchema.id = _dataRefSchema.$id;
          delete _dataRefSchema.$id;
        }
        if (meta && $data)
          this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
      }
      defaultMeta() {
        const { meta, schemaId } = this.opts;
        return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : 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, meta) {
        if (typeof this.opts.loadSchema != "function") {
          throw new Error("options.loadSchema should be a function");
        }
        const { loadSchema } = this.opts;
        return runCompileAsync.call(this, schema, meta);
        async function runCompileAsync(_schema, _meta) {
          await loadMetaSchema.call(this, _schema.$schema);
          const sch = this._addSchema(_schema, _meta);
          return sch.validate || _compileAsync.call(this, sch);
        }
        __name(runCompileAsync, "runCompileAsync");
        async function loadMetaSchema($ref) {
          if ($ref && !this.getSchema($ref)) {
            await runCompileAsync.call(this, { $ref }, true);
          }
        }
        __name(loadMetaSchema, "loadMetaSchema");
        async function _compileAsync(sch) {
          try {
            return this._compileSchemaEnv(sch);
          } catch (e2) {
            if (!(e2 instanceof ref_error_1.default))
              throw e2;
            checkLoaded.call(this, e2);
            await loadMissingSchema.call(this, e2.missingSchema);
            return _compileAsync.call(this, sch);
          }
        }
        __name(_compileAsync, "_compileAsync");
        function checkLoaded({ missingSchema: ref, missingRef }) {
          if (this.refs[ref]) {
            throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
          }
        }
        __name(checkLoaded, "checkLoaded");
        async function loadMissingSchema(ref) {
          const _schema = await _loadSchema.call(this, ref);
          if (!this.refs[ref])
            await loadMetaSchema.call(this, _schema.$schema);
          if (!this.refs[ref])
            this.addSchema(_schema, ref, meta);
        }
        __name(loadMissingSchema, "loadMissingSchema");
        async function _loadSchema(ref) {
          const p = this._loading[ref];
          if (p)
            return p;
          try {
            return await (this._loading[ref] = loadSchema(ref));
          } finally {
            delete this._loading[ref];
          }
        }
        __name(_loadSchema, "_loadSchema");
      }
      // 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 id;
        if (typeof schema === "object") {
          const { schemaId } = this.opts;
          id = schema[schemaId];
          if (id !== void 0 && typeof id != "string") {
            throw new Error(`schema ${schemaId} must be string`);
          }
        }
        key = (0, resolve_1.normalizeId)(key || id);
        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 $schema;
        $schema = schema.$schema;
        if ($schema !== void 0 && typeof $schema != "string") {
          throw new Error("$schema must be a string");
        }
        $schema = $schema || this.opts.defaultMeta || this.defaultMeta();
        if (!$schema) {
          this.logger.warn("meta-schema not available");
          this.errors = null;
          return true;
        }
        const valid = this.validate($schema, 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 id = schemaKeyRef[this.opts.schemaId];
            if (id) {
              id = (0, resolve_1.normalizeId)(id);
              delete this.schemas[id];
              delete this.refs[id];
            }
            return this;
          }
          default:
            throw new Error("ajv.removeSchema: invalid parameter");
        }
      }
      // add "vocabulary" - a collection of keywords
      addVocabulary(definitions) {
        for (const def2 of definitions)
          this.addKeyword(def2);
        return this;
      }
      addKeyword(kwdOrDef, def2) {
        let keyword;
        if (typeof kwdOrDef == "string") {
          keyword = kwdOrDef;
          if (typeof def2 == "object") {
            this.logger.warn("these parameters are deprecated, see docs for addKeyword");
            def2.keyword = keyword;
          }
        } else if (typeof kwdOrDef == "object" && def2 === void 0) {
          def2 = kwdOrDef;
          keyword = def2.keyword;
          if (Array.isArray(keyword) && !keyword.length) {
            throw new Error("addKeywords: keyword must be string or non-empty array");
          }
        } else {
          throw new Error("invalid addKeywords parameters");
        }
        checkKeyword.call(this, keyword, def2);
        if (!def2) {
          (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
          return this;
        }
        keywordMetaschema.call(this, def2);
        const definition = {
          ...def2,
          type: (0, dataType_1.getJSONTypes)(def2.type),
          schemaType: (0, dataType_1.getJSONTypes)(def2.schemaType)
        };
        (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t2) => addRule.call(this, k, definition, t2)));
        return this;
      }
      getKeyword(keyword) {
        const rule = this.RULES.all[keyword];
        return typeof rule == "object" ? rule.definition : !!rule;
      }
      // Remove keyword
      removeKeyword(keyword) {
        const { RULES } = this;
        delete RULES.keywords[keyword];
        delete RULES.all[keyword];
        for (const group of RULES.rules) {
          const i = group.rules.findIndex((rule) => rule.keyword === keyword);
          if (i >= 0)
            group.rules.splice(i, 1);
        }
        return this;
      }
      // Add format
      addFormat(name3, format4) {
        if (typeof format4 == "string")
          format4 = new RegExp(format4);
        this.formats[name3] = format4;
        return this;
      }
      errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) {
        if (!errors || errors.length === 0)
          return "No errors";
        return errors.map((e2) => `${dataVar}${e2.instancePath} ${e2.message}`).reduce((text, msg) => text + separator + msg);
      }
      $dataMetaSchema(metaSchema, keywordsJsonPointers) {
        const rules = this.RULES.all;
        metaSchema = JSON.parse(JSON.stringify(metaSchema));
        for (const jsonPointer of keywordsJsonPointers) {
          const segments = jsonPointer.split("/").slice(1);
          let keywords2 = metaSchema;
          for (const seg of segments)
            keywords2 = keywords2[seg];
          for (const key in rules) {
            const rule = rules[key];
            if (typeof rule != "object")
              continue;
            const { $data } = rule.definition;
            const schema = keywords2[key];
            if ($data && schema)
              keywords2[key] = schemaOrData(schema);
          }
        }
        return metaSchema;
      }
      _removeAllSchemas(schemas, regex3) {
        for (const keyRef in schemas) {
          const sch = schemas[keyRef];
          if (!regex3 || regex3.test(keyRef)) {
            if (typeof sch == "string") {
              delete schemas[keyRef];
            } else if (sch && !sch.meta) {
              this._cache.delete(sch.schema);
              delete schemas[keyRef];
            }
          }
        }
      }
      _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
        let id;
        const { schemaId } = this.opts;
        if (typeof schema == "object") {
          id = 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)(id || baseId);
        const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
        sch = new compile_1.SchemaEnv({ schema, schemaId, meta, 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(id) {
        if (this.schemas[id] || this.refs[id]) {
          throw new Error(`schema with key or id "${id}" 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;
    exports2.default = Ajv2;
    function checkOptions(checkOpts, options2, msg, log = "error") {
      for (const key in checkOpts) {
        const opt = key;
        if (opt in options2)
          this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
      }
    }
    __name(checkOptions, "checkOptions");
    function getSchEnv(keyRef) {
      keyRef = (0, resolve_1.normalizeId)(keyRef);
      return this.schemas[keyRef] || this.refs[keyRef];
    }
    __name(getSchEnv, "getSchEnv");
    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);
    }
    __name(addInitialSchemas, "addInitialSchemas");
    function addInitialFormats() {
      for (const name3 in this.opts.formats) {
        const format4 = this.opts.formats[name3];
        if (format4)
          this.addFormat(name3, format4);
      }
    }
    __name(addInitialFormats, "addInitialFormats");
    function addInitialKeywords(defs) {
      if (Array.isArray(defs)) {
        this.addVocabulary(defs);
        return;
      }
      this.logger.warn("keywords option as map is deprecated, pass array");
      for (const keyword in defs) {
        const def2 = defs[keyword];
        if (!def2.keyword)
          def2.keyword = keyword;
        this.addKeyword(def2);
      }
    }
    __name(addInitialKeywords, "addInitialKeywords");
    function getMetaSchemaOptions() {
      const metaOpts = { ...this.opts };
      for (const opt of META_IGNORE_OPTIONS)
        delete metaOpts[opt];
      return metaOpts;
    }
    __name(getMetaSchemaOptions, "getMetaSchemaOptions");
    var noLogs = { log() {
    }, warn() {
    }, error() {
    } };
    function getLogger(logger6) {
      if (logger6 === false)
        return noLogs;
      if (logger6 === void 0)
        return console;
      if (logger6.log && logger6.warn && logger6.error)
        return logger6;
      throw new Error("logger must implement log, warn and error methods");
    }
    __name(getLogger, "getLogger");
    var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
    function checkKeyword(keyword, def2) {
      const { RULES } = this;
      (0, util_1.eachItem)(keyword, (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 (!def2)
        return;
      if (def2.$data && !("code" in def2 || "validate" in def2)) {
        throw new Error('$data keyword must have "code" or "validate" function');
      }
    }
    __name(checkKeyword, "checkKeyword");
    function addRule(keyword, definition, dataType) {
      var _a6;
      const post = definition === null || definition === void 0 ? void 0 : definition.post;
      if (dataType && post)
        throw new Error('keyword with "post" flag cannot have "type"');
      const { RULES } = this;
      let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t2 }) => t2 === dataType);
      if (!ruleGroup) {
        ruleGroup = { type: dataType, rules: [] };
        RULES.rules.push(ruleGroup);
      }
      RULES.keywords[keyword] = true;
      if (!definition)
        return;
      const rule = {
        keyword,
        definition: {
          ...definition,
          type: (0, dataType_1.getJSONTypes)(definition.type),
          schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType)
        }
      };
      if (definition.before)
        addBeforeRule.call(this, ruleGroup, rule, definition.before);
      else
        ruleGroup.rules.push(rule);
      RULES.all[keyword] = rule;
      (_a6 = definition.implements) === null || _a6 === void 0 ? void 0 : _a6.forEach((kwd) => this.addKeyword(kwd));
    }
    __name(addRule, "addRule");
    function addBeforeRule(ruleGroup, rule, before) {
      const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
      if (i >= 0) {
        ruleGroup.rules.splice(i, 0, rule);
      } else {
        ruleGroup.rules.push(rule);
        this.logger.warn(`rule ${before} is not defined`);
      }
    }
    __name(addBeforeRule, "addBeforeRule");
    function keywordMetaschema(def2) {
      let { metaSchema } = def2;
      if (metaSchema === void 0)
        return;
      if (def2.$data && this.opts.$data)
        metaSchema = schemaOrData(metaSchema);
      def2.validateSchema = this.compile(metaSchema, true);
    }
    __name(keywordMetaschema, "keywordMetaschema");
    var $dataRef = {
      $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"
    };
    function schemaOrData(schema) {
      return { anyOf: [schema, $dataRef] };
    }
    __name(schemaOrData, "schemaOrData");
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/core/id.js
var require_id = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/core/id.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var def2 = {
      keyword: "id",
      code() {
        throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/core/ref.js
var require_ref = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/core/ref.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.callRef = exports2.getValidate = void 0;
    var ref_error_1 = require_ref_error();
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var compile_1 = require_compile();
    var util_1 = require_util9();
    var def2 = {
      keyword: "$ref",
      schemaType: "string",
      code(cxt) {
        const { gen, schema: $ref, it } = cxt;
        const { baseId, schemaEnv: env7, validateName: validateName2, opts, self: self2 } = it;
        const { root } = env7;
        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(it.opts.uriResolver, baseId, $ref);
        if (schOrEnv instanceof compile_1.SchemaEnv)
          return callValidate(schOrEnv);
        return inlineRefSchema(schOrEnv);
        function callRootRef() {
          if (env7 === root)
            return callRef(cxt, validateName2, env7, env7.$async);
          const rootName = gen.scopeValue("root", { ref: root });
          return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async);
        }
        __name(callRootRef, "callRootRef");
        function callValidate(sch) {
          const v = getValidate(cxt, sch);
          callRef(cxt, v, sch, sch.$async);
        }
        __name(callValidate, "callValidate");
        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);
        }
        __name(inlineRefSchema, "inlineRefSchema");
      }
    };
    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`;
    }
    __name(getValidate, "getValidate");
    exports2.getValidate = getValidate;
    function callRef(cxt, v, sch, $async) {
      const { gen, it } = cxt;
      const { allErrors, schemaEnv: env7, opts } = it;
      const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
      if ($async)
        callAsyncRef();
      else
        callSyncRef();
      function callAsyncRef() {
        if (!env7.$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);
        }, (e2) => {
          gen.if((0, codegen_1._)`!(${e2} instanceof ${it.ValidationError})`, () => gen.throw(e2));
          addErrorsFrom(e2);
          if (!allErrors)
            gen.assign(valid, false);
        });
        cxt.ok(valid);
      }
      __name(callAsyncRef, "callAsyncRef");
      function callSyncRef() {
        cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
      }
      __name(callSyncRef, "callSyncRef");
      function addErrorsFrom(source2) {
        const errs = (0, codegen_1._)`${source2}.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`);
      }
      __name(addErrorsFrom, "addErrorsFrom");
      function addEvaluatedFrom(source2) {
        var _a6;
        if (!it.opts.unevaluated)
          return;
        const schEvaluated = (_a6 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a6 === void 0 ? void 0 : _a6.evaluated;
        if (it.props !== true) {
          if (schEvaluated && !schEvaluated.dynamicProps) {
            if (schEvaluated.props !== void 0) {
              it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
            }
          } else {
            const props = gen.var("props", (0, codegen_1._)`${source2}.evaluated.props`);
            it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
          }
        }
        if (it.items !== true) {
          if (schEvaluated && !schEvaluated.dynamicItems) {
            if (schEvaluated.items !== void 0) {
              it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
            }
          } else {
            const items = gen.var("items", (0, codegen_1._)`${source2}.evaluated.items`);
            it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
          }
        }
      }
      __name(addEvaluatedFrom, "addEvaluatedFrom");
    }
    __name(callRef, "callRef");
    exports2.callRef = callRef;
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/core/index.js
var require_core2 = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/core/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var id_1 = require_id();
    var ref_1 = require_ref();
    var core = [
      "$schema",
      "$id",
      "$defs",
      "$vocabulary",
      { keyword: "$comment" },
      "definitions",
      id_1.default,
      ref_1.default
    ];
    exports2.default = core;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/validation/limitNumber.js
var require_limitNumber = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var ops = codegen_1.operators;
    var 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 }
    };
    var error = {
      message: /* @__PURE__ */ __name(({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, "message"),
      params: /* @__PURE__ */ __name(({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: Object.keys(KWDs),
      type: "number",
      schemaType: "number",
      $data: true,
      error,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/validation/multipleOf.js
var require_multipleOf = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var error = {
      message: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, "message"),
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: "multipleOf",
      type: "number",
      schemaType: "number",
      $data: true,
      error,
      code(cxt) {
        const { gen, data, schemaCode, it } = cxt;
        const prec = it.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}))`);
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/runtime/ucs2length.js
var require_ucs2length = __commonJS({
  "packages/core/node_modules/ajv/dist/runtime/ucs2length.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    function ucs2length(str2) {
      const len = str2.length;
      let length = 0;
      let pos2 = 0;
      let value;
      while (pos2 < len) {
        length++;
        value = str2.charCodeAt(pos2++);
        if (value >= 55296 && value <= 56319 && pos2 < len) {
          value = str2.charCodeAt(pos2);
          if ((value & 64512) === 56320)
            pos2++;
        }
      }
      return length;
    }
    __name(ucs2length, "ucs2length");
    exports2.default = ucs2length;
    ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/validation/limitLength.js
var require_limitLength = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var ucs2length_1 = require_ucs2length();
    var error = {
      message({ keyword, schemaCode }) {
        const comp = keyword === "maxLength" ? "more" : "fewer";
        return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`;
      },
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: ["maxLength", "minLength"],
      type: "string",
      schemaType: "number",
      $data: true,
      error,
      code(cxt) {
        const { keyword, data, schemaCode, it } = cxt;
        const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
        const len = it.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._)`${len} ${op} ${schemaCode}`);
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/validation/pattern.js
var require_pattern = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var error = {
      message: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, "message"),
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: "pattern",
      type: "string",
      schemaType: "string",
      $data: true,
      error,
      code(cxt) {
        const { data, $data, schema, schemaCode, it } = cxt;
        const u = it.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})`);
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/validation/limitProperties.js
var require_limitProperties = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var error = {
      message({ keyword, schemaCode }) {
        const comp = keyword === "maxProperties" ? "more" : "fewer";
        return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`;
      },
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: ["maxProperties", "minProperties"],
      type: "object",
      schemaType: "number",
      $data: true,
      error,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`);
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/validation/required.js
var require_required = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/validation/required.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var error = {
      message: /* @__PURE__ */ __name(({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, "message"),
      params: /* @__PURE__ */ __name(({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}`, "params")
    };
    var def2 = {
      keyword: "required",
      type: "object",
      schemaType: "array",
      $data: true,
      error,
      code(cxt) {
        const { gen, schema, schemaCode, data, $data, it } = cxt;
        const { opts } = it;
        if (!$data && schema.length === 0)
          return;
        const useLoop = schema.length >= opts.loopRequired;
        if (it.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 = it.schemaEnv.baseId + it.errSchemaPath;
              const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
              (0, util_1.checkStrictMode)(it, msg, it.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);
            }
          }
        }
        __name(allErrorsMode, "allErrorsMode");
        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();
          }
        }
        __name(exitOnErrorMode, "exitOnErrorMode");
        function loopAllRequired() {
          gen.forOf("prop", schemaCode, (prop) => {
            cxt.setParams({ missingProperty: prop });
            gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
          });
        }
        __name(loopAllRequired, "loopAllRequired");
        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);
        }
        __name(loopUntilMissing, "loopUntilMissing");
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/validation/limitItems.js
var require_limitItems = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var error = {
      message({ keyword, schemaCode }) {
        const comp = keyword === "maxItems" ? "more" : "fewer";
        return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`;
      },
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: ["maxItems", "minItems"],
      type: "array",
      schemaType: "number",
      $data: true,
      error,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`);
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/runtime/equal.js
var require_equal = __commonJS({
  "packages/core/node_modules/ajv/dist/runtime/equal.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var equal = require_fast_deep_equal();
    equal.code = 'require("ajv/dist/runtime/equal").default';
    exports2.default = equal;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js
var require_uniqueItems = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var dataType_1 = require_dataType();
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var equal_1 = require_equal();
    var error = {
      message: /* @__PURE__ */ __name(({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, "message"),
      params: /* @__PURE__ */ __name(({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}`, "params")
    };
    var def2 = {
      keyword: "uniqueItems",
      type: "array",
      schemaType: "boolean",
      $data: true,
      error,
      code(cxt) {
        const { gen, data, $data, schema, parentSchema, schemaCode, it } = 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 i = gen.let("i", (0, codegen_1._)`${data}.length`);
          const j = gen.let("j");
          cxt.setParams({ i, j });
          gen.assign(valid, true);
          gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
        }
        __name(validateUniqueItems, "validateUniqueItems");
        function canOptimize() {
          return itemTypes.length > 0 && !itemTypes.some((t2) => t2 === "object" || t2 === "array");
        }
        __name(canOptimize, "canOptimize");
        function loopN(i, j) {
          const item = gen.name("item");
          const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
          const indices = gen.const("indices", (0, codegen_1._)`{}`);
          gen.for((0, codegen_1._)`;${i}--;`, () => {
            gen.let(item, (0, codegen_1._)`${data}[${i}]`);
            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}] = ${i}`);
          });
        }
        __name(loopN, "loopN");
        function loopN2(i, j) {
          const eql = (0, util_1.useFunc)(gen, equal_1.default);
          const outer = gen.name("outer");
          gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => {
            cxt.error();
            gen.assign(valid, false).break(outer);
          })));
        }
        __name(loopN2, "loopN2");
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/validation/const.js
var require_const = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/validation/const.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var equal_1 = require_equal();
    var error = {
      message: "must be equal to constant",
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: "const",
      $data: true,
      error,
      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}`);
        }
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/validation/enum.js
var require_enum = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var equal_1 = require_equal();
    var error = {
      message: "must be equal to one of the allowed values",
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: "enum",
      schemaType: "array",
      $data: true,
      error,
      code(cxt) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        if (!$data && schema.length === 0)
          throw new Error("enum must have non-empty array");
        const useLoop = schema.length >= it.opts.loopEnum;
        let eql;
        const getEql = /* @__PURE__ */ __name(() => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default), "getEql");
        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, i) => equalCode(vSchema, i)));
        }
        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()));
        }
        __name(loopEnum, "loopEnum");
        function equalCode(vSchema, i) {
          const sch = schema[i];
          return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`;
        }
        __name(equalCode, "equalCode");
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/validation/index.js
var require_validation2 = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/validation/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var limitNumber_1 = require_limitNumber();
    var multipleOf_1 = require_multipleOf();
    var limitLength_1 = require_limitLength();
    var pattern_1 = require_pattern();
    var limitProperties_1 = require_limitProperties();
    var required_1 = require_required();
    var limitItems_1 = require_limitItems();
    var uniqueItems_1 = require_uniqueItems();
    var const_1 = require_const();
    var enum_1 = require_enum();
    var validation2 = [
      // 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
    ];
    exports2.default = validation2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js
var require_additionalItems = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateAdditionalItems = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var error = {
      message: /* @__PURE__ */ __name(({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, "message"),
      params: /* @__PURE__ */ __name(({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`, "params")
    };
    var def2 = {
      keyword: "additionalItems",
      type: "array",
      schemaType: ["boolean", "object"],
      before: "uniqueItems",
      error,
      code(cxt) {
        const { parentSchema, it } = cxt;
        const { items } = parentSchema;
        if (!Array.isArray(items)) {
          (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
          return;
        }
        validateAdditionalItems(cxt, items);
      }
    };
    function validateAdditionalItems(cxt, items) {
      const { gen, schema, data, keyword, it } = cxt;
      it.items = true;
      const len = gen.const("len", (0, codegen_1._)`${data}.length`);
      if (schema === false) {
        cxt.setParams({ len: items.length });
        cxt.pass((0, codegen_1._)`${len} <= ${items.length}`);
      } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
        const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`);
        gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
        cxt.ok(valid);
      }
      function validateItems(valid) {
        gen.forRange("i", items.length, len, (i) => {
          cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);
          if (!it.allErrors)
            gen.if((0, codegen_1.not)(valid), () => gen.break());
        });
      }
      __name(validateItems, "validateItems");
    }
    __name(validateAdditionalItems, "validateAdditionalItems");
    exports2.validateAdditionalItems = validateAdditionalItems;
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/items.js
var require_items = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateTuple = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var code_1 = require_code2();
    var def2 = {
      keyword: "items",
      type: "array",
      schemaType: ["object", "array", "boolean"],
      before: "uniqueItems",
      code(cxt) {
        const { schema, it } = cxt;
        if (Array.isArray(schema))
          return validateTuple(cxt, "additionalItems", schema);
        it.items = true;
        if ((0, util_1.alwaysValidSchema)(it, schema))
          return;
        cxt.ok((0, code_1.validateArray)(cxt));
      }
    };
    function validateTuple(cxt, extraItems, schArr = cxt.schema) {
      const { gen, parentSchema, data, keyword, it } = cxt;
      checkStrictTuple(parentSchema);
      if (it.opts.unevaluated && schArr.length && it.items !== true) {
        it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);
      }
      const valid = gen.name("valid");
      const len = gen.const("len", (0, codegen_1._)`${data}.length`);
      schArr.forEach((sch, i) => {
        if ((0, util_1.alwaysValidSchema)(it, sch))
          return;
        gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({
          keyword,
          schemaProp: i,
          dataProp: i
        }, valid));
        cxt.ok(valid);
      });
      function checkStrictTuple(sch) {
        const { opts, errSchemaPath } = it;
        const l2 = schArr.length;
        const fullTuple = l2 === sch.minItems && (l2 === sch.maxItems || sch[extraItems] === false);
        if (opts.strictTuples && !fullTuple) {
          const msg = `"${keyword}" is ${l2}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
          (0, util_1.checkStrictMode)(it, msg, opts.strictTuples);
        }
      }
      __name(checkStrictTuple, "checkStrictTuple");
    }
    __name(validateTuple, "validateTuple");
    exports2.validateTuple = validateTuple;
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js
var require_prefixItems = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var items_1 = require_items();
    var def2 = {
      keyword: "prefixItems",
      type: "array",
      schemaType: ["array"],
      before: "uniqueItems",
      code: /* @__PURE__ */ __name((cxt) => (0, items_1.validateTuple)(cxt, "items"), "code")
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/items2020.js
var require_items2020 = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var code_1 = require_code2();
    var additionalItems_1 = require_additionalItems();
    var error = {
      message: /* @__PURE__ */ __name(({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, "message"),
      params: /* @__PURE__ */ __name(({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`, "params")
    };
    var def2 = {
      keyword: "items",
      type: "array",
      schemaType: ["object", "boolean"],
      before: "uniqueItems",
      error,
      code(cxt) {
        const { schema, parentSchema, it } = cxt;
        const { prefixItems } = parentSchema;
        it.items = true;
        if ((0, util_1.alwaysValidSchema)(it, schema))
          return;
        if (prefixItems)
          (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
        else
          cxt.ok((0, code_1.validateArray)(cxt));
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/contains.js
var require_contains = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var error = {
      message: /* @__PURE__ */ __name(({ params: { min, max } }) => max === 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 ${max} valid item(s)`, "message"),
      params: /* @__PURE__ */ __name(({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}`, "params")
    };
    var def2 = {
      keyword: "contains",
      type: "array",
      schemaType: ["object", "boolean"],
      before: "uniqueItems",
      trackErrors: true,
      error,
      code(cxt) {
        const { gen, schema, parentSchema, data, it } = cxt;
        let min;
        let max;
        const { minContains, maxContains } = parentSchema;
        if (it.opts.next) {
          min = minContains === void 0 ? 1 : minContains;
          max = maxContains;
        } else {
          min = 1;
        }
        const len = gen.const("len", (0, codegen_1._)`${data}.length`);
        cxt.setParams({ min, max });
        if (max === void 0 && min === 0) {
          (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
          return;
        }
        if (max !== void 0 && min > max) {
          (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
          cxt.fail();
          return;
        }
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
          let cond = (0, codegen_1._)`${len} >= ${min}`;
          if (max !== void 0)
            cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`;
          cxt.pass(cond);
          return;
        }
        it.items = true;
        const valid = gen.name("valid");
        if (max === void 0 && min === 1) {
          validateItems(valid, () => gen.if(valid, () => gen.break()));
        } else if (min === 0) {
          gen.let(valid, true);
          if (max !== 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)));
        }
        __name(validateItemsWithCount, "validateItemsWithCount");
        function validateItems(_valid, block2) {
          gen.forRange("i", 0, len, (i) => {
            cxt.subschema({
              keyword: "contains",
              dataProp: i,
              dataPropType: util_1.Type.Num,
              compositeRule: true
            }, _valid);
            block2();
          });
        }
        __name(validateItems, "validateItems");
        function checkLimits(count) {
          gen.code((0, codegen_1._)`${count}++`);
          if (max === void 0) {
            gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());
          } else {
            gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break());
            if (min === 1)
              gen.assign(valid, true);
            else
              gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));
          }
        }
        __name(checkLimits, "checkLimits");
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/dependencies.js
var require_dependencies = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateSchemaDeps = exports2.validatePropertyDeps = exports2.error = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var code_1 = require_code2();
    exports2.error = {
      message: /* @__PURE__ */ __name(({ 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`;
      }, "message"),
      params: /* @__PURE__ */ __name(({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`, "params")
      // TODO change to reference
    };
    var def2 = {
      keyword: "dependencies",
      type: "object",
      schemaType: "object",
      error: exports2.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];
    }
    __name(splitDependencies, "splitDependencies");
    function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
      const { gen, data, it } = 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 hasProperty2 = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
        cxt.setParams({
          property: prop,
          depsCount: deps.length,
          deps: deps.join(", ")
        });
        if (it.allErrors) {
          gen.if(hasProperty2, () => {
            for (const depProp of deps) {
              (0, code_1.checkReportMissingProp)(cxt, depProp);
            }
          });
        } else {
          gen.if((0, codegen_1._)`${hasProperty2} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
          (0, code_1.reportMissingProp)(cxt, missing);
          gen.else();
        }
      }
    }
    __name(validatePropertyDeps, "validatePropertyDeps");
    exports2.validatePropertyDeps = validatePropertyDeps;
    function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
      const { gen, data, keyword, it } = cxt;
      const valid = gen.name("valid");
      for (const prop in schemaDeps) {
        if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))
          continue;
        gen.if(
          (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties),
          () => {
            const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
            cxt.mergeValidEvaluated(schCxt, valid);
          },
          () => gen.var(valid, true)
          // TODO var
        );
        cxt.ok(valid);
      }
    }
    __name(validateSchemaDeps, "validateSchemaDeps");
    exports2.validateSchemaDeps = validateSchemaDeps;
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js
var require_propertyNames = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var error = {
      message: "property name must be valid",
      params: /* @__PURE__ */ __name(({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}`, "params")
    };
    var def2 = {
      keyword: "propertyNames",
      type: "object",
      schemaType: ["object", "boolean"],
      error,
      code(cxt) {
        const { gen, schema, data, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, 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 (!it.allErrors)
              gen.break();
          });
        });
        cxt.ok(valid);
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js
var require_additionalProperties = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var util_1 = require_util9();
    var error = {
      message: "must NOT have additional properties",
      params: /* @__PURE__ */ __name(({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}`, "params")
    };
    var def2 = {
      keyword: "additionalProperties",
      type: ["object"],
      schemaType: ["boolean", "object"],
      allowUndefined: true,
      trackErrors: true,
      error,
      code(cxt) {
        const { gen, schema, parentSchema, data, errsCount, it } = cxt;
        if (!errsCount)
          throw new Error("ajv implementation error");
        const { allErrors, opts } = it;
        it.props = true;
        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, 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));
          });
        }
        __name(checkAdditionalProperties, "checkAdditionalProperties");
        function isAdditional(key) {
          let definedProp;
          if (props.length > 8) {
            const propsSchema = (0, util_1.schemaRefOrVal)(it, 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);
        }
        __name(isAdditional, "isAdditional");
        function deleteAdditional(key) {
          gen.code((0, codegen_1._)`delete ${data}[${key}]`);
        }
        __name(deleteAdditional, "deleteAdditional");
        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)(it, 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());
            }
          }
        }
        __name(additionalPropertyCode, "additionalPropertyCode");
        function applyAdditionalSchema(key, valid, errors) {
          const subschema = {
            keyword: "additionalProperties",
            dataProp: key,
            dataPropType: util_1.Type.Str
          };
          if (errors === false) {
            Object.assign(subschema, {
              compositeRule: true,
              createErrors: false,
              allErrors: false
            });
          }
          cxt.subschema(subschema, valid);
        }
        __name(applyAdditionalSchema, "applyAdditionalSchema");
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/properties.js
var require_properties = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var validate_1 = require_validate();
    var code_1 = require_code2();
    var util_1 = require_util9();
    var additionalProperties_1 = require_additionalProperties();
    var def2 = {
      keyword: "properties",
      type: "object",
      schemaType: "object",
      code(cxt) {
        const { gen, schema, parentSchema, data, it } = cxt;
        if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) {
          additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
        }
        const allProps = (0, code_1.allSchemaProperties)(schema);
        for (const prop of allProps) {
          it.definedProperties.add(prop);
        }
        if (it.opts.unevaluated && allProps.length && it.props !== true) {
          it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
        }
        const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
        if (properties.length === 0)
          return;
        const valid = gen.name("valid");
        for (const prop of properties) {
          if (hasDefault(prop)) {
            applyPropertySchema(prop);
          } else {
            gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));
            applyPropertySchema(prop);
            if (!it.allErrors)
              gen.else().var(valid, true);
            gen.endIf();
          }
          cxt.it.definedProperties.add(prop);
          cxt.ok(valid);
        }
        function hasDefault(prop) {
          return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0;
        }
        __name(hasDefault, "hasDefault");
        function applyPropertySchema(prop) {
          cxt.subschema({
            keyword: "properties",
            schemaProp: prop,
            dataProp: prop
          }, valid);
        }
        __name(applyPropertySchema, "applyPropertySchema");
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js
var require_patternProperties = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var util_2 = require_util9();
    var def2 = {
      keyword: "patternProperties",
      type: "object",
      schemaType: "object",
      code(cxt) {
        const { gen, schema, data, parentSchema, it } = cxt;
        const { opts } = it;
        const patterns = (0, code_1.allSchemaProperties)(schema);
        const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));
        if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) {
          return;
        }
        const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
        const valid = gen.name("valid");
        if (it.props !== true && !(it.props instanceof codegen_1.Name)) {
          it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
        }
        const { props } = it;
        validatePatternProperties();
        function validatePatternProperties() {
          for (const pat of patterns) {
            if (checkProperties)
              checkMatchingProperties(pat);
            if (it.allErrors) {
              validateProperties(pat);
            } else {
              gen.var(valid, true);
              validateProperties(pat);
              gen.if(valid);
            }
          }
        }
        __name(validatePatternProperties, "validatePatternProperties");
        function checkMatchingProperties(pat) {
          for (const prop in checkProperties) {
            if (new RegExp(pat).test(prop)) {
              (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
            }
          }
        }
        __name(checkMatchingProperties, "checkMatchingProperties");
        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 (it.opts.unevaluated && props !== true) {
                gen.assign((0, codegen_1._)`${props}[${key}]`, true);
              } else if (!alwaysValid && !it.allErrors) {
                gen.if((0, codegen_1.not)(valid), () => gen.break());
              }
            });
          });
        }
        __name(validateProperties, "validateProperties");
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/not.js
var require_not = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var util_1 = require_util9();
    var def2 = {
      keyword: "not",
      schemaType: ["object", "boolean"],
      trackErrors: true,
      code(cxt) {
        const { gen, schema, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, 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" }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/anyOf.js
var require_anyOf = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code2();
    var def2 = {
      keyword: "anyOf",
      schemaType: "array",
      trackErrors: true,
      code: code_1.validateUnion,
      error: { message: "must match a schema in anyOf" }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/oneOf.js
var require_oneOf = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var error = {
      message: "must match exactly one schema in oneOf",
      params: /* @__PURE__ */ __name(({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}`, "params")
    };
    var def2 = {
      keyword: "oneOf",
      schemaType: "array",
      trackErrors: true,
      error,
      code(cxt) {
        const { gen, schema, parentSchema, it } = cxt;
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        if (it.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, i) => {
            let schCxt;
            if ((0, util_1.alwaysValidSchema)(it, sch)) {
              gen.var(schValid, true);
            } else {
              schCxt = cxt.subschema({
                keyword: "oneOf",
                schemaProp: i,
                compositeRule: true
              }, schValid);
            }
            if (i > 0) {
              gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else();
            }
            gen.if(schValid, () => {
              gen.assign(valid, true);
              gen.assign(passing, i);
              if (schCxt)
                cxt.mergeEvaluated(schCxt, codegen_1.Name);
            });
          });
        }
        __name(validateOneOf, "validateOneOf");
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/allOf.js
var require_allOf = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var util_1 = require_util9();
    var def2 = {
      keyword: "allOf",
      schemaType: "array",
      code(cxt) {
        const { gen, schema, it } = cxt;
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        const valid = gen.name("valid");
        schema.forEach((sch, i) => {
          if ((0, util_1.alwaysValidSchema)(it, sch))
            return;
          const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
          cxt.ok(valid);
          cxt.mergeEvaluated(schCxt);
        });
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/if.js
var require_if = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var error = {
      message: /* @__PURE__ */ __name(({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, "message"),
      params: /* @__PURE__ */ __name(({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}`, "params")
    };
    var def2 = {
      keyword: "if",
      schemaType: ["object", "boolean"],
      trackErrors: true,
      error,
      code(cxt) {
        const { gen, parentSchema, it } = cxt;
        if (parentSchema.then === void 0 && parentSchema.else === void 0) {
          (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
        }
        const hasThen = hasSchema(it, "then");
        const hasElse = hasSchema(it, "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);
        }
        __name(validateIf, "validateIf");
        function validateClause(keyword, ifClause) {
          return () => {
            const schCxt = cxt.subschema({ keyword }, schValid);
            gen.assign(valid, schValid);
            cxt.mergeValidEvaluated(schCxt, valid);
            if (ifClause)
              gen.assign(ifClause, (0, codegen_1._)`${keyword}`);
            else
              cxt.setParams({ ifClause: keyword });
          };
        }
        __name(validateClause, "validateClause");
      }
    };
    function hasSchema(it, keyword) {
      const schema = it.schema[keyword];
      return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema);
    }
    __name(hasSchema, "hasSchema");
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/thenElse.js
var require_thenElse = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var util_1 = require_util9();
    var def2 = {
      keyword: ["then", "else"],
      schemaType: ["object", "boolean"],
      code({ keyword, parentSchema, it }) {
        if (parentSchema.if === void 0)
          (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/index.js
var require_applicator = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var additionalItems_1 = require_additionalItems();
    var prefixItems_1 = require_prefixItems();
    var items_1 = require_items();
    var items2020_1 = require_items2020();
    var contains_1 = require_contains();
    var dependencies_1 = require_dependencies();
    var propertyNames_1 = require_propertyNames();
    var additionalProperties_1 = require_additionalProperties();
    var properties_1 = require_properties();
    var patternProperties_1 = require_patternProperties();
    var not_1 = require_not();
    var anyOf_1 = require_anyOf();
    var oneOf_1 = require_oneOf();
    var allOf_1 = require_allOf();
    var if_1 = require_if();
    var thenElse_1 = require_thenElse();
    function getApplicator(draft2020 = false) {
      const applicator = [
        // 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)
        applicator.push(prefixItems_1.default, items2020_1.default);
      else
        applicator.push(additionalItems_1.default, items_1.default);
      applicator.push(contains_1.default);
      return applicator;
    }
    __name(getApplicator, "getApplicator");
    exports2.default = getApplicator;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/format/format.js
var require_format = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/format/format.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var error = {
      message: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, "message"),
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: "format",
      type: ["number", "string"],
      schemaType: "string",
      $data: true,
      error,
      code(cxt, ruleType) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        const { opts, errSchemaPath, schemaEnv, self: self2 } = it;
        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 format4 = gen.let("format");
          gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format4, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format4, 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} && !${format4}`;
          }
          __name(unknownFmt, "unknownFmt");
          function invalidFmt() {
            const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format4}(${data}) : ${format4}(${data}))` : (0, codegen_1._)`${format4}(${data})`;
            const validData = (0, codegen_1._)`(typeof ${format4} == "function" ? ${callFormat} : ${format4}.test(${data}))`;
            return (0, codegen_1._)`${format4} && ${format4} !== true && ${fType} === ${ruleType} && !${validData}`;
          }
          __name(invalidFmt, "invalidFmt");
        }
        __name(validate$DataFormat, "validate$DataFormat");
        function validateFormat() {
          const formatDef = self2.formats[schema];
          if (!formatDef) {
            unknownFormat();
            return;
          }
          if (formatDef === true)
            return;
          const [fmtType, format4, 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}"`;
            }
            __name(unknownMsg, "unknownMsg");
          }
          __name(unknownFormat, "unknownFormat");
          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];
          }
          __name(getFormat, "getFormat");
          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 format4 == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`;
          }
          __name(validCondition, "validCondition");
        }
        __name(validateFormat, "validateFormat");
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/format/index.js
var require_format2 = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/format/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var format_1 = require_format();
    var format4 = [format_1.default];
    exports2.default = format4;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/metadata.js
var require_metadata = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/metadata.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.contentVocabulary = exports2.metadataVocabulary = void 0;
    exports2.metadataVocabulary = [
      "title",
      "description",
      "default",
      "deprecated",
      "readOnly",
      "writeOnly",
      "examples"
    ];
    exports2.contentVocabulary = [
      "contentMediaType",
      "contentEncoding",
      "contentSchema"
    ];
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/draft7.js
var require_draft7 = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/draft7.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var core_1 = require_core2();
    var validation_1 = require_validation2();
    var applicator_1 = require_applicator();
    var format_1 = require_format2();
    var metadata_1 = require_metadata();
    var draft7Vocabularies = [
      core_1.default,
      validation_1.default,
      (0, applicator_1.default)(),
      format_1.default,
      metadata_1.metadataVocabulary,
      metadata_1.contentVocabulary
    ];
    exports2.default = draft7Vocabularies;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/discriminator/types.js
var require_types = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DiscrError = void 0;
    var DiscrError;
    (function(DiscrError2) {
      DiscrError2["Tag"] = "tag";
      DiscrError2["Mapping"] = "mapping";
    })(DiscrError || (exports2.DiscrError = DiscrError = {}));
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/discriminator/index.js
var require_discriminator = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var types_1 = require_types();
    var compile_1 = require_compile();
    var ref_error_1 = require_ref_error();
    var util_1 = require_util9();
    var error = {
      message: /* @__PURE__ */ __name(({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, "message"),
      params: /* @__PURE__ */ __name(({ params: { discrError, tag: tag2, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag2}}`, "params")
    };
    var def2 = {
      keyword: "discriminator",
      type: "object",
      schemaType: "object",
      error,
      code(cxt) {
        const { gen, data, schema, parentSchema, it } = cxt;
        const { oneOf } = parentSchema;
        if (!it.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 (!oneOf)
          throw new Error("discriminator: requires oneOf keyword");
        const valid = gen.let("valid", false);
        const tag2 = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`);
        gen.if((0, codegen_1._)`typeof ${tag2} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag: tag2, tagName }));
        cxt.ok(valid);
        function validateMapping() {
          const mapping = getMapping();
          gen.if(false);
          for (const tagValue in mapping) {
            gen.elseIf((0, codegen_1._)`${tag2} === ${tagValue}`);
            gen.assign(valid, applyTagSchema(mapping[tagValue]));
          }
          gen.else();
          cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag: tag2, tagName });
          gen.endIf();
        }
        __name(validateMapping, "validateMapping");
        function applyTagSchema(schemaProp) {
          const _valid = gen.name("valid");
          const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
          cxt.mergeEvaluated(schCxt, codegen_1.Name);
          return _valid;
        }
        __name(applyTagSchema, "applyTagSchema");
        function getMapping() {
          var _a6;
          const oneOfMapping = {};
          const topRequired = hasRequired(parentSchema);
          let tagRequired = true;
          for (let i = 0; i < oneOf.length; i++) {
            let sch = oneOf[i];
            if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
              const ref = sch.$ref;
              sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);
              if (sch instanceof compile_1.SchemaEnv)
                sch = sch.schema;
              if (sch === void 0)
                throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
            }
            const propSch = (_a6 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a6 === void 0 ? void 0 : _a6[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, i);
          }
          if (!tagRequired)
            throw new Error(`discriminator: "${tagName}" must be required`);
          return oneOfMapping;
          function hasRequired({ required }) {
            return Array.isArray(required) && required.includes(tagName);
          }
          __name(hasRequired, "hasRequired");
          function addMappings(sch, i) {
            if (sch.const) {
              addMapping(sch.const, i);
            } else if (sch.enum) {
              for (const tagValue of sch.enum) {
                addMapping(tagValue, i);
              }
            } else {
              throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
            }
          }
          __name(addMappings, "addMappings");
          function addMapping(tagValue, i) {
            if (typeof tagValue != "string" || tagValue in oneOfMapping) {
              throw new Error(`discriminator: "${tagName}" values must be unique strings`);
            }
            oneOfMapping[tagValue] = i;
          }
          __name(addMapping, "addMapping");
        }
        __name(getMapping, "getMapping");
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/refs/json-schema-draft-07.json
var require_json_schema_draft_07 = __commonJS({
  "packages/core/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports2, module2) {
    module2.exports = {
      $schema: "http://json-schema.org/draft-07/schema#",
      $id: "http://json-schema.org/draft-07/schema#",
      title: "Core schema meta-schema",
      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: []
        }
      },
      type: ["object", "boolean"],
      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: "#" }
      },
      default: true
    };
  }
});

// packages/core/node_modules/ajv/dist/ajv.js
var require_ajv = __commonJS({
  "packages/core/node_modules/ajv/dist/ajv.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MissingRefError = exports2.ValidationError = exports2.CodeGen = exports2.Name = exports2.nil = exports2.stringify = exports2.str = exports2._ = exports2.KeywordCxt = exports2.Ajv = void 0;
    var core_1 = require_core();
    var draft7_1 = require_draft7();
    var discriminator_1 = require_discriminator();
    var draft7MetaSchema = require_json_schema_draft_07();
    var META_SUPPORT_DATA = ["/properties"];
    var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
    var Ajv2 = class extends core_1.default {
      static {
        __name(this, "Ajv");
      }
      _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);
      }
    };
    exports2.Ajv = Ajv2;
    module2.exports = exports2 = Ajv2;
    module2.exports.Ajv = Ajv2;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.default = Ajv2;
    var validate_1 = require_validate();
    Object.defineProperty(exports2, "KeywordCxt", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return validate_1.KeywordCxt;
    }, "get") });
    var codegen_1 = require_codegen();
    Object.defineProperty(exports2, "_", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1._;
    }, "get") });
    Object.defineProperty(exports2, "str", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.str;
    }, "get") });
    Object.defineProperty(exports2, "stringify", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.stringify;
    }, "get") });
    Object.defineProperty(exports2, "nil", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.nil;
    }, "get") });
    Object.defineProperty(exports2, "Name", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.Name;
    }, "get") });
    Object.defineProperty(exports2, "CodeGen", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.CodeGen;
    }, "get") });
    var validation_error_1 = require_validation_error();
    Object.defineProperty(exports2, "ValidationError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return validation_error_1.default;
    }, "get") });
    var ref_error_1 = require_ref_error();
    Object.defineProperty(exports2, "MissingRefError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ref_error_1.default;
    }, "get") });
  }
});

// node_modules/ajv-formats/dist/formats.js
var require_formats = __commonJS({
  "node_modules/ajv-formats/dist/formats.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.formatNames = exports2.fastFormats = exports2.fullFormats = void 0;
    function fmtDef(validate4, compare) {
      return { validate: validate4, compare };
    }
    __name(fmtDef, "fmtDef");
    exports2.fullFormats = {
      // date: http://tools.ietf.org/html/rfc3339#section-5.6
      date: fmtDef(date, 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,
      "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: regex3,
      // 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
    };
    exports2.fastFormats = {
      ...exports2.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
    };
    exports2.formatNames = Object.keys(exports2.fullFormats);
    function isLeapYear(year) {
      return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    }
    __name(isLeapYear, "isLeapYear");
    var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
    var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    function date(str2) {
      const matches = DATE.exec(str2);
      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]);
    }
    __name(date, "date");
    function compareDate(d1, d2) {
      if (!(d1 && d2))
        return void 0;
      if (d1 > d2)
        return 1;
      if (d1 < d2)
        return -1;
      return 0;
    }
    __name(compareDate, "compareDate");
    var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;
    function getTime(strictTimeZone) {
      return /* @__PURE__ */ __name(function time(str2) {
        const matches = TIME.exec(str2);
        if (!matches)
          return false;
        const hr2 = +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 (hr2 <= 23 && min <= 59 && sec < 60)
          return true;
        const utcMin = min - tzM * tzSign;
        const utcHr = hr2 - tzH * tzSign - (utcMin < 0 ? 1 : 0);
        return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61;
      }, "time");
    }
    __name(getTime, "getTime");
    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;
    }
    __name(compareTime, "compareTime");
    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;
    }
    __name(compareIsoTime, "compareIsoTime");
    var DATE_TIME_SEPARATOR = /t|\s/i;
    function getDateTime(strictTimeZone) {
      const time = getTime(strictTimeZone);
      return /* @__PURE__ */ __name(function date_time(str2) {
        const dateTime = str2.split(DATE_TIME_SEPARATOR);
        return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]);
      }, "date_time");
    }
    __name(getDateTime, "getDateTime");
    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;
    }
    __name(compareDateTime, "compareDateTime");
    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);
    }
    __name(compareIsoDateTime, "compareIsoDateTime");
    var NOT_URI_FRAGMENT = /\/|:/;
    var 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 uri(str2) {
      return NOT_URI_FRAGMENT.test(str2) && URI.test(str2);
    }
    __name(uri, "uri");
    var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;
    function byte(str2) {
      BYTE.lastIndex = 0;
      return BYTE.test(str2);
    }
    __name(byte, "byte");
    var MIN_INT32 = -(2 ** 31);
    var MAX_INT32 = 2 ** 31 - 1;
    function validateInt32(value) {
      return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;
    }
    __name(validateInt32, "validateInt32");
    function validateInt64(value) {
      return Number.isInteger(value);
    }
    __name(validateInt64, "validateInt64");
    function validateNumber() {
      return true;
    }
    __name(validateNumber, "validateNumber");
    var Z_ANCHOR = /[^\\]\\Z/;
    function regex3(str2) {
      if (Z_ANCHOR.test(str2))
        return false;
      try {
        new RegExp(str2);
        return true;
      } catch (e2) {
        return false;
      }
    }
    __name(regex3, "regex");
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/code.js
var require_code3 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/code.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.regexpCode = exports2.getEsmExportName = exports2.getProperty = exports2.safeStringify = exports2.stringify = exports2.strConcat = exports2.addCodeArg = exports2.str = exports2._ = exports2.nil = exports2._Code = exports2.Name = exports2.IDENTIFIER = exports2._CodeOrName = void 0;
    var _CodeOrName = class {
      static {
        __name(this, "_CodeOrName");
      }
    };
    exports2._CodeOrName = _CodeOrName;
    exports2.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
    var Name = class extends _CodeOrName {
      static {
        __name(this, "Name");
      }
      constructor(s2) {
        super();
        if (!exports2.IDENTIFIER.test(s2))
          throw new Error("CodeGen: name must be a valid identifier");
        this.str = s2;
      }
      toString() {
        return this.str;
      }
      emptyStr() {
        return false;
      }
      get names() {
        return { [this.str]: 1 };
      }
    };
    exports2.Name = Name;
    var _Code = class extends _CodeOrName {
      static {
        __name(this, "_Code");
      }
      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 _a6;
        return (_a6 = this._str) !== null && _a6 !== void 0 ? _a6 : this._str = this._items.reduce((s2, c3) => `${s2}${c3}`, "");
      }
      get names() {
        var _a6;
        return (_a6 = this._names) !== null && _a6 !== void 0 ? _a6 : this._names = this._items.reduce((names, c3) => {
          if (c3 instanceof Name)
            names[c3.str] = (names[c3.str] || 0) + 1;
          return names;
        }, {});
      }
    };
    exports2._Code = _Code;
    exports2.nil = new _Code("");
    function _(strs, ...args) {
      const code2 = [strs[0]];
      let i = 0;
      while (i < args.length) {
        addCodeArg(code2, args[i]);
        code2.push(strs[++i]);
      }
      return new _Code(code2);
    }
    __name(_, "_");
    exports2._ = _;
    var plus = new _Code("+");
    function str2(strs, ...args) {
      const expr = [safeStringify(strs[0])];
      let i = 0;
      while (i < args.length) {
        expr.push(plus);
        addCodeArg(expr, args[i]);
        expr.push(plus, safeStringify(strs[++i]));
      }
      optimize(expr);
      return new _Code(expr);
    }
    __name(str2, "str");
    exports2.str = str2;
    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));
    }
    __name(addCodeArg, "addCodeArg");
    exports2.addCodeArg = addCodeArg;
    function optimize(expr) {
      let i = 1;
      while (i < expr.length - 1) {
        if (expr[i] === plus) {
          const res = mergeExprItems(expr[i - 1], expr[i + 1]);
          if (res !== void 0) {
            expr.splice(i - 1, 3, res);
            continue;
          }
          expr[i++] = "+";
        }
        i++;
      }
    }
    __name(optimize, "optimize");
    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;
    }
    __name(mergeExprItems, "mergeExprItems");
    function strConcat(c1, c22) {
      return c22.emptyStr() ? c1 : c1.emptyStr() ? c22 : str2`${c1}${c22}`;
    }
    __name(strConcat, "strConcat");
    exports2.strConcat = strConcat;
    function interpolate(x) {
      return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x);
    }
    __name(interpolate, "interpolate");
    function stringify5(x) {
      return new _Code(safeStringify(x));
    }
    __name(stringify5, "stringify");
    exports2.stringify = stringify5;
    function safeStringify(x) {
      return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
    }
    __name(safeStringify, "safeStringify");
    exports2.safeStringify = safeStringify;
    function getProperty2(key) {
      return typeof key == "string" && exports2.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`;
    }
    __name(getProperty2, "getProperty");
    exports2.getProperty = getProperty2;
    function getEsmExportName(key) {
      if (typeof key == "string" && exports2.IDENTIFIER.test(key)) {
        return new _Code(`${key}`);
      }
      throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
    }
    __name(getEsmExportName, "getEsmExportName");
    exports2.getEsmExportName = getEsmExportName;
    function regexpCode(rx) {
      return new _Code(rx.toString());
    }
    __name(regexpCode, "regexpCode");
    exports2.regexpCode = regexpCode;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/scope.js
var require_scope2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/scope.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ValueScope = exports2.ValueScopeName = exports2.Scope = exports2.varKinds = exports2.UsedValueState = void 0;
    var code_1 = require_code3();
    var ValueError = class extends Error {
      static {
        __name(this, "ValueError");
      }
      constructor(name3) {
        super(`CodeGen: "code" for ${name3} not defined`);
        this.value = name3.value;
      }
    };
    var UsedValueState;
    (function(UsedValueState2) {
      UsedValueState2[UsedValueState2["Started"] = 0] = "Started";
      UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed";
    })(UsedValueState || (exports2.UsedValueState = UsedValueState = {}));
    exports2.varKinds = {
      const: new code_1.Name("const"),
      let: new code_1.Name("let"),
      var: new code_1.Name("var")
    };
    var Scope = class {
      static {
        __name(this, "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 _a6, _b2;
        if (((_b2 = (_a6 = this._parent) === null || _a6 === void 0 ? void 0 : _a6._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 };
      }
    };
    exports2.Scope = Scope;
    var ValueScopeName = class extends code_1.Name {
      static {
        __name(this, "ValueScopeName");
      }
      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}]`;
      }
    };
    exports2.ValueScopeName = ValueScopeName;
    var line = (0, code_1._)`\n`;
    var ValueScope = class extends Scope {
      static {
        __name(this, "ValueScope");
      }
      constructor(opts) {
        super(opts);
        this._values = {};
        this._scope = opts.scope;
        this.opts = { ...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 _a6;
        if (value.ref === void 0)
          throw new Error("CodeGen: ref must be passed in value");
        const name3 = this.toName(nameOrPrefix);
        const { prefix } = name3;
        const valueKey = (_a6 = value.key) !== null && _a6 !== void 0 ? _a6 : 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, name3);
        const s2 = this._scope[prefix] || (this._scope[prefix] = []);
        const itemIndex = s2.length;
        s2[itemIndex] = value.ref;
        name3.setValue(value, { property: prefix, itemIndex });
        return name3;
      }
      getValue(prefix, keyOrRef) {
        const vs = this._values[prefix];
        if (!vs)
          return;
        return vs.get(keyOrRef);
      }
      scopeRefs(scopeName, values = this._values) {
        return this._reduceValues(values, (name3) => {
          if (name3.scopePath === void 0)
            throw new Error(`CodeGen: name "${name3}" has no value`);
          return (0, code_1._)`${scopeName}${name3.scopePath}`;
        });
      }
      scopeCode(values = this._values, usedValues, getCode) {
        return this._reduceValues(values, (name3) => {
          if (name3.value === void 0)
            throw new Error(`CodeGen: name "${name3}" has no value`);
          return name3.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((name3) => {
            if (nameSet.has(name3))
              return;
            nameSet.set(name3, UsedValueState.Started);
            let c3 = valueCode(name3);
            if (c3) {
              const def2 = this.opts.es5 ? exports2.varKinds.var : exports2.varKinds.const;
              code2 = (0, code_1._)`${code2}${def2} ${name3} = ${c3};${this.opts._n}`;
            } else if (c3 = getCode === null || getCode === void 0 ? void 0 : getCode(name3)) {
              code2 = (0, code_1._)`${code2}${c3}${this.opts._n}`;
            } else {
              throw new ValueError(name3);
            }
            nameSet.set(name3, UsedValueState.Completed);
          });
        }
        return code2;
      }
    };
    exports2.ValueScope = ValueScope;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/index.js
var require_codegen2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.or = exports2.and = exports2.not = exports2.CodeGen = exports2.operators = exports2.varKinds = exports2.ValueScopeName = exports2.ValueScope = exports2.Scope = exports2.Name = exports2.regexpCode = exports2.stringify = exports2.getProperty = exports2.nil = exports2.strConcat = exports2.str = exports2._ = void 0;
    var code_1 = require_code3();
    var scope_1 = require_scope2();
    var code_2 = require_code3();
    Object.defineProperty(exports2, "_", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return code_2._;
    }, "get") });
    Object.defineProperty(exports2, "str", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return code_2.str;
    }, "get") });
    Object.defineProperty(exports2, "strConcat", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return code_2.strConcat;
    }, "get") });
    Object.defineProperty(exports2, "nil", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return code_2.nil;
    }, "get") });
    Object.defineProperty(exports2, "getProperty", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return code_2.getProperty;
    }, "get") });
    Object.defineProperty(exports2, "stringify", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return code_2.stringify;
    }, "get") });
    Object.defineProperty(exports2, "regexpCode", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return code_2.regexpCode;
    }, "get") });
    Object.defineProperty(exports2, "Name", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return code_2.Name;
    }, "get") });
    var scope_2 = require_scope2();
    Object.defineProperty(exports2, "Scope", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return scope_2.Scope;
    }, "get") });
    Object.defineProperty(exports2, "ValueScope", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return scope_2.ValueScope;
    }, "get") });
    Object.defineProperty(exports2, "ValueScopeName", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return scope_2.ValueScopeName;
    }, "get") });
    Object.defineProperty(exports2, "varKinds", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return scope_2.varKinds;
    }, "get") });
    exports2.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("+")
    };
    var Node4 = class {
      static {
        __name(this, "Node");
      }
      optimizeNodes() {
        return this;
      }
      optimizeNames(_names, _constants) {
        return this;
      }
    };
    var Def = class extends Node4 {
      static {
        __name(this, "Def");
      }
      constructor(varKind, name3, rhs) {
        super();
        this.varKind = varKind;
        this.name = name3;
        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(names, constants4) {
        if (!names[this.name.str])
          return;
        if (this.rhs)
          this.rhs = optimizeExpr(this.rhs, names, constants4);
        return this;
      }
      get names() {
        return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
      }
    };
    var Assign = class extends Node4 {
      static {
        __name(this, "Assign");
      }
      constructor(lhs, rhs, sideEffects) {
        super();
        this.lhs = lhs;
        this.rhs = rhs;
        this.sideEffects = sideEffects;
      }
      render({ _n }) {
        return `${this.lhs} = ${this.rhs};` + _n;
      }
      optimizeNames(names, constants4) {
        if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
          return;
        this.rhs = optimizeExpr(this.rhs, names, constants4);
        return this;
      }
      get names() {
        const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
        return addExprNames(names, this.rhs);
      }
    };
    var AssignOp = class extends Assign {
      static {
        __name(this, "AssignOp");
      }
      constructor(lhs, op, rhs, sideEffects) {
        super(lhs, rhs, sideEffects);
        this.op = op;
      }
      render({ _n }) {
        return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
      }
    };
    var Label = class extends Node4 {
      static {
        __name(this, "Label");
      }
      constructor(label) {
        super();
        this.label = label;
        this.names = {};
      }
      render({ _n }) {
        return `${this.label}:` + _n;
      }
    };
    var Break = class extends Node4 {
      static {
        __name(this, "Break");
      }
      constructor(label) {
        super();
        this.label = label;
        this.names = {};
      }
      render({ _n }) {
        const label = this.label ? ` ${this.label}` : "";
        return `break${label};` + _n;
      }
    };
    var Throw = class extends Node4 {
      static {
        __name(this, "Throw");
      }
      constructor(error) {
        super();
        this.error = error;
      }
      render({ _n }) {
        return `throw ${this.error};` + _n;
      }
      get names() {
        return this.error.names;
      }
    };
    var AnyCode = class extends Node4 {
      static {
        __name(this, "AnyCode");
      }
      constructor(code2) {
        super();
        this.code = code2;
      }
      render({ _n }) {
        return `${this.code};` + _n;
      }
      optimizeNodes() {
        return `${this.code}` ? this : void 0;
      }
      optimizeNames(names, constants4) {
        this.code = optimizeExpr(this.code, names, constants4);
        return this;
      }
      get names() {
        return this.code instanceof code_1._CodeOrName ? this.code.names : {};
      }
    };
    var ParentNode = class extends Node4 {
      static {
        __name(this, "ParentNode");
      }
      constructor(nodes = []) {
        super();
        this.nodes = nodes;
      }
      render(opts) {
        return this.nodes.reduce((code2, n2) => code2 + n2.render(opts), "");
      }
      optimizeNodes() {
        const { nodes } = this;
        let i = nodes.length;
        while (i--) {
          const n2 = nodes[i].optimizeNodes();
          if (Array.isArray(n2))
            nodes.splice(i, 1, ...n2);
          else if (n2)
            nodes[i] = n2;
          else
            nodes.splice(i, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      optimizeNames(names, constants4) {
        const { nodes } = this;
        let i = nodes.length;
        while (i--) {
          const n2 = nodes[i];
          if (n2.optimizeNames(names, constants4))
            continue;
          subtractNames(names, n2.names);
          nodes.splice(i, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      get names() {
        return this.nodes.reduce((names, n2) => addNames(names, n2.names), {});
      }
    };
    var BlockNode = class extends ParentNode {
      static {
        __name(this, "BlockNode");
      }
      render(opts) {
        return "{" + opts._n + super.render(opts) + "}" + opts._n;
      }
    };
    var Root2 = class extends ParentNode {
      static {
        __name(this, "Root");
      }
    };
    var Else = class extends BlockNode {
      static {
        __name(this, "Else");
      }
    };
    Else.kind = "else";
    var If = class _If extends BlockNode {
      static {
        __name(this, "If");
      }
      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 e2 = this.else;
        if (e2) {
          const ns = e2.optimizeNodes();
          e2 = this.else = Array.isArray(ns) ? new Else(ns) : ns;
        }
        if (e2) {
          if (cond === false)
            return e2 instanceof _If ? e2 : e2.nodes;
          if (this.nodes.length)
            return this;
          return new _If(not(cond), e2 instanceof _If ? [e2] : e2.nodes);
        }
        if (cond === false || !this.nodes.length)
          return void 0;
        return this;
      }
      optimizeNames(names, constants4) {
        var _a6;
        this.else = (_a6 = this.else) === null || _a6 === void 0 ? void 0 : _a6.optimizeNames(names, constants4);
        if (!(super.optimizeNames(names, constants4) || this.else))
          return;
        this.condition = optimizeExpr(this.condition, names, constants4);
        return this;
      }
      get names() {
        const names = super.names;
        addExprNames(names, this.condition);
        if (this.else)
          addNames(names, this.else.names);
        return names;
      }
    };
    If.kind = "if";
    var For = class extends BlockNode {
      static {
        __name(this, "For");
      }
    };
    For.kind = "for";
    var ForLoop = class extends For {
      static {
        __name(this, "ForLoop");
      }
      constructor(iteration) {
        super();
        this.iteration = iteration;
      }
      render(opts) {
        return `for(${this.iteration})` + super.render(opts);
      }
      optimizeNames(names, constants4) {
        if (!super.optimizeNames(names, constants4))
          return;
        this.iteration = optimizeExpr(this.iteration, names, constants4);
        return this;
      }
      get names() {
        return addNames(super.names, this.iteration.names);
      }
    };
    var ForRange = class extends For {
      static {
        __name(this, "ForRange");
      }
      constructor(varKind, name3, from, to) {
        super();
        this.varKind = varKind;
        this.name = name3;
        this.from = from;
        this.to = to;
      }
      render(opts) {
        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
        const { name: name3, from, to } = this;
        return `for(${varKind} ${name3}=${from}; ${name3}<${to}; ${name3}++)` + super.render(opts);
      }
      get names() {
        const names = addExprNames(super.names, this.from);
        return addExprNames(names, this.to);
      }
    };
    var ForIter = class extends For {
      static {
        __name(this, "ForIter");
      }
      constructor(loop, varKind, name3, iterable) {
        super();
        this.loop = loop;
        this.varKind = varKind;
        this.name = name3;
        this.iterable = iterable;
      }
      render(opts) {
        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
      }
      optimizeNames(names, constants4) {
        if (!super.optimizeNames(names, constants4))
          return;
        this.iterable = optimizeExpr(this.iterable, names, constants4);
        return this;
      }
      get names() {
        return addNames(super.names, this.iterable.names);
      }
    };
    var Func = class extends BlockNode {
      static {
        __name(this, "Func");
      }
      constructor(name3, args, async) {
        super();
        this.name = name3;
        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";
    var Return = class extends ParentNode {
      static {
        __name(this, "Return");
      }
      render(opts) {
        return "return " + super.render(opts);
      }
    };
    Return.kind = "return";
    var Try = class extends BlockNode {
      static {
        __name(this, "Try");
      }
      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 _a6, _b2;
        super.optimizeNodes();
        (_a6 = this.catch) === null || _a6 === void 0 ? void 0 : _a6.optimizeNodes();
        (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNodes();
        return this;
      }
      optimizeNames(names, constants4) {
        var _a6, _b2;
        super.optimizeNames(names, constants4);
        (_a6 = this.catch) === null || _a6 === void 0 ? void 0 : _a6.optimizeNames(names, constants4);
        (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNames(names, constants4);
        return this;
      }
      get names() {
        const names = super.names;
        if (this.catch)
          addNames(names, this.catch.names);
        if (this.finally)
          addNames(names, this.finally.names);
        return names;
      }
    };
    var Catch = class extends BlockNode {
      static {
        __name(this, "Catch");
      }
      constructor(error) {
        super();
        this.error = error;
      }
      render(opts) {
        return `catch(${this.error})` + super.render(opts);
      }
    };
    Catch.kind = "catch";
    var Finally = class extends BlockNode {
      static {
        __name(this, "Finally");
      }
      render(opts) {
        return "finally" + super.render(opts);
      }
    };
    Finally.kind = "finally";
    var CodeGen = class {
      static {
        __name(this, "CodeGen");
      }
      constructor(extScope, opts = {}) {
        this._values = {};
        this._blockStarts = [];
        this._constants = {};
        this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
        this._extScope = extScope;
        this._scope = new scope_1.Scope({ parent: extScope });
        this._nodes = [new Root2()];
      }
      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 name3 = this._extScope.value(prefixOrName, value);
        const vs = this._values[name3.prefix] || (this._values[name3.prefix] = /* @__PURE__ */ new Set());
        vs.add(name3);
        return name3;
      }
      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 name3 = this._scope.toName(nameOrPrefix);
        if (rhs !== void 0 && constant)
          this._constants[name3.str] = rhs;
        this._leafNode(new Def(varKind, name3, rhs));
        return name3;
      }
      // `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, exports2.operators.ADD, rhs));
      }
      // appends passed SafeExpr to code or executes Block
      code(c3) {
        if (typeof c3 == "function")
          c3();
        else if (c3 !== code_1.nil)
          this._leafNode(new AnyCode(c3));
        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 name3 = this._scope.toName(nameOrPrefix);
        return this._for(new ForRange(varKind, name3, from, to), () => forBody(name3));
      }
      // `for-of` statement (in es5 mode replace with a normal for loop)
      forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
        const name3 = 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`, (i) => {
            this.var(name3, (0, code_1._)`${arr}[${i}]`);
            forBody(name3);
          });
        }
        return this._for(new ForIter("of", varKind, name3, iterable), () => forBody(name3));
      }
      // `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 name3 = this._scope.toName(nameOrPrefix);
        return this._for(new ForIter("in", varKind, name3, obj), () => forBody(name3));
      }
      // 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 error = this.name("e");
          this._currNode = node.catch = new Catch(error);
          catchCode(error);
        }
        if (finallyCode) {
          this._currNode = node.finally = new Finally();
          this.code(finallyCode);
        }
        return this._endBlockNode(Catch, Finally);
      }
      // `throw` statement
      throw(error) {
        return this._leafNode(new Throw(error));
      }
      // 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 len = this._blockStarts.pop();
        if (len === void 0)
          throw new Error("CodeGen: not in self-balancing block");
        const toClose = this._nodes.length - len;
        if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) {
          throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
        }
        this._nodes.length = len;
        return this;
      }
      // `function` heading (or definition if funcBody is passed)
      func(name3, args = code_1.nil, async, funcBody) {
        this._blockNode(new Func(name3, args, async));
        if (funcBody)
          this.code(funcBody).endFunc();
        return this;
      }
      // end function definition
      endFunc() {
        return this._endBlockNode(Func);
      }
      optimize(n2 = 1) {
        while (n2-- > 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 n2 = this._currNode;
        if (n2 instanceof N1 || N2 && n2 instanceof N2) {
          this._nodes.pop();
          return this;
        }
        throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
      }
      _elseNode(node) {
        const n2 = this._currNode;
        if (!(n2 instanceof If)) {
          throw new Error('CodeGen: "else" without "if"');
        }
        this._currNode = n2.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;
      }
    };
    exports2.CodeGen = CodeGen;
    function addNames(names, from) {
      for (const n2 in from)
        names[n2] = (names[n2] || 0) + (from[n2] || 0);
      return names;
    }
    __name(addNames, "addNames");
    function addExprNames(names, from) {
      return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
    }
    __name(addExprNames, "addExprNames");
    function optimizeExpr(expr, names, constants4) {
      if (expr instanceof code_1.Name)
        return replaceName(expr);
      if (!canOptimize(expr))
        return expr;
      return new code_1._Code(expr._items.reduce((items, c3) => {
        if (c3 instanceof code_1.Name)
          c3 = replaceName(c3);
        if (c3 instanceof code_1._Code)
          items.push(...c3._items);
        else
          items.push(c3);
        return items;
      }, []));
      function replaceName(n2) {
        const c3 = constants4[n2.str];
        if (c3 === void 0 || names[n2.str] !== 1)
          return n2;
        delete names[n2.str];
        return c3;
      }
      __name(replaceName, "replaceName");
      function canOptimize(e2) {
        return e2 instanceof code_1._Code && e2._items.some((c3) => c3 instanceof code_1.Name && names[c3.str] === 1 && constants4[c3.str] !== void 0);
      }
      __name(canOptimize, "canOptimize");
    }
    __name(optimizeExpr, "optimizeExpr");
    function subtractNames(names, from) {
      for (const n2 in from)
        names[n2] = (names[n2] || 0) - (from[n2] || 0);
    }
    __name(subtractNames, "subtractNames");
    function not(x) {
      return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`;
    }
    __name(not, "not");
    exports2.not = not;
    var andCode = mappend(exports2.operators.AND);
    function and(...args) {
      return args.reduce(andCode);
    }
    __name(and, "and");
    exports2.and = and;
    var orCode = mappend(exports2.operators.OR);
    function or(...args) {
      return args.reduce(orCode);
    }
    __name(or, "or");
    exports2.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)}`;
    }
    __name(mappend, "mappend");
    function par(x) {
      return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`;
    }
    __name(par, "par");
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/util.js
var require_util10 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/util.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.checkStrictMode = exports2.getErrorPath = exports2.Type = exports2.useFunc = exports2.setEvaluated = exports2.evaluatedPropsToName = exports2.mergeEvaluated = exports2.eachItem = exports2.unescapeJsonPointer = exports2.escapeJsonPointer = exports2.escapeFragment = exports2.unescapeFragment = exports2.schemaRefOrVal = exports2.schemaHasRulesButRef = exports2.schemaHasRules = exports2.checkUnknownRules = exports2.alwaysValidSchema = exports2.toHash = void 0;
    var codegen_1 = require_codegen2();
    var code_1 = require_code3();
    function toHash(arr) {
      const hash = {};
      for (const item of arr)
        hash[item] = true;
      return hash;
    }
    __name(toHash, "toHash");
    exports2.toHash = toHash;
    function alwaysValidSchema(it, schema) {
      if (typeof schema == "boolean")
        return schema;
      if (Object.keys(schema).length === 0)
        return true;
      checkUnknownRules(it, schema);
      return !schemaHasRules(schema, it.self.RULES.all);
    }
    __name(alwaysValidSchema, "alwaysValidSchema");
    exports2.alwaysValidSchema = alwaysValidSchema;
    function checkUnknownRules(it, schema = it.schema) {
      const { opts, self: self2 } = it;
      if (!opts.strictSchema)
        return;
      if (typeof schema === "boolean")
        return;
      const rules = self2.RULES.keywords;
      for (const key in schema) {
        if (!rules[key])
          checkStrictMode(it, `unknown keyword: "${key}"`);
      }
    }
    __name(checkUnknownRules, "checkUnknownRules");
    exports2.checkUnknownRules = checkUnknownRules;
    function schemaHasRules(schema, rules) {
      if (typeof schema == "boolean")
        return !schema;
      for (const key in schema)
        if (rules[key])
          return true;
      return false;
    }
    __name(schemaHasRules, "schemaHasRules");
    exports2.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;
    }
    __name(schemaHasRulesButRef, "schemaHasRulesButRef");
    exports2.schemaHasRulesButRef = schemaHasRulesButRef;
    function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $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)(keyword)}`;
    }
    __name(schemaRefOrVal, "schemaRefOrVal");
    exports2.schemaRefOrVal = schemaRefOrVal;
    function unescapeFragment(str2) {
      return unescapeJsonPointer(decodeURIComponent(str2));
    }
    __name(unescapeFragment, "unescapeFragment");
    exports2.unescapeFragment = unescapeFragment;
    function escapeFragment(str2) {
      return encodeURIComponent(escapeJsonPointer(str2));
    }
    __name(escapeFragment, "escapeFragment");
    exports2.escapeFragment = escapeFragment;
    function escapeJsonPointer(str2) {
      if (typeof str2 == "number")
        return `${str2}`;
      return str2.replace(/~/g, "~0").replace(/\//g, "~1");
    }
    __name(escapeJsonPointer, "escapeJsonPointer");
    exports2.escapeJsonPointer = escapeJsonPointer;
    function unescapeJsonPointer(str2) {
      return str2.replace(/~1/g, "/").replace(/~0/g, "~");
    }
    __name(unescapeJsonPointer, "unescapeJsonPointer");
    exports2.unescapeJsonPointer = unescapeJsonPointer;
    function eachItem(xs, f) {
      if (Array.isArray(xs)) {
        for (const x of xs)
          f(x);
      } else {
        f(xs);
      }
    }
    __name(eachItem, "eachItem");
    exports2.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;
      };
    }
    __name(makeMergeEvaluated, "makeMergeEvaluated");
    exports2.mergeEvaluated = {
      props: makeMergeEvaluated({
        mergeNames: /* @__PURE__ */ __name((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})`));
        }), "mergeNames"),
        mergeToName: /* @__PURE__ */ __name((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);
          }
        }), "mergeToName"),
        mergeValues: /* @__PURE__ */ __name((from, to) => from === true ? true : { ...from, ...to }, "mergeValues"),
        resultToName: evaluatedPropsToName
      }),
      items: makeMergeEvaluated({
        mergeNames: /* @__PURE__ */ __name((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}`)), "mergeNames"),
        mergeToName: /* @__PURE__ */ __name((gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), "mergeToName"),
        mergeValues: /* @__PURE__ */ __name((from, to) => from === true ? true : Math.max(from, to), "mergeValues"),
        resultToName: /* @__PURE__ */ __name((gen, items) => gen.var("items", items), "resultToName")
      })
    };
    function evaluatedPropsToName(gen, ps) {
      if (ps === true)
        return gen.var("props", true);
      const props = gen.var("props", (0, codegen_1._)`{}`);
      if (ps !== void 0)
        setEvaluated(gen, props, ps);
      return props;
    }
    __name(evaluatedPropsToName, "evaluatedPropsToName");
    exports2.evaluatedPropsToName = evaluatedPropsToName;
    function setEvaluated(gen, props, ps) {
      Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true));
    }
    __name(setEvaluated, "setEvaluated");
    exports2.setEvaluated = setEvaluated;
    var snippets = {};
    function useFunc(gen, f) {
      return gen.scopeValue("func", {
        ref: f,
        code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code))
      });
    }
    __name(useFunc, "useFunc");
    exports2.useFunc = useFunc;
    var Type2;
    (function(Type3) {
      Type3[Type3["Num"] = 0] = "Num";
      Type3[Type3["Str"] = 1] = "Str";
    })(Type2 || (exports2.Type = Type2 = {}));
    function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
      if (dataProp instanceof codegen_1.Name) {
        const isNumber3 = dataPropType === Type2.Num;
        return jsPropertySyntax ? isNumber3 ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber3 ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`;
      }
      return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
    }
    __name(getErrorPath, "getErrorPath");
    exports2.getErrorPath = getErrorPath;
    function checkStrictMode(it, msg, mode = it.opts.strictSchema) {
      if (!mode)
        return;
      msg = `strict mode: ${msg}`;
      if (mode === true)
        throw new Error(msg);
      it.self.logger.warn(msg);
    }
    __name(checkStrictMode, "checkStrictMode");
    exports2.checkStrictMode = checkStrictMode;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/names.js
var require_names2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/names.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var names = {
      // 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")
    };
    exports2.default = names;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/errors.js
var require_errors3 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/errors.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.extendErrors = exports2.resetErrorsCount = exports2.reportExtraError = exports2.reportError = exports2.keyword$DataError = exports2.keywordError = void 0;
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var names_1 = require_names2();
    exports2.keywordError = {
      message: /* @__PURE__ */ __name(({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation`, "message")
    };
    exports2.keyword$DataError = {
      message: /* @__PURE__ */ __name(({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)`, "message")
    };
    function reportError3(cxt, error = exports2.keywordError, errorPaths, overrideAllErrors) {
      const { it } = cxt;
      const { gen, compositeRule, allErrors } = it;
      const errObj = errorObjectCode(cxt, error, errorPaths);
      if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) {
        addError(gen, errObj);
      } else {
        returnErrors(it, (0, codegen_1._)`[${errObj}]`);
      }
    }
    __name(reportError3, "reportError");
    exports2.reportError = reportError3;
    function reportExtraError(cxt, error = exports2.keywordError, errorPaths) {
      const { it } = cxt;
      const { gen, compositeRule, allErrors } = it;
      const errObj = errorObjectCode(cxt, error, errorPaths);
      addError(gen, errObj);
      if (!(compositeRule || allErrors)) {
        returnErrors(it, names_1.default.vErrors);
      }
    }
    __name(reportExtraError, "reportExtraError");
    exports2.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)));
    }
    __name(resetErrorsCount, "resetErrorsCount");
    exports2.resetErrorsCount = resetErrorsCount;
    function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) {
      if (errsCount === void 0)
        throw new Error("ajv implementation error");
      const err = gen.name("err");
      gen.forRange("i", errsCount, names_1.default.errors, (i) => {
        gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`);
        gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
        gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`);
        if (it.opts.verbose) {
          gen.assign((0, codegen_1._)`${err}.schema`, schemaValue);
          gen.assign((0, codegen_1._)`${err}.data`, data);
        }
      });
    }
    __name(extendErrors, "extendErrors");
    exports2.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}++`);
    }
    __name(addError, "addError");
    function returnErrors(it, errs) {
      const { gen, validateName: validateName2, schemaEnv } = it;
      if (schemaEnv.$async) {
        gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`);
      } else {
        gen.assign((0, codegen_1._)`${validateName2}.errors`, errs);
        gen.return(false);
      }
    }
    __name(returnErrors, "returnErrors");
    var 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, error, errorPaths) {
      const { createErrors } = cxt.it;
      if (createErrors === false)
        return (0, codegen_1._)`{}`;
      return errorObject(cxt, error, errorPaths);
    }
    __name(errorObjectCode, "errorObjectCode");
    function errorObject(cxt, error, errorPaths = {}) {
      const { gen, it } = cxt;
      const keyValues = [
        errorInstancePath(it, errorPaths),
        errorSchemaPath(cxt, errorPaths)
      ];
      extraErrorProps(cxt, error, keyValues);
      return gen.object(...keyValues);
    }
    __name(errorObject, "errorObject");
    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)];
    }
    __name(errorInstancePath, "errorInstancePath");
    function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
      let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`;
      if (schemaPath) {
        schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
      }
      return [E.schemaPath, schPath];
    }
    __name(errorSchemaPath, "errorSchemaPath");
    function extraErrorProps(cxt, { params, message }, keyValues) {
      const { keyword, data, schemaValue, it } = cxt;
      const { opts, propertyName, topSchemaRef, schemaPath } = it;
      keyValues.push([E.keyword, keyword], [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]);
    }
    __name(extraErrorProps, "extraErrorProps");
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/boolSchema.js
var require_boolSchema2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.boolOrEmptySchema = exports2.topBoolOrEmptySchema = void 0;
    var errors_1 = require_errors3();
    var codegen_1 = require_codegen2();
    var names_1 = require_names2();
    var boolError = {
      message: "boolean schema is false"
    };
    function topBoolOrEmptySchema(it) {
      const { gen, schema, validateName: validateName2 } = it;
      if (schema === false) {
        falseSchemaError(it, false);
      } else if (typeof schema == "object" && schema.$async === true) {
        gen.return(names_1.default.data);
      } else {
        gen.assign((0, codegen_1._)`${validateName2}.errors`, null);
        gen.return(true);
      }
    }
    __name(topBoolOrEmptySchema, "topBoolOrEmptySchema");
    exports2.topBoolOrEmptySchema = topBoolOrEmptySchema;
    function boolOrEmptySchema(it, valid) {
      const { gen, schema } = it;
      if (schema === false) {
        gen.var(valid, false);
        falseSchemaError(it);
      } else {
        gen.var(valid, true);
      }
    }
    __name(boolOrEmptySchema, "boolOrEmptySchema");
    exports2.boolOrEmptySchema = boolOrEmptySchema;
    function falseSchemaError(it, overrideAllErrors) {
      const { gen, data } = it;
      const cxt = {
        gen,
        keyword: "false schema",
        data,
        schema: false,
        schemaCode: false,
        schemaValue: false,
        params: {},
        it
      };
      (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors);
    }
    __name(falseSchemaError, "falseSchemaError");
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/rules.js
var require_rules2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/rules.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRules = exports2.isJSONType = void 0;
    var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
    var jsonTypes = new Set(_jsonTypes);
    function isJSONType(x) {
      return typeof x == "string" && jsonTypes.has(x);
    }
    __name(isJSONType, "isJSONType");
    exports2.isJSONType = isJSONType;
    function getRules() {
      const groups = {
        number: { type: "number", rules: [] },
        string: { type: "string", rules: [] },
        array: { type: "array", rules: [] },
        object: { type: "object", rules: [] }
      };
      return {
        types: { ...groups, integer: true, boolean: true, null: true },
        rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
        post: { rules: [] },
        all: {},
        keywords: {}
      };
    }
    __name(getRules, "getRules");
    exports2.getRules = getRules;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/applicability.js
var require_applicability2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/applicability.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.shouldUseRule = exports2.shouldUseGroup = exports2.schemaHasRulesForType = void 0;
    function schemaHasRulesForType({ schema, self: self2 }, type) {
      const group = self2.RULES.types[type];
      return group && group !== true && shouldUseGroup(schema, group);
    }
    __name(schemaHasRulesForType, "schemaHasRulesForType");
    exports2.schemaHasRulesForType = schemaHasRulesForType;
    function shouldUseGroup(schema, group) {
      return group.rules.some((rule) => shouldUseRule(schema, rule));
    }
    __name(shouldUseGroup, "shouldUseGroup");
    exports2.shouldUseGroup = shouldUseGroup;
    function shouldUseRule(schema, rule) {
      var _a6;
      return schema[rule.keyword] !== void 0 || ((_a6 = rule.definition.implements) === null || _a6 === void 0 ? void 0 : _a6.some((kwd) => schema[kwd] !== void 0));
    }
    __name(shouldUseRule, "shouldUseRule");
    exports2.shouldUseRule = shouldUseRule;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/dataType.js
var require_dataType2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/dataType.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.reportTypeError = exports2.checkDataTypes = exports2.checkDataType = exports2.coerceAndCheckDataType = exports2.getJSONTypes = exports2.getSchemaTypes = exports2.DataType = void 0;
    var rules_1 = require_rules2();
    var applicability_1 = require_applicability2();
    var errors_1 = require_errors3();
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var DataType;
    (function(DataType2) {
      DataType2[DataType2["Correct"] = 0] = "Correct";
      DataType2[DataType2["Wrong"] = 1] = "Wrong";
    })(DataType || (exports2.DataType = DataType = {}));
    function getSchemaTypes(schema) {
      const types3 = getJSONTypes(schema.type);
      const hasNull = types3.includes("null");
      if (hasNull) {
        if (schema.nullable === false)
          throw new Error("type: null contradicts nullable: false");
      } else {
        if (!types3.length && schema.nullable !== void 0) {
          throw new Error('"nullable" cannot be used without "type"');
        }
        if (schema.nullable === true)
          types3.push("null");
      }
      return types3;
    }
    __name(getSchemaTypes, "getSchemaTypes");
    exports2.getSchemaTypes = getSchemaTypes;
    function getJSONTypes(ts) {
      const types3 = Array.isArray(ts) ? ts : ts ? [ts] : [];
      if (types3.every(rules_1.isJSONType))
        return types3;
      throw new Error("type must be JSONType or JSONType[]: " + types3.join(","));
    }
    __name(getJSONTypes, "getJSONTypes");
    exports2.getJSONTypes = getJSONTypes;
    function coerceAndCheckDataType(it, types3) {
      const { gen, data, opts } = it;
      const coerceTo = coerceToTypes(types3, opts.coerceTypes);
      const checkTypes = types3.length > 0 && !(coerceTo.length === 0 && types3.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types3[0]));
      if (checkTypes) {
        const wrongType = checkDataTypes(types3, data, opts.strictNumbers, DataType.Wrong);
        gen.if(wrongType, () => {
          if (coerceTo.length)
            coerceData(it, types3, coerceTo);
          else
            reportTypeError(it);
        });
      }
      return checkTypes;
    }
    __name(coerceAndCheckDataType, "coerceAndCheckDataType");
    exports2.coerceAndCheckDataType = coerceAndCheckDataType;
    var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]);
    function coerceToTypes(types3, coerceTypes) {
      return coerceTypes ? types3.filter((t2) => COERCIBLE.has(t2) || coerceTypes === "array" && t2 === "array") : [];
    }
    __name(coerceToTypes, "coerceToTypes");
    function coerceData(it, types3, coerceTo) {
      const { gen, data, opts } = it;
      const dataType = 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._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types3, data, opts.strictNumbers), () => gen.assign(coerced, data)));
      }
      gen.if((0, codegen_1._)`${coerced} !== undefined`);
      for (const t2 of coerceTo) {
        if (COERCIBLE.has(t2) || t2 === "array" && opts.coerceTypes === "array") {
          coerceSpecificType(t2);
        }
      }
      gen.else();
      reportTypeError(it);
      gen.endIf();
      gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {
        gen.assign(data, coerced);
        assignParentData(it, coerced);
      });
      function coerceSpecificType(t2) {
        switch (t2) {
          case "string":
            gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "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._)`${dataType} == "boolean" || ${data} === null
              || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`);
            return;
          case "integer":
            gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null
              || (${dataType} === "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._)`${dataType} === "string" || ${dataType} === "number"
              || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`);
        }
      }
      __name(coerceSpecificType, "coerceSpecificType");
    }
    __name(coerceData, "coerceData");
    function assignParentData({ gen, parentData, parentDataProperty }, expr) {
      gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr));
    }
    __name(assignParentData, "assignParentData");
    function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
      const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
      let cond;
      switch (dataType) {
        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} ${dataType}`;
      }
      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);
      }
      __name(numCond, "numCond");
    }
    __name(checkDataType, "checkDataType");
    exports2.checkDataType = checkDataType;
    function checkDataTypes(dataTypes, data, strictNums, correct) {
      if (dataTypes.length === 1) {
        return checkDataType(dataTypes[0], data, strictNums, correct);
      }
      let cond;
      const types3 = (0, util_1.toHash)(dataTypes);
      if (types3.array && types3.object) {
        const notObj = (0, codegen_1._)`typeof ${data} != "object"`;
        cond = types3.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`;
        delete types3.null;
        delete types3.array;
        delete types3.object;
      } else {
        cond = codegen_1.nil;
      }
      if (types3.number)
        delete types3.integer;
      for (const t2 in types3)
        cond = (0, codegen_1.and)(cond, checkDataType(t2, data, strictNums, correct));
      return cond;
    }
    __name(checkDataTypes, "checkDataTypes");
    exports2.checkDataTypes = checkDataTypes;
    var typeError = {
      message: /* @__PURE__ */ __name(({ schema }) => `must be ${schema}`, "message"),
      params: /* @__PURE__ */ __name(({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}`, "params")
    };
    function reportTypeError(it) {
      const cxt = getTypeErrorContext(it);
      (0, errors_1.reportError)(cxt, typeError);
    }
    __name(reportTypeError, "reportTypeError");
    exports2.reportTypeError = reportTypeError;
    function getTypeErrorContext(it) {
      const { gen, data, schema } = it;
      const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
      return {
        gen,
        keyword: "type",
        data,
        schema: schema.type,
        schemaCode,
        schemaValue: schemaCode,
        parentSchema: schema,
        params: {},
        it
      };
    }
    __name(getTypeErrorContext, "getTypeErrorContext");
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/defaults.js
var require_defaults2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/defaults.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.assignDefaults = void 0;
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    function assignDefaults(it, ty) {
      const { properties, items } = it.schema;
      if (ty === "object" && properties) {
        for (const key in properties) {
          assignDefault(it, key, properties[key].default);
        }
      } else if (ty === "array" && Array.isArray(items)) {
        items.forEach((sch, i) => assignDefault(it, i, sch.default));
      }
    }
    __name(assignDefaults, "assignDefaults");
    exports2.assignDefaults = assignDefaults;
    function assignDefault(it, prop, defaultValue) {
      const { gen, compositeRule, data, opts } = it;
      if (defaultValue === void 0)
        return;
      const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`;
      if (compositeRule) {
        (0, util_1.checkStrictMode)(it, `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)}`);
    }
    __name(assignDefault, "assignDefault");
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/code.js
var require_code4 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/code.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateUnion = exports2.validateArray = exports2.usePattern = exports2.callValidateCode = exports2.schemaProperties = exports2.allSchemaProperties = exports2.noPropertyInData = exports2.propertyInData = exports2.isOwnProperty = exports2.hasPropFunc = exports2.reportMissingProp = exports2.checkMissingProp = exports2.checkReportMissingProp = void 0;
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var names_1 = require_names2();
    var util_2 = require_util10();
    function checkReportMissingProp(cxt, prop) {
      const { gen, data, it } = cxt;
      gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
        cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true);
        cxt.error();
      });
    }
    __name(checkReportMissingProp, "checkReportMissingProp");
    exports2.checkReportMissingProp = checkReportMissingProp;
    function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
      return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`)));
    }
    __name(checkMissingProp, "checkMissingProp");
    exports2.checkMissingProp = checkMissingProp;
    function reportMissingProp(cxt, missing) {
      cxt.setParams({ missingProperty: missing }, true);
      cxt.error();
    }
    __name(reportMissingProp, "reportMissingProp");
    exports2.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`
      });
    }
    __name(hasPropFunc, "hasPropFunc");
    exports2.hasPropFunc = hasPropFunc;
    function isOwnProperty(gen, data, property) {
      return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`;
    }
    __name(isOwnProperty, "isOwnProperty");
    exports2.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;
    }
    __name(propertyInData, "propertyInData");
    exports2.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;
    }
    __name(noPropertyInData, "noPropertyInData");
    exports2.noPropertyInData = noPropertyInData;
    function allSchemaProperties(schemaMap) {
      return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
    }
    __name(allSchemaProperties, "allSchemaProperties");
    exports2.allSchemaProperties = allSchemaProperties;
    function schemaProperties(it, schemaMap) {
      return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
    }
    __name(schemaProperties, "schemaProperties");
    exports2.schemaProperties = schemaProperties;
    function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context2, 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, it.parentData],
        [names_1.default.parentDataProperty, it.parentDataProperty],
        [names_1.default.rootData, names_1.default.rootData]
      ];
      if (it.opts.dynamicRef)
        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
      const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
      return context2 !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context2}, ${args})` : (0, codegen_1._)`${func}(${args})`;
    }
    __name(callValidateCode, "callValidateCode");
    exports2.callValidateCode = callValidateCode;
    var newRegExp = (0, codegen_1._)`new RegExp`;
    function usePattern({ gen, it: { opts } }, pattern) {
      const u = opts.unicodeRegExp ? "u" : "";
      const { regExp } = opts.code;
      const rx = regExp(pattern, 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)}(${pattern}, ${u})`
      });
    }
    __name(usePattern, "usePattern");
    exports2.usePattern = usePattern;
    function validateArray(cxt) {
      const { gen, data, keyword, it } = cxt;
      const valid = gen.name("valid");
      if (it.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 len = gen.const("len", (0, codegen_1._)`${data}.length`);
        gen.forRange("i", 0, len, (i) => {
          cxt.subschema({
            keyword,
            dataProp: i,
            dataPropType: util_1.Type.Num
          }, valid);
          gen.if((0, codegen_1.not)(valid), notValid);
        });
      }
      __name(validateItems, "validateItems");
    }
    __name(validateArray, "validateArray");
    exports2.validateArray = validateArray;
    function validateUnion(cxt) {
      const { gen, schema, keyword, it } = cxt;
      if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
      const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));
      if (alwaysValid && !it.opts.unevaluated)
        return;
      const valid = gen.let("valid", false);
      const schValid = gen.name("_valid");
      gen.block(() => schema.forEach((_sch, i) => {
        const schCxt = cxt.subschema({
          keyword,
          schemaProp: i,
          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));
    }
    __name(validateUnion, "validateUnion");
    exports2.validateUnion = validateUnion;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/keyword.js
var require_keyword2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/keyword.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateKeywordUsage = exports2.validSchemaType = exports2.funcKeywordCode = exports2.macroKeywordCode = void 0;
    var codegen_1 = require_codegen2();
    var names_1 = require_names2();
    var code_1 = require_code4();
    var errors_1 = require_errors3();
    function macroKeywordCode(cxt, def2) {
      const { gen, keyword, schema, parentSchema, it } = cxt;
      const macroSchema = def2.macro.call(it.self, schema, parentSchema, it);
      const schemaRef = useKeyword(gen, keyword, macroSchema);
      if (it.opts.validateSchema !== false)
        it.self.validateSchema(macroSchema, true);
      const valid = gen.name("valid");
      cxt.subschema({
        schema: macroSchema,
        schemaPath: codegen_1.nil,
        errSchemaPath: `${it.errSchemaPath}/${keyword}`,
        topSchemaRef: schemaRef,
        compositeRule: true
      }, valid);
      cxt.pass(valid, () => cxt.error(true));
    }
    __name(macroKeywordCode, "macroKeywordCode");
    exports2.macroKeywordCode = macroKeywordCode;
    function funcKeywordCode(cxt, def2) {
      var _a6;
      const { gen, keyword, schema, parentSchema, $data, it } = cxt;
      checkAsyncKeyword(it, def2);
      const validate4 = !$data && def2.compile ? def2.compile.call(it.self, schema, parentSchema, it) : def2.validate;
      const validateRef = useKeyword(gen, keyword, validate4);
      const valid = gen.let("valid");
      cxt.block$data(valid, validateKeyword);
      cxt.ok((_a6 = def2.valid) !== null && _a6 !== void 0 ? _a6 : valid);
      function validateKeyword() {
        if (def2.errors === false) {
          assignValid();
          if (def2.modifying)
            modifyData(cxt);
          reportErrs(() => cxt.error());
        } else {
          const ruleErrs = def2.async ? validateAsync() : validateSync();
          if (def2.modifying)
            modifyData(cxt);
          reportErrs(() => addErrs(cxt, ruleErrs));
        }
      }
      __name(validateKeyword, "validateKeyword");
      function validateAsync() {
        const ruleErrs = gen.let("ruleErrs", null);
        gen.try(() => assignValid((0, codegen_1._)`await `), (e2) => gen.assign(valid, false).if((0, codegen_1._)`${e2} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e2}.errors`), () => gen.throw(e2)));
        return ruleErrs;
      }
      __name(validateAsync, "validateAsync");
      function validateSync() {
        const validateErrs = (0, codegen_1._)`${validateRef}.errors`;
        gen.assign(validateErrs, null);
        assignValid(codegen_1.nil);
        return validateErrs;
      }
      __name(validateSync, "validateSync");
      function assignValid(_await = def2.async ? (0, codegen_1._)`await ` : codegen_1.nil) {
        const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
        const passSchema = !("compile" in def2 && !$data || def2.schema === false);
        gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def2.modifying);
      }
      __name(assignValid, "assignValid");
      function reportErrs(errors) {
        var _a7;
        gen.if((0, codegen_1.not)((_a7 = def2.valid) !== null && _a7 !== void 0 ? _a7 : valid), errors);
      }
      __name(reportErrs, "reportErrs");
    }
    __name(funcKeywordCode, "funcKeywordCode");
    exports2.funcKeywordCode = funcKeywordCode;
    function modifyData(cxt) {
      const { gen, data, it } = cxt;
      gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`));
    }
    __name(modifyData, "modifyData");
    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());
    }
    __name(addErrs, "addErrs");
    function checkAsyncKeyword({ schemaEnv }, def2) {
      if (def2.async && !schemaEnv.$async)
        throw new Error("async keyword in sync schema");
    }
    __name(checkAsyncKeyword, "checkAsyncKeyword");
    function useKeyword(gen, keyword, result) {
      if (result === void 0)
        throw new Error(`keyword "${keyword}" failed to compile`);
      return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
    }
    __name(useKeyword, "useKeyword");
    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");
    }
    __name(validSchemaType, "validSchemaType");
    exports2.validSchemaType = validSchemaType;
    function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def2, keyword) {
      if (Array.isArray(def2.keyword) ? !def2.keyword.includes(keyword) : def2.keyword !== keyword) {
        throw new Error("ajv implementation error");
      }
      const deps = def2.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 ${keyword}: ${deps.join(",")}`);
      }
      if (def2.validateSchema) {
        const valid = def2.validateSchema(schema[keyword]);
        if (!valid) {
          const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def2.validateSchema.errors);
          if (opts.validateSchema === "log")
            self2.logger.error(msg);
          else
            throw new Error(msg);
        }
      }
    }
    __name(validateKeywordUsage, "validateKeywordUsage");
    exports2.validateKeywordUsage = validateKeywordUsage;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/subschema.js
var require_subschema2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/subschema.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.extendSubschemaMode = exports2.extendSubschemaData = exports2.getSubschema = void 0;
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
      if (keyword !== void 0 && schema !== void 0) {
        throw new Error('both "keyword" and "schema" passed, only one allowed');
      }
      if (keyword !== void 0) {
        const sch = it.schema[keyword];
        return schemaProp === void 0 ? {
          schema: sch,
          schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
          errSchemaPath: `${it.errSchemaPath}/${keyword}`
        } : {
          schema: sch[schemaProp],
          schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
          errSchemaPath: `${it.errSchemaPath}/${keyword}/${(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');
    }
    __name(getSubschema, "getSubschema");
    exports2.getSubschema = getSubschema;
    function extendSubschemaData(subschema, it, { 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 } = it;
      if (dataProp !== void 0) {
        const { errorPath, dataPathArr, opts } = it;
        const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
        dataContextProps(nextData);
        subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
        subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`;
        subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
      }
      if (data !== void 0) {
        const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true);
        dataContextProps(nextData);
        if (propertyName !== void 0)
          subschema.propertyName = propertyName;
      }
      if (dataTypes)
        subschema.dataTypes = dataTypes;
      function dataContextProps(_nextData) {
        subschema.data = _nextData;
        subschema.dataLevel = it.dataLevel + 1;
        subschema.dataTypes = [];
        it.definedProperties = /* @__PURE__ */ new Set();
        subschema.parentData = it.data;
        subschema.dataNames = [...it.dataNames, _nextData];
      }
      __name(dataContextProps, "dataContextProps");
    }
    __name(extendSubschemaData, "extendSubschemaData");
    exports2.extendSubschemaData = extendSubschemaData;
    function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
      if (compositeRule !== void 0)
        subschema.compositeRule = compositeRule;
      if (createErrors !== void 0)
        subschema.createErrors = createErrors;
      if (allErrors !== void 0)
        subschema.allErrors = allErrors;
      subschema.jtdDiscriminator = jtdDiscriminator;
      subschema.jtdMetadata = jtdMetadata;
    }
    __name(extendSubschemaMode, "extendSubschemaMode");
    exports2.extendSubschemaMode = extendSubschemaMode;
  }
});

// node_modules/ajv-formats/node_modules/json-schema-traverse/index.js
var require_json_schema_traverse2 = __commonJS({
  "node_modules/ajv-formats/node_modules/json-schema-traverse/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var traverse = module2.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 i = 0; i < sch.length; i++)
                _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i);
            }
          } 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);
      }
    }
    __name(_traverse, "_traverse");
    function escapeJsonPtr(str2) {
      return str2.replace(/~/g, "~0").replace(/\//g, "~1");
    }
    __name(escapeJsonPtr, "escapeJsonPtr");
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/resolve.js
var require_resolve2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/resolve.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getSchemaRefs = exports2.resolveUrl = exports2.normalizeId = exports2._getFullPath = exports2.getFullPath = exports2.inlineRef = void 0;
    var util_1 = require_util10();
    var equal = require_fast_deep_equal();
    var traverse = require_json_schema_traverse2();
    var 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;
    }
    __name(inlineRef, "inlineRef");
    exports2.inlineRef = inlineRef;
    var 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;
    }
    __name(hasRef, "hasRef");
    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;
    }
    __name(countKeys, "countKeys");
    function getFullPath(resolver, id = "", normalize10) {
      if (normalize10 !== false)
        id = normalizeId(id);
      const p = resolver.parse(id);
      return _getFullPath(resolver, p);
    }
    __name(getFullPath, "getFullPath");
    exports2.getFullPath = getFullPath;
    function _getFullPath(resolver, p) {
      const serialized = resolver.serialize(p);
      return serialized.split("#")[0] + "#";
    }
    __name(_getFullPath, "_getFullPath");
    exports2._getFullPath = _getFullPath;
    var TRAILING_SLASH_HASH = /#\/?$/;
    function normalizeId(id) {
      return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
    }
    __name(normalizeId, "normalizeId");
    exports2.normalizeId = normalizeId;
    function resolveUrl(resolver, baseId, id) {
      id = normalizeId(id);
      return resolver.resolve(baseId, id);
    }
    __name(resolveUrl, "resolveUrl");
    exports2.resolveUrl = resolveUrl;
    var 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(ref) {
          const _resolve = this.opts.uriResolver.resolve;
          ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
          if (schemaRefs.has(ref))
            throw ambiguos(ref);
          schemaRefs.add(ref);
          let schOrRef = this.refs[ref];
          if (typeof schOrRef == "string")
            schOrRef = this.refs[schOrRef];
          if (typeof schOrRef == "object") {
            checkAmbiguosRef(sch, schOrRef.schema, ref);
          } else if (ref !== normalizeId(fullPath)) {
            if (ref[0] === "#") {
              checkAmbiguosRef(sch, localRefs[ref], ref);
              localRefs[ref] = sch;
            } else {
              this.refs[ref] = fullPath;
            }
          }
          return ref;
        }
        __name(addRef, "addRef");
        function addAnchor(anchor) {
          if (typeof anchor == "string") {
            if (!ANCHOR.test(anchor))
              throw new Error(`invalid anchor "${anchor}"`);
            addRef.call(this, `#${anchor}`);
          }
        }
        __name(addAnchor, "addAnchor");
      });
      return localRefs;
      function checkAmbiguosRef(sch1, sch2, ref) {
        if (sch2 !== void 0 && !equal(sch1, sch2))
          throw ambiguos(ref);
      }
      __name(checkAmbiguosRef, "checkAmbiguosRef");
      function ambiguos(ref) {
        return new Error(`reference "${ref}" resolves to more than one schema`);
      }
      __name(ambiguos, "ambiguos");
    }
    __name(getSchemaRefs, "getSchemaRefs");
    exports2.getSchemaRefs = getSchemaRefs;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/index.js
var require_validate2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getData = exports2.KeywordCxt = exports2.validateFunctionCode = void 0;
    var boolSchema_1 = require_boolSchema2();
    var dataType_1 = require_dataType2();
    var applicability_1 = require_applicability2();
    var dataType_2 = require_dataType2();
    var defaults_1 = require_defaults2();
    var keyword_1 = require_keyword2();
    var subschema_1 = require_subschema2();
    var codegen_1 = require_codegen2();
    var names_1 = require_names2();
    var resolve_1 = require_resolve2();
    var util_1 = require_util10();
    var errors_1 = require_errors3();
    function validateFunctionCode(it) {
      if (isSchemaObj(it)) {
        checkKeywords(it);
        if (schemaCxtHasRules(it)) {
          topSchemaObjCode(it);
          return;
        }
      }
      validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
    }
    __name(validateFunctionCode, "validateFunctionCode");
    exports2.validateFunctionCode = validateFunctionCode;
    function validateFunction({ gen, validateName: validateName2, schema, schemaEnv, opts }, body) {
      if (opts.code.es5) {
        gen.func(validateName2, (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(validateName2, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
      }
    }
    __name(validateFunction, "validateFunction");
    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}}={}`;
    }
    __name(destructureValCxt, "destructureValCxt");
    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._)`{}`);
      });
    }
    __name(destructureValCxtES5, "destructureValCxtES5");
    function topSchemaObjCode(it) {
      const { schema, opts, gen } = it;
      validateFunction(it, () => {
        if (opts.$comment && schema.$comment)
          commentKeyword(it);
        checkNoDefault(it);
        gen.let(names_1.default.vErrors, null);
        gen.let(names_1.default.errors, 0);
        if (opts.unevaluated)
          resetEvaluated(it);
        typeAndKeywords(it);
        returnResults(it);
      });
      return;
    }
    __name(topSchemaObjCode, "topSchemaObjCode");
    function resetEvaluated(it) {
      const { gen, validateName: validateName2 } = it;
      it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName2}.evaluated`);
      gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`));
      gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`));
    }
    __name(resetEvaluated, "resetEvaluated");
    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;
    }
    __name(funcSourceUrl, "funcSourceUrl");
    function subschemaCode(it, valid) {
      if (isSchemaObj(it)) {
        checkKeywords(it);
        if (schemaCxtHasRules(it)) {
          subSchemaObjCode(it, valid);
          return;
        }
      }
      (0, boolSchema_1.boolOrEmptySchema)(it, valid);
    }
    __name(subschemaCode, "subschemaCode");
    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;
    }
    __name(schemaCxtHasRules, "schemaCxtHasRules");
    function isSchemaObj(it) {
      return typeof it.schema != "boolean";
    }
    __name(isSchemaObj, "isSchemaObj");
    function subSchemaObjCode(it, valid) {
      const { schema, gen, opts } = it;
      if (opts.$comment && schema.$comment)
        commentKeyword(it);
      updateContext(it);
      checkAsyncSchema(it);
      const errsCount = gen.const("_errs", names_1.default.errors);
      typeAndKeywords(it, errsCount);
      gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
    }
    __name(subSchemaObjCode, "subSchemaObjCode");
    function checkKeywords(it) {
      (0, util_1.checkUnknownRules)(it);
      checkRefsAndKeywords(it);
    }
    __name(checkKeywords, "checkKeywords");
    function typeAndKeywords(it, errsCount) {
      if (it.opts.jtd)
        return schemaKeywords(it, [], false, errsCount);
      const types3 = (0, dataType_1.getSchemaTypes)(it.schema);
      const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types3);
      schemaKeywords(it, types3, !checkedTypes, errsCount);
    }
    __name(typeAndKeywords, "typeAndKeywords");
    function checkRefsAndKeywords(it) {
      const { schema, errSchemaPath, opts, self: self2 } = it;
      if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) {
        self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
      }
    }
    __name(checkRefsAndKeywords, "checkRefsAndKeywords");
    function checkNoDefault(it) {
      const { schema, opts } = it;
      if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {
        (0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
      }
    }
    __name(checkNoDefault, "checkNoDefault");
    function updateContext(it) {
      const schId = it.schema[it.opts.schemaId];
      if (schId)
        it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
    }
    __name(updateContext, "updateContext");
    function checkAsyncSchema(it) {
      if (it.schema.$async && !it.schemaEnv.$async)
        throw new Error("async schema in sync schema");
    }
    __name(checkAsyncSchema, "checkAsyncSchema");
    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)`);
      }
    }
    __name(commentKeyword, "commentKeyword");
    function returnResults(it) {
      const { gen, schemaEnv, validateName: validateName2, ValidationError, opts } = it;
      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._)`${validateName2}.errors`, names_1.default.vErrors);
        if (opts.unevaluated)
          assignEvaluated(it);
        gen.return((0, codegen_1._)`${names_1.default.errors} === 0`);
      }
    }
    __name(returnResults, "returnResults");
    function assignEvaluated({ gen, evaluated, props, items }) {
      if (props instanceof codegen_1.Name)
        gen.assign((0, codegen_1._)`${evaluated}.props`, props);
      if (items instanceof codegen_1.Name)
        gen.assign((0, codegen_1._)`${evaluated}.items`, items);
    }
    __name(assignEvaluated, "assignEvaluated");
    function schemaKeywords(it, types3, typeErrors, errsCount) {
      const { gen, schema, data, allErrors, opts, self: self2 } = it;
      const { RULES } = self2;
      if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
        gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition));
        return;
      }
      if (!opts.jtd)
        checkStrictTypes(it, types3);
      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(it, group);
          if (types3.length === 1 && types3[0] === group.type && typeErrors) {
            gen.else();
            (0, dataType_2.reportTypeError)(it);
          }
          gen.endIf();
        } else {
          iterateKeywords(it, group);
        }
        if (!allErrors)
          gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);
      }
      __name(groupKeywords, "groupKeywords");
    }
    __name(schemaKeywords, "schemaKeywords");
    function iterateKeywords(it, group) {
      const { gen, schema, opts: { useDefaults } } = it;
      if (useDefaults)
        (0, defaults_1.assignDefaults)(it, group.type);
      gen.block(() => {
        for (const rule of group.rules) {
          if ((0, applicability_1.shouldUseRule)(schema, rule)) {
            keywordCode(it, rule.keyword, rule.definition, group.type);
          }
        }
      });
    }
    __name(iterateKeywords, "iterateKeywords");
    function checkStrictTypes(it, types3) {
      if (it.schemaEnv.meta || !it.opts.strictTypes)
        return;
      checkContextTypes(it, types3);
      if (!it.opts.allowUnionTypes)
        checkMultipleTypes(it, types3);
      checkKeywordTypes(it, it.dataTypes);
    }
    __name(checkStrictTypes, "checkStrictTypes");
    function checkContextTypes(it, types3) {
      if (!types3.length)
        return;
      if (!it.dataTypes.length) {
        it.dataTypes = types3;
        return;
      }
      types3.forEach((t2) => {
        if (!includesType(it.dataTypes, t2)) {
          strictTypesError(it, `type "${t2}" not allowed by context "${it.dataTypes.join(",")}"`);
        }
      });
      narrowSchemaTypes(it, types3);
    }
    __name(checkContextTypes, "checkContextTypes");
    function checkMultipleTypes(it, ts) {
      if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
        strictTypesError(it, "use allowUnionTypes to allow union type keyword");
      }
    }
    __name(checkMultipleTypes, "checkMultipleTypes");
    function checkKeywordTypes(it, ts) {
      const rules = it.self.RULES.all;
      for (const keyword in rules) {
        const rule = rules[keyword];
        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
          const { type } = rule.definition;
          if (type.length && !type.some((t2) => hasApplicableType(ts, t2))) {
            strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
          }
        }
      }
    }
    __name(checkKeywordTypes, "checkKeywordTypes");
    function hasApplicableType(schTs, kwdT) {
      return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer");
    }
    __name(hasApplicableType, "hasApplicableType");
    function includesType(ts, t2) {
      return ts.includes(t2) || t2 === "integer" && ts.includes("number");
    }
    __name(includesType, "includesType");
    function narrowSchemaTypes(it, withTypes) {
      const ts = [];
      for (const t2 of it.dataTypes) {
        if (includesType(withTypes, t2))
          ts.push(t2);
        else if (withTypes.includes("integer") && t2 === "number")
          ts.push("integer");
      }
      it.dataTypes = ts;
    }
    __name(narrowSchemaTypes, "narrowSchemaTypes");
    function strictTypesError(it, msg) {
      const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
      msg += ` at "${schemaPath}" (strictTypes)`;
      (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
    }
    __name(strictTypesError, "strictTypesError");
    var KeywordCxt = class {
      static {
        __name(this, "KeywordCxt");
      }
      constructor(it, def2, keyword) {
        (0, keyword_1.validateKeywordUsage)(it, def2, keyword);
        this.gen = it.gen;
        this.allErrors = it.allErrors;
        this.keyword = keyword;
        this.data = it.data;
        this.schema = it.schema[keyword];
        this.$data = def2.$data && it.opts.$data && this.schema && this.schema.$data;
        this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
        this.schemaType = def2.schemaType;
        this.parentSchema = it.schema;
        this.params = {};
        this.it = it;
        this.def = def2;
        if (this.$data) {
          this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
        } else {
          this.schemaCode = this.schemaValue;
          if (!(0, keyword_1.validSchemaType)(this.schema, def2.schemaType, def2.allowUndefined)) {
            throw new Error(`${keyword} value must be ${JSON.stringify(def2.schemaType)}`);
          }
        }
        if ("code" in def2 ? def2.trackErrors : def2.errors !== false) {
          this.errsCount = it.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(append2, errorParams, errorPaths) {
        if (errorParams) {
          this.setParams(errorParams);
          this._error(append2, errorPaths);
          this.setParams({});
          return;
        }
        this._error(append2, errorPaths);
      }
      _error(append2, errorPaths) {
        ;
        (append2 ? 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: def2 } = 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 || def2.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: def2, it } = 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, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
          }
          return codegen_1.nil;
        }
        __name(wrong$DataType, "wrong$DataType");
        function invalid$DataSchema() {
          if (def2.validateSchema) {
            const validateSchemaRef = gen.scopeValue("validate$data", { ref: def2.validateSchema });
            return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`;
          }
          return codegen_1.nil;
        }
        __name(invalid$DataSchema, "invalid$DataSchema");
      }
      subschema(appl, valid) {
        const subschema = (0, subschema_1.getSubschema)(this.it, appl);
        (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
        (0, subschema_1.extendSubschemaMode)(subschema, appl);
        const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 };
        subschemaCode(nextContext, valid);
        return nextContext;
      }
      mergeEvaluated(schemaCxt, toName) {
        const { it, gen } = this;
        if (!it.opts.unevaluated)
          return;
        if (it.props !== true && schemaCxt.props !== void 0) {
          it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
        }
        if (it.items !== true && schemaCxt.items !== void 0) {
          it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
        }
      }
      mergeValidEvaluated(schemaCxt, valid) {
        const { it, gen } = this;
        if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
          gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
          return true;
        }
      }
    };
    exports2.KeywordCxt = KeywordCxt;
    function keywordCode(it, keyword, def2, ruleType) {
      const cxt = new KeywordCxt(it, def2, keyword);
      if ("code" in def2) {
        def2.code(cxt, ruleType);
      } else if (cxt.$data && def2.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def2);
      } else if ("macro" in def2) {
        (0, keyword_1.macroKeywordCode)(cxt, def2);
      } else if (def2.compile || def2.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def2);
      }
    }
    __name(keywordCode, "keywordCode");
    var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
    var 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}`;
      }
      __name(errorMsg, "errorMsg");
    }
    __name(getData, "getData");
    exports2.getData = getData;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/runtime/validation_error.js
var require_validation_error2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/runtime/validation_error.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var ValidationError = class extends Error {
      static {
        __name(this, "ValidationError");
      }
      constructor(errors) {
        super("validation failed");
        this.errors = errors;
        this.ajv = this.validation = true;
      }
    };
    exports2.default = ValidationError;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/ref_error.js
var require_ref_error2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/ref_error.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var resolve_1 = require_resolve2();
    var MissingRefError = class extends Error {
      static {
        __name(this, "MissingRefError");
      }
      constructor(resolver, baseId, ref, msg) {
        super(msg || `can't resolve reference ${ref} from id ${baseId}`);
        this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);
        this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
      }
    };
    exports2.default = MissingRefError;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/index.js
var require_compile2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.resolveSchema = exports2.getCompilingSchema = exports2.resolveRef = exports2.compileSchema = exports2.SchemaEnv = void 0;
    var codegen_1 = require_codegen2();
    var validation_error_1 = require_validation_error2();
    var names_1 = require_names2();
    var resolve_1 = require_resolve2();
    var util_1 = require_util10();
    var validate_1 = require_validate2();
    var SchemaEnv = class {
      static {
        __name(this, "SchemaEnv");
      }
      constructor(env7) {
        var _a6;
        this.refs = {};
        this.dynamicAnchors = {};
        let schema;
        if (typeof env7.schema == "object")
          schema = env7.schema;
        this.schema = env7.schema;
        this.schemaId = env7.schemaId;
        this.root = env7.root || this;
        this.baseId = (_a6 = env7.baseId) !== null && _a6 !== void 0 ? _a6 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env7.schemaId || "$id"]);
        this.schemaPath = env7.schemaPath;
        this.localRefs = env7.localRefs;
        this.meta = env7.meta;
        this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
        this.refs = {};
      }
    };
    exports2.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 validateName2 = gen.scopeName("validate");
      sch.validateName = validateName2;
      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: validateName2,
        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 validate4 = makeValidate(this, this.scope.get());
        this.scope.value(validateName2, { ref: validate4 });
        validate4.errors = null;
        validate4.schema = sch.schema;
        validate4.schemaEnv = sch;
        if (sch.$async)
          validate4.$async = true;
        if (this.opts.code.source === true) {
          validate4.source = { validateName: validateName2, validateCode, scopeValues: gen._values };
        }
        if (this.opts.unevaluated) {
          const { props, items } = schemaCxt;
          validate4.evaluated = {
            props: props instanceof codegen_1.Name ? void 0 : props,
            items: items instanceof codegen_1.Name ? void 0 : items,
            dynamicProps: props instanceof codegen_1.Name,
            dynamicItems: items instanceof codegen_1.Name
          };
          if (validate4.source)
            validate4.source.evaluated = (0, codegen_1.stringify)(validate4.evaluated);
        }
        sch.validate = validate4;
        return sch;
      } catch (e2) {
        delete sch.validate;
        delete sch.validateName;
        if (sourceCode)
          this.logger.error("Error compiling schema, function code:", sourceCode);
        throw e2;
      } finally {
        this._compilations.delete(sch);
      }
    }
    __name(compileSchema, "compileSchema");
    exports2.compileSchema = compileSchema;
    function resolveRef(root, baseId, ref) {
      var _a6;
      ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
      const schOrFunc = root.refs[ref];
      if (schOrFunc)
        return schOrFunc;
      let _sch = resolve24.call(this, root, ref);
      if (_sch === void 0) {
        const schema = (_a6 = root.localRefs) === null || _a6 === void 0 ? void 0 : _a6[ref];
        const { schemaId } = this.opts;
        if (schema)
          _sch = new SchemaEnv({ schema, schemaId, root, baseId });
      }
      if (_sch === void 0)
        return;
      return root.refs[ref] = inlineOrCompile.call(this, _sch);
    }
    __name(resolveRef, "resolveRef");
    exports2.resolveRef = resolveRef;
    function inlineOrCompile(sch) {
      if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
        return sch.schema;
      return sch.validate ? sch : compileSchema.call(this, sch);
    }
    __name(inlineOrCompile, "inlineOrCompile");
    function getCompilingSchema(schEnv) {
      for (const sch of this._compilations) {
        if (sameSchemaEnv(sch, schEnv))
          return sch;
      }
    }
    __name(getCompilingSchema, "getCompilingSchema");
    exports2.getCompilingSchema = getCompilingSchema;
    function sameSchemaEnv(s1, s2) {
      return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
    }
    __name(sameSchemaEnv, "sameSchemaEnv");
    function resolve24(root, ref) {
      let sch;
      while (typeof (sch = this.refs[ref]) == "string")
        ref = sch;
      return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
    }
    __name(resolve24, "resolve");
    function resolveSchema(root, ref) {
      const p = this.opts.uriResolver.parse(ref);
      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 id = (0, resolve_1.normalizeId)(refPath);
      const schOrRef = this.refs[id] || this.schemas[id];
      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 (id === (0, resolve_1.normalizeId)(ref)) {
        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);
    }
    __name(resolveSchema, "resolveSchema");
    exports2.resolveSchema = resolveSchema;
    var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([
      "properties",
      "patternProperties",
      "enum",
      "dependencies",
      "definitions"
    ]);
    function getJsonPointer(parsedRef, { baseId, schema, root }) {
      var _a6;
      if (((_a6 = parsedRef.fragment) === null || _a6 === void 0 ? void 0 : _a6[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 env7;
      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);
        env7 = resolveSchema.call(this, root, $ref);
      }
      const { schemaId } = this.opts;
      env7 = env7 || new SchemaEnv({ schema, schemaId, root, baseId });
      if (env7.schema !== env7.root.schema)
        return env7;
      return void 0;
    }
    __name(getJsonPointer, "getJsonPointer");
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/refs/data.json
var require_data2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/refs/data.json"(exports2, module2) {
    module2.exports = {
      $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
      description: "Meta-schema for $data reference (JSON AnySchema extension proposal)",
      type: "object",
      required: ["$data"],
      properties: {
        $data: {
          type: "string",
          anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }]
        }
      },
      additionalProperties: false
    };
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/runtime/uri.js
var require_uri2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/runtime/uri.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var uri = require_fast_uri();
    uri.code = 'require("ajv/dist/runtime/uri").default';
    exports2.default = uri;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/core.js
var require_core3 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/core.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CodeGen = exports2.Name = exports2.nil = exports2.stringify = exports2.str = exports2._ = exports2.KeywordCxt = void 0;
    var validate_1 = require_validate2();
    Object.defineProperty(exports2, "KeywordCxt", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return validate_1.KeywordCxt;
    }, "get") });
    var codegen_1 = require_codegen2();
    Object.defineProperty(exports2, "_", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1._;
    }, "get") });
    Object.defineProperty(exports2, "str", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.str;
    }, "get") });
    Object.defineProperty(exports2, "stringify", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.stringify;
    }, "get") });
    Object.defineProperty(exports2, "nil", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.nil;
    }, "get") });
    Object.defineProperty(exports2, "Name", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.Name;
    }, "get") });
    Object.defineProperty(exports2, "CodeGen", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.CodeGen;
    }, "get") });
    var validation_error_1 = require_validation_error2();
    var ref_error_1 = require_ref_error2();
    var rules_1 = require_rules2();
    var compile_1 = require_compile2();
    var codegen_2 = require_codegen2();
    var resolve_1 = require_resolve2();
    var dataType_1 = require_dataType2();
    var util_1 = require_util10();
    var $dataRefSchema = require_data2();
    var uri_1 = require_uri2();
    var defaultRegExp = /* @__PURE__ */ __name((str2, flags) => new RegExp(str2, flags), "defaultRegExp");
    defaultRegExp.code = "new RegExp";
    var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
    var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([
      "validate",
      "serialize",
      "parse",
      "wrapper",
      "root",
      "schema",
      "keyword",
      "pattern",
      "formats",
      "validate$data",
      "func",
      "obj",
      "Error"
    ]);
    var 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."
    };
    var deprecatedOptions = {
      ignoreKeywordsWithRef: "",
      jsPropertySyntax: "",
      unicode: '"minLength"/"maxLength" account for unicode characters by default.'
    };
    var MAX_EXPRESSION = 200;
    function requiredOptions(o2) {
      var _a6, _b2, _c2, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
      const s2 = o2.strict;
      const _optz = (_a6 = o2.code) === null || _a6 === void 0 ? void 0 : _a6.optimize;
      const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;
      const regExp = (_c2 = (_b2 = o2.code) === null || _b2 === void 0 ? void 0 : _b2.regExp) !== null && _c2 !== void 0 ? _c2 : defaultRegExp;
      const uriResolver = (_d = o2.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
      return {
        strictSchema: (_f = (_e = o2.strictSchema) !== null && _e !== void 0 ? _e : s2) !== null && _f !== void 0 ? _f : true,
        strictNumbers: (_h = (_g = o2.strictNumbers) !== null && _g !== void 0 ? _g : s2) !== null && _h !== void 0 ? _h : true,
        strictTypes: (_k = (_j = o2.strictTypes) !== null && _j !== void 0 ? _j : s2) !== null && _k !== void 0 ? _k : "log",
        strictTuples: (_m = (_l = o2.strictTuples) !== null && _l !== void 0 ? _l : s2) !== null && _m !== void 0 ? _m : "log",
        strictRequired: (_p = (_o = o2.strictRequired) !== null && _o !== void 0 ? _o : s2) !== null && _p !== void 0 ? _p : false,
        code: o2.code ? { ...o2.code, optimize, regExp } : { optimize, regExp },
        loopRequired: (_q = o2.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
        loopEnum: (_r = o2.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
        meta: (_s = o2.meta) !== null && _s !== void 0 ? _s : true,
        messages: (_t = o2.messages) !== null && _t !== void 0 ? _t : true,
        inlineRefs: (_u = o2.inlineRefs) !== null && _u !== void 0 ? _u : true,
        schemaId: (_v = o2.schemaId) !== null && _v !== void 0 ? _v : "$id",
        addUsedSchema: (_w = o2.addUsedSchema) !== null && _w !== void 0 ? _w : true,
        validateSchema: (_x = o2.validateSchema) !== null && _x !== void 0 ? _x : true,
        validateFormats: (_y = o2.validateFormats) !== null && _y !== void 0 ? _y : true,
        unicodeRegExp: (_z = o2.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
        int32range: (_0 = o2.int32range) !== null && _0 !== void 0 ? _0 : true,
        uriResolver
      };
    }
    __name(requiredOptions, "requiredOptions");
    var Ajv2 = class {
      static {
        __name(this, "Ajv");
      }
      constructor(opts = {}) {
        this.schemas = {};
        this.refs = {};
        this.formats = {};
        this._compilations = /* @__PURE__ */ new Set();
        this._loading = {};
        this._cache = /* @__PURE__ */ new Map();
        opts = this.opts = { ...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, schemaId } = this.opts;
        let _dataRefSchema = $dataRefSchema;
        if (schemaId === "id") {
          _dataRefSchema = { ...$dataRefSchema };
          _dataRefSchema.id = _dataRefSchema.$id;
          delete _dataRefSchema.$id;
        }
        if (meta && $data)
          this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
      }
      defaultMeta() {
        const { meta, schemaId } = this.opts;
        return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : 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, meta) {
        if (typeof this.opts.loadSchema != "function") {
          throw new Error("options.loadSchema should be a function");
        }
        const { loadSchema } = this.opts;
        return runCompileAsync.call(this, schema, meta);
        async function runCompileAsync(_schema, _meta) {
          await loadMetaSchema.call(this, _schema.$schema);
          const sch = this._addSchema(_schema, _meta);
          return sch.validate || _compileAsync.call(this, sch);
        }
        __name(runCompileAsync, "runCompileAsync");
        async function loadMetaSchema($ref) {
          if ($ref && !this.getSchema($ref)) {
            await runCompileAsync.call(this, { $ref }, true);
          }
        }
        __name(loadMetaSchema, "loadMetaSchema");
        async function _compileAsync(sch) {
          try {
            return this._compileSchemaEnv(sch);
          } catch (e2) {
            if (!(e2 instanceof ref_error_1.default))
              throw e2;
            checkLoaded.call(this, e2);
            await loadMissingSchema.call(this, e2.missingSchema);
            return _compileAsync.call(this, sch);
          }
        }
        __name(_compileAsync, "_compileAsync");
        function checkLoaded({ missingSchema: ref, missingRef }) {
          if (this.refs[ref]) {
            throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
          }
        }
        __name(checkLoaded, "checkLoaded");
        async function loadMissingSchema(ref) {
          const _schema = await _loadSchema.call(this, ref);
          if (!this.refs[ref])
            await loadMetaSchema.call(this, _schema.$schema);
          if (!this.refs[ref])
            this.addSchema(_schema, ref, meta);
        }
        __name(loadMissingSchema, "loadMissingSchema");
        async function _loadSchema(ref) {
          const p = this._loading[ref];
          if (p)
            return p;
          try {
            return await (this._loading[ref] = loadSchema(ref));
          } finally {
            delete this._loading[ref];
          }
        }
        __name(_loadSchema, "_loadSchema");
      }
      // 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 id;
        if (typeof schema === "object") {
          const { schemaId } = this.opts;
          id = schema[schemaId];
          if (id !== void 0 && typeof id != "string") {
            throw new Error(`schema ${schemaId} must be string`);
          }
        }
        key = (0, resolve_1.normalizeId)(key || id);
        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 $schema;
        $schema = schema.$schema;
        if ($schema !== void 0 && typeof $schema != "string") {
          throw new Error("$schema must be a string");
        }
        $schema = $schema || this.opts.defaultMeta || this.defaultMeta();
        if (!$schema) {
          this.logger.warn("meta-schema not available");
          this.errors = null;
          return true;
        }
        const valid = this.validate($schema, 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 id = schemaKeyRef[this.opts.schemaId];
            if (id) {
              id = (0, resolve_1.normalizeId)(id);
              delete this.schemas[id];
              delete this.refs[id];
            }
            return this;
          }
          default:
            throw new Error("ajv.removeSchema: invalid parameter");
        }
      }
      // add "vocabulary" - a collection of keywords
      addVocabulary(definitions) {
        for (const def2 of definitions)
          this.addKeyword(def2);
        return this;
      }
      addKeyword(kwdOrDef, def2) {
        let keyword;
        if (typeof kwdOrDef == "string") {
          keyword = kwdOrDef;
          if (typeof def2 == "object") {
            this.logger.warn("these parameters are deprecated, see docs for addKeyword");
            def2.keyword = keyword;
          }
        } else if (typeof kwdOrDef == "object" && def2 === void 0) {
          def2 = kwdOrDef;
          keyword = def2.keyword;
          if (Array.isArray(keyword) && !keyword.length) {
            throw new Error("addKeywords: keyword must be string or non-empty array");
          }
        } else {
          throw new Error("invalid addKeywords parameters");
        }
        checkKeyword.call(this, keyword, def2);
        if (!def2) {
          (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
          return this;
        }
        keywordMetaschema.call(this, def2);
        const definition = {
          ...def2,
          type: (0, dataType_1.getJSONTypes)(def2.type),
          schemaType: (0, dataType_1.getJSONTypes)(def2.schemaType)
        };
        (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t2) => addRule.call(this, k, definition, t2)));
        return this;
      }
      getKeyword(keyword) {
        const rule = this.RULES.all[keyword];
        return typeof rule == "object" ? rule.definition : !!rule;
      }
      // Remove keyword
      removeKeyword(keyword) {
        const { RULES } = this;
        delete RULES.keywords[keyword];
        delete RULES.all[keyword];
        for (const group of RULES.rules) {
          const i = group.rules.findIndex((rule) => rule.keyword === keyword);
          if (i >= 0)
            group.rules.splice(i, 1);
        }
        return this;
      }
      // Add format
      addFormat(name3, format4) {
        if (typeof format4 == "string")
          format4 = new RegExp(format4);
        this.formats[name3] = format4;
        return this;
      }
      errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) {
        if (!errors || errors.length === 0)
          return "No errors";
        return errors.map((e2) => `${dataVar}${e2.instancePath} ${e2.message}`).reduce((text, msg) => text + separator + msg);
      }
      $dataMetaSchema(metaSchema, keywordsJsonPointers) {
        const rules = this.RULES.all;
        metaSchema = JSON.parse(JSON.stringify(metaSchema));
        for (const jsonPointer of keywordsJsonPointers) {
          const segments = jsonPointer.split("/").slice(1);
          let keywords2 = metaSchema;
          for (const seg of segments)
            keywords2 = keywords2[seg];
          for (const key in rules) {
            const rule = rules[key];
            if (typeof rule != "object")
              continue;
            const { $data } = rule.definition;
            const schema = keywords2[key];
            if ($data && schema)
              keywords2[key] = schemaOrData(schema);
          }
        }
        return metaSchema;
      }
      _removeAllSchemas(schemas, regex3) {
        for (const keyRef in schemas) {
          const sch = schemas[keyRef];
          if (!regex3 || regex3.test(keyRef)) {
            if (typeof sch == "string") {
              delete schemas[keyRef];
            } else if (sch && !sch.meta) {
              this._cache.delete(sch.schema);
              delete schemas[keyRef];
            }
          }
        }
      }
      _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
        let id;
        const { schemaId } = this.opts;
        if (typeof schema == "object") {
          id = 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)(id || baseId);
        const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
        sch = new compile_1.SchemaEnv({ schema, schemaId, meta, 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(id) {
        if (this.schemas[id] || this.refs[id]) {
          throw new Error(`schema with key or id "${id}" 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;
    exports2.default = Ajv2;
    function checkOptions(checkOpts, options2, msg, log = "error") {
      for (const key in checkOpts) {
        const opt = key;
        if (opt in options2)
          this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
      }
    }
    __name(checkOptions, "checkOptions");
    function getSchEnv(keyRef) {
      keyRef = (0, resolve_1.normalizeId)(keyRef);
      return this.schemas[keyRef] || this.refs[keyRef];
    }
    __name(getSchEnv, "getSchEnv");
    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);
    }
    __name(addInitialSchemas, "addInitialSchemas");
    function addInitialFormats() {
      for (const name3 in this.opts.formats) {
        const format4 = this.opts.formats[name3];
        if (format4)
          this.addFormat(name3, format4);
      }
    }
    __name(addInitialFormats, "addInitialFormats");
    function addInitialKeywords(defs) {
      if (Array.isArray(defs)) {
        this.addVocabulary(defs);
        return;
      }
      this.logger.warn("keywords option as map is deprecated, pass array");
      for (const keyword in defs) {
        const def2 = defs[keyword];
        if (!def2.keyword)
          def2.keyword = keyword;
        this.addKeyword(def2);
      }
    }
    __name(addInitialKeywords, "addInitialKeywords");
    function getMetaSchemaOptions() {
      const metaOpts = { ...this.opts };
      for (const opt of META_IGNORE_OPTIONS)
        delete metaOpts[opt];
      return metaOpts;
    }
    __name(getMetaSchemaOptions, "getMetaSchemaOptions");
    var noLogs = { log() {
    }, warn() {
    }, error() {
    } };
    function getLogger(logger6) {
      if (logger6 === false)
        return noLogs;
      if (logger6 === void 0)
        return console;
      if (logger6.log && logger6.warn && logger6.error)
        return logger6;
      throw new Error("logger must implement log, warn and error methods");
    }
    __name(getLogger, "getLogger");
    var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
    function checkKeyword(keyword, def2) {
      const { RULES } = this;
      (0, util_1.eachItem)(keyword, (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 (!def2)
        return;
      if (def2.$data && !("code" in def2 || "validate" in def2)) {
        throw new Error('$data keyword must have "code" or "validate" function');
      }
    }
    __name(checkKeyword, "checkKeyword");
    function addRule(keyword, definition, dataType) {
      var _a6;
      const post = definition === null || definition === void 0 ? void 0 : definition.post;
      if (dataType && post)
        throw new Error('keyword with "post" flag cannot have "type"');
      const { RULES } = this;
      let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t2 }) => t2 === dataType);
      if (!ruleGroup) {
        ruleGroup = { type: dataType, rules: [] };
        RULES.rules.push(ruleGroup);
      }
      RULES.keywords[keyword] = true;
      if (!definition)
        return;
      const rule = {
        keyword,
        definition: {
          ...definition,
          type: (0, dataType_1.getJSONTypes)(definition.type),
          schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType)
        }
      };
      if (definition.before)
        addBeforeRule.call(this, ruleGroup, rule, definition.before);
      else
        ruleGroup.rules.push(rule);
      RULES.all[keyword] = rule;
      (_a6 = definition.implements) === null || _a6 === void 0 ? void 0 : _a6.forEach((kwd) => this.addKeyword(kwd));
    }
    __name(addRule, "addRule");
    function addBeforeRule(ruleGroup, rule, before) {
      const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
      if (i >= 0) {
        ruleGroup.rules.splice(i, 0, rule);
      } else {
        ruleGroup.rules.push(rule);
        this.logger.warn(`rule ${before} is not defined`);
      }
    }
    __name(addBeforeRule, "addBeforeRule");
    function keywordMetaschema(def2) {
      let { metaSchema } = def2;
      if (metaSchema === void 0)
        return;
      if (def2.$data && this.opts.$data)
        metaSchema = schemaOrData(metaSchema);
      def2.validateSchema = this.compile(metaSchema, true);
    }
    __name(keywordMetaschema, "keywordMetaschema");
    var $dataRef = {
      $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"
    };
    function schemaOrData(schema) {
      return { anyOf: [schema, $dataRef] };
    }
    __name(schemaOrData, "schemaOrData");
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/id.js
var require_id2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/id.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var def2 = {
      keyword: "id",
      code() {
        throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/ref.js
var require_ref2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/ref.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.callRef = exports2.getValidate = void 0;
    var ref_error_1 = require_ref_error2();
    var code_1 = require_code4();
    var codegen_1 = require_codegen2();
    var names_1 = require_names2();
    var compile_1 = require_compile2();
    var util_1 = require_util10();
    var def2 = {
      keyword: "$ref",
      schemaType: "string",
      code(cxt) {
        const { gen, schema: $ref, it } = cxt;
        const { baseId, schemaEnv: env7, validateName: validateName2, opts, self: self2 } = it;
        const { root } = env7;
        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(it.opts.uriResolver, baseId, $ref);
        if (schOrEnv instanceof compile_1.SchemaEnv)
          return callValidate(schOrEnv);
        return inlineRefSchema(schOrEnv);
        function callRootRef() {
          if (env7 === root)
            return callRef(cxt, validateName2, env7, env7.$async);
          const rootName = gen.scopeValue("root", { ref: root });
          return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async);
        }
        __name(callRootRef, "callRootRef");
        function callValidate(sch) {
          const v = getValidate(cxt, sch);
          callRef(cxt, v, sch, sch.$async);
        }
        __name(callValidate, "callValidate");
        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);
        }
        __name(inlineRefSchema, "inlineRefSchema");
      }
    };
    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`;
    }
    __name(getValidate, "getValidate");
    exports2.getValidate = getValidate;
    function callRef(cxt, v, sch, $async) {
      const { gen, it } = cxt;
      const { allErrors, schemaEnv: env7, opts } = it;
      const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
      if ($async)
        callAsyncRef();
      else
        callSyncRef();
      function callAsyncRef() {
        if (!env7.$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);
        }, (e2) => {
          gen.if((0, codegen_1._)`!(${e2} instanceof ${it.ValidationError})`, () => gen.throw(e2));
          addErrorsFrom(e2);
          if (!allErrors)
            gen.assign(valid, false);
        });
        cxt.ok(valid);
      }
      __name(callAsyncRef, "callAsyncRef");
      function callSyncRef() {
        cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
      }
      __name(callSyncRef, "callSyncRef");
      function addErrorsFrom(source2) {
        const errs = (0, codegen_1._)`${source2}.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`);
      }
      __name(addErrorsFrom, "addErrorsFrom");
      function addEvaluatedFrom(source2) {
        var _a6;
        if (!it.opts.unevaluated)
          return;
        const schEvaluated = (_a6 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a6 === void 0 ? void 0 : _a6.evaluated;
        if (it.props !== true) {
          if (schEvaluated && !schEvaluated.dynamicProps) {
            if (schEvaluated.props !== void 0) {
              it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
            }
          } else {
            const props = gen.var("props", (0, codegen_1._)`${source2}.evaluated.props`);
            it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
          }
        }
        if (it.items !== true) {
          if (schEvaluated && !schEvaluated.dynamicItems) {
            if (schEvaluated.items !== void 0) {
              it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
            }
          } else {
            const items = gen.var("items", (0, codegen_1._)`${source2}.evaluated.items`);
            it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
          }
        }
      }
      __name(addEvaluatedFrom, "addEvaluatedFrom");
    }
    __name(callRef, "callRef");
    exports2.callRef = callRef;
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/index.js
var require_core4 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var id_1 = require_id2();
    var ref_1 = require_ref2();
    var core = [
      "$schema",
      "$id",
      "$defs",
      "$vocabulary",
      { keyword: "$comment" },
      "definitions",
      id_1.default,
      ref_1.default
    ];
    exports2.default = core;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitNumber.js
var require_limitNumber2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var ops = codegen_1.operators;
    var 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 }
    };
    var error = {
      message: /* @__PURE__ */ __name(({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, "message"),
      params: /* @__PURE__ */ __name(({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: Object.keys(KWDs),
      type: "number",
      schemaType: "number",
      $data: true,
      error,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/multipleOf.js
var require_multipleOf2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var error = {
      message: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, "message"),
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: "multipleOf",
      type: "number",
      schemaType: "number",
      $data: true,
      error,
      code(cxt) {
        const { gen, data, schemaCode, it } = cxt;
        const prec = it.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}))`);
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/runtime/ucs2length.js
var require_ucs2length2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/runtime/ucs2length.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    function ucs2length(str2) {
      const len = str2.length;
      let length = 0;
      let pos2 = 0;
      let value;
      while (pos2 < len) {
        length++;
        value = str2.charCodeAt(pos2++);
        if (value >= 55296 && value <= 56319 && pos2 < len) {
          value = str2.charCodeAt(pos2);
          if ((value & 64512) === 56320)
            pos2++;
        }
      }
      return length;
    }
    __name(ucs2length, "ucs2length");
    exports2.default = ucs2length;
    ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitLength.js
var require_limitLength2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var ucs2length_1 = require_ucs2length2();
    var error = {
      message({ keyword, schemaCode }) {
        const comp = keyword === "maxLength" ? "more" : "fewer";
        return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`;
      },
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: ["maxLength", "minLength"],
      type: "string",
      schemaType: "number",
      $data: true,
      error,
      code(cxt) {
        const { keyword, data, schemaCode, it } = cxt;
        const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
        const len = it.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._)`${len} ${op} ${schemaCode}`);
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/pattern.js
var require_pattern2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code4();
    var codegen_1 = require_codegen2();
    var error = {
      message: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, "message"),
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: "pattern",
      type: "string",
      schemaType: "string",
      $data: true,
      error,
      code(cxt) {
        const { data, $data, schema, schemaCode, it } = cxt;
        const u = it.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})`);
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitProperties.js
var require_limitProperties2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var error = {
      message({ keyword, schemaCode }) {
        const comp = keyword === "maxProperties" ? "more" : "fewer";
        return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`;
      },
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: ["maxProperties", "minProperties"],
      type: "object",
      schemaType: "number",
      $data: true,
      error,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`);
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/required.js
var require_required2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/required.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code4();
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var error = {
      message: /* @__PURE__ */ __name(({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, "message"),
      params: /* @__PURE__ */ __name(({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}`, "params")
    };
    var def2 = {
      keyword: "required",
      type: "object",
      schemaType: "array",
      $data: true,
      error,
      code(cxt) {
        const { gen, schema, schemaCode, data, $data, it } = cxt;
        const { opts } = it;
        if (!$data && schema.length === 0)
          return;
        const useLoop = schema.length >= opts.loopRequired;
        if (it.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 = it.schemaEnv.baseId + it.errSchemaPath;
              const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
              (0, util_1.checkStrictMode)(it, msg, it.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);
            }
          }
        }
        __name(allErrorsMode, "allErrorsMode");
        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();
          }
        }
        __name(exitOnErrorMode, "exitOnErrorMode");
        function loopAllRequired() {
          gen.forOf("prop", schemaCode, (prop) => {
            cxt.setParams({ missingProperty: prop });
            gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
          });
        }
        __name(loopAllRequired, "loopAllRequired");
        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);
        }
        __name(loopUntilMissing, "loopUntilMissing");
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitItems.js
var require_limitItems2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var error = {
      message({ keyword, schemaCode }) {
        const comp = keyword === "maxItems" ? "more" : "fewer";
        return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`;
      },
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: ["maxItems", "minItems"],
      type: "array",
      schemaType: "number",
      $data: true,
      error,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`);
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/runtime/equal.js
var require_equal2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/runtime/equal.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var equal = require_fast_deep_equal();
    equal.code = 'require("ajv/dist/runtime/equal").default';
    exports2.default = equal;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js
var require_uniqueItems2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var dataType_1 = require_dataType2();
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var equal_1 = require_equal2();
    var error = {
      message: /* @__PURE__ */ __name(({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, "message"),
      params: /* @__PURE__ */ __name(({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}`, "params")
    };
    var def2 = {
      keyword: "uniqueItems",
      type: "array",
      schemaType: "boolean",
      $data: true,
      error,
      code(cxt) {
        const { gen, data, $data, schema, parentSchema, schemaCode, it } = 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 i = gen.let("i", (0, codegen_1._)`${data}.length`);
          const j = gen.let("j");
          cxt.setParams({ i, j });
          gen.assign(valid, true);
          gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
        }
        __name(validateUniqueItems, "validateUniqueItems");
        function canOptimize() {
          return itemTypes.length > 0 && !itemTypes.some((t2) => t2 === "object" || t2 === "array");
        }
        __name(canOptimize, "canOptimize");
        function loopN(i, j) {
          const item = gen.name("item");
          const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
          const indices = gen.const("indices", (0, codegen_1._)`{}`);
          gen.for((0, codegen_1._)`;${i}--;`, () => {
            gen.let(item, (0, codegen_1._)`${data}[${i}]`);
            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}] = ${i}`);
          });
        }
        __name(loopN, "loopN");
        function loopN2(i, j) {
          const eql = (0, util_1.useFunc)(gen, equal_1.default);
          const outer = gen.name("outer");
          gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => {
            cxt.error();
            gen.assign(valid, false).break(outer);
          })));
        }
        __name(loopN2, "loopN2");
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/const.js
var require_const2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/const.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var equal_1 = require_equal2();
    var error = {
      message: "must be equal to constant",
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: "const",
      $data: true,
      error,
      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}`);
        }
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/enum.js
var require_enum2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var equal_1 = require_equal2();
    var error = {
      message: "must be equal to one of the allowed values",
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: "enum",
      schemaType: "array",
      $data: true,
      error,
      code(cxt) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        if (!$data && schema.length === 0)
          throw new Error("enum must have non-empty array");
        const useLoop = schema.length >= it.opts.loopEnum;
        let eql;
        const getEql = /* @__PURE__ */ __name(() => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default), "getEql");
        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, i) => equalCode(vSchema, i)));
        }
        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()));
        }
        __name(loopEnum, "loopEnum");
        function equalCode(vSchema, i) {
          const sch = schema[i];
          return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`;
        }
        __name(equalCode, "equalCode");
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/index.js
var require_validation3 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var limitNumber_1 = require_limitNumber2();
    var multipleOf_1 = require_multipleOf2();
    var limitLength_1 = require_limitLength2();
    var pattern_1 = require_pattern2();
    var limitProperties_1 = require_limitProperties2();
    var required_1 = require_required2();
    var limitItems_1 = require_limitItems2();
    var uniqueItems_1 = require_uniqueItems2();
    var const_1 = require_const2();
    var enum_1 = require_enum2();
    var validation2 = [
      // 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
    ];
    exports2.default = validation2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js
var require_additionalItems2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateAdditionalItems = void 0;
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var error = {
      message: /* @__PURE__ */ __name(({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, "message"),
      params: /* @__PURE__ */ __name(({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`, "params")
    };
    var def2 = {
      keyword: "additionalItems",
      type: "array",
      schemaType: ["boolean", "object"],
      before: "uniqueItems",
      error,
      code(cxt) {
        const { parentSchema, it } = cxt;
        const { items } = parentSchema;
        if (!Array.isArray(items)) {
          (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
          return;
        }
        validateAdditionalItems(cxt, items);
      }
    };
    function validateAdditionalItems(cxt, items) {
      const { gen, schema, data, keyword, it } = cxt;
      it.items = true;
      const len = gen.const("len", (0, codegen_1._)`${data}.length`);
      if (schema === false) {
        cxt.setParams({ len: items.length });
        cxt.pass((0, codegen_1._)`${len} <= ${items.length}`);
      } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
        const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`);
        gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
        cxt.ok(valid);
      }
      function validateItems(valid) {
        gen.forRange("i", items.length, len, (i) => {
          cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);
          if (!it.allErrors)
            gen.if((0, codegen_1.not)(valid), () => gen.break());
        });
      }
      __name(validateItems, "validateItems");
    }
    __name(validateAdditionalItems, "validateAdditionalItems");
    exports2.validateAdditionalItems = validateAdditionalItems;
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items.js
var require_items2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateTuple = void 0;
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var code_1 = require_code4();
    var def2 = {
      keyword: "items",
      type: "array",
      schemaType: ["object", "array", "boolean"],
      before: "uniqueItems",
      code(cxt) {
        const { schema, it } = cxt;
        if (Array.isArray(schema))
          return validateTuple(cxt, "additionalItems", schema);
        it.items = true;
        if ((0, util_1.alwaysValidSchema)(it, schema))
          return;
        cxt.ok((0, code_1.validateArray)(cxt));
      }
    };
    function validateTuple(cxt, extraItems, schArr = cxt.schema) {
      const { gen, parentSchema, data, keyword, it } = cxt;
      checkStrictTuple(parentSchema);
      if (it.opts.unevaluated && schArr.length && it.items !== true) {
        it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);
      }
      const valid = gen.name("valid");
      const len = gen.const("len", (0, codegen_1._)`${data}.length`);
      schArr.forEach((sch, i) => {
        if ((0, util_1.alwaysValidSchema)(it, sch))
          return;
        gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({
          keyword,
          schemaProp: i,
          dataProp: i
        }, valid));
        cxt.ok(valid);
      });
      function checkStrictTuple(sch) {
        const { opts, errSchemaPath } = it;
        const l2 = schArr.length;
        const fullTuple = l2 === sch.minItems && (l2 === sch.maxItems || sch[extraItems] === false);
        if (opts.strictTuples && !fullTuple) {
          const msg = `"${keyword}" is ${l2}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
          (0, util_1.checkStrictMode)(it, msg, opts.strictTuples);
        }
      }
      __name(checkStrictTuple, "checkStrictTuple");
    }
    __name(validateTuple, "validateTuple");
    exports2.validateTuple = validateTuple;
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js
var require_prefixItems2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var items_1 = require_items2();
    var def2 = {
      keyword: "prefixItems",
      type: "array",
      schemaType: ["array"],
      before: "uniqueItems",
      code: /* @__PURE__ */ __name((cxt) => (0, items_1.validateTuple)(cxt, "items"), "code")
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items2020.js
var require_items20202 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var code_1 = require_code4();
    var additionalItems_1 = require_additionalItems2();
    var error = {
      message: /* @__PURE__ */ __name(({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, "message"),
      params: /* @__PURE__ */ __name(({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`, "params")
    };
    var def2 = {
      keyword: "items",
      type: "array",
      schemaType: ["object", "boolean"],
      before: "uniqueItems",
      error,
      code(cxt) {
        const { schema, parentSchema, it } = cxt;
        const { prefixItems } = parentSchema;
        it.items = true;
        if ((0, util_1.alwaysValidSchema)(it, schema))
          return;
        if (prefixItems)
          (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
        else
          cxt.ok((0, code_1.validateArray)(cxt));
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/contains.js
var require_contains2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var error = {
      message: /* @__PURE__ */ __name(({ params: { min, max } }) => max === 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 ${max} valid item(s)`, "message"),
      params: /* @__PURE__ */ __name(({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}`, "params")
    };
    var def2 = {
      keyword: "contains",
      type: "array",
      schemaType: ["object", "boolean"],
      before: "uniqueItems",
      trackErrors: true,
      error,
      code(cxt) {
        const { gen, schema, parentSchema, data, it } = cxt;
        let min;
        let max;
        const { minContains, maxContains } = parentSchema;
        if (it.opts.next) {
          min = minContains === void 0 ? 1 : minContains;
          max = maxContains;
        } else {
          min = 1;
        }
        const len = gen.const("len", (0, codegen_1._)`${data}.length`);
        cxt.setParams({ min, max });
        if (max === void 0 && min === 0) {
          (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
          return;
        }
        if (max !== void 0 && min > max) {
          (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
          cxt.fail();
          return;
        }
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
          let cond = (0, codegen_1._)`${len} >= ${min}`;
          if (max !== void 0)
            cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`;
          cxt.pass(cond);
          return;
        }
        it.items = true;
        const valid = gen.name("valid");
        if (max === void 0 && min === 1) {
          validateItems(valid, () => gen.if(valid, () => gen.break()));
        } else if (min === 0) {
          gen.let(valid, true);
          if (max !== 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)));
        }
        __name(validateItemsWithCount, "validateItemsWithCount");
        function validateItems(_valid, block2) {
          gen.forRange("i", 0, len, (i) => {
            cxt.subschema({
              keyword: "contains",
              dataProp: i,
              dataPropType: util_1.Type.Num,
              compositeRule: true
            }, _valid);
            block2();
          });
        }
        __name(validateItems, "validateItems");
        function checkLimits(count) {
          gen.code((0, codegen_1._)`${count}++`);
          if (max === void 0) {
            gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());
          } else {
            gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break());
            if (min === 1)
              gen.assign(valid, true);
            else
              gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));
          }
        }
        __name(checkLimits, "checkLimits");
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/dependencies.js
var require_dependencies2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateSchemaDeps = exports2.validatePropertyDeps = exports2.error = void 0;
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var code_1 = require_code4();
    exports2.error = {
      message: /* @__PURE__ */ __name(({ 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`;
      }, "message"),
      params: /* @__PURE__ */ __name(({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`, "params")
      // TODO change to reference
    };
    var def2 = {
      keyword: "dependencies",
      type: "object",
      schemaType: "object",
      error: exports2.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];
    }
    __name(splitDependencies, "splitDependencies");
    function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
      const { gen, data, it } = 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 hasProperty2 = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
        cxt.setParams({
          property: prop,
          depsCount: deps.length,
          deps: deps.join(", ")
        });
        if (it.allErrors) {
          gen.if(hasProperty2, () => {
            for (const depProp of deps) {
              (0, code_1.checkReportMissingProp)(cxt, depProp);
            }
          });
        } else {
          gen.if((0, codegen_1._)`${hasProperty2} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
          (0, code_1.reportMissingProp)(cxt, missing);
          gen.else();
        }
      }
    }
    __name(validatePropertyDeps, "validatePropertyDeps");
    exports2.validatePropertyDeps = validatePropertyDeps;
    function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
      const { gen, data, keyword, it } = cxt;
      const valid = gen.name("valid");
      for (const prop in schemaDeps) {
        if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))
          continue;
        gen.if(
          (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties),
          () => {
            const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
            cxt.mergeValidEvaluated(schCxt, valid);
          },
          () => gen.var(valid, true)
          // TODO var
        );
        cxt.ok(valid);
      }
    }
    __name(validateSchemaDeps, "validateSchemaDeps");
    exports2.validateSchemaDeps = validateSchemaDeps;
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js
var require_propertyNames2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var error = {
      message: "property name must be valid",
      params: /* @__PURE__ */ __name(({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}`, "params")
    };
    var def2 = {
      keyword: "propertyNames",
      type: "object",
      schemaType: ["object", "boolean"],
      error,
      code(cxt) {
        const { gen, schema, data, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, 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 (!it.allErrors)
              gen.break();
          });
        });
        cxt.ok(valid);
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js
var require_additionalProperties2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code4();
    var codegen_1 = require_codegen2();
    var names_1 = require_names2();
    var util_1 = require_util10();
    var error = {
      message: "must NOT have additional properties",
      params: /* @__PURE__ */ __name(({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}`, "params")
    };
    var def2 = {
      keyword: "additionalProperties",
      type: ["object"],
      schemaType: ["boolean", "object"],
      allowUndefined: true,
      trackErrors: true,
      error,
      code(cxt) {
        const { gen, schema, parentSchema, data, errsCount, it } = cxt;
        if (!errsCount)
          throw new Error("ajv implementation error");
        const { allErrors, opts } = it;
        it.props = true;
        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, 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));
          });
        }
        __name(checkAdditionalProperties, "checkAdditionalProperties");
        function isAdditional(key) {
          let definedProp;
          if (props.length > 8) {
            const propsSchema = (0, util_1.schemaRefOrVal)(it, 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);
        }
        __name(isAdditional, "isAdditional");
        function deleteAdditional(key) {
          gen.code((0, codegen_1._)`delete ${data}[${key}]`);
        }
        __name(deleteAdditional, "deleteAdditional");
        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)(it, 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());
            }
          }
        }
        __name(additionalPropertyCode, "additionalPropertyCode");
        function applyAdditionalSchema(key, valid, errors) {
          const subschema = {
            keyword: "additionalProperties",
            dataProp: key,
            dataPropType: util_1.Type.Str
          };
          if (errors === false) {
            Object.assign(subschema, {
              compositeRule: true,
              createErrors: false,
              allErrors: false
            });
          }
          cxt.subschema(subschema, valid);
        }
        __name(applyAdditionalSchema, "applyAdditionalSchema");
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/properties.js
var require_properties2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var validate_1 = require_validate2();
    var code_1 = require_code4();
    var util_1 = require_util10();
    var additionalProperties_1 = require_additionalProperties2();
    var def2 = {
      keyword: "properties",
      type: "object",
      schemaType: "object",
      code(cxt) {
        const { gen, schema, parentSchema, data, it } = cxt;
        if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) {
          additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
        }
        const allProps = (0, code_1.allSchemaProperties)(schema);
        for (const prop of allProps) {
          it.definedProperties.add(prop);
        }
        if (it.opts.unevaluated && allProps.length && it.props !== true) {
          it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
        }
        const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
        if (properties.length === 0)
          return;
        const valid = gen.name("valid");
        for (const prop of properties) {
          if (hasDefault(prop)) {
            applyPropertySchema(prop);
          } else {
            gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));
            applyPropertySchema(prop);
            if (!it.allErrors)
              gen.else().var(valid, true);
            gen.endIf();
          }
          cxt.it.definedProperties.add(prop);
          cxt.ok(valid);
        }
        function hasDefault(prop) {
          return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0;
        }
        __name(hasDefault, "hasDefault");
        function applyPropertySchema(prop) {
          cxt.subschema({
            keyword: "properties",
            schemaProp: prop,
            dataProp: prop
          }, valid);
        }
        __name(applyPropertySchema, "applyPropertySchema");
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js
var require_patternProperties2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code4();
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var util_2 = require_util10();
    var def2 = {
      keyword: "patternProperties",
      type: "object",
      schemaType: "object",
      code(cxt) {
        const { gen, schema, data, parentSchema, it } = cxt;
        const { opts } = it;
        const patterns = (0, code_1.allSchemaProperties)(schema);
        const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));
        if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) {
          return;
        }
        const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
        const valid = gen.name("valid");
        if (it.props !== true && !(it.props instanceof codegen_1.Name)) {
          it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
        }
        const { props } = it;
        validatePatternProperties();
        function validatePatternProperties() {
          for (const pat of patterns) {
            if (checkProperties)
              checkMatchingProperties(pat);
            if (it.allErrors) {
              validateProperties(pat);
            } else {
              gen.var(valid, true);
              validateProperties(pat);
              gen.if(valid);
            }
          }
        }
        __name(validatePatternProperties, "validatePatternProperties");
        function checkMatchingProperties(pat) {
          for (const prop in checkProperties) {
            if (new RegExp(pat).test(prop)) {
              (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
            }
          }
        }
        __name(checkMatchingProperties, "checkMatchingProperties");
        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 (it.opts.unevaluated && props !== true) {
                gen.assign((0, codegen_1._)`${props}[${key}]`, true);
              } else if (!alwaysValid && !it.allErrors) {
                gen.if((0, codegen_1.not)(valid), () => gen.break());
              }
            });
          });
        }
        __name(validateProperties, "validateProperties");
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/not.js
var require_not2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var util_1 = require_util10();
    var def2 = {
      keyword: "not",
      schemaType: ["object", "boolean"],
      trackErrors: true,
      code(cxt) {
        const { gen, schema, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, 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" }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/anyOf.js
var require_anyOf2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code4();
    var def2 = {
      keyword: "anyOf",
      schemaType: "array",
      trackErrors: true,
      code: code_1.validateUnion,
      error: { message: "must match a schema in anyOf" }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/oneOf.js
var require_oneOf2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var error = {
      message: "must match exactly one schema in oneOf",
      params: /* @__PURE__ */ __name(({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}`, "params")
    };
    var def2 = {
      keyword: "oneOf",
      schemaType: "array",
      trackErrors: true,
      error,
      code(cxt) {
        const { gen, schema, parentSchema, it } = cxt;
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        if (it.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, i) => {
            let schCxt;
            if ((0, util_1.alwaysValidSchema)(it, sch)) {
              gen.var(schValid, true);
            } else {
              schCxt = cxt.subschema({
                keyword: "oneOf",
                schemaProp: i,
                compositeRule: true
              }, schValid);
            }
            if (i > 0) {
              gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else();
            }
            gen.if(schValid, () => {
              gen.assign(valid, true);
              gen.assign(passing, i);
              if (schCxt)
                cxt.mergeEvaluated(schCxt, codegen_1.Name);
            });
          });
        }
        __name(validateOneOf, "validateOneOf");
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/allOf.js
var require_allOf2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var util_1 = require_util10();
    var def2 = {
      keyword: "allOf",
      schemaType: "array",
      code(cxt) {
        const { gen, schema, it } = cxt;
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        const valid = gen.name("valid");
        schema.forEach((sch, i) => {
          if ((0, util_1.alwaysValidSchema)(it, sch))
            return;
          const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
          cxt.ok(valid);
          cxt.mergeEvaluated(schCxt);
        });
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/if.js
var require_if2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var error = {
      message: /* @__PURE__ */ __name(({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, "message"),
      params: /* @__PURE__ */ __name(({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}`, "params")
    };
    var def2 = {
      keyword: "if",
      schemaType: ["object", "boolean"],
      trackErrors: true,
      error,
      code(cxt) {
        const { gen, parentSchema, it } = cxt;
        if (parentSchema.then === void 0 && parentSchema.else === void 0) {
          (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
        }
        const hasThen = hasSchema(it, "then");
        const hasElse = hasSchema(it, "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);
        }
        __name(validateIf, "validateIf");
        function validateClause(keyword, ifClause) {
          return () => {
            const schCxt = cxt.subschema({ keyword }, schValid);
            gen.assign(valid, schValid);
            cxt.mergeValidEvaluated(schCxt, valid);
            if (ifClause)
              gen.assign(ifClause, (0, codegen_1._)`${keyword}`);
            else
              cxt.setParams({ ifClause: keyword });
          };
        }
        __name(validateClause, "validateClause");
      }
    };
    function hasSchema(it, keyword) {
      const schema = it.schema[keyword];
      return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema);
    }
    __name(hasSchema, "hasSchema");
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/thenElse.js
var require_thenElse2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var util_1 = require_util10();
    var def2 = {
      keyword: ["then", "else"],
      schemaType: ["object", "boolean"],
      code({ keyword, parentSchema, it }) {
        if (parentSchema.if === void 0)
          (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/index.js
var require_applicator2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var additionalItems_1 = require_additionalItems2();
    var prefixItems_1 = require_prefixItems2();
    var items_1 = require_items2();
    var items2020_1 = require_items20202();
    var contains_1 = require_contains2();
    var dependencies_1 = require_dependencies2();
    var propertyNames_1 = require_propertyNames2();
    var additionalProperties_1 = require_additionalProperties2();
    var properties_1 = require_properties2();
    var patternProperties_1 = require_patternProperties2();
    var not_1 = require_not2();
    var anyOf_1 = require_anyOf2();
    var oneOf_1 = require_oneOf2();
    var allOf_1 = require_allOf2();
    var if_1 = require_if2();
    var thenElse_1 = require_thenElse2();
    function getApplicator(draft2020 = false) {
      const applicator = [
        // 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)
        applicator.push(prefixItems_1.default, items2020_1.default);
      else
        applicator.push(additionalItems_1.default, items_1.default);
      applicator.push(contains_1.default);
      return applicator;
    }
    __name(getApplicator, "getApplicator");
    exports2.default = getApplicator;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/format/format.js
var require_format3 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/format/format.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var error = {
      message: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, "message"),
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: "format",
      type: ["number", "string"],
      schemaType: "string",
      $data: true,
      error,
      code(cxt, ruleType) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        const { opts, errSchemaPath, schemaEnv, self: self2 } = it;
        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 format4 = gen.let("format");
          gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format4, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format4, 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} && !${format4}`;
          }
          __name(unknownFmt, "unknownFmt");
          function invalidFmt() {
            const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format4}(${data}) : ${format4}(${data}))` : (0, codegen_1._)`${format4}(${data})`;
            const validData = (0, codegen_1._)`(typeof ${format4} == "function" ? ${callFormat} : ${format4}.test(${data}))`;
            return (0, codegen_1._)`${format4} && ${format4} !== true && ${fType} === ${ruleType} && !${validData}`;
          }
          __name(invalidFmt, "invalidFmt");
        }
        __name(validate$DataFormat, "validate$DataFormat");
        function validateFormat() {
          const formatDef = self2.formats[schema];
          if (!formatDef) {
            unknownFormat();
            return;
          }
          if (formatDef === true)
            return;
          const [fmtType, format4, 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}"`;
            }
            __name(unknownMsg, "unknownMsg");
          }
          __name(unknownFormat, "unknownFormat");
          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];
          }
          __name(getFormat, "getFormat");
          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 format4 == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`;
          }
          __name(validCondition, "validCondition");
        }
        __name(validateFormat, "validateFormat");
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/format/index.js
var require_format4 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/format/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var format_1 = require_format3();
    var format4 = [format_1.default];
    exports2.default = format4;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/metadata.js
var require_metadata2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/metadata.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.contentVocabulary = exports2.metadataVocabulary = void 0;
    exports2.metadataVocabulary = [
      "title",
      "description",
      "default",
      "deprecated",
      "readOnly",
      "writeOnly",
      "examples"
    ];
    exports2.contentVocabulary = [
      "contentMediaType",
      "contentEncoding",
      "contentSchema"
    ];
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/draft7.js
var require_draft72 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/draft7.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var core_1 = require_core4();
    var validation_1 = require_validation3();
    var applicator_1 = require_applicator2();
    var format_1 = require_format4();
    var metadata_1 = require_metadata2();
    var draft7Vocabularies = [
      core_1.default,
      validation_1.default,
      (0, applicator_1.default)(),
      format_1.default,
      metadata_1.metadataVocabulary,
      metadata_1.contentVocabulary
    ];
    exports2.default = draft7Vocabularies;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/discriminator/types.js
var require_types2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DiscrError = void 0;
    var DiscrError;
    (function(DiscrError2) {
      DiscrError2["Tag"] = "tag";
      DiscrError2["Mapping"] = "mapping";
    })(DiscrError || (exports2.DiscrError = DiscrError = {}));
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/discriminator/index.js
var require_discriminator2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var types_1 = require_types2();
    var compile_1 = require_compile2();
    var ref_error_1 = require_ref_error2();
    var util_1 = require_util10();
    var error = {
      message: /* @__PURE__ */ __name(({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, "message"),
      params: /* @__PURE__ */ __name(({ params: { discrError, tag: tag2, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag2}}`, "params")
    };
    var def2 = {
      keyword: "discriminator",
      type: "object",
      schemaType: "object",
      error,
      code(cxt) {
        const { gen, data, schema, parentSchema, it } = cxt;
        const { oneOf } = parentSchema;
        if (!it.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 (!oneOf)
          throw new Error("discriminator: requires oneOf keyword");
        const valid = gen.let("valid", false);
        const tag2 = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`);
        gen.if((0, codegen_1._)`typeof ${tag2} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag: tag2, tagName }));
        cxt.ok(valid);
        function validateMapping() {
          const mapping = getMapping();
          gen.if(false);
          for (const tagValue in mapping) {
            gen.elseIf((0, codegen_1._)`${tag2} === ${tagValue}`);
            gen.assign(valid, applyTagSchema(mapping[tagValue]));
          }
          gen.else();
          cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag: tag2, tagName });
          gen.endIf();
        }
        __name(validateMapping, "validateMapping");
        function applyTagSchema(schemaProp) {
          const _valid = gen.name("valid");
          const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
          cxt.mergeEvaluated(schCxt, codegen_1.Name);
          return _valid;
        }
        __name(applyTagSchema, "applyTagSchema");
        function getMapping() {
          var _a6;
          const oneOfMapping = {};
          const topRequired = hasRequired(parentSchema);
          let tagRequired = true;
          for (let i = 0; i < oneOf.length; i++) {
            let sch = oneOf[i];
            if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
              const ref = sch.$ref;
              sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);
              if (sch instanceof compile_1.SchemaEnv)
                sch = sch.schema;
              if (sch === void 0)
                throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
            }
            const propSch = (_a6 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a6 === void 0 ? void 0 : _a6[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, i);
          }
          if (!tagRequired)
            throw new Error(`discriminator: "${tagName}" must be required`);
          return oneOfMapping;
          function hasRequired({ required }) {
            return Array.isArray(required) && required.includes(tagName);
          }
          __name(hasRequired, "hasRequired");
          function addMappings(sch, i) {
            if (sch.const) {
              addMapping(sch.const, i);
            } else if (sch.enum) {
              for (const tagValue of sch.enum) {
                addMapping(tagValue, i);
              }
            } else {
              throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
            }
          }
          __name(addMappings, "addMappings");
          function addMapping(tagValue, i) {
            if (typeof tagValue != "string" || tagValue in oneOfMapping) {
              throw new Error(`discriminator: "${tagName}" values must be unique strings`);
            }
            oneOfMapping[tagValue] = i;
          }
          __name(addMapping, "addMapping");
        }
        __name(getMapping, "getMapping");
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/refs/json-schema-draft-07.json
var require_json_schema_draft_072 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports2, module2) {
    module2.exports = {
      $schema: "http://json-schema.org/draft-07/schema#",
      $id: "http://json-schema.org/draft-07/schema#",
      title: "Core schema meta-schema",
      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: []
        }
      },
      type: ["object", "boolean"],
      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: "#" }
      },
      default: true
    };
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/ajv.js
var require_ajv2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/ajv.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MissingRefError = exports2.ValidationError = exports2.CodeGen = exports2.Name = exports2.nil = exports2.stringify = exports2.str = exports2._ = exports2.KeywordCxt = exports2.Ajv = void 0;
    var core_1 = require_core3();
    var draft7_1 = require_draft72();
    var discriminator_1 = require_discriminator2();
    var draft7MetaSchema = require_json_schema_draft_072();
    var META_SUPPORT_DATA = ["/properties"];
    var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
    var Ajv2 = class extends core_1.default {
      static {
        __name(this, "Ajv");
      }
      _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);
      }
    };
    exports2.Ajv = Ajv2;
    module2.exports = exports2 = Ajv2;
    module2.exports.Ajv = Ajv2;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.default = Ajv2;
    var validate_1 = require_validate2();
    Object.defineProperty(exports2, "KeywordCxt", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return validate_1.KeywordCxt;
    }, "get") });
    var codegen_1 = require_codegen2();
    Object.defineProperty(exports2, "_", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1._;
    }, "get") });
    Object.defineProperty(exports2, "str", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.str;
    }, "get") });
    Object.defineProperty(exports2, "stringify", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.stringify;
    }, "get") });
    Object.defineProperty(exports2, "nil", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.nil;
    }, "get") });
    Object.defineProperty(exports2, "Name", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.Name;
    }, "get") });
    Object.defineProperty(exports2, "CodeGen", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.CodeGen;
    }, "get") });
    var validation_error_1 = require_validation_error2();
    Object.defineProperty(exports2, "ValidationError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return validation_error_1.default;
    }, "get") });
    var ref_error_1 = require_ref_error2();
    Object.defineProperty(exports2, "MissingRefError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ref_error_1.default;
    }, "get") });
  }
});

// node_modules/ajv-formats/dist/limit.js
var require_limit = __commonJS({
  "node_modules/ajv-formats/dist/limit.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.formatLimitDefinition = void 0;
    var ajv_1 = require_ajv2();
    var codegen_1 = require_codegen2();
    var ops = codegen_1.operators;
    var 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 }
    };
    var error = {
      message: /* @__PURE__ */ __name(({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, "message"),
      params: /* @__PURE__ */ __name(({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`, "params")
    };
    exports2.formatLimitDefinition = {
      keyword: Object.keys(KWDs),
      type: "string",
      schemaType: "string",
      $data: true,
      error,
      code(cxt) {
        const { gen, data, schemaCode, keyword, it } = cxt;
        const { opts, self: self2 } = it;
        if (!opts.validateFormats)
          return;
        const fCxt = new ajv_1.KeywordCxt(it, 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)));
        }
        __name(validate$DataFormat, "validate$DataFormat");
        function validateFormat() {
          const format4 = fCxt.schema;
          const fmtDef = self2.formats[format4];
          if (!fmtDef || fmtDef === true)
            return;
          if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") {
            throw new Error(`"${keyword}": format "${format4}" does not define "compare" function`);
          }
          const fmt = gen.scopeValue("formats", {
            key: format4,
            ref: fmtDef,
            code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format4)}` : void 0
          });
          cxt.fail$data(compareCode(fmt));
        }
        __name(validateFormat, "validateFormat");
        function compareCode(fmt) {
          return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`;
        }
        __name(compareCode, "compareCode");
      },
      dependencies: ["format"]
    };
    var formatLimitPlugin = /* @__PURE__ */ __name((ajv) => {
      ajv.addKeyword(exports2.formatLimitDefinition);
      return ajv;
    }, "formatLimitPlugin");
    exports2.default = formatLimitPlugin;
  }
});

// node_modules/ajv-formats/dist/index.js
var require_dist3 = __commonJS({
  "node_modules/ajv-formats/dist/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var formats_1 = require_formats();
    var limit_1 = require_limit();
    var codegen_1 = require_codegen2();
    var fullName = new codegen_1.Name("fullFormats");
    var fastName = new codegen_1.Name("fastFormats");
    var formatsPlugin = /* @__PURE__ */ __name((ajv, opts = { keywords: true }) => {
      if (Array.isArray(opts)) {
        addFormats2(ajv, opts, formats_1.fullFormats, fullName);
        return ajv;
      }
      const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];
      const list3 = opts.formats || formats_1.formatNames;
      addFormats2(ajv, list3, formats, exportName);
      if (opts.keywords)
        (0, limit_1.default)(ajv);
      return ajv;
    }, "formatsPlugin");
    formatsPlugin.get = (name3, mode = "full") => {
      const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats;
      const f = formats[name3];
      if (!f)
        throw new Error(`Unknown format "${name3}"`);
      return f;
    };
    function addFormats2(ajv, list3, fs95, exportName) {
      var _a6;
      var _b2;
      (_a6 = (_b2 = ajv.opts.code).formats) !== null && _a6 !== void 0 ? _a6 : _b2.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
      for (const f of list3)
        ajv.addFormat(f, fs95[f]);
    }
    __name(addFormats2, "addFormats");
    module2.exports = exports2 = formatsPlugin;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.default = formatsPlugin;
  }
});

// packages/core/dist/src/utils/schemaValidator.js
function fixBooleanCasing(data) {
  for (const key of Object.keys(data)) {
    if (!(key in data))
      continue;
    if (typeof data[key] === "object") {
      fixBooleanCasing(data[key]);
    } else if (data[key] === "True")
      data[key] = "true";
    else if (data[key] === "False")
      data[key] = "false";
  }
}
var import_ajv, addFormats, AjvClass, ajValidator, addFormatsFunc, SchemaValidator;
var init_schemaValidator = __esm({
  "packages/core/dist/src/utils/schemaValidator.js"() {
    "use strict";
    init_esbuild_shims();
    import_ajv = __toESM(require_ajv(), 1);
    addFormats = __toESM(require_dist3(), 1);
    AjvClass = import_ajv.default.default || import_ajv.default;
    ajValidator = new AjvClass(
      // See: https://ajv.js.org/options.html#strict-mode-options
      {
        // strictSchema defaults to true and prevents use of JSON schemas that
        // include unrecognized keywords. The JSON schema spec specifically allows
        // for the use of non-standard keywords and the spec-compliant behavior
        // is to ignore those keywords. Note that setting this to false also
        // allows use of non-standard or custom formats (the unknown format value
        // will be logged but the schema will still be considered valid).
        strictSchema: false
      }
    );
    addFormatsFunc = addFormats.default || addFormats;
    addFormatsFunc(ajValidator);
    SchemaValidator = class {
      static {
        __name(this, "SchemaValidator");
      }
      /**
       * Returns null if the data confroms to the schema described by schema (or if schema
       *  is null). Otherwise, returns a string describing the error.
       */
      static validate(schema, data) {
        if (!schema) {
          return null;
        }
        if (typeof data !== "object" || data === null) {
          return "Value of params must be an object";
        }
        const validate4 = ajValidator.compile(schema);
        const valid = validate4(data);
        if (!valid && validate4.errors) {
          fixBooleanCasing(data);
          const validate5 = ajValidator.compile(schema);
          const valid2 = validate5(data);
          if (!valid2 && validate5.errors) {
            return ajValidator.errorsText(validate5.errors, { dataVar: "params" });
          }
        }
        return null;
      }
    };
    __name(fixBooleanCasing, "fixBooleanCasing");
  }
});

// packages/core/dist/src/subagents/subagent-statistics.js
var SubagentStatistics;
var init_subagent_statistics = __esm({
  "packages/core/dist/src/subagents/subagent-statistics.js"() {
    "use strict";
    init_esbuild_shims();
    SubagentStatistics = class {
      static {
        __name(this, "SubagentStatistics");
      }
      startTimeMs = 0;
      rounds = 0;
      totalToolCalls = 0;
      successfulToolCalls = 0;
      failedToolCalls = 0;
      inputTokens = 0;
      outputTokens = 0;
      toolUsage = /* @__PURE__ */ new Map();
      start(now = Date.now()) {
        this.startTimeMs = now;
      }
      setRounds(rounds) {
        this.rounds = rounds;
      }
      recordToolCall(name3, success, durationMs, lastError) {
        this.totalToolCalls += 1;
        if (success)
          this.successfulToolCalls += 1;
        else
          this.failedToolCalls += 1;
        const tu = this.toolUsage.get(name3) || {
          name: name3,
          count: 0,
          success: 0,
          failure: 0,
          lastError: void 0,
          totalDurationMs: 0,
          averageDurationMs: 0
        };
        tu.count += 1;
        if (success)
          tu.success += 1;
        else
          tu.failure += 1;
        if (lastError)
          tu.lastError = lastError;
        tu.totalDurationMs += Math.max(0, durationMs || 0);
        tu.averageDurationMs = tu.count > 0 ? tu.totalDurationMs / tu.count : 0;
        this.toolUsage.set(name3, tu);
      }
      recordTokens(input, output) {
        this.inputTokens += Math.max(0, input || 0);
        this.outputTokens += Math.max(0, output || 0);
      }
      getSummary(now = Date.now()) {
        const totalDurationMs = this.startTimeMs ? now - this.startTimeMs : 0;
        const totalToolCalls = this.totalToolCalls;
        const successRate = totalToolCalls > 0 ? this.successfulToolCalls / totalToolCalls * 100 : 0;
        const totalTokens = this.inputTokens + this.outputTokens;
        const estimatedCost = this.inputTokens * 3e-5 + this.outputTokens * 6e-5;
        return {
          rounds: this.rounds,
          totalDurationMs,
          totalToolCalls,
          successfulToolCalls: this.successfulToolCalls,
          failedToolCalls: this.failedToolCalls,
          successRate,
          inputTokens: this.inputTokens,
          outputTokens: this.outputTokens,
          totalTokens,
          estimatedCost,
          toolUsage: Array.from(this.toolUsage.values())
        };
      }
      formatCompact(taskDesc, now = Date.now()) {
        const stats = this.getSummary(now);
        const sr = stats.totalToolCalls > 0 ? stats.successRate ?? stats.successfulToolCalls / stats.totalToolCalls * 100 : 0;
        const lines = [
          `\u{1F4CB} Task Completed: ${taskDesc}`,
          `\u{1F527} Tool Usage: ${stats.totalToolCalls} calls${stats.totalToolCalls ? `, ${sr.toFixed(1)}% success` : ""}`,
          `\u23F1\uFE0F Duration: ${this.fmtDuration(stats.totalDurationMs)} | \u{1F501} Rounds: ${stats.rounds}`
        ];
        if (typeof stats.totalTokens === "number") {
          lines.push(`\u{1F522} Tokens: ${stats.totalTokens.toLocaleString()}${stats.inputTokens || stats.outputTokens ? ` (in ${stats.inputTokens ?? 0}, out ${stats.outputTokens ?? 0})` : ""}`);
        }
        return lines.join("\n");
      }
      formatDetailed(taskDesc, now = Date.now()) {
        const stats = this.getSummary(now);
        const sr = stats.totalToolCalls > 0 ? stats.successRate ?? stats.successfulToolCalls / stats.totalToolCalls * 100 : 0;
        const lines = [];
        lines.push(`\u{1F4CB} Task Completed: ${taskDesc}`);
        lines.push(`\u23F1\uFE0F Duration: ${this.fmtDuration(stats.totalDurationMs)} | \u{1F501} Rounds: ${stats.rounds}`);
        let quality = "Poor execution";
        if (sr >= 95)
          quality = "Excellent execution";
        else if (sr >= 85)
          quality = "Good execution";
        else if (sr >= 70)
          quality = "Fair execution";
        lines.push(`\u2705 Quality: ${quality} (${sr.toFixed(1)}% tool success)`);
        const d = stats.totalDurationMs;
        let speed = "Long execution - consider breaking down tasks";
        if (d < 1e4)
          speed = "Fast completion - under 10 seconds";
        else if (d < 6e4)
          speed = "Good speed - under a minute";
        else if (d < 3e5)
          speed = "Moderate duration - a few minutes";
        lines.push(`\u{1F680} Speed: ${speed}`);
        lines.push(`\u{1F527} Tools: ${stats.totalToolCalls} calls, ${sr.toFixed(1)}% success (${stats.successfulToolCalls} ok, ${stats.failedToolCalls} failed)`);
        if (typeof stats.totalTokens === "number") {
          lines.push(`\u{1F522} Tokens: ${stats.totalTokens.toLocaleString()} (in ${stats.inputTokens ?? 0}, out ${stats.outputTokens ?? 0})`);
        }
        if (stats.toolUsage && stats.toolUsage.length) {
          const sorted2 = [...stats.toolUsage].sort((a, b) => b.count - a.count).slice(0, 5);
          lines.push("\nTop tools:");
          for (const t2 of sorted2) {
            const avg = typeof t2.averageDurationMs === "number" ? `, avg ${this.fmtDuration(Math.round(t2.averageDurationMs))}` : "";
            lines.push(` - ${t2.name}: ${t2.count} calls (${t2.success} ok, ${t2.failure} fail${avg}${t2.lastError ? `, last error: ${t2.lastError}` : ""})`);
          }
        }
        const tips = this.generatePerformanceTips(stats);
        if (tips.length) {
          lines.push("\n\u{1F4A1} Performance Insights:");
          for (const tip of tips.slice(0, 3))
            lines.push(` - ${tip}`);
        }
        return lines.join("\n");
      }
      fmtDuration(ms) {
        if (ms < 1e3)
          return `${Math.round(ms)}ms`;
        if (ms < 6e4)
          return `${(ms / 1e3).toFixed(1)}s`;
        if (ms < 36e5) {
          const m2 = Math.floor(ms / 6e4);
          const s2 = Math.floor(ms % 6e4 / 1e3);
          return `${m2}m ${s2}s`;
        }
        const h = Math.floor(ms / 36e5);
        const m = Math.floor(ms % 36e5 / 6e4);
        return `${h}h ${m}m`;
      }
      generatePerformanceTips(stats) {
        const tips = [];
        const totalCalls = stats.totalToolCalls;
        const sr = stats.totalToolCalls > 0 ? stats.successRate ?? stats.successfulToolCalls / stats.totalToolCalls * 100 : 0;
        if (sr < 80)
          tips.push("Low tool success rate - review inputs and error messages");
        if (stats.totalDurationMs > 6e4)
          tips.push("Long execution time - consider breaking down complex tasks");
        if (typeof stats.totalTokens === "number" && stats.totalTokens > 1e5) {
          tips.push("High token usage - consider optimizing prompts or narrowing scope");
        }
        if (typeof stats.totalTokens === "number" && totalCalls > 0) {
          const avgTokPerCall = stats.totalTokens / totalCalls;
          if (avgTokPerCall > 5e3)
            tips.push(`High token usage per tool call (~${Math.round(avgTokPerCall)} tokens/call)`);
        }
        const isNetworkTool = /* @__PURE__ */ __name((name3) => /web|fetch|search/i.test(name3), "isNetworkTool");
        const hadNetworkFailure = (stats.toolUsage || []).some((t2) => isNetworkTool(t2.name) && t2.lastError && /timeout|network/i.test(t2.lastError));
        if (hadNetworkFailure)
          tips.push("Network operations had failures - consider increasing timeout or checking connectivity");
        const slow = (stats.toolUsage || []).filter((t2) => (t2.averageDurationMs ?? 0) > 1e4).sort((a, b) => (b.averageDurationMs ?? 0) - (a.averageDurationMs ?? 0));
        if (slow.length)
          tips.push(`Consider optimizing ${slow[0].name} operations (avg ${this.fmtDuration(Math.round(slow[0].averageDurationMs))})`);
        return tips;
      }
    };
  }
});

// packages/core/dist/src/tools/tools.js
function isTool(obj) {
  return typeof obj === "object" && obj !== null && "name" in obj && "build" in obj && typeof obj.build === "function";
}
function hasCycleInSchema(schema) {
  function resolveRef(ref) {
    if (!ref.startsWith("#/")) {
      return null;
    }
    const path108 = ref.substring(2).split("/");
    let current = schema;
    for (const segment of path108) {
      if (typeof current !== "object" || current === null || !Object.prototype.hasOwnProperty.call(current, segment)) {
        return null;
      }
      current = current[segment];
    }
    return current;
  }
  __name(resolveRef, "resolveRef");
  function traverse(node, visitedRefs, pathRefs) {
    if (typeof node !== "object" || node === null) {
      return false;
    }
    if (Array.isArray(node)) {
      for (const item of node) {
        if (traverse(item, visitedRefs, pathRefs)) {
          return true;
        }
      }
      return false;
    }
    if ("$ref" in node && typeof node.$ref === "string") {
      const ref = node.$ref;
      if (ref === "#/" || pathRefs.has(ref)) {
        return true;
      }
      if (visitedRefs.has(ref)) {
        return false;
      }
      const resolvedNode = resolveRef(ref);
      if (resolvedNode) {
        visitedRefs.add(ref);
        pathRefs.add(ref);
        const hasCycle = traverse(resolvedNode, visitedRefs, pathRefs);
        pathRefs.delete(ref);
        return hasCycle;
      }
    }
    for (const key in node) {
      if (Object.prototype.hasOwnProperty.call(node, key)) {
        if (traverse(node[key], visitedRefs, pathRefs)) {
          return true;
        }
      }
    }
    return false;
  }
  __name(traverse, "traverse");
  return traverse(schema, /* @__PURE__ */ new Set(), /* @__PURE__ */ new Set());
}
var BaseToolInvocation, DeclarativeTool, BaseDeclarativeTool, ToolConfirmationOutcome, Kind, MUTATOR_KINDS;
var init_tools = __esm({
  "packages/core/dist/src/tools/tools.js"() {
    "use strict";
    init_esbuild_shims();
    init_tool_error();
    init_schemaValidator();
    init_subagent_statistics();
    BaseToolInvocation = class {
      static {
        __name(this, "BaseToolInvocation");
      }
      params;
      constructor(params) {
        this.params = params;
      }
      toolLocations() {
        return [];
      }
      shouldConfirmExecute(_abortSignal) {
        return Promise.resolve(false);
      }
    };
    DeclarativeTool = class {
      static {
        __name(this, "DeclarativeTool");
      }
      name;
      displayName;
      description;
      kind;
      parameterSchema;
      isOutputMarkdown;
      canUpdateOutput;
      constructor(name3, displayName, description, kind, parameterSchema, isOutputMarkdown = true, canUpdateOutput = false) {
        this.name = name3;
        this.displayName = displayName;
        this.description = description;
        this.kind = kind;
        this.parameterSchema = parameterSchema;
        this.isOutputMarkdown = isOutputMarkdown;
        this.canUpdateOutput = canUpdateOutput;
      }
      get schema() {
        return {
          name: this.name,
          description: this.description,
          parametersJsonSchema: this.parameterSchema
        };
      }
      /**
       * Validates the raw tool parameters.
       * Subclasses should override this to add custom validation logic
       * beyond the JSON schema check.
       * @param params The raw parameters from the model.
       * @returns An error message string if invalid, null otherwise.
       */
      validateToolParams(_params) {
        return null;
      }
      /**
       * A convenience method that builds and executes the tool in one step.
       * Throws an error if validation fails.
       * @param params The raw, untrusted parameters from the model.
       * @param signal AbortSignal for tool cancellation.
       * @param updateOutput Optional callback to stream output.
       * @returns The result of the tool execution.
       */
      async buildAndExecute(params, signal, updateOutput2, shellExecutionConfig) {
        const invocation = this.build(params);
        return invocation.execute(signal, updateOutput2, shellExecutionConfig);
      }
      /**
       * Similar to `build` but never throws.
       * @param params The raw, untrusted parameters from the model.
       * @returns A `ToolInvocation` instance.
       */
      silentBuild(params) {
        try {
          return this.build(params);
        } catch (e2) {
          if (e2 instanceof Error) {
            return e2;
          }
          return new Error(String(e2));
        }
      }
      /**
       * A convenience method that builds and executes the tool in one step.
       * Never throws.
       * @param params The raw, untrusted parameters from the model.
       * @params abortSignal a signal to abort.
       * @returns The result of the tool execution.
       */
      async validateBuildAndExecute(params, abortSignal) {
        const invocationOrError = this.silentBuild(params);
        if (invocationOrError instanceof Error) {
          const errorMessage = invocationOrError.message;
          return {
            llmContent: `Error: Invalid parameters provided. Reason: ${errorMessage}`,
            returnDisplay: errorMessage,
            error: {
              message: errorMessage,
              type: ToolErrorType.INVALID_TOOL_PARAMS
            }
          };
        }
        try {
          return await invocationOrError.execute(abortSignal);
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : String(error);
          return {
            llmContent: `Error: Tool call execution failed. Reason: ${errorMessage}`,
            returnDisplay: errorMessage,
            error: {
              message: errorMessage,
              type: ToolErrorType.EXECUTION_FAILED
            }
          };
        }
      }
    };
    BaseDeclarativeTool = class extends DeclarativeTool {
      static {
        __name(this, "BaseDeclarativeTool");
      }
      build(params) {
        const validationError = this.validateToolParams(params);
        if (validationError) {
          throw new Error(validationError);
        }
        return this.createInvocation(params);
      }
      validateToolParams(params) {
        const errors = SchemaValidator.validate(this.schema.parametersJsonSchema, params);
        if (errors) {
          return errors;
        }
        return this.validateToolParamValues(params);
      }
      validateToolParamValues(_params) {
        return null;
      }
    };
    __name(isTool, "isTool");
    __name(hasCycleInSchema, "hasCycleInSchema");
    (function(ToolConfirmationOutcome2) {
      ToolConfirmationOutcome2["ProceedOnce"] = "proceed_once";
      ToolConfirmationOutcome2["ProceedAlways"] = "proceed_always";
      ToolConfirmationOutcome2["ProceedAlwaysServer"] = "proceed_always_server";
      ToolConfirmationOutcome2["ProceedAlwaysTool"] = "proceed_always_tool";
      ToolConfirmationOutcome2["ModifyWithEditor"] = "modify_with_editor";
      ToolConfirmationOutcome2["Cancel"] = "cancel";
    })(ToolConfirmationOutcome || (ToolConfirmationOutcome = {}));
    (function(Kind2) {
      Kind2["Read"] = "read";
      Kind2["Edit"] = "edit";
      Kind2["Delete"] = "delete";
      Kind2["Move"] = "move";
      Kind2["Search"] = "search";
      Kind2["Execute"] = "execute";
      Kind2["Think"] = "think";
      Kind2["Fetch"] = "fetch";
      Kind2["Other"] = "other";
    })(Kind || (Kind = {}));
    MUTATOR_KINDS = [
      Kind.Edit,
      Kind.Delete,
      Kind.Move,
      Kind.Execute
    ];
  }
});

// packages/core/dist/src/tools/mcp-tool.js
function transformTextBlock(block2) {
  return { text: block2.text };
}
function transformImageAudioBlock(block2, toolName) {
  return [
    {
      text: `[Tool '${toolName}' provided the following ${block2.type} data with mime-type: ${block2.mimeType}]`
    },
    {
      inlineData: {
        mimeType: block2.mimeType,
        data: block2.data
      }
    }
  ];
}
function transformResourceBlock(block2, toolName) {
  const resource = block2.resource;
  if (resource?.text) {
    return { text: resource.text };
  }
  if (resource?.blob) {
    const mimeType = resource.mimeType || "application/octet-stream";
    return [
      {
        text: `[Tool '${toolName}' provided the following embedded resource with mime-type: ${mimeType}]`
      },
      {
        inlineData: {
          mimeType,
          data: resource.blob
        }
      }
    ];
  }
  return null;
}
function transformResourceLinkBlock(block2) {
  return {
    text: `Resource Link: ${block2.title || block2.name} at ${block2.uri}`
  };
}
function transformMcpContentToParts(sdkResponse) {
  const funcResponse = sdkResponse?.[0]?.functionResponse;
  const mcpContent = funcResponse?.response?.["content"];
  const toolName = funcResponse?.name || "unknown tool";
  if (!Array.isArray(mcpContent)) {
    return [{ text: "[Error: Could not parse tool response]" }];
  }
  const transformed = mcpContent.flatMap((block2) => {
    switch (block2.type) {
      case "text":
        return transformTextBlock(block2);
      case "image":
      case "audio":
        return transformImageAudioBlock(block2, toolName);
      case "resource":
        return transformResourceBlock(block2, toolName);
      case "resource_link":
        return transformResourceLinkBlock(block2);
      default:
        return null;
    }
  });
  return transformed.filter((part) => part !== null);
}
function getStringifiedResultForDisplay(rawResponse) {
  const mcpContent = rawResponse?.[0]?.functionResponse?.response?.["content"];
  if (!Array.isArray(mcpContent)) {
    return "```json\n" + JSON.stringify(rawResponse, null, 2) + "\n```";
  }
  const displayParts = mcpContent.map((block2) => {
    switch (block2.type) {
      case "text":
        return block2.text;
      case "image":
        return `[Image: ${block2.mimeType}]`;
      case "audio":
        return `[Audio: ${block2.mimeType}]`;
      case "resource_link":
        return `[Link to ${block2.title || block2.name}: ${block2.uri}]`;
      case "resource":
        if (block2.resource?.text) {
          return block2.resource.text;
        }
        return `[Embedded Resource: ${block2.resource?.mimeType || "unknown type"}]`;
      default:
        return `[Unknown content type: ${block2.type}]`;
    }
  });
  return displayParts.join("\n");
}
function generateValidName(name3) {
  let validToolname = name3.replace(/[^a-zA-Z0-9_.-]/g, "_");
  if (validToolname.length > 63) {
    validToolname = validToolname.slice(0, 28) + "___" + validToolname.slice(-32);
  }
  return validToolname;
}
var DiscoveredMCPToolInvocation, DiscoveredMCPTool;
var init_mcp_tool = __esm({
  "packages/core/dist/src/tools/mcp-tool.js"() {
    "use strict";
    init_esbuild_shims();
    init_safeJsonStringify();
    init_tools();
    init_tool_error();
    DiscoveredMCPToolInvocation = class _DiscoveredMCPToolInvocation extends BaseToolInvocation {
      static {
        __name(this, "DiscoveredMCPToolInvocation");
      }
      mcpTool;
      serverName;
      serverToolName;
      displayName;
      trust;
      cliConfig;
      static allowlist = /* @__PURE__ */ new Set();
      constructor(mcpTool, serverName, serverToolName, displayName, trust, params = {}, cliConfig) {
        super(params);
        this.mcpTool = mcpTool;
        this.serverName = serverName;
        this.serverToolName = serverToolName;
        this.displayName = displayName;
        this.trust = trust;
        this.cliConfig = cliConfig;
      }
      async shouldConfirmExecute(_abortSignal) {
        const serverAllowListKey = this.serverName;
        const toolAllowListKey = `${this.serverName}.${this.serverToolName}`;
        if (this.cliConfig?.isTrustedFolder() && this.trust) {
          return false;
        }
        if (_DiscoveredMCPToolInvocation.allowlist.has(serverAllowListKey) || _DiscoveredMCPToolInvocation.allowlist.has(toolAllowListKey)) {
          return false;
        }
        const confirmationDetails = {
          type: "mcp",
          title: "Confirm MCP Tool Execution",
          serverName: this.serverName,
          toolName: this.serverToolName,
          // Display original tool name in confirmation
          toolDisplayName: this.displayName,
          // Display global registry name exposed to model and user
          onConfirm: /* @__PURE__ */ __name(async (outcome) => {
            if (outcome === ToolConfirmationOutcome.ProceedAlwaysServer) {
              _DiscoveredMCPToolInvocation.allowlist.add(serverAllowListKey);
            } else if (outcome === ToolConfirmationOutcome.ProceedAlwaysTool) {
              _DiscoveredMCPToolInvocation.allowlist.add(toolAllowListKey);
            }
          }, "onConfirm")
        };
        return confirmationDetails;
      }
      // Determine if the response contains tool errors
      // This is needed because CallToolResults should return errors inside the response.
      // ref: https://modelcontextprotocol.io/specification/2025-06-18/schema#calltoolresult
      isMCPToolError(rawResponseParts) {
        const functionResponse = rawResponseParts?.[0]?.functionResponse;
        const response = functionResponse?.response;
        if (response) {
          const error = response?.error;
          const isError = error?.isError;
          if (error && (isError === true || isError === "true")) {
            return true;
          }
        }
        return false;
      }
      async execute(signal) {
        const functionCalls = [
          {
            name: this.serverToolName,
            args: this.params
          }
        ];
        const rawResponseParts = await new Promise((resolve24, reject) => {
          if (signal.aborted) {
            const error = new Error("Tool call aborted");
            error.name = "AbortError";
            reject(error);
            return;
          }
          const onAbort = /* @__PURE__ */ __name(() => {
            cleanup();
            const error = new Error("Tool call aborted");
            error.name = "AbortError";
            reject(error);
          }, "onAbort");
          const cleanup = /* @__PURE__ */ __name(() => {
            signal.removeEventListener("abort", onAbort);
          }, "cleanup");
          signal.addEventListener("abort", onAbort, { once: true });
          this.mcpTool.callTool(functionCalls).then((res) => {
            cleanup();
            resolve24(res);
          }).catch((err) => {
            cleanup();
            reject(err);
          });
        });
        if (this.isMCPToolError(rawResponseParts)) {
          const errorMessage = `MCP tool '${this.serverToolName}' reported tool error for function call: ${safeJsonStringify(functionCalls[0])} with response: ${safeJsonStringify(rawResponseParts)}`;
          return {
            llmContent: errorMessage,
            returnDisplay: `Error: MCP tool '${this.serverToolName}' reported an error.`,
            error: {
              message: errorMessage,
              type: ToolErrorType.MCP_TOOL_ERROR
            }
          };
        }
        const transformedParts = transformMcpContentToParts(rawResponseParts);
        return {
          llmContent: transformedParts,
          returnDisplay: getStringifiedResultForDisplay(rawResponseParts)
        };
      }
      getDescription() {
        return safeJsonStringify(this.params);
      }
    };
    DiscoveredMCPTool = class _DiscoveredMCPTool extends BaseDeclarativeTool {
      static {
        __name(this, "DiscoveredMCPTool");
      }
      mcpTool;
      serverName;
      serverToolName;
      parameterSchema;
      trust;
      cliConfig;
      constructor(mcpTool, serverName, serverToolName, description, parameterSchema, trust, nameOverride, cliConfig) {
        super(
          nameOverride ?? generateValidName(serverToolName),
          `${serverToolName} (${serverName} MCP Server)`,
          description,
          Kind.Other,
          parameterSchema,
          true,
          // isOutputMarkdown
          false
        );
        this.mcpTool = mcpTool;
        this.serverName = serverName;
        this.serverToolName = serverToolName;
        this.parameterSchema = parameterSchema;
        this.trust = trust;
        this.cliConfig = cliConfig;
      }
      asFullyQualifiedTool() {
        return new _DiscoveredMCPTool(this.mcpTool, this.serverName, this.serverToolName, this.description, this.parameterSchema, this.trust, `${this.serverName}__${this.serverToolName}`, this.cliConfig);
      }
      createInvocation(params) {
        return new DiscoveredMCPToolInvocation(this.mcpTool, this.serverName, this.serverToolName, this.displayName, this.trust, params, this.cliConfig);
      }
    };
    __name(transformTextBlock, "transformTextBlock");
    __name(transformImageAudioBlock, "transformImageAudioBlock");
    __name(transformResourceBlock, "transformResourceBlock");
    __name(transformResourceLinkBlock, "transformResourceLinkBlock");
    __name(transformMcpContentToParts, "transformMcpContentToParts");
    __name(getStringifiedResultForDisplay, "getStringifiedResultForDisplay");
    __name(generateValidName, "generateValidName");
  }
});

// packages/core/dist/src/telemetry/tool-call-decision.js
function getDecisionFromOutcome(outcome) {
  switch (outcome) {
    case ToolConfirmationOutcome.ProceedOnce:
      return ToolCallDecision.ACCEPT;
    case ToolConfirmationOutcome.ProceedAlways:
    case ToolConfirmationOutcome.ProceedAlwaysServer:
    case ToolConfirmationOutcome.ProceedAlwaysTool:
      return ToolCallDecision.AUTO_ACCEPT;
    case ToolConfirmationOutcome.ModifyWithEditor:
      return ToolCallDecision.MODIFY;
    case ToolConfirmationOutcome.Cancel:
    default:
      return ToolCallDecision.REJECT;
  }
}
var ToolCallDecision;
var init_tool_call_decision = __esm({
  "packages/core/dist/src/telemetry/tool-call-decision.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    (function(ToolCallDecision2) {
      ToolCallDecision2["ACCEPT"] = "accept";
      ToolCallDecision2["REJECT"] = "reject";
      ToolCallDecision2["MODIFY"] = "modify";
      ToolCallDecision2["AUTO_ACCEPT"] = "auto_accept";
    })(ToolCallDecision || (ToolCallDecision = {}));
    __name(getDecisionFromOutcome, "getDecisionFromOutcome");
  }
});

// packages/core/dist/src/telemetry/types.js
function makeSlashCommandEvent({ command: command2, subcommand, status }) {
  return {
    "event.name": "slash_command",
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    command: command2,
    subcommand,
    status
  };
}
function makeChatCompressionEvent({ tokens_before, tokens_after }) {
  return {
    "event.name": "chat_compression",
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    tokens_before,
    tokens_after
  };
}
var StartSessionEvent, EndSessionEvent, UserPromptEvent, ToolCallEvent, ApiRequestEvent, ApiErrorEvent, ApiCancelEvent, ApiResponseEvent, FlashFallbackEvent, RipgrepFallbackEvent, LoopType, LoopDetectedEvent, LoopDetectionDisabledEvent, NextSpeakerCheckEvent, SlashCommandStatus, IdeConnectionType, IdeConnectionEvent, ConversationFinishedEvent, KittySequenceOverflowEvent, FileOperationEvent, ContentRetryEvent, ContentRetryFailureEvent, ExtensionInstallEvent, ToolOutputTruncatedEvent, ExtensionUninstallEvent, ExtensionEnableEvent, ModelSlashCommandEvent, SubagentExecutionEvent, AuthEvent, ExtensionDisableEvent;
var init_types3 = __esm({
  "packages/core/dist/src/telemetry/types.js"() {
    "use strict";
    init_esbuild_shims();
    init_mcp_tool();
    init_contentGenerator();
    init_tool_call_decision();
    StartSessionEvent = class {
      static {
        __name(this, "StartSessionEvent");
      }
      "event.name";
      "event.timestamp";
      model;
      embedding_model;
      sandbox_enabled;
      core_tools_enabled;
      approval_mode;
      api_key_enabled;
      vertex_ai_enabled;
      debug_enabled;
      mcp_servers;
      telemetry_enabled;
      telemetry_log_user_prompts_enabled;
      file_filtering_respect_git_ignore;
      mcp_servers_count;
      mcp_tools_count;
      mcp_tools;
      output_format;
      constructor(config, toolRegistry) {
        const generatorConfig = config.getContentGeneratorConfig();
        const mcpServers = config.getMcpServers();
        let useGemini = false;
        let useVertex = false;
        if (generatorConfig && generatorConfig.authType) {
          useGemini = generatorConfig.authType === AuthType2.USE_GEMINI;
          useVertex = generatorConfig.authType === AuthType2.USE_VERTEX_AI;
        }
        this["event.name"] = "cli_config";
        this.model = config.getModel();
        this.embedding_model = config.getEmbeddingModel();
        this.sandbox_enabled = typeof config.getSandbox() === "string" || !!config.getSandbox();
        this.core_tools_enabled = (config.getCoreTools() ?? []).join(",");
        this.approval_mode = config.getApprovalMode();
        this.api_key_enabled = useGemini || useVertex;
        this.vertex_ai_enabled = useVertex;
        this.debug_enabled = config.getDebugMode();
        this.mcp_servers = mcpServers ? Object.keys(mcpServers).join(",") : "";
        this.telemetry_enabled = config.getTelemetryEnabled();
        this.telemetry_log_user_prompts_enabled = config.getTelemetryLogPromptsEnabled();
        this.file_filtering_respect_git_ignore = config.getFileFilteringRespectGitIgnore();
        this.mcp_servers_count = mcpServers ? Object.keys(mcpServers).length : 0;
        this.output_format = config.getOutputFormat();
        if (toolRegistry) {
          const mcpTools = toolRegistry.getAllTools().filter((tool) => tool instanceof DiscoveredMCPTool);
          this.mcp_tools_count = mcpTools.length;
          this.mcp_tools = mcpTools.map((tool) => tool.name).join(",");
        }
      }
    };
    EndSessionEvent = class {
      static {
        __name(this, "EndSessionEvent");
      }
      "event.name";
      "event.timestamp";
      session_id;
      constructor(config) {
        this["event.name"] = "end_session";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.session_id = config?.getSessionId();
      }
    };
    UserPromptEvent = class {
      static {
        __name(this, "UserPromptEvent");
      }
      "event.name";
      "event.timestamp";
      prompt_length;
      prompt_id;
      auth_type;
      prompt;
      constructor(prompt_length, prompt_Id, auth_type, prompt) {
        this["event.name"] = "user_prompt";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.prompt_length = prompt_length;
        this.prompt_id = prompt_Id;
        this.auth_type = auth_type;
        this.prompt = prompt;
      }
    };
    ToolCallEvent = class {
      static {
        __name(this, "ToolCallEvent");
      }
      "event.name";
      "event.timestamp";
      function_name;
      function_args;
      duration_ms;
      status;
      success;
      // Keep for backward compatibility
      decision;
      error;
      error_type;
      prompt_id;
      response_id;
      tool_type;
      content_length;
      mcp_server_name;
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      metadata;
      constructor(call) {
        this["event.name"] = "tool_call";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.function_name = call.request.name;
        this.function_args = call.request.args;
        this.duration_ms = call.durationMs ?? 0;
        this.status = call.status;
        this.success = call.status === "success";
        this.decision = call.outcome ? getDecisionFromOutcome(call.outcome) : void 0;
        this.error = call.response.error?.message;
        this.error_type = call.response.errorType;
        this.prompt_id = call.request.prompt_id;
        this.content_length = call.response.contentLength;
        if (typeof call.tool !== "undefined" && call.tool instanceof DiscoveredMCPTool) {
          this.tool_type = "mcp";
          this.mcp_server_name = call.tool.serverName;
        } else {
          this.tool_type = "native";
        }
        this.response_id = call.request.response_id;
        if (call.status === "success" && typeof call.response.resultDisplay === "object" && call.response.resultDisplay !== null && "diffStat" in call.response.resultDisplay) {
          const diffStat = call.response.resultDisplay.diffStat;
          if (diffStat) {
            this.metadata = {
              model_added_lines: diffStat.model_added_lines,
              model_removed_lines: diffStat.model_removed_lines,
              model_added_chars: diffStat.model_added_chars,
              model_removed_chars: diffStat.model_removed_chars,
              user_added_lines: diffStat.user_added_lines,
              user_removed_lines: diffStat.user_removed_lines,
              user_added_chars: diffStat.user_added_chars,
              user_removed_chars: diffStat.user_removed_chars
            };
          }
        }
      }
    };
    ApiRequestEvent = class {
      static {
        __name(this, "ApiRequestEvent");
      }
      "event.name";
      "event.timestamp";
      model;
      prompt_id;
      request_text;
      constructor(model, prompt_id, request_text) {
        this["event.name"] = "api_request";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.model = model;
        this.prompt_id = prompt_id;
        this.request_text = request_text;
      }
    };
    ApiErrorEvent = class {
      static {
        __name(this, "ApiErrorEvent");
      }
      "event.name";
      "event.timestamp";
      // ISO 8601
      response_id;
      model;
      error;
      error_type;
      status_code;
      duration_ms;
      prompt_id;
      auth_type;
      constructor(response_id, model, error, duration_ms, prompt_id, auth_type, error_type, status_code) {
        this["event.name"] = "api_error";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.response_id = response_id;
        this.model = model;
        this.error = error;
        this.error_type = error_type;
        this.status_code = status_code;
        this.duration_ms = duration_ms;
        this.prompt_id = prompt_id;
        this.auth_type = auth_type;
      }
    };
    ApiCancelEvent = class {
      static {
        __name(this, "ApiCancelEvent");
      }
      "event.name";
      "event.timestamp";
      model;
      prompt_id;
      auth_type;
      constructor(model, prompt_id, auth_type) {
        this["event.name"] = "api_cancel";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.model = model;
        this.prompt_id = prompt_id;
        this.auth_type = auth_type;
      }
    };
    ApiResponseEvent = class {
      static {
        __name(this, "ApiResponseEvent");
      }
      "event.name";
      "event.timestamp";
      // ISO 8601
      response_id;
      model;
      status_code;
      duration_ms;
      input_token_count;
      output_token_count;
      cached_content_token_count;
      thoughts_token_count;
      tool_token_count;
      total_token_count;
      response_text;
      prompt_id;
      auth_type;
      constructor(response_id, model, duration_ms, prompt_id, auth_type, usage_data, response_text) {
        this["event.name"] = "api_response";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.response_id = response_id;
        this.model = model;
        this.duration_ms = duration_ms;
        this.status_code = 200;
        this.input_token_count = usage_data?.promptTokenCount ?? 0;
        this.output_token_count = usage_data?.candidatesTokenCount ?? 0;
        this.cached_content_token_count = usage_data?.cachedContentTokenCount ?? 0;
        this.thoughts_token_count = usage_data?.thoughtsTokenCount ?? 0;
        this.tool_token_count = usage_data?.toolUsePromptTokenCount ?? 0;
        this.total_token_count = usage_data?.totalTokenCount ?? 0;
        this.response_text = response_text;
        this.prompt_id = prompt_id;
        this.auth_type = auth_type;
      }
    };
    FlashFallbackEvent = class {
      static {
        __name(this, "FlashFallbackEvent");
      }
      "event.name";
      "event.timestamp";
      auth_type;
      constructor(auth_type) {
        this["event.name"] = "flash_fallback";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.auth_type = auth_type;
      }
    };
    RipgrepFallbackEvent = class {
      static {
        __name(this, "RipgrepFallbackEvent");
      }
      "event.name";
      "event.timestamp";
      use_ripgrep;
      use_builtin_ripgrep;
      error;
      constructor(use_ripgrep, use_builtin_ripgrep, error) {
        this["event.name"] = "ripgrep_fallback";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.use_ripgrep = use_ripgrep;
        this.use_builtin_ripgrep = use_builtin_ripgrep;
        this.error = error;
      }
    };
    (function(LoopType2) {
      LoopType2["CONSECUTIVE_IDENTICAL_TOOL_CALLS"] = "consecutive_identical_tool_calls";
      LoopType2["CHANTING_IDENTICAL_SENTENCES"] = "chanting_identical_sentences";
      LoopType2["LLM_DETECTED_LOOP"] = "llm_detected_loop";
    })(LoopType || (LoopType = {}));
    LoopDetectedEvent = class {
      static {
        __name(this, "LoopDetectedEvent");
      }
      "event.name";
      "event.timestamp";
      loop_type;
      prompt_id;
      constructor(loop_type, prompt_id) {
        this["event.name"] = "loop_detected";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.loop_type = loop_type;
        this.prompt_id = prompt_id;
      }
    };
    LoopDetectionDisabledEvent = class {
      static {
        __name(this, "LoopDetectionDisabledEvent");
      }
      "event.name";
      "event.timestamp";
      prompt_id;
      constructor(prompt_id) {
        this["event.name"] = "loop_detection_disabled";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.prompt_id = prompt_id;
      }
    };
    NextSpeakerCheckEvent = class {
      static {
        __name(this, "NextSpeakerCheckEvent");
      }
      "event.name";
      "event.timestamp";
      prompt_id;
      finish_reason;
      result;
      constructor(prompt_id, finish_reason, result) {
        this["event.name"] = "next_speaker_check";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.prompt_id = prompt_id;
        this.finish_reason = finish_reason;
        this.result = result;
      }
    };
    __name(makeSlashCommandEvent, "makeSlashCommandEvent");
    (function(SlashCommandStatus2) {
      SlashCommandStatus2["SUCCESS"] = "success";
      SlashCommandStatus2["ERROR"] = "error";
    })(SlashCommandStatus || (SlashCommandStatus = {}));
    __name(makeChatCompressionEvent, "makeChatCompressionEvent");
    (function(IdeConnectionType2) {
      IdeConnectionType2["START"] = "start";
      IdeConnectionType2["SESSION"] = "session";
    })(IdeConnectionType || (IdeConnectionType = {}));
    IdeConnectionEvent = class {
      static {
        __name(this, "IdeConnectionEvent");
      }
      "event.name";
      "event.timestamp";
      connection_type;
      constructor(connection_type) {
        this["event.name"] = "ide_connection";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.connection_type = connection_type;
      }
    };
    ConversationFinishedEvent = class {
      static {
        __name(this, "ConversationFinishedEvent");
      }
      "event_name";
      "event.timestamp";
      // ISO 8601;
      approvalMode;
      turnCount;
      constructor(approvalMode, turnCount) {
        this["event_name"] = "conversation_finished";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.approvalMode = approvalMode;
        this.turnCount = turnCount;
      }
    };
    KittySequenceOverflowEvent = class {
      static {
        __name(this, "KittySequenceOverflowEvent");
      }
      "event.name";
      "event.timestamp";
      // ISO 8601
      sequence_length;
      truncated_sequence;
      constructor(sequence_length, truncated_sequence) {
        this["event.name"] = "kitty_sequence_overflow";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.sequence_length = sequence_length;
        this.truncated_sequence = truncated_sequence.substring(0, 20);
      }
    };
    FileOperationEvent = class {
      static {
        __name(this, "FileOperationEvent");
      }
      "event.name";
      "event.timestamp";
      tool_name;
      operation;
      lines;
      mimetype;
      extension;
      programming_language;
      constructor(tool_name, operation, lines, mimetype, extension, programming_language) {
        this["event.name"] = "file_operation";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.tool_name = tool_name;
        this.operation = operation;
        this.lines = lines;
        this.mimetype = mimetype;
        this.extension = extension;
        this.programming_language = programming_language;
      }
    };
    ContentRetryEvent = class {
      static {
        __name(this, "ContentRetryEvent");
      }
      "event.name";
      "event.timestamp";
      attempt_number;
      error_type;
      // e.g., 'EmptyStreamError'
      retry_delay_ms;
      model;
      constructor(attempt_number, error_type, retry_delay_ms, model) {
        this["event.name"] = "content_retry";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.attempt_number = attempt_number;
        this.error_type = error_type;
        this.retry_delay_ms = retry_delay_ms;
        this.model = model;
      }
    };
    ContentRetryFailureEvent = class {
      static {
        __name(this, "ContentRetryFailureEvent");
      }
      "event.name";
      "event.timestamp";
      total_attempts;
      final_error_type;
      total_duration_ms;
      // Optional: total time spent retrying
      model;
      constructor(total_attempts, final_error_type, model, total_duration_ms) {
        this["event.name"] = "content_retry_failure";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.total_attempts = total_attempts;
        this.final_error_type = final_error_type;
        this.total_duration_ms = total_duration_ms;
        this.model = model;
      }
    };
    ExtensionInstallEvent = class {
      static {
        __name(this, "ExtensionInstallEvent");
      }
      "event.name";
      "event.timestamp";
      extension_name;
      extension_version;
      extension_source;
      status;
      constructor(extension_name, extension_version, extension_source, status) {
        this["event.name"] = "extension_install";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.extension_name = extension_name;
        this.extension_version = extension_version;
        this.extension_source = extension_source;
        this.status = status;
      }
    };
    ToolOutputTruncatedEvent = class {
      static {
        __name(this, "ToolOutputTruncatedEvent");
      }
      eventName = "tool_output_truncated";
      "event.timestamp" = (/* @__PURE__ */ new Date()).toISOString();
      "event.name";
      tool_name;
      original_content_length;
      truncated_content_length;
      threshold;
      lines;
      prompt_id;
      constructor(prompt_id, details) {
        this["event.name"] = this.eventName;
        this.prompt_id = prompt_id;
        this.tool_name = details.toolName;
        this.original_content_length = details.originalContentLength;
        this.truncated_content_length = details.truncatedContentLength;
        this.threshold = details.threshold;
        this.lines = details.lines;
      }
    };
    ExtensionUninstallEvent = class {
      static {
        __name(this, "ExtensionUninstallEvent");
      }
      "event.name";
      "event.timestamp";
      extension_name;
      status;
      constructor(extension_name, status) {
        this["event.name"] = "extension_uninstall";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.extension_name = extension_name;
        this.status = status;
      }
    };
    ExtensionEnableEvent = class {
      static {
        __name(this, "ExtensionEnableEvent");
      }
      "event.name";
      "event.timestamp";
      extension_name;
      setting_scope;
      constructor(extension_name, settingScope) {
        this["event.name"] = "extension_enable";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.extension_name = extension_name;
        this.setting_scope = settingScope;
      }
    };
    ModelSlashCommandEvent = class {
      static {
        __name(this, "ModelSlashCommandEvent");
      }
      "event.name";
      "event.timestamp";
      model_name;
      constructor(model_name) {
        this["event.name"] = "model_slash_command";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.model_name = model_name;
      }
    };
    SubagentExecutionEvent = class {
      static {
        __name(this, "SubagentExecutionEvent");
      }
      "event.name";
      "event.timestamp";
      subagent_name;
      status;
      terminate_reason;
      result;
      execution_summary;
      constructor(subagent_name, status, options2) {
        this["event.name"] = "subagent_execution";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.subagent_name = subagent_name;
        this.status = status;
        this.terminate_reason = options2?.terminate_reason;
        this.result = options2?.result;
        this.execution_summary = options2?.execution_summary;
      }
    };
    AuthEvent = class {
      static {
        __name(this, "AuthEvent");
      }
      "event.name";
      "event.timestamp";
      auth_type;
      action_type;
      status;
      error_message;
      constructor(auth_type, action_type, status, error_message) {
        this["event.name"] = "auth";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.auth_type = auth_type;
        this.action_type = action_type;
        this.status = status;
        this.error_message = error_message;
      }
    };
    ExtensionDisableEvent = class {
      static {
        __name(this, "ExtensionDisableEvent");
      }
      "event.name";
      "event.timestamp";
      extension_name;
      setting_scope;
      constructor(extension_name, settingScope) {
        this["event.name"] = "extension_disable";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.extension_name = extension_name;
        this.setting_scope = settingScope;
      }
    };
  }
});

// node_modules/@opentelemetry/api-logs/build/src/types/LogRecord.js
var require_LogRecord = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/types/LogRecord.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SeverityNumber = void 0;
    var SeverityNumber;
    (function(SeverityNumber2) {
      SeverityNumber2[SeverityNumber2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
      SeverityNumber2[SeverityNumber2["TRACE"] = 1] = "TRACE";
      SeverityNumber2[SeverityNumber2["TRACE2"] = 2] = "TRACE2";
      SeverityNumber2[SeverityNumber2["TRACE3"] = 3] = "TRACE3";
      SeverityNumber2[SeverityNumber2["TRACE4"] = 4] = "TRACE4";
      SeverityNumber2[SeverityNumber2["DEBUG"] = 5] = "DEBUG";
      SeverityNumber2[SeverityNumber2["DEBUG2"] = 6] = "DEBUG2";
      SeverityNumber2[SeverityNumber2["DEBUG3"] = 7] = "DEBUG3";
      SeverityNumber2[SeverityNumber2["DEBUG4"] = 8] = "DEBUG4";
      SeverityNumber2[SeverityNumber2["INFO"] = 9] = "INFO";
      SeverityNumber2[SeverityNumber2["INFO2"] = 10] = "INFO2";
      SeverityNumber2[SeverityNumber2["INFO3"] = 11] = "INFO3";
      SeverityNumber2[SeverityNumber2["INFO4"] = 12] = "INFO4";
      SeverityNumber2[SeverityNumber2["WARN"] = 13] = "WARN";
      SeverityNumber2[SeverityNumber2["WARN2"] = 14] = "WARN2";
      SeverityNumber2[SeverityNumber2["WARN3"] = 15] = "WARN3";
      SeverityNumber2[SeverityNumber2["WARN4"] = 16] = "WARN4";
      SeverityNumber2[SeverityNumber2["ERROR"] = 17] = "ERROR";
      SeverityNumber2[SeverityNumber2["ERROR2"] = 18] = "ERROR2";
      SeverityNumber2[SeverityNumber2["ERROR3"] = 19] = "ERROR3";
      SeverityNumber2[SeverityNumber2["ERROR4"] = 20] = "ERROR4";
      SeverityNumber2[SeverityNumber2["FATAL"] = 21] = "FATAL";
      SeverityNumber2[SeverityNumber2["FATAL2"] = 22] = "FATAL2";
      SeverityNumber2[SeverityNumber2["FATAL3"] = 23] = "FATAL3";
      SeverityNumber2[SeverityNumber2["FATAL4"] = 24] = "FATAL4";
    })(SeverityNumber = exports2.SeverityNumber || (exports2.SeverityNumber = {}));
  }
});

// node_modules/@opentelemetry/api-logs/build/src/NoopLogger.js
var require_NoopLogger = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/NoopLogger.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NOOP_LOGGER = exports2.NoopLogger = void 0;
    var NoopLogger = class {
      static {
        __name(this, "NoopLogger");
      }
      emit(_logRecord) {
      }
    };
    exports2.NoopLogger = NoopLogger;
    exports2.NOOP_LOGGER = new NoopLogger();
  }
});

// node_modules/@opentelemetry/api-logs/build/src/NoopLoggerProvider.js
var require_NoopLoggerProvider = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/NoopLoggerProvider.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NOOP_LOGGER_PROVIDER = exports2.NoopLoggerProvider = void 0;
    var NoopLogger_1 = require_NoopLogger();
    var NoopLoggerProvider = class {
      static {
        __name(this, "NoopLoggerProvider");
      }
      getLogger(_name, _version, _options) {
        return new NoopLogger_1.NoopLogger();
      }
    };
    exports2.NoopLoggerProvider = NoopLoggerProvider;
    exports2.NOOP_LOGGER_PROVIDER = new NoopLoggerProvider();
  }
});

// node_modules/@opentelemetry/api-logs/build/src/ProxyLogger.js
var require_ProxyLogger = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/ProxyLogger.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ProxyLogger = void 0;
    var NoopLogger_1 = require_NoopLogger();
    var ProxyLogger = class {
      static {
        __name(this, "ProxyLogger");
      }
      constructor(_provider, name3, version2, options2) {
        this._provider = _provider;
        this.name = name3;
        this.version = version2;
        this.options = options2;
      }
      /**
       * Emit a log record. This method should only be used by log appenders.
       *
       * @param logRecord
       */
      emit(logRecord) {
        this._getLogger().emit(logRecord);
      }
      /**
       * Try to get a logger from the proxy logger provider.
       * If the proxy logger provider has no delegate, return a noop logger.
       */
      _getLogger() {
        if (this._delegate) {
          return this._delegate;
        }
        const logger6 = this._provider.getDelegateLogger(this.name, this.version, this.options);
        if (!logger6) {
          return NoopLogger_1.NOOP_LOGGER;
        }
        this._delegate = logger6;
        return this._delegate;
      }
    };
    exports2.ProxyLogger = ProxyLogger;
  }
});

// node_modules/@opentelemetry/api-logs/build/src/ProxyLoggerProvider.js
var require_ProxyLoggerProvider = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/ProxyLoggerProvider.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ProxyLoggerProvider = void 0;
    var NoopLoggerProvider_1 = require_NoopLoggerProvider();
    var ProxyLogger_1 = require_ProxyLogger();
    var ProxyLoggerProvider = class {
      static {
        __name(this, "ProxyLoggerProvider");
      }
      getLogger(name3, version2, options2) {
        var _a6;
        return (_a6 = this.getDelegateLogger(name3, version2, options2)) !== null && _a6 !== void 0 ? _a6 : new ProxyLogger_1.ProxyLogger(this, name3, version2, options2);
      }
      getDelegate() {
        var _a6;
        return (_a6 = this._delegate) !== null && _a6 !== void 0 ? _a6 : NoopLoggerProvider_1.NOOP_LOGGER_PROVIDER;
      }
      /**
       * Set the delegate logger provider
       */
      setDelegate(delegate) {
        this._delegate = delegate;
      }
      getDelegateLogger(name3, version2, options2) {
        var _a6;
        return (_a6 = this._delegate) === null || _a6 === void 0 ? void 0 : _a6.getLogger(name3, version2, options2);
      }
    };
    exports2.ProxyLoggerProvider = ProxyLoggerProvider;
  }
});

// node_modules/@opentelemetry/api-logs/build/src/platform/node/globalThis.js
var require_globalThis = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/platform/node/globalThis.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2._globalThis = void 0;
    exports2._globalThis = typeof globalThis === "object" ? globalThis : globalThis;
  }
});

// node_modules/@opentelemetry/api-logs/build/src/platform/node/index.js
var require_node2 = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/platform/node/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2._globalThis = void 0;
    var globalThis_1 = require_globalThis();
    Object.defineProperty(exports2, "_globalThis", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return globalThis_1._globalThis;
    }, "get") });
  }
});

// node_modules/@opentelemetry/api-logs/build/src/platform/index.js
var require_platform = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/platform/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2._globalThis = void 0;
    var node_1 = require_node2();
    Object.defineProperty(exports2, "_globalThis", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1._globalThis;
    }, "get") });
  }
});

// node_modules/@opentelemetry/api-logs/build/src/internal/global-utils.js
var require_global_utils = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/internal/global-utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.API_BACKWARDS_COMPATIBILITY_VERSION = exports2.makeGetter = exports2._global = exports2.GLOBAL_LOGS_API_KEY = void 0;
    var platform_1 = require_platform();
    exports2.GLOBAL_LOGS_API_KEY = Symbol.for("io.opentelemetry.js.api.logs");
    exports2._global = platform_1._globalThis;
    function makeGetter(requiredVersion, instance, fallback) {
      return (version2) => version2 === requiredVersion ? instance : fallback;
    }
    __name(makeGetter, "makeGetter");
    exports2.makeGetter = makeGetter;
    exports2.API_BACKWARDS_COMPATIBILITY_VERSION = 1;
  }
});

// node_modules/@opentelemetry/api-logs/build/src/api/logs.js
var require_logs = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/api/logs.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LogsAPI = void 0;
    var global_utils_1 = require_global_utils();
    var NoopLoggerProvider_1 = require_NoopLoggerProvider();
    var ProxyLoggerProvider_1 = require_ProxyLoggerProvider();
    var LogsAPI = class _LogsAPI {
      static {
        __name(this, "LogsAPI");
      }
      constructor() {
        this._proxyLoggerProvider = new ProxyLoggerProvider_1.ProxyLoggerProvider();
      }
      static getInstance() {
        if (!this._instance) {
          this._instance = new _LogsAPI();
        }
        return this._instance;
      }
      setGlobalLoggerProvider(provider) {
        if (global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY]) {
          return this.getLoggerProvider();
        }
        global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY] = (0, global_utils_1.makeGetter)(global_utils_1.API_BACKWARDS_COMPATIBILITY_VERSION, provider, NoopLoggerProvider_1.NOOP_LOGGER_PROVIDER);
        this._proxyLoggerProvider.setDelegate(provider);
        return provider;
      }
      /**
       * Returns the global logger provider.
       *
       * @returns LoggerProvider
       */
      getLoggerProvider() {
        var _a6, _b2;
        return (_b2 = (_a6 = global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY]) === null || _a6 === void 0 ? void 0 : _a6.call(global_utils_1._global, global_utils_1.API_BACKWARDS_COMPATIBILITY_VERSION)) !== null && _b2 !== void 0 ? _b2 : this._proxyLoggerProvider;
      }
      /**
       * Returns a logger from the global logger provider.
       *
       * @returns Logger
       */
      getLogger(name3, version2, options2) {
        return this.getLoggerProvider().getLogger(name3, version2, options2);
      }
      /** Remove the global logger provider */
      disable() {
        delete global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY];
        this._proxyLoggerProvider = new ProxyLoggerProvider_1.ProxyLoggerProvider();
      }
    };
    exports2.LogsAPI = LogsAPI;
  }
});

// node_modules/@opentelemetry/api-logs/build/src/index.js
var require_src7 = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.logs = exports2.ProxyLoggerProvider = exports2.ProxyLogger = exports2.NoopLoggerProvider = exports2.NOOP_LOGGER_PROVIDER = exports2.NoopLogger = exports2.NOOP_LOGGER = exports2.SeverityNumber = void 0;
    var LogRecord_1 = require_LogRecord();
    Object.defineProperty(exports2, "SeverityNumber", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return LogRecord_1.SeverityNumber;
    }, "get") });
    var NoopLogger_1 = require_NoopLogger();
    Object.defineProperty(exports2, "NOOP_LOGGER", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return NoopLogger_1.NOOP_LOGGER;
    }, "get") });
    Object.defineProperty(exports2, "NoopLogger", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return NoopLogger_1.NoopLogger;
    }, "get") });
    var NoopLoggerProvider_1 = require_NoopLoggerProvider();
    Object.defineProperty(exports2, "NOOP_LOGGER_PROVIDER", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return NoopLoggerProvider_1.NOOP_LOGGER_PROVIDER;
    }, "get") });
    Object.defineProperty(exports2, "NoopLoggerProvider", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return NoopLoggerProvider_1.NoopLoggerProvider;
    }, "get") });
    var ProxyLogger_1 = require_ProxyLogger();
    Object.defineProperty(exports2, "ProxyLogger", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ProxyLogger_1.ProxyLogger;
    }, "get") });
    var ProxyLoggerProvider_1 = require_ProxyLoggerProvider();
    Object.defineProperty(exports2, "ProxyLoggerProvider", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ProxyLoggerProvider_1.ProxyLoggerProvider;
    }, "get") });
    var logs_1 = require_logs();
    exports2.logs = logs_1.LogsAPI.getInstance();
  }
});

// node_modules/@opentelemetry/semantic-conventions/build/esm/internal/utils.js
// @__NO_SIDE_EFFECTS__
function createConstMap(values) {
  let res = {};
  const len = values.length;
  for (let lp = 0; lp < len; lp++) {
    const val = values[lp];
    if (val) {
      res[String(val).toUpperCase().replace(/[-.]/g, "_")] = val;
    }
  }
  return res;
}
var init_utils = __esm({
  "node_modules/@opentelemetry/semantic-conventions/build/esm/internal/utils.js"() {
    init_esbuild_shims();
    __name(createConstMap, "createConstMap");
  }
});

// node_modules/@opentelemetry/semantic-conventions/build/esm/trace/SemanticAttributes.js
var TMP_AWS_LAMBDA_INVOKED_ARN, TMP_DB_SYSTEM, TMP_DB_CONNECTION_STRING, TMP_DB_USER, TMP_DB_JDBC_DRIVER_CLASSNAME, TMP_DB_NAME, TMP_DB_STATEMENT, TMP_DB_OPERATION, TMP_DB_MSSQL_INSTANCE_NAME, TMP_DB_CASSANDRA_KEYSPACE, TMP_DB_CASSANDRA_PAGE_SIZE, TMP_DB_CASSANDRA_CONSISTENCY_LEVEL, TMP_DB_CASSANDRA_TABLE, TMP_DB_CASSANDRA_IDEMPOTENCE, TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT, TMP_DB_CASSANDRA_COORDINATOR_ID, TMP_DB_CASSANDRA_COORDINATOR_DC, TMP_DB_HBASE_NAMESPACE, TMP_DB_REDIS_DATABASE_INDEX, TMP_DB_MONGODB_COLLECTION, TMP_DB_SQL_TABLE, TMP_EXCEPTION_TYPE, TMP_EXCEPTION_MESSAGE, TMP_EXCEPTION_STACKTRACE, TMP_EXCEPTION_ESCAPED, TMP_FAAS_TRIGGER, TMP_FAAS_EXECUTION, TMP_FAAS_DOCUMENT_COLLECTION, TMP_FAAS_DOCUMENT_OPERATION, TMP_FAAS_DOCUMENT_TIME, TMP_FAAS_DOCUMENT_NAME, TMP_FAAS_TIME, TMP_FAAS_CRON, TMP_FAAS_COLDSTART, TMP_FAAS_INVOKED_NAME, TMP_FAAS_INVOKED_PROVIDER, TMP_FAAS_INVOKED_REGION, TMP_NET_TRANSPORT, TMP_NET_PEER_IP, TMP_NET_PEER_PORT, TMP_NET_PEER_NAME, TMP_NET_HOST_IP, TMP_NET_HOST_PORT, TMP_NET_HOST_NAME, TMP_NET_HOST_CONNECTION_TYPE, TMP_NET_HOST_CONNECTION_SUBTYPE, TMP_NET_HOST_CARRIER_NAME, TMP_NET_HOST_CARRIER_MCC, TMP_NET_HOST_CARRIER_MNC, TMP_NET_HOST_CARRIER_ICC, TMP_PEER_SERVICE, TMP_ENDUSER_ID, TMP_ENDUSER_ROLE, TMP_ENDUSER_SCOPE, TMP_THREAD_ID, TMP_THREAD_NAME, TMP_CODE_FUNCTION, TMP_CODE_NAMESPACE, TMP_CODE_FILEPATH, TMP_CODE_LINENO, TMP_HTTP_METHOD, TMP_HTTP_URL, TMP_HTTP_TARGET, TMP_HTTP_HOST, TMP_HTTP_SCHEME, TMP_HTTP_STATUS_CODE, TMP_HTTP_FLAVOR, TMP_HTTP_USER_AGENT, TMP_HTTP_REQUEST_CONTENT_LENGTH, TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED, TMP_HTTP_RESPONSE_CONTENT_LENGTH, TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, TMP_HTTP_SERVER_NAME, TMP_HTTP_ROUTE, TMP_HTTP_CLIENT_IP, TMP_AWS_DYNAMODB_TABLE_NAMES, TMP_AWS_DYNAMODB_CONSUMED_CAPACITY, TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS, TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY, TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY, TMP_AWS_DYNAMODB_CONSISTENT_READ, TMP_AWS_DYNAMODB_PROJECTION, TMP_AWS_DYNAMODB_LIMIT, TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET, TMP_AWS_DYNAMODB_INDEX_NAME, TMP_AWS_DYNAMODB_SELECT, TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES, TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES, TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE, TMP_AWS_DYNAMODB_TABLE_COUNT, TMP_AWS_DYNAMODB_SCAN_FORWARD, TMP_AWS_DYNAMODB_SEGMENT, TMP_AWS_DYNAMODB_TOTAL_SEGMENTS, TMP_AWS_DYNAMODB_COUNT, TMP_AWS_DYNAMODB_SCANNED_COUNT, TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS, TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES, TMP_MESSAGING_SYSTEM, TMP_MESSAGING_DESTINATION, TMP_MESSAGING_DESTINATION_KIND, TMP_MESSAGING_TEMP_DESTINATION, TMP_MESSAGING_PROTOCOL, TMP_MESSAGING_PROTOCOL_VERSION, TMP_MESSAGING_URL, TMP_MESSAGING_MESSAGE_ID, TMP_MESSAGING_CONVERSATION_ID, TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES, TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES, TMP_MESSAGING_OPERATION, TMP_MESSAGING_CONSUMER_ID, TMP_MESSAGING_RABBITMQ_ROUTING_KEY, TMP_MESSAGING_KAFKA_MESSAGE_KEY, TMP_MESSAGING_KAFKA_CONSUMER_GROUP, TMP_MESSAGING_KAFKA_CLIENT_ID, TMP_MESSAGING_KAFKA_PARTITION, TMP_MESSAGING_KAFKA_TOMBSTONE, TMP_RPC_SYSTEM, TMP_RPC_SERVICE, TMP_RPC_METHOD, TMP_RPC_GRPC_STATUS_CODE, TMP_RPC_JSONRPC_VERSION, TMP_RPC_JSONRPC_REQUEST_ID, TMP_RPC_JSONRPC_ERROR_CODE, TMP_RPC_JSONRPC_ERROR_MESSAGE, TMP_MESSAGE_TYPE, TMP_MESSAGE_ID, TMP_MESSAGE_COMPRESSED_SIZE, TMP_MESSAGE_UNCOMPRESSED_SIZE, SEMATTRS_AWS_LAMBDA_INVOKED_ARN, SEMATTRS_DB_SYSTEM, SEMATTRS_DB_CONNECTION_STRING, SEMATTRS_DB_USER, SEMATTRS_DB_JDBC_DRIVER_CLASSNAME, SEMATTRS_DB_NAME, SEMATTRS_DB_STATEMENT, SEMATTRS_DB_OPERATION, SEMATTRS_DB_MSSQL_INSTANCE_NAME, SEMATTRS_DB_CASSANDRA_KEYSPACE, SEMATTRS_DB_CASSANDRA_PAGE_SIZE, SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL, SEMATTRS_DB_CASSANDRA_TABLE, SEMATTRS_DB_CASSANDRA_IDEMPOTENCE, SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT, SEMATTRS_DB_CASSANDRA_COORDINATOR_ID, SEMATTRS_DB_CASSANDRA_COORDINATOR_DC, SEMATTRS_DB_HBASE_NAMESPACE, SEMATTRS_DB_REDIS_DATABASE_INDEX, SEMATTRS_DB_MONGODB_COLLECTION, SEMATTRS_DB_SQL_TABLE, SEMATTRS_EXCEPTION_TYPE, SEMATTRS_EXCEPTION_MESSAGE, SEMATTRS_EXCEPTION_STACKTRACE, SEMATTRS_EXCEPTION_ESCAPED, SEMATTRS_FAAS_TRIGGER, SEMATTRS_FAAS_EXECUTION, SEMATTRS_FAAS_DOCUMENT_COLLECTION, SEMATTRS_FAAS_DOCUMENT_OPERATION, SEMATTRS_FAAS_DOCUMENT_TIME, SEMATTRS_FAAS_DOCUMENT_NAME, SEMATTRS_FAAS_TIME, SEMATTRS_FAAS_CRON, SEMATTRS_FAAS_COLDSTART, SEMATTRS_FAAS_INVOKED_NAME, SEMATTRS_FAAS_INVOKED_PROVIDER, SEMATTRS_FAAS_INVOKED_REGION, SEMATTRS_NET_TRANSPORT, SEMATTRS_NET_PEER_IP, SEMATTRS_NET_PEER_PORT, SEMATTRS_NET_PEER_NAME, SEMATTRS_NET_HOST_IP, SEMATTRS_NET_HOST_PORT, SEMATTRS_NET_HOST_NAME, SEMATTRS_NET_HOST_CONNECTION_TYPE, SEMATTRS_NET_HOST_CONNECTION_SUBTYPE, SEMATTRS_NET_HOST_CARRIER_NAME, SEMATTRS_NET_HOST_CARRIER_MCC, SEMATTRS_NET_HOST_CARRIER_MNC, SEMATTRS_NET_HOST_CARRIER_ICC, SEMATTRS_PEER_SERVICE, SEMATTRS_ENDUSER_ID, SEMATTRS_ENDUSER_ROLE, SEMATTRS_ENDUSER_SCOPE, SEMATTRS_THREAD_ID, SEMATTRS_THREAD_NAME, SEMATTRS_CODE_FUNCTION, SEMATTRS_CODE_NAMESPACE, SEMATTRS_CODE_FILEPATH, SEMATTRS_CODE_LINENO, SEMATTRS_HTTP_METHOD, SEMATTRS_HTTP_URL, SEMATTRS_HTTP_TARGET, SEMATTRS_HTTP_HOST, SEMATTRS_HTTP_SCHEME, SEMATTRS_HTTP_STATUS_CODE, SEMATTRS_HTTP_FLAVOR, SEMATTRS_HTTP_USER_AGENT, SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH, SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED, SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH, SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, SEMATTRS_HTTP_SERVER_NAME, SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_CLIENT_IP, SEMATTRS_AWS_DYNAMODB_TABLE_NAMES, SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY, SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS, SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY, SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY, SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ, SEMATTRS_AWS_DYNAMODB_PROJECTION, SEMATTRS_AWS_DYNAMODB_LIMIT, SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET, SEMATTRS_AWS_DYNAMODB_INDEX_NAME, SEMATTRS_AWS_DYNAMODB_SELECT, SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES, SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES, SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE, SEMATTRS_AWS_DYNAMODB_TABLE_COUNT, SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD, SEMATTRS_AWS_DYNAMODB_SEGMENT, SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS, SEMATTRS_AWS_DYNAMODB_COUNT, SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT, SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS, SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES, SEMATTRS_MESSAGING_SYSTEM, SEMATTRS_MESSAGING_DESTINATION, SEMATTRS_MESSAGING_DESTINATION_KIND, SEMATTRS_MESSAGING_TEMP_DESTINATION, SEMATTRS_MESSAGING_PROTOCOL, SEMATTRS_MESSAGING_PROTOCOL_VERSION, SEMATTRS_MESSAGING_URL, SEMATTRS_MESSAGING_MESSAGE_ID, SEMATTRS_MESSAGING_CONVERSATION_ID, SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES, SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES, SEMATTRS_MESSAGING_OPERATION, SEMATTRS_MESSAGING_CONSUMER_ID, SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY, SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY, SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP, SEMATTRS_MESSAGING_KAFKA_CLIENT_ID, SEMATTRS_MESSAGING_KAFKA_PARTITION, SEMATTRS_MESSAGING_KAFKA_TOMBSTONE, SEMATTRS_RPC_SYSTEM, SEMATTRS_RPC_SERVICE, SEMATTRS_RPC_METHOD, SEMATTRS_RPC_GRPC_STATUS_CODE, SEMATTRS_RPC_JSONRPC_VERSION, SEMATTRS_RPC_JSONRPC_REQUEST_ID, SEMATTRS_RPC_JSONRPC_ERROR_CODE, SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE, SEMATTRS_MESSAGE_TYPE, SEMATTRS_MESSAGE_ID, SEMATTRS_MESSAGE_COMPRESSED_SIZE, SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE, SemanticAttributes, TMP_DBSYSTEMVALUES_OTHER_SQL, TMP_DBSYSTEMVALUES_MSSQL, TMP_DBSYSTEMVALUES_MYSQL, TMP_DBSYSTEMVALUES_ORACLE, TMP_DBSYSTEMVALUES_DB2, TMP_DBSYSTEMVALUES_POSTGRESQL, TMP_DBSYSTEMVALUES_REDSHIFT, TMP_DBSYSTEMVALUES_HIVE, TMP_DBSYSTEMVALUES_CLOUDSCAPE, TMP_DBSYSTEMVALUES_HSQLDB, TMP_DBSYSTEMVALUES_PROGRESS, TMP_DBSYSTEMVALUES_MAXDB, TMP_DBSYSTEMVALUES_HANADB, TMP_DBSYSTEMVALUES_INGRES, TMP_DBSYSTEMVALUES_FIRSTSQL, TMP_DBSYSTEMVALUES_EDB, TMP_DBSYSTEMVALUES_CACHE, TMP_DBSYSTEMVALUES_ADABAS, TMP_DBSYSTEMVALUES_FIREBIRD, TMP_DBSYSTEMVALUES_DERBY, TMP_DBSYSTEMVALUES_FILEMAKER, TMP_DBSYSTEMVALUES_INFORMIX, TMP_DBSYSTEMVALUES_INSTANTDB, TMP_DBSYSTEMVALUES_INTERBASE, TMP_DBSYSTEMVALUES_MARIADB, TMP_DBSYSTEMVALUES_NETEZZA, TMP_DBSYSTEMVALUES_PERVASIVE, TMP_DBSYSTEMVALUES_POINTBASE, TMP_DBSYSTEMVALUES_SQLITE, TMP_DBSYSTEMVALUES_SYBASE, TMP_DBSYSTEMVALUES_TERADATA, TMP_DBSYSTEMVALUES_VERTICA, TMP_DBSYSTEMVALUES_H2, TMP_DBSYSTEMVALUES_COLDFUSION, TMP_DBSYSTEMVALUES_CASSANDRA, TMP_DBSYSTEMVALUES_HBASE, TMP_DBSYSTEMVALUES_MONGODB, TMP_DBSYSTEMVALUES_REDIS, TMP_DBSYSTEMVALUES_COUCHBASE, TMP_DBSYSTEMVALUES_COUCHDB, TMP_DBSYSTEMVALUES_COSMOSDB, TMP_DBSYSTEMVALUES_DYNAMODB, TMP_DBSYSTEMVALUES_NEO4J, TMP_DBSYSTEMVALUES_GEODE, TMP_DBSYSTEMVALUES_ELASTICSEARCH, TMP_DBSYSTEMVALUES_MEMCACHED, TMP_DBSYSTEMVALUES_COCKROACHDB, DBSYSTEMVALUES_OTHER_SQL, DBSYSTEMVALUES_MSSQL, DBSYSTEMVALUES_MYSQL, DBSYSTEMVALUES_ORACLE, DBSYSTEMVALUES_DB2, DBSYSTEMVALUES_POSTGRESQL, DBSYSTEMVALUES_REDSHIFT, DBSYSTEMVALUES_HIVE, DBSYSTEMVALUES_CLOUDSCAPE, DBSYSTEMVALUES_HSQLDB, DBSYSTEMVALUES_PROGRESS, DBSYSTEMVALUES_MAXDB, DBSYSTEMVALUES_HANADB, DBSYSTEMVALUES_INGRES, DBSYSTEMVALUES_FIRSTSQL, DBSYSTEMVALUES_EDB, DBSYSTEMVALUES_CACHE, DBSYSTEMVALUES_ADABAS, DBSYSTEMVALUES_FIREBIRD, DBSYSTEMVALUES_DERBY, DBSYSTEMVALUES_FILEMAKER, DBSYSTEMVALUES_INFORMIX, DBSYSTEMVALUES_INSTANTDB, DBSYSTEMVALUES_INTERBASE, DBSYSTEMVALUES_MARIADB, DBSYSTEMVALUES_NETEZZA, DBSYSTEMVALUES_PERVASIVE, DBSYSTEMVALUES_POINTBASE, DBSYSTEMVALUES_SQLITE, DBSYSTEMVALUES_SYBASE, DBSYSTEMVALUES_TERADATA, DBSYSTEMVALUES_VERTICA, DBSYSTEMVALUES_H2, DBSYSTEMVALUES_COLDFUSION, DBSYSTEMVALUES_CASSANDRA, DBSYSTEMVALUES_HBASE, DBSYSTEMVALUES_MONGODB, DBSYSTEMVALUES_REDIS, DBSYSTEMVALUES_COUCHBASE, DBSYSTEMVALUES_COUCHDB, DBSYSTEMVALUES_COSMOSDB, DBSYSTEMVALUES_DYNAMODB, DBSYSTEMVALUES_NEO4J, DBSYSTEMVALUES_GEODE, DBSYSTEMVALUES_ELASTICSEARCH, DBSYSTEMVALUES_MEMCACHED, DBSYSTEMVALUES_COCKROACHDB, DbSystemValues, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL, DBCASSANDRACONSISTENCYLEVELVALUES_ALL, DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM, DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM, DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM, DBCASSANDRACONSISTENCYLEVELVALUES_ONE, DBCASSANDRACONSISTENCYLEVELVALUES_TWO, DBCASSANDRACONSISTENCYLEVELVALUES_THREE, DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE, DBCASSANDRACONSISTENCYLEVELVALUES_ANY, DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL, DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL, DbCassandraConsistencyLevelValues, TMP_FAASTRIGGERVALUES_DATASOURCE, TMP_FAASTRIGGERVALUES_HTTP, TMP_FAASTRIGGERVALUES_PUBSUB, TMP_FAASTRIGGERVALUES_TIMER, TMP_FAASTRIGGERVALUES_OTHER, FAASTRIGGERVALUES_DATASOURCE, FAASTRIGGERVALUES_HTTP, FAASTRIGGERVALUES_PUBSUB, FAASTRIGGERVALUES_TIMER, FAASTRIGGERVALUES_OTHER, FaasTriggerValues, TMP_FAASDOCUMENTOPERATIONVALUES_INSERT, TMP_FAASDOCUMENTOPERATIONVALUES_EDIT, TMP_FAASDOCUMENTOPERATIONVALUES_DELETE, FAASDOCUMENTOPERATIONVALUES_INSERT, FAASDOCUMENTOPERATIONVALUES_EDIT, FAASDOCUMENTOPERATIONVALUES_DELETE, FaasDocumentOperationValues, TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD, TMP_FAASINVOKEDPROVIDERVALUES_AWS, TMP_FAASINVOKEDPROVIDERVALUES_AZURE, TMP_FAASINVOKEDPROVIDERVALUES_GCP, FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD, FAASINVOKEDPROVIDERVALUES_AWS, FAASINVOKEDPROVIDERVALUES_AZURE, FAASINVOKEDPROVIDERVALUES_GCP, FaasInvokedProviderValues, TMP_NETTRANSPORTVALUES_IP_TCP, TMP_NETTRANSPORTVALUES_IP_UDP, TMP_NETTRANSPORTVALUES_IP, TMP_NETTRANSPORTVALUES_UNIX, TMP_NETTRANSPORTVALUES_PIPE, TMP_NETTRANSPORTVALUES_INPROC, TMP_NETTRANSPORTVALUES_OTHER, NETTRANSPORTVALUES_IP_TCP, NETTRANSPORTVALUES_IP_UDP, NETTRANSPORTVALUES_IP, NETTRANSPORTVALUES_UNIX, NETTRANSPORTVALUES_PIPE, NETTRANSPORTVALUES_INPROC, NETTRANSPORTVALUES_OTHER, NetTransportValues, TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI, TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED, TMP_NETHOSTCONNECTIONTYPEVALUES_CELL, TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE, TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN, NETHOSTCONNECTIONTYPEVALUES_WIFI, NETHOSTCONNECTIONTYPEVALUES_WIRED, NETHOSTCONNECTIONTYPEVALUES_CELL, NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE, NETHOSTCONNECTIONTYPEVALUES_UNKNOWN, NetHostConnectionTypeValues, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA, NETHOSTCONNECTIONSUBTYPEVALUES_GPRS, NETHOSTCONNECTIONSUBTYPEVALUES_EDGE, NETHOSTCONNECTIONSUBTYPEVALUES_UMTS, NETHOSTCONNECTIONSUBTYPEVALUES_CDMA, NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0, NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A, NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT, NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA, NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA, NETHOSTCONNECTIONSUBTYPEVALUES_HSPA, NETHOSTCONNECTIONSUBTYPEVALUES_IDEN, NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B, NETHOSTCONNECTIONSUBTYPEVALUES_LTE, NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD, NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP, NETHOSTCONNECTIONSUBTYPEVALUES_GSM, NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA, NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN, NETHOSTCONNECTIONSUBTYPEVALUES_NR, NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA, NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA, NetHostConnectionSubtypeValues, TMP_HTTPFLAVORVALUES_HTTP_1_0, TMP_HTTPFLAVORVALUES_HTTP_1_1, TMP_HTTPFLAVORVALUES_HTTP_2_0, TMP_HTTPFLAVORVALUES_SPDY, TMP_HTTPFLAVORVALUES_QUIC, HTTPFLAVORVALUES_HTTP_1_0, HTTPFLAVORVALUES_HTTP_1_1, HTTPFLAVORVALUES_HTTP_2_0, HTTPFLAVORVALUES_SPDY, HTTPFLAVORVALUES_QUIC, HttpFlavorValues, TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE, TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC, MESSAGINGDESTINATIONKINDVALUES_QUEUE, MESSAGINGDESTINATIONKINDVALUES_TOPIC, MessagingDestinationKindValues, TMP_MESSAGINGOPERATIONVALUES_RECEIVE, TMP_MESSAGINGOPERATIONVALUES_PROCESS, MESSAGINGOPERATIONVALUES_RECEIVE, MESSAGINGOPERATIONVALUES_PROCESS, MessagingOperationValues, TMP_RPCGRPCSTATUSCODEVALUES_OK, TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED, TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN, TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT, TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED, TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND, TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS, TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED, TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED, TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION, TMP_RPCGRPCSTATUSCODEVALUES_ABORTED, TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE, TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED, TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL, TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE, TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS, TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED, RPCGRPCSTATUSCODEVALUES_OK, RPCGRPCSTATUSCODEVALUES_CANCELLED, RPCGRPCSTATUSCODEVALUES_UNKNOWN, RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT, RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED, RPCGRPCSTATUSCODEVALUES_NOT_FOUND, RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS, RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED, RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED, RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION, RPCGRPCSTATUSCODEVALUES_ABORTED, RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE, RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED, RPCGRPCSTATUSCODEVALUES_INTERNAL, RPCGRPCSTATUSCODEVALUES_UNAVAILABLE, RPCGRPCSTATUSCODEVALUES_DATA_LOSS, RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED, RpcGrpcStatusCodeValues, TMP_MESSAGETYPEVALUES_SENT, TMP_MESSAGETYPEVALUES_RECEIVED, MESSAGETYPEVALUES_SENT, MESSAGETYPEVALUES_RECEIVED, MessageTypeValues;
var init_SemanticAttributes = __esm({
  "node_modules/@opentelemetry/semantic-conventions/build/esm/trace/SemanticAttributes.js"() {
    init_esbuild_shims();
    init_utils();
    TMP_AWS_LAMBDA_INVOKED_ARN = "aws.lambda.invoked_arn";
    TMP_DB_SYSTEM = "db.system";
    TMP_DB_CONNECTION_STRING = "db.connection_string";
    TMP_DB_USER = "db.user";
    TMP_DB_JDBC_DRIVER_CLASSNAME = "db.jdbc.driver_classname";
    TMP_DB_NAME = "db.name";
    TMP_DB_STATEMENT = "db.statement";
    TMP_DB_OPERATION = "db.operation";
    TMP_DB_MSSQL_INSTANCE_NAME = "db.mssql.instance_name";
    TMP_DB_CASSANDRA_KEYSPACE = "db.cassandra.keyspace";
    TMP_DB_CASSANDRA_PAGE_SIZE = "db.cassandra.page_size";
    TMP_DB_CASSANDRA_CONSISTENCY_LEVEL = "db.cassandra.consistency_level";
    TMP_DB_CASSANDRA_TABLE = "db.cassandra.table";
    TMP_DB_CASSANDRA_IDEMPOTENCE = "db.cassandra.idempotence";
    TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = "db.cassandra.speculative_execution_count";
    TMP_DB_CASSANDRA_COORDINATOR_ID = "db.cassandra.coordinator.id";
    TMP_DB_CASSANDRA_COORDINATOR_DC = "db.cassandra.coordinator.dc";
    TMP_DB_HBASE_NAMESPACE = "db.hbase.namespace";
    TMP_DB_REDIS_DATABASE_INDEX = "db.redis.database_index";
    TMP_DB_MONGODB_COLLECTION = "db.mongodb.collection";
    TMP_DB_SQL_TABLE = "db.sql.table";
    TMP_EXCEPTION_TYPE = "exception.type";
    TMP_EXCEPTION_MESSAGE = "exception.message";
    TMP_EXCEPTION_STACKTRACE = "exception.stacktrace";
    TMP_EXCEPTION_ESCAPED = "exception.escaped";
    TMP_FAAS_TRIGGER = "faas.trigger";
    TMP_FAAS_EXECUTION = "faas.execution";
    TMP_FAAS_DOCUMENT_COLLECTION = "faas.document.collection";
    TMP_FAAS_DOCUMENT_OPERATION = "faas.document.operation";
    TMP_FAAS_DOCUMENT_TIME = "faas.document.time";
    TMP_FAAS_DOCUMENT_NAME = "faas.document.name";
    TMP_FAAS_TIME = "faas.time";
    TMP_FAAS_CRON = "faas.cron";
    TMP_FAAS_COLDSTART = "faas.coldstart";
    TMP_FAAS_INVOKED_NAME = "faas.invoked_name";
    TMP_FAAS_INVOKED_PROVIDER = "faas.invoked_provider";
    TMP_FAAS_INVOKED_REGION = "faas.invoked_region";
    TMP_NET_TRANSPORT = "net.transport";
    TMP_NET_PEER_IP = "net.peer.ip";
    TMP_NET_PEER_PORT = "net.peer.port";
    TMP_NET_PEER_NAME = "net.peer.name";
    TMP_NET_HOST_IP = "net.host.ip";
    TMP_NET_HOST_PORT = "net.host.port";
    TMP_NET_HOST_NAME = "net.host.name";
    TMP_NET_HOST_CONNECTION_TYPE = "net.host.connection.type";
    TMP_NET_HOST_CONNECTION_SUBTYPE = "net.host.connection.subtype";
    TMP_NET_HOST_CARRIER_NAME = "net.host.carrier.name";
    TMP_NET_HOST_CARRIER_MCC = "net.host.carrier.mcc";
    TMP_NET_HOST_CARRIER_MNC = "net.host.carrier.mnc";
    TMP_NET_HOST_CARRIER_ICC = "net.host.carrier.icc";
    TMP_PEER_SERVICE = "peer.service";
    TMP_ENDUSER_ID = "enduser.id";
    TMP_ENDUSER_ROLE = "enduser.role";
    TMP_ENDUSER_SCOPE = "enduser.scope";
    TMP_THREAD_ID = "thread.id";
    TMP_THREAD_NAME = "thread.name";
    TMP_CODE_FUNCTION = "code.function";
    TMP_CODE_NAMESPACE = "code.namespace";
    TMP_CODE_FILEPATH = "code.filepath";
    TMP_CODE_LINENO = "code.lineno";
    TMP_HTTP_METHOD = "http.method";
    TMP_HTTP_URL = "http.url";
    TMP_HTTP_TARGET = "http.target";
    TMP_HTTP_HOST = "http.host";
    TMP_HTTP_SCHEME = "http.scheme";
    TMP_HTTP_STATUS_CODE = "http.status_code";
    TMP_HTTP_FLAVOR = "http.flavor";
    TMP_HTTP_USER_AGENT = "http.user_agent";
    TMP_HTTP_REQUEST_CONTENT_LENGTH = "http.request_content_length";
    TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = "http.request_content_length_uncompressed";
    TMP_HTTP_RESPONSE_CONTENT_LENGTH = "http.response_content_length";
    TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = "http.response_content_length_uncompressed";
    TMP_HTTP_SERVER_NAME = "http.server_name";
    TMP_HTTP_ROUTE = "http.route";
    TMP_HTTP_CLIENT_IP = "http.client_ip";
    TMP_AWS_DYNAMODB_TABLE_NAMES = "aws.dynamodb.table_names";
    TMP_AWS_DYNAMODB_CONSUMED_CAPACITY = "aws.dynamodb.consumed_capacity";
    TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = "aws.dynamodb.item_collection_metrics";
    TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = "aws.dynamodb.provisioned_read_capacity";
    TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = "aws.dynamodb.provisioned_write_capacity";
    TMP_AWS_DYNAMODB_CONSISTENT_READ = "aws.dynamodb.consistent_read";
    TMP_AWS_DYNAMODB_PROJECTION = "aws.dynamodb.projection";
    TMP_AWS_DYNAMODB_LIMIT = "aws.dynamodb.limit";
    TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET = "aws.dynamodb.attributes_to_get";
    TMP_AWS_DYNAMODB_INDEX_NAME = "aws.dynamodb.index_name";
    TMP_AWS_DYNAMODB_SELECT = "aws.dynamodb.select";
    TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = "aws.dynamodb.global_secondary_indexes";
    TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = "aws.dynamodb.local_secondary_indexes";
    TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = "aws.dynamodb.exclusive_start_table";
    TMP_AWS_DYNAMODB_TABLE_COUNT = "aws.dynamodb.table_count";
    TMP_AWS_DYNAMODB_SCAN_FORWARD = "aws.dynamodb.scan_forward";
    TMP_AWS_DYNAMODB_SEGMENT = "aws.dynamodb.segment";
    TMP_AWS_DYNAMODB_TOTAL_SEGMENTS = "aws.dynamodb.total_segments";
    TMP_AWS_DYNAMODB_COUNT = "aws.dynamodb.count";
    TMP_AWS_DYNAMODB_SCANNED_COUNT = "aws.dynamodb.scanned_count";
    TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = "aws.dynamodb.attribute_definitions";
    TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = "aws.dynamodb.global_secondary_index_updates";
    TMP_MESSAGING_SYSTEM = "messaging.system";
    TMP_MESSAGING_DESTINATION = "messaging.destination";
    TMP_MESSAGING_DESTINATION_KIND = "messaging.destination_kind";
    TMP_MESSAGING_TEMP_DESTINATION = "messaging.temp_destination";
    TMP_MESSAGING_PROTOCOL = "messaging.protocol";
    TMP_MESSAGING_PROTOCOL_VERSION = "messaging.protocol_version";
    TMP_MESSAGING_URL = "messaging.url";
    TMP_MESSAGING_MESSAGE_ID = "messaging.message_id";
    TMP_MESSAGING_CONVERSATION_ID = "messaging.conversation_id";
    TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = "messaging.message_payload_size_bytes";
    TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = "messaging.message_payload_compressed_size_bytes";
    TMP_MESSAGING_OPERATION = "messaging.operation";
    TMP_MESSAGING_CONSUMER_ID = "messaging.consumer_id";
    TMP_MESSAGING_RABBITMQ_ROUTING_KEY = "messaging.rabbitmq.routing_key";
    TMP_MESSAGING_KAFKA_MESSAGE_KEY = "messaging.kafka.message_key";
    TMP_MESSAGING_KAFKA_CONSUMER_GROUP = "messaging.kafka.consumer_group";
    TMP_MESSAGING_KAFKA_CLIENT_ID = "messaging.kafka.client_id";
    TMP_MESSAGING_KAFKA_PARTITION = "messaging.kafka.partition";
    TMP_MESSAGING_KAFKA_TOMBSTONE = "messaging.kafka.tombstone";
    TMP_RPC_SYSTEM = "rpc.system";
    TMP_RPC_SERVICE = "rpc.service";
    TMP_RPC_METHOD = "rpc.method";
    TMP_RPC_GRPC_STATUS_CODE = "rpc.grpc.status_code";
    TMP_RPC_JSONRPC_VERSION = "rpc.jsonrpc.version";
    TMP_RPC_JSONRPC_REQUEST_ID = "rpc.jsonrpc.request_id";
    TMP_RPC_JSONRPC_ERROR_CODE = "rpc.jsonrpc.error_code";
    TMP_RPC_JSONRPC_ERROR_MESSAGE = "rpc.jsonrpc.error_message";
    TMP_MESSAGE_TYPE = "message.type";
    TMP_MESSAGE_ID = "message.id";
    TMP_MESSAGE_COMPRESSED_SIZE = "message.compressed_size";
    TMP_MESSAGE_UNCOMPRESSED_SIZE = "message.uncompressed_size";
    SEMATTRS_AWS_LAMBDA_INVOKED_ARN = TMP_AWS_LAMBDA_INVOKED_ARN;
    SEMATTRS_DB_SYSTEM = TMP_DB_SYSTEM;
    SEMATTRS_DB_CONNECTION_STRING = TMP_DB_CONNECTION_STRING;
    SEMATTRS_DB_USER = TMP_DB_USER;
    SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = TMP_DB_JDBC_DRIVER_CLASSNAME;
    SEMATTRS_DB_NAME = TMP_DB_NAME;
    SEMATTRS_DB_STATEMENT = TMP_DB_STATEMENT;
    SEMATTRS_DB_OPERATION = TMP_DB_OPERATION;
    SEMATTRS_DB_MSSQL_INSTANCE_NAME = TMP_DB_MSSQL_INSTANCE_NAME;
    SEMATTRS_DB_CASSANDRA_KEYSPACE = TMP_DB_CASSANDRA_KEYSPACE;
    SEMATTRS_DB_CASSANDRA_PAGE_SIZE = TMP_DB_CASSANDRA_PAGE_SIZE;
    SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = TMP_DB_CASSANDRA_CONSISTENCY_LEVEL;
    SEMATTRS_DB_CASSANDRA_TABLE = TMP_DB_CASSANDRA_TABLE;
    SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = TMP_DB_CASSANDRA_IDEMPOTENCE;
    SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT;
    SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = TMP_DB_CASSANDRA_COORDINATOR_ID;
    SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = TMP_DB_CASSANDRA_COORDINATOR_DC;
    SEMATTRS_DB_HBASE_NAMESPACE = TMP_DB_HBASE_NAMESPACE;
    SEMATTRS_DB_REDIS_DATABASE_INDEX = TMP_DB_REDIS_DATABASE_INDEX;
    SEMATTRS_DB_MONGODB_COLLECTION = TMP_DB_MONGODB_COLLECTION;
    SEMATTRS_DB_SQL_TABLE = TMP_DB_SQL_TABLE;
    SEMATTRS_EXCEPTION_TYPE = TMP_EXCEPTION_TYPE;
    SEMATTRS_EXCEPTION_MESSAGE = TMP_EXCEPTION_MESSAGE;
    SEMATTRS_EXCEPTION_STACKTRACE = TMP_EXCEPTION_STACKTRACE;
    SEMATTRS_EXCEPTION_ESCAPED = TMP_EXCEPTION_ESCAPED;
    SEMATTRS_FAAS_TRIGGER = TMP_FAAS_TRIGGER;
    SEMATTRS_FAAS_EXECUTION = TMP_FAAS_EXECUTION;
    SEMATTRS_FAAS_DOCUMENT_COLLECTION = TMP_FAAS_DOCUMENT_COLLECTION;
    SEMATTRS_FAAS_DOCUMENT_OPERATION = TMP_FAAS_DOCUMENT_OPERATION;
    SEMATTRS_FAAS_DOCUMENT_TIME = TMP_FAAS_DOCUMENT_TIME;
    SEMATTRS_FAAS_DOCUMENT_NAME = TMP_FAAS_DOCUMENT_NAME;
    SEMATTRS_FAAS_TIME = TMP_FAAS_TIME;
    SEMATTRS_FAAS_CRON = TMP_FAAS_CRON;
    SEMATTRS_FAAS_COLDSTART = TMP_FAAS_COLDSTART;
    SEMATTRS_FAAS_INVOKED_NAME = TMP_FAAS_INVOKED_NAME;
    SEMATTRS_FAAS_INVOKED_PROVIDER = TMP_FAAS_INVOKED_PROVIDER;
    SEMATTRS_FAAS_INVOKED_REGION = TMP_FAAS_INVOKED_REGION;
    SEMATTRS_NET_TRANSPORT = TMP_NET_TRANSPORT;
    SEMATTRS_NET_PEER_IP = TMP_NET_PEER_IP;
    SEMATTRS_NET_PEER_PORT = TMP_NET_PEER_PORT;
    SEMATTRS_NET_PEER_NAME = TMP_NET_PEER_NAME;
    SEMATTRS_NET_HOST_IP = TMP_NET_HOST_IP;
    SEMATTRS_NET_HOST_PORT = TMP_NET_HOST_PORT;
    SEMATTRS_NET_HOST_NAME = TMP_NET_HOST_NAME;
    SEMATTRS_NET_HOST_CONNECTION_TYPE = TMP_NET_HOST_CONNECTION_TYPE;
    SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = TMP_NET_HOST_CONNECTION_SUBTYPE;
    SEMATTRS_NET_HOST_CARRIER_NAME = TMP_NET_HOST_CARRIER_NAME;
    SEMATTRS_NET_HOST_CARRIER_MCC = TMP_NET_HOST_CARRIER_MCC;
    SEMATTRS_NET_HOST_CARRIER_MNC = TMP_NET_HOST_CARRIER_MNC;
    SEMATTRS_NET_HOST_CARRIER_ICC = TMP_NET_HOST_CARRIER_ICC;
    SEMATTRS_PEER_SERVICE = TMP_PEER_SERVICE;
    SEMATTRS_ENDUSER_ID = TMP_ENDUSER_ID;
    SEMATTRS_ENDUSER_ROLE = TMP_ENDUSER_ROLE;
    SEMATTRS_ENDUSER_SCOPE = TMP_ENDUSER_SCOPE;
    SEMATTRS_THREAD_ID = TMP_THREAD_ID;
    SEMATTRS_THREAD_NAME = TMP_THREAD_NAME;
    SEMATTRS_CODE_FUNCTION = TMP_CODE_FUNCTION;
    SEMATTRS_CODE_NAMESPACE = TMP_CODE_NAMESPACE;
    SEMATTRS_CODE_FILEPATH = TMP_CODE_FILEPATH;
    SEMATTRS_CODE_LINENO = TMP_CODE_LINENO;
    SEMATTRS_HTTP_METHOD = TMP_HTTP_METHOD;
    SEMATTRS_HTTP_URL = TMP_HTTP_URL;
    SEMATTRS_HTTP_TARGET = TMP_HTTP_TARGET;
    SEMATTRS_HTTP_HOST = TMP_HTTP_HOST;
    SEMATTRS_HTTP_SCHEME = TMP_HTTP_SCHEME;
    SEMATTRS_HTTP_STATUS_CODE = TMP_HTTP_STATUS_CODE;
    SEMATTRS_HTTP_FLAVOR = TMP_HTTP_FLAVOR;
    SEMATTRS_HTTP_USER_AGENT = TMP_HTTP_USER_AGENT;
    SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = TMP_HTTP_REQUEST_CONTENT_LENGTH;
    SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED;
    SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = TMP_HTTP_RESPONSE_CONTENT_LENGTH;
    SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED;
    SEMATTRS_HTTP_SERVER_NAME = TMP_HTTP_SERVER_NAME;
    SEMATTRS_HTTP_ROUTE = TMP_HTTP_ROUTE;
    SEMATTRS_HTTP_CLIENT_IP = TMP_HTTP_CLIENT_IP;
    SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = TMP_AWS_DYNAMODB_TABLE_NAMES;
    SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = TMP_AWS_DYNAMODB_CONSUMED_CAPACITY;
    SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS;
    SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY;
    SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY;
    SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = TMP_AWS_DYNAMODB_CONSISTENT_READ;
    SEMATTRS_AWS_DYNAMODB_PROJECTION = TMP_AWS_DYNAMODB_PROJECTION;
    SEMATTRS_AWS_DYNAMODB_LIMIT = TMP_AWS_DYNAMODB_LIMIT;
    SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET;
    SEMATTRS_AWS_DYNAMODB_INDEX_NAME = TMP_AWS_DYNAMODB_INDEX_NAME;
    SEMATTRS_AWS_DYNAMODB_SELECT = TMP_AWS_DYNAMODB_SELECT;
    SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES;
    SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES;
    SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE;
    SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = TMP_AWS_DYNAMODB_TABLE_COUNT;
    SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = TMP_AWS_DYNAMODB_SCAN_FORWARD;
    SEMATTRS_AWS_DYNAMODB_SEGMENT = TMP_AWS_DYNAMODB_SEGMENT;
    SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = TMP_AWS_DYNAMODB_TOTAL_SEGMENTS;
    SEMATTRS_AWS_DYNAMODB_COUNT = TMP_AWS_DYNAMODB_COUNT;
    SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = TMP_AWS_DYNAMODB_SCANNED_COUNT;
    SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS;
    SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES;
    SEMATTRS_MESSAGING_SYSTEM = TMP_MESSAGING_SYSTEM;
    SEMATTRS_MESSAGING_DESTINATION = TMP_MESSAGING_DESTINATION;
    SEMATTRS_MESSAGING_DESTINATION_KIND = TMP_MESSAGING_DESTINATION_KIND;
    SEMATTRS_MESSAGING_TEMP_DESTINATION = TMP_MESSAGING_TEMP_DESTINATION;
    SEMATTRS_MESSAGING_PROTOCOL = TMP_MESSAGING_PROTOCOL;
    SEMATTRS_MESSAGING_PROTOCOL_VERSION = TMP_MESSAGING_PROTOCOL_VERSION;
    SEMATTRS_MESSAGING_URL = TMP_MESSAGING_URL;
    SEMATTRS_MESSAGING_MESSAGE_ID = TMP_MESSAGING_MESSAGE_ID;
    SEMATTRS_MESSAGING_CONVERSATION_ID = TMP_MESSAGING_CONVERSATION_ID;
    SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES;
    SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES;
    SEMATTRS_MESSAGING_OPERATION = TMP_MESSAGING_OPERATION;
    SEMATTRS_MESSAGING_CONSUMER_ID = TMP_MESSAGING_CONSUMER_ID;
    SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = TMP_MESSAGING_RABBITMQ_ROUTING_KEY;
    SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = TMP_MESSAGING_KAFKA_MESSAGE_KEY;
    SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = TMP_MESSAGING_KAFKA_CONSUMER_GROUP;
    SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = TMP_MESSAGING_KAFKA_CLIENT_ID;
    SEMATTRS_MESSAGING_KAFKA_PARTITION = TMP_MESSAGING_KAFKA_PARTITION;
    SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = TMP_MESSAGING_KAFKA_TOMBSTONE;
    SEMATTRS_RPC_SYSTEM = TMP_RPC_SYSTEM;
    SEMATTRS_RPC_SERVICE = TMP_RPC_SERVICE;
    SEMATTRS_RPC_METHOD = TMP_RPC_METHOD;
    SEMATTRS_RPC_GRPC_STATUS_CODE = TMP_RPC_GRPC_STATUS_CODE;
    SEMATTRS_RPC_JSONRPC_VERSION = TMP_RPC_JSONRPC_VERSION;
    SEMATTRS_RPC_JSONRPC_REQUEST_ID = TMP_RPC_JSONRPC_REQUEST_ID;
    SEMATTRS_RPC_JSONRPC_ERROR_CODE = TMP_RPC_JSONRPC_ERROR_CODE;
    SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = TMP_RPC_JSONRPC_ERROR_MESSAGE;
    SEMATTRS_MESSAGE_TYPE = TMP_MESSAGE_TYPE;
    SEMATTRS_MESSAGE_ID = TMP_MESSAGE_ID;
    SEMATTRS_MESSAGE_COMPRESSED_SIZE = TMP_MESSAGE_COMPRESSED_SIZE;
    SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = TMP_MESSAGE_UNCOMPRESSED_SIZE;
    SemanticAttributes = /* @__PURE__ */ createConstMap([
      TMP_AWS_LAMBDA_INVOKED_ARN,
      TMP_DB_SYSTEM,
      TMP_DB_CONNECTION_STRING,
      TMP_DB_USER,
      TMP_DB_JDBC_DRIVER_CLASSNAME,
      TMP_DB_NAME,
      TMP_DB_STATEMENT,
      TMP_DB_OPERATION,
      TMP_DB_MSSQL_INSTANCE_NAME,
      TMP_DB_CASSANDRA_KEYSPACE,
      TMP_DB_CASSANDRA_PAGE_SIZE,
      TMP_DB_CASSANDRA_CONSISTENCY_LEVEL,
      TMP_DB_CASSANDRA_TABLE,
      TMP_DB_CASSANDRA_IDEMPOTENCE,
      TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,
      TMP_DB_CASSANDRA_COORDINATOR_ID,
      TMP_DB_CASSANDRA_COORDINATOR_DC,
      TMP_DB_HBASE_NAMESPACE,
      TMP_DB_REDIS_DATABASE_INDEX,
      TMP_DB_MONGODB_COLLECTION,
      TMP_DB_SQL_TABLE,
      TMP_EXCEPTION_TYPE,
      TMP_EXCEPTION_MESSAGE,
      TMP_EXCEPTION_STACKTRACE,
      TMP_EXCEPTION_ESCAPED,
      TMP_FAAS_TRIGGER,
      TMP_FAAS_EXECUTION,
      TMP_FAAS_DOCUMENT_COLLECTION,
      TMP_FAAS_DOCUMENT_OPERATION,
      TMP_FAAS_DOCUMENT_TIME,
      TMP_FAAS_DOCUMENT_NAME,
      TMP_FAAS_TIME,
      TMP_FAAS_CRON,
      TMP_FAAS_COLDSTART,
      TMP_FAAS_INVOKED_NAME,
      TMP_FAAS_INVOKED_PROVIDER,
      TMP_FAAS_INVOKED_REGION,
      TMP_NET_TRANSPORT,
      TMP_NET_PEER_IP,
      TMP_NET_PEER_PORT,
      TMP_NET_PEER_NAME,
      TMP_NET_HOST_IP,
      TMP_NET_HOST_PORT,
      TMP_NET_HOST_NAME,
      TMP_NET_HOST_CONNECTION_TYPE,
      TMP_NET_HOST_CONNECTION_SUBTYPE,
      TMP_NET_HOST_CARRIER_NAME,
      TMP_NET_HOST_CARRIER_MCC,
      TMP_NET_HOST_CARRIER_MNC,
      TMP_NET_HOST_CARRIER_ICC,
      TMP_PEER_SERVICE,
      TMP_ENDUSER_ID,
      TMP_ENDUSER_ROLE,
      TMP_ENDUSER_SCOPE,
      TMP_THREAD_ID,
      TMP_THREAD_NAME,
      TMP_CODE_FUNCTION,
      TMP_CODE_NAMESPACE,
      TMP_CODE_FILEPATH,
      TMP_CODE_LINENO,
      TMP_HTTP_METHOD,
      TMP_HTTP_URL,
      TMP_HTTP_TARGET,
      TMP_HTTP_HOST,
      TMP_HTTP_SCHEME,
      TMP_HTTP_STATUS_CODE,
      TMP_HTTP_FLAVOR,
      TMP_HTTP_USER_AGENT,
      TMP_HTTP_REQUEST_CONTENT_LENGTH,
      TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,
      TMP_HTTP_RESPONSE_CONTENT_LENGTH,
      TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,
      TMP_HTTP_SERVER_NAME,
      TMP_HTTP_ROUTE,
      TMP_HTTP_CLIENT_IP,
      TMP_AWS_DYNAMODB_TABLE_NAMES,
      TMP_AWS_DYNAMODB_CONSUMED_CAPACITY,
      TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,
      TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,
      TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,
      TMP_AWS_DYNAMODB_CONSISTENT_READ,
      TMP_AWS_DYNAMODB_PROJECTION,
      TMP_AWS_DYNAMODB_LIMIT,
      TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET,
      TMP_AWS_DYNAMODB_INDEX_NAME,
      TMP_AWS_DYNAMODB_SELECT,
      TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,
      TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,
      TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,
      TMP_AWS_DYNAMODB_TABLE_COUNT,
      TMP_AWS_DYNAMODB_SCAN_FORWARD,
      TMP_AWS_DYNAMODB_SEGMENT,
      TMP_AWS_DYNAMODB_TOTAL_SEGMENTS,
      TMP_AWS_DYNAMODB_COUNT,
      TMP_AWS_DYNAMODB_SCANNED_COUNT,
      TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,
      TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,
      TMP_MESSAGING_SYSTEM,
      TMP_MESSAGING_DESTINATION,
      TMP_MESSAGING_DESTINATION_KIND,
      TMP_MESSAGING_TEMP_DESTINATION,
      TMP_MESSAGING_PROTOCOL,
      TMP_MESSAGING_PROTOCOL_VERSION,
      TMP_MESSAGING_URL,
      TMP_MESSAGING_MESSAGE_ID,
      TMP_MESSAGING_CONVERSATION_ID,
      TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,
      TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,
      TMP_MESSAGING_OPERATION,
      TMP_MESSAGING_CONSUMER_ID,
      TMP_MESSAGING_RABBITMQ_ROUTING_KEY,
      TMP_MESSAGING_KAFKA_MESSAGE_KEY,
      TMP_MESSAGING_KAFKA_CONSUMER_GROUP,
      TMP_MESSAGING_KAFKA_CLIENT_ID,
      TMP_MESSAGING_KAFKA_PARTITION,
      TMP_MESSAGING_KAFKA_TOMBSTONE,
      TMP_RPC_SYSTEM,
      TMP_RPC_SERVICE,
      TMP_RPC_METHOD,
      TMP_RPC_GRPC_STATUS_CODE,
      TMP_RPC_JSONRPC_VERSION,
      TMP_RPC_JSONRPC_REQUEST_ID,
      TMP_RPC_JSONRPC_ERROR_CODE,
      TMP_RPC_JSONRPC_ERROR_MESSAGE,
      TMP_MESSAGE_TYPE,
      TMP_MESSAGE_ID,
      TMP_MESSAGE_COMPRESSED_SIZE,
      TMP_MESSAGE_UNCOMPRESSED_SIZE
    ]);
    TMP_DBSYSTEMVALUES_OTHER_SQL = "other_sql";
    TMP_DBSYSTEMVALUES_MSSQL = "mssql";
    TMP_DBSYSTEMVALUES_MYSQL = "mysql";
    TMP_DBSYSTEMVALUES_ORACLE = "oracle";
    TMP_DBSYSTEMVALUES_DB2 = "db2";
    TMP_DBSYSTEMVALUES_POSTGRESQL = "postgresql";
    TMP_DBSYSTEMVALUES_REDSHIFT = "redshift";
    TMP_DBSYSTEMVALUES_HIVE = "hive";
    TMP_DBSYSTEMVALUES_CLOUDSCAPE = "cloudscape";
    TMP_DBSYSTEMVALUES_HSQLDB = "hsqldb";
    TMP_DBSYSTEMVALUES_PROGRESS = "progress";
    TMP_DBSYSTEMVALUES_MAXDB = "maxdb";
    TMP_DBSYSTEMVALUES_HANADB = "hanadb";
    TMP_DBSYSTEMVALUES_INGRES = "ingres";
    TMP_DBSYSTEMVALUES_FIRSTSQL = "firstsql";
    TMP_DBSYSTEMVALUES_EDB = "edb";
    TMP_DBSYSTEMVALUES_CACHE = "cache";
    TMP_DBSYSTEMVALUES_ADABAS = "adabas";
    TMP_DBSYSTEMVALUES_FIREBIRD = "firebird";
    TMP_DBSYSTEMVALUES_DERBY = "derby";
    TMP_DBSYSTEMVALUES_FILEMAKER = "filemaker";
    TMP_DBSYSTEMVALUES_INFORMIX = "informix";
    TMP_DBSYSTEMVALUES_INSTANTDB = "instantdb";
    TMP_DBSYSTEMVALUES_INTERBASE = "interbase";
    TMP_DBSYSTEMVALUES_MARIADB = "mariadb";
    TMP_DBSYSTEMVALUES_NETEZZA = "netezza";
    TMP_DBSYSTEMVALUES_PERVASIVE = "pervasive";
    TMP_DBSYSTEMVALUES_POINTBASE = "pointbase";
    TMP_DBSYSTEMVALUES_SQLITE = "sqlite";
    TMP_DBSYSTEMVALUES_SYBASE = "sybase";
    TMP_DBSYSTEMVALUES_TERADATA = "teradata";
    TMP_DBSYSTEMVALUES_VERTICA = "vertica";
    TMP_DBSYSTEMVALUES_H2 = "h2";
    TMP_DBSYSTEMVALUES_COLDFUSION = "coldfusion";
    TMP_DBSYSTEMVALUES_CASSANDRA = "cassandra";
    TMP_DBSYSTEMVALUES_HBASE = "hbase";
    TMP_DBSYSTEMVALUES_MONGODB = "mongodb";
    TMP_DBSYSTEMVALUES_REDIS = "redis";
    TMP_DBSYSTEMVALUES_COUCHBASE = "couchbase";
    TMP_DBSYSTEMVALUES_COUCHDB = "couchdb";
    TMP_DBSYSTEMVALUES_COSMOSDB = "cosmosdb";
    TMP_DBSYSTEMVALUES_DYNAMODB = "dynamodb";
    TMP_DBSYSTEMVALUES_NEO4J = "neo4j";
    TMP_DBSYSTEMVALUES_GEODE = "geode";
    TMP_DBSYSTEMVALUES_ELASTICSEARCH = "elasticsearch";
    TMP_DBSYSTEMVALUES_MEMCACHED = "memcached";
    TMP_DBSYSTEMVALUES_COCKROACHDB = "cockroachdb";
    DBSYSTEMVALUES_OTHER_SQL = TMP_DBSYSTEMVALUES_OTHER_SQL;
    DBSYSTEMVALUES_MSSQL = TMP_DBSYSTEMVALUES_MSSQL;
    DBSYSTEMVALUES_MYSQL = TMP_DBSYSTEMVALUES_MYSQL;
    DBSYSTEMVALUES_ORACLE = TMP_DBSYSTEMVALUES_ORACLE;
    DBSYSTEMVALUES_DB2 = TMP_DBSYSTEMVALUES_DB2;
    DBSYSTEMVALUES_POSTGRESQL = TMP_DBSYSTEMVALUES_POSTGRESQL;
    DBSYSTEMVALUES_REDSHIFT = TMP_DBSYSTEMVALUES_REDSHIFT;
    DBSYSTEMVALUES_HIVE = TMP_DBSYSTEMVALUES_HIVE;
    DBSYSTEMVALUES_CLOUDSCAPE = TMP_DBSYSTEMVALUES_CLOUDSCAPE;
    DBSYSTEMVALUES_HSQLDB = TMP_DBSYSTEMVALUES_HSQLDB;
    DBSYSTEMVALUES_PROGRESS = TMP_DBSYSTEMVALUES_PROGRESS;
    DBSYSTEMVALUES_MAXDB = TMP_DBSYSTEMVALUES_MAXDB;
    DBSYSTEMVALUES_HANADB = TMP_DBSYSTEMVALUES_HANADB;
    DBSYSTEMVALUES_INGRES = TMP_DBSYSTEMVALUES_INGRES;
    DBSYSTEMVALUES_FIRSTSQL = TMP_DBSYSTEMVALUES_FIRSTSQL;
    DBSYSTEMVALUES_EDB = TMP_DBSYSTEMVALUES_EDB;
    DBSYSTEMVALUES_CACHE = TMP_DBSYSTEMVALUES_CACHE;
    DBSYSTEMVALUES_ADABAS = TMP_DBSYSTEMVALUES_ADABAS;
    DBSYSTEMVALUES_FIREBIRD = TMP_DBSYSTEMVALUES_FIREBIRD;
    DBSYSTEMVALUES_DERBY = TMP_DBSYSTEMVALUES_DERBY;
    DBSYSTEMVALUES_FILEMAKER = TMP_DBSYSTEMVALUES_FILEMAKER;
    DBSYSTEMVALUES_INFORMIX = TMP_DBSYSTEMVALUES_INFORMIX;
    DBSYSTEMVALUES_INSTANTDB = TMP_DBSYSTEMVALUES_INSTANTDB;
    DBSYSTEMVALUES_INTERBASE = TMP_DBSYSTEMVALUES_INTERBASE;
    DBSYSTEMVALUES_MARIADB = TMP_DBSYSTEMVALUES_MARIADB;
    DBSYSTEMVALUES_NETEZZA = TMP_DBSYSTEMVALUES_NETEZZA;
    DBSYSTEMVALUES_PERVASIVE = TMP_DBSYSTEMVALUES_PERVASIVE;
    DBSYSTEMVALUES_POINTBASE = TMP_DBSYSTEMVALUES_POINTBASE;
    DBSYSTEMVALUES_SQLITE = TMP_DBSYSTEMVALUES_SQLITE;
    DBSYSTEMVALUES_SYBASE = TMP_DBSYSTEMVALUES_SYBASE;
    DBSYSTEMVALUES_TERADATA = TMP_DBSYSTEMVALUES_TERADATA;
    DBSYSTEMVALUES_VERTICA = TMP_DBSYSTEMVALUES_VERTICA;
    DBSYSTEMVALUES_H2 = TMP_DBSYSTEMVALUES_H2;
    DBSYSTEMVALUES_COLDFUSION = TMP_DBSYSTEMVALUES_COLDFUSION;
    DBSYSTEMVALUES_CASSANDRA = TMP_DBSYSTEMVALUES_CASSANDRA;
    DBSYSTEMVALUES_HBASE = TMP_DBSYSTEMVALUES_HBASE;
    DBSYSTEMVALUES_MONGODB = TMP_DBSYSTEMVALUES_MONGODB;
    DBSYSTEMVALUES_REDIS = TMP_DBSYSTEMVALUES_REDIS;
    DBSYSTEMVALUES_COUCHBASE = TMP_DBSYSTEMVALUES_COUCHBASE;
    DBSYSTEMVALUES_COUCHDB = TMP_DBSYSTEMVALUES_COUCHDB;
    DBSYSTEMVALUES_COSMOSDB = TMP_DBSYSTEMVALUES_COSMOSDB;
    DBSYSTEMVALUES_DYNAMODB = TMP_DBSYSTEMVALUES_DYNAMODB;
    DBSYSTEMVALUES_NEO4J = TMP_DBSYSTEMVALUES_NEO4J;
    DBSYSTEMVALUES_GEODE = TMP_DBSYSTEMVALUES_GEODE;
    DBSYSTEMVALUES_ELASTICSEARCH = TMP_DBSYSTEMVALUES_ELASTICSEARCH;
    DBSYSTEMVALUES_MEMCACHED = TMP_DBSYSTEMVALUES_MEMCACHED;
    DBSYSTEMVALUES_COCKROACHDB = TMP_DBSYSTEMVALUES_COCKROACHDB;
    DbSystemValues = /* @__PURE__ */ createConstMap([
      TMP_DBSYSTEMVALUES_OTHER_SQL,
      TMP_DBSYSTEMVALUES_MSSQL,
      TMP_DBSYSTEMVALUES_MYSQL,
      TMP_DBSYSTEMVALUES_ORACLE,
      TMP_DBSYSTEMVALUES_DB2,
      TMP_DBSYSTEMVALUES_POSTGRESQL,
      TMP_DBSYSTEMVALUES_REDSHIFT,
      TMP_DBSYSTEMVALUES_HIVE,
      TMP_DBSYSTEMVALUES_CLOUDSCAPE,
      TMP_DBSYSTEMVALUES_HSQLDB,
      TMP_DBSYSTEMVALUES_PROGRESS,
      TMP_DBSYSTEMVALUES_MAXDB,
      TMP_DBSYSTEMVALUES_HANADB,
      TMP_DBSYSTEMVALUES_INGRES,
      TMP_DBSYSTEMVALUES_FIRSTSQL,
      TMP_DBSYSTEMVALUES_EDB,
      TMP_DBSYSTEMVALUES_CACHE,
      TMP_DBSYSTEMVALUES_ADABAS,
      TMP_DBSYSTEMVALUES_FIREBIRD,
      TMP_DBSYSTEMVALUES_DERBY,
      TMP_DBSYSTEMVALUES_FILEMAKER,
      TMP_DBSYSTEMVALUES_INFORMIX,
      TMP_DBSYSTEMVALUES_INSTANTDB,
      TMP_DBSYSTEMVALUES_INTERBASE,
      TMP_DBSYSTEMVALUES_MARIADB,
      TMP_DBSYSTEMVALUES_NETEZZA,
      TMP_DBSYSTEMVALUES_PERVASIVE,
      TMP_DBSYSTEMVALUES_POINTBASE,
      TMP_DBSYSTEMVALUES_SQLITE,
      TMP_DBSYSTEMVALUES_SYBASE,
      TMP_DBSYSTEMVALUES_TERADATA,
      TMP_DBSYSTEMVALUES_VERTICA,
      TMP_DBSYSTEMVALUES_H2,
      TMP_DBSYSTEMVALUES_COLDFUSION,
      TMP_DBSYSTEMVALUES_CASSANDRA,
      TMP_DBSYSTEMVALUES_HBASE,
      TMP_DBSYSTEMVALUES_MONGODB,
      TMP_DBSYSTEMVALUES_REDIS,
      TMP_DBSYSTEMVALUES_COUCHBASE,
      TMP_DBSYSTEMVALUES_COUCHDB,
      TMP_DBSYSTEMVALUES_COSMOSDB,
      TMP_DBSYSTEMVALUES_DYNAMODB,
      TMP_DBSYSTEMVALUES_NEO4J,
      TMP_DBSYSTEMVALUES_GEODE,
      TMP_DBSYSTEMVALUES_ELASTICSEARCH,
      TMP_DBSYSTEMVALUES_MEMCACHED,
      TMP_DBSYSTEMVALUES_COCKROACHDB
    ]);
    TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL = "all";
    TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = "each_quorum";
    TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = "quorum";
    TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = "local_quorum";
    TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE = "one";
    TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO = "two";
    TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE = "three";
    TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = "local_one";
    TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY = "any";
    TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = "serial";
    TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = "local_serial";
    DBCASSANDRACONSISTENCYLEVELVALUES_ALL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL;
    DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM;
    DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM;
    DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM;
    DBCASSANDRACONSISTENCYLEVELVALUES_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE;
    DBCASSANDRACONSISTENCYLEVELVALUES_TWO = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO;
    DBCASSANDRACONSISTENCYLEVELVALUES_THREE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE;
    DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE;
    DBCASSANDRACONSISTENCYLEVELVALUES_ANY = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY;
    DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL;
    DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL;
    DbCassandraConsistencyLevelValues = /* @__PURE__ */ createConstMap([
      TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL,
      TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,
      TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,
      TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,
      TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE,
      TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO,
      TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE,
      TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,
      TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY,
      TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,
      TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL
    ]);
    TMP_FAASTRIGGERVALUES_DATASOURCE = "datasource";
    TMP_FAASTRIGGERVALUES_HTTP = "http";
    TMP_FAASTRIGGERVALUES_PUBSUB = "pubsub";
    TMP_FAASTRIGGERVALUES_TIMER = "timer";
    TMP_FAASTRIGGERVALUES_OTHER = "other";
    FAASTRIGGERVALUES_DATASOURCE = TMP_FAASTRIGGERVALUES_DATASOURCE;
    FAASTRIGGERVALUES_HTTP = TMP_FAASTRIGGERVALUES_HTTP;
    FAASTRIGGERVALUES_PUBSUB = TMP_FAASTRIGGERVALUES_PUBSUB;
    FAASTRIGGERVALUES_TIMER = TMP_FAASTRIGGERVALUES_TIMER;
    FAASTRIGGERVALUES_OTHER = TMP_FAASTRIGGERVALUES_OTHER;
    FaasTriggerValues = /* @__PURE__ */ createConstMap([
      TMP_FAASTRIGGERVALUES_DATASOURCE,
      TMP_FAASTRIGGERVALUES_HTTP,
      TMP_FAASTRIGGERVALUES_PUBSUB,
      TMP_FAASTRIGGERVALUES_TIMER,
      TMP_FAASTRIGGERVALUES_OTHER
    ]);
    TMP_FAASDOCUMENTOPERATIONVALUES_INSERT = "insert";
    TMP_FAASDOCUMENTOPERATIONVALUES_EDIT = "edit";
    TMP_FAASDOCUMENTOPERATIONVALUES_DELETE = "delete";
    FAASDOCUMENTOPERATIONVALUES_INSERT = TMP_FAASDOCUMENTOPERATIONVALUES_INSERT;
    FAASDOCUMENTOPERATIONVALUES_EDIT = TMP_FAASDOCUMENTOPERATIONVALUES_EDIT;
    FAASDOCUMENTOPERATIONVALUES_DELETE = TMP_FAASDOCUMENTOPERATIONVALUES_DELETE;
    FaasDocumentOperationValues = /* @__PURE__ */ createConstMap([
      TMP_FAASDOCUMENTOPERATIONVALUES_INSERT,
      TMP_FAASDOCUMENTOPERATIONVALUES_EDIT,
      TMP_FAASDOCUMENTOPERATIONVALUES_DELETE
    ]);
    TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = "alibaba_cloud";
    TMP_FAASINVOKEDPROVIDERVALUES_AWS = "aws";
    TMP_FAASINVOKEDPROVIDERVALUES_AZURE = "azure";
    TMP_FAASINVOKEDPROVIDERVALUES_GCP = "gcp";
    FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD;
    FAASINVOKEDPROVIDERVALUES_AWS = TMP_FAASINVOKEDPROVIDERVALUES_AWS;
    FAASINVOKEDPROVIDERVALUES_AZURE = TMP_FAASINVOKEDPROVIDERVALUES_AZURE;
    FAASINVOKEDPROVIDERVALUES_GCP = TMP_FAASINVOKEDPROVIDERVALUES_GCP;
    FaasInvokedProviderValues = /* @__PURE__ */ createConstMap([
      TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,
      TMP_FAASINVOKEDPROVIDERVALUES_AWS,
      TMP_FAASINVOKEDPROVIDERVALUES_AZURE,
      TMP_FAASINVOKEDPROVIDERVALUES_GCP
    ]);
    TMP_NETTRANSPORTVALUES_IP_TCP = "ip_tcp";
    TMP_NETTRANSPORTVALUES_IP_UDP = "ip_udp";
    TMP_NETTRANSPORTVALUES_IP = "ip";
    TMP_NETTRANSPORTVALUES_UNIX = "unix";
    TMP_NETTRANSPORTVALUES_PIPE = "pipe";
    TMP_NETTRANSPORTVALUES_INPROC = "inproc";
    TMP_NETTRANSPORTVALUES_OTHER = "other";
    NETTRANSPORTVALUES_IP_TCP = TMP_NETTRANSPORTVALUES_IP_TCP;
    NETTRANSPORTVALUES_IP_UDP = TMP_NETTRANSPORTVALUES_IP_UDP;
    NETTRANSPORTVALUES_IP = TMP_NETTRANSPORTVALUES_IP;
    NETTRANSPORTVALUES_UNIX = TMP_NETTRANSPORTVALUES_UNIX;
    NETTRANSPORTVALUES_PIPE = TMP_NETTRANSPORTVALUES_PIPE;
    NETTRANSPORTVALUES_INPROC = TMP_NETTRANSPORTVALUES_INPROC;
    NETTRANSPORTVALUES_OTHER = TMP_NETTRANSPORTVALUES_OTHER;
    NetTransportValues = /* @__PURE__ */ createConstMap([
      TMP_NETTRANSPORTVALUES_IP_TCP,
      TMP_NETTRANSPORTVALUES_IP_UDP,
      TMP_NETTRANSPORTVALUES_IP,
      TMP_NETTRANSPORTVALUES_UNIX,
      TMP_NETTRANSPORTVALUES_PIPE,
      TMP_NETTRANSPORTVALUES_INPROC,
      TMP_NETTRANSPORTVALUES_OTHER
    ]);
    TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI = "wifi";
    TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED = "wired";
    TMP_NETHOSTCONNECTIONTYPEVALUES_CELL = "cell";
    TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = "unavailable";
    TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = "unknown";
    NETHOSTCONNECTIONTYPEVALUES_WIFI = TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI;
    NETHOSTCONNECTIONTYPEVALUES_WIRED = TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED;
    NETHOSTCONNECTIONTYPEVALUES_CELL = TMP_NETHOSTCONNECTIONTYPEVALUES_CELL;
    NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE;
    NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN;
    NetHostConnectionTypeValues = /* @__PURE__ */ createConstMap([
      TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI,
      TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED,
      TMP_NETHOSTCONNECTIONTYPEVALUES_CELL,
      TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,
      TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN
    ]);
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = "gprs";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = "edge";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = "umts";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = "cdma";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = "evdo_0";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = "evdo_a";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = "cdma2000_1xrtt";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = "hsdpa";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = "hsupa";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = "hspa";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = "iden";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = "evdo_b";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE = "lte";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = "ehrpd";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = "hspap";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM = "gsm";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = "td_scdma";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = "iwlan";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR = "nr";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = "nrnsa";
    TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = "lte_ca";
    NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS;
    NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE;
    NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS;
    NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA;
    NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0;
    NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A;
    NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT;
    NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA;
    NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA;
    NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA;
    NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN;
    NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B;
    NETHOSTCONNECTIONSUBTYPEVALUES_LTE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE;
    NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD;
    NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP;
    NETHOSTCONNECTIONSUBTYPEVALUES_GSM = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM;
    NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA;
    NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN;
    NETHOSTCONNECTIONSUBTYPEVALUES_NR = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR;
    NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA;
    NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA;
    NetHostConnectionSubtypeValues = /* @__PURE__ */ createConstMap([
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,
      TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA
    ]);
    TMP_HTTPFLAVORVALUES_HTTP_1_0 = "1.0";
    TMP_HTTPFLAVORVALUES_HTTP_1_1 = "1.1";
    TMP_HTTPFLAVORVALUES_HTTP_2_0 = "2.0";
    TMP_HTTPFLAVORVALUES_SPDY = "SPDY";
    TMP_HTTPFLAVORVALUES_QUIC = "QUIC";
    HTTPFLAVORVALUES_HTTP_1_0 = TMP_HTTPFLAVORVALUES_HTTP_1_0;
    HTTPFLAVORVALUES_HTTP_1_1 = TMP_HTTPFLAVORVALUES_HTTP_1_1;
    HTTPFLAVORVALUES_HTTP_2_0 = TMP_HTTPFLAVORVALUES_HTTP_2_0;
    HTTPFLAVORVALUES_SPDY = TMP_HTTPFLAVORVALUES_SPDY;
    HTTPFLAVORVALUES_QUIC = TMP_HTTPFLAVORVALUES_QUIC;
    HttpFlavorValues = {
      HTTP_1_0: TMP_HTTPFLAVORVALUES_HTTP_1_0,
      HTTP_1_1: TMP_HTTPFLAVORVALUES_HTTP_1_1,
      HTTP_2_0: TMP_HTTPFLAVORVALUES_HTTP_2_0,
      SPDY: TMP_HTTPFLAVORVALUES_SPDY,
      QUIC: TMP_HTTPFLAVORVALUES_QUIC
    };
    TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE = "queue";
    TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC = "topic";
    MESSAGINGDESTINATIONKINDVALUES_QUEUE = TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE;
    MESSAGINGDESTINATIONKINDVALUES_TOPIC = TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC;
    MessagingDestinationKindValues = /* @__PURE__ */ createConstMap([
      TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE,
      TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC
    ]);
    TMP_MESSAGINGOPERATIONVALUES_RECEIVE = "receive";
    TMP_MESSAGINGOPERATIONVALUES_PROCESS = "process";
    MESSAGINGOPERATIONVALUES_RECEIVE = TMP_MESSAGINGOPERATIONVALUES_RECEIVE;
    MESSAGINGOPERATIONVALUES_PROCESS = TMP_MESSAGINGOPERATIONVALUES_PROCESS;
    MessagingOperationValues = /* @__PURE__ */ createConstMap([
      TMP_MESSAGINGOPERATIONVALUES_RECEIVE,
      TMP_MESSAGINGOPERATIONVALUES_PROCESS
    ]);
    TMP_RPCGRPCSTATUSCODEVALUES_OK = 0;
    TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED = 1;
    TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN = 2;
    TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = 3;
    TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = 4;
    TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND = 5;
    TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = 6;
    TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = 7;
    TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = 8;
    TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = 9;
    TMP_RPCGRPCSTATUSCODEVALUES_ABORTED = 10;
    TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = 11;
    TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = 12;
    TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL = 13;
    TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = 14;
    TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS = 15;
    TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = 16;
    RPCGRPCSTATUSCODEVALUES_OK = TMP_RPCGRPCSTATUSCODEVALUES_OK;
    RPCGRPCSTATUSCODEVALUES_CANCELLED = TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED;
    RPCGRPCSTATUSCODEVALUES_UNKNOWN = TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN;
    RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT;
    RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED;
    RPCGRPCSTATUSCODEVALUES_NOT_FOUND = TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND;
    RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS;
    RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED;
    RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED;
    RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION;
    RPCGRPCSTATUSCODEVALUES_ABORTED = TMP_RPCGRPCSTATUSCODEVALUES_ABORTED;
    RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE;
    RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED;
    RPCGRPCSTATUSCODEVALUES_INTERNAL = TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL;
    RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE;
    RPCGRPCSTATUSCODEVALUES_DATA_LOSS = TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS;
    RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED;
    RpcGrpcStatusCodeValues = {
      OK: TMP_RPCGRPCSTATUSCODEVALUES_OK,
      CANCELLED: TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED,
      UNKNOWN: TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN,
      INVALID_ARGUMENT: TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT,
      DEADLINE_EXCEEDED: TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED,
      NOT_FOUND: TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND,
      ALREADY_EXISTS: TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS,
      PERMISSION_DENIED: TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED,
      RESOURCE_EXHAUSTED: TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED,
      FAILED_PRECONDITION: TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION,
      ABORTED: TMP_RPCGRPCSTATUSCODEVALUES_ABORTED,
      OUT_OF_RANGE: TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE,
      UNIMPLEMENTED: TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED,
      INTERNAL: TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL,
      UNAVAILABLE: TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE,
      DATA_LOSS: TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS,
      UNAUTHENTICATED: TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED
    };
    TMP_MESSAGETYPEVALUES_SENT = "SENT";
    TMP_MESSAGETYPEVALUES_RECEIVED = "RECEIVED";
    MESSAGETYPEVALUES_SENT = TMP_MESSAGETYPEVALUES_SENT;
    MESSAGETYPEVALUES_RECEIVED = TMP_MESSAGETYPEVALUES_RECEIVED;
    MessageTypeValues = /* @__PURE__ */ createConstMap([
      TMP_MESSAGETYPEVALUES_SENT,
      TMP_MESSAGETYPEVALUES_RECEIVED
    ]);
  }
});

// node_modules/@opentelemetry/semantic-conventions/build/esm/trace/index.js
var init_trace = __esm({
  "node_modules/@opentelemetry/semantic-conventions/build/esm/trace/index.js"() {
    init_esbuild_shims();
    init_SemanticAttributes();
  }
});

// node_modules/@opentelemetry/semantic-conventions/build/esm/resource/SemanticResourceAttributes.js
var TMP_CLOUD_PROVIDER, TMP_CLOUD_ACCOUNT_ID, TMP_CLOUD_REGION, TMP_CLOUD_AVAILABILITY_ZONE, TMP_CLOUD_PLATFORM, TMP_AWS_ECS_CONTAINER_ARN, TMP_AWS_ECS_CLUSTER_ARN, TMP_AWS_ECS_LAUNCHTYPE, TMP_AWS_ECS_TASK_ARN, TMP_AWS_ECS_TASK_FAMILY, TMP_AWS_ECS_TASK_REVISION, TMP_AWS_EKS_CLUSTER_ARN, TMP_AWS_LOG_GROUP_NAMES, TMP_AWS_LOG_GROUP_ARNS, TMP_AWS_LOG_STREAM_NAMES, TMP_AWS_LOG_STREAM_ARNS, TMP_CONTAINER_NAME, TMP_CONTAINER_ID, TMP_CONTAINER_RUNTIME, TMP_CONTAINER_IMAGE_NAME, TMP_CONTAINER_IMAGE_TAG, TMP_DEPLOYMENT_ENVIRONMENT, TMP_DEVICE_ID, TMP_DEVICE_MODEL_IDENTIFIER, TMP_DEVICE_MODEL_NAME, TMP_FAAS_NAME, TMP_FAAS_ID, TMP_FAAS_VERSION, TMP_FAAS_INSTANCE, TMP_FAAS_MAX_MEMORY, TMP_HOST_ID, TMP_HOST_NAME, TMP_HOST_TYPE, TMP_HOST_ARCH, TMP_HOST_IMAGE_NAME, TMP_HOST_IMAGE_ID, TMP_HOST_IMAGE_VERSION, TMP_K8S_CLUSTER_NAME, TMP_K8S_NODE_NAME, TMP_K8S_NODE_UID, TMP_K8S_NAMESPACE_NAME, TMP_K8S_POD_UID, TMP_K8S_POD_NAME, TMP_K8S_CONTAINER_NAME, TMP_K8S_REPLICASET_UID, TMP_K8S_REPLICASET_NAME, TMP_K8S_DEPLOYMENT_UID, TMP_K8S_DEPLOYMENT_NAME, TMP_K8S_STATEFULSET_UID, TMP_K8S_STATEFULSET_NAME, TMP_K8S_DAEMONSET_UID, TMP_K8S_DAEMONSET_NAME, TMP_K8S_JOB_UID, TMP_K8S_JOB_NAME, TMP_K8S_CRONJOB_UID, TMP_K8S_CRONJOB_NAME, TMP_OS_TYPE, TMP_OS_DESCRIPTION, TMP_OS_NAME, TMP_OS_VERSION, TMP_PROCESS_PID, TMP_PROCESS_EXECUTABLE_NAME, TMP_PROCESS_EXECUTABLE_PATH, TMP_PROCESS_COMMAND, TMP_PROCESS_COMMAND_LINE, TMP_PROCESS_COMMAND_ARGS, TMP_PROCESS_OWNER, TMP_PROCESS_RUNTIME_NAME, TMP_PROCESS_RUNTIME_VERSION, TMP_PROCESS_RUNTIME_DESCRIPTION, TMP_SERVICE_NAME, TMP_SERVICE_NAMESPACE, TMP_SERVICE_INSTANCE_ID, TMP_SERVICE_VERSION, TMP_TELEMETRY_SDK_NAME, TMP_TELEMETRY_SDK_LANGUAGE, TMP_TELEMETRY_SDK_VERSION, TMP_TELEMETRY_AUTO_VERSION, TMP_WEBENGINE_NAME, TMP_WEBENGINE_VERSION, TMP_WEBENGINE_DESCRIPTION, SEMRESATTRS_CLOUD_PROVIDER, SEMRESATTRS_CLOUD_ACCOUNT_ID, SEMRESATTRS_CLOUD_REGION, SEMRESATTRS_CLOUD_AVAILABILITY_ZONE, SEMRESATTRS_CLOUD_PLATFORM, SEMRESATTRS_AWS_ECS_CONTAINER_ARN, SEMRESATTRS_AWS_ECS_CLUSTER_ARN, SEMRESATTRS_AWS_ECS_LAUNCHTYPE, SEMRESATTRS_AWS_ECS_TASK_ARN, SEMRESATTRS_AWS_ECS_TASK_FAMILY, SEMRESATTRS_AWS_ECS_TASK_REVISION, SEMRESATTRS_AWS_EKS_CLUSTER_ARN, SEMRESATTRS_AWS_LOG_GROUP_NAMES, SEMRESATTRS_AWS_LOG_GROUP_ARNS, SEMRESATTRS_AWS_LOG_STREAM_NAMES, SEMRESATTRS_AWS_LOG_STREAM_ARNS, SEMRESATTRS_CONTAINER_NAME, SEMRESATTRS_CONTAINER_ID, SEMRESATTRS_CONTAINER_RUNTIME, SEMRESATTRS_CONTAINER_IMAGE_NAME, SEMRESATTRS_CONTAINER_IMAGE_TAG, SEMRESATTRS_DEPLOYMENT_ENVIRONMENT, SEMRESATTRS_DEVICE_ID, SEMRESATTRS_DEVICE_MODEL_IDENTIFIER, SEMRESATTRS_DEVICE_MODEL_NAME, SEMRESATTRS_FAAS_NAME, SEMRESATTRS_FAAS_ID, SEMRESATTRS_FAAS_VERSION, SEMRESATTRS_FAAS_INSTANCE, SEMRESATTRS_FAAS_MAX_MEMORY, SEMRESATTRS_HOST_ID, SEMRESATTRS_HOST_NAME, SEMRESATTRS_HOST_TYPE, SEMRESATTRS_HOST_ARCH, SEMRESATTRS_HOST_IMAGE_NAME, SEMRESATTRS_HOST_IMAGE_ID, SEMRESATTRS_HOST_IMAGE_VERSION, SEMRESATTRS_K8S_CLUSTER_NAME, SEMRESATTRS_K8S_NODE_NAME, SEMRESATTRS_K8S_NODE_UID, SEMRESATTRS_K8S_NAMESPACE_NAME, SEMRESATTRS_K8S_POD_UID, SEMRESATTRS_K8S_POD_NAME, SEMRESATTRS_K8S_CONTAINER_NAME, SEMRESATTRS_K8S_REPLICASET_UID, SEMRESATTRS_K8S_REPLICASET_NAME, SEMRESATTRS_K8S_DEPLOYMENT_UID, SEMRESATTRS_K8S_DEPLOYMENT_NAME, SEMRESATTRS_K8S_STATEFULSET_UID, SEMRESATTRS_K8S_STATEFULSET_NAME, SEMRESATTRS_K8S_DAEMONSET_UID, SEMRESATTRS_K8S_DAEMONSET_NAME, SEMRESATTRS_K8S_JOB_UID, SEMRESATTRS_K8S_JOB_NAME, SEMRESATTRS_K8S_CRONJOB_UID, SEMRESATTRS_K8S_CRONJOB_NAME, SEMRESATTRS_OS_TYPE, SEMRESATTRS_OS_DESCRIPTION, SEMRESATTRS_OS_NAME, SEMRESATTRS_OS_VERSION, SEMRESATTRS_PROCESS_PID, SEMRESATTRS_PROCESS_EXECUTABLE_NAME, SEMRESATTRS_PROCESS_EXECUTABLE_PATH, SEMRESATTRS_PROCESS_COMMAND, SEMRESATTRS_PROCESS_COMMAND_LINE, SEMRESATTRS_PROCESS_COMMAND_ARGS, SEMRESATTRS_PROCESS_OWNER, SEMRESATTRS_PROCESS_RUNTIME_NAME, SEMRESATTRS_PROCESS_RUNTIME_VERSION, SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION, SEMRESATTRS_SERVICE_NAME, SEMRESATTRS_SERVICE_NAMESPACE, SEMRESATTRS_SERVICE_INSTANCE_ID, SEMRESATTRS_SERVICE_VERSION, SEMRESATTRS_TELEMETRY_SDK_NAME, SEMRESATTRS_TELEMETRY_SDK_LANGUAGE, SEMRESATTRS_TELEMETRY_SDK_VERSION, SEMRESATTRS_TELEMETRY_AUTO_VERSION, SEMRESATTRS_WEBENGINE_NAME, SEMRESATTRS_WEBENGINE_VERSION, SEMRESATTRS_WEBENGINE_DESCRIPTION, SemanticResourceAttributes, TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD, TMP_CLOUDPROVIDERVALUES_AWS, TMP_CLOUDPROVIDERVALUES_AZURE, TMP_CLOUDPROVIDERVALUES_GCP, CLOUDPROVIDERVALUES_ALIBABA_CLOUD, CLOUDPROVIDERVALUES_AWS, CLOUDPROVIDERVALUES_AZURE, CLOUDPROVIDERVALUES_GCP, CloudProviderValues, TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS, TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC, TMP_CLOUDPLATFORMVALUES_AWS_EC2, TMP_CLOUDPLATFORMVALUES_AWS_ECS, TMP_CLOUDPLATFORMVALUES_AWS_EKS, TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA, TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, TMP_CLOUDPLATFORMVALUES_AZURE_VM, TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES, TMP_CLOUDPLATFORMVALUES_AZURE_AKS, TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS, TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE, TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE, TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN, TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE, TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS, TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE, CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS, CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC, CLOUDPLATFORMVALUES_AWS_EC2, CLOUDPLATFORMVALUES_AWS_ECS, CLOUDPLATFORMVALUES_AWS_EKS, CLOUDPLATFORMVALUES_AWS_LAMBDA, CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, CLOUDPLATFORMVALUES_AZURE_VM, CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES, CLOUDPLATFORMVALUES_AZURE_AKS, CLOUDPLATFORMVALUES_AZURE_FUNCTIONS, CLOUDPLATFORMVALUES_AZURE_APP_SERVICE, CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE, CLOUDPLATFORMVALUES_GCP_CLOUD_RUN, CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE, CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS, CLOUDPLATFORMVALUES_GCP_APP_ENGINE, CloudPlatformValues, TMP_AWSECSLAUNCHTYPEVALUES_EC2, TMP_AWSECSLAUNCHTYPEVALUES_FARGATE, AWSECSLAUNCHTYPEVALUES_EC2, AWSECSLAUNCHTYPEVALUES_FARGATE, AwsEcsLaunchtypeValues, TMP_HOSTARCHVALUES_AMD64, TMP_HOSTARCHVALUES_ARM32, TMP_HOSTARCHVALUES_ARM64, TMP_HOSTARCHVALUES_IA64, TMP_HOSTARCHVALUES_PPC32, TMP_HOSTARCHVALUES_PPC64, TMP_HOSTARCHVALUES_X86, HOSTARCHVALUES_AMD64, HOSTARCHVALUES_ARM32, HOSTARCHVALUES_ARM64, HOSTARCHVALUES_IA64, HOSTARCHVALUES_PPC32, HOSTARCHVALUES_PPC64, HOSTARCHVALUES_X86, HostArchValues, TMP_OSTYPEVALUES_WINDOWS, TMP_OSTYPEVALUES_LINUX, TMP_OSTYPEVALUES_DARWIN, TMP_OSTYPEVALUES_FREEBSD, TMP_OSTYPEVALUES_NETBSD, TMP_OSTYPEVALUES_OPENBSD, TMP_OSTYPEVALUES_DRAGONFLYBSD, TMP_OSTYPEVALUES_HPUX, TMP_OSTYPEVALUES_AIX, TMP_OSTYPEVALUES_SOLARIS, TMP_OSTYPEVALUES_Z_OS, OSTYPEVALUES_WINDOWS, OSTYPEVALUES_LINUX, OSTYPEVALUES_DARWIN, OSTYPEVALUES_FREEBSD, OSTYPEVALUES_NETBSD, OSTYPEVALUES_OPENBSD, OSTYPEVALUES_DRAGONFLYBSD, OSTYPEVALUES_HPUX, OSTYPEVALUES_AIX, OSTYPEVALUES_SOLARIS, OSTYPEVALUES_Z_OS, OsTypeValues, TMP_TELEMETRYSDKLANGUAGEVALUES_CPP, TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET, TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG, TMP_TELEMETRYSDKLANGUAGEVALUES_GO, TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA, TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS, TMP_TELEMETRYSDKLANGUAGEVALUES_PHP, TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON, TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY, TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS, TELEMETRYSDKLANGUAGEVALUES_CPP, TELEMETRYSDKLANGUAGEVALUES_DOTNET, TELEMETRYSDKLANGUAGEVALUES_ERLANG, TELEMETRYSDKLANGUAGEVALUES_GO, TELEMETRYSDKLANGUAGEVALUES_JAVA, TELEMETRYSDKLANGUAGEVALUES_NODEJS, TELEMETRYSDKLANGUAGEVALUES_PHP, TELEMETRYSDKLANGUAGEVALUES_PYTHON, TELEMETRYSDKLANGUAGEVALUES_RUBY, TELEMETRYSDKLANGUAGEVALUES_WEBJS, TelemetrySdkLanguageValues;
var init_SemanticResourceAttributes = __esm({
  "node_modules/@opentelemetry/semantic-conventions/build/esm/resource/SemanticResourceAttributes.js"() {
    init_esbuild_shims();
    init_utils();
    TMP_CLOUD_PROVIDER = "cloud.provider";
    TMP_CLOUD_ACCOUNT_ID = "cloud.account.id";
    TMP_CLOUD_REGION = "cloud.region";
    TMP_CLOUD_AVAILABILITY_ZONE = "cloud.availability_zone";
    TMP_CLOUD_PLATFORM = "cloud.platform";
    TMP_AWS_ECS_CONTAINER_ARN = "aws.ecs.container.arn";
    TMP_AWS_ECS_CLUSTER_ARN = "aws.ecs.cluster.arn";
    TMP_AWS_ECS_LAUNCHTYPE = "aws.ecs.launchtype";
    TMP_AWS_ECS_TASK_ARN = "aws.ecs.task.arn";
    TMP_AWS_ECS_TASK_FAMILY = "aws.ecs.task.family";
    TMP_AWS_ECS_TASK_REVISION = "aws.ecs.task.revision";
    TMP_AWS_EKS_CLUSTER_ARN = "aws.eks.cluster.arn";
    TMP_AWS_LOG_GROUP_NAMES = "aws.log.group.names";
    TMP_AWS_LOG_GROUP_ARNS = "aws.log.group.arns";
    TMP_AWS_LOG_STREAM_NAMES = "aws.log.stream.names";
    TMP_AWS_LOG_STREAM_ARNS = "aws.log.stream.arns";
    TMP_CONTAINER_NAME = "container.name";
    TMP_CONTAINER_ID = "container.id";
    TMP_CONTAINER_RUNTIME = "container.runtime";
    TMP_CONTAINER_IMAGE_NAME = "container.image.name";
    TMP_CONTAINER_IMAGE_TAG = "container.image.tag";
    TMP_DEPLOYMENT_ENVIRONMENT = "deployment.environment";
    TMP_DEVICE_ID = "device.id";
    TMP_DEVICE_MODEL_IDENTIFIER = "device.model.identifier";
    TMP_DEVICE_MODEL_NAME = "device.model.name";
    TMP_FAAS_NAME = "faas.name";
    TMP_FAAS_ID = "faas.id";
    TMP_FAAS_VERSION = "faas.version";
    TMP_FAAS_INSTANCE = "faas.instance";
    TMP_FAAS_MAX_MEMORY = "faas.max_memory";
    TMP_HOST_ID = "host.id";
    TMP_HOST_NAME = "host.name";
    TMP_HOST_TYPE = "host.type";
    TMP_HOST_ARCH = "host.arch";
    TMP_HOST_IMAGE_NAME = "host.image.name";
    TMP_HOST_IMAGE_ID = "host.image.id";
    TMP_HOST_IMAGE_VERSION = "host.image.version";
    TMP_K8S_CLUSTER_NAME = "k8s.cluster.name";
    TMP_K8S_NODE_NAME = "k8s.node.name";
    TMP_K8S_NODE_UID = "k8s.node.uid";
    TMP_K8S_NAMESPACE_NAME = "k8s.namespace.name";
    TMP_K8S_POD_UID = "k8s.pod.uid";
    TMP_K8S_POD_NAME = "k8s.pod.name";
    TMP_K8S_CONTAINER_NAME = "k8s.container.name";
    TMP_K8S_REPLICASET_UID = "k8s.replicaset.uid";
    TMP_K8S_REPLICASET_NAME = "k8s.replicaset.name";
    TMP_K8S_DEPLOYMENT_UID = "k8s.deployment.uid";
    TMP_K8S_DEPLOYMENT_NAME = "k8s.deployment.name";
    TMP_K8S_STATEFULSET_UID = "k8s.statefulset.uid";
    TMP_K8S_STATEFULSET_NAME = "k8s.statefulset.name";
    TMP_K8S_DAEMONSET_UID = "k8s.daemonset.uid";
    TMP_K8S_DAEMONSET_NAME = "k8s.daemonset.name";
    TMP_K8S_JOB_UID = "k8s.job.uid";
    TMP_K8S_JOB_NAME = "k8s.job.name";
    TMP_K8S_CRONJOB_UID = "k8s.cronjob.uid";
    TMP_K8S_CRONJOB_NAME = "k8s.cronjob.name";
    TMP_OS_TYPE = "os.type";
    TMP_OS_DESCRIPTION = "os.description";
    TMP_OS_NAME = "os.name";
    TMP_OS_VERSION = "os.version";
    TMP_PROCESS_PID = "process.pid";
    TMP_PROCESS_EXECUTABLE_NAME = "process.executable.name";
    TMP_PROCESS_EXECUTABLE_PATH = "process.executable.path";
    TMP_PROCESS_COMMAND = "process.command";
    TMP_PROCESS_COMMAND_LINE = "process.command_line";
    TMP_PROCESS_COMMAND_ARGS = "process.command_args";
    TMP_PROCESS_OWNER = "process.owner";
    TMP_PROCESS_RUNTIME_NAME = "process.runtime.name";
    TMP_PROCESS_RUNTIME_VERSION = "process.runtime.version";
    TMP_PROCESS_RUNTIME_DESCRIPTION = "process.runtime.description";
    TMP_SERVICE_NAME = "service.name";
    TMP_SERVICE_NAMESPACE = "service.namespace";
    TMP_SERVICE_INSTANCE_ID = "service.instance.id";
    TMP_SERVICE_VERSION = "service.version";
    TMP_TELEMETRY_SDK_NAME = "telemetry.sdk.name";
    TMP_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language";
    TMP_TELEMETRY_SDK_VERSION = "telemetry.sdk.version";
    TMP_TELEMETRY_AUTO_VERSION = "telemetry.auto.version";
    TMP_WEBENGINE_NAME = "webengine.name";
    TMP_WEBENGINE_VERSION = "webengine.version";
    TMP_WEBENGINE_DESCRIPTION = "webengine.description";
    SEMRESATTRS_CLOUD_PROVIDER = TMP_CLOUD_PROVIDER;
    SEMRESATTRS_CLOUD_ACCOUNT_ID = TMP_CLOUD_ACCOUNT_ID;
    SEMRESATTRS_CLOUD_REGION = TMP_CLOUD_REGION;
    SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = TMP_CLOUD_AVAILABILITY_ZONE;
    SEMRESATTRS_CLOUD_PLATFORM = TMP_CLOUD_PLATFORM;
    SEMRESATTRS_AWS_ECS_CONTAINER_ARN = TMP_AWS_ECS_CONTAINER_ARN;
    SEMRESATTRS_AWS_ECS_CLUSTER_ARN = TMP_AWS_ECS_CLUSTER_ARN;
    SEMRESATTRS_AWS_ECS_LAUNCHTYPE = TMP_AWS_ECS_LAUNCHTYPE;
    SEMRESATTRS_AWS_ECS_TASK_ARN = TMP_AWS_ECS_TASK_ARN;
    SEMRESATTRS_AWS_ECS_TASK_FAMILY = TMP_AWS_ECS_TASK_FAMILY;
    SEMRESATTRS_AWS_ECS_TASK_REVISION = TMP_AWS_ECS_TASK_REVISION;
    SEMRESATTRS_AWS_EKS_CLUSTER_ARN = TMP_AWS_EKS_CLUSTER_ARN;
    SEMRESATTRS_AWS_LOG_GROUP_NAMES = TMP_AWS_LOG_GROUP_NAMES;
    SEMRESATTRS_AWS_LOG_GROUP_ARNS = TMP_AWS_LOG_GROUP_ARNS;
    SEMRESATTRS_AWS_LOG_STREAM_NAMES = TMP_AWS_LOG_STREAM_NAMES;
    SEMRESATTRS_AWS_LOG_STREAM_ARNS = TMP_AWS_LOG_STREAM_ARNS;
    SEMRESATTRS_CONTAINER_NAME = TMP_CONTAINER_NAME;
    SEMRESATTRS_CONTAINER_ID = TMP_CONTAINER_ID;
    SEMRESATTRS_CONTAINER_RUNTIME = TMP_CONTAINER_RUNTIME;
    SEMRESATTRS_CONTAINER_IMAGE_NAME = TMP_CONTAINER_IMAGE_NAME;
    SEMRESATTRS_CONTAINER_IMAGE_TAG = TMP_CONTAINER_IMAGE_TAG;
    SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = TMP_DEPLOYMENT_ENVIRONMENT;
    SEMRESATTRS_DEVICE_ID = TMP_DEVICE_ID;
    SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = TMP_DEVICE_MODEL_IDENTIFIER;
    SEMRESATTRS_DEVICE_MODEL_NAME = TMP_DEVICE_MODEL_NAME;
    SEMRESATTRS_FAAS_NAME = TMP_FAAS_NAME;
    SEMRESATTRS_FAAS_ID = TMP_FAAS_ID;
    SEMRESATTRS_FAAS_VERSION = TMP_FAAS_VERSION;
    SEMRESATTRS_FAAS_INSTANCE = TMP_FAAS_INSTANCE;
    SEMRESATTRS_FAAS_MAX_MEMORY = TMP_FAAS_MAX_MEMORY;
    SEMRESATTRS_HOST_ID = TMP_HOST_ID;
    SEMRESATTRS_HOST_NAME = TMP_HOST_NAME;
    SEMRESATTRS_HOST_TYPE = TMP_HOST_TYPE;
    SEMRESATTRS_HOST_ARCH = TMP_HOST_ARCH;
    SEMRESATTRS_HOST_IMAGE_NAME = TMP_HOST_IMAGE_NAME;
    SEMRESATTRS_HOST_IMAGE_ID = TMP_HOST_IMAGE_ID;
    SEMRESATTRS_HOST_IMAGE_VERSION = TMP_HOST_IMAGE_VERSION;
    SEMRESATTRS_K8S_CLUSTER_NAME = TMP_K8S_CLUSTER_NAME;
    SEMRESATTRS_K8S_NODE_NAME = TMP_K8S_NODE_NAME;
    SEMRESATTRS_K8S_NODE_UID = TMP_K8S_NODE_UID;
    SEMRESATTRS_K8S_NAMESPACE_NAME = TMP_K8S_NAMESPACE_NAME;
    SEMRESATTRS_K8S_POD_UID = TMP_K8S_POD_UID;
    SEMRESATTRS_K8S_POD_NAME = TMP_K8S_POD_NAME;
    SEMRESATTRS_K8S_CONTAINER_NAME = TMP_K8S_CONTAINER_NAME;
    SEMRESATTRS_K8S_REPLICASET_UID = TMP_K8S_REPLICASET_UID;
    SEMRESATTRS_K8S_REPLICASET_NAME = TMP_K8S_REPLICASET_NAME;
    SEMRESATTRS_K8S_DEPLOYMENT_UID = TMP_K8S_DEPLOYMENT_UID;
    SEMRESATTRS_K8S_DEPLOYMENT_NAME = TMP_K8S_DEPLOYMENT_NAME;
    SEMRESATTRS_K8S_STATEFULSET_UID = TMP_K8S_STATEFULSET_UID;
    SEMRESATTRS_K8S_STATEFULSET_NAME = TMP_K8S_STATEFULSET_NAME;
    SEMRESATTRS_K8S_DAEMONSET_UID = TMP_K8S_DAEMONSET_UID;
    SEMRESATTRS_K8S_DAEMONSET_NAME = TMP_K8S_DAEMONSET_NAME;
    SEMRESATTRS_K8S_JOB_UID = TMP_K8S_JOB_UID;
    SEMRESATTRS_K8S_JOB_NAME = TMP_K8S_JOB_NAME;
    SEMRESATTRS_K8S_CRONJOB_UID = TMP_K8S_CRONJOB_UID;
    SEMRESATTRS_K8S_CRONJOB_NAME = TMP_K8S_CRONJOB_NAME;
    SEMRESATTRS_OS_TYPE = TMP_OS_TYPE;
    SEMRESATTRS_OS_DESCRIPTION = TMP_OS_DESCRIPTION;
    SEMRESATTRS_OS_NAME = TMP_OS_NAME;
    SEMRESATTRS_OS_VERSION = TMP_OS_VERSION;
    SEMRESATTRS_PROCESS_PID = TMP_PROCESS_PID;
    SEMRESATTRS_PROCESS_EXECUTABLE_NAME = TMP_PROCESS_EXECUTABLE_NAME;
    SEMRESATTRS_PROCESS_EXECUTABLE_PATH = TMP_PROCESS_EXECUTABLE_PATH;
    SEMRESATTRS_PROCESS_COMMAND = TMP_PROCESS_COMMAND;
    SEMRESATTRS_PROCESS_COMMAND_LINE = TMP_PROCESS_COMMAND_LINE;
    SEMRESATTRS_PROCESS_COMMAND_ARGS = TMP_PROCESS_COMMAND_ARGS;
    SEMRESATTRS_PROCESS_OWNER = TMP_PROCESS_OWNER;
    SEMRESATTRS_PROCESS_RUNTIME_NAME = TMP_PROCESS_RUNTIME_NAME;
    SEMRESATTRS_PROCESS_RUNTIME_VERSION = TMP_PROCESS_RUNTIME_VERSION;
    SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = TMP_PROCESS_RUNTIME_DESCRIPTION;
    SEMRESATTRS_SERVICE_NAME = TMP_SERVICE_NAME;
    SEMRESATTRS_SERVICE_NAMESPACE = TMP_SERVICE_NAMESPACE;
    SEMRESATTRS_SERVICE_INSTANCE_ID = TMP_SERVICE_INSTANCE_ID;
    SEMRESATTRS_SERVICE_VERSION = TMP_SERVICE_VERSION;
    SEMRESATTRS_TELEMETRY_SDK_NAME = TMP_TELEMETRY_SDK_NAME;
    SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = TMP_TELEMETRY_SDK_LANGUAGE;
    SEMRESATTRS_TELEMETRY_SDK_VERSION = TMP_TELEMETRY_SDK_VERSION;
    SEMRESATTRS_TELEMETRY_AUTO_VERSION = TMP_TELEMETRY_AUTO_VERSION;
    SEMRESATTRS_WEBENGINE_NAME = TMP_WEBENGINE_NAME;
    SEMRESATTRS_WEBENGINE_VERSION = TMP_WEBENGINE_VERSION;
    SEMRESATTRS_WEBENGINE_DESCRIPTION = TMP_WEBENGINE_DESCRIPTION;
    SemanticResourceAttributes = /* @__PURE__ */ createConstMap([
      TMP_CLOUD_PROVIDER,
      TMP_CLOUD_ACCOUNT_ID,
      TMP_CLOUD_REGION,
      TMP_CLOUD_AVAILABILITY_ZONE,
      TMP_CLOUD_PLATFORM,
      TMP_AWS_ECS_CONTAINER_ARN,
      TMP_AWS_ECS_CLUSTER_ARN,
      TMP_AWS_ECS_LAUNCHTYPE,
      TMP_AWS_ECS_TASK_ARN,
      TMP_AWS_ECS_TASK_FAMILY,
      TMP_AWS_ECS_TASK_REVISION,
      TMP_AWS_EKS_CLUSTER_ARN,
      TMP_AWS_LOG_GROUP_NAMES,
      TMP_AWS_LOG_GROUP_ARNS,
      TMP_AWS_LOG_STREAM_NAMES,
      TMP_AWS_LOG_STREAM_ARNS,
      TMP_CONTAINER_NAME,
      TMP_CONTAINER_ID,
      TMP_CONTAINER_RUNTIME,
      TMP_CONTAINER_IMAGE_NAME,
      TMP_CONTAINER_IMAGE_TAG,
      TMP_DEPLOYMENT_ENVIRONMENT,
      TMP_DEVICE_ID,
      TMP_DEVICE_MODEL_IDENTIFIER,
      TMP_DEVICE_MODEL_NAME,
      TMP_FAAS_NAME,
      TMP_FAAS_ID,
      TMP_FAAS_VERSION,
      TMP_FAAS_INSTANCE,
      TMP_FAAS_MAX_MEMORY,
      TMP_HOST_ID,
      TMP_HOST_NAME,
      TMP_HOST_TYPE,
      TMP_HOST_ARCH,
      TMP_HOST_IMAGE_NAME,
      TMP_HOST_IMAGE_ID,
      TMP_HOST_IMAGE_VERSION,
      TMP_K8S_CLUSTER_NAME,
      TMP_K8S_NODE_NAME,
      TMP_K8S_NODE_UID,
      TMP_K8S_NAMESPACE_NAME,
      TMP_K8S_POD_UID,
      TMP_K8S_POD_NAME,
      TMP_K8S_CONTAINER_NAME,
      TMP_K8S_REPLICASET_UID,
      TMP_K8S_REPLICASET_NAME,
      TMP_K8S_DEPLOYMENT_UID,
      TMP_K8S_DEPLOYMENT_NAME,
      TMP_K8S_STATEFULSET_UID,
      TMP_K8S_STATEFULSET_NAME,
      TMP_K8S_DAEMONSET_UID,
      TMP_K8S_DAEMONSET_NAME,
      TMP_K8S_JOB_UID,
      TMP_K8S_JOB_NAME,
      TMP_K8S_CRONJOB_UID,
      TMP_K8S_CRONJOB_NAME,
      TMP_OS_TYPE,
      TMP_OS_DESCRIPTION,
      TMP_OS_NAME,
      TMP_OS_VERSION,
      TMP_PROCESS_PID,
      TMP_PROCESS_EXECUTABLE_NAME,
      TMP_PROCESS_EXECUTABLE_PATH,
      TMP_PROCESS_COMMAND,
      TMP_PROCESS_COMMAND_LINE,
      TMP_PROCESS_COMMAND_ARGS,
      TMP_PROCESS_OWNER,
      TMP_PROCESS_RUNTIME_NAME,
      TMP_PROCESS_RUNTIME_VERSION,
      TMP_PROCESS_RUNTIME_DESCRIPTION,
      TMP_SERVICE_NAME,
      TMP_SERVICE_NAMESPACE,
      TMP_SERVICE_INSTANCE_ID,
      TMP_SERVICE_VERSION,
      TMP_TELEMETRY_SDK_NAME,
      TMP_TELEMETRY_SDK_LANGUAGE,
      TMP_TELEMETRY_SDK_VERSION,
      TMP_TELEMETRY_AUTO_VERSION,
      TMP_WEBENGINE_NAME,
      TMP_WEBENGINE_VERSION,
      TMP_WEBENGINE_DESCRIPTION
    ]);
    TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD = "alibaba_cloud";
    TMP_CLOUDPROVIDERVALUES_AWS = "aws";
    TMP_CLOUDPROVIDERVALUES_AZURE = "azure";
    TMP_CLOUDPROVIDERVALUES_GCP = "gcp";
    CLOUDPROVIDERVALUES_ALIBABA_CLOUD = TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD;
    CLOUDPROVIDERVALUES_AWS = TMP_CLOUDPROVIDERVALUES_AWS;
    CLOUDPROVIDERVALUES_AZURE = TMP_CLOUDPROVIDERVALUES_AZURE;
    CLOUDPROVIDERVALUES_GCP = TMP_CLOUDPROVIDERVALUES_GCP;
    CloudProviderValues = /* @__PURE__ */ createConstMap([
      TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD,
      TMP_CLOUDPROVIDERVALUES_AWS,
      TMP_CLOUDPROVIDERVALUES_AZURE,
      TMP_CLOUDPROVIDERVALUES_GCP
    ]);
    TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = "alibaba_cloud_ecs";
    TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = "alibaba_cloud_fc";
    TMP_CLOUDPLATFORMVALUES_AWS_EC2 = "aws_ec2";
    TMP_CLOUDPLATFORMVALUES_AWS_ECS = "aws_ecs";
    TMP_CLOUDPLATFORMVALUES_AWS_EKS = "aws_eks";
    TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA = "aws_lambda";
    TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = "aws_elastic_beanstalk";
    TMP_CLOUDPLATFORMVALUES_AZURE_VM = "azure_vm";
    TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = "azure_container_instances";
    TMP_CLOUDPLATFORMVALUES_AZURE_AKS = "azure_aks";
    TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = "azure_functions";
    TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = "azure_app_service";
    TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = "gcp_compute_engine";
    TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = "gcp_cloud_run";
    TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = "gcp_kubernetes_engine";
    TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = "gcp_cloud_functions";
    TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE = "gcp_app_engine";
    CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS;
    CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC;
    CLOUDPLATFORMVALUES_AWS_EC2 = TMP_CLOUDPLATFORMVALUES_AWS_EC2;
    CLOUDPLATFORMVALUES_AWS_ECS = TMP_CLOUDPLATFORMVALUES_AWS_ECS;
    CLOUDPLATFORMVALUES_AWS_EKS = TMP_CLOUDPLATFORMVALUES_AWS_EKS;
    CLOUDPLATFORMVALUES_AWS_LAMBDA = TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA;
    CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK;
    CLOUDPLATFORMVALUES_AZURE_VM = TMP_CLOUDPLATFORMVALUES_AZURE_VM;
    CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES;
    CLOUDPLATFORMVALUES_AZURE_AKS = TMP_CLOUDPLATFORMVALUES_AZURE_AKS;
    CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS;
    CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE;
    CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE;
    CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN;
    CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE;
    CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS;
    CLOUDPLATFORMVALUES_GCP_APP_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE;
    CloudPlatformValues = /* @__PURE__ */ createConstMap([
      TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,
      TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,
      TMP_CLOUDPLATFORMVALUES_AWS_EC2,
      TMP_CLOUDPLATFORMVALUES_AWS_ECS,
      TMP_CLOUDPLATFORMVALUES_AWS_EKS,
      TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA,
      TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,
      TMP_CLOUDPLATFORMVALUES_AZURE_VM,
      TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,
      TMP_CLOUDPLATFORMVALUES_AZURE_AKS,
      TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,
      TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,
      TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,
      TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,
      TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,
      TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,
      TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE
    ]);
    TMP_AWSECSLAUNCHTYPEVALUES_EC2 = "ec2";
    TMP_AWSECSLAUNCHTYPEVALUES_FARGATE = "fargate";
    AWSECSLAUNCHTYPEVALUES_EC2 = TMP_AWSECSLAUNCHTYPEVALUES_EC2;
    AWSECSLAUNCHTYPEVALUES_FARGATE = TMP_AWSECSLAUNCHTYPEVALUES_FARGATE;
    AwsEcsLaunchtypeValues = /* @__PURE__ */ createConstMap([
      TMP_AWSECSLAUNCHTYPEVALUES_EC2,
      TMP_AWSECSLAUNCHTYPEVALUES_FARGATE
    ]);
    TMP_HOSTARCHVALUES_AMD64 = "amd64";
    TMP_HOSTARCHVALUES_ARM32 = "arm32";
    TMP_HOSTARCHVALUES_ARM64 = "arm64";
    TMP_HOSTARCHVALUES_IA64 = "ia64";
    TMP_HOSTARCHVALUES_PPC32 = "ppc32";
    TMP_HOSTARCHVALUES_PPC64 = "ppc64";
    TMP_HOSTARCHVALUES_X86 = "x86";
    HOSTARCHVALUES_AMD64 = TMP_HOSTARCHVALUES_AMD64;
    HOSTARCHVALUES_ARM32 = TMP_HOSTARCHVALUES_ARM32;
    HOSTARCHVALUES_ARM64 = TMP_HOSTARCHVALUES_ARM64;
    HOSTARCHVALUES_IA64 = TMP_HOSTARCHVALUES_IA64;
    HOSTARCHVALUES_PPC32 = TMP_HOSTARCHVALUES_PPC32;
    HOSTARCHVALUES_PPC64 = TMP_HOSTARCHVALUES_PPC64;
    HOSTARCHVALUES_X86 = TMP_HOSTARCHVALUES_X86;
    HostArchValues = /* @__PURE__ */ createConstMap([
      TMP_HOSTARCHVALUES_AMD64,
      TMP_HOSTARCHVALUES_ARM32,
      TMP_HOSTARCHVALUES_ARM64,
      TMP_HOSTARCHVALUES_IA64,
      TMP_HOSTARCHVALUES_PPC32,
      TMP_HOSTARCHVALUES_PPC64,
      TMP_HOSTARCHVALUES_X86
    ]);
    TMP_OSTYPEVALUES_WINDOWS = "windows";
    TMP_OSTYPEVALUES_LINUX = "linux";
    TMP_OSTYPEVALUES_DARWIN = "darwin";
    TMP_OSTYPEVALUES_FREEBSD = "freebsd";
    TMP_OSTYPEVALUES_NETBSD = "netbsd";
    TMP_OSTYPEVALUES_OPENBSD = "openbsd";
    TMP_OSTYPEVALUES_DRAGONFLYBSD = "dragonflybsd";
    TMP_OSTYPEVALUES_HPUX = "hpux";
    TMP_OSTYPEVALUES_AIX = "aix";
    TMP_OSTYPEVALUES_SOLARIS = "solaris";
    TMP_OSTYPEVALUES_Z_OS = "z_os";
    OSTYPEVALUES_WINDOWS = TMP_OSTYPEVALUES_WINDOWS;
    OSTYPEVALUES_LINUX = TMP_OSTYPEVALUES_LINUX;
    OSTYPEVALUES_DARWIN = TMP_OSTYPEVALUES_DARWIN;
    OSTYPEVALUES_FREEBSD = TMP_OSTYPEVALUES_FREEBSD;
    OSTYPEVALUES_NETBSD = TMP_OSTYPEVALUES_NETBSD;
    OSTYPEVALUES_OPENBSD = TMP_OSTYPEVALUES_OPENBSD;
    OSTYPEVALUES_DRAGONFLYBSD = TMP_OSTYPEVALUES_DRAGONFLYBSD;
    OSTYPEVALUES_HPUX = TMP_OSTYPEVALUES_HPUX;
    OSTYPEVALUES_AIX = TMP_OSTYPEVALUES_AIX;
    OSTYPEVALUES_SOLARIS = TMP_OSTYPEVALUES_SOLARIS;
    OSTYPEVALUES_Z_OS = TMP_OSTYPEVALUES_Z_OS;
    OsTypeValues = /* @__PURE__ */ createConstMap([
      TMP_OSTYPEVALUES_WINDOWS,
      TMP_OSTYPEVALUES_LINUX,
      TMP_OSTYPEVALUES_DARWIN,
      TMP_OSTYPEVALUES_FREEBSD,
      TMP_OSTYPEVALUES_NETBSD,
      TMP_OSTYPEVALUES_OPENBSD,
      TMP_OSTYPEVALUES_DRAGONFLYBSD,
      TMP_OSTYPEVALUES_HPUX,
      TMP_OSTYPEVALUES_AIX,
      TMP_OSTYPEVALUES_SOLARIS,
      TMP_OSTYPEVALUES_Z_OS
    ]);
    TMP_TELEMETRYSDKLANGUAGEVALUES_CPP = "cpp";
    TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET = "dotnet";
    TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG = "erlang";
    TMP_TELEMETRYSDKLANGUAGEVALUES_GO = "go";
    TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA = "java";
    TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS = "nodejs";
    TMP_TELEMETRYSDKLANGUAGEVALUES_PHP = "php";
    TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON = "python";
    TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY = "ruby";
    TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS = "webjs";
    TELEMETRYSDKLANGUAGEVALUES_CPP = TMP_TELEMETRYSDKLANGUAGEVALUES_CPP;
    TELEMETRYSDKLANGUAGEVALUES_DOTNET = TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET;
    TELEMETRYSDKLANGUAGEVALUES_ERLANG = TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG;
    TELEMETRYSDKLANGUAGEVALUES_GO = TMP_TELEMETRYSDKLANGUAGEVALUES_GO;
    TELEMETRYSDKLANGUAGEVALUES_JAVA = TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA;
    TELEMETRYSDKLANGUAGEVALUES_NODEJS = TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS;
    TELEMETRYSDKLANGUAGEVALUES_PHP = TMP_TELEMETRYSDKLANGUAGEVALUES_PHP;
    TELEMETRYSDKLANGUAGEVALUES_PYTHON = TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON;
    TELEMETRYSDKLANGUAGEVALUES_RUBY = TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY;
    TELEMETRYSDKLANGUAGEVALUES_WEBJS = TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS;
    TelemetrySdkLanguageValues = /* @__PURE__ */ createConstMap([
      TMP_TELEMETRYSDKLANGUAGEVALUES_CPP,
      TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET,
      TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG,
      TMP_TELEMETRYSDKLANGUAGEVALUES_GO,
      TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA,
      TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS,
      TMP_TELEMETRYSDKLANGUAGEVALUES_PHP,
      TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON,
      TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY,
      TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS
    ]);
  }
});

// node_modules/@opentelemetry/semantic-conventions/build/esm/resource/index.js
var init_resource = __esm({
  "node_modules/@opentelemetry/semantic-conventions/build/esm/resource/index.js"() {
    init_esbuild_shims();
    init_SemanticResourceAttributes();
  }
});

// node_modules/@opentelemetry/semantic-conventions/build/esm/stable_attributes.js
var ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT, ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED, ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED, ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED, ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED, ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE, ATTR_ASPNETCORE_RATE_LIMITING_POLICY, ATTR_ASPNETCORE_RATE_LIMITING_RESULT, ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED, ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER, ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER, ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED, ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED, ATTR_ASPNETCORE_ROUTING_IS_FALLBACK, ATTR_ASPNETCORE_ROUTING_MATCH_STATUS, ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE, ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS, ATTR_CLIENT_ADDRESS, ATTR_CLIENT_PORT, ATTR_CODE_COLUMN_NUMBER, ATTR_CODE_FILE_PATH, ATTR_CODE_FUNCTION_NAME, ATTR_CODE_LINE_NUMBER, ATTR_CODE_STACKTRACE, ATTR_DB_COLLECTION_NAME, ATTR_DB_NAMESPACE, ATTR_DB_OPERATION_BATCH_SIZE, ATTR_DB_OPERATION_NAME, ATTR_DB_QUERY_SUMMARY, ATTR_DB_QUERY_TEXT, ATTR_DB_RESPONSE_STATUS_CODE, ATTR_DB_STORED_PROCEDURE_NAME, ATTR_DB_SYSTEM_NAME, DB_SYSTEM_NAME_VALUE_MARIADB, DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER, DB_SYSTEM_NAME_VALUE_MYSQL, DB_SYSTEM_NAME_VALUE_POSTGRESQL, ATTR_DOTNET_GC_HEAP_GENERATION, DOTNET_GC_HEAP_GENERATION_VALUE_GEN0, DOTNET_GC_HEAP_GENERATION_VALUE_GEN1, DOTNET_GC_HEAP_GENERATION_VALUE_GEN2, DOTNET_GC_HEAP_GENERATION_VALUE_LOH, DOTNET_GC_HEAP_GENERATION_VALUE_POH, ATTR_ERROR_TYPE, ERROR_TYPE_VALUE_OTHER, ATTR_EXCEPTION_ESCAPED, ATTR_EXCEPTION_MESSAGE, ATTR_EXCEPTION_STACKTRACE, ATTR_EXCEPTION_TYPE, ATTR_HTTP_REQUEST_HEADER, ATTR_HTTP_REQUEST_METHOD, HTTP_REQUEST_METHOD_VALUE_OTHER, HTTP_REQUEST_METHOD_VALUE_CONNECT, HTTP_REQUEST_METHOD_VALUE_DELETE, HTTP_REQUEST_METHOD_VALUE_GET, HTTP_REQUEST_METHOD_VALUE_HEAD, HTTP_REQUEST_METHOD_VALUE_OPTIONS, HTTP_REQUEST_METHOD_VALUE_PATCH, HTTP_REQUEST_METHOD_VALUE_POST, HTTP_REQUEST_METHOD_VALUE_PUT, HTTP_REQUEST_METHOD_VALUE_TRACE, ATTR_HTTP_REQUEST_METHOD_ORIGINAL, ATTR_HTTP_REQUEST_RESEND_COUNT, ATTR_HTTP_RESPONSE_HEADER, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_HTTP_ROUTE, ATTR_JVM_GC_ACTION, ATTR_JVM_GC_NAME, ATTR_JVM_MEMORY_POOL_NAME, ATTR_JVM_MEMORY_TYPE, JVM_MEMORY_TYPE_VALUE_HEAP, JVM_MEMORY_TYPE_VALUE_NON_HEAP, ATTR_JVM_THREAD_DAEMON, ATTR_JVM_THREAD_STATE, JVM_THREAD_STATE_VALUE_BLOCKED, JVM_THREAD_STATE_VALUE_NEW, JVM_THREAD_STATE_VALUE_RUNNABLE, JVM_THREAD_STATE_VALUE_TERMINATED, JVM_THREAD_STATE_VALUE_TIMED_WAITING, JVM_THREAD_STATE_VALUE_WAITING, ATTR_NETWORK_LOCAL_ADDRESS, ATTR_NETWORK_LOCAL_PORT, ATTR_NETWORK_PEER_ADDRESS, ATTR_NETWORK_PEER_PORT, ATTR_NETWORK_PROTOCOL_NAME, ATTR_NETWORK_PROTOCOL_VERSION, ATTR_NETWORK_TRANSPORT, NETWORK_TRANSPORT_VALUE_PIPE, NETWORK_TRANSPORT_VALUE_QUIC, NETWORK_TRANSPORT_VALUE_TCP, NETWORK_TRANSPORT_VALUE_UDP, NETWORK_TRANSPORT_VALUE_UNIX, ATTR_NETWORK_TYPE, NETWORK_TYPE_VALUE_IPV4, NETWORK_TYPE_VALUE_IPV6, ATTR_OTEL_SCOPE_NAME, ATTR_OTEL_SCOPE_VERSION, ATTR_OTEL_STATUS_CODE, OTEL_STATUS_CODE_VALUE_ERROR, OTEL_STATUS_CODE_VALUE_OK, ATTR_OTEL_STATUS_DESCRIPTION, ATTR_SERVER_ADDRESS, ATTR_SERVER_PORT, ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION, ATTR_SIGNALR_CONNECTION_STATUS, SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN, SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE, SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT, ATTR_SIGNALR_TRANSPORT, SIGNALR_TRANSPORT_VALUE_LONG_POLLING, SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS, SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS, ATTR_TELEMETRY_SDK_LANGUAGE, TELEMETRY_SDK_LANGUAGE_VALUE_CPP, TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET, TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG, TELEMETRY_SDK_LANGUAGE_VALUE_GO, TELEMETRY_SDK_LANGUAGE_VALUE_JAVA, TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS, TELEMETRY_SDK_LANGUAGE_VALUE_PHP, TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON, TELEMETRY_SDK_LANGUAGE_VALUE_RUBY, TELEMETRY_SDK_LANGUAGE_VALUE_RUST, TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT, TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS, ATTR_TELEMETRY_SDK_NAME, ATTR_TELEMETRY_SDK_VERSION, ATTR_URL_FRAGMENT, ATTR_URL_FULL, ATTR_URL_PATH, ATTR_URL_QUERY, ATTR_URL_SCHEME, ATTR_USER_AGENT_ORIGINAL;
var init_stable_attributes = __esm({
  "node_modules/@opentelemetry/semantic-conventions/build/esm/stable_attributes.js"() {
    init_esbuild_shims();
    ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = "aspnetcore.diagnostics.exception.result";
    ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = "aborted";
    ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = "handled";
    ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = "skipped";
    ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = "unhandled";
    ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = "aspnetcore.diagnostics.handler.type";
    ATTR_ASPNETCORE_RATE_LIMITING_POLICY = "aspnetcore.rate_limiting.policy";
    ATTR_ASPNETCORE_RATE_LIMITING_RESULT = "aspnetcore.rate_limiting.result";
    ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = "acquired";
    ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = "endpoint_limiter";
    ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = "global_limiter";
    ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = "request_canceled";
    ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = "aspnetcore.request.is_unhandled";
    ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = "aspnetcore.routing.is_fallback";
    ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = "aspnetcore.routing.match_status";
    ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = "failure";
    ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = "success";
    ATTR_CLIENT_ADDRESS = "client.address";
    ATTR_CLIENT_PORT = "client.port";
    ATTR_CODE_COLUMN_NUMBER = "code.column.number";
    ATTR_CODE_FILE_PATH = "code.file.path";
    ATTR_CODE_FUNCTION_NAME = "code.function.name";
    ATTR_CODE_LINE_NUMBER = "code.line.number";
    ATTR_CODE_STACKTRACE = "code.stacktrace";
    ATTR_DB_COLLECTION_NAME = "db.collection.name";
    ATTR_DB_NAMESPACE = "db.namespace";
    ATTR_DB_OPERATION_BATCH_SIZE = "db.operation.batch.size";
    ATTR_DB_OPERATION_NAME = "db.operation.name";
    ATTR_DB_QUERY_SUMMARY = "db.query.summary";
    ATTR_DB_QUERY_TEXT = "db.query.text";
    ATTR_DB_RESPONSE_STATUS_CODE = "db.response.status_code";
    ATTR_DB_STORED_PROCEDURE_NAME = "db.stored_procedure.name";
    ATTR_DB_SYSTEM_NAME = "db.system.name";
    DB_SYSTEM_NAME_VALUE_MARIADB = "mariadb";
    DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = "microsoft.sql_server";
    DB_SYSTEM_NAME_VALUE_MYSQL = "mysql";
    DB_SYSTEM_NAME_VALUE_POSTGRESQL = "postgresql";
    ATTR_DOTNET_GC_HEAP_GENERATION = "dotnet.gc.heap.generation";
    DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = "gen0";
    DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = "gen1";
    DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = "gen2";
    DOTNET_GC_HEAP_GENERATION_VALUE_LOH = "loh";
    DOTNET_GC_HEAP_GENERATION_VALUE_POH = "poh";
    ATTR_ERROR_TYPE = "error.type";
    ERROR_TYPE_VALUE_OTHER = "_OTHER";
    ATTR_EXCEPTION_ESCAPED = "exception.escaped";
    ATTR_EXCEPTION_MESSAGE = "exception.message";
    ATTR_EXCEPTION_STACKTRACE = "exception.stacktrace";
    ATTR_EXCEPTION_TYPE = "exception.type";
    ATTR_HTTP_REQUEST_HEADER = /* @__PURE__ */ __name((key) => `http.request.header.${key}`, "ATTR_HTTP_REQUEST_HEADER");
    ATTR_HTTP_REQUEST_METHOD = "http.request.method";
    HTTP_REQUEST_METHOD_VALUE_OTHER = "_OTHER";
    HTTP_REQUEST_METHOD_VALUE_CONNECT = "CONNECT";
    HTTP_REQUEST_METHOD_VALUE_DELETE = "DELETE";
    HTTP_REQUEST_METHOD_VALUE_GET = "GET";
    HTTP_REQUEST_METHOD_VALUE_HEAD = "HEAD";
    HTTP_REQUEST_METHOD_VALUE_OPTIONS = "OPTIONS";
    HTTP_REQUEST_METHOD_VALUE_PATCH = "PATCH";
    HTTP_REQUEST_METHOD_VALUE_POST = "POST";
    HTTP_REQUEST_METHOD_VALUE_PUT = "PUT";
    HTTP_REQUEST_METHOD_VALUE_TRACE = "TRACE";
    ATTR_HTTP_REQUEST_METHOD_ORIGINAL = "http.request.method_original";
    ATTR_HTTP_REQUEST_RESEND_COUNT = "http.request.resend_count";
    ATTR_HTTP_RESPONSE_HEADER = /* @__PURE__ */ __name((key) => `http.response.header.${key}`, "ATTR_HTTP_RESPONSE_HEADER");
    ATTR_HTTP_RESPONSE_STATUS_CODE = "http.response.status_code";
    ATTR_HTTP_ROUTE = "http.route";
    ATTR_JVM_GC_ACTION = "jvm.gc.action";
    ATTR_JVM_GC_NAME = "jvm.gc.name";
    ATTR_JVM_MEMORY_POOL_NAME = "jvm.memory.pool.name";
    ATTR_JVM_MEMORY_TYPE = "jvm.memory.type";
    JVM_MEMORY_TYPE_VALUE_HEAP = "heap";
    JVM_MEMORY_TYPE_VALUE_NON_HEAP = "non_heap";
    ATTR_JVM_THREAD_DAEMON = "jvm.thread.daemon";
    ATTR_JVM_THREAD_STATE = "jvm.thread.state";
    JVM_THREAD_STATE_VALUE_BLOCKED = "blocked";
    JVM_THREAD_STATE_VALUE_NEW = "new";
    JVM_THREAD_STATE_VALUE_RUNNABLE = "runnable";
    JVM_THREAD_STATE_VALUE_TERMINATED = "terminated";
    JVM_THREAD_STATE_VALUE_TIMED_WAITING = "timed_waiting";
    JVM_THREAD_STATE_VALUE_WAITING = "waiting";
    ATTR_NETWORK_LOCAL_ADDRESS = "network.local.address";
    ATTR_NETWORK_LOCAL_PORT = "network.local.port";
    ATTR_NETWORK_PEER_ADDRESS = "network.peer.address";
    ATTR_NETWORK_PEER_PORT = "network.peer.port";
    ATTR_NETWORK_PROTOCOL_NAME = "network.protocol.name";
    ATTR_NETWORK_PROTOCOL_VERSION = "network.protocol.version";
    ATTR_NETWORK_TRANSPORT = "network.transport";
    NETWORK_TRANSPORT_VALUE_PIPE = "pipe";
    NETWORK_TRANSPORT_VALUE_QUIC = "quic";
    NETWORK_TRANSPORT_VALUE_TCP = "tcp";
    NETWORK_TRANSPORT_VALUE_UDP = "udp";
    NETWORK_TRANSPORT_VALUE_UNIX = "unix";
    ATTR_NETWORK_TYPE = "network.type";
    NETWORK_TYPE_VALUE_IPV4 = "ipv4";
    NETWORK_TYPE_VALUE_IPV6 = "ipv6";
    ATTR_OTEL_SCOPE_NAME = "otel.scope.name";
    ATTR_OTEL_SCOPE_VERSION = "otel.scope.version";
    ATTR_OTEL_STATUS_CODE = "otel.status_code";
    OTEL_STATUS_CODE_VALUE_ERROR = "ERROR";
    OTEL_STATUS_CODE_VALUE_OK = "OK";
    ATTR_OTEL_STATUS_DESCRIPTION = "otel.status_description";
    ATTR_SERVER_ADDRESS = "server.address";
    ATTR_SERVER_PORT = "server.port";
    ATTR_SERVICE_NAME = "service.name";
    ATTR_SERVICE_VERSION = "service.version";
    ATTR_SIGNALR_CONNECTION_STATUS = "signalr.connection.status";
    SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = "app_shutdown";
    SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = "normal_closure";
    SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = "timeout";
    ATTR_SIGNALR_TRANSPORT = "signalr.transport";
    SIGNALR_TRANSPORT_VALUE_LONG_POLLING = "long_polling";
    SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = "server_sent_events";
    SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = "web_sockets";
    ATTR_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language";
    TELEMETRY_SDK_LANGUAGE_VALUE_CPP = "cpp";
    TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = "dotnet";
    TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = "erlang";
    TELEMETRY_SDK_LANGUAGE_VALUE_GO = "go";
    TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = "java";
    TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = "nodejs";
    TELEMETRY_SDK_LANGUAGE_VALUE_PHP = "php";
    TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = "python";
    TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = "ruby";
    TELEMETRY_SDK_LANGUAGE_VALUE_RUST = "rust";
    TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = "swift";
    TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = "webjs";
    ATTR_TELEMETRY_SDK_NAME = "telemetry.sdk.name";
    ATTR_TELEMETRY_SDK_VERSION = "telemetry.sdk.version";
    ATTR_URL_FRAGMENT = "url.fragment";
    ATTR_URL_FULL = "url.full";
    ATTR_URL_PATH = "url.path";
    ATTR_URL_QUERY = "url.query";
    ATTR_URL_SCHEME = "url.scheme";
    ATTR_USER_AGENT_ORIGINAL = "user_agent.original";
  }
});

// node_modules/@opentelemetry/semantic-conventions/build/esm/stable_metrics.js
var METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS, METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES, METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS, METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE, METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION, METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS, METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS, METRIC_DB_CLIENT_OPERATION_DURATION, METRIC_DOTNET_ASSEMBLY_COUNT, METRIC_DOTNET_EXCEPTIONS, METRIC_DOTNET_GC_COLLECTIONS, METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED, METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE, METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE, METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE, METRIC_DOTNET_GC_PAUSE_TIME, METRIC_DOTNET_JIT_COMPILATION_TIME, METRIC_DOTNET_JIT_COMPILED_IL_SIZE, METRIC_DOTNET_JIT_COMPILED_METHODS, METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS, METRIC_DOTNET_PROCESS_CPU_COUNT, METRIC_DOTNET_PROCESS_CPU_TIME, METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET, METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH, METRIC_DOTNET_THREAD_POOL_THREAD_COUNT, METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT, METRIC_DOTNET_TIMER_COUNT, METRIC_HTTP_CLIENT_REQUEST_DURATION, METRIC_HTTP_SERVER_REQUEST_DURATION, METRIC_JVM_CLASS_COUNT, METRIC_JVM_CLASS_LOADED, METRIC_JVM_CLASS_UNLOADED, METRIC_JVM_CPU_COUNT, METRIC_JVM_CPU_RECENT_UTILIZATION, METRIC_JVM_CPU_TIME, METRIC_JVM_GC_DURATION, METRIC_JVM_MEMORY_COMMITTED, METRIC_JVM_MEMORY_LIMIT, METRIC_JVM_MEMORY_USED, METRIC_JVM_MEMORY_USED_AFTER_LAST_GC, METRIC_JVM_THREAD_COUNT, METRIC_KESTREL_ACTIVE_CONNECTIONS, METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES, METRIC_KESTREL_CONNECTION_DURATION, METRIC_KESTREL_QUEUED_CONNECTIONS, METRIC_KESTREL_QUEUED_REQUESTS, METRIC_KESTREL_REJECTED_CONNECTIONS, METRIC_KESTREL_TLS_HANDSHAKE_DURATION, METRIC_KESTREL_UPGRADED_CONNECTIONS, METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS, METRIC_SIGNALR_SERVER_CONNECTION_DURATION;
var init_stable_metrics = __esm({
  "node_modules/@opentelemetry/semantic-conventions/build/esm/stable_metrics.js"() {
    init_esbuild_shims();
    METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = "aspnetcore.diagnostics.exceptions";
    METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = "aspnetcore.rate_limiting.active_request_leases";
    METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = "aspnetcore.rate_limiting.queued_requests";
    METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = "aspnetcore.rate_limiting.request.time_in_queue";
    METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = "aspnetcore.rate_limiting.request_lease.duration";
    METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = "aspnetcore.rate_limiting.requests";
    METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = "aspnetcore.routing.match_attempts";
    METRIC_DB_CLIENT_OPERATION_DURATION = "db.client.operation.duration";
    METRIC_DOTNET_ASSEMBLY_COUNT = "dotnet.assembly.count";
    METRIC_DOTNET_EXCEPTIONS = "dotnet.exceptions";
    METRIC_DOTNET_GC_COLLECTIONS = "dotnet.gc.collections";
    METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = "dotnet.gc.heap.total_allocated";
    METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = "dotnet.gc.last_collection.heap.fragmentation.size";
    METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = "dotnet.gc.last_collection.heap.size";
    METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = "dotnet.gc.last_collection.memory.committed_size";
    METRIC_DOTNET_GC_PAUSE_TIME = "dotnet.gc.pause.time";
    METRIC_DOTNET_JIT_COMPILATION_TIME = "dotnet.jit.compilation.time";
    METRIC_DOTNET_JIT_COMPILED_IL_SIZE = "dotnet.jit.compiled_il.size";
    METRIC_DOTNET_JIT_COMPILED_METHODS = "dotnet.jit.compiled_methods";
    METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = "dotnet.monitor.lock_contentions";
    METRIC_DOTNET_PROCESS_CPU_COUNT = "dotnet.process.cpu.count";
    METRIC_DOTNET_PROCESS_CPU_TIME = "dotnet.process.cpu.time";
    METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = "dotnet.process.memory.working_set";
    METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = "dotnet.thread_pool.queue.length";
    METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = "dotnet.thread_pool.thread.count";
    METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = "dotnet.thread_pool.work_item.count";
    METRIC_DOTNET_TIMER_COUNT = "dotnet.timer.count";
    METRIC_HTTP_CLIENT_REQUEST_DURATION = "http.client.request.duration";
    METRIC_HTTP_SERVER_REQUEST_DURATION = "http.server.request.duration";
    METRIC_JVM_CLASS_COUNT = "jvm.class.count";
    METRIC_JVM_CLASS_LOADED = "jvm.class.loaded";
    METRIC_JVM_CLASS_UNLOADED = "jvm.class.unloaded";
    METRIC_JVM_CPU_COUNT = "jvm.cpu.count";
    METRIC_JVM_CPU_RECENT_UTILIZATION = "jvm.cpu.recent_utilization";
    METRIC_JVM_CPU_TIME = "jvm.cpu.time";
    METRIC_JVM_GC_DURATION = "jvm.gc.duration";
    METRIC_JVM_MEMORY_COMMITTED = "jvm.memory.committed";
    METRIC_JVM_MEMORY_LIMIT = "jvm.memory.limit";
    METRIC_JVM_MEMORY_USED = "jvm.memory.used";
    METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = "jvm.memory.used_after_last_gc";
    METRIC_JVM_THREAD_COUNT = "jvm.thread.count";
    METRIC_KESTREL_ACTIVE_CONNECTIONS = "kestrel.active_connections";
    METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = "kestrel.active_tls_handshakes";
    METRIC_KESTREL_CONNECTION_DURATION = "kestrel.connection.duration";
    METRIC_KESTREL_QUEUED_CONNECTIONS = "kestrel.queued_connections";
    METRIC_KESTREL_QUEUED_REQUESTS = "kestrel.queued_requests";
    METRIC_KESTREL_REJECTED_CONNECTIONS = "kestrel.rejected_connections";
    METRIC_KESTREL_TLS_HANDSHAKE_DURATION = "kestrel.tls_handshake.duration";
    METRIC_KESTREL_UPGRADED_CONNECTIONS = "kestrel.upgraded_connections";
    METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = "signalr.server.active_connections";
    METRIC_SIGNALR_SERVER_CONNECTION_DURATION = "signalr.server.connection.duration";
  }
});

// node_modules/@opentelemetry/semantic-conventions/build/esm/index.js
var esm_exports = {};
__export(esm_exports, {
  ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED: () => ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED,
  ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED: () => ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED,
  ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED: () => ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED,
  ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED: () => ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED,
  ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED: () => ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED,
  ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER: () => ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER,
  ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER: () => ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER,
  ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED: () => ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED,
  ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE: () => ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE,
  ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS: () => ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS,
  ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT: () => ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT,
  ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE: () => ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE,
  ATTR_ASPNETCORE_RATE_LIMITING_POLICY: () => ATTR_ASPNETCORE_RATE_LIMITING_POLICY,
  ATTR_ASPNETCORE_RATE_LIMITING_RESULT: () => ATTR_ASPNETCORE_RATE_LIMITING_RESULT,
  ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED: () => ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED,
  ATTR_ASPNETCORE_ROUTING_IS_FALLBACK: () => ATTR_ASPNETCORE_ROUTING_IS_FALLBACK,
  ATTR_ASPNETCORE_ROUTING_MATCH_STATUS: () => ATTR_ASPNETCORE_ROUTING_MATCH_STATUS,
  ATTR_CLIENT_ADDRESS: () => ATTR_CLIENT_ADDRESS,
  ATTR_CLIENT_PORT: () => ATTR_CLIENT_PORT,
  ATTR_CODE_COLUMN_NUMBER: () => ATTR_CODE_COLUMN_NUMBER,
  ATTR_CODE_FILE_PATH: () => ATTR_CODE_FILE_PATH,
  ATTR_CODE_FUNCTION_NAME: () => ATTR_CODE_FUNCTION_NAME,
  ATTR_CODE_LINE_NUMBER: () => ATTR_CODE_LINE_NUMBER,
  ATTR_CODE_STACKTRACE: () => ATTR_CODE_STACKTRACE,
  ATTR_DB_COLLECTION_NAME: () => ATTR_DB_COLLECTION_NAME,
  ATTR_DB_NAMESPACE: () => ATTR_DB_NAMESPACE,
  ATTR_DB_OPERATION_BATCH_SIZE: () => ATTR_DB_OPERATION_BATCH_SIZE,
  ATTR_DB_OPERATION_NAME: () => ATTR_DB_OPERATION_NAME,
  ATTR_DB_QUERY_SUMMARY: () => ATTR_DB_QUERY_SUMMARY,
  ATTR_DB_QUERY_TEXT: () => ATTR_DB_QUERY_TEXT,
  ATTR_DB_RESPONSE_STATUS_CODE: () => ATTR_DB_RESPONSE_STATUS_CODE,
  ATTR_DB_STORED_PROCEDURE_NAME: () => ATTR_DB_STORED_PROCEDURE_NAME,
  ATTR_DB_SYSTEM_NAME: () => ATTR_DB_SYSTEM_NAME,
  ATTR_DOTNET_GC_HEAP_GENERATION: () => ATTR_DOTNET_GC_HEAP_GENERATION,
  ATTR_ERROR_TYPE: () => ATTR_ERROR_TYPE,
  ATTR_EXCEPTION_ESCAPED: () => ATTR_EXCEPTION_ESCAPED,
  ATTR_EXCEPTION_MESSAGE: () => ATTR_EXCEPTION_MESSAGE,
  ATTR_EXCEPTION_STACKTRACE: () => ATTR_EXCEPTION_STACKTRACE,
  ATTR_EXCEPTION_TYPE: () => ATTR_EXCEPTION_TYPE,
  ATTR_HTTP_REQUEST_HEADER: () => ATTR_HTTP_REQUEST_HEADER,
  ATTR_HTTP_REQUEST_METHOD: () => ATTR_HTTP_REQUEST_METHOD,
  ATTR_HTTP_REQUEST_METHOD_ORIGINAL: () => ATTR_HTTP_REQUEST_METHOD_ORIGINAL,
  ATTR_HTTP_REQUEST_RESEND_COUNT: () => ATTR_HTTP_REQUEST_RESEND_COUNT,
  ATTR_HTTP_RESPONSE_HEADER: () => ATTR_HTTP_RESPONSE_HEADER,
  ATTR_HTTP_RESPONSE_STATUS_CODE: () => ATTR_HTTP_RESPONSE_STATUS_CODE,
  ATTR_HTTP_ROUTE: () => ATTR_HTTP_ROUTE,
  ATTR_JVM_GC_ACTION: () => ATTR_JVM_GC_ACTION,
  ATTR_JVM_GC_NAME: () => ATTR_JVM_GC_NAME,
  ATTR_JVM_MEMORY_POOL_NAME: () => ATTR_JVM_MEMORY_POOL_NAME,
  ATTR_JVM_MEMORY_TYPE: () => ATTR_JVM_MEMORY_TYPE,
  ATTR_JVM_THREAD_DAEMON: () => ATTR_JVM_THREAD_DAEMON,
  ATTR_JVM_THREAD_STATE: () => ATTR_JVM_THREAD_STATE,
  ATTR_NETWORK_LOCAL_ADDRESS: () => ATTR_NETWORK_LOCAL_ADDRESS,
  ATTR_NETWORK_LOCAL_PORT: () => ATTR_NETWORK_LOCAL_PORT,
  ATTR_NETWORK_PEER_ADDRESS: () => ATTR_NETWORK_PEER_ADDRESS,
  ATTR_NETWORK_PEER_PORT: () => ATTR_NETWORK_PEER_PORT,
  ATTR_NETWORK_PROTOCOL_NAME: () => ATTR_NETWORK_PROTOCOL_NAME,
  ATTR_NETWORK_PROTOCOL_VERSION: () => ATTR_NETWORK_PROTOCOL_VERSION,
  ATTR_NETWORK_TRANSPORT: () => ATTR_NETWORK_TRANSPORT,
  ATTR_NETWORK_TYPE: () => ATTR_NETWORK_TYPE,
  ATTR_OTEL_SCOPE_NAME: () => ATTR_OTEL_SCOPE_NAME,
  ATTR_OTEL_SCOPE_VERSION: () => ATTR_OTEL_SCOPE_VERSION,
  ATTR_OTEL_STATUS_CODE: () => ATTR_OTEL_STATUS_CODE,
  ATTR_OTEL_STATUS_DESCRIPTION: () => ATTR_OTEL_STATUS_DESCRIPTION,
  ATTR_SERVER_ADDRESS: () => ATTR_SERVER_ADDRESS,
  ATTR_SERVER_PORT: () => ATTR_SERVER_PORT,
  ATTR_SERVICE_NAME: () => ATTR_SERVICE_NAME,
  ATTR_SERVICE_VERSION: () => ATTR_SERVICE_VERSION,
  ATTR_SIGNALR_CONNECTION_STATUS: () => ATTR_SIGNALR_CONNECTION_STATUS,
  ATTR_SIGNALR_TRANSPORT: () => ATTR_SIGNALR_TRANSPORT,
  ATTR_TELEMETRY_SDK_LANGUAGE: () => ATTR_TELEMETRY_SDK_LANGUAGE,
  ATTR_TELEMETRY_SDK_NAME: () => ATTR_TELEMETRY_SDK_NAME,
  ATTR_TELEMETRY_SDK_VERSION: () => ATTR_TELEMETRY_SDK_VERSION,
  ATTR_URL_FRAGMENT: () => ATTR_URL_FRAGMENT,
  ATTR_URL_FULL: () => ATTR_URL_FULL,
  ATTR_URL_PATH: () => ATTR_URL_PATH,
  ATTR_URL_QUERY: () => ATTR_URL_QUERY,
  ATTR_URL_SCHEME: () => ATTR_URL_SCHEME,
  ATTR_USER_AGENT_ORIGINAL: () => ATTR_USER_AGENT_ORIGINAL,
  AWSECSLAUNCHTYPEVALUES_EC2: () => AWSECSLAUNCHTYPEVALUES_EC2,
  AWSECSLAUNCHTYPEVALUES_FARGATE: () => AWSECSLAUNCHTYPEVALUES_FARGATE,
  AwsEcsLaunchtypeValues: () => AwsEcsLaunchtypeValues,
  CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS: () => CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,
  CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC: () => CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,
  CLOUDPLATFORMVALUES_AWS_EC2: () => CLOUDPLATFORMVALUES_AWS_EC2,
  CLOUDPLATFORMVALUES_AWS_ECS: () => CLOUDPLATFORMVALUES_AWS_ECS,
  CLOUDPLATFORMVALUES_AWS_EKS: () => CLOUDPLATFORMVALUES_AWS_EKS,
  CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK: () => CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,
  CLOUDPLATFORMVALUES_AWS_LAMBDA: () => CLOUDPLATFORMVALUES_AWS_LAMBDA,
  CLOUDPLATFORMVALUES_AZURE_AKS: () => CLOUDPLATFORMVALUES_AZURE_AKS,
  CLOUDPLATFORMVALUES_AZURE_APP_SERVICE: () => CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,
  CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES: () => CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,
  CLOUDPLATFORMVALUES_AZURE_FUNCTIONS: () => CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,
  CLOUDPLATFORMVALUES_AZURE_VM: () => CLOUDPLATFORMVALUES_AZURE_VM,
  CLOUDPLATFORMVALUES_GCP_APP_ENGINE: () => CLOUDPLATFORMVALUES_GCP_APP_ENGINE,
  CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS: () => CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,
  CLOUDPLATFORMVALUES_GCP_CLOUD_RUN: () => CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,
  CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE: () => CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,
  CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE: () => CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,
  CLOUDPROVIDERVALUES_ALIBABA_CLOUD: () => CLOUDPROVIDERVALUES_ALIBABA_CLOUD,
  CLOUDPROVIDERVALUES_AWS: () => CLOUDPROVIDERVALUES_AWS,
  CLOUDPROVIDERVALUES_AZURE: () => CLOUDPROVIDERVALUES_AZURE,
  CLOUDPROVIDERVALUES_GCP: () => CLOUDPROVIDERVALUES_GCP,
  CloudPlatformValues: () => CloudPlatformValues,
  CloudProviderValues: () => CloudProviderValues,
  DBCASSANDRACONSISTENCYLEVELVALUES_ALL: () => DBCASSANDRACONSISTENCYLEVELVALUES_ALL,
  DBCASSANDRACONSISTENCYLEVELVALUES_ANY: () => DBCASSANDRACONSISTENCYLEVELVALUES_ANY,
  DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM: () => DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,
  DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE: () => DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,
  DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM: () => DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,
  DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL: () => DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,
  DBCASSANDRACONSISTENCYLEVELVALUES_ONE: () => DBCASSANDRACONSISTENCYLEVELVALUES_ONE,
  DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM: () => DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,
  DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL: () => DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,
  DBCASSANDRACONSISTENCYLEVELVALUES_THREE: () => DBCASSANDRACONSISTENCYLEVELVALUES_THREE,
  DBCASSANDRACONSISTENCYLEVELVALUES_TWO: () => DBCASSANDRACONSISTENCYLEVELVALUES_TWO,
  DBSYSTEMVALUES_ADABAS: () => DBSYSTEMVALUES_ADABAS,
  DBSYSTEMVALUES_CACHE: () => DBSYSTEMVALUES_CACHE,
  DBSYSTEMVALUES_CASSANDRA: () => DBSYSTEMVALUES_CASSANDRA,
  DBSYSTEMVALUES_CLOUDSCAPE: () => DBSYSTEMVALUES_CLOUDSCAPE,
  DBSYSTEMVALUES_COCKROACHDB: () => DBSYSTEMVALUES_COCKROACHDB,
  DBSYSTEMVALUES_COLDFUSION: () => DBSYSTEMVALUES_COLDFUSION,
  DBSYSTEMVALUES_COSMOSDB: () => DBSYSTEMVALUES_COSMOSDB,
  DBSYSTEMVALUES_COUCHBASE: () => DBSYSTEMVALUES_COUCHBASE,
  DBSYSTEMVALUES_COUCHDB: () => DBSYSTEMVALUES_COUCHDB,
  DBSYSTEMVALUES_DB2: () => DBSYSTEMVALUES_DB2,
  DBSYSTEMVALUES_DERBY: () => DBSYSTEMVALUES_DERBY,
  DBSYSTEMVALUES_DYNAMODB: () => DBSYSTEMVALUES_DYNAMODB,
  DBSYSTEMVALUES_EDB: () => DBSYSTEMVALUES_EDB,
  DBSYSTEMVALUES_ELASTICSEARCH: () => DBSYSTEMVALUES_ELASTICSEARCH,
  DBSYSTEMVALUES_FILEMAKER: () => DBSYSTEMVALUES_FILEMAKER,
  DBSYSTEMVALUES_FIREBIRD: () => DBSYSTEMVALUES_FIREBIRD,
  DBSYSTEMVALUES_FIRSTSQL: () => DBSYSTEMVALUES_FIRSTSQL,
  DBSYSTEMVALUES_GEODE: () => DBSYSTEMVALUES_GEODE,
  DBSYSTEMVALUES_H2: () => DBSYSTEMVALUES_H2,
  DBSYSTEMVALUES_HANADB: () => DBSYSTEMVALUES_HANADB,
  DBSYSTEMVALUES_HBASE: () => DBSYSTEMVALUES_HBASE,
  DBSYSTEMVALUES_HIVE: () => DBSYSTEMVALUES_HIVE,
  DBSYSTEMVALUES_HSQLDB: () => DBSYSTEMVALUES_HSQLDB,
  DBSYSTEMVALUES_INFORMIX: () => DBSYSTEMVALUES_INFORMIX,
  DBSYSTEMVALUES_INGRES: () => DBSYSTEMVALUES_INGRES,
  DBSYSTEMVALUES_INSTANTDB: () => DBSYSTEMVALUES_INSTANTDB,
  DBSYSTEMVALUES_INTERBASE: () => DBSYSTEMVALUES_INTERBASE,
  DBSYSTEMVALUES_MARIADB: () => DBSYSTEMVALUES_MARIADB,
  DBSYSTEMVALUES_MAXDB: () => DBSYSTEMVALUES_MAXDB,
  DBSYSTEMVALUES_MEMCACHED: () => DBSYSTEMVALUES_MEMCACHED,
  DBSYSTEMVALUES_MONGODB: () => DBSYSTEMVALUES_MONGODB,
  DBSYSTEMVALUES_MSSQL: () => DBSYSTEMVALUES_MSSQL,
  DBSYSTEMVALUES_MYSQL: () => DBSYSTEMVALUES_MYSQL,
  DBSYSTEMVALUES_NEO4J: () => DBSYSTEMVALUES_NEO4J,
  DBSYSTEMVALUES_NETEZZA: () => DBSYSTEMVALUES_NETEZZA,
  DBSYSTEMVALUES_ORACLE: () => DBSYSTEMVALUES_ORACLE,
  DBSYSTEMVALUES_OTHER_SQL: () => DBSYSTEMVALUES_OTHER_SQL,
  DBSYSTEMVALUES_PERVASIVE: () => DBSYSTEMVALUES_PERVASIVE,
  DBSYSTEMVALUES_POINTBASE: () => DBSYSTEMVALUES_POINTBASE,
  DBSYSTEMVALUES_POSTGRESQL: () => DBSYSTEMVALUES_POSTGRESQL,
  DBSYSTEMVALUES_PROGRESS: () => DBSYSTEMVALUES_PROGRESS,
  DBSYSTEMVALUES_REDIS: () => DBSYSTEMVALUES_REDIS,
  DBSYSTEMVALUES_REDSHIFT: () => DBSYSTEMVALUES_REDSHIFT,
  DBSYSTEMVALUES_SQLITE: () => DBSYSTEMVALUES_SQLITE,
  DBSYSTEMVALUES_SYBASE: () => DBSYSTEMVALUES_SYBASE,
  DBSYSTEMVALUES_TERADATA: () => DBSYSTEMVALUES_TERADATA,
  DBSYSTEMVALUES_VERTICA: () => DBSYSTEMVALUES_VERTICA,
  DB_SYSTEM_NAME_VALUE_MARIADB: () => DB_SYSTEM_NAME_VALUE_MARIADB,
  DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER: () => DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER,
  DB_SYSTEM_NAME_VALUE_MYSQL: () => DB_SYSTEM_NAME_VALUE_MYSQL,
  DB_SYSTEM_NAME_VALUE_POSTGRESQL: () => DB_SYSTEM_NAME_VALUE_POSTGRESQL,
  DOTNET_GC_HEAP_GENERATION_VALUE_GEN0: () => DOTNET_GC_HEAP_GENERATION_VALUE_GEN0,
  DOTNET_GC_HEAP_GENERATION_VALUE_GEN1: () => DOTNET_GC_HEAP_GENERATION_VALUE_GEN1,
  DOTNET_GC_HEAP_GENERATION_VALUE_GEN2: () => DOTNET_GC_HEAP_GENERATION_VALUE_GEN2,
  DOTNET_GC_HEAP_GENERATION_VALUE_LOH: () => DOTNET_GC_HEAP_GENERATION_VALUE_LOH,
  DOTNET_GC_HEAP_GENERATION_VALUE_POH: () => DOTNET_GC_HEAP_GENERATION_VALUE_POH,
  DbCassandraConsistencyLevelValues: () => DbCassandraConsistencyLevelValues,
  DbSystemValues: () => DbSystemValues,
  ERROR_TYPE_VALUE_OTHER: () => ERROR_TYPE_VALUE_OTHER,
  FAASDOCUMENTOPERATIONVALUES_DELETE: () => FAASDOCUMENTOPERATIONVALUES_DELETE,
  FAASDOCUMENTOPERATIONVALUES_EDIT: () => FAASDOCUMENTOPERATIONVALUES_EDIT,
  FAASDOCUMENTOPERATIONVALUES_INSERT: () => FAASDOCUMENTOPERATIONVALUES_INSERT,
  FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD: () => FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,
  FAASINVOKEDPROVIDERVALUES_AWS: () => FAASINVOKEDPROVIDERVALUES_AWS,
  FAASINVOKEDPROVIDERVALUES_AZURE: () => FAASINVOKEDPROVIDERVALUES_AZURE,
  FAASINVOKEDPROVIDERVALUES_GCP: () => FAASINVOKEDPROVIDERVALUES_GCP,
  FAASTRIGGERVALUES_DATASOURCE: () => FAASTRIGGERVALUES_DATASOURCE,
  FAASTRIGGERVALUES_HTTP: () => FAASTRIGGERVALUES_HTTP,
  FAASTRIGGERVALUES_OTHER: () => FAASTRIGGERVALUES_OTHER,
  FAASTRIGGERVALUES_PUBSUB: () => FAASTRIGGERVALUES_PUBSUB,
  FAASTRIGGERVALUES_TIMER: () => FAASTRIGGERVALUES_TIMER,
  FaasDocumentOperationValues: () => FaasDocumentOperationValues,
  FaasInvokedProviderValues: () => FaasInvokedProviderValues,
  FaasTriggerValues: () => FaasTriggerValues,
  HOSTARCHVALUES_AMD64: () => HOSTARCHVALUES_AMD64,
  HOSTARCHVALUES_ARM32: () => HOSTARCHVALUES_ARM32,
  HOSTARCHVALUES_ARM64: () => HOSTARCHVALUES_ARM64,
  HOSTARCHVALUES_IA64: () => HOSTARCHVALUES_IA64,
  HOSTARCHVALUES_PPC32: () => HOSTARCHVALUES_PPC32,
  HOSTARCHVALUES_PPC64: () => HOSTARCHVALUES_PPC64,
  HOSTARCHVALUES_X86: () => HOSTARCHVALUES_X86,
  HTTPFLAVORVALUES_HTTP_1_0: () => HTTPFLAVORVALUES_HTTP_1_0,
  HTTPFLAVORVALUES_HTTP_1_1: () => HTTPFLAVORVALUES_HTTP_1_1,
  HTTPFLAVORVALUES_HTTP_2_0: () => HTTPFLAVORVALUES_HTTP_2_0,
  HTTPFLAVORVALUES_QUIC: () => HTTPFLAVORVALUES_QUIC,
  HTTPFLAVORVALUES_SPDY: () => HTTPFLAVORVALUES_SPDY,
  HTTP_REQUEST_METHOD_VALUE_CONNECT: () => HTTP_REQUEST_METHOD_VALUE_CONNECT,
  HTTP_REQUEST_METHOD_VALUE_DELETE: () => HTTP_REQUEST_METHOD_VALUE_DELETE,
  HTTP_REQUEST_METHOD_VALUE_GET: () => HTTP_REQUEST_METHOD_VALUE_GET,
  HTTP_REQUEST_METHOD_VALUE_HEAD: () => HTTP_REQUEST_METHOD_VALUE_HEAD,
  HTTP_REQUEST_METHOD_VALUE_OPTIONS: () => HTTP_REQUEST_METHOD_VALUE_OPTIONS,
  HTTP_REQUEST_METHOD_VALUE_OTHER: () => HTTP_REQUEST_METHOD_VALUE_OTHER,
  HTTP_REQUEST_METHOD_VALUE_PATCH: () => HTTP_REQUEST_METHOD_VALUE_PATCH,
  HTTP_REQUEST_METHOD_VALUE_POST: () => HTTP_REQUEST_METHOD_VALUE_POST,
  HTTP_REQUEST_METHOD_VALUE_PUT: () => HTTP_REQUEST_METHOD_VALUE_PUT,
  HTTP_REQUEST_METHOD_VALUE_TRACE: () => HTTP_REQUEST_METHOD_VALUE_TRACE,
  HostArchValues: () => HostArchValues,
  HttpFlavorValues: () => HttpFlavorValues,
  JVM_MEMORY_TYPE_VALUE_HEAP: () => JVM_MEMORY_TYPE_VALUE_HEAP,
  JVM_MEMORY_TYPE_VALUE_NON_HEAP: () => JVM_MEMORY_TYPE_VALUE_NON_HEAP,
  JVM_THREAD_STATE_VALUE_BLOCKED: () => JVM_THREAD_STATE_VALUE_BLOCKED,
  JVM_THREAD_STATE_VALUE_NEW: () => JVM_THREAD_STATE_VALUE_NEW,
  JVM_THREAD_STATE_VALUE_RUNNABLE: () => JVM_THREAD_STATE_VALUE_RUNNABLE,
  JVM_THREAD_STATE_VALUE_TERMINATED: () => JVM_THREAD_STATE_VALUE_TERMINATED,
  JVM_THREAD_STATE_VALUE_TIMED_WAITING: () => JVM_THREAD_STATE_VALUE_TIMED_WAITING,
  JVM_THREAD_STATE_VALUE_WAITING: () => JVM_THREAD_STATE_VALUE_WAITING,
  MESSAGETYPEVALUES_RECEIVED: () => MESSAGETYPEVALUES_RECEIVED,
  MESSAGETYPEVALUES_SENT: () => MESSAGETYPEVALUES_SENT,
  MESSAGINGDESTINATIONKINDVALUES_QUEUE: () => MESSAGINGDESTINATIONKINDVALUES_QUEUE,
  MESSAGINGDESTINATIONKINDVALUES_TOPIC: () => MESSAGINGDESTINATIONKINDVALUES_TOPIC,
  MESSAGINGOPERATIONVALUES_PROCESS: () => MESSAGINGOPERATIONVALUES_PROCESS,
  MESSAGINGOPERATIONVALUES_RECEIVE: () => MESSAGINGOPERATIONVALUES_RECEIVE,
  METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS: () => METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS,
  METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES: () => METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES,
  METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS: () => METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS,
  METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS: () => METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS,
  METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION: () => METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION,
  METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE: () => METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE,
  METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS: () => METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS,
  METRIC_DB_CLIENT_OPERATION_DURATION: () => METRIC_DB_CLIENT_OPERATION_DURATION,
  METRIC_DOTNET_ASSEMBLY_COUNT: () => METRIC_DOTNET_ASSEMBLY_COUNT,
  METRIC_DOTNET_EXCEPTIONS: () => METRIC_DOTNET_EXCEPTIONS,
  METRIC_DOTNET_GC_COLLECTIONS: () => METRIC_DOTNET_GC_COLLECTIONS,
  METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED: () => METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED,
  METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE: () => METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE,
  METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE: () => METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE,
  METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE: () => METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE,
  METRIC_DOTNET_GC_PAUSE_TIME: () => METRIC_DOTNET_GC_PAUSE_TIME,
  METRIC_DOTNET_JIT_COMPILATION_TIME: () => METRIC_DOTNET_JIT_COMPILATION_TIME,
  METRIC_DOTNET_JIT_COMPILED_IL_SIZE: () => METRIC_DOTNET_JIT_COMPILED_IL_SIZE,
  METRIC_DOTNET_JIT_COMPILED_METHODS: () => METRIC_DOTNET_JIT_COMPILED_METHODS,
  METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS: () => METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS,
  METRIC_DOTNET_PROCESS_CPU_COUNT: () => METRIC_DOTNET_PROCESS_CPU_COUNT,
  METRIC_DOTNET_PROCESS_CPU_TIME: () => METRIC_DOTNET_PROCESS_CPU_TIME,
  METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET: () => METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET,
  METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH: () => METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH,
  METRIC_DOTNET_THREAD_POOL_THREAD_COUNT: () => METRIC_DOTNET_THREAD_POOL_THREAD_COUNT,
  METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT: () => METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT,
  METRIC_DOTNET_TIMER_COUNT: () => METRIC_DOTNET_TIMER_COUNT,
  METRIC_HTTP_CLIENT_REQUEST_DURATION: () => METRIC_HTTP_CLIENT_REQUEST_DURATION,
  METRIC_HTTP_SERVER_REQUEST_DURATION: () => METRIC_HTTP_SERVER_REQUEST_DURATION,
  METRIC_JVM_CLASS_COUNT: () => METRIC_JVM_CLASS_COUNT,
  METRIC_JVM_CLASS_LOADED: () => METRIC_JVM_CLASS_LOADED,
  METRIC_JVM_CLASS_UNLOADED: () => METRIC_JVM_CLASS_UNLOADED,
  METRIC_JVM_CPU_COUNT: () => METRIC_JVM_CPU_COUNT,
  METRIC_JVM_CPU_RECENT_UTILIZATION: () => METRIC_JVM_CPU_RECENT_UTILIZATION,
  METRIC_JVM_CPU_TIME: () => METRIC_JVM_CPU_TIME,
  METRIC_JVM_GC_DURATION: () => METRIC_JVM_GC_DURATION,
  METRIC_JVM_MEMORY_COMMITTED: () => METRIC_JVM_MEMORY_COMMITTED,
  METRIC_JVM_MEMORY_LIMIT: () => METRIC_JVM_MEMORY_LIMIT,
  METRIC_JVM_MEMORY_USED: () => METRIC_JVM_MEMORY_USED,
  METRIC_JVM_MEMORY_USED_AFTER_LAST_GC: () => METRIC_JVM_MEMORY_USED_AFTER_LAST_GC,
  METRIC_JVM_THREAD_COUNT: () => METRIC_JVM_THREAD_COUNT,
  METRIC_KESTREL_ACTIVE_CONNECTIONS: () => METRIC_KESTREL_ACTIVE_CONNECTIONS,
  METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES: () => METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES,
  METRIC_KESTREL_CONNECTION_DURATION: () => METRIC_KESTREL_CONNECTION_DURATION,
  METRIC_KESTREL_QUEUED_CONNECTIONS: () => METRIC_KESTREL_QUEUED_CONNECTIONS,
  METRIC_KESTREL_QUEUED_REQUESTS: () => METRIC_KESTREL_QUEUED_REQUESTS,
  METRIC_KESTREL_REJECTED_CONNECTIONS: () => METRIC_KESTREL_REJECTED_CONNECTIONS,
  METRIC_KESTREL_TLS_HANDSHAKE_DURATION: () => METRIC_KESTREL_TLS_HANDSHAKE_DURATION,
  METRIC_KESTREL_UPGRADED_CONNECTIONS: () => METRIC_KESTREL_UPGRADED_CONNECTIONS,
  METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS: () => METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS,
  METRIC_SIGNALR_SERVER_CONNECTION_DURATION: () => METRIC_SIGNALR_SERVER_CONNECTION_DURATION,
  MessageTypeValues: () => MessageTypeValues,
  MessagingDestinationKindValues: () => MessagingDestinationKindValues,
  MessagingOperationValues: () => MessagingOperationValues,
  NETHOSTCONNECTIONSUBTYPEVALUES_CDMA: () => NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,
  NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT: () => NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,
  NETHOSTCONNECTIONSUBTYPEVALUES_EDGE: () => NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,
  NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD: () => NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,
  NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0: () => NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,
  NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A: () => NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,
  NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B: () => NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,
  NETHOSTCONNECTIONSUBTYPEVALUES_GPRS: () => NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,
  NETHOSTCONNECTIONSUBTYPEVALUES_GSM: () => NETHOSTCONNECTIONSUBTYPEVALUES_GSM,
  NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA: () => NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,
  NETHOSTCONNECTIONSUBTYPEVALUES_HSPA: () => NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,
  NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP: () => NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,
  NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA: () => NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,
  NETHOSTCONNECTIONSUBTYPEVALUES_IDEN: () => NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,
  NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN: () => NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,
  NETHOSTCONNECTIONSUBTYPEVALUES_LTE: () => NETHOSTCONNECTIONSUBTYPEVALUES_LTE,
  NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA: () => NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,
  NETHOSTCONNECTIONSUBTYPEVALUES_NR: () => NETHOSTCONNECTIONSUBTYPEVALUES_NR,
  NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA: () => NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,
  NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA: () => NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,
  NETHOSTCONNECTIONSUBTYPEVALUES_UMTS: () => NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,
  NETHOSTCONNECTIONTYPEVALUES_CELL: () => NETHOSTCONNECTIONTYPEVALUES_CELL,
  NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE: () => NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,
  NETHOSTCONNECTIONTYPEVALUES_UNKNOWN: () => NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,
  NETHOSTCONNECTIONTYPEVALUES_WIFI: () => NETHOSTCONNECTIONTYPEVALUES_WIFI,
  NETHOSTCONNECTIONTYPEVALUES_WIRED: () => NETHOSTCONNECTIONTYPEVALUES_WIRED,
  NETTRANSPORTVALUES_INPROC: () => NETTRANSPORTVALUES_INPROC,
  NETTRANSPORTVALUES_IP: () => NETTRANSPORTVALUES_IP,
  NETTRANSPORTVALUES_IP_TCP: () => NETTRANSPORTVALUES_IP_TCP,
  NETTRANSPORTVALUES_IP_UDP: () => NETTRANSPORTVALUES_IP_UDP,
  NETTRANSPORTVALUES_OTHER: () => NETTRANSPORTVALUES_OTHER,
  NETTRANSPORTVALUES_PIPE: () => NETTRANSPORTVALUES_PIPE,
  NETTRANSPORTVALUES_UNIX: () => NETTRANSPORTVALUES_UNIX,
  NETWORK_TRANSPORT_VALUE_PIPE: () => NETWORK_TRANSPORT_VALUE_PIPE,
  NETWORK_TRANSPORT_VALUE_QUIC: () => NETWORK_TRANSPORT_VALUE_QUIC,
  NETWORK_TRANSPORT_VALUE_TCP: () => NETWORK_TRANSPORT_VALUE_TCP,
  NETWORK_TRANSPORT_VALUE_UDP: () => NETWORK_TRANSPORT_VALUE_UDP,
  NETWORK_TRANSPORT_VALUE_UNIX: () => NETWORK_TRANSPORT_VALUE_UNIX,
  NETWORK_TYPE_VALUE_IPV4: () => NETWORK_TYPE_VALUE_IPV4,
  NETWORK_TYPE_VALUE_IPV6: () => NETWORK_TYPE_VALUE_IPV6,
  NetHostConnectionSubtypeValues: () => NetHostConnectionSubtypeValues,
  NetHostConnectionTypeValues: () => NetHostConnectionTypeValues,
  NetTransportValues: () => NetTransportValues,
  OSTYPEVALUES_AIX: () => OSTYPEVALUES_AIX,
  OSTYPEVALUES_DARWIN: () => OSTYPEVALUES_DARWIN,
  OSTYPEVALUES_DRAGONFLYBSD: () => OSTYPEVALUES_DRAGONFLYBSD,
  OSTYPEVALUES_FREEBSD: () => OSTYPEVALUES_FREEBSD,
  OSTYPEVALUES_HPUX: () => OSTYPEVALUES_HPUX,
  OSTYPEVALUES_LINUX: () => OSTYPEVALUES_LINUX,
  OSTYPEVALUES_NETBSD: () => OSTYPEVALUES_NETBSD,
  OSTYPEVALUES_OPENBSD: () => OSTYPEVALUES_OPENBSD,
  OSTYPEVALUES_SOLARIS: () => OSTYPEVALUES_SOLARIS,
  OSTYPEVALUES_WINDOWS: () => OSTYPEVALUES_WINDOWS,
  OSTYPEVALUES_Z_OS: () => OSTYPEVALUES_Z_OS,
  OTEL_STATUS_CODE_VALUE_ERROR: () => OTEL_STATUS_CODE_VALUE_ERROR,
  OTEL_STATUS_CODE_VALUE_OK: () => OTEL_STATUS_CODE_VALUE_OK,
  OsTypeValues: () => OsTypeValues,
  RPCGRPCSTATUSCODEVALUES_ABORTED: () => RPCGRPCSTATUSCODEVALUES_ABORTED,
  RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS: () => RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS,
  RPCGRPCSTATUSCODEVALUES_CANCELLED: () => RPCGRPCSTATUSCODEVALUES_CANCELLED,
  RPCGRPCSTATUSCODEVALUES_DATA_LOSS: () => RPCGRPCSTATUSCODEVALUES_DATA_LOSS,
  RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED: () => RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED,
  RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION: () => RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION,
  RPCGRPCSTATUSCODEVALUES_INTERNAL: () => RPCGRPCSTATUSCODEVALUES_INTERNAL,
  RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT: () => RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT,
  RPCGRPCSTATUSCODEVALUES_NOT_FOUND: () => RPCGRPCSTATUSCODEVALUES_NOT_FOUND,
  RPCGRPCSTATUSCODEVALUES_OK: () => RPCGRPCSTATUSCODEVALUES_OK,
  RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE: () => RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE,
  RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED: () => RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED,
  RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED: () => RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED,
  RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED: () => RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED,
  RPCGRPCSTATUSCODEVALUES_UNAVAILABLE: () => RPCGRPCSTATUSCODEVALUES_UNAVAILABLE,
  RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED: () => RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED,
  RPCGRPCSTATUSCODEVALUES_UNKNOWN: () => RPCGRPCSTATUSCODEVALUES_UNKNOWN,
  RpcGrpcStatusCodeValues: () => RpcGrpcStatusCodeValues,
  SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET: () => SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET,
  SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS: () => SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,
  SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ: () => SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ,
  SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY: () => SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY,
  SEMATTRS_AWS_DYNAMODB_COUNT: () => SEMATTRS_AWS_DYNAMODB_COUNT,
  SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE: () => SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,
  SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES: () => SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,
  SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES: () => SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,
  SEMATTRS_AWS_DYNAMODB_INDEX_NAME: () => SEMATTRS_AWS_DYNAMODB_INDEX_NAME,
  SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS: () => SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,
  SEMATTRS_AWS_DYNAMODB_LIMIT: () => SEMATTRS_AWS_DYNAMODB_LIMIT,
  SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES: () => SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,
  SEMATTRS_AWS_DYNAMODB_PROJECTION: () => SEMATTRS_AWS_DYNAMODB_PROJECTION,
  SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY: () => SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,
  SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY: () => SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,
  SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT: () => SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT,
  SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD: () => SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD,
  SEMATTRS_AWS_DYNAMODB_SEGMENT: () => SEMATTRS_AWS_DYNAMODB_SEGMENT,
  SEMATTRS_AWS_DYNAMODB_SELECT: () => SEMATTRS_AWS_DYNAMODB_SELECT,
  SEMATTRS_AWS_DYNAMODB_TABLE_COUNT: () => SEMATTRS_AWS_DYNAMODB_TABLE_COUNT,
  SEMATTRS_AWS_DYNAMODB_TABLE_NAMES: () => SEMATTRS_AWS_DYNAMODB_TABLE_NAMES,
  SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS: () => SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS,
  SEMATTRS_AWS_LAMBDA_INVOKED_ARN: () => SEMATTRS_AWS_LAMBDA_INVOKED_ARN,
  SEMATTRS_CODE_FILEPATH: () => SEMATTRS_CODE_FILEPATH,
  SEMATTRS_CODE_FUNCTION: () => SEMATTRS_CODE_FUNCTION,
  SEMATTRS_CODE_LINENO: () => SEMATTRS_CODE_LINENO,
  SEMATTRS_CODE_NAMESPACE: () => SEMATTRS_CODE_NAMESPACE,
  SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL: () => SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL,
  SEMATTRS_DB_CASSANDRA_COORDINATOR_DC: () => SEMATTRS_DB_CASSANDRA_COORDINATOR_DC,
  SEMATTRS_DB_CASSANDRA_COORDINATOR_ID: () => SEMATTRS_DB_CASSANDRA_COORDINATOR_ID,
  SEMATTRS_DB_CASSANDRA_IDEMPOTENCE: () => SEMATTRS_DB_CASSANDRA_IDEMPOTENCE,
  SEMATTRS_DB_CASSANDRA_KEYSPACE: () => SEMATTRS_DB_CASSANDRA_KEYSPACE,
  SEMATTRS_DB_CASSANDRA_PAGE_SIZE: () => SEMATTRS_DB_CASSANDRA_PAGE_SIZE,
  SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT: () => SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,
  SEMATTRS_DB_CASSANDRA_TABLE: () => SEMATTRS_DB_CASSANDRA_TABLE,
  SEMATTRS_DB_CONNECTION_STRING: () => SEMATTRS_DB_CONNECTION_STRING,
  SEMATTRS_DB_HBASE_NAMESPACE: () => SEMATTRS_DB_HBASE_NAMESPACE,
  SEMATTRS_DB_JDBC_DRIVER_CLASSNAME: () => SEMATTRS_DB_JDBC_DRIVER_CLASSNAME,
  SEMATTRS_DB_MONGODB_COLLECTION: () => SEMATTRS_DB_MONGODB_COLLECTION,
  SEMATTRS_DB_MSSQL_INSTANCE_NAME: () => SEMATTRS_DB_MSSQL_INSTANCE_NAME,
  SEMATTRS_DB_NAME: () => SEMATTRS_DB_NAME,
  SEMATTRS_DB_OPERATION: () => SEMATTRS_DB_OPERATION,
  SEMATTRS_DB_REDIS_DATABASE_INDEX: () => SEMATTRS_DB_REDIS_DATABASE_INDEX,
  SEMATTRS_DB_SQL_TABLE: () => SEMATTRS_DB_SQL_TABLE,
  SEMATTRS_DB_STATEMENT: () => SEMATTRS_DB_STATEMENT,
  SEMATTRS_DB_SYSTEM: () => SEMATTRS_DB_SYSTEM,
  SEMATTRS_DB_USER: () => SEMATTRS_DB_USER,
  SEMATTRS_ENDUSER_ID: () => SEMATTRS_ENDUSER_ID,
  SEMATTRS_ENDUSER_ROLE: () => SEMATTRS_ENDUSER_ROLE,
  SEMATTRS_ENDUSER_SCOPE: () => SEMATTRS_ENDUSER_SCOPE,
  SEMATTRS_EXCEPTION_ESCAPED: () => SEMATTRS_EXCEPTION_ESCAPED,
  SEMATTRS_EXCEPTION_MESSAGE: () => SEMATTRS_EXCEPTION_MESSAGE,
  SEMATTRS_EXCEPTION_STACKTRACE: () => SEMATTRS_EXCEPTION_STACKTRACE,
  SEMATTRS_EXCEPTION_TYPE: () => SEMATTRS_EXCEPTION_TYPE,
  SEMATTRS_FAAS_COLDSTART: () => SEMATTRS_FAAS_COLDSTART,
  SEMATTRS_FAAS_CRON: () => SEMATTRS_FAAS_CRON,
  SEMATTRS_FAAS_DOCUMENT_COLLECTION: () => SEMATTRS_FAAS_DOCUMENT_COLLECTION,
  SEMATTRS_FAAS_DOCUMENT_NAME: () => SEMATTRS_FAAS_DOCUMENT_NAME,
  SEMATTRS_FAAS_DOCUMENT_OPERATION: () => SEMATTRS_FAAS_DOCUMENT_OPERATION,
  SEMATTRS_FAAS_DOCUMENT_TIME: () => SEMATTRS_FAAS_DOCUMENT_TIME,
  SEMATTRS_FAAS_EXECUTION: () => SEMATTRS_FAAS_EXECUTION,
  SEMATTRS_FAAS_INVOKED_NAME: () => SEMATTRS_FAAS_INVOKED_NAME,
  SEMATTRS_FAAS_INVOKED_PROVIDER: () => SEMATTRS_FAAS_INVOKED_PROVIDER,
  SEMATTRS_FAAS_INVOKED_REGION: () => SEMATTRS_FAAS_INVOKED_REGION,
  SEMATTRS_FAAS_TIME: () => SEMATTRS_FAAS_TIME,
  SEMATTRS_FAAS_TRIGGER: () => SEMATTRS_FAAS_TRIGGER,
  SEMATTRS_HTTP_CLIENT_IP: () => SEMATTRS_HTTP_CLIENT_IP,
  SEMATTRS_HTTP_FLAVOR: () => SEMATTRS_HTTP_FLAVOR,
  SEMATTRS_HTTP_HOST: () => SEMATTRS_HTTP_HOST,
  SEMATTRS_HTTP_METHOD: () => SEMATTRS_HTTP_METHOD,
  SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH: () => SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH,
  SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED: () => SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,
  SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH: () => SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH,
  SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED: () => SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,
  SEMATTRS_HTTP_ROUTE: () => SEMATTRS_HTTP_ROUTE,
  SEMATTRS_HTTP_SCHEME: () => SEMATTRS_HTTP_SCHEME,
  SEMATTRS_HTTP_SERVER_NAME: () => SEMATTRS_HTTP_SERVER_NAME,
  SEMATTRS_HTTP_STATUS_CODE: () => SEMATTRS_HTTP_STATUS_CODE,
  SEMATTRS_HTTP_TARGET: () => SEMATTRS_HTTP_TARGET,
  SEMATTRS_HTTP_URL: () => SEMATTRS_HTTP_URL,
  SEMATTRS_HTTP_USER_AGENT: () => SEMATTRS_HTTP_USER_AGENT,
  SEMATTRS_MESSAGE_COMPRESSED_SIZE: () => SEMATTRS_MESSAGE_COMPRESSED_SIZE,
  SEMATTRS_MESSAGE_ID: () => SEMATTRS_MESSAGE_ID,
  SEMATTRS_MESSAGE_TYPE: () => SEMATTRS_MESSAGE_TYPE,
  SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE: () => SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE,
  SEMATTRS_MESSAGING_CONSUMER_ID: () => SEMATTRS_MESSAGING_CONSUMER_ID,
  SEMATTRS_MESSAGING_CONVERSATION_ID: () => SEMATTRS_MESSAGING_CONVERSATION_ID,
  SEMATTRS_MESSAGING_DESTINATION: () => SEMATTRS_MESSAGING_DESTINATION,
  SEMATTRS_MESSAGING_DESTINATION_KIND: () => SEMATTRS_MESSAGING_DESTINATION_KIND,
  SEMATTRS_MESSAGING_KAFKA_CLIENT_ID: () => SEMATTRS_MESSAGING_KAFKA_CLIENT_ID,
  SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP: () => SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP,
  SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY: () => SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY,
  SEMATTRS_MESSAGING_KAFKA_PARTITION: () => SEMATTRS_MESSAGING_KAFKA_PARTITION,
  SEMATTRS_MESSAGING_KAFKA_TOMBSTONE: () => SEMATTRS_MESSAGING_KAFKA_TOMBSTONE,
  SEMATTRS_MESSAGING_MESSAGE_ID: () => SEMATTRS_MESSAGING_MESSAGE_ID,
  SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES: () => SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,
  SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES: () => SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,
  SEMATTRS_MESSAGING_OPERATION: () => SEMATTRS_MESSAGING_OPERATION,
  SEMATTRS_MESSAGING_PROTOCOL: () => SEMATTRS_MESSAGING_PROTOCOL,
  SEMATTRS_MESSAGING_PROTOCOL_VERSION: () => SEMATTRS_MESSAGING_PROTOCOL_VERSION,
  SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY: () => SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY,
  SEMATTRS_MESSAGING_SYSTEM: () => SEMATTRS_MESSAGING_SYSTEM,
  SEMATTRS_MESSAGING_TEMP_DESTINATION: () => SEMATTRS_MESSAGING_TEMP_DESTINATION,
  SEMATTRS_MESSAGING_URL: () => SEMATTRS_MESSAGING_URL,
  SEMATTRS_NET_HOST_CARRIER_ICC: () => SEMATTRS_NET_HOST_CARRIER_ICC,
  SEMATTRS_NET_HOST_CARRIER_MCC: () => SEMATTRS_NET_HOST_CARRIER_MCC,
  SEMATTRS_NET_HOST_CARRIER_MNC: () => SEMATTRS_NET_HOST_CARRIER_MNC,
  SEMATTRS_NET_HOST_CARRIER_NAME: () => SEMATTRS_NET_HOST_CARRIER_NAME,
  SEMATTRS_NET_HOST_CONNECTION_SUBTYPE: () => SEMATTRS_NET_HOST_CONNECTION_SUBTYPE,
  SEMATTRS_NET_HOST_CONNECTION_TYPE: () => SEMATTRS_NET_HOST_CONNECTION_TYPE,
  SEMATTRS_NET_HOST_IP: () => SEMATTRS_NET_HOST_IP,
  SEMATTRS_NET_HOST_NAME: () => SEMATTRS_NET_HOST_NAME,
  SEMATTRS_NET_HOST_PORT: () => SEMATTRS_NET_HOST_PORT,
  SEMATTRS_NET_PEER_IP: () => SEMATTRS_NET_PEER_IP,
  SEMATTRS_NET_PEER_NAME: () => SEMATTRS_NET_PEER_NAME,
  SEMATTRS_NET_PEER_PORT: () => SEMATTRS_NET_PEER_PORT,
  SEMATTRS_NET_TRANSPORT: () => SEMATTRS_NET_TRANSPORT,
  SEMATTRS_PEER_SERVICE: () => SEMATTRS_PEER_SERVICE,
  SEMATTRS_RPC_GRPC_STATUS_CODE: () => SEMATTRS_RPC_GRPC_STATUS_CODE,
  SEMATTRS_RPC_JSONRPC_ERROR_CODE: () => SEMATTRS_RPC_JSONRPC_ERROR_CODE,
  SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE: () => SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE,
  SEMATTRS_RPC_JSONRPC_REQUEST_ID: () => SEMATTRS_RPC_JSONRPC_REQUEST_ID,
  SEMATTRS_RPC_JSONRPC_VERSION: () => SEMATTRS_RPC_JSONRPC_VERSION,
  SEMATTRS_RPC_METHOD: () => SEMATTRS_RPC_METHOD,
  SEMATTRS_RPC_SERVICE: () => SEMATTRS_RPC_SERVICE,
  SEMATTRS_RPC_SYSTEM: () => SEMATTRS_RPC_SYSTEM,
  SEMATTRS_THREAD_ID: () => SEMATTRS_THREAD_ID,
  SEMATTRS_THREAD_NAME: () => SEMATTRS_THREAD_NAME,
  SEMRESATTRS_AWS_ECS_CLUSTER_ARN: () => SEMRESATTRS_AWS_ECS_CLUSTER_ARN,
  SEMRESATTRS_AWS_ECS_CONTAINER_ARN: () => SEMRESATTRS_AWS_ECS_CONTAINER_ARN,
  SEMRESATTRS_AWS_ECS_LAUNCHTYPE: () => SEMRESATTRS_AWS_ECS_LAUNCHTYPE,
  SEMRESATTRS_AWS_ECS_TASK_ARN: () => SEMRESATTRS_AWS_ECS_TASK_ARN,
  SEMRESATTRS_AWS_ECS_TASK_FAMILY: () => SEMRESATTRS_AWS_ECS_TASK_FAMILY,
  SEMRESATTRS_AWS_ECS_TASK_REVISION: () => SEMRESATTRS_AWS_ECS_TASK_REVISION,
  SEMRESATTRS_AWS_EKS_CLUSTER_ARN: () => SEMRESATTRS_AWS_EKS_CLUSTER_ARN,
  SEMRESATTRS_AWS_LOG_GROUP_ARNS: () => SEMRESATTRS_AWS_LOG_GROUP_ARNS,
  SEMRESATTRS_AWS_LOG_GROUP_NAMES: () => SEMRESATTRS_AWS_LOG_GROUP_NAMES,
  SEMRESATTRS_AWS_LOG_STREAM_ARNS: () => SEMRESATTRS_AWS_LOG_STREAM_ARNS,
  SEMRESATTRS_AWS_LOG_STREAM_NAMES: () => SEMRESATTRS_AWS_LOG_STREAM_NAMES,
  SEMRESATTRS_CLOUD_ACCOUNT_ID: () => SEMRESATTRS_CLOUD_ACCOUNT_ID,
  SEMRESATTRS_CLOUD_AVAILABILITY_ZONE: () => SEMRESATTRS_CLOUD_AVAILABILITY_ZONE,
  SEMRESATTRS_CLOUD_PLATFORM: () => SEMRESATTRS_CLOUD_PLATFORM,
  SEMRESATTRS_CLOUD_PROVIDER: () => SEMRESATTRS_CLOUD_PROVIDER,
  SEMRESATTRS_CLOUD_REGION: () => SEMRESATTRS_CLOUD_REGION,
  SEMRESATTRS_CONTAINER_ID: () => SEMRESATTRS_CONTAINER_ID,
  SEMRESATTRS_CONTAINER_IMAGE_NAME: () => SEMRESATTRS_CONTAINER_IMAGE_NAME,
  SEMRESATTRS_CONTAINER_IMAGE_TAG: () => SEMRESATTRS_CONTAINER_IMAGE_TAG,
  SEMRESATTRS_CONTAINER_NAME: () => SEMRESATTRS_CONTAINER_NAME,
  SEMRESATTRS_CONTAINER_RUNTIME: () => SEMRESATTRS_CONTAINER_RUNTIME,
  SEMRESATTRS_DEPLOYMENT_ENVIRONMENT: () => SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,
  SEMRESATTRS_DEVICE_ID: () => SEMRESATTRS_DEVICE_ID,
  SEMRESATTRS_DEVICE_MODEL_IDENTIFIER: () => SEMRESATTRS_DEVICE_MODEL_IDENTIFIER,
  SEMRESATTRS_DEVICE_MODEL_NAME: () => SEMRESATTRS_DEVICE_MODEL_NAME,
  SEMRESATTRS_FAAS_ID: () => SEMRESATTRS_FAAS_ID,
  SEMRESATTRS_FAAS_INSTANCE: () => SEMRESATTRS_FAAS_INSTANCE,
  SEMRESATTRS_FAAS_MAX_MEMORY: () => SEMRESATTRS_FAAS_MAX_MEMORY,
  SEMRESATTRS_FAAS_NAME: () => SEMRESATTRS_FAAS_NAME,
  SEMRESATTRS_FAAS_VERSION: () => SEMRESATTRS_FAAS_VERSION,
  SEMRESATTRS_HOST_ARCH: () => SEMRESATTRS_HOST_ARCH,
  SEMRESATTRS_HOST_ID: () => SEMRESATTRS_HOST_ID,
  SEMRESATTRS_HOST_IMAGE_ID: () => SEMRESATTRS_HOST_IMAGE_ID,
  SEMRESATTRS_HOST_IMAGE_NAME: () => SEMRESATTRS_HOST_IMAGE_NAME,
  SEMRESATTRS_HOST_IMAGE_VERSION: () => SEMRESATTRS_HOST_IMAGE_VERSION,
  SEMRESATTRS_HOST_NAME: () => SEMRESATTRS_HOST_NAME,
  SEMRESATTRS_HOST_TYPE: () => SEMRESATTRS_HOST_TYPE,
  SEMRESATTRS_K8S_CLUSTER_NAME: () => SEMRESATTRS_K8S_CLUSTER_NAME,
  SEMRESATTRS_K8S_CONTAINER_NAME: () => SEMRESATTRS_K8S_CONTAINER_NAME,
  SEMRESATTRS_K8S_CRONJOB_NAME: () => SEMRESATTRS_K8S_CRONJOB_NAME,
  SEMRESATTRS_K8S_CRONJOB_UID: () => SEMRESATTRS_K8S_CRONJOB_UID,
  SEMRESATTRS_K8S_DAEMONSET_NAME: () => SEMRESATTRS_K8S_DAEMONSET_NAME,
  SEMRESATTRS_K8S_DAEMONSET_UID: () => SEMRESATTRS_K8S_DAEMONSET_UID,
  SEMRESATTRS_K8S_DEPLOYMENT_NAME: () => SEMRESATTRS_K8S_DEPLOYMENT_NAME,
  SEMRESATTRS_K8S_DEPLOYMENT_UID: () => SEMRESATTRS_K8S_DEPLOYMENT_UID,
  SEMRESATTRS_K8S_JOB_NAME: () => SEMRESATTRS_K8S_JOB_NAME,
  SEMRESATTRS_K8S_JOB_UID: () => SEMRESATTRS_K8S_JOB_UID,
  SEMRESATTRS_K8S_NAMESPACE_NAME: () => SEMRESATTRS_K8S_NAMESPACE_NAME,
  SEMRESATTRS_K8S_NODE_NAME: () => SEMRESATTRS_K8S_NODE_NAME,
  SEMRESATTRS_K8S_NODE_UID: () => SEMRESATTRS_K8S_NODE_UID,
  SEMRESATTRS_K8S_POD_NAME: () => SEMRESATTRS_K8S_POD_NAME,
  SEMRESATTRS_K8S_POD_UID: () => SEMRESATTRS_K8S_POD_UID,
  SEMRESATTRS_K8S_REPLICASET_NAME: () => SEMRESATTRS_K8S_REPLICASET_NAME,
  SEMRESATTRS_K8S_REPLICASET_UID: () => SEMRESATTRS_K8S_REPLICASET_UID,
  SEMRESATTRS_K8S_STATEFULSET_NAME: () => SEMRESATTRS_K8S_STATEFULSET_NAME,
  SEMRESATTRS_K8S_STATEFULSET_UID: () => SEMRESATTRS_K8S_STATEFULSET_UID,
  SEMRESATTRS_OS_DESCRIPTION: () => SEMRESATTRS_OS_DESCRIPTION,
  SEMRESATTRS_OS_NAME: () => SEMRESATTRS_OS_NAME,
  SEMRESATTRS_OS_TYPE: () => SEMRESATTRS_OS_TYPE,
  SEMRESATTRS_OS_VERSION: () => SEMRESATTRS_OS_VERSION,
  SEMRESATTRS_PROCESS_COMMAND: () => SEMRESATTRS_PROCESS_COMMAND,
  SEMRESATTRS_PROCESS_COMMAND_ARGS: () => SEMRESATTRS_PROCESS_COMMAND_ARGS,
  SEMRESATTRS_PROCESS_COMMAND_LINE: () => SEMRESATTRS_PROCESS_COMMAND_LINE,
  SEMRESATTRS_PROCESS_EXECUTABLE_NAME: () => SEMRESATTRS_PROCESS_EXECUTABLE_NAME,
  SEMRESATTRS_PROCESS_EXECUTABLE_PATH: () => SEMRESATTRS_PROCESS_EXECUTABLE_PATH,
  SEMRESATTRS_PROCESS_OWNER: () => SEMRESATTRS_PROCESS_OWNER,
  SEMRESATTRS_PROCESS_PID: () => SEMRESATTRS_PROCESS_PID,
  SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION: () => SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION,
  SEMRESATTRS_PROCESS_RUNTIME_NAME: () => SEMRESATTRS_PROCESS_RUNTIME_NAME,
  SEMRESATTRS_PROCESS_RUNTIME_VERSION: () => SEMRESATTRS_PROCESS_RUNTIME_VERSION,
  SEMRESATTRS_SERVICE_INSTANCE_ID: () => SEMRESATTRS_SERVICE_INSTANCE_ID,
  SEMRESATTRS_SERVICE_NAME: () => SEMRESATTRS_SERVICE_NAME,
  SEMRESATTRS_SERVICE_NAMESPACE: () => SEMRESATTRS_SERVICE_NAMESPACE,
  SEMRESATTRS_SERVICE_VERSION: () => SEMRESATTRS_SERVICE_VERSION,
  SEMRESATTRS_TELEMETRY_AUTO_VERSION: () => SEMRESATTRS_TELEMETRY_AUTO_VERSION,
  SEMRESATTRS_TELEMETRY_SDK_LANGUAGE: () => SEMRESATTRS_TELEMETRY_SDK_LANGUAGE,
  SEMRESATTRS_TELEMETRY_SDK_NAME: () => SEMRESATTRS_TELEMETRY_SDK_NAME,
  SEMRESATTRS_TELEMETRY_SDK_VERSION: () => SEMRESATTRS_TELEMETRY_SDK_VERSION,
  SEMRESATTRS_WEBENGINE_DESCRIPTION: () => SEMRESATTRS_WEBENGINE_DESCRIPTION,
  SEMRESATTRS_WEBENGINE_NAME: () => SEMRESATTRS_WEBENGINE_NAME,
  SEMRESATTRS_WEBENGINE_VERSION: () => SEMRESATTRS_WEBENGINE_VERSION,
  SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN: () => SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN,
  SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE: () => SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE,
  SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT: () => SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT,
  SIGNALR_TRANSPORT_VALUE_LONG_POLLING: () => SIGNALR_TRANSPORT_VALUE_LONG_POLLING,
  SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS: () => SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS,
  SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS: () => SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS,
  SemanticAttributes: () => SemanticAttributes,
  SemanticResourceAttributes: () => SemanticResourceAttributes,
  TELEMETRYSDKLANGUAGEVALUES_CPP: () => TELEMETRYSDKLANGUAGEVALUES_CPP,
  TELEMETRYSDKLANGUAGEVALUES_DOTNET: () => TELEMETRYSDKLANGUAGEVALUES_DOTNET,
  TELEMETRYSDKLANGUAGEVALUES_ERLANG: () => TELEMETRYSDKLANGUAGEVALUES_ERLANG,
  TELEMETRYSDKLANGUAGEVALUES_GO: () => TELEMETRYSDKLANGUAGEVALUES_GO,
  TELEMETRYSDKLANGUAGEVALUES_JAVA: () => TELEMETRYSDKLANGUAGEVALUES_JAVA,
  TELEMETRYSDKLANGUAGEVALUES_NODEJS: () => TELEMETRYSDKLANGUAGEVALUES_NODEJS,
  TELEMETRYSDKLANGUAGEVALUES_PHP: () => TELEMETRYSDKLANGUAGEVALUES_PHP,
  TELEMETRYSDKLANGUAGEVALUES_PYTHON: () => TELEMETRYSDKLANGUAGEVALUES_PYTHON,
  TELEMETRYSDKLANGUAGEVALUES_RUBY: () => TELEMETRYSDKLANGUAGEVALUES_RUBY,
  TELEMETRYSDKLANGUAGEVALUES_WEBJS: () => TELEMETRYSDKLANGUAGEVALUES_WEBJS,
  TELEMETRY_SDK_LANGUAGE_VALUE_CPP: () => TELEMETRY_SDK_LANGUAGE_VALUE_CPP,
  TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET: () => TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET,
  TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG: () => TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG,
  TELEMETRY_SDK_LANGUAGE_VALUE_GO: () => TELEMETRY_SDK_LANGUAGE_VALUE_GO,
  TELEMETRY_SDK_LANGUAGE_VALUE_JAVA: () => TELEMETRY_SDK_LANGUAGE_VALUE_JAVA,
  TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS: () => TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,
  TELEMETRY_SDK_LANGUAGE_VALUE_PHP: () => TELEMETRY_SDK_LANGUAGE_VALUE_PHP,
  TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON: () => TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON,
  TELEMETRY_SDK_LANGUAGE_VALUE_RUBY: () => TELEMETRY_SDK_LANGUAGE_VALUE_RUBY,
  TELEMETRY_SDK_LANGUAGE_VALUE_RUST: () => TELEMETRY_SDK_LANGUAGE_VALUE_RUST,
  TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT: () => TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT,
  TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS: () => TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS,
  TelemetrySdkLanguageValues: () => TelemetrySdkLanguageValues
});
var init_esm = __esm({
  "node_modules/@opentelemetry/semantic-conventions/build/esm/index.js"() {
    init_esbuild_shims();
    init_trace();
    init_resource();
    init_stable_attributes();
    init_stable_metrics();
  }
});

// packages/core/dist/src/telemetry/constants.js
var SERVICE_NAME, EVENT_USER_PROMPT, EVENT_TOOL_CALL, EVENT_API_REQUEST, EVENT_API_ERROR, EVENT_API_CANCEL, EVENT_API_RESPONSE, EVENT_CLI_CONFIG, EVENT_EXTENSION_DISABLE, EVENT_EXTENSION_ENABLE, EVENT_EXTENSION_INSTALL, EVENT_EXTENSION_UNINSTALL, EVENT_FLASH_FALLBACK, EVENT_RIPGREP_FALLBACK, EVENT_NEXT_SPEAKER_CHECK, EVENT_SLASH_COMMAND, EVENT_IDE_CONNECTION, EVENT_CHAT_COMPRESSION, EVENT_CONTENT_RETRY, EVENT_CONTENT_RETRY_FAILURE, EVENT_CONVERSATION_FINISHED, EVENT_FILE_OPERATION, EVENT_MODEL_SLASH_COMMAND, EVENT_SUBAGENT_EXECUTION, EVENT_AUTH;
var init_constants = __esm({
  "packages/core/dist/src/telemetry/constants.js"() {
    "use strict";
    init_esbuild_shims();
    SERVICE_NAME = "qwen-code";
    EVENT_USER_PROMPT = "qwen-code.user_prompt";
    EVENT_TOOL_CALL = "qwen-code.tool_call";
    EVENT_API_REQUEST = "qwen-code.api_request";
    EVENT_API_ERROR = "qwen-code.api_error";
    EVENT_API_CANCEL = "qwen-code.api_cancel";
    EVENT_API_RESPONSE = "qwen-code.api_response";
    EVENT_CLI_CONFIG = "qwen-code.config";
    EVENT_EXTENSION_DISABLE = "qwen-code.extension_disable";
    EVENT_EXTENSION_ENABLE = "qwen-code.extension_enable";
    EVENT_EXTENSION_INSTALL = "qwen-code.extension_install";
    EVENT_EXTENSION_UNINSTALL = "qwen-code.extension_uninstall";
    EVENT_FLASH_FALLBACK = "qwen-code.flash_fallback";
    EVENT_RIPGREP_FALLBACK = "qwen-code.ripgrep_fallback";
    EVENT_NEXT_SPEAKER_CHECK = "qwen-code.next_speaker_check";
    EVENT_SLASH_COMMAND = "qwen-code.slash_command";
    EVENT_IDE_CONNECTION = "qwen-code.ide_connection";
    EVENT_CHAT_COMPRESSION = "qwen-code.chat_compression";
    EVENT_CONTENT_RETRY = "qwen-code.chat.content_retry";
    EVENT_CONTENT_RETRY_FAILURE = "qwen-code.chat.content_retry_failure";
    EVENT_CONVERSATION_FINISHED = "qwen-code.conversation_finished";
    EVENT_FILE_OPERATION = "qwen-code.file_operation";
    EVENT_MODEL_SLASH_COMMAND = "qwen-code.slash_command.model";
    EVENT_SUBAGENT_EXECUTION = "qwen-code.subagent_execution";
    EVENT_AUTH = "qwen-code.auth";
  }
});

// node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js
var _globalThis;
var init_globalThis = __esm({
  "node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js"() {
    init_esbuild_shims();
    _globalThis = typeof globalThis === "object" ? globalThis : globalThis;
  }
});

// node_modules/@opentelemetry/api/build/esm/platform/node/index.js
var init_node2 = __esm({
  "node_modules/@opentelemetry/api/build/esm/platform/node/index.js"() {
    init_esbuild_shims();
    init_globalThis();
  }
});

// node_modules/@opentelemetry/api/build/esm/platform/index.js
var init_platform = __esm({
  "node_modules/@opentelemetry/api/build/esm/platform/index.js"() {
    init_esbuild_shims();
    init_node2();
  }
});

// node_modules/@opentelemetry/api/build/esm/version.js
var VERSION;
var init_version2 = __esm({
  "node_modules/@opentelemetry/api/build/esm/version.js"() {
    init_esbuild_shims();
    VERSION = "1.9.0";
  }
});

// node_modules/@opentelemetry/api/build/esm/internal/semver.js
function _makeCompatibilityCheck(ownVersion) {
  var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
  var rejectedVersions = /* @__PURE__ */ new Set();
  var myVersionMatch = ownVersion.match(re);
  if (!myVersionMatch) {
    return function() {
      return false;
    };
  }
  var ownVersionParsed = {
    major: +myVersionMatch[1],
    minor: +myVersionMatch[2],
    patch: +myVersionMatch[3],
    prerelease: myVersionMatch[4]
  };
  if (ownVersionParsed.prerelease != null) {
    return /* @__PURE__ */ __name(function isExactmatch(globalVersion) {
      return globalVersion === ownVersion;
    }, "isExactmatch");
  }
  function _reject(v) {
    rejectedVersions.add(v);
    return false;
  }
  __name(_reject, "_reject");
  function _accept(v) {
    acceptedVersions.add(v);
    return true;
  }
  __name(_accept, "_accept");
  return /* @__PURE__ */ __name(function isCompatible2(globalVersion) {
    if (acceptedVersions.has(globalVersion)) {
      return true;
    }
    if (rejectedVersions.has(globalVersion)) {
      return false;
    }
    var globalVersionMatch = globalVersion.match(re);
    if (!globalVersionMatch) {
      return _reject(globalVersion);
    }
    var globalVersionParsed = {
      major: +globalVersionMatch[1],
      minor: +globalVersionMatch[2],
      patch: +globalVersionMatch[3],
      prerelease: globalVersionMatch[4]
    };
    if (globalVersionParsed.prerelease != null) {
      return _reject(globalVersion);
    }
    if (ownVersionParsed.major !== globalVersionParsed.major) {
      return _reject(globalVersion);
    }
    if (ownVersionParsed.major === 0) {
      if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) {
        return _accept(globalVersion);
      }
      return _reject(globalVersion);
    }
    if (ownVersionParsed.minor <= globalVersionParsed.minor) {
      return _accept(globalVersion);
    }
    return _reject(globalVersion);
  }, "isCompatible");
}
var re, isCompatible;
var init_semver = __esm({
  "node_modules/@opentelemetry/api/build/esm/internal/semver.js"() {
    init_esbuild_shims();
    init_version2();
    re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
    __name(_makeCompatibilityCheck, "_makeCompatibilityCheck");
    isCompatible = _makeCompatibilityCheck(VERSION);
  }
});

// node_modules/@opentelemetry/api/build/esm/internal/global-utils.js
function registerGlobal(type, instance, diag3, allowOverride) {
  var _a6;
  if (allowOverride === void 0) {
    allowOverride = false;
  }
  var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a6 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a6 !== void 0 ? _a6 : {
    version: VERSION
  };
  if (!allowOverride && api[type]) {
    var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
    diag3.error(err.stack || err.message);
    return false;
  }
  if (api.version !== VERSION) {
    var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION);
    diag3.error(err.stack || err.message);
    return false;
  }
  api[type] = instance;
  diag3.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION + ".");
  return true;
}
function getGlobal(type) {
  var _a6, _b2;
  var globalVersion = (_a6 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a6 === void 0 ? void 0 : _a6.version;
  if (!globalVersion || !isCompatible(globalVersion)) {
    return;
  }
  return (_b2 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b2 === void 0 ? void 0 : _b2[type];
}
function unregisterGlobal(type, diag3) {
  diag3.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION + ".");
  var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
  if (api) {
    delete api[type];
  }
}
var major, GLOBAL_OPENTELEMETRY_API_KEY, _global;
var init_global_utils = __esm({
  "node_modules/@opentelemetry/api/build/esm/internal/global-utils.js"() {
    init_esbuild_shims();
    init_platform();
    init_version2();
    init_semver();
    major = VERSION.split(".")[0];
    GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major);
    _global = _globalThis;
    __name(registerGlobal, "registerGlobal");
    __name(getGlobal, "getGlobal");
    __name(unregisterGlobal, "unregisterGlobal");
  }
});

// node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js
function logProxy(funcName, namespace, args) {
  var logger6 = getGlobal("diag");
  if (!logger6) {
    return;
  }
  args.unshift(namespace);
  return logger6[funcName].apply(logger6, __spreadArray([], __read(args), false));
}
var __read, __spreadArray, DiagComponentLogger;
var init_ComponentLogger = __esm({
  "node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js"() {
    init_esbuild_shims();
    init_global_utils();
    __read = function(o2, n2) {
      var m = typeof Symbol === "function" && o2[Symbol.iterator];
      if (!m) return o2;
      var i = m.call(o2), r3, ar = [], e2;
      try {
        while ((n2 === void 0 || n2-- > 0) && !(r3 = i.next()).done) ar.push(r3.value);
      } catch (error) {
        e2 = { error };
      } finally {
        try {
          if (r3 && !r3.done && (m = i["return"])) m.call(i);
        } finally {
          if (e2) throw e2.error;
        }
      }
      return ar;
    };
    __spreadArray = function(to, from, pack) {
      if (pack || arguments.length === 2) for (var i = 0, l2 = from.length, ar; i < l2; i++) {
        if (ar || !(i in from)) {
          if (!ar) ar = Array.prototype.slice.call(from, 0, i);
          ar[i] = from[i];
        }
      }
      return to.concat(ar || Array.prototype.slice.call(from));
    };
    DiagComponentLogger = /** @class */
    function() {
      function DiagComponentLogger2(props) {
        this._namespace = props.namespace || "DiagComponentLogger";
      }
      __name(DiagComponentLogger2, "DiagComponentLogger");
      DiagComponentLogger2.prototype.debug = function() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        return logProxy("debug", this._namespace, args);
      };
      DiagComponentLogger2.prototype.error = function() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        return logProxy("error", this._namespace, args);
      };
      DiagComponentLogger2.prototype.info = function() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        return logProxy("info", this._namespace, args);
      };
      DiagComponentLogger2.prototype.warn = function() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        return logProxy("warn", this._namespace, args);
      };
      DiagComponentLogger2.prototype.verbose = function() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        return logProxy("verbose", this._namespace, args);
      };
      return DiagComponentLogger2;
    }();
    __name(logProxy, "logProxy");
  }
});

// node_modules/@opentelemetry/api/build/esm/diag/types.js
var DiagLogLevel;
var init_types4 = __esm({
  "node_modules/@opentelemetry/api/build/esm/diag/types.js"() {
    init_esbuild_shims();
    (function(DiagLogLevel2) {
      DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE";
      DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR";
      DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN";
      DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO";
      DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG";
      DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE";
      DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL";
    })(DiagLogLevel || (DiagLogLevel = {}));
  }
});

// node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js
function createLogLevelDiagLogger(maxLevel, logger6) {
  if (maxLevel < DiagLogLevel.NONE) {
    maxLevel = DiagLogLevel.NONE;
  } else if (maxLevel > DiagLogLevel.ALL) {
    maxLevel = DiagLogLevel.ALL;
  }
  logger6 = logger6 || {};
  function _filterFunc(funcName, theLevel) {
    var theFunc = logger6[funcName];
    if (typeof theFunc === "function" && maxLevel >= theLevel) {
      return theFunc.bind(logger6);
    }
    return function() {
    };
  }
  __name(_filterFunc, "_filterFunc");
  return {
    error: _filterFunc("error", DiagLogLevel.ERROR),
    warn: _filterFunc("warn", DiagLogLevel.WARN),
    info: _filterFunc("info", DiagLogLevel.INFO),
    debug: _filterFunc("debug", DiagLogLevel.DEBUG),
    verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE)
  };
}
var init_logLevelLogger = __esm({
  "node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js"() {
    init_esbuild_shims();
    init_types4();
    __name(createLogLevelDiagLogger, "createLogLevelDiagLogger");
  }
});

// node_modules/@opentelemetry/api/build/esm/api/diag.js
var __read2, __spreadArray2, API_NAME, DiagAPI;
var init_diag = __esm({
  "node_modules/@opentelemetry/api/build/esm/api/diag.js"() {
    init_esbuild_shims();
    init_ComponentLogger();
    init_logLevelLogger();
    init_types4();
    init_global_utils();
    __read2 = function(o2, n2) {
      var m = typeof Symbol === "function" && o2[Symbol.iterator];
      if (!m) return o2;
      var i = m.call(o2), r3, ar = [], e2;
      try {
        while ((n2 === void 0 || n2-- > 0) && !(r3 = i.next()).done) ar.push(r3.value);
      } catch (error) {
        e2 = { error };
      } finally {
        try {
          if (r3 && !r3.done && (m = i["return"])) m.call(i);
        } finally {
          if (e2) throw e2.error;
        }
      }
      return ar;
    };
    __spreadArray2 = function(to, from, pack) {
      if (pack || arguments.length === 2) for (var i = 0, l2 = from.length, ar; i < l2; i++) {
        if (ar || !(i in from)) {
          if (!ar) ar = Array.prototype.slice.call(from, 0, i);
          ar[i] = from[i];
        }
      }
      return to.concat(ar || Array.prototype.slice.call(from));
    };
    API_NAME = "diag";
    DiagAPI = /** @class */
    function() {
      function DiagAPI2() {
        function _logProxy(funcName) {
          return function() {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments[_i];
            }
            var logger6 = getGlobal("diag");
            if (!logger6)
              return;
            return logger6[funcName].apply(logger6, __spreadArray2([], __read2(args), false));
          };
        }
        __name(_logProxy, "_logProxy");
        var self2 = this;
        var setLogger = /* @__PURE__ */ __name(function(logger6, optionsOrLogLevel) {
          var _a6, _b2, _c2;
          if (optionsOrLogLevel === void 0) {
            optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };
          }
          if (logger6 === self2) {
            var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
            self2.error((_a6 = err.stack) !== null && _a6 !== void 0 ? _a6 : err.message);
            return false;
          }
          if (typeof optionsOrLogLevel === "number") {
            optionsOrLogLevel = {
              logLevel: optionsOrLogLevel
            };
          }
          var oldLogger = getGlobal("diag");
          var newLogger = createLogLevelDiagLogger((_b2 = optionsOrLogLevel.logLevel) !== null && _b2 !== void 0 ? _b2 : DiagLogLevel.INFO, logger6);
          if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
            var stack = (_c2 = new Error().stack) !== null && _c2 !== void 0 ? _c2 : "<failed to generate stacktrace>";
            oldLogger.warn("Current logger will be overwritten from " + stack);
            newLogger.warn("Current logger will overwrite one already registered from " + stack);
          }
          return registerGlobal("diag", newLogger, self2, true);
        }, "setLogger");
        self2.setLogger = setLogger;
        self2.disable = function() {
          unregisterGlobal(API_NAME, self2);
        };
        self2.createComponentLogger = function(options2) {
          return new DiagComponentLogger(options2);
        };
        self2.verbose = _logProxy("verbose");
        self2.debug = _logProxy("debug");
        self2.info = _logProxy("info");
        self2.warn = _logProxy("warn");
        self2.error = _logProxy("error");
      }
      __name(DiagAPI2, "DiagAPI");
      DiagAPI2.instance = function() {
        if (!this._instance) {
          this._instance = new DiagAPI2();
        }
        return this._instance;
      };
      return DiagAPI2;
    }();
  }
});

// node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js
var __read3, __values2, BaggageImpl;
var init_baggage_impl = __esm({
  "node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js"() {
    init_esbuild_shims();
    __read3 = function(o2, n2) {
      var m = typeof Symbol === "function" && o2[Symbol.iterator];
      if (!m) return o2;
      var i = m.call(o2), r3, ar = [], e2;
      try {
        while ((n2 === void 0 || n2-- > 0) && !(r3 = i.next()).done) ar.push(r3.value);
      } catch (error) {
        e2 = { error };
      } finally {
        try {
          if (r3 && !r3.done && (m = i["return"])) m.call(i);
        } finally {
          if (e2) throw e2.error;
        }
      }
      return ar;
    };
    __values2 = function(o2) {
      var s2 = typeof Symbol === "function" && Symbol.iterator, m = s2 && o2[s2], i = 0;
      if (m) return m.call(o2);
      if (o2 && typeof o2.length === "number") return {
        next: /* @__PURE__ */ __name(function() {
          if (o2 && i >= o2.length) o2 = void 0;
          return { value: o2 && o2[i++], done: !o2 };
        }, "next")
      };
      throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined.");
    };
    BaggageImpl = /** @class */
    function() {
      function BaggageImpl2(entries) {
        this._entries = entries ? new Map(entries) : /* @__PURE__ */ new Map();
      }
      __name(BaggageImpl2, "BaggageImpl");
      BaggageImpl2.prototype.getEntry = function(key) {
        var entry = this._entries.get(key);
        if (!entry) {
          return void 0;
        }
        return Object.assign({}, entry);
      };
      BaggageImpl2.prototype.getAllEntries = function() {
        return Array.from(this._entries.entries()).map(function(_a6) {
          var _b2 = __read3(_a6, 2), k = _b2[0], v = _b2[1];
          return [k, v];
        });
      };
      BaggageImpl2.prototype.setEntry = function(key, entry) {
        var newBaggage = new BaggageImpl2(this._entries);
        newBaggage._entries.set(key, entry);
        return newBaggage;
      };
      BaggageImpl2.prototype.removeEntry = function(key) {
        var newBaggage = new BaggageImpl2(this._entries);
        newBaggage._entries.delete(key);
        return newBaggage;
      };
      BaggageImpl2.prototype.removeEntries = function() {
        var e_1, _a6;
        var keys = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          keys[_i] = arguments[_i];
        }
        var newBaggage = new BaggageImpl2(this._entries);
        try {
          for (var keys_1 = __values2(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
            var key = keys_1_1.value;
            newBaggage._entries.delete(key);
          }
        } catch (e_1_1) {
          e_1 = { error: e_1_1 };
        } finally {
          try {
            if (keys_1_1 && !keys_1_1.done && (_a6 = keys_1.return)) _a6.call(keys_1);
          } finally {
            if (e_1) throw e_1.error;
          }
        }
        return newBaggage;
      };
      BaggageImpl2.prototype.clear = function() {
        return new BaggageImpl2();
      };
      return BaggageImpl2;
    }();
  }
});

// node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.js
var baggageEntryMetadataSymbol;
var init_symbol = __esm({
  "node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.js"() {
    init_esbuild_shims();
    baggageEntryMetadataSymbol = Symbol("BaggageEntryMetadata");
  }
});

// node_modules/@opentelemetry/api/build/esm/baggage/utils.js
function createBaggage(entries) {
  if (entries === void 0) {
    entries = {};
  }
  return new BaggageImpl(new Map(Object.entries(entries)));
}
function baggageEntryMetadataFromString(str2) {
  if (typeof str2 !== "string") {
    diag.error("Cannot create baggage metadata from unknown type: " + typeof str2);
    str2 = "";
  }
  return {
    __TYPE__: baggageEntryMetadataSymbol,
    toString: /* @__PURE__ */ __name(function() {
      return str2;
    }, "toString")
  };
}
var diag;
var init_utils2 = __esm({
  "node_modules/@opentelemetry/api/build/esm/baggage/utils.js"() {
    init_esbuild_shims();
    init_diag();
    init_baggage_impl();
    init_symbol();
    diag = DiagAPI.instance();
    __name(createBaggage, "createBaggage");
    __name(baggageEntryMetadataFromString, "baggageEntryMetadataFromString");
  }
});

// node_modules/@opentelemetry/api/build/esm/context/context.js
function createContextKey(description) {
  return Symbol.for(description);
}
var BaseContext, ROOT_CONTEXT;
var init_context = __esm({
  "node_modules/@opentelemetry/api/build/esm/context/context.js"() {
    init_esbuild_shims();
    __name(createContextKey, "createContextKey");
    BaseContext = /** @class */
    /* @__PURE__ */ function() {
      function BaseContext2(parentContext) {
        var self2 = this;
        self2._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
        self2.getValue = function(key) {
          return self2._currentContext.get(key);
        };
        self2.setValue = function(key, value) {
          var context2 = new BaseContext2(self2._currentContext);
          context2._currentContext.set(key, value);
          return context2;
        };
        self2.deleteValue = function(key) {
          var context2 = new BaseContext2(self2._currentContext);
          context2._currentContext.delete(key);
          return context2;
        };
      }
      __name(BaseContext2, "BaseContext");
      return BaseContext2;
    }();
    ROOT_CONTEXT = new BaseContext();
  }
});

// node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.js
var consoleMap, DiagConsoleLogger;
var init_consoleLogger = __esm({
  "node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.js"() {
    init_esbuild_shims();
    consoleMap = [
      { n: "error", c: "error" },
      { n: "warn", c: "warn" },
      { n: "info", c: "info" },
      { n: "debug", c: "debug" },
      { n: "verbose", c: "trace" }
    ];
    DiagConsoleLogger = /** @class */
    /* @__PURE__ */ function() {
      function DiagConsoleLogger2() {
        function _consoleFunc(funcName) {
          return function() {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments[_i];
            }
            if (console) {
              var theFunc = console[funcName];
              if (typeof theFunc !== "function") {
                theFunc = console.log;
              }
              if (typeof theFunc === "function") {
                return theFunc.apply(console, args);
              }
            }
          };
        }
        __name(_consoleFunc, "_consoleFunc");
        for (var i = 0; i < consoleMap.length; i++) {
          this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c);
        }
      }
      __name(DiagConsoleLogger2, "DiagConsoleLogger");
      return DiagConsoleLogger2;
    }();
  }
});

// node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js
function createNoopMeter() {
  return NOOP_METER;
}
var __extends, NoopMeter, NoopMetric, NoopCounterMetric, NoopUpDownCounterMetric, NoopGaugeMetric, NoopHistogramMetric, NoopObservableMetric, NoopObservableCounterMetric, NoopObservableGaugeMetric, NoopObservableUpDownCounterMetric, NOOP_METER, NOOP_COUNTER_METRIC, NOOP_GAUGE_METRIC, NOOP_HISTOGRAM_METRIC, NOOP_UP_DOWN_COUNTER_METRIC, NOOP_OBSERVABLE_COUNTER_METRIC, NOOP_OBSERVABLE_GAUGE_METRIC, NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;
var init_NoopMeter = __esm({
  "node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js"() {
    init_esbuild_shims();
    __extends = /* @__PURE__ */ function() {
      var extendStatics = /* @__PURE__ */ __name(function(d, b) {
        extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
          d2.__proto__ = b2;
        } || function(d2, b2) {
          for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
        };
        return extendStatics(d, b);
      }, "extendStatics");
      return function(d, b) {
        if (typeof b !== "function" && b !== null)
          throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() {
          this.constructor = d;
        }
        __name(__, "__");
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
      };
    }();
    NoopMeter = /** @class */
    function() {
      function NoopMeter2() {
      }
      __name(NoopMeter2, "NoopMeter");
      NoopMeter2.prototype.createGauge = function(_name, _options) {
        return NOOP_GAUGE_METRIC;
      };
      NoopMeter2.prototype.createHistogram = function(_name, _options) {
        return NOOP_HISTOGRAM_METRIC;
      };
      NoopMeter2.prototype.createCounter = function(_name, _options) {
        return NOOP_COUNTER_METRIC;
      };
      NoopMeter2.prototype.createUpDownCounter = function(_name, _options) {
        return NOOP_UP_DOWN_COUNTER_METRIC;
      };
      NoopMeter2.prototype.createObservableGauge = function(_name, _options) {
        return NOOP_OBSERVABLE_GAUGE_METRIC;
      };
      NoopMeter2.prototype.createObservableCounter = function(_name, _options) {
        return NOOP_OBSERVABLE_COUNTER_METRIC;
      };
      NoopMeter2.prototype.createObservableUpDownCounter = function(_name, _options) {
        return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;
      };
      NoopMeter2.prototype.addBatchObservableCallback = function(_callback, _observables) {
      };
      NoopMeter2.prototype.removeBatchObservableCallback = function(_callback) {
      };
      return NoopMeter2;
    }();
    NoopMetric = /** @class */
    /* @__PURE__ */ function() {
      function NoopMetric2() {
      }
      __name(NoopMetric2, "NoopMetric");
      return NoopMetric2;
    }();
    NoopCounterMetric = /** @class */
    function(_super) {
      __extends(NoopCounterMetric2, _super);
      function NoopCounterMetric2() {
        return _super !== null && _super.apply(this, arguments) || this;
      }
      __name(NoopCounterMetric2, "NoopCounterMetric");
      NoopCounterMetric2.prototype.add = function(_value, _attributes) {
      };
      return NoopCounterMetric2;
    }(NoopMetric);
    NoopUpDownCounterMetric = /** @class */
    function(_super) {
      __extends(NoopUpDownCounterMetric2, _super);
      function NoopUpDownCounterMetric2() {
        return _super !== null && _super.apply(this, arguments) || this;
      }
      __name(NoopUpDownCounterMetric2, "NoopUpDownCounterMetric");
      NoopUpDownCounterMetric2.prototype.add = function(_value, _attributes) {
      };
      return NoopUpDownCounterMetric2;
    }(NoopMetric);
    NoopGaugeMetric = /** @class */
    function(_super) {
      __extends(NoopGaugeMetric2, _super);
      function NoopGaugeMetric2() {
        return _super !== null && _super.apply(this, arguments) || this;
      }
      __name(NoopGaugeMetric2, "NoopGaugeMetric");
      NoopGaugeMetric2.prototype.record = function(_value, _attributes) {
      };
      return NoopGaugeMetric2;
    }(NoopMetric);
    NoopHistogramMetric = /** @class */
    function(_super) {
      __extends(NoopHistogramMetric2, _super);
      function NoopHistogramMetric2() {
        return _super !== null && _super.apply(this, arguments) || this;
      }
      __name(NoopHistogramMetric2, "NoopHistogramMetric");
      NoopHistogramMetric2.prototype.record = function(_value, _attributes) {
      };
      return NoopHistogramMetric2;
    }(NoopMetric);
    NoopObservableMetric = /** @class */
    function() {
      function NoopObservableMetric2() {
      }
      __name(NoopObservableMetric2, "NoopObservableMetric");
      NoopObservableMetric2.prototype.addCallback = function(_callback) {
      };
      NoopObservableMetric2.prototype.removeCallback = function(_callback) {
      };
      return NoopObservableMetric2;
    }();
    NoopObservableCounterMetric = /** @class */
    function(_super) {
      __extends(NoopObservableCounterMetric2, _super);
      function NoopObservableCounterMetric2() {
        return _super !== null && _super.apply(this, arguments) || this;
      }
      __name(NoopObservableCounterMetric2, "NoopObservableCounterMetric");
      return NoopObservableCounterMetric2;
    }(NoopObservableMetric);
    NoopObservableGaugeMetric = /** @class */
    function(_super) {
      __extends(NoopObservableGaugeMetric2, _super);
      function NoopObservableGaugeMetric2() {
        return _super !== null && _super.apply(this, arguments) || this;
      }
      __name(NoopObservableGaugeMetric2, "NoopObservableGaugeMetric");
      return NoopObservableGaugeMetric2;
    }(NoopObservableMetric);
    NoopObservableUpDownCounterMetric = /** @class */
    function(_super) {
      __extends(NoopObservableUpDownCounterMetric2, _super);
      function NoopObservableUpDownCounterMetric2() {
        return _super !== null && _super.apply(this, arguments) || this;
      }
      __name(NoopObservableUpDownCounterMetric2, "NoopObservableUpDownCounterMetric");
      return NoopObservableUpDownCounterMetric2;
    }(NoopObservableMetric);
    NOOP_METER = new NoopMeter();
    NOOP_COUNTER_METRIC = new NoopCounterMetric();
    NOOP_GAUGE_METRIC = new NoopGaugeMetric();
    NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric();
    NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric();
    NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric();
    NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric();
    NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric();
    __name(createNoopMeter, "createNoopMeter");
  }
});

// node_modules/@opentelemetry/api/build/esm/metrics/Metric.js
var ValueType;
var init_Metric = __esm({
  "node_modules/@opentelemetry/api/build/esm/metrics/Metric.js"() {
    init_esbuild_shims();
    (function(ValueType2) {
      ValueType2[ValueType2["INT"] = 0] = "INT";
      ValueType2[ValueType2["DOUBLE"] = 1] = "DOUBLE";
    })(ValueType || (ValueType = {}));
  }
});

// node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js
var defaultTextMapGetter, defaultTextMapSetter;
var init_TextMapPropagator = __esm({
  "node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js"() {
    init_esbuild_shims();
    defaultTextMapGetter = {
      get: /* @__PURE__ */ __name(function(carrier, key) {
        if (carrier == null) {
          return void 0;
        }
        return carrier[key];
      }, "get"),
      keys: /* @__PURE__ */ __name(function(carrier) {
        if (carrier == null) {
          return [];
        }
        return Object.keys(carrier);
      }, "keys")
    };
    defaultTextMapSetter = {
      set: /* @__PURE__ */ __name(function(carrier, key, value) {
        if (carrier == null) {
          return;
        }
        carrier[key] = value;
      }, "set")
    };
  }
});

// node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js
var __read4, __spreadArray3, NoopContextManager;
var init_NoopContextManager = __esm({
  "node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js"() {
    init_esbuild_shims();
    init_context();
    __read4 = function(o2, n2) {
      var m = typeof Symbol === "function" && o2[Symbol.iterator];
      if (!m) return o2;
      var i = m.call(o2), r3, ar = [], e2;
      try {
        while ((n2 === void 0 || n2-- > 0) && !(r3 = i.next()).done) ar.push(r3.value);
      } catch (error) {
        e2 = { error };
      } finally {
        try {
          if (r3 && !r3.done && (m = i["return"])) m.call(i);
        } finally {
          if (e2) throw e2.error;
        }
      }
      return ar;
    };
    __spreadArray3 = function(to, from, pack) {
      if (pack || arguments.length === 2) for (var i = 0, l2 = from.length, ar; i < l2; i++) {
        if (ar || !(i in from)) {
          if (!ar) ar = Array.prototype.slice.call(from, 0, i);
          ar[i] = from[i];
        }
      }
      return to.concat(ar || Array.prototype.slice.call(from));
    };
    NoopContextManager = /** @class */
    function() {
      function NoopContextManager2() {
      }
      __name(NoopContextManager2, "NoopContextManager");
      NoopContextManager2.prototype.active = function() {
        return ROOT_CONTEXT;
      };
      NoopContextManager2.prototype.with = function(_context, fn, thisArg) {
        var args = [];
        for (var _i = 3; _i < arguments.length; _i++) {
          args[_i - 3] = arguments[_i];
        }
        return fn.call.apply(fn, __spreadArray3([thisArg], __read4(args), false));
      };
      NoopContextManager2.prototype.bind = function(_context, target) {
        return target;
      };
      NoopContextManager2.prototype.enable = function() {
        return this;
      };
      NoopContextManager2.prototype.disable = function() {
        return this;
      };
      return NoopContextManager2;
    }();
  }
});

// node_modules/@opentelemetry/api/build/esm/api/context.js
var __read5, __spreadArray4, API_NAME2, NOOP_CONTEXT_MANAGER, ContextAPI;
var init_context2 = __esm({
  "node_modules/@opentelemetry/api/build/esm/api/context.js"() {
    init_esbuild_shims();
    init_NoopContextManager();
    init_global_utils();
    init_diag();
    __read5 = function(o2, n2) {
      var m = typeof Symbol === "function" && o2[Symbol.iterator];
      if (!m) return o2;
      var i = m.call(o2), r3, ar = [], e2;
      try {
        while ((n2 === void 0 || n2-- > 0) && !(r3 = i.next()).done) ar.push(r3.value);
      } catch (error) {
        e2 = { error };
      } finally {
        try {
          if (r3 && !r3.done && (m = i["return"])) m.call(i);
        } finally {
          if (e2) throw e2.error;
        }
      }
      return ar;
    };
    __spreadArray4 = function(to, from, pack) {
      if (pack || arguments.length === 2) for (var i = 0, l2 = from.length, ar; i < l2; i++) {
        if (ar || !(i in from)) {
          if (!ar) ar = Array.prototype.slice.call(from, 0, i);
          ar[i] = from[i];
        }
      }
      return to.concat(ar || Array.prototype.slice.call(from));
    };
    API_NAME2 = "context";
    NOOP_CONTEXT_MANAGER = new NoopContextManager();
    ContextAPI = /** @class */
    function() {
      function ContextAPI2() {
      }
      __name(ContextAPI2, "ContextAPI");
      ContextAPI2.getInstance = function() {
        if (!this._instance) {
          this._instance = new ContextAPI2();
        }
        return this._instance;
      };
      ContextAPI2.prototype.setGlobalContextManager = function(contextManager) {
        return registerGlobal(API_NAME2, contextManager, DiagAPI.instance());
      };
      ContextAPI2.prototype.active = function() {
        return this._getContextManager().active();
      };
      ContextAPI2.prototype.with = function(context2, fn, thisArg) {
        var _a6;
        var args = [];
        for (var _i = 3; _i < arguments.length; _i++) {
          args[_i - 3] = arguments[_i];
        }
        return (_a6 = this._getContextManager()).with.apply(_a6, __spreadArray4([context2, fn, thisArg], __read5(args), false));
      };
      ContextAPI2.prototype.bind = function(context2, target) {
        return this._getContextManager().bind(context2, target);
      };
      ContextAPI2.prototype._getContextManager = function() {
        return getGlobal(API_NAME2) || NOOP_CONTEXT_MANAGER;
      };
      ContextAPI2.prototype.disable = function() {
        this._getContextManager().disable();
        unregisterGlobal(API_NAME2, DiagAPI.instance());
      };
      return ContextAPI2;
    }();
  }
});

// node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js
var TraceFlags;
var init_trace_flags = __esm({
  "node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js"() {
    init_esbuild_shims();
    (function(TraceFlags2) {
      TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE";
      TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED";
    })(TraceFlags || (TraceFlags = {}));
  }
});

// node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js
var INVALID_SPANID, INVALID_TRACEID, INVALID_SPAN_CONTEXT;
var init_invalid_span_constants = __esm({
  "node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js"() {
    init_esbuild_shims();
    init_trace_flags();
    INVALID_SPANID = "0000000000000000";
    INVALID_TRACEID = "00000000000000000000000000000000";
    INVALID_SPAN_CONTEXT = {
      traceId: INVALID_TRACEID,
      spanId: INVALID_SPANID,
      traceFlags: TraceFlags.NONE
    };
  }
});

// node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js
var NonRecordingSpan;
var init_NonRecordingSpan = __esm({
  "node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js"() {
    init_esbuild_shims();
    init_invalid_span_constants();
    NonRecordingSpan = /** @class */
    function() {
      function NonRecordingSpan2(_spanContext) {
        if (_spanContext === void 0) {
          _spanContext = INVALID_SPAN_CONTEXT;
        }
        this._spanContext = _spanContext;
      }
      __name(NonRecordingSpan2, "NonRecordingSpan");
      NonRecordingSpan2.prototype.spanContext = function() {
        return this._spanContext;
      };
      NonRecordingSpan2.prototype.setAttribute = function(_key, _value) {
        return this;
      };
      NonRecordingSpan2.prototype.setAttributes = function(_attributes) {
        return this;
      };
      NonRecordingSpan2.prototype.addEvent = function(_name, _attributes) {
        return this;
      };
      NonRecordingSpan2.prototype.addLink = function(_link) {
        return this;
      };
      NonRecordingSpan2.prototype.addLinks = function(_links) {
        return this;
      };
      NonRecordingSpan2.prototype.setStatus = function(_status) {
        return this;
      };
      NonRecordingSpan2.prototype.updateName = function(_name) {
        return this;
      };
      NonRecordingSpan2.prototype.end = function(_endTime) {
      };
      NonRecordingSpan2.prototype.isRecording = function() {
        return false;
      };
      NonRecordingSpan2.prototype.recordException = function(_exception, _time) {
      };
      return NonRecordingSpan2;
    }();
  }
});

// node_modules/@opentelemetry/api/build/esm/trace/context-utils.js
function getSpan(context2) {
  return context2.getValue(SPAN_KEY) || void 0;
}
function getActiveSpan() {
  return getSpan(ContextAPI.getInstance().active());
}
function setSpan(context2, span) {
  return context2.setValue(SPAN_KEY, span);
}
function deleteSpan(context2) {
  return context2.deleteValue(SPAN_KEY);
}
function setSpanContext(context2, spanContext) {
  return setSpan(context2, new NonRecordingSpan(spanContext));
}
function getSpanContext(context2) {
  var _a6;
  return (_a6 = getSpan(context2)) === null || _a6 === void 0 ? void 0 : _a6.spanContext();
}
var SPAN_KEY;
var init_context_utils = __esm({
  "node_modules/@opentelemetry/api/build/esm/trace/context-utils.js"() {
    init_esbuild_shims();
    init_context();
    init_NonRecordingSpan();
    init_context2();
    SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN");
    __name(getSpan, "getSpan");
    __name(getActiveSpan, "getActiveSpan");
    __name(setSpan, "setSpan");
    __name(deleteSpan, "deleteSpan");
    __name(setSpanContext, "setSpanContext");
    __name(getSpanContext, "getSpanContext");
  }
});

// node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js
function isValidTraceId(traceId) {
  return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;
}
function isValidSpanId(spanId) {
  return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;
}
function isSpanContextValid(spanContext) {
  return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId);
}
function wrapSpanContext(spanContext) {
  return new NonRecordingSpan(spanContext);
}
var VALID_TRACEID_REGEX, VALID_SPANID_REGEX;
var init_spancontext_utils = __esm({
  "node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js"() {
    init_esbuild_shims();
    init_invalid_span_constants();
    init_NonRecordingSpan();
    VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;
    VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;
    __name(isValidTraceId, "isValidTraceId");
    __name(isValidSpanId, "isValidSpanId");
    __name(isSpanContextValid, "isSpanContextValid");
    __name(wrapSpanContext, "wrapSpanContext");
  }
});

// node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js
function isSpanContext(spanContext) {
  return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number";
}
var contextApi, NoopTracer;
var init_NoopTracer = __esm({
  "node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js"() {
    init_esbuild_shims();
    init_context2();
    init_context_utils();
    init_NonRecordingSpan();
    init_spancontext_utils();
    contextApi = ContextAPI.getInstance();
    NoopTracer = /** @class */
    function() {
      function NoopTracer2() {
      }
      __name(NoopTracer2, "NoopTracer");
      NoopTracer2.prototype.startSpan = function(name3, options2, context2) {
        if (context2 === void 0) {
          context2 = contextApi.active();
        }
        var root = Boolean(options2 === null || options2 === void 0 ? void 0 : options2.root);
        if (root) {
          return new NonRecordingSpan();
        }
        var parentFromContext = context2 && getSpanContext(context2);
        if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) {
          return new NonRecordingSpan(parentFromContext);
        } else {
          return new NonRecordingSpan();
        }
      };
      NoopTracer2.prototype.startActiveSpan = function(name3, arg2, arg3, arg4) {
        var opts;
        var ctx;
        var fn;
        if (arguments.length < 2) {
          return;
        } else if (arguments.length === 2) {
          fn = arg2;
        } else if (arguments.length === 3) {
          opts = arg2;
          fn = arg3;
        } else {
          opts = arg2;
          ctx = arg3;
          fn = arg4;
        }
        var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();
        var span = this.startSpan(name3, opts, parentContext);
        var contextWithSpanSet = setSpan(parentContext, span);
        return contextApi.with(contextWithSpanSet, fn, void 0, span);
      };
      return NoopTracer2;
    }();
    __name(isSpanContext, "isSpanContext");
  }
});

// node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js
var NOOP_TRACER, ProxyTracer;
var init_ProxyTracer = __esm({
  "node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js"() {
    init_esbuild_shims();
    init_NoopTracer();
    NOOP_TRACER = new NoopTracer();
    ProxyTracer = /** @class */
    function() {
      function ProxyTracer2(_provider, name3, version2, options2) {
        this._provider = _provider;
        this.name = name3;
        this.version = version2;
        this.options = options2;
      }
      __name(ProxyTracer2, "ProxyTracer");
      ProxyTracer2.prototype.startSpan = function(name3, options2, context2) {
        return this._getTracer().startSpan(name3, options2, context2);
      };
      ProxyTracer2.prototype.startActiveSpan = function(_name, _options, _context, _fn) {
        var tracer = this._getTracer();
        return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
      };
      ProxyTracer2.prototype._getTracer = function() {
        if (this._delegate) {
          return this._delegate;
        }
        var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
        if (!tracer) {
          return NOOP_TRACER;
        }
        this._delegate = tracer;
        return this._delegate;
      };
      return ProxyTracer2;
    }();
  }
});

// node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js
var NoopTracerProvider;
var init_NoopTracerProvider = __esm({
  "node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js"() {
    init_esbuild_shims();
    init_NoopTracer();
    NoopTracerProvider = /** @class */
    function() {
      function NoopTracerProvider2() {
      }
      __name(NoopTracerProvider2, "NoopTracerProvider");
      NoopTracerProvider2.prototype.getTracer = function(_name, _version, _options) {
        return new NoopTracer();
      };
      return NoopTracerProvider2;
    }();
  }
});

// node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js
var NOOP_TRACER_PROVIDER, ProxyTracerProvider;
var init_ProxyTracerProvider = __esm({
  "node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js"() {
    init_esbuild_shims();
    init_ProxyTracer();
    init_NoopTracerProvider();
    NOOP_TRACER_PROVIDER = new NoopTracerProvider();
    ProxyTracerProvider = /** @class */
    function() {
      function ProxyTracerProvider2() {
      }
      __name(ProxyTracerProvider2, "ProxyTracerProvider");
      ProxyTracerProvider2.prototype.getTracer = function(name3, version2, options2) {
        var _a6;
        return (_a6 = this.getDelegateTracer(name3, version2, options2)) !== null && _a6 !== void 0 ? _a6 : new ProxyTracer(this, name3, version2, options2);
      };
      ProxyTracerProvider2.prototype.getDelegate = function() {
        var _a6;
        return (_a6 = this._delegate) !== null && _a6 !== void 0 ? _a6 : NOOP_TRACER_PROVIDER;
      };
      ProxyTracerProvider2.prototype.setDelegate = function(delegate) {
        this._delegate = delegate;
      };
      ProxyTracerProvider2.prototype.getDelegateTracer = function(name3, version2, options2) {
        var _a6;
        return (_a6 = this._delegate) === null || _a6 === void 0 ? void 0 : _a6.getTracer(name3, version2, options2);
      };
      return ProxyTracerProvider2;
    }();
  }
});

// node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.js
var SamplingDecision;
var init_SamplingResult = __esm({
  "node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.js"() {
    init_esbuild_shims();
    (function(SamplingDecision2) {
      SamplingDecision2[SamplingDecision2["NOT_RECORD"] = 0] = "NOT_RECORD";
      SamplingDecision2[SamplingDecision2["RECORD"] = 1] = "RECORD";
      SamplingDecision2[SamplingDecision2["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED";
    })(SamplingDecision || (SamplingDecision = {}));
  }
});

// node_modules/@opentelemetry/api/build/esm/trace/span_kind.js
var SpanKind;
var init_span_kind = __esm({
  "node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"() {
    init_esbuild_shims();
    (function(SpanKind2) {
      SpanKind2[SpanKind2["INTERNAL"] = 0] = "INTERNAL";
      SpanKind2[SpanKind2["SERVER"] = 1] = "SERVER";
      SpanKind2[SpanKind2["CLIENT"] = 2] = "CLIENT";
      SpanKind2[SpanKind2["PRODUCER"] = 3] = "PRODUCER";
      SpanKind2[SpanKind2["CONSUMER"] = 4] = "CONSUMER";
    })(SpanKind || (SpanKind = {}));
  }
});

// node_modules/@opentelemetry/api/build/esm/trace/status.js
var SpanStatusCode;
var init_status = __esm({
  "node_modules/@opentelemetry/api/build/esm/trace/status.js"() {
    init_esbuild_shims();
    (function(SpanStatusCode2) {
      SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET";
      SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK";
      SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR";
    })(SpanStatusCode || (SpanStatusCode = {}));
  }
});

// node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.js
function validateKey(key) {
  return VALID_KEY_REGEX.test(key);
}
function validateValue(value) {
  return VALID_VALUE_BASE_REGEX.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value);
}
var VALID_KEY_CHAR_RANGE, VALID_KEY, VALID_VENDOR_KEY, VALID_KEY_REGEX, VALID_VALUE_BASE_REGEX, INVALID_VALUE_COMMA_EQUAL_REGEX;
var init_tracestate_validators = __esm({
  "node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.js"() {
    init_esbuild_shims();
    VALID_KEY_CHAR_RANGE = "[_0-9a-z-*/]";
    VALID_KEY = "[a-z]" + VALID_KEY_CHAR_RANGE + "{0,255}";
    VALID_VENDOR_KEY = "[a-z0-9]" + VALID_KEY_CHAR_RANGE + "{0,240}@[a-z]" + VALID_KEY_CHAR_RANGE + "{0,13}";
    VALID_KEY_REGEX = new RegExp("^(?:" + VALID_KEY + "|" + VALID_VENDOR_KEY + ")$");
    VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;
    INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;
    __name(validateKey, "validateKey");
    __name(validateValue, "validateValue");
  }
});

// node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.js
var MAX_TRACE_STATE_ITEMS, MAX_TRACE_STATE_LEN, LIST_MEMBERS_SEPARATOR, LIST_MEMBER_KEY_VALUE_SPLITTER, TraceStateImpl;
var init_tracestate_impl = __esm({
  "node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.js"() {
    init_esbuild_shims();
    init_tracestate_validators();
    MAX_TRACE_STATE_ITEMS = 32;
    MAX_TRACE_STATE_LEN = 512;
    LIST_MEMBERS_SEPARATOR = ",";
    LIST_MEMBER_KEY_VALUE_SPLITTER = "=";
    TraceStateImpl = /** @class */
    function() {
      function TraceStateImpl2(rawTraceState) {
        this._internalState = /* @__PURE__ */ new Map();
        if (rawTraceState)
          this._parse(rawTraceState);
      }
      __name(TraceStateImpl2, "TraceStateImpl");
      TraceStateImpl2.prototype.set = function(key, value) {
        var traceState = this._clone();
        if (traceState._internalState.has(key)) {
          traceState._internalState.delete(key);
        }
        traceState._internalState.set(key, value);
        return traceState;
      };
      TraceStateImpl2.prototype.unset = function(key) {
        var traceState = this._clone();
        traceState._internalState.delete(key);
        return traceState;
      };
      TraceStateImpl2.prototype.get = function(key) {
        return this._internalState.get(key);
      };
      TraceStateImpl2.prototype.serialize = function() {
        var _this = this;
        return this._keys().reduce(function(agg, key) {
          agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + _this.get(key));
          return agg;
        }, []).join(LIST_MEMBERS_SEPARATOR);
      };
      TraceStateImpl2.prototype._parse = function(rawTraceState) {
        if (rawTraceState.length > MAX_TRACE_STATE_LEN)
          return;
        this._internalState = rawTraceState.split(LIST_MEMBERS_SEPARATOR).reverse().reduce(function(agg, part) {
          var listMember = part.trim();
          var i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);
          if (i !== -1) {
            var key = listMember.slice(0, i);
            var value = listMember.slice(i + 1, part.length);
            if (validateKey(key) && validateValue(value)) {
              agg.set(key, value);
            } else {
            }
          }
          return agg;
        }, /* @__PURE__ */ new Map());
        if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {
          this._internalState = new Map(Array.from(this._internalState.entries()).reverse().slice(0, MAX_TRACE_STATE_ITEMS));
        }
      };
      TraceStateImpl2.prototype._keys = function() {
        return Array.from(this._internalState.keys()).reverse();
      };
      TraceStateImpl2.prototype._clone = function() {
        var traceState = new TraceStateImpl2();
        traceState._internalState = new Map(this._internalState);
        return traceState;
      };
      return TraceStateImpl2;
    }();
  }
});

// node_modules/@opentelemetry/api/build/esm/trace/internal/utils.js
function createTraceState(rawTraceState) {
  return new TraceStateImpl(rawTraceState);
}
var init_utils3 = __esm({
  "node_modules/@opentelemetry/api/build/esm/trace/internal/utils.js"() {
    init_esbuild_shims();
    init_tracestate_impl();
    __name(createTraceState, "createTraceState");
  }
});

// node_modules/@opentelemetry/api/build/esm/context-api.js
var context;
var init_context_api = __esm({
  "node_modules/@opentelemetry/api/build/esm/context-api.js"() {
    init_esbuild_shims();
    init_context2();
    context = ContextAPI.getInstance();
  }
});

// node_modules/@opentelemetry/api/build/esm/diag-api.js
var diag2;
var init_diag_api = __esm({
  "node_modules/@opentelemetry/api/build/esm/diag-api.js"() {
    init_esbuild_shims();
    init_diag();
    diag2 = DiagAPI.instance();
  }
});

// node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js
var NoopMeterProvider, NOOP_METER_PROVIDER;
var init_NoopMeterProvider = __esm({
  "node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js"() {
    init_esbuild_shims();
    init_NoopMeter();
    NoopMeterProvider = /** @class */
    function() {
      function NoopMeterProvider2() {
      }
      __name(NoopMeterProvider2, "NoopMeterProvider");
      NoopMeterProvider2.prototype.getMeter = function(_name, _version, _options) {
        return NOOP_METER;
      };
      return NoopMeterProvider2;
    }();
    NOOP_METER_PROVIDER = new NoopMeterProvider();
  }
});

// node_modules/@opentelemetry/api/build/esm/api/metrics.js
var API_NAME3, MetricsAPI;
var init_metrics = __esm({
  "node_modules/@opentelemetry/api/build/esm/api/metrics.js"() {
    init_esbuild_shims();
    init_NoopMeterProvider();
    init_global_utils();
    init_diag();
    API_NAME3 = "metrics";
    MetricsAPI = /** @class */
    function() {
      function MetricsAPI2() {
      }
      __name(MetricsAPI2, "MetricsAPI");
      MetricsAPI2.getInstance = function() {
        if (!this._instance) {
          this._instance = new MetricsAPI2();
        }
        return this._instance;
      };
      MetricsAPI2.prototype.setGlobalMeterProvider = function(provider) {
        return registerGlobal(API_NAME3, provider, DiagAPI.instance());
      };
      MetricsAPI2.prototype.getMeterProvider = function() {
        return getGlobal(API_NAME3) || NOOP_METER_PROVIDER;
      };
      MetricsAPI2.prototype.getMeter = function(name3, version2, options2) {
        return this.getMeterProvider().getMeter(name3, version2, options2);
      };
      MetricsAPI2.prototype.disable = function() {
        unregisterGlobal(API_NAME3, DiagAPI.instance());
      };
      return MetricsAPI2;
    }();
  }
});

// node_modules/@opentelemetry/api/build/esm/metrics-api.js
var metrics;
var init_metrics_api = __esm({
  "node_modules/@opentelemetry/api/build/esm/metrics-api.js"() {
    init_esbuild_shims();
    init_metrics();
    metrics = MetricsAPI.getInstance();
  }
});

// node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js
var NoopTextMapPropagator;
var init_NoopTextMapPropagator = __esm({
  "node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js"() {
    init_esbuild_shims();
    NoopTextMapPropagator = /** @class */
    function() {
      function NoopTextMapPropagator2() {
      }
      __name(NoopTextMapPropagator2, "NoopTextMapPropagator");
      NoopTextMapPropagator2.prototype.inject = function(_context, _carrier) {
      };
      NoopTextMapPropagator2.prototype.extract = function(context2, _carrier) {
        return context2;
      };
      NoopTextMapPropagator2.prototype.fields = function() {
        return [];
      };
      return NoopTextMapPropagator2;
    }();
  }
});

// node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js
function getBaggage(context2) {
  return context2.getValue(BAGGAGE_KEY) || void 0;
}
function getActiveBaggage() {
  return getBaggage(ContextAPI.getInstance().active());
}
function setBaggage(context2, baggage) {
  return context2.setValue(BAGGAGE_KEY, baggage);
}
function deleteBaggage(context2) {
  return context2.deleteValue(BAGGAGE_KEY);
}
var BAGGAGE_KEY;
var init_context_helpers = __esm({
  "node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js"() {
    init_esbuild_shims();
    init_context2();
    init_context();
    BAGGAGE_KEY = createContextKey("OpenTelemetry Baggage Key");
    __name(getBaggage, "getBaggage");
    __name(getActiveBaggage, "getActiveBaggage");
    __name(setBaggage, "setBaggage");
    __name(deleteBaggage, "deleteBaggage");
  }
});

// node_modules/@opentelemetry/api/build/esm/api/propagation.js
var API_NAME4, NOOP_TEXT_MAP_PROPAGATOR, PropagationAPI;
var init_propagation = __esm({
  "node_modules/@opentelemetry/api/build/esm/api/propagation.js"() {
    init_esbuild_shims();
    init_global_utils();
    init_NoopTextMapPropagator();
    init_TextMapPropagator();
    init_context_helpers();
    init_utils2();
    init_diag();
    API_NAME4 = "propagation";
    NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator();
    PropagationAPI = /** @class */
    function() {
      function PropagationAPI2() {
        this.createBaggage = createBaggage;
        this.getBaggage = getBaggage;
        this.getActiveBaggage = getActiveBaggage;
        this.setBaggage = setBaggage;
        this.deleteBaggage = deleteBaggage;
      }
      __name(PropagationAPI2, "PropagationAPI");
      PropagationAPI2.getInstance = function() {
        if (!this._instance) {
          this._instance = new PropagationAPI2();
        }
        return this._instance;
      };
      PropagationAPI2.prototype.setGlobalPropagator = function(propagator) {
        return registerGlobal(API_NAME4, propagator, DiagAPI.instance());
      };
      PropagationAPI2.prototype.inject = function(context2, carrier, setter) {
        if (setter === void 0) {
          setter = defaultTextMapSetter;
        }
        return this._getGlobalPropagator().inject(context2, carrier, setter);
      };
      PropagationAPI2.prototype.extract = function(context2, carrier, getter) {
        if (getter === void 0) {
          getter = defaultTextMapGetter;
        }
        return this._getGlobalPropagator().extract(context2, carrier, getter);
      };
      PropagationAPI2.prototype.fields = function() {
        return this._getGlobalPropagator().fields();
      };
      PropagationAPI2.prototype.disable = function() {
        unregisterGlobal(API_NAME4, DiagAPI.instance());
      };
      PropagationAPI2.prototype._getGlobalPropagator = function() {
        return getGlobal(API_NAME4) || NOOP_TEXT_MAP_PROPAGATOR;
      };
      return PropagationAPI2;
    }();
  }
});

// node_modules/@opentelemetry/api/build/esm/propagation-api.js
var propagation;
var init_propagation_api = __esm({
  "node_modules/@opentelemetry/api/build/esm/propagation-api.js"() {
    init_esbuild_shims();
    init_propagation();
    propagation = PropagationAPI.getInstance();
  }
});

// node_modules/@opentelemetry/api/build/esm/api/trace.js
var API_NAME5, TraceAPI;
var init_trace2 = __esm({
  "node_modules/@opentelemetry/api/build/esm/api/trace.js"() {
    init_esbuild_shims();
    init_global_utils();
    init_ProxyTracerProvider();
    init_spancontext_utils();
    init_context_utils();
    init_diag();
    API_NAME5 = "trace";
    TraceAPI = /** @class */
    function() {
      function TraceAPI2() {
        this._proxyTracerProvider = new ProxyTracerProvider();
        this.wrapSpanContext = wrapSpanContext;
        this.isSpanContextValid = isSpanContextValid;
        this.deleteSpan = deleteSpan;
        this.getSpan = getSpan;
        this.getActiveSpan = getActiveSpan;
        this.getSpanContext = getSpanContext;
        this.setSpan = setSpan;
        this.setSpanContext = setSpanContext;
      }
      __name(TraceAPI2, "TraceAPI");
      TraceAPI2.getInstance = function() {
        if (!this._instance) {
          this._instance = new TraceAPI2();
        }
        return this._instance;
      };
      TraceAPI2.prototype.setGlobalTracerProvider = function(provider) {
        var success = registerGlobal(API_NAME5, this._proxyTracerProvider, DiagAPI.instance());
        if (success) {
          this._proxyTracerProvider.setDelegate(provider);
        }
        return success;
      };
      TraceAPI2.prototype.getTracerProvider = function() {
        return getGlobal(API_NAME5) || this._proxyTracerProvider;
      };
      TraceAPI2.prototype.getTracer = function(name3, version2) {
        return this.getTracerProvider().getTracer(name3, version2);
      };
      TraceAPI2.prototype.disable = function() {
        unregisterGlobal(API_NAME5, DiagAPI.instance());
        this._proxyTracerProvider = new ProxyTracerProvider();
      };
      return TraceAPI2;
    }();
  }
});

// node_modules/@opentelemetry/api/build/esm/trace-api.js
var trace;
var init_trace_api = __esm({
  "node_modules/@opentelemetry/api/build/esm/trace-api.js"() {
    init_esbuild_shims();
    init_trace2();
    trace = TraceAPI.getInstance();
  }
});

// node_modules/@opentelemetry/api/build/esm/index.js
var esm_exports2 = {};
__export(esm_exports2, {
  DiagConsoleLogger: () => DiagConsoleLogger,
  DiagLogLevel: () => DiagLogLevel,
  INVALID_SPANID: () => INVALID_SPANID,
  INVALID_SPAN_CONTEXT: () => INVALID_SPAN_CONTEXT,
  INVALID_TRACEID: () => INVALID_TRACEID,
  ProxyTracer: () => ProxyTracer,
  ProxyTracerProvider: () => ProxyTracerProvider,
  ROOT_CONTEXT: () => ROOT_CONTEXT,
  SamplingDecision: () => SamplingDecision,
  SpanKind: () => SpanKind,
  SpanStatusCode: () => SpanStatusCode,
  TraceFlags: () => TraceFlags,
  ValueType: () => ValueType,
  baggageEntryMetadataFromString: () => baggageEntryMetadataFromString,
  context: () => context,
  createContextKey: () => createContextKey,
  createNoopMeter: () => createNoopMeter,
  createTraceState: () => createTraceState,
  default: () => esm_default,
  defaultTextMapGetter: () => defaultTextMapGetter,
  defaultTextMapSetter: () => defaultTextMapSetter,
  diag: () => diag2,
  isSpanContextValid: () => isSpanContextValid,
  isValidSpanId: () => isValidSpanId,
  isValidTraceId: () => isValidTraceId,
  metrics: () => metrics,
  propagation: () => propagation,
  trace: () => trace
});
var esm_default;
var init_esm2 = __esm({
  "node_modules/@opentelemetry/api/build/esm/index.js"() {
    init_esbuild_shims();
    init_utils2();
    init_context();
    init_consoleLogger();
    init_types4();
    init_NoopMeter();
    init_Metric();
    init_TextMapPropagator();
    init_ProxyTracer();
    init_ProxyTracerProvider();
    init_SamplingResult();
    init_span_kind();
    init_status();
    init_trace_flags();
    init_utils3();
    init_spancontext_utils();
    init_invalid_span_constants();
    init_context_api();
    init_diag_api();
    init_metrics_api();
    init_propagation_api();
    init_trace_api();
    esm_default = {
      context,
      diag: diag2,
      metrics,
      propagation,
      trace
    };
  }
});

// packages/core/dist/src/telemetry/metrics.js
function getMeter() {
  if (!cliMeter) {
    cliMeter = metrics.getMeter(SERVICE_NAME);
  }
  return cliMeter;
}
function initializeMetrics(config) {
  if (isMetricsInitialized)
    return;
  const meter = getMeter();
  if (!meter)
    return;
  Object.entries(COUNTER_DEFINITIONS).forEach(([name3, { description, valueType, assign }]) => {
    assign(meter.createCounter(name3, { description, valueType }));
  });
  subagentExecutionCounter = meter.createCounter(SUBAGENT_EXECUTION_COUNT, {
    description: "Counts subagent execution events, tagged by status and subagent name.",
    valueType: ValueType.INT
  });
  Object.entries(HISTOGRAM_DEFINITIONS).forEach(([name3, { description, unit, valueType, assign }]) => {
    assign(meter.createHistogram(name3, { description, unit, valueType }));
  });
  sessionCounter?.add(1, baseMetricDefinition.getCommonAttributes(config));
  initializePerformanceMonitoring(config);
  isMetricsInitialized = true;
}
function recordChatCompressionMetrics(config, attributes) {
  if (!chatCompressionCounter || !isMetricsInitialized)
    return;
  chatCompressionCounter.add(1, {
    ...baseMetricDefinition.getCommonAttributes(config),
    ...attributes
  });
}
function recordToolCallMetrics(config, durationMs, attributes) {
  if (!toolCallCounter || !toolCallLatencyHistogram || !isMetricsInitialized)
    return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config),
    ...attributes
  };
  toolCallCounter.add(1, metricAttributes);
  toolCallLatencyHistogram.record(durationMs, {
    ...baseMetricDefinition.getCommonAttributes(config),
    function_name: attributes.function_name
  });
}
function recordTokenUsageMetrics(config, tokenCount, attributes) {
  if (!tokenUsageCounter || !isMetricsInitialized)
    return;
  tokenUsageCounter.add(tokenCount, {
    ...baseMetricDefinition.getCommonAttributes(config),
    ...attributes
  });
}
function recordApiResponseMetrics(config, durationMs, attributes) {
  if (!apiRequestCounter || !apiRequestLatencyHistogram || !isMetricsInitialized)
    return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config),
    model: attributes.model,
    status_code: attributes.status_code ?? "ok"
  };
  apiRequestCounter.add(1, metricAttributes);
  apiRequestLatencyHistogram.record(durationMs, {
    ...baseMetricDefinition.getCommonAttributes(config),
    model: attributes.model
  });
}
function recordApiErrorMetrics(config, durationMs, attributes) {
  if (!apiRequestCounter || !apiRequestLatencyHistogram || !isMetricsInitialized)
    return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config),
    model: attributes.model,
    status_code: attributes.status_code ?? "error",
    error_type: attributes.error_type ?? "unknown"
  };
  apiRequestCounter.add(1, metricAttributes);
  apiRequestLatencyHistogram.record(durationMs, {
    ...baseMetricDefinition.getCommonAttributes(config),
    model: attributes.model
  });
}
function recordFileOperationMetric(config, attributes) {
  if (!fileOperationCounter || !isMetricsInitialized)
    return;
  fileOperationCounter.add(1, {
    ...baseMetricDefinition.getCommonAttributes(config),
    ...attributes
  });
}
function recordContentRetry(config) {
  if (!contentRetryCounter || !isMetricsInitialized)
    return;
  contentRetryCounter.add(1, baseMetricDefinition.getCommonAttributes(config));
}
function recordContentRetryFailure(config) {
  if (!contentRetryFailureCounter || !isMetricsInitialized)
    return;
  contentRetryFailureCounter.add(1, baseMetricDefinition.getCommonAttributes(config));
}
function recordModelSlashCommand(config, event) {
  if (!modelSlashCommandCallCounter || !isMetricsInitialized)
    return;
  modelSlashCommandCallCounter.add(1, {
    ...baseMetricDefinition.getCommonAttributes(config),
    "slash_command.model.model_name": event.model_name
  });
}
function initializePerformanceMonitoring(config) {
  const meter = getMeter();
  if (!meter)
    return;
  isPerformanceMonitoringEnabled = config.getTelemetryEnabled();
  if (!isPerformanceMonitoringEnabled)
    return;
  Object.entries(PERFORMANCE_COUNTER_DEFINITIONS).forEach(([name3, { description, valueType, assign }]) => {
    assign(meter.createCounter(name3, { description, valueType }));
  });
  Object.entries(PERFORMANCE_HISTOGRAM_DEFINITIONS).forEach(([name3, { description, unit, valueType, assign }]) => {
    assign(meter.createHistogram(name3, { description, unit, valueType }));
  });
}
function recordSubagentExecutionMetrics(config, subagentName, status, terminateReason) {
  if (!subagentExecutionCounter || !isMetricsInitialized)
    return;
  const attributes = {
    ...baseMetricDefinition.getCommonAttributes(config),
    subagent_name: subagentName,
    status
  };
  if (terminateReason) {
    attributes["terminate_reason"] = terminateReason;
  }
  subagentExecutionCounter.add(1, attributes);
}
var TOOL_CALL_COUNT, TOOL_CALL_LATENCY, API_REQUEST_COUNT, API_REQUEST_LATENCY, TOKEN_USAGE, SESSION_COUNT, FILE_OPERATION_COUNT, INVALID_CHUNK_COUNT, CONTENT_RETRY_COUNT, CONTENT_RETRY_FAILURE_COUNT, MODEL_SLASH_COMMAND_CALL_COUNT, SUBAGENT_EXECUTION_COUNT, STARTUP_TIME, MEMORY_USAGE, CPU_USAGE, TOOL_QUEUE_DEPTH, TOOL_EXECUTION_BREAKDOWN, TOKEN_EFFICIENCY, API_REQUEST_BREAKDOWN, PERFORMANCE_SCORE, REGRESSION_DETECTION, REGRESSION_PERCENTAGE_CHANGE, BASELINE_COMPARISON, baseMetricDefinition, COUNTER_DEFINITIONS, HISTOGRAM_DEFINITIONS, PERFORMANCE_COUNTER_DEFINITIONS, PERFORMANCE_HISTOGRAM_DEFINITIONS, FileOperation, PerformanceMetricType, MemoryMetricType, ToolExecutionPhase, ApiRequestPhase, cliMeter, toolCallCounter, toolCallLatencyHistogram, apiRequestCounter, apiRequestLatencyHistogram, tokenUsageCounter, sessionCounter, fileOperationCounter, chatCompressionCounter, invalidChunkCounter, contentRetryCounter, contentRetryFailureCounter, subagentExecutionCounter, modelSlashCommandCallCounter, startupTimeHistogram, memoryUsageGauge, cpuUsageGauge, toolQueueDepthGauge, toolExecutionBreakdownHistogram, tokenEfficiencyHistogram, apiRequestBreakdownHistogram, performanceScoreGauge, regressionDetectionCounter, regressionPercentageChangeHistogram, baselineComparisonHistogram, isMetricsInitialized, isPerformanceMonitoringEnabled;
var init_metrics2 = __esm({
  "packages/core/dist/src/telemetry/metrics.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm2();
    init_constants();
    TOOL_CALL_COUNT = `${SERVICE_NAME}.tool.call.count`;
    TOOL_CALL_LATENCY = `${SERVICE_NAME}.tool.call.latency`;
    API_REQUEST_COUNT = `${SERVICE_NAME}.api.request.count`;
    API_REQUEST_LATENCY = `${SERVICE_NAME}.api.request.latency`;
    TOKEN_USAGE = `${SERVICE_NAME}.token.usage`;
    SESSION_COUNT = `${SERVICE_NAME}.session.count`;
    FILE_OPERATION_COUNT = `${SERVICE_NAME}.file.operation.count`;
    INVALID_CHUNK_COUNT = `${SERVICE_NAME}.chat.invalid_chunk.count`;
    CONTENT_RETRY_COUNT = `${SERVICE_NAME}.chat.content_retry.count`;
    CONTENT_RETRY_FAILURE_COUNT = `${SERVICE_NAME}.chat.content_retry_failure.count`;
    MODEL_SLASH_COMMAND_CALL_COUNT = `${SERVICE_NAME}.slash_command.model.call_count`;
    SUBAGENT_EXECUTION_COUNT = `${SERVICE_NAME}.subagent.execution.count`;
    STARTUP_TIME = `${SERVICE_NAME}.startup.duration`;
    MEMORY_USAGE = `${SERVICE_NAME}.memory.usage`;
    CPU_USAGE = `${SERVICE_NAME}.cpu.usage`;
    TOOL_QUEUE_DEPTH = `${SERVICE_NAME}.tool.queue.depth`;
    TOOL_EXECUTION_BREAKDOWN = `${SERVICE_NAME}.tool.execution.breakdown`;
    TOKEN_EFFICIENCY = `${SERVICE_NAME}.token.efficiency`;
    API_REQUEST_BREAKDOWN = `${SERVICE_NAME}.api.request.breakdown`;
    PERFORMANCE_SCORE = `${SERVICE_NAME}.performance.score`;
    REGRESSION_DETECTION = `${SERVICE_NAME}.performance.regression`;
    REGRESSION_PERCENTAGE_CHANGE = `${SERVICE_NAME}.performance.regression.percentage_change`;
    BASELINE_COMPARISON = `${SERVICE_NAME}.performance.baseline.comparison`;
    baseMetricDefinition = {
      getCommonAttributes: /* @__PURE__ */ __name((config) => ({
        "session.id": config.getSessionId()
      }), "getCommonAttributes")
    };
    COUNTER_DEFINITIONS = {
      [TOOL_CALL_COUNT]: {
        description: "Counts tool calls, tagged by function name and success.",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c3) => toolCallCounter = c3, "assign"),
        attributes: {}
      },
      [API_REQUEST_COUNT]: {
        description: "Counts API requests, tagged by model and status.",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c3) => apiRequestCounter = c3, "assign"),
        attributes: {}
      },
      [TOKEN_USAGE]: {
        description: "Counts the total number of tokens used.",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c3) => tokenUsageCounter = c3, "assign"),
        attributes: {}
      },
      [SESSION_COUNT]: {
        description: "Count of CLI sessions started.",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c3) => sessionCounter = c3, "assign"),
        attributes: {}
      },
      [FILE_OPERATION_COUNT]: {
        description: "Counts file operations (create, read, update).",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c3) => fileOperationCounter = c3, "assign"),
        attributes: {}
      },
      [INVALID_CHUNK_COUNT]: {
        description: "Counts invalid chunks received from a stream.",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c3) => invalidChunkCounter = c3, "assign"),
        attributes: {}
      },
      [CONTENT_RETRY_COUNT]: {
        description: "Counts retries due to content errors (e.g., empty stream).",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c3) => contentRetryCounter = c3, "assign"),
        attributes: {}
      },
      [CONTENT_RETRY_FAILURE_COUNT]: {
        description: "Counts occurrences of all content retries failing.",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c3) => contentRetryFailureCounter = c3, "assign"),
        attributes: {}
      },
      [MODEL_SLASH_COMMAND_CALL_COUNT]: {
        description: "Counts model slash command calls.",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c3) => modelSlashCommandCallCounter = c3, "assign"),
        attributes: {}
      },
      [EVENT_CHAT_COMPRESSION]: {
        description: "Counts chat compression events.",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c3) => chatCompressionCounter = c3, "assign"),
        attributes: {}
      }
    };
    HISTOGRAM_DEFINITIONS = {
      [TOOL_CALL_LATENCY]: {
        description: "Latency of tool calls in milliseconds.",
        unit: "ms",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((h) => toolCallLatencyHistogram = h, "assign"),
        attributes: {}
      },
      [API_REQUEST_LATENCY]: {
        description: "Latency of API requests in milliseconds.",
        unit: "ms",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((h) => apiRequestLatencyHistogram = h, "assign"),
        attributes: {}
      }
    };
    PERFORMANCE_COUNTER_DEFINITIONS = {
      [REGRESSION_DETECTION]: {
        description: "Performance regression detection events.",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((c3) => regressionDetectionCounter = c3, "assign"),
        attributes: {}
      }
    };
    PERFORMANCE_HISTOGRAM_DEFINITIONS = {
      [STARTUP_TIME]: {
        description: "CLI startup time in milliseconds, broken down by initialization phase.",
        unit: "ms",
        valueType: ValueType.DOUBLE,
        assign: /* @__PURE__ */ __name((h) => startupTimeHistogram = h, "assign"),
        attributes: {}
      },
      [MEMORY_USAGE]: {
        description: "Memory usage in bytes.",
        unit: "bytes",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((h) => memoryUsageGauge = h, "assign"),
        attributes: {}
      },
      [CPU_USAGE]: {
        description: "CPU usage percentage.",
        unit: "percent",
        valueType: ValueType.DOUBLE,
        assign: /* @__PURE__ */ __name((h) => cpuUsageGauge = h, "assign"),
        attributes: {}
      },
      [TOOL_QUEUE_DEPTH]: {
        description: "Number of tools in execution queue.",
        unit: "count",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((h) => toolQueueDepthGauge = h, "assign"),
        attributes: {}
      },
      [TOOL_EXECUTION_BREAKDOWN]: {
        description: "Tool execution time breakdown by phase in milliseconds.",
        unit: "ms",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((h) => toolExecutionBreakdownHistogram = h, "assign"),
        attributes: {}
      },
      [TOKEN_EFFICIENCY]: {
        description: "Token efficiency metrics (tokens per operation, cache hit rate, etc.).",
        unit: "ratio",
        valueType: ValueType.DOUBLE,
        assign: /* @__PURE__ */ __name((h) => tokenEfficiencyHistogram = h, "assign"),
        attributes: {}
      },
      [API_REQUEST_BREAKDOWN]: {
        description: "API request time breakdown by phase in milliseconds.",
        unit: "ms",
        valueType: ValueType.INT,
        assign: /* @__PURE__ */ __name((h) => apiRequestBreakdownHistogram = h, "assign"),
        attributes: {}
      },
      [PERFORMANCE_SCORE]: {
        description: "Composite performance score (0-100).",
        unit: "score",
        valueType: ValueType.DOUBLE,
        assign: /* @__PURE__ */ __name((h) => performanceScoreGauge = h, "assign"),
        attributes: {}
      },
      [REGRESSION_PERCENTAGE_CHANGE]: {
        description: "Percentage change compared to baseline for detected regressions.",
        unit: "percent",
        valueType: ValueType.DOUBLE,
        assign: /* @__PURE__ */ __name((h) => regressionPercentageChangeHistogram = h, "assign"),
        attributes: {}
      },
      [BASELINE_COMPARISON]: {
        description: "Performance comparison to established baseline (percentage change).",
        unit: "percent",
        valueType: ValueType.DOUBLE,
        assign: /* @__PURE__ */ __name((h) => baselineComparisonHistogram = h, "assign"),
        attributes: {}
      }
    };
    (function(FileOperation2) {
      FileOperation2["CREATE"] = "create";
      FileOperation2["READ"] = "read";
      FileOperation2["UPDATE"] = "update";
    })(FileOperation || (FileOperation = {}));
    (function(PerformanceMetricType2) {
      PerformanceMetricType2["STARTUP"] = "startup";
      PerformanceMetricType2["MEMORY"] = "memory";
      PerformanceMetricType2["CPU"] = "cpu";
      PerformanceMetricType2["TOOL_EXECUTION"] = "tool_execution";
      PerformanceMetricType2["API_REQUEST"] = "api_request";
      PerformanceMetricType2["TOKEN_EFFICIENCY"] = "token_efficiency";
    })(PerformanceMetricType || (PerformanceMetricType = {}));
    (function(MemoryMetricType2) {
      MemoryMetricType2["HEAP_USED"] = "heap_used";
      MemoryMetricType2["HEAP_TOTAL"] = "heap_total";
      MemoryMetricType2["EXTERNAL"] = "external";
      MemoryMetricType2["RSS"] = "rss";
    })(MemoryMetricType || (MemoryMetricType = {}));
    (function(ToolExecutionPhase2) {
      ToolExecutionPhase2["VALIDATION"] = "validation";
      ToolExecutionPhase2["PREPARATION"] = "preparation";
      ToolExecutionPhase2["EXECUTION"] = "execution";
      ToolExecutionPhase2["RESULT_PROCESSING"] = "result_processing";
    })(ToolExecutionPhase || (ToolExecutionPhase = {}));
    (function(ApiRequestPhase2) {
      ApiRequestPhase2["REQUEST_PREPARATION"] = "request_preparation";
      ApiRequestPhase2["NETWORK_LATENCY"] = "network_latency";
      ApiRequestPhase2["RESPONSE_PROCESSING"] = "response_processing";
      ApiRequestPhase2["TOKEN_PROCESSING"] = "token_processing";
    })(ApiRequestPhase || (ApiRequestPhase = {}));
    isMetricsInitialized = false;
    isPerformanceMonitoringEnabled = false;
    __name(getMeter, "getMeter");
    __name(initializeMetrics, "initializeMetrics");
    __name(recordChatCompressionMetrics, "recordChatCompressionMetrics");
    __name(recordToolCallMetrics, "recordToolCallMetrics");
    __name(recordTokenUsageMetrics, "recordTokenUsageMetrics");
    __name(recordApiResponseMetrics, "recordApiResponseMetrics");
    __name(recordApiErrorMetrics, "recordApiErrorMetrics");
    __name(recordFileOperationMetric, "recordFileOperationMetric");
    __name(recordContentRetry, "recordContentRetry");
    __name(recordContentRetryFailure, "recordContentRetryFailure");
    __name(recordModelSlashCommand, "recordModelSlashCommand");
    __name(initializePerformanceMonitoring, "initializePerformanceMonitoring");
    __name(recordSubagentExecutionMetrics, "recordSubagentExecutionMetrics");
  }
});

// packages/core/dist/src/utils/installationManager.js
import * as fs14 from "node:fs";
import { randomUUID as randomUUID3 } from "node:crypto";
import * as path10 from "node:path";
var InstallationManager;
var init_installationManager = __esm({
  "packages/core/dist/src/utils/installationManager.js"() {
    "use strict";
    init_esbuild_shims();
    init_storage();
    InstallationManager = class {
      static {
        __name(this, "InstallationManager");
      }
      getInstallationIdPath() {
        return Storage.getInstallationIdPath();
      }
      readInstallationIdFromFile() {
        const installationIdFile = this.getInstallationIdPath();
        if (fs14.existsSync(installationIdFile)) {
          const installationid = fs14.readFileSync(installationIdFile, "utf-8").trim();
          return installationid || null;
        }
        return null;
      }
      writeInstallationIdToFile(installationId) {
        const installationIdFile = this.getInstallationIdPath();
        const dir = path10.dirname(installationIdFile);
        fs14.mkdirSync(dir, { recursive: true });
        fs14.writeFileSync(installationIdFile, installationId, "utf-8");
      }
      /**
       * Retrieves the installation ID from a file, creating it if it doesn't exist.
       * This ID is used for unique user installation tracking.
       * @returns A UUID string for the user.
       */
      getInstallationId() {
        try {
          let installationId = this.readInstallationIdFromFile();
          if (!installationId) {
            installationId = randomUUID3();
            this.writeInstallationIdToFile(installationId);
          }
          return installationId;
        } catch (error) {
          console.error("Error accessing installation ID file, generating ephemeral ID:", error);
          return "123456789";
        }
      }
    };
  }
});

// node_modules/mnemonist/utils/comparators.js
var require_comparators = __commonJS({
  "node_modules/mnemonist/utils/comparators.js"(exports2) {
    init_esbuild_shims();
    var DEFAULT_COMPARATOR = /* @__PURE__ */ __name(function(a, b) {
      if (a < b)
        return -1;
      if (a > b)
        return 1;
      return 0;
    }, "DEFAULT_COMPARATOR");
    var DEFAULT_REVERSE_COMPARATOR = /* @__PURE__ */ __name(function(a, b) {
      if (a < b)
        return 1;
      if (a > b)
        return -1;
      return 0;
    }, "DEFAULT_REVERSE_COMPARATOR");
    function reverseComparator(comparator) {
      return function(a, b) {
        return comparator(b, a);
      };
    }
    __name(reverseComparator, "reverseComparator");
    function createTupleComparator(size) {
      if (size === 2) {
        return function(a, b) {
          if (a[0] < b[0])
            return -1;
          if (a[0] > b[0])
            return 1;
          if (a[1] < b[1])
            return -1;
          if (a[1] > b[1])
            return 1;
          return 0;
        };
      }
      return function(a, b) {
        var i = 0;
        while (i < size) {
          if (a[i] < b[i])
            return -1;
          if (a[i] > b[i])
            return 1;
          i++;
        }
        return 0;
      };
    }
    __name(createTupleComparator, "createTupleComparator");
    exports2.DEFAULT_COMPARATOR = DEFAULT_COMPARATOR;
    exports2.DEFAULT_REVERSE_COMPARATOR = DEFAULT_REVERSE_COMPARATOR;
    exports2.reverseComparator = reverseComparator;
    exports2.createTupleComparator = createTupleComparator;
  }
});

// node_modules/obliterator/support.js
var require_support = __commonJS({
  "node_modules/obliterator/support.js"(exports2) {
    init_esbuild_shims();
    exports2.ARRAY_BUFFER_SUPPORT = typeof ArrayBuffer !== "undefined";
    exports2.SYMBOL_SUPPORT = typeof Symbol !== "undefined";
  }
});

// node_modules/obliterator/foreach.js
var require_foreach = __commonJS({
  "node_modules/obliterator/foreach.js"(exports2, module2) {
    init_esbuild_shims();
    var support = require_support();
    var ARRAY_BUFFER_SUPPORT = support.ARRAY_BUFFER_SUPPORT;
    var SYMBOL_SUPPORT = support.SYMBOL_SUPPORT;
    module2.exports = /* @__PURE__ */ __name(function forEach2(iterable, callback) {
      var iterator, k, i, l2, s2;
      if (!iterable) throw new Error("obliterator/forEach: invalid iterable.");
      if (typeof callback !== "function")
        throw new Error("obliterator/forEach: expecting a callback.");
      if (Array.isArray(iterable) || ARRAY_BUFFER_SUPPORT && ArrayBuffer.isView(iterable) || typeof iterable === "string" || iterable.toString() === "[object Arguments]") {
        for (i = 0, l2 = iterable.length; i < l2; i++) callback(iterable[i], i);
        return;
      }
      if (typeof iterable.forEach === "function") {
        iterable.forEach(callback);
        return;
      }
      if (SYMBOL_SUPPORT && Symbol.iterator in iterable && typeof iterable.next !== "function") {
        iterable = iterable[Symbol.iterator]();
      }
      if (typeof iterable.next === "function") {
        iterator = iterable;
        i = 0;
        while (s2 = iterator.next(), s2.done !== true) {
          callback(s2.value, i);
          i++;
        }
        return;
      }
      for (k in iterable) {
        if (iterable.hasOwnProperty(k)) {
          callback(iterable[k], k);
        }
      }
      return;
    }, "forEach");
  }
});

// node_modules/mnemonist/fibonacci-heap.js
var require_fibonacci_heap = __commonJS({
  "node_modules/mnemonist/fibonacci-heap.js"(exports2, module2) {
    init_esbuild_shims();
    var comparators = require_comparators();
    var forEach2 = require_foreach();
    var DEFAULT_COMPARATOR = comparators.DEFAULT_COMPARATOR;
    var reverseComparator = comparators.reverseComparator;
    function FibonacciHeap2(comparator) {
      this.clear();
      this.comparator = comparator || DEFAULT_COMPARATOR;
      if (typeof this.comparator !== "function")
        throw new Error("mnemonist/FibonacciHeap.constructor: given comparator should be a function.");
    }
    __name(FibonacciHeap2, "FibonacciHeap");
    FibonacciHeap2.prototype.clear = function() {
      this.root = null;
      this.min = null;
      this.size = 0;
    };
    function createNode2(item) {
      return {
        item,
        degree: 0
      };
    }
    __name(createNode2, "createNode");
    function mergeWithRoot(heap, node) {
      if (!heap.root) {
        heap.root = node;
      } else {
        node.right = heap.root.right;
        node.left = heap.root;
        heap.root.right.left = node;
        heap.root.right = node;
      }
    }
    __name(mergeWithRoot, "mergeWithRoot");
    FibonacciHeap2.prototype.push = function(item) {
      var node = createNode2(item);
      node.left = node;
      node.right = node;
      mergeWithRoot(this, node);
      if (!this.min || this.comparator(node.item, this.min.item) <= 0)
        this.min = node;
      return ++this.size;
    };
    FibonacciHeap2.prototype.peek = function() {
      return this.min ? this.min.item : void 0;
    };
    function consumeLinkedList(head) {
      var nodes = [], node = head, flag = false;
      while (true) {
        if (node === head && flag)
          break;
        else if (node === head)
          flag = true;
        nodes.push(node);
        node = node.right;
      }
      return nodes;
    }
    __name(consumeLinkedList, "consumeLinkedList");
    function removeFromRoot(heap, node) {
      if (heap.root === node)
        heap.root = node.right;
      node.left.right = node.right;
      node.right.left = node.left;
    }
    __name(removeFromRoot, "removeFromRoot");
    function mergeWithChild(parent, node) {
      if (!parent.child) {
        parent.child = node;
      } else {
        node.right = parent.child.right;
        node.left = parent.child;
        parent.child.right.left = node;
        parent.child.right = node;
      }
    }
    __name(mergeWithChild, "mergeWithChild");
    function link3(heap, y, x) {
      removeFromRoot(heap, y);
      y.left = y;
      y.right = y;
      mergeWithChild(x, y);
      x.degree++;
      y.parent = x;
    }
    __name(link3, "link");
    function consolidate(heap) {
      var A = new Array(heap.size), nodes = consumeLinkedList(heap.root), i, l2, x, y, d, t2;
      for (i = 0, l2 = nodes.length; i < l2; i++) {
        x = nodes[i];
        d = x.degree;
        while (A[d]) {
          y = A[d];
          if (heap.comparator(x.item, y.item) > 0) {
            t2 = x;
            x = y;
            y = t2;
          }
          link3(heap, y, x);
          A[d] = null;
          d++;
        }
        A[d] = x;
      }
      for (i = 0; i < heap.size; i++) {
        if (A[i] && heap.comparator(A[i].item, heap.min.item) <= 0)
          heap.min = A[i];
      }
    }
    __name(consolidate, "consolidate");
    FibonacciHeap2.prototype.pop = function() {
      if (!this.size)
        return void 0;
      var z = this.min;
      if (z.child) {
        var nodes = consumeLinkedList(z.child), node, i, l2;
        for (i = 0, l2 = nodes.length; i < l2; i++) {
          node = nodes[i];
          mergeWithRoot(this, node);
          delete node.parent;
        }
      }
      removeFromRoot(this, z);
      if (z === z.right) {
        this.min = null;
        this.root = null;
      } else {
        this.min = z.right;
        consolidate(this);
      }
      this.size--;
      return z.item;
    };
    FibonacciHeap2.prototype.inspect = function() {
      var proxy = {
        size: this.size
      };
      if (this.min && "item" in this.min)
        proxy.top = this.min.item;
      Object.defineProperty(proxy, "constructor", {
        value: FibonacciHeap2,
        enumerable: false
      });
      return proxy;
    };
    if (typeof Symbol !== "undefined")
      FibonacciHeap2.prototype[Symbol.for("nodejs.util.inspect.custom")] = FibonacciHeap2.prototype.inspect;
    function MaxFibonacciHeap2(comparator) {
      this.clear();
      this.comparator = comparator || DEFAULT_COMPARATOR;
      if (typeof this.comparator !== "function")
        throw new Error("mnemonist/FibonacciHeap.constructor: given comparator should be a function.");
      this.comparator = reverseComparator(this.comparator);
    }
    __name(MaxFibonacciHeap2, "MaxFibonacciHeap");
    MaxFibonacciHeap2.prototype = FibonacciHeap2.prototype;
    FibonacciHeap2.from = function(iterable, comparator) {
      var heap = new FibonacciHeap2(comparator);
      forEach2(iterable, function(value) {
        heap.push(value);
      });
      return heap;
    };
    MaxFibonacciHeap2.from = function(iterable, comparator) {
      var heap = new MaxFibonacciHeap2(comparator);
      forEach2(iterable, function(value) {
        heap.push(value);
      });
      return heap;
    };
    FibonacciHeap2.MinFibonacciHeap = FibonacciHeap2;
    FibonacciHeap2.MaxFibonacciHeap = MaxFibonacciHeap2;
    module2.exports = FibonacciHeap2;
  }
});

// node_modules/mnemonist/utils/typed-arrays.js
var require_typed_arrays = __commonJS({
  "node_modules/mnemonist/utils/typed-arrays.js"(exports2) {
    init_esbuild_shims();
    var MAX_8BIT_INTEGER = Math.pow(2, 8) - 1;
    var MAX_16BIT_INTEGER = Math.pow(2, 16) - 1;
    var MAX_32BIT_INTEGER = Math.pow(2, 32) - 1;
    var MAX_SIGNED_8BIT_INTEGER = Math.pow(2, 7) - 1;
    var MAX_SIGNED_16BIT_INTEGER = Math.pow(2, 15) - 1;
    var MAX_SIGNED_32BIT_INTEGER = Math.pow(2, 31) - 1;
    exports2.getPointerArray = function(size) {
      var maxIndex = size - 1;
      if (maxIndex <= MAX_8BIT_INTEGER)
        return Uint8Array;
      if (maxIndex <= MAX_16BIT_INTEGER)
        return Uint16Array;
      if (maxIndex <= MAX_32BIT_INTEGER)
        return Uint32Array;
      throw new Error("mnemonist: Pointer Array of size > 4294967295 is not supported.");
    };
    exports2.getSignedPointerArray = function(size) {
      var maxIndex = size - 1;
      if (maxIndex <= MAX_SIGNED_8BIT_INTEGER)
        return Int8Array;
      if (maxIndex <= MAX_SIGNED_16BIT_INTEGER)
        return Int16Array;
      if (maxIndex <= MAX_SIGNED_32BIT_INTEGER)
        return Int32Array;
      return Float64Array;
    };
    exports2.getNumberType = function(value) {
      if (value === (value | 0)) {
        if (Math.sign(value) === -1) {
          if (value <= 127 && value >= -128)
            return Int8Array;
          if (value <= 32767 && value >= -32768)
            return Int16Array;
          return Int32Array;
        } else {
          if (value <= 255)
            return Uint8Array;
          if (value <= 65535)
            return Uint16Array;
          return Uint32Array;
        }
      }
      return Float64Array;
    };
    var TYPE_PRIORITY = {
      Uint8Array: 1,
      Int8Array: 2,
      Uint16Array: 3,
      Int16Array: 4,
      Uint32Array: 5,
      Int32Array: 6,
      Float32Array: 7,
      Float64Array: 8
    };
    exports2.getMinimalRepresentation = function(array, getter) {
      var maxType = null, maxPriority = 0, p, t2, v, i, l2;
      for (i = 0, l2 = array.length; i < l2; i++) {
        v = getter ? getter(array[i]) : array[i];
        t2 = exports2.getNumberType(v);
        p = TYPE_PRIORITY[t2.name];
        if (p > maxPriority) {
          maxPriority = p;
          maxType = t2;
        }
      }
      return maxType;
    };
    exports2.isTypedArray = function(value) {
      return typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView(value);
    };
    exports2.concat = function() {
      var length = 0, i, o2, l2;
      for (i = 0, l2 = arguments.length; i < l2; i++)
        length += arguments[i].length;
      var array = new arguments[0].constructor(length);
      for (i = 0, o2 = 0; i < l2; i++) {
        array.set(arguments[i], o2);
        o2 += arguments[i].length;
      }
      return array;
    };
    exports2.indices = function(length) {
      var PointerArray = exports2.getPointerArray(length);
      var array = new PointerArray(length);
      for (var i = 0; i < length; i++)
        array[i] = i;
      return array;
    };
  }
});

// node_modules/mnemonist/utils/iterables.js
var require_iterables = __commonJS({
  "node_modules/mnemonist/utils/iterables.js"(exports2) {
    init_esbuild_shims();
    var forEach2 = require_foreach();
    var typed = require_typed_arrays();
    function isArrayLike2(target) {
      return Array.isArray(target) || typed.isTypedArray(target);
    }
    __name(isArrayLike2, "isArrayLike");
    function guessLength(target) {
      if (typeof target.length === "number")
        return target.length;
      if (typeof target.size === "number")
        return target.size;
      return;
    }
    __name(guessLength, "guessLength");
    function toArray(target) {
      var l2 = guessLength(target);
      var array = typeof l2 === "number" ? new Array(l2) : [];
      var i = 0;
      forEach2(target, function(value) {
        array[i++] = value;
      });
      return array;
    }
    __name(toArray, "toArray");
    function toArrayWithIndices(target) {
      var l2 = guessLength(target);
      var IndexArray = typeof l2 === "number" ? typed.getPointerArray(l2) : Array;
      var array = typeof l2 === "number" ? new Array(l2) : [];
      var indices = typeof l2 === "number" ? new IndexArray(l2) : [];
      var i = 0;
      forEach2(target, function(value) {
        array[i] = value;
        indices[i] = i++;
      });
      return [array, indices];
    }
    __name(toArrayWithIndices, "toArrayWithIndices");
    exports2.isArrayLike = isArrayLike2;
    exports2.guessLength = guessLength;
    exports2.toArray = toArray;
    exports2.toArrayWithIndices = toArrayWithIndices;
  }
});

// node_modules/mnemonist/heap.js
var require_heap = __commonJS({
  "node_modules/mnemonist/heap.js"(exports2, module2) {
    init_esbuild_shims();
    var forEach2 = require_foreach();
    var comparators = require_comparators();
    var iterables = require_iterables();
    var DEFAULT_COMPARATOR = comparators.DEFAULT_COMPARATOR;
    var reverseComparator = comparators.reverseComparator;
    function siftDown(compare, heap, startIndex, i) {
      var item = heap[i], parentIndex, parent;
      while (i > startIndex) {
        parentIndex = i - 1 >> 1;
        parent = heap[parentIndex];
        if (compare(item, parent) < 0) {
          heap[i] = parent;
          i = parentIndex;
          continue;
        }
        break;
      }
      heap[i] = item;
    }
    __name(siftDown, "siftDown");
    function siftUp(compare, heap, i) {
      var endIndex = heap.length, startIndex = i, item = heap[i], childIndex = 2 * i + 1, rightIndex;
      while (childIndex < endIndex) {
        rightIndex = childIndex + 1;
        if (rightIndex < endIndex && compare(heap[childIndex], heap[rightIndex]) >= 0) {
          childIndex = rightIndex;
        }
        heap[i] = heap[childIndex];
        i = childIndex;
        childIndex = 2 * i + 1;
      }
      heap[i] = item;
      siftDown(compare, heap, startIndex, i);
    }
    __name(siftUp, "siftUp");
    function push2(compare, heap, item) {
      heap.push(item);
      siftDown(compare, heap, 0, heap.length - 1);
    }
    __name(push2, "push");
    function pop(compare, heap) {
      var lastItem = heap.pop();
      if (heap.length !== 0) {
        var item = heap[0];
        heap[0] = lastItem;
        siftUp(compare, heap, 0);
        return item;
      }
      return lastItem;
    }
    __name(pop, "pop");
    function replace2(compare, heap, item) {
      if (heap.length === 0)
        throw new Error("mnemonist/heap.replace: cannot pop an empty heap.");
      var popped = heap[0];
      heap[0] = item;
      siftUp(compare, heap, 0);
      return popped;
    }
    __name(replace2, "replace");
    function pushpop(compare, heap, item) {
      var tmp;
      if (heap.length !== 0 && compare(heap[0], item) < 0) {
        tmp = heap[0];
        heap[0] = item;
        item = tmp;
        siftUp(compare, heap, 0);
      }
      return item;
    }
    __name(pushpop, "pushpop");
    function heapify(compare, array) {
      var n2 = array.length, l2 = n2 >> 1, i = l2;
      while (--i >= 0)
        siftUp(compare, array, i);
    }
    __name(heapify, "heapify");
    function consume(compare, heap) {
      var l2 = heap.length, i = 0;
      var array = new Array(l2);
      while (i < l2)
        array[i++] = pop(compare, heap);
      return array;
    }
    __name(consume, "consume");
    function nsmallest(compare, n2, iterable) {
      if (arguments.length === 2) {
        iterable = n2;
        n2 = compare;
        compare = DEFAULT_COMPARATOR;
      }
      var reverseCompare = reverseComparator(compare);
      var i, l2, v;
      var min = Infinity;
      var result;
      if (n2 === 1) {
        if (iterables.isArrayLike(iterable)) {
          for (i = 0, l2 = iterable.length; i < l2; i++) {
            v = iterable[i];
            if (min === Infinity || compare(v, min) < 0)
              min = v;
          }
          result = new iterable.constructor(1);
          result[0] = min;
          return result;
        }
        forEach2(iterable, function(value) {
          if (min === Infinity || compare(value, min) < 0)
            min = value;
        });
        return [min];
      }
      if (iterables.isArrayLike(iterable)) {
        if (n2 >= iterable.length)
          return iterable.slice().sort(compare);
        result = iterable.slice(0, n2);
        heapify(reverseCompare, result);
        for (i = n2, l2 = iterable.length; i < l2; i++)
          if (reverseCompare(iterable[i], result[0]) > 0)
            replace2(reverseCompare, result, iterable[i]);
        return result.sort(compare);
      }
      var size = iterables.guessLength(iterable);
      if (size !== null && size < n2)
        n2 = size;
      result = new Array(n2);
      i = 0;
      forEach2(iterable, function(value) {
        if (i < n2) {
          result[i] = value;
        } else {
          if (i === n2)
            heapify(reverseCompare, result);
          if (reverseCompare(value, result[0]) > 0)
            replace2(reverseCompare, result, value);
        }
        i++;
      });
      if (result.length > i)
        result.length = i;
      return result.sort(compare);
    }
    __name(nsmallest, "nsmallest");
    function nlargest(compare, n2, iterable) {
      if (arguments.length === 2) {
        iterable = n2;
        n2 = compare;
        compare = DEFAULT_COMPARATOR;
      }
      var reverseCompare = reverseComparator(compare);
      var i, l2, v;
      var max = -Infinity;
      var result;
      if (n2 === 1) {
        if (iterables.isArrayLike(iterable)) {
          for (i = 0, l2 = iterable.length; i < l2; i++) {
            v = iterable[i];
            if (max === -Infinity || compare(v, max) > 0)
              max = v;
          }
          result = new iterable.constructor(1);
          result[0] = max;
          return result;
        }
        forEach2(iterable, function(value) {
          if (max === -Infinity || compare(value, max) > 0)
            max = value;
        });
        return [max];
      }
      if (iterables.isArrayLike(iterable)) {
        if (n2 >= iterable.length)
          return iterable.slice().sort(reverseCompare);
        result = iterable.slice(0, n2);
        heapify(compare, result);
        for (i = n2, l2 = iterable.length; i < l2; i++)
          if (compare(iterable[i], result[0]) > 0)
            replace2(compare, result, iterable[i]);
        return result.sort(reverseCompare);
      }
      var size = iterables.guessLength(iterable);
      if (size !== null && size < n2)
        n2 = size;
      result = new Array(n2);
      i = 0;
      forEach2(iterable, function(value) {
        if (i < n2) {
          result[i] = value;
        } else {
          if (i === n2)
            heapify(compare, result);
          if (compare(value, result[0]) > 0)
            replace2(compare, result, value);
        }
        i++;
      });
      if (result.length > i)
        result.length = i;
      return result.sort(reverseCompare);
    }
    __name(nlargest, "nlargest");
    function Heap2(comparator) {
      this.clear();
      this.comparator = comparator || DEFAULT_COMPARATOR;
      if (typeof this.comparator !== "function")
        throw new Error("mnemonist/Heap.constructor: given comparator should be a function.");
    }
    __name(Heap2, "Heap");
    Heap2.prototype.clear = function() {
      this.items = [];
      this.size = 0;
    };
    Heap2.prototype.push = function(item) {
      push2(this.comparator, this.items, item);
      return ++this.size;
    };
    Heap2.prototype.peek = function() {
      return this.items[0];
    };
    Heap2.prototype.pop = function() {
      if (this.size !== 0)
        this.size--;
      return pop(this.comparator, this.items);
    };
    Heap2.prototype.replace = function(item) {
      return replace2(this.comparator, this.items, item);
    };
    Heap2.prototype.pushpop = function(item) {
      return pushpop(this.comparator, this.items, item);
    };
    Heap2.prototype.consume = function() {
      this.size = 0;
      return consume(this.comparator, this.items);
    };
    Heap2.prototype.toArray = function() {
      return consume(this.comparator, this.items.slice());
    };
    Heap2.prototype.inspect = function() {
      var proxy = this.toArray();
      Object.defineProperty(proxy, "constructor", {
        value: Heap2,
        enumerable: false
      });
      return proxy;
    };
    if (typeof Symbol !== "undefined")
      Heap2.prototype[Symbol.for("nodejs.util.inspect.custom")] = Heap2.prototype.inspect;
    function MaxHeap2(comparator) {
      this.clear();
      this.comparator = comparator || DEFAULT_COMPARATOR;
      if (typeof this.comparator !== "function")
        throw new Error("mnemonist/MaxHeap.constructor: given comparator should be a function.");
      this.comparator = reverseComparator(this.comparator);
    }
    __name(MaxHeap2, "MaxHeap");
    MaxHeap2.prototype = Heap2.prototype;
    Heap2.from = function(iterable, comparator) {
      var heap = new Heap2(comparator);
      var items;
      if (iterables.isArrayLike(iterable))
        items = iterable.slice();
      else
        items = iterables.toArray(iterable);
      heapify(heap.comparator, items);
      heap.items = items;
      heap.size = items.length;
      return heap;
    };
    MaxHeap2.from = function(iterable, comparator) {
      var heap = new MaxHeap2(comparator);
      var items;
      if (iterables.isArrayLike(iterable))
        items = iterable.slice();
      else
        items = iterables.toArray(iterable);
      heapify(heap.comparator, items);
      heap.items = items;
      heap.size = items.length;
      return heap;
    };
    Heap2.siftUp = siftUp;
    Heap2.siftDown = siftDown;
    Heap2.push = push2;
    Heap2.pop = pop;
    Heap2.replace = replace2;
    Heap2.pushpop = pushpop;
    Heap2.heapify = heapify;
    Heap2.consume = consume;
    Heap2.nsmallest = nsmallest;
    Heap2.nlargest = nlargest;
    Heap2.MinHeap = Heap2;
    Heap2.MaxHeap = MaxHeap2;
    module2.exports = Heap2;
  }
});

// node_modules/mnemonist/suffix-array.js
var require_suffix_array = __commonJS({
  "node_modules/mnemonist/suffix-array.js"(exports2, module2) {
    init_esbuild_shims();
    var SEPARATOR = "";
    function sort(string, array, offset) {
      var l2 = array.length, buckets = [], i = l2, j = -1, b, d = 0, bits;
      while (i--)
        j = Math.max(string[array[i] + offset], j);
      bits = j >> 24 && 32 || j >> 16 && 24 || j >> 8 && 16 || 8;
      for (; d < bits; d += 4) {
        for (i = 16; i--; )
          buckets[i] = [];
        for (i = l2; i--; )
          buckets[string[array[i] + offset] >> d & 15].push(array[i]);
        for (b = 0; b < 16; b++) {
          for (j = buckets[b].length; j--; )
            array[++i] = buckets[b][j];
        }
      }
    }
    __name(sort, "sort");
    function compare(string, lookup, m, n2) {
      return string[m] - string[n2] || (m % 3 === 2 ? string[m + 1] - string[n2 + 1] || lookup[m + 2] - lookup[n2 + 2] : lookup[m + 1] - lookup[n2 + 1]);
    }
    __name(compare, "compare");
    function build(string, l2) {
      var a = [], b = [], al = 2 * l2 / 3 | 0, bl = l2 - al, r3 = al + 1 >> 1, i = al, j = 0, k, lookup = [], result = [];
      if (l2 === 1)
        return [0];
      while (i--)
        a[i] = (i * 3 >> 1) + 1;
      for (i = 3; i--; )
        sort(string, a, i);
      j = b[(a[0] / 3 | 0) + (a[0] % 3 === 1 ? 0 : r3)] = 1;
      for (i = 1; i < al; i++) {
        if (string[a[i]] !== string[a[i - 1]] || string[a[i] + 1] !== string[a[i - 1] + 1] || string[a[i] + 2] !== string[a[i - 1] + 2])
          j++;
        b[(a[i] / 3 | 0) + (a[i] % 3 === 1 ? 0 : r3)] = j;
      }
      if (j < al) {
        b = build(b, al);
        for (i = al; i--; )
          a[i] = b[i] < r3 ? b[i] * 3 + 1 : (b[i] - r3) * 3 + 2;
      }
      for (i = al; i--; )
        lookup[a[i]] = i;
      lookup[l2] = -1;
      lookup[l2 + 1] = -2;
      b = l2 % 3 === 1 ? [l2 - 1] : [];
      for (i = 0; i < al; i++) {
        if (a[i] % 3 === 1)
          b.push(a[i] - 1);
      }
      sort(string, b, 0);
      for (i = 0, j = 0, k = 0; i < al && j < bl; )
        result[k++] = compare(string, lookup, a[i], b[j]) < 0 ? a[i++] : b[j++];
      while (i < al)
        result[k++] = a[i++];
      while (j < bl)
        result[k++] = b[j++];
      return result;
    }
    __name(build, "build");
    function convert2(target) {
      var length = target.length, paddingOffset = length % 3, array = new Array(length + paddingOffset), l2, i;
      if (typeof target !== "string") {
        var uniqueTokens = /* @__PURE__ */ Object.create(null);
        for (i = 0; i < length; i++) {
          if (!uniqueTokens[target[i]])
            uniqueTokens[target[i]] = true;
        }
        var alphabet = /* @__PURE__ */ Object.create(null), sortedUniqueTokens = Object.keys(uniqueTokens).sort();
        for (i = 0, l2 = sortedUniqueTokens.length; i < l2; i++)
          alphabet[sortedUniqueTokens[i]] = i + 1;
        for (i = 0; i < length; i++) {
          array[i] = alphabet[target[i]];
        }
      } else {
        for (i = 0; i < length; i++)
          array[i] = target.charCodeAt(i);
      }
      for (i = length; i < length + paddingOffset; i++)
        array[i] = 0;
      return array;
    }
    __name(convert2, "convert");
    function SuffixArray2(string) {
      this.hasArbitrarySequence = typeof string !== "string";
      this.string = string;
      this.length = string.length;
      this.array = build(convert2(string), this.length);
    }
    __name(SuffixArray2, "SuffixArray");
    SuffixArray2.prototype.toString = function() {
      return this.array.join(",");
    };
    SuffixArray2.prototype.toJSON = function() {
      return this.array;
    };
    SuffixArray2.prototype.inspect = function() {
      var array = new Array(this.length);
      for (var i = 0; i < this.length; i++)
        array[i] = this.string.slice(this.array[i]);
      Object.defineProperty(array, "constructor", {
        value: SuffixArray2,
        enumerable: false
      });
      return array;
    };
    if (typeof Symbol !== "undefined")
      SuffixArray2.prototype[Symbol.for("nodejs.util.inspect.custom")] = SuffixArray2.prototype.inspect;
    function GeneralizedSuffixArray2(strings) {
      this.hasArbitrarySequence = typeof strings[0] !== "string";
      this.size = strings.length;
      if (this.hasArbitrarySequence) {
        this.text = [];
        for (var i = 0, l2 = this.size; i < l2; i++) {
          this.text.push.apply(this.text, strings[i]);
          if (i < l2 - 1)
            this.text.push(SEPARATOR);
        }
      } else {
        this.text = strings.join(SEPARATOR);
      }
      this.firstLength = strings[0].length;
      this.length = this.text.length;
      this.array = build(convert2(this.text), this.length);
    }
    __name(GeneralizedSuffixArray2, "GeneralizedSuffixArray");
    GeneralizedSuffixArray2.prototype.longestCommonSubsequence = function() {
      var lcs = this.hasArbitrarySequence ? [] : "", lcp, i, j, s2, t2;
      for (i = 1; i < this.length; i++) {
        s2 = this.array[i];
        t2 = this.array[i - 1];
        if (s2 < this.firstLength && t2 < this.firstLength)
          continue;
        if (s2 > this.firstLength && t2 > this.firstLength)
          continue;
        lcp = Math.min(this.length - s2, this.length - t2);
        for (j = 0; j < lcp; j++) {
          if (this.text[s2 + j] !== this.text[t2 + j]) {
            lcp = j;
            break;
          }
        }
        if (lcp > lcs.length)
          lcs = this.text.slice(s2, s2 + lcp);
      }
      return lcs;
    };
    GeneralizedSuffixArray2.prototype.toString = function() {
      return this.array.join(",");
    };
    GeneralizedSuffixArray2.prototype.toJSON = function() {
      return this.array;
    };
    GeneralizedSuffixArray2.prototype.inspect = function() {
      var array = new Array(this.length);
      for (var i = 0; i < this.length; i++)
        array[i] = this.text.slice(this.array[i]);
      Object.defineProperty(array, "constructor", {
        value: GeneralizedSuffixArray2,
        enumerable: false
      });
      return array;
    };
    if (typeof Symbol !== "undefined")
      GeneralizedSuffixArray2.prototype[Symbol.for("nodejs.util.inspect.custom")] = GeneralizedSuffixArray2.prototype.inspect;
    SuffixArray2.GeneralizedSuffixArray = GeneralizedSuffixArray2;
    module2.exports = SuffixArray2;
  }
});

// node_modules/obliterator/iterator.js
var require_iterator = __commonJS({
  "node_modules/obliterator/iterator.js"(exports2, module2) {
    init_esbuild_shims();
    function Iterator(next) {
      if (typeof next !== "function")
        throw new Error("obliterator/iterator: expecting a function!");
      this.next = next;
    }
    __name(Iterator, "Iterator");
    if (typeof Symbol !== "undefined")
      Iterator.prototype[Symbol.iterator] = function() {
        return this;
      };
    Iterator.of = function() {
      var args = arguments, l2 = args.length, i = 0;
      return new Iterator(function() {
        if (i >= l2) return { done: true };
        return { done: false, value: args[i++] };
      });
    };
    Iterator.empty = function() {
      var iterator = new Iterator(function() {
        return { done: true };
      });
      return iterator;
    };
    Iterator.fromSequence = function(sequence) {
      var i = 0, l2 = sequence.length;
      return new Iterator(function() {
        if (i >= l2) return { done: true };
        return { done: false, value: sequence[i++] };
      });
    };
    Iterator.is = function(value) {
      if (value instanceof Iterator) return true;
      return typeof value === "object" && value !== null && typeof value.next === "function";
    };
    module2.exports = Iterator;
  }
});

// node_modules/mnemonist/vector.js
var require_vector = __commonJS({
  "node_modules/mnemonist/vector.js"(exports2, module2) {
    init_esbuild_shims();
    var Iterator = require_iterator();
    var forEach2 = require_foreach();
    var iterables = require_iterables();
    var typed = require_typed_arrays();
    var DEFAULT_GROWING_POLICY = /* @__PURE__ */ __name(function(currentCapacity) {
      return Math.max(1, Math.ceil(currentCapacity * 1.5));
    }, "DEFAULT_GROWING_POLICY");
    var pointerArrayFactory = /* @__PURE__ */ __name(function(capacity) {
      var PointerArray = typed.getPointerArray(capacity);
      return new PointerArray(capacity);
    }, "pointerArrayFactory");
    function Vector2(ArrayClass, initialCapacityOrOptions) {
      if (arguments.length < 1)
        throw new Error("mnemonist/vector: expecting at least a byte array constructor.");
      var initialCapacity = initialCapacityOrOptions || 0, policy = DEFAULT_GROWING_POLICY, initialLength = 0, factory = false;
      if (typeof initialCapacityOrOptions === "object") {
        initialCapacity = initialCapacityOrOptions.initialCapacity || 0;
        initialLength = initialCapacityOrOptions.initialLength || 0;
        policy = initialCapacityOrOptions.policy || policy;
        factory = initialCapacityOrOptions.factory === true;
      }
      this.factory = factory ? ArrayClass : null;
      this.ArrayClass = ArrayClass;
      this.length = initialLength;
      this.capacity = Math.max(initialLength, initialCapacity);
      this.policy = policy;
      this.array = new ArrayClass(this.capacity);
    }
    __name(Vector2, "Vector");
    Vector2.prototype.set = function(index, value) {
      if (this.length < index)
        throw new Error("Vector(" + this.ArrayClass.name + ").set: index out of bounds.");
      this.array[index] = value;
      return this;
    };
    Vector2.prototype.get = function(index) {
      if (this.length < index)
        return void 0;
      return this.array[index];
    };
    Vector2.prototype.applyPolicy = function(override) {
      var newCapacity = this.policy(override || this.capacity);
      if (typeof newCapacity !== "number" || newCapacity < 0)
        throw new Error("mnemonist/vector.applyPolicy: policy returned an invalid value (expecting a positive integer).");
      if (newCapacity <= this.capacity)
        throw new Error("mnemonist/vector.applyPolicy: policy returned a less or equal capacity to allocate.");
      return newCapacity;
    };
    Vector2.prototype.reallocate = function(capacity) {
      if (capacity === this.capacity)
        return this;
      var oldArray = this.array;
      if (capacity < this.length)
        this.length = capacity;
      if (capacity > this.capacity) {
        if (this.factory === null)
          this.array = new this.ArrayClass(capacity);
        else
          this.array = this.factory(capacity);
        if (typed.isTypedArray(this.array)) {
          this.array.set(oldArray, 0);
        } else {
          for (var i = 0, l2 = this.length; i < l2; i++)
            this.array[i] = oldArray[i];
        }
      } else {
        this.array = oldArray.slice(0, capacity);
      }
      this.capacity = capacity;
      return this;
    };
    Vector2.prototype.grow = function(capacity) {
      var newCapacity;
      if (typeof capacity === "number") {
        if (this.capacity >= capacity)
          return this;
        newCapacity = this.capacity;
        while (newCapacity < capacity)
          newCapacity = this.applyPolicy(newCapacity);
        this.reallocate(newCapacity);
        return this;
      }
      newCapacity = this.applyPolicy();
      this.reallocate(newCapacity);
      return this;
    };
    Vector2.prototype.resize = function(length) {
      if (length === this.length)
        return this;
      if (length < this.length) {
        this.length = length;
        return this;
      }
      this.length = length;
      this.reallocate(length);
      return this;
    };
    Vector2.prototype.push = function(value) {
      if (this.capacity === this.length)
        this.grow();
      this.array[this.length++] = value;
      return this.length;
    };
    Vector2.prototype.pop = function() {
      if (this.length === 0)
        return;
      return this.array[--this.length];
    };
    Vector2.prototype.values = function() {
      var items = this.array, l2 = this.length, i = 0;
      return new Iterator(function() {
        if (i >= l2)
          return {
            done: true
          };
        var value = items[i];
        i++;
        return {
          value,
          done: false
        };
      });
    };
    Vector2.prototype.entries = function() {
      var items = this.array, l2 = this.length, i = 0;
      return new Iterator(function() {
        if (i >= l2)
          return {
            done: true
          };
        var value = items[i];
        return {
          value: [i++, value],
          done: false
        };
      });
    };
    if (typeof Symbol !== "undefined")
      Vector2.prototype[Symbol.iterator] = Vector2.prototype.values;
    Vector2.prototype.inspect = function() {
      var proxy = this.array.slice(0, this.length);
      proxy.type = this.array.constructor.name;
      proxy.items = this.length;
      proxy.capacity = this.capacity;
      Object.defineProperty(proxy, "constructor", {
        value: Vector2,
        enumerable: false
      });
      return proxy;
    };
    if (typeof Symbol !== "undefined")
      Vector2.prototype[Symbol.for("nodejs.util.inspect.custom")] = Vector2.prototype.inspect;
    Vector2.from = function(iterable, ArrayClass, capacity) {
      if (arguments.length < 3) {
        capacity = iterables.guessLength(iterable);
        if (typeof capacity !== "number")
          throw new Error("mnemonist/vector.from: could not guess iterable length. Please provide desired capacity as last argument.");
      }
      var vector = new Vector2(ArrayClass, capacity);
      forEach2(iterable, function(value) {
        vector.push(value);
      });
      return vector;
    };
    function subClass(ArrayClass) {
      var SubClass = /* @__PURE__ */ __name(function(initialCapacityOrOptions) {
        Vector2.call(this, ArrayClass, initialCapacityOrOptions);
      }, "SubClass");
      for (var k in Vector2.prototype) {
        if (Vector2.prototype.hasOwnProperty(k))
          SubClass.prototype[k] = Vector2.prototype[k];
      }
      SubClass.from = function(iterable, capacity) {
        return Vector2.from(iterable, ArrayClass, capacity);
      };
      if (typeof Symbol !== "undefined")
        SubClass.prototype[Symbol.iterator] = SubClass.prototype.values;
      return SubClass;
    }
    __name(subClass, "subClass");
    Vector2.Int8Vector = subClass(Int8Array);
    Vector2.Uint8Vector = subClass(Uint8Array);
    Vector2.Uint8ClampedVector = subClass(Uint8ClampedArray);
    Vector2.Int16Vector = subClass(Int16Array);
    Vector2.Uint16Vector = subClass(Uint16Array);
    Vector2.Int32Vector = subClass(Int32Array);
    Vector2.Uint32Vector = subClass(Uint32Array);
    Vector2.Float32Vector = subClass(Float32Array);
    Vector2.Float64Vector = subClass(Float64Array);
    Vector2.PointerVector = subClass(pointerArrayFactory);
    module2.exports = Vector2;
  }
});

// node_modules/mnemonist/fixed-deque.js
var require_fixed_deque = __commonJS({
  "node_modules/mnemonist/fixed-deque.js"(exports2, module2) {
    init_esbuild_shims();
    var iterables = require_iterables();
    var Iterator = require_iterator();
    function FixedDeque(ArrayClass, capacity) {
      if (arguments.length < 2)
        throw new Error("mnemonist/fixed-deque: expecting an Array class and a capacity.");
      if (typeof capacity !== "number" || capacity <= 0)
        throw new Error("mnemonist/fixed-deque: `capacity` should be a positive number.");
      this.ArrayClass = ArrayClass;
      this.capacity = capacity;
      this.items = new ArrayClass(this.capacity);
      this.clear();
    }
    __name(FixedDeque, "FixedDeque");
    FixedDeque.prototype.clear = function() {
      this.start = 0;
      this.size = 0;
    };
    FixedDeque.prototype.push = function(item) {
      if (this.size === this.capacity)
        throw new Error("mnemonist/fixed-deque.push: deque capacity (" + this.capacity + ") exceeded!");
      var index = this.start + this.size;
      if (index >= this.capacity)
        index -= this.capacity;
      this.items[index] = item;
      return ++this.size;
    };
    FixedDeque.prototype.unshift = function(item) {
      if (this.size === this.capacity)
        throw new Error("mnemonist/fixed-deque.unshift: deque capacity (" + this.capacity + ") exceeded!");
      var index = this.start - 1;
      if (this.start === 0)
        index = this.capacity - 1;
      this.items[index] = item;
      this.start = index;
      return ++this.size;
    };
    FixedDeque.prototype.pop = function() {
      if (this.size === 0)
        return;
      this.size--;
      var index = this.start + this.size;
      if (index >= this.capacity)
        index -= this.capacity;
      return this.items[index];
    };
    FixedDeque.prototype.shift = function() {
      if (this.size === 0)
        return;
      var index = this.start;
      this.size--;
      this.start++;
      if (this.start === this.capacity)
        this.start = 0;
      return this.items[index];
    };
    FixedDeque.prototype.peekFirst = function() {
      if (this.size === 0)
        return;
      return this.items[this.start];
    };
    FixedDeque.prototype.peekLast = function() {
      if (this.size === 0)
        return;
      var index = this.start + this.size - 1;
      if (index >= this.capacity)
        index -= this.capacity;
      return this.items[index];
    };
    FixedDeque.prototype.get = function(index) {
      if (this.size === 0 || index >= this.capacity)
        return;
      index = this.start + index;
      if (index >= this.capacity)
        index -= this.capacity;
      return this.items[index];
    };
    FixedDeque.prototype.forEach = function(callback, scope) {
      scope = arguments.length > 1 ? scope : this;
      var c3 = this.capacity, l2 = this.size, i = this.start, j = 0;
      while (j < l2) {
        callback.call(scope, this.items[i], j, this);
        i++;
        j++;
        if (i === c3)
          i = 0;
      }
    };
    FixedDeque.prototype.toArray = function() {
      var offset = this.start + this.size;
      if (offset < this.capacity)
        return this.items.slice(this.start, offset);
      var array = new this.ArrayClass(this.size), c3 = this.capacity, l2 = this.size, i = this.start, j = 0;
      while (j < l2) {
        array[j] = this.items[i];
        i++;
        j++;
        if (i === c3)
          i = 0;
      }
      return array;
    };
    FixedDeque.prototype.values = function() {
      var items = this.items, c3 = this.capacity, l2 = this.size, i = this.start, j = 0;
      return new Iterator(function() {
        if (j >= l2)
          return {
            done: true
          };
        var value = items[i];
        i++;
        j++;
        if (i === c3)
          i = 0;
        return {
          value,
          done: false
        };
      });
    };
    FixedDeque.prototype.entries = function() {
      var items = this.items, c3 = this.capacity, l2 = this.size, i = this.start, j = 0;
      return new Iterator(function() {
        if (j >= l2)
          return {
            done: true
          };
        var value = items[i];
        i++;
        if (i === c3)
          i = 0;
        return {
          value: [j++, value],
          done: false
        };
      });
    };
    if (typeof Symbol !== "undefined")
      FixedDeque.prototype[Symbol.iterator] = FixedDeque.prototype.values;
    FixedDeque.prototype.inspect = function() {
      var array = this.toArray();
      array.type = this.ArrayClass.name;
      array.capacity = this.capacity;
      Object.defineProperty(array, "constructor", {
        value: FixedDeque,
        enumerable: false
      });
      return array;
    };
    if (typeof Symbol !== "undefined")
      FixedDeque.prototype[Symbol.for("nodejs.util.inspect.custom")] = FixedDeque.prototype.inspect;
    FixedDeque.from = function(iterable, ArrayClass, capacity) {
      if (arguments.length < 3) {
        capacity = iterables.guessLength(iterable);
        if (typeof capacity !== "number")
          throw new Error("mnemonist/fixed-deque.from: could not guess iterable length. Please provide desired capacity as last argument.");
      }
      var deque = new FixedDeque(ArrayClass, capacity);
      if (iterables.isArrayLike(iterable)) {
        var i, l2;
        for (i = 0, l2 = iterable.length; i < l2; i++)
          deque.items[i] = iterable[i];
        deque.size = l2;
        return deque;
      }
      iterables.forEach(iterable, function(value) {
        deque.push(value);
      });
      return deque;
    };
    module2.exports = FixedDeque;
  }
});

// node_modules/mnemonist/index.mjs
var import_fibonacci_heap, import_heap, import_suffix_array, import_vector, import_fixed_deque, MinFibonacciHeap, MaxFibonacciHeap, MinHeap, MaxHeap, GeneralizedSuffixArray, Uint8Vector, Uint8ClampedVector, Int8Vector, Uint16Vector, Int16Vector, Uint32Vector, Int32Vector, Float32Vector, Float64Vector, PointerVector;
var init_mnemonist = __esm({
  "node_modules/mnemonist/index.mjs"() {
    init_esbuild_shims();
    import_fibonacci_heap = __toESM(require_fibonacci_heap(), 1);
    import_heap = __toESM(require_heap(), 1);
    import_suffix_array = __toESM(require_suffix_array(), 1);
    import_vector = __toESM(require_vector(), 1);
    import_fixed_deque = __toESM(require_fixed_deque(), 1);
    MinFibonacciHeap = import_fibonacci_heap.default.MinFibonacciHeap;
    MaxFibonacciHeap = import_fibonacci_heap.default.MaxFibonacciHeap;
    MinHeap = import_heap.default.MinHeap;
    MaxHeap = import_heap.default.MaxHeap;
    GeneralizedSuffixArray = import_suffix_array.default.GeneralizedSuffixArray;
    Uint8Vector = import_vector.default.Uint8Vector;
    Uint8ClampedVector = import_vector.default.Uint8ClampedVector;
    Int8Vector = import_vector.default.Int8Vector;
    Uint16Vector = import_vector.default.Uint16Vector;
    Int16Vector = import_vector.default.Int16Vector;
    Uint32Vector = import_vector.default.Uint32Vector;
    Int32Vector = import_vector.default.Int32Vector;
    Float32Vector = import_vector.default.Float32Vector;
    Float64Vector = import_vector.default.Float64Vector;
    PointerVector = import_vector.default.PointerVector;
  }
});

// packages/core/dist/src/telemetry/qwen-logger/qwen-logger.js
import { Buffer as Buffer3 } from "buffer";
import * as https from "https";
import * as os9 from "node:os";
var import_https_proxy_agent, USAGE_STATS_HOSTNAME, USAGE_STATS_PATH, RUN_APP_ID, FLUSH_INTERVAL_MS, MAX_EVENTS, MAX_RETRY_EVENTS, QwenLogger;
var init_qwen_logger = __esm({
  "packages/core/dist/src/telemetry/qwen-logger/qwen-logger.js"() {
    "use strict";
    init_esbuild_shims();
    import_https_proxy_agent = __toESM(require_dist2(), 1);
    init_types3();
    init_safeJsonStringify();
    init_installationManager();
    init_mnemonist();
    init_contentGenerator();
    USAGE_STATS_HOSTNAME = "gb4w8c3ygj-default-sea.rum.aliyuncs.com";
    USAGE_STATS_PATH = "/";
    RUN_APP_ID = "gb4w8c3ygj@851d5d500f08f92";
    FLUSH_INTERVAL_MS = 1e3 * 60;
    MAX_EVENTS = 1e3;
    MAX_RETRY_EVENTS = 100;
    QwenLogger = class _QwenLogger {
      static {
        __name(this, "QwenLogger");
      }
      static instance;
      config;
      installationManager;
      /**
       * Queue of pending events that need to be flushed to the server. New events
       * are added to this queue and then flushed on demand (via `flushToRum`)
       */
      events;
      /**
       * The last time that the events were successfully flushed to the server.
       */
      lastFlushTime = Date.now();
      userId;
      sessionId;
      /**
       * The value is true when there is a pending flush happening. This prevents
       * concurrent flush operations.
       */
      isFlushInProgress = false;
      /**
       * This value is true when a flush was requested during an ongoing flush.
       */
      pendingFlush = false;
      isShutdown = false;
      constructor(config) {
        this.config = config;
        this.events = new import_fixed_deque.default(Array, MAX_EVENTS);
        this.installationManager = new InstallationManager();
        this.userId = this.generateUserId();
        this.sessionId = typeof this.config?.getSessionId === "function" ? this.config.getSessionId() : "";
      }
      generateUserId() {
        const installationId = this.installationManager.getInstallationId();
        return `user-${installationId ?? "unknown"}`;
      }
      static getInstance(config) {
        if (config === void 0 || !config?.getUsageStatisticsEnabled())
          return void 0;
        if (!_QwenLogger.instance) {
          _QwenLogger.instance = new _QwenLogger(config);
          process.on("exit", _QwenLogger.instance.shutdown.bind(_QwenLogger.instance));
        }
        return _QwenLogger.instance;
      }
      enqueueLogEvent(event) {
        try {
          const wasAtCapacity = this.events.size >= MAX_EVENTS;
          if (wasAtCapacity) {
            this.events.shift();
          }
          this.events.push(event);
          if (wasAtCapacity && this.config?.getDebugMode()) {
            console.debug(`QwenLogger: Dropped old event to prevent memory leak (queue size: ${this.events.size})`);
          }
        } catch (error) {
          if (this.config?.getDebugMode()) {
            console.error("QwenLogger: Failed to enqueue log event.", error);
          }
        }
      }
      createRumEvent(eventType, type, name3, properties) {
        return {
          timestamp: Date.now(),
          event_type: eventType,
          type,
          name: name3,
          ...properties || {}
        };
      }
      createViewEvent(type, name3, properties) {
        return this.createRumEvent("view", type, name3, properties);
      }
      createActionEvent(type, name3, properties) {
        return this.createRumEvent("action", type, name3, properties);
      }
      createResourceEvent(type, name3, properties) {
        return this.createRumEvent("resource", type, name3, properties);
      }
      createExceptionEvent(type, name3, properties) {
        return this.createRumEvent("exception", type, name3, properties);
      }
      getOsMetadata() {
        return {
          type: os9.platform(),
          version: os9.release()
        };
      }
      async createRumPayload() {
        const authType = this.config?.getAuthType();
        const version2 = this.config?.getCliVersion() || "unknown";
        const osMetadata = this.getOsMetadata();
        return {
          app: {
            id: RUN_APP_ID,
            env: process.env["DEBUG"] ? "dev" : "prod",
            version: version2 || "unknown",
            type: "cli"
          },
          user: {
            id: this.userId
          },
          session: {
            id: this.sessionId
          },
          view: {
            id: this.sessionId,
            name: "qwen-code-cli"
          },
          os: osMetadata,
          events: this.events.toArray(),
          properties: {
            auth_type: authType,
            model: this.config?.getModel(),
            base_url: authType === AuthType2.USE_OPENAI ? this.config?.getContentGeneratorConfig().baseUrl || "" : ""
          },
          _v: `qwen-code@${version2}`
        };
      }
      flushIfNeeded() {
        if (Date.now() - this.lastFlushTime < FLUSH_INTERVAL_MS) {
          return;
        }
        this.flushToRum().catch((error) => {
          if (this.config?.getDebugMode()) {
            console.debug("Error flushing to RUM:", error);
          }
        });
      }
      async flushToRum() {
        if (this.isFlushInProgress) {
          if (this.config?.getDebugMode()) {
            console.debug("QwenLogger: Flush already in progress, marking pending flush.");
          }
          this.pendingFlush = true;
          return Promise.resolve({});
        }
        this.isFlushInProgress = true;
        if (this.config?.getDebugMode()) {
          console.log("Flushing log events to RUM.");
        }
        if (this.events.size === 0) {
          this.isFlushInProgress = false;
          return {};
        }
        const eventsToSend = this.events.toArray();
        this.events.clear();
        const rumPayload = await this.createRumPayload();
        rumPayload.events = eventsToSend;
        try {
          await new Promise((resolve24, reject) => {
            const body = safeJsonStringify(rumPayload);
            const options2 = {
              hostname: USAGE_STATS_HOSTNAME,
              path: USAGE_STATS_PATH,
              method: "POST",
              headers: {
                "Content-Length": Buffer3.byteLength(body),
                "Content-Type": "text/plain;charset=UTF-8"
              }
            };
            const bufs = [];
            const req = https.request({
              ...options2,
              agent: this.getProxyAgent()
            }, (res) => {
              if (res.statusCode && (res.statusCode < 200 || res.statusCode >= 300)) {
                const err = new Error(`Request failed with status ${res.statusCode}`);
                res.resume();
                return reject(err);
              }
              res.on("data", (buf) => bufs.push(buf));
              res.on("end", () => resolve24(Buffer3.concat(bufs)));
            });
            req.on("error", reject);
            req.end(body);
          });
          this.lastFlushTime = Date.now();
          return {};
        } catch (error) {
          if (this.config?.getDebugMode()) {
            console.error("RUM flush failed.", error);
          }
          this.requeueFailedEvents(eventsToSend);
          return {};
        } finally {
          this.isFlushInProgress = false;
          if (this.pendingFlush) {
            this.pendingFlush = false;
            this.flushToRum().catch((error) => {
              if (this.config?.getDebugMode()) {
                console.debug("Error in pending flush to RUM:", error);
              }
            });
          }
        }
      }
      // session events
      logStartSessionEvent(event) {
        const applicationEvent = this.createViewEvent("session", "session_start", {
          properties: {
            model: event.model
          },
          snapshots: JSON.stringify({
            embedding_model: event.embedding_model,
            sandbox_enabled: event.sandbox_enabled,
            core_tools_enabled: event.core_tools_enabled,
            approval_mode: event.approval_mode,
            api_key_enabled: event.api_key_enabled,
            vertex_ai_enabled: event.vertex_ai_enabled,
            debug_enabled: event.debug_enabled,
            mcp_servers: event.mcp_servers,
            telemetry_enabled: event.telemetry_enabled,
            telemetry_log_user_prompts_enabled: event.telemetry_log_user_prompts_enabled
          })
        });
        this.enqueueLogEvent(applicationEvent);
        this.flushToRum().catch((error) => {
          if (this.config?.getDebugMode()) {
            console.debug("Error flushing to RUM:", error);
          }
        });
      }
      logEndSessionEvent(_event) {
        const applicationEvent = this.createViewEvent("session", "session_end", {});
        this.enqueueLogEvent(applicationEvent);
        this.flushToRum().catch((error) => {
          if (this.config?.getDebugMode()) {
            console.debug("Error flushing to RUM:", error);
          }
        });
      }
      logConversationFinishedEvent(event) {
        const rumEvent = this.createActionEvent("conversation", "conversation_finished", {
          snapshots: JSON.stringify({
            approval_mode: event.approvalMode,
            turn_count: event.turnCount
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      // user action events
      logNewPromptEvent(event) {
        const rumEvent = this.createActionEvent("user", "new_prompt", {
          properties: {
            auth_type: event.auth_type,
            prompt_id: event.prompt_id
          },
          snapshots: JSON.stringify({
            prompt_length: event.prompt_length
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logSlashCommandEvent(event) {
        const rumEvent = this.createActionEvent("user", "slash_command", {
          snapshots: JSON.stringify({
            command: event.command,
            subcommand: event.subcommand
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logModelSlashCommandEvent(event) {
        const rumEvent = this.createActionEvent("user", "model_slash_command", {
          snapshots: JSON.stringify({
            model_name: event.model_name
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      // tool call events
      logToolCallEvent(event) {
        const rumEvent = this.createActionEvent("tool", `tool_call#${event.function_name}`, {
          properties: {
            prompt_id: event.prompt_id,
            response_id: event.response_id
          },
          snapshots: JSON.stringify({
            function_name: event.function_name,
            decision: event.decision,
            success: event.success,
            duration_ms: event.duration_ms,
            error: event.error,
            error_type: event.error_type
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logFileOperationEvent(event) {
        const rumEvent = this.createActionEvent("tool", `file_operation#${event.tool_name}`, {
          snapshots: JSON.stringify({
            tool_name: event.tool_name,
            operation: event.operation,
            lines: event.lines,
            mimetype: event.mimetype,
            extension: event.extension,
            programming_language: event.programming_language
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logSubagentExecutionEvent(event) {
        const rumEvent = this.createActionEvent("tool", "subagent_execution", {
          snapshots: JSON.stringify({
            subagent_name: event.subagent_name,
            status: event.status,
            terminate_reason: event.terminate_reason,
            execution_summary: event.execution_summary
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logToolOutputTruncatedEvent(event) {
        const rumEvent = this.createActionEvent("tool", "tool_output_truncated", {
          snapshots: JSON.stringify({
            tool_name: event.tool_name,
            original_content_length: event.original_content_length,
            truncated_content_length: event.truncated_content_length,
            threshold: event.threshold,
            lines: event.lines
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      // api events
      logApiRequestEvent(event) {
        const rumEvent = this.createResourceEvent("api", "api_request", {
          properties: {
            model: event.model,
            prompt_id: event.prompt_id
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logApiResponseEvent(event) {
        const rumEvent = this.createResourceEvent("api", "api_response", {
          status_code: event.status_code?.toString() ?? "",
          duration: event.duration_ms,
          success: 1,
          trace_id: event.response_id,
          properties: {
            auth_type: event.auth_type,
            model: event.model,
            prompt_id: event.prompt_id
          },
          snapshots: JSON.stringify({
            input_token_count: event.input_token_count,
            output_token_count: event.output_token_count,
            cached_content_token_count: event.cached_content_token_count,
            thoughts_token_count: event.thoughts_token_count,
            tool_token_count: event.tool_token_count
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logApiCancelEvent(event) {
        const rumEvent = this.createActionEvent("api", "api_cancel", {
          properties: {
            model: event.model,
            prompt_id: event.prompt_id,
            auth_type: event.auth_type
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logApiErrorEvent(event) {
        const rumEvent = this.createResourceEvent("api", "api_error", {
          status_code: event.status_code?.toString() ?? "",
          duration: event.duration_ms,
          success: 0,
          message: event.error,
          trace_id: event.response_id,
          properties: {
            auth_type: event.auth_type,
            model: event.model,
            prompt_id: event.prompt_id
          },
          snapshots: JSON.stringify({
            error_type: event.error_type
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      // error events
      logInvalidChunkEvent(event) {
        const rumEvent = this.createExceptionEvent("error", "invalid_chunk", {
          subtype: "invalid_chunk",
          message: event.error_message
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logContentRetryFailureEvent(event) {
        const rumEvent = this.createExceptionEvent("error", "content_retry_failure", {
          subtype: "content_retry_failure",
          message: `Content retry failed after ${event.total_attempts} attempts`,
          snapshots: JSON.stringify({
            total_attempts: event.total_attempts,
            final_error_type: event.final_error_type,
            total_duration_ms: event.total_duration_ms
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logMalformedJsonResponseEvent(event) {
        const rumEvent = this.createExceptionEvent("error", "malformed_json_response", {
          subtype: "malformed_json_response",
          properties: {
            model: event.model
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logLoopDetectedEvent(event) {
        const rumEvent = this.createExceptionEvent("error", "loop_detected", {
          subtype: "loop_detected",
          properties: {
            prompt_id: event.prompt_id
          },
          snapshots: JSON.stringify({
            loop_type: event.loop_type
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logKittySequenceOverflowEvent(event) {
        const rumEvent = this.createExceptionEvent("overflow", "kitty_sequence_overflow", {
          subtype: "kitty_sequence_overflow",
          snapshots: JSON.stringify({
            sequence_length: event.sequence_length,
            truncated_sequence: event.truncated_sequence
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      // ide events
      logIdeConnectionEvent(event) {
        const rumEvent = this.createActionEvent("ide", "ide_connection", {
          snapshots: JSON.stringify({ connection_type: event.connection_type })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      // extension events
      logExtensionInstallEvent(event) {
        const rumEvent = this.createActionEvent("extension", "extension_install", {
          snapshots: JSON.stringify({
            extension_name: event.extension_name,
            extension_version: event.extension_version,
            extension_source: event.extension_source,
            status: event.status
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logExtensionUninstallEvent(event) {
        const rumEvent = this.createActionEvent("extension", "extension_uninstall", {
          snapshots: JSON.stringify({
            extension_name: event.extension_name,
            status: event.status
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logExtensionEnableEvent(event) {
        const rumEvent = this.createActionEvent("extension", "extension_enable", {
          snapshots: JSON.stringify({
            extension_name: event.extension_name,
            setting_scope: event.setting_scope
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logExtensionDisableEvent(event) {
        const rumEvent = this.createActionEvent("extension", "extension_disable", {
          snapshots: JSON.stringify({
            extension_name: event.extension_name,
            setting_scope: event.setting_scope
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logAuthEvent(event) {
        const snapshots = {
          auth_type: event.auth_type,
          action_type: event.action_type,
          status: event.status
        };
        if (event.error_message) {
          snapshots["error_message"] = event.error_message;
        }
        const rumEvent = this.createActionEvent("auth", "auth", {
          snapshots: JSON.stringify(snapshots)
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      // misc events
      logFlashFallbackEvent(event) {
        const rumEvent = this.createActionEvent("misc", "flash_fallback", {
          properties: {
            auth_type: event.auth_type
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logRipgrepFallbackEvent(event) {
        const rumEvent = this.createActionEvent("misc", "ripgrep_fallback", {
          snapshots: JSON.stringify({
            platform: process.platform,
            arch: process.arch,
            use_ripgrep: event.use_ripgrep,
            use_builtin_ripgrep: event.use_builtin_ripgrep,
            error: event.error ?? void 0
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logLoopDetectionDisabledEvent() {
        const rumEvent = this.createActionEvent("misc", "loop_detection_disabled", {});
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logNextSpeakerCheck(event) {
        const rumEvent = this.createActionEvent("misc", "next_speaker_check", {
          properties: {
            prompt_id: event.prompt_id
          },
          snapshots: JSON.stringify({
            finish_reason: event.finish_reason,
            result: event.result
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logChatCompressionEvent(event) {
        const rumEvent = this.createActionEvent("misc", "chat_compression", {
          snapshots: JSON.stringify({
            tokens_before: event.tokens_before,
            tokens_after: event.tokens_after
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logContentRetryEvent(event) {
        const rumEvent = this.createActionEvent("misc", "content_retry", {
          snapshots: JSON.stringify({
            attempt_number: event.attempt_number,
            error_type: event.error_type,
            retry_delay_ms: event.retry_delay_ms
          })
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      getProxyAgent() {
        const proxyUrl = this.config?.getProxy();
        if (!proxyUrl)
          return void 0;
        if (proxyUrl.startsWith("http")) {
          return new import_https_proxy_agent.HttpsProxyAgent(proxyUrl);
        } else {
          throw new Error("Unsupported proxy type");
        }
      }
      shutdown() {
        if (this.isShutdown)
          return;
        this.isShutdown = true;
        const event = new EndSessionEvent(this.config);
        this.logEndSessionEvent(event);
      }
      requeueFailedEvents(eventsToSend) {
        const eventsToRetry = eventsToSend.slice(-MAX_RETRY_EVENTS);
        if (eventsToSend.length > MAX_RETRY_EVENTS && this.config?.getDebugMode()) {
          console.warn(`QwenLogger: Dropping ${eventsToSend.length - MAX_RETRY_EVENTS} events due to retry queue limit. Total events: ${eventsToSend.length}, keeping: ${MAX_RETRY_EVENTS}`);
        }
        const availableSpace = MAX_EVENTS - this.events.size;
        const numEventsToRequeue = Math.min(eventsToRetry.length, availableSpace);
        if (numEventsToRequeue === 0) {
          if (this.config?.getDebugMode()) {
            console.debug(`QwenLogger: No events re-queued (queue size: ${this.events.size})`);
          }
          return;
        }
        const eventsToRequeue = eventsToRetry.slice(eventsToRetry.length - numEventsToRequeue);
        for (let i = eventsToRequeue.length - 1; i >= 0; i--) {
          this.events.unshift(eventsToRequeue[i]);
        }
        while (this.events.size > MAX_EVENTS) {
          this.events.pop();
        }
        if (this.config?.getDebugMode()) {
          console.debug(`QwenLogger: Re-queued ${numEventsToRequeue} events for retry (queue size: ${this.events.size})`);
        }
      }
    };
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/OTLPExporterBase.js
var OTLPExporterBase;
var init_OTLPExporterBase = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/OTLPExporterBase.js"() {
    init_esbuild_shims();
    OTLPExporterBase = class {
      static {
        __name(this, "OTLPExporterBase");
      }
      _delegate;
      constructor(_delegate) {
        this._delegate = _delegate;
      }
      /**
       * Export items.
       * @param items
       * @param resultCallback
       */
      export(items, resultCallback) {
        this._delegate.export(items, resultCallback);
      }
      forceFlush() {
        return this._delegate.forceFlush();
      }
      shutdown() {
        return this._delegate.shutdown();
      }
    };
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/types.js
var OTLPExporterError;
var init_types5 = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/types.js"() {
    init_esbuild_shims();
    OTLPExporterError = class extends Error {
      static {
        __name(this, "OTLPExporterError");
      }
      code;
      name = "OTLPExporterError";
      data;
      constructor(message, code2, data) {
        super(message);
        this.data = data;
        this.code = code2;
      }
    };
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/shared-configuration.js
function validateTimeoutMillis(timeoutMillis) {
  if (Number.isFinite(timeoutMillis) && timeoutMillis > 0) {
    return timeoutMillis;
  }
  throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${timeoutMillis}')`);
}
function wrapStaticHeadersInFunction(headers) {
  if (headers == null) {
    return void 0;
  }
  return () => headers;
}
function mergeOtlpSharedConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) {
  return {
    timeoutMillis: validateTimeoutMillis(userProvidedConfiguration.timeoutMillis ?? fallbackConfiguration.timeoutMillis ?? defaultConfiguration.timeoutMillis),
    concurrencyLimit: userProvidedConfiguration.concurrencyLimit ?? fallbackConfiguration.concurrencyLimit ?? defaultConfiguration.concurrencyLimit,
    compression: userProvidedConfiguration.compression ?? fallbackConfiguration.compression ?? defaultConfiguration.compression
  };
}
function getSharedConfigurationDefaults() {
  return {
    timeoutMillis: 1e4,
    concurrencyLimit: 30,
    compression: "none"
  };
}
var init_shared_configuration = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/shared-configuration.js"() {
    init_esbuild_shims();
    __name(validateTimeoutMillis, "validateTimeoutMillis");
    __name(wrapStaticHeadersInFunction, "wrapStaticHeadersInFunction");
    __name(mergeOtlpSharedConfigurationWithDefaults, "mergeOtlpSharedConfigurationWithDefaults");
    __name(getSharedConfigurationDefaults, "getSharedConfigurationDefaults");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/legacy-node-configuration.js
var CompressionAlgorithm;
var init_legacy_node_configuration = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/legacy-node-configuration.js"() {
    init_esbuild_shims();
    (function(CompressionAlgorithm2) {
      CompressionAlgorithm2["NONE"] = "none";
      CompressionAlgorithm2["GZIP"] = "gzip";
    })(CompressionAlgorithm || (CompressionAlgorithm = {}));
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/bounded-queue-export-promise-handler.js
function createBoundedQueueExportPromiseHandler(options2) {
  return new BoundedQueueExportPromiseHandler(options2.concurrencyLimit);
}
var BoundedQueueExportPromiseHandler;
var init_bounded_queue_export_promise_handler = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/bounded-queue-export-promise-handler.js"() {
    init_esbuild_shims();
    BoundedQueueExportPromiseHandler = class {
      static {
        __name(this, "BoundedQueueExportPromiseHandler");
      }
      _concurrencyLimit;
      _sendingPromises = [];
      /**
       * @param concurrencyLimit maximum promises allowed in a queue at the same time.
       */
      constructor(concurrencyLimit) {
        this._concurrencyLimit = concurrencyLimit;
      }
      pushPromise(promise) {
        if (this.hasReachedLimit()) {
          throw new Error("Concurrency Limit reached");
        }
        this._sendingPromises.push(promise);
        const popPromise = /* @__PURE__ */ __name(() => {
          const index = this._sendingPromises.indexOf(promise);
          void this._sendingPromises.splice(index, 1);
        }, "popPromise");
        promise.then(popPromise, popPromise);
      }
      hasReachedLimit() {
        return this._sendingPromises.length >= this._concurrencyLimit;
      }
      async awaitAll() {
        await Promise.all(this._sendingPromises);
      }
    };
    __name(createBoundedQueueExportPromiseHandler, "createBoundedQueueExportPromiseHandler");
  }
});

// node_modules/@opentelemetry/core/build/src/trace/suppress-tracing.js
var require_suppress_tracing = __commonJS({
  "node_modules/@opentelemetry/core/build/src/trace/suppress-tracing.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isTracingSuppressed = exports2.unsuppressTracing = exports2.suppressTracing = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var SUPPRESS_TRACING_KEY = (0, api_1.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");
    function suppressTracing(context2) {
      return context2.setValue(SUPPRESS_TRACING_KEY, true);
    }
    __name(suppressTracing, "suppressTracing");
    exports2.suppressTracing = suppressTracing;
    function unsuppressTracing(context2) {
      return context2.deleteValue(SUPPRESS_TRACING_KEY);
    }
    __name(unsuppressTracing, "unsuppressTracing");
    exports2.unsuppressTracing = unsuppressTracing;
    function isTracingSuppressed(context2) {
      return context2.getValue(SUPPRESS_TRACING_KEY) === true;
    }
    __name(isTracingSuppressed, "isTracingSuppressed");
    exports2.isTracingSuppressed = isTracingSuppressed;
  }
});

// node_modules/@opentelemetry/core/build/src/baggage/constants.js
var require_constants8 = __commonJS({
  "node_modules/@opentelemetry/core/build/src/baggage/constants.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BAGGAGE_MAX_TOTAL_LENGTH = exports2.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = exports2.BAGGAGE_MAX_NAME_VALUE_PAIRS = exports2.BAGGAGE_HEADER = exports2.BAGGAGE_ITEMS_SEPARATOR = exports2.BAGGAGE_PROPERTIES_SEPARATOR = exports2.BAGGAGE_KEY_PAIR_SEPARATOR = void 0;
    exports2.BAGGAGE_KEY_PAIR_SEPARATOR = "=";
    exports2.BAGGAGE_PROPERTIES_SEPARATOR = ";";
    exports2.BAGGAGE_ITEMS_SEPARATOR = ",";
    exports2.BAGGAGE_HEADER = "baggage";
    exports2.BAGGAGE_MAX_NAME_VALUE_PAIRS = 180;
    exports2.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096;
    exports2.BAGGAGE_MAX_TOTAL_LENGTH = 8192;
  }
});

// node_modules/@opentelemetry/core/build/src/baggage/utils.js
var require_utils4 = __commonJS({
  "node_modules/@opentelemetry/core/build/src/baggage/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.parseKeyPairsIntoRecord = exports2.parsePairKeyValue = exports2.getKeyPairs = exports2.serializeKeyPairs = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var constants_1 = require_constants8();
    function serializeKeyPairs(keyPairs) {
      return keyPairs.reduce((hValue, current) => {
        const value = `${hValue}${hValue !== "" ? constants_1.BAGGAGE_ITEMS_SEPARATOR : ""}${current}`;
        return value.length > constants_1.BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value;
      }, "");
    }
    __name(serializeKeyPairs, "serializeKeyPairs");
    exports2.serializeKeyPairs = serializeKeyPairs;
    function getKeyPairs(baggage) {
      return baggage.getAllEntries().map(([key, value]) => {
        let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`;
        if (value.metadata !== void 0) {
          entry += constants_1.BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString();
        }
        return entry;
      });
    }
    __name(getKeyPairs, "getKeyPairs");
    exports2.getKeyPairs = getKeyPairs;
    function parsePairKeyValue(entry) {
      const valueProps = entry.split(constants_1.BAGGAGE_PROPERTIES_SEPARATOR);
      if (valueProps.length <= 0)
        return;
      const keyPairPart = valueProps.shift();
      if (!keyPairPart)
        return;
      const separatorIndex = keyPairPart.indexOf(constants_1.BAGGAGE_KEY_PAIR_SEPARATOR);
      if (separatorIndex <= 0)
        return;
      const key = decodeURIComponent(keyPairPart.substring(0, separatorIndex).trim());
      const value = decodeURIComponent(keyPairPart.substring(separatorIndex + 1).trim());
      let metadata;
      if (valueProps.length > 0) {
        metadata = (0, api_1.baggageEntryMetadataFromString)(valueProps.join(constants_1.BAGGAGE_PROPERTIES_SEPARATOR));
      }
      return { key, value, metadata };
    }
    __name(parsePairKeyValue, "parsePairKeyValue");
    exports2.parsePairKeyValue = parsePairKeyValue;
    function parseKeyPairsIntoRecord2(value) {
      const result = {};
      if (typeof value === "string" && value.length > 0) {
        value.split(constants_1.BAGGAGE_ITEMS_SEPARATOR).forEach((entry) => {
          const keyPair = parsePairKeyValue(entry);
          if (keyPair !== void 0 && keyPair.value.length > 0) {
            result[keyPair.key] = keyPair.value;
          }
        });
      }
      return result;
    }
    __name(parseKeyPairsIntoRecord2, "parseKeyPairsIntoRecord");
    exports2.parseKeyPairsIntoRecord = parseKeyPairsIntoRecord2;
  }
});

// node_modules/@opentelemetry/core/build/src/baggage/propagation/W3CBaggagePropagator.js
var require_W3CBaggagePropagator = __commonJS({
  "node_modules/@opentelemetry/core/build/src/baggage/propagation/W3CBaggagePropagator.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.W3CBaggagePropagator = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var suppress_tracing_1 = require_suppress_tracing();
    var constants_1 = require_constants8();
    var utils_1 = require_utils4();
    var W3CBaggagePropagator = class {
      static {
        __name(this, "W3CBaggagePropagator");
      }
      inject(context2, carrier, setter) {
        const baggage = api_1.propagation.getBaggage(context2);
        if (!baggage || (0, suppress_tracing_1.isTracingSuppressed)(context2))
          return;
        const keyPairs = (0, utils_1.getKeyPairs)(baggage).filter((pair) => {
          return pair.length <= constants_1.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS;
        }).slice(0, constants_1.BAGGAGE_MAX_NAME_VALUE_PAIRS);
        const headerValue = (0, utils_1.serializeKeyPairs)(keyPairs);
        if (headerValue.length > 0) {
          setter.set(carrier, constants_1.BAGGAGE_HEADER, headerValue);
        }
      }
      extract(context2, carrier, getter) {
        const headerValue = getter.get(carrier, constants_1.BAGGAGE_HEADER);
        const baggageString = Array.isArray(headerValue) ? headerValue.join(constants_1.BAGGAGE_ITEMS_SEPARATOR) : headerValue;
        if (!baggageString)
          return context2;
        const baggage = {};
        if (baggageString.length === 0) {
          return context2;
        }
        const pairs = baggageString.split(constants_1.BAGGAGE_ITEMS_SEPARATOR);
        pairs.forEach((entry) => {
          const keyPair = (0, utils_1.parsePairKeyValue)(entry);
          if (keyPair) {
            const baggageEntry = { value: keyPair.value };
            if (keyPair.metadata) {
              baggageEntry.metadata = keyPair.metadata;
            }
            baggage[keyPair.key] = baggageEntry;
          }
        });
        if (Object.entries(baggage).length === 0) {
          return context2;
        }
        return api_1.propagation.setBaggage(context2, api_1.propagation.createBaggage(baggage));
      }
      fields() {
        return [constants_1.BAGGAGE_HEADER];
      }
    };
    exports2.W3CBaggagePropagator = W3CBaggagePropagator;
  }
});

// node_modules/@opentelemetry/core/build/src/common/anchored-clock.js
var require_anchored_clock = __commonJS({
  "node_modules/@opentelemetry/core/build/src/common/anchored-clock.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AnchoredClock = void 0;
    var AnchoredClock = class {
      static {
        __name(this, "AnchoredClock");
      }
      _monotonicClock;
      _epochMillis;
      _performanceMillis;
      /**
       * Create a new AnchoredClock anchored to the current time returned by systemClock.
       *
       * @param systemClock should be a clock that returns the number of milliseconds since January 1 1970 such as Date
       * @param monotonicClock should be a clock that counts milliseconds monotonically such as window.performance or perf_hooks.performance
       */
      constructor(systemClock, monotonicClock) {
        this._monotonicClock = monotonicClock;
        this._epochMillis = systemClock.now();
        this._performanceMillis = monotonicClock.now();
      }
      /**
       * Returns the current time by adding the number of milliseconds since the
       * AnchoredClock was created to the creation epoch time
       */
      now() {
        const delta = this._monotonicClock.now() - this._performanceMillis;
        return this._epochMillis + delta;
      }
    };
    exports2.AnchoredClock = AnchoredClock;
  }
});

// node_modules/@opentelemetry/core/build/src/common/attributes.js
var require_attributes = __commonJS({
  "node_modules/@opentelemetry/core/build/src/common/attributes.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isAttributeValue = exports2.isAttributeKey = exports2.sanitizeAttributes = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    function sanitizeAttributes(attributes) {
      const out = {};
      if (typeof attributes !== "object" || attributes == null) {
        return out;
      }
      for (const [key, val] of Object.entries(attributes)) {
        if (!isAttributeKey(key)) {
          api_1.diag.warn(`Invalid attribute key: ${key}`);
          continue;
        }
        if (!isAttributeValue(val)) {
          api_1.diag.warn(`Invalid attribute value set for key: ${key}`);
          continue;
        }
        if (Array.isArray(val)) {
          out[key] = val.slice();
        } else {
          out[key] = val;
        }
      }
      return out;
    }
    __name(sanitizeAttributes, "sanitizeAttributes");
    exports2.sanitizeAttributes = sanitizeAttributes;
    function isAttributeKey(key) {
      return typeof key === "string" && key.length > 0;
    }
    __name(isAttributeKey, "isAttributeKey");
    exports2.isAttributeKey = isAttributeKey;
    function isAttributeValue(val) {
      if (val == null) {
        return true;
      }
      if (Array.isArray(val)) {
        return isHomogeneousAttributeValueArray(val);
      }
      return isValidPrimitiveAttributeValue(val);
    }
    __name(isAttributeValue, "isAttributeValue");
    exports2.isAttributeValue = isAttributeValue;
    function isHomogeneousAttributeValueArray(arr) {
      let type;
      for (const element of arr) {
        if (element == null)
          continue;
        if (!type) {
          if (isValidPrimitiveAttributeValue(element)) {
            type = typeof element;
            continue;
          }
          return false;
        }
        if (typeof element === type) {
          continue;
        }
        return false;
      }
      return true;
    }
    __name(isHomogeneousAttributeValueArray, "isHomogeneousAttributeValueArray");
    function isValidPrimitiveAttributeValue(val) {
      switch (typeof val) {
        case "number":
        case "boolean":
        case "string":
          return true;
      }
      return false;
    }
    __name(isValidPrimitiveAttributeValue, "isValidPrimitiveAttributeValue");
  }
});

// node_modules/@opentelemetry/core/build/src/common/logging-error-handler.js
var require_logging_error_handler = __commonJS({
  "node_modules/@opentelemetry/core/build/src/common/logging-error-handler.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.loggingErrorHandler = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    function loggingErrorHandler() {
      return (ex) => {
        api_1.diag.error(stringifyException(ex));
      };
    }
    __name(loggingErrorHandler, "loggingErrorHandler");
    exports2.loggingErrorHandler = loggingErrorHandler;
    function stringifyException(ex) {
      if (typeof ex === "string") {
        return ex;
      } else {
        return JSON.stringify(flattenException(ex));
      }
    }
    __name(stringifyException, "stringifyException");
    function flattenException(ex) {
      const result = {};
      let current = ex;
      while (current !== null) {
        Object.getOwnPropertyNames(current).forEach((propertyName) => {
          if (result[propertyName])
            return;
          const value = current[propertyName];
          if (value) {
            result[propertyName] = String(value);
          }
        });
        current = Object.getPrototypeOf(current);
      }
      return result;
    }
    __name(flattenException, "flattenException");
  }
});

// node_modules/@opentelemetry/core/build/src/common/global-error-handler.js
var require_global_error_handler = __commonJS({
  "node_modules/@opentelemetry/core/build/src/common/global-error-handler.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.globalErrorHandler = exports2.setGlobalErrorHandler = void 0;
    var logging_error_handler_1 = require_logging_error_handler();
    var delegateHandler = (0, logging_error_handler_1.loggingErrorHandler)();
    function setGlobalErrorHandler(handler) {
      delegateHandler = handler;
    }
    __name(setGlobalErrorHandler, "setGlobalErrorHandler");
    exports2.setGlobalErrorHandler = setGlobalErrorHandler;
    function globalErrorHandler(ex) {
      try {
        delegateHandler(ex);
      } catch {
      }
    }
    __name(globalErrorHandler, "globalErrorHandler");
    exports2.globalErrorHandler = globalErrorHandler;
  }
});

// node_modules/@opentelemetry/core/build/src/platform/node/environment.js
var require_environment = __commonJS({
  "node_modules/@opentelemetry/core/build/src/platform/node/environment.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getStringListFromEnv = exports2.getBooleanFromEnv = exports2.getStringFromEnv = exports2.getNumberFromEnv = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var util_1 = __require("util");
    function getNumberFromEnv(key) {
      const raw2 = process.env[key];
      if (raw2 == null || raw2.trim() === "") {
        return void 0;
      }
      const value = Number(raw2);
      if (isNaN(value)) {
        api_1.diag.warn(`Unknown value ${(0, util_1.inspect)(raw2)} for ${key}, expected a number, using defaults`);
        return void 0;
      }
      return value;
    }
    __name(getNumberFromEnv, "getNumberFromEnv");
    exports2.getNumberFromEnv = getNumberFromEnv;
    function getStringFromEnv(key) {
      const raw2 = process.env[key];
      if (raw2 == null || raw2.trim() === "") {
        return void 0;
      }
      return raw2;
    }
    __name(getStringFromEnv, "getStringFromEnv");
    exports2.getStringFromEnv = getStringFromEnv;
    function getBooleanFromEnv(key) {
      const raw2 = process.env[key]?.trim().toLowerCase();
      if (raw2 == null || raw2 === "") {
        return false;
      }
      if (raw2 === "true") {
        return true;
      } else if (raw2 === "false") {
        return false;
      } else {
        api_1.diag.warn(`Unknown value ${(0, util_1.inspect)(raw2)} for ${key}, expected 'true' or 'false', falling back to 'false' (default)`);
        return false;
      }
    }
    __name(getBooleanFromEnv, "getBooleanFromEnv");
    exports2.getBooleanFromEnv = getBooleanFromEnv;
    function getStringListFromEnv(key) {
      return getStringFromEnv(key)?.split(",").map((v) => v.trim()).filter((s2) => s2 !== "");
    }
    __name(getStringListFromEnv, "getStringListFromEnv");
    exports2.getStringListFromEnv = getStringListFromEnv;
  }
});

// node_modules/@opentelemetry/core/build/src/platform/node/globalThis.js
var require_globalThis2 = __commonJS({
  "node_modules/@opentelemetry/core/build/src/platform/node/globalThis.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2._globalThis = void 0;
    exports2._globalThis = typeof globalThis === "object" ? globalThis : globalThis;
  }
});

// node_modules/@opentelemetry/core/build/src/platform/node/performance.js
var require_performance = __commonJS({
  "node_modules/@opentelemetry/core/build/src/platform/node/performance.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.otperformance = void 0;
    var perf_hooks_1 = __require("perf_hooks");
    exports2.otperformance = perf_hooks_1.performance;
  }
});

// node_modules/@opentelemetry/core/build/src/version.js
var require_version = __commonJS({
  "node_modules/@opentelemetry/core/build/src/version.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.VERSION = void 0;
    exports2.VERSION = "2.0.1";
  }
});

// node_modules/@opentelemetry/core/build/src/semconv.js
var require_semconv = __commonJS({
  "node_modules/@opentelemetry/core/build/src/semconv.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ATTR_PROCESS_RUNTIME_NAME = void 0;
    exports2.ATTR_PROCESS_RUNTIME_NAME = "process.runtime.name";
  }
});

// node_modules/@opentelemetry/core/build/src/platform/node/sdk-info.js
var require_sdk_info = __commonJS({
  "node_modules/@opentelemetry/core/build/src/platform/node/sdk-info.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SDK_INFO = void 0;
    var version_1 = require_version();
    var semantic_conventions_1 = (init_esm(), __toCommonJS(esm_exports));
    var semconv_1 = require_semconv();
    exports2.SDK_INFO = {
      [semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME]: "opentelemetry",
      [semconv_1.ATTR_PROCESS_RUNTIME_NAME]: "node",
      [semantic_conventions_1.ATTR_TELEMETRY_SDK_LANGUAGE]: semantic_conventions_1.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,
      [semantic_conventions_1.ATTR_TELEMETRY_SDK_VERSION]: version_1.VERSION
    };
  }
});

// node_modules/@opentelemetry/core/build/src/platform/node/timer-util.js
var require_timer_util = __commonJS({
  "node_modules/@opentelemetry/core/build/src/platform/node/timer-util.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.unrefTimer = void 0;
    function unrefTimer(timer) {
      timer.unref();
    }
    __name(unrefTimer, "unrefTimer");
    exports2.unrefTimer = unrefTimer;
  }
});

// node_modules/@opentelemetry/core/build/src/platform/node/index.js
var require_node3 = __commonJS({
  "node_modules/@opentelemetry/core/build/src/platform/node/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.unrefTimer = exports2.SDK_INFO = exports2.otperformance = exports2._globalThis = exports2.getStringListFromEnv = exports2.getNumberFromEnv = exports2.getBooleanFromEnv = exports2.getStringFromEnv = void 0;
    var environment_1 = require_environment();
    Object.defineProperty(exports2, "getStringFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return environment_1.getStringFromEnv;
    }, "get") });
    Object.defineProperty(exports2, "getBooleanFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return environment_1.getBooleanFromEnv;
    }, "get") });
    Object.defineProperty(exports2, "getNumberFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return environment_1.getNumberFromEnv;
    }, "get") });
    Object.defineProperty(exports2, "getStringListFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return environment_1.getStringListFromEnv;
    }, "get") });
    var globalThis_1 = require_globalThis2();
    Object.defineProperty(exports2, "_globalThis", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return globalThis_1._globalThis;
    }, "get") });
    var performance_1 = require_performance();
    Object.defineProperty(exports2, "otperformance", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return performance_1.otperformance;
    }, "get") });
    var sdk_info_1 = require_sdk_info();
    Object.defineProperty(exports2, "SDK_INFO", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_info_1.SDK_INFO;
    }, "get") });
    var timer_util_1 = require_timer_util();
    Object.defineProperty(exports2, "unrefTimer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return timer_util_1.unrefTimer;
    }, "get") });
  }
});

// node_modules/@opentelemetry/core/build/src/platform/index.js
var require_platform2 = __commonJS({
  "node_modules/@opentelemetry/core/build/src/platform/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getStringListFromEnv = exports2.getNumberFromEnv = exports2.getStringFromEnv = exports2.getBooleanFromEnv = exports2.unrefTimer = exports2.otperformance = exports2._globalThis = exports2.SDK_INFO = void 0;
    var node_1 = require_node3();
    Object.defineProperty(exports2, "SDK_INFO", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.SDK_INFO;
    }, "get") });
    Object.defineProperty(exports2, "_globalThis", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1._globalThis;
    }, "get") });
    Object.defineProperty(exports2, "otperformance", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.otperformance;
    }, "get") });
    Object.defineProperty(exports2, "unrefTimer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.unrefTimer;
    }, "get") });
    Object.defineProperty(exports2, "getBooleanFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.getBooleanFromEnv;
    }, "get") });
    Object.defineProperty(exports2, "getStringFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.getStringFromEnv;
    }, "get") });
    Object.defineProperty(exports2, "getNumberFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.getNumberFromEnv;
    }, "get") });
    Object.defineProperty(exports2, "getStringListFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.getStringListFromEnv;
    }, "get") });
  }
});

// node_modules/@opentelemetry/core/build/src/common/time.js
var require_time = __commonJS({
  "node_modules/@opentelemetry/core/build/src/common/time.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.addHrTimes = exports2.isTimeInput = exports2.isTimeInputHrTime = exports2.hrTimeToMicroseconds = exports2.hrTimeToMilliseconds = exports2.hrTimeToNanoseconds = exports2.hrTimeToTimeStamp = exports2.hrTimeDuration = exports2.timeInputToHrTime = exports2.hrTime = exports2.getTimeOrigin = exports2.millisToHrTime = void 0;
    var platform_1 = require_platform2();
    var NANOSECOND_DIGITS = 9;
    var NANOSECOND_DIGITS_IN_MILLIS = 6;
    var MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);
    var SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);
    function millisToHrTime(epochMillis) {
      const epochSeconds = epochMillis / 1e3;
      const seconds = Math.trunc(epochSeconds);
      const nanos = Math.round(epochMillis % 1e3 * MILLISECONDS_TO_NANOSECONDS);
      return [seconds, nanos];
    }
    __name(millisToHrTime, "millisToHrTime");
    exports2.millisToHrTime = millisToHrTime;
    function getTimeOrigin() {
      let timeOrigin = platform_1.otperformance.timeOrigin;
      if (typeof timeOrigin !== "number") {
        const perf2 = platform_1.otperformance;
        timeOrigin = perf2.timing && perf2.timing.fetchStart;
      }
      return timeOrigin;
    }
    __name(getTimeOrigin, "getTimeOrigin");
    exports2.getTimeOrigin = getTimeOrigin;
    function hrTime(performanceNow) {
      const timeOrigin = millisToHrTime(getTimeOrigin());
      const now = millisToHrTime(typeof performanceNow === "number" ? performanceNow : platform_1.otperformance.now());
      return addHrTimes(timeOrigin, now);
    }
    __name(hrTime, "hrTime");
    exports2.hrTime = hrTime;
    function timeInputToHrTime(time) {
      if (isTimeInputHrTime(time)) {
        return time;
      } else if (typeof time === "number") {
        if (time < getTimeOrigin()) {
          return hrTime(time);
        } else {
          return millisToHrTime(time);
        }
      } else if (time instanceof Date) {
        return millisToHrTime(time.getTime());
      } else {
        throw TypeError("Invalid input type");
      }
    }
    __name(timeInputToHrTime, "timeInputToHrTime");
    exports2.timeInputToHrTime = timeInputToHrTime;
    function hrTimeDuration(startTime, endTime) {
      let seconds = endTime[0] - startTime[0];
      let nanos = endTime[1] - startTime[1];
      if (nanos < 0) {
        seconds -= 1;
        nanos += SECOND_TO_NANOSECONDS;
      }
      return [seconds, nanos];
    }
    __name(hrTimeDuration, "hrTimeDuration");
    exports2.hrTimeDuration = hrTimeDuration;
    function hrTimeToTimeStamp(time) {
      const precision = NANOSECOND_DIGITS;
      const tmp = `${"0".repeat(precision)}${time[1]}Z`;
      const nanoString = tmp.substring(tmp.length - precision - 1);
      const date = new Date(time[0] * 1e3).toISOString();
      return date.replace("000Z", nanoString);
    }
    __name(hrTimeToTimeStamp, "hrTimeToTimeStamp");
    exports2.hrTimeToTimeStamp = hrTimeToTimeStamp;
    function hrTimeToNanoseconds(time) {
      return time[0] * SECOND_TO_NANOSECONDS + time[1];
    }
    __name(hrTimeToNanoseconds, "hrTimeToNanoseconds");
    exports2.hrTimeToNanoseconds = hrTimeToNanoseconds;
    function hrTimeToMilliseconds(time) {
      return time[0] * 1e3 + time[1] / 1e6;
    }
    __name(hrTimeToMilliseconds, "hrTimeToMilliseconds");
    exports2.hrTimeToMilliseconds = hrTimeToMilliseconds;
    function hrTimeToMicroseconds(time) {
      return time[0] * 1e6 + time[1] / 1e3;
    }
    __name(hrTimeToMicroseconds, "hrTimeToMicroseconds");
    exports2.hrTimeToMicroseconds = hrTimeToMicroseconds;
    function isTimeInputHrTime(value) {
      return Array.isArray(value) && value.length === 2 && typeof value[0] === "number" && typeof value[1] === "number";
    }
    __name(isTimeInputHrTime, "isTimeInputHrTime");
    exports2.isTimeInputHrTime = isTimeInputHrTime;
    function isTimeInput(value) {
      return isTimeInputHrTime(value) || typeof value === "number" || value instanceof Date;
    }
    __name(isTimeInput, "isTimeInput");
    exports2.isTimeInput = isTimeInput;
    function addHrTimes(time1, time2) {
      const out = [time1[0] + time2[0], time1[1] + time2[1]];
      if (out[1] >= SECOND_TO_NANOSECONDS) {
        out[1] -= SECOND_TO_NANOSECONDS;
        out[0] += 1;
      }
      return out;
    }
    __name(addHrTimes, "addHrTimes");
    exports2.addHrTimes = addHrTimes;
  }
});

// node_modules/@opentelemetry/core/build/src/ExportResult.js
var require_ExportResult = __commonJS({
  "node_modules/@opentelemetry/core/build/src/ExportResult.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ExportResultCode = void 0;
    var ExportResultCode3;
    (function(ExportResultCode4) {
      ExportResultCode4[ExportResultCode4["SUCCESS"] = 0] = "SUCCESS";
      ExportResultCode4[ExportResultCode4["FAILED"] = 1] = "FAILED";
    })(ExportResultCode3 = exports2.ExportResultCode || (exports2.ExportResultCode = {}));
  }
});

// node_modules/@opentelemetry/core/build/src/propagation/composite.js
var require_composite = __commonJS({
  "node_modules/@opentelemetry/core/build/src/propagation/composite.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CompositePropagator = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var CompositePropagator = class {
      static {
        __name(this, "CompositePropagator");
      }
      _propagators;
      _fields;
      /**
       * Construct a composite propagator from a list of propagators.
       *
       * @param [config] Configuration object for composite propagator
       */
      constructor(config = {}) {
        this._propagators = config.propagators ?? [];
        this._fields = Array.from(new Set(this._propagators.map((p) => typeof p.fields === "function" ? p.fields() : []).reduce((x, y) => x.concat(y), [])));
      }
      /**
       * Run each of the configured propagators with the given context and carrier.
       * Propagators are run in the order they are configured, so if multiple
       * propagators write the same carrier key, the propagator later in the list
       * will "win".
       *
       * @param context Context to inject
       * @param carrier Carrier into which context will be injected
       */
      inject(context2, carrier, setter) {
        for (const propagator of this._propagators) {
          try {
            propagator.inject(context2, carrier, setter);
          } catch (err) {
            api_1.diag.warn(`Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`);
          }
        }
      }
      /**
       * Run each of the configured propagators with the given context and carrier.
       * Propagators are run in the order they are configured, so if multiple
       * propagators write the same context key, the propagator later in the list
       * will "win".
       *
       * @param context Context to add values to
       * @param carrier Carrier from which to extract context
       */
      extract(context2, carrier, getter) {
        return this._propagators.reduce((ctx, propagator) => {
          try {
            return propagator.extract(ctx, carrier, getter);
          } catch (err) {
            api_1.diag.warn(`Failed to extract with ${propagator.constructor.name}. Err: ${err.message}`);
          }
          return ctx;
        }, context2);
      }
      fields() {
        return this._fields.slice();
      }
    };
    exports2.CompositePropagator = CompositePropagator;
  }
});

// node_modules/@opentelemetry/core/build/src/internal/validators.js
var require_validators = __commonJS({
  "node_modules/@opentelemetry/core/build/src/internal/validators.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateValue = exports2.validateKey = void 0;
    var VALID_KEY_CHAR_RANGE2 = "[_0-9a-z-*/]";
    var VALID_KEY2 = `[a-z]${VALID_KEY_CHAR_RANGE2}{0,255}`;
    var VALID_VENDOR_KEY2 = `[a-z0-9]${VALID_KEY_CHAR_RANGE2}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE2}{0,13}`;
    var VALID_KEY_REGEX2 = new RegExp(`^(?:${VALID_KEY2}|${VALID_VENDOR_KEY2})$`);
    var VALID_VALUE_BASE_REGEX2 = /^[ -~]{0,255}[!-~]$/;
    var INVALID_VALUE_COMMA_EQUAL_REGEX2 = /,|=/;
    function validateKey2(key) {
      return VALID_KEY_REGEX2.test(key);
    }
    __name(validateKey2, "validateKey");
    exports2.validateKey = validateKey2;
    function validateValue2(value) {
      return VALID_VALUE_BASE_REGEX2.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX2.test(value);
    }
    __name(validateValue2, "validateValue");
    exports2.validateValue = validateValue2;
  }
});

// node_modules/@opentelemetry/core/build/src/trace/TraceState.js
var require_TraceState = __commonJS({
  "node_modules/@opentelemetry/core/build/src/trace/TraceState.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.TraceState = void 0;
    var validators_1 = require_validators();
    var MAX_TRACE_STATE_ITEMS2 = 32;
    var MAX_TRACE_STATE_LEN2 = 512;
    var LIST_MEMBERS_SEPARATOR2 = ",";
    var LIST_MEMBER_KEY_VALUE_SPLITTER2 = "=";
    var TraceState = class _TraceState {
      static {
        __name(this, "TraceState");
      }
      _internalState = /* @__PURE__ */ new Map();
      constructor(rawTraceState) {
        if (rawTraceState)
          this._parse(rawTraceState);
      }
      set(key, value) {
        const traceState = this._clone();
        if (traceState._internalState.has(key)) {
          traceState._internalState.delete(key);
        }
        traceState._internalState.set(key, value);
        return traceState;
      }
      unset(key) {
        const traceState = this._clone();
        traceState._internalState.delete(key);
        return traceState;
      }
      get(key) {
        return this._internalState.get(key);
      }
      serialize() {
        return this._keys().reduce((agg, key) => {
          agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER2 + this.get(key));
          return agg;
        }, []).join(LIST_MEMBERS_SEPARATOR2);
      }
      _parse(rawTraceState) {
        if (rawTraceState.length > MAX_TRACE_STATE_LEN2)
          return;
        this._internalState = rawTraceState.split(LIST_MEMBERS_SEPARATOR2).reverse().reduce((agg, part) => {
          const listMember = part.trim();
          const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER2);
          if (i !== -1) {
            const key = listMember.slice(0, i);
            const value = listMember.slice(i + 1, part.length);
            if ((0, validators_1.validateKey)(key) && (0, validators_1.validateValue)(value)) {
              agg.set(key, value);
            } else {
            }
          }
          return agg;
        }, /* @__PURE__ */ new Map());
        if (this._internalState.size > MAX_TRACE_STATE_ITEMS2) {
          this._internalState = new Map(Array.from(this._internalState.entries()).reverse().slice(0, MAX_TRACE_STATE_ITEMS2));
        }
      }
      _keys() {
        return Array.from(this._internalState.keys()).reverse();
      }
      _clone() {
        const traceState = new _TraceState();
        traceState._internalState = new Map(this._internalState);
        return traceState;
      }
    };
    exports2.TraceState = TraceState;
  }
});

// node_modules/@opentelemetry/core/build/src/trace/W3CTraceContextPropagator.js
var require_W3CTraceContextPropagator = __commonJS({
  "node_modules/@opentelemetry/core/build/src/trace/W3CTraceContextPropagator.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.W3CTraceContextPropagator = exports2.parseTraceParent = exports2.TRACE_STATE_HEADER = exports2.TRACE_PARENT_HEADER = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var suppress_tracing_1 = require_suppress_tracing();
    var TraceState_1 = require_TraceState();
    exports2.TRACE_PARENT_HEADER = "traceparent";
    exports2.TRACE_STATE_HEADER = "tracestate";
    var VERSION3 = "00";
    var VERSION_PART = "(?!ff)[\\da-f]{2}";
    var TRACE_ID_PART = "(?![0]{32})[\\da-f]{32}";
    var PARENT_ID_PART = "(?![0]{16})[\\da-f]{16}";
    var FLAGS_PART = "[\\da-f]{2}";
    var TRACE_PARENT_REGEX = new RegExp(`^\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\s?$`);
    function parseTraceParent(traceParent) {
      const match2 = TRACE_PARENT_REGEX.exec(traceParent);
      if (!match2)
        return null;
      if (match2[1] === "00" && match2[5])
        return null;
      return {
        traceId: match2[2],
        spanId: match2[3],
        traceFlags: parseInt(match2[4], 16)
      };
    }
    __name(parseTraceParent, "parseTraceParent");
    exports2.parseTraceParent = parseTraceParent;
    var W3CTraceContextPropagator = class {
      static {
        __name(this, "W3CTraceContextPropagator");
      }
      inject(context2, carrier, setter) {
        const spanContext = api_1.trace.getSpanContext(context2);
        if (!spanContext || (0, suppress_tracing_1.isTracingSuppressed)(context2) || !(0, api_1.isSpanContextValid)(spanContext))
          return;
        const traceParent = `${VERSION3}-${spanContext.traceId}-${spanContext.spanId}-0${Number(spanContext.traceFlags || api_1.TraceFlags.NONE).toString(16)}`;
        setter.set(carrier, exports2.TRACE_PARENT_HEADER, traceParent);
        if (spanContext.traceState) {
          setter.set(carrier, exports2.TRACE_STATE_HEADER, spanContext.traceState.serialize());
        }
      }
      extract(context2, carrier, getter) {
        const traceParentHeader = getter.get(carrier, exports2.TRACE_PARENT_HEADER);
        if (!traceParentHeader)
          return context2;
        const traceParent = Array.isArray(traceParentHeader) ? traceParentHeader[0] : traceParentHeader;
        if (typeof traceParent !== "string")
          return context2;
        const spanContext = parseTraceParent(traceParent);
        if (!spanContext)
          return context2;
        spanContext.isRemote = true;
        const traceStateHeader = getter.get(carrier, exports2.TRACE_STATE_HEADER);
        if (traceStateHeader) {
          const state = Array.isArray(traceStateHeader) ? traceStateHeader.join(",") : traceStateHeader;
          spanContext.traceState = new TraceState_1.TraceState(typeof state === "string" ? state : void 0);
        }
        return api_1.trace.setSpanContext(context2, spanContext);
      }
      fields() {
        return [exports2.TRACE_PARENT_HEADER, exports2.TRACE_STATE_HEADER];
      }
    };
    exports2.W3CTraceContextPropagator = W3CTraceContextPropagator;
  }
});

// node_modules/@opentelemetry/core/build/src/trace/rpc-metadata.js
var require_rpc_metadata = __commonJS({
  "node_modules/@opentelemetry/core/build/src/trace/rpc-metadata.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRPCMetadata = exports2.deleteRPCMetadata = exports2.setRPCMetadata = exports2.RPCType = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var RPC_METADATA_KEY = (0, api_1.createContextKey)("OpenTelemetry SDK Context Key RPC_METADATA");
    var RPCType;
    (function(RPCType2) {
      RPCType2["HTTP"] = "http";
    })(RPCType = exports2.RPCType || (exports2.RPCType = {}));
    function setRPCMetadata(context2, meta) {
      return context2.setValue(RPC_METADATA_KEY, meta);
    }
    __name(setRPCMetadata, "setRPCMetadata");
    exports2.setRPCMetadata = setRPCMetadata;
    function deleteRPCMetadata(context2) {
      return context2.deleteValue(RPC_METADATA_KEY);
    }
    __name(deleteRPCMetadata, "deleteRPCMetadata");
    exports2.deleteRPCMetadata = deleteRPCMetadata;
    function getRPCMetadata(context2) {
      return context2.getValue(RPC_METADATA_KEY);
    }
    __name(getRPCMetadata, "getRPCMetadata");
    exports2.getRPCMetadata = getRPCMetadata;
  }
});

// node_modules/@opentelemetry/core/build/src/utils/lodash.merge.js
var require_lodash_merge = __commonJS({
  "node_modules/@opentelemetry/core/build/src/utils/lodash.merge.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isPlainObject = void 0;
    var objectTag = "[object Object]";
    var nullTag = "[object Null]";
    var undefinedTag = "[object Undefined]";
    var funcProto = Function.prototype;
    var funcToString = funcProto.toString;
    var objectCtorString = funcToString.call(Object);
    var getPrototypeOf = Object.getPrototypeOf;
    var objectProto = Object.prototype;
    var hasOwnProperty2 = objectProto.hasOwnProperty;
    var symToStringTag = Symbol ? Symbol.toStringTag : void 0;
    var nativeObjectToString = objectProto.toString;
    function isPlainObject2(value) {
      if (!isObjectLike(value) || baseGetTag(value) !== objectTag) {
        return false;
      }
      const proto3 = getPrototypeOf(value);
      if (proto3 === null) {
        return true;
      }
      const Ctor = hasOwnProperty2.call(proto3, "constructor") && proto3.constructor;
      return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) === objectCtorString;
    }
    __name(isPlainObject2, "isPlainObject");
    exports2.isPlainObject = isPlainObject2;
    function isObjectLike(value) {
      return value != null && typeof value == "object";
    }
    __name(isObjectLike, "isObjectLike");
    function baseGetTag(value) {
      if (value == null) {
        return value === void 0 ? undefinedTag : nullTag;
      }
      return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString2(value);
    }
    __name(baseGetTag, "baseGetTag");
    function getRawTag(value) {
      const isOwn = hasOwnProperty2.call(value, symToStringTag), tag2 = value[symToStringTag];
      let unmasked = false;
      try {
        value[symToStringTag] = void 0;
        unmasked = true;
      } catch (e2) {
      }
      const result = nativeObjectToString.call(value);
      if (unmasked) {
        if (isOwn) {
          value[symToStringTag] = tag2;
        } else {
          delete value[symToStringTag];
        }
      }
      return result;
    }
    __name(getRawTag, "getRawTag");
    function objectToString2(value) {
      return nativeObjectToString.call(value);
    }
    __name(objectToString2, "objectToString");
  }
});

// node_modules/@opentelemetry/core/build/src/utils/merge.js
var require_merge = __commonJS({
  "node_modules/@opentelemetry/core/build/src/utils/merge.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.merge = void 0;
    var lodash_merge_1 = require_lodash_merge();
    var MAX_LEVEL = 20;
    function merge3(...args) {
      let result = args.shift();
      const objects = /* @__PURE__ */ new WeakMap();
      while (args.length > 0) {
        result = mergeTwoObjects(result, args.shift(), 0, objects);
      }
      return result;
    }
    __name(merge3, "merge");
    exports2.merge = merge3;
    function takeValue(value) {
      if (isArray2(value)) {
        return value.slice();
      }
      return value;
    }
    __name(takeValue, "takeValue");
    function mergeTwoObjects(one, two, level = 0, objects) {
      let result;
      if (level > MAX_LEVEL) {
        return void 0;
      }
      level++;
      if (isPrimitive(one) || isPrimitive(two) || isFunction3(two)) {
        result = takeValue(two);
      } else if (isArray2(one)) {
        result = one.slice();
        if (isArray2(two)) {
          for (let i = 0, j = two.length; i < j; i++) {
            result.push(takeValue(two[i]));
          }
        } else if (isObject3(two)) {
          const keys = Object.keys(two);
          for (let i = 0, j = keys.length; i < j; i++) {
            const key = keys[i];
            result[key] = takeValue(two[key]);
          }
        }
      } else if (isObject3(one)) {
        if (isObject3(two)) {
          if (!shouldMerge(one, two)) {
            return two;
          }
          result = Object.assign({}, one);
          const keys = Object.keys(two);
          for (let i = 0, j = keys.length; i < j; i++) {
            const key = keys[i];
            const twoValue = two[key];
            if (isPrimitive(twoValue)) {
              if (typeof twoValue === "undefined") {
                delete result[key];
              } else {
                result[key] = twoValue;
              }
            } else {
              const obj1 = result[key];
              const obj2 = twoValue;
              if (wasObjectReferenced(one, key, objects) || wasObjectReferenced(two, key, objects)) {
                delete result[key];
              } else {
                if (isObject3(obj1) && isObject3(obj2)) {
                  const arr1 = objects.get(obj1) || [];
                  const arr2 = objects.get(obj2) || [];
                  arr1.push({ obj: one, key });
                  arr2.push({ obj: two, key });
                  objects.set(obj1, arr1);
                  objects.set(obj2, arr2);
                }
                result[key] = mergeTwoObjects(result[key], twoValue, level, objects);
              }
            }
          }
        } else {
          result = two;
        }
      }
      return result;
    }
    __name(mergeTwoObjects, "mergeTwoObjects");
    function wasObjectReferenced(obj, key, objects) {
      const arr = objects.get(obj[key]) || [];
      for (let i = 0, j = arr.length; i < j; i++) {
        const info = arr[i];
        if (info.key === key && info.obj === obj) {
          return true;
        }
      }
      return false;
    }
    __name(wasObjectReferenced, "wasObjectReferenced");
    function isArray2(value) {
      return Array.isArray(value);
    }
    __name(isArray2, "isArray");
    function isFunction3(value) {
      return typeof value === "function";
    }
    __name(isFunction3, "isFunction");
    function isObject3(value) {
      return !isPrimitive(value) && !isArray2(value) && !isFunction3(value) && typeof value === "object";
    }
    __name(isObject3, "isObject");
    function isPrimitive(value) {
      return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "undefined" || value instanceof Date || value instanceof RegExp || value === null;
    }
    __name(isPrimitive, "isPrimitive");
    function shouldMerge(one, two) {
      if (!(0, lodash_merge_1.isPlainObject)(one) || !(0, lodash_merge_1.isPlainObject)(two)) {
        return false;
      }
      return true;
    }
    __name(shouldMerge, "shouldMerge");
  }
});

// node_modules/@opentelemetry/core/build/src/utils/timeout.js
var require_timeout = __commonJS({
  "node_modules/@opentelemetry/core/build/src/utils/timeout.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.callWithTimeout = exports2.TimeoutError = void 0;
    var TimeoutError2 = class _TimeoutError extends Error {
      static {
        __name(this, "TimeoutError");
      }
      constructor(message) {
        super(message);
        Object.setPrototypeOf(this, _TimeoutError.prototype);
      }
    };
    exports2.TimeoutError = TimeoutError2;
    function callWithTimeout(promise, timeout2) {
      let timeoutHandle;
      const timeoutPromise = new Promise(/* @__PURE__ */ __name(function timeoutFunction(_resolve, reject) {
        timeoutHandle = setTimeout(/* @__PURE__ */ __name(function timeoutHandler() {
          reject(new TimeoutError2("Operation timed out."));
        }, "timeoutHandler"), timeout2);
      }, "timeoutFunction"));
      return Promise.race([promise, timeoutPromise]).then((result) => {
        clearTimeout(timeoutHandle);
        return result;
      }, (reason) => {
        clearTimeout(timeoutHandle);
        throw reason;
      });
    }
    __name(callWithTimeout, "callWithTimeout");
    exports2.callWithTimeout = callWithTimeout;
  }
});

// node_modules/@opentelemetry/core/build/src/utils/url.js
var require_url = __commonJS({
  "node_modules/@opentelemetry/core/build/src/utils/url.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isUrlIgnored = exports2.urlMatches = void 0;
    function urlMatches(url2, urlToMatch) {
      if (typeof urlToMatch === "string") {
        return url2 === urlToMatch;
      } else {
        return !!url2.match(urlToMatch);
      }
    }
    __name(urlMatches, "urlMatches");
    exports2.urlMatches = urlMatches;
    function isUrlIgnored(url2, ignoredUrls) {
      if (!ignoredUrls) {
        return false;
      }
      for (const ignoreUrl of ignoredUrls) {
        if (urlMatches(url2, ignoreUrl)) {
          return true;
        }
      }
      return false;
    }
    __name(isUrlIgnored, "isUrlIgnored");
    exports2.isUrlIgnored = isUrlIgnored;
  }
});

// node_modules/@opentelemetry/core/build/src/utils/promise.js
var require_promise2 = __commonJS({
  "node_modules/@opentelemetry/core/build/src/utils/promise.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Deferred = void 0;
    var Deferred = class {
      static {
        __name(this, "Deferred");
      }
      _promise;
      _resolve;
      _reject;
      constructor() {
        this._promise = new Promise((resolve24, reject) => {
          this._resolve = resolve24;
          this._reject = reject;
        });
      }
      get promise() {
        return this._promise;
      }
      resolve(val) {
        this._resolve(val);
      }
      reject(err) {
        this._reject(err);
      }
    };
    exports2.Deferred = Deferred;
  }
});

// node_modules/@opentelemetry/core/build/src/utils/callback.js
var require_callback = __commonJS({
  "node_modules/@opentelemetry/core/build/src/utils/callback.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BindOnceFuture = void 0;
    var promise_1 = require_promise2();
    var BindOnceFuture = class {
      static {
        __name(this, "BindOnceFuture");
      }
      _callback;
      _that;
      _isCalled = false;
      _deferred = new promise_1.Deferred();
      constructor(_callback, _that) {
        this._callback = _callback;
        this._that = _that;
      }
      get isCalled() {
        return this._isCalled;
      }
      get promise() {
        return this._deferred.promise;
      }
      call(...args) {
        if (!this._isCalled) {
          this._isCalled = true;
          try {
            Promise.resolve(this._callback.call(this._that, ...args)).then((val) => this._deferred.resolve(val), (err) => this._deferred.reject(err));
          } catch (err) {
            this._deferred.reject(err);
          }
        }
        return this._deferred.promise;
      }
    };
    exports2.BindOnceFuture = BindOnceFuture;
  }
});

// node_modules/@opentelemetry/core/build/src/utils/configuration.js
var require_configuration = __commonJS({
  "node_modules/@opentelemetry/core/build/src/utils/configuration.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.diagLogLevelFromString = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var logLevelMap = {
      ALL: api_1.DiagLogLevel.ALL,
      VERBOSE: api_1.DiagLogLevel.VERBOSE,
      DEBUG: api_1.DiagLogLevel.DEBUG,
      INFO: api_1.DiagLogLevel.INFO,
      WARN: api_1.DiagLogLevel.WARN,
      ERROR: api_1.DiagLogLevel.ERROR,
      NONE: api_1.DiagLogLevel.NONE
    };
    function diagLogLevelFromString(value) {
      if (value == null) {
        return void 0;
      }
      const resolvedLogLevel = logLevelMap[value.toUpperCase()];
      if (resolvedLogLevel == null) {
        api_1.diag.warn(`Unknown log level "${value}", expected one of ${Object.keys(logLevelMap)}, using default`);
        return api_1.DiagLogLevel.INFO;
      }
      return resolvedLogLevel;
    }
    __name(diagLogLevelFromString, "diagLogLevelFromString");
    exports2.diagLogLevelFromString = diagLogLevelFromString;
  }
});

// node_modules/@opentelemetry/core/build/src/internal/exporter.js
var require_exporter = __commonJS({
  "node_modules/@opentelemetry/core/build/src/internal/exporter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2._export = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var suppress_tracing_1 = require_suppress_tracing();
    function _export(exporter, arg) {
      return new Promise((resolve24) => {
        api_1.context.with((0, suppress_tracing_1.suppressTracing)(api_1.context.active()), () => {
          exporter.export(arg, (result) => {
            resolve24(result);
          });
        });
      });
    }
    __name(_export, "_export");
    exports2._export = _export;
  }
});

// node_modules/@opentelemetry/core/build/src/index.js
var require_src8 = __commonJS({
  "node_modules/@opentelemetry/core/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.internal = exports2.diagLogLevelFromString = exports2.BindOnceFuture = exports2.urlMatches = exports2.isUrlIgnored = exports2.callWithTimeout = exports2.TimeoutError = exports2.merge = exports2.TraceState = exports2.unsuppressTracing = exports2.suppressTracing = exports2.isTracingSuppressed = exports2.setRPCMetadata = exports2.getRPCMetadata = exports2.deleteRPCMetadata = exports2.RPCType = exports2.parseTraceParent = exports2.W3CTraceContextPropagator = exports2.TRACE_STATE_HEADER = exports2.TRACE_PARENT_HEADER = exports2.CompositePropagator = exports2.unrefTimer = exports2.otperformance = exports2.getStringListFromEnv = exports2.getNumberFromEnv = exports2.getBooleanFromEnv = exports2.getStringFromEnv = exports2._globalThis = exports2.SDK_INFO = exports2.parseKeyPairsIntoRecord = exports2.ExportResultCode = exports2.timeInputToHrTime = exports2.millisToHrTime = exports2.isTimeInputHrTime = exports2.isTimeInput = exports2.hrTimeToTimeStamp = exports2.hrTimeToNanoseconds = exports2.hrTimeToMilliseconds = exports2.hrTimeToMicroseconds = exports2.hrTimeDuration = exports2.hrTime = exports2.getTimeOrigin = exports2.addHrTimes = exports2.loggingErrorHandler = exports2.setGlobalErrorHandler = exports2.globalErrorHandler = exports2.sanitizeAttributes = exports2.isAttributeValue = exports2.AnchoredClock = exports2.W3CBaggagePropagator = void 0;
    var W3CBaggagePropagator_1 = require_W3CBaggagePropagator();
    Object.defineProperty(exports2, "W3CBaggagePropagator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return W3CBaggagePropagator_1.W3CBaggagePropagator;
    }, "get") });
    var anchored_clock_1 = require_anchored_clock();
    Object.defineProperty(exports2, "AnchoredClock", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return anchored_clock_1.AnchoredClock;
    }, "get") });
    var attributes_1 = require_attributes();
    Object.defineProperty(exports2, "isAttributeValue", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return attributes_1.isAttributeValue;
    }, "get") });
    Object.defineProperty(exports2, "sanitizeAttributes", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return attributes_1.sanitizeAttributes;
    }, "get") });
    var global_error_handler_1 = require_global_error_handler();
    Object.defineProperty(exports2, "globalErrorHandler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return global_error_handler_1.globalErrorHandler;
    }, "get") });
    Object.defineProperty(exports2, "setGlobalErrorHandler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return global_error_handler_1.setGlobalErrorHandler;
    }, "get") });
    var logging_error_handler_1 = require_logging_error_handler();
    Object.defineProperty(exports2, "loggingErrorHandler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return logging_error_handler_1.loggingErrorHandler;
    }, "get") });
    var time_1 = require_time();
    Object.defineProperty(exports2, "addHrTimes", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.addHrTimes;
    }, "get") });
    Object.defineProperty(exports2, "getTimeOrigin", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.getTimeOrigin;
    }, "get") });
    Object.defineProperty(exports2, "hrTime", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.hrTime;
    }, "get") });
    Object.defineProperty(exports2, "hrTimeDuration", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.hrTimeDuration;
    }, "get") });
    Object.defineProperty(exports2, "hrTimeToMicroseconds", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.hrTimeToMicroseconds;
    }, "get") });
    Object.defineProperty(exports2, "hrTimeToMilliseconds", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.hrTimeToMilliseconds;
    }, "get") });
    Object.defineProperty(exports2, "hrTimeToNanoseconds", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.hrTimeToNanoseconds;
    }, "get") });
    Object.defineProperty(exports2, "hrTimeToTimeStamp", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.hrTimeToTimeStamp;
    }, "get") });
    Object.defineProperty(exports2, "isTimeInput", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.isTimeInput;
    }, "get") });
    Object.defineProperty(exports2, "isTimeInputHrTime", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.isTimeInputHrTime;
    }, "get") });
    Object.defineProperty(exports2, "millisToHrTime", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.millisToHrTime;
    }, "get") });
    Object.defineProperty(exports2, "timeInputToHrTime", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.timeInputToHrTime;
    }, "get") });
    var ExportResult_1 = require_ExportResult();
    Object.defineProperty(exports2, "ExportResultCode", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ExportResult_1.ExportResultCode;
    }, "get") });
    var utils_1 = require_utils4();
    Object.defineProperty(exports2, "parseKeyPairsIntoRecord", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return utils_1.parseKeyPairsIntoRecord;
    }, "get") });
    var platform_1 = require_platform2();
    Object.defineProperty(exports2, "SDK_INFO", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.SDK_INFO;
    }, "get") });
    Object.defineProperty(exports2, "_globalThis", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1._globalThis;
    }, "get") });
    Object.defineProperty(exports2, "getStringFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.getStringFromEnv;
    }, "get") });
    Object.defineProperty(exports2, "getBooleanFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.getBooleanFromEnv;
    }, "get") });
    Object.defineProperty(exports2, "getNumberFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.getNumberFromEnv;
    }, "get") });
    Object.defineProperty(exports2, "getStringListFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.getStringListFromEnv;
    }, "get") });
    Object.defineProperty(exports2, "otperformance", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.otperformance;
    }, "get") });
    Object.defineProperty(exports2, "unrefTimer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.unrefTimer;
    }, "get") });
    var composite_1 = require_composite();
    Object.defineProperty(exports2, "CompositePropagator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return composite_1.CompositePropagator;
    }, "get") });
    var W3CTraceContextPropagator_1 = require_W3CTraceContextPropagator();
    Object.defineProperty(exports2, "TRACE_PARENT_HEADER", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return W3CTraceContextPropagator_1.TRACE_PARENT_HEADER;
    }, "get") });
    Object.defineProperty(exports2, "TRACE_STATE_HEADER", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return W3CTraceContextPropagator_1.TRACE_STATE_HEADER;
    }, "get") });
    Object.defineProperty(exports2, "W3CTraceContextPropagator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return W3CTraceContextPropagator_1.W3CTraceContextPropagator;
    }, "get") });
    Object.defineProperty(exports2, "parseTraceParent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return W3CTraceContextPropagator_1.parseTraceParent;
    }, "get") });
    var rpc_metadata_1 = require_rpc_metadata();
    Object.defineProperty(exports2, "RPCType", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return rpc_metadata_1.RPCType;
    }, "get") });
    Object.defineProperty(exports2, "deleteRPCMetadata", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return rpc_metadata_1.deleteRPCMetadata;
    }, "get") });
    Object.defineProperty(exports2, "getRPCMetadata", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return rpc_metadata_1.getRPCMetadata;
    }, "get") });
    Object.defineProperty(exports2, "setRPCMetadata", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return rpc_metadata_1.setRPCMetadata;
    }, "get") });
    var suppress_tracing_1 = require_suppress_tracing();
    Object.defineProperty(exports2, "isTracingSuppressed", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return suppress_tracing_1.isTracingSuppressed;
    }, "get") });
    Object.defineProperty(exports2, "suppressTracing", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return suppress_tracing_1.suppressTracing;
    }, "get") });
    Object.defineProperty(exports2, "unsuppressTracing", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return suppress_tracing_1.unsuppressTracing;
    }, "get") });
    var TraceState_1 = require_TraceState();
    Object.defineProperty(exports2, "TraceState", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return TraceState_1.TraceState;
    }, "get") });
    var merge_1 = require_merge();
    Object.defineProperty(exports2, "merge", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return merge_1.merge;
    }, "get") });
    var timeout_1 = require_timeout();
    Object.defineProperty(exports2, "TimeoutError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return timeout_1.TimeoutError;
    }, "get") });
    Object.defineProperty(exports2, "callWithTimeout", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return timeout_1.callWithTimeout;
    }, "get") });
    var url_1 = require_url();
    Object.defineProperty(exports2, "isUrlIgnored", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return url_1.isUrlIgnored;
    }, "get") });
    Object.defineProperty(exports2, "urlMatches", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return url_1.urlMatches;
    }, "get") });
    var callback_1 = require_callback();
    Object.defineProperty(exports2, "BindOnceFuture", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return callback_1.BindOnceFuture;
    }, "get") });
    var configuration_1 = require_configuration();
    Object.defineProperty(exports2, "diagLogLevelFromString", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return configuration_1.diagLogLevelFromString;
    }, "get") });
    var exporter_1 = require_exporter();
    exports2.internal = {
      _export: exporter_1._export
    };
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/logging-response-handler.js
function isPartialSuccessResponse(response) {
  return Object.prototype.hasOwnProperty.call(response, "partialSuccess");
}
function createLoggingPartialSuccessResponseHandler() {
  return {
    handleResponse(response) {
      if (response == null || !isPartialSuccessResponse(response) || response.partialSuccess == null || Object.keys(response.partialSuccess).length === 0) {
        return;
      }
      diag2.warn("Received Partial Success response:", JSON.stringify(response.partialSuccess));
    }
  };
}
var init_logging_response_handler = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/logging-response-handler.js"() {
    init_esbuild_shims();
    init_esm2();
    __name(isPartialSuccessResponse, "isPartialSuccessResponse");
    __name(createLoggingPartialSuccessResponseHandler, "createLoggingPartialSuccessResponseHandler");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-export-delegate.js
function createOtlpExportDelegate(components, settings) {
  return new OTLPExportDelegate(components.transport, components.serializer, createLoggingPartialSuccessResponseHandler(), components.promiseHandler, settings.timeout);
}
var import_core, OTLPExportDelegate;
var init_otlp_export_delegate = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-export-delegate.js"() {
    init_esbuild_shims();
    import_core = __toESM(require_src8());
    init_types5();
    init_logging_response_handler();
    init_esm2();
    OTLPExportDelegate = class {
      static {
        __name(this, "OTLPExportDelegate");
      }
      _transport;
      _serializer;
      _responseHandler;
      _promiseQueue;
      _timeout;
      _diagLogger;
      constructor(_transport, _serializer, _responseHandler, _promiseQueue, _timeout) {
        this._transport = _transport;
        this._serializer = _serializer;
        this._responseHandler = _responseHandler;
        this._promiseQueue = _promiseQueue;
        this._timeout = _timeout;
        this._diagLogger = diag2.createComponentLogger({
          namespace: "OTLPExportDelegate"
        });
      }
      export(internalRepresentation, resultCallback) {
        this._diagLogger.debug("items to be sent", internalRepresentation);
        if (this._promiseQueue.hasReachedLimit()) {
          resultCallback({
            code: import_core.ExportResultCode.FAILED,
            error: new Error("Concurrent export limit reached")
          });
          return;
        }
        const serializedRequest = this._serializer.serializeRequest(internalRepresentation);
        if (serializedRequest == null) {
          resultCallback({
            code: import_core.ExportResultCode.FAILED,
            error: new Error("Nothing to send")
          });
          return;
        }
        this._promiseQueue.pushPromise(this._transport.send(serializedRequest, this._timeout).then((response) => {
          if (response.status === "success") {
            if (response.data != null) {
              try {
                this._responseHandler.handleResponse(this._serializer.deserializeResponse(response.data));
              } catch (e2) {
                this._diagLogger.warn("Export succeeded but could not deserialize response - is the response specification compliant?", e2, response.data);
              }
            }
            resultCallback({
              code: import_core.ExportResultCode.SUCCESS
            });
            return;
          } else if (response.status === "failure" && response.error) {
            resultCallback({
              code: import_core.ExportResultCode.FAILED,
              error: response.error
            });
            return;
          } else if (response.status === "retryable") {
            resultCallback({
              code: import_core.ExportResultCode.FAILED,
              error: new OTLPExporterError("Export failed with retryable status")
            });
          } else {
            resultCallback({
              code: import_core.ExportResultCode.FAILED,
              error: new OTLPExporterError("Export failed with unknown error")
            });
          }
        }, (reason) => resultCallback({
          code: import_core.ExportResultCode.FAILED,
          error: reason
        })));
      }
      forceFlush() {
        return this._promiseQueue.awaitAll();
      }
      async shutdown() {
        this._diagLogger.debug("shutdown started");
        await this.forceFlush();
        this._transport.shutdown();
      }
    };
    __name(createOtlpExportDelegate, "createOtlpExportDelegate");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-network-export-delegate.js
function createOtlpNetworkExportDelegate(options2, serializer, transport) {
  return createOtlpExportDelegate({
    transport,
    serializer,
    promiseHandler: createBoundedQueueExportPromiseHandler(options2)
  }, { timeout: options2.timeoutMillis });
}
var init_otlp_network_export_delegate = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-network-export-delegate.js"() {
    init_esbuild_shims();
    init_bounded_queue_export_promise_handler();
    init_otlp_export_delegate();
    __name(createOtlpNetworkExportDelegate, "createOtlpNetworkExportDelegate");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/index.js
var esm_exports3 = {};
__export(esm_exports3, {
  CompressionAlgorithm: () => CompressionAlgorithm,
  OTLPExporterBase: () => OTLPExporterBase,
  OTLPExporterError: () => OTLPExporterError,
  createOtlpNetworkExportDelegate: () => createOtlpNetworkExportDelegate,
  getSharedConfigurationDefaults: () => getSharedConfigurationDefaults,
  mergeOtlpSharedConfigurationWithDefaults: () => mergeOtlpSharedConfigurationWithDefaults
});
var init_esm3 = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/index.js"() {
    init_esbuild_shims();
    init_OTLPExporterBase();
    init_types5();
    init_shared_configuration();
    init_legacy_node_configuration();
    init_otlp_network_export_delegate();
  }
});

// node_modules/@grpc/grpc-js/build/src/constants.js
var require_constants9 = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/constants.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = exports2.DEFAULT_MAX_SEND_MESSAGE_LENGTH = exports2.Propagate = exports2.LogVerbosity = exports2.Status = void 0;
    var Status;
    (function(Status2) {
      Status2[Status2["OK"] = 0] = "OK";
      Status2[Status2["CANCELLED"] = 1] = "CANCELLED";
      Status2[Status2["UNKNOWN"] = 2] = "UNKNOWN";
      Status2[Status2["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT";
      Status2[Status2["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED";
      Status2[Status2["NOT_FOUND"] = 5] = "NOT_FOUND";
      Status2[Status2["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS";
      Status2[Status2["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED";
      Status2[Status2["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED";
      Status2[Status2["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION";
      Status2[Status2["ABORTED"] = 10] = "ABORTED";
      Status2[Status2["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE";
      Status2[Status2["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED";
      Status2[Status2["INTERNAL"] = 13] = "INTERNAL";
      Status2[Status2["UNAVAILABLE"] = 14] = "UNAVAILABLE";
      Status2[Status2["DATA_LOSS"] = 15] = "DATA_LOSS";
      Status2[Status2["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED";
    })(Status || (exports2.Status = Status = {}));
    var LogVerbosity;
    (function(LogVerbosity2) {
      LogVerbosity2[LogVerbosity2["DEBUG"] = 0] = "DEBUG";
      LogVerbosity2[LogVerbosity2["INFO"] = 1] = "INFO";
      LogVerbosity2[LogVerbosity2["ERROR"] = 2] = "ERROR";
      LogVerbosity2[LogVerbosity2["NONE"] = 3] = "NONE";
    })(LogVerbosity || (exports2.LogVerbosity = LogVerbosity = {}));
    var Propagate;
    (function(Propagate2) {
      Propagate2[Propagate2["DEADLINE"] = 1] = "DEADLINE";
      Propagate2[Propagate2["CENSUS_STATS_CONTEXT"] = 2] = "CENSUS_STATS_CONTEXT";
      Propagate2[Propagate2["CENSUS_TRACING_CONTEXT"] = 4] = "CENSUS_TRACING_CONTEXT";
      Propagate2[Propagate2["CANCELLATION"] = 8] = "CANCELLATION";
      Propagate2[Propagate2["DEFAULTS"] = 65535] = "DEFAULTS";
    })(Propagate || (exports2.Propagate = Propagate = {}));
    exports2.DEFAULT_MAX_SEND_MESSAGE_LENGTH = -1;
    exports2.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = 4 * 1024 * 1024;
  }
});

// node_modules/@grpc/grpc-js/package.json
var require_package3 = __commonJS({
  "node_modules/@grpc/grpc-js/package.json"(exports2, module2) {
    module2.exports = {
      name: "@grpc/grpc-js",
      version: "1.13.4",
      description: "gRPC Library for Node - pure JS implementation",
      homepage: "https://grpc.io/",
      repository: "https://github.com/grpc/grpc-node/tree/master/packages/grpc-js",
      main: "build/src/index.js",
      engines: {
        node: ">=12.10.0"
      },
      keywords: [],
      author: {
        name: "Google Inc."
      },
      types: "build/src/index.d.ts",
      license: "Apache-2.0",
      devDependencies: {
        "@grpc/proto-loader": "file:../proto-loader",
        "@types/gulp": "^4.0.17",
        "@types/gulp-mocha": "0.0.37",
        "@types/lodash": "^4.14.202",
        "@types/mocha": "^10.0.6",
        "@types/ncp": "^2.0.8",
        "@types/node": ">=20.11.20",
        "@types/pify": "^5.0.4",
        "@types/semver": "^7.5.8",
        "@typescript-eslint/eslint-plugin": "^7.1.0",
        "@typescript-eslint/parser": "^7.1.0",
        "@typescript-eslint/typescript-estree": "^7.1.0",
        "clang-format": "^1.8.0",
        eslint: "^8.42.0",
        "eslint-config-prettier": "^8.8.0",
        "eslint-plugin-node": "^11.1.0",
        "eslint-plugin-prettier": "^4.2.1",
        execa: "^2.0.3",
        gulp: "^4.0.2",
        "gulp-mocha": "^6.0.0",
        lodash: "^4.17.21",
        madge: "^5.0.1",
        "mocha-jenkins-reporter": "^0.4.1",
        ncp: "^2.0.0",
        pify: "^4.0.1",
        prettier: "^2.8.8",
        rimraf: "^3.0.2",
        semver: "^7.6.0",
        "ts-node": "^10.9.2",
        typescript: "^5.3.3"
      },
      contributors: [
        {
          name: "Google Inc."
        }
      ],
      scripts: {
        build: "npm run compile",
        clean: "rimraf ./build",
        compile: "tsc -p .",
        format: 'clang-format -i -style="{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}" src/*.ts test/*.ts',
        lint: "eslint src/*.ts test/*.ts",
        prepare: "npm run generate-types && npm run compile",
        test: "gulp test",
        check: "npm run lint",
        fix: "eslint --fix src/*.ts test/*.ts",
        pretest: "npm run generate-types && npm run generate-test-types && npm run compile",
        posttest: "npm run check && madge -c ./build/src",
        "generate-types": "proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --includeDirs proto/ --include-dirs test/fixtures/ -O src/generated/ --grpcLib ../index channelz.proto",
        "generate-test-types": "proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --include-dirs test/fixtures/ -O test/generated/ --grpcLib ../../src/index test_service.proto"
      },
      dependencies: {
        "@grpc/proto-loader": "^0.7.13",
        "@js-sdsl/ordered-map": "^4.4.2"
      },
      files: [
        "src/**/*.ts",
        "build/src/**/*.{js,d.ts,js.map}",
        "proto/*.proto",
        "LICENSE",
        "deps/envoy-api/envoy/api/v2/**/*.proto",
        "deps/envoy-api/envoy/config/**/*.proto",
        "deps/envoy-api/envoy/service/**/*.proto",
        "deps/envoy-api/envoy/type/**/*.proto",
        "deps/udpa/udpa/**/*.proto",
        "deps/googleapis/google/api/*.proto",
        "deps/googleapis/google/rpc/*.proto",
        "deps/protoc-gen-validate/validate/**/*.proto"
      ]
    };
  }
});

// node_modules/@grpc/grpc-js/build/src/logging.js
var require_logging = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/logging.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var _a6;
    var _b2;
    var _c2;
    var _d;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.log = exports2.setLoggerVerbosity = exports2.setLogger = exports2.getLogger = void 0;
    exports2.trace = trace2;
    exports2.isTracerEnabled = isTracerEnabled;
    var constants_1 = require_constants9();
    var process_1 = __require("process");
    var clientVersion = require_package3().version;
    var DEFAULT_LOGGER = {
      error: /* @__PURE__ */ __name((message, ...optionalParams) => {
        console.error("E " + message, ...optionalParams);
      }, "error"),
      info: /* @__PURE__ */ __name((message, ...optionalParams) => {
        console.error("I " + message, ...optionalParams);
      }, "info"),
      debug: /* @__PURE__ */ __name((message, ...optionalParams) => {
        console.error("D " + message, ...optionalParams);
      }, "debug")
    };
    var _logger = DEFAULT_LOGGER;
    var _logVerbosity = constants_1.LogVerbosity.ERROR;
    var verbosityString = (_b2 = (_a6 = process.env.GRPC_NODE_VERBOSITY) !== null && _a6 !== void 0 ? _a6 : process.env.GRPC_VERBOSITY) !== null && _b2 !== void 0 ? _b2 : "";
    switch (verbosityString.toUpperCase()) {
      case "DEBUG":
        _logVerbosity = constants_1.LogVerbosity.DEBUG;
        break;
      case "INFO":
        _logVerbosity = constants_1.LogVerbosity.INFO;
        break;
      case "ERROR":
        _logVerbosity = constants_1.LogVerbosity.ERROR;
        break;
      case "NONE":
        _logVerbosity = constants_1.LogVerbosity.NONE;
        break;
      default:
    }
    var getLogger = /* @__PURE__ */ __name(() => {
      return _logger;
    }, "getLogger");
    exports2.getLogger = getLogger;
    var setLogger = /* @__PURE__ */ __name((logger6) => {
      _logger = logger6;
    }, "setLogger");
    exports2.setLogger = setLogger;
    var setLoggerVerbosity = /* @__PURE__ */ __name((verbosity) => {
      _logVerbosity = verbosity;
    }, "setLoggerVerbosity");
    exports2.setLoggerVerbosity = setLoggerVerbosity;
    var log = /* @__PURE__ */ __name((severity, ...args) => {
      let logFunction;
      if (severity >= _logVerbosity) {
        switch (severity) {
          case constants_1.LogVerbosity.DEBUG:
            logFunction = _logger.debug;
            break;
          case constants_1.LogVerbosity.INFO:
            logFunction = _logger.info;
            break;
          case constants_1.LogVerbosity.ERROR:
            logFunction = _logger.error;
            break;
        }
        if (!logFunction) {
          logFunction = _logger.error;
        }
        if (logFunction) {
          logFunction.bind(_logger)(...args);
        }
      }
    }, "log");
    exports2.log = log;
    var tracersString = (_d = (_c2 = process.env.GRPC_NODE_TRACE) !== null && _c2 !== void 0 ? _c2 : process.env.GRPC_TRACE) !== null && _d !== void 0 ? _d : "";
    var enabledTracers = /* @__PURE__ */ new Set();
    var disabledTracers = /* @__PURE__ */ new Set();
    for (const tracerName of tracersString.split(",")) {
      if (tracerName.startsWith("-")) {
        disabledTracers.add(tracerName.substring(1));
      } else {
        enabledTracers.add(tracerName);
      }
    }
    var allEnabled = enabledTracers.has("all");
    function trace2(severity, tracer, text) {
      if (isTracerEnabled(tracer)) {
        (0, exports2.log)(severity, (/* @__PURE__ */ new Date()).toISOString() + " | v" + clientVersion + " " + process_1.pid + " | " + tracer + " | " + text);
      }
    }
    __name(trace2, "trace");
    function isTracerEnabled(tracer) {
      return !disabledTracers.has(tracer) && (allEnabled || enabledTracers.has(tracer));
    }
    __name(isTracerEnabled, "isTracerEnabled");
  }
});

// node_modules/@grpc/grpc-js/build/src/error.js
var require_error = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/error.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getErrorMessage = getErrorMessage4;
    exports2.getErrorCode = getErrorCode;
    function getErrorMessage4(error) {
      if (error instanceof Error) {
        return error.message;
      } else {
        return String(error);
      }
    }
    __name(getErrorMessage4, "getErrorMessage");
    function getErrorCode(error) {
      if (typeof error === "object" && error !== null && "code" in error && typeof error.code === "number") {
        return error.code;
      } else {
        return null;
      }
    }
    __name(getErrorCode, "getErrorCode");
  }
});

// node_modules/@grpc/grpc-js/build/src/metadata.js
var require_metadata3 = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/metadata.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Metadata = void 0;
    var logging_1 = require_logging();
    var constants_1 = require_constants9();
    var error_1 = require_error();
    var LEGAL_KEY_REGEX = /^[0-9a-z_.-]+$/;
    var LEGAL_NON_BINARY_VALUE_REGEX = /^[ -~]*$/;
    function isLegalKey(key) {
      return LEGAL_KEY_REGEX.test(key);
    }
    __name(isLegalKey, "isLegalKey");
    function isLegalNonBinaryValue(value) {
      return LEGAL_NON_BINARY_VALUE_REGEX.test(value);
    }
    __name(isLegalNonBinaryValue, "isLegalNonBinaryValue");
    function isBinaryKey(key) {
      return key.endsWith("-bin");
    }
    __name(isBinaryKey, "isBinaryKey");
    function isCustomMetadata(key) {
      return !key.startsWith("grpc-");
    }
    __name(isCustomMetadata, "isCustomMetadata");
    function normalizeKey(key) {
      return key.toLowerCase();
    }
    __name(normalizeKey, "normalizeKey");
    function validate4(key, value) {
      if (!isLegalKey(key)) {
        throw new Error('Metadata key "' + key + '" contains illegal characters');
      }
      if (value !== null && value !== void 0) {
        if (isBinaryKey(key)) {
          if (!Buffer.isBuffer(value)) {
            throw new Error("keys that end with '-bin' must have Buffer values");
          }
        } else {
          if (Buffer.isBuffer(value)) {
            throw new Error("keys that don't end with '-bin' must have String values");
          }
          if (!isLegalNonBinaryValue(value)) {
            throw new Error('Metadata string value "' + value + '" contains illegal characters');
          }
        }
      }
    }
    __name(validate4, "validate");
    var Metadata = class _Metadata {
      static {
        __name(this, "Metadata");
      }
      constructor(options2 = {}) {
        this.internalRepr = /* @__PURE__ */ new Map();
        this.options = options2;
      }
      /**
       * Sets the given value for the given key by replacing any other values
       * associated with that key. Normalizes the key.
       * @param key The key to whose value should be set.
       * @param value The value to set. Must be a buffer if and only
       *   if the normalized key ends with '-bin'.
       */
      set(key, value) {
        key = normalizeKey(key);
        validate4(key, value);
        this.internalRepr.set(key, [value]);
      }
      /**
       * Adds the given value for the given key by appending to a list of previous
       * values associated with that key. Normalizes the key.
       * @param key The key for which a new value should be appended.
       * @param value The value to add. Must be a buffer if and only
       *   if the normalized key ends with '-bin'.
       */
      add(key, value) {
        key = normalizeKey(key);
        validate4(key, value);
        const existingValue = this.internalRepr.get(key);
        if (existingValue === void 0) {
          this.internalRepr.set(key, [value]);
        } else {
          existingValue.push(value);
        }
      }
      /**
       * Removes the given key and any associated values. Normalizes the key.
       * @param key The key whose values should be removed.
       */
      remove(key) {
        key = normalizeKey(key);
        this.internalRepr.delete(key);
      }
      /**
       * Gets a list of all values associated with the key. Normalizes the key.
       * @param key The key whose value should be retrieved.
       * @return A list of values associated with the given key.
       */
      get(key) {
        key = normalizeKey(key);
        return this.internalRepr.get(key) || [];
      }
      /**
       * Gets a plain object mapping each key to the first value associated with it.
       * This reflects the most common way that people will want to see metadata.
       * @return A key/value mapping of the metadata.
       */
      getMap() {
        const result = {};
        for (const [key, values] of this.internalRepr) {
          if (values.length > 0) {
            const v = values[0];
            result[key] = Buffer.isBuffer(v) ? Buffer.from(v) : v;
          }
        }
        return result;
      }
      /**
       * Clones the metadata object.
       * @return The newly cloned object.
       */
      clone() {
        const newMetadata = new _Metadata(this.options);
        const newInternalRepr = newMetadata.internalRepr;
        for (const [key, value] of this.internalRepr) {
          const clonedValue = value.map((v) => {
            if (Buffer.isBuffer(v)) {
              return Buffer.from(v);
            } else {
              return v;
            }
          });
          newInternalRepr.set(key, clonedValue);
        }
        return newMetadata;
      }
      /**
       * Merges all key-value pairs from a given Metadata object into this one.
       * If both this object and the given object have values in the same key,
       * values from the other Metadata object will be appended to this object's
       * values.
       * @param other A Metadata object.
       */
      merge(other2) {
        for (const [key, values] of other2.internalRepr) {
          const mergedValue = (this.internalRepr.get(key) || []).concat(values);
          this.internalRepr.set(key, mergedValue);
        }
      }
      setOptions(options2) {
        this.options = options2;
      }
      getOptions() {
        return this.options;
      }
      /**
       * Creates an OutgoingHttpHeaders object that can be used with the http2 API.
       */
      toHttp2Headers() {
        const result = {};
        for (const [key, values] of this.internalRepr) {
          result[key] = values.map(bufToString);
        }
        return result;
      }
      /**
       * This modifies the behavior of JSON.stringify to show an object
       * representation of the metadata map.
       */
      toJSON() {
        const result = {};
        for (const [key, values] of this.internalRepr) {
          result[key] = values;
        }
        return result;
      }
      /**
       * Returns a new Metadata object based fields in a given IncomingHttpHeaders
       * object.
       * @param headers An IncomingHttpHeaders object.
       */
      static fromHttp2Headers(headers) {
        const result = new _Metadata();
        for (const key of Object.keys(headers)) {
          if (key.charAt(0) === ":") {
            continue;
          }
          const values = headers[key];
          try {
            if (isBinaryKey(key)) {
              if (Array.isArray(values)) {
                values.forEach((value) => {
                  result.add(key, Buffer.from(value, "base64"));
                });
              } else if (values !== void 0) {
                if (isCustomMetadata(key)) {
                  values.split(",").forEach((v) => {
                    result.add(key, Buffer.from(v.trim(), "base64"));
                  });
                } else {
                  result.add(key, Buffer.from(values, "base64"));
                }
              }
            } else {
              if (Array.isArray(values)) {
                values.forEach((value) => {
                  result.add(key, value);
                });
              } else if (values !== void 0) {
                result.add(key, values);
              }
            }
          } catch (error) {
            const message = `Failed to add metadata entry ${key}: ${values}. ${(0, error_1.getErrorMessage)(error)}. For more information see https://github.com/grpc/grpc-node/issues/1173`;
            (0, logging_1.log)(constants_1.LogVerbosity.ERROR, message);
          }
        }
        return result;
      }
    };
    exports2.Metadata = Metadata;
    var bufToString = /* @__PURE__ */ __name((val) => {
      return Buffer.isBuffer(val) ? val.toString("base64") : val;
    }, "bufToString");
  }
});

// node_modules/@grpc/grpc-js/build/src/call-credentials.js
var require_call_credentials = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/call-credentials.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CallCredentials = void 0;
    var metadata_1 = require_metadata3();
    function isCurrentOauth2Client(client) {
      return "getRequestHeaders" in client && typeof client.getRequestHeaders === "function";
    }
    __name(isCurrentOauth2Client, "isCurrentOauth2Client");
    var CallCredentials = class _CallCredentials {
      static {
        __name(this, "CallCredentials");
      }
      /**
       * Creates a new CallCredentials object from a given function that generates
       * Metadata objects.
       * @param metadataGenerator A function that accepts a set of options, and
       * generates a Metadata object based on these options, which is passed back
       * to the caller via a supplied (err, metadata) callback.
       */
      static createFromMetadataGenerator(metadataGenerator) {
        return new SingleCallCredentials(metadataGenerator);
      }
      /**
       * Create a gRPC credential from a Google credential object.
       * @param googleCredentials The authentication client to use.
       * @return The resulting CallCredentials object.
       */
      static createFromGoogleCredential(googleCredentials) {
        return _CallCredentials.createFromMetadataGenerator((options2, callback) => {
          let getHeaders;
          if (isCurrentOauth2Client(googleCredentials)) {
            getHeaders = googleCredentials.getRequestHeaders(options2.service_url);
          } else {
            getHeaders = new Promise((resolve24, reject) => {
              googleCredentials.getRequestMetadata(options2.service_url, (err, headers) => {
                if (err) {
                  reject(err);
                  return;
                }
                if (!headers) {
                  reject(new Error("Headers not set by metadata plugin"));
                  return;
                }
                resolve24(headers);
              });
            });
          }
          getHeaders.then((headers) => {
            const metadata = new metadata_1.Metadata();
            for (const key of Object.keys(headers)) {
              metadata.add(key, headers[key]);
            }
            callback(null, metadata);
          }, (err) => {
            callback(err);
          });
        });
      }
      static createEmpty() {
        return new EmptyCallCredentials();
      }
    };
    exports2.CallCredentials = CallCredentials;
    var ComposedCallCredentials = class _ComposedCallCredentials extends CallCredentials {
      static {
        __name(this, "ComposedCallCredentials");
      }
      constructor(creds) {
        super();
        this.creds = creds;
      }
      async generateMetadata(options2) {
        const base = new metadata_1.Metadata();
        const generated = await Promise.all(this.creds.map((cred) => cred.generateMetadata(options2)));
        for (const gen of generated) {
          base.merge(gen);
        }
        return base;
      }
      compose(other2) {
        return new _ComposedCallCredentials(this.creds.concat([other2]));
      }
      _equals(other2) {
        if (this === other2) {
          return true;
        }
        if (other2 instanceof _ComposedCallCredentials) {
          return this.creds.every((value, index) => value._equals(other2.creds[index]));
        } else {
          return false;
        }
      }
    };
    var SingleCallCredentials = class _SingleCallCredentials extends CallCredentials {
      static {
        __name(this, "SingleCallCredentials");
      }
      constructor(metadataGenerator) {
        super();
        this.metadataGenerator = metadataGenerator;
      }
      generateMetadata(options2) {
        return new Promise((resolve24, reject) => {
          this.metadataGenerator(options2, (err, metadata) => {
            if (metadata !== void 0) {
              resolve24(metadata);
            } else {
              reject(err);
            }
          });
        });
      }
      compose(other2) {
        return new ComposedCallCredentials([this, other2]);
      }
      _equals(other2) {
        if (this === other2) {
          return true;
        }
        if (other2 instanceof _SingleCallCredentials) {
          return this.metadataGenerator === other2.metadataGenerator;
        } else {
          return false;
        }
      }
    };
    var EmptyCallCredentials = class _EmptyCallCredentials extends CallCredentials {
      static {
        __name(this, "EmptyCallCredentials");
      }
      generateMetadata(options2) {
        return Promise.resolve(new metadata_1.Metadata());
      }
      compose(other2) {
        return other2;
      }
      _equals(other2) {
        return other2 instanceof _EmptyCallCredentials;
      }
    };
  }
});

// node_modules/@grpc/grpc-js/build/src/tls-helpers.js
var require_tls_helpers = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/tls-helpers.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CIPHER_SUITES = void 0;
    exports2.getDefaultRootsData = getDefaultRootsData;
    var fs95 = __require("fs");
    exports2.CIPHER_SUITES = process.env.GRPC_SSL_CIPHER_SUITES;
    var DEFAULT_ROOTS_FILE_PATH = process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH;
    var defaultRootsData = null;
    function getDefaultRootsData() {
      if (DEFAULT_ROOTS_FILE_PATH) {
        if (defaultRootsData === null) {
          defaultRootsData = fs95.readFileSync(DEFAULT_ROOTS_FILE_PATH);
        }
        return defaultRootsData;
      }
      return null;
    }
    __name(getDefaultRootsData, "getDefaultRootsData");
  }
});

// node_modules/@grpc/grpc-js/build/src/uri-parser.js
var require_uri_parser = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/uri-parser.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.parseUri = parseUri;
    exports2.splitHostPort = splitHostPort;
    exports2.combineHostPort = combineHostPort;
    exports2.uriToString = uriToString;
    var URI_REGEX = /^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/;
    function parseUri(uriString) {
      const parsedUri = URI_REGEX.exec(uriString);
      if (parsedUri === null) {
        return null;
      }
      return {
        scheme: parsedUri[1],
        authority: parsedUri[2],
        path: parsedUri[3]
      };
    }
    __name(parseUri, "parseUri");
    var NUMBER_REGEX = /^\d+$/;
    function splitHostPort(path108) {
      if (path108.startsWith("[")) {
        const hostEnd = path108.indexOf("]");
        if (hostEnd === -1) {
          return null;
        }
        const host = path108.substring(1, hostEnd);
        if (host.indexOf(":") === -1) {
          return null;
        }
        if (path108.length > hostEnd + 1) {
          if (path108[hostEnd + 1] === ":") {
            const portString = path108.substring(hostEnd + 2);
            if (NUMBER_REGEX.test(portString)) {
              return {
                host,
                port: +portString
              };
            } else {
              return null;
            }
          } else {
            return null;
          }
        } else {
          return {
            host
          };
        }
      } else {
        const splitPath = path108.split(":");
        if (splitPath.length === 2) {
          if (NUMBER_REGEX.test(splitPath[1])) {
            return {
              host: splitPath[0],
              port: +splitPath[1]
            };
          } else {
            return null;
          }
        } else {
          return {
            host: path108
          };
        }
      }
    }
    __name(splitHostPort, "splitHostPort");
    function combineHostPort(hostPort) {
      if (hostPort.port === void 0) {
        return hostPort.host;
      } else {
        if (hostPort.host.includes(":")) {
          return `[${hostPort.host}]:${hostPort.port}`;
        } else {
          return `${hostPort.host}:${hostPort.port}`;
        }
      }
    }
    __name(combineHostPort, "combineHostPort");
    function uriToString(uri) {
      let result = "";
      if (uri.scheme !== void 0) {
        result += uri.scheme + ":";
      }
      if (uri.authority !== void 0) {
        result += "//" + uri.authority + "/";
      }
      result += uri.path;
      return result;
    }
    __name(uriToString, "uriToString");
  }
});

// node_modules/@grpc/grpc-js/build/src/resolver.js
var require_resolver = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/resolver.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.registerResolver = registerResolver;
    exports2.registerDefaultScheme = registerDefaultScheme;
    exports2.createResolver = createResolver;
    exports2.getDefaultAuthority = getDefaultAuthority;
    exports2.mapUriDefaultScheme = mapUriDefaultScheme;
    var uri_parser_1 = require_uri_parser();
    var registeredResolvers = {};
    var defaultScheme = null;
    function registerResolver(scheme, resolverClass) {
      registeredResolvers[scheme] = resolverClass;
    }
    __name(registerResolver, "registerResolver");
    function registerDefaultScheme(scheme) {
      defaultScheme = scheme;
    }
    __name(registerDefaultScheme, "registerDefaultScheme");
    function createResolver(target, listener, options2) {
      if (target.scheme !== void 0 && target.scheme in registeredResolvers) {
        return new registeredResolvers[target.scheme](target, listener, options2);
      } else {
        throw new Error(`No resolver could be created for target ${(0, uri_parser_1.uriToString)(target)}`);
      }
    }
    __name(createResolver, "createResolver");
    function getDefaultAuthority(target) {
      if (target.scheme !== void 0 && target.scheme in registeredResolvers) {
        return registeredResolvers[target.scheme].getDefaultAuthority(target);
      } else {
        throw new Error(`Invalid target ${(0, uri_parser_1.uriToString)(target)}`);
      }
    }
    __name(getDefaultAuthority, "getDefaultAuthority");
    function mapUriDefaultScheme(target) {
      if (target.scheme === void 0 || !(target.scheme in registeredResolvers)) {
        if (defaultScheme !== null) {
          return {
            scheme: defaultScheme,
            authority: void 0,
            path: (0, uri_parser_1.uriToString)(target)
          };
        } else {
          return null;
        }
      }
      return target;
    }
    __name(mapUriDefaultScheme, "mapUriDefaultScheme");
  }
});

// node_modules/@grpc/grpc-js/build/src/channel-credentials.js
var require_channel_credentials = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/channel-credentials.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ChannelCredentials = void 0;
    exports2.createCertificateProviderChannelCredentials = createCertificateProviderChannelCredentials;
    var tls_1 = __require("tls");
    var call_credentials_1 = require_call_credentials();
    var tls_helpers_1 = require_tls_helpers();
    var uri_parser_1 = require_uri_parser();
    var resolver_1 = require_resolver();
    var logging_1 = require_logging();
    var constants_1 = require_constants9();
    function verifyIsBufferOrNull(obj, friendlyName) {
      if (obj && !(obj instanceof Buffer)) {
        throw new TypeError(`${friendlyName}, if provided, must be a Buffer.`);
      }
    }
    __name(verifyIsBufferOrNull, "verifyIsBufferOrNull");
    var ChannelCredentials = class {
      static {
        __name(this, "ChannelCredentials");
      }
      /**
       * Returns a copy of this object with the included set of per-call credentials
       * expanded to include callCredentials.
       * @param callCredentials A CallCredentials object to associate with this
       * instance.
       */
      compose(callCredentials) {
        return new ComposedChannelCredentialsImpl(this, callCredentials);
      }
      /**
       * Return a new ChannelCredentials instance with a given set of credentials.
       * The resulting instance can be used to construct a Channel that communicates
       * over TLS.
       * @param rootCerts The root certificate data.
       * @param privateKey The client certificate private key, if available.
       * @param certChain The client certificate key chain, if available.
       * @param verifyOptions Additional options to modify certificate verification
       */
      static createSsl(rootCerts, privateKey, certChain, verifyOptions) {
        var _a6;
        verifyIsBufferOrNull(rootCerts, "Root certificate");
        verifyIsBufferOrNull(privateKey, "Private key");
        verifyIsBufferOrNull(certChain, "Certificate chain");
        if (privateKey && !certChain) {
          throw new Error("Private key must be given with accompanying certificate chain");
        }
        if (!privateKey && certChain) {
          throw new Error("Certificate chain must be given with accompanying private key");
        }
        const secureContext = (0, tls_1.createSecureContext)({
          ca: (_a6 = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a6 !== void 0 ? _a6 : void 0,
          key: privateKey !== null && privateKey !== void 0 ? privateKey : void 0,
          cert: certChain !== null && certChain !== void 0 ? certChain : void 0,
          ciphers: tls_helpers_1.CIPHER_SUITES
        });
        return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {});
      }
      /**
       * Return a new ChannelCredentials instance with credentials created using
       * the provided secureContext. The resulting instances can be used to
       * construct a Channel that communicates over TLS. gRPC will not override
       * anything in the provided secureContext, so the environment variables
       * GRPC_SSL_CIPHER_SUITES and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH will
       * not be applied.
       * @param secureContext The return value of tls.createSecureContext()
       * @param verifyOptions Additional options to modify certificate verification
       */
      static createFromSecureContext(secureContext, verifyOptions) {
        return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {});
      }
      /**
       * Return a new ChannelCredentials instance with no credentials.
       */
      static createInsecure() {
        return new InsecureChannelCredentialsImpl();
      }
    };
    exports2.ChannelCredentials = ChannelCredentials;
    var InsecureChannelCredentialsImpl = class _InsecureChannelCredentialsImpl extends ChannelCredentials {
      static {
        __name(this, "InsecureChannelCredentialsImpl");
      }
      constructor() {
        super();
      }
      compose(callCredentials) {
        throw new Error("Cannot compose insecure credentials");
      }
      _isSecure() {
        return false;
      }
      _equals(other2) {
        return other2 instanceof _InsecureChannelCredentialsImpl;
      }
      _createSecureConnector(channelTarget, options2, callCredentials) {
        return {
          connect(socket) {
            return Promise.resolve({
              socket,
              secure: false
            });
          },
          waitForReady: /* @__PURE__ */ __name(() => {
            return Promise.resolve();
          }, "waitForReady"),
          getCallCredentials: /* @__PURE__ */ __name(() => {
            return callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty();
          }, "getCallCredentials"),
          destroy() {
          }
        };
      }
    };
    function getConnectionOptions(secureContext, verifyOptions, channelTarget, options2) {
      var _a6, _b2;
      const connectionOptions = {
        secureContext
      };
      let realTarget = channelTarget;
      if ("grpc.http_connect_target" in options2) {
        const parsedTarget = (0, uri_parser_1.parseUri)(options2["grpc.http_connect_target"]);
        if (parsedTarget) {
          realTarget = parsedTarget;
        }
      }
      const targetPath = (0, resolver_1.getDefaultAuthority)(realTarget);
      const hostPort = (0, uri_parser_1.splitHostPort)(targetPath);
      const remoteHost = (_a6 = hostPort === null || hostPort === void 0 ? void 0 : hostPort.host) !== null && _a6 !== void 0 ? _a6 : targetPath;
      connectionOptions.host = remoteHost;
      if (verifyOptions.checkServerIdentity) {
        connectionOptions.checkServerIdentity = verifyOptions.checkServerIdentity;
      }
      if (verifyOptions.rejectUnauthorized !== void 0) {
        connectionOptions.rejectUnauthorized = verifyOptions.rejectUnauthorized;
      }
      connectionOptions.ALPNProtocols = ["h2"];
      if (options2["grpc.ssl_target_name_override"]) {
        const sslTargetNameOverride = options2["grpc.ssl_target_name_override"];
        const originalCheckServerIdentity = (_b2 = connectionOptions.checkServerIdentity) !== null && _b2 !== void 0 ? _b2 : tls_1.checkServerIdentity;
        connectionOptions.checkServerIdentity = (host, cert) => {
          return originalCheckServerIdentity(sslTargetNameOverride, cert);
        };
        connectionOptions.servername = sslTargetNameOverride;
      } else {
        connectionOptions.servername = remoteHost;
      }
      if (options2["grpc-node.tls_enable_trace"]) {
        connectionOptions.enableTrace = true;
      }
      return connectionOptions;
    }
    __name(getConnectionOptions, "getConnectionOptions");
    var SecureConnectorImpl = class {
      static {
        __name(this, "SecureConnectorImpl");
      }
      constructor(connectionOptions, callCredentials) {
        this.connectionOptions = connectionOptions;
        this.callCredentials = callCredentials;
      }
      connect(socket) {
        const tlsConnectOptions = Object.assign({ socket }, this.connectionOptions);
        return new Promise((resolve24, reject) => {
          const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => {
            var _a6;
            if (((_a6 = this.connectionOptions.rejectUnauthorized) !== null && _a6 !== void 0 ? _a6 : true) && !tlsSocket.authorized) {
              reject(tlsSocket.authorizationError);
              return;
            }
            resolve24({
              socket: tlsSocket,
              secure: true
            });
          });
          tlsSocket.on("error", (error) => {
            reject(error);
          });
        });
      }
      waitForReady() {
        return Promise.resolve();
      }
      getCallCredentials() {
        return this.callCredentials;
      }
      destroy() {
      }
    };
    var SecureChannelCredentialsImpl = class _SecureChannelCredentialsImpl extends ChannelCredentials {
      static {
        __name(this, "SecureChannelCredentialsImpl");
      }
      constructor(secureContext, verifyOptions) {
        super();
        this.secureContext = secureContext;
        this.verifyOptions = verifyOptions;
      }
      _isSecure() {
        return true;
      }
      _equals(other2) {
        if (this === other2) {
          return true;
        }
        if (other2 instanceof _SecureChannelCredentialsImpl) {
          return this.secureContext === other2.secureContext && this.verifyOptions.checkServerIdentity === other2.verifyOptions.checkServerIdentity;
        } else {
          return false;
        }
      }
      _createSecureConnector(channelTarget, options2, callCredentials) {
        const connectionOptions = getConnectionOptions(this.secureContext, this.verifyOptions, channelTarget, options2);
        return new SecureConnectorImpl(connectionOptions, callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty());
      }
    };
    var CertificateProviderChannelCredentialsImpl = class _CertificateProviderChannelCredentialsImpl extends ChannelCredentials {
      static {
        __name(this, "CertificateProviderChannelCredentialsImpl");
      }
      constructor(caCertificateProvider, identityCertificateProvider, verifyOptions) {
        super();
        this.caCertificateProvider = caCertificateProvider;
        this.identityCertificateProvider = identityCertificateProvider;
        this.verifyOptions = verifyOptions;
        this.refcount = 0;
        this.latestCaUpdate = void 0;
        this.latestIdentityUpdate = void 0;
        this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this);
        this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this);
        this.secureContextWatchers = [];
      }
      _isSecure() {
        return true;
      }
      _equals(other2) {
        var _a6, _b2;
        if (this === other2) {
          return true;
        }
        if (other2 instanceof _CertificateProviderChannelCredentialsImpl) {
          return this.caCertificateProvider === other2.caCertificateProvider && this.identityCertificateProvider === other2.identityCertificateProvider && ((_a6 = this.verifyOptions) === null || _a6 === void 0 ? void 0 : _a6.checkServerIdentity) === ((_b2 = other2.verifyOptions) === null || _b2 === void 0 ? void 0 : _b2.checkServerIdentity);
        } else {
          return false;
        }
      }
      ref() {
        var _a6;
        if (this.refcount === 0) {
          this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener);
          (_a6 = this.identityCertificateProvider) === null || _a6 === void 0 ? void 0 : _a6.addIdentityCertificateListener(this.identityCertificateUpdateListener);
        }
        this.refcount += 1;
      }
      unref() {
        var _a6;
        this.refcount -= 1;
        if (this.refcount === 0) {
          this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener);
          (_a6 = this.identityCertificateProvider) === null || _a6 === void 0 ? void 0 : _a6.removeIdentityCertificateListener(this.identityCertificateUpdateListener);
        }
      }
      _createSecureConnector(channelTarget, options2, callCredentials) {
        this.ref();
        return new _CertificateProviderChannelCredentialsImpl.SecureConnectorImpl(this, channelTarget, options2, callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty());
      }
      maybeUpdateWatchers() {
        if (this.hasReceivedUpdates()) {
          for (const watcher of this.secureContextWatchers) {
            watcher(this.getLatestSecureContext());
          }
          this.secureContextWatchers = [];
        }
      }
      handleCaCertificateUpdate(update2) {
        this.latestCaUpdate = update2;
        this.maybeUpdateWatchers();
      }
      handleIdentityCertitificateUpdate(update2) {
        this.latestIdentityUpdate = update2;
        this.maybeUpdateWatchers();
      }
      hasReceivedUpdates() {
        if (this.latestCaUpdate === void 0) {
          return false;
        }
        if (this.identityCertificateProvider && this.latestIdentityUpdate === void 0) {
          return false;
        }
        return true;
      }
      getSecureContext() {
        if (this.hasReceivedUpdates()) {
          return Promise.resolve(this.getLatestSecureContext());
        } else {
          return new Promise((resolve24) => {
            this.secureContextWatchers.push(resolve24);
          });
        }
      }
      getLatestSecureContext() {
        var _a6, _b2;
        if (!this.latestCaUpdate) {
          return null;
        }
        if (this.identityCertificateProvider !== null && !this.latestIdentityUpdate) {
          return null;
        }
        try {
          return (0, tls_1.createSecureContext)({
            ca: this.latestCaUpdate.caCertificate,
            key: (_a6 = this.latestIdentityUpdate) === null || _a6 === void 0 ? void 0 : _a6.privateKey,
            cert: (_b2 = this.latestIdentityUpdate) === null || _b2 === void 0 ? void 0 : _b2.certificate,
            ciphers: tls_helpers_1.CIPHER_SUITES
          });
        } catch (e2) {
          (0, logging_1.log)(constants_1.LogVerbosity.ERROR, "Failed to createSecureContext with error " + e2.message);
          return null;
        }
      }
    };
    CertificateProviderChannelCredentialsImpl.SecureConnectorImpl = class {
      constructor(parent, channelTarget, options2, callCredentials) {
        this.parent = parent;
        this.channelTarget = channelTarget;
        this.options = options2;
        this.callCredentials = callCredentials;
      }
      connect(socket) {
        return new Promise((resolve24, reject) => {
          const secureContext = this.parent.getLatestSecureContext();
          if (!secureContext) {
            reject(new Error("Failed to load credentials"));
            return;
          }
          if (socket.closed) {
            reject(new Error("Socket closed while loading credentials"));
          }
          const connnectionOptions = getConnectionOptions(secureContext, this.parent.verifyOptions, this.channelTarget, this.options);
          const tlsConnectOptions = Object.assign({ socket }, connnectionOptions);
          const closeCallback = /* @__PURE__ */ __name(() => {
            reject(new Error("Socket closed"));
          }, "closeCallback");
          const errorCallback = /* @__PURE__ */ __name((error) => {
            reject(error);
          }, "errorCallback");
          const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => {
            var _a6;
            tlsSocket.removeListener("close", closeCallback);
            tlsSocket.removeListener("error", errorCallback);
            if (((_a6 = this.parent.verifyOptions.rejectUnauthorized) !== null && _a6 !== void 0 ? _a6 : true) && !tlsSocket.authorized) {
              reject(tlsSocket.authorizationError);
              return;
            }
            resolve24({
              socket: tlsSocket,
              secure: true
            });
          });
          tlsSocket.once("close", closeCallback);
          tlsSocket.once("error", errorCallback);
        });
      }
      async waitForReady() {
        await this.parent.getSecureContext();
      }
      getCallCredentials() {
        return this.callCredentials;
      }
      destroy() {
        this.parent.unref();
      }
    };
    function createCertificateProviderChannelCredentials(caCertificateProvider, identityCertificateProvider, verifyOptions) {
      return new CertificateProviderChannelCredentialsImpl(caCertificateProvider, identityCertificateProvider, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {});
    }
    __name(createCertificateProviderChannelCredentials, "createCertificateProviderChannelCredentials");
    var ComposedChannelCredentialsImpl = class _ComposedChannelCredentialsImpl extends ChannelCredentials {
      static {
        __name(this, "ComposedChannelCredentialsImpl");
      }
      constructor(channelCredentials, callCredentials) {
        super();
        this.channelCredentials = channelCredentials;
        this.callCredentials = callCredentials;
        if (!channelCredentials._isSecure()) {
          throw new Error("Cannot compose insecure credentials");
        }
      }
      compose(callCredentials) {
        const combinedCallCredentials = this.callCredentials.compose(callCredentials);
        return new _ComposedChannelCredentialsImpl(this.channelCredentials, combinedCallCredentials);
      }
      _isSecure() {
        return true;
      }
      _equals(other2) {
        if (this === other2) {
          return true;
        }
        if (other2 instanceof _ComposedChannelCredentialsImpl) {
          return this.channelCredentials._equals(other2.channelCredentials) && this.callCredentials._equals(other2.callCredentials);
        } else {
          return false;
        }
      }
      _createSecureConnector(channelTarget, options2, callCredentials) {
        const combinedCallCredentials = this.callCredentials.compose(callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty());
        return this.channelCredentials._createSecureConnector(channelTarget, options2, combinedCallCredentials);
      }
    };
  }
});

// node_modules/@grpc/grpc-js/build/src/load-balancer.js
var require_load_balancer = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/load-balancer.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createChildChannelControlHelper = createChildChannelControlHelper;
    exports2.registerLoadBalancerType = registerLoadBalancerType;
    exports2.registerDefaultLoadBalancerType = registerDefaultLoadBalancerType;
    exports2.createLoadBalancer = createLoadBalancer;
    exports2.isLoadBalancerNameRegistered = isLoadBalancerNameRegistered;
    exports2.parseLoadBalancingConfig = parseLoadBalancingConfig;
    exports2.getDefaultConfig = getDefaultConfig;
    exports2.selectLbConfigFromList = selectLbConfigFromList;
    var logging_1 = require_logging();
    var constants_1 = require_constants9();
    function createChildChannelControlHelper(parent, overrides) {
      var _a6, _b2, _c2, _d, _e, _f, _g, _h, _j, _k;
      return {
        createSubchannel: (_b2 = (_a6 = overrides.createSubchannel) === null || _a6 === void 0 ? void 0 : _a6.bind(overrides)) !== null && _b2 !== void 0 ? _b2 : parent.createSubchannel.bind(parent),
        updateState: (_d = (_c2 = overrides.updateState) === null || _c2 === void 0 ? void 0 : _c2.bind(overrides)) !== null && _d !== void 0 ? _d : parent.updateState.bind(parent),
        requestReresolution: (_f = (_e = overrides.requestReresolution) === null || _e === void 0 ? void 0 : _e.bind(overrides)) !== null && _f !== void 0 ? _f : parent.requestReresolution.bind(parent),
        addChannelzChild: (_h = (_g = overrides.addChannelzChild) === null || _g === void 0 ? void 0 : _g.bind(overrides)) !== null && _h !== void 0 ? _h : parent.addChannelzChild.bind(parent),
        removeChannelzChild: (_k = (_j = overrides.removeChannelzChild) === null || _j === void 0 ? void 0 : _j.bind(overrides)) !== null && _k !== void 0 ? _k : parent.removeChannelzChild.bind(parent)
      };
    }
    __name(createChildChannelControlHelper, "createChildChannelControlHelper");
    var registeredLoadBalancerTypes = {};
    var defaultLoadBalancerType = null;
    function registerLoadBalancerType(typeName, loadBalancerType, loadBalancingConfigType) {
      registeredLoadBalancerTypes[typeName] = {
        LoadBalancer: loadBalancerType,
        LoadBalancingConfig: loadBalancingConfigType
      };
    }
    __name(registerLoadBalancerType, "registerLoadBalancerType");
    function registerDefaultLoadBalancerType(typeName) {
      defaultLoadBalancerType = typeName;
    }
    __name(registerDefaultLoadBalancerType, "registerDefaultLoadBalancerType");
    function createLoadBalancer(config, channelControlHelper) {
      const typeName = config.getLoadBalancerName();
      if (typeName in registeredLoadBalancerTypes) {
        return new registeredLoadBalancerTypes[typeName].LoadBalancer(channelControlHelper);
      } else {
        return null;
      }
    }
    __name(createLoadBalancer, "createLoadBalancer");
    function isLoadBalancerNameRegistered(typeName) {
      return typeName in registeredLoadBalancerTypes;
    }
    __name(isLoadBalancerNameRegistered, "isLoadBalancerNameRegistered");
    function parseLoadBalancingConfig(rawConfig) {
      const keys = Object.keys(rawConfig);
      if (keys.length !== 1) {
        throw new Error("Provided load balancing config has multiple conflicting entries");
      }
      const typeName = keys[0];
      if (typeName in registeredLoadBalancerTypes) {
        try {
          return registeredLoadBalancerTypes[typeName].LoadBalancingConfig.createFromJson(rawConfig[typeName]);
        } catch (e2) {
          throw new Error(`${typeName}: ${e2.message}`);
        }
      } else {
        throw new Error(`Unrecognized load balancing config name ${typeName}`);
      }
    }
    __name(parseLoadBalancingConfig, "parseLoadBalancingConfig");
    function getDefaultConfig() {
      if (!defaultLoadBalancerType) {
        throw new Error("No default load balancer type registered");
      }
      return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig();
    }
    __name(getDefaultConfig, "getDefaultConfig");
    function selectLbConfigFromList(configs, fallbackTodefault = false) {
      for (const config of configs) {
        try {
          return parseLoadBalancingConfig(config);
        } catch (e2) {
          (0, logging_1.log)(constants_1.LogVerbosity.DEBUG, "Config parsing failed with error", e2.message);
          continue;
        }
      }
      if (fallbackTodefault) {
        if (defaultLoadBalancerType) {
          return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig();
        } else {
          return null;
        }
      } else {
        return null;
      }
    }
    __name(selectLbConfigFromList, "selectLbConfigFromList");
  }
});

// node_modules/@grpc/grpc-js/build/src/service-config.js
var require_service_config = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/service-config.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateRetryThrottling = validateRetryThrottling;
    exports2.validateServiceConfig = validateServiceConfig;
    exports2.extractAndSelectServiceConfig = extractAndSelectServiceConfig;
    var os43 = __require("os");
    var constants_1 = require_constants9();
    var DURATION_REGEX = /^\d+(\.\d{1,9})?s$/;
    var CLIENT_LANGUAGE_STRING = "node";
    function validateName2(obj) {
      if ("service" in obj && obj.service !== "") {
        if (typeof obj.service !== "string") {
          throw new Error(`Invalid method config name: invalid service: expected type string, got ${typeof obj.service}`);
        }
        if ("method" in obj && obj.method !== "") {
          if (typeof obj.method !== "string") {
            throw new Error(`Invalid method config name: invalid method: expected type string, got ${typeof obj.service}`);
          }
          return {
            service: obj.service,
            method: obj.method
          };
        } else {
          return {
            service: obj.service
          };
        }
      } else {
        if ("method" in obj && obj.method !== void 0) {
          throw new Error(`Invalid method config name: method set with empty or unset service`);
        }
        return {};
      }
    }
    __name(validateName2, "validateName");
    function validateRetryPolicy(obj) {
      if (!("maxAttempts" in obj) || !Number.isInteger(obj.maxAttempts) || obj.maxAttempts < 2) {
        throw new Error("Invalid method config retry policy: maxAttempts must be an integer at least 2");
      }
      if (!("initialBackoff" in obj) || typeof obj.initialBackoff !== "string" || !DURATION_REGEX.test(obj.initialBackoff)) {
        throw new Error("Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s");
      }
      if (!("maxBackoff" in obj) || typeof obj.maxBackoff !== "string" || !DURATION_REGEX.test(obj.maxBackoff)) {
        throw new Error("Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s");
      }
      if (!("backoffMultiplier" in obj) || typeof obj.backoffMultiplier !== "number" || obj.backoffMultiplier <= 0) {
        throw new Error("Invalid method config retry policy: backoffMultiplier must be a number greater than 0");
      }
      if (!("retryableStatusCodes" in obj && Array.isArray(obj.retryableStatusCodes))) {
        throw new Error("Invalid method config retry policy: retryableStatusCodes is required");
      }
      if (obj.retryableStatusCodes.length === 0) {
        throw new Error("Invalid method config retry policy: retryableStatusCodes must be non-empty");
      }
      for (const value of obj.retryableStatusCodes) {
        if (typeof value === "number") {
          if (!Object.values(constants_1.Status).includes(value)) {
            throw new Error("Invalid method config retry policy: retryableStatusCodes value not in status code range");
          }
        } else if (typeof value === "string") {
          if (!Object.values(constants_1.Status).includes(value.toUpperCase())) {
            throw new Error("Invalid method config retry policy: retryableStatusCodes value not a status code name");
          }
        } else {
          throw new Error("Invalid method config retry policy: retryableStatusCodes value must be a string or number");
        }
      }
      return {
        maxAttempts: obj.maxAttempts,
        initialBackoff: obj.initialBackoff,
        maxBackoff: obj.maxBackoff,
        backoffMultiplier: obj.backoffMultiplier,
        retryableStatusCodes: obj.retryableStatusCodes
      };
    }
    __name(validateRetryPolicy, "validateRetryPolicy");
    function validateHedgingPolicy(obj) {
      if (!("maxAttempts" in obj) || !Number.isInteger(obj.maxAttempts) || obj.maxAttempts < 2) {
        throw new Error("Invalid method config hedging policy: maxAttempts must be an integer at least 2");
      }
      if ("hedgingDelay" in obj && (typeof obj.hedgingDelay !== "string" || !DURATION_REGEX.test(obj.hedgingDelay))) {
        throw new Error("Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s");
      }
      if ("nonFatalStatusCodes" in obj && Array.isArray(obj.nonFatalStatusCodes)) {
        for (const value of obj.nonFatalStatusCodes) {
          if (typeof value === "number") {
            if (!Object.values(constants_1.Status).includes(value)) {
              throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not in status code range");
            }
          } else if (typeof value === "string") {
            if (!Object.values(constants_1.Status).includes(value.toUpperCase())) {
              throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not a status code name");
            }
          } else {
            throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number");
          }
        }
      }
      const result = {
        maxAttempts: obj.maxAttempts
      };
      if (obj.hedgingDelay) {
        result.hedgingDelay = obj.hedgingDelay;
      }
      if (obj.nonFatalStatusCodes) {
        result.nonFatalStatusCodes = obj.nonFatalStatusCodes;
      }
      return result;
    }
    __name(validateHedgingPolicy, "validateHedgingPolicy");
    function validateMethodConfig(obj) {
      var _a6;
      const result = {
        name: []
      };
      if (!("name" in obj) || !Array.isArray(obj.name)) {
        throw new Error("Invalid method config: invalid name array");
      }
      for (const name3 of obj.name) {
        result.name.push(validateName2(name3));
      }
      if ("waitForReady" in obj) {
        if (typeof obj.waitForReady !== "boolean") {
          throw new Error("Invalid method config: invalid waitForReady");
        }
        result.waitForReady = obj.waitForReady;
      }
      if ("timeout" in obj) {
        if (typeof obj.timeout === "object") {
          if (!("seconds" in obj.timeout) || !(typeof obj.timeout.seconds === "number")) {
            throw new Error("Invalid method config: invalid timeout.seconds");
          }
          if (!("nanos" in obj.timeout) || !(typeof obj.timeout.nanos === "number")) {
            throw new Error("Invalid method config: invalid timeout.nanos");
          }
          result.timeout = obj.timeout;
        } else if (typeof obj.timeout === "string" && DURATION_REGEX.test(obj.timeout)) {
          const timeoutParts = obj.timeout.substring(0, obj.timeout.length - 1).split(".");
          result.timeout = {
            seconds: timeoutParts[0] | 0,
            nanos: ((_a6 = timeoutParts[1]) !== null && _a6 !== void 0 ? _a6 : 0) | 0
          };
        } else {
          throw new Error("Invalid method config: invalid timeout");
        }
      }
      if ("maxRequestBytes" in obj) {
        if (typeof obj.maxRequestBytes !== "number") {
          throw new Error("Invalid method config: invalid maxRequestBytes");
        }
        result.maxRequestBytes = obj.maxRequestBytes;
      }
      if ("maxResponseBytes" in obj) {
        if (typeof obj.maxResponseBytes !== "number") {
          throw new Error("Invalid method config: invalid maxRequestBytes");
        }
        result.maxResponseBytes = obj.maxResponseBytes;
      }
      if ("retryPolicy" in obj) {
        if ("hedgingPolicy" in obj) {
          throw new Error("Invalid method config: retryPolicy and hedgingPolicy cannot both be specified");
        } else {
          result.retryPolicy = validateRetryPolicy(obj.retryPolicy);
        }
      } else if ("hedgingPolicy" in obj) {
        result.hedgingPolicy = validateHedgingPolicy(obj.hedgingPolicy);
      }
      return result;
    }
    __name(validateMethodConfig, "validateMethodConfig");
    function validateRetryThrottling(obj) {
      if (!("maxTokens" in obj) || typeof obj.maxTokens !== "number" || obj.maxTokens <= 0 || obj.maxTokens > 1e3) {
        throw new Error("Invalid retryThrottling: maxTokens must be a number in (0, 1000]");
      }
      if (!("tokenRatio" in obj) || typeof obj.tokenRatio !== "number" || obj.tokenRatio <= 0) {
        throw new Error("Invalid retryThrottling: tokenRatio must be a number greater than 0");
      }
      return {
        maxTokens: +obj.maxTokens.toFixed(3),
        tokenRatio: +obj.tokenRatio.toFixed(3)
      };
    }
    __name(validateRetryThrottling, "validateRetryThrottling");
    function validateLoadBalancingConfig(obj) {
      if (!(typeof obj === "object" && obj !== null)) {
        throw new Error(`Invalid loadBalancingConfig: unexpected type ${typeof obj}`);
      }
      const keys = Object.keys(obj);
      if (keys.length > 1) {
        throw new Error(`Invalid loadBalancingConfig: unexpected multiple keys ${keys}`);
      }
      if (keys.length === 0) {
        throw new Error("Invalid loadBalancingConfig: load balancing policy name required");
      }
      return {
        [keys[0]]: obj[keys[0]]
      };
    }
    __name(validateLoadBalancingConfig, "validateLoadBalancingConfig");
    function validateServiceConfig(obj) {
      const result = {
        loadBalancingConfig: [],
        methodConfig: []
      };
      if ("loadBalancingPolicy" in obj) {
        if (typeof obj.loadBalancingPolicy === "string") {
          result.loadBalancingPolicy = obj.loadBalancingPolicy;
        } else {
          throw new Error("Invalid service config: invalid loadBalancingPolicy");
        }
      }
      if ("loadBalancingConfig" in obj) {
        if (Array.isArray(obj.loadBalancingConfig)) {
          for (const config of obj.loadBalancingConfig) {
            result.loadBalancingConfig.push(validateLoadBalancingConfig(config));
          }
        } else {
          throw new Error("Invalid service config: invalid loadBalancingConfig");
        }
      }
      if ("methodConfig" in obj) {
        if (Array.isArray(obj.methodConfig)) {
          for (const methodConfig of obj.methodConfig) {
            result.methodConfig.push(validateMethodConfig(methodConfig));
          }
        }
      }
      if ("retryThrottling" in obj) {
        result.retryThrottling = validateRetryThrottling(obj.retryThrottling);
      }
      const seenMethodNames = [];
      for (const methodConfig of result.methodConfig) {
        for (const name3 of methodConfig.name) {
          for (const seenName of seenMethodNames) {
            if (name3.service === seenName.service && name3.method === seenName.method) {
              throw new Error(`Invalid service config: duplicate name ${name3.service}/${name3.method}`);
            }
          }
          seenMethodNames.push(name3);
        }
      }
      return result;
    }
    __name(validateServiceConfig, "validateServiceConfig");
    function validateCanaryConfig(obj) {
      if (!("serviceConfig" in obj)) {
        throw new Error("Invalid service config choice: missing service config");
      }
      const result = {
        serviceConfig: validateServiceConfig(obj.serviceConfig)
      };
      if ("clientLanguage" in obj) {
        if (Array.isArray(obj.clientLanguage)) {
          result.clientLanguage = [];
          for (const lang of obj.clientLanguage) {
            if (typeof lang === "string") {
              result.clientLanguage.push(lang);
            } else {
              throw new Error("Invalid service config choice: invalid clientLanguage");
            }
          }
        } else {
          throw new Error("Invalid service config choice: invalid clientLanguage");
        }
      }
      if ("clientHostname" in obj) {
        if (Array.isArray(obj.clientHostname)) {
          result.clientHostname = [];
          for (const lang of obj.clientHostname) {
            if (typeof lang === "string") {
              result.clientHostname.push(lang);
            } else {
              throw new Error("Invalid service config choice: invalid clientHostname");
            }
          }
        } else {
          throw new Error("Invalid service config choice: invalid clientHostname");
        }
      }
      if ("percentage" in obj) {
        if (typeof obj.percentage === "number" && 0 <= obj.percentage && obj.percentage <= 100) {
          result.percentage = obj.percentage;
        } else {
          throw new Error("Invalid service config choice: invalid percentage");
        }
      }
      const allowedFields = [
        "clientLanguage",
        "percentage",
        "clientHostname",
        "serviceConfig"
      ];
      for (const field in obj) {
        if (!allowedFields.includes(field)) {
          throw new Error(`Invalid service config choice: unexpected field ${field}`);
        }
      }
      return result;
    }
    __name(validateCanaryConfig, "validateCanaryConfig");
    function validateAndSelectCanaryConfig(obj, percentage) {
      if (!Array.isArray(obj)) {
        throw new Error("Invalid service config list");
      }
      for (const config of obj) {
        const validatedConfig = validateCanaryConfig(config);
        if (typeof validatedConfig.percentage === "number" && percentage > validatedConfig.percentage) {
          continue;
        }
        if (Array.isArray(validatedConfig.clientHostname)) {
          let hostnameMatched = false;
          for (const hostname3 of validatedConfig.clientHostname) {
            if (hostname3 === os43.hostname()) {
              hostnameMatched = true;
            }
          }
          if (!hostnameMatched) {
            continue;
          }
        }
        if (Array.isArray(validatedConfig.clientLanguage)) {
          let languageMatched = false;
          for (const language of validatedConfig.clientLanguage) {
            if (language === CLIENT_LANGUAGE_STRING) {
              languageMatched = true;
            }
          }
          if (!languageMatched) {
            continue;
          }
        }
        return validatedConfig.serviceConfig;
      }
      throw new Error("No matching service config found");
    }
    __name(validateAndSelectCanaryConfig, "validateAndSelectCanaryConfig");
    function extractAndSelectServiceConfig(txtRecord, percentage) {
      for (const record of txtRecord) {
        if (record.length > 0 && record[0].startsWith("grpc_config=")) {
          const recordString = record.join("").substring("grpc_config=".length);
          const recordJson = JSON.parse(recordString);
          return validateAndSelectCanaryConfig(recordJson, percentage);
        }
      }
      return null;
    }
    __name(extractAndSelectServiceConfig, "extractAndSelectServiceConfig");
  }
});

// node_modules/@grpc/grpc-js/build/src/connectivity-state.js
var require_connectivity_state = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/connectivity-state.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ConnectivityState = void 0;
    var ConnectivityState;
    (function(ConnectivityState2) {
      ConnectivityState2[ConnectivityState2["IDLE"] = 0] = "IDLE";
      ConnectivityState2[ConnectivityState2["CONNECTING"] = 1] = "CONNECTING";
      ConnectivityState2[ConnectivityState2["READY"] = 2] = "READY";
      ConnectivityState2[ConnectivityState2["TRANSIENT_FAILURE"] = 3] = "TRANSIENT_FAILURE";
      ConnectivityState2[ConnectivityState2["SHUTDOWN"] = 4] = "SHUTDOWN";
    })(ConnectivityState || (exports2.ConnectivityState = ConnectivityState = {}));
  }
});

// node_modules/@grpc/grpc-js/build/src/picker.js
var require_picker = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/picker.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.QueuePicker = exports2.UnavailablePicker = exports2.PickResultType = void 0;
    var metadata_1 = require_metadata3();
    var constants_1 = require_constants9();
    var PickResultType;
    (function(PickResultType2) {
      PickResultType2[PickResultType2["COMPLETE"] = 0] = "COMPLETE";
      PickResultType2[PickResultType2["QUEUE"] = 1] = "QUEUE";
      PickResultType2[PickResultType2["TRANSIENT_FAILURE"] = 2] = "TRANSIENT_FAILURE";
      PickResultType2[PickResultType2["DROP"] = 3] = "DROP";
    })(PickResultType || (exports2.PickResultType = PickResultType = {}));
    var UnavailablePicker = class {
      static {
        __name(this, "UnavailablePicker");
      }
      constructor(status) {
        this.status = Object.assign({ code: constants_1.Status.UNAVAILABLE, details: "No connection established", metadata: new metadata_1.Metadata() }, status);
      }
      pick(pickArgs) {
        return {
          pickResultType: PickResultType.TRANSIENT_FAILURE,
          subchannel: null,
          status: this.status,
          onCallStarted: null,
          onCallEnded: null
        };
      }
    };
    exports2.UnavailablePicker = UnavailablePicker;
    var QueuePicker = class {
      static {
        __name(this, "QueuePicker");
      }
      // Constructed with a load balancer. Calls exitIdle on it the first time pick is called
      constructor(loadBalancer, childPicker) {
        this.loadBalancer = loadBalancer;
        this.childPicker = childPicker;
        this.calledExitIdle = false;
      }
      pick(pickArgs) {
        if (!this.calledExitIdle) {
          process.nextTick(() => {
            this.loadBalancer.exitIdle();
          });
          this.calledExitIdle = true;
        }
        if (this.childPicker) {
          return this.childPicker.pick(pickArgs);
        } else {
          return {
            pickResultType: PickResultType.QUEUE,
            subchannel: null,
            status: null,
            onCallStarted: null,
            onCallEnded: null
          };
        }
      }
    };
    exports2.QueuePicker = QueuePicker;
  }
});

// node_modules/@grpc/grpc-js/build/src/backoff-timeout.js
var require_backoff_timeout = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/backoff-timeout.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BackoffTimeout = void 0;
    var constants_1 = require_constants9();
    var logging = require_logging();
    var TRACER_NAME = "backoff";
    var INITIAL_BACKOFF_MS = 1e3;
    var BACKOFF_MULTIPLIER2 = 1.6;
    var MAX_BACKOFF_MS = 12e4;
    var BACKOFF_JITTER = 0.2;
    function uniformRandom(min, max) {
      return Math.random() * (max - min) + min;
    }
    __name(uniformRandom, "uniformRandom");
    var BackoffTimeout = class _BackoffTimeout {
      static {
        __name(this, "BackoffTimeout");
      }
      constructor(callback, options2) {
        this.callback = callback;
        this.initialDelay = INITIAL_BACKOFF_MS;
        this.multiplier = BACKOFF_MULTIPLIER2;
        this.maxDelay = MAX_BACKOFF_MS;
        this.jitter = BACKOFF_JITTER;
        this.running = false;
        this.hasRef = true;
        this.startTime = /* @__PURE__ */ new Date();
        this.endTime = /* @__PURE__ */ new Date();
        this.id = _BackoffTimeout.getNextId();
        if (options2) {
          if (options2.initialDelay) {
            this.initialDelay = options2.initialDelay;
          }
          if (options2.multiplier) {
            this.multiplier = options2.multiplier;
          }
          if (options2.jitter) {
            this.jitter = options2.jitter;
          }
          if (options2.maxDelay) {
            this.maxDelay = options2.maxDelay;
          }
        }
        this.trace("constructed initialDelay=" + this.initialDelay + " multiplier=" + this.multiplier + " jitter=" + this.jitter + " maxDelay=" + this.maxDelay);
        this.nextDelay = this.initialDelay;
        this.timerId = setTimeout(() => {
        }, 0);
        clearTimeout(this.timerId);
      }
      static getNextId() {
        return this.nextId++;
      }
      trace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "{" + this.id + "} " + text);
      }
      runTimer(delay4) {
        var _a6, _b2;
        this.trace("runTimer(delay=" + delay4 + ")");
        this.endTime = this.startTime;
        this.endTime.setMilliseconds(this.endTime.getMilliseconds() + delay4);
        clearTimeout(this.timerId);
        this.timerId = setTimeout(() => {
          this.trace("timer fired");
          this.running = false;
          this.callback();
        }, delay4);
        if (!this.hasRef) {
          (_b2 = (_a6 = this.timerId).unref) === null || _b2 === void 0 ? void 0 : _b2.call(_a6);
        }
      }
      /**
       * Call the callback after the current amount of delay time
       */
      runOnce() {
        this.trace("runOnce()");
        this.running = true;
        this.startTime = /* @__PURE__ */ new Date();
        this.runTimer(this.nextDelay);
        const nextBackoff = Math.min(this.nextDelay * this.multiplier, this.maxDelay);
        const jitterMagnitude = nextBackoff * this.jitter;
        this.nextDelay = nextBackoff + uniformRandom(-jitterMagnitude, jitterMagnitude);
      }
      /**
       * Stop the timer. The callback will not be called until `runOnce` is called
       * again.
       */
      stop() {
        this.trace("stop()");
        clearTimeout(this.timerId);
        this.running = false;
      }
      /**
       * Reset the delay time to its initial value. If the timer is still running,
       * retroactively apply that reset to the current timer.
       */
      reset() {
        this.trace("reset() running=" + this.running);
        this.nextDelay = this.initialDelay;
        if (this.running) {
          const now = /* @__PURE__ */ new Date();
          const newEndTime = this.startTime;
          newEndTime.setMilliseconds(newEndTime.getMilliseconds() + this.nextDelay);
          clearTimeout(this.timerId);
          if (now < newEndTime) {
            this.runTimer(newEndTime.getTime() - now.getTime());
          } else {
            this.running = false;
          }
        }
      }
      /**
       * Check whether the timer is currently running.
       */
      isRunning() {
        return this.running;
      }
      /**
       * Set that while the timer is running, it should keep the Node process
       * running.
       */
      ref() {
        var _a6, _b2;
        this.hasRef = true;
        (_b2 = (_a6 = this.timerId).ref) === null || _b2 === void 0 ? void 0 : _b2.call(_a6);
      }
      /**
       * Set that while the timer is running, it should not keep the Node process
       * running.
       */
      unref() {
        var _a6, _b2;
        this.hasRef = false;
        (_b2 = (_a6 = this.timerId).unref) === null || _b2 === void 0 ? void 0 : _b2.call(_a6);
      }
      /**
       * Get the approximate timestamp of when the timer will fire. Only valid if
       * this.isRunning() is true.
       */
      getEndTime() {
        return this.endTime;
      }
    };
    exports2.BackoffTimeout = BackoffTimeout;
    BackoffTimeout.nextId = 0;
  }
});

// node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js
var require_load_balancer_child_handler = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ChildLoadBalancerHandler = void 0;
    var load_balancer_1 = require_load_balancer();
    var connectivity_state_1 = require_connectivity_state();
    var TYPE_NAME = "child_load_balancer_helper";
    var ChildLoadBalancerHandler = class {
      static {
        __name(this, "ChildLoadBalancerHandler");
      }
      constructor(channelControlHelper) {
        this.channelControlHelper = channelControlHelper;
        this.currentChild = null;
        this.pendingChild = null;
        this.latestConfig = null;
        this.ChildPolicyHelper = class {
          constructor(parent) {
            this.parent = parent;
            this.child = null;
          }
          createSubchannel(subchannelAddress, subchannelArgs) {
            return this.parent.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs);
          }
          updateState(connectivityState, picker, errorMessage) {
            var _a6;
            if (this.calledByPendingChild()) {
              if (connectivityState === connectivity_state_1.ConnectivityState.CONNECTING) {
                return;
              }
              (_a6 = this.parent.currentChild) === null || _a6 === void 0 ? void 0 : _a6.destroy();
              this.parent.currentChild = this.parent.pendingChild;
              this.parent.pendingChild = null;
            } else if (!this.calledByCurrentChild()) {
              return;
            }
            this.parent.channelControlHelper.updateState(connectivityState, picker, errorMessage);
          }
          requestReresolution() {
            var _a6;
            const latestChild = (_a6 = this.parent.pendingChild) !== null && _a6 !== void 0 ? _a6 : this.parent.currentChild;
            if (this.child === latestChild) {
              this.parent.channelControlHelper.requestReresolution();
            }
          }
          setChild(newChild) {
            this.child = newChild;
          }
          addChannelzChild(child) {
            this.parent.channelControlHelper.addChannelzChild(child);
          }
          removeChannelzChild(child) {
            this.parent.channelControlHelper.removeChannelzChild(child);
          }
          calledByPendingChild() {
            return this.child === this.parent.pendingChild;
          }
          calledByCurrentChild() {
            return this.child === this.parent.currentChild;
          }
        };
      }
      configUpdateRequiresNewPolicyInstance(oldConfig, newConfig) {
        return oldConfig.getLoadBalancerName() !== newConfig.getLoadBalancerName();
      }
      /**
       * Prerequisites: lbConfig !== null and lbConfig.name is registered
       * @param endpointList
       * @param lbConfig
       * @param attributes
       */
      updateAddressList(endpointList, lbConfig, options2) {
        let childToUpdate;
        if (this.currentChild === null || this.latestConfig === null || this.configUpdateRequiresNewPolicyInstance(this.latestConfig, lbConfig)) {
          const newHelper = new this.ChildPolicyHelper(this);
          const newChild = (0, load_balancer_1.createLoadBalancer)(lbConfig, newHelper);
          newHelper.setChild(newChild);
          if (this.currentChild === null) {
            this.currentChild = newChild;
            childToUpdate = this.currentChild;
          } else {
            if (this.pendingChild) {
              this.pendingChild.destroy();
            }
            this.pendingChild = newChild;
            childToUpdate = this.pendingChild;
          }
        } else {
          if (this.pendingChild === null) {
            childToUpdate = this.currentChild;
          } else {
            childToUpdate = this.pendingChild;
          }
        }
        this.latestConfig = lbConfig;
        childToUpdate.updateAddressList(endpointList, lbConfig, options2);
      }
      exitIdle() {
        if (this.currentChild) {
          this.currentChild.exitIdle();
          if (this.pendingChild) {
            this.pendingChild.exitIdle();
          }
        }
      }
      resetBackoff() {
        if (this.currentChild) {
          this.currentChild.resetBackoff();
          if (this.pendingChild) {
            this.pendingChild.resetBackoff();
          }
        }
      }
      destroy() {
        if (this.currentChild) {
          this.currentChild.destroy();
          this.currentChild = null;
        }
        if (this.pendingChild) {
          this.pendingChild.destroy();
          this.pendingChild = null;
        }
      }
      getTypeName() {
        return TYPE_NAME;
      }
    };
    exports2.ChildLoadBalancerHandler = ChildLoadBalancerHandler;
  }
});

// node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js
var require_resolving_load_balancer = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ResolvingLoadBalancer = void 0;
    var load_balancer_1 = require_load_balancer();
    var service_config_1 = require_service_config();
    var connectivity_state_1 = require_connectivity_state();
    var resolver_1 = require_resolver();
    var picker_1 = require_picker();
    var backoff_timeout_1 = require_backoff_timeout();
    var constants_1 = require_constants9();
    var metadata_1 = require_metadata3();
    var logging = require_logging();
    var constants_2 = require_constants9();
    var uri_parser_1 = require_uri_parser();
    var load_balancer_child_handler_1 = require_load_balancer_child_handler();
    var TRACER_NAME = "resolving_load_balancer";
    function trace2(text) {
      logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    var NAME_MATCH_LEVEL_ORDER = [
      "SERVICE_AND_METHOD",
      "SERVICE",
      "EMPTY"
    ];
    function hasMatchingName(service, method, methodConfig, matchLevel) {
      for (const name3 of methodConfig.name) {
        switch (matchLevel) {
          case "EMPTY":
            if (!name3.service && !name3.method) {
              return true;
            }
            break;
          case "SERVICE":
            if (name3.service === service && !name3.method) {
              return true;
            }
            break;
          case "SERVICE_AND_METHOD":
            if (name3.service === service && name3.method === method) {
              return true;
            }
        }
      }
      return false;
    }
    __name(hasMatchingName, "hasMatchingName");
    function findMatchingConfig(service, method, methodConfigs, matchLevel) {
      for (const config of methodConfigs) {
        if (hasMatchingName(service, method, config, matchLevel)) {
          return config;
        }
      }
      return null;
    }
    __name(findMatchingConfig, "findMatchingConfig");
    function getDefaultConfigSelector(serviceConfig) {
      return {
        invoke(methodName, metadata) {
          var _a6, _b2;
          const splitName = methodName.split("/").filter((x) => x.length > 0);
          const service = (_a6 = splitName[0]) !== null && _a6 !== void 0 ? _a6 : "";
          const method = (_b2 = splitName[1]) !== null && _b2 !== void 0 ? _b2 : "";
          if (serviceConfig && serviceConfig.methodConfig) {
            for (const matchLevel of NAME_MATCH_LEVEL_ORDER) {
              const matchingConfig = findMatchingConfig(service, method, serviceConfig.methodConfig, matchLevel);
              if (matchingConfig) {
                return {
                  methodConfig: matchingConfig,
                  pickInformation: {},
                  status: constants_1.Status.OK,
                  dynamicFilterFactories: []
                };
              }
            }
          }
          return {
            methodConfig: { name: [] },
            pickInformation: {},
            status: constants_1.Status.OK,
            dynamicFilterFactories: []
          };
        },
        unref() {
        }
      };
    }
    __name(getDefaultConfigSelector, "getDefaultConfigSelector");
    var ResolvingLoadBalancer = class {
      static {
        __name(this, "ResolvingLoadBalancer");
      }
      /**
       * Wrapper class that behaves like a `LoadBalancer` and also handles name
       * resolution internally.
       * @param target The address of the backend to connect to.
       * @param channelControlHelper `ChannelControlHelper` instance provided by
       *     this load balancer's owner.
       * @param defaultServiceConfig The default service configuration to be used
       *     if none is provided by the name resolver. A `null` value indicates
       *     that the default behavior should be the default unconfigured behavior.
       *     In practice, that means using the "pick first" load balancer
       *     implmentation
       */
      constructor(target, channelControlHelper, channelOptions, onSuccessfulResolution, onFailedResolution) {
        this.target = target;
        this.channelControlHelper = channelControlHelper;
        this.channelOptions = channelOptions;
        this.onSuccessfulResolution = onSuccessfulResolution;
        this.onFailedResolution = onFailedResolution;
        this.latestChildState = connectivity_state_1.ConnectivityState.IDLE;
        this.latestChildPicker = new picker_1.QueuePicker(this);
        this.latestChildErrorMessage = null;
        this.currentState = connectivity_state_1.ConnectivityState.IDLE;
        this.previousServiceConfig = null;
        this.continueResolving = false;
        if (channelOptions["grpc.service_config"]) {
          this.defaultServiceConfig = (0, service_config_1.validateServiceConfig)(JSON.parse(channelOptions["grpc.service_config"]));
        } else {
          this.defaultServiceConfig = {
            loadBalancingConfig: [],
            methodConfig: []
          };
        }
        this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null);
        this.childLoadBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler({
          createSubchannel: channelControlHelper.createSubchannel.bind(channelControlHelper),
          requestReresolution: /* @__PURE__ */ __name(() => {
            if (this.backoffTimeout.isRunning()) {
              trace2("requestReresolution delayed by backoff timer until " + this.backoffTimeout.getEndTime().toISOString());
              this.continueResolving = true;
            } else {
              this.updateResolution();
            }
          }, "requestReresolution"),
          updateState: /* @__PURE__ */ __name((newState, picker, errorMessage) => {
            this.latestChildState = newState;
            this.latestChildPicker = picker;
            this.latestChildErrorMessage = errorMessage;
            this.updateState(newState, picker, errorMessage);
          }, "updateState"),
          addChannelzChild: channelControlHelper.addChannelzChild.bind(channelControlHelper),
          removeChannelzChild: channelControlHelper.removeChannelzChild.bind(channelControlHelper)
        });
        this.innerResolver = (0, resolver_1.createResolver)(target, {
          onSuccessfulResolution: /* @__PURE__ */ __name((endpointList, serviceConfig, serviceConfigError, configSelector, attributes) => {
            var _a6;
            this.backoffTimeout.stop();
            this.backoffTimeout.reset();
            let workingServiceConfig = null;
            if (serviceConfig === null) {
              if (serviceConfigError === null) {
                this.previousServiceConfig = null;
                workingServiceConfig = this.defaultServiceConfig;
              } else {
                if (this.previousServiceConfig === null) {
                  this.handleResolutionFailure(serviceConfigError);
                } else {
                  workingServiceConfig = this.previousServiceConfig;
                }
              }
            } else {
              workingServiceConfig = serviceConfig;
              this.previousServiceConfig = serviceConfig;
            }
            const workingConfigList = (_a6 = workingServiceConfig === null || workingServiceConfig === void 0 ? void 0 : workingServiceConfig.loadBalancingConfig) !== null && _a6 !== void 0 ? _a6 : [];
            const loadBalancingConfig = (0, load_balancer_1.selectLbConfigFromList)(workingConfigList, true);
            if (loadBalancingConfig === null) {
              this.handleResolutionFailure({
                code: constants_1.Status.UNAVAILABLE,
                details: "All load balancer options in service config are not compatible",
                metadata: new metadata_1.Metadata()
              });
              configSelector === null || configSelector === void 0 ? void 0 : configSelector.unref();
              return;
            }
            this.childLoadBalancer.updateAddressList(endpointList, loadBalancingConfig, Object.assign(Object.assign({}, this.channelOptions), attributes));
            const finalServiceConfig = workingServiceConfig !== null && workingServiceConfig !== void 0 ? workingServiceConfig : this.defaultServiceConfig;
            this.onSuccessfulResolution(finalServiceConfig, configSelector !== null && configSelector !== void 0 ? configSelector : getDefaultConfigSelector(finalServiceConfig));
          }, "onSuccessfulResolution"),
          onError: /* @__PURE__ */ __name((error) => {
            this.handleResolutionFailure(error);
          }, "onError")
        }, channelOptions);
        const backoffOptions = {
          initialDelay: channelOptions["grpc.initial_reconnect_backoff_ms"],
          maxDelay: channelOptions["grpc.max_reconnect_backoff_ms"]
        };
        this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => {
          if (this.continueResolving) {
            this.updateResolution();
            this.continueResolving = false;
          } else {
            this.updateState(this.latestChildState, this.latestChildPicker, this.latestChildErrorMessage);
          }
        }, backoffOptions);
        this.backoffTimeout.unref();
      }
      updateResolution() {
        this.innerResolver.updateResolution();
        if (this.currentState === connectivity_state_1.ConnectivityState.IDLE) {
          this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, this.latestChildPicker, this.latestChildErrorMessage);
        }
        this.backoffTimeout.runOnce();
      }
      updateState(connectivityState, picker, errorMessage) {
        trace2((0, uri_parser_1.uriToString)(this.target) + " " + connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[connectivityState]);
        if (connectivityState === connectivity_state_1.ConnectivityState.IDLE) {
          picker = new picker_1.QueuePicker(this, picker);
        }
        this.currentState = connectivityState;
        this.channelControlHelper.updateState(connectivityState, picker, errorMessage);
      }
      handleResolutionFailure(error) {
        if (this.latestChildState === connectivity_state_1.ConnectivityState.IDLE) {
          this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(error), error.details);
          this.onFailedResolution(error);
        }
      }
      exitIdle() {
        if (this.currentState === connectivity_state_1.ConnectivityState.IDLE || this.currentState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) {
          if (this.backoffTimeout.isRunning()) {
            this.continueResolving = true;
          } else {
            this.updateResolution();
          }
        }
        this.childLoadBalancer.exitIdle();
      }
      updateAddressList(endpointList, lbConfig) {
        throw new Error("updateAddressList not supported on ResolvingLoadBalancer");
      }
      resetBackoff() {
        this.backoffTimeout.reset();
        this.childLoadBalancer.resetBackoff();
      }
      destroy() {
        this.childLoadBalancer.destroy();
        this.innerResolver.destroy();
        this.backoffTimeout.reset();
        this.backoffTimeout.stop();
        this.latestChildState = connectivity_state_1.ConnectivityState.IDLE;
        this.latestChildPicker = new picker_1.QueuePicker(this);
        this.currentState = connectivity_state_1.ConnectivityState.IDLE;
        this.previousServiceConfig = null;
        this.continueResolving = false;
      }
      getTypeName() {
        return "resolving_load_balancer";
      }
    };
    exports2.ResolvingLoadBalancer = ResolvingLoadBalancer;
  }
});

// node_modules/@grpc/grpc-js/build/src/channel-options.js
var require_channel_options = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/channel-options.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.recognizedOptions = void 0;
    exports2.channelOptionsEqual = channelOptionsEqual;
    exports2.recognizedOptions = {
      "grpc.ssl_target_name_override": true,
      "grpc.primary_user_agent": true,
      "grpc.secondary_user_agent": true,
      "grpc.default_authority": true,
      "grpc.keepalive_time_ms": true,
      "grpc.keepalive_timeout_ms": true,
      "grpc.keepalive_permit_without_calls": true,
      "grpc.service_config": true,
      "grpc.max_concurrent_streams": true,
      "grpc.initial_reconnect_backoff_ms": true,
      "grpc.max_reconnect_backoff_ms": true,
      "grpc.use_local_subchannel_pool": true,
      "grpc.max_send_message_length": true,
      "grpc.max_receive_message_length": true,
      "grpc.enable_http_proxy": true,
      "grpc.enable_channelz": true,
      "grpc.dns_min_time_between_resolutions_ms": true,
      "grpc.enable_retries": true,
      "grpc.per_rpc_retry_buffer_size": true,
      "grpc.retry_buffer_size": true,
      "grpc.max_connection_age_ms": true,
      "grpc.max_connection_age_grace_ms": true,
      "grpc-node.max_session_memory": true,
      "grpc.service_config_disable_resolution": true,
      "grpc.client_idle_timeout_ms": true,
      "grpc-node.tls_enable_trace": true,
      "grpc.lb.ring_hash.ring_size_cap": true,
      "grpc-node.retry_max_attempts_limit": true,
      "grpc-node.flow_control_window": true
    };
    function channelOptionsEqual(options1, options2) {
      const keys1 = Object.keys(options1).sort();
      const keys2 = Object.keys(options2).sort();
      if (keys1.length !== keys2.length) {
        return false;
      }
      for (let i = 0; i < keys1.length; i += 1) {
        if (keys1[i] !== keys2[i]) {
          return false;
        }
        if (options1[keys1[i]] !== options2[keys2[i]]) {
          return false;
        }
      }
      return true;
    }
    __name(channelOptionsEqual, "channelOptionsEqual");
  }
});

// node_modules/@grpc/grpc-js/build/src/subchannel-address.js
var require_subchannel_address = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/subchannel-address.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.EndpointMap = void 0;
    exports2.isTcpSubchannelAddress = isTcpSubchannelAddress;
    exports2.subchannelAddressEqual = subchannelAddressEqual;
    exports2.subchannelAddressToString = subchannelAddressToString;
    exports2.stringToSubchannelAddress = stringToSubchannelAddress;
    exports2.endpointEqual = endpointEqual;
    exports2.endpointToString = endpointToString;
    exports2.endpointHasAddress = endpointHasAddress;
    var net_1 = __require("net");
    function isTcpSubchannelAddress(address) {
      return "port" in address;
    }
    __name(isTcpSubchannelAddress, "isTcpSubchannelAddress");
    function subchannelAddressEqual(address1, address2) {
      if (!address1 && !address2) {
        return true;
      }
      if (!address1 || !address2) {
        return false;
      }
      if (isTcpSubchannelAddress(address1)) {
        return isTcpSubchannelAddress(address2) && address1.host === address2.host && address1.port === address2.port;
      } else {
        return !isTcpSubchannelAddress(address2) && address1.path === address2.path;
      }
    }
    __name(subchannelAddressEqual, "subchannelAddressEqual");
    function subchannelAddressToString(address) {
      if (isTcpSubchannelAddress(address)) {
        if ((0, net_1.isIPv6)(address.host)) {
          return "[" + address.host + "]:" + address.port;
        } else {
          return address.host + ":" + address.port;
        }
      } else {
        return address.path;
      }
    }
    __name(subchannelAddressToString, "subchannelAddressToString");
    var DEFAULT_PORT = 443;
    function stringToSubchannelAddress(addressString, port) {
      if ((0, net_1.isIP)(addressString)) {
        return {
          host: addressString,
          port: port !== null && port !== void 0 ? port : DEFAULT_PORT
        };
      } else {
        return {
          path: addressString
        };
      }
    }
    __name(stringToSubchannelAddress, "stringToSubchannelAddress");
    function endpointEqual(endpoint1, endpoint2) {
      if (endpoint1.addresses.length !== endpoint2.addresses.length) {
        return false;
      }
      for (let i = 0; i < endpoint1.addresses.length; i++) {
        if (!subchannelAddressEqual(endpoint1.addresses[i], endpoint2.addresses[i])) {
          return false;
        }
      }
      return true;
    }
    __name(endpointEqual, "endpointEqual");
    function endpointToString(endpoint) {
      return "[" + endpoint.addresses.map(subchannelAddressToString).join(", ") + "]";
    }
    __name(endpointToString, "endpointToString");
    function endpointHasAddress(endpoint, expectedAddress) {
      for (const address of endpoint.addresses) {
        if (subchannelAddressEqual(address, expectedAddress)) {
          return true;
        }
      }
      return false;
    }
    __name(endpointHasAddress, "endpointHasAddress");
    function endpointEqualUnordered(endpoint1, endpoint2) {
      if (endpoint1.addresses.length !== endpoint2.addresses.length) {
        return false;
      }
      for (const address1 of endpoint1.addresses) {
        let matchFound = false;
        for (const address2 of endpoint2.addresses) {
          if (subchannelAddressEqual(address1, address2)) {
            matchFound = true;
            break;
          }
        }
        if (!matchFound) {
          return false;
        }
      }
      return true;
    }
    __name(endpointEqualUnordered, "endpointEqualUnordered");
    var EndpointMap = class {
      static {
        __name(this, "EndpointMap");
      }
      constructor() {
        this.map = /* @__PURE__ */ new Set();
      }
      get size() {
        return this.map.size;
      }
      getForSubchannelAddress(address) {
        for (const entry of this.map) {
          if (endpointHasAddress(entry.key, address)) {
            return entry.value;
          }
        }
        return void 0;
      }
      /**
       * Delete any entries in this map with keys that are not in endpoints
       * @param endpoints
       */
      deleteMissing(endpoints) {
        const removedValues = [];
        for (const entry of this.map) {
          let foundEntry = false;
          for (const endpoint of endpoints) {
            if (endpointEqualUnordered(endpoint, entry.key)) {
              foundEntry = true;
            }
          }
          if (!foundEntry) {
            removedValues.push(entry.value);
            this.map.delete(entry);
          }
        }
        return removedValues;
      }
      get(endpoint) {
        for (const entry of this.map) {
          if (endpointEqualUnordered(endpoint, entry.key)) {
            return entry.value;
          }
        }
        return void 0;
      }
      set(endpoint, mapEntry) {
        for (const entry of this.map) {
          if (endpointEqualUnordered(endpoint, entry.key)) {
            entry.value = mapEntry;
            return;
          }
        }
        this.map.add({ key: endpoint, value: mapEntry });
      }
      delete(endpoint) {
        for (const entry of this.map) {
          if (endpointEqualUnordered(endpoint, entry.key)) {
            this.map.delete(entry);
            return;
          }
        }
      }
      has(endpoint) {
        for (const entry of this.map) {
          if (endpointEqualUnordered(endpoint, entry.key)) {
            return true;
          }
        }
        return false;
      }
      clear() {
        this.map.clear();
      }
      *keys() {
        for (const entry of this.map) {
          yield entry.key;
        }
      }
      *values() {
        for (const entry of this.map) {
          yield entry.value;
        }
      }
      *entries() {
        for (const entry of this.map) {
          yield [entry.key, entry.value];
        }
      }
    };
    exports2.EndpointMap = EndpointMap;
  }
});

// node_modules/@js-sdsl/ordered-map/dist/cjs/index.js
var require_cjs = __commonJS({
  "node_modules/@js-sdsl/ordered-map/dist/cjs/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "t", {
      value: true
    });
    var TreeNode = class {
      static {
        __name(this, "TreeNode");
      }
      constructor(t2, e2, s2 = 1) {
        this.i = void 0;
        this.h = void 0;
        this.o = void 0;
        this.u = t2;
        this.l = e2;
        this.p = s2;
      }
      I() {
        let t2 = this;
        const e2 = t2.o.o === t2;
        if (e2 && t2.p === 1) {
          t2 = t2.h;
        } else if (t2.i) {
          t2 = t2.i;
          while (t2.h) {
            t2 = t2.h;
          }
        } else {
          if (e2) {
            return t2.o;
          }
          let s2 = t2.o;
          while (s2.i === t2) {
            t2 = s2;
            s2 = t2.o;
          }
          t2 = s2;
        }
        return t2;
      }
      B() {
        let t2 = this;
        if (t2.h) {
          t2 = t2.h;
          while (t2.i) {
            t2 = t2.i;
          }
          return t2;
        } else {
          let e2 = t2.o;
          while (e2.h === t2) {
            t2 = e2;
            e2 = t2.o;
          }
          if (t2.h !== e2) {
            return e2;
          } else return t2;
        }
      }
      _() {
        const t2 = this.o;
        const e2 = this.h;
        const s2 = e2.i;
        if (t2.o === this) t2.o = e2;
        else if (t2.i === this) t2.i = e2;
        else t2.h = e2;
        e2.o = t2;
        e2.i = this;
        this.o = e2;
        this.h = s2;
        if (s2) s2.o = this;
        return e2;
      }
      g() {
        const t2 = this.o;
        const e2 = this.i;
        const s2 = e2.h;
        if (t2.o === this) t2.o = e2;
        else if (t2.i === this) t2.i = e2;
        else t2.h = e2;
        e2.o = t2;
        e2.h = this;
        this.o = e2;
        this.i = s2;
        if (s2) s2.o = this;
        return e2;
      }
    };
    var TreeNodeEnableIndex = class extends TreeNode {
      static {
        __name(this, "TreeNodeEnableIndex");
      }
      constructor() {
        super(...arguments);
        this.M = 1;
      }
      _() {
        const t2 = super._();
        this.O();
        t2.O();
        return t2;
      }
      g() {
        const t2 = super.g();
        this.O();
        t2.O();
        return t2;
      }
      O() {
        this.M = 1;
        if (this.i) {
          this.M += this.i.M;
        }
        if (this.h) {
          this.M += this.h.M;
        }
      }
    };
    var ContainerIterator = class {
      static {
        __name(this, "ContainerIterator");
      }
      constructor(t2 = 0) {
        this.iteratorType = t2;
      }
      equals(t2) {
        return this.T === t2.T;
      }
    };
    var Base = class {
      static {
        __name(this, "Base");
      }
      constructor() {
        this.m = 0;
      }
      get length() {
        return this.m;
      }
      size() {
        return this.m;
      }
      empty() {
        return this.m === 0;
      }
    };
    var Container = class extends Base {
      static {
        __name(this, "Container");
      }
    };
    function throwIteratorAccessError() {
      throw new RangeError("Iterator access denied!");
    }
    __name(throwIteratorAccessError, "throwIteratorAccessError");
    var TreeContainer = class extends Container {
      static {
        __name(this, "TreeContainer");
      }
      constructor(t2 = function(t3, e3) {
        if (t3 < e3) return -1;
        if (t3 > e3) return 1;
        return 0;
      }, e2 = false) {
        super();
        this.v = void 0;
        this.A = t2;
        this.enableIndex = e2;
        this.N = e2 ? TreeNodeEnableIndex : TreeNode;
        this.C = new this.N();
      }
      R(t2, e2) {
        let s2 = this.C;
        while (t2) {
          const i = this.A(t2.u, e2);
          if (i < 0) {
            t2 = t2.h;
          } else if (i > 0) {
            s2 = t2;
            t2 = t2.i;
          } else return t2;
        }
        return s2;
      }
      K(t2, e2) {
        let s2 = this.C;
        while (t2) {
          const i = this.A(t2.u, e2);
          if (i <= 0) {
            t2 = t2.h;
          } else {
            s2 = t2;
            t2 = t2.i;
          }
        }
        return s2;
      }
      L(t2, e2) {
        let s2 = this.C;
        while (t2) {
          const i = this.A(t2.u, e2);
          if (i < 0) {
            s2 = t2;
            t2 = t2.h;
          } else if (i > 0) {
            t2 = t2.i;
          } else return t2;
        }
        return s2;
      }
      k(t2, e2) {
        let s2 = this.C;
        while (t2) {
          const i = this.A(t2.u, e2);
          if (i < 0) {
            s2 = t2;
            t2 = t2.h;
          } else {
            t2 = t2.i;
          }
        }
        return s2;
      }
      P(t2) {
        while (true) {
          const e2 = t2.o;
          if (e2 === this.C) return;
          if (t2.p === 1) {
            t2.p = 0;
            return;
          }
          if (t2 === e2.i) {
            const s2 = e2.h;
            if (s2.p === 1) {
              s2.p = 0;
              e2.p = 1;
              if (e2 === this.v) {
                this.v = e2._();
              } else e2._();
            } else {
              if (s2.h && s2.h.p === 1) {
                s2.p = e2.p;
                e2.p = 0;
                s2.h.p = 0;
                if (e2 === this.v) {
                  this.v = e2._();
                } else e2._();
                return;
              } else if (s2.i && s2.i.p === 1) {
                s2.p = 1;
                s2.i.p = 0;
                s2.g();
              } else {
                s2.p = 1;
                t2 = e2;
              }
            }
          } else {
            const s2 = e2.i;
            if (s2.p === 1) {
              s2.p = 0;
              e2.p = 1;
              if (e2 === this.v) {
                this.v = e2.g();
              } else e2.g();
            } else {
              if (s2.i && s2.i.p === 1) {
                s2.p = e2.p;
                e2.p = 0;
                s2.i.p = 0;
                if (e2 === this.v) {
                  this.v = e2.g();
                } else e2.g();
                return;
              } else if (s2.h && s2.h.p === 1) {
                s2.p = 1;
                s2.h.p = 0;
                s2._();
              } else {
                s2.p = 1;
                t2 = e2;
              }
            }
          }
        }
      }
      S(t2) {
        if (this.m === 1) {
          this.clear();
          return;
        }
        let e2 = t2;
        while (e2.i || e2.h) {
          if (e2.h) {
            e2 = e2.h;
            while (e2.i) e2 = e2.i;
          } else {
            e2 = e2.i;
          }
          const s3 = t2.u;
          t2.u = e2.u;
          e2.u = s3;
          const i = t2.l;
          t2.l = e2.l;
          e2.l = i;
          t2 = e2;
        }
        if (this.C.i === e2) {
          this.C.i = e2.o;
        } else if (this.C.h === e2) {
          this.C.h = e2.o;
        }
        this.P(e2);
        let s2 = e2.o;
        if (e2 === s2.i) {
          s2.i = void 0;
        } else s2.h = void 0;
        this.m -= 1;
        this.v.p = 0;
        if (this.enableIndex) {
          while (s2 !== this.C) {
            s2.M -= 1;
            s2 = s2.o;
          }
        }
      }
      U(t2) {
        const e2 = typeof t2 === "number" ? t2 : void 0;
        const s2 = typeof t2 === "function" ? t2 : void 0;
        const i = typeof t2 === "undefined" ? [] : void 0;
        let r3 = 0;
        let n2 = this.v;
        const h = [];
        while (h.length || n2) {
          if (n2) {
            h.push(n2);
            n2 = n2.i;
          } else {
            n2 = h.pop();
            if (r3 === e2) return n2;
            i && i.push(n2);
            s2 && s2(n2, r3, this);
            r3 += 1;
            n2 = n2.h;
          }
        }
        return i;
      }
      j(t2) {
        while (true) {
          const e2 = t2.o;
          if (e2.p === 0) return;
          const s2 = e2.o;
          if (e2 === s2.i) {
            const i = s2.h;
            if (i && i.p === 1) {
              i.p = e2.p = 0;
              if (s2 === this.v) return;
              s2.p = 1;
              t2 = s2;
              continue;
            } else if (t2 === e2.h) {
              t2.p = 0;
              if (t2.i) {
                t2.i.o = e2;
              }
              if (t2.h) {
                t2.h.o = s2;
              }
              e2.h = t2.i;
              s2.i = t2.h;
              t2.i = e2;
              t2.h = s2;
              if (s2 === this.v) {
                this.v = t2;
                this.C.o = t2;
              } else {
                const e3 = s2.o;
                if (e3.i === s2) {
                  e3.i = t2;
                } else e3.h = t2;
              }
              t2.o = s2.o;
              e2.o = t2;
              s2.o = t2;
              s2.p = 1;
            } else {
              e2.p = 0;
              if (s2 === this.v) {
                this.v = s2.g();
              } else s2.g();
              s2.p = 1;
              return;
            }
          } else {
            const i = s2.i;
            if (i && i.p === 1) {
              i.p = e2.p = 0;
              if (s2 === this.v) return;
              s2.p = 1;
              t2 = s2;
              continue;
            } else if (t2 === e2.i) {
              t2.p = 0;
              if (t2.i) {
                t2.i.o = s2;
              }
              if (t2.h) {
                t2.h.o = e2;
              }
              s2.h = t2.i;
              e2.i = t2.h;
              t2.i = s2;
              t2.h = e2;
              if (s2 === this.v) {
                this.v = t2;
                this.C.o = t2;
              } else {
                const e3 = s2.o;
                if (e3.i === s2) {
                  e3.i = t2;
                } else e3.h = t2;
              }
              t2.o = s2.o;
              e2.o = t2;
              s2.o = t2;
              s2.p = 1;
            } else {
              e2.p = 0;
              if (s2 === this.v) {
                this.v = s2._();
              } else s2._();
              s2.p = 1;
              return;
            }
          }
          if (this.enableIndex) {
            e2.O();
            s2.O();
            t2.O();
          }
          return;
        }
      }
      q(t2, e2, s2) {
        if (this.v === void 0) {
          this.m += 1;
          this.v = new this.N(t2, e2, 0);
          this.v.o = this.C;
          this.C.o = this.C.i = this.C.h = this.v;
          return this.m;
        }
        let i;
        const r3 = this.C.i;
        const n2 = this.A(r3.u, t2);
        if (n2 === 0) {
          r3.l = e2;
          return this.m;
        } else if (n2 > 0) {
          r3.i = new this.N(t2, e2);
          r3.i.o = r3;
          i = r3.i;
          this.C.i = i;
        } else {
          const r4 = this.C.h;
          const n3 = this.A(r4.u, t2);
          if (n3 === 0) {
            r4.l = e2;
            return this.m;
          } else if (n3 < 0) {
            r4.h = new this.N(t2, e2);
            r4.h.o = r4;
            i = r4.h;
            this.C.h = i;
          } else {
            if (s2 !== void 0) {
              const r5 = s2.T;
              if (r5 !== this.C) {
                const s3 = this.A(r5.u, t2);
                if (s3 === 0) {
                  r5.l = e2;
                  return this.m;
                } else if (s3 > 0) {
                  const s4 = r5.I();
                  const n4 = this.A(s4.u, t2);
                  if (n4 === 0) {
                    s4.l = e2;
                    return this.m;
                  } else if (n4 < 0) {
                    i = new this.N(t2, e2);
                    if (s4.h === void 0) {
                      s4.h = i;
                      i.o = s4;
                    } else {
                      r5.i = i;
                      i.o = r5;
                    }
                  }
                }
              }
            }
            if (i === void 0) {
              i = this.v;
              while (true) {
                const s3 = this.A(i.u, t2);
                if (s3 > 0) {
                  if (i.i === void 0) {
                    i.i = new this.N(t2, e2);
                    i.i.o = i;
                    i = i.i;
                    break;
                  }
                  i = i.i;
                } else if (s3 < 0) {
                  if (i.h === void 0) {
                    i.h = new this.N(t2, e2);
                    i.h.o = i;
                    i = i.h;
                    break;
                  }
                  i = i.h;
                } else {
                  i.l = e2;
                  return this.m;
                }
              }
            }
          }
        }
        if (this.enableIndex) {
          let t3 = i.o;
          while (t3 !== this.C) {
            t3.M += 1;
            t3 = t3.o;
          }
        }
        this.j(i);
        this.m += 1;
        return this.m;
      }
      H(t2, e2) {
        while (t2) {
          const s2 = this.A(t2.u, e2);
          if (s2 < 0) {
            t2 = t2.h;
          } else if (s2 > 0) {
            t2 = t2.i;
          } else return t2;
        }
        return t2 || this.C;
      }
      clear() {
        this.m = 0;
        this.v = void 0;
        this.C.o = void 0;
        this.C.i = this.C.h = void 0;
      }
      updateKeyByIterator(t2, e2) {
        const s2 = t2.T;
        if (s2 === this.C) {
          throwIteratorAccessError();
        }
        if (this.m === 1) {
          s2.u = e2;
          return true;
        }
        const i = s2.B().u;
        if (s2 === this.C.i) {
          if (this.A(i, e2) > 0) {
            s2.u = e2;
            return true;
          }
          return false;
        }
        const r3 = s2.I().u;
        if (s2 === this.C.h) {
          if (this.A(r3, e2) < 0) {
            s2.u = e2;
            return true;
          }
          return false;
        }
        if (this.A(r3, e2) >= 0 || this.A(i, e2) <= 0) return false;
        s2.u = e2;
        return true;
      }
      eraseElementByPos(t2) {
        if (t2 < 0 || t2 > this.m - 1) {
          throw new RangeError();
        }
        const e2 = this.U(t2);
        this.S(e2);
        return this.m;
      }
      eraseElementByKey(t2) {
        if (this.m === 0) return false;
        const e2 = this.H(this.v, t2);
        if (e2 === this.C) return false;
        this.S(e2);
        return true;
      }
      eraseElementByIterator(t2) {
        const e2 = t2.T;
        if (e2 === this.C) {
          throwIteratorAccessError();
        }
        const s2 = e2.h === void 0;
        const i = t2.iteratorType === 0;
        if (i) {
          if (s2) t2.next();
        } else {
          if (!s2 || e2.i === void 0) t2.next();
        }
        this.S(e2);
        return t2;
      }
      getHeight() {
        if (this.m === 0) return 0;
        function traversal(t2) {
          if (!t2) return 0;
          return Math.max(traversal(t2.i), traversal(t2.h)) + 1;
        }
        __name(traversal, "traversal");
        return traversal(this.v);
      }
    };
    var TreeIterator = class extends ContainerIterator {
      static {
        __name(this, "TreeIterator");
      }
      constructor(t2, e2, s2) {
        super(s2);
        this.T = t2;
        this.C = e2;
        if (this.iteratorType === 0) {
          this.pre = function() {
            if (this.T === this.C.i) {
              throwIteratorAccessError();
            }
            this.T = this.T.I();
            return this;
          };
          this.next = function() {
            if (this.T === this.C) {
              throwIteratorAccessError();
            }
            this.T = this.T.B();
            return this;
          };
        } else {
          this.pre = function() {
            if (this.T === this.C.h) {
              throwIteratorAccessError();
            }
            this.T = this.T.B();
            return this;
          };
          this.next = function() {
            if (this.T === this.C) {
              throwIteratorAccessError();
            }
            this.T = this.T.I();
            return this;
          };
        }
      }
      get index() {
        let t2 = this.T;
        const e2 = this.C.o;
        if (t2 === this.C) {
          if (e2) {
            return e2.M - 1;
          }
          return 0;
        }
        let s2 = 0;
        if (t2.i) {
          s2 += t2.i.M;
        }
        while (t2 !== e2) {
          const e3 = t2.o;
          if (t2 === e3.h) {
            s2 += 1;
            if (e3.i) {
              s2 += e3.i.M;
            }
          }
          t2 = e3;
        }
        return s2;
      }
      isAccessible() {
        return this.T !== this.C;
      }
    };
    var OrderedMapIterator = class _OrderedMapIterator extends TreeIterator {
      static {
        __name(this, "OrderedMapIterator");
      }
      constructor(t2, e2, s2, i) {
        super(t2, e2, i);
        this.container = s2;
      }
      get pointer() {
        if (this.T === this.C) {
          throwIteratorAccessError();
        }
        const t2 = this;
        return new Proxy([], {
          get(e2, s2) {
            if (s2 === "0") return t2.T.u;
            else if (s2 === "1") return t2.T.l;
            e2[0] = t2.T.u;
            e2[1] = t2.T.l;
            return e2[s2];
          },
          set(e2, s2, i) {
            if (s2 !== "1") {
              throw new TypeError("prop must be 1");
            }
            t2.T.l = i;
            return true;
          }
        });
      }
      copy() {
        return new _OrderedMapIterator(this.T, this.C, this.container, this.iteratorType);
      }
    };
    var OrderedMap = class extends TreeContainer {
      static {
        __name(this, "OrderedMap");
      }
      constructor(t2 = [], e2, s2) {
        super(e2, s2);
        const i = this;
        t2.forEach(function(t3) {
          i.setElement(t3[0], t3[1]);
        });
      }
      begin() {
        return new OrderedMapIterator(this.C.i || this.C, this.C, this);
      }
      end() {
        return new OrderedMapIterator(this.C, this.C, this);
      }
      rBegin() {
        return new OrderedMapIterator(this.C.h || this.C, this.C, this, 1);
      }
      rEnd() {
        return new OrderedMapIterator(this.C, this.C, this, 1);
      }
      front() {
        if (this.m === 0) return;
        const t2 = this.C.i;
        return [t2.u, t2.l];
      }
      back() {
        if (this.m === 0) return;
        const t2 = this.C.h;
        return [t2.u, t2.l];
      }
      lowerBound(t2) {
        const e2 = this.R(this.v, t2);
        return new OrderedMapIterator(e2, this.C, this);
      }
      upperBound(t2) {
        const e2 = this.K(this.v, t2);
        return new OrderedMapIterator(e2, this.C, this);
      }
      reverseLowerBound(t2) {
        const e2 = this.L(this.v, t2);
        return new OrderedMapIterator(e2, this.C, this);
      }
      reverseUpperBound(t2) {
        const e2 = this.k(this.v, t2);
        return new OrderedMapIterator(e2, this.C, this);
      }
      forEach(t2) {
        this.U(function(e2, s2, i) {
          t2([e2.u, e2.l], s2, i);
        });
      }
      setElement(t2, e2, s2) {
        return this.q(t2, e2, s2);
      }
      getElementByPos(t2) {
        if (t2 < 0 || t2 > this.m - 1) {
          throw new RangeError();
        }
        const e2 = this.U(t2);
        return [e2.u, e2.l];
      }
      find(t2) {
        const e2 = this.H(this.v, t2);
        return new OrderedMapIterator(e2, this.C, this);
      }
      getElementByKey(t2) {
        const e2 = this.H(this.v, t2);
        return e2.l;
      }
      union(t2) {
        const e2 = this;
        t2.forEach(function(t3) {
          e2.setElement(t3[0], t3[1]);
        });
        return this.m;
      }
      *[Symbol.iterator]() {
        const t2 = this.m;
        const e2 = this.U();
        for (let s2 = 0; s2 < t2; ++s2) {
          const t3 = e2[s2];
          yield [t3.u, t3.l];
        }
      }
    };
    exports2.OrderedMap = OrderedMap;
  }
});

// node_modules/@grpc/grpc-js/build/src/admin.js
var require_admin = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/admin.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.registerAdminService = registerAdminService;
    exports2.addAdminServicesToServer = addAdminServicesToServer;
    var registeredAdminServices = [];
    function registerAdminService(getServiceDefinition, getHandlers) {
      registeredAdminServices.push({ getServiceDefinition, getHandlers });
    }
    __name(registerAdminService, "registerAdminService");
    function addAdminServicesToServer(server) {
      for (const { getServiceDefinition, getHandlers } of registeredAdminServices) {
        server.addService(getServiceDefinition(), getHandlers());
      }
    }
    __name(addAdminServicesToServer, "addAdminServicesToServer");
  }
});

// node_modules/@grpc/grpc-js/build/src/call.js
var require_call = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/call.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ClientDuplexStreamImpl = exports2.ClientWritableStreamImpl = exports2.ClientReadableStreamImpl = exports2.ClientUnaryCallImpl = void 0;
    exports2.callErrorFromStatus = callErrorFromStatus;
    var events_1 = __require("events");
    var stream_1 = __require("stream");
    var constants_1 = require_constants9();
    function callErrorFromStatus(status, callerStack) {
      const message = `${status.code} ${constants_1.Status[status.code]}: ${status.details}`;
      const error = new Error(message);
      const stack = `${error.stack}
for call at
${callerStack}`;
      return Object.assign(new Error(message), status, { stack });
    }
    __name(callErrorFromStatus, "callErrorFromStatus");
    var ClientUnaryCallImpl = class extends events_1.EventEmitter {
      static {
        __name(this, "ClientUnaryCallImpl");
      }
      constructor() {
        super();
      }
      cancel() {
        var _a6;
        (_a6 = this.call) === null || _a6 === void 0 ? void 0 : _a6.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client");
      }
      getPeer() {
        var _a6, _b2;
        return (_b2 = (_a6 = this.call) === null || _a6 === void 0 ? void 0 : _a6.getPeer()) !== null && _b2 !== void 0 ? _b2 : "unknown";
      }
    };
    exports2.ClientUnaryCallImpl = ClientUnaryCallImpl;
    var ClientReadableStreamImpl = class extends stream_1.Readable {
      static {
        __name(this, "ClientReadableStreamImpl");
      }
      constructor(deserialize) {
        super({ objectMode: true });
        this.deserialize = deserialize;
      }
      cancel() {
        var _a6;
        (_a6 = this.call) === null || _a6 === void 0 ? void 0 : _a6.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client");
      }
      getPeer() {
        var _a6, _b2;
        return (_b2 = (_a6 = this.call) === null || _a6 === void 0 ? void 0 : _a6.getPeer()) !== null && _b2 !== void 0 ? _b2 : "unknown";
      }
      _read(_size2) {
        var _a6;
        (_a6 = this.call) === null || _a6 === void 0 ? void 0 : _a6.startRead();
      }
    };
    exports2.ClientReadableStreamImpl = ClientReadableStreamImpl;
    var ClientWritableStreamImpl = class extends stream_1.Writable {
      static {
        __name(this, "ClientWritableStreamImpl");
      }
      constructor(serialize2) {
        super({ objectMode: true });
        this.serialize = serialize2;
      }
      cancel() {
        var _a6;
        (_a6 = this.call) === null || _a6 === void 0 ? void 0 : _a6.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client");
      }
      getPeer() {
        var _a6, _b2;
        return (_b2 = (_a6 = this.call) === null || _a6 === void 0 ? void 0 : _a6.getPeer()) !== null && _b2 !== void 0 ? _b2 : "unknown";
      }
      _write(chunk, encoding, cb) {
        var _a6;
        const context2 = {
          callback: cb
        };
        const flags = Number(encoding);
        if (!Number.isNaN(flags)) {
          context2.flags = flags;
        }
        (_a6 = this.call) === null || _a6 === void 0 ? void 0 : _a6.sendMessageWithContext(context2, chunk);
      }
      _final(cb) {
        var _a6;
        (_a6 = this.call) === null || _a6 === void 0 ? void 0 : _a6.halfClose();
        cb();
      }
    };
    exports2.ClientWritableStreamImpl = ClientWritableStreamImpl;
    var ClientDuplexStreamImpl = class extends stream_1.Duplex {
      static {
        __name(this, "ClientDuplexStreamImpl");
      }
      constructor(serialize2, deserialize) {
        super({ objectMode: true });
        this.serialize = serialize2;
        this.deserialize = deserialize;
      }
      cancel() {
        var _a6;
        (_a6 = this.call) === null || _a6 === void 0 ? void 0 : _a6.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client");
      }
      getPeer() {
        var _a6, _b2;
        return (_b2 = (_a6 = this.call) === null || _a6 === void 0 ? void 0 : _a6.getPeer()) !== null && _b2 !== void 0 ? _b2 : "unknown";
      }
      _read(_size2) {
        var _a6;
        (_a6 = this.call) === null || _a6 === void 0 ? void 0 : _a6.startRead();
      }
      _write(chunk, encoding, cb) {
        var _a6;
        const context2 = {
          callback: cb
        };
        const flags = Number(encoding);
        if (!Number.isNaN(flags)) {
          context2.flags = flags;
        }
        (_a6 = this.call) === null || _a6 === void 0 ? void 0 : _a6.sendMessageWithContext(context2, chunk);
      }
      _final(cb) {
        var _a6;
        (_a6 = this.call) === null || _a6 === void 0 ? void 0 : _a6.halfClose();
        cb();
      }
    };
    exports2.ClientDuplexStreamImpl = ClientDuplexStreamImpl;
  }
});

// node_modules/@grpc/grpc-js/build/src/call-interface.js
var require_call_interface = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/call-interface.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InterceptingListenerImpl = void 0;
    exports2.isInterceptingListener = isInterceptingListener;
    function isInterceptingListener(listener) {
      return listener.onReceiveMetadata !== void 0 && listener.onReceiveMetadata.length === 1;
    }
    __name(isInterceptingListener, "isInterceptingListener");
    var InterceptingListenerImpl = class {
      static {
        __name(this, "InterceptingListenerImpl");
      }
      constructor(listener, nextListener) {
        this.listener = listener;
        this.nextListener = nextListener;
        this.processingMetadata = false;
        this.hasPendingMessage = false;
        this.processingMessage = false;
        this.pendingStatus = null;
      }
      processPendingMessage() {
        if (this.hasPendingMessage) {
          this.nextListener.onReceiveMessage(this.pendingMessage);
          this.pendingMessage = null;
          this.hasPendingMessage = false;
        }
      }
      processPendingStatus() {
        if (this.pendingStatus) {
          this.nextListener.onReceiveStatus(this.pendingStatus);
        }
      }
      onReceiveMetadata(metadata) {
        this.processingMetadata = true;
        this.listener.onReceiveMetadata(metadata, (metadata2) => {
          this.processingMetadata = false;
          this.nextListener.onReceiveMetadata(metadata2);
          this.processPendingMessage();
          this.processPendingStatus();
        });
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      onReceiveMessage(message) {
        this.processingMessage = true;
        this.listener.onReceiveMessage(message, (msg) => {
          this.processingMessage = false;
          if (this.processingMetadata) {
            this.pendingMessage = msg;
            this.hasPendingMessage = true;
          } else {
            this.nextListener.onReceiveMessage(msg);
            this.processPendingStatus();
          }
        });
      }
      onReceiveStatus(status) {
        this.listener.onReceiveStatus(status, (processedStatus) => {
          if (this.processingMetadata || this.processingMessage) {
            this.pendingStatus = processedStatus;
          } else {
            this.nextListener.onReceiveStatus(processedStatus);
          }
        });
      }
    };
    exports2.InterceptingListenerImpl = InterceptingListenerImpl;
  }
});

// node_modules/@grpc/grpc-js/build/src/client-interceptors.js
var require_client_interceptors = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/client-interceptors.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InterceptingCall = exports2.RequesterBuilder = exports2.ListenerBuilder = exports2.InterceptorConfigurationError = void 0;
    exports2.getInterceptingCall = getInterceptingCall;
    var metadata_1 = require_metadata3();
    var call_interface_1 = require_call_interface();
    var constants_1 = require_constants9();
    var error_1 = require_error();
    var InterceptorConfigurationError = class _InterceptorConfigurationError extends Error {
      static {
        __name(this, "InterceptorConfigurationError");
      }
      constructor(message) {
        super(message);
        this.name = "InterceptorConfigurationError";
        Error.captureStackTrace(this, _InterceptorConfigurationError);
      }
    };
    exports2.InterceptorConfigurationError = InterceptorConfigurationError;
    var ListenerBuilder = class {
      static {
        __name(this, "ListenerBuilder");
      }
      constructor() {
        this.metadata = void 0;
        this.message = void 0;
        this.status = void 0;
      }
      withOnReceiveMetadata(onReceiveMetadata) {
        this.metadata = onReceiveMetadata;
        return this;
      }
      withOnReceiveMessage(onReceiveMessage) {
        this.message = onReceiveMessage;
        return this;
      }
      withOnReceiveStatus(onReceiveStatus) {
        this.status = onReceiveStatus;
        return this;
      }
      build() {
        return {
          onReceiveMetadata: this.metadata,
          onReceiveMessage: this.message,
          onReceiveStatus: this.status
        };
      }
    };
    exports2.ListenerBuilder = ListenerBuilder;
    var RequesterBuilder = class {
      static {
        __name(this, "RequesterBuilder");
      }
      constructor() {
        this.start = void 0;
        this.message = void 0;
        this.halfClose = void 0;
        this.cancel = void 0;
      }
      withStart(start) {
        this.start = start;
        return this;
      }
      withSendMessage(sendMessage) {
        this.message = sendMessage;
        return this;
      }
      withHalfClose(halfClose) {
        this.halfClose = halfClose;
        return this;
      }
      withCancel(cancel) {
        this.cancel = cancel;
        return this;
      }
      build() {
        return {
          start: this.start,
          sendMessage: this.message,
          halfClose: this.halfClose,
          cancel: this.cancel
        };
      }
    };
    exports2.RequesterBuilder = RequesterBuilder;
    var defaultListener = {
      onReceiveMetadata: /* @__PURE__ */ __name((metadata, next) => {
        next(metadata);
      }, "onReceiveMetadata"),
      onReceiveMessage: /* @__PURE__ */ __name((message, next) => {
        next(message);
      }, "onReceiveMessage"),
      onReceiveStatus: /* @__PURE__ */ __name((status, next) => {
        next(status);
      }, "onReceiveStatus")
    };
    var defaultRequester = {
      start: /* @__PURE__ */ __name((metadata, listener, next) => {
        next(metadata, listener);
      }, "start"),
      sendMessage: /* @__PURE__ */ __name((message, next) => {
        next(message);
      }, "sendMessage"),
      halfClose: /* @__PURE__ */ __name((next) => {
        next();
      }, "halfClose"),
      cancel: /* @__PURE__ */ __name((next) => {
        next();
      }, "cancel")
    };
    var InterceptingCall = class {
      static {
        __name(this, "InterceptingCall");
      }
      constructor(nextCall, requester) {
        var _a6, _b2, _c2, _d;
        this.nextCall = nextCall;
        this.processingMetadata = false;
        this.pendingMessageContext = null;
        this.processingMessage = false;
        this.pendingHalfClose = false;
        if (requester) {
          this.requester = {
            start: (_a6 = requester.start) !== null && _a6 !== void 0 ? _a6 : defaultRequester.start,
            sendMessage: (_b2 = requester.sendMessage) !== null && _b2 !== void 0 ? _b2 : defaultRequester.sendMessage,
            halfClose: (_c2 = requester.halfClose) !== null && _c2 !== void 0 ? _c2 : defaultRequester.halfClose,
            cancel: (_d = requester.cancel) !== null && _d !== void 0 ? _d : defaultRequester.cancel
          };
        } else {
          this.requester = defaultRequester;
        }
      }
      cancelWithStatus(status, details) {
        this.requester.cancel(() => {
          this.nextCall.cancelWithStatus(status, details);
        });
      }
      getPeer() {
        return this.nextCall.getPeer();
      }
      processPendingMessage() {
        if (this.pendingMessageContext) {
          this.nextCall.sendMessageWithContext(this.pendingMessageContext, this.pendingMessage);
          this.pendingMessageContext = null;
          this.pendingMessage = null;
        }
      }
      processPendingHalfClose() {
        if (this.pendingHalfClose) {
          this.nextCall.halfClose();
        }
      }
      start(metadata, interceptingListener) {
        var _a6, _b2, _c2, _d, _e, _f;
        const fullInterceptingListener = {
          onReceiveMetadata: (_b2 = (_a6 = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a6 === void 0 ? void 0 : _a6.bind(interceptingListener)) !== null && _b2 !== void 0 ? _b2 : (metadata2) => {
          },
          onReceiveMessage: (_d = (_c2 = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _c2 === void 0 ? void 0 : _c2.bind(interceptingListener)) !== null && _d !== void 0 ? _d : (message) => {
          },
          onReceiveStatus: (_f = (_e = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _e === void 0 ? void 0 : _e.bind(interceptingListener)) !== null && _f !== void 0 ? _f : (status) => {
          }
        };
        this.processingMetadata = true;
        this.requester.start(metadata, fullInterceptingListener, (md, listener) => {
          var _a7, _b3, _c3;
          this.processingMetadata = false;
          let finalInterceptingListener;
          if ((0, call_interface_1.isInterceptingListener)(listener)) {
            finalInterceptingListener = listener;
          } else {
            const fullListener = {
              onReceiveMetadata: (_a7 = listener.onReceiveMetadata) !== null && _a7 !== void 0 ? _a7 : defaultListener.onReceiveMetadata,
              onReceiveMessage: (_b3 = listener.onReceiveMessage) !== null && _b3 !== void 0 ? _b3 : defaultListener.onReceiveMessage,
              onReceiveStatus: (_c3 = listener.onReceiveStatus) !== null && _c3 !== void 0 ? _c3 : defaultListener.onReceiveStatus
            };
            finalInterceptingListener = new call_interface_1.InterceptingListenerImpl(fullListener, fullInterceptingListener);
          }
          this.nextCall.start(md, finalInterceptingListener);
          this.processPendingMessage();
          this.processPendingHalfClose();
        });
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      sendMessageWithContext(context2, message) {
        this.processingMessage = true;
        this.requester.sendMessage(message, (finalMessage) => {
          this.processingMessage = false;
          if (this.processingMetadata) {
            this.pendingMessageContext = context2;
            this.pendingMessage = message;
          } else {
            this.nextCall.sendMessageWithContext(context2, finalMessage);
            this.processPendingHalfClose();
          }
        });
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      sendMessage(message) {
        this.sendMessageWithContext({}, message);
      }
      startRead() {
        this.nextCall.startRead();
      }
      halfClose() {
        this.requester.halfClose(() => {
          if (this.processingMetadata || this.processingMessage) {
            this.pendingHalfClose = true;
          } else {
            this.nextCall.halfClose();
          }
        });
      }
    };
    exports2.InterceptingCall = InterceptingCall;
    function getCall(channel, path108, options2) {
      var _a6, _b2;
      const deadline = (_a6 = options2.deadline) !== null && _a6 !== void 0 ? _a6 : Infinity;
      const host = options2.host;
      const parent = (_b2 = options2.parent) !== null && _b2 !== void 0 ? _b2 : null;
      const propagateFlags = options2.propagate_flags;
      const credentials = options2.credentials;
      const call = channel.createCall(path108, deadline, host, parent, propagateFlags);
      if (credentials) {
        call.setCredentials(credentials);
      }
      return call;
    }
    __name(getCall, "getCall");
    var BaseInterceptingCall = class {
      static {
        __name(this, "BaseInterceptingCall");
      }
      constructor(call, methodDefinition) {
        this.call = call;
        this.methodDefinition = methodDefinition;
      }
      cancelWithStatus(status, details) {
        this.call.cancelWithStatus(status, details);
      }
      getPeer() {
        return this.call.getPeer();
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      sendMessageWithContext(context2, message) {
        let serialized;
        try {
          serialized = this.methodDefinition.requestSerialize(message);
        } catch (e2) {
          this.call.cancelWithStatus(constants_1.Status.INTERNAL, `Request message serialization failure: ${(0, error_1.getErrorMessage)(e2)}`);
          return;
        }
        this.call.sendMessageWithContext(context2, serialized);
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      sendMessage(message) {
        this.sendMessageWithContext({}, message);
      }
      start(metadata, interceptingListener) {
        let readError = null;
        this.call.start(metadata, {
          onReceiveMetadata: /* @__PURE__ */ __name((metadata2) => {
            var _a6;
            (_a6 = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a6 === void 0 ? void 0 : _a6.call(interceptingListener, metadata2);
          }, "onReceiveMetadata"),
          onReceiveMessage: /* @__PURE__ */ __name((message) => {
            var _a6;
            let deserialized;
            try {
              deserialized = this.methodDefinition.responseDeserialize(message);
            } catch (e2) {
              readError = {
                code: constants_1.Status.INTERNAL,
                details: `Response message parsing error: ${(0, error_1.getErrorMessage)(e2)}`,
                metadata: new metadata_1.Metadata()
              };
              this.call.cancelWithStatus(readError.code, readError.details);
              return;
            }
            (_a6 = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _a6 === void 0 ? void 0 : _a6.call(interceptingListener, deserialized);
          }, "onReceiveMessage"),
          onReceiveStatus: /* @__PURE__ */ __name((status) => {
            var _a6, _b2;
            if (readError) {
              (_a6 = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _a6 === void 0 ? void 0 : _a6.call(interceptingListener, readError);
            } else {
              (_b2 = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _b2 === void 0 ? void 0 : _b2.call(interceptingListener, status);
            }
          }, "onReceiveStatus")
        });
      }
      startRead() {
        this.call.startRead();
      }
      halfClose() {
        this.call.halfClose();
      }
    };
    var BaseUnaryInterceptingCall = class extends BaseInterceptingCall {
      static {
        __name(this, "BaseUnaryInterceptingCall");
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      constructor(call, methodDefinition) {
        super(call, methodDefinition);
      }
      start(metadata, listener) {
        var _a6, _b2;
        let receivedMessage = false;
        const wrapperListener = {
          onReceiveMetadata: (_b2 = (_a6 = listener === null || listener === void 0 ? void 0 : listener.onReceiveMetadata) === null || _a6 === void 0 ? void 0 : _a6.bind(listener)) !== null && _b2 !== void 0 ? _b2 : (metadata2) => {
          },
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          onReceiveMessage: /* @__PURE__ */ __name((message) => {
            var _a7;
            receivedMessage = true;
            (_a7 = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a7 === void 0 ? void 0 : _a7.call(listener, message);
          }, "onReceiveMessage"),
          onReceiveStatus: /* @__PURE__ */ __name((status) => {
            var _a7, _b3;
            if (!receivedMessage) {
              (_a7 = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a7 === void 0 ? void 0 : _a7.call(listener, null);
            }
            (_b3 = listener === null || listener === void 0 ? void 0 : listener.onReceiveStatus) === null || _b3 === void 0 ? void 0 : _b3.call(listener, status);
          }, "onReceiveStatus")
        };
        super.start(metadata, wrapperListener);
        this.call.startRead();
      }
    };
    var BaseStreamingInterceptingCall = class extends BaseInterceptingCall {
      static {
        __name(this, "BaseStreamingInterceptingCall");
      }
    };
    function getBottomInterceptingCall(channel, options2, methodDefinition) {
      const call = getCall(channel, methodDefinition.path, options2);
      if (methodDefinition.responseStream) {
        return new BaseStreamingInterceptingCall(call, methodDefinition);
      } else {
        return new BaseUnaryInterceptingCall(call, methodDefinition);
      }
    }
    __name(getBottomInterceptingCall, "getBottomInterceptingCall");
    function getInterceptingCall(interceptorArgs, methodDefinition, options2, channel) {
      if (interceptorArgs.clientInterceptors.length > 0 && interceptorArgs.clientInterceptorProviders.length > 0) {
        throw new InterceptorConfigurationError("Both interceptors and interceptor_providers were passed as options to the client constructor. Only one of these is allowed.");
      }
      if (interceptorArgs.callInterceptors.length > 0 && interceptorArgs.callInterceptorProviders.length > 0) {
        throw new InterceptorConfigurationError("Both interceptors and interceptor_providers were passed as call options. Only one of these is allowed.");
      }
      let interceptors = [];
      if (interceptorArgs.callInterceptors.length > 0 || interceptorArgs.callInterceptorProviders.length > 0) {
        interceptors = [].concat(interceptorArgs.callInterceptors, interceptorArgs.callInterceptorProviders.map((provider) => provider(methodDefinition))).filter((interceptor) => interceptor);
      } else {
        interceptors = [].concat(interceptorArgs.clientInterceptors, interceptorArgs.clientInterceptorProviders.map((provider) => provider(methodDefinition))).filter((interceptor) => interceptor);
      }
      const interceptorOptions = Object.assign({}, options2, {
        method_definition: methodDefinition
      });
      const getCall2 = interceptors.reduceRight((nextCall, nextInterceptor) => {
        return (currentOptions) => nextInterceptor(currentOptions, nextCall);
      }, (finalOptions) => getBottomInterceptingCall(channel, finalOptions, methodDefinition));
      return getCall2(interceptorOptions);
    }
    __name(getInterceptingCall, "getInterceptingCall");
  }
});

// node_modules/@grpc/grpc-js/build/src/client.js
var require_client2 = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/client.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Client = void 0;
    var call_1 = require_call();
    var channel_1 = require_channel();
    var connectivity_state_1 = require_connectivity_state();
    var constants_1 = require_constants9();
    var metadata_1 = require_metadata3();
    var client_interceptors_1 = require_client_interceptors();
    var CHANNEL_SYMBOL = Symbol();
    var INTERCEPTOR_SYMBOL = Symbol();
    var INTERCEPTOR_PROVIDER_SYMBOL = Symbol();
    var CALL_INVOCATION_TRANSFORMER_SYMBOL = Symbol();
    function isFunction3(arg) {
      return typeof arg === "function";
    }
    __name(isFunction3, "isFunction");
    function getErrorStackString(error) {
      var _a6;
      return ((_a6 = error.stack) === null || _a6 === void 0 ? void 0 : _a6.split("\n").slice(1).join("\n")) || "no stack trace available";
    }
    __name(getErrorStackString, "getErrorStackString");
    var Client2 = class {
      static {
        __name(this, "Client");
      }
      constructor(address, credentials, options2 = {}) {
        var _a6, _b2;
        options2 = Object.assign({}, options2);
        this[INTERCEPTOR_SYMBOL] = (_a6 = options2.interceptors) !== null && _a6 !== void 0 ? _a6 : [];
        delete options2.interceptors;
        this[INTERCEPTOR_PROVIDER_SYMBOL] = (_b2 = options2.interceptor_providers) !== null && _b2 !== void 0 ? _b2 : [];
        delete options2.interceptor_providers;
        if (this[INTERCEPTOR_SYMBOL].length > 0 && this[INTERCEPTOR_PROVIDER_SYMBOL].length > 0) {
          throw new Error("Both interceptors and interceptor_providers were passed as options to the client constructor. Only one of these is allowed.");
        }
        this[CALL_INVOCATION_TRANSFORMER_SYMBOL] = options2.callInvocationTransformer;
        delete options2.callInvocationTransformer;
        if (options2.channelOverride) {
          this[CHANNEL_SYMBOL] = options2.channelOverride;
        } else if (options2.channelFactoryOverride) {
          const channelFactoryOverride = options2.channelFactoryOverride;
          delete options2.channelFactoryOverride;
          this[CHANNEL_SYMBOL] = channelFactoryOverride(address, credentials, options2);
        } else {
          this[CHANNEL_SYMBOL] = new channel_1.ChannelImplementation(address, credentials, options2);
        }
      }
      close() {
        this[CHANNEL_SYMBOL].close();
      }
      getChannel() {
        return this[CHANNEL_SYMBOL];
      }
      waitForReady(deadline, callback) {
        const checkState = /* @__PURE__ */ __name((err) => {
          if (err) {
            callback(new Error("Failed to connect before the deadline"));
            return;
          }
          let newState;
          try {
            newState = this[CHANNEL_SYMBOL].getConnectivityState(true);
          } catch (e2) {
            callback(new Error("The channel has been closed"));
            return;
          }
          if (newState === connectivity_state_1.ConnectivityState.READY) {
            callback();
          } else {
            try {
              this[CHANNEL_SYMBOL].watchConnectivityState(newState, deadline, checkState);
            } catch (e2) {
              callback(new Error("The channel has been closed"));
            }
          }
        }, "checkState");
        setImmediate(checkState);
      }
      checkOptionalUnaryResponseArguments(arg1, arg2, arg3) {
        if (isFunction3(arg1)) {
          return { metadata: new metadata_1.Metadata(), options: {}, callback: arg1 };
        } else if (isFunction3(arg2)) {
          if (arg1 instanceof metadata_1.Metadata) {
            return { metadata: arg1, options: {}, callback: arg2 };
          } else {
            return { metadata: new metadata_1.Metadata(), options: arg1, callback: arg2 };
          }
        } else {
          if (!(arg1 instanceof metadata_1.Metadata && arg2 instanceof Object && isFunction3(arg3))) {
            throw new Error("Incorrect arguments passed");
          }
          return { metadata: arg1, options: arg2, callback: arg3 };
        }
      }
      makeUnaryRequest(method, serialize2, deserialize, argument, metadata, options2, callback) {
        var _a6, _b2;
        const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options2, callback);
        const methodDefinition = {
          path: method,
          requestStream: false,
          responseStream: false,
          requestSerialize: serialize2,
          responseDeserialize: deserialize
        };
        let callProperties = {
          argument,
          metadata: checkedArguments.metadata,
          call: new call_1.ClientUnaryCallImpl(),
          channel: this[CHANNEL_SYMBOL],
          methodDefinition,
          callOptions: checkedArguments.options,
          callback: checkedArguments.callback
        };
        if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) {
          callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties);
        }
        const emitter = callProperties.call;
        const interceptorArgs = {
          clientInterceptors: this[INTERCEPTOR_SYMBOL],
          clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL],
          callInterceptors: (_a6 = callProperties.callOptions.interceptors) !== null && _a6 !== void 0 ? _a6 : [],
          callInterceptorProviders: (_b2 = callProperties.callOptions.interceptor_providers) !== null && _b2 !== void 0 ? _b2 : []
        };
        const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel);
        emitter.call = call;
        let responseMessage = null;
        let receivedStatus = false;
        let callerStackError = new Error();
        call.start(callProperties.metadata, {
          onReceiveMetadata: /* @__PURE__ */ __name((metadata2) => {
            emitter.emit("metadata", metadata2);
          }, "onReceiveMetadata"),
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          onReceiveMessage(message) {
            if (responseMessage !== null) {
              call.cancelWithStatus(constants_1.Status.UNIMPLEMENTED, "Too many responses received");
            }
            responseMessage = message;
          },
          onReceiveStatus(status) {
            if (receivedStatus) {
              return;
            }
            receivedStatus = true;
            if (status.code === constants_1.Status.OK) {
              if (responseMessage === null) {
                const callerStack = getErrorStackString(callerStackError);
                callProperties.callback((0, call_1.callErrorFromStatus)({
                  code: constants_1.Status.UNIMPLEMENTED,
                  details: "No message received",
                  metadata: status.metadata
                }, callerStack));
              } else {
                callProperties.callback(null, responseMessage);
              }
            } else {
              const callerStack = getErrorStackString(callerStackError);
              callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack));
            }
            callerStackError = null;
            emitter.emit("status", status);
          }
        });
        call.sendMessage(argument);
        call.halfClose();
        return emitter;
      }
      makeClientStreamRequest(method, serialize2, deserialize, metadata, options2, callback) {
        var _a6, _b2;
        const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options2, callback);
        const methodDefinition = {
          path: method,
          requestStream: true,
          responseStream: false,
          requestSerialize: serialize2,
          responseDeserialize: deserialize
        };
        let callProperties = {
          metadata: checkedArguments.metadata,
          call: new call_1.ClientWritableStreamImpl(serialize2),
          channel: this[CHANNEL_SYMBOL],
          methodDefinition,
          callOptions: checkedArguments.options,
          callback: checkedArguments.callback
        };
        if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) {
          callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties);
        }
        const emitter = callProperties.call;
        const interceptorArgs = {
          clientInterceptors: this[INTERCEPTOR_SYMBOL],
          clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL],
          callInterceptors: (_a6 = callProperties.callOptions.interceptors) !== null && _a6 !== void 0 ? _a6 : [],
          callInterceptorProviders: (_b2 = callProperties.callOptions.interceptor_providers) !== null && _b2 !== void 0 ? _b2 : []
        };
        const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel);
        emitter.call = call;
        let responseMessage = null;
        let receivedStatus = false;
        let callerStackError = new Error();
        call.start(callProperties.metadata, {
          onReceiveMetadata: /* @__PURE__ */ __name((metadata2) => {
            emitter.emit("metadata", metadata2);
          }, "onReceiveMetadata"),
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          onReceiveMessage(message) {
            if (responseMessage !== null) {
              call.cancelWithStatus(constants_1.Status.UNIMPLEMENTED, "Too many responses received");
            }
            responseMessage = message;
            call.startRead();
          },
          onReceiveStatus(status) {
            if (receivedStatus) {
              return;
            }
            receivedStatus = true;
            if (status.code === constants_1.Status.OK) {
              if (responseMessage === null) {
                const callerStack = getErrorStackString(callerStackError);
                callProperties.callback((0, call_1.callErrorFromStatus)({
                  code: constants_1.Status.UNIMPLEMENTED,
                  details: "No message received",
                  metadata: status.metadata
                }, callerStack));
              } else {
                callProperties.callback(null, responseMessage);
              }
            } else {
              const callerStack = getErrorStackString(callerStackError);
              callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack));
            }
            callerStackError = null;
            emitter.emit("status", status);
          }
        });
        return emitter;
      }
      checkMetadataAndOptions(arg1, arg2) {
        let metadata;
        let options2;
        if (arg1 instanceof metadata_1.Metadata) {
          metadata = arg1;
          if (arg2) {
            options2 = arg2;
          } else {
            options2 = {};
          }
        } else {
          if (arg1) {
            options2 = arg1;
          } else {
            options2 = {};
          }
          metadata = new metadata_1.Metadata();
        }
        return { metadata, options: options2 };
      }
      makeServerStreamRequest(method, serialize2, deserialize, argument, metadata, options2) {
        var _a6, _b2;
        const checkedArguments = this.checkMetadataAndOptions(metadata, options2);
        const methodDefinition = {
          path: method,
          requestStream: false,
          responseStream: true,
          requestSerialize: serialize2,
          responseDeserialize: deserialize
        };
        let callProperties = {
          argument,
          metadata: checkedArguments.metadata,
          call: new call_1.ClientReadableStreamImpl(deserialize),
          channel: this[CHANNEL_SYMBOL],
          methodDefinition,
          callOptions: checkedArguments.options
        };
        if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) {
          callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties);
        }
        const stream2 = callProperties.call;
        const interceptorArgs = {
          clientInterceptors: this[INTERCEPTOR_SYMBOL],
          clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL],
          callInterceptors: (_a6 = callProperties.callOptions.interceptors) !== null && _a6 !== void 0 ? _a6 : [],
          callInterceptorProviders: (_b2 = callProperties.callOptions.interceptor_providers) !== null && _b2 !== void 0 ? _b2 : []
        };
        const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel);
        stream2.call = call;
        let receivedStatus = false;
        let callerStackError = new Error();
        call.start(callProperties.metadata, {
          onReceiveMetadata(metadata2) {
            stream2.emit("metadata", metadata2);
          },
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          onReceiveMessage(message) {
            stream2.push(message);
          },
          onReceiveStatus(status) {
            if (receivedStatus) {
              return;
            }
            receivedStatus = true;
            stream2.push(null);
            if (status.code !== constants_1.Status.OK) {
              const callerStack = getErrorStackString(callerStackError);
              stream2.emit("error", (0, call_1.callErrorFromStatus)(status, callerStack));
            }
            callerStackError = null;
            stream2.emit("status", status);
          }
        });
        call.sendMessage(argument);
        call.halfClose();
        return stream2;
      }
      makeBidiStreamRequest(method, serialize2, deserialize, metadata, options2) {
        var _a6, _b2;
        const checkedArguments = this.checkMetadataAndOptions(metadata, options2);
        const methodDefinition = {
          path: method,
          requestStream: true,
          responseStream: true,
          requestSerialize: serialize2,
          responseDeserialize: deserialize
        };
        let callProperties = {
          metadata: checkedArguments.metadata,
          call: new call_1.ClientDuplexStreamImpl(serialize2, deserialize),
          channel: this[CHANNEL_SYMBOL],
          methodDefinition,
          callOptions: checkedArguments.options
        };
        if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) {
          callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties);
        }
        const stream2 = callProperties.call;
        const interceptorArgs = {
          clientInterceptors: this[INTERCEPTOR_SYMBOL],
          clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL],
          callInterceptors: (_a6 = callProperties.callOptions.interceptors) !== null && _a6 !== void 0 ? _a6 : [],
          callInterceptorProviders: (_b2 = callProperties.callOptions.interceptor_providers) !== null && _b2 !== void 0 ? _b2 : []
        };
        const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel);
        stream2.call = call;
        let receivedStatus = false;
        let callerStackError = new Error();
        call.start(callProperties.metadata, {
          onReceiveMetadata(metadata2) {
            stream2.emit("metadata", metadata2);
          },
          onReceiveMessage(message) {
            stream2.push(message);
          },
          onReceiveStatus(status) {
            if (receivedStatus) {
              return;
            }
            receivedStatus = true;
            stream2.push(null);
            if (status.code !== constants_1.Status.OK) {
              const callerStack = getErrorStackString(callerStackError);
              stream2.emit("error", (0, call_1.callErrorFromStatus)(status, callerStack));
            }
            callerStackError = null;
            stream2.emit("status", status);
          }
        });
        return stream2;
      }
    };
    exports2.Client = Client2;
  }
});

// node_modules/@grpc/grpc-js/build/src/make-client.js
var require_make_client = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/make-client.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.makeClientConstructor = makeClientConstructor;
    exports2.loadPackageDefinition = loadPackageDefinition;
    var client_1 = require_client2();
    var requesterFuncs = {
      unary: client_1.Client.prototype.makeUnaryRequest,
      server_stream: client_1.Client.prototype.makeServerStreamRequest,
      client_stream: client_1.Client.prototype.makeClientStreamRequest,
      bidi: client_1.Client.prototype.makeBidiStreamRequest
    };
    function isPrototypePolluted(key) {
      return ["__proto__", "prototype", "constructor"].includes(key);
    }
    __name(isPrototypePolluted, "isPrototypePolluted");
    function makeClientConstructor(methods, serviceName, classOptions) {
      if (!classOptions) {
        classOptions = {};
      }
      class ServiceClientImpl extends client_1.Client {
        static {
          __name(this, "ServiceClientImpl");
        }
      }
      Object.keys(methods).forEach((name3) => {
        if (isPrototypePolluted(name3)) {
          return;
        }
        const attrs = methods[name3];
        let methodType;
        if (typeof name3 === "string" && name3.charAt(0) === "$") {
          throw new Error("Method names cannot start with $");
        }
        if (attrs.requestStream) {
          if (attrs.responseStream) {
            methodType = "bidi";
          } else {
            methodType = "client_stream";
          }
        } else {
          if (attrs.responseStream) {
            methodType = "server_stream";
          } else {
            methodType = "unary";
          }
        }
        const serialize2 = attrs.requestSerialize;
        const deserialize = attrs.responseDeserialize;
        const methodFunc = partial(requesterFuncs[methodType], attrs.path, serialize2, deserialize);
        ServiceClientImpl.prototype[name3] = methodFunc;
        Object.assign(ServiceClientImpl.prototype[name3], attrs);
        if (attrs.originalName && !isPrototypePolluted(attrs.originalName)) {
          ServiceClientImpl.prototype[attrs.originalName] = ServiceClientImpl.prototype[name3];
        }
      });
      ServiceClientImpl.service = methods;
      ServiceClientImpl.serviceName = serviceName;
      return ServiceClientImpl;
    }
    __name(makeClientConstructor, "makeClientConstructor");
    function partial(fn, path108, serialize2, deserialize) {
      return function(...args) {
        return fn.call(this, path108, serialize2, deserialize, ...args);
      };
    }
    __name(partial, "partial");
    function isProtobufTypeDefinition(obj) {
      return "format" in obj;
    }
    __name(isProtobufTypeDefinition, "isProtobufTypeDefinition");
    function loadPackageDefinition(packageDef) {
      const result = {};
      for (const serviceFqn in packageDef) {
        if (Object.prototype.hasOwnProperty.call(packageDef, serviceFqn)) {
          const service = packageDef[serviceFqn];
          const nameComponents = serviceFqn.split(".");
          if (nameComponents.some((comp) => isPrototypePolluted(comp))) {
            continue;
          }
          const serviceName = nameComponents[nameComponents.length - 1];
          let current = result;
          for (const packageName of nameComponents.slice(0, -1)) {
            if (!current[packageName]) {
              current[packageName] = {};
            }
            current = current[packageName];
          }
          if (isProtobufTypeDefinition(service)) {
            current[serviceName] = service;
          } else {
            current[serviceName] = makeClientConstructor(service, serviceName, {});
          }
        }
      }
      return result;
    }
    __name(loadPackageDefinition, "loadPackageDefinition");
  }
});

// node_modules/lodash.camelcase/index.js
var require_lodash = __commonJS({
  "node_modules/lodash.camelcase/index.js"(exports2, module2) {
    init_esbuild_shims();
    var INFINITY2 = 1 / 0;
    var symbolTag = "[object Symbol]";
    var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
    var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
    var rsAstralRange = "\\ud800-\\udfff";
    var rsComboMarksRange = "\\u0300-\\u036f\\ufe20-\\ufe23";
    var rsComboSymbolsRange = "\\u20d0-\\u20f0";
    var rsDingbatRange = "\\u2700-\\u27bf";
    var rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff";
    var rsMathOpRange = "\\xac\\xb1\\xd7\\xf7";
    var rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf";
    var rsPunctuationRange = "\\u2000-\\u206f";
    var rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000";
    var rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde";
    var rsVarRange = "\\ufe0e\\ufe0f";
    var rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
    var rsApos = "['\u2019]";
    var rsAstral = "[" + rsAstralRange + "]";
    var rsBreak = "[" + rsBreakRange + "]";
    var rsCombo = "[" + rsComboMarksRange + rsComboSymbolsRange + "]";
    var rsDigits = "\\d+";
    var rsDingbat = "[" + rsDingbatRange + "]";
    var rsLower = "[" + rsLowerRange + "]";
    var rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]";
    var rsFitz = "\\ud83c[\\udffb-\\udfff]";
    var rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")";
    var rsNonAstral = "[^" + rsAstralRange + "]";
    var rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}";
    var rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]";
    var rsUpper = "[" + rsUpperRange + "]";
    var rsZWJ = "\\u200d";
    var rsLowerMisc = "(?:" + rsLower + "|" + rsMisc + ")";
    var rsUpperMisc = "(?:" + rsUpper + "|" + rsMisc + ")";
    var rsOptLowerContr = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?";
    var rsOptUpperContr = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?";
    var reOptMod = rsModifier + "?";
    var rsOptVar = "[" + rsVarRange + "]?";
    var rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*";
    var rsSeq = rsOptVar + reOptMod + rsOptJoin;
    var rsEmoji = "(?:" + [rsDingbat, rsRegional, rsSurrPair].join("|") + ")" + rsSeq;
    var rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")";
    var reApos = RegExp(rsApos, "g");
    var reComboMark = RegExp(rsCombo, "g");
    var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g");
    var reUnicodeWord = RegExp([
      rsUpper + "?" + rsLower + "+" + rsOptLowerContr + "(?=" + [rsBreak, rsUpper, "$"].join("|") + ")",
      rsUpperMisc + "+" + rsOptUpperContr + "(?=" + [rsBreak, rsUpper + rsLowerMisc, "$"].join("|") + ")",
      rsUpper + "?" + rsLowerMisc + "+" + rsOptLowerContr,
      rsUpper + "+" + rsOptUpperContr,
      rsDigits,
      rsEmoji
    ].join("|"), "g");
    var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + "]");
    var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
    var deburredLetters = {
      // Latin-1 Supplement block.
      "\xC0": "A",
      "\xC1": "A",
      "\xC2": "A",
      "\xC3": "A",
      "\xC4": "A",
      "\xC5": "A",
      "\xE0": "a",
      "\xE1": "a",
      "\xE2": "a",
      "\xE3": "a",
      "\xE4": "a",
      "\xE5": "a",
      "\xC7": "C",
      "\xE7": "c",
      "\xD0": "D",
      "\xF0": "d",
      "\xC8": "E",
      "\xC9": "E",
      "\xCA": "E",
      "\xCB": "E",
      "\xE8": "e",
      "\xE9": "e",
      "\xEA": "e",
      "\xEB": "e",
      "\xCC": "I",
      "\xCD": "I",
      "\xCE": "I",
      "\xCF": "I",
      "\xEC": "i",
      "\xED": "i",
      "\xEE": "i",
      "\xEF": "i",
      "\xD1": "N",
      "\xF1": "n",
      "\xD2": "O",
      "\xD3": "O",
      "\xD4": "O",
      "\xD5": "O",
      "\xD6": "O",
      "\xD8": "O",
      "\xF2": "o",
      "\xF3": "o",
      "\xF4": "o",
      "\xF5": "o",
      "\xF6": "o",
      "\xF8": "o",
      "\xD9": "U",
      "\xDA": "U",
      "\xDB": "U",
      "\xDC": "U",
      "\xF9": "u",
      "\xFA": "u",
      "\xFB": "u",
      "\xFC": "u",
      "\xDD": "Y",
      "\xFD": "y",
      "\xFF": "y",
      "\xC6": "Ae",
      "\xE6": "ae",
      "\xDE": "Th",
      "\xFE": "th",
      "\xDF": "ss",
      // Latin Extended-A block.
      "\u0100": "A",
      "\u0102": "A",
      "\u0104": "A",
      "\u0101": "a",
      "\u0103": "a",
      "\u0105": "a",
      "\u0106": "C",
      "\u0108": "C",
      "\u010A": "C",
      "\u010C": "C",
      "\u0107": "c",
      "\u0109": "c",
      "\u010B": "c",
      "\u010D": "c",
      "\u010E": "D",
      "\u0110": "D",
      "\u010F": "d",
      "\u0111": "d",
      "\u0112": "E",
      "\u0114": "E",
      "\u0116": "E",
      "\u0118": "E",
      "\u011A": "E",
      "\u0113": "e",
      "\u0115": "e",
      "\u0117": "e",
      "\u0119": "e",
      "\u011B": "e",
      "\u011C": "G",
      "\u011E": "G",
      "\u0120": "G",
      "\u0122": "G",
      "\u011D": "g",
      "\u011F": "g",
      "\u0121": "g",
      "\u0123": "g",
      "\u0124": "H",
      "\u0126": "H",
      "\u0125": "h",
      "\u0127": "h",
      "\u0128": "I",
      "\u012A": "I",
      "\u012C": "I",
      "\u012E": "I",
      "\u0130": "I",
      "\u0129": "i",
      "\u012B": "i",
      "\u012D": "i",
      "\u012F": "i",
      "\u0131": "i",
      "\u0134": "J",
      "\u0135": "j",
      "\u0136": "K",
      "\u0137": "k",
      "\u0138": "k",
      "\u0139": "L",
      "\u013B": "L",
      "\u013D": "L",
      "\u013F": "L",
      "\u0141": "L",
      "\u013A": "l",
      "\u013C": "l",
      "\u013E": "l",
      "\u0140": "l",
      "\u0142": "l",
      "\u0143": "N",
      "\u0145": "N",
      "\u0147": "N",
      "\u014A": "N",
      "\u0144": "n",
      "\u0146": "n",
      "\u0148": "n",
      "\u014B": "n",
      "\u014C": "O",
      "\u014E": "O",
      "\u0150": "O",
      "\u014D": "o",
      "\u014F": "o",
      "\u0151": "o",
      "\u0154": "R",
      "\u0156": "R",
      "\u0158": "R",
      "\u0155": "r",
      "\u0157": "r",
      "\u0159": "r",
      "\u015A": "S",
      "\u015C": "S",
      "\u015E": "S",
      "\u0160": "S",
      "\u015B": "s",
      "\u015D": "s",
      "\u015F": "s",
      "\u0161": "s",
      "\u0162": "T",
      "\u0164": "T",
      "\u0166": "T",
      "\u0163": "t",
      "\u0165": "t",
      "\u0167": "t",
      "\u0168": "U",
      "\u016A": "U",
      "\u016C": "U",
      "\u016E": "U",
      "\u0170": "U",
      "\u0172": "U",
      "\u0169": "u",
      "\u016B": "u",
      "\u016D": "u",
      "\u016F": "u",
      "\u0171": "u",
      "\u0173": "u",
      "\u0174": "W",
      "\u0175": "w",
      "\u0176": "Y",
      "\u0177": "y",
      "\u0178": "Y",
      "\u0179": "Z",
      "\u017B": "Z",
      "\u017D": "Z",
      "\u017A": "z",
      "\u017C": "z",
      "\u017E": "z",
      "\u0132": "IJ",
      "\u0133": "ij",
      "\u0152": "Oe",
      "\u0153": "oe",
      "\u0149": "'n",
      "\u017F": "ss"
    };
    var freeGlobal = typeof globalThis == "object" && globalThis && globalThis.Object === Object && globalThis;
    var freeSelf = typeof self == "object" && self && self.Object === Object && self;
    var root = freeGlobal || freeSelf || Function("return this")();
    function arrayReduce(array, iteratee, accumulator, initAccum) {
      var index = -1, length = array ? array.length : 0;
      if (initAccum && length) {
        accumulator = array[++index];
      }
      while (++index < length) {
        accumulator = iteratee(accumulator, array[index], index, array);
      }
      return accumulator;
    }
    __name(arrayReduce, "arrayReduce");
    function asciiToArray(string) {
      return string.split("");
    }
    __name(asciiToArray, "asciiToArray");
    function asciiWords(string) {
      return string.match(reAsciiWord) || [];
    }
    __name(asciiWords, "asciiWords");
    function basePropertyOf(object) {
      return function(key) {
        return object == null ? void 0 : object[key];
      };
    }
    __name(basePropertyOf, "basePropertyOf");
    var deburrLetter = basePropertyOf(deburredLetters);
    function hasUnicode(string) {
      return reHasUnicode.test(string);
    }
    __name(hasUnicode, "hasUnicode");
    function hasUnicodeWord(string) {
      return reHasUnicodeWord.test(string);
    }
    __name(hasUnicodeWord, "hasUnicodeWord");
    function stringToArray(string) {
      return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string);
    }
    __name(stringToArray, "stringToArray");
    function unicodeToArray(string) {
      return string.match(reUnicode) || [];
    }
    __name(unicodeToArray, "unicodeToArray");
    function unicodeWords(string) {
      return string.match(reUnicodeWord) || [];
    }
    __name(unicodeWords, "unicodeWords");
    var objectProto = Object.prototype;
    var objectToString2 = objectProto.toString;
    var Symbol2 = root.Symbol;
    var symbolProto = Symbol2 ? Symbol2.prototype : void 0;
    var symbolToString = symbolProto ? symbolProto.toString : void 0;
    function baseSlice(array, start, end) {
      var index = -1, length = array.length;
      if (start < 0) {
        start = -start > length ? 0 : length + start;
      }
      end = end > length ? length : end;
      if (end < 0) {
        end += length;
      }
      length = start > end ? 0 : end - start >>> 0;
      start >>>= 0;
      var result = Array(length);
      while (++index < length) {
        result[index] = array[index + start];
      }
      return result;
    }
    __name(baseSlice, "baseSlice");
    function baseToString(value) {
      if (typeof value == "string") {
        return value;
      }
      if (isSymbol(value)) {
        return symbolToString ? symbolToString.call(value) : "";
      }
      var result = value + "";
      return result == "0" && 1 / value == -INFINITY2 ? "-0" : result;
    }
    __name(baseToString, "baseToString");
    function castSlice(array, start, end) {
      var length = array.length;
      end = end === void 0 ? length : end;
      return !start && end >= length ? array : baseSlice(array, start, end);
    }
    __name(castSlice, "castSlice");
    function createCaseFirst(methodName) {
      return function(string) {
        string = toString(string);
        var strSymbols = hasUnicode(string) ? stringToArray(string) : void 0;
        var chr = strSymbols ? strSymbols[0] : string.charAt(0);
        var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string.slice(1);
        return chr[methodName]() + trailing;
      };
    }
    __name(createCaseFirst, "createCaseFirst");
    function createCompounder(callback) {
      return function(string) {
        return arrayReduce(words(deburr(string).replace(reApos, "")), callback, "");
      };
    }
    __name(createCompounder, "createCompounder");
    function isObjectLike(value) {
      return !!value && typeof value == "object";
    }
    __name(isObjectLike, "isObjectLike");
    function isSymbol(value) {
      return typeof value == "symbol" || isObjectLike(value) && objectToString2.call(value) == symbolTag;
    }
    __name(isSymbol, "isSymbol");
    function toString(value) {
      return value == null ? "" : baseToString(value);
    }
    __name(toString, "toString");
    var camelCase3 = createCompounder(function(result, word, index) {
      word = word.toLowerCase();
      return result + (index ? capitalize(word) : word);
    });
    function capitalize(string) {
      return upperFirst(toString(string).toLowerCase());
    }
    __name(capitalize, "capitalize");
    function deburr(string) {
      string = toString(string);
      return string && string.replace(reLatin, deburrLetter).replace(reComboMark, "");
    }
    __name(deburr, "deburr");
    var upperFirst = createCaseFirst("toUpperCase");
    function words(string, pattern, guard) {
      string = toString(string);
      pattern = guard ? void 0 : pattern;
      if (pattern === void 0) {
        return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
      }
      return string.match(pattern) || [];
    }
    __name(words, "words");
    module2.exports = camelCase3;
  }
});

// node_modules/@protobufjs/aspromise/index.js
var require_aspromise = __commonJS({
  "node_modules/@protobufjs/aspromise/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = asPromise;
    function asPromise(fn, ctx) {
      var params = new Array(arguments.length - 1), offset = 0, index = 2, pending = true;
      while (index < arguments.length)
        params[offset++] = arguments[index++];
      return new Promise(/* @__PURE__ */ __name(function executor(resolve24, reject) {
        params[offset] = /* @__PURE__ */ __name(function callback(err) {
          if (pending) {
            pending = false;
            if (err)
              reject(err);
            else {
              var params2 = new Array(arguments.length - 1), offset2 = 0;
              while (offset2 < params2.length)
                params2[offset2++] = arguments[offset2];
              resolve24.apply(null, params2);
            }
          }
        }, "callback");
        try {
          fn.apply(ctx || null, params);
        } catch (err) {
          if (pending) {
            pending = false;
            reject(err);
          }
        }
      }, "executor"));
    }
    __name(asPromise, "asPromise");
  }
});

// node_modules/@protobufjs/base64/index.js
var require_base64 = __commonJS({
  "node_modules/@protobufjs/base64/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var base64 = exports2;
    base64.length = /* @__PURE__ */ __name(function length(string) {
      var p = string.length;
      if (!p)
        return 0;
      var n2 = 0;
      while (--p % 4 > 1 && string.charAt(p) === "=")
        ++n2;
      return Math.ceil(string.length * 3) / 4 - n2;
    }, "length");
    var b64 = new Array(64);
    var s64 = new Array(123);
    for (i = 0; i < 64; )
      s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;
    var i;
    base64.encode = /* @__PURE__ */ __name(function encode4(buffer, start, end) {
      var parts = null, chunk = [];
      var i2 = 0, j = 0, t2;
      while (start < end) {
        var b = buffer[start++];
        switch (j) {
          case 0:
            chunk[i2++] = b64[b >> 2];
            t2 = (b & 3) << 4;
            j = 1;
            break;
          case 1:
            chunk[i2++] = b64[t2 | b >> 4];
            t2 = (b & 15) << 2;
            j = 2;
            break;
          case 2:
            chunk[i2++] = b64[t2 | b >> 6];
            chunk[i2++] = b64[b & 63];
            j = 0;
            break;
        }
        if (i2 > 8191) {
          (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
          i2 = 0;
        }
      }
      if (j) {
        chunk[i2++] = b64[t2];
        chunk[i2++] = 61;
        if (j === 1)
          chunk[i2++] = 61;
      }
      if (parts) {
        if (i2)
          parts.push(String.fromCharCode.apply(String, chunk.slice(0, i2)));
        return parts.join("");
      }
      return String.fromCharCode.apply(String, chunk.slice(0, i2));
    }, "encode");
    var invalidEncoding = "invalid encoding";
    base64.decode = /* @__PURE__ */ __name(function decode2(string, buffer, offset) {
      var start = offset;
      var j = 0, t2;
      for (var i2 = 0; i2 < string.length; ) {
        var c3 = string.charCodeAt(i2++);
        if (c3 === 61 && j > 1)
          break;
        if ((c3 = s64[c3]) === void 0)
          throw Error(invalidEncoding);
        switch (j) {
          case 0:
            t2 = c3;
            j = 1;
            break;
          case 1:
            buffer[offset++] = t2 << 2 | (c3 & 48) >> 4;
            t2 = c3;
            j = 2;
            break;
          case 2:
            buffer[offset++] = (t2 & 15) << 4 | (c3 & 60) >> 2;
            t2 = c3;
            j = 3;
            break;
          case 3:
            buffer[offset++] = (t2 & 3) << 6 | c3;
            j = 0;
            break;
        }
      }
      if (j === 1)
        throw Error(invalidEncoding);
      return offset - start;
    }, "decode");
    base64.test = /* @__PURE__ */ __name(function test(string) {
      return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);
    }, "test");
  }
});

// node_modules/@protobufjs/eventemitter/index.js
var require_eventemitter = __commonJS({
  "node_modules/@protobufjs/eventemitter/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = EventEmitter10;
    function EventEmitter10() {
      this._listeners = {};
    }
    __name(EventEmitter10, "EventEmitter");
    EventEmitter10.prototype.on = /* @__PURE__ */ __name(function on(evt, fn, ctx) {
      (this._listeners[evt] || (this._listeners[evt] = [])).push({
        fn,
        ctx: ctx || this
      });
      return this;
    }, "on");
    EventEmitter10.prototype.off = /* @__PURE__ */ __name(function off(evt, fn) {
      if (evt === void 0)
        this._listeners = {};
      else {
        if (fn === void 0)
          this._listeners[evt] = [];
        else {
          var listeners = this._listeners[evt];
          for (var i = 0; i < listeners.length; )
            if (listeners[i].fn === fn)
              listeners.splice(i, 1);
            else
              ++i;
        }
      }
      return this;
    }, "off");
    EventEmitter10.prototype.emit = /* @__PURE__ */ __name(function emit(evt) {
      var listeners = this._listeners[evt];
      if (listeners) {
        var args = [], i = 1;
        for (; i < arguments.length; )
          args.push(arguments[i++]);
        for (i = 0; i < listeners.length; )
          listeners[i].fn.apply(listeners[i++].ctx, args);
      }
      return this;
    }, "emit");
  }
});

// node_modules/@protobufjs/float/index.js
var require_float = __commonJS({
  "node_modules/@protobufjs/float/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = factory(factory);
    function factory(exports3) {
      if (typeof Float32Array !== "undefined") (function() {
        var f32 = new Float32Array([-0]), f8b = new Uint8Array(f32.buffer), le = f8b[3] === 128;
        function writeFloat_f32_cpy(val, buf, pos2) {
          f32[0] = val;
          buf[pos2] = f8b[0];
          buf[pos2 + 1] = f8b[1];
          buf[pos2 + 2] = f8b[2];
          buf[pos2 + 3] = f8b[3];
        }
        __name(writeFloat_f32_cpy, "writeFloat_f32_cpy");
        function writeFloat_f32_rev(val, buf, pos2) {
          f32[0] = val;
          buf[pos2] = f8b[3];
          buf[pos2 + 1] = f8b[2];
          buf[pos2 + 2] = f8b[1];
          buf[pos2 + 3] = f8b[0];
        }
        __name(writeFloat_f32_rev, "writeFloat_f32_rev");
        exports3.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;
        exports3.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;
        function readFloat_f32_cpy(buf, pos2) {
          f8b[0] = buf[pos2];
          f8b[1] = buf[pos2 + 1];
          f8b[2] = buf[pos2 + 2];
          f8b[3] = buf[pos2 + 3];
          return f32[0];
        }
        __name(readFloat_f32_cpy, "readFloat_f32_cpy");
        function readFloat_f32_rev(buf, pos2) {
          f8b[3] = buf[pos2];
          f8b[2] = buf[pos2 + 1];
          f8b[1] = buf[pos2 + 2];
          f8b[0] = buf[pos2 + 3];
          return f32[0];
        }
        __name(readFloat_f32_rev, "readFloat_f32_rev");
        exports3.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;
        exports3.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;
      })();
      else (function() {
        function writeFloat_ieee754(writeUint, val, buf, pos2) {
          var sign = val < 0 ? 1 : 0;
          if (sign)
            val = -val;
          if (val === 0)
            writeUint(1 / val > 0 ? (
              /* positive */
              0
            ) : (
              /* negative 0 */
              2147483648
            ), buf, pos2);
          else if (isNaN(val))
            writeUint(2143289344, buf, pos2);
          else if (val > 34028234663852886e22)
            writeUint((sign << 31 | 2139095040) >>> 0, buf, pos2);
          else if (val < 11754943508222875e-54)
            writeUint((sign << 31 | Math.round(val / 1401298464324817e-60)) >>> 0, buf, pos2);
          else {
            var exponent = Math.floor(Math.log(val) / Math.LN2), mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;
            writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos2);
          }
        }
        __name(writeFloat_ieee754, "writeFloat_ieee754");
        exports3.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);
        exports3.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);
        function readFloat_ieee754(readUint, buf, pos2) {
          var uint = readUint(buf, pos2), sign = (uint >> 31) * 2 + 1, exponent = uint >>> 23 & 255, mantissa = uint & 8388607;
          return exponent === 255 ? mantissa ? NaN : sign * Infinity : exponent === 0 ? sign * 1401298464324817e-60 * mantissa : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);
        }
        __name(readFloat_ieee754, "readFloat_ieee754");
        exports3.readFloatLE = readFloat_ieee754.bind(null, readUintLE);
        exports3.readFloatBE = readFloat_ieee754.bind(null, readUintBE);
      })();
      if (typeof Float64Array !== "undefined") (function() {
        var f64 = new Float64Array([-0]), f8b = new Uint8Array(f64.buffer), le = f8b[7] === 128;
        function writeDouble_f64_cpy(val, buf, pos2) {
          f64[0] = val;
          buf[pos2] = f8b[0];
          buf[pos2 + 1] = f8b[1];
          buf[pos2 + 2] = f8b[2];
          buf[pos2 + 3] = f8b[3];
          buf[pos2 + 4] = f8b[4];
          buf[pos2 + 5] = f8b[5];
          buf[pos2 + 6] = f8b[6];
          buf[pos2 + 7] = f8b[7];
        }
        __name(writeDouble_f64_cpy, "writeDouble_f64_cpy");
        function writeDouble_f64_rev(val, buf, pos2) {
          f64[0] = val;
          buf[pos2] = f8b[7];
          buf[pos2 + 1] = f8b[6];
          buf[pos2 + 2] = f8b[5];
          buf[pos2 + 3] = f8b[4];
          buf[pos2 + 4] = f8b[3];
          buf[pos2 + 5] = f8b[2];
          buf[pos2 + 6] = f8b[1];
          buf[pos2 + 7] = f8b[0];
        }
        __name(writeDouble_f64_rev, "writeDouble_f64_rev");
        exports3.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;
        exports3.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;
        function readDouble_f64_cpy(buf, pos2) {
          f8b[0] = buf[pos2];
          f8b[1] = buf[pos2 + 1];
          f8b[2] = buf[pos2 + 2];
          f8b[3] = buf[pos2 + 3];
          f8b[4] = buf[pos2 + 4];
          f8b[5] = buf[pos2 + 5];
          f8b[6] = buf[pos2 + 6];
          f8b[7] = buf[pos2 + 7];
          return f64[0];
        }
        __name(readDouble_f64_cpy, "readDouble_f64_cpy");
        function readDouble_f64_rev(buf, pos2) {
          f8b[7] = buf[pos2];
          f8b[6] = buf[pos2 + 1];
          f8b[5] = buf[pos2 + 2];
          f8b[4] = buf[pos2 + 3];
          f8b[3] = buf[pos2 + 4];
          f8b[2] = buf[pos2 + 5];
          f8b[1] = buf[pos2 + 6];
          f8b[0] = buf[pos2 + 7];
          return f64[0];
        }
        __name(readDouble_f64_rev, "readDouble_f64_rev");
        exports3.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;
        exports3.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;
      })();
      else (function() {
        function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos2) {
          var sign = val < 0 ? 1 : 0;
          if (sign)
            val = -val;
          if (val === 0) {
            writeUint(0, buf, pos2 + off0);
            writeUint(1 / val > 0 ? (
              /* positive */
              0
            ) : (
              /* negative 0 */
              2147483648
            ), buf, pos2 + off1);
          } else if (isNaN(val)) {
            writeUint(0, buf, pos2 + off0);
            writeUint(2146959360, buf, pos2 + off1);
          } else if (val > 17976931348623157e292) {
            writeUint(0, buf, pos2 + off0);
            writeUint((sign << 31 | 2146435072) >>> 0, buf, pos2 + off1);
          } else {
            var mantissa;
            if (val < 22250738585072014e-324) {
              mantissa = val / 5e-324;
              writeUint(mantissa >>> 0, buf, pos2 + off0);
              writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos2 + off1);
            } else {
              var exponent = Math.floor(Math.log(val) / Math.LN2);
              if (exponent === 1024)
                exponent = 1023;
              mantissa = val * Math.pow(2, -exponent);
              writeUint(mantissa * 4503599627370496 >>> 0, buf, pos2 + off0);
              writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos2 + off1);
            }
          }
        }
        __name(writeDouble_ieee754, "writeDouble_ieee754");
        exports3.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);
        exports3.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);
        function readDouble_ieee754(readUint, off0, off1, buf, pos2) {
          var lo = readUint(buf, pos2 + off0), hi = readUint(buf, pos2 + off1);
          var sign = (hi >> 31) * 2 + 1, exponent = hi >>> 20 & 2047, mantissa = 4294967296 * (hi & 1048575) + lo;
          return exponent === 2047 ? mantissa ? NaN : sign * Infinity : exponent === 0 ? sign * 5e-324 * mantissa : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);
        }
        __name(readDouble_ieee754, "readDouble_ieee754");
        exports3.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);
        exports3.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);
      })();
      return exports3;
    }
    __name(factory, "factory");
    function writeUintLE(val, buf, pos2) {
      buf[pos2] = val & 255;
      buf[pos2 + 1] = val >>> 8 & 255;
      buf[pos2 + 2] = val >>> 16 & 255;
      buf[pos2 + 3] = val >>> 24;
    }
    __name(writeUintLE, "writeUintLE");
    function writeUintBE(val, buf, pos2) {
      buf[pos2] = val >>> 24;
      buf[pos2 + 1] = val >>> 16 & 255;
      buf[pos2 + 2] = val >>> 8 & 255;
      buf[pos2 + 3] = val & 255;
    }
    __name(writeUintBE, "writeUintBE");
    function readUintLE(buf, pos2) {
      return (buf[pos2] | buf[pos2 + 1] << 8 | buf[pos2 + 2] << 16 | buf[pos2 + 3] << 24) >>> 0;
    }
    __name(readUintLE, "readUintLE");
    function readUintBE(buf, pos2) {
      return (buf[pos2] << 24 | buf[pos2 + 1] << 16 | buf[pos2 + 2] << 8 | buf[pos2 + 3]) >>> 0;
    }
    __name(readUintBE, "readUintBE");
  }
});

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

// node_modules/@protobufjs/utf8/index.js
var require_utf8 = __commonJS({
  "node_modules/@protobufjs/utf8/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var utf8 = exports2;
    utf8.length = /* @__PURE__ */ __name(function utf8_length(string) {
      var len = 0, c3 = 0;
      for (var i = 0; i < string.length; ++i) {
        c3 = string.charCodeAt(i);
        if (c3 < 128)
          len += 1;
        else if (c3 < 2048)
          len += 2;
        else if ((c3 & 64512) === 55296 && (string.charCodeAt(i + 1) & 64512) === 56320) {
          ++i;
          len += 4;
        } else
          len += 3;
      }
      return len;
    }, "utf8_length");
    utf8.read = /* @__PURE__ */ __name(function utf8_read(buffer, start, end) {
      var len = end - start;
      if (len < 1)
        return "";
      var parts = null, chunk = [], i = 0, t2;
      while (start < end) {
        t2 = buffer[start++];
        if (t2 < 128)
          chunk[i++] = t2;
        else if (t2 > 191 && t2 < 224)
          chunk[i++] = (t2 & 31) << 6 | buffer[start++] & 63;
        else if (t2 > 239 && t2 < 365) {
          t2 = ((t2 & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 65536;
          chunk[i++] = 55296 + (t2 >> 10);
          chunk[i++] = 56320 + (t2 & 1023);
        } else
          chunk[i++] = (t2 & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;
        if (i > 8191) {
          (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
          i = 0;
        }
      }
      if (parts) {
        if (i)
          parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
        return parts.join("");
      }
      return String.fromCharCode.apply(String, chunk.slice(0, i));
    }, "utf8_read");
    utf8.write = /* @__PURE__ */ __name(function utf8_write(string, buffer, offset) {
      var start = offset, c1, c22;
      for (var i = 0; i < string.length; ++i) {
        c1 = string.charCodeAt(i);
        if (c1 < 128) {
          buffer[offset++] = c1;
        } else if (c1 < 2048) {
          buffer[offset++] = c1 >> 6 | 192;
          buffer[offset++] = c1 & 63 | 128;
        } else if ((c1 & 64512) === 55296 && ((c22 = string.charCodeAt(i + 1)) & 64512) === 56320) {
          c1 = 65536 + ((c1 & 1023) << 10) + (c22 & 1023);
          ++i;
          buffer[offset++] = c1 >> 18 | 240;
          buffer[offset++] = c1 >> 12 & 63 | 128;
          buffer[offset++] = c1 >> 6 & 63 | 128;
          buffer[offset++] = c1 & 63 | 128;
        } else {
          buffer[offset++] = c1 >> 12 | 224;
          buffer[offset++] = c1 >> 6 & 63 | 128;
          buffer[offset++] = c1 & 63 | 128;
        }
      }
      return offset - start;
    }, "utf8_write");
  }
});

// node_modules/@protobufjs/pool/index.js
var require_pool2 = __commonJS({
  "node_modules/@protobufjs/pool/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = pool;
    function pool(alloc, slice, size) {
      var SIZE = size || 8192;
      var MAX2 = SIZE >>> 1;
      var slab2 = null;
      var offset = SIZE;
      return /* @__PURE__ */ __name(function pool_alloc(size2) {
        if (size2 < 1 || size2 > MAX2)
          return alloc(size2);
        if (offset + size2 > SIZE) {
          slab2 = alloc(SIZE);
          offset = 0;
        }
        var buf = slice.call(slab2, offset, offset += size2);
        if (offset & 7)
          offset = (offset | 7) + 1;
        return buf;
      }, "pool_alloc");
    }
    __name(pool, "pool");
  }
});

// node_modules/protobufjs/src/util/longbits.js
var require_longbits = __commonJS({
  "node_modules/protobufjs/src/util/longbits.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = LongBits;
    var util4 = require_minimal();
    function LongBits(lo, hi) {
      this.lo = lo >>> 0;
      this.hi = hi >>> 0;
    }
    __name(LongBits, "LongBits");
    var zero = LongBits.zero = new LongBits(0, 0);
    zero.toNumber = function() {
      return 0;
    };
    zero.zzEncode = zero.zzDecode = function() {
      return this;
    };
    zero.length = function() {
      return 1;
    };
    var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0";
    LongBits.fromNumber = /* @__PURE__ */ __name(function fromNumber(value) {
      if (value === 0)
        return zero;
      var sign = value < 0;
      if (sign)
        value = -value;
      var lo = value >>> 0, hi = (value - lo) / 4294967296 >>> 0;
      if (sign) {
        hi = ~hi >>> 0;
        lo = ~lo >>> 0;
        if (++lo > 4294967295) {
          lo = 0;
          if (++hi > 4294967295)
            hi = 0;
        }
      }
      return new LongBits(lo, hi);
    }, "fromNumber");
    LongBits.from = /* @__PURE__ */ __name(function from(value) {
      if (typeof value === "number")
        return LongBits.fromNumber(value);
      if (util4.isString(value)) {
        if (util4.Long)
          value = util4.Long.fromString(value);
        else
          return LongBits.fromNumber(parseInt(value, 10));
      }
      return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;
    }, "from");
    LongBits.prototype.toNumber = /* @__PURE__ */ __name(function toNumber2(unsigned) {
      if (!unsigned && this.hi >>> 31) {
        var lo = ~this.lo + 1 >>> 0, hi = ~this.hi >>> 0;
        if (!lo)
          hi = hi + 1 >>> 0;
        return -(lo + hi * 4294967296);
      }
      return this.lo + this.hi * 4294967296;
    }, "toNumber");
    LongBits.prototype.toLong = /* @__PURE__ */ __name(function toLong(unsigned) {
      return util4.Long ? new util4.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };
    }, "toLong");
    var charCodeAt = String.prototype.charCodeAt;
    LongBits.fromHash = /* @__PURE__ */ __name(function fromHash(hash) {
      if (hash === zeroHash)
        return zero;
      return new LongBits(
        (charCodeAt.call(hash, 0) | charCodeAt.call(hash, 1) << 8 | charCodeAt.call(hash, 2) << 16 | charCodeAt.call(hash, 3) << 24) >>> 0,
        (charCodeAt.call(hash, 4) | charCodeAt.call(hash, 5) << 8 | charCodeAt.call(hash, 6) << 16 | charCodeAt.call(hash, 7) << 24) >>> 0
      );
    }, "fromHash");
    LongBits.prototype.toHash = /* @__PURE__ */ __name(function toHash() {
      return String.fromCharCode(
        this.lo & 255,
        this.lo >>> 8 & 255,
        this.lo >>> 16 & 255,
        this.lo >>> 24,
        this.hi & 255,
        this.hi >>> 8 & 255,
        this.hi >>> 16 & 255,
        this.hi >>> 24
      );
    }, "toHash");
    LongBits.prototype.zzEncode = /* @__PURE__ */ __name(function zzEncode() {
      var mask = this.hi >> 31;
      this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;
      this.lo = (this.lo << 1 ^ mask) >>> 0;
      return this;
    }, "zzEncode");
    LongBits.prototype.zzDecode = /* @__PURE__ */ __name(function zzDecode() {
      var mask = -(this.lo & 1);
      this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;
      this.hi = (this.hi >>> 1 ^ mask) >>> 0;
      return this;
    }, "zzDecode");
    LongBits.prototype.length = /* @__PURE__ */ __name(function length() {
      var part0 = this.lo, part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, part2 = this.hi >>> 24;
      return part2 === 0 ? part1 === 0 ? part0 < 16384 ? part0 < 128 ? 1 : 2 : part0 < 2097152 ? 3 : 4 : part1 < 16384 ? part1 < 128 ? 5 : 6 : part1 < 2097152 ? 7 : 8 : part2 < 128 ? 9 : 10;
    }, "length");
  }
});

// node_modules/protobufjs/src/util/minimal.js
var require_minimal = __commonJS({
  "node_modules/protobufjs/src/util/minimal.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var util4 = exports2;
    util4.asPromise = require_aspromise();
    util4.base64 = require_base64();
    util4.EventEmitter = require_eventemitter();
    util4.float = require_float();
    util4.inquire = require_inquire();
    util4.utf8 = require_utf8();
    util4.pool = require_pool2();
    util4.LongBits = require_longbits();
    util4.isNode = Boolean(typeof globalThis !== "undefined" && globalThis && globalThis.process && globalThis.process.versions && globalThis.process.versions.node);
    util4.global = util4.isNode && globalThis || typeof window !== "undefined" && window || typeof self !== "undefined" && self || exports2;
    util4.emptyArray = Object.freeze ? Object.freeze([]) : (
      /* istanbul ignore next */
      []
    );
    util4.emptyObject = Object.freeze ? Object.freeze({}) : (
      /* istanbul ignore next */
      {}
    );
    util4.isInteger = Number.isInteger || /* istanbul ignore next */
    /* @__PURE__ */ __name(function isInteger2(value) {
      return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
    }, "isInteger");
    util4.isString = /* @__PURE__ */ __name(function isString2(value) {
      return typeof value === "string" || value instanceof String;
    }, "isString");
    util4.isObject = /* @__PURE__ */ __name(function isObject3(value) {
      return value && typeof value === "object";
    }, "isObject");
    util4.isset = /**
     * Checks if a property on a message is considered to be present.
     * @param {Object} obj Plain object or message instance
     * @param {string} prop Property name
     * @returns {boolean} `true` if considered to be present, otherwise `false`
     */
    util4.isSet = /* @__PURE__ */ __name(function isSet(obj, prop) {
      var value = obj[prop];
      if (value != null && obj.hasOwnProperty(prop))
        return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;
      return false;
    }, "isSet");
    util4.Buffer = function() {
      try {
        var Buffer5 = util4.inquire("buffer").Buffer;
        return Buffer5.prototype.utf8Write ? Buffer5 : (
          /* istanbul ignore next */
          null
        );
      } catch (e2) {
        return null;
      }
    }();
    util4._Buffer_from = null;
    util4._Buffer_allocUnsafe = null;
    util4.newBuffer = /* @__PURE__ */ __name(function newBuffer(sizeOrArray) {
      return typeof sizeOrArray === "number" ? util4.Buffer ? util4._Buffer_allocUnsafe(sizeOrArray) : new util4.Array(sizeOrArray) : util4.Buffer ? util4._Buffer_from(sizeOrArray) : typeof Uint8Array === "undefined" ? sizeOrArray : new Uint8Array(sizeOrArray);
    }, "newBuffer");
    util4.Array = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
    util4.Long = /* istanbul ignore next */
    util4.global.dcodeIO && /* istanbul ignore next */
    util4.global.dcodeIO.Long || /* istanbul ignore next */
    util4.global.Long || util4.inquire("long");
    util4.key2Re = /^true|false|0|1$/;
    util4.key32Re = /^-?(?:0|[1-9][0-9]*)$/;
    util4.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;
    util4.longToHash = /* @__PURE__ */ __name(function longToHash(value) {
      return value ? util4.LongBits.from(value).toHash() : util4.LongBits.zeroHash;
    }, "longToHash");
    util4.longFromHash = /* @__PURE__ */ __name(function longFromHash(hash, unsigned) {
      var bits = util4.LongBits.fromHash(hash);
      if (util4.Long)
        return util4.Long.fromBits(bits.lo, bits.hi, unsigned);
      return bits.toNumber(Boolean(unsigned));
    }, "longFromHash");
    function merge3(dst, src, ifNotSet) {
      for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)
        if (dst[keys[i]] === void 0 || !ifNotSet)
          dst[keys[i]] = src[keys[i]];
      return dst;
    }
    __name(merge3, "merge");
    util4.merge = merge3;
    util4.lcFirst = /* @__PURE__ */ __name(function lcFirst(str2) {
      return str2.charAt(0).toLowerCase() + str2.substring(1);
    }, "lcFirst");
    function newError(name3) {
      function CustomError(message, properties) {
        if (!(this instanceof CustomError))
          return new CustomError(message, properties);
        Object.defineProperty(this, "message", { get: /* @__PURE__ */ __name(function() {
          return message;
        }, "get") });
        if (Error.captureStackTrace)
          Error.captureStackTrace(this, CustomError);
        else
          Object.defineProperty(this, "stack", { value: new Error().stack || "" });
        if (properties)
          merge3(this, properties);
      }
      __name(CustomError, "CustomError");
      CustomError.prototype = Object.create(Error.prototype, {
        constructor: {
          value: CustomError,
          writable: true,
          enumerable: false,
          configurable: true
        },
        name: {
          get: /* @__PURE__ */ __name(function get3() {
            return name3;
          }, "get"),
          set: void 0,
          enumerable: false,
          // configurable: false would accurately preserve the behavior of
          // the original, but I'm guessing that was not intentional.
          // For an actual error subclass, this property would
          // be configurable.
          configurable: true
        },
        toString: {
          value: /* @__PURE__ */ __name(function value() {
            return this.name + ": " + this.message;
          }, "value"),
          writable: true,
          enumerable: false,
          configurable: true
        }
      });
      return CustomError;
    }
    __name(newError, "newError");
    util4.newError = newError;
    util4.ProtocolError = newError("ProtocolError");
    util4.oneOfGetter = /* @__PURE__ */ __name(function getOneOf(fieldNames) {
      var fieldMap = {};
      for (var i = 0; i < fieldNames.length; ++i)
        fieldMap[fieldNames[i]] = 1;
      return function() {
        for (var keys = Object.keys(this), i2 = keys.length - 1; i2 > -1; --i2)
          if (fieldMap[keys[i2]] === 1 && this[keys[i2]] !== void 0 && this[keys[i2]] !== null)
            return keys[i2];
      };
    }, "getOneOf");
    util4.oneOfSetter = /* @__PURE__ */ __name(function setOneOf(fieldNames) {
      return function(name3) {
        for (var i = 0; i < fieldNames.length; ++i)
          if (fieldNames[i] !== name3)
            delete this[fieldNames[i]];
      };
    }, "setOneOf");
    util4.toJSONOptions = {
      longs: String,
      enums: String,
      bytes: String,
      json: true
    };
    util4._configure = function() {
      var Buffer5 = util4.Buffer;
      if (!Buffer5) {
        util4._Buffer_from = util4._Buffer_allocUnsafe = null;
        return;
      }
      util4._Buffer_from = Buffer5.from !== Uint8Array.from && Buffer5.from || /* istanbul ignore next */
      /* @__PURE__ */ __name(function Buffer_from(value, encoding) {
        return new Buffer5(value, encoding);
      }, "Buffer_from");
      util4._Buffer_allocUnsafe = Buffer5.allocUnsafe || /* istanbul ignore next */
      /* @__PURE__ */ __name(function Buffer_allocUnsafe(size) {
        return new Buffer5(size);
      }, "Buffer_allocUnsafe");
    };
  }
});

// node_modules/protobufjs/src/writer.js
var require_writer = __commonJS({
  "node_modules/protobufjs/src/writer.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Writer;
    var util4 = require_minimal();
    var BufferWriter;
    var LongBits = util4.LongBits;
    var base64 = util4.base64;
    var utf8 = util4.utf8;
    function Op(fn, len, val) {
      this.fn = fn;
      this.len = len;
      this.next = void 0;
      this.val = val;
    }
    __name(Op, "Op");
    function noop6() {
    }
    __name(noop6, "noop");
    function State2(writer) {
      this.head = writer.head;
      this.tail = writer.tail;
      this.len = writer.len;
      this.next = writer.states;
    }
    __name(State2, "State");
    function Writer() {
      this.len = 0;
      this.head = new Op(noop6, 0, 0);
      this.tail = this.head;
      this.states = null;
    }
    __name(Writer, "Writer");
    var create3 = /* @__PURE__ */ __name(function create4() {
      return util4.Buffer ? /* @__PURE__ */ __name(function create_buffer_setup() {
        return (Writer.create = /* @__PURE__ */ __name(function create_buffer() {
          return new BufferWriter();
        }, "create_buffer"))();
      }, "create_buffer_setup") : /* @__PURE__ */ __name(function create_array() {
        return new Writer();
      }, "create_array");
    }, "create");
    Writer.create = create3();
    Writer.alloc = /* @__PURE__ */ __name(function alloc(size) {
      return new util4.Array(size);
    }, "alloc");
    if (util4.Array !== Array)
      Writer.alloc = util4.pool(Writer.alloc, util4.Array.prototype.subarray);
    Writer.prototype._push = /* @__PURE__ */ __name(function push2(fn, len, val) {
      this.tail = this.tail.next = new Op(fn, len, val);
      this.len += len;
      return this;
    }, "push");
    function writeByte(val, buf, pos2) {
      buf[pos2] = val & 255;
    }
    __name(writeByte, "writeByte");
    function writeVarint32(val, buf, pos2) {
      while (val > 127) {
        buf[pos2++] = val & 127 | 128;
        val >>>= 7;
      }
      buf[pos2] = val;
    }
    __name(writeVarint32, "writeVarint32");
    function VarintOp(len, val) {
      this.len = len;
      this.next = void 0;
      this.val = val;
    }
    __name(VarintOp, "VarintOp");
    VarintOp.prototype = Object.create(Op.prototype);
    VarintOp.prototype.fn = writeVarint32;
    Writer.prototype.uint32 = /* @__PURE__ */ __name(function write_uint32(value) {
      this.len += (this.tail = this.tail.next = new VarintOp(
        (value = value >>> 0) < 128 ? 1 : value < 16384 ? 2 : value < 2097152 ? 3 : value < 268435456 ? 4 : 5,
        value
      )).len;
      return this;
    }, "write_uint32");
    Writer.prototype.int32 = /* @__PURE__ */ __name(function write_int32(value) {
      return value < 0 ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) : this.uint32(value);
    }, "write_int32");
    Writer.prototype.sint32 = /* @__PURE__ */ __name(function write_sint32(value) {
      return this.uint32((value << 1 ^ value >> 31) >>> 0);
    }, "write_sint32");
    function writeVarint64(val, buf, pos2) {
      while (val.hi) {
        buf[pos2++] = val.lo & 127 | 128;
        val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;
        val.hi >>>= 7;
      }
      while (val.lo > 127) {
        buf[pos2++] = val.lo & 127 | 128;
        val.lo = val.lo >>> 7;
      }
      buf[pos2++] = val.lo;
    }
    __name(writeVarint64, "writeVarint64");
    Writer.prototype.uint64 = /* @__PURE__ */ __name(function write_uint64(value) {
      var bits = LongBits.from(value);
      return this._push(writeVarint64, bits.length(), bits);
    }, "write_uint64");
    Writer.prototype.int64 = Writer.prototype.uint64;
    Writer.prototype.sint64 = /* @__PURE__ */ __name(function write_sint64(value) {
      var bits = LongBits.from(value).zzEncode();
      return this._push(writeVarint64, bits.length(), bits);
    }, "write_sint64");
    Writer.prototype.bool = /* @__PURE__ */ __name(function write_bool(value) {
      return this._push(writeByte, 1, value ? 1 : 0);
    }, "write_bool");
    function writeFixed32(val, buf, pos2) {
      buf[pos2] = val & 255;
      buf[pos2 + 1] = val >>> 8 & 255;
      buf[pos2 + 2] = val >>> 16 & 255;
      buf[pos2 + 3] = val >>> 24;
    }
    __name(writeFixed32, "writeFixed32");
    Writer.prototype.fixed32 = /* @__PURE__ */ __name(function write_fixed32(value) {
      return this._push(writeFixed32, 4, value >>> 0);
    }, "write_fixed32");
    Writer.prototype.sfixed32 = Writer.prototype.fixed32;
    Writer.prototype.fixed64 = /* @__PURE__ */ __name(function write_fixed64(value) {
      var bits = LongBits.from(value);
      return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);
    }, "write_fixed64");
    Writer.prototype.sfixed64 = Writer.prototype.fixed64;
    Writer.prototype.float = /* @__PURE__ */ __name(function write_float(value) {
      return this._push(util4.float.writeFloatLE, 4, value);
    }, "write_float");
    Writer.prototype.double = /* @__PURE__ */ __name(function write_double(value) {
      return this._push(util4.float.writeDoubleLE, 8, value);
    }, "write_double");
    var writeBytes = util4.Array.prototype.set ? /* @__PURE__ */ __name(function writeBytes_set(val, buf, pos2) {
      buf.set(val, pos2);
    }, "writeBytes_set") : /* @__PURE__ */ __name(function writeBytes_for(val, buf, pos2) {
      for (var i = 0; i < val.length; ++i)
        buf[pos2 + i] = val[i];
    }, "writeBytes_for");
    Writer.prototype.bytes = /* @__PURE__ */ __name(function write_bytes(value) {
      var len = value.length >>> 0;
      if (!len)
        return this._push(writeByte, 1, 0);
      if (util4.isString(value)) {
        var buf = Writer.alloc(len = base64.length(value));
        base64.decode(value, buf, 0);
        value = buf;
      }
      return this.uint32(len)._push(writeBytes, len, value);
    }, "write_bytes");
    Writer.prototype.string = /* @__PURE__ */ __name(function write_string(value) {
      var len = utf8.length(value);
      return len ? this.uint32(len)._push(utf8.write, len, value) : this._push(writeByte, 1, 0);
    }, "write_string");
    Writer.prototype.fork = /* @__PURE__ */ __name(function fork() {
      this.states = new State2(this);
      this.head = this.tail = new Op(noop6, 0, 0);
      this.len = 0;
      return this;
    }, "fork");
    Writer.prototype.reset = /* @__PURE__ */ __name(function reset() {
      if (this.states) {
        this.head = this.states.head;
        this.tail = this.states.tail;
        this.len = this.states.len;
        this.states = this.states.next;
      } else {
        this.head = this.tail = new Op(noop6, 0, 0);
        this.len = 0;
      }
      return this;
    }, "reset");
    Writer.prototype.ldelim = /* @__PURE__ */ __name(function ldelim() {
      var head = this.head, tail = this.tail, len = this.len;
      this.reset().uint32(len);
      if (len) {
        this.tail.next = head.next;
        this.tail = tail;
        this.len += len;
      }
      return this;
    }, "ldelim");
    Writer.prototype.finish = /* @__PURE__ */ __name(function finish() {
      var head = this.head.next, buf = this.constructor.alloc(this.len), pos2 = 0;
      while (head) {
        head.fn(head.val, buf, pos2);
        pos2 += head.len;
        head = head.next;
      }
      return buf;
    }, "finish");
    Writer._configure = function(BufferWriter_) {
      BufferWriter = BufferWriter_;
      Writer.create = create3();
      BufferWriter._configure();
    };
  }
});

// node_modules/protobufjs/src/writer_buffer.js
var require_writer_buffer = __commonJS({
  "node_modules/protobufjs/src/writer_buffer.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = BufferWriter;
    var Writer = require_writer();
    (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;
    var util4 = require_minimal();
    function BufferWriter() {
      Writer.call(this);
    }
    __name(BufferWriter, "BufferWriter");
    BufferWriter._configure = function() {
      BufferWriter.alloc = util4._Buffer_allocUnsafe;
      BufferWriter.writeBytesBuffer = util4.Buffer && util4.Buffer.prototype instanceof Uint8Array && util4.Buffer.prototype.set.name === "set" ? /* @__PURE__ */ __name(function writeBytesBuffer_set(val, buf, pos2) {
        buf.set(val, pos2);
      }, "writeBytesBuffer_set") : /* @__PURE__ */ __name(function writeBytesBuffer_copy(val, buf, pos2) {
        if (val.copy)
          val.copy(buf, pos2, 0, val.length);
        else for (var i = 0; i < val.length; )
          buf[pos2++] = val[i++];
      }, "writeBytesBuffer_copy");
    };
    BufferWriter.prototype.bytes = /* @__PURE__ */ __name(function write_bytes_buffer(value) {
      if (util4.isString(value))
        value = util4._Buffer_from(value, "base64");
      var len = value.length >>> 0;
      this.uint32(len);
      if (len)
        this._push(BufferWriter.writeBytesBuffer, len, value);
      return this;
    }, "write_bytes_buffer");
    function writeStringBuffer(val, buf, pos2) {
      if (val.length < 40)
        util4.utf8.write(val, buf, pos2);
      else if (buf.utf8Write)
        buf.utf8Write(val, pos2);
      else
        buf.write(val, pos2);
    }
    __name(writeStringBuffer, "writeStringBuffer");
    BufferWriter.prototype.string = /* @__PURE__ */ __name(function write_string_buffer(value) {
      var len = util4.Buffer.byteLength(value);
      this.uint32(len);
      if (len)
        this._push(writeStringBuffer, len, value);
      return this;
    }, "write_string_buffer");
    BufferWriter._configure();
  }
});

// node_modules/protobufjs/src/reader.js
var require_reader = __commonJS({
  "node_modules/protobufjs/src/reader.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Reader;
    var util4 = require_minimal();
    var BufferReader;
    var LongBits = util4.LongBits;
    var utf8 = util4.utf8;
    function indexOutOfRange(reader, writeLength) {
      return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len);
    }
    __name(indexOutOfRange, "indexOutOfRange");
    function Reader(buffer) {
      this.buf = buffer;
      this.pos = 0;
      this.len = buffer.length;
    }
    __name(Reader, "Reader");
    var create_array = typeof Uint8Array !== "undefined" ? /* @__PURE__ */ __name(function create_typed_array(buffer) {
      if (buffer instanceof Uint8Array || Array.isArray(buffer))
        return new Reader(buffer);
      throw Error("illegal buffer");
    }, "create_typed_array") : /* @__PURE__ */ __name(function create_array2(buffer) {
      if (Array.isArray(buffer))
        return new Reader(buffer);
      throw Error("illegal buffer");
    }, "create_array");
    var create3 = /* @__PURE__ */ __name(function create4() {
      return util4.Buffer ? /* @__PURE__ */ __name(function create_buffer_setup(buffer) {
        return (Reader.create = /* @__PURE__ */ __name(function create_buffer(buffer2) {
          return util4.Buffer.isBuffer(buffer2) ? new BufferReader(buffer2) : create_array(buffer2);
        }, "create_buffer"))(buffer);
      }, "create_buffer_setup") : create_array;
    }, "create");
    Reader.create = create3();
    Reader.prototype._slice = util4.Array.prototype.subarray || /* istanbul ignore next */
    util4.Array.prototype.slice;
    Reader.prototype.uint32 = (/* @__PURE__ */ __name(function read_uint32_setup() {
      var value = 4294967295;
      return /* @__PURE__ */ __name(function read_uint32() {
        value = (this.buf[this.pos] & 127) >>> 0;
        if (this.buf[this.pos++] < 128) return value;
        value = (value | (this.buf[this.pos] & 127) << 7) >>> 0;
        if (this.buf[this.pos++] < 128) return value;
        value = (value | (this.buf[this.pos] & 127) << 14) >>> 0;
        if (this.buf[this.pos++] < 128) return value;
        value = (value | (this.buf[this.pos] & 127) << 21) >>> 0;
        if (this.buf[this.pos++] < 128) return value;
        value = (value | (this.buf[this.pos] & 15) << 28) >>> 0;
        if (this.buf[this.pos++] < 128) return value;
        if ((this.pos += 5) > this.len) {
          this.pos = this.len;
          throw indexOutOfRange(this, 10);
        }
        return value;
      }, "read_uint32");
    }, "read_uint32_setup"))();
    Reader.prototype.int32 = /* @__PURE__ */ __name(function read_int32() {
      return this.uint32() | 0;
    }, "read_int32");
    Reader.prototype.sint32 = /* @__PURE__ */ __name(function read_sint32() {
      var value = this.uint32();
      return value >>> 1 ^ -(value & 1) | 0;
    }, "read_sint32");
    function readLongVarint() {
      var bits = new LongBits(0, 0);
      var i = 0;
      if (this.len - this.pos > 4) {
        for (; i < 4; ++i) {
          bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
          if (this.buf[this.pos++] < 128)
            return bits;
        }
        bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;
        bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;
        if (this.buf[this.pos++] < 128)
          return bits;
        i = 0;
      } else {
        for (; i < 3; ++i) {
          if (this.pos >= this.len)
            throw indexOutOfRange(this);
          bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
          if (this.buf[this.pos++] < 128)
            return bits;
        }
        bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;
        return bits;
      }
      if (this.len - this.pos > 4) {
        for (; i < 5; ++i) {
          bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
          if (this.buf[this.pos++] < 128)
            return bits;
        }
      } else {
        for (; i < 5; ++i) {
          if (this.pos >= this.len)
            throw indexOutOfRange(this);
          bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
          if (this.buf[this.pos++] < 128)
            return bits;
        }
      }
      throw Error("invalid varint encoding");
    }
    __name(readLongVarint, "readLongVarint");
    Reader.prototype.bool = /* @__PURE__ */ __name(function read_bool() {
      return this.uint32() !== 0;
    }, "read_bool");
    function readFixed32_end(buf, end) {
      return (buf[end - 4] | buf[end - 3] << 8 | buf[end - 2] << 16 | buf[end - 1] << 24) >>> 0;
    }
    __name(readFixed32_end, "readFixed32_end");
    Reader.prototype.fixed32 = /* @__PURE__ */ __name(function read_fixed32() {
      if (this.pos + 4 > this.len)
        throw indexOutOfRange(this, 4);
      return readFixed32_end(this.buf, this.pos += 4);
    }, "read_fixed32");
    Reader.prototype.sfixed32 = /* @__PURE__ */ __name(function read_sfixed32() {
      if (this.pos + 4 > this.len)
        throw indexOutOfRange(this, 4);
      return readFixed32_end(this.buf, this.pos += 4) | 0;
    }, "read_sfixed32");
    function readFixed64() {
      if (this.pos + 8 > this.len)
        throw indexOutOfRange(this, 8);
      return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));
    }
    __name(readFixed64, "readFixed64");
    Reader.prototype.float = /* @__PURE__ */ __name(function read_float() {
      if (this.pos + 4 > this.len)
        throw indexOutOfRange(this, 4);
      var value = util4.float.readFloatLE(this.buf, this.pos);
      this.pos += 4;
      return value;
    }, "read_float");
    Reader.prototype.double = /* @__PURE__ */ __name(function read_double() {
      if (this.pos + 8 > this.len)
        throw indexOutOfRange(this, 4);
      var value = util4.float.readDoubleLE(this.buf, this.pos);
      this.pos += 8;
      return value;
    }, "read_double");
    Reader.prototype.bytes = /* @__PURE__ */ __name(function read_bytes() {
      var length = this.uint32(), start = this.pos, end = this.pos + length;
      if (end > this.len)
        throw indexOutOfRange(this, length);
      this.pos += length;
      if (Array.isArray(this.buf))
        return this.buf.slice(start, end);
      if (start === end) {
        var nativeBuffer = util4.Buffer;
        return nativeBuffer ? nativeBuffer.alloc(0) : new this.buf.constructor(0);
      }
      return this._slice.call(this.buf, start, end);
    }, "read_bytes");
    Reader.prototype.string = /* @__PURE__ */ __name(function read_string() {
      var bytes = this.bytes();
      return utf8.read(bytes, 0, bytes.length);
    }, "read_string");
    Reader.prototype.skip = /* @__PURE__ */ __name(function skip(length) {
      if (typeof length === "number") {
        if (this.pos + length > this.len)
          throw indexOutOfRange(this, length);
        this.pos += length;
      } else {
        do {
          if (this.pos >= this.len)
            throw indexOutOfRange(this);
        } while (this.buf[this.pos++] & 128);
      }
      return this;
    }, "skip");
    Reader.prototype.skipType = function(wireType) {
      switch (wireType) {
        case 0:
          this.skip();
          break;
        case 1:
          this.skip(8);
          break;
        case 2:
          this.skip(this.uint32());
          break;
        case 3:
          while ((wireType = this.uint32() & 7) !== 4) {
            this.skipType(wireType);
          }
          break;
        case 5:
          this.skip(4);
          break;
        /* istanbul ignore next */
        default:
          throw Error("invalid wire type " + wireType + " at offset " + this.pos);
      }
      return this;
    };
    Reader._configure = function(BufferReader_) {
      BufferReader = BufferReader_;
      Reader.create = create3();
      BufferReader._configure();
      var fn = util4.Long ? "toLong" : (
        /* istanbul ignore next */
        "toNumber"
      );
      util4.merge(Reader.prototype, {
        int64: /* @__PURE__ */ __name(function read_int64() {
          return readLongVarint.call(this)[fn](false);
        }, "read_int64"),
        uint64: /* @__PURE__ */ __name(function read_uint64() {
          return readLongVarint.call(this)[fn](true);
        }, "read_uint64"),
        sint64: /* @__PURE__ */ __name(function read_sint64() {
          return readLongVarint.call(this).zzDecode()[fn](false);
        }, "read_sint64"),
        fixed64: /* @__PURE__ */ __name(function read_fixed64() {
          return readFixed64.call(this)[fn](true);
        }, "read_fixed64"),
        sfixed64: /* @__PURE__ */ __name(function read_sfixed64() {
          return readFixed64.call(this)[fn](false);
        }, "read_sfixed64")
      });
    };
  }
});

// node_modules/protobufjs/src/reader_buffer.js
var require_reader_buffer = __commonJS({
  "node_modules/protobufjs/src/reader_buffer.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = BufferReader;
    var Reader = require_reader();
    (BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;
    var util4 = require_minimal();
    function BufferReader(buffer) {
      Reader.call(this, buffer);
    }
    __name(BufferReader, "BufferReader");
    BufferReader._configure = function() {
      if (util4.Buffer)
        BufferReader.prototype._slice = util4.Buffer.prototype.slice;
    };
    BufferReader.prototype.string = /* @__PURE__ */ __name(function read_string_buffer() {
      var len = this.uint32();
      return this.buf.utf8Slice ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len));
    }, "read_string_buffer");
    BufferReader._configure();
  }
});

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

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

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

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

// node_modules/@protobufjs/codegen/index.js
var require_codegen3 = __commonJS({
  "node_modules/@protobufjs/codegen/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = codegen;
    function codegen(functionParams, functionName) {
      if (typeof functionParams === "string") {
        functionName = functionParams;
        functionParams = void 0;
      }
      var body = [];
      function Codegen(formatStringOrScope) {
        if (typeof formatStringOrScope !== "string") {
          var source2 = toString();
          if (codegen.verbose)
            console.log("codegen: " + source2);
          source2 = "return " + source2;
          if (formatStringOrScope) {
            var scopeKeys = Object.keys(formatStringOrScope), scopeParams = new Array(scopeKeys.length + 1), scopeValues = new Array(scopeKeys.length), scopeOffset = 0;
            while (scopeOffset < scopeKeys.length) {
              scopeParams[scopeOffset] = scopeKeys[scopeOffset];
              scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];
            }
            scopeParams[scopeOffset] = source2;
            return Function.apply(null, scopeParams).apply(null, scopeValues);
          }
          return Function(source2)();
        }
        var formatParams = new Array(arguments.length - 1), formatOffset = 0;
        while (formatOffset < formatParams.length)
          formatParams[formatOffset] = arguments[++formatOffset];
        formatOffset = 0;
        formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, /* @__PURE__ */ __name(function replace2($0, $1) {
          var value = formatParams[formatOffset++];
          switch ($1) {
            case "d":
            case "f":
              return String(Number(value));
            case "i":
              return String(Math.floor(value));
            case "j":
              return JSON.stringify(value);
            case "s":
              return String(value);
          }
          return "%";
        }, "replace"));
        if (formatOffset !== formatParams.length)
          throw Error("parameter count mismatch");
        body.push(formatStringOrScope);
        return Codegen;
      }
      __name(Codegen, "Codegen");
      function toString(functionNameOverride) {
        return "function " + (functionNameOverride || functionName || "") + "(" + (functionParams && functionParams.join(",") || "") + "){\n  " + body.join("\n  ") + "\n}";
      }
      __name(toString, "toString");
      Codegen.toString = toString;
      return Codegen;
    }
    __name(codegen, "codegen");
    codegen.verbose = false;
  }
});

// node_modules/@protobufjs/fetch/index.js
var require_fetch2 = __commonJS({
  "node_modules/@protobufjs/fetch/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = fetch2;
    var asPromise = require_aspromise();
    var inquire2 = require_inquire();
    var fs95 = inquire2("fs");
    function fetch2(filename, options2, callback) {
      if (typeof options2 === "function") {
        callback = options2;
        options2 = {};
      } else if (!options2)
        options2 = {};
      if (!callback)
        return asPromise(fetch2, this, filename, options2);
      if (!options2.xhr && fs95 && fs95.readFile)
        return fs95.readFile(filename, /* @__PURE__ */ __name(function fetchReadFileCallback(err, contents) {
          return err && typeof XMLHttpRequest !== "undefined" ? fetch2.xhr(filename, options2, callback) : err ? callback(err) : callback(null, options2.binary ? contents : contents.toString("utf8"));
        }, "fetchReadFileCallback"));
      return fetch2.xhr(filename, options2, callback);
    }
    __name(fetch2, "fetch");
    fetch2.xhr = /* @__PURE__ */ __name(function fetch_xhr(filename, options2, callback) {
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = /* @__PURE__ */ __name(function fetchOnReadyStateChange() {
        if (xhr.readyState !== 4)
          return void 0;
        if (xhr.status !== 0 && xhr.status !== 200)
          return callback(Error("status " + xhr.status));
        if (options2.binary) {
          var buffer = xhr.response;
          if (!buffer) {
            buffer = [];
            for (var i = 0; i < xhr.responseText.length; ++i)
              buffer.push(xhr.responseText.charCodeAt(i) & 255);
          }
          return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer);
        }
        return callback(null, xhr.responseText);
      }, "fetchOnReadyStateChange");
      if (options2.binary) {
        if ("overrideMimeType" in xhr)
          xhr.overrideMimeType("text/plain; charset=x-user-defined");
        xhr.responseType = "arraybuffer";
      }
      xhr.open("GET", filename);
      xhr.send();
    }, "fetch_xhr");
  }
});

// node_modules/@protobufjs/path/index.js
var require_path = __commonJS({
  "node_modules/@protobufjs/path/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var path108 = exports2;
    var isAbsolute9 = (
      /**
       * Tests if the specified path is absolute.
       * @param {string} path Path to test
       * @returns {boolean} `true` if path is absolute
       */
      path108.isAbsolute = /* @__PURE__ */ __name(function isAbsolute10(path109) {
        return /^(?:\/|\w+:)/.test(path109);
      }, "isAbsolute")
    );
    var normalize10 = (
      /**
       * Normalizes the specified path.
       * @param {string} path Path to normalize
       * @returns {string} Normalized path
       */
      path108.normalize = /* @__PURE__ */ __name(function normalize11(path109) {
        path109 = path109.replace(/\\/g, "/").replace(/\/{2,}/g, "/");
        var parts = path109.split("/"), absolute = isAbsolute9(path109), prefix = "";
        if (absolute)
          prefix = parts.shift() + "/";
        for (var i = 0; i < parts.length; ) {
          if (parts[i] === "..") {
            if (i > 0 && parts[i - 1] !== "..")
              parts.splice(--i, 2);
            else if (absolute)
              parts.splice(i, 1);
            else
              ++i;
          } else if (parts[i] === ".")
            parts.splice(i, 1);
          else
            ++i;
        }
        return prefix + parts.join("/");
      }, "normalize")
    );
    path108.resolve = /* @__PURE__ */ __name(function resolve24(originPath, includePath, alreadyNormalized) {
      if (!alreadyNormalized)
        includePath = normalize10(includePath);
      if (isAbsolute9(includePath))
        return includePath;
      if (!alreadyNormalized)
        originPath = normalize10(originPath);
      return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize10(originPath + "/" + includePath) : includePath;
    }, "resolve");
  }
});

// node_modules/protobufjs/src/namespace.js
var require_namespace = __commonJS({
  "node_modules/protobufjs/src/namespace.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Namespace;
    var ReflectionObject = require_object();
    ((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace";
    var Field = require_field();
    var util4 = require_util11();
    var OneOf = require_oneof();
    var Type2;
    var Service;
    var Enum;
    Namespace.fromJSON = /* @__PURE__ */ __name(function fromJSON(name3, json2) {
      return new Namespace(name3, json2.options).addJSON(json2.nested);
    }, "fromJSON");
    function arrayToJSON(array, toJSONOptions) {
      if (!(array && array.length))
        return void 0;
      var obj = {};
      for (var i = 0; i < array.length; ++i)
        obj[array[i].name] = array[i].toJSON(toJSONOptions);
      return obj;
    }
    __name(arrayToJSON, "arrayToJSON");
    Namespace.arrayToJSON = arrayToJSON;
    Namespace.isReservedId = /* @__PURE__ */ __name(function isReservedId(reserved, id) {
      if (reserved) {
        for (var i = 0; i < reserved.length; ++i)
          if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] > id)
            return true;
      }
      return false;
    }, "isReservedId");
    Namespace.isReservedName = /* @__PURE__ */ __name(function isReservedName(reserved, name3) {
      if (reserved) {
        for (var i = 0; i < reserved.length; ++i)
          if (reserved[i] === name3)
            return true;
      }
      return false;
    }, "isReservedName");
    function Namespace(name3, options2) {
      ReflectionObject.call(this, name3, options2);
      this.nested = void 0;
      this._nestedArray = null;
      this._lookupCache = {};
      this._needsRecursiveFeatureResolution = true;
      this._needsRecursiveResolve = true;
    }
    __name(Namespace, "Namespace");
    function clearCache(namespace) {
      namespace._nestedArray = null;
      namespace._lookupCache = {};
      var parent = namespace;
      while (parent = parent.parent) {
        parent._lookupCache = {};
      }
      return namespace;
    }
    __name(clearCache, "clearCache");
    Object.defineProperty(Namespace.prototype, "nestedArray", {
      get: /* @__PURE__ */ __name(function() {
        return this._nestedArray || (this._nestedArray = util4.toArray(this.nested));
      }, "get")
    });
    Namespace.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      return util4.toObject([
        "options",
        this.options,
        "nested",
        arrayToJSON(this.nestedArray, toJSONOptions)
      ]);
    }, "toJSON");
    Namespace.prototype.addJSON = /* @__PURE__ */ __name(function addJSON(nestedJson) {
      var ns = this;
      if (nestedJson) {
        for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {
          nested = nestedJson[names[i]];
          ns.add(
            // most to least likely
            (nested.fields !== void 0 ? Type2.fromJSON : nested.values !== void 0 ? Enum.fromJSON : nested.methods !== void 0 ? Service.fromJSON : nested.id !== void 0 ? Field.fromJSON : Namespace.fromJSON)(names[i], nested)
          );
        }
      }
      return this;
    }, "addJSON");
    Namespace.prototype.get = /* @__PURE__ */ __name(function get3(name3) {
      return this.nested && this.nested[name3] || null;
    }, "get");
    Namespace.prototype.getEnum = /* @__PURE__ */ __name(function getEnum(name3) {
      if (this.nested && this.nested[name3] instanceof Enum)
        return this.nested[name3].values;
      throw Error("no such enum: " + name3);
    }, "getEnum");
    Namespace.prototype.add = /* @__PURE__ */ __name(function add(object) {
      if (!(object instanceof Field && object.extend !== void 0 || object instanceof Type2 || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace))
        throw TypeError("object must be a valid nested object");
      if (!this.nested)
        this.nested = {};
      else {
        var prev = this.get(object.name);
        if (prev) {
          if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type2 || prev instanceof Service)) {
            var nested = prev.nestedArray;
            for (var i = 0; i < nested.length; ++i)
              object.add(nested[i]);
            this.remove(prev);
            if (!this.nested)
              this.nested = {};
            object.setOptions(prev.options, true);
          } else
            throw Error("duplicate name '" + object.name + "' in " + this);
        }
      }
      this.nested[object.name] = object;
      if (!(this instanceof Type2 || this instanceof Service || this instanceof Enum || this instanceof Field)) {
        if (!object._edition) {
          object._edition = object._defaultEdition;
        }
      }
      this._needsRecursiveFeatureResolution = true;
      this._needsRecursiveResolve = true;
      var parent = this;
      while (parent = parent.parent) {
        parent._needsRecursiveFeatureResolution = true;
        parent._needsRecursiveResolve = true;
      }
      object.onAdd(this);
      return clearCache(this);
    }, "add");
    Namespace.prototype.remove = /* @__PURE__ */ __name(function remove2(object) {
      if (!(object instanceof ReflectionObject))
        throw TypeError("object must be a ReflectionObject");
      if (object.parent !== this)
        throw Error(object + " is not a member of " + this);
      delete this.nested[object.name];
      if (!Object.keys(this.nested).length)
        this.nested = void 0;
      object.onRemove(this);
      return clearCache(this);
    }, "remove");
    Namespace.prototype.define = /* @__PURE__ */ __name(function define2(path108, json2) {
      if (util4.isString(path108))
        path108 = path108.split(".");
      else if (!Array.isArray(path108))
        throw TypeError("illegal path");
      if (path108 && path108.length && path108[0] === "")
        throw Error("path must be relative");
      var ptr = this;
      while (path108.length > 0) {
        var part = path108.shift();
        if (ptr.nested && ptr.nested[part]) {
          ptr = ptr.nested[part];
          if (!(ptr instanceof Namespace))
            throw Error("path conflicts with non-namespace objects");
        } else
          ptr.add(ptr = new Namespace(part));
      }
      if (json2)
        ptr.addJSON(json2);
      return ptr;
    }, "define");
    Namespace.prototype.resolveAll = /* @__PURE__ */ __name(function resolveAll() {
      if (!this._needsRecursiveResolve) return this;
      this._resolveFeaturesRecursive(this._edition);
      var nested = this.nestedArray, i = 0;
      this.resolve();
      while (i < nested.length)
        if (nested[i] instanceof Namespace)
          nested[i++].resolveAll();
        else
          nested[i++].resolve();
      this._needsRecursiveResolve = false;
      return this;
    }, "resolveAll");
    Namespace.prototype._resolveFeaturesRecursive = /* @__PURE__ */ __name(function _resolveFeaturesRecursive(edition) {
      if (!this._needsRecursiveFeatureResolution) return this;
      this._needsRecursiveFeatureResolution = false;
      edition = this._edition || edition;
      ReflectionObject.prototype._resolveFeaturesRecursive.call(this, edition);
      this.nestedArray.forEach((nested) => {
        nested._resolveFeaturesRecursive(edition);
      });
      return this;
    }, "_resolveFeaturesRecursive");
    Namespace.prototype.lookup = /* @__PURE__ */ __name(function lookup(path108, filterTypes, parentAlreadyChecked) {
      if (typeof filterTypes === "boolean") {
        parentAlreadyChecked = filterTypes;
        filterTypes = void 0;
      } else if (filterTypes && !Array.isArray(filterTypes))
        filterTypes = [filterTypes];
      if (util4.isString(path108) && path108.length) {
        if (path108 === ".")
          return this.root;
        path108 = path108.split(".");
      } else if (!path108.length)
        return this;
      var flatPath = path108.join(".");
      if (path108[0] === "")
        return this.root.lookup(path108.slice(1), filterTypes);
      var found = this.root._fullyQualifiedObjects && this.root._fullyQualifiedObjects["." + flatPath];
      if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {
        return found;
      }
      found = this._lookupImpl(path108, flatPath);
      if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {
        return found;
      }
      if (parentAlreadyChecked)
        return null;
      var current = this;
      while (current.parent) {
        found = current.parent._lookupImpl(path108, flatPath);
        if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {
          return found;
        }
        current = current.parent;
      }
      return null;
    }, "lookup");
    Namespace.prototype._lookupImpl = /* @__PURE__ */ __name(function lookup(path108, flatPath) {
      if (Object.prototype.hasOwnProperty.call(this._lookupCache, flatPath)) {
        return this._lookupCache[flatPath];
      }
      var found = this.get(path108[0]);
      var exact = null;
      if (found) {
        if (path108.length === 1) {
          exact = found;
        } else if (found instanceof Namespace) {
          path108 = path108.slice(1);
          exact = found._lookupImpl(path108, path108.join("."));
        }
      } else {
        for (var i = 0; i < this.nestedArray.length; ++i)
          if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i]._lookupImpl(path108, flatPath)))
            exact = found;
      }
      this._lookupCache[flatPath] = exact;
      return exact;
    }, "lookup");
    Namespace.prototype.lookupType = /* @__PURE__ */ __name(function lookupType(path108) {
      var found = this.lookup(path108, [Type2]);
      if (!found)
        throw Error("no such type: " + path108);
      return found;
    }, "lookupType");
    Namespace.prototype.lookupEnum = /* @__PURE__ */ __name(function lookupEnum(path108) {
      var found = this.lookup(path108, [Enum]);
      if (!found)
        throw Error("no such Enum '" + path108 + "' in " + this);
      return found;
    }, "lookupEnum");
    Namespace.prototype.lookupTypeOrEnum = /* @__PURE__ */ __name(function lookupTypeOrEnum(path108) {
      var found = this.lookup(path108, [Type2, Enum]);
      if (!found)
        throw Error("no such Type or Enum '" + path108 + "' in " + this);
      return found;
    }, "lookupTypeOrEnum");
    Namespace.prototype.lookupService = /* @__PURE__ */ __name(function lookupService(path108) {
      var found = this.lookup(path108, [Service]);
      if (!found)
        throw Error("no such Service '" + path108 + "' in " + this);
      return found;
    }, "lookupService");
    Namespace._configure = function(Type_, Service_, Enum_) {
      Type2 = Type_;
      Service = Service_;
      Enum = Enum_;
    };
  }
});

// node_modules/protobufjs/src/mapfield.js
var require_mapfield = __commonJS({
  "node_modules/protobufjs/src/mapfield.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = MapField;
    var Field = require_field();
    ((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField";
    var types3 = require_types3();
    var util4 = require_util11();
    function MapField(name3, id, keyType, type, options2, comment) {
      Field.call(this, name3, id, type, void 0, void 0, options2, comment);
      if (!util4.isString(keyType))
        throw TypeError("keyType must be a string");
      this.keyType = keyType;
      this.resolvedKeyType = null;
      this.map = true;
    }
    __name(MapField, "MapField");
    MapField.fromJSON = /* @__PURE__ */ __name(function fromJSON(name3, json2) {
      return new MapField(name3, json2.id, json2.keyType, json2.type, json2.options, json2.comment);
    }, "fromJSON");
    MapField.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util4.toObject([
        "keyType",
        this.keyType,
        "type",
        this.type,
        "id",
        this.id,
        "extend",
        this.extend,
        "options",
        this.options,
        "comment",
        keepComments ? this.comment : void 0
      ]);
    }, "toJSON");
    MapField.prototype.resolve = /* @__PURE__ */ __name(function resolve24() {
      if (this.resolved)
        return this;
      if (types3.mapKey[this.keyType] === void 0)
        throw Error("invalid key type: " + this.keyType);
      return Field.prototype.resolve.call(this);
    }, "resolve");
    MapField.d = /* @__PURE__ */ __name(function decorateMapField(fieldId, fieldKeyType, fieldValueType) {
      if (typeof fieldValueType === "function")
        fieldValueType = util4.decorateType(fieldValueType).name;
      else if (fieldValueType && typeof fieldValueType === "object")
        fieldValueType = util4.decorateEnum(fieldValueType).name;
      return /* @__PURE__ */ __name(function mapFieldDecorator(prototype, fieldName) {
        util4.decorateType(prototype.constructor).add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));
      }, "mapFieldDecorator");
    }, "decorateMapField");
  }
});

// node_modules/protobufjs/src/method.js
var require_method = __commonJS({
  "node_modules/protobufjs/src/method.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Method;
    var ReflectionObject = require_object();
    ((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method";
    var util4 = require_util11();
    function Method(name3, type, requestType, responseType, requestStream, responseStream, options2, comment, parsedOptions) {
      if (util4.isObject(requestStream)) {
        options2 = requestStream;
        requestStream = responseStream = void 0;
      } else if (util4.isObject(responseStream)) {
        options2 = responseStream;
        responseStream = void 0;
      }
      if (!(type === void 0 || util4.isString(type)))
        throw TypeError("type must be a string");
      if (!util4.isString(requestType))
        throw TypeError("requestType must be a string");
      if (!util4.isString(responseType))
        throw TypeError("responseType must be a string");
      ReflectionObject.call(this, name3, options2);
      this.type = type || "rpc";
      this.requestType = requestType;
      this.requestStream = requestStream ? true : void 0;
      this.responseType = responseType;
      this.responseStream = responseStream ? true : void 0;
      this.resolvedRequestType = null;
      this.resolvedResponseType = null;
      this.comment = comment;
      this.parsedOptions = parsedOptions;
    }
    __name(Method, "Method");
    Method.fromJSON = /* @__PURE__ */ __name(function fromJSON(name3, json2) {
      return new Method(name3, json2.type, json2.requestType, json2.responseType, json2.requestStream, json2.responseStream, json2.options, json2.comment, json2.parsedOptions);
    }, "fromJSON");
    Method.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util4.toObject([
        "type",
        this.type !== "rpc" && /* istanbul ignore next */
        this.type || void 0,
        "requestType",
        this.requestType,
        "requestStream",
        this.requestStream,
        "responseType",
        this.responseType,
        "responseStream",
        this.responseStream,
        "options",
        this.options,
        "comment",
        keepComments ? this.comment : void 0,
        "parsedOptions",
        this.parsedOptions
      ]);
    }, "toJSON");
    Method.prototype.resolve = /* @__PURE__ */ __name(function resolve24() {
      if (this.resolved)
        return this;
      this.resolvedRequestType = this.parent.lookupType(this.requestType);
      this.resolvedResponseType = this.parent.lookupType(this.responseType);
      return ReflectionObject.prototype.resolve.call(this);
    }, "resolve");
  }
});

// node_modules/protobufjs/src/service.js
var require_service2 = __commonJS({
  "node_modules/protobufjs/src/service.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Service;
    var Namespace = require_namespace();
    ((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service";
    var Method = require_method();
    var util4 = require_util11();
    var rpc = require_rpc();
    function Service(name3, options2) {
      Namespace.call(this, name3, options2);
      this.methods = {};
      this._methodsArray = null;
    }
    __name(Service, "Service");
    Service.fromJSON = /* @__PURE__ */ __name(function fromJSON(name3, json2) {
      var service = new Service(name3, json2.options);
      if (json2.methods)
        for (var names = Object.keys(json2.methods), i = 0; i < names.length; ++i)
          service.add(Method.fromJSON(names[i], json2.methods[names[i]]));
      if (json2.nested)
        service.addJSON(json2.nested);
      if (json2.edition)
        service._edition = json2.edition;
      service.comment = json2.comment;
      service._defaultEdition = "proto3";
      return service;
    }, "fromJSON");
    Service.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util4.toObject([
        "edition",
        this._editionToJSON(),
        "options",
        inherited && inherited.options || void 0,
        "methods",
        Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */
        {},
        "nested",
        inherited && inherited.nested || void 0,
        "comment",
        keepComments ? this.comment : void 0
      ]);
    }, "toJSON");
    Object.defineProperty(Service.prototype, "methodsArray", {
      get: /* @__PURE__ */ __name(function() {
        return this._methodsArray || (this._methodsArray = util4.toArray(this.methods));
      }, "get")
    });
    function clearCache(service) {
      service._methodsArray = null;
      return service;
    }
    __name(clearCache, "clearCache");
    Service.prototype.get = /* @__PURE__ */ __name(function get3(name3) {
      return this.methods[name3] || Namespace.prototype.get.call(this, name3);
    }, "get");
    Service.prototype.resolveAll = /* @__PURE__ */ __name(function resolveAll() {
      if (!this._needsRecursiveResolve) return this;
      Namespace.prototype.resolve.call(this);
      var methods = this.methodsArray;
      for (var i = 0; i < methods.length; ++i)
        methods[i].resolve();
      return this;
    }, "resolveAll");
    Service.prototype._resolveFeaturesRecursive = /* @__PURE__ */ __name(function _resolveFeaturesRecursive(edition) {
      if (!this._needsRecursiveFeatureResolution) return this;
      edition = this._edition || edition;
      Namespace.prototype._resolveFeaturesRecursive.call(this, edition);
      this.methodsArray.forEach((method) => {
        method._resolveFeaturesRecursive(edition);
      });
      return this;
    }, "_resolveFeaturesRecursive");
    Service.prototype.add = /* @__PURE__ */ __name(function add(object) {
      if (this.get(object.name))
        throw Error("duplicate name '" + object.name + "' in " + this);
      if (object instanceof Method) {
        this.methods[object.name] = object;
        object.parent = this;
        return clearCache(this);
      }
      return Namespace.prototype.add.call(this, object);
    }, "add");
    Service.prototype.remove = /* @__PURE__ */ __name(function remove2(object) {
      if (object instanceof Method) {
        if (this.methods[object.name] !== object)
          throw Error(object + " is not a member of " + this);
        delete this.methods[object.name];
        object.parent = null;
        return clearCache(this);
      }
      return Namespace.prototype.remove.call(this, object);
    }, "remove");
    Service.prototype.create = /* @__PURE__ */ __name(function create3(rpcImpl, requestDelimited, responseDelimited) {
      var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);
      for (var i = 0, method; i < /* initializes */
      this.methodsArray.length; ++i) {
        var methodName = util4.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, "");
        rpcService[methodName] = util4.codegen(["r", "c"], util4.isReserved(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({
          m: method,
          q: method.resolvedRequestType.ctor,
          s: method.resolvedResponseType.ctor
        });
      }
      return rpcService;
    }, "create");
  }
});

// node_modules/protobufjs/src/message.js
var require_message = __commonJS({
  "node_modules/protobufjs/src/message.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Message;
    var util4 = require_minimal();
    function Message(properties) {
      if (properties)
        for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
          this[keys[i]] = properties[keys[i]];
    }
    __name(Message, "Message");
    Message.create = /* @__PURE__ */ __name(function create3(properties) {
      return this.$type.create(properties);
    }, "create");
    Message.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
      return this.$type.encode(message, writer);
    }, "encode");
    Message.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
      return this.$type.encodeDelimited(message, writer);
    }, "encodeDelimited");
    Message.decode = /* @__PURE__ */ __name(function decode2(reader) {
      return this.$type.decode(reader);
    }, "decode");
    Message.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
      return this.$type.decodeDelimited(reader);
    }, "decodeDelimited");
    Message.verify = /* @__PURE__ */ __name(function verify(message) {
      return this.$type.verify(message);
    }, "verify");
    Message.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
      return this.$type.fromObject(object);
    }, "fromObject");
    Message.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
      return this.$type.toObject(message, options2);
    }, "toObject");
    Message.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
      return this.$type.toObject(this, util4.toJSONOptions);
    }, "toJSON");
  }
});

// node_modules/protobufjs/src/decoder.js
var require_decoder = __commonJS({
  "node_modules/protobufjs/src/decoder.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = decoder;
    var Enum = require_enum3();
    var types3 = require_types3();
    var util4 = require_util11();
    function missing(field) {
      return "missing required '" + field.name + "'";
    }
    __name(missing, "missing");
    function decoder(mtype) {
      var gen = util4.codegen(["r", "l", "e"], mtype.name + "$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor" + (mtype.fieldsArray.filter(function(field2) {
        return field2.map;
      }).length ? ",k,value" : ""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){");
      var i = 0;
      for (; i < /* initializes */
      mtype.fieldsArray.length; ++i) {
        var field = mtype._fieldsArray[i].resolve(), type = field.resolvedType instanceof Enum ? "int32" : field.type, ref = "m" + util4.safeProp(field.name);
        gen("case %i: {", field.id);
        if (field.map) {
          gen("if(%s===util.emptyObject)", ref)("%s={}", ref)("var c2 = r.uint32()+r.pos");
          if (types3.defaults[field.keyType] !== void 0) gen("k=%j", types3.defaults[field.keyType]);
          else gen("k=null");
          if (types3.defaults[type] !== void 0) gen("value=%j", types3.defaults[type]);
          else gen("value=null");
          gen("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break", field.keyType)("case 2:");
          if (types3.basic[type] === void 0) gen("value=types[%i].decode(r,r.uint32())", i);
          else gen("value=r.%s()", type);
          gen("break")("default:")("r.skipType(tag2&7)")("break")("}")("}");
          if (types3.long[field.keyType] !== void 0) gen('%s[typeof k==="object"?util.longToHash(k):k]=value', ref);
          else gen("%s[k]=value", ref);
        } else if (field.repeated) {
          gen("if(!(%s&&%s.length))", ref, ref)("%s=[]", ref);
          if (types3.packed[type] !== void 0) gen("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())", ref, type)("}else");
          if (types3.basic[type] === void 0) gen(field.delimited ? "%s.push(types[%i].decode(r,undefined,((t&~7)|4)))" : "%s.push(types[%i].decode(r,r.uint32()))", ref, i);
          else gen("%s.push(r.%s())", ref, type);
        } else if (types3.basic[type] === void 0) gen(field.delimited ? "%s=types[%i].decode(r,undefined,((t&~7)|4))" : "%s=types[%i].decode(r,r.uint32())", ref, i);
        else gen("%s=r.%s()", ref, type);
        gen("break")("}");
      }
      gen("default:")("r.skipType(t&7)")("break")("}")("}");
      for (i = 0; i < mtype._fieldsArray.length; ++i) {
        var rfield = mtype._fieldsArray[i];
        if (rfield.required) gen("if(!m.hasOwnProperty(%j))", rfield.name)("throw util.ProtocolError(%j,{instance:m})", missing(rfield));
      }
      return gen("return m");
    }
    __name(decoder, "decoder");
  }
});

// node_modules/protobufjs/src/verifier.js
var require_verifier = __commonJS({
  "node_modules/protobufjs/src/verifier.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = verifier;
    var Enum = require_enum3();
    var util4 = require_util11();
    function invalid(field, expected) {
      return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:" + field.keyType + "}" : "") + " expected";
    }
    __name(invalid, "invalid");
    function genVerifyValue(gen, field, fieldIndex, ref) {
      if (field.resolvedType) {
        if (field.resolvedType instanceof Enum) {
          gen("switch(%s){", ref)("default:")("return%j", invalid(field, "enum value"));
          for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen("case %i:", field.resolvedType.values[keys[j]]);
          gen("break")("}");
        } else {
          gen("{")("var e=types[%i].verify(%s);", fieldIndex, ref)("if(e)")("return%j+e", field.name + ".")("}");
        }
      } else {
        switch (field.type) {
          case "int32":
          case "uint32":
          case "sint32":
          case "fixed32":
          case "sfixed32":
            gen("if(!util.isInteger(%s))", ref)("return%j", invalid(field, "integer"));
            break;
          case "int64":
          case "uint64":
          case "sint64":
          case "fixed64":
          case "sfixed64":
            gen("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref)("return%j", invalid(field, "integer|Long"));
            break;
          case "float":
          case "double":
            gen('if(typeof %s!=="number")', ref)("return%j", invalid(field, "number"));
            break;
          case "bool":
            gen('if(typeof %s!=="boolean")', ref)("return%j", invalid(field, "boolean"));
            break;
          case "string":
            gen("if(!util.isString(%s))", ref)("return%j", invalid(field, "string"));
            break;
          case "bytes":
            gen('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))', ref, ref, ref)("return%j", invalid(field, "buffer"));
            break;
        }
      }
      return gen;
    }
    __name(genVerifyValue, "genVerifyValue");
    function genVerifyKey(gen, field, ref) {
      switch (field.keyType) {
        case "int32":
        case "uint32":
        case "sint32":
        case "fixed32":
        case "sfixed32":
          gen("if(!util.key32Re.test(%s))", ref)("return%j", invalid(field, "integer key"));
          break;
        case "int64":
        case "uint64":
        case "sint64":
        case "fixed64":
        case "sfixed64":
          gen("if(!util.key64Re.test(%s))", ref)("return%j", invalid(field, "integer|Long key"));
          break;
        case "bool":
          gen("if(!util.key2Re.test(%s))", ref)("return%j", invalid(field, "boolean key"));
          break;
      }
      return gen;
    }
    __name(genVerifyKey, "genVerifyKey");
    function verifier(mtype) {
      var gen = util4.codegen(["m"], mtype.name + "$verify")('if(typeof m!=="object"||m===null)')("return%j", "object expected");
      var oneofs = mtype.oneofsArray, seenFirstField = {};
      if (oneofs.length) gen("var p={}");
      for (var i = 0; i < /* initializes */
      mtype.fieldsArray.length; ++i) {
        var field = mtype._fieldsArray[i].resolve(), ref = "m" + util4.safeProp(field.name);
        if (field.optional) gen("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name);
        if (field.map) {
          gen("if(!util.isObject(%s))", ref)("return%j", invalid(field, "object"))("var k=Object.keys(%s)", ref)("for(var i=0;i<k.length;++i){");
          genVerifyKey(gen, field, "k[i]");
          genVerifyValue(gen, field, i, ref + "[k[i]]")("}");
        } else if (field.repeated) {
          gen("if(!Array.isArray(%s))", ref)("return%j", invalid(field, "array"))("for(var i=0;i<%s.length;++i){", ref);
          genVerifyValue(gen, field, i, ref + "[i]")("}");
        } else {
          if (field.partOf) {
            var oneofProp = util4.safeProp(field.partOf.name);
            if (seenFirstField[field.partOf.name] === 1) gen("if(p%s===1)", oneofProp)("return%j", field.partOf.name + ": multiple values");
            seenFirstField[field.partOf.name] = 1;
            gen("p%s=1", oneofProp);
          }
          genVerifyValue(gen, field, i, ref);
        }
        if (field.optional) gen("}");
      }
      return gen("return null");
    }
    __name(verifier, "verifier");
  }
});

// node_modules/protobufjs/src/converter.js
var require_converter = __commonJS({
  "node_modules/protobufjs/src/converter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var converter = exports2;
    var Enum = require_enum3();
    var util4 = require_util11();
    function genValuePartial_fromObject(gen, field, fieldIndex, prop) {
      var defaultAlreadyEmitted = false;
      if (field.resolvedType) {
        if (field.resolvedType instanceof Enum) {
          gen("switch(d%s){", prop);
          for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {
            if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) {
              gen("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}', prop, prop, prop);
              if (!field.repeated) gen("break");
              defaultAlreadyEmitted = true;
            }
            gen("case%j:", keys[i])("case %i:", values[keys[i]])("m%s=%j", prop, values[keys[i]])("break");
          }
          gen("}");
        } else gen('if(typeof d%s!=="object")', prop)("throw TypeError(%j)", field.fullName + ": object expected")("m%s=types[%i].fromObject(d%s)", prop, fieldIndex, prop);
      } else {
        var isUnsigned = false;
        switch (field.type) {
          case "double":
          case "float":
            gen("m%s=Number(d%s)", prop, prop);
            break;
          case "uint32":
          case "fixed32":
            gen("m%s=d%s>>>0", prop, prop);
            break;
          case "int32":
          case "sint32":
          case "sfixed32":
            gen("m%s=d%s|0", prop, prop);
            break;
          case "uint64":
            isUnsigned = true;
          // eslint-disable-next-line no-fallthrough
          case "int64":
          case "sint64":
          case "fixed64":
          case "sfixed64":
            gen("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop, prop, isUnsigned)('else if(typeof d%s==="string")', prop)("m%s=parseInt(d%s,10)", prop, prop)('else if(typeof d%s==="number")', prop)("m%s=d%s", prop, prop)('else if(typeof d%s==="object")', prop)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : "");
            break;
          case "bytes":
            gen('if(typeof d%s==="string")', prop)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop)("else if(d%s.length >= 0)", prop)("m%s=d%s", prop, prop);
            break;
          case "string":
            gen("m%s=String(d%s)", prop, prop);
            break;
          case "bool":
            gen("m%s=Boolean(d%s)", prop, prop);
            break;
        }
      }
      return gen;
    }
    __name(genValuePartial_fromObject, "genValuePartial_fromObject");
    converter.fromObject = /* @__PURE__ */ __name(function fromObject(mtype) {
      var fields = mtype.fieldsArray;
      var gen = util4.codegen(["d"], mtype.name + "$fromObject")("if(d instanceof this.ctor)")("return d");
      if (!fields.length) return gen("return new this.ctor");
      gen("var m=new this.ctor");
      for (var i = 0; i < fields.length; ++i) {
        var field = fields[i].resolve(), prop = util4.safeProp(field.name);
        if (field.map) {
          gen("if(d%s){", prop)('if(typeof d%s!=="object")', prop)("throw TypeError(%j)", field.fullName + ": object expected")("m%s={}", prop)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){", prop);
          genValuePartial_fromObject(
            gen,
            field,
            /* not sorted */
            i,
            prop + "[ks[i]]"
          )("}")("}");
        } else if (field.repeated) {
          gen("if(d%s){", prop)("if(!Array.isArray(d%s))", prop)("throw TypeError(%j)", field.fullName + ": array expected")("m%s=[]", prop)("for(var i=0;i<d%s.length;++i){", prop);
          genValuePartial_fromObject(
            gen,
            field,
            /* not sorted */
            i,
            prop + "[i]"
          )("}")("}");
        } else {
          if (!(field.resolvedType instanceof Enum)) gen("if(d%s!=null){", prop);
          genValuePartial_fromObject(
            gen,
            field,
            /* not sorted */
            i,
            prop
          );
          if (!(field.resolvedType instanceof Enum)) gen("}");
        }
      }
      return gen("return m");
    }, "fromObject");
    function genValuePartial_toObject(gen, field, fieldIndex, prop) {
      if (field.resolvedType) {
        if (field.resolvedType instanceof Enum) gen("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s", prop, fieldIndex, prop, prop, fieldIndex, prop, prop);
        else gen("d%s=types[%i].toObject(m%s,o)", prop, fieldIndex, prop);
      } else {
        var isUnsigned = false;
        switch (field.type) {
          case "double":
          case "float":
            gen("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s", prop, prop, prop, prop);
            break;
          case "uint64":
            isUnsigned = true;
          // eslint-disable-next-line no-fallthrough
          case "int64":
          case "sint64":
          case "fixed64":
          case "sfixed64":
            gen('if(typeof m%s==="number")', prop)("d%s=o.longs===String?String(m%s):m%s", prop, prop, prop)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true" : "", prop);
            break;
          case "bytes":
            gen("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop);
            break;
          default:
            gen("d%s=m%s", prop, prop);
            break;
        }
      }
      return gen;
    }
    __name(genValuePartial_toObject, "genValuePartial_toObject");
    converter.toObject = /* @__PURE__ */ __name(function toObject(mtype) {
      var fields = mtype.fieldsArray.slice().sort(util4.compareFieldsById);
      if (!fields.length)
        return util4.codegen()("return {}");
      var gen = util4.codegen(["m", "o"], mtype.name + "$toObject")("if(!o)")("o={}")("var d={}");
      var repeatedFields = [], mapFields = [], normalFields = [], i = 0;
      for (; i < fields.length; ++i)
        if (!fields[i].partOf)
          (fields[i].resolve().repeated ? repeatedFields : fields[i].map ? mapFields : normalFields).push(fields[i]);
      if (repeatedFields.length) {
        gen("if(o.arrays||o.defaults){");
        for (i = 0; i < repeatedFields.length; ++i) gen("d%s=[]", util4.safeProp(repeatedFields[i].name));
        gen("}");
      }
      if (mapFields.length) {
        gen("if(o.objects||o.defaults){");
        for (i = 0; i < mapFields.length; ++i) gen("d%s={}", util4.safeProp(mapFields[i].name));
        gen("}");
      }
      if (normalFields.length) {
        gen("if(o.defaults){");
        for (i = 0; i < normalFields.length; ++i) {
          var field = normalFields[i], prop = util4.safeProp(field.name);
          if (field.resolvedType instanceof Enum) gen("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);
          else if (field.long) gen("if(util.Long){")("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop)("}else")("d%s=o.longs===String?%j:%i", prop, field.typeDefault.toString(), field.typeDefault.toNumber());
          else if (field.bytes) {
            var arrayDefault = "[" + Array.prototype.slice.call(field.typeDefault).join(",") + "]";
            gen("if(o.bytes===String)d%s=%j", prop, String.fromCharCode.apply(String, field.typeDefault))("else{")("d%s=%s", prop, arrayDefault)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", prop, prop)("}");
          } else gen("d%s=%j", prop, field.typeDefault);
        }
        gen("}");
      }
      var hasKs2 = false;
      for (i = 0; i < fields.length; ++i) {
        var field = fields[i], index = mtype._fieldsArray.indexOf(field), prop = util4.safeProp(field.name);
        if (field.map) {
          if (!hasKs2) {
            hasKs2 = true;
            gen("var ks2");
          }
          gen("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop)("d%s={}", prop)("for(var j=0;j<ks2.length;++j){");
          genValuePartial_toObject(
            gen,
            field,
            /* sorted */
            index,
            prop + "[ks2[j]]"
          )("}");
        } else if (field.repeated) {
          gen("if(m%s&&m%s.length){", prop, prop)("d%s=[]", prop)("for(var j=0;j<m%s.length;++j){", prop);
          genValuePartial_toObject(
            gen,
            field,
            /* sorted */
            index,
            prop + "[j]"
          )("}");
        } else {
          gen("if(m%s!=null&&m.hasOwnProperty(%j)){", prop, field.name);
          genValuePartial_toObject(
            gen,
            field,
            /* sorted */
            index,
            prop
          );
          if (field.partOf) gen("if(o.oneofs)")("d%s=%j", util4.safeProp(field.partOf.name), field.name);
        }
        gen("}");
      }
      return gen("return d");
    }, "toObject");
  }
});

// node_modules/protobufjs/src/wrappers.js
var require_wrappers = __commonJS({
  "node_modules/protobufjs/src/wrappers.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var wrappers = exports2;
    var Message = require_message();
    wrappers[".google.protobuf.Any"] = {
      fromObject: /* @__PURE__ */ __name(function(object) {
        if (object && object["@type"]) {
          var name3 = object["@type"].substring(object["@type"].lastIndexOf("/") + 1);
          var type = this.lookup(name3);
          if (type) {
            var type_url = object["@type"].charAt(0) === "." ? object["@type"].slice(1) : object["@type"];
            if (type_url.indexOf("/") === -1) {
              type_url = "/" + type_url;
            }
            return this.create({
              type_url,
              value: type.encode(type.fromObject(object)).finish()
            });
          }
        }
        return this.fromObject(object);
      }, "fromObject"),
      toObject: /* @__PURE__ */ __name(function(message, options2) {
        var googleApi = "type.googleapis.com/";
        var prefix = "";
        var name3 = "";
        if (options2 && options2.json && message.type_url && message.value) {
          name3 = message.type_url.substring(message.type_url.lastIndexOf("/") + 1);
          prefix = message.type_url.substring(0, message.type_url.lastIndexOf("/") + 1);
          var type = this.lookup(name3);
          if (type)
            message = type.decode(message.value);
        }
        if (!(message instanceof this.ctor) && message instanceof Message) {
          var object = message.$type.toObject(message, options2);
          var messageName = message.$type.fullName[0] === "." ? message.$type.fullName.slice(1) : message.$type.fullName;
          if (prefix === "") {
            prefix = googleApi;
          }
          name3 = prefix + messageName;
          object["@type"] = name3;
          return object;
        }
        return this.toObject(message, options2);
      }, "toObject")
    };
  }
});

// node_modules/protobufjs/src/type.js
var require_type = __commonJS({
  "node_modules/protobufjs/src/type.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Type2;
    var Namespace = require_namespace();
    ((Type2.prototype = Object.create(Namespace.prototype)).constructor = Type2).className = "Type";
    var Enum = require_enum3();
    var OneOf = require_oneof();
    var Field = require_field();
    var MapField = require_mapfield();
    var Service = require_service2();
    var Message = require_message();
    var Reader = require_reader();
    var Writer = require_writer();
    var util4 = require_util11();
    var encoder = require_encoder();
    var decoder = require_decoder();
    var verifier = require_verifier();
    var converter = require_converter();
    var wrappers = require_wrappers();
    function Type2(name3, options2) {
      Namespace.call(this, name3, options2);
      this.fields = {};
      this.oneofs = void 0;
      this.extensions = void 0;
      this.reserved = void 0;
      this.group = void 0;
      this._fieldsById = null;
      this._fieldsArray = null;
      this._oneofsArray = null;
      this._ctor = null;
    }
    __name(Type2, "Type");
    Object.defineProperties(Type2.prototype, {
      /**
       * Message fields by id.
       * @name Type#fieldsById
       * @type {Object.<number,Field>}
       * @readonly
       */
      fieldsById: {
        get: /* @__PURE__ */ __name(function() {
          if (this._fieldsById)
            return this._fieldsById;
          this._fieldsById = {};
          for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {
            var field = this.fields[names[i]], id = field.id;
            if (this._fieldsById[id])
              throw Error("duplicate id " + id + " in " + this);
            this._fieldsById[id] = field;
          }
          return this._fieldsById;
        }, "get")
      },
      /**
       * Fields of this message as an array for iteration.
       * @name Type#fieldsArray
       * @type {Field[]}
       * @readonly
       */
      fieldsArray: {
        get: /* @__PURE__ */ __name(function() {
          return this._fieldsArray || (this._fieldsArray = util4.toArray(this.fields));
        }, "get")
      },
      /**
       * Oneofs of this message as an array for iteration.
       * @name Type#oneofsArray
       * @type {OneOf[]}
       * @readonly
       */
      oneofsArray: {
        get: /* @__PURE__ */ __name(function() {
          return this._oneofsArray || (this._oneofsArray = util4.toArray(this.oneofs));
        }, "get")
      },
      /**
       * The registered constructor, if any registered, otherwise a generic constructor.
       * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.
       * @name Type#ctor
       * @type {Constructor<{}>}
       */
      ctor: {
        get: /* @__PURE__ */ __name(function() {
          return this._ctor || (this.ctor = Type2.generateConstructor(this)());
        }, "get"),
        set: /* @__PURE__ */ __name(function(ctor) {
          var prototype = ctor.prototype;
          if (!(prototype instanceof Message)) {
            (ctor.prototype = new Message()).constructor = ctor;
            util4.merge(ctor.prototype, prototype);
          }
          ctor.$type = ctor.prototype.$type = this;
          util4.merge(ctor, Message, true);
          this._ctor = ctor;
          var i = 0;
          for (; i < /* initializes */
          this.fieldsArray.length; ++i)
            this._fieldsArray[i].resolve();
          var ctorProperties = {};
          for (i = 0; i < /* initializes */
          this.oneofsArray.length; ++i)
            ctorProperties[this._oneofsArray[i].resolve().name] = {
              get: util4.oneOfGetter(this._oneofsArray[i].oneof),
              set: util4.oneOfSetter(this._oneofsArray[i].oneof)
            };
          if (i)
            Object.defineProperties(ctor.prototype, ctorProperties);
        }, "set")
      }
    });
    Type2.generateConstructor = /* @__PURE__ */ __name(function generateConstructor(mtype) {
      var gen = util4.codegen(["p"], mtype.name);
      for (var i = 0, field; i < mtype.fieldsArray.length; ++i)
        if ((field = mtype._fieldsArray[i]).map) gen("this%s={}", util4.safeProp(field.name));
        else if (field.repeated) gen("this%s=[]", util4.safeProp(field.name));
      return gen("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]");
    }, "generateConstructor");
    function clearCache(type) {
      type._fieldsById = type._fieldsArray = type._oneofsArray = null;
      delete type.encode;
      delete type.decode;
      delete type.verify;
      return type;
    }
    __name(clearCache, "clearCache");
    Type2.fromJSON = /* @__PURE__ */ __name(function fromJSON(name3, json2) {
      var type = new Type2(name3, json2.options);
      type.extensions = json2.extensions;
      type.reserved = json2.reserved;
      var names = Object.keys(json2.fields), i = 0;
      for (; i < names.length; ++i)
        type.add(
          (typeof json2.fields[names[i]].keyType !== "undefined" ? MapField.fromJSON : Field.fromJSON)(names[i], json2.fields[names[i]])
        );
      if (json2.oneofs)
        for (names = Object.keys(json2.oneofs), i = 0; i < names.length; ++i)
          type.add(OneOf.fromJSON(names[i], json2.oneofs[names[i]]));
      if (json2.nested)
        for (names = Object.keys(json2.nested), i = 0; i < names.length; ++i) {
          var nested = json2.nested[names[i]];
          type.add(
            // most to least likely
            (nested.id !== void 0 ? Field.fromJSON : nested.fields !== void 0 ? Type2.fromJSON : nested.values !== void 0 ? Enum.fromJSON : nested.methods !== void 0 ? Service.fromJSON : Namespace.fromJSON)(names[i], nested)
          );
        }
      if (json2.extensions && json2.extensions.length)
        type.extensions = json2.extensions;
      if (json2.reserved && json2.reserved.length)
        type.reserved = json2.reserved;
      if (json2.group)
        type.group = true;
      if (json2.comment)
        type.comment = json2.comment;
      if (json2.edition)
        type._edition = json2.edition;
      type._defaultEdition = "proto3";
      return type;
    }, "fromJSON");
    Type2.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util4.toObject([
        "edition",
        this._editionToJSON(),
        "options",
        inherited && inherited.options || void 0,
        "oneofs",
        Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),
        "fields",
        Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) {
          return !obj.declaringField;
        }), toJSONOptions) || {},
        "extensions",
        this.extensions && this.extensions.length ? this.extensions : void 0,
        "reserved",
        this.reserved && this.reserved.length ? this.reserved : void 0,
        "group",
        this.group || void 0,
        "nested",
        inherited && inherited.nested || void 0,
        "comment",
        keepComments ? this.comment : void 0
      ]);
    }, "toJSON");
    Type2.prototype.resolveAll = /* @__PURE__ */ __name(function resolveAll() {
      if (!this._needsRecursiveResolve) return this;
      Namespace.prototype.resolveAll.call(this);
      var oneofs = this.oneofsArray;
      i = 0;
      while (i < oneofs.length)
        oneofs[i++].resolve();
      var fields = this.fieldsArray, i = 0;
      while (i < fields.length)
        fields[i++].resolve();
      return this;
    }, "resolveAll");
    Type2.prototype._resolveFeaturesRecursive = /* @__PURE__ */ __name(function _resolveFeaturesRecursive(edition) {
      if (!this._needsRecursiveFeatureResolution) return this;
      edition = this._edition || edition;
      Namespace.prototype._resolveFeaturesRecursive.call(this, edition);
      this.oneofsArray.forEach((oneof) => {
        oneof._resolveFeatures(edition);
      });
      this.fieldsArray.forEach((field) => {
        field._resolveFeatures(edition);
      });
      return this;
    }, "_resolveFeaturesRecursive");
    Type2.prototype.get = /* @__PURE__ */ __name(function get3(name3) {
      return this.fields[name3] || this.oneofs && this.oneofs[name3] || this.nested && this.nested[name3] || null;
    }, "get");
    Type2.prototype.add = /* @__PURE__ */ __name(function add(object) {
      if (this.get(object.name))
        throw Error("duplicate name '" + object.name + "' in " + this);
      if (object instanceof Field && object.extend === void 0) {
        if (this._fieldsById ? (
          /* istanbul ignore next */
          this._fieldsById[object.id]
        ) : this.fieldsById[object.id])
          throw Error("duplicate id " + object.id + " in " + this);
        if (this.isReservedId(object.id))
          throw Error("id " + object.id + " is reserved in " + this);
        if (this.isReservedName(object.name))
          throw Error("name '" + object.name + "' is reserved in " + this);
        if (object.parent)
          object.parent.remove(object);
        this.fields[object.name] = object;
        object.message = this;
        object.onAdd(this);
        return clearCache(this);
      }
      if (object instanceof OneOf) {
        if (!this.oneofs)
          this.oneofs = {};
        this.oneofs[object.name] = object;
        object.onAdd(this);
        return clearCache(this);
      }
      return Namespace.prototype.add.call(this, object);
    }, "add");
    Type2.prototype.remove = /* @__PURE__ */ __name(function remove2(object) {
      if (object instanceof Field && object.extend === void 0) {
        if (!this.fields || this.fields[object.name] !== object)
          throw Error(object + " is not a member of " + this);
        delete this.fields[object.name];
        object.parent = null;
        object.onRemove(this);
        return clearCache(this);
      }
      if (object instanceof OneOf) {
        if (!this.oneofs || this.oneofs[object.name] !== object)
          throw Error(object + " is not a member of " + this);
        delete this.oneofs[object.name];
        object.parent = null;
        object.onRemove(this);
        return clearCache(this);
      }
      return Namespace.prototype.remove.call(this, object);
    }, "remove");
    Type2.prototype.isReservedId = /* @__PURE__ */ __name(function isReservedId(id) {
      return Namespace.isReservedId(this.reserved, id);
    }, "isReservedId");
    Type2.prototype.isReservedName = /* @__PURE__ */ __name(function isReservedName(name3) {
      return Namespace.isReservedName(this.reserved, name3);
    }, "isReservedName");
    Type2.prototype.create = /* @__PURE__ */ __name(function create3(properties) {
      return new this.ctor(properties);
    }, "create");
    Type2.prototype.setup = /* @__PURE__ */ __name(function setup() {
      var fullName = this.fullName, types3 = [];
      for (var i = 0; i < /* initializes */
      this.fieldsArray.length; ++i)
        types3.push(this._fieldsArray[i].resolve().resolvedType);
      this.encode = encoder(this)({
        Writer,
        types: types3,
        util: util4
      });
      this.decode = decoder(this)({
        Reader,
        types: types3,
        util: util4
      });
      this.verify = verifier(this)({
        types: types3,
        util: util4
      });
      this.fromObject = converter.fromObject(this)({
        types: types3,
        util: util4
      });
      this.toObject = converter.toObject(this)({
        types: types3,
        util: util4
      });
      var wrapper = wrappers[fullName];
      if (wrapper) {
        var originalThis = Object.create(this);
        originalThis.fromObject = this.fromObject;
        this.fromObject = wrapper.fromObject.bind(originalThis);
        originalThis.toObject = this.toObject;
        this.toObject = wrapper.toObject.bind(originalThis);
      }
      return this;
    }, "setup");
    Type2.prototype.encode = /* @__PURE__ */ __name(function encode_setup(message, writer) {
      return this.setup().encode(message, writer);
    }, "encode_setup");
    Type2.prototype.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
      return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();
    }, "encodeDelimited");
    Type2.prototype.decode = /* @__PURE__ */ __name(function decode_setup(reader, length) {
      return this.setup().decode(reader, length);
    }, "decode_setup");
    Type2.prototype.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
      if (!(reader instanceof Reader))
        reader = Reader.create(reader);
      return this.decode(reader, reader.uint32());
    }, "decodeDelimited");
    Type2.prototype.verify = /* @__PURE__ */ __name(function verify_setup(message) {
      return this.setup().verify(message);
    }, "verify_setup");
    Type2.prototype.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
      return this.setup().fromObject(object);
    }, "fromObject");
    Type2.prototype.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
      return this.setup().toObject(message, options2);
    }, "toObject");
    Type2.d = /* @__PURE__ */ __name(function decorateType(typeName) {
      return /* @__PURE__ */ __name(function typeDecorator(target) {
        util4.decorateType(target, typeName);
      }, "typeDecorator");
    }, "decorateType");
  }
});

// node_modules/protobufjs/src/root.js
var require_root = __commonJS({
  "node_modules/protobufjs/src/root.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Root2;
    var Namespace = require_namespace();
    ((Root2.prototype = Object.create(Namespace.prototype)).constructor = Root2).className = "Root";
    var Field = require_field();
    var Enum = require_enum3();
    var OneOf = require_oneof();
    var util4 = require_util11();
    var Type2;
    var parse12;
    var common;
    function Root2(options2) {
      Namespace.call(this, "", options2);
      this.deferred = [];
      this.files = [];
      this._edition = "proto2";
      this._fullyQualifiedObjects = {};
    }
    __name(Root2, "Root");
    Root2.fromJSON = /* @__PURE__ */ __name(function fromJSON(json2, root) {
      if (!root)
        root = new Root2();
      if (json2.options)
        root.setOptions(json2.options);
      return root.addJSON(json2.nested).resolveAll();
    }, "fromJSON");
    Root2.prototype.resolvePath = util4.path.resolve;
    Root2.prototype.fetch = util4.fetch;
    function SYNC() {
    }
    __name(SYNC, "SYNC");
    Root2.prototype.load = /* @__PURE__ */ __name(function load(filename, options2, callback) {
      if (typeof options2 === "function") {
        callback = options2;
        options2 = void 0;
      }
      var self2 = this;
      if (!callback) {
        return util4.asPromise(load, self2, filename, options2);
      }
      var sync2 = callback === SYNC;
      function finish(err, root) {
        if (!callback) {
          return;
        }
        if (sync2) {
          throw err;
        }
        if (root) {
          root.resolveAll();
        }
        var cb = callback;
        callback = null;
        cb(err, root);
      }
      __name(finish, "finish");
      function getBundledFileName(filename2) {
        var idx = filename2.lastIndexOf("google/protobuf/");
        if (idx > -1) {
          var altname = filename2.substring(idx);
          if (altname in common) return altname;
        }
        return null;
      }
      __name(getBundledFileName, "getBundledFileName");
      function process51(filename2, source2) {
        try {
          if (util4.isString(source2) && source2.charAt(0) === "{")
            source2 = JSON.parse(source2);
          if (!util4.isString(source2))
            self2.setOptions(source2.options).addJSON(source2.nested);
          else {
            parse12.filename = filename2;
            var parsed = parse12(source2, self2, options2), resolved2, i2 = 0;
            if (parsed.imports) {
              for (; i2 < parsed.imports.length; ++i2)
                if (resolved2 = getBundledFileName(parsed.imports[i2]) || self2.resolvePath(filename2, parsed.imports[i2]))
                  fetch2(resolved2);
            }
            if (parsed.weakImports) {
              for (i2 = 0; i2 < parsed.weakImports.length; ++i2)
                if (resolved2 = getBundledFileName(parsed.weakImports[i2]) || self2.resolvePath(filename2, parsed.weakImports[i2]))
                  fetch2(resolved2, true);
            }
          }
        } catch (err) {
          finish(err);
        }
        if (!sync2 && !queued) {
          finish(null, self2);
        }
      }
      __name(process51, "process");
      function fetch2(filename2, weak) {
        filename2 = getBundledFileName(filename2) || filename2;
        if (self2.files.indexOf(filename2) > -1) {
          return;
        }
        self2.files.push(filename2);
        if (filename2 in common) {
          if (sync2) {
            process51(filename2, common[filename2]);
          } else {
            ++queued;
            setTimeout(function() {
              --queued;
              process51(filename2, common[filename2]);
            });
          }
          return;
        }
        if (sync2) {
          var source2;
          try {
            source2 = util4.fs.readFileSync(filename2).toString("utf8");
          } catch (err) {
            if (!weak)
              finish(err);
            return;
          }
          process51(filename2, source2);
        } else {
          ++queued;
          self2.fetch(filename2, function(err, source3) {
            --queued;
            if (!callback) {
              return;
            }
            if (err) {
              if (!weak)
                finish(err);
              else if (!queued)
                finish(null, self2);
              return;
            }
            process51(filename2, source3);
          });
        }
      }
      __name(fetch2, "fetch");
      var queued = 0;
      if (util4.isString(filename)) {
        filename = [filename];
      }
      for (var i = 0, resolved; i < filename.length; ++i)
        if (resolved = self2.resolvePath("", filename[i]))
          fetch2(resolved);
      if (sync2) {
        self2.resolveAll();
        return self2;
      }
      if (!queued) {
        finish(null, self2);
      }
      return self2;
    }, "load");
    Root2.prototype.loadSync = /* @__PURE__ */ __name(function loadSync(filename, options2) {
      if (!util4.isNode)
        throw Error("not supported");
      return this.load(filename, options2, SYNC);
    }, "loadSync");
    Root2.prototype.resolveAll = /* @__PURE__ */ __name(function resolveAll() {
      if (!this._needsRecursiveResolve) return this;
      if (this.deferred.length)
        throw Error("unresolvable extensions: " + this.deferred.map(function(field) {
          return "'extend " + field.extend + "' in " + field.parent.fullName;
        }).join(", "));
      return Namespace.prototype.resolveAll.call(this);
    }, "resolveAll");
    var exposeRe = /^[A-Z]/;
    function tryHandleExtension(root, field) {
      var extendedType = field.parent.lookup(field.extend);
      if (extendedType) {
        var sisterField = new Field(field.fullName, field.id, field.type, field.rule, void 0, field.options);
        if (extendedType.get(sisterField.name)) {
          return true;
        }
        sisterField.declaringField = field;
        field.extensionField = sisterField;
        extendedType.add(sisterField);
        return true;
      }
      return false;
    }
    __name(tryHandleExtension, "tryHandleExtension");
    Root2.prototype._handleAdd = /* @__PURE__ */ __name(function _handleAdd(object) {
      if (object instanceof Field) {
        if (
          /* an extension field (implies not part of a oneof) */
          object.extend !== void 0 && /* not already handled */
          !object.extensionField
        ) {
          if (!tryHandleExtension(this, object))
            this.deferred.push(object);
        }
      } else if (object instanceof Enum) {
        if (exposeRe.test(object.name))
          object.parent[object.name] = object.values;
      } else if (!(object instanceof OneOf)) {
        if (object instanceof Type2)
          for (var i = 0; i < this.deferred.length; )
            if (tryHandleExtension(this, this.deferred[i]))
              this.deferred.splice(i, 1);
            else
              ++i;
        for (var j = 0; j < /* initializes */
        object.nestedArray.length; ++j)
          this._handleAdd(object._nestedArray[j]);
        if (exposeRe.test(object.name))
          object.parent[object.name] = object;
      }
      if (object instanceof Type2 || object instanceof Enum || object instanceof Field) {
        this._fullyQualifiedObjects[object.fullName] = object;
      }
    }, "_handleAdd");
    Root2.prototype._handleRemove = /* @__PURE__ */ __name(function _handleRemove(object) {
      if (object instanceof Field) {
        if (
          /* an extension field */
          object.extend !== void 0
        ) {
          if (
            /* already handled */
            object.extensionField
          ) {
            object.extensionField.parent.remove(object.extensionField);
            object.extensionField = null;
          } else {
            var index = this.deferred.indexOf(object);
            if (index > -1)
              this.deferred.splice(index, 1);
          }
        }
      } else if (object instanceof Enum) {
        if (exposeRe.test(object.name))
          delete object.parent[object.name];
      } else if (object instanceof Namespace) {
        for (var i = 0; i < /* initializes */
        object.nestedArray.length; ++i)
          this._handleRemove(object._nestedArray[i]);
        if (exposeRe.test(object.name))
          delete object.parent[object.name];
      }
      delete this._fullyQualifiedObjects[object.fullName];
    }, "_handleRemove");
    Root2._configure = function(Type_, parse_2, common_) {
      Type2 = Type_;
      parse12 = parse_2;
      common = common_;
    };
  }
});

// node_modules/protobufjs/src/util.js
var require_util11 = __commonJS({
  "node_modules/protobufjs/src/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var util4 = module2.exports = require_minimal();
    var roots = require_roots();
    var Type2;
    var Enum;
    util4.codegen = require_codegen3();
    util4.fetch = require_fetch2();
    util4.path = require_path();
    util4.fs = util4.inquire("fs");
    util4.toArray = /* @__PURE__ */ __name(function toArray(object) {
      if (object) {
        var keys = Object.keys(object), array = new Array(keys.length), index = 0;
        while (index < keys.length)
          array[index] = object[keys[index++]];
        return array;
      }
      return [];
    }, "toArray");
    util4.toObject = /* @__PURE__ */ __name(function toObject(array) {
      var object = {}, index = 0;
      while (index < array.length) {
        var key = array[index++], val = array[index++];
        if (val !== void 0)
          object[key] = val;
      }
      return object;
    }, "toObject");
    var safePropBackslashRe = /\\/g;
    var safePropQuoteRe = /"/g;
    util4.isReserved = /* @__PURE__ */ __name(function isReserved(name3) {
      return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name3);
    }, "isReserved");
    util4.safeProp = /* @__PURE__ */ __name(function safeProp(prop) {
      if (!/^[$\w_]+$/.test(prop) || util4.isReserved(prop))
        return '["' + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, '\\"') + '"]';
      return "." + prop;
    }, "safeProp");
    util4.ucFirst = /* @__PURE__ */ __name(function ucFirst(str2) {
      return str2.charAt(0).toUpperCase() + str2.substring(1);
    }, "ucFirst");
    var camelCaseRe = /_([a-z])/g;
    util4.camelCase = /* @__PURE__ */ __name(function camelCase3(str2) {
      return str2.substring(0, 1) + str2.substring(1).replace(camelCaseRe, function($0, $1) {
        return $1.toUpperCase();
      });
    }, "camelCase");
    util4.compareFieldsById = /* @__PURE__ */ __name(function compareFieldsById(a, b) {
      return a.id - b.id;
    }, "compareFieldsById");
    util4.decorateType = /* @__PURE__ */ __name(function decorateType(ctor, typeName) {
      if (ctor.$type) {
        if (typeName && ctor.$type.name !== typeName) {
          util4.decorateRoot.remove(ctor.$type);
          ctor.$type.name = typeName;
          util4.decorateRoot.add(ctor.$type);
        }
        return ctor.$type;
      }
      if (!Type2)
        Type2 = require_type();
      var type = new Type2(typeName || ctor.name);
      util4.decorateRoot.add(type);
      type.ctor = ctor;
      Object.defineProperty(ctor, "$type", { value: type, enumerable: false });
      Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false });
      return type;
    }, "decorateType");
    var decorateEnumIndex = 0;
    util4.decorateEnum = /* @__PURE__ */ __name(function decorateEnum(object) {
      if (object.$type)
        return object.$type;
      if (!Enum)
        Enum = require_enum3();
      var enm = new Enum("Enum" + decorateEnumIndex++, object);
      util4.decorateRoot.add(enm);
      Object.defineProperty(object, "$type", { value: enm, enumerable: false });
      return enm;
    }, "decorateEnum");
    util4.setProperty = /* @__PURE__ */ __name(function setProperty2(dst, path108, value, ifNotSet) {
      function setProp(dst2, path109, value2) {
        var part = path109.shift();
        if (part === "__proto__" || part === "prototype") {
          return dst2;
        }
        if (path109.length > 0) {
          dst2[part] = setProp(dst2[part] || {}, path109, value2);
        } else {
          var prevValue = dst2[part];
          if (prevValue && ifNotSet)
            return dst2;
          if (prevValue)
            value2 = [].concat(prevValue).concat(value2);
          dst2[part] = value2;
        }
        return dst2;
      }
      __name(setProp, "setProp");
      if (typeof dst !== "object")
        throw TypeError("dst must be an object");
      if (!path108)
        throw TypeError("path must be specified");
      path108 = path108.split(".");
      return setProp(dst, path108, value);
    }, "setProperty");
    Object.defineProperty(util4, "decorateRoot", {
      get: /* @__PURE__ */ __name(function() {
        return roots["decorated"] || (roots["decorated"] = new (require_root())());
      }, "get")
    });
  }
});

// node_modules/protobufjs/src/types.js
var require_types3 = __commonJS({
  "node_modules/protobufjs/src/types.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var types3 = exports2;
    var util4 = require_util11();
    var s2 = [
      "double",
      // 0
      "float",
      // 1
      "int32",
      // 2
      "uint32",
      // 3
      "sint32",
      // 4
      "fixed32",
      // 5
      "sfixed32",
      // 6
      "int64",
      // 7
      "uint64",
      // 8
      "sint64",
      // 9
      "fixed64",
      // 10
      "sfixed64",
      // 11
      "bool",
      // 12
      "string",
      // 13
      "bytes"
      // 14
    ];
    function bake(values, offset) {
      var i = 0, o2 = {};
      offset |= 0;
      while (i < values.length) o2[s2[i + offset]] = values[i++];
      return o2;
    }
    __name(bake, "bake");
    types3.basic = bake([
      /* double   */
      1,
      /* float    */
      5,
      /* int32    */
      0,
      /* uint32   */
      0,
      /* sint32   */
      0,
      /* fixed32  */
      5,
      /* sfixed32 */
      5,
      /* int64    */
      0,
      /* uint64   */
      0,
      /* sint64   */
      0,
      /* fixed64  */
      1,
      /* sfixed64 */
      1,
      /* bool     */
      0,
      /* string   */
      2,
      /* bytes    */
      2
    ]);
    types3.defaults = bake([
      /* double   */
      0,
      /* float    */
      0,
      /* int32    */
      0,
      /* uint32   */
      0,
      /* sint32   */
      0,
      /* fixed32  */
      0,
      /* sfixed32 */
      0,
      /* int64    */
      0,
      /* uint64   */
      0,
      /* sint64   */
      0,
      /* fixed64  */
      0,
      /* sfixed64 */
      0,
      /* bool     */
      false,
      /* string   */
      "",
      /* bytes    */
      util4.emptyArray,
      /* message  */
      null
    ]);
    types3.long = bake([
      /* int64    */
      0,
      /* uint64   */
      0,
      /* sint64   */
      0,
      /* fixed64  */
      1,
      /* sfixed64 */
      1
    ], 7);
    types3.mapKey = bake([
      /* int32    */
      0,
      /* uint32   */
      0,
      /* sint32   */
      0,
      /* fixed32  */
      5,
      /* sfixed32 */
      5,
      /* int64    */
      0,
      /* uint64   */
      0,
      /* sint64   */
      0,
      /* fixed64  */
      1,
      /* sfixed64 */
      1,
      /* bool     */
      0,
      /* string   */
      2
    ], 2);
    types3.packed = bake([
      /* double   */
      1,
      /* float    */
      5,
      /* int32    */
      0,
      /* uint32   */
      0,
      /* sint32   */
      0,
      /* fixed32  */
      5,
      /* sfixed32 */
      5,
      /* int64    */
      0,
      /* uint64   */
      0,
      /* sint64   */
      0,
      /* fixed64  */
      1,
      /* sfixed64 */
      1,
      /* bool     */
      0
    ]);
  }
});

// node_modules/protobufjs/src/field.js
var require_field = __commonJS({
  "node_modules/protobufjs/src/field.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Field;
    var ReflectionObject = require_object();
    ((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field";
    var Enum = require_enum3();
    var types3 = require_types3();
    var util4 = require_util11();
    var Type2;
    var ruleRe = /^required|optional|repeated$/;
    Field.fromJSON = /* @__PURE__ */ __name(function fromJSON(name3, json2) {
      var field = new Field(name3, json2.id, json2.type, json2.rule, json2.extend, json2.options, json2.comment);
      if (json2.edition)
        field._edition = json2.edition;
      field._defaultEdition = "proto3";
      return field;
    }, "fromJSON");
    function Field(name3, id, type, rule, extend, options2, comment) {
      if (util4.isObject(rule)) {
        comment = extend;
        options2 = rule;
        rule = extend = void 0;
      } else if (util4.isObject(extend)) {
        comment = options2;
        options2 = extend;
        extend = void 0;
      }
      ReflectionObject.call(this, name3, options2);
      if (!util4.isInteger(id) || id < 0)
        throw TypeError("id must be a non-negative integer");
      if (!util4.isString(type))
        throw TypeError("type must be a string");
      if (rule !== void 0 && !ruleRe.test(rule = rule.toString().toLowerCase()))
        throw TypeError("rule must be a string rule");
      if (extend !== void 0 && !util4.isString(extend))
        throw TypeError("extend must be a string");
      if (rule === "proto3_optional") {
        rule = "optional";
      }
      this.rule = rule && rule !== "optional" ? rule : void 0;
      this.type = type;
      this.id = id;
      this.extend = extend || void 0;
      this.repeated = rule === "repeated";
      this.map = false;
      this.message = null;
      this.partOf = null;
      this.typeDefault = null;
      this.defaultValue = null;
      this.long = util4.Long ? types3.long[type] !== void 0 : (
        /* istanbul ignore next */
        false
      );
      this.bytes = type === "bytes";
      this.resolvedType = null;
      this.extensionField = null;
      this.declaringField = null;
      this.comment = comment;
    }
    __name(Field, "Field");
    Object.defineProperty(Field.prototype, "required", {
      get: /* @__PURE__ */ __name(function() {
        return this._features.field_presence === "LEGACY_REQUIRED";
      }, "get")
    });
    Object.defineProperty(Field.prototype, "optional", {
      get: /* @__PURE__ */ __name(function() {
        return !this.required;
      }, "get")
    });
    Object.defineProperty(Field.prototype, "delimited", {
      get: /* @__PURE__ */ __name(function() {
        return this.resolvedType instanceof Type2 && this._features.message_encoding === "DELIMITED";
      }, "get")
    });
    Object.defineProperty(Field.prototype, "packed", {
      get: /* @__PURE__ */ __name(function() {
        return this._features.repeated_field_encoding === "PACKED";
      }, "get")
    });
    Object.defineProperty(Field.prototype, "hasPresence", {
      get: /* @__PURE__ */ __name(function() {
        if (this.repeated || this.map) {
          return false;
        }
        return this.partOf || // oneofs
        this.declaringField || this.extensionField || // extensions
        this._features.field_presence !== "IMPLICIT";
      }, "get")
    });
    Field.prototype.setOption = /* @__PURE__ */ __name(function setOption(name3, value, ifNotSet) {
      return ReflectionObject.prototype.setOption.call(this, name3, value, ifNotSet);
    }, "setOption");
    Field.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util4.toObject([
        "edition",
        this._editionToJSON(),
        "rule",
        this.rule !== "optional" && this.rule || void 0,
        "type",
        this.type,
        "id",
        this.id,
        "extend",
        this.extend,
        "options",
        this.options,
        "comment",
        keepComments ? this.comment : void 0
      ]);
    }, "toJSON");
    Field.prototype.resolve = /* @__PURE__ */ __name(function resolve24() {
      if (this.resolved)
        return this;
      if ((this.typeDefault = types3.defaults[this.type]) === void 0) {
        this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);
        if (this.resolvedType instanceof Type2)
          this.typeDefault = null;
        else
          this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]];
      } else if (this.options && this.options.proto3_optional) {
        this.typeDefault = null;
      }
      if (this.options && this.options["default"] != null) {
        this.typeDefault = this.options["default"];
        if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string")
          this.typeDefault = this.resolvedType.values[this.typeDefault];
      }
      if (this.options) {
        if (this.options.packed !== void 0 && this.resolvedType && !(this.resolvedType instanceof Enum))
          delete this.options.packed;
        if (!Object.keys(this.options).length)
          this.options = void 0;
      }
      if (this.long) {
        this.typeDefault = util4.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u");
        if (Object.freeze)
          Object.freeze(this.typeDefault);
      } else if (this.bytes && typeof this.typeDefault === "string") {
        var buf;
        if (util4.base64.test(this.typeDefault))
          util4.base64.decode(this.typeDefault, buf = util4.newBuffer(util4.base64.length(this.typeDefault)), 0);
        else
          util4.utf8.write(this.typeDefault, buf = util4.newBuffer(util4.utf8.length(this.typeDefault)), 0);
        this.typeDefault = buf;
      }
      if (this.map)
        this.defaultValue = util4.emptyObject;
      else if (this.repeated)
        this.defaultValue = util4.emptyArray;
      else
        this.defaultValue = this.typeDefault;
      if (this.parent instanceof Type2)
        this.parent.ctor.prototype[this.name] = this.defaultValue;
      return ReflectionObject.prototype.resolve.call(this);
    }, "resolve");
    Field.prototype._inferLegacyProtoFeatures = /* @__PURE__ */ __name(function _inferLegacyProtoFeatures(edition) {
      if (edition !== "proto2" && edition !== "proto3") {
        return {};
      }
      var features = {};
      if (this.rule === "required") {
        features.field_presence = "LEGACY_REQUIRED";
      }
      if (this.parent && types3.defaults[this.type] === void 0) {
        var type = this.parent.get(this.type.split(".").pop());
        if (type && type instanceof Type2 && type.group) {
          features.message_encoding = "DELIMITED";
        }
      }
      if (this.getOption("packed") === true) {
        features.repeated_field_encoding = "PACKED";
      } else if (this.getOption("packed") === false) {
        features.repeated_field_encoding = "EXPANDED";
      }
      return features;
    }, "_inferLegacyProtoFeatures");
    Field.prototype._resolveFeatures = /* @__PURE__ */ __name(function _resolveFeatures(edition) {
      return ReflectionObject.prototype._resolveFeatures.call(this, this._edition || edition);
    }, "_resolveFeatures");
    Field.d = /* @__PURE__ */ __name(function decorateField(fieldId, fieldType, fieldRule, defaultValue) {
      if (typeof fieldType === "function")
        fieldType = util4.decorateType(fieldType).name;
      else if (fieldType && typeof fieldType === "object")
        fieldType = util4.decorateEnum(fieldType).name;
      return /* @__PURE__ */ __name(function fieldDecorator(prototype, fieldName) {
        util4.decorateType(prototype.constructor).add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue }));
      }, "fieldDecorator");
    }, "decorateField");
    Field._configure = /* @__PURE__ */ __name(function configure(Type_) {
      Type2 = Type_;
    }, "configure");
  }
});

// node_modules/protobufjs/src/oneof.js
var require_oneof = __commonJS({
  "node_modules/protobufjs/src/oneof.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = OneOf;
    var ReflectionObject = require_object();
    ((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf";
    var Field = require_field();
    var util4 = require_util11();
    function OneOf(name3, fieldNames, options2, comment) {
      if (!Array.isArray(fieldNames)) {
        options2 = fieldNames;
        fieldNames = void 0;
      }
      ReflectionObject.call(this, name3, options2);
      if (!(fieldNames === void 0 || Array.isArray(fieldNames)))
        throw TypeError("fieldNames must be an Array");
      this.oneof = fieldNames || [];
      this.fieldsArray = [];
      this.comment = comment;
    }
    __name(OneOf, "OneOf");
    OneOf.fromJSON = /* @__PURE__ */ __name(function fromJSON(name3, json2) {
      return new OneOf(name3, json2.oneof, json2.options, json2.comment);
    }, "fromJSON");
    OneOf.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util4.toObject([
        "options",
        this.options,
        "oneof",
        this.oneof,
        "comment",
        keepComments ? this.comment : void 0
      ]);
    }, "toJSON");
    function addFieldsToParent(oneof) {
      if (oneof.parent) {
        for (var i = 0; i < oneof.fieldsArray.length; ++i)
          if (!oneof.fieldsArray[i].parent)
            oneof.parent.add(oneof.fieldsArray[i]);
      }
    }
    __name(addFieldsToParent, "addFieldsToParent");
    OneOf.prototype.add = /* @__PURE__ */ __name(function add(field) {
      if (!(field instanceof Field))
        throw TypeError("field must be a Field");
      if (field.parent && field.parent !== this.parent)
        field.parent.remove(field);
      this.oneof.push(field.name);
      this.fieldsArray.push(field);
      field.partOf = this;
      addFieldsToParent(this);
      return this;
    }, "add");
    OneOf.prototype.remove = /* @__PURE__ */ __name(function remove2(field) {
      if (!(field instanceof Field))
        throw TypeError("field must be a Field");
      var index = this.fieldsArray.indexOf(field);
      if (index < 0)
        throw Error(field + " is not a member of " + this);
      this.fieldsArray.splice(index, 1);
      index = this.oneof.indexOf(field.name);
      if (index > -1)
        this.oneof.splice(index, 1);
      field.partOf = null;
      return this;
    }, "remove");
    OneOf.prototype.onAdd = /* @__PURE__ */ __name(function onAdd(parent) {
      ReflectionObject.prototype.onAdd.call(this, parent);
      var self2 = this;
      for (var i = 0; i < this.oneof.length; ++i) {
        var field = parent.get(this.oneof[i]);
        if (field && !field.partOf) {
          field.partOf = self2;
          self2.fieldsArray.push(field);
        }
      }
      addFieldsToParent(this);
    }, "onAdd");
    OneOf.prototype.onRemove = /* @__PURE__ */ __name(function onRemove(parent) {
      for (var i = 0, field; i < this.fieldsArray.length; ++i)
        if ((field = this.fieldsArray[i]).parent)
          field.parent.remove(field);
      ReflectionObject.prototype.onRemove.call(this, parent);
    }, "onRemove");
    Object.defineProperty(OneOf.prototype, "isProto3Optional", {
      get: /* @__PURE__ */ __name(function() {
        if (this.fieldsArray == null || this.fieldsArray.length !== 1) {
          return false;
        }
        var field = this.fieldsArray[0];
        return field.options != null && field.options["proto3_optional"] === true;
      }, "get")
    });
    OneOf.d = /* @__PURE__ */ __name(function decorateOneOf() {
      var fieldNames = new Array(arguments.length), index = 0;
      while (index < arguments.length)
        fieldNames[index] = arguments[index++];
      return /* @__PURE__ */ __name(function oneOfDecorator(prototype, oneofName) {
        util4.decorateType(prototype.constructor).add(new OneOf(oneofName, fieldNames));
        Object.defineProperty(prototype, oneofName, {
          get: util4.oneOfGetter(fieldNames),
          set: util4.oneOfSetter(fieldNames)
        });
      }, "oneOfDecorator");
    }, "decorateOneOf");
  }
});

// node_modules/protobufjs/src/object.js
var require_object = __commonJS({
  "node_modules/protobufjs/src/object.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = ReflectionObject;
    ReflectionObject.className = "ReflectionObject";
    var OneOf = require_oneof();
    var util4 = require_util11();
    var Root2;
    var editions2023Defaults = { enum_type: "OPEN", field_presence: "EXPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY" };
    var proto2Defaults = { enum_type: "CLOSED", field_presence: "EXPLICIT", json_format: "LEGACY_BEST_EFFORT", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "EXPANDED", utf8_validation: "NONE" };
    var proto3Defaults = { enum_type: "OPEN", field_presence: "IMPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY" };
    function ReflectionObject(name3, options2) {
      if (!util4.isString(name3))
        throw TypeError("name must be a string");
      if (options2 && !util4.isObject(options2))
        throw TypeError("options must be an object");
      this.options = options2;
      this.parsedOptions = null;
      this.name = name3;
      this._edition = null;
      this._defaultEdition = "proto2";
      this._features = {};
      this._featuresResolved = false;
      this.parent = null;
      this.resolved = false;
      this.comment = null;
      this.filename = null;
    }
    __name(ReflectionObject, "ReflectionObject");
    Object.defineProperties(ReflectionObject.prototype, {
      /**
       * Reference to the root namespace.
       * @name ReflectionObject#root
       * @type {Root}
       * @readonly
       */
      root: {
        get: /* @__PURE__ */ __name(function() {
          var ptr = this;
          while (ptr.parent !== null)
            ptr = ptr.parent;
          return ptr;
        }, "get")
      },
      /**
       * Full name including leading dot.
       * @name ReflectionObject#fullName
       * @type {string}
       * @readonly
       */
      fullName: {
        get: /* @__PURE__ */ __name(function() {
          var path108 = [this.name], ptr = this.parent;
          while (ptr) {
            path108.unshift(ptr.name);
            ptr = ptr.parent;
          }
          return path108.join(".");
        }, "get")
      }
    });
    ReflectionObject.prototype.toJSON = /* istanbul ignore next */
    /* @__PURE__ */ __name(function toJSON() {
      throw Error();
    }, "toJSON");
    ReflectionObject.prototype.onAdd = /* @__PURE__ */ __name(function onAdd(parent) {
      if (this.parent && this.parent !== parent)
        this.parent.remove(this);
      this.parent = parent;
      this.resolved = false;
      var root = parent.root;
      if (root instanceof Root2)
        root._handleAdd(this);
    }, "onAdd");
    ReflectionObject.prototype.onRemove = /* @__PURE__ */ __name(function onRemove(parent) {
      var root = parent.root;
      if (root instanceof Root2)
        root._handleRemove(this);
      this.parent = null;
      this.resolved = false;
    }, "onRemove");
    ReflectionObject.prototype.resolve = /* @__PURE__ */ __name(function resolve24() {
      if (this.resolved)
        return this;
      if (this.root instanceof Root2)
        this.resolved = true;
      return this;
    }, "resolve");
    ReflectionObject.prototype._resolveFeaturesRecursive = /* @__PURE__ */ __name(function _resolveFeaturesRecursive(edition) {
      return this._resolveFeatures(this._edition || edition);
    }, "_resolveFeaturesRecursive");
    ReflectionObject.prototype._resolveFeatures = /* @__PURE__ */ __name(function _resolveFeatures(edition) {
      if (this._featuresResolved) {
        return;
      }
      var defaults3 = {};
      if (!edition) {
        throw new Error("Unknown edition for " + this.fullName);
      }
      var protoFeatures = Object.assign(
        this.options ? Object.assign({}, this.options.features) : {},
        this._inferLegacyProtoFeatures(edition)
      );
      if (this._edition) {
        if (edition === "proto2") {
          defaults3 = Object.assign({}, proto2Defaults);
        } else if (edition === "proto3") {
          defaults3 = Object.assign({}, proto3Defaults);
        } else if (edition === "2023") {
          defaults3 = Object.assign({}, editions2023Defaults);
        } else {
          throw new Error("Unknown edition: " + edition);
        }
        this._features = Object.assign(defaults3, protoFeatures || {});
        this._featuresResolved = true;
        return;
      }
      if (this.partOf instanceof OneOf) {
        var lexicalParentFeaturesCopy = Object.assign({}, this.partOf._features);
        this._features = Object.assign(lexicalParentFeaturesCopy, protoFeatures || {});
      } else if (this.declaringField) {
      } else if (this.parent) {
        var parentFeaturesCopy = Object.assign({}, this.parent._features);
        this._features = Object.assign(parentFeaturesCopy, protoFeatures || {});
      } else {
        throw new Error("Unable to find a parent for " + this.fullName);
      }
      if (this.extensionField) {
        this.extensionField._features = this._features;
      }
      this._featuresResolved = true;
    }, "_resolveFeatures");
    ReflectionObject.prototype._inferLegacyProtoFeatures = /* @__PURE__ */ __name(function _inferLegacyProtoFeatures() {
      return {};
    }, "_inferLegacyProtoFeatures");
    ReflectionObject.prototype.getOption = /* @__PURE__ */ __name(function getOption(name3) {
      if (this.options)
        return this.options[name3];
      return void 0;
    }, "getOption");
    ReflectionObject.prototype.setOption = /* @__PURE__ */ __name(function setOption(name3, value, ifNotSet) {
      if (!this.options)
        this.options = {};
      if (/^features\./.test(name3)) {
        util4.setProperty(this.options, name3, value, ifNotSet);
      } else if (!ifNotSet || this.options[name3] === void 0) {
        if (this.getOption(name3) !== value) this.resolved = false;
        this.options[name3] = value;
      }
      return this;
    }, "setOption");
    ReflectionObject.prototype.setParsedOption = /* @__PURE__ */ __name(function setParsedOption(name3, value, propName) {
      if (!this.parsedOptions) {
        this.parsedOptions = [];
      }
      var parsedOptions = this.parsedOptions;
      if (propName) {
        var opt = parsedOptions.find(function(opt2) {
          return Object.prototype.hasOwnProperty.call(opt2, name3);
        });
        if (opt) {
          var newValue = opt[name3];
          util4.setProperty(newValue, propName, value);
        } else {
          opt = {};
          opt[name3] = util4.setProperty({}, propName, value);
          parsedOptions.push(opt);
        }
      } else {
        var newOpt = {};
        newOpt[name3] = value;
        parsedOptions.push(newOpt);
      }
      return this;
    }, "setParsedOption");
    ReflectionObject.prototype.setOptions = /* @__PURE__ */ __name(function setOptions2(options2, ifNotSet) {
      if (options2)
        for (var keys = Object.keys(options2), i = 0; i < keys.length; ++i)
          this.setOption(keys[i], options2[keys[i]], ifNotSet);
      return this;
    }, "setOptions");
    ReflectionObject.prototype.toString = /* @__PURE__ */ __name(function toString() {
      var className = this.constructor.className, fullName = this.fullName;
      if (fullName.length)
        return className + " " + fullName;
      return className;
    }, "toString");
    ReflectionObject.prototype._editionToJSON = /* @__PURE__ */ __name(function _editionToJSON() {
      if (!this._edition || this._edition === "proto3") {
        return void 0;
      }
      return this._edition;
    }, "_editionToJSON");
    ReflectionObject._configure = function(Root_) {
      Root2 = Root_;
    };
  }
});

// node_modules/protobufjs/src/enum.js
var require_enum3 = __commonJS({
  "node_modules/protobufjs/src/enum.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Enum;
    var ReflectionObject = require_object();
    ((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum";
    var Namespace = require_namespace();
    var util4 = require_util11();
    function Enum(name3, values, options2, comment, comments, valuesOptions) {
      ReflectionObject.call(this, name3, options2);
      if (values && typeof values !== "object")
        throw TypeError("values must be an object");
      this.valuesById = {};
      this.values = Object.create(this.valuesById);
      this.comment = comment;
      this.comments = comments || {};
      this.valuesOptions = valuesOptions;
      this._valuesFeatures = {};
      this.reserved = void 0;
      if (values) {
        for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)
          if (typeof values[keys[i]] === "number")
            this.valuesById[this.values[keys[i]] = values[keys[i]]] = keys[i];
      }
    }
    __name(Enum, "Enum");
    Enum.prototype._resolveFeatures = /* @__PURE__ */ __name(function _resolveFeatures(edition) {
      edition = this._edition || edition;
      ReflectionObject.prototype._resolveFeatures.call(this, edition);
      Object.keys(this.values).forEach((key) => {
        var parentFeaturesCopy = Object.assign({}, this._features);
        this._valuesFeatures[key] = Object.assign(parentFeaturesCopy, this.valuesOptions && this.valuesOptions[key] && this.valuesOptions[key].features);
      });
      return this;
    }, "_resolveFeatures");
    Enum.fromJSON = /* @__PURE__ */ __name(function fromJSON(name3, json2) {
      var enm = new Enum(name3, json2.values, json2.options, json2.comment, json2.comments);
      enm.reserved = json2.reserved;
      if (json2.edition)
        enm._edition = json2.edition;
      enm._defaultEdition = "proto3";
      return enm;
    }, "fromJSON");
    Enum.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util4.toObject([
        "edition",
        this._editionToJSON(),
        "options",
        this.options,
        "valuesOptions",
        this.valuesOptions,
        "values",
        this.values,
        "reserved",
        this.reserved && this.reserved.length ? this.reserved : void 0,
        "comment",
        keepComments ? this.comment : void 0,
        "comments",
        keepComments ? this.comments : void 0
      ]);
    }, "toJSON");
    Enum.prototype.add = /* @__PURE__ */ __name(function add(name3, id, comment, options2) {
      if (!util4.isString(name3))
        throw TypeError("name must be a string");
      if (!util4.isInteger(id))
        throw TypeError("id must be an integer");
      if (this.values[name3] !== void 0)
        throw Error("duplicate name '" + name3 + "' in " + this);
      if (this.isReservedId(id))
        throw Error("id " + id + " is reserved in " + this);
      if (this.isReservedName(name3))
        throw Error("name '" + name3 + "' is reserved in " + this);
      if (this.valuesById[id] !== void 0) {
        if (!(this.options && this.options.allow_alias))
          throw Error("duplicate id " + id + " in " + this);
        this.values[name3] = id;
      } else
        this.valuesById[this.values[name3] = id] = name3;
      if (options2) {
        if (this.valuesOptions === void 0)
          this.valuesOptions = {};
        this.valuesOptions[name3] = options2 || null;
      }
      this.comments[name3] = comment || null;
      return this;
    }, "add");
    Enum.prototype.remove = /* @__PURE__ */ __name(function remove2(name3) {
      if (!util4.isString(name3))
        throw TypeError("name must be a string");
      var val = this.values[name3];
      if (val == null)
        throw Error("name '" + name3 + "' does not exist in " + this);
      delete this.valuesById[val];
      delete this.values[name3];
      delete this.comments[name3];
      if (this.valuesOptions)
        delete this.valuesOptions[name3];
      return this;
    }, "remove");
    Enum.prototype.isReservedId = /* @__PURE__ */ __name(function isReservedId(id) {
      return Namespace.isReservedId(this.reserved, id);
    }, "isReservedId");
    Enum.prototype.isReservedName = /* @__PURE__ */ __name(function isReservedName(name3) {
      return Namespace.isReservedName(this.reserved, name3);
    }, "isReservedName");
  }
});

// node_modules/protobufjs/src/encoder.js
var require_encoder = __commonJS({
  "node_modules/protobufjs/src/encoder.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = encoder;
    var Enum = require_enum3();
    var types3 = require_types3();
    var util4 = require_util11();
    function genTypePartial(gen, field, fieldIndex, ref) {
      return field.delimited ? gen("types[%i].encode(%s,w.uint32(%i)).uint32(%i)", fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0) : gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0);
    }
    __name(genTypePartial, "genTypePartial");
    function encoder(mtype) {
      var gen = util4.codegen(["m", "w"], mtype.name + "$encode")("if(!w)")("w=Writer.create()");
      var i, ref;
      var fields = (
        /* initializes */
        mtype.fieldsArray.slice().sort(util4.compareFieldsById)
      );
      for (var i = 0; i < fields.length; ++i) {
        var field = fields[i].resolve(), index = mtype._fieldsArray.indexOf(field), type = field.resolvedType instanceof Enum ? "int32" : field.type, wireType = types3.basic[type];
        ref = "m" + util4.safeProp(field.name);
        if (field.map) {
          gen("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){", ref)("w.uint32(%i).fork().uint32(%i).%s(ks[i])", (field.id << 3 | 2) >>> 0, 8 | types3.mapKey[field.keyType], field.keyType);
          if (wireType === void 0) gen("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref);
          else gen(".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref);
          gen("}")("}");
        } else if (field.repeated) {
          gen("if(%s!=null&&%s.length){", ref, ref);
          if (field.packed && types3.packed[type] !== void 0) {
            gen("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0)("for(var i=0;i<%s.length;++i)", ref)("w.%s(%s[i])", type, ref)("w.ldelim()");
          } else {
            gen("for(var i=0;i<%s.length;++i)", ref);
            if (wireType === void 0)
              genTypePartial(gen, field, index, ref + "[i]");
            else gen("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref);
          }
          gen("}");
        } else {
          if (field.optional) gen("if(%s!=null&&Object.hasOwnProperty.call(m,%j))", ref, field.name);
          if (wireType === void 0)
            genTypePartial(gen, field, index, ref);
          else gen("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref);
        }
      }
      return gen("return w");
    }
    __name(encoder, "encoder");
  }
});

// node_modules/protobufjs/src/index-light.js
var require_index_light = __commonJS({
  "node_modules/protobufjs/src/index-light.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var protobuf = module2.exports = require_index_minimal();
    protobuf.build = "light";
    function load(filename, root, callback) {
      if (typeof root === "function") {
        callback = root;
        root = new protobuf.Root();
      } else if (!root)
        root = new protobuf.Root();
      return root.load(filename, callback);
    }
    __name(load, "load");
    protobuf.load = load;
    function loadSync(filename, root) {
      if (!root)
        root = new protobuf.Root();
      return root.loadSync(filename);
    }
    __name(loadSync, "loadSync");
    protobuf.loadSync = loadSync;
    protobuf.encoder = require_encoder();
    protobuf.decoder = require_decoder();
    protobuf.verifier = require_verifier();
    protobuf.converter = require_converter();
    protobuf.ReflectionObject = require_object();
    protobuf.Namespace = require_namespace();
    protobuf.Root = require_root();
    protobuf.Enum = require_enum3();
    protobuf.Type = require_type();
    protobuf.Field = require_field();
    protobuf.OneOf = require_oneof();
    protobuf.MapField = require_mapfield();
    protobuf.Service = require_service2();
    protobuf.Method = require_method();
    protobuf.Message = require_message();
    protobuf.wrappers = require_wrappers();
    protobuf.types = require_types3();
    protobuf.util = require_util11();
    protobuf.ReflectionObject._configure(protobuf.Root);
    protobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum);
    protobuf.Root._configure(protobuf.Type);
    protobuf.Field._configure(protobuf.Type);
  }
});

// node_modules/protobufjs/src/tokenize.js
var require_tokenize = __commonJS({
  "node_modules/protobufjs/src/tokenize.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = tokenize4;
    var delimRe = /[\s{}=;:[\],'"()<>]/g;
    var stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g;
    var stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g;
    var setCommentRe = /^ *[*/]+ */;
    var setCommentAltRe = /^\s*\*?\/*/;
    var setCommentSplitRe = /\n/g;
    var whitespaceRe = /\s/;
    var unescapeRe = /\\(.?)/g;
    var unescapeMap = {
      "0": "\0",
      "r": "\r",
      "n": "\n",
      "t": "	"
    };
    function unescape4(str2) {
      return str2.replace(unescapeRe, function($0, $1) {
        switch ($1) {
          case "\\":
          case "":
            return $1;
          default:
            return unescapeMap[$1] || "";
        }
      });
    }
    __name(unescape4, "unescape");
    tokenize4.unescape = unescape4;
    function tokenize4(source2, alternateCommentMode) {
      source2 = source2.toString();
      var offset = 0, length = source2.length, line = 1, lastCommentLine = 0, comments = {};
      var stack = [];
      var stringDelim = null;
      function illegal(subject) {
        return Error("illegal " + subject + " (line " + line + ")");
      }
      __name(illegal, "illegal");
      function readString() {
        var re2 = stringDelim === "'" ? stringSingleRe : stringDoubleRe;
        re2.lastIndex = offset - 1;
        var match2 = re2.exec(source2);
        if (!match2)
          throw illegal("string");
        offset = re2.lastIndex;
        push2(stringDelim);
        stringDelim = null;
        return unescape4(match2[1]);
      }
      __name(readString, "readString");
      function charAt(pos2) {
        return source2.charAt(pos2);
      }
      __name(charAt, "charAt");
      function setComment(start, end, isLeading) {
        var comment = {
          type: source2.charAt(start++),
          lineEmpty: false,
          leading: isLeading
        };
        var lookback;
        if (alternateCommentMode) {
          lookback = 2;
        } else {
          lookback = 3;
        }
        var commentOffset = start - lookback, c3;
        do {
          if (--commentOffset < 0 || (c3 = source2.charAt(commentOffset)) === "\n") {
            comment.lineEmpty = true;
            break;
          }
        } while (c3 === " " || c3 === "	");
        var lines = source2.substring(start, end).split(setCommentSplitRe);
        for (var i = 0; i < lines.length; ++i)
          lines[i] = lines[i].replace(alternateCommentMode ? setCommentAltRe : setCommentRe, "").trim();
        comment.text = lines.join("\n").trim();
        comments[line] = comment;
        lastCommentLine = line;
      }
      __name(setComment, "setComment");
      function isDoubleSlashCommentLine(startOffset) {
        var endOffset = findEndOfLine(startOffset);
        var lineText = source2.substring(startOffset, endOffset);
        var isComment2 = /^\s*\/\//.test(lineText);
        return isComment2;
      }
      __name(isDoubleSlashCommentLine, "isDoubleSlashCommentLine");
      function findEndOfLine(cursor) {
        var endOffset = cursor;
        while (endOffset < length && charAt(endOffset) !== "\n") {
          endOffset++;
        }
        return endOffset;
      }
      __name(findEndOfLine, "findEndOfLine");
      function next() {
        if (stack.length > 0)
          return stack.shift();
        if (stringDelim)
          return readString();
        var repeat, prev, curr, start, isDoc, isLeadingComment = offset === 0;
        do {
          if (offset === length)
            return null;
          repeat = false;
          while (whitespaceRe.test(curr = charAt(offset))) {
            if (curr === "\n") {
              isLeadingComment = true;
              ++line;
            }
            if (++offset === length)
              return null;
          }
          if (charAt(offset) === "/") {
            if (++offset === length) {
              throw illegal("comment");
            }
            if (charAt(offset) === "/") {
              if (!alternateCommentMode) {
                isDoc = charAt(start = offset + 1) === "/";
                while (charAt(++offset) !== "\n") {
                  if (offset === length) {
                    return null;
                  }
                }
                ++offset;
                if (isDoc) {
                  setComment(start, offset - 1, isLeadingComment);
                  isLeadingComment = true;
                }
                ++line;
                repeat = true;
              } else {
                start = offset;
                isDoc = false;
                if (isDoubleSlashCommentLine(offset - 1)) {
                  isDoc = true;
                  do {
                    offset = findEndOfLine(offset);
                    if (offset === length) {
                      break;
                    }
                    offset++;
                    if (!isLeadingComment) {
                      break;
                    }
                  } while (isDoubleSlashCommentLine(offset));
                } else {
                  offset = Math.min(length, findEndOfLine(offset) + 1);
                }
                if (isDoc) {
                  setComment(start, offset, isLeadingComment);
                  isLeadingComment = true;
                }
                line++;
                repeat = true;
              }
            } else if ((curr = charAt(offset)) === "*") {
              start = offset + 1;
              isDoc = alternateCommentMode || charAt(start) === "*";
              do {
                if (curr === "\n") {
                  ++line;
                }
                if (++offset === length) {
                  throw illegal("comment");
                }
                prev = curr;
                curr = charAt(offset);
              } while (prev !== "*" || curr !== "/");
              ++offset;
              if (isDoc) {
                setComment(start, offset - 2, isLeadingComment);
                isLeadingComment = true;
              }
              repeat = true;
            } else {
              return "/";
            }
          }
        } while (repeat);
        var end = offset;
        delimRe.lastIndex = 0;
        var delim = delimRe.test(charAt(end++));
        if (!delim)
          while (end < length && !delimRe.test(charAt(end)))
            ++end;
        var token2 = source2.substring(offset, offset = end);
        if (token2 === '"' || token2 === "'")
          stringDelim = token2;
        return token2;
      }
      __name(next, "next");
      function push2(token2) {
        stack.push(token2);
      }
      __name(push2, "push");
      function peek() {
        if (!stack.length) {
          var token2 = next();
          if (token2 === null)
            return null;
          push2(token2);
        }
        return stack[0];
      }
      __name(peek, "peek");
      function skip(expected, optional) {
        var actual = peek(), equals2 = actual === expected;
        if (equals2) {
          next();
          return true;
        }
        if (!optional)
          throw illegal("token '" + actual + "', '" + expected + "' expected");
        return false;
      }
      __name(skip, "skip");
      function cmnt(trailingLine) {
        var ret = null;
        var comment;
        if (trailingLine === void 0) {
          comment = comments[line - 1];
          delete comments[line - 1];
          if (comment && (alternateCommentMode || comment.type === "*" || comment.lineEmpty)) {
            ret = comment.leading ? comment.text : null;
          }
        } else {
          if (lastCommentLine < trailingLine) {
            peek();
          }
          comment = comments[trailingLine];
          delete comments[trailingLine];
          if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === "/")) {
            ret = comment.leading ? null : comment.text;
          }
        }
        return ret;
      }
      __name(cmnt, "cmnt");
      return Object.defineProperty({
        next,
        peek,
        push: push2,
        skip,
        cmnt
      }, "line", {
        get: /* @__PURE__ */ __name(function() {
          return line;
        }, "get")
      });
    }
    __name(tokenize4, "tokenize");
  }
});

// node_modules/protobufjs/src/parse.js
var require_parse3 = __commonJS({
  "node_modules/protobufjs/src/parse.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = parse12;
    parse12.filename = null;
    parse12.defaults = { keepCase: false };
    var tokenize4 = require_tokenize();
    var Root2 = require_root();
    var Type2 = require_type();
    var Field = require_field();
    var MapField = require_mapfield();
    var OneOf = require_oneof();
    var Enum = require_enum3();
    var Service = require_service2();
    var Method = require_method();
    var ReflectionObject = require_object();
    var types3 = require_types3();
    var util4 = require_util11();
    var base10Re = /^[1-9][0-9]*$/;
    var base10NegRe = /^-?[1-9][0-9]*$/;
    var base16Re = /^0[x][0-9a-fA-F]+$/;
    var base16NegRe = /^-?0[x][0-9a-fA-F]+$/;
    var base8Re = /^0[0-7]+$/;
    var base8NegRe = /^-?0[0-7]+$/;
    var numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/;
    var nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/;
    var typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;
    function parse12(source2, root, options2) {
      if (!(root instanceof Root2)) {
        options2 = root;
        root = new Root2();
      }
      if (!options2)
        options2 = parse12.defaults;
      var preferTrailingComment = options2.preferTrailingComment || false;
      var tn = tokenize4(source2, options2.alternateCommentMode || false), next = tn.next, push2 = tn.push, peek = tn.peek, skip = tn.skip, cmnt = tn.cmnt;
      var head = true, pkg2, imports, weakImports, edition = "proto2";
      var ptr = root;
      var topLevelObjects = [];
      var topLevelOptions = {};
      var applyCase = options2.keepCase ? function(name3) {
        return name3;
      } : util4.camelCase;
      function resolveFileFeatures() {
        topLevelObjects.forEach((obj) => {
          obj._edition = edition;
          Object.keys(topLevelOptions).forEach((opt) => {
            if (obj.getOption(opt) !== void 0) return;
            obj.setOption(opt, topLevelOptions[opt], true);
          });
        });
      }
      __name(resolveFileFeatures, "resolveFileFeatures");
      function illegal(token3, name3, insideTryCatch) {
        var filename = parse12.filename;
        if (!insideTryCatch)
          parse12.filename = null;
        return Error("illegal " + (name3 || "token") + " '" + token3 + "' (" + (filename ? filename + ", " : "") + "line " + tn.line + ")");
      }
      __name(illegal, "illegal");
      function readString() {
        var values = [], token3;
        do {
          if ((token3 = next()) !== '"' && token3 !== "'")
            throw illegal(token3);
          values.push(next());
          skip(token3);
          token3 = peek();
        } while (token3 === '"' || token3 === "'");
        return values.join("");
      }
      __name(readString, "readString");
      function readValue(acceptTypeRef) {
        var token3 = next();
        switch (token3) {
          case "'":
          case '"':
            push2(token3);
            return readString();
          case "true":
          case "TRUE":
            return true;
          case "false":
          case "FALSE":
            return false;
        }
        try {
          return parseNumber(
            token3,
            /* insideTryCatch */
            true
          );
        } catch (e2) {
          if (acceptTypeRef && typeRefRe.test(token3))
            return token3;
          throw illegal(token3, "value");
        }
      }
      __name(readValue, "readValue");
      function readRanges(target, acceptStrings) {
        var token3, start;
        do {
          if (acceptStrings && ((token3 = peek()) === '"' || token3 === "'")) {
            var str2 = readString();
            target.push(str2);
            if (edition >= 2023) {
              throw illegal(str2, "id");
            }
          } else {
            try {
              target.push([start = parseId(next()), skip("to", true) ? parseId(next()) : start]);
            } catch (err) {
              if (acceptStrings && typeRefRe.test(token3) && edition >= 2023) {
                target.push(token3);
              } else {
                throw err;
              }
            }
          }
        } while (skip(",", true));
        var dummy = { options: void 0 };
        dummy.setOption = function(name3, value) {
          if (this.options === void 0) this.options = {};
          this.options[name3] = value;
        };
        ifBlock(
          dummy,
          /* @__PURE__ */ __name(function parseRange_block(token4) {
            if (token4 === "option") {
              parseOption(dummy, token4);
              skip(";");
            } else
              throw illegal(token4);
          }, "parseRange_block"),
          /* @__PURE__ */ __name(function parseRange_line() {
            parseInlineOptions(dummy);
          }, "parseRange_line")
        );
      }
      __name(readRanges, "readRanges");
      function parseNumber(token3, insideTryCatch) {
        var sign = 1;
        if (token3.charAt(0) === "-") {
          sign = -1;
          token3 = token3.substring(1);
        }
        switch (token3) {
          case "inf":
          case "INF":
          case "Inf":
            return sign * Infinity;
          case "nan":
          case "NAN":
          case "Nan":
          case "NaN":
            return NaN;
          case "0":
            return 0;
        }
        if (base10Re.test(token3))
          return sign * parseInt(token3, 10);
        if (base16Re.test(token3))
          return sign * parseInt(token3, 16);
        if (base8Re.test(token3))
          return sign * parseInt(token3, 8);
        if (numberRe.test(token3))
          return sign * parseFloat(token3);
        throw illegal(token3, "number", insideTryCatch);
      }
      __name(parseNumber, "parseNumber");
      function parseId(token3, acceptNegative) {
        switch (token3) {
          case "max":
          case "MAX":
          case "Max":
            return 536870911;
          case "0":
            return 0;
        }
        if (!acceptNegative && token3.charAt(0) === "-")
          throw illegal(token3, "id");
        if (base10NegRe.test(token3))
          return parseInt(token3, 10);
        if (base16NegRe.test(token3))
          return parseInt(token3, 16);
        if (base8NegRe.test(token3))
          return parseInt(token3, 8);
        throw illegal(token3, "id");
      }
      __name(parseId, "parseId");
      function parsePackage() {
        if (pkg2 !== void 0)
          throw illegal("package");
        pkg2 = next();
        if (!typeRefRe.test(pkg2))
          throw illegal(pkg2, "name");
        ptr = ptr.define(pkg2);
        skip(";");
      }
      __name(parsePackage, "parsePackage");
      function parseImport() {
        var token3 = peek();
        var whichImports;
        switch (token3) {
          case "weak":
            whichImports = weakImports || (weakImports = []);
            next();
            break;
          case "public":
            next();
          // eslint-disable-next-line no-fallthrough
          default:
            whichImports = imports || (imports = []);
            break;
        }
        token3 = readString();
        skip(";");
        whichImports.push(token3);
      }
      __name(parseImport, "parseImport");
      function parseSyntax() {
        skip("=");
        edition = readString();
        if (edition < 2023)
          throw illegal(edition, "syntax");
        skip(";");
      }
      __name(parseSyntax, "parseSyntax");
      function parseEdition() {
        skip("=");
        edition = readString();
        const supportedEditions = ["2023"];
        if (!supportedEditions.includes(edition))
          throw illegal(edition, "edition");
        skip(";");
      }
      __name(parseEdition, "parseEdition");
      function parseCommon(parent, token3) {
        switch (token3) {
          case "option":
            parseOption(parent, token3);
            skip(";");
            return true;
          case "message":
            parseType(parent, token3);
            return true;
          case "enum":
            parseEnum(parent, token3);
            return true;
          case "service":
            parseService(parent, token3);
            return true;
          case "extend":
            parseExtension(parent, token3);
            return true;
        }
        return false;
      }
      __name(parseCommon, "parseCommon");
      function ifBlock(obj, fnIf, fnElse) {
        var trailingLine = tn.line;
        if (obj) {
          if (typeof obj.comment !== "string") {
            obj.comment = cmnt();
          }
          obj.filename = parse12.filename;
        }
        if (skip("{", true)) {
          var token3;
          while ((token3 = next()) !== "}")
            fnIf(token3);
          skip(";", true);
        } else {
          if (fnElse)
            fnElse();
          skip(";");
          if (obj && (typeof obj.comment !== "string" || preferTrailingComment))
            obj.comment = cmnt(trailingLine) || obj.comment;
        }
      }
      __name(ifBlock, "ifBlock");
      function parseType(parent, token3) {
        if (!nameRe.test(token3 = next()))
          throw illegal(token3, "type name");
        var type = new Type2(token3);
        ifBlock(type, /* @__PURE__ */ __name(function parseType_block(token4) {
          if (parseCommon(type, token4))
            return;
          switch (token4) {
            case "map":
              parseMapField(type, token4);
              break;
            case "required":
              if (edition !== "proto2")
                throw illegal(token4);
            /* eslint-disable no-fallthrough */
            case "repeated":
              parseField(type, token4);
              break;
            case "optional":
              if (edition === "proto3") {
                parseField(type, "proto3_optional");
              } else if (edition !== "proto2") {
                throw illegal(token4);
              } else {
                parseField(type, "optional");
              }
              break;
            case "oneof":
              parseOneOf(type, token4);
              break;
            case "extensions":
              readRanges(type.extensions || (type.extensions = []));
              break;
            case "reserved":
              readRanges(type.reserved || (type.reserved = []), true);
              break;
            default:
              if (edition === "proto2" || !typeRefRe.test(token4)) {
                throw illegal(token4);
              }
              push2(token4);
              parseField(type, "optional");
              break;
          }
        }, "parseType_block"));
        parent.add(type);
        if (parent === ptr) {
          topLevelObjects.push(type);
        }
      }
      __name(parseType, "parseType");
      function parseField(parent, rule, extend) {
        var type = next();
        if (type === "group") {
          parseGroup(parent, rule);
          return;
        }
        while (type.endsWith(".") || peek().startsWith(".")) {
          type += next();
        }
        if (!typeRefRe.test(type))
          throw illegal(type, "type");
        var name3 = next();
        if (!nameRe.test(name3))
          throw illegal(name3, "name");
        name3 = applyCase(name3);
        skip("=");
        var field = new Field(name3, parseId(next()), type, rule, extend);
        ifBlock(field, /* @__PURE__ */ __name(function parseField_block(token3) {
          if (token3 === "option") {
            parseOption(field, token3);
            skip(";");
          } else
            throw illegal(token3);
        }, "parseField_block"), /* @__PURE__ */ __name(function parseField_line() {
          parseInlineOptions(field);
        }, "parseField_line"));
        if (rule === "proto3_optional") {
          var oneof = new OneOf("_" + name3);
          field.setOption("proto3_optional", true);
          oneof.add(field);
          parent.add(oneof);
        } else {
          parent.add(field);
        }
        if (parent === ptr) {
          topLevelObjects.push(field);
        }
      }
      __name(parseField, "parseField");
      function parseGroup(parent, rule) {
        if (edition >= 2023) {
          throw illegal("group");
        }
        var name3 = next();
        if (!nameRe.test(name3))
          throw illegal(name3, "name");
        var fieldName = util4.lcFirst(name3);
        if (name3 === fieldName)
          name3 = util4.ucFirst(name3);
        skip("=");
        var id = parseId(next());
        var type = new Type2(name3);
        type.group = true;
        var field = new Field(fieldName, id, name3, rule);
        field.filename = parse12.filename;
        ifBlock(type, /* @__PURE__ */ __name(function parseGroup_block(token3) {
          switch (token3) {
            case "option":
              parseOption(type, token3);
              skip(";");
              break;
            case "required":
            case "repeated":
              parseField(type, token3);
              break;
            case "optional":
              if (edition === "proto3") {
                parseField(type, "proto3_optional");
              } else {
                parseField(type, "optional");
              }
              break;
            case "message":
              parseType(type, token3);
              break;
            case "enum":
              parseEnum(type, token3);
              break;
            case "reserved":
              readRanges(type.reserved || (type.reserved = []), true);
              break;
            /* istanbul ignore next */
            default:
              throw illegal(token3);
          }
        }, "parseGroup_block"));
        parent.add(type).add(field);
      }
      __name(parseGroup, "parseGroup");
      function parseMapField(parent) {
        skip("<");
        var keyType = next();
        if (types3.mapKey[keyType] === void 0)
          throw illegal(keyType, "type");
        skip(",");
        var valueType = next();
        if (!typeRefRe.test(valueType))
          throw illegal(valueType, "type");
        skip(">");
        var name3 = next();
        if (!nameRe.test(name3))
          throw illegal(name3, "name");
        skip("=");
        var field = new MapField(applyCase(name3), parseId(next()), keyType, valueType);
        ifBlock(field, /* @__PURE__ */ __name(function parseMapField_block(token3) {
          if (token3 === "option") {
            parseOption(field, token3);
            skip(";");
          } else
            throw illegal(token3);
        }, "parseMapField_block"), /* @__PURE__ */ __name(function parseMapField_line() {
          parseInlineOptions(field);
        }, "parseMapField_line"));
        parent.add(field);
      }
      __name(parseMapField, "parseMapField");
      function parseOneOf(parent, token3) {
        if (!nameRe.test(token3 = next()))
          throw illegal(token3, "name");
        var oneof = new OneOf(applyCase(token3));
        ifBlock(oneof, /* @__PURE__ */ __name(function parseOneOf_block(token4) {
          if (token4 === "option") {
            parseOption(oneof, token4);
            skip(";");
          } else {
            push2(token4);
            parseField(oneof, "optional");
          }
        }, "parseOneOf_block"));
        parent.add(oneof);
      }
      __name(parseOneOf, "parseOneOf");
      function parseEnum(parent, token3) {
        if (!nameRe.test(token3 = next()))
          throw illegal(token3, "name");
        var enm = new Enum(token3);
        ifBlock(enm, /* @__PURE__ */ __name(function parseEnum_block(token4) {
          switch (token4) {
            case "option":
              parseOption(enm, token4);
              skip(";");
              break;
            case "reserved":
              readRanges(enm.reserved || (enm.reserved = []), true);
              if (enm.reserved === void 0) enm.reserved = [];
              break;
            default:
              parseEnumValue(enm, token4);
          }
        }, "parseEnum_block"));
        parent.add(enm);
        if (parent === ptr) {
          topLevelObjects.push(enm);
        }
      }
      __name(parseEnum, "parseEnum");
      function parseEnumValue(parent, token3) {
        if (!nameRe.test(token3))
          throw illegal(token3, "name");
        skip("=");
        var value = parseId(next(), true), dummy = {
          options: void 0
        };
        dummy.getOption = function(name3) {
          return this.options[name3];
        };
        dummy.setOption = function(name3, value2) {
          ReflectionObject.prototype.setOption.call(dummy, name3, value2);
        };
        dummy.setParsedOption = function() {
          return void 0;
        };
        ifBlock(dummy, /* @__PURE__ */ __name(function parseEnumValue_block(token4) {
          if (token4 === "option") {
            parseOption(dummy, token4);
            skip(";");
          } else
            throw illegal(token4);
        }, "parseEnumValue_block"), /* @__PURE__ */ __name(function parseEnumValue_line() {
          parseInlineOptions(dummy);
        }, "parseEnumValue_line"));
        parent.add(token3, value, dummy.comment, dummy.parsedOptions || dummy.options);
      }
      __name(parseEnumValue, "parseEnumValue");
      function parseOption(parent, token3) {
        var option2;
        var propName;
        var isOption = true;
        if (token3 === "option") {
          token3 = next();
        }
        while (token3 !== "=") {
          if (token3 === "(") {
            var parensValue = next();
            skip(")");
            token3 = "(" + parensValue + ")";
          }
          if (isOption) {
            isOption = false;
            if (token3.includes(".") && !token3.includes("(")) {
              var tokens = token3.split(".");
              option2 = tokens[0] + ".";
              token3 = tokens[1];
              continue;
            }
            option2 = token3;
          } else {
            propName = propName ? propName += token3 : token3;
          }
          token3 = next();
        }
        var name3 = propName ? option2.concat(propName) : option2;
        var optionValue = parseOptionValue(parent, name3);
        propName = propName && propName[0] === "." ? propName.slice(1) : propName;
        option2 = option2 && option2[option2.length - 1] === "." ? option2.slice(0, -1) : option2;
        setParsedOption(parent, option2, optionValue, propName);
      }
      __name(parseOption, "parseOption");
      function parseOptionValue(parent, name3) {
        if (skip("{", true)) {
          var objectResult = {};
          while (!skip("}", true)) {
            if (!nameRe.test(token2 = next())) {
              throw illegal(token2, "name");
            }
            if (token2 === null) {
              throw illegal(token2, "end of input");
            }
            var value;
            var propName = token2;
            skip(":", true);
            if (peek() === "{") {
              value = parseOptionValue(parent, name3 + "." + token2);
            } else if (peek() === "[") {
              value = [];
              var lastValue;
              if (skip("[", true)) {
                do {
                  lastValue = readValue(true);
                  value.push(lastValue);
                } while (skip(",", true));
                skip("]");
                if (typeof lastValue !== "undefined") {
                  setOption(parent, name3 + "." + token2, lastValue);
                }
              }
            } else {
              value = readValue(true);
              setOption(parent, name3 + "." + token2, value);
            }
            var prevValue = objectResult[propName];
            if (prevValue)
              value = [].concat(prevValue).concat(value);
            objectResult[propName] = value;
            skip(",", true);
            skip(";", true);
          }
          return objectResult;
        }
        var simpleValue = readValue(true);
        setOption(parent, name3, simpleValue);
        return simpleValue;
      }
      __name(parseOptionValue, "parseOptionValue");
      function setOption(parent, name3, value) {
        if (ptr === parent && /^features\./.test(name3)) {
          topLevelOptions[name3] = value;
          return;
        }
        if (parent.setOption)
          parent.setOption(name3, value);
      }
      __name(setOption, "setOption");
      function setParsedOption(parent, name3, value, propName) {
        if (parent.setParsedOption)
          parent.setParsedOption(name3, value, propName);
      }
      __name(setParsedOption, "setParsedOption");
      function parseInlineOptions(parent) {
        if (skip("[", true)) {
          do {
            parseOption(parent, "option");
          } while (skip(",", true));
          skip("]");
        }
        return parent;
      }
      __name(parseInlineOptions, "parseInlineOptions");
      function parseService(parent, token3) {
        if (!nameRe.test(token3 = next()))
          throw illegal(token3, "service name");
        var service = new Service(token3);
        ifBlock(service, /* @__PURE__ */ __name(function parseService_block(token4) {
          if (parseCommon(service, token4)) {
            return;
          }
          if (token4 === "rpc")
            parseMethod(service, token4);
          else
            throw illegal(token4);
        }, "parseService_block"));
        parent.add(service);
        if (parent === ptr) {
          topLevelObjects.push(service);
        }
      }
      __name(parseService, "parseService");
      function parseMethod(parent, token3) {
        var commentText = cmnt();
        var type = token3;
        if (!nameRe.test(token3 = next()))
          throw illegal(token3, "name");
        var name3 = token3, requestType, requestStream, responseType, responseStream;
        skip("(");
        if (skip("stream", true))
          requestStream = true;
        if (!typeRefRe.test(token3 = next()))
          throw illegal(token3);
        requestType = token3;
        skip(")");
        skip("returns");
        skip("(");
        if (skip("stream", true))
          responseStream = true;
        if (!typeRefRe.test(token3 = next()))
          throw illegal(token3);
        responseType = token3;
        skip(")");
        var method = new Method(name3, type, requestType, responseType, requestStream, responseStream);
        method.comment = commentText;
        ifBlock(method, /* @__PURE__ */ __name(function parseMethod_block(token4) {
          if (token4 === "option") {
            parseOption(method, token4);
            skip(";");
          } else
            throw illegal(token4);
        }, "parseMethod_block"));
        parent.add(method);
      }
      __name(parseMethod, "parseMethod");
      function parseExtension(parent, token3) {
        if (!typeRefRe.test(token3 = next()))
          throw illegal(token3, "reference");
        var reference = token3;
        ifBlock(null, /* @__PURE__ */ __name(function parseExtension_block(token4) {
          switch (token4) {
            case "required":
            case "repeated":
              parseField(parent, token4, reference);
              break;
            case "optional":
              if (edition === "proto3") {
                parseField(parent, "proto3_optional", reference);
              } else {
                parseField(parent, "optional", reference);
              }
              break;
            default:
              if (edition === "proto2" || !typeRefRe.test(token4))
                throw illegal(token4);
              push2(token4);
              parseField(parent, "optional", reference);
              break;
          }
        }, "parseExtension_block"));
      }
      __name(parseExtension, "parseExtension");
      var token2;
      while ((token2 = next()) !== null) {
        switch (token2) {
          case "package":
            if (!head)
              throw illegal(token2);
            parsePackage();
            break;
          case "import":
            if (!head)
              throw illegal(token2);
            parseImport();
            break;
          case "syntax":
            if (!head)
              throw illegal(token2);
            parseSyntax();
            break;
          case "edition":
            if (!head)
              throw illegal(token2);
            parseEdition();
            break;
          case "option":
            parseOption(ptr, token2);
            skip(";", true);
            break;
          default:
            if (parseCommon(ptr, token2)) {
              head = false;
              continue;
            }
            throw illegal(token2);
        }
      }
      resolveFileFeatures();
      parse12.filename = null;
      return {
        "package": pkg2,
        "imports": imports,
        weakImports,
        root
      };
    }
    __name(parse12, "parse");
  }
});

// node_modules/protobufjs/src/common.js
var require_common3 = __commonJS({
  "node_modules/protobufjs/src/common.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = common;
    var commonRe = /\/|\./;
    function common(name3, json2) {
      if (!commonRe.test(name3)) {
        name3 = "google/protobuf/" + name3 + ".proto";
        json2 = { nested: { google: { nested: { protobuf: { nested: json2 } } } } };
      }
      common[name3] = json2;
    }
    __name(common, "common");
    common("any", {
      /**
       * Properties of a google.protobuf.Any message.
       * @interface IAny
       * @type {Object}
       * @property {string} [typeUrl]
       * @property {Uint8Array} [bytes]
       * @memberof common
       */
      Any: {
        fields: {
          type_url: {
            type: "string",
            id: 1
          },
          value: {
            type: "bytes",
            id: 2
          }
        }
      }
    });
    var timeType;
    common("duration", {
      /**
       * Properties of a google.protobuf.Duration message.
       * @interface IDuration
       * @type {Object}
       * @property {number|Long} [seconds]
       * @property {number} [nanos]
       * @memberof common
       */
      Duration: timeType = {
        fields: {
          seconds: {
            type: "int64",
            id: 1
          },
          nanos: {
            type: "int32",
            id: 2
          }
        }
      }
    });
    common("timestamp", {
      /**
       * Properties of a google.protobuf.Timestamp message.
       * @interface ITimestamp
       * @type {Object}
       * @property {number|Long} [seconds]
       * @property {number} [nanos]
       * @memberof common
       */
      Timestamp: timeType
    });
    common("empty", {
      /**
       * Properties of a google.protobuf.Empty message.
       * @interface IEmpty
       * @memberof common
       */
      Empty: {
        fields: {}
      }
    });
    common("struct", {
      /**
       * Properties of a google.protobuf.Struct message.
       * @interface IStruct
       * @type {Object}
       * @property {Object.<string,IValue>} [fields]
       * @memberof common
       */
      Struct: {
        fields: {
          fields: {
            keyType: "string",
            type: "Value",
            id: 1
          }
        }
      },
      /**
       * Properties of a google.protobuf.Value message.
       * @interface IValue
       * @type {Object}
       * @property {string} [kind]
       * @property {0} [nullValue]
       * @property {number} [numberValue]
       * @property {string} [stringValue]
       * @property {boolean} [boolValue]
       * @property {IStruct} [structValue]
       * @property {IListValue} [listValue]
       * @memberof common
       */
      Value: {
        oneofs: {
          kind: {
            oneof: [
              "nullValue",
              "numberValue",
              "stringValue",
              "boolValue",
              "structValue",
              "listValue"
            ]
          }
        },
        fields: {
          nullValue: {
            type: "NullValue",
            id: 1
          },
          numberValue: {
            type: "double",
            id: 2
          },
          stringValue: {
            type: "string",
            id: 3
          },
          boolValue: {
            type: "bool",
            id: 4
          },
          structValue: {
            type: "Struct",
            id: 5
          },
          listValue: {
            type: "ListValue",
            id: 6
          }
        }
      },
      NullValue: {
        values: {
          NULL_VALUE: 0
        }
      },
      /**
       * Properties of a google.protobuf.ListValue message.
       * @interface IListValue
       * @type {Object}
       * @property {Array.<IValue>} [values]
       * @memberof common
       */
      ListValue: {
        fields: {
          values: {
            rule: "repeated",
            type: "Value",
            id: 1
          }
        }
      }
    });
    common("wrappers", {
      /**
       * Properties of a google.protobuf.DoubleValue message.
       * @interface IDoubleValue
       * @type {Object}
       * @property {number} [value]
       * @memberof common
       */
      DoubleValue: {
        fields: {
          value: {
            type: "double",
            id: 1
          }
        }
      },
      /**
       * Properties of a google.protobuf.FloatValue message.
       * @interface IFloatValue
       * @type {Object}
       * @property {number} [value]
       * @memberof common
       */
      FloatValue: {
        fields: {
          value: {
            type: "float",
            id: 1
          }
        }
      },
      /**
       * Properties of a google.protobuf.Int64Value message.
       * @interface IInt64Value
       * @type {Object}
       * @property {number|Long} [value]
       * @memberof common
       */
      Int64Value: {
        fields: {
          value: {
            type: "int64",
            id: 1
          }
        }
      },
      /**
       * Properties of a google.protobuf.UInt64Value message.
       * @interface IUInt64Value
       * @type {Object}
       * @property {number|Long} [value]
       * @memberof common
       */
      UInt64Value: {
        fields: {
          value: {
            type: "uint64",
            id: 1
          }
        }
      },
      /**
       * Properties of a google.protobuf.Int32Value message.
       * @interface IInt32Value
       * @type {Object}
       * @property {number} [value]
       * @memberof common
       */
      Int32Value: {
        fields: {
          value: {
            type: "int32",
            id: 1
          }
        }
      },
      /**
       * Properties of a google.protobuf.UInt32Value message.
       * @interface IUInt32Value
       * @type {Object}
       * @property {number} [value]
       * @memberof common
       */
      UInt32Value: {
        fields: {
          value: {
            type: "uint32",
            id: 1
          }
        }
      },
      /**
       * Properties of a google.protobuf.BoolValue message.
       * @interface IBoolValue
       * @type {Object}
       * @property {boolean} [value]
       * @memberof common
       */
      BoolValue: {
        fields: {
          value: {
            type: "bool",
            id: 1
          }
        }
      },
      /**
       * Properties of a google.protobuf.StringValue message.
       * @interface IStringValue
       * @type {Object}
       * @property {string} [value]
       * @memberof common
       */
      StringValue: {
        fields: {
          value: {
            type: "string",
            id: 1
          }
        }
      },
      /**
       * Properties of a google.protobuf.BytesValue message.
       * @interface IBytesValue
       * @type {Object}
       * @property {Uint8Array} [value]
       * @memberof common
       */
      BytesValue: {
        fields: {
          value: {
            type: "bytes",
            id: 1
          }
        }
      }
    });
    common("field_mask", {
      /**
       * Properties of a google.protobuf.FieldMask message.
       * @interface IDoubleValue
       * @type {Object}
       * @property {number} [value]
       * @memberof common
       */
      FieldMask: {
        fields: {
          paths: {
            rule: "repeated",
            type: "string",
            id: 1
          }
        }
      }
    });
    common.get = /* @__PURE__ */ __name(function get3(file) {
      return common[file] || null;
    }, "get");
  }
});

// node_modules/protobufjs/src/index.js
var require_src9 = __commonJS({
  "node_modules/protobufjs/src/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var protobuf = module2.exports = require_index_light();
    protobuf.build = "full";
    protobuf.tokenize = require_tokenize();
    protobuf.parse = require_parse3();
    protobuf.common = require_common3();
    protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common);
  }
});

// node_modules/protobufjs/index.js
var require_protobufjs = __commonJS({
  "node_modules/protobufjs/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = require_src9();
  }
});

// node_modules/protobufjs/google/protobuf/descriptor.json
var require_descriptor = __commonJS({
  "node_modules/protobufjs/google/protobuf/descriptor.json"(exports2, module2) {
    module2.exports = {
      nested: {
        google: {
          nested: {
            protobuf: {
              options: {
                go_package: "google.golang.org/protobuf/types/descriptorpb",
                java_package: "com.google.protobuf",
                java_outer_classname: "DescriptorProtos",
                csharp_namespace: "Google.Protobuf.Reflection",
                objc_class_prefix: "GPB",
                cc_enable_arenas: true,
                optimize_for: "SPEED"
              },
              nested: {
                FileDescriptorSet: {
                  edition: "proto2",
                  fields: {
                    file: {
                      rule: "repeated",
                      type: "FileDescriptorProto",
                      id: 1
                    }
                  },
                  extensions: [
                    [
                      536e6,
                      536e6
                    ]
                  ]
                },
                Edition: {
                  edition: "proto2",
                  values: {
                    EDITION_UNKNOWN: 0,
                    EDITION_LEGACY: 900,
                    EDITION_PROTO2: 998,
                    EDITION_PROTO3: 999,
                    EDITION_2023: 1e3,
                    EDITION_2024: 1001,
                    EDITION_1_TEST_ONLY: 1,
                    EDITION_2_TEST_ONLY: 2,
                    EDITION_99997_TEST_ONLY: 99997,
                    EDITION_99998_TEST_ONLY: 99998,
                    EDITION_99999_TEST_ONLY: 99999,
                    EDITION_MAX: 2147483647
                  }
                },
                FileDescriptorProto: {
                  edition: "proto2",
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    package: {
                      type: "string",
                      id: 2
                    },
                    dependency: {
                      rule: "repeated",
                      type: "string",
                      id: 3
                    },
                    publicDependency: {
                      rule: "repeated",
                      type: "int32",
                      id: 10
                    },
                    weakDependency: {
                      rule: "repeated",
                      type: "int32",
                      id: 11
                    },
                    optionDependency: {
                      rule: "repeated",
                      type: "string",
                      id: 15
                    },
                    messageType: {
                      rule: "repeated",
                      type: "DescriptorProto",
                      id: 4
                    },
                    enumType: {
                      rule: "repeated",
                      type: "EnumDescriptorProto",
                      id: 5
                    },
                    service: {
                      rule: "repeated",
                      type: "ServiceDescriptorProto",
                      id: 6
                    },
                    extension: {
                      rule: "repeated",
                      type: "FieldDescriptorProto",
                      id: 7
                    },
                    options: {
                      type: "FileOptions",
                      id: 8
                    },
                    sourceCodeInfo: {
                      type: "SourceCodeInfo",
                      id: 9
                    },
                    syntax: {
                      type: "string",
                      id: 12
                    },
                    edition: {
                      type: "Edition",
                      id: 14
                    }
                  }
                },
                DescriptorProto: {
                  edition: "proto2",
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    field: {
                      rule: "repeated",
                      type: "FieldDescriptorProto",
                      id: 2
                    },
                    extension: {
                      rule: "repeated",
                      type: "FieldDescriptorProto",
                      id: 6
                    },
                    nestedType: {
                      rule: "repeated",
                      type: "DescriptorProto",
                      id: 3
                    },
                    enumType: {
                      rule: "repeated",
                      type: "EnumDescriptorProto",
                      id: 4
                    },
                    extensionRange: {
                      rule: "repeated",
                      type: "ExtensionRange",
                      id: 5
                    },
                    oneofDecl: {
                      rule: "repeated",
                      type: "OneofDescriptorProto",
                      id: 8
                    },
                    options: {
                      type: "MessageOptions",
                      id: 7
                    },
                    reservedRange: {
                      rule: "repeated",
                      type: "ReservedRange",
                      id: 9
                    },
                    reservedName: {
                      rule: "repeated",
                      type: "string",
                      id: 10
                    },
                    visibility: {
                      type: "SymbolVisibility",
                      id: 11
                    }
                  },
                  nested: {
                    ExtensionRange: {
                      fields: {
                        start: {
                          type: "int32",
                          id: 1
                        },
                        end: {
                          type: "int32",
                          id: 2
                        },
                        options: {
                          type: "ExtensionRangeOptions",
                          id: 3
                        }
                      }
                    },
                    ReservedRange: {
                      fields: {
                        start: {
                          type: "int32",
                          id: 1
                        },
                        end: {
                          type: "int32",
                          id: 2
                        }
                      }
                    }
                  }
                },
                ExtensionRangeOptions: {
                  edition: "proto2",
                  fields: {
                    uninterpretedOption: {
                      rule: "repeated",
                      type: "UninterpretedOption",
                      id: 999
                    },
                    declaration: {
                      rule: "repeated",
                      type: "Declaration",
                      id: 2,
                      options: {
                        retention: "RETENTION_SOURCE"
                      }
                    },
                    features: {
                      type: "FeatureSet",
                      id: 50
                    },
                    verification: {
                      type: "VerificationState",
                      id: 3,
                      options: {
                        default: "UNVERIFIED",
                        retention: "RETENTION_SOURCE"
                      }
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      536870911
                    ]
                  ],
                  nested: {
                    Declaration: {
                      fields: {
                        number: {
                          type: "int32",
                          id: 1
                        },
                        fullName: {
                          type: "string",
                          id: 2
                        },
                        type: {
                          type: "string",
                          id: 3
                        },
                        reserved: {
                          type: "bool",
                          id: 5
                        },
                        repeated: {
                          type: "bool",
                          id: 6
                        }
                      },
                      reserved: [
                        [
                          4,
                          4
                        ]
                      ]
                    },
                    VerificationState: {
                      values: {
                        DECLARATION: 0,
                        UNVERIFIED: 1
                      }
                    }
                  }
                },
                FieldDescriptorProto: {
                  edition: "proto2",
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    number: {
                      type: "int32",
                      id: 3
                    },
                    label: {
                      type: "Label",
                      id: 4
                    },
                    type: {
                      type: "Type",
                      id: 5
                    },
                    typeName: {
                      type: "string",
                      id: 6
                    },
                    extendee: {
                      type: "string",
                      id: 2
                    },
                    defaultValue: {
                      type: "string",
                      id: 7
                    },
                    oneofIndex: {
                      type: "int32",
                      id: 9
                    },
                    jsonName: {
                      type: "string",
                      id: 10
                    },
                    options: {
                      type: "FieldOptions",
                      id: 8
                    },
                    proto3Optional: {
                      type: "bool",
                      id: 17
                    }
                  },
                  nested: {
                    Type: {
                      values: {
                        TYPE_DOUBLE: 1,
                        TYPE_FLOAT: 2,
                        TYPE_INT64: 3,
                        TYPE_UINT64: 4,
                        TYPE_INT32: 5,
                        TYPE_FIXED64: 6,
                        TYPE_FIXED32: 7,
                        TYPE_BOOL: 8,
                        TYPE_STRING: 9,
                        TYPE_GROUP: 10,
                        TYPE_MESSAGE: 11,
                        TYPE_BYTES: 12,
                        TYPE_UINT32: 13,
                        TYPE_ENUM: 14,
                        TYPE_SFIXED32: 15,
                        TYPE_SFIXED64: 16,
                        TYPE_SINT32: 17,
                        TYPE_SINT64: 18
                      }
                    },
                    Label: {
                      values: {
                        LABEL_OPTIONAL: 1,
                        LABEL_REPEATED: 3,
                        LABEL_REQUIRED: 2
                      }
                    }
                  }
                },
                OneofDescriptorProto: {
                  edition: "proto2",
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    options: {
                      type: "OneofOptions",
                      id: 2
                    }
                  }
                },
                EnumDescriptorProto: {
                  edition: "proto2",
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    value: {
                      rule: "repeated",
                      type: "EnumValueDescriptorProto",
                      id: 2
                    },
                    options: {
                      type: "EnumOptions",
                      id: 3
                    },
                    reservedRange: {
                      rule: "repeated",
                      type: "EnumReservedRange",
                      id: 4
                    },
                    reservedName: {
                      rule: "repeated",
                      type: "string",
                      id: 5
                    },
                    visibility: {
                      type: "SymbolVisibility",
                      id: 6
                    }
                  },
                  nested: {
                    EnumReservedRange: {
                      fields: {
                        start: {
                          type: "int32",
                          id: 1
                        },
                        end: {
                          type: "int32",
                          id: 2
                        }
                      }
                    }
                  }
                },
                EnumValueDescriptorProto: {
                  edition: "proto2",
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    number: {
                      type: "int32",
                      id: 2
                    },
                    options: {
                      type: "EnumValueOptions",
                      id: 3
                    }
                  }
                },
                ServiceDescriptorProto: {
                  edition: "proto2",
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    method: {
                      rule: "repeated",
                      type: "MethodDescriptorProto",
                      id: 2
                    },
                    options: {
                      type: "ServiceOptions",
                      id: 3
                    }
                  }
                },
                MethodDescriptorProto: {
                  edition: "proto2",
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    inputType: {
                      type: "string",
                      id: 2
                    },
                    outputType: {
                      type: "string",
                      id: 3
                    },
                    options: {
                      type: "MethodOptions",
                      id: 4
                    },
                    clientStreaming: {
                      type: "bool",
                      id: 5
                    },
                    serverStreaming: {
                      type: "bool",
                      id: 6
                    }
                  }
                },
                FileOptions: {
                  edition: "proto2",
                  fields: {
                    javaPackage: {
                      type: "string",
                      id: 1
                    },
                    javaOuterClassname: {
                      type: "string",
                      id: 8
                    },
                    javaMultipleFiles: {
                      type: "bool",
                      id: 10
                    },
                    javaGenerateEqualsAndHash: {
                      type: "bool",
                      id: 20,
                      options: {
                        deprecated: true
                      }
                    },
                    javaStringCheckUtf8: {
                      type: "bool",
                      id: 27
                    },
                    optimizeFor: {
                      type: "OptimizeMode",
                      id: 9,
                      options: {
                        default: "SPEED"
                      }
                    },
                    goPackage: {
                      type: "string",
                      id: 11
                    },
                    ccGenericServices: {
                      type: "bool",
                      id: 16
                    },
                    javaGenericServices: {
                      type: "bool",
                      id: 17
                    },
                    pyGenericServices: {
                      type: "bool",
                      id: 18
                    },
                    deprecated: {
                      type: "bool",
                      id: 23
                    },
                    ccEnableArenas: {
                      type: "bool",
                      id: 31,
                      options: {
                        default: true
                      }
                    },
                    objcClassPrefix: {
                      type: "string",
                      id: 36
                    },
                    csharpNamespace: {
                      type: "string",
                      id: 37
                    },
                    swiftPrefix: {
                      type: "string",
                      id: 39
                    },
                    phpClassPrefix: {
                      type: "string",
                      id: 40
                    },
                    phpNamespace: {
                      type: "string",
                      id: 41
                    },
                    phpMetadataNamespace: {
                      type: "string",
                      id: 44
                    },
                    rubyPackage: {
                      type: "string",
                      id: 45
                    },
                    features: {
                      type: "FeatureSet",
                      id: 50
                    },
                    uninterpretedOption: {
                      rule: "repeated",
                      type: "UninterpretedOption",
                      id: 999
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      536870911
                    ]
                  ],
                  reserved: [
                    [
                      42,
                      42
                    ],
                    "php_generic_services",
                    [
                      38,
                      38
                    ]
                  ],
                  nested: {
                    OptimizeMode: {
                      values: {
                        SPEED: 1,
                        CODE_SIZE: 2,
                        LITE_RUNTIME: 3
                      }
                    }
                  }
                },
                MessageOptions: {
                  edition: "proto2",
                  fields: {
                    messageSetWireFormat: {
                      type: "bool",
                      id: 1
                    },
                    noStandardDescriptorAccessor: {
                      type: "bool",
                      id: 2
                    },
                    deprecated: {
                      type: "bool",
                      id: 3
                    },
                    mapEntry: {
                      type: "bool",
                      id: 7
                    },
                    deprecatedLegacyJsonFieldConflicts: {
                      type: "bool",
                      id: 11,
                      options: {
                        deprecated: true
                      }
                    },
                    features: {
                      type: "FeatureSet",
                      id: 12
                    },
                    uninterpretedOption: {
                      rule: "repeated",
                      type: "UninterpretedOption",
                      id: 999
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      536870911
                    ]
                  ],
                  reserved: [
                    [
                      4,
                      4
                    ],
                    [
                      5,
                      5
                    ],
                    [
                      6,
                      6
                    ],
                    [
                      8,
                      8
                    ],
                    [
                      9,
                      9
                    ]
                  ]
                },
                FieldOptions: {
                  edition: "proto2",
                  fields: {
                    ctype: {
                      type: "CType",
                      id: 1,
                      options: {
                        default: "STRING"
                      }
                    },
                    packed: {
                      type: "bool",
                      id: 2
                    },
                    jstype: {
                      type: "JSType",
                      id: 6,
                      options: {
                        default: "JS_NORMAL"
                      }
                    },
                    lazy: {
                      type: "bool",
                      id: 5
                    },
                    unverifiedLazy: {
                      type: "bool",
                      id: 15
                    },
                    deprecated: {
                      type: "bool",
                      id: 3
                    },
                    weak: {
                      type: "bool",
                      id: 10,
                      options: {
                        deprecated: true
                      }
                    },
                    debugRedact: {
                      type: "bool",
                      id: 16
                    },
                    retention: {
                      type: "OptionRetention",
                      id: 17
                    },
                    targets: {
                      rule: "repeated",
                      type: "OptionTargetType",
                      id: 19
                    },
                    editionDefaults: {
                      rule: "repeated",
                      type: "EditionDefault",
                      id: 20
                    },
                    features: {
                      type: "FeatureSet",
                      id: 21
                    },
                    featureSupport: {
                      type: "FeatureSupport",
                      id: 22
                    },
                    uninterpretedOption: {
                      rule: "repeated",
                      type: "UninterpretedOption",
                      id: 999
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      536870911
                    ]
                  ],
                  reserved: [
                    [
                      4,
                      4
                    ],
                    [
                      18,
                      18
                    ]
                  ],
                  nested: {
                    CType: {
                      values: {
                        STRING: 0,
                        CORD: 1,
                        STRING_PIECE: 2
                      }
                    },
                    JSType: {
                      values: {
                        JS_NORMAL: 0,
                        JS_STRING: 1,
                        JS_NUMBER: 2
                      }
                    },
                    OptionRetention: {
                      values: {
                        RETENTION_UNKNOWN: 0,
                        RETENTION_RUNTIME: 1,
                        RETENTION_SOURCE: 2
                      }
                    },
                    OptionTargetType: {
                      values: {
                        TARGET_TYPE_UNKNOWN: 0,
                        TARGET_TYPE_FILE: 1,
                        TARGET_TYPE_EXTENSION_RANGE: 2,
                        TARGET_TYPE_MESSAGE: 3,
                        TARGET_TYPE_FIELD: 4,
                        TARGET_TYPE_ONEOF: 5,
                        TARGET_TYPE_ENUM: 6,
                        TARGET_TYPE_ENUM_ENTRY: 7,
                        TARGET_TYPE_SERVICE: 8,
                        TARGET_TYPE_METHOD: 9
                      }
                    },
                    EditionDefault: {
                      fields: {
                        edition: {
                          type: "Edition",
                          id: 3
                        },
                        value: {
                          type: "string",
                          id: 2
                        }
                      }
                    },
                    FeatureSupport: {
                      fields: {
                        editionIntroduced: {
                          type: "Edition",
                          id: 1
                        },
                        editionDeprecated: {
                          type: "Edition",
                          id: 2
                        },
                        deprecationWarning: {
                          type: "string",
                          id: 3
                        },
                        editionRemoved: {
                          type: "Edition",
                          id: 4
                        }
                      }
                    }
                  }
                },
                OneofOptions: {
                  edition: "proto2",
                  fields: {
                    features: {
                      type: "FeatureSet",
                      id: 1
                    },
                    uninterpretedOption: {
                      rule: "repeated",
                      type: "UninterpretedOption",
                      id: 999
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      536870911
                    ]
                  ]
                },
                EnumOptions: {
                  edition: "proto2",
                  fields: {
                    allowAlias: {
                      type: "bool",
                      id: 2
                    },
                    deprecated: {
                      type: "bool",
                      id: 3
                    },
                    deprecatedLegacyJsonFieldConflicts: {
                      type: "bool",
                      id: 6,
                      options: {
                        deprecated: true
                      }
                    },
                    features: {
                      type: "FeatureSet",
                      id: 7
                    },
                    uninterpretedOption: {
                      rule: "repeated",
                      type: "UninterpretedOption",
                      id: 999
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      536870911
                    ]
                  ],
                  reserved: [
                    [
                      5,
                      5
                    ]
                  ]
                },
                EnumValueOptions: {
                  edition: "proto2",
                  fields: {
                    deprecated: {
                      type: "bool",
                      id: 1
                    },
                    features: {
                      type: "FeatureSet",
                      id: 2
                    },
                    debugRedact: {
                      type: "bool",
                      id: 3
                    },
                    featureSupport: {
                      type: "FieldOptions.FeatureSupport",
                      id: 4
                    },
                    uninterpretedOption: {
                      rule: "repeated",
                      type: "UninterpretedOption",
                      id: 999
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      536870911
                    ]
                  ]
                },
                ServiceOptions: {
                  edition: "proto2",
                  fields: {
                    features: {
                      type: "FeatureSet",
                      id: 34
                    },
                    deprecated: {
                      type: "bool",
                      id: 33
                    },
                    uninterpretedOption: {
                      rule: "repeated",
                      type: "UninterpretedOption",
                      id: 999
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      536870911
                    ]
                  ]
                },
                MethodOptions: {
                  edition: "proto2",
                  fields: {
                    deprecated: {
                      type: "bool",
                      id: 33
                    },
                    idempotencyLevel: {
                      type: "IdempotencyLevel",
                      id: 34,
                      options: {
                        default: "IDEMPOTENCY_UNKNOWN"
                      }
                    },
                    features: {
                      type: "FeatureSet",
                      id: 35
                    },
                    uninterpretedOption: {
                      rule: "repeated",
                      type: "UninterpretedOption",
                      id: 999
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      536870911
                    ]
                  ],
                  nested: {
                    IdempotencyLevel: {
                      values: {
                        IDEMPOTENCY_UNKNOWN: 0,
                        NO_SIDE_EFFECTS: 1,
                        IDEMPOTENT: 2
                      }
                    }
                  }
                },
                UninterpretedOption: {
                  edition: "proto2",
                  fields: {
                    name: {
                      rule: "repeated",
                      type: "NamePart",
                      id: 2
                    },
                    identifierValue: {
                      type: "string",
                      id: 3
                    },
                    positiveIntValue: {
                      type: "uint64",
                      id: 4
                    },
                    negativeIntValue: {
                      type: "int64",
                      id: 5
                    },
                    doubleValue: {
                      type: "double",
                      id: 6
                    },
                    stringValue: {
                      type: "bytes",
                      id: 7
                    },
                    aggregateValue: {
                      type: "string",
                      id: 8
                    }
                  },
                  nested: {
                    NamePart: {
                      fields: {
                        namePart: {
                          rule: "required",
                          type: "string",
                          id: 1
                        },
                        isExtension: {
                          rule: "required",
                          type: "bool",
                          id: 2
                        }
                      }
                    }
                  }
                },
                FeatureSet: {
                  edition: "proto2",
                  fields: {
                    fieldPresence: {
                      type: "FieldPresence",
                      id: 1,
                      options: {
                        retention: "RETENTION_RUNTIME",
                        targets: "TARGET_TYPE_FILE",
                        "feature_support.edition_introduced": "EDITION_2023",
                        "edition_defaults.edition": "EDITION_2023",
                        "edition_defaults.value": "EXPLICIT"
                      }
                    },
                    enumType: {
                      type: "EnumType",
                      id: 2,
                      options: {
                        retention: "RETENTION_RUNTIME",
                        targets: "TARGET_TYPE_FILE",
                        "feature_support.edition_introduced": "EDITION_2023",
                        "edition_defaults.edition": "EDITION_PROTO3",
                        "edition_defaults.value": "OPEN"
                      }
                    },
                    repeatedFieldEncoding: {
                      type: "RepeatedFieldEncoding",
                      id: 3,
                      options: {
                        retention: "RETENTION_RUNTIME",
                        targets: "TARGET_TYPE_FILE",
                        "feature_support.edition_introduced": "EDITION_2023",
                        "edition_defaults.edition": "EDITION_PROTO3",
                        "edition_defaults.value": "PACKED"
                      }
                    },
                    utf8Validation: {
                      type: "Utf8Validation",
                      id: 4,
                      options: {
                        retention: "RETENTION_RUNTIME",
                        targets: "TARGET_TYPE_FILE",
                        "feature_support.edition_introduced": "EDITION_2023",
                        "edition_defaults.edition": "EDITION_PROTO3",
                        "edition_defaults.value": "VERIFY"
                      }
                    },
                    messageEncoding: {
                      type: "MessageEncoding",
                      id: 5,
                      options: {
                        retention: "RETENTION_RUNTIME",
                        targets: "TARGET_TYPE_FILE",
                        "feature_support.edition_introduced": "EDITION_2023",
                        "edition_defaults.edition": "EDITION_LEGACY",
                        "edition_defaults.value": "LENGTH_PREFIXED"
                      }
                    },
                    jsonFormat: {
                      type: "JsonFormat",
                      id: 6,
                      options: {
                        retention: "RETENTION_RUNTIME",
                        targets: "TARGET_TYPE_FILE",
                        "feature_support.edition_introduced": "EDITION_2023",
                        "edition_defaults.edition": "EDITION_PROTO3",
                        "edition_defaults.value": "ALLOW"
                      }
                    },
                    enforceNamingStyle: {
                      type: "EnforceNamingStyle",
                      id: 7,
                      options: {
                        retention: "RETENTION_SOURCE",
                        targets: "TARGET_TYPE_METHOD",
                        "feature_support.edition_introduced": "EDITION_2024",
                        "edition_defaults.edition": "EDITION_2024",
                        "edition_defaults.value": "STYLE2024"
                      }
                    },
                    defaultSymbolVisibility: {
                      type: "VisibilityFeature.DefaultSymbolVisibility",
                      id: 8,
                      options: {
                        retention: "RETENTION_SOURCE",
                        targets: "TARGET_TYPE_FILE",
                        "feature_support.edition_introduced": "EDITION_2024",
                        "edition_defaults.edition": "EDITION_2024",
                        "edition_defaults.value": "EXPORT_TOP_LEVEL"
                      }
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      9994
                    ],
                    [
                      9995,
                      9999
                    ],
                    [
                      1e4,
                      1e4
                    ]
                  ],
                  reserved: [
                    [
                      999,
                      999
                    ]
                  ],
                  nested: {
                    FieldPresence: {
                      values: {
                        FIELD_PRESENCE_UNKNOWN: 0,
                        EXPLICIT: 1,
                        IMPLICIT: 2,
                        LEGACY_REQUIRED: 3
                      }
                    },
                    EnumType: {
                      values: {
                        ENUM_TYPE_UNKNOWN: 0,
                        OPEN: 1,
                        CLOSED: 2
                      }
                    },
                    RepeatedFieldEncoding: {
                      values: {
                        REPEATED_FIELD_ENCODING_UNKNOWN: 0,
                        PACKED: 1,
                        EXPANDED: 2
                      }
                    },
                    Utf8Validation: {
                      values: {
                        UTF8_VALIDATION_UNKNOWN: 0,
                        VERIFY: 2,
                        NONE: 3
                      }
                    },
                    MessageEncoding: {
                      values: {
                        MESSAGE_ENCODING_UNKNOWN: 0,
                        LENGTH_PREFIXED: 1,
                        DELIMITED: 2
                      }
                    },
                    JsonFormat: {
                      values: {
                        JSON_FORMAT_UNKNOWN: 0,
                        ALLOW: 1,
                        LEGACY_BEST_EFFORT: 2
                      }
                    },
                    EnforceNamingStyle: {
                      values: {
                        ENFORCE_NAMING_STYLE_UNKNOWN: 0,
                        STYLE2024: 1,
                        STYLE_LEGACY: 2
                      }
                    },
                    VisibilityFeature: {
                      fields: {},
                      reserved: [
                        [
                          1,
                          536870911
                        ]
                      ],
                      nested: {
                        DefaultSymbolVisibility: {
                          values: {
                            DEFAULT_SYMBOL_VISIBILITY_UNKNOWN: 0,
                            EXPORT_ALL: 1,
                            EXPORT_TOP_LEVEL: 2,
                            LOCAL_ALL: 3,
                            STRICT: 4
                          }
                        }
                      }
                    }
                  }
                },
                FeatureSetDefaults: {
                  edition: "proto2",
                  fields: {
                    defaults: {
                      rule: "repeated",
                      type: "FeatureSetEditionDefault",
                      id: 1
                    },
                    minimumEdition: {
                      type: "Edition",
                      id: 4
                    },
                    maximumEdition: {
                      type: "Edition",
                      id: 5
                    }
                  },
                  nested: {
                    FeatureSetEditionDefault: {
                      fields: {
                        edition: {
                          type: "Edition",
                          id: 3
                        },
                        overridableFeatures: {
                          type: "FeatureSet",
                          id: 4
                        },
                        fixedFeatures: {
                          type: "FeatureSet",
                          id: 5
                        }
                      },
                      reserved: [
                        [
                          1,
                          1
                        ],
                        [
                          2,
                          2
                        ],
                        "features"
                      ]
                    }
                  }
                },
                SourceCodeInfo: {
                  edition: "proto2",
                  fields: {
                    location: {
                      rule: "repeated",
                      type: "Location",
                      id: 1
                    }
                  },
                  extensions: [
                    [
                      536e6,
                      536e6
                    ]
                  ],
                  nested: {
                    Location: {
                      fields: {
                        path: {
                          rule: "repeated",
                          type: "int32",
                          id: 1,
                          options: {
                            packed: true
                          }
                        },
                        span: {
                          rule: "repeated",
                          type: "int32",
                          id: 2,
                          options: {
                            packed: true
                          }
                        },
                        leadingComments: {
                          type: "string",
                          id: 3
                        },
                        trailingComments: {
                          type: "string",
                          id: 4
                        },
                        leadingDetachedComments: {
                          rule: "repeated",
                          type: "string",
                          id: 6
                        }
                      }
                    }
                  }
                },
                GeneratedCodeInfo: {
                  edition: "proto2",
                  fields: {
                    annotation: {
                      rule: "repeated",
                      type: "Annotation",
                      id: 1
                    }
                  },
                  nested: {
                    Annotation: {
                      fields: {
                        path: {
                          rule: "repeated",
                          type: "int32",
                          id: 1,
                          options: {
                            packed: true
                          }
                        },
                        sourceFile: {
                          type: "string",
                          id: 2
                        },
                        begin: {
                          type: "int32",
                          id: 3
                        },
                        end: {
                          type: "int32",
                          id: 4
                        },
                        semantic: {
                          type: "Semantic",
                          id: 5
                        }
                      },
                      nested: {
                        Semantic: {
                          values: {
                            NONE: 0,
                            SET: 1,
                            ALIAS: 2
                          }
                        }
                      }
                    }
                  }
                },
                SymbolVisibility: {
                  edition: "proto2",
                  values: {
                    VISIBILITY_UNSET: 0,
                    VISIBILITY_LOCAL: 1,
                    VISIBILITY_EXPORT: 2
                  }
                }
              }
            }
          }
        }
      }
    };
  }
});

// node_modules/protobufjs/ext/descriptor/index.js
var require_descriptor2 = __commonJS({
  "node_modules/protobufjs/ext/descriptor/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var $protobuf = require_protobufjs();
    module2.exports = exports2 = $protobuf.descriptor = $protobuf.Root.fromJSON(require_descriptor()).lookup(".google.protobuf");
    var Namespace = $protobuf.Namespace;
    var Root2 = $protobuf.Root;
    var Enum = $protobuf.Enum;
    var Type2 = $protobuf.Type;
    var Field = $protobuf.Field;
    var MapField = $protobuf.MapField;
    var OneOf = $protobuf.OneOf;
    var Service = $protobuf.Service;
    var Method = $protobuf.Method;
    Root2.fromDescriptor = /* @__PURE__ */ __name(function fromDescriptor(descriptor2) {
      if (typeof descriptor2.length === "number")
        descriptor2 = exports2.FileDescriptorSet.decode(descriptor2);
      var root = new Root2();
      if (descriptor2.file) {
        var fileDescriptor, filePackage;
        for (var j = 0, i; j < descriptor2.file.length; ++j) {
          filePackage = root;
          if ((fileDescriptor = descriptor2.file[j])["package"] && fileDescriptor["package"].length)
            filePackage = root.define(fileDescriptor["package"]);
          var edition = editionFromDescriptor(fileDescriptor);
          if (fileDescriptor.name && fileDescriptor.name.length)
            root.files.push(filePackage.filename = fileDescriptor.name);
          if (fileDescriptor.messageType)
            for (i = 0; i < fileDescriptor.messageType.length; ++i)
              filePackage.add(Type2.fromDescriptor(fileDescriptor.messageType[i], edition));
          if (fileDescriptor.enumType)
            for (i = 0; i < fileDescriptor.enumType.length; ++i)
              filePackage.add(Enum.fromDescriptor(fileDescriptor.enumType[i], edition));
          if (fileDescriptor.extension)
            for (i = 0; i < fileDescriptor.extension.length; ++i)
              filePackage.add(Field.fromDescriptor(fileDescriptor.extension[i], edition));
          if (fileDescriptor.service)
            for (i = 0; i < fileDescriptor.service.length; ++i)
              filePackage.add(Service.fromDescriptor(fileDescriptor.service[i], edition));
          var opts = fromDescriptorOptions(fileDescriptor.options, exports2.FileOptions);
          if (opts) {
            var ks = Object.keys(opts);
            for (i = 0; i < ks.length; ++i)
              filePackage.setOption(ks[i], opts[ks[i]]);
          }
        }
      }
      return root.resolveAll();
    }, "fromDescriptor");
    Root2.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor(edition) {
      var set = exports2.FileDescriptorSet.create();
      Root_toDescriptorRecursive(this, set.file, edition);
      return set;
    }, "toDescriptor");
    function Root_toDescriptorRecursive(ns, files, edition) {
      var file = exports2.FileDescriptorProto.create({ name: ns.filename || (ns.fullName.substring(1).replace(/\./g, "_") || "root") + ".proto" });
      editionToDescriptor(edition, file);
      if (!(ns instanceof Root2))
        file["package"] = ns.fullName.substring(1);
      for (var i = 0, nested; i < ns.nestedArray.length; ++i)
        if ((nested = ns._nestedArray[i]) instanceof Type2)
          file.messageType.push(nested.toDescriptor(edition));
        else if (nested instanceof Enum)
          file.enumType.push(nested.toDescriptor());
        else if (nested instanceof Field)
          file.extension.push(nested.toDescriptor(edition));
        else if (nested instanceof Service)
          file.service.push(nested.toDescriptor());
        else if (nested instanceof /* plain */
        Namespace)
          Root_toDescriptorRecursive(nested, files, edition);
      file.options = toDescriptorOptions(ns.options, exports2.FileOptions);
      if (file.messageType.length + file.enumType.length + file.extension.length + file.service.length)
        files.push(file);
    }
    __name(Root_toDescriptorRecursive, "Root_toDescriptorRecursive");
    var unnamedMessageIndex = 0;
    Type2.fromDescriptor = /* @__PURE__ */ __name(function fromDescriptor(descriptor2, edition, nested) {
      if (typeof descriptor2.length === "number")
        descriptor2 = exports2.DescriptorProto.decode(descriptor2);
      var type = new Type2(descriptor2.name.length ? descriptor2.name : "Type" + unnamedMessageIndex++, fromDescriptorOptions(descriptor2.options, exports2.MessageOptions)), i;
      if (!nested)
        type._edition = edition;
      if (descriptor2.oneofDecl)
        for (i = 0; i < descriptor2.oneofDecl.length; ++i)
          type.add(OneOf.fromDescriptor(descriptor2.oneofDecl[i]));
      if (descriptor2.field)
        for (i = 0; i < descriptor2.field.length; ++i) {
          var field = Field.fromDescriptor(descriptor2.field[i], edition, true);
          type.add(field);
          if (descriptor2.field[i].hasOwnProperty("oneofIndex"))
            type.oneofsArray[descriptor2.field[i].oneofIndex].add(field);
        }
      if (descriptor2.extension)
        for (i = 0; i < descriptor2.extension.length; ++i)
          type.add(Field.fromDescriptor(descriptor2.extension[i], edition, true));
      if (descriptor2.nestedType)
        for (i = 0; i < descriptor2.nestedType.length; ++i) {
          type.add(Type2.fromDescriptor(descriptor2.nestedType[i], edition, true));
          if (descriptor2.nestedType[i].options && descriptor2.nestedType[i].options.mapEntry)
            type.setOption("map_entry", true);
        }
      if (descriptor2.enumType)
        for (i = 0; i < descriptor2.enumType.length; ++i)
          type.add(Enum.fromDescriptor(descriptor2.enumType[i], edition, true));
      if (descriptor2.extensionRange && descriptor2.extensionRange.length) {
        type.extensions = [];
        for (i = 0; i < descriptor2.extensionRange.length; ++i)
          type.extensions.push([descriptor2.extensionRange[i].start, descriptor2.extensionRange[i].end]);
      }
      if (descriptor2.reservedRange && descriptor2.reservedRange.length || descriptor2.reservedName && descriptor2.reservedName.length) {
        type.reserved = [];
        if (descriptor2.reservedRange)
          for (i = 0; i < descriptor2.reservedRange.length; ++i)
            type.reserved.push([descriptor2.reservedRange[i].start, descriptor2.reservedRange[i].end]);
        if (descriptor2.reservedName)
          for (i = 0; i < descriptor2.reservedName.length; ++i)
            type.reserved.push(descriptor2.reservedName[i]);
      }
      return type;
    }, "fromDescriptor");
    Type2.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor(edition) {
      var descriptor2 = exports2.DescriptorProto.create({ name: this.name }), i;
      for (i = 0; i < this.fieldsArray.length; ++i) {
        var fieldDescriptor;
        descriptor2.field.push(fieldDescriptor = this._fieldsArray[i].toDescriptor(edition));
        if (this._fieldsArray[i] instanceof MapField) {
          var keyType = toDescriptorType(this._fieldsArray[i].keyType, this._fieldsArray[i].resolvedKeyType, false), valueType = toDescriptorType(this._fieldsArray[i].type, this._fieldsArray[i].resolvedType, false), valueTypeName = valueType === /* type */
          11 || valueType === /* enum */
          14 ? this._fieldsArray[i].resolvedType && shortname(this.parent, this._fieldsArray[i].resolvedType) || this._fieldsArray[i].type : void 0;
          descriptor2.nestedType.push(exports2.DescriptorProto.create({
            name: fieldDescriptor.typeName,
            field: [
              exports2.FieldDescriptorProto.create({ name: "key", number: 1, label: 1, type: keyType }),
              // can't reference a type or enum
              exports2.FieldDescriptorProto.create({ name: "value", number: 2, label: 1, type: valueType, typeName: valueTypeName })
            ],
            options: exports2.MessageOptions.create({ mapEntry: true })
          }));
        }
      }
      for (i = 0; i < this.oneofsArray.length; ++i)
        descriptor2.oneofDecl.push(this._oneofsArray[i].toDescriptor());
      for (i = 0; i < this.nestedArray.length; ++i) {
        if (this._nestedArray[i] instanceof Field)
          descriptor2.field.push(this._nestedArray[i].toDescriptor(edition));
        else if (this._nestedArray[i] instanceof Type2)
          descriptor2.nestedType.push(this._nestedArray[i].toDescriptor(edition));
        else if (this._nestedArray[i] instanceof Enum)
          descriptor2.enumType.push(this._nestedArray[i].toDescriptor());
      }
      if (this.extensions)
        for (i = 0; i < this.extensions.length; ++i)
          descriptor2.extensionRange.push(exports2.DescriptorProto.ExtensionRange.create({ start: this.extensions[i][0], end: this.extensions[i][1] }));
      if (this.reserved)
        for (i = 0; i < this.reserved.length; ++i)
          if (typeof this.reserved[i] === "string")
            descriptor2.reservedName.push(this.reserved[i]);
          else
            descriptor2.reservedRange.push(exports2.DescriptorProto.ReservedRange.create({ start: this.reserved[i][0], end: this.reserved[i][1] }));
      descriptor2.options = toDescriptorOptions(this.options, exports2.MessageOptions);
      return descriptor2;
    }, "toDescriptor");
    var numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/;
    Field.fromDescriptor = /* @__PURE__ */ __name(function fromDescriptor(descriptor2, edition, nested) {
      if (typeof descriptor2.length === "number")
        descriptor2 = exports2.DescriptorProto.decode(descriptor2);
      if (typeof descriptor2.number !== "number")
        throw Error("missing field id");
      var fieldType;
      if (descriptor2.typeName && descriptor2.typeName.length)
        fieldType = descriptor2.typeName;
      else
        fieldType = fromDescriptorType(descriptor2.type);
      var fieldRule;
      switch (descriptor2.label) {
        // 0 is reserved for errors
        case 1:
          fieldRule = void 0;
          break;
        case 2:
          fieldRule = "required";
          break;
        case 3:
          fieldRule = "repeated";
          break;
        default:
          throw Error("illegal label: " + descriptor2.label);
      }
      var extendee = descriptor2.extendee;
      if (descriptor2.extendee !== void 0) {
        extendee = extendee.length ? extendee : void 0;
      }
      var field = new Field(
        descriptor2.name.length ? descriptor2.name : "field" + descriptor2.number,
        descriptor2.number,
        fieldType,
        fieldRule,
        extendee
      );
      if (!nested)
        field._edition = edition;
      field.options = fromDescriptorOptions(descriptor2.options, exports2.FieldOptions);
      if (descriptor2.proto3_optional)
        field.options.proto3_optional = true;
      if (descriptor2.defaultValue && descriptor2.defaultValue.length) {
        var defaultValue = descriptor2.defaultValue;
        switch (defaultValue) {
          case "true":
          case "TRUE":
            defaultValue = true;
            break;
          case "false":
          case "FALSE":
            defaultValue = false;
            break;
          default:
            var match2 = numberRe.exec(defaultValue);
            if (match2)
              defaultValue = parseInt(defaultValue);
            break;
        }
        field.setOption("default", defaultValue);
      }
      if (packableDescriptorType(descriptor2.type)) {
        if (edition === "proto3") {
          if (descriptor2.options && !descriptor2.options.packed)
            field.setOption("packed", false);
        } else if ((!edition || edition === "proto2") && descriptor2.options && descriptor2.options.packed)
          field.setOption("packed", true);
      }
      return field;
    }, "fromDescriptor");
    Field.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor(edition) {
      var descriptor2 = exports2.FieldDescriptorProto.create({ name: this.name, number: this.id });
      if (this.map) {
        descriptor2.type = 11;
        descriptor2.typeName = $protobuf.util.ucFirst(this.name);
        descriptor2.label = 3;
      } else {
        switch (descriptor2.type = toDescriptorType(this.type, this.resolve().resolvedType, this.delimited)) {
          case 10:
          // group
          case 11:
          // type
          case 14:
            descriptor2.typeName = this.resolvedType ? shortname(this.parent, this.resolvedType) : this.type;
            break;
        }
        if (this.rule === "repeated") {
          descriptor2.label = 3;
        } else if (this.required && edition === "proto2") {
          descriptor2.label = 2;
        } else {
          descriptor2.label = 1;
        }
      }
      descriptor2.extendee = this.extensionField ? this.extensionField.parent.fullName : this.extend;
      if (this.partOf) {
        if ((descriptor2.oneofIndex = this.parent.oneofsArray.indexOf(this.partOf)) < 0)
          throw Error("missing oneof");
      }
      if (this.options) {
        descriptor2.options = toDescriptorOptions(this.options, exports2.FieldOptions);
        if (this.options["default"] != null)
          descriptor2.defaultValue = String(this.options["default"]);
        if (this.options.proto3_optional)
          descriptor2.proto3_optional = true;
      }
      if (edition === "proto3") {
        if (!this.packed)
          (descriptor2.options || (descriptor2.options = exports2.FieldOptions.create())).packed = false;
      } else if ((!edition || edition === "proto2") && this.packed)
        (descriptor2.options || (descriptor2.options = exports2.FieldOptions.create())).packed = true;
      return descriptor2;
    }, "toDescriptor");
    var unnamedEnumIndex = 0;
    Enum.fromDescriptor = /* @__PURE__ */ __name(function fromDescriptor(descriptor2, edition, nested) {
      if (typeof descriptor2.length === "number")
        descriptor2 = exports2.EnumDescriptorProto.decode(descriptor2);
      var values = {};
      if (descriptor2.value)
        for (var i = 0; i < descriptor2.value.length; ++i) {
          var name3 = descriptor2.value[i].name, value = descriptor2.value[i].number || 0;
          values[name3 && name3.length ? name3 : "NAME" + value] = value;
        }
      var enm = new Enum(
        descriptor2.name && descriptor2.name.length ? descriptor2.name : "Enum" + unnamedEnumIndex++,
        values,
        fromDescriptorOptions(descriptor2.options, exports2.EnumOptions)
      );
      if (!nested)
        enm._edition = edition;
      return enm;
    }, "fromDescriptor");
    Enum.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor() {
      var values = [];
      for (var i = 0, ks = Object.keys(this.values); i < ks.length; ++i)
        values.push(exports2.EnumValueDescriptorProto.create({ name: ks[i], number: this.values[ks[i]] }));
      return exports2.EnumDescriptorProto.create({
        name: this.name,
        value: values,
        options: toDescriptorOptions(this.options, exports2.EnumOptions)
      });
    }, "toDescriptor");
    var unnamedOneofIndex = 0;
    OneOf.fromDescriptor = /* @__PURE__ */ __name(function fromDescriptor(descriptor2) {
      if (typeof descriptor2.length === "number")
        descriptor2 = exports2.OneofDescriptorProto.decode(descriptor2);
      return new OneOf(
        // unnamedOneOfIndex is global, not per type, because we have no ref to a type here
        descriptor2.name && descriptor2.name.length ? descriptor2.name : "oneof" + unnamedOneofIndex++
        // fromDescriptorOptions(descriptor.options, exports.OneofOptions) - only uninterpreted_option
      );
    }, "fromDescriptor");
    OneOf.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor() {
      return exports2.OneofDescriptorProto.create({
        name: this.name
        // options: toDescriptorOptions(this.options, exports.OneofOptions) - only uninterpreted_option
      });
    }, "toDescriptor");
    var unnamedServiceIndex = 0;
    Service.fromDescriptor = /* @__PURE__ */ __name(function fromDescriptor(descriptor2, edition, nested) {
      if (typeof descriptor2.length === "number")
        descriptor2 = exports2.ServiceDescriptorProto.decode(descriptor2);
      var service = new Service(descriptor2.name && descriptor2.name.length ? descriptor2.name : "Service" + unnamedServiceIndex++, fromDescriptorOptions(descriptor2.options, exports2.ServiceOptions));
      if (!nested)
        service._edition = edition;
      if (descriptor2.method)
        for (var i = 0; i < descriptor2.method.length; ++i)
          service.add(Method.fromDescriptor(descriptor2.method[i]));
      return service;
    }, "fromDescriptor");
    Service.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor() {
      var methods = [];
      for (var i = 0; i < this.methodsArray.length; ++i)
        methods.push(this._methodsArray[i].toDescriptor());
      return exports2.ServiceDescriptorProto.create({
        name: this.name,
        method: methods,
        options: toDescriptorOptions(this.options, exports2.ServiceOptions)
      });
    }, "toDescriptor");
    var unnamedMethodIndex = 0;
    Method.fromDescriptor = /* @__PURE__ */ __name(function fromDescriptor(descriptor2) {
      if (typeof descriptor2.length === "number")
        descriptor2 = exports2.MethodDescriptorProto.decode(descriptor2);
      return new Method(
        // unnamedMethodIndex is global, not per service, because we have no ref to a service here
        descriptor2.name && descriptor2.name.length ? descriptor2.name : "Method" + unnamedMethodIndex++,
        "rpc",
        descriptor2.inputType,
        descriptor2.outputType,
        Boolean(descriptor2.clientStreaming),
        Boolean(descriptor2.serverStreaming),
        fromDescriptorOptions(descriptor2.options, exports2.MethodOptions)
      );
    }, "fromDescriptor");
    Method.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor() {
      return exports2.MethodDescriptorProto.create({
        name: this.name,
        inputType: this.resolvedRequestType ? this.resolvedRequestType.fullName : this.requestType,
        outputType: this.resolvedResponseType ? this.resolvedResponseType.fullName : this.responseType,
        clientStreaming: this.requestStream,
        serverStreaming: this.responseStream,
        options: toDescriptorOptions(this.options, exports2.MethodOptions)
      });
    }, "toDescriptor");
    function fromDescriptorType(type) {
      switch (type) {
        // 0 is reserved for errors
        case 1:
          return "double";
        case 2:
          return "float";
        case 3:
          return "int64";
        case 4:
          return "uint64";
        case 5:
          return "int32";
        case 6:
          return "fixed64";
        case 7:
          return "fixed32";
        case 8:
          return "bool";
        case 9:
          return "string";
        case 12:
          return "bytes";
        case 13:
          return "uint32";
        case 15:
          return "sfixed32";
        case 16:
          return "sfixed64";
        case 17:
          return "sint32";
        case 18:
          return "sint64";
      }
      throw Error("illegal type: " + type);
    }
    __name(fromDescriptorType, "fromDescriptorType");
    function packableDescriptorType(type) {
      switch (type) {
        case 1:
        // double
        case 2:
        // float
        case 3:
        // int64
        case 4:
        // uint64
        case 5:
        // int32
        case 6:
        // fixed64
        case 7:
        // fixed32
        case 8:
        // bool
        case 13:
        // uint32
        case 14:
        // enum (!)
        case 15:
        // sfixed32
        case 16:
        // sfixed64
        case 17:
        // sint32
        case 18:
          return true;
      }
      return false;
    }
    __name(packableDescriptorType, "packableDescriptorType");
    function toDescriptorType(type, resolvedType, delimited) {
      switch (type) {
        // 0 is reserved for errors
        case "double":
          return 1;
        case "float":
          return 2;
        case "int64":
          return 3;
        case "uint64":
          return 4;
        case "int32":
          return 5;
        case "fixed64":
          return 6;
        case "fixed32":
          return 7;
        case "bool":
          return 8;
        case "string":
          return 9;
        case "bytes":
          return 12;
        case "uint32":
          return 13;
        case "sfixed32":
          return 15;
        case "sfixed64":
          return 16;
        case "sint32":
          return 17;
        case "sint64":
          return 18;
      }
      if (resolvedType instanceof Enum)
        return 14;
      if (resolvedType instanceof Type2)
        return delimited ? 10 : 11;
      throw Error("illegal type: " + type);
    }
    __name(toDescriptorType, "toDescriptorType");
    function fromDescriptorOptionsRecursive(obj, type) {
      var val = {};
      for (var i = 0, field, key; i < type.fieldsArray.length; ++i) {
        if ((key = (field = type._fieldsArray[i]).name) === "uninterpretedOption") continue;
        if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;
        var newKey = underScore(key);
        if (field.resolvedType instanceof Type2) {
          val[newKey] = fromDescriptorOptionsRecursive(obj[key], field.resolvedType);
        } else if (field.resolvedType instanceof Enum) {
          val[newKey] = field.resolvedType.valuesById[obj[key]];
        } else {
          val[newKey] = obj[key];
        }
      }
      return val;
    }
    __name(fromDescriptorOptionsRecursive, "fromDescriptorOptionsRecursive");
    function fromDescriptorOptions(options2, type) {
      if (!options2)
        return void 0;
      return fromDescriptorOptionsRecursive(type.toObject(options2), type);
    }
    __name(fromDescriptorOptions, "fromDescriptorOptions");
    function toDescriptorOptionsRecursive(obj, type) {
      var val = {};
      var keys = Object.keys(obj);
      for (var i = 0; i < keys.length; ++i) {
        var key = keys[i];
        var newKey = $protobuf.util.camelCase(key);
        if (!Object.prototype.hasOwnProperty.call(type.fields, newKey)) continue;
        var field = type.fields[newKey];
        if (field.resolvedType instanceof Type2) {
          val[newKey] = toDescriptorOptionsRecursive(obj[key], field.resolvedType);
        } else {
          val[newKey] = obj[key];
        }
        if (field.repeated && !Array.isArray(val[newKey])) {
          val[newKey] = [val[newKey]];
        }
      }
      return val;
    }
    __name(toDescriptorOptionsRecursive, "toDescriptorOptionsRecursive");
    function toDescriptorOptions(options2, type) {
      if (!options2)
        return void 0;
      return type.fromObject(toDescriptorOptionsRecursive(options2, type));
    }
    __name(toDescriptorOptions, "toDescriptorOptions");
    function shortname(from, to) {
      var fromPath = from.fullName.split("."), toPath3 = to.fullName.split("."), i = 0, j = 0, k = toPath3.length - 1;
      if (!(from instanceof Root2) && to instanceof Namespace)
        while (i < fromPath.length && j < k && fromPath[i] === toPath3[j]) {
          var other2 = to.lookup(fromPath[i++], true);
          if (other2 !== null && other2 !== to)
            break;
          ++j;
        }
      else
        for (; i < fromPath.length && j < k && fromPath[i] === toPath3[j]; ++i, ++j) ;
      return toPath3.slice(j).join(".");
    }
    __name(shortname, "shortname");
    function underScore(str2) {
      return str2.substring(0, 1) + str2.substring(1).replace(/([A-Z])(?=[a-z]|$)/g, function($0, $1) {
        return "_" + $1.toLowerCase();
      });
    }
    __name(underScore, "underScore");
    function editionFromDescriptor(fileDescriptor) {
      if (fileDescriptor.syntax === "editions") {
        switch (fileDescriptor.edition) {
          case exports2.Edition.EDITION_2023:
            return "2023";
          default:
            throw new Error("Unsupported edition " + fileDescriptor.edition);
        }
      }
      if (fileDescriptor.syntax === "proto3") {
        return "proto3";
      }
      return "proto2";
    }
    __name(editionFromDescriptor, "editionFromDescriptor");
    function editionToDescriptor(edition, fileDescriptor) {
      if (!edition) return;
      if (edition === "proto2" || edition === "proto3") {
        fileDescriptor.syntax = edition;
      } else {
        fileDescriptor.syntax = "editions";
        switch (edition) {
          case "2023":
            fileDescriptor.edition = exports2.Edition.EDITION_2023;
            break;
          default:
            throw new Error("Unsupported edition " + edition);
        }
      }
    }
    __name(editionToDescriptor, "editionToDescriptor");
  }
});

// node_modules/protobufjs/google/protobuf/api.json
var require_api2 = __commonJS({
  "node_modules/protobufjs/google/protobuf/api.json"(exports2, module2) {
    module2.exports = {
      nested: {
        google: {
          nested: {
            protobuf: {
              nested: {
                Api: {
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    methods: {
                      rule: "repeated",
                      type: "Method",
                      id: 2
                    },
                    options: {
                      rule: "repeated",
                      type: "Option",
                      id: 3
                    },
                    version: {
                      type: "string",
                      id: 4
                    },
                    sourceContext: {
                      type: "SourceContext",
                      id: 5
                    },
                    mixins: {
                      rule: "repeated",
                      type: "Mixin",
                      id: 6
                    },
                    syntax: {
                      type: "Syntax",
                      id: 7
                    }
                  }
                },
                Method: {
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    requestTypeUrl: {
                      type: "string",
                      id: 2
                    },
                    requestStreaming: {
                      type: "bool",
                      id: 3
                    },
                    responseTypeUrl: {
                      type: "string",
                      id: 4
                    },
                    responseStreaming: {
                      type: "bool",
                      id: 5
                    },
                    options: {
                      rule: "repeated",
                      type: "Option",
                      id: 6
                    },
                    syntax: {
                      type: "Syntax",
                      id: 7
                    }
                  }
                },
                Mixin: {
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    root: {
                      type: "string",
                      id: 2
                    }
                  }
                },
                SourceContext: {
                  fields: {
                    fileName: {
                      type: "string",
                      id: 1
                    }
                  }
                },
                Option: {
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    value: {
                      type: "Any",
                      id: 2
                    }
                  }
                },
                Syntax: {
                  values: {
                    SYNTAX_PROTO2: 0,
                    SYNTAX_PROTO3: 1
                  }
                }
              }
            }
          }
        }
      }
    };
  }
});

// node_modules/protobufjs/google/protobuf/source_context.json
var require_source_context = __commonJS({
  "node_modules/protobufjs/google/protobuf/source_context.json"(exports2, module2) {
    module2.exports = {
      nested: {
        google: {
          nested: {
            protobuf: {
              nested: {
                SourceContext: {
                  fields: {
                    fileName: {
                      type: "string",
                      id: 1
                    }
                  }
                }
              }
            }
          }
        }
      }
    };
  }
});

// node_modules/protobufjs/google/protobuf/type.json
var require_type2 = __commonJS({
  "node_modules/protobufjs/google/protobuf/type.json"(exports2, module2) {
    module2.exports = {
      nested: {
        google: {
          nested: {
            protobuf: {
              nested: {
                Type: {
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    fields: {
                      rule: "repeated",
                      type: "Field",
                      id: 2
                    },
                    oneofs: {
                      rule: "repeated",
                      type: "string",
                      id: 3
                    },
                    options: {
                      rule: "repeated",
                      type: "Option",
                      id: 4
                    },
                    sourceContext: {
                      type: "SourceContext",
                      id: 5
                    },
                    syntax: {
                      type: "Syntax",
                      id: 6
                    }
                  }
                },
                Field: {
                  fields: {
                    kind: {
                      type: "Kind",
                      id: 1
                    },
                    cardinality: {
                      type: "Cardinality",
                      id: 2
                    },
                    number: {
                      type: "int32",
                      id: 3
                    },
                    name: {
                      type: "string",
                      id: 4
                    },
                    typeUrl: {
                      type: "string",
                      id: 6
                    },
                    oneofIndex: {
                      type: "int32",
                      id: 7
                    },
                    packed: {
                      type: "bool",
                      id: 8
                    },
                    options: {
                      rule: "repeated",
                      type: "Option",
                      id: 9
                    },
                    jsonName: {
                      type: "string",
                      id: 10
                    },
                    defaultValue: {
                      type: "string",
                      id: 11
                    }
                  },
                  nested: {
                    Kind: {
                      values: {
                        TYPE_UNKNOWN: 0,
                        TYPE_DOUBLE: 1,
                        TYPE_FLOAT: 2,
                        TYPE_INT64: 3,
                        TYPE_UINT64: 4,
                        TYPE_INT32: 5,
                        TYPE_FIXED64: 6,
                        TYPE_FIXED32: 7,
                        TYPE_BOOL: 8,
                        TYPE_STRING: 9,
                        TYPE_GROUP: 10,
                        TYPE_MESSAGE: 11,
                        TYPE_BYTES: 12,
                        TYPE_UINT32: 13,
                        TYPE_ENUM: 14,
                        TYPE_SFIXED32: 15,
                        TYPE_SFIXED64: 16,
                        TYPE_SINT32: 17,
                        TYPE_SINT64: 18
                      }
                    },
                    Cardinality: {
                      values: {
                        CARDINALITY_UNKNOWN: 0,
                        CARDINALITY_OPTIONAL: 1,
                        CARDINALITY_REQUIRED: 2,
                        CARDINALITY_REPEATED: 3
                      }
                    }
                  }
                },
                Enum: {
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    enumvalue: {
                      rule: "repeated",
                      type: "EnumValue",
                      id: 2
                    },
                    options: {
                      rule: "repeated",
                      type: "Option",
                      id: 3
                    },
                    sourceContext: {
                      type: "SourceContext",
                      id: 4
                    },
                    syntax: {
                      type: "Syntax",
                      id: 5
                    }
                  }
                },
                EnumValue: {
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    number: {
                      type: "int32",
                      id: 2
                    },
                    options: {
                      rule: "repeated",
                      type: "Option",
                      id: 3
                    }
                  }
                },
                Option: {
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    value: {
                      type: "Any",
                      id: 2
                    }
                  }
                },
                Syntax: {
                  values: {
                    SYNTAX_PROTO2: 0,
                    SYNTAX_PROTO3: 1
                  }
                },
                Any: {
                  fields: {
                    type_url: {
                      type: "string",
                      id: 1
                    },
                    value: {
                      type: "bytes",
                      id: 2
                    }
                  }
                },
                SourceContext: {
                  fields: {
                    fileName: {
                      type: "string",
                      id: 1
                    }
                  }
                }
              }
            }
          }
        }
      }
    };
  }
});

// node_modules/@grpc/proto-loader/build/src/util.js
var require_util12 = __commonJS({
  "node_modules/@grpc/proto-loader/build/src/util.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.addCommonProtos = exports2.loadProtosWithOptionsSync = exports2.loadProtosWithOptions = void 0;
    var fs95 = __require("fs");
    var path108 = __require("path");
    var Protobuf = require_protobufjs();
    function addIncludePathResolver(root, includePaths) {
      const originalResolvePath = root.resolvePath;
      root.resolvePath = (origin, target) => {
        if (path108.isAbsolute(target)) {
          return target;
        }
        for (const directory of includePaths) {
          const fullPath = path108.join(directory, target);
          try {
            fs95.accessSync(fullPath, fs95.constants.R_OK);
            return fullPath;
          } catch (err) {
            continue;
          }
        }
        process.emitWarning(`${target} not found in any of the include paths ${includePaths}`);
        return originalResolvePath(origin, target);
      };
    }
    __name(addIncludePathResolver, "addIncludePathResolver");
    async function loadProtosWithOptions(filename, options2) {
      const root = new Protobuf.Root();
      options2 = options2 || {};
      if (!!options2.includeDirs) {
        if (!Array.isArray(options2.includeDirs)) {
          return Promise.reject(new Error("The includeDirs option must be an array"));
        }
        addIncludePathResolver(root, options2.includeDirs);
      }
      const loadedRoot = await root.load(filename, options2);
      loadedRoot.resolveAll();
      return loadedRoot;
    }
    __name(loadProtosWithOptions, "loadProtosWithOptions");
    exports2.loadProtosWithOptions = loadProtosWithOptions;
    function loadProtosWithOptionsSync(filename, options2) {
      const root = new Protobuf.Root();
      options2 = options2 || {};
      if (!!options2.includeDirs) {
        if (!Array.isArray(options2.includeDirs)) {
          throw new Error("The includeDirs option must be an array");
        }
        addIncludePathResolver(root, options2.includeDirs);
      }
      const loadedRoot = root.loadSync(filename, options2);
      loadedRoot.resolveAll();
      return loadedRoot;
    }
    __name(loadProtosWithOptionsSync, "loadProtosWithOptionsSync");
    exports2.loadProtosWithOptionsSync = loadProtosWithOptionsSync;
    function addCommonProtos() {
      const apiDescriptor = require_api2();
      const descriptorDescriptor = require_descriptor();
      const sourceContextDescriptor = require_source_context();
      const typeDescriptor = require_type2();
      Protobuf.common("api", apiDescriptor.nested.google.nested.protobuf.nested);
      Protobuf.common("descriptor", descriptorDescriptor.nested.google.nested.protobuf.nested);
      Protobuf.common("source_context", sourceContextDescriptor.nested.google.nested.protobuf.nested);
      Protobuf.common("type", typeDescriptor.nested.google.nested.protobuf.nested);
    }
    __name(addCommonProtos, "addCommonProtos");
    exports2.addCommonProtos = addCommonProtos;
  }
});

// node_modules/long/umd/index.js
var require_umd = __commonJS({
  "node_modules/long/umd/index.js"(exports2, module2) {
    init_esbuild_shims();
    (function(global2, factory) {
      function preferDefault(exports3) {
        return exports3.default || exports3;
      }
      __name(preferDefault, "preferDefault");
      if (typeof define === "function" && define.amd) {
        define([], function() {
          var exports3 = {};
          factory(exports3);
          return preferDefault(exports3);
        });
      } else if (typeof exports2 === "object") {
        factory(exports2);
        if (typeof module2 === "object") module2.exports = preferDefault(exports2);
      } else {
        (function() {
          var exports3 = {};
          factory(exports3);
          global2.Long = preferDefault(exports3);
        })();
      }
    })(
      typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : exports2,
      function(_exports) {
        "use strict";
        Object.defineProperty(_exports, "__esModule", {
          value: true
        });
        _exports.default = void 0;
        var wasm2 = null;
        try {
          wasm2 = new WebAssembly.Instance(
            new WebAssembly.Module(
              new Uint8Array([
                // \0asm
                0,
                97,
                115,
                109,
                // version 1
                1,
                0,
                0,
                0,
                // section "type"
                1,
                13,
                2,
                // 0, () => i32
                96,
                0,
                1,
                127,
                // 1, (i32, i32, i32, i32) => i32
                96,
                4,
                127,
                127,
                127,
                127,
                1,
                127,
                // section "function"
                3,
                7,
                6,
                // 0, type 0
                0,
                // 1, type 1
                1,
                // 2, type 1
                1,
                // 3, type 1
                1,
                // 4, type 1
                1,
                // 5, type 1
                1,
                // section "global"
                6,
                6,
                1,
                // 0, "high", mutable i32
                127,
                1,
                65,
                0,
                11,
                // section "export"
                7,
                50,
                6,
                // 0, "mul"
                3,
                109,
                117,
                108,
                0,
                1,
                // 1, "div_s"
                5,
                100,
                105,
                118,
                95,
                115,
                0,
                2,
                // 2, "div_u"
                5,
                100,
                105,
                118,
                95,
                117,
                0,
                3,
                // 3, "rem_s"
                5,
                114,
                101,
                109,
                95,
                115,
                0,
                4,
                // 4, "rem_u"
                5,
                114,
                101,
                109,
                95,
                117,
                0,
                5,
                // 5, "get_high"
                8,
                103,
                101,
                116,
                95,
                104,
                105,
                103,
                104,
                0,
                0,
                // section "code"
                10,
                191,
                1,
                6,
                // 0, "get_high"
                4,
                0,
                35,
                0,
                11,
                // 1, "mul"
                36,
                1,
                1,
                126,
                32,
                0,
                173,
                32,
                1,
                173,
                66,
                32,
                134,
                132,
                32,
                2,
                173,
                32,
                3,
                173,
                66,
                32,
                134,
                132,
                126,
                34,
                4,
                66,
                32,
                135,
                167,
                36,
                0,
                32,
                4,
                167,
                11,
                // 2, "div_s"
                36,
                1,
                1,
                126,
                32,
                0,
                173,
                32,
                1,
                173,
                66,
                32,
                134,
                132,
                32,
                2,
                173,
                32,
                3,
                173,
                66,
                32,
                134,
                132,
                127,
                34,
                4,
                66,
                32,
                135,
                167,
                36,
                0,
                32,
                4,
                167,
                11,
                // 3, "div_u"
                36,
                1,
                1,
                126,
                32,
                0,
                173,
                32,
                1,
                173,
                66,
                32,
                134,
                132,
                32,
                2,
                173,
                32,
                3,
                173,
                66,
                32,
                134,
                132,
                128,
                34,
                4,
                66,
                32,
                135,
                167,
                36,
                0,
                32,
                4,
                167,
                11,
                // 4, "rem_s"
                36,
                1,
                1,
                126,
                32,
                0,
                173,
                32,
                1,
                173,
                66,
                32,
                134,
                132,
                32,
                2,
                173,
                32,
                3,
                173,
                66,
                32,
                134,
                132,
                129,
                34,
                4,
                66,
                32,
                135,
                167,
                36,
                0,
                32,
                4,
                167,
                11,
                // 5, "rem_u"
                36,
                1,
                1,
                126,
                32,
                0,
                173,
                32,
                1,
                173,
                66,
                32,
                134,
                132,
                32,
                2,
                173,
                32,
                3,
                173,
                66,
                32,
                134,
                132,
                130,
                34,
                4,
                66,
                32,
                135,
                167,
                36,
                0,
                32,
                4,
                167,
                11
              ])
            ),
            {}
          ).exports;
        } catch {
        }
        function Long(low, high, unsigned) {
          this.low = low | 0;
          this.high = high | 0;
          this.unsigned = !!unsigned;
        }
        __name(Long, "Long");
        Long.prototype.__isLong__;
        Object.defineProperty(Long.prototype, "__isLong__", {
          value: true
        });
        function isLong(obj) {
          return (obj && obj["__isLong__"]) === true;
        }
        __name(isLong, "isLong");
        function ctz32(value) {
          var c3 = Math.clz32(value & -value);
          return value ? 31 - c3 : c3;
        }
        __name(ctz32, "ctz32");
        Long.isLong = isLong;
        var INT_CACHE = {};
        var UINT_CACHE = {};
        function fromInt(value, unsigned) {
          var obj, cachedObj, cache5;
          if (unsigned) {
            value >>>= 0;
            if (cache5 = 0 <= value && value < 256) {
              cachedObj = UINT_CACHE[value];
              if (cachedObj) return cachedObj;
            }
            obj = fromBits(value, 0, true);
            if (cache5) UINT_CACHE[value] = obj;
            return obj;
          } else {
            value |= 0;
            if (cache5 = -128 <= value && value < 128) {
              cachedObj = INT_CACHE[value];
              if (cachedObj) return cachedObj;
            }
            obj = fromBits(value, value < 0 ? -1 : 0, false);
            if (cache5) INT_CACHE[value] = obj;
            return obj;
          }
        }
        __name(fromInt, "fromInt");
        Long.fromInt = fromInt;
        function fromNumber(value, unsigned) {
          if (isNaN(value)) return unsigned ? UZERO : ZERO;
          if (unsigned) {
            if (value < 0) return UZERO;
            if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE;
          } else {
            if (value <= -TWO_PWR_63_DBL) return MIN_VALUE;
            if (value + 1 >= TWO_PWR_63_DBL) return MAX_VALUE;
          }
          if (value < 0) return fromNumber(-value, unsigned).neg();
          return fromBits(
            value % TWO_PWR_32_DBL | 0,
            value / TWO_PWR_32_DBL | 0,
            unsigned
          );
        }
        __name(fromNumber, "fromNumber");
        Long.fromNumber = fromNumber;
        function fromBits(lowBits, highBits, unsigned) {
          return new Long(lowBits, highBits, unsigned);
        }
        __name(fromBits, "fromBits");
        Long.fromBits = fromBits;
        var pow_dbl = Math.pow;
        function fromString(str2, unsigned, radix) {
          if (str2.length === 0) throw Error("empty string");
          if (typeof unsigned === "number") {
            radix = unsigned;
            unsigned = false;
          } else {
            unsigned = !!unsigned;
          }
          if (str2 === "NaN" || str2 === "Infinity" || str2 === "+Infinity" || str2 === "-Infinity")
            return unsigned ? UZERO : ZERO;
          radix = radix || 10;
          if (radix < 2 || 36 < radix) throw RangeError("radix");
          var p;
          if ((p = str2.indexOf("-")) > 0) throw Error("interior hyphen");
          else if (p === 0) {
            return fromString(str2.substring(1), unsigned, radix).neg();
          }
          var radixToPower = fromNumber(pow_dbl(radix, 8));
          var result = ZERO;
          for (var i = 0; i < str2.length; i += 8) {
            var size = Math.min(8, str2.length - i), value = parseInt(str2.substring(i, i + size), radix);
            if (size < 8) {
              var power = fromNumber(pow_dbl(radix, size));
              result = result.mul(power).add(fromNumber(value));
            } else {
              result = result.mul(radixToPower);
              result = result.add(fromNumber(value));
            }
          }
          result.unsigned = unsigned;
          return result;
        }
        __name(fromString, "fromString");
        Long.fromString = fromString;
        function fromValue(val, unsigned) {
          if (typeof val === "number") return fromNumber(val, unsigned);
          if (typeof val === "string") return fromString(val, unsigned);
          return fromBits(
            val.low,
            val.high,
            typeof unsigned === "boolean" ? unsigned : val.unsigned
          );
        }
        __name(fromValue, "fromValue");
        Long.fromValue = fromValue;
        var TWO_PWR_16_DBL = 1 << 16;
        var TWO_PWR_24_DBL = 1 << 24;
        var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
        var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
        var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
        var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
        var ZERO = fromInt(0);
        Long.ZERO = ZERO;
        var UZERO = fromInt(0, true);
        Long.UZERO = UZERO;
        var ONE = fromInt(1);
        Long.ONE = ONE;
        var UONE = fromInt(1, true);
        Long.UONE = UONE;
        var NEG_ONE = fromInt(-1);
        Long.NEG_ONE = NEG_ONE;
        var MAX_VALUE = fromBits(4294967295 | 0, 2147483647 | 0, false);
        Long.MAX_VALUE = MAX_VALUE;
        var MAX_UNSIGNED_VALUE = fromBits(4294967295 | 0, 4294967295 | 0, true);
        Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
        var MIN_VALUE = fromBits(0, 2147483648 | 0, false);
        Long.MIN_VALUE = MIN_VALUE;
        var LongPrototype = Long.prototype;
        LongPrototype.toInt = /* @__PURE__ */ __name(function toInt2() {
          return this.unsigned ? this.low >>> 0 : this.low;
        }, "toInt");
        LongPrototype.toNumber = /* @__PURE__ */ __name(function toNumber2() {
          if (this.unsigned)
            return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
          return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
        }, "toNumber");
        LongPrototype.toString = /* @__PURE__ */ __name(function toString(radix) {
          radix = radix || 10;
          if (radix < 2 || 36 < radix) throw RangeError("radix");
          if (this.isZero()) return "0";
          if (this.isNegative()) {
            if (this.eq(MIN_VALUE)) {
              var radixLong = fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
              return div.toString(radix) + rem1.toInt().toString(radix);
            } else return "-" + this.neg().toString(radix);
          }
          var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), rem = this;
          var result = "";
          while (true) {
            var remDiv = rem.div(radixToPower), intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, digits2 = intval.toString(radix);
            rem = remDiv;
            if (rem.isZero()) return digits2 + result;
            else {
              while (digits2.length < 6) digits2 = "0" + digits2;
              result = "" + digits2 + result;
            }
          }
        }, "toString");
        LongPrototype.getHighBits = /* @__PURE__ */ __name(function getHighBits() {
          return this.high;
        }, "getHighBits");
        LongPrototype.getHighBitsUnsigned = /* @__PURE__ */ __name(function getHighBitsUnsigned() {
          return this.high >>> 0;
        }, "getHighBitsUnsigned");
        LongPrototype.getLowBits = /* @__PURE__ */ __name(function getLowBits() {
          return this.low;
        }, "getLowBits");
        LongPrototype.getLowBitsUnsigned = /* @__PURE__ */ __name(function getLowBitsUnsigned() {
          return this.low >>> 0;
        }, "getLowBitsUnsigned");
        LongPrototype.getNumBitsAbs = /* @__PURE__ */ __name(function getNumBitsAbs() {
          if (this.isNegative())
            return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
          var val = this.high != 0 ? this.high : this.low;
          for (var bit = 31; bit > 0; bit--) if ((val & 1 << bit) != 0) break;
          return this.high != 0 ? bit + 33 : bit + 1;
        }, "getNumBitsAbs");
        LongPrototype.isSafeInteger = /* @__PURE__ */ __name(function isSafeInteger() {
          var top11Bits = this.high >> 21;
          if (!top11Bits) return true;
          if (this.unsigned) return false;
          return top11Bits === -1 && !(this.low === 0 && this.high === -2097152);
        }, "isSafeInteger");
        LongPrototype.isZero = /* @__PURE__ */ __name(function isZero() {
          return this.high === 0 && this.low === 0;
        }, "isZero");
        LongPrototype.eqz = LongPrototype.isZero;
        LongPrototype.isNegative = /* @__PURE__ */ __name(function isNegative() {
          return !this.unsigned && this.high < 0;
        }, "isNegative");
        LongPrototype.isPositive = /* @__PURE__ */ __name(function isPositive() {
          return this.unsigned || this.high >= 0;
        }, "isPositive");
        LongPrototype.isOdd = /* @__PURE__ */ __name(function isOdd() {
          return (this.low & 1) === 1;
        }, "isOdd");
        LongPrototype.isEven = /* @__PURE__ */ __name(function isEven() {
          return (this.low & 1) === 0;
        }, "isEven");
        LongPrototype.equals = /* @__PURE__ */ __name(function equals2(other2) {
          if (!isLong(other2)) other2 = fromValue(other2);
          if (this.unsigned !== other2.unsigned && this.high >>> 31 === 1 && other2.high >>> 31 === 1)
            return false;
          return this.high === other2.high && this.low === other2.low;
        }, "equals");
        LongPrototype.eq = LongPrototype.equals;
        LongPrototype.notEquals = /* @__PURE__ */ __name(function notEquals(other2) {
          return !this.eq(
            /* validates */
            other2
          );
        }, "notEquals");
        LongPrototype.neq = LongPrototype.notEquals;
        LongPrototype.ne = LongPrototype.notEquals;
        LongPrototype.lessThan = /* @__PURE__ */ __name(function lessThan(other2) {
          return this.comp(
            /* validates */
            other2
          ) < 0;
        }, "lessThan");
        LongPrototype.lt = LongPrototype.lessThan;
        LongPrototype.lessThanOrEqual = /* @__PURE__ */ __name(function lessThanOrEqual(other2) {
          return this.comp(
            /* validates */
            other2
          ) <= 0;
        }, "lessThanOrEqual");
        LongPrototype.lte = LongPrototype.lessThanOrEqual;
        LongPrototype.le = LongPrototype.lessThanOrEqual;
        LongPrototype.greaterThan = /* @__PURE__ */ __name(function greaterThan(other2) {
          return this.comp(
            /* validates */
            other2
          ) > 0;
        }, "greaterThan");
        LongPrototype.gt = LongPrototype.greaterThan;
        LongPrototype.greaterThanOrEqual = /* @__PURE__ */ __name(function greaterThanOrEqual(other2) {
          return this.comp(
            /* validates */
            other2
          ) >= 0;
        }, "greaterThanOrEqual");
        LongPrototype.gte = LongPrototype.greaterThanOrEqual;
        LongPrototype.ge = LongPrototype.greaterThanOrEqual;
        LongPrototype.compare = /* @__PURE__ */ __name(function compare(other2) {
          if (!isLong(other2)) other2 = fromValue(other2);
          if (this.eq(other2)) return 0;
          var thisNeg = this.isNegative(), otherNeg = other2.isNegative();
          if (thisNeg && !otherNeg) return -1;
          if (!thisNeg && otherNeg) return 1;
          if (!this.unsigned) return this.sub(other2).isNegative() ? -1 : 1;
          return other2.high >>> 0 > this.high >>> 0 || other2.high === this.high && other2.low >>> 0 > this.low >>> 0 ? -1 : 1;
        }, "compare");
        LongPrototype.comp = LongPrototype.compare;
        LongPrototype.negate = /* @__PURE__ */ __name(function negate() {
          if (!this.unsigned && this.eq(MIN_VALUE)) return MIN_VALUE;
          return this.not().add(ONE);
        }, "negate");
        LongPrototype.neg = LongPrototype.negate;
        LongPrototype.add = /* @__PURE__ */ __name(function add(addend) {
          if (!isLong(addend)) addend = fromValue(addend);
          var a48 = this.high >>> 16;
          var a32 = this.high & 65535;
          var a16 = this.low >>> 16;
          var a00 = this.low & 65535;
          var b48 = addend.high >>> 16;
          var b32 = addend.high & 65535;
          var b16 = addend.low >>> 16;
          var b00 = addend.low & 65535;
          var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
          c00 += a00 + b00;
          c16 += c00 >>> 16;
          c00 &= 65535;
          c16 += a16 + b16;
          c32 += c16 >>> 16;
          c16 &= 65535;
          c32 += a32 + b32;
          c48 += c32 >>> 16;
          c32 &= 65535;
          c48 += a48 + b48;
          c48 &= 65535;
          return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
        }, "add");
        LongPrototype.subtract = /* @__PURE__ */ __name(function subtract(subtrahend) {
          if (!isLong(subtrahend)) subtrahend = fromValue(subtrahend);
          return this.add(subtrahend.neg());
        }, "subtract");
        LongPrototype.sub = LongPrototype.subtract;
        LongPrototype.multiply = /* @__PURE__ */ __name(function multiply(multiplier) {
          if (this.isZero()) return this;
          if (!isLong(multiplier)) multiplier = fromValue(multiplier);
          if (wasm2) {
            var low = wasm2["mul"](
              this.low,
              this.high,
              multiplier.low,
              multiplier.high
            );
            return fromBits(low, wasm2["get_high"](), this.unsigned);
          }
          if (multiplier.isZero()) return this.unsigned ? UZERO : ZERO;
          if (this.eq(MIN_VALUE)) return multiplier.isOdd() ? MIN_VALUE : ZERO;
          if (multiplier.eq(MIN_VALUE)) return this.isOdd() ? MIN_VALUE : ZERO;
          if (this.isNegative()) {
            if (multiplier.isNegative()) return this.neg().mul(multiplier.neg());
            else return this.neg().mul(multiplier).neg();
          } else if (multiplier.isNegative())
            return this.mul(multiplier.neg()).neg();
          if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
            return fromNumber(
              this.toNumber() * multiplier.toNumber(),
              this.unsigned
            );
          var a48 = this.high >>> 16;
          var a32 = this.high & 65535;
          var a16 = this.low >>> 16;
          var a00 = this.low & 65535;
          var b48 = multiplier.high >>> 16;
          var b32 = multiplier.high & 65535;
          var b16 = multiplier.low >>> 16;
          var b00 = multiplier.low & 65535;
          var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
          c00 += a00 * b00;
          c16 += c00 >>> 16;
          c00 &= 65535;
          c16 += a16 * b00;
          c32 += c16 >>> 16;
          c16 &= 65535;
          c16 += a00 * b16;
          c32 += c16 >>> 16;
          c16 &= 65535;
          c32 += a32 * b00;
          c48 += c32 >>> 16;
          c32 &= 65535;
          c32 += a16 * b16;
          c48 += c32 >>> 16;
          c32 &= 65535;
          c32 += a00 * b32;
          c48 += c32 >>> 16;
          c32 &= 65535;
          c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
          c48 &= 65535;
          return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
        }, "multiply");
        LongPrototype.mul = LongPrototype.multiply;
        LongPrototype.divide = /* @__PURE__ */ __name(function divide(divisor) {
          if (!isLong(divisor)) divisor = fromValue(divisor);
          if (divisor.isZero()) throw Error("division by zero");
          if (wasm2) {
            if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) {
              return this;
            }
            var low = (this.unsigned ? wasm2["div_u"] : wasm2["div_s"])(
              this.low,
              this.high,
              divisor.low,
              divisor.high
            );
            return fromBits(low, wasm2["get_high"](), this.unsigned);
          }
          if (this.isZero()) return this.unsigned ? UZERO : ZERO;
          var approx, rem, res;
          if (!this.unsigned) {
            if (this.eq(MIN_VALUE)) {
              if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
                return MIN_VALUE;
              else if (divisor.eq(MIN_VALUE)) return ONE;
              else {
                var halfThis = this.shr(1);
                approx = halfThis.div(divisor).shl(1);
                if (approx.eq(ZERO)) {
                  return divisor.isNegative() ? ONE : NEG_ONE;
                } else {
                  rem = this.sub(divisor.mul(approx));
                  res = approx.add(rem.div(divisor));
                  return res;
                }
              }
            } else if (divisor.eq(MIN_VALUE)) return this.unsigned ? UZERO : ZERO;
            if (this.isNegative()) {
              if (divisor.isNegative()) return this.neg().div(divisor.neg());
              return this.neg().div(divisor).neg();
            } else if (divisor.isNegative()) return this.div(divisor.neg()).neg();
            res = ZERO;
          } else {
            if (!divisor.unsigned) divisor = divisor.toUnsigned();
            if (divisor.gt(this)) return UZERO;
            if (divisor.gt(this.shru(1)))
              return UONE;
            res = UZERO;
          }
          rem = this;
          while (rem.gte(divisor)) {
            approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
            var log2 = Math.ceil(Math.log(approx) / Math.LN2), delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48), approxRes = fromNumber(approx), approxRem = approxRes.mul(divisor);
            while (approxRem.isNegative() || approxRem.gt(rem)) {
              approx -= delta;
              approxRes = fromNumber(approx, this.unsigned);
              approxRem = approxRes.mul(divisor);
            }
            if (approxRes.isZero()) approxRes = ONE;
            res = res.add(approxRes);
            rem = rem.sub(approxRem);
          }
          return res;
        }, "divide");
        LongPrototype.div = LongPrototype.divide;
        LongPrototype.modulo = /* @__PURE__ */ __name(function modulo(divisor) {
          if (!isLong(divisor)) divisor = fromValue(divisor);
          if (wasm2) {
            var low = (this.unsigned ? wasm2["rem_u"] : wasm2["rem_s"])(
              this.low,
              this.high,
              divisor.low,
              divisor.high
            );
            return fromBits(low, wasm2["get_high"](), this.unsigned);
          }
          return this.sub(this.div(divisor).mul(divisor));
        }, "modulo");
        LongPrototype.mod = LongPrototype.modulo;
        LongPrototype.rem = LongPrototype.modulo;
        LongPrototype.not = /* @__PURE__ */ __name(function not() {
          return fromBits(~this.low, ~this.high, this.unsigned);
        }, "not");
        LongPrototype.countLeadingZeros = /* @__PURE__ */ __name(function countLeadingZeros() {
          return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32;
        }, "countLeadingZeros");
        LongPrototype.clz = LongPrototype.countLeadingZeros;
        LongPrototype.countTrailingZeros = /* @__PURE__ */ __name(function countTrailingZeros() {
          return this.low ? ctz32(this.low) : ctz32(this.high) + 32;
        }, "countTrailingZeros");
        LongPrototype.ctz = LongPrototype.countTrailingZeros;
        LongPrototype.and = /* @__PURE__ */ __name(function and(other2) {
          if (!isLong(other2)) other2 = fromValue(other2);
          return fromBits(
            this.low & other2.low,
            this.high & other2.high,
            this.unsigned
          );
        }, "and");
        LongPrototype.or = /* @__PURE__ */ __name(function or(other2) {
          if (!isLong(other2)) other2 = fromValue(other2);
          return fromBits(
            this.low | other2.low,
            this.high | other2.high,
            this.unsigned
          );
        }, "or");
        LongPrototype.xor = /* @__PURE__ */ __name(function xor(other2) {
          if (!isLong(other2)) other2 = fromValue(other2);
          return fromBits(
            this.low ^ other2.low,
            this.high ^ other2.high,
            this.unsigned
          );
        }, "xor");
        LongPrototype.shiftLeft = /* @__PURE__ */ __name(function shiftLeft(numBits) {
          if (isLong(numBits)) numBits = numBits.toInt();
          if ((numBits &= 63) === 0) return this;
          else if (numBits < 32)
            return fromBits(
              this.low << numBits,
              this.high << numBits | this.low >>> 32 - numBits,
              this.unsigned
            );
          else return fromBits(0, this.low << numBits - 32, this.unsigned);
        }, "shiftLeft");
        LongPrototype.shl = LongPrototype.shiftLeft;
        LongPrototype.shiftRight = /* @__PURE__ */ __name(function shiftRight(numBits) {
          if (isLong(numBits)) numBits = numBits.toInt();
          if ((numBits &= 63) === 0) return this;
          else if (numBits < 32)
            return fromBits(
              this.low >>> numBits | this.high << 32 - numBits,
              this.high >> numBits,
              this.unsigned
            );
          else
            return fromBits(
              this.high >> numBits - 32,
              this.high >= 0 ? 0 : -1,
              this.unsigned
            );
        }, "shiftRight");
        LongPrototype.shr = LongPrototype.shiftRight;
        LongPrototype.shiftRightUnsigned = /* @__PURE__ */ __name(function shiftRightUnsigned(numBits) {
          if (isLong(numBits)) numBits = numBits.toInt();
          if ((numBits &= 63) === 0) return this;
          if (numBits < 32)
            return fromBits(
              this.low >>> numBits | this.high << 32 - numBits,
              this.high >>> numBits,
              this.unsigned
            );
          if (numBits === 32) return fromBits(this.high, 0, this.unsigned);
          return fromBits(this.high >>> numBits - 32, 0, this.unsigned);
        }, "shiftRightUnsigned");
        LongPrototype.shru = LongPrototype.shiftRightUnsigned;
        LongPrototype.shr_u = LongPrototype.shiftRightUnsigned;
        LongPrototype.rotateLeft = /* @__PURE__ */ __name(function rotateLeft(numBits) {
          var b;
          if (isLong(numBits)) numBits = numBits.toInt();
          if ((numBits &= 63) === 0) return this;
          if (numBits === 32) return fromBits(this.high, this.low, this.unsigned);
          if (numBits < 32) {
            b = 32 - numBits;
            return fromBits(
              this.low << numBits | this.high >>> b,
              this.high << numBits | this.low >>> b,
              this.unsigned
            );
          }
          numBits -= 32;
          b = 32 - numBits;
          return fromBits(
            this.high << numBits | this.low >>> b,
            this.low << numBits | this.high >>> b,
            this.unsigned
          );
        }, "rotateLeft");
        LongPrototype.rotl = LongPrototype.rotateLeft;
        LongPrototype.rotateRight = /* @__PURE__ */ __name(function rotateRight(numBits) {
          var b;
          if (isLong(numBits)) numBits = numBits.toInt();
          if ((numBits &= 63) === 0) return this;
          if (numBits === 32) return fromBits(this.high, this.low, this.unsigned);
          if (numBits < 32) {
            b = 32 - numBits;
            return fromBits(
              this.high << b | this.low >>> numBits,
              this.low << b | this.high >>> numBits,
              this.unsigned
            );
          }
          numBits -= 32;
          b = 32 - numBits;
          return fromBits(
            this.low << b | this.high >>> numBits,
            this.high << b | this.low >>> numBits,
            this.unsigned
          );
        }, "rotateRight");
        LongPrototype.rotr = LongPrototype.rotateRight;
        LongPrototype.toSigned = /* @__PURE__ */ __name(function toSigned() {
          if (!this.unsigned) return this;
          return fromBits(this.low, this.high, false);
        }, "toSigned");
        LongPrototype.toUnsigned = /* @__PURE__ */ __name(function toUnsigned() {
          if (this.unsigned) return this;
          return fromBits(this.low, this.high, true);
        }, "toUnsigned");
        LongPrototype.toBytes = /* @__PURE__ */ __name(function toBytes(le) {
          return le ? this.toBytesLE() : this.toBytesBE();
        }, "toBytes");
        LongPrototype.toBytesLE = /* @__PURE__ */ __name(function toBytesLE() {
          var hi = this.high, lo = this.low;
          return [
            lo & 255,
            lo >>> 8 & 255,
            lo >>> 16 & 255,
            lo >>> 24,
            hi & 255,
            hi >>> 8 & 255,
            hi >>> 16 & 255,
            hi >>> 24
          ];
        }, "toBytesLE");
        LongPrototype.toBytesBE = /* @__PURE__ */ __name(function toBytesBE() {
          var hi = this.high, lo = this.low;
          return [
            hi >>> 24,
            hi >>> 16 & 255,
            hi >>> 8 & 255,
            hi & 255,
            lo >>> 24,
            lo >>> 16 & 255,
            lo >>> 8 & 255,
            lo & 255
          ];
        }, "toBytesBE");
        Long.fromBytes = /* @__PURE__ */ __name(function fromBytes(bytes, unsigned, le) {
          return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
        }, "fromBytes");
        Long.fromBytesLE = /* @__PURE__ */ __name(function fromBytesLE(bytes, unsigned) {
          return new Long(
            bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24,
            bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24,
            unsigned
          );
        }, "fromBytesLE");
        Long.fromBytesBE = /* @__PURE__ */ __name(function fromBytesBE(bytes, unsigned) {
          return new Long(
            bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7],
            bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3],
            unsigned
          );
        }, "fromBytesBE");
        if (typeof BigInt === "function") {
          Long.fromBigInt = /* @__PURE__ */ __name(function fromBigInt(value, unsigned) {
            var lowBits = Number(BigInt.asIntN(32, value));
            var highBits = Number(BigInt.asIntN(32, value >> BigInt(32)));
            return fromBits(lowBits, highBits, unsigned);
          }, "fromBigInt");
          Long.fromValue = /* @__PURE__ */ __name(function fromValueWithBigInt(value, unsigned) {
            if (typeof value === "bigint") return Long.fromBigInt(value, unsigned);
            return fromValue(value, unsigned);
          }, "fromValueWithBigInt");
          LongPrototype.toBigInt = /* @__PURE__ */ __name(function toBigInt() {
            var lowBigInt = BigInt(this.low >>> 0);
            var highBigInt = BigInt(this.unsigned ? this.high >>> 0 : this.high);
            return highBigInt << BigInt(32) | lowBigInt;
          }, "toBigInt");
        }
        var _default = _exports.default = Long;
      }
    );
  }
});

// node_modules/@grpc/proto-loader/build/src/index.js
var require_src10 = __commonJS({
  "node_modules/@grpc/proto-loader/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.loadFileDescriptorSetFromObject = exports2.loadFileDescriptorSetFromBuffer = exports2.fromJSON = exports2.loadSync = exports2.load = exports2.IdempotencyLevel = exports2.isAnyExtension = exports2.Long = void 0;
    var camelCase3 = require_lodash();
    var Protobuf = require_protobufjs();
    var descriptor2 = require_descriptor2();
    var util_1 = require_util12();
    var Long = require_umd();
    exports2.Long = Long;
    function isAnyExtension(obj) {
      return "@type" in obj && typeof obj["@type"] === "string";
    }
    __name(isAnyExtension, "isAnyExtension");
    exports2.isAnyExtension = isAnyExtension;
    var IdempotencyLevel;
    (function(IdempotencyLevel2) {
      IdempotencyLevel2["IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN";
      IdempotencyLevel2["NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS";
      IdempotencyLevel2["IDEMPOTENT"] = "IDEMPOTENT";
    })(IdempotencyLevel = exports2.IdempotencyLevel || (exports2.IdempotencyLevel = {}));
    var descriptorOptions = {
      longs: String,
      enums: String,
      bytes: String,
      defaults: true,
      oneofs: true,
      json: true
    };
    function joinName(baseName, name3) {
      if (baseName === "") {
        return name3;
      } else {
        return baseName + "." + name3;
      }
    }
    __name(joinName, "joinName");
    function isHandledReflectionObject(obj) {
      return obj instanceof Protobuf.Service || obj instanceof Protobuf.Type || obj instanceof Protobuf.Enum;
    }
    __name(isHandledReflectionObject, "isHandledReflectionObject");
    function isNamespaceBase(obj) {
      return obj instanceof Protobuf.Namespace || obj instanceof Protobuf.Root;
    }
    __name(isNamespaceBase, "isNamespaceBase");
    function getAllHandledReflectionObjects(obj, parentName) {
      const objName = joinName(parentName, obj.name);
      if (isHandledReflectionObject(obj)) {
        return [[objName, obj]];
      } else {
        if (isNamespaceBase(obj) && typeof obj.nested !== "undefined") {
          return Object.keys(obj.nested).map((name3) => {
            return getAllHandledReflectionObjects(obj.nested[name3], objName);
          }).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
        }
      }
      return [];
    }
    __name(getAllHandledReflectionObjects, "getAllHandledReflectionObjects");
    function createDeserializer(cls, options2) {
      return /* @__PURE__ */ __name(function deserialize(argBuf) {
        return cls.toObject(cls.decode(argBuf), options2);
      }, "deserialize");
    }
    __name(createDeserializer, "createDeserializer");
    function createSerializer(cls) {
      return /* @__PURE__ */ __name(function serialize2(arg) {
        if (Array.isArray(arg)) {
          throw new Error(`Failed to serialize message: expected object with ${cls.name} structure, got array instead`);
        }
        const message = cls.fromObject(arg);
        return cls.encode(message).finish();
      }, "serialize");
    }
    __name(createSerializer, "createSerializer");
    function mapMethodOptions(options2) {
      return (options2 || []).reduce((obj, item) => {
        for (const [key, value] of Object.entries(item)) {
          switch (key) {
            case "uninterpreted_option":
              obj.uninterpreted_option.push(item.uninterpreted_option);
              break;
            default:
              obj[key] = value;
          }
        }
        return obj;
      }, {
        deprecated: false,
        idempotency_level: IdempotencyLevel.IDEMPOTENCY_UNKNOWN,
        uninterpreted_option: []
      });
    }
    __name(mapMethodOptions, "mapMethodOptions");
    function createMethodDefinition(method, serviceName, options2, fileDescriptors) {
      const requestType = method.resolvedRequestType;
      const responseType = method.resolvedResponseType;
      return {
        path: "/" + serviceName + "/" + method.name,
        requestStream: !!method.requestStream,
        responseStream: !!method.responseStream,
        requestSerialize: createSerializer(requestType),
        requestDeserialize: createDeserializer(requestType, options2),
        responseSerialize: createSerializer(responseType),
        responseDeserialize: createDeserializer(responseType, options2),
        // TODO(murgatroid99): Find a better way to handle this
        originalName: camelCase3(method.name),
        requestType: createMessageDefinition(requestType, fileDescriptors),
        responseType: createMessageDefinition(responseType, fileDescriptors),
        options: mapMethodOptions(method.parsedOptions)
      };
    }
    __name(createMethodDefinition, "createMethodDefinition");
    function createServiceDefinition(service, name3, options2, fileDescriptors) {
      const def2 = {};
      for (const method of service.methodsArray) {
        def2[method.name] = createMethodDefinition(method, name3, options2, fileDescriptors);
      }
      return def2;
    }
    __name(createServiceDefinition, "createServiceDefinition");
    function createMessageDefinition(message, fileDescriptors) {
      const messageDescriptor = message.toDescriptor("proto3");
      return {
        format: "Protocol Buffer 3 DescriptorProto",
        type: messageDescriptor.$type.toObject(messageDescriptor, descriptorOptions),
        fileDescriptorProtos: fileDescriptors
      };
    }
    __name(createMessageDefinition, "createMessageDefinition");
    function createEnumDefinition(enumType2, fileDescriptors) {
      const enumDescriptor = enumType2.toDescriptor("proto3");
      return {
        format: "Protocol Buffer 3 EnumDescriptorProto",
        type: enumDescriptor.$type.toObject(enumDescriptor, descriptorOptions),
        fileDescriptorProtos: fileDescriptors
      };
    }
    __name(createEnumDefinition, "createEnumDefinition");
    function createDefinition(obj, name3, options2, fileDescriptors) {
      if (obj instanceof Protobuf.Service) {
        return createServiceDefinition(obj, name3, options2, fileDescriptors);
      } else if (obj instanceof Protobuf.Type) {
        return createMessageDefinition(obj, fileDescriptors);
      } else if (obj instanceof Protobuf.Enum) {
        return createEnumDefinition(obj, fileDescriptors);
      } else {
        throw new Error("Type mismatch in reflection object handling");
      }
    }
    __name(createDefinition, "createDefinition");
    function createPackageDefinition(root, options2) {
      const def2 = {};
      root.resolveAll();
      const descriptorList = root.toDescriptor("proto3").file;
      const bufferList = descriptorList.map((value) => Buffer.from(descriptor2.FileDescriptorProto.encode(value).finish()));
      for (const [name3, obj] of getAllHandledReflectionObjects(root, "")) {
        def2[name3] = createDefinition(obj, name3, options2, bufferList);
      }
      return def2;
    }
    __name(createPackageDefinition, "createPackageDefinition");
    function createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options2) {
      options2 = options2 || {};
      const root = Protobuf.Root.fromDescriptor(decodedDescriptorSet);
      root.resolveAll();
      return createPackageDefinition(root, options2);
    }
    __name(createPackageDefinitionFromDescriptorSet, "createPackageDefinitionFromDescriptorSet");
    function load(filename, options2) {
      return (0, util_1.loadProtosWithOptions)(filename, options2).then((loadedRoot) => {
        return createPackageDefinition(loadedRoot, options2);
      });
    }
    __name(load, "load");
    exports2.load = load;
    function loadSync(filename, options2) {
      const loadedRoot = (0, util_1.loadProtosWithOptionsSync)(filename, options2);
      return createPackageDefinition(loadedRoot, options2);
    }
    __name(loadSync, "loadSync");
    exports2.loadSync = loadSync;
    function fromJSON(json2, options2) {
      options2 = options2 || {};
      const loadedRoot = Protobuf.Root.fromJSON(json2);
      loadedRoot.resolveAll();
      return createPackageDefinition(loadedRoot, options2);
    }
    __name(fromJSON, "fromJSON");
    exports2.fromJSON = fromJSON;
    function loadFileDescriptorSetFromBuffer(descriptorSet, options2) {
      const decodedDescriptorSet = descriptor2.FileDescriptorSet.decode(descriptorSet);
      return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options2);
    }
    __name(loadFileDescriptorSetFromBuffer, "loadFileDescriptorSetFromBuffer");
    exports2.loadFileDescriptorSetFromBuffer = loadFileDescriptorSetFromBuffer;
    function loadFileDescriptorSetFromObject(descriptorSet, options2) {
      const decodedDescriptorSet = descriptor2.FileDescriptorSet.fromObject(descriptorSet);
      return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options2);
    }
    __name(loadFileDescriptorSetFromObject, "loadFileDescriptorSetFromObject");
    exports2.loadFileDescriptorSetFromObject = loadFileDescriptorSetFromObject;
    (0, util_1.addCommonProtos)();
  }
});

// node_modules/@grpc/grpc-js/build/src/channelz.js
var require_channelz = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/channelz.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.registerChannelzSocket = exports2.registerChannelzServer = exports2.registerChannelzSubchannel = exports2.registerChannelzChannel = exports2.ChannelzCallTrackerStub = exports2.ChannelzCallTracker = exports2.ChannelzChildrenTrackerStub = exports2.ChannelzChildrenTracker = exports2.ChannelzTrace = exports2.ChannelzTraceStub = void 0;
    exports2.unregisterChannelzRef = unregisterChannelzRef;
    exports2.getChannelzHandlers = getChannelzHandlers;
    exports2.getChannelzServiceDefinition = getChannelzServiceDefinition;
    exports2.setup = setup;
    var net_1 = __require("net");
    var ordered_map_1 = require_cjs();
    var connectivity_state_1 = require_connectivity_state();
    var constants_1 = require_constants9();
    var subchannel_address_1 = require_subchannel_address();
    var admin_1 = require_admin();
    var make_client_1 = require_make_client();
    function channelRefToMessage(ref) {
      return {
        channel_id: ref.id,
        name: ref.name
      };
    }
    __name(channelRefToMessage, "channelRefToMessage");
    function subchannelRefToMessage(ref) {
      return {
        subchannel_id: ref.id,
        name: ref.name
      };
    }
    __name(subchannelRefToMessage, "subchannelRefToMessage");
    function serverRefToMessage(ref) {
      return {
        server_id: ref.id
      };
    }
    __name(serverRefToMessage, "serverRefToMessage");
    function socketRefToMessage(ref) {
      return {
        socket_id: ref.id,
        name: ref.name
      };
    }
    __name(socketRefToMessage, "socketRefToMessage");
    var TARGET_RETAINED_TRACES = 32;
    var DEFAULT_MAX_RESULTS = 100;
    var ChannelzTraceStub = class {
      static {
        __name(this, "ChannelzTraceStub");
      }
      constructor() {
        this.events = [];
        this.creationTimestamp = /* @__PURE__ */ new Date();
        this.eventsLogged = 0;
      }
      addTrace() {
      }
      getTraceMessage() {
        return {
          creation_timestamp: dateToProtoTimestamp(this.creationTimestamp),
          num_events_logged: this.eventsLogged,
          events: []
        };
      }
    };
    exports2.ChannelzTraceStub = ChannelzTraceStub;
    var ChannelzTrace = class {
      static {
        __name(this, "ChannelzTrace");
      }
      constructor() {
        this.events = [];
        this.eventsLogged = 0;
        this.creationTimestamp = /* @__PURE__ */ new Date();
      }
      addTrace(severity, description, child) {
        const timestamp = /* @__PURE__ */ new Date();
        this.events.push({
          description,
          severity,
          timestamp,
          childChannel: (child === null || child === void 0 ? void 0 : child.kind) === "channel" ? child : void 0,
          childSubchannel: (child === null || child === void 0 ? void 0 : child.kind) === "subchannel" ? child : void 0
        });
        if (this.events.length >= TARGET_RETAINED_TRACES * 2) {
          this.events = this.events.slice(TARGET_RETAINED_TRACES);
        }
        this.eventsLogged += 1;
      }
      getTraceMessage() {
        return {
          creation_timestamp: dateToProtoTimestamp(this.creationTimestamp),
          num_events_logged: this.eventsLogged,
          events: this.events.map((event) => {
            return {
              description: event.description,
              severity: event.severity,
              timestamp: dateToProtoTimestamp(event.timestamp),
              channel_ref: event.childChannel ? channelRefToMessage(event.childChannel) : null,
              subchannel_ref: event.childSubchannel ? subchannelRefToMessage(event.childSubchannel) : null
            };
          })
        };
      }
    };
    exports2.ChannelzTrace = ChannelzTrace;
    var ChannelzChildrenTracker = class {
      static {
        __name(this, "ChannelzChildrenTracker");
      }
      constructor() {
        this.channelChildren = new ordered_map_1.OrderedMap();
        this.subchannelChildren = new ordered_map_1.OrderedMap();
        this.socketChildren = new ordered_map_1.OrderedMap();
        this.trackerMap = {
          [
            "channel"
            /* EntityTypes.channel */
          ]: this.channelChildren,
          [
            "subchannel"
            /* EntityTypes.subchannel */
          ]: this.subchannelChildren,
          [
            "socket"
            /* EntityTypes.socket */
          ]: this.socketChildren
        };
      }
      refChild(child) {
        const tracker = this.trackerMap[child.kind];
        const trackedChild = tracker.find(child.id);
        if (trackedChild.equals(tracker.end())) {
          tracker.setElement(child.id, {
            ref: child,
            count: 1
          }, trackedChild);
        } else {
          trackedChild.pointer[1].count += 1;
        }
      }
      unrefChild(child) {
        const tracker = this.trackerMap[child.kind];
        const trackedChild = tracker.getElementByKey(child.id);
        if (trackedChild !== void 0) {
          trackedChild.count -= 1;
          if (trackedChild.count === 0) {
            tracker.eraseElementByKey(child.id);
          }
        }
      }
      getChildLists() {
        return {
          channels: this.channelChildren,
          subchannels: this.subchannelChildren,
          sockets: this.socketChildren
        };
      }
    };
    exports2.ChannelzChildrenTracker = ChannelzChildrenTracker;
    var ChannelzChildrenTrackerStub = class extends ChannelzChildrenTracker {
      static {
        __name(this, "ChannelzChildrenTrackerStub");
      }
      refChild() {
      }
      unrefChild() {
      }
    };
    exports2.ChannelzChildrenTrackerStub = ChannelzChildrenTrackerStub;
    var ChannelzCallTracker = class {
      static {
        __name(this, "ChannelzCallTracker");
      }
      constructor() {
        this.callsStarted = 0;
        this.callsSucceeded = 0;
        this.callsFailed = 0;
        this.lastCallStartedTimestamp = null;
      }
      addCallStarted() {
        this.callsStarted += 1;
        this.lastCallStartedTimestamp = /* @__PURE__ */ new Date();
      }
      addCallSucceeded() {
        this.callsSucceeded += 1;
      }
      addCallFailed() {
        this.callsFailed += 1;
      }
    };
    exports2.ChannelzCallTracker = ChannelzCallTracker;
    var ChannelzCallTrackerStub = class extends ChannelzCallTracker {
      static {
        __name(this, "ChannelzCallTrackerStub");
      }
      addCallStarted() {
      }
      addCallSucceeded() {
      }
      addCallFailed() {
      }
    };
    exports2.ChannelzCallTrackerStub = ChannelzCallTrackerStub;
    var entityMaps = {
      [
        "channel"
        /* EntityTypes.channel */
      ]: new ordered_map_1.OrderedMap(),
      [
        "subchannel"
        /* EntityTypes.subchannel */
      ]: new ordered_map_1.OrderedMap(),
      [
        "server"
        /* EntityTypes.server */
      ]: new ordered_map_1.OrderedMap(),
      [
        "socket"
        /* EntityTypes.socket */
      ]: new ordered_map_1.OrderedMap()
    };
    var generateRegisterFn = /* @__PURE__ */ __name((kind) => {
      let nextId = 1;
      function getNextId() {
        return nextId++;
      }
      __name(getNextId, "getNextId");
      const entityMap = entityMaps[kind];
      return (name3, getInfo, channelzEnabled) => {
        const id = getNextId();
        const ref = { id, name: name3, kind };
        if (channelzEnabled) {
          entityMap.setElement(id, { ref, getInfo });
        }
        return ref;
      };
    }, "generateRegisterFn");
    exports2.registerChannelzChannel = generateRegisterFn(
      "channel"
      /* EntityTypes.channel */
    );
    exports2.registerChannelzSubchannel = generateRegisterFn(
      "subchannel"
      /* EntityTypes.subchannel */
    );
    exports2.registerChannelzServer = generateRegisterFn(
      "server"
      /* EntityTypes.server */
    );
    exports2.registerChannelzSocket = generateRegisterFn(
      "socket"
      /* EntityTypes.socket */
    );
    function unregisterChannelzRef(ref) {
      entityMaps[ref.kind].eraseElementByKey(ref.id);
    }
    __name(unregisterChannelzRef, "unregisterChannelzRef");
    function parseIPv6Section(addressSection) {
      const numberValue = Number.parseInt(addressSection, 16);
      return [numberValue / 256 | 0, numberValue % 256];
    }
    __name(parseIPv6Section, "parseIPv6Section");
    function parseIPv6Chunk(addressChunk) {
      if (addressChunk === "") {
        return [];
      }
      const bytePairs = addressChunk.split(":").map((section) => parseIPv6Section(section));
      const result = [];
      return result.concat(...bytePairs);
    }
    __name(parseIPv6Chunk, "parseIPv6Chunk");
    function isIPv6MappedIPv4(ipAddress) {
      return (0, net_1.isIPv6)(ipAddress) && ipAddress.toLowerCase().startsWith("::ffff:") && (0, net_1.isIPv4)(ipAddress.substring(7));
    }
    __name(isIPv6MappedIPv4, "isIPv6MappedIPv4");
    function ipv4AddressStringToBuffer(ipAddress) {
      return Buffer.from(Uint8Array.from(ipAddress.split(".").map((segment) => Number.parseInt(segment))));
    }
    __name(ipv4AddressStringToBuffer, "ipv4AddressStringToBuffer");
    function ipAddressStringToBuffer(ipAddress) {
      if ((0, net_1.isIPv4)(ipAddress)) {
        return ipv4AddressStringToBuffer(ipAddress);
      } else if (isIPv6MappedIPv4(ipAddress)) {
        return ipv4AddressStringToBuffer(ipAddress.substring(7));
      } else if ((0, net_1.isIPv6)(ipAddress)) {
        let leftSection;
        let rightSection;
        const doubleColonIndex = ipAddress.indexOf("::");
        if (doubleColonIndex === -1) {
          leftSection = ipAddress;
          rightSection = "";
        } else {
          leftSection = ipAddress.substring(0, doubleColonIndex);
          rightSection = ipAddress.substring(doubleColonIndex + 2);
        }
        const leftBuffer = Buffer.from(parseIPv6Chunk(leftSection));
        const rightBuffer = Buffer.from(parseIPv6Chunk(rightSection));
        const middleBuffer = Buffer.alloc(16 - leftBuffer.length - rightBuffer.length, 0);
        return Buffer.concat([leftBuffer, middleBuffer, rightBuffer]);
      } else {
        return null;
      }
    }
    __name(ipAddressStringToBuffer, "ipAddressStringToBuffer");
    function connectivityStateToMessage(state) {
      switch (state) {
        case connectivity_state_1.ConnectivityState.CONNECTING:
          return {
            state: "CONNECTING"
          };
        case connectivity_state_1.ConnectivityState.IDLE:
          return {
            state: "IDLE"
          };
        case connectivity_state_1.ConnectivityState.READY:
          return {
            state: "READY"
          };
        case connectivity_state_1.ConnectivityState.SHUTDOWN:
          return {
            state: "SHUTDOWN"
          };
        case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE:
          return {
            state: "TRANSIENT_FAILURE"
          };
        default:
          return {
            state: "UNKNOWN"
          };
      }
    }
    __name(connectivityStateToMessage, "connectivityStateToMessage");
    function dateToProtoTimestamp(date) {
      if (!date) {
        return null;
      }
      const millisSinceEpoch = date.getTime();
      return {
        seconds: millisSinceEpoch / 1e3 | 0,
        nanos: millisSinceEpoch % 1e3 * 1e6
      };
    }
    __name(dateToProtoTimestamp, "dateToProtoTimestamp");
    function getChannelMessage(channelEntry) {
      const resolvedInfo = channelEntry.getInfo();
      const channelRef = [];
      const subchannelRef = [];
      resolvedInfo.children.channels.forEach((el) => {
        channelRef.push(channelRefToMessage(el[1].ref));
      });
      resolvedInfo.children.subchannels.forEach((el) => {
        subchannelRef.push(subchannelRefToMessage(el[1].ref));
      });
      return {
        ref: channelRefToMessage(channelEntry.ref),
        data: {
          target: resolvedInfo.target,
          state: connectivityStateToMessage(resolvedInfo.state),
          calls_started: resolvedInfo.callTracker.callsStarted,
          calls_succeeded: resolvedInfo.callTracker.callsSucceeded,
          calls_failed: resolvedInfo.callTracker.callsFailed,
          last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp),
          trace: resolvedInfo.trace.getTraceMessage()
        },
        channel_ref: channelRef,
        subchannel_ref: subchannelRef
      };
    }
    __name(getChannelMessage, "getChannelMessage");
    function GetChannel(call, callback) {
      const channelId = parseInt(call.request.channel_id, 10);
      const channelEntry = entityMaps[
        "channel"
        /* EntityTypes.channel */
      ].getElementByKey(channelId);
      if (channelEntry === void 0) {
        callback({
          code: constants_1.Status.NOT_FOUND,
          details: "No channel data found for id " + channelId
        });
        return;
      }
      callback(null, { channel: getChannelMessage(channelEntry) });
    }
    __name(GetChannel, "GetChannel");
    function GetTopChannels(call, callback) {
      const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS;
      const resultList = [];
      const startId = parseInt(call.request.start_channel_id, 10);
      const channelEntries = entityMaps[
        "channel"
        /* EntityTypes.channel */
      ];
      let i;
      for (i = channelEntries.lowerBound(startId); !i.equals(channelEntries.end()) && resultList.length < maxResults; i = i.next()) {
        resultList.push(getChannelMessage(i.pointer[1]));
      }
      callback(null, {
        channel: resultList,
        end: i.equals(channelEntries.end())
      });
    }
    __name(GetTopChannels, "GetTopChannels");
    function getServerMessage(serverEntry) {
      const resolvedInfo = serverEntry.getInfo();
      const listenSocket = [];
      resolvedInfo.listenerChildren.sockets.forEach((el) => {
        listenSocket.push(socketRefToMessage(el[1].ref));
      });
      return {
        ref: serverRefToMessage(serverEntry.ref),
        data: {
          calls_started: resolvedInfo.callTracker.callsStarted,
          calls_succeeded: resolvedInfo.callTracker.callsSucceeded,
          calls_failed: resolvedInfo.callTracker.callsFailed,
          last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp),
          trace: resolvedInfo.trace.getTraceMessage()
        },
        listen_socket: listenSocket
      };
    }
    __name(getServerMessage, "getServerMessage");
    function GetServer(call, callback) {
      const serverId = parseInt(call.request.server_id, 10);
      const serverEntries = entityMaps[
        "server"
        /* EntityTypes.server */
      ];
      const serverEntry = serverEntries.getElementByKey(serverId);
      if (serverEntry === void 0) {
        callback({
          code: constants_1.Status.NOT_FOUND,
          details: "No server data found for id " + serverId
        });
        return;
      }
      callback(null, { server: getServerMessage(serverEntry) });
    }
    __name(GetServer, "GetServer");
    function GetServers(call, callback) {
      const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS;
      const startId = parseInt(call.request.start_server_id, 10);
      const serverEntries = entityMaps[
        "server"
        /* EntityTypes.server */
      ];
      const resultList = [];
      let i;
      for (i = serverEntries.lowerBound(startId); !i.equals(serverEntries.end()) && resultList.length < maxResults; i = i.next()) {
        resultList.push(getServerMessage(i.pointer[1]));
      }
      callback(null, {
        server: resultList,
        end: i.equals(serverEntries.end())
      });
    }
    __name(GetServers, "GetServers");
    function GetSubchannel(call, callback) {
      const subchannelId = parseInt(call.request.subchannel_id, 10);
      const subchannelEntry = entityMaps[
        "subchannel"
        /* EntityTypes.subchannel */
      ].getElementByKey(subchannelId);
      if (subchannelEntry === void 0) {
        callback({
          code: constants_1.Status.NOT_FOUND,
          details: "No subchannel data found for id " + subchannelId
        });
        return;
      }
      const resolvedInfo = subchannelEntry.getInfo();
      const listenSocket = [];
      resolvedInfo.children.sockets.forEach((el) => {
        listenSocket.push(socketRefToMessage(el[1].ref));
      });
      const subchannelMessage = {
        ref: subchannelRefToMessage(subchannelEntry.ref),
        data: {
          target: resolvedInfo.target,
          state: connectivityStateToMessage(resolvedInfo.state),
          calls_started: resolvedInfo.callTracker.callsStarted,
          calls_succeeded: resolvedInfo.callTracker.callsSucceeded,
          calls_failed: resolvedInfo.callTracker.callsFailed,
          last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp),
          trace: resolvedInfo.trace.getTraceMessage()
        },
        socket_ref: listenSocket
      };
      callback(null, { subchannel: subchannelMessage });
    }
    __name(GetSubchannel, "GetSubchannel");
    function subchannelAddressToAddressMessage(subchannelAddress) {
      var _a6;
      if ((0, subchannel_address_1.isTcpSubchannelAddress)(subchannelAddress)) {
        return {
          address: "tcpip_address",
          tcpip_address: {
            ip_address: (_a6 = ipAddressStringToBuffer(subchannelAddress.host)) !== null && _a6 !== void 0 ? _a6 : void 0,
            port: subchannelAddress.port
          }
        };
      } else {
        return {
          address: "uds_address",
          uds_address: {
            filename: subchannelAddress.path
          }
        };
      }
    }
    __name(subchannelAddressToAddressMessage, "subchannelAddressToAddressMessage");
    function GetSocket(call, callback) {
      var _a6, _b2, _c2, _d, _e;
      const socketId = parseInt(call.request.socket_id, 10);
      const socketEntry = entityMaps[
        "socket"
        /* EntityTypes.socket */
      ].getElementByKey(socketId);
      if (socketEntry === void 0) {
        callback({
          code: constants_1.Status.NOT_FOUND,
          details: "No socket data found for id " + socketId
        });
        return;
      }
      const resolvedInfo = socketEntry.getInfo();
      const securityMessage = resolvedInfo.security ? {
        model: "tls",
        tls: {
          cipher_suite: resolvedInfo.security.cipherSuiteStandardName ? "standard_name" : "other_name",
          standard_name: (_a6 = resolvedInfo.security.cipherSuiteStandardName) !== null && _a6 !== void 0 ? _a6 : void 0,
          other_name: (_b2 = resolvedInfo.security.cipherSuiteOtherName) !== null && _b2 !== void 0 ? _b2 : void 0,
          local_certificate: (_c2 = resolvedInfo.security.localCertificate) !== null && _c2 !== void 0 ? _c2 : void 0,
          remote_certificate: (_d = resolvedInfo.security.remoteCertificate) !== null && _d !== void 0 ? _d : void 0
        }
      } : null;
      const socketMessage = {
        ref: socketRefToMessage(socketEntry.ref),
        local: resolvedInfo.localAddress ? subchannelAddressToAddressMessage(resolvedInfo.localAddress) : null,
        remote: resolvedInfo.remoteAddress ? subchannelAddressToAddressMessage(resolvedInfo.remoteAddress) : null,
        remote_name: (_e = resolvedInfo.remoteName) !== null && _e !== void 0 ? _e : void 0,
        security: securityMessage,
        data: {
          keep_alives_sent: resolvedInfo.keepAlivesSent,
          streams_started: resolvedInfo.streamsStarted,
          streams_succeeded: resolvedInfo.streamsSucceeded,
          streams_failed: resolvedInfo.streamsFailed,
          last_local_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastLocalStreamCreatedTimestamp),
          last_remote_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastRemoteStreamCreatedTimestamp),
          messages_received: resolvedInfo.messagesReceived,
          messages_sent: resolvedInfo.messagesSent,
          last_message_received_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageReceivedTimestamp),
          last_message_sent_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageSentTimestamp),
          local_flow_control_window: resolvedInfo.localFlowControlWindow ? { value: resolvedInfo.localFlowControlWindow } : null,
          remote_flow_control_window: resolvedInfo.remoteFlowControlWindow ? { value: resolvedInfo.remoteFlowControlWindow } : null
        }
      };
      callback(null, { socket: socketMessage });
    }
    __name(GetSocket, "GetSocket");
    function GetServerSockets(call, callback) {
      const serverId = parseInt(call.request.server_id, 10);
      const serverEntry = entityMaps[
        "server"
        /* EntityTypes.server */
      ].getElementByKey(serverId);
      if (serverEntry === void 0) {
        callback({
          code: constants_1.Status.NOT_FOUND,
          details: "No server data found for id " + serverId
        });
        return;
      }
      const startId = parseInt(call.request.start_socket_id, 10);
      const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS;
      const resolvedInfo = serverEntry.getInfo();
      const allSockets = resolvedInfo.sessionChildren.sockets;
      const resultList = [];
      let i;
      for (i = allSockets.lowerBound(startId); !i.equals(allSockets.end()) && resultList.length < maxResults; i = i.next()) {
        resultList.push(socketRefToMessage(i.pointer[1].ref));
      }
      callback(null, {
        socket_ref: resultList,
        end: i.equals(allSockets.end())
      });
    }
    __name(GetServerSockets, "GetServerSockets");
    function getChannelzHandlers() {
      return {
        GetChannel,
        GetTopChannels,
        GetServer,
        GetServers,
        GetSubchannel,
        GetSocket,
        GetServerSockets
      };
    }
    __name(getChannelzHandlers, "getChannelzHandlers");
    var loadedChannelzDefinition = null;
    function getChannelzServiceDefinition() {
      if (loadedChannelzDefinition) {
        return loadedChannelzDefinition;
      }
      const loaderLoadSync = require_src10().loadSync;
      const loadedProto = loaderLoadSync("channelz.proto", {
        keepCase: true,
        longs: String,
        enums: String,
        defaults: true,
        oneofs: true,
        includeDirs: [`${__dirname}/../../proto`]
      });
      const channelzGrpcObject = (0, make_client_1.loadPackageDefinition)(loadedProto);
      loadedChannelzDefinition = channelzGrpcObject.grpc.channelz.v1.Channelz.service;
      return loadedChannelzDefinition;
    }
    __name(getChannelzServiceDefinition, "getChannelzServiceDefinition");
    function setup() {
      (0, admin_1.registerAdminService)(getChannelzServiceDefinition, getChannelzHandlers);
    }
    __name(setup, "setup");
  }
});

// node_modules/@grpc/grpc-js/build/src/subchannel.js
var require_subchannel = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/subchannel.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Subchannel = void 0;
    var connectivity_state_1 = require_connectivity_state();
    var backoff_timeout_1 = require_backoff_timeout();
    var logging = require_logging();
    var constants_1 = require_constants9();
    var uri_parser_1 = require_uri_parser();
    var subchannel_address_1 = require_subchannel_address();
    var channelz_1 = require_channelz();
    var TRACER_NAME = "subchannel";
    var KEEPALIVE_MAX_TIME_MS = ~(1 << 31);
    var Subchannel = class {
      static {
        __name(this, "Subchannel");
      }
      /**
       * A class representing a connection to a single backend.
       * @param channelTarget The target string for the channel as a whole
       * @param subchannelAddress The address for the backend that this subchannel
       *     will connect to
       * @param options The channel options, plus any specific subchannel options
       *     for this subchannel
       * @param credentials The channel credentials used to establish this
       *     connection
       */
      constructor(channelTarget, subchannelAddress, options2, credentials, connector) {
        var _a6;
        this.channelTarget = channelTarget;
        this.subchannelAddress = subchannelAddress;
        this.options = options2;
        this.connector = connector;
        this.connectivityState = connectivity_state_1.ConnectivityState.IDLE;
        this.transport = null;
        this.continueConnecting = false;
        this.stateListeners = /* @__PURE__ */ new Set();
        this.refcount = 0;
        this.channelzEnabled = true;
        const backoffOptions = {
          initialDelay: options2["grpc.initial_reconnect_backoff_ms"],
          maxDelay: options2["grpc.max_reconnect_backoff_ms"]
        };
        this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => {
          this.handleBackoffTimer();
        }, backoffOptions);
        this.backoffTimeout.unref();
        this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress);
        this.keepaliveTime = (_a6 = options2["grpc.keepalive_time_ms"]) !== null && _a6 !== void 0 ? _a6 : -1;
        if (options2["grpc.enable_channelz"] === 0) {
          this.channelzEnabled = false;
          this.channelzTrace = new channelz_1.ChannelzTraceStub();
          this.callTracker = new channelz_1.ChannelzCallTrackerStub();
          this.childrenTracker = new channelz_1.ChannelzChildrenTrackerStub();
          this.streamTracker = new channelz_1.ChannelzCallTrackerStub();
        } else {
          this.channelzTrace = new channelz_1.ChannelzTrace();
          this.callTracker = new channelz_1.ChannelzCallTracker();
          this.childrenTracker = new channelz_1.ChannelzChildrenTracker();
          this.streamTracker = new channelz_1.ChannelzCallTracker();
        }
        this.channelzRef = (0, channelz_1.registerChannelzSubchannel)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled);
        this.channelzTrace.addTrace("CT_INFO", "Subchannel created");
        this.trace("Subchannel constructed with options " + JSON.stringify(options2, void 0, 2));
        this.secureConnector = credentials._createSecureConnector(channelTarget, options2);
      }
      getChannelzInfo() {
        return {
          state: this.connectivityState,
          trace: this.channelzTrace,
          callTracker: this.callTracker,
          children: this.childrenTracker.getChildLists(),
          target: this.subchannelAddressString
        };
      }
      trace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text);
      }
      refTrace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, "subchannel_refcount", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text);
      }
      handleBackoffTimer() {
        if (this.continueConnecting) {
          this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING);
        } else {
          this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.IDLE);
        }
      }
      /**
       * Start a backoff timer with the current nextBackoff timeout
       */
      startBackoff() {
        this.backoffTimeout.runOnce();
      }
      stopBackoff() {
        this.backoffTimeout.stop();
        this.backoffTimeout.reset();
      }
      startConnectingInternal() {
        let options2 = this.options;
        if (options2["grpc.keepalive_time_ms"]) {
          const adjustedKeepaliveTime = Math.min(this.keepaliveTime, KEEPALIVE_MAX_TIME_MS);
          options2 = Object.assign(Object.assign({}, options2), { "grpc.keepalive_time_ms": adjustedKeepaliveTime });
        }
        this.connector.connect(this.subchannelAddress, this.secureConnector, options2).then((transport) => {
          if (this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.READY)) {
            this.transport = transport;
            if (this.channelzEnabled) {
              this.childrenTracker.refChild(transport.getChannelzRef());
            }
            transport.addDisconnectListener((tooManyPings) => {
              this.transitionToState([connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE);
              if (tooManyPings && this.keepaliveTime > 0) {
                this.keepaliveTime *= 2;
                logging.log(constants_1.LogVerbosity.ERROR, `Connection to ${(0, uri_parser_1.uriToString)(this.channelTarget)} at ${this.subchannelAddressString} rejected by server because of excess pings. Increasing ping interval to ${this.keepaliveTime} ms`);
              }
            });
          } else {
            transport.shutdown();
          }
        }, (error) => {
          this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, `${error}`);
        });
      }
      /**
       * Initiate a state transition from any element of oldStates to the new
       * state. If the current connectivityState is not in oldStates, do nothing.
       * @param oldStates The set of states to transition from
       * @param newState The state to transition to
       * @returns True if the state changed, false otherwise
       */
      transitionToState(oldStates, newState, errorMessage) {
        var _a6, _b2;
        if (oldStates.indexOf(this.connectivityState) === -1) {
          return false;
        }
        if (errorMessage) {
          this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState] + ' with error "' + errorMessage + '"');
        } else {
          this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState]);
        }
        if (this.channelzEnabled) {
          this.channelzTrace.addTrace("CT_INFO", "Connectivity state change to " + connectivity_state_1.ConnectivityState[newState]);
        }
        const previousState = this.connectivityState;
        this.connectivityState = newState;
        switch (newState) {
          case connectivity_state_1.ConnectivityState.READY:
            this.stopBackoff();
            break;
          case connectivity_state_1.ConnectivityState.CONNECTING:
            this.startBackoff();
            this.startConnectingInternal();
            this.continueConnecting = false;
            break;
          case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE:
            if (this.channelzEnabled && this.transport) {
              this.childrenTracker.unrefChild(this.transport.getChannelzRef());
            }
            (_a6 = this.transport) === null || _a6 === void 0 ? void 0 : _a6.shutdown();
            this.transport = null;
            if (!this.backoffTimeout.isRunning()) {
              process.nextTick(() => {
                this.handleBackoffTimer();
              });
            }
            break;
          case connectivity_state_1.ConnectivityState.IDLE:
            if (this.channelzEnabled && this.transport) {
              this.childrenTracker.unrefChild(this.transport.getChannelzRef());
            }
            (_b2 = this.transport) === null || _b2 === void 0 ? void 0 : _b2.shutdown();
            this.transport = null;
            break;
          default:
            throw new Error(`Invalid state: unknown ConnectivityState ${newState}`);
        }
        for (const listener of this.stateListeners) {
          listener(this, previousState, newState, this.keepaliveTime, errorMessage);
        }
        return true;
      }
      ref() {
        this.refTrace("refcount " + this.refcount + " -> " + (this.refcount + 1));
        this.refcount += 1;
      }
      unref() {
        this.refTrace("refcount " + this.refcount + " -> " + (this.refcount - 1));
        this.refcount -= 1;
        if (this.refcount === 0) {
          this.channelzTrace.addTrace("CT_INFO", "Shutting down");
          (0, channelz_1.unregisterChannelzRef)(this.channelzRef);
          this.secureConnector.destroy();
          process.nextTick(() => {
            this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING, connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE);
          });
        }
      }
      unrefIfOneRef() {
        if (this.refcount === 1) {
          this.unref();
          return true;
        }
        return false;
      }
      createCall(metadata, host, method, listener) {
        if (!this.transport) {
          throw new Error("Cannot create call, subchannel not READY");
        }
        let statsTracker;
        if (this.channelzEnabled) {
          this.callTracker.addCallStarted();
          this.streamTracker.addCallStarted();
          statsTracker = {
            onCallEnd: /* @__PURE__ */ __name((status) => {
              if (status.code === constants_1.Status.OK) {
                this.callTracker.addCallSucceeded();
              } else {
                this.callTracker.addCallFailed();
              }
            }, "onCallEnd")
          };
        } else {
          statsTracker = {};
        }
        return this.transport.createCall(metadata, host, method, listener, statsTracker);
      }
      /**
       * If the subchannel is currently IDLE, start connecting and switch to the
       * CONNECTING state. If the subchannel is current in TRANSIENT_FAILURE,
       * the next time it would transition to IDLE, start connecting again instead.
       * Otherwise, do nothing.
       */
      startConnecting() {
        process.nextTick(() => {
          if (!this.transitionToState([connectivity_state_1.ConnectivityState.IDLE], connectivity_state_1.ConnectivityState.CONNECTING)) {
            if (this.connectivityState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) {
              this.continueConnecting = true;
            }
          }
        });
      }
      /**
       * Get the subchannel's current connectivity state.
       */
      getConnectivityState() {
        return this.connectivityState;
      }
      /**
       * Add a listener function to be called whenever the subchannel's
       * connectivity state changes.
       * @param listener
       */
      addConnectivityStateListener(listener) {
        this.stateListeners.add(listener);
      }
      /**
       * Remove a listener previously added with `addConnectivityStateListener`
       * @param listener A reference to a function previously passed to
       *     `addConnectivityStateListener`
       */
      removeConnectivityStateListener(listener) {
        this.stateListeners.delete(listener);
      }
      /**
       * Reset the backoff timeout, and immediately start connecting if in backoff.
       */
      resetBackoff() {
        process.nextTick(() => {
          this.backoffTimeout.reset();
          this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING);
        });
      }
      getAddress() {
        return this.subchannelAddressString;
      }
      getChannelzRef() {
        return this.channelzRef;
      }
      isHealthy() {
        return true;
      }
      addHealthStateWatcher(listener) {
      }
      removeHealthStateWatcher(listener) {
      }
      getRealSubchannel() {
        return this;
      }
      realSubchannelEquals(other2) {
        return other2.getRealSubchannel() === this;
      }
      throttleKeepalive(newKeepaliveTime) {
        if (newKeepaliveTime > this.keepaliveTime) {
          this.keepaliveTime = newKeepaliveTime;
        }
      }
      getCallCredentials() {
        return this.secureConnector.getCallCredentials();
      }
    };
    exports2.Subchannel = Subchannel;
  }
});

// node_modules/@grpc/grpc-js/build/src/environment.js
var require_environment2 = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/environment.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var _a6;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = void 0;
    exports2.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = ((_a6 = process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) !== null && _a6 !== void 0 ? _a6 : "false") === "true";
  }
});

// node_modules/@grpc/grpc-js/build/src/resolver-dns.js
var require_resolver_dns = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/resolver-dns.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DEFAULT_PORT = void 0;
    exports2.setup = setup;
    var resolver_1 = require_resolver();
    var dns_1 = __require("dns");
    var service_config_1 = require_service_config();
    var constants_1 = require_constants9();
    var metadata_1 = require_metadata3();
    var logging = require_logging();
    var constants_2 = require_constants9();
    var uri_parser_1 = require_uri_parser();
    var net_1 = __require("net");
    var backoff_timeout_1 = require_backoff_timeout();
    var environment_1 = require_environment2();
    var TRACER_NAME = "dns_resolver";
    function trace2(text) {
      logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    exports2.DEFAULT_PORT = 443;
    var DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS = 3e4;
    var DnsResolver = class {
      static {
        __name(this, "DnsResolver");
      }
      constructor(target, listener, channelOptions) {
        var _a6, _b2, _c2;
        this.target = target;
        this.listener = listener;
        this.pendingLookupPromise = null;
        this.pendingTxtPromise = null;
        this.latestLookupResult = null;
        this.latestServiceConfig = null;
        this.latestServiceConfigError = null;
        this.continueResolving = false;
        this.isNextResolutionTimerRunning = false;
        this.isServiceConfigEnabled = true;
        this.returnedIpResult = false;
        this.alternativeResolver = new dns_1.promises.Resolver();
        trace2("Resolver constructed for target " + (0, uri_parser_1.uriToString)(target));
        if (target.authority) {
          this.alternativeResolver.setServers([target.authority]);
        }
        const hostPort = (0, uri_parser_1.splitHostPort)(target.path);
        if (hostPort === null) {
          this.ipResult = null;
          this.dnsHostname = null;
          this.port = null;
        } else {
          if ((0, net_1.isIPv4)(hostPort.host) || (0, net_1.isIPv6)(hostPort.host)) {
            this.ipResult = [
              {
                addresses: [
                  {
                    host: hostPort.host,
                    port: (_a6 = hostPort.port) !== null && _a6 !== void 0 ? _a6 : exports2.DEFAULT_PORT
                  }
                ]
              }
            ];
            this.dnsHostname = null;
            this.port = null;
          } else {
            this.ipResult = null;
            this.dnsHostname = hostPort.host;
            this.port = (_b2 = hostPort.port) !== null && _b2 !== void 0 ? _b2 : exports2.DEFAULT_PORT;
          }
        }
        this.percentage = Math.random() * 100;
        if (channelOptions["grpc.service_config_disable_resolution"] === 1) {
          this.isServiceConfigEnabled = false;
        }
        this.defaultResolutionError = {
          code: constants_1.Status.UNAVAILABLE,
          details: `Name resolution failed for target ${(0, uri_parser_1.uriToString)(this.target)}`,
          metadata: new metadata_1.Metadata()
        };
        const backoffOptions = {
          initialDelay: channelOptions["grpc.initial_reconnect_backoff_ms"],
          maxDelay: channelOptions["grpc.max_reconnect_backoff_ms"]
        };
        this.backoff = new backoff_timeout_1.BackoffTimeout(() => {
          if (this.continueResolving) {
            this.startResolutionWithBackoff();
          }
        }, backoffOptions);
        this.backoff.unref();
        this.minTimeBetweenResolutionsMs = (_c2 = channelOptions["grpc.dns_min_time_between_resolutions_ms"]) !== null && _c2 !== void 0 ? _c2 : DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS;
        this.nextResolutionTimer = setTimeout(() => {
        }, 0);
        clearTimeout(this.nextResolutionTimer);
      }
      /**
       * If the target is an IP address, just provide that address as a result.
       * Otherwise, initiate A, AAAA, and TXT lookups
       */
      startResolution() {
        if (this.ipResult !== null) {
          if (!this.returnedIpResult) {
            trace2("Returning IP address for target " + (0, uri_parser_1.uriToString)(this.target));
            setImmediate(() => {
              this.listener.onSuccessfulResolution(this.ipResult, null, null, null, {});
            });
            this.returnedIpResult = true;
          }
          this.backoff.stop();
          this.backoff.reset();
          this.stopNextResolutionTimer();
          return;
        }
        if (this.dnsHostname === null) {
          trace2("Failed to parse DNS address " + (0, uri_parser_1.uriToString)(this.target));
          setImmediate(() => {
            this.listener.onError({
              code: constants_1.Status.UNAVAILABLE,
              details: `Failed to parse DNS address ${(0, uri_parser_1.uriToString)(this.target)}`,
              metadata: new metadata_1.Metadata()
            });
          });
          this.stopNextResolutionTimer();
        } else {
          if (this.pendingLookupPromise !== null) {
            return;
          }
          trace2("Looking up DNS hostname " + this.dnsHostname);
          this.latestLookupResult = null;
          const hostname3 = this.dnsHostname;
          this.pendingLookupPromise = this.lookup(hostname3);
          this.pendingLookupPromise.then((addressList) => {
            if (this.pendingLookupPromise === null) {
              return;
            }
            this.pendingLookupPromise = null;
            this.backoff.reset();
            this.backoff.stop();
            this.latestLookupResult = addressList.map((address) => ({
              addresses: [address]
            }));
            const allAddressesString = "[" + addressList.map((addr) => addr.host + ":" + addr.port).join(",") + "]";
            trace2("Resolved addresses for target " + (0, uri_parser_1.uriToString)(this.target) + ": " + allAddressesString);
            if (this.latestLookupResult.length === 0) {
              this.listener.onError(this.defaultResolutionError);
              return;
            }
            this.listener.onSuccessfulResolution(this.latestLookupResult, this.latestServiceConfig, this.latestServiceConfigError, null, {});
          }, (err) => {
            if (this.pendingLookupPromise === null) {
              return;
            }
            trace2("Resolution error for target " + (0, uri_parser_1.uriToString)(this.target) + ": " + err.message);
            this.pendingLookupPromise = null;
            this.stopNextResolutionTimer();
            this.listener.onError(this.defaultResolutionError);
          });
          if (this.isServiceConfigEnabled && this.pendingTxtPromise === null) {
            this.pendingTxtPromise = this.resolveTxt(hostname3);
            this.pendingTxtPromise.then((txtRecord) => {
              if (this.pendingTxtPromise === null) {
                return;
              }
              this.pendingTxtPromise = null;
              try {
                this.latestServiceConfig = (0, service_config_1.extractAndSelectServiceConfig)(txtRecord, this.percentage);
              } catch (err) {
                this.latestServiceConfigError = {
                  code: constants_1.Status.UNAVAILABLE,
                  details: `Parsing service config failed with error ${err.message}`,
                  metadata: new metadata_1.Metadata()
                };
              }
              if (this.latestLookupResult !== null) {
                this.listener.onSuccessfulResolution(this.latestLookupResult, this.latestServiceConfig, this.latestServiceConfigError, null, {});
              }
            }, (err) => {
            });
          }
        }
      }
      async lookup(hostname3) {
        if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) {
          trace2("Using alternative DNS resolver.");
          const records = await Promise.allSettled([
            this.alternativeResolver.resolve4(hostname3),
            this.alternativeResolver.resolve6(hostname3)
          ]);
          if (records.every((result) => result.status === "rejected")) {
            throw new Error(records[0].reason);
          }
          return records.reduce((acc, result) => {
            return result.status === "fulfilled" ? [...acc, ...result.value] : acc;
          }, []).map((addr) => ({
            host: addr,
            port: +this.port
          }));
        }
        const addressList = await dns_1.promises.lookup(hostname3, { all: true });
        return addressList.map((addr) => ({ host: addr.address, port: +this.port }));
      }
      async resolveTxt(hostname3) {
        if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) {
          trace2("Using alternative DNS resolver.");
          return this.alternativeResolver.resolveTxt(hostname3);
        }
        return dns_1.promises.resolveTxt(hostname3);
      }
      startNextResolutionTimer() {
        var _a6, _b2;
        clearTimeout(this.nextResolutionTimer);
        this.nextResolutionTimer = setTimeout(() => {
          this.stopNextResolutionTimer();
          if (this.continueResolving) {
            this.startResolutionWithBackoff();
          }
        }, this.minTimeBetweenResolutionsMs);
        (_b2 = (_a6 = this.nextResolutionTimer).unref) === null || _b2 === void 0 ? void 0 : _b2.call(_a6);
        this.isNextResolutionTimerRunning = true;
      }
      stopNextResolutionTimer() {
        clearTimeout(this.nextResolutionTimer);
        this.isNextResolutionTimerRunning = false;
      }
      startResolutionWithBackoff() {
        if (this.pendingLookupPromise === null) {
          this.continueResolving = false;
          this.backoff.runOnce();
          this.startNextResolutionTimer();
          this.startResolution();
        }
      }
      updateResolution() {
        if (this.pendingLookupPromise === null) {
          if (this.isNextResolutionTimerRunning || this.backoff.isRunning()) {
            if (this.isNextResolutionTimerRunning) {
              trace2('resolution update delayed by "min time between resolutions" rate limit');
            } else {
              trace2("resolution update delayed by backoff timer until " + this.backoff.getEndTime().toISOString());
            }
            this.continueResolving = true;
          } else {
            this.startResolutionWithBackoff();
          }
        }
      }
      /**
       * Reset the resolver to the same state it had when it was created. In-flight
       * DNS requests cannot be cancelled, but they are discarded and their results
       * will be ignored.
       */
      destroy() {
        this.continueResolving = false;
        this.backoff.reset();
        this.backoff.stop();
        this.stopNextResolutionTimer();
        this.pendingLookupPromise = null;
        this.pendingTxtPromise = null;
        this.latestLookupResult = null;
        this.latestServiceConfig = null;
        this.latestServiceConfigError = null;
        this.returnedIpResult = false;
      }
      /**
       * Get the default authority for the given target. For IP targets, that is
       * the IP address. For DNS targets, it is the hostname.
       * @param target
       */
      static getDefaultAuthority(target) {
        return target.path;
      }
    };
    function setup() {
      (0, resolver_1.registerResolver)("dns", DnsResolver);
      (0, resolver_1.registerDefaultScheme)("dns");
    }
    __name(setup, "setup");
  }
});

// node_modules/@grpc/grpc-js/build/src/http_proxy.js
var require_http_proxy = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/http_proxy.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.parseCIDR = parseCIDR;
    exports2.mapProxyName = mapProxyName;
    exports2.getProxiedConnection = getProxiedConnection;
    var logging_1 = require_logging();
    var constants_1 = require_constants9();
    var net_1 = __require("net");
    var http4 = __require("http");
    var logging = require_logging();
    var subchannel_address_1 = require_subchannel_address();
    var uri_parser_1 = require_uri_parser();
    var url_1 = __require("url");
    var resolver_dns_1 = require_resolver_dns();
    var TRACER_NAME = "proxy";
    function trace2(text) {
      logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    function getProxyInfo() {
      let proxyEnv = "";
      let envVar = "";
      if (process.env.grpc_proxy) {
        envVar = "grpc_proxy";
        proxyEnv = process.env.grpc_proxy;
      } else if (process.env.https_proxy) {
        envVar = "https_proxy";
        proxyEnv = process.env.https_proxy;
      } else if (process.env.http_proxy) {
        envVar = "http_proxy";
        proxyEnv = process.env.http_proxy;
      } else {
        return {};
      }
      let proxyUrl;
      try {
        proxyUrl = new url_1.URL(proxyEnv);
      } catch (e2) {
        (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `cannot parse value of "${envVar}" env var`);
        return {};
      }
      if (proxyUrl.protocol !== "http:") {
        (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `"${proxyUrl.protocol}" scheme not supported in proxy URI`);
        return {};
      }
      let userCred = null;
      if (proxyUrl.username) {
        if (proxyUrl.password) {
          (0, logging_1.log)(constants_1.LogVerbosity.INFO, "userinfo found in proxy URI");
          userCred = decodeURIComponent(`${proxyUrl.username}:${proxyUrl.password}`);
        } else {
          userCred = proxyUrl.username;
        }
      }
      const hostname3 = proxyUrl.hostname;
      let port = proxyUrl.port;
      if (port === "") {
        port = "80";
      }
      const result = {
        address: `${hostname3}:${port}`
      };
      if (userCred) {
        result.creds = userCred;
      }
      trace2("Proxy server " + result.address + " set by environment variable " + envVar);
      return result;
    }
    __name(getProxyInfo, "getProxyInfo");
    function getNoProxyHostList() {
      let noProxyStr = process.env.no_grpc_proxy;
      let envVar = "no_grpc_proxy";
      if (!noProxyStr) {
        noProxyStr = process.env.no_proxy;
        envVar = "no_proxy";
      }
      if (noProxyStr) {
        trace2("No proxy server list set by environment variable " + envVar);
        return noProxyStr.split(",");
      } else {
        return [];
      }
    }
    __name(getNoProxyHostList, "getNoProxyHostList");
    function parseCIDR(cidrString) {
      const splitRange = cidrString.split("/");
      if (splitRange.length !== 2) {
        return null;
      }
      const prefixLength = parseInt(splitRange[1], 10);
      if (!(0, net_1.isIPv4)(splitRange[0]) || Number.isNaN(prefixLength) || prefixLength < 0 || prefixLength > 32) {
        return null;
      }
      return {
        ip: ipToInt(splitRange[0]),
        prefixLength
      };
    }
    __name(parseCIDR, "parseCIDR");
    function ipToInt(ip) {
      return ip.split(".").reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0);
    }
    __name(ipToInt, "ipToInt");
    function isIpInCIDR(cidr, serverHost) {
      const ip = cidr.ip;
      const mask = -1 << 32 - cidr.prefixLength;
      const hostIP = ipToInt(serverHost);
      return (hostIP & mask) === (ip & mask);
    }
    __name(isIpInCIDR, "isIpInCIDR");
    function hostMatchesNoProxyList(serverHost) {
      for (const host of getNoProxyHostList()) {
        const parsedCIDR = parseCIDR(host);
        if ((0, net_1.isIPv4)(serverHost) && parsedCIDR && isIpInCIDR(parsedCIDR, serverHost)) {
          return true;
        } else if (serverHost.endsWith(host)) {
          return true;
        }
      }
      return false;
    }
    __name(hostMatchesNoProxyList, "hostMatchesNoProxyList");
    function mapProxyName(target, options2) {
      var _a6;
      const noProxyResult = {
        target,
        extraOptions: {}
      };
      if (((_a6 = options2["grpc.enable_http_proxy"]) !== null && _a6 !== void 0 ? _a6 : 1) === 0) {
        return noProxyResult;
      }
      if (target.scheme === "unix") {
        return noProxyResult;
      }
      const proxyInfo = getProxyInfo();
      if (!proxyInfo.address) {
        return noProxyResult;
      }
      const hostPort = (0, uri_parser_1.splitHostPort)(target.path);
      if (!hostPort) {
        return noProxyResult;
      }
      const serverHost = hostPort.host;
      if (hostMatchesNoProxyList(serverHost)) {
        trace2("Not using proxy for target in no_proxy list: " + (0, uri_parser_1.uriToString)(target));
        return noProxyResult;
      }
      const extraOptions = {
        "grpc.http_connect_target": (0, uri_parser_1.uriToString)(target)
      };
      if (proxyInfo.creds) {
        extraOptions["grpc.http_connect_creds"] = proxyInfo.creds;
      }
      return {
        target: {
          scheme: "dns",
          path: proxyInfo.address
        },
        extraOptions
      };
    }
    __name(mapProxyName, "mapProxyName");
    function getProxiedConnection(address, channelOptions) {
      var _a6;
      if (!("grpc.http_connect_target" in channelOptions)) {
        return Promise.resolve(null);
      }
      const realTarget = channelOptions["grpc.http_connect_target"];
      const parsedTarget = (0, uri_parser_1.parseUri)(realTarget);
      if (parsedTarget === null) {
        return Promise.resolve(null);
      }
      const splitHostPost = (0, uri_parser_1.splitHostPort)(parsedTarget.path);
      if (splitHostPost === null) {
        return Promise.resolve(null);
      }
      const hostPort = `${splitHostPost.host}:${(_a6 = splitHostPost.port) !== null && _a6 !== void 0 ? _a6 : resolver_dns_1.DEFAULT_PORT}`;
      const options2 = {
        method: "CONNECT",
        path: hostPort
      };
      const headers = {
        Host: hostPort
      };
      if ((0, subchannel_address_1.isTcpSubchannelAddress)(address)) {
        options2.host = address.host;
        options2.port = address.port;
      } else {
        options2.socketPath = address.path;
      }
      if ("grpc.http_connect_creds" in channelOptions) {
        headers["Proxy-Authorization"] = "Basic " + Buffer.from(channelOptions["grpc.http_connect_creds"]).toString("base64");
      }
      options2.headers = headers;
      const proxyAddressString = (0, subchannel_address_1.subchannelAddressToString)(address);
      trace2("Using proxy " + proxyAddressString + " to connect to " + options2.path);
      return new Promise((resolve24, reject) => {
        const request4 = http4.request(options2);
        request4.once("connect", (res, socket, head) => {
          request4.removeAllListeners();
          socket.removeAllListeners();
          if (res.statusCode === 200) {
            trace2("Successfully connected to " + options2.path + " through proxy " + proxyAddressString);
            if (head.length > 0) {
              socket.unshift(head);
            }
            trace2("Successfully established a plaintext connection to " + options2.path + " through proxy " + proxyAddressString);
            resolve24(socket);
          } else {
            (0, logging_1.log)(constants_1.LogVerbosity.ERROR, "Failed to connect to " + options2.path + " through proxy " + proxyAddressString + " with status " + res.statusCode);
            reject();
          }
        });
        request4.once("error", (err) => {
          request4.removeAllListeners();
          (0, logging_1.log)(constants_1.LogVerbosity.ERROR, "Failed to connect to proxy " + proxyAddressString + " with error " + err.message);
          reject();
        });
        request4.end();
      });
    }
    __name(getProxiedConnection, "getProxiedConnection");
  }
});

// node_modules/@grpc/grpc-js/build/src/stream-decoder.js
var require_stream_decoder = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/stream-decoder.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.StreamDecoder = void 0;
    var ReadState;
    (function(ReadState2) {
      ReadState2[ReadState2["NO_DATA"] = 0] = "NO_DATA";
      ReadState2[ReadState2["READING_SIZE"] = 1] = "READING_SIZE";
      ReadState2[ReadState2["READING_MESSAGE"] = 2] = "READING_MESSAGE";
    })(ReadState || (ReadState = {}));
    var StreamDecoder = class {
      static {
        __name(this, "StreamDecoder");
      }
      constructor(maxReadMessageLength) {
        this.maxReadMessageLength = maxReadMessageLength;
        this.readState = ReadState.NO_DATA;
        this.readCompressFlag = Buffer.alloc(1);
        this.readPartialSize = Buffer.alloc(4);
        this.readSizeRemaining = 4;
        this.readMessageSize = 0;
        this.readPartialMessage = [];
        this.readMessageRemaining = 0;
      }
      write(data) {
        let readHead = 0;
        let toRead;
        const result = [];
        while (readHead < data.length) {
          switch (this.readState) {
            case ReadState.NO_DATA:
              this.readCompressFlag = data.slice(readHead, readHead + 1);
              readHead += 1;
              this.readState = ReadState.READING_SIZE;
              this.readPartialSize.fill(0);
              this.readSizeRemaining = 4;
              this.readMessageSize = 0;
              this.readMessageRemaining = 0;
              this.readPartialMessage = [];
              break;
            case ReadState.READING_SIZE:
              toRead = Math.min(data.length - readHead, this.readSizeRemaining);
              data.copy(this.readPartialSize, 4 - this.readSizeRemaining, readHead, readHead + toRead);
              this.readSizeRemaining -= toRead;
              readHead += toRead;
              if (this.readSizeRemaining === 0) {
                this.readMessageSize = this.readPartialSize.readUInt32BE(0);
                if (this.maxReadMessageLength !== -1 && this.readMessageSize > this.maxReadMessageLength) {
                  throw new Error(`Received message larger than max (${this.readMessageSize} vs ${this.maxReadMessageLength})`);
                }
                this.readMessageRemaining = this.readMessageSize;
                if (this.readMessageRemaining > 0) {
                  this.readState = ReadState.READING_MESSAGE;
                } else {
                  const message = Buffer.concat([this.readCompressFlag, this.readPartialSize], 5);
                  this.readState = ReadState.NO_DATA;
                  result.push(message);
                }
              }
              break;
            case ReadState.READING_MESSAGE:
              toRead = Math.min(data.length - readHead, this.readMessageRemaining);
              this.readPartialMessage.push(data.slice(readHead, readHead + toRead));
              this.readMessageRemaining -= toRead;
              readHead += toRead;
              if (this.readMessageRemaining === 0) {
                const framedMessageBuffers = [
                  this.readCompressFlag,
                  this.readPartialSize
                ].concat(this.readPartialMessage);
                const framedMessage = Buffer.concat(framedMessageBuffers, this.readMessageSize + 5);
                this.readState = ReadState.NO_DATA;
                result.push(framedMessage);
              }
              break;
            default:
              throw new Error("Unexpected read state");
          }
        }
        return result;
      }
    };
    exports2.StreamDecoder = StreamDecoder;
  }
});

// node_modules/@grpc/grpc-js/build/src/subchannel-call.js
var require_subchannel_call = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/subchannel-call.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Http2SubchannelCall = void 0;
    var http22 = __require("http2");
    var os43 = __require("os");
    var constants_1 = require_constants9();
    var metadata_1 = require_metadata3();
    var stream_decoder_1 = require_stream_decoder();
    var logging = require_logging();
    var constants_2 = require_constants9();
    var TRACER_NAME = "subchannel_call";
    function getSystemErrorName(errno) {
      for (const [name3, num] of Object.entries(os43.constants.errno)) {
        if (num === errno) {
          return name3;
        }
      }
      return "Unknown system error " + errno;
    }
    __name(getSystemErrorName, "getSystemErrorName");
    function mapHttpStatusCode(code2) {
      const details = `Received HTTP status code ${code2}`;
      let mappedStatusCode;
      switch (code2) {
        // TODO(murgatroid99): handle 100 and 101
        case 400:
          mappedStatusCode = constants_1.Status.INTERNAL;
          break;
        case 401:
          mappedStatusCode = constants_1.Status.UNAUTHENTICATED;
          break;
        case 403:
          mappedStatusCode = constants_1.Status.PERMISSION_DENIED;
          break;
        case 404:
          mappedStatusCode = constants_1.Status.UNIMPLEMENTED;
          break;
        case 429:
        case 502:
        case 503:
        case 504:
          mappedStatusCode = constants_1.Status.UNAVAILABLE;
          break;
        default:
          mappedStatusCode = constants_1.Status.UNKNOWN;
      }
      return {
        code: mappedStatusCode,
        details,
        metadata: new metadata_1.Metadata()
      };
    }
    __name(mapHttpStatusCode, "mapHttpStatusCode");
    var Http2SubchannelCall = class {
      static {
        __name(this, "Http2SubchannelCall");
      }
      constructor(http2Stream, callEventTracker, listener, transport, callId) {
        var _a6;
        this.http2Stream = http2Stream;
        this.callEventTracker = callEventTracker;
        this.listener = listener;
        this.transport = transport;
        this.callId = callId;
        this.isReadFilterPending = false;
        this.isPushPending = false;
        this.canPush = false;
        this.readsClosed = false;
        this.statusOutput = false;
        this.unpushedReadMessages = [];
        this.finalStatus = null;
        this.internalError = null;
        this.serverEndedCall = false;
        this.connectionDropped = false;
        const maxReceiveMessageLength = (_a6 = transport.getOptions()["grpc.max_receive_message_length"]) !== null && _a6 !== void 0 ? _a6 : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH;
        this.decoder = new stream_decoder_1.StreamDecoder(maxReceiveMessageLength);
        http2Stream.on("response", (headers, flags) => {
          let headersString = "";
          for (const header of Object.keys(headers)) {
            headersString += "		" + header + ": " + headers[header] + "\n";
          }
          this.trace("Received server headers:\n" + headersString);
          this.httpStatusCode = headers[":status"];
          if (flags & http22.constants.NGHTTP2_FLAG_END_STREAM) {
            this.handleTrailers(headers);
          } else {
            let metadata;
            try {
              metadata = metadata_1.Metadata.fromHttp2Headers(headers);
            } catch (error) {
              this.endCall({
                code: constants_1.Status.UNKNOWN,
                details: error.message,
                metadata: new metadata_1.Metadata()
              });
              return;
            }
            this.listener.onReceiveMetadata(metadata);
          }
        });
        http2Stream.on("trailers", (headers) => {
          this.handleTrailers(headers);
        });
        http2Stream.on("data", (data) => {
          if (this.statusOutput) {
            return;
          }
          this.trace("receive HTTP/2 data frame of length " + data.length);
          let messages;
          try {
            messages = this.decoder.write(data);
          } catch (e2) {
            if (this.httpStatusCode !== void 0 && this.httpStatusCode !== 200) {
              const mappedStatus = mapHttpStatusCode(this.httpStatusCode);
              this.cancelWithStatus(mappedStatus.code, mappedStatus.details);
            } else {
              this.cancelWithStatus(constants_1.Status.RESOURCE_EXHAUSTED, e2.message);
            }
            return;
          }
          for (const message of messages) {
            this.trace("parsed message of length " + message.length);
            this.callEventTracker.addMessageReceived();
            this.tryPush(message);
          }
        });
        http2Stream.on("end", () => {
          this.readsClosed = true;
          this.maybeOutputStatus();
        });
        http2Stream.on("close", () => {
          this.serverEndedCall = true;
          process.nextTick(() => {
            var _a7;
            this.trace("HTTP/2 stream closed with code " + http2Stream.rstCode);
            if (((_a7 = this.finalStatus) === null || _a7 === void 0 ? void 0 : _a7.code) === constants_1.Status.OK) {
              return;
            }
            let code2;
            let details = "";
            switch (http2Stream.rstCode) {
              case http22.constants.NGHTTP2_NO_ERROR:
                if (this.finalStatus !== null) {
                  return;
                }
                if (this.httpStatusCode && this.httpStatusCode !== 200) {
                  const mappedStatus = mapHttpStatusCode(this.httpStatusCode);
                  code2 = mappedStatus.code;
                  details = mappedStatus.details;
                } else {
                  code2 = constants_1.Status.INTERNAL;
                  details = `Received RST_STREAM with code ${http2Stream.rstCode} (Call ended without gRPC status)`;
                }
                break;
              case http22.constants.NGHTTP2_REFUSED_STREAM:
                code2 = constants_1.Status.UNAVAILABLE;
                details = "Stream refused by server";
                break;
              case http22.constants.NGHTTP2_CANCEL:
                if (this.connectionDropped) {
                  code2 = constants_1.Status.UNAVAILABLE;
                  details = "Connection dropped";
                } else {
                  code2 = constants_1.Status.CANCELLED;
                  details = "Call cancelled";
                }
                break;
              case http22.constants.NGHTTP2_ENHANCE_YOUR_CALM:
                code2 = constants_1.Status.RESOURCE_EXHAUSTED;
                details = "Bandwidth exhausted or memory limit exceeded";
                break;
              case http22.constants.NGHTTP2_INADEQUATE_SECURITY:
                code2 = constants_1.Status.PERMISSION_DENIED;
                details = "Protocol not secure enough";
                break;
              case http22.constants.NGHTTP2_INTERNAL_ERROR:
                code2 = constants_1.Status.INTERNAL;
                if (this.internalError === null) {
                  details = `Received RST_STREAM with code ${http2Stream.rstCode} (Internal server error)`;
                } else {
                  if (this.internalError.code === "ECONNRESET" || this.internalError.code === "ETIMEDOUT") {
                    code2 = constants_1.Status.UNAVAILABLE;
                    details = this.internalError.message;
                  } else {
                    details = `Received RST_STREAM with code ${http2Stream.rstCode} triggered by internal client error: ${this.internalError.message}`;
                  }
                }
                break;
              default:
                code2 = constants_1.Status.INTERNAL;
                details = `Received RST_STREAM with code ${http2Stream.rstCode}`;
            }
            this.endCall({
              code: code2,
              details,
              metadata: new metadata_1.Metadata(),
              rstCode: http2Stream.rstCode
            });
          });
        });
        http2Stream.on("error", (err) => {
          if (err.code !== "ERR_HTTP2_STREAM_ERROR") {
            this.trace("Node error event: message=" + err.message + " code=" + err.code + " errno=" + getSystemErrorName(err.errno) + " syscall=" + err.syscall);
            this.internalError = err;
          }
          this.callEventTracker.onStreamEnd(false);
        });
      }
      getDeadlineInfo() {
        return [`remote_addr=${this.getPeer()}`];
      }
      onDisconnect() {
        this.connectionDropped = true;
        setImmediate(() => {
          this.endCall({
            code: constants_1.Status.UNAVAILABLE,
            details: "Connection dropped",
            metadata: new metadata_1.Metadata()
          });
        });
      }
      outputStatus() {
        if (!this.statusOutput) {
          this.statusOutput = true;
          this.trace("ended with status: code=" + this.finalStatus.code + ' details="' + this.finalStatus.details + '"');
          this.callEventTracker.onCallEnd(this.finalStatus);
          process.nextTick(() => {
            this.listener.onReceiveStatus(this.finalStatus);
          });
          this.http2Stream.resume();
        }
      }
      trace(text) {
        logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callId + "] " + text);
      }
      /**
       * On first call, emits a 'status' event with the given StatusObject.
       * Subsequent calls are no-ops.
       * @param status The status of the call.
       */
      endCall(status) {
        if (this.finalStatus === null || this.finalStatus.code === constants_1.Status.OK) {
          this.finalStatus = status;
          this.maybeOutputStatus();
        }
        this.destroyHttp2Stream();
      }
      maybeOutputStatus() {
        if (this.finalStatus !== null) {
          if (this.finalStatus.code !== constants_1.Status.OK || this.readsClosed && this.unpushedReadMessages.length === 0 && !this.isReadFilterPending && !this.isPushPending) {
            this.outputStatus();
          }
        }
      }
      push(message) {
        this.trace("pushing to reader message of length " + (message instanceof Buffer ? message.length : null));
        this.canPush = false;
        this.isPushPending = true;
        process.nextTick(() => {
          this.isPushPending = false;
          if (this.statusOutput) {
            return;
          }
          this.listener.onReceiveMessage(message);
          this.maybeOutputStatus();
        });
      }
      tryPush(messageBytes) {
        if (this.canPush) {
          this.http2Stream.pause();
          this.push(messageBytes);
        } else {
          this.trace("unpushedReadMessages.push message of length " + messageBytes.length);
          this.unpushedReadMessages.push(messageBytes);
        }
      }
      handleTrailers(headers) {
        this.serverEndedCall = true;
        this.callEventTracker.onStreamEnd(true);
        let headersString = "";
        for (const header of Object.keys(headers)) {
          headersString += "		" + header + ": " + headers[header] + "\n";
        }
        this.trace("Received server trailers:\n" + headersString);
        let metadata;
        try {
          metadata = metadata_1.Metadata.fromHttp2Headers(headers);
        } catch (e2) {
          metadata = new metadata_1.Metadata();
        }
        const metadataMap = metadata.getMap();
        let status;
        if (typeof metadataMap["grpc-status"] === "string") {
          const receivedStatus = Number(metadataMap["grpc-status"]);
          this.trace("received status code " + receivedStatus + " from server");
          metadata.remove("grpc-status");
          let details = "";
          if (typeof metadataMap["grpc-message"] === "string") {
            try {
              details = decodeURI(metadataMap["grpc-message"]);
            } catch (e2) {
              details = metadataMap["grpc-message"];
            }
            metadata.remove("grpc-message");
            this.trace('received status details string "' + details + '" from server');
          }
          status = {
            code: receivedStatus,
            details,
            metadata
          };
        } else if (this.httpStatusCode) {
          status = mapHttpStatusCode(this.httpStatusCode);
          status.metadata = metadata;
        } else {
          status = {
            code: constants_1.Status.UNKNOWN,
            details: "No status information received",
            metadata
          };
        }
        this.endCall(status);
      }
      destroyHttp2Stream() {
        var _a6;
        if (this.http2Stream.destroyed) {
          return;
        }
        if (this.serverEndedCall) {
          this.http2Stream.end();
        } else {
          let code2;
          if (((_a6 = this.finalStatus) === null || _a6 === void 0 ? void 0 : _a6.code) === constants_1.Status.OK) {
            code2 = http22.constants.NGHTTP2_NO_ERROR;
          } else {
            code2 = http22.constants.NGHTTP2_CANCEL;
          }
          this.trace("close http2 stream with code " + code2);
          this.http2Stream.close(code2);
        }
      }
      cancelWithStatus(status, details) {
        this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"');
        this.endCall({ code: status, details, metadata: new metadata_1.Metadata() });
      }
      getStatus() {
        return this.finalStatus;
      }
      getPeer() {
        return this.transport.getPeerName();
      }
      getCallNumber() {
        return this.callId;
      }
      startRead() {
        if (this.finalStatus !== null && this.finalStatus.code !== constants_1.Status.OK) {
          this.readsClosed = true;
          this.maybeOutputStatus();
          return;
        }
        this.canPush = true;
        if (this.unpushedReadMessages.length > 0) {
          const nextMessage = this.unpushedReadMessages.shift();
          this.push(nextMessage);
          return;
        }
        this.http2Stream.resume();
      }
      sendMessageWithContext(context2, message) {
        this.trace("write() called with message of length " + message.length);
        const cb = /* @__PURE__ */ __name((error) => {
          process.nextTick(() => {
            var _a6;
            let code2 = constants_1.Status.UNAVAILABLE;
            if ((error === null || error === void 0 ? void 0 : error.code) === "ERR_STREAM_WRITE_AFTER_END") {
              code2 = constants_1.Status.INTERNAL;
            }
            if (error) {
              this.cancelWithStatus(code2, `Write error: ${error.message}`);
            }
            (_a6 = context2.callback) === null || _a6 === void 0 ? void 0 : _a6.call(context2);
          });
        }, "cb");
        this.trace("sending data chunk of length " + message.length);
        this.callEventTracker.addMessageSent();
        try {
          this.http2Stream.write(message, cb);
        } catch (error) {
          this.endCall({
            code: constants_1.Status.UNAVAILABLE,
            details: `Write failed with error ${error.message}`,
            metadata: new metadata_1.Metadata()
          });
        }
      }
      halfClose() {
        this.trace("end() called");
        this.trace("calling end() on HTTP/2 stream");
        this.http2Stream.end();
      }
    };
    exports2.Http2SubchannelCall = Http2SubchannelCall;
  }
});

// node_modules/@grpc/grpc-js/build/src/call-number.js
var require_call_number = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/call-number.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getNextCallNumber = getNextCallNumber;
    var nextCallNumber = 0;
    function getNextCallNumber() {
      return nextCallNumber++;
    }
    __name(getNextCallNumber, "getNextCallNumber");
  }
});

// node_modules/@grpc/grpc-js/build/src/transport.js
var require_transport = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/transport.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Http2SubchannelConnector = void 0;
    var http22 = __require("http2");
    var channelz_1 = require_channelz();
    var constants_1 = require_constants9();
    var http_proxy_1 = require_http_proxy();
    var logging = require_logging();
    var resolver_1 = require_resolver();
    var subchannel_address_1 = require_subchannel_address();
    var uri_parser_1 = require_uri_parser();
    var net2 = __require("net");
    var subchannel_call_1 = require_subchannel_call();
    var call_number_1 = require_call_number();
    var TRACER_NAME = "transport";
    var FLOW_CONTROL_TRACER_NAME = "transport_flowctrl";
    var clientVersion = require_package3().version;
    var { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_TE, HTTP2_HEADER_USER_AGENT } = http22.constants;
    var KEEPALIVE_TIMEOUT_MS = 2e4;
    var tooManyPingsData = Buffer.from("too_many_pings", "ascii");
    var Http2Transport = class {
      static {
        __name(this, "Http2Transport");
      }
      constructor(session, subchannelAddress, options2, remoteName) {
        this.session = session;
        this.options = options2;
        this.remoteName = remoteName;
        this.keepaliveTimer = null;
        this.pendingSendKeepalivePing = false;
        this.activeCalls = /* @__PURE__ */ new Set();
        this.disconnectListeners = [];
        this.disconnectHandled = false;
        this.channelzEnabled = true;
        this.keepalivesSent = 0;
        this.messagesSent = 0;
        this.messagesReceived = 0;
        this.lastMessageSentTimestamp = null;
        this.lastMessageReceivedTimestamp = null;
        this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress);
        if (options2["grpc.enable_channelz"] === 0) {
          this.channelzEnabled = false;
          this.streamTracker = new channelz_1.ChannelzCallTrackerStub();
        } else {
          this.streamTracker = new channelz_1.ChannelzCallTracker();
        }
        this.channelzRef = (0, channelz_1.registerChannelzSocket)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled);
        this.userAgent = [
          options2["grpc.primary_user_agent"],
          `grpc-node-js/${clientVersion}`,
          options2["grpc.secondary_user_agent"]
        ].filter((e2) => e2).join(" ");
        if ("grpc.keepalive_time_ms" in options2) {
          this.keepaliveTimeMs = options2["grpc.keepalive_time_ms"];
        } else {
          this.keepaliveTimeMs = -1;
        }
        if ("grpc.keepalive_timeout_ms" in options2) {
          this.keepaliveTimeoutMs = options2["grpc.keepalive_timeout_ms"];
        } else {
          this.keepaliveTimeoutMs = KEEPALIVE_TIMEOUT_MS;
        }
        if ("grpc.keepalive_permit_without_calls" in options2) {
          this.keepaliveWithoutCalls = options2["grpc.keepalive_permit_without_calls"] === 1;
        } else {
          this.keepaliveWithoutCalls = false;
        }
        session.once("close", () => {
          this.trace("session closed");
          this.handleDisconnect();
        });
        session.once("goaway", (errorCode, lastStreamID, opaqueData) => {
          let tooManyPings = false;
          if (errorCode === http22.constants.NGHTTP2_ENHANCE_YOUR_CALM && opaqueData && opaqueData.equals(tooManyPingsData)) {
            tooManyPings = true;
          }
          this.trace("connection closed by GOAWAY with code " + errorCode + " and data " + (opaqueData === null || opaqueData === void 0 ? void 0 : opaqueData.toString()));
          this.reportDisconnectToOwner(tooManyPings);
        });
        session.once("error", (error) => {
          this.trace("connection closed with error " + error.message);
          this.handleDisconnect();
        });
        session.socket.once("close", (hadError) => {
          this.trace("connection closed. hadError=" + hadError);
          this.handleDisconnect();
        });
        if (logging.isTracerEnabled(TRACER_NAME)) {
          session.on("remoteSettings", (settings) => {
            this.trace("new settings received" + (this.session !== session ? " on the old connection" : "") + ": " + JSON.stringify(settings));
          });
          session.on("localSettings", (settings) => {
            this.trace("local settings acknowledged by remote" + (this.session !== session ? " on the old connection" : "") + ": " + JSON.stringify(settings));
          });
        }
        if (this.keepaliveWithoutCalls) {
          this.maybeStartKeepalivePingTimer();
        }
      }
      getChannelzInfo() {
        var _a6, _b2, _c2;
        const sessionSocket = this.session.socket;
        const remoteAddress = sessionSocket.remoteAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) : null;
        const localAddress = sessionSocket.localAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) : null;
        let tlsInfo;
        if (this.session.encrypted) {
          const tlsSocket = sessionSocket;
          const cipherInfo = tlsSocket.getCipher();
          const certificate = tlsSocket.getCertificate();
          const peerCertificate = tlsSocket.getPeerCertificate();
          tlsInfo = {
            cipherSuiteStandardName: (_a6 = cipherInfo.standardName) !== null && _a6 !== void 0 ? _a6 : null,
            cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name,
            localCertificate: certificate && "raw" in certificate ? certificate.raw : null,
            remoteCertificate: peerCertificate && "raw" in peerCertificate ? peerCertificate.raw : null
          };
        } else {
          tlsInfo = null;
        }
        const socketInfo = {
          remoteAddress,
          localAddress,
          security: tlsInfo,
          remoteName: this.remoteName,
          streamsStarted: this.streamTracker.callsStarted,
          streamsSucceeded: this.streamTracker.callsSucceeded,
          streamsFailed: this.streamTracker.callsFailed,
          messagesSent: this.messagesSent,
          messagesReceived: this.messagesReceived,
          keepAlivesSent: this.keepalivesSent,
          lastLocalStreamCreatedTimestamp: this.streamTracker.lastCallStartedTimestamp,
          lastRemoteStreamCreatedTimestamp: null,
          lastMessageSentTimestamp: this.lastMessageSentTimestamp,
          lastMessageReceivedTimestamp: this.lastMessageReceivedTimestamp,
          localFlowControlWindow: (_b2 = this.session.state.localWindowSize) !== null && _b2 !== void 0 ? _b2 : null,
          remoteFlowControlWindow: (_c2 = this.session.state.remoteWindowSize) !== null && _c2 !== void 0 ? _c2 : null
        };
        return socketInfo;
      }
      trace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text);
      }
      keepaliveTrace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, "keepalive", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text);
      }
      flowControlTrace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, FLOW_CONTROL_TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text);
      }
      internalsTrace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, "transport_internals", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text);
      }
      /**
       * Indicate to the owner of this object that this transport should no longer
       * be used. That happens if the connection drops, or if the server sends a
       * GOAWAY.
       * @param tooManyPings If true, this was triggered by a GOAWAY with data
       * indicating that the session was closed becaues the client sent too many
       * pings.
       * @returns
       */
      reportDisconnectToOwner(tooManyPings) {
        if (this.disconnectHandled) {
          return;
        }
        this.disconnectHandled = true;
        this.disconnectListeners.forEach((listener) => listener(tooManyPings));
      }
      /**
       * Handle connection drops, but not GOAWAYs.
       */
      handleDisconnect() {
        this.clearKeepaliveTimeout();
        this.reportDisconnectToOwner(false);
        for (const call of this.activeCalls) {
          call.onDisconnect();
        }
        setImmediate(() => {
          this.session.destroy();
        });
      }
      addDisconnectListener(listener) {
        this.disconnectListeners.push(listener);
      }
      canSendPing() {
        return !this.session.destroyed && this.keepaliveTimeMs > 0 && (this.keepaliveWithoutCalls || this.activeCalls.size > 0);
      }
      maybeSendPing() {
        var _a6, _b2;
        if (!this.canSendPing()) {
          this.pendingSendKeepalivePing = true;
          return;
        }
        if (this.keepaliveTimer) {
          console.error("keepaliveTimeout is not null");
          return;
        }
        if (this.channelzEnabled) {
          this.keepalivesSent += 1;
        }
        this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms");
        this.keepaliveTimer = setTimeout(() => {
          this.keepaliveTimer = null;
          this.keepaliveTrace("Ping timeout passed without response");
          this.handleDisconnect();
        }, this.keepaliveTimeoutMs);
        (_b2 = (_a6 = this.keepaliveTimer).unref) === null || _b2 === void 0 ? void 0 : _b2.call(_a6);
        let pingSendError = "";
        try {
          const pingSentSuccessfully = this.session.ping((err, duration, payload) => {
            this.clearKeepaliveTimeout();
            if (err) {
              this.keepaliveTrace("Ping failed with error " + err.message);
              this.handleDisconnect();
            } else {
              this.keepaliveTrace("Received ping response");
              this.maybeStartKeepalivePingTimer();
            }
          });
          if (!pingSentSuccessfully) {
            pingSendError = "Ping returned false";
          }
        } catch (e2) {
          pingSendError = (e2 instanceof Error ? e2.message : "") || "Unknown error";
        }
        if (pingSendError) {
          this.keepaliveTrace("Ping send failed: " + pingSendError);
          this.handleDisconnect();
        }
      }
      /**
       * Starts the keepalive ping timer if appropriate. If the timer already ran
       * out while there were no active requests, instead send a ping immediately.
       * If the ping timer is already running or a ping is currently in flight,
       * instead do nothing and wait for them to resolve.
       */
      maybeStartKeepalivePingTimer() {
        var _a6, _b2;
        if (!this.canSendPing()) {
          return;
        }
        if (this.pendingSendKeepalivePing) {
          this.pendingSendKeepalivePing = false;
          this.maybeSendPing();
        } else if (!this.keepaliveTimer) {
          this.keepaliveTrace("Starting keepalive timer for " + this.keepaliveTimeMs + "ms");
          this.keepaliveTimer = setTimeout(() => {
            this.keepaliveTimer = null;
            this.maybeSendPing();
          }, this.keepaliveTimeMs);
          (_b2 = (_a6 = this.keepaliveTimer).unref) === null || _b2 === void 0 ? void 0 : _b2.call(_a6);
        }
      }
      /**
       * Clears whichever keepalive timeout is currently active, if any.
       */
      clearKeepaliveTimeout() {
        if (this.keepaliveTimer) {
          clearTimeout(this.keepaliveTimer);
          this.keepaliveTimer = null;
        }
      }
      removeActiveCall(call) {
        this.activeCalls.delete(call);
        if (this.activeCalls.size === 0) {
          this.session.unref();
        }
      }
      addActiveCall(call) {
        this.activeCalls.add(call);
        if (this.activeCalls.size === 1) {
          this.session.ref();
          if (!this.keepaliveWithoutCalls) {
            this.maybeStartKeepalivePingTimer();
          }
        }
      }
      createCall(metadata, host, method, listener, subchannelCallStatsTracker) {
        const headers = metadata.toHttp2Headers();
        headers[HTTP2_HEADER_AUTHORITY] = host;
        headers[HTTP2_HEADER_USER_AGENT] = this.userAgent;
        headers[HTTP2_HEADER_CONTENT_TYPE] = "application/grpc";
        headers[HTTP2_HEADER_METHOD] = "POST";
        headers[HTTP2_HEADER_PATH] = method;
        headers[HTTP2_HEADER_TE] = "trailers";
        let http2Stream;
        try {
          http2Stream = this.session.request(headers);
        } catch (e2) {
          this.handleDisconnect();
          throw e2;
        }
        this.flowControlTrace("local window size: " + this.session.state.localWindowSize + " remote window size: " + this.session.state.remoteWindowSize);
        this.internalsTrace("session.closed=" + this.session.closed + " session.destroyed=" + this.session.destroyed + " session.socket.destroyed=" + this.session.socket.destroyed);
        let eventTracker;
        let call;
        if (this.channelzEnabled) {
          this.streamTracker.addCallStarted();
          eventTracker = {
            addMessageSent: /* @__PURE__ */ __name(() => {
              var _a6;
              this.messagesSent += 1;
              this.lastMessageSentTimestamp = /* @__PURE__ */ new Date();
              (_a6 = subchannelCallStatsTracker.addMessageSent) === null || _a6 === void 0 ? void 0 : _a6.call(subchannelCallStatsTracker);
            }, "addMessageSent"),
            addMessageReceived: /* @__PURE__ */ __name(() => {
              var _a6;
              this.messagesReceived += 1;
              this.lastMessageReceivedTimestamp = /* @__PURE__ */ new Date();
              (_a6 = subchannelCallStatsTracker.addMessageReceived) === null || _a6 === void 0 ? void 0 : _a6.call(subchannelCallStatsTracker);
            }, "addMessageReceived"),
            onCallEnd: /* @__PURE__ */ __name((status) => {
              var _a6;
              (_a6 = subchannelCallStatsTracker.onCallEnd) === null || _a6 === void 0 ? void 0 : _a6.call(subchannelCallStatsTracker, status);
              this.removeActiveCall(call);
            }, "onCallEnd"),
            onStreamEnd: /* @__PURE__ */ __name((success) => {
              var _a6;
              if (success) {
                this.streamTracker.addCallSucceeded();
              } else {
                this.streamTracker.addCallFailed();
              }
              (_a6 = subchannelCallStatsTracker.onStreamEnd) === null || _a6 === void 0 ? void 0 : _a6.call(subchannelCallStatsTracker, success);
            }, "onStreamEnd")
          };
        } else {
          eventTracker = {
            addMessageSent: /* @__PURE__ */ __name(() => {
              var _a6;
              (_a6 = subchannelCallStatsTracker.addMessageSent) === null || _a6 === void 0 ? void 0 : _a6.call(subchannelCallStatsTracker);
            }, "addMessageSent"),
            addMessageReceived: /* @__PURE__ */ __name(() => {
              var _a6;
              (_a6 = subchannelCallStatsTracker.addMessageReceived) === null || _a6 === void 0 ? void 0 : _a6.call(subchannelCallStatsTracker);
            }, "addMessageReceived"),
            onCallEnd: /* @__PURE__ */ __name((status) => {
              var _a6;
              (_a6 = subchannelCallStatsTracker.onCallEnd) === null || _a6 === void 0 ? void 0 : _a6.call(subchannelCallStatsTracker, status);
              this.removeActiveCall(call);
            }, "onCallEnd"),
            onStreamEnd: /* @__PURE__ */ __name((success) => {
              var _a6;
              (_a6 = subchannelCallStatsTracker.onStreamEnd) === null || _a6 === void 0 ? void 0 : _a6.call(subchannelCallStatsTracker, success);
            }, "onStreamEnd")
          };
        }
        call = new subchannel_call_1.Http2SubchannelCall(http2Stream, eventTracker, listener, this, (0, call_number_1.getNextCallNumber)());
        this.addActiveCall(call);
        return call;
      }
      getChannelzRef() {
        return this.channelzRef;
      }
      getPeerName() {
        return this.subchannelAddressString;
      }
      getOptions() {
        return this.options;
      }
      shutdown() {
        this.session.close();
        (0, channelz_1.unregisterChannelzRef)(this.channelzRef);
      }
    };
    var Http2SubchannelConnector = class {
      static {
        __name(this, "Http2SubchannelConnector");
      }
      constructor(channelTarget) {
        this.channelTarget = channelTarget;
        this.session = null;
        this.isShutdown = false;
      }
      trace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, (0, uri_parser_1.uriToString)(this.channelTarget) + " " + text);
      }
      createSession(secureConnectResult, address, options2) {
        if (this.isShutdown) {
          return Promise.reject();
        }
        if (secureConnectResult.socket.closed) {
          return Promise.reject("Connection closed before starting HTTP/2 handshake");
        }
        return new Promise((resolve24, reject) => {
          let remoteName = null;
          let realTarget = this.channelTarget;
          if ("grpc.http_connect_target" in options2) {
            const parsedTarget = (0, uri_parser_1.parseUri)(options2["grpc.http_connect_target"]);
            if (parsedTarget) {
              realTarget = parsedTarget;
              remoteName = (0, uri_parser_1.uriToString)(parsedTarget);
            }
          }
          const scheme = secureConnectResult.secure ? "https" : "http";
          const targetPath = (0, resolver_1.getDefaultAuthority)(realTarget);
          const closeHandler = /* @__PURE__ */ __name(() => {
            var _a6;
            (_a6 = this.session) === null || _a6 === void 0 ? void 0 : _a6.destroy();
            this.session = null;
            setImmediate(() => {
              if (!reportedError) {
                reportedError = true;
                reject(`${errorMessage.trim()} (${(/* @__PURE__ */ new Date()).toISOString()})`);
              }
            });
          }, "closeHandler");
          const errorHandler = /* @__PURE__ */ __name((error) => {
            var _a6;
            (_a6 = this.session) === null || _a6 === void 0 ? void 0 : _a6.destroy();
            errorMessage = error.message;
            this.trace("connection failed with error " + errorMessage);
            if (!reportedError) {
              reportedError = true;
              reject(`${errorMessage} (${(/* @__PURE__ */ new Date()).toISOString()})`);
            }
          }, "errorHandler");
          const sessionOptions = {
            createConnection: /* @__PURE__ */ __name((authority, option2) => {
              return secureConnectResult.socket;
            }, "createConnection")
          };
          if (options2["grpc-node.flow_control_window"] !== void 0) {
            sessionOptions.settings = {
              initialWindowSize: options2["grpc-node.flow_control_window"]
            };
          }
          const session = http22.connect(`${scheme}://${targetPath}`, sessionOptions);
          this.session = session;
          let errorMessage = "Failed to connect";
          let reportedError = false;
          session.unref();
          session.once("remoteSettings", () => {
            session.removeAllListeners();
            secureConnectResult.socket.removeListener("close", closeHandler);
            secureConnectResult.socket.removeListener("error", errorHandler);
            resolve24(new Http2Transport(session, address, options2, remoteName));
            this.session = null;
          });
          session.once("close", closeHandler);
          session.once("error", errorHandler);
          secureConnectResult.socket.once("close", closeHandler);
          secureConnectResult.socket.once("error", errorHandler);
        });
      }
      tcpConnect(address, options2) {
        return (0, http_proxy_1.getProxiedConnection)(address, options2).then((proxiedSocket) => {
          if (proxiedSocket) {
            return proxiedSocket;
          } else {
            return new Promise((resolve24, reject) => {
              const closeCallback = /* @__PURE__ */ __name(() => {
                reject(new Error("Socket closed"));
              }, "closeCallback");
              const errorCallback = /* @__PURE__ */ __name((error) => {
                reject(error);
              }, "errorCallback");
              const socket = net2.connect(address, () => {
                socket.removeListener("close", closeCallback);
                socket.removeListener("error", errorCallback);
                resolve24(socket);
              });
              socket.once("close", closeCallback);
              socket.once("error", errorCallback);
            });
          }
        });
      }
      async connect(address, secureConnector, options2) {
        if (this.isShutdown) {
          return Promise.reject();
        }
        let tcpConnection = null;
        let secureConnectResult = null;
        const addressString = (0, subchannel_address_1.subchannelAddressToString)(address);
        try {
          this.trace(addressString + " Waiting for secureConnector to be ready");
          await secureConnector.waitForReady();
          this.trace(addressString + " secureConnector is ready");
          tcpConnection = await this.tcpConnect(address, options2);
          tcpConnection.setNoDelay();
          this.trace(addressString + " Established TCP connection");
          secureConnectResult = await secureConnector.connect(tcpConnection);
          this.trace(addressString + " Established secure connection");
          return this.createSession(secureConnectResult, address, options2);
        } catch (e2) {
          tcpConnection === null || tcpConnection === void 0 ? void 0 : tcpConnection.destroy();
          secureConnectResult === null || secureConnectResult === void 0 ? void 0 : secureConnectResult.socket.destroy();
          throw e2;
        }
      }
      shutdown() {
        var _a6;
        this.isShutdown = true;
        (_a6 = this.session) === null || _a6 === void 0 ? void 0 : _a6.close();
        this.session = null;
      }
    };
    exports2.Http2SubchannelConnector = Http2SubchannelConnector;
  }
});

// node_modules/@grpc/grpc-js/build/src/subchannel-pool.js
var require_subchannel_pool = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/subchannel-pool.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SubchannelPool = void 0;
    exports2.getSubchannelPool = getSubchannelPool;
    var channel_options_1 = require_channel_options();
    var subchannel_1 = require_subchannel();
    var subchannel_address_1 = require_subchannel_address();
    var uri_parser_1 = require_uri_parser();
    var transport_1 = require_transport();
    var REF_CHECK_INTERVAL = 1e4;
    var SubchannelPool = class {
      static {
        __name(this, "SubchannelPool");
      }
      /**
       * A pool of subchannels use for making connections. Subchannels with the
       * exact same parameters will be reused.
       */
      constructor() {
        this.pool = /* @__PURE__ */ Object.create(null);
        this.cleanupTimer = null;
      }
      /**
       * Unrefs all unused subchannels and cancels the cleanup task if all
       * subchannels have been unrefed.
       */
      unrefUnusedSubchannels() {
        let allSubchannelsUnrefed = true;
        for (const channelTarget in this.pool) {
          const subchannelObjArray = this.pool[channelTarget];
          const refedSubchannels = subchannelObjArray.filter((value) => !value.subchannel.unrefIfOneRef());
          if (refedSubchannels.length > 0) {
            allSubchannelsUnrefed = false;
          }
          this.pool[channelTarget] = refedSubchannels;
        }
        if (allSubchannelsUnrefed && this.cleanupTimer !== null) {
          clearInterval(this.cleanupTimer);
          this.cleanupTimer = null;
        }
      }
      /**
       * Ensures that the cleanup task is spawned.
       */
      ensureCleanupTask() {
        var _a6, _b2;
        if (this.cleanupTimer === null) {
          this.cleanupTimer = setInterval(() => {
            this.unrefUnusedSubchannels();
          }, REF_CHECK_INTERVAL);
          (_b2 = (_a6 = this.cleanupTimer).unref) === null || _b2 === void 0 ? void 0 : _b2.call(_a6);
        }
      }
      /**
       * Get a subchannel if one already exists with exactly matching parameters.
       * Otherwise, create and save a subchannel with those parameters.
       * @param channelTarget
       * @param subchannelTarget
       * @param channelArguments
       * @param channelCredentials
       */
      getOrCreateSubchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials) {
        this.ensureCleanupTask();
        const channelTarget = (0, uri_parser_1.uriToString)(channelTargetUri);
        if (channelTarget in this.pool) {
          const subchannelObjArray = this.pool[channelTarget];
          for (const subchannelObj of subchannelObjArray) {
            if ((0, subchannel_address_1.subchannelAddressEqual)(subchannelTarget, subchannelObj.subchannelAddress) && (0, channel_options_1.channelOptionsEqual)(channelArguments, subchannelObj.channelArguments) && channelCredentials._equals(subchannelObj.channelCredentials)) {
              return subchannelObj.subchannel;
            }
          }
        }
        const subchannel = new subchannel_1.Subchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials, new transport_1.Http2SubchannelConnector(channelTargetUri));
        if (!(channelTarget in this.pool)) {
          this.pool[channelTarget] = [];
        }
        this.pool[channelTarget].push({
          subchannelAddress: subchannelTarget,
          channelArguments,
          channelCredentials,
          subchannel
        });
        subchannel.ref();
        return subchannel;
      }
    };
    exports2.SubchannelPool = SubchannelPool;
    var globalSubchannelPool = new SubchannelPool();
    function getSubchannelPool(global2) {
      if (global2) {
        return globalSubchannelPool;
      } else {
        return new SubchannelPool();
      }
    }
    __name(getSubchannelPool, "getSubchannelPool");
  }
});

// node_modules/@grpc/grpc-js/build/src/filter-stack.js
var require_filter_stack = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/filter-stack.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.FilterStackFactory = exports2.FilterStack = void 0;
    var FilterStack = class {
      static {
        __name(this, "FilterStack");
      }
      constructor(filters) {
        this.filters = filters;
      }
      sendMetadata(metadata) {
        let result = metadata;
        for (let i = 0; i < this.filters.length; i++) {
          result = this.filters[i].sendMetadata(result);
        }
        return result;
      }
      receiveMetadata(metadata) {
        let result = metadata;
        for (let i = this.filters.length - 1; i >= 0; i--) {
          result = this.filters[i].receiveMetadata(result);
        }
        return result;
      }
      sendMessage(message) {
        let result = message;
        for (let i = 0; i < this.filters.length; i++) {
          result = this.filters[i].sendMessage(result);
        }
        return result;
      }
      receiveMessage(message) {
        let result = message;
        for (let i = this.filters.length - 1; i >= 0; i--) {
          result = this.filters[i].receiveMessage(result);
        }
        return result;
      }
      receiveTrailers(status) {
        let result = status;
        for (let i = this.filters.length - 1; i >= 0; i--) {
          result = this.filters[i].receiveTrailers(result);
        }
        return result;
      }
      push(filters) {
        this.filters.unshift(...filters);
      }
      getFilters() {
        return this.filters;
      }
    };
    exports2.FilterStack = FilterStack;
    var FilterStackFactory = class _FilterStackFactory {
      static {
        __name(this, "FilterStackFactory");
      }
      constructor(factories) {
        this.factories = factories;
      }
      push(filterFactories) {
        this.factories.unshift(...filterFactories);
      }
      clone() {
        return new _FilterStackFactory([...this.factories]);
      }
      createFilter() {
        return new FilterStack(this.factories.map((factory) => factory.createFilter()));
      }
    };
    exports2.FilterStackFactory = FilterStackFactory;
  }
});

// node_modules/@grpc/grpc-js/build/src/compression-algorithms.js
var require_compression_algorithms = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/compression-algorithms.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CompressionAlgorithms = void 0;
    var CompressionAlgorithms;
    (function(CompressionAlgorithms2) {
      CompressionAlgorithms2[CompressionAlgorithms2["identity"] = 0] = "identity";
      CompressionAlgorithms2[CompressionAlgorithms2["deflate"] = 1] = "deflate";
      CompressionAlgorithms2[CompressionAlgorithms2["gzip"] = 2] = "gzip";
    })(CompressionAlgorithms || (exports2.CompressionAlgorithms = CompressionAlgorithms = {}));
  }
});

// node_modules/@grpc/grpc-js/build/src/filter.js
var require_filter = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/filter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BaseFilter = void 0;
    var BaseFilter = class {
      static {
        __name(this, "BaseFilter");
      }
      async sendMetadata(metadata) {
        return metadata;
      }
      receiveMetadata(metadata) {
        return metadata;
      }
      async sendMessage(message) {
        return message;
      }
      async receiveMessage(message) {
        return message;
      }
      receiveTrailers(status) {
        return status;
      }
    };
    exports2.BaseFilter = BaseFilter;
  }
});

// node_modules/@grpc/grpc-js/build/src/compression-filter.js
var require_compression_filter = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/compression-filter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CompressionFilterFactory = exports2.CompressionFilter = void 0;
    var zlib2 = __require("zlib");
    var compression_algorithms_1 = require_compression_algorithms();
    var constants_1 = require_constants9();
    var filter_1 = require_filter();
    var logging = require_logging();
    var isCompressionAlgorithmKey = /* @__PURE__ */ __name((key) => {
      return typeof key === "number" && typeof compression_algorithms_1.CompressionAlgorithms[key] === "string";
    }, "isCompressionAlgorithmKey");
    var CompressionHandler = class {
      static {
        __name(this, "CompressionHandler");
      }
      /**
       * @param message Raw uncompressed message bytes
       * @param compress Indicates whether the message should be compressed
       * @return Framed message, compressed if applicable
       */
      async writeMessage(message, compress) {
        let messageBuffer = message;
        if (compress) {
          messageBuffer = await this.compressMessage(messageBuffer);
        }
        const output = Buffer.allocUnsafe(messageBuffer.length + 5);
        output.writeUInt8(compress ? 1 : 0, 0);
        output.writeUInt32BE(messageBuffer.length, 1);
        messageBuffer.copy(output, 5);
        return output;
      }
      /**
       * @param data Framed message, possibly compressed
       * @return Uncompressed message
       */
      async readMessage(data) {
        const compressed = data.readUInt8(0) === 1;
        let messageBuffer = data.slice(5);
        if (compressed) {
          messageBuffer = await this.decompressMessage(messageBuffer);
        }
        return messageBuffer;
      }
    };
    var IdentityHandler = class extends CompressionHandler {
      static {
        __name(this, "IdentityHandler");
      }
      async compressMessage(message) {
        return message;
      }
      async writeMessage(message, compress) {
        const output = Buffer.allocUnsafe(message.length + 5);
        output.writeUInt8(0, 0);
        output.writeUInt32BE(message.length, 1);
        message.copy(output, 5);
        return output;
      }
      decompressMessage(message) {
        return Promise.reject(new Error('Received compressed message but "grpc-encoding" header was identity'));
      }
    };
    var DeflateHandler = class extends CompressionHandler {
      static {
        __name(this, "DeflateHandler");
      }
      constructor(maxRecvMessageLength) {
        super();
        this.maxRecvMessageLength = maxRecvMessageLength;
      }
      compressMessage(message) {
        return new Promise((resolve24, reject) => {
          zlib2.deflate(message, (err, output) => {
            if (err) {
              reject(err);
            } else {
              resolve24(output);
            }
          });
        });
      }
      decompressMessage(message) {
        return new Promise((resolve24, reject) => {
          let totalLength = 0;
          const messageParts = [];
          const decompresser = zlib2.createInflate();
          decompresser.on("data", (chunk) => {
            messageParts.push(chunk);
            totalLength += chunk.byteLength;
            if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) {
              decompresser.destroy();
              reject({
                code: constants_1.Status.RESOURCE_EXHAUSTED,
                details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}`
              });
            }
          });
          decompresser.on("end", () => {
            resolve24(Buffer.concat(messageParts));
          });
          decompresser.write(message);
          decompresser.end();
        });
      }
    };
    var GzipHandler = class extends CompressionHandler {
      static {
        __name(this, "GzipHandler");
      }
      constructor(maxRecvMessageLength) {
        super();
        this.maxRecvMessageLength = maxRecvMessageLength;
      }
      compressMessage(message) {
        return new Promise((resolve24, reject) => {
          zlib2.gzip(message, (err, output) => {
            if (err) {
              reject(err);
            } else {
              resolve24(output);
            }
          });
        });
      }
      decompressMessage(message) {
        return new Promise((resolve24, reject) => {
          let totalLength = 0;
          const messageParts = [];
          const decompresser = zlib2.createGunzip();
          decompresser.on("data", (chunk) => {
            messageParts.push(chunk);
            totalLength += chunk.byteLength;
            if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) {
              decompresser.destroy();
              reject({
                code: constants_1.Status.RESOURCE_EXHAUSTED,
                details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}`
              });
            }
          });
          decompresser.on("end", () => {
            resolve24(Buffer.concat(messageParts));
          });
          decompresser.write(message);
          decompresser.end();
        });
      }
    };
    var UnknownHandler = class extends CompressionHandler {
      static {
        __name(this, "UnknownHandler");
      }
      constructor(compressionName) {
        super();
        this.compressionName = compressionName;
      }
      compressMessage(message) {
        return Promise.reject(new Error(`Received message compressed with unsupported compression method ${this.compressionName}`));
      }
      decompressMessage(message) {
        return Promise.reject(new Error(`Compression method not supported: ${this.compressionName}`));
      }
    };
    function getCompressionHandler(compressionName, maxReceiveMessageSize) {
      switch (compressionName) {
        case "identity":
          return new IdentityHandler();
        case "deflate":
          return new DeflateHandler(maxReceiveMessageSize);
        case "gzip":
          return new GzipHandler(maxReceiveMessageSize);
        default:
          return new UnknownHandler(compressionName);
      }
    }
    __name(getCompressionHandler, "getCompressionHandler");
    var CompressionFilter = class extends filter_1.BaseFilter {
      static {
        __name(this, "CompressionFilter");
      }
      constructor(channelOptions, sharedFilterConfig) {
        var _a6, _b2, _c2;
        super();
        this.sharedFilterConfig = sharedFilterConfig;
        this.sendCompression = new IdentityHandler();
        this.receiveCompression = new IdentityHandler();
        this.currentCompressionAlgorithm = "identity";
        const compressionAlgorithmKey = channelOptions["grpc.default_compression_algorithm"];
        this.maxReceiveMessageLength = (_a6 = channelOptions["grpc.max_receive_message_length"]) !== null && _a6 !== void 0 ? _a6 : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH;
        this.maxSendMessageLength = (_b2 = channelOptions["grpc.max_send_message_length"]) !== null && _b2 !== void 0 ? _b2 : constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH;
        if (compressionAlgorithmKey !== void 0) {
          if (isCompressionAlgorithmKey(compressionAlgorithmKey)) {
            const clientSelectedEncoding = compression_algorithms_1.CompressionAlgorithms[compressionAlgorithmKey];
            const serverSupportedEncodings = (_c2 = sharedFilterConfig.serverSupportedEncodingHeader) === null || _c2 === void 0 ? void 0 : _c2.split(",");
            if (!serverSupportedEncodings || serverSupportedEncodings.includes(clientSelectedEncoding)) {
              this.currentCompressionAlgorithm = clientSelectedEncoding;
              this.sendCompression = getCompressionHandler(this.currentCompressionAlgorithm, -1);
            }
          } else {
            logging.log(constants_1.LogVerbosity.ERROR, `Invalid value provided for grpc.default_compression_algorithm option: ${compressionAlgorithmKey}`);
          }
        }
      }
      async sendMetadata(metadata) {
        const headers = await metadata;
        headers.set("grpc-accept-encoding", "identity,deflate,gzip");
        headers.set("accept-encoding", "identity");
        if (this.currentCompressionAlgorithm === "identity") {
          headers.remove("grpc-encoding");
        } else {
          headers.set("grpc-encoding", this.currentCompressionAlgorithm);
        }
        return headers;
      }
      receiveMetadata(metadata) {
        const receiveEncoding = metadata.get("grpc-encoding");
        if (receiveEncoding.length > 0) {
          const encoding = receiveEncoding[0];
          if (typeof encoding === "string") {
            this.receiveCompression = getCompressionHandler(encoding, this.maxReceiveMessageLength);
          }
        }
        metadata.remove("grpc-encoding");
        const serverSupportedEncodingsHeader = metadata.get("grpc-accept-encoding")[0];
        if (serverSupportedEncodingsHeader) {
          this.sharedFilterConfig.serverSupportedEncodingHeader = serverSupportedEncodingsHeader;
          const serverSupportedEncodings = serverSupportedEncodingsHeader.split(",");
          if (!serverSupportedEncodings.includes(this.currentCompressionAlgorithm)) {
            this.sendCompression = new IdentityHandler();
            this.currentCompressionAlgorithm = "identity";
          }
        }
        metadata.remove("grpc-accept-encoding");
        return metadata;
      }
      async sendMessage(message) {
        var _a6;
        const resolvedMessage = await message;
        if (this.maxSendMessageLength !== -1 && resolvedMessage.message.length > this.maxSendMessageLength) {
          throw {
            code: constants_1.Status.RESOURCE_EXHAUSTED,
            details: `Attempted to send message with a size larger than ${this.maxSendMessageLength}`
          };
        }
        let compress;
        if (this.sendCompression instanceof IdentityHandler) {
          compress = false;
        } else {
          compress = (((_a6 = resolvedMessage.flags) !== null && _a6 !== void 0 ? _a6 : 0) & 2) === 0;
        }
        return {
          message: await this.sendCompression.writeMessage(resolvedMessage.message, compress),
          flags: resolvedMessage.flags
        };
      }
      async receiveMessage(message) {
        return this.receiveCompression.readMessage(await message);
      }
    };
    exports2.CompressionFilter = CompressionFilter;
    var CompressionFilterFactory = class {
      static {
        __name(this, "CompressionFilterFactory");
      }
      constructor(channel, options2) {
        this.options = options2;
        this.sharedFilterConfig = {};
      }
      createFilter() {
        return new CompressionFilter(this.options, this.sharedFilterConfig);
      }
    };
    exports2.CompressionFilterFactory = CompressionFilterFactory;
  }
});

// node_modules/@grpc/grpc-js/build/src/deadline.js
var require_deadline = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/deadline.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.minDeadline = minDeadline;
    exports2.getDeadlineTimeoutString = getDeadlineTimeoutString;
    exports2.getRelativeTimeout = getRelativeTimeout;
    exports2.deadlineToString = deadlineToString;
    exports2.formatDateDifference = formatDateDifference;
    function minDeadline(...deadlineList) {
      let minValue = Infinity;
      for (const deadline of deadlineList) {
        const deadlineMsecs = deadline instanceof Date ? deadline.getTime() : deadline;
        if (deadlineMsecs < minValue) {
          minValue = deadlineMsecs;
        }
      }
      return minValue;
    }
    __name(minDeadline, "minDeadline");
    var units = [
      ["m", 1],
      ["S", 1e3],
      ["M", 60 * 1e3],
      ["H", 60 * 60 * 1e3]
    ];
    function getDeadlineTimeoutString(deadline) {
      const now = (/* @__PURE__ */ new Date()).getTime();
      if (deadline instanceof Date) {
        deadline = deadline.getTime();
      }
      const timeoutMs = Math.max(deadline - now, 0);
      for (const [unit, factor] of units) {
        const amount = timeoutMs / factor;
        if (amount < 1e8) {
          return String(Math.ceil(amount)) + unit;
        }
      }
      throw new Error("Deadline is too far in the future");
    }
    __name(getDeadlineTimeoutString, "getDeadlineTimeoutString");
    var MAX_TIMEOUT_TIME = 2147483647;
    function getRelativeTimeout(deadline) {
      const deadlineMs = deadline instanceof Date ? deadline.getTime() : deadline;
      const now = (/* @__PURE__ */ new Date()).getTime();
      const timeout2 = deadlineMs - now;
      if (timeout2 < 0) {
        return 0;
      } else if (timeout2 > MAX_TIMEOUT_TIME) {
        return Infinity;
      } else {
        return timeout2;
      }
    }
    __name(getRelativeTimeout, "getRelativeTimeout");
    function deadlineToString(deadline) {
      if (deadline instanceof Date) {
        return deadline.toISOString();
      } else {
        const dateDeadline = new Date(deadline);
        if (Number.isNaN(dateDeadline.getTime())) {
          return "" + deadline;
        } else {
          return dateDeadline.toISOString();
        }
      }
    }
    __name(deadlineToString, "deadlineToString");
    function formatDateDifference(startDate, endDate) {
      return ((endDate.getTime() - startDate.getTime()) / 1e3).toFixed(3) + "s";
    }
    __name(formatDateDifference, "formatDateDifference");
  }
});

// node_modules/@grpc/grpc-js/build/src/control-plane-status.js
var require_control_plane_status = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/control-plane-status.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.restrictControlPlaneStatusCode = restrictControlPlaneStatusCode;
    var constants_1 = require_constants9();
    var INAPPROPRIATE_CONTROL_PLANE_CODES = [
      constants_1.Status.OK,
      constants_1.Status.INVALID_ARGUMENT,
      constants_1.Status.NOT_FOUND,
      constants_1.Status.ALREADY_EXISTS,
      constants_1.Status.FAILED_PRECONDITION,
      constants_1.Status.ABORTED,
      constants_1.Status.OUT_OF_RANGE,
      constants_1.Status.DATA_LOSS
    ];
    function restrictControlPlaneStatusCode(code2, details) {
      if (INAPPROPRIATE_CONTROL_PLANE_CODES.includes(code2)) {
        return {
          code: constants_1.Status.INTERNAL,
          details: `Invalid status from control plane: ${code2} ${constants_1.Status[code2]} ${details}`
        };
      } else {
        return { code: code2, details };
      }
    }
    __name(restrictControlPlaneStatusCode, "restrictControlPlaneStatusCode");
  }
});

// node_modules/@grpc/grpc-js/build/src/load-balancing-call.js
var require_load_balancing_call = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/load-balancing-call.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LoadBalancingCall = void 0;
    var connectivity_state_1 = require_connectivity_state();
    var constants_1 = require_constants9();
    var deadline_1 = require_deadline();
    var metadata_1 = require_metadata3();
    var picker_1 = require_picker();
    var uri_parser_1 = require_uri_parser();
    var logging = require_logging();
    var control_plane_status_1 = require_control_plane_status();
    var http22 = __require("http2");
    var TRACER_NAME = "load_balancing_call";
    var LoadBalancingCall = class {
      static {
        __name(this, "LoadBalancingCall");
      }
      constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber) {
        var _a6, _b2;
        this.channel = channel;
        this.callConfig = callConfig;
        this.methodName = methodName;
        this.host = host;
        this.credentials = credentials;
        this.deadline = deadline;
        this.callNumber = callNumber;
        this.child = null;
        this.readPending = false;
        this.pendingMessage = null;
        this.pendingHalfClose = false;
        this.ended = false;
        this.metadata = null;
        this.listener = null;
        this.onCallEnded = null;
        this.childStartTime = null;
        const splitPath = this.methodName.split("/");
        let serviceName = "";
        if (splitPath.length >= 2) {
          serviceName = splitPath[1];
        }
        const hostname3 = (_b2 = (_a6 = (0, uri_parser_1.splitHostPort)(this.host)) === null || _a6 === void 0 ? void 0 : _a6.host) !== null && _b2 !== void 0 ? _b2 : "localhost";
        this.serviceUrl = `https://${hostname3}/${serviceName}`;
        this.startTime = /* @__PURE__ */ new Date();
      }
      getDeadlineInfo() {
        var _a6, _b2;
        const deadlineInfo = [];
        if (this.childStartTime) {
          if (this.childStartTime > this.startTime) {
            if ((_a6 = this.metadata) === null || _a6 === void 0 ? void 0 : _a6.getOptions().waitForReady) {
              deadlineInfo.push("wait_for_ready");
            }
            deadlineInfo.push(`LB pick: ${(0, deadline_1.formatDateDifference)(this.startTime, this.childStartTime)}`);
          }
          deadlineInfo.push(...this.child.getDeadlineInfo());
          return deadlineInfo;
        } else {
          if ((_b2 = this.metadata) === null || _b2 === void 0 ? void 0 : _b2.getOptions().waitForReady) {
            deadlineInfo.push("wait_for_ready");
          }
          deadlineInfo.push("Waiting for LB pick");
        }
        return deadlineInfo;
      }
      trace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text);
      }
      outputStatus(status, progress) {
        var _a6, _b2;
        if (!this.ended) {
          this.ended = true;
          this.trace("ended with status: code=" + status.code + ' details="' + status.details + '" start time=' + this.startTime.toISOString());
          const finalStatus = Object.assign(Object.assign({}, status), { progress });
          (_a6 = this.listener) === null || _a6 === void 0 ? void 0 : _a6.onReceiveStatus(finalStatus);
          (_b2 = this.onCallEnded) === null || _b2 === void 0 ? void 0 : _b2.call(this, finalStatus.code);
        }
      }
      doPick() {
        var _a6, _b2;
        if (this.ended) {
          return;
        }
        if (!this.metadata) {
          throw new Error("doPick called before start");
        }
        this.trace("Pick called");
        const finalMetadata = this.metadata.clone();
        const pickResult = this.channel.doPick(finalMetadata, this.callConfig.pickInformation);
        const subchannelString = pickResult.subchannel ? "(" + pickResult.subchannel.getChannelzRef().id + ") " + pickResult.subchannel.getAddress() : "" + pickResult.subchannel;
        this.trace("Pick result: " + picker_1.PickResultType[pickResult.pickResultType] + " subchannel: " + subchannelString + " status: " + ((_a6 = pickResult.status) === null || _a6 === void 0 ? void 0 : _a6.code) + " " + ((_b2 = pickResult.status) === null || _b2 === void 0 ? void 0 : _b2.details));
        switch (pickResult.pickResultType) {
          case picker_1.PickResultType.COMPLETE:
            const combinedCallCredentials = this.credentials.compose(pickResult.subchannel.getCallCredentials());
            combinedCallCredentials.generateMetadata({ method_name: this.methodName, service_url: this.serviceUrl }).then((credsMetadata) => {
              var _a7;
              if (this.ended) {
                this.trace("Credentials metadata generation finished after call ended");
                return;
              }
              finalMetadata.merge(credsMetadata);
              if (finalMetadata.get("authorization").length > 1) {
                this.outputStatus({
                  code: constants_1.Status.INTERNAL,
                  details: '"authorization" metadata cannot have multiple values',
                  metadata: new metadata_1.Metadata()
                }, "PROCESSED");
              }
              if (pickResult.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) {
                this.trace("Picked subchannel " + subchannelString + " has state " + connectivity_state_1.ConnectivityState[pickResult.subchannel.getConnectivityState()] + " after getting credentials metadata. Retrying pick");
                this.doPick();
                return;
              }
              if (this.deadline !== Infinity) {
                finalMetadata.set("grpc-timeout", (0, deadline_1.getDeadlineTimeoutString)(this.deadline));
              }
              try {
                this.child = pickResult.subchannel.getRealSubchannel().createCall(finalMetadata, this.host, this.methodName, {
                  onReceiveMetadata: /* @__PURE__ */ __name((metadata) => {
                    this.trace("Received metadata");
                    this.listener.onReceiveMetadata(metadata);
                  }, "onReceiveMetadata"),
                  onReceiveMessage: /* @__PURE__ */ __name((message) => {
                    this.trace("Received message");
                    this.listener.onReceiveMessage(message);
                  }, "onReceiveMessage"),
                  onReceiveStatus: /* @__PURE__ */ __name((status) => {
                    this.trace("Received status");
                    if (status.rstCode === http22.constants.NGHTTP2_REFUSED_STREAM) {
                      this.outputStatus(status, "REFUSED");
                    } else {
                      this.outputStatus(status, "PROCESSED");
                    }
                  }, "onReceiveStatus")
                });
                this.childStartTime = /* @__PURE__ */ new Date();
              } catch (error) {
                this.trace("Failed to start call on picked subchannel " + subchannelString + " with error " + error.message);
                this.outputStatus({
                  code: constants_1.Status.INTERNAL,
                  details: "Failed to start HTTP/2 stream with error " + error.message,
                  metadata: new metadata_1.Metadata()
                }, "NOT_STARTED");
                return;
              }
              (_a7 = pickResult.onCallStarted) === null || _a7 === void 0 ? void 0 : _a7.call(pickResult);
              this.onCallEnded = pickResult.onCallEnded;
              this.trace("Created child call [" + this.child.getCallNumber() + "]");
              if (this.readPending) {
                this.child.startRead();
              }
              if (this.pendingMessage) {
                this.child.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message);
              }
              if (this.pendingHalfClose) {
                this.child.halfClose();
              }
            }, (error) => {
              const { code: code3, details: details2 } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error.code === "number" ? error.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error.message}`);
              this.outputStatus({
                code: code3,
                details: details2,
                metadata: new metadata_1.Metadata()
              }, "PROCESSED");
            });
            break;
          case picker_1.PickResultType.DROP:
            const { code: code2, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details);
            setImmediate(() => {
              this.outputStatus({ code: code2, details, metadata: pickResult.status.metadata }, "DROP");
            });
            break;
          case picker_1.PickResultType.TRANSIENT_FAILURE:
            if (this.metadata.getOptions().waitForReady) {
              this.channel.queueCallForPick(this);
            } else {
              const { code: code3, details: details2 } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details);
              setImmediate(() => {
                this.outputStatus({ code: code3, details: details2, metadata: pickResult.status.metadata }, "PROCESSED");
              });
            }
            break;
          case picker_1.PickResultType.QUEUE:
            this.channel.queueCallForPick(this);
        }
      }
      cancelWithStatus(status, details) {
        var _a6;
        this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"');
        (_a6 = this.child) === null || _a6 === void 0 ? void 0 : _a6.cancelWithStatus(status, details);
        this.outputStatus({ code: status, details, metadata: new metadata_1.Metadata() }, "PROCESSED");
      }
      getPeer() {
        var _a6, _b2;
        return (_b2 = (_a6 = this.child) === null || _a6 === void 0 ? void 0 : _a6.getPeer()) !== null && _b2 !== void 0 ? _b2 : this.channel.getTarget();
      }
      start(metadata, listener) {
        this.trace("start called");
        this.listener = listener;
        this.metadata = metadata;
        this.doPick();
      }
      sendMessageWithContext(context2, message) {
        this.trace("write() called with message of length " + message.length);
        if (this.child) {
          this.child.sendMessageWithContext(context2, message);
        } else {
          this.pendingMessage = { context: context2, message };
        }
      }
      startRead() {
        this.trace("startRead called");
        if (this.child) {
          this.child.startRead();
        } else {
          this.readPending = true;
        }
      }
      halfClose() {
        this.trace("halfClose called");
        if (this.child) {
          this.child.halfClose();
        } else {
          this.pendingHalfClose = true;
        }
      }
      setCredentials(credentials) {
        throw new Error("Method not implemented.");
      }
      getCallNumber() {
        return this.callNumber;
      }
    };
    exports2.LoadBalancingCall = LoadBalancingCall;
  }
});

// node_modules/@grpc/grpc-js/build/src/resolving-call.js
var require_resolving_call = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/resolving-call.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ResolvingCall = void 0;
    var call_credentials_1 = require_call_credentials();
    var constants_1 = require_constants9();
    var deadline_1 = require_deadline();
    var metadata_1 = require_metadata3();
    var logging = require_logging();
    var control_plane_status_1 = require_control_plane_status();
    var TRACER_NAME = "resolving_call";
    var ResolvingCall = class {
      static {
        __name(this, "ResolvingCall");
      }
      constructor(channel, method, options2, filterStackFactory, callNumber) {
        this.channel = channel;
        this.method = method;
        this.filterStackFactory = filterStackFactory;
        this.callNumber = callNumber;
        this.child = null;
        this.readPending = false;
        this.pendingMessage = null;
        this.pendingHalfClose = false;
        this.ended = false;
        this.readFilterPending = false;
        this.writeFilterPending = false;
        this.pendingChildStatus = null;
        this.metadata = null;
        this.listener = null;
        this.statusWatchers = [];
        this.deadlineTimer = setTimeout(() => {
        }, 0);
        this.filterStack = null;
        this.deadlineStartTime = null;
        this.configReceivedTime = null;
        this.childStartTime = null;
        this.credentials = call_credentials_1.CallCredentials.createEmpty();
        this.deadline = options2.deadline;
        this.host = options2.host;
        if (options2.parentCall) {
          if (options2.flags & constants_1.Propagate.CANCELLATION) {
            options2.parentCall.on("cancelled", () => {
              this.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled by parent call");
            });
          }
          if (options2.flags & constants_1.Propagate.DEADLINE) {
            this.trace("Propagating deadline from parent: " + options2.parentCall.getDeadline());
            this.deadline = (0, deadline_1.minDeadline)(this.deadline, options2.parentCall.getDeadline());
          }
        }
        this.trace("Created");
        this.runDeadlineTimer();
      }
      trace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text);
      }
      runDeadlineTimer() {
        clearTimeout(this.deadlineTimer);
        this.deadlineStartTime = /* @__PURE__ */ new Date();
        this.trace("Deadline: " + (0, deadline_1.deadlineToString)(this.deadline));
        const timeout2 = (0, deadline_1.getRelativeTimeout)(this.deadline);
        if (timeout2 !== Infinity) {
          this.trace("Deadline will be reached in " + timeout2 + "ms");
          const handleDeadline = /* @__PURE__ */ __name(() => {
            if (!this.deadlineStartTime) {
              this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, "Deadline exceeded");
              return;
            }
            const deadlineInfo = [];
            const deadlineEndTime = /* @__PURE__ */ new Date();
            deadlineInfo.push(`Deadline exceeded after ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, deadlineEndTime)}`);
            if (this.configReceivedTime) {
              if (this.configReceivedTime > this.deadlineStartTime) {
                deadlineInfo.push(`name resolution: ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, this.configReceivedTime)}`);
              }
              if (this.childStartTime) {
                if (this.childStartTime > this.configReceivedTime) {
                  deadlineInfo.push(`metadata filters: ${(0, deadline_1.formatDateDifference)(this.configReceivedTime, this.childStartTime)}`);
                }
              } else {
                deadlineInfo.push("waiting for metadata filters");
              }
            } else {
              deadlineInfo.push("waiting for name resolution");
            }
            if (this.child) {
              deadlineInfo.push(...this.child.getDeadlineInfo());
            }
            this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, deadlineInfo.join(","));
          }, "handleDeadline");
          if (timeout2 <= 0) {
            process.nextTick(handleDeadline);
          } else {
            this.deadlineTimer = setTimeout(handleDeadline, timeout2);
          }
        }
      }
      outputStatus(status) {
        if (!this.ended) {
          this.ended = true;
          if (!this.filterStack) {
            this.filterStack = this.filterStackFactory.createFilter();
          }
          clearTimeout(this.deadlineTimer);
          const filteredStatus = this.filterStack.receiveTrailers(status);
          this.trace("ended with status: code=" + filteredStatus.code + ' details="' + filteredStatus.details + '"');
          this.statusWatchers.forEach((watcher) => watcher(filteredStatus));
          process.nextTick(() => {
            var _a6;
            (_a6 = this.listener) === null || _a6 === void 0 ? void 0 : _a6.onReceiveStatus(filteredStatus);
          });
        }
      }
      sendMessageOnChild(context2, message) {
        if (!this.child) {
          throw new Error("sendMessageonChild called with child not populated");
        }
        const child = this.child;
        this.writeFilterPending = true;
        this.filterStack.sendMessage(Promise.resolve({ message, flags: context2.flags })).then((filteredMessage) => {
          this.writeFilterPending = false;
          child.sendMessageWithContext(context2, filteredMessage.message);
          if (this.pendingHalfClose) {
            child.halfClose();
          }
        }, (status) => {
          this.cancelWithStatus(status.code, status.details);
        });
      }
      getConfig() {
        if (this.ended) {
          return;
        }
        if (!this.metadata || !this.listener) {
          throw new Error("getConfig called before start");
        }
        const configResult = this.channel.getConfig(this.method, this.metadata);
        if (configResult.type === "NONE") {
          this.channel.queueCallForConfig(this);
          return;
        } else if (configResult.type === "ERROR") {
          if (this.metadata.getOptions().waitForReady) {
            this.channel.queueCallForConfig(this);
          } else {
            this.outputStatus(configResult.error);
          }
          return;
        }
        this.configReceivedTime = /* @__PURE__ */ new Date();
        const config = configResult.config;
        if (config.status !== constants_1.Status.OK) {
          const { code: code2, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(config.status, "Failed to route call to method " + this.method);
          this.outputStatus({
            code: code2,
            details,
            metadata: new metadata_1.Metadata()
          });
          return;
        }
        if (config.methodConfig.timeout) {
          const configDeadline = /* @__PURE__ */ new Date();
          configDeadline.setSeconds(configDeadline.getSeconds() + config.methodConfig.timeout.seconds);
          configDeadline.setMilliseconds(configDeadline.getMilliseconds() + config.methodConfig.timeout.nanos / 1e6);
          this.deadline = (0, deadline_1.minDeadline)(this.deadline, configDeadline);
          this.runDeadlineTimer();
        }
        this.filterStackFactory.push(config.dynamicFilterFactories);
        this.filterStack = this.filterStackFactory.createFilter();
        this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then((filteredMetadata) => {
          this.child = this.channel.createRetryingCall(config, this.method, this.host, this.credentials, this.deadline);
          this.trace("Created child [" + this.child.getCallNumber() + "]");
          this.childStartTime = /* @__PURE__ */ new Date();
          this.child.start(filteredMetadata, {
            onReceiveMetadata: /* @__PURE__ */ __name((metadata) => {
              this.trace("Received metadata");
              this.listener.onReceiveMetadata(this.filterStack.receiveMetadata(metadata));
            }, "onReceiveMetadata"),
            onReceiveMessage: /* @__PURE__ */ __name((message) => {
              this.trace("Received message");
              this.readFilterPending = true;
              this.filterStack.receiveMessage(message).then((filteredMesssage) => {
                this.trace("Finished filtering received message");
                this.readFilterPending = false;
                this.listener.onReceiveMessage(filteredMesssage);
                if (this.pendingChildStatus) {
                  this.outputStatus(this.pendingChildStatus);
                }
              }, (status) => {
                this.cancelWithStatus(status.code, status.details);
              });
            }, "onReceiveMessage"),
            onReceiveStatus: /* @__PURE__ */ __name((status) => {
              this.trace("Received status");
              if (this.readFilterPending) {
                this.pendingChildStatus = status;
              } else {
                this.outputStatus(status);
              }
            }, "onReceiveStatus")
          });
          if (this.readPending) {
            this.child.startRead();
          }
          if (this.pendingMessage) {
            this.sendMessageOnChild(this.pendingMessage.context, this.pendingMessage.message);
          } else if (this.pendingHalfClose) {
            this.child.halfClose();
          }
        }, (status) => {
          this.outputStatus(status);
        });
      }
      reportResolverError(status) {
        var _a6;
        if ((_a6 = this.metadata) === null || _a6 === void 0 ? void 0 : _a6.getOptions().waitForReady) {
          this.channel.queueCallForConfig(this);
        } else {
          this.outputStatus(status);
        }
      }
      cancelWithStatus(status, details) {
        var _a6;
        this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"');
        (_a6 = this.child) === null || _a6 === void 0 ? void 0 : _a6.cancelWithStatus(status, details);
        this.outputStatus({
          code: status,
          details,
          metadata: new metadata_1.Metadata()
        });
      }
      getPeer() {
        var _a6, _b2;
        return (_b2 = (_a6 = this.child) === null || _a6 === void 0 ? void 0 : _a6.getPeer()) !== null && _b2 !== void 0 ? _b2 : this.channel.getTarget();
      }
      start(metadata, listener) {
        this.trace("start called");
        this.metadata = metadata.clone();
        this.listener = listener;
        this.getConfig();
      }
      sendMessageWithContext(context2, message) {
        this.trace("write() called with message of length " + message.length);
        if (this.child) {
          this.sendMessageOnChild(context2, message);
        } else {
          this.pendingMessage = { context: context2, message };
        }
      }
      startRead() {
        this.trace("startRead called");
        if (this.child) {
          this.child.startRead();
        } else {
          this.readPending = true;
        }
      }
      halfClose() {
        this.trace("halfClose called");
        if (this.child && !this.writeFilterPending) {
          this.child.halfClose();
        } else {
          this.pendingHalfClose = true;
        }
      }
      setCredentials(credentials) {
        this.credentials = credentials;
      }
      addStatusWatcher(watcher) {
        this.statusWatchers.push(watcher);
      }
      getCallNumber() {
        return this.callNumber;
      }
    };
    exports2.ResolvingCall = ResolvingCall;
  }
});

// node_modules/@grpc/grpc-js/build/src/retrying-call.js
var require_retrying_call = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/retrying-call.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RetryingCall = exports2.MessageBufferTracker = exports2.RetryThrottler = void 0;
    var constants_1 = require_constants9();
    var deadline_1 = require_deadline();
    var metadata_1 = require_metadata3();
    var logging = require_logging();
    var TRACER_NAME = "retrying_call";
    var RetryThrottler = class {
      static {
        __name(this, "RetryThrottler");
      }
      constructor(maxTokens, tokenRatio, previousRetryThrottler) {
        this.maxTokens = maxTokens;
        this.tokenRatio = tokenRatio;
        if (previousRetryThrottler) {
          this.tokens = previousRetryThrottler.tokens * (maxTokens / previousRetryThrottler.maxTokens);
        } else {
          this.tokens = maxTokens;
        }
      }
      addCallSucceeded() {
        this.tokens = Math.min(this.tokens + this.tokenRatio, this.maxTokens);
      }
      addCallFailed() {
        this.tokens = Math.max(this.tokens - 1, 0);
      }
      canRetryCall() {
        return this.tokens > this.maxTokens / 2;
      }
    };
    exports2.RetryThrottler = RetryThrottler;
    var MessageBufferTracker = class {
      static {
        __name(this, "MessageBufferTracker");
      }
      constructor(totalLimit, limitPerCall) {
        this.totalLimit = totalLimit;
        this.limitPerCall = limitPerCall;
        this.totalAllocated = 0;
        this.allocatedPerCall = /* @__PURE__ */ new Map();
      }
      allocate(size, callId) {
        var _a6;
        const currentPerCall = (_a6 = this.allocatedPerCall.get(callId)) !== null && _a6 !== void 0 ? _a6 : 0;
        if (this.limitPerCall - currentPerCall < size || this.totalLimit - this.totalAllocated < size) {
          return false;
        }
        this.allocatedPerCall.set(callId, currentPerCall + size);
        this.totalAllocated += size;
        return true;
      }
      free(size, callId) {
        var _a6;
        if (this.totalAllocated < size) {
          throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > total allocated ${this.totalAllocated}`);
        }
        this.totalAllocated -= size;
        const currentPerCall = (_a6 = this.allocatedPerCall.get(callId)) !== null && _a6 !== void 0 ? _a6 : 0;
        if (currentPerCall < size) {
          throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > allocated for call ${currentPerCall}`);
        }
        this.allocatedPerCall.set(callId, currentPerCall - size);
      }
      freeAll(callId) {
        var _a6;
        const currentPerCall = (_a6 = this.allocatedPerCall.get(callId)) !== null && _a6 !== void 0 ? _a6 : 0;
        if (this.totalAllocated < currentPerCall) {
          throw new Error(`Invalid buffer allocation state: call ${callId} allocated ${currentPerCall} > total allocated ${this.totalAllocated}`);
        }
        this.totalAllocated -= currentPerCall;
        this.allocatedPerCall.delete(callId);
      }
    };
    exports2.MessageBufferTracker = MessageBufferTracker;
    var PREVIONS_RPC_ATTEMPTS_METADATA_KEY = "grpc-previous-rpc-attempts";
    var DEFAULT_MAX_ATTEMPTS_LIMIT = 5;
    var RetryingCall = class {
      static {
        __name(this, "RetryingCall");
      }
      constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber, bufferTracker, retryThrottler) {
        var _a6;
        this.channel = channel;
        this.callConfig = callConfig;
        this.methodName = methodName;
        this.host = host;
        this.credentials = credentials;
        this.deadline = deadline;
        this.callNumber = callNumber;
        this.bufferTracker = bufferTracker;
        this.retryThrottler = retryThrottler;
        this.listener = null;
        this.initialMetadata = null;
        this.underlyingCalls = [];
        this.writeBuffer = [];
        this.writeBufferOffset = 0;
        this.readStarted = false;
        this.transparentRetryUsed = false;
        this.attempts = 0;
        this.hedgingTimer = null;
        this.committedCallIndex = null;
        this.initialRetryBackoffSec = 0;
        this.nextRetryBackoffSec = 0;
        const maxAttemptsLimit = (_a6 = channel.getOptions()["grpc-node.retry_max_attempts_limit"]) !== null && _a6 !== void 0 ? _a6 : DEFAULT_MAX_ATTEMPTS_LIMIT;
        if (channel.getOptions()["grpc.enable_retries"] === 0) {
          this.state = "NO_RETRY";
          this.maxAttempts = 1;
        } else if (callConfig.methodConfig.retryPolicy) {
          this.state = "RETRY";
          const retryPolicy = callConfig.methodConfig.retryPolicy;
          this.nextRetryBackoffSec = this.initialRetryBackoffSec = Number(retryPolicy.initialBackoff.substring(0, retryPolicy.initialBackoff.length - 1));
          this.maxAttempts = Math.min(retryPolicy.maxAttempts, maxAttemptsLimit);
        } else if (callConfig.methodConfig.hedgingPolicy) {
          this.state = "HEDGING";
          this.maxAttempts = Math.min(callConfig.methodConfig.hedgingPolicy.maxAttempts, maxAttemptsLimit);
        } else {
          this.state = "TRANSPARENT_ONLY";
          this.maxAttempts = 1;
        }
        this.startTime = /* @__PURE__ */ new Date();
      }
      getDeadlineInfo() {
        if (this.underlyingCalls.length === 0) {
          return [];
        }
        const deadlineInfo = [];
        const latestCall = this.underlyingCalls[this.underlyingCalls.length - 1];
        if (this.underlyingCalls.length > 1) {
          deadlineInfo.push(`previous attempts: ${this.underlyingCalls.length - 1}`);
        }
        if (latestCall.startTime > this.startTime) {
          deadlineInfo.push(`time to current attempt start: ${(0, deadline_1.formatDateDifference)(this.startTime, latestCall.startTime)}`);
        }
        deadlineInfo.push(...latestCall.call.getDeadlineInfo());
        return deadlineInfo;
      }
      getCallNumber() {
        return this.callNumber;
      }
      trace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text);
      }
      reportStatus(statusObject) {
        this.trace("ended with status: code=" + statusObject.code + ' details="' + statusObject.details + '" start time=' + this.startTime.toISOString());
        this.bufferTracker.freeAll(this.callNumber);
        this.writeBufferOffset = this.writeBufferOffset + this.writeBuffer.length;
        this.writeBuffer = [];
        process.nextTick(() => {
          var _a6;
          (_a6 = this.listener) === null || _a6 === void 0 ? void 0 : _a6.onReceiveStatus({
            code: statusObject.code,
            details: statusObject.details,
            metadata: statusObject.metadata
          });
        });
      }
      cancelWithStatus(status, details) {
        this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"');
        this.reportStatus({ code: status, details, metadata: new metadata_1.Metadata() });
        for (const { call } of this.underlyingCalls) {
          call.cancelWithStatus(status, details);
        }
      }
      getPeer() {
        if (this.committedCallIndex !== null) {
          return this.underlyingCalls[this.committedCallIndex].call.getPeer();
        } else {
          return "unknown";
        }
      }
      getBufferEntry(messageIndex) {
        var _a6;
        return (_a6 = this.writeBuffer[messageIndex - this.writeBufferOffset]) !== null && _a6 !== void 0 ? _a6 : {
          entryType: "FREED",
          allocated: false
        };
      }
      getNextBufferIndex() {
        return this.writeBufferOffset + this.writeBuffer.length;
      }
      clearSentMessages() {
        if (this.state !== "COMMITTED") {
          return;
        }
        let earliestNeededMessageIndex;
        if (this.underlyingCalls[this.committedCallIndex].state === "COMPLETED") {
          earliestNeededMessageIndex = this.getNextBufferIndex();
        } else {
          earliestNeededMessageIndex = this.underlyingCalls[this.committedCallIndex].nextMessageToSend;
        }
        for (let messageIndex = this.writeBufferOffset; messageIndex < earliestNeededMessageIndex; messageIndex++) {
          const bufferEntry = this.getBufferEntry(messageIndex);
          if (bufferEntry.allocated) {
            this.bufferTracker.free(bufferEntry.message.message.length, this.callNumber);
          }
        }
        this.writeBuffer = this.writeBuffer.slice(earliestNeededMessageIndex - this.writeBufferOffset);
        this.writeBufferOffset = earliestNeededMessageIndex;
      }
      commitCall(index) {
        var _a6, _b2;
        if (this.state === "COMMITTED") {
          return;
        }
        this.trace("Committing call [" + this.underlyingCalls[index].call.getCallNumber() + "] at index " + index);
        this.state = "COMMITTED";
        (_b2 = (_a6 = this.callConfig).onCommitted) === null || _b2 === void 0 ? void 0 : _b2.call(_a6);
        this.committedCallIndex = index;
        for (let i = 0; i < this.underlyingCalls.length; i++) {
          if (i === index) {
            continue;
          }
          if (this.underlyingCalls[i].state === "COMPLETED") {
            continue;
          }
          this.underlyingCalls[i].state = "COMPLETED";
          this.underlyingCalls[i].call.cancelWithStatus(constants_1.Status.CANCELLED, "Discarded in favor of other hedged attempt");
        }
        this.clearSentMessages();
      }
      commitCallWithMostMessages() {
        if (this.state === "COMMITTED") {
          return;
        }
        let mostMessages = -1;
        let callWithMostMessages = -1;
        for (const [index, childCall] of this.underlyingCalls.entries()) {
          if (childCall.state === "ACTIVE" && childCall.nextMessageToSend > mostMessages) {
            mostMessages = childCall.nextMessageToSend;
            callWithMostMessages = index;
          }
        }
        if (callWithMostMessages === -1) {
          this.state = "TRANSPARENT_ONLY";
        } else {
          this.commitCall(callWithMostMessages);
        }
      }
      isStatusCodeInList(list3, code2) {
        return list3.some((value) => {
          var _a6;
          return value === code2 || value.toString().toLowerCase() === ((_a6 = constants_1.Status[code2]) === null || _a6 === void 0 ? void 0 : _a6.toLowerCase());
        });
      }
      getNextRetryBackoffMs() {
        var _a6;
        const retryPolicy = (_a6 = this.callConfig) === null || _a6 === void 0 ? void 0 : _a6.methodConfig.retryPolicy;
        if (!retryPolicy) {
          return 0;
        }
        const nextBackoffMs = Math.random() * this.nextRetryBackoffSec * 1e3;
        const maxBackoffSec = Number(retryPolicy.maxBackoff.substring(0, retryPolicy.maxBackoff.length - 1));
        this.nextRetryBackoffSec = Math.min(this.nextRetryBackoffSec * retryPolicy.backoffMultiplier, maxBackoffSec);
        return nextBackoffMs;
      }
      maybeRetryCall(pushback, callback) {
        if (this.state !== "RETRY") {
          callback(false);
          return;
        }
        if (this.attempts >= this.maxAttempts) {
          callback(false);
          return;
        }
        let retryDelayMs;
        if (pushback === null) {
          retryDelayMs = this.getNextRetryBackoffMs();
        } else if (pushback < 0) {
          this.state = "TRANSPARENT_ONLY";
          callback(false);
          return;
        } else {
          retryDelayMs = pushback;
          this.nextRetryBackoffSec = this.initialRetryBackoffSec;
        }
        setTimeout(() => {
          var _a6, _b2;
          if (this.state !== "RETRY") {
            callback(false);
            return;
          }
          if ((_b2 = (_a6 = this.retryThrottler) === null || _a6 === void 0 ? void 0 : _a6.canRetryCall()) !== null && _b2 !== void 0 ? _b2 : true) {
            callback(true);
            this.attempts += 1;
            this.startNewAttempt();
          } else {
            this.trace("Retry attempt denied by throttling policy");
            callback(false);
          }
        }, retryDelayMs);
      }
      countActiveCalls() {
        let count = 0;
        for (const call of this.underlyingCalls) {
          if ((call === null || call === void 0 ? void 0 : call.state) === "ACTIVE") {
            count += 1;
          }
        }
        return count;
      }
      handleProcessedStatus(status, callIndex, pushback) {
        var _a6, _b2, _c2;
        switch (this.state) {
          case "COMMITTED":
          case "NO_RETRY":
          case "TRANSPARENT_ONLY":
            this.commitCall(callIndex);
            this.reportStatus(status);
            break;
          case "HEDGING":
            if (this.isStatusCodeInList((_a6 = this.callConfig.methodConfig.hedgingPolicy.nonFatalStatusCodes) !== null && _a6 !== void 0 ? _a6 : [], status.code)) {
              (_b2 = this.retryThrottler) === null || _b2 === void 0 ? void 0 : _b2.addCallFailed();
              let delayMs;
              if (pushback === null) {
                delayMs = 0;
              } else if (pushback < 0) {
                this.state = "TRANSPARENT_ONLY";
                this.commitCall(callIndex);
                this.reportStatus(status);
                return;
              } else {
                delayMs = pushback;
              }
              setTimeout(() => {
                this.maybeStartHedgingAttempt();
                if (this.countActiveCalls() === 0) {
                  this.commitCall(callIndex);
                  this.reportStatus(status);
                }
              }, delayMs);
            } else {
              this.commitCall(callIndex);
              this.reportStatus(status);
            }
            break;
          case "RETRY":
            if (this.isStatusCodeInList(this.callConfig.methodConfig.retryPolicy.retryableStatusCodes, status.code)) {
              (_c2 = this.retryThrottler) === null || _c2 === void 0 ? void 0 : _c2.addCallFailed();
              this.maybeRetryCall(pushback, (retried) => {
                if (!retried) {
                  this.commitCall(callIndex);
                  this.reportStatus(status);
                }
              });
            } else {
              this.commitCall(callIndex);
              this.reportStatus(status);
            }
            break;
        }
      }
      getPushback(metadata) {
        const mdValue = metadata.get("grpc-retry-pushback-ms");
        if (mdValue.length === 0) {
          return null;
        }
        try {
          return parseInt(mdValue[0]);
        } catch (e2) {
          return -1;
        }
      }
      handleChildStatus(status, callIndex) {
        var _a6;
        if (this.underlyingCalls[callIndex].state === "COMPLETED") {
          return;
        }
        this.trace("state=" + this.state + " handling status with progress " + status.progress + " from child [" + this.underlyingCalls[callIndex].call.getCallNumber() + "] in state " + this.underlyingCalls[callIndex].state);
        this.underlyingCalls[callIndex].state = "COMPLETED";
        if (status.code === constants_1.Status.OK) {
          (_a6 = this.retryThrottler) === null || _a6 === void 0 ? void 0 : _a6.addCallSucceeded();
          this.commitCall(callIndex);
          this.reportStatus(status);
          return;
        }
        if (this.state === "NO_RETRY") {
          this.commitCall(callIndex);
          this.reportStatus(status);
          return;
        }
        if (this.state === "COMMITTED") {
          this.reportStatus(status);
          return;
        }
        const pushback = this.getPushback(status.metadata);
        switch (status.progress) {
          case "NOT_STARTED":
            this.startNewAttempt();
            break;
          case "REFUSED":
            if (this.transparentRetryUsed) {
              this.handleProcessedStatus(status, callIndex, pushback);
            } else {
              this.transparentRetryUsed = true;
              this.startNewAttempt();
            }
            break;
          case "DROP":
            this.commitCall(callIndex);
            this.reportStatus(status);
            break;
          case "PROCESSED":
            this.handleProcessedStatus(status, callIndex, pushback);
            break;
        }
      }
      maybeStartHedgingAttempt() {
        if (this.state !== "HEDGING") {
          return;
        }
        if (!this.callConfig.methodConfig.hedgingPolicy) {
          return;
        }
        if (this.attempts >= this.maxAttempts) {
          return;
        }
        this.attempts += 1;
        this.startNewAttempt();
        this.maybeStartHedgingTimer();
      }
      maybeStartHedgingTimer() {
        var _a6, _b2, _c2;
        if (this.hedgingTimer) {
          clearTimeout(this.hedgingTimer);
        }
        if (this.state !== "HEDGING") {
          return;
        }
        if (!this.callConfig.methodConfig.hedgingPolicy) {
          return;
        }
        const hedgingPolicy = this.callConfig.methodConfig.hedgingPolicy;
        if (this.attempts >= this.maxAttempts) {
          return;
        }
        const hedgingDelayString = (_a6 = hedgingPolicy.hedgingDelay) !== null && _a6 !== void 0 ? _a6 : "0s";
        const hedgingDelaySec = Number(hedgingDelayString.substring(0, hedgingDelayString.length - 1));
        this.hedgingTimer = setTimeout(() => {
          this.maybeStartHedgingAttempt();
        }, hedgingDelaySec * 1e3);
        (_c2 = (_b2 = this.hedgingTimer).unref) === null || _c2 === void 0 ? void 0 : _c2.call(_b2);
      }
      startNewAttempt() {
        const child = this.channel.createLoadBalancingCall(this.callConfig, this.methodName, this.host, this.credentials, this.deadline);
        this.trace("Created child call [" + child.getCallNumber() + "] for attempt " + this.attempts);
        const index = this.underlyingCalls.length;
        this.underlyingCalls.push({
          state: "ACTIVE",
          call: child,
          nextMessageToSend: 0,
          startTime: /* @__PURE__ */ new Date()
        });
        const previousAttempts = this.attempts - 1;
        const initialMetadata = this.initialMetadata.clone();
        if (previousAttempts > 0) {
          initialMetadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`);
        }
        let receivedMetadata = false;
        child.start(initialMetadata, {
          onReceiveMetadata: /* @__PURE__ */ __name((metadata) => {
            this.trace("Received metadata from child [" + child.getCallNumber() + "]");
            this.commitCall(index);
            receivedMetadata = true;
            if (previousAttempts > 0) {
              metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`);
            }
            if (this.underlyingCalls[index].state === "ACTIVE") {
              this.listener.onReceiveMetadata(metadata);
            }
          }, "onReceiveMetadata"),
          onReceiveMessage: /* @__PURE__ */ __name((message) => {
            this.trace("Received message from child [" + child.getCallNumber() + "]");
            this.commitCall(index);
            if (this.underlyingCalls[index].state === "ACTIVE") {
              this.listener.onReceiveMessage(message);
            }
          }, "onReceiveMessage"),
          onReceiveStatus: /* @__PURE__ */ __name((status) => {
            this.trace("Received status from child [" + child.getCallNumber() + "]");
            if (!receivedMetadata && previousAttempts > 0) {
              status.metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`);
            }
            this.handleChildStatus(status, index);
          }, "onReceiveStatus")
        });
        this.sendNextChildMessage(index);
        if (this.readStarted) {
          child.startRead();
        }
      }
      start(metadata, listener) {
        this.trace("start called");
        this.listener = listener;
        this.initialMetadata = metadata;
        this.attempts += 1;
        this.startNewAttempt();
        this.maybeStartHedgingTimer();
      }
      handleChildWriteCompleted(childIndex) {
        var _a6, _b2;
        const childCall = this.underlyingCalls[childIndex];
        const messageIndex = childCall.nextMessageToSend;
        (_b2 = (_a6 = this.getBufferEntry(messageIndex)).callback) === null || _b2 === void 0 ? void 0 : _b2.call(_a6);
        this.clearSentMessages();
        childCall.nextMessageToSend += 1;
        this.sendNextChildMessage(childIndex);
      }
      sendNextChildMessage(childIndex) {
        const childCall = this.underlyingCalls[childIndex];
        if (childCall.state === "COMPLETED") {
          return;
        }
        if (this.getBufferEntry(childCall.nextMessageToSend)) {
          const bufferEntry = this.getBufferEntry(childCall.nextMessageToSend);
          switch (bufferEntry.entryType) {
            case "MESSAGE":
              childCall.call.sendMessageWithContext({
                callback: /* @__PURE__ */ __name((error) => {
                  this.handleChildWriteCompleted(childIndex);
                }, "callback")
              }, bufferEntry.message.message);
              break;
            case "HALF_CLOSE":
              childCall.nextMessageToSend += 1;
              childCall.call.halfClose();
              break;
            case "FREED":
              break;
          }
        }
      }
      sendMessageWithContext(context2, message) {
        var _a6;
        this.trace("write() called with message of length " + message.length);
        const writeObj = {
          message,
          flags: context2.flags
        };
        const messageIndex = this.getNextBufferIndex();
        const bufferEntry = {
          entryType: "MESSAGE",
          message: writeObj,
          allocated: this.bufferTracker.allocate(message.length, this.callNumber)
        };
        this.writeBuffer.push(bufferEntry);
        if (bufferEntry.allocated) {
          (_a6 = context2.callback) === null || _a6 === void 0 ? void 0 : _a6.call(context2);
          for (const [callIndex, call] of this.underlyingCalls.entries()) {
            if (call.state === "ACTIVE" && call.nextMessageToSend === messageIndex) {
              call.call.sendMessageWithContext({
                callback: /* @__PURE__ */ __name((error) => {
                  this.handleChildWriteCompleted(callIndex);
                }, "callback")
              }, message);
            }
          }
        } else {
          this.commitCallWithMostMessages();
          if (this.committedCallIndex === null) {
            return;
          }
          const call = this.underlyingCalls[this.committedCallIndex];
          bufferEntry.callback = context2.callback;
          if (call.state === "ACTIVE" && call.nextMessageToSend === messageIndex) {
            call.call.sendMessageWithContext({
              callback: /* @__PURE__ */ __name((error) => {
                this.handleChildWriteCompleted(this.committedCallIndex);
              }, "callback")
            }, message);
          }
        }
      }
      startRead() {
        this.trace("startRead called");
        this.readStarted = true;
        for (const underlyingCall of this.underlyingCalls) {
          if ((underlyingCall === null || underlyingCall === void 0 ? void 0 : underlyingCall.state) === "ACTIVE") {
            underlyingCall.call.startRead();
          }
        }
      }
      halfClose() {
        this.trace("halfClose called");
        const halfCloseIndex = this.getNextBufferIndex();
        this.writeBuffer.push({
          entryType: "HALF_CLOSE",
          allocated: false
        });
        for (const call of this.underlyingCalls) {
          if ((call === null || call === void 0 ? void 0 : call.state) === "ACTIVE" && call.nextMessageToSend === halfCloseIndex) {
            call.nextMessageToSend += 1;
            call.call.halfClose();
          }
        }
      }
      setCredentials(newCredentials) {
        throw new Error("Method not implemented.");
      }
      getMethod() {
        return this.methodName;
      }
      getHost() {
        return this.host;
      }
    };
    exports2.RetryingCall = RetryingCall;
  }
});

// node_modules/@grpc/grpc-js/build/src/subchannel-interface.js
var require_subchannel_interface = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/subchannel-interface.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BaseSubchannelWrapper = void 0;
    var BaseSubchannelWrapper = class {
      static {
        __name(this, "BaseSubchannelWrapper");
      }
      constructor(child) {
        this.child = child;
        this.healthy = true;
        this.healthListeners = /* @__PURE__ */ new Set();
        child.addHealthStateWatcher((childHealthy) => {
          if (this.healthy) {
            this.updateHealthListeners();
          }
        });
      }
      updateHealthListeners() {
        for (const listener of this.healthListeners) {
          listener(this.isHealthy());
        }
      }
      getConnectivityState() {
        return this.child.getConnectivityState();
      }
      addConnectivityStateListener(listener) {
        this.child.addConnectivityStateListener(listener);
      }
      removeConnectivityStateListener(listener) {
        this.child.removeConnectivityStateListener(listener);
      }
      startConnecting() {
        this.child.startConnecting();
      }
      getAddress() {
        return this.child.getAddress();
      }
      throttleKeepalive(newKeepaliveTime) {
        this.child.throttleKeepalive(newKeepaliveTime);
      }
      ref() {
        this.child.ref();
      }
      unref() {
        this.child.unref();
      }
      getChannelzRef() {
        return this.child.getChannelzRef();
      }
      isHealthy() {
        return this.healthy && this.child.isHealthy();
      }
      addHealthStateWatcher(listener) {
        this.healthListeners.add(listener);
      }
      removeHealthStateWatcher(listener) {
        this.healthListeners.delete(listener);
      }
      setHealthy(healthy) {
        if (healthy !== this.healthy) {
          this.healthy = healthy;
          if (this.child.isHealthy()) {
            this.updateHealthListeners();
          }
        }
      }
      getRealSubchannel() {
        return this.child.getRealSubchannel();
      }
      realSubchannelEquals(other2) {
        return this.getRealSubchannel() === other2.getRealSubchannel();
      }
      getCallCredentials() {
        return this.child.getCallCredentials();
      }
    };
    exports2.BaseSubchannelWrapper = BaseSubchannelWrapper;
  }
});

// node_modules/@grpc/grpc-js/build/src/internal-channel.js
var require_internal_channel = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/internal-channel.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InternalChannel = exports2.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = void 0;
    var channel_credentials_1 = require_channel_credentials();
    var resolving_load_balancer_1 = require_resolving_load_balancer();
    var subchannel_pool_1 = require_subchannel_pool();
    var picker_1 = require_picker();
    var metadata_1 = require_metadata3();
    var constants_1 = require_constants9();
    var filter_stack_1 = require_filter_stack();
    var compression_filter_1 = require_compression_filter();
    var resolver_1 = require_resolver();
    var logging_1 = require_logging();
    var http_proxy_1 = require_http_proxy();
    var uri_parser_1 = require_uri_parser();
    var connectivity_state_1 = require_connectivity_state();
    var channelz_1 = require_channelz();
    var load_balancing_call_1 = require_load_balancing_call();
    var deadline_1 = require_deadline();
    var resolving_call_1 = require_resolving_call();
    var call_number_1 = require_call_number();
    var control_plane_status_1 = require_control_plane_status();
    var retrying_call_1 = require_retrying_call();
    var subchannel_interface_1 = require_subchannel_interface();
    var MAX_TIMEOUT_TIME = 2147483647;
    var MIN_IDLE_TIMEOUT_MS = 1e3;
    var DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1e3;
    var RETRY_THROTTLER_MAP = /* @__PURE__ */ new Map();
    var DEFAULT_RETRY_BUFFER_SIZE_BYTES = 1 << 24;
    var DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES = 1 << 20;
    var ChannelSubchannelWrapper = class extends subchannel_interface_1.BaseSubchannelWrapper {
      static {
        __name(this, "ChannelSubchannelWrapper");
      }
      constructor(childSubchannel, channel) {
        super(childSubchannel);
        this.channel = channel;
        this.refCount = 0;
        this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime) => {
          channel.throttleKeepalive(keepaliveTime);
        };
      }
      ref() {
        if (this.refCount === 0) {
          this.child.addConnectivityStateListener(this.subchannelStateListener);
          this.channel.addWrappedSubchannel(this);
        }
        this.child.ref();
        this.refCount += 1;
      }
      unref() {
        this.child.unref();
        this.refCount -= 1;
        if (this.refCount <= 0) {
          this.child.removeConnectivityStateListener(this.subchannelStateListener);
          this.channel.removeWrappedSubchannel(this);
        }
      }
    };
    var ShutdownPicker = class {
      static {
        __name(this, "ShutdownPicker");
      }
      pick(pickArgs) {
        return {
          pickResultType: picker_1.PickResultType.DROP,
          status: {
            code: constants_1.Status.UNAVAILABLE,
            details: "Channel closed before call started",
            metadata: new metadata_1.Metadata()
          },
          subchannel: null,
          onCallStarted: null,
          onCallEnded: null
        };
      }
    };
    exports2.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = "grpc.internal.no_subchannel";
    var ChannelzInfoTracker = class {
      static {
        __name(this, "ChannelzInfoTracker");
      }
      constructor(target) {
        this.target = target;
        this.trace = new channelz_1.ChannelzTrace();
        this.callTracker = new channelz_1.ChannelzCallTracker();
        this.childrenTracker = new channelz_1.ChannelzChildrenTracker();
        this.state = connectivity_state_1.ConnectivityState.IDLE;
      }
      getChannelzInfoCallback() {
        return () => {
          return {
            target: this.target,
            state: this.state,
            trace: this.trace,
            callTracker: this.callTracker,
            children: this.childrenTracker.getChildLists()
          };
        };
      }
    };
    var InternalChannel = class {
      static {
        __name(this, "InternalChannel");
      }
      constructor(target, credentials, options2) {
        var _a6, _b2, _c2, _d, _e, _f;
        this.credentials = credentials;
        this.options = options2;
        this.connectivityState = connectivity_state_1.ConnectivityState.IDLE;
        this.currentPicker = new picker_1.UnavailablePicker();
        this.configSelectionQueue = [];
        this.pickQueue = [];
        this.connectivityStateWatchers = [];
        this.callRefTimer = null;
        this.configSelector = null;
        this.currentResolutionError = null;
        this.wrappedSubchannels = /* @__PURE__ */ new Set();
        this.callCount = 0;
        this.idleTimer = null;
        this.channelzEnabled = true;
        this.randomChannelId = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
        if (typeof target !== "string") {
          throw new TypeError("Channel target must be a string");
        }
        if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) {
          throw new TypeError("Channel credentials must be a ChannelCredentials object");
        }
        if (options2) {
          if (typeof options2 !== "object") {
            throw new TypeError("Channel options must be an object");
          }
        }
        this.channelzInfoTracker = new ChannelzInfoTracker(target);
        const originalTargetUri = (0, uri_parser_1.parseUri)(target);
        if (originalTargetUri === null) {
          throw new Error(`Could not parse target name "${target}"`);
        }
        const defaultSchemeMapResult = (0, resolver_1.mapUriDefaultScheme)(originalTargetUri);
        if (defaultSchemeMapResult === null) {
          throw new Error(`Could not find a default scheme for target name "${target}"`);
        }
        if (this.options["grpc.enable_channelz"] === 0) {
          this.channelzEnabled = false;
        }
        this.channelzRef = (0, channelz_1.registerChannelzChannel)(target, this.channelzInfoTracker.getChannelzInfoCallback(), this.channelzEnabled);
        if (this.channelzEnabled) {
          this.channelzInfoTracker.trace.addTrace("CT_INFO", "Channel created");
        }
        if (this.options["grpc.default_authority"]) {
          this.defaultAuthority = this.options["grpc.default_authority"];
        } else {
          this.defaultAuthority = (0, resolver_1.getDefaultAuthority)(defaultSchemeMapResult);
        }
        const proxyMapResult = (0, http_proxy_1.mapProxyName)(defaultSchemeMapResult, options2);
        this.target = proxyMapResult.target;
        this.options = Object.assign({}, this.options, proxyMapResult.extraOptions);
        this.subchannelPool = (0, subchannel_pool_1.getSubchannelPool)(((_a6 = this.options["grpc.use_local_subchannel_pool"]) !== null && _a6 !== void 0 ? _a6 : 0) === 0);
        this.retryBufferTracker = new retrying_call_1.MessageBufferTracker((_b2 = this.options["grpc.retry_buffer_size"]) !== null && _b2 !== void 0 ? _b2 : DEFAULT_RETRY_BUFFER_SIZE_BYTES, (_c2 = this.options["grpc.per_rpc_retry_buffer_size"]) !== null && _c2 !== void 0 ? _c2 : DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES);
        this.keepaliveTime = (_d = this.options["grpc.keepalive_time_ms"]) !== null && _d !== void 0 ? _d : -1;
        this.idleTimeoutMs = Math.max((_e = this.options["grpc.client_idle_timeout_ms"]) !== null && _e !== void 0 ? _e : DEFAULT_IDLE_TIMEOUT_MS, MIN_IDLE_TIMEOUT_MS);
        const channelControlHelper = {
          createSubchannel: /* @__PURE__ */ __name((subchannelAddress, subchannelArgs) => {
            const finalSubchannelArgs = {};
            for (const [key, value] of Object.entries(subchannelArgs)) {
              if (!key.startsWith(exports2.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX)) {
                finalSubchannelArgs[key] = value;
              }
            }
            const subchannel = this.subchannelPool.getOrCreateSubchannel(this.target, subchannelAddress, finalSubchannelArgs, this.credentials);
            subchannel.throttleKeepalive(this.keepaliveTime);
            if (this.channelzEnabled) {
              this.channelzInfoTracker.trace.addTrace("CT_INFO", "Created subchannel or used existing subchannel", subchannel.getChannelzRef());
            }
            const wrappedSubchannel = new ChannelSubchannelWrapper(subchannel, this);
            return wrappedSubchannel;
          }, "createSubchannel"),
          updateState: /* @__PURE__ */ __name((connectivityState, picker) => {
            this.currentPicker = picker;
            const queueCopy = this.pickQueue.slice();
            this.pickQueue = [];
            if (queueCopy.length > 0) {
              this.callRefTimerUnref();
            }
            for (const call of queueCopy) {
              call.doPick();
            }
            this.updateState(connectivityState);
          }, "updateState"),
          requestReresolution: /* @__PURE__ */ __name(() => {
            throw new Error("Resolving load balancer should never call requestReresolution");
          }, "requestReresolution"),
          addChannelzChild: /* @__PURE__ */ __name((child) => {
            if (this.channelzEnabled) {
              this.channelzInfoTracker.childrenTracker.refChild(child);
            }
          }, "addChannelzChild"),
          removeChannelzChild: /* @__PURE__ */ __name((child) => {
            if (this.channelzEnabled) {
              this.channelzInfoTracker.childrenTracker.unrefChild(child);
            }
          }, "removeChannelzChild")
        };
        this.resolvingLoadBalancer = new resolving_load_balancer_1.ResolvingLoadBalancer(this.target, channelControlHelper, this.options, (serviceConfig, configSelector) => {
          var _a7;
          if (serviceConfig.retryThrottling) {
            RETRY_THROTTLER_MAP.set(this.getTarget(), new retrying_call_1.RetryThrottler(serviceConfig.retryThrottling.maxTokens, serviceConfig.retryThrottling.tokenRatio, RETRY_THROTTLER_MAP.get(this.getTarget())));
          } else {
            RETRY_THROTTLER_MAP.delete(this.getTarget());
          }
          if (this.channelzEnabled) {
            this.channelzInfoTracker.trace.addTrace("CT_INFO", "Address resolution succeeded");
          }
          (_a7 = this.configSelector) === null || _a7 === void 0 ? void 0 : _a7.unref();
          this.configSelector = configSelector;
          this.currentResolutionError = null;
          process.nextTick(() => {
            const localQueue = this.configSelectionQueue;
            this.configSelectionQueue = [];
            if (localQueue.length > 0) {
              this.callRefTimerUnref();
            }
            for (const call of localQueue) {
              call.getConfig();
            }
          });
        }, (status) => {
          if (this.channelzEnabled) {
            this.channelzInfoTracker.trace.addTrace("CT_WARNING", "Address resolution failed with code " + status.code + ' and details "' + status.details + '"');
          }
          if (this.configSelectionQueue.length > 0) {
            this.trace("Name resolution failed with calls queued for config selection");
          }
          if (this.configSelector === null) {
            this.currentResolutionError = Object.assign(Object.assign({}, (0, control_plane_status_1.restrictControlPlaneStatusCode)(status.code, status.details)), { metadata: status.metadata });
          }
          const localQueue = this.configSelectionQueue;
          this.configSelectionQueue = [];
          if (localQueue.length > 0) {
            this.callRefTimerUnref();
          }
          for (const call of localQueue) {
            call.reportResolverError(status);
          }
        });
        this.filterStackFactory = new filter_stack_1.FilterStackFactory([
          new compression_filter_1.CompressionFilterFactory(this, this.options)
        ]);
        this.trace("Channel constructed with options " + JSON.stringify(options2, void 0, 2));
        const error = new Error();
        if ((0, logging_1.isTracerEnabled)("channel_stacktrace")) {
          (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, "channel_stacktrace", "(" + this.channelzRef.id + ") Channel constructed \n" + ((_f = error.stack) === null || _f === void 0 ? void 0 : _f.substring(error.stack.indexOf("\n") + 1)));
        }
        this.lastActivityTimestamp = /* @__PURE__ */ new Date();
      }
      trace(text, verbosityOverride) {
        (0, logging_1.trace)(verbosityOverride !== null && verbosityOverride !== void 0 ? verbosityOverride : constants_1.LogVerbosity.DEBUG, "channel", "(" + this.channelzRef.id + ") " + (0, uri_parser_1.uriToString)(this.target) + " " + text);
      }
      callRefTimerRef() {
        var _a6, _b2, _c2, _d;
        if (!this.callRefTimer) {
          this.callRefTimer = setInterval(() => {
          }, MAX_TIMEOUT_TIME);
        }
        if (!((_b2 = (_a6 = this.callRefTimer).hasRef) === null || _b2 === void 0 ? void 0 : _b2.call(_a6))) {
          this.trace("callRefTimer.ref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.length);
          (_d = (_c2 = this.callRefTimer).ref) === null || _d === void 0 ? void 0 : _d.call(_c2);
        }
      }
      callRefTimerUnref() {
        var _a6, _b2, _c2;
        if (!((_a6 = this.callRefTimer) === null || _a6 === void 0 ? void 0 : _a6.hasRef) || this.callRefTimer.hasRef()) {
          this.trace("callRefTimer.unref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.length);
          (_c2 = (_b2 = this.callRefTimer) === null || _b2 === void 0 ? void 0 : _b2.unref) === null || _c2 === void 0 ? void 0 : _c2.call(_b2);
        }
      }
      removeConnectivityStateWatcher(watcherObject) {
        const watcherIndex = this.connectivityStateWatchers.findIndex((value) => value === watcherObject);
        if (watcherIndex >= 0) {
          this.connectivityStateWatchers.splice(watcherIndex, 1);
        }
      }
      updateState(newState) {
        (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, "connectivity_state", "(" + this.channelzRef.id + ") " + (0, uri_parser_1.uriToString)(this.target) + " " + connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState]);
        if (this.channelzEnabled) {
          this.channelzInfoTracker.trace.addTrace("CT_INFO", "Connectivity state change to " + connectivity_state_1.ConnectivityState[newState]);
        }
        this.connectivityState = newState;
        this.channelzInfoTracker.state = newState;
        const watchersCopy = this.connectivityStateWatchers.slice();
        for (const watcherObject of watchersCopy) {
          if (newState !== watcherObject.currentState) {
            if (watcherObject.timer) {
              clearTimeout(watcherObject.timer);
            }
            this.removeConnectivityStateWatcher(watcherObject);
            watcherObject.callback();
          }
        }
        if (newState !== connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) {
          this.currentResolutionError = null;
        }
      }
      throttleKeepalive(newKeepaliveTime) {
        if (newKeepaliveTime > this.keepaliveTime) {
          this.keepaliveTime = newKeepaliveTime;
          for (const wrappedSubchannel of this.wrappedSubchannels) {
            wrappedSubchannel.throttleKeepalive(newKeepaliveTime);
          }
        }
      }
      addWrappedSubchannel(wrappedSubchannel) {
        this.wrappedSubchannels.add(wrappedSubchannel);
      }
      removeWrappedSubchannel(wrappedSubchannel) {
        this.wrappedSubchannels.delete(wrappedSubchannel);
      }
      doPick(metadata, extraPickInfo) {
        return this.currentPicker.pick({
          metadata,
          extraPickInfo
        });
      }
      queueCallForPick(call) {
        this.pickQueue.push(call);
        this.callRefTimerRef();
      }
      getConfig(method, metadata) {
        if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN) {
          this.resolvingLoadBalancer.exitIdle();
        }
        if (this.configSelector) {
          return {
            type: "SUCCESS",
            config: this.configSelector.invoke(method, metadata, this.randomChannelId)
          };
        } else {
          if (this.currentResolutionError) {
            return {
              type: "ERROR",
              error: this.currentResolutionError
            };
          } else {
            return {
              type: "NONE"
            };
          }
        }
      }
      queueCallForConfig(call) {
        this.configSelectionQueue.push(call);
        this.callRefTimerRef();
      }
      enterIdle() {
        this.resolvingLoadBalancer.destroy();
        this.updateState(connectivity_state_1.ConnectivityState.IDLE);
        this.currentPicker = new picker_1.QueuePicker(this.resolvingLoadBalancer);
        if (this.idleTimer) {
          clearTimeout(this.idleTimer);
          this.idleTimer = null;
        }
        if (this.callRefTimer) {
          clearInterval(this.callRefTimer);
          this.callRefTimer = null;
        }
      }
      startIdleTimeout(timeoutMs) {
        var _a6, _b2;
        this.idleTimer = setTimeout(() => {
          if (this.callCount > 0) {
            this.startIdleTimeout(this.idleTimeoutMs);
            return;
          }
          const now = /* @__PURE__ */ new Date();
          const timeSinceLastActivity = now.valueOf() - this.lastActivityTimestamp.valueOf();
          if (timeSinceLastActivity >= this.idleTimeoutMs) {
            this.trace("Idle timer triggered after " + this.idleTimeoutMs + "ms of inactivity");
            this.enterIdle();
          } else {
            this.startIdleTimeout(this.idleTimeoutMs - timeSinceLastActivity);
          }
        }, timeoutMs);
        (_b2 = (_a6 = this.idleTimer).unref) === null || _b2 === void 0 ? void 0 : _b2.call(_a6);
      }
      maybeStartIdleTimer() {
        if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN && !this.idleTimer) {
          this.startIdleTimeout(this.idleTimeoutMs);
        }
      }
      onCallStart() {
        if (this.channelzEnabled) {
          this.channelzInfoTracker.callTracker.addCallStarted();
        }
        this.callCount += 1;
      }
      onCallEnd(status) {
        if (this.channelzEnabled) {
          if (status.code === constants_1.Status.OK) {
            this.channelzInfoTracker.callTracker.addCallSucceeded();
          } else {
            this.channelzInfoTracker.callTracker.addCallFailed();
          }
        }
        this.callCount -= 1;
        this.lastActivityTimestamp = /* @__PURE__ */ new Date();
        this.maybeStartIdleTimer();
      }
      createLoadBalancingCall(callConfig, method, host, credentials, deadline) {
        const callNumber = (0, call_number_1.getNextCallNumber)();
        this.trace("createLoadBalancingCall [" + callNumber + '] method="' + method + '"');
        return new load_balancing_call_1.LoadBalancingCall(this, callConfig, method, host, credentials, deadline, callNumber);
      }
      createRetryingCall(callConfig, method, host, credentials, deadline) {
        const callNumber = (0, call_number_1.getNextCallNumber)();
        this.trace("createRetryingCall [" + callNumber + '] method="' + method + '"');
        return new retrying_call_1.RetryingCall(this, callConfig, method, host, credentials, deadline, callNumber, this.retryBufferTracker, RETRY_THROTTLER_MAP.get(this.getTarget()));
      }
      createResolvingCall(method, deadline, host, parentCall, propagateFlags) {
        const callNumber = (0, call_number_1.getNextCallNumber)();
        this.trace("createResolvingCall [" + callNumber + '] method="' + method + '", deadline=' + (0, deadline_1.deadlineToString)(deadline));
        const finalOptions = {
          deadline,
          flags: propagateFlags !== null && propagateFlags !== void 0 ? propagateFlags : constants_1.Propagate.DEFAULTS,
          host: host !== null && host !== void 0 ? host : this.defaultAuthority,
          parentCall
        };
        const call = new resolving_call_1.ResolvingCall(this, method, finalOptions, this.filterStackFactory.clone(), callNumber);
        this.onCallStart();
        call.addStatusWatcher((status) => {
          this.onCallEnd(status);
        });
        return call;
      }
      close() {
        var _a6;
        this.resolvingLoadBalancer.destroy();
        this.updateState(connectivity_state_1.ConnectivityState.SHUTDOWN);
        this.currentPicker = new ShutdownPicker();
        for (const call of this.configSelectionQueue) {
          call.cancelWithStatus(constants_1.Status.UNAVAILABLE, "Channel closed before call started");
        }
        this.configSelectionQueue = [];
        for (const call of this.pickQueue) {
          call.cancelWithStatus(constants_1.Status.UNAVAILABLE, "Channel closed before call started");
        }
        this.pickQueue = [];
        if (this.callRefTimer) {
          clearInterval(this.callRefTimer);
        }
        if (this.idleTimer) {
          clearTimeout(this.idleTimer);
        }
        if (this.channelzEnabled) {
          (0, channelz_1.unregisterChannelzRef)(this.channelzRef);
        }
        this.subchannelPool.unrefUnusedSubchannels();
        (_a6 = this.configSelector) === null || _a6 === void 0 ? void 0 : _a6.unref();
        this.configSelector = null;
      }
      getTarget() {
        return (0, uri_parser_1.uriToString)(this.target);
      }
      getConnectivityState(tryToConnect) {
        const connectivityState = this.connectivityState;
        if (tryToConnect) {
          this.resolvingLoadBalancer.exitIdle();
          this.lastActivityTimestamp = /* @__PURE__ */ new Date();
          this.maybeStartIdleTimer();
        }
        return connectivityState;
      }
      watchConnectivityState(currentState, deadline, callback) {
        if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) {
          throw new Error("Channel has been shut down");
        }
        let timer = null;
        if (deadline !== Infinity) {
          const deadlineDate = deadline instanceof Date ? deadline : new Date(deadline);
          const now = /* @__PURE__ */ new Date();
          if (deadline === -Infinity || deadlineDate <= now) {
            process.nextTick(callback, new Error("Deadline passed without connectivity state change"));
            return;
          }
          timer = setTimeout(() => {
            this.removeConnectivityStateWatcher(watcherObject);
            callback(new Error("Deadline passed without connectivity state change"));
          }, deadlineDate.getTime() - now.getTime());
        }
        const watcherObject = {
          currentState,
          callback,
          timer
        };
        this.connectivityStateWatchers.push(watcherObject);
      }
      /**
       * Get the channelz reference object for this channel. The returned value is
       * garbage if channelz is disabled for this channel.
       * @returns
       */
      getChannelzRef() {
        return this.channelzRef;
      }
      createCall(method, deadline, host, parentCall, propagateFlags) {
        if (typeof method !== "string") {
          throw new TypeError("Channel#createCall: method must be a string");
        }
        if (!(typeof deadline === "number" || deadline instanceof Date)) {
          throw new TypeError("Channel#createCall: deadline must be a number or Date");
        }
        if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) {
          throw new Error("Channel has been shut down");
        }
        return this.createResolvingCall(method, deadline, host, parentCall, propagateFlags);
      }
      getOptions() {
        return this.options;
      }
    };
    exports2.InternalChannel = InternalChannel;
  }
});

// node_modules/@grpc/grpc-js/build/src/channel.js
var require_channel = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/channel.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ChannelImplementation = void 0;
    var channel_credentials_1 = require_channel_credentials();
    var internal_channel_1 = require_internal_channel();
    var ChannelImplementation = class {
      static {
        __name(this, "ChannelImplementation");
      }
      constructor(target, credentials, options2) {
        if (typeof target !== "string") {
          throw new TypeError("Channel target must be a string");
        }
        if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) {
          throw new TypeError("Channel credentials must be a ChannelCredentials object");
        }
        if (options2) {
          if (typeof options2 !== "object") {
            throw new TypeError("Channel options must be an object");
          }
        }
        this.internalChannel = new internal_channel_1.InternalChannel(target, credentials, options2);
      }
      close() {
        this.internalChannel.close();
      }
      getTarget() {
        return this.internalChannel.getTarget();
      }
      getConnectivityState(tryToConnect) {
        return this.internalChannel.getConnectivityState(tryToConnect);
      }
      watchConnectivityState(currentState, deadline, callback) {
        this.internalChannel.watchConnectivityState(currentState, deadline, callback);
      }
      /**
       * Get the channelz reference object for this channel. The returned value is
       * garbage if channelz is disabled for this channel.
       * @returns
       */
      getChannelzRef() {
        return this.internalChannel.getChannelzRef();
      }
      createCall(method, deadline, host, parentCall, propagateFlags) {
        if (typeof method !== "string") {
          throw new TypeError("Channel#createCall: method must be a string");
        }
        if (!(typeof deadline === "number" || deadline instanceof Date)) {
          throw new TypeError("Channel#createCall: deadline must be a number or Date");
        }
        return this.internalChannel.createCall(method, deadline, host, parentCall, propagateFlags);
      }
    };
    exports2.ChannelImplementation = ChannelImplementation;
  }
});

// node_modules/@grpc/grpc-js/build/src/server-call.js
var require_server_call = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/server-call.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ServerDuplexStreamImpl = exports2.ServerWritableStreamImpl = exports2.ServerReadableStreamImpl = exports2.ServerUnaryCallImpl = void 0;
    exports2.serverErrorToStatus = serverErrorToStatus;
    var events_1 = __require("events");
    var stream_1 = __require("stream");
    var constants_1 = require_constants9();
    var metadata_1 = require_metadata3();
    function serverErrorToStatus(error, overrideTrailers) {
      var _a6;
      const status = {
        code: constants_1.Status.UNKNOWN,
        details: "message" in error ? error.message : "Unknown Error",
        metadata: (_a6 = overrideTrailers !== null && overrideTrailers !== void 0 ? overrideTrailers : error.metadata) !== null && _a6 !== void 0 ? _a6 : null
      };
      if ("code" in error && typeof error.code === "number" && Number.isInteger(error.code)) {
        status.code = error.code;
        if ("details" in error && typeof error.details === "string") {
          status.details = error.details;
        }
      }
      return status;
    }
    __name(serverErrorToStatus, "serverErrorToStatus");
    var ServerUnaryCallImpl = class extends events_1.EventEmitter {
      static {
        __name(this, "ServerUnaryCallImpl");
      }
      constructor(path108, call, metadata, request4) {
        super();
        this.path = path108;
        this.call = call;
        this.metadata = metadata;
        this.request = request4;
        this.cancelled = false;
      }
      getPeer() {
        return this.call.getPeer();
      }
      sendMetadata(responseMetadata) {
        this.call.sendMetadata(responseMetadata);
      }
      getDeadline() {
        return this.call.getDeadline();
      }
      getPath() {
        return this.path;
      }
      getHost() {
        return this.call.getHost();
      }
    };
    exports2.ServerUnaryCallImpl = ServerUnaryCallImpl;
    var ServerReadableStreamImpl = class extends stream_1.Readable {
      static {
        __name(this, "ServerReadableStreamImpl");
      }
      constructor(path108, call, metadata) {
        super({ objectMode: true });
        this.path = path108;
        this.call = call;
        this.metadata = metadata;
        this.cancelled = false;
      }
      _read(size) {
        this.call.startRead();
      }
      getPeer() {
        return this.call.getPeer();
      }
      sendMetadata(responseMetadata) {
        this.call.sendMetadata(responseMetadata);
      }
      getDeadline() {
        return this.call.getDeadline();
      }
      getPath() {
        return this.path;
      }
      getHost() {
        return this.call.getHost();
      }
    };
    exports2.ServerReadableStreamImpl = ServerReadableStreamImpl;
    var ServerWritableStreamImpl = class extends stream_1.Writable {
      static {
        __name(this, "ServerWritableStreamImpl");
      }
      constructor(path108, call, metadata, request4) {
        super({ objectMode: true });
        this.path = path108;
        this.call = call;
        this.metadata = metadata;
        this.request = request4;
        this.pendingStatus = {
          code: constants_1.Status.OK,
          details: "OK"
        };
        this.cancelled = false;
        this.trailingMetadata = new metadata_1.Metadata();
        this.on("error", (err) => {
          this.pendingStatus = serverErrorToStatus(err);
          this.end();
        });
      }
      getPeer() {
        return this.call.getPeer();
      }
      sendMetadata(responseMetadata) {
        this.call.sendMetadata(responseMetadata);
      }
      getDeadline() {
        return this.call.getDeadline();
      }
      getPath() {
        return this.path;
      }
      getHost() {
        return this.call.getHost();
      }
      _write(chunk, encoding, callback) {
        this.call.sendMessage(chunk, callback);
      }
      _final(callback) {
        var _a6;
        callback(null);
        this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a6 = this.pendingStatus.metadata) !== null && _a6 !== void 0 ? _a6 : this.trailingMetadata }));
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      end(metadata) {
        if (metadata) {
          this.trailingMetadata = metadata;
        }
        return super.end();
      }
    };
    exports2.ServerWritableStreamImpl = ServerWritableStreamImpl;
    var ServerDuplexStreamImpl = class extends stream_1.Duplex {
      static {
        __name(this, "ServerDuplexStreamImpl");
      }
      constructor(path108, call, metadata) {
        super({ objectMode: true });
        this.path = path108;
        this.call = call;
        this.metadata = metadata;
        this.pendingStatus = {
          code: constants_1.Status.OK,
          details: "OK"
        };
        this.cancelled = false;
        this.trailingMetadata = new metadata_1.Metadata();
        this.on("error", (err) => {
          this.pendingStatus = serverErrorToStatus(err);
          this.end();
        });
      }
      getPeer() {
        return this.call.getPeer();
      }
      sendMetadata(responseMetadata) {
        this.call.sendMetadata(responseMetadata);
      }
      getDeadline() {
        return this.call.getDeadline();
      }
      getPath() {
        return this.path;
      }
      getHost() {
        return this.call.getHost();
      }
      _read(size) {
        this.call.startRead();
      }
      _write(chunk, encoding, callback) {
        this.call.sendMessage(chunk, callback);
      }
      _final(callback) {
        var _a6;
        callback(null);
        this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a6 = this.pendingStatus.metadata) !== null && _a6 !== void 0 ? _a6 : this.trailingMetadata }));
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      end(metadata) {
        if (metadata) {
          this.trailingMetadata = metadata;
        }
        return super.end();
      }
    };
    exports2.ServerDuplexStreamImpl = ServerDuplexStreamImpl;
  }
});

// node_modules/@grpc/grpc-js/build/src/server-credentials.js
var require_server_credentials = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/server-credentials.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ServerCredentials = void 0;
    exports2.createCertificateProviderServerCredentials = createCertificateProviderServerCredentials;
    exports2.createServerCredentialsWithInterceptors = createServerCredentialsWithInterceptors;
    var tls_helpers_1 = require_tls_helpers();
    var ServerCredentials = class {
      static {
        __name(this, "ServerCredentials");
      }
      constructor(serverConstructorOptions, contextOptions) {
        this.serverConstructorOptions = serverConstructorOptions;
        this.watchers = /* @__PURE__ */ new Set();
        this.latestContextOptions = null;
        this.latestContextOptions = contextOptions !== null && contextOptions !== void 0 ? contextOptions : null;
      }
      _addWatcher(watcher) {
        this.watchers.add(watcher);
      }
      _removeWatcher(watcher) {
        this.watchers.delete(watcher);
      }
      getWatcherCount() {
        return this.watchers.size;
      }
      updateSecureContextOptions(options2) {
        this.latestContextOptions = options2;
        for (const watcher of this.watchers) {
          watcher(this.latestContextOptions);
        }
      }
      _isSecure() {
        return this.serverConstructorOptions !== null;
      }
      _getSecureContextOptions() {
        return this.latestContextOptions;
      }
      _getConstructorOptions() {
        return this.serverConstructorOptions;
      }
      _getInterceptors() {
        return [];
      }
      static createInsecure() {
        return new InsecureServerCredentials();
      }
      static createSsl(rootCerts, keyCertPairs, checkClientCertificate = false) {
        var _a6;
        if (rootCerts !== null && !Buffer.isBuffer(rootCerts)) {
          throw new TypeError("rootCerts must be null or a Buffer");
        }
        if (!Array.isArray(keyCertPairs)) {
          throw new TypeError("keyCertPairs must be an array");
        }
        if (typeof checkClientCertificate !== "boolean") {
          throw new TypeError("checkClientCertificate must be a boolean");
        }
        const cert = [];
        const key = [];
        for (let i = 0; i < keyCertPairs.length; i++) {
          const pair = keyCertPairs[i];
          if (pair === null || typeof pair !== "object") {
            throw new TypeError(`keyCertPair[${i}] must be an object`);
          }
          if (!Buffer.isBuffer(pair.private_key)) {
            throw new TypeError(`keyCertPair[${i}].private_key must be a Buffer`);
          }
          if (!Buffer.isBuffer(pair.cert_chain)) {
            throw new TypeError(`keyCertPair[${i}].cert_chain must be a Buffer`);
          }
          cert.push(pair.cert_chain);
          key.push(pair.private_key);
        }
        return new SecureServerCredentials({
          requestCert: checkClientCertificate,
          ciphers: tls_helpers_1.CIPHER_SUITES
        }, {
          ca: (_a6 = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a6 !== void 0 ? _a6 : void 0,
          cert,
          key
        });
      }
    };
    exports2.ServerCredentials = ServerCredentials;
    var InsecureServerCredentials = class _InsecureServerCredentials extends ServerCredentials {
      static {
        __name(this, "InsecureServerCredentials");
      }
      constructor() {
        super(null);
      }
      _getSettings() {
        return null;
      }
      _equals(other2) {
        return other2 instanceof _InsecureServerCredentials;
      }
    };
    var SecureServerCredentials = class _SecureServerCredentials extends ServerCredentials {
      static {
        __name(this, "SecureServerCredentials");
      }
      constructor(constructorOptions, contextOptions) {
        super(constructorOptions, contextOptions);
        this.options = Object.assign(Object.assign({}, constructorOptions), contextOptions);
      }
      /**
       * Checks equality by checking the options that are actually set by
       * createSsl.
       * @param other
       * @returns
       */
      _equals(other2) {
        if (this === other2) {
          return true;
        }
        if (!(other2 instanceof _SecureServerCredentials)) {
          return false;
        }
        if (Buffer.isBuffer(this.options.ca) && Buffer.isBuffer(other2.options.ca)) {
          if (!this.options.ca.equals(other2.options.ca)) {
            return false;
          }
        } else {
          if (this.options.ca !== other2.options.ca) {
            return false;
          }
        }
        if (Array.isArray(this.options.cert) && Array.isArray(other2.options.cert)) {
          if (this.options.cert.length !== other2.options.cert.length) {
            return false;
          }
          for (let i = 0; i < this.options.cert.length; i++) {
            const thisCert = this.options.cert[i];
            const otherCert = other2.options.cert[i];
            if (Buffer.isBuffer(thisCert) && Buffer.isBuffer(otherCert)) {
              if (!thisCert.equals(otherCert)) {
                return false;
              }
            } else {
              if (thisCert !== otherCert) {
                return false;
              }
            }
          }
        } else {
          if (this.options.cert !== other2.options.cert) {
            return false;
          }
        }
        if (Array.isArray(this.options.key) && Array.isArray(other2.options.key)) {
          if (this.options.key.length !== other2.options.key.length) {
            return false;
          }
          for (let i = 0; i < this.options.key.length; i++) {
            const thisKey = this.options.key[i];
            const otherKey = other2.options.key[i];
            if (Buffer.isBuffer(thisKey) && Buffer.isBuffer(otherKey)) {
              if (!thisKey.equals(otherKey)) {
                return false;
              }
            } else {
              if (thisKey !== otherKey) {
                return false;
              }
            }
          }
        } else {
          if (this.options.key !== other2.options.key) {
            return false;
          }
        }
        if (this.options.requestCert !== other2.options.requestCert) {
          return false;
        }
        return true;
      }
    };
    var CertificateProviderServerCredentials = class _CertificateProviderServerCredentials extends ServerCredentials {
      static {
        __name(this, "CertificateProviderServerCredentials");
      }
      constructor(identityCertificateProvider, caCertificateProvider, requireClientCertificate) {
        super({
          requestCert: caCertificateProvider !== null,
          rejectUnauthorized: requireClientCertificate,
          ciphers: tls_helpers_1.CIPHER_SUITES
        });
        this.identityCertificateProvider = identityCertificateProvider;
        this.caCertificateProvider = caCertificateProvider;
        this.requireClientCertificate = requireClientCertificate;
        this.latestCaUpdate = null;
        this.latestIdentityUpdate = null;
        this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this);
        this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this);
      }
      _addWatcher(watcher) {
        var _a6;
        if (this.getWatcherCount() === 0) {
          (_a6 = this.caCertificateProvider) === null || _a6 === void 0 ? void 0 : _a6.addCaCertificateListener(this.caCertificateUpdateListener);
          this.identityCertificateProvider.addIdentityCertificateListener(this.identityCertificateUpdateListener);
        }
        super._addWatcher(watcher);
      }
      _removeWatcher(watcher) {
        var _a6;
        super._removeWatcher(watcher);
        if (this.getWatcherCount() === 0) {
          (_a6 = this.caCertificateProvider) === null || _a6 === void 0 ? void 0 : _a6.removeCaCertificateListener(this.caCertificateUpdateListener);
          this.identityCertificateProvider.removeIdentityCertificateListener(this.identityCertificateUpdateListener);
        }
      }
      _equals(other2) {
        if (this === other2) {
          return true;
        }
        if (!(other2 instanceof _CertificateProviderServerCredentials)) {
          return false;
        }
        return this.caCertificateProvider === other2.caCertificateProvider && this.identityCertificateProvider === other2.identityCertificateProvider && this.requireClientCertificate === other2.requireClientCertificate;
      }
      calculateSecureContextOptions() {
        var _a6;
        if (this.latestIdentityUpdate === null) {
          return null;
        }
        if (this.caCertificateProvider !== null && this.latestCaUpdate === null) {
          return null;
        }
        return {
          ca: (_a6 = this.latestCaUpdate) === null || _a6 === void 0 ? void 0 : _a6.caCertificate,
          cert: [this.latestIdentityUpdate.certificate],
          key: [this.latestIdentityUpdate.privateKey]
        };
      }
      finalizeUpdate() {
        const secureContextOptions = this.calculateSecureContextOptions();
        this.updateSecureContextOptions(secureContextOptions);
      }
      handleCaCertificateUpdate(update2) {
        this.latestCaUpdate = update2;
        this.finalizeUpdate();
      }
      handleIdentityCertitificateUpdate(update2) {
        this.latestIdentityUpdate = update2;
        this.finalizeUpdate();
      }
    };
    function createCertificateProviderServerCredentials(caCertificateProvider, identityCertificateProvider, requireClientCertificate) {
      return new CertificateProviderServerCredentials(caCertificateProvider, identityCertificateProvider, requireClientCertificate);
    }
    __name(createCertificateProviderServerCredentials, "createCertificateProviderServerCredentials");
    var InterceptorServerCredentials = class _InterceptorServerCredentials extends ServerCredentials {
      static {
        __name(this, "InterceptorServerCredentials");
      }
      constructor(childCredentials, interceptors) {
        super({});
        this.childCredentials = childCredentials;
        this.interceptors = interceptors;
      }
      _isSecure() {
        return this.childCredentials._isSecure();
      }
      _equals(other2) {
        if (!(other2 instanceof _InterceptorServerCredentials)) {
          return false;
        }
        if (!this.childCredentials._equals(other2.childCredentials)) {
          return false;
        }
        if (this.interceptors.length !== other2.interceptors.length) {
          return false;
        }
        for (let i = 0; i < this.interceptors.length; i++) {
          if (this.interceptors[i] !== other2.interceptors[i]) {
            return false;
          }
        }
        return true;
      }
      _getInterceptors() {
        return this.interceptors;
      }
      _addWatcher(watcher) {
        this.childCredentials._addWatcher(watcher);
      }
      _removeWatcher(watcher) {
        this.childCredentials._removeWatcher(watcher);
      }
      _getConstructorOptions() {
        return this.childCredentials._getConstructorOptions();
      }
      _getSecureContextOptions() {
        return this.childCredentials._getSecureContextOptions();
      }
    };
    function createServerCredentialsWithInterceptors(credentials, interceptors) {
      return new InterceptorServerCredentials(credentials, interceptors);
    }
    __name(createServerCredentialsWithInterceptors, "createServerCredentialsWithInterceptors");
  }
});

// node_modules/@grpc/grpc-js/build/src/server-interceptors.js
var require_server_interceptors = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/server-interceptors.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BaseServerInterceptingCall = exports2.ServerInterceptingCall = exports2.ResponderBuilder = exports2.ServerListenerBuilder = void 0;
    exports2.isInterceptingServerListener = isInterceptingServerListener;
    exports2.getServerInterceptingCall = getServerInterceptingCall;
    var metadata_1 = require_metadata3();
    var constants_1 = require_constants9();
    var http22 = __require("http2");
    var error_1 = require_error();
    var zlib2 = __require("zlib");
    var stream_decoder_1 = require_stream_decoder();
    var logging = require_logging();
    var TRACER_NAME = "server_call";
    function trace2(text) {
      logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    var ServerListenerBuilder = class {
      static {
        __name(this, "ServerListenerBuilder");
      }
      constructor() {
        this.metadata = void 0;
        this.message = void 0;
        this.halfClose = void 0;
        this.cancel = void 0;
      }
      withOnReceiveMetadata(onReceiveMetadata) {
        this.metadata = onReceiveMetadata;
        return this;
      }
      withOnReceiveMessage(onReceiveMessage) {
        this.message = onReceiveMessage;
        return this;
      }
      withOnReceiveHalfClose(onReceiveHalfClose) {
        this.halfClose = onReceiveHalfClose;
        return this;
      }
      withOnCancel(onCancel) {
        this.cancel = onCancel;
        return this;
      }
      build() {
        return {
          onReceiveMetadata: this.metadata,
          onReceiveMessage: this.message,
          onReceiveHalfClose: this.halfClose,
          onCancel: this.cancel
        };
      }
    };
    exports2.ServerListenerBuilder = ServerListenerBuilder;
    function isInterceptingServerListener(listener) {
      return listener.onReceiveMetadata !== void 0 && listener.onReceiveMetadata.length === 1;
    }
    __name(isInterceptingServerListener, "isInterceptingServerListener");
    var InterceptingServerListenerImpl = class {
      static {
        __name(this, "InterceptingServerListenerImpl");
      }
      constructor(listener, nextListener) {
        this.listener = listener;
        this.nextListener = nextListener;
        this.cancelled = false;
        this.processingMetadata = false;
        this.hasPendingMessage = false;
        this.pendingMessage = null;
        this.processingMessage = false;
        this.hasPendingHalfClose = false;
      }
      processPendingMessage() {
        if (this.hasPendingMessage) {
          this.nextListener.onReceiveMessage(this.pendingMessage);
          this.pendingMessage = null;
          this.hasPendingMessage = false;
        }
      }
      processPendingHalfClose() {
        if (this.hasPendingHalfClose) {
          this.nextListener.onReceiveHalfClose();
          this.hasPendingHalfClose = false;
        }
      }
      onReceiveMetadata(metadata) {
        if (this.cancelled) {
          return;
        }
        this.processingMetadata = true;
        this.listener.onReceiveMetadata(metadata, (interceptedMetadata) => {
          this.processingMetadata = false;
          if (this.cancelled) {
            return;
          }
          this.nextListener.onReceiveMetadata(interceptedMetadata);
          this.processPendingMessage();
          this.processPendingHalfClose();
        });
      }
      onReceiveMessage(message) {
        if (this.cancelled) {
          return;
        }
        this.processingMessage = true;
        this.listener.onReceiveMessage(message, (msg) => {
          this.processingMessage = false;
          if (this.cancelled) {
            return;
          }
          if (this.processingMetadata) {
            this.pendingMessage = msg;
            this.hasPendingMessage = true;
          } else {
            this.nextListener.onReceiveMessage(msg);
            this.processPendingHalfClose();
          }
        });
      }
      onReceiveHalfClose() {
        if (this.cancelled) {
          return;
        }
        this.listener.onReceiveHalfClose(() => {
          if (this.cancelled) {
            return;
          }
          if (this.processingMetadata || this.processingMessage) {
            this.hasPendingHalfClose = true;
          } else {
            this.nextListener.onReceiveHalfClose();
          }
        });
      }
      onCancel() {
        this.cancelled = true;
        this.listener.onCancel();
        this.nextListener.onCancel();
      }
    };
    var ResponderBuilder = class {
      static {
        __name(this, "ResponderBuilder");
      }
      constructor() {
        this.start = void 0;
        this.metadata = void 0;
        this.message = void 0;
        this.status = void 0;
      }
      withStart(start) {
        this.start = start;
        return this;
      }
      withSendMetadata(sendMetadata) {
        this.metadata = sendMetadata;
        return this;
      }
      withSendMessage(sendMessage) {
        this.message = sendMessage;
        return this;
      }
      withSendStatus(sendStatus) {
        this.status = sendStatus;
        return this;
      }
      build() {
        return {
          start: this.start,
          sendMetadata: this.metadata,
          sendMessage: this.message,
          sendStatus: this.status
        };
      }
    };
    exports2.ResponderBuilder = ResponderBuilder;
    var defaultServerListener = {
      onReceiveMetadata: /* @__PURE__ */ __name((metadata, next) => {
        next(metadata);
      }, "onReceiveMetadata"),
      onReceiveMessage: /* @__PURE__ */ __name((message, next) => {
        next(message);
      }, "onReceiveMessage"),
      onReceiveHalfClose: /* @__PURE__ */ __name((next) => {
        next();
      }, "onReceiveHalfClose"),
      onCancel: /* @__PURE__ */ __name(() => {
      }, "onCancel")
    };
    var defaultResponder = {
      start: /* @__PURE__ */ __name((next) => {
        next();
      }, "start"),
      sendMetadata: /* @__PURE__ */ __name((metadata, next) => {
        next(metadata);
      }, "sendMetadata"),
      sendMessage: /* @__PURE__ */ __name((message, next) => {
        next(message);
      }, "sendMessage"),
      sendStatus: /* @__PURE__ */ __name((status, next) => {
        next(status);
      }, "sendStatus")
    };
    var ServerInterceptingCall = class {
      static {
        __name(this, "ServerInterceptingCall");
      }
      constructor(nextCall, responder) {
        var _a6, _b2, _c2, _d;
        this.nextCall = nextCall;
        this.processingMetadata = false;
        this.sentMetadata = false;
        this.processingMessage = false;
        this.pendingMessage = null;
        this.pendingMessageCallback = null;
        this.pendingStatus = null;
        this.responder = {
          start: (_a6 = responder === null || responder === void 0 ? void 0 : responder.start) !== null && _a6 !== void 0 ? _a6 : defaultResponder.start,
          sendMetadata: (_b2 = responder === null || responder === void 0 ? void 0 : responder.sendMetadata) !== null && _b2 !== void 0 ? _b2 : defaultResponder.sendMetadata,
          sendMessage: (_c2 = responder === null || responder === void 0 ? void 0 : responder.sendMessage) !== null && _c2 !== void 0 ? _c2 : defaultResponder.sendMessage,
          sendStatus: (_d = responder === null || responder === void 0 ? void 0 : responder.sendStatus) !== null && _d !== void 0 ? _d : defaultResponder.sendStatus
        };
      }
      processPendingMessage() {
        if (this.pendingMessageCallback) {
          this.nextCall.sendMessage(this.pendingMessage, this.pendingMessageCallback);
          this.pendingMessage = null;
          this.pendingMessageCallback = null;
        }
      }
      processPendingStatus() {
        if (this.pendingStatus) {
          this.nextCall.sendStatus(this.pendingStatus);
          this.pendingStatus = null;
        }
      }
      start(listener) {
        this.responder.start((interceptedListener) => {
          var _a6, _b2, _c2, _d;
          const fullInterceptedListener = {
            onReceiveMetadata: (_a6 = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMetadata) !== null && _a6 !== void 0 ? _a6 : defaultServerListener.onReceiveMetadata,
            onReceiveMessage: (_b2 = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMessage) !== null && _b2 !== void 0 ? _b2 : defaultServerListener.onReceiveMessage,
            onReceiveHalfClose: (_c2 = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveHalfClose) !== null && _c2 !== void 0 ? _c2 : defaultServerListener.onReceiveHalfClose,
            onCancel: (_d = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onCancel) !== null && _d !== void 0 ? _d : defaultServerListener.onCancel
          };
          const finalInterceptingListener = new InterceptingServerListenerImpl(fullInterceptedListener, listener);
          this.nextCall.start(finalInterceptingListener);
        });
      }
      sendMetadata(metadata) {
        this.processingMetadata = true;
        this.sentMetadata = true;
        this.responder.sendMetadata(metadata, (interceptedMetadata) => {
          this.processingMetadata = false;
          this.nextCall.sendMetadata(interceptedMetadata);
          this.processPendingMessage();
          this.processPendingStatus();
        });
      }
      sendMessage(message, callback) {
        this.processingMessage = true;
        if (!this.sentMetadata) {
          this.sendMetadata(new metadata_1.Metadata());
        }
        this.responder.sendMessage(message, (interceptedMessage) => {
          this.processingMessage = false;
          if (this.processingMetadata) {
            this.pendingMessage = interceptedMessage;
            this.pendingMessageCallback = callback;
          } else {
            this.nextCall.sendMessage(interceptedMessage, callback);
          }
        });
      }
      sendStatus(status) {
        this.responder.sendStatus(status, (interceptedStatus) => {
          if (this.processingMetadata || this.processingMessage) {
            this.pendingStatus = interceptedStatus;
          } else {
            this.nextCall.sendStatus(interceptedStatus);
          }
        });
      }
      startRead() {
        this.nextCall.startRead();
      }
      getPeer() {
        return this.nextCall.getPeer();
      }
      getDeadline() {
        return this.nextCall.getDeadline();
      }
      getHost() {
        return this.nextCall.getHost();
      }
    };
    exports2.ServerInterceptingCall = ServerInterceptingCall;
    var GRPC_ACCEPT_ENCODING_HEADER = "grpc-accept-encoding";
    var GRPC_ENCODING_HEADER = "grpc-encoding";
    var GRPC_MESSAGE_HEADER = "grpc-message";
    var GRPC_STATUS_HEADER = "grpc-status";
    var GRPC_TIMEOUT_HEADER = "grpc-timeout";
    var DEADLINE_REGEX = /(\d{1,8})\s*([HMSmun])/;
    var deadlineUnitsToMs = {
      H: 36e5,
      M: 6e4,
      S: 1e3,
      m: 1,
      u: 1e-3,
      n: 1e-6
    };
    var defaultCompressionHeaders = {
      // TODO(cjihrig): Remove these encoding headers from the default response
      // once compression is integrated.
      [GRPC_ACCEPT_ENCODING_HEADER]: "identity,deflate,gzip",
      [GRPC_ENCODING_HEADER]: "identity"
    };
    var defaultResponseHeaders = {
      [http22.constants.HTTP2_HEADER_STATUS]: http22.constants.HTTP_STATUS_OK,
      [http22.constants.HTTP2_HEADER_CONTENT_TYPE]: "application/grpc+proto"
    };
    var defaultResponseOptions = {
      waitForTrailers: true
    };
    var BaseServerInterceptingCall = class {
      static {
        __name(this, "BaseServerInterceptingCall");
      }
      constructor(stream2, headers, callEventTracker, handler, options2) {
        var _a6;
        this.stream = stream2;
        this.callEventTracker = callEventTracker;
        this.handler = handler;
        this.listener = null;
        this.deadlineTimer = null;
        this.deadline = Infinity;
        this.maxSendMessageSize = constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH;
        this.maxReceiveMessageSize = constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH;
        this.cancelled = false;
        this.metadataSent = false;
        this.wantTrailers = false;
        this.cancelNotified = false;
        this.incomingEncoding = "identity";
        this.readQueue = [];
        this.isReadPending = false;
        this.receivedHalfClose = false;
        this.streamEnded = false;
        this.stream.once("error", (err) => {
        });
        this.stream.once("close", () => {
          var _a7;
          trace2("Request to method " + ((_a7 = this.handler) === null || _a7 === void 0 ? void 0 : _a7.path) + " stream closed with rstCode " + this.stream.rstCode);
          if (this.callEventTracker && !this.streamEnded) {
            this.streamEnded = true;
            this.callEventTracker.onStreamEnd(false);
            this.callEventTracker.onCallEnd({
              code: constants_1.Status.CANCELLED,
              details: "Stream closed before sending status",
              metadata: null
            });
          }
          this.notifyOnCancel();
        });
        this.stream.on("data", (data) => {
          this.handleDataFrame(data);
        });
        this.stream.pause();
        this.stream.on("end", () => {
          this.handleEndEvent();
        });
        if ("grpc.max_send_message_length" in options2) {
          this.maxSendMessageSize = options2["grpc.max_send_message_length"];
        }
        if ("grpc.max_receive_message_length" in options2) {
          this.maxReceiveMessageSize = options2["grpc.max_receive_message_length"];
        }
        this.host = (_a6 = headers[":authority"]) !== null && _a6 !== void 0 ? _a6 : headers.host;
        this.decoder = new stream_decoder_1.StreamDecoder(this.maxReceiveMessageSize);
        const metadata = metadata_1.Metadata.fromHttp2Headers(headers);
        if (logging.isTracerEnabled(TRACER_NAME)) {
          trace2("Request to " + this.handler.path + " received headers " + JSON.stringify(metadata.toJSON()));
        }
        const timeoutHeader = metadata.get(GRPC_TIMEOUT_HEADER);
        if (timeoutHeader.length > 0) {
          this.handleTimeoutHeader(timeoutHeader[0]);
        }
        const encodingHeader = metadata.get(GRPC_ENCODING_HEADER);
        if (encodingHeader.length > 0) {
          this.incomingEncoding = encodingHeader[0];
        }
        metadata.remove(GRPC_TIMEOUT_HEADER);
        metadata.remove(GRPC_ENCODING_HEADER);
        metadata.remove(GRPC_ACCEPT_ENCODING_HEADER);
        metadata.remove(http22.constants.HTTP2_HEADER_ACCEPT_ENCODING);
        metadata.remove(http22.constants.HTTP2_HEADER_TE);
        metadata.remove(http22.constants.HTTP2_HEADER_CONTENT_TYPE);
        this.metadata = metadata;
      }
      handleTimeoutHeader(timeoutHeader) {
        const match2 = timeoutHeader.toString().match(DEADLINE_REGEX);
        if (match2 === null) {
          const status = {
            code: constants_1.Status.INTERNAL,
            details: `Invalid ${GRPC_TIMEOUT_HEADER} value "${timeoutHeader}"`,
            metadata: null
          };
          process.nextTick(() => {
            this.sendStatus(status);
          });
          return;
        }
        const timeout2 = +match2[1] * deadlineUnitsToMs[match2[2]] | 0;
        const now = /* @__PURE__ */ new Date();
        this.deadline = now.setMilliseconds(now.getMilliseconds() + timeout2);
        this.deadlineTimer = setTimeout(() => {
          const status = {
            code: constants_1.Status.DEADLINE_EXCEEDED,
            details: "Deadline exceeded",
            metadata: null
          };
          this.sendStatus(status);
        }, timeout2);
      }
      checkCancelled() {
        if (!this.cancelled && (this.stream.destroyed || this.stream.closed)) {
          this.notifyOnCancel();
          this.cancelled = true;
        }
        return this.cancelled;
      }
      notifyOnCancel() {
        if (this.cancelNotified) {
          return;
        }
        this.cancelNotified = true;
        this.cancelled = true;
        process.nextTick(() => {
          var _a6;
          (_a6 = this.listener) === null || _a6 === void 0 ? void 0 : _a6.onCancel();
        });
        if (this.deadlineTimer) {
          clearTimeout(this.deadlineTimer);
        }
        this.stream.resume();
      }
      /**
       * A server handler can start sending messages without explicitly sending
       * metadata. In that case, we need to send headers before sending any
       * messages. This function does that if necessary.
       */
      maybeSendMetadata() {
        if (!this.metadataSent) {
          this.sendMetadata(new metadata_1.Metadata());
        }
      }
      /**
       * Serialize a message to a length-delimited byte string.
       * @param value
       * @returns
       */
      serializeMessage(value) {
        const messageBuffer = this.handler.serialize(value);
        const byteLength = messageBuffer.byteLength;
        const output = Buffer.allocUnsafe(byteLength + 5);
        output.writeUInt8(0, 0);
        output.writeUInt32BE(byteLength, 1);
        messageBuffer.copy(output, 5);
        return output;
      }
      decompressMessage(message, encoding) {
        const messageContents = message.subarray(5);
        if (encoding === "identity") {
          return messageContents;
        } else if (encoding === "deflate" || encoding === "gzip") {
          let decompresser;
          if (encoding === "deflate") {
            decompresser = zlib2.createInflate();
          } else {
            decompresser = zlib2.createGunzip();
          }
          return new Promise((resolve24, reject) => {
            let totalLength = 0;
            const messageParts = [];
            decompresser.on("data", (chunk) => {
              messageParts.push(chunk);
              totalLength += chunk.byteLength;
              if (this.maxReceiveMessageSize !== -1 && totalLength > this.maxReceiveMessageSize) {
                decompresser.destroy();
                reject({
                  code: constants_1.Status.RESOURCE_EXHAUSTED,
                  details: `Received message that decompresses to a size larger than ${this.maxReceiveMessageSize}`
                });
              }
            });
            decompresser.on("end", () => {
              resolve24(Buffer.concat(messageParts));
            });
            decompresser.write(messageContents);
            decompresser.end();
          });
        } else {
          return Promise.reject({
            code: constants_1.Status.UNIMPLEMENTED,
            details: `Received message compressed with unsupported encoding "${encoding}"`
          });
        }
      }
      async decompressAndMaybePush(queueEntry) {
        if (queueEntry.type !== "COMPRESSED") {
          throw new Error(`Invalid queue entry type: ${queueEntry.type}`);
        }
        const compressed = queueEntry.compressedMessage.readUInt8(0) === 1;
        const compressedMessageEncoding = compressed ? this.incomingEncoding : "identity";
        let decompressedMessage;
        try {
          decompressedMessage = await this.decompressMessage(queueEntry.compressedMessage, compressedMessageEncoding);
        } catch (err) {
          this.sendStatus(err);
          return;
        }
        try {
          queueEntry.parsedMessage = this.handler.deserialize(decompressedMessage);
        } catch (err) {
          this.sendStatus({
            code: constants_1.Status.INTERNAL,
            details: `Error deserializing request: ${err.message}`
          });
          return;
        }
        queueEntry.type = "READABLE";
        this.maybePushNextMessage();
      }
      maybePushNextMessage() {
        if (this.listener && this.isReadPending && this.readQueue.length > 0 && this.readQueue[0].type !== "COMPRESSED") {
          this.isReadPending = false;
          const nextQueueEntry = this.readQueue.shift();
          if (nextQueueEntry.type === "READABLE") {
            this.listener.onReceiveMessage(nextQueueEntry.parsedMessage);
          } else {
            this.listener.onReceiveHalfClose();
          }
        }
      }
      handleDataFrame(data) {
        var _a6;
        if (this.checkCancelled()) {
          return;
        }
        trace2("Request to " + this.handler.path + " received data frame of size " + data.length);
        let rawMessages;
        try {
          rawMessages = this.decoder.write(data);
        } catch (e2) {
          this.sendStatus({ code: constants_1.Status.RESOURCE_EXHAUSTED, details: e2.message });
          return;
        }
        for (const messageBytes of rawMessages) {
          this.stream.pause();
          const queueEntry = {
            type: "COMPRESSED",
            compressedMessage: messageBytes,
            parsedMessage: null
          };
          this.readQueue.push(queueEntry);
          this.decompressAndMaybePush(queueEntry);
          (_a6 = this.callEventTracker) === null || _a6 === void 0 ? void 0 : _a6.addMessageReceived();
        }
      }
      handleEndEvent() {
        this.readQueue.push({
          type: "HALF_CLOSE",
          compressedMessage: null,
          parsedMessage: null
        });
        this.receivedHalfClose = true;
        this.maybePushNextMessage();
      }
      start(listener) {
        trace2("Request to " + this.handler.path + " start called");
        if (this.checkCancelled()) {
          return;
        }
        this.listener = listener;
        listener.onReceiveMetadata(this.metadata);
      }
      sendMetadata(metadata) {
        if (this.checkCancelled()) {
          return;
        }
        if (this.metadataSent) {
          return;
        }
        this.metadataSent = true;
        const custom2 = metadata ? metadata.toHttp2Headers() : null;
        const headers = Object.assign(Object.assign(Object.assign({}, defaultResponseHeaders), defaultCompressionHeaders), custom2);
        this.stream.respond(headers, defaultResponseOptions);
      }
      sendMessage(message, callback) {
        if (this.checkCancelled()) {
          return;
        }
        let response;
        try {
          response = this.serializeMessage(message);
        } catch (e2) {
          this.sendStatus({
            code: constants_1.Status.INTERNAL,
            details: `Error serializing response: ${(0, error_1.getErrorMessage)(e2)}`,
            metadata: null
          });
          return;
        }
        if (this.maxSendMessageSize !== -1 && response.length - 5 > this.maxSendMessageSize) {
          this.sendStatus({
            code: constants_1.Status.RESOURCE_EXHAUSTED,
            details: `Sent message larger than max (${response.length} vs. ${this.maxSendMessageSize})`,
            metadata: null
          });
          return;
        }
        this.maybeSendMetadata();
        trace2("Request to " + this.handler.path + " sent data frame of size " + response.length);
        this.stream.write(response, (error) => {
          var _a6;
          if (error) {
            this.sendStatus({
              code: constants_1.Status.INTERNAL,
              details: `Error writing message: ${(0, error_1.getErrorMessage)(error)}`,
              metadata: null
            });
            return;
          }
          (_a6 = this.callEventTracker) === null || _a6 === void 0 ? void 0 : _a6.addMessageSent();
          callback();
        });
      }
      sendStatus(status) {
        var _a6, _b2;
        if (this.checkCancelled()) {
          return;
        }
        trace2("Request to method " + ((_a6 = this.handler) === null || _a6 === void 0 ? void 0 : _a6.path) + " ended with status code: " + constants_1.Status[status.code] + " details: " + status.details);
        if (this.metadataSent) {
          if (!this.wantTrailers) {
            this.wantTrailers = true;
            this.stream.once("wantTrailers", () => {
              var _a7;
              if (this.callEventTracker && !this.streamEnded) {
                this.streamEnded = true;
                this.callEventTracker.onStreamEnd(true);
                this.callEventTracker.onCallEnd(status);
              }
              const trailersToSend = Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, (_a7 = status.metadata) === null || _a7 === void 0 ? void 0 : _a7.toHttp2Headers());
              this.stream.sendTrailers(trailersToSend);
              this.notifyOnCancel();
            });
            this.stream.end();
          } else {
            this.notifyOnCancel();
          }
        } else {
          if (this.callEventTracker && !this.streamEnded) {
            this.streamEnded = true;
            this.callEventTracker.onStreamEnd(true);
            this.callEventTracker.onCallEnd(status);
          }
          const trailersToSend = Object.assign(Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, defaultResponseHeaders), (_b2 = status.metadata) === null || _b2 === void 0 ? void 0 : _b2.toHttp2Headers());
          this.stream.respond(trailersToSend, { endStream: true });
          this.notifyOnCancel();
        }
      }
      startRead() {
        trace2("Request to " + this.handler.path + " startRead called");
        if (this.checkCancelled()) {
          return;
        }
        this.isReadPending = true;
        if (this.readQueue.length === 0) {
          if (!this.receivedHalfClose) {
            this.stream.resume();
          }
        } else {
          this.maybePushNextMessage();
        }
      }
      getPeer() {
        var _a6;
        const socket = (_a6 = this.stream.session) === null || _a6 === void 0 ? void 0 : _a6.socket;
        if (socket === null || socket === void 0 ? void 0 : socket.remoteAddress) {
          if (socket.remotePort) {
            return `${socket.remoteAddress}:${socket.remotePort}`;
          } else {
            return socket.remoteAddress;
          }
        } else {
          return "unknown";
        }
      }
      getDeadline() {
        return this.deadline;
      }
      getHost() {
        return this.host;
      }
    };
    exports2.BaseServerInterceptingCall = BaseServerInterceptingCall;
    function getServerInterceptingCall(interceptors, stream2, headers, callEventTracker, handler, options2) {
      const methodDefinition = {
        path: handler.path,
        requestStream: handler.type === "clientStream" || handler.type === "bidi",
        responseStream: handler.type === "serverStream" || handler.type === "bidi",
        requestDeserialize: handler.deserialize,
        responseSerialize: handler.serialize
      };
      const baseCall = new BaseServerInterceptingCall(stream2, headers, callEventTracker, handler, options2);
      return interceptors.reduce((call, interceptor) => {
        return interceptor(methodDefinition, call);
      }, baseCall);
    }
    __name(getServerInterceptingCall, "getServerInterceptingCall");
  }
});

// node_modules/@grpc/grpc-js/build/src/server.js
var require_server = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/server.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __runInitializers = exports2 && exports2.__runInitializers || function(thisArg, initializers, value) {
      var useValue = arguments.length > 2;
      for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
      }
      return useValue ? value : void 0;
    };
    var __esDecorate = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      __name(accept, "accept");
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor2 = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context2 = {};
        for (var p in contextIn) context2[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context2.access[p] = contextIn.access[p];
        context2.addInitializer = function(f) {
          if (done) throw new TypeError("Cannot add initializers after decoration has completed");
          extraInitializers.push(accept(f || null));
        };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor2.get, set: descriptor2.set } : descriptor2[key], context2);
        if (kind === "accessor") {
          if (result === void 0) continue;
          if (result === null || typeof result !== "object") throw new TypeError("Object expected");
          if (_ = accept(result.get)) descriptor2.get = _;
          if (_ = accept(result.set)) descriptor2.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor2[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor2);
      done = true;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Server = void 0;
    var http22 = __require("http2");
    var util4 = __require("util");
    var constants_1 = require_constants9();
    var server_call_1 = require_server_call();
    var server_credentials_1 = require_server_credentials();
    var resolver_1 = require_resolver();
    var logging = require_logging();
    var subchannel_address_1 = require_subchannel_address();
    var uri_parser_1 = require_uri_parser();
    var channelz_1 = require_channelz();
    var server_interceptors_1 = require_server_interceptors();
    var UNLIMITED_CONNECTION_AGE_MS = ~(1 << 31);
    var KEEPALIVE_MAX_TIME_MS = ~(1 << 31);
    var KEEPALIVE_TIMEOUT_MS = 2e4;
    var MAX_CONNECTION_IDLE_MS = ~(1 << 31);
    var { HTTP2_HEADER_PATH } = http22.constants;
    var TRACER_NAME = "server";
    var kMaxAge = Buffer.from("max_age");
    function serverCallTrace(text) {
      logging.trace(constants_1.LogVerbosity.DEBUG, "server_call", text);
    }
    __name(serverCallTrace, "serverCallTrace");
    function noop6() {
    }
    __name(noop6, "noop");
    function deprecate(message) {
      return function(target, context2) {
        return util4.deprecate(target, message);
      };
    }
    __name(deprecate, "deprecate");
    function getUnimplementedStatusResponse(methodName) {
      return {
        code: constants_1.Status.UNIMPLEMENTED,
        details: `The server does not implement the method ${methodName}`
      };
    }
    __name(getUnimplementedStatusResponse, "getUnimplementedStatusResponse");
    function getDefaultHandler(handlerType, methodName) {
      const unimplementedStatusResponse = getUnimplementedStatusResponse(methodName);
      switch (handlerType) {
        case "unary":
          return (call, callback) => {
            callback(unimplementedStatusResponse, null);
          };
        case "clientStream":
          return (call, callback) => {
            callback(unimplementedStatusResponse, null);
          };
        case "serverStream":
          return (call) => {
            call.emit("error", unimplementedStatusResponse);
          };
        case "bidi":
          return (call) => {
            call.emit("error", unimplementedStatusResponse);
          };
        default:
          throw new Error(`Invalid handlerType ${handlerType}`);
      }
    }
    __name(getDefaultHandler, "getDefaultHandler");
    var Server = (() => {
      var _a6;
      let _instanceExtraInitializers = [];
      let _start_decorators;
      return _a6 = class Server {
        static {
          __name(this, "Server");
        }
        constructor(options2) {
          var _b2, _c2, _d, _e, _f, _g;
          this.boundPorts = (__runInitializers(this, _instanceExtraInitializers), /* @__PURE__ */ new Map());
          this.http2Servers = /* @__PURE__ */ new Map();
          this.sessionIdleTimeouts = /* @__PURE__ */ new Map();
          this.handlers = /* @__PURE__ */ new Map();
          this.sessions = /* @__PURE__ */ new Map();
          this.started = false;
          this.shutdown = false;
          this.serverAddressString = "null";
          this.channelzEnabled = true;
          this.options = options2 !== null && options2 !== void 0 ? options2 : {};
          if (this.options["grpc.enable_channelz"] === 0) {
            this.channelzEnabled = false;
            this.channelzTrace = new channelz_1.ChannelzTraceStub();
            this.callTracker = new channelz_1.ChannelzCallTrackerStub();
            this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub();
            this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub();
          } else {
            this.channelzTrace = new channelz_1.ChannelzTrace();
            this.callTracker = new channelz_1.ChannelzCallTracker();
            this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTracker();
            this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTracker();
          }
          this.channelzRef = (0, channelz_1.registerChannelzServer)("server", () => this.getChannelzInfo(), this.channelzEnabled);
          this.channelzTrace.addTrace("CT_INFO", "Server created");
          this.maxConnectionAgeMs = (_b2 = this.options["grpc.max_connection_age_ms"]) !== null && _b2 !== void 0 ? _b2 : UNLIMITED_CONNECTION_AGE_MS;
          this.maxConnectionAgeGraceMs = (_c2 = this.options["grpc.max_connection_age_grace_ms"]) !== null && _c2 !== void 0 ? _c2 : UNLIMITED_CONNECTION_AGE_MS;
          this.keepaliveTimeMs = (_d = this.options["grpc.keepalive_time_ms"]) !== null && _d !== void 0 ? _d : KEEPALIVE_MAX_TIME_MS;
          this.keepaliveTimeoutMs = (_e = this.options["grpc.keepalive_timeout_ms"]) !== null && _e !== void 0 ? _e : KEEPALIVE_TIMEOUT_MS;
          this.sessionIdleTimeout = (_f = this.options["grpc.max_connection_idle_ms"]) !== null && _f !== void 0 ? _f : MAX_CONNECTION_IDLE_MS;
          this.commonServerOptions = {
            maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER
          };
          if ("grpc-node.max_session_memory" in this.options) {
            this.commonServerOptions.maxSessionMemory = this.options["grpc-node.max_session_memory"];
          } else {
            this.commonServerOptions.maxSessionMemory = Number.MAX_SAFE_INTEGER;
          }
          if ("grpc.max_concurrent_streams" in this.options) {
            this.commonServerOptions.settings = {
              maxConcurrentStreams: this.options["grpc.max_concurrent_streams"]
            };
          }
          this.interceptors = (_g = this.options.interceptors) !== null && _g !== void 0 ? _g : [];
          this.trace("Server constructed");
        }
        getChannelzInfo() {
          return {
            trace: this.channelzTrace,
            callTracker: this.callTracker,
            listenerChildren: this.listenerChildrenTracker.getChildLists(),
            sessionChildren: this.sessionChildrenTracker.getChildLists()
          };
        }
        getChannelzSessionInfo(session) {
          var _b2, _c2, _d;
          const sessionInfo = this.sessions.get(session);
          const sessionSocket = session.socket;
          const remoteAddress = sessionSocket.remoteAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) : null;
          const localAddress = sessionSocket.localAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) : null;
          let tlsInfo;
          if (session.encrypted) {
            const tlsSocket = sessionSocket;
            const cipherInfo = tlsSocket.getCipher();
            const certificate = tlsSocket.getCertificate();
            const peerCertificate = tlsSocket.getPeerCertificate();
            tlsInfo = {
              cipherSuiteStandardName: (_b2 = cipherInfo.standardName) !== null && _b2 !== void 0 ? _b2 : null,
              cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name,
              localCertificate: certificate && "raw" in certificate ? certificate.raw : null,
              remoteCertificate: peerCertificate && "raw" in peerCertificate ? peerCertificate.raw : null
            };
          } else {
            tlsInfo = null;
          }
          const socketInfo = {
            remoteAddress,
            localAddress,
            security: tlsInfo,
            remoteName: null,
            streamsStarted: sessionInfo.streamTracker.callsStarted,
            streamsSucceeded: sessionInfo.streamTracker.callsSucceeded,
            streamsFailed: sessionInfo.streamTracker.callsFailed,
            messagesSent: sessionInfo.messagesSent,
            messagesReceived: sessionInfo.messagesReceived,
            keepAlivesSent: sessionInfo.keepAlivesSent,
            lastLocalStreamCreatedTimestamp: null,
            lastRemoteStreamCreatedTimestamp: sessionInfo.streamTracker.lastCallStartedTimestamp,
            lastMessageSentTimestamp: sessionInfo.lastMessageSentTimestamp,
            lastMessageReceivedTimestamp: sessionInfo.lastMessageReceivedTimestamp,
            localFlowControlWindow: (_c2 = session.state.localWindowSize) !== null && _c2 !== void 0 ? _c2 : null,
            remoteFlowControlWindow: (_d = session.state.remoteWindowSize) !== null && _d !== void 0 ? _d : null
          };
          return socketInfo;
        }
        trace(text) {
          logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + text);
        }
        keepaliveTrace(text) {
          logging.trace(constants_1.LogVerbosity.DEBUG, "keepalive", "(" + this.channelzRef.id + ") " + text);
        }
        addProtoService() {
          throw new Error("Not implemented. Use addService() instead");
        }
        addService(service, implementation) {
          if (service === null || typeof service !== "object" || implementation === null || typeof implementation !== "object") {
            throw new Error("addService() requires two objects as arguments");
          }
          const serviceKeys = Object.keys(service);
          if (serviceKeys.length === 0) {
            throw new Error("Cannot add an empty service to a server");
          }
          serviceKeys.forEach((name3) => {
            const attrs = service[name3];
            let methodType;
            if (attrs.requestStream) {
              if (attrs.responseStream) {
                methodType = "bidi";
              } else {
                methodType = "clientStream";
              }
            } else {
              if (attrs.responseStream) {
                methodType = "serverStream";
              } else {
                methodType = "unary";
              }
            }
            let implFn = implementation[name3];
            let impl;
            if (implFn === void 0 && typeof attrs.originalName === "string") {
              implFn = implementation[attrs.originalName];
            }
            if (implFn !== void 0) {
              impl = implFn.bind(implementation);
            } else {
              impl = getDefaultHandler(methodType, name3);
            }
            const success = this.register(attrs.path, impl, attrs.responseSerialize, attrs.requestDeserialize, methodType);
            if (success === false) {
              throw new Error(`Method handler for ${attrs.path} already provided.`);
            }
          });
        }
        removeService(service) {
          if (service === null || typeof service !== "object") {
            throw new Error("removeService() requires object as argument");
          }
          const serviceKeys = Object.keys(service);
          serviceKeys.forEach((name3) => {
            const attrs = service[name3];
            this.unregister(attrs.path);
          });
        }
        bind(port, creds) {
          throw new Error("Not implemented. Use bindAsync() instead");
        }
        /**
         * This API is experimental, so API stability is not guaranteed across minor versions.
         * @param boundAddress
         * @returns
         */
        experimentalRegisterListenerToChannelz(boundAddress) {
          return (0, channelz_1.registerChannelzSocket)((0, subchannel_address_1.subchannelAddressToString)(boundAddress), () => {
            return {
              localAddress: boundAddress,
              remoteAddress: null,
              security: null,
              remoteName: null,
              streamsStarted: 0,
              streamsSucceeded: 0,
              streamsFailed: 0,
              messagesSent: 0,
              messagesReceived: 0,
              keepAlivesSent: 0,
              lastLocalStreamCreatedTimestamp: null,
              lastRemoteStreamCreatedTimestamp: null,
              lastMessageSentTimestamp: null,
              lastMessageReceivedTimestamp: null,
              localFlowControlWindow: null,
              remoteFlowControlWindow: null
            };
          }, this.channelzEnabled);
        }
        experimentalUnregisterListenerFromChannelz(channelzRef) {
          (0, channelz_1.unregisterChannelzRef)(channelzRef);
        }
        createHttp2Server(credentials) {
          let http2Server;
          if (credentials._isSecure()) {
            const constructorOptions = credentials._getConstructorOptions();
            const contextOptions = credentials._getSecureContextOptions();
            const secureServerOptions = Object.assign(Object.assign(Object.assign(Object.assign({}, this.commonServerOptions), constructorOptions), contextOptions), { enableTrace: this.options["grpc-node.tls_enable_trace"] === 1 });
            let areCredentialsValid = contextOptions !== null;
            this.trace("Initial credentials valid: " + areCredentialsValid);
            http2Server = http22.createSecureServer(secureServerOptions);
            http2Server.prependListener("connection", (socket) => {
              if (!areCredentialsValid) {
                this.trace("Dropped connection from " + JSON.stringify(socket.address()) + " due to unloaded credentials");
                socket.destroy();
              }
            });
            http2Server.on("secureConnection", (socket) => {
              socket.on("error", (e2) => {
                this.trace("An incoming TLS connection closed with error: " + e2.message);
              });
            });
            const credsWatcher = /* @__PURE__ */ __name((options2) => {
              if (options2) {
                const secureServer = http2Server;
                try {
                  secureServer.setSecureContext(options2);
                } catch (e2) {
                  logging.log(constants_1.LogVerbosity.ERROR, "Failed to set secure context with error " + e2.message);
                  options2 = null;
                }
              }
              areCredentialsValid = options2 !== null;
              this.trace("Post-update credentials valid: " + areCredentialsValid);
            }, "credsWatcher");
            credentials._addWatcher(credsWatcher);
            http2Server.on("close", () => {
              credentials._removeWatcher(credsWatcher);
            });
          } else {
            http2Server = http22.createServer(this.commonServerOptions);
          }
          http2Server.setTimeout(0, noop6);
          this._setupHandlers(http2Server, credentials._getInterceptors());
          return http2Server;
        }
        bindOneAddress(address, boundPortObject) {
          this.trace("Attempting to bind " + (0, subchannel_address_1.subchannelAddressToString)(address));
          const http2Server = this.createHttp2Server(boundPortObject.credentials);
          return new Promise((resolve24, reject) => {
            const onError2 = /* @__PURE__ */ __name((err) => {
              this.trace("Failed to bind " + (0, subchannel_address_1.subchannelAddressToString)(address) + " with error " + err.message);
              resolve24({
                port: "port" in address ? address.port : 1,
                error: err.message
              });
            }, "onError");
            http2Server.once("error", onError2);
            http2Server.listen(address, () => {
              const boundAddress = http2Server.address();
              let boundSubchannelAddress;
              if (typeof boundAddress === "string") {
                boundSubchannelAddress = {
                  path: boundAddress
                };
              } else {
                boundSubchannelAddress = {
                  host: boundAddress.address,
                  port: boundAddress.port
                };
              }
              const channelzRef = this.experimentalRegisterListenerToChannelz(boundSubchannelAddress);
              this.listenerChildrenTracker.refChild(channelzRef);
              this.http2Servers.set(http2Server, {
                channelzRef,
                sessions: /* @__PURE__ */ new Set(),
                ownsChannelzRef: true
              });
              boundPortObject.listeningServers.add(http2Server);
              this.trace("Successfully bound " + (0, subchannel_address_1.subchannelAddressToString)(boundSubchannelAddress));
              resolve24({
                port: "port" in boundSubchannelAddress ? boundSubchannelAddress.port : 1
              });
              http2Server.removeListener("error", onError2);
            });
          });
        }
        async bindManyPorts(addressList, boundPortObject) {
          if (addressList.length === 0) {
            return {
              count: 0,
              port: 0,
              errors: []
            };
          }
          if ((0, subchannel_address_1.isTcpSubchannelAddress)(addressList[0]) && addressList[0].port === 0) {
            const firstAddressResult = await this.bindOneAddress(addressList[0], boundPortObject);
            if (firstAddressResult.error) {
              const restAddressResult = await this.bindManyPorts(addressList.slice(1), boundPortObject);
              return Object.assign(Object.assign({}, restAddressResult), { errors: [firstAddressResult.error, ...restAddressResult.errors] });
            } else {
              const restAddresses = addressList.slice(1).map((address) => (0, subchannel_address_1.isTcpSubchannelAddress)(address) ? { host: address.host, port: firstAddressResult.port } : address);
              const restAddressResult = await Promise.all(restAddresses.map((address) => this.bindOneAddress(address, boundPortObject)));
              const allResults = [firstAddressResult, ...restAddressResult];
              return {
                count: allResults.filter((result) => result.error === void 0).length,
                port: firstAddressResult.port,
                errors: allResults.filter((result) => result.error).map((result) => result.error)
              };
            }
          } else {
            const allResults = await Promise.all(addressList.map((address) => this.bindOneAddress(address, boundPortObject)));
            return {
              count: allResults.filter((result) => result.error === void 0).length,
              port: allResults[0].port,
              errors: allResults.filter((result) => result.error).map((result) => result.error)
            };
          }
        }
        async bindAddressList(addressList, boundPortObject) {
          const bindResult = await this.bindManyPorts(addressList, boundPortObject);
          if (bindResult.count > 0) {
            if (bindResult.count < addressList.length) {
              logging.log(constants_1.LogVerbosity.INFO, `WARNING Only ${bindResult.count} addresses added out of total ${addressList.length} resolved`);
            }
            return bindResult.port;
          } else {
            const errorString = `No address added out of total ${addressList.length} resolved`;
            logging.log(constants_1.LogVerbosity.ERROR, errorString);
            throw new Error(`${errorString} errors: [${bindResult.errors.join(",")}]`);
          }
        }
        resolvePort(port) {
          return new Promise((resolve24, reject) => {
            const resolverListener = {
              onSuccessfulResolution: /* @__PURE__ */ __name((endpointList, serviceConfig, serviceConfigError) => {
                resolverListener.onSuccessfulResolution = () => {
                };
                const addressList = [].concat(...endpointList.map((endpoint) => endpoint.addresses));
                if (addressList.length === 0) {
                  reject(new Error(`No addresses resolved for port ${port}`));
                  return;
                }
                resolve24(addressList);
              }, "onSuccessfulResolution"),
              onError: /* @__PURE__ */ __name((error) => {
                reject(new Error(error.details));
              }, "onError")
            };
            const resolver = (0, resolver_1.createResolver)(port, resolverListener, this.options);
            resolver.updateResolution();
          });
        }
        async bindPort(port, boundPortObject) {
          const addressList = await this.resolvePort(port);
          if (boundPortObject.cancelled) {
            this.completeUnbind(boundPortObject);
            throw new Error("bindAsync operation cancelled by unbind call");
          }
          const portNumber = await this.bindAddressList(addressList, boundPortObject);
          if (boundPortObject.cancelled) {
            this.completeUnbind(boundPortObject);
            throw new Error("bindAsync operation cancelled by unbind call");
          }
          return portNumber;
        }
        normalizePort(port) {
          const initialPortUri = (0, uri_parser_1.parseUri)(port);
          if (initialPortUri === null) {
            throw new Error(`Could not parse port "${port}"`);
          }
          const portUri = (0, resolver_1.mapUriDefaultScheme)(initialPortUri);
          if (portUri === null) {
            throw new Error(`Could not get a default scheme for port "${port}"`);
          }
          return portUri;
        }
        bindAsync(port, creds, callback) {
          if (this.shutdown) {
            throw new Error("bindAsync called after shutdown");
          }
          if (typeof port !== "string") {
            throw new TypeError("port must be a string");
          }
          if (creds === null || !(creds instanceof server_credentials_1.ServerCredentials)) {
            throw new TypeError("creds must be a ServerCredentials object");
          }
          if (typeof callback !== "function") {
            throw new TypeError("callback must be a function");
          }
          this.trace("bindAsync port=" + port);
          const portUri = this.normalizePort(port);
          const deferredCallback = /* @__PURE__ */ __name((error, port2) => {
            process.nextTick(() => callback(error, port2));
          }, "deferredCallback");
          let boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri));
          if (boundPortObject) {
            if (!creds._equals(boundPortObject.credentials)) {
              deferredCallback(new Error(`${port} already bound with incompatible credentials`), 0);
              return;
            }
            boundPortObject.cancelled = false;
            if (boundPortObject.completionPromise) {
              boundPortObject.completionPromise.then((portNum) => callback(null, portNum), (error) => callback(error, 0));
            } else {
              deferredCallback(null, boundPortObject.portNumber);
            }
            return;
          }
          boundPortObject = {
            mapKey: (0, uri_parser_1.uriToString)(portUri),
            originalUri: portUri,
            completionPromise: null,
            cancelled: false,
            portNumber: 0,
            credentials: creds,
            listeningServers: /* @__PURE__ */ new Set()
          };
          const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path);
          const completionPromise = this.bindPort(portUri, boundPortObject);
          boundPortObject.completionPromise = completionPromise;
          if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) {
            completionPromise.then((portNum) => {
              const finalUri = {
                scheme: portUri.scheme,
                authority: portUri.authority,
                path: (0, uri_parser_1.combineHostPort)({ host: splitPort.host, port: portNum })
              };
              boundPortObject.mapKey = (0, uri_parser_1.uriToString)(finalUri);
              boundPortObject.completionPromise = null;
              boundPortObject.portNumber = portNum;
              this.boundPorts.set(boundPortObject.mapKey, boundPortObject);
              callback(null, portNum);
            }, (error) => {
              callback(error, 0);
            });
          } else {
            this.boundPorts.set(boundPortObject.mapKey, boundPortObject);
            completionPromise.then((portNum) => {
              boundPortObject.completionPromise = null;
              boundPortObject.portNumber = portNum;
              callback(null, portNum);
            }, (error) => {
              callback(error, 0);
            });
          }
        }
        registerInjectorToChannelz() {
          return (0, channelz_1.registerChannelzSocket)("injector", () => {
            return {
              localAddress: null,
              remoteAddress: null,
              security: null,
              remoteName: null,
              streamsStarted: 0,
              streamsSucceeded: 0,
              streamsFailed: 0,
              messagesSent: 0,
              messagesReceived: 0,
              keepAlivesSent: 0,
              lastLocalStreamCreatedTimestamp: null,
              lastRemoteStreamCreatedTimestamp: null,
              lastMessageSentTimestamp: null,
              lastMessageReceivedTimestamp: null,
              localFlowControlWindow: null,
              remoteFlowControlWindow: null
            };
          }, this.channelzEnabled);
        }
        /**
         * This API is experimental, so API stability is not guaranteed across minor versions.
         * @param credentials
         * @param channelzRef
         * @returns
         */
        experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, ownsChannelzRef = false) {
          if (credentials === null || !(credentials instanceof server_credentials_1.ServerCredentials)) {
            throw new TypeError("creds must be a ServerCredentials object");
          }
          if (this.channelzEnabled) {
            this.listenerChildrenTracker.refChild(channelzRef);
          }
          const server = this.createHttp2Server(credentials);
          const sessionsSet = /* @__PURE__ */ new Set();
          this.http2Servers.set(server, {
            channelzRef,
            sessions: sessionsSet,
            ownsChannelzRef
          });
          return {
            injectConnection: /* @__PURE__ */ __name((connection) => {
              server.emit("connection", connection);
            }, "injectConnection"),
            drain: /* @__PURE__ */ __name((graceTimeMs) => {
              var _b2, _c2;
              for (const session of sessionsSet) {
                this.closeSession(session);
              }
              (_c2 = (_b2 = setTimeout(() => {
                for (const session of sessionsSet) {
                  session.destroy(http22.constants.NGHTTP2_CANCEL);
                }
              }, graceTimeMs)).unref) === null || _c2 === void 0 ? void 0 : _c2.call(_b2);
            }, "drain"),
            destroy: /* @__PURE__ */ __name(() => {
              this.closeServer(server);
              for (const session of sessionsSet) {
                this.closeSession(session);
              }
            }, "destroy")
          };
        }
        createConnectionInjector(credentials) {
          if (credentials === null || !(credentials instanceof server_credentials_1.ServerCredentials)) {
            throw new TypeError("creds must be a ServerCredentials object");
          }
          const channelzRef = this.registerInjectorToChannelz();
          return this.experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, true);
        }
        closeServer(server, callback) {
          this.trace("Closing server with address " + JSON.stringify(server.address()));
          const serverInfo = this.http2Servers.get(server);
          server.close(() => {
            if (serverInfo && serverInfo.ownsChannelzRef) {
              this.listenerChildrenTracker.unrefChild(serverInfo.channelzRef);
              (0, channelz_1.unregisterChannelzRef)(serverInfo.channelzRef);
            }
            this.http2Servers.delete(server);
            callback === null || callback === void 0 ? void 0 : callback();
          });
        }
        closeSession(session, callback) {
          var _b2;
          this.trace("Closing session initiated by " + ((_b2 = session.socket) === null || _b2 === void 0 ? void 0 : _b2.remoteAddress));
          const sessionInfo = this.sessions.get(session);
          const closeCallback = /* @__PURE__ */ __name(() => {
            if (sessionInfo) {
              this.sessionChildrenTracker.unrefChild(sessionInfo.ref);
              (0, channelz_1.unregisterChannelzRef)(sessionInfo.ref);
            }
            callback === null || callback === void 0 ? void 0 : callback();
          }, "closeCallback");
          if (session.closed) {
            queueMicrotask(closeCallback);
          } else {
            session.close(closeCallback);
          }
        }
        completeUnbind(boundPortObject) {
          for (const server of boundPortObject.listeningServers) {
            const serverInfo = this.http2Servers.get(server);
            this.closeServer(server, () => {
              boundPortObject.listeningServers.delete(server);
            });
            if (serverInfo) {
              for (const session of serverInfo.sessions) {
                this.closeSession(session);
              }
            }
          }
          this.boundPorts.delete(boundPortObject.mapKey);
        }
        /**
         * Unbind a previously bound port, or cancel an in-progress bindAsync
         * operation. If port 0 was bound, only the actual bound port can be
         * unbound. For example, if bindAsync was called with "localhost:0" and the
         * bound port result was 54321, it can be unbound as "localhost:54321".
         * @param port
         */
        unbind(port) {
          this.trace("unbind port=" + port);
          const portUri = this.normalizePort(port);
          const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path);
          if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) {
            throw new Error("Cannot unbind port 0");
          }
          const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri));
          if (boundPortObject) {
            this.trace("unbinding " + boundPortObject.mapKey + " originally bound as " + (0, uri_parser_1.uriToString)(boundPortObject.originalUri));
            if (boundPortObject.completionPromise) {
              boundPortObject.cancelled = true;
            } else {
              this.completeUnbind(boundPortObject);
            }
          }
        }
        /**
         * Gracefully close all connections associated with a previously bound port.
         * After the grace time, forcefully close all remaining open connections.
         *
         * If port 0 was bound, only the actual bound port can be
         * drained. For example, if bindAsync was called with "localhost:0" and the
         * bound port result was 54321, it can be drained as "localhost:54321".
         * @param port
         * @param graceTimeMs
         * @returns
         */
        drain(port, graceTimeMs) {
          var _b2, _c2;
          this.trace("drain port=" + port + " graceTimeMs=" + graceTimeMs);
          const portUri = this.normalizePort(port);
          const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path);
          if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) {
            throw new Error("Cannot drain port 0");
          }
          const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri));
          if (!boundPortObject) {
            return;
          }
          const allSessions = /* @__PURE__ */ new Set();
          for (const http2Server of boundPortObject.listeningServers) {
            const serverEntry = this.http2Servers.get(http2Server);
            if (serverEntry) {
              for (const session of serverEntry.sessions) {
                allSessions.add(session);
                this.closeSession(session, () => {
                  allSessions.delete(session);
                });
              }
            }
          }
          (_c2 = (_b2 = setTimeout(() => {
            for (const session of allSessions) {
              session.destroy(http22.constants.NGHTTP2_CANCEL);
            }
          }, graceTimeMs)).unref) === null || _c2 === void 0 ? void 0 : _c2.call(_b2);
        }
        forceShutdown() {
          for (const boundPortObject of this.boundPorts.values()) {
            boundPortObject.cancelled = true;
          }
          this.boundPorts.clear();
          for (const server of this.http2Servers.keys()) {
            this.closeServer(server);
          }
          this.sessions.forEach((channelzInfo, session) => {
            this.closeSession(session);
            session.destroy(http22.constants.NGHTTP2_CANCEL);
          });
          this.sessions.clear();
          (0, channelz_1.unregisterChannelzRef)(this.channelzRef);
          this.shutdown = true;
        }
        register(name3, handler, serialize2, deserialize, type) {
          if (this.handlers.has(name3)) {
            return false;
          }
          this.handlers.set(name3, {
            func: handler,
            serialize: serialize2,
            deserialize,
            type,
            path: name3
          });
          return true;
        }
        unregister(name3) {
          return this.handlers.delete(name3);
        }
        /**
         * @deprecated No longer needed as of version 1.10.x
         */
        start() {
          if (this.http2Servers.size === 0 || [...this.http2Servers.keys()].every((server) => !server.listening)) {
            throw new Error("server must be bound in order to start");
          }
          if (this.started === true) {
            throw new Error("server is already started");
          }
          this.started = true;
        }
        tryShutdown(callback) {
          var _b2;
          const wrappedCallback = /* @__PURE__ */ __name((error) => {
            (0, channelz_1.unregisterChannelzRef)(this.channelzRef);
            callback(error);
          }, "wrappedCallback");
          let pendingChecks = 0;
          function maybeCallback() {
            pendingChecks--;
            if (pendingChecks === 0) {
              wrappedCallback();
            }
          }
          __name(maybeCallback, "maybeCallback");
          this.shutdown = true;
          for (const [serverKey, server] of this.http2Servers.entries()) {
            pendingChecks++;
            const serverString = server.channelzRef.name;
            this.trace("Waiting for server " + serverString + " to close");
            this.closeServer(serverKey, () => {
              this.trace("Server " + serverString + " finished closing");
              maybeCallback();
            });
            for (const session of server.sessions.keys()) {
              pendingChecks++;
              const sessionString = (_b2 = session.socket) === null || _b2 === void 0 ? void 0 : _b2.remoteAddress;
              this.trace("Waiting for session " + sessionString + " to close");
              this.closeSession(session, () => {
                this.trace("Session " + sessionString + " finished closing");
                maybeCallback();
              });
            }
          }
          if (pendingChecks === 0) {
            wrappedCallback();
          }
        }
        addHttp2Port() {
          throw new Error("Not yet implemented");
        }
        /**
         * Get the channelz reference object for this server. The returned value is
         * garbage if channelz is disabled for this server.
         * @returns
         */
        getChannelzRef() {
          return this.channelzRef;
        }
        _verifyContentType(stream2, headers) {
          const contentType = headers[http22.constants.HTTP2_HEADER_CONTENT_TYPE];
          if (typeof contentType !== "string" || !contentType.startsWith("application/grpc")) {
            stream2.respond({
              [http22.constants.HTTP2_HEADER_STATUS]: http22.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE
            }, { endStream: true });
            return false;
          }
          return true;
        }
        _retrieveHandler(path108) {
          serverCallTrace("Received call to method " + path108 + " at address " + this.serverAddressString);
          const handler = this.handlers.get(path108);
          if (handler === void 0) {
            serverCallTrace("No handler registered for method " + path108 + ". Sending UNIMPLEMENTED status.");
            return null;
          }
          return handler;
        }
        _respondWithError(err, stream2, channelzSessionInfo = null) {
          var _b2, _c2;
          const trailersToSend = Object.assign({ "grpc-status": (_b2 = err.code) !== null && _b2 !== void 0 ? _b2 : constants_1.Status.INTERNAL, "grpc-message": err.details, [http22.constants.HTTP2_HEADER_STATUS]: http22.constants.HTTP_STATUS_OK, [http22.constants.HTTP2_HEADER_CONTENT_TYPE]: "application/grpc+proto" }, (_c2 = err.metadata) === null || _c2 === void 0 ? void 0 : _c2.toHttp2Headers());
          stream2.respond(trailersToSend, { endStream: true });
          this.callTracker.addCallFailed();
          channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed();
        }
        _channelzHandler(extraInterceptors, stream2, headers) {
          this.onStreamOpened(stream2);
          const channelzSessionInfo = this.sessions.get(stream2.session);
          this.callTracker.addCallStarted();
          channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallStarted();
          if (!this._verifyContentType(stream2, headers)) {
            this.callTracker.addCallFailed();
            channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed();
            return;
          }
          const path108 = headers[HTTP2_HEADER_PATH];
          const handler = this._retrieveHandler(path108);
          if (!handler) {
            this._respondWithError(getUnimplementedStatusResponse(path108), stream2, channelzSessionInfo);
            return;
          }
          const callEventTracker = {
            addMessageSent: /* @__PURE__ */ __name(() => {
              if (channelzSessionInfo) {
                channelzSessionInfo.messagesSent += 1;
                channelzSessionInfo.lastMessageSentTimestamp = /* @__PURE__ */ new Date();
              }
            }, "addMessageSent"),
            addMessageReceived: /* @__PURE__ */ __name(() => {
              if (channelzSessionInfo) {
                channelzSessionInfo.messagesReceived += 1;
                channelzSessionInfo.lastMessageReceivedTimestamp = /* @__PURE__ */ new Date();
              }
            }, "addMessageReceived"),
            onCallEnd: /* @__PURE__ */ __name((status) => {
              if (status.code === constants_1.Status.OK) {
                this.callTracker.addCallSucceeded();
              } else {
                this.callTracker.addCallFailed();
              }
            }, "onCallEnd"),
            onStreamEnd: /* @__PURE__ */ __name((success) => {
              if (channelzSessionInfo) {
                if (success) {
                  channelzSessionInfo.streamTracker.addCallSucceeded();
                } else {
                  channelzSessionInfo.streamTracker.addCallFailed();
                }
              }
            }, "onStreamEnd")
          };
          const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream2, headers, callEventTracker, handler, this.options);
          if (!this._runHandlerForCall(call, handler)) {
            this.callTracker.addCallFailed();
            channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed();
            call.sendStatus({
              code: constants_1.Status.INTERNAL,
              details: `Unknown handler type: ${handler.type}`
            });
          }
        }
        _streamHandler(extraInterceptors, stream2, headers) {
          this.onStreamOpened(stream2);
          if (this._verifyContentType(stream2, headers) !== true) {
            return;
          }
          const path108 = headers[HTTP2_HEADER_PATH];
          const handler = this._retrieveHandler(path108);
          if (!handler) {
            this._respondWithError(getUnimplementedStatusResponse(path108), stream2, null);
            return;
          }
          const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream2, headers, null, handler, this.options);
          if (!this._runHandlerForCall(call, handler)) {
            call.sendStatus({
              code: constants_1.Status.INTERNAL,
              details: `Unknown handler type: ${handler.type}`
            });
          }
        }
        _runHandlerForCall(call, handler) {
          const { type } = handler;
          if (type === "unary") {
            handleUnary(call, handler);
          } else if (type === "clientStream") {
            handleClientStreaming(call, handler);
          } else if (type === "serverStream") {
            handleServerStreaming(call, handler);
          } else if (type === "bidi") {
            handleBidiStreaming(call, handler);
          } else {
            return false;
          }
          return true;
        }
        _setupHandlers(http2Server, extraInterceptors) {
          if (http2Server === null) {
            return;
          }
          const serverAddress = http2Server.address();
          let serverAddressString = "null";
          if (serverAddress) {
            if (typeof serverAddress === "string") {
              serverAddressString = serverAddress;
            } else {
              serverAddressString = serverAddress.address + ":" + serverAddress.port;
            }
          }
          this.serverAddressString = serverAddressString;
          const handler = this.channelzEnabled ? this._channelzHandler : this._streamHandler;
          const sessionHandler = this.channelzEnabled ? this._channelzSessionHandler(http2Server) : this._sessionHandler(http2Server);
          http2Server.on("stream", handler.bind(this, extraInterceptors));
          http2Server.on("session", sessionHandler);
        }
        _sessionHandler(http2Server) {
          return (session) => {
            var _b2, _c2;
            (_b2 = this.http2Servers.get(http2Server)) === null || _b2 === void 0 ? void 0 : _b2.sessions.add(session);
            let connectionAgeTimer = null;
            let connectionAgeGraceTimer = null;
            let keepaliveTimer = null;
            let sessionClosedByServer = false;
            const idleTimeoutObj = this.enableIdleTimeout(session);
            if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) {
              const jitterMagnitude = this.maxConnectionAgeMs / 10;
              const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude;
              connectionAgeTimer = setTimeout(() => {
                var _b3, _c3;
                sessionClosedByServer = true;
                this.trace("Connection dropped by max connection age: " + ((_b3 = session.socket) === null || _b3 === void 0 ? void 0 : _b3.remoteAddress));
                try {
                  session.goaway(http22.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge);
                } catch (e2) {
                  session.destroy();
                  return;
                }
                session.close();
                if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) {
                  connectionAgeGraceTimer = setTimeout(() => {
                    session.destroy();
                  }, this.maxConnectionAgeGraceMs);
                  (_c3 = connectionAgeGraceTimer.unref) === null || _c3 === void 0 ? void 0 : _c3.call(connectionAgeGraceTimer);
                }
              }, this.maxConnectionAgeMs + jitter);
              (_c2 = connectionAgeTimer.unref) === null || _c2 === void 0 ? void 0 : _c2.call(connectionAgeTimer);
            }
            const clearKeepaliveTimeout = /* @__PURE__ */ __name(() => {
              if (keepaliveTimer) {
                clearTimeout(keepaliveTimer);
                keepaliveTimer = null;
              }
            }, "clearKeepaliveTimeout");
            const canSendPing = /* @__PURE__ */ __name(() => {
              return !session.destroyed && this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && this.keepaliveTimeMs > 0;
            }, "canSendPing");
            let sendPing;
            const maybeStartKeepalivePingTimer = /* @__PURE__ */ __name(() => {
              var _b3;
              if (!canSendPing()) {
                return;
              }
              this.keepaliveTrace("Starting keepalive timer for " + this.keepaliveTimeMs + "ms");
              keepaliveTimer = setTimeout(() => {
                clearKeepaliveTimeout();
                sendPing();
              }, this.keepaliveTimeMs);
              (_b3 = keepaliveTimer.unref) === null || _b3 === void 0 ? void 0 : _b3.call(keepaliveTimer);
            }, "maybeStartKeepalivePingTimer");
            sendPing = /* @__PURE__ */ __name(() => {
              var _b3;
              if (!canSendPing()) {
                return;
              }
              this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms");
              let pingSendError = "";
              try {
                const pingSentSuccessfully = session.ping((err, duration, payload) => {
                  clearKeepaliveTimeout();
                  if (err) {
                    this.keepaliveTrace("Ping failed with error: " + err.message);
                    sessionClosedByServer = true;
                    session.close();
                  } else {
                    this.keepaliveTrace("Received ping response");
                    maybeStartKeepalivePingTimer();
                  }
                });
                if (!pingSentSuccessfully) {
                  pingSendError = "Ping returned false";
                }
              } catch (e2) {
                pingSendError = (e2 instanceof Error ? e2.message : "") || "Unknown error";
              }
              if (pingSendError) {
                this.keepaliveTrace("Ping send failed: " + pingSendError);
                this.trace("Connection dropped due to ping send error: " + pingSendError);
                sessionClosedByServer = true;
                session.close();
                return;
              }
              keepaliveTimer = setTimeout(() => {
                clearKeepaliveTimeout();
                this.keepaliveTrace("Ping timeout passed without response");
                this.trace("Connection dropped by keepalive timeout");
                sessionClosedByServer = true;
                session.close();
              }, this.keepaliveTimeoutMs);
              (_b3 = keepaliveTimer.unref) === null || _b3 === void 0 ? void 0 : _b3.call(keepaliveTimer);
            }, "sendPing");
            maybeStartKeepalivePingTimer();
            session.on("close", () => {
              var _b3, _c3;
              if (!sessionClosedByServer) {
                this.trace(`Connection dropped by client ${(_b3 = session.socket) === null || _b3 === void 0 ? void 0 : _b3.remoteAddress}`);
              }
              if (connectionAgeTimer) {
                clearTimeout(connectionAgeTimer);
              }
              if (connectionAgeGraceTimer) {
                clearTimeout(connectionAgeGraceTimer);
              }
              clearKeepaliveTimeout();
              if (idleTimeoutObj !== null) {
                clearTimeout(idleTimeoutObj.timeout);
                this.sessionIdleTimeouts.delete(session);
              }
              (_c3 = this.http2Servers.get(http2Server)) === null || _c3 === void 0 ? void 0 : _c3.sessions.delete(session);
            });
          };
        }
        _channelzSessionHandler(http2Server) {
          return (session) => {
            var _b2, _c2, _d, _e;
            const channelzRef = (0, channelz_1.registerChannelzSocket)((_c2 = (_b2 = session.socket) === null || _b2 === void 0 ? void 0 : _b2.remoteAddress) !== null && _c2 !== void 0 ? _c2 : "unknown", this.getChannelzSessionInfo.bind(this, session), this.channelzEnabled);
            const channelzSessionInfo = {
              ref: channelzRef,
              streamTracker: new channelz_1.ChannelzCallTracker(),
              messagesSent: 0,
              messagesReceived: 0,
              keepAlivesSent: 0,
              lastMessageSentTimestamp: null,
              lastMessageReceivedTimestamp: null
            };
            (_d = this.http2Servers.get(http2Server)) === null || _d === void 0 ? void 0 : _d.sessions.add(session);
            this.sessions.set(session, channelzSessionInfo);
            const clientAddress = `${session.socket.remoteAddress}:${session.socket.remotePort}`;
            this.channelzTrace.addTrace("CT_INFO", "Connection established by client " + clientAddress);
            this.trace("Connection established by client " + clientAddress);
            this.sessionChildrenTracker.refChild(channelzRef);
            let connectionAgeTimer = null;
            let connectionAgeGraceTimer = null;
            let keepaliveTimeout = null;
            let sessionClosedByServer = false;
            const idleTimeoutObj = this.enableIdleTimeout(session);
            if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) {
              const jitterMagnitude = this.maxConnectionAgeMs / 10;
              const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude;
              connectionAgeTimer = setTimeout(() => {
                var _b3;
                sessionClosedByServer = true;
                this.channelzTrace.addTrace("CT_INFO", "Connection dropped by max connection age from " + clientAddress);
                try {
                  session.goaway(http22.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge);
                } catch (e2) {
                  session.destroy();
                  return;
                }
                session.close();
                if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) {
                  connectionAgeGraceTimer = setTimeout(() => {
                    session.destroy();
                  }, this.maxConnectionAgeGraceMs);
                  (_b3 = connectionAgeGraceTimer.unref) === null || _b3 === void 0 ? void 0 : _b3.call(connectionAgeGraceTimer);
                }
              }, this.maxConnectionAgeMs + jitter);
              (_e = connectionAgeTimer.unref) === null || _e === void 0 ? void 0 : _e.call(connectionAgeTimer);
            }
            const clearKeepaliveTimeout = /* @__PURE__ */ __name(() => {
              if (keepaliveTimeout) {
                clearTimeout(keepaliveTimeout);
                keepaliveTimeout = null;
              }
            }, "clearKeepaliveTimeout");
            const canSendPing = /* @__PURE__ */ __name(() => {
              return !session.destroyed && this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && this.keepaliveTimeMs > 0;
            }, "canSendPing");
            let sendPing;
            const maybeStartKeepalivePingTimer = /* @__PURE__ */ __name(() => {
              var _b3;
              if (!canSendPing()) {
                return;
              }
              this.keepaliveTrace("Starting keepalive timer for " + this.keepaliveTimeMs + "ms");
              keepaliveTimeout = setTimeout(() => {
                clearKeepaliveTimeout();
                sendPing();
              }, this.keepaliveTimeMs);
              (_b3 = keepaliveTimeout.unref) === null || _b3 === void 0 ? void 0 : _b3.call(keepaliveTimeout);
            }, "maybeStartKeepalivePingTimer");
            sendPing = /* @__PURE__ */ __name(() => {
              var _b3;
              if (!canSendPing()) {
                return;
              }
              this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms");
              let pingSendError = "";
              try {
                const pingSentSuccessfully = session.ping((err, duration, payload) => {
                  clearKeepaliveTimeout();
                  if (err) {
                    this.keepaliveTrace("Ping failed with error: " + err.message);
                    this.channelzTrace.addTrace("CT_INFO", "Connection dropped due to error of a ping frame " + err.message + " return in " + duration);
                    sessionClosedByServer = true;
                    session.close();
                  } else {
                    this.keepaliveTrace("Received ping response");
                    maybeStartKeepalivePingTimer();
                  }
                });
                if (!pingSentSuccessfully) {
                  pingSendError = "Ping returned false";
                }
              } catch (e2) {
                pingSendError = (e2 instanceof Error ? e2.message : "") || "Unknown error";
              }
              if (pingSendError) {
                this.keepaliveTrace("Ping send failed: " + pingSendError);
                this.channelzTrace.addTrace("CT_INFO", "Connection dropped due to ping send error: " + pingSendError);
                sessionClosedByServer = true;
                session.close();
                return;
              }
              channelzSessionInfo.keepAlivesSent += 1;
              keepaliveTimeout = setTimeout(() => {
                clearKeepaliveTimeout();
                this.keepaliveTrace("Ping timeout passed without response");
                this.channelzTrace.addTrace("CT_INFO", "Connection dropped by keepalive timeout from " + clientAddress);
                sessionClosedByServer = true;
                session.close();
              }, this.keepaliveTimeoutMs);
              (_b3 = keepaliveTimeout.unref) === null || _b3 === void 0 ? void 0 : _b3.call(keepaliveTimeout);
            }, "sendPing");
            maybeStartKeepalivePingTimer();
            session.on("close", () => {
              var _b3;
              if (!sessionClosedByServer) {
                this.channelzTrace.addTrace("CT_INFO", "Connection dropped by client " + clientAddress);
              }
              this.sessionChildrenTracker.unrefChild(channelzRef);
              (0, channelz_1.unregisterChannelzRef)(channelzRef);
              if (connectionAgeTimer) {
                clearTimeout(connectionAgeTimer);
              }
              if (connectionAgeGraceTimer) {
                clearTimeout(connectionAgeGraceTimer);
              }
              clearKeepaliveTimeout();
              if (idleTimeoutObj !== null) {
                clearTimeout(idleTimeoutObj.timeout);
                this.sessionIdleTimeouts.delete(session);
              }
              (_b3 = this.http2Servers.get(http2Server)) === null || _b3 === void 0 ? void 0 : _b3.sessions.delete(session);
              this.sessions.delete(session);
            });
          };
        }
        enableIdleTimeout(session) {
          var _b2, _c2;
          if (this.sessionIdleTimeout >= MAX_CONNECTION_IDLE_MS) {
            return null;
          }
          const idleTimeoutObj = {
            activeStreams: 0,
            lastIdle: Date.now(),
            onClose: this.onStreamClose.bind(this, session),
            timeout: setTimeout(this.onIdleTimeout, this.sessionIdleTimeout, this, session)
          };
          (_c2 = (_b2 = idleTimeoutObj.timeout).unref) === null || _c2 === void 0 ? void 0 : _c2.call(_b2);
          this.sessionIdleTimeouts.set(session, idleTimeoutObj);
          const { socket } = session;
          this.trace("Enable idle timeout for " + socket.remoteAddress + ":" + socket.remotePort);
          return idleTimeoutObj;
        }
        onIdleTimeout(ctx, session) {
          const { socket } = session;
          const sessionInfo = ctx.sessionIdleTimeouts.get(session);
          if (sessionInfo !== void 0 && sessionInfo.activeStreams === 0) {
            if (Date.now() - sessionInfo.lastIdle >= ctx.sessionIdleTimeout) {
              ctx.trace("Session idle timeout triggered for " + (socket === null || socket === void 0 ? void 0 : socket.remoteAddress) + ":" + (socket === null || socket === void 0 ? void 0 : socket.remotePort) + " last idle at " + sessionInfo.lastIdle);
              ctx.closeSession(session);
            } else {
              sessionInfo.timeout.refresh();
            }
          }
        }
        onStreamOpened(stream2) {
          const session = stream2.session;
          const idleTimeoutObj = this.sessionIdleTimeouts.get(session);
          if (idleTimeoutObj) {
            idleTimeoutObj.activeStreams += 1;
            stream2.once("close", idleTimeoutObj.onClose);
          }
        }
        onStreamClose(session) {
          var _b2, _c2;
          const idleTimeoutObj = this.sessionIdleTimeouts.get(session);
          if (idleTimeoutObj) {
            idleTimeoutObj.activeStreams -= 1;
            if (idleTimeoutObj.activeStreams === 0) {
              idleTimeoutObj.lastIdle = Date.now();
              idleTimeoutObj.timeout.refresh();
              this.trace("Session onStreamClose" + ((_b2 = session.socket) === null || _b2 === void 0 ? void 0 : _b2.remoteAddress) + ":" + ((_c2 = session.socket) === null || _c2 === void 0 ? void 0 : _c2.remotePort) + " at " + idleTimeoutObj.lastIdle);
            }
          }
        }
      }, (() => {
        const _metadata = typeof Symbol === "function" && Symbol.metadata ? /* @__PURE__ */ Object.create(null) : void 0;
        _start_decorators = [deprecate("Calling start() is no longer necessary. It can be safely omitted.")];
        __esDecorate(_a6, null, _start_decorators, { kind: "method", name: "start", static: false, private: false, access: { has: /* @__PURE__ */ __name((obj) => "start" in obj, "has"), get: /* @__PURE__ */ __name((obj) => obj.start, "get") }, metadata: _metadata }, null, _instanceExtraInitializers);
        if (_metadata) Object.defineProperty(_a6, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
      })(), _a6;
    })();
    exports2.Server = Server;
    async function handleUnary(call, handler) {
      let stream2;
      function respond(err, value, trailer, flags) {
        if (err) {
          call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer));
          return;
        }
        call.sendMessage(value, () => {
          call.sendStatus({
            code: constants_1.Status.OK,
            details: "OK",
            metadata: trailer !== null && trailer !== void 0 ? trailer : null
          });
        });
      }
      __name(respond, "respond");
      let requestMetadata;
      let requestMessage = null;
      call.start({
        onReceiveMetadata(metadata) {
          requestMetadata = metadata;
          call.startRead();
        },
        onReceiveMessage(message) {
          if (requestMessage) {
            call.sendStatus({
              code: constants_1.Status.UNIMPLEMENTED,
              details: `Received a second request message for server streaming method ${handler.path}`,
              metadata: null
            });
            return;
          }
          requestMessage = message;
          call.startRead();
        },
        onReceiveHalfClose() {
          if (!requestMessage) {
            call.sendStatus({
              code: constants_1.Status.UNIMPLEMENTED,
              details: `Received no request message for server streaming method ${handler.path}`,
              metadata: null
            });
            return;
          }
          stream2 = new server_call_1.ServerWritableStreamImpl(handler.path, call, requestMetadata, requestMessage);
          try {
            handler.func(stream2, respond);
          } catch (err) {
            call.sendStatus({
              code: constants_1.Status.UNKNOWN,
              details: `Server method handler threw error ${err.message}`,
              metadata: null
            });
          }
        },
        onCancel() {
          if (stream2) {
            stream2.cancelled = true;
            stream2.emit("cancelled", "cancelled");
          }
        }
      });
    }
    __name(handleUnary, "handleUnary");
    function handleClientStreaming(call, handler) {
      let stream2;
      function respond(err, value, trailer, flags) {
        if (err) {
          call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer));
          return;
        }
        call.sendMessage(value, () => {
          call.sendStatus({
            code: constants_1.Status.OK,
            details: "OK",
            metadata: trailer !== null && trailer !== void 0 ? trailer : null
          });
        });
      }
      __name(respond, "respond");
      call.start({
        onReceiveMetadata(metadata) {
          stream2 = new server_call_1.ServerDuplexStreamImpl(handler.path, call, metadata);
          try {
            handler.func(stream2, respond);
          } catch (err) {
            call.sendStatus({
              code: constants_1.Status.UNKNOWN,
              details: `Server method handler threw error ${err.message}`,
              metadata: null
            });
          }
        },
        onReceiveMessage(message) {
          stream2.push(message);
        },
        onReceiveHalfClose() {
          stream2.push(null);
        },
        onCancel() {
          if (stream2) {
            stream2.cancelled = true;
            stream2.emit("cancelled", "cancelled");
            stream2.destroy();
          }
        }
      });
    }
    __name(handleClientStreaming, "handleClientStreaming");
    function handleServerStreaming(call, handler) {
      let stream2;
      let requestMetadata;
      let requestMessage = null;
      call.start({
        onReceiveMetadata(metadata) {
          requestMetadata = metadata;
          call.startRead();
        },
        onReceiveMessage(message) {
          if (requestMessage) {
            call.sendStatus({
              code: constants_1.Status.UNIMPLEMENTED,
              details: `Received a second request message for server streaming method ${handler.path}`,
              metadata: null
            });
            return;
          }
          requestMessage = message;
          call.startRead();
        },
        onReceiveHalfClose() {
          if (!requestMessage) {
            call.sendStatus({
              code: constants_1.Status.UNIMPLEMENTED,
              details: `Received no request message for server streaming method ${handler.path}`,
              metadata: null
            });
            return;
          }
          stream2 = new server_call_1.ServerWritableStreamImpl(handler.path, call, requestMetadata, requestMessage);
          try {
            handler.func(stream2);
          } catch (err) {
            call.sendStatus({
              code: constants_1.Status.UNKNOWN,
              details: `Server method handler threw error ${err.message}`,
              metadata: null
            });
          }
        },
        onCancel() {
          if (stream2) {
            stream2.cancelled = true;
            stream2.emit("cancelled", "cancelled");
            stream2.destroy();
          }
        }
      });
    }
    __name(handleServerStreaming, "handleServerStreaming");
    function handleBidiStreaming(call, handler) {
      let stream2;
      call.start({
        onReceiveMetadata(metadata) {
          stream2 = new server_call_1.ServerDuplexStreamImpl(handler.path, call, metadata);
          try {
            handler.func(stream2);
          } catch (err) {
            call.sendStatus({
              code: constants_1.Status.UNKNOWN,
              details: `Server method handler threw error ${err.message}`,
              metadata: null
            });
          }
        },
        onReceiveMessage(message) {
          stream2.push(message);
        },
        onReceiveHalfClose() {
          stream2.push(null);
        },
        onCancel() {
          if (stream2) {
            stream2.cancelled = true;
            stream2.emit("cancelled", "cancelled");
            stream2.destroy();
          }
        }
      });
    }
    __name(handleBidiStreaming, "handleBidiStreaming");
  }
});

// node_modules/@grpc/grpc-js/build/src/status-builder.js
var require_status_builder = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/status-builder.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.StatusBuilder = void 0;
    var StatusBuilder = class {
      static {
        __name(this, "StatusBuilder");
      }
      constructor() {
        this.code = null;
        this.details = null;
        this.metadata = null;
      }
      /**
       * Adds a status code to the builder.
       */
      withCode(code2) {
        this.code = code2;
        return this;
      }
      /**
       * Adds details to the builder.
       */
      withDetails(details) {
        this.details = details;
        return this;
      }
      /**
       * Adds metadata to the builder.
       */
      withMetadata(metadata) {
        this.metadata = metadata;
        return this;
      }
      /**
       * Builds the status object.
       */
      build() {
        const status = {};
        if (this.code !== null) {
          status.code = this.code;
        }
        if (this.details !== null) {
          status.details = this.details;
        }
        if (this.metadata !== null) {
          status.metadata = this.metadata;
        }
        return status;
      }
    };
    exports2.StatusBuilder = StatusBuilder;
  }
});

// node_modules/@grpc/grpc-js/build/src/duration.js
var require_duration = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/duration.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.msToDuration = msToDuration;
    exports2.durationToMs = durationToMs;
    exports2.isDuration = isDuration;
    exports2.parseDuration = parseDuration;
    function msToDuration(millis) {
      return {
        seconds: millis / 1e3 | 0,
        nanos: millis % 1e3 * 1e6 | 0
      };
    }
    __name(msToDuration, "msToDuration");
    function durationToMs(duration) {
      return duration.seconds * 1e3 + duration.nanos / 1e6 | 0;
    }
    __name(durationToMs, "durationToMs");
    function isDuration(value) {
      return typeof value.seconds === "number" && typeof value.nanos === "number";
    }
    __name(isDuration, "isDuration");
    var durationRegex2 = /^(\d+)(?:\.(\d+))?s$/;
    function parseDuration(value) {
      const match2 = value.match(durationRegex2);
      if (!match2) {
        return null;
      }
      return {
        seconds: Number.parseInt(match2[1], 10),
        nanos: match2[2] ? Number.parseInt(match2[2].padEnd(9, "0"), 10) : 0
      };
    }
    __name(parseDuration, "parseDuration");
  }
});

// node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js
var require_load_balancer_pick_first = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LeafLoadBalancer = exports2.PickFirstLoadBalancer = exports2.PickFirstLoadBalancingConfig = void 0;
    exports2.shuffled = shuffled;
    exports2.setup = setup;
    var load_balancer_1 = require_load_balancer();
    var connectivity_state_1 = require_connectivity_state();
    var picker_1 = require_picker();
    var subchannel_address_1 = require_subchannel_address();
    var logging = require_logging();
    var constants_1 = require_constants9();
    var subchannel_address_2 = require_subchannel_address();
    var net_1 = __require("net");
    var TRACER_NAME = "pick_first";
    function trace2(text) {
      logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    var TYPE_NAME = "pick_first";
    var CONNECTION_DELAY_INTERVAL_MS = 250;
    var PickFirstLoadBalancingConfig = class _PickFirstLoadBalancingConfig {
      static {
        __name(this, "PickFirstLoadBalancingConfig");
      }
      constructor(shuffleAddressList) {
        this.shuffleAddressList = shuffleAddressList;
      }
      getLoadBalancerName() {
        return TYPE_NAME;
      }
      toJsonObject() {
        return {
          [TYPE_NAME]: {
            shuffleAddressList: this.shuffleAddressList
          }
        };
      }
      getShuffleAddressList() {
        return this.shuffleAddressList;
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      static createFromJson(obj) {
        if ("shuffleAddressList" in obj && !(typeof obj.shuffleAddressList === "boolean")) {
          throw new Error("pick_first config field shuffleAddressList must be a boolean if provided");
        }
        return new _PickFirstLoadBalancingConfig(obj.shuffleAddressList === true);
      }
    };
    exports2.PickFirstLoadBalancingConfig = PickFirstLoadBalancingConfig;
    var PickFirstPicker = class {
      static {
        __name(this, "PickFirstPicker");
      }
      constructor(subchannel) {
        this.subchannel = subchannel;
      }
      pick(pickArgs) {
        return {
          pickResultType: picker_1.PickResultType.COMPLETE,
          subchannel: this.subchannel,
          status: null,
          onCallStarted: null,
          onCallEnded: null
        };
      }
    };
    function shuffled(list3) {
      const result = list3.slice();
      for (let i = result.length - 1; i > 1; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        const temp = result[i];
        result[i] = result[j];
        result[j] = temp;
      }
      return result;
    }
    __name(shuffled, "shuffled");
    function interleaveAddressFamilies(addressList) {
      if (addressList.length === 0) {
        return [];
      }
      const result = [];
      const ipv6Addresses = [];
      const ipv4Addresses = [];
      const ipv6First = (0, subchannel_address_2.isTcpSubchannelAddress)(addressList[0]) && (0, net_1.isIPv6)(addressList[0].host);
      for (const address of addressList) {
        if ((0, subchannel_address_2.isTcpSubchannelAddress)(address) && (0, net_1.isIPv6)(address.host)) {
          ipv6Addresses.push(address);
        } else {
          ipv4Addresses.push(address);
        }
      }
      const firstList = ipv6First ? ipv6Addresses : ipv4Addresses;
      const secondList = ipv6First ? ipv4Addresses : ipv6Addresses;
      for (let i = 0; i < Math.max(firstList.length, secondList.length); i++) {
        if (i < firstList.length) {
          result.push(firstList[i]);
        }
        if (i < secondList.length) {
          result.push(secondList[i]);
        }
      }
      return result;
    }
    __name(interleaveAddressFamilies, "interleaveAddressFamilies");
    var REPORT_HEALTH_STATUS_OPTION_NAME = "grpc-node.internal.pick-first.report_health_status";
    var PickFirstLoadBalancer = class {
      static {
        __name(this, "PickFirstLoadBalancer");
      }
      /**
       * Load balancer that attempts to connect to each backend in the address list
       * in order, and picks the first one that connects, using it for every
       * request.
       * @param channelControlHelper `ChannelControlHelper` instance provided by
       *     this load balancer's owner.
       */
      constructor(channelControlHelper) {
        this.channelControlHelper = channelControlHelper;
        this.children = [];
        this.currentState = connectivity_state_1.ConnectivityState.IDLE;
        this.currentSubchannelIndex = 0;
        this.currentPick = null;
        this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime, errorMessage) => {
          this.onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage);
        };
        this.pickedSubchannelHealthListener = () => this.calculateAndReportNewState();
        this.stickyTransientFailureMode = false;
        this.reportHealthStatus = false;
        this.lastError = null;
        this.latestAddressList = null;
        this.latestOptions = {};
        this.connectionDelayTimeout = setTimeout(() => {
        }, 0);
        clearTimeout(this.connectionDelayTimeout);
      }
      allChildrenHaveReportedTF() {
        return this.children.every((child) => child.hasReportedTransientFailure);
      }
      resetChildrenReportedTF() {
        this.children.every((child) => child.hasReportedTransientFailure = false);
      }
      calculateAndReportNewState() {
        var _a6;
        if (this.currentPick) {
          if (this.reportHealthStatus && !this.currentPick.isHealthy()) {
            const errorMessage = `Picked subchannel ${this.currentPick.getAddress()} is unhealthy`;
            this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({
              details: errorMessage
            }), errorMessage);
          } else {
            this.updateState(connectivity_state_1.ConnectivityState.READY, new PickFirstPicker(this.currentPick), null);
          }
        } else if (((_a6 = this.latestAddressList) === null || _a6 === void 0 ? void 0 : _a6.length) === 0) {
          const errorMessage = `No connection established. Last error: ${this.lastError}`;
          this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({
            details: errorMessage
          }), errorMessage);
        } else if (this.children.length === 0) {
          this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null);
        } else {
          if (this.stickyTransientFailureMode) {
            const errorMessage = `No connection established. Last error: ${this.lastError}`;
            this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({
              details: errorMessage
            }), errorMessage);
          } else {
            this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null);
          }
        }
      }
      requestReresolution() {
        this.channelControlHelper.requestReresolution();
      }
      maybeEnterStickyTransientFailureMode() {
        if (!this.allChildrenHaveReportedTF()) {
          return;
        }
        this.requestReresolution();
        this.resetChildrenReportedTF();
        if (this.stickyTransientFailureMode) {
          this.calculateAndReportNewState();
          return;
        }
        this.stickyTransientFailureMode = true;
        for (const { subchannel } of this.children) {
          subchannel.startConnecting();
        }
        this.calculateAndReportNewState();
      }
      removeCurrentPick() {
        if (this.currentPick !== null) {
          this.currentPick.removeConnectivityStateListener(this.subchannelStateListener);
          this.channelControlHelper.removeChannelzChild(this.currentPick.getChannelzRef());
          this.currentPick.removeHealthStateWatcher(this.pickedSubchannelHealthListener);
          this.currentPick.unref();
          this.currentPick = null;
        }
      }
      onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage) {
        var _a6;
        if ((_a6 = this.currentPick) === null || _a6 === void 0 ? void 0 : _a6.realSubchannelEquals(subchannel)) {
          if (newState !== connectivity_state_1.ConnectivityState.READY) {
            this.removeCurrentPick();
            this.calculateAndReportNewState();
          }
          return;
        }
        for (const [index, child] of this.children.entries()) {
          if (subchannel.realSubchannelEquals(child.subchannel)) {
            if (newState === connectivity_state_1.ConnectivityState.READY) {
              this.pickSubchannel(child.subchannel);
            }
            if (newState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) {
              child.hasReportedTransientFailure = true;
              if (errorMessage) {
                this.lastError = errorMessage;
              }
              this.maybeEnterStickyTransientFailureMode();
              if (index === this.currentSubchannelIndex) {
                this.startNextSubchannelConnecting(index + 1);
              }
            }
            child.subchannel.startConnecting();
            return;
          }
        }
      }
      startNextSubchannelConnecting(startIndex) {
        clearTimeout(this.connectionDelayTimeout);
        for (const [index, child] of this.children.entries()) {
          if (index >= startIndex) {
            const subchannelState = child.subchannel.getConnectivityState();
            if (subchannelState === connectivity_state_1.ConnectivityState.IDLE || subchannelState === connectivity_state_1.ConnectivityState.CONNECTING) {
              this.startConnecting(index);
              return;
            }
          }
        }
        this.maybeEnterStickyTransientFailureMode();
      }
      /**
       * Have a single subchannel in the `subchannels` list start connecting.
       * @param subchannelIndex The index into the `subchannels` list.
       */
      startConnecting(subchannelIndex) {
        var _a6, _b2;
        clearTimeout(this.connectionDelayTimeout);
        this.currentSubchannelIndex = subchannelIndex;
        if (this.children[subchannelIndex].subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) {
          trace2("Start connecting to subchannel with address " + this.children[subchannelIndex].subchannel.getAddress());
          process.nextTick(() => {
            var _a7;
            (_a7 = this.children[subchannelIndex]) === null || _a7 === void 0 ? void 0 : _a7.subchannel.startConnecting();
          });
        }
        this.connectionDelayTimeout = setTimeout(() => {
          this.startNextSubchannelConnecting(subchannelIndex + 1);
        }, CONNECTION_DELAY_INTERVAL_MS);
        (_b2 = (_a6 = this.connectionDelayTimeout).unref) === null || _b2 === void 0 ? void 0 : _b2.call(_a6);
      }
      /**
       * Declare that the specified subchannel should be used to make requests.
       * This functions the same independent of whether subchannel is a member of
       * this.children and whether it is equal to this.currentPick.
       * Prerequisite: subchannel.getConnectivityState() === READY.
       * @param subchannel
       */
      pickSubchannel(subchannel) {
        trace2("Pick subchannel with address " + subchannel.getAddress());
        this.stickyTransientFailureMode = false;
        subchannel.ref();
        this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef());
        this.removeCurrentPick();
        this.resetSubchannelList();
        subchannel.addConnectivityStateListener(this.subchannelStateListener);
        subchannel.addHealthStateWatcher(this.pickedSubchannelHealthListener);
        this.currentPick = subchannel;
        clearTimeout(this.connectionDelayTimeout);
        this.calculateAndReportNewState();
      }
      updateState(newState, picker, errorMessage) {
        trace2(connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[newState]);
        this.currentState = newState;
        this.channelControlHelper.updateState(newState, picker, errorMessage);
      }
      resetSubchannelList() {
        for (const child of this.children) {
          child.subchannel.removeConnectivityStateListener(this.subchannelStateListener);
          child.subchannel.unref();
          this.channelControlHelper.removeChannelzChild(child.subchannel.getChannelzRef());
        }
        this.currentSubchannelIndex = 0;
        this.children = [];
      }
      connectToAddressList(addressList, options2) {
        trace2("connectToAddressList([" + addressList.map((address) => (0, subchannel_address_1.subchannelAddressToString)(address)) + "])");
        const newChildrenList = addressList.map((address) => ({
          subchannel: this.channelControlHelper.createSubchannel(address, options2),
          hasReportedTransientFailure: false
        }));
        for (const { subchannel } of newChildrenList) {
          if (subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.READY) {
            this.pickSubchannel(subchannel);
            return;
          }
        }
        for (const { subchannel } of newChildrenList) {
          subchannel.ref();
          this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef());
        }
        this.resetSubchannelList();
        this.children = newChildrenList;
        for (const { subchannel } of this.children) {
          subchannel.addConnectivityStateListener(this.subchannelStateListener);
        }
        for (const child of this.children) {
          if (child.subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) {
            child.hasReportedTransientFailure = true;
          }
        }
        this.startNextSubchannelConnecting(0);
        this.calculateAndReportNewState();
      }
      updateAddressList(endpointList, lbConfig, options2) {
        if (!(lbConfig instanceof PickFirstLoadBalancingConfig)) {
          return;
        }
        this.reportHealthStatus = options2[REPORT_HEALTH_STATUS_OPTION_NAME];
        if (lbConfig.getShuffleAddressList()) {
          endpointList = shuffled(endpointList);
        }
        const rawAddressList = [].concat(...endpointList.map((endpoint) => endpoint.addresses));
        trace2("updateAddressList([" + rawAddressList.map((address) => (0, subchannel_address_1.subchannelAddressToString)(address)) + "])");
        if (rawAddressList.length === 0) {
          this.lastError = "No addresses resolved";
        }
        const addressList = interleaveAddressFamilies(rawAddressList);
        this.latestAddressList = addressList;
        this.latestOptions = options2;
        this.connectToAddressList(addressList, options2);
      }
      exitIdle() {
        if (this.currentState === connectivity_state_1.ConnectivityState.IDLE && this.latestAddressList) {
          this.connectToAddressList(this.latestAddressList, this.latestOptions);
        }
      }
      resetBackoff() {
      }
      destroy() {
        this.resetSubchannelList();
        this.removeCurrentPick();
      }
      getTypeName() {
        return TYPE_NAME;
      }
    };
    exports2.PickFirstLoadBalancer = PickFirstLoadBalancer;
    var LEAF_CONFIG = new PickFirstLoadBalancingConfig(false);
    var LeafLoadBalancer = class {
      static {
        __name(this, "LeafLoadBalancer");
      }
      constructor(endpoint, channelControlHelper, options2) {
        this.endpoint = endpoint;
        this.options = options2;
        this.latestState = connectivity_state_1.ConnectivityState.IDLE;
        const childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, {
          updateState: /* @__PURE__ */ __name((connectivityState, picker, errorMessage) => {
            this.latestState = connectivityState;
            this.latestPicker = picker;
            channelControlHelper.updateState(connectivityState, picker, errorMessage);
          }, "updateState")
        });
        this.pickFirstBalancer = new PickFirstLoadBalancer(childChannelControlHelper);
        this.latestPicker = new picker_1.QueuePicker(this.pickFirstBalancer);
      }
      startConnecting() {
        this.pickFirstBalancer.updateAddressList([this.endpoint], LEAF_CONFIG, Object.assign(Object.assign({}, this.options), { [REPORT_HEALTH_STATUS_OPTION_NAME]: true }));
      }
      /**
       * Update the endpoint associated with this LeafLoadBalancer to a new
       * endpoint. Does not trigger connection establishment if a connection
       * attempt is not already in progress.
       * @param newEndpoint
       */
      updateEndpoint(newEndpoint, newOptions) {
        this.options = newOptions;
        this.endpoint = newEndpoint;
        if (this.latestState !== connectivity_state_1.ConnectivityState.IDLE) {
          this.startConnecting();
        }
      }
      getConnectivityState() {
        return this.latestState;
      }
      getPicker() {
        return this.latestPicker;
      }
      getEndpoint() {
        return this.endpoint;
      }
      exitIdle() {
        this.pickFirstBalancer.exitIdle();
      }
      destroy() {
        this.pickFirstBalancer.destroy();
      }
    };
    exports2.LeafLoadBalancer = LeafLoadBalancer;
    function setup() {
      (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, PickFirstLoadBalancer, PickFirstLoadBalancingConfig);
      (0, load_balancer_1.registerDefaultLoadBalancerType)(TYPE_NAME);
    }
    __name(setup, "setup");
  }
});

// node_modules/@grpc/grpc-js/build/src/certificate-provider.js
var require_certificate_provider = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/certificate-provider.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.FileWatcherCertificateProvider = void 0;
    var fs95 = __require("fs");
    var logging = require_logging();
    var constants_1 = require_constants9();
    var util_1 = __require("util");
    var TRACER_NAME = "certificate_provider";
    function trace2(text) {
      logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    var readFilePromise = (0, util_1.promisify)(fs95.readFile);
    var FileWatcherCertificateProvider = class {
      static {
        __name(this, "FileWatcherCertificateProvider");
      }
      constructor(config) {
        this.config = config;
        this.refreshTimer = null;
        this.fileResultPromise = null;
        this.latestCaUpdate = void 0;
        this.caListeners = /* @__PURE__ */ new Set();
        this.latestIdentityUpdate = void 0;
        this.identityListeners = /* @__PURE__ */ new Set();
        this.lastUpdateTime = null;
        if (config.certificateFile === void 0 !== (config.privateKeyFile === void 0)) {
          throw new Error("certificateFile and privateKeyFile must be set or unset together");
        }
        if (config.certificateFile === void 0 && config.caCertificateFile === void 0) {
          throw new Error("At least one of certificateFile and caCertificateFile must be set");
        }
        trace2("File watcher constructed with config " + JSON.stringify(config));
      }
      updateCertificates() {
        if (this.fileResultPromise) {
          return;
        }
        this.fileResultPromise = Promise.allSettled([
          this.config.certificateFile ? readFilePromise(this.config.certificateFile) : Promise.reject(),
          this.config.privateKeyFile ? readFilePromise(this.config.privateKeyFile) : Promise.reject(),
          this.config.caCertificateFile ? readFilePromise(this.config.caCertificateFile) : Promise.reject()
        ]);
        this.fileResultPromise.then(([certificateResult, privateKeyResult, caCertificateResult]) => {
          if (!this.refreshTimer) {
            return;
          }
          trace2("File watcher read certificates certificate " + certificateResult.status + ", privateKey " + privateKeyResult.status + ", CA certificate " + caCertificateResult.status);
          this.lastUpdateTime = /* @__PURE__ */ new Date();
          this.fileResultPromise = null;
          if (certificateResult.status === "fulfilled" && privateKeyResult.status === "fulfilled") {
            this.latestIdentityUpdate = {
              certificate: certificateResult.value,
              privateKey: privateKeyResult.value
            };
          } else {
            this.latestIdentityUpdate = null;
          }
          if (caCertificateResult.status === "fulfilled") {
            this.latestCaUpdate = {
              caCertificate: caCertificateResult.value
            };
          } else {
            this.latestCaUpdate = null;
          }
          for (const listener of this.identityListeners) {
            listener(this.latestIdentityUpdate);
          }
          for (const listener of this.caListeners) {
            listener(this.latestCaUpdate);
          }
        });
        trace2("File watcher initiated certificate update");
      }
      maybeStartWatchingFiles() {
        if (!this.refreshTimer) {
          const timeSinceLastUpdate = this.lastUpdateTime ? (/* @__PURE__ */ new Date()).getTime() - this.lastUpdateTime.getTime() : Infinity;
          if (timeSinceLastUpdate > this.config.refreshIntervalMs) {
            this.updateCertificates();
          }
          if (timeSinceLastUpdate > this.config.refreshIntervalMs * 2) {
            this.latestCaUpdate = void 0;
            this.latestIdentityUpdate = void 0;
          }
          this.refreshTimer = setInterval(() => this.updateCertificates(), this.config.refreshIntervalMs);
          trace2("File watcher started watching");
        }
      }
      maybeStopWatchingFiles() {
        if (this.caListeners.size === 0 && this.identityListeners.size === 0) {
          this.fileResultPromise = null;
          if (this.refreshTimer) {
            clearInterval(this.refreshTimer);
            this.refreshTimer = null;
          }
        }
      }
      addCaCertificateListener(listener) {
        this.caListeners.add(listener);
        this.maybeStartWatchingFiles();
        if (this.latestCaUpdate !== void 0) {
          process.nextTick(listener, this.latestCaUpdate);
        }
      }
      removeCaCertificateListener(listener) {
        this.caListeners.delete(listener);
        this.maybeStopWatchingFiles();
      }
      addIdentityCertificateListener(listener) {
        this.identityListeners.add(listener);
        this.maybeStartWatchingFiles();
        if (this.latestIdentityUpdate !== void 0) {
          process.nextTick(listener, this.latestIdentityUpdate);
        }
      }
      removeIdentityCertificateListener(listener) {
        this.identityListeners.delete(listener);
        this.maybeStopWatchingFiles();
      }
    };
    exports2.FileWatcherCertificateProvider = FileWatcherCertificateProvider;
  }
});

// node_modules/@grpc/grpc-js/build/src/experimental.js
var require_experimental = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/experimental.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = exports2.createCertificateProviderChannelCredentials = exports2.FileWatcherCertificateProvider = exports2.createCertificateProviderServerCredentials = exports2.createServerCredentialsWithInterceptors = exports2.BaseSubchannelWrapper = exports2.registerAdminService = exports2.FilterStackFactory = exports2.BaseFilter = exports2.PickResultType = exports2.QueuePicker = exports2.UnavailablePicker = exports2.ChildLoadBalancerHandler = exports2.EndpointMap = exports2.endpointHasAddress = exports2.endpointToString = exports2.subchannelAddressToString = exports2.LeafLoadBalancer = exports2.isLoadBalancerNameRegistered = exports2.parseLoadBalancingConfig = exports2.selectLbConfigFromList = exports2.registerLoadBalancerType = exports2.createChildChannelControlHelper = exports2.BackoffTimeout = exports2.parseDuration = exports2.durationToMs = exports2.splitHostPort = exports2.uriToString = exports2.createResolver = exports2.registerResolver = exports2.log = exports2.trace = void 0;
    var logging_1 = require_logging();
    Object.defineProperty(exports2, "trace", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return logging_1.trace;
    }, "get") });
    Object.defineProperty(exports2, "log", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return logging_1.log;
    }, "get") });
    var resolver_1 = require_resolver();
    Object.defineProperty(exports2, "registerResolver", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return resolver_1.registerResolver;
    }, "get") });
    Object.defineProperty(exports2, "createResolver", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return resolver_1.createResolver;
    }, "get") });
    var uri_parser_1 = require_uri_parser();
    Object.defineProperty(exports2, "uriToString", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return uri_parser_1.uriToString;
    }, "get") });
    Object.defineProperty(exports2, "splitHostPort", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return uri_parser_1.splitHostPort;
    }, "get") });
    var duration_1 = require_duration();
    Object.defineProperty(exports2, "durationToMs", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return duration_1.durationToMs;
    }, "get") });
    Object.defineProperty(exports2, "parseDuration", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return duration_1.parseDuration;
    }, "get") });
    var backoff_timeout_1 = require_backoff_timeout();
    Object.defineProperty(exports2, "BackoffTimeout", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return backoff_timeout_1.BackoffTimeout;
    }, "get") });
    var load_balancer_1 = require_load_balancer();
    Object.defineProperty(exports2, "createChildChannelControlHelper", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return load_balancer_1.createChildChannelControlHelper;
    }, "get") });
    Object.defineProperty(exports2, "registerLoadBalancerType", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return load_balancer_1.registerLoadBalancerType;
    }, "get") });
    Object.defineProperty(exports2, "selectLbConfigFromList", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return load_balancer_1.selectLbConfigFromList;
    }, "get") });
    Object.defineProperty(exports2, "parseLoadBalancingConfig", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return load_balancer_1.parseLoadBalancingConfig;
    }, "get") });
    Object.defineProperty(exports2, "isLoadBalancerNameRegistered", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return load_balancer_1.isLoadBalancerNameRegistered;
    }, "get") });
    var load_balancer_pick_first_1 = require_load_balancer_pick_first();
    Object.defineProperty(exports2, "LeafLoadBalancer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return load_balancer_pick_first_1.LeafLoadBalancer;
    }, "get") });
    var subchannel_address_1 = require_subchannel_address();
    Object.defineProperty(exports2, "subchannelAddressToString", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return subchannel_address_1.subchannelAddressToString;
    }, "get") });
    Object.defineProperty(exports2, "endpointToString", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return subchannel_address_1.endpointToString;
    }, "get") });
    Object.defineProperty(exports2, "endpointHasAddress", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return subchannel_address_1.endpointHasAddress;
    }, "get") });
    Object.defineProperty(exports2, "EndpointMap", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return subchannel_address_1.EndpointMap;
    }, "get") });
    var load_balancer_child_handler_1 = require_load_balancer_child_handler();
    Object.defineProperty(exports2, "ChildLoadBalancerHandler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return load_balancer_child_handler_1.ChildLoadBalancerHandler;
    }, "get") });
    var picker_1 = require_picker();
    Object.defineProperty(exports2, "UnavailablePicker", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return picker_1.UnavailablePicker;
    }, "get") });
    Object.defineProperty(exports2, "QueuePicker", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return picker_1.QueuePicker;
    }, "get") });
    Object.defineProperty(exports2, "PickResultType", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return picker_1.PickResultType;
    }, "get") });
    var filter_1 = require_filter();
    Object.defineProperty(exports2, "BaseFilter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return filter_1.BaseFilter;
    }, "get") });
    var filter_stack_1 = require_filter_stack();
    Object.defineProperty(exports2, "FilterStackFactory", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return filter_stack_1.FilterStackFactory;
    }, "get") });
    var admin_1 = require_admin();
    Object.defineProperty(exports2, "registerAdminService", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return admin_1.registerAdminService;
    }, "get") });
    var subchannel_interface_1 = require_subchannel_interface();
    Object.defineProperty(exports2, "BaseSubchannelWrapper", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return subchannel_interface_1.BaseSubchannelWrapper;
    }, "get") });
    var server_credentials_1 = require_server_credentials();
    Object.defineProperty(exports2, "createServerCredentialsWithInterceptors", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return server_credentials_1.createServerCredentialsWithInterceptors;
    }, "get") });
    Object.defineProperty(exports2, "createCertificateProviderServerCredentials", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return server_credentials_1.createCertificateProviderServerCredentials;
    }, "get") });
    var certificate_provider_1 = require_certificate_provider();
    Object.defineProperty(exports2, "FileWatcherCertificateProvider", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return certificate_provider_1.FileWatcherCertificateProvider;
    }, "get") });
    var channel_credentials_1 = require_channel_credentials();
    Object.defineProperty(exports2, "createCertificateProviderChannelCredentials", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return channel_credentials_1.createCertificateProviderChannelCredentials;
    }, "get") });
    var internal_channel_1 = require_internal_channel();
    Object.defineProperty(exports2, "SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return internal_channel_1.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX;
    }, "get") });
  }
});

// node_modules/@grpc/grpc-js/build/src/resolver-uds.js
var require_resolver_uds = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/resolver-uds.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.setup = setup;
    var resolver_1 = require_resolver();
    var UdsResolver = class {
      static {
        __name(this, "UdsResolver");
      }
      constructor(target, listener, channelOptions) {
        this.listener = listener;
        this.hasReturnedResult = false;
        this.endpoints = [];
        let path108;
        if (target.authority === "") {
          path108 = "/" + target.path;
        } else {
          path108 = target.path;
        }
        this.endpoints = [{ addresses: [{ path: path108 }] }];
      }
      updateResolution() {
        if (!this.hasReturnedResult) {
          this.hasReturnedResult = true;
          process.nextTick(this.listener.onSuccessfulResolution, this.endpoints, null, null, null, {});
        }
      }
      destroy() {
        this.hasReturnedResult = false;
      }
      static getDefaultAuthority(target) {
        return "localhost";
      }
    };
    function setup() {
      (0, resolver_1.registerResolver)("unix", UdsResolver);
    }
    __name(setup, "setup");
  }
});

// node_modules/@grpc/grpc-js/build/src/resolver-ip.js
var require_resolver_ip = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/resolver-ip.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.setup = setup;
    var net_1 = __require("net");
    var constants_1 = require_constants9();
    var metadata_1 = require_metadata3();
    var resolver_1 = require_resolver();
    var uri_parser_1 = require_uri_parser();
    var logging = require_logging();
    var TRACER_NAME = "ip_resolver";
    function trace2(text) {
      logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    var IPV4_SCHEME = "ipv4";
    var IPV6_SCHEME = "ipv6";
    var DEFAULT_PORT = 443;
    var IpResolver = class {
      static {
        __name(this, "IpResolver");
      }
      constructor(target, listener, channelOptions) {
        var _a6;
        this.listener = listener;
        this.endpoints = [];
        this.error = null;
        this.hasReturnedResult = false;
        trace2("Resolver constructed for target " + (0, uri_parser_1.uriToString)(target));
        const addresses = [];
        if (!(target.scheme === IPV4_SCHEME || target.scheme === IPV6_SCHEME)) {
          this.error = {
            code: constants_1.Status.UNAVAILABLE,
            details: `Unrecognized scheme ${target.scheme} in IP resolver`,
            metadata: new metadata_1.Metadata()
          };
          return;
        }
        const pathList = target.path.split(",");
        for (const path108 of pathList) {
          const hostPort = (0, uri_parser_1.splitHostPort)(path108);
          if (hostPort === null) {
            this.error = {
              code: constants_1.Status.UNAVAILABLE,
              details: `Failed to parse ${target.scheme} address ${path108}`,
              metadata: new metadata_1.Metadata()
            };
            return;
          }
          if (target.scheme === IPV4_SCHEME && !(0, net_1.isIPv4)(hostPort.host) || target.scheme === IPV6_SCHEME && !(0, net_1.isIPv6)(hostPort.host)) {
            this.error = {
              code: constants_1.Status.UNAVAILABLE,
              details: `Failed to parse ${target.scheme} address ${path108}`,
              metadata: new metadata_1.Metadata()
            };
            return;
          }
          addresses.push({
            host: hostPort.host,
            port: (_a6 = hostPort.port) !== null && _a6 !== void 0 ? _a6 : DEFAULT_PORT
          });
        }
        this.endpoints = addresses.map((address) => ({ addresses: [address] }));
        trace2("Parsed " + target.scheme + " address list " + addresses);
      }
      updateResolution() {
        if (!this.hasReturnedResult) {
          this.hasReturnedResult = true;
          process.nextTick(() => {
            if (this.error) {
              this.listener.onError(this.error);
            } else {
              this.listener.onSuccessfulResolution(this.endpoints, null, null, null, {});
            }
          });
        }
      }
      destroy() {
        this.hasReturnedResult = false;
      }
      static getDefaultAuthority(target) {
        return target.path.split(",")[0];
      }
    };
    function setup() {
      (0, resolver_1.registerResolver)(IPV4_SCHEME, IpResolver);
      (0, resolver_1.registerResolver)(IPV6_SCHEME, IpResolver);
    }
    __name(setup, "setup");
  }
});

// node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js
var require_load_balancer_round_robin = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RoundRobinLoadBalancer = void 0;
    exports2.setup = setup;
    var load_balancer_1 = require_load_balancer();
    var connectivity_state_1 = require_connectivity_state();
    var picker_1 = require_picker();
    var logging = require_logging();
    var constants_1 = require_constants9();
    var subchannel_address_1 = require_subchannel_address();
    var load_balancer_pick_first_1 = require_load_balancer_pick_first();
    var TRACER_NAME = "round_robin";
    function trace2(text) {
      logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    var TYPE_NAME = "round_robin";
    var RoundRobinLoadBalancingConfig = class _RoundRobinLoadBalancingConfig {
      static {
        __name(this, "RoundRobinLoadBalancingConfig");
      }
      getLoadBalancerName() {
        return TYPE_NAME;
      }
      constructor() {
      }
      toJsonObject() {
        return {
          [TYPE_NAME]: {}
        };
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      static createFromJson(obj) {
        return new _RoundRobinLoadBalancingConfig();
      }
    };
    var RoundRobinPicker = class {
      static {
        __name(this, "RoundRobinPicker");
      }
      constructor(children, nextIndex = 0) {
        this.children = children;
        this.nextIndex = nextIndex;
      }
      pick(pickArgs) {
        const childPicker = this.children[this.nextIndex].picker;
        this.nextIndex = (this.nextIndex + 1) % this.children.length;
        return childPicker.pick(pickArgs);
      }
      /**
       * Check what the next subchannel returned would be. Used by the load
       * balancer implementation to preserve this part of the picker state if
       * possible when a subchannel connects or disconnects.
       */
      peekNextEndpoint() {
        return this.children[this.nextIndex].endpoint;
      }
    };
    var RoundRobinLoadBalancer = class {
      static {
        __name(this, "RoundRobinLoadBalancer");
      }
      constructor(channelControlHelper) {
        this.channelControlHelper = channelControlHelper;
        this.children = [];
        this.currentState = connectivity_state_1.ConnectivityState.IDLE;
        this.currentReadyPicker = null;
        this.updatesPaused = false;
        this.lastError = null;
        this.childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, {
          updateState: /* @__PURE__ */ __name((connectivityState, picker, errorMessage) => {
            if (this.currentState === connectivity_state_1.ConnectivityState.READY && connectivityState !== connectivity_state_1.ConnectivityState.READY) {
              this.channelControlHelper.requestReresolution();
            }
            if (errorMessage) {
              this.lastError = errorMessage;
            }
            this.calculateAndUpdateState();
          }, "updateState")
        });
      }
      countChildrenWithState(state) {
        return this.children.filter((child) => child.getConnectivityState() === state).length;
      }
      calculateAndUpdateState() {
        if (this.updatesPaused) {
          return;
        }
        if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.READY) > 0) {
          const readyChildren = this.children.filter((child) => child.getConnectivityState() === connectivity_state_1.ConnectivityState.READY);
          let index = 0;
          if (this.currentReadyPicker !== null) {
            const nextPickedEndpoint = this.currentReadyPicker.peekNextEndpoint();
            index = readyChildren.findIndex((child) => (0, subchannel_address_1.endpointEqual)(child.getEndpoint(), nextPickedEndpoint));
            if (index < 0) {
              index = 0;
            }
          }
          this.updateState(connectivity_state_1.ConnectivityState.READY, new RoundRobinPicker(readyChildren.map((child) => ({
            endpoint: child.getEndpoint(),
            picker: child.getPicker()
          })), index), null);
        } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) {
          this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null);
        } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) {
          const errorMessage = `round_robin: No connection established. Last error: ${this.lastError}`;
          this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({
            details: errorMessage
          }), errorMessage);
        } else {
          this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null);
        }
        for (const child of this.children) {
          if (child.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) {
            child.exitIdle();
          }
        }
      }
      updateState(newState, picker, errorMessage) {
        trace2(connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[newState]);
        if (newState === connectivity_state_1.ConnectivityState.READY) {
          this.currentReadyPicker = picker;
        } else {
          this.currentReadyPicker = null;
        }
        this.currentState = newState;
        this.channelControlHelper.updateState(newState, picker, errorMessage);
      }
      resetSubchannelList() {
        for (const child of this.children) {
          child.destroy();
        }
      }
      updateAddressList(endpointList, lbConfig, options2) {
        this.resetSubchannelList();
        trace2("Connect to endpoint list " + endpointList.map(subchannel_address_1.endpointToString));
        this.updatesPaused = true;
        this.children = endpointList.map((endpoint) => new load_balancer_pick_first_1.LeafLoadBalancer(endpoint, this.childChannelControlHelper, options2));
        for (const child of this.children) {
          child.startConnecting();
        }
        this.updatesPaused = false;
        this.calculateAndUpdateState();
      }
      exitIdle() {
      }
      resetBackoff() {
      }
      destroy() {
        this.resetSubchannelList();
      }
      getTypeName() {
        return TYPE_NAME;
      }
    };
    exports2.RoundRobinLoadBalancer = RoundRobinLoadBalancer;
    function setup() {
      (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, RoundRobinLoadBalancer, RoundRobinLoadBalancingConfig);
    }
    __name(setup, "setup");
  }
});

// node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js
var require_load_balancer_outlier_detection = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var _a6;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OutlierDetectionLoadBalancer = exports2.OutlierDetectionLoadBalancingConfig = void 0;
    exports2.setup = setup;
    var connectivity_state_1 = require_connectivity_state();
    var constants_1 = require_constants9();
    var duration_1 = require_duration();
    var experimental_1 = require_experimental();
    var load_balancer_1 = require_load_balancer();
    var load_balancer_child_handler_1 = require_load_balancer_child_handler();
    var picker_1 = require_picker();
    var subchannel_address_1 = require_subchannel_address();
    var subchannel_interface_1 = require_subchannel_interface();
    var logging = require_logging();
    var TRACER_NAME = "outlier_detection";
    function trace2(text) {
      logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    var TYPE_NAME = "outlier_detection";
    var OUTLIER_DETECTION_ENABLED = ((_a6 = process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION) !== null && _a6 !== void 0 ? _a6 : "true") === "true";
    var defaultSuccessRateEjectionConfig = {
      stdev_factor: 1900,
      enforcement_percentage: 100,
      minimum_hosts: 5,
      request_volume: 100
    };
    var defaultFailurePercentageEjectionConfig = {
      threshold: 85,
      enforcement_percentage: 100,
      minimum_hosts: 5,
      request_volume: 50
    };
    function validateFieldType(obj, fieldName, expectedType, objectName) {
      if (fieldName in obj && obj[fieldName] !== void 0 && typeof obj[fieldName] !== expectedType) {
        const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName;
        throw new Error(`outlier detection config ${fullFieldName} parse error: expected ${expectedType}, got ${typeof obj[fieldName]}`);
      }
    }
    __name(validateFieldType, "validateFieldType");
    function validatePositiveDuration(obj, fieldName, objectName) {
      const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName;
      if (fieldName in obj && obj[fieldName] !== void 0) {
        if (!(0, duration_1.isDuration)(obj[fieldName])) {
          throw new Error(`outlier detection config ${fullFieldName} parse error: expected Duration, got ${typeof obj[fieldName]}`);
        }
        if (!(obj[fieldName].seconds >= 0 && obj[fieldName].seconds <= 315576e6 && obj[fieldName].nanos >= 0 && obj[fieldName].nanos <= 999999999)) {
          throw new Error(`outlier detection config ${fullFieldName} parse error: values out of range for non-negative Duaration`);
        }
      }
    }
    __name(validatePositiveDuration, "validatePositiveDuration");
    function validatePercentage(obj, fieldName, objectName) {
      const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName;
      validateFieldType(obj, fieldName, "number", objectName);
      if (fieldName in obj && obj[fieldName] !== void 0 && !(obj[fieldName] >= 0 && obj[fieldName] <= 100)) {
        throw new Error(`outlier detection config ${fullFieldName} parse error: value out of range for percentage (0-100)`);
      }
    }
    __name(validatePercentage, "validatePercentage");
    var OutlierDetectionLoadBalancingConfig = class _OutlierDetectionLoadBalancingConfig {
      static {
        __name(this, "OutlierDetectionLoadBalancingConfig");
      }
      constructor(intervalMs, baseEjectionTimeMs, maxEjectionTimeMs, maxEjectionPercent, successRateEjection, failurePercentageEjection, childPolicy) {
        this.childPolicy = childPolicy;
        if (childPolicy.getLoadBalancerName() === "pick_first") {
          throw new Error("outlier_detection LB policy cannot have a pick_first child policy");
        }
        this.intervalMs = intervalMs !== null && intervalMs !== void 0 ? intervalMs : 1e4;
        this.baseEjectionTimeMs = baseEjectionTimeMs !== null && baseEjectionTimeMs !== void 0 ? baseEjectionTimeMs : 3e4;
        this.maxEjectionTimeMs = maxEjectionTimeMs !== null && maxEjectionTimeMs !== void 0 ? maxEjectionTimeMs : 3e5;
        this.maxEjectionPercent = maxEjectionPercent !== null && maxEjectionPercent !== void 0 ? maxEjectionPercent : 10;
        this.successRateEjection = successRateEjection ? Object.assign(Object.assign({}, defaultSuccessRateEjectionConfig), successRateEjection) : null;
        this.failurePercentageEjection = failurePercentageEjection ? Object.assign(Object.assign({}, defaultFailurePercentageEjectionConfig), failurePercentageEjection) : null;
      }
      getLoadBalancerName() {
        return TYPE_NAME;
      }
      toJsonObject() {
        var _a7, _b2;
        return {
          outlier_detection: {
            interval: (0, duration_1.msToDuration)(this.intervalMs),
            base_ejection_time: (0, duration_1.msToDuration)(this.baseEjectionTimeMs),
            max_ejection_time: (0, duration_1.msToDuration)(this.maxEjectionTimeMs),
            max_ejection_percent: this.maxEjectionPercent,
            success_rate_ejection: (_a7 = this.successRateEjection) !== null && _a7 !== void 0 ? _a7 : void 0,
            failure_percentage_ejection: (_b2 = this.failurePercentageEjection) !== null && _b2 !== void 0 ? _b2 : void 0,
            child_policy: [this.childPolicy.toJsonObject()]
          }
        };
      }
      getIntervalMs() {
        return this.intervalMs;
      }
      getBaseEjectionTimeMs() {
        return this.baseEjectionTimeMs;
      }
      getMaxEjectionTimeMs() {
        return this.maxEjectionTimeMs;
      }
      getMaxEjectionPercent() {
        return this.maxEjectionPercent;
      }
      getSuccessRateEjectionConfig() {
        return this.successRateEjection;
      }
      getFailurePercentageEjectionConfig() {
        return this.failurePercentageEjection;
      }
      getChildPolicy() {
        return this.childPolicy;
      }
      static createFromJson(obj) {
        var _a7;
        validatePositiveDuration(obj, "interval");
        validatePositiveDuration(obj, "base_ejection_time");
        validatePositiveDuration(obj, "max_ejection_time");
        validatePercentage(obj, "max_ejection_percent");
        if ("success_rate_ejection" in obj && obj.success_rate_ejection !== void 0) {
          if (typeof obj.success_rate_ejection !== "object") {
            throw new Error("outlier detection config success_rate_ejection must be an object");
          }
          validateFieldType(obj.success_rate_ejection, "stdev_factor", "number", "success_rate_ejection");
          validatePercentage(obj.success_rate_ejection, "enforcement_percentage", "success_rate_ejection");
          validateFieldType(obj.success_rate_ejection, "minimum_hosts", "number", "success_rate_ejection");
          validateFieldType(obj.success_rate_ejection, "request_volume", "number", "success_rate_ejection");
        }
        if ("failure_percentage_ejection" in obj && obj.failure_percentage_ejection !== void 0) {
          if (typeof obj.failure_percentage_ejection !== "object") {
            throw new Error("outlier detection config failure_percentage_ejection must be an object");
          }
          validatePercentage(obj.failure_percentage_ejection, "threshold", "failure_percentage_ejection");
          validatePercentage(obj.failure_percentage_ejection, "enforcement_percentage", "failure_percentage_ejection");
          validateFieldType(obj.failure_percentage_ejection, "minimum_hosts", "number", "failure_percentage_ejection");
          validateFieldType(obj.failure_percentage_ejection, "request_volume", "number", "failure_percentage_ejection");
        }
        if (!("child_policy" in obj) || !Array.isArray(obj.child_policy)) {
          throw new Error("outlier detection config child_policy must be an array");
        }
        const childPolicy = (0, load_balancer_1.selectLbConfigFromList)(obj.child_policy);
        if (!childPolicy) {
          throw new Error("outlier detection config child_policy: no valid recognized policy found");
        }
        return new _OutlierDetectionLoadBalancingConfig(obj.interval ? (0, duration_1.durationToMs)(obj.interval) : null, obj.base_ejection_time ? (0, duration_1.durationToMs)(obj.base_ejection_time) : null, obj.max_ejection_time ? (0, duration_1.durationToMs)(obj.max_ejection_time) : null, (_a7 = obj.max_ejection_percent) !== null && _a7 !== void 0 ? _a7 : null, obj.success_rate_ejection, obj.failure_percentage_ejection, childPolicy);
      }
    };
    exports2.OutlierDetectionLoadBalancingConfig = OutlierDetectionLoadBalancingConfig;
    var OutlierDetectionSubchannelWrapper = class extends subchannel_interface_1.BaseSubchannelWrapper {
      static {
        __name(this, "OutlierDetectionSubchannelWrapper");
      }
      constructor(childSubchannel, mapEntry) {
        super(childSubchannel);
        this.mapEntry = mapEntry;
        this.refCount = 0;
      }
      ref() {
        this.child.ref();
        this.refCount += 1;
      }
      unref() {
        this.child.unref();
        this.refCount -= 1;
        if (this.refCount <= 0) {
          if (this.mapEntry) {
            const index = this.mapEntry.subchannelWrappers.indexOf(this);
            if (index >= 0) {
              this.mapEntry.subchannelWrappers.splice(index, 1);
            }
          }
        }
      }
      eject() {
        this.setHealthy(false);
      }
      uneject() {
        this.setHealthy(true);
      }
      getMapEntry() {
        return this.mapEntry;
      }
      getWrappedSubchannel() {
        return this.child;
      }
    };
    function createEmptyBucket() {
      return {
        success: 0,
        failure: 0
      };
    }
    __name(createEmptyBucket, "createEmptyBucket");
    var CallCounter = class {
      static {
        __name(this, "CallCounter");
      }
      constructor() {
        this.activeBucket = createEmptyBucket();
        this.inactiveBucket = createEmptyBucket();
      }
      addSuccess() {
        this.activeBucket.success += 1;
      }
      addFailure() {
        this.activeBucket.failure += 1;
      }
      switchBuckets() {
        this.inactiveBucket = this.activeBucket;
        this.activeBucket = createEmptyBucket();
      }
      getLastSuccesses() {
        return this.inactiveBucket.success;
      }
      getLastFailures() {
        return this.inactiveBucket.failure;
      }
    };
    var OutlierDetectionPicker = class {
      static {
        __name(this, "OutlierDetectionPicker");
      }
      constructor(wrappedPicker, countCalls) {
        this.wrappedPicker = wrappedPicker;
        this.countCalls = countCalls;
      }
      pick(pickArgs) {
        const wrappedPick = this.wrappedPicker.pick(pickArgs);
        if (wrappedPick.pickResultType === picker_1.PickResultType.COMPLETE) {
          const subchannelWrapper = wrappedPick.subchannel;
          const mapEntry = subchannelWrapper.getMapEntry();
          if (mapEntry) {
            let onCallEnded = wrappedPick.onCallEnded;
            if (this.countCalls) {
              onCallEnded = /* @__PURE__ */ __name((statusCode) => {
                var _a7;
                if (statusCode === constants_1.Status.OK) {
                  mapEntry.counter.addSuccess();
                } else {
                  mapEntry.counter.addFailure();
                }
                (_a7 = wrappedPick.onCallEnded) === null || _a7 === void 0 ? void 0 : _a7.call(wrappedPick, statusCode);
              }, "onCallEnded");
            }
            return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel(), onCallEnded });
          } else {
            return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel() });
          }
        } else {
          return wrappedPick;
        }
      }
    };
    var OutlierDetectionLoadBalancer = class {
      static {
        __name(this, "OutlierDetectionLoadBalancer");
      }
      constructor(channelControlHelper) {
        this.entryMap = new subchannel_address_1.EndpointMap();
        this.latestConfig = null;
        this.timerStartTime = null;
        this.childBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler((0, experimental_1.createChildChannelControlHelper)(channelControlHelper, {
          createSubchannel: /* @__PURE__ */ __name((subchannelAddress, subchannelArgs) => {
            const originalSubchannel = channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs);
            const mapEntry = this.entryMap.getForSubchannelAddress(subchannelAddress);
            const subchannelWrapper = new OutlierDetectionSubchannelWrapper(originalSubchannel, mapEntry);
            if ((mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.currentEjectionTimestamp) !== null) {
              subchannelWrapper.eject();
            }
            mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.subchannelWrappers.push(subchannelWrapper);
            return subchannelWrapper;
          }, "createSubchannel"),
          updateState: /* @__PURE__ */ __name((connectivityState, picker, errorMessage) => {
            if (connectivityState === connectivity_state_1.ConnectivityState.READY) {
              channelControlHelper.updateState(connectivityState, new OutlierDetectionPicker(picker, this.isCountingEnabled()), errorMessage);
            } else {
              channelControlHelper.updateState(connectivityState, picker, errorMessage);
            }
          }, "updateState")
        }));
        this.ejectionTimer = setInterval(() => {
        }, 0);
        clearInterval(this.ejectionTimer);
      }
      isCountingEnabled() {
        return this.latestConfig !== null && (this.latestConfig.getSuccessRateEjectionConfig() !== null || this.latestConfig.getFailurePercentageEjectionConfig() !== null);
      }
      getCurrentEjectionPercent() {
        let ejectionCount = 0;
        for (const mapEntry of this.entryMap.values()) {
          if (mapEntry.currentEjectionTimestamp !== null) {
            ejectionCount += 1;
          }
        }
        return ejectionCount * 100 / this.entryMap.size;
      }
      runSuccessRateCheck(ejectionTimestamp) {
        if (!this.latestConfig) {
          return;
        }
        const successRateConfig = this.latestConfig.getSuccessRateEjectionConfig();
        if (!successRateConfig) {
          return;
        }
        trace2("Running success rate check");
        const targetRequestVolume = successRateConfig.request_volume;
        let addresesWithTargetVolume = 0;
        const successRates = [];
        for (const [endpoint, mapEntry] of this.entryMap.entries()) {
          const successes = mapEntry.counter.getLastSuccesses();
          const failures = mapEntry.counter.getLastFailures();
          trace2("Stats for " + (0, subchannel_address_1.endpointToString)(endpoint) + ": successes=" + successes + " failures=" + failures + " targetRequestVolume=" + targetRequestVolume);
          if (successes + failures >= targetRequestVolume) {
            addresesWithTargetVolume += 1;
            successRates.push(successes / (successes + failures));
          }
        }
        trace2("Found " + addresesWithTargetVolume + " success rate candidates; currentEjectionPercent=" + this.getCurrentEjectionPercent() + " successRates=[" + successRates + "]");
        if (addresesWithTargetVolume < successRateConfig.minimum_hosts) {
          return;
        }
        const successRateMean = successRates.reduce((a, b) => a + b) / successRates.length;
        let successRateDeviationSum = 0;
        for (const rate of successRates) {
          const deviation = rate - successRateMean;
          successRateDeviationSum += deviation * deviation;
        }
        const successRateVariance = successRateDeviationSum / successRates.length;
        const successRateStdev = Math.sqrt(successRateVariance);
        const ejectionThreshold = successRateMean - successRateStdev * (successRateConfig.stdev_factor / 1e3);
        trace2("stdev=" + successRateStdev + " ejectionThreshold=" + ejectionThreshold);
        for (const [address, mapEntry] of this.entryMap.entries()) {
          if (this.getCurrentEjectionPercent() >= this.latestConfig.getMaxEjectionPercent()) {
            break;
          }
          const successes = mapEntry.counter.getLastSuccesses();
          const failures = mapEntry.counter.getLastFailures();
          if (successes + failures < targetRequestVolume) {
            continue;
          }
          const successRate = successes / (successes + failures);
          trace2("Checking candidate " + address + " successRate=" + successRate);
          if (successRate < ejectionThreshold) {
            const randomNumber = Math.random() * 100;
            trace2("Candidate " + address + " randomNumber=" + randomNumber + " enforcement_percentage=" + successRateConfig.enforcement_percentage);
            if (randomNumber < successRateConfig.enforcement_percentage) {
              trace2("Ejecting candidate " + address);
              this.eject(mapEntry, ejectionTimestamp);
            }
          }
        }
      }
      runFailurePercentageCheck(ejectionTimestamp) {
        if (!this.latestConfig) {
          return;
        }
        const failurePercentageConfig = this.latestConfig.getFailurePercentageEjectionConfig();
        if (!failurePercentageConfig) {
          return;
        }
        trace2("Running failure percentage check. threshold=" + failurePercentageConfig.threshold + " request volume threshold=" + failurePercentageConfig.request_volume);
        let addressesWithTargetVolume = 0;
        for (const mapEntry of this.entryMap.values()) {
          const successes = mapEntry.counter.getLastSuccesses();
          const failures = mapEntry.counter.getLastFailures();
          if (successes + failures >= failurePercentageConfig.request_volume) {
            addressesWithTargetVolume += 1;
          }
        }
        if (addressesWithTargetVolume < failurePercentageConfig.minimum_hosts) {
          return;
        }
        for (const [address, mapEntry] of this.entryMap.entries()) {
          if (this.getCurrentEjectionPercent() >= this.latestConfig.getMaxEjectionPercent()) {
            break;
          }
          const successes = mapEntry.counter.getLastSuccesses();
          const failures = mapEntry.counter.getLastFailures();
          trace2("Candidate successes=" + successes + " failures=" + failures);
          if (successes + failures < failurePercentageConfig.request_volume) {
            continue;
          }
          const failurePercentage = failures * 100 / (failures + successes);
          if (failurePercentage > failurePercentageConfig.threshold) {
            const randomNumber = Math.random() * 100;
            trace2("Candidate " + address + " randomNumber=" + randomNumber + " enforcement_percentage=" + failurePercentageConfig.enforcement_percentage);
            if (randomNumber < failurePercentageConfig.enforcement_percentage) {
              trace2("Ejecting candidate " + address);
              this.eject(mapEntry, ejectionTimestamp);
            }
          }
        }
      }
      eject(mapEntry, ejectionTimestamp) {
        mapEntry.currentEjectionTimestamp = /* @__PURE__ */ new Date();
        mapEntry.ejectionTimeMultiplier += 1;
        for (const subchannelWrapper of mapEntry.subchannelWrappers) {
          subchannelWrapper.eject();
        }
      }
      uneject(mapEntry) {
        mapEntry.currentEjectionTimestamp = null;
        for (const subchannelWrapper of mapEntry.subchannelWrappers) {
          subchannelWrapper.uneject();
        }
      }
      switchAllBuckets() {
        for (const mapEntry of this.entryMap.values()) {
          mapEntry.counter.switchBuckets();
        }
      }
      startTimer(delayMs) {
        var _a7, _b2;
        this.ejectionTimer = setTimeout(() => this.runChecks(), delayMs);
        (_b2 = (_a7 = this.ejectionTimer).unref) === null || _b2 === void 0 ? void 0 : _b2.call(_a7);
      }
      runChecks() {
        const ejectionTimestamp = /* @__PURE__ */ new Date();
        trace2("Ejection timer running");
        this.switchAllBuckets();
        if (!this.latestConfig) {
          return;
        }
        this.timerStartTime = ejectionTimestamp;
        this.startTimer(this.latestConfig.getIntervalMs());
        this.runSuccessRateCheck(ejectionTimestamp);
        this.runFailurePercentageCheck(ejectionTimestamp);
        for (const [address, mapEntry] of this.entryMap.entries()) {
          if (mapEntry.currentEjectionTimestamp === null) {
            if (mapEntry.ejectionTimeMultiplier > 0) {
              mapEntry.ejectionTimeMultiplier -= 1;
            }
          } else {
            const baseEjectionTimeMs = this.latestConfig.getBaseEjectionTimeMs();
            const maxEjectionTimeMs = this.latestConfig.getMaxEjectionTimeMs();
            const returnTime = new Date(mapEntry.currentEjectionTimestamp.getTime());
            returnTime.setMilliseconds(returnTime.getMilliseconds() + Math.min(baseEjectionTimeMs * mapEntry.ejectionTimeMultiplier, Math.max(baseEjectionTimeMs, maxEjectionTimeMs)));
            if (returnTime < /* @__PURE__ */ new Date()) {
              trace2("Unejecting " + address);
              this.uneject(mapEntry);
            }
          }
        }
      }
      updateAddressList(endpointList, lbConfig, options2) {
        if (!(lbConfig instanceof OutlierDetectionLoadBalancingConfig)) {
          return;
        }
        trace2("Received update with config: " + JSON.stringify(lbConfig.toJsonObject(), void 0, 2));
        for (const endpoint of endpointList) {
          if (!this.entryMap.has(endpoint)) {
            trace2("Adding map entry for " + (0, subchannel_address_1.endpointToString)(endpoint));
            this.entryMap.set(endpoint, {
              counter: new CallCounter(),
              currentEjectionTimestamp: null,
              ejectionTimeMultiplier: 0,
              subchannelWrappers: []
            });
          }
        }
        this.entryMap.deleteMissing(endpointList);
        const childPolicy = lbConfig.getChildPolicy();
        this.childBalancer.updateAddressList(endpointList, childPolicy, options2);
        if (lbConfig.getSuccessRateEjectionConfig() || lbConfig.getFailurePercentageEjectionConfig()) {
          if (this.timerStartTime) {
            trace2("Previous timer existed. Replacing timer");
            clearTimeout(this.ejectionTimer);
            const remainingDelay = lbConfig.getIntervalMs() - ((/* @__PURE__ */ new Date()).getTime() - this.timerStartTime.getTime());
            this.startTimer(remainingDelay);
          } else {
            trace2("Starting new timer");
            this.timerStartTime = /* @__PURE__ */ new Date();
            this.startTimer(lbConfig.getIntervalMs());
            this.switchAllBuckets();
          }
        } else {
          trace2("Counting disabled. Cancelling timer.");
          this.timerStartTime = null;
          clearTimeout(this.ejectionTimer);
          for (const mapEntry of this.entryMap.values()) {
            this.uneject(mapEntry);
            mapEntry.ejectionTimeMultiplier = 0;
          }
        }
        this.latestConfig = lbConfig;
      }
      exitIdle() {
        this.childBalancer.exitIdle();
      }
      resetBackoff() {
        this.childBalancer.resetBackoff();
      }
      destroy() {
        clearTimeout(this.ejectionTimer);
        this.childBalancer.destroy();
      }
      getTypeName() {
        return TYPE_NAME;
      }
    };
    exports2.OutlierDetectionLoadBalancer = OutlierDetectionLoadBalancer;
    function setup() {
      if (OUTLIER_DETECTION_ENABLED) {
        (0, experimental_1.registerLoadBalancerType)(TYPE_NAME, OutlierDetectionLoadBalancer, OutlierDetectionLoadBalancingConfig);
      }
    }
    __name(setup, "setup");
  }
});

// node_modules/@grpc/grpc-js/build/src/index.js
var require_src11 = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.experimental = exports2.ServerInterceptingCall = exports2.ResponderBuilder = exports2.ServerListenerBuilder = exports2.addAdminServicesToServer = exports2.getChannelzHandlers = exports2.getChannelzServiceDefinition = exports2.InterceptorConfigurationError = exports2.InterceptingCall = exports2.RequesterBuilder = exports2.ListenerBuilder = exports2.StatusBuilder = exports2.getClientChannel = exports2.ServerCredentials = exports2.Server = exports2.setLogVerbosity = exports2.setLogger = exports2.load = exports2.loadObject = exports2.CallCredentials = exports2.ChannelCredentials = exports2.waitForClientReady = exports2.closeClient = exports2.Channel = exports2.makeGenericClientConstructor = exports2.makeClientConstructor = exports2.loadPackageDefinition = exports2.Client = exports2.compressionAlgorithms = exports2.propagate = exports2.connectivityState = exports2.status = exports2.logVerbosity = exports2.Metadata = exports2.credentials = void 0;
    var call_credentials_1 = require_call_credentials();
    Object.defineProperty(exports2, "CallCredentials", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return call_credentials_1.CallCredentials;
    }, "get") });
    var channel_1 = require_channel();
    Object.defineProperty(exports2, "Channel", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return channel_1.ChannelImplementation;
    }, "get") });
    var compression_algorithms_1 = require_compression_algorithms();
    Object.defineProperty(exports2, "compressionAlgorithms", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return compression_algorithms_1.CompressionAlgorithms;
    }, "get") });
    var connectivity_state_1 = require_connectivity_state();
    Object.defineProperty(exports2, "connectivityState", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return connectivity_state_1.ConnectivityState;
    }, "get") });
    var channel_credentials_1 = require_channel_credentials();
    Object.defineProperty(exports2, "ChannelCredentials", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return channel_credentials_1.ChannelCredentials;
    }, "get") });
    var client_1 = require_client2();
    Object.defineProperty(exports2, "Client", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return client_1.Client;
    }, "get") });
    var constants_1 = require_constants9();
    Object.defineProperty(exports2, "logVerbosity", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return constants_1.LogVerbosity;
    }, "get") });
    Object.defineProperty(exports2, "status", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return constants_1.Status;
    }, "get") });
    Object.defineProperty(exports2, "propagate", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return constants_1.Propagate;
    }, "get") });
    var logging = require_logging();
    var make_client_1 = require_make_client();
    Object.defineProperty(exports2, "loadPackageDefinition", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return make_client_1.loadPackageDefinition;
    }, "get") });
    Object.defineProperty(exports2, "makeClientConstructor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return make_client_1.makeClientConstructor;
    }, "get") });
    Object.defineProperty(exports2, "makeGenericClientConstructor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return make_client_1.makeClientConstructor;
    }, "get") });
    var metadata_1 = require_metadata3();
    Object.defineProperty(exports2, "Metadata", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return metadata_1.Metadata;
    }, "get") });
    var server_1 = require_server();
    Object.defineProperty(exports2, "Server", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return server_1.Server;
    }, "get") });
    var server_credentials_1 = require_server_credentials();
    Object.defineProperty(exports2, "ServerCredentials", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return server_credentials_1.ServerCredentials;
    }, "get") });
    var status_builder_1 = require_status_builder();
    Object.defineProperty(exports2, "StatusBuilder", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return status_builder_1.StatusBuilder;
    }, "get") });
    exports2.credentials = {
      /**
       * Combine a ChannelCredentials with any number of CallCredentials into a
       * single ChannelCredentials object.
       * @param channelCredentials The ChannelCredentials object.
       * @param callCredentials Any number of CallCredentials objects.
       * @return The resulting ChannelCredentials object.
       */
      combineChannelCredentials: /* @__PURE__ */ __name((channelCredentials, ...callCredentials) => {
        return callCredentials.reduce((acc, other2) => acc.compose(other2), channelCredentials);
      }, "combineChannelCredentials"),
      /**
       * Combine any number of CallCredentials into a single CallCredentials
       * object.
       * @param first The first CallCredentials object.
       * @param additional Any number of additional CallCredentials objects.
       * @return The resulting CallCredentials object.
       */
      combineCallCredentials: /* @__PURE__ */ __name((first2, ...additional) => {
        return additional.reduce((acc, other2) => acc.compose(other2), first2);
      }, "combineCallCredentials"),
      // from channel-credentials.ts
      createInsecure: channel_credentials_1.ChannelCredentials.createInsecure,
      createSsl: channel_credentials_1.ChannelCredentials.createSsl,
      createFromSecureContext: channel_credentials_1.ChannelCredentials.createFromSecureContext,
      // from call-credentials.ts
      createFromMetadataGenerator: call_credentials_1.CallCredentials.createFromMetadataGenerator,
      createFromGoogleCredential: call_credentials_1.CallCredentials.createFromGoogleCredential,
      createEmpty: call_credentials_1.CallCredentials.createEmpty
    };
    var closeClient = /* @__PURE__ */ __name((client) => client.close(), "closeClient");
    exports2.closeClient = closeClient;
    var waitForClientReady = /* @__PURE__ */ __name((client, deadline, callback) => client.waitForReady(deadline, callback), "waitForClientReady");
    exports2.waitForClientReady = waitForClientReady;
    var loadObject = /* @__PURE__ */ __name((value, options2) => {
      throw new Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead");
    }, "loadObject");
    exports2.loadObject = loadObject;
    var load = /* @__PURE__ */ __name((filename, format4, options2) => {
      throw new Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead");
    }, "load");
    exports2.load = load;
    var setLogger = /* @__PURE__ */ __name((logger6) => {
      logging.setLogger(logger6);
    }, "setLogger");
    exports2.setLogger = setLogger;
    var setLogVerbosity = /* @__PURE__ */ __name((verbosity) => {
      logging.setLoggerVerbosity(verbosity);
    }, "setLogVerbosity");
    exports2.setLogVerbosity = setLogVerbosity;
    var getClientChannel = /* @__PURE__ */ __name((client) => {
      return client_1.Client.prototype.getChannel.call(client);
    }, "getClientChannel");
    exports2.getClientChannel = getClientChannel;
    var client_interceptors_1 = require_client_interceptors();
    Object.defineProperty(exports2, "ListenerBuilder", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return client_interceptors_1.ListenerBuilder;
    }, "get") });
    Object.defineProperty(exports2, "RequesterBuilder", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return client_interceptors_1.RequesterBuilder;
    }, "get") });
    Object.defineProperty(exports2, "InterceptingCall", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return client_interceptors_1.InterceptingCall;
    }, "get") });
    Object.defineProperty(exports2, "InterceptorConfigurationError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return client_interceptors_1.InterceptorConfigurationError;
    }, "get") });
    var channelz_1 = require_channelz();
    Object.defineProperty(exports2, "getChannelzServiceDefinition", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return channelz_1.getChannelzServiceDefinition;
    }, "get") });
    Object.defineProperty(exports2, "getChannelzHandlers", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return channelz_1.getChannelzHandlers;
    }, "get") });
    var admin_1 = require_admin();
    Object.defineProperty(exports2, "addAdminServicesToServer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return admin_1.addAdminServicesToServer;
    }, "get") });
    var server_interceptors_1 = require_server_interceptors();
    Object.defineProperty(exports2, "ServerListenerBuilder", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return server_interceptors_1.ServerListenerBuilder;
    }, "get") });
    Object.defineProperty(exports2, "ResponderBuilder", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return server_interceptors_1.ResponderBuilder;
    }, "get") });
    Object.defineProperty(exports2, "ServerInterceptingCall", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return server_interceptors_1.ServerInterceptingCall;
    }, "get") });
    var experimental = require_experimental();
    exports2.experimental = experimental;
    var resolver_dns = require_resolver_dns();
    var resolver_uds = require_resolver_uds();
    var resolver_ip = require_resolver_ip();
    var load_balancer_pick_first = require_load_balancer_pick_first();
    var load_balancer_round_robin = require_load_balancer_round_robin();
    var load_balancer_outlier_detection = require_load_balancer_outlier_detection();
    var channelz = require_channelz();
    (() => {
      resolver_dns.setup();
      resolver_uds.setup();
      resolver_ip.setup();
      load_balancer_pick_first.setup();
      load_balancer_round_robin.setup();
      load_balancer_outlier_detection.setup();
      channelz.setup();
    })();
  }
});

// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/create-service-client-constructor.js
var require_create_service_client_constructor = __commonJS({
  "node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/create-service-client-constructor.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createServiceClientConstructor = void 0;
    var grpc = require_src11();
    function createServiceClientConstructor(path108, name3) {
      const serviceDefinition = {
        export: {
          path: path108,
          requestStream: false,
          responseStream: false,
          requestSerialize: /* @__PURE__ */ __name((arg) => {
            return arg;
          }, "requestSerialize"),
          requestDeserialize: /* @__PURE__ */ __name((arg) => {
            return arg;
          }, "requestDeserialize"),
          responseSerialize: /* @__PURE__ */ __name((arg) => {
            return arg;
          }, "responseSerialize"),
          responseDeserialize: /* @__PURE__ */ __name((arg) => {
            return arg;
          }, "responseDeserialize")
        }
      };
      return grpc.makeGenericClientConstructor(serviceDefinition, name3);
    }
    __name(createServiceClientConstructor, "createServiceClientConstructor");
    exports2.createServiceClientConstructor = createServiceClientConstructor;
  }
});

// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/grpc-exporter-transport.js
var require_grpc_exporter_transport = __commonJS({
  "node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/grpc-exporter-transport.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createOtlpGrpcExporterTransport = exports2.GrpcExporterTransport = exports2.createEmptyMetadata = exports2.createSslCredentials = exports2.createInsecureCredentials = void 0;
    var GRPC_COMPRESSION_NONE = 0;
    var GRPC_COMPRESSION_GZIP = 2;
    function toGrpcCompression(compression) {
      return compression === "gzip" ? GRPC_COMPRESSION_GZIP : GRPC_COMPRESSION_NONE;
    }
    __name(toGrpcCompression, "toGrpcCompression");
    function createInsecureCredentials() {
      const {
        credentials
        // eslint-disable-next-line @typescript-eslint/no-require-imports
      } = require_src11();
      return credentials.createInsecure();
    }
    __name(createInsecureCredentials, "createInsecureCredentials");
    exports2.createInsecureCredentials = createInsecureCredentials;
    function createSslCredentials(rootCert, privateKey, certChain) {
      const {
        credentials
        // eslint-disable-next-line @typescript-eslint/no-require-imports
      } = require_src11();
      return credentials.createSsl(rootCert, privateKey, certChain);
    }
    __name(createSslCredentials, "createSslCredentials");
    exports2.createSslCredentials = createSslCredentials;
    function createEmptyMetadata() {
      const {
        Metadata
        // eslint-disable-next-line @typescript-eslint/no-require-imports
      } = require_src11();
      return new Metadata();
    }
    __name(createEmptyMetadata, "createEmptyMetadata");
    exports2.createEmptyMetadata = createEmptyMetadata;
    var GrpcExporterTransport = class {
      static {
        __name(this, "GrpcExporterTransport");
      }
      _parameters;
      _client;
      _metadata;
      constructor(_parameters) {
        this._parameters = _parameters;
      }
      shutdown() {
        this._client?.close();
      }
      send(data, timeoutMillis) {
        const buffer = Buffer.from(data);
        if (this._client == null) {
          const {
            createServiceClientConstructor
            // eslint-disable-next-line @typescript-eslint/no-require-imports
          } = require_create_service_client_constructor();
          try {
            this._metadata = this._parameters.metadata();
          } catch (error) {
            return Promise.resolve({
              status: "failure",
              error
            });
          }
          const clientConstructor = createServiceClientConstructor(this._parameters.grpcPath, this._parameters.grpcName);
          try {
            this._client = new clientConstructor(this._parameters.address, this._parameters.credentials(), {
              "grpc.default_compression_algorithm": toGrpcCompression(this._parameters.compression)
            });
          } catch (error) {
            return Promise.resolve({
              status: "failure",
              error
            });
          }
        }
        return new Promise((resolve24) => {
          const deadline = Date.now() + timeoutMillis;
          if (this._metadata == null) {
            return resolve24({
              error: new Error("metadata was null"),
              status: "failure"
            });
          }
          this._client.export(buffer, this._metadata, { deadline }, (err, response) => {
            if (err) {
              resolve24({
                status: "failure",
                error: err
              });
            } else {
              resolve24({
                data: response,
                status: "success"
              });
            }
          });
        });
      }
    };
    exports2.GrpcExporterTransport = GrpcExporterTransport;
    function createOtlpGrpcExporterTransport(options2) {
      return new GrpcExporterTransport(options2);
    }
    __name(createOtlpGrpcExporterTransport, "createOtlpGrpcExporterTransport");
    exports2.createOtlpGrpcExporterTransport = createOtlpGrpcExporterTransport;
  }
});

// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/version.js
var require_version2 = __commonJS({
  "node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/version.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.VERSION = void 0;
    exports2.VERSION = "0.203.0";
  }
});

// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-configuration.js
var require_otlp_grpc_configuration = __commonJS({
  "node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-configuration.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getOtlpGrpcDefaultConfiguration = exports2.mergeOtlpGrpcConfigurationWithDefaults = exports2.validateAndNormalizeUrl = void 0;
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var grpc_exporter_transport_1 = require_grpc_exporter_transport();
    var version_1 = require_version2();
    var url_1 = __require("url");
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    function validateAndNormalizeUrl(url2) {
      url2 = url2.trim();
      const hasProtocol = url2.match(/^([\w]{1,8}):\/\//);
      if (!hasProtocol) {
        url2 = `https://${url2}`;
      }
      const target = new url_1.URL(url2);
      if (target.protocol === "unix:") {
        return url2;
      }
      if (target.pathname && target.pathname !== "/") {
        api_1.diag.warn("URL path should not be set when using grpc, the path part of the URL will be ignored.");
      }
      if (target.protocol !== "" && !target.protocol?.match(/^(http)s?:$/)) {
        api_1.diag.warn("URL protocol should be http(s)://. Using http://.");
      }
      return target.host;
    }
    __name(validateAndNormalizeUrl, "validateAndNormalizeUrl");
    exports2.validateAndNormalizeUrl = validateAndNormalizeUrl;
    function overrideMetadataEntriesIfNotPresent(metadata, additionalMetadata) {
      for (const [key, value] of Object.entries(additionalMetadata.getMap())) {
        if (metadata.get(key).length < 1) {
          metadata.set(key, value);
        }
      }
    }
    __name(overrideMetadataEntriesIfNotPresent, "overrideMetadataEntriesIfNotPresent");
    function mergeOtlpGrpcConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) {
      const rawUrl = userProvidedConfiguration.url ?? fallbackConfiguration.url ?? defaultConfiguration.url;
      return {
        ...(0, otlp_exporter_base_1.mergeOtlpSharedConfigurationWithDefaults)(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration),
        metadata: /* @__PURE__ */ __name(() => {
          const metadata = defaultConfiguration.metadata();
          overrideMetadataEntriesIfNotPresent(
            metadata,
            // clone to ensure we don't modify what the user gave us in case they hold on to the returned reference
            userProvidedConfiguration.metadata?.().clone() ?? (0, grpc_exporter_transport_1.createEmptyMetadata)()
          );
          overrideMetadataEntriesIfNotPresent(metadata, fallbackConfiguration.metadata?.() ?? (0, grpc_exporter_transport_1.createEmptyMetadata)());
          return metadata;
        }, "metadata"),
        url: validateAndNormalizeUrl(rawUrl),
        credentials: userProvidedConfiguration.credentials ?? fallbackConfiguration.credentials?.(rawUrl) ?? defaultConfiguration.credentials(rawUrl)
      };
    }
    __name(mergeOtlpGrpcConfigurationWithDefaults, "mergeOtlpGrpcConfigurationWithDefaults");
    exports2.mergeOtlpGrpcConfigurationWithDefaults = mergeOtlpGrpcConfigurationWithDefaults;
    function getOtlpGrpcDefaultConfiguration() {
      return {
        ...(0, otlp_exporter_base_1.getSharedConfigurationDefaults)(),
        metadata: /* @__PURE__ */ __name(() => {
          const metadata = (0, grpc_exporter_transport_1.createEmptyMetadata)();
          metadata.set("User-Agent", `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`);
          return metadata;
        }, "metadata"),
        url: "http://localhost:4317",
        credentials: /* @__PURE__ */ __name((url2) => {
          if (url2.startsWith("http://")) {
            return () => (0, grpc_exporter_transport_1.createInsecureCredentials)();
          } else {
            return () => (0, grpc_exporter_transport_1.createSslCredentials)();
          }
        }, "credentials")
      };
    }
    __name(getOtlpGrpcDefaultConfiguration, "getOtlpGrpcDefaultConfiguration");
    exports2.getOtlpGrpcDefaultConfiguration = getOtlpGrpcDefaultConfiguration;
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/is-export-retryable.js
function isExportRetryable(statusCode) {
  const retryCodes = [429, 502, 503, 504];
  return retryCodes.includes(statusCode);
}
function parseRetryAfterToMills(retryAfter) {
  if (retryAfter == null) {
    return void 0;
  }
  const seconds = Number.parseInt(retryAfter, 10);
  if (Number.isInteger(seconds)) {
    return seconds > 0 ? seconds * 1e3 : -1;
  }
  const delay4 = new Date(retryAfter).getTime() - Date.now();
  if (delay4 >= 0) {
    return delay4;
  }
  return 0;
}
var init_is_export_retryable = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/is-export-retryable.js"() {
    init_esbuild_shims();
    __name(isExportRetryable, "isExportRetryable");
    __name(parseRetryAfterToMills, "parseRetryAfterToMills");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/transport/http-transport-utils.js
var http_transport_utils_exports = {};
__export(http_transport_utils_exports, {
  compressAndSend: () => compressAndSend,
  createHttpAgent: () => createHttpAgent,
  sendWithHttp: () => sendWithHttp
});
import * as http2 from "http";
import * as https2 from "https";
import * as zlib from "zlib";
import { Readable as Readable2 } from "stream";
function sendWithHttp(params, agent, data, onDone, timeoutMillis) {
  const parsedUrl = new URL(params.url);
  const options2 = {
    hostname: parsedUrl.hostname,
    port: parsedUrl.port,
    path: parsedUrl.pathname,
    method: "POST",
    headers: {
      ...params.headers()
    },
    agent
  };
  const request4 = parsedUrl.protocol === "http:" ? http2.request : https2.request;
  const req = request4(options2, (res) => {
    const responseData = [];
    res.on("data", (chunk) => responseData.push(chunk));
    res.on("end", () => {
      if (res.statusCode && res.statusCode < 299) {
        onDone({
          status: "success",
          data: Buffer.concat(responseData)
        });
      } else if (res.statusCode && isExportRetryable(res.statusCode)) {
        onDone({
          status: "retryable",
          retryInMillis: parseRetryAfterToMills(res.headers["retry-after"])
        });
      } else {
        const error = new OTLPExporterError(res.statusMessage, res.statusCode, Buffer.concat(responseData).toString());
        onDone({
          status: "failure",
          error
        });
      }
    });
  });
  req.setTimeout(timeoutMillis, () => {
    req.destroy();
    onDone({
      status: "failure",
      error: new Error("Request Timeout")
    });
  });
  req.on("error", (error) => {
    onDone({
      status: "failure",
      error
    });
  });
  compressAndSend(req, params.compression, data, (error) => {
    onDone({
      status: "failure",
      error
    });
  });
}
function compressAndSend(req, compression, data, onError2) {
  let dataStream = readableFromUint8Array(data);
  if (compression === "gzip") {
    req.setHeader("Content-Encoding", "gzip");
    dataStream = dataStream.on("error", onError2).pipe(zlib.createGzip()).on("error", onError2);
  }
  dataStream.pipe(req).on("error", onError2);
}
function readableFromUint8Array(buff) {
  const readable = new Readable2();
  readable.push(buff);
  readable.push(null);
  return readable;
}
function createHttpAgent(rawUrl, agentOptions) {
  const parsedUrl = new URL(rawUrl);
  const Agent3 = parsedUrl.protocol === "http:" ? http2.Agent : https2.Agent;
  return new Agent3(agentOptions);
}
var init_http_transport_utils = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/transport/http-transport-utils.js"() {
    init_esbuild_shims();
    init_is_export_retryable();
    init_types5();
    __name(sendWithHttp, "sendWithHttp");
    __name(compressAndSend, "compressAndSend");
    __name(readableFromUint8Array, "readableFromUint8Array");
    __name(createHttpAgent, "createHttpAgent");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/transport/http-exporter-transport.js
function createHttpExporterTransport(parameters) {
  return new HttpExporterTransport(parameters);
}
var HttpExporterTransport;
var init_http_exporter_transport = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/transport/http-exporter-transport.js"() {
    init_esbuild_shims();
    HttpExporterTransport = class {
      static {
        __name(this, "HttpExporterTransport");
      }
      _parameters;
      _utils = null;
      constructor(_parameters) {
        this._parameters = _parameters;
      }
      async send(data, timeoutMillis) {
        const { agent, send } = this._loadUtils();
        return new Promise((resolve24) => {
          send(this._parameters, agent, data, (result) => {
            resolve24(result);
          }, timeoutMillis);
        });
      }
      shutdown() {
      }
      _loadUtils() {
        let utils = this._utils;
        if (utils === null) {
          const {
            sendWithHttp: sendWithHttp2,
            createHttpAgent: createHttpAgent2
            // eslint-disable-next-line @typescript-eslint/no-require-imports
          } = (init_http_transport_utils(), __toCommonJS(http_transport_utils_exports));
          utils = this._utils = {
            agent: createHttpAgent2(this._parameters.url, this._parameters.agentOptions),
            send: sendWithHttp2
          };
        }
        return utils;
      }
    };
    __name(createHttpExporterTransport, "createHttpExporterTransport");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/retrying-transport.js
function getJitter() {
  return Math.random() * (2 * JITTER) - JITTER;
}
function createRetryingTransport(options2) {
  return new RetryingTransport(options2.transport);
}
var MAX_ATTEMPTS, INITIAL_BACKOFF, MAX_BACKOFF, BACKOFF_MULTIPLIER, JITTER, RetryingTransport;
var init_retrying_transport = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/retrying-transport.js"() {
    init_esbuild_shims();
    MAX_ATTEMPTS = 5;
    INITIAL_BACKOFF = 1e3;
    MAX_BACKOFF = 5e3;
    BACKOFF_MULTIPLIER = 1.5;
    JITTER = 0.2;
    __name(getJitter, "getJitter");
    RetryingTransport = class {
      static {
        __name(this, "RetryingTransport");
      }
      _transport;
      constructor(_transport) {
        this._transport = _transport;
      }
      retry(data, timeoutMillis, inMillis) {
        return new Promise((resolve24, reject) => {
          setTimeout(() => {
            this._transport.send(data, timeoutMillis).then(resolve24, reject);
          }, inMillis);
        });
      }
      async send(data, timeoutMillis) {
        const deadline = Date.now() + timeoutMillis;
        let result = await this._transport.send(data, timeoutMillis);
        let attempts = MAX_ATTEMPTS;
        let nextBackoff = INITIAL_BACKOFF;
        while (result.status === "retryable" && attempts > 0) {
          attempts--;
          const backoff = Math.max(Math.min(nextBackoff, MAX_BACKOFF) + getJitter(), 0);
          nextBackoff = nextBackoff * BACKOFF_MULTIPLIER;
          const retryInMillis = result.retryInMillis ?? backoff;
          const remainingTimeoutMillis = deadline - Date.now();
          if (retryInMillis > remainingTimeoutMillis) {
            return result;
          }
          result = await this.retry(data, remainingTimeoutMillis, retryInMillis);
        }
        return result;
      }
      shutdown() {
        return this._transport.shutdown();
      }
    };
    __name(createRetryingTransport, "createRetryingTransport");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-http-export-delegate.js
function createOtlpHttpExportDelegate(options2, serializer) {
  return createOtlpExportDelegate({
    transport: createRetryingTransport({
      transport: createHttpExporterTransport(options2)
    }),
    serializer,
    promiseHandler: createBoundedQueueExportPromiseHandler(options2)
  }, { timeout: options2.timeoutMillis });
}
var init_otlp_http_export_delegate = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-http-export-delegate.js"() {
    init_esbuild_shims();
    init_otlp_export_delegate();
    init_http_exporter_transport();
    init_bounded_queue_export_promise_handler();
    init_retrying_transport();
    __name(createOtlpHttpExportDelegate, "createOtlpHttpExportDelegate");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/shared-env-configuration.js
function parseAndValidateTimeoutFromEnv(timeoutEnvVar) {
  const envTimeout = process.env[timeoutEnvVar]?.trim();
  if (envTimeout != null && envTimeout !== "") {
    const definedTimeout = Number(envTimeout);
    if (Number.isFinite(definedTimeout) && definedTimeout > 0) {
      return definedTimeout;
    }
    diag2.warn(`Configuration: ${timeoutEnvVar} is invalid, expected number greater than 0 (actual: ${envTimeout})`);
  }
  return void 0;
}
function getTimeoutFromEnv(signalIdentifier) {
  const specificTimeout = parseAndValidateTimeoutFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_TIMEOUT`);
  const nonSpecificTimeout = parseAndValidateTimeoutFromEnv("OTEL_EXPORTER_OTLP_TIMEOUT");
  return specificTimeout ?? nonSpecificTimeout;
}
function parseAndValidateCompressionFromEnv(compressionEnvVar) {
  const compression = process.env[compressionEnvVar]?.trim();
  if (compression === "") {
    return void 0;
  }
  if (compression == null || compression === "none" || compression === "gzip") {
    return compression;
  }
  diag2.warn(`Configuration: ${compressionEnvVar} is invalid, expected 'none' or 'gzip' (actual: '${compression}')`);
  return void 0;
}
function getCompressionFromEnv(signalIdentifier) {
  const specificCompression = parseAndValidateCompressionFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_COMPRESSION`);
  const nonSpecificCompression = parseAndValidateCompressionFromEnv("OTEL_EXPORTER_OTLP_COMPRESSION");
  return specificCompression ?? nonSpecificCompression;
}
function getSharedConfigurationFromEnvironment(signalIdentifier) {
  return {
    timeoutMillis: getTimeoutFromEnv(signalIdentifier),
    compression: getCompressionFromEnv(signalIdentifier)
  };
}
var init_shared_env_configuration = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/shared-env-configuration.js"() {
    init_esbuild_shims();
    init_esm2();
    __name(parseAndValidateTimeoutFromEnv, "parseAndValidateTimeoutFromEnv");
    __name(getTimeoutFromEnv, "getTimeoutFromEnv");
    __name(parseAndValidateCompressionFromEnv, "parseAndValidateCompressionFromEnv");
    __name(getCompressionFromEnv, "getCompressionFromEnv");
    __name(getSharedConfigurationFromEnvironment, "getSharedConfigurationFromEnvironment");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/util.js
function validateAndNormalizeHeaders(partialHeaders) {
  return () => {
    const headers = {};
    Object.entries(partialHeaders?.() ?? {}).forEach(([key, value]) => {
      if (typeof value !== "undefined") {
        headers[key] = String(value);
      } else {
        diag2.warn(`Header "${key}" has invalid value (${value}) and will be ignored`);
      }
    });
    return headers;
  };
}
var init_util = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/util.js"() {
    init_esbuild_shims();
    init_esm2();
    __name(validateAndNormalizeHeaders, "validateAndNormalizeHeaders");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/otlp-http-configuration.js
function mergeHeaders(userProvidedHeaders, fallbackHeaders, defaultHeaders) {
  const requiredHeaders = {
    ...defaultHeaders()
  };
  const headers = {};
  return () => {
    if (fallbackHeaders != null) {
      Object.assign(headers, fallbackHeaders());
    }
    if (userProvidedHeaders != null) {
      Object.assign(headers, userProvidedHeaders());
    }
    return Object.assign(headers, requiredHeaders);
  };
}
function validateUserProvidedUrl(url2) {
  if (url2 == null) {
    return void 0;
  }
  try {
    new URL(url2);
    return url2;
  } catch {
    throw new Error(`Configuration: Could not parse user-provided export URL: '${url2}'`);
  }
}
function mergeOtlpHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) {
  return {
    ...mergeOtlpSharedConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration),
    headers: mergeHeaders(validateAndNormalizeHeaders(userProvidedConfiguration.headers), fallbackConfiguration.headers, defaultConfiguration.headers),
    url: validateUserProvidedUrl(userProvidedConfiguration.url) ?? fallbackConfiguration.url ?? defaultConfiguration.url,
    agentOptions: userProvidedConfiguration.agentOptions ?? fallbackConfiguration.agentOptions ?? defaultConfiguration.agentOptions
  };
}
function getHttpConfigurationDefaults(requiredHeaders, signalResourcePath) {
  return {
    ...getSharedConfigurationDefaults(),
    headers: /* @__PURE__ */ __name(() => requiredHeaders, "headers"),
    url: "http://localhost:4318/" + signalResourcePath,
    agentOptions: { keepAlive: true }
  };
}
var init_otlp_http_configuration = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/otlp-http-configuration.js"() {
    init_esbuild_shims();
    init_shared_configuration();
    init_util();
    __name(mergeHeaders, "mergeHeaders");
    __name(validateUserProvidedUrl, "validateUserProvidedUrl");
    __name(mergeOtlpHttpConfigurationWithDefaults, "mergeOtlpHttpConfigurationWithDefaults");
    __name(getHttpConfigurationDefaults, "getHttpConfigurationDefaults");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/otlp-http-env-configuration.js
function getStaticHeadersFromEnv(signalIdentifier) {
  const signalSpecificRawHeaders = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`]?.trim();
  const nonSignalSpecificRawHeaders = process.env["OTEL_EXPORTER_OTLP_HEADERS"]?.trim();
  const signalSpecificHeaders = (0, import_core2.parseKeyPairsIntoRecord)(signalSpecificRawHeaders);
  const nonSignalSpecificHeaders = (0, import_core2.parseKeyPairsIntoRecord)(nonSignalSpecificRawHeaders);
  if (Object.keys(signalSpecificHeaders).length === 0 && Object.keys(nonSignalSpecificHeaders).length === 0) {
    return void 0;
  }
  return Object.assign({}, (0, import_core2.parseKeyPairsIntoRecord)(nonSignalSpecificRawHeaders), (0, import_core2.parseKeyPairsIntoRecord)(signalSpecificRawHeaders));
}
function appendRootPathToUrlIfNeeded(url2) {
  try {
    const parsedUrl = new URL(url2);
    return parsedUrl.toString();
  } catch {
    diag2.warn(`Configuration: Could not parse environment-provided export URL: '${url2}', falling back to undefined`);
    return void 0;
  }
}
function appendResourcePathToUrl(url2, path108) {
  try {
    new URL(url2);
  } catch {
    diag2.warn(`Configuration: Could not parse environment-provided export URL: '${url2}', falling back to undefined`);
    return void 0;
  }
  if (!url2.endsWith("/")) {
    url2 = url2 + "/";
  }
  url2 += path108;
  try {
    new URL(url2);
  } catch {
    diag2.warn(`Configuration: Provided URL appended with '${path108}' is not a valid URL, using 'undefined' instead of '${url2}'`);
    return void 0;
  }
  return url2;
}
function getNonSpecificUrlFromEnv(signalResourcePath) {
  const envUrl = process.env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim();
  if (envUrl == null || envUrl === "") {
    return void 0;
  }
  return appendResourcePathToUrl(envUrl, signalResourcePath);
}
function getSpecificUrlFromEnv(signalIdentifier) {
  const envUrl = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`]?.trim();
  if (envUrl == null || envUrl === "") {
    return void 0;
  }
  return appendRootPathToUrlIfNeeded(envUrl);
}
function getHttpConfigurationFromEnvironment(signalIdentifier, signalResourcePath) {
  return {
    ...getSharedConfigurationFromEnvironment(signalIdentifier),
    url: getSpecificUrlFromEnv(signalIdentifier) ?? getNonSpecificUrlFromEnv(signalResourcePath),
    headers: wrapStaticHeadersInFunction(getStaticHeadersFromEnv(signalIdentifier))
  };
}
var import_core2;
var init_otlp_http_env_configuration = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/otlp-http-env-configuration.js"() {
    init_esbuild_shims();
    import_core2 = __toESM(require_src8());
    init_esm2();
    init_shared_env_configuration();
    init_shared_configuration();
    __name(getStaticHeadersFromEnv, "getStaticHeadersFromEnv");
    __name(appendRootPathToUrlIfNeeded, "appendRootPathToUrlIfNeeded");
    __name(appendResourcePathToUrl, "appendResourcePathToUrl");
    __name(getNonSpecificUrlFromEnv, "getNonSpecificUrlFromEnv");
    __name(getSpecificUrlFromEnv, "getSpecificUrlFromEnv");
    __name(getHttpConfigurationFromEnvironment, "getHttpConfigurationFromEnvironment");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/convert-legacy-node-http-options.js
function convertLegacyAgentOptions(config) {
  if (config?.keepAlive != null) {
    if (config.httpAgentOptions != null) {
      if (config.httpAgentOptions.keepAlive == null) {
        config.httpAgentOptions.keepAlive = config.keepAlive;
      }
    } else {
      config.httpAgentOptions = {
        keepAlive: config.keepAlive
      };
    }
  }
  return config.httpAgentOptions;
}
function convertLegacyHttpOptions(config, signalIdentifier, signalResourcePath, requiredHeaders) {
  if (config.metadata) {
    diag2.warn("Metadata cannot be set when using http");
  }
  return mergeOtlpHttpConfigurationWithDefaults({
    url: config.url,
    headers: wrapStaticHeadersInFunction(config.headers),
    concurrencyLimit: config.concurrencyLimit,
    timeoutMillis: config.timeoutMillis,
    compression: config.compression,
    agentOptions: convertLegacyAgentOptions(config)
  }, getHttpConfigurationFromEnvironment(signalIdentifier, signalResourcePath), getHttpConfigurationDefaults(requiredHeaders, signalResourcePath));
}
var init_convert_legacy_node_http_options = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/convert-legacy-node-http-options.js"() {
    init_esbuild_shims();
    init_otlp_http_configuration();
    init_otlp_http_env_configuration();
    init_esm2();
    init_shared_configuration();
    __name(convertLegacyAgentOptions, "convertLegacyAgentOptions");
    __name(convertLegacyHttpOptions, "convertLegacyHttpOptions");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/index-node-http.js
var index_node_http_exports = {};
__export(index_node_http_exports, {
  convertLegacyHttpOptions: () => convertLegacyHttpOptions,
  createOtlpHttpExportDelegate: () => createOtlpHttpExportDelegate,
  getSharedConfigurationFromEnvironment: () => getSharedConfigurationFromEnvironment
});
var init_index_node_http = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/index-node-http.js"() {
    init_esbuild_shims();
    init_otlp_http_export_delegate();
    init_shared_env_configuration();
    init_convert_legacy_node_http_options();
  }
});

// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-env-configuration.js
var require_otlp_grpc_env_configuration = __commonJS({
  "node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-env-configuration.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getOtlpGrpcConfigurationFromEnv = void 0;
    var core_1 = require_src8();
    var grpc_exporter_transport_1 = require_grpc_exporter_transport();
    var node_http_1 = (init_index_node_http(), __toCommonJS(index_node_http_exports));
    var fs95 = __require("fs");
    var path108 = __require("path");
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    function fallbackIfNullishOrBlank(signalSpecific, nonSignalSpecific) {
      if (signalSpecific != null && signalSpecific !== "") {
        return signalSpecific;
      }
      if (nonSignalSpecific != null && nonSignalSpecific !== "") {
        return nonSignalSpecific;
      }
      return void 0;
    }
    __name(fallbackIfNullishOrBlank, "fallbackIfNullishOrBlank");
    function getMetadataFromEnv(signalIdentifier) {
      const signalSpecificRawHeaders = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`]?.trim();
      const nonSignalSpecificRawHeaders = process.env["OTEL_EXPORTER_OTLP_HEADERS"]?.trim();
      const signalSpecificHeaders = (0, core_1.parseKeyPairsIntoRecord)(signalSpecificRawHeaders);
      const nonSignalSpecificHeaders = (0, core_1.parseKeyPairsIntoRecord)(nonSignalSpecificRawHeaders);
      if (Object.keys(signalSpecificHeaders).length === 0 && Object.keys(nonSignalSpecificHeaders).length === 0) {
        return void 0;
      }
      const mergeHeaders3 = Object.assign({}, nonSignalSpecificHeaders, signalSpecificHeaders);
      const metadata = (0, grpc_exporter_transport_1.createEmptyMetadata)();
      for (const [key, value] of Object.entries(mergeHeaders3)) {
        metadata.set(key, value);
      }
      return metadata;
    }
    __name(getMetadataFromEnv, "getMetadataFromEnv");
    function getMetadataProviderFromEnv(signalIdentifier) {
      const metadata = getMetadataFromEnv(signalIdentifier);
      if (metadata == null) {
        return void 0;
      }
      return () => metadata;
    }
    __name(getMetadataProviderFromEnv, "getMetadataProviderFromEnv");
    function getUrlFromEnv(signalIdentifier) {
      const specificEndpoint = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`]?.trim();
      const nonSpecificEndpoint = process.env[`OTEL_EXPORTER_OTLP_ENDPOINT`]?.trim();
      return fallbackIfNullishOrBlank(specificEndpoint, nonSpecificEndpoint);
    }
    __name(getUrlFromEnv, "getUrlFromEnv");
    function getInsecureSettingFromEnv(signalIdentifier) {
      const signalSpecificInsecureValue = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_INSECURE`]?.toLowerCase().trim();
      const nonSignalSpecificInsecureValue = process.env[`OTEL_EXPORTER_OTLP_INSECURE`]?.toLowerCase().trim();
      return fallbackIfNullishOrBlank(signalSpecificInsecureValue, nonSignalSpecificInsecureValue) === "true";
    }
    __name(getInsecureSettingFromEnv, "getInsecureSettingFromEnv");
    function readFileFromEnv(signalSpecificEnvVar, nonSignalSpecificEnvVar, warningMessage) {
      const signalSpecificPath = process.env[signalSpecificEnvVar]?.trim();
      const nonSignalSpecificPath = process.env[nonSignalSpecificEnvVar]?.trim();
      const filePath = fallbackIfNullishOrBlank(signalSpecificPath, nonSignalSpecificPath);
      if (filePath != null) {
        try {
          return fs95.readFileSync(path108.resolve(process.cwd(), filePath));
        } catch {
          api_1.diag.warn(warningMessage);
          return void 0;
        }
      } else {
        return void 0;
      }
    }
    __name(readFileFromEnv, "readFileFromEnv");
    function getClientCertificateFromEnv(signalIdentifier) {
      return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_CERTIFICATE`, "OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE", "Failed to read client certificate chain file");
    }
    __name(getClientCertificateFromEnv, "getClientCertificateFromEnv");
    function getClientKeyFromEnv(signalIdentifier) {
      return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_KEY`, "OTEL_EXPORTER_OTLP_CLIENT_KEY", "Failed to read client certificate private key file");
    }
    __name(getClientKeyFromEnv, "getClientKeyFromEnv");
    function getRootCertificateFromEnv(signalIdentifier) {
      return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CERTIFICATE`, "OTEL_EXPORTER_OTLP_CERTIFICATE", "Failed to read root certificate file");
    }
    __name(getRootCertificateFromEnv, "getRootCertificateFromEnv");
    function getCredentialsFromEnvIgnoreInsecure(signalIdentifier) {
      const clientKey = getClientKeyFromEnv(signalIdentifier);
      const clientCertificate = getClientCertificateFromEnv(signalIdentifier);
      const rootCertificate = getRootCertificateFromEnv(signalIdentifier);
      const clientChainIntact = clientKey != null && clientCertificate != null;
      if (rootCertificate != null && !clientChainIntact) {
        api_1.diag.warn("Client key and certificate must both be provided, but one was missing - attempting to create credentials from just the root certificate");
        return (0, grpc_exporter_transport_1.createSslCredentials)(getRootCertificateFromEnv(signalIdentifier));
      }
      return (0, grpc_exporter_transport_1.createSslCredentials)(rootCertificate, clientKey, clientCertificate);
    }
    __name(getCredentialsFromEnvIgnoreInsecure, "getCredentialsFromEnvIgnoreInsecure");
    function getCredentialsFromEnv(signalIdentifier) {
      if (getInsecureSettingFromEnv(signalIdentifier)) {
        return (0, grpc_exporter_transport_1.createInsecureCredentials)();
      }
      return getCredentialsFromEnvIgnoreInsecure(signalIdentifier);
    }
    __name(getCredentialsFromEnv, "getCredentialsFromEnv");
    function getOtlpGrpcConfigurationFromEnv(signalIdentifier) {
      return {
        ...(0, node_http_1.getSharedConfigurationFromEnvironment)(signalIdentifier),
        metadata: getMetadataProviderFromEnv(signalIdentifier),
        url: getUrlFromEnv(signalIdentifier),
        credentials: /* @__PURE__ */ __name((finalResolvedUrl) => {
          if (finalResolvedUrl.startsWith("http://")) {
            return () => {
              return (0, grpc_exporter_transport_1.createInsecureCredentials)();
            };
          } else if (finalResolvedUrl.startsWith("https://")) {
            return () => {
              return getCredentialsFromEnvIgnoreInsecure(signalIdentifier);
            };
          }
          return () => {
            return getCredentialsFromEnv(signalIdentifier);
          };
        }, "credentials")
      };
    }
    __name(getOtlpGrpcConfigurationFromEnv, "getOtlpGrpcConfigurationFromEnv");
    exports2.getOtlpGrpcConfigurationFromEnv = getOtlpGrpcConfigurationFromEnv;
  }
});

// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/convert-legacy-otlp-grpc-options.js
var require_convert_legacy_otlp_grpc_options = __commonJS({
  "node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/convert-legacy-otlp-grpc-options.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.convertLegacyOtlpGrpcOptions = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var otlp_grpc_configuration_1 = require_otlp_grpc_configuration();
    var grpc_exporter_transport_1 = require_grpc_exporter_transport();
    var otlp_grpc_env_configuration_1 = require_otlp_grpc_env_configuration();
    function convertLegacyOtlpGrpcOptions(config, signalIdentifier) {
      if (config.headers) {
        api_1.diag.warn("Headers cannot be set when using grpc");
      }
      const userProvidedCredentials = config.credentials;
      return (0, otlp_grpc_configuration_1.mergeOtlpGrpcConfigurationWithDefaults)({
        url: config.url,
        metadata: /* @__PURE__ */ __name(() => {
          return config.metadata ?? (0, grpc_exporter_transport_1.createEmptyMetadata)();
        }, "metadata"),
        compression: config.compression,
        timeoutMillis: config.timeoutMillis,
        concurrencyLimit: config.concurrencyLimit,
        credentials: userProvidedCredentials != null ? () => userProvidedCredentials : void 0
      }, (0, otlp_grpc_env_configuration_1.getOtlpGrpcConfigurationFromEnv)(signalIdentifier), (0, otlp_grpc_configuration_1.getOtlpGrpcDefaultConfiguration)());
    }
    __name(convertLegacyOtlpGrpcOptions, "convertLegacyOtlpGrpcOptions");
    exports2.convertLegacyOtlpGrpcOptions = convertLegacyOtlpGrpcOptions;
  }
});

// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/otlp-grpc-export-delegate.js
var require_otlp_grpc_export_delegate = __commonJS({
  "node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/otlp-grpc-export-delegate.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createOtlpGrpcExportDelegate = void 0;
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var grpc_exporter_transport_1 = require_grpc_exporter_transport();
    function createOtlpGrpcExportDelegate(options2, serializer, grpcName, grpcPath) {
      return (0, otlp_exporter_base_1.createOtlpNetworkExportDelegate)(options2, serializer, (0, grpc_exporter_transport_1.createOtlpGrpcExporterTransport)({
        address: options2.url,
        compression: options2.compression,
        credentials: options2.credentials,
        metadata: options2.metadata,
        grpcName,
        grpcPath
      }));
    }
    __name(createOtlpGrpcExportDelegate, "createOtlpGrpcExportDelegate");
    exports2.createOtlpGrpcExportDelegate = createOtlpGrpcExportDelegate;
  }
});

// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/index.js
var require_src12 = __commonJS({
  "node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createOtlpGrpcExportDelegate = exports2.convertLegacyOtlpGrpcOptions = void 0;
    var convert_legacy_otlp_grpc_options_1 = require_convert_legacy_otlp_grpc_options();
    Object.defineProperty(exports2, "convertLegacyOtlpGrpcOptions", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return convert_legacy_otlp_grpc_options_1.convertLegacyOtlpGrpcOptions;
    }, "get") });
    var otlp_grpc_export_delegate_1 = require_otlp_grpc_export_delegate();
    Object.defineProperty(exports2, "createOtlpGrpcExportDelegate", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return otlp_grpc_export_delegate_1.createOtlpGrpcExportDelegate;
    }, "get") });
  }
});

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

// node_modules/@opentelemetry/otlp-transformer/build/src/generated/root.js
var require_root2 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/generated/root.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var $protobuf = require_minimal2();
    var $Reader = $protobuf.Reader;
    var $Writer = $protobuf.Writer;
    var $util = $protobuf.util;
    var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {});
    $root.opentelemetry = function() {
      var opentelemetry = {};
      opentelemetry.proto = function() {
        var proto3 = {};
        proto3.common = function() {
          var common = {};
          common.v1 = function() {
            var v12 = {};
            v12.AnyValue = function() {
              function AnyValue(properties) {
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(AnyValue, "AnyValue");
              AnyValue.prototype.stringValue = null;
              AnyValue.prototype.boolValue = null;
              AnyValue.prototype.intValue = null;
              AnyValue.prototype.doubleValue = null;
              AnyValue.prototype.arrayValue = null;
              AnyValue.prototype.kvlistValue = null;
              AnyValue.prototype.bytesValue = null;
              var $oneOfFields;
              Object.defineProperty(AnyValue.prototype, "value", {
                get: $util.oneOfGetter($oneOfFields = ["stringValue", "boolValue", "intValue", "doubleValue", "arrayValue", "kvlistValue", "bytesValue"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              AnyValue.create = /* @__PURE__ */ __name(function create3(properties) {
                return new AnyValue(properties);
              }, "create");
              AnyValue.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.stringValue != null && Object.hasOwnProperty.call(message, "stringValue"))
                  writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).string(message.stringValue);
                if (message.boolValue != null && Object.hasOwnProperty.call(message, "boolValue"))
                  writer.uint32(
                    /* id 2, wireType 0 =*/
                    16
                  ).bool(message.boolValue);
                if (message.intValue != null && Object.hasOwnProperty.call(message, "intValue"))
                  writer.uint32(
                    /* id 3, wireType 0 =*/
                    24
                  ).int64(message.intValue);
                if (message.doubleValue != null && Object.hasOwnProperty.call(message, "doubleValue"))
                  writer.uint32(
                    /* id 4, wireType 1 =*/
                    33
                  ).double(message.doubleValue);
                if (message.arrayValue != null && Object.hasOwnProperty.call(message, "arrayValue"))
                  $root.opentelemetry.proto.common.v1.ArrayValue.encode(message.arrayValue, writer.uint32(
                    /* id 5, wireType 2 =*/
                    42
                  ).fork()).ldelim();
                if (message.kvlistValue != null && Object.hasOwnProperty.call(message, "kvlistValue"))
                  $root.opentelemetry.proto.common.v1.KeyValueList.encode(message.kvlistValue, writer.uint32(
                    /* id 6, wireType 2 =*/
                    50
                  ).fork()).ldelim();
                if (message.bytesValue != null && Object.hasOwnProperty.call(message, "bytesValue"))
                  writer.uint32(
                    /* id 7, wireType 2 =*/
                    58
                  ).bytes(message.bytesValue);
                return writer;
              }, "encode");
              AnyValue.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              AnyValue.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.AnyValue();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      message.stringValue = reader.string();
                      break;
                    }
                    case 2: {
                      message.boolValue = reader.bool();
                      break;
                    }
                    case 3: {
                      message.intValue = reader.int64();
                      break;
                    }
                    case 4: {
                      message.doubleValue = reader.double();
                      break;
                    }
                    case 5: {
                      message.arrayValue = $root.opentelemetry.proto.common.v1.ArrayValue.decode(reader, reader.uint32());
                      break;
                    }
                    case 6: {
                      message.kvlistValue = $root.opentelemetry.proto.common.v1.KeyValueList.decode(reader, reader.uint32());
                      break;
                    }
                    case 7: {
                      message.bytesValue = reader.bytes();
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              AnyValue.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              AnyValue.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                var properties = {};
                if (message.stringValue != null && message.hasOwnProperty("stringValue")) {
                  properties.value = 1;
                  if (!$util.isString(message.stringValue))
                    return "stringValue: string expected";
                }
                if (message.boolValue != null && message.hasOwnProperty("boolValue")) {
                  if (properties.value === 1)
                    return "value: multiple values";
                  properties.value = 1;
                  if (typeof message.boolValue !== "boolean")
                    return "boolValue: boolean expected";
                }
                if (message.intValue != null && message.hasOwnProperty("intValue")) {
                  if (properties.value === 1)
                    return "value: multiple values";
                  properties.value = 1;
                  if (!$util.isInteger(message.intValue) && !(message.intValue && $util.isInteger(message.intValue.low) && $util.isInteger(message.intValue.high)))
                    return "intValue: integer|Long expected";
                }
                if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) {
                  if (properties.value === 1)
                    return "value: multiple values";
                  properties.value = 1;
                  if (typeof message.doubleValue !== "number")
                    return "doubleValue: number expected";
                }
                if (message.arrayValue != null && message.hasOwnProperty("arrayValue")) {
                  if (properties.value === 1)
                    return "value: multiple values";
                  properties.value = 1;
                  {
                    var error = $root.opentelemetry.proto.common.v1.ArrayValue.verify(message.arrayValue);
                    if (error)
                      return "arrayValue." + error;
                  }
                }
                if (message.kvlistValue != null && message.hasOwnProperty("kvlistValue")) {
                  if (properties.value === 1)
                    return "value: multiple values";
                  properties.value = 1;
                  {
                    var error = $root.opentelemetry.proto.common.v1.KeyValueList.verify(message.kvlistValue);
                    if (error)
                      return "kvlistValue." + error;
                  }
                }
                if (message.bytesValue != null && message.hasOwnProperty("bytesValue")) {
                  if (properties.value === 1)
                    return "value: multiple values";
                  properties.value = 1;
                  if (!(message.bytesValue && typeof message.bytesValue.length === "number" || $util.isString(message.bytesValue)))
                    return "bytesValue: buffer expected";
                }
                return null;
              }, "verify");
              AnyValue.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.common.v1.AnyValue)
                  return object;
                var message = new $root.opentelemetry.proto.common.v1.AnyValue();
                if (object.stringValue != null)
                  message.stringValue = String(object.stringValue);
                if (object.boolValue != null)
                  message.boolValue = Boolean(object.boolValue);
                if (object.intValue != null) {
                  if ($util.Long)
                    (message.intValue = $util.Long.fromValue(object.intValue)).unsigned = false;
                  else if (typeof object.intValue === "string")
                    message.intValue = parseInt(object.intValue, 10);
                  else if (typeof object.intValue === "number")
                    message.intValue = object.intValue;
                  else if (typeof object.intValue === "object")
                    message.intValue = new $util.LongBits(object.intValue.low >>> 0, object.intValue.high >>> 0).toNumber();
                }
                if (object.doubleValue != null)
                  message.doubleValue = Number(object.doubleValue);
                if (object.arrayValue != null) {
                  if (typeof object.arrayValue !== "object")
                    throw TypeError(".opentelemetry.proto.common.v1.AnyValue.arrayValue: object expected");
                  message.arrayValue = $root.opentelemetry.proto.common.v1.ArrayValue.fromObject(object.arrayValue);
                }
                if (object.kvlistValue != null) {
                  if (typeof object.kvlistValue !== "object")
                    throw TypeError(".opentelemetry.proto.common.v1.AnyValue.kvlistValue: object expected");
                  message.kvlistValue = $root.opentelemetry.proto.common.v1.KeyValueList.fromObject(object.kvlistValue);
                }
                if (object.bytesValue != null) {
                  if (typeof object.bytesValue === "string")
                    $util.base64.decode(object.bytesValue, message.bytesValue = $util.newBuffer($util.base64.length(object.bytesValue)), 0);
                  else if (object.bytesValue.length >= 0)
                    message.bytesValue = object.bytesValue;
                }
                return message;
              }, "fromObject");
              AnyValue.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (message.stringValue != null && message.hasOwnProperty("stringValue")) {
                  object.stringValue = message.stringValue;
                  if (options2.oneofs)
                    object.value = "stringValue";
                }
                if (message.boolValue != null && message.hasOwnProperty("boolValue")) {
                  object.boolValue = message.boolValue;
                  if (options2.oneofs)
                    object.value = "boolValue";
                }
                if (message.intValue != null && message.hasOwnProperty("intValue")) {
                  if (typeof message.intValue === "number")
                    object.intValue = options2.longs === String ? String(message.intValue) : message.intValue;
                  else
                    object.intValue = options2.longs === String ? $util.Long.prototype.toString.call(message.intValue) : options2.longs === Number ? new $util.LongBits(message.intValue.low >>> 0, message.intValue.high >>> 0).toNumber() : message.intValue;
                  if (options2.oneofs)
                    object.value = "intValue";
                }
                if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) {
                  object.doubleValue = options2.json && !isFinite(message.doubleValue) ? String(message.doubleValue) : message.doubleValue;
                  if (options2.oneofs)
                    object.value = "doubleValue";
                }
                if (message.arrayValue != null && message.hasOwnProperty("arrayValue")) {
                  object.arrayValue = $root.opentelemetry.proto.common.v1.ArrayValue.toObject(message.arrayValue, options2);
                  if (options2.oneofs)
                    object.value = "arrayValue";
                }
                if (message.kvlistValue != null && message.hasOwnProperty("kvlistValue")) {
                  object.kvlistValue = $root.opentelemetry.proto.common.v1.KeyValueList.toObject(message.kvlistValue, options2);
                  if (options2.oneofs)
                    object.value = "kvlistValue";
                }
                if (message.bytesValue != null && message.hasOwnProperty("bytesValue")) {
                  object.bytesValue = options2.bytes === String ? $util.base64.encode(message.bytesValue, 0, message.bytesValue.length) : options2.bytes === Array ? Array.prototype.slice.call(message.bytesValue) : message.bytesValue;
                  if (options2.oneofs)
                    object.value = "bytesValue";
                }
                return object;
              }, "toObject");
              AnyValue.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              AnyValue.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.common.v1.AnyValue";
              }, "getTypeUrl");
              return AnyValue;
            }();
            v12.ArrayValue = function() {
              function ArrayValue(properties) {
                this.values = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(ArrayValue, "ArrayValue");
              ArrayValue.prototype.values = $util.emptyArray;
              ArrayValue.create = /* @__PURE__ */ __name(function create3(properties) {
                return new ArrayValue(properties);
              }, "create");
              ArrayValue.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.values != null && message.values.length)
                  for (var i = 0; i < message.values.length; ++i)
                    $root.opentelemetry.proto.common.v1.AnyValue.encode(message.values[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              ArrayValue.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              ArrayValue.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.ArrayValue();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      if (!(message.values && message.values.length))
                        message.values = [];
                      message.values.push($root.opentelemetry.proto.common.v1.AnyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              ArrayValue.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              ArrayValue.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.values != null && message.hasOwnProperty("values")) {
                  if (!Array.isArray(message.values))
                    return "values: array expected";
                  for (var i = 0; i < message.values.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.AnyValue.verify(message.values[i]);
                    if (error)
                      return "values." + error;
                  }
                }
                return null;
              }, "verify");
              ArrayValue.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.common.v1.ArrayValue)
                  return object;
                var message = new $root.opentelemetry.proto.common.v1.ArrayValue();
                if (object.values) {
                  if (!Array.isArray(object.values))
                    throw TypeError(".opentelemetry.proto.common.v1.ArrayValue.values: array expected");
                  message.values = [];
                  for (var i = 0; i < object.values.length; ++i) {
                    if (typeof object.values[i] !== "object")
                      throw TypeError(".opentelemetry.proto.common.v1.ArrayValue.values: object expected");
                    message.values[i] = $root.opentelemetry.proto.common.v1.AnyValue.fromObject(object.values[i]);
                  }
                }
                return message;
              }, "fromObject");
              ArrayValue.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.values = [];
                if (message.values && message.values.length) {
                  object.values = [];
                  for (var j = 0; j < message.values.length; ++j)
                    object.values[j] = $root.opentelemetry.proto.common.v1.AnyValue.toObject(message.values[j], options2);
                }
                return object;
              }, "toObject");
              ArrayValue.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              ArrayValue.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.common.v1.ArrayValue";
              }, "getTypeUrl");
              return ArrayValue;
            }();
            v12.KeyValueList = function() {
              function KeyValueList(properties) {
                this.values = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(KeyValueList, "KeyValueList");
              KeyValueList.prototype.values = $util.emptyArray;
              KeyValueList.create = /* @__PURE__ */ __name(function create3(properties) {
                return new KeyValueList(properties);
              }, "create");
              KeyValueList.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.values != null && message.values.length)
                  for (var i = 0; i < message.values.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.values[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              KeyValueList.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              KeyValueList.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.KeyValueList();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      if (!(message.values && message.values.length))
                        message.values = [];
                      message.values.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              KeyValueList.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              KeyValueList.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.values != null && message.hasOwnProperty("values")) {
                  if (!Array.isArray(message.values))
                    return "values: array expected";
                  for (var i = 0; i < message.values.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.values[i]);
                    if (error)
                      return "values." + error;
                  }
                }
                return null;
              }, "verify");
              KeyValueList.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.common.v1.KeyValueList)
                  return object;
                var message = new $root.opentelemetry.proto.common.v1.KeyValueList();
                if (object.values) {
                  if (!Array.isArray(object.values))
                    throw TypeError(".opentelemetry.proto.common.v1.KeyValueList.values: array expected");
                  message.values = [];
                  for (var i = 0; i < object.values.length; ++i) {
                    if (typeof object.values[i] !== "object")
                      throw TypeError(".opentelemetry.proto.common.v1.KeyValueList.values: object expected");
                    message.values[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.values[i]);
                  }
                }
                return message;
              }, "fromObject");
              KeyValueList.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.values = [];
                if (message.values && message.values.length) {
                  object.values = [];
                  for (var j = 0; j < message.values.length; ++j)
                    object.values[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.values[j], options2);
                }
                return object;
              }, "toObject");
              KeyValueList.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              KeyValueList.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.common.v1.KeyValueList";
              }, "getTypeUrl");
              return KeyValueList;
            }();
            v12.KeyValue = function() {
              function KeyValue(properties) {
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(KeyValue, "KeyValue");
              KeyValue.prototype.key = null;
              KeyValue.prototype.value = null;
              KeyValue.create = /* @__PURE__ */ __name(function create3(properties) {
                return new KeyValue(properties);
              }, "create");
              KeyValue.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.key != null && Object.hasOwnProperty.call(message, "key"))
                  writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).string(message.key);
                if (message.value != null && Object.hasOwnProperty.call(message, "value"))
                  $root.opentelemetry.proto.common.v1.AnyValue.encode(message.value, writer.uint32(
                    /* id 2, wireType 2 =*/
                    18
                  ).fork()).ldelim();
                return writer;
              }, "encode");
              KeyValue.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              KeyValue.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.KeyValue();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      message.key = reader.string();
                      break;
                    }
                    case 2: {
                      message.value = $root.opentelemetry.proto.common.v1.AnyValue.decode(reader, reader.uint32());
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              KeyValue.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              KeyValue.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.key != null && message.hasOwnProperty("key")) {
                  if (!$util.isString(message.key))
                    return "key: string expected";
                }
                if (message.value != null && message.hasOwnProperty("value")) {
                  var error = $root.opentelemetry.proto.common.v1.AnyValue.verify(message.value);
                  if (error)
                    return "value." + error;
                }
                return null;
              }, "verify");
              KeyValue.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.common.v1.KeyValue)
                  return object;
                var message = new $root.opentelemetry.proto.common.v1.KeyValue();
                if (object.key != null)
                  message.key = String(object.key);
                if (object.value != null) {
                  if (typeof object.value !== "object")
                    throw TypeError(".opentelemetry.proto.common.v1.KeyValue.value: object expected");
                  message.value = $root.opentelemetry.proto.common.v1.AnyValue.fromObject(object.value);
                }
                return message;
              }, "fromObject");
              KeyValue.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.defaults) {
                  object.key = "";
                  object.value = null;
                }
                if (message.key != null && message.hasOwnProperty("key"))
                  object.key = message.key;
                if (message.value != null && message.hasOwnProperty("value"))
                  object.value = $root.opentelemetry.proto.common.v1.AnyValue.toObject(message.value, options2);
                return object;
              }, "toObject");
              KeyValue.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              KeyValue.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.common.v1.KeyValue";
              }, "getTypeUrl");
              return KeyValue;
            }();
            v12.InstrumentationScope = function() {
              function InstrumentationScope(properties) {
                this.attributes = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(InstrumentationScope, "InstrumentationScope");
              InstrumentationScope.prototype.name = null;
              InstrumentationScope.prototype.version = null;
              InstrumentationScope.prototype.attributes = $util.emptyArray;
              InstrumentationScope.prototype.droppedAttributesCount = null;
              InstrumentationScope.create = /* @__PURE__ */ __name(function create3(properties) {
                return new InstrumentationScope(properties);
              }, "create");
              InstrumentationScope.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.name != null && Object.hasOwnProperty.call(message, "name"))
                  writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).string(message.name);
                if (message.version != null && Object.hasOwnProperty.call(message, "version"))
                  writer.uint32(
                    /* id 2, wireType 2 =*/
                    18
                  ).string(message.version);
                if (message.attributes != null && message.attributes.length)
                  for (var i = 0; i < message.attributes.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                      /* id 3, wireType 2 =*/
                      26
                    ).fork()).ldelim();
                if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount"))
                  writer.uint32(
                    /* id 4, wireType 0 =*/
                    32
                  ).uint32(message.droppedAttributesCount);
                return writer;
              }, "encode");
              InstrumentationScope.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              InstrumentationScope.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.InstrumentationScope();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      message.name = reader.string();
                      break;
                    }
                    case 2: {
                      message.version = reader.string();
                      break;
                    }
                    case 3: {
                      if (!(message.attributes && message.attributes.length))
                        message.attributes = [];
                      message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    case 4: {
                      message.droppedAttributesCount = reader.uint32();
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              InstrumentationScope.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              InstrumentationScope.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.name != null && message.hasOwnProperty("name")) {
                  if (!$util.isString(message.name))
                    return "name: string expected";
                }
                if (message.version != null && message.hasOwnProperty("version")) {
                  if (!$util.isString(message.version))
                    return "version: string expected";
                }
                if (message.attributes != null && message.hasOwnProperty("attributes")) {
                  if (!Array.isArray(message.attributes))
                    return "attributes: array expected";
                  for (var i = 0; i < message.attributes.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                    if (error)
                      return "attributes." + error;
                  }
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) {
                  if (!$util.isInteger(message.droppedAttributesCount))
                    return "droppedAttributesCount: integer expected";
                }
                return null;
              }, "verify");
              InstrumentationScope.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.common.v1.InstrumentationScope)
                  return object;
                var message = new $root.opentelemetry.proto.common.v1.InstrumentationScope();
                if (object.name != null)
                  message.name = String(object.name);
                if (object.version != null)
                  message.version = String(object.version);
                if (object.attributes) {
                  if (!Array.isArray(object.attributes))
                    throw TypeError(".opentelemetry.proto.common.v1.InstrumentationScope.attributes: array expected");
                  message.attributes = [];
                  for (var i = 0; i < object.attributes.length; ++i) {
                    if (typeof object.attributes[i] !== "object")
                      throw TypeError(".opentelemetry.proto.common.v1.InstrumentationScope.attributes: object expected");
                    message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                  }
                }
                if (object.droppedAttributesCount != null)
                  message.droppedAttributesCount = object.droppedAttributesCount >>> 0;
                return message;
              }, "fromObject");
              InstrumentationScope.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.attributes = [];
                if (options2.defaults) {
                  object.name = "";
                  object.version = "";
                  object.droppedAttributesCount = 0;
                }
                if (message.name != null && message.hasOwnProperty("name"))
                  object.name = message.name;
                if (message.version != null && message.hasOwnProperty("version"))
                  object.version = message.version;
                if (message.attributes && message.attributes.length) {
                  object.attributes = [];
                  for (var j = 0; j < message.attributes.length; ++j)
                    object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options2);
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount"))
                  object.droppedAttributesCount = message.droppedAttributesCount;
                return object;
              }, "toObject");
              InstrumentationScope.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              InstrumentationScope.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.common.v1.InstrumentationScope";
              }, "getTypeUrl");
              return InstrumentationScope;
            }();
            v12.EntityRef = function() {
              function EntityRef(properties) {
                this.idKeys = [];
                this.descriptionKeys = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(EntityRef, "EntityRef");
              EntityRef.prototype.schemaUrl = null;
              EntityRef.prototype.type = null;
              EntityRef.prototype.idKeys = $util.emptyArray;
              EntityRef.prototype.descriptionKeys = $util.emptyArray;
              EntityRef.create = /* @__PURE__ */ __name(function create3(properties) {
                return new EntityRef(properties);
              }, "create");
              EntityRef.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl"))
                  writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).string(message.schemaUrl);
                if (message.type != null && Object.hasOwnProperty.call(message, "type"))
                  writer.uint32(
                    /* id 2, wireType 2 =*/
                    18
                  ).string(message.type);
                if (message.idKeys != null && message.idKeys.length)
                  for (var i = 0; i < message.idKeys.length; ++i)
                    writer.uint32(
                      /* id 3, wireType 2 =*/
                      26
                    ).string(message.idKeys[i]);
                if (message.descriptionKeys != null && message.descriptionKeys.length)
                  for (var i = 0; i < message.descriptionKeys.length; ++i)
                    writer.uint32(
                      /* id 4, wireType 2 =*/
                      34
                    ).string(message.descriptionKeys[i]);
                return writer;
              }, "encode");
              EntityRef.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              EntityRef.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.EntityRef();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      message.schemaUrl = reader.string();
                      break;
                    }
                    case 2: {
                      message.type = reader.string();
                      break;
                    }
                    case 3: {
                      if (!(message.idKeys && message.idKeys.length))
                        message.idKeys = [];
                      message.idKeys.push(reader.string());
                      break;
                    }
                    case 4: {
                      if (!(message.descriptionKeys && message.descriptionKeys.length))
                        message.descriptionKeys = [];
                      message.descriptionKeys.push(reader.string());
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              EntityRef.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              EntityRef.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) {
                  if (!$util.isString(message.schemaUrl))
                    return "schemaUrl: string expected";
                }
                if (message.type != null && message.hasOwnProperty("type")) {
                  if (!$util.isString(message.type))
                    return "type: string expected";
                }
                if (message.idKeys != null && message.hasOwnProperty("idKeys")) {
                  if (!Array.isArray(message.idKeys))
                    return "idKeys: array expected";
                  for (var i = 0; i < message.idKeys.length; ++i)
                    if (!$util.isString(message.idKeys[i]))
                      return "idKeys: string[] expected";
                }
                if (message.descriptionKeys != null && message.hasOwnProperty("descriptionKeys")) {
                  if (!Array.isArray(message.descriptionKeys))
                    return "descriptionKeys: array expected";
                  for (var i = 0; i < message.descriptionKeys.length; ++i)
                    if (!$util.isString(message.descriptionKeys[i]))
                      return "descriptionKeys: string[] expected";
                }
                return null;
              }, "verify");
              EntityRef.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.common.v1.EntityRef)
                  return object;
                var message = new $root.opentelemetry.proto.common.v1.EntityRef();
                if (object.schemaUrl != null)
                  message.schemaUrl = String(object.schemaUrl);
                if (object.type != null)
                  message.type = String(object.type);
                if (object.idKeys) {
                  if (!Array.isArray(object.idKeys))
                    throw TypeError(".opentelemetry.proto.common.v1.EntityRef.idKeys: array expected");
                  message.idKeys = [];
                  for (var i = 0; i < object.idKeys.length; ++i)
                    message.idKeys[i] = String(object.idKeys[i]);
                }
                if (object.descriptionKeys) {
                  if (!Array.isArray(object.descriptionKeys))
                    throw TypeError(".opentelemetry.proto.common.v1.EntityRef.descriptionKeys: array expected");
                  message.descriptionKeys = [];
                  for (var i = 0; i < object.descriptionKeys.length; ++i)
                    message.descriptionKeys[i] = String(object.descriptionKeys[i]);
                }
                return message;
              }, "fromObject");
              EntityRef.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults) {
                  object.idKeys = [];
                  object.descriptionKeys = [];
                }
                if (options2.defaults) {
                  object.schemaUrl = "";
                  object.type = "";
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object.schemaUrl = message.schemaUrl;
                if (message.type != null && message.hasOwnProperty("type"))
                  object.type = message.type;
                if (message.idKeys && message.idKeys.length) {
                  object.idKeys = [];
                  for (var j = 0; j < message.idKeys.length; ++j)
                    object.idKeys[j] = message.idKeys[j];
                }
                if (message.descriptionKeys && message.descriptionKeys.length) {
                  object.descriptionKeys = [];
                  for (var j = 0; j < message.descriptionKeys.length; ++j)
                    object.descriptionKeys[j] = message.descriptionKeys[j];
                }
                return object;
              }, "toObject");
              EntityRef.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              EntityRef.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.common.v1.EntityRef";
              }, "getTypeUrl");
              return EntityRef;
            }();
            return v12;
          }();
          return common;
        }();
        proto3.resource = function() {
          var resource = {};
          resource.v1 = function() {
            var v12 = {};
            v12.Resource = function() {
              function Resource(properties) {
                this.attributes = [];
                this.entityRefs = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(Resource, "Resource");
              Resource.prototype.attributes = $util.emptyArray;
              Resource.prototype.droppedAttributesCount = null;
              Resource.prototype.entityRefs = $util.emptyArray;
              Resource.create = /* @__PURE__ */ __name(function create3(properties) {
                return new Resource(properties);
              }, "create");
              Resource.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.attributes != null && message.attributes.length)
                  for (var i = 0; i < message.attributes.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount"))
                  writer.uint32(
                    /* id 2, wireType 0 =*/
                    16
                  ).uint32(message.droppedAttributesCount);
                if (message.entityRefs != null && message.entityRefs.length)
                  for (var i = 0; i < message.entityRefs.length; ++i)
                    $root.opentelemetry.proto.common.v1.EntityRef.encode(message.entityRefs[i], writer.uint32(
                      /* id 3, wireType 2 =*/
                      26
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              Resource.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              Resource.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.resource.v1.Resource();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      if (!(message.attributes && message.attributes.length))
                        message.attributes = [];
                      message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    case 2: {
                      message.droppedAttributesCount = reader.uint32();
                      break;
                    }
                    case 3: {
                      if (!(message.entityRefs && message.entityRefs.length))
                        message.entityRefs = [];
                      message.entityRefs.push($root.opentelemetry.proto.common.v1.EntityRef.decode(reader, reader.uint32()));
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              Resource.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              Resource.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.attributes != null && message.hasOwnProperty("attributes")) {
                  if (!Array.isArray(message.attributes))
                    return "attributes: array expected";
                  for (var i = 0; i < message.attributes.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                    if (error)
                      return "attributes." + error;
                  }
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) {
                  if (!$util.isInteger(message.droppedAttributesCount))
                    return "droppedAttributesCount: integer expected";
                }
                if (message.entityRefs != null && message.hasOwnProperty("entityRefs")) {
                  if (!Array.isArray(message.entityRefs))
                    return "entityRefs: array expected";
                  for (var i = 0; i < message.entityRefs.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.EntityRef.verify(message.entityRefs[i]);
                    if (error)
                      return "entityRefs." + error;
                  }
                }
                return null;
              }, "verify");
              Resource.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.resource.v1.Resource)
                  return object;
                var message = new $root.opentelemetry.proto.resource.v1.Resource();
                if (object.attributes) {
                  if (!Array.isArray(object.attributes))
                    throw TypeError(".opentelemetry.proto.resource.v1.Resource.attributes: array expected");
                  message.attributes = [];
                  for (var i = 0; i < object.attributes.length; ++i) {
                    if (typeof object.attributes[i] !== "object")
                      throw TypeError(".opentelemetry.proto.resource.v1.Resource.attributes: object expected");
                    message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                  }
                }
                if (object.droppedAttributesCount != null)
                  message.droppedAttributesCount = object.droppedAttributesCount >>> 0;
                if (object.entityRefs) {
                  if (!Array.isArray(object.entityRefs))
                    throw TypeError(".opentelemetry.proto.resource.v1.Resource.entityRefs: array expected");
                  message.entityRefs = [];
                  for (var i = 0; i < object.entityRefs.length; ++i) {
                    if (typeof object.entityRefs[i] !== "object")
                      throw TypeError(".opentelemetry.proto.resource.v1.Resource.entityRefs: object expected");
                    message.entityRefs[i] = $root.opentelemetry.proto.common.v1.EntityRef.fromObject(object.entityRefs[i]);
                  }
                }
                return message;
              }, "fromObject");
              Resource.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults) {
                  object.attributes = [];
                  object.entityRefs = [];
                }
                if (options2.defaults)
                  object.droppedAttributesCount = 0;
                if (message.attributes && message.attributes.length) {
                  object.attributes = [];
                  for (var j = 0; j < message.attributes.length; ++j)
                    object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options2);
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount"))
                  object.droppedAttributesCount = message.droppedAttributesCount;
                if (message.entityRefs && message.entityRefs.length) {
                  object.entityRefs = [];
                  for (var j = 0; j < message.entityRefs.length; ++j)
                    object.entityRefs[j] = $root.opentelemetry.proto.common.v1.EntityRef.toObject(message.entityRefs[j], options2);
                }
                return object;
              }, "toObject");
              Resource.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              Resource.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.resource.v1.Resource";
              }, "getTypeUrl");
              return Resource;
            }();
            return v12;
          }();
          return resource;
        }();
        proto3.trace = function() {
          var trace2 = {};
          trace2.v1 = function() {
            var v12 = {};
            v12.TracesData = function() {
              function TracesData(properties) {
                this.resourceSpans = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(TracesData, "TracesData");
              TracesData.prototype.resourceSpans = $util.emptyArray;
              TracesData.create = /* @__PURE__ */ __name(function create3(properties) {
                return new TracesData(properties);
              }, "create");
              TracesData.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.resourceSpans != null && message.resourceSpans.length)
                  for (var i = 0; i < message.resourceSpans.length; ++i)
                    $root.opentelemetry.proto.trace.v1.ResourceSpans.encode(message.resourceSpans[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              TracesData.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              TracesData.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.TracesData();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      if (!(message.resourceSpans && message.resourceSpans.length))
                        message.resourceSpans = [];
                      message.resourceSpans.push($root.opentelemetry.proto.trace.v1.ResourceSpans.decode(reader, reader.uint32()));
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              TracesData.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              TracesData.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.resourceSpans != null && message.hasOwnProperty("resourceSpans")) {
                  if (!Array.isArray(message.resourceSpans))
                    return "resourceSpans: array expected";
                  for (var i = 0; i < message.resourceSpans.length; ++i) {
                    var error = $root.opentelemetry.proto.trace.v1.ResourceSpans.verify(message.resourceSpans[i]);
                    if (error)
                      return "resourceSpans." + error;
                  }
                }
                return null;
              }, "verify");
              TracesData.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.trace.v1.TracesData)
                  return object;
                var message = new $root.opentelemetry.proto.trace.v1.TracesData();
                if (object.resourceSpans) {
                  if (!Array.isArray(object.resourceSpans))
                    throw TypeError(".opentelemetry.proto.trace.v1.TracesData.resourceSpans: array expected");
                  message.resourceSpans = [];
                  for (var i = 0; i < object.resourceSpans.length; ++i) {
                    if (typeof object.resourceSpans[i] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.TracesData.resourceSpans: object expected");
                    message.resourceSpans[i] = $root.opentelemetry.proto.trace.v1.ResourceSpans.fromObject(object.resourceSpans[i]);
                  }
                }
                return message;
              }, "fromObject");
              TracesData.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.resourceSpans = [];
                if (message.resourceSpans && message.resourceSpans.length) {
                  object.resourceSpans = [];
                  for (var j = 0; j < message.resourceSpans.length; ++j)
                    object.resourceSpans[j] = $root.opentelemetry.proto.trace.v1.ResourceSpans.toObject(message.resourceSpans[j], options2);
                }
                return object;
              }, "toObject");
              TracesData.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              TracesData.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.trace.v1.TracesData";
              }, "getTypeUrl");
              return TracesData;
            }();
            v12.ResourceSpans = function() {
              function ResourceSpans(properties) {
                this.scopeSpans = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(ResourceSpans, "ResourceSpans");
              ResourceSpans.prototype.resource = null;
              ResourceSpans.prototype.scopeSpans = $util.emptyArray;
              ResourceSpans.prototype.schemaUrl = null;
              ResourceSpans.create = /* @__PURE__ */ __name(function create3(properties) {
                return new ResourceSpans(properties);
              }, "create");
              ResourceSpans.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.resource != null && Object.hasOwnProperty.call(message, "resource"))
                  $root.opentelemetry.proto.resource.v1.Resource.encode(message.resource, writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).fork()).ldelim();
                if (message.scopeSpans != null && message.scopeSpans.length)
                  for (var i = 0; i < message.scopeSpans.length; ++i)
                    $root.opentelemetry.proto.trace.v1.ScopeSpans.encode(message.scopeSpans[i], writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).fork()).ldelim();
                if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl"))
                  writer.uint32(
                    /* id 3, wireType 2 =*/
                    26
                  ).string(message.schemaUrl);
                return writer;
              }, "encode");
              ResourceSpans.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              ResourceSpans.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.ResourceSpans();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      message.resource = $root.opentelemetry.proto.resource.v1.Resource.decode(reader, reader.uint32());
                      break;
                    }
                    case 2: {
                      if (!(message.scopeSpans && message.scopeSpans.length))
                        message.scopeSpans = [];
                      message.scopeSpans.push($root.opentelemetry.proto.trace.v1.ScopeSpans.decode(reader, reader.uint32()));
                      break;
                    }
                    case 3: {
                      message.schemaUrl = reader.string();
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              ResourceSpans.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              ResourceSpans.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.resource != null && message.hasOwnProperty("resource")) {
                  var error = $root.opentelemetry.proto.resource.v1.Resource.verify(message.resource);
                  if (error)
                    return "resource." + error;
                }
                if (message.scopeSpans != null && message.hasOwnProperty("scopeSpans")) {
                  if (!Array.isArray(message.scopeSpans))
                    return "scopeSpans: array expected";
                  for (var i = 0; i < message.scopeSpans.length; ++i) {
                    var error = $root.opentelemetry.proto.trace.v1.ScopeSpans.verify(message.scopeSpans[i]);
                    if (error)
                      return "scopeSpans." + error;
                  }
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) {
                  if (!$util.isString(message.schemaUrl))
                    return "schemaUrl: string expected";
                }
                return null;
              }, "verify");
              ResourceSpans.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.trace.v1.ResourceSpans)
                  return object;
                var message = new $root.opentelemetry.proto.trace.v1.ResourceSpans();
                if (object.resource != null) {
                  if (typeof object.resource !== "object")
                    throw TypeError(".opentelemetry.proto.trace.v1.ResourceSpans.resource: object expected");
                  message.resource = $root.opentelemetry.proto.resource.v1.Resource.fromObject(object.resource);
                }
                if (object.scopeSpans) {
                  if (!Array.isArray(object.scopeSpans))
                    throw TypeError(".opentelemetry.proto.trace.v1.ResourceSpans.scopeSpans: array expected");
                  message.scopeSpans = [];
                  for (var i = 0; i < object.scopeSpans.length; ++i) {
                    if (typeof object.scopeSpans[i] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.ResourceSpans.scopeSpans: object expected");
                    message.scopeSpans[i] = $root.opentelemetry.proto.trace.v1.ScopeSpans.fromObject(object.scopeSpans[i]);
                  }
                }
                if (object.schemaUrl != null)
                  message.schemaUrl = String(object.schemaUrl);
                return message;
              }, "fromObject");
              ResourceSpans.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.scopeSpans = [];
                if (options2.defaults) {
                  object.resource = null;
                  object.schemaUrl = "";
                }
                if (message.resource != null && message.hasOwnProperty("resource"))
                  object.resource = $root.opentelemetry.proto.resource.v1.Resource.toObject(message.resource, options2);
                if (message.scopeSpans && message.scopeSpans.length) {
                  object.scopeSpans = [];
                  for (var j = 0; j < message.scopeSpans.length; ++j)
                    object.scopeSpans[j] = $root.opentelemetry.proto.trace.v1.ScopeSpans.toObject(message.scopeSpans[j], options2);
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object.schemaUrl = message.schemaUrl;
                return object;
              }, "toObject");
              ResourceSpans.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              ResourceSpans.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.trace.v1.ResourceSpans";
              }, "getTypeUrl");
              return ResourceSpans;
            }();
            v12.ScopeSpans = function() {
              function ScopeSpans(properties) {
                this.spans = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(ScopeSpans, "ScopeSpans");
              ScopeSpans.prototype.scope = null;
              ScopeSpans.prototype.spans = $util.emptyArray;
              ScopeSpans.prototype.schemaUrl = null;
              ScopeSpans.create = /* @__PURE__ */ __name(function create3(properties) {
                return new ScopeSpans(properties);
              }, "create");
              ScopeSpans.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.scope != null && Object.hasOwnProperty.call(message, "scope"))
                  $root.opentelemetry.proto.common.v1.InstrumentationScope.encode(message.scope, writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).fork()).ldelim();
                if (message.spans != null && message.spans.length)
                  for (var i = 0; i < message.spans.length; ++i)
                    $root.opentelemetry.proto.trace.v1.Span.encode(message.spans[i], writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).fork()).ldelim();
                if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl"))
                  writer.uint32(
                    /* id 3, wireType 2 =*/
                    26
                  ).string(message.schemaUrl);
                return writer;
              }, "encode");
              ScopeSpans.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              ScopeSpans.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.ScopeSpans();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.decode(reader, reader.uint32());
                      break;
                    }
                    case 2: {
                      if (!(message.spans && message.spans.length))
                        message.spans = [];
                      message.spans.push($root.opentelemetry.proto.trace.v1.Span.decode(reader, reader.uint32()));
                      break;
                    }
                    case 3: {
                      message.schemaUrl = reader.string();
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              ScopeSpans.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              ScopeSpans.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.scope != null && message.hasOwnProperty("scope")) {
                  var error = $root.opentelemetry.proto.common.v1.InstrumentationScope.verify(message.scope);
                  if (error)
                    return "scope." + error;
                }
                if (message.spans != null && message.hasOwnProperty("spans")) {
                  if (!Array.isArray(message.spans))
                    return "spans: array expected";
                  for (var i = 0; i < message.spans.length; ++i) {
                    var error = $root.opentelemetry.proto.trace.v1.Span.verify(message.spans[i]);
                    if (error)
                      return "spans." + error;
                  }
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) {
                  if (!$util.isString(message.schemaUrl))
                    return "schemaUrl: string expected";
                }
                return null;
              }, "verify");
              ScopeSpans.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.trace.v1.ScopeSpans)
                  return object;
                var message = new $root.opentelemetry.proto.trace.v1.ScopeSpans();
                if (object.scope != null) {
                  if (typeof object.scope !== "object")
                    throw TypeError(".opentelemetry.proto.trace.v1.ScopeSpans.scope: object expected");
                  message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(object.scope);
                }
                if (object.spans) {
                  if (!Array.isArray(object.spans))
                    throw TypeError(".opentelemetry.proto.trace.v1.ScopeSpans.spans: array expected");
                  message.spans = [];
                  for (var i = 0; i < object.spans.length; ++i) {
                    if (typeof object.spans[i] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.ScopeSpans.spans: object expected");
                    message.spans[i] = $root.opentelemetry.proto.trace.v1.Span.fromObject(object.spans[i]);
                  }
                }
                if (object.schemaUrl != null)
                  message.schemaUrl = String(object.schemaUrl);
                return message;
              }, "fromObject");
              ScopeSpans.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.spans = [];
                if (options2.defaults) {
                  object.scope = null;
                  object.schemaUrl = "";
                }
                if (message.scope != null && message.hasOwnProperty("scope"))
                  object.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.toObject(message.scope, options2);
                if (message.spans && message.spans.length) {
                  object.spans = [];
                  for (var j = 0; j < message.spans.length; ++j)
                    object.spans[j] = $root.opentelemetry.proto.trace.v1.Span.toObject(message.spans[j], options2);
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object.schemaUrl = message.schemaUrl;
                return object;
              }, "toObject");
              ScopeSpans.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              ScopeSpans.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.trace.v1.ScopeSpans";
              }, "getTypeUrl");
              return ScopeSpans;
            }();
            v12.Span = function() {
              function Span(properties) {
                this.attributes = [];
                this.events = [];
                this.links = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(Span, "Span");
              Span.prototype.traceId = null;
              Span.prototype.spanId = null;
              Span.prototype.traceState = null;
              Span.prototype.parentSpanId = null;
              Span.prototype.flags = null;
              Span.prototype.name = null;
              Span.prototype.kind = null;
              Span.prototype.startTimeUnixNano = null;
              Span.prototype.endTimeUnixNano = null;
              Span.prototype.attributes = $util.emptyArray;
              Span.prototype.droppedAttributesCount = null;
              Span.prototype.events = $util.emptyArray;
              Span.prototype.droppedEventsCount = null;
              Span.prototype.links = $util.emptyArray;
              Span.prototype.droppedLinksCount = null;
              Span.prototype.status = null;
              Span.create = /* @__PURE__ */ __name(function create3(properties) {
                return new Span(properties);
              }, "create");
              Span.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.traceId != null && Object.hasOwnProperty.call(message, "traceId"))
                  writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).bytes(message.traceId);
                if (message.spanId != null && Object.hasOwnProperty.call(message, "spanId"))
                  writer.uint32(
                    /* id 2, wireType 2 =*/
                    18
                  ).bytes(message.spanId);
                if (message.traceState != null && Object.hasOwnProperty.call(message, "traceState"))
                  writer.uint32(
                    /* id 3, wireType 2 =*/
                    26
                  ).string(message.traceState);
                if (message.parentSpanId != null && Object.hasOwnProperty.call(message, "parentSpanId"))
                  writer.uint32(
                    /* id 4, wireType 2 =*/
                    34
                  ).bytes(message.parentSpanId);
                if (message.name != null && Object.hasOwnProperty.call(message, "name"))
                  writer.uint32(
                    /* id 5, wireType 2 =*/
                    42
                  ).string(message.name);
                if (message.kind != null && Object.hasOwnProperty.call(message, "kind"))
                  writer.uint32(
                    /* id 6, wireType 0 =*/
                    48
                  ).int32(message.kind);
                if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano"))
                  writer.uint32(
                    /* id 7, wireType 1 =*/
                    57
                  ).fixed64(message.startTimeUnixNano);
                if (message.endTimeUnixNano != null && Object.hasOwnProperty.call(message, "endTimeUnixNano"))
                  writer.uint32(
                    /* id 8, wireType 1 =*/
                    65
                  ).fixed64(message.endTimeUnixNano);
                if (message.attributes != null && message.attributes.length)
                  for (var i = 0; i < message.attributes.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                      /* id 9, wireType 2 =*/
                      74
                    ).fork()).ldelim();
                if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount"))
                  writer.uint32(
                    /* id 10, wireType 0 =*/
                    80
                  ).uint32(message.droppedAttributesCount);
                if (message.events != null && message.events.length)
                  for (var i = 0; i < message.events.length; ++i)
                    $root.opentelemetry.proto.trace.v1.Span.Event.encode(message.events[i], writer.uint32(
                      /* id 11, wireType 2 =*/
                      90
                    ).fork()).ldelim();
                if (message.droppedEventsCount != null && Object.hasOwnProperty.call(message, "droppedEventsCount"))
                  writer.uint32(
                    /* id 12, wireType 0 =*/
                    96
                  ).uint32(message.droppedEventsCount);
                if (message.links != null && message.links.length)
                  for (var i = 0; i < message.links.length; ++i)
                    $root.opentelemetry.proto.trace.v1.Span.Link.encode(message.links[i], writer.uint32(
                      /* id 13, wireType 2 =*/
                      106
                    ).fork()).ldelim();
                if (message.droppedLinksCount != null && Object.hasOwnProperty.call(message, "droppedLinksCount"))
                  writer.uint32(
                    /* id 14, wireType 0 =*/
                    112
                  ).uint32(message.droppedLinksCount);
                if (message.status != null && Object.hasOwnProperty.call(message, "status"))
                  $root.opentelemetry.proto.trace.v1.Status.encode(message.status, writer.uint32(
                    /* id 15, wireType 2 =*/
                    122
                  ).fork()).ldelim();
                if (message.flags != null && Object.hasOwnProperty.call(message, "flags"))
                  writer.uint32(
                    /* id 16, wireType 5 =*/
                    133
                  ).fixed32(message.flags);
                return writer;
              }, "encode");
              Span.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              Span.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.Span();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      message.traceId = reader.bytes();
                      break;
                    }
                    case 2: {
                      message.spanId = reader.bytes();
                      break;
                    }
                    case 3: {
                      message.traceState = reader.string();
                      break;
                    }
                    case 4: {
                      message.parentSpanId = reader.bytes();
                      break;
                    }
                    case 16: {
                      message.flags = reader.fixed32();
                      break;
                    }
                    case 5: {
                      message.name = reader.string();
                      break;
                    }
                    case 6: {
                      message.kind = reader.int32();
                      break;
                    }
                    case 7: {
                      message.startTimeUnixNano = reader.fixed64();
                      break;
                    }
                    case 8: {
                      message.endTimeUnixNano = reader.fixed64();
                      break;
                    }
                    case 9: {
                      if (!(message.attributes && message.attributes.length))
                        message.attributes = [];
                      message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    case 10: {
                      message.droppedAttributesCount = reader.uint32();
                      break;
                    }
                    case 11: {
                      if (!(message.events && message.events.length))
                        message.events = [];
                      message.events.push($root.opentelemetry.proto.trace.v1.Span.Event.decode(reader, reader.uint32()));
                      break;
                    }
                    case 12: {
                      message.droppedEventsCount = reader.uint32();
                      break;
                    }
                    case 13: {
                      if (!(message.links && message.links.length))
                        message.links = [];
                      message.links.push($root.opentelemetry.proto.trace.v1.Span.Link.decode(reader, reader.uint32()));
                      break;
                    }
                    case 14: {
                      message.droppedLinksCount = reader.uint32();
                      break;
                    }
                    case 15: {
                      message.status = $root.opentelemetry.proto.trace.v1.Status.decode(reader, reader.uint32());
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              Span.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              Span.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.traceId != null && message.hasOwnProperty("traceId")) {
                  if (!(message.traceId && typeof message.traceId.length === "number" || $util.isString(message.traceId)))
                    return "traceId: buffer expected";
                }
                if (message.spanId != null && message.hasOwnProperty("spanId")) {
                  if (!(message.spanId && typeof message.spanId.length === "number" || $util.isString(message.spanId)))
                    return "spanId: buffer expected";
                }
                if (message.traceState != null && message.hasOwnProperty("traceState")) {
                  if (!$util.isString(message.traceState))
                    return "traceState: string expected";
                }
                if (message.parentSpanId != null && message.hasOwnProperty("parentSpanId")) {
                  if (!(message.parentSpanId && typeof message.parentSpanId.length === "number" || $util.isString(message.parentSpanId)))
                    return "parentSpanId: buffer expected";
                }
                if (message.flags != null && message.hasOwnProperty("flags")) {
                  if (!$util.isInteger(message.flags))
                    return "flags: integer expected";
                }
                if (message.name != null && message.hasOwnProperty("name")) {
                  if (!$util.isString(message.name))
                    return "name: string expected";
                }
                if (message.kind != null && message.hasOwnProperty("kind"))
                  switch (message.kind) {
                    default:
                      return "kind: enum value expected";
                    case 0:
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                      break;
                  }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) {
                  if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high)))
                    return "startTimeUnixNano: integer|Long expected";
                }
                if (message.endTimeUnixNano != null && message.hasOwnProperty("endTimeUnixNano")) {
                  if (!$util.isInteger(message.endTimeUnixNano) && !(message.endTimeUnixNano && $util.isInteger(message.endTimeUnixNano.low) && $util.isInteger(message.endTimeUnixNano.high)))
                    return "endTimeUnixNano: integer|Long expected";
                }
                if (message.attributes != null && message.hasOwnProperty("attributes")) {
                  if (!Array.isArray(message.attributes))
                    return "attributes: array expected";
                  for (var i = 0; i < message.attributes.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                    if (error)
                      return "attributes." + error;
                  }
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) {
                  if (!$util.isInteger(message.droppedAttributesCount))
                    return "droppedAttributesCount: integer expected";
                }
                if (message.events != null && message.hasOwnProperty("events")) {
                  if (!Array.isArray(message.events))
                    return "events: array expected";
                  for (var i = 0; i < message.events.length; ++i) {
                    var error = $root.opentelemetry.proto.trace.v1.Span.Event.verify(message.events[i]);
                    if (error)
                      return "events." + error;
                  }
                }
                if (message.droppedEventsCount != null && message.hasOwnProperty("droppedEventsCount")) {
                  if (!$util.isInteger(message.droppedEventsCount))
                    return "droppedEventsCount: integer expected";
                }
                if (message.links != null && message.hasOwnProperty("links")) {
                  if (!Array.isArray(message.links))
                    return "links: array expected";
                  for (var i = 0; i < message.links.length; ++i) {
                    var error = $root.opentelemetry.proto.trace.v1.Span.Link.verify(message.links[i]);
                    if (error)
                      return "links." + error;
                  }
                }
                if (message.droppedLinksCount != null && message.hasOwnProperty("droppedLinksCount")) {
                  if (!$util.isInteger(message.droppedLinksCount))
                    return "droppedLinksCount: integer expected";
                }
                if (message.status != null && message.hasOwnProperty("status")) {
                  var error = $root.opentelemetry.proto.trace.v1.Status.verify(message.status);
                  if (error)
                    return "status." + error;
                }
                return null;
              }, "verify");
              Span.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.trace.v1.Span)
                  return object;
                var message = new $root.opentelemetry.proto.trace.v1.Span();
                if (object.traceId != null) {
                  if (typeof object.traceId === "string")
                    $util.base64.decode(object.traceId, message.traceId = $util.newBuffer($util.base64.length(object.traceId)), 0);
                  else if (object.traceId.length >= 0)
                    message.traceId = object.traceId;
                }
                if (object.spanId != null) {
                  if (typeof object.spanId === "string")
                    $util.base64.decode(object.spanId, message.spanId = $util.newBuffer($util.base64.length(object.spanId)), 0);
                  else if (object.spanId.length >= 0)
                    message.spanId = object.spanId;
                }
                if (object.traceState != null)
                  message.traceState = String(object.traceState);
                if (object.parentSpanId != null) {
                  if (typeof object.parentSpanId === "string")
                    $util.base64.decode(object.parentSpanId, message.parentSpanId = $util.newBuffer($util.base64.length(object.parentSpanId)), 0);
                  else if (object.parentSpanId.length >= 0)
                    message.parentSpanId = object.parentSpanId;
                }
                if (object.flags != null)
                  message.flags = object.flags >>> 0;
                if (object.name != null)
                  message.name = String(object.name);
                switch (object.kind) {
                  default:
                    if (typeof object.kind === "number") {
                      message.kind = object.kind;
                      break;
                    }
                    break;
                  case "SPAN_KIND_UNSPECIFIED":
                  case 0:
                    message.kind = 0;
                    break;
                  case "SPAN_KIND_INTERNAL":
                  case 1:
                    message.kind = 1;
                    break;
                  case "SPAN_KIND_SERVER":
                  case 2:
                    message.kind = 2;
                    break;
                  case "SPAN_KIND_CLIENT":
                  case 3:
                    message.kind = 3;
                    break;
                  case "SPAN_KIND_PRODUCER":
                  case 4:
                    message.kind = 4;
                    break;
                  case "SPAN_KIND_CONSUMER":
                  case 5:
                    message.kind = 5;
                    break;
                }
                if (object.startTimeUnixNano != null) {
                  if ($util.Long)
                    (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false;
                  else if (typeof object.startTimeUnixNano === "string")
                    message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10);
                  else if (typeof object.startTimeUnixNano === "number")
                    message.startTimeUnixNano = object.startTimeUnixNano;
                  else if (typeof object.startTimeUnixNano === "object")
                    message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber();
                }
                if (object.endTimeUnixNano != null) {
                  if ($util.Long)
                    (message.endTimeUnixNano = $util.Long.fromValue(object.endTimeUnixNano)).unsigned = false;
                  else if (typeof object.endTimeUnixNano === "string")
                    message.endTimeUnixNano = parseInt(object.endTimeUnixNano, 10);
                  else if (typeof object.endTimeUnixNano === "number")
                    message.endTimeUnixNano = object.endTimeUnixNano;
                  else if (typeof object.endTimeUnixNano === "object")
                    message.endTimeUnixNano = new $util.LongBits(object.endTimeUnixNano.low >>> 0, object.endTimeUnixNano.high >>> 0).toNumber();
                }
                if (object.attributes) {
                  if (!Array.isArray(object.attributes))
                    throw TypeError(".opentelemetry.proto.trace.v1.Span.attributes: array expected");
                  message.attributes = [];
                  for (var i = 0; i < object.attributes.length; ++i) {
                    if (typeof object.attributes[i] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.Span.attributes: object expected");
                    message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                  }
                }
                if (object.droppedAttributesCount != null)
                  message.droppedAttributesCount = object.droppedAttributesCount >>> 0;
                if (object.events) {
                  if (!Array.isArray(object.events))
                    throw TypeError(".opentelemetry.proto.trace.v1.Span.events: array expected");
                  message.events = [];
                  for (var i = 0; i < object.events.length; ++i) {
                    if (typeof object.events[i] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.Span.events: object expected");
                    message.events[i] = $root.opentelemetry.proto.trace.v1.Span.Event.fromObject(object.events[i]);
                  }
                }
                if (object.droppedEventsCount != null)
                  message.droppedEventsCount = object.droppedEventsCount >>> 0;
                if (object.links) {
                  if (!Array.isArray(object.links))
                    throw TypeError(".opentelemetry.proto.trace.v1.Span.links: array expected");
                  message.links = [];
                  for (var i = 0; i < object.links.length; ++i) {
                    if (typeof object.links[i] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.Span.links: object expected");
                    message.links[i] = $root.opentelemetry.proto.trace.v1.Span.Link.fromObject(object.links[i]);
                  }
                }
                if (object.droppedLinksCount != null)
                  message.droppedLinksCount = object.droppedLinksCount >>> 0;
                if (object.status != null) {
                  if (typeof object.status !== "object")
                    throw TypeError(".opentelemetry.proto.trace.v1.Span.status: object expected");
                  message.status = $root.opentelemetry.proto.trace.v1.Status.fromObject(object.status);
                }
                return message;
              }, "fromObject");
              Span.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults) {
                  object.attributes = [];
                  object.events = [];
                  object.links = [];
                }
                if (options2.defaults) {
                  if (options2.bytes === String)
                    object.traceId = "";
                  else {
                    object.traceId = [];
                    if (options2.bytes !== Array)
                      object.traceId = $util.newBuffer(object.traceId);
                  }
                  if (options2.bytes === String)
                    object.spanId = "";
                  else {
                    object.spanId = [];
                    if (options2.bytes !== Array)
                      object.spanId = $util.newBuffer(object.spanId);
                  }
                  object.traceState = "";
                  if (options2.bytes === String)
                    object.parentSpanId = "";
                  else {
                    object.parentSpanId = [];
                    if (options2.bytes !== Array)
                      object.parentSpanId = $util.newBuffer(object.parentSpanId);
                  }
                  object.name = "";
                  object.kind = options2.enums === String ? "SPAN_KIND_UNSPECIFIED" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.startTimeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object.startTimeUnixNano = options2.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.endTimeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object.endTimeUnixNano = options2.longs === String ? "0" : 0;
                  object.droppedAttributesCount = 0;
                  object.droppedEventsCount = 0;
                  object.droppedLinksCount = 0;
                  object.status = null;
                  object.flags = 0;
                }
                if (message.traceId != null && message.hasOwnProperty("traceId"))
                  object.traceId = options2.bytes === String ? $util.base64.encode(message.traceId, 0, message.traceId.length) : options2.bytes === Array ? Array.prototype.slice.call(message.traceId) : message.traceId;
                if (message.spanId != null && message.hasOwnProperty("spanId"))
                  object.spanId = options2.bytes === String ? $util.base64.encode(message.spanId, 0, message.spanId.length) : options2.bytes === Array ? Array.prototype.slice.call(message.spanId) : message.spanId;
                if (message.traceState != null && message.hasOwnProperty("traceState"))
                  object.traceState = message.traceState;
                if (message.parentSpanId != null && message.hasOwnProperty("parentSpanId"))
                  object.parentSpanId = options2.bytes === String ? $util.base64.encode(message.parentSpanId, 0, message.parentSpanId.length) : options2.bytes === Array ? Array.prototype.slice.call(message.parentSpanId) : message.parentSpanId;
                if (message.name != null && message.hasOwnProperty("name"))
                  object.name = message.name;
                if (message.kind != null && message.hasOwnProperty("kind"))
                  object.kind = options2.enums === String ? $root.opentelemetry.proto.trace.v1.Span.SpanKind[message.kind] === void 0 ? message.kind : $root.opentelemetry.proto.trace.v1.Span.SpanKind[message.kind] : message.kind;
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano"))
                  if (typeof message.startTimeUnixNano === "number")
                    object.startTimeUnixNano = options2.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano;
                  else
                    object.startTimeUnixNano = options2.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options2.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano;
                if (message.endTimeUnixNano != null && message.hasOwnProperty("endTimeUnixNano"))
                  if (typeof message.endTimeUnixNano === "number")
                    object.endTimeUnixNano = options2.longs === String ? String(message.endTimeUnixNano) : message.endTimeUnixNano;
                  else
                    object.endTimeUnixNano = options2.longs === String ? $util.Long.prototype.toString.call(message.endTimeUnixNano) : options2.longs === Number ? new $util.LongBits(message.endTimeUnixNano.low >>> 0, message.endTimeUnixNano.high >>> 0).toNumber() : message.endTimeUnixNano;
                if (message.attributes && message.attributes.length) {
                  object.attributes = [];
                  for (var j = 0; j < message.attributes.length; ++j)
                    object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options2);
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount"))
                  object.droppedAttributesCount = message.droppedAttributesCount;
                if (message.events && message.events.length) {
                  object.events = [];
                  for (var j = 0; j < message.events.length; ++j)
                    object.events[j] = $root.opentelemetry.proto.trace.v1.Span.Event.toObject(message.events[j], options2);
                }
                if (message.droppedEventsCount != null && message.hasOwnProperty("droppedEventsCount"))
                  object.droppedEventsCount = message.droppedEventsCount;
                if (message.links && message.links.length) {
                  object.links = [];
                  for (var j = 0; j < message.links.length; ++j)
                    object.links[j] = $root.opentelemetry.proto.trace.v1.Span.Link.toObject(message.links[j], options2);
                }
                if (message.droppedLinksCount != null && message.hasOwnProperty("droppedLinksCount"))
                  object.droppedLinksCount = message.droppedLinksCount;
                if (message.status != null && message.hasOwnProperty("status"))
                  object.status = $root.opentelemetry.proto.trace.v1.Status.toObject(message.status, options2);
                if (message.flags != null && message.hasOwnProperty("flags"))
                  object.flags = message.flags;
                return object;
              }, "toObject");
              Span.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              Span.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.trace.v1.Span";
              }, "getTypeUrl");
              Span.SpanKind = function() {
                var valuesById = {}, values = Object.create(valuesById);
                values[valuesById[0] = "SPAN_KIND_UNSPECIFIED"] = 0;
                values[valuesById[1] = "SPAN_KIND_INTERNAL"] = 1;
                values[valuesById[2] = "SPAN_KIND_SERVER"] = 2;
                values[valuesById[3] = "SPAN_KIND_CLIENT"] = 3;
                values[valuesById[4] = "SPAN_KIND_PRODUCER"] = 4;
                values[valuesById[5] = "SPAN_KIND_CONSUMER"] = 5;
                return values;
              }();
              Span.Event = function() {
                function Event2(properties) {
                  this.attributes = [];
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(Event2, "Event");
                Event2.prototype.timeUnixNano = null;
                Event2.prototype.name = null;
                Event2.prototype.attributes = $util.emptyArray;
                Event2.prototype.droppedAttributesCount = null;
                Event2.create = /* @__PURE__ */ __name(function create3(properties) {
                  return new Event2(properties);
                }, "create");
                Event2.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano"))
                    writer.uint32(
                      /* id 1, wireType 1 =*/
                      9
                    ).fixed64(message.timeUnixNano);
                  if (message.name != null && Object.hasOwnProperty.call(message, "name"))
                    writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).string(message.name);
                  if (message.attributes != null && message.attributes.length)
                    for (var i = 0; i < message.attributes.length; ++i)
                      $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                        /* id 3, wireType 2 =*/
                        26
                      ).fork()).ldelim();
                  if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount"))
                    writer.uint32(
                      /* id 4, wireType 0 =*/
                      32
                    ).uint32(message.droppedAttributesCount);
                  return writer;
                }, "encode");
                Event2.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                Event2.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.Span.Event();
                  while (reader.pos < end) {
                    var tag2 = reader.uint32();
                    if (tag2 === error)
                      break;
                    switch (tag2 >>> 3) {
                      case 1: {
                        message.timeUnixNano = reader.fixed64();
                        break;
                      }
                      case 2: {
                        message.name = reader.string();
                        break;
                      }
                      case 3: {
                        if (!(message.attributes && message.attributes.length))
                          message.attributes = [];
                        message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                        break;
                      }
                      case 4: {
                        message.droppedAttributesCount = reader.uint32();
                        break;
                      }
                      default:
                        reader.skipType(tag2 & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                Event2.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                Event2.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) {
                    if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high)))
                      return "timeUnixNano: integer|Long expected";
                  }
                  if (message.name != null && message.hasOwnProperty("name")) {
                    if (!$util.isString(message.name))
                      return "name: string expected";
                  }
                  if (message.attributes != null && message.hasOwnProperty("attributes")) {
                    if (!Array.isArray(message.attributes))
                      return "attributes: array expected";
                    for (var i = 0; i < message.attributes.length; ++i) {
                      var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                      if (error)
                        return "attributes." + error;
                    }
                  }
                  if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) {
                    if (!$util.isInteger(message.droppedAttributesCount))
                      return "droppedAttributesCount: integer expected";
                  }
                  return null;
                }, "verify");
                Event2.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.trace.v1.Span.Event)
                    return object;
                  var message = new $root.opentelemetry.proto.trace.v1.Span.Event();
                  if (object.timeUnixNano != null) {
                    if ($util.Long)
                      (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false;
                    else if (typeof object.timeUnixNano === "string")
                      message.timeUnixNano = parseInt(object.timeUnixNano, 10);
                    else if (typeof object.timeUnixNano === "number")
                      message.timeUnixNano = object.timeUnixNano;
                    else if (typeof object.timeUnixNano === "object")
                      message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber();
                  }
                  if (object.name != null)
                    message.name = String(object.name);
                  if (object.attributes) {
                    if (!Array.isArray(object.attributes))
                      throw TypeError(".opentelemetry.proto.trace.v1.Span.Event.attributes: array expected");
                    message.attributes = [];
                    for (var i = 0; i < object.attributes.length; ++i) {
                      if (typeof object.attributes[i] !== "object")
                        throw TypeError(".opentelemetry.proto.trace.v1.Span.Event.attributes: object expected");
                      message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                    }
                  }
                  if (object.droppedAttributesCount != null)
                    message.droppedAttributesCount = object.droppedAttributesCount >>> 0;
                  return message;
                }, "fromObject");
                Event2.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object = {};
                  if (options2.arrays || options2.defaults)
                    object.attributes = [];
                  if (options2.defaults) {
                    if ($util.Long) {
                      var long = new $util.Long(0, 0, false);
                      object.timeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                    } else
                      object.timeUnixNano = options2.longs === String ? "0" : 0;
                    object.name = "";
                    object.droppedAttributesCount = 0;
                  }
                  if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano"))
                    if (typeof message.timeUnixNano === "number")
                      object.timeUnixNano = options2.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                    else
                      object.timeUnixNano = options2.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options2.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano;
                  if (message.name != null && message.hasOwnProperty("name"))
                    object.name = message.name;
                  if (message.attributes && message.attributes.length) {
                    object.attributes = [];
                    for (var j = 0; j < message.attributes.length; ++j)
                      object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options2);
                  }
                  if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount"))
                    object.droppedAttributesCount = message.droppedAttributesCount;
                  return object;
                }, "toObject");
                Event2.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                Event2.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.trace.v1.Span.Event";
                }, "getTypeUrl");
                return Event2;
              }();
              Span.Link = function() {
                function Link2(properties) {
                  this.attributes = [];
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(Link2, "Link");
                Link2.prototype.traceId = null;
                Link2.prototype.spanId = null;
                Link2.prototype.traceState = null;
                Link2.prototype.attributes = $util.emptyArray;
                Link2.prototype.droppedAttributesCount = null;
                Link2.prototype.flags = null;
                Link2.create = /* @__PURE__ */ __name(function create3(properties) {
                  return new Link2(properties);
                }, "create");
                Link2.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.traceId != null && Object.hasOwnProperty.call(message, "traceId"))
                    writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).bytes(message.traceId);
                  if (message.spanId != null && Object.hasOwnProperty.call(message, "spanId"))
                    writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).bytes(message.spanId);
                  if (message.traceState != null && Object.hasOwnProperty.call(message, "traceState"))
                    writer.uint32(
                      /* id 3, wireType 2 =*/
                      26
                    ).string(message.traceState);
                  if (message.attributes != null && message.attributes.length)
                    for (var i = 0; i < message.attributes.length; ++i)
                      $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                        /* id 4, wireType 2 =*/
                        34
                      ).fork()).ldelim();
                  if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount"))
                    writer.uint32(
                      /* id 5, wireType 0 =*/
                      40
                    ).uint32(message.droppedAttributesCount);
                  if (message.flags != null && Object.hasOwnProperty.call(message, "flags"))
                    writer.uint32(
                      /* id 6, wireType 5 =*/
                      53
                    ).fixed32(message.flags);
                  return writer;
                }, "encode");
                Link2.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                Link2.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.Span.Link();
                  while (reader.pos < end) {
                    var tag2 = reader.uint32();
                    if (tag2 === error)
                      break;
                    switch (tag2 >>> 3) {
                      case 1: {
                        message.traceId = reader.bytes();
                        break;
                      }
                      case 2: {
                        message.spanId = reader.bytes();
                        break;
                      }
                      case 3: {
                        message.traceState = reader.string();
                        break;
                      }
                      case 4: {
                        if (!(message.attributes && message.attributes.length))
                          message.attributes = [];
                        message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                        break;
                      }
                      case 5: {
                        message.droppedAttributesCount = reader.uint32();
                        break;
                      }
                      case 6: {
                        message.flags = reader.fixed32();
                        break;
                      }
                      default:
                        reader.skipType(tag2 & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                Link2.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                Link2.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.traceId != null && message.hasOwnProperty("traceId")) {
                    if (!(message.traceId && typeof message.traceId.length === "number" || $util.isString(message.traceId)))
                      return "traceId: buffer expected";
                  }
                  if (message.spanId != null && message.hasOwnProperty("spanId")) {
                    if (!(message.spanId && typeof message.spanId.length === "number" || $util.isString(message.spanId)))
                      return "spanId: buffer expected";
                  }
                  if (message.traceState != null && message.hasOwnProperty("traceState")) {
                    if (!$util.isString(message.traceState))
                      return "traceState: string expected";
                  }
                  if (message.attributes != null && message.hasOwnProperty("attributes")) {
                    if (!Array.isArray(message.attributes))
                      return "attributes: array expected";
                    for (var i = 0; i < message.attributes.length; ++i) {
                      var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                      if (error)
                        return "attributes." + error;
                    }
                  }
                  if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) {
                    if (!$util.isInteger(message.droppedAttributesCount))
                      return "droppedAttributesCount: integer expected";
                  }
                  if (message.flags != null && message.hasOwnProperty("flags")) {
                    if (!$util.isInteger(message.flags))
                      return "flags: integer expected";
                  }
                  return null;
                }, "verify");
                Link2.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.trace.v1.Span.Link)
                    return object;
                  var message = new $root.opentelemetry.proto.trace.v1.Span.Link();
                  if (object.traceId != null) {
                    if (typeof object.traceId === "string")
                      $util.base64.decode(object.traceId, message.traceId = $util.newBuffer($util.base64.length(object.traceId)), 0);
                    else if (object.traceId.length >= 0)
                      message.traceId = object.traceId;
                  }
                  if (object.spanId != null) {
                    if (typeof object.spanId === "string")
                      $util.base64.decode(object.spanId, message.spanId = $util.newBuffer($util.base64.length(object.spanId)), 0);
                    else if (object.spanId.length >= 0)
                      message.spanId = object.spanId;
                  }
                  if (object.traceState != null)
                    message.traceState = String(object.traceState);
                  if (object.attributes) {
                    if (!Array.isArray(object.attributes))
                      throw TypeError(".opentelemetry.proto.trace.v1.Span.Link.attributes: array expected");
                    message.attributes = [];
                    for (var i = 0; i < object.attributes.length; ++i) {
                      if (typeof object.attributes[i] !== "object")
                        throw TypeError(".opentelemetry.proto.trace.v1.Span.Link.attributes: object expected");
                      message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                    }
                  }
                  if (object.droppedAttributesCount != null)
                    message.droppedAttributesCount = object.droppedAttributesCount >>> 0;
                  if (object.flags != null)
                    message.flags = object.flags >>> 0;
                  return message;
                }, "fromObject");
                Link2.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object = {};
                  if (options2.arrays || options2.defaults)
                    object.attributes = [];
                  if (options2.defaults) {
                    if (options2.bytes === String)
                      object.traceId = "";
                    else {
                      object.traceId = [];
                      if (options2.bytes !== Array)
                        object.traceId = $util.newBuffer(object.traceId);
                    }
                    if (options2.bytes === String)
                      object.spanId = "";
                    else {
                      object.spanId = [];
                      if (options2.bytes !== Array)
                        object.spanId = $util.newBuffer(object.spanId);
                    }
                    object.traceState = "";
                    object.droppedAttributesCount = 0;
                    object.flags = 0;
                  }
                  if (message.traceId != null && message.hasOwnProperty("traceId"))
                    object.traceId = options2.bytes === String ? $util.base64.encode(message.traceId, 0, message.traceId.length) : options2.bytes === Array ? Array.prototype.slice.call(message.traceId) : message.traceId;
                  if (message.spanId != null && message.hasOwnProperty("spanId"))
                    object.spanId = options2.bytes === String ? $util.base64.encode(message.spanId, 0, message.spanId.length) : options2.bytes === Array ? Array.prototype.slice.call(message.spanId) : message.spanId;
                  if (message.traceState != null && message.hasOwnProperty("traceState"))
                    object.traceState = message.traceState;
                  if (message.attributes && message.attributes.length) {
                    object.attributes = [];
                    for (var j = 0; j < message.attributes.length; ++j)
                      object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options2);
                  }
                  if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount"))
                    object.droppedAttributesCount = message.droppedAttributesCount;
                  if (message.flags != null && message.hasOwnProperty("flags"))
                    object.flags = message.flags;
                  return object;
                }, "toObject");
                Link2.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                Link2.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.trace.v1.Span.Link";
                }, "getTypeUrl");
                return Link2;
              }();
              return Span;
            }();
            v12.Status = function() {
              function Status(properties) {
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(Status, "Status");
              Status.prototype.message = null;
              Status.prototype.code = null;
              Status.create = /* @__PURE__ */ __name(function create3(properties) {
                return new Status(properties);
              }, "create");
              Status.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.message != null && Object.hasOwnProperty.call(message, "message"))
                  writer.uint32(
                    /* id 2, wireType 2 =*/
                    18
                  ).string(message.message);
                if (message.code != null && Object.hasOwnProperty.call(message, "code"))
                  writer.uint32(
                    /* id 3, wireType 0 =*/
                    24
                  ).int32(message.code);
                return writer;
              }, "encode");
              Status.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              Status.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.Status();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 2: {
                      message.message = reader.string();
                      break;
                    }
                    case 3: {
                      message.code = reader.int32();
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              Status.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              Status.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.message != null && message.hasOwnProperty("message")) {
                  if (!$util.isString(message.message))
                    return "message: string expected";
                }
                if (message.code != null && message.hasOwnProperty("code"))
                  switch (message.code) {
                    default:
                      return "code: enum value expected";
                    case 0:
                    case 1:
                    case 2:
                      break;
                  }
                return null;
              }, "verify");
              Status.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.trace.v1.Status)
                  return object;
                var message = new $root.opentelemetry.proto.trace.v1.Status();
                if (object.message != null)
                  message.message = String(object.message);
                switch (object.code) {
                  default:
                    if (typeof object.code === "number") {
                      message.code = object.code;
                      break;
                    }
                    break;
                  case "STATUS_CODE_UNSET":
                  case 0:
                    message.code = 0;
                    break;
                  case "STATUS_CODE_OK":
                  case 1:
                    message.code = 1;
                    break;
                  case "STATUS_CODE_ERROR":
                  case 2:
                    message.code = 2;
                    break;
                }
                return message;
              }, "fromObject");
              Status.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.defaults) {
                  object.message = "";
                  object.code = options2.enums === String ? "STATUS_CODE_UNSET" : 0;
                }
                if (message.message != null && message.hasOwnProperty("message"))
                  object.message = message.message;
                if (message.code != null && message.hasOwnProperty("code"))
                  object.code = options2.enums === String ? $root.opentelemetry.proto.trace.v1.Status.StatusCode[message.code] === void 0 ? message.code : $root.opentelemetry.proto.trace.v1.Status.StatusCode[message.code] : message.code;
                return object;
              }, "toObject");
              Status.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              Status.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.trace.v1.Status";
              }, "getTypeUrl");
              Status.StatusCode = function() {
                var valuesById = {}, values = Object.create(valuesById);
                values[valuesById[0] = "STATUS_CODE_UNSET"] = 0;
                values[valuesById[1] = "STATUS_CODE_OK"] = 1;
                values[valuesById[2] = "STATUS_CODE_ERROR"] = 2;
                return values;
              }();
              return Status;
            }();
            v12.SpanFlags = function() {
              var valuesById = {}, values = Object.create(valuesById);
              values[valuesById[0] = "SPAN_FLAGS_DO_NOT_USE"] = 0;
              values[valuesById[255] = "SPAN_FLAGS_TRACE_FLAGS_MASK"] = 255;
              values[valuesById[256] = "SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK"] = 256;
              values[valuesById[512] = "SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK"] = 512;
              return values;
            }();
            return v12;
          }();
          return trace2;
        }();
        proto3.collector = function() {
          var collector = {};
          collector.trace = function() {
            var trace2 = {};
            trace2.v1 = function() {
              var v12 = {};
              v12.TraceService = function() {
                function TraceService(rpcImpl, requestDelimited, responseDelimited) {
                  $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited);
                }
                __name(TraceService, "TraceService");
                (TraceService.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = TraceService;
                TraceService.create = /* @__PURE__ */ __name(function create3(rpcImpl, requestDelimited, responseDelimited) {
                  return new this(rpcImpl, requestDelimited, responseDelimited);
                }, "create");
                Object.defineProperty(TraceService.prototype["export"] = /* @__PURE__ */ __name(function export_(request4, callback) {
                  return this.rpcCall(export_, $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest, $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse, request4, callback);
                }, "export_"), "name", { value: "Export" });
                return TraceService;
              }();
              v12.ExportTraceServiceRequest = function() {
                function ExportTraceServiceRequest(properties) {
                  this.resourceSpans = [];
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ExportTraceServiceRequest, "ExportTraceServiceRequest");
                ExportTraceServiceRequest.prototype.resourceSpans = $util.emptyArray;
                ExportTraceServiceRequest.create = /* @__PURE__ */ __name(function create3(properties) {
                  return new ExportTraceServiceRequest(properties);
                }, "create");
                ExportTraceServiceRequest.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.resourceSpans != null && message.resourceSpans.length)
                    for (var i = 0; i < message.resourceSpans.length; ++i)
                      $root.opentelemetry.proto.trace.v1.ResourceSpans.encode(message.resourceSpans[i], writer.uint32(
                        /* id 1, wireType 2 =*/
                        10
                      ).fork()).ldelim();
                  return writer;
                }, "encode");
                ExportTraceServiceRequest.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ExportTraceServiceRequest.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest();
                  while (reader.pos < end) {
                    var tag2 = reader.uint32();
                    if (tag2 === error)
                      break;
                    switch (tag2 >>> 3) {
                      case 1: {
                        if (!(message.resourceSpans && message.resourceSpans.length))
                          message.resourceSpans = [];
                        message.resourceSpans.push($root.opentelemetry.proto.trace.v1.ResourceSpans.decode(reader, reader.uint32()));
                        break;
                      }
                      default:
                        reader.skipType(tag2 & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ExportTraceServiceRequest.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ExportTraceServiceRequest.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.resourceSpans != null && message.hasOwnProperty("resourceSpans")) {
                    if (!Array.isArray(message.resourceSpans))
                      return "resourceSpans: array expected";
                    for (var i = 0; i < message.resourceSpans.length; ++i) {
                      var error = $root.opentelemetry.proto.trace.v1.ResourceSpans.verify(message.resourceSpans[i]);
                      if (error)
                        return "resourceSpans." + error;
                    }
                  }
                  return null;
                }, "verify");
                ExportTraceServiceRequest.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest)
                    return object;
                  var message = new $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest();
                  if (object.resourceSpans) {
                    if (!Array.isArray(object.resourceSpans))
                      throw TypeError(".opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.resourceSpans: array expected");
                    message.resourceSpans = [];
                    for (var i = 0; i < object.resourceSpans.length; ++i) {
                      if (typeof object.resourceSpans[i] !== "object")
                        throw TypeError(".opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.resourceSpans: object expected");
                      message.resourceSpans[i] = $root.opentelemetry.proto.trace.v1.ResourceSpans.fromObject(object.resourceSpans[i]);
                    }
                  }
                  return message;
                }, "fromObject");
                ExportTraceServiceRequest.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object = {};
                  if (options2.arrays || options2.defaults)
                    object.resourceSpans = [];
                  if (message.resourceSpans && message.resourceSpans.length) {
                    object.resourceSpans = [];
                    for (var j = 0; j < message.resourceSpans.length; ++j)
                      object.resourceSpans[j] = $root.opentelemetry.proto.trace.v1.ResourceSpans.toObject(message.resourceSpans[j], options2);
                  }
                  return object;
                }, "toObject");
                ExportTraceServiceRequest.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ExportTraceServiceRequest.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest";
                }, "getTypeUrl");
                return ExportTraceServiceRequest;
              }();
              v12.ExportTraceServiceResponse = function() {
                function ExportTraceServiceResponse(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ExportTraceServiceResponse, "ExportTraceServiceResponse");
                ExportTraceServiceResponse.prototype.partialSuccess = null;
                ExportTraceServiceResponse.create = /* @__PURE__ */ __name(function create3(properties) {
                  return new ExportTraceServiceResponse(properties);
                }, "create");
                ExportTraceServiceResponse.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.partialSuccess != null && Object.hasOwnProperty.call(message, "partialSuccess"))
                    $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.encode(message.partialSuccess, writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                  return writer;
                }, "encode");
                ExportTraceServiceResponse.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ExportTraceServiceResponse.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse();
                  while (reader.pos < end) {
                    var tag2 = reader.uint32();
                    if (tag2 === error)
                      break;
                    switch (tag2 >>> 3) {
                      case 1: {
                        message.partialSuccess = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.decode(reader, reader.uint32());
                        break;
                      }
                      default:
                        reader.skipType(tag2 & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ExportTraceServiceResponse.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ExportTraceServiceResponse.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess")) {
                    var error = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.verify(message.partialSuccess);
                    if (error)
                      return "partialSuccess." + error;
                  }
                  return null;
                }, "verify");
                ExportTraceServiceResponse.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse)
                    return object;
                  var message = new $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse();
                  if (object.partialSuccess != null) {
                    if (typeof object.partialSuccess !== "object")
                      throw TypeError(".opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse.partialSuccess: object expected");
                    message.partialSuccess = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.fromObject(object.partialSuccess);
                  }
                  return message;
                }, "fromObject");
                ExportTraceServiceResponse.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object = {};
                  if (options2.defaults)
                    object.partialSuccess = null;
                  if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess"))
                    object.partialSuccess = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.toObject(message.partialSuccess, options2);
                  return object;
                }, "toObject");
                ExportTraceServiceResponse.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ExportTraceServiceResponse.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse";
                }, "getTypeUrl");
                return ExportTraceServiceResponse;
              }();
              v12.ExportTracePartialSuccess = function() {
                function ExportTracePartialSuccess(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ExportTracePartialSuccess, "ExportTracePartialSuccess");
                ExportTracePartialSuccess.prototype.rejectedSpans = null;
                ExportTracePartialSuccess.prototype.errorMessage = null;
                ExportTracePartialSuccess.create = /* @__PURE__ */ __name(function create3(properties) {
                  return new ExportTracePartialSuccess(properties);
                }, "create");
                ExportTracePartialSuccess.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.rejectedSpans != null && Object.hasOwnProperty.call(message, "rejectedSpans"))
                    writer.uint32(
                      /* id 1, wireType 0 =*/
                      8
                    ).int64(message.rejectedSpans);
                  if (message.errorMessage != null && Object.hasOwnProperty.call(message, "errorMessage"))
                    writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).string(message.errorMessage);
                  return writer;
                }, "encode");
                ExportTracePartialSuccess.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ExportTracePartialSuccess.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess();
                  while (reader.pos < end) {
                    var tag2 = reader.uint32();
                    if (tag2 === error)
                      break;
                    switch (tag2 >>> 3) {
                      case 1: {
                        message.rejectedSpans = reader.int64();
                        break;
                      }
                      case 2: {
                        message.errorMessage = reader.string();
                        break;
                      }
                      default:
                        reader.skipType(tag2 & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ExportTracePartialSuccess.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ExportTracePartialSuccess.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.rejectedSpans != null && message.hasOwnProperty("rejectedSpans")) {
                    if (!$util.isInteger(message.rejectedSpans) && !(message.rejectedSpans && $util.isInteger(message.rejectedSpans.low) && $util.isInteger(message.rejectedSpans.high)))
                      return "rejectedSpans: integer|Long expected";
                  }
                  if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) {
                    if (!$util.isString(message.errorMessage))
                      return "errorMessage: string expected";
                  }
                  return null;
                }, "verify");
                ExportTracePartialSuccess.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess)
                    return object;
                  var message = new $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess();
                  if (object.rejectedSpans != null) {
                    if ($util.Long)
                      (message.rejectedSpans = $util.Long.fromValue(object.rejectedSpans)).unsigned = false;
                    else if (typeof object.rejectedSpans === "string")
                      message.rejectedSpans = parseInt(object.rejectedSpans, 10);
                    else if (typeof object.rejectedSpans === "number")
                      message.rejectedSpans = object.rejectedSpans;
                    else if (typeof object.rejectedSpans === "object")
                      message.rejectedSpans = new $util.LongBits(object.rejectedSpans.low >>> 0, object.rejectedSpans.high >>> 0).toNumber();
                  }
                  if (object.errorMessage != null)
                    message.errorMessage = String(object.errorMessage);
                  return message;
                }, "fromObject");
                ExportTracePartialSuccess.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object = {};
                  if (options2.defaults) {
                    if ($util.Long) {
                      var long = new $util.Long(0, 0, false);
                      object.rejectedSpans = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                    } else
                      object.rejectedSpans = options2.longs === String ? "0" : 0;
                    object.errorMessage = "";
                  }
                  if (message.rejectedSpans != null && message.hasOwnProperty("rejectedSpans"))
                    if (typeof message.rejectedSpans === "number")
                      object.rejectedSpans = options2.longs === String ? String(message.rejectedSpans) : message.rejectedSpans;
                    else
                      object.rejectedSpans = options2.longs === String ? $util.Long.prototype.toString.call(message.rejectedSpans) : options2.longs === Number ? new $util.LongBits(message.rejectedSpans.low >>> 0, message.rejectedSpans.high >>> 0).toNumber() : message.rejectedSpans;
                  if (message.errorMessage != null && message.hasOwnProperty("errorMessage"))
                    object.errorMessage = message.errorMessage;
                  return object;
                }, "toObject");
                ExportTracePartialSuccess.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ExportTracePartialSuccess.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess";
                }, "getTypeUrl");
                return ExportTracePartialSuccess;
              }();
              return v12;
            }();
            return trace2;
          }();
          collector.metrics = function() {
            var metrics2 = {};
            metrics2.v1 = function() {
              var v12 = {};
              v12.MetricsService = function() {
                function MetricsService(rpcImpl, requestDelimited, responseDelimited) {
                  $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited);
                }
                __name(MetricsService, "MetricsService");
                (MetricsService.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = MetricsService;
                MetricsService.create = /* @__PURE__ */ __name(function create3(rpcImpl, requestDelimited, responseDelimited) {
                  return new this(rpcImpl, requestDelimited, responseDelimited);
                }, "create");
                Object.defineProperty(MetricsService.prototype["export"] = /* @__PURE__ */ __name(function export_(request4, callback) {
                  return this.rpcCall(export_, $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest, $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse, request4, callback);
                }, "export_"), "name", { value: "Export" });
                return MetricsService;
              }();
              v12.ExportMetricsServiceRequest = function() {
                function ExportMetricsServiceRequest(properties) {
                  this.resourceMetrics = [];
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ExportMetricsServiceRequest, "ExportMetricsServiceRequest");
                ExportMetricsServiceRequest.prototype.resourceMetrics = $util.emptyArray;
                ExportMetricsServiceRequest.create = /* @__PURE__ */ __name(function create3(properties) {
                  return new ExportMetricsServiceRequest(properties);
                }, "create");
                ExportMetricsServiceRequest.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.resourceMetrics != null && message.resourceMetrics.length)
                    for (var i = 0; i < message.resourceMetrics.length; ++i)
                      $root.opentelemetry.proto.metrics.v1.ResourceMetrics.encode(message.resourceMetrics[i], writer.uint32(
                        /* id 1, wireType 2 =*/
                        10
                      ).fork()).ldelim();
                  return writer;
                }, "encode");
                ExportMetricsServiceRequest.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ExportMetricsServiceRequest.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest();
                  while (reader.pos < end) {
                    var tag2 = reader.uint32();
                    if (tag2 === error)
                      break;
                    switch (tag2 >>> 3) {
                      case 1: {
                        if (!(message.resourceMetrics && message.resourceMetrics.length))
                          message.resourceMetrics = [];
                        message.resourceMetrics.push($root.opentelemetry.proto.metrics.v1.ResourceMetrics.decode(reader, reader.uint32()));
                        break;
                      }
                      default:
                        reader.skipType(tag2 & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ExportMetricsServiceRequest.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ExportMetricsServiceRequest.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.resourceMetrics != null && message.hasOwnProperty("resourceMetrics")) {
                    if (!Array.isArray(message.resourceMetrics))
                      return "resourceMetrics: array expected";
                    for (var i = 0; i < message.resourceMetrics.length; ++i) {
                      var error = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.verify(message.resourceMetrics[i]);
                      if (error)
                        return "resourceMetrics." + error;
                    }
                  }
                  return null;
                }, "verify");
                ExportMetricsServiceRequest.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest)
                    return object;
                  var message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest();
                  if (object.resourceMetrics) {
                    if (!Array.isArray(object.resourceMetrics))
                      throw TypeError(".opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.resourceMetrics: array expected");
                    message.resourceMetrics = [];
                    for (var i = 0; i < object.resourceMetrics.length; ++i) {
                      if (typeof object.resourceMetrics[i] !== "object")
                        throw TypeError(".opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.resourceMetrics: object expected");
                      message.resourceMetrics[i] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.fromObject(object.resourceMetrics[i]);
                    }
                  }
                  return message;
                }, "fromObject");
                ExportMetricsServiceRequest.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object = {};
                  if (options2.arrays || options2.defaults)
                    object.resourceMetrics = [];
                  if (message.resourceMetrics && message.resourceMetrics.length) {
                    object.resourceMetrics = [];
                    for (var j = 0; j < message.resourceMetrics.length; ++j)
                      object.resourceMetrics[j] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.toObject(message.resourceMetrics[j], options2);
                  }
                  return object;
                }, "toObject");
                ExportMetricsServiceRequest.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ExportMetricsServiceRequest.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest";
                }, "getTypeUrl");
                return ExportMetricsServiceRequest;
              }();
              v12.ExportMetricsServiceResponse = function() {
                function ExportMetricsServiceResponse(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ExportMetricsServiceResponse, "ExportMetricsServiceResponse");
                ExportMetricsServiceResponse.prototype.partialSuccess = null;
                ExportMetricsServiceResponse.create = /* @__PURE__ */ __name(function create3(properties) {
                  return new ExportMetricsServiceResponse(properties);
                }, "create");
                ExportMetricsServiceResponse.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.partialSuccess != null && Object.hasOwnProperty.call(message, "partialSuccess"))
                    $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.encode(message.partialSuccess, writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                  return writer;
                }, "encode");
                ExportMetricsServiceResponse.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ExportMetricsServiceResponse.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse();
                  while (reader.pos < end) {
                    var tag2 = reader.uint32();
                    if (tag2 === error)
                      break;
                    switch (tag2 >>> 3) {
                      case 1: {
                        message.partialSuccess = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.decode(reader, reader.uint32());
                        break;
                      }
                      default:
                        reader.skipType(tag2 & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ExportMetricsServiceResponse.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ExportMetricsServiceResponse.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess")) {
                    var error = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.verify(message.partialSuccess);
                    if (error)
                      return "partialSuccess." + error;
                  }
                  return null;
                }, "verify");
                ExportMetricsServiceResponse.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse)
                    return object;
                  var message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse();
                  if (object.partialSuccess != null) {
                    if (typeof object.partialSuccess !== "object")
                      throw TypeError(".opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse.partialSuccess: object expected");
                    message.partialSuccess = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.fromObject(object.partialSuccess);
                  }
                  return message;
                }, "fromObject");
                ExportMetricsServiceResponse.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object = {};
                  if (options2.defaults)
                    object.partialSuccess = null;
                  if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess"))
                    object.partialSuccess = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.toObject(message.partialSuccess, options2);
                  return object;
                }, "toObject");
                ExportMetricsServiceResponse.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ExportMetricsServiceResponse.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse";
                }, "getTypeUrl");
                return ExportMetricsServiceResponse;
              }();
              v12.ExportMetricsPartialSuccess = function() {
                function ExportMetricsPartialSuccess(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ExportMetricsPartialSuccess, "ExportMetricsPartialSuccess");
                ExportMetricsPartialSuccess.prototype.rejectedDataPoints = null;
                ExportMetricsPartialSuccess.prototype.errorMessage = null;
                ExportMetricsPartialSuccess.create = /* @__PURE__ */ __name(function create3(properties) {
                  return new ExportMetricsPartialSuccess(properties);
                }, "create");
                ExportMetricsPartialSuccess.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.rejectedDataPoints != null && Object.hasOwnProperty.call(message, "rejectedDataPoints"))
                    writer.uint32(
                      /* id 1, wireType 0 =*/
                      8
                    ).int64(message.rejectedDataPoints);
                  if (message.errorMessage != null && Object.hasOwnProperty.call(message, "errorMessage"))
                    writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).string(message.errorMessage);
                  return writer;
                }, "encode");
                ExportMetricsPartialSuccess.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ExportMetricsPartialSuccess.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess();
                  while (reader.pos < end) {
                    var tag2 = reader.uint32();
                    if (tag2 === error)
                      break;
                    switch (tag2 >>> 3) {
                      case 1: {
                        message.rejectedDataPoints = reader.int64();
                        break;
                      }
                      case 2: {
                        message.errorMessage = reader.string();
                        break;
                      }
                      default:
                        reader.skipType(tag2 & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ExportMetricsPartialSuccess.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ExportMetricsPartialSuccess.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.rejectedDataPoints != null && message.hasOwnProperty("rejectedDataPoints")) {
                    if (!$util.isInteger(message.rejectedDataPoints) && !(message.rejectedDataPoints && $util.isInteger(message.rejectedDataPoints.low) && $util.isInteger(message.rejectedDataPoints.high)))
                      return "rejectedDataPoints: integer|Long expected";
                  }
                  if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) {
                    if (!$util.isString(message.errorMessage))
                      return "errorMessage: string expected";
                  }
                  return null;
                }, "verify");
                ExportMetricsPartialSuccess.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess)
                    return object;
                  var message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess();
                  if (object.rejectedDataPoints != null) {
                    if ($util.Long)
                      (message.rejectedDataPoints = $util.Long.fromValue(object.rejectedDataPoints)).unsigned = false;
                    else if (typeof object.rejectedDataPoints === "string")
                      message.rejectedDataPoints = parseInt(object.rejectedDataPoints, 10);
                    else if (typeof object.rejectedDataPoints === "number")
                      message.rejectedDataPoints = object.rejectedDataPoints;
                    else if (typeof object.rejectedDataPoints === "object")
                      message.rejectedDataPoints = new $util.LongBits(object.rejectedDataPoints.low >>> 0, object.rejectedDataPoints.high >>> 0).toNumber();
                  }
                  if (object.errorMessage != null)
                    message.errorMessage = String(object.errorMessage);
                  return message;
                }, "fromObject");
                ExportMetricsPartialSuccess.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object = {};
                  if (options2.defaults) {
                    if ($util.Long) {
                      var long = new $util.Long(0, 0, false);
                      object.rejectedDataPoints = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                    } else
                      object.rejectedDataPoints = options2.longs === String ? "0" : 0;
                    object.errorMessage = "";
                  }
                  if (message.rejectedDataPoints != null && message.hasOwnProperty("rejectedDataPoints"))
                    if (typeof message.rejectedDataPoints === "number")
                      object.rejectedDataPoints = options2.longs === String ? String(message.rejectedDataPoints) : message.rejectedDataPoints;
                    else
                      object.rejectedDataPoints = options2.longs === String ? $util.Long.prototype.toString.call(message.rejectedDataPoints) : options2.longs === Number ? new $util.LongBits(message.rejectedDataPoints.low >>> 0, message.rejectedDataPoints.high >>> 0).toNumber() : message.rejectedDataPoints;
                  if (message.errorMessage != null && message.hasOwnProperty("errorMessage"))
                    object.errorMessage = message.errorMessage;
                  return object;
                }, "toObject");
                ExportMetricsPartialSuccess.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ExportMetricsPartialSuccess.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess";
                }, "getTypeUrl");
                return ExportMetricsPartialSuccess;
              }();
              return v12;
            }();
            return metrics2;
          }();
          collector.logs = function() {
            var logs2 = {};
            logs2.v1 = function() {
              var v12 = {};
              v12.LogsService = function() {
                function LogsService(rpcImpl, requestDelimited, responseDelimited) {
                  $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited);
                }
                __name(LogsService, "LogsService");
                (LogsService.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = LogsService;
                LogsService.create = /* @__PURE__ */ __name(function create3(rpcImpl, requestDelimited, responseDelimited) {
                  return new this(rpcImpl, requestDelimited, responseDelimited);
                }, "create");
                Object.defineProperty(LogsService.prototype["export"] = /* @__PURE__ */ __name(function export_(request4, callback) {
                  return this.rpcCall(export_, $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest, $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse, request4, callback);
                }, "export_"), "name", { value: "Export" });
                return LogsService;
              }();
              v12.ExportLogsServiceRequest = function() {
                function ExportLogsServiceRequest(properties) {
                  this.resourceLogs = [];
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ExportLogsServiceRequest, "ExportLogsServiceRequest");
                ExportLogsServiceRequest.prototype.resourceLogs = $util.emptyArray;
                ExportLogsServiceRequest.create = /* @__PURE__ */ __name(function create3(properties) {
                  return new ExportLogsServiceRequest(properties);
                }, "create");
                ExportLogsServiceRequest.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.resourceLogs != null && message.resourceLogs.length)
                    for (var i = 0; i < message.resourceLogs.length; ++i)
                      $root.opentelemetry.proto.logs.v1.ResourceLogs.encode(message.resourceLogs[i], writer.uint32(
                        /* id 1, wireType 2 =*/
                        10
                      ).fork()).ldelim();
                  return writer;
                }, "encode");
                ExportLogsServiceRequest.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ExportLogsServiceRequest.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest();
                  while (reader.pos < end) {
                    var tag2 = reader.uint32();
                    if (tag2 === error)
                      break;
                    switch (tag2 >>> 3) {
                      case 1: {
                        if (!(message.resourceLogs && message.resourceLogs.length))
                          message.resourceLogs = [];
                        message.resourceLogs.push($root.opentelemetry.proto.logs.v1.ResourceLogs.decode(reader, reader.uint32()));
                        break;
                      }
                      default:
                        reader.skipType(tag2 & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ExportLogsServiceRequest.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ExportLogsServiceRequest.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.resourceLogs != null && message.hasOwnProperty("resourceLogs")) {
                    if (!Array.isArray(message.resourceLogs))
                      return "resourceLogs: array expected";
                    for (var i = 0; i < message.resourceLogs.length; ++i) {
                      var error = $root.opentelemetry.proto.logs.v1.ResourceLogs.verify(message.resourceLogs[i]);
                      if (error)
                        return "resourceLogs." + error;
                    }
                  }
                  return null;
                }, "verify");
                ExportLogsServiceRequest.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest)
                    return object;
                  var message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest();
                  if (object.resourceLogs) {
                    if (!Array.isArray(object.resourceLogs))
                      throw TypeError(".opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.resourceLogs: array expected");
                    message.resourceLogs = [];
                    for (var i = 0; i < object.resourceLogs.length; ++i) {
                      if (typeof object.resourceLogs[i] !== "object")
                        throw TypeError(".opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.resourceLogs: object expected");
                      message.resourceLogs[i] = $root.opentelemetry.proto.logs.v1.ResourceLogs.fromObject(object.resourceLogs[i]);
                    }
                  }
                  return message;
                }, "fromObject");
                ExportLogsServiceRequest.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object = {};
                  if (options2.arrays || options2.defaults)
                    object.resourceLogs = [];
                  if (message.resourceLogs && message.resourceLogs.length) {
                    object.resourceLogs = [];
                    for (var j = 0; j < message.resourceLogs.length; ++j)
                      object.resourceLogs[j] = $root.opentelemetry.proto.logs.v1.ResourceLogs.toObject(message.resourceLogs[j], options2);
                  }
                  return object;
                }, "toObject");
                ExportLogsServiceRequest.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ExportLogsServiceRequest.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest";
                }, "getTypeUrl");
                return ExportLogsServiceRequest;
              }();
              v12.ExportLogsServiceResponse = function() {
                function ExportLogsServiceResponse(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ExportLogsServiceResponse, "ExportLogsServiceResponse");
                ExportLogsServiceResponse.prototype.partialSuccess = null;
                ExportLogsServiceResponse.create = /* @__PURE__ */ __name(function create3(properties) {
                  return new ExportLogsServiceResponse(properties);
                }, "create");
                ExportLogsServiceResponse.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.partialSuccess != null && Object.hasOwnProperty.call(message, "partialSuccess"))
                    $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.encode(message.partialSuccess, writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                  return writer;
                }, "encode");
                ExportLogsServiceResponse.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ExportLogsServiceResponse.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse();
                  while (reader.pos < end) {
                    var tag2 = reader.uint32();
                    if (tag2 === error)
                      break;
                    switch (tag2 >>> 3) {
                      case 1: {
                        message.partialSuccess = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.decode(reader, reader.uint32());
                        break;
                      }
                      default:
                        reader.skipType(tag2 & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ExportLogsServiceResponse.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ExportLogsServiceResponse.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess")) {
                    var error = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.verify(message.partialSuccess);
                    if (error)
                      return "partialSuccess." + error;
                  }
                  return null;
                }, "verify");
                ExportLogsServiceResponse.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse)
                    return object;
                  var message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse();
                  if (object.partialSuccess != null) {
                    if (typeof object.partialSuccess !== "object")
                      throw TypeError(".opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse.partialSuccess: object expected");
                    message.partialSuccess = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.fromObject(object.partialSuccess);
                  }
                  return message;
                }, "fromObject");
                ExportLogsServiceResponse.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object = {};
                  if (options2.defaults)
                    object.partialSuccess = null;
                  if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess"))
                    object.partialSuccess = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.toObject(message.partialSuccess, options2);
                  return object;
                }, "toObject");
                ExportLogsServiceResponse.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ExportLogsServiceResponse.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse";
                }, "getTypeUrl");
                return ExportLogsServiceResponse;
              }();
              v12.ExportLogsPartialSuccess = function() {
                function ExportLogsPartialSuccess(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ExportLogsPartialSuccess, "ExportLogsPartialSuccess");
                ExportLogsPartialSuccess.prototype.rejectedLogRecords = null;
                ExportLogsPartialSuccess.prototype.errorMessage = null;
                ExportLogsPartialSuccess.create = /* @__PURE__ */ __name(function create3(properties) {
                  return new ExportLogsPartialSuccess(properties);
                }, "create");
                ExportLogsPartialSuccess.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.rejectedLogRecords != null && Object.hasOwnProperty.call(message, "rejectedLogRecords"))
                    writer.uint32(
                      /* id 1, wireType 0 =*/
                      8
                    ).int64(message.rejectedLogRecords);
                  if (message.errorMessage != null && Object.hasOwnProperty.call(message, "errorMessage"))
                    writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).string(message.errorMessage);
                  return writer;
                }, "encode");
                ExportLogsPartialSuccess.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ExportLogsPartialSuccess.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess();
                  while (reader.pos < end) {
                    var tag2 = reader.uint32();
                    if (tag2 === error)
                      break;
                    switch (tag2 >>> 3) {
                      case 1: {
                        message.rejectedLogRecords = reader.int64();
                        break;
                      }
                      case 2: {
                        message.errorMessage = reader.string();
                        break;
                      }
                      default:
                        reader.skipType(tag2 & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ExportLogsPartialSuccess.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ExportLogsPartialSuccess.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.rejectedLogRecords != null && message.hasOwnProperty("rejectedLogRecords")) {
                    if (!$util.isInteger(message.rejectedLogRecords) && !(message.rejectedLogRecords && $util.isInteger(message.rejectedLogRecords.low) && $util.isInteger(message.rejectedLogRecords.high)))
                      return "rejectedLogRecords: integer|Long expected";
                  }
                  if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) {
                    if (!$util.isString(message.errorMessage))
                      return "errorMessage: string expected";
                  }
                  return null;
                }, "verify");
                ExportLogsPartialSuccess.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess)
                    return object;
                  var message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess();
                  if (object.rejectedLogRecords != null) {
                    if ($util.Long)
                      (message.rejectedLogRecords = $util.Long.fromValue(object.rejectedLogRecords)).unsigned = false;
                    else if (typeof object.rejectedLogRecords === "string")
                      message.rejectedLogRecords = parseInt(object.rejectedLogRecords, 10);
                    else if (typeof object.rejectedLogRecords === "number")
                      message.rejectedLogRecords = object.rejectedLogRecords;
                    else if (typeof object.rejectedLogRecords === "object")
                      message.rejectedLogRecords = new $util.LongBits(object.rejectedLogRecords.low >>> 0, object.rejectedLogRecords.high >>> 0).toNumber();
                  }
                  if (object.errorMessage != null)
                    message.errorMessage = String(object.errorMessage);
                  return message;
                }, "fromObject");
                ExportLogsPartialSuccess.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object = {};
                  if (options2.defaults) {
                    if ($util.Long) {
                      var long = new $util.Long(0, 0, false);
                      object.rejectedLogRecords = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                    } else
                      object.rejectedLogRecords = options2.longs === String ? "0" : 0;
                    object.errorMessage = "";
                  }
                  if (message.rejectedLogRecords != null && message.hasOwnProperty("rejectedLogRecords"))
                    if (typeof message.rejectedLogRecords === "number")
                      object.rejectedLogRecords = options2.longs === String ? String(message.rejectedLogRecords) : message.rejectedLogRecords;
                    else
                      object.rejectedLogRecords = options2.longs === String ? $util.Long.prototype.toString.call(message.rejectedLogRecords) : options2.longs === Number ? new $util.LongBits(message.rejectedLogRecords.low >>> 0, message.rejectedLogRecords.high >>> 0).toNumber() : message.rejectedLogRecords;
                  if (message.errorMessage != null && message.hasOwnProperty("errorMessage"))
                    object.errorMessage = message.errorMessage;
                  return object;
                }, "toObject");
                ExportLogsPartialSuccess.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ExportLogsPartialSuccess.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess";
                }, "getTypeUrl");
                return ExportLogsPartialSuccess;
              }();
              return v12;
            }();
            return logs2;
          }();
          return collector;
        }();
        proto3.metrics = function() {
          var metrics2 = {};
          metrics2.v1 = function() {
            var v12 = {};
            v12.MetricsData = function() {
              function MetricsData(properties) {
                this.resourceMetrics = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(MetricsData, "MetricsData");
              MetricsData.prototype.resourceMetrics = $util.emptyArray;
              MetricsData.create = /* @__PURE__ */ __name(function create3(properties) {
                return new MetricsData(properties);
              }, "create");
              MetricsData.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.resourceMetrics != null && message.resourceMetrics.length)
                  for (var i = 0; i < message.resourceMetrics.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.ResourceMetrics.encode(message.resourceMetrics[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              MetricsData.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              MetricsData.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.MetricsData();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      if (!(message.resourceMetrics && message.resourceMetrics.length))
                        message.resourceMetrics = [];
                      message.resourceMetrics.push($root.opentelemetry.proto.metrics.v1.ResourceMetrics.decode(reader, reader.uint32()));
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              MetricsData.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              MetricsData.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.resourceMetrics != null && message.hasOwnProperty("resourceMetrics")) {
                  if (!Array.isArray(message.resourceMetrics))
                    return "resourceMetrics: array expected";
                  for (var i = 0; i < message.resourceMetrics.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.verify(message.resourceMetrics[i]);
                    if (error)
                      return "resourceMetrics." + error;
                  }
                }
                return null;
              }, "verify");
              MetricsData.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.MetricsData)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.MetricsData();
                if (object.resourceMetrics) {
                  if (!Array.isArray(object.resourceMetrics))
                    throw TypeError(".opentelemetry.proto.metrics.v1.MetricsData.resourceMetrics: array expected");
                  message.resourceMetrics = [];
                  for (var i = 0; i < object.resourceMetrics.length; ++i) {
                    if (typeof object.resourceMetrics[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.MetricsData.resourceMetrics: object expected");
                    message.resourceMetrics[i] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.fromObject(object.resourceMetrics[i]);
                  }
                }
                return message;
              }, "fromObject");
              MetricsData.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.resourceMetrics = [];
                if (message.resourceMetrics && message.resourceMetrics.length) {
                  object.resourceMetrics = [];
                  for (var j = 0; j < message.resourceMetrics.length; ++j)
                    object.resourceMetrics[j] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.toObject(message.resourceMetrics[j], options2);
                }
                return object;
              }, "toObject");
              MetricsData.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              MetricsData.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.MetricsData";
              }, "getTypeUrl");
              return MetricsData;
            }();
            v12.ResourceMetrics = function() {
              function ResourceMetrics(properties) {
                this.scopeMetrics = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(ResourceMetrics, "ResourceMetrics");
              ResourceMetrics.prototype.resource = null;
              ResourceMetrics.prototype.scopeMetrics = $util.emptyArray;
              ResourceMetrics.prototype.schemaUrl = null;
              ResourceMetrics.create = /* @__PURE__ */ __name(function create3(properties) {
                return new ResourceMetrics(properties);
              }, "create");
              ResourceMetrics.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.resource != null && Object.hasOwnProperty.call(message, "resource"))
                  $root.opentelemetry.proto.resource.v1.Resource.encode(message.resource, writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).fork()).ldelim();
                if (message.scopeMetrics != null && message.scopeMetrics.length)
                  for (var i = 0; i < message.scopeMetrics.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.ScopeMetrics.encode(message.scopeMetrics[i], writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).fork()).ldelim();
                if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl"))
                  writer.uint32(
                    /* id 3, wireType 2 =*/
                    26
                  ).string(message.schemaUrl);
                return writer;
              }, "encode");
              ResourceMetrics.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              ResourceMetrics.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ResourceMetrics();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      message.resource = $root.opentelemetry.proto.resource.v1.Resource.decode(reader, reader.uint32());
                      break;
                    }
                    case 2: {
                      if (!(message.scopeMetrics && message.scopeMetrics.length))
                        message.scopeMetrics = [];
                      message.scopeMetrics.push($root.opentelemetry.proto.metrics.v1.ScopeMetrics.decode(reader, reader.uint32()));
                      break;
                    }
                    case 3: {
                      message.schemaUrl = reader.string();
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              ResourceMetrics.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              ResourceMetrics.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.resource != null && message.hasOwnProperty("resource")) {
                  var error = $root.opentelemetry.proto.resource.v1.Resource.verify(message.resource);
                  if (error)
                    return "resource." + error;
                }
                if (message.scopeMetrics != null && message.hasOwnProperty("scopeMetrics")) {
                  if (!Array.isArray(message.scopeMetrics))
                    return "scopeMetrics: array expected";
                  for (var i = 0; i < message.scopeMetrics.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.ScopeMetrics.verify(message.scopeMetrics[i]);
                    if (error)
                      return "scopeMetrics." + error;
                  }
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) {
                  if (!$util.isString(message.schemaUrl))
                    return "schemaUrl: string expected";
                }
                return null;
              }, "verify");
              ResourceMetrics.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.ResourceMetrics)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.ResourceMetrics();
                if (object.resource != null) {
                  if (typeof object.resource !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.ResourceMetrics.resource: object expected");
                  message.resource = $root.opentelemetry.proto.resource.v1.Resource.fromObject(object.resource);
                }
                if (object.scopeMetrics) {
                  if (!Array.isArray(object.scopeMetrics))
                    throw TypeError(".opentelemetry.proto.metrics.v1.ResourceMetrics.scopeMetrics: array expected");
                  message.scopeMetrics = [];
                  for (var i = 0; i < object.scopeMetrics.length; ++i) {
                    if (typeof object.scopeMetrics[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ResourceMetrics.scopeMetrics: object expected");
                    message.scopeMetrics[i] = $root.opentelemetry.proto.metrics.v1.ScopeMetrics.fromObject(object.scopeMetrics[i]);
                  }
                }
                if (object.schemaUrl != null)
                  message.schemaUrl = String(object.schemaUrl);
                return message;
              }, "fromObject");
              ResourceMetrics.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.scopeMetrics = [];
                if (options2.defaults) {
                  object.resource = null;
                  object.schemaUrl = "";
                }
                if (message.resource != null && message.hasOwnProperty("resource"))
                  object.resource = $root.opentelemetry.proto.resource.v1.Resource.toObject(message.resource, options2);
                if (message.scopeMetrics && message.scopeMetrics.length) {
                  object.scopeMetrics = [];
                  for (var j = 0; j < message.scopeMetrics.length; ++j)
                    object.scopeMetrics[j] = $root.opentelemetry.proto.metrics.v1.ScopeMetrics.toObject(message.scopeMetrics[j], options2);
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object.schemaUrl = message.schemaUrl;
                return object;
              }, "toObject");
              ResourceMetrics.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              ResourceMetrics.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ResourceMetrics";
              }, "getTypeUrl");
              return ResourceMetrics;
            }();
            v12.ScopeMetrics = function() {
              function ScopeMetrics(properties) {
                this.metrics = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(ScopeMetrics, "ScopeMetrics");
              ScopeMetrics.prototype.scope = null;
              ScopeMetrics.prototype.metrics = $util.emptyArray;
              ScopeMetrics.prototype.schemaUrl = null;
              ScopeMetrics.create = /* @__PURE__ */ __name(function create3(properties) {
                return new ScopeMetrics(properties);
              }, "create");
              ScopeMetrics.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.scope != null && Object.hasOwnProperty.call(message, "scope"))
                  $root.opentelemetry.proto.common.v1.InstrumentationScope.encode(message.scope, writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).fork()).ldelim();
                if (message.metrics != null && message.metrics.length)
                  for (var i = 0; i < message.metrics.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.Metric.encode(message.metrics[i], writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).fork()).ldelim();
                if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl"))
                  writer.uint32(
                    /* id 3, wireType 2 =*/
                    26
                  ).string(message.schemaUrl);
                return writer;
              }, "encode");
              ScopeMetrics.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              ScopeMetrics.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ScopeMetrics();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.decode(reader, reader.uint32());
                      break;
                    }
                    case 2: {
                      if (!(message.metrics && message.metrics.length))
                        message.metrics = [];
                      message.metrics.push($root.opentelemetry.proto.metrics.v1.Metric.decode(reader, reader.uint32()));
                      break;
                    }
                    case 3: {
                      message.schemaUrl = reader.string();
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              ScopeMetrics.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              ScopeMetrics.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.scope != null && message.hasOwnProperty("scope")) {
                  var error = $root.opentelemetry.proto.common.v1.InstrumentationScope.verify(message.scope);
                  if (error)
                    return "scope." + error;
                }
                if (message.metrics != null && message.hasOwnProperty("metrics")) {
                  if (!Array.isArray(message.metrics))
                    return "metrics: array expected";
                  for (var i = 0; i < message.metrics.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.Metric.verify(message.metrics[i]);
                    if (error)
                      return "metrics." + error;
                  }
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) {
                  if (!$util.isString(message.schemaUrl))
                    return "schemaUrl: string expected";
                }
                return null;
              }, "verify");
              ScopeMetrics.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.ScopeMetrics)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.ScopeMetrics();
                if (object.scope != null) {
                  if (typeof object.scope !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.ScopeMetrics.scope: object expected");
                  message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(object.scope);
                }
                if (object.metrics) {
                  if (!Array.isArray(object.metrics))
                    throw TypeError(".opentelemetry.proto.metrics.v1.ScopeMetrics.metrics: array expected");
                  message.metrics = [];
                  for (var i = 0; i < object.metrics.length; ++i) {
                    if (typeof object.metrics[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ScopeMetrics.metrics: object expected");
                    message.metrics[i] = $root.opentelemetry.proto.metrics.v1.Metric.fromObject(object.metrics[i]);
                  }
                }
                if (object.schemaUrl != null)
                  message.schemaUrl = String(object.schemaUrl);
                return message;
              }, "fromObject");
              ScopeMetrics.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.metrics = [];
                if (options2.defaults) {
                  object.scope = null;
                  object.schemaUrl = "";
                }
                if (message.scope != null && message.hasOwnProperty("scope"))
                  object.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.toObject(message.scope, options2);
                if (message.metrics && message.metrics.length) {
                  object.metrics = [];
                  for (var j = 0; j < message.metrics.length; ++j)
                    object.metrics[j] = $root.opentelemetry.proto.metrics.v1.Metric.toObject(message.metrics[j], options2);
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object.schemaUrl = message.schemaUrl;
                return object;
              }, "toObject");
              ScopeMetrics.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              ScopeMetrics.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ScopeMetrics";
              }, "getTypeUrl");
              return ScopeMetrics;
            }();
            v12.Metric = function() {
              function Metric(properties) {
                this.metadata = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(Metric, "Metric");
              Metric.prototype.name = null;
              Metric.prototype.description = null;
              Metric.prototype.unit = null;
              Metric.prototype.gauge = null;
              Metric.prototype.sum = null;
              Metric.prototype.histogram = null;
              Metric.prototype.exponentialHistogram = null;
              Metric.prototype.summary = null;
              Metric.prototype.metadata = $util.emptyArray;
              var $oneOfFields;
              Object.defineProperty(Metric.prototype, "data", {
                get: $util.oneOfGetter($oneOfFields = ["gauge", "sum", "histogram", "exponentialHistogram", "summary"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              Metric.create = /* @__PURE__ */ __name(function create3(properties) {
                return new Metric(properties);
              }, "create");
              Metric.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.name != null && Object.hasOwnProperty.call(message, "name"))
                  writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).string(message.name);
                if (message.description != null && Object.hasOwnProperty.call(message, "description"))
                  writer.uint32(
                    /* id 2, wireType 2 =*/
                    18
                  ).string(message.description);
                if (message.unit != null && Object.hasOwnProperty.call(message, "unit"))
                  writer.uint32(
                    /* id 3, wireType 2 =*/
                    26
                  ).string(message.unit);
                if (message.gauge != null && Object.hasOwnProperty.call(message, "gauge"))
                  $root.opentelemetry.proto.metrics.v1.Gauge.encode(message.gauge, writer.uint32(
                    /* id 5, wireType 2 =*/
                    42
                  ).fork()).ldelim();
                if (message.sum != null && Object.hasOwnProperty.call(message, "sum"))
                  $root.opentelemetry.proto.metrics.v1.Sum.encode(message.sum, writer.uint32(
                    /* id 7, wireType 2 =*/
                    58
                  ).fork()).ldelim();
                if (message.histogram != null && Object.hasOwnProperty.call(message, "histogram"))
                  $root.opentelemetry.proto.metrics.v1.Histogram.encode(message.histogram, writer.uint32(
                    /* id 9, wireType 2 =*/
                    74
                  ).fork()).ldelim();
                if (message.exponentialHistogram != null && Object.hasOwnProperty.call(message, "exponentialHistogram"))
                  $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.encode(message.exponentialHistogram, writer.uint32(
                    /* id 10, wireType 2 =*/
                    82
                  ).fork()).ldelim();
                if (message.summary != null && Object.hasOwnProperty.call(message, "summary"))
                  $root.opentelemetry.proto.metrics.v1.Summary.encode(message.summary, writer.uint32(
                    /* id 11, wireType 2 =*/
                    90
                  ).fork()).ldelim();
                if (message.metadata != null && message.metadata.length)
                  for (var i = 0; i < message.metadata.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.metadata[i], writer.uint32(
                      /* id 12, wireType 2 =*/
                      98
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              Metric.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              Metric.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Metric();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      message.name = reader.string();
                      break;
                    }
                    case 2: {
                      message.description = reader.string();
                      break;
                    }
                    case 3: {
                      message.unit = reader.string();
                      break;
                    }
                    case 5: {
                      message.gauge = $root.opentelemetry.proto.metrics.v1.Gauge.decode(reader, reader.uint32());
                      break;
                    }
                    case 7: {
                      message.sum = $root.opentelemetry.proto.metrics.v1.Sum.decode(reader, reader.uint32());
                      break;
                    }
                    case 9: {
                      message.histogram = $root.opentelemetry.proto.metrics.v1.Histogram.decode(reader, reader.uint32());
                      break;
                    }
                    case 10: {
                      message.exponentialHistogram = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.decode(reader, reader.uint32());
                      break;
                    }
                    case 11: {
                      message.summary = $root.opentelemetry.proto.metrics.v1.Summary.decode(reader, reader.uint32());
                      break;
                    }
                    case 12: {
                      if (!(message.metadata && message.metadata.length))
                        message.metadata = [];
                      message.metadata.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              Metric.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              Metric.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                var properties = {};
                if (message.name != null && message.hasOwnProperty("name")) {
                  if (!$util.isString(message.name))
                    return "name: string expected";
                }
                if (message.description != null && message.hasOwnProperty("description")) {
                  if (!$util.isString(message.description))
                    return "description: string expected";
                }
                if (message.unit != null && message.hasOwnProperty("unit")) {
                  if (!$util.isString(message.unit))
                    return "unit: string expected";
                }
                if (message.gauge != null && message.hasOwnProperty("gauge")) {
                  properties.data = 1;
                  {
                    var error = $root.opentelemetry.proto.metrics.v1.Gauge.verify(message.gauge);
                    if (error)
                      return "gauge." + error;
                  }
                }
                if (message.sum != null && message.hasOwnProperty("sum")) {
                  if (properties.data === 1)
                    return "data: multiple values";
                  properties.data = 1;
                  {
                    var error = $root.opentelemetry.proto.metrics.v1.Sum.verify(message.sum);
                    if (error)
                      return "sum." + error;
                  }
                }
                if (message.histogram != null && message.hasOwnProperty("histogram")) {
                  if (properties.data === 1)
                    return "data: multiple values";
                  properties.data = 1;
                  {
                    var error = $root.opentelemetry.proto.metrics.v1.Histogram.verify(message.histogram);
                    if (error)
                      return "histogram." + error;
                  }
                }
                if (message.exponentialHistogram != null && message.hasOwnProperty("exponentialHistogram")) {
                  if (properties.data === 1)
                    return "data: multiple values";
                  properties.data = 1;
                  {
                    var error = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.verify(message.exponentialHistogram);
                    if (error)
                      return "exponentialHistogram." + error;
                  }
                }
                if (message.summary != null && message.hasOwnProperty("summary")) {
                  if (properties.data === 1)
                    return "data: multiple values";
                  properties.data = 1;
                  {
                    var error = $root.opentelemetry.proto.metrics.v1.Summary.verify(message.summary);
                    if (error)
                      return "summary." + error;
                  }
                }
                if (message.metadata != null && message.hasOwnProperty("metadata")) {
                  if (!Array.isArray(message.metadata))
                    return "metadata: array expected";
                  for (var i = 0; i < message.metadata.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.metadata[i]);
                    if (error)
                      return "metadata." + error;
                  }
                }
                return null;
              }, "verify");
              Metric.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.Metric)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.Metric();
                if (object.name != null)
                  message.name = String(object.name);
                if (object.description != null)
                  message.description = String(object.description);
                if (object.unit != null)
                  message.unit = String(object.unit);
                if (object.gauge != null) {
                  if (typeof object.gauge !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.Metric.gauge: object expected");
                  message.gauge = $root.opentelemetry.proto.metrics.v1.Gauge.fromObject(object.gauge);
                }
                if (object.sum != null) {
                  if (typeof object.sum !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.Metric.sum: object expected");
                  message.sum = $root.opentelemetry.proto.metrics.v1.Sum.fromObject(object.sum);
                }
                if (object.histogram != null) {
                  if (typeof object.histogram !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.Metric.histogram: object expected");
                  message.histogram = $root.opentelemetry.proto.metrics.v1.Histogram.fromObject(object.histogram);
                }
                if (object.exponentialHistogram != null) {
                  if (typeof object.exponentialHistogram !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.Metric.exponentialHistogram: object expected");
                  message.exponentialHistogram = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.fromObject(object.exponentialHistogram);
                }
                if (object.summary != null) {
                  if (typeof object.summary !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.Metric.summary: object expected");
                  message.summary = $root.opentelemetry.proto.metrics.v1.Summary.fromObject(object.summary);
                }
                if (object.metadata) {
                  if (!Array.isArray(object.metadata))
                    throw TypeError(".opentelemetry.proto.metrics.v1.Metric.metadata: array expected");
                  message.metadata = [];
                  for (var i = 0; i < object.metadata.length; ++i) {
                    if (typeof object.metadata[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Metric.metadata: object expected");
                    message.metadata[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.metadata[i]);
                  }
                }
                return message;
              }, "fromObject");
              Metric.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.metadata = [];
                if (options2.defaults) {
                  object.name = "";
                  object.description = "";
                  object.unit = "";
                }
                if (message.name != null && message.hasOwnProperty("name"))
                  object.name = message.name;
                if (message.description != null && message.hasOwnProperty("description"))
                  object.description = message.description;
                if (message.unit != null && message.hasOwnProperty("unit"))
                  object.unit = message.unit;
                if (message.gauge != null && message.hasOwnProperty("gauge")) {
                  object.gauge = $root.opentelemetry.proto.metrics.v1.Gauge.toObject(message.gauge, options2);
                  if (options2.oneofs)
                    object.data = "gauge";
                }
                if (message.sum != null && message.hasOwnProperty("sum")) {
                  object.sum = $root.opentelemetry.proto.metrics.v1.Sum.toObject(message.sum, options2);
                  if (options2.oneofs)
                    object.data = "sum";
                }
                if (message.histogram != null && message.hasOwnProperty("histogram")) {
                  object.histogram = $root.opentelemetry.proto.metrics.v1.Histogram.toObject(message.histogram, options2);
                  if (options2.oneofs)
                    object.data = "histogram";
                }
                if (message.exponentialHistogram != null && message.hasOwnProperty("exponentialHistogram")) {
                  object.exponentialHistogram = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.toObject(message.exponentialHistogram, options2);
                  if (options2.oneofs)
                    object.data = "exponentialHistogram";
                }
                if (message.summary != null && message.hasOwnProperty("summary")) {
                  object.summary = $root.opentelemetry.proto.metrics.v1.Summary.toObject(message.summary, options2);
                  if (options2.oneofs)
                    object.data = "summary";
                }
                if (message.metadata && message.metadata.length) {
                  object.metadata = [];
                  for (var j = 0; j < message.metadata.length; ++j)
                    object.metadata[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.metadata[j], options2);
                }
                return object;
              }, "toObject");
              Metric.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              Metric.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Metric";
              }, "getTypeUrl");
              return Metric;
            }();
            v12.Gauge = function() {
              function Gauge(properties) {
                this.dataPoints = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(Gauge, "Gauge");
              Gauge.prototype.dataPoints = $util.emptyArray;
              Gauge.create = /* @__PURE__ */ __name(function create3(properties) {
                return new Gauge(properties);
              }, "create");
              Gauge.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.dataPoints != null && message.dataPoints.length)
                  for (var i = 0; i < message.dataPoints.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.NumberDataPoint.encode(message.dataPoints[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              Gauge.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              Gauge.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Gauge();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      if (!(message.dataPoints && message.dataPoints.length))
                        message.dataPoints = [];
                      message.dataPoints.push($root.opentelemetry.proto.metrics.v1.NumberDataPoint.decode(reader, reader.uint32()));
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              Gauge.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              Gauge.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) {
                  if (!Array.isArray(message.dataPoints))
                    return "dataPoints: array expected";
                  for (var i = 0; i < message.dataPoints.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.verify(message.dataPoints[i]);
                    if (error)
                      return "dataPoints." + error;
                  }
                }
                return null;
              }, "verify");
              Gauge.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.Gauge)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.Gauge();
                if (object.dataPoints) {
                  if (!Array.isArray(object.dataPoints))
                    throw TypeError(".opentelemetry.proto.metrics.v1.Gauge.dataPoints: array expected");
                  message.dataPoints = [];
                  for (var i = 0; i < object.dataPoints.length; ++i) {
                    if (typeof object.dataPoints[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Gauge.dataPoints: object expected");
                    message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.fromObject(object.dataPoints[i]);
                  }
                }
                return message;
              }, "fromObject");
              Gauge.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.dataPoints = [];
                if (message.dataPoints && message.dataPoints.length) {
                  object.dataPoints = [];
                  for (var j = 0; j < message.dataPoints.length; ++j)
                    object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.toObject(message.dataPoints[j], options2);
                }
                return object;
              }, "toObject");
              Gauge.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              Gauge.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Gauge";
              }, "getTypeUrl");
              return Gauge;
            }();
            v12.Sum = function() {
              function Sum(properties) {
                this.dataPoints = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(Sum, "Sum");
              Sum.prototype.dataPoints = $util.emptyArray;
              Sum.prototype.aggregationTemporality = null;
              Sum.prototype.isMonotonic = null;
              Sum.create = /* @__PURE__ */ __name(function create3(properties) {
                return new Sum(properties);
              }, "create");
              Sum.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.dataPoints != null && message.dataPoints.length)
                  for (var i = 0; i < message.dataPoints.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.NumberDataPoint.encode(message.dataPoints[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                if (message.aggregationTemporality != null && Object.hasOwnProperty.call(message, "aggregationTemporality"))
                  writer.uint32(
                    /* id 2, wireType 0 =*/
                    16
                  ).int32(message.aggregationTemporality);
                if (message.isMonotonic != null && Object.hasOwnProperty.call(message, "isMonotonic"))
                  writer.uint32(
                    /* id 3, wireType 0 =*/
                    24
                  ).bool(message.isMonotonic);
                return writer;
              }, "encode");
              Sum.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              Sum.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Sum();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      if (!(message.dataPoints && message.dataPoints.length))
                        message.dataPoints = [];
                      message.dataPoints.push($root.opentelemetry.proto.metrics.v1.NumberDataPoint.decode(reader, reader.uint32()));
                      break;
                    }
                    case 2: {
                      message.aggregationTemporality = reader.int32();
                      break;
                    }
                    case 3: {
                      message.isMonotonic = reader.bool();
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              Sum.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              Sum.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) {
                  if (!Array.isArray(message.dataPoints))
                    return "dataPoints: array expected";
                  for (var i = 0; i < message.dataPoints.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.verify(message.dataPoints[i]);
                    if (error)
                      return "dataPoints." + error;
                  }
                }
                if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality"))
                  switch (message.aggregationTemporality) {
                    default:
                      return "aggregationTemporality: enum value expected";
                    case 0:
                    case 1:
                    case 2:
                      break;
                  }
                if (message.isMonotonic != null && message.hasOwnProperty("isMonotonic")) {
                  if (typeof message.isMonotonic !== "boolean")
                    return "isMonotonic: boolean expected";
                }
                return null;
              }, "verify");
              Sum.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.Sum)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.Sum();
                if (object.dataPoints) {
                  if (!Array.isArray(object.dataPoints))
                    throw TypeError(".opentelemetry.proto.metrics.v1.Sum.dataPoints: array expected");
                  message.dataPoints = [];
                  for (var i = 0; i < object.dataPoints.length; ++i) {
                    if (typeof object.dataPoints[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Sum.dataPoints: object expected");
                    message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.fromObject(object.dataPoints[i]);
                  }
                }
                switch (object.aggregationTemporality) {
                  default:
                    if (typeof object.aggregationTemporality === "number") {
                      message.aggregationTemporality = object.aggregationTemporality;
                      break;
                    }
                    break;
                  case "AGGREGATION_TEMPORALITY_UNSPECIFIED":
                  case 0:
                    message.aggregationTemporality = 0;
                    break;
                  case "AGGREGATION_TEMPORALITY_DELTA":
                  case 1:
                    message.aggregationTemporality = 1;
                    break;
                  case "AGGREGATION_TEMPORALITY_CUMULATIVE":
                  case 2:
                    message.aggregationTemporality = 2;
                    break;
                }
                if (object.isMonotonic != null)
                  message.isMonotonic = Boolean(object.isMonotonic);
                return message;
              }, "fromObject");
              Sum.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.dataPoints = [];
                if (options2.defaults) {
                  object.aggregationTemporality = options2.enums === String ? "AGGREGATION_TEMPORALITY_UNSPECIFIED" : 0;
                  object.isMonotonic = false;
                }
                if (message.dataPoints && message.dataPoints.length) {
                  object.dataPoints = [];
                  for (var j = 0; j < message.dataPoints.length; ++j)
                    object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.toObject(message.dataPoints[j], options2);
                }
                if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality"))
                  object.aggregationTemporality = options2.enums === String ? $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] === void 0 ? message.aggregationTemporality : $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] : message.aggregationTemporality;
                if (message.isMonotonic != null && message.hasOwnProperty("isMonotonic"))
                  object.isMonotonic = message.isMonotonic;
                return object;
              }, "toObject");
              Sum.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              Sum.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Sum";
              }, "getTypeUrl");
              return Sum;
            }();
            v12.Histogram = function() {
              function Histogram(properties) {
                this.dataPoints = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(Histogram, "Histogram");
              Histogram.prototype.dataPoints = $util.emptyArray;
              Histogram.prototype.aggregationTemporality = null;
              Histogram.create = /* @__PURE__ */ __name(function create3(properties) {
                return new Histogram(properties);
              }, "create");
              Histogram.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.dataPoints != null && message.dataPoints.length)
                  for (var i = 0; i < message.dataPoints.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.encode(message.dataPoints[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                if (message.aggregationTemporality != null && Object.hasOwnProperty.call(message, "aggregationTemporality"))
                  writer.uint32(
                    /* id 2, wireType 0 =*/
                    16
                  ).int32(message.aggregationTemporality);
                return writer;
              }, "encode");
              Histogram.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              Histogram.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Histogram();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      if (!(message.dataPoints && message.dataPoints.length))
                        message.dataPoints = [];
                      message.dataPoints.push($root.opentelemetry.proto.metrics.v1.HistogramDataPoint.decode(reader, reader.uint32()));
                      break;
                    }
                    case 2: {
                      message.aggregationTemporality = reader.int32();
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              Histogram.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              Histogram.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) {
                  if (!Array.isArray(message.dataPoints))
                    return "dataPoints: array expected";
                  for (var i = 0; i < message.dataPoints.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.verify(message.dataPoints[i]);
                    if (error)
                      return "dataPoints." + error;
                  }
                }
                if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality"))
                  switch (message.aggregationTemporality) {
                    default:
                      return "aggregationTemporality: enum value expected";
                    case 0:
                    case 1:
                    case 2:
                      break;
                  }
                return null;
              }, "verify");
              Histogram.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.Histogram)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.Histogram();
                if (object.dataPoints) {
                  if (!Array.isArray(object.dataPoints))
                    throw TypeError(".opentelemetry.proto.metrics.v1.Histogram.dataPoints: array expected");
                  message.dataPoints = [];
                  for (var i = 0; i < object.dataPoints.length; ++i) {
                    if (typeof object.dataPoints[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Histogram.dataPoints: object expected");
                    message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.fromObject(object.dataPoints[i]);
                  }
                }
                switch (object.aggregationTemporality) {
                  default:
                    if (typeof object.aggregationTemporality === "number") {
                      message.aggregationTemporality = object.aggregationTemporality;
                      break;
                    }
                    break;
                  case "AGGREGATION_TEMPORALITY_UNSPECIFIED":
                  case 0:
                    message.aggregationTemporality = 0;
                    break;
                  case "AGGREGATION_TEMPORALITY_DELTA":
                  case 1:
                    message.aggregationTemporality = 1;
                    break;
                  case "AGGREGATION_TEMPORALITY_CUMULATIVE":
                  case 2:
                    message.aggregationTemporality = 2;
                    break;
                }
                return message;
              }, "fromObject");
              Histogram.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.dataPoints = [];
                if (options2.defaults)
                  object.aggregationTemporality = options2.enums === String ? "AGGREGATION_TEMPORALITY_UNSPECIFIED" : 0;
                if (message.dataPoints && message.dataPoints.length) {
                  object.dataPoints = [];
                  for (var j = 0; j < message.dataPoints.length; ++j)
                    object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.toObject(message.dataPoints[j], options2);
                }
                if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality"))
                  object.aggregationTemporality = options2.enums === String ? $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] === void 0 ? message.aggregationTemporality : $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] : message.aggregationTemporality;
                return object;
              }, "toObject");
              Histogram.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              Histogram.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Histogram";
              }, "getTypeUrl");
              return Histogram;
            }();
            v12.ExponentialHistogram = function() {
              function ExponentialHistogram(properties) {
                this.dataPoints = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(ExponentialHistogram, "ExponentialHistogram");
              ExponentialHistogram.prototype.dataPoints = $util.emptyArray;
              ExponentialHistogram.prototype.aggregationTemporality = null;
              ExponentialHistogram.create = /* @__PURE__ */ __name(function create3(properties) {
                return new ExponentialHistogram(properties);
              }, "create");
              ExponentialHistogram.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.dataPoints != null && message.dataPoints.length)
                  for (var i = 0; i < message.dataPoints.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.encode(message.dataPoints[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                if (message.aggregationTemporality != null && Object.hasOwnProperty.call(message, "aggregationTemporality"))
                  writer.uint32(
                    /* id 2, wireType 0 =*/
                    16
                  ).int32(message.aggregationTemporality);
                return writer;
              }, "encode");
              ExponentialHistogram.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              ExponentialHistogram.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogram();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      if (!(message.dataPoints && message.dataPoints.length))
                        message.dataPoints = [];
                      message.dataPoints.push($root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.decode(reader, reader.uint32()));
                      break;
                    }
                    case 2: {
                      message.aggregationTemporality = reader.int32();
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              ExponentialHistogram.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              ExponentialHistogram.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) {
                  if (!Array.isArray(message.dataPoints))
                    return "dataPoints: array expected";
                  for (var i = 0; i < message.dataPoints.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.verify(message.dataPoints[i]);
                    if (error)
                      return "dataPoints." + error;
                  }
                }
                if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality"))
                  switch (message.aggregationTemporality) {
                    default:
                      return "aggregationTemporality: enum value expected";
                    case 0:
                    case 1:
                    case 2:
                      break;
                  }
                return null;
              }, "verify");
              ExponentialHistogram.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.ExponentialHistogram)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogram();
                if (object.dataPoints) {
                  if (!Array.isArray(object.dataPoints))
                    throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogram.dataPoints: array expected");
                  message.dataPoints = [];
                  for (var i = 0; i < object.dataPoints.length; ++i) {
                    if (typeof object.dataPoints[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogram.dataPoints: object expected");
                    message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.fromObject(object.dataPoints[i]);
                  }
                }
                switch (object.aggregationTemporality) {
                  default:
                    if (typeof object.aggregationTemporality === "number") {
                      message.aggregationTemporality = object.aggregationTemporality;
                      break;
                    }
                    break;
                  case "AGGREGATION_TEMPORALITY_UNSPECIFIED":
                  case 0:
                    message.aggregationTemporality = 0;
                    break;
                  case "AGGREGATION_TEMPORALITY_DELTA":
                  case 1:
                    message.aggregationTemporality = 1;
                    break;
                  case "AGGREGATION_TEMPORALITY_CUMULATIVE":
                  case 2:
                    message.aggregationTemporality = 2;
                    break;
                }
                return message;
              }, "fromObject");
              ExponentialHistogram.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.dataPoints = [];
                if (options2.defaults)
                  object.aggregationTemporality = options2.enums === String ? "AGGREGATION_TEMPORALITY_UNSPECIFIED" : 0;
                if (message.dataPoints && message.dataPoints.length) {
                  object.dataPoints = [];
                  for (var j = 0; j < message.dataPoints.length; ++j)
                    object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.toObject(message.dataPoints[j], options2);
                }
                if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality"))
                  object.aggregationTemporality = options2.enums === String ? $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] === void 0 ? message.aggregationTemporality : $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] : message.aggregationTemporality;
                return object;
              }, "toObject");
              ExponentialHistogram.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              ExponentialHistogram.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ExponentialHistogram";
              }, "getTypeUrl");
              return ExponentialHistogram;
            }();
            v12.Summary = function() {
              function Summary(properties) {
                this.dataPoints = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(Summary, "Summary");
              Summary.prototype.dataPoints = $util.emptyArray;
              Summary.create = /* @__PURE__ */ __name(function create3(properties) {
                return new Summary(properties);
              }, "create");
              Summary.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.dataPoints != null && message.dataPoints.length)
                  for (var i = 0; i < message.dataPoints.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.encode(message.dataPoints[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              Summary.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              Summary.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Summary();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      if (!(message.dataPoints && message.dataPoints.length))
                        message.dataPoints = [];
                      message.dataPoints.push($root.opentelemetry.proto.metrics.v1.SummaryDataPoint.decode(reader, reader.uint32()));
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              Summary.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              Summary.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) {
                  if (!Array.isArray(message.dataPoints))
                    return "dataPoints: array expected";
                  for (var i = 0; i < message.dataPoints.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.verify(message.dataPoints[i]);
                    if (error)
                      return "dataPoints." + error;
                  }
                }
                return null;
              }, "verify");
              Summary.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.Summary)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.Summary();
                if (object.dataPoints) {
                  if (!Array.isArray(object.dataPoints))
                    throw TypeError(".opentelemetry.proto.metrics.v1.Summary.dataPoints: array expected");
                  message.dataPoints = [];
                  for (var i = 0; i < object.dataPoints.length; ++i) {
                    if (typeof object.dataPoints[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Summary.dataPoints: object expected");
                    message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.fromObject(object.dataPoints[i]);
                  }
                }
                return message;
              }, "fromObject");
              Summary.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.dataPoints = [];
                if (message.dataPoints && message.dataPoints.length) {
                  object.dataPoints = [];
                  for (var j = 0; j < message.dataPoints.length; ++j)
                    object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.toObject(message.dataPoints[j], options2);
                }
                return object;
              }, "toObject");
              Summary.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              Summary.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Summary";
              }, "getTypeUrl");
              return Summary;
            }();
            v12.AggregationTemporality = function() {
              var valuesById = {}, values = Object.create(valuesById);
              values[valuesById[0] = "AGGREGATION_TEMPORALITY_UNSPECIFIED"] = 0;
              values[valuesById[1] = "AGGREGATION_TEMPORALITY_DELTA"] = 1;
              values[valuesById[2] = "AGGREGATION_TEMPORALITY_CUMULATIVE"] = 2;
              return values;
            }();
            v12.DataPointFlags = function() {
              var valuesById = {}, values = Object.create(valuesById);
              values[valuesById[0] = "DATA_POINT_FLAGS_DO_NOT_USE"] = 0;
              values[valuesById[1] = "DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK"] = 1;
              return values;
            }();
            v12.NumberDataPoint = function() {
              function NumberDataPoint(properties) {
                this.attributes = [];
                this.exemplars = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(NumberDataPoint, "NumberDataPoint");
              NumberDataPoint.prototype.attributes = $util.emptyArray;
              NumberDataPoint.prototype.startTimeUnixNano = null;
              NumberDataPoint.prototype.timeUnixNano = null;
              NumberDataPoint.prototype.asDouble = null;
              NumberDataPoint.prototype.asInt = null;
              NumberDataPoint.prototype.exemplars = $util.emptyArray;
              NumberDataPoint.prototype.flags = null;
              var $oneOfFields;
              Object.defineProperty(NumberDataPoint.prototype, "value", {
                get: $util.oneOfGetter($oneOfFields = ["asDouble", "asInt"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              NumberDataPoint.create = /* @__PURE__ */ __name(function create3(properties) {
                return new NumberDataPoint(properties);
              }, "create");
              NumberDataPoint.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano"))
                  writer.uint32(
                    /* id 2, wireType 1 =*/
                    17
                  ).fixed64(message.startTimeUnixNano);
                if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano"))
                  writer.uint32(
                    /* id 3, wireType 1 =*/
                    25
                  ).fixed64(message.timeUnixNano);
                if (message.asDouble != null && Object.hasOwnProperty.call(message, "asDouble"))
                  writer.uint32(
                    /* id 4, wireType 1 =*/
                    33
                  ).double(message.asDouble);
                if (message.exemplars != null && message.exemplars.length)
                  for (var i = 0; i < message.exemplars.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.Exemplar.encode(message.exemplars[i], writer.uint32(
                      /* id 5, wireType 2 =*/
                      42
                    ).fork()).ldelim();
                if (message.asInt != null && Object.hasOwnProperty.call(message, "asInt"))
                  writer.uint32(
                    /* id 6, wireType 1 =*/
                    49
                  ).sfixed64(message.asInt);
                if (message.attributes != null && message.attributes.length)
                  for (var i = 0; i < message.attributes.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                      /* id 7, wireType 2 =*/
                      58
                    ).fork()).ldelim();
                if (message.flags != null && Object.hasOwnProperty.call(message, "flags"))
                  writer.uint32(
                    /* id 8, wireType 0 =*/
                    64
                  ).uint32(message.flags);
                return writer;
              }, "encode");
              NumberDataPoint.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              NumberDataPoint.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.NumberDataPoint();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 7: {
                      if (!(message.attributes && message.attributes.length))
                        message.attributes = [];
                      message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    case 2: {
                      message.startTimeUnixNano = reader.fixed64();
                      break;
                    }
                    case 3: {
                      message.timeUnixNano = reader.fixed64();
                      break;
                    }
                    case 4: {
                      message.asDouble = reader.double();
                      break;
                    }
                    case 6: {
                      message.asInt = reader.sfixed64();
                      break;
                    }
                    case 5: {
                      if (!(message.exemplars && message.exemplars.length))
                        message.exemplars = [];
                      message.exemplars.push($root.opentelemetry.proto.metrics.v1.Exemplar.decode(reader, reader.uint32()));
                      break;
                    }
                    case 8: {
                      message.flags = reader.uint32();
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              NumberDataPoint.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              NumberDataPoint.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                var properties = {};
                if (message.attributes != null && message.hasOwnProperty("attributes")) {
                  if (!Array.isArray(message.attributes))
                    return "attributes: array expected";
                  for (var i = 0; i < message.attributes.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                    if (error)
                      return "attributes." + error;
                  }
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) {
                  if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high)))
                    return "startTimeUnixNano: integer|Long expected";
                }
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) {
                  if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high)))
                    return "timeUnixNano: integer|Long expected";
                }
                if (message.asDouble != null && message.hasOwnProperty("asDouble")) {
                  properties.value = 1;
                  if (typeof message.asDouble !== "number")
                    return "asDouble: number expected";
                }
                if (message.asInt != null && message.hasOwnProperty("asInt")) {
                  if (properties.value === 1)
                    return "value: multiple values";
                  properties.value = 1;
                  if (!$util.isInteger(message.asInt) && !(message.asInt && $util.isInteger(message.asInt.low) && $util.isInteger(message.asInt.high)))
                    return "asInt: integer|Long expected";
                }
                if (message.exemplars != null && message.hasOwnProperty("exemplars")) {
                  if (!Array.isArray(message.exemplars))
                    return "exemplars: array expected";
                  for (var i = 0; i < message.exemplars.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.Exemplar.verify(message.exemplars[i]);
                    if (error)
                      return "exemplars." + error;
                  }
                }
                if (message.flags != null && message.hasOwnProperty("flags")) {
                  if (!$util.isInteger(message.flags))
                    return "flags: integer expected";
                }
                return null;
              }, "verify");
              NumberDataPoint.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.NumberDataPoint)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.NumberDataPoint();
                if (object.attributes) {
                  if (!Array.isArray(object.attributes))
                    throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.attributes: array expected");
                  message.attributes = [];
                  for (var i = 0; i < object.attributes.length; ++i) {
                    if (typeof object.attributes[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.attributes: object expected");
                    message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                  }
                }
                if (object.startTimeUnixNano != null) {
                  if ($util.Long)
                    (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false;
                  else if (typeof object.startTimeUnixNano === "string")
                    message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10);
                  else if (typeof object.startTimeUnixNano === "number")
                    message.startTimeUnixNano = object.startTimeUnixNano;
                  else if (typeof object.startTimeUnixNano === "object")
                    message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber();
                }
                if (object.timeUnixNano != null) {
                  if ($util.Long)
                    (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false;
                  else if (typeof object.timeUnixNano === "string")
                    message.timeUnixNano = parseInt(object.timeUnixNano, 10);
                  else if (typeof object.timeUnixNano === "number")
                    message.timeUnixNano = object.timeUnixNano;
                  else if (typeof object.timeUnixNano === "object")
                    message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber();
                }
                if (object.asDouble != null)
                  message.asDouble = Number(object.asDouble);
                if (object.asInt != null) {
                  if ($util.Long)
                    (message.asInt = $util.Long.fromValue(object.asInt)).unsigned = false;
                  else if (typeof object.asInt === "string")
                    message.asInt = parseInt(object.asInt, 10);
                  else if (typeof object.asInt === "number")
                    message.asInt = object.asInt;
                  else if (typeof object.asInt === "object")
                    message.asInt = new $util.LongBits(object.asInt.low >>> 0, object.asInt.high >>> 0).toNumber();
                }
                if (object.exemplars) {
                  if (!Array.isArray(object.exemplars))
                    throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.exemplars: array expected");
                  message.exemplars = [];
                  for (var i = 0; i < object.exemplars.length; ++i) {
                    if (typeof object.exemplars[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.exemplars: object expected");
                    message.exemplars[i] = $root.opentelemetry.proto.metrics.v1.Exemplar.fromObject(object.exemplars[i]);
                  }
                }
                if (object.flags != null)
                  message.flags = object.flags >>> 0;
                return message;
              }, "fromObject");
              NumberDataPoint.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults) {
                  object.exemplars = [];
                  object.attributes = [];
                }
                if (options2.defaults) {
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.startTimeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object.startTimeUnixNano = options2.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.timeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object.timeUnixNano = options2.longs === String ? "0" : 0;
                  object.flags = 0;
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano"))
                  if (typeof message.startTimeUnixNano === "number")
                    object.startTimeUnixNano = options2.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano;
                  else
                    object.startTimeUnixNano = options2.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options2.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano;
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano"))
                  if (typeof message.timeUnixNano === "number")
                    object.timeUnixNano = options2.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                  else
                    object.timeUnixNano = options2.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options2.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano;
                if (message.asDouble != null && message.hasOwnProperty("asDouble")) {
                  object.asDouble = options2.json && !isFinite(message.asDouble) ? String(message.asDouble) : message.asDouble;
                  if (options2.oneofs)
                    object.value = "asDouble";
                }
                if (message.exemplars && message.exemplars.length) {
                  object.exemplars = [];
                  for (var j = 0; j < message.exemplars.length; ++j)
                    object.exemplars[j] = $root.opentelemetry.proto.metrics.v1.Exemplar.toObject(message.exemplars[j], options2);
                }
                if (message.asInt != null && message.hasOwnProperty("asInt")) {
                  if (typeof message.asInt === "number")
                    object.asInt = options2.longs === String ? String(message.asInt) : message.asInt;
                  else
                    object.asInt = options2.longs === String ? $util.Long.prototype.toString.call(message.asInt) : options2.longs === Number ? new $util.LongBits(message.asInt.low >>> 0, message.asInt.high >>> 0).toNumber() : message.asInt;
                  if (options2.oneofs)
                    object.value = "asInt";
                }
                if (message.attributes && message.attributes.length) {
                  object.attributes = [];
                  for (var j = 0; j < message.attributes.length; ++j)
                    object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options2);
                }
                if (message.flags != null && message.hasOwnProperty("flags"))
                  object.flags = message.flags;
                return object;
              }, "toObject");
              NumberDataPoint.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              NumberDataPoint.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.NumberDataPoint";
              }, "getTypeUrl");
              return NumberDataPoint;
            }();
            v12.HistogramDataPoint = function() {
              function HistogramDataPoint(properties) {
                this.attributes = [];
                this.bucketCounts = [];
                this.explicitBounds = [];
                this.exemplars = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(HistogramDataPoint, "HistogramDataPoint");
              HistogramDataPoint.prototype.attributes = $util.emptyArray;
              HistogramDataPoint.prototype.startTimeUnixNano = null;
              HistogramDataPoint.prototype.timeUnixNano = null;
              HistogramDataPoint.prototype.count = null;
              HistogramDataPoint.prototype.sum = null;
              HistogramDataPoint.prototype.bucketCounts = $util.emptyArray;
              HistogramDataPoint.prototype.explicitBounds = $util.emptyArray;
              HistogramDataPoint.prototype.exemplars = $util.emptyArray;
              HistogramDataPoint.prototype.flags = null;
              HistogramDataPoint.prototype.min = null;
              HistogramDataPoint.prototype.max = null;
              var $oneOfFields;
              Object.defineProperty(HistogramDataPoint.prototype, "_sum", {
                get: $util.oneOfGetter($oneOfFields = ["sum"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              Object.defineProperty(HistogramDataPoint.prototype, "_min", {
                get: $util.oneOfGetter($oneOfFields = ["min"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              Object.defineProperty(HistogramDataPoint.prototype, "_max", {
                get: $util.oneOfGetter($oneOfFields = ["max"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              HistogramDataPoint.create = /* @__PURE__ */ __name(function create3(properties) {
                return new HistogramDataPoint(properties);
              }, "create");
              HistogramDataPoint.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano"))
                  writer.uint32(
                    /* id 2, wireType 1 =*/
                    17
                  ).fixed64(message.startTimeUnixNano);
                if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano"))
                  writer.uint32(
                    /* id 3, wireType 1 =*/
                    25
                  ).fixed64(message.timeUnixNano);
                if (message.count != null && Object.hasOwnProperty.call(message, "count"))
                  writer.uint32(
                    /* id 4, wireType 1 =*/
                    33
                  ).fixed64(message.count);
                if (message.sum != null && Object.hasOwnProperty.call(message, "sum"))
                  writer.uint32(
                    /* id 5, wireType 1 =*/
                    41
                  ).double(message.sum);
                if (message.bucketCounts != null && message.bucketCounts.length) {
                  writer.uint32(
                    /* id 6, wireType 2 =*/
                    50
                  ).fork();
                  for (var i = 0; i < message.bucketCounts.length; ++i)
                    writer.fixed64(message.bucketCounts[i]);
                  writer.ldelim();
                }
                if (message.explicitBounds != null && message.explicitBounds.length) {
                  writer.uint32(
                    /* id 7, wireType 2 =*/
                    58
                  ).fork();
                  for (var i = 0; i < message.explicitBounds.length; ++i)
                    writer.double(message.explicitBounds[i]);
                  writer.ldelim();
                }
                if (message.exemplars != null && message.exemplars.length)
                  for (var i = 0; i < message.exemplars.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.Exemplar.encode(message.exemplars[i], writer.uint32(
                      /* id 8, wireType 2 =*/
                      66
                    ).fork()).ldelim();
                if (message.attributes != null && message.attributes.length)
                  for (var i = 0; i < message.attributes.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                      /* id 9, wireType 2 =*/
                      74
                    ).fork()).ldelim();
                if (message.flags != null && Object.hasOwnProperty.call(message, "flags"))
                  writer.uint32(
                    /* id 10, wireType 0 =*/
                    80
                  ).uint32(message.flags);
                if (message.min != null && Object.hasOwnProperty.call(message, "min"))
                  writer.uint32(
                    /* id 11, wireType 1 =*/
                    89
                  ).double(message.min);
                if (message.max != null && Object.hasOwnProperty.call(message, "max"))
                  writer.uint32(
                    /* id 12, wireType 1 =*/
                    97
                  ).double(message.max);
                return writer;
              }, "encode");
              HistogramDataPoint.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              HistogramDataPoint.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.HistogramDataPoint();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 9: {
                      if (!(message.attributes && message.attributes.length))
                        message.attributes = [];
                      message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    case 2: {
                      message.startTimeUnixNano = reader.fixed64();
                      break;
                    }
                    case 3: {
                      message.timeUnixNano = reader.fixed64();
                      break;
                    }
                    case 4: {
                      message.count = reader.fixed64();
                      break;
                    }
                    case 5: {
                      message.sum = reader.double();
                      break;
                    }
                    case 6: {
                      if (!(message.bucketCounts && message.bucketCounts.length))
                        message.bucketCounts = [];
                      if ((tag2 & 7) === 2) {
                        var end2 = reader.uint32() + reader.pos;
                        while (reader.pos < end2)
                          message.bucketCounts.push(reader.fixed64());
                      } else
                        message.bucketCounts.push(reader.fixed64());
                      break;
                    }
                    case 7: {
                      if (!(message.explicitBounds && message.explicitBounds.length))
                        message.explicitBounds = [];
                      if ((tag2 & 7) === 2) {
                        var end2 = reader.uint32() + reader.pos;
                        while (reader.pos < end2)
                          message.explicitBounds.push(reader.double());
                      } else
                        message.explicitBounds.push(reader.double());
                      break;
                    }
                    case 8: {
                      if (!(message.exemplars && message.exemplars.length))
                        message.exemplars = [];
                      message.exemplars.push($root.opentelemetry.proto.metrics.v1.Exemplar.decode(reader, reader.uint32()));
                      break;
                    }
                    case 10: {
                      message.flags = reader.uint32();
                      break;
                    }
                    case 11: {
                      message.min = reader.double();
                      break;
                    }
                    case 12: {
                      message.max = reader.double();
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              HistogramDataPoint.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              HistogramDataPoint.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                var properties = {};
                if (message.attributes != null && message.hasOwnProperty("attributes")) {
                  if (!Array.isArray(message.attributes))
                    return "attributes: array expected";
                  for (var i = 0; i < message.attributes.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                    if (error)
                      return "attributes." + error;
                  }
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) {
                  if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high)))
                    return "startTimeUnixNano: integer|Long expected";
                }
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) {
                  if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high)))
                    return "timeUnixNano: integer|Long expected";
                }
                if (message.count != null && message.hasOwnProperty("count")) {
                  if (!$util.isInteger(message.count) && !(message.count && $util.isInteger(message.count.low) && $util.isInteger(message.count.high)))
                    return "count: integer|Long expected";
                }
                if (message.sum != null && message.hasOwnProperty("sum")) {
                  properties._sum = 1;
                  if (typeof message.sum !== "number")
                    return "sum: number expected";
                }
                if (message.bucketCounts != null && message.hasOwnProperty("bucketCounts")) {
                  if (!Array.isArray(message.bucketCounts))
                    return "bucketCounts: array expected";
                  for (var i = 0; i < message.bucketCounts.length; ++i)
                    if (!$util.isInteger(message.bucketCounts[i]) && !(message.bucketCounts[i] && $util.isInteger(message.bucketCounts[i].low) && $util.isInteger(message.bucketCounts[i].high)))
                      return "bucketCounts: integer|Long[] expected";
                }
                if (message.explicitBounds != null && message.hasOwnProperty("explicitBounds")) {
                  if (!Array.isArray(message.explicitBounds))
                    return "explicitBounds: array expected";
                  for (var i = 0; i < message.explicitBounds.length; ++i)
                    if (typeof message.explicitBounds[i] !== "number")
                      return "explicitBounds: number[] expected";
                }
                if (message.exemplars != null && message.hasOwnProperty("exemplars")) {
                  if (!Array.isArray(message.exemplars))
                    return "exemplars: array expected";
                  for (var i = 0; i < message.exemplars.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.Exemplar.verify(message.exemplars[i]);
                    if (error)
                      return "exemplars." + error;
                  }
                }
                if (message.flags != null && message.hasOwnProperty("flags")) {
                  if (!$util.isInteger(message.flags))
                    return "flags: integer expected";
                }
                if (message.min != null && message.hasOwnProperty("min")) {
                  properties._min = 1;
                  if (typeof message.min !== "number")
                    return "min: number expected";
                }
                if (message.max != null && message.hasOwnProperty("max")) {
                  properties._max = 1;
                  if (typeof message.max !== "number")
                    return "max: number expected";
                }
                return null;
              }, "verify");
              HistogramDataPoint.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.HistogramDataPoint)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.HistogramDataPoint();
                if (object.attributes) {
                  if (!Array.isArray(object.attributes))
                    throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.attributes: array expected");
                  message.attributes = [];
                  for (var i = 0; i < object.attributes.length; ++i) {
                    if (typeof object.attributes[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.attributes: object expected");
                    message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                  }
                }
                if (object.startTimeUnixNano != null) {
                  if ($util.Long)
                    (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false;
                  else if (typeof object.startTimeUnixNano === "string")
                    message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10);
                  else if (typeof object.startTimeUnixNano === "number")
                    message.startTimeUnixNano = object.startTimeUnixNano;
                  else if (typeof object.startTimeUnixNano === "object")
                    message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber();
                }
                if (object.timeUnixNano != null) {
                  if ($util.Long)
                    (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false;
                  else if (typeof object.timeUnixNano === "string")
                    message.timeUnixNano = parseInt(object.timeUnixNano, 10);
                  else if (typeof object.timeUnixNano === "number")
                    message.timeUnixNano = object.timeUnixNano;
                  else if (typeof object.timeUnixNano === "object")
                    message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber();
                }
                if (object.count != null) {
                  if ($util.Long)
                    (message.count = $util.Long.fromValue(object.count)).unsigned = false;
                  else if (typeof object.count === "string")
                    message.count = parseInt(object.count, 10);
                  else if (typeof object.count === "number")
                    message.count = object.count;
                  else if (typeof object.count === "object")
                    message.count = new $util.LongBits(object.count.low >>> 0, object.count.high >>> 0).toNumber();
                }
                if (object.sum != null)
                  message.sum = Number(object.sum);
                if (object.bucketCounts) {
                  if (!Array.isArray(object.bucketCounts))
                    throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.bucketCounts: array expected");
                  message.bucketCounts = [];
                  for (var i = 0; i < object.bucketCounts.length; ++i)
                    if ($util.Long)
                      (message.bucketCounts[i] = $util.Long.fromValue(object.bucketCounts[i])).unsigned = false;
                    else if (typeof object.bucketCounts[i] === "string")
                      message.bucketCounts[i] = parseInt(object.bucketCounts[i], 10);
                    else if (typeof object.bucketCounts[i] === "number")
                      message.bucketCounts[i] = object.bucketCounts[i];
                    else if (typeof object.bucketCounts[i] === "object")
                      message.bucketCounts[i] = new $util.LongBits(object.bucketCounts[i].low >>> 0, object.bucketCounts[i].high >>> 0).toNumber();
                }
                if (object.explicitBounds) {
                  if (!Array.isArray(object.explicitBounds))
                    throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.explicitBounds: array expected");
                  message.explicitBounds = [];
                  for (var i = 0; i < object.explicitBounds.length; ++i)
                    message.explicitBounds[i] = Number(object.explicitBounds[i]);
                }
                if (object.exemplars) {
                  if (!Array.isArray(object.exemplars))
                    throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.exemplars: array expected");
                  message.exemplars = [];
                  for (var i = 0; i < object.exemplars.length; ++i) {
                    if (typeof object.exemplars[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.exemplars: object expected");
                    message.exemplars[i] = $root.opentelemetry.proto.metrics.v1.Exemplar.fromObject(object.exemplars[i]);
                  }
                }
                if (object.flags != null)
                  message.flags = object.flags >>> 0;
                if (object.min != null)
                  message.min = Number(object.min);
                if (object.max != null)
                  message.max = Number(object.max);
                return message;
              }, "fromObject");
              HistogramDataPoint.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults) {
                  object.bucketCounts = [];
                  object.explicitBounds = [];
                  object.exemplars = [];
                  object.attributes = [];
                }
                if (options2.defaults) {
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.startTimeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object.startTimeUnixNano = options2.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.timeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object.timeUnixNano = options2.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.count = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object.count = options2.longs === String ? "0" : 0;
                  object.flags = 0;
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano"))
                  if (typeof message.startTimeUnixNano === "number")
                    object.startTimeUnixNano = options2.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano;
                  else
                    object.startTimeUnixNano = options2.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options2.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano;
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano"))
                  if (typeof message.timeUnixNano === "number")
                    object.timeUnixNano = options2.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                  else
                    object.timeUnixNano = options2.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options2.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano;
                if (message.count != null && message.hasOwnProperty("count"))
                  if (typeof message.count === "number")
                    object.count = options2.longs === String ? String(message.count) : message.count;
                  else
                    object.count = options2.longs === String ? $util.Long.prototype.toString.call(message.count) : options2.longs === Number ? new $util.LongBits(message.count.low >>> 0, message.count.high >>> 0).toNumber() : message.count;
                if (message.sum != null && message.hasOwnProperty("sum")) {
                  object.sum = options2.json && !isFinite(message.sum) ? String(message.sum) : message.sum;
                  if (options2.oneofs)
                    object._sum = "sum";
                }
                if (message.bucketCounts && message.bucketCounts.length) {
                  object.bucketCounts = [];
                  for (var j = 0; j < message.bucketCounts.length; ++j)
                    if (typeof message.bucketCounts[j] === "number")
                      object.bucketCounts[j] = options2.longs === String ? String(message.bucketCounts[j]) : message.bucketCounts[j];
                    else
                      object.bucketCounts[j] = options2.longs === String ? $util.Long.prototype.toString.call(message.bucketCounts[j]) : options2.longs === Number ? new $util.LongBits(message.bucketCounts[j].low >>> 0, message.bucketCounts[j].high >>> 0).toNumber() : message.bucketCounts[j];
                }
                if (message.explicitBounds && message.explicitBounds.length) {
                  object.explicitBounds = [];
                  for (var j = 0; j < message.explicitBounds.length; ++j)
                    object.explicitBounds[j] = options2.json && !isFinite(message.explicitBounds[j]) ? String(message.explicitBounds[j]) : message.explicitBounds[j];
                }
                if (message.exemplars && message.exemplars.length) {
                  object.exemplars = [];
                  for (var j = 0; j < message.exemplars.length; ++j)
                    object.exemplars[j] = $root.opentelemetry.proto.metrics.v1.Exemplar.toObject(message.exemplars[j], options2);
                }
                if (message.attributes && message.attributes.length) {
                  object.attributes = [];
                  for (var j = 0; j < message.attributes.length; ++j)
                    object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options2);
                }
                if (message.flags != null && message.hasOwnProperty("flags"))
                  object.flags = message.flags;
                if (message.min != null && message.hasOwnProperty("min")) {
                  object.min = options2.json && !isFinite(message.min) ? String(message.min) : message.min;
                  if (options2.oneofs)
                    object._min = "min";
                }
                if (message.max != null && message.hasOwnProperty("max")) {
                  object.max = options2.json && !isFinite(message.max) ? String(message.max) : message.max;
                  if (options2.oneofs)
                    object._max = "max";
                }
                return object;
              }, "toObject");
              HistogramDataPoint.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              HistogramDataPoint.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.HistogramDataPoint";
              }, "getTypeUrl");
              return HistogramDataPoint;
            }();
            v12.ExponentialHistogramDataPoint = function() {
              function ExponentialHistogramDataPoint(properties) {
                this.attributes = [];
                this.exemplars = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(ExponentialHistogramDataPoint, "ExponentialHistogramDataPoint");
              ExponentialHistogramDataPoint.prototype.attributes = $util.emptyArray;
              ExponentialHistogramDataPoint.prototype.startTimeUnixNano = null;
              ExponentialHistogramDataPoint.prototype.timeUnixNano = null;
              ExponentialHistogramDataPoint.prototype.count = null;
              ExponentialHistogramDataPoint.prototype.sum = null;
              ExponentialHistogramDataPoint.prototype.scale = null;
              ExponentialHistogramDataPoint.prototype.zeroCount = null;
              ExponentialHistogramDataPoint.prototype.positive = null;
              ExponentialHistogramDataPoint.prototype.negative = null;
              ExponentialHistogramDataPoint.prototype.flags = null;
              ExponentialHistogramDataPoint.prototype.exemplars = $util.emptyArray;
              ExponentialHistogramDataPoint.prototype.min = null;
              ExponentialHistogramDataPoint.prototype.max = null;
              ExponentialHistogramDataPoint.prototype.zeroThreshold = null;
              var $oneOfFields;
              Object.defineProperty(ExponentialHistogramDataPoint.prototype, "_sum", {
                get: $util.oneOfGetter($oneOfFields = ["sum"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              Object.defineProperty(ExponentialHistogramDataPoint.prototype, "_min", {
                get: $util.oneOfGetter($oneOfFields = ["min"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              Object.defineProperty(ExponentialHistogramDataPoint.prototype, "_max", {
                get: $util.oneOfGetter($oneOfFields = ["max"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              ExponentialHistogramDataPoint.create = /* @__PURE__ */ __name(function create3(properties) {
                return new ExponentialHistogramDataPoint(properties);
              }, "create");
              ExponentialHistogramDataPoint.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.attributes != null && message.attributes.length)
                  for (var i = 0; i < message.attributes.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano"))
                  writer.uint32(
                    /* id 2, wireType 1 =*/
                    17
                  ).fixed64(message.startTimeUnixNano);
                if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano"))
                  writer.uint32(
                    /* id 3, wireType 1 =*/
                    25
                  ).fixed64(message.timeUnixNano);
                if (message.count != null && Object.hasOwnProperty.call(message, "count"))
                  writer.uint32(
                    /* id 4, wireType 1 =*/
                    33
                  ).fixed64(message.count);
                if (message.sum != null && Object.hasOwnProperty.call(message, "sum"))
                  writer.uint32(
                    /* id 5, wireType 1 =*/
                    41
                  ).double(message.sum);
                if (message.scale != null && Object.hasOwnProperty.call(message, "scale"))
                  writer.uint32(
                    /* id 6, wireType 0 =*/
                    48
                  ).sint32(message.scale);
                if (message.zeroCount != null && Object.hasOwnProperty.call(message, "zeroCount"))
                  writer.uint32(
                    /* id 7, wireType 1 =*/
                    57
                  ).fixed64(message.zeroCount);
                if (message.positive != null && Object.hasOwnProperty.call(message, "positive"))
                  $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.encode(message.positive, writer.uint32(
                    /* id 8, wireType 2 =*/
                    66
                  ).fork()).ldelim();
                if (message.negative != null && Object.hasOwnProperty.call(message, "negative"))
                  $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.encode(message.negative, writer.uint32(
                    /* id 9, wireType 2 =*/
                    74
                  ).fork()).ldelim();
                if (message.flags != null && Object.hasOwnProperty.call(message, "flags"))
                  writer.uint32(
                    /* id 10, wireType 0 =*/
                    80
                  ).uint32(message.flags);
                if (message.exemplars != null && message.exemplars.length)
                  for (var i = 0; i < message.exemplars.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.Exemplar.encode(message.exemplars[i], writer.uint32(
                      /* id 11, wireType 2 =*/
                      90
                    ).fork()).ldelim();
                if (message.min != null && Object.hasOwnProperty.call(message, "min"))
                  writer.uint32(
                    /* id 12, wireType 1 =*/
                    97
                  ).double(message.min);
                if (message.max != null && Object.hasOwnProperty.call(message, "max"))
                  writer.uint32(
                    /* id 13, wireType 1 =*/
                    105
                  ).double(message.max);
                if (message.zeroThreshold != null && Object.hasOwnProperty.call(message, "zeroThreshold"))
                  writer.uint32(
                    /* id 14, wireType 1 =*/
                    113
                  ).double(message.zeroThreshold);
                return writer;
              }, "encode");
              ExponentialHistogramDataPoint.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              ExponentialHistogramDataPoint.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      if (!(message.attributes && message.attributes.length))
                        message.attributes = [];
                      message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    case 2: {
                      message.startTimeUnixNano = reader.fixed64();
                      break;
                    }
                    case 3: {
                      message.timeUnixNano = reader.fixed64();
                      break;
                    }
                    case 4: {
                      message.count = reader.fixed64();
                      break;
                    }
                    case 5: {
                      message.sum = reader.double();
                      break;
                    }
                    case 6: {
                      message.scale = reader.sint32();
                      break;
                    }
                    case 7: {
                      message.zeroCount = reader.fixed64();
                      break;
                    }
                    case 8: {
                      message.positive = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.decode(reader, reader.uint32());
                      break;
                    }
                    case 9: {
                      message.negative = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.decode(reader, reader.uint32());
                      break;
                    }
                    case 10: {
                      message.flags = reader.uint32();
                      break;
                    }
                    case 11: {
                      if (!(message.exemplars && message.exemplars.length))
                        message.exemplars = [];
                      message.exemplars.push($root.opentelemetry.proto.metrics.v1.Exemplar.decode(reader, reader.uint32()));
                      break;
                    }
                    case 12: {
                      message.min = reader.double();
                      break;
                    }
                    case 13: {
                      message.max = reader.double();
                      break;
                    }
                    case 14: {
                      message.zeroThreshold = reader.double();
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              ExponentialHistogramDataPoint.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              ExponentialHistogramDataPoint.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                var properties = {};
                if (message.attributes != null && message.hasOwnProperty("attributes")) {
                  if (!Array.isArray(message.attributes))
                    return "attributes: array expected";
                  for (var i = 0; i < message.attributes.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                    if (error)
                      return "attributes." + error;
                  }
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) {
                  if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high)))
                    return "startTimeUnixNano: integer|Long expected";
                }
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) {
                  if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high)))
                    return "timeUnixNano: integer|Long expected";
                }
                if (message.count != null && message.hasOwnProperty("count")) {
                  if (!$util.isInteger(message.count) && !(message.count && $util.isInteger(message.count.low) && $util.isInteger(message.count.high)))
                    return "count: integer|Long expected";
                }
                if (message.sum != null && message.hasOwnProperty("sum")) {
                  properties._sum = 1;
                  if (typeof message.sum !== "number")
                    return "sum: number expected";
                }
                if (message.scale != null && message.hasOwnProperty("scale")) {
                  if (!$util.isInteger(message.scale))
                    return "scale: integer expected";
                }
                if (message.zeroCount != null && message.hasOwnProperty("zeroCount")) {
                  if (!$util.isInteger(message.zeroCount) && !(message.zeroCount && $util.isInteger(message.zeroCount.low) && $util.isInteger(message.zeroCount.high)))
                    return "zeroCount: integer|Long expected";
                }
                if (message.positive != null && message.hasOwnProperty("positive")) {
                  var error = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify(message.positive);
                  if (error)
                    return "positive." + error;
                }
                if (message.negative != null && message.hasOwnProperty("negative")) {
                  var error = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify(message.negative);
                  if (error)
                    return "negative." + error;
                }
                if (message.flags != null && message.hasOwnProperty("flags")) {
                  if (!$util.isInteger(message.flags))
                    return "flags: integer expected";
                }
                if (message.exemplars != null && message.hasOwnProperty("exemplars")) {
                  if (!Array.isArray(message.exemplars))
                    return "exemplars: array expected";
                  for (var i = 0; i < message.exemplars.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.Exemplar.verify(message.exemplars[i]);
                    if (error)
                      return "exemplars." + error;
                  }
                }
                if (message.min != null && message.hasOwnProperty("min")) {
                  properties._min = 1;
                  if (typeof message.min !== "number")
                    return "min: number expected";
                }
                if (message.max != null && message.hasOwnProperty("max")) {
                  properties._max = 1;
                  if (typeof message.max !== "number")
                    return "max: number expected";
                }
                if (message.zeroThreshold != null && message.hasOwnProperty("zeroThreshold")) {
                  if (typeof message.zeroThreshold !== "number")
                    return "zeroThreshold: number expected";
                }
                return null;
              }, "verify");
              ExponentialHistogramDataPoint.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint();
                if (object.attributes) {
                  if (!Array.isArray(object.attributes))
                    throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.attributes: array expected");
                  message.attributes = [];
                  for (var i = 0; i < object.attributes.length; ++i) {
                    if (typeof object.attributes[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.attributes: object expected");
                    message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                  }
                }
                if (object.startTimeUnixNano != null) {
                  if ($util.Long)
                    (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false;
                  else if (typeof object.startTimeUnixNano === "string")
                    message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10);
                  else if (typeof object.startTimeUnixNano === "number")
                    message.startTimeUnixNano = object.startTimeUnixNano;
                  else if (typeof object.startTimeUnixNano === "object")
                    message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber();
                }
                if (object.timeUnixNano != null) {
                  if ($util.Long)
                    (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false;
                  else if (typeof object.timeUnixNano === "string")
                    message.timeUnixNano = parseInt(object.timeUnixNano, 10);
                  else if (typeof object.timeUnixNano === "number")
                    message.timeUnixNano = object.timeUnixNano;
                  else if (typeof object.timeUnixNano === "object")
                    message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber();
                }
                if (object.count != null) {
                  if ($util.Long)
                    (message.count = $util.Long.fromValue(object.count)).unsigned = false;
                  else if (typeof object.count === "string")
                    message.count = parseInt(object.count, 10);
                  else if (typeof object.count === "number")
                    message.count = object.count;
                  else if (typeof object.count === "object")
                    message.count = new $util.LongBits(object.count.low >>> 0, object.count.high >>> 0).toNumber();
                }
                if (object.sum != null)
                  message.sum = Number(object.sum);
                if (object.scale != null)
                  message.scale = object.scale | 0;
                if (object.zeroCount != null) {
                  if ($util.Long)
                    (message.zeroCount = $util.Long.fromValue(object.zeroCount)).unsigned = false;
                  else if (typeof object.zeroCount === "string")
                    message.zeroCount = parseInt(object.zeroCount, 10);
                  else if (typeof object.zeroCount === "number")
                    message.zeroCount = object.zeroCount;
                  else if (typeof object.zeroCount === "object")
                    message.zeroCount = new $util.LongBits(object.zeroCount.low >>> 0, object.zeroCount.high >>> 0).toNumber();
                }
                if (object.positive != null) {
                  if (typeof object.positive !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.positive: object expected");
                  message.positive = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.fromObject(object.positive);
                }
                if (object.negative != null) {
                  if (typeof object.negative !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.negative: object expected");
                  message.negative = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.fromObject(object.negative);
                }
                if (object.flags != null)
                  message.flags = object.flags >>> 0;
                if (object.exemplars) {
                  if (!Array.isArray(object.exemplars))
                    throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.exemplars: array expected");
                  message.exemplars = [];
                  for (var i = 0; i < object.exemplars.length; ++i) {
                    if (typeof object.exemplars[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.exemplars: object expected");
                    message.exemplars[i] = $root.opentelemetry.proto.metrics.v1.Exemplar.fromObject(object.exemplars[i]);
                  }
                }
                if (object.min != null)
                  message.min = Number(object.min);
                if (object.max != null)
                  message.max = Number(object.max);
                if (object.zeroThreshold != null)
                  message.zeroThreshold = Number(object.zeroThreshold);
                return message;
              }, "fromObject");
              ExponentialHistogramDataPoint.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults) {
                  object.attributes = [];
                  object.exemplars = [];
                }
                if (options2.defaults) {
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.startTimeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object.startTimeUnixNano = options2.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.timeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object.timeUnixNano = options2.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.count = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object.count = options2.longs === String ? "0" : 0;
                  object.scale = 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.zeroCount = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object.zeroCount = options2.longs === String ? "0" : 0;
                  object.positive = null;
                  object.negative = null;
                  object.flags = 0;
                  object.zeroThreshold = 0;
                }
                if (message.attributes && message.attributes.length) {
                  object.attributes = [];
                  for (var j = 0; j < message.attributes.length; ++j)
                    object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options2);
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano"))
                  if (typeof message.startTimeUnixNano === "number")
                    object.startTimeUnixNano = options2.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano;
                  else
                    object.startTimeUnixNano = options2.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options2.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano;
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano"))
                  if (typeof message.timeUnixNano === "number")
                    object.timeUnixNano = options2.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                  else
                    object.timeUnixNano = options2.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options2.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano;
                if (message.count != null && message.hasOwnProperty("count"))
                  if (typeof message.count === "number")
                    object.count = options2.longs === String ? String(message.count) : message.count;
                  else
                    object.count = options2.longs === String ? $util.Long.prototype.toString.call(message.count) : options2.longs === Number ? new $util.LongBits(message.count.low >>> 0, message.count.high >>> 0).toNumber() : message.count;
                if (message.sum != null && message.hasOwnProperty("sum")) {
                  object.sum = options2.json && !isFinite(message.sum) ? String(message.sum) : message.sum;
                  if (options2.oneofs)
                    object._sum = "sum";
                }
                if (message.scale != null && message.hasOwnProperty("scale"))
                  object.scale = message.scale;
                if (message.zeroCount != null && message.hasOwnProperty("zeroCount"))
                  if (typeof message.zeroCount === "number")
                    object.zeroCount = options2.longs === String ? String(message.zeroCount) : message.zeroCount;
                  else
                    object.zeroCount = options2.longs === String ? $util.Long.prototype.toString.call(message.zeroCount) : options2.longs === Number ? new $util.LongBits(message.zeroCount.low >>> 0, message.zeroCount.high >>> 0).toNumber() : message.zeroCount;
                if (message.positive != null && message.hasOwnProperty("positive"))
                  object.positive = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.toObject(message.positive, options2);
                if (message.negative != null && message.hasOwnProperty("negative"))
                  object.negative = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.toObject(message.negative, options2);
                if (message.flags != null && message.hasOwnProperty("flags"))
                  object.flags = message.flags;
                if (message.exemplars && message.exemplars.length) {
                  object.exemplars = [];
                  for (var j = 0; j < message.exemplars.length; ++j)
                    object.exemplars[j] = $root.opentelemetry.proto.metrics.v1.Exemplar.toObject(message.exemplars[j], options2);
                }
                if (message.min != null && message.hasOwnProperty("min")) {
                  object.min = options2.json && !isFinite(message.min) ? String(message.min) : message.min;
                  if (options2.oneofs)
                    object._min = "min";
                }
                if (message.max != null && message.hasOwnProperty("max")) {
                  object.max = options2.json && !isFinite(message.max) ? String(message.max) : message.max;
                  if (options2.oneofs)
                    object._max = "max";
                }
                if (message.zeroThreshold != null && message.hasOwnProperty("zeroThreshold"))
                  object.zeroThreshold = options2.json && !isFinite(message.zeroThreshold) ? String(message.zeroThreshold) : message.zeroThreshold;
                return object;
              }, "toObject");
              ExponentialHistogramDataPoint.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              ExponentialHistogramDataPoint.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint";
              }, "getTypeUrl");
              ExponentialHistogramDataPoint.Buckets = function() {
                function Buckets(properties) {
                  this.bucketCounts = [];
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(Buckets, "Buckets");
                Buckets.prototype.offset = null;
                Buckets.prototype.bucketCounts = $util.emptyArray;
                Buckets.create = /* @__PURE__ */ __name(function create3(properties) {
                  return new Buckets(properties);
                }, "create");
                Buckets.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.offset != null && Object.hasOwnProperty.call(message, "offset"))
                    writer.uint32(
                      /* id 1, wireType 0 =*/
                      8
                    ).sint32(message.offset);
                  if (message.bucketCounts != null && message.bucketCounts.length) {
                    writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).fork();
                    for (var i = 0; i < message.bucketCounts.length; ++i)
                      writer.uint64(message.bucketCounts[i]);
                    writer.ldelim();
                  }
                  return writer;
                }, "encode");
                Buckets.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                Buckets.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets();
                  while (reader.pos < end) {
                    var tag2 = reader.uint32();
                    if (tag2 === error)
                      break;
                    switch (tag2 >>> 3) {
                      case 1: {
                        message.offset = reader.sint32();
                        break;
                      }
                      case 2: {
                        if (!(message.bucketCounts && message.bucketCounts.length))
                          message.bucketCounts = [];
                        if ((tag2 & 7) === 2) {
                          var end2 = reader.uint32() + reader.pos;
                          while (reader.pos < end2)
                            message.bucketCounts.push(reader.uint64());
                        } else
                          message.bucketCounts.push(reader.uint64());
                        break;
                      }
                      default:
                        reader.skipType(tag2 & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                Buckets.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                Buckets.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.offset != null && message.hasOwnProperty("offset")) {
                    if (!$util.isInteger(message.offset))
                      return "offset: integer expected";
                  }
                  if (message.bucketCounts != null && message.hasOwnProperty("bucketCounts")) {
                    if (!Array.isArray(message.bucketCounts))
                      return "bucketCounts: array expected";
                    for (var i = 0; i < message.bucketCounts.length; ++i)
                      if (!$util.isInteger(message.bucketCounts[i]) && !(message.bucketCounts[i] && $util.isInteger(message.bucketCounts[i].low) && $util.isInteger(message.bucketCounts[i].high)))
                        return "bucketCounts: integer|Long[] expected";
                  }
                  return null;
                }, "verify");
                Buckets.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets)
                    return object;
                  var message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets();
                  if (object.offset != null)
                    message.offset = object.offset | 0;
                  if (object.bucketCounts) {
                    if (!Array.isArray(object.bucketCounts))
                      throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.bucketCounts: array expected");
                    message.bucketCounts = [];
                    for (var i = 0; i < object.bucketCounts.length; ++i)
                      if ($util.Long)
                        (message.bucketCounts[i] = $util.Long.fromValue(object.bucketCounts[i])).unsigned = true;
                      else if (typeof object.bucketCounts[i] === "string")
                        message.bucketCounts[i] = parseInt(object.bucketCounts[i], 10);
                      else if (typeof object.bucketCounts[i] === "number")
                        message.bucketCounts[i] = object.bucketCounts[i];
                      else if (typeof object.bucketCounts[i] === "object")
                        message.bucketCounts[i] = new $util.LongBits(object.bucketCounts[i].low >>> 0, object.bucketCounts[i].high >>> 0).toNumber(true);
                  }
                  return message;
                }, "fromObject");
                Buckets.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object = {};
                  if (options2.arrays || options2.defaults)
                    object.bucketCounts = [];
                  if (options2.defaults)
                    object.offset = 0;
                  if (message.offset != null && message.hasOwnProperty("offset"))
                    object.offset = message.offset;
                  if (message.bucketCounts && message.bucketCounts.length) {
                    object.bucketCounts = [];
                    for (var j = 0; j < message.bucketCounts.length; ++j)
                      if (typeof message.bucketCounts[j] === "number")
                        object.bucketCounts[j] = options2.longs === String ? String(message.bucketCounts[j]) : message.bucketCounts[j];
                      else
                        object.bucketCounts[j] = options2.longs === String ? $util.Long.prototype.toString.call(message.bucketCounts[j]) : options2.longs === Number ? new $util.LongBits(message.bucketCounts[j].low >>> 0, message.bucketCounts[j].high >>> 0).toNumber(true) : message.bucketCounts[j];
                  }
                  return object;
                }, "toObject");
                Buckets.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                Buckets.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets";
                }, "getTypeUrl");
                return Buckets;
              }();
              return ExponentialHistogramDataPoint;
            }();
            v12.SummaryDataPoint = function() {
              function SummaryDataPoint(properties) {
                this.attributes = [];
                this.quantileValues = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(SummaryDataPoint, "SummaryDataPoint");
              SummaryDataPoint.prototype.attributes = $util.emptyArray;
              SummaryDataPoint.prototype.startTimeUnixNano = null;
              SummaryDataPoint.prototype.timeUnixNano = null;
              SummaryDataPoint.prototype.count = null;
              SummaryDataPoint.prototype.sum = null;
              SummaryDataPoint.prototype.quantileValues = $util.emptyArray;
              SummaryDataPoint.prototype.flags = null;
              SummaryDataPoint.create = /* @__PURE__ */ __name(function create3(properties) {
                return new SummaryDataPoint(properties);
              }, "create");
              SummaryDataPoint.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano"))
                  writer.uint32(
                    /* id 2, wireType 1 =*/
                    17
                  ).fixed64(message.startTimeUnixNano);
                if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano"))
                  writer.uint32(
                    /* id 3, wireType 1 =*/
                    25
                  ).fixed64(message.timeUnixNano);
                if (message.count != null && Object.hasOwnProperty.call(message, "count"))
                  writer.uint32(
                    /* id 4, wireType 1 =*/
                    33
                  ).fixed64(message.count);
                if (message.sum != null && Object.hasOwnProperty.call(message, "sum"))
                  writer.uint32(
                    /* id 5, wireType 1 =*/
                    41
                  ).double(message.sum);
                if (message.quantileValues != null && message.quantileValues.length)
                  for (var i = 0; i < message.quantileValues.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.encode(message.quantileValues[i], writer.uint32(
                      /* id 6, wireType 2 =*/
                      50
                    ).fork()).ldelim();
                if (message.attributes != null && message.attributes.length)
                  for (var i = 0; i < message.attributes.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                      /* id 7, wireType 2 =*/
                      58
                    ).fork()).ldelim();
                if (message.flags != null && Object.hasOwnProperty.call(message, "flags"))
                  writer.uint32(
                    /* id 8, wireType 0 =*/
                    64
                  ).uint32(message.flags);
                return writer;
              }, "encode");
              SummaryDataPoint.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              SummaryDataPoint.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.SummaryDataPoint();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 7: {
                      if (!(message.attributes && message.attributes.length))
                        message.attributes = [];
                      message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    case 2: {
                      message.startTimeUnixNano = reader.fixed64();
                      break;
                    }
                    case 3: {
                      message.timeUnixNano = reader.fixed64();
                      break;
                    }
                    case 4: {
                      message.count = reader.fixed64();
                      break;
                    }
                    case 5: {
                      message.sum = reader.double();
                      break;
                    }
                    case 6: {
                      if (!(message.quantileValues && message.quantileValues.length))
                        message.quantileValues = [];
                      message.quantileValues.push($root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.decode(reader, reader.uint32()));
                      break;
                    }
                    case 8: {
                      message.flags = reader.uint32();
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              SummaryDataPoint.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              SummaryDataPoint.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.attributes != null && message.hasOwnProperty("attributes")) {
                  if (!Array.isArray(message.attributes))
                    return "attributes: array expected";
                  for (var i = 0; i < message.attributes.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                    if (error)
                      return "attributes." + error;
                  }
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) {
                  if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high)))
                    return "startTimeUnixNano: integer|Long expected";
                }
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) {
                  if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high)))
                    return "timeUnixNano: integer|Long expected";
                }
                if (message.count != null && message.hasOwnProperty("count")) {
                  if (!$util.isInteger(message.count) && !(message.count && $util.isInteger(message.count.low) && $util.isInteger(message.count.high)))
                    return "count: integer|Long expected";
                }
                if (message.sum != null && message.hasOwnProperty("sum")) {
                  if (typeof message.sum !== "number")
                    return "sum: number expected";
                }
                if (message.quantileValues != null && message.hasOwnProperty("quantileValues")) {
                  if (!Array.isArray(message.quantileValues))
                    return "quantileValues: array expected";
                  for (var i = 0; i < message.quantileValues.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.verify(message.quantileValues[i]);
                    if (error)
                      return "quantileValues." + error;
                  }
                }
                if (message.flags != null && message.hasOwnProperty("flags")) {
                  if (!$util.isInteger(message.flags))
                    return "flags: integer expected";
                }
                return null;
              }, "verify");
              SummaryDataPoint.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.SummaryDataPoint)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.SummaryDataPoint();
                if (object.attributes) {
                  if (!Array.isArray(object.attributes))
                    throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.attributes: array expected");
                  message.attributes = [];
                  for (var i = 0; i < object.attributes.length; ++i) {
                    if (typeof object.attributes[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.attributes: object expected");
                    message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                  }
                }
                if (object.startTimeUnixNano != null) {
                  if ($util.Long)
                    (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false;
                  else if (typeof object.startTimeUnixNano === "string")
                    message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10);
                  else if (typeof object.startTimeUnixNano === "number")
                    message.startTimeUnixNano = object.startTimeUnixNano;
                  else if (typeof object.startTimeUnixNano === "object")
                    message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber();
                }
                if (object.timeUnixNano != null) {
                  if ($util.Long)
                    (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false;
                  else if (typeof object.timeUnixNano === "string")
                    message.timeUnixNano = parseInt(object.timeUnixNano, 10);
                  else if (typeof object.timeUnixNano === "number")
                    message.timeUnixNano = object.timeUnixNano;
                  else if (typeof object.timeUnixNano === "object")
                    message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber();
                }
                if (object.count != null) {
                  if ($util.Long)
                    (message.count = $util.Long.fromValue(object.count)).unsigned = false;
                  else if (typeof object.count === "string")
                    message.count = parseInt(object.count, 10);
                  else if (typeof object.count === "number")
                    message.count = object.count;
                  else if (typeof object.count === "object")
                    message.count = new $util.LongBits(object.count.low >>> 0, object.count.high >>> 0).toNumber();
                }
                if (object.sum != null)
                  message.sum = Number(object.sum);
                if (object.quantileValues) {
                  if (!Array.isArray(object.quantileValues))
                    throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.quantileValues: array expected");
                  message.quantileValues = [];
                  for (var i = 0; i < object.quantileValues.length; ++i) {
                    if (typeof object.quantileValues[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.quantileValues: object expected");
                    message.quantileValues[i] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.fromObject(object.quantileValues[i]);
                  }
                }
                if (object.flags != null)
                  message.flags = object.flags >>> 0;
                return message;
              }, "fromObject");
              SummaryDataPoint.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults) {
                  object.quantileValues = [];
                  object.attributes = [];
                }
                if (options2.defaults) {
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.startTimeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object.startTimeUnixNano = options2.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.timeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object.timeUnixNano = options2.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.count = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object.count = options2.longs === String ? "0" : 0;
                  object.sum = 0;
                  object.flags = 0;
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano"))
                  if (typeof message.startTimeUnixNano === "number")
                    object.startTimeUnixNano = options2.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano;
                  else
                    object.startTimeUnixNano = options2.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options2.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano;
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano"))
                  if (typeof message.timeUnixNano === "number")
                    object.timeUnixNano = options2.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                  else
                    object.timeUnixNano = options2.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options2.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano;
                if (message.count != null && message.hasOwnProperty("count"))
                  if (typeof message.count === "number")
                    object.count = options2.longs === String ? String(message.count) : message.count;
                  else
                    object.count = options2.longs === String ? $util.Long.prototype.toString.call(message.count) : options2.longs === Number ? new $util.LongBits(message.count.low >>> 0, message.count.high >>> 0).toNumber() : message.count;
                if (message.sum != null && message.hasOwnProperty("sum"))
                  object.sum = options2.json && !isFinite(message.sum) ? String(message.sum) : message.sum;
                if (message.quantileValues && message.quantileValues.length) {
                  object.quantileValues = [];
                  for (var j = 0; j < message.quantileValues.length; ++j)
                    object.quantileValues[j] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.toObject(message.quantileValues[j], options2);
                }
                if (message.attributes && message.attributes.length) {
                  object.attributes = [];
                  for (var j = 0; j < message.attributes.length; ++j)
                    object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options2);
                }
                if (message.flags != null && message.hasOwnProperty("flags"))
                  object.flags = message.flags;
                return object;
              }, "toObject");
              SummaryDataPoint.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              SummaryDataPoint.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.SummaryDataPoint";
              }, "getTypeUrl");
              SummaryDataPoint.ValueAtQuantile = function() {
                function ValueAtQuantile(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ValueAtQuantile, "ValueAtQuantile");
                ValueAtQuantile.prototype.quantile = null;
                ValueAtQuantile.prototype.value = null;
                ValueAtQuantile.create = /* @__PURE__ */ __name(function create3(properties) {
                  return new ValueAtQuantile(properties);
                }, "create");
                ValueAtQuantile.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.quantile != null && Object.hasOwnProperty.call(message, "quantile"))
                    writer.uint32(
                      /* id 1, wireType 1 =*/
                      9
                    ).double(message.quantile);
                  if (message.value != null && Object.hasOwnProperty.call(message, "value"))
                    writer.uint32(
                      /* id 2, wireType 1 =*/
                      17
                    ).double(message.value);
                  return writer;
                }, "encode");
                ValueAtQuantile.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ValueAtQuantile.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile();
                  while (reader.pos < end) {
                    var tag2 = reader.uint32();
                    if (tag2 === error)
                      break;
                    switch (tag2 >>> 3) {
                      case 1: {
                        message.quantile = reader.double();
                        break;
                      }
                      case 2: {
                        message.value = reader.double();
                        break;
                      }
                      default:
                        reader.skipType(tag2 & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ValueAtQuantile.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ValueAtQuantile.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.quantile != null && message.hasOwnProperty("quantile")) {
                    if (typeof message.quantile !== "number")
                      return "quantile: number expected";
                  }
                  if (message.value != null && message.hasOwnProperty("value")) {
                    if (typeof message.value !== "number")
                      return "value: number expected";
                  }
                  return null;
                }, "verify");
                ValueAtQuantile.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile)
                    return object;
                  var message = new $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile();
                  if (object.quantile != null)
                    message.quantile = Number(object.quantile);
                  if (object.value != null)
                    message.value = Number(object.value);
                  return message;
                }, "fromObject");
                ValueAtQuantile.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                  if (!options2)
                    options2 = {};
                  var object = {};
                  if (options2.defaults) {
                    object.quantile = 0;
                    object.value = 0;
                  }
                  if (message.quantile != null && message.hasOwnProperty("quantile"))
                    object.quantile = options2.json && !isFinite(message.quantile) ? String(message.quantile) : message.quantile;
                  if (message.value != null && message.hasOwnProperty("value"))
                    object.value = options2.json && !isFinite(message.value) ? String(message.value) : message.value;
                  return object;
                }, "toObject");
                ValueAtQuantile.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ValueAtQuantile.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile";
                }, "getTypeUrl");
                return ValueAtQuantile;
              }();
              return SummaryDataPoint;
            }();
            v12.Exemplar = function() {
              function Exemplar(properties) {
                this.filteredAttributes = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(Exemplar, "Exemplar");
              Exemplar.prototype.filteredAttributes = $util.emptyArray;
              Exemplar.prototype.timeUnixNano = null;
              Exemplar.prototype.asDouble = null;
              Exemplar.prototype.asInt = null;
              Exemplar.prototype.spanId = null;
              Exemplar.prototype.traceId = null;
              var $oneOfFields;
              Object.defineProperty(Exemplar.prototype, "value", {
                get: $util.oneOfGetter($oneOfFields = ["asDouble", "asInt"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              Exemplar.create = /* @__PURE__ */ __name(function create3(properties) {
                return new Exemplar(properties);
              }, "create");
              Exemplar.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano"))
                  writer.uint32(
                    /* id 2, wireType 1 =*/
                    17
                  ).fixed64(message.timeUnixNano);
                if (message.asDouble != null && Object.hasOwnProperty.call(message, "asDouble"))
                  writer.uint32(
                    /* id 3, wireType 1 =*/
                    25
                  ).double(message.asDouble);
                if (message.spanId != null && Object.hasOwnProperty.call(message, "spanId"))
                  writer.uint32(
                    /* id 4, wireType 2 =*/
                    34
                  ).bytes(message.spanId);
                if (message.traceId != null && Object.hasOwnProperty.call(message, "traceId"))
                  writer.uint32(
                    /* id 5, wireType 2 =*/
                    42
                  ).bytes(message.traceId);
                if (message.asInt != null && Object.hasOwnProperty.call(message, "asInt"))
                  writer.uint32(
                    /* id 6, wireType 1 =*/
                    49
                  ).sfixed64(message.asInt);
                if (message.filteredAttributes != null && message.filteredAttributes.length)
                  for (var i = 0; i < message.filteredAttributes.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.filteredAttributes[i], writer.uint32(
                      /* id 7, wireType 2 =*/
                      58
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              Exemplar.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              Exemplar.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Exemplar();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 7: {
                      if (!(message.filteredAttributes && message.filteredAttributes.length))
                        message.filteredAttributes = [];
                      message.filteredAttributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    case 2: {
                      message.timeUnixNano = reader.fixed64();
                      break;
                    }
                    case 3: {
                      message.asDouble = reader.double();
                      break;
                    }
                    case 6: {
                      message.asInt = reader.sfixed64();
                      break;
                    }
                    case 4: {
                      message.spanId = reader.bytes();
                      break;
                    }
                    case 5: {
                      message.traceId = reader.bytes();
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              Exemplar.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              Exemplar.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                var properties = {};
                if (message.filteredAttributes != null && message.hasOwnProperty("filteredAttributes")) {
                  if (!Array.isArray(message.filteredAttributes))
                    return "filteredAttributes: array expected";
                  for (var i = 0; i < message.filteredAttributes.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.filteredAttributes[i]);
                    if (error)
                      return "filteredAttributes." + error;
                  }
                }
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) {
                  if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high)))
                    return "timeUnixNano: integer|Long expected";
                }
                if (message.asDouble != null && message.hasOwnProperty("asDouble")) {
                  properties.value = 1;
                  if (typeof message.asDouble !== "number")
                    return "asDouble: number expected";
                }
                if (message.asInt != null && message.hasOwnProperty("asInt")) {
                  if (properties.value === 1)
                    return "value: multiple values";
                  properties.value = 1;
                  if (!$util.isInteger(message.asInt) && !(message.asInt && $util.isInteger(message.asInt.low) && $util.isInteger(message.asInt.high)))
                    return "asInt: integer|Long expected";
                }
                if (message.spanId != null && message.hasOwnProperty("spanId")) {
                  if (!(message.spanId && typeof message.spanId.length === "number" || $util.isString(message.spanId)))
                    return "spanId: buffer expected";
                }
                if (message.traceId != null && message.hasOwnProperty("traceId")) {
                  if (!(message.traceId && typeof message.traceId.length === "number" || $util.isString(message.traceId)))
                    return "traceId: buffer expected";
                }
                return null;
              }, "verify");
              Exemplar.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.Exemplar)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.Exemplar();
                if (object.filteredAttributes) {
                  if (!Array.isArray(object.filteredAttributes))
                    throw TypeError(".opentelemetry.proto.metrics.v1.Exemplar.filteredAttributes: array expected");
                  message.filteredAttributes = [];
                  for (var i = 0; i < object.filteredAttributes.length; ++i) {
                    if (typeof object.filteredAttributes[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Exemplar.filteredAttributes: object expected");
                    message.filteredAttributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.filteredAttributes[i]);
                  }
                }
                if (object.timeUnixNano != null) {
                  if ($util.Long)
                    (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false;
                  else if (typeof object.timeUnixNano === "string")
                    message.timeUnixNano = parseInt(object.timeUnixNano, 10);
                  else if (typeof object.timeUnixNano === "number")
                    message.timeUnixNano = object.timeUnixNano;
                  else if (typeof object.timeUnixNano === "object")
                    message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber();
                }
                if (object.asDouble != null)
                  message.asDouble = Number(object.asDouble);
                if (object.asInt != null) {
                  if ($util.Long)
                    (message.asInt = $util.Long.fromValue(object.asInt)).unsigned = false;
                  else if (typeof object.asInt === "string")
                    message.asInt = parseInt(object.asInt, 10);
                  else if (typeof object.asInt === "number")
                    message.asInt = object.asInt;
                  else if (typeof object.asInt === "object")
                    message.asInt = new $util.LongBits(object.asInt.low >>> 0, object.asInt.high >>> 0).toNumber();
                }
                if (object.spanId != null) {
                  if (typeof object.spanId === "string")
                    $util.base64.decode(object.spanId, message.spanId = $util.newBuffer($util.base64.length(object.spanId)), 0);
                  else if (object.spanId.length >= 0)
                    message.spanId = object.spanId;
                }
                if (object.traceId != null) {
                  if (typeof object.traceId === "string")
                    $util.base64.decode(object.traceId, message.traceId = $util.newBuffer($util.base64.length(object.traceId)), 0);
                  else if (object.traceId.length >= 0)
                    message.traceId = object.traceId;
                }
                return message;
              }, "fromObject");
              Exemplar.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.filteredAttributes = [];
                if (options2.defaults) {
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.timeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object.timeUnixNano = options2.longs === String ? "0" : 0;
                  if (options2.bytes === String)
                    object.spanId = "";
                  else {
                    object.spanId = [];
                    if (options2.bytes !== Array)
                      object.spanId = $util.newBuffer(object.spanId);
                  }
                  if (options2.bytes === String)
                    object.traceId = "";
                  else {
                    object.traceId = [];
                    if (options2.bytes !== Array)
                      object.traceId = $util.newBuffer(object.traceId);
                  }
                }
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano"))
                  if (typeof message.timeUnixNano === "number")
                    object.timeUnixNano = options2.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                  else
                    object.timeUnixNano = options2.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options2.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano;
                if (message.asDouble != null && message.hasOwnProperty("asDouble")) {
                  object.asDouble = options2.json && !isFinite(message.asDouble) ? String(message.asDouble) : message.asDouble;
                  if (options2.oneofs)
                    object.value = "asDouble";
                }
                if (message.spanId != null && message.hasOwnProperty("spanId"))
                  object.spanId = options2.bytes === String ? $util.base64.encode(message.spanId, 0, message.spanId.length) : options2.bytes === Array ? Array.prototype.slice.call(message.spanId) : message.spanId;
                if (message.traceId != null && message.hasOwnProperty("traceId"))
                  object.traceId = options2.bytes === String ? $util.base64.encode(message.traceId, 0, message.traceId.length) : options2.bytes === Array ? Array.prototype.slice.call(message.traceId) : message.traceId;
                if (message.asInt != null && message.hasOwnProperty("asInt")) {
                  if (typeof message.asInt === "number")
                    object.asInt = options2.longs === String ? String(message.asInt) : message.asInt;
                  else
                    object.asInt = options2.longs === String ? $util.Long.prototype.toString.call(message.asInt) : options2.longs === Number ? new $util.LongBits(message.asInt.low >>> 0, message.asInt.high >>> 0).toNumber() : message.asInt;
                  if (options2.oneofs)
                    object.value = "asInt";
                }
                if (message.filteredAttributes && message.filteredAttributes.length) {
                  object.filteredAttributes = [];
                  for (var j = 0; j < message.filteredAttributes.length; ++j)
                    object.filteredAttributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.filteredAttributes[j], options2);
                }
                return object;
              }, "toObject");
              Exemplar.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              Exemplar.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Exemplar";
              }, "getTypeUrl");
              return Exemplar;
            }();
            return v12;
          }();
          return metrics2;
        }();
        proto3.logs = function() {
          var logs2 = {};
          logs2.v1 = function() {
            var v12 = {};
            v12.LogsData = function() {
              function LogsData(properties) {
                this.resourceLogs = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(LogsData, "LogsData");
              LogsData.prototype.resourceLogs = $util.emptyArray;
              LogsData.create = /* @__PURE__ */ __name(function create3(properties) {
                return new LogsData(properties);
              }, "create");
              LogsData.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.resourceLogs != null && message.resourceLogs.length)
                  for (var i = 0; i < message.resourceLogs.length; ++i)
                    $root.opentelemetry.proto.logs.v1.ResourceLogs.encode(message.resourceLogs[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              LogsData.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              LogsData.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.logs.v1.LogsData();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      if (!(message.resourceLogs && message.resourceLogs.length))
                        message.resourceLogs = [];
                      message.resourceLogs.push($root.opentelemetry.proto.logs.v1.ResourceLogs.decode(reader, reader.uint32()));
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              LogsData.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              LogsData.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.resourceLogs != null && message.hasOwnProperty("resourceLogs")) {
                  if (!Array.isArray(message.resourceLogs))
                    return "resourceLogs: array expected";
                  for (var i = 0; i < message.resourceLogs.length; ++i) {
                    var error = $root.opentelemetry.proto.logs.v1.ResourceLogs.verify(message.resourceLogs[i]);
                    if (error)
                      return "resourceLogs." + error;
                  }
                }
                return null;
              }, "verify");
              LogsData.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.logs.v1.LogsData)
                  return object;
                var message = new $root.opentelemetry.proto.logs.v1.LogsData();
                if (object.resourceLogs) {
                  if (!Array.isArray(object.resourceLogs))
                    throw TypeError(".opentelemetry.proto.logs.v1.LogsData.resourceLogs: array expected");
                  message.resourceLogs = [];
                  for (var i = 0; i < object.resourceLogs.length; ++i) {
                    if (typeof object.resourceLogs[i] !== "object")
                      throw TypeError(".opentelemetry.proto.logs.v1.LogsData.resourceLogs: object expected");
                    message.resourceLogs[i] = $root.opentelemetry.proto.logs.v1.ResourceLogs.fromObject(object.resourceLogs[i]);
                  }
                }
                return message;
              }, "fromObject");
              LogsData.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.resourceLogs = [];
                if (message.resourceLogs && message.resourceLogs.length) {
                  object.resourceLogs = [];
                  for (var j = 0; j < message.resourceLogs.length; ++j)
                    object.resourceLogs[j] = $root.opentelemetry.proto.logs.v1.ResourceLogs.toObject(message.resourceLogs[j], options2);
                }
                return object;
              }, "toObject");
              LogsData.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              LogsData.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.logs.v1.LogsData";
              }, "getTypeUrl");
              return LogsData;
            }();
            v12.ResourceLogs = function() {
              function ResourceLogs(properties) {
                this.scopeLogs = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(ResourceLogs, "ResourceLogs");
              ResourceLogs.prototype.resource = null;
              ResourceLogs.prototype.scopeLogs = $util.emptyArray;
              ResourceLogs.prototype.schemaUrl = null;
              ResourceLogs.create = /* @__PURE__ */ __name(function create3(properties) {
                return new ResourceLogs(properties);
              }, "create");
              ResourceLogs.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.resource != null && Object.hasOwnProperty.call(message, "resource"))
                  $root.opentelemetry.proto.resource.v1.Resource.encode(message.resource, writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).fork()).ldelim();
                if (message.scopeLogs != null && message.scopeLogs.length)
                  for (var i = 0; i < message.scopeLogs.length; ++i)
                    $root.opentelemetry.proto.logs.v1.ScopeLogs.encode(message.scopeLogs[i], writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).fork()).ldelim();
                if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl"))
                  writer.uint32(
                    /* id 3, wireType 2 =*/
                    26
                  ).string(message.schemaUrl);
                return writer;
              }, "encode");
              ResourceLogs.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              ResourceLogs.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.logs.v1.ResourceLogs();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      message.resource = $root.opentelemetry.proto.resource.v1.Resource.decode(reader, reader.uint32());
                      break;
                    }
                    case 2: {
                      if (!(message.scopeLogs && message.scopeLogs.length))
                        message.scopeLogs = [];
                      message.scopeLogs.push($root.opentelemetry.proto.logs.v1.ScopeLogs.decode(reader, reader.uint32()));
                      break;
                    }
                    case 3: {
                      message.schemaUrl = reader.string();
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              ResourceLogs.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              ResourceLogs.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.resource != null && message.hasOwnProperty("resource")) {
                  var error = $root.opentelemetry.proto.resource.v1.Resource.verify(message.resource);
                  if (error)
                    return "resource." + error;
                }
                if (message.scopeLogs != null && message.hasOwnProperty("scopeLogs")) {
                  if (!Array.isArray(message.scopeLogs))
                    return "scopeLogs: array expected";
                  for (var i = 0; i < message.scopeLogs.length; ++i) {
                    var error = $root.opentelemetry.proto.logs.v1.ScopeLogs.verify(message.scopeLogs[i]);
                    if (error)
                      return "scopeLogs." + error;
                  }
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) {
                  if (!$util.isString(message.schemaUrl))
                    return "schemaUrl: string expected";
                }
                return null;
              }, "verify");
              ResourceLogs.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.logs.v1.ResourceLogs)
                  return object;
                var message = new $root.opentelemetry.proto.logs.v1.ResourceLogs();
                if (object.resource != null) {
                  if (typeof object.resource !== "object")
                    throw TypeError(".opentelemetry.proto.logs.v1.ResourceLogs.resource: object expected");
                  message.resource = $root.opentelemetry.proto.resource.v1.Resource.fromObject(object.resource);
                }
                if (object.scopeLogs) {
                  if (!Array.isArray(object.scopeLogs))
                    throw TypeError(".opentelemetry.proto.logs.v1.ResourceLogs.scopeLogs: array expected");
                  message.scopeLogs = [];
                  for (var i = 0; i < object.scopeLogs.length; ++i) {
                    if (typeof object.scopeLogs[i] !== "object")
                      throw TypeError(".opentelemetry.proto.logs.v1.ResourceLogs.scopeLogs: object expected");
                    message.scopeLogs[i] = $root.opentelemetry.proto.logs.v1.ScopeLogs.fromObject(object.scopeLogs[i]);
                  }
                }
                if (object.schemaUrl != null)
                  message.schemaUrl = String(object.schemaUrl);
                return message;
              }, "fromObject");
              ResourceLogs.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.scopeLogs = [];
                if (options2.defaults) {
                  object.resource = null;
                  object.schemaUrl = "";
                }
                if (message.resource != null && message.hasOwnProperty("resource"))
                  object.resource = $root.opentelemetry.proto.resource.v1.Resource.toObject(message.resource, options2);
                if (message.scopeLogs && message.scopeLogs.length) {
                  object.scopeLogs = [];
                  for (var j = 0; j < message.scopeLogs.length; ++j)
                    object.scopeLogs[j] = $root.opentelemetry.proto.logs.v1.ScopeLogs.toObject(message.scopeLogs[j], options2);
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object.schemaUrl = message.schemaUrl;
                return object;
              }, "toObject");
              ResourceLogs.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              ResourceLogs.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.logs.v1.ResourceLogs";
              }, "getTypeUrl");
              return ResourceLogs;
            }();
            v12.ScopeLogs = function() {
              function ScopeLogs(properties) {
                this.logRecords = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(ScopeLogs, "ScopeLogs");
              ScopeLogs.prototype.scope = null;
              ScopeLogs.prototype.logRecords = $util.emptyArray;
              ScopeLogs.prototype.schemaUrl = null;
              ScopeLogs.create = /* @__PURE__ */ __name(function create3(properties) {
                return new ScopeLogs(properties);
              }, "create");
              ScopeLogs.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.scope != null && Object.hasOwnProperty.call(message, "scope"))
                  $root.opentelemetry.proto.common.v1.InstrumentationScope.encode(message.scope, writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).fork()).ldelim();
                if (message.logRecords != null && message.logRecords.length)
                  for (var i = 0; i < message.logRecords.length; ++i)
                    $root.opentelemetry.proto.logs.v1.LogRecord.encode(message.logRecords[i], writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).fork()).ldelim();
                if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl"))
                  writer.uint32(
                    /* id 3, wireType 2 =*/
                    26
                  ).string(message.schemaUrl);
                return writer;
              }, "encode");
              ScopeLogs.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              ScopeLogs.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.logs.v1.ScopeLogs();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.decode(reader, reader.uint32());
                      break;
                    }
                    case 2: {
                      if (!(message.logRecords && message.logRecords.length))
                        message.logRecords = [];
                      message.logRecords.push($root.opentelemetry.proto.logs.v1.LogRecord.decode(reader, reader.uint32()));
                      break;
                    }
                    case 3: {
                      message.schemaUrl = reader.string();
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              ScopeLogs.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              ScopeLogs.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.scope != null && message.hasOwnProperty("scope")) {
                  var error = $root.opentelemetry.proto.common.v1.InstrumentationScope.verify(message.scope);
                  if (error)
                    return "scope." + error;
                }
                if (message.logRecords != null && message.hasOwnProperty("logRecords")) {
                  if (!Array.isArray(message.logRecords))
                    return "logRecords: array expected";
                  for (var i = 0; i < message.logRecords.length; ++i) {
                    var error = $root.opentelemetry.proto.logs.v1.LogRecord.verify(message.logRecords[i]);
                    if (error)
                      return "logRecords." + error;
                  }
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) {
                  if (!$util.isString(message.schemaUrl))
                    return "schemaUrl: string expected";
                }
                return null;
              }, "verify");
              ScopeLogs.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.logs.v1.ScopeLogs)
                  return object;
                var message = new $root.opentelemetry.proto.logs.v1.ScopeLogs();
                if (object.scope != null) {
                  if (typeof object.scope !== "object")
                    throw TypeError(".opentelemetry.proto.logs.v1.ScopeLogs.scope: object expected");
                  message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(object.scope);
                }
                if (object.logRecords) {
                  if (!Array.isArray(object.logRecords))
                    throw TypeError(".opentelemetry.proto.logs.v1.ScopeLogs.logRecords: array expected");
                  message.logRecords = [];
                  for (var i = 0; i < object.logRecords.length; ++i) {
                    if (typeof object.logRecords[i] !== "object")
                      throw TypeError(".opentelemetry.proto.logs.v1.ScopeLogs.logRecords: object expected");
                    message.logRecords[i] = $root.opentelemetry.proto.logs.v1.LogRecord.fromObject(object.logRecords[i]);
                  }
                }
                if (object.schemaUrl != null)
                  message.schemaUrl = String(object.schemaUrl);
                return message;
              }, "fromObject");
              ScopeLogs.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.logRecords = [];
                if (options2.defaults) {
                  object.scope = null;
                  object.schemaUrl = "";
                }
                if (message.scope != null && message.hasOwnProperty("scope"))
                  object.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.toObject(message.scope, options2);
                if (message.logRecords && message.logRecords.length) {
                  object.logRecords = [];
                  for (var j = 0; j < message.logRecords.length; ++j)
                    object.logRecords[j] = $root.opentelemetry.proto.logs.v1.LogRecord.toObject(message.logRecords[j], options2);
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object.schemaUrl = message.schemaUrl;
                return object;
              }, "toObject");
              ScopeLogs.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              ScopeLogs.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.logs.v1.ScopeLogs";
              }, "getTypeUrl");
              return ScopeLogs;
            }();
            v12.SeverityNumber = function() {
              var valuesById = {}, values = Object.create(valuesById);
              values[valuesById[0] = "SEVERITY_NUMBER_UNSPECIFIED"] = 0;
              values[valuesById[1] = "SEVERITY_NUMBER_TRACE"] = 1;
              values[valuesById[2] = "SEVERITY_NUMBER_TRACE2"] = 2;
              values[valuesById[3] = "SEVERITY_NUMBER_TRACE3"] = 3;
              values[valuesById[4] = "SEVERITY_NUMBER_TRACE4"] = 4;
              values[valuesById[5] = "SEVERITY_NUMBER_DEBUG"] = 5;
              values[valuesById[6] = "SEVERITY_NUMBER_DEBUG2"] = 6;
              values[valuesById[7] = "SEVERITY_NUMBER_DEBUG3"] = 7;
              values[valuesById[8] = "SEVERITY_NUMBER_DEBUG4"] = 8;
              values[valuesById[9] = "SEVERITY_NUMBER_INFO"] = 9;
              values[valuesById[10] = "SEVERITY_NUMBER_INFO2"] = 10;
              values[valuesById[11] = "SEVERITY_NUMBER_INFO3"] = 11;
              values[valuesById[12] = "SEVERITY_NUMBER_INFO4"] = 12;
              values[valuesById[13] = "SEVERITY_NUMBER_WARN"] = 13;
              values[valuesById[14] = "SEVERITY_NUMBER_WARN2"] = 14;
              values[valuesById[15] = "SEVERITY_NUMBER_WARN3"] = 15;
              values[valuesById[16] = "SEVERITY_NUMBER_WARN4"] = 16;
              values[valuesById[17] = "SEVERITY_NUMBER_ERROR"] = 17;
              values[valuesById[18] = "SEVERITY_NUMBER_ERROR2"] = 18;
              values[valuesById[19] = "SEVERITY_NUMBER_ERROR3"] = 19;
              values[valuesById[20] = "SEVERITY_NUMBER_ERROR4"] = 20;
              values[valuesById[21] = "SEVERITY_NUMBER_FATAL"] = 21;
              values[valuesById[22] = "SEVERITY_NUMBER_FATAL2"] = 22;
              values[valuesById[23] = "SEVERITY_NUMBER_FATAL3"] = 23;
              values[valuesById[24] = "SEVERITY_NUMBER_FATAL4"] = 24;
              return values;
            }();
            v12.LogRecordFlags = function() {
              var valuesById = {}, values = Object.create(valuesById);
              values[valuesById[0] = "LOG_RECORD_FLAGS_DO_NOT_USE"] = 0;
              values[valuesById[255] = "LOG_RECORD_FLAGS_TRACE_FLAGS_MASK"] = 255;
              return values;
            }();
            v12.LogRecord = function() {
              function LogRecord(properties) {
                this.attributes = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(LogRecord, "LogRecord");
              LogRecord.prototype.timeUnixNano = null;
              LogRecord.prototype.observedTimeUnixNano = null;
              LogRecord.prototype.severityNumber = null;
              LogRecord.prototype.severityText = null;
              LogRecord.prototype.body = null;
              LogRecord.prototype.attributes = $util.emptyArray;
              LogRecord.prototype.droppedAttributesCount = null;
              LogRecord.prototype.flags = null;
              LogRecord.prototype.traceId = null;
              LogRecord.prototype.spanId = null;
              LogRecord.prototype.eventName = null;
              LogRecord.create = /* @__PURE__ */ __name(function create3(properties) {
                return new LogRecord(properties);
              }, "create");
              LogRecord.encode = /* @__PURE__ */ __name(function encode4(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano"))
                  writer.uint32(
                    /* id 1, wireType 1 =*/
                    9
                  ).fixed64(message.timeUnixNano);
                if (message.severityNumber != null && Object.hasOwnProperty.call(message, "severityNumber"))
                  writer.uint32(
                    /* id 2, wireType 0 =*/
                    16
                  ).int32(message.severityNumber);
                if (message.severityText != null && Object.hasOwnProperty.call(message, "severityText"))
                  writer.uint32(
                    /* id 3, wireType 2 =*/
                    26
                  ).string(message.severityText);
                if (message.body != null && Object.hasOwnProperty.call(message, "body"))
                  $root.opentelemetry.proto.common.v1.AnyValue.encode(message.body, writer.uint32(
                    /* id 5, wireType 2 =*/
                    42
                  ).fork()).ldelim();
                if (message.attributes != null && message.attributes.length)
                  for (var i = 0; i < message.attributes.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                      /* id 6, wireType 2 =*/
                      50
                    ).fork()).ldelim();
                if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount"))
                  writer.uint32(
                    /* id 7, wireType 0 =*/
                    56
                  ).uint32(message.droppedAttributesCount);
                if (message.flags != null && Object.hasOwnProperty.call(message, "flags"))
                  writer.uint32(
                    /* id 8, wireType 5 =*/
                    69
                  ).fixed32(message.flags);
                if (message.traceId != null && Object.hasOwnProperty.call(message, "traceId"))
                  writer.uint32(
                    /* id 9, wireType 2 =*/
                    74
                  ).bytes(message.traceId);
                if (message.spanId != null && Object.hasOwnProperty.call(message, "spanId"))
                  writer.uint32(
                    /* id 10, wireType 2 =*/
                    82
                  ).bytes(message.spanId);
                if (message.observedTimeUnixNano != null && Object.hasOwnProperty.call(message, "observedTimeUnixNano"))
                  writer.uint32(
                    /* id 11, wireType 1 =*/
                    89
                  ).fixed64(message.observedTimeUnixNano);
                if (message.eventName != null && Object.hasOwnProperty.call(message, "eventName"))
                  writer.uint32(
                    /* id 12, wireType 2 =*/
                    98
                  ).string(message.eventName);
                return writer;
              }, "encode");
              LogRecord.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              LogRecord.decode = /* @__PURE__ */ __name(function decode2(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.logs.v1.LogRecord();
                while (reader.pos < end) {
                  var tag2 = reader.uint32();
                  if (tag2 === error)
                    break;
                  switch (tag2 >>> 3) {
                    case 1: {
                      message.timeUnixNano = reader.fixed64();
                      break;
                    }
                    case 11: {
                      message.observedTimeUnixNano = reader.fixed64();
                      break;
                    }
                    case 2: {
                      message.severityNumber = reader.int32();
                      break;
                    }
                    case 3: {
                      message.severityText = reader.string();
                      break;
                    }
                    case 5: {
                      message.body = $root.opentelemetry.proto.common.v1.AnyValue.decode(reader, reader.uint32());
                      break;
                    }
                    case 6: {
                      if (!(message.attributes && message.attributes.length))
                        message.attributes = [];
                      message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    case 7: {
                      message.droppedAttributesCount = reader.uint32();
                      break;
                    }
                    case 8: {
                      message.flags = reader.fixed32();
                      break;
                    }
                    case 9: {
                      message.traceId = reader.bytes();
                      break;
                    }
                    case 10: {
                      message.spanId = reader.bytes();
                      break;
                    }
                    case 12: {
                      message.eventName = reader.string();
                      break;
                    }
                    default:
                      reader.skipType(tag2 & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              LogRecord.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              LogRecord.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) {
                  if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high)))
                    return "timeUnixNano: integer|Long expected";
                }
                if (message.observedTimeUnixNano != null && message.hasOwnProperty("observedTimeUnixNano")) {
                  if (!$util.isInteger(message.observedTimeUnixNano) && !(message.observedTimeUnixNano && $util.isInteger(message.observedTimeUnixNano.low) && $util.isInteger(message.observedTimeUnixNano.high)))
                    return "observedTimeUnixNano: integer|Long expected";
                }
                if (message.severityNumber != null && message.hasOwnProperty("severityNumber"))
                  switch (message.severityNumber) {
                    default:
                      return "severityNumber: 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:
                    case 11:
                    case 12:
                    case 13:
                    case 14:
                    case 15:
                    case 16:
                    case 17:
                    case 18:
                    case 19:
                    case 20:
                    case 21:
                    case 22:
                    case 23:
                    case 24:
                      break;
                  }
                if (message.severityText != null && message.hasOwnProperty("severityText")) {
                  if (!$util.isString(message.severityText))
                    return "severityText: string expected";
                }
                if (message.body != null && message.hasOwnProperty("body")) {
                  var error = $root.opentelemetry.proto.common.v1.AnyValue.verify(message.body);
                  if (error)
                    return "body." + error;
                }
                if (message.attributes != null && message.hasOwnProperty("attributes")) {
                  if (!Array.isArray(message.attributes))
                    return "attributes: array expected";
                  for (var i = 0; i < message.attributes.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                    if (error)
                      return "attributes." + error;
                  }
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) {
                  if (!$util.isInteger(message.droppedAttributesCount))
                    return "droppedAttributesCount: integer expected";
                }
                if (message.flags != null && message.hasOwnProperty("flags")) {
                  if (!$util.isInteger(message.flags))
                    return "flags: integer expected";
                }
                if (message.traceId != null && message.hasOwnProperty("traceId")) {
                  if (!(message.traceId && typeof message.traceId.length === "number" || $util.isString(message.traceId)))
                    return "traceId: buffer expected";
                }
                if (message.spanId != null && message.hasOwnProperty("spanId")) {
                  if (!(message.spanId && typeof message.spanId.length === "number" || $util.isString(message.spanId)))
                    return "spanId: buffer expected";
                }
                if (message.eventName != null && message.hasOwnProperty("eventName")) {
                  if (!$util.isString(message.eventName))
                    return "eventName: string expected";
                }
                return null;
              }, "verify");
              LogRecord.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.logs.v1.LogRecord)
                  return object;
                var message = new $root.opentelemetry.proto.logs.v1.LogRecord();
                if (object.timeUnixNano != null) {
                  if ($util.Long)
                    (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false;
                  else if (typeof object.timeUnixNano === "string")
                    message.timeUnixNano = parseInt(object.timeUnixNano, 10);
                  else if (typeof object.timeUnixNano === "number")
                    message.timeUnixNano = object.timeUnixNano;
                  else if (typeof object.timeUnixNano === "object")
                    message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber();
                }
                if (object.observedTimeUnixNano != null) {
                  if ($util.Long)
                    (message.observedTimeUnixNano = $util.Long.fromValue(object.observedTimeUnixNano)).unsigned = false;
                  else if (typeof object.observedTimeUnixNano === "string")
                    message.observedTimeUnixNano = parseInt(object.observedTimeUnixNano, 10);
                  else if (typeof object.observedTimeUnixNano === "number")
                    message.observedTimeUnixNano = object.observedTimeUnixNano;
                  else if (typeof object.observedTimeUnixNano === "object")
                    message.observedTimeUnixNano = new $util.LongBits(object.observedTimeUnixNano.low >>> 0, object.observedTimeUnixNano.high >>> 0).toNumber();
                }
                switch (object.severityNumber) {
                  default:
                    if (typeof object.severityNumber === "number") {
                      message.severityNumber = object.severityNumber;
                      break;
                    }
                    break;
                  case "SEVERITY_NUMBER_UNSPECIFIED":
                  case 0:
                    message.severityNumber = 0;
                    break;
                  case "SEVERITY_NUMBER_TRACE":
                  case 1:
                    message.severityNumber = 1;
                    break;
                  case "SEVERITY_NUMBER_TRACE2":
                  case 2:
                    message.severityNumber = 2;
                    break;
                  case "SEVERITY_NUMBER_TRACE3":
                  case 3:
                    message.severityNumber = 3;
                    break;
                  case "SEVERITY_NUMBER_TRACE4":
                  case 4:
                    message.severityNumber = 4;
                    break;
                  case "SEVERITY_NUMBER_DEBUG":
                  case 5:
                    message.severityNumber = 5;
                    break;
                  case "SEVERITY_NUMBER_DEBUG2":
                  case 6:
                    message.severityNumber = 6;
                    break;
                  case "SEVERITY_NUMBER_DEBUG3":
                  case 7:
                    message.severityNumber = 7;
                    break;
                  case "SEVERITY_NUMBER_DEBUG4":
                  case 8:
                    message.severityNumber = 8;
                    break;
                  case "SEVERITY_NUMBER_INFO":
                  case 9:
                    message.severityNumber = 9;
                    break;
                  case "SEVERITY_NUMBER_INFO2":
                  case 10:
                    message.severityNumber = 10;
                    break;
                  case "SEVERITY_NUMBER_INFO3":
                  case 11:
                    message.severityNumber = 11;
                    break;
                  case "SEVERITY_NUMBER_INFO4":
                  case 12:
                    message.severityNumber = 12;
                    break;
                  case "SEVERITY_NUMBER_WARN":
                  case 13:
                    message.severityNumber = 13;
                    break;
                  case "SEVERITY_NUMBER_WARN2":
                  case 14:
                    message.severityNumber = 14;
                    break;
                  case "SEVERITY_NUMBER_WARN3":
                  case 15:
                    message.severityNumber = 15;
                    break;
                  case "SEVERITY_NUMBER_WARN4":
                  case 16:
                    message.severityNumber = 16;
                    break;
                  case "SEVERITY_NUMBER_ERROR":
                  case 17:
                    message.severityNumber = 17;
                    break;
                  case "SEVERITY_NUMBER_ERROR2":
                  case 18:
                    message.severityNumber = 18;
                    break;
                  case "SEVERITY_NUMBER_ERROR3":
                  case 19:
                    message.severityNumber = 19;
                    break;
                  case "SEVERITY_NUMBER_ERROR4":
                  case 20:
                    message.severityNumber = 20;
                    break;
                  case "SEVERITY_NUMBER_FATAL":
                  case 21:
                    message.severityNumber = 21;
                    break;
                  case "SEVERITY_NUMBER_FATAL2":
                  case 22:
                    message.severityNumber = 22;
                    break;
                  case "SEVERITY_NUMBER_FATAL3":
                  case 23:
                    message.severityNumber = 23;
                    break;
                  case "SEVERITY_NUMBER_FATAL4":
                  case 24:
                    message.severityNumber = 24;
                    break;
                }
                if (object.severityText != null)
                  message.severityText = String(object.severityText);
                if (object.body != null) {
                  if (typeof object.body !== "object")
                    throw TypeError(".opentelemetry.proto.logs.v1.LogRecord.body: object expected");
                  message.body = $root.opentelemetry.proto.common.v1.AnyValue.fromObject(object.body);
                }
                if (object.attributes) {
                  if (!Array.isArray(object.attributes))
                    throw TypeError(".opentelemetry.proto.logs.v1.LogRecord.attributes: array expected");
                  message.attributes = [];
                  for (var i = 0; i < object.attributes.length; ++i) {
                    if (typeof object.attributes[i] !== "object")
                      throw TypeError(".opentelemetry.proto.logs.v1.LogRecord.attributes: object expected");
                    message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                  }
                }
                if (object.droppedAttributesCount != null)
                  message.droppedAttributesCount = object.droppedAttributesCount >>> 0;
                if (object.flags != null)
                  message.flags = object.flags >>> 0;
                if (object.traceId != null) {
                  if (typeof object.traceId === "string")
                    $util.base64.decode(object.traceId, message.traceId = $util.newBuffer($util.base64.length(object.traceId)), 0);
                  else if (object.traceId.length >= 0)
                    message.traceId = object.traceId;
                }
                if (object.spanId != null) {
                  if (typeof object.spanId === "string")
                    $util.base64.decode(object.spanId, message.spanId = $util.newBuffer($util.base64.length(object.spanId)), 0);
                  else if (object.spanId.length >= 0)
                    message.spanId = object.spanId;
                }
                if (object.eventName != null)
                  message.eventName = String(object.eventName);
                return message;
              }, "fromObject");
              LogRecord.toObject = /* @__PURE__ */ __name(function toObject(message, options2) {
                if (!options2)
                  options2 = {};
                var object = {};
                if (options2.arrays || options2.defaults)
                  object.attributes = [];
                if (options2.defaults) {
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.timeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object.timeUnixNano = options2.longs === String ? "0" : 0;
                  object.severityNumber = options2.enums === String ? "SEVERITY_NUMBER_UNSPECIFIED" : 0;
                  object.severityText = "";
                  object.body = null;
                  object.droppedAttributesCount = 0;
                  object.flags = 0;
                  if (options2.bytes === String)
                    object.traceId = "";
                  else {
                    object.traceId = [];
                    if (options2.bytes !== Array)
                      object.traceId = $util.newBuffer(object.traceId);
                  }
                  if (options2.bytes === String)
                    object.spanId = "";
                  else {
                    object.spanId = [];
                    if (options2.bytes !== Array)
                      object.spanId = $util.newBuffer(object.spanId);
                  }
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.observedTimeUnixNano = options2.longs === String ? long.toString() : options2.longs === Number ? long.toNumber() : long;
                  } else
                    object.observedTimeUnixNano = options2.longs === String ? "0" : 0;
                  object.eventName = "";
                }
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano"))
                  if (typeof message.timeUnixNano === "number")
                    object.timeUnixNano = options2.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                  else
                    object.timeUnixNano = options2.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options2.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano;
                if (message.severityNumber != null && message.hasOwnProperty("severityNumber"))
                  object.severityNumber = options2.enums === String ? $root.opentelemetry.proto.logs.v1.SeverityNumber[message.severityNumber] === void 0 ? message.severityNumber : $root.opentelemetry.proto.logs.v1.SeverityNumber[message.severityNumber] : message.severityNumber;
                if (message.severityText != null && message.hasOwnProperty("severityText"))
                  object.severityText = message.severityText;
                if (message.body != null && message.hasOwnProperty("body"))
                  object.body = $root.opentelemetry.proto.common.v1.AnyValue.toObject(message.body, options2);
                if (message.attributes && message.attributes.length) {
                  object.attributes = [];
                  for (var j = 0; j < message.attributes.length; ++j)
                    object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options2);
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount"))
                  object.droppedAttributesCount = message.droppedAttributesCount;
                if (message.flags != null && message.hasOwnProperty("flags"))
                  object.flags = message.flags;
                if (message.traceId != null && message.hasOwnProperty("traceId"))
                  object.traceId = options2.bytes === String ? $util.base64.encode(message.traceId, 0, message.traceId.length) : options2.bytes === Array ? Array.prototype.slice.call(message.traceId) : message.traceId;
                if (message.spanId != null && message.hasOwnProperty("spanId"))
                  object.spanId = options2.bytes === String ? $util.base64.encode(message.spanId, 0, message.spanId.length) : options2.bytes === Array ? Array.prototype.slice.call(message.spanId) : message.spanId;
                if (message.observedTimeUnixNano != null && message.hasOwnProperty("observedTimeUnixNano"))
                  if (typeof message.observedTimeUnixNano === "number")
                    object.observedTimeUnixNano = options2.longs === String ? String(message.observedTimeUnixNano) : message.observedTimeUnixNano;
                  else
                    object.observedTimeUnixNano = options2.longs === String ? $util.Long.prototype.toString.call(message.observedTimeUnixNano) : options2.longs === Number ? new $util.LongBits(message.observedTimeUnixNano.low >>> 0, message.observedTimeUnixNano.high >>> 0).toNumber() : message.observedTimeUnixNano;
                if (message.eventName != null && message.hasOwnProperty("eventName"))
                  object.eventName = message.eventName;
                return object;
              }, "toObject");
              LogRecord.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              LogRecord.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.logs.v1.LogRecord";
              }, "getTypeUrl");
              return LogRecord;
            }();
            return v12;
          }();
          return logs2;
        }();
        return proto3;
      }();
      return opentelemetry;
    }();
    module2.exports = $root;
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/common/hex-to-binary.js
var require_hex_to_binary = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/common/hex-to-binary.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.hexToBinary = void 0;
    function intValue(charCode) {
      if (charCode >= 48 && charCode <= 57) {
        return charCode - 48;
      }
      if (charCode >= 97 && charCode <= 102) {
        return charCode - 87;
      }
      return charCode - 55;
    }
    __name(intValue, "intValue");
    function hexToBinary(hexStr) {
      const buf = new Uint8Array(hexStr.length / 2);
      let offset = 0;
      for (let i = 0; i < hexStr.length; i += 2) {
        const hi = intValue(hexStr.charCodeAt(i));
        const lo = intValue(hexStr.charCodeAt(i + 1));
        buf[offset++] = hi << 4 | lo;
      }
      return buf;
    }
    __name(hexToBinary, "hexToBinary");
    exports2.hexToBinary = hexToBinary;
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/common/utils.js
var require_utils5 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/common/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getOtlpEncoder = exports2.encodeAsString = exports2.encodeAsLongBits = exports2.toLongBits = exports2.hrTimeToNanos = void 0;
    var core_1 = require_src8();
    var hex_to_binary_1 = require_hex_to_binary();
    function hrTimeToNanos(hrTime) {
      const NANOSECONDS = BigInt(1e9);
      return BigInt(hrTime[0]) * NANOSECONDS + BigInt(hrTime[1]);
    }
    __name(hrTimeToNanos, "hrTimeToNanos");
    exports2.hrTimeToNanos = hrTimeToNanos;
    function toLongBits(value) {
      const low = Number(BigInt.asUintN(32, value));
      const high = Number(BigInt.asUintN(32, value >> BigInt(32)));
      return { low, high };
    }
    __name(toLongBits, "toLongBits");
    exports2.toLongBits = toLongBits;
    function encodeAsLongBits(hrTime) {
      const nanos = hrTimeToNanos(hrTime);
      return toLongBits(nanos);
    }
    __name(encodeAsLongBits, "encodeAsLongBits");
    exports2.encodeAsLongBits = encodeAsLongBits;
    function encodeAsString(hrTime) {
      const nanos = hrTimeToNanos(hrTime);
      return nanos.toString();
    }
    __name(encodeAsString, "encodeAsString");
    exports2.encodeAsString = encodeAsString;
    var encodeTimestamp = typeof BigInt !== "undefined" ? encodeAsString : core_1.hrTimeToNanoseconds;
    function identity(value) {
      return value;
    }
    __name(identity, "identity");
    function optionalHexToBinary(str2) {
      if (str2 === void 0)
        return void 0;
      return (0, hex_to_binary_1.hexToBinary)(str2);
    }
    __name(optionalHexToBinary, "optionalHexToBinary");
    var DEFAULT_ENCODER = {
      encodeHrTime: encodeAsLongBits,
      encodeSpanContext: hex_to_binary_1.hexToBinary,
      encodeOptionalSpanContext: optionalHexToBinary
    };
    function getOtlpEncoder(options2) {
      if (options2 === void 0) {
        return DEFAULT_ENCODER;
      }
      const useLongBits = options2.useLongBits ?? true;
      const useHex = options2.useHex ?? false;
      return {
        encodeHrTime: useLongBits ? encodeAsLongBits : encodeTimestamp,
        encodeSpanContext: useHex ? identity : hex_to_binary_1.hexToBinary,
        encodeOptionalSpanContext: useHex ? identity : optionalHexToBinary
      };
    }
    __name(getOtlpEncoder, "getOtlpEncoder");
    exports2.getOtlpEncoder = getOtlpEncoder;
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/common/internal.js
var require_internal = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/common/internal.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.toAnyValue = exports2.toKeyValue = exports2.toAttributes = exports2.createInstrumentationScope = exports2.createResource = void 0;
    function createResource(resource) {
      return {
        attributes: toAttributes(resource.attributes),
        droppedAttributesCount: 0
      };
    }
    __name(createResource, "createResource");
    exports2.createResource = createResource;
    function createInstrumentationScope(scope) {
      return {
        name: scope.name,
        version: scope.version
      };
    }
    __name(createInstrumentationScope, "createInstrumentationScope");
    exports2.createInstrumentationScope = createInstrumentationScope;
    function toAttributes(attributes) {
      return Object.keys(attributes).map((key) => toKeyValue(key, attributes[key]));
    }
    __name(toAttributes, "toAttributes");
    exports2.toAttributes = toAttributes;
    function toKeyValue(key, value) {
      return {
        key,
        value: toAnyValue(value)
      };
    }
    __name(toKeyValue, "toKeyValue");
    exports2.toKeyValue = toKeyValue;
    function toAnyValue(value) {
      const t2 = typeof value;
      if (t2 === "string")
        return { stringValue: value };
      if (t2 === "number") {
        if (!Number.isInteger(value))
          return { doubleValue: value };
        return { intValue: value };
      }
      if (t2 === "boolean")
        return { boolValue: value };
      if (value instanceof Uint8Array)
        return { bytesValue: value };
      if (Array.isArray(value))
        return { arrayValue: { values: value.map(toAnyValue) } };
      if (t2 === "object" && value != null)
        return {
          kvlistValue: {
            values: Object.entries(value).map(([k, v]) => toKeyValue(k, v))
          }
        };
      return {};
    }
    __name(toAnyValue, "toAnyValue");
    exports2.toAnyValue = toAnyValue;
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/logs/internal.js
var require_internal2 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/logs/internal.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.toLogAttributes = exports2.createExportLogsServiceRequest = void 0;
    var utils_1 = require_utils5();
    var internal_1 = require_internal();
    function createExportLogsServiceRequest(logRecords, options2) {
      const encoder = (0, utils_1.getOtlpEncoder)(options2);
      return {
        resourceLogs: logRecordsToResourceLogs(logRecords, encoder)
      };
    }
    __name(createExportLogsServiceRequest, "createExportLogsServiceRequest");
    exports2.createExportLogsServiceRequest = createExportLogsServiceRequest;
    function createResourceMap(logRecords) {
      const resourceMap = /* @__PURE__ */ new Map();
      for (const record of logRecords) {
        const { resource, instrumentationScope: { name: name3, version: version2 = "", schemaUrl = "" } } = record;
        let ismMap = resourceMap.get(resource);
        if (!ismMap) {
          ismMap = /* @__PURE__ */ new Map();
          resourceMap.set(resource, ismMap);
        }
        const ismKey = `${name3}@${version2}:${schemaUrl}`;
        let records = ismMap.get(ismKey);
        if (!records) {
          records = [];
          ismMap.set(ismKey, records);
        }
        records.push(record);
      }
      return resourceMap;
    }
    __name(createResourceMap, "createResourceMap");
    function logRecordsToResourceLogs(logRecords, encoder) {
      const resourceMap = createResourceMap(logRecords);
      return Array.from(resourceMap, ([resource, ismMap]) => ({
        resource: (0, internal_1.createResource)(resource),
        scopeLogs: Array.from(ismMap, ([, scopeLogs]) => {
          return {
            scope: (0, internal_1.createInstrumentationScope)(scopeLogs[0].instrumentationScope),
            logRecords: scopeLogs.map((log) => toLogRecord(log, encoder)),
            schemaUrl: scopeLogs[0].instrumentationScope.schemaUrl
          };
        }),
        schemaUrl: void 0
      }));
    }
    __name(logRecordsToResourceLogs, "logRecordsToResourceLogs");
    function toLogRecord(log, encoder) {
      return {
        timeUnixNano: encoder.encodeHrTime(log.hrTime),
        observedTimeUnixNano: encoder.encodeHrTime(log.hrTimeObserved),
        severityNumber: toSeverityNumber(log.severityNumber),
        severityText: log.severityText,
        body: (0, internal_1.toAnyValue)(log.body),
        eventName: log.eventName,
        attributes: toLogAttributes(log.attributes),
        droppedAttributesCount: log.droppedAttributesCount,
        flags: log.spanContext?.traceFlags,
        traceId: encoder.encodeOptionalSpanContext(log.spanContext?.traceId),
        spanId: encoder.encodeOptionalSpanContext(log.spanContext?.spanId)
      };
    }
    __name(toLogRecord, "toLogRecord");
    function toSeverityNumber(severityNumber) {
      return severityNumber;
    }
    __name(toSeverityNumber, "toSeverityNumber");
    function toLogAttributes(attributes) {
      return Object.keys(attributes).map((key) => (0, internal_1.toKeyValue)(key, attributes[key]));
    }
    __name(toLogAttributes, "toLogAttributes");
    exports2.toLogAttributes = toLogAttributes;
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/logs.js
var require_logs2 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/logs.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ProtobufLogsSerializer = void 0;
    var root = require_root2();
    var internal_1 = require_internal2();
    var logsResponseType = root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse;
    var logsRequestType = root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest;
    exports2.ProtobufLogsSerializer = {
      serializeRequest: /* @__PURE__ */ __name((arg) => {
        const request4 = (0, internal_1.createExportLogsServiceRequest)(arg);
        return logsRequestType.encode(request4).finish();
      }, "serializeRequest"),
      deserializeResponse: /* @__PURE__ */ __name((arg) => {
        return logsResponseType.decode(arg);
      }, "deserializeResponse")
    };
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/index.js
var require_protobuf = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ProtobufLogsSerializer = void 0;
    var logs_1 = require_logs2();
    Object.defineProperty(exports2, "ProtobufLogsSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return logs_1.ProtobufLogsSerializer;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationTemporality.js
var require_AggregationTemporality = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationTemporality.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AggregationTemporality = void 0;
    var AggregationTemporality2;
    (function(AggregationTemporality3) {
      AggregationTemporality3[AggregationTemporality3["DELTA"] = 0] = "DELTA";
      AggregationTemporality3[AggregationTemporality3["CUMULATIVE"] = 1] = "CUMULATIVE";
    })(AggregationTemporality2 = exports2.AggregationTemporality || (exports2.AggregationTemporality = {}));
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricData.js
var require_MetricData = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricData.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DataPointType = exports2.InstrumentType = void 0;
    var InstrumentType;
    (function(InstrumentType2) {
      InstrumentType2["COUNTER"] = "COUNTER";
      InstrumentType2["GAUGE"] = "GAUGE";
      InstrumentType2["HISTOGRAM"] = "HISTOGRAM";
      InstrumentType2["UP_DOWN_COUNTER"] = "UP_DOWN_COUNTER";
      InstrumentType2["OBSERVABLE_COUNTER"] = "OBSERVABLE_COUNTER";
      InstrumentType2["OBSERVABLE_GAUGE"] = "OBSERVABLE_GAUGE";
      InstrumentType2["OBSERVABLE_UP_DOWN_COUNTER"] = "OBSERVABLE_UP_DOWN_COUNTER";
    })(InstrumentType = exports2.InstrumentType || (exports2.InstrumentType = {}));
    var DataPointType;
    (function(DataPointType2) {
      DataPointType2[DataPointType2["HISTOGRAM"] = 0] = "HISTOGRAM";
      DataPointType2[DataPointType2["EXPONENTIAL_HISTOGRAM"] = 1] = "EXPONENTIAL_HISTOGRAM";
      DataPointType2[DataPointType2["GAUGE"] = 2] = "GAUGE";
      DataPointType2[DataPointType2["SUM"] = 3] = "SUM";
    })(DataPointType = exports2.DataPointType || (exports2.DataPointType = {}));
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/utils.js
var require_utils6 = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.equalsCaseInsensitive = exports2.binarySearchUB = exports2.setEquals = exports2.FlatMap = exports2.isPromiseAllSettledRejectionResult = exports2.PromiseAllSettled = exports2.callWithTimeout = exports2.TimeoutError = exports2.instrumentationScopeId = exports2.hashAttributes = exports2.isNotNullish = void 0;
    function isNotNullish(item) {
      return item !== void 0 && item !== null;
    }
    __name(isNotNullish, "isNotNullish");
    exports2.isNotNullish = isNotNullish;
    function hashAttributes(attributes) {
      let keys = Object.keys(attributes);
      if (keys.length === 0)
        return "";
      keys = keys.sort();
      return JSON.stringify(keys.map((key) => [key, attributes[key]]));
    }
    __name(hashAttributes, "hashAttributes");
    exports2.hashAttributes = hashAttributes;
    function instrumentationScopeId(instrumentationScope) {
      return `${instrumentationScope.name}:${instrumentationScope.version ?? ""}:${instrumentationScope.schemaUrl ?? ""}`;
    }
    __name(instrumentationScopeId, "instrumentationScopeId");
    exports2.instrumentationScopeId = instrumentationScopeId;
    var TimeoutError2 = class _TimeoutError extends Error {
      static {
        __name(this, "TimeoutError");
      }
      constructor(message) {
        super(message);
        Object.setPrototypeOf(this, _TimeoutError.prototype);
      }
    };
    exports2.TimeoutError = TimeoutError2;
    function callWithTimeout(promise, timeout2) {
      let timeoutHandle;
      const timeoutPromise = new Promise(/* @__PURE__ */ __name(function timeoutFunction(_resolve, reject) {
        timeoutHandle = setTimeout(/* @__PURE__ */ __name(function timeoutHandler() {
          reject(new TimeoutError2("Operation timed out."));
        }, "timeoutHandler"), timeout2);
      }, "timeoutFunction"));
      return Promise.race([promise, timeoutPromise]).then((result) => {
        clearTimeout(timeoutHandle);
        return result;
      }, (reason) => {
        clearTimeout(timeoutHandle);
        throw reason;
      });
    }
    __name(callWithTimeout, "callWithTimeout");
    exports2.callWithTimeout = callWithTimeout;
    async function PromiseAllSettled(promises6) {
      return Promise.all(promises6.map(async (p) => {
        try {
          const ret = await p;
          return {
            status: "fulfilled",
            value: ret
          };
        } catch (e2) {
          return {
            status: "rejected",
            reason: e2
          };
        }
      }));
    }
    __name(PromiseAllSettled, "PromiseAllSettled");
    exports2.PromiseAllSettled = PromiseAllSettled;
    function isPromiseAllSettledRejectionResult(it) {
      return it.status === "rejected";
    }
    __name(isPromiseAllSettledRejectionResult, "isPromiseAllSettledRejectionResult");
    exports2.isPromiseAllSettledRejectionResult = isPromiseAllSettledRejectionResult;
    function FlatMap(arr, fn) {
      const result = [];
      arr.forEach((it) => {
        result.push(...fn(it));
      });
      return result;
    }
    __name(FlatMap, "FlatMap");
    exports2.FlatMap = FlatMap;
    function setEquals(lhs, rhs) {
      if (lhs.size !== rhs.size) {
        return false;
      }
      for (const item of lhs) {
        if (!rhs.has(item)) {
          return false;
        }
      }
      return true;
    }
    __name(setEquals, "setEquals");
    exports2.setEquals = setEquals;
    function binarySearchUB(arr, value) {
      let lo = 0;
      let hi = arr.length - 1;
      let ret = arr.length;
      while (hi >= lo) {
        const mid = lo + Math.trunc((hi - lo) / 2);
        if (arr[mid] < value) {
          lo = mid + 1;
        } else {
          ret = mid;
          hi = mid - 1;
        }
      }
      return ret;
    }
    __name(binarySearchUB, "binarySearchUB");
    exports2.binarySearchUB = binarySearchUB;
    function equalsCaseInsensitive(lhs, rhs) {
      return lhs.toLowerCase() === rhs.toLowerCase();
    }
    __name(equalsCaseInsensitive, "equalsCaseInsensitive");
    exports2.equalsCaseInsensitive = equalsCaseInsensitive;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/types.js
var require_types4 = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/types.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AggregatorKind = void 0;
    var AggregatorKind;
    (function(AggregatorKind2) {
      AggregatorKind2[AggregatorKind2["DROP"] = 0] = "DROP";
      AggregatorKind2[AggregatorKind2["SUM"] = 1] = "SUM";
      AggregatorKind2[AggregatorKind2["LAST_VALUE"] = 2] = "LAST_VALUE";
      AggregatorKind2[AggregatorKind2["HISTOGRAM"] = 3] = "HISTOGRAM";
      AggregatorKind2[AggregatorKind2["EXPONENTIAL_HISTOGRAM"] = 4] = "EXPONENTIAL_HISTOGRAM";
    })(AggregatorKind = exports2.AggregatorKind || (exports2.AggregatorKind = {}));
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Drop.js
var require_Drop = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Drop.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DropAggregator = void 0;
    var types_1 = require_types4();
    var DropAggregator = class {
      static {
        __name(this, "DropAggregator");
      }
      kind = types_1.AggregatorKind.DROP;
      createAccumulation() {
        return void 0;
      }
      merge(_previous, _delta) {
        return void 0;
      }
      diff(_previous, _current) {
        return void 0;
      }
      toMetricData(_descriptor, _aggregationTemporality, _accumulationByAttributes, _endTime) {
        return void 0;
      }
    };
    exports2.DropAggregator = DropAggregator;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Histogram.js
var require_Histogram = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Histogram.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.HistogramAggregator = exports2.HistogramAccumulation = void 0;
    var types_1 = require_types4();
    var MetricData_1 = require_MetricData();
    var utils_1 = require_utils6();
    function createNewEmptyCheckpoint(boundaries) {
      const counts = boundaries.map(() => 0);
      counts.push(0);
      return {
        buckets: {
          boundaries,
          counts
        },
        sum: 0,
        count: 0,
        hasMinMax: false,
        min: Infinity,
        max: -Infinity
      };
    }
    __name(createNewEmptyCheckpoint, "createNewEmptyCheckpoint");
    var HistogramAccumulation = class {
      static {
        __name(this, "HistogramAccumulation");
      }
      startTime;
      _boundaries;
      _recordMinMax;
      _current;
      constructor(startTime, _boundaries, _recordMinMax = true, _current = createNewEmptyCheckpoint(_boundaries)) {
        this.startTime = startTime;
        this._boundaries = _boundaries;
        this._recordMinMax = _recordMinMax;
        this._current = _current;
      }
      record(value) {
        if (Number.isNaN(value)) {
          return;
        }
        this._current.count += 1;
        this._current.sum += value;
        if (this._recordMinMax) {
          this._current.min = Math.min(value, this._current.min);
          this._current.max = Math.max(value, this._current.max);
          this._current.hasMinMax = true;
        }
        const idx = (0, utils_1.binarySearchUB)(this._boundaries, value);
        this._current.buckets.counts[idx] += 1;
      }
      setStartTime(startTime) {
        this.startTime = startTime;
      }
      toPointValue() {
        return this._current;
      }
    };
    exports2.HistogramAccumulation = HistogramAccumulation;
    var HistogramAggregator = class {
      static {
        __name(this, "HistogramAggregator");
      }
      _boundaries;
      _recordMinMax;
      kind = types_1.AggregatorKind.HISTOGRAM;
      /**
       * @param _boundaries sorted upper bounds of recorded values.
       * @param _recordMinMax If set to true, min and max will be recorded. Otherwise, min and max will not be recorded.
       */
      constructor(_boundaries, _recordMinMax) {
        this._boundaries = _boundaries;
        this._recordMinMax = _recordMinMax;
      }
      createAccumulation(startTime) {
        return new HistogramAccumulation(startTime, this._boundaries, this._recordMinMax);
      }
      /**
       * Return the result of the merge of two histogram accumulations. As long as one Aggregator
       * instance produces all Accumulations with constant boundaries we don't need to worry about
       * merging accumulations with different boundaries.
       */
      merge(previous, delta) {
        const previousValue = previous.toPointValue();
        const deltaValue = delta.toPointValue();
        const previousCounts = previousValue.buckets.counts;
        const deltaCounts = deltaValue.buckets.counts;
        const mergedCounts = new Array(previousCounts.length);
        for (let idx = 0; idx < previousCounts.length; idx++) {
          mergedCounts[idx] = previousCounts[idx] + deltaCounts[idx];
        }
        let min = Infinity;
        let max = -Infinity;
        if (this._recordMinMax) {
          if (previousValue.hasMinMax && deltaValue.hasMinMax) {
            min = Math.min(previousValue.min, deltaValue.min);
            max = Math.max(previousValue.max, deltaValue.max);
          } else if (previousValue.hasMinMax) {
            min = previousValue.min;
            max = previousValue.max;
          } else if (deltaValue.hasMinMax) {
            min = deltaValue.min;
            max = deltaValue.max;
          }
        }
        return new HistogramAccumulation(previous.startTime, previousValue.buckets.boundaries, this._recordMinMax, {
          buckets: {
            boundaries: previousValue.buckets.boundaries,
            counts: mergedCounts
          },
          count: previousValue.count + deltaValue.count,
          sum: previousValue.sum + deltaValue.sum,
          hasMinMax: this._recordMinMax && (previousValue.hasMinMax || deltaValue.hasMinMax),
          min,
          max
        });
      }
      /**
       * Returns a new DELTA aggregation by comparing two cumulative measurements.
       */
      diff(previous, current) {
        const previousValue = previous.toPointValue();
        const currentValue = current.toPointValue();
        const previousCounts = previousValue.buckets.counts;
        const currentCounts = currentValue.buckets.counts;
        const diffedCounts = new Array(previousCounts.length);
        for (let idx = 0; idx < previousCounts.length; idx++) {
          diffedCounts[idx] = currentCounts[idx] - previousCounts[idx];
        }
        return new HistogramAccumulation(current.startTime, previousValue.buckets.boundaries, this._recordMinMax, {
          buckets: {
            boundaries: previousValue.buckets.boundaries,
            counts: diffedCounts
          },
          count: currentValue.count - previousValue.count,
          sum: currentValue.sum - previousValue.sum,
          hasMinMax: false,
          min: Infinity,
          max: -Infinity
        });
      }
      toMetricData(descriptor2, aggregationTemporality, accumulationByAttributes, endTime) {
        return {
          descriptor: descriptor2,
          aggregationTemporality,
          dataPointType: MetricData_1.DataPointType.HISTOGRAM,
          dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => {
            const pointValue = accumulation.toPointValue();
            const allowsNegativeValues = descriptor2.type === MetricData_1.InstrumentType.GAUGE || descriptor2.type === MetricData_1.InstrumentType.UP_DOWN_COUNTER || descriptor2.type === MetricData_1.InstrumentType.OBSERVABLE_GAUGE || descriptor2.type === MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;
            return {
              attributes,
              startTime: accumulation.startTime,
              endTime,
              value: {
                min: pointValue.hasMinMax ? pointValue.min : void 0,
                max: pointValue.hasMinMax ? pointValue.max : void 0,
                sum: !allowsNegativeValues ? pointValue.sum : void 0,
                buckets: pointValue.buckets,
                count: pointValue.count
              }
            };
          })
        };
      }
    };
    exports2.HistogramAggregator = HistogramAggregator;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/Buckets.js
var require_Buckets = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/Buckets.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Buckets = void 0;
    var Buckets = class _Buckets {
      static {
        __name(this, "Buckets");
      }
      backing;
      indexBase;
      indexStart;
      indexEnd;
      /**
       * The term index refers to the number of the exponential histogram bucket
       * used to determine its boundaries. The lower boundary of a bucket is
       * determined by base ** index and the upper boundary of a bucket is
       * determined by base ** (index + 1). index values are signed to account
       * for values less than or equal to 1.
       *
       * indexBase is the index of the 0th position in the
       * backing array, i.e., backing[0] is the count
       * in the bucket with index `indexBase`.
       *
       * indexStart is the smallest index value represented
       * in the backing array.
       *
       * indexEnd is the largest index value represented in
       * the backing array.
       */
      constructor(backing = new BucketsBacking(), indexBase = 0, indexStart = 0, indexEnd = 0) {
        this.backing = backing;
        this.indexBase = indexBase;
        this.indexStart = indexStart;
        this.indexEnd = indexEnd;
      }
      /**
       * Offset is the bucket index of the smallest entry in the counts array
       * @returns {number}
       */
      get offset() {
        return this.indexStart;
      }
      /**
       * Buckets is a view into the backing array.
       * @returns {number}
       */
      get length() {
        if (this.backing.length === 0) {
          return 0;
        }
        if (this.indexEnd === this.indexStart && this.at(0) === 0) {
          return 0;
        }
        return this.indexEnd - this.indexStart + 1;
      }
      /**
       * An array of counts, where count[i] carries the count
       * of the bucket at index (offset+i).  count[i] is the count of
       * values greater than base^(offset+i) and less than or equal to
       * base^(offset+i+1).
       * @returns {number} The logical counts based on the backing array
       */
      counts() {
        return Array.from({ length: this.length }, (_, i) => this.at(i));
      }
      /**
       * At returns the count of the bucket at a position in the logical
       * array of counts.
       * @param position
       * @returns {number}
       */
      at(position) {
        const bias = this.indexBase - this.indexStart;
        if (position < bias) {
          position += this.backing.length;
        }
        position -= bias;
        return this.backing.countAt(position);
      }
      /**
       * incrementBucket increments the backing array index by `increment`
       * @param bucketIndex
       * @param increment
       */
      incrementBucket(bucketIndex, increment2) {
        this.backing.increment(bucketIndex, increment2);
      }
      /**
       * decrementBucket decrements the backing array index by `decrement`
       * if decrement is greater than the current value, it's set to 0.
       * @param bucketIndex
       * @param decrement
       */
      decrementBucket(bucketIndex, decrement) {
        this.backing.decrement(bucketIndex, decrement);
      }
      /**
       * trim removes leading and / or trailing zero buckets (which can occur
       * after diffing two histos) and rotates the backing array so that the
       * smallest non-zero index is in the 0th position of the backing array
       */
      trim() {
        for (let i = 0; i < this.length; i++) {
          if (this.at(i) !== 0) {
            this.indexStart += i;
            break;
          } else if (i === this.length - 1) {
            this.indexStart = this.indexEnd = this.indexBase = 0;
            return;
          }
        }
        for (let i = this.length - 1; i >= 0; i--) {
          if (this.at(i) !== 0) {
            this.indexEnd -= this.length - i - 1;
            break;
          }
        }
        this._rotate();
      }
      /**
       * downscale first rotates, then collapses 2**`by`-to-1 buckets.
       * @param by
       */
      downscale(by) {
        this._rotate();
        const size = 1 + this.indexEnd - this.indexStart;
        const each = 1 << by;
        let inpos = 0;
        let outpos = 0;
        for (let pos2 = this.indexStart; pos2 <= this.indexEnd; ) {
          let mod2 = pos2 % each;
          if (mod2 < 0) {
            mod2 += each;
          }
          for (let i = mod2; i < each && inpos < size; i++) {
            this._relocateBucket(outpos, inpos);
            inpos++;
            pos2++;
          }
          outpos++;
        }
        this.indexStart >>= by;
        this.indexEnd >>= by;
        this.indexBase = this.indexStart;
      }
      /**
       * Clone returns a deep copy of Buckets
       * @returns {Buckets}
       */
      clone() {
        return new _Buckets(this.backing.clone(), this.indexBase, this.indexStart, this.indexEnd);
      }
      /**
       * _rotate shifts the backing array contents so that indexStart ==
       * indexBase to simplify the downscale logic.
       */
      _rotate() {
        const bias = this.indexBase - this.indexStart;
        if (bias === 0) {
          return;
        } else if (bias > 0) {
          this.backing.reverse(0, this.backing.length);
          this.backing.reverse(0, bias);
          this.backing.reverse(bias, this.backing.length);
        } else {
          this.backing.reverse(0, this.backing.length);
          this.backing.reverse(0, this.backing.length + bias);
        }
        this.indexBase = this.indexStart;
      }
      /**
       * _relocateBucket adds the count in counts[src] to counts[dest] and
       * resets count[src] to zero.
       */
      _relocateBucket(dest, src) {
        if (dest === src) {
          return;
        }
        this.incrementBucket(dest, this.backing.emptyBucket(src));
      }
    };
    exports2.Buckets = Buckets;
    var BucketsBacking = class _BucketsBacking {
      static {
        __name(this, "BucketsBacking");
      }
      _counts;
      constructor(_counts = [0]) {
        this._counts = _counts;
      }
      /**
       * length returns the physical size of the backing array, which
       * is >= buckets.length()
       */
      get length() {
        return this._counts.length;
      }
      /**
       * countAt returns the count in a specific bucket
       */
      countAt(pos2) {
        return this._counts[pos2];
      }
      /**
       * growTo grows a backing array and copies old entries
       * into their correct new positions.
       */
      growTo(newSize, oldPositiveLimit, newPositiveLimit) {
        const tmp = new Array(newSize).fill(0);
        tmp.splice(newPositiveLimit, this._counts.length - oldPositiveLimit, ...this._counts.slice(oldPositiveLimit));
        tmp.splice(0, oldPositiveLimit, ...this._counts.slice(0, oldPositiveLimit));
        this._counts = tmp;
      }
      /**
       * reverse the items in the backing array in the range [from, limit).
       */
      reverse(from, limit2) {
        const num = Math.floor((from + limit2) / 2) - from;
        for (let i = 0; i < num; i++) {
          const tmp = this._counts[from + i];
          this._counts[from + i] = this._counts[limit2 - i - 1];
          this._counts[limit2 - i - 1] = tmp;
        }
      }
      /**
       * emptyBucket empties the count from a bucket, for
       * moving into another.
       */
      emptyBucket(src) {
        const tmp = this._counts[src];
        this._counts[src] = 0;
        return tmp;
      }
      /**
       * increments a bucket by `increment`
       */
      increment(bucketIndex, increment2) {
        this._counts[bucketIndex] += increment2;
      }
      /**
       * decrements a bucket by `decrement`
       */
      decrement(bucketIndex, decrement) {
        if (this._counts[bucketIndex] >= decrement) {
          this._counts[bucketIndex] -= decrement;
        } else {
          this._counts[bucketIndex] = 0;
        }
      }
      /**
       * clone returns a deep copy of BucketsBacking
       */
      clone() {
        return new _BucketsBacking([...this._counts]);
      }
    };
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ieee754.js
var require_ieee754 = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ieee754.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getSignificand = exports2.getNormalBase2 = exports2.MIN_VALUE = exports2.MAX_NORMAL_EXPONENT = exports2.MIN_NORMAL_EXPONENT = exports2.SIGNIFICAND_WIDTH = void 0;
    exports2.SIGNIFICAND_WIDTH = 52;
    var EXPONENT_MASK = 2146435072;
    var SIGNIFICAND_MASK = 1048575;
    var EXPONENT_BIAS = 1023;
    exports2.MIN_NORMAL_EXPONENT = -EXPONENT_BIAS + 1;
    exports2.MAX_NORMAL_EXPONENT = EXPONENT_BIAS;
    exports2.MIN_VALUE = Math.pow(2, -1022);
    function getNormalBase2(value) {
      const dv = new DataView(new ArrayBuffer(8));
      dv.setFloat64(0, value);
      const hiBits = dv.getUint32(0);
      const expBits = (hiBits & EXPONENT_MASK) >> 20;
      return expBits - EXPONENT_BIAS;
    }
    __name(getNormalBase2, "getNormalBase2");
    exports2.getNormalBase2 = getNormalBase2;
    function getSignificand(value) {
      const dv = new DataView(new ArrayBuffer(8));
      dv.setFloat64(0, value);
      const hiBits = dv.getUint32(0);
      const loBits = dv.getUint32(4);
      const significandHiBits = (hiBits & SIGNIFICAND_MASK) * Math.pow(2, 32);
      return significandHiBits + loBits;
    }
    __name(getSignificand, "getSignificand");
    exports2.getSignificand = getSignificand;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/util.js
var require_util13 = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/util.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.nextGreaterSquare = exports2.ldexp = void 0;
    function ldexp(frac3, exp) {
      if (frac3 === 0 || frac3 === Number.POSITIVE_INFINITY || frac3 === Number.NEGATIVE_INFINITY || Number.isNaN(frac3)) {
        return frac3;
      }
      return frac3 * Math.pow(2, exp);
    }
    __name(ldexp, "ldexp");
    exports2.ldexp = ldexp;
    function nextGreaterSquare(v) {
      v--;
      v |= v >> 1;
      v |= v >> 2;
      v |= v >> 4;
      v |= v >> 8;
      v |= v >> 16;
      v++;
      return v;
    }
    __name(nextGreaterSquare, "nextGreaterSquare");
    exports2.nextGreaterSquare = nextGreaterSquare;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/types.js
var require_types5 = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/types.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MappingError = void 0;
    var MappingError = class extends Error {
      static {
        __name(this, "MappingError");
      }
    };
    exports2.MappingError = MappingError;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ExponentMapping.js
var require_ExponentMapping = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ExponentMapping.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ExponentMapping = void 0;
    var ieee754 = require_ieee754();
    var util4 = require_util13();
    var types_1 = require_types5();
    var ExponentMapping = class {
      static {
        __name(this, "ExponentMapping");
      }
      _shift;
      constructor(scale) {
        this._shift = -scale;
      }
      /**
       * Maps positive floating point values to indexes corresponding to scale
       * @param value
       * @returns {number} index for provided value at the current scale
       */
      mapToIndex(value) {
        if (value < ieee754.MIN_VALUE) {
          return this._minNormalLowerBoundaryIndex();
        }
        const exp = ieee754.getNormalBase2(value);
        const correction = this._rightShift(ieee754.getSignificand(value) - 1, ieee754.SIGNIFICAND_WIDTH);
        return exp + correction >> this._shift;
      }
      /**
       * Returns the lower bucket boundary for the given index for scale
       *
       * @param index
       * @returns {number}
       */
      lowerBoundary(index) {
        const minIndex = this._minNormalLowerBoundaryIndex();
        if (index < minIndex) {
          throw new types_1.MappingError(`underflow: ${index} is < minimum lower boundary: ${minIndex}`);
        }
        const maxIndex = this._maxNormalLowerBoundaryIndex();
        if (index > maxIndex) {
          throw new types_1.MappingError(`overflow: ${index} is > maximum lower boundary: ${maxIndex}`);
        }
        return util4.ldexp(1, index << this._shift);
      }
      /**
       * The scale used by this mapping
       * @returns {number}
       */
      get scale() {
        if (this._shift === 0) {
          return 0;
        }
        return -this._shift;
      }
      _minNormalLowerBoundaryIndex() {
        let index = ieee754.MIN_NORMAL_EXPONENT >> this._shift;
        if (this._shift < 2) {
          index--;
        }
        return index;
      }
      _maxNormalLowerBoundaryIndex() {
        return ieee754.MAX_NORMAL_EXPONENT >> this._shift;
      }
      _rightShift(value, shift) {
        return Math.floor(value * Math.pow(2, -shift));
      }
    };
    exports2.ExponentMapping = ExponentMapping;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/LogarithmMapping.js
var require_LogarithmMapping = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/LogarithmMapping.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LogarithmMapping = void 0;
    var ieee754 = require_ieee754();
    var util4 = require_util13();
    var types_1 = require_types5();
    var LogarithmMapping = class {
      static {
        __name(this, "LogarithmMapping");
      }
      _scale;
      _scaleFactor;
      _inverseFactor;
      constructor(scale) {
        this._scale = scale;
        this._scaleFactor = util4.ldexp(Math.LOG2E, scale);
        this._inverseFactor = util4.ldexp(Math.LN2, -scale);
      }
      /**
       * Maps positive floating point values to indexes corresponding to scale
       * @param value
       * @returns {number} index for provided value at the current scale
       */
      mapToIndex(value) {
        if (value <= ieee754.MIN_VALUE) {
          return this._minNormalLowerBoundaryIndex() - 1;
        }
        if (ieee754.getSignificand(value) === 0) {
          const exp = ieee754.getNormalBase2(value);
          return (exp << this._scale) - 1;
        }
        const index = Math.floor(Math.log(value) * this._scaleFactor);
        const maxIndex = this._maxNormalLowerBoundaryIndex();
        if (index >= maxIndex) {
          return maxIndex;
        }
        return index;
      }
      /**
       * Returns the lower bucket boundary for the given index for scale
       *
       * @param index
       * @returns {number}
       */
      lowerBoundary(index) {
        const maxIndex = this._maxNormalLowerBoundaryIndex();
        if (index >= maxIndex) {
          if (index === maxIndex) {
            return 2 * Math.exp((index - (1 << this._scale)) / this._scaleFactor);
          }
          throw new types_1.MappingError(`overflow: ${index} is > maximum lower boundary: ${maxIndex}`);
        }
        const minIndex = this._minNormalLowerBoundaryIndex();
        if (index <= minIndex) {
          if (index === minIndex) {
            return ieee754.MIN_VALUE;
          } else if (index === minIndex - 1) {
            return Math.exp((index + (1 << this._scale)) / this._scaleFactor) / 2;
          }
          throw new types_1.MappingError(`overflow: ${index} is < minimum lower boundary: ${minIndex}`);
        }
        return Math.exp(index * this._inverseFactor);
      }
      /**
       * The scale used by this mapping
       * @returns {number}
       */
      get scale() {
        return this._scale;
      }
      _minNormalLowerBoundaryIndex() {
        return ieee754.MIN_NORMAL_EXPONENT << this._scale;
      }
      _maxNormalLowerBoundaryIndex() {
        return (ieee754.MAX_NORMAL_EXPONENT + 1 << this._scale) - 1;
      }
    };
    exports2.LogarithmMapping = LogarithmMapping;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/getMapping.js
var require_getMapping = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/getMapping.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getMapping = void 0;
    var ExponentMapping_1 = require_ExponentMapping();
    var LogarithmMapping_1 = require_LogarithmMapping();
    var types_1 = require_types5();
    var MIN_SCALE = -10;
    var MAX_SCALE = 20;
    var PREBUILT_MAPPINGS = Array.from({ length: 31 }, (_, i) => {
      if (i > 10) {
        return new LogarithmMapping_1.LogarithmMapping(i - 10);
      }
      return new ExponentMapping_1.ExponentMapping(i - 10);
    });
    function getMapping(scale) {
      if (scale > MAX_SCALE || scale < MIN_SCALE) {
        throw new types_1.MappingError(`expected scale >= ${MIN_SCALE} && <= ${MAX_SCALE}, got: ${scale}`);
      }
      return PREBUILT_MAPPINGS[scale + 10];
    }
    __name(getMapping, "getMapping");
    exports2.getMapping = getMapping;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/ExponentialHistogram.js
var require_ExponentialHistogram = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/ExponentialHistogram.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ExponentialHistogramAggregator = exports2.ExponentialHistogramAccumulation = void 0;
    var types_1 = require_types4();
    var MetricData_1 = require_MetricData();
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var Buckets_1 = require_Buckets();
    var getMapping_1 = require_getMapping();
    var util_1 = require_util13();
    var HighLow = class _HighLow {
      static {
        __name(this, "HighLow");
      }
      low;
      high;
      static combine(h1, h2) {
        return new _HighLow(Math.min(h1.low, h2.low), Math.max(h1.high, h2.high));
      }
      constructor(low, high) {
        this.low = low;
        this.high = high;
      }
    };
    var MAX_SCALE = 20;
    var DEFAULT_MAX_SIZE = 160;
    var MIN_MAX_SIZE = 2;
    var ExponentialHistogramAccumulation = class _ExponentialHistogramAccumulation {
      static {
        __name(this, "ExponentialHistogramAccumulation");
      }
      startTime;
      _maxSize;
      _recordMinMax;
      _sum;
      _count;
      _zeroCount;
      _min;
      _max;
      _positive;
      _negative;
      _mapping;
      constructor(startTime = startTime, _maxSize = DEFAULT_MAX_SIZE, _recordMinMax = true, _sum = 0, _count = 0, _zeroCount = 0, _min = Number.POSITIVE_INFINITY, _max = Number.NEGATIVE_INFINITY, _positive = new Buckets_1.Buckets(), _negative = new Buckets_1.Buckets(), _mapping = (0, getMapping_1.getMapping)(MAX_SCALE)) {
        this.startTime = startTime;
        this._maxSize = _maxSize;
        this._recordMinMax = _recordMinMax;
        this._sum = _sum;
        this._count = _count;
        this._zeroCount = _zeroCount;
        this._min = _min;
        this._max = _max;
        this._positive = _positive;
        this._negative = _negative;
        this._mapping = _mapping;
        if (this._maxSize < MIN_MAX_SIZE) {
          api_1.diag.warn(`Exponential Histogram Max Size set to ${this._maxSize},                 changing to the minimum size of: ${MIN_MAX_SIZE}`);
          this._maxSize = MIN_MAX_SIZE;
        }
      }
      /**
       * record updates a histogram with a single count
       * @param {Number} value
       */
      record(value) {
        this.updateByIncrement(value, 1);
      }
      /**
       * Sets the start time for this accumulation
       * @param {HrTime} startTime
       */
      setStartTime(startTime) {
        this.startTime = startTime;
      }
      /**
       * Returns the datapoint representation of this accumulation
       * @param {HrTime} startTime
       */
      toPointValue() {
        return {
          hasMinMax: this._recordMinMax,
          min: this.min,
          max: this.max,
          sum: this.sum,
          positive: {
            offset: this.positive.offset,
            bucketCounts: this.positive.counts()
          },
          negative: {
            offset: this.negative.offset,
            bucketCounts: this.negative.counts()
          },
          count: this.count,
          scale: this.scale,
          zeroCount: this.zeroCount
        };
      }
      /**
       * @returns {Number} The sum of values recorded by this accumulation
       */
      get sum() {
        return this._sum;
      }
      /**
       * @returns {Number} The minimum value recorded by this accumulation
       */
      get min() {
        return this._min;
      }
      /**
       * @returns {Number} The maximum value recorded by this accumulation
       */
      get max() {
        return this._max;
      }
      /**
       * @returns {Number} The count of values recorded by this accumulation
       */
      get count() {
        return this._count;
      }
      /**
       * @returns {Number} The number of 0 values recorded by this accumulation
       */
      get zeroCount() {
        return this._zeroCount;
      }
      /**
       * @returns {Number} The scale used by this accumulation
       */
      get scale() {
        if (this._count === this._zeroCount) {
          return 0;
        }
        return this._mapping.scale;
      }
      /**
       * positive holds the positive values
       * @returns {Buckets}
       */
      get positive() {
        return this._positive;
      }
      /**
       * negative holds the negative values by their absolute value
       * @returns {Buckets}
       */
      get negative() {
        return this._negative;
      }
      /**
       * updateByIncr supports updating a histogram with a non-negative
       * increment.
       * @param value
       * @param increment
       */
      updateByIncrement(value, increment2) {
        if (Number.isNaN(value)) {
          return;
        }
        if (value > this._max) {
          this._max = value;
        }
        if (value < this._min) {
          this._min = value;
        }
        this._count += increment2;
        if (value === 0) {
          this._zeroCount += increment2;
          return;
        }
        this._sum += value * increment2;
        if (value > 0) {
          this._updateBuckets(this._positive, value, increment2);
        } else {
          this._updateBuckets(this._negative, -value, increment2);
        }
      }
      /**
       * merge combines data from previous value into self
       * @param {ExponentialHistogramAccumulation} previous
       */
      merge(previous) {
        if (this._count === 0) {
          this._min = previous.min;
          this._max = previous.max;
        } else if (previous.count !== 0) {
          if (previous.min < this.min) {
            this._min = previous.min;
          }
          if (previous.max > this.max) {
            this._max = previous.max;
          }
        }
        this.startTime = previous.startTime;
        this._sum += previous.sum;
        this._count += previous.count;
        this._zeroCount += previous.zeroCount;
        const minScale = this._minScale(previous);
        this._downscale(this.scale - minScale);
        this._mergeBuckets(this.positive, previous, previous.positive, minScale);
        this._mergeBuckets(this.negative, previous, previous.negative, minScale);
      }
      /**
       * diff subtracts other from self
       * @param {ExponentialHistogramAccumulation} other
       */
      diff(other2) {
        this._min = Infinity;
        this._max = -Infinity;
        this._sum -= other2.sum;
        this._count -= other2.count;
        this._zeroCount -= other2.zeroCount;
        const minScale = this._minScale(other2);
        this._downscale(this.scale - minScale);
        this._diffBuckets(this.positive, other2, other2.positive, minScale);
        this._diffBuckets(this.negative, other2, other2.negative, minScale);
      }
      /**
       * clone returns a deep copy of self
       * @returns {ExponentialHistogramAccumulation}
       */
      clone() {
        return new _ExponentialHistogramAccumulation(this.startTime, this._maxSize, this._recordMinMax, this._sum, this._count, this._zeroCount, this._min, this._max, this.positive.clone(), this.negative.clone(), this._mapping);
      }
      /**
       * _updateBuckets maps the incoming value to a bucket index for the current
       * scale. If the bucket index is outside of the range of the backing array,
       * it will rescale the backing array and update the mapping for the new scale.
       */
      _updateBuckets(buckets, value, increment2) {
        let index = this._mapping.mapToIndex(value);
        let rescalingNeeded = false;
        let high = 0;
        let low = 0;
        if (buckets.length === 0) {
          buckets.indexStart = index;
          buckets.indexEnd = buckets.indexStart;
          buckets.indexBase = buckets.indexStart;
        } else if (index < buckets.indexStart && buckets.indexEnd - index >= this._maxSize) {
          rescalingNeeded = true;
          low = index;
          high = buckets.indexEnd;
        } else if (index > buckets.indexEnd && index - buckets.indexStart >= this._maxSize) {
          rescalingNeeded = true;
          low = buckets.indexStart;
          high = index;
        }
        if (rescalingNeeded) {
          const change = this._changeScale(high, low);
          this._downscale(change);
          index = this._mapping.mapToIndex(value);
        }
        this._incrementIndexBy(buckets, index, increment2);
      }
      /**
       * _incrementIndexBy increments the count of the bucket specified by `index`.
       * If the index is outside of the range [buckets.indexStart, buckets.indexEnd]
       * the boundaries of the backing array will be adjusted and more buckets will
       * be added if needed.
       */
      _incrementIndexBy(buckets, index, increment2) {
        if (increment2 === 0) {
          return;
        }
        if (buckets.length === 0) {
          buckets.indexStart = buckets.indexEnd = buckets.indexBase = index;
        }
        if (index < buckets.indexStart) {
          const span = buckets.indexEnd - index;
          if (span >= buckets.backing.length) {
            this._grow(buckets, span + 1);
          }
          buckets.indexStart = index;
        } else if (index > buckets.indexEnd) {
          const span = index - buckets.indexStart;
          if (span >= buckets.backing.length) {
            this._grow(buckets, span + 1);
          }
          buckets.indexEnd = index;
        }
        let bucketIndex = index - buckets.indexBase;
        if (bucketIndex < 0) {
          bucketIndex += buckets.backing.length;
        }
        buckets.incrementBucket(bucketIndex, increment2);
      }
      /**
       * grow resizes the backing array by doubling in size up to maxSize.
       * This extends the array with a bunch of zeros and copies the
       * existing counts to the same position.
       */
      _grow(buckets, needed) {
        const size = buckets.backing.length;
        const bias = buckets.indexBase - buckets.indexStart;
        const oldPositiveLimit = size - bias;
        let newSize = (0, util_1.nextGreaterSquare)(needed);
        if (newSize > this._maxSize) {
          newSize = this._maxSize;
        }
        const newPositiveLimit = newSize - bias;
        buckets.backing.growTo(newSize, oldPositiveLimit, newPositiveLimit);
      }
      /**
       * _changeScale computes how much downscaling is needed by shifting the
       * high and low values until they are separated by no more than size.
       */
      _changeScale(high, low) {
        let change = 0;
        while (high - low >= this._maxSize) {
          high >>= 1;
          low >>= 1;
          change++;
        }
        return change;
      }
      /**
       * _downscale subtracts `change` from the current mapping scale.
       */
      _downscale(change) {
        if (change === 0) {
          return;
        }
        if (change < 0) {
          throw new Error(`impossible change of scale: ${this.scale}`);
        }
        const newScale = this._mapping.scale - change;
        this._positive.downscale(change);
        this._negative.downscale(change);
        this._mapping = (0, getMapping_1.getMapping)(newScale);
      }
      /**
       * _minScale is used by diff and merge to compute an ideal combined scale
       */
      _minScale(other2) {
        const minScale = Math.min(this.scale, other2.scale);
        const highLowPos = HighLow.combine(this._highLowAtScale(this.positive, this.scale, minScale), this._highLowAtScale(other2.positive, other2.scale, minScale));
        const highLowNeg = HighLow.combine(this._highLowAtScale(this.negative, this.scale, minScale), this._highLowAtScale(other2.negative, other2.scale, minScale));
        return Math.min(minScale - this._changeScale(highLowPos.high, highLowPos.low), minScale - this._changeScale(highLowNeg.high, highLowNeg.low));
      }
      /**
       * _highLowAtScale is used by diff and merge to compute an ideal combined scale.
       */
      _highLowAtScale(buckets, currentScale, newScale) {
        if (buckets.length === 0) {
          return new HighLow(0, -1);
        }
        const shift = currentScale - newScale;
        return new HighLow(buckets.indexStart >> shift, buckets.indexEnd >> shift);
      }
      /**
       * _mergeBuckets translates index values from another histogram and
       * adds the values into the corresponding buckets of this histogram.
       */
      _mergeBuckets(ours, other2, theirs, scale) {
        const theirOffset = theirs.offset;
        const theirChange = other2.scale - scale;
        for (let i = 0; i < theirs.length; i++) {
          this._incrementIndexBy(ours, theirOffset + i >> theirChange, theirs.at(i));
        }
      }
      /**
       * _diffBuckets translates index values from another histogram and
       * subtracts the values in the corresponding buckets of this histogram.
       */
      _diffBuckets(ours, other2, theirs, scale) {
        const theirOffset = theirs.offset;
        const theirChange = other2.scale - scale;
        for (let i = 0; i < theirs.length; i++) {
          const ourIndex = theirOffset + i >> theirChange;
          let bucketIndex = ourIndex - ours.indexBase;
          if (bucketIndex < 0) {
            bucketIndex += ours.backing.length;
          }
          ours.decrementBucket(bucketIndex, theirs.at(i));
        }
        ours.trim();
      }
    };
    exports2.ExponentialHistogramAccumulation = ExponentialHistogramAccumulation;
    var ExponentialHistogramAggregator = class {
      static {
        __name(this, "ExponentialHistogramAggregator");
      }
      _maxSize;
      _recordMinMax;
      kind = types_1.AggregatorKind.EXPONENTIAL_HISTOGRAM;
      /**
       * @param _maxSize Maximum number of buckets for each of the positive
       *    and negative ranges, exclusive of the zero-bucket.
       * @param _recordMinMax If set to true, min and max will be recorded.
       *    Otherwise, min and max will not be recorded.
       */
      constructor(_maxSize, _recordMinMax) {
        this._maxSize = _maxSize;
        this._recordMinMax = _recordMinMax;
      }
      createAccumulation(startTime) {
        return new ExponentialHistogramAccumulation(startTime, this._maxSize, this._recordMinMax);
      }
      /**
       * Return the result of the merge of two exponential histogram accumulations.
       */
      merge(previous, delta) {
        const result = delta.clone();
        result.merge(previous);
        return result;
      }
      /**
       * Returns a new DELTA aggregation by comparing two cumulative measurements.
       */
      diff(previous, current) {
        const result = current.clone();
        result.diff(previous);
        return result;
      }
      toMetricData(descriptor2, aggregationTemporality, accumulationByAttributes, endTime) {
        return {
          descriptor: descriptor2,
          aggregationTemporality,
          dataPointType: MetricData_1.DataPointType.EXPONENTIAL_HISTOGRAM,
          dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => {
            const pointValue = accumulation.toPointValue();
            const allowsNegativeValues = descriptor2.type === MetricData_1.InstrumentType.GAUGE || descriptor2.type === MetricData_1.InstrumentType.UP_DOWN_COUNTER || descriptor2.type === MetricData_1.InstrumentType.OBSERVABLE_GAUGE || descriptor2.type === MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;
            return {
              attributes,
              startTime: accumulation.startTime,
              endTime,
              value: {
                min: pointValue.hasMinMax ? pointValue.min : void 0,
                max: pointValue.hasMinMax ? pointValue.max : void 0,
                sum: !allowsNegativeValues ? pointValue.sum : void 0,
                positive: {
                  offset: pointValue.positive.offset,
                  bucketCounts: pointValue.positive.bucketCounts
                },
                negative: {
                  offset: pointValue.negative.offset,
                  bucketCounts: pointValue.negative.bucketCounts
                },
                count: pointValue.count,
                scale: pointValue.scale,
                zeroCount: pointValue.zeroCount
              }
            };
          })
        };
      }
    };
    exports2.ExponentialHistogramAggregator = ExponentialHistogramAggregator;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/LastValue.js
var require_LastValue = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/LastValue.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LastValueAggregator = exports2.LastValueAccumulation = void 0;
    var types_1 = require_types4();
    var core_1 = require_src8();
    var MetricData_1 = require_MetricData();
    var LastValueAccumulation = class {
      static {
        __name(this, "LastValueAccumulation");
      }
      startTime;
      _current;
      sampleTime;
      constructor(startTime, _current = 0, sampleTime = [0, 0]) {
        this.startTime = startTime;
        this._current = _current;
        this.sampleTime = sampleTime;
      }
      record(value) {
        this._current = value;
        this.sampleTime = (0, core_1.millisToHrTime)(Date.now());
      }
      setStartTime(startTime) {
        this.startTime = startTime;
      }
      toPointValue() {
        return this._current;
      }
    };
    exports2.LastValueAccumulation = LastValueAccumulation;
    var LastValueAggregator = class {
      static {
        __name(this, "LastValueAggregator");
      }
      kind = types_1.AggregatorKind.LAST_VALUE;
      createAccumulation(startTime) {
        return new LastValueAccumulation(startTime);
      }
      /**
       * Returns the result of the merge of the given accumulations.
       *
       * Return the newly captured (delta) accumulation for LastValueAggregator.
       */
      merge(previous, delta) {
        const latestAccumulation = (0, core_1.hrTimeToMicroseconds)(delta.sampleTime) >= (0, core_1.hrTimeToMicroseconds)(previous.sampleTime) ? delta : previous;
        return new LastValueAccumulation(previous.startTime, latestAccumulation.toPointValue(), latestAccumulation.sampleTime);
      }
      /**
       * Returns a new DELTA aggregation by comparing two cumulative measurements.
       *
       * A delta aggregation is not meaningful to LastValueAggregator, just return
       * the newly captured (delta) accumulation for LastValueAggregator.
       */
      diff(previous, current) {
        const latestAccumulation = (0, core_1.hrTimeToMicroseconds)(current.sampleTime) >= (0, core_1.hrTimeToMicroseconds)(previous.sampleTime) ? current : previous;
        return new LastValueAccumulation(current.startTime, latestAccumulation.toPointValue(), latestAccumulation.sampleTime);
      }
      toMetricData(descriptor2, aggregationTemporality, accumulationByAttributes, endTime) {
        return {
          descriptor: descriptor2,
          aggregationTemporality,
          dataPointType: MetricData_1.DataPointType.GAUGE,
          dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => {
            return {
              attributes,
              startTime: accumulation.startTime,
              endTime,
              value: accumulation.toPointValue()
            };
          })
        };
      }
    };
    exports2.LastValueAggregator = LastValueAggregator;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Sum.js
var require_Sum = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Sum.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SumAggregator = exports2.SumAccumulation = void 0;
    var types_1 = require_types4();
    var MetricData_1 = require_MetricData();
    var SumAccumulation = class {
      static {
        __name(this, "SumAccumulation");
      }
      startTime;
      monotonic;
      _current;
      reset;
      constructor(startTime, monotonic, _current = 0, reset = false) {
        this.startTime = startTime;
        this.monotonic = monotonic;
        this._current = _current;
        this.reset = reset;
      }
      record(value) {
        if (this.monotonic && value < 0) {
          return;
        }
        this._current += value;
      }
      setStartTime(startTime) {
        this.startTime = startTime;
      }
      toPointValue() {
        return this._current;
      }
    };
    exports2.SumAccumulation = SumAccumulation;
    var SumAggregator = class {
      static {
        __name(this, "SumAggregator");
      }
      monotonic;
      kind = types_1.AggregatorKind.SUM;
      constructor(monotonic) {
        this.monotonic = monotonic;
      }
      createAccumulation(startTime) {
        return new SumAccumulation(startTime, this.monotonic);
      }
      /**
       * Returns the result of the merge of the given accumulations.
       */
      merge(previous, delta) {
        const prevPv = previous.toPointValue();
        const deltaPv = delta.toPointValue();
        if (delta.reset) {
          return new SumAccumulation(delta.startTime, this.monotonic, deltaPv, delta.reset);
        }
        return new SumAccumulation(previous.startTime, this.monotonic, prevPv + deltaPv);
      }
      /**
       * Returns a new DELTA aggregation by comparing two cumulative measurements.
       */
      diff(previous, current) {
        const prevPv = previous.toPointValue();
        const currPv = current.toPointValue();
        if (this.monotonic && prevPv > currPv) {
          return new SumAccumulation(current.startTime, this.monotonic, currPv, true);
        }
        return new SumAccumulation(current.startTime, this.monotonic, currPv - prevPv);
      }
      toMetricData(descriptor2, aggregationTemporality, accumulationByAttributes, endTime) {
        return {
          descriptor: descriptor2,
          aggregationTemporality,
          dataPointType: MetricData_1.DataPointType.SUM,
          dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => {
            return {
              attributes,
              startTime: accumulation.startTime,
              endTime,
              value: accumulation.toPointValue()
            };
          }),
          isMonotonic: this.monotonic
        };
      }
    };
    exports2.SumAggregator = SumAggregator;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/index.js
var require_aggregator = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SumAggregator = exports2.SumAccumulation = exports2.LastValueAggregator = exports2.LastValueAccumulation = exports2.ExponentialHistogramAggregator = exports2.ExponentialHistogramAccumulation = exports2.HistogramAggregator = exports2.HistogramAccumulation = exports2.DropAggregator = void 0;
    var Drop_1 = require_Drop();
    Object.defineProperty(exports2, "DropAggregator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return Drop_1.DropAggregator;
    }, "get") });
    var Histogram_1 = require_Histogram();
    Object.defineProperty(exports2, "HistogramAccumulation", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return Histogram_1.HistogramAccumulation;
    }, "get") });
    Object.defineProperty(exports2, "HistogramAggregator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return Histogram_1.HistogramAggregator;
    }, "get") });
    var ExponentialHistogram_1 = require_ExponentialHistogram();
    Object.defineProperty(exports2, "ExponentialHistogramAccumulation", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ExponentialHistogram_1.ExponentialHistogramAccumulation;
    }, "get") });
    Object.defineProperty(exports2, "ExponentialHistogramAggregator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ExponentialHistogram_1.ExponentialHistogramAggregator;
    }, "get") });
    var LastValue_1 = require_LastValue();
    Object.defineProperty(exports2, "LastValueAccumulation", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return LastValue_1.LastValueAccumulation;
    }, "get") });
    Object.defineProperty(exports2, "LastValueAggregator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return LastValue_1.LastValueAggregator;
    }, "get") });
    var Sum_1 = require_Sum();
    Object.defineProperty(exports2, "SumAccumulation", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return Sum_1.SumAccumulation;
    }, "get") });
    Object.defineProperty(exports2, "SumAggregator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return Sum_1.SumAggregator;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/view/Aggregation.js
var require_Aggregation = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/view/Aggregation.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DEFAULT_AGGREGATION = exports2.EXPONENTIAL_HISTOGRAM_AGGREGATION = exports2.HISTOGRAM_AGGREGATION = exports2.LAST_VALUE_AGGREGATION = exports2.SUM_AGGREGATION = exports2.DROP_AGGREGATION = exports2.DefaultAggregation = exports2.ExponentialHistogramAggregation = exports2.ExplicitBucketHistogramAggregation = exports2.HistogramAggregation = exports2.LastValueAggregation = exports2.SumAggregation = exports2.DropAggregation = void 0;
    var api = (init_esm2(), __toCommonJS(esm_exports2));
    var aggregator_1 = require_aggregator();
    var MetricData_1 = require_MetricData();
    var DropAggregation = class _DropAggregation {
      static {
        __name(this, "DropAggregation");
      }
      static DEFAULT_INSTANCE = new aggregator_1.DropAggregator();
      createAggregator(_instrument) {
        return _DropAggregation.DEFAULT_INSTANCE;
      }
    };
    exports2.DropAggregation = DropAggregation;
    var SumAggregation = class _SumAggregation {
      static {
        __name(this, "SumAggregation");
      }
      static MONOTONIC_INSTANCE = new aggregator_1.SumAggregator(true);
      static NON_MONOTONIC_INSTANCE = new aggregator_1.SumAggregator(false);
      createAggregator(instrument) {
        switch (instrument.type) {
          case MetricData_1.InstrumentType.COUNTER:
          case MetricData_1.InstrumentType.OBSERVABLE_COUNTER:
          case MetricData_1.InstrumentType.HISTOGRAM: {
            return _SumAggregation.MONOTONIC_INSTANCE;
          }
          default: {
            return _SumAggregation.NON_MONOTONIC_INSTANCE;
          }
        }
      }
    };
    exports2.SumAggregation = SumAggregation;
    var LastValueAggregation = class _LastValueAggregation {
      static {
        __name(this, "LastValueAggregation");
      }
      static DEFAULT_INSTANCE = new aggregator_1.LastValueAggregator();
      createAggregator(_instrument) {
        return _LastValueAggregation.DEFAULT_INSTANCE;
      }
    };
    exports2.LastValueAggregation = LastValueAggregation;
    var HistogramAggregation = class _HistogramAggregation {
      static {
        __name(this, "HistogramAggregation");
      }
      static DEFAULT_INSTANCE = new aggregator_1.HistogramAggregator([0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1e3, 2500, 5e3, 7500, 1e4], true);
      createAggregator(_instrument) {
        return _HistogramAggregation.DEFAULT_INSTANCE;
      }
    };
    exports2.HistogramAggregation = HistogramAggregation;
    var ExplicitBucketHistogramAggregation = class {
      static {
        __name(this, "ExplicitBucketHistogramAggregation");
      }
      _recordMinMax;
      _boundaries;
      /**
       * @param boundaries the bucket boundaries of the histogram aggregation
       * @param _recordMinMax If set to true, min and max will be recorded. Otherwise, min and max will not be recorded.
       */
      constructor(boundaries, _recordMinMax = true) {
        this._recordMinMax = _recordMinMax;
        if (boundaries == null) {
          throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");
        }
        boundaries = boundaries.concat();
        boundaries = boundaries.sort((a, b) => a - b);
        const minusInfinityIndex = boundaries.lastIndexOf(-Infinity);
        let infinityIndex = boundaries.indexOf(Infinity);
        if (infinityIndex === -1) {
          infinityIndex = void 0;
        }
        this._boundaries = boundaries.slice(minusInfinityIndex + 1, infinityIndex);
      }
      createAggregator(_instrument) {
        return new aggregator_1.HistogramAggregator(this._boundaries, this._recordMinMax);
      }
    };
    exports2.ExplicitBucketHistogramAggregation = ExplicitBucketHistogramAggregation;
    var ExponentialHistogramAggregation = class {
      static {
        __name(this, "ExponentialHistogramAggregation");
      }
      _maxSize;
      _recordMinMax;
      constructor(_maxSize = 160, _recordMinMax = true) {
        this._maxSize = _maxSize;
        this._recordMinMax = _recordMinMax;
      }
      createAggregator(_instrument) {
        return new aggregator_1.ExponentialHistogramAggregator(this._maxSize, this._recordMinMax);
      }
    };
    exports2.ExponentialHistogramAggregation = ExponentialHistogramAggregation;
    var DefaultAggregation = class {
      static {
        __name(this, "DefaultAggregation");
      }
      _resolve(instrument) {
        switch (instrument.type) {
          case MetricData_1.InstrumentType.COUNTER:
          case MetricData_1.InstrumentType.UP_DOWN_COUNTER:
          case MetricData_1.InstrumentType.OBSERVABLE_COUNTER:
          case MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER: {
            return exports2.SUM_AGGREGATION;
          }
          case MetricData_1.InstrumentType.GAUGE:
          case MetricData_1.InstrumentType.OBSERVABLE_GAUGE: {
            return exports2.LAST_VALUE_AGGREGATION;
          }
          case MetricData_1.InstrumentType.HISTOGRAM: {
            if (instrument.advice.explicitBucketBoundaries) {
              return new ExplicitBucketHistogramAggregation(instrument.advice.explicitBucketBoundaries);
            }
            return exports2.HISTOGRAM_AGGREGATION;
          }
        }
        api.diag.warn(`Unable to recognize instrument type: ${instrument.type}`);
        return exports2.DROP_AGGREGATION;
      }
      createAggregator(instrument) {
        return this._resolve(instrument).createAggregator(instrument);
      }
    };
    exports2.DefaultAggregation = DefaultAggregation;
    exports2.DROP_AGGREGATION = new DropAggregation();
    exports2.SUM_AGGREGATION = new SumAggregation();
    exports2.LAST_VALUE_AGGREGATION = new LastValueAggregation();
    exports2.HISTOGRAM_AGGREGATION = new HistogramAggregation();
    exports2.EXPONENTIAL_HISTOGRAM_AGGREGATION = new ExponentialHistogramAggregation();
    exports2.DEFAULT_AGGREGATION = new DefaultAggregation();
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/view/AggregationOption.js
var require_AggregationOption = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/view/AggregationOption.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.toAggregation = exports2.AggregationType = void 0;
    var Aggregation_1 = require_Aggregation();
    var AggregationType;
    (function(AggregationType2) {
      AggregationType2[AggregationType2["DEFAULT"] = 0] = "DEFAULT";
      AggregationType2[AggregationType2["DROP"] = 1] = "DROP";
      AggregationType2[AggregationType2["SUM"] = 2] = "SUM";
      AggregationType2[AggregationType2["LAST_VALUE"] = 3] = "LAST_VALUE";
      AggregationType2[AggregationType2["EXPLICIT_BUCKET_HISTOGRAM"] = 4] = "EXPLICIT_BUCKET_HISTOGRAM";
      AggregationType2[AggregationType2["EXPONENTIAL_HISTOGRAM"] = 5] = "EXPONENTIAL_HISTOGRAM";
    })(AggregationType = exports2.AggregationType || (exports2.AggregationType = {}));
    function toAggregation(option2) {
      switch (option2.type) {
        case AggregationType.DEFAULT:
          return Aggregation_1.DEFAULT_AGGREGATION;
        case AggregationType.DROP:
          return Aggregation_1.DROP_AGGREGATION;
        case AggregationType.SUM:
          return Aggregation_1.SUM_AGGREGATION;
        case AggregationType.LAST_VALUE:
          return Aggregation_1.LAST_VALUE_AGGREGATION;
        case AggregationType.EXPONENTIAL_HISTOGRAM: {
          const expOption = option2;
          return new Aggregation_1.ExponentialHistogramAggregation(expOption.options?.maxSize, expOption.options?.recordMinMax);
        }
        case AggregationType.EXPLICIT_BUCKET_HISTOGRAM: {
          const expOption = option2;
          if (expOption.options == null) {
            return Aggregation_1.HISTOGRAM_AGGREGATION;
          } else {
            return new Aggregation_1.ExplicitBucketHistogramAggregation(expOption.options?.boundaries, expOption.options?.recordMinMax);
          }
        }
        default:
          throw new Error("Unsupported Aggregation");
      }
    }
    __name(toAggregation, "toAggregation");
    exports2.toAggregation = toAggregation;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationSelector.js
var require_AggregationSelector = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationSelector.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = exports2.DEFAULT_AGGREGATION_SELECTOR = void 0;
    var AggregationTemporality_1 = require_AggregationTemporality();
    var AggregationOption_1 = require_AggregationOption();
    var DEFAULT_AGGREGATION_SELECTOR = /* @__PURE__ */ __name((_instrumentType) => {
      return {
        type: AggregationOption_1.AggregationType.DEFAULT
      };
    }, "DEFAULT_AGGREGATION_SELECTOR");
    exports2.DEFAULT_AGGREGATION_SELECTOR = DEFAULT_AGGREGATION_SELECTOR;
    var DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = /* @__PURE__ */ __name((_instrumentType) => AggregationTemporality_1.AggregationTemporality.CUMULATIVE, "DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR");
    exports2.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricReader.js
var require_MetricReader = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricReader.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MetricReader = void 0;
    var api = (init_esm2(), __toCommonJS(esm_exports2));
    var utils_1 = require_utils6();
    var AggregationSelector_1 = require_AggregationSelector();
    var MetricReader = class {
      static {
        __name(this, "MetricReader");
      }
      // Tracks the shutdown state.
      // TODO: use BindOncePromise here once a new version of @opentelemetry/core is available.
      _shutdown = false;
      // Additional MetricProducers which will be combined with the SDK's output
      _metricProducers;
      // MetricProducer used by this instance which produces metrics from the SDK
      _sdkMetricProducer;
      _aggregationTemporalitySelector;
      _aggregationSelector;
      _cardinalitySelector;
      constructor(options2) {
        this._aggregationSelector = options2?.aggregationSelector ?? AggregationSelector_1.DEFAULT_AGGREGATION_SELECTOR;
        this._aggregationTemporalitySelector = options2?.aggregationTemporalitySelector ?? AggregationSelector_1.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR;
        this._metricProducers = options2?.metricProducers ?? [];
        this._cardinalitySelector = options2?.cardinalitySelector;
      }
      setMetricProducer(metricProducer) {
        if (this._sdkMetricProducer) {
          throw new Error("MetricReader can not be bound to a MeterProvider again.");
        }
        this._sdkMetricProducer = metricProducer;
        this.onInitialized();
      }
      selectAggregation(instrumentType) {
        return this._aggregationSelector(instrumentType);
      }
      selectAggregationTemporality(instrumentType) {
        return this._aggregationTemporalitySelector(instrumentType);
      }
      selectCardinalityLimit(instrumentType) {
        return this._cardinalitySelector ? this._cardinalitySelector(instrumentType) : 2e3;
      }
      /**
       * Handle once the SDK has initialized this {@link MetricReader}
       * Overriding this method is optional.
       */
      onInitialized() {
      }
      async collect(options2) {
        if (this._sdkMetricProducer === void 0) {
          throw new Error("MetricReader is not bound to a MetricProducer");
        }
        if (this._shutdown) {
          throw new Error("MetricReader is shutdown");
        }
        const [sdkCollectionResults, ...additionalCollectionResults] = await Promise.all([
          this._sdkMetricProducer.collect({
            timeoutMillis: options2?.timeoutMillis
          }),
          ...this._metricProducers.map((producer) => producer.collect({
            timeoutMillis: options2?.timeoutMillis
          }))
        ]);
        const errors = sdkCollectionResults.errors.concat((0, utils_1.FlatMap)(additionalCollectionResults, (result) => result.errors));
        const resource = sdkCollectionResults.resourceMetrics.resource;
        const scopeMetrics = sdkCollectionResults.resourceMetrics.scopeMetrics.concat((0, utils_1.FlatMap)(additionalCollectionResults, (result) => result.resourceMetrics.scopeMetrics));
        return {
          resourceMetrics: {
            resource,
            scopeMetrics
          },
          errors
        };
      }
      async shutdown(options2) {
        if (this._shutdown) {
          api.diag.error("Cannot call shutdown twice.");
          return;
        }
        if (options2?.timeoutMillis == null) {
          await this.onShutdown();
        } else {
          await (0, utils_1.callWithTimeout)(this.onShutdown(), options2.timeoutMillis);
        }
        this._shutdown = true;
      }
      async forceFlush(options2) {
        if (this._shutdown) {
          api.diag.warn("Cannot forceFlush on already shutdown MetricReader.");
          return;
        }
        if (options2?.timeoutMillis == null) {
          await this.onForceFlush();
          return;
        }
        await (0, utils_1.callWithTimeout)(this.onForceFlush(), options2.timeoutMillis);
      }
    };
    exports2.MetricReader = MetricReader;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/export/PeriodicExportingMetricReader.js
var require_PeriodicExportingMetricReader = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/export/PeriodicExportingMetricReader.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PeriodicExportingMetricReader = void 0;
    var api = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var MetricReader_1 = require_MetricReader();
    var utils_1 = require_utils6();
    var PeriodicExportingMetricReader2 = class extends MetricReader_1.MetricReader {
      static {
        __name(this, "PeriodicExportingMetricReader");
      }
      _interval;
      _exporter;
      _exportInterval;
      _exportTimeout;
      constructor(options2) {
        super({
          aggregationSelector: options2.exporter.selectAggregation?.bind(options2.exporter),
          aggregationTemporalitySelector: options2.exporter.selectAggregationTemporality?.bind(options2.exporter),
          metricProducers: options2.metricProducers
        });
        if (options2.exportIntervalMillis !== void 0 && options2.exportIntervalMillis <= 0) {
          throw Error("exportIntervalMillis must be greater than 0");
        }
        if (options2.exportTimeoutMillis !== void 0 && options2.exportTimeoutMillis <= 0) {
          throw Error("exportTimeoutMillis must be greater than 0");
        }
        if (options2.exportTimeoutMillis !== void 0 && options2.exportIntervalMillis !== void 0 && options2.exportIntervalMillis < options2.exportTimeoutMillis) {
          throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");
        }
        this._exportInterval = options2.exportIntervalMillis ?? 6e4;
        this._exportTimeout = options2.exportTimeoutMillis ?? 3e4;
        this._exporter = options2.exporter;
      }
      async _runOnce() {
        try {
          await (0, utils_1.callWithTimeout)(this._doRun(), this._exportTimeout);
        } catch (err) {
          if (err instanceof utils_1.TimeoutError) {
            api.diag.error("Export took longer than %s milliseconds and timed out.", this._exportTimeout);
            return;
          }
          (0, core_1.globalErrorHandler)(err);
        }
      }
      async _doRun() {
        const { resourceMetrics, errors } = await this.collect({
          timeoutMillis: this._exportTimeout
        });
        if (errors.length > 0) {
          api.diag.error("PeriodicExportingMetricReader: metrics collection errors", ...errors);
        }
        if (resourceMetrics.resource.asyncAttributesPending) {
          try {
            await resourceMetrics.resource.waitForAsyncAttributes?.();
          } catch (e2) {
            api.diag.debug("Error while resolving async portion of resource: ", e2);
            (0, core_1.globalErrorHandler)(e2);
          }
        }
        if (resourceMetrics.scopeMetrics.length === 0) {
          return;
        }
        const result = await core_1.internal._export(this._exporter, resourceMetrics);
        if (result.code !== core_1.ExportResultCode.SUCCESS) {
          throw new Error(`PeriodicExportingMetricReader: metrics export failed (error ${result.error})`);
        }
      }
      onInitialized() {
        this._interval = setInterval(() => {
          void this._runOnce();
        }, this._exportInterval);
        (0, core_1.unrefTimer)(this._interval);
      }
      async onForceFlush() {
        await this._runOnce();
        await this._exporter.forceFlush();
      }
      async onShutdown() {
        if (this._interval) {
          clearInterval(this._interval);
        }
        await this.onForceFlush();
        await this._exporter.shutdown();
      }
    };
    exports2.PeriodicExportingMetricReader = PeriodicExportingMetricReader2;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/export/InMemoryMetricExporter.js
var require_InMemoryMetricExporter = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/export/InMemoryMetricExporter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InMemoryMetricExporter = void 0;
    var core_1 = require_src8();
    var InMemoryMetricExporter = class {
      static {
        __name(this, "InMemoryMetricExporter");
      }
      _shutdown = false;
      _aggregationTemporality;
      _metrics = [];
      constructor(aggregationTemporality) {
        this._aggregationTemporality = aggregationTemporality;
      }
      /**
       * @inheritedDoc
       */
      export(metrics2, resultCallback) {
        if (this._shutdown) {
          setTimeout(() => resultCallback({ code: core_1.ExportResultCode.FAILED }), 0);
          return;
        }
        this._metrics.push(metrics2);
        setTimeout(() => resultCallback({ code: core_1.ExportResultCode.SUCCESS }), 0);
      }
      /**
       * Returns all the collected resource metrics
       * @returns ResourceMetrics[]
       */
      getMetrics() {
        return this._metrics;
      }
      forceFlush() {
        return Promise.resolve();
      }
      reset() {
        this._metrics = [];
      }
      selectAggregationTemporality(_instrumentType) {
        return this._aggregationTemporality;
      }
      shutdown() {
        this._shutdown = true;
        return Promise.resolve();
      }
    };
    exports2.InMemoryMetricExporter = InMemoryMetricExporter;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/export/ConsoleMetricExporter.js
var require_ConsoleMetricExporter = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/export/ConsoleMetricExporter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ConsoleMetricExporter = void 0;
    var core_1 = require_src8();
    var AggregationSelector_1 = require_AggregationSelector();
    var ConsoleMetricExporter2 = class _ConsoleMetricExporter {
      static {
        __name(this, "ConsoleMetricExporter");
      }
      _shutdown = false;
      _temporalitySelector;
      constructor(options2) {
        this._temporalitySelector = options2?.temporalitySelector ?? AggregationSelector_1.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR;
      }
      export(metrics2, resultCallback) {
        if (this._shutdown) {
          setImmediate(resultCallback, { code: core_1.ExportResultCode.FAILED });
          return;
        }
        return _ConsoleMetricExporter._sendMetrics(metrics2, resultCallback);
      }
      forceFlush() {
        return Promise.resolve();
      }
      selectAggregationTemporality(_instrumentType) {
        return this._temporalitySelector(_instrumentType);
      }
      shutdown() {
        this._shutdown = true;
        return Promise.resolve();
      }
      static _sendMetrics(metrics2, done) {
        for (const scopeMetrics of metrics2.scopeMetrics) {
          for (const metric of scopeMetrics.metrics) {
            console.dir({
              descriptor: metric.descriptor,
              dataPointType: metric.dataPointType,
              dataPoints: metric.dataPoints
            }, { depth: null });
          }
        }
        done({ code: core_1.ExportResultCode.SUCCESS });
      }
    };
    exports2.ConsoleMetricExporter = ConsoleMetricExporter2;
  }
});

// node_modules/@opentelemetry/resources/build/src/platform/node/default-service-name.js
var require_default_service_name = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/platform/node/default-service-name.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.defaultServiceName = void 0;
    function defaultServiceName() {
      return `unknown_service:${process.argv0}`;
    }
    __name(defaultServiceName, "defaultServiceName");
    exports2.defaultServiceName = defaultServiceName;
  }
});

// node_modules/@opentelemetry/resources/build/src/platform/node/index.js
var require_node4 = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/platform/node/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.defaultServiceName = void 0;
    var default_service_name_1 = require_default_service_name();
    Object.defineProperty(exports2, "defaultServiceName", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return default_service_name_1.defaultServiceName;
    }, "get") });
  }
});

// node_modules/@opentelemetry/resources/build/src/platform/index.js
var require_platform3 = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/platform/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.defaultServiceName = void 0;
    var node_1 = require_node4();
    Object.defineProperty(exports2, "defaultServiceName", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.defaultServiceName;
    }, "get") });
  }
});

// node_modules/@opentelemetry/resources/build/src/utils.js
var require_utils7 = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.identity = exports2.isPromiseLike = void 0;
    var isPromiseLike = /* @__PURE__ */ __name((val) => {
      return val !== null && typeof val === "object" && typeof val.then === "function";
    }, "isPromiseLike");
    exports2.isPromiseLike = isPromiseLike;
    function identity(_) {
      return _;
    }
    __name(identity, "identity");
    exports2.identity = identity;
  }
});

// node_modules/@opentelemetry/resources/build/src/ResourceImpl.js
var require_ResourceImpl = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/ResourceImpl.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.defaultResource = exports2.emptyResource = exports2.resourceFromDetectedResource = exports2.resourceFromAttributes = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var semantic_conventions_1 = (init_esm(), __toCommonJS(esm_exports));
    var platform_1 = require_platform3();
    var utils_1 = require_utils7();
    var ResourceImpl = class _ResourceImpl {
      static {
        __name(this, "ResourceImpl");
      }
      _rawAttributes;
      _asyncAttributesPending = false;
      _memoizedAttributes;
      static FromAttributeList(attributes) {
        const res = new _ResourceImpl({});
        res._rawAttributes = guardedRawAttributes(attributes);
        res._asyncAttributesPending = attributes.filter(([_, val]) => (0, utils_1.isPromiseLike)(val)).length > 0;
        return res;
      }
      constructor(resource) {
        const attributes = resource.attributes ?? {};
        this._rawAttributes = Object.entries(attributes).map(([k, v]) => {
          if ((0, utils_1.isPromiseLike)(v)) {
            this._asyncAttributesPending = true;
          }
          return [k, v];
        });
        this._rawAttributes = guardedRawAttributes(this._rawAttributes);
      }
      get asyncAttributesPending() {
        return this._asyncAttributesPending;
      }
      async waitForAsyncAttributes() {
        if (!this.asyncAttributesPending) {
          return;
        }
        for (let i = 0; i < this._rawAttributes.length; i++) {
          const [k, v] = this._rawAttributes[i];
          this._rawAttributes[i] = [k, (0, utils_1.isPromiseLike)(v) ? await v : v];
        }
        this._asyncAttributesPending = false;
      }
      get attributes() {
        if (this.asyncAttributesPending) {
          api_1.diag.error("Accessing resource attributes before async attributes settled");
        }
        if (this._memoizedAttributes) {
          return this._memoizedAttributes;
        }
        const attrs = {};
        for (const [k, v] of this._rawAttributes) {
          if ((0, utils_1.isPromiseLike)(v)) {
            api_1.diag.debug(`Unsettled resource attribute ${k} skipped`);
            continue;
          }
          if (v != null) {
            attrs[k] ??= v;
          }
        }
        if (!this._asyncAttributesPending) {
          this._memoizedAttributes = attrs;
        }
        return attrs;
      }
      getRawAttributes() {
        return this._rawAttributes;
      }
      merge(resource) {
        if (resource == null)
          return this;
        return _ResourceImpl.FromAttributeList([
          ...resource.getRawAttributes(),
          ...this.getRawAttributes()
        ]);
      }
    };
    function resourceFromAttributes2(attributes) {
      return ResourceImpl.FromAttributeList(Object.entries(attributes));
    }
    __name(resourceFromAttributes2, "resourceFromAttributes");
    exports2.resourceFromAttributes = resourceFromAttributes2;
    function resourceFromDetectedResource(detectedResource) {
      return new ResourceImpl(detectedResource);
    }
    __name(resourceFromDetectedResource, "resourceFromDetectedResource");
    exports2.resourceFromDetectedResource = resourceFromDetectedResource;
    function emptyResource() {
      return resourceFromAttributes2({});
    }
    __name(emptyResource, "emptyResource");
    exports2.emptyResource = emptyResource;
    function defaultResource() {
      return resourceFromAttributes2({
        [semantic_conventions_1.ATTR_SERVICE_NAME]: (0, platform_1.defaultServiceName)(),
        [semantic_conventions_1.ATTR_TELEMETRY_SDK_LANGUAGE]: core_1.SDK_INFO[semantic_conventions_1.ATTR_TELEMETRY_SDK_LANGUAGE],
        [semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME]: core_1.SDK_INFO[semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME],
        [semantic_conventions_1.ATTR_TELEMETRY_SDK_VERSION]: core_1.SDK_INFO[semantic_conventions_1.ATTR_TELEMETRY_SDK_VERSION]
      });
    }
    __name(defaultResource, "defaultResource");
    exports2.defaultResource = defaultResource;
    function guardedRawAttributes(attributes) {
      return attributes.map(([k, v]) => {
        if ((0, utils_1.isPromiseLike)(v)) {
          return [
            k,
            v.catch((err) => {
              api_1.diag.debug("promise rejection for resource attribute: %s - %s", k, err);
              return void 0;
            })
          ];
        }
        return [k, v];
      });
    }
    __name(guardedRawAttributes, "guardedRawAttributes");
  }
});

// node_modules/@opentelemetry/resources/build/src/detect-resources.js
var require_detect_resources = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detect-resources.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.detectResources = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var ResourceImpl_1 = require_ResourceImpl();
    var detectResources = /* @__PURE__ */ __name((config = {}) => {
      const resources = (config.detectors || []).map((d) => {
        try {
          const resource = (0, ResourceImpl_1.resourceFromDetectedResource)(d.detect(config));
          api_1.diag.debug(`${d.constructor.name} found resource.`, resource);
          return resource;
        } catch (e2) {
          api_1.diag.debug(`${d.constructor.name} failed: ${e2.message}`);
          return (0, ResourceImpl_1.emptyResource)();
        }
      });
      return resources.reduce((acc, resource) => acc.merge(resource), (0, ResourceImpl_1.emptyResource)());
    }, "detectResources");
    exports2.detectResources = detectResources;
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/EnvDetector.js
var require_EnvDetector = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/EnvDetector.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.envDetector = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var semantic_conventions_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src8();
    var EnvDetector = class {
      static {
        __name(this, "EnvDetector");
      }
      // Type, attribute keys, and attribute values should not exceed 256 characters.
      _MAX_LENGTH = 255;
      // OTEL_RESOURCE_ATTRIBUTES is a comma-separated list of attributes.
      _COMMA_SEPARATOR = ",";
      // OTEL_RESOURCE_ATTRIBUTES contains key value pair separated by '='.
      _LABEL_KEY_VALUE_SPLITTER = "=";
      _ERROR_MESSAGE_INVALID_CHARS = "should be a ASCII string with a length greater than 0 and not exceed " + this._MAX_LENGTH + " characters.";
      _ERROR_MESSAGE_INVALID_VALUE = "should be a ASCII string with a length not exceed " + this._MAX_LENGTH + " characters.";
      /**
       * Returns a {@link Resource} populated with attributes from the
       * OTEL_RESOURCE_ATTRIBUTES environment variable. Note this is an async
       * function to conform to the Detector interface.
       *
       * @param config The resource detection config
       */
      detect(_config) {
        const attributes = {};
        const rawAttributes = (0, core_1.getStringFromEnv)("OTEL_RESOURCE_ATTRIBUTES");
        const serviceName = (0, core_1.getStringFromEnv)("OTEL_SERVICE_NAME");
        if (rawAttributes) {
          try {
            const parsedAttributes = this._parseResourceAttributes(rawAttributes);
            Object.assign(attributes, parsedAttributes);
          } catch (e2) {
            api_1.diag.debug(`EnvDetector failed: ${e2.message}`);
          }
        }
        if (serviceName) {
          attributes[semantic_conventions_1.ATTR_SERVICE_NAME] = serviceName;
        }
        return { attributes };
      }
      /**
       * Creates an attribute map from the OTEL_RESOURCE_ATTRIBUTES environment
       * variable.
       *
       * OTEL_RESOURCE_ATTRIBUTES: A comma-separated list of attributes describing
       * the source in more detail, e.g. “key1=val1,key2=val2”. Domain names and
       * paths are accepted as attribute keys. Values may be quoted or unquoted in
       * general. If a value contains whitespace, =, or " characters, it must
       * always be quoted.
       *
       * @param rawEnvAttributes The resource attributes as a comma-separated list
       * of key/value pairs.
       * @returns The sanitized resource attributes.
       */
      _parseResourceAttributes(rawEnvAttributes) {
        if (!rawEnvAttributes)
          return {};
        const attributes = {};
        const rawAttributes = rawEnvAttributes.split(this._COMMA_SEPARATOR, -1);
        for (const rawAttribute of rawAttributes) {
          const keyValuePair = rawAttribute.split(this._LABEL_KEY_VALUE_SPLITTER, -1);
          if (keyValuePair.length !== 2) {
            continue;
          }
          let [key, value] = keyValuePair;
          key = key.trim();
          value = value.trim().split(/^"|"$/).join("");
          if (!this._isValidAndNotEmpty(key)) {
            throw new Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`);
          }
          if (!this._isValid(value)) {
            throw new Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`);
          }
          attributes[key] = decodeURIComponent(value);
        }
        return attributes;
      }
      /**
       * Determines whether the given String is a valid printable ASCII string with
       * a length not exceed _MAX_LENGTH characters.
       *
       * @param str The String to be validated.
       * @returns Whether the String is valid.
       */
      _isValid(name3) {
        return name3.length <= this._MAX_LENGTH && this._isBaggageOctetString(name3);
      }
      // https://www.w3.org/TR/baggage/#definition
      _isBaggageOctetString(str2) {
        for (let i = 0; i < str2.length; i++) {
          const ch = str2.charCodeAt(i);
          if (ch < 33 || ch === 44 || ch === 59 || ch === 92 || ch > 126) {
            return false;
          }
        }
        return true;
      }
      /**
       * Determines whether the given String is a valid printable ASCII string with
       * a length greater than 0 and not exceed _MAX_LENGTH characters.
       *
       * @param str The String to be validated.
       * @returns Whether the String is valid and not empty.
       */
      _isValidAndNotEmpty(str2) {
        return str2.length > 0 && this._isValid(str2);
      }
    };
    exports2.envDetector = new EnvDetector();
  }
});

// node_modules/@opentelemetry/resources/build/src/semconv.js
var require_semconv2 = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/semconv.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ATTR_WEBENGINE_VERSION = exports2.ATTR_WEBENGINE_NAME = exports2.ATTR_WEBENGINE_DESCRIPTION = exports2.ATTR_SERVICE_NAMESPACE = exports2.ATTR_SERVICE_INSTANCE_ID = exports2.ATTR_PROCESS_RUNTIME_VERSION = exports2.ATTR_PROCESS_RUNTIME_NAME = exports2.ATTR_PROCESS_RUNTIME_DESCRIPTION = exports2.ATTR_PROCESS_PID = exports2.ATTR_PROCESS_OWNER = exports2.ATTR_PROCESS_EXECUTABLE_PATH = exports2.ATTR_PROCESS_EXECUTABLE_NAME = exports2.ATTR_PROCESS_COMMAND_ARGS = exports2.ATTR_PROCESS_COMMAND = exports2.ATTR_OS_VERSION = exports2.ATTR_OS_TYPE = exports2.ATTR_K8S_POD_NAME = exports2.ATTR_K8S_NAMESPACE_NAME = exports2.ATTR_K8S_DEPLOYMENT_NAME = exports2.ATTR_K8S_CLUSTER_NAME = exports2.ATTR_HOST_TYPE = exports2.ATTR_HOST_NAME = exports2.ATTR_HOST_IMAGE_VERSION = exports2.ATTR_HOST_IMAGE_NAME = exports2.ATTR_HOST_IMAGE_ID = exports2.ATTR_HOST_ID = exports2.ATTR_HOST_ARCH = exports2.ATTR_CONTAINER_NAME = exports2.ATTR_CONTAINER_IMAGE_TAGS = exports2.ATTR_CONTAINER_IMAGE_NAME = exports2.ATTR_CONTAINER_ID = exports2.ATTR_CLOUD_REGION = exports2.ATTR_CLOUD_PROVIDER = exports2.ATTR_CLOUD_AVAILABILITY_ZONE = exports2.ATTR_CLOUD_ACCOUNT_ID = void 0;
    exports2.ATTR_CLOUD_ACCOUNT_ID = "cloud.account.id";
    exports2.ATTR_CLOUD_AVAILABILITY_ZONE = "cloud.availability_zone";
    exports2.ATTR_CLOUD_PROVIDER = "cloud.provider";
    exports2.ATTR_CLOUD_REGION = "cloud.region";
    exports2.ATTR_CONTAINER_ID = "container.id";
    exports2.ATTR_CONTAINER_IMAGE_NAME = "container.image.name";
    exports2.ATTR_CONTAINER_IMAGE_TAGS = "container.image.tags";
    exports2.ATTR_CONTAINER_NAME = "container.name";
    exports2.ATTR_HOST_ARCH = "host.arch";
    exports2.ATTR_HOST_ID = "host.id";
    exports2.ATTR_HOST_IMAGE_ID = "host.image.id";
    exports2.ATTR_HOST_IMAGE_NAME = "host.image.name";
    exports2.ATTR_HOST_IMAGE_VERSION = "host.image.version";
    exports2.ATTR_HOST_NAME = "host.name";
    exports2.ATTR_HOST_TYPE = "host.type";
    exports2.ATTR_K8S_CLUSTER_NAME = "k8s.cluster.name";
    exports2.ATTR_K8S_DEPLOYMENT_NAME = "k8s.deployment.name";
    exports2.ATTR_K8S_NAMESPACE_NAME = "k8s.namespace.name";
    exports2.ATTR_K8S_POD_NAME = "k8s.pod.name";
    exports2.ATTR_OS_TYPE = "os.type";
    exports2.ATTR_OS_VERSION = "os.version";
    exports2.ATTR_PROCESS_COMMAND = "process.command";
    exports2.ATTR_PROCESS_COMMAND_ARGS = "process.command_args";
    exports2.ATTR_PROCESS_EXECUTABLE_NAME = "process.executable.name";
    exports2.ATTR_PROCESS_EXECUTABLE_PATH = "process.executable.path";
    exports2.ATTR_PROCESS_OWNER = "process.owner";
    exports2.ATTR_PROCESS_PID = "process.pid";
    exports2.ATTR_PROCESS_RUNTIME_DESCRIPTION = "process.runtime.description";
    exports2.ATTR_PROCESS_RUNTIME_NAME = "process.runtime.name";
    exports2.ATTR_PROCESS_RUNTIME_VERSION = "process.runtime.version";
    exports2.ATTR_SERVICE_INSTANCE_ID = "service.instance.id";
    exports2.ATTR_SERVICE_NAMESPACE = "service.namespace";
    exports2.ATTR_WEBENGINE_DESCRIPTION = "webengine.description";
    exports2.ATTR_WEBENGINE_NAME = "webengine.name";
    exports2.ATTR_WEBENGINE_VERSION = "webengine.version";
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/execAsync.js
var require_execAsync = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/execAsync.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.execAsync = void 0;
    var child_process2 = __require("child_process");
    var util4 = __require("util");
    exports2.execAsync = util4.promisify(child_process2.exec);
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-darwin.js
var require_getMachineId_darwin = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-darwin.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getMachineId = void 0;
    var execAsync_1 = require_execAsync();
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    async function getMachineId() {
      try {
        const result = await (0, execAsync_1.execAsync)('ioreg -rd1 -c "IOPlatformExpertDevice"');
        const idLine = result.stdout.split("\n").find((line) => line.includes("IOPlatformUUID"));
        if (!idLine) {
          return void 0;
        }
        const parts = idLine.split('" = "');
        if (parts.length === 2) {
          return parts[1].slice(0, -1);
        }
      } catch (e2) {
        api_1.diag.debug(`error reading machine id: ${e2}`);
      }
      return void 0;
    }
    __name(getMachineId, "getMachineId");
    exports2.getMachineId = getMachineId;
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-linux.js
var require_getMachineId_linux = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-linux.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getMachineId = void 0;
    var fs_1 = __require("fs");
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    async function getMachineId() {
      const paths = ["/etc/machine-id", "/var/lib/dbus/machine-id"];
      for (const path108 of paths) {
        try {
          const result = await fs_1.promises.readFile(path108, { encoding: "utf8" });
          return result.trim();
        } catch (e2) {
          api_1.diag.debug(`error reading machine id: ${e2}`);
        }
      }
      return void 0;
    }
    __name(getMachineId, "getMachineId");
    exports2.getMachineId = getMachineId;
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-bsd.js
var require_getMachineId_bsd = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-bsd.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getMachineId = void 0;
    var fs_1 = __require("fs");
    var execAsync_1 = require_execAsync();
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    async function getMachineId() {
      try {
        const result = await fs_1.promises.readFile("/etc/hostid", { encoding: "utf8" });
        return result.trim();
      } catch (e2) {
        api_1.diag.debug(`error reading machine id: ${e2}`);
      }
      try {
        const result = await (0, execAsync_1.execAsync)("kenv -q smbios.system.uuid");
        return result.stdout.trim();
      } catch (e2) {
        api_1.diag.debug(`error reading machine id: ${e2}`);
      }
      return void 0;
    }
    __name(getMachineId, "getMachineId");
    exports2.getMachineId = getMachineId;
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-win.js
var require_getMachineId_win = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-win.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getMachineId = void 0;
    var process51 = __require("process");
    var execAsync_1 = require_execAsync();
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    async function getMachineId() {
      const args = "QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid";
      let command2 = "%windir%\\System32\\REG.exe";
      if (process51.arch === "ia32" && "PROCESSOR_ARCHITEW6432" in process51.env) {
        command2 = "%windir%\\sysnative\\cmd.exe /c " + command2;
      }
      try {
        const result = await (0, execAsync_1.execAsync)(`${command2} ${args}`);
        const parts = result.stdout.split("REG_SZ");
        if (parts.length === 2) {
          return parts[1].trim();
        }
      } catch (e2) {
        api_1.diag.debug(`error reading machine id: ${e2}`);
      }
      return void 0;
    }
    __name(getMachineId, "getMachineId");
    exports2.getMachineId = getMachineId;
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-unsupported.js
var require_getMachineId_unsupported = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-unsupported.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getMachineId = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    async function getMachineId() {
      api_1.diag.debug("could not read machine-id: unsupported platform");
      return void 0;
    }
    __name(getMachineId, "getMachineId");
    exports2.getMachineId = getMachineId;
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId.js
var require_getMachineId = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getMachineId = void 0;
    var process51 = __require("process");
    var getMachineIdImpl;
    async function getMachineId() {
      if (!getMachineIdImpl) {
        switch (process51.platform) {
          case "darwin":
            getMachineIdImpl = (await Promise.resolve().then(() => __toESM(require_getMachineId_darwin()))).getMachineId;
            break;
          case "linux":
            getMachineIdImpl = (await Promise.resolve().then(() => __toESM(require_getMachineId_linux()))).getMachineId;
            break;
          case "freebsd":
            getMachineIdImpl = (await Promise.resolve().then(() => __toESM(require_getMachineId_bsd()))).getMachineId;
            break;
          case "win32":
            getMachineIdImpl = (await Promise.resolve().then(() => __toESM(require_getMachineId_win()))).getMachineId;
            break;
          default:
            getMachineIdImpl = (await Promise.resolve().then(() => __toESM(require_getMachineId_unsupported()))).getMachineId;
            break;
        }
      }
      return getMachineIdImpl();
    }
    __name(getMachineId, "getMachineId");
    exports2.getMachineId = getMachineId;
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/utils.js
var require_utils8 = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.normalizeType = exports2.normalizeArch = void 0;
    var normalizeArch2 = /* @__PURE__ */ __name((nodeArchString) => {
      switch (nodeArchString) {
        case "arm":
          return "arm32";
        case "ppc":
          return "ppc32";
        case "x64":
          return "amd64";
        default:
          return nodeArchString;
      }
    }, "normalizeArch");
    exports2.normalizeArch = normalizeArch2;
    var normalizeType = /* @__PURE__ */ __name((nodePlatform) => {
      switch (nodePlatform) {
        case "sunos":
          return "solaris";
        case "win32":
          return "windows";
        default:
          return nodePlatform;
      }
    }, "normalizeType");
    exports2.normalizeType = normalizeType;
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/HostDetector.js
var require_HostDetector = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/HostDetector.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.hostDetector = void 0;
    var semconv_1 = require_semconv2();
    var os_1 = __require("os");
    var getMachineId_1 = require_getMachineId();
    var utils_1 = require_utils8();
    var HostDetector = class {
      static {
        __name(this, "HostDetector");
      }
      detect(_config) {
        const attributes = {
          [semconv_1.ATTR_HOST_NAME]: (0, os_1.hostname)(),
          [semconv_1.ATTR_HOST_ARCH]: (0, utils_1.normalizeArch)((0, os_1.arch)()),
          [semconv_1.ATTR_HOST_ID]: (0, getMachineId_1.getMachineId)()
        };
        return { attributes };
      }
    };
    exports2.hostDetector = new HostDetector();
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/OSDetector.js
var require_OSDetector = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/OSDetector.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.osDetector = void 0;
    var semconv_1 = require_semconv2();
    var os_1 = __require("os");
    var utils_1 = require_utils8();
    var OSDetector = class {
      static {
        __name(this, "OSDetector");
      }
      detect(_config) {
        const attributes = {
          [semconv_1.ATTR_OS_TYPE]: (0, utils_1.normalizeType)((0, os_1.platform)()),
          [semconv_1.ATTR_OS_VERSION]: (0, os_1.release)()
        };
        return { attributes };
      }
    };
    exports2.osDetector = new OSDetector();
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ProcessDetector.js
var require_ProcessDetector = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ProcessDetector.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.processDetector = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var semconv_1 = require_semconv2();
    var os43 = __require("os");
    var ProcessDetector = class {
      static {
        __name(this, "ProcessDetector");
      }
      detect(_config) {
        const attributes = {
          [semconv_1.ATTR_PROCESS_PID]: process.pid,
          [semconv_1.ATTR_PROCESS_EXECUTABLE_NAME]: process.title,
          [semconv_1.ATTR_PROCESS_EXECUTABLE_PATH]: process.execPath,
          [semconv_1.ATTR_PROCESS_COMMAND_ARGS]: [
            process.argv[0],
            ...process.execArgv,
            ...process.argv.slice(1)
          ],
          [semconv_1.ATTR_PROCESS_RUNTIME_VERSION]: process.versions.node,
          [semconv_1.ATTR_PROCESS_RUNTIME_NAME]: "nodejs",
          [semconv_1.ATTR_PROCESS_RUNTIME_DESCRIPTION]: "Node.js"
        };
        if (process.argv.length > 1) {
          attributes[semconv_1.ATTR_PROCESS_COMMAND] = process.argv[1];
        }
        try {
          const userInfo2 = os43.userInfo();
          attributes[semconv_1.ATTR_PROCESS_OWNER] = userInfo2.username;
        } catch (e2) {
          api_1.diag.debug(`error obtaining process owner: ${e2}`);
        }
        return { attributes };
      }
    };
    exports2.processDetector = new ProcessDetector();
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ServiceInstanceIdDetector.js
var require_ServiceInstanceIdDetector = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ServiceInstanceIdDetector.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.serviceInstanceIdDetector = void 0;
    var semconv_1 = require_semconv2();
    var crypto_1 = __require("crypto");
    var ServiceInstanceIdDetector = class {
      static {
        __name(this, "ServiceInstanceIdDetector");
      }
      detect(_config) {
        return {
          attributes: {
            [semconv_1.ATTR_SERVICE_INSTANCE_ID]: (0, crypto_1.randomUUID)()
          }
        };
      }
    };
    exports2.serviceInstanceIdDetector = new ServiceInstanceIdDetector();
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/index.js
var require_node5 = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.serviceInstanceIdDetector = exports2.processDetector = exports2.osDetector = exports2.hostDetector = void 0;
    var HostDetector_1 = require_HostDetector();
    Object.defineProperty(exports2, "hostDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return HostDetector_1.hostDetector;
    }, "get") });
    var OSDetector_1 = require_OSDetector();
    Object.defineProperty(exports2, "osDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OSDetector_1.osDetector;
    }, "get") });
    var ProcessDetector_1 = require_ProcessDetector();
    Object.defineProperty(exports2, "processDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ProcessDetector_1.processDetector;
    }, "get") });
    var ServiceInstanceIdDetector_1 = require_ServiceInstanceIdDetector();
    Object.defineProperty(exports2, "serviceInstanceIdDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ServiceInstanceIdDetector_1.serviceInstanceIdDetector;
    }, "get") });
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/index.js
var require_platform4 = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.serviceInstanceIdDetector = exports2.processDetector = exports2.osDetector = exports2.hostDetector = void 0;
    var node_1 = require_node5();
    Object.defineProperty(exports2, "hostDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.hostDetector;
    }, "get") });
    Object.defineProperty(exports2, "osDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.osDetector;
    }, "get") });
    Object.defineProperty(exports2, "processDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.processDetector;
    }, "get") });
    Object.defineProperty(exports2, "serviceInstanceIdDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.serviceInstanceIdDetector;
    }, "get") });
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/NoopDetector.js
var require_NoopDetector = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/NoopDetector.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.noopDetector = exports2.NoopDetector = void 0;
    var NoopDetector = class {
      static {
        __name(this, "NoopDetector");
      }
      detect() {
        return {
          attributes: {}
        };
      }
    };
    exports2.NoopDetector = NoopDetector;
    exports2.noopDetector = new NoopDetector();
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/index.js
var require_detectors = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.noopDetector = exports2.serviceInstanceIdDetector = exports2.processDetector = exports2.osDetector = exports2.hostDetector = exports2.envDetector = void 0;
    var EnvDetector_1 = require_EnvDetector();
    Object.defineProperty(exports2, "envDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return EnvDetector_1.envDetector;
    }, "get") });
    var platform_1 = require_platform4();
    Object.defineProperty(exports2, "hostDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.hostDetector;
    }, "get") });
    Object.defineProperty(exports2, "osDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.osDetector;
    }, "get") });
    Object.defineProperty(exports2, "processDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.processDetector;
    }, "get") });
    Object.defineProperty(exports2, "serviceInstanceIdDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.serviceInstanceIdDetector;
    }, "get") });
    var NoopDetector_1 = require_NoopDetector();
    Object.defineProperty(exports2, "noopDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return NoopDetector_1.noopDetector;
    }, "get") });
  }
});

// node_modules/@opentelemetry/resources/build/src/index.js
var require_src13 = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.defaultServiceName = exports2.emptyResource = exports2.defaultResource = exports2.resourceFromAttributes = exports2.serviceInstanceIdDetector = exports2.processDetector = exports2.osDetector = exports2.hostDetector = exports2.envDetector = exports2.detectResources = void 0;
    var detect_resources_1 = require_detect_resources();
    Object.defineProperty(exports2, "detectResources", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return detect_resources_1.detectResources;
    }, "get") });
    var detectors_1 = require_detectors();
    Object.defineProperty(exports2, "envDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return detectors_1.envDetector;
    }, "get") });
    Object.defineProperty(exports2, "hostDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return detectors_1.hostDetector;
    }, "get") });
    Object.defineProperty(exports2, "osDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return detectors_1.osDetector;
    }, "get") });
    Object.defineProperty(exports2, "processDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return detectors_1.processDetector;
    }, "get") });
    Object.defineProperty(exports2, "serviceInstanceIdDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return detectors_1.serviceInstanceIdDetector;
    }, "get") });
    var ResourceImpl_1 = require_ResourceImpl();
    Object.defineProperty(exports2, "resourceFromAttributes", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ResourceImpl_1.resourceFromAttributes;
    }, "get") });
    Object.defineProperty(exports2, "defaultResource", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ResourceImpl_1.defaultResource;
    }, "get") });
    Object.defineProperty(exports2, "emptyResource", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ResourceImpl_1.emptyResource;
    }, "get") });
    var platform_1 = require_platform3();
    Object.defineProperty(exports2, "defaultServiceName", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.defaultServiceName;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/view/ViewRegistry.js
var require_ViewRegistry = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/view/ViewRegistry.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ViewRegistry = void 0;
    var ViewRegistry = class {
      static {
        __name(this, "ViewRegistry");
      }
      _registeredViews = [];
      addView(view) {
        this._registeredViews.push(view);
      }
      findViews(instrument, meter) {
        const views = this._registeredViews.filter((registeredView) => {
          return this._matchInstrument(registeredView.instrumentSelector, instrument) && this._matchMeter(registeredView.meterSelector, meter);
        });
        return views;
      }
      _matchInstrument(selector, instrument) {
        return (selector.getType() === void 0 || instrument.type === selector.getType()) && selector.getNameFilter().match(instrument.name) && selector.getUnitFilter().match(instrument.unit);
      }
      _matchMeter(selector, meter) {
        return selector.getNameFilter().match(meter.name) && (meter.version === void 0 || selector.getVersionFilter().match(meter.version)) && (meter.schemaUrl === void 0 || selector.getSchemaUrlFilter().match(meter.schemaUrl));
      }
    };
    exports2.ViewRegistry = ViewRegistry;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/InstrumentDescriptor.js
var require_InstrumentDescriptor = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/InstrumentDescriptor.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isValidName = exports2.isDescriptorCompatibleWith = exports2.createInstrumentDescriptorWithView = exports2.createInstrumentDescriptor = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var utils_1 = require_utils6();
    function createInstrumentDescriptor(name3, type, options2) {
      if (!isValidName(name3)) {
        api_1.diag.warn(`Invalid metric name: "${name3}". The metric name should be a ASCII string with a length no greater than 255 characters.`);
      }
      return {
        name: name3,
        type,
        description: options2?.description ?? "",
        unit: options2?.unit ?? "",
        valueType: options2?.valueType ?? api_1.ValueType.DOUBLE,
        advice: options2?.advice ?? {}
      };
    }
    __name(createInstrumentDescriptor, "createInstrumentDescriptor");
    exports2.createInstrumentDescriptor = createInstrumentDescriptor;
    function createInstrumentDescriptorWithView(view, instrument) {
      return {
        name: view.name ?? instrument.name,
        description: view.description ?? instrument.description,
        type: instrument.type,
        unit: instrument.unit,
        valueType: instrument.valueType,
        advice: instrument.advice
      };
    }
    __name(createInstrumentDescriptorWithView, "createInstrumentDescriptorWithView");
    exports2.createInstrumentDescriptorWithView = createInstrumentDescriptorWithView;
    function isDescriptorCompatibleWith(descriptor2, otherDescriptor) {
      return (0, utils_1.equalsCaseInsensitive)(descriptor2.name, otherDescriptor.name) && descriptor2.unit === otherDescriptor.unit && descriptor2.type === otherDescriptor.type && descriptor2.valueType === otherDescriptor.valueType;
    }
    __name(isDescriptorCompatibleWith, "isDescriptorCompatibleWith");
    exports2.isDescriptorCompatibleWith = isDescriptorCompatibleWith;
    var NAME_REGEXP = /^[a-z][a-z0-9_.\-/]{0,254}$/i;
    function isValidName(name3) {
      return name3.match(NAME_REGEXP) != null;
    }
    __name(isValidName, "isValidName");
    exports2.isValidName = isValidName;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/Instruments.js
var require_Instruments = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/Instruments.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isObservableInstrument = exports2.ObservableUpDownCounterInstrument = exports2.ObservableGaugeInstrument = exports2.ObservableCounterInstrument = exports2.ObservableInstrument = exports2.HistogramInstrument = exports2.GaugeInstrument = exports2.CounterInstrument = exports2.UpDownCounterInstrument = exports2.SyncInstrument = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var SyncInstrument = class {
      static {
        __name(this, "SyncInstrument");
      }
      _writableMetricStorage;
      _descriptor;
      constructor(_writableMetricStorage, _descriptor) {
        this._writableMetricStorage = _writableMetricStorage;
        this._descriptor = _descriptor;
      }
      _record(value, attributes = {}, context2 = api_1.context.active()) {
        if (typeof value !== "number") {
          api_1.diag.warn(`non-number value provided to metric ${this._descriptor.name}: ${value}`);
          return;
        }
        if (this._descriptor.valueType === api_1.ValueType.INT && !Number.isInteger(value)) {
          api_1.diag.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`);
          value = Math.trunc(value);
          if (!Number.isInteger(value)) {
            return;
          }
        }
        this._writableMetricStorage.record(value, attributes, context2, (0, core_1.millisToHrTime)(Date.now()));
      }
    };
    exports2.SyncInstrument = SyncInstrument;
    var UpDownCounterInstrument = class extends SyncInstrument {
      static {
        __name(this, "UpDownCounterInstrument");
      }
      /**
       * Increment value of counter by the input. Inputs may be negative.
       */
      add(value, attributes, ctx) {
        this._record(value, attributes, ctx);
      }
    };
    exports2.UpDownCounterInstrument = UpDownCounterInstrument;
    var CounterInstrument = class extends SyncInstrument {
      static {
        __name(this, "CounterInstrument");
      }
      /**
       * Increment value of counter by the input. Inputs may not be negative.
       */
      add(value, attributes, ctx) {
        if (value < 0) {
          api_1.diag.warn(`negative value provided to counter ${this._descriptor.name}: ${value}`);
          return;
        }
        this._record(value, attributes, ctx);
      }
    };
    exports2.CounterInstrument = CounterInstrument;
    var GaugeInstrument = class extends SyncInstrument {
      static {
        __name(this, "GaugeInstrument");
      }
      /**
       * Records a measurement.
       */
      record(value, attributes, ctx) {
        this._record(value, attributes, ctx);
      }
    };
    exports2.GaugeInstrument = GaugeInstrument;
    var HistogramInstrument = class extends SyncInstrument {
      static {
        __name(this, "HistogramInstrument");
      }
      /**
       * Records a measurement. Value of the measurement must not be negative.
       */
      record(value, attributes, ctx) {
        if (value < 0) {
          api_1.diag.warn(`negative value provided to histogram ${this._descriptor.name}: ${value}`);
          return;
        }
        this._record(value, attributes, ctx);
      }
    };
    exports2.HistogramInstrument = HistogramInstrument;
    var ObservableInstrument = class {
      static {
        __name(this, "ObservableInstrument");
      }
      _observableRegistry;
      /** @internal */
      _metricStorages;
      /** @internal */
      _descriptor;
      constructor(descriptor2, metricStorages, _observableRegistry) {
        this._observableRegistry = _observableRegistry;
        this._descriptor = descriptor2;
        this._metricStorages = metricStorages;
      }
      /**
       * @see {Observable.addCallback}
       */
      addCallback(callback) {
        this._observableRegistry.addCallback(callback, this);
      }
      /**
       * @see {Observable.removeCallback}
       */
      removeCallback(callback) {
        this._observableRegistry.removeCallback(callback, this);
      }
    };
    exports2.ObservableInstrument = ObservableInstrument;
    var ObservableCounterInstrument = class extends ObservableInstrument {
      static {
        __name(this, "ObservableCounterInstrument");
      }
    };
    exports2.ObservableCounterInstrument = ObservableCounterInstrument;
    var ObservableGaugeInstrument = class extends ObservableInstrument {
      static {
        __name(this, "ObservableGaugeInstrument");
      }
    };
    exports2.ObservableGaugeInstrument = ObservableGaugeInstrument;
    var ObservableUpDownCounterInstrument = class extends ObservableInstrument {
      static {
        __name(this, "ObservableUpDownCounterInstrument");
      }
    };
    exports2.ObservableUpDownCounterInstrument = ObservableUpDownCounterInstrument;
    function isObservableInstrument(it) {
      return it instanceof ObservableInstrument;
    }
    __name(isObservableInstrument, "isObservableInstrument");
    exports2.isObservableInstrument = isObservableInstrument;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/Meter.js
var require_Meter = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/Meter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Meter = void 0;
    var InstrumentDescriptor_1 = require_InstrumentDescriptor();
    var Instruments_1 = require_Instruments();
    var MetricData_1 = require_MetricData();
    var Meter = class {
      static {
        __name(this, "Meter");
      }
      _meterSharedState;
      constructor(_meterSharedState) {
        this._meterSharedState = _meterSharedState;
      }
      /**
       * Create a {@link Gauge} instrument.
       */
      createGauge(name3, options2) {
        const descriptor2 = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name3, MetricData_1.InstrumentType.GAUGE, options2);
        const storage = this._meterSharedState.registerMetricStorage(descriptor2);
        return new Instruments_1.GaugeInstrument(storage, descriptor2);
      }
      /**
       * Create a {@link Histogram} instrument.
       */
      createHistogram(name3, options2) {
        const descriptor2 = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name3, MetricData_1.InstrumentType.HISTOGRAM, options2);
        const storage = this._meterSharedState.registerMetricStorage(descriptor2);
        return new Instruments_1.HistogramInstrument(storage, descriptor2);
      }
      /**
       * Create a {@link Counter} instrument.
       */
      createCounter(name3, options2) {
        const descriptor2 = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name3, MetricData_1.InstrumentType.COUNTER, options2);
        const storage = this._meterSharedState.registerMetricStorage(descriptor2);
        return new Instruments_1.CounterInstrument(storage, descriptor2);
      }
      /**
       * Create a {@link UpDownCounter} instrument.
       */
      createUpDownCounter(name3, options2) {
        const descriptor2 = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name3, MetricData_1.InstrumentType.UP_DOWN_COUNTER, options2);
        const storage = this._meterSharedState.registerMetricStorage(descriptor2);
        return new Instruments_1.UpDownCounterInstrument(storage, descriptor2);
      }
      /**
       * Create a {@link ObservableGauge} instrument.
       */
      createObservableGauge(name3, options2) {
        const descriptor2 = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name3, MetricData_1.InstrumentType.OBSERVABLE_GAUGE, options2);
        const storages = this._meterSharedState.registerAsyncMetricStorage(descriptor2);
        return new Instruments_1.ObservableGaugeInstrument(descriptor2, storages, this._meterSharedState.observableRegistry);
      }
      /**
       * Create a {@link ObservableCounter} instrument.
       */
      createObservableCounter(name3, options2) {
        const descriptor2 = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name3, MetricData_1.InstrumentType.OBSERVABLE_COUNTER, options2);
        const storages = this._meterSharedState.registerAsyncMetricStorage(descriptor2);
        return new Instruments_1.ObservableCounterInstrument(descriptor2, storages, this._meterSharedState.observableRegistry);
      }
      /**
       * Create a {@link ObservableUpDownCounter} instrument.
       */
      createObservableUpDownCounter(name3, options2) {
        const descriptor2 = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name3, MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER, options2);
        const storages = this._meterSharedState.registerAsyncMetricStorage(descriptor2);
        return new Instruments_1.ObservableUpDownCounterInstrument(descriptor2, storages, this._meterSharedState.observableRegistry);
      }
      /**
       * @see {@link Meter.addBatchObservableCallback}
       */
      addBatchObservableCallback(callback, observables) {
        this._meterSharedState.observableRegistry.addBatchCallback(callback, observables);
      }
      /**
       * @see {@link Meter.removeBatchObservableCallback}
       */
      removeBatchObservableCallback(callback, observables) {
        this._meterSharedState.observableRegistry.removeBatchCallback(callback, observables);
      }
    };
    exports2.Meter = Meter;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorage.js
var require_MetricStorage = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorage.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MetricStorage = void 0;
    var InstrumentDescriptor_1 = require_InstrumentDescriptor();
    var MetricStorage = class {
      static {
        __name(this, "MetricStorage");
      }
      _instrumentDescriptor;
      constructor(_instrumentDescriptor) {
        this._instrumentDescriptor = _instrumentDescriptor;
      }
      getInstrumentDescriptor() {
        return this._instrumentDescriptor;
      }
      updateDescription(description) {
        this._instrumentDescriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(this._instrumentDescriptor.name, this._instrumentDescriptor.type, {
          description,
          valueType: this._instrumentDescriptor.valueType,
          unit: this._instrumentDescriptor.unit,
          advice: this._instrumentDescriptor.advice
        });
      }
    };
    exports2.MetricStorage = MetricStorage;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/HashMap.js
var require_HashMap = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/HashMap.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AttributeHashMap = exports2.HashMap = void 0;
    var utils_1 = require_utils6();
    var HashMap = class {
      static {
        __name(this, "HashMap");
      }
      _hash;
      _valueMap = /* @__PURE__ */ new Map();
      _keyMap = /* @__PURE__ */ new Map();
      constructor(_hash) {
        this._hash = _hash;
      }
      get(key, hashCode) {
        hashCode ??= this._hash(key);
        return this._valueMap.get(hashCode);
      }
      getOrDefault(key, defaultFactory) {
        const hash = this._hash(key);
        if (this._valueMap.has(hash)) {
          return this._valueMap.get(hash);
        }
        const val = defaultFactory();
        if (!this._keyMap.has(hash)) {
          this._keyMap.set(hash, key);
        }
        this._valueMap.set(hash, val);
        return val;
      }
      set(key, value, hashCode) {
        hashCode ??= this._hash(key);
        if (!this._keyMap.has(hashCode)) {
          this._keyMap.set(hashCode, key);
        }
        this._valueMap.set(hashCode, value);
      }
      has(key, hashCode) {
        hashCode ??= this._hash(key);
        return this._valueMap.has(hashCode);
      }
      *keys() {
        const keyIterator = this._keyMap.entries();
        let next = keyIterator.next();
        while (next.done !== true) {
          yield [next.value[1], next.value[0]];
          next = keyIterator.next();
        }
      }
      *entries() {
        const valueIterator = this._valueMap.entries();
        let next = valueIterator.next();
        while (next.done !== true) {
          yield [this._keyMap.get(next.value[0]), next.value[1], next.value[0]];
          next = valueIterator.next();
        }
      }
      get size() {
        return this._valueMap.size;
      }
    };
    exports2.HashMap = HashMap;
    var AttributeHashMap = class extends HashMap {
      static {
        __name(this, "AttributeHashMap");
      }
      constructor() {
        super(utils_1.hashAttributes);
      }
    };
    exports2.AttributeHashMap = AttributeHashMap;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/DeltaMetricProcessor.js
var require_DeltaMetricProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/DeltaMetricProcessor.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DeltaMetricProcessor = void 0;
    var utils_1 = require_utils6();
    var HashMap_1 = require_HashMap();
    var DeltaMetricProcessor = class {
      static {
        __name(this, "DeltaMetricProcessor");
      }
      _aggregator;
      _activeCollectionStorage = new HashMap_1.AttributeHashMap();
      // TODO: find a reasonable mean to clean the memo;
      // https://github.com/open-telemetry/opentelemetry-specification/pull/2208
      _cumulativeMemoStorage = new HashMap_1.AttributeHashMap();
      _cardinalityLimit;
      _overflowAttributes = { "otel.metric.overflow": true };
      _overflowHashCode;
      constructor(_aggregator, aggregationCardinalityLimit) {
        this._aggregator = _aggregator;
        this._cardinalityLimit = (aggregationCardinalityLimit ?? 2e3) - 1;
        this._overflowHashCode = (0, utils_1.hashAttributes)(this._overflowAttributes);
      }
      record(value, attributes, _context, collectionTime) {
        let accumulation = this._activeCollectionStorage.get(attributes);
        if (!accumulation) {
          if (this._activeCollectionStorage.size >= this._cardinalityLimit) {
            const overflowAccumulation = this._activeCollectionStorage.getOrDefault(this._overflowAttributes, () => this._aggregator.createAccumulation(collectionTime));
            overflowAccumulation?.record(value);
            return;
          }
          accumulation = this._aggregator.createAccumulation(collectionTime);
          this._activeCollectionStorage.set(attributes, accumulation);
        }
        accumulation?.record(value);
      }
      batchCumulate(measurements, collectionTime) {
        Array.from(measurements.entries()).forEach(([attributes, value, hashCode]) => {
          const accumulation = this._aggregator.createAccumulation(collectionTime);
          accumulation?.record(value);
          let delta = accumulation;
          if (this._cumulativeMemoStorage.has(attributes, hashCode)) {
            const previous = this._cumulativeMemoStorage.get(attributes, hashCode);
            delta = this._aggregator.diff(previous, accumulation);
          } else {
            if (this._cumulativeMemoStorage.size >= this._cardinalityLimit) {
              attributes = this._overflowAttributes;
              hashCode = this._overflowHashCode;
              if (this._cumulativeMemoStorage.has(attributes, hashCode)) {
                const previous = this._cumulativeMemoStorage.get(attributes, hashCode);
                delta = this._aggregator.diff(previous, accumulation);
              }
            }
          }
          if (this._activeCollectionStorage.has(attributes, hashCode)) {
            const active = this._activeCollectionStorage.get(attributes, hashCode);
            delta = this._aggregator.merge(active, delta);
          }
          this._cumulativeMemoStorage.set(attributes, accumulation, hashCode);
          this._activeCollectionStorage.set(attributes, delta, hashCode);
        });
      }
      /**
       * Returns a collection of delta metrics. Start time is the when first
       * time event collected.
       */
      collect() {
        const unreportedDelta = this._activeCollectionStorage;
        this._activeCollectionStorage = new HashMap_1.AttributeHashMap();
        return unreportedDelta;
      }
    };
    exports2.DeltaMetricProcessor = DeltaMetricProcessor;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/TemporalMetricProcessor.js
var require_TemporalMetricProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/TemporalMetricProcessor.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.TemporalMetricProcessor = void 0;
    var AggregationTemporality_1 = require_AggregationTemporality();
    var HashMap_1 = require_HashMap();
    var TemporalMetricProcessor = class _TemporalMetricProcessor {
      static {
        __name(this, "TemporalMetricProcessor");
      }
      _aggregator;
      _unreportedAccumulations = /* @__PURE__ */ new Map();
      _reportHistory = /* @__PURE__ */ new Map();
      constructor(_aggregator, collectorHandles) {
        this._aggregator = _aggregator;
        collectorHandles.forEach((handle) => {
          this._unreportedAccumulations.set(handle, []);
        });
      }
      /**
       * Builds the {@link MetricData} streams to report against a specific MetricCollector.
       * @param collector The information of the MetricCollector.
       * @param collectors The registered collectors.
       * @param instrumentDescriptor The instrumentation descriptor that these metrics generated with.
       * @param currentAccumulations The current accumulation of metric data from instruments.
       * @param collectionTime The current collection timestamp.
       * @returns The {@link MetricData} points or `null`.
       */
      buildMetrics(collector, instrumentDescriptor, currentAccumulations, collectionTime) {
        this._stashAccumulations(currentAccumulations);
        const unreportedAccumulations = this._getMergedUnreportedAccumulations(collector);
        let result = unreportedAccumulations;
        let aggregationTemporality;
        if (this._reportHistory.has(collector)) {
          const last2 = this._reportHistory.get(collector);
          const lastCollectionTime = last2.collectionTime;
          aggregationTemporality = last2.aggregationTemporality;
          if (aggregationTemporality === AggregationTemporality_1.AggregationTemporality.CUMULATIVE) {
            result = _TemporalMetricProcessor.merge(last2.accumulations, unreportedAccumulations, this._aggregator);
          } else {
            result = _TemporalMetricProcessor.calibrateStartTime(last2.accumulations, unreportedAccumulations, lastCollectionTime);
          }
        } else {
          aggregationTemporality = collector.selectAggregationTemporality(instrumentDescriptor.type);
        }
        this._reportHistory.set(collector, {
          accumulations: result,
          collectionTime,
          aggregationTemporality
        });
        const accumulationRecords = AttributesMapToAccumulationRecords(result);
        if (accumulationRecords.length === 0) {
          return void 0;
        }
        return this._aggregator.toMetricData(
          instrumentDescriptor,
          aggregationTemporality,
          accumulationRecords,
          /* endTime */
          collectionTime
        );
      }
      _stashAccumulations(currentAccumulation) {
        const registeredCollectors = this._unreportedAccumulations.keys();
        for (const collector of registeredCollectors) {
          let stash = this._unreportedAccumulations.get(collector);
          if (stash === void 0) {
            stash = [];
            this._unreportedAccumulations.set(collector, stash);
          }
          stash.push(currentAccumulation);
        }
      }
      _getMergedUnreportedAccumulations(collector) {
        let result = new HashMap_1.AttributeHashMap();
        const unreportedList = this._unreportedAccumulations.get(collector);
        this._unreportedAccumulations.set(collector, []);
        if (unreportedList === void 0) {
          return result;
        }
        for (const it of unreportedList) {
          result = _TemporalMetricProcessor.merge(result, it, this._aggregator);
        }
        return result;
      }
      static merge(last2, current, aggregator) {
        const result = last2;
        const iterator = current.entries();
        let next = iterator.next();
        while (next.done !== true) {
          const [key, record, hash] = next.value;
          if (last2.has(key, hash)) {
            const lastAccumulation = last2.get(key, hash);
            const accumulation = aggregator.merge(lastAccumulation, record);
            result.set(key, accumulation, hash);
          } else {
            result.set(key, record, hash);
          }
          next = iterator.next();
        }
        return result;
      }
      /**
       * Calibrate the reported metric streams' startTime to lastCollectionTime. Leaves
       * the new stream to be the initial observation time unchanged.
       */
      static calibrateStartTime(last2, current, lastCollectionTime) {
        for (const [key, hash] of last2.keys()) {
          const currentAccumulation = current.get(key, hash);
          currentAccumulation?.setStartTime(lastCollectionTime);
        }
        return current;
      }
    };
    exports2.TemporalMetricProcessor = TemporalMetricProcessor;
    function AttributesMapToAccumulationRecords(map2) {
      return Array.from(map2.entries());
    }
    __name(AttributesMapToAccumulationRecords, "AttributesMapToAccumulationRecords");
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/AsyncMetricStorage.js
var require_AsyncMetricStorage = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/AsyncMetricStorage.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AsyncMetricStorage = void 0;
    var MetricStorage_1 = require_MetricStorage();
    var DeltaMetricProcessor_1 = require_DeltaMetricProcessor();
    var TemporalMetricProcessor_1 = require_TemporalMetricProcessor();
    var HashMap_1 = require_HashMap();
    var AsyncMetricStorage = class extends MetricStorage_1.MetricStorage {
      static {
        __name(this, "AsyncMetricStorage");
      }
      _attributesProcessor;
      _aggregationCardinalityLimit;
      _deltaMetricStorage;
      _temporalMetricStorage;
      constructor(_instrumentDescriptor, aggregator, _attributesProcessor, collectorHandles, _aggregationCardinalityLimit) {
        super(_instrumentDescriptor);
        this._attributesProcessor = _attributesProcessor;
        this._aggregationCardinalityLimit = _aggregationCardinalityLimit;
        this._deltaMetricStorage = new DeltaMetricProcessor_1.DeltaMetricProcessor(aggregator, this._aggregationCardinalityLimit);
        this._temporalMetricStorage = new TemporalMetricProcessor_1.TemporalMetricProcessor(aggregator, collectorHandles);
      }
      record(measurements, observationTime) {
        const processed = new HashMap_1.AttributeHashMap();
        Array.from(measurements.entries()).forEach(([attributes, value]) => {
          processed.set(this._attributesProcessor.process(attributes), value);
        });
        this._deltaMetricStorage.batchCumulate(processed, observationTime);
      }
      /**
       * Collects the metrics from this storage. The ObservableCallback is invoked
       * during the collection.
       *
       * Note: This is a stateful operation and may reset any interval-related
       * state for the MetricCollector.
       */
      collect(collector, collectionTime) {
        const accumulations = this._deltaMetricStorage.collect();
        return this._temporalMetricStorage.buildMetrics(collector, this._instrumentDescriptor, accumulations, collectionTime);
      }
    };
    exports2.AsyncMetricStorage = AsyncMetricStorage;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/view/RegistrationConflicts.js
var require_RegistrationConflicts = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/view/RegistrationConflicts.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getConflictResolutionRecipe = exports2.getDescriptionResolutionRecipe = exports2.getTypeConflictResolutionRecipe = exports2.getUnitConflictResolutionRecipe = exports2.getValueTypeConflictResolutionRecipe = exports2.getIncompatibilityDetails = void 0;
    function getIncompatibilityDetails(existing, otherDescriptor) {
      let incompatibility = "";
      if (existing.unit !== otherDescriptor.unit) {
        incompatibility += `	- Unit '${existing.unit}' does not match '${otherDescriptor.unit}'
`;
      }
      if (existing.type !== otherDescriptor.type) {
        incompatibility += `	- Type '${existing.type}' does not match '${otherDescriptor.type}'
`;
      }
      if (existing.valueType !== otherDescriptor.valueType) {
        incompatibility += `	- Value Type '${existing.valueType}' does not match '${otherDescriptor.valueType}'
`;
      }
      if (existing.description !== otherDescriptor.description) {
        incompatibility += `	- Description '${existing.description}' does not match '${otherDescriptor.description}'
`;
      }
      return incompatibility;
    }
    __name(getIncompatibilityDetails, "getIncompatibilityDetails");
    exports2.getIncompatibilityDetails = getIncompatibilityDetails;
    function getValueTypeConflictResolutionRecipe(existing, otherDescriptor) {
      return `	- use valueType '${existing.valueType}' on instrument creation or use an instrument name other than '${otherDescriptor.name}'`;
    }
    __name(getValueTypeConflictResolutionRecipe, "getValueTypeConflictResolutionRecipe");
    exports2.getValueTypeConflictResolutionRecipe = getValueTypeConflictResolutionRecipe;
    function getUnitConflictResolutionRecipe(existing, otherDescriptor) {
      return `	- use unit '${existing.unit}' on instrument creation or use an instrument name other than '${otherDescriptor.name}'`;
    }
    __name(getUnitConflictResolutionRecipe, "getUnitConflictResolutionRecipe");
    exports2.getUnitConflictResolutionRecipe = getUnitConflictResolutionRecipe;
    function getTypeConflictResolutionRecipe(existing, otherDescriptor) {
      const selector = {
        name: otherDescriptor.name,
        type: otherDescriptor.type,
        unit: otherDescriptor.unit
      };
      const selectorString = JSON.stringify(selector);
      return `	- create a new view with a name other than '${existing.name}' and InstrumentSelector '${selectorString}'`;
    }
    __name(getTypeConflictResolutionRecipe, "getTypeConflictResolutionRecipe");
    exports2.getTypeConflictResolutionRecipe = getTypeConflictResolutionRecipe;
    function getDescriptionResolutionRecipe(existing, otherDescriptor) {
      const selector = {
        name: otherDescriptor.name,
        type: otherDescriptor.type,
        unit: otherDescriptor.unit
      };
      const selectorString = JSON.stringify(selector);
      return `	- create a new view with a name other than '${existing.name}' and InstrumentSelector '${selectorString}'
    	- OR - create a new view with the name ${existing.name} and description '${existing.description}' and InstrumentSelector ${selectorString}
    	- OR - create a new view with the name ${otherDescriptor.name} and description '${existing.description}' and InstrumentSelector ${selectorString}`;
    }
    __name(getDescriptionResolutionRecipe, "getDescriptionResolutionRecipe");
    exports2.getDescriptionResolutionRecipe = getDescriptionResolutionRecipe;
    function getConflictResolutionRecipe(existing, otherDescriptor) {
      if (existing.valueType !== otherDescriptor.valueType) {
        return getValueTypeConflictResolutionRecipe(existing, otherDescriptor);
      }
      if (existing.unit !== otherDescriptor.unit) {
        return getUnitConflictResolutionRecipe(existing, otherDescriptor);
      }
      if (existing.type !== otherDescriptor.type) {
        return getTypeConflictResolutionRecipe(existing, otherDescriptor);
      }
      if (existing.description !== otherDescriptor.description) {
        return getDescriptionResolutionRecipe(existing, otherDescriptor);
      }
      return "";
    }
    __name(getConflictResolutionRecipe, "getConflictResolutionRecipe");
    exports2.getConflictResolutionRecipe = getConflictResolutionRecipe;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorageRegistry.js
var require_MetricStorageRegistry = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorageRegistry.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MetricStorageRegistry = void 0;
    var InstrumentDescriptor_1 = require_InstrumentDescriptor();
    var api = (init_esm2(), __toCommonJS(esm_exports2));
    var RegistrationConflicts_1 = require_RegistrationConflicts();
    var MetricStorageRegistry = class _MetricStorageRegistry {
      static {
        __name(this, "MetricStorageRegistry");
      }
      _sharedRegistry = /* @__PURE__ */ new Map();
      _perCollectorRegistry = /* @__PURE__ */ new Map();
      static create() {
        return new _MetricStorageRegistry();
      }
      getStorages(collector) {
        let storages = [];
        for (const metricStorages of this._sharedRegistry.values()) {
          storages = storages.concat(metricStorages);
        }
        const perCollectorStorages = this._perCollectorRegistry.get(collector);
        if (perCollectorStorages != null) {
          for (const metricStorages of perCollectorStorages.values()) {
            storages = storages.concat(metricStorages);
          }
        }
        return storages;
      }
      register(storage) {
        this._registerStorage(storage, this._sharedRegistry);
      }
      registerForCollector(collector, storage) {
        let storageMap = this._perCollectorRegistry.get(collector);
        if (storageMap == null) {
          storageMap = /* @__PURE__ */ new Map();
          this._perCollectorRegistry.set(collector, storageMap);
        }
        this._registerStorage(storage, storageMap);
      }
      findOrUpdateCompatibleStorage(expectedDescriptor) {
        const storages = this._sharedRegistry.get(expectedDescriptor.name);
        if (storages === void 0) {
          return null;
        }
        return this._findOrUpdateCompatibleStorage(expectedDescriptor, storages);
      }
      findOrUpdateCompatibleCollectorStorage(collector, expectedDescriptor) {
        const storageMap = this._perCollectorRegistry.get(collector);
        if (storageMap === void 0) {
          return null;
        }
        const storages = storageMap.get(expectedDescriptor.name);
        if (storages === void 0) {
          return null;
        }
        return this._findOrUpdateCompatibleStorage(expectedDescriptor, storages);
      }
      _registerStorage(storage, storageMap) {
        const descriptor2 = storage.getInstrumentDescriptor();
        const storages = storageMap.get(descriptor2.name);
        if (storages === void 0) {
          storageMap.set(descriptor2.name, [storage]);
          return;
        }
        storages.push(storage);
      }
      _findOrUpdateCompatibleStorage(expectedDescriptor, existingStorages) {
        let compatibleStorage = null;
        for (const existingStorage of existingStorages) {
          const existingDescriptor = existingStorage.getInstrumentDescriptor();
          if ((0, InstrumentDescriptor_1.isDescriptorCompatibleWith)(existingDescriptor, expectedDescriptor)) {
            if (existingDescriptor.description !== expectedDescriptor.description) {
              if (expectedDescriptor.description.length > existingDescriptor.description.length) {
                existingStorage.updateDescription(expectedDescriptor.description);
              }
              api.diag.warn("A view or instrument with the name ", expectedDescriptor.name, " has already been registered, but has a different description and is incompatible with another registered view.\n", "Details:\n", (0, RegistrationConflicts_1.getIncompatibilityDetails)(existingDescriptor, expectedDescriptor), "The longer description will be used.\nTo resolve the conflict:", (0, RegistrationConflicts_1.getConflictResolutionRecipe)(existingDescriptor, expectedDescriptor));
            }
            compatibleStorage = existingStorage;
          } else {
            api.diag.warn("A view or instrument with the name ", expectedDescriptor.name, " has already been registered and is incompatible with another registered view.\n", "Details:\n", (0, RegistrationConflicts_1.getIncompatibilityDetails)(existingDescriptor, expectedDescriptor), "To resolve the conflict:\n", (0, RegistrationConflicts_1.getConflictResolutionRecipe)(existingDescriptor, expectedDescriptor));
          }
        }
        return compatibleStorage;
      }
    };
    exports2.MetricStorageRegistry = MetricStorageRegistry;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/MultiWritableMetricStorage.js
var require_MultiWritableMetricStorage = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/MultiWritableMetricStorage.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MultiMetricStorage = void 0;
    var MultiMetricStorage = class {
      static {
        __name(this, "MultiMetricStorage");
      }
      _backingStorages;
      constructor(_backingStorages) {
        this._backingStorages = _backingStorages;
      }
      record(value, attributes, context2, recordTime) {
        this._backingStorages.forEach((it) => {
          it.record(value, attributes, context2, recordTime);
        });
      }
    };
    exports2.MultiMetricStorage = MultiMetricStorage;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/ObservableResult.js
var require_ObservableResult = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/ObservableResult.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BatchObservableResultImpl = exports2.ObservableResultImpl = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var HashMap_1 = require_HashMap();
    var Instruments_1 = require_Instruments();
    var ObservableResultImpl = class {
      static {
        __name(this, "ObservableResultImpl");
      }
      _instrumentName;
      _valueType;
      /**
       * @internal
       */
      _buffer = new HashMap_1.AttributeHashMap();
      constructor(_instrumentName, _valueType) {
        this._instrumentName = _instrumentName;
        this._valueType = _valueType;
      }
      /**
       * Observe a measurement of the value associated with the given attributes.
       */
      observe(value, attributes = {}) {
        if (typeof value !== "number") {
          api_1.diag.warn(`non-number value provided to metric ${this._instrumentName}: ${value}`);
          return;
        }
        if (this._valueType === api_1.ValueType.INT && !Number.isInteger(value)) {
          api_1.diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`);
          value = Math.trunc(value);
          if (!Number.isInteger(value)) {
            return;
          }
        }
        this._buffer.set(attributes, value);
      }
    };
    exports2.ObservableResultImpl = ObservableResultImpl;
    var BatchObservableResultImpl = class {
      static {
        __name(this, "BatchObservableResultImpl");
      }
      /**
       * @internal
       */
      _buffer = /* @__PURE__ */ new Map();
      /**
       * Observe a measurement of the value associated with the given attributes.
       */
      observe(metric, value, attributes = {}) {
        if (!(0, Instruments_1.isObservableInstrument)(metric)) {
          return;
        }
        let map2 = this._buffer.get(metric);
        if (map2 == null) {
          map2 = new HashMap_1.AttributeHashMap();
          this._buffer.set(metric, map2);
        }
        if (typeof value !== "number") {
          api_1.diag.warn(`non-number value provided to metric ${metric._descriptor.name}: ${value}`);
          return;
        }
        if (metric._descriptor.valueType === api_1.ValueType.INT && !Number.isInteger(value)) {
          api_1.diag.warn(`INT value type cannot accept a floating-point value for ${metric._descriptor.name}, ignoring the fractional digits.`);
          value = Math.trunc(value);
          if (!Number.isInteger(value)) {
            return;
          }
        }
        map2.set(attributes, value);
      }
    };
    exports2.BatchObservableResultImpl = BatchObservableResultImpl;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/ObservableRegistry.js
var require_ObservableRegistry = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/ObservableRegistry.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ObservableRegistry = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var Instruments_1 = require_Instruments();
    var ObservableResult_1 = require_ObservableResult();
    var utils_1 = require_utils6();
    var ObservableRegistry = class {
      static {
        __name(this, "ObservableRegistry");
      }
      _callbacks = [];
      _batchCallbacks = [];
      addCallback(callback, instrument) {
        const idx = this._findCallback(callback, instrument);
        if (idx >= 0) {
          return;
        }
        this._callbacks.push({ callback, instrument });
      }
      removeCallback(callback, instrument) {
        const idx = this._findCallback(callback, instrument);
        if (idx < 0) {
          return;
        }
        this._callbacks.splice(idx, 1);
      }
      addBatchCallback(callback, instruments) {
        const observableInstruments = new Set(instruments.filter(Instruments_1.isObservableInstrument));
        if (observableInstruments.size === 0) {
          api_1.diag.error("BatchObservableCallback is not associated with valid instruments", instruments);
          return;
        }
        const idx = this._findBatchCallback(callback, observableInstruments);
        if (idx >= 0) {
          return;
        }
        this._batchCallbacks.push({ callback, instruments: observableInstruments });
      }
      removeBatchCallback(callback, instruments) {
        const observableInstruments = new Set(instruments.filter(Instruments_1.isObservableInstrument));
        const idx = this._findBatchCallback(callback, observableInstruments);
        if (idx < 0) {
          return;
        }
        this._batchCallbacks.splice(idx, 1);
      }
      /**
       * @returns a promise of rejected reasons for invoking callbacks.
       */
      async observe(collectionTime, timeoutMillis) {
        const callbackFutures = this._observeCallbacks(collectionTime, timeoutMillis);
        const batchCallbackFutures = this._observeBatchCallbacks(collectionTime, timeoutMillis);
        const results = await (0, utils_1.PromiseAllSettled)([
          ...callbackFutures,
          ...batchCallbackFutures
        ]);
        const rejections = results.filter(utils_1.isPromiseAllSettledRejectionResult).map((it) => it.reason);
        return rejections;
      }
      _observeCallbacks(observationTime, timeoutMillis) {
        return this._callbacks.map(async ({ callback, instrument }) => {
          const observableResult = new ObservableResult_1.ObservableResultImpl(instrument._descriptor.name, instrument._descriptor.valueType);
          let callPromise = Promise.resolve(callback(observableResult));
          if (timeoutMillis != null) {
            callPromise = (0, utils_1.callWithTimeout)(callPromise, timeoutMillis);
          }
          await callPromise;
          instrument._metricStorages.forEach((metricStorage) => {
            metricStorage.record(observableResult._buffer, observationTime);
          });
        });
      }
      _observeBatchCallbacks(observationTime, timeoutMillis) {
        return this._batchCallbacks.map(async ({ callback, instruments }) => {
          const observableResult = new ObservableResult_1.BatchObservableResultImpl();
          let callPromise = Promise.resolve(callback(observableResult));
          if (timeoutMillis != null) {
            callPromise = (0, utils_1.callWithTimeout)(callPromise, timeoutMillis);
          }
          await callPromise;
          instruments.forEach((instrument) => {
            const buffer = observableResult._buffer.get(instrument);
            if (buffer == null) {
              return;
            }
            instrument._metricStorages.forEach((metricStorage) => {
              metricStorage.record(buffer, observationTime);
            });
          });
        });
      }
      _findCallback(callback, instrument) {
        return this._callbacks.findIndex((record) => {
          return record.callback === callback && record.instrument === instrument;
        });
      }
      _findBatchCallback(callback, instruments) {
        return this._batchCallbacks.findIndex((record) => {
          return record.callback === callback && (0, utils_1.setEquals)(record.instruments, instruments);
        });
      }
    };
    exports2.ObservableRegistry = ObservableRegistry;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/SyncMetricStorage.js
var require_SyncMetricStorage = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/SyncMetricStorage.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SyncMetricStorage = void 0;
    var MetricStorage_1 = require_MetricStorage();
    var DeltaMetricProcessor_1 = require_DeltaMetricProcessor();
    var TemporalMetricProcessor_1 = require_TemporalMetricProcessor();
    var SyncMetricStorage = class extends MetricStorage_1.MetricStorage {
      static {
        __name(this, "SyncMetricStorage");
      }
      _attributesProcessor;
      _aggregationCardinalityLimit;
      _deltaMetricStorage;
      _temporalMetricStorage;
      constructor(instrumentDescriptor, aggregator, _attributesProcessor, collectorHandles, _aggregationCardinalityLimit) {
        super(instrumentDescriptor);
        this._attributesProcessor = _attributesProcessor;
        this._aggregationCardinalityLimit = _aggregationCardinalityLimit;
        this._deltaMetricStorage = new DeltaMetricProcessor_1.DeltaMetricProcessor(aggregator, this._aggregationCardinalityLimit);
        this._temporalMetricStorage = new TemporalMetricProcessor_1.TemporalMetricProcessor(aggregator, collectorHandles);
      }
      record(value, attributes, context2, recordTime) {
        attributes = this._attributesProcessor.process(attributes, context2);
        this._deltaMetricStorage.record(value, attributes, context2, recordTime);
      }
      /**
       * Collects the metrics from this storage.
       *
       * Note: This is a stateful operation and may reset any interval-related
       * state for the MetricCollector.
       */
      collect(collector, collectionTime) {
        const accumulations = this._deltaMetricStorage.collect();
        return this._temporalMetricStorage.buildMetrics(collector, this._instrumentDescriptor, accumulations, collectionTime);
      }
    };
    exports2.SyncMetricStorage = SyncMetricStorage;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/view/AttributesProcessor.js
var require_AttributesProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/view/AttributesProcessor.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createDenyListAttributesProcessor = exports2.createAllowListAttributesProcessor = exports2.createMultiAttributesProcessor = exports2.createNoopAttributesProcessor = void 0;
    var NoopAttributesProcessor = class {
      static {
        __name(this, "NoopAttributesProcessor");
      }
      process(incoming, _context) {
        return incoming;
      }
    };
    var MultiAttributesProcessor = class {
      static {
        __name(this, "MultiAttributesProcessor");
      }
      _processors;
      constructor(_processors) {
        this._processors = _processors;
      }
      process(incoming, context2) {
        let filteredAttributes = incoming;
        for (const processor of this._processors) {
          filteredAttributes = processor.process(filteredAttributes, context2);
        }
        return filteredAttributes;
      }
    };
    var AllowListProcessor = class {
      static {
        __name(this, "AllowListProcessor");
      }
      _allowedAttributeNames;
      constructor(_allowedAttributeNames) {
        this._allowedAttributeNames = _allowedAttributeNames;
      }
      process(incoming, _context) {
        const filteredAttributes = {};
        Object.keys(incoming).filter((attributeName) => this._allowedAttributeNames.includes(attributeName)).forEach((attributeName) => filteredAttributes[attributeName] = incoming[attributeName]);
        return filteredAttributes;
      }
    };
    var DenyListProcessor = class {
      static {
        __name(this, "DenyListProcessor");
      }
      _deniedAttributeNames;
      constructor(_deniedAttributeNames) {
        this._deniedAttributeNames = _deniedAttributeNames;
      }
      process(incoming, _context) {
        const filteredAttributes = {};
        Object.keys(incoming).filter((attributeName) => !this._deniedAttributeNames.includes(attributeName)).forEach((attributeName) => filteredAttributes[attributeName] = incoming[attributeName]);
        return filteredAttributes;
      }
    };
    function createNoopAttributesProcessor() {
      return NOOP3;
    }
    __name(createNoopAttributesProcessor, "createNoopAttributesProcessor");
    exports2.createNoopAttributesProcessor = createNoopAttributesProcessor;
    function createMultiAttributesProcessor(processors) {
      return new MultiAttributesProcessor(processors);
    }
    __name(createMultiAttributesProcessor, "createMultiAttributesProcessor");
    exports2.createMultiAttributesProcessor = createMultiAttributesProcessor;
    function createAllowListAttributesProcessor(attributeAllowList) {
      return new AllowListProcessor(attributeAllowList);
    }
    __name(createAllowListAttributesProcessor, "createAllowListAttributesProcessor");
    exports2.createAllowListAttributesProcessor = createAllowListAttributesProcessor;
    function createDenyListAttributesProcessor(attributeDenyList) {
      return new DenyListProcessor(attributeDenyList);
    }
    __name(createDenyListAttributesProcessor, "createDenyListAttributesProcessor");
    exports2.createDenyListAttributesProcessor = createDenyListAttributesProcessor;
    var NOOP3 = new NoopAttributesProcessor();
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterSharedState.js
var require_MeterSharedState = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterSharedState.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MeterSharedState = void 0;
    var InstrumentDescriptor_1 = require_InstrumentDescriptor();
    var Meter_1 = require_Meter();
    var utils_1 = require_utils6();
    var AsyncMetricStorage_1 = require_AsyncMetricStorage();
    var MetricStorageRegistry_1 = require_MetricStorageRegistry();
    var MultiWritableMetricStorage_1 = require_MultiWritableMetricStorage();
    var ObservableRegistry_1 = require_ObservableRegistry();
    var SyncMetricStorage_1 = require_SyncMetricStorage();
    var AttributesProcessor_1 = require_AttributesProcessor();
    var MeterSharedState = class {
      static {
        __name(this, "MeterSharedState");
      }
      _meterProviderSharedState;
      _instrumentationScope;
      metricStorageRegistry = new MetricStorageRegistry_1.MetricStorageRegistry();
      observableRegistry = new ObservableRegistry_1.ObservableRegistry();
      meter;
      constructor(_meterProviderSharedState, _instrumentationScope) {
        this._meterProviderSharedState = _meterProviderSharedState;
        this._instrumentationScope = _instrumentationScope;
        this.meter = new Meter_1.Meter(this);
      }
      registerMetricStorage(descriptor2) {
        const storages = this._registerMetricStorage(descriptor2, SyncMetricStorage_1.SyncMetricStorage);
        if (storages.length === 1) {
          return storages[0];
        }
        return new MultiWritableMetricStorage_1.MultiMetricStorage(storages);
      }
      registerAsyncMetricStorage(descriptor2) {
        const storages = this._registerMetricStorage(descriptor2, AsyncMetricStorage_1.AsyncMetricStorage);
        return storages;
      }
      /**
       * @param collector opaque handle of {@link MetricCollector} which initiated the collection.
       * @param collectionTime the HrTime at which the collection was initiated.
       * @param options options for collection.
       * @returns the list of metric data collected.
       */
      async collect(collector, collectionTime, options2) {
        const errors = await this.observableRegistry.observe(collectionTime, options2?.timeoutMillis);
        const storages = this.metricStorageRegistry.getStorages(collector);
        if (storages.length === 0) {
          return null;
        }
        const metricDataList = storages.map((metricStorage) => {
          return metricStorage.collect(collector, collectionTime);
        }).filter(utils_1.isNotNullish);
        if (metricDataList.length === 0) {
          return { errors };
        }
        return {
          scopeMetrics: {
            scope: this._instrumentationScope,
            metrics: metricDataList
          },
          errors
        };
      }
      _registerMetricStorage(descriptor2, MetricStorageType) {
        const views = this._meterProviderSharedState.viewRegistry.findViews(descriptor2, this._instrumentationScope);
        let storages = views.map((view) => {
          const viewDescriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptorWithView)(view, descriptor2);
          const compatibleStorage = this.metricStorageRegistry.findOrUpdateCompatibleStorage(viewDescriptor);
          if (compatibleStorage != null) {
            return compatibleStorage;
          }
          const aggregator = view.aggregation.createAggregator(viewDescriptor);
          const viewStorage = new MetricStorageType(viewDescriptor, aggregator, view.attributesProcessor, this._meterProviderSharedState.metricCollectors, view.aggregationCardinalityLimit);
          this.metricStorageRegistry.register(viewStorage);
          return viewStorage;
        });
        if (storages.length === 0) {
          const perCollectorAggregations = this._meterProviderSharedState.selectAggregations(descriptor2.type);
          const collectorStorages = perCollectorAggregations.map(([collector, aggregation]) => {
            const compatibleStorage = this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(collector, descriptor2);
            if (compatibleStorage != null) {
              return compatibleStorage;
            }
            const aggregator = aggregation.createAggregator(descriptor2);
            const cardinalityLimit = collector.selectCardinalityLimit(descriptor2.type);
            const storage = new MetricStorageType(descriptor2, aggregator, (0, AttributesProcessor_1.createNoopAttributesProcessor)(), [collector], cardinalityLimit);
            this.metricStorageRegistry.registerForCollector(collector, storage);
            return storage;
          });
          storages = storages.concat(collectorStorages);
        }
        return storages;
      }
    };
    exports2.MeterSharedState = MeterSharedState;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterProviderSharedState.js
var require_MeterProviderSharedState = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterProviderSharedState.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MeterProviderSharedState = void 0;
    var utils_1 = require_utils6();
    var ViewRegistry_1 = require_ViewRegistry();
    var MeterSharedState_1 = require_MeterSharedState();
    var AggregationOption_1 = require_AggregationOption();
    var MeterProviderSharedState = class {
      static {
        __name(this, "MeterProviderSharedState");
      }
      resource;
      viewRegistry = new ViewRegistry_1.ViewRegistry();
      metricCollectors = [];
      meterSharedStates = /* @__PURE__ */ new Map();
      constructor(resource) {
        this.resource = resource;
      }
      getMeterSharedState(instrumentationScope) {
        const id = (0, utils_1.instrumentationScopeId)(instrumentationScope);
        let meterSharedState = this.meterSharedStates.get(id);
        if (meterSharedState == null) {
          meterSharedState = new MeterSharedState_1.MeterSharedState(this, instrumentationScope);
          this.meterSharedStates.set(id, meterSharedState);
        }
        return meterSharedState;
      }
      selectAggregations(instrumentType) {
        const result = [];
        for (const collector of this.metricCollectors) {
          result.push([
            collector,
            (0, AggregationOption_1.toAggregation)(collector.selectAggregation(instrumentType))
          ]);
        }
        return result;
      }
    };
    exports2.MeterProviderSharedState = MeterProviderSharedState;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricCollector.js
var require_MetricCollector = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricCollector.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MetricCollector = void 0;
    var core_1 = require_src8();
    var MetricCollector = class {
      static {
        __name(this, "MetricCollector");
      }
      _sharedState;
      _metricReader;
      constructor(_sharedState, _metricReader) {
        this._sharedState = _sharedState;
        this._metricReader = _metricReader;
      }
      async collect(options2) {
        const collectionTime = (0, core_1.millisToHrTime)(Date.now());
        const scopeMetrics = [];
        const errors = [];
        const meterCollectionPromises = Array.from(this._sharedState.meterSharedStates.values()).map(async (meterSharedState) => {
          const current = await meterSharedState.collect(this, collectionTime, options2);
          if (current?.scopeMetrics != null) {
            scopeMetrics.push(current.scopeMetrics);
          }
          if (current?.errors != null) {
            errors.push(...current.errors);
          }
        });
        await Promise.all(meterCollectionPromises);
        return {
          resourceMetrics: {
            resource: this._sharedState.resource,
            scopeMetrics
          },
          errors
        };
      }
      /**
       * Delegates for MetricReader.forceFlush.
       */
      async forceFlush(options2) {
        await this._metricReader.forceFlush(options2);
      }
      /**
       * Delegates for MetricReader.shutdown.
       */
      async shutdown(options2) {
        await this._metricReader.shutdown(options2);
      }
      selectAggregationTemporality(instrumentType) {
        return this._metricReader.selectAggregationTemporality(instrumentType);
      }
      selectAggregation(instrumentType) {
        return this._metricReader.selectAggregation(instrumentType);
      }
      /**
       * Select the cardinality limit for the given {@link InstrumentType} for this
       * collector.
       */
      selectCardinalityLimit(instrumentType) {
        return this._metricReader.selectCardinalityLimit?.(instrumentType) ?? 2e3;
      }
    };
    exports2.MetricCollector = MetricCollector;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/view/Predicate.js
var require_Predicate = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/view/Predicate.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ExactPredicate = exports2.PatternPredicate = void 0;
    var ESCAPE = /[\^$\\.+?()[\]{}|]/g;
    var PatternPredicate = class _PatternPredicate {
      static {
        __name(this, "PatternPredicate");
      }
      _matchAll;
      _regexp;
      constructor(pattern) {
        if (pattern === "*") {
          this._matchAll = true;
          this._regexp = /.*/;
        } else {
          this._matchAll = false;
          this._regexp = new RegExp(_PatternPredicate.escapePattern(pattern));
        }
      }
      match(str2) {
        if (this._matchAll) {
          return true;
        }
        return this._regexp.test(str2);
      }
      static escapePattern(pattern) {
        return `^${pattern.replace(ESCAPE, "\\$&").replace("*", ".*")}$`;
      }
      static hasWildcard(pattern) {
        return pattern.includes("*");
      }
    };
    exports2.PatternPredicate = PatternPredicate;
    var ExactPredicate = class {
      static {
        __name(this, "ExactPredicate");
      }
      _matchAll;
      _pattern;
      constructor(pattern) {
        this._matchAll = pattern === void 0;
        this._pattern = pattern;
      }
      match(str2) {
        if (this._matchAll) {
          return true;
        }
        if (str2 === this._pattern) {
          return true;
        }
        return false;
      }
    };
    exports2.ExactPredicate = ExactPredicate;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/view/InstrumentSelector.js
var require_InstrumentSelector = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/view/InstrumentSelector.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InstrumentSelector = void 0;
    var Predicate_1 = require_Predicate();
    var InstrumentSelector = class {
      static {
        __name(this, "InstrumentSelector");
      }
      _nameFilter;
      _type;
      _unitFilter;
      constructor(criteria) {
        this._nameFilter = new Predicate_1.PatternPredicate(criteria?.name ?? "*");
        this._type = criteria?.type;
        this._unitFilter = new Predicate_1.ExactPredicate(criteria?.unit);
      }
      getType() {
        return this._type;
      }
      getNameFilter() {
        return this._nameFilter;
      }
      getUnitFilter() {
        return this._unitFilter;
      }
    };
    exports2.InstrumentSelector = InstrumentSelector;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/view/MeterSelector.js
var require_MeterSelector = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/view/MeterSelector.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MeterSelector = void 0;
    var Predicate_1 = require_Predicate();
    var MeterSelector = class {
      static {
        __name(this, "MeterSelector");
      }
      _nameFilter;
      _versionFilter;
      _schemaUrlFilter;
      constructor(criteria) {
        this._nameFilter = new Predicate_1.ExactPredicate(criteria?.name);
        this._versionFilter = new Predicate_1.ExactPredicate(criteria?.version);
        this._schemaUrlFilter = new Predicate_1.ExactPredicate(criteria?.schemaUrl);
      }
      getNameFilter() {
        return this._nameFilter;
      }
      /**
       * TODO: semver filter? no spec yet.
       */
      getVersionFilter() {
        return this._versionFilter;
      }
      getSchemaUrlFilter() {
        return this._schemaUrlFilter;
      }
    };
    exports2.MeterSelector = MeterSelector;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/view/View.js
var require_View = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/view/View.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.View = void 0;
    var Predicate_1 = require_Predicate();
    var AttributesProcessor_1 = require_AttributesProcessor();
    var InstrumentSelector_1 = require_InstrumentSelector();
    var MeterSelector_1 = require_MeterSelector();
    var AggregationOption_1 = require_AggregationOption();
    function isSelectorNotProvided(options2) {
      return options2.instrumentName == null && options2.instrumentType == null && options2.instrumentUnit == null && options2.meterName == null && options2.meterVersion == null && options2.meterSchemaUrl == null;
    }
    __name(isSelectorNotProvided, "isSelectorNotProvided");
    function validateViewOptions(viewOptions) {
      if (isSelectorNotProvided(viewOptions)) {
        throw new Error("Cannot create view with no selector arguments supplied");
      }
      if (viewOptions.name != null && (viewOptions?.instrumentName == null || Predicate_1.PatternPredicate.hasWildcard(viewOptions.instrumentName))) {
        throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.");
      }
    }
    __name(validateViewOptions, "validateViewOptions");
    var View = class {
      static {
        __name(this, "View");
      }
      name;
      description;
      aggregation;
      attributesProcessor;
      instrumentSelector;
      meterSelector;
      aggregationCardinalityLimit;
      /**
       * Create a new {@link View} instance.
       *
       * Parameters can be categorized as two types:
       *  Instrument selection criteria: Used to describe the instrument(s) this view will be applied to.
       *  Will be treated as additive (the Instrument has to meet all the provided criteria to be selected).
       *
       *  Metric stream altering: Alter the metric stream of instruments selected by instrument selection criteria.
       *
       * @param viewOptions {@link ViewOptions} for altering the metric stream and instrument selection.
       * @param viewOptions.name
       * Alters the metric stream:
       *  This will be used as the name of the metrics stream.
       *  If not provided, the original Instrument name will be used.
       * @param viewOptions.description
       * Alters the metric stream:
       *  This will be used as the description of the metrics stream.
       *  If not provided, the original Instrument description will be used by default.
       * @param viewOptions.attributesProcessors
       * Alters the metric stream:
       *  If provided, the attributes will be modified as defined by the added processors.
       *  If not provided, all attribute keys will be used by default.
       * @param viewOptions.aggregationCardinalityLimit
       * Alters the metric stream:
       *  Sets a limit on the number of unique attribute combinations (cardinality) that can be aggregated.
       *  If not provided, the default limit of 2000 will be used.
       * @param viewOptions.aggregation
       * Alters the metric stream:
       *  Alters the {@link Aggregation} of the metric stream.
       * @param viewOptions.instrumentName
       * Instrument selection criteria:
       *  Original name of the Instrument(s) with wildcard support.
       * @param viewOptions.instrumentType
       * Instrument selection criteria:
       *  The original type of the Instrument(s).
       * @param viewOptions.instrumentUnit
       * Instrument selection criteria:
       *  The unit of the Instrument(s).
       * @param viewOptions.meterName
       * Instrument selection criteria:
       *  The name of the Meter. No wildcard support, name must match the meter exactly.
       * @param viewOptions.meterVersion
       * Instrument selection criteria:
       *  The version of the Meter. No wildcard support, version must match exactly.
       * @param viewOptions.meterSchemaUrl
       * Instrument selection criteria:
       *  The schema URL of the Meter. No wildcard support, schema URL must match exactly.
       *
       * @example
       * // Create a view that changes the Instrument 'my.instrument' to use to an
       * // ExplicitBucketHistogramAggregation with the boundaries [20, 30, 40]
       * new View({
       *   aggregation: new ExplicitBucketHistogramAggregation([20, 30, 40]),
       *   instrumentName: 'my.instrument'
       * })
       */
      constructor(viewOptions) {
        validateViewOptions(viewOptions);
        if (viewOptions.attributesProcessors != null) {
          this.attributesProcessor = (0, AttributesProcessor_1.createMultiAttributesProcessor)(viewOptions.attributesProcessors);
        } else {
          this.attributesProcessor = (0, AttributesProcessor_1.createNoopAttributesProcessor)();
        }
        this.name = viewOptions.name;
        this.description = viewOptions.description;
        this.aggregation = (0, AggregationOption_1.toAggregation)(viewOptions.aggregation ?? { type: AggregationOption_1.AggregationType.DEFAULT });
        this.instrumentSelector = new InstrumentSelector_1.InstrumentSelector({
          name: viewOptions.instrumentName,
          type: viewOptions.instrumentType,
          unit: viewOptions.instrumentUnit
        });
        this.meterSelector = new MeterSelector_1.MeterSelector({
          name: viewOptions.meterName,
          version: viewOptions.meterVersion,
          schemaUrl: viewOptions.meterSchemaUrl
        });
        this.aggregationCardinalityLimit = viewOptions.aggregationCardinalityLimit;
      }
    };
    exports2.View = View;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/MeterProvider.js
var require_MeterProvider = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/MeterProvider.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MeterProvider = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var resources_1 = require_src13();
    var MeterProviderSharedState_1 = require_MeterProviderSharedState();
    var MetricCollector_1 = require_MetricCollector();
    var View_1 = require_View();
    var MeterProvider = class {
      static {
        __name(this, "MeterProvider");
      }
      _sharedState;
      _shutdown = false;
      constructor(options2) {
        this._sharedState = new MeterProviderSharedState_1.MeterProviderSharedState(options2?.resource ?? (0, resources_1.defaultResource)());
        if (options2?.views != null && options2.views.length > 0) {
          for (const viewOption of options2.views) {
            this._sharedState.viewRegistry.addView(new View_1.View(viewOption));
          }
        }
        if (options2?.readers != null && options2.readers.length > 0) {
          for (const metricReader of options2.readers) {
            const collector = new MetricCollector_1.MetricCollector(this._sharedState, metricReader);
            metricReader.setMetricProducer(collector);
            this._sharedState.metricCollectors.push(collector);
          }
        }
      }
      /**
       * Get a meter with the configuration of the MeterProvider.
       */
      getMeter(name3, version2 = "", options2 = {}) {
        if (this._shutdown) {
          api_1.diag.warn("A shutdown MeterProvider cannot provide a Meter");
          return (0, api_1.createNoopMeter)();
        }
        return this._sharedState.getMeterSharedState({
          name: name3,
          version: version2,
          schemaUrl: options2.schemaUrl
        }).meter;
      }
      /**
       * Shut down the MeterProvider and all registered
       * MetricReaders.
       *
       * Returns a promise which is resolved when all flushes are complete.
       */
      async shutdown(options2) {
        if (this._shutdown) {
          api_1.diag.warn("shutdown may only be called once per MeterProvider");
          return;
        }
        this._shutdown = true;
        await Promise.all(this._sharedState.metricCollectors.map((collector) => {
          return collector.shutdown(options2);
        }));
      }
      /**
       * Notifies all registered MetricReaders to flush any buffered data.
       *
       * Returns a promise which is resolved when all flushes are complete.
       */
      async forceFlush(options2) {
        if (this._shutdown) {
          api_1.diag.warn("invalid attempt to force flush after MeterProvider shutdown");
          return;
        }
        await Promise.all(this._sharedState.metricCollectors.map((collector) => {
          return collector.forceFlush(options2);
        }));
      }
    };
    exports2.MeterProvider = MeterProvider;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/index.js
var require_src14 = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.TimeoutError = exports2.createDenyListAttributesProcessor = exports2.createAllowListAttributesProcessor = exports2.AggregationType = exports2.MeterProvider = exports2.ConsoleMetricExporter = exports2.InMemoryMetricExporter = exports2.PeriodicExportingMetricReader = exports2.MetricReader = exports2.InstrumentType = exports2.DataPointType = exports2.AggregationTemporality = void 0;
    var AggregationTemporality_1 = require_AggregationTemporality();
    Object.defineProperty(exports2, "AggregationTemporality", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return AggregationTemporality_1.AggregationTemporality;
    }, "get") });
    var MetricData_1 = require_MetricData();
    Object.defineProperty(exports2, "DataPointType", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return MetricData_1.DataPointType;
    }, "get") });
    Object.defineProperty(exports2, "InstrumentType", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return MetricData_1.InstrumentType;
    }, "get") });
    var MetricReader_1 = require_MetricReader();
    Object.defineProperty(exports2, "MetricReader", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return MetricReader_1.MetricReader;
    }, "get") });
    var PeriodicExportingMetricReader_1 = require_PeriodicExportingMetricReader();
    Object.defineProperty(exports2, "PeriodicExportingMetricReader", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return PeriodicExportingMetricReader_1.PeriodicExportingMetricReader;
    }, "get") });
    var InMemoryMetricExporter_1 = require_InMemoryMetricExporter();
    Object.defineProperty(exports2, "InMemoryMetricExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return InMemoryMetricExporter_1.InMemoryMetricExporter;
    }, "get") });
    var ConsoleMetricExporter_1 = require_ConsoleMetricExporter();
    Object.defineProperty(exports2, "ConsoleMetricExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ConsoleMetricExporter_1.ConsoleMetricExporter;
    }, "get") });
    var MeterProvider_1 = require_MeterProvider();
    Object.defineProperty(exports2, "MeterProvider", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return MeterProvider_1.MeterProvider;
    }, "get") });
    var AggregationOption_1 = require_AggregationOption();
    Object.defineProperty(exports2, "AggregationType", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return AggregationOption_1.AggregationType;
    }, "get") });
    var AttributesProcessor_1 = require_AttributesProcessor();
    Object.defineProperty(exports2, "createAllowListAttributesProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return AttributesProcessor_1.createAllowListAttributesProcessor;
    }, "get") });
    Object.defineProperty(exports2, "createDenyListAttributesProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return AttributesProcessor_1.createDenyListAttributesProcessor;
    }, "get") });
    var utils_1 = require_utils6();
    Object.defineProperty(exports2, "TimeoutError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return utils_1.TimeoutError;
    }, "get") });
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal-types.js
var require_internal_types = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal-types.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.EAggregationTemporality = void 0;
    var EAggregationTemporality;
    (function(EAggregationTemporality2) {
      EAggregationTemporality2[EAggregationTemporality2["AGGREGATION_TEMPORALITY_UNSPECIFIED"] = 0] = "AGGREGATION_TEMPORALITY_UNSPECIFIED";
      EAggregationTemporality2[EAggregationTemporality2["AGGREGATION_TEMPORALITY_DELTA"] = 1] = "AGGREGATION_TEMPORALITY_DELTA";
      EAggregationTemporality2[EAggregationTemporality2["AGGREGATION_TEMPORALITY_CUMULATIVE"] = 2] = "AGGREGATION_TEMPORALITY_CUMULATIVE";
    })(EAggregationTemporality = exports2.EAggregationTemporality || (exports2.EAggregationTemporality = {}));
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal.js
var require_internal3 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createExportMetricsServiceRequest = exports2.toMetric = exports2.toScopeMetrics = exports2.toResourceMetrics = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var sdk_metrics_1 = require_src14();
    var internal_types_1 = require_internal_types();
    var utils_1 = require_utils5();
    var internal_1 = require_internal();
    function toResourceMetrics(resourceMetrics, options2) {
      const encoder = (0, utils_1.getOtlpEncoder)(options2);
      return {
        resource: (0, internal_1.createResource)(resourceMetrics.resource),
        schemaUrl: void 0,
        scopeMetrics: toScopeMetrics(resourceMetrics.scopeMetrics, encoder)
      };
    }
    __name(toResourceMetrics, "toResourceMetrics");
    exports2.toResourceMetrics = toResourceMetrics;
    function toScopeMetrics(scopeMetrics, encoder) {
      return Array.from(scopeMetrics.map((metrics2) => ({
        scope: (0, internal_1.createInstrumentationScope)(metrics2.scope),
        metrics: metrics2.metrics.map((metricData) => toMetric(metricData, encoder)),
        schemaUrl: metrics2.scope.schemaUrl
      })));
    }
    __name(toScopeMetrics, "toScopeMetrics");
    exports2.toScopeMetrics = toScopeMetrics;
    function toMetric(metricData, encoder) {
      const out = {
        name: metricData.descriptor.name,
        description: metricData.descriptor.description,
        unit: metricData.descriptor.unit
      };
      const aggregationTemporality = toAggregationTemporality(metricData.aggregationTemporality);
      switch (metricData.dataPointType) {
        case sdk_metrics_1.DataPointType.SUM:
          out.sum = {
            aggregationTemporality,
            isMonotonic: metricData.isMonotonic,
            dataPoints: toSingularDataPoints(metricData, encoder)
          };
          break;
        case sdk_metrics_1.DataPointType.GAUGE:
          out.gauge = {
            dataPoints: toSingularDataPoints(metricData, encoder)
          };
          break;
        case sdk_metrics_1.DataPointType.HISTOGRAM:
          out.histogram = {
            aggregationTemporality,
            dataPoints: toHistogramDataPoints(metricData, encoder)
          };
          break;
        case sdk_metrics_1.DataPointType.EXPONENTIAL_HISTOGRAM:
          out.exponentialHistogram = {
            aggregationTemporality,
            dataPoints: toExponentialHistogramDataPoints(metricData, encoder)
          };
          break;
      }
      return out;
    }
    __name(toMetric, "toMetric");
    exports2.toMetric = toMetric;
    function toSingularDataPoint(dataPoint, valueType, encoder) {
      const out = {
        attributes: (0, internal_1.toAttributes)(dataPoint.attributes),
        startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime),
        timeUnixNano: encoder.encodeHrTime(dataPoint.endTime)
      };
      switch (valueType) {
        case api_1.ValueType.INT:
          out.asInt = dataPoint.value;
          break;
        case api_1.ValueType.DOUBLE:
          out.asDouble = dataPoint.value;
          break;
      }
      return out;
    }
    __name(toSingularDataPoint, "toSingularDataPoint");
    function toSingularDataPoints(metricData, encoder) {
      return metricData.dataPoints.map((dataPoint) => {
        return toSingularDataPoint(dataPoint, metricData.descriptor.valueType, encoder);
      });
    }
    __name(toSingularDataPoints, "toSingularDataPoints");
    function toHistogramDataPoints(metricData, encoder) {
      return metricData.dataPoints.map((dataPoint) => {
        const histogram = dataPoint.value;
        return {
          attributes: (0, internal_1.toAttributes)(dataPoint.attributes),
          bucketCounts: histogram.buckets.counts,
          explicitBounds: histogram.buckets.boundaries,
          count: histogram.count,
          sum: histogram.sum,
          min: histogram.min,
          max: histogram.max,
          startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime),
          timeUnixNano: encoder.encodeHrTime(dataPoint.endTime)
        };
      });
    }
    __name(toHistogramDataPoints, "toHistogramDataPoints");
    function toExponentialHistogramDataPoints(metricData, encoder) {
      return metricData.dataPoints.map((dataPoint) => {
        const histogram = dataPoint.value;
        return {
          attributes: (0, internal_1.toAttributes)(dataPoint.attributes),
          count: histogram.count,
          min: histogram.min,
          max: histogram.max,
          sum: histogram.sum,
          positive: {
            offset: histogram.positive.offset,
            bucketCounts: histogram.positive.bucketCounts
          },
          negative: {
            offset: histogram.negative.offset,
            bucketCounts: histogram.negative.bucketCounts
          },
          scale: histogram.scale,
          zeroCount: histogram.zeroCount,
          startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime),
          timeUnixNano: encoder.encodeHrTime(dataPoint.endTime)
        };
      });
    }
    __name(toExponentialHistogramDataPoints, "toExponentialHistogramDataPoints");
    function toAggregationTemporality(temporality) {
      switch (temporality) {
        case sdk_metrics_1.AggregationTemporality.DELTA:
          return internal_types_1.EAggregationTemporality.AGGREGATION_TEMPORALITY_DELTA;
        case sdk_metrics_1.AggregationTemporality.CUMULATIVE:
          return internal_types_1.EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE;
      }
    }
    __name(toAggregationTemporality, "toAggregationTemporality");
    function createExportMetricsServiceRequest(resourceMetrics, options2) {
      return {
        resourceMetrics: resourceMetrics.map((metrics2) => toResourceMetrics(metrics2, options2))
      };
    }
    __name(createExportMetricsServiceRequest, "createExportMetricsServiceRequest");
    exports2.createExportMetricsServiceRequest = createExportMetricsServiceRequest;
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/metrics.js
var require_metrics = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/metrics.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ProtobufMetricsSerializer = void 0;
    var root = require_root2();
    var internal_1 = require_internal3();
    var metricsResponseType = root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse;
    var metricsRequestType = root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest;
    exports2.ProtobufMetricsSerializer = {
      serializeRequest: /* @__PURE__ */ __name((arg) => {
        const request4 = (0, internal_1.createExportMetricsServiceRequest)([arg]);
        return metricsRequestType.encode(request4).finish();
      }, "serializeRequest"),
      deserializeResponse: /* @__PURE__ */ __name((arg) => {
        return metricsResponseType.decode(arg);
      }, "deserializeResponse")
    };
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/index.js
var require_protobuf2 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ProtobufMetricsSerializer = void 0;
    var metrics_1 = require_metrics();
    Object.defineProperty(exports2, "ProtobufMetricsSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return metrics_1.ProtobufMetricsSerializer;
    }, "get") });
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/trace/internal.js
var require_internal4 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/trace/internal.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createExportTraceServiceRequest = exports2.toOtlpSpanEvent = exports2.toOtlpLink = exports2.sdkSpanToOtlpSpan = void 0;
    var internal_1 = require_internal();
    var utils_1 = require_utils5();
    function sdkSpanToOtlpSpan(span, encoder) {
      const ctx = span.spanContext();
      const status = span.status;
      const parentSpanId = span.parentSpanContext?.spanId ? encoder.encodeSpanContext(span.parentSpanContext?.spanId) : void 0;
      return {
        traceId: encoder.encodeSpanContext(ctx.traceId),
        spanId: encoder.encodeSpanContext(ctx.spanId),
        parentSpanId,
        traceState: ctx.traceState?.serialize(),
        name: span.name,
        // Span kind is offset by 1 because the API does not define a value for unset
        kind: span.kind == null ? 0 : span.kind + 1,
        startTimeUnixNano: encoder.encodeHrTime(span.startTime),
        endTimeUnixNano: encoder.encodeHrTime(span.endTime),
        attributes: (0, internal_1.toAttributes)(span.attributes),
        droppedAttributesCount: span.droppedAttributesCount,
        events: span.events.map((event) => toOtlpSpanEvent(event, encoder)),
        droppedEventsCount: span.droppedEventsCount,
        status: {
          // API and proto enums share the same values
          code: status.code,
          message: status.message
        },
        links: span.links.map((link3) => toOtlpLink(link3, encoder)),
        droppedLinksCount: span.droppedLinksCount
      };
    }
    __name(sdkSpanToOtlpSpan, "sdkSpanToOtlpSpan");
    exports2.sdkSpanToOtlpSpan = sdkSpanToOtlpSpan;
    function toOtlpLink(link3, encoder) {
      return {
        attributes: link3.attributes ? (0, internal_1.toAttributes)(link3.attributes) : [],
        spanId: encoder.encodeSpanContext(link3.context.spanId),
        traceId: encoder.encodeSpanContext(link3.context.traceId),
        traceState: link3.context.traceState?.serialize(),
        droppedAttributesCount: link3.droppedAttributesCount || 0
      };
    }
    __name(toOtlpLink, "toOtlpLink");
    exports2.toOtlpLink = toOtlpLink;
    function toOtlpSpanEvent(timedEvent, encoder) {
      return {
        attributes: timedEvent.attributes ? (0, internal_1.toAttributes)(timedEvent.attributes) : [],
        name: timedEvent.name,
        timeUnixNano: encoder.encodeHrTime(timedEvent.time),
        droppedAttributesCount: timedEvent.droppedAttributesCount || 0
      };
    }
    __name(toOtlpSpanEvent, "toOtlpSpanEvent");
    exports2.toOtlpSpanEvent = toOtlpSpanEvent;
    function createExportTraceServiceRequest(spans, options2) {
      const encoder = (0, utils_1.getOtlpEncoder)(options2);
      return {
        resourceSpans: spanRecordsToResourceSpans(spans, encoder)
      };
    }
    __name(createExportTraceServiceRequest, "createExportTraceServiceRequest");
    exports2.createExportTraceServiceRequest = createExportTraceServiceRequest;
    function createResourceMap(readableSpans) {
      const resourceMap = /* @__PURE__ */ new Map();
      for (const record of readableSpans) {
        let ilsMap = resourceMap.get(record.resource);
        if (!ilsMap) {
          ilsMap = /* @__PURE__ */ new Map();
          resourceMap.set(record.resource, ilsMap);
        }
        const instrumentationScopeKey = `${record.instrumentationScope.name}@${record.instrumentationScope.version || ""}:${record.instrumentationScope.schemaUrl || ""}`;
        let records = ilsMap.get(instrumentationScopeKey);
        if (!records) {
          records = [];
          ilsMap.set(instrumentationScopeKey, records);
        }
        records.push(record);
      }
      return resourceMap;
    }
    __name(createResourceMap, "createResourceMap");
    function spanRecordsToResourceSpans(readableSpans, encoder) {
      const resourceMap = createResourceMap(readableSpans);
      const out = [];
      const entryIterator = resourceMap.entries();
      let entry = entryIterator.next();
      while (!entry.done) {
        const [resource, ilmMap] = entry.value;
        const scopeResourceSpans = [];
        const ilmIterator = ilmMap.values();
        let ilmEntry = ilmIterator.next();
        while (!ilmEntry.done) {
          const scopeSpans = ilmEntry.value;
          if (scopeSpans.length > 0) {
            const spans = scopeSpans.map((readableSpan) => sdkSpanToOtlpSpan(readableSpan, encoder));
            scopeResourceSpans.push({
              scope: (0, internal_1.createInstrumentationScope)(scopeSpans[0].instrumentationScope),
              spans,
              schemaUrl: scopeSpans[0].instrumentationScope.schemaUrl
            });
          }
          ilmEntry = ilmIterator.next();
        }
        const transformedSpans = {
          resource: (0, internal_1.createResource)(resource),
          scopeSpans: scopeResourceSpans,
          schemaUrl: void 0
        };
        out.push(transformedSpans);
        entry = entryIterator.next();
      }
      return out;
    }
    __name(spanRecordsToResourceSpans, "spanRecordsToResourceSpans");
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/trace.js
var require_trace = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/trace.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ProtobufTraceSerializer = void 0;
    var root = require_root2();
    var internal_1 = require_internal4();
    var traceResponseType = root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse;
    var traceRequestType = root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest;
    exports2.ProtobufTraceSerializer = {
      serializeRequest: /* @__PURE__ */ __name((arg) => {
        const request4 = (0, internal_1.createExportTraceServiceRequest)(arg);
        return traceRequestType.encode(request4).finish();
      }, "serializeRequest"),
      deserializeResponse: /* @__PURE__ */ __name((arg) => {
        return traceResponseType.decode(arg);
      }, "deserializeResponse")
    };
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/index.js
var require_protobuf3 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ProtobufTraceSerializer = void 0;
    var trace_1 = require_trace();
    Object.defineProperty(exports2, "ProtobufTraceSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return trace_1.ProtobufTraceSerializer;
    }, "get") });
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/logs.js
var require_logs3 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/logs.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.JsonLogsSerializer = void 0;
    var internal_1 = require_internal2();
    exports2.JsonLogsSerializer = {
      serializeRequest: /* @__PURE__ */ __name((arg) => {
        const request4 = (0, internal_1.createExportLogsServiceRequest)(arg, {
          useHex: true,
          useLongBits: false
        });
        const encoder = new TextEncoder();
        return encoder.encode(JSON.stringify(request4));
      }, "serializeRequest"),
      deserializeResponse: /* @__PURE__ */ __name((arg) => {
        if (arg.length === 0) {
          return {};
        }
        const decoder = new TextDecoder();
        return JSON.parse(decoder.decode(arg));
      }, "deserializeResponse")
    };
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/index.js
var require_json = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.JsonLogsSerializer = void 0;
    var logs_1 = require_logs3();
    Object.defineProperty(exports2, "JsonLogsSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return logs_1.JsonLogsSerializer;
    }, "get") });
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/metrics.js
var require_metrics2 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/metrics.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.JsonMetricsSerializer = void 0;
    var internal_1 = require_internal3();
    exports2.JsonMetricsSerializer = {
      serializeRequest: /* @__PURE__ */ __name((arg) => {
        const request4 = (0, internal_1.createExportMetricsServiceRequest)([arg], {
          useLongBits: false
        });
        const encoder = new TextEncoder();
        return encoder.encode(JSON.stringify(request4));
      }, "serializeRequest"),
      deserializeResponse: /* @__PURE__ */ __name((arg) => {
        if (arg.length === 0) {
          return {};
        }
        const decoder = new TextDecoder();
        return JSON.parse(decoder.decode(arg));
      }, "deserializeResponse")
    };
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/index.js
var require_json2 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.JsonMetricsSerializer = void 0;
    var metrics_1 = require_metrics2();
    Object.defineProperty(exports2, "JsonMetricsSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return metrics_1.JsonMetricsSerializer;
    }, "get") });
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/trace.js
var require_trace2 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/trace.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.JsonTraceSerializer = void 0;
    var internal_1 = require_internal4();
    exports2.JsonTraceSerializer = {
      serializeRequest: /* @__PURE__ */ __name((arg) => {
        const request4 = (0, internal_1.createExportTraceServiceRequest)(arg, {
          useHex: true,
          useLongBits: false
        });
        const encoder = new TextEncoder();
        return encoder.encode(JSON.stringify(request4));
      }, "serializeRequest"),
      deserializeResponse: /* @__PURE__ */ __name((arg) => {
        if (arg.length === 0) {
          return {};
        }
        const decoder = new TextDecoder();
        return JSON.parse(decoder.decode(arg));
      }, "deserializeResponse")
    };
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/index.js
var require_json3 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.JsonTraceSerializer = void 0;
    var trace_1 = require_trace2();
    Object.defineProperty(exports2, "JsonTraceSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return trace_1.JsonTraceSerializer;
    }, "get") });
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/index.js
var require_src15 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.JsonTraceSerializer = exports2.JsonMetricsSerializer = exports2.JsonLogsSerializer = exports2.ProtobufTraceSerializer = exports2.ProtobufMetricsSerializer = exports2.ProtobufLogsSerializer = void 0;
    var protobuf_1 = require_protobuf();
    Object.defineProperty(exports2, "ProtobufLogsSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return protobuf_1.ProtobufLogsSerializer;
    }, "get") });
    var protobuf_2 = require_protobuf2();
    Object.defineProperty(exports2, "ProtobufMetricsSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return protobuf_2.ProtobufMetricsSerializer;
    }, "get") });
    var protobuf_3 = require_protobuf3();
    Object.defineProperty(exports2, "ProtobufTraceSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return protobuf_3.ProtobufTraceSerializer;
    }, "get") });
    var json_1 = require_json();
    Object.defineProperty(exports2, "JsonLogsSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return json_1.JsonLogsSerializer;
    }, "get") });
    var json_2 = require_json2();
    Object.defineProperty(exports2, "JsonMetricsSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return json_2.JsonMetricsSerializer;
    }, "get") });
    var json_3 = require_json3();
    Object.defineProperty(exports2, "JsonTraceSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return json_3.JsonTraceSerializer;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/OTLPTraceExporter.js
var require_OTLPTraceExporter = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/OTLPTraceExporter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPTraceExporter = void 0;
    var otlp_grpc_exporter_base_1 = require_src12();
    var otlp_transformer_1 = require_src15();
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var OTLPTraceExporter2 = class extends otlp_exporter_base_1.OTLPExporterBase {
      static {
        __name(this, "OTLPTraceExporter");
      }
      constructor(config = {}) {
        super((0, otlp_grpc_exporter_base_1.createOtlpGrpcExportDelegate)((0, otlp_grpc_exporter_base_1.convertLegacyOtlpGrpcOptions)(config, "TRACES"), otlp_transformer_1.ProtobufTraceSerializer, "TraceExportService", "/opentelemetry.proto.collector.trace.v1.TraceService/Export"));
      }
    };
    exports2.OTLPTraceExporter = OTLPTraceExporter2;
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/index.js
var require_src16 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPTraceExporter = void 0;
    var OTLPTraceExporter_1 = require_OTLPTraceExporter();
    Object.defineProperty(exports2, "OTLPTraceExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPTraceExporter_1.OTLPTraceExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/OTLPLogExporter.js
var require_OTLPLogExporter = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/OTLPLogExporter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPLogExporter = void 0;
    var otlp_grpc_exporter_base_1 = require_src12();
    var otlp_transformer_1 = require_src15();
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var OTLPLogExporter2 = class extends otlp_exporter_base_1.OTLPExporterBase {
      static {
        __name(this, "OTLPLogExporter");
      }
      constructor(config = {}) {
        super((0, otlp_grpc_exporter_base_1.createOtlpGrpcExportDelegate)((0, otlp_grpc_exporter_base_1.convertLegacyOtlpGrpcOptions)(config, "LOGS"), otlp_transformer_1.ProtobufLogsSerializer, "LogsExportService", "/opentelemetry.proto.collector.logs.v1.LogsService/Export"));
      }
    };
    exports2.OTLPLogExporter = OTLPLogExporter2;
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/index.js
var require_src17 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPLogExporter = void 0;
    var OTLPLogExporter_1 = require_OTLPLogExporter();
    Object.defineProperty(exports2, "OTLPLogExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPLogExporter_1.OTLPLogExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterOptions.js
var require_OTLPMetricExporterOptions = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterOptions.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AggregationTemporalityPreference = void 0;
    var AggregationTemporalityPreference;
    (function(AggregationTemporalityPreference2) {
      AggregationTemporalityPreference2[AggregationTemporalityPreference2["DELTA"] = 0] = "DELTA";
      AggregationTemporalityPreference2[AggregationTemporalityPreference2["CUMULATIVE"] = 1] = "CUMULATIVE";
      AggregationTemporalityPreference2[AggregationTemporalityPreference2["LOWMEMORY"] = 2] = "LOWMEMORY";
    })(AggregationTemporalityPreference = exports2.AggregationTemporalityPreference || (exports2.AggregationTemporalityPreference = {}));
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterBase.js
var require_OTLPMetricExporterBase = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterBase.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPMetricExporterBase = exports2.LowMemoryTemporalitySelector = exports2.DeltaTemporalitySelector = exports2.CumulativeTemporalitySelector = void 0;
    var core_1 = require_src8();
    var sdk_metrics_1 = require_src14();
    var OTLPMetricExporterOptions_1 = require_OTLPMetricExporterOptions();
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var CumulativeTemporalitySelector = /* @__PURE__ */ __name(() => sdk_metrics_1.AggregationTemporality.CUMULATIVE, "CumulativeTemporalitySelector");
    exports2.CumulativeTemporalitySelector = CumulativeTemporalitySelector;
    var DeltaTemporalitySelector = /* @__PURE__ */ __name((instrumentType) => {
      switch (instrumentType) {
        case sdk_metrics_1.InstrumentType.COUNTER:
        case sdk_metrics_1.InstrumentType.OBSERVABLE_COUNTER:
        case sdk_metrics_1.InstrumentType.GAUGE:
        case sdk_metrics_1.InstrumentType.HISTOGRAM:
        case sdk_metrics_1.InstrumentType.OBSERVABLE_GAUGE:
          return sdk_metrics_1.AggregationTemporality.DELTA;
        case sdk_metrics_1.InstrumentType.UP_DOWN_COUNTER:
        case sdk_metrics_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER:
          return sdk_metrics_1.AggregationTemporality.CUMULATIVE;
      }
    }, "DeltaTemporalitySelector");
    exports2.DeltaTemporalitySelector = DeltaTemporalitySelector;
    var LowMemoryTemporalitySelector = /* @__PURE__ */ __name((instrumentType) => {
      switch (instrumentType) {
        case sdk_metrics_1.InstrumentType.COUNTER:
        case sdk_metrics_1.InstrumentType.HISTOGRAM:
          return sdk_metrics_1.AggregationTemporality.DELTA;
        case sdk_metrics_1.InstrumentType.GAUGE:
        case sdk_metrics_1.InstrumentType.UP_DOWN_COUNTER:
        case sdk_metrics_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER:
        case sdk_metrics_1.InstrumentType.OBSERVABLE_COUNTER:
        case sdk_metrics_1.InstrumentType.OBSERVABLE_GAUGE:
          return sdk_metrics_1.AggregationTemporality.CUMULATIVE;
      }
    }, "LowMemoryTemporalitySelector");
    exports2.LowMemoryTemporalitySelector = LowMemoryTemporalitySelector;
    function chooseTemporalitySelectorFromEnvironment() {
      const configuredTemporality = ((0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE") ?? "cumulative").toLowerCase();
      if (configuredTemporality === "cumulative") {
        return exports2.CumulativeTemporalitySelector;
      }
      if (configuredTemporality === "delta") {
        return exports2.DeltaTemporalitySelector;
      }
      if (configuredTemporality === "lowmemory") {
        return exports2.LowMemoryTemporalitySelector;
      }
      api_1.diag.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${configuredTemporality}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`);
      return exports2.CumulativeTemporalitySelector;
    }
    __name(chooseTemporalitySelectorFromEnvironment, "chooseTemporalitySelectorFromEnvironment");
    function chooseTemporalitySelector(temporalityPreference) {
      if (temporalityPreference != null) {
        if (temporalityPreference === OTLPMetricExporterOptions_1.AggregationTemporalityPreference.DELTA) {
          return exports2.DeltaTemporalitySelector;
        } else if (temporalityPreference === OTLPMetricExporterOptions_1.AggregationTemporalityPreference.LOWMEMORY) {
          return exports2.LowMemoryTemporalitySelector;
        }
        return exports2.CumulativeTemporalitySelector;
      }
      return chooseTemporalitySelectorFromEnvironment();
    }
    __name(chooseTemporalitySelector, "chooseTemporalitySelector");
    var DEFAULT_AGGREGATION = Object.freeze({
      type: sdk_metrics_1.AggregationType.DEFAULT
    });
    function chooseAggregationSelector(config) {
      return config?.aggregationPreference ?? (() => DEFAULT_AGGREGATION);
    }
    __name(chooseAggregationSelector, "chooseAggregationSelector");
    var OTLPMetricExporterBase = class extends otlp_exporter_base_1.OTLPExporterBase {
      static {
        __name(this, "OTLPMetricExporterBase");
      }
      _aggregationTemporalitySelector;
      _aggregationSelector;
      constructor(delegate, config) {
        super(delegate);
        this._aggregationSelector = chooseAggregationSelector(config);
        this._aggregationTemporalitySelector = chooseTemporalitySelector(config?.temporalityPreference);
      }
      selectAggregation(instrumentType) {
        return this._aggregationSelector(instrumentType);
      }
      selectAggregationTemporality(instrumentType) {
        return this._aggregationTemporalitySelector(instrumentType);
      }
    };
    exports2.OTLPMetricExporterBase = OTLPMetricExporterBase;
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/version.js
var require_version3 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/version.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.VERSION = void 0;
    exports2.VERSION = "0.203.0";
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/OTLPMetricExporter.js
var require_OTLPMetricExporter = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/OTLPMetricExporter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPMetricExporter = void 0;
    var OTLPMetricExporterBase_1 = require_OTLPMetricExporterBase();
    var otlp_transformer_1 = require_src15();
    var version_1 = require_version3();
    var node_http_1 = (init_index_node_http(), __toCommonJS(index_node_http_exports));
    var USER_AGENT = {
      "User-Agent": `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`
    };
    var OTLPMetricExporter2 = class extends OTLPMetricExporterBase_1.OTLPMetricExporterBase {
      static {
        __name(this, "OTLPMetricExporter");
      }
      constructor(config) {
        super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config ?? {}, "METRICS", "v1/metrics", {
          ...USER_AGENT,
          "Content-Type": "application/json"
        }), otlp_transformer_1.JsonMetricsSerializer), config);
      }
    };
    exports2.OTLPMetricExporter = OTLPMetricExporter2;
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/index.js
var require_node6 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPMetricExporter = void 0;
    var OTLPMetricExporter_1 = require_OTLPMetricExporter();
    Object.defineProperty(exports2, "OTLPMetricExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPMetricExporter_1.OTLPMetricExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/index.js
var require_platform5 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPMetricExporter = void 0;
    var node_1 = require_node6();
    Object.defineProperty(exports2, "OTLPMetricExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.OTLPMetricExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/index.js
var require_src18 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPMetricExporterBase = exports2.LowMemoryTemporalitySelector = exports2.DeltaTemporalitySelector = exports2.CumulativeTemporalitySelector = exports2.AggregationTemporalityPreference = exports2.OTLPMetricExporter = void 0;
    var platform_1 = require_platform5();
    Object.defineProperty(exports2, "OTLPMetricExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.OTLPMetricExporter;
    }, "get") });
    var OTLPMetricExporterOptions_1 = require_OTLPMetricExporterOptions();
    Object.defineProperty(exports2, "AggregationTemporalityPreference", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPMetricExporterOptions_1.AggregationTemporalityPreference;
    }, "get") });
    var OTLPMetricExporterBase_1 = require_OTLPMetricExporterBase();
    Object.defineProperty(exports2, "CumulativeTemporalitySelector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPMetricExporterBase_1.CumulativeTemporalitySelector;
    }, "get") });
    Object.defineProperty(exports2, "DeltaTemporalitySelector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPMetricExporterBase_1.DeltaTemporalitySelector;
    }, "get") });
    Object.defineProperty(exports2, "LowMemoryTemporalitySelector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPMetricExporterBase_1.LowMemoryTemporalitySelector;
    }, "get") });
    Object.defineProperty(exports2, "OTLPMetricExporterBase", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPMetricExporterBase_1.OTLPMetricExporterBase;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/OTLPMetricExporter.js
var require_OTLPMetricExporter2 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/OTLPMetricExporter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPMetricExporter = void 0;
    var exporter_metrics_otlp_http_1 = require_src18();
    var otlp_grpc_exporter_base_1 = require_src12();
    var otlp_transformer_1 = require_src15();
    var OTLPMetricExporter2 = class extends exporter_metrics_otlp_http_1.OTLPMetricExporterBase {
      static {
        __name(this, "OTLPMetricExporter");
      }
      constructor(config) {
        super((0, otlp_grpc_exporter_base_1.createOtlpGrpcExportDelegate)((0, otlp_grpc_exporter_base_1.convertLegacyOtlpGrpcOptions)(config ?? {}, "METRICS"), otlp_transformer_1.ProtobufMetricsSerializer, "MetricsExportService", "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export"), config);
      }
    };
    exports2.OTLPMetricExporter = OTLPMetricExporter2;
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/index.js
var require_src19 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPMetricExporter = void 0;
    var OTLPMetricExporter_1 = require_OTLPMetricExporter2();
    Object.defineProperty(exports2, "OTLPMetricExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPMetricExporter_1.OTLPMetricExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/version.js
var require_version4 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/version.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.VERSION = void 0;
    exports2.VERSION = "0.203.0";
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/OTLPTraceExporter.js
var require_OTLPTraceExporter2 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/OTLPTraceExporter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPTraceExporter = void 0;
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var version_1 = require_version4();
    var otlp_transformer_1 = require_src15();
    var node_http_1 = (init_index_node_http(), __toCommonJS(index_node_http_exports));
    var OTLPTraceExporter2 = class extends otlp_exporter_base_1.OTLPExporterBase {
      static {
        __name(this, "OTLPTraceExporter");
      }
      constructor(config = {}) {
        super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, "TRACES", "v1/traces", {
          "User-Agent": `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`,
          "Content-Type": "application/json"
        }), otlp_transformer_1.JsonTraceSerializer));
      }
    };
    exports2.OTLPTraceExporter = OTLPTraceExporter2;
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/index.js
var require_node7 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPTraceExporter = void 0;
    var OTLPTraceExporter_1 = require_OTLPTraceExporter2();
    Object.defineProperty(exports2, "OTLPTraceExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPTraceExporter_1.OTLPTraceExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/index.js
var require_platform6 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPTraceExporter = void 0;
    var node_1 = require_node7();
    Object.defineProperty(exports2, "OTLPTraceExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.OTLPTraceExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/index.js
var require_src20 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPTraceExporter = void 0;
    var platform_1 = require_platform6();
    Object.defineProperty(exports2, "OTLPTraceExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.OTLPTraceExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/version.js
var require_version5 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/version.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.VERSION = void 0;
    exports2.VERSION = "0.203.0";
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/OTLPLogExporter.js
var require_OTLPLogExporter2 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/OTLPLogExporter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPLogExporter = void 0;
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var otlp_transformer_1 = require_src15();
    var version_1 = require_version5();
    var node_http_1 = (init_index_node_http(), __toCommonJS(index_node_http_exports));
    var OTLPLogExporter2 = class extends otlp_exporter_base_1.OTLPExporterBase {
      static {
        __name(this, "OTLPLogExporter");
      }
      constructor(config = {}) {
        super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, "LOGS", "v1/logs", {
          "User-Agent": `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`,
          "Content-Type": "application/json"
        }), otlp_transformer_1.JsonLogsSerializer));
      }
    };
    exports2.OTLPLogExporter = OTLPLogExporter2;
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/index.js
var require_node8 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPLogExporter = void 0;
    var OTLPLogExporter_1 = require_OTLPLogExporter2();
    Object.defineProperty(exports2, "OTLPLogExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPLogExporter_1.OTLPLogExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/index.js
var require_platform7 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPLogExporter = void 0;
    var node_1 = require_node8();
    Object.defineProperty(exports2, "OTLPLogExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.OTLPLogExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/index.js
var require_src21 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPLogExporter = void 0;
    var platform_1 = require_platform7();
    Object.defineProperty(exports2, "OTLPLogExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.OTLPLogExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/LogRecordImpl.js
var require_LogRecordImpl = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/LogRecordImpl.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LogRecordImpl = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var api = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var LogRecordImpl = class {
      static {
        __name(this, "LogRecordImpl");
      }
      hrTime;
      hrTimeObserved;
      spanContext;
      resource;
      instrumentationScope;
      attributes = {};
      _severityText;
      _severityNumber;
      _body;
      _eventName;
      totalAttributesCount = 0;
      _isReadonly = false;
      _logRecordLimits;
      set severityText(severityText) {
        if (this._isLogRecordReadonly()) {
          return;
        }
        this._severityText = severityText;
      }
      get severityText() {
        return this._severityText;
      }
      set severityNumber(severityNumber) {
        if (this._isLogRecordReadonly()) {
          return;
        }
        this._severityNumber = severityNumber;
      }
      get severityNumber() {
        return this._severityNumber;
      }
      set body(body) {
        if (this._isLogRecordReadonly()) {
          return;
        }
        this._body = body;
      }
      get body() {
        return this._body;
      }
      get eventName() {
        return this._eventName;
      }
      set eventName(eventName) {
        if (this._isLogRecordReadonly()) {
          return;
        }
        this._eventName = eventName;
      }
      get droppedAttributesCount() {
        return this.totalAttributesCount - Object.keys(this.attributes).length;
      }
      constructor(_sharedState, instrumentationScope, logRecord) {
        const { timestamp, observedTimestamp, eventName, severityNumber, severityText, body, attributes = {}, context: context2 } = logRecord;
        const now = Date.now();
        this.hrTime = (0, core_1.timeInputToHrTime)(timestamp ?? now);
        this.hrTimeObserved = (0, core_1.timeInputToHrTime)(observedTimestamp ?? now);
        if (context2) {
          const spanContext = api.trace.getSpanContext(context2);
          if (spanContext && api.isSpanContextValid(spanContext)) {
            this.spanContext = spanContext;
          }
        }
        this.severityNumber = severityNumber;
        this.severityText = severityText;
        this.body = body;
        this.resource = _sharedState.resource;
        this.instrumentationScope = instrumentationScope;
        this._logRecordLimits = _sharedState.logRecordLimits;
        this._eventName = eventName;
        this.setAttributes(attributes);
      }
      setAttribute(key, value) {
        if (this._isLogRecordReadonly()) {
          return this;
        }
        if (value === null) {
          return this;
        }
        if (key.length === 0) {
          api.diag.warn(`Invalid attribute key: ${key}`);
          return this;
        }
        if (!(0, core_1.isAttributeValue)(value) && !(typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0)) {
          api.diag.warn(`Invalid attribute value set for key: ${key}`);
          return this;
        }
        this.totalAttributesCount += 1;
        if (Object.keys(this.attributes).length >= this._logRecordLimits.attributeCountLimit && !Object.prototype.hasOwnProperty.call(this.attributes, key)) {
          if (this.droppedAttributesCount === 1) {
            api.diag.warn("Dropping extra attributes.");
          }
          return this;
        }
        if ((0, core_1.isAttributeValue)(value)) {
          this.attributes[key] = this._truncateToSize(value);
        } else {
          this.attributes[key] = value;
        }
        return this;
      }
      setAttributes(attributes) {
        for (const [k, v] of Object.entries(attributes)) {
          this.setAttribute(k, v);
        }
        return this;
      }
      setBody(body) {
        this.body = body;
        return this;
      }
      setEventName(eventName) {
        this.eventName = eventName;
        return this;
      }
      setSeverityNumber(severityNumber) {
        this.severityNumber = severityNumber;
        return this;
      }
      setSeverityText(severityText) {
        this.severityText = severityText;
        return this;
      }
      /**
       * @internal
       * A LogRecordProcessor may freely modify logRecord for the duration of the OnEmit call.
       * If logRecord is needed after OnEmit returns (i.e. for asynchronous processing) only reads are permitted.
       */
      _makeReadonly() {
        this._isReadonly = true;
      }
      _truncateToSize(value) {
        const limit2 = this._logRecordLimits.attributeValueLengthLimit;
        if (limit2 <= 0) {
          api.diag.warn(`Attribute value limit must be positive, got ${limit2}`);
          return value;
        }
        if (typeof value === "string") {
          return this._truncateToLimitUtil(value, limit2);
        }
        if (Array.isArray(value)) {
          return value.map((val) => typeof val === "string" ? this._truncateToLimitUtil(val, limit2) : val);
        }
        return value;
      }
      _truncateToLimitUtil(value, limit2) {
        if (value.length <= limit2) {
          return value;
        }
        return value.substring(0, limit2);
      }
      _isLogRecordReadonly() {
        if (this._isReadonly) {
          api_1.diag.warn("Can not execute the operation on emitted log record");
        }
        return this._isReadonly;
      }
    };
    exports2.LogRecordImpl = LogRecordImpl;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/Logger.js
var require_Logger = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/Logger.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Logger = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var LogRecordImpl_1 = require_LogRecordImpl();
    var Logger2 = class {
      static {
        __name(this, "Logger");
      }
      instrumentationScope;
      _sharedState;
      constructor(instrumentationScope, _sharedState) {
        this.instrumentationScope = instrumentationScope;
        this._sharedState = _sharedState;
      }
      emit(logRecord) {
        const currentContext = logRecord.context || api_1.context.active();
        const logRecordInstance = new LogRecordImpl_1.LogRecordImpl(this._sharedState, this.instrumentationScope, {
          context: currentContext,
          ...logRecord
        });
        this._sharedState.activeProcessor.onEmit(logRecordInstance, currentContext);
        logRecordInstance._makeReadonly();
      }
    };
    exports2.Logger = Logger2;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/config.js
var require_config = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/config.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.reconfigureLimits = exports2.loadDefaultConfig = void 0;
    var core_1 = require_src8();
    function loadDefaultConfig() {
      return {
        forceFlushTimeoutMillis: 3e4,
        logRecordLimits: {
          attributeValueLengthLimit: (0, core_1.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity,
          attributeCountLimit: (0, core_1.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT") ?? 128
        },
        includeTraceContext: true
      };
    }
    __name(loadDefaultConfig, "loadDefaultConfig");
    exports2.loadDefaultConfig = loadDefaultConfig;
    function reconfigureLimits(logRecordLimits) {
      return {
        /**
         * Reassign log record attribute count limit to use first non null value defined by user or use default value
         */
        attributeCountLimit: logRecordLimits.attributeCountLimit ?? (0, core_1.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT") ?? (0, core_1.getNumberFromEnv)("OTEL_ATTRIBUTE_COUNT_LIMIT") ?? 128,
        /**
         * Reassign log record attribute value length limit to use first non null value defined by user or use default value
         */
        attributeValueLengthLimit: logRecordLimits.attributeValueLengthLimit ?? (0, core_1.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? (0, core_1.getNumberFromEnv)("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity
      };
    }
    __name(reconfigureLimits, "reconfigureLimits");
    exports2.reconfigureLimits = reconfigureLimits;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/export/NoopLogRecordProcessor.js
var require_NoopLogRecordProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/export/NoopLogRecordProcessor.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NoopLogRecordProcessor = void 0;
    var NoopLogRecordProcessor = class {
      static {
        __name(this, "NoopLogRecordProcessor");
      }
      forceFlush() {
        return Promise.resolve();
      }
      onEmit(_logRecord, _context) {
      }
      shutdown() {
        return Promise.resolve();
      }
    };
    exports2.NoopLogRecordProcessor = NoopLogRecordProcessor;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/MultiLogRecordProcessor.js
var require_MultiLogRecordProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/MultiLogRecordProcessor.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MultiLogRecordProcessor = void 0;
    var core_1 = require_src8();
    var MultiLogRecordProcessor = class {
      static {
        __name(this, "MultiLogRecordProcessor");
      }
      processors;
      forceFlushTimeoutMillis;
      constructor(processors, forceFlushTimeoutMillis) {
        this.processors = processors;
        this.forceFlushTimeoutMillis = forceFlushTimeoutMillis;
      }
      async forceFlush() {
        const timeout2 = this.forceFlushTimeoutMillis;
        await Promise.all(this.processors.map((processor) => (0, core_1.callWithTimeout)(processor.forceFlush(), timeout2)));
      }
      onEmit(logRecord, context2) {
        this.processors.forEach((processors) => processors.onEmit(logRecord, context2));
      }
      async shutdown() {
        await Promise.all(this.processors.map((processor) => processor.shutdown()));
      }
    };
    exports2.MultiLogRecordProcessor = MultiLogRecordProcessor;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/internal/LoggerProviderSharedState.js
var require_LoggerProviderSharedState = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/internal/LoggerProviderSharedState.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LoggerProviderSharedState = void 0;
    var NoopLogRecordProcessor_1 = require_NoopLogRecordProcessor();
    var MultiLogRecordProcessor_1 = require_MultiLogRecordProcessor();
    var LoggerProviderSharedState = class {
      static {
        __name(this, "LoggerProviderSharedState");
      }
      resource;
      forceFlushTimeoutMillis;
      logRecordLimits;
      processors;
      loggers = /* @__PURE__ */ new Map();
      activeProcessor;
      registeredLogRecordProcessors = [];
      constructor(resource, forceFlushTimeoutMillis, logRecordLimits, processors) {
        this.resource = resource;
        this.forceFlushTimeoutMillis = forceFlushTimeoutMillis;
        this.logRecordLimits = logRecordLimits;
        this.processors = processors;
        if (processors.length > 0) {
          this.registeredLogRecordProcessors = processors;
          this.activeProcessor = new MultiLogRecordProcessor_1.MultiLogRecordProcessor(this.registeredLogRecordProcessors, this.forceFlushTimeoutMillis);
        } else {
          this.activeProcessor = new NoopLogRecordProcessor_1.NoopLogRecordProcessor();
        }
      }
    };
    exports2.LoggerProviderSharedState = LoggerProviderSharedState;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/LoggerProvider.js
var require_LoggerProvider = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/LoggerProvider.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LoggerProvider = exports2.DEFAULT_LOGGER_NAME = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var api_logs_1 = require_src7();
    var resources_1 = require_src13();
    var core_1 = require_src8();
    var Logger_1 = require_Logger();
    var config_1 = require_config();
    var LoggerProviderSharedState_1 = require_LoggerProviderSharedState();
    exports2.DEFAULT_LOGGER_NAME = "unknown";
    var LoggerProvider = class {
      static {
        __name(this, "LoggerProvider");
      }
      _shutdownOnce;
      _sharedState;
      constructor(config = {}) {
        const mergedConfig = (0, core_1.merge)({}, (0, config_1.loadDefaultConfig)(), config);
        const resource = config.resource ?? (0, resources_1.defaultResource)();
        this._sharedState = new LoggerProviderSharedState_1.LoggerProviderSharedState(resource, mergedConfig.forceFlushTimeoutMillis, (0, config_1.reconfigureLimits)(mergedConfig.logRecordLimits), config?.processors ?? []);
        this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this);
      }
      /**
       * Get a logger with the configuration of the LoggerProvider.
       */
      getLogger(name3, version2, options2) {
        if (this._shutdownOnce.isCalled) {
          api_1.diag.warn("A shutdown LoggerProvider cannot provide a Logger");
          return api_logs_1.NOOP_LOGGER;
        }
        if (!name3) {
          api_1.diag.warn("Logger requested without instrumentation scope name.");
        }
        const loggerName = name3 || exports2.DEFAULT_LOGGER_NAME;
        const key = `${loggerName}@${version2 || ""}:${options2?.schemaUrl || ""}`;
        if (!this._sharedState.loggers.has(key)) {
          this._sharedState.loggers.set(key, new Logger_1.Logger({ name: loggerName, version: version2, schemaUrl: options2?.schemaUrl }, this._sharedState));
        }
        return this._sharedState.loggers.get(key);
      }
      /**
       * Notifies all registered LogRecordProcessor to flush any buffered data.
       *
       * Returns a promise which is resolved when all flushes are complete.
       */
      forceFlush() {
        if (this._shutdownOnce.isCalled) {
          api_1.diag.warn("invalid attempt to force flush after LoggerProvider shutdown");
          return this._shutdownOnce.promise;
        }
        return this._sharedState.activeProcessor.forceFlush();
      }
      /**
       * Flush all buffered data and shut down the LoggerProvider and all registered
       * LogRecordProcessor.
       *
       * Returns a promise which is resolved when all flushes are complete.
       */
      shutdown() {
        if (this._shutdownOnce.isCalled) {
          api_1.diag.warn("shutdown may only be called once per LoggerProvider");
          return this._shutdownOnce.promise;
        }
        return this._shutdownOnce.call();
      }
      _shutdown() {
        return this._sharedState.activeProcessor.shutdown();
      }
    };
    exports2.LoggerProvider = LoggerProvider;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/export/ConsoleLogRecordExporter.js
var require_ConsoleLogRecordExporter = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/export/ConsoleLogRecordExporter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ConsoleLogRecordExporter = void 0;
    var core_1 = require_src8();
    var core_2 = require_src8();
    var ConsoleLogRecordExporter2 = class {
      static {
        __name(this, "ConsoleLogRecordExporter");
      }
      /**
       * Export logs.
       * @param logs
       * @param resultCallback
       */
      export(logs2, resultCallback) {
        this._sendLogRecords(logs2, resultCallback);
      }
      /**
       * Shutdown the exporter.
       */
      shutdown() {
        return Promise.resolve();
      }
      /**
       * converts logRecord info into more readable format
       * @param logRecord
       */
      _exportInfo(logRecord) {
        return {
          resource: {
            attributes: logRecord.resource.attributes
          },
          instrumentationScope: logRecord.instrumentationScope,
          timestamp: (0, core_1.hrTimeToMicroseconds)(logRecord.hrTime),
          traceId: logRecord.spanContext?.traceId,
          spanId: logRecord.spanContext?.spanId,
          traceFlags: logRecord.spanContext?.traceFlags,
          severityText: logRecord.severityText,
          severityNumber: logRecord.severityNumber,
          body: logRecord.body,
          attributes: logRecord.attributes
        };
      }
      /**
       * Showing logs  in console
       * @param logRecords
       * @param done
       */
      _sendLogRecords(logRecords, done) {
        for (const logRecord of logRecords) {
          console.dir(this._exportInfo(logRecord), { depth: 3 });
        }
        done?.({ code: core_2.ExportResultCode.SUCCESS });
      }
    };
    exports2.ConsoleLogRecordExporter = ConsoleLogRecordExporter2;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/export/SimpleLogRecordProcessor.js
var require_SimpleLogRecordProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/export/SimpleLogRecordProcessor.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SimpleLogRecordProcessor = void 0;
    var core_1 = require_src8();
    var SimpleLogRecordProcessor = class {
      static {
        __name(this, "SimpleLogRecordProcessor");
      }
      _exporter;
      _shutdownOnce;
      _unresolvedExports;
      constructor(_exporter) {
        this._exporter = _exporter;
        this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this);
        this._unresolvedExports = /* @__PURE__ */ new Set();
      }
      onEmit(logRecord) {
        if (this._shutdownOnce.isCalled) {
          return;
        }
        const doExport = /* @__PURE__ */ __name(() => core_1.internal._export(this._exporter, [logRecord]).then((result) => {
          if (result.code !== core_1.ExportResultCode.SUCCESS) {
            (0, core_1.globalErrorHandler)(result.error ?? new Error(`SimpleLogRecordProcessor: log record export failed (status ${result})`));
          }
        }).catch(core_1.globalErrorHandler), "doExport");
        if (logRecord.resource.asyncAttributesPending) {
          const exportPromise = logRecord.resource.waitForAsyncAttributes?.().then(() => {
            this._unresolvedExports.delete(exportPromise);
            return doExport();
          }, core_1.globalErrorHandler);
          if (exportPromise != null) {
            this._unresolvedExports.add(exportPromise);
          }
        } else {
          void doExport();
        }
      }
      async forceFlush() {
        await Promise.all(Array.from(this._unresolvedExports));
      }
      shutdown() {
        return this._shutdownOnce.call();
      }
      _shutdown() {
        return this._exporter.shutdown();
      }
    };
    exports2.SimpleLogRecordProcessor = SimpleLogRecordProcessor;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/export/InMemoryLogRecordExporter.js
var require_InMemoryLogRecordExporter = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/export/InMemoryLogRecordExporter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InMemoryLogRecordExporter = void 0;
    var core_1 = require_src8();
    var InMemoryLogRecordExporter = class {
      static {
        __name(this, "InMemoryLogRecordExporter");
      }
      _finishedLogRecords = [];
      /**
       * Indicates if the exporter has been "shutdown."
       * When false, exported log records will not be stored in-memory.
       */
      _stopped = false;
      export(logs2, resultCallback) {
        if (this._stopped) {
          return resultCallback({
            code: core_1.ExportResultCode.FAILED,
            error: new Error("Exporter has been stopped")
          });
        }
        this._finishedLogRecords.push(...logs2);
        resultCallback({ code: core_1.ExportResultCode.SUCCESS });
      }
      shutdown() {
        this._stopped = true;
        this.reset();
        return Promise.resolve();
      }
      getFinishedLogRecords() {
        return this._finishedLogRecords;
      }
      reset() {
        this._finishedLogRecords = [];
      }
    };
    exports2.InMemoryLogRecordExporter = InMemoryLogRecordExporter;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/export/BatchLogRecordProcessorBase.js
var require_BatchLogRecordProcessorBase = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/export/BatchLogRecordProcessorBase.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BatchLogRecordProcessorBase = void 0;
    var core_1 = require_src8();
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_2 = require_src8();
    var BatchLogRecordProcessorBase = class {
      static {
        __name(this, "BatchLogRecordProcessorBase");
      }
      _exporter;
      _maxExportBatchSize;
      _maxQueueSize;
      _scheduledDelayMillis;
      _exportTimeoutMillis;
      _finishedLogRecords = [];
      _timer;
      _shutdownOnce;
      constructor(_exporter, config) {
        this._exporter = _exporter;
        this._maxExportBatchSize = config?.maxExportBatchSize ?? (0, core_1.getNumberFromEnv)("OTEL_BLRP_MAX_EXPORT_BATCH_SIZE") ?? 512;
        this._maxQueueSize = config?.maxQueueSize ?? (0, core_1.getNumberFromEnv)("OTEL_BLRP_MAX_QUEUE_SIZE") ?? 2048;
        this._scheduledDelayMillis = config?.scheduledDelayMillis ?? (0, core_1.getNumberFromEnv)("OTEL_BLRP_SCHEDULE_DELAY") ?? 5e3;
        this._exportTimeoutMillis = config?.exportTimeoutMillis ?? (0, core_1.getNumberFromEnv)("OTEL_BLRP_EXPORT_TIMEOUT") ?? 3e4;
        this._shutdownOnce = new core_2.BindOnceFuture(this._shutdown, this);
        if (this._maxExportBatchSize > this._maxQueueSize) {
          api_1.diag.warn("BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize");
          this._maxExportBatchSize = this._maxQueueSize;
        }
      }
      onEmit(logRecord) {
        if (this._shutdownOnce.isCalled) {
          return;
        }
        this._addToBuffer(logRecord);
      }
      forceFlush() {
        if (this._shutdownOnce.isCalled) {
          return this._shutdownOnce.promise;
        }
        return this._flushAll();
      }
      shutdown() {
        return this._shutdownOnce.call();
      }
      async _shutdown() {
        this.onShutdown();
        await this._flushAll();
        await this._exporter.shutdown();
      }
      /** Add a LogRecord in the buffer. */
      _addToBuffer(logRecord) {
        if (this._finishedLogRecords.length >= this._maxQueueSize) {
          return;
        }
        this._finishedLogRecords.push(logRecord);
        this._maybeStartTimer();
      }
      /**
       * Send all LogRecords to the exporter respecting the batch size limit
       * This function is used only on forceFlush or shutdown,
       * for all other cases _flush should be used
       * */
      _flushAll() {
        return new Promise((resolve24, reject) => {
          const promises6 = [];
          const batchCount = Math.ceil(this._finishedLogRecords.length / this._maxExportBatchSize);
          for (let i = 0; i < batchCount; i++) {
            promises6.push(this._flushOneBatch());
          }
          Promise.all(promises6).then(() => {
            resolve24();
          }).catch(reject);
        });
      }
      _flushOneBatch() {
        this._clearTimer();
        if (this._finishedLogRecords.length === 0) {
          return Promise.resolve();
        }
        return new Promise((resolve24, reject) => {
          (0, core_2.callWithTimeout)(this._export(this._finishedLogRecords.splice(0, this._maxExportBatchSize)), this._exportTimeoutMillis).then(() => resolve24()).catch(reject);
        });
      }
      _maybeStartTimer() {
        if (this._timer !== void 0) {
          return;
        }
        this._timer = setTimeout(() => {
          this._flushOneBatch().then(() => {
            if (this._finishedLogRecords.length > 0) {
              this._clearTimer();
              this._maybeStartTimer();
            }
          }).catch((e2) => {
            (0, core_2.globalErrorHandler)(e2);
          });
        }, this._scheduledDelayMillis);
        (0, core_2.unrefTimer)(this._timer);
      }
      _clearTimer() {
        if (this._timer !== void 0) {
          clearTimeout(this._timer);
          this._timer = void 0;
        }
      }
      _export(logRecords) {
        const doExport = /* @__PURE__ */ __name(() => core_2.internal._export(this._exporter, logRecords).then((result) => {
          if (result.code !== core_2.ExportResultCode.SUCCESS) {
            (0, core_2.globalErrorHandler)(result.error ?? new Error(`BatchLogRecordProcessor: log record export failed (status ${result})`));
          }
        }).catch(core_2.globalErrorHandler), "doExport");
        const pendingResources = logRecords.map((logRecord) => logRecord.resource).filter((resource) => resource.asyncAttributesPending);
        if (pendingResources.length === 0) {
          return doExport();
        } else {
          return Promise.all(pendingResources.map((resource) => resource.waitForAsyncAttributes?.())).then(doExport, core_2.globalErrorHandler);
        }
      }
    };
    exports2.BatchLogRecordProcessorBase = BatchLogRecordProcessorBase;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/platform/node/export/BatchLogRecordProcessor.js
var require_BatchLogRecordProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/platform/node/export/BatchLogRecordProcessor.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BatchLogRecordProcessor = void 0;
    var BatchLogRecordProcessorBase_1 = require_BatchLogRecordProcessorBase();
    var BatchLogRecordProcessor2 = class extends BatchLogRecordProcessorBase_1.BatchLogRecordProcessorBase {
      static {
        __name(this, "BatchLogRecordProcessor");
      }
      onShutdown() {
      }
    };
    exports2.BatchLogRecordProcessor = BatchLogRecordProcessor2;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/platform/node/index.js
var require_node9 = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/platform/node/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BatchLogRecordProcessor = void 0;
    var BatchLogRecordProcessor_1 = require_BatchLogRecordProcessor();
    Object.defineProperty(exports2, "BatchLogRecordProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return BatchLogRecordProcessor_1.BatchLogRecordProcessor;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/platform/index.js
var require_platform8 = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/platform/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BatchLogRecordProcessor = void 0;
    var node_1 = require_node9();
    Object.defineProperty(exports2, "BatchLogRecordProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.BatchLogRecordProcessor;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/index.js
var require_src22 = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BatchLogRecordProcessor = exports2.InMemoryLogRecordExporter = exports2.SimpleLogRecordProcessor = exports2.ConsoleLogRecordExporter = exports2.NoopLogRecordProcessor = exports2.LoggerProvider = void 0;
    var LoggerProvider_1 = require_LoggerProvider();
    Object.defineProperty(exports2, "LoggerProvider", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return LoggerProvider_1.LoggerProvider;
    }, "get") });
    var NoopLogRecordProcessor_1 = require_NoopLogRecordProcessor();
    Object.defineProperty(exports2, "NoopLogRecordProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return NoopLogRecordProcessor_1.NoopLogRecordProcessor;
    }, "get") });
    var ConsoleLogRecordExporter_1 = require_ConsoleLogRecordExporter();
    Object.defineProperty(exports2, "ConsoleLogRecordExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ConsoleLogRecordExporter_1.ConsoleLogRecordExporter;
    }, "get") });
    var SimpleLogRecordProcessor_1 = require_SimpleLogRecordProcessor();
    Object.defineProperty(exports2, "SimpleLogRecordProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return SimpleLogRecordProcessor_1.SimpleLogRecordProcessor;
    }, "get") });
    var InMemoryLogRecordExporter_1 = require_InMemoryLogRecordExporter();
    Object.defineProperty(exports2, "InMemoryLogRecordExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return InMemoryLogRecordExporter_1.InMemoryLogRecordExporter;
    }, "get") });
    var platform_1 = require_platform8();
    Object.defineProperty(exports2, "BatchLogRecordProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.BatchLogRecordProcessor;
    }, "get") });
  }
});

// node_modules/@opentelemetry/context-async-hooks/build/src/AbstractAsyncHooksContextManager.js
var require_AbstractAsyncHooksContextManager = __commonJS({
  "node_modules/@opentelemetry/context-async-hooks/build/src/AbstractAsyncHooksContextManager.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AbstractAsyncHooksContextManager = void 0;
    var events_1 = __require("events");
    var ADD_LISTENER_METHODS = [
      "addListener",
      "on",
      "once",
      "prependListener",
      "prependOnceListener"
    ];
    var AbstractAsyncHooksContextManager = class {
      static {
        __name(this, "AbstractAsyncHooksContextManager");
      }
      /**
       * Binds a the certain context or the active one to the target function and then returns the target
       * @param context A context (span) to be bind to target
       * @param target a function or event emitter. When target or one of its callbacks is called,
       *  the provided context will be used as the active context for the duration of the call.
       */
      bind(context2, target) {
        if (target instanceof events_1.EventEmitter) {
          return this._bindEventEmitter(context2, target);
        }
        if (typeof target === "function") {
          return this._bindFunction(context2, target);
        }
        return target;
      }
      _bindFunction(context2, target) {
        const manager = this;
        const contextWrapper = /* @__PURE__ */ __name(function(...args) {
          return manager.with(context2, () => target.apply(this, args));
        }, "contextWrapper");
        Object.defineProperty(contextWrapper, "length", {
          enumerable: false,
          configurable: true,
          writable: false,
          value: target.length
        });
        return contextWrapper;
      }
      /**
       * By default, EventEmitter call their callback with their context, which we do
       * not want, instead we will bind a specific context to all callbacks that
       * go through it.
       * @param context the context we want to bind
       * @param ee EventEmitter an instance of EventEmitter to patch
       */
      _bindEventEmitter(context2, ee) {
        const map2 = this._getPatchMap(ee);
        if (map2 !== void 0)
          return ee;
        this._createPatchMap(ee);
        ADD_LISTENER_METHODS.forEach((methodName) => {
          if (ee[methodName] === void 0)
            return;
          ee[methodName] = this._patchAddListener(ee, ee[methodName], context2);
        });
        if (typeof ee.removeListener === "function") {
          ee.removeListener = this._patchRemoveListener(ee, ee.removeListener);
        }
        if (typeof ee.off === "function") {
          ee.off = this._patchRemoveListener(ee, ee.off);
        }
        if (typeof ee.removeAllListeners === "function") {
          ee.removeAllListeners = this._patchRemoveAllListeners(ee, ee.removeAllListeners);
        }
        return ee;
      }
      /**
       * Patch methods that remove a given listener so that we match the "patched"
       * version of that listener (the one that propagate context).
       * @param ee EventEmitter instance
       * @param original reference to the patched method
       */
      _patchRemoveListener(ee, original) {
        const contextManager = this;
        return function(event, listener) {
          const events = contextManager._getPatchMap(ee)?.[event];
          if (events === void 0) {
            return original.call(this, event, listener);
          }
          const patchedListener = events.get(listener);
          return original.call(this, event, patchedListener || listener);
        };
      }
      /**
       * Patch methods that remove all listeners so we remove our
       * internal references for a given event.
       * @param ee EventEmitter instance
       * @param original reference to the patched method
       */
      _patchRemoveAllListeners(ee, original) {
        const contextManager = this;
        return function(event) {
          const map2 = contextManager._getPatchMap(ee);
          if (map2 !== void 0) {
            if (arguments.length === 0) {
              contextManager._createPatchMap(ee);
            } else if (map2[event] !== void 0) {
              delete map2[event];
            }
          }
          return original.apply(this, arguments);
        };
      }
      /**
       * Patch methods on an event emitter instance that can add listeners so we
       * can force them to propagate a given context.
       * @param ee EventEmitter instance
       * @param original reference to the patched method
       * @param [context] context to propagate when calling listeners
       */
      _patchAddListener(ee, original, context2) {
        const contextManager = this;
        return function(event, listener) {
          if (contextManager._wrapped) {
            return original.call(this, event, listener);
          }
          let map2 = contextManager._getPatchMap(ee);
          if (map2 === void 0) {
            map2 = contextManager._createPatchMap(ee);
          }
          let listeners = map2[event];
          if (listeners === void 0) {
            listeners = /* @__PURE__ */ new WeakMap();
            map2[event] = listeners;
          }
          const patchedListener = contextManager.bind(context2, listener);
          listeners.set(listener, patchedListener);
          contextManager._wrapped = true;
          try {
            return original.call(this, event, patchedListener);
          } finally {
            contextManager._wrapped = false;
          }
        };
      }
      _createPatchMap(ee) {
        const map2 = /* @__PURE__ */ Object.create(null);
        ee[this._kOtListeners] = map2;
        return map2;
      }
      _getPatchMap(ee) {
        return ee[this._kOtListeners];
      }
      _kOtListeners = Symbol("OtListeners");
      _wrapped = false;
    };
    exports2.AbstractAsyncHooksContextManager = AbstractAsyncHooksContextManager;
  }
});

// node_modules/@opentelemetry/context-async-hooks/build/src/AsyncHooksContextManager.js
var require_AsyncHooksContextManager = __commonJS({
  "node_modules/@opentelemetry/context-async-hooks/build/src/AsyncHooksContextManager.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AsyncHooksContextManager = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var asyncHooks = __require("async_hooks");
    var AbstractAsyncHooksContextManager_1 = require_AbstractAsyncHooksContextManager();
    var AsyncHooksContextManager = class extends AbstractAsyncHooksContextManager_1.AbstractAsyncHooksContextManager {
      static {
        __name(this, "AsyncHooksContextManager");
      }
      _asyncHook;
      _contexts = /* @__PURE__ */ new Map();
      _stack = [];
      constructor() {
        super();
        this._asyncHook = asyncHooks.createHook({
          init: this._init.bind(this),
          before: this._before.bind(this),
          after: this._after.bind(this),
          destroy: this._destroy.bind(this),
          promiseResolve: this._destroy.bind(this)
        });
      }
      active() {
        return this._stack[this._stack.length - 1] ?? api_1.ROOT_CONTEXT;
      }
      with(context2, fn, thisArg, ...args) {
        this._enterContext(context2);
        try {
          return fn.call(thisArg, ...args);
        } finally {
          this._exitContext();
        }
      }
      enable() {
        this._asyncHook.enable();
        return this;
      }
      disable() {
        this._asyncHook.disable();
        this._contexts.clear();
        this._stack = [];
        return this;
      }
      /**
       * Init hook will be called when userland create a async context, setting the
       * context as the current one if it exist.
       * @param uid id of the async context
       * @param type the resource type
       */
      _init(uid, type) {
        if (type === "TIMERWRAP")
          return;
        const context2 = this._stack[this._stack.length - 1];
        if (context2 !== void 0) {
          this._contexts.set(uid, context2);
        }
      }
      /**
       * Destroy hook will be called when a given context is no longer used so we can
       * remove its attached context.
       * @param uid uid of the async context
       */
      _destroy(uid) {
        this._contexts.delete(uid);
      }
      /**
       * Before hook is called just before executing a async context.
       * @param uid uid of the async context
       */
      _before(uid) {
        const context2 = this._contexts.get(uid);
        if (context2 !== void 0) {
          this._enterContext(context2);
        }
      }
      /**
       * After hook is called just after completing the execution of a async context.
       */
      _after() {
        this._exitContext();
      }
      /**
       * Set the given context as active
       */
      _enterContext(context2) {
        this._stack.push(context2);
      }
      /**
       * Remove the context at the root of the stack
       */
      _exitContext() {
        this._stack.pop();
      }
    };
    exports2.AsyncHooksContextManager = AsyncHooksContextManager;
  }
});

// node_modules/@opentelemetry/context-async-hooks/build/src/AsyncLocalStorageContextManager.js
var require_AsyncLocalStorageContextManager = __commonJS({
  "node_modules/@opentelemetry/context-async-hooks/build/src/AsyncLocalStorageContextManager.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AsyncLocalStorageContextManager = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var async_hooks_1 = __require("async_hooks");
    var AbstractAsyncHooksContextManager_1 = require_AbstractAsyncHooksContextManager();
    var AsyncLocalStorageContextManager = class extends AbstractAsyncHooksContextManager_1.AbstractAsyncHooksContextManager {
      static {
        __name(this, "AsyncLocalStorageContextManager");
      }
      _asyncLocalStorage;
      constructor() {
        super();
        this._asyncLocalStorage = new async_hooks_1.AsyncLocalStorage();
      }
      active() {
        return this._asyncLocalStorage.getStore() ?? api_1.ROOT_CONTEXT;
      }
      with(context2, fn, thisArg, ...args) {
        const cb = thisArg == null ? fn : fn.bind(thisArg);
        return this._asyncLocalStorage.run(context2, cb, ...args);
      }
      enable() {
        return this;
      }
      disable() {
        this._asyncLocalStorage.disable();
        return this;
      }
    };
    exports2.AsyncLocalStorageContextManager = AsyncLocalStorageContextManager;
  }
});

// node_modules/@opentelemetry/context-async-hooks/build/src/index.js
var require_src23 = __commonJS({
  "node_modules/@opentelemetry/context-async-hooks/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AsyncLocalStorageContextManager = exports2.AsyncHooksContextManager = void 0;
    var AsyncHooksContextManager_1 = require_AsyncHooksContextManager();
    Object.defineProperty(exports2, "AsyncHooksContextManager", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return AsyncHooksContextManager_1.AsyncHooksContextManager;
    }, "get") });
    var AsyncLocalStorageContextManager_1 = require_AsyncLocalStorageContextManager();
    Object.defineProperty(exports2, "AsyncLocalStorageContextManager", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return AsyncLocalStorageContextManager_1.AsyncLocalStorageContextManager;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/enums.js
var require_enums = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/enums.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ExceptionEventName = void 0;
    exports2.ExceptionEventName = "exception";
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/Span.js
var require_Span = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/Span.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SpanImpl = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var semantic_conventions_1 = (init_esm(), __toCommonJS(esm_exports));
    var enums_1 = require_enums();
    var SpanImpl = class {
      static {
        __name(this, "SpanImpl");
      }
      // Below properties are included to implement ReadableSpan for export
      // purposes but are not intended to be written-to directly.
      _spanContext;
      kind;
      parentSpanContext;
      attributes = {};
      links = [];
      events = [];
      startTime;
      resource;
      instrumentationScope;
      _droppedAttributesCount = 0;
      _droppedEventsCount = 0;
      _droppedLinksCount = 0;
      name;
      status = {
        code: api_1.SpanStatusCode.UNSET
      };
      endTime = [0, 0];
      _ended = false;
      _duration = [-1, -1];
      _spanProcessor;
      _spanLimits;
      _attributeValueLengthLimit;
      _performanceStartTime;
      _performanceOffset;
      _startTimeProvided;
      /**
       * Constructs a new SpanImpl instance.
       */
      constructor(opts) {
        const now = Date.now();
        this._spanContext = opts.spanContext;
        this._performanceStartTime = core_1.otperformance.now();
        this._performanceOffset = now - (this._performanceStartTime + (0, core_1.getTimeOrigin)());
        this._startTimeProvided = opts.startTime != null;
        this._spanLimits = opts.spanLimits;
        this._attributeValueLengthLimit = this._spanLimits.attributeValueLengthLimit || 0;
        this._spanProcessor = opts.spanProcessor;
        this.name = opts.name;
        this.parentSpanContext = opts.parentSpanContext;
        this.kind = opts.kind;
        this.links = opts.links || [];
        this.startTime = this._getTime(opts.startTime ?? now);
        this.resource = opts.resource;
        this.instrumentationScope = opts.scope;
        if (opts.attributes != null) {
          this.setAttributes(opts.attributes);
        }
        this._spanProcessor.onStart(this, opts.context);
      }
      spanContext() {
        return this._spanContext;
      }
      setAttribute(key, value) {
        if (value == null || this._isSpanEnded())
          return this;
        if (key.length === 0) {
          api_1.diag.warn(`Invalid attribute key: ${key}`);
          return this;
        }
        if (!(0, core_1.isAttributeValue)(value)) {
          api_1.diag.warn(`Invalid attribute value set for key: ${key}`);
          return this;
        }
        const { attributeCountLimit } = this._spanLimits;
        if (attributeCountLimit !== void 0 && Object.keys(this.attributes).length >= attributeCountLimit && !Object.prototype.hasOwnProperty.call(this.attributes, key)) {
          this._droppedAttributesCount++;
          return this;
        }
        this.attributes[key] = this._truncateToSize(value);
        return this;
      }
      setAttributes(attributes) {
        for (const [k, v] of Object.entries(attributes)) {
          this.setAttribute(k, v);
        }
        return this;
      }
      /**
       *
       * @param name Span Name
       * @param [attributesOrStartTime] Span attributes or start time
       *     if type is {@type TimeInput} and 3rd param is undefined
       * @param [timeStamp] Specified time stamp for the event
       */
      addEvent(name3, attributesOrStartTime, timeStamp) {
        if (this._isSpanEnded())
          return this;
        const { eventCountLimit } = this._spanLimits;
        if (eventCountLimit === 0) {
          api_1.diag.warn("No events allowed.");
          this._droppedEventsCount++;
          return this;
        }
        if (eventCountLimit !== void 0 && this.events.length >= eventCountLimit) {
          if (this._droppedEventsCount === 0) {
            api_1.diag.debug("Dropping extra events.");
          }
          this.events.shift();
          this._droppedEventsCount++;
        }
        if ((0, core_1.isTimeInput)(attributesOrStartTime)) {
          if (!(0, core_1.isTimeInput)(timeStamp)) {
            timeStamp = attributesOrStartTime;
          }
          attributesOrStartTime = void 0;
        }
        const attributes = (0, core_1.sanitizeAttributes)(attributesOrStartTime);
        this.events.push({
          name: name3,
          attributes,
          time: this._getTime(timeStamp),
          droppedAttributesCount: 0
        });
        return this;
      }
      addLink(link3) {
        this.links.push(link3);
        return this;
      }
      addLinks(links) {
        this.links.push(...links);
        return this;
      }
      setStatus(status) {
        if (this._isSpanEnded())
          return this;
        this.status = { ...status };
        if (this.status.message != null && typeof status.message !== "string") {
          api_1.diag.warn(`Dropping invalid status.message of type '${typeof status.message}', expected 'string'`);
          delete this.status.message;
        }
        return this;
      }
      updateName(name3) {
        if (this._isSpanEnded())
          return this;
        this.name = name3;
        return this;
      }
      end(endTime) {
        if (this._isSpanEnded()) {
          api_1.diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);
          return;
        }
        this._ended = true;
        this.endTime = this._getTime(endTime);
        this._duration = (0, core_1.hrTimeDuration)(this.startTime, this.endTime);
        if (this._duration[0] < 0) {
          api_1.diag.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.", this.startTime, this.endTime);
          this.endTime = this.startTime.slice();
          this._duration = [0, 0];
        }
        if (this._droppedEventsCount > 0) {
          api_1.diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`);
        }
        this._spanProcessor.onEnd(this);
      }
      _getTime(inp) {
        if (typeof inp === "number" && inp <= core_1.otperformance.now()) {
          return (0, core_1.hrTime)(inp + this._performanceOffset);
        }
        if (typeof inp === "number") {
          return (0, core_1.millisToHrTime)(inp);
        }
        if (inp instanceof Date) {
          return (0, core_1.millisToHrTime)(inp.getTime());
        }
        if ((0, core_1.isTimeInputHrTime)(inp)) {
          return inp;
        }
        if (this._startTimeProvided) {
          return (0, core_1.millisToHrTime)(Date.now());
        }
        const msDuration = core_1.otperformance.now() - this._performanceStartTime;
        return (0, core_1.addHrTimes)(this.startTime, (0, core_1.millisToHrTime)(msDuration));
      }
      isRecording() {
        return this._ended === false;
      }
      recordException(exception, time) {
        const attributes = {};
        if (typeof exception === "string") {
          attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE] = exception;
        } else if (exception) {
          if (exception.code) {
            attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] = exception.code.toString();
          } else if (exception.name) {
            attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] = exception.name;
          }
          if (exception.message) {
            attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE] = exception.message;
          }
          if (exception.stack) {
            attributes[semantic_conventions_1.ATTR_EXCEPTION_STACKTRACE] = exception.stack;
          }
        }
        if (attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] || attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE]) {
          this.addEvent(enums_1.ExceptionEventName, attributes, time);
        } else {
          api_1.diag.warn(`Failed to record an exception ${exception}`);
        }
      }
      get duration() {
        return this._duration;
      }
      get ended() {
        return this._ended;
      }
      get droppedAttributesCount() {
        return this._droppedAttributesCount;
      }
      get droppedEventsCount() {
        return this._droppedEventsCount;
      }
      get droppedLinksCount() {
        return this._droppedLinksCount;
      }
      _isSpanEnded() {
        if (this._ended) {
          const error = new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);
          api_1.diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`, error);
        }
        return this._ended;
      }
      // Utility function to truncate given value within size
      // for value type of string, will truncate to given limit
      // for type of non-string, will return same value
      _truncateToLimitUtil(value, limit2) {
        if (value.length <= limit2) {
          return value;
        }
        return value.substring(0, limit2);
      }
      /**
       * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
       * return string with truncated to {@code attributeValueLengthLimit} characters
       *
       * If the given attribute value is array of strings then
       * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters
       *
       * Otherwise return same Attribute {@code value}
       *
       * @param value Attribute value
       * @returns truncated attribute value if required, otherwise same value
       */
      _truncateToSize(value) {
        const limit2 = this._attributeValueLengthLimit;
        if (limit2 <= 0) {
          api_1.diag.warn(`Attribute value limit must be positive, got ${limit2}`);
          return value;
        }
        if (typeof value === "string") {
          return this._truncateToLimitUtil(value, limit2);
        }
        if (Array.isArray(value)) {
          return value.map((val) => typeof val === "string" ? this._truncateToLimitUtil(val, limit2) : val);
        }
        return value;
      }
    };
    exports2.SpanImpl = SpanImpl;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/Sampler.js
var require_Sampler = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/Sampler.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SamplingDecision = void 0;
    var SamplingDecision2;
    (function(SamplingDecision3) {
      SamplingDecision3[SamplingDecision3["NOT_RECORD"] = 0] = "NOT_RECORD";
      SamplingDecision3[SamplingDecision3["RECORD"] = 1] = "RECORD";
      SamplingDecision3[SamplingDecision3["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED";
    })(SamplingDecision2 = exports2.SamplingDecision || (exports2.SamplingDecision = {}));
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOffSampler.js
var require_AlwaysOffSampler = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOffSampler.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AlwaysOffSampler = void 0;
    var Sampler_1 = require_Sampler();
    var AlwaysOffSampler = class {
      static {
        __name(this, "AlwaysOffSampler");
      }
      shouldSample() {
        return {
          decision: Sampler_1.SamplingDecision.NOT_RECORD
        };
      }
      toString() {
        return "AlwaysOffSampler";
      }
    };
    exports2.AlwaysOffSampler = AlwaysOffSampler;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOnSampler.js
var require_AlwaysOnSampler = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOnSampler.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AlwaysOnSampler = void 0;
    var Sampler_1 = require_Sampler();
    var AlwaysOnSampler = class {
      static {
        __name(this, "AlwaysOnSampler");
      }
      shouldSample() {
        return {
          decision: Sampler_1.SamplingDecision.RECORD_AND_SAMPLED
        };
      }
      toString() {
        return "AlwaysOnSampler";
      }
    };
    exports2.AlwaysOnSampler = AlwaysOnSampler;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/ParentBasedSampler.js
var require_ParentBasedSampler = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/ParentBasedSampler.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ParentBasedSampler = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var AlwaysOffSampler_1 = require_AlwaysOffSampler();
    var AlwaysOnSampler_1 = require_AlwaysOnSampler();
    var ParentBasedSampler = class {
      static {
        __name(this, "ParentBasedSampler");
      }
      _root;
      _remoteParentSampled;
      _remoteParentNotSampled;
      _localParentSampled;
      _localParentNotSampled;
      constructor(config) {
        this._root = config.root;
        if (!this._root) {
          (0, core_1.globalErrorHandler)(new Error("ParentBasedSampler must have a root sampler configured"));
          this._root = new AlwaysOnSampler_1.AlwaysOnSampler();
        }
        this._remoteParentSampled = config.remoteParentSampled ?? new AlwaysOnSampler_1.AlwaysOnSampler();
        this._remoteParentNotSampled = config.remoteParentNotSampled ?? new AlwaysOffSampler_1.AlwaysOffSampler();
        this._localParentSampled = config.localParentSampled ?? new AlwaysOnSampler_1.AlwaysOnSampler();
        this._localParentNotSampled = config.localParentNotSampled ?? new AlwaysOffSampler_1.AlwaysOffSampler();
      }
      shouldSample(context2, traceId, spanName, spanKind, attributes, links) {
        const parentContext = api_1.trace.getSpanContext(context2);
        if (!parentContext || !(0, api_1.isSpanContextValid)(parentContext)) {
          return this._root.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
        }
        if (parentContext.isRemote) {
          if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) {
            return this._remoteParentSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
          }
          return this._remoteParentNotSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
        }
        if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) {
          return this._localParentSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
        }
        return this._localParentNotSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
      }
      toString() {
        return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;
      }
    };
    exports2.ParentBasedSampler = ParentBasedSampler;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/TraceIdRatioBasedSampler.js
var require_TraceIdRatioBasedSampler = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/TraceIdRatioBasedSampler.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.TraceIdRatioBasedSampler = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var Sampler_1 = require_Sampler();
    var TraceIdRatioBasedSampler = class {
      static {
        __name(this, "TraceIdRatioBasedSampler");
      }
      _ratio;
      _upperBound;
      constructor(_ratio = 0) {
        this._ratio = _ratio;
        this._ratio = this._normalize(_ratio);
        this._upperBound = Math.floor(this._ratio * 4294967295);
      }
      shouldSample(context2, traceId) {
        return {
          decision: (0, api_1.isValidTraceId)(traceId) && this._accumulate(traceId) < this._upperBound ? Sampler_1.SamplingDecision.RECORD_AND_SAMPLED : Sampler_1.SamplingDecision.NOT_RECORD
        };
      }
      toString() {
        return `TraceIdRatioBased{${this._ratio}}`;
      }
      _normalize(ratio) {
        if (typeof ratio !== "number" || isNaN(ratio))
          return 0;
        return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;
      }
      _accumulate(traceId) {
        let accumulation = 0;
        for (let i = 0; i < traceId.length / 8; i++) {
          const pos2 = i * 8;
          const part = parseInt(traceId.slice(pos2, pos2 + 8), 16);
          accumulation = (accumulation ^ part) >>> 0;
        }
        return accumulation;
      }
    };
    exports2.TraceIdRatioBasedSampler = TraceIdRatioBasedSampler;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/config.js
var require_config2 = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/config.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.buildSamplerFromEnv = exports2.loadDefaultConfig = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var AlwaysOffSampler_1 = require_AlwaysOffSampler();
    var AlwaysOnSampler_1 = require_AlwaysOnSampler();
    var ParentBasedSampler_1 = require_ParentBasedSampler();
    var TraceIdRatioBasedSampler_1 = require_TraceIdRatioBasedSampler();
    var DEFAULT_RATIO = 1;
    function loadDefaultConfig() {
      return {
        sampler: buildSamplerFromEnv(),
        forceFlushTimeoutMillis: 3e4,
        generalLimits: {
          attributeValueLengthLimit: (0, core_1.getNumberFromEnv)("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity,
          attributeCountLimit: (0, core_1.getNumberFromEnv)("OTEL_ATTRIBUTE_COUNT_LIMIT") ?? 128
        },
        spanLimits: {
          attributeValueLengthLimit: (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity,
          attributeCountLimit: (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT") ?? 128,
          linkCountLimit: (0, core_1.getNumberFromEnv)("OTEL_SPAN_LINK_COUNT_LIMIT") ?? 128,
          eventCountLimit: (0, core_1.getNumberFromEnv)("OTEL_SPAN_EVENT_COUNT_LIMIT") ?? 128,
          attributePerEventCountLimit: (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT") ?? 128,
          attributePerLinkCountLimit: (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT") ?? 128
        }
      };
    }
    __name(loadDefaultConfig, "loadDefaultConfig");
    exports2.loadDefaultConfig = loadDefaultConfig;
    function buildSamplerFromEnv() {
      const sampler = (0, core_1.getStringFromEnv)("OTEL_TRACES_SAMPLER") ?? "parentbased_always_on";
      switch (sampler) {
        case "always_on":
          return new AlwaysOnSampler_1.AlwaysOnSampler();
        case "always_off":
          return new AlwaysOffSampler_1.AlwaysOffSampler();
        case "parentbased_always_on":
          return new ParentBasedSampler_1.ParentBasedSampler({
            root: new AlwaysOnSampler_1.AlwaysOnSampler()
          });
        case "parentbased_always_off":
          return new ParentBasedSampler_1.ParentBasedSampler({
            root: new AlwaysOffSampler_1.AlwaysOffSampler()
          });
        case "traceidratio":
          return new TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());
        case "parentbased_traceidratio":
          return new ParentBasedSampler_1.ParentBasedSampler({
            root: new TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv())
          });
        default:
          api_1.diag.error(`OTEL_TRACES_SAMPLER value "${sampler}" invalid, defaulting to "${"parentbased_always_on"}".`);
          return new ParentBasedSampler_1.ParentBasedSampler({
            root: new AlwaysOnSampler_1.AlwaysOnSampler()
          });
      }
    }
    __name(buildSamplerFromEnv, "buildSamplerFromEnv");
    exports2.buildSamplerFromEnv = buildSamplerFromEnv;
    function getSamplerProbabilityFromEnv() {
      const probability = (0, core_1.getNumberFromEnv)("OTEL_TRACES_SAMPLER_ARG");
      if (probability == null) {
        api_1.diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`);
        return DEFAULT_RATIO;
      }
      if (probability < 0 || probability > 1) {
        api_1.diag.error(`OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`);
        return DEFAULT_RATIO;
      }
      return probability;
    }
    __name(getSamplerProbabilityFromEnv, "getSamplerProbabilityFromEnv");
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/utility.js
var require_utility = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/utility.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.reconfigureLimits = exports2.mergeConfig = exports2.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = exports2.DEFAULT_ATTRIBUTE_COUNT_LIMIT = void 0;
    var config_1 = require_config2();
    var core_1 = require_src8();
    exports2.DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;
    exports2.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;
    function mergeConfig(userConfig) {
      const perInstanceDefaults = {
        sampler: (0, config_1.buildSamplerFromEnv)()
      };
      const DEFAULT_CONFIG = (0, config_1.loadDefaultConfig)();
      const target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig);
      target.generalLimits = Object.assign({}, DEFAULT_CONFIG.generalLimits, userConfig.generalLimits || {});
      target.spanLimits = Object.assign({}, DEFAULT_CONFIG.spanLimits, userConfig.spanLimits || {});
      return target;
    }
    __name(mergeConfig, "mergeConfig");
    exports2.mergeConfig = mergeConfig;
    function reconfigureLimits(userConfig) {
      const spanLimits = Object.assign({}, userConfig.spanLimits);
      spanLimits.attributeCountLimit = userConfig.spanLimits?.attributeCountLimit ?? userConfig.generalLimits?.attributeCountLimit ?? (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT") ?? (0, core_1.getNumberFromEnv)("OTEL_ATTRIBUTE_COUNT_LIMIT") ?? exports2.DEFAULT_ATTRIBUTE_COUNT_LIMIT;
      spanLimits.attributeValueLengthLimit = userConfig.spanLimits?.attributeValueLengthLimit ?? userConfig.generalLimits?.attributeValueLengthLimit ?? (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? (0, core_1.getNumberFromEnv)("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? exports2.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;
      return Object.assign({}, userConfig, { spanLimits });
    }
    __name(reconfigureLimits, "reconfigureLimits");
    exports2.reconfigureLimits = reconfigureLimits;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/export/BatchSpanProcessorBase.js
var require_BatchSpanProcessorBase = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/export/BatchSpanProcessorBase.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BatchSpanProcessorBase = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var BatchSpanProcessorBase = class {
      static {
        __name(this, "BatchSpanProcessorBase");
      }
      _exporter;
      _maxExportBatchSize;
      _maxQueueSize;
      _scheduledDelayMillis;
      _exportTimeoutMillis;
      _isExporting = false;
      _finishedSpans = [];
      _timer;
      _shutdownOnce;
      _droppedSpansCount = 0;
      constructor(_exporter, config) {
        this._exporter = _exporter;
        this._maxExportBatchSize = typeof config?.maxExportBatchSize === "number" ? config.maxExportBatchSize : (0, core_1.getNumberFromEnv)("OTEL_BSP_MAX_EXPORT_BATCH_SIZE") ?? 512;
        this._maxQueueSize = typeof config?.maxQueueSize === "number" ? config.maxQueueSize : (0, core_1.getNumberFromEnv)("OTEL_BSP_MAX_QUEUE_SIZE") ?? 2048;
        this._scheduledDelayMillis = typeof config?.scheduledDelayMillis === "number" ? config.scheduledDelayMillis : (0, core_1.getNumberFromEnv)("OTEL_BSP_SCHEDULE_DELAY") ?? 5e3;
        this._exportTimeoutMillis = typeof config?.exportTimeoutMillis === "number" ? config.exportTimeoutMillis : (0, core_1.getNumberFromEnv)("OTEL_BSP_EXPORT_TIMEOUT") ?? 3e4;
        this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this);
        if (this._maxExportBatchSize > this._maxQueueSize) {
          api_1.diag.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize");
          this._maxExportBatchSize = this._maxQueueSize;
        }
      }
      forceFlush() {
        if (this._shutdownOnce.isCalled) {
          return this._shutdownOnce.promise;
        }
        return this._flushAll();
      }
      // does nothing.
      onStart(_span, _parentContext) {
      }
      onEnd(span) {
        if (this._shutdownOnce.isCalled) {
          return;
        }
        if ((span.spanContext().traceFlags & api_1.TraceFlags.SAMPLED) === 0) {
          return;
        }
        this._addToBuffer(span);
      }
      shutdown() {
        return this._shutdownOnce.call();
      }
      _shutdown() {
        return Promise.resolve().then(() => {
          return this.onShutdown();
        }).then(() => {
          return this._flushAll();
        }).then(() => {
          return this._exporter.shutdown();
        });
      }
      /** Add a span in the buffer. */
      _addToBuffer(span) {
        if (this._finishedSpans.length >= this._maxQueueSize) {
          if (this._droppedSpansCount === 0) {
            api_1.diag.debug("maxQueueSize reached, dropping spans");
          }
          this._droppedSpansCount++;
          return;
        }
        if (this._droppedSpansCount > 0) {
          api_1.diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`);
          this._droppedSpansCount = 0;
        }
        this._finishedSpans.push(span);
        this._maybeStartTimer();
      }
      /**
       * Send all spans to the exporter respecting the batch size limit
       * This function is used only on forceFlush or shutdown,
       * for all other cases _flush should be used
       * */
      _flushAll() {
        return new Promise((resolve24, reject) => {
          const promises6 = [];
          const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize);
          for (let i = 0, j = count; i < j; i++) {
            promises6.push(this._flushOneBatch());
          }
          Promise.all(promises6).then(() => {
            resolve24();
          }).catch(reject);
        });
      }
      _flushOneBatch() {
        this._clearTimer();
        if (this._finishedSpans.length === 0) {
          return Promise.resolve();
        }
        return new Promise((resolve24, reject) => {
          const timer = setTimeout(() => {
            reject(new Error("Timeout"));
          }, this._exportTimeoutMillis);
          api_1.context.with((0, core_1.suppressTracing)(api_1.context.active()), () => {
            let spans;
            if (this._finishedSpans.length <= this._maxExportBatchSize) {
              spans = this._finishedSpans;
              this._finishedSpans = [];
            } else {
              spans = this._finishedSpans.splice(0, this._maxExportBatchSize);
            }
            const doExport = /* @__PURE__ */ __name(() => this._exporter.export(spans, (result) => {
              clearTimeout(timer);
              if (result.code === core_1.ExportResultCode.SUCCESS) {
                resolve24();
              } else {
                reject(result.error ?? new Error("BatchSpanProcessor: span export failed"));
              }
            }), "doExport");
            let pendingResources = null;
            for (let i = 0, len = spans.length; i < len; i++) {
              const span = spans[i];
              if (span.resource.asyncAttributesPending && span.resource.waitForAsyncAttributes) {
                pendingResources ??= [];
                pendingResources.push(span.resource.waitForAsyncAttributes());
              }
            }
            if (pendingResources === null) {
              doExport();
            } else {
              Promise.all(pendingResources).then(doExport, (err) => {
                (0, core_1.globalErrorHandler)(err);
                reject(err);
              });
            }
          });
        });
      }
      _maybeStartTimer() {
        if (this._isExporting)
          return;
        const flush = /* @__PURE__ */ __name(() => {
          this._isExporting = true;
          this._flushOneBatch().finally(() => {
            this._isExporting = false;
            if (this._finishedSpans.length > 0) {
              this._clearTimer();
              this._maybeStartTimer();
            }
          }).catch((e2) => {
            this._isExporting = false;
            (0, core_1.globalErrorHandler)(e2);
          });
        }, "flush");
        if (this._finishedSpans.length >= this._maxExportBatchSize) {
          return flush();
        }
        if (this._timer !== void 0)
          return;
        this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);
        (0, core_1.unrefTimer)(this._timer);
      }
      _clearTimer() {
        if (this._timer !== void 0) {
          clearTimeout(this._timer);
          this._timer = void 0;
        }
      }
    };
    exports2.BatchSpanProcessorBase = BatchSpanProcessorBase;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/export/BatchSpanProcessor.js
var require_BatchSpanProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/export/BatchSpanProcessor.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BatchSpanProcessor = void 0;
    var BatchSpanProcessorBase_1 = require_BatchSpanProcessorBase();
    var BatchSpanProcessor2 = class extends BatchSpanProcessorBase_1.BatchSpanProcessorBase {
      static {
        __name(this, "BatchSpanProcessor");
      }
      onShutdown() {
      }
    };
    exports2.BatchSpanProcessor = BatchSpanProcessor2;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/RandomIdGenerator.js
var require_RandomIdGenerator = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/RandomIdGenerator.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RandomIdGenerator = void 0;
    var SPAN_ID_BYTES = 8;
    var TRACE_ID_BYTES = 16;
    var RandomIdGenerator = class {
      static {
        __name(this, "RandomIdGenerator");
      }
      /**
       * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
       * characters corresponding to 128 bits.
       */
      generateTraceId = getIdGenerator(TRACE_ID_BYTES);
      /**
       * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
       * characters corresponding to 64 bits.
       */
      generateSpanId = getIdGenerator(SPAN_ID_BYTES);
    };
    exports2.RandomIdGenerator = RandomIdGenerator;
    var SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);
    function getIdGenerator(bytes) {
      return /* @__PURE__ */ __name(function generateId() {
        for (let i = 0; i < bytes / 4; i++) {
          SHARED_BUFFER.writeUInt32BE(Math.random() * 2 ** 32 >>> 0, i * 4);
        }
        for (let i = 0; i < bytes; i++) {
          if (SHARED_BUFFER[i] > 0) {
            break;
          } else if (i === bytes - 1) {
            SHARED_BUFFER[bytes - 1] = 1;
          }
        }
        return SHARED_BUFFER.toString("hex", 0, bytes);
      }, "generateId");
    }
    __name(getIdGenerator, "getIdGenerator");
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/index.js
var require_node10 = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RandomIdGenerator = exports2.BatchSpanProcessor = void 0;
    var BatchSpanProcessor_1 = require_BatchSpanProcessor();
    Object.defineProperty(exports2, "BatchSpanProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return BatchSpanProcessor_1.BatchSpanProcessor;
    }, "get") });
    var RandomIdGenerator_1 = require_RandomIdGenerator();
    Object.defineProperty(exports2, "RandomIdGenerator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return RandomIdGenerator_1.RandomIdGenerator;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/platform/index.js
var require_platform9 = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/platform/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RandomIdGenerator = exports2.BatchSpanProcessor = void 0;
    var node_1 = require_node10();
    Object.defineProperty(exports2, "BatchSpanProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.BatchSpanProcessor;
    }, "get") });
    Object.defineProperty(exports2, "RandomIdGenerator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.RandomIdGenerator;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/Tracer.js
var require_Tracer = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/Tracer.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Tracer = void 0;
    var api = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var Span_1 = require_Span();
    var utility_1 = require_utility();
    var platform_1 = require_platform9();
    var Tracer = class {
      static {
        __name(this, "Tracer");
      }
      _sampler;
      _generalLimits;
      _spanLimits;
      _idGenerator;
      instrumentationScope;
      _resource;
      _spanProcessor;
      /**
       * Constructs a new Tracer instance.
       */
      constructor(instrumentationScope, config, resource, spanProcessor) {
        const localConfig = (0, utility_1.mergeConfig)(config);
        this._sampler = localConfig.sampler;
        this._generalLimits = localConfig.generalLimits;
        this._spanLimits = localConfig.spanLimits;
        this._idGenerator = config.idGenerator || new platform_1.RandomIdGenerator();
        this._resource = resource;
        this._spanProcessor = spanProcessor;
        this.instrumentationScope = instrumentationScope;
      }
      /**
       * Starts a new Span or returns the default NoopSpan based on the sampling
       * decision.
       */
      startSpan(name3, options2 = {}, context2 = api.context.active()) {
        if (options2.root) {
          context2 = api.trace.deleteSpan(context2);
        }
        const parentSpan = api.trace.getSpan(context2);
        if ((0, core_1.isTracingSuppressed)(context2)) {
          api.diag.debug("Instrumentation suppressed, returning Noop Span");
          const nonRecordingSpan = api.trace.wrapSpanContext(api.INVALID_SPAN_CONTEXT);
          return nonRecordingSpan;
        }
        const parentSpanContext = parentSpan?.spanContext();
        const spanId = this._idGenerator.generateSpanId();
        let validParentSpanContext;
        let traceId;
        let traceState;
        if (!parentSpanContext || !api.trace.isSpanContextValid(parentSpanContext)) {
          traceId = this._idGenerator.generateTraceId();
        } else {
          traceId = parentSpanContext.traceId;
          traceState = parentSpanContext.traceState;
          validParentSpanContext = parentSpanContext;
        }
        const spanKind = options2.kind ?? api.SpanKind.INTERNAL;
        const links = (options2.links ?? []).map((link3) => {
          return {
            context: link3.context,
            attributes: (0, core_1.sanitizeAttributes)(link3.attributes)
          };
        });
        const attributes = (0, core_1.sanitizeAttributes)(options2.attributes);
        const samplingResult = this._sampler.shouldSample(context2, traceId, name3, spanKind, attributes, links);
        traceState = samplingResult.traceState ?? traceState;
        const traceFlags = samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED ? api.TraceFlags.SAMPLED : api.TraceFlags.NONE;
        const spanContext = { traceId, spanId, traceFlags, traceState };
        if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) {
          api.diag.debug("Recording is off, propagating context in a non-recording span");
          const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);
          return nonRecordingSpan;
        }
        const initAttributes = (0, core_1.sanitizeAttributes)(Object.assign(attributes, samplingResult.attributes));
        const span = new Span_1.SpanImpl({
          resource: this._resource,
          scope: this.instrumentationScope,
          context: context2,
          spanContext,
          name: name3,
          kind: spanKind,
          links,
          parentSpanContext: validParentSpanContext,
          attributes: initAttributes,
          startTime: options2.startTime,
          spanProcessor: this._spanProcessor,
          spanLimits: this._spanLimits
        });
        return span;
      }
      startActiveSpan(name3, arg2, arg3, arg4) {
        let opts;
        let ctx;
        let fn;
        if (arguments.length < 2) {
          return;
        } else if (arguments.length === 2) {
          fn = arg2;
        } else if (arguments.length === 3) {
          opts = arg2;
          fn = arg3;
        } else {
          opts = arg2;
          ctx = arg3;
          fn = arg4;
        }
        const parentContext = ctx ?? api.context.active();
        const span = this.startSpan(name3, opts, parentContext);
        const contextWithSpanSet = api.trace.setSpan(parentContext, span);
        return api.context.with(contextWithSpanSet, fn, void 0, span);
      }
      /** Returns the active {@link GeneralLimits}. */
      getGeneralLimits() {
        return this._generalLimits;
      }
      /** Returns the active {@link SpanLimits}. */
      getSpanLimits() {
        return this._spanLimits;
      }
    };
    exports2.Tracer = Tracer;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/MultiSpanProcessor.js
var require_MultiSpanProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/MultiSpanProcessor.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MultiSpanProcessor = void 0;
    var core_1 = require_src8();
    var MultiSpanProcessor = class {
      static {
        __name(this, "MultiSpanProcessor");
      }
      _spanProcessors;
      constructor(_spanProcessors) {
        this._spanProcessors = _spanProcessors;
      }
      forceFlush() {
        const promises6 = [];
        for (const spanProcessor of this._spanProcessors) {
          promises6.push(spanProcessor.forceFlush());
        }
        return new Promise((resolve24) => {
          Promise.all(promises6).then(() => {
            resolve24();
          }).catch((error) => {
            (0, core_1.globalErrorHandler)(error || new Error("MultiSpanProcessor: forceFlush failed"));
            resolve24();
          });
        });
      }
      onStart(span, context2) {
        for (const spanProcessor of this._spanProcessors) {
          spanProcessor.onStart(span, context2);
        }
      }
      onEnd(span) {
        for (const spanProcessor of this._spanProcessors) {
          spanProcessor.onEnd(span);
        }
      }
      shutdown() {
        const promises6 = [];
        for (const spanProcessor of this._spanProcessors) {
          promises6.push(spanProcessor.shutdown());
        }
        return new Promise((resolve24, reject) => {
          Promise.all(promises6).then(() => {
            resolve24();
          }, reject);
        });
      }
    };
    exports2.MultiSpanProcessor = MultiSpanProcessor;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/BasicTracerProvider.js
var require_BasicTracerProvider = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/BasicTracerProvider.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BasicTracerProvider = exports2.ForceFlushState = void 0;
    var core_1 = require_src8();
    var resources_1 = require_src13();
    var Tracer_1 = require_Tracer();
    var config_1 = require_config2();
    var MultiSpanProcessor_1 = require_MultiSpanProcessor();
    var utility_1 = require_utility();
    var ForceFlushState;
    (function(ForceFlushState2) {
      ForceFlushState2[ForceFlushState2["resolved"] = 0] = "resolved";
      ForceFlushState2[ForceFlushState2["timeout"] = 1] = "timeout";
      ForceFlushState2[ForceFlushState2["error"] = 2] = "error";
      ForceFlushState2[ForceFlushState2["unresolved"] = 3] = "unresolved";
    })(ForceFlushState = exports2.ForceFlushState || (exports2.ForceFlushState = {}));
    var BasicTracerProvider = class {
      static {
        __name(this, "BasicTracerProvider");
      }
      _config;
      _tracers = /* @__PURE__ */ new Map();
      _resource;
      _activeSpanProcessor;
      constructor(config = {}) {
        const mergedConfig = (0, core_1.merge)({}, (0, config_1.loadDefaultConfig)(), (0, utility_1.reconfigureLimits)(config));
        this._resource = mergedConfig.resource ?? (0, resources_1.defaultResource)();
        this._config = Object.assign({}, mergedConfig, {
          resource: this._resource
        });
        const spanProcessors = [];
        if (config.spanProcessors?.length) {
          spanProcessors.push(...config.spanProcessors);
        }
        this._activeSpanProcessor = new MultiSpanProcessor_1.MultiSpanProcessor(spanProcessors);
      }
      getTracer(name3, version2, options2) {
        const key = `${name3}@${version2 || ""}:${options2?.schemaUrl || ""}`;
        if (!this._tracers.has(key)) {
          this._tracers.set(key, new Tracer_1.Tracer({ name: name3, version: version2, schemaUrl: options2?.schemaUrl }, this._config, this._resource, this._activeSpanProcessor));
        }
        return this._tracers.get(key);
      }
      forceFlush() {
        const timeout2 = this._config.forceFlushTimeoutMillis;
        const promises6 = this._activeSpanProcessor["_spanProcessors"].map((spanProcessor) => {
          return new Promise((resolve24) => {
            let state;
            const timeoutInterval = setTimeout(() => {
              resolve24(new Error(`Span processor did not completed within timeout period of ${timeout2} ms`));
              state = ForceFlushState.timeout;
            }, timeout2);
            spanProcessor.forceFlush().then(() => {
              clearTimeout(timeoutInterval);
              if (state !== ForceFlushState.timeout) {
                state = ForceFlushState.resolved;
                resolve24(state);
              }
            }).catch((error) => {
              clearTimeout(timeoutInterval);
              state = ForceFlushState.error;
              resolve24(error);
            });
          });
        });
        return new Promise((resolve24, reject) => {
          Promise.all(promises6).then((results) => {
            const errors = results.filter((result) => result !== ForceFlushState.resolved);
            if (errors.length > 0) {
              reject(errors);
            } else {
              resolve24();
            }
          }).catch((error) => reject([error]));
        });
      }
      shutdown() {
        return this._activeSpanProcessor.shutdown();
      }
    };
    exports2.BasicTracerProvider = BasicTracerProvider;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/export/ConsoleSpanExporter.js
var require_ConsoleSpanExporter = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/export/ConsoleSpanExporter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ConsoleSpanExporter = void 0;
    var core_1 = require_src8();
    var ConsoleSpanExporter2 = class {
      static {
        __name(this, "ConsoleSpanExporter");
      }
      /**
       * Export spans.
       * @param spans
       * @param resultCallback
       */
      export(spans, resultCallback) {
        return this._sendSpans(spans, resultCallback);
      }
      /**
       * Shutdown the exporter.
       */
      shutdown() {
        this._sendSpans([]);
        return this.forceFlush();
      }
      /**
       * Exports any pending spans in exporter
       */
      forceFlush() {
        return Promise.resolve();
      }
      /**
       * converts span info into more readable format
       * @param span
       */
      _exportInfo(span) {
        return {
          resource: {
            attributes: span.resource.attributes
          },
          instrumentationScope: span.instrumentationScope,
          traceId: span.spanContext().traceId,
          parentSpanContext: span.parentSpanContext,
          traceState: span.spanContext().traceState?.serialize(),
          name: span.name,
          id: span.spanContext().spanId,
          kind: span.kind,
          timestamp: (0, core_1.hrTimeToMicroseconds)(span.startTime),
          duration: (0, core_1.hrTimeToMicroseconds)(span.duration),
          attributes: span.attributes,
          status: span.status,
          events: span.events,
          links: span.links
        };
      }
      /**
       * Showing spans in console
       * @param spans
       * @param done
       */
      _sendSpans(spans, done) {
        for (const span of spans) {
          console.dir(this._exportInfo(span), { depth: 3 });
        }
        if (done) {
          return done({ code: core_1.ExportResultCode.SUCCESS });
        }
      }
    };
    exports2.ConsoleSpanExporter = ConsoleSpanExporter2;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/export/InMemorySpanExporter.js
var require_InMemorySpanExporter = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/export/InMemorySpanExporter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InMemorySpanExporter = void 0;
    var core_1 = require_src8();
    var InMemorySpanExporter = class {
      static {
        __name(this, "InMemorySpanExporter");
      }
      _finishedSpans = [];
      /**
       * Indicates if the exporter has been "shutdown."
       * When false, exported spans will not be stored in-memory.
       */
      _stopped = false;
      export(spans, resultCallback) {
        if (this._stopped)
          return resultCallback({
            code: core_1.ExportResultCode.FAILED,
            error: new Error("Exporter has been stopped")
          });
        this._finishedSpans.push(...spans);
        setTimeout(() => resultCallback({ code: core_1.ExportResultCode.SUCCESS }), 0);
      }
      shutdown() {
        this._stopped = true;
        this._finishedSpans = [];
        return this.forceFlush();
      }
      /**
       * Exports any pending spans in the exporter
       */
      forceFlush() {
        return Promise.resolve();
      }
      reset() {
        this._finishedSpans = [];
      }
      getFinishedSpans() {
        return this._finishedSpans;
      }
    };
    exports2.InMemorySpanExporter = InMemorySpanExporter;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/export/SimpleSpanProcessor.js
var require_SimpleSpanProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/export/SimpleSpanProcessor.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SimpleSpanProcessor = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var SimpleSpanProcessor = class {
      static {
        __name(this, "SimpleSpanProcessor");
      }
      _exporter;
      _shutdownOnce;
      _pendingExports;
      constructor(_exporter) {
        this._exporter = _exporter;
        this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this);
        this._pendingExports = /* @__PURE__ */ new Set();
      }
      async forceFlush() {
        await Promise.all(Array.from(this._pendingExports));
        if (this._exporter.forceFlush) {
          await this._exporter.forceFlush();
        }
      }
      onStart(_span, _parentContext) {
      }
      onEnd(span) {
        if (this._shutdownOnce.isCalled) {
          return;
        }
        if ((span.spanContext().traceFlags & api_1.TraceFlags.SAMPLED) === 0) {
          return;
        }
        const pendingExport = this._doExport(span).catch((err) => (0, core_1.globalErrorHandler)(err));
        this._pendingExports.add(pendingExport);
        pendingExport.finally(() => this._pendingExports.delete(pendingExport));
      }
      async _doExport(span) {
        if (span.resource.asyncAttributesPending) {
          await span.resource.waitForAsyncAttributes?.();
        }
        const result = await core_1.internal._export(this._exporter, [span]);
        if (result.code !== core_1.ExportResultCode.SUCCESS) {
          throw result.error ?? new Error(`SimpleSpanProcessor: span export failed (status ${result})`);
        }
      }
      shutdown() {
        return this._shutdownOnce.call();
      }
      _shutdown() {
        return this._exporter.shutdown();
      }
    };
    exports2.SimpleSpanProcessor = SimpleSpanProcessor;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/export/NoopSpanProcessor.js
var require_NoopSpanProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/export/NoopSpanProcessor.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NoopSpanProcessor = void 0;
    var NoopSpanProcessor = class {
      static {
        __name(this, "NoopSpanProcessor");
      }
      onStart(_span, _context) {
      }
      onEnd(_span) {
      }
      shutdown() {
        return Promise.resolve();
      }
      forceFlush() {
        return Promise.resolve();
      }
    };
    exports2.NoopSpanProcessor = NoopSpanProcessor;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/index.js
var require_src24 = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SamplingDecision = exports2.TraceIdRatioBasedSampler = exports2.ParentBasedSampler = exports2.AlwaysOnSampler = exports2.AlwaysOffSampler = exports2.NoopSpanProcessor = exports2.SimpleSpanProcessor = exports2.InMemorySpanExporter = exports2.ConsoleSpanExporter = exports2.RandomIdGenerator = exports2.BatchSpanProcessor = exports2.BasicTracerProvider = void 0;
    var BasicTracerProvider_1 = require_BasicTracerProvider();
    Object.defineProperty(exports2, "BasicTracerProvider", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return BasicTracerProvider_1.BasicTracerProvider;
    }, "get") });
    var platform_1 = require_platform9();
    Object.defineProperty(exports2, "BatchSpanProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.BatchSpanProcessor;
    }, "get") });
    Object.defineProperty(exports2, "RandomIdGenerator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.RandomIdGenerator;
    }, "get") });
    var ConsoleSpanExporter_1 = require_ConsoleSpanExporter();
    Object.defineProperty(exports2, "ConsoleSpanExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ConsoleSpanExporter_1.ConsoleSpanExporter;
    }, "get") });
    var InMemorySpanExporter_1 = require_InMemorySpanExporter();
    Object.defineProperty(exports2, "InMemorySpanExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return InMemorySpanExporter_1.InMemorySpanExporter;
    }, "get") });
    var SimpleSpanProcessor_1 = require_SimpleSpanProcessor();
    Object.defineProperty(exports2, "SimpleSpanProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return SimpleSpanProcessor_1.SimpleSpanProcessor;
    }, "get") });
    var NoopSpanProcessor_1 = require_NoopSpanProcessor();
    Object.defineProperty(exports2, "NoopSpanProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return NoopSpanProcessor_1.NoopSpanProcessor;
    }, "get") });
    var AlwaysOffSampler_1 = require_AlwaysOffSampler();
    Object.defineProperty(exports2, "AlwaysOffSampler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return AlwaysOffSampler_1.AlwaysOffSampler;
    }, "get") });
    var AlwaysOnSampler_1 = require_AlwaysOnSampler();
    Object.defineProperty(exports2, "AlwaysOnSampler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return AlwaysOnSampler_1.AlwaysOnSampler;
    }, "get") });
    var ParentBasedSampler_1 = require_ParentBasedSampler();
    Object.defineProperty(exports2, "ParentBasedSampler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ParentBasedSampler_1.ParentBasedSampler;
    }, "get") });
    var TraceIdRatioBasedSampler_1 = require_TraceIdRatioBasedSampler();
    Object.defineProperty(exports2, "TraceIdRatioBasedSampler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler;
    }, "get") });
    var Sampler_1 = require_Sampler();
    Object.defineProperty(exports2, "SamplingDecision", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return Sampler_1.SamplingDecision;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-trace-node/build/src/NodeTracerProvider.js
var require_NodeTracerProvider = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-node/build/src/NodeTracerProvider.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NodeTracerProvider = void 0;
    var context_async_hooks_1 = require_src23();
    var sdk_trace_base_1 = require_src24();
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    function setupContextManager(contextManager) {
      if (contextManager === null) {
        return;
      }
      if (contextManager === void 0) {
        const defaultContextManager = new context_async_hooks_1.AsyncLocalStorageContextManager();
        defaultContextManager.enable();
        api_1.context.setGlobalContextManager(defaultContextManager);
        return;
      }
      contextManager.enable();
      api_1.context.setGlobalContextManager(contextManager);
    }
    __name(setupContextManager, "setupContextManager");
    function setupPropagator(propagator) {
      if (propagator === null) {
        return;
      }
      if (propagator === void 0) {
        api_1.propagation.setGlobalPropagator(new core_1.CompositePropagator({
          propagators: [
            new core_1.W3CTraceContextPropagator(),
            new core_1.W3CBaggagePropagator()
          ]
        }));
        return;
      }
      api_1.propagation.setGlobalPropagator(propagator);
    }
    __name(setupPropagator, "setupPropagator");
    var NodeTracerProvider = class extends sdk_trace_base_1.BasicTracerProvider {
      static {
        __name(this, "NodeTracerProvider");
      }
      constructor(config = {}) {
        super(config);
      }
      /**
       * Register this TracerProvider for use with the OpenTelemetry API.
       * Undefined values may be replaced with defaults, and
       * null values will be skipped.
       *
       * @param config Configuration object for SDK registration
       */
      register(config = {}) {
        api_1.trace.setGlobalTracerProvider(this);
        setupContextManager(config.contextManager);
        setupPropagator(config.propagator);
      }
    };
    exports2.NodeTracerProvider = NodeTracerProvider;
  }
});

// node_modules/@opentelemetry/sdk-trace-node/build/src/index.js
var require_src25 = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-node/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.TraceIdRatioBasedSampler = exports2.SimpleSpanProcessor = exports2.SamplingDecision = exports2.RandomIdGenerator = exports2.ParentBasedSampler = exports2.NoopSpanProcessor = exports2.InMemorySpanExporter = exports2.ConsoleSpanExporter = exports2.BatchSpanProcessor = exports2.BasicTracerProvider = exports2.AlwaysOnSampler = exports2.AlwaysOffSampler = exports2.NodeTracerProvider = void 0;
    var NodeTracerProvider_1 = require_NodeTracerProvider();
    Object.defineProperty(exports2, "NodeTracerProvider", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return NodeTracerProvider_1.NodeTracerProvider;
    }, "get") });
    var sdk_trace_base_1 = require_src24();
    Object.defineProperty(exports2, "AlwaysOffSampler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.AlwaysOffSampler;
    }, "get") });
    Object.defineProperty(exports2, "AlwaysOnSampler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.AlwaysOnSampler;
    }, "get") });
    Object.defineProperty(exports2, "BasicTracerProvider", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.BasicTracerProvider;
    }, "get") });
    Object.defineProperty(exports2, "BatchSpanProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.BatchSpanProcessor;
    }, "get") });
    Object.defineProperty(exports2, "ConsoleSpanExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.ConsoleSpanExporter;
    }, "get") });
    Object.defineProperty(exports2, "InMemorySpanExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.InMemorySpanExporter;
    }, "get") });
    Object.defineProperty(exports2, "NoopSpanProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.NoopSpanProcessor;
    }, "get") });
    Object.defineProperty(exports2, "ParentBasedSampler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.ParentBasedSampler;
    }, "get") });
    Object.defineProperty(exports2, "RandomIdGenerator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.RandomIdGenerator;
    }, "get") });
    Object.defineProperty(exports2, "SamplingDecision", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.SamplingDecision;
    }, "get") });
    Object.defineProperty(exports2, "SimpleSpanProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.SimpleSpanProcessor;
    }, "get") });
    Object.defineProperty(exports2, "TraceIdRatioBasedSampler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.TraceIdRatioBasedSampler;
    }, "get") });
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/autoLoaderUtils.js
var require_autoLoaderUtils = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/autoLoaderUtils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.disableInstrumentations = exports2.enableInstrumentations = void 0;
    function enableInstrumentations(instrumentations, tracerProvider, meterProvider, loggerProvider) {
      for (let i = 0, j = instrumentations.length; i < j; i++) {
        const instrumentation = instrumentations[i];
        if (tracerProvider) {
          instrumentation.setTracerProvider(tracerProvider);
        }
        if (meterProvider) {
          instrumentation.setMeterProvider(meterProvider);
        }
        if (loggerProvider && instrumentation.setLoggerProvider) {
          instrumentation.setLoggerProvider(loggerProvider);
        }
        if (!instrumentation.getConfig().enabled) {
          instrumentation.enable();
        }
      }
    }
    __name(enableInstrumentations, "enableInstrumentations");
    exports2.enableInstrumentations = enableInstrumentations;
    function disableInstrumentations(instrumentations) {
      instrumentations.forEach((instrumentation) => instrumentation.disable());
    }
    __name(disableInstrumentations, "disableInstrumentations");
    exports2.disableInstrumentations = disableInstrumentations;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/autoLoader.js
var require_autoLoader = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/autoLoader.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.registerInstrumentations = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var api_logs_1 = require_src7();
    var autoLoaderUtils_1 = require_autoLoaderUtils();
    function registerInstrumentations(options2) {
      const tracerProvider = options2.tracerProvider || api_1.trace.getTracerProvider();
      const meterProvider = options2.meterProvider || api_1.metrics.getMeterProvider();
      const loggerProvider = options2.loggerProvider || api_logs_1.logs.getLoggerProvider();
      const instrumentations = options2.instrumentations?.flat() ?? [];
      (0, autoLoaderUtils_1.enableInstrumentations)(instrumentations, tracerProvider, meterProvider, loggerProvider);
      return () => {
        (0, autoLoaderUtils_1.disableInstrumentations)(instrumentations);
      };
    }
    __name(registerInstrumentations, "registerInstrumentations");
    exports2.registerInstrumentations = registerInstrumentations;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/semver.js
var require_semver = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/semver.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.satisfies = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var VERSION_REGEXP = /^(?:v)?(?<version>(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*))(?:-(?<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?<build>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
    var RANGE_REGEXP = /^(?<op><|>|=|==|<=|>=|~|\^|~>)?\s*(?:v)?(?<version>(?<major>x|X|\*|0|[1-9]\d*)(?:\.(?<minor>x|X|\*|0|[1-9]\d*))?(?:\.(?<patch>x|X|\*|0|[1-9]\d*))?)(?:-(?<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?<build>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
    var operatorResMap = {
      ">": [1],
      ">=": [0, 1],
      "=": [0],
      "<=": [-1, 0],
      "<": [-1],
      "!=": [-1, 1]
    };
    function satisfies(version2, range, options2) {
      if (!_validateVersion(version2)) {
        api_1.diag.error(`Invalid version: ${version2}`);
        return false;
      }
      if (!range) {
        return true;
      }
      range = range.replace(/([<>=~^]+)\s+/g, "$1");
      const parsedVersion = _parseVersion(version2);
      if (!parsedVersion) {
        return false;
      }
      const allParsedRanges = [];
      const checkResult = _doSatisfies(parsedVersion, range, allParsedRanges, options2);
      if (checkResult && !options2?.includePrerelease) {
        return _doPreleaseCheck(parsedVersion, allParsedRanges);
      }
      return checkResult;
    }
    __name(satisfies, "satisfies");
    exports2.satisfies = satisfies;
    function _validateVersion(version2) {
      return typeof version2 === "string" && VERSION_REGEXP.test(version2);
    }
    __name(_validateVersion, "_validateVersion");
    function _doSatisfies(parsedVersion, range, allParsedRanges, options2) {
      if (range.includes("||")) {
        const ranges2 = range.trim().split("||");
        for (const r3 of ranges2) {
          if (_checkRange(parsedVersion, r3, allParsedRanges, options2)) {
            return true;
          }
        }
        return false;
      } else if (range.includes(" - ")) {
        range = replaceHyphen(range, options2);
      } else if (range.includes(" ")) {
        const ranges2 = range.trim().replace(/\s{2,}/g, " ").split(" ");
        for (const r3 of ranges2) {
          if (!_checkRange(parsedVersion, r3, allParsedRanges, options2)) {
            return false;
          }
        }
        return true;
      }
      return _checkRange(parsedVersion, range, allParsedRanges, options2);
    }
    __name(_doSatisfies, "_doSatisfies");
    function _checkRange(parsedVersion, range, allParsedRanges, options2) {
      range = _normalizeRange(range, options2);
      if (range.includes(" ")) {
        return _doSatisfies(parsedVersion, range, allParsedRanges, options2);
      } else {
        const parsedRange = _parseRange(range);
        allParsedRanges.push(parsedRange);
        return _satisfies(parsedVersion, parsedRange);
      }
    }
    __name(_checkRange, "_checkRange");
    function _satisfies(parsedVersion, parsedRange) {
      if (parsedRange.invalid) {
        return false;
      }
      if (!parsedRange.version || _isWildcard(parsedRange.version)) {
        return true;
      }
      let comparisonResult = _compareVersionSegments(parsedVersion.versionSegments || [], parsedRange.versionSegments || []);
      if (comparisonResult === 0) {
        const versionPrereleaseSegments = parsedVersion.prereleaseSegments || [];
        const rangePrereleaseSegments = parsedRange.prereleaseSegments || [];
        if (!versionPrereleaseSegments.length && !rangePrereleaseSegments.length) {
          comparisonResult = 0;
        } else if (!versionPrereleaseSegments.length && rangePrereleaseSegments.length) {
          comparisonResult = 1;
        } else if (versionPrereleaseSegments.length && !rangePrereleaseSegments.length) {
          comparisonResult = -1;
        } else {
          comparisonResult = _compareVersionSegments(versionPrereleaseSegments, rangePrereleaseSegments);
        }
      }
      return operatorResMap[parsedRange.op]?.includes(comparisonResult);
    }
    __name(_satisfies, "_satisfies");
    function _doPreleaseCheck(parsedVersion, allParsedRanges) {
      if (parsedVersion.prerelease) {
        return allParsedRanges.some((r3) => r3.prerelease && r3.version === parsedVersion.version);
      }
      return true;
    }
    __name(_doPreleaseCheck, "_doPreleaseCheck");
    function _normalizeRange(range, options2) {
      range = range.trim();
      range = replaceCaret(range, options2);
      range = replaceTilde(range);
      range = replaceXRange(range, options2);
      range = range.trim();
      return range;
    }
    __name(_normalizeRange, "_normalizeRange");
    function isX(id) {
      return !id || id.toLowerCase() === "x" || id === "*";
    }
    __name(isX, "isX");
    function _parseVersion(versionString) {
      const match2 = versionString.match(VERSION_REGEXP);
      if (!match2) {
        api_1.diag.error(`Invalid version: ${versionString}`);
        return void 0;
      }
      const version2 = match2.groups.version;
      const prerelease = match2.groups.prerelease;
      const build = match2.groups.build;
      const versionSegments = version2.split(".");
      const prereleaseSegments = prerelease?.split(".");
      return {
        op: void 0,
        version: version2,
        versionSegments,
        versionSegmentCount: versionSegments.length,
        prerelease,
        prereleaseSegments,
        prereleaseSegmentCount: prereleaseSegments ? prereleaseSegments.length : 0,
        build
      };
    }
    __name(_parseVersion, "_parseVersion");
    function _parseRange(rangeString) {
      if (!rangeString) {
        return {};
      }
      const match2 = rangeString.match(RANGE_REGEXP);
      if (!match2) {
        api_1.diag.error(`Invalid range: ${rangeString}`);
        return {
          invalid: true
        };
      }
      let op = match2.groups.op;
      const version2 = match2.groups.version;
      const prerelease = match2.groups.prerelease;
      const build = match2.groups.build;
      const versionSegments = version2.split(".");
      const prereleaseSegments = prerelease?.split(".");
      if (op === "==") {
        op = "=";
      }
      return {
        op: op || "=",
        version: version2,
        versionSegments,
        versionSegmentCount: versionSegments.length,
        prerelease,
        prereleaseSegments,
        prereleaseSegmentCount: prereleaseSegments ? prereleaseSegments.length : 0,
        build
      };
    }
    __name(_parseRange, "_parseRange");
    function _isWildcard(s2) {
      return s2 === "*" || s2 === "x" || s2 === "X";
    }
    __name(_isWildcard, "_isWildcard");
    function _parseVersionString(v) {
      const n2 = parseInt(v, 10);
      return isNaN(n2) ? v : n2;
    }
    __name(_parseVersionString, "_parseVersionString");
    function _normalizeVersionType(a, b) {
      if (typeof a === typeof b) {
        if (typeof a === "number") {
          return [a, b];
        } else if (typeof a === "string") {
          return [a, b];
        } else {
          throw new Error("Version segments can only be strings or numbers");
        }
      } else {
        return [String(a), String(b)];
      }
    }
    __name(_normalizeVersionType, "_normalizeVersionType");
    function _compareVersionStrings(v12, v2) {
      if (_isWildcard(v12) || _isWildcard(v2)) {
        return 0;
      }
      const [parsedV1, parsedV2] = _normalizeVersionType(_parseVersionString(v12), _parseVersionString(v2));
      if (parsedV1 > parsedV2) {
        return 1;
      } else if (parsedV1 < parsedV2) {
        return -1;
      }
      return 0;
    }
    __name(_compareVersionStrings, "_compareVersionStrings");
    function _compareVersionSegments(v12, v2) {
      for (let i = 0; i < Math.max(v12.length, v2.length); i++) {
        const res = _compareVersionStrings(v12[i] || "0", v2[i] || "0");
        if (res !== 0) {
          return res;
        }
      }
      return 0;
    }
    __name(_compareVersionSegments, "_compareVersionSegments");
    var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
    var NUMERICIDENTIFIER = "0|[1-9]\\d*";
    var NONNUMERICIDENTIFIER = `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`;
    var GTLT = "((?:<|>)?=?)";
    var PRERELEASEIDENTIFIER = `(?:${NUMERICIDENTIFIER}|${NONNUMERICIDENTIFIER})`;
    var PRERELEASE = `(?:-(${PRERELEASEIDENTIFIER}(?:\\.${PRERELEASEIDENTIFIER})*))`;
    var BUILDIDENTIFIER = `${LETTERDASHNUMBER}+`;
    var BUILD = `(?:\\+(${BUILDIDENTIFIER}(?:\\.${BUILDIDENTIFIER})*))`;
    var XRANGEIDENTIFIER = `${NUMERICIDENTIFIER}|x|X|\\*`;
    var XRANGEPLAIN = `[v=\\s]*(${XRANGEIDENTIFIER})(?:\\.(${XRANGEIDENTIFIER})(?:\\.(${XRANGEIDENTIFIER})(?:${PRERELEASE})?${BUILD}?)?)?`;
    var XRANGE = `^${GTLT}\\s*${XRANGEPLAIN}$`;
    var XRANGE_REGEXP = new RegExp(XRANGE);
    var HYPHENRANGE = `^\\s*(${XRANGEPLAIN})\\s+-\\s+(${XRANGEPLAIN})\\s*$`;
    var HYPHENRANGE_REGEXP = new RegExp(HYPHENRANGE);
    var LONETILDE = "(?:~>?)";
    var TILDE = `^${LONETILDE}${XRANGEPLAIN}$`;
    var TILDE_REGEXP = new RegExp(TILDE);
    var LONECARET = "(?:\\^)";
    var CARET = `^${LONECARET}${XRANGEPLAIN}$`;
    var CARET_REGEXP = new RegExp(CARET);
    function replaceTilde(comp) {
      const r3 = TILDE_REGEXP;
      return comp.replace(r3, (_, M, m, p, pr) => {
        let ret;
        if (isX(M)) {
          ret = "";
        } else if (isX(m)) {
          ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
        } else if (isX(p)) {
          ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
        } else if (pr) {
          ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
        } else {
          ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
        }
        return ret;
      });
    }
    __name(replaceTilde, "replaceTilde");
    function replaceCaret(comp, options2) {
      const r3 = CARET_REGEXP;
      const z = options2?.includePrerelease ? "-0" : "";
      return comp.replace(r3, (_, M, m, p, pr) => {
        let ret;
        if (isX(M)) {
          ret = "";
        } else if (isX(m)) {
          ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
        } else if (isX(p)) {
          if (M === "0") {
            ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
          } else {
            ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
          }
        } else if (pr) {
          if (M === "0") {
            if (m === "0") {
              ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;
            } else {
              ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
            }
          } else {
            ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;
          }
        } else {
          if (M === "0") {
            if (m === "0") {
              ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`;
            } else {
              ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`;
            }
          } else {
            ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;
          }
        }
        return ret;
      });
    }
    __name(replaceCaret, "replaceCaret");
    function replaceXRange(comp, options2) {
      const r3 = XRANGE_REGEXP;
      return comp.replace(r3, (ret, gtlt, M, m, p, pr) => {
        const xM = isX(M);
        const xm = xM || isX(m);
        const xp = xm || isX(p);
        const anyX = xp;
        if (gtlt === "=" && anyX) {
          gtlt = "";
        }
        pr = options2?.includePrerelease ? "-0" : "";
        if (xM) {
          if (gtlt === ">" || gtlt === "<") {
            ret = "<0.0.0-0";
          } else {
            ret = "*";
          }
        } else if (gtlt && anyX) {
          if (xm) {
            m = 0;
          }
          p = 0;
          if (gtlt === ">") {
            gtlt = ">=";
            if (xm) {
              M = +M + 1;
              m = 0;
              p = 0;
            } else {
              m = +m + 1;
              p = 0;
            }
          } else if (gtlt === "<=") {
            gtlt = "<";
            if (xm) {
              M = +M + 1;
            } else {
              m = +m + 1;
            }
          }
          if (gtlt === "<") {
            pr = "-0";
          }
          ret = `${gtlt + M}.${m}.${p}${pr}`;
        } else if (xm) {
          ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
        } else if (xp) {
          ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
        }
        return ret;
      });
    }
    __name(replaceXRange, "replaceXRange");
    function replaceHyphen(comp, options2) {
      const r3 = HYPHENRANGE_REGEXP;
      return comp.replace(r3, (_, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
        if (isX(fM)) {
          from = "";
        } else if (isX(fm)) {
          from = `>=${fM}.0.0${options2?.includePrerelease ? "-0" : ""}`;
        } else if (isX(fp)) {
          from = `>=${fM}.${fm}.0${options2?.includePrerelease ? "-0" : ""}`;
        } else if (fpr) {
          from = `>=${from}`;
        } else {
          from = `>=${from}${options2?.includePrerelease ? "-0" : ""}`;
        }
        if (isX(tM)) {
          to = "";
        } else if (isX(tm)) {
          to = `<${+tM + 1}.0.0-0`;
        } else if (isX(tp)) {
          to = `<${tM}.${+tm + 1}.0-0`;
        } else if (tpr) {
          to = `<=${tM}.${tm}.${tp}-${tpr}`;
        } else if (options2?.includePrerelease) {
          to = `<${tM}.${tm}.${+tp + 1}-0`;
        } else {
          to = `<=${to}`;
        }
        return `${from} ${to}`.trim();
      });
    }
    __name(replaceHyphen, "replaceHyphen");
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/shimmer.js
var require_shimmer = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/shimmer.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.massUnwrap = exports2.unwrap = exports2.massWrap = exports2.wrap = void 0;
    var logger6 = console.error.bind(console);
    function defineProperty2(obj, name3, value) {
      const enumerable = !!obj[name3] && Object.prototype.propertyIsEnumerable.call(obj, name3);
      Object.defineProperty(obj, name3, {
        configurable: true,
        enumerable,
        writable: true,
        value
      });
    }
    __name(defineProperty2, "defineProperty");
    var wrap2 = /* @__PURE__ */ __name((nodule, name3, wrapper) => {
      if (!nodule || !nodule[name3]) {
        logger6("no original function " + String(name3) + " to wrap");
        return;
      }
      if (!wrapper) {
        logger6("no wrapper function");
        logger6(new Error().stack);
        return;
      }
      const original = nodule[name3];
      if (typeof original !== "function" || typeof wrapper !== "function") {
        logger6("original object and wrapper must be functions");
        return;
      }
      const wrapped = wrapper(original, name3);
      defineProperty2(wrapped, "__original", original);
      defineProperty2(wrapped, "__unwrap", () => {
        if (nodule[name3] === wrapped) {
          defineProperty2(nodule, name3, original);
        }
      });
      defineProperty2(wrapped, "__wrapped", true);
      defineProperty2(nodule, name3, wrapped);
      return wrapped;
    }, "wrap");
    exports2.wrap = wrap2;
    var massWrap = /* @__PURE__ */ __name((nodules, names, wrapper) => {
      if (!nodules) {
        logger6("must provide one or more modules to patch");
        logger6(new Error().stack);
        return;
      } else if (!Array.isArray(nodules)) {
        nodules = [nodules];
      }
      if (!(names && Array.isArray(names))) {
        logger6("must provide one or more functions to wrap on modules");
        return;
      }
      nodules.forEach((nodule) => {
        names.forEach((name3) => {
          (0, exports2.wrap)(nodule, name3, wrapper);
        });
      });
    }, "massWrap");
    exports2.massWrap = massWrap;
    var unwrap = /* @__PURE__ */ __name((nodule, name3) => {
      if (!nodule || !nodule[name3]) {
        logger6("no function to unwrap.");
        logger6(new Error().stack);
        return;
      }
      const wrapped = nodule[name3];
      if (!wrapped.__unwrap) {
        logger6("no original to unwrap to -- has " + String(name3) + " already been unwrapped?");
      } else {
        wrapped.__unwrap();
        return;
      }
    }, "unwrap");
    exports2.unwrap = unwrap;
    var massUnwrap = /* @__PURE__ */ __name((nodules, names) => {
      if (!nodules) {
        logger6("must provide one or more modules to patch");
        logger6(new Error().stack);
        return;
      } else if (!Array.isArray(nodules)) {
        nodules = [nodules];
      }
      if (!(names && Array.isArray(names))) {
        logger6("must provide one or more functions to unwrap on modules");
        return;
      }
      nodules.forEach((nodule) => {
        names.forEach((name3) => {
          (0, exports2.unwrap)(nodule, name3);
        });
      });
    }, "massUnwrap");
    exports2.massUnwrap = massUnwrap;
    function shimmer(options2) {
      if (options2 && options2.logger) {
        if (typeof options2.logger !== "function") {
          logger6("new logger isn't a function, not replacing");
        } else {
          logger6 = options2.logger;
        }
      }
    }
    __name(shimmer, "shimmer");
    exports2.default = shimmer;
    shimmer.wrap = exports2.wrap;
    shimmer.massWrap = exports2.massWrap;
    shimmer.unwrap = exports2.unwrap;
    shimmer.massUnwrap = exports2.massUnwrap;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/instrumentation.js
var require_instrumentation = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/instrumentation.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InstrumentationAbstract = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var api_logs_1 = require_src7();
    var shimmer = require_shimmer();
    var InstrumentationAbstract = class {
      static {
        __name(this, "InstrumentationAbstract");
      }
      instrumentationName;
      instrumentationVersion;
      _config = {};
      _tracer;
      _meter;
      _logger;
      _diag;
      constructor(instrumentationName, instrumentationVersion, config) {
        this.instrumentationName = instrumentationName;
        this.instrumentationVersion = instrumentationVersion;
        this.setConfig(config);
        this._diag = api_1.diag.createComponentLogger({
          namespace: instrumentationName
        });
        this._tracer = api_1.trace.getTracer(instrumentationName, instrumentationVersion);
        this._meter = api_1.metrics.getMeter(instrumentationName, instrumentationVersion);
        this._logger = api_logs_1.logs.getLogger(instrumentationName, instrumentationVersion);
        this._updateMetricInstruments();
      }
      /* Api to wrap instrumented method */
      _wrap = shimmer.wrap;
      /* Api to unwrap instrumented methods */
      _unwrap = shimmer.unwrap;
      /* Api to mass wrap instrumented method */
      _massWrap = shimmer.massWrap;
      /* Api to mass unwrap instrumented methods */
      _massUnwrap = shimmer.massUnwrap;
      /* Returns meter */
      get meter() {
        return this._meter;
      }
      /**
       * Sets MeterProvider to this plugin
       * @param meterProvider
       */
      setMeterProvider(meterProvider) {
        this._meter = meterProvider.getMeter(this.instrumentationName, this.instrumentationVersion);
        this._updateMetricInstruments();
      }
      /* Returns logger */
      get logger() {
        return this._logger;
      }
      /**
       * Sets LoggerProvider to this plugin
       * @param loggerProvider
       */
      setLoggerProvider(loggerProvider) {
        this._logger = loggerProvider.getLogger(this.instrumentationName, this.instrumentationVersion);
      }
      /**
       * @experimental
       *
       * Get module definitions defined by {@link init}.
       * This can be used for experimental compile-time instrumentation.
       *
       * @returns an array of {@link InstrumentationModuleDefinition}
       */
      getModuleDefinitions() {
        const initResult = this.init() ?? [];
        if (!Array.isArray(initResult)) {
          return [initResult];
        }
        return initResult;
      }
      /**
       * Sets the new metric instruments with the current Meter.
       */
      _updateMetricInstruments() {
        return;
      }
      /* Returns InstrumentationConfig */
      getConfig() {
        return this._config;
      }
      /**
       * Sets InstrumentationConfig to this plugin
       * @param config
       */
      setConfig(config) {
        this._config = {
          enabled: true,
          ...config
        };
      }
      /**
       * Sets TraceProvider to this plugin
       * @param tracerProvider
       */
      setTracerProvider(tracerProvider) {
        this._tracer = tracerProvider.getTracer(this.instrumentationName, this.instrumentationVersion);
      }
      /* Returns tracer */
      get tracer() {
        return this._tracer;
      }
      /**
       * Execute span customization hook, if configured, and log any errors.
       * Any semantics of the trigger and info are defined by the specific instrumentation.
       * @param hookHandler The optional hook handler which the user has configured via instrumentation config
       * @param triggerName The name of the trigger for executing the hook for logging purposes
       * @param span The span to which the hook should be applied
       * @param info The info object to be passed to the hook, with useful data the hook may use
       */
      _runSpanCustomizationHook(hookHandler, triggerName, span, info) {
        if (!hookHandler) {
          return;
        }
        try {
          hookHandler(span, info);
        } catch (e2) {
          this._diag.error(`Error running span customization hook due to exception in handler`, { triggerName }, e2);
        }
      }
    };
    exports2.InstrumentationAbstract = InstrumentationAbstract;
  }
});

// node_modules/module-details-from-path/index.js
var require_module_details_from_path = __commonJS({
  "node_modules/module-details-from-path/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var sep7 = __require("path").sep;
    module2.exports = function(file) {
      var segments = file.split(sep7);
      var index = segments.lastIndexOf("node_modules");
      if (index === -1) return;
      if (!segments[index + 1]) return;
      var scoped = segments[index + 1][0] === "@";
      var name3 = scoped ? segments[index + 1] + "/" + segments[index + 2] : segments[index + 1];
      var offset = scoped ? 3 : 2;
      var basedir = "";
      var lastBaseDirSegmentIndex = index + offset - 1;
      for (var i = 0; i <= lastBaseDirSegmentIndex; i++) {
        if (i === lastBaseDirSegmentIndex) {
          basedir += segments[i];
        } else {
          basedir += segments[i] + sep7;
        }
      }
      var path108 = "";
      var lastSegmentIndex = segments.length - 1;
      for (var i2 = index + offset; i2 <= lastSegmentIndex; i2++) {
        if (i2 === lastSegmentIndex) {
          path108 += segments[i2];
        } else {
          path108 += segments[i2] + sep7;
        }
      }
      return {
        name: name3,
        basedir,
        path: path108
      };
    };
  }
});

// node_modules/resolve/lib/homedir.js
var require_homedir = __commonJS({
  "node_modules/resolve/lib/homedir.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var os43 = __require("os");
    module2.exports = os43.homedir || /* @__PURE__ */ __name(function homedir20() {
      var home = process.env.HOME;
      var user = process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME;
      if (process.platform === "win32") {
        return process.env.USERPROFILE || process.env.HOMEDRIVE + process.env.HOMEPATH || home || null;
      }
      if (process.platform === "darwin") {
        return home || (user ? "/Users/" + user : null);
      }
      if (process.platform === "linux") {
        return home || (process.getuid() === 0 ? "/root" : user ? "/home/" + user : null);
      }
      return home || null;
    }, "homedir");
  }
});

// node_modules/resolve/lib/caller.js
var require_caller = __commonJS({
  "node_modules/resolve/lib/caller.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = function() {
      var origPrepareStackTrace = Error.prepareStackTrace;
      Error.prepareStackTrace = function(_, stack2) {
        return stack2;
      };
      var stack = new Error().stack;
      Error.prepareStackTrace = origPrepareStackTrace;
      return stack[2].getFileName();
    };
  }
});

// node_modules/path-parse/index.js
var require_path_parse = __commonJS({
  "node_modules/path-parse/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var isWindows8 = process.platform === "win32";
    var splitWindowsRe = /^(((?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?[\\\/]?)(?:[^\\\/]*[\\\/])*)((\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))[\\\/]*$/;
    var win323 = {};
    function win32SplitPath(filename) {
      return splitWindowsRe.exec(filename).slice(1);
    }
    __name(win32SplitPath, "win32SplitPath");
    win323.parse = function(pathString) {
      if (typeof pathString !== "string") {
        throw new TypeError(
          "Parameter 'pathString' must be a string, not " + typeof pathString
        );
      }
      var allParts = win32SplitPath(pathString);
      if (!allParts || allParts.length !== 5) {
        throw new TypeError("Invalid path '" + pathString + "'");
      }
      return {
        root: allParts[1],
        dir: allParts[0] === allParts[1] ? allParts[0] : allParts[0].slice(0, -1),
        base: allParts[2],
        ext: allParts[4],
        name: allParts[3]
      };
    };
    var splitPathRe = /^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/;
    var posix3 = {};
    function posixSplitPath(filename) {
      return splitPathRe.exec(filename).slice(1);
    }
    __name(posixSplitPath, "posixSplitPath");
    posix3.parse = function(pathString) {
      if (typeof pathString !== "string") {
        throw new TypeError(
          "Parameter 'pathString' must be a string, not " + typeof pathString
        );
      }
      var allParts = posixSplitPath(pathString);
      if (!allParts || allParts.length !== 5) {
        throw new TypeError("Invalid path '" + pathString + "'");
      }
      return {
        root: allParts[1],
        dir: allParts[0].slice(0, -1),
        base: allParts[2],
        ext: allParts[4],
        name: allParts[3]
      };
    };
    if (isWindows8)
      module2.exports = win323.parse;
    else
      module2.exports = posix3.parse;
    module2.exports.posix = posix3.parse;
    module2.exports.win32 = win323.parse;
  }
});

// node_modules/resolve/lib/node-modules-paths.js
var require_node_modules_paths = __commonJS({
  "node_modules/resolve/lib/node-modules-paths.js"(exports2, module2) {
    init_esbuild_shims();
    var path108 = __require("path");
    var parse12 = path108.parse || require_path_parse();
    var getNodeModulesDirs = /* @__PURE__ */ __name(function getNodeModulesDirs2(absoluteStart, modules) {
      var prefix = "/";
      if (/^([A-Za-z]:)/.test(absoluteStart)) {
        prefix = "";
      } else if (/^\\\\/.test(absoluteStart)) {
        prefix = "\\\\";
      }
      var paths = [absoluteStart];
      var parsed = parse12(absoluteStart);
      while (parsed.dir !== paths[paths.length - 1]) {
        paths.push(parsed.dir);
        parsed = parse12(parsed.dir);
      }
      return paths.reduce(function(dirs, aPath) {
        return dirs.concat(modules.map(function(moduleDir) {
          return path108.resolve(prefix, aPath, moduleDir);
        }));
      }, []);
    }, "getNodeModulesDirs");
    module2.exports = /* @__PURE__ */ __name(function nodeModulesPaths(start, opts, request4) {
      var modules = opts && opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ["node_modules"];
      if (opts && typeof opts.paths === "function") {
        return opts.paths(
          request4,
          start,
          function() {
            return getNodeModulesDirs(start, modules);
          },
          opts
        );
      }
      var dirs = getNodeModulesDirs(start, modules);
      return opts && opts.paths ? dirs.concat(opts.paths) : dirs;
    }, "nodeModulesPaths");
  }
});

// node_modules/resolve/lib/normalize-options.js
var require_normalize_options = __commonJS({
  "node_modules/resolve/lib/normalize-options.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = function(x, opts) {
      return opts || {};
    };
  }
});

// node_modules/function-bind/implementation.js
var require_implementation = __commonJS({
  "node_modules/function-bind/implementation.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var ERROR_MESSAGE = "Function.prototype.bind called on incompatible ";
    var toStr = Object.prototype.toString;
    var max = Math.max;
    var funcType = "[object Function]";
    var concatty = /* @__PURE__ */ __name(function concatty2(a, b) {
      var arr = [];
      for (var i = 0; i < a.length; i += 1) {
        arr[i] = a[i];
      }
      for (var j = 0; j < b.length; j += 1) {
        arr[j + a.length] = b[j];
      }
      return arr;
    }, "concatty");
    var slicy = /* @__PURE__ */ __name(function slicy2(arrLike, offset) {
      var arr = [];
      for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
        arr[j] = arrLike[i];
      }
      return arr;
    }, "slicy");
    var joiny = /* @__PURE__ */ __name(function(arr, joiner) {
      var str2 = "";
      for (var i = 0; i < arr.length; i += 1) {
        str2 += arr[i];
        if (i + 1 < arr.length) {
          str2 += joiner;
        }
      }
      return str2;
    }, "joiny");
    module2.exports = /* @__PURE__ */ __name(function bind(that) {
      var target = this;
      if (typeof target !== "function" || toStr.apply(target) !== funcType) {
        throw new TypeError(ERROR_MESSAGE + target);
      }
      var args = slicy(arguments, 1);
      var bound;
      var binder = /* @__PURE__ */ __name(function() {
        if (this instanceof bound) {
          var result = target.apply(
            this,
            concatty(args, arguments)
          );
          if (Object(result) === result) {
            return result;
          }
          return this;
        }
        return target.apply(
          that,
          concatty(args, arguments)
        );
      }, "binder");
      var boundLength = max(0, target.length - args.length);
      var boundArgs = [];
      for (var i = 0; i < boundLength; i++) {
        boundArgs[i] = "$" + i;
      }
      bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder);
      if (target.prototype) {
        var Empty = /* @__PURE__ */ __name(function Empty2() {
        }, "Empty");
        Empty.prototype = target.prototype;
        bound.prototype = new Empty();
        Empty.prototype = null;
      }
      return bound;
    }, "bind");
  }
});

// node_modules/function-bind/index.js
var require_function_bind = __commonJS({
  "node_modules/function-bind/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var implementation = require_implementation();
    module2.exports = Function.prototype.bind || implementation;
  }
});

// node_modules/hasown/index.js
var require_hasown = __commonJS({
  "node_modules/hasown/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var call = Function.prototype.call;
    var $hasOwn = Object.prototype.hasOwnProperty;
    var bind = require_function_bind();
    module2.exports = bind.call(call, $hasOwn);
  }
});

// node_modules/is-core-module/core.json
var require_core5 = __commonJS({
  "node_modules/is-core-module/core.json"(exports2, module2) {
    module2.exports = {
      assert: true,
      "node:assert": [">= 14.18 && < 15", ">= 16"],
      "assert/strict": ">= 15",
      "node:assert/strict": ">= 16",
      async_hooks: ">= 8",
      "node:async_hooks": [">= 14.18 && < 15", ">= 16"],
      buffer_ieee754: ">= 0.5 && < 0.9.7",
      buffer: true,
      "node:buffer": [">= 14.18 && < 15", ">= 16"],
      child_process: true,
      "node:child_process": [">= 14.18 && < 15", ">= 16"],
      cluster: ">= 0.5",
      "node:cluster": [">= 14.18 && < 15", ">= 16"],
      console: true,
      "node:console": [">= 14.18 && < 15", ">= 16"],
      constants: true,
      "node:constants": [">= 14.18 && < 15", ">= 16"],
      crypto: true,
      "node:crypto": [">= 14.18 && < 15", ">= 16"],
      _debug_agent: ">= 1 && < 8",
      _debugger: "< 8",
      dgram: true,
      "node:dgram": [">= 14.18 && < 15", ">= 16"],
      diagnostics_channel: [">= 14.17 && < 15", ">= 15.1"],
      "node:diagnostics_channel": [">= 14.18 && < 15", ">= 16"],
      dns: true,
      "node:dns": [">= 14.18 && < 15", ">= 16"],
      "dns/promises": ">= 15",
      "node:dns/promises": ">= 16",
      domain: ">= 0.7.12",
      "node:domain": [">= 14.18 && < 15", ">= 16"],
      events: true,
      "node:events": [">= 14.18 && < 15", ">= 16"],
      freelist: "< 6",
      fs: true,
      "node:fs": [">= 14.18 && < 15", ">= 16"],
      "fs/promises": [">= 10 && < 10.1", ">= 14"],
      "node:fs/promises": [">= 14.18 && < 15", ">= 16"],
      _http_agent: ">= 0.11.1",
      "node:_http_agent": [">= 14.18 && < 15", ">= 16"],
      _http_client: ">= 0.11.1",
      "node:_http_client": [">= 14.18 && < 15", ">= 16"],
      _http_common: ">= 0.11.1",
      "node:_http_common": [">= 14.18 && < 15", ">= 16"],
      _http_incoming: ">= 0.11.1",
      "node:_http_incoming": [">= 14.18 && < 15", ">= 16"],
      _http_outgoing: ">= 0.11.1",
      "node:_http_outgoing": [">= 14.18 && < 15", ">= 16"],
      _http_server: ">= 0.11.1",
      "node:_http_server": [">= 14.18 && < 15", ">= 16"],
      http: true,
      "node:http": [">= 14.18 && < 15", ">= 16"],
      http2: ">= 8.8",
      "node:http2": [">= 14.18 && < 15", ">= 16"],
      https: true,
      "node:https": [">= 14.18 && < 15", ">= 16"],
      inspector: ">= 8",
      "node:inspector": [">= 14.18 && < 15", ">= 16"],
      "inspector/promises": [">= 19"],
      "node:inspector/promises": [">= 19"],
      _linklist: "< 8",
      module: true,
      "node:module": [">= 14.18 && < 15", ">= 16"],
      net: true,
      "node:net": [">= 14.18 && < 15", ">= 16"],
      "node-inspect/lib/_inspect": ">= 7.6 && < 12",
      "node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12",
      "node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12",
      os: true,
      "node:os": [">= 14.18 && < 15", ">= 16"],
      path: true,
      "node:path": [">= 14.18 && < 15", ">= 16"],
      "path/posix": ">= 15.3",
      "node:path/posix": ">= 16",
      "path/win32": ">= 15.3",
      "node:path/win32": ">= 16",
      perf_hooks: ">= 8.5",
      "node:perf_hooks": [">= 14.18 && < 15", ">= 16"],
      process: ">= 1",
      "node:process": [">= 14.18 && < 15", ">= 16"],
      punycode: ">= 0.5",
      "node:punycode": [">= 14.18 && < 15", ">= 16"],
      querystring: true,
      "node:querystring": [">= 14.18 && < 15", ">= 16"],
      readline: true,
      "node:readline": [">= 14.18 && < 15", ">= 16"],
      "readline/promises": ">= 17",
      "node:readline/promises": ">= 17",
      repl: true,
      "node:repl": [">= 14.18 && < 15", ">= 16"],
      "node:sea": [">= 20.12 && < 21", ">= 21.7"],
      smalloc: ">= 0.11.5 && < 3",
      "node:sqlite": [">= 22.13 && < 23", ">= 23.4"],
      _stream_duplex: ">= 0.9.4",
      "node:_stream_duplex": [">= 14.18 && < 15", ">= 16"],
      _stream_transform: ">= 0.9.4",
      "node:_stream_transform": [">= 14.18 && < 15", ">= 16"],
      _stream_wrap: ">= 1.4.1",
      "node:_stream_wrap": [">= 14.18 && < 15", ">= 16"],
      _stream_passthrough: ">= 0.9.4",
      "node:_stream_passthrough": [">= 14.18 && < 15", ">= 16"],
      _stream_readable: ">= 0.9.4",
      "node:_stream_readable": [">= 14.18 && < 15", ">= 16"],
      _stream_writable: ">= 0.9.4",
      "node:_stream_writable": [">= 14.18 && < 15", ">= 16"],
      stream: true,
      "node:stream": [">= 14.18 && < 15", ">= 16"],
      "stream/consumers": ">= 16.7",
      "node:stream/consumers": ">= 16.7",
      "stream/promises": ">= 15",
      "node:stream/promises": ">= 16",
      "stream/web": ">= 16.5",
      "node:stream/web": ">= 16.5",
      string_decoder: true,
      "node:string_decoder": [">= 14.18 && < 15", ">= 16"],
      sys: [">= 0.4 && < 0.7", ">= 0.8"],
      "node:sys": [">= 14.18 && < 15", ">= 16"],
      "test/reporters": ">= 19.9 && < 20.2",
      "node:test/reporters": [">= 18.17 && < 19", ">= 19.9", ">= 20"],
      "test/mock_loader": ">= 22.3 && < 22.7",
      "node:test/mock_loader": ">= 22.3 && < 22.7",
      "node:test": [">= 16.17 && < 17", ">= 18"],
      timers: true,
      "node:timers": [">= 14.18 && < 15", ">= 16"],
      "timers/promises": ">= 15",
      "node:timers/promises": ">= 16",
      _tls_common: ">= 0.11.13",
      "node:_tls_common": [">= 14.18 && < 15", ">= 16"],
      _tls_legacy: ">= 0.11.3 && < 10",
      _tls_wrap: ">= 0.11.3",
      "node:_tls_wrap": [">= 14.18 && < 15", ">= 16"],
      tls: true,
      "node:tls": [">= 14.18 && < 15", ">= 16"],
      trace_events: ">= 10",
      "node:trace_events": [">= 14.18 && < 15", ">= 16"],
      tty: true,
      "node:tty": [">= 14.18 && < 15", ">= 16"],
      url: true,
      "node:url": [">= 14.18 && < 15", ">= 16"],
      util: true,
      "node:util": [">= 14.18 && < 15", ">= 16"],
      "util/types": ">= 15.3",
      "node:util/types": ">= 16",
      "v8/tools/arguments": ">= 10 && < 12",
      "v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      v8: ">= 1",
      "node:v8": [">= 14.18 && < 15", ">= 16"],
      vm: true,
      "node:vm": [">= 14.18 && < 15", ">= 16"],
      wasi: [">= 13.4 && < 13.5", ">= 18.17 && < 19", ">= 20"],
      "node:wasi": [">= 18.17 && < 19", ">= 20"],
      worker_threads: ">= 11.7",
      "node:worker_threads": [">= 14.18 && < 15", ">= 16"],
      zlib: ">= 0.5",
      "node:zlib": [">= 14.18 && < 15", ">= 16"]
    };
  }
});

// node_modules/is-core-module/index.js
var require_is_core_module = __commonJS({
  "node_modules/is-core-module/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var hasOwn2 = require_hasown();
    function specifierIncluded(current, specifier) {
      var nodeParts = current.split(".");
      var parts = specifier.split(" ");
      var op = parts.length > 1 ? parts[0] : "=";
      var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split(".");
      for (var i = 0; i < 3; ++i) {
        var cur = parseInt(nodeParts[i] || 0, 10);
        var ver = parseInt(versionParts[i] || 0, 10);
        if (cur === ver) {
          continue;
        }
        if (op === "<") {
          return cur < ver;
        }
        if (op === ">=") {
          return cur >= ver;
        }
        return false;
      }
      return op === ">=";
    }
    __name(specifierIncluded, "specifierIncluded");
    function matchesRange(current, range) {
      var specifiers = range.split(/ ?&& ?/);
      if (specifiers.length === 0) {
        return false;
      }
      for (var i = 0; i < specifiers.length; ++i) {
        if (!specifierIncluded(current, specifiers[i])) {
          return false;
        }
      }
      return true;
    }
    __name(matchesRange, "matchesRange");
    function versionIncluded(nodeVersion2, specifierValue) {
      if (typeof specifierValue === "boolean") {
        return specifierValue;
      }
      var current = typeof nodeVersion2 === "undefined" ? process.versions && process.versions.node : nodeVersion2;
      if (typeof current !== "string") {
        throw new TypeError(typeof nodeVersion2 === "undefined" ? "Unable to determine current node version" : "If provided, a valid node version is required");
      }
      if (specifierValue && typeof specifierValue === "object") {
        for (var i = 0; i < specifierValue.length; ++i) {
          if (matchesRange(current, specifierValue[i])) {
            return true;
          }
        }
        return false;
      }
      return matchesRange(current, specifierValue);
    }
    __name(versionIncluded, "versionIncluded");
    var data = require_core5();
    module2.exports = /* @__PURE__ */ __name(function isCore(x, nodeVersion2) {
      return hasOwn2(data, x) && versionIncluded(nodeVersion2, data[x]);
    }, "isCore");
  }
});

// node_modules/resolve/lib/async.js
var require_async = __commonJS({
  "node_modules/resolve/lib/async.js"(exports2, module2) {
    init_esbuild_shims();
    var fs95 = __require("fs");
    var getHomedir = require_homedir();
    var path108 = __require("path");
    var caller = require_caller();
    var nodeModulesPaths = require_node_modules_paths();
    var normalizeOptions = require_normalize_options();
    var isCore = require_is_core_module();
    var realpathFS = process.platform !== "win32" && fs95.realpath && typeof fs95.realpath.native === "function" ? fs95.realpath.native : fs95.realpath;
    var homedir20 = getHomedir();
    var defaultPaths = /* @__PURE__ */ __name(function() {
      return [
        path108.join(homedir20, ".node_modules"),
        path108.join(homedir20, ".node_libraries")
      ];
    }, "defaultPaths");
    var defaultIsFile = /* @__PURE__ */ __name(function isFile2(file, cb) {
      fs95.stat(file, function(err, stat7) {
        if (!err) {
          return cb(null, stat7.isFile() || stat7.isFIFO());
        }
        if (err.code === "ENOENT" || err.code === "ENOTDIR") return cb(null, false);
        return cb(err);
      });
    }, "isFile");
    var defaultIsDir = /* @__PURE__ */ __name(function isDirectory(dir, cb) {
      fs95.stat(dir, function(err, stat7) {
        if (!err) {
          return cb(null, stat7.isDirectory());
        }
        if (err.code === "ENOENT" || err.code === "ENOTDIR") return cb(null, false);
        return cb(err);
      });
    }, "isDirectory");
    var defaultRealpath = /* @__PURE__ */ __name(function realpath2(x, cb) {
      realpathFS(x, function(realpathErr, realPath) {
        if (realpathErr && realpathErr.code !== "ENOENT") cb(realpathErr);
        else cb(null, realpathErr ? x : realPath);
      });
    }, "realpath");
    var maybeRealpath = /* @__PURE__ */ __name(function maybeRealpath2(realpath2, x, opts, cb) {
      if (opts && opts.preserveSymlinks === false) {
        realpath2(x, cb);
      } else {
        cb(null, x);
      }
    }, "maybeRealpath");
    var defaultReadPackage = /* @__PURE__ */ __name(function defaultReadPackage2(readFile11, pkgfile, cb) {
      readFile11(pkgfile, function(readFileErr, body) {
        if (readFileErr) cb(readFileErr);
        else {
          try {
            var pkg2 = JSON.parse(body);
            cb(null, pkg2);
          } catch (jsonErr) {
            cb(null);
          }
        }
      });
    }, "defaultReadPackage");
    var getPackageCandidates = /* @__PURE__ */ __name(function getPackageCandidates2(x, start, opts) {
      var dirs = nodeModulesPaths(start, opts, x);
      for (var i = 0; i < dirs.length; i++) {
        dirs[i] = path108.join(dirs[i], x);
      }
      return dirs;
    }, "getPackageCandidates");
    module2.exports = /* @__PURE__ */ __name(function resolve24(x, options2, callback) {
      var cb = callback;
      var opts = options2;
      if (typeof options2 === "function") {
        cb = opts;
        opts = {};
      }
      if (typeof x !== "string") {
        var err = new TypeError("Path must be a string.");
        return process.nextTick(function() {
          cb(err);
        });
      }
      opts = normalizeOptions(x, opts);
      var isFile2 = opts.isFile || defaultIsFile;
      var isDirectory = opts.isDirectory || defaultIsDir;
      var readFile11 = opts.readFile || fs95.readFile;
      var realpath2 = opts.realpath || defaultRealpath;
      var readPackage2 = opts.readPackage || defaultReadPackage;
      if (opts.readFile && opts.readPackage) {
        var conflictErr = new TypeError("`readFile` and `readPackage` are mutually exclusive.");
        return process.nextTick(function() {
          cb(conflictErr);
        });
      }
      var packageIterator = opts.packageIterator;
      var extensions = opts.extensions || [".js"];
      var includeCoreModules = opts.includeCoreModules !== false;
      var basedir = opts.basedir || path108.dirname(caller());
      var parent = opts.filename || basedir;
      opts.paths = opts.paths || defaultPaths();
      var absoluteStart = path108.resolve(basedir);
      maybeRealpath(
        realpath2,
        absoluteStart,
        opts,
        function(err2, realStart) {
          if (err2) cb(err2);
          else init(realStart);
        }
      );
      var res;
      function init(basedir2) {
        if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) {
          res = path108.resolve(basedir2, x);
          if (x === "." || x === ".." || x.slice(-1) === "/") res += "/";
          if (/\/$/.test(x) && res === basedir2) {
            loadAsDirectory(res, opts.package, onfile);
          } else loadAsFile(res, opts.package, onfile);
        } else if (includeCoreModules && isCore(x)) {
          return cb(null, x);
        } else loadNodeModules(x, basedir2, function(err2, n2, pkg2) {
          if (err2) cb(err2);
          else if (n2) {
            return maybeRealpath(realpath2, n2, opts, function(err3, realN) {
              if (err3) {
                cb(err3);
              } else {
                cb(null, realN, pkg2);
              }
            });
          } else {
            var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
            moduleError.code = "MODULE_NOT_FOUND";
            cb(moduleError);
          }
        });
      }
      __name(init, "init");
      function onfile(err2, m, pkg2) {
        if (err2) cb(err2);
        else if (m) cb(null, m, pkg2);
        else loadAsDirectory(res, function(err3, d, pkg3) {
          if (err3) cb(err3);
          else if (d) {
            maybeRealpath(realpath2, d, opts, function(err4, realD) {
              if (err4) {
                cb(err4);
              } else {
                cb(null, realD, pkg3);
              }
            });
          } else {
            var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
            moduleError.code = "MODULE_NOT_FOUND";
            cb(moduleError);
          }
        });
      }
      __name(onfile, "onfile");
      function loadAsFile(x2, thePackage, callback2) {
        var loadAsFilePackage = thePackage;
        var cb2 = callback2;
        if (typeof loadAsFilePackage === "function") {
          cb2 = loadAsFilePackage;
          loadAsFilePackage = void 0;
        }
        var exts = [""].concat(extensions);
        load(exts, x2, loadAsFilePackage);
        function load(exts2, x3, loadPackage) {
          if (exts2.length === 0) return cb2(null, void 0, loadPackage);
          var file = x3 + exts2[0];
          var pkg2 = loadPackage;
          if (pkg2) onpkg(null, pkg2);
          else loadpkg(path108.dirname(file), onpkg);
          function onpkg(err2, pkg_, dir) {
            pkg2 = pkg_;
            if (err2) return cb2(err2);
            if (dir && pkg2 && opts.pathFilter) {
              var rfile = path108.relative(dir, file);
              var rel = rfile.slice(0, rfile.length - exts2[0].length);
              var r3 = opts.pathFilter(pkg2, x3, rel);
              if (r3) return load(
                [""].concat(extensions.slice()),
                path108.resolve(dir, r3),
                pkg2
              );
            }
            isFile2(file, onex);
          }
          __name(onpkg, "onpkg");
          function onex(err2, ex) {
            if (err2) return cb2(err2);
            if (ex) return cb2(null, file, pkg2);
            load(exts2.slice(1), x3, pkg2);
          }
          __name(onex, "onex");
        }
        __name(load, "load");
      }
      __name(loadAsFile, "loadAsFile");
      function loadpkg(dir, cb2) {
        if (dir === "" || dir === "/") return cb2(null);
        if (process.platform === "win32" && /^\w:[/\\]*$/.test(dir)) {
          return cb2(null);
        }
        if (/[/\\]node_modules[/\\]*$/.test(dir)) return cb2(null);
        maybeRealpath(realpath2, dir, opts, function(unwrapErr, pkgdir) {
          if (unwrapErr) return loadpkg(path108.dirname(dir), cb2);
          var pkgfile = path108.join(pkgdir, "package.json");
          isFile2(pkgfile, function(err2, ex) {
            if (!ex) return loadpkg(path108.dirname(dir), cb2);
            readPackage2(readFile11, pkgfile, function(err3, pkgParam) {
              if (err3) cb2(err3);
              var pkg2 = pkgParam;
              if (pkg2 && opts.packageFilter) {
                pkg2 = opts.packageFilter(pkg2, pkgfile);
              }
              cb2(null, pkg2, dir);
            });
          });
        });
      }
      __name(loadpkg, "loadpkg");
      function loadAsDirectory(x2, loadAsDirectoryPackage, callback2) {
        var cb2 = callback2;
        var fpkg = loadAsDirectoryPackage;
        if (typeof fpkg === "function") {
          cb2 = fpkg;
          fpkg = opts.package;
        }
        maybeRealpath(realpath2, x2, opts, function(unwrapErr, pkgdir) {
          if (unwrapErr) return cb2(unwrapErr);
          var pkgfile = path108.join(pkgdir, "package.json");
          isFile2(pkgfile, function(err2, ex) {
            if (err2) return cb2(err2);
            if (!ex) return loadAsFile(path108.join(x2, "index"), fpkg, cb2);
            readPackage2(readFile11, pkgfile, function(err3, pkgParam) {
              if (err3) return cb2(err3);
              var pkg2 = pkgParam;
              if (pkg2 && opts.packageFilter) {
                pkg2 = opts.packageFilter(pkg2, pkgfile);
              }
              if (pkg2 && pkg2.main) {
                if (typeof pkg2.main !== "string") {
                  var mainError = new TypeError("package \u201C" + pkg2.name + "\u201D `main` must be a string");
                  mainError.code = "INVALID_PACKAGE_MAIN";
                  return cb2(mainError);
                }
                if (pkg2.main === "." || pkg2.main === "./") {
                  pkg2.main = "index";
                }
                loadAsFile(path108.resolve(x2, pkg2.main), pkg2, function(err4, m, pkg3) {
                  if (err4) return cb2(err4);
                  if (m) return cb2(null, m, pkg3);
                  if (!pkg3) return loadAsFile(path108.join(x2, "index"), pkg3, cb2);
                  var dir = path108.resolve(x2, pkg3.main);
                  loadAsDirectory(dir, pkg3, function(err5, n2, pkg4) {
                    if (err5) return cb2(err5);
                    if (n2) return cb2(null, n2, pkg4);
                    loadAsFile(path108.join(x2, "index"), pkg4, cb2);
                  });
                });
                return;
              }
              loadAsFile(path108.join(x2, "/index"), pkg2, cb2);
            });
          });
        });
      }
      __name(loadAsDirectory, "loadAsDirectory");
      function processDirs(cb2, dirs) {
        if (dirs.length === 0) return cb2(null, void 0);
        var dir = dirs[0];
        isDirectory(path108.dirname(dir), isdir);
        function isdir(err2, isdir2) {
          if (err2) return cb2(err2);
          if (!isdir2) return processDirs(cb2, dirs.slice(1));
          loadAsFile(dir, opts.package, onfile2);
        }
        __name(isdir, "isdir");
        function onfile2(err2, m, pkg2) {
          if (err2) return cb2(err2);
          if (m) return cb2(null, m, pkg2);
          loadAsDirectory(dir, opts.package, ondir);
        }
        __name(onfile2, "onfile");
        function ondir(err2, n2, pkg2) {
          if (err2) return cb2(err2);
          if (n2) return cb2(null, n2, pkg2);
          processDirs(cb2, dirs.slice(1));
        }
        __name(ondir, "ondir");
      }
      __name(processDirs, "processDirs");
      function loadNodeModules(x2, start, cb2) {
        var thunk = /* @__PURE__ */ __name(function() {
          return getPackageCandidates(x2, start, opts);
        }, "thunk");
        processDirs(
          cb2,
          packageIterator ? packageIterator(x2, start, thunk, opts) : thunk()
        );
      }
      __name(loadNodeModules, "loadNodeModules");
    }, "resolve");
  }
});

// node_modules/resolve/lib/core.json
var require_core6 = __commonJS({
  "node_modules/resolve/lib/core.json"(exports2, module2) {
    module2.exports = {
      assert: true,
      "node:assert": [">= 14.18 && < 15", ">= 16"],
      "assert/strict": ">= 15",
      "node:assert/strict": ">= 16",
      async_hooks: ">= 8",
      "node:async_hooks": [">= 14.18 && < 15", ">= 16"],
      buffer_ieee754: ">= 0.5 && < 0.9.7",
      buffer: true,
      "node:buffer": [">= 14.18 && < 15", ">= 16"],
      child_process: true,
      "node:child_process": [">= 14.18 && < 15", ">= 16"],
      cluster: ">= 0.5",
      "node:cluster": [">= 14.18 && < 15", ">= 16"],
      console: true,
      "node:console": [">= 14.18 && < 15", ">= 16"],
      constants: true,
      "node:constants": [">= 14.18 && < 15", ">= 16"],
      crypto: true,
      "node:crypto": [">= 14.18 && < 15", ">= 16"],
      _debug_agent: ">= 1 && < 8",
      _debugger: "< 8",
      dgram: true,
      "node:dgram": [">= 14.18 && < 15", ">= 16"],
      diagnostics_channel: [">= 14.17 && < 15", ">= 15.1"],
      "node:diagnostics_channel": [">= 14.18 && < 15", ">= 16"],
      dns: true,
      "node:dns": [">= 14.18 && < 15", ">= 16"],
      "dns/promises": ">= 15",
      "node:dns/promises": ">= 16",
      domain: ">= 0.7.12",
      "node:domain": [">= 14.18 && < 15", ">= 16"],
      events: true,
      "node:events": [">= 14.18 && < 15", ">= 16"],
      freelist: "< 6",
      fs: true,
      "node:fs": [">= 14.18 && < 15", ">= 16"],
      "fs/promises": [">= 10 && < 10.1", ">= 14"],
      "node:fs/promises": [">= 14.18 && < 15", ">= 16"],
      _http_agent: ">= 0.11.1",
      "node:_http_agent": [">= 14.18 && < 15", ">= 16"],
      _http_client: ">= 0.11.1",
      "node:_http_client": [">= 14.18 && < 15", ">= 16"],
      _http_common: ">= 0.11.1",
      "node:_http_common": [">= 14.18 && < 15", ">= 16"],
      _http_incoming: ">= 0.11.1",
      "node:_http_incoming": [">= 14.18 && < 15", ">= 16"],
      _http_outgoing: ">= 0.11.1",
      "node:_http_outgoing": [">= 14.18 && < 15", ">= 16"],
      _http_server: ">= 0.11.1",
      "node:_http_server": [">= 14.18 && < 15", ">= 16"],
      http: true,
      "node:http": [">= 14.18 && < 15", ">= 16"],
      http2: ">= 8.8",
      "node:http2": [">= 14.18 && < 15", ">= 16"],
      https: true,
      "node:https": [">= 14.18 && < 15", ">= 16"],
      inspector: ">= 8",
      "node:inspector": [">= 14.18 && < 15", ">= 16"],
      "inspector/promises": [">= 19"],
      "node:inspector/promises": [">= 19"],
      _linklist: "< 8",
      module: true,
      "node:module": [">= 14.18 && < 15", ">= 16"],
      net: true,
      "node:net": [">= 14.18 && < 15", ">= 16"],
      "node-inspect/lib/_inspect": ">= 7.6 && < 12",
      "node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12",
      "node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12",
      os: true,
      "node:os": [">= 14.18 && < 15", ">= 16"],
      path: true,
      "node:path": [">= 14.18 && < 15", ">= 16"],
      "path/posix": ">= 15.3",
      "node:path/posix": ">= 16",
      "path/win32": ">= 15.3",
      "node:path/win32": ">= 16",
      perf_hooks: ">= 8.5",
      "node:perf_hooks": [">= 14.18 && < 15", ">= 16"],
      process: ">= 1",
      "node:process": [">= 14.18 && < 15", ">= 16"],
      punycode: ">= 0.5",
      "node:punycode": [">= 14.18 && < 15", ">= 16"],
      querystring: true,
      "node:querystring": [">= 14.18 && < 15", ">= 16"],
      readline: true,
      "node:readline": [">= 14.18 && < 15", ">= 16"],
      "readline/promises": ">= 17",
      "node:readline/promises": ">= 17",
      repl: true,
      "node:repl": [">= 14.18 && < 15", ">= 16"],
      "node:sea": [">= 20.12 && < 21", ">= 21.7"],
      smalloc: ">= 0.11.5 && < 3",
      "node:sqlite": ">= 23.4",
      _stream_duplex: ">= 0.9.4",
      "node:_stream_duplex": [">= 14.18 && < 15", ">= 16"],
      _stream_transform: ">= 0.9.4",
      "node:_stream_transform": [">= 14.18 && < 15", ">= 16"],
      _stream_wrap: ">= 1.4.1",
      "node:_stream_wrap": [">= 14.18 && < 15", ">= 16"],
      _stream_passthrough: ">= 0.9.4",
      "node:_stream_passthrough": [">= 14.18 && < 15", ">= 16"],
      _stream_readable: ">= 0.9.4",
      "node:_stream_readable": [">= 14.18 && < 15", ">= 16"],
      _stream_writable: ">= 0.9.4",
      "node:_stream_writable": [">= 14.18 && < 15", ">= 16"],
      stream: true,
      "node:stream": [">= 14.18 && < 15", ">= 16"],
      "stream/consumers": ">= 16.7",
      "node:stream/consumers": ">= 16.7",
      "stream/promises": ">= 15",
      "node:stream/promises": ">= 16",
      "stream/web": ">= 16.5",
      "node:stream/web": ">= 16.5",
      string_decoder: true,
      "node:string_decoder": [">= 14.18 && < 15", ">= 16"],
      sys: [">= 0.4 && < 0.7", ">= 0.8"],
      "node:sys": [">= 14.18 && < 15", ">= 16"],
      "test/reporters": ">= 19.9 && < 20.2",
      "node:test/reporters": [">= 18.17 && < 19", ">= 19.9", ">= 20"],
      "test/mock_loader": ">= 22.3 && < 22.7",
      "node:test/mock_loader": ">= 22.3 && < 22.7",
      "node:test": [">= 16.17 && < 17", ">= 18"],
      timers: true,
      "node:timers": [">= 14.18 && < 15", ">= 16"],
      "timers/promises": ">= 15",
      "node:timers/promises": ">= 16",
      _tls_common: ">= 0.11.13",
      "node:_tls_common": [">= 14.18 && < 15", ">= 16"],
      _tls_legacy: ">= 0.11.3 && < 10",
      _tls_wrap: ">= 0.11.3",
      "node:_tls_wrap": [">= 14.18 && < 15", ">= 16"],
      tls: true,
      "node:tls": [">= 14.18 && < 15", ">= 16"],
      trace_events: ">= 10",
      "node:trace_events": [">= 14.18 && < 15", ">= 16"],
      tty: true,
      "node:tty": [">= 14.18 && < 15", ">= 16"],
      url: true,
      "node:url": [">= 14.18 && < 15", ">= 16"],
      util: true,
      "node:util": [">= 14.18 && < 15", ">= 16"],
      "util/types": ">= 15.3",
      "node:util/types": ">= 16",
      "v8/tools/arguments": ">= 10 && < 12",
      "v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      v8: ">= 1",
      "node:v8": [">= 14.18 && < 15", ">= 16"],
      vm: true,
      "node:vm": [">= 14.18 && < 15", ">= 16"],
      wasi: [">= 13.4 && < 13.5", ">= 18.17 && < 19", ">= 20"],
      "node:wasi": [">= 18.17 && < 19", ">= 20"],
      worker_threads: ">= 11.7",
      "node:worker_threads": [">= 14.18 && < 15", ">= 16"],
      zlib: ">= 0.5",
      "node:zlib": [">= 14.18 && < 15", ">= 16"]
    };
  }
});

// node_modules/resolve/lib/core.js
var require_core7 = __commonJS({
  "node_modules/resolve/lib/core.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var isCoreModule = require_is_core_module();
    var data = require_core6();
    var core = {};
    for (mod2 in data) {
      if (Object.prototype.hasOwnProperty.call(data, mod2)) {
        core[mod2] = isCoreModule(mod2);
      }
    }
    var mod2;
    module2.exports = core;
  }
});

// node_modules/resolve/lib/is-core.js
var require_is_core = __commonJS({
  "node_modules/resolve/lib/is-core.js"(exports2, module2) {
    init_esbuild_shims();
    var isCoreModule = require_is_core_module();
    module2.exports = /* @__PURE__ */ __name(function isCore(x) {
      return isCoreModule(x);
    }, "isCore");
  }
});

// node_modules/resolve/lib/sync.js
var require_sync = __commonJS({
  "node_modules/resolve/lib/sync.js"(exports2, module2) {
    init_esbuild_shims();
    var isCore = require_is_core_module();
    var fs95 = __require("fs");
    var path108 = __require("path");
    var getHomedir = require_homedir();
    var caller = require_caller();
    var nodeModulesPaths = require_node_modules_paths();
    var normalizeOptions = require_normalize_options();
    var realpathFS = process.platform !== "win32" && fs95.realpathSync && typeof fs95.realpathSync.native === "function" ? fs95.realpathSync.native : fs95.realpathSync;
    var homedir20 = getHomedir();
    var defaultPaths = /* @__PURE__ */ __name(function() {
      return [
        path108.join(homedir20, ".node_modules"),
        path108.join(homedir20, ".node_libraries")
      ];
    }, "defaultPaths");
    var defaultIsFile = /* @__PURE__ */ __name(function isFile2(file) {
      try {
        var stat7 = fs95.statSync(file, { throwIfNoEntry: false });
      } catch (e2) {
        if (e2 && (e2.code === "ENOENT" || e2.code === "ENOTDIR")) return false;
        throw e2;
      }
      return !!stat7 && (stat7.isFile() || stat7.isFIFO());
    }, "isFile");
    var defaultIsDir = /* @__PURE__ */ __name(function isDirectory(dir) {
      try {
        var stat7 = fs95.statSync(dir, { throwIfNoEntry: false });
      } catch (e2) {
        if (e2 && (e2.code === "ENOENT" || e2.code === "ENOTDIR")) return false;
        throw e2;
      }
      return !!stat7 && stat7.isDirectory();
    }, "isDirectory");
    var defaultRealpathSync = /* @__PURE__ */ __name(function realpathSync8(x) {
      try {
        return realpathFS(x);
      } catch (realpathErr) {
        if (realpathErr.code !== "ENOENT") {
          throw realpathErr;
        }
      }
      return x;
    }, "realpathSync");
    var maybeRealpathSync = /* @__PURE__ */ __name(function maybeRealpathSync2(realpathSync8, x, opts) {
      if (opts && opts.preserveSymlinks === false) {
        return realpathSync8(x);
      }
      return x;
    }, "maybeRealpathSync");
    var defaultReadPackageSync = /* @__PURE__ */ __name(function defaultReadPackageSync2(readFileSync15, pkgfile) {
      var body = readFileSync15(pkgfile);
      try {
        var pkg2 = JSON.parse(body);
        return pkg2;
      } catch (jsonErr) {
      }
    }, "defaultReadPackageSync");
    var getPackageCandidates = /* @__PURE__ */ __name(function getPackageCandidates2(x, start, opts) {
      var dirs = nodeModulesPaths(start, opts, x);
      for (var i = 0; i < dirs.length; i++) {
        dirs[i] = path108.join(dirs[i], x);
      }
      return dirs;
    }, "getPackageCandidates");
    module2.exports = /* @__PURE__ */ __name(function resolveSync(x, options2) {
      if (typeof x !== "string") {
        throw new TypeError("Path must be a string.");
      }
      var opts = normalizeOptions(x, options2);
      var isFile2 = opts.isFile || defaultIsFile;
      var readFileSync15 = opts.readFileSync || fs95.readFileSync;
      var isDirectory = opts.isDirectory || defaultIsDir;
      var realpathSync8 = opts.realpathSync || defaultRealpathSync;
      var readPackageSync2 = opts.readPackageSync || defaultReadPackageSync;
      if (opts.readFileSync && opts.readPackageSync) {
        throw new TypeError("`readFileSync` and `readPackageSync` are mutually exclusive.");
      }
      var packageIterator = opts.packageIterator;
      var extensions = opts.extensions || [".js"];
      var includeCoreModules = opts.includeCoreModules !== false;
      var basedir = opts.basedir || path108.dirname(caller());
      var parent = opts.filename || basedir;
      opts.paths = opts.paths || defaultPaths();
      var absoluteStart = maybeRealpathSync(realpathSync8, path108.resolve(basedir), opts);
      if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) {
        var res = path108.resolve(absoluteStart, x);
        if (x === "." || x === ".." || x.slice(-1) === "/") res += "/";
        var m = loadAsFileSync(res) || loadAsDirectorySync(res);
        if (m) return maybeRealpathSync(realpathSync8, m, opts);
      } else if (includeCoreModules && isCore(x)) {
        return x;
      } else {
        var n2 = loadNodeModulesSync(x, absoluteStart);
        if (n2) return maybeRealpathSync(realpathSync8, n2, opts);
      }
      var err = new Error("Cannot find module '" + x + "' from '" + parent + "'");
      err.code = "MODULE_NOT_FOUND";
      throw err;
      function loadAsFileSync(x2) {
        var pkg2 = loadpkg(path108.dirname(x2));
        if (pkg2 && pkg2.dir && pkg2.pkg && opts.pathFilter) {
          var rfile = path108.relative(pkg2.dir, x2);
          var r3 = opts.pathFilter(pkg2.pkg, x2, rfile);
          if (r3) {
            x2 = path108.resolve(pkg2.dir, r3);
          }
        }
        if (isFile2(x2)) {
          return x2;
        }
        for (var i = 0; i < extensions.length; i++) {
          var file = x2 + extensions[i];
          if (isFile2(file)) {
            return file;
          }
        }
      }
      __name(loadAsFileSync, "loadAsFileSync");
      function loadpkg(dir) {
        if (dir === "" || dir === "/") return;
        if (process.platform === "win32" && /^\w:[/\\]*$/.test(dir)) {
          return;
        }
        if (/[/\\]node_modules[/\\]*$/.test(dir)) return;
        var pkgfile = path108.join(maybeRealpathSync(realpathSync8, dir, opts), "package.json");
        if (!isFile2(pkgfile)) {
          return loadpkg(path108.dirname(dir));
        }
        var pkg2 = readPackageSync2(readFileSync15, pkgfile);
        if (pkg2 && opts.packageFilter) {
          pkg2 = opts.packageFilter(
            pkg2,
            /*pkgfile,*/
            dir
          );
        }
        return { pkg: pkg2, dir };
      }
      __name(loadpkg, "loadpkg");
      function loadAsDirectorySync(x2) {
        var pkgfile = path108.join(maybeRealpathSync(realpathSync8, x2, opts), "/package.json");
        if (isFile2(pkgfile)) {
          try {
            var pkg2 = readPackageSync2(readFileSync15, pkgfile);
          } catch (e2) {
          }
          if (pkg2 && opts.packageFilter) {
            pkg2 = opts.packageFilter(
              pkg2,
              /*pkgfile,*/
              x2
            );
          }
          if (pkg2 && pkg2.main) {
            if (typeof pkg2.main !== "string") {
              var mainError = new TypeError("package \u201C" + pkg2.name + "\u201D `main` must be a string");
              mainError.code = "INVALID_PACKAGE_MAIN";
              throw mainError;
            }
            if (pkg2.main === "." || pkg2.main === "./") {
              pkg2.main = "index";
            }
            try {
              var m2 = loadAsFileSync(path108.resolve(x2, pkg2.main));
              if (m2) return m2;
              var n3 = loadAsDirectorySync(path108.resolve(x2, pkg2.main));
              if (n3) return n3;
            } catch (e2) {
            }
          }
        }
        return loadAsFileSync(path108.join(x2, "/index"));
      }
      __name(loadAsDirectorySync, "loadAsDirectorySync");
      function loadNodeModulesSync(x2, start) {
        var thunk = /* @__PURE__ */ __name(function() {
          return getPackageCandidates(x2, start, opts);
        }, "thunk");
        var dirs = packageIterator ? packageIterator(x2, start, thunk, opts) : thunk();
        for (var i = 0; i < dirs.length; i++) {
          var dir = dirs[i];
          if (isDirectory(path108.dirname(dir))) {
            var m2 = loadAsFileSync(dir);
            if (m2) return m2;
            var n3 = loadAsDirectorySync(dir);
            if (n3) return n3;
          }
        }
      }
      __name(loadNodeModulesSync, "loadNodeModulesSync");
    }, "resolveSync");
  }
});

// node_modules/resolve/index.js
var require_resolve3 = __commonJS({
  "node_modules/resolve/index.js"(exports2, module2) {
    init_esbuild_shims();
    var async = require_async();
    async.core = require_core7();
    async.isCore = require_is_core();
    async.sync = require_sync();
    module2.exports = async;
  }
});

// node_modules/require-in-the-middle/package.json
var require_package4 = __commonJS({
  "node_modules/require-in-the-middle/package.json"(exports2, module2) {
    module2.exports = {
      name: "require-in-the-middle",
      version: "7.5.2",
      description: "Module to hook into the Node.js require function",
      main: "index.js",
      types: "types/index.d.ts",
      dependencies: {
        debug: "^4.3.5",
        "module-details-from-path": "^1.0.3",
        resolve: "^1.22.8"
      },
      devDependencies: {
        "@babel/core": "^7.9.0",
        "@babel/preset-env": "^7.9.5",
        "@babel/preset-typescript": "^7.9.0",
        "@babel/register": "^7.9.0",
        "ipp-printer": "^1.0.0",
        patterns: "^1.0.3",
        roundround: "^0.2.0",
        semver: "^6.3.0",
        standard: "^14.3.1",
        tape: "^4.11.0"
      },
      scripts: {
        test: "npm run test:lint && npm run test:tape && npm run test:babel",
        "test:lint": "standard",
        "test:tape": "tape test/*.js",
        "test:babel": "node test/babel/babel-register.js"
      },
      repository: {
        type: "git",
        url: "git+https://github.com/nodejs/require-in-the-middle.git"
      },
      keywords: [
        "require",
        "hook",
        "shim",
        "shimmer",
        "shimming",
        "patch",
        "monkey",
        "monkeypatch",
        "module",
        "load"
      ],
      files: [
        "types"
      ],
      author: "Thomas Watson Steen <w@tson.dk> (https://twitter.com/wa7son)",
      license: "MIT",
      bugs: {
        url: "https://github.com/nodejs/require-in-the-middle/issues"
      },
      homepage: "https://github.com/nodejs/require-in-the-middle#readme",
      engines: {
        node: ">=8.6.0"
      }
    };
  }
});

// node_modules/require-in-the-middle/index.js
var require_require_in_the_middle = __commonJS({
  "node_modules/require-in-the-middle/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var path108 = __require("path");
    var Module = __require("module");
    var debug2 = require_src()("require-in-the-middle");
    var moduleDetailsFromPath = require_module_details_from_path();
    module2.exports = Hook;
    module2.exports.Hook = Hook;
    var builtinModules;
    var isCore;
    if (Module.isBuiltin) {
      isCore = Module.isBuiltin;
    } else if (Module.builtinModules) {
      isCore = /* @__PURE__ */ __name((moduleName2) => {
        if (moduleName2.startsWith("node:")) {
          return true;
        }
        if (builtinModules === void 0) {
          builtinModules = new Set(Module.builtinModules);
        }
        return builtinModules.has(moduleName2);
      }, "isCore");
    } else {
      const _resolve2 = require_resolve3();
      const [major2, minor] = process.versions.node.split(".").map(Number);
      if (major2 === 8 && minor < 8) {
        isCore = /* @__PURE__ */ __name((moduleName2) => {
          if (moduleName2 === "http2") {
            return true;
          }
          return !!_resolve2.core[moduleName2];
        }, "isCore");
      } else {
        isCore = /* @__PURE__ */ __name((moduleName2) => {
          return !!_resolve2.core[moduleName2];
        }, "isCore");
      }
    }
    var _resolve;
    function resolve24(moduleName2, basedir) {
      if (!_resolve) {
        if (__require.resolve && __require.resolve.paths) {
          _resolve = /* @__PURE__ */ __name(function(moduleName3, basedir2) {
            return __require.resolve(moduleName3, { paths: [basedir2] });
          }, "_resolve");
        } else {
          const resolve25 = require_resolve3();
          _resolve = /* @__PURE__ */ __name(function(moduleName3, basedir2) {
            return resolve25.sync(moduleName3, { basedir: basedir2 });
          }, "_resolve");
        }
      }
      return _resolve(moduleName2, basedir);
    }
    __name(resolve24, "resolve");
    var normalize10 = /([/\\]index)?(\.js)?$/;
    var ExportsCache = class {
      static {
        __name(this, "ExportsCache");
      }
      constructor() {
        this._localCache = /* @__PURE__ */ new Map();
        this._kRitmExports = Symbol("RitmExports");
      }
      has(filename, isBuiltin) {
        if (this._localCache.has(filename)) {
          return true;
        } else if (!isBuiltin) {
          const mod2 = __require.cache[filename];
          return !!(mod2 && this._kRitmExports in mod2);
        } else {
          return false;
        }
      }
      get(filename, isBuiltin) {
        const cachedExports = this._localCache.get(filename);
        if (cachedExports !== void 0) {
          return cachedExports;
        } else if (!isBuiltin) {
          const mod2 = __require.cache[filename];
          return mod2 && mod2[this._kRitmExports];
        }
      }
      set(filename, exports3, isBuiltin) {
        if (isBuiltin) {
          this._localCache.set(filename, exports3);
        } else if (filename in __require.cache) {
          __require.cache[filename][this._kRitmExports] = exports3;
        } else {
          debug2('non-core module is unexpectedly not in require.cache: "%s"', filename);
          this._localCache.set(filename, exports3);
        }
      }
    };
    function Hook(modules, options2, onrequire) {
      if (this instanceof Hook === false) return new Hook(modules, options2, onrequire);
      if (typeof modules === "function") {
        onrequire = modules;
        modules = null;
        options2 = null;
      } else if (typeof options2 === "function") {
        onrequire = options2;
        options2 = null;
      }
      if (typeof Module._resolveFilename !== "function") {
        console.error("Error: Expected Module._resolveFilename to be a function (was: %s) - aborting!", typeof Module._resolveFilename);
        console.error("Please report this error as an issue related to Node.js %s at %s", process.version, require_package4().bugs.url);
        return;
      }
      this._cache = new ExportsCache();
      this._unhooked = false;
      this._origRequire = Module.prototype.require;
      const self2 = this;
      const patching = /* @__PURE__ */ new Set();
      const internals = options2 ? options2.internals === true : false;
      const hasWhitelist = Array.isArray(modules);
      debug2("registering require hook");
      this._require = Module.prototype.require = function(id) {
        if (self2._unhooked === true) {
          debug2("ignoring require call - module is soft-unhooked");
          return self2._origRequire.apply(this, arguments);
        }
        return patchedRequire.call(this, arguments, false);
      };
      if (typeof process.getBuiltinModule === "function") {
        this._origGetBuiltinModule = process.getBuiltinModule;
        this._getBuiltinModule = process.getBuiltinModule = function(id) {
          if (self2._unhooked === true) {
            debug2("ignoring process.getBuiltinModule call - module is soft-unhooked");
            return self2._origGetBuiltinModule.apply(this, arguments);
          }
          return patchedRequire.call(this, arguments, true);
        };
      }
      function patchedRequire(args, coreOnly) {
        const id = args[0];
        const core = isCore(id);
        let filename;
        if (core) {
          filename = id;
          if (id.startsWith("node:")) {
            const idWithoutPrefix = id.slice(5);
            if (isCore(idWithoutPrefix)) {
              filename = idWithoutPrefix;
            }
          }
        } else if (coreOnly) {
          debug2("call to process.getBuiltinModule with unknown built-in id");
          return self2._origGetBuiltinModule.apply(this, args);
        } else {
          try {
            filename = Module._resolveFilename(id, this);
          } catch (resolveErr) {
            debug2('Module._resolveFilename("%s") threw %j, calling original Module.require', id, resolveErr.message);
            return self2._origRequire.apply(this, args);
          }
        }
        let moduleName2, basedir;
        debug2("processing %s module require('%s'): %s", core === true ? "core" : "non-core", id, filename);
        if (self2._cache.has(filename, core) === true) {
          debug2("returning already patched cached module: %s", filename);
          return self2._cache.get(filename, core);
        }
        const isPatching = patching.has(filename);
        if (isPatching === false) {
          patching.add(filename);
        }
        const exports3 = coreOnly ? self2._origGetBuiltinModule.apply(this, args) : self2._origRequire.apply(this, args);
        if (isPatching === true) {
          debug2("module is in the process of being patched already - ignoring: %s", filename);
          return exports3;
        }
        patching.delete(filename);
        if (core === true) {
          if (hasWhitelist === true && modules.includes(filename) === false) {
            debug2("ignoring core module not on whitelist: %s", filename);
            return exports3;
          }
          moduleName2 = filename;
        } else if (hasWhitelist === true && modules.includes(filename)) {
          const parsedPath = path108.parse(filename);
          moduleName2 = parsedPath.name;
          basedir = parsedPath.dir;
        } else {
          const stat7 = moduleDetailsFromPath(filename);
          if (stat7 === void 0) {
            debug2("could not parse filename: %s", filename);
            return exports3;
          }
          moduleName2 = stat7.name;
          basedir = stat7.basedir;
          const fullModuleName = resolveModuleName(stat7);
          debug2("resolved filename to module: %s (id: %s, resolved: %s, basedir: %s)", moduleName2, id, fullModuleName, basedir);
          let matchFound = false;
          if (hasWhitelist) {
            if (!id.startsWith(".") && modules.includes(id)) {
              moduleName2 = id;
              matchFound = true;
            }
            if (!modules.includes(moduleName2) && !modules.includes(fullModuleName)) {
              return exports3;
            }
            if (modules.includes(fullModuleName) && fullModuleName !== moduleName2) {
              moduleName2 = fullModuleName;
              matchFound = true;
            }
          }
          if (!matchFound) {
            let res;
            try {
              res = resolve24(moduleName2, basedir);
            } catch (e2) {
              debug2("could not resolve module: %s", moduleName2);
              self2._cache.set(filename, exports3, core);
              return exports3;
            }
            if (res !== filename) {
              if (internals === true) {
                moduleName2 = moduleName2 + path108.sep + path108.relative(basedir, filename);
                debug2("preparing to process require of internal file: %s", moduleName2);
              } else {
                debug2("ignoring require of non-main module file: %s", res);
                self2._cache.set(filename, exports3, core);
                return exports3;
              }
            }
          }
        }
        self2._cache.set(filename, exports3, core);
        debug2("calling require hook: %s", moduleName2);
        const patchedExports = onrequire(exports3, moduleName2, basedir);
        self2._cache.set(filename, patchedExports, core);
        debug2("returning module: %s", moduleName2);
        return patchedExports;
      }
      __name(patchedRequire, "patchedRequire");
    }
    __name(Hook, "Hook");
    Hook.prototype.unhook = function() {
      this._unhooked = true;
      if (this._require === Module.prototype.require) {
        Module.prototype.require = this._origRequire;
        debug2("require unhook successful");
      } else {
        debug2("require unhook unsuccessful");
      }
      if (process.getBuiltinModule !== void 0) {
        if (this._getBuiltinModule === process.getBuiltinModule) {
          process.getBuiltinModule = this._origGetBuiltinModule;
          debug2("process.getBuiltinModule unhook successful");
        } else {
          debug2("process.getBuiltinModule unhook unsuccessful");
        }
      }
    };
    function resolveModuleName(stat7) {
      const normalizedPath = path108.sep !== "/" ? stat7.path.split(path108.sep).join("/") : stat7.path;
      return path108.posix.join(stat7.name, normalizedPath).replace(normalize10, "");
    }
    __name(resolveModuleName, "resolveModuleName");
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/platform/node/ModuleNameTrie.js
var require_ModuleNameTrie = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/platform/node/ModuleNameTrie.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ModuleNameTrie = exports2.ModuleNameSeparator = void 0;
    exports2.ModuleNameSeparator = "/";
    var ModuleNameTrieNode = class {
      static {
        __name(this, "ModuleNameTrieNode");
      }
      hooks = [];
      children = /* @__PURE__ */ new Map();
    };
    var ModuleNameTrie = class {
      static {
        __name(this, "ModuleNameTrie");
      }
      _trie = new ModuleNameTrieNode();
      _counter = 0;
      /**
       * Insert a module hook into the trie
       *
       * @param {Hooked} hook Hook
       */
      insert(hook) {
        let trieNode = this._trie;
        for (const moduleNamePart of hook.moduleName.split(exports2.ModuleNameSeparator)) {
          let nextNode = trieNode.children.get(moduleNamePart);
          if (!nextNode) {
            nextNode = new ModuleNameTrieNode();
            trieNode.children.set(moduleNamePart, nextNode);
          }
          trieNode = nextNode;
        }
        trieNode.hooks.push({ hook, insertedId: this._counter++ });
      }
      /**
       * Search for matching hooks in the trie
       *
       * @param {string} moduleName Module name
       * @param {boolean} maintainInsertionOrder Whether to return the results in insertion order
       * @param {boolean} fullOnly Whether to return only full matches
       * @returns {Hooked[]} Matching hooks
       */
      search(moduleName2, { maintainInsertionOrder, fullOnly } = {}) {
        let trieNode = this._trie;
        const results = [];
        let foundFull = true;
        for (const moduleNamePart of moduleName2.split(exports2.ModuleNameSeparator)) {
          const nextNode = trieNode.children.get(moduleNamePart);
          if (!nextNode) {
            foundFull = false;
            break;
          }
          if (!fullOnly) {
            results.push(...nextNode.hooks);
          }
          trieNode = nextNode;
        }
        if (fullOnly && foundFull) {
          results.push(...trieNode.hooks);
        }
        if (results.length === 0) {
          return [];
        }
        if (results.length === 1) {
          return [results[0].hook];
        }
        if (maintainInsertionOrder) {
          results.sort((a, b) => a.insertedId - b.insertedId);
        }
        return results.map(({ hook }) => hook);
      }
    };
    exports2.ModuleNameTrie = ModuleNameTrie;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/platform/node/RequireInTheMiddleSingleton.js
var require_RequireInTheMiddleSingleton = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/platform/node/RequireInTheMiddleSingleton.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RequireInTheMiddleSingleton = void 0;
    var require_in_the_middle_1 = require_require_in_the_middle();
    var path108 = __require("path");
    var ModuleNameTrie_1 = require_ModuleNameTrie();
    var isMocha = [
      "afterEach",
      "after",
      "beforeEach",
      "before",
      "describe",
      "it"
    ].every((fn) => {
      return typeof globalThis[fn] === "function";
    });
    var RequireInTheMiddleSingleton = class _RequireInTheMiddleSingleton {
      static {
        __name(this, "RequireInTheMiddleSingleton");
      }
      _moduleNameTrie = new ModuleNameTrie_1.ModuleNameTrie();
      static _instance;
      constructor() {
        this._initialize();
      }
      _initialize() {
        new require_in_the_middle_1.Hook(
          // Intercept all `require` calls; we will filter the matching ones below
          null,
          { internals: true },
          (exports3, name3, basedir) => {
            const normalizedModuleName = normalizePathSeparators(name3);
            const matches = this._moduleNameTrie.search(normalizedModuleName, {
              maintainInsertionOrder: true,
              // For core modules (e.g. `fs`), do not match on sub-paths (e.g. `fs/promises').
              // This matches the behavior of `require-in-the-middle`.
              // `basedir` is always `undefined` for core modules.
              fullOnly: basedir === void 0
            });
            for (const { onRequire } of matches) {
              exports3 = onRequire(exports3, name3, basedir);
            }
            return exports3;
          }
        );
      }
      /**
       * Register a hook with `require-in-the-middle`
       *
       * @param {string} moduleName Module name
       * @param {OnRequireFn} onRequire Hook function
       * @returns {Hooked} Registered hook
       */
      register(moduleName2, onRequire) {
        const hooked = { moduleName: moduleName2, onRequire };
        this._moduleNameTrie.insert(hooked);
        return hooked;
      }
      /**
       * Get the `RequireInTheMiddleSingleton` singleton
       *
       * @returns {RequireInTheMiddleSingleton} Singleton of `RequireInTheMiddleSingleton`
       */
      static getInstance() {
        if (isMocha)
          return new _RequireInTheMiddleSingleton();
        return this._instance = this._instance ?? new _RequireInTheMiddleSingleton();
      }
    };
    exports2.RequireInTheMiddleSingleton = RequireInTheMiddleSingleton;
    function normalizePathSeparators(moduleNameOrPath) {
      return path108.sep !== ModuleNameTrie_1.ModuleNameSeparator ? moduleNameOrPath.split(path108.sep).join(ModuleNameTrie_1.ModuleNameSeparator) : moduleNameOrPath;
    }
    __name(normalizePathSeparators, "normalizePathSeparators");
  }
});

// node_modules/import-in-the-middle/lib/register.js
var require_register = __commonJS({
  "node_modules/import-in-the-middle/lib/register.js"(exports2) {
    init_esbuild_shims();
    var importHooks = [];
    var setters = /* @__PURE__ */ new WeakMap();
    var getters = /* @__PURE__ */ new WeakMap();
    var specifiers = /* @__PURE__ */ new Map();
    var toHook = [];
    var proxyHandler = {
      set(target, name3, value) {
        return setters.get(target)[name3](value);
      },
      get(target, name3) {
        if (name3 === Symbol.toStringTag) {
          return "Module";
        }
        const getter = getters.get(target)[name3];
        if (typeof getter === "function") {
          return getter();
        }
      },
      defineProperty(target, property, descriptor2) {
        if (!("value" in descriptor2)) {
          throw new Error("Getters/setters are not supported for exports property descriptors.");
        }
        return setters.get(target)[property](descriptor2.value);
      }
    };
    function register(name3, namespace, set, get3, specifier) {
      specifiers.set(name3, specifier);
      setters.set(namespace, set);
      getters.set(namespace, get3);
      const proxy = new Proxy(namespace, proxyHandler);
      importHooks.forEach((hook) => hook(name3, proxy));
      toHook.push([name3, proxy]);
    }
    __name(register, "register");
    var experimentalPatchInternals = false;
    function getExperimentalPatchInternals() {
      return experimentalPatchInternals;
    }
    __name(getExperimentalPatchInternals, "getExperimentalPatchInternals");
    function setExperimentalPatchInternals(value) {
      experimentalPatchInternals = value;
    }
    __name(setExperimentalPatchInternals, "setExperimentalPatchInternals");
    exports2.register = register;
    exports2.importHooks = importHooks;
    exports2.specifiers = specifiers;
    exports2.toHook = toHook;
    exports2.getExperimentalPatchInternals = getExperimentalPatchInternals;
    exports2.setExperimentalPatchInternals = setExperimentalPatchInternals;
  }
});

// node_modules/import-in-the-middle/index.js
var require_import_in_the_middle = __commonJS({
  "node_modules/import-in-the-middle/index.js"(exports2, module2) {
    init_esbuild_shims();
    var path108 = __require("path");
    var parse12 = require_module_details_from_path();
    var { fileURLToPath: fileURLToPath14 } = __require("url");
    var { MessageChannel: MessageChannel2 } = __require("worker_threads");
    var {
      importHooks,
      specifiers,
      toHook,
      getExperimentalPatchInternals
    } = require_register();
    function addHook(hook) {
      importHooks.push(hook);
      toHook.forEach(([name3, namespace]) => hook(name3, namespace));
    }
    __name(addHook, "addHook");
    function removeHook(hook) {
      const index = importHooks.indexOf(hook);
      if (index > -1) {
        importHooks.splice(index, 1);
      }
    }
    __name(removeHook, "removeHook");
    function callHookFn(hookFn, namespace, name3, baseDir) {
      const newDefault = hookFn(namespace, name3, baseDir);
      if (newDefault && newDefault !== namespace) {
        namespace.default = newDefault;
      }
    }
    __name(callHookFn, "callHookFn");
    var sendModulesToLoader;
    function createAddHookMessageChannel() {
      const { port1, port2 } = new MessageChannel2();
      let pendingAckCount = 0;
      let resolveFn;
      sendModulesToLoader = /* @__PURE__ */ __name((modules) => {
        pendingAckCount++;
        port1.postMessage(modules);
      }, "sendModulesToLoader");
      port1.on("message", () => {
        pendingAckCount--;
        if (resolveFn && pendingAckCount <= 0) {
          resolveFn();
        }
      }).unref();
      function waitForAllMessagesAcknowledged() {
        const timer = setInterval(() => {
        }, 1e3);
        const promise = new Promise((resolve24) => {
          resolveFn = resolve24;
        }).then(() => {
          clearInterval(timer);
        });
        if (pendingAckCount === 0) {
          resolveFn();
        }
        return promise;
      }
      __name(waitForAllMessagesAcknowledged, "waitForAllMessagesAcknowledged");
      const addHookMessagePort = port2;
      const registerOptions = { data: { addHookMessagePort, include: [] }, transferList: [addHookMessagePort] };
      return { registerOptions, addHookMessagePort, waitForAllMessagesAcknowledged };
    }
    __name(createAddHookMessageChannel, "createAddHookMessageChannel");
    function Hook(modules, options2, hookFn) {
      if (this instanceof Hook === false) return new Hook(modules, options2, hookFn);
      if (typeof modules === "function") {
        hookFn = modules;
        modules = null;
        options2 = null;
      } else if (typeof options2 === "function") {
        hookFn = options2;
        options2 = null;
      }
      const internals = options2 ? options2.internals === true : false;
      if (sendModulesToLoader && Array.isArray(modules)) {
        sendModulesToLoader(modules);
      }
      this._iitmHook = (name3, namespace) => {
        const filename = name3;
        const isBuiltin = name3.startsWith("node:");
        let baseDir;
        if (isBuiltin) {
          name3 = name3.replace(/^node:/, "");
        } else {
          if (name3.startsWith("file://")) {
            try {
              name3 = fileURLToPath14(name3);
            } catch (e2) {
            }
          }
          const details = parse12(name3);
          if (details) {
            name3 = details.name;
            baseDir = details.basedir;
          }
        }
        if (modules) {
          for (const moduleName2 of modules) {
            if (moduleName2 === name3) {
              if (baseDir) {
                if (internals) {
                  name3 = name3 + path108.sep + path108.relative(baseDir, fileURLToPath14(filename));
                } else {
                  if (!getExperimentalPatchInternals() && !baseDir.endsWith(specifiers.get(filename))) continue;
                }
              }
              callHookFn(hookFn, namespace, name3, baseDir);
            }
          }
        } else {
          callHookFn(hookFn, namespace, name3, baseDir);
        }
      };
      addHook(this._iitmHook);
    }
    __name(Hook, "Hook");
    Hook.prototype.unhook = function() {
      removeHook(this._iitmHook);
    };
    module2.exports = Hook;
    module2.exports.Hook = Hook;
    module2.exports.addHook = addHook;
    module2.exports.removeHook = removeHook;
    module2.exports.createAddHookMessageChannel = createAddHookMessageChannel;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/utils.js
var require_utils9 = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isWrapped = exports2.safeExecuteInTheMiddleAsync = exports2.safeExecuteInTheMiddle = void 0;
    function safeExecuteInTheMiddle(execute, onFinish, preventThrowingError) {
      let error;
      let result;
      try {
        result = execute();
      } catch (e2) {
        error = e2;
      } finally {
        onFinish(error, result);
        if (error && !preventThrowingError) {
          throw error;
        }
        return result;
      }
    }
    __name(safeExecuteInTheMiddle, "safeExecuteInTheMiddle");
    exports2.safeExecuteInTheMiddle = safeExecuteInTheMiddle;
    async function safeExecuteInTheMiddleAsync(execute, onFinish, preventThrowingError) {
      let error;
      let result;
      try {
        result = await execute();
      } catch (e2) {
        error = e2;
      } finally {
        onFinish(error, result);
        if (error && !preventThrowingError) {
          throw error;
        }
        return result;
      }
    }
    __name(safeExecuteInTheMiddleAsync, "safeExecuteInTheMiddleAsync");
    exports2.safeExecuteInTheMiddleAsync = safeExecuteInTheMiddleAsync;
    function isWrapped(func) {
      return typeof func === "function" && typeof func.__original === "function" && typeof func.__unwrap === "function" && func.__wrapped === true;
    }
    __name(isWrapped, "isWrapped");
    exports2.isWrapped = isWrapped;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/platform/node/instrumentation.js
var require_instrumentation2 = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/platform/node/instrumentation.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InstrumentationBase = void 0;
    var path108 = __require("path");
    var util_1 = __require("util");
    var semver_1 = require_semver();
    var shimmer_1 = require_shimmer();
    var instrumentation_1 = require_instrumentation();
    var RequireInTheMiddleSingleton_1 = require_RequireInTheMiddleSingleton();
    var import_in_the_middle_1 = require_import_in_the_middle();
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var require_in_the_middle_1 = require_require_in_the_middle();
    var fs_1 = __require("fs");
    var utils_1 = require_utils9();
    var InstrumentationBase = class extends instrumentation_1.InstrumentationAbstract {
      static {
        __name(this, "InstrumentationBase");
      }
      _modules;
      _hooks = [];
      _requireInTheMiddleSingleton = RequireInTheMiddleSingleton_1.RequireInTheMiddleSingleton.getInstance();
      _enabled = false;
      constructor(instrumentationName, instrumentationVersion, config) {
        super(instrumentationName, instrumentationVersion, config);
        let modules = this.init();
        if (modules && !Array.isArray(modules)) {
          modules = [modules];
        }
        this._modules = modules || [];
        if (this._config.enabled) {
          this.enable();
        }
      }
      _wrap = /* @__PURE__ */ __name((moduleExports, name3, wrapper) => {
        if ((0, utils_1.isWrapped)(moduleExports[name3])) {
          this._unwrap(moduleExports, name3);
        }
        if (!util_1.types.isProxy(moduleExports)) {
          return (0, shimmer_1.wrap)(moduleExports, name3, wrapper);
        } else {
          const wrapped = (0, shimmer_1.wrap)(Object.assign({}, moduleExports), name3, wrapper);
          Object.defineProperty(moduleExports, name3, {
            value: wrapped
          });
          return wrapped;
        }
      }, "_wrap");
      _unwrap = /* @__PURE__ */ __name((moduleExports, name3) => {
        if (!util_1.types.isProxy(moduleExports)) {
          return (0, shimmer_1.unwrap)(moduleExports, name3);
        } else {
          return Object.defineProperty(moduleExports, name3, {
            value: moduleExports[name3]
          });
        }
      }, "_unwrap");
      _massWrap = /* @__PURE__ */ __name((moduleExportsArray, names, wrapper) => {
        if (!moduleExportsArray) {
          api_1.diag.error("must provide one or more modules to patch");
          return;
        } else if (!Array.isArray(moduleExportsArray)) {
          moduleExportsArray = [moduleExportsArray];
        }
        if (!(names && Array.isArray(names))) {
          api_1.diag.error("must provide one or more functions to wrap on modules");
          return;
        }
        moduleExportsArray.forEach((moduleExports) => {
          names.forEach((name3) => {
            this._wrap(moduleExports, name3, wrapper);
          });
        });
      }, "_massWrap");
      _massUnwrap = /* @__PURE__ */ __name((moduleExportsArray, names) => {
        if (!moduleExportsArray) {
          api_1.diag.error("must provide one or more modules to patch");
          return;
        } else if (!Array.isArray(moduleExportsArray)) {
          moduleExportsArray = [moduleExportsArray];
        }
        if (!(names && Array.isArray(names))) {
          api_1.diag.error("must provide one or more functions to wrap on modules");
          return;
        }
        moduleExportsArray.forEach((moduleExports) => {
          names.forEach((name3) => {
            this._unwrap(moduleExports, name3);
          });
        });
      }, "_massUnwrap");
      _warnOnPreloadedModules() {
        this._modules.forEach((module3) => {
          const { name: name3 } = module3;
          try {
            const resolvedModule = __require.resolve(name3);
            if (__require.cache[resolvedModule]) {
              this._diag.warn(`Module ${name3} has been loaded before ${this.instrumentationName} so it might not work, please initialize it before requiring ${name3}`);
            }
          } catch {
          }
        });
      }
      _extractPackageVersion(baseDir) {
        try {
          const json2 = (0, fs_1.readFileSync)(path108.join(baseDir, "package.json"), {
            encoding: "utf8"
          });
          const version2 = JSON.parse(json2).version;
          return typeof version2 === "string" ? version2 : void 0;
        } catch {
          api_1.diag.warn("Failed extracting version", baseDir);
        }
        return void 0;
      }
      _onRequire(module3, exports3, name3, baseDir) {
        if (!baseDir) {
          if (typeof module3.patch === "function") {
            module3.moduleExports = exports3;
            if (this._enabled) {
              this._diag.debug("Applying instrumentation patch for nodejs core module on require hook", {
                module: module3.name
              });
              return module3.patch(exports3);
            }
          }
          return exports3;
        }
        const version2 = this._extractPackageVersion(baseDir);
        module3.moduleVersion = version2;
        if (module3.name === name3) {
          if (isSupported(module3.supportedVersions, version2, module3.includePrerelease)) {
            if (typeof module3.patch === "function") {
              module3.moduleExports = exports3;
              if (this._enabled) {
                this._diag.debug("Applying instrumentation patch for module on require hook", {
                  module: module3.name,
                  version: module3.moduleVersion,
                  baseDir
                });
                return module3.patch(exports3, module3.moduleVersion);
              }
            }
          }
          return exports3;
        }
        const files = module3.files ?? [];
        const normalizedName = path108.normalize(name3);
        const supportedFileInstrumentations = files.filter((f) => f.name === normalizedName).filter((f) => isSupported(f.supportedVersions, version2, module3.includePrerelease));
        return supportedFileInstrumentations.reduce((patchedExports, file) => {
          file.moduleExports = patchedExports;
          if (this._enabled) {
            this._diag.debug("Applying instrumentation patch for nodejs module file on require hook", {
              module: module3.name,
              version: module3.moduleVersion,
              fileName: file.name,
              baseDir
            });
            return file.patch(patchedExports, module3.moduleVersion);
          }
          return patchedExports;
        }, exports3);
      }
      enable() {
        if (this._enabled) {
          return;
        }
        this._enabled = true;
        if (this._hooks.length > 0) {
          for (const module3 of this._modules) {
            if (typeof module3.patch === "function" && module3.moduleExports) {
              this._diag.debug("Applying instrumentation patch for nodejs module on instrumentation enabled", {
                module: module3.name,
                version: module3.moduleVersion
              });
              module3.patch(module3.moduleExports, module3.moduleVersion);
            }
            for (const file of module3.files) {
              if (file.moduleExports) {
                this._diag.debug("Applying instrumentation patch for nodejs module file on instrumentation enabled", {
                  module: module3.name,
                  version: module3.moduleVersion,
                  fileName: file.name
                });
                file.patch(file.moduleExports, module3.moduleVersion);
              }
            }
          }
          return;
        }
        this._warnOnPreloadedModules();
        for (const module3 of this._modules) {
          const hookFn = /* @__PURE__ */ __name((exports3, name3, baseDir) => {
            if (!baseDir && path108.isAbsolute(name3)) {
              const parsedPath = path108.parse(name3);
              name3 = parsedPath.name;
              baseDir = parsedPath.dir;
            }
            return this._onRequire(module3, exports3, name3, baseDir);
          }, "hookFn");
          const onRequire = /* @__PURE__ */ __name((exports3, name3, baseDir) => {
            return this._onRequire(module3, exports3, name3, baseDir);
          }, "onRequire");
          const hook = path108.isAbsolute(module3.name) ? new require_in_the_middle_1.Hook([module3.name], { internals: true }, onRequire) : this._requireInTheMiddleSingleton.register(module3.name, onRequire);
          this._hooks.push(hook);
          const esmHook = new import_in_the_middle_1.Hook([module3.name], { internals: false }, hookFn);
          this._hooks.push(esmHook);
        }
      }
      disable() {
        if (!this._enabled) {
          return;
        }
        this._enabled = false;
        for (const module3 of this._modules) {
          if (typeof module3.unpatch === "function" && module3.moduleExports) {
            this._diag.debug("Removing instrumentation patch for nodejs module on instrumentation disabled", {
              module: module3.name,
              version: module3.moduleVersion
            });
            module3.unpatch(module3.moduleExports, module3.moduleVersion);
          }
          for (const file of module3.files) {
            if (file.moduleExports) {
              this._diag.debug("Removing instrumentation patch for nodejs module file on instrumentation disabled", {
                module: module3.name,
                version: module3.moduleVersion,
                fileName: file.name
              });
              file.unpatch(file.moduleExports, module3.moduleVersion);
            }
          }
        }
      }
      isEnabled() {
        return this._enabled;
      }
    };
    exports2.InstrumentationBase = InstrumentationBase;
    function isSupported(supportedVersions, version2, includePrerelease) {
      if (typeof version2 === "undefined") {
        return supportedVersions.includes("*");
      }
      return supportedVersions.some((supportedVersion) => {
        return (0, semver_1.satisfies)(version2, supportedVersion, { includePrerelease });
      });
    }
    __name(isSupported, "isSupported");
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/platform/node/normalize.js
var require_normalize = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/platform/node/normalize.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.normalize = void 0;
    var path_1 = __require("path");
    Object.defineProperty(exports2, "normalize", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return path_1.normalize;
    }, "get") });
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/platform/node/index.js
var require_node11 = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/platform/node/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.normalize = exports2.InstrumentationBase = void 0;
    var instrumentation_1 = require_instrumentation2();
    Object.defineProperty(exports2, "InstrumentationBase", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return instrumentation_1.InstrumentationBase;
    }, "get") });
    var normalize_1 = require_normalize();
    Object.defineProperty(exports2, "normalize", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return normalize_1.normalize;
    }, "get") });
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/platform/index.js
var require_platform10 = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/platform/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.normalize = exports2.InstrumentationBase = void 0;
    var node_1 = require_node11();
    Object.defineProperty(exports2, "InstrumentationBase", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.InstrumentationBase;
    }, "get") });
    Object.defineProperty(exports2, "normalize", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.normalize;
    }, "get") });
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/instrumentationNodeModuleDefinition.js
var require_instrumentationNodeModuleDefinition = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/instrumentationNodeModuleDefinition.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InstrumentationNodeModuleDefinition = void 0;
    var InstrumentationNodeModuleDefinition = class {
      static {
        __name(this, "InstrumentationNodeModuleDefinition");
      }
      name;
      supportedVersions;
      patch;
      unpatch;
      files;
      constructor(name3, supportedVersions, patch, unpatch, files) {
        this.name = name3;
        this.supportedVersions = supportedVersions;
        this.patch = patch;
        this.unpatch = unpatch;
        this.files = files || [];
      }
    };
    exports2.InstrumentationNodeModuleDefinition = InstrumentationNodeModuleDefinition;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/instrumentationNodeModuleFile.js
var require_instrumentationNodeModuleFile = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/instrumentationNodeModuleFile.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InstrumentationNodeModuleFile = void 0;
    var index_1 = require_platform10();
    var InstrumentationNodeModuleFile = class {
      static {
        __name(this, "InstrumentationNodeModuleFile");
      }
      supportedVersions;
      patch;
      unpatch;
      name;
      constructor(name3, supportedVersions, patch, unpatch) {
        this.supportedVersions = supportedVersions;
        this.patch = patch;
        this.unpatch = unpatch;
        this.name = (0, index_1.normalize)(name3);
      }
    };
    exports2.InstrumentationNodeModuleFile = InstrumentationNodeModuleFile;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/semconvStability.js
var require_semconvStability = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/semconvStability.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.semconvStabilityFromStr = exports2.SemconvStability = void 0;
    var SemconvStability;
    (function(SemconvStability2) {
      SemconvStability2[SemconvStability2["STABLE"] = 1] = "STABLE";
      SemconvStability2[SemconvStability2["OLD"] = 2] = "OLD";
      SemconvStability2[SemconvStability2["DUPLICATE"] = 3] = "DUPLICATE";
    })(SemconvStability = exports2.SemconvStability || (exports2.SemconvStability = {}));
    function semconvStabilityFromStr(namespace, str2) {
      let semconvStability = SemconvStability.OLD;
      const entries = str2?.split(",").map((v) => v.trim()).filter((s2) => s2 !== "");
      for (const entry of entries ?? []) {
        if (entry.toLowerCase() === namespace + "/dup") {
          semconvStability = SemconvStability.DUPLICATE;
          break;
        } else if (entry.toLowerCase() === namespace) {
          semconvStability = SemconvStability.STABLE;
        }
      }
      return semconvStability;
    }
    __name(semconvStabilityFromStr, "semconvStabilityFromStr");
    exports2.semconvStabilityFromStr = semconvStabilityFromStr;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/index.js
var require_src26 = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.semconvStabilityFromStr = exports2.SemconvStability = exports2.safeExecuteInTheMiddleAsync = exports2.safeExecuteInTheMiddle = exports2.isWrapped = exports2.InstrumentationNodeModuleFile = exports2.InstrumentationNodeModuleDefinition = exports2.InstrumentationBase = exports2.registerInstrumentations = void 0;
    var autoLoader_1 = require_autoLoader();
    Object.defineProperty(exports2, "registerInstrumentations", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return autoLoader_1.registerInstrumentations;
    }, "get") });
    var index_1 = require_platform10();
    Object.defineProperty(exports2, "InstrumentationBase", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return index_1.InstrumentationBase;
    }, "get") });
    var instrumentationNodeModuleDefinition_1 = require_instrumentationNodeModuleDefinition();
    Object.defineProperty(exports2, "InstrumentationNodeModuleDefinition", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return instrumentationNodeModuleDefinition_1.InstrumentationNodeModuleDefinition;
    }, "get") });
    var instrumentationNodeModuleFile_1 = require_instrumentationNodeModuleFile();
    Object.defineProperty(exports2, "InstrumentationNodeModuleFile", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return instrumentationNodeModuleFile_1.InstrumentationNodeModuleFile;
    }, "get") });
    var utils_1 = require_utils9();
    Object.defineProperty(exports2, "isWrapped", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return utils_1.isWrapped;
    }, "get") });
    Object.defineProperty(exports2, "safeExecuteInTheMiddle", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return utils_1.safeExecuteInTheMiddle;
    }, "get") });
    Object.defineProperty(exports2, "safeExecuteInTheMiddleAsync", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return utils_1.safeExecuteInTheMiddleAsync;
    }, "get") });
    var semconvStability_1 = require_semconvStability();
    Object.defineProperty(exports2, "SemconvStability", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return semconvStability_1.SemconvStability;
    }, "get") });
    Object.defineProperty(exports2, "semconvStabilityFromStr", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return semconvStability_1.semconvStabilityFromStr;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/version.js
var require_version6 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/version.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.VERSION = void 0;
    exports2.VERSION = "0.203.0";
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/OTLPLogExporter.js
var require_OTLPLogExporter3 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/OTLPLogExporter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPLogExporter = void 0;
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var otlp_transformer_1 = require_src15();
    var node_http_1 = (init_index_node_http(), __toCommonJS(index_node_http_exports));
    var version_1 = require_version6();
    var OTLPLogExporter2 = class extends otlp_exporter_base_1.OTLPExporterBase {
      static {
        __name(this, "OTLPLogExporter");
      }
      constructor(config = {}) {
        super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, "LOGS", "v1/logs", {
          "User-Agent": `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`,
          "Content-Type": "application/x-protobuf"
        }), otlp_transformer_1.ProtobufLogsSerializer));
      }
    };
    exports2.OTLPLogExporter = OTLPLogExporter2;
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/index.js
var require_node12 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPLogExporter = void 0;
    var OTLPLogExporter_1 = require_OTLPLogExporter3();
    Object.defineProperty(exports2, "OTLPLogExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPLogExporter_1.OTLPLogExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/index.js
var require_platform11 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPLogExporter = void 0;
    var node_1 = require_node12();
    Object.defineProperty(exports2, "OTLPLogExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.OTLPLogExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/index.js
var require_src27 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPLogExporter = void 0;
    var platform_1 = require_platform11();
    Object.defineProperty(exports2, "OTLPLogExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.OTLPLogExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/version.js
var require_version7 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/version.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.VERSION = void 0;
    exports2.VERSION = "0.203.0";
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/OTLPMetricExporter.js
var require_OTLPMetricExporter3 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/OTLPMetricExporter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPMetricExporter = void 0;
    var exporter_metrics_otlp_http_1 = require_src18();
    var otlp_transformer_1 = require_src15();
    var version_1 = require_version7();
    var node_http_1 = (init_index_node_http(), __toCommonJS(index_node_http_exports));
    var OTLPMetricExporter2 = class extends exporter_metrics_otlp_http_1.OTLPMetricExporterBase {
      static {
        __name(this, "OTLPMetricExporter");
      }
      constructor(config) {
        super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config ?? {}, "METRICS", "v1/metrics", {
          "User-Agent": `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`,
          "Content-Type": "application/x-protobuf"
        }), otlp_transformer_1.ProtobufMetricsSerializer), config);
      }
    };
    exports2.OTLPMetricExporter = OTLPMetricExporter2;
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/index.js
var require_node13 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPMetricExporter = void 0;
    var OTLPMetricExporter_1 = require_OTLPMetricExporter3();
    Object.defineProperty(exports2, "OTLPMetricExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPMetricExporter_1.OTLPMetricExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/index.js
var require_platform12 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPMetricExporter = void 0;
    var node_1 = require_node13();
    Object.defineProperty(exports2, "OTLPMetricExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.OTLPMetricExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/index.js
var require_src28 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPMetricExporter = void 0;
    var platform_1 = require_platform12();
    Object.defineProperty(exports2, "OTLPMetricExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.OTLPMetricExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusSerializer.js
var require_PrometheusSerializer = __commonJS({
  "node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusSerializer.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PrometheusSerializer = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var sdk_metrics_1 = require_src14();
    var core_1 = require_src8();
    function escapeString(str2) {
      return str2.replace(/\\/g, "\\\\").replace(/\n/g, "\\n");
    }
    __name(escapeString, "escapeString");
    function escapeAttributeValue(str2 = "") {
      if (typeof str2 !== "string") {
        str2 = JSON.stringify(str2);
      }
      return escapeString(str2).replace(/"/g, '\\"');
    }
    __name(escapeAttributeValue, "escapeAttributeValue");
    var invalidCharacterRegex = /[^a-z0-9_]/gi;
    var multipleUnderscoreRegex = /_{2,}/g;
    function sanitizePrometheusMetricName(name3) {
      return name3.replace(invalidCharacterRegex, "_").replace(multipleUnderscoreRegex, "_");
    }
    __name(sanitizePrometheusMetricName, "sanitizePrometheusMetricName");
    function enforcePrometheusNamingConvention(name3, data) {
      if (!name3.endsWith("_total") && data.dataPointType === sdk_metrics_1.DataPointType.SUM && data.isMonotonic) {
        name3 = name3 + "_total";
      }
      return name3;
    }
    __name(enforcePrometheusNamingConvention, "enforcePrometheusNamingConvention");
    function valueString(value) {
      if (value === Infinity) {
        return "+Inf";
      } else if (value === -Infinity) {
        return "-Inf";
      } else {
        return `${value}`;
      }
    }
    __name(valueString, "valueString");
    function toPrometheusType(metricData) {
      switch (metricData.dataPointType) {
        case sdk_metrics_1.DataPointType.SUM:
          if (metricData.isMonotonic) {
            return "counter";
          }
          return "gauge";
        case sdk_metrics_1.DataPointType.GAUGE:
          return "gauge";
        case sdk_metrics_1.DataPointType.HISTOGRAM:
          return "histogram";
        default:
          return "untyped";
      }
    }
    __name(toPrometheusType, "toPrometheusType");
    function stringify5(metricName, attributes, value, timestamp, additionalAttributes) {
      let hasAttribute = false;
      let attributesStr = "";
      for (const [key, val] of Object.entries(attributes)) {
        const sanitizedAttributeName = sanitizePrometheusMetricName(key);
        hasAttribute = true;
        attributesStr += `${attributesStr.length > 0 ? "," : ""}${sanitizedAttributeName}="${escapeAttributeValue(val)}"`;
      }
      if (additionalAttributes) {
        for (const [key, val] of Object.entries(additionalAttributes)) {
          const sanitizedAttributeName = sanitizePrometheusMetricName(key);
          hasAttribute = true;
          attributesStr += `${attributesStr.length > 0 ? "," : ""}${sanitizedAttributeName}="${escapeAttributeValue(val)}"`;
        }
      }
      if (hasAttribute) {
        metricName += `{${attributesStr}}`;
      }
      return `${metricName} ${valueString(value)}${timestamp !== void 0 ? " " + String(timestamp) : ""}
`;
    }
    __name(stringify5, "stringify");
    var NO_REGISTERED_METRICS = "# no registered metrics";
    var PrometheusSerializer = class {
      static {
        __name(this, "PrometheusSerializer");
      }
      _prefix;
      _appendTimestamp;
      _additionalAttributes;
      _withResourceConstantLabels;
      constructor(prefix, appendTimestamp = false, withResourceConstantLabels) {
        if (prefix) {
          this._prefix = prefix + "_";
        }
        this._appendTimestamp = appendTimestamp;
        this._withResourceConstantLabels = withResourceConstantLabels;
      }
      serialize(resourceMetrics) {
        let str2 = "";
        this._additionalAttributes = this._filterResourceConstantLabels(resourceMetrics.resource.attributes, this._withResourceConstantLabels);
        for (const scopeMetrics of resourceMetrics.scopeMetrics) {
          str2 += this._serializeScopeMetrics(scopeMetrics);
        }
        if (str2 === "") {
          str2 += NO_REGISTERED_METRICS;
        }
        return this._serializeResource(resourceMetrics.resource) + str2;
      }
      _filterResourceConstantLabels(attributes, pattern) {
        if (pattern) {
          const filteredAttributes = {};
          for (const [key, value] of Object.entries(attributes)) {
            if (key.match(pattern)) {
              filteredAttributes[key] = value;
            }
          }
          return filteredAttributes;
        }
        return;
      }
      _serializeScopeMetrics(scopeMetrics) {
        let str2 = "";
        for (const metric of scopeMetrics.metrics) {
          str2 += this._serializeMetricData(metric) + "\n";
        }
        return str2;
      }
      _serializeMetricData(metricData) {
        let name3 = sanitizePrometheusMetricName(escapeString(metricData.descriptor.name));
        if (this._prefix) {
          name3 = `${this._prefix}${name3}`;
        }
        const dataPointType = metricData.dataPointType;
        name3 = enforcePrometheusNamingConvention(name3, metricData);
        const help = `# HELP ${name3} ${escapeString(metricData.descriptor.description || "description missing")}`;
        const unit = metricData.descriptor.unit ? `
# UNIT ${name3} ${escapeString(metricData.descriptor.unit)}` : "";
        const type = `# TYPE ${name3} ${toPrometheusType(metricData)}`;
        let results = "";
        switch (dataPointType) {
          case sdk_metrics_1.DataPointType.SUM:
          case sdk_metrics_1.DataPointType.GAUGE: {
            results = metricData.dataPoints.map((it) => this._serializeSingularDataPoint(name3, metricData, it)).join("");
            break;
          }
          case sdk_metrics_1.DataPointType.HISTOGRAM: {
            results = metricData.dataPoints.map((it) => this._serializeHistogramDataPoint(name3, metricData, it)).join("");
            break;
          }
          default: {
            api_1.diag.error(`Unrecognizable DataPointType: ${dataPointType} for metric "${name3}"`);
          }
        }
        return `${help}${unit}
${type}
${results}`.trim();
      }
      _serializeSingularDataPoint(name3, data, dataPoint) {
        let results = "";
        name3 = enforcePrometheusNamingConvention(name3, data);
        const { value, attributes } = dataPoint;
        const timestamp = (0, core_1.hrTimeToMilliseconds)(dataPoint.endTime);
        results += stringify5(name3, attributes, value, this._appendTimestamp ? timestamp : void 0, this._additionalAttributes);
        return results;
      }
      _serializeHistogramDataPoint(name3, data, dataPoint) {
        let results = "";
        name3 = enforcePrometheusNamingConvention(name3, data);
        const attributes = dataPoint.attributes;
        const histogram = dataPoint.value;
        const timestamp = (0, core_1.hrTimeToMilliseconds)(dataPoint.endTime);
        for (const key of ["count", "sum"]) {
          const value = histogram[key];
          if (value != null)
            results += stringify5(name3 + "_" + key, attributes, value, this._appendTimestamp ? timestamp : void 0, this._additionalAttributes);
        }
        let cumulativeSum = 0;
        const countEntries = histogram.buckets.counts.entries();
        let infiniteBoundaryDefined = false;
        for (const [idx, val] of countEntries) {
          cumulativeSum += val;
          const upperBound = histogram.buckets.boundaries[idx];
          if (upperBound === void 0 && infiniteBoundaryDefined) {
            break;
          }
          if (upperBound === Infinity) {
            infiniteBoundaryDefined = true;
          }
          results += stringify5(name3 + "_bucket", attributes, cumulativeSum, this._appendTimestamp ? timestamp : void 0, Object.assign({}, this._additionalAttributes ?? {}, {
            le: upperBound === void 0 || upperBound === Infinity ? "+Inf" : String(upperBound)
          }));
        }
        return results;
      }
      _serializeResource(resource) {
        const name3 = "target_info";
        const help = `# HELP ${name3} Target metadata`;
        const type = `# TYPE ${name3} gauge`;
        const results = stringify5(name3, resource.attributes, 1).trim();
        return `${help}
${type}
${results}
`;
      }
    };
    exports2.PrometheusSerializer = PrometheusSerializer;
  }
});

// node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusExporter.js
var require_PrometheusExporter = __commonJS({
  "node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusExporter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PrometheusExporter = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var sdk_metrics_1 = require_src14();
    var http_1 = __require("http");
    var PrometheusSerializer_1 = require_PrometheusSerializer();
    var url_1 = __require("url");
    var PrometheusExporter = class _PrometheusExporter extends sdk_metrics_1.MetricReader {
      static {
        __name(this, "PrometheusExporter");
      }
      static DEFAULT_OPTIONS = {
        host: void 0,
        port: 9464,
        endpoint: "/metrics",
        prefix: "",
        appendTimestamp: false,
        withResourceConstantLabels: void 0
      };
      _host;
      _port;
      _baseUrl;
      _endpoint;
      _server;
      _prefix;
      _appendTimestamp;
      _serializer;
      _startServerPromise;
      // This will be required when histogram is implemented. Leaving here so it is not forgotten
      // Histogram cannot have a attribute named 'le'
      // private static readonly RESERVED_HISTOGRAM_LABEL = 'le';
      /**
       * Constructor
       * @param config Exporter configuration
       * @param callback Callback to be called after a server was started
       */
      constructor(config = {}, callback = () => {
      }) {
        super({
          aggregationSelector: /* @__PURE__ */ __name((_instrumentType) => {
            return {
              type: sdk_metrics_1.AggregationType.DEFAULT
            };
          }, "aggregationSelector"),
          aggregationTemporalitySelector: /* @__PURE__ */ __name((_instrumentType) => sdk_metrics_1.AggregationTemporality.CUMULATIVE, "aggregationTemporalitySelector"),
          metricProducers: config.metricProducers
        });
        this._host = config.host || process.env.OTEL_EXPORTER_PROMETHEUS_HOST || _PrometheusExporter.DEFAULT_OPTIONS.host;
        this._port = config.port || Number(process.env.OTEL_EXPORTER_PROMETHEUS_PORT) || _PrometheusExporter.DEFAULT_OPTIONS.port;
        this._prefix = config.prefix || _PrometheusExporter.DEFAULT_OPTIONS.prefix;
        this._appendTimestamp = typeof config.appendTimestamp === "boolean" ? config.appendTimestamp : _PrometheusExporter.DEFAULT_OPTIONS.appendTimestamp;
        const _withResourceConstantLabels = config.withResourceConstantLabels || _PrometheusExporter.DEFAULT_OPTIONS.withResourceConstantLabels;
        this._server = (0, http_1.createServer)(this._requestHandler).unref();
        this._serializer = new PrometheusSerializer_1.PrometheusSerializer(this._prefix, this._appendTimestamp, _withResourceConstantLabels);
        this._baseUrl = `http://${this._host}:${this._port}/`;
        this._endpoint = (config.endpoint || _PrometheusExporter.DEFAULT_OPTIONS.endpoint).replace(/^([^/])/, "/$1");
        if (config.preventServerStart !== true) {
          this.startServer().then(callback, (err) => {
            api_1.diag.error(err);
            callback(err);
          });
        } else if (callback) {
          queueMicrotask(callback);
        }
      }
      async onForceFlush() {
      }
      /**
       * Shuts down the export server and clears the registry
       */
      onShutdown() {
        return this.stopServer();
      }
      /**
       * Stops the Prometheus export server
       */
      stopServer() {
        if (!this._server) {
          api_1.diag.debug("Prometheus stopServer() was called but server was never started.");
          return Promise.resolve();
        } else {
          return new Promise((resolve24) => {
            this._server.close((err) => {
              if (!err) {
                api_1.diag.debug("Prometheus exporter was stopped");
              } else {
                if (err.code !== "ERR_SERVER_NOT_RUNNING") {
                  (0, core_1.globalErrorHandler)(err);
                }
              }
              resolve24();
            });
          });
        }
      }
      /**
       * Starts the Prometheus export server
       */
      startServer() {
        this._startServerPromise ??= new Promise((resolve24, reject) => {
          this._server.once("error", reject);
          this._server.listen({
            port: this._port,
            host: this._host
          }, () => {
            api_1.diag.debug(`Prometheus exporter server started: ${this._host}:${this._port}/${this._endpoint}`);
            resolve24();
          });
        });
        return this._startServerPromise;
      }
      /**
       * Request handler that responds with the current state of metrics
       * @param _request Incoming HTTP request of server instance
       * @param response HTTP response object used to response to request
       */
      getMetricsRequestHandler(_request, response) {
        this._exportMetrics(response);
      }
      /**
       * Request handler used by http library to respond to incoming requests
       * for the current state of metrics by the Prometheus backend.
       *
       * @param request Incoming HTTP request to export server
       * @param response HTTP response object used to respond to request
       */
      _requestHandler = /* @__PURE__ */ __name((request4, response) => {
        if (request4.url != null && new url_1.URL(request4.url, this._baseUrl).pathname === this._endpoint) {
          this._exportMetrics(response);
        } else {
          this._notFound(response);
        }
      }, "_requestHandler");
      /**
       * Responds to incoming message with current state of all metrics.
       */
      _exportMetrics = /* @__PURE__ */ __name((response) => {
        response.statusCode = 200;
        response.setHeader("content-type", "text/plain");
        this.collect().then((collectionResult) => {
          const { resourceMetrics, errors } = collectionResult;
          if (errors.length) {
            api_1.diag.error("PrometheusExporter: metrics collection errors", ...errors);
          }
          response.end(this._serializer.serialize(resourceMetrics));
        }, (err) => {
          response.end(`# failed to export metrics: ${err}`);
        });
      }, "_exportMetrics");
      /**
       * Responds with 404 status code to all requests that do not match the configured endpoint.
       */
      _notFound = /* @__PURE__ */ __name((response) => {
        response.statusCode = 404;
        response.end();
      }, "_notFound");
    };
    exports2.PrometheusExporter = PrometheusExporter;
  }
});

// node_modules/@opentelemetry/exporter-prometheus/build/src/index.js
var require_src29 = __commonJS({
  "node_modules/@opentelemetry/exporter-prometheus/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PrometheusSerializer = exports2.PrometheusExporter = void 0;
    var PrometheusExporter_1 = require_PrometheusExporter();
    Object.defineProperty(exports2, "PrometheusExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return PrometheusExporter_1.PrometheusExporter;
    }, "get") });
    var PrometheusSerializer_1 = require_PrometheusSerializer();
    Object.defineProperty(exports2, "PrometheusSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return PrometheusSerializer_1.PrometheusSerializer;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/version.js
var require_version8 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/version.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.VERSION = void 0;
    exports2.VERSION = "0.203.0";
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/OTLPTraceExporter.js
var require_OTLPTraceExporter3 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/OTLPTraceExporter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPTraceExporter = void 0;
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var otlp_transformer_1 = require_src15();
    var version_1 = require_version8();
    var node_http_1 = (init_index_node_http(), __toCommonJS(index_node_http_exports));
    var OTLPTraceExporter2 = class extends otlp_exporter_base_1.OTLPExporterBase {
      static {
        __name(this, "OTLPTraceExporter");
      }
      constructor(config = {}) {
        super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, "TRACES", "v1/traces", {
          "User-Agent": `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`,
          "Content-Type": "application/x-protobuf"
        }), otlp_transformer_1.ProtobufTraceSerializer));
      }
    };
    exports2.OTLPTraceExporter = OTLPTraceExporter2;
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/index.js
var require_node14 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPTraceExporter = void 0;
    var OTLPTraceExporter_1 = require_OTLPTraceExporter3();
    Object.defineProperty(exports2, "OTLPTraceExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPTraceExporter_1.OTLPTraceExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/index.js
var require_platform13 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPTraceExporter = void 0;
    var node_1 = require_node14();
    Object.defineProperty(exports2, "OTLPTraceExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.OTLPTraceExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/index.js
var require_src30 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPTraceExporter = void 0;
    var platform_1 = require_platform13();
    Object.defineProperty(exports2, "OTLPTraceExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.OTLPTraceExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-zipkin/build/src/platform/node/util.js
var require_util14 = __commonJS({
  "node_modules/@opentelemetry/exporter-zipkin/build/src/platform/node/util.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.prepareSend = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var http4 = __require("http");
    var https4 = __require("https");
    function prepareSend(urlStr, headers) {
      const url2 = new URL(urlStr);
      const reqOpts = Object.assign({
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          ...headers
        }
      });
      return /* @__PURE__ */ __name(function send(zipkinSpans, done) {
        if (zipkinSpans.length === 0) {
          api_1.diag.debug("Zipkin send with empty spans");
          return done({ code: core_1.ExportResultCode.SUCCESS });
        }
        const { request: request4 } = url2.protocol === "http:" ? http4 : https4;
        const req = request4(url2, reqOpts, (res) => {
          let rawData = "";
          res.on("data", (chunk) => {
            rawData += chunk;
          });
          res.on("end", () => {
            const statusCode = res.statusCode || 0;
            api_1.diag.debug(`Zipkin response status code: ${statusCode}, body: ${rawData}`);
            if (statusCode < 400) {
              return done({ code: core_1.ExportResultCode.SUCCESS });
            } else {
              return done({
                code: core_1.ExportResultCode.FAILED,
                error: new Error(`Got unexpected status code from zipkin: ${statusCode}`)
              });
            }
          });
        });
        req.on("error", (error) => {
          return done({
            code: core_1.ExportResultCode.FAILED,
            error
          });
        });
        const payload = JSON.stringify(zipkinSpans);
        api_1.diag.debug(`Zipkin request payload: ${payload}`);
        req.write(payload, "utf8");
        req.end();
      }, "send");
    }
    __name(prepareSend, "prepareSend");
    exports2.prepareSend = prepareSend;
  }
});

// node_modules/@opentelemetry/exporter-zipkin/build/src/platform/node/index.js
var require_node15 = __commonJS({
  "node_modules/@opentelemetry/exporter-zipkin/build/src/platform/node/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.prepareSend = void 0;
    var util_1 = require_util14();
    Object.defineProperty(exports2, "prepareSend", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return util_1.prepareSend;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-zipkin/build/src/platform/index.js
var require_platform14 = __commonJS({
  "node_modules/@opentelemetry/exporter-zipkin/build/src/platform/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.prepareSend = void 0;
    var node_1 = require_node15();
    Object.defineProperty(exports2, "prepareSend", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.prepareSend;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-zipkin/build/src/types.js
var require_types6 = __commonJS({
  "node_modules/@opentelemetry/exporter-zipkin/build/src/types.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SpanKind = void 0;
    var SpanKind2;
    (function(SpanKind3) {
      SpanKind3["CLIENT"] = "CLIENT";
      SpanKind3["SERVER"] = "SERVER";
      SpanKind3["CONSUMER"] = "CONSUMER";
      SpanKind3["PRODUCER"] = "PRODUCER";
    })(SpanKind2 = exports2.SpanKind || (exports2.SpanKind = {}));
  }
});

// node_modules/@opentelemetry/exporter-zipkin/build/src/transform.js
var require_transform = __commonJS({
  "node_modules/@opentelemetry/exporter-zipkin/build/src/transform.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2._toZipkinAnnotations = exports2._toZipkinTags = exports2.toZipkinSpan = exports2.defaultStatusErrorTagName = exports2.defaultStatusCodeTagName = void 0;
    var api = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var zipkinTypes = require_types6();
    var ZIPKIN_SPAN_KIND_MAPPING = {
      [api.SpanKind.CLIENT]: zipkinTypes.SpanKind.CLIENT,
      [api.SpanKind.SERVER]: zipkinTypes.SpanKind.SERVER,
      [api.SpanKind.CONSUMER]: zipkinTypes.SpanKind.CONSUMER,
      [api.SpanKind.PRODUCER]: zipkinTypes.SpanKind.PRODUCER,
      // When absent, the span is local.
      [api.SpanKind.INTERNAL]: void 0
    };
    exports2.defaultStatusCodeTagName = "otel.status_code";
    exports2.defaultStatusErrorTagName = "error";
    function toZipkinSpan(span, serviceName, statusCodeTagName, statusErrorTagName) {
      const zipkinSpan = {
        traceId: span.spanContext().traceId,
        parentId: span.parentSpanContext?.spanId,
        name: span.name,
        id: span.spanContext().spanId,
        kind: ZIPKIN_SPAN_KIND_MAPPING[span.kind],
        timestamp: (0, core_1.hrTimeToMicroseconds)(span.startTime),
        duration: Math.round((0, core_1.hrTimeToMicroseconds)(span.duration)),
        localEndpoint: { serviceName },
        tags: _toZipkinTags(span, statusCodeTagName, statusErrorTagName),
        annotations: span.events.length ? _toZipkinAnnotations(span.events) : void 0
      };
      return zipkinSpan;
    }
    __name(toZipkinSpan, "toZipkinSpan");
    exports2.toZipkinSpan = toZipkinSpan;
    function _toZipkinTags({ attributes, resource, status, droppedAttributesCount, droppedEventsCount, droppedLinksCount }, statusCodeTagName, statusErrorTagName) {
      const tags = {};
      for (const key of Object.keys(attributes)) {
        tags[key] = String(attributes[key]);
      }
      if (status.code !== api.SpanStatusCode.UNSET) {
        tags[statusCodeTagName] = String(api.SpanStatusCode[status.code]);
      }
      if (status.code === api.SpanStatusCode.ERROR && status.message) {
        tags[statusErrorTagName] = status.message;
      }
      if (droppedAttributesCount) {
        tags["otel.dropped_attributes_count"] = String(droppedAttributesCount);
      }
      if (droppedEventsCount) {
        tags["otel.dropped_events_count"] = String(droppedEventsCount);
      }
      if (droppedLinksCount) {
        tags["otel.dropped_links_count"] = String(droppedLinksCount);
      }
      Object.keys(resource.attributes).forEach((name3) => tags[name3] = String(resource.attributes[name3]));
      return tags;
    }
    __name(_toZipkinTags, "_toZipkinTags");
    exports2._toZipkinTags = _toZipkinTags;
    function _toZipkinAnnotations(events) {
      return events.map((event) => ({
        timestamp: Math.round((0, core_1.hrTimeToMicroseconds)(event.time)),
        value: event.name
      }));
    }
    __name(_toZipkinAnnotations, "_toZipkinAnnotations");
    exports2._toZipkinAnnotations = _toZipkinAnnotations;
  }
});

// node_modules/@opentelemetry/exporter-zipkin/build/src/utils.js
var require_utils10 = __commonJS({
  "node_modules/@opentelemetry/exporter-zipkin/build/src/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.prepareGetHeaders = void 0;
    function prepareGetHeaders(getExportRequestHeaders) {
      return function() {
        return getExportRequestHeaders();
      };
    }
    __name(prepareGetHeaders, "prepareGetHeaders");
    exports2.prepareGetHeaders = prepareGetHeaders;
  }
});

// node_modules/@opentelemetry/exporter-zipkin/build/src/zipkin.js
var require_zipkin = __commonJS({
  "node_modules/@opentelemetry/exporter-zipkin/build/src/zipkin.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ZipkinExporter = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var index_1 = require_platform14();
    var transform_1 = require_transform();
    var semantic_conventions_1 = (init_esm(), __toCommonJS(esm_exports));
    var utils_1 = require_utils10();
    var ZipkinExporter = class {
      static {
        __name(this, "ZipkinExporter");
      }
      DEFAULT_SERVICE_NAME = "OpenTelemetry Service";
      _statusCodeTagName;
      _statusDescriptionTagName;
      _urlStr;
      _send;
      _getHeaders;
      _serviceName;
      _isShutdown;
      _sendingPromises = [];
      constructor(config = {}) {
        this._urlStr = config.url || ((0, core_1.getStringFromEnv)("OTEL_EXPORTER_ZIPKIN_ENDPOINT") ?? "http://localhost:9411/api/v2/spans");
        this._send = (0, index_1.prepareSend)(this._urlStr, config.headers);
        this._serviceName = config.serviceName;
        this._statusCodeTagName = config.statusCodeTagName || transform_1.defaultStatusCodeTagName;
        this._statusDescriptionTagName = config.statusDescriptionTagName || transform_1.defaultStatusErrorTagName;
        this._isShutdown = false;
        if (typeof config.getExportRequestHeaders === "function") {
          this._getHeaders = (0, utils_1.prepareGetHeaders)(config.getExportRequestHeaders);
        } else {
          this._beforeSend = function() {
          };
        }
      }
      /**
       * Export spans.
       */
      export(spans, resultCallback) {
        const serviceName = String(this._serviceName || spans[0].resource.attributes[semantic_conventions_1.ATTR_SERVICE_NAME] || this.DEFAULT_SERVICE_NAME);
        api_1.diag.debug("Zipkin exporter export");
        if (this._isShutdown) {
          setTimeout(() => resultCallback({
            code: core_1.ExportResultCode.FAILED,
            error: new Error("Exporter has been shutdown")
          }));
          return;
        }
        const promise = new Promise((resolve24) => {
          this._sendSpans(spans, serviceName, (result) => {
            resolve24();
            resultCallback(result);
          });
        });
        this._sendingPromises.push(promise);
        const popPromise = /* @__PURE__ */ __name(() => {
          const index = this._sendingPromises.indexOf(promise);
          this._sendingPromises.splice(index, 1);
        }, "popPromise");
        promise.then(popPromise, popPromise);
      }
      /**
       * Shutdown exporter. Noop operation in this exporter.
       */
      shutdown() {
        api_1.diag.debug("Zipkin exporter shutdown");
        this._isShutdown = true;
        return this.forceFlush();
      }
      /**
       * Exports any pending spans in exporter
       */
      forceFlush() {
        return new Promise((resolve24, reject) => {
          Promise.all(this._sendingPromises).then(() => {
            resolve24();
          }, reject);
        });
      }
      /**
       * if user defines getExportRequestHeaders in config then this will be called
       * every time before send, otherwise it will be replaced with noop in
       * constructor
       * @default noop
       */
      _beforeSend() {
        if (this._getHeaders) {
          this._send = (0, index_1.prepareSend)(this._urlStr, this._getHeaders());
        }
      }
      /**
       * Transform spans and sends to Zipkin service.
       */
      _sendSpans(spans, serviceName, done) {
        const zipkinSpans = spans.map((span) => (0, transform_1.toZipkinSpan)(span, String(span.attributes[semantic_conventions_1.ATTR_SERVICE_NAME] || span.resource.attributes[semantic_conventions_1.ATTR_SERVICE_NAME] || serviceName), this._statusCodeTagName, this._statusDescriptionTagName));
        this._beforeSend();
        return this._send(zipkinSpans, (result) => {
          if (done) {
            return done(result);
          }
        });
      }
    };
    exports2.ZipkinExporter = ZipkinExporter;
  }
});

// node_modules/@opentelemetry/exporter-zipkin/build/src/index.js
var require_src31 = __commonJS({
  "node_modules/@opentelemetry/exporter-zipkin/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ZipkinExporter = exports2.prepareSend = void 0;
    var platform_1 = require_platform14();
    Object.defineProperty(exports2, "prepareSend", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.prepareSend;
    }, "get") });
    var zipkin_1 = require_zipkin();
    Object.defineProperty(exports2, "ZipkinExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return zipkin_1.ZipkinExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/propagator-b3/build/src/common.js
var require_common4 = __commonJS({
  "node_modules/@opentelemetry/propagator-b3/build/src/common.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.B3_DEBUG_FLAG_KEY = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    exports2.B3_DEBUG_FLAG_KEY = (0, api_1.createContextKey)("OpenTelemetry Context Key B3 Debug Flag");
  }
});

// node_modules/@opentelemetry/propagator-b3/build/src/constants.js
var require_constants10 = __commonJS({
  "node_modules/@opentelemetry/propagator-b3/build/src/constants.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.X_B3_FLAGS = exports2.X_B3_PARENT_SPAN_ID = exports2.X_B3_SAMPLED = exports2.X_B3_SPAN_ID = exports2.X_B3_TRACE_ID = exports2.B3_CONTEXT_HEADER = void 0;
    exports2.B3_CONTEXT_HEADER = "b3";
    exports2.X_B3_TRACE_ID = "x-b3-traceid";
    exports2.X_B3_SPAN_ID = "x-b3-spanid";
    exports2.X_B3_SAMPLED = "x-b3-sampled";
    exports2.X_B3_PARENT_SPAN_ID = "x-b3-parentspanid";
    exports2.X_B3_FLAGS = "x-b3-flags";
  }
});

// node_modules/@opentelemetry/propagator-b3/build/src/B3MultiPropagator.js
var require_B3MultiPropagator = __commonJS({
  "node_modules/@opentelemetry/propagator-b3/build/src/B3MultiPropagator.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.B3MultiPropagator = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var common_1 = require_common4();
    var constants_1 = require_constants10();
    var VALID_SAMPLED_VALUES = /* @__PURE__ */ new Set([true, "true", "True", "1", 1]);
    var VALID_UNSAMPLED_VALUES = /* @__PURE__ */ new Set([false, "false", "False", "0", 0]);
    function isValidSampledValue(sampled) {
      return sampled === api_1.TraceFlags.SAMPLED || sampled === api_1.TraceFlags.NONE;
    }
    __name(isValidSampledValue, "isValidSampledValue");
    function parseHeader(header) {
      return Array.isArray(header) ? header[0] : header;
    }
    __name(parseHeader, "parseHeader");
    function getHeaderValue(carrier, getter, key) {
      const header = getter.get(carrier, key);
      return parseHeader(header);
    }
    __name(getHeaderValue, "getHeaderValue");
    function getTraceId(carrier, getter) {
      const traceId = getHeaderValue(carrier, getter, constants_1.X_B3_TRACE_ID);
      if (typeof traceId === "string") {
        return traceId.padStart(32, "0");
      }
      return "";
    }
    __name(getTraceId, "getTraceId");
    function getSpanId(carrier, getter) {
      const spanId = getHeaderValue(carrier, getter, constants_1.X_B3_SPAN_ID);
      if (typeof spanId === "string") {
        return spanId;
      }
      return "";
    }
    __name(getSpanId, "getSpanId");
    function getDebug(carrier, getter) {
      const debug2 = getHeaderValue(carrier, getter, constants_1.X_B3_FLAGS);
      return debug2 === "1" ? "1" : void 0;
    }
    __name(getDebug, "getDebug");
    function getTraceFlags(carrier, getter) {
      const traceFlags = getHeaderValue(carrier, getter, constants_1.X_B3_SAMPLED);
      const debug2 = getDebug(carrier, getter);
      if (debug2 === "1" || VALID_SAMPLED_VALUES.has(traceFlags)) {
        return api_1.TraceFlags.SAMPLED;
      }
      if (traceFlags === void 0 || VALID_UNSAMPLED_VALUES.has(traceFlags)) {
        return api_1.TraceFlags.NONE;
      }
      return;
    }
    __name(getTraceFlags, "getTraceFlags");
    var B3MultiPropagator = class {
      static {
        __name(this, "B3MultiPropagator");
      }
      inject(context2, carrier, setter) {
        const spanContext = api_1.trace.getSpanContext(context2);
        if (!spanContext || !(0, api_1.isSpanContextValid)(spanContext) || (0, core_1.isTracingSuppressed)(context2))
          return;
        const debug2 = context2.getValue(common_1.B3_DEBUG_FLAG_KEY);
        setter.set(carrier, constants_1.X_B3_TRACE_ID, spanContext.traceId);
        setter.set(carrier, constants_1.X_B3_SPAN_ID, spanContext.spanId);
        if (debug2 === "1") {
          setter.set(carrier, constants_1.X_B3_FLAGS, debug2);
        } else if (spanContext.traceFlags !== void 0) {
          setter.set(carrier, constants_1.X_B3_SAMPLED, (api_1.TraceFlags.SAMPLED & spanContext.traceFlags) === api_1.TraceFlags.SAMPLED ? "1" : "0");
        }
      }
      extract(context2, carrier, getter) {
        const traceId = getTraceId(carrier, getter);
        const spanId = getSpanId(carrier, getter);
        const traceFlags = getTraceFlags(carrier, getter);
        const debug2 = getDebug(carrier, getter);
        if ((0, api_1.isValidTraceId)(traceId) && (0, api_1.isValidSpanId)(spanId) && isValidSampledValue(traceFlags)) {
          context2 = context2.setValue(common_1.B3_DEBUG_FLAG_KEY, debug2);
          return api_1.trace.setSpanContext(context2, {
            traceId,
            spanId,
            isRemote: true,
            traceFlags
          });
        }
        return context2;
      }
      fields() {
        return [
          constants_1.X_B3_TRACE_ID,
          constants_1.X_B3_SPAN_ID,
          constants_1.X_B3_FLAGS,
          constants_1.X_B3_SAMPLED,
          constants_1.X_B3_PARENT_SPAN_ID
        ];
      }
    };
    exports2.B3MultiPropagator = B3MultiPropagator;
  }
});

// node_modules/@opentelemetry/propagator-b3/build/src/B3SinglePropagator.js
var require_B3SinglePropagator = __commonJS({
  "node_modules/@opentelemetry/propagator-b3/build/src/B3SinglePropagator.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.B3SinglePropagator = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var common_1 = require_common4();
    var constants_1 = require_constants10();
    var B3_CONTEXT_REGEX = /((?:[0-9a-f]{16}){1,2})-([0-9a-f]{16})(?:-([01d](?![0-9a-f])))?(?:-([0-9a-f]{16}))?/;
    var PADDING = "0".repeat(16);
    var SAMPLED_VALUES = /* @__PURE__ */ new Set(["d", "1"]);
    var DEBUG_STATE = "d";
    function convertToTraceId128(traceId) {
      return traceId.length === 32 ? traceId : `${PADDING}${traceId}`;
    }
    __name(convertToTraceId128, "convertToTraceId128");
    function convertToTraceFlags(samplingState) {
      if (samplingState && SAMPLED_VALUES.has(samplingState)) {
        return api_1.TraceFlags.SAMPLED;
      }
      return api_1.TraceFlags.NONE;
    }
    __name(convertToTraceFlags, "convertToTraceFlags");
    var B3SinglePropagator = class {
      static {
        __name(this, "B3SinglePropagator");
      }
      inject(context2, carrier, setter) {
        const spanContext = api_1.trace.getSpanContext(context2);
        if (!spanContext || !(0, api_1.isSpanContextValid)(spanContext) || (0, core_1.isTracingSuppressed)(context2))
          return;
        const samplingState = context2.getValue(common_1.B3_DEBUG_FLAG_KEY) || spanContext.traceFlags & 1;
        const value = `${spanContext.traceId}-${spanContext.spanId}-${samplingState}`;
        setter.set(carrier, constants_1.B3_CONTEXT_HEADER, value);
      }
      extract(context2, carrier, getter) {
        const header = getter.get(carrier, constants_1.B3_CONTEXT_HEADER);
        const b3Context = Array.isArray(header) ? header[0] : header;
        if (typeof b3Context !== "string")
          return context2;
        const match2 = b3Context.match(B3_CONTEXT_REGEX);
        if (!match2)
          return context2;
        const [, extractedTraceId, spanId, samplingState] = match2;
        const traceId = convertToTraceId128(extractedTraceId);
        if (!(0, api_1.isValidTraceId)(traceId) || !(0, api_1.isValidSpanId)(spanId))
          return context2;
        const traceFlags = convertToTraceFlags(samplingState);
        if (samplingState === DEBUG_STATE) {
          context2 = context2.setValue(common_1.B3_DEBUG_FLAG_KEY, samplingState);
        }
        return api_1.trace.setSpanContext(context2, {
          traceId,
          spanId,
          isRemote: true,
          traceFlags
        });
      }
      fields() {
        return [constants_1.B3_CONTEXT_HEADER];
      }
    };
    exports2.B3SinglePropagator = B3SinglePropagator;
  }
});

// node_modules/@opentelemetry/propagator-b3/build/src/types.js
var require_types7 = __commonJS({
  "node_modules/@opentelemetry/propagator-b3/build/src/types.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.B3InjectEncoding = void 0;
    var B3InjectEncoding;
    (function(B3InjectEncoding2) {
      B3InjectEncoding2[B3InjectEncoding2["SINGLE_HEADER"] = 0] = "SINGLE_HEADER";
      B3InjectEncoding2[B3InjectEncoding2["MULTI_HEADER"] = 1] = "MULTI_HEADER";
    })(B3InjectEncoding = exports2.B3InjectEncoding || (exports2.B3InjectEncoding = {}));
  }
});

// node_modules/@opentelemetry/propagator-b3/build/src/B3Propagator.js
var require_B3Propagator = __commonJS({
  "node_modules/@opentelemetry/propagator-b3/build/src/B3Propagator.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.B3Propagator = void 0;
    var core_1 = require_src8();
    var B3MultiPropagator_1 = require_B3MultiPropagator();
    var B3SinglePropagator_1 = require_B3SinglePropagator();
    var constants_1 = require_constants10();
    var types_1 = require_types7();
    var B3Propagator = class {
      static {
        __name(this, "B3Propagator");
      }
      _b3MultiPropagator = new B3MultiPropagator_1.B3MultiPropagator();
      _b3SinglePropagator = new B3SinglePropagator_1.B3SinglePropagator();
      _inject;
      _fields;
      constructor(config = {}) {
        if (config.injectEncoding === types_1.B3InjectEncoding.MULTI_HEADER) {
          this._inject = this._b3MultiPropagator.inject;
          this._fields = this._b3MultiPropagator.fields();
        } else {
          this._inject = this._b3SinglePropagator.inject;
          this._fields = this._b3SinglePropagator.fields();
        }
      }
      inject(context2, carrier, setter) {
        if ((0, core_1.isTracingSuppressed)(context2)) {
          return;
        }
        this._inject(context2, carrier, setter);
      }
      extract(context2, carrier, getter) {
        const header = getter.get(carrier, constants_1.B3_CONTEXT_HEADER);
        const b3Context = Array.isArray(header) ? header[0] : header;
        if (b3Context) {
          return this._b3SinglePropagator.extract(context2, carrier, getter);
        } else {
          return this._b3MultiPropagator.extract(context2, carrier, getter);
        }
      }
      fields() {
        return this._fields;
      }
    };
    exports2.B3Propagator = B3Propagator;
  }
});

// node_modules/@opentelemetry/propagator-b3/build/src/index.js
var require_src32 = __commonJS({
  "node_modules/@opentelemetry/propagator-b3/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.B3InjectEncoding = exports2.X_B3_TRACE_ID = exports2.X_B3_SPAN_ID = exports2.X_B3_SAMPLED = exports2.X_B3_PARENT_SPAN_ID = exports2.X_B3_FLAGS = exports2.B3_CONTEXT_HEADER = exports2.B3Propagator = void 0;
    var B3Propagator_1 = require_B3Propagator();
    Object.defineProperty(exports2, "B3Propagator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return B3Propagator_1.B3Propagator;
    }, "get") });
    var constants_1 = require_constants10();
    Object.defineProperty(exports2, "B3_CONTEXT_HEADER", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return constants_1.B3_CONTEXT_HEADER;
    }, "get") });
    Object.defineProperty(exports2, "X_B3_FLAGS", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return constants_1.X_B3_FLAGS;
    }, "get") });
    Object.defineProperty(exports2, "X_B3_PARENT_SPAN_ID", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return constants_1.X_B3_PARENT_SPAN_ID;
    }, "get") });
    Object.defineProperty(exports2, "X_B3_SAMPLED", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return constants_1.X_B3_SAMPLED;
    }, "get") });
    Object.defineProperty(exports2, "X_B3_SPAN_ID", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return constants_1.X_B3_SPAN_ID;
    }, "get") });
    Object.defineProperty(exports2, "X_B3_TRACE_ID", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return constants_1.X_B3_TRACE_ID;
    }, "get") });
    var types_1 = require_types7();
    Object.defineProperty(exports2, "B3InjectEncoding", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return types_1.B3InjectEncoding;
    }, "get") });
  }
});

// node_modules/@opentelemetry/propagator-jaeger/build/src/JaegerPropagator.js
var require_JaegerPropagator = __commonJS({
  "node_modules/@opentelemetry/propagator-jaeger/build/src/JaegerPropagator.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.JaegerPropagator = exports2.UBER_BAGGAGE_HEADER_PREFIX = exports2.UBER_TRACE_ID_HEADER = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    exports2.UBER_TRACE_ID_HEADER = "uber-trace-id";
    exports2.UBER_BAGGAGE_HEADER_PREFIX = "uberctx";
    var JaegerPropagator = class {
      static {
        __name(this, "JaegerPropagator");
      }
      _jaegerTraceHeader;
      _jaegerBaggageHeaderPrefix;
      constructor(config) {
        if (typeof config === "string") {
          this._jaegerTraceHeader = config;
          this._jaegerBaggageHeaderPrefix = exports2.UBER_BAGGAGE_HEADER_PREFIX;
        } else {
          this._jaegerTraceHeader = config?.customTraceHeader || exports2.UBER_TRACE_ID_HEADER;
          this._jaegerBaggageHeaderPrefix = config?.customBaggageHeaderPrefix || exports2.UBER_BAGGAGE_HEADER_PREFIX;
        }
      }
      inject(context2, carrier, setter) {
        const spanContext = api_1.trace.getSpanContext(context2);
        const baggage = api_1.propagation.getBaggage(context2);
        if (spanContext && (0, core_1.isTracingSuppressed)(context2) === false) {
          const traceFlags = `0${(spanContext.traceFlags || api_1.TraceFlags.NONE).toString(16)}`;
          setter.set(carrier, this._jaegerTraceHeader, `${spanContext.traceId}:${spanContext.spanId}:0:${traceFlags}`);
        }
        if (baggage) {
          for (const [key, entry] of baggage.getAllEntries()) {
            setter.set(carrier, `${this._jaegerBaggageHeaderPrefix}-${key}`, encodeURIComponent(entry.value));
          }
        }
      }
      extract(context2, carrier, getter) {
        const uberTraceIdHeader = getter.get(carrier, this._jaegerTraceHeader);
        const uberTraceId = Array.isArray(uberTraceIdHeader) ? uberTraceIdHeader[0] : uberTraceIdHeader;
        const baggageValues = getter.keys(carrier).filter((key) => key.startsWith(`${this._jaegerBaggageHeaderPrefix}-`)).map((key) => {
          const value = getter.get(carrier, key);
          return {
            key: key.substring(this._jaegerBaggageHeaderPrefix.length + 1),
            value: Array.isArray(value) ? value[0] : value
          };
        });
        let newContext = context2;
        if (typeof uberTraceId === "string") {
          const spanContext = deserializeSpanContext(uberTraceId);
          if (spanContext) {
            newContext = api_1.trace.setSpanContext(newContext, spanContext);
          }
        }
        if (baggageValues.length === 0)
          return newContext;
        let currentBaggage = api_1.propagation.getBaggage(context2) ?? api_1.propagation.createBaggage();
        for (const baggageEntry of baggageValues) {
          if (baggageEntry.value === void 0)
            continue;
          currentBaggage = currentBaggage.setEntry(baggageEntry.key, {
            value: decodeURIComponent(baggageEntry.value)
          });
        }
        newContext = api_1.propagation.setBaggage(newContext, currentBaggage);
        return newContext;
      }
      fields() {
        return [this._jaegerTraceHeader];
      }
    };
    exports2.JaegerPropagator = JaegerPropagator;
    var VALID_HEX_RE = /^[0-9a-f]{1,2}$/i;
    function deserializeSpanContext(serializedString) {
      const headers = decodeURIComponent(serializedString).split(":");
      if (headers.length !== 4) {
        return null;
      }
      const [_traceId, _spanId, , flags] = headers;
      const traceId = _traceId.padStart(32, "0");
      const spanId = _spanId.padStart(16, "0");
      const traceFlags = VALID_HEX_RE.test(flags) ? parseInt(flags, 16) & 1 : 1;
      return { traceId, spanId, isRemote: true, traceFlags };
    }
    __name(deserializeSpanContext, "deserializeSpanContext");
  }
});

// node_modules/@opentelemetry/propagator-jaeger/build/src/index.js
var require_src33 = __commonJS({
  "node_modules/@opentelemetry/propagator-jaeger/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.UBER_TRACE_ID_HEADER = exports2.UBER_BAGGAGE_HEADER_PREFIX = exports2.JaegerPropagator = void 0;
    var JaegerPropagator_1 = require_JaegerPropagator();
    Object.defineProperty(exports2, "JaegerPropagator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return JaegerPropagator_1.JaegerPropagator;
    }, "get") });
    Object.defineProperty(exports2, "UBER_BAGGAGE_HEADER_PREFIX", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return JaegerPropagator_1.UBER_BAGGAGE_HEADER_PREFIX;
    }, "get") });
    Object.defineProperty(exports2, "UBER_TRACE_ID_HEADER", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return JaegerPropagator_1.UBER_TRACE_ID_HEADER;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-node/build/src/utils.js
var require_utils11 = __commonJS({
  "node_modules/@opentelemetry/sdk-node/build/src/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getPropagatorFromEnv = exports2.getSpanProcessorsFromEnv = exports2.getOtlpProtocolFromEnv = exports2.filterBlanksAndNulls = exports2.getResourceDetectorsFromEnv = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var exporter_trace_otlp_proto_1 = require_src30();
    var exporter_trace_otlp_http_1 = require_src20();
    var exporter_trace_otlp_grpc_1 = require_src16();
    var exporter_zipkin_1 = require_src31();
    var resources_1 = require_src13();
    var sdk_trace_base_1 = require_src24();
    var propagator_b3_1 = require_src32();
    var propagator_jaeger_1 = require_src33();
    var RESOURCE_DETECTOR_ENVIRONMENT = "env";
    var RESOURCE_DETECTOR_HOST = "host";
    var RESOURCE_DETECTOR_OS = "os";
    var RESOURCE_DETECTOR_PROCESS = "process";
    var RESOURCE_DETECTOR_SERVICE_INSTANCE_ID = "serviceinstance";
    function getResourceDetectorsFromEnv() {
      const resourceDetectors = /* @__PURE__ */ new Map([
        [RESOURCE_DETECTOR_ENVIRONMENT, resources_1.envDetector],
        [RESOURCE_DETECTOR_HOST, resources_1.hostDetector],
        [RESOURCE_DETECTOR_OS, resources_1.osDetector],
        [RESOURCE_DETECTOR_SERVICE_INSTANCE_ID, resources_1.serviceInstanceIdDetector],
        [RESOURCE_DETECTOR_PROCESS, resources_1.processDetector]
      ]);
      const resourceDetectorsFromEnv = (0, core_1.getStringListFromEnv)("OTEL_NODE_RESOURCE_DETECTORS") ?? ["all"];
      if (resourceDetectorsFromEnv.includes("all")) {
        return [...resourceDetectors.values()].flat();
      }
      if (resourceDetectorsFromEnv.includes("none")) {
        return [];
      }
      return resourceDetectorsFromEnv.flatMap((detector) => {
        const resourceDetector = resourceDetectors.get(detector);
        if (!resourceDetector) {
          api_1.diag.warn(`Invalid resource detector "${detector}" specified in the environment variable OTEL_NODE_RESOURCE_DETECTORS`);
        }
        return resourceDetector || [];
      });
    }
    __name(getResourceDetectorsFromEnv, "getResourceDetectorsFromEnv");
    exports2.getResourceDetectorsFromEnv = getResourceDetectorsFromEnv;
    function filterBlanksAndNulls(list3) {
      return list3.map((item) => item.trim()).filter((s2) => s2 !== "null" && s2 !== "");
    }
    __name(filterBlanksAndNulls, "filterBlanksAndNulls");
    exports2.filterBlanksAndNulls = filterBlanksAndNulls;
    function getOtlpProtocolFromEnv() {
      return (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_PROTOCOL") ?? "http/protobuf";
    }
    __name(getOtlpProtocolFromEnv, "getOtlpProtocolFromEnv");
    exports2.getOtlpProtocolFromEnv = getOtlpProtocolFromEnv;
    function getOtlpExporterFromEnv() {
      const protocol = getOtlpProtocolFromEnv();
      switch (protocol) {
        case "grpc":
          return new exporter_trace_otlp_grpc_1.OTLPTraceExporter();
        case "http/json":
          return new exporter_trace_otlp_http_1.OTLPTraceExporter();
        case "http/protobuf":
          return new exporter_trace_otlp_proto_1.OTLPTraceExporter();
        default:
          api_1.diag.warn(`Unsupported OTLP traces protocol: ${protocol}. Using http/protobuf.`);
          return new exporter_trace_otlp_proto_1.OTLPTraceExporter();
      }
    }
    __name(getOtlpExporterFromEnv, "getOtlpExporterFromEnv");
    function getJaegerExporter() {
      try {
        const { JaegerExporter } = __require("@opentelemetry/exporter-jaeger");
        return new JaegerExporter();
      } catch (e2) {
        throw new Error(`Could not instantiate JaegerExporter. This could be due to the JaegerExporter's lack of support for bundling. If possible, use @opentelemetry/exporter-trace-otlp-proto instead. Original Error: ${e2}`);
      }
    }
    __name(getJaegerExporter, "getJaegerExporter");
    function getSpanProcessorsFromEnv() {
      const exportersMap = /* @__PURE__ */ new Map([
        ["otlp", () => getOtlpExporterFromEnv()],
        ["zipkin", () => new exporter_zipkin_1.ZipkinExporter()],
        ["console", () => new sdk_trace_base_1.ConsoleSpanExporter()],
        ["jaeger", () => getJaegerExporter()]
      ]);
      const exporters = [];
      const processors = [];
      let traceExportersList = filterBlanksAndNulls(Array.from(new Set((0, core_1.getStringListFromEnv)("OTEL_TRACES_EXPORTER"))));
      if (traceExportersList[0] === "none") {
        api_1.diag.warn('OTEL_TRACES_EXPORTER contains "none". SDK will not be initialized.');
        return [];
      }
      if (traceExportersList.length === 0) {
        api_1.diag.debug("OTEL_TRACES_EXPORTER is empty. Using default otlp exporter.");
        traceExportersList = ["otlp"];
      } else if (traceExportersList.length > 1 && traceExportersList.includes("none")) {
        api_1.diag.warn('OTEL_TRACES_EXPORTER contains "none" along with other exporters. Using default otlp exporter.');
        traceExportersList = ["otlp"];
      }
      for (const name3 of traceExportersList) {
        const exporter = exportersMap.get(name3)?.();
        if (exporter) {
          exporters.push(exporter);
        } else {
          api_1.diag.warn(`Unrecognized OTEL_TRACES_EXPORTER value: ${name3}.`);
        }
      }
      for (const exp of exporters) {
        if (exp instanceof sdk_trace_base_1.ConsoleSpanExporter) {
          processors.push(new sdk_trace_base_1.SimpleSpanProcessor(exp));
        } else {
          processors.push(new sdk_trace_base_1.BatchSpanProcessor(exp));
        }
      }
      if (exporters.length === 0) {
        api_1.diag.warn("Unable to set up trace exporter(s) due to invalid exporter and/or protocol values.");
      }
      return processors;
    }
    __name(getSpanProcessorsFromEnv, "getSpanProcessorsFromEnv");
    exports2.getSpanProcessorsFromEnv = getSpanProcessorsFromEnv;
    function getPropagatorFromEnv() {
      const propagatorsEnvVarValue = (0, core_1.getStringListFromEnv)("OTEL_PROPAGATORS");
      if (propagatorsEnvVarValue == null) {
        return void 0;
      }
      const propagatorsFactory = /* @__PURE__ */ new Map([
        ["tracecontext", () => new core_1.W3CTraceContextPropagator()],
        ["baggage", () => new core_1.W3CBaggagePropagator()],
        ["b3", () => new propagator_b3_1.B3Propagator()],
        [
          "b3multi",
          () => new propagator_b3_1.B3Propagator({ injectEncoding: propagator_b3_1.B3InjectEncoding.MULTI_HEADER })
        ],
        ["jaeger", () => new propagator_jaeger_1.JaegerPropagator()]
      ]);
      const uniquePropagatorNames = Array.from(new Set(propagatorsEnvVarValue));
      const propagators = uniquePropagatorNames.map((name3) => {
        const propagator = propagatorsFactory.get(name3)?.();
        if (!propagator) {
          api_1.diag.warn(`Propagator "${name3}" requested through environment variable is unavailable.`);
          return void 0;
        }
        return propagator;
      });
      const validPropagators = propagators.reduce((list3, item) => {
        if (item) {
          list3.push(item);
        }
        return list3;
      }, []);
      if (validPropagators.length === 0) {
        return null;
      } else if (uniquePropagatorNames.length === 1) {
        return validPropagators[0];
      } else {
        return new core_1.CompositePropagator({
          propagators: validPropagators
        });
      }
    }
    __name(getPropagatorFromEnv, "getPropagatorFromEnv");
    exports2.getPropagatorFromEnv = getPropagatorFromEnv;
  }
});

// node_modules/@opentelemetry/sdk-node/build/src/sdk.js
var require_sdk = __commonJS({
  "node_modules/@opentelemetry/sdk-node/build/src/sdk.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NodeSDK = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var api_logs_1 = require_src7();
    var instrumentation_1 = require_src26();
    var resources_1 = require_src13();
    var sdk_logs_1 = require_src22();
    var exporter_logs_otlp_http_1 = require_src21();
    var exporter_logs_otlp_grpc_1 = require_src17();
    var exporter_logs_otlp_proto_1 = require_src27();
    var exporter_metrics_otlp_grpc_1 = require_src19();
    var exporter_metrics_otlp_proto_1 = require_src28();
    var exporter_metrics_otlp_http_1 = require_src18();
    var exporter_prometheus_1 = require_src29();
    var sdk_metrics_1 = require_src14();
    var sdk_trace_base_1 = require_src24();
    var sdk_trace_node_1 = require_src25();
    var semantic_conventions_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src8();
    var utils_1 = require_utils11();
    function getValueInMillis(envName, defaultValue) {
      return parseInt(process.env[envName] || "") || defaultValue;
    }
    __name(getValueInMillis, "getValueInMillis");
    function configureMetricProviderFromEnv() {
      const metricReaders = [];
      const enabledExporters = (0, core_1.getStringListFromEnv)("OTEL_METRICS_EXPORTER");
      if (!enabledExporters) {
        return metricReaders;
      }
      if (enabledExporters.length === 0) {
        api_1.diag.debug("OTEL_METRICS_EXPORTER is empty. Using default otlp exporter.");
      }
      if (enabledExporters.includes("none")) {
        api_1.diag.info(`OTEL_METRICS_EXPORTER contains "none". Metric provider will not be initialized.`);
        return metricReaders;
      }
      enabledExporters.forEach((exporter) => {
        if (exporter === "otlp") {
          const protocol = process.env.OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?.trim() || process.env.OTEL_EXPORTER_OTLP_PROTOCOL?.trim();
          const exportIntervalMillis = getValueInMillis("OTEL_METRIC_EXPORT_INTERVAL", 6e4);
          const exportTimeoutMillis = getValueInMillis("OTEL_METRIC_EXPORT_TIMEOUT", 3e4);
          switch (protocol) {
            case "grpc":
              metricReaders.push(new sdk_metrics_1.PeriodicExportingMetricReader({
                exporter: new exporter_metrics_otlp_grpc_1.OTLPMetricExporter(),
                exportIntervalMillis,
                exportTimeoutMillis
              }));
              break;
            case "http/json":
              metricReaders.push(new sdk_metrics_1.PeriodicExportingMetricReader({
                exporter: new exporter_metrics_otlp_http_1.OTLPMetricExporter(),
                exportIntervalMillis,
                exportTimeoutMillis
              }));
              break;
            case "http/protobuf":
              metricReaders.push(new sdk_metrics_1.PeriodicExportingMetricReader({
                exporter: new exporter_metrics_otlp_proto_1.OTLPMetricExporter(),
                exportIntervalMillis,
                exportTimeoutMillis
              }));
              break;
            default:
              api_1.diag.warn(`Unsupported OTLP metrics protocol: "${protocol}". Using http/protobuf.`);
              metricReaders.push(new sdk_metrics_1.PeriodicExportingMetricReader({
                exporter: new exporter_metrics_otlp_proto_1.OTLPMetricExporter(),
                exportIntervalMillis,
                exportTimeoutMillis
              }));
          }
        } else if (exporter === "console") {
          metricReaders.push(new sdk_metrics_1.PeriodicExportingMetricReader({
            exporter: new sdk_metrics_1.ConsoleMetricExporter()
          }));
        } else if (exporter === "prometheus") {
          metricReaders.push(new exporter_prometheus_1.PrometheusExporter());
        } else {
          api_1.diag.warn(`Unsupported OTEL_METRICS_EXPORTER value: "${exporter}". Supported values are: otlp, console, prometheus, none.`);
        }
      });
      return metricReaders;
    }
    __name(configureMetricProviderFromEnv, "configureMetricProviderFromEnv");
    var NodeSDK2 = class {
      static {
        __name(this, "NodeSDK");
      }
      _tracerProviderConfig;
      _loggerProviderConfig;
      _meterProviderConfig;
      _instrumentations;
      _resource;
      _resourceDetectors;
      _autoDetectResources;
      _tracerProvider;
      _loggerProvider;
      _meterProvider;
      _serviceName;
      _configuration;
      _disabled;
      /**
       * Create a new NodeJS SDK instance
       */
      constructor(configuration = {}) {
        if ((0, core_1.getBooleanFromEnv)("OTEL_SDK_DISABLED")) {
          this._disabled = true;
        }
        const logLevel = (0, core_1.getStringFromEnv)("OTEL_LOG_LEVEL");
        if (logLevel != null) {
          api_1.diag.setLogger(new api_1.DiagConsoleLogger(), {
            logLevel: (0, core_1.diagLogLevelFromString)(logLevel)
          });
        }
        this._configuration = configuration;
        this._resource = configuration.resource ?? (0, resources_1.defaultResource)();
        this._autoDetectResources = configuration.autoDetectResources ?? true;
        if (!this._autoDetectResources) {
          this._resourceDetectors = [];
        } else if (configuration.resourceDetectors != null) {
          this._resourceDetectors = configuration.resourceDetectors;
        } else if ((0, core_1.getStringFromEnv)("OTEL_NODE_RESOURCE_DETECTORS")) {
          this._resourceDetectors = (0, utils_1.getResourceDetectorsFromEnv)();
        } else {
          this._resourceDetectors = [resources_1.envDetector, resources_1.processDetector, resources_1.hostDetector];
        }
        this._serviceName = configuration.serviceName;
        if (configuration.traceExporter || configuration.spanProcessor || configuration.spanProcessors) {
          const tracerProviderConfig = {};
          if (configuration.sampler) {
            tracerProviderConfig.sampler = configuration.sampler;
          }
          if (configuration.spanLimits) {
            tracerProviderConfig.spanLimits = configuration.spanLimits;
          }
          if (configuration.idGenerator) {
            tracerProviderConfig.idGenerator = configuration.idGenerator;
          }
          if (configuration.spanProcessor) {
            api_1.diag.warn("The 'spanProcessor' option is deprecated. Please use 'spanProcessors' instead.");
          }
          const spanProcessor = configuration.spanProcessor ?? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
          new sdk_trace_base_1.BatchSpanProcessor(configuration.traceExporter);
          const spanProcessors = configuration.spanProcessors ?? [spanProcessor];
          this._tracerProviderConfig = {
            tracerConfig: tracerProviderConfig,
            spanProcessors,
            contextManager: configuration.contextManager,
            textMapPropagator: configuration.textMapPropagator
          };
        }
        if (configuration.logRecordProcessors) {
          this._loggerProviderConfig = {
            logRecordProcessors: configuration.logRecordProcessors
          };
        } else if (configuration.logRecordProcessor) {
          this._loggerProviderConfig = {
            logRecordProcessors: [configuration.logRecordProcessor]
          };
          api_1.diag.warn("The 'logRecordProcessor' option is deprecated. Please use 'logRecordProcessors' instead.");
        } else {
          this.configureLoggerProviderFromEnv();
        }
        if (configuration.metricReader || configuration.views) {
          const meterProviderConfig = {};
          if (configuration.metricReader) {
            meterProviderConfig.reader = configuration.metricReader;
          }
          if (configuration.views) {
            meterProviderConfig.views = configuration.views;
          }
          this._meterProviderConfig = meterProviderConfig;
        }
        this._instrumentations = configuration.instrumentations?.flat() ?? [];
      }
      /**
       * Call this method to construct SDK components and register them with the OpenTelemetry API.
       */
      start() {
        if (this._disabled) {
          return;
        }
        (0, instrumentation_1.registerInstrumentations)({
          instrumentations: this._instrumentations
        });
        if (this._autoDetectResources) {
          const internalConfig = {
            detectors: this._resourceDetectors
          };
          this._resource = this._resource.merge((0, resources_1.detectResources)(internalConfig));
        }
        this._resource = this._serviceName === void 0 ? this._resource : this._resource.merge((0, resources_1.resourceFromAttributes)({
          [semantic_conventions_1.ATTR_SERVICE_NAME]: this._serviceName
        }));
        const spanProcessors = this._tracerProviderConfig ? this._tracerProviderConfig.spanProcessors : (0, utils_1.getSpanProcessorsFromEnv)();
        this._tracerProvider = new sdk_trace_node_1.NodeTracerProvider({
          ...this._configuration,
          resource: this._resource,
          spanProcessors
        });
        if (spanProcessors.length > 0) {
          this._tracerProvider.register({
            contextManager: this._tracerProviderConfig?.contextManager ?? // _tracerProviderConfig may be undefined if trace-specific settings are not provided - fall back to raw config
            this._configuration?.contextManager,
            propagator: this._tracerProviderConfig?.textMapPropagator ?? (0, utils_1.getPropagatorFromEnv)()
          });
        }
        if (this._loggerProviderConfig) {
          const loggerProvider = new sdk_logs_1.LoggerProvider({
            resource: this._resource,
            processors: this._loggerProviderConfig.logRecordProcessors
          });
          this._loggerProvider = loggerProvider;
          api_logs_1.logs.setGlobalLoggerProvider(loggerProvider);
        }
        const metricReadersFromEnv = configureMetricProviderFromEnv();
        if (this._meterProviderConfig || metricReadersFromEnv.length > 0) {
          const readers = [];
          if (this._meterProviderConfig?.reader) {
            readers.push(this._meterProviderConfig.reader);
          }
          if (readers.length === 0) {
            metricReadersFromEnv.forEach((r3) => readers.push(r3));
          }
          const meterProvider = new sdk_metrics_1.MeterProvider({
            resource: this._resource,
            views: this._meterProviderConfig?.views ?? [],
            readers
          });
          this._meterProvider = meterProvider;
          api_1.metrics.setGlobalMeterProvider(meterProvider);
          for (const instrumentation of this._instrumentations) {
            instrumentation.setMeterProvider(api_1.metrics.getMeterProvider());
          }
        }
      }
      shutdown() {
        const promises6 = [];
        if (this._tracerProvider) {
          promises6.push(this._tracerProvider.shutdown());
        }
        if (this._loggerProvider) {
          promises6.push(this._loggerProvider.shutdown());
        }
        if (this._meterProvider) {
          promises6.push(this._meterProvider.shutdown());
        }
        return Promise.all(promises6).then(() => {
        });
      }
      configureLoggerProviderFromEnv() {
        const enabledExporters = (0, core_1.getStringListFromEnv)("OTEL_LOGS_EXPORTER") ?? [];
        if (enabledExporters.length === 0) {
          api_1.diag.debug("OTEL_LOGS_EXPORTER is empty. Using default otlp exporter.");
          enabledExporters.push("otlp");
        }
        if (enabledExporters.includes("none")) {
          api_1.diag.info(`OTEL_LOGS_EXPORTER contains "none". Logger provider will not be initialized.`);
          return;
        }
        const exporters = [];
        enabledExporters.forEach((exporter) => {
          if (exporter === "otlp") {
            const protocol = ((0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_LOGS_PROTOCOL") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_PROTOCOL"))?.trim();
            switch (protocol) {
              case "grpc":
                exporters.push(new exporter_logs_otlp_grpc_1.OTLPLogExporter());
                break;
              case "http/json":
                exporters.push(new exporter_logs_otlp_http_1.OTLPLogExporter());
                break;
              case "http/protobuf":
                exporters.push(new exporter_logs_otlp_proto_1.OTLPLogExporter());
                break;
              case void 0:
              case "":
                exporters.push(new exporter_logs_otlp_proto_1.OTLPLogExporter());
                break;
              default:
                api_1.diag.warn(`Unsupported OTLP logs protocol: "${protocol}". Using http/protobuf.`);
                exporters.push(new exporter_logs_otlp_proto_1.OTLPLogExporter());
            }
          } else if (exporter === "console") {
            exporters.push(new sdk_logs_1.ConsoleLogRecordExporter());
          } else {
            api_1.diag.warn(`Unsupported OTEL_LOGS_EXPORTER value: "${exporter}". Supported values are: otlp, console, none.`);
          }
        });
        if (exporters.length > 0) {
          this._loggerProviderConfig = {
            logRecordProcessors: exporters.map((exporter) => {
              if (exporter instanceof sdk_logs_1.ConsoleLogRecordExporter) {
                return new sdk_logs_1.SimpleLogRecordProcessor(exporter);
              } else {
                return new sdk_logs_1.BatchLogRecordProcessor(exporter);
              }
            })
          };
        }
      }
    };
    exports2.NodeSDK = NodeSDK2;
  }
});

// node_modules/@opentelemetry/sdk-node/build/src/index.js
var require_src34 = __commonJS({
  "node_modules/@opentelemetry/sdk-node/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NodeSDK = exports2.tracing = exports2.resources = exports2.node = exports2.metrics = exports2.logs = exports2.core = exports2.contextBase = exports2.api = void 0;
    exports2.api = (init_esm2(), __toCommonJS(esm_exports2));
    exports2.contextBase = (init_esm2(), __toCommonJS(esm_exports2));
    exports2.core = require_src8();
    exports2.logs = require_src22();
    exports2.metrics = require_src14();
    exports2.node = require_src25();
    exports2.resources = require_src13();
    exports2.tracing = require_src24();
    var sdk_1 = require_sdk();
    Object.defineProperty(exports2, "NodeSDK", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_1.NodeSDK;
    }, "get") });
  }
});

// node_modules/@opentelemetry/instrumentation-http/build/src/version.js
var require_version9 = __commonJS({
  "node_modules/@opentelemetry/instrumentation-http/build/src/version.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.VERSION = void 0;
    exports2.VERSION = "0.203.0";
  }
});

// node_modules/@opentelemetry/instrumentation-http/build/src/semconv.js
var require_semconv3 = __commonJS({
  "node_modules/@opentelemetry/instrumentation-http/build/src/semconv.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.HTTP_FLAVOR_VALUE_HTTP_1_1 = exports2.NET_TRANSPORT_VALUE_IP_UDP = exports2.NET_TRANSPORT_VALUE_IP_TCP = exports2.ATTR_NET_TRANSPORT = exports2.ATTR_NET_PEER_PORT = exports2.ATTR_NET_PEER_NAME = exports2.ATTR_NET_PEER_IP = exports2.ATTR_NET_HOST_PORT = exports2.ATTR_NET_HOST_NAME = exports2.ATTR_NET_HOST_IP = exports2.ATTR_HTTP_USER_AGENT = exports2.ATTR_HTTP_URL = exports2.ATTR_HTTP_TARGET = exports2.ATTR_HTTP_STATUS_CODE = exports2.ATTR_HTTP_SERVER_NAME = exports2.ATTR_HTTP_SCHEME = exports2.ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = exports2.ATTR_HTTP_RESPONSE_CONTENT_LENGTH = exports2.ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = exports2.ATTR_HTTP_REQUEST_CONTENT_LENGTH = exports2.ATTR_HTTP_METHOD = exports2.ATTR_HTTP_HOST = exports2.ATTR_HTTP_FLAVOR = exports2.ATTR_HTTP_CLIENT_IP = exports2.USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST = exports2.USER_AGENT_SYNTHETIC_TYPE_VALUE_BOT = exports2.ATTR_USER_AGENT_SYNTHETIC_TYPE = void 0;
    exports2.ATTR_USER_AGENT_SYNTHETIC_TYPE = "user_agent.synthetic.type";
    exports2.USER_AGENT_SYNTHETIC_TYPE_VALUE_BOT = "bot";
    exports2.USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST = "test";
    exports2.ATTR_HTTP_CLIENT_IP = "http.client_ip";
    exports2.ATTR_HTTP_FLAVOR = "http.flavor";
    exports2.ATTR_HTTP_HOST = "http.host";
    exports2.ATTR_HTTP_METHOD = "http.method";
    exports2.ATTR_HTTP_REQUEST_CONTENT_LENGTH = "http.request_content_length";
    exports2.ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = "http.request_content_length_uncompressed";
    exports2.ATTR_HTTP_RESPONSE_CONTENT_LENGTH = "http.response_content_length";
    exports2.ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = "http.response_content_length_uncompressed";
    exports2.ATTR_HTTP_SCHEME = "http.scheme";
    exports2.ATTR_HTTP_SERVER_NAME = "http.server_name";
    exports2.ATTR_HTTP_STATUS_CODE = "http.status_code";
    exports2.ATTR_HTTP_TARGET = "http.target";
    exports2.ATTR_HTTP_URL = "http.url";
    exports2.ATTR_HTTP_USER_AGENT = "http.user_agent";
    exports2.ATTR_NET_HOST_IP = "net.host.ip";
    exports2.ATTR_NET_HOST_NAME = "net.host.name";
    exports2.ATTR_NET_HOST_PORT = "net.host.port";
    exports2.ATTR_NET_PEER_IP = "net.peer.ip";
    exports2.ATTR_NET_PEER_NAME = "net.peer.name";
    exports2.ATTR_NET_PEER_PORT = "net.peer.port";
    exports2.ATTR_NET_TRANSPORT = "net.transport";
    exports2.NET_TRANSPORT_VALUE_IP_TCP = "ip_tcp";
    exports2.NET_TRANSPORT_VALUE_IP_UDP = "ip_udp";
    exports2.HTTP_FLAVOR_VALUE_HTTP_1_1 = "1.1";
  }
});

// node_modules/@opentelemetry/instrumentation-http/build/src/enums/AttributeNames.js
var require_AttributeNames = __commonJS({
  "node_modules/@opentelemetry/instrumentation-http/build/src/enums/AttributeNames.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AttributeNames = void 0;
    var AttributeNames;
    (function(AttributeNames2) {
      AttributeNames2["HTTP_ERROR_NAME"] = "http.error_name";
      AttributeNames2["HTTP_ERROR_MESSAGE"] = "http.error_message";
      AttributeNames2["HTTP_STATUS_TEXT"] = "http.status_text";
    })(AttributeNames = exports2.AttributeNames || (exports2.AttributeNames = {}));
  }
});

// node_modules/@opentelemetry/instrumentation-http/build/src/internal-types.js
var require_internal_types2 = __commonJS({
  "node_modules/@opentelemetry/instrumentation-http/build/src/internal-types.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SYNTHETIC_BOT_NAMES = exports2.SYNTHETIC_TEST_NAMES = void 0;
    exports2.SYNTHETIC_TEST_NAMES = ["alwayson"];
    exports2.SYNTHETIC_BOT_NAMES = ["googlebot", "bingbot"];
  }
});

// node_modules/forwarded-parse/lib/error.js
var require_error2 = __commonJS({
  "node_modules/forwarded-parse/lib/error.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var util4 = __require("util");
    function ParseError2(message, input) {
      Error.captureStackTrace(this, ParseError2);
      this.name = this.constructor.name;
      this.message = message;
      this.input = input;
    }
    __name(ParseError2, "ParseError");
    util4.inherits(ParseError2, Error);
    module2.exports = ParseError2;
  }
});

// node_modules/forwarded-parse/lib/ascii.js
var require_ascii = __commonJS({
  "node_modules/forwarded-parse/lib/ascii.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    function isDelimiter2(code2) {
      return code2 === 34 || code2 === 40 || code2 === 41 || code2 === 44 || code2 === 47 || code2 >= 58 && code2 <= 64 || code2 >= 91 && code2 <= 93 || code2 === 123 || code2 === 125;
    }
    __name(isDelimiter2, "isDelimiter");
    function isTokenChar(code2) {
      return code2 === 33 || code2 >= 35 && code2 <= 39 || code2 === 42 || code2 === 43 || code2 === 45 || code2 === 46 || code2 >= 48 && code2 <= 57 || code2 >= 65 && code2 <= 90 || code2 >= 94 && code2 <= 122 || code2 === 124 || code2 === 126;
    }
    __name(isTokenChar, "isTokenChar");
    function isPrint(code2) {
      return code2 >= 32 && code2 <= 126;
    }
    __name(isPrint, "isPrint");
    function isExtended(code2) {
      return code2 >= 128 && code2 <= 255;
    }
    __name(isExtended, "isExtended");
    module2.exports = {
      isDelimiter: isDelimiter2,
      isTokenChar,
      isExtended,
      isPrint
    };
  }
});

// node_modules/forwarded-parse/index.js
var require_forwarded_parse = __commonJS({
  "node_modules/forwarded-parse/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var util4 = __require("util");
    var ParseError2 = require_error2();
    var ascii = require_ascii();
    var isDelimiter2 = ascii.isDelimiter;
    var isTokenChar = ascii.isTokenChar;
    var isExtended = ascii.isExtended;
    var isPrint = ascii.isPrint;
    function decode2(str2) {
      return str2.replace(/\\(.)/g, "$1");
    }
    __name(decode2, "decode");
    function unexpectedCharacterMessage(header, position) {
      return util4.format(
        "Unexpected character '%s' at index %d",
        header.charAt(position),
        position
      );
    }
    __name(unexpectedCharacterMessage, "unexpectedCharacterMessage");
    function parse12(header) {
      var mustUnescape = false;
      var isEscaping = false;
      var inQuotes = false;
      var forwarded = {};
      var output = [];
      var start = -1;
      var end = -1;
      var parameter;
      var code2;
      for (var i = 0; i < header.length; i++) {
        code2 = header.charCodeAt(i);
        if (parameter === void 0) {
          if (i !== 0 && start === -1 && (code2 === 32 || code2 === 9)) {
            continue;
          }
          if (isTokenChar(code2)) {
            if (start === -1) start = i;
          } else if (code2 === 61 && start !== -1) {
            parameter = header.slice(start, i).toLowerCase();
            start = -1;
          } else {
            throw new ParseError2(unexpectedCharacterMessage(header, i), header);
          }
        } else {
          if (isEscaping && (code2 === 9 || isPrint(code2) || isExtended(code2))) {
            isEscaping = false;
          } else if (isTokenChar(code2)) {
            if (end !== -1) {
              throw new ParseError2(unexpectedCharacterMessage(header, i), header);
            }
            if (start === -1) start = i;
          } else if (isDelimiter2(code2) || isExtended(code2)) {
            if (inQuotes) {
              if (code2 === 34) {
                inQuotes = false;
                end = i;
              } else if (code2 === 92) {
                if (start === -1) start = i;
                isEscaping = mustUnescape = true;
              } else if (start === -1) {
                start = i;
              }
            } else if (code2 === 34 && header.charCodeAt(i - 1) === 61) {
              inQuotes = true;
            } else if ((code2 === 44 || code2 === 59) && (start !== -1 || end !== -1)) {
              if (start !== -1) {
                if (end === -1) end = i;
                forwarded[parameter] = mustUnescape ? decode2(header.slice(start, end)) : header.slice(start, end);
              } else {
                forwarded[parameter] = "";
              }
              if (code2 === 44) {
                output.push(forwarded);
                forwarded = {};
              }
              parameter = void 0;
              start = end = -1;
            } else {
              throw new ParseError2(unexpectedCharacterMessage(header, i), header);
            }
          } else if (code2 === 32 || code2 === 9) {
            if (end !== -1) continue;
            if (inQuotes) {
              if (start === -1) start = i;
            } else if (start !== -1) {
              end = i;
            } else {
              throw new ParseError2(unexpectedCharacterMessage(header, i), header);
            }
          } else {
            throw new ParseError2(unexpectedCharacterMessage(header, i), header);
          }
        }
      }
      if (parameter === void 0 || inQuotes || start === -1 && end === -1 || code2 === 32 || code2 === 9) {
        throw new ParseError2("Unexpected end of input", header);
      }
      if (start !== -1) {
        if (end === -1) end = i;
        forwarded[parameter] = mustUnescape ? decode2(header.slice(start, end)) : header.slice(start, end);
      } else {
        forwarded[parameter] = "";
      }
      output.push(forwarded);
      return output;
    }
    __name(parse12, "parse");
    module2.exports = parse12;
  }
});

// node_modules/@opentelemetry/instrumentation-http/build/src/utils.js
var require_utils12 = __commonJS({
  "node_modules/@opentelemetry/instrumentation-http/build/src/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.headerCapture = exports2.getIncomingStableRequestMetricAttributesOnResponse = exports2.getIncomingRequestMetricAttributesOnResponse = exports2.getIncomingRequestAttributesOnResponse = exports2.getIncomingRequestMetricAttributes = exports2.getIncomingRequestAttributes = exports2.getRemoteClientAddress = exports2.getOutgoingStableRequestMetricAttributesOnResponse = exports2.getOutgoingRequestMetricAttributesOnResponse = exports2.getOutgoingRequestAttributesOnResponse = exports2.setAttributesFromHttpKind = exports2.getOutgoingRequestMetricAttributes = exports2.getOutgoingRequestAttributes = exports2.extractHostnameAndPort = exports2.isValidOptionsType = exports2.getRequestInfo = exports2.isCompressed = exports2.setResponseContentLengthAttribute = exports2.setRequestContentLengthAttribute = exports2.setSpanWithError = exports2.satisfiesPattern = exports2.parseResponseStatus = exports2.getAbsoluteUrl = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var semantic_conventions_1 = (init_esm(), __toCommonJS(esm_exports));
    var semconv_1 = require_semconv3();
    var core_1 = require_src8();
    var instrumentation_1 = require_src26();
    var url2 = __require("url");
    var AttributeNames_1 = require_AttributeNames();
    var internal_types_1 = require_internal_types2();
    var forwardedParse = require_forwarded_parse();
    var getAbsoluteUrl = /* @__PURE__ */ __name((requestUrl, headers, fallbackProtocol = "http:") => {
      const reqUrlObject = requestUrl || {};
      const protocol = reqUrlObject.protocol || fallbackProtocol;
      const port = (reqUrlObject.port || "").toString();
      const path108 = reqUrlObject.path || "/";
      let host = reqUrlObject.host || reqUrlObject.hostname || headers.host || "localhost";
      if (host.indexOf(":") === -1 && port && port !== "80" && port !== "443") {
        host += `:${port}`;
      }
      return `${protocol}//${host}${path108}`;
    }, "getAbsoluteUrl");
    exports2.getAbsoluteUrl = getAbsoluteUrl;
    var parseResponseStatus = /* @__PURE__ */ __name((kind, statusCode) => {
      const upperBound = kind === api_1.SpanKind.CLIENT ? 400 : 500;
      if (statusCode && statusCode >= 100 && statusCode < upperBound) {
        return api_1.SpanStatusCode.UNSET;
      }
      return api_1.SpanStatusCode.ERROR;
    }, "parseResponseStatus");
    exports2.parseResponseStatus = parseResponseStatus;
    var satisfiesPattern = /* @__PURE__ */ __name((constant, pattern) => {
      if (typeof pattern === "string") {
        return pattern === constant;
      } else if (pattern instanceof RegExp) {
        return pattern.test(constant);
      } else if (typeof pattern === "function") {
        return pattern(constant);
      } else {
        throw new TypeError("Pattern is in unsupported datatype");
      }
    }, "satisfiesPattern");
    exports2.satisfiesPattern = satisfiesPattern;
    var setSpanWithError = /* @__PURE__ */ __name((span, error, semconvStability) => {
      const message = error.message;
      if (semconvStability & instrumentation_1.SemconvStability.OLD) {
        span.setAttribute(AttributeNames_1.AttributeNames.HTTP_ERROR_NAME, error.name);
        span.setAttribute(AttributeNames_1.AttributeNames.HTTP_ERROR_MESSAGE, message);
      }
      if (semconvStability & instrumentation_1.SemconvStability.STABLE) {
        span.setAttribute(semantic_conventions_1.ATTR_ERROR_TYPE, error.name);
      }
      span.setStatus({ code: api_1.SpanStatusCode.ERROR, message });
      span.recordException(error);
    }, "setSpanWithError");
    exports2.setSpanWithError = setSpanWithError;
    var setRequestContentLengthAttribute = /* @__PURE__ */ __name((request4, attributes) => {
      const length = getContentLength(request4.headers);
      if (length === null)
        return;
      if ((0, exports2.isCompressed)(request4.headers)) {
        attributes[semconv_1.ATTR_HTTP_REQUEST_CONTENT_LENGTH] = length;
      } else {
        attributes[semconv_1.ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED] = length;
      }
    }, "setRequestContentLengthAttribute");
    exports2.setRequestContentLengthAttribute = setRequestContentLengthAttribute;
    var setResponseContentLengthAttribute = /* @__PURE__ */ __name((response, attributes) => {
      const length = getContentLength(response.headers);
      if (length === null)
        return;
      if ((0, exports2.isCompressed)(response.headers)) {
        attributes[semconv_1.ATTR_HTTP_RESPONSE_CONTENT_LENGTH] = length;
      } else {
        attributes[semconv_1.ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED] = length;
      }
    }, "setResponseContentLengthAttribute");
    exports2.setResponseContentLengthAttribute = setResponseContentLengthAttribute;
    function getContentLength(headers) {
      const contentLengthHeader = headers["content-length"];
      if (contentLengthHeader === void 0)
        return null;
      const contentLength = parseInt(contentLengthHeader, 10);
      if (isNaN(contentLength))
        return null;
      return contentLength;
    }
    __name(getContentLength, "getContentLength");
    var isCompressed = /* @__PURE__ */ __name((headers) => {
      const encoding = headers["content-encoding"];
      return !!encoding && encoding !== "identity";
    }, "isCompressed");
    exports2.isCompressed = isCompressed;
    function stringUrlToHttpOptions(stringUrl) {
      const { hostname: hostname3, pathname, port, username, password, search, protocol, hash, href, origin, host } = new URL(stringUrl);
      const options2 = {
        protocol,
        hostname: hostname3 && hostname3[0] === "[" ? hostname3.slice(1, -1) : hostname3,
        hash,
        search,
        pathname,
        path: `${pathname || ""}${search || ""}`,
        href,
        origin,
        host
      };
      if (port !== "") {
        options2.port = Number(port);
      }
      if (username || password) {
        options2.auth = `${decodeURIComponent(username)}:${decodeURIComponent(password)}`;
      }
      return options2;
    }
    __name(stringUrlToHttpOptions, "stringUrlToHttpOptions");
    var getRequestInfo = /* @__PURE__ */ __name((logger6, options2, extraOptions) => {
      let pathname;
      let origin;
      let optionsParsed;
      let invalidUrl = false;
      if (typeof options2 === "string") {
        try {
          const convertedOptions = stringUrlToHttpOptions(options2);
          optionsParsed = convertedOptions;
          pathname = convertedOptions.pathname || "/";
        } catch (e2) {
          invalidUrl = true;
          logger6.verbose("Unable to parse URL provided to HTTP request, using fallback to determine path. Original error:", e2);
          optionsParsed = {
            path: options2
          };
          pathname = optionsParsed.path || "/";
        }
        origin = `${optionsParsed.protocol || "http:"}//${optionsParsed.host}`;
        if (extraOptions !== void 0) {
          Object.assign(optionsParsed, extraOptions);
        }
      } else if (options2 instanceof url2.URL) {
        optionsParsed = {
          protocol: options2.protocol,
          hostname: typeof options2.hostname === "string" && options2.hostname.startsWith("[") ? options2.hostname.slice(1, -1) : options2.hostname,
          path: `${options2.pathname || ""}${options2.search || ""}`
        };
        if (options2.port !== "") {
          optionsParsed.port = Number(options2.port);
        }
        if (options2.username || options2.password) {
          optionsParsed.auth = `${options2.username}:${options2.password}`;
        }
        pathname = options2.pathname;
        origin = options2.origin;
        if (extraOptions !== void 0) {
          Object.assign(optionsParsed, extraOptions);
        }
      } else {
        optionsParsed = Object.assign({ protocol: options2.host ? "http:" : void 0 }, options2);
        const hostname3 = optionsParsed.host || (optionsParsed.port != null ? `${optionsParsed.hostname}${optionsParsed.port}` : optionsParsed.hostname);
        origin = `${optionsParsed.protocol || "http:"}//${hostname3}`;
        pathname = options2.pathname;
        if (!pathname && optionsParsed.path) {
          try {
            const parsedUrl = new URL(optionsParsed.path, origin);
            pathname = parsedUrl.pathname || "/";
          } catch {
            pathname = "/";
          }
        }
      }
      const method = optionsParsed.method ? optionsParsed.method.toUpperCase() : "GET";
      return { origin, pathname, method, optionsParsed, invalidUrl };
    }, "getRequestInfo");
    exports2.getRequestInfo = getRequestInfo;
    var isValidOptionsType = /* @__PURE__ */ __name((options2) => {
      if (!options2) {
        return false;
      }
      const type = typeof options2;
      return type === "string" || type === "object" && !Array.isArray(options2);
    }, "isValidOptionsType");
    exports2.isValidOptionsType = isValidOptionsType;
    var extractHostnameAndPort = /* @__PURE__ */ __name((requestOptions) => {
      if (requestOptions.hostname && requestOptions.port) {
        return { hostname: requestOptions.hostname, port: requestOptions.port };
      }
      const matches = requestOptions.host?.match(/^([^:/ ]+)(:\d{1,5})?/) || null;
      const hostname3 = requestOptions.hostname || (matches === null ? "localhost" : matches[1]);
      let port = requestOptions.port;
      if (!port) {
        if (matches && matches[2]) {
          port = matches[2].substring(1);
        } else {
          port = requestOptions.protocol === "https:" ? "443" : "80";
        }
      }
      return { hostname: hostname3, port };
    }, "extractHostnameAndPort");
    exports2.extractHostnameAndPort = extractHostnameAndPort;
    var getOutgoingRequestAttributes = /* @__PURE__ */ __name((requestOptions, options2, semconvStability, enableSyntheticSourceDetection) => {
      const hostname3 = options2.hostname;
      const port = options2.port;
      const method = requestOptions.method ?? "GET";
      const normalizedMethod = normalizeMethod(method);
      const headers = requestOptions.headers || {};
      const userAgent2 = headers["user-agent"];
      const urlFull = (0, exports2.getAbsoluteUrl)(requestOptions, headers, `${options2.component}:`);
      const oldAttributes = {
        [semconv_1.ATTR_HTTP_URL]: urlFull,
        [semconv_1.ATTR_HTTP_METHOD]: method,
        [semconv_1.ATTR_HTTP_TARGET]: requestOptions.path || "/",
        [semconv_1.ATTR_NET_PEER_NAME]: hostname3,
        [semconv_1.ATTR_HTTP_HOST]: headers.host ?? `${hostname3}:${port}`
      };
      const newAttributes = {
        // Required attributes
        [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD]: normalizedMethod,
        [semantic_conventions_1.ATTR_SERVER_ADDRESS]: hostname3,
        [semantic_conventions_1.ATTR_SERVER_PORT]: Number(port),
        [semantic_conventions_1.ATTR_URL_FULL]: urlFull,
        [semantic_conventions_1.ATTR_USER_AGENT_ORIGINAL]: userAgent2
        // leaving out protocol version, it is not yet negotiated
        // leaving out protocol name, it is only required when protocol version is set
        // retries and redirects not supported
        // Opt-in attributes left off for now
      };
      if (method !== normalizedMethod) {
        newAttributes[semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = method;
      }
      if (enableSyntheticSourceDetection && userAgent2) {
        newAttributes[semconv_1.ATTR_USER_AGENT_SYNTHETIC_TYPE] = getSyntheticType(userAgent2);
      }
      if (userAgent2 !== void 0) {
        oldAttributes[semconv_1.ATTR_HTTP_USER_AGENT] = userAgent2;
      }
      switch (semconvStability) {
        case instrumentation_1.SemconvStability.STABLE:
          return Object.assign(newAttributes, options2.hookAttributes);
        case instrumentation_1.SemconvStability.OLD:
          return Object.assign(oldAttributes, options2.hookAttributes);
      }
      return Object.assign(oldAttributes, newAttributes, options2.hookAttributes);
    }, "getOutgoingRequestAttributes");
    exports2.getOutgoingRequestAttributes = getOutgoingRequestAttributes;
    var getOutgoingRequestMetricAttributes = /* @__PURE__ */ __name((spanAttributes) => {
      const metricAttributes = {};
      metricAttributes[semconv_1.ATTR_HTTP_METHOD] = spanAttributes[semconv_1.ATTR_HTTP_METHOD];
      metricAttributes[semconv_1.ATTR_NET_PEER_NAME] = spanAttributes[semconv_1.ATTR_NET_PEER_NAME];
      return metricAttributes;
    }, "getOutgoingRequestMetricAttributes");
    exports2.getOutgoingRequestMetricAttributes = getOutgoingRequestMetricAttributes;
    var setAttributesFromHttpKind = /* @__PURE__ */ __name((kind, attributes) => {
      if (kind) {
        attributes[semconv_1.ATTR_HTTP_FLAVOR] = kind;
        if (kind.toUpperCase() !== "QUIC") {
          attributes[semconv_1.ATTR_NET_TRANSPORT] = semconv_1.NET_TRANSPORT_VALUE_IP_TCP;
        } else {
          attributes[semconv_1.ATTR_NET_TRANSPORT] = semconv_1.NET_TRANSPORT_VALUE_IP_UDP;
        }
      }
    }, "setAttributesFromHttpKind");
    exports2.setAttributesFromHttpKind = setAttributesFromHttpKind;
    var getSyntheticType = /* @__PURE__ */ __name((userAgent2) => {
      const userAgentString = String(userAgent2).toLowerCase();
      for (const name3 of internal_types_1.SYNTHETIC_TEST_NAMES) {
        if (userAgentString.includes(name3)) {
          return semconv_1.USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST;
        }
      }
      for (const name3 of internal_types_1.SYNTHETIC_BOT_NAMES) {
        if (userAgentString.includes(name3)) {
          return semconv_1.USER_AGENT_SYNTHETIC_TYPE_VALUE_BOT;
        }
      }
      return;
    }, "getSyntheticType");
    var getOutgoingRequestAttributesOnResponse = /* @__PURE__ */ __name((response, semconvStability) => {
      const { statusCode, statusMessage, httpVersion, socket } = response;
      const oldAttributes = {};
      const stableAttributes = {};
      if (statusCode != null) {
        stableAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE] = statusCode;
      }
      if (socket) {
        const { remoteAddress, remotePort } = socket;
        oldAttributes[semconv_1.ATTR_NET_PEER_IP] = remoteAddress;
        oldAttributes[semconv_1.ATTR_NET_PEER_PORT] = remotePort;
        stableAttributes[semantic_conventions_1.ATTR_NETWORK_PEER_ADDRESS] = remoteAddress;
        stableAttributes[semantic_conventions_1.ATTR_NETWORK_PEER_PORT] = remotePort;
        stableAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION] = response.httpVersion;
      }
      (0, exports2.setResponseContentLengthAttribute)(response, oldAttributes);
      if (statusCode) {
        oldAttributes[semconv_1.ATTR_HTTP_STATUS_CODE] = statusCode;
        oldAttributes[AttributeNames_1.AttributeNames.HTTP_STATUS_TEXT] = (statusMessage || "").toUpperCase();
      }
      (0, exports2.setAttributesFromHttpKind)(httpVersion, oldAttributes);
      switch (semconvStability) {
        case instrumentation_1.SemconvStability.STABLE:
          return stableAttributes;
        case instrumentation_1.SemconvStability.OLD:
          return oldAttributes;
      }
      return Object.assign(oldAttributes, stableAttributes);
    }, "getOutgoingRequestAttributesOnResponse");
    exports2.getOutgoingRequestAttributesOnResponse = getOutgoingRequestAttributesOnResponse;
    var getOutgoingRequestMetricAttributesOnResponse = /* @__PURE__ */ __name((spanAttributes) => {
      const metricAttributes = {};
      metricAttributes[semconv_1.ATTR_NET_PEER_PORT] = spanAttributes[semconv_1.ATTR_NET_PEER_PORT];
      metricAttributes[semconv_1.ATTR_HTTP_STATUS_CODE] = spanAttributes[semconv_1.ATTR_HTTP_STATUS_CODE];
      metricAttributes[semconv_1.ATTR_HTTP_FLAVOR] = spanAttributes[semconv_1.ATTR_HTTP_FLAVOR];
      return metricAttributes;
    }, "getOutgoingRequestMetricAttributesOnResponse");
    exports2.getOutgoingRequestMetricAttributesOnResponse = getOutgoingRequestMetricAttributesOnResponse;
    var getOutgoingStableRequestMetricAttributesOnResponse = /* @__PURE__ */ __name((spanAttributes) => {
      const metricAttributes = {};
      if (spanAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]) {
        metricAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION] = spanAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION];
      }
      if (spanAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE]) {
        metricAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE] = spanAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE];
      }
      return metricAttributes;
    }, "getOutgoingStableRequestMetricAttributesOnResponse");
    exports2.getOutgoingStableRequestMetricAttributesOnResponse = getOutgoingStableRequestMetricAttributesOnResponse;
    function parseHostHeader(hostHeader, proto3) {
      const parts = hostHeader.split(":");
      if (parts.length === 1) {
        if (proto3 === "http") {
          return { host: parts[0], port: "80" };
        }
        if (proto3 === "https") {
          return { host: parts[0], port: "443" };
        }
        return { host: parts[0] };
      }
      if (parts.length === 2) {
        return {
          host: parts[0],
          port: parts[1]
        };
      }
      if (parts[0].startsWith("[")) {
        if (parts[parts.length - 1].endsWith("]")) {
          if (proto3 === "http") {
            return { host: hostHeader, port: "80" };
          }
          if (proto3 === "https") {
            return { host: hostHeader, port: "443" };
          }
        } else if (parts[parts.length - 2].endsWith("]")) {
          return {
            host: parts.slice(0, -1).join(":"),
            port: parts[parts.length - 1]
          };
        }
      }
      return { host: hostHeader };
    }
    __name(parseHostHeader, "parseHostHeader");
    function getServerAddress(request4, component) {
      const forwardedHeader = request4.headers["forwarded"];
      if (forwardedHeader) {
        for (const entry of parseForwardedHeader(forwardedHeader)) {
          if (entry.host) {
            return parseHostHeader(entry.host, entry.proto);
          }
        }
      }
      const xForwardedHost = request4.headers["x-forwarded-host"];
      if (typeof xForwardedHost === "string") {
        if (typeof request4.headers["x-forwarded-proto"] === "string") {
          return parseHostHeader(xForwardedHost, request4.headers["x-forwarded-proto"]);
        }
        if (Array.isArray(request4.headers["x-forwarded-proto"])) {
          return parseHostHeader(xForwardedHost, request4.headers["x-forwarded-proto"][0]);
        }
        return parseHostHeader(xForwardedHost);
      } else if (Array.isArray(xForwardedHost) && typeof xForwardedHost[0] === "string" && xForwardedHost[0].length > 0) {
        if (typeof request4.headers["x-forwarded-proto"] === "string") {
          return parseHostHeader(xForwardedHost[0], request4.headers["x-forwarded-proto"]);
        }
        if (Array.isArray(request4.headers["x-forwarded-proto"])) {
          return parseHostHeader(xForwardedHost[0], request4.headers["x-forwarded-proto"][0]);
        }
        return parseHostHeader(xForwardedHost[0]);
      }
      const host = request4.headers["host"];
      if (typeof host === "string" && host.length > 0) {
        return parseHostHeader(host, component);
      }
      return null;
    }
    __name(getServerAddress, "getServerAddress");
    function getRemoteClientAddress(request4) {
      const forwardedHeader = request4.headers["forwarded"];
      if (forwardedHeader) {
        for (const entry of parseForwardedHeader(forwardedHeader)) {
          if (entry.for) {
            return entry.for;
          }
        }
      }
      const xForwardedFor = request4.headers["x-forwarded-for"];
      if (typeof xForwardedFor === "string") {
        return xForwardedFor;
      } else if (Array.isArray(xForwardedFor)) {
        return xForwardedFor[0];
      }
      const remote = request4.socket.remoteAddress;
      if (remote) {
        return remote;
      }
      return null;
    }
    __name(getRemoteClientAddress, "getRemoteClientAddress");
    exports2.getRemoteClientAddress = getRemoteClientAddress;
    function getInfoFromIncomingMessage(component, request4, logger6) {
      try {
        if (request4.headers.host) {
          return new URL(request4.url ?? "/", `${component}://${request4.headers.host}`);
        } else {
          const unsafeParsedUrl = new URL(
            request4.url ?? "/",
            // using localhost as a workaround to still use the URL constructor for parsing
            `${component}://localhost`
          );
          return {
            pathname: unsafeParsedUrl.pathname,
            search: unsafeParsedUrl.search,
            toString: /* @__PURE__ */ __name(function() {
              return unsafeParsedUrl.pathname + unsafeParsedUrl.search;
            }, "toString")
          };
        }
      } catch (e2) {
        logger6.verbose("Unable to get URL from request", e2);
        return {};
      }
    }
    __name(getInfoFromIncomingMessage, "getInfoFromIncomingMessage");
    var getIncomingRequestAttributes = /* @__PURE__ */ __name((request4, options2, logger6) => {
      const headers = request4.headers;
      const userAgent2 = headers["user-agent"];
      const ips = headers["x-forwarded-for"];
      const httpVersion = request4.httpVersion;
      const host = headers.host;
      const hostname3 = host?.replace(/^(.*)(:[0-9]{1,5})/, "$1") || "localhost";
      const method = request4.method;
      const normalizedMethod = normalizeMethod(method);
      const serverAddress = getServerAddress(request4, options2.component);
      const serverName = options2.serverName;
      const remoteClientAddress = getRemoteClientAddress(request4);
      const newAttributes = {
        [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD]: normalizedMethod,
        [semantic_conventions_1.ATTR_URL_SCHEME]: options2.component,
        [semantic_conventions_1.ATTR_SERVER_ADDRESS]: serverAddress?.host,
        [semantic_conventions_1.ATTR_NETWORK_PEER_ADDRESS]: request4.socket.remoteAddress,
        [semantic_conventions_1.ATTR_NETWORK_PEER_PORT]: request4.socket.remotePort,
        [semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]: request4.httpVersion,
        [semantic_conventions_1.ATTR_USER_AGENT_ORIGINAL]: userAgent2
      };
      const parsedUrl = getInfoFromIncomingMessage(options2.component, request4, logger6);
      if (parsedUrl?.pathname != null) {
        newAttributes[semantic_conventions_1.ATTR_URL_PATH] = parsedUrl.pathname;
      }
      if (parsedUrl.search) {
        newAttributes[semantic_conventions_1.ATTR_URL_QUERY] = parsedUrl.search.slice(1);
      }
      if (remoteClientAddress != null) {
        newAttributes[semantic_conventions_1.ATTR_CLIENT_ADDRESS] = remoteClientAddress.split(",")[0];
      }
      if (serverAddress?.port != null) {
        newAttributes[semantic_conventions_1.ATTR_SERVER_PORT] = Number(serverAddress.port);
      }
      if (method !== normalizedMethod) {
        newAttributes[semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = method;
      }
      if (options2.enableSyntheticSourceDetection && userAgent2) {
        newAttributes[semconv_1.ATTR_USER_AGENT_SYNTHETIC_TYPE] = getSyntheticType(userAgent2);
      }
      const oldAttributes = {
        [semconv_1.ATTR_HTTP_URL]: parsedUrl.toString(),
        [semconv_1.ATTR_HTTP_HOST]: host,
        [semconv_1.ATTR_NET_HOST_NAME]: hostname3,
        [semconv_1.ATTR_HTTP_METHOD]: method,
        [semconv_1.ATTR_HTTP_SCHEME]: options2.component
      };
      if (typeof ips === "string") {
        oldAttributes[semconv_1.ATTR_HTTP_CLIENT_IP] = ips.split(",")[0];
      }
      if (typeof serverName === "string") {
        oldAttributes[semconv_1.ATTR_HTTP_SERVER_NAME] = serverName;
      }
      if (parsedUrl?.pathname) {
        oldAttributes[semconv_1.ATTR_HTTP_TARGET] = parsedUrl?.pathname + parsedUrl?.search || "/";
      }
      if (userAgent2 !== void 0) {
        oldAttributes[semconv_1.ATTR_HTTP_USER_AGENT] = userAgent2;
      }
      (0, exports2.setRequestContentLengthAttribute)(request4, oldAttributes);
      (0, exports2.setAttributesFromHttpKind)(httpVersion, oldAttributes);
      switch (options2.semconvStability) {
        case instrumentation_1.SemconvStability.STABLE:
          return Object.assign(newAttributes, options2.hookAttributes);
        case instrumentation_1.SemconvStability.OLD:
          return Object.assign(oldAttributes, options2.hookAttributes);
      }
      return Object.assign(oldAttributes, newAttributes, options2.hookAttributes);
    }, "getIncomingRequestAttributes");
    exports2.getIncomingRequestAttributes = getIncomingRequestAttributes;
    var getIncomingRequestMetricAttributes = /* @__PURE__ */ __name((spanAttributes) => {
      const metricAttributes = {};
      metricAttributes[semconv_1.ATTR_HTTP_SCHEME] = spanAttributes[semconv_1.ATTR_HTTP_SCHEME];
      metricAttributes[semconv_1.ATTR_HTTP_METHOD] = spanAttributes[semconv_1.ATTR_HTTP_METHOD];
      metricAttributes[semconv_1.ATTR_NET_HOST_NAME] = spanAttributes[semconv_1.ATTR_NET_HOST_NAME];
      metricAttributes[semconv_1.ATTR_HTTP_FLAVOR] = spanAttributes[semconv_1.ATTR_HTTP_FLAVOR];
      return metricAttributes;
    }, "getIncomingRequestMetricAttributes");
    exports2.getIncomingRequestMetricAttributes = getIncomingRequestMetricAttributes;
    var getIncomingRequestAttributesOnResponse = /* @__PURE__ */ __name((request4, response, semconvStability) => {
      const { socket } = request4;
      const { statusCode, statusMessage } = response;
      const newAttributes = {
        [semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE]: statusCode
      };
      const rpcMetadata = (0, core_1.getRPCMetadata)(api_1.context.active());
      const oldAttributes = {};
      if (socket) {
        const { localAddress, localPort, remoteAddress, remotePort } = socket;
        oldAttributes[semconv_1.ATTR_NET_HOST_IP] = localAddress;
        oldAttributes[semconv_1.ATTR_NET_HOST_PORT] = localPort;
        oldAttributes[semconv_1.ATTR_NET_PEER_IP] = remoteAddress;
        oldAttributes[semconv_1.ATTR_NET_PEER_PORT] = remotePort;
      }
      oldAttributes[semconv_1.ATTR_HTTP_STATUS_CODE] = statusCode;
      oldAttributes[AttributeNames_1.AttributeNames.HTTP_STATUS_TEXT] = (statusMessage || "").toUpperCase();
      if (rpcMetadata?.type === core_1.RPCType.HTTP && rpcMetadata.route !== void 0) {
        oldAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] = rpcMetadata.route;
        newAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] = rpcMetadata.route;
      }
      switch (semconvStability) {
        case instrumentation_1.SemconvStability.STABLE:
          return newAttributes;
        case instrumentation_1.SemconvStability.OLD:
          return oldAttributes;
      }
      return Object.assign(oldAttributes, newAttributes);
    }, "getIncomingRequestAttributesOnResponse");
    exports2.getIncomingRequestAttributesOnResponse = getIncomingRequestAttributesOnResponse;
    var getIncomingRequestMetricAttributesOnResponse = /* @__PURE__ */ __name((spanAttributes) => {
      const metricAttributes = {};
      metricAttributes[semconv_1.ATTR_HTTP_STATUS_CODE] = spanAttributes[semconv_1.ATTR_HTTP_STATUS_CODE];
      metricAttributes[semconv_1.ATTR_NET_HOST_PORT] = spanAttributes[semconv_1.ATTR_NET_HOST_PORT];
      if (spanAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] !== void 0) {
        metricAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] = spanAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE];
      }
      return metricAttributes;
    }, "getIncomingRequestMetricAttributesOnResponse");
    exports2.getIncomingRequestMetricAttributesOnResponse = getIncomingRequestMetricAttributesOnResponse;
    var getIncomingStableRequestMetricAttributesOnResponse = /* @__PURE__ */ __name((spanAttributes) => {
      const metricAttributes = {};
      if (spanAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] !== void 0) {
        metricAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] = spanAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE];
      }
      if (spanAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE]) {
        metricAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE] = spanAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE];
      }
      return metricAttributes;
    }, "getIncomingStableRequestMetricAttributesOnResponse");
    exports2.getIncomingStableRequestMetricAttributesOnResponse = getIncomingStableRequestMetricAttributesOnResponse;
    function headerCapture(type, headers) {
      const normalizedHeaders = /* @__PURE__ */ new Map();
      for (let i = 0, len = headers.length; i < len; i++) {
        const capturedHeader = headers[i].toLowerCase();
        normalizedHeaders.set(capturedHeader, capturedHeader.replace(/-/g, "_"));
      }
      return (span, getHeader) => {
        for (const capturedHeader of normalizedHeaders.keys()) {
          const value = getHeader(capturedHeader);
          if (value === void 0) {
            continue;
          }
          const normalizedHeader = normalizedHeaders.get(capturedHeader);
          const key = `http.${type}.header.${normalizedHeader}`;
          if (typeof value === "string") {
            span.setAttribute(key, [value]);
          } else if (Array.isArray(value)) {
            span.setAttribute(key, value);
          } else {
            span.setAttribute(key, [value]);
          }
        }
      };
    }
    __name(headerCapture, "headerCapture");
    exports2.headerCapture = headerCapture;
    var KNOWN_METHODS = /* @__PURE__ */ new Set([
      // methods from https://www.rfc-editor.org/rfc/rfc9110.html#name-methods
      "GET",
      "HEAD",
      "POST",
      "PUT",
      "DELETE",
      "CONNECT",
      "OPTIONS",
      "TRACE",
      // PATCH from https://www.rfc-editor.org/rfc/rfc5789.html
      "PATCH"
    ]);
    function normalizeMethod(method) {
      if (method == null) {
        return "GET";
      }
      const upper = method.toUpperCase();
      if (KNOWN_METHODS.has(upper)) {
        return upper;
      }
      return "_OTHER";
    }
    __name(normalizeMethod, "normalizeMethod");
    function parseForwardedHeader(header) {
      try {
        return forwardedParse(header);
      } catch {
        return [];
      }
    }
    __name(parseForwardedHeader, "parseForwardedHeader");
  }
});

// node_modules/@opentelemetry/instrumentation-http/build/src/http.js
var require_http = __commonJS({
  "node_modules/@opentelemetry/instrumentation-http/build/src/http.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.HttpInstrumentation = void 0;
    var api_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var url2 = __require("url");
    var version_1 = require_version9();
    var instrumentation_1 = require_src26();
    var events_1 = __require("events");
    var semantic_conventions_1 = (init_esm(), __toCommonJS(esm_exports));
    var utils_1 = require_utils12();
    var HttpInstrumentation2 = class extends instrumentation_1.InstrumentationBase {
      static {
        __name(this, "HttpInstrumentation");
      }
      /** keep track on spans not ended */
      _spanNotEnded = /* @__PURE__ */ new WeakSet();
      _headerCapture;
      _semconvStability = instrumentation_1.SemconvStability.OLD;
      constructor(config = {}) {
        super("@opentelemetry/instrumentation-http", version_1.VERSION, config);
        this._headerCapture = this._createHeaderCapture();
        this._semconvStability = (0, instrumentation_1.semconvStabilityFromStr)("http", process.env.OTEL_SEMCONV_STABILITY_OPT_IN);
      }
      _updateMetricInstruments() {
        this._oldHttpServerDurationHistogram = this.meter.createHistogram("http.server.duration", {
          description: "Measures the duration of inbound HTTP requests.",
          unit: "ms",
          valueType: api_1.ValueType.DOUBLE
        });
        this._oldHttpClientDurationHistogram = this.meter.createHistogram("http.client.duration", {
          description: "Measures the duration of outbound HTTP requests.",
          unit: "ms",
          valueType: api_1.ValueType.DOUBLE
        });
        this._stableHttpServerDurationHistogram = this.meter.createHistogram(semantic_conventions_1.METRIC_HTTP_SERVER_REQUEST_DURATION, {
          description: "Duration of HTTP server requests.",
          unit: "s",
          valueType: api_1.ValueType.DOUBLE,
          advice: {
            explicitBucketBoundaries: [
              5e-3,
              0.01,
              0.025,
              0.05,
              0.075,
              0.1,
              0.25,
              0.5,
              0.75,
              1,
              2.5,
              5,
              7.5,
              10
            ]
          }
        });
        this._stableHttpClientDurationHistogram = this.meter.createHistogram(semantic_conventions_1.METRIC_HTTP_CLIENT_REQUEST_DURATION, {
          description: "Duration of HTTP client requests.",
          unit: "s",
          valueType: api_1.ValueType.DOUBLE,
          advice: {
            explicitBucketBoundaries: [
              5e-3,
              0.01,
              0.025,
              0.05,
              0.075,
              0.1,
              0.25,
              0.5,
              0.75,
              1,
              2.5,
              5,
              7.5,
              10
            ]
          }
        });
      }
      _recordServerDuration(durationMs, oldAttributes, stableAttributes) {
        if (this._semconvStability & instrumentation_1.SemconvStability.OLD) {
          this._oldHttpServerDurationHistogram.record(durationMs, oldAttributes);
        }
        if (this._semconvStability & instrumentation_1.SemconvStability.STABLE) {
          this._stableHttpServerDurationHistogram.record(durationMs / 1e3, stableAttributes);
        }
      }
      _recordClientDuration(durationMs, oldAttributes, stableAttributes) {
        if (this._semconvStability & instrumentation_1.SemconvStability.OLD) {
          this._oldHttpClientDurationHistogram.record(durationMs, oldAttributes);
        }
        if (this._semconvStability & instrumentation_1.SemconvStability.STABLE) {
          this._stableHttpClientDurationHistogram.record(durationMs / 1e3, stableAttributes);
        }
      }
      setConfig(config = {}) {
        super.setConfig(config);
        this._headerCapture = this._createHeaderCapture();
      }
      init() {
        return [this._getHttpsInstrumentation(), this._getHttpInstrumentation()];
      }
      _getHttpInstrumentation() {
        return new instrumentation_1.InstrumentationNodeModuleDefinition("http", ["*"], (moduleExports) => {
          const isESM = moduleExports[Symbol.toStringTag] === "Module";
          if (!this.getConfig().disableOutgoingRequestInstrumentation) {
            const patchedRequest = this._wrap(moduleExports, "request", this._getPatchOutgoingRequestFunction("http"));
            const patchedGet = this._wrap(moduleExports, "get", this._getPatchOutgoingGetFunction(patchedRequest));
            if (isESM) {
              moduleExports.default.request = patchedRequest;
              moduleExports.default.get = patchedGet;
            }
          }
          if (!this.getConfig().disableIncomingRequestInstrumentation) {
            this._wrap(moduleExports.Server.prototype, "emit", this._getPatchIncomingRequestFunction("http"));
          }
          return moduleExports;
        }, (moduleExports) => {
          if (moduleExports === void 0)
            return;
          if (!this.getConfig().disableOutgoingRequestInstrumentation) {
            this._unwrap(moduleExports, "request");
            this._unwrap(moduleExports, "get");
          }
          if (!this.getConfig().disableIncomingRequestInstrumentation) {
            this._unwrap(moduleExports.Server.prototype, "emit");
          }
        });
      }
      _getHttpsInstrumentation() {
        return new instrumentation_1.InstrumentationNodeModuleDefinition("https", ["*"], (moduleExports) => {
          const isESM = moduleExports[Symbol.toStringTag] === "Module";
          if (!this.getConfig().disableOutgoingRequestInstrumentation) {
            const patchedRequest = this._wrap(moduleExports, "request", this._getPatchHttpsOutgoingRequestFunction("https"));
            const patchedGet = this._wrap(moduleExports, "get", this._getPatchHttpsOutgoingGetFunction(patchedRequest));
            if (isESM) {
              moduleExports.default.request = patchedRequest;
              moduleExports.default.get = patchedGet;
            }
          }
          if (!this.getConfig().disableIncomingRequestInstrumentation) {
            this._wrap(moduleExports.Server.prototype, "emit", this._getPatchIncomingRequestFunction("https"));
          }
          return moduleExports;
        }, (moduleExports) => {
          if (moduleExports === void 0)
            return;
          if (!this.getConfig().disableOutgoingRequestInstrumentation) {
            this._unwrap(moduleExports, "request");
            this._unwrap(moduleExports, "get");
          }
          if (!this.getConfig().disableIncomingRequestInstrumentation) {
            this._unwrap(moduleExports.Server.prototype, "emit");
          }
        });
      }
      /**
       * Creates spans for incoming requests, restoring spans' context if applied.
       */
      _getPatchIncomingRequestFunction(component) {
        return (original) => {
          return this._incomingRequestFunction(component, original);
        };
      }
      /**
       * Creates spans for outgoing requests, sending spans' context for distributed
       * tracing.
       */
      _getPatchOutgoingRequestFunction(component) {
        return (original) => {
          return this._outgoingRequestFunction(component, original);
        };
      }
      _getPatchOutgoingGetFunction(clientRequest) {
        return (_original) => {
          return /* @__PURE__ */ __name(function outgoingGetRequest(options2, ...args) {
            const req = clientRequest(options2, ...args);
            req.end();
            return req;
          }, "outgoingGetRequest");
        };
      }
      /** Patches HTTPS outgoing requests */
      _getPatchHttpsOutgoingRequestFunction(component) {
        return (original) => {
          const instrumentation = this;
          return /* @__PURE__ */ __name(function httpsOutgoingRequest(options2, ...args) {
            if (component === "https" && typeof options2 === "object" && options2?.constructor?.name !== "URL") {
              options2 = Object.assign({}, options2);
              instrumentation._setDefaultOptions(options2);
            }
            return instrumentation._getPatchOutgoingRequestFunction(component)(original)(options2, ...args);
          }, "httpsOutgoingRequest");
        };
      }
      _setDefaultOptions(options2) {
        options2.protocol = options2.protocol || "https:";
        options2.port = options2.port || 443;
      }
      /** Patches HTTPS outgoing get requests */
      _getPatchHttpsOutgoingGetFunction(clientRequest) {
        return (original) => {
          const instrumentation = this;
          return /* @__PURE__ */ __name(function httpsOutgoingRequest(options2, ...args) {
            return instrumentation._getPatchOutgoingGetFunction(clientRequest)(original)(options2, ...args);
          }, "httpsOutgoingRequest");
        };
      }
      /**
       * Attach event listeners to a client request to end span and add span attributes.
       *
       * @param request The original request object.
       * @param span representing the current operation
       * @param startTime representing the start time of the request to calculate duration in Metric
       * @param oldMetricAttributes metric attributes for old semantic conventions
       * @param stableMetricAttributes metric attributes for new semantic conventions
       */
      _traceClientRequest(request4, span, startTime, oldMetricAttributes, stableMetricAttributes) {
        if (this.getConfig().requestHook) {
          this._callRequestHook(span, request4);
        }
        let responseFinished = false;
        request4.prependListener("response", (response) => {
          this._diag.debug("outgoingRequest on response()");
          if (request4.listenerCount("response") <= 1) {
            response.resume();
          }
          const responseAttributes = (0, utils_1.getOutgoingRequestAttributesOnResponse)(response, this._semconvStability);
          span.setAttributes(responseAttributes);
          oldMetricAttributes = Object.assign(oldMetricAttributes, (0, utils_1.getOutgoingRequestMetricAttributesOnResponse)(responseAttributes));
          stableMetricAttributes = Object.assign(stableMetricAttributes, (0, utils_1.getOutgoingStableRequestMetricAttributesOnResponse)(responseAttributes));
          if (this.getConfig().responseHook) {
            this._callResponseHook(span, response);
          }
          this._headerCapture.client.captureRequestHeaders(span, (header) => request4.getHeader(header));
          this._headerCapture.client.captureResponseHeaders(span, (header) => response.headers[header]);
          api_1.context.bind(api_1.context.active(), response);
          const endHandler = /* @__PURE__ */ __name(() => {
            this._diag.debug("outgoingRequest on end()");
            if (responseFinished) {
              return;
            }
            responseFinished = true;
            let status;
            if (response.aborted && !response.complete) {
              status = { code: api_1.SpanStatusCode.ERROR };
            } else {
              status = {
                code: (0, utils_1.parseResponseStatus)(api_1.SpanKind.CLIENT, response.statusCode)
              };
            }
            span.setStatus(status);
            if (this.getConfig().applyCustomAttributesOnSpan) {
              (0, instrumentation_1.safeExecuteInTheMiddle)(() => this.getConfig().applyCustomAttributesOnSpan(span, request4, response), () => {
              }, true);
            }
            this._closeHttpSpan(span, api_1.SpanKind.CLIENT, startTime, oldMetricAttributes, stableMetricAttributes);
          }, "endHandler");
          response.on("end", endHandler);
          response.on(events_1.errorMonitor, (error) => {
            this._diag.debug("outgoingRequest on error()", error);
            if (responseFinished) {
              return;
            }
            responseFinished = true;
            (0, utils_1.setSpanWithError)(span, error, this._semconvStability);
            span.setStatus({
              code: api_1.SpanStatusCode.ERROR,
              message: error.message
            });
            this._closeHttpSpan(span, api_1.SpanKind.CLIENT, startTime, oldMetricAttributes, stableMetricAttributes);
          });
        });
        request4.on("close", () => {
          this._diag.debug("outgoingRequest on request close()");
          if (request4.aborted || responseFinished) {
            return;
          }
          responseFinished = true;
          this._closeHttpSpan(span, api_1.SpanKind.CLIENT, startTime, oldMetricAttributes, stableMetricAttributes);
        });
        request4.on(events_1.errorMonitor, (error) => {
          this._diag.debug("outgoingRequest on request error()", error);
          if (responseFinished) {
            return;
          }
          responseFinished = true;
          (0, utils_1.setSpanWithError)(span, error, this._semconvStability);
          this._closeHttpSpan(span, api_1.SpanKind.CLIENT, startTime, oldMetricAttributes, stableMetricAttributes);
        });
        this._diag.debug("http.ClientRequest return request");
        return request4;
      }
      _incomingRequestFunction(component, original) {
        const instrumentation = this;
        return /* @__PURE__ */ __name(function incomingRequest(event, ...args) {
          if (event !== "request") {
            return original.apply(this, [event, ...args]);
          }
          const request4 = args[0];
          const response = args[1];
          const method = request4.method || "GET";
          instrumentation._diag.debug(`${component} instrumentation incomingRequest`);
          if ((0, instrumentation_1.safeExecuteInTheMiddle)(() => instrumentation.getConfig().ignoreIncomingRequestHook?.(request4), (e2) => {
            if (e2 != null) {
              instrumentation._diag.error("caught ignoreIncomingRequestHook error: ", e2);
            }
          }, true)) {
            return api_1.context.with((0, core_1.suppressTracing)(api_1.context.active()), () => {
              api_1.context.bind(api_1.context.active(), request4);
              api_1.context.bind(api_1.context.active(), response);
              return original.apply(this, [event, ...args]);
            });
          }
          const headers = request4.headers;
          const spanAttributes = (0, utils_1.getIncomingRequestAttributes)(request4, {
            component,
            serverName: instrumentation.getConfig().serverName,
            hookAttributes: instrumentation._callStartSpanHook(request4, instrumentation.getConfig().startIncomingSpanHook),
            semconvStability: instrumentation._semconvStability,
            enableSyntheticSourceDetection: instrumentation.getConfig().enableSyntheticSourceDetection || false
          }, instrumentation._diag);
          const spanOptions = {
            kind: api_1.SpanKind.SERVER,
            attributes: spanAttributes
          };
          const startTime = (0, core_1.hrTime)();
          const oldMetricAttributes = (0, utils_1.getIncomingRequestMetricAttributes)(spanAttributes);
          const stableMetricAttributes = {
            [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD]: spanAttributes[semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD],
            [semantic_conventions_1.ATTR_URL_SCHEME]: spanAttributes[semantic_conventions_1.ATTR_URL_SCHEME]
          };
          if (spanAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]) {
            stableMetricAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION] = spanAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION];
          }
          const ctx = api_1.propagation.extract(api_1.ROOT_CONTEXT, headers);
          const span = instrumentation._startHttpSpan(method, spanOptions, ctx);
          const rpcMetadata = {
            type: core_1.RPCType.HTTP,
            span
          };
          return api_1.context.with((0, core_1.setRPCMetadata)(api_1.trace.setSpan(ctx, span), rpcMetadata), () => {
            api_1.context.bind(api_1.context.active(), request4);
            api_1.context.bind(api_1.context.active(), response);
            if (instrumentation.getConfig().requestHook) {
              instrumentation._callRequestHook(span, request4);
            }
            if (instrumentation.getConfig().responseHook) {
              instrumentation._callResponseHook(span, response);
            }
            instrumentation._headerCapture.server.captureRequestHeaders(span, (header) => request4.headers[header]);
            let hasError = false;
            response.on("close", () => {
              if (hasError) {
                return;
              }
              instrumentation._onServerResponseFinish(request4, response, span, oldMetricAttributes, stableMetricAttributes, startTime);
            });
            response.on(events_1.errorMonitor, (err) => {
              hasError = true;
              instrumentation._onServerResponseError(span, oldMetricAttributes, stableMetricAttributes, startTime, err);
            });
            return (0, instrumentation_1.safeExecuteInTheMiddle)(() => original.apply(this, [event, ...args]), (error) => {
              if (error) {
                (0, utils_1.setSpanWithError)(span, error, instrumentation._semconvStability);
                instrumentation._closeHttpSpan(span, api_1.SpanKind.SERVER, startTime, oldMetricAttributes, stableMetricAttributes);
                throw error;
              }
            });
          });
        }, "incomingRequest");
      }
      _outgoingRequestFunction(component, original) {
        const instrumentation = this;
        return /* @__PURE__ */ __name(function outgoingRequest(options2, ...args) {
          if (!(0, utils_1.isValidOptionsType)(options2)) {
            return original.apply(this, [options2, ...args]);
          }
          const extraOptions = typeof args[0] === "object" && (typeof options2 === "string" || options2 instanceof url2.URL) ? args.shift() : void 0;
          const { method, invalidUrl, optionsParsed } = (0, utils_1.getRequestInfo)(instrumentation._diag, options2, extraOptions);
          if ((0, instrumentation_1.safeExecuteInTheMiddle)(() => instrumentation.getConfig().ignoreOutgoingRequestHook?.(optionsParsed), (e2) => {
            if (e2 != null) {
              instrumentation._diag.error("caught ignoreOutgoingRequestHook error: ", e2);
            }
          }, true)) {
            return original.apply(this, [optionsParsed, ...args]);
          }
          const { hostname: hostname3, port } = (0, utils_1.extractHostnameAndPort)(optionsParsed);
          const attributes = (0, utils_1.getOutgoingRequestAttributes)(optionsParsed, {
            component,
            port,
            hostname: hostname3,
            hookAttributes: instrumentation._callStartSpanHook(optionsParsed, instrumentation.getConfig().startOutgoingSpanHook)
          }, instrumentation._semconvStability, instrumentation.getConfig().enableSyntheticSourceDetection || false);
          const startTime = (0, core_1.hrTime)();
          const oldMetricAttributes = (0, utils_1.getOutgoingRequestMetricAttributes)(attributes);
          const stableMetricAttributes = {
            [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD]: attributes[semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD],
            [semantic_conventions_1.ATTR_SERVER_ADDRESS]: attributes[semantic_conventions_1.ATTR_SERVER_ADDRESS],
            [semantic_conventions_1.ATTR_SERVER_PORT]: attributes[semantic_conventions_1.ATTR_SERVER_PORT]
          };
          if (attributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE]) {
            stableMetricAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE] = attributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE];
          }
          if (attributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]) {
            stableMetricAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION] = attributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION];
          }
          const spanOptions = {
            kind: api_1.SpanKind.CLIENT,
            attributes
          };
          const span = instrumentation._startHttpSpan(method, spanOptions);
          const parentContext = api_1.context.active();
          const requestContext = api_1.trace.setSpan(parentContext, span);
          if (!optionsParsed.headers) {
            optionsParsed.headers = {};
          } else {
            optionsParsed.headers = Object.assign({}, optionsParsed.headers);
          }
          api_1.propagation.inject(requestContext, optionsParsed.headers);
          return api_1.context.with(requestContext, () => {
            const cb = args[args.length - 1];
            if (typeof cb === "function") {
              args[args.length - 1] = api_1.context.bind(parentContext, cb);
            }
            const request4 = (0, instrumentation_1.safeExecuteInTheMiddle)(() => {
              if (invalidUrl) {
                return original.apply(this, [options2, ...args]);
              } else {
                return original.apply(this, [optionsParsed, ...args]);
              }
            }, (error) => {
              if (error) {
                (0, utils_1.setSpanWithError)(span, error, instrumentation._semconvStability);
                instrumentation._closeHttpSpan(span, api_1.SpanKind.CLIENT, startTime, oldMetricAttributes, stableMetricAttributes);
                throw error;
              }
            });
            instrumentation._diag.debug(`${component} instrumentation outgoingRequest`);
            api_1.context.bind(parentContext, request4);
            return instrumentation._traceClientRequest(request4, span, startTime, oldMetricAttributes, stableMetricAttributes);
          });
        }, "outgoingRequest");
      }
      _onServerResponseFinish(request4, response, span, oldMetricAttributes, stableMetricAttributes, startTime) {
        const attributes = (0, utils_1.getIncomingRequestAttributesOnResponse)(request4, response, this._semconvStability);
        oldMetricAttributes = Object.assign(oldMetricAttributes, (0, utils_1.getIncomingRequestMetricAttributesOnResponse)(attributes));
        stableMetricAttributes = Object.assign(stableMetricAttributes, (0, utils_1.getIncomingStableRequestMetricAttributesOnResponse)(attributes));
        this._headerCapture.server.captureResponseHeaders(span, (header) => response.getHeader(header));
        span.setAttributes(attributes).setStatus({
          code: (0, utils_1.parseResponseStatus)(api_1.SpanKind.SERVER, response.statusCode)
        });
        const route = attributes[semantic_conventions_1.ATTR_HTTP_ROUTE];
        if (route) {
          span.updateName(`${request4.method || "GET"} ${route}`);
        }
        if (this.getConfig().applyCustomAttributesOnSpan) {
          (0, instrumentation_1.safeExecuteInTheMiddle)(() => this.getConfig().applyCustomAttributesOnSpan(span, request4, response), () => {
          }, true);
        }
        this._closeHttpSpan(span, api_1.SpanKind.SERVER, startTime, oldMetricAttributes, stableMetricAttributes);
      }
      _onServerResponseError(span, oldMetricAttributes, stableMetricAttributes, startTime, error) {
        (0, utils_1.setSpanWithError)(span, error, this._semconvStability);
        this._closeHttpSpan(span, api_1.SpanKind.SERVER, startTime, oldMetricAttributes, stableMetricAttributes);
      }
      _startHttpSpan(name3, options2, ctx = api_1.context.active()) {
        const requireParent = options2.kind === api_1.SpanKind.CLIENT ? this.getConfig().requireParentforOutgoingSpans : this.getConfig().requireParentforIncomingSpans;
        let span;
        const currentSpan = api_1.trace.getSpan(ctx);
        if (requireParent === true && currentSpan === void 0) {
          span = api_1.trace.wrapSpanContext(api_1.INVALID_SPAN_CONTEXT);
        } else if (requireParent === true && currentSpan?.spanContext().isRemote) {
          span = currentSpan;
        } else {
          span = this.tracer.startSpan(name3, options2, ctx);
        }
        this._spanNotEnded.add(span);
        return span;
      }
      _closeHttpSpan(span, spanKind, startTime, oldMetricAttributes, stableMetricAttributes) {
        if (!this._spanNotEnded.has(span)) {
          return;
        }
        span.end();
        this._spanNotEnded.delete(span);
        const duration = (0, core_1.hrTimeToMilliseconds)((0, core_1.hrTimeDuration)(startTime, (0, core_1.hrTime)()));
        if (spanKind === api_1.SpanKind.SERVER) {
          this._recordServerDuration(duration, oldMetricAttributes, stableMetricAttributes);
        } else if (spanKind === api_1.SpanKind.CLIENT) {
          this._recordClientDuration(duration, oldMetricAttributes, stableMetricAttributes);
        }
      }
      _callResponseHook(span, response) {
        (0, instrumentation_1.safeExecuteInTheMiddle)(() => this.getConfig().responseHook(span, response), () => {
        }, true);
      }
      _callRequestHook(span, request4) {
        (0, instrumentation_1.safeExecuteInTheMiddle)(() => this.getConfig().requestHook(span, request4), () => {
        }, true);
      }
      _callStartSpanHook(request4, hookFunc) {
        if (typeof hookFunc === "function") {
          return (0, instrumentation_1.safeExecuteInTheMiddle)(() => hookFunc(request4), () => {
          }, true);
        }
      }
      _createHeaderCapture() {
        const config = this.getConfig();
        return {
          client: {
            captureRequestHeaders: (0, utils_1.headerCapture)("request", config.headersToSpanAttributes?.client?.requestHeaders ?? []),
            captureResponseHeaders: (0, utils_1.headerCapture)("response", config.headersToSpanAttributes?.client?.responseHeaders ?? [])
          },
          server: {
            captureRequestHeaders: (0, utils_1.headerCapture)("request", config.headersToSpanAttributes?.server?.requestHeaders ?? []),
            captureResponseHeaders: (0, utils_1.headerCapture)("response", config.headersToSpanAttributes?.server?.responseHeaders ?? [])
          }
        };
      }
    };
    exports2.HttpInstrumentation = HttpInstrumentation2;
  }
});

// node_modules/@opentelemetry/instrumentation-http/build/src/index.js
var require_src35 = __commonJS({
  "node_modules/@opentelemetry/instrumentation-http/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.HttpInstrumentation = void 0;
    var http_1 = require_http();
    Object.defineProperty(exports2, "HttpInstrumentation", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return http_1.HttpInstrumentation;
    }, "get") });
  }
});

// packages/core/dist/src/telemetry/file-exporters.js
import * as fs15 from "node:fs";
var import_core3, import_sdk_metrics, FileExporter, FileSpanExporter, FileLogExporter, FileMetricExporter;
var init_file_exporters = __esm({
  "packages/core/dist/src/telemetry/file-exporters.js"() {
    "use strict";
    init_esbuild_shims();
    import_core3 = __toESM(require_src8(), 1);
    import_sdk_metrics = __toESM(require_src14(), 1);
    FileExporter = class {
      static {
        __name(this, "FileExporter");
      }
      writeStream;
      constructor(filePath) {
        this.writeStream = fs15.createWriteStream(filePath, { flags: "a" });
      }
      serialize(data) {
        return JSON.stringify(data, null, 2) + "\n";
      }
      shutdown() {
        return new Promise((resolve24) => {
          this.writeStream.end(resolve24);
        });
      }
    };
    FileSpanExporter = class extends FileExporter {
      static {
        __name(this, "FileSpanExporter");
      }
      export(spans, resultCallback) {
        const data = spans.map((span) => this.serialize(span)).join("");
        this.writeStream.write(data, (err) => {
          resultCallback({
            code: err ? import_core3.ExportResultCode.FAILED : import_core3.ExportResultCode.SUCCESS,
            error: err || void 0
          });
        });
      }
    };
    FileLogExporter = class extends FileExporter {
      static {
        __name(this, "FileLogExporter");
      }
      export(logs2, resultCallback) {
        const data = logs2.map((log) => this.serialize(log)).join("");
        this.writeStream.write(data, (err) => {
          resultCallback({
            code: err ? import_core3.ExportResultCode.FAILED : import_core3.ExportResultCode.SUCCESS,
            error: err || void 0
          });
        });
      }
    };
    FileMetricExporter = class extends FileExporter {
      static {
        __name(this, "FileMetricExporter");
      }
      export(metrics2, resultCallback) {
        const data = this.serialize(metrics2);
        this.writeStream.write(data, (err) => {
          resultCallback({
            code: err ? import_core3.ExportResultCode.FAILED : import_core3.ExportResultCode.SUCCESS,
            error: err || void 0
          });
        });
      }
      getPreferredAggregationTemporality() {
        return import_sdk_metrics.AggregationTemporality.CUMULATIVE;
      }
      async forceFlush() {
        return Promise.resolve();
      }
    };
  }
});

// packages/core/dist/src/telemetry/sdk.js
function isTelemetrySdkInitialized() {
  return telemetryInitialized;
}
function parseOtlpEndpoint(otlpEndpointSetting, protocol) {
  if (!otlpEndpointSetting) {
    return void 0;
  }
  const trimmedEndpoint = otlpEndpointSetting.replace(/^["']|["']$/g, "");
  try {
    const url2 = new URL(trimmedEndpoint);
    if (protocol === "grpc") {
      return url2.origin;
    }
    return url2.href;
  } catch (error) {
    diag2.error("Invalid OTLP endpoint URL provided:", trimmedEndpoint, error);
    return void 0;
  }
}
function initializeTelemetry(config) {
  if (telemetryInitialized || !config.getTelemetryEnabled()) {
    return;
  }
  const resource = (0, import_resources.resourceFromAttributes)({
    [SemanticResourceAttributes.SERVICE_NAME]: SERVICE_NAME,
    [SemanticResourceAttributes.SERVICE_VERSION]: process.version,
    "session.id": config.getSessionId()
  });
  const otlpEndpoint = config.getTelemetryOtlpEndpoint();
  const otlpProtocol = config.getTelemetryOtlpProtocol();
  const parsedEndpoint = parseOtlpEndpoint(otlpEndpoint, otlpProtocol);
  const telemetryOutfile = config.getTelemetryOutfile();
  const useOtlp = !!parsedEndpoint && !telemetryOutfile;
  let spanExporter;
  let logExporter;
  let metricReader;
  if (useOtlp) {
    if (otlpProtocol === "http") {
      spanExporter = new import_exporter_trace_otlp_http.OTLPTraceExporter({
        url: parsedEndpoint
      });
      logExporter = new import_exporter_logs_otlp_http.OTLPLogExporter({
        url: parsedEndpoint
      });
      metricReader = new import_sdk_metrics2.PeriodicExportingMetricReader({
        exporter: new import_exporter_metrics_otlp_http.OTLPMetricExporter({
          url: parsedEndpoint
        }),
        exportIntervalMillis: 1e4
      });
    } else {
      spanExporter = new import_exporter_trace_otlp_grpc.OTLPTraceExporter({
        url: parsedEndpoint,
        compression: CompressionAlgorithm.GZIP
      });
      logExporter = new import_exporter_logs_otlp_grpc.OTLPLogExporter({
        url: parsedEndpoint,
        compression: CompressionAlgorithm.GZIP
      });
      metricReader = new import_sdk_metrics2.PeriodicExportingMetricReader({
        exporter: new import_exporter_metrics_otlp_grpc.OTLPMetricExporter({
          url: parsedEndpoint,
          compression: CompressionAlgorithm.GZIP
        }),
        exportIntervalMillis: 1e4
      });
    }
  } else if (telemetryOutfile) {
    spanExporter = new FileSpanExporter(telemetryOutfile);
    logExporter = new FileLogExporter(telemetryOutfile);
    metricReader = new import_sdk_metrics2.PeriodicExportingMetricReader({
      exporter: new FileMetricExporter(telemetryOutfile),
      exportIntervalMillis: 1e4
    });
  } else {
    spanExporter = new import_sdk_trace_node.ConsoleSpanExporter();
    logExporter = new import_sdk_logs.ConsoleLogRecordExporter();
    metricReader = new import_sdk_metrics2.PeriodicExportingMetricReader({
      exporter: new import_sdk_metrics2.ConsoleMetricExporter(),
      exportIntervalMillis: 1e4
    });
  }
  sdk = new import_sdk_node.NodeSDK({
    resource,
    spanProcessors: [new import_sdk_trace_node.BatchSpanProcessor(spanExporter)],
    logRecordProcessors: [new import_sdk_logs.BatchLogRecordProcessor(logExporter)],
    metricReader,
    instrumentations: [new import_instrumentation_http.HttpInstrumentation()]
  });
  try {
    sdk.start();
    if (config.getDebugMode()) {
      console.log("OpenTelemetry SDK started successfully.");
    }
    telemetryInitialized = true;
    initializeMetrics(config);
  } catch (error) {
    console.error("Error starting OpenTelemetry SDK:", error);
  }
  process.on("SIGTERM", () => {
    shutdownTelemetry(config);
  });
  process.on("SIGINT", () => {
    shutdownTelemetry(config);
  });
  process.on("exit", () => {
    shutdownTelemetry(config);
  });
}
async function shutdownTelemetry(config) {
  if (!telemetryInitialized || !sdk) {
    return;
  }
  try {
    await sdk.shutdown();
    if (config.getDebugMode()) {
      console.log("OpenTelemetry SDK shut down successfully.");
    }
  } catch (error) {
    console.error("Error shutting down SDK:", error);
  } finally {
    telemetryInitialized = false;
  }
}
var import_exporter_trace_otlp_grpc, import_exporter_logs_otlp_grpc, import_exporter_metrics_otlp_grpc, import_exporter_trace_otlp_http, import_exporter_logs_otlp_http, import_exporter_metrics_otlp_http, import_sdk_node, import_resources, import_sdk_trace_node, import_sdk_logs, import_sdk_metrics2, import_instrumentation_http, sdk, telemetryInitialized;
var init_sdk = __esm({
  "packages/core/dist/src/telemetry/sdk.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm2();
    import_exporter_trace_otlp_grpc = __toESM(require_src16(), 1);
    import_exporter_logs_otlp_grpc = __toESM(require_src17(), 1);
    import_exporter_metrics_otlp_grpc = __toESM(require_src19(), 1);
    import_exporter_trace_otlp_http = __toESM(require_src20(), 1);
    import_exporter_logs_otlp_http = __toESM(require_src21(), 1);
    import_exporter_metrics_otlp_http = __toESM(require_src18(), 1);
    init_esm3();
    import_sdk_node = __toESM(require_src34(), 1);
    init_esm();
    import_resources = __toESM(require_src13(), 1);
    import_sdk_trace_node = __toESM(require_src25(), 1);
    import_sdk_logs = __toESM(require_src22(), 1);
    import_sdk_metrics2 = __toESM(require_src14(), 1);
    import_instrumentation_http = __toESM(require_src35(), 1);
    init_constants();
    init_metrics2();
    init_file_exporters();
    diag2.setLogger(new DiagConsoleLogger(), DiagLogLevel.INFO);
    telemetryInitialized = false;
    __name(isTelemetrySdkInitialized, "isTelemetrySdkInitialized");
    __name(parseOtlpEndpoint, "parseOtlpEndpoint");
    __name(initializeTelemetry, "initializeTelemetry");
    __name(shutdownTelemetry, "shutdownTelemetry");
  }
});

// packages/core/dist/src/telemetry/uiTelemetry.js
import { EventEmitter as EventEmitter4 } from "node:events";
var createInitialModelMetrics, createInitialMetrics, UiTelemetryService, uiTelemetryService;
var init_uiTelemetry = __esm({
  "packages/core/dist/src/telemetry/uiTelemetry.js"() {
    "use strict";
    init_esbuild_shims();
    init_constants();
    init_tool_call_decision();
    createInitialModelMetrics = /* @__PURE__ */ __name(() => ({
      api: {
        totalRequests: 0,
        totalErrors: 0,
        totalLatencyMs: 0
      },
      tokens: {
        prompt: 0,
        candidates: 0,
        total: 0,
        cached: 0,
        thoughts: 0,
        tool: 0
      }
    }), "createInitialModelMetrics");
    createInitialMetrics = /* @__PURE__ */ __name(() => ({
      models: {},
      tools: {
        totalCalls: 0,
        totalSuccess: 0,
        totalFail: 0,
        totalDurationMs: 0,
        totalDecisions: {
          [ToolCallDecision.ACCEPT]: 0,
          [ToolCallDecision.REJECT]: 0,
          [ToolCallDecision.MODIFY]: 0,
          [ToolCallDecision.AUTO_ACCEPT]: 0
        },
        byName: {}
      },
      files: {
        totalLinesAdded: 0,
        totalLinesRemoved: 0
      }
    }), "createInitialMetrics");
    UiTelemetryService = class extends EventEmitter4 {
      static {
        __name(this, "UiTelemetryService");
      }
      #metrics = createInitialMetrics();
      #lastPromptTokenCount = 0;
      addEvent(event) {
        switch (event["event.name"]) {
          case EVENT_API_RESPONSE:
            this.processApiResponse(event);
            break;
          case EVENT_API_ERROR:
            this.processApiError(event);
            break;
          case EVENT_TOOL_CALL:
            this.processToolCall(event);
            break;
          default:
            return;
        }
        this.emit("update", {
          metrics: this.#metrics,
          lastPromptTokenCount: this.#lastPromptTokenCount
        });
      }
      getMetrics() {
        return this.#metrics;
      }
      getLastPromptTokenCount() {
        return this.#lastPromptTokenCount;
      }
      setLastPromptTokenCount(lastPromptTokenCount) {
        this.#lastPromptTokenCount = lastPromptTokenCount;
        this.emit("update", {
          metrics: this.#metrics,
          lastPromptTokenCount: this.#lastPromptTokenCount
        });
      }
      getOrCreateModelMetrics(modelName) {
        if (!this.#metrics.models[modelName]) {
          this.#metrics.models[modelName] = createInitialModelMetrics();
        }
        return this.#metrics.models[modelName];
      }
      processApiResponse(event) {
        const modelMetrics = this.getOrCreateModelMetrics(event.model);
        modelMetrics.api.totalRequests++;
        modelMetrics.api.totalLatencyMs += event.duration_ms;
        modelMetrics.tokens.prompt += event.input_token_count;
        modelMetrics.tokens.candidates += event.output_token_count;
        modelMetrics.tokens.total += event.total_token_count;
        modelMetrics.tokens.cached += event.cached_content_token_count;
        modelMetrics.tokens.thoughts += event.thoughts_token_count;
        modelMetrics.tokens.tool += event.tool_token_count;
      }
      processApiError(event) {
        const modelMetrics = this.getOrCreateModelMetrics(event.model);
        modelMetrics.api.totalRequests++;
        modelMetrics.api.totalErrors++;
        modelMetrics.api.totalLatencyMs += event.duration_ms;
      }
      processToolCall(event) {
        const { tools, files } = this.#metrics;
        tools.totalCalls++;
        tools.totalDurationMs += event.duration_ms;
        if (event.success) {
          tools.totalSuccess++;
        } else {
          tools.totalFail++;
        }
        if (!tools.byName[event.function_name]) {
          tools.byName[event.function_name] = {
            count: 0,
            success: 0,
            fail: 0,
            durationMs: 0,
            decisions: {
              [ToolCallDecision.ACCEPT]: 0,
              [ToolCallDecision.REJECT]: 0,
              [ToolCallDecision.MODIFY]: 0,
              [ToolCallDecision.AUTO_ACCEPT]: 0
            }
          };
        }
        const toolStats = tools.byName[event.function_name];
        toolStats.count++;
        toolStats.durationMs += event.duration_ms;
        if (event.success) {
          toolStats.success++;
        } else {
          toolStats.fail++;
        }
        if (event.decision) {
          tools.totalDecisions[event.decision]++;
          toolStats.decisions[event.decision]++;
        }
        if (event.metadata) {
          if (event.metadata["model_added_lines"] !== void 0) {
            files.totalLinesAdded += event.metadata["model_added_lines"];
          }
          if (event.metadata["model_removed_lines"] !== void 0) {
            files.totalLinesRemoved += event.metadata["model_removed_lines"];
          }
        }
      }
    };
    uiTelemetryService = new UiTelemetryService();
  }
});

// packages/core/dist/src/telemetry/loggers.js
function getCommonAttributes(config) {
  const userAccountManager2 = new UserAccountManager();
  const email = userAccountManager2.getCachedGoogleAccount();
  return {
    "session.id": config.getSessionId(),
    ...email && { "user.email": email }
  };
}
function logCliConfiguration(config, event) {
  QwenLogger.getInstance(config)?.logStartSessionEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    "event.name": EVENT_CLI_CONFIG,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    model: event.model,
    embedding_model: event.embedding_model,
    sandbox_enabled: event.sandbox_enabled,
    core_tools_enabled: event.core_tools_enabled,
    approval_mode: event.approval_mode,
    api_key_enabled: event.api_key_enabled,
    vertex_ai_enabled: event.vertex_ai_enabled,
    log_user_prompts_enabled: event.telemetry_log_user_prompts_enabled,
    file_filtering_respect_git_ignore: event.file_filtering_respect_git_ignore,
    debug_mode: event.debug_enabled,
    mcp_servers: event.mcp_servers,
    mcp_servers_count: event.mcp_servers_count,
    mcp_tools: event.mcp_tools,
    mcp_tools_count: event.mcp_tools_count,
    output_format: event.output_format
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: "CLI configuration loaded.",
    attributes
  };
  logger6.emit(logRecord);
}
function logUserPrompt(config, event) {
  QwenLogger.getInstance(config)?.logNewPromptEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    "event.name": EVENT_USER_PROMPT,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    prompt_length: event.prompt_length,
    prompt_id: event.prompt_id
  };
  if (event.auth_type) {
    attributes["auth_type"] = event.auth_type;
  }
  if (shouldLogUserPrompts(config)) {
    attributes["prompt"] = event.prompt;
  }
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `User prompt. Length: ${event.prompt_length}.`,
    attributes
  };
  logger6.emit(logRecord);
}
function logToolCall(config, event) {
  const uiEvent = {
    ...event,
    "event.name": EVENT_TOOL_CALL,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  uiTelemetryService.addEvent(uiEvent);
  QwenLogger.getInstance(config)?.logToolCallEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_TOOL_CALL,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    function_args: safeJsonStringify(event.function_args, 2)
  };
  if (event.error) {
    attributes["error.message"] = event.error;
    if (event.error_type) {
      attributes["error.type"] = event.error_type;
    }
  }
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Tool call: ${event.function_name}${event.decision ? `. Decision: ${event.decision}` : ""}. Success: ${event.success}. Duration: ${event.duration_ms}ms.`,
    attributes
  };
  logger6.emit(logRecord);
  recordToolCallMetrics(config, event.duration_ms, {
    function_name: event.function_name,
    success: event.success,
    decision: event.decision,
    tool_type: event.tool_type
  });
}
function logToolOutputTruncated(config, event) {
  QwenLogger.getInstance(config)?.logToolOutputTruncatedEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": "tool_output_truncated",
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Tool output truncated for ${event.tool_name}.`,
    attributes
  };
  logger6.emit(logRecord);
}
function logFileOperation(config, event) {
  QwenLogger.getInstance(config)?.logFileOperationEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    "event.name": EVENT_FILE_OPERATION,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    tool_name: event.tool_name,
    operation: event.operation
  };
  if (event.lines) {
    attributes["lines"] = event.lines;
  }
  if (event.mimetype) {
    attributes["mimetype"] = event.mimetype;
  }
  if (event.extension) {
    attributes["extension"] = event.extension;
  }
  if (event.programming_language) {
    attributes["programming_language"] = event.programming_language;
  }
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `File operation: ${event.operation}. Lines: ${event.lines}.`,
    attributes
  };
  logger6.emit(logRecord);
  recordFileOperationMetric(config, {
    operation: event.operation,
    lines: event.lines,
    mimetype: event.mimetype,
    extension: event.extension,
    programming_language: event.programming_language
  });
}
function logApiRequest(config, event) {
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_API_REQUEST,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `API request to ${event.model}.`,
    attributes
  };
  logger6.emit(logRecord);
}
function logFlashFallback(config, event) {
  QwenLogger.getInstance(config)?.logFlashFallbackEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_FLASH_FALLBACK,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Switching to flash as Fallback.`,
    attributes
  };
  logger6.emit(logRecord);
}
function logRipgrepFallback(config, event) {
  QwenLogger.getInstance(config)?.logRipgrepFallbackEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_RIPGREP_FALLBACK,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Switching to grep as fallback.`,
    attributes
  };
  logger6.emit(logRecord);
}
function logApiError(config, event) {
  const uiEvent = {
    ...event,
    "event.name": EVENT_API_ERROR,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  uiTelemetryService.addEvent(uiEvent);
  QwenLogger.getInstance(config)?.logApiErrorEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_API_ERROR,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    ["error.message"]: event.error,
    model_name: event.model,
    duration: event.duration_ms
  };
  if (event.error_type) {
    attributes["error.type"] = event.error_type;
  }
  if (typeof event.status_code === "number") {
    attributes[SemanticAttributes.HTTP_STATUS_CODE] = event.status_code;
  }
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `API error for ${event.model}. Error: ${event.error}. Duration: ${event.duration_ms}ms.`,
    attributes
  };
  logger6.emit(logRecord);
  recordApiErrorMetrics(config, event.duration_ms, {
    model: event.model,
    status_code: event.status_code,
    error_type: event.error_type
  });
}
function logApiCancel(config, event) {
  const uiEvent = {
    ...event,
    "event.name": EVENT_API_CANCEL,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  uiTelemetryService.addEvent(uiEvent);
  QwenLogger.getInstance(config)?.logApiCancelEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_API_CANCEL,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    model_name: event.model
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `API request cancelled for ${event.model}.`,
    attributes
  };
  logger6.emit(logRecord);
}
function logApiResponse(config, event) {
  const uiEvent = {
    ...event,
    "event.name": EVENT_API_RESPONSE,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  uiTelemetryService.addEvent(uiEvent);
  QwenLogger.getInstance(config)?.logApiResponseEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_API_RESPONSE,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  if (event.response_text) {
    attributes["response_text"] = event.response_text;
  }
  if (event.status_code) {
    if (typeof event.status_code === "number") {
      attributes[SemanticAttributes.HTTP_STATUS_CODE] = event.status_code;
    }
  }
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `API response from ${event.model}. Status: ${event.status_code || "N/A"}. Duration: ${event.duration_ms}ms.`,
    attributes
  };
  logger6.emit(logRecord);
  recordApiResponseMetrics(config, event.duration_ms, {
    model: event.model,
    status_code: event.status_code
  });
  recordTokenUsageMetrics(config, event.input_token_count, {
    model: event.model,
    type: "input"
  });
  recordTokenUsageMetrics(config, event.output_token_count, {
    model: event.model,
    type: "output"
  });
  recordTokenUsageMetrics(config, event.cached_content_token_count, {
    model: event.model,
    type: "cache"
  });
  recordTokenUsageMetrics(config, event.thoughts_token_count, {
    model: event.model,
    type: "thought"
  });
  recordTokenUsageMetrics(config, event.tool_token_count, {
    model: event.model,
    type: "tool"
  });
}
function logLoopDetected(config, event) {
  QwenLogger.getInstance(config)?.logLoopDetectedEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Loop detected. Type: ${event.loop_type}.`,
    attributes
  };
  logger6.emit(logRecord);
}
function logLoopDetectionDisabled(config, _event) {
  QwenLogger.getInstance(config)?.logLoopDetectionDisabledEvent();
}
function logNextSpeakerCheck(config, event) {
  QwenLogger.getInstance(config)?.logNextSpeakerCheck(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_NEXT_SPEAKER_CHECK
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Next speaker check.`,
    attributes
  };
  logger6.emit(logRecord);
}
function logSlashCommand(config, event) {
  QwenLogger.getInstance(config)?.logSlashCommandEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_SLASH_COMMAND
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Slash command: ${event.command}.`,
    attributes
  };
  logger6.emit(logRecord);
}
function logIdeConnection(config, event) {
  QwenLogger.getInstance(config)?.logIdeConnectionEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_IDE_CONNECTION
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Ide connection. Type: ${event.connection_type}.`,
    attributes
  };
  logger6.emit(logRecord);
}
function logConversationFinishedEvent(config, event) {
  QwenLogger.getInstance(config)?.logConversationFinishedEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_CONVERSATION_FINISHED
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Conversation finished.`,
    attributes
  };
  logger6.emit(logRecord);
}
function logChatCompression(config, event) {
  QwenLogger.getInstance(config)?.logChatCompressionEvent(event);
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_CHAT_COMPRESSION
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Chat compression (Saved ${event.tokens_before - event.tokens_after} tokens)`,
    attributes
  };
  logger6.emit(logRecord);
  recordChatCompressionMetrics(config, {
    tokens_before: event.tokens_before,
    tokens_after: event.tokens_after
  });
}
function logKittySequenceOverflow(config, event) {
  QwenLogger.getInstance(config)?.logKittySequenceOverflowEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Kitty sequence buffer overflow: ${event.sequence_length} bytes`,
    attributes
  };
  logger6.emit(logRecord);
}
function logContentRetry(config, event) {
  QwenLogger.getInstance(config)?.logContentRetryEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_CONTENT_RETRY
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Content retry attempt ${event.attempt_number} due to ${event.error_type}.`,
    attributes
  };
  logger6.emit(logRecord);
  recordContentRetry(config);
}
function logContentRetryFailure(config, event) {
  QwenLogger.getInstance(config)?.logContentRetryFailureEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_CONTENT_RETRY_FAILURE
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `All content retries failed after ${event.total_attempts} attempts.`,
    attributes
  };
  logger6.emit(logRecord);
  recordContentRetryFailure(config);
}
function logSubagentExecution(config, event) {
  QwenLogger.getInstance(config)?.logSubagentExecutionEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_SUBAGENT_EXECUTION,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Subagent execution: ${event.subagent_name}.`,
    attributes
  };
  logger6.emit(logRecord);
  recordSubagentExecutionMetrics(config, event.subagent_name, event.status, event.terminate_reason);
}
function logModelSlashCommand(config, event) {
  QwenLogger.getInstance(config)?.logModelSlashCommandEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_MODEL_SLASH_COMMAND
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Model slash command. Model: ${event.model_name}`,
    attributes
  };
  logger6.emit(logRecord);
  recordModelSlashCommand(config, event);
}
function logExtensionInstallEvent(config, event) {
  QwenLogger.getInstance(config)?.logExtensionInstallEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_EXTENSION_INSTALL,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    extension_name: event.extension_name,
    extension_version: event.extension_version,
    extension_source: event.extension_source,
    status: event.status
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Installed extension ${event.extension_name}`,
    attributes
  };
  logger6.emit(logRecord);
}
function logExtensionUninstall(config, event) {
  QwenLogger.getInstance(config)?.logExtensionUninstallEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_EXTENSION_UNINSTALL,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Uninstalled extension ${event.extension_name}`,
    attributes
  };
  logger6.emit(logRecord);
}
function logExtensionEnable(config, event) {
  QwenLogger.getInstance(config)?.logExtensionEnableEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_EXTENSION_ENABLE,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Enabled extension ${event.extension_name}`,
    attributes
  };
  logger6.emit(logRecord);
}
function logExtensionDisable(config, event) {
  QwenLogger.getInstance(config)?.logExtensionDisableEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_EXTENSION_DISABLE,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Disabled extension ${event.extension_name}`,
    attributes
  };
  logger6.emit(logRecord);
}
function logAuth(config, event) {
  QwenLogger.getInstance(config)?.logAuthEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_AUTH,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    auth_type: event.auth_type,
    action_type: event.action_type,
    status: event.status
  };
  if (event.error_message) {
    attributes["error.message"] = event.error_message;
  }
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Auth event: ${event.action_type} ${event.status} for ${event.auth_type}`,
    attributes
  };
  logger6.emit(logRecord);
}
var import_api_logs, shouldLogUserPrompts;
var init_loggers = __esm({
  "packages/core/dist/src/telemetry/loggers.js"() {
    "use strict";
    init_esbuild_shims();
    import_api_logs = __toESM(require_src7(), 1);
    init_esm();
    init_safeJsonStringify();
    init_userAccountManager();
    init_constants();
    init_metrics2();
    init_qwen_logger();
    init_sdk();
    init_uiTelemetry();
    shouldLogUserPrompts = /* @__PURE__ */ __name((config) => config.getTelemetryLogPromptsEnabled(), "shouldLogUserPrompts");
    __name(getCommonAttributes, "getCommonAttributes");
    __name(logCliConfiguration, "logCliConfiguration");
    __name(logUserPrompt, "logUserPrompt");
    __name(logToolCall, "logToolCall");
    __name(logToolOutputTruncated, "logToolOutputTruncated");
    __name(logFileOperation, "logFileOperation");
    __name(logApiRequest, "logApiRequest");
    __name(logFlashFallback, "logFlashFallback");
    __name(logRipgrepFallback, "logRipgrepFallback");
    __name(logApiError, "logApiError");
    __name(logApiCancel, "logApiCancel");
    __name(logApiResponse, "logApiResponse");
    __name(logLoopDetected, "logLoopDetected");
    __name(logLoopDetectionDisabled, "logLoopDetectionDisabled");
    __name(logNextSpeakerCheck, "logNextSpeakerCheck");
    __name(logSlashCommand, "logSlashCommand");
    __name(logIdeConnection, "logIdeConnection");
    __name(logConversationFinishedEvent, "logConversationFinishedEvent");
    __name(logChatCompression, "logChatCompression");
    __name(logKittySequenceOverflow, "logKittySequenceOverflow");
    __name(logContentRetry, "logContentRetry");
    __name(logContentRetryFailure, "logContentRetryFailure");
    __name(logSubagentExecution, "logSubagentExecution");
    __name(logModelSlashCommand, "logModelSlashCommand");
    __name(logExtensionInstallEvent, "logExtensionInstallEvent");
    __name(logExtensionUninstall, "logExtensionUninstall");
    __name(logExtensionEnable, "logExtensionEnable");
    __name(logExtensionDisable, "logExtensionDisable");
    __name(logAuth, "logAuth");
  }
});

// packages/core/dist/src/utils/quotaErrorDetection.js
function isApiError(error) {
  return typeof error === "object" && error !== null && "error" in error && typeof error.error === "object" && "message" in error.error;
}
function isStructuredError(error) {
  return typeof error === "object" && error !== null && "message" in error && typeof error.message === "string";
}
function isProQuotaExceededError(error) {
  const checkMessage = /* @__PURE__ */ __name((message) => message.includes("Quota exceeded for quota metric 'Gemini") && message.includes("Pro Requests'"), "checkMessage");
  if (typeof error === "string") {
    return checkMessage(error);
  }
  if (isStructuredError(error)) {
    return checkMessage(error.message);
  }
  if (isApiError(error)) {
    return checkMessage(error.error.message);
  }
  if (error && typeof error === "object" && "response" in error) {
    const gaxiosError = error;
    if (gaxiosError.response && gaxiosError.response.data) {
      if (typeof gaxiosError.response.data === "string") {
        return checkMessage(gaxiosError.response.data);
      }
      if (typeof gaxiosError.response.data === "object" && gaxiosError.response.data !== null && "error" in gaxiosError.response.data) {
        const errorData = gaxiosError.response.data;
        return checkMessage(errorData.error?.message || "");
      }
    }
  }
  return false;
}
function isGenericQuotaExceededError(error) {
  if (typeof error === "string") {
    return error.includes("Quota exceeded for quota metric");
  }
  if (isStructuredError(error)) {
    return error.message.includes("Quota exceeded for quota metric");
  }
  if (isApiError(error)) {
    return error.error.message.includes("Quota exceeded for quota metric");
  }
  return false;
}
function isQwenQuotaExceededError(error) {
  const checkMessage = /* @__PURE__ */ __name((message) => {
    const lowerMessage = message.toLowerCase();
    return lowerMessage.includes("insufficient_quota") || lowerMessage.includes("free allocated quota exceeded") || lowerMessage.includes("quota") && lowerMessage.includes("exceeded");
  }, "checkMessage");
  if (typeof error === "string") {
    return checkMessage(error);
  }
  if (isStructuredError(error)) {
    return checkMessage(error.message);
  }
  if (isApiError(error)) {
    return checkMessage(error.error.message);
  }
  return false;
}
function isQwenThrottlingError(error) {
  const checkMessage = /* @__PURE__ */ __name((message) => {
    const lowerMessage = message.toLowerCase();
    return lowerMessage.includes("throttling") || lowerMessage.includes("requests throttling triggered") || lowerMessage.includes("rate limit") || lowerMessage.includes("too many requests");
  }, "checkMessage");
  const getStatusCode = /* @__PURE__ */ __name((error2) => {
    if (error2 && typeof error2 === "object") {
      const errorObj = error2;
      return errorObj.status || errorObj.code;
    }
    return void 0;
  }, "getStatusCode");
  const statusCode = getStatusCode(error);
  if (typeof error === "string") {
    return statusCode === 429 && checkMessage(error) || error.includes("throttling");
  }
  if (isStructuredError(error)) {
    return statusCode === 429 && checkMessage(error.message);
  }
  if (isApiError(error)) {
    return error.error.code === 429 && checkMessage(error.error.message);
  }
  return false;
}
var init_quotaErrorDetection = __esm({
  "packages/core/dist/src/utils/quotaErrorDetection.js"() {
    "use strict";
    init_esbuild_shims();
    __name(isApiError, "isApiError");
    __name(isStructuredError, "isStructuredError");
    __name(isProQuotaExceededError, "isProQuotaExceededError");
    __name(isGenericQuotaExceededError, "isGenericQuotaExceededError");
    __name(isQwenQuotaExceededError, "isQwenQuotaExceededError");
    __name(isQwenThrottlingError, "isQwenThrottlingError");
  }
});

// packages/core/dist/src/core/loggingContentGenerator.js
var LoggingContentGenerator;
var init_loggingContentGenerator = __esm({
  "packages/core/dist/src/core/loggingContentGenerator.js"() {
    "use strict";
    init_esbuild_shims();
    init_types3();
    init_loggers();
    init_converter();
    init_quotaErrorDetection();
    LoggingContentGenerator = class {
      static {
        __name(this, "LoggingContentGenerator");
      }
      wrapped;
      config;
      constructor(wrapped, config) {
        this.wrapped = wrapped;
        this.config = config;
      }
      getWrapped() {
        return this.wrapped;
      }
      logApiRequest(contents, model, promptId) {
        const requestText = JSON.stringify(contents);
        logApiRequest(this.config, new ApiRequestEvent(model, promptId, requestText));
      }
      _logApiResponse(responseId, durationMs, model, prompt_id, usageMetadata, responseText) {
        logApiResponse(this.config, new ApiResponseEvent(responseId, model, durationMs, prompt_id, this.config.getContentGeneratorConfig()?.authType, usageMetadata, responseText));
      }
      _logApiError(responseId, durationMs, error, model, prompt_id) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        const errorType = error instanceof Error ? error.name : "unknown";
        logApiError(this.config, new ApiErrorEvent(responseId, model, errorMessage, durationMs, prompt_id, this.config.getContentGeneratorConfig()?.authType, errorType, isStructuredError(error) ? error.status : void 0));
      }
      async generateContent(req, userPromptId) {
        const startTime = Date.now();
        this.logApiRequest(toContents(req.contents), req.model, userPromptId);
        try {
          const response = await this.wrapped.generateContent(req, userPromptId);
          const durationMs = Date.now() - startTime;
          this._logApiResponse(response.responseId ?? "", durationMs, response.modelVersion || req.model, userPromptId, response.usageMetadata, JSON.stringify(response));
          return response;
        } catch (error) {
          const durationMs = Date.now() - startTime;
          this._logApiError(void 0, durationMs, error, req.model, userPromptId);
          throw error;
        }
      }
      async generateContentStream(req, userPromptId) {
        const startTime = Date.now();
        this.logApiRequest(toContents(req.contents), req.model, userPromptId);
        let stream2;
        try {
          stream2 = await this.wrapped.generateContentStream(req, userPromptId);
        } catch (error) {
          const durationMs = Date.now() - startTime;
          this._logApiError(void 0, durationMs, error, req.model, userPromptId);
          throw error;
        }
        return this.loggingStreamWrapper(stream2, startTime, userPromptId, req.model);
      }
      async *loggingStreamWrapper(stream2, startTime, userPromptId, model) {
        const responses = [];
        let lastUsageMetadata;
        try {
          for await (const response of stream2) {
            responses.push(response);
            if (response.usageMetadata) {
              lastUsageMetadata = response.usageMetadata;
            }
            yield response;
          }
          const durationMs = Date.now() - startTime;
          this._logApiResponse(responses[0]?.responseId ?? "", durationMs, responses[0]?.modelVersion || model, userPromptId, lastUsageMetadata, JSON.stringify(responses));
        } catch (error) {
          const durationMs = Date.now() - startTime;
          this._logApiError(void 0, durationMs, error, responses[0]?.modelVersion || model, userPromptId);
          throw error;
        }
      }
      async countTokens(req) {
        return this.wrapped.countTokens(req);
      }
      async embedContent(req) {
        return this.wrapped.embedContent(req);
      }
    };
  }
});

// packages/core/dist/src/code_assist/codeAssist.js
async function createCodeAssistContentGenerator(httpOptions, authType, config, sessionId2) {
  if (authType === AuthType2.LOGIN_WITH_GOOGLE || authType === AuthType2.CLOUD_SHELL) {
    const authClient = await getOauthClient(authType, config);
    const userData = await setupUser(authClient);
    return new CodeAssistServer(authClient, userData.projectId, httpOptions, sessionId2, userData.userTier);
  }
  throw new Error(`Unsupported authType: ${authType}`);
}
var init_codeAssist = __esm({
  "packages/core/dist/src/code_assist/codeAssist.js"() {
    "use strict";
    init_esbuild_shims();
    init_contentGenerator();
    init_oauth2();
    init_setup();
    init_server();
    init_loggingContentGenerator();
    __name(createCodeAssistContentGenerator, "createCodeAssistContentGenerator");
  }
});

// packages/core/dist/src/config/models.js
function getEffectiveModel(isInFallbackMode, requestedModel) {
  if (!isInFallbackMode) {
    return requestedModel;
  }
  if (requestedModel.includes("lite")) {
    return requestedModel;
  }
  return DEFAULT_GEMINI_FLASH_MODEL;
}
var DEFAULT_QWEN_MODEL, DEFAULT_QWEN_EMBEDDING_MODEL, DEFAULT_GEMINI_MODEL, DEFAULT_GEMINI_FLASH_MODEL, DEFAULT_GEMINI_FLASH_LITE_MODEL, DEFAULT_GEMINI_MODEL_AUTO, DEFAULT_THINKING_MODE;
var init_models = __esm({
  "packages/core/dist/src/config/models.js"() {
    "use strict";
    init_esbuild_shims();
    DEFAULT_QWEN_MODEL = "coder-model";
    DEFAULT_QWEN_EMBEDDING_MODEL = "text-embedding-v4";
    DEFAULT_GEMINI_MODEL = "coder-model";
    DEFAULT_GEMINI_FLASH_MODEL = "gemini-2.5-flash";
    DEFAULT_GEMINI_FLASH_LITE_MODEL = "gemini-2.5-flash-lite";
    DEFAULT_GEMINI_MODEL_AUTO = "auto";
    DEFAULT_THINKING_MODE = -1;
    __name(getEffectiveModel, "getEffectiveModel");
  }
});

// node_modules/openai/internal/tslib.mjs
function __classPrivateFieldSet(receiver, state, value, kind, f) {
  if (kind === "m")
    throw new TypeError("Private method is not writable");
  if (kind === "a" && !f)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
}
function __classPrivateFieldGet(receiver, state, kind, f) {
  if (kind === "a" && !f)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
var init_tslib = __esm({
  "node_modules/openai/internal/tslib.mjs"() {
    init_esbuild_shims();
    __name(__classPrivateFieldSet, "__classPrivateFieldSet");
    __name(__classPrivateFieldGet, "__classPrivateFieldGet");
  }
});

// node_modules/openai/internal/utils/uuid.mjs
var uuid4;
var init_uuid = __esm({
  "node_modules/openai/internal/utils/uuid.mjs"() {
    init_esbuild_shims();
    uuid4 = /* @__PURE__ */ __name(function() {
      const { crypto: crypto18 } = globalThis;
      if (crypto18?.randomUUID) {
        uuid4 = crypto18.randomUUID.bind(crypto18);
        return crypto18.randomUUID();
      }
      const u8 = new Uint8Array(1);
      const randomByte = crypto18 ? () => crypto18.getRandomValues(u8)[0] : () => Math.random() * 255 & 255;
      return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c3) => (+c3 ^ randomByte() & 15 >> +c3 / 4).toString(16));
    }, "uuid4");
  }
});

// node_modules/openai/internal/errors.mjs
function isAbortError(err) {
  return typeof err === "object" && err !== null && // Spec-compliant fetch implementations
  ("name" in err && err.name === "AbortError" || // Expo fetch
  "message" in err && String(err.message).includes("FetchRequestCanceledException"));
}
var castToError;
var init_errors2 = __esm({
  "node_modules/openai/internal/errors.mjs"() {
    init_esbuild_shims();
    __name(isAbortError, "isAbortError");
    castToError = /* @__PURE__ */ __name((err) => {
      if (err instanceof Error)
        return err;
      if (typeof err === "object" && err !== null) {
        try {
          if (Object.prototype.toString.call(err) === "[object Error]") {
            const error = new Error(err.message, err.cause ? { cause: err.cause } : {});
            if (err.stack)
              error.stack = err.stack;
            if (err.cause && !error.cause)
              error.cause = err.cause;
            if (err.name)
              error.name = err.name;
            return error;
          }
        } catch {
        }
        try {
          return new Error(JSON.stringify(err));
        } catch {
        }
      }
      return new Error(err);
    }, "castToError");
  }
});

// node_modules/openai/core/error.mjs
var OpenAIError, APIError, APIUserAbortError, APIConnectionError, APIConnectionTimeoutError, BadRequestError2, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, InternalServerError, LengthFinishReasonError, ContentFilterFinishReasonError, InvalidWebhookSignatureError;
var init_error = __esm({
  "node_modules/openai/core/error.mjs"() {
    init_esbuild_shims();
    init_errors2();
    OpenAIError = class extends Error {
      static {
        __name(this, "OpenAIError");
      }
    };
    APIError = class _APIError extends OpenAIError {
      static {
        __name(this, "APIError");
      }
      constructor(status, error, message, headers) {
        super(`${_APIError.makeMessage(status, error, message)}`);
        this.status = status;
        this.headers = headers;
        this.requestID = headers?.get("x-request-id");
        this.error = error;
        const data = error;
        this.code = data?.["code"];
        this.param = data?.["param"];
        this.type = data?.["type"];
      }
      static makeMessage(status, error, message) {
        const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
        if (status && msg) {
          return `${status} ${msg}`;
        }
        if (status) {
          return `${status} status code (no body)`;
        }
        if (msg) {
          return msg;
        }
        return "(no status code or body)";
      }
      static generate(status, errorResponse, message, headers) {
        if (!status || !headers) {
          return new APIConnectionError({ message, cause: castToError(errorResponse) });
        }
        const error = errorResponse?.["error"];
        if (status === 400) {
          return new BadRequestError2(status, error, message, headers);
        }
        if (status === 401) {
          return new AuthenticationError(status, error, message, headers);
        }
        if (status === 403) {
          return new PermissionDeniedError(status, error, message, headers);
        }
        if (status === 404) {
          return new NotFoundError(status, error, message, headers);
        }
        if (status === 409) {
          return new ConflictError(status, error, message, headers);
        }
        if (status === 422) {
          return new UnprocessableEntityError(status, error, message, headers);
        }
        if (status === 429) {
          return new RateLimitError(status, error, message, headers);
        }
        if (status >= 500) {
          return new InternalServerError(status, error, message, headers);
        }
        return new _APIError(status, error, message, headers);
      }
    };
    APIUserAbortError = class extends APIError {
      static {
        __name(this, "APIUserAbortError");
      }
      constructor({ message } = {}) {
        super(void 0, void 0, message || "Request was aborted.", void 0);
      }
    };
    APIConnectionError = class extends APIError {
      static {
        __name(this, "APIConnectionError");
      }
      constructor({ message, cause }) {
        super(void 0, void 0, message || "Connection error.", void 0);
        if (cause)
          this.cause = cause;
      }
    };
    APIConnectionTimeoutError = class extends APIConnectionError {
      static {
        __name(this, "APIConnectionTimeoutError");
      }
      constructor({ message } = {}) {
        super({ message: message ?? "Request timed out." });
      }
    };
    BadRequestError2 = class extends APIError {
      static {
        __name(this, "BadRequestError");
      }
    };
    AuthenticationError = class extends APIError {
      static {
        __name(this, "AuthenticationError");
      }
    };
    PermissionDeniedError = class extends APIError {
      static {
        __name(this, "PermissionDeniedError");
      }
    };
    NotFoundError = class extends APIError {
      static {
        __name(this, "NotFoundError");
      }
    };
    ConflictError = class extends APIError {
      static {
        __name(this, "ConflictError");
      }
    };
    UnprocessableEntityError = class extends APIError {
      static {
        __name(this, "UnprocessableEntityError");
      }
    };
    RateLimitError = class extends APIError {
      static {
        __name(this, "RateLimitError");
      }
    };
    InternalServerError = class extends APIError {
      static {
        __name(this, "InternalServerError");
      }
    };
    LengthFinishReasonError = class extends OpenAIError {
      static {
        __name(this, "LengthFinishReasonError");
      }
      constructor() {
        super(`Could not parse response content as the length limit was reached`);
      }
    };
    ContentFilterFinishReasonError = class extends OpenAIError {
      static {
        __name(this, "ContentFilterFinishReasonError");
      }
      constructor() {
        super(`Could not parse response content as the request was rejected by the content filter`);
      }
    };
    InvalidWebhookSignatureError = class extends Error {
      static {
        __name(this, "InvalidWebhookSignatureError");
      }
      constructor(message) {
        super(message);
      }
    };
  }
});

// node_modules/openai/internal/utils/values.mjs
function maybeObj(x) {
  if (typeof x !== "object") {
    return {};
  }
  return x ?? {};
}
function isEmptyObj(obj) {
  if (!obj)
    return true;
  for (const _k in obj)
    return false;
  return true;
}
function hasOwn(obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key);
}
function isObj(obj) {
  return obj != null && typeof obj === "object" && !Array.isArray(obj);
}
var startsWithSchemeRegexp, isAbsoluteURL, isArray, isReadonlyArray, validatePositiveInteger, safeJSON;
var init_values = __esm({
  "node_modules/openai/internal/utils/values.mjs"() {
    init_esbuild_shims();
    init_error();
    startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
    isAbsoluteURL = /* @__PURE__ */ __name((url2) => {
      return startsWithSchemeRegexp.test(url2);
    }, "isAbsoluteURL");
    isArray = /* @__PURE__ */ __name((val) => (isArray = Array.isArray, isArray(val)), "isArray");
    isReadonlyArray = isArray;
    __name(maybeObj, "maybeObj");
    __name(isEmptyObj, "isEmptyObj");
    __name(hasOwn, "hasOwn");
    __name(isObj, "isObj");
    validatePositiveInteger = /* @__PURE__ */ __name((name3, n2) => {
      if (typeof n2 !== "number" || !Number.isInteger(n2)) {
        throw new OpenAIError(`${name3} must be an integer`);
      }
      if (n2 < 0) {
        throw new OpenAIError(`${name3} must be a positive integer`);
      }
      return n2;
    }, "validatePositiveInteger");
    safeJSON = /* @__PURE__ */ __name((text) => {
      try {
        return JSON.parse(text);
      } catch (err) {
        return void 0;
      }
    }, "safeJSON");
  }
});

// node_modules/openai/internal/utils/sleep.mjs
var sleep2;
var init_sleep = __esm({
  "node_modules/openai/internal/utils/sleep.mjs"() {
    init_esbuild_shims();
    sleep2 = /* @__PURE__ */ __name((ms) => new Promise((resolve24) => setTimeout(resolve24, ms)), "sleep");
  }
});

// node_modules/openai/version.mjs
var VERSION2;
var init_version3 = __esm({
  "node_modules/openai/version.mjs"() {
    init_esbuild_shims();
    VERSION2 = "5.11.0";
  }
});

// node_modules/openai/internal/detect-platform.mjs
function getDetectedPlatform() {
  if (typeof Deno !== "undefined" && Deno.build != null) {
    return "deno";
  }
  if (typeof EdgeRuntime !== "undefined") {
    return "edge";
  }
  if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") {
    return "node";
  }
  return "unknown";
}
function getBrowserInfo() {
  if (typeof navigator === "undefined" || !navigator) {
    return null;
  }
  const browserPatterns = [
    { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
  ];
  for (const { key, pattern } of browserPatterns) {
    const match2 = pattern.exec(navigator.userAgent);
    if (match2) {
      const major2 = match2[1] || 0;
      const minor = match2[2] || 0;
      const patch = match2[3] || 0;
      return { browser: key, version: `${major2}.${minor}.${patch}` };
    }
  }
  return null;
}
var isRunningInBrowser, getPlatformProperties, normalizeArch, normalizePlatform, _platformHeaders, getPlatformHeaders;
var init_detect_platform = __esm({
  "node_modules/openai/internal/detect-platform.mjs"() {
    init_esbuild_shims();
    init_version3();
    isRunningInBrowser = /* @__PURE__ */ __name(() => {
      return (
        // @ts-ignore
        typeof window !== "undefined" && // @ts-ignore
        typeof window.document !== "undefined" && // @ts-ignore
        typeof navigator !== "undefined"
      );
    }, "isRunningInBrowser");
    __name(getDetectedPlatform, "getDetectedPlatform");
    getPlatformProperties = /* @__PURE__ */ __name(() => {
      const detectedPlatform = getDetectedPlatform();
      if (detectedPlatform === "deno") {
        return {
          "X-Stainless-Lang": "js",
          "X-Stainless-Package-Version": VERSION2,
          "X-Stainless-OS": normalizePlatform(Deno.build.os),
          "X-Stainless-Arch": normalizeArch(Deno.build.arch),
          "X-Stainless-Runtime": "deno",
          "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown"
        };
      }
      if (typeof EdgeRuntime !== "undefined") {
        return {
          "X-Stainless-Lang": "js",
          "X-Stainless-Package-Version": VERSION2,
          "X-Stainless-OS": "Unknown",
          "X-Stainless-Arch": `other:${EdgeRuntime}`,
          "X-Stainless-Runtime": "edge",
          "X-Stainless-Runtime-Version": globalThis.process.version
        };
      }
      if (detectedPlatform === "node") {
        return {
          "X-Stainless-Lang": "js",
          "X-Stainless-Package-Version": VERSION2,
          "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"),
          "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"),
          "X-Stainless-Runtime": "node",
          "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown"
        };
      }
      const browserInfo = getBrowserInfo();
      if (browserInfo) {
        return {
          "X-Stainless-Lang": "js",
          "X-Stainless-Package-Version": VERSION2,
          "X-Stainless-OS": "Unknown",
          "X-Stainless-Arch": "unknown",
          "X-Stainless-Runtime": `browser:${browserInfo.browser}`,
          "X-Stainless-Runtime-Version": browserInfo.version
        };
      }
      return {
        "X-Stainless-Lang": "js",
        "X-Stainless-Package-Version": VERSION2,
        "X-Stainless-OS": "Unknown",
        "X-Stainless-Arch": "unknown",
        "X-Stainless-Runtime": "unknown",
        "X-Stainless-Runtime-Version": "unknown"
      };
    }, "getPlatformProperties");
    __name(getBrowserInfo, "getBrowserInfo");
    normalizeArch = /* @__PURE__ */ __name((arch3) => {
      if (arch3 === "x32")
        return "x32";
      if (arch3 === "x86_64" || arch3 === "x64")
        return "x64";
      if (arch3 === "arm")
        return "arm";
      if (arch3 === "aarch64" || arch3 === "arm64")
        return "arm64";
      if (arch3)
        return `other:${arch3}`;
      return "unknown";
    }, "normalizeArch");
    normalizePlatform = /* @__PURE__ */ __name((platform15) => {
      platform15 = platform15.toLowerCase();
      if (platform15.includes("ios"))
        return "iOS";
      if (platform15 === "android")
        return "Android";
      if (platform15 === "darwin")
        return "MacOS";
      if (platform15 === "win32")
        return "Windows";
      if (platform15 === "freebsd")
        return "FreeBSD";
      if (platform15 === "openbsd")
        return "OpenBSD";
      if (platform15 === "linux")
        return "Linux";
      if (platform15)
        return `Other:${platform15}`;
      return "Unknown";
    }, "normalizePlatform");
    getPlatformHeaders = /* @__PURE__ */ __name(() => {
      return _platformHeaders ?? (_platformHeaders = getPlatformProperties());
    }, "getPlatformHeaders");
  }
});

// node_modules/openai/internal/shims.mjs
function getDefaultFetch() {
  if (typeof fetch !== "undefined") {
    return fetch;
  }
  throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`");
}
function makeReadableStream(...args) {
  const ReadableStream2 = globalThis.ReadableStream;
  if (typeof ReadableStream2 === "undefined") {
    throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
  }
  return new ReadableStream2(...args);
}
function ReadableStreamFrom(iterable) {
  let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
  return makeReadableStream({
    start() {
    },
    async pull(controller) {
      const { done, value } = await iter.next();
      if (done) {
        controller.close();
      } else {
        controller.enqueue(value);
      }
    },
    async cancel() {
      await iter.return?.();
    }
  });
}
function ReadableStreamToAsyncIterable(stream2) {
  if (stream2[Symbol.asyncIterator])
    return stream2;
  const reader = stream2.getReader();
  return {
    async next() {
      try {
        const result = await reader.read();
        if (result?.done)
          reader.releaseLock();
        return result;
      } catch (e2) {
        reader.releaseLock();
        throw e2;
      }
    },
    async return() {
      const cancelPromise = reader.cancel();
      reader.releaseLock();
      await cancelPromise;
      return { done: true, value: void 0 };
    },
    [Symbol.asyncIterator]() {
      return this;
    }
  };
}
async function CancelReadableStream(stream2) {
  if (stream2 === null || typeof stream2 !== "object")
    return;
  if (stream2[Symbol.asyncIterator]) {
    await stream2[Symbol.asyncIterator]().return?.();
    return;
  }
  const reader = stream2.getReader();
  const cancelPromise = reader.cancel();
  reader.releaseLock();
  await cancelPromise;
}
var init_shims = __esm({
  "node_modules/openai/internal/shims.mjs"() {
    init_esbuild_shims();
    __name(getDefaultFetch, "getDefaultFetch");
    __name(makeReadableStream, "makeReadableStream");
    __name(ReadableStreamFrom, "ReadableStreamFrom");
    __name(ReadableStreamToAsyncIterable, "ReadableStreamToAsyncIterable");
    __name(CancelReadableStream, "CancelReadableStream");
  }
});

// node_modules/openai/internal/request-options.mjs
var FallbackEncoder;
var init_request_options = __esm({
  "node_modules/openai/internal/request-options.mjs"() {
    init_esbuild_shims();
    FallbackEncoder = /* @__PURE__ */ __name(({ headers, body }) => {
      return {
        bodyHeaders: {
          "content-type": "application/json"
        },
        body: JSON.stringify(body)
      };
    }, "FallbackEncoder");
  }
});

// node_modules/openai/internal/qs/formats.mjs
var default_format, default_formatter, formatters, RFC1738;
var init_formats = __esm({
  "node_modules/openai/internal/qs/formats.mjs"() {
    init_esbuild_shims();
    default_format = "RFC3986";
    default_formatter = /* @__PURE__ */ __name((v) => String(v), "default_formatter");
    formatters = {
      RFC1738: /* @__PURE__ */ __name((v) => String(v).replace(/%20/g, "+"), "RFC1738"),
      RFC3986: default_formatter
    };
    RFC1738 = "RFC1738";
  }
});

// node_modules/openai/internal/qs/utils.mjs
function is_buffer(obj) {
  if (!obj || typeof obj !== "object") {
    return false;
  }
  return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
}
function maybe_map(val, fn) {
  if (isArray(val)) {
    const mapped = [];
    for (let i = 0; i < val.length; i += 1) {
      mapped.push(fn(val[i]));
    }
    return mapped;
  }
  return fn(val);
}
var has, hex_table, limit, encode;
var init_utils4 = __esm({
  "node_modules/openai/internal/qs/utils.mjs"() {
    init_esbuild_shims();
    init_formats();
    init_values();
    has = /* @__PURE__ */ __name((obj, key) => (has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has(obj, key)), "has");
    hex_table = /* @__PURE__ */ (() => {
      const array = [];
      for (let i = 0; i < 256; ++i) {
        array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase());
      }
      return array;
    })();
    limit = 1024;
    encode = /* @__PURE__ */ __name((str2, _defaultEncoder, charset, _kind, format4) => {
      if (str2.length === 0) {
        return str2;
      }
      let string = str2;
      if (typeof str2 === "symbol") {
        string = Symbol.prototype.toString.call(str2);
      } else if (typeof str2 !== "string") {
        string = String(str2);
      }
      if (charset === "iso-8859-1") {
        return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) {
          return "%26%23" + parseInt($0.slice(2), 16) + "%3B";
        });
      }
      let out = "";
      for (let j = 0; j < string.length; j += limit) {
        const segment = string.length >= limit ? string.slice(j, j + limit) : string;
        const arr = [];
        for (let i = 0; i < segment.length; ++i) {
          let c3 = segment.charCodeAt(i);
          if (c3 === 45 || // -
          c3 === 46 || // .
          c3 === 95 || // _
          c3 === 126 || // ~
          c3 >= 48 && c3 <= 57 || // 0-9
          c3 >= 65 && c3 <= 90 || // a-z
          c3 >= 97 && c3 <= 122 || // A-Z
          format4 === RFC1738 && (c3 === 40 || c3 === 41)) {
            arr[arr.length] = segment.charAt(i);
            continue;
          }
          if (c3 < 128) {
            arr[arr.length] = hex_table[c3];
            continue;
          }
          if (c3 < 2048) {
            arr[arr.length] = hex_table[192 | c3 >> 6] + hex_table[128 | c3 & 63];
            continue;
          }
          if (c3 < 55296 || c3 >= 57344) {
            arr[arr.length] = hex_table[224 | c3 >> 12] + hex_table[128 | c3 >> 6 & 63] + hex_table[128 | c3 & 63];
            continue;
          }
          i += 1;
          c3 = 65536 + ((c3 & 1023) << 10 | segment.charCodeAt(i) & 1023);
          arr[arr.length] = hex_table[240 | c3 >> 18] + hex_table[128 | c3 >> 12 & 63] + hex_table[128 | c3 >> 6 & 63] + hex_table[128 | c3 & 63];
        }
        out += arr.join("");
      }
      return out;
    }, "encode");
    __name(is_buffer, "is_buffer");
    __name(maybe_map, "maybe_map");
  }
});

// node_modules/openai/internal/qs/stringify.mjs
function is_non_nullish_primitive(v) {
  return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint";
}
function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter4, sort, allowDots, serializeDate, format4, formatter, encodeValuesOnly, charset, sideChannel) {
  let obj = object;
  let tmp_sc = sideChannel;
  let step = 0;
  let find_flag = false;
  while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) {
    const pos2 = tmp_sc.get(object);
    step += 1;
    if (typeof pos2 !== "undefined") {
      if (pos2 === step) {
        throw new RangeError("Cyclic object value");
      } else {
        find_flag = true;
      }
    }
    if (typeof tmp_sc.get(sentinel) === "undefined") {
      step = 0;
    }
  }
  if (typeof filter4 === "function") {
    obj = filter4(prefix, obj);
  } else if (obj instanceof Date) {
    obj = serializeDate?.(obj);
  } else if (generateArrayPrefix === "comma" && isArray(obj)) {
    obj = maybe_map(obj, function(value) {
      if (value instanceof Date) {
        return serializeDate?.(value);
      }
      return value;
    });
  }
  if (obj === null) {
    if (strictNullHandling) {
      return encoder && !encodeValuesOnly ? (
        // @ts-expect-error
        encoder(prefix, defaults.encoder, charset, "key", format4)
      ) : prefix;
    }
    obj = "";
  }
  if (is_non_nullish_primitive(obj) || is_buffer(obj)) {
    if (encoder) {
      const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format4);
      return [
        formatter?.(key_value) + "=" + // @ts-expect-error
        formatter?.(encoder(obj, defaults.encoder, charset, "value", format4))
      ];
    }
    return [formatter?.(prefix) + "=" + formatter?.(String(obj))];
  }
  const values = [];
  if (typeof obj === "undefined") {
    return values;
  }
  let obj_keys;
  if (generateArrayPrefix === "comma" && isArray(obj)) {
    if (encodeValuesOnly && encoder) {
      obj = maybe_map(obj, encoder);
    }
    obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }];
  } else if (isArray(filter4)) {
    obj_keys = filter4;
  } else {
    const keys = Object.keys(obj);
    obj_keys = sort ? keys.sort(sort) : keys;
  }
  const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix);
  const adjusted_prefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix;
  if (allowEmptyArrays && isArray(obj) && obj.length === 0) {
    return adjusted_prefix + "[]";
  }
  for (let j = 0; j < obj_keys.length; ++j) {
    const key = obj_keys[j];
    const value = (
      // @ts-ignore
      typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key]
    );
    if (skipNulls && value === null) {
      continue;
    }
    const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key;
    const key_prefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]");
    sideChannel.set(object, step);
    const valueSideChannel = /* @__PURE__ */ new WeakMap();
    valueSideChannel.set(sentinel, sideChannel);
    push_to_array(values, inner_stringify(
      value,
      key_prefix,
      generateArrayPrefix,
      commaRoundTrip,
      allowEmptyArrays,
      strictNullHandling,
      skipNulls,
      encodeDotInKeys,
      // @ts-ignore
      generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder,
      filter4,
      sort,
      allowDots,
      serializeDate,
      format4,
      formatter,
      encodeValuesOnly,
      charset,
      valueSideChannel
    ));
  }
  return values;
}
function normalize_stringify_options(opts = defaults) {
  if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") {
    throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");
  }
  if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") {
    throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");
  }
  if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") {
    throw new TypeError("Encoder has to be a function.");
  }
  const charset = opts.charset || defaults.charset;
  if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") {
    throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
  }
  let format4 = default_format;
  if (typeof opts.format !== "undefined") {
    if (!has(formatters, opts.format)) {
      throw new TypeError("Unknown format option provided.");
    }
    format4 = opts.format;
  }
  const formatter = formatters[format4];
  let filter4 = defaults.filter;
  if (typeof opts.filter === "function" || isArray(opts.filter)) {
    filter4 = opts.filter;
  }
  let arrayFormat;
  if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) {
    arrayFormat = opts.arrayFormat;
  } else if ("indices" in opts) {
    arrayFormat = opts.indices ? "indices" : "repeat";
  } else {
    arrayFormat = defaults.arrayFormat;
  }
  if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") {
    throw new TypeError("`commaRoundTrip` must be a boolean, or absent");
  }
  const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots;
  return {
    addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix,
    // @ts-ignore
    allowDots,
    allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,
    arrayFormat,
    charset,
    charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel,
    commaRoundTrip: !!opts.commaRoundTrip,
    delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter,
    encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode,
    encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys,
    encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder,
    encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
    filter: filter4,
    format: format4,
    formatter,
    serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate,
    skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls,
    // @ts-ignore
    sort: typeof opts.sort === "function" ? opts.sort : null,
    strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling
  };
}
function stringify2(object, opts = {}) {
  let obj = object;
  const options2 = normalize_stringify_options(opts);
  let obj_keys;
  let filter4;
  if (typeof options2.filter === "function") {
    filter4 = options2.filter;
    obj = filter4("", obj);
  } else if (isArray(options2.filter)) {
    filter4 = options2.filter;
    obj_keys = filter4;
  }
  const keys = [];
  if (typeof obj !== "object" || obj === null) {
    return "";
  }
  const generateArrayPrefix = array_prefix_generators[options2.arrayFormat];
  const commaRoundTrip = generateArrayPrefix === "comma" && options2.commaRoundTrip;
  if (!obj_keys) {
    obj_keys = Object.keys(obj);
  }
  if (options2.sort) {
    obj_keys.sort(options2.sort);
  }
  const sideChannel = /* @__PURE__ */ new WeakMap();
  for (let i = 0; i < obj_keys.length; ++i) {
    const key = obj_keys[i];
    if (options2.skipNulls && obj[key] === null) {
      continue;
    }
    push_to_array(keys, inner_stringify(
      obj[key],
      key,
      // @ts-expect-error
      generateArrayPrefix,
      commaRoundTrip,
      options2.allowEmptyArrays,
      options2.strictNullHandling,
      options2.skipNulls,
      options2.encodeDotInKeys,
      options2.encode ? options2.encoder : null,
      options2.filter,
      options2.sort,
      options2.allowDots,
      options2.serializeDate,
      options2.format,
      options2.formatter,
      options2.encodeValuesOnly,
      options2.charset,
      sideChannel
    ));
  }
  const joined = keys.join(options2.delimiter);
  let prefix = options2.addQueryPrefix === true ? "?" : "";
  if (options2.charsetSentinel) {
    if (options2.charset === "iso-8859-1") {
      prefix += "utf8=%26%2310003%3B&";
    } else {
      prefix += "utf8=%E2%9C%93&";
    }
  }
  return joined.length > 0 ? prefix + joined : "";
}
var array_prefix_generators, push_to_array, toISOString, defaults, sentinel;
var init_stringify2 = __esm({
  "node_modules/openai/internal/qs/stringify.mjs"() {
    init_esbuild_shims();
    init_utils4();
    init_formats();
    init_values();
    array_prefix_generators = {
      brackets(prefix) {
        return String(prefix) + "[]";
      },
      comma: "comma",
      indices(prefix, key) {
        return String(prefix) + "[" + key + "]";
      },
      repeat(prefix) {
        return String(prefix);
      }
    };
    push_to_array = /* @__PURE__ */ __name(function(arr, value_or_array) {
      Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]);
    }, "push_to_array");
    defaults = {
      addQueryPrefix: false,
      allowDots: false,
      allowEmptyArrays: false,
      arrayFormat: "indices",
      charset: "utf-8",
      charsetSentinel: false,
      delimiter: "&",
      encode: true,
      encodeDotInKeys: false,
      encoder: encode,
      encodeValuesOnly: false,
      format: default_format,
      formatter: default_formatter,
      /** @deprecated */
      indices: false,
      serializeDate(date) {
        return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date);
      },
      skipNulls: false,
      strictNullHandling: false
    };
    __name(is_non_nullish_primitive, "is_non_nullish_primitive");
    sentinel = {};
    __name(inner_stringify, "inner_stringify");
    __name(normalize_stringify_options, "normalize_stringify_options");
    __name(stringify2, "stringify");
  }
});

// node_modules/openai/internal/qs/index.mjs
var init_qs = __esm({
  "node_modules/openai/internal/qs/index.mjs"() {
    init_esbuild_shims();
    init_formats();
    init_stringify2();
  }
});

// node_modules/openai/internal/utils/bytes.mjs
function concatBytes(buffers) {
  let length = 0;
  for (const buffer of buffers) {
    length += buffer.length;
  }
  const output = new Uint8Array(length);
  let index = 0;
  for (const buffer of buffers) {
    output.set(buffer, index);
    index += buffer.length;
  }
  return output;
}
function encodeUTF8(str2) {
  let encoder;
  return (encodeUTF8_ ?? (encoder = new globalThis.TextEncoder(), encodeUTF8_ = encoder.encode.bind(encoder)))(str2);
}
function decodeUTF8(bytes) {
  let decoder;
  return (decodeUTF8_ ?? (decoder = new globalThis.TextDecoder(), decodeUTF8_ = decoder.decode.bind(decoder)))(bytes);
}
var encodeUTF8_, decodeUTF8_;
var init_bytes = __esm({
  "node_modules/openai/internal/utils/bytes.mjs"() {
    init_esbuild_shims();
    __name(concatBytes, "concatBytes");
    __name(encodeUTF8, "encodeUTF8");
    __name(decodeUTF8, "decodeUTF8");
  }
});

// node_modules/openai/internal/decoders/line.mjs
function findNewlineIndex(buffer, startIndex) {
  const newline2 = 10;
  const carriage = 13;
  for (let i = startIndex ?? 0; i < buffer.length; i++) {
    if (buffer[i] === newline2) {
      return { preceding: i, index: i + 1, carriage: false };
    }
    if (buffer[i] === carriage) {
      return { preceding: i, index: i + 1, carriage: true };
    }
  }
  return null;
}
function findDoubleNewlineIndex(buffer) {
  const newline2 = 10;
  const carriage = 13;
  for (let i = 0; i < buffer.length - 1; i++) {
    if (buffer[i] === newline2 && buffer[i + 1] === newline2) {
      return i + 2;
    }
    if (buffer[i] === carriage && buffer[i + 1] === carriage) {
      return i + 2;
    }
    if (buffer[i] === carriage && buffer[i + 1] === newline2 && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline2) {
      return i + 4;
    }
  }
  return -1;
}
var _LineDecoder_buffer, _LineDecoder_carriageReturnIndex, LineDecoder;
var init_line = __esm({
  "node_modules/openai/internal/decoders/line.mjs"() {
    init_esbuild_shims();
    init_tslib();
    init_bytes();
    LineDecoder = class {
      static {
        __name(this, "LineDecoder");
      }
      constructor() {
        _LineDecoder_buffer.set(this, void 0);
        _LineDecoder_carriageReturnIndex.set(this, void 0);
        __classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f");
        __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
      }
      decode(chunk) {
        if (chunk == null) {
          return [];
        }
        const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk;
        __classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f");
        const lines = [];
        let patternIndex;
        while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) {
          if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) {
            __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f");
            continue;
          }
          if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) {
            lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1)));
            __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")), "f");
            __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
            continue;
          }
          const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
          const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex));
          lines.push(line);
          __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f");
          __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
        }
        return lines;
      }
      flush() {
        if (!__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) {
          return [];
        }
        return this.decode("\n");
      }
    };
    _LineDecoder_buffer = /* @__PURE__ */ new WeakMap(), _LineDecoder_carriageReturnIndex = /* @__PURE__ */ new WeakMap();
    LineDecoder.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]);
    LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
    __name(findNewlineIndex, "findNewlineIndex");
    __name(findDoubleNewlineIndex, "findDoubleNewlineIndex");
  }
});

// node_modules/openai/internal/utils/log.mjs
function noop2() {
}
function makeLogFn(fnLevel, logger6, logLevel) {
  if (!logger6 || levelNumbers[fnLevel] > levelNumbers[logLevel]) {
    return noop2;
  } else {
    return logger6[fnLevel].bind(logger6);
  }
}
function loggerFor(client) {
  const logger6 = client.logger;
  const logLevel = client.logLevel ?? "off";
  if (!logger6) {
    return noopLogger;
  }
  const cachedLogger = cachedLoggers.get(logger6);
  if (cachedLogger && cachedLogger[0] === logLevel) {
    return cachedLogger[1];
  }
  const levelLogger = {
    error: makeLogFn("error", logger6, logLevel),
    warn: makeLogFn("warn", logger6, logLevel),
    info: makeLogFn("info", logger6, logLevel),
    debug: makeLogFn("debug", logger6, logLevel)
  };
  cachedLoggers.set(logger6, [logLevel, levelLogger]);
  return levelLogger;
}
var levelNumbers, parseLogLevel, noopLogger, cachedLoggers, formatRequestDetails;
var init_log = __esm({
  "node_modules/openai/internal/utils/log.mjs"() {
    init_esbuild_shims();
    init_values();
    levelNumbers = {
      off: 0,
      error: 200,
      warn: 300,
      info: 400,
      debug: 500
    };
    parseLogLevel = /* @__PURE__ */ __name((maybeLevel, sourceName, client) => {
      if (!maybeLevel) {
        return void 0;
      }
      if (hasOwn(levelNumbers, maybeLevel)) {
        return maybeLevel;
      }
      loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);
      return void 0;
    }, "parseLogLevel");
    __name(noop2, "noop");
    __name(makeLogFn, "makeLogFn");
    noopLogger = {
      error: noop2,
      warn: noop2,
      info: noop2,
      debug: noop2
    };
    cachedLoggers = /* @__PURE__ */ new WeakMap();
    __name(loggerFor, "loggerFor");
    formatRequestDetails = /* @__PURE__ */ __name((details) => {
      if (details.options) {
        details.options = { ...details.options };
        delete details.options["headers"];
      }
      if (details.headers) {
        details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name3, value]) => [
          name3,
          name3.toLowerCase() === "authorization" || name3.toLowerCase() === "cookie" || name3.toLowerCase() === "set-cookie" ? "***" : value
        ]));
      }
      if ("retryOfRequestLogID" in details) {
        if (details.retryOfRequestLogID) {
          details.retryOf = details.retryOfRequestLogID;
        }
        delete details.retryOfRequestLogID;
      }
      return details;
    }, "formatRequestDetails");
  }
});

// node_modules/openai/core/streaming.mjs
async function* _iterSSEMessages(response, controller) {
  if (!response.body) {
    controller.abort();
    if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") {
      throw new OpenAIError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
    }
    throw new OpenAIError(`Attempted to iterate over a response with no body`);
  }
  const sseDecoder = new SSEDecoder();
  const lineDecoder = new LineDecoder();
  const iter = ReadableStreamToAsyncIterable(response.body);
  for await (const sseChunk of iterSSEChunks(iter)) {
    for (const line of lineDecoder.decode(sseChunk)) {
      const sse = sseDecoder.decode(line);
      if (sse)
        yield sse;
    }
  }
  for (const line of lineDecoder.flush()) {
    const sse = sseDecoder.decode(line);
    if (sse)
      yield sse;
  }
}
async function* iterSSEChunks(iterator) {
  let data = new Uint8Array();
  for await (const chunk of iterator) {
    if (chunk == null) {
      continue;
    }
    const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk;
    let newData = new Uint8Array(data.length + binaryChunk.length);
    newData.set(data);
    newData.set(binaryChunk, data.length);
    data = newData;
    let patternIndex;
    while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
      yield data.slice(0, patternIndex);
      data = data.slice(patternIndex);
    }
  }
  if (data.length > 0) {
    yield data;
  }
}
function partition(str2, delimiter2) {
  const index = str2.indexOf(delimiter2);
  if (index !== -1) {
    return [str2.substring(0, index), delimiter2, str2.substring(index + delimiter2.length)];
  }
  return [str2, "", ""];
}
var _Stream_client, Stream2, SSEDecoder;
var init_streaming = __esm({
  "node_modules/openai/core/streaming.mjs"() {
    init_esbuild_shims();
    init_tslib();
    init_error();
    init_shims();
    init_line();
    init_shims();
    init_errors2();
    init_bytes();
    init_log();
    init_error();
    Stream2 = class _Stream {
      static {
        __name(this, "Stream");
      }
      constructor(iterator, controller, client) {
        this.iterator = iterator;
        _Stream_client.set(this, void 0);
        this.controller = controller;
        __classPrivateFieldSet(this, _Stream_client, client, "f");
      }
      static fromSSEResponse(response, controller, client) {
        let consumed = false;
        const logger6 = client ? loggerFor(client) : console;
        async function* iterator() {
          if (consumed) {
            throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
          }
          consumed = true;
          let done = false;
          try {
            for await (const sse of _iterSSEMessages(response, controller)) {
              if (done)
                continue;
              if (sse.data.startsWith("[DONE]")) {
                done = true;
                continue;
              }
              if (sse.event === null || !sse.event.startsWith("thread.")) {
                let data;
                try {
                  data = JSON.parse(sse.data);
                } catch (e2) {
                  logger6.error(`Could not parse message into JSON:`, sse.data);
                  logger6.error(`From chunk:`, sse.raw);
                  throw e2;
                }
                if (data && data.error) {
                  throw new APIError(void 0, data.error, void 0, response.headers);
                }
                yield data;
              } else {
                let data;
                try {
                  data = JSON.parse(sse.data);
                } catch (e2) {
                  console.error(`Could not parse message into JSON:`, sse.data);
                  console.error(`From chunk:`, sse.raw);
                  throw e2;
                }
                if (sse.event == "error") {
                  throw new APIError(void 0, data.error, data.message, void 0);
                }
                yield { event: sse.event, data };
              }
            }
            done = true;
          } catch (e2) {
            if (isAbortError(e2))
              return;
            throw e2;
          } finally {
            if (!done)
              controller.abort();
          }
        }
        __name(iterator, "iterator");
        return new _Stream(iterator, controller, client);
      }
      /**
       * Generates a Stream from a newline-separated ReadableStream
       * where each item is a JSON value.
       */
      static fromReadableStream(readableStream, controller, client) {
        let consumed = false;
        async function* iterLines() {
          const lineDecoder = new LineDecoder();
          const iter = ReadableStreamToAsyncIterable(readableStream);
          for await (const chunk of iter) {
            for (const line of lineDecoder.decode(chunk)) {
              yield line;
            }
          }
          for (const line of lineDecoder.flush()) {
            yield line;
          }
        }
        __name(iterLines, "iterLines");
        async function* iterator() {
          if (consumed) {
            throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
          }
          consumed = true;
          let done = false;
          try {
            for await (const line of iterLines()) {
              if (done)
                continue;
              if (line)
                yield JSON.parse(line);
            }
            done = true;
          } catch (e2) {
            if (isAbortError(e2))
              return;
            throw e2;
          } finally {
            if (!done)
              controller.abort();
          }
        }
        __name(iterator, "iterator");
        return new _Stream(iterator, controller, client);
      }
      [(_Stream_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
        return this.iterator();
      }
      /**
       * Splits the stream into two streams which can be
       * independently read from at different speeds.
       */
      tee() {
        const left3 = [];
        const right3 = [];
        const iterator = this.iterator();
        const teeIterator = /* @__PURE__ */ __name((queue) => {
          return {
            next: /* @__PURE__ */ __name(() => {
              if (queue.length === 0) {
                const result = iterator.next();
                left3.push(result);
                right3.push(result);
              }
              return queue.shift();
            }, "next")
          };
        }, "teeIterator");
        return [
          new _Stream(() => teeIterator(left3), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")),
          new _Stream(() => teeIterator(right3), this.controller, __classPrivateFieldGet(this, _Stream_client, "f"))
        ];
      }
      /**
       * Converts this stream to a newline-separated ReadableStream of
       * JSON stringified values in the stream
       * which can be turned back into a Stream with `Stream.fromReadableStream()`.
       */
      toReadableStream() {
        const self2 = this;
        let iter;
        return makeReadableStream({
          async start() {
            iter = self2[Symbol.asyncIterator]();
          },
          async pull(ctrl) {
            try {
              const { value, done } = await iter.next();
              if (done)
                return ctrl.close();
              const bytes = encodeUTF8(JSON.stringify(value) + "\n");
              ctrl.enqueue(bytes);
            } catch (err) {
              ctrl.error(err);
            }
          },
          async cancel() {
            await iter.return?.();
          }
        });
      }
    };
    __name(_iterSSEMessages, "_iterSSEMessages");
    __name(iterSSEChunks, "iterSSEChunks");
    SSEDecoder = class {
      static {
        __name(this, "SSEDecoder");
      }
      constructor() {
        this.event = null;
        this.data = [];
        this.chunks = [];
      }
      decode(line) {
        if (line.endsWith("\r")) {
          line = line.substring(0, line.length - 1);
        }
        if (!line) {
          if (!this.event && !this.data.length)
            return null;
          const sse = {
            event: this.event,
            data: this.data.join("\n"),
            raw: this.chunks
          };
          this.event = null;
          this.data = [];
          this.chunks = [];
          return sse;
        }
        this.chunks.push(line);
        if (line.startsWith(":")) {
          return null;
        }
        let [fieldname, _, value] = partition(line, ":");
        if (value.startsWith(" ")) {
          value = value.substring(1);
        }
        if (fieldname === "event") {
          this.event = value;
        } else if (fieldname === "data") {
          this.data.push(value);
        }
        return null;
      }
    };
    __name(partition, "partition");
  }
});

// node_modules/openai/internal/parse.mjs
async function defaultParseResponse(client, props) {
  const { response, requestLogID, retryOfRequestLogID, startTime } = props;
  const body = await (async () => {
    if (props.options.stream) {
      loggerFor(client).debug("response", response.status, response.url, response.headers, response.body);
      if (props.options.__streamClass) {
        return props.options.__streamClass.fromSSEResponse(response, props.controller, client);
      }
      return Stream2.fromSSEResponse(response, props.controller, client);
    }
    if (response.status === 204) {
      return null;
    }
    if (props.options.__binaryResponse) {
      return response;
    }
    const contentType = response.headers.get("content-type");
    const mediaType = contentType?.split(";")[0]?.trim();
    const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json");
    if (isJSON) {
      const json2 = await response.json();
      return addRequestID(json2, response);
    }
    const text = await response.text();
    return text;
  })();
  loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({
    retryOfRequestLogID,
    url: response.url,
    status: response.status,
    body,
    durationMs: Date.now() - startTime
  }));
  return body;
}
function addRequestID(value, response) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return value;
  }
  return Object.defineProperty(value, "_request_id", {
    value: response.headers.get("x-request-id"),
    enumerable: false
  });
}
var init_parse2 = __esm({
  "node_modules/openai/internal/parse.mjs"() {
    init_esbuild_shims();
    init_streaming();
    init_log();
    __name(defaultParseResponse, "defaultParseResponse");
    __name(addRequestID, "addRequestID");
  }
});

// node_modules/openai/core/api-promise.mjs
var _APIPromise_client, APIPromise;
var init_api_promise = __esm({
  "node_modules/openai/core/api-promise.mjs"() {
    init_esbuild_shims();
    init_tslib();
    init_parse2();
    APIPromise = class _APIPromise extends Promise {
      static {
        __name(this, "APIPromise");
      }
      constructor(client, responsePromise, parseResponse2 = defaultParseResponse) {
        super((resolve24) => {
          resolve24(null);
        });
        this.responsePromise = responsePromise;
        this.parseResponse = parseResponse2;
        _APIPromise_client.set(this, void 0);
        __classPrivateFieldSet(this, _APIPromise_client, client, "f");
      }
      _thenUnwrap(transform) {
        return new _APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response));
      }
      /**
       * Gets the raw `Response` instance instead of parsing the response
       * data.
       *
       * If you want to parse the response body but still get the `Response`
       * instance, you can use {@link withResponse()}.
       *
       * 👋 Getting the wrong TypeScript type for `Response`?
       * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
       * to your `tsconfig.json`.
       */
      asResponse() {
        return this.responsePromise.then((p) => p.response);
      }
      /**
       * Gets the parsed response data, the raw `Response` instance and the ID of the request,
       * returned via the X-Request-ID header which is useful for debugging requests and reporting
       * issues to OpenAI.
       *
       * If you just want to get the raw `Response` instance without parsing it,
       * you can use {@link asResponse()}.
       *
       * 👋 Getting the wrong TypeScript type for `Response`?
       * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
       * to your `tsconfig.json`.
       */
      async withResponse() {
        const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
        return { data, response, request_id: response.headers.get("x-request-id") };
      }
      parse() {
        if (!this.parsedPromise) {
          this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data));
        }
        return this.parsedPromise;
      }
      then(onfulfilled, onrejected) {
        return this.parse().then(onfulfilled, onrejected);
      }
      catch(onrejected) {
        return this.parse().catch(onrejected);
      }
      finally(onfinally) {
        return this.parse().finally(onfinally);
      }
    };
    _APIPromise_client = /* @__PURE__ */ new WeakMap();
  }
});

// node_modules/openai/core/pagination.mjs
var _AbstractPage_client, AbstractPage, PagePromise, Page, CursorPage;
var init_pagination = __esm({
  "node_modules/openai/core/pagination.mjs"() {
    init_esbuild_shims();
    init_tslib();
    init_error();
    init_parse2();
    init_api_promise();
    init_values();
    AbstractPage = class {
      static {
        __name(this, "AbstractPage");
      }
      constructor(client, response, body, options2) {
        _AbstractPage_client.set(this, void 0);
        __classPrivateFieldSet(this, _AbstractPage_client, client, "f");
        this.options = options2;
        this.response = response;
        this.body = body;
      }
      hasNextPage() {
        const items = this.getPaginatedItems();
        if (!items.length)
          return false;
        return this.nextPageRequestOptions() != null;
      }
      async getNextPage() {
        const nextOptions = this.nextPageRequestOptions();
        if (!nextOptions) {
          throw new OpenAIError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
        }
        return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
      }
      async *iterPages() {
        let page = this;
        yield page;
        while (page.hasNextPage()) {
          page = await page.getNextPage();
          yield page;
        }
      }
      async *[(_AbstractPage_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
        for await (const page of this.iterPages()) {
          for (const item of page.getPaginatedItems()) {
            yield item;
          }
        }
      }
    };
    PagePromise = class extends APIPromise {
      static {
        __name(this, "PagePromise");
      }
      constructor(client, request4, Page2) {
        super(client, request4, async (client2, props) => new Page2(client2, props.response, await defaultParseResponse(client2, props), props.options));
      }
      /**
       * Allow auto-paginating iteration on an unawaited list call, eg:
       *
       *    for await (const item of client.items.list()) {
       *      console.log(item)
       *    }
       */
      async *[Symbol.asyncIterator]() {
        const page = await this;
        for await (const item of page) {
          yield item;
        }
      }
    };
    Page = class extends AbstractPage {
      static {
        __name(this, "Page");
      }
      constructor(client, response, body, options2) {
        super(client, response, body, options2);
        this.data = body.data || [];
        this.object = body.object;
      }
      getPaginatedItems() {
        return this.data ?? [];
      }
      nextPageRequestOptions() {
        return null;
      }
    };
    CursorPage = class extends AbstractPage {
      static {
        __name(this, "CursorPage");
      }
      constructor(client, response, body, options2) {
        super(client, response, body, options2);
        this.data = body.data || [];
        this.has_more = body.has_more || false;
      }
      getPaginatedItems() {
        return this.data ?? [];
      }
      hasNextPage() {
        if (this.has_more === false) {
          return false;
        }
        return super.hasNextPage();
      }
      nextPageRequestOptions() {
        const data = this.getPaginatedItems();
        const id = data[data.length - 1]?.id;
        if (!id) {
          return null;
        }
        return {
          ...this.options,
          query: {
            ...maybeObj(this.options.query),
            after: id
          }
        };
      }
    };
  }
});

// node_modules/openai/internal/uploads.mjs
function makeFile(fileBits, fileName, options2) {
  checkFileSupport();
  return new File(fileBits, fileName ?? "unknown_file", options2);
}
function getName(value) {
  return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0;
}
function supportsFormData(fetchObject) {
  const fetch2 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch;
  const cached = supportsFormDataMap.get(fetch2);
  if (cached)
    return cached;
  const promise = (async () => {
    try {
      const FetchResponse = "Response" in fetch2 ? fetch2.Response : (await fetch2("data:,")).constructor;
      const data = new FormData();
      if (data.toString() === await new FetchResponse(data).text()) {
        return false;
      }
      return true;
    } catch {
      return true;
    }
  })();
  supportsFormDataMap.set(fetch2, promise);
  return promise;
}
var checkFileSupport, isAsyncIterable, multipartFormRequestOptions, supportsFormDataMap, createForm, isNamedBlob, addFormValue;
var init_uploads = __esm({
  "node_modules/openai/internal/uploads.mjs"() {
    init_esbuild_shims();
    init_shims();
    checkFileSupport = /* @__PURE__ */ __name(() => {
      if (typeof File === "undefined") {
        const { process: process51 } = globalThis;
        const isOldNode = typeof process51?.versions?.node === "string" && parseInt(process51.versions.node.split(".")) < 20;
        throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : ""));
      }
    }, "checkFileSupport");
    __name(makeFile, "makeFile");
    __name(getName, "getName");
    isAsyncIterable = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", "isAsyncIterable");
    multipartFormRequestOptions = /* @__PURE__ */ __name(async (opts, fetch2) => {
      return { ...opts, body: await createForm(opts.body, fetch2) };
    }, "multipartFormRequestOptions");
    supportsFormDataMap = /* @__PURE__ */ new WeakMap();
    __name(supportsFormData, "supportsFormData");
    createForm = /* @__PURE__ */ __name(async (body, fetch2) => {
      if (!await supportsFormData(fetch2)) {
        throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");
      }
      const form = new FormData();
      await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
      return form;
    }, "createForm");
    isNamedBlob = /* @__PURE__ */ __name((value) => value instanceof Blob && "name" in value, "isNamedBlob");
    addFormValue = /* @__PURE__ */ __name(async (form, key, value) => {
      if (value === void 0)
        return;
      if (value == null) {
        throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
      }
      if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
        form.append(key, String(value));
      } else if (value instanceof Response) {
        form.append(key, makeFile([await value.blob()], getName(value)));
      } else if (isAsyncIterable(value)) {
        form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value)));
      } else if (isNamedBlob(value)) {
        form.append(key, value, getName(value));
      } else if (Array.isArray(value)) {
        await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry)));
      } else if (typeof value === "object") {
        await Promise.all(Object.entries(value).map(([name3, prop]) => addFormValue(form, `${key}[${name3}]`, prop)));
      } else {
        throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
      }
    }, "addFormValue");
  }
});

// node_modules/openai/internal/to-file.mjs
async function toFile(value, name3, options2) {
  checkFileSupport();
  value = await value;
  if (isFileLike(value)) {
    if (value instanceof File) {
      return value;
    }
    return makeFile([await value.arrayBuffer()], value.name);
  }
  if (isResponseLike(value)) {
    const blob = await value.blob();
    name3 || (name3 = new URL(value.url).pathname.split(/[\\/]/).pop());
    return makeFile(await getBytes(blob), name3, options2);
  }
  const parts = await getBytes(value);
  name3 || (name3 = getName(value));
  if (!options2?.type) {
    const type = parts.find((part) => typeof part === "object" && "type" in part && part.type);
    if (typeof type === "string") {
      options2 = { ...options2, type };
    }
  }
  return makeFile(parts, name3, options2);
}
async function getBytes(value) {
  let parts = [];
  if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
  value instanceof ArrayBuffer) {
    parts.push(value);
  } else if (isBlobLike(value)) {
    parts.push(value instanceof Blob ? value : await value.arrayBuffer());
  } else if (isAsyncIterable(value)) {
    for await (const chunk of value) {
      parts.push(...await getBytes(chunk));
    }
  } else {
    const constructor = value?.constructor?.name;
    throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`);
  }
  return parts;
}
function propsForError(value) {
  if (typeof value !== "object" || value === null)
    return "";
  const props = Object.getOwnPropertyNames(value);
  return `; props: [${props.map((p) => `"${p}"`).join(", ")}]`;
}
var isBlobLike, isFileLike, isResponseLike;
var init_to_file = __esm({
  "node_modules/openai/internal/to-file.mjs"() {
    init_esbuild_shims();
    init_uploads();
    init_uploads();
    isBlobLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function", "isBlobLike");
    isFileLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value), "isFileLike");
    isResponseLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function", "isResponseLike");
    __name(toFile, "toFile");
    __name(getBytes, "getBytes");
    __name(propsForError, "propsForError");
  }
});

// node_modules/openai/core/uploads.mjs
var init_uploads2 = __esm({
  "node_modules/openai/core/uploads.mjs"() {
    init_esbuild_shims();
    init_to_file();
  }
});

// node_modules/openai/core/resource.mjs
var APIResource;
var init_resource2 = __esm({
  "node_modules/openai/core/resource.mjs"() {
    init_esbuild_shims();
    APIResource = class {
      static {
        __name(this, "APIResource");
      }
      constructor(client) {
        this._client = client;
      }
    };
  }
});

// node_modules/openai/internal/utils/path.mjs
function encodeURIPath(str2) {
  return str2.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
}
var EMPTY, createPathTagFunction, path11;
var init_path = __esm({
  "node_modules/openai/internal/utils/path.mjs"() {
    init_esbuild_shims();
    init_error();
    __name(encodeURIPath, "encodeURIPath");
    EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
    createPathTagFunction = /* @__PURE__ */ __name((pathEncoder = encodeURIPath) => /* @__PURE__ */ __name(function path108(statics, ...params) {
      if (statics.length === 1)
        return statics[0];
      let postPath = false;
      const invalidSegments = [];
      const path109 = statics.reduce((previousValue, currentValue, index) => {
        if (/[?#]/.test(currentValue)) {
          postPath = true;
        }
        const value = params[index];
        let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value);
        if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms
        value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) {
          encoded = value + "";
          invalidSegments.push({
            start: previousValue.length + currentValue.length,
            length: encoded.length,
            error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter`
          });
        }
        return previousValue + currentValue + (index === params.length ? "" : encoded);
      }, "");
      const pathOnly = path109.split(/[?#]/, 1)[0];
      const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
      let match2;
      while ((match2 = invalidSegmentPattern.exec(pathOnly)) !== null) {
        invalidSegments.push({
          start: match2.index,
          length: match2[0].length,
          error: `Value "${match2[0]}" can't be safely passed as a path parameter`
        });
      }
      invalidSegments.sort((a, b) => a.start - b.start);
      if (invalidSegments.length > 0) {
        let lastEnd = 0;
        const underline = invalidSegments.reduce((acc, segment) => {
          const spaces = " ".repeat(segment.start - lastEnd);
          const arrows = "^".repeat(segment.length);
          lastEnd = segment.start + segment.length;
          return acc + spaces + arrows;
        }, "");
        throw new OpenAIError(`Path parameters result in path with invalid segments:
${invalidSegments.map((e2) => e2.error).join("\n")}
${path109}
${underline}`);
      }
      return path109;
    }, "path"), "createPathTagFunction");
    path11 = /* @__PURE__ */ createPathTagFunction(encodeURIPath);
  }
});

// node_modules/openai/resources/chat/completions/messages.mjs
var Messages;
var init_messages = __esm({
  "node_modules/openai/resources/chat/completions/messages.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_pagination();
    init_path();
    Messages = class extends APIResource {
      static {
        __name(this, "Messages");
      }
      /**
       * Get the messages in a stored chat completion. Only Chat Completions that have
       * been created with the `store` parameter set to `true` will be returned.
       *
       * @example
       * ```ts
       * // Automatically fetches more pages as needed.
       * for await (const chatCompletionStoreMessage of client.chat.completions.messages.list(
       *   'completion_id',
       * )) {
       *   // ...
       * }
       * ```
       */
      list(completionID, query = {}, options2) {
        return this._client.getAPIList(path11`/chat/completions/${completionID}/messages`, CursorPage, { query, ...options2 });
      }
    };
  }
});

// node_modules/openai/error.mjs
var init_error2 = __esm({
  "node_modules/openai/error.mjs"() {
    init_esbuild_shims();
    init_error();
  }
});

// node_modules/openai/lib/RunnableFunction.mjs
function isRunnableFunctionWithParse(fn) {
  return typeof fn.parse === "function";
}
var init_RunnableFunction = __esm({
  "node_modules/openai/lib/RunnableFunction.mjs"() {
    init_esbuild_shims();
    __name(isRunnableFunctionWithParse, "isRunnableFunctionWithParse");
  }
});

// node_modules/openai/lib/chatCompletionUtils.mjs
var isAssistantMessage, isToolMessage;
var init_chatCompletionUtils = __esm({
  "node_modules/openai/lib/chatCompletionUtils.mjs"() {
    init_esbuild_shims();
    isAssistantMessage = /* @__PURE__ */ __name((message) => {
      return message?.role === "assistant";
    }, "isAssistantMessage");
    isToolMessage = /* @__PURE__ */ __name((message) => {
      return message?.role === "tool";
    }, "isToolMessage");
  }
});

// node_modules/openai/lib/EventStream.mjs
var _EventStream_instances, _EventStream_connectedPromise, _EventStream_resolveConnectedPromise, _EventStream_rejectConnectedPromise, _EventStream_endPromise, _EventStream_resolveEndPromise, _EventStream_rejectEndPromise, _EventStream_listeners, _EventStream_ended, _EventStream_errored, _EventStream_aborted, _EventStream_catchingPromiseCreated, _EventStream_handleError, EventStream;
var init_EventStream = __esm({
  "node_modules/openai/lib/EventStream.mjs"() {
    init_esbuild_shims();
    init_tslib();
    init_error2();
    EventStream = class {
      static {
        __name(this, "EventStream");
      }
      constructor() {
        _EventStream_instances.add(this);
        this.controller = new AbortController();
        _EventStream_connectedPromise.set(this, void 0);
        _EventStream_resolveConnectedPromise.set(this, () => {
        });
        _EventStream_rejectConnectedPromise.set(this, () => {
        });
        _EventStream_endPromise.set(this, void 0);
        _EventStream_resolveEndPromise.set(this, () => {
        });
        _EventStream_rejectEndPromise.set(this, () => {
        });
        _EventStream_listeners.set(this, {});
        _EventStream_ended.set(this, false);
        _EventStream_errored.set(this, false);
        _EventStream_aborted.set(this, false);
        _EventStream_catchingPromiseCreated.set(this, false);
        __classPrivateFieldSet(this, _EventStream_connectedPromise, new Promise((resolve24, reject) => {
          __classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve24, "f");
          __classPrivateFieldSet(this, _EventStream_rejectConnectedPromise, reject, "f");
        }), "f");
        __classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve24, reject) => {
          __classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve24, "f");
          __classPrivateFieldSet(this, _EventStream_rejectEndPromise, reject, "f");
        }), "f");
        __classPrivateFieldGet(this, _EventStream_connectedPromise, "f").catch(() => {
        });
        __classPrivateFieldGet(this, _EventStream_endPromise, "f").catch(() => {
        });
      }
      _run(executor) {
        setTimeout(() => {
          executor().then(() => {
            this._emitFinal();
            this._emit("end");
          }, __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).bind(this));
        }, 0);
      }
      _connected() {
        if (this.ended)
          return;
        __classPrivateFieldGet(this, _EventStream_resolveConnectedPromise, "f").call(this);
        this._emit("connect");
      }
      get ended() {
        return __classPrivateFieldGet(this, _EventStream_ended, "f");
      }
      get errored() {
        return __classPrivateFieldGet(this, _EventStream_errored, "f");
      }
      get aborted() {
        return __classPrivateFieldGet(this, _EventStream_aborted, "f");
      }
      abort() {
        this.controller.abort();
      }
      /**
       * Adds the listener function to the end of the listeners array for the event.
       * No checks are made to see if the listener has already been added. Multiple calls passing
       * the same combination of event and listener will result in the listener being added, and
       * called, multiple times.
       * @returns this ChatCompletionStream, so that calls can be chained
       */
      on(event, listener) {
        const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []);
        listeners.push({ listener });
        return this;
      }
      /**
       * Removes the specified listener from the listener array for the event.
       * off() will remove, at most, one instance of a listener from the listener array. If any single
       * listener has been added multiple times to the listener array for the specified event, then
       * off() must be called multiple times to remove each instance.
       * @returns this ChatCompletionStream, so that calls can be chained
       */
      off(event, listener) {
        const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event];
        if (!listeners)
          return this;
        const index = listeners.findIndex((l2) => l2.listener === listener);
        if (index >= 0)
          listeners.splice(index, 1);
        return this;
      }
      /**
       * Adds a one-time listener function for the event. The next time the event is triggered,
       * this listener is removed and then invoked.
       * @returns this ChatCompletionStream, so that calls can be chained
       */
      once(event, listener) {
        const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []);
        listeners.push({ listener, once: true });
        return this;
      }
      /**
       * This is similar to `.once()`, but returns a Promise that resolves the next time
       * the event is triggered, instead of calling a listener callback.
       * @returns a Promise that resolves the next time given event is triggered,
       * or rejects if an error is emitted.  (If you request the 'error' event,
       * returns a promise that resolves with the error).
       *
       * Example:
       *
       *   const message = await stream.emitted('message') // rejects if the stream errors
       */
      emitted(event) {
        return new Promise((resolve24, reject) => {
          __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f");
          if (event !== "error")
            this.once("error", reject);
          this.once(event, resolve24);
        });
      }
      async done() {
        __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f");
        await __classPrivateFieldGet(this, _EventStream_endPromise, "f");
      }
      _emit(event, ...args) {
        if (__classPrivateFieldGet(this, _EventStream_ended, "f")) {
          return;
        }
        if (event === "end") {
          __classPrivateFieldSet(this, _EventStream_ended, true, "f");
          __classPrivateFieldGet(this, _EventStream_resolveEndPromise, "f").call(this);
        }
        const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event];
        if (listeners) {
          __classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = listeners.filter((l2) => !l2.once);
          listeners.forEach(({ listener }) => listener(...args));
        }
        if (event === "abort") {
          const error = args[0];
          if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
            Promise.reject(error);
          }
          __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
          __classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error);
          this._emit("end");
          return;
        }
        if (event === "error") {
          const error = args[0];
          if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
            Promise.reject(error);
          }
          __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
          __classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error);
          this._emit("end");
        }
      }
      _emitFinal() {
      }
    };
    _EventStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_endPromise = /* @__PURE__ */ new WeakMap(), _EventStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _EventStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _EventStream_listeners = /* @__PURE__ */ new WeakMap(), _EventStream_ended = /* @__PURE__ */ new WeakMap(), _EventStream_errored = /* @__PURE__ */ new WeakMap(), _EventStream_aborted = /* @__PURE__ */ new WeakMap(), _EventStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _EventStream_instances = /* @__PURE__ */ new WeakSet(), _EventStream_handleError = /* @__PURE__ */ __name(function _EventStream_handleError2(error) {
      __classPrivateFieldSet(this, _EventStream_errored, true, "f");
      if (error instanceof Error && error.name === "AbortError") {
        error = new APIUserAbortError();
      }
      if (error instanceof APIUserAbortError) {
        __classPrivateFieldSet(this, _EventStream_aborted, true, "f");
        return this._emit("abort", error);
      }
      if (error instanceof OpenAIError) {
        return this._emit("error", error);
      }
      if (error instanceof Error) {
        const openAIError = new OpenAIError(error.message);
        openAIError.cause = error;
        return this._emit("error", openAIError);
      }
      return this._emit("error", new OpenAIError(String(error)));
    }, "_EventStream_handleError");
  }
});

// node_modules/openai/lib/parser.mjs
function isAutoParsableResponseFormat(response_format) {
  return response_format?.["$brand"] === "auto-parseable-response-format";
}
function isAutoParsableTool(tool) {
  return tool?.["$brand"] === "auto-parseable-tool";
}
function maybeParseChatCompletion(completion3, params) {
  if (!params || !hasAutoParseableInput(params)) {
    return {
      ...completion3,
      choices: completion3.choices.map((choice2) => ({
        ...choice2,
        message: {
          ...choice2.message,
          parsed: null,
          ...choice2.message.tool_calls ? {
            tool_calls: choice2.message.tool_calls
          } : void 0
        }
      }))
    };
  }
  return parseChatCompletion(completion3, params);
}
function parseChatCompletion(completion3, params) {
  const choices = completion3.choices.map((choice2) => {
    if (choice2.finish_reason === "length") {
      throw new LengthFinishReasonError();
    }
    if (choice2.finish_reason === "content_filter") {
      throw new ContentFilterFinishReasonError();
    }
    return {
      ...choice2,
      message: {
        ...choice2.message,
        ...choice2.message.tool_calls ? {
          tool_calls: choice2.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? void 0
        } : void 0,
        parsed: choice2.message.content && !choice2.message.refusal ? parseResponseFormat(params, choice2.message.content) : null
      }
    };
  });
  return { ...completion3, choices };
}
function parseResponseFormat(params, content) {
  if (params.response_format?.type !== "json_schema") {
    return null;
  }
  if (params.response_format?.type === "json_schema") {
    if ("$parseRaw" in params.response_format) {
      const response_format = params.response_format;
      return response_format.$parseRaw(content);
    }
    return JSON.parse(content);
  }
  return null;
}
function parseToolCall(params, toolCall) {
  const inputTool = params.tools?.find((inputTool2) => inputTool2.function?.name === toolCall.function.name);
  return {
    ...toolCall,
    function: {
      ...toolCall.function,
      parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments) : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments) : null
    }
  };
}
function shouldParseToolCall(params, toolCall) {
  if (!params) {
    return false;
  }
  const inputTool = params.tools?.find((inputTool2) => inputTool2.function?.name === toolCall.function.name);
  return isAutoParsableTool(inputTool) || inputTool?.function.strict || false;
}
function hasAutoParseableInput(params) {
  if (isAutoParsableResponseFormat(params.response_format)) {
    return true;
  }
  return params.tools?.some((t2) => isAutoParsableTool(t2) || t2.type === "function" && t2.function.strict === true) ?? false;
}
function validateInputTools(tools) {
  for (const tool of tools ?? []) {
    if (tool.type !== "function") {
      throw new OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``);
    }
    if (tool.function.strict !== true) {
      throw new OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`);
    }
  }
}
var init_parser = __esm({
  "node_modules/openai/lib/parser.mjs"() {
    init_esbuild_shims();
    init_error2();
    __name(isAutoParsableResponseFormat, "isAutoParsableResponseFormat");
    __name(isAutoParsableTool, "isAutoParsableTool");
    __name(maybeParseChatCompletion, "maybeParseChatCompletion");
    __name(parseChatCompletion, "parseChatCompletion");
    __name(parseResponseFormat, "parseResponseFormat");
    __name(parseToolCall, "parseToolCall");
    __name(shouldParseToolCall, "shouldParseToolCall");
    __name(hasAutoParseableInput, "hasAutoParseableInput");
    __name(validateInputTools, "validateInputTools");
  }
});

// node_modules/openai/lib/AbstractChatCompletionRunner.mjs
var _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionToolCall, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult, DEFAULT_MAX_CHAT_COMPLETIONS, AbstractChatCompletionRunner;
var init_AbstractChatCompletionRunner = __esm({
  "node_modules/openai/lib/AbstractChatCompletionRunner.mjs"() {
    init_esbuild_shims();
    init_tslib();
    init_error2();
    init_RunnableFunction();
    init_chatCompletionUtils();
    init_EventStream();
    init_parser();
    DEFAULT_MAX_CHAT_COMPLETIONS = 10;
    AbstractChatCompletionRunner = class extends EventStream {
      static {
        __name(this, "AbstractChatCompletionRunner");
      }
      constructor() {
        super(...arguments);
        _AbstractChatCompletionRunner_instances.add(this);
        this._chatCompletions = [];
        this.messages = [];
      }
      _addChatCompletion(chatCompletion) {
        this._chatCompletions.push(chatCompletion);
        this._emit("chatCompletion", chatCompletion);
        const message = chatCompletion.choices[0]?.message;
        if (message)
          this._addMessage(message);
        return chatCompletion;
      }
      _addMessage(message, emit = true) {
        if (!("content" in message))
          message.content = null;
        this.messages.push(message);
        if (emit) {
          this._emit("message", message);
          if (isToolMessage(message) && message.content) {
            this._emit("functionToolCallResult", message.content);
          } else if (isAssistantMessage(message) && message.tool_calls) {
            for (const tool_call of message.tool_calls) {
              if (tool_call.type === "function") {
                this._emit("functionToolCall", tool_call.function);
              }
            }
          }
        }
      }
      /**
       * @returns a promise that resolves with the final ChatCompletion, or rejects
       * if an error occurred or the stream ended prematurely without producing a ChatCompletion.
       */
      async finalChatCompletion() {
        await this.done();
        const completion3 = this._chatCompletions[this._chatCompletions.length - 1];
        if (!completion3)
          throw new OpenAIError("stream ended without producing a ChatCompletion");
        return completion3;
      }
      /**
       * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects
       * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
       */
      async finalContent() {
        await this.done();
        return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
      }
      /**
       * @returns a promise that resolves with the the final assistant ChatCompletionMessage response,
       * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
       */
      async finalMessage() {
        await this.done();
        return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
      }
      /**
       * @returns a promise that resolves with the content of the final FunctionCall, or rejects
       * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
       */
      async finalFunctionToolCall() {
        await this.done();
        return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this);
      }
      async finalFunctionToolCallResult() {
        await this.done();
        return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this);
      }
      async totalUsage() {
        await this.done();
        return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this);
      }
      allChatCompletions() {
        return [...this._chatCompletions];
      }
      _emitFinal() {
        const completion3 = this._chatCompletions[this._chatCompletions.length - 1];
        if (completion3)
          this._emit("finalChatCompletion", completion3);
        const finalMessage = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
        if (finalMessage)
          this._emit("finalMessage", finalMessage);
        const finalContent = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
        if (finalContent)
          this._emit("finalContent", finalContent);
        const finalFunctionCall = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this);
        if (finalFunctionCall)
          this._emit("finalFunctionToolCall", finalFunctionCall);
        const finalFunctionCallResult = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this);
        if (finalFunctionCallResult != null)
          this._emit("finalFunctionToolCallResult", finalFunctionCallResult);
        if (this._chatCompletions.some((c3) => c3.usage)) {
          this._emit("totalUsage", __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this));
        }
      }
      async _createChatCompletion(client, params, options2) {
        const signal = options2?.signal;
        if (signal) {
          if (signal.aborted)
            this.controller.abort();
          signal.addEventListener("abort", () => this.controller.abort());
        }
        __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params);
        const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options2, signal: this.controller.signal });
        this._connected();
        return this._addChatCompletion(parseChatCompletion(chatCompletion, params));
      }
      async _runChatCompletion(client, params, options2) {
        for (const message of params.messages) {
          this._addMessage(message, false);
        }
        return await this._createChatCompletion(client, params, options2);
      }
      async _runTools(client, params, options2) {
        const role = "tool";
        const { tool_choice = "auto", stream: stream2, ...restParams } = params;
        const singleFunctionToCall = typeof tool_choice !== "string" && tool_choice?.function?.name;
        const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options2 || {};
        const inputTools = params.tools.map((tool) => {
          if (isAutoParsableTool(tool)) {
            if (!tool.$callback) {
              throw new OpenAIError("Tool given to `.runTools()` that does not have an associated function");
            }
            return {
              type: "function",
              function: {
                function: tool.$callback,
                name: tool.function.name,
                description: tool.function.description || "",
                parameters: tool.function.parameters,
                parse: tool.$parseRaw,
                strict: true
              }
            };
          }
          return tool;
        });
        const functionsByName = {};
        for (const f of inputTools) {
          if (f.type === "function") {
            functionsByName[f.function.name || f.function.function.name] = f.function;
          }
        }
        const tools = "tools" in params ? inputTools.map((t2) => t2.type === "function" ? {
          type: "function",
          function: {
            name: t2.function.name || t2.function.function.name,
            parameters: t2.function.parameters,
            description: t2.function.description,
            strict: t2.function.strict
          }
        } : t2) : void 0;
        for (const message of params.messages) {
          this._addMessage(message, false);
        }
        for (let i = 0; i < maxChatCompletions; ++i) {
          const chatCompletion = await this._createChatCompletion(client, {
            ...restParams,
            tool_choice,
            tools,
            messages: [...this.messages]
          }, options2);
          const message = chatCompletion.choices[0]?.message;
          if (!message) {
            throw new OpenAIError(`missing message in ChatCompletion response`);
          }
          if (!message.tool_calls?.length) {
            return;
          }
          for (const tool_call of message.tool_calls) {
            if (tool_call.type !== "function")
              continue;
            const tool_call_id = tool_call.id;
            const { name: name3, arguments: args } = tool_call.function;
            const fn = functionsByName[name3];
            if (!fn) {
              const content2 = `Invalid tool_call: ${JSON.stringify(name3)}. Available options are: ${Object.keys(functionsByName).map((name4) => JSON.stringify(name4)).join(", ")}. Please try again`;
              this._addMessage({ role, tool_call_id, content: content2 });
              continue;
            } else if (singleFunctionToCall && singleFunctionToCall !== name3) {
              const content2 = `Invalid tool_call: ${JSON.stringify(name3)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;
              this._addMessage({ role, tool_call_id, content: content2 });
              continue;
            }
            let parsed;
            try {
              parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args;
            } catch (error) {
              const content2 = error instanceof Error ? error.message : String(error);
              this._addMessage({ role, tool_call_id, content: content2 });
              continue;
            }
            const rawContent = await fn.function(parsed, this);
            const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
            this._addMessage({ role, tool_call_id, content });
            if (singleFunctionToCall) {
              return;
            }
          }
        }
        return;
      }
    };
    _AbstractChatCompletionRunner_instances = /* @__PURE__ */ new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = /* @__PURE__ */ __name(function _AbstractChatCompletionRunner_getFinalContent2() {
      return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null;
    }, "_AbstractChatCompletionRunner_getFinalContent"), _AbstractChatCompletionRunner_getFinalMessage = /* @__PURE__ */ __name(function _AbstractChatCompletionRunner_getFinalMessage2() {
      let i = this.messages.length;
      while (i-- > 0) {
        const message = this.messages[i];
        if (isAssistantMessage(message)) {
          const ret = {
            ...message,
            content: message.content ?? null,
            refusal: message.refusal ?? null
          };
          return ret;
        }
      }
      throw new OpenAIError("stream ended without producing a ChatCompletionMessage with role=assistant");
    }, "_AbstractChatCompletionRunner_getFinalMessage"), _AbstractChatCompletionRunner_getFinalFunctionToolCall = /* @__PURE__ */ __name(function _AbstractChatCompletionRunner_getFinalFunctionToolCall2() {
      for (let i = this.messages.length - 1; i >= 0; i--) {
        const message = this.messages[i];
        if (isAssistantMessage(message) && message?.tool_calls?.length) {
          return message.tool_calls.at(-1)?.function;
        }
      }
      return;
    }, "_AbstractChatCompletionRunner_getFinalFunctionToolCall"), _AbstractChatCompletionRunner_getFinalFunctionToolCallResult = /* @__PURE__ */ __name(function _AbstractChatCompletionRunner_getFinalFunctionToolCallResult2() {
      for (let i = this.messages.length - 1; i >= 0; i--) {
        const message = this.messages[i];
        if (isToolMessage(message) && message.content != null && typeof message.content === "string" && this.messages.some((x) => x.role === "assistant" && x.tool_calls?.some((y) => y.type === "function" && y.id === message.tool_call_id))) {
          return message.content;
        }
      }
      return;
    }, "_AbstractChatCompletionRunner_getFinalFunctionToolCallResult"), _AbstractChatCompletionRunner_calculateTotalUsage = /* @__PURE__ */ __name(function _AbstractChatCompletionRunner_calculateTotalUsage2() {
      const total = {
        completion_tokens: 0,
        prompt_tokens: 0,
        total_tokens: 0
      };
      for (const { usage: usage2 } of this._chatCompletions) {
        if (usage2) {
          total.completion_tokens += usage2.completion_tokens;
          total.prompt_tokens += usage2.prompt_tokens;
          total.total_tokens += usage2.total_tokens;
        }
      }
      return total;
    }, "_AbstractChatCompletionRunner_calculateTotalUsage"), _AbstractChatCompletionRunner_validateParams = /* @__PURE__ */ __name(function _AbstractChatCompletionRunner_validateParams2(params) {
      if (params.n != null && params.n > 1) {
        throw new OpenAIError("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.");
      }
    }, "_AbstractChatCompletionRunner_validateParams"), _AbstractChatCompletionRunner_stringifyFunctionCallResult = /* @__PURE__ */ __name(function _AbstractChatCompletionRunner_stringifyFunctionCallResult2(rawContent) {
      return typeof rawContent === "string" ? rawContent : rawContent === void 0 ? "undefined" : JSON.stringify(rawContent);
    }, "_AbstractChatCompletionRunner_stringifyFunctionCallResult");
  }
});

// node_modules/openai/lib/ChatCompletionRunner.mjs
var ChatCompletionRunner;
var init_ChatCompletionRunner = __esm({
  "node_modules/openai/lib/ChatCompletionRunner.mjs"() {
    init_esbuild_shims();
    init_AbstractChatCompletionRunner();
    init_chatCompletionUtils();
    ChatCompletionRunner = class _ChatCompletionRunner extends AbstractChatCompletionRunner {
      static {
        __name(this, "ChatCompletionRunner");
      }
      static runTools(client, params, options2) {
        const runner = new _ChatCompletionRunner();
        const opts = {
          ...options2,
          headers: { ...options2?.headers, "X-Stainless-Helper-Method": "runTools" }
        };
        runner._run(() => runner._runTools(client, params, opts));
        return runner;
      }
      _addMessage(message, emit = true) {
        super._addMessage(message, emit);
        if (isAssistantMessage(message) && message.content) {
          this._emit("content", message.content);
        }
      }
    };
  }
});

// node_modules/openai/streaming.mjs
var init_streaming2 = __esm({
  "node_modules/openai/streaming.mjs"() {
    init_esbuild_shims();
    init_streaming();
  }
});

// node_modules/openai/_vendor/partial-json-parser/parser.mjs
function parseJSON(jsonString, allowPartial = Allow.ALL) {
  if (typeof jsonString !== "string") {
    throw new TypeError(`expecting str, got ${typeof jsonString}`);
  }
  if (!jsonString.trim()) {
    throw new Error(`${jsonString} is empty`);
  }
  return _parseJSON(jsonString.trim(), allowPartial);
}
var STR, NUM, ARR, OBJ, NULL, BOOL, NAN, INFINITY, MINUS_INFINITY, INF, SPECIAL, ATOM, COLLECTION, ALL, Allow, PartialJSON, MalformedJSON, _parseJSON, partialParse;
var init_parser2 = __esm({
  "node_modules/openai/_vendor/partial-json-parser/parser.mjs"() {
    init_esbuild_shims();
    STR = 1;
    NUM = 2;
    ARR = 4;
    OBJ = 8;
    NULL = 16;
    BOOL = 32;
    NAN = 64;
    INFINITY = 128;
    MINUS_INFINITY = 256;
    INF = INFINITY | MINUS_INFINITY;
    SPECIAL = NULL | BOOL | INF | NAN;
    ATOM = STR | NUM | SPECIAL;
    COLLECTION = ARR | OBJ;
    ALL = ATOM | COLLECTION;
    Allow = {
      STR,
      NUM,
      ARR,
      OBJ,
      NULL,
      BOOL,
      NAN,
      INFINITY,
      MINUS_INFINITY,
      INF,
      SPECIAL,
      ATOM,
      COLLECTION,
      ALL
    };
    PartialJSON = class extends Error {
      static {
        __name(this, "PartialJSON");
      }
    };
    MalformedJSON = class extends Error {
      static {
        __name(this, "MalformedJSON");
      }
    };
    __name(parseJSON, "parseJSON");
    _parseJSON = /* @__PURE__ */ __name((jsonString, allow) => {
      const length = jsonString.length;
      let index = 0;
      const markPartialJSON = /* @__PURE__ */ __name((msg) => {
        throw new PartialJSON(`${msg} at position ${index}`);
      }, "markPartialJSON");
      const throwMalformedError = /* @__PURE__ */ __name((msg) => {
        throw new MalformedJSON(`${msg} at position ${index}`);
      }, "throwMalformedError");
      const parseAny = /* @__PURE__ */ __name(() => {
        skipBlank();
        if (index >= length)
          markPartialJSON("Unexpected end of input");
        if (jsonString[index] === '"')
          return parseStr();
        if (jsonString[index] === "{")
          return parseObj();
        if (jsonString[index] === "[")
          return parseArr();
        if (jsonString.substring(index, index + 4) === "null" || Allow.NULL & allow && length - index < 4 && "null".startsWith(jsonString.substring(index))) {
          index += 4;
          return null;
        }
        if (jsonString.substring(index, index + 4) === "true" || Allow.BOOL & allow && length - index < 4 && "true".startsWith(jsonString.substring(index))) {
          index += 4;
          return true;
        }
        if (jsonString.substring(index, index + 5) === "false" || Allow.BOOL & allow && length - index < 5 && "false".startsWith(jsonString.substring(index))) {
          index += 5;
          return false;
        }
        if (jsonString.substring(index, index + 8) === "Infinity" || Allow.INFINITY & allow && length - index < 8 && "Infinity".startsWith(jsonString.substring(index))) {
          index += 8;
          return Infinity;
        }
        if (jsonString.substring(index, index + 9) === "-Infinity" || Allow.MINUS_INFINITY & allow && 1 < length - index && length - index < 9 && "-Infinity".startsWith(jsonString.substring(index))) {
          index += 9;
          return -Infinity;
        }
        if (jsonString.substring(index, index + 3) === "NaN" || Allow.NAN & allow && length - index < 3 && "NaN".startsWith(jsonString.substring(index))) {
          index += 3;
          return NaN;
        }
        return parseNum();
      }, "parseAny");
      const parseStr = /* @__PURE__ */ __name(() => {
        const start = index;
        let escape7 = false;
        index++;
        while (index < length && (jsonString[index] !== '"' || escape7 && jsonString[index - 1] === "\\")) {
          escape7 = jsonString[index] === "\\" ? !escape7 : false;
          index++;
        }
        if (jsonString.charAt(index) == '"') {
          try {
            return JSON.parse(jsonString.substring(start, ++index - Number(escape7)));
          } catch (e2) {
            throwMalformedError(String(e2));
          }
        } else if (Allow.STR & allow) {
          try {
            return JSON.parse(jsonString.substring(start, index - Number(escape7)) + '"');
          } catch (e2) {
            return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("\\")) + '"');
          }
        }
        markPartialJSON("Unterminated string literal");
      }, "parseStr");
      const parseObj = /* @__PURE__ */ __name(() => {
        index++;
        skipBlank();
        const obj = {};
        try {
          while (jsonString[index] !== "}") {
            skipBlank();
            if (index >= length && Allow.OBJ & allow)
              return obj;
            const key = parseStr();
            skipBlank();
            index++;
            try {
              const value = parseAny();
              Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true });
            } catch (e2) {
              if (Allow.OBJ & allow)
                return obj;
              else
                throw e2;
            }
            skipBlank();
            if (jsonString[index] === ",")
              index++;
          }
        } catch (e2) {
          if (Allow.OBJ & allow)
            return obj;
          else
            markPartialJSON("Expected '}' at end of object");
        }
        index++;
        return obj;
      }, "parseObj");
      const parseArr = /* @__PURE__ */ __name(() => {
        index++;
        const arr = [];
        try {
          while (jsonString[index] !== "]") {
            arr.push(parseAny());
            skipBlank();
            if (jsonString[index] === ",") {
              index++;
            }
          }
        } catch (e2) {
          if (Allow.ARR & allow) {
            return arr;
          }
          markPartialJSON("Expected ']' at end of array");
        }
        index++;
        return arr;
      }, "parseArr");
      const parseNum = /* @__PURE__ */ __name(() => {
        if (index === 0) {
          if (jsonString === "-" && Allow.NUM & allow)
            markPartialJSON("Not sure what '-' is");
          try {
            return JSON.parse(jsonString);
          } catch (e2) {
            if (Allow.NUM & allow) {
              try {
                if ("." === jsonString[jsonString.length - 1])
                  return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf(".")));
                return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("e")));
              } catch (e3) {
              }
            }
            throwMalformedError(String(e2));
          }
        }
        const start = index;
        if (jsonString[index] === "-")
          index++;
        while (jsonString[index] && !",]}".includes(jsonString[index]))
          index++;
        if (index == length && !(Allow.NUM & allow))
          markPartialJSON("Unterminated number literal");
        try {
          return JSON.parse(jsonString.substring(start, index));
        } catch (e2) {
          if (jsonString.substring(start, index) === "-" && Allow.NUM & allow)
            markPartialJSON("Not sure what '-' is");
          try {
            return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("e")));
          } catch (e3) {
            throwMalformedError(String(e3));
          }
        }
      }, "parseNum");
      const skipBlank = /* @__PURE__ */ __name(() => {
        while (index < length && " \n\r	".includes(jsonString[index])) {
          index++;
        }
      }, "skipBlank");
      return parseAny();
    }, "_parseJSON");
    partialParse = /* @__PURE__ */ __name((input) => parseJSON(input, Allow.ALL ^ Allow.NUM), "partialParse");
  }
});

// node_modules/openai/lib/ChatCompletionStream.mjs
function finalizeChatCompletion(snapshot, params) {
  const { id, choices, created, model, system_fingerprint, ...rest } = snapshot;
  const completion3 = {
    ...rest,
    id,
    choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => {
      if (!finish_reason) {
        throw new OpenAIError(`missing finish_reason for choice ${index}`);
      }
      const { content = null, function_call, tool_calls, ...messageRest } = message;
      const role = message.role;
      if (!role) {
        throw new OpenAIError(`missing role for choice ${index}`);
      }
      if (function_call) {
        const { arguments: args, name: name3 } = function_call;
        if (args == null) {
          throw new OpenAIError(`missing function_call.arguments for choice ${index}`);
        }
        if (!name3) {
          throw new OpenAIError(`missing function_call.name for choice ${index}`);
        }
        return {
          ...choiceRest,
          message: {
            content,
            function_call: { arguments: args, name: name3 },
            role,
            refusal: message.refusal ?? null
          },
          finish_reason,
          index,
          logprobs
        };
      }
      if (tool_calls) {
        return {
          ...choiceRest,
          index,
          finish_reason,
          logprobs,
          message: {
            ...messageRest,
            role,
            content,
            refusal: message.refusal ?? null,
            tool_calls: tool_calls.map((tool_call, i) => {
              const { function: fn, type, id: id2, ...toolRest } = tool_call;
              const { arguments: args, name: name3, ...fnRest } = fn || {};
              if (id2 == null) {
                throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].id
${str(snapshot)}`);
              }
              if (type == null) {
                throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type
${str(snapshot)}`);
              }
              if (name3 == null) {
                throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name
${str(snapshot)}`);
              }
              if (args == null) {
                throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments
${str(snapshot)}`);
              }
              return { ...toolRest, id: id2, type, function: { ...fnRest, name: name3, arguments: args } };
            })
          }
        };
      }
      return {
        ...choiceRest,
        message: { ...messageRest, content, role, refusal: message.refusal ?? null },
        finish_reason,
        index,
        logprobs
      };
    }),
    created,
    model,
    object: "chat.completion",
    ...system_fingerprint ? { system_fingerprint } : {}
  };
  return maybeParseChatCompletion(completion3, params);
}
function str(x) {
  return JSON.stringify(x);
}
function assertIsEmpty(obj) {
  return;
}
function assertNever(_x) {
}
var _ChatCompletionStream_instances, _ChatCompletionStream_params, _ChatCompletionStream_choiceEventStates, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_getChoiceEventState, _ChatCompletionStream_addChunk, _ChatCompletionStream_emitToolCallDoneEvent, _ChatCompletionStream_emitContentDoneEvents, _ChatCompletionStream_endRequest, _ChatCompletionStream_getAutoParseableResponseFormat, _ChatCompletionStream_accumulateChatCompletion, ChatCompletionStream;
var init_ChatCompletionStream = __esm({
  "node_modules/openai/lib/ChatCompletionStream.mjs"() {
    init_esbuild_shims();
    init_tslib();
    init_error2();
    init_AbstractChatCompletionRunner();
    init_streaming2();
    init_parser();
    init_parser2();
    ChatCompletionStream = class _ChatCompletionStream extends AbstractChatCompletionRunner {
      static {
        __name(this, "ChatCompletionStream");
      }
      constructor(params) {
        super();
        _ChatCompletionStream_instances.add(this);
        _ChatCompletionStream_params.set(this, void 0);
        _ChatCompletionStream_choiceEventStates.set(this, void 0);
        _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0);
        __classPrivateFieldSet(this, _ChatCompletionStream_params, params, "f");
        __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f");
      }
      get currentChatCompletionSnapshot() {
        return __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
      }
      /**
       * Intended for use on the frontend, consuming a stream produced with
       * `.toReadableStream()` on the backend.
       *
       * Note that messages sent to the model do not appear in `.on('message')`
       * in this context.
       */
      static fromReadableStream(stream2) {
        const runner = new _ChatCompletionStream(null);
        runner._run(() => runner._fromReadableStream(stream2));
        return runner;
      }
      static createChatCompletion(client, params, options2) {
        const runner = new _ChatCompletionStream(params);
        runner._run(() => runner._runChatCompletion(client, { ...params, stream: true }, { ...options2, headers: { ...options2?.headers, "X-Stainless-Helper-Method": "stream" } }));
        return runner;
      }
      async _createChatCompletion(client, params, options2) {
        super._createChatCompletion;
        const signal = options2?.signal;
        if (signal) {
          if (signal.aborted)
            this.controller.abort();
          signal.addEventListener("abort", () => this.controller.abort());
        }
        __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
        const stream2 = await client.chat.completions.create({ ...params, stream: true }, { ...options2, signal: this.controller.signal });
        this._connected();
        for await (const chunk of stream2) {
          __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
        }
        if (stream2.controller.signal?.aborted) {
          throw new APIUserAbortError();
        }
        return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
      }
      async _fromReadableStream(readableStream, options2) {
        const signal = options2?.signal;
        if (signal) {
          if (signal.aborted)
            this.controller.abort();
          signal.addEventListener("abort", () => this.controller.abort());
        }
        __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
        this._connected();
        const stream2 = Stream2.fromReadableStream(readableStream, this.controller);
        let chatId;
        for await (const chunk of stream2) {
          if (chatId && chatId !== chunk.id) {
            this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
          }
          __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
          chatId = chunk.id;
        }
        if (stream2.controller.signal?.aborted) {
          throw new APIUserAbortError();
        }
        return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
      }
      [(_ChatCompletionStream_params = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_choiceEventStates = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_instances = /* @__PURE__ */ new WeakSet(), _ChatCompletionStream_beginRequest = /* @__PURE__ */ __name(function _ChatCompletionStream_beginRequest2() {
        if (this.ended)
          return;
        __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f");
      }, "_ChatCompletionStream_beginRequest"), _ChatCompletionStream_getChoiceEventState = /* @__PURE__ */ __name(function _ChatCompletionStream_getChoiceEventState2(choice2) {
        let state = __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice2.index];
        if (state) {
          return state;
        }
        state = {
          content_done: false,
          refusal_done: false,
          logprobs_content_done: false,
          logprobs_refusal_done: false,
          done_tool_calls: /* @__PURE__ */ new Set(),
          current_tool_call_index: null
        };
        __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice2.index] = state;
        return state;
      }, "_ChatCompletionStream_getChoiceEventState"), _ChatCompletionStream_addChunk = /* @__PURE__ */ __name(function _ChatCompletionStream_addChunk2(chunk) {
        if (this.ended)
          return;
        const completion3 = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk);
        this._emit("chunk", chunk, completion3);
        for (const choice2 of chunk.choices) {
          const choiceSnapshot = completion3.choices[choice2.index];
          if (choice2.delta.content != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.content) {
            this._emit("content", choice2.delta.content, choiceSnapshot.message.content);
            this._emit("content.delta", {
              delta: choice2.delta.content,
              snapshot: choiceSnapshot.message.content,
              parsed: choiceSnapshot.message.parsed
            });
          }
          if (choice2.delta.refusal != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.refusal) {
            this._emit("refusal.delta", {
              delta: choice2.delta.refusal,
              snapshot: choiceSnapshot.message.refusal
            });
          }
          if (choice2.logprobs?.content != null && choiceSnapshot.message?.role === "assistant") {
            this._emit("logprobs.content.delta", {
              content: choice2.logprobs?.content,
              snapshot: choiceSnapshot.logprobs?.content ?? []
            });
          }
          if (choice2.logprobs?.refusal != null && choiceSnapshot.message?.role === "assistant") {
            this._emit("logprobs.refusal.delta", {
              refusal: choice2.logprobs?.refusal,
              snapshot: choiceSnapshot.logprobs?.refusal ?? []
            });
          }
          const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
          if (choiceSnapshot.finish_reason) {
            __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
            if (state.current_tool_call_index != null) {
              __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
            }
          }
          for (const toolCall of choice2.delta.tool_calls ?? []) {
            if (state.current_tool_call_index !== toolCall.index) {
              __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
              if (state.current_tool_call_index != null) {
                __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
              }
            }
            state.current_tool_call_index = toolCall.index;
          }
          for (const toolCallDelta of choice2.delta.tool_calls ?? []) {
            const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index];
            if (!toolCallSnapshot?.type) {
              continue;
            }
            if (toolCallSnapshot?.type === "function") {
              this._emit("tool_calls.function.arguments.delta", {
                name: toolCallSnapshot.function?.name,
                index: toolCallDelta.index,
                arguments: toolCallSnapshot.function.arguments,
                parsed_arguments: toolCallSnapshot.function.parsed_arguments,
                arguments_delta: toolCallDelta.function?.arguments ?? ""
              });
            } else {
              assertNever(toolCallSnapshot?.type);
            }
          }
        }
      }, "_ChatCompletionStream_addChunk"), _ChatCompletionStream_emitToolCallDoneEvent = /* @__PURE__ */ __name(function _ChatCompletionStream_emitToolCallDoneEvent2(choiceSnapshot, toolCallIndex) {
        const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
        if (state.done_tool_calls.has(toolCallIndex)) {
          return;
        }
        const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallIndex];
        if (!toolCallSnapshot) {
          throw new Error("no tool call snapshot");
        }
        if (!toolCallSnapshot.type) {
          throw new Error("tool call snapshot missing `type`");
        }
        if (toolCallSnapshot.type === "function") {
          const inputTool = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => tool.type === "function" && tool.function.name === toolCallSnapshot.function.name);
          this._emit("tool_calls.function.arguments.done", {
            name: toolCallSnapshot.function.name,
            index: toolCallIndex,
            arguments: toolCallSnapshot.function.arguments,
            parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments) : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments) : null
          });
        } else {
          assertNever(toolCallSnapshot.type);
        }
      }, "_ChatCompletionStream_emitToolCallDoneEvent"), _ChatCompletionStream_emitContentDoneEvents = /* @__PURE__ */ __name(function _ChatCompletionStream_emitContentDoneEvents2(choiceSnapshot) {
        const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
        if (choiceSnapshot.message.content && !state.content_done) {
          state.content_done = true;
          const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this);
          this._emit("content.done", {
            content: choiceSnapshot.message.content,
            parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null
          });
        }
        if (choiceSnapshot.message.refusal && !state.refusal_done) {
          state.refusal_done = true;
          this._emit("refusal.done", { refusal: choiceSnapshot.message.refusal });
        }
        if (choiceSnapshot.logprobs?.content && !state.logprobs_content_done) {
          state.logprobs_content_done = true;
          this._emit("logprobs.content.done", { content: choiceSnapshot.logprobs.content });
        }
        if (choiceSnapshot.logprobs?.refusal && !state.logprobs_refusal_done) {
          state.logprobs_refusal_done = true;
          this._emit("logprobs.refusal.done", { refusal: choiceSnapshot.logprobs.refusal });
        }
      }, "_ChatCompletionStream_emitContentDoneEvents"), _ChatCompletionStream_endRequest = /* @__PURE__ */ __name(function _ChatCompletionStream_endRequest2() {
        if (this.ended) {
          throw new OpenAIError(`stream has ended, this shouldn't happen`);
        }
        const snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
        if (!snapshot) {
          throw new OpenAIError(`request ended without sending any chunks`);
        }
        __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f");
        __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f");
        return finalizeChatCompletion(snapshot, __classPrivateFieldGet(this, _ChatCompletionStream_params, "f"));
      }, "_ChatCompletionStream_endRequest"), _ChatCompletionStream_getAutoParseableResponseFormat = /* @__PURE__ */ __name(function _ChatCompletionStream_getAutoParseableResponseFormat2() {
        const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format;
        if (isAutoParsableResponseFormat(responseFormat)) {
          return responseFormat;
        }
        return null;
      }, "_ChatCompletionStream_getAutoParseableResponseFormat"), _ChatCompletionStream_accumulateChatCompletion = /* @__PURE__ */ __name(function _ChatCompletionStream_accumulateChatCompletion2(chunk) {
        var _a6, _b2, _c2, _d;
        let snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
        const { choices, ...rest } = chunk;
        if (!snapshot) {
          snapshot = __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, {
            ...rest,
            choices: []
          }, "f");
        } else {
          Object.assign(snapshot, rest);
        }
        for (const { delta, finish_reason, index, logprobs = null, ...other2 } of chunk.choices) {
          let choice2 = snapshot.choices[index];
          if (!choice2) {
            choice2 = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other2 };
          }
          if (logprobs) {
            if (!choice2.logprobs) {
              choice2.logprobs = Object.assign({}, logprobs);
            } else {
              const { content: content2, refusal: refusal2, ...rest3 } = logprobs;
              assertIsEmpty(rest3);
              Object.assign(choice2.logprobs, rest3);
              if (content2) {
                (_a6 = choice2.logprobs).content ?? (_a6.content = []);
                choice2.logprobs.content.push(...content2);
              }
              if (refusal2) {
                (_b2 = choice2.logprobs).refusal ?? (_b2.refusal = []);
                choice2.logprobs.refusal.push(...refusal2);
              }
            }
          }
          if (finish_reason) {
            choice2.finish_reason = finish_reason;
            if (__classPrivateFieldGet(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f"))) {
              if (finish_reason === "length") {
                throw new LengthFinishReasonError();
              }
              if (finish_reason === "content_filter") {
                throw new ContentFilterFinishReasonError();
              }
            }
          }
          Object.assign(choice2, other2);
          if (!delta)
            continue;
          const { content, refusal, function_call, role, tool_calls, ...rest2 } = delta;
          assertIsEmpty(rest2);
          Object.assign(choice2.message, rest2);
          if (refusal) {
            choice2.message.refusal = (choice2.message.refusal || "") + refusal;
          }
          if (role)
            choice2.message.role = role;
          if (function_call) {
            if (!choice2.message.function_call) {
              choice2.message.function_call = function_call;
            } else {
              if (function_call.name)
                choice2.message.function_call.name = function_call.name;
              if (function_call.arguments) {
                (_c2 = choice2.message.function_call).arguments ?? (_c2.arguments = "");
                choice2.message.function_call.arguments += function_call.arguments;
              }
            }
          }
          if (content) {
            choice2.message.content = (choice2.message.content || "") + content;
            if (!choice2.message.refusal && __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) {
              choice2.message.parsed = partialParse(choice2.message.content);
            }
          }
          if (tool_calls) {
            if (!choice2.message.tool_calls)
              choice2.message.tool_calls = [];
            for (const { index: index2, id, type, function: fn, ...rest3 } of tool_calls) {
              const tool_call = (_d = choice2.message.tool_calls)[index2] ?? (_d[index2] = {});
              Object.assign(tool_call, rest3);
              if (id)
                tool_call.id = id;
              if (type)
                tool_call.type = type;
              if (fn)
                tool_call.function ?? (tool_call.function = { name: fn.name ?? "", arguments: "" });
              if (fn?.name)
                tool_call.function.name = fn.name;
              if (fn?.arguments) {
                tool_call.function.arguments += fn.arguments;
                if (shouldParseToolCall(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), tool_call)) {
                  tool_call.function.parsed_arguments = partialParse(tool_call.function.arguments);
                }
              }
            }
          }
        }
        return snapshot;
      }, "_ChatCompletionStream_accumulateChatCompletion"), Symbol.asyncIterator)]() {
        const pushQueue = [];
        const readQueue = [];
        let done = false;
        this.on("chunk", (chunk) => {
          const reader = readQueue.shift();
          if (reader) {
            reader.resolve(chunk);
          } else {
            pushQueue.push(chunk);
          }
        });
        this.on("end", () => {
          done = true;
          for (const reader of readQueue) {
            reader.resolve(void 0);
          }
          readQueue.length = 0;
        });
        this.on("abort", (err) => {
          done = true;
          for (const reader of readQueue) {
            reader.reject(err);
          }
          readQueue.length = 0;
        });
        this.on("error", (err) => {
          done = true;
          for (const reader of readQueue) {
            reader.reject(err);
          }
          readQueue.length = 0;
        });
        return {
          next: /* @__PURE__ */ __name(async () => {
            if (!pushQueue.length) {
              if (done) {
                return { value: void 0, done: true };
              }
              return new Promise((resolve24, reject) => readQueue.push({ resolve: resolve24, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
            }
            const chunk = pushQueue.shift();
            return { value: chunk, done: false };
          }, "next"),
          return: /* @__PURE__ */ __name(async () => {
            this.abort();
            return { value: void 0, done: true };
          }, "return")
        };
      }
      toReadableStream() {
        const stream2 = new Stream2(this[Symbol.asyncIterator].bind(this), this.controller);
        return stream2.toReadableStream();
      }
    };
    __name(finalizeChatCompletion, "finalizeChatCompletion");
    __name(str, "str");
    __name(assertIsEmpty, "assertIsEmpty");
    __name(assertNever, "assertNever");
  }
});

// node_modules/openai/lib/ChatCompletionStreamingRunner.mjs
var ChatCompletionStreamingRunner;
var init_ChatCompletionStreamingRunner = __esm({
  "node_modules/openai/lib/ChatCompletionStreamingRunner.mjs"() {
    init_esbuild_shims();
    init_ChatCompletionStream();
    ChatCompletionStreamingRunner = class _ChatCompletionStreamingRunner extends ChatCompletionStream {
      static {
        __name(this, "ChatCompletionStreamingRunner");
      }
      static fromReadableStream(stream2) {
        const runner = new _ChatCompletionStreamingRunner(null);
        runner._run(() => runner._fromReadableStream(stream2));
        return runner;
      }
      static runTools(client, params, options2) {
        const runner = new _ChatCompletionStreamingRunner(
          // @ts-expect-error TODO these types are incompatible
          params
        );
        const opts = {
          ...options2,
          headers: { ...options2?.headers, "X-Stainless-Helper-Method": "runTools" }
        };
        runner._run(() => runner._runTools(client, params, opts));
        return runner;
      }
    };
  }
});

// node_modules/openai/resources/chat/completions/completions.mjs
var Completions;
var init_completions = __esm({
  "node_modules/openai/resources/chat/completions/completions.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_messages();
    init_messages();
    init_pagination();
    init_path();
    init_ChatCompletionRunner();
    init_ChatCompletionStreamingRunner();
    init_ChatCompletionStream();
    init_parser();
    init_ChatCompletionStreamingRunner();
    init_RunnableFunction();
    init_ChatCompletionStream();
    init_ChatCompletionRunner();
    Completions = class extends APIResource {
      static {
        __name(this, "Completions");
      }
      constructor() {
        super(...arguments);
        this.messages = new Messages(this._client);
      }
      create(body, options2) {
        return this._client.post("/chat/completions", { body, ...options2, stream: body.stream ?? false });
      }
      /**
       * Get a stored chat completion. Only Chat Completions that have been created with
       * the `store` parameter set to `true` will be returned.
       *
       * @example
       * ```ts
       * const chatCompletion =
       *   await client.chat.completions.retrieve('completion_id');
       * ```
       */
      retrieve(completionID, options2) {
        return this._client.get(path11`/chat/completions/${completionID}`, options2);
      }
      /**
       * Modify a stored chat completion. Only Chat Completions that have been created
       * with the `store` parameter set to `true` can be modified. Currently, the only
       * supported modification is to update the `metadata` field.
       *
       * @example
       * ```ts
       * const chatCompletion = await client.chat.completions.update(
       *   'completion_id',
       *   { metadata: { foo: 'string' } },
       * );
       * ```
       */
      update(completionID, body, options2) {
        return this._client.post(path11`/chat/completions/${completionID}`, { body, ...options2 });
      }
      /**
       * List stored Chat Completions. Only Chat Completions that have been stored with
       * the `store` parameter set to `true` will be returned.
       *
       * @example
       * ```ts
       * // Automatically fetches more pages as needed.
       * for await (const chatCompletion of client.chat.completions.list()) {
       *   // ...
       * }
       * ```
       */
      list(query = {}, options2) {
        return this._client.getAPIList("/chat/completions", CursorPage, { query, ...options2 });
      }
      /**
       * Delete a stored chat completion. Only Chat Completions that have been created
       * with the `store` parameter set to `true` can be deleted.
       *
       * @example
       * ```ts
       * const chatCompletionDeleted =
       *   await client.chat.completions.delete('completion_id');
       * ```
       */
      delete(completionID, options2) {
        return this._client.delete(path11`/chat/completions/${completionID}`, options2);
      }
      parse(body, options2) {
        validateInputTools(body.tools);
        return this._client.chat.completions.create(body, {
          ...options2,
          headers: {
            ...options2?.headers,
            "X-Stainless-Helper-Method": "chat.completions.parse"
          }
        })._thenUnwrap((completion3) => parseChatCompletion(completion3, body));
      }
      runTools(body, options2) {
        if (body.stream) {
          return ChatCompletionStreamingRunner.runTools(this._client, body, options2);
        }
        return ChatCompletionRunner.runTools(this._client, body, options2);
      }
      /**
       * Creates a chat completion stream
       */
      stream(body, options2) {
        return ChatCompletionStream.createChatCompletion(this._client, body, options2);
      }
    };
    Completions.Messages = Messages;
  }
});

// node_modules/openai/resources/chat/chat.mjs
var Chat2;
var init_chat = __esm({
  "node_modules/openai/resources/chat/chat.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_completions();
    init_completions();
    Chat2 = class extends APIResource {
      static {
        __name(this, "Chat");
      }
      constructor() {
        super(...arguments);
        this.completions = new Completions(this._client);
      }
    };
    Chat2.Completions = Completions;
  }
});

// node_modules/openai/resources/chat/completions/index.mjs
var init_completions2 = __esm({
  "node_modules/openai/resources/chat/completions/index.mjs"() {
    init_esbuild_shims();
    init_completions();
    init_completions();
    init_messages();
  }
});

// node_modules/openai/resources/chat/index.mjs
var init_chat2 = __esm({
  "node_modules/openai/resources/chat/index.mjs"() {
    init_esbuild_shims();
    init_chat();
    init_completions2();
  }
});

// node_modules/openai/resources/shared.mjs
var init_shared = __esm({
  "node_modules/openai/resources/shared.mjs"() {
    init_esbuild_shims();
  }
});

// node_modules/openai/internal/headers.mjs
function* iterateHeaders(headers) {
  if (!headers)
    return;
  if (brand_privateNullableHeaders in headers) {
    const { values, nulls } = headers;
    yield* values.entries();
    for (const name3 of nulls) {
      yield [name3, null];
    }
    return;
  }
  let shouldClear = false;
  let iter;
  if (headers instanceof Headers) {
    iter = headers.entries();
  } else if (isReadonlyArray(headers)) {
    iter = headers;
  } else {
    shouldClear = true;
    iter = Object.entries(headers ?? {});
  }
  for (let row of iter) {
    const name3 = row[0];
    if (typeof name3 !== "string")
      throw new TypeError("expected header name to be a string");
    const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];
    let didClear = false;
    for (const value of values) {
      if (value === void 0)
        continue;
      if (shouldClear && !didClear) {
        didClear = true;
        yield [name3, null];
      }
      yield [name3, value];
    }
  }
}
var brand_privateNullableHeaders, buildHeaders;
var init_headers = __esm({
  "node_modules/openai/internal/headers.mjs"() {
    init_esbuild_shims();
    init_values();
    brand_privateNullableHeaders = /* @__PURE__ */ Symbol("brand.privateNullableHeaders");
    __name(iterateHeaders, "iterateHeaders");
    buildHeaders = /* @__PURE__ */ __name((newHeaders) => {
      const targetHeaders = new Headers();
      const nullHeaders = /* @__PURE__ */ new Set();
      for (const headers of newHeaders) {
        const seenHeaders = /* @__PURE__ */ new Set();
        for (const [name3, value] of iterateHeaders(headers)) {
          const lowerName = name3.toLowerCase();
          if (!seenHeaders.has(lowerName)) {
            targetHeaders.delete(name3);
            seenHeaders.add(lowerName);
          }
          if (value === null) {
            targetHeaders.delete(name3);
            nullHeaders.add(lowerName);
          } else {
            targetHeaders.append(name3, value);
            nullHeaders.delete(lowerName);
          }
        }
      }
      return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };
    }, "buildHeaders");
  }
});

// node_modules/openai/resources/audio/speech.mjs
var Speech;
var init_speech = __esm({
  "node_modules/openai/resources/audio/speech.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_headers();
    Speech = class extends APIResource {
      static {
        __name(this, "Speech");
      }
      /**
       * Generates audio from the input text.
       *
       * @example
       * ```ts
       * const speech = await client.audio.speech.create({
       *   input: 'input',
       *   model: 'string',
       *   voice: 'ash',
       * });
       *
       * const content = await speech.blob();
       * console.log(content);
       * ```
       */
      create(body, options2) {
        return this._client.post("/audio/speech", {
          body,
          ...options2,
          headers: buildHeaders([{ Accept: "application/octet-stream" }, options2?.headers]),
          __binaryResponse: true
        });
      }
    };
  }
});

// node_modules/openai/resources/audio/transcriptions.mjs
var Transcriptions;
var init_transcriptions = __esm({
  "node_modules/openai/resources/audio/transcriptions.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_uploads();
    Transcriptions = class extends APIResource {
      static {
        __name(this, "Transcriptions");
      }
      create(body, options2) {
        return this._client.post("/audio/transcriptions", multipartFormRequestOptions({
          body,
          ...options2,
          stream: body.stream ?? false,
          __metadata: { model: body.model }
        }, this._client));
      }
    };
  }
});

// node_modules/openai/resources/audio/translations.mjs
var Translations;
var init_translations = __esm({
  "node_modules/openai/resources/audio/translations.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_uploads();
    Translations = class extends APIResource {
      static {
        __name(this, "Translations");
      }
      create(body, options2) {
        return this._client.post("/audio/translations", multipartFormRequestOptions({ body, ...options2, __metadata: { model: body.model } }, this._client));
      }
    };
  }
});

// node_modules/openai/resources/audio/audio.mjs
var Audio;
var init_audio = __esm({
  "node_modules/openai/resources/audio/audio.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_speech();
    init_speech();
    init_transcriptions();
    init_transcriptions();
    init_translations();
    init_translations();
    Audio = class extends APIResource {
      static {
        __name(this, "Audio");
      }
      constructor() {
        super(...arguments);
        this.transcriptions = new Transcriptions(this._client);
        this.translations = new Translations(this._client);
        this.speech = new Speech(this._client);
      }
    };
    Audio.Transcriptions = Transcriptions;
    Audio.Translations = Translations;
    Audio.Speech = Speech;
  }
});

// node_modules/openai/resources/batches.mjs
var Batches2;
var init_batches = __esm({
  "node_modules/openai/resources/batches.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_pagination();
    init_path();
    Batches2 = class extends APIResource {
      static {
        __name(this, "Batches");
      }
      /**
       * Creates and executes a batch from an uploaded file of requests
       */
      create(body, options2) {
        return this._client.post("/batches", { body, ...options2 });
      }
      /**
       * Retrieves a batch.
       */
      retrieve(batchID, options2) {
        return this._client.get(path11`/batches/${batchID}`, options2);
      }
      /**
       * List your organization's batches.
       */
      list(query = {}, options2) {
        return this._client.getAPIList("/batches", CursorPage, { query, ...options2 });
      }
      /**
       * Cancels an in-progress batch. The batch will be in status `cancelling` for up to
       * 10 minutes, before changing to `cancelled`, where it will have partial results
       * (if any) available in the output file.
       */
      cancel(batchID, options2) {
        return this._client.post(path11`/batches/${batchID}/cancel`, options2);
      }
    };
  }
});

// node_modules/openai/resources/beta/assistants.mjs
var Assistants;
var init_assistants = __esm({
  "node_modules/openai/resources/beta/assistants.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_pagination();
    init_headers();
    init_path();
    Assistants = class extends APIResource {
      static {
        __name(this, "Assistants");
      }
      /**
       * Create an assistant with a model and instructions.
       *
       * @example
       * ```ts
       * const assistant = await client.beta.assistants.create({
       *   model: 'gpt-4o',
       * });
       * ```
       */
      create(body, options2) {
        return this._client.post("/assistants", {
          body,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Retrieves an assistant.
       *
       * @example
       * ```ts
       * const assistant = await client.beta.assistants.retrieve(
       *   'assistant_id',
       * );
       * ```
       */
      retrieve(assistantID, options2) {
        return this._client.get(path11`/assistants/${assistantID}`, {
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Modifies an assistant.
       *
       * @example
       * ```ts
       * const assistant = await client.beta.assistants.update(
       *   'assistant_id',
       * );
       * ```
       */
      update(assistantID, body, options2) {
        return this._client.post(path11`/assistants/${assistantID}`, {
          body,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Returns a list of assistants.
       *
       * @example
       * ```ts
       * // Automatically fetches more pages as needed.
       * for await (const assistant of client.beta.assistants.list()) {
       *   // ...
       * }
       * ```
       */
      list(query = {}, options2) {
        return this._client.getAPIList("/assistants", CursorPage, {
          query,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Delete an assistant.
       *
       * @example
       * ```ts
       * const assistantDeleted =
       *   await client.beta.assistants.delete('assistant_id');
       * ```
       */
      delete(assistantID, options2) {
        return this._client.delete(path11`/assistants/${assistantID}`, {
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
    };
  }
});

// node_modules/openai/resources/beta/realtime/sessions.mjs
var Sessions;
var init_sessions = __esm({
  "node_modules/openai/resources/beta/realtime/sessions.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_headers();
    Sessions = class extends APIResource {
      static {
        __name(this, "Sessions");
      }
      /**
       * Create an ephemeral API token for use in client-side applications with the
       * Realtime API. Can be configured with the same session parameters as the
       * `session.update` client event.
       *
       * It responds with a session object, plus a `client_secret` key which contains a
       * usable ephemeral API token that can be used to authenticate browser clients for
       * the Realtime API.
       *
       * @example
       * ```ts
       * const session =
       *   await client.beta.realtime.sessions.create();
       * ```
       */
      create(body, options2) {
        return this._client.post("/realtime/sessions", {
          body,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
    };
  }
});

// node_modules/openai/resources/beta/realtime/transcription-sessions.mjs
var TranscriptionSessions;
var init_transcription_sessions = __esm({
  "node_modules/openai/resources/beta/realtime/transcription-sessions.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_headers();
    TranscriptionSessions = class extends APIResource {
      static {
        __name(this, "TranscriptionSessions");
      }
      /**
       * Create an ephemeral API token for use in client-side applications with the
       * Realtime API specifically for realtime transcriptions. Can be configured with
       * the same session parameters as the `transcription_session.update` client event.
       *
       * It responds with a session object, plus a `client_secret` key which contains a
       * usable ephemeral API token that can be used to authenticate browser clients for
       * the Realtime API.
       *
       * @example
       * ```ts
       * const transcriptionSession =
       *   await client.beta.realtime.transcriptionSessions.create();
       * ```
       */
      create(body, options2) {
        return this._client.post("/realtime/transcription_sessions", {
          body,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
    };
  }
});

// node_modules/openai/resources/beta/realtime/realtime.mjs
var Realtime;
var init_realtime = __esm({
  "node_modules/openai/resources/beta/realtime/realtime.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_sessions();
    init_sessions();
    init_transcription_sessions();
    init_transcription_sessions();
    Realtime = class extends APIResource {
      static {
        __name(this, "Realtime");
      }
      constructor() {
        super(...arguments);
        this.sessions = new Sessions(this._client);
        this.transcriptionSessions = new TranscriptionSessions(this._client);
      }
    };
    Realtime.Sessions = Sessions;
    Realtime.TranscriptionSessions = TranscriptionSessions;
  }
});

// node_modules/openai/resources/beta/threads/messages.mjs
var Messages2;
var init_messages2 = __esm({
  "node_modules/openai/resources/beta/threads/messages.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_pagination();
    init_headers();
    init_path();
    Messages2 = class extends APIResource {
      static {
        __name(this, "Messages");
      }
      /**
       * Create a message.
       *
       * @deprecated The Assistants API is deprecated in favor of the Responses API
       */
      create(threadID, body, options2) {
        return this._client.post(path11`/threads/${threadID}/messages`, {
          body,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Retrieve a message.
       *
       * @deprecated The Assistants API is deprecated in favor of the Responses API
       */
      retrieve(messageID, params, options2) {
        const { thread_id } = params;
        return this._client.get(path11`/threads/${thread_id}/messages/${messageID}`, {
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Modifies a message.
       *
       * @deprecated The Assistants API is deprecated in favor of the Responses API
       */
      update(messageID, params, options2) {
        const { thread_id, ...body } = params;
        return this._client.post(path11`/threads/${thread_id}/messages/${messageID}`, {
          body,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Returns a list of messages for a given thread.
       *
       * @deprecated The Assistants API is deprecated in favor of the Responses API
       */
      list(threadID, query = {}, options2) {
        return this._client.getAPIList(path11`/threads/${threadID}/messages`, CursorPage, {
          query,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Deletes a message.
       *
       * @deprecated The Assistants API is deprecated in favor of the Responses API
       */
      delete(messageID, params, options2) {
        const { thread_id } = params;
        return this._client.delete(path11`/threads/${thread_id}/messages/${messageID}`, {
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
    };
  }
});

// node_modules/openai/resources/beta/threads/runs/steps.mjs
var Steps;
var init_steps = __esm({
  "node_modules/openai/resources/beta/threads/runs/steps.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_pagination();
    init_headers();
    init_path();
    Steps = class extends APIResource {
      static {
        __name(this, "Steps");
      }
      /**
       * Retrieves a run step.
       *
       * @deprecated The Assistants API is deprecated in favor of the Responses API
       */
      retrieve(stepID, params, options2) {
        const { thread_id, run_id, ...query } = params;
        return this._client.get(path11`/threads/${thread_id}/runs/${run_id}/steps/${stepID}`, {
          query,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Returns a list of run steps belonging to a run.
       *
       * @deprecated The Assistants API is deprecated in favor of the Responses API
       */
      list(runID, params, options2) {
        const { thread_id, ...query } = params;
        return this._client.getAPIList(path11`/threads/${thread_id}/runs/${runID}/steps`, CursorPage, {
          query,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
    };
  }
});

// node_modules/openai/internal/utils/base64.mjs
var toFloat32Array;
var init_base64 = __esm({
  "node_modules/openai/internal/utils/base64.mjs"() {
    init_esbuild_shims();
    init_error();
    init_bytes();
    toFloat32Array = /* @__PURE__ */ __name((base64Str) => {
      if (typeof Buffer !== "undefined") {
        const buf = Buffer.from(base64Str, "base64");
        return Array.from(new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT));
      } else {
        const binaryStr = atob(base64Str);
        const len = binaryStr.length;
        const bytes = new Uint8Array(len);
        for (let i = 0; i < len; i++) {
          bytes[i] = binaryStr.charCodeAt(i);
        }
        return Array.from(new Float32Array(bytes.buffer));
      }
    }, "toFloat32Array");
  }
});

// node_modules/openai/internal/utils/env.mjs
var readEnv;
var init_env = __esm({
  "node_modules/openai/internal/utils/env.mjs"() {
    init_esbuild_shims();
    readEnv = /* @__PURE__ */ __name((env7) => {
      if (typeof globalThis.process !== "undefined") {
        return globalThis.process.env?.[env7]?.trim() ?? void 0;
      }
      if (typeof globalThis.Deno !== "undefined") {
        return globalThis.Deno.env?.get?.(env7)?.trim();
      }
      return void 0;
    }, "readEnv");
  }
});

// node_modules/openai/internal/utils.mjs
var init_utils5 = __esm({
  "node_modules/openai/internal/utils.mjs"() {
    init_esbuild_shims();
    init_values();
    init_base64();
    init_env();
    init_log();
    init_uuid();
    init_sleep();
  }
});

// node_modules/openai/lib/AssistantStream.mjs
function assertNever2(_x) {
}
var _AssistantStream_instances, _a, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun, AssistantStream;
var init_AssistantStream = __esm({
  "node_modules/openai/lib/AssistantStream.mjs"() {
    init_esbuild_shims();
    init_tslib();
    init_streaming2();
    init_error2();
    init_EventStream();
    init_utils5();
    AssistantStream = class extends EventStream {
      static {
        __name(this, "AssistantStream");
      }
      constructor() {
        super(...arguments);
        _AssistantStream_instances.add(this);
        _AssistantStream_events.set(this, []);
        _AssistantStream_runStepSnapshots.set(this, {});
        _AssistantStream_messageSnapshots.set(this, {});
        _AssistantStream_messageSnapshot.set(this, void 0);
        _AssistantStream_finalRun.set(this, void 0);
        _AssistantStream_currentContentIndex.set(this, void 0);
        _AssistantStream_currentContent.set(this, void 0);
        _AssistantStream_currentToolCallIndex.set(this, void 0);
        _AssistantStream_currentToolCall.set(this, void 0);
        _AssistantStream_currentEvent.set(this, void 0);
        _AssistantStream_currentRunSnapshot.set(this, void 0);
        _AssistantStream_currentRunStepSnapshot.set(this, void 0);
      }
      [(_AssistantStream_events = /* @__PURE__ */ new WeakMap(), _AssistantStream_runStepSnapshots = /* @__PURE__ */ new WeakMap(), _AssistantStream_messageSnapshots = /* @__PURE__ */ new WeakMap(), _AssistantStream_messageSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_finalRun = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentContentIndex = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentContent = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentToolCallIndex = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentToolCall = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentEvent = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentRunSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentRunStepSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() {
        const pushQueue = [];
        const readQueue = [];
        let done = false;
        this.on("event", (event) => {
          const reader = readQueue.shift();
          if (reader) {
            reader.resolve(event);
          } else {
            pushQueue.push(event);
          }
        });
        this.on("end", () => {
          done = true;
          for (const reader of readQueue) {
            reader.resolve(void 0);
          }
          readQueue.length = 0;
        });
        this.on("abort", (err) => {
          done = true;
          for (const reader of readQueue) {
            reader.reject(err);
          }
          readQueue.length = 0;
        });
        this.on("error", (err) => {
          done = true;
          for (const reader of readQueue) {
            reader.reject(err);
          }
          readQueue.length = 0;
        });
        return {
          next: /* @__PURE__ */ __name(async () => {
            if (!pushQueue.length) {
              if (done) {
                return { value: void 0, done: true };
              }
              return new Promise((resolve24, reject) => readQueue.push({ resolve: resolve24, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
            }
            const chunk = pushQueue.shift();
            return { value: chunk, done: false };
          }, "next"),
          return: /* @__PURE__ */ __name(async () => {
            this.abort();
            return { value: void 0, done: true };
          }, "return")
        };
      }
      static fromReadableStream(stream2) {
        const runner = new _a();
        runner._run(() => runner._fromReadableStream(stream2));
        return runner;
      }
      async _fromReadableStream(readableStream, options2) {
        const signal = options2?.signal;
        if (signal) {
          if (signal.aborted)
            this.controller.abort();
          signal.addEventListener("abort", () => this.controller.abort());
        }
        this._connected();
        const stream2 = Stream2.fromReadableStream(readableStream, this.controller);
        for await (const event of stream2) {
          __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
        }
        if (stream2.controller.signal?.aborted) {
          throw new APIUserAbortError();
        }
        return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
      }
      toReadableStream() {
        const stream2 = new Stream2(this[Symbol.asyncIterator].bind(this), this.controller);
        return stream2.toReadableStream();
      }
      static createToolAssistantStream(runId, runs, params, options2) {
        const runner = new _a();
        runner._run(() => runner._runToolAssistantStream(runId, runs, params, {
          ...options2,
          headers: { ...options2?.headers, "X-Stainless-Helper-Method": "stream" }
        }));
        return runner;
      }
      async _createToolAssistantStream(run, runId, params, options2) {
        const signal = options2?.signal;
        if (signal) {
          if (signal.aborted)
            this.controller.abort();
          signal.addEventListener("abort", () => this.controller.abort());
        }
        const body = { ...params, stream: true };
        const stream2 = await run.submitToolOutputs(runId, body, {
          ...options2,
          signal: this.controller.signal
        });
        this._connected();
        for await (const event of stream2) {
          __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
        }
        if (stream2.controller.signal?.aborted) {
          throw new APIUserAbortError();
        }
        return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
      }
      static createThreadAssistantStream(params, thread, options2) {
        const runner = new _a();
        runner._run(() => runner._threadAssistantStream(params, thread, {
          ...options2,
          headers: { ...options2?.headers, "X-Stainless-Helper-Method": "stream" }
        }));
        return runner;
      }
      static createAssistantStream(threadId, runs, params, options2) {
        const runner = new _a();
        runner._run(() => runner._runAssistantStream(threadId, runs, params, {
          ...options2,
          headers: { ...options2?.headers, "X-Stainless-Helper-Method": "stream" }
        }));
        return runner;
      }
      currentEvent() {
        return __classPrivateFieldGet(this, _AssistantStream_currentEvent, "f");
      }
      currentRun() {
        return __classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, "f");
      }
      currentMessageSnapshot() {
        return __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f");
      }
      currentRunStepSnapshot() {
        return __classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f");
      }
      async finalRunSteps() {
        await this.done();
        return Object.values(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f"));
      }
      async finalMessages() {
        await this.done();
        return Object.values(__classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f"));
      }
      async finalRun() {
        await this.done();
        if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f"))
          throw Error("Final run was not received.");
        return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f");
      }
      async _createThreadAssistantStream(thread, params, options2) {
        const signal = options2?.signal;
        if (signal) {
          if (signal.aborted)
            this.controller.abort();
          signal.addEventListener("abort", () => this.controller.abort());
        }
        const body = { ...params, stream: true };
        const stream2 = await thread.createAndRun(body, { ...options2, signal: this.controller.signal });
        this._connected();
        for await (const event of stream2) {
          __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
        }
        if (stream2.controller.signal?.aborted) {
          throw new APIUserAbortError();
        }
        return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
      }
      async _createAssistantStream(run, threadId, params, options2) {
        const signal = options2?.signal;
        if (signal) {
          if (signal.aborted)
            this.controller.abort();
          signal.addEventListener("abort", () => this.controller.abort());
        }
        const body = { ...params, stream: true };
        const stream2 = await run.create(threadId, body, { ...options2, signal: this.controller.signal });
        this._connected();
        for await (const event of stream2) {
          __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
        }
        if (stream2.controller.signal?.aborted) {
          throw new APIUserAbortError();
        }
        return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
      }
      static accumulateDelta(acc, delta) {
        for (const [key, deltaValue] of Object.entries(delta)) {
          if (!acc.hasOwnProperty(key)) {
            acc[key] = deltaValue;
            continue;
          }
          let accValue = acc[key];
          if (accValue === null || accValue === void 0) {
            acc[key] = deltaValue;
            continue;
          }
          if (key === "index" || key === "type") {
            acc[key] = deltaValue;
            continue;
          }
          if (typeof accValue === "string" && typeof deltaValue === "string") {
            accValue += deltaValue;
          } else if (typeof accValue === "number" && typeof deltaValue === "number") {
            accValue += deltaValue;
          } else if (isObj(accValue) && isObj(deltaValue)) {
            accValue = this.accumulateDelta(accValue, deltaValue);
          } else if (Array.isArray(accValue) && Array.isArray(deltaValue)) {
            if (accValue.every((x) => typeof x === "string" || typeof x === "number")) {
              accValue.push(...deltaValue);
              continue;
            }
            for (const deltaEntry of deltaValue) {
              if (!isObj(deltaEntry)) {
                throw new Error(`Expected array delta entry to be an object but got: ${deltaEntry}`);
              }
              const index = deltaEntry["index"];
              if (index == null) {
                console.error(deltaEntry);
                throw new Error("Expected array delta entry to have an `index` property");
              }
              if (typeof index !== "number") {
                throw new Error(`Expected array delta entry \`index\` property to be a number but got ${index}`);
              }
              const accEntry = accValue[index];
              if (accEntry == null) {
                accValue.push(deltaEntry);
              } else {
                accValue[index] = this.accumulateDelta(accEntry, deltaEntry);
              }
            }
            continue;
          } else {
            throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`);
          }
          acc[key] = accValue;
        }
        return acc;
      }
      _addRun(run) {
        return run;
      }
      async _threadAssistantStream(params, thread, options2) {
        return await this._createThreadAssistantStream(thread, params, options2);
      }
      async _runAssistantStream(threadId, runs, params, options2) {
        return await this._createAssistantStream(runs, threadId, params, options2);
      }
      async _runToolAssistantStream(runId, runs, params, options2) {
        return await this._createToolAssistantStream(runs, runId, params, options2);
      }
    };
    _a = AssistantStream, _AssistantStream_addEvent = /* @__PURE__ */ __name(function _AssistantStream_addEvent2(event) {
      if (this.ended)
        return;
      __classPrivateFieldSet(this, _AssistantStream_currentEvent, event, "f");
      __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event);
      switch (event.event) {
        case "thread.created":
          break;
        case "thread.run.created":
        case "thread.run.queued":
        case "thread.run.in_progress":
        case "thread.run.requires_action":
        case "thread.run.completed":
        case "thread.run.incomplete":
        case "thread.run.failed":
        case "thread.run.cancelling":
        case "thread.run.cancelled":
        case "thread.run.expired":
          __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event);
          break;
        case "thread.run.step.created":
        case "thread.run.step.in_progress":
        case "thread.run.step.delta":
        case "thread.run.step.completed":
        case "thread.run.step.failed":
        case "thread.run.step.cancelled":
        case "thread.run.step.expired":
          __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event);
          break;
        case "thread.message.created":
        case "thread.message.in_progress":
        case "thread.message.delta":
        case "thread.message.completed":
        case "thread.message.incomplete":
          __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event);
          break;
        case "error":
          throw new Error("Encountered an error event in event processing - errors should be processed earlier");
        default:
          assertNever2(event);
      }
    }, "_AssistantStream_addEvent"), _AssistantStream_endRequest = /* @__PURE__ */ __name(function _AssistantStream_endRequest2() {
      if (this.ended) {
        throw new OpenAIError(`stream has ended, this shouldn't happen`);
      }
      if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f"))
        throw Error("Final run has not been received");
      return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f");
    }, "_AssistantStream_endRequest"), _AssistantStream_handleMessage = /* @__PURE__ */ __name(function _AssistantStream_handleMessage2(event) {
      const [accumulatedMessage, newContent] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
      __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f");
      __classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage;
      for (const content of newContent) {
        const snapshotContent = accumulatedMessage.content[content.index];
        if (snapshotContent?.type == "text") {
          this._emit("textCreated", snapshotContent.text);
        }
      }
      switch (event.event) {
        case "thread.message.created":
          this._emit("messageCreated", event.data);
          break;
        case "thread.message.in_progress":
          break;
        case "thread.message.delta":
          this._emit("messageDelta", event.data.delta, accumulatedMessage);
          if (event.data.delta.content) {
            for (const content of event.data.delta.content) {
              if (content.type == "text" && content.text) {
                let textDelta = content.text;
                let snapshot = accumulatedMessage.content[content.index];
                if (snapshot && snapshot.type == "text") {
                  this._emit("textDelta", textDelta, snapshot.text);
                } else {
                  throw Error("The snapshot associated with this text delta is not text or missing");
                }
              }
              if (content.index != __classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")) {
                if (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f")) {
                  switch (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f").type) {
                    case "text":
                      this._emit("textDone", __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
                      break;
                    case "image_file":
                      this._emit("imageFileDone", __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
                      break;
                  }
                }
                __classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, "f");
              }
              __classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f");
            }
          }
          break;
        case "thread.message.completed":
        case "thread.message.incomplete":
          if (__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f") !== void 0) {
            const currentContent = event.data.content[__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")];
            if (currentContent) {
              switch (currentContent.type) {
                case "image_file":
                  this._emit("imageFileDone", currentContent.image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
                  break;
                case "text":
                  this._emit("textDone", currentContent.text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
                  break;
              }
            }
          }
          if (__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) {
            this._emit("messageDone", event.data);
          }
          __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, void 0, "f");
      }
    }, "_AssistantStream_handleMessage"), _AssistantStream_handleRunStep = /* @__PURE__ */ __name(function _AssistantStream_handleRunStep2(event) {
      const accumulatedRunStep = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event);
      __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f");
      switch (event.event) {
        case "thread.run.step.created":
          this._emit("runStepCreated", event.data);
          break;
        case "thread.run.step.delta":
          const delta = event.data.delta;
          if (delta.step_details && delta.step_details.type == "tool_calls" && delta.step_details.tool_calls && accumulatedRunStep.step_details.type == "tool_calls") {
            for (const toolCall of delta.step_details.tool_calls) {
              if (toolCall.index == __classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, "f")) {
                this._emit("toolCallDelta", toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]);
              } else {
                if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
                  this._emit("toolCallDone", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
                }
                __classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f");
                __classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f");
                if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"))
                  this._emit("toolCallCreated", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
              }
            }
          }
          this._emit("runStepDelta", event.data.delta, accumulatedRunStep);
          break;
        case "thread.run.step.completed":
        case "thread.run.step.failed":
        case "thread.run.step.cancelled":
        case "thread.run.step.expired":
          __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, void 0, "f");
          const details = event.data.step_details;
          if (details.type == "tool_calls") {
            if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
              this._emit("toolCallDone", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
              __classPrivateFieldSet(this, _AssistantStream_currentToolCall, void 0, "f");
            }
          }
          this._emit("runStepDone", event.data, accumulatedRunStep);
          break;
        case "thread.run.step.in_progress":
          break;
      }
    }, "_AssistantStream_handleRunStep"), _AssistantStream_handleEvent = /* @__PURE__ */ __name(function _AssistantStream_handleEvent2(event) {
      __classPrivateFieldGet(this, _AssistantStream_events, "f").push(event);
      this._emit("event", event);
    }, "_AssistantStream_handleEvent"), _AssistantStream_accumulateRunStep = /* @__PURE__ */ __name(function _AssistantStream_accumulateRunStep2(event) {
      switch (event.event) {
        case "thread.run.step.created":
          __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
          return event.data;
        case "thread.run.step.delta":
          let snapshot = __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
          if (!snapshot) {
            throw Error("Received a RunStepDelta before creation of a snapshot");
          }
          let data = event.data;
          if (data.delta) {
            const accumulated = _a.accumulateDelta(snapshot, data.delta);
            __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated;
          }
          return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
        case "thread.run.step.completed":
        case "thread.run.step.failed":
        case "thread.run.step.cancelled":
        case "thread.run.step.expired":
        case "thread.run.step.in_progress":
          __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
          break;
      }
      if (__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id])
        return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
      throw new Error("No snapshot available");
    }, "_AssistantStream_accumulateRunStep"), _AssistantStream_accumulateMessage = /* @__PURE__ */ __name(function _AssistantStream_accumulateMessage2(event, snapshot) {
      let newContent = [];
      switch (event.event) {
        case "thread.message.created":
          return [event.data, newContent];
        case "thread.message.delta":
          if (!snapshot) {
            throw Error("Received a delta with no existing snapshot (there should be one from message creation)");
          }
          let data = event.data;
          if (data.delta.content) {
            for (const contentElement of data.delta.content) {
              if (contentElement.index in snapshot.content) {
                let currentContent = snapshot.content[contentElement.index];
                snapshot.content[contentElement.index] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent);
              } else {
                snapshot.content[contentElement.index] = contentElement;
                newContent.push(contentElement);
              }
            }
          }
          return [snapshot, newContent];
        case "thread.message.in_progress":
        case "thread.message.completed":
        case "thread.message.incomplete":
          if (snapshot) {
            return [snapshot, newContent];
          } else {
            throw Error("Received thread message event with no existing snapshot");
          }
      }
      throw Error("Tried to accumulate a non-message event");
    }, "_AssistantStream_accumulateMessage"), _AssistantStream_accumulateContent = /* @__PURE__ */ __name(function _AssistantStream_accumulateContent2(contentElement, currentContent) {
      return _a.accumulateDelta(currentContent, contentElement);
    }, "_AssistantStream_accumulateContent"), _AssistantStream_handleRun = /* @__PURE__ */ __name(function _AssistantStream_handleRun2(event) {
      __classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, "f");
      switch (event.event) {
        case "thread.run.created":
          break;
        case "thread.run.queued":
          break;
        case "thread.run.in_progress":
          break;
        case "thread.run.requires_action":
        case "thread.run.cancelled":
        case "thread.run.failed":
        case "thread.run.completed":
        case "thread.run.expired":
        case "thread.run.incomplete":
          __classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, "f");
          if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
            this._emit("toolCallDone", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
            __classPrivateFieldSet(this, _AssistantStream_currentToolCall, void 0, "f");
          }
          break;
        case "thread.run.cancelling":
          break;
      }
    }, "_AssistantStream_handleRun");
    __name(assertNever2, "assertNever");
  }
});

// node_modules/openai/resources/beta/threads/runs/runs.mjs
var Runs;
var init_runs = __esm({
  "node_modules/openai/resources/beta/threads/runs/runs.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_steps();
    init_steps();
    init_pagination();
    init_headers();
    init_AssistantStream();
    init_sleep();
    init_path();
    Runs = class extends APIResource {
      static {
        __name(this, "Runs");
      }
      constructor() {
        super(...arguments);
        this.steps = new Steps(this._client);
      }
      create(threadID, params, options2) {
        const { include, ...body } = params;
        return this._client.post(path11`/threads/${threadID}/runs`, {
          query: { include },
          body,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
          stream: params.stream ?? false
        });
      }
      /**
       * Retrieves a run.
       *
       * @deprecated The Assistants API is deprecated in favor of the Responses API
       */
      retrieve(runID, params, options2) {
        const { thread_id } = params;
        return this._client.get(path11`/threads/${thread_id}/runs/${runID}`, {
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Modifies a run.
       *
       * @deprecated The Assistants API is deprecated in favor of the Responses API
       */
      update(runID, params, options2) {
        const { thread_id, ...body } = params;
        return this._client.post(path11`/threads/${thread_id}/runs/${runID}`, {
          body,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Returns a list of runs belonging to a thread.
       *
       * @deprecated The Assistants API is deprecated in favor of the Responses API
       */
      list(threadID, query = {}, options2) {
        return this._client.getAPIList(path11`/threads/${threadID}/runs`, CursorPage, {
          query,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Cancels a run that is `in_progress`.
       *
       * @deprecated The Assistants API is deprecated in favor of the Responses API
       */
      cancel(runID, params, options2) {
        const { thread_id } = params;
        return this._client.post(path11`/threads/${thread_id}/runs/${runID}/cancel`, {
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * A helper to create a run an poll for a terminal state. More information on Run
       * lifecycles can be found here:
       * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
       */
      async createAndPoll(threadId, body, options2) {
        const run = await this.create(threadId, body, options2);
        return await this.poll(run.id, { thread_id: threadId }, options2);
      }
      /**
       * Create a Run stream
       *
       * @deprecated use `stream` instead
       */
      createAndStream(threadId, body, options2) {
        return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options2);
      }
      /**
       * A helper to poll a run status until it reaches a terminal state. More
       * information on Run lifecycles can be found here:
       * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
       */
      async poll(runId, params, options2) {
        const headers = buildHeaders([
          options2?.headers,
          {
            "X-Stainless-Poll-Helper": "true",
            "X-Stainless-Custom-Poll-Interval": options2?.pollIntervalMs?.toString() ?? void 0
          }
        ]);
        while (true) {
          const { data: run, response } = await this.retrieve(runId, params, {
            ...options2,
            headers: { ...options2?.headers, ...headers }
          }).withResponse();
          switch (run.status) {
            //If we are in any sort of intermediate state we poll
            case "queued":
            case "in_progress":
            case "cancelling":
              let sleepInterval = 5e3;
              if (options2?.pollIntervalMs) {
                sleepInterval = options2.pollIntervalMs;
              } else {
                const headerInterval = response.headers.get("openai-poll-after-ms");
                if (headerInterval) {
                  const headerIntervalMs = parseInt(headerInterval);
                  if (!isNaN(headerIntervalMs)) {
                    sleepInterval = headerIntervalMs;
                  }
                }
              }
              await sleep2(sleepInterval);
              break;
            //We return the run in any terminal state.
            case "requires_action":
            case "incomplete":
            case "cancelled":
            case "completed":
            case "failed":
            case "expired":
              return run;
          }
        }
      }
      /**
       * Create a Run stream
       */
      stream(threadId, body, options2) {
        return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options2);
      }
      submitToolOutputs(runID, params, options2) {
        const { thread_id, ...body } = params;
        return this._client.post(path11`/threads/${thread_id}/runs/${runID}/submit_tool_outputs`, {
          body,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
          stream: params.stream ?? false
        });
      }
      /**
       * A helper to submit a tool output to a run and poll for a terminal run state.
       * More information on Run lifecycles can be found here:
       * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
       */
      async submitToolOutputsAndPoll(runId, params, options2) {
        const run = await this.submitToolOutputs(runId, params, options2);
        return await this.poll(run.id, params, options2);
      }
      /**
       * Submit the tool outputs from a previous run and stream the run to a terminal
       * state. More information on Run lifecycles can be found here:
       * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
       */
      submitToolOutputsStream(runId, params, options2) {
        return AssistantStream.createToolAssistantStream(runId, this._client.beta.threads.runs, params, options2);
      }
    };
    Runs.Steps = Steps;
  }
});

// node_modules/openai/resources/beta/threads/threads.mjs
var Threads;
var init_threads = __esm({
  "node_modules/openai/resources/beta/threads/threads.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_messages2();
    init_messages2();
    init_runs();
    init_runs();
    init_headers();
    init_AssistantStream();
    init_path();
    Threads = class extends APIResource {
      static {
        __name(this, "Threads");
      }
      constructor() {
        super(...arguments);
        this.runs = new Runs(this._client);
        this.messages = new Messages2(this._client);
      }
      /**
       * Create a thread.
       *
       * @deprecated The Assistants API is deprecated in favor of the Responses API
       */
      create(body = {}, options2) {
        return this._client.post("/threads", {
          body,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Retrieves a thread.
       *
       * @deprecated The Assistants API is deprecated in favor of the Responses API
       */
      retrieve(threadID, options2) {
        return this._client.get(path11`/threads/${threadID}`, {
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Modifies a thread.
       *
       * @deprecated The Assistants API is deprecated in favor of the Responses API
       */
      update(threadID, body, options2) {
        return this._client.post(path11`/threads/${threadID}`, {
          body,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Delete a thread.
       *
       * @deprecated The Assistants API is deprecated in favor of the Responses API
       */
      delete(threadID, options2) {
        return this._client.delete(path11`/threads/${threadID}`, {
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      createAndRun(body, options2) {
        return this._client.post("/threads/runs", {
          body,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
          stream: body.stream ?? false
        });
      }
      /**
       * A helper to create a thread, start a run and then poll for a terminal state.
       * More information on Run lifecycles can be found here:
       * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
       */
      async createAndRunPoll(body, options2) {
        const run = await this.createAndRun(body, options2);
        return await this.runs.poll(run.id, { thread_id: run.thread_id }, options2);
      }
      /**
       * Create a thread and stream the run back
       */
      createAndRunStream(body, options2) {
        return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options2);
      }
    };
    Threads.Runs = Runs;
    Threads.Messages = Messages2;
  }
});

// node_modules/openai/resources/beta/beta.mjs
var Beta;
var init_beta = __esm({
  "node_modules/openai/resources/beta/beta.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_assistants();
    init_assistants();
    init_realtime();
    init_realtime();
    init_threads();
    init_threads();
    Beta = class extends APIResource {
      static {
        __name(this, "Beta");
      }
      constructor() {
        super(...arguments);
        this.realtime = new Realtime(this._client);
        this.assistants = new Assistants(this._client);
        this.threads = new Threads(this._client);
      }
    };
    Beta.Realtime = Realtime;
    Beta.Assistants = Assistants;
    Beta.Threads = Threads;
  }
});

// node_modules/openai/resources/completions.mjs
var Completions2;
var init_completions3 = __esm({
  "node_modules/openai/resources/completions.mjs"() {
    init_esbuild_shims();
    init_resource2();
    Completions2 = class extends APIResource {
      static {
        __name(this, "Completions");
      }
      create(body, options2) {
        return this._client.post("/completions", { body, ...options2, stream: body.stream ?? false });
      }
    };
  }
});

// node_modules/openai/resources/containers/files/content.mjs
var Content;
var init_content = __esm({
  "node_modules/openai/resources/containers/files/content.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_headers();
    init_path();
    Content = class extends APIResource {
      static {
        __name(this, "Content");
      }
      /**
       * Retrieve Container File Content
       */
      retrieve(fileID, params, options2) {
        const { container_id } = params;
        return this._client.get(path11`/containers/${container_id}/files/${fileID}/content`, {
          ...options2,
          headers: buildHeaders([{ Accept: "application/binary" }, options2?.headers]),
          __binaryResponse: true
        });
      }
    };
  }
});

// node_modules/openai/resources/containers/files/files.mjs
var Files2;
var init_files = __esm({
  "node_modules/openai/resources/containers/files/files.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_content();
    init_content();
    init_pagination();
    init_headers();
    init_uploads();
    init_path();
    Files2 = class extends APIResource {
      static {
        __name(this, "Files");
      }
      constructor() {
        super(...arguments);
        this.content = new Content(this._client);
      }
      /**
       * Create a Container File
       *
       * You can send either a multipart/form-data request with the raw file content, or
       * a JSON request with a file ID.
       */
      create(containerID, body, options2) {
        return this._client.post(path11`/containers/${containerID}/files`, multipartFormRequestOptions({ body, ...options2 }, this._client));
      }
      /**
       * Retrieve Container File
       */
      retrieve(fileID, params, options2) {
        const { container_id } = params;
        return this._client.get(path11`/containers/${container_id}/files/${fileID}`, options2);
      }
      /**
       * List Container files
       */
      list(containerID, query = {}, options2) {
        return this._client.getAPIList(path11`/containers/${containerID}/files`, CursorPage, {
          query,
          ...options2
        });
      }
      /**
       * Delete Container File
       */
      delete(fileID, params, options2) {
        const { container_id } = params;
        return this._client.delete(path11`/containers/${container_id}/files/${fileID}`, {
          ...options2,
          headers: buildHeaders([{ Accept: "*/*" }, options2?.headers])
        });
      }
    };
    Files2.Content = Content;
  }
});

// node_modules/openai/resources/containers/containers.mjs
var Containers;
var init_containers = __esm({
  "node_modules/openai/resources/containers/containers.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_files();
    init_files();
    init_pagination();
    init_headers();
    init_path();
    Containers = class extends APIResource {
      static {
        __name(this, "Containers");
      }
      constructor() {
        super(...arguments);
        this.files = new Files2(this._client);
      }
      /**
       * Create Container
       */
      create(body, options2) {
        return this._client.post("/containers", { body, ...options2 });
      }
      /**
       * Retrieve Container
       */
      retrieve(containerID, options2) {
        return this._client.get(path11`/containers/${containerID}`, options2);
      }
      /**
       * List Containers
       */
      list(query = {}, options2) {
        return this._client.getAPIList("/containers", CursorPage, { query, ...options2 });
      }
      /**
       * Delete Container
       */
      delete(containerID, options2) {
        return this._client.delete(path11`/containers/${containerID}`, {
          ...options2,
          headers: buildHeaders([{ Accept: "*/*" }, options2?.headers])
        });
      }
    };
    Containers.Files = Files2;
  }
});

// node_modules/openai/resources/embeddings.mjs
var Embeddings;
var init_embeddings = __esm({
  "node_modules/openai/resources/embeddings.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_utils5();
    Embeddings = class extends APIResource {
      static {
        __name(this, "Embeddings");
      }
      /**
       * Creates an embedding vector representing the input text.
       *
       * @example
       * ```ts
       * const createEmbeddingResponse =
       *   await client.embeddings.create({
       *     input: 'The quick brown fox jumped over the lazy dog',
       *     model: 'text-embedding-3-small',
       *   });
       * ```
       */
      create(body, options2) {
        const hasUserProvidedEncodingFormat = !!body.encoding_format;
        let encoding_format = hasUserProvidedEncodingFormat ? body.encoding_format : "base64";
        if (hasUserProvidedEncodingFormat) {
          loggerFor(this._client).debug("embeddings/user defined encoding_format:", body.encoding_format);
        }
        const response = this._client.post("/embeddings", {
          body: {
            ...body,
            encoding_format
          },
          ...options2
        });
        if (hasUserProvidedEncodingFormat) {
          return response;
        }
        loggerFor(this._client).debug("embeddings/decoding base64 embeddings from base64");
        return response._thenUnwrap((response2) => {
          if (response2 && response2.data) {
            response2.data.forEach((embeddingBase64Obj) => {
              const embeddingBase64Str = embeddingBase64Obj.embedding;
              embeddingBase64Obj.embedding = toFloat32Array(embeddingBase64Str);
            });
          }
          return response2;
        });
      }
    };
  }
});

// node_modules/openai/resources/evals/runs/output-items.mjs
var OutputItems;
var init_output_items = __esm({
  "node_modules/openai/resources/evals/runs/output-items.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_pagination();
    init_path();
    OutputItems = class extends APIResource {
      static {
        __name(this, "OutputItems");
      }
      /**
       * Get an evaluation run output item by ID.
       */
      retrieve(outputItemID, params, options2) {
        const { eval_id, run_id } = params;
        return this._client.get(path11`/evals/${eval_id}/runs/${run_id}/output_items/${outputItemID}`, options2);
      }
      /**
       * Get a list of output items for an evaluation run.
       */
      list(runID, params, options2) {
        const { eval_id, ...query } = params;
        return this._client.getAPIList(path11`/evals/${eval_id}/runs/${runID}/output_items`, CursorPage, { query, ...options2 });
      }
    };
  }
});

// node_modules/openai/resources/evals/runs/runs.mjs
var Runs2;
var init_runs2 = __esm({
  "node_modules/openai/resources/evals/runs/runs.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_output_items();
    init_output_items();
    init_pagination();
    init_path();
    Runs2 = class extends APIResource {
      static {
        __name(this, "Runs");
      }
      constructor() {
        super(...arguments);
        this.outputItems = new OutputItems(this._client);
      }
      /**
       * Kicks off a new run for a given evaluation, specifying the data source, and what
       * model configuration to use to test. The datasource will be validated against the
       * schema specified in the config of the evaluation.
       */
      create(evalID, body, options2) {
        return this._client.post(path11`/evals/${evalID}/runs`, { body, ...options2 });
      }
      /**
       * Get an evaluation run by ID.
       */
      retrieve(runID, params, options2) {
        const { eval_id } = params;
        return this._client.get(path11`/evals/${eval_id}/runs/${runID}`, options2);
      }
      /**
       * Get a list of runs for an evaluation.
       */
      list(evalID, query = {}, options2) {
        return this._client.getAPIList(path11`/evals/${evalID}/runs`, CursorPage, {
          query,
          ...options2
        });
      }
      /**
       * Delete an eval run.
       */
      delete(runID, params, options2) {
        const { eval_id } = params;
        return this._client.delete(path11`/evals/${eval_id}/runs/${runID}`, options2);
      }
      /**
       * Cancel an ongoing evaluation run.
       */
      cancel(runID, params, options2) {
        const { eval_id } = params;
        return this._client.post(path11`/evals/${eval_id}/runs/${runID}`, options2);
      }
    };
    Runs2.OutputItems = OutputItems;
  }
});

// node_modules/openai/resources/evals/evals.mjs
var Evals;
var init_evals = __esm({
  "node_modules/openai/resources/evals/evals.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_runs2();
    init_runs2();
    init_pagination();
    init_path();
    Evals = class extends APIResource {
      static {
        __name(this, "Evals");
      }
      constructor() {
        super(...arguments);
        this.runs = new Runs2(this._client);
      }
      /**
       * Create the structure of an evaluation that can be used to test a model's
       * performance. An evaluation is a set of testing criteria and the config for a
       * data source, which dictates the schema of the data used in the evaluation. After
       * creating an evaluation, you can run it on different models and model parameters.
       * We support several types of graders and datasources. For more information, see
       * the [Evals guide](https://platform.openai.com/docs/guides/evals).
       */
      create(body, options2) {
        return this._client.post("/evals", { body, ...options2 });
      }
      /**
       * Get an evaluation by ID.
       */
      retrieve(evalID, options2) {
        return this._client.get(path11`/evals/${evalID}`, options2);
      }
      /**
       * Update certain properties of an evaluation.
       */
      update(evalID, body, options2) {
        return this._client.post(path11`/evals/${evalID}`, { body, ...options2 });
      }
      /**
       * List evaluations for a project.
       */
      list(query = {}, options2) {
        return this._client.getAPIList("/evals", CursorPage, { query, ...options2 });
      }
      /**
       * Delete an evaluation.
       */
      delete(evalID, options2) {
        return this._client.delete(path11`/evals/${evalID}`, options2);
      }
    };
    Evals.Runs = Runs2;
  }
});

// node_modules/openai/resources/files.mjs
var Files3;
var init_files2 = __esm({
  "node_modules/openai/resources/files.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_pagination();
    init_headers();
    init_sleep();
    init_error2();
    init_uploads();
    init_path();
    Files3 = class extends APIResource {
      static {
        __name(this, "Files");
      }
      /**
       * Upload a file that can be used across various endpoints. Individual files can be
       * up to 512 MB, and the size of all files uploaded by one organization can be up
       * to 100 GB.
       *
       * The Assistants API supports files up to 2 million tokens and of specific file
       * types. See the
       * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for
       * details.
       *
       * The Fine-tuning API only supports `.jsonl` files. The input also has certain
       * required formats for fine-tuning
       * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or
       * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input)
       * models.
       *
       * The Batch API only supports `.jsonl` files up to 200 MB in size. The input also
       * has a specific required
       * [format](https://platform.openai.com/docs/api-reference/batch/request-input).
       *
       * Please [contact us](https://help.openai.com/) if you need to increase these
       * storage limits.
       */
      create(body, options2) {
        return this._client.post("/files", multipartFormRequestOptions({ body, ...options2 }, this._client));
      }
      /**
       * Returns information about a specific file.
       */
      retrieve(fileID, options2) {
        return this._client.get(path11`/files/${fileID}`, options2);
      }
      /**
       * Returns a list of files.
       */
      list(query = {}, options2) {
        return this._client.getAPIList("/files", CursorPage, { query, ...options2 });
      }
      /**
       * Delete a file.
       */
      delete(fileID, options2) {
        return this._client.delete(path11`/files/${fileID}`, options2);
      }
      /**
       * Returns the contents of the specified file.
       */
      content(fileID, options2) {
        return this._client.get(path11`/files/${fileID}/content`, {
          ...options2,
          headers: buildHeaders([{ Accept: "application/binary" }, options2?.headers]),
          __binaryResponse: true
        });
      }
      /**
       * Waits for the given file to be processed, default timeout is 30 mins.
       */
      async waitForProcessing(id, { pollInterval = 5e3, maxWait = 30 * 60 * 1e3 } = {}) {
        const TERMINAL_STATES = /* @__PURE__ */ new Set(["processed", "error", "deleted"]);
        const start = Date.now();
        let file = await this.retrieve(id);
        while (!file.status || !TERMINAL_STATES.has(file.status)) {
          await sleep2(pollInterval);
          file = await this.retrieve(id);
          if (Date.now() - start > maxWait) {
            throw new APIConnectionTimeoutError({
              message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`
            });
          }
        }
        return file;
      }
    };
  }
});

// node_modules/openai/resources/fine-tuning/methods.mjs
var Methods;
var init_methods = __esm({
  "node_modules/openai/resources/fine-tuning/methods.mjs"() {
    init_esbuild_shims();
    init_resource2();
    Methods = class extends APIResource {
      static {
        __name(this, "Methods");
      }
    };
  }
});

// node_modules/openai/resources/fine-tuning/alpha/graders.mjs
var Graders;
var init_graders = __esm({
  "node_modules/openai/resources/fine-tuning/alpha/graders.mjs"() {
    init_esbuild_shims();
    init_resource2();
    Graders = class extends APIResource {
      static {
        __name(this, "Graders");
      }
      /**
       * Run a grader.
       *
       * @example
       * ```ts
       * const response = await client.fineTuning.alpha.graders.run({
       *   grader: {
       *     input: 'input',
       *     name: 'name',
       *     operation: 'eq',
       *     reference: 'reference',
       *     type: 'string_check',
       *   },
       *   model_sample: 'model_sample',
       * });
       * ```
       */
      run(body, options2) {
        return this._client.post("/fine_tuning/alpha/graders/run", { body, ...options2 });
      }
      /**
       * Validate a grader.
       *
       * @example
       * ```ts
       * const response =
       *   await client.fineTuning.alpha.graders.validate({
       *     grader: {
       *       input: 'input',
       *       name: 'name',
       *       operation: 'eq',
       *       reference: 'reference',
       *       type: 'string_check',
       *     },
       *   });
       * ```
       */
      validate(body, options2) {
        return this._client.post("/fine_tuning/alpha/graders/validate", { body, ...options2 });
      }
    };
  }
});

// node_modules/openai/resources/fine-tuning/alpha/alpha.mjs
var Alpha;
var init_alpha = __esm({
  "node_modules/openai/resources/fine-tuning/alpha/alpha.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_graders();
    init_graders();
    Alpha = class extends APIResource {
      static {
        __name(this, "Alpha");
      }
      constructor() {
        super(...arguments);
        this.graders = new Graders(this._client);
      }
    };
    Alpha.Graders = Graders;
  }
});

// node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs
var Permissions;
var init_permissions = __esm({
  "node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_pagination();
    init_path();
    Permissions = class extends APIResource {
      static {
        __name(this, "Permissions");
      }
      /**
       * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys).
       *
       * This enables organization owners to share fine-tuned models with other projects
       * in their organization.
       *
       * @example
       * ```ts
       * // Automatically fetches more pages as needed.
       * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create(
       *   'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd',
       *   { project_ids: ['string'] },
       * )) {
       *   // ...
       * }
       * ```
       */
      create(fineTunedModelCheckpoint, body, options2) {
        return this._client.getAPIList(path11`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, Page, { body, method: "post", ...options2 });
      }
      /**
       * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys).
       *
       * Organization owners can use this endpoint to view all permissions for a
       * fine-tuned model checkpoint.
       *
       * @example
       * ```ts
       * const permission =
       *   await client.fineTuning.checkpoints.permissions.retrieve(
       *     'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
       *   );
       * ```
       */
      retrieve(fineTunedModelCheckpoint, query = {}, options2) {
        return this._client.get(path11`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, {
          query,
          ...options2
        });
      }
      /**
       * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys).
       *
       * Organization owners can use this endpoint to delete a permission for a
       * fine-tuned model checkpoint.
       *
       * @example
       * ```ts
       * const permission =
       *   await client.fineTuning.checkpoints.permissions.delete(
       *     'cp_zc4Q7MP6XxulcVzj4MZdwsAB',
       *     {
       *       fine_tuned_model_checkpoint:
       *         'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd',
       *     },
       *   );
       * ```
       */
      delete(permissionID, params, options2) {
        const { fine_tuned_model_checkpoint } = params;
        return this._client.delete(path11`/fine_tuning/checkpoints/${fine_tuned_model_checkpoint}/permissions/${permissionID}`, options2);
      }
    };
  }
});

// node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs
var Checkpoints;
var init_checkpoints = __esm({
  "node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_permissions();
    init_permissions();
    Checkpoints = class extends APIResource {
      static {
        __name(this, "Checkpoints");
      }
      constructor() {
        super(...arguments);
        this.permissions = new Permissions(this._client);
      }
    };
    Checkpoints.Permissions = Permissions;
  }
});

// node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs
var Checkpoints2;
var init_checkpoints2 = __esm({
  "node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_pagination();
    init_path();
    Checkpoints2 = class extends APIResource {
      static {
        __name(this, "Checkpoints");
      }
      /**
       * List checkpoints for a fine-tuning job.
       *
       * @example
       * ```ts
       * // Automatically fetches more pages as needed.
       * for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list(
       *   'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
       * )) {
       *   // ...
       * }
       * ```
       */
      list(fineTuningJobID, query = {}, options2) {
        return this._client.getAPIList(path11`/fine_tuning/jobs/${fineTuningJobID}/checkpoints`, CursorPage, { query, ...options2 });
      }
    };
  }
});

// node_modules/openai/resources/fine-tuning/jobs/jobs.mjs
var Jobs;
var init_jobs = __esm({
  "node_modules/openai/resources/fine-tuning/jobs/jobs.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_checkpoints2();
    init_checkpoints2();
    init_pagination();
    init_path();
    Jobs = class extends APIResource {
      static {
        __name(this, "Jobs");
      }
      constructor() {
        super(...arguments);
        this.checkpoints = new Checkpoints2(this._client);
      }
      /**
       * Creates a fine-tuning job which begins the process of creating a new model from
       * a given dataset.
       *
       * Response includes details of the enqueued job including job status and the name
       * of the fine-tuned models once complete.
       *
       * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization)
       *
       * @example
       * ```ts
       * const fineTuningJob = await client.fineTuning.jobs.create({
       *   model: 'gpt-4o-mini',
       *   training_file: 'file-abc123',
       * });
       * ```
       */
      create(body, options2) {
        return this._client.post("/fine_tuning/jobs", { body, ...options2 });
      }
      /**
       * Get info about a fine-tuning job.
       *
       * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization)
       *
       * @example
       * ```ts
       * const fineTuningJob = await client.fineTuning.jobs.retrieve(
       *   'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
       * );
       * ```
       */
      retrieve(fineTuningJobID, options2) {
        return this._client.get(path11`/fine_tuning/jobs/${fineTuningJobID}`, options2);
      }
      /**
       * List your organization's fine-tuning jobs
       *
       * @example
       * ```ts
       * // Automatically fetches more pages as needed.
       * for await (const fineTuningJob of client.fineTuning.jobs.list()) {
       *   // ...
       * }
       * ```
       */
      list(query = {}, options2) {
        return this._client.getAPIList("/fine_tuning/jobs", CursorPage, { query, ...options2 });
      }
      /**
       * Immediately cancel a fine-tune job.
       *
       * @example
       * ```ts
       * const fineTuningJob = await client.fineTuning.jobs.cancel(
       *   'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
       * );
       * ```
       */
      cancel(fineTuningJobID, options2) {
        return this._client.post(path11`/fine_tuning/jobs/${fineTuningJobID}/cancel`, options2);
      }
      /**
       * Get status updates for a fine-tuning job.
       *
       * @example
       * ```ts
       * // Automatically fetches more pages as needed.
       * for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents(
       *   'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
       * )) {
       *   // ...
       * }
       * ```
       */
      listEvents(fineTuningJobID, query = {}, options2) {
        return this._client.getAPIList(path11`/fine_tuning/jobs/${fineTuningJobID}/events`, CursorPage, { query, ...options2 });
      }
      /**
       * Pause a fine-tune job.
       *
       * @example
       * ```ts
       * const fineTuningJob = await client.fineTuning.jobs.pause(
       *   'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
       * );
       * ```
       */
      pause(fineTuningJobID, options2) {
        return this._client.post(path11`/fine_tuning/jobs/${fineTuningJobID}/pause`, options2);
      }
      /**
       * Resume a fine-tune job.
       *
       * @example
       * ```ts
       * const fineTuningJob = await client.fineTuning.jobs.resume(
       *   'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
       * );
       * ```
       */
      resume(fineTuningJobID, options2) {
        return this._client.post(path11`/fine_tuning/jobs/${fineTuningJobID}/resume`, options2);
      }
    };
    Jobs.Checkpoints = Checkpoints2;
  }
});

// node_modules/openai/resources/fine-tuning/fine-tuning.mjs
var FineTuning;
var init_fine_tuning = __esm({
  "node_modules/openai/resources/fine-tuning/fine-tuning.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_methods();
    init_methods();
    init_alpha();
    init_alpha();
    init_checkpoints();
    init_checkpoints();
    init_jobs();
    init_jobs();
    FineTuning = class extends APIResource {
      static {
        __name(this, "FineTuning");
      }
      constructor() {
        super(...arguments);
        this.methods = new Methods(this._client);
        this.jobs = new Jobs(this._client);
        this.checkpoints = new Checkpoints(this._client);
        this.alpha = new Alpha(this._client);
      }
    };
    FineTuning.Methods = Methods;
    FineTuning.Jobs = Jobs;
    FineTuning.Checkpoints = Checkpoints;
    FineTuning.Alpha = Alpha;
  }
});

// node_modules/openai/resources/graders/grader-models.mjs
var GraderModels;
var init_grader_models = __esm({
  "node_modules/openai/resources/graders/grader-models.mjs"() {
    init_esbuild_shims();
    init_resource2();
    GraderModels = class extends APIResource {
      static {
        __name(this, "GraderModels");
      }
    };
  }
});

// node_modules/openai/resources/graders/graders.mjs
var Graders2;
var init_graders2 = __esm({
  "node_modules/openai/resources/graders/graders.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_grader_models();
    init_grader_models();
    Graders2 = class extends APIResource {
      static {
        __name(this, "Graders");
      }
      constructor() {
        super(...arguments);
        this.graderModels = new GraderModels(this._client);
      }
    };
    Graders2.GraderModels = GraderModels;
  }
});

// node_modules/openai/resources/images.mjs
var Images;
var init_images = __esm({
  "node_modules/openai/resources/images.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_uploads();
    Images = class extends APIResource {
      static {
        __name(this, "Images");
      }
      /**
       * Creates a variation of a given image. This endpoint only supports `dall-e-2`.
       *
       * @example
       * ```ts
       * const imagesResponse = await client.images.createVariation({
       *   image: fs.createReadStream('otter.png'),
       * });
       * ```
       */
      createVariation(body, options2) {
        return this._client.post("/images/variations", multipartFormRequestOptions({ body, ...options2 }, this._client));
      }
      edit(body, options2) {
        return this._client.post("/images/edits", multipartFormRequestOptions({ body, ...options2, stream: body.stream ?? false }, this._client));
      }
      generate(body, options2) {
        return this._client.post("/images/generations", { body, ...options2, stream: body.stream ?? false });
      }
    };
  }
});

// node_modules/openai/resources/models.mjs
var Models2;
var init_models2 = __esm({
  "node_modules/openai/resources/models.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_pagination();
    init_path();
    Models2 = class extends APIResource {
      static {
        __name(this, "Models");
      }
      /**
       * Retrieves a model instance, providing basic information about the model such as
       * the owner and permissioning.
       */
      retrieve(model, options2) {
        return this._client.get(path11`/models/${model}`, options2);
      }
      /**
       * Lists the currently available models, and provides basic information about each
       * one such as the owner and availability.
       */
      list(options2) {
        return this._client.getAPIList("/models", Page, options2);
      }
      /**
       * Delete a fine-tuned model. You must have the Owner role in your organization to
       * delete a model.
       */
      delete(model, options2) {
        return this._client.delete(path11`/models/${model}`, options2);
      }
    };
  }
});

// node_modules/openai/resources/moderations.mjs
var Moderations;
var init_moderations = __esm({
  "node_modules/openai/resources/moderations.mjs"() {
    init_esbuild_shims();
    init_resource2();
    Moderations = class extends APIResource {
      static {
        __name(this, "Moderations");
      }
      /**
       * Classifies if text and/or image inputs are potentially harmful. Learn more in
       * the [moderation guide](https://platform.openai.com/docs/guides/moderation).
       */
      create(body, options2) {
        return this._client.post("/moderations", { body, ...options2 });
      }
    };
  }
});

// node_modules/openai/lib/ResponsesParser.mjs
function maybeParseResponse(response, params) {
  if (!params || !hasAutoParseableInput2(params)) {
    return {
      ...response,
      output_parsed: null,
      output: response.output.map((item) => {
        if (item.type === "function_call") {
          return {
            ...item,
            parsed_arguments: null
          };
        }
        if (item.type === "message") {
          return {
            ...item,
            content: item.content.map((content) => ({
              ...content,
              parsed: null
            }))
          };
        } else {
          return item;
        }
      })
    };
  }
  return parseResponse(response, params);
}
function parseResponse(response, params) {
  const output = response.output.map((item) => {
    if (item.type === "function_call") {
      return {
        ...item,
        parsed_arguments: parseToolCall2(params, item)
      };
    }
    if (item.type === "message") {
      const content = item.content.map((content2) => {
        if (content2.type === "output_text") {
          return {
            ...content2,
            parsed: parseTextFormat(params, content2.text)
          };
        }
        return content2;
      });
      return {
        ...item,
        content
      };
    }
    return item;
  });
  const parsed = Object.assign({}, response, { output });
  if (!Object.getOwnPropertyDescriptor(response, "output_text")) {
    addOutputText(parsed);
  }
  Object.defineProperty(parsed, "output_parsed", {
    enumerable: true,
    get() {
      for (const output2 of parsed.output) {
        if (output2.type !== "message") {
          continue;
        }
        for (const content of output2.content) {
          if (content.type === "output_text" && content.parsed !== null) {
            return content.parsed;
          }
        }
      }
      return null;
    }
  });
  return parsed;
}
function parseTextFormat(params, content) {
  if (params.text?.format?.type !== "json_schema") {
    return null;
  }
  if ("$parseRaw" in params.text?.format) {
    const text_format = params.text?.format;
    return text_format.$parseRaw(content);
  }
  return JSON.parse(content);
}
function hasAutoParseableInput2(params) {
  if (isAutoParsableResponseFormat(params.text?.format)) {
    return true;
  }
  return false;
}
function isAutoParsableTool2(tool) {
  return tool?.["$brand"] === "auto-parseable-tool";
}
function getInputToolByName(input_tools, name3) {
  return input_tools.find((tool) => tool.type === "function" && tool.name === name3);
}
function parseToolCall2(params, toolCall) {
  const inputTool = getInputToolByName(params.tools ?? [], toolCall.name);
  return {
    ...toolCall,
    ...toolCall,
    parsed_arguments: isAutoParsableTool2(inputTool) ? inputTool.$parseRaw(toolCall.arguments) : inputTool?.strict ? JSON.parse(toolCall.arguments) : null
  };
}
function addOutputText(rsp) {
  const texts = [];
  for (const output of rsp.output) {
    if (output.type !== "message") {
      continue;
    }
    for (const content of output.content) {
      if (content.type === "output_text") {
        texts.push(content.text);
      }
    }
  }
  rsp.output_text = texts.join("");
}
var init_ResponsesParser = __esm({
  "node_modules/openai/lib/ResponsesParser.mjs"() {
    init_esbuild_shims();
    init_error2();
    init_parser();
    __name(maybeParseResponse, "maybeParseResponse");
    __name(parseResponse, "parseResponse");
    __name(parseTextFormat, "parseTextFormat");
    __name(hasAutoParseableInput2, "hasAutoParseableInput");
    __name(isAutoParsableTool2, "isAutoParsableTool");
    __name(getInputToolByName, "getInputToolByName");
    __name(parseToolCall2, "parseToolCall");
    __name(addOutputText, "addOutputText");
  }
});

// node_modules/openai/lib/responses/ResponseStream.mjs
function finalizeResponse(snapshot, params) {
  return maybeParseResponse(snapshot, params);
}
var _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, _ResponseStream_accumulateResponse, ResponseStream;
var init_ResponseStream = __esm({
  "node_modules/openai/lib/responses/ResponseStream.mjs"() {
    init_esbuild_shims();
    init_tslib();
    init_error2();
    init_EventStream();
    init_ResponsesParser();
    ResponseStream = class _ResponseStream extends EventStream {
      static {
        __name(this, "ResponseStream");
      }
      constructor(params) {
        super();
        _ResponseStream_instances.add(this);
        _ResponseStream_params.set(this, void 0);
        _ResponseStream_currentResponseSnapshot.set(this, void 0);
        _ResponseStream_finalResponse.set(this, void 0);
        __classPrivateFieldSet(this, _ResponseStream_params, params, "f");
      }
      static createResponse(client, params, options2) {
        const runner = new _ResponseStream(params);
        runner._run(() => runner._createOrRetrieveResponse(client, params, {
          ...options2,
          headers: { ...options2?.headers, "X-Stainless-Helper-Method": "stream" }
        }));
        return runner;
      }
      async _createOrRetrieveResponse(client, params, options2) {
        const signal = options2?.signal;
        if (signal) {
          if (signal.aborted)
            this.controller.abort();
          signal.addEventListener("abort", () => this.controller.abort());
        }
        __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this);
        let stream2;
        let starting_after = null;
        if ("response_id" in params) {
          stream2 = await client.responses.retrieve(params.response_id, { stream: true }, { ...options2, signal: this.controller.signal, stream: true });
          starting_after = params.starting_after ?? null;
        } else {
          stream2 = await client.responses.create({ ...params, stream: true }, { ...options2, signal: this.controller.signal });
        }
        this._connected();
        for await (const event of stream2) {
          __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event, starting_after);
        }
        if (stream2.controller.signal?.aborted) {
          throw new APIUserAbortError();
        }
        return __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this);
      }
      [(_ResponseStream_params = /* @__PURE__ */ new WeakMap(), _ResponseStream_currentResponseSnapshot = /* @__PURE__ */ new WeakMap(), _ResponseStream_finalResponse = /* @__PURE__ */ new WeakMap(), _ResponseStream_instances = /* @__PURE__ */ new WeakSet(), _ResponseStream_beginRequest = /* @__PURE__ */ __name(function _ResponseStream_beginRequest2() {
        if (this.ended)
          return;
        __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, void 0, "f");
      }, "_ResponseStream_beginRequest"), _ResponseStream_addEvent = /* @__PURE__ */ __name(function _ResponseStream_addEvent2(event, starting_after) {
        if (this.ended)
          return;
        const maybeEmit = /* @__PURE__ */ __name((name3, event2) => {
          if (starting_after == null || event2.sequence_number > starting_after) {
            this._emit(name3, event2);
          }
        }, "maybeEmit");
        const response = __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_accumulateResponse).call(this, event);
        maybeEmit("event", event);
        switch (event.type) {
          case "response.output_text.delta": {
            const output = response.output[event.output_index];
            if (!output) {
              throw new OpenAIError(`missing output at index ${event.output_index}`);
            }
            if (output.type === "message") {
              const content = output.content[event.content_index];
              if (!content) {
                throw new OpenAIError(`missing content at index ${event.content_index}`);
              }
              if (content.type !== "output_text") {
                throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
              }
              maybeEmit("response.output_text.delta", {
                ...event,
                snapshot: content.text
              });
            }
            break;
          }
          case "response.function_call_arguments.delta": {
            const output = response.output[event.output_index];
            if (!output) {
              throw new OpenAIError(`missing output at index ${event.output_index}`);
            }
            if (output.type === "function_call") {
              maybeEmit("response.function_call_arguments.delta", {
                ...event,
                snapshot: output.arguments
              });
            }
            break;
          }
          default:
            maybeEmit(event.type, event);
            break;
        }
      }, "_ResponseStream_addEvent"), _ResponseStream_endRequest = /* @__PURE__ */ __name(function _ResponseStream_endRequest2() {
        if (this.ended) {
          throw new OpenAIError(`stream has ended, this shouldn't happen`);
        }
        const snapshot = __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f");
        if (!snapshot) {
          throw new OpenAIError(`request ended without sending any events`);
        }
        __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, void 0, "f");
        const parsedResponse = finalizeResponse(snapshot, __classPrivateFieldGet(this, _ResponseStream_params, "f"));
        __classPrivateFieldSet(this, _ResponseStream_finalResponse, parsedResponse, "f");
        return parsedResponse;
      }, "_ResponseStream_endRequest"), _ResponseStream_accumulateResponse = /* @__PURE__ */ __name(function _ResponseStream_accumulateResponse2(event) {
        let snapshot = __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f");
        if (!snapshot) {
          if (event.type !== "response.created") {
            throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`);
          }
          snapshot = __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f");
          return snapshot;
        }
        switch (event.type) {
          case "response.output_item.added": {
            snapshot.output.push(event.item);
            break;
          }
          case "response.content_part.added": {
            const output = snapshot.output[event.output_index];
            if (!output) {
              throw new OpenAIError(`missing output at index ${event.output_index}`);
            }
            if (output.type === "message") {
              output.content.push(event.part);
            }
            break;
          }
          case "response.output_text.delta": {
            const output = snapshot.output[event.output_index];
            if (!output) {
              throw new OpenAIError(`missing output at index ${event.output_index}`);
            }
            if (output.type === "message") {
              const content = output.content[event.content_index];
              if (!content) {
                throw new OpenAIError(`missing content at index ${event.content_index}`);
              }
              if (content.type !== "output_text") {
                throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
              }
              content.text += event.delta;
            }
            break;
          }
          case "response.function_call_arguments.delta": {
            const output = snapshot.output[event.output_index];
            if (!output) {
              throw new OpenAIError(`missing output at index ${event.output_index}`);
            }
            if (output.type === "function_call") {
              output.arguments += event.delta;
            }
            break;
          }
          case "response.completed": {
            __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f");
            break;
          }
        }
        return snapshot;
      }, "_ResponseStream_accumulateResponse"), Symbol.asyncIterator)]() {
        const pushQueue = [];
        const readQueue = [];
        let done = false;
        this.on("event", (event) => {
          const reader = readQueue.shift();
          if (reader) {
            reader.resolve(event);
          } else {
            pushQueue.push(event);
          }
        });
        this.on("end", () => {
          done = true;
          for (const reader of readQueue) {
            reader.resolve(void 0);
          }
          readQueue.length = 0;
        });
        this.on("abort", (err) => {
          done = true;
          for (const reader of readQueue) {
            reader.reject(err);
          }
          readQueue.length = 0;
        });
        this.on("error", (err) => {
          done = true;
          for (const reader of readQueue) {
            reader.reject(err);
          }
          readQueue.length = 0;
        });
        return {
          next: /* @__PURE__ */ __name(async () => {
            if (!pushQueue.length) {
              if (done) {
                return { value: void 0, done: true };
              }
              return new Promise((resolve24, reject) => readQueue.push({ resolve: resolve24, reject })).then((event2) => event2 ? { value: event2, done: false } : { value: void 0, done: true });
            }
            const event = pushQueue.shift();
            return { value: event, done: false };
          }, "next"),
          return: /* @__PURE__ */ __name(async () => {
            this.abort();
            return { value: void 0, done: true };
          }, "return")
        };
      }
      /**
       * @returns a promise that resolves with the final Response, or rejects
       * if an error occurred or the stream ended prematurely without producing a REsponse.
       */
      async finalResponse() {
        await this.done();
        const response = __classPrivateFieldGet(this, _ResponseStream_finalResponse, "f");
        if (!response)
          throw new OpenAIError("stream ended without producing a ChatCompletion");
        return response;
      }
    };
    __name(finalizeResponse, "finalizeResponse");
  }
});

// node_modules/openai/resources/responses/input-items.mjs
var InputItems;
var init_input_items = __esm({
  "node_modules/openai/resources/responses/input-items.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_pagination();
    init_path();
    InputItems = class extends APIResource {
      static {
        __name(this, "InputItems");
      }
      /**
       * Returns a list of input items for a given response.
       *
       * @example
       * ```ts
       * // Automatically fetches more pages as needed.
       * for await (const responseItem of client.responses.inputItems.list(
       *   'response_id',
       * )) {
       *   // ...
       * }
       * ```
       */
      list(responseID, query = {}, options2) {
        return this._client.getAPIList(path11`/responses/${responseID}/input_items`, CursorPage, { query, ...options2 });
      }
    };
  }
});

// node_modules/openai/resources/responses/responses.mjs
var Responses;
var init_responses = __esm({
  "node_modules/openai/resources/responses/responses.mjs"() {
    init_esbuild_shims();
    init_ResponsesParser();
    init_ResponseStream();
    init_resource2();
    init_input_items();
    init_input_items();
    init_headers();
    init_path();
    Responses = class extends APIResource {
      static {
        __name(this, "Responses");
      }
      constructor() {
        super(...arguments);
        this.inputItems = new InputItems(this._client);
      }
      create(body, options2) {
        return this._client.post("/responses", { body, ...options2, stream: body.stream ?? false })._thenUnwrap((rsp) => {
          if ("object" in rsp && rsp.object === "response") {
            addOutputText(rsp);
          }
          return rsp;
        });
      }
      retrieve(responseID, query = {}, options2) {
        return this._client.get(path11`/responses/${responseID}`, {
          query,
          ...options2,
          stream: query?.stream ?? false
        })._thenUnwrap((rsp) => {
          if ("object" in rsp && rsp.object === "response") {
            addOutputText(rsp);
          }
          return rsp;
        });
      }
      /**
       * Deletes a model response with the given ID.
       *
       * @example
       * ```ts
       * await client.responses.delete(
       *   'resp_677efb5139a88190b512bc3fef8e535d',
       * );
       * ```
       */
      delete(responseID, options2) {
        return this._client.delete(path11`/responses/${responseID}`, {
          ...options2,
          headers: buildHeaders([{ Accept: "*/*" }, options2?.headers])
        });
      }
      parse(body, options2) {
        return this._client.responses.create(body, options2)._thenUnwrap((response) => parseResponse(response, body));
      }
      /**
       * Creates a model response stream
       */
      stream(body, options2) {
        return ResponseStream.createResponse(this._client, body, options2);
      }
      /**
       * Cancels a model response with the given ID. Only responses created with the
       * `background` parameter set to `true` can be cancelled.
       * [Learn more](https://platform.openai.com/docs/guides/background).
       *
       * @example
       * ```ts
       * const response = await client.responses.cancel(
       *   'resp_677efb5139a88190b512bc3fef8e535d',
       * );
       * ```
       */
      cancel(responseID, options2) {
        return this._client.post(path11`/responses/${responseID}/cancel`, options2);
      }
    };
    Responses.InputItems = InputItems;
  }
});

// node_modules/openai/resources/uploads/parts.mjs
var Parts;
var init_parts = __esm({
  "node_modules/openai/resources/uploads/parts.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_uploads();
    init_path();
    Parts = class extends APIResource {
      static {
        __name(this, "Parts");
      }
      /**
       * Adds a
       * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an
       * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object.
       * A Part represents a chunk of bytes from the file you are trying to upload.
       *
       * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload
       * maximum of 8 GB.
       *
       * It is possible to add multiple Parts in parallel. You can decide the intended
       * order of the Parts when you
       * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete).
       */
      create(uploadID, body, options2) {
        return this._client.post(path11`/uploads/${uploadID}/parts`, multipartFormRequestOptions({ body, ...options2 }, this._client));
      }
    };
  }
});

// node_modules/openai/resources/uploads/uploads.mjs
var Uploads;
var init_uploads3 = __esm({
  "node_modules/openai/resources/uploads/uploads.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_parts();
    init_parts();
    init_path();
    Uploads = class extends APIResource {
      static {
        __name(this, "Uploads");
      }
      constructor() {
        super(...arguments);
        this.parts = new Parts(this._client);
      }
      /**
       * Creates an intermediate
       * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object
       * that you can add
       * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to.
       * Currently, an Upload can accept at most 8 GB in total and expires after an hour
       * after you create it.
       *
       * Once you complete the Upload, we will create a
       * [File](https://platform.openai.com/docs/api-reference/files/object) object that
       * contains all the parts you uploaded. This File is usable in the rest of our
       * platform as a regular File object.
       *
       * For certain `purpose` values, the correct `mime_type` must be specified. Please
       * refer to documentation for the
       * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files).
       *
       * For guidance on the proper filename extensions for each purpose, please follow
       * the documentation on
       * [creating a File](https://platform.openai.com/docs/api-reference/files/create).
       */
      create(body, options2) {
        return this._client.post("/uploads", { body, ...options2 });
      }
      /**
       * Cancels the Upload. No Parts may be added after an Upload is cancelled.
       */
      cancel(uploadID, options2) {
        return this._client.post(path11`/uploads/${uploadID}/cancel`, options2);
      }
      /**
       * Completes the
       * [Upload](https://platform.openai.com/docs/api-reference/uploads/object).
       *
       * Within the returned Upload object, there is a nested
       * [File](https://platform.openai.com/docs/api-reference/files/object) object that
       * is ready to use in the rest of the platform.
       *
       * You can specify the order of the Parts by passing in an ordered list of the Part
       * IDs.
       *
       * The number of bytes uploaded upon completion must match the number of bytes
       * initially specified when creating the Upload object. No Parts may be added after
       * an Upload is completed.
       */
      complete(uploadID, body, options2) {
        return this._client.post(path11`/uploads/${uploadID}/complete`, { body, ...options2 });
      }
    };
    Uploads.Parts = Parts;
  }
});

// node_modules/openai/lib/Util.mjs
var allSettledWithThrow;
var init_Util = __esm({
  "node_modules/openai/lib/Util.mjs"() {
    init_esbuild_shims();
    allSettledWithThrow = /* @__PURE__ */ __name(async (promises6) => {
      const results = await Promise.allSettled(promises6);
      const rejected = results.filter((result) => result.status === "rejected");
      if (rejected.length) {
        for (const result of rejected) {
          console.error(result.reason);
        }
        throw new Error(`${rejected.length} promise(s) failed - see the above errors`);
      }
      const values = [];
      for (const result of results) {
        if (result.status === "fulfilled") {
          values.push(result.value);
        }
      }
      return values;
    }, "allSettledWithThrow");
  }
});

// node_modules/openai/resources/vector-stores/file-batches.mjs
var FileBatches;
var init_file_batches = __esm({
  "node_modules/openai/resources/vector-stores/file-batches.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_pagination();
    init_headers();
    init_sleep();
    init_Util();
    init_path();
    FileBatches = class extends APIResource {
      static {
        __name(this, "FileBatches");
      }
      /**
       * Create a vector store file batch.
       */
      create(vectorStoreID, body, options2) {
        return this._client.post(path11`/vector_stores/${vectorStoreID}/file_batches`, {
          body,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Retrieves a vector store file batch.
       */
      retrieve(batchID, params, options2) {
        const { vector_store_id } = params;
        return this._client.get(path11`/vector_stores/${vector_store_id}/file_batches/${batchID}`, {
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Cancel a vector store file batch. This attempts to cancel the processing of
       * files in this batch as soon as possible.
       */
      cancel(batchID, params, options2) {
        const { vector_store_id } = params;
        return this._client.post(path11`/vector_stores/${vector_store_id}/file_batches/${batchID}/cancel`, {
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Create a vector store batch and poll until all files have been processed.
       */
      async createAndPoll(vectorStoreId, body, options2) {
        const batch = await this.create(vectorStoreId, body);
        return await this.poll(vectorStoreId, batch.id, options2);
      }
      /**
       * Returns a list of vector store files in a batch.
       */
      listFiles(batchID, params, options2) {
        const { vector_store_id, ...query } = params;
        return this._client.getAPIList(path11`/vector_stores/${vector_store_id}/file_batches/${batchID}/files`, CursorPage, { query, ...options2, headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]) });
      }
      /**
       * Wait for the given file batch to be processed.
       *
       * Note: this will return even if one of the files failed to process, you need to
       * check batch.file_counts.failed_count to handle this case.
       */
      async poll(vectorStoreID, batchID, options2) {
        const headers = buildHeaders([
          options2?.headers,
          {
            "X-Stainless-Poll-Helper": "true",
            "X-Stainless-Custom-Poll-Interval": options2?.pollIntervalMs?.toString() ?? void 0
          }
        ]);
        while (true) {
          const { data: batch, response } = await this.retrieve(batchID, { vector_store_id: vectorStoreID }, {
            ...options2,
            headers
          }).withResponse();
          switch (batch.status) {
            case "in_progress":
              let sleepInterval = 5e3;
              if (options2?.pollIntervalMs) {
                sleepInterval = options2.pollIntervalMs;
              } else {
                const headerInterval = response.headers.get("openai-poll-after-ms");
                if (headerInterval) {
                  const headerIntervalMs = parseInt(headerInterval);
                  if (!isNaN(headerIntervalMs)) {
                    sleepInterval = headerIntervalMs;
                  }
                }
              }
              await sleep2(sleepInterval);
              break;
            case "failed":
            case "cancelled":
            case "completed":
              return batch;
          }
        }
      }
      /**
       * Uploads the given files concurrently and then creates a vector store file batch.
       *
       * The concurrency limit is configurable using the `maxConcurrency` parameter.
       */
      async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options2) {
        if (files == null || files.length == 0) {
          throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`);
        }
        const configuredConcurrency = options2?.maxConcurrency ?? 5;
        const concurrencyLimit = Math.min(configuredConcurrency, files.length);
        const client = this._client;
        const fileIterator = files.values();
        const allFileIds = [...fileIds];
        async function processFiles(iterator) {
          for (let item of iterator) {
            const fileObj = await client.files.create({ file: item, purpose: "assistants" }, options2);
            allFileIds.push(fileObj.id);
          }
        }
        __name(processFiles, "processFiles");
        const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles);
        await allSettledWithThrow(workers);
        return await this.createAndPoll(vectorStoreId, {
          file_ids: allFileIds
        });
      }
    };
  }
});

// node_modules/openai/resources/vector-stores/files.mjs
var Files4;
var init_files3 = __esm({
  "node_modules/openai/resources/vector-stores/files.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_pagination();
    init_headers();
    init_utils5();
    init_path();
    Files4 = class extends APIResource {
      static {
        __name(this, "Files");
      }
      /**
       * Create a vector store file by attaching a
       * [File](https://platform.openai.com/docs/api-reference/files) to a
       * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object).
       */
      create(vectorStoreID, body, options2) {
        return this._client.post(path11`/vector_stores/${vectorStoreID}/files`, {
          body,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Retrieves a vector store file.
       */
      retrieve(fileID, params, options2) {
        const { vector_store_id } = params;
        return this._client.get(path11`/vector_stores/${vector_store_id}/files/${fileID}`, {
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Update attributes on a vector store file.
       */
      update(fileID, params, options2) {
        const { vector_store_id, ...body } = params;
        return this._client.post(path11`/vector_stores/${vector_store_id}/files/${fileID}`, {
          body,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Returns a list of vector store files.
       */
      list(vectorStoreID, query = {}, options2) {
        return this._client.getAPIList(path11`/vector_stores/${vectorStoreID}/files`, CursorPage, {
          query,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Delete a vector store file. This will remove the file from the vector store but
       * the file itself will not be deleted. To delete the file, use the
       * [delete file](https://platform.openai.com/docs/api-reference/files/delete)
       * endpoint.
       */
      delete(fileID, params, options2) {
        const { vector_store_id } = params;
        return this._client.delete(path11`/vector_stores/${vector_store_id}/files/${fileID}`, {
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Attach a file to the given vector store and wait for it to be processed.
       */
      async createAndPoll(vectorStoreId, body, options2) {
        const file = await this.create(vectorStoreId, body, options2);
        return await this.poll(vectorStoreId, file.id, options2);
      }
      /**
       * Wait for the vector store file to finish processing.
       *
       * Note: this will return even if the file failed to process, you need to check
       * file.last_error and file.status to handle these cases
       */
      async poll(vectorStoreID, fileID, options2) {
        const headers = buildHeaders([
          options2?.headers,
          {
            "X-Stainless-Poll-Helper": "true",
            "X-Stainless-Custom-Poll-Interval": options2?.pollIntervalMs?.toString() ?? void 0
          }
        ]);
        while (true) {
          const fileResponse = await this.retrieve(fileID, {
            vector_store_id: vectorStoreID
          }, { ...options2, headers }).withResponse();
          const file = fileResponse.data;
          switch (file.status) {
            case "in_progress":
              let sleepInterval = 5e3;
              if (options2?.pollIntervalMs) {
                sleepInterval = options2.pollIntervalMs;
              } else {
                const headerInterval = fileResponse.response.headers.get("openai-poll-after-ms");
                if (headerInterval) {
                  const headerIntervalMs = parseInt(headerInterval);
                  if (!isNaN(headerIntervalMs)) {
                    sleepInterval = headerIntervalMs;
                  }
                }
              }
              await sleep2(sleepInterval);
              break;
            case "failed":
            case "completed":
              return file;
          }
        }
      }
      /**
       * Upload a file to the `files` API and then attach it to the given vector store.
       *
       * Note the file will be asynchronously processed (you can use the alternative
       * polling helper method to wait for processing to complete).
       */
      async upload(vectorStoreId, file, options2) {
        const fileInfo = await this._client.files.create({ file, purpose: "assistants" }, options2);
        return this.create(vectorStoreId, { file_id: fileInfo.id }, options2);
      }
      /**
       * Add a file to a vector store and poll until processing is complete.
       */
      async uploadAndPoll(vectorStoreId, file, options2) {
        const fileInfo = await this.upload(vectorStoreId, file, options2);
        return await this.poll(vectorStoreId, fileInfo.id, options2);
      }
      /**
       * Retrieve the parsed contents of a vector store file.
       */
      content(fileID, params, options2) {
        const { vector_store_id } = params;
        return this._client.getAPIList(path11`/vector_stores/${vector_store_id}/files/${fileID}/content`, Page, { ...options2, headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]) });
      }
    };
  }
});

// node_modules/openai/resources/vector-stores/vector-stores.mjs
var VectorStores;
var init_vector_stores = __esm({
  "node_modules/openai/resources/vector-stores/vector-stores.mjs"() {
    init_esbuild_shims();
    init_resource2();
    init_file_batches();
    init_file_batches();
    init_files3();
    init_files3();
    init_pagination();
    init_headers();
    init_path();
    VectorStores = class extends APIResource {
      static {
        __name(this, "VectorStores");
      }
      constructor() {
        super(...arguments);
        this.files = new Files4(this._client);
        this.fileBatches = new FileBatches(this._client);
      }
      /**
       * Create a vector store.
       */
      create(body, options2) {
        return this._client.post("/vector_stores", {
          body,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Retrieves a vector store.
       */
      retrieve(vectorStoreID, options2) {
        return this._client.get(path11`/vector_stores/${vectorStoreID}`, {
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Modifies a vector store.
       */
      update(vectorStoreID, body, options2) {
        return this._client.post(path11`/vector_stores/${vectorStoreID}`, {
          body,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Returns a list of vector stores.
       */
      list(query = {}, options2) {
        return this._client.getAPIList("/vector_stores", CursorPage, {
          query,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Delete a vector store.
       */
      delete(vectorStoreID, options2) {
        return this._client.delete(path11`/vector_stores/${vectorStoreID}`, {
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Search a vector store for relevant chunks based on a query and file attributes
       * filter.
       */
      search(vectorStoreID, body, options2) {
        return this._client.getAPIList(path11`/vector_stores/${vectorStoreID}/search`, Page, {
          body,
          method: "post",
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
    };
    VectorStores.Files = Files4;
    VectorStores.FileBatches = FileBatches;
  }
});

// node_modules/openai/resources/webhooks.mjs
var _Webhooks_instances, _Webhooks_validateSecret, _Webhooks_getRequiredHeader, Webhooks;
var init_webhooks = __esm({
  "node_modules/openai/resources/webhooks.mjs"() {
    init_esbuild_shims();
    init_tslib();
    init_error2();
    init_resource2();
    init_headers();
    Webhooks = class extends APIResource {
      static {
        __name(this, "Webhooks");
      }
      constructor() {
        super(...arguments);
        _Webhooks_instances.add(this);
      }
      /**
       * Validates that the given payload was sent by OpenAI and parses the payload.
       */
      async unwrap(payload, headers, secret = this._client.webhookSecret, tolerance = 300) {
        await this.verifySignature(payload, headers, secret, tolerance);
        return JSON.parse(payload);
      }
      /**
       * Validates whether or not the webhook payload was sent by OpenAI.
       *
       * An error will be raised if the webhook payload was not sent by OpenAI.
       *
       * @param payload - The webhook payload
       * @param headers - The webhook headers
       * @param secret - The webhook secret (optional, will use client secret if not provided)
       * @param tolerance - Maximum age of the webhook in seconds (default: 300 = 5 minutes)
       */
      async verifySignature(payload, headers, secret = this._client.webhookSecret, tolerance = 300) {
        if (typeof crypto === "undefined" || typeof crypto.subtle.importKey !== "function" || typeof crypto.subtle.verify !== "function") {
          throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");
        }
        __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_validateSecret).call(this, secret);
        const headersObj = buildHeaders([headers]).values;
        const signatureHeader = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-signature");
        const timestamp = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-timestamp");
        const webhookId = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-id");
        const timestampSeconds = parseInt(timestamp, 10);
        if (isNaN(timestampSeconds)) {
          throw new InvalidWebhookSignatureError("Invalid webhook timestamp format");
        }
        const nowSeconds = Math.floor(Date.now() / 1e3);
        if (nowSeconds - timestampSeconds > tolerance) {
          throw new InvalidWebhookSignatureError("Webhook timestamp is too old");
        }
        if (timestampSeconds > nowSeconds + tolerance) {
          throw new InvalidWebhookSignatureError("Webhook timestamp is too new");
        }
        const signatures = signatureHeader.split(" ").map((part) => part.startsWith("v1,") ? part.substring(3) : part);
        const decodedSecret = secret.startsWith("whsec_") ? Buffer.from(secret.replace("whsec_", ""), "base64") : Buffer.from(secret, "utf-8");
        const signedPayload = webhookId ? `${webhookId}.${timestamp}.${payload}` : `${timestamp}.${payload}`;
        const key = await crypto.subtle.importKey("raw", decodedSecret, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
        for (const signature of signatures) {
          try {
            const signatureBytes = Buffer.from(signature, "base64");
            const isValid2 = await crypto.subtle.verify("HMAC", key, signatureBytes, new TextEncoder().encode(signedPayload));
            if (isValid2) {
              return;
            }
          } catch {
            continue;
          }
        }
        throw new InvalidWebhookSignatureError("The given webhook signature does not match the expected signature");
      }
    };
    _Webhooks_instances = /* @__PURE__ */ new WeakSet(), _Webhooks_validateSecret = /* @__PURE__ */ __name(function _Webhooks_validateSecret2(secret) {
      if (typeof secret !== "string" || secret.length === 0) {
        throw new Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`);
      }
    }, "_Webhooks_validateSecret"), _Webhooks_getRequiredHeader = /* @__PURE__ */ __name(function _Webhooks_getRequiredHeader2(headers, name3) {
      if (!headers) {
        throw new Error(`Headers are required`);
      }
      const value = headers.get(name3);
      if (value === null || value === void 0) {
        throw new Error(`Missing required header: ${name3}`);
      }
      return value;
    }, "_Webhooks_getRequiredHeader");
  }
});

// node_modules/openai/resources/index.mjs
var init_resources = __esm({
  "node_modules/openai/resources/index.mjs"() {
    init_esbuild_shims();
    init_chat2();
    init_shared();
    init_audio();
    init_batches();
    init_beta();
    init_completions3();
    init_containers();
    init_embeddings();
    init_evals();
    init_files2();
    init_fine_tuning();
    init_graders2();
    init_images();
    init_models2();
    init_moderations();
    init_responses();
    init_uploads3();
    init_vector_stores();
    init_webhooks();
  }
});

// node_modules/openai/client.mjs
var _OpenAI_instances, _a2, _OpenAI_encoder, _OpenAI_baseURLOverridden, OpenAI;
var init_client = __esm({
  "node_modules/openai/client.mjs"() {
    init_esbuild_shims();
    init_tslib();
    init_uuid();
    init_values();
    init_sleep();
    init_errors2();
    init_detect_platform();
    init_shims();
    init_request_options();
    init_qs();
    init_version3();
    init_error();
    init_pagination();
    init_uploads2();
    init_resources();
    init_api_promise();
    init_batches();
    init_completions3();
    init_embeddings();
    init_files2();
    init_images();
    init_models2();
    init_moderations();
    init_webhooks();
    init_audio();
    init_beta();
    init_chat();
    init_containers();
    init_evals();
    init_fine_tuning();
    init_graders2();
    init_responses();
    init_uploads3();
    init_vector_stores();
    init_detect_platform();
    init_headers();
    init_env();
    init_log();
    init_values();
    OpenAI = class {
      static {
        __name(this, "OpenAI");
      }
      /**
       * API Client for interfacing with the OpenAI API.
       *
       * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined]
       * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]
       * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null]
       * @param {string | null | undefined} [opts.webhookSecret=process.env['OPENAI_WEBHOOK_SECRET'] ?? null]
       * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API.
       * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
       * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
       * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
       * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
       * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
       * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
       * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
       */
      constructor({ baseURL = readEnv("OPENAI_BASE_URL"), apiKey = readEnv("OPENAI_API_KEY"), organization = readEnv("OPENAI_ORG_ID") ?? null, project = readEnv("OPENAI_PROJECT_ID") ?? null, webhookSecret = readEnv("OPENAI_WEBHOOK_SECRET") ?? null, ...opts } = {}) {
        _OpenAI_instances.add(this);
        _OpenAI_encoder.set(this, void 0);
        this.completions = new Completions2(this);
        this.chat = new Chat2(this);
        this.embeddings = new Embeddings(this);
        this.files = new Files3(this);
        this.images = new Images(this);
        this.audio = new Audio(this);
        this.moderations = new Moderations(this);
        this.models = new Models2(this);
        this.fineTuning = new FineTuning(this);
        this.graders = new Graders2(this);
        this.vectorStores = new VectorStores(this);
        this.webhooks = new Webhooks(this);
        this.beta = new Beta(this);
        this.batches = new Batches2(this);
        this.uploads = new Uploads(this);
        this.responses = new Responses(this);
        this.evals = new Evals(this);
        this.containers = new Containers(this);
        if (apiKey === void 0) {
          throw new OpenAIError("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");
        }
        const options2 = {
          apiKey,
          organization,
          project,
          webhookSecret,
          ...opts,
          baseURL: baseURL || `https://api.openai.com/v1`
        };
        if (!options2.dangerouslyAllowBrowser && isRunningInBrowser()) {
          throw new OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");
        }
        this.baseURL = options2.baseURL;
        this.timeout = options2.timeout ?? _a2.DEFAULT_TIMEOUT;
        this.logger = options2.logger ?? console;
        const defaultLogLevel = "warn";
        this.logLevel = defaultLogLevel;
        this.logLevel = parseLogLevel(options2.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("OPENAI_LOG"), "process.env['OPENAI_LOG']", this) ?? defaultLogLevel;
        this.fetchOptions = options2.fetchOptions;
        this.maxRetries = options2.maxRetries ?? 2;
        this.fetch = options2.fetch ?? getDefaultFetch();
        __classPrivateFieldSet(this, _OpenAI_encoder, FallbackEncoder, "f");
        this._options = options2;
        this.apiKey = apiKey;
        this.organization = organization;
        this.project = project;
        this.webhookSecret = webhookSecret;
      }
      /**
       * Create a new client instance re-using the same options given to the current client with optional overriding.
       */
      withOptions(options2) {
        const client = new this.constructor({
          ...this._options,
          baseURL: this.baseURL,
          maxRetries: this.maxRetries,
          timeout: this.timeout,
          logger: this.logger,
          logLevel: this.logLevel,
          fetch: this.fetch,
          fetchOptions: this.fetchOptions,
          apiKey: this.apiKey,
          organization: this.organization,
          project: this.project,
          webhookSecret: this.webhookSecret,
          ...options2
        });
        return client;
      }
      defaultQuery() {
        return this._options.defaultQuery;
      }
      validateHeaders({ values, nulls }) {
        return;
      }
      async authHeaders(opts) {
        return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]);
      }
      stringifyQuery(query) {
        return stringify2(query, { arrayFormat: "brackets" });
      }
      getUserAgent() {
        return `${this.constructor.name}/JS ${VERSION2}`;
      }
      defaultIdempotencyKey() {
        return `stainless-node-retry-${uuid4()}`;
      }
      makeStatusError(status, error, message, headers) {
        return APIError.generate(status, error, message, headers);
      }
      buildURL(path108, query, defaultBaseURL) {
        const baseURL = !__classPrivateFieldGet(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL;
        const url2 = isAbsoluteURL(path108) ? new URL(path108) : new URL(baseURL + (baseURL.endsWith("/") && path108.startsWith("/") ? path108.slice(1) : path108));
        const defaultQuery = this.defaultQuery();
        if (!isEmptyObj(defaultQuery)) {
          query = { ...defaultQuery, ...query };
        }
        if (typeof query === "object" && query && !Array.isArray(query)) {
          url2.search = this.stringifyQuery(query);
        }
        return url2.toString();
      }
      /**
       * Used as a callback for mutating the given `FinalRequestOptions` object.
       */
      async prepareOptions(options2) {
      }
      /**
       * Used as a callback for mutating the given `RequestInit` object.
       *
       * This is useful for cases where you want to add certain headers based off of
       * the request properties, e.g. `method` or `url`.
       */
      async prepareRequest(request4, { url: url2, options: options2 }) {
      }
      get(path108, opts) {
        return this.methodRequest("get", path108, opts);
      }
      post(path108, opts) {
        return this.methodRequest("post", path108, opts);
      }
      patch(path108, opts) {
        return this.methodRequest("patch", path108, opts);
      }
      put(path108, opts) {
        return this.methodRequest("put", path108, opts);
      }
      delete(path108, opts) {
        return this.methodRequest("delete", path108, opts);
      }
      methodRequest(method, path108, opts) {
        return this.request(Promise.resolve(opts).then((opts2) => {
          return { method, path: path108, ...opts2 };
        }));
      }
      request(options2, remainingRetries = null) {
        return new APIPromise(this, this.makeRequest(options2, remainingRetries, void 0));
      }
      async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
        const options2 = await optionsInput;
        const maxRetries = options2.maxRetries ?? this.maxRetries;
        if (retriesRemaining == null) {
          retriesRemaining = maxRetries;
        }
        await this.prepareOptions(options2);
        const { req, url: url2, timeout: timeout2 } = await this.buildRequest(options2, {
          retryCount: maxRetries - retriesRemaining
        });
        await this.prepareRequest(req, { url: url2, options: options2 });
        const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0");
        const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`;
        const startTime = Date.now();
        loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
          retryOfRequestLogID,
          method: options2.method,
          url: url2,
          options: options2,
          headers: req.headers
        }));
        if (options2.signal?.aborted) {
          throw new APIUserAbortError();
        }
        const controller = new AbortController();
        const response = await this.fetchWithTimeout(url2, req, timeout2, controller).catch(castToError);
        const headersTime = Date.now();
        if (response instanceof Error) {
          const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
          if (options2.signal?.aborted) {
            throw new APIUserAbortError();
          }
          const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
          if (retriesRemaining) {
            loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
            loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({
              retryOfRequestLogID,
              url: url2,
              durationMs: headersTime - startTime,
              message: response.message
            }));
            return this.retryRequest(options2, retriesRemaining, retryOfRequestLogID ?? requestLogID);
          }
          loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`);
          loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({
            retryOfRequestLogID,
            url: url2,
            durationMs: headersTime - startTime,
            message: response.message
          }));
          if (isTimeout) {
            throw new APIConnectionTimeoutError();
          }
          throw new APIConnectionError({ cause: response });
        }
        const specialHeaders = [...response.headers.entries()].filter(([name3]) => name3 === "x-request-id").map(([name3, value]) => ", " + name3 + ": " + JSON.stringify(value)).join("");
        const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url2} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`;
        if (!response.ok) {
          const shouldRetry = await this.shouldRetry(response);
          if (retriesRemaining && shouldRetry) {
            const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
            await CancelReadableStream(response.body);
            loggerFor(this).info(`${responseInfo} - ${retryMessage2}`);
            loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({
              retryOfRequestLogID,
              url: response.url,
              status: response.status,
              headers: response.headers,
              durationMs: headersTime - startTime
            }));
            return this.retryRequest(options2, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
          }
          const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
          loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
          const errText = await response.text().catch((err2) => castToError(err2).message);
          const errJSON = safeJSON(errText);
          const errMessage = errJSON ? void 0 : errText;
          loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
            retryOfRequestLogID,
            url: response.url,
            status: response.status,
            headers: response.headers,
            message: errMessage,
            durationMs: Date.now() - startTime
          }));
          const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
          throw err;
        }
        loggerFor(this).info(responseInfo);
        loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
          retryOfRequestLogID,
          url: response.url,
          status: response.status,
          headers: response.headers,
          durationMs: headersTime - startTime
        }));
        return { response, options: options2, controller, requestLogID, retryOfRequestLogID, startTime };
      }
      getAPIList(path108, Page2, opts) {
        return this.requestAPIList(Page2, { method: "get", path: path108, ...opts });
      }
      requestAPIList(Page2, options2) {
        const request4 = this.makeRequest(options2, null, void 0);
        return new PagePromise(this, request4, Page2);
      }
      async fetchWithTimeout(url2, init, ms, controller) {
        const { signal, method, ...options2 } = init || {};
        if (signal)
          signal.addEventListener("abort", () => controller.abort());
        const timeout2 = setTimeout(() => controller.abort(), ms);
        const isReadableBody = globalThis.ReadableStream && options2.body instanceof globalThis.ReadableStream || typeof options2.body === "object" && options2.body !== null && Symbol.asyncIterator in options2.body;
        const fetchOptions = {
          signal: controller.signal,
          ...isReadableBody ? { duplex: "half" } : {},
          method: "GET",
          ...options2
        };
        if (method) {
          fetchOptions.method = method.toUpperCase();
        }
        try {
          return await this.fetch.call(void 0, url2, fetchOptions);
        } finally {
          clearTimeout(timeout2);
        }
      }
      async shouldRetry(response) {
        const shouldRetryHeader = response.headers.get("x-should-retry");
        if (shouldRetryHeader === "true")
          return true;
        if (shouldRetryHeader === "false")
          return false;
        if (response.status === 408)
          return true;
        if (response.status === 409)
          return true;
        if (response.status === 429)
          return true;
        if (response.status >= 500)
          return true;
        return false;
      }
      async retryRequest(options2, retriesRemaining, requestLogID, responseHeaders) {
        let timeoutMillis;
        const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms");
        if (retryAfterMillisHeader) {
          const timeoutMs = parseFloat(retryAfterMillisHeader);
          if (!Number.isNaN(timeoutMs)) {
            timeoutMillis = timeoutMs;
          }
        }
        const retryAfterHeader = responseHeaders?.get("retry-after");
        if (retryAfterHeader && !timeoutMillis) {
          const timeoutSeconds = parseFloat(retryAfterHeader);
          if (!Number.isNaN(timeoutSeconds)) {
            timeoutMillis = timeoutSeconds * 1e3;
          } else {
            timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
          }
        }
        if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) {
          const maxRetries = options2.maxRetries ?? this.maxRetries;
          timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
        }
        await sleep2(timeoutMillis);
        return this.makeRequest(options2, retriesRemaining - 1, requestLogID);
      }
      calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
        const initialRetryDelay = 0.5;
        const maxRetryDelay = 8;
        const numRetries = maxRetries - retriesRemaining;
        const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
        const jitter = 1 - Math.random() * 0.25;
        return sleepSeconds * jitter * 1e3;
      }
      async buildRequest(inputOptions, { retryCount = 0 } = {}) {
        const options2 = { ...inputOptions };
        const { method, path: path108, query, defaultBaseURL } = options2;
        const url2 = this.buildURL(path108, query, defaultBaseURL);
        if ("timeout" in options2)
          validatePositiveInteger("timeout", options2.timeout);
        options2.timeout = options2.timeout ?? this.timeout;
        const { bodyHeaders, body } = this.buildBody({ options: options2 });
        const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
        const req = {
          method,
          headers: reqHeaders,
          ...options2.signal && { signal: options2.signal },
          ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" },
          ...body && { body },
          ...this.fetchOptions ?? {},
          ...options2.fetchOptions ?? {}
        };
        return { req, url: url2, timeout: options2.timeout };
      }
      async buildHeaders({ options: options2, method, bodyHeaders, retryCount }) {
        let idempotencyHeaders = {};
        if (this.idempotencyHeader && method !== "get") {
          if (!options2.idempotencyKey)
            options2.idempotencyKey = this.defaultIdempotencyKey();
          idempotencyHeaders[this.idempotencyHeader] = options2.idempotencyKey;
        }
        const headers = buildHeaders([
          idempotencyHeaders,
          {
            Accept: "application/json",
            "User-Agent": this.getUserAgent(),
            "X-Stainless-Retry-Count": String(retryCount),
            ...options2.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options2.timeout / 1e3)) } : {},
            ...getPlatformHeaders(),
            "OpenAI-Organization": this.organization,
            "OpenAI-Project": this.project
          },
          await this.authHeaders(options2),
          this._options.defaultHeaders,
          bodyHeaders,
          options2.headers
        ]);
        this.validateHeaders(headers);
        return headers.values;
      }
      buildBody({ options: { body, headers: rawHeaders } }) {
        if (!body) {
          return { bodyHeaders: void 0, body: void 0 };
        }
        const headers = buildHeaders([rawHeaders]);
        if (
          // Pass raw type verbatim
          ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now
          headers.values.has("content-type") || // `Blob` is superset of `File`
          body instanceof Blob || // `FormData` -> `multipart/form-data`
          body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded`
          body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`)
          globalThis.ReadableStream && body instanceof globalThis.ReadableStream
        ) {
          return { bodyHeaders: void 0, body };
        } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) {
          return { bodyHeaders: void 0, body: ReadableStreamFrom(body) };
        } else {
          return __classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { body, headers });
        }
      }
    };
    _a2 = OpenAI, _OpenAI_encoder = /* @__PURE__ */ new WeakMap(), _OpenAI_instances = /* @__PURE__ */ new WeakSet(), _OpenAI_baseURLOverridden = /* @__PURE__ */ __name(function _OpenAI_baseURLOverridden2() {
      return this.baseURL !== "https://api.openai.com/v1";
    }, "_OpenAI_baseURLOverridden");
    OpenAI.OpenAI = _a2;
    OpenAI.DEFAULT_TIMEOUT = 6e5;
    OpenAI.OpenAIError = OpenAIError;
    OpenAI.APIError = APIError;
    OpenAI.APIConnectionError = APIConnectionError;
    OpenAI.APIConnectionTimeoutError = APIConnectionTimeoutError;
    OpenAI.APIUserAbortError = APIUserAbortError;
    OpenAI.NotFoundError = NotFoundError;
    OpenAI.ConflictError = ConflictError;
    OpenAI.RateLimitError = RateLimitError;
    OpenAI.BadRequestError = BadRequestError2;
    OpenAI.AuthenticationError = AuthenticationError;
    OpenAI.InternalServerError = InternalServerError;
    OpenAI.PermissionDeniedError = PermissionDeniedError;
    OpenAI.UnprocessableEntityError = UnprocessableEntityError;
    OpenAI.InvalidWebhookSignatureError = InvalidWebhookSignatureError;
    OpenAI.toFile = toFile;
    OpenAI.Completions = Completions2;
    OpenAI.Chat = Chat2;
    OpenAI.Embeddings = Embeddings;
    OpenAI.Files = Files3;
    OpenAI.Images = Images;
    OpenAI.Audio = Audio;
    OpenAI.Moderations = Moderations;
    OpenAI.Models = Models2;
    OpenAI.FineTuning = FineTuning;
    OpenAI.Graders = Graders2;
    OpenAI.VectorStores = VectorStores;
    OpenAI.Webhooks = Webhooks;
    OpenAI.Beta = Beta;
    OpenAI.Batches = Batches2;
    OpenAI.Uploads = Uploads;
    OpenAI.Responses = Responses;
    OpenAI.Evals = Evals;
    OpenAI.Containers = Containers;
  }
});

// node_modules/openai/azure.mjs
var init_azure = __esm({
  "node_modules/openai/azure.mjs"() {
    init_esbuild_shims();
    init_error2();
    init_utils5();
    init_client();
    init_headers();
  }
});

// node_modules/openai/index.mjs
var init_openai = __esm({
  "node_modules/openai/index.mjs"() {
    init_esbuild_shims();
    init_client();
    init_uploads2();
    init_api_promise();
    init_client();
    init_pagination();
    init_error();
    init_azure();
  }
});

// packages/core/dist/src/core/openaiContentGenerator/constants.js
var DEFAULT_TIMEOUT, DEFAULT_MAX_RETRIES, DEFAULT_DASHSCOPE_BASE_URL;
var init_constants2 = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/constants.js"() {
    "use strict";
    init_esbuild_shims();
    DEFAULT_TIMEOUT = 12e4;
    DEFAULT_MAX_RETRIES = 3;
    DEFAULT_DASHSCOPE_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1";
  }
});

// packages/core/dist/src/core/openaiContentGenerator/provider/default.js
var DefaultOpenAICompatibleProvider;
var init_default = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/provider/default.js"() {
    "use strict";
    init_esbuild_shims();
    init_openai();
    init_constants2();
    DefaultOpenAICompatibleProvider = class {
      static {
        __name(this, "DefaultOpenAICompatibleProvider");
      }
      contentGeneratorConfig;
      cliConfig;
      constructor(contentGeneratorConfig, cliConfig) {
        this.cliConfig = cliConfig;
        this.contentGeneratorConfig = contentGeneratorConfig;
      }
      buildHeaders() {
        const version2 = this.cliConfig.getCliVersion() || "unknown";
        const userAgent2 = `QwenCode/${version2} (${process.platform}; ${process.arch})`;
        return {
          "User-Agent": userAgent2
        };
      }
      buildClient() {
        const { apiKey, baseUrl, timeout: timeout2 = DEFAULT_TIMEOUT, maxRetries = DEFAULT_MAX_RETRIES } = this.contentGeneratorConfig;
        const defaultHeaders = this.buildHeaders();
        return new OpenAI({
          apiKey,
          baseURL: baseUrl,
          timeout: timeout2,
          maxRetries,
          defaultHeaders
        });
      }
      buildRequest(request4, _userPromptId) {
        return {
          ...request4
          // Preserve all original parameters including sampling params
        };
      }
    };
  }
});

// packages/core/dist/src/core/openaiContentGenerator/provider/modelscope.js
var ModelScopeOpenAICompatibleProvider;
var init_modelscope = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/provider/modelscope.js"() {
    "use strict";
    init_esbuild_shims();
    init_default();
    ModelScopeOpenAICompatibleProvider = class extends DefaultOpenAICompatibleProvider {
      static {
        __name(this, "ModelScopeOpenAICompatibleProvider");
      }
      /**
       * Checks if the configuration is for ModelScope.
       */
      static isModelScopeProvider(config) {
        return !!config.baseUrl?.includes("modelscope");
      }
      /**
       * ModelScope does not support `stream_options` when `stream` is false.
       * This method removes `stream_options` if `stream` is not true.
       */
      buildRequest(request4, userPromptId) {
        const newRequest = super.buildRequest(request4, userPromptId);
        if (!newRequest.stream) {
          delete newRequest.stream_options;
        }
        return newRequest;
      }
    };
  }
});

// packages/core/dist/src/core/tokenLimits.js
function normalize(model) {
  let s2 = (model ?? "").toLowerCase().trim();
  s2 = s2.replace(/^.*\//, "");
  s2 = s2.split("|").pop() ?? s2;
  s2 = s2.split(":").pop() ?? s2;
  s2 = s2.replace(/\s+/g, "-");
  s2 = s2.replace(/-preview/g, "");
  if (!s2.match(/^qwen-(?:plus|flash|vl-max)-latest$/) && !s2.match(/^kimi-k2-\d{4}$/)) {
    s2 = s2.replace(/-(?:\d{4,}|\d+x\d+b|v\d+(?:\.\d+)*|(?<=-[^-]+-)\d+(?:\.\d+)+|latest|exp)$/g, "");
  }
  s2 = s2.replace(/-(?:\d?bit|int[48]|bf16|fp16|q[45]|quantized)$/g, "");
  return s2;
}
function tokenLimit(model, type = "input") {
  const norm = normalize(model);
  const patterns = type === "output" ? OUTPUT_PATTERNS : PATTERNS;
  for (const [regex3, limit2] of patterns) {
    if (regex3.test(norm)) {
      return limit2;
    }
  }
  return type === "output" ? DEFAULT_OUTPUT_TOKEN_LIMIT : DEFAULT_TOKEN_LIMIT;
}
var DEFAULT_TOKEN_LIMIT, DEFAULT_OUTPUT_TOKEN_LIMIT, LIMITS, PATTERNS, OUTPUT_PATTERNS;
var init_tokenLimits = __esm({
  "packages/core/dist/src/core/tokenLimits.js"() {
    "use strict";
    init_esbuild_shims();
    DEFAULT_TOKEN_LIMIT = 131072;
    DEFAULT_OUTPUT_TOKEN_LIMIT = 4096;
    LIMITS = {
      "32k": 32768,
      "64k": 65536,
      "128k": 131072,
      "200k": 2e5,
      // vendor-declared decimal, used by OpenAI, Anthropic, GLM etc.
      "256k": 262144,
      "512k": 524288,
      "1m": 1048576,
      "2m": 2097152,
      "10m": 10485760,
      // 10 million tokens
      // Output token limits (typically much smaller than input limits)
      "4k": 4096,
      "8k": 8192,
      "16k": 16384
    };
    __name(normalize, "normalize");
    PATTERNS = [
      // -------------------
      // Google Gemini
      // -------------------
      [/^gemini-1\.5-pro$/, LIMITS["2m"]],
      [/^gemini-1\.5-flash$/, LIMITS["1m"]],
      [/^gemini-2\.5-pro.*$/, LIMITS["1m"]],
      [/^gemini-2\.5-flash.*$/, LIMITS["1m"]],
      [/^gemini-2\.0-flash-image-generation$/, LIMITS["32k"]],
      [/^gemini-2\.0-flash.*$/, LIMITS["1m"]],
      // -------------------
      // OpenAI (o3 / o4-mini / gpt-4.1 / gpt-4o family)
      // o3 and o4-mini document a 200,000-token context window (decimal).
      // Note: GPT-4.1 models typically report 1_048_576 (1M) context in OpenAI announcements.
      [/^o3(?:-mini|$).*$/, LIMITS["200k"]],
      [/^o3.*$/, LIMITS["200k"]],
      [/^o4-mini.*$/, LIMITS["200k"]],
      [/^gpt-4\.1-mini.*$/, LIMITS["1m"]],
      [/^gpt-4\.1.*$/, LIMITS["1m"]],
      [/^gpt-4o-mini.*$/, LIMITS["128k"]],
      [/^gpt-4o.*$/, LIMITS["128k"]],
      [/^gpt-4.*$/, LIMITS["128k"]],
      // -------------------
      // Anthropic Claude
      // - Claude Sonnet / Sonnet 3.5 and related Sonnet variants: 200,000 tokens documented.
      // - Some Sonnet/Opus models offer 1M in beta/enterprise tiers (handled separately if needed).
      [/^claude-3\.5-sonnet.*$/, LIMITS["200k"]],
      [/^claude-3\.7-sonnet.*$/, LIMITS["1m"]],
      // some Sonnet 3.7/Opus variants advertise 1M beta in docs
      [/^claude-sonnet-4.*$/, LIMITS["1m"]],
      [/^claude-opus-4.*$/, LIMITS["1m"]],
      // -------------------
      // Alibaba / Qwen
      // -------------------
      // Commercial Qwen3-Coder-Plus: 1M token context
      [/^qwen3-coder-plus(-.*)?$/, LIMITS["1m"]],
      // catches "qwen3-coder-plus" and date variants
      // Commercial Qwen3-Coder-Flash: 1M token context
      [/^qwen3-coder-flash(-.*)?$/, LIMITS["1m"]],
      // catches "qwen3-coder-flash" and date variants
      // Generic coder-model: same as qwen3-coder-plus (1M token context)
      [/^coder-model$/, LIMITS["1m"]],
      // Commercial Qwen3-Max-Preview: 256K token context
      [/^qwen3-max(-preview)?(-.*)?$/, LIMITS["256k"]],
      // catches "qwen3-max" or "qwen3-max-preview" and date variants
      // Open-source Qwen3-Coder variants: 256K native
      [/^qwen3-coder-.*$/, LIMITS["256k"]],
      // Open-source Qwen3 2507 variants: 256K native
      [/^qwen3-.*-2507-.*$/, LIMITS["256k"]],
      // Open-source long-context Qwen2.5-1M
      [/^qwen2\.5-1m.*$/, LIMITS["1m"]],
      // Standard Qwen2.5: 128K
      [/^qwen2\.5.*$/, LIMITS["128k"]],
      // Studio commercial Qwen-Plus / Qwen-Flash / Qwen-Turbo
      [/^qwen-plus-latest$/, LIMITS["1m"]],
      // Commercial latest: 1M
      [/^qwen-plus.*$/, LIMITS["128k"]],
      // Standard: 128K
      [/^qwen-flash-latest$/, LIMITS["1m"]],
      [/^qwen-turbo.*$/, LIMITS["128k"]],
      // Qwen Vision Models
      [/^qwen3-vl-plus$/, LIMITS["256k"]],
      // Qwen3-VL-Plus: 256K input
      [/^qwen-vl-max.*$/, LIMITS["128k"]],
      // Generic vision-model: same as qwen-vl-max (128K token context)
      [/^vision-model$/, LIMITS["128k"]],
      // -------------------
      // ByteDance Seed-OSS (512K)
      // -------------------
      [/^seed-oss.*$/, LIMITS["512k"]],
      // -------------------
      // Zhipu GLM
      // -------------------
      [/^glm-4\.5v(?:-.*)?$/, LIMITS["64k"]],
      [/^glm-4\.5-air(?:-.*)?$/, LIMITS["128k"]],
      [/^glm-4\.5(?:-.*)?$/, LIMITS["128k"]],
      [/^glm-4\.6(?:-.*)?$/, 202752],
      // exact limit from the model config file
      // -------------------
      // DeepSeek
      // -------------------
      [/^deepseek(?:-.*)?$/, LIMITS["128k"]],
      // -------------------
      // Moonshot / Kimi
      // -------------------
      [/^kimi-k2-0905$/, LIMITS["256k"]],
      // Kimi-k2-0905-preview: 256K context
      [/^kimi-k2-turbo.*$/, LIMITS["256k"]],
      // Kimi-k2-turbo-preview: 256K context
      [/^kimi-k2-0711$/, LIMITS["128k"]],
      // Kimi-k2-0711-preview: 128K context
      [/^kimi-k2-instruct.*$/, LIMITS["128k"]],
      // Kimi-k2-instruct: 128K context
      // -------------------
      // GPT-OSS / Llama & Mistral examples
      // -------------------
      [/^gpt-oss.*$/, LIMITS["128k"]],
      [/^llama-4-scout.*$/, LIMITS["10m"]],
      [/^mistral-large-2.*$/, LIMITS["128k"]]
    ];
    OUTPUT_PATTERNS = [
      // -------------------
      // Alibaba / Qwen - DashScope Models
      // -------------------
      // Qwen3-Coder-Plus: 65,536 max output tokens
      [/^qwen3-coder-plus(-.*)?$/, LIMITS["64k"]],
      // Generic coder-model: same as qwen3-coder-plus (64K max output tokens)
      [/^coder-model$/, LIMITS["64k"]],
      // Qwen3-Max: 65,536 max output tokens
      [/^qwen3-max(-preview)?(-.*)?$/, LIMITS["64k"]],
      // Qwen-VL-Max-Latest: 8,192 max output tokens
      [/^qwen-vl-max-latest$/, LIMITS["8k"]],
      // Generic vision-model: same as qwen-vl-max-latest (8K max output tokens)
      [/^vision-model$/, LIMITS["8k"]],
      // Qwen3-VL-Plus: 32K max output tokens
      [/^qwen3-vl-plus$/, LIMITS["32k"]],
      // Deepseek-chat: 8k max tokens
      [/^deepseek-chat$/, LIMITS["8k"]],
      // Deepseek-reasoner: 64k max tokens
      [/^deepseek-reasoner$/, LIMITS["64k"]]
    ];
    __name(tokenLimit, "tokenLimit");
  }
});

// packages/core/dist/src/core/openaiContentGenerator/provider/dashscope.js
var DashScopeOpenAICompatibleProvider;
var init_dashscope = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/provider/dashscope.js"() {
    "use strict";
    init_esbuild_shims();
    init_openai();
    init_contentGenerator();
    init_constants2();
    init_tokenLimits();
    DashScopeOpenAICompatibleProvider = class {
      static {
        __name(this, "DashScopeOpenAICompatibleProvider");
      }
      contentGeneratorConfig;
      cliConfig;
      constructor(contentGeneratorConfig, cliConfig) {
        this.cliConfig = cliConfig;
        this.contentGeneratorConfig = contentGeneratorConfig;
      }
      static isDashScopeProvider(contentGeneratorConfig) {
        const authType = contentGeneratorConfig.authType;
        const baseUrl = contentGeneratorConfig.baseUrl;
        return authType === AuthType2.QWEN_OAUTH || baseUrl === "https://dashscope.aliyuncs.com/compatible-mode/v1" || baseUrl === "https://dashscope-intl.aliyuncs.com/compatible-mode/v1";
      }
      buildHeaders() {
        const version2 = this.cliConfig.getCliVersion() || "unknown";
        const userAgent2 = `QwenCode/${version2} (${process.platform}; ${process.arch})`;
        const { authType } = this.contentGeneratorConfig;
        return {
          "User-Agent": userAgent2,
          "X-DashScope-CacheControl": "enable",
          "X-DashScope-UserAgent": userAgent2,
          "X-DashScope-AuthType": authType
        };
      }
      buildClient() {
        const { apiKey, baseUrl = DEFAULT_DASHSCOPE_BASE_URL, timeout: timeout2 = DEFAULT_TIMEOUT, maxRetries = DEFAULT_MAX_RETRIES } = this.contentGeneratorConfig;
        const defaultHeaders = this.buildHeaders();
        return new OpenAI({
          apiKey,
          baseURL: baseUrl,
          timeout: timeout2,
          maxRetries,
          defaultHeaders
        });
      }
      /**
       * Build and configure the request for DashScope API.
       *
       * This method applies DashScope-specific configurations including:
       * - Cache control for the system message, last tool message (when tools are configured),
       *   and the latest history message
       * - Output token limits based on model capabilities
       * - Vision model specific parameters (vl_high_resolution_images)
       * - Request metadata for session tracking
       *
       * @param request - The original chat completion request parameters
       * @param userPromptId - Unique identifier for the user prompt for session tracking
       * @returns Configured request with DashScope-specific parameters applied
       */
      buildRequest(request4, userPromptId) {
        let messages = request4.messages;
        let tools = request4.tools;
        if (!this.shouldDisableCacheControl()) {
          const { messages: updatedMessages, tools: updatedTools } = this.addDashScopeCacheControl(request4, request4.stream ? "all" : "system_only");
          messages = updatedMessages;
          tools = updatedTools;
        }
        const requestWithTokenLimits = this.applyOutputTokenLimit(request4, request4.model);
        if (this.isVisionModel(request4.model)) {
          return {
            ...requestWithTokenLimits,
            messages,
            ...tools ? { tools } : {},
            ...this.buildMetadata(userPromptId) || {},
            /* @ts-expect-error dashscope exclusive */
            vl_high_resolution_images: true
          };
        }
        return {
          ...requestWithTokenLimits,
          // Preserve all original parameters including sampling params and adjusted max_tokens
          messages,
          ...tools ? { tools } : {},
          ...this.buildMetadata(userPromptId) || {}
        };
      }
      buildMetadata(userPromptId) {
        return {
          metadata: {
            sessionId: this.cliConfig.getSessionId?.(),
            promptId: userPromptId
          }
        };
      }
      /**
       * Add cache control flag to specified message(s) for DashScope providers
       */
      addDashScopeCacheControl(request4, cacheControl) {
        const messages = request4.messages;
        const systemIndex = messages.findIndex((msg) => msg.role === "system");
        const lastIndex = messages.length - 1;
        const updatedMessages = messages.length === 0 ? messages : messages.map((message, index) => {
          const shouldAddCacheControl = Boolean(index === systemIndex && systemIndex !== -1 || index === lastIndex && cacheControl === "all");
          if (!shouldAddCacheControl || !("content" in message) || message.content === null || message.content === void 0) {
            return message;
          }
          return {
            ...message,
            content: this.addCacheControlToContent(message.content)
          };
        });
        const updatedTools = cacheControl === "all" && request4.tools?.length ? this.addCacheControlToTools(request4.tools) : request4.tools;
        return {
          messages: updatedMessages,
          tools: updatedTools
        };
      }
      addCacheControlToTools(tools) {
        if (tools.length === 0) {
          return tools;
        }
        const updatedTools = [...tools];
        const lastToolIndex = tools.length - 1;
        updatedTools[lastToolIndex] = {
          ...updatedTools[lastToolIndex],
          cache_control: { type: "ephemeral" }
        };
        return updatedTools;
      }
      /**
       * Add cache control to message content, handling both string and array formats
       */
      addCacheControlToContent(content) {
        const contentArray = this.normalizeContentToArray(content);
        return this.addCacheControlToContentArray(contentArray);
      }
      /**
       * Normalize content to array format
       */
      normalizeContentToArray(content) {
        if (typeof content === "string") {
          return [
            {
              type: "text",
              text: content
            }
          ];
        }
        return [...content];
      }
      /**
       * Add cache control to the content array
       */
      addCacheControlToContentArray(contentArray) {
        if (contentArray.length === 0) {
          return [
            {
              type: "text",
              text: "",
              cache_control: { type: "ephemeral" }
            }
          ];
        }
        const lastItem = contentArray[contentArray.length - 1];
        if (lastItem.type === "text") {
          contentArray[contentArray.length - 1] = {
            ...lastItem,
            cache_control: { type: "ephemeral" }
          };
        } else {
          contentArray.push({
            type: "text",
            text: "",
            cache_control: { type: "ephemeral" }
          });
        }
        return contentArray;
      }
      isVisionModel(model) {
        if (!model) {
          return false;
        }
        const normalized2 = model.toLowerCase();
        if (normalized2 === "vision-model") {
          return true;
        }
        if (normalized2.startsWith("qwen-vl")) {
          return true;
        }
        if (normalized2.startsWith("qwen3-vl-plus")) {
          return true;
        }
        return false;
      }
      /**
       * Apply output token limit to a request's max_tokens parameter.
       *
       * Ensures that existing max_tokens parameters don't exceed the model's maximum output
       * token limit. Only modifies max_tokens when already present in the request.
       *
       * @param request - The chat completion request parameters
       * @param model - The model name to get the output token limit for
       * @returns The request with max_tokens adjusted to respect the model's limits (if present)
       */
      applyOutputTokenLimit(request4, model) {
        const currentMaxTokens = request4.max_tokens;
        if (currentMaxTokens === void 0 || currentMaxTokens === null) {
          return request4;
        }
        const modelLimit = tokenLimit(model, "output");
        if (currentMaxTokens > modelLimit) {
          return {
            ...request4,
            max_tokens: modelLimit
          };
        }
        return request4;
      }
      /**
       * Check if cache control should be disabled based on configuration.
       *
       * @returns true if cache control should be disabled, false otherwise
       */
      shouldDisableCacheControl() {
        return this.cliConfig.getContentGeneratorConfig()?.disableCacheControl === true;
      }
    };
  }
});

// packages/core/dist/src/core/openaiContentGenerator/provider/deepseek.js
var DeepSeekOpenAICompatibleProvider;
var init_deepseek = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/provider/deepseek.js"() {
    "use strict";
    init_esbuild_shims();
    init_default();
    DeepSeekOpenAICompatibleProvider = class extends DefaultOpenAICompatibleProvider {
      static {
        __name(this, "DeepSeekOpenAICompatibleProvider");
      }
      constructor(contentGeneratorConfig, cliConfig) {
        super(contentGeneratorConfig, cliConfig);
      }
      static isDeepSeekProvider(contentGeneratorConfig) {
        const baseUrl = contentGeneratorConfig.baseUrl ?? "";
        return baseUrl.toLowerCase().includes("api.deepseek.com");
      }
      buildRequest(request4, userPromptId) {
        const baseRequest = super.buildRequest(request4, userPromptId);
        if (!baseRequest.messages?.length) {
          return baseRequest;
        }
        const messages = baseRequest.messages.map((message) => {
          if (!("content" in message)) {
            return message;
          }
          const { content } = message;
          if (typeof content === "string" || content === null || content === void 0) {
            return message;
          }
          if (!Array.isArray(content)) {
            return message;
          }
          const text = content.map((part) => {
            if (part.type !== "text") {
              throw new Error(`DeepSeek provider only supports text content. Found non-text part of type '${part.type}' in message with role '${message.role}'.`);
            }
            return part.text ?? "";
          }).join("");
          return {
            ...message,
            content: text
          };
        });
        return {
          ...baseRequest,
          messages
        };
      }
    };
  }
});

// packages/core/dist/src/core/openaiContentGenerator/provider/openrouter.js
var OpenRouterOpenAICompatibleProvider;
var init_openrouter = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/provider/openrouter.js"() {
    "use strict";
    init_esbuild_shims();
    init_default();
    OpenRouterOpenAICompatibleProvider = class extends DefaultOpenAICompatibleProvider {
      static {
        __name(this, "OpenRouterOpenAICompatibleProvider");
      }
      constructor(contentGeneratorConfig, cliConfig) {
        super(contentGeneratorConfig, cliConfig);
      }
      static isOpenRouterProvider(contentGeneratorConfig) {
        const baseURL = contentGeneratorConfig.baseUrl || "";
        return baseURL.includes("openrouter.ai");
      }
      buildHeaders() {
        const baseHeaders = super.buildHeaders();
        return {
          ...baseHeaders,
          "HTTP-Referer": "https://github.com/QwenLM/qwen-code.git",
          "X-Title": "Qwen Code"
        };
      }
    };
  }
});

// packages/core/dist/src/core/openaiContentGenerator/provider/index.js
var init_provider = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/provider/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_modelscope();
    init_dashscope();
    init_deepseek();
    init_openrouter();
    init_default();
  }
});

// node_modules/jsonrepair/lib/esm/utils/JSONRepairError.js
var JSONRepairError;
var init_JSONRepairError = __esm({
  "node_modules/jsonrepair/lib/esm/utils/JSONRepairError.js"() {
    init_esbuild_shims();
    JSONRepairError = class extends Error {
      static {
        __name(this, "JSONRepairError");
      }
      constructor(message, position) {
        super(`${message} at position ${position}`);
        this.position = position;
      }
    };
  }
});

// node_modules/jsonrepair/lib/esm/utils/stringUtils.js
function isHex(char) {
  return /^[0-9A-Fa-f]$/.test(char);
}
function isDigit2(char) {
  return char >= "0" && char <= "9";
}
function isValidStringCharacter(char) {
  return char >= " ";
}
function isDelimiter(char) {
  return ",:[]/{}()\n+".includes(char);
}
function isFunctionNameCharStart(char) {
  return char >= "a" && char <= "z" || char >= "A" && char <= "Z" || char === "_" || char === "$";
}
function isFunctionNameChar(char) {
  return char >= "a" && char <= "z" || char >= "A" && char <= "Z" || char === "_" || char === "$" || char >= "0" && char <= "9";
}
function isUnquotedStringDelimiter(char) {
  return ",[]/{}\n+".includes(char);
}
function isStartOfValue(char) {
  return isQuote(char) || regexStartOfValue.test(char);
}
function isControlCharacter(char) {
  return char === "\n" || char === "\r" || char === "	" || char === "\b" || char === "\f";
}
function isWhitespace(text, index) {
  const code2 = text.charCodeAt(index);
  return code2 === codeSpace || code2 === codeNewline || code2 === codeTab || code2 === codeReturn;
}
function isWhitespaceExceptNewline(text, index) {
  const code2 = text.charCodeAt(index);
  return code2 === codeSpace || code2 === codeTab || code2 === codeReturn;
}
function isSpecialWhitespace(text, index) {
  const code2 = text.charCodeAt(index);
  return code2 === codeNonBreakingSpace || code2 >= codeEnQuad && code2 <= codeHairSpace || code2 === codeNarrowNoBreakSpace || code2 === codeMediumMathematicalSpace || code2 === codeIdeographicSpace;
}
function isQuote(char) {
  return isDoubleQuoteLike(char) || isSingleQuoteLike(char);
}
function isDoubleQuoteLike(char) {
  return char === '"' || char === "\u201C" || char === "\u201D";
}
function isDoubleQuote(char) {
  return char === '"';
}
function isSingleQuoteLike(char) {
  return char === "'" || char === "\u2018" || char === "\u2019" || char === "`" || char === "\xB4";
}
function isSingleQuote(char) {
  return char === "'";
}
function stripLastOccurrence(text, textToStrip) {
  let stripRemainingText = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
  const index = text.lastIndexOf(textToStrip);
  return index !== -1 ? text.substring(0, index) + (stripRemainingText ? "" : text.substring(index + 1)) : text;
}
function insertBeforeLastWhitespace(text, textToInsert) {
  let index = text.length;
  if (!isWhitespace(text, index - 1)) {
    return text + textToInsert;
  }
  while (isWhitespace(text, index - 1)) {
    index--;
  }
  return text.substring(0, index) + textToInsert + text.substring(index);
}
function removeAtIndex(text, start, count) {
  return text.substring(0, start) + text.substring(start + count);
}
function endsWithCommaOrNewline(text) {
  return /[,\n][ \t\r]*$/.test(text);
}
var codeSpace, codeNewline, codeTab, codeReturn, codeNonBreakingSpace, codeEnQuad, codeHairSpace, codeNarrowNoBreakSpace, codeMediumMathematicalSpace, codeIdeographicSpace, regexUrlStart, regexUrlChar, regexStartOfValue;
var init_stringUtils = __esm({
  "node_modules/jsonrepair/lib/esm/utils/stringUtils.js"() {
    init_esbuild_shims();
    codeSpace = 32;
    codeNewline = 10;
    codeTab = 9;
    codeReturn = 13;
    codeNonBreakingSpace = 160;
    codeEnQuad = 8192;
    codeHairSpace = 8202;
    codeNarrowNoBreakSpace = 8239;
    codeMediumMathematicalSpace = 8287;
    codeIdeographicSpace = 12288;
    __name(isHex, "isHex");
    __name(isDigit2, "isDigit");
    __name(isValidStringCharacter, "isValidStringCharacter");
    __name(isDelimiter, "isDelimiter");
    __name(isFunctionNameCharStart, "isFunctionNameCharStart");
    __name(isFunctionNameChar, "isFunctionNameChar");
    regexUrlStart = /^(http|https|ftp|mailto|file|data|irc):\/\/$/;
    regexUrlChar = /^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;
    __name(isUnquotedStringDelimiter, "isUnquotedStringDelimiter");
    __name(isStartOfValue, "isStartOfValue");
    regexStartOfValue = /^[[{\w-]$/;
    __name(isControlCharacter, "isControlCharacter");
    __name(isWhitespace, "isWhitespace");
    __name(isWhitespaceExceptNewline, "isWhitespaceExceptNewline");
    __name(isSpecialWhitespace, "isSpecialWhitespace");
    __name(isQuote, "isQuote");
    __name(isDoubleQuoteLike, "isDoubleQuoteLike");
    __name(isDoubleQuote, "isDoubleQuote");
    __name(isSingleQuoteLike, "isSingleQuoteLike");
    __name(isSingleQuote, "isSingleQuote");
    __name(stripLastOccurrence, "stripLastOccurrence");
    __name(insertBeforeLastWhitespace, "insertBeforeLastWhitespace");
    __name(removeAtIndex, "removeAtIndex");
    __name(endsWithCommaOrNewline, "endsWithCommaOrNewline");
  }
});

// node_modules/jsonrepair/lib/esm/regular/jsonrepair.js
function jsonrepair(text) {
  let i = 0;
  let output = "";
  parseMarkdownCodeBlock(["```", "[```", "{```"]);
  const processed = parseValue2();
  if (!processed) {
    throwUnexpectedEnd();
  }
  parseMarkdownCodeBlock(["```", "```]", "```}"]);
  const processedComma = parseCharacter(",");
  if (processedComma) {
    parseWhitespaceAndSkipComments();
  }
  if (isStartOfValue(text[i]) && endsWithCommaOrNewline(output)) {
    if (!processedComma) {
      output = insertBeforeLastWhitespace(output, ",");
    }
    parseNewlineDelimitedJSON();
  } else if (processedComma) {
    output = stripLastOccurrence(output, ",");
  }
  while (text[i] === "}" || text[i] === "]") {
    i++;
    parseWhitespaceAndSkipComments();
  }
  if (i >= text.length) {
    return output;
  }
  throwUnexpectedCharacter();
  function parseValue2() {
    parseWhitespaceAndSkipComments();
    const processed2 = parseObject() || parseArray() || parseString() || parseNumber() || parseKeywords() || parseUnquotedString(false) || parseRegex();
    parseWhitespaceAndSkipComments();
    return processed2;
  }
  __name(parseValue2, "parseValue");
  function parseWhitespaceAndSkipComments() {
    let skipNewline = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
    const start = i;
    let changed = parseWhitespace(skipNewline);
    do {
      changed = parseComment();
      if (changed) {
        changed = parseWhitespace(skipNewline);
      }
    } while (changed);
    return i > start;
  }
  __name(parseWhitespaceAndSkipComments, "parseWhitespaceAndSkipComments");
  function parseWhitespace(skipNewline) {
    const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline;
    let whitespace = "";
    while (true) {
      if (_isWhiteSpace(text, i)) {
        whitespace += text[i];
        i++;
      } else if (isSpecialWhitespace(text, i)) {
        whitespace += " ";
        i++;
      } else {
        break;
      }
    }
    if (whitespace.length > 0) {
      output += whitespace;
      return true;
    }
    return false;
  }
  __name(parseWhitespace, "parseWhitespace");
  function parseComment() {
    if (text[i] === "/" && text[i + 1] === "*") {
      while (i < text.length && !atEndOfBlockComment(text, i)) {
        i++;
      }
      i += 2;
      return true;
    }
    if (text[i] === "/" && text[i + 1] === "/") {
      while (i < text.length && text[i] !== "\n") {
        i++;
      }
      return true;
    }
    return false;
  }
  __name(parseComment, "parseComment");
  function parseMarkdownCodeBlock(blocks) {
    if (skipMarkdownCodeBlock(blocks)) {
      if (isFunctionNameCharStart(text[i])) {
        while (i < text.length && isFunctionNameChar(text[i])) {
          i++;
        }
      }
      parseWhitespaceAndSkipComments();
      return true;
    }
    return false;
  }
  __name(parseMarkdownCodeBlock, "parseMarkdownCodeBlock");
  function skipMarkdownCodeBlock(blocks) {
    parseWhitespace(true);
    for (const block2 of blocks) {
      const end = i + block2.length;
      if (text.slice(i, end) === block2) {
        i = end;
        return true;
      }
    }
    return false;
  }
  __name(skipMarkdownCodeBlock, "skipMarkdownCodeBlock");
  function parseCharacter(char) {
    if (text[i] === char) {
      output += text[i];
      i++;
      return true;
    }
    return false;
  }
  __name(parseCharacter, "parseCharacter");
  function skipCharacter(char) {
    if (text[i] === char) {
      i++;
      return true;
    }
    return false;
  }
  __name(skipCharacter, "skipCharacter");
  function skipEscapeCharacter() {
    return skipCharacter("\\");
  }
  __name(skipEscapeCharacter, "skipEscapeCharacter");
  function skipEllipsis() {
    parseWhitespaceAndSkipComments();
    if (text[i] === "." && text[i + 1] === "." && text[i + 2] === ".") {
      i += 3;
      parseWhitespaceAndSkipComments();
      skipCharacter(",");
      return true;
    }
    return false;
  }
  __name(skipEllipsis, "skipEllipsis");
  function parseObject() {
    if (text[i] === "{") {
      output += "{";
      i++;
      parseWhitespaceAndSkipComments();
      if (skipCharacter(",")) {
        parseWhitespaceAndSkipComments();
      }
      let initial = true;
      while (i < text.length && text[i] !== "}") {
        let processedComma2;
        if (!initial) {
          processedComma2 = parseCharacter(",");
          if (!processedComma2) {
            output = insertBeforeLastWhitespace(output, ",");
          }
          parseWhitespaceAndSkipComments();
        } else {
          processedComma2 = true;
          initial = false;
        }
        skipEllipsis();
        const processedKey = parseString() || parseUnquotedString(true);
        if (!processedKey) {
          if (text[i] === "}" || text[i] === "{" || text[i] === "]" || text[i] === "[" || text[i] === void 0) {
            output = stripLastOccurrence(output, ",");
          } else {
            throwObjectKeyExpected();
          }
          break;
        }
        parseWhitespaceAndSkipComments();
        const processedColon = parseCharacter(":");
        const truncatedText = i >= text.length;
        if (!processedColon) {
          if (isStartOfValue(text[i]) || truncatedText) {
            output = insertBeforeLastWhitespace(output, ":");
          } else {
            throwColonExpected();
          }
        }
        const processedValue = parseValue2();
        if (!processedValue) {
          if (processedColon || truncatedText) {
            output += "null";
          } else {
            throwColonExpected();
          }
        }
      }
      if (text[i] === "}") {
        output += "}";
        i++;
      } else {
        output = insertBeforeLastWhitespace(output, "}");
      }
      return true;
    }
    return false;
  }
  __name(parseObject, "parseObject");
  function parseArray() {
    if (text[i] === "[") {
      output += "[";
      i++;
      parseWhitespaceAndSkipComments();
      if (skipCharacter(",")) {
        parseWhitespaceAndSkipComments();
      }
      let initial = true;
      while (i < text.length && text[i] !== "]") {
        if (!initial) {
          const processedComma2 = parseCharacter(",");
          if (!processedComma2) {
            output = insertBeforeLastWhitespace(output, ",");
          }
        } else {
          initial = false;
        }
        skipEllipsis();
        const processedValue = parseValue2();
        if (!processedValue) {
          output = stripLastOccurrence(output, ",");
          break;
        }
      }
      if (text[i] === "]") {
        output += "]";
        i++;
      } else {
        output = insertBeforeLastWhitespace(output, "]");
      }
      return true;
    }
    return false;
  }
  __name(parseArray, "parseArray");
  function parseNewlineDelimitedJSON() {
    let initial = true;
    let processedValue = true;
    while (processedValue) {
      if (!initial) {
        const processedComma2 = parseCharacter(",");
        if (!processedComma2) {
          output = insertBeforeLastWhitespace(output, ",");
        }
      } else {
        initial = false;
      }
      processedValue = parseValue2();
    }
    if (!processedValue) {
      output = stripLastOccurrence(output, ",");
    }
    output = `[
${output}
]`;
  }
  __name(parseNewlineDelimitedJSON, "parseNewlineDelimitedJSON");
  function parseString() {
    let stopAtDelimiter = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false;
    let stopAtIndex = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : -1;
    let skipEscapeChars = text[i] === "\\";
    if (skipEscapeChars) {
      i++;
      skipEscapeChars = true;
    }
    if (isQuote(text[i])) {
      const isEndQuote = isDoubleQuote(text[i]) ? isDoubleQuote : isSingleQuote(text[i]) ? isSingleQuote : isSingleQuoteLike(text[i]) ? isSingleQuoteLike : isDoubleQuoteLike;
      const iBefore = i;
      const oBefore = output.length;
      let str2 = '"';
      i++;
      while (true) {
        if (i >= text.length) {
          const iPrev = prevNonWhitespaceIndex(i - 1);
          if (!stopAtDelimiter && isDelimiter(text.charAt(iPrev))) {
            i = iBefore;
            output = output.substring(0, oBefore);
            return parseString(true);
          }
          str2 = insertBeforeLastWhitespace(str2, '"');
          output += str2;
          return true;
        }
        if (i === stopAtIndex) {
          str2 = insertBeforeLastWhitespace(str2, '"');
          output += str2;
          return true;
        }
        if (isEndQuote(text[i])) {
          const iQuote = i;
          const oQuote = str2.length;
          str2 += '"';
          i++;
          output += str2;
          parseWhitespaceAndSkipComments(false);
          if (stopAtDelimiter || i >= text.length || isDelimiter(text[i]) || isQuote(text[i]) || isDigit2(text[i])) {
            parseConcatenatedString();
            return true;
          }
          const iPrevChar = prevNonWhitespaceIndex(iQuote - 1);
          const prevChar = text.charAt(iPrevChar);
          if (prevChar === ",") {
            i = iBefore;
            output = output.substring(0, oBefore);
            return parseString(false, iPrevChar);
          }
          if (isDelimiter(prevChar)) {
            i = iBefore;
            output = output.substring(0, oBefore);
            return parseString(true);
          }
          output = output.substring(0, oBefore);
          i = iQuote + 1;
          str2 = `${str2.substring(0, oQuote)}\\${str2.substring(oQuote)}`;
        } else if (stopAtDelimiter && isUnquotedStringDelimiter(text[i])) {
          if (text[i - 1] === ":" && regexUrlStart.test(text.substring(iBefore + 1, i + 2))) {
            while (i < text.length && regexUrlChar.test(text[i])) {
              str2 += text[i];
              i++;
            }
          }
          str2 = insertBeforeLastWhitespace(str2, '"');
          output += str2;
          parseConcatenatedString();
          return true;
        } else if (text[i] === "\\") {
          const char = text.charAt(i + 1);
          const escapeChar = escapeCharacters[char];
          if (escapeChar !== void 0) {
            str2 += text.slice(i, i + 2);
            i += 2;
          } else if (char === "u") {
            let j = 2;
            while (j < 6 && isHex(text[i + j])) {
              j++;
            }
            if (j === 6) {
              str2 += text.slice(i, i + 6);
              i += 6;
            } else if (i + j >= text.length) {
              i = text.length;
            } else {
              throwInvalidUnicodeCharacter();
            }
          } else {
            str2 += char;
            i += 2;
          }
        } else {
          const char = text.charAt(i);
          if (char === '"' && text[i - 1] !== "\\") {
            str2 += `\\${char}`;
            i++;
          } else if (isControlCharacter(char)) {
            str2 += controlCharacters[char];
            i++;
          } else {
            if (!isValidStringCharacter(char)) {
              throwInvalidCharacter(char);
            }
            str2 += char;
            i++;
          }
        }
        if (skipEscapeChars) {
          skipEscapeCharacter();
        }
      }
    }
    return false;
  }
  __name(parseString, "parseString");
  function parseConcatenatedString() {
    let processed2 = false;
    parseWhitespaceAndSkipComments();
    while (text[i] === "+") {
      processed2 = true;
      i++;
      parseWhitespaceAndSkipComments();
      output = stripLastOccurrence(output, '"', true);
      const start = output.length;
      const parsedStr = parseString();
      if (parsedStr) {
        output = removeAtIndex(output, start, 1);
      } else {
        output = insertBeforeLastWhitespace(output, '"');
      }
    }
    return processed2;
  }
  __name(parseConcatenatedString, "parseConcatenatedString");
  function parseNumber() {
    const start = i;
    if (text[i] === "-") {
      i++;
      if (atEndOfNumber()) {
        repairNumberEndingWithNumericSymbol(start);
        return true;
      }
      if (!isDigit2(text[i])) {
        i = start;
        return false;
      }
    }
    while (isDigit2(text[i])) {
      i++;
    }
    if (text[i] === ".") {
      i++;
      if (atEndOfNumber()) {
        repairNumberEndingWithNumericSymbol(start);
        return true;
      }
      if (!isDigit2(text[i])) {
        i = start;
        return false;
      }
      while (isDigit2(text[i])) {
        i++;
      }
    }
    if (text[i] === "e" || text[i] === "E") {
      i++;
      if (text[i] === "-" || text[i] === "+") {
        i++;
      }
      if (atEndOfNumber()) {
        repairNumberEndingWithNumericSymbol(start);
        return true;
      }
      if (!isDigit2(text[i])) {
        i = start;
        return false;
      }
      while (isDigit2(text[i])) {
        i++;
      }
    }
    if (!atEndOfNumber()) {
      i = start;
      return false;
    }
    if (i > start) {
      const num = text.slice(start, i);
      const hasInvalidLeadingZero = /^0\d/.test(num);
      output += hasInvalidLeadingZero ? `"${num}"` : num;
      return true;
    }
    return false;
  }
  __name(parseNumber, "parseNumber");
  function parseKeywords() {
    return parseKeyword("true", "true") || parseKeyword("false", "false") || parseKeyword("null", "null") || // repair Python keywords True, False, None
    parseKeyword("True", "true") || parseKeyword("False", "false") || parseKeyword("None", "null");
  }
  __name(parseKeywords, "parseKeywords");
  function parseKeyword(name3, value) {
    if (text.slice(i, i + name3.length) === name3) {
      output += value;
      i += name3.length;
      return true;
    }
    return false;
  }
  __name(parseKeyword, "parseKeyword");
  function parseUnquotedString(isKey) {
    const start = i;
    if (isFunctionNameCharStart(text[i])) {
      while (i < text.length && isFunctionNameChar(text[i])) {
        i++;
      }
      let j = i;
      while (isWhitespace(text, j)) {
        j++;
      }
      if (text[j] === "(") {
        i = j + 1;
        parseValue2();
        if (text[i] === ")") {
          i++;
          if (text[i] === ";") {
            i++;
          }
        }
        return true;
      }
    }
    while (i < text.length && !isUnquotedStringDelimiter(text[i]) && !isQuote(text[i]) && (!isKey || text[i] !== ":")) {
      i++;
    }
    if (text[i - 1] === ":" && regexUrlStart.test(text.substring(start, i + 2))) {
      while (i < text.length && regexUrlChar.test(text[i])) {
        i++;
      }
    }
    if (i > start) {
      while (isWhitespace(text, i - 1) && i > 0) {
        i--;
      }
      const symbol = text.slice(start, i);
      output += symbol === "undefined" ? "null" : JSON.stringify(symbol);
      if (text[i] === '"') {
        i++;
      }
      return true;
    }
  }
  __name(parseUnquotedString, "parseUnquotedString");
  function parseRegex() {
    if (text[i] === "/") {
      const start = i;
      i++;
      while (i < text.length && (text[i] !== "/" || text[i - 1] === "\\")) {
        i++;
      }
      i++;
      output += `"${text.substring(start, i)}"`;
      return true;
    }
  }
  __name(parseRegex, "parseRegex");
  function prevNonWhitespaceIndex(start) {
    let prev = start;
    while (prev > 0 && isWhitespace(text, prev)) {
      prev--;
    }
    return prev;
  }
  __name(prevNonWhitespaceIndex, "prevNonWhitespaceIndex");
  function atEndOfNumber() {
    return i >= text.length || isDelimiter(text[i]) || isWhitespace(text, i);
  }
  __name(atEndOfNumber, "atEndOfNumber");
  function repairNumberEndingWithNumericSymbol(start) {
    output += `${text.slice(start, i)}0`;
  }
  __name(repairNumberEndingWithNumericSymbol, "repairNumberEndingWithNumericSymbol");
  function throwInvalidCharacter(char) {
    throw new JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i);
  }
  __name(throwInvalidCharacter, "throwInvalidCharacter");
  function throwUnexpectedCharacter() {
    throw new JSONRepairError(`Unexpected character ${JSON.stringify(text[i])}`, i);
  }
  __name(throwUnexpectedCharacter, "throwUnexpectedCharacter");
  function throwUnexpectedEnd() {
    throw new JSONRepairError("Unexpected end of json string", text.length);
  }
  __name(throwUnexpectedEnd, "throwUnexpectedEnd");
  function throwObjectKeyExpected() {
    throw new JSONRepairError("Object key expected", i);
  }
  __name(throwObjectKeyExpected, "throwObjectKeyExpected");
  function throwColonExpected() {
    throw new JSONRepairError("Colon expected", i);
  }
  __name(throwColonExpected, "throwColonExpected");
  function throwInvalidUnicodeCharacter() {
    const chars = text.slice(i, i + 6);
    throw new JSONRepairError(`Invalid unicode character "${chars}"`, i);
  }
  __name(throwInvalidUnicodeCharacter, "throwInvalidUnicodeCharacter");
}
function atEndOfBlockComment(text, i) {
  return text[i] === "*" && text[i + 1] === "/";
}
var controlCharacters, escapeCharacters;
var init_jsonrepair = __esm({
  "node_modules/jsonrepair/lib/esm/regular/jsonrepair.js"() {
    init_esbuild_shims();
    init_JSONRepairError();
    init_stringUtils();
    controlCharacters = {
      "\b": "\\b",
      "\f": "\\f",
      "\n": "\\n",
      "\r": "\\r",
      "	": "\\t"
    };
    escapeCharacters = {
      '"': '"',
      "\\": "\\",
      "/": "/",
      b: "\b",
      f: "\f",
      n: "\n",
      r: "\r",
      t: "	"
      // note that \u is handled separately in parseString()
    };
    __name(jsonrepair, "jsonrepair");
    __name(atEndOfBlockComment, "atEndOfBlockComment");
  }
});

// node_modules/jsonrepair/lib/esm/index.js
var init_esm4 = __esm({
  "node_modules/jsonrepair/lib/esm/index.js"() {
    init_esbuild_shims();
    init_jsonrepair();
  }
});

// packages/core/dist/src/utils/safeJsonParse.js
function safeJsonParse(jsonString, fallbackValue = {}) {
  if (!jsonString || typeof jsonString !== "string") {
    return fallbackValue;
  }
  try {
    return JSON.parse(jsonString);
  } catch (error) {
    try {
      const repairedJson = jsonrepair(jsonString);
      return JSON.parse(repairedJson);
    } catch (repairError) {
      console.error("Failed to parse JSON even with jsonrepair:", {
        originalError: error,
        repairError,
        jsonString
      });
      return fallbackValue;
    }
  }
}
var init_safeJsonParse = __esm({
  "packages/core/dist/src/utils/safeJsonParse.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm4();
    __name(safeJsonParse, "safeJsonParse");
  }
});

// packages/core/dist/src/core/openaiContentGenerator/streamingToolCallParser.js
var StreamingToolCallParser;
var init_streamingToolCallParser = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/streamingToolCallParser.js"() {
    "use strict";
    init_esbuild_shims();
    init_safeJsonParse();
    StreamingToolCallParser = class {
      static {
        __name(this, "StreamingToolCallParser");
      }
      /** Accumulated buffer containing all received chunks for each tool call index */
      buffers = /* @__PURE__ */ new Map();
      /** Current nesting depth in JSON structure for each tool call index */
      depths = /* @__PURE__ */ new Map();
      /** Whether we're currently inside a string literal for each tool call index */
      inStrings = /* @__PURE__ */ new Map();
      /** Whether the next character should be treated as escaped for each tool call index */
      escapes = /* @__PURE__ */ new Map();
      /** Metadata for each tool call index */
      toolCallMeta = /* @__PURE__ */ new Map();
      /** Map from tool call ID to actual index used for storage */
      idToIndexMap = /* @__PURE__ */ new Map();
      /** Counter for generating new indices when collisions occur */
      nextAvailableIndex = 0;
      /**
       * Processes a new chunk of tool call data and attempts to parse complete JSON objects
       *
       * Handles the core problems of streaming tool call parsing:
       * - Resolves index collisions when the same index is reused for different tool calls
       * - Routes chunks without IDs to the correct incomplete tool call
       * - Tracks JSON parsing state (depth, string boundaries, escapes) per tool call
       * - Attempts parsing only when JSON structure is complete (depth = 0)
       * - Repairs common issues like unclosed strings
       *
       * @param index - Tool call index from streaming response (may collide with existing calls)
       * @param chunk - String chunk that may be empty, partial JSON, or complete data
       * @param id - Optional tool call ID for collision detection and chunk routing
       * @param name - Optional function name stored as metadata
       * @returns ToolCallParseResult with completion status, parsed value, and repair info
       */
      addChunk(index, chunk, id, name3) {
        let actualIndex = index;
        if (id) {
          if (this.idToIndexMap.has(id)) {
            actualIndex = this.idToIndexMap.get(id);
          } else {
            if (this.buffers.has(index)) {
              const existingBuffer = this.buffers.get(index);
              const existingDepth = this.depths.get(index);
              const existingMeta = this.toolCallMeta.get(index);
              if (existingBuffer.trim() && existingDepth === 0 && existingMeta?.id && existingMeta.id !== id) {
                try {
                  JSON.parse(existingBuffer);
                  actualIndex = this.findNextAvailableIndex();
                } catch {
                }
              }
            }
            this.idToIndexMap.set(id, actualIndex);
          }
        } else {
          if (this.buffers.has(index)) {
            const existingBuffer = this.buffers.get(index);
            const existingDepth = this.depths.get(index);
            if (existingDepth > 0 || !existingBuffer.trim()) {
              actualIndex = index;
            } else {
              try {
                JSON.parse(existingBuffer);
                actualIndex = this.findMostRecentIncompleteIndex();
              } catch {
                actualIndex = index;
              }
            }
          }
        }
        if (!this.buffers.has(actualIndex)) {
          this.buffers.set(actualIndex, "");
          this.depths.set(actualIndex, 0);
          this.inStrings.set(actualIndex, false);
          this.escapes.set(actualIndex, false);
          this.toolCallMeta.set(actualIndex, {});
        }
        const meta = this.toolCallMeta.get(actualIndex);
        if (id)
          meta.id = id;
        if (name3)
          meta.name = name3;
        const currentBuffer = this.buffers.get(actualIndex);
        const currentDepth = this.depths.get(actualIndex);
        const currentInString = this.inStrings.get(actualIndex);
        const currentEscape = this.escapes.get(actualIndex);
        const newBuffer = currentBuffer + chunk;
        this.buffers.set(actualIndex, newBuffer);
        let depth = currentDepth;
        let inString = currentInString;
        let escape7 = currentEscape;
        for (const char of chunk) {
          if (!inString) {
            if (char === "{" || char === "[")
              depth++;
            else if (char === "}" || char === "]")
              depth--;
          }
          if (char === '"' && !escape7) {
            inString = !inString;
          }
          escape7 = char === "\\" && !escape7;
        }
        this.depths.set(actualIndex, depth);
        this.inStrings.set(actualIndex, inString);
        this.escapes.set(actualIndex, escape7);
        if (depth === 0 && newBuffer.trim().length > 0) {
          try {
            const parsed = JSON.parse(newBuffer);
            return { complete: true, value: parsed };
          } catch (e2) {
            if (inString) {
              try {
                const repaired = JSON.parse(newBuffer + '"');
                return {
                  complete: true,
                  value: repaired,
                  repaired: true
                };
              } catch {
              }
            }
            return {
              complete: false,
              error: e2 instanceof Error ? e2 : new Error(String(e2))
            };
          }
        }
        return { complete: false };
      }
      /**
       * Gets the current tool call metadata for a specific index
       *
       * @param index - The tool call index
       * @returns Object containing id and name if available
       */
      getToolCallMeta(index) {
        return this.toolCallMeta.get(index) || {};
      }
      /**
       * Gets all completed tool calls that are ready to be emitted
       *
       * Attempts to parse accumulated buffers using multiple strategies:
       * 1. Standard JSON.parse()
       * 2. Auto-close unclosed strings and retry
       * 3. Fallback to safeJsonParse for malformed data
       *
       * Only returns tool calls with both name metadata and non-empty buffers.
       * Should be called when streaming is complete (finish_reason is present).
       *
       * @returns Array of completed tool calls with their metadata and parsed arguments
       */
      getCompletedToolCalls() {
        const completed = [];
        for (const [index, buffer] of this.buffers.entries()) {
          const meta = this.toolCallMeta.get(index);
          if (meta?.name && buffer.trim()) {
            let args = {};
            try {
              args = JSON.parse(buffer);
            } catch {
              const inString = this.inStrings.get(index);
              if (inString) {
                try {
                  args = JSON.parse(buffer + '"');
                } catch {
                  args = safeJsonParse(buffer, {});
                }
              } else {
                args = safeJsonParse(buffer, {});
              }
            }
            completed.push({
              id: meta.id,
              name: meta.name,
              args,
              index
            });
          }
        }
        return completed;
      }
      /**
       * Finds the next available index for a new tool call
       *
       * Scans indices starting from nextAvailableIndex to find one that's safe to use.
       * Reuses indices with empty buffers or incomplete parsing states.
       * Skips indices with complete, parseable tool call data to prevent overwriting.
       *
       * @returns The next available index safe for storing a new tool call
       */
      findNextAvailableIndex() {
        while (this.buffers.has(this.nextAvailableIndex)) {
          const buffer = this.buffers.get(this.nextAvailableIndex);
          const depth = this.depths.get(this.nextAvailableIndex);
          const meta = this.toolCallMeta.get(this.nextAvailableIndex);
          if (!buffer.trim() || depth > 0 || !meta?.id) {
            return this.nextAvailableIndex;
          }
          try {
            JSON.parse(buffer);
            if (depth === 0) {
              this.nextAvailableIndex++;
              continue;
            }
          } catch {
            return this.nextAvailableIndex;
          }
          this.nextAvailableIndex++;
        }
        return this.nextAvailableIndex++;
      }
      /**
       * Finds the most recent incomplete tool call index
       *
       * Used when continuation chunks arrive without IDs. Scans existing tool calls
       * to find the highest index with incomplete parsing state (depth > 0, empty buffer,
       * or unparseable JSON). Falls back to creating a new index if none found.
       *
       * @returns The index of the most recent incomplete tool call, or a new available index
       */
      findMostRecentIncompleteIndex() {
        let maxIndex = -1;
        for (const [index, buffer] of this.buffers.entries()) {
          const depth = this.depths.get(index);
          const meta = this.toolCallMeta.get(index);
          if (meta?.id && (depth > 0 || !buffer.trim())) {
            maxIndex = Math.max(maxIndex, index);
          } else if (buffer.trim()) {
            try {
              JSON.parse(buffer);
            } catch {
              maxIndex = Math.max(maxIndex, index);
            }
          }
        }
        return maxIndex >= 0 ? maxIndex : this.findNextAvailableIndex();
      }
      /**
       * Resets the parser state for a specific tool call index
       *
       * @param index - The tool call index to reset
       */
      resetIndex(index) {
        this.buffers.set(index, "");
        this.depths.set(index, 0);
        this.inStrings.set(index, false);
        this.escapes.set(index, false);
        this.toolCallMeta.set(index, {});
      }
      /**
       * Resets the entire parser state for processing a new stream
       *
       * Clears all accumulated buffers, parsing states, metadata, and counters.
       * Allows the parser to be reused for multiple independent streams without
       * data leakage between sessions.
       */
      reset() {
        this.buffers.clear();
        this.depths.clear();
        this.inStrings.clear();
        this.escapes.clear();
        this.toolCallMeta.clear();
        this.idToIndexMap.clear();
        this.nextAvailableIndex = 0;
      }
      /**
       * Gets the current accumulated buffer content for a specific index
       *
       * @param index - The tool call index to retrieve buffer for
       * @returns The current buffer content for the specified index (empty string if not found)
       */
      getBuffer(index) {
        return this.buffers.get(index) || "";
      }
      /**
       * Gets the current parsing state information for a specific index
       *
       * @param index - The tool call index to get state information for
       * @returns Object containing current parsing state (depth, inString, escape)
       */
      getState(index) {
        return {
          depth: this.depths.get(index) || 0,
          inString: this.inStrings.get(index) || false,
          escape: this.escapes.get(index) || false
        };
      }
    };
  }
});

// packages/core/dist/src/core/openaiContentGenerator/converter.js
var OpenAIContentConverter;
var init_converter2 = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/converter.js"() {
    "use strict";
    init_esbuild_shims();
    init_node();
    init_safeJsonParse();
    init_streamingToolCallParser();
    OpenAIContentConverter = class {
      static {
        __name(this, "OpenAIContentConverter");
      }
      model;
      streamingToolCallParser = new StreamingToolCallParser();
      constructor(model) {
        this.model = model;
      }
      /**
       * Reset streaming tool calls parser for new stream processing
       * This should be called at the beginning of each stream to prevent
       * data pollution from previous incomplete streams
       */
      resetStreamingToolCalls() {
        this.streamingToolCallParser.reset();
      }
      /**
       * Convert Gemini tool parameters to OpenAI JSON Schema format
       */
      convertGeminiToolParametersToOpenAI(parameters) {
        if (!parameters || typeof parameters !== "object") {
          return parameters;
        }
        const converted = JSON.parse(JSON.stringify(parameters));
        const convertTypes = /* @__PURE__ */ __name((obj) => {
          if (typeof obj !== "object" || obj === null) {
            return obj;
          }
          if (Array.isArray(obj)) {
            return obj.map(convertTypes);
          }
          const result = {};
          for (const [key, value] of Object.entries(obj)) {
            if (key === "type" && typeof value === "string") {
              const lowerValue = value.toLowerCase();
              if (lowerValue === "integer") {
                result[key] = "integer";
              } else if (lowerValue === "number") {
                result[key] = "number";
              } else {
                result[key] = lowerValue;
              }
            } else if (key === "minimum" || key === "maximum" || key === "multipleOf") {
              if (typeof value === "string" && !isNaN(Number(value))) {
                result[key] = Number(value);
              } else {
                result[key] = value;
              }
            } else if (key === "minLength" || key === "maxLength" || key === "minItems" || key === "maxItems") {
              if (typeof value === "string" && !isNaN(Number(value))) {
                result[key] = parseInt(value, 10);
              } else {
                result[key] = value;
              }
            } else if (typeof value === "object") {
              result[key] = convertTypes(value);
            } else {
              result[key] = value;
            }
          }
          return result;
        }, "convertTypes");
        return convertTypes(converted);
      }
      /**
       * Convert Gemini tools to OpenAI format for API compatibility.
       * Handles both Gemini tools (using 'parameters' field) and MCP tools (using 'parametersJsonSchema' field).
       */
      async convertGeminiToolsToOpenAI(geminiTools) {
        const openAITools = [];
        for (const tool of geminiTools) {
          let actualTool;
          if ("tool" in tool) {
            actualTool = await tool.tool();
          } else {
            actualTool = tool;
          }
          if (actualTool.functionDeclarations) {
            for (const func of actualTool.functionDeclarations) {
              if (func.name && func.description) {
                let parameters;
                if (func.parametersJsonSchema) {
                  if (func.parametersJsonSchema) {
                    const paramsCopy = {
                      ...func.parametersJsonSchema
                    };
                    parameters = paramsCopy;
                  }
                } else if (func.parameters) {
                  parameters = this.convertGeminiToolParametersToOpenAI(func.parameters);
                }
                openAITools.push({
                  type: "function",
                  function: {
                    name: func.name,
                    description: func.description,
                    parameters
                  }
                });
              }
            }
          }
        }
        return openAITools;
      }
      /**
       * Convert Gemini request to OpenAI message format
       */
      convertGeminiRequestToOpenAI(request4) {
        const messages = [];
        this.addSystemInstructionMessage(request4, messages);
        this.processContents(request4.contents, messages);
        const cleanedMessages = this.cleanOrphanedToolCalls(messages);
        const mergedMessages = this.mergeConsecutiveAssistantMessages(cleanedMessages);
        return mergedMessages;
      }
      /**
       * Extract and add system instruction message from request config
       */
      addSystemInstructionMessage(request4, messages) {
        if (!request4.config?.systemInstruction)
          return;
        const systemText = this.extractTextFromContentUnion(request4.config.systemInstruction);
        if (systemText) {
          messages.push({
            role: "system",
            content: systemText
          });
        }
      }
      /**
       * Process contents and convert to OpenAI messages
       */
      processContents(contents, messages) {
        if (Array.isArray(contents)) {
          for (const content of contents) {
            this.processContent(content, messages);
          }
        } else if (contents) {
          this.processContent(contents, messages);
        }
      }
      /**
       * Process a single content item and convert to OpenAI message(s)
       */
      processContent(content, messages) {
        if (typeof content === "string") {
          messages.push({ role: "user", content });
          return;
        }
        if (!this.isContentObject(content))
          return;
        const parsedParts = this.parseParts(content.parts || []);
        if (parsedParts.functionResponses.length > 0) {
          for (const funcResponse of parsedParts.functionResponses) {
            messages.push({
              role: "tool",
              tool_call_id: funcResponse.id || "",
              content: this.extractFunctionResponseContent(funcResponse.response)
            });
          }
          return;
        }
        if (content.role === "model" && parsedParts.functionCalls.length > 0) {
          const toolCalls = parsedParts.functionCalls.map((fc, index) => ({
            id: fc.id || `call_${index}`,
            type: "function",
            function: {
              name: fc.name || "",
              arguments: JSON.stringify(fc.args || {})
            }
          }));
          messages.push({
            role: "assistant",
            content: parsedParts.textParts.join("") || null,
            tool_calls: toolCalls
          });
          return;
        }
        const role = content.role === "model" ? "assistant" : "user";
        const openAIMessage = this.createMultimodalMessage(role, parsedParts);
        if (openAIMessage) {
          messages.push(openAIMessage);
        }
      }
      /**
       * Parse Gemini parts into categorized components
       */
      parseParts(parts) {
        const textParts = [];
        const functionCalls = [];
        const functionResponses = [];
        const mediaParts = [];
        for (const part of parts) {
          if (typeof part === "string") {
            textParts.push(part);
          } else if ("text" in part && part.text) {
            textParts.push(part.text);
          } else if ("functionCall" in part && part.functionCall) {
            functionCalls.push(part.functionCall);
          } else if ("functionResponse" in part && part.functionResponse) {
            functionResponses.push(part.functionResponse);
          } else if ("inlineData" in part && part.inlineData) {
            const { data, mimeType } = part.inlineData;
            if (data && mimeType) {
              const mediaType = this.getMediaType(mimeType);
              mediaParts.push({ type: mediaType, data, mimeType });
            }
          } else if ("fileData" in part && part.fileData) {
            const { fileUri, mimeType } = part.fileData;
            if (fileUri && mimeType) {
              const mediaType = this.getMediaType(mimeType);
              mediaParts.push({
                type: mediaType,
                data: "",
                mimeType,
                fileUri
              });
            }
          }
        }
        return { textParts, functionCalls, functionResponses, mediaParts };
      }
      extractFunctionResponseContent(response) {
        if (response === null || response === void 0) {
          return "";
        }
        if (typeof response === "string") {
          return response;
        }
        if (typeof response === "object") {
          const responseObject = response;
          const output = responseObject["output"];
          if (typeof output === "string") {
            return output;
          }
          const error = responseObject["error"];
          if (typeof error === "string") {
            return error;
          }
        }
        try {
          const serialized = JSON.stringify(response);
          return serialized ?? String(response);
        } catch {
          return String(response);
        }
      }
      /**
       * Determine media type from MIME type
       */
      getMediaType(mimeType) {
        if (mimeType.startsWith("image/"))
          return "image";
        if (mimeType.startsWith("audio/"))
          return "audio";
        return "file";
      }
      /**
       * Create multimodal OpenAI message from parsed parts
       */
      createMultimodalMessage(role, parsedParts) {
        const { textParts, mediaParts } = parsedParts;
        const content = textParts.map((text) => ({ type: "text", text }));
        if (mediaParts.length === 0) {
          return content.length > 0 ? { role, content } : null;
        }
        if (role === "assistant") {
          return content.length > 0 ? { role: "assistant", content } : null;
        }
        const contentArray = [...content];
        for (const mediaPart of mediaParts) {
          if (mediaPart.type === "image") {
            if (mediaPart.fileUri) {
              contentArray.push({
                type: "image_url",
                image_url: { url: mediaPart.fileUri }
              });
            } else if (mediaPart.data) {
              const dataUrl = `data:${mediaPart.mimeType};base64,${mediaPart.data}`;
              contentArray.push({
                type: "image_url",
                image_url: { url: dataUrl }
              });
            }
          } else if (mediaPart.type === "audio" && mediaPart.data) {
            const format4 = this.getAudioFormat(mediaPart.mimeType);
            if (format4) {
              contentArray.push({
                type: "input_audio",
                input_audio: {
                  data: mediaPart.data,
                  format: format4
                }
              });
            }
          }
        }
        return contentArray.length > 0 ? { role: "user", content: contentArray } : null;
      }
      /**
       * Convert MIME type to OpenAI audio format
       */
      getAudioFormat(mimeType) {
        if (mimeType.includes("wav"))
          return "wav";
        if (mimeType.includes("mp3") || mimeType.includes("mpeg"))
          return "mp3";
        return null;
      }
      /**
       * Type guard to check if content is a valid Content object
       */
      isContentObject(content) {
        return typeof content === "object" && content !== null && "role" in content && "parts" in content && Array.isArray(content["parts"]);
      }
      /**
       * Extract text content from various Gemini content union types
       */
      extractTextFromContentUnion(contentUnion) {
        if (typeof contentUnion === "string") {
          return contentUnion;
        }
        if (Array.isArray(contentUnion)) {
          return contentUnion.map((item) => this.extractTextFromContentUnion(item)).filter(Boolean).join("\n");
        }
        if (typeof contentUnion === "object" && contentUnion !== null) {
          if ("parts" in contentUnion) {
            const content = contentUnion;
            return content.parts?.map((part) => {
              if (typeof part === "string")
                return part;
              if ("text" in part)
                return part.text || "";
              return "";
            }).filter(Boolean).join("\n") || "";
          }
        }
        return "";
      }
      /**
       * Convert OpenAI response to Gemini format
       */
      convertOpenAIResponseToGemini(openaiResponse) {
        const choice2 = openaiResponse.choices[0];
        const response = new GenerateContentResponse();
        const parts = [];
        if (choice2.message.content) {
          parts.push({ text: choice2.message.content });
        }
        if (choice2.message.tool_calls) {
          for (const toolCall of choice2.message.tool_calls) {
            if (toolCall.function) {
              let args = {};
              if (toolCall.function.arguments) {
                args = safeJsonParse(toolCall.function.arguments, {});
              }
              parts.push({
                functionCall: {
                  id: toolCall.id,
                  name: toolCall.function.name,
                  args
                }
              });
            }
          }
        }
        response.responseId = openaiResponse.id;
        response.createTime = openaiResponse.created ? openaiResponse.created.toString() : (/* @__PURE__ */ new Date()).getTime().toString();
        response.candidates = [
          {
            content: {
              parts,
              role: "model"
            },
            finishReason: this.mapOpenAIFinishReasonToGemini(choice2.finish_reason || "stop"),
            index: 0,
            safetyRatings: []
          }
        ];
        response.modelVersion = this.model;
        response.promptFeedback = { safetyRatings: [] };
        if (openaiResponse.usage) {
          const usage2 = openaiResponse.usage;
          const promptTokens = usage2.prompt_tokens || 0;
          const completionTokens = usage2.completion_tokens || 0;
          const totalTokens = usage2.total_tokens || 0;
          const extendedUsage = usage2;
          const cachedTokens = usage2.prompt_tokens_details?.cached_tokens ?? extendedUsage.cached_tokens ?? 0;
          let finalPromptTokens = promptTokens;
          let finalCompletionTokens = completionTokens;
          if (totalTokens > 0 && promptTokens === 0 && completionTokens === 0) {
            finalPromptTokens = Math.round(totalTokens * 0.7);
            finalCompletionTokens = Math.round(totalTokens * 0.3);
          }
          response.usageMetadata = {
            promptTokenCount: finalPromptTokens,
            candidatesTokenCount: finalCompletionTokens,
            totalTokenCount: totalTokens,
            cachedContentTokenCount: cachedTokens
          };
        }
        return response;
      }
      /**
       * Convert OpenAI stream chunk to Gemini format
       */
      convertOpenAIChunkToGemini(chunk) {
        const choice2 = chunk.choices?.[0];
        const response = new GenerateContentResponse();
        if (choice2) {
          const parts = [];
          if (choice2.delta?.content) {
            if (typeof choice2.delta.content === "string") {
              parts.push({ text: choice2.delta.content });
            }
          }
          if (choice2.delta?.tool_calls) {
            for (const toolCall of choice2.delta.tool_calls) {
              const index = toolCall.index ?? 0;
              if (toolCall.function?.arguments) {
                this.streamingToolCallParser.addChunk(index, toolCall.function.arguments, toolCall.id, toolCall.function.name);
              } else {
                this.streamingToolCallParser.addChunk(
                  index,
                  "",
                  // Empty chunk for metadata-only updates
                  toolCall.id,
                  toolCall.function?.name
                );
              }
            }
          }
          if (choice2.finish_reason) {
            const completedToolCalls = this.streamingToolCallParser.getCompletedToolCalls();
            for (const toolCall of completedToolCalls) {
              if (toolCall.name) {
                parts.push({
                  functionCall: {
                    id: toolCall.id || `call_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
                    name: toolCall.name,
                    args: toolCall.args
                  }
                });
              }
            }
            this.streamingToolCallParser.reset();
          }
          const candidate = {
            content: {
              parts,
              role: "model"
            },
            index: 0,
            safetyRatings: []
          };
          if (choice2.finish_reason) {
            candidate.finishReason = this.mapOpenAIFinishReasonToGemini(choice2.finish_reason);
          }
          response.candidates = [candidate];
        } else {
          response.candidates = [];
        }
        response.responseId = chunk.id;
        response.createTime = chunk.created ? chunk.created.toString() : (/* @__PURE__ */ new Date()).getTime().toString();
        response.modelVersion = this.model;
        response.promptFeedback = { safetyRatings: [] };
        if (chunk.usage) {
          const usage2 = chunk.usage;
          const promptTokens = usage2.prompt_tokens || 0;
          const completionTokens = usage2.completion_tokens || 0;
          const totalTokens = usage2.total_tokens || 0;
          const extendedUsage = usage2;
          const cachedTokens = usage2.prompt_tokens_details?.cached_tokens ?? extendedUsage.cached_tokens ?? 0;
          let finalPromptTokens = promptTokens;
          let finalCompletionTokens = completionTokens;
          if (totalTokens > 0 && promptTokens === 0 && completionTokens === 0) {
            finalPromptTokens = Math.round(totalTokens * 0.7);
            finalCompletionTokens = Math.round(totalTokens * 0.3);
          }
          response.usageMetadata = {
            promptTokenCount: finalPromptTokens,
            candidatesTokenCount: finalCompletionTokens,
            totalTokenCount: totalTokens,
            cachedContentTokenCount: cachedTokens
          };
        }
        return response;
      }
      /**
       * Convert Gemini response format to OpenAI chat completion format for logging
       */
      convertGeminiResponseToOpenAI(response) {
        const candidate = response.candidates?.[0];
        const content = candidate?.content;
        let messageContent = null;
        const toolCalls = [];
        if (content?.parts) {
          const textParts = [];
          for (const part of content.parts) {
            if ("text" in part && part.text) {
              textParts.push(part.text);
            } else if ("functionCall" in part && part.functionCall) {
              toolCalls.push({
                id: part.functionCall.id || `call_${toolCalls.length}`,
                type: "function",
                function: {
                  name: part.functionCall.name || "",
                  arguments: JSON.stringify(part.functionCall.args || {})
                }
              });
            }
          }
          messageContent = textParts.join("").trimEnd();
        }
        const choice2 = {
          index: 0,
          message: {
            role: "assistant",
            content: messageContent,
            refusal: null
          },
          finish_reason: this.mapGeminiFinishReasonToOpenAI(candidate?.finishReason),
          logprobs: null
        };
        if (toolCalls.length > 0) {
          choice2.message.tool_calls = toolCalls;
        }
        const openaiResponse = {
          id: response.responseId || `chatcmpl-${Date.now()}`,
          object: "chat.completion",
          created: response.createTime ? Number(response.createTime) : Math.floor(Date.now() / 1e3),
          model: this.model,
          choices: [choice2]
        };
        if (response.usageMetadata) {
          openaiResponse.usage = {
            prompt_tokens: response.usageMetadata.promptTokenCount || 0,
            completion_tokens: response.usageMetadata.candidatesTokenCount || 0,
            total_tokens: response.usageMetadata.totalTokenCount || 0
          };
          if (response.usageMetadata.cachedContentTokenCount) {
            openaiResponse.usage.prompt_tokens_details = {
              cached_tokens: response.usageMetadata.cachedContentTokenCount
            };
          }
        }
        return openaiResponse;
      }
      /**
       * Map OpenAI finish reasons to Gemini finish reasons
       */
      mapOpenAIFinishReasonToGemini(openaiReason) {
        if (!openaiReason)
          return FinishReason.FINISH_REASON_UNSPECIFIED;
        const mapping = {
          stop: FinishReason.STOP,
          length: FinishReason.MAX_TOKENS,
          content_filter: FinishReason.SAFETY,
          function_call: FinishReason.STOP,
          tool_calls: FinishReason.STOP
        };
        return mapping[openaiReason] || FinishReason.FINISH_REASON_UNSPECIFIED;
      }
      /**
       * Map Gemini finish reasons to OpenAI finish reasons
       */
      mapGeminiFinishReasonToOpenAI(geminiReason) {
        if (!geminiReason)
          return "stop";
        switch (geminiReason) {
          case "STOP":
          case 1:
            return "stop";
          case "MAX_TOKENS":
          case 2:
            return "length";
          case "SAFETY":
          case 3:
            return "content_filter";
          case "RECITATION":
          case 4:
            return "content_filter";
          case "OTHER":
          case 5:
            return "stop";
          default:
            return "stop";
        }
      }
      /**
       * Clean up orphaned tool calls from message history to prevent OpenAI API errors
       */
      cleanOrphanedToolCalls(messages) {
        const cleaned = [];
        const toolCallIds = /* @__PURE__ */ new Set();
        const toolResponseIds = /* @__PURE__ */ new Set();
        for (const message of messages) {
          if (message.role === "assistant" && "tool_calls" in message && message.tool_calls) {
            for (const toolCall of message.tool_calls) {
              if (toolCall.id) {
                toolCallIds.add(toolCall.id);
              }
            }
          } else if (message.role === "tool" && "tool_call_id" in message && message.tool_call_id) {
            toolResponseIds.add(message.tool_call_id);
          }
        }
        for (const message of messages) {
          if (message.role === "assistant" && "tool_calls" in message && message.tool_calls) {
            const validToolCalls = message.tool_calls.filter((toolCall) => toolCall.id && toolResponseIds.has(toolCall.id));
            if (validToolCalls.length > 0) {
              const cleanedMessage = { ...message };
              cleanedMessage.tool_calls = validToolCalls;
              cleaned.push(cleanedMessage);
            } else if (typeof message.content === "string" && message.content.trim()) {
              const cleanedMessage = { ...message };
              delete cleanedMessage.tool_calls;
              cleaned.push(cleanedMessage);
            }
          } else if (message.role === "tool" && "tool_call_id" in message && message.tool_call_id) {
            if (toolCallIds.has(message.tool_call_id)) {
              cleaned.push(message);
            }
          } else {
            cleaned.push(message);
          }
        }
        const finalCleaned = [];
        const finalToolCallIds = /* @__PURE__ */ new Set();
        for (const message of cleaned) {
          if (message.role === "assistant" && "tool_calls" in message && message.tool_calls) {
            for (const toolCall of message.tool_calls) {
              if (toolCall.id) {
                finalToolCallIds.add(toolCall.id);
              }
            }
          }
        }
        const finalToolResponseIds = /* @__PURE__ */ new Set();
        for (const message of cleaned) {
          if (message.role === "tool" && "tool_call_id" in message && message.tool_call_id) {
            finalToolResponseIds.add(message.tool_call_id);
          }
        }
        for (const message of cleaned) {
          if (message.role === "assistant" && "tool_calls" in message && message.tool_calls) {
            const finalValidToolCalls = message.tool_calls.filter((toolCall) => toolCall.id && finalToolResponseIds.has(toolCall.id));
            if (finalValidToolCalls.length > 0) {
              const cleanedMessage = { ...message };
              cleanedMessage.tool_calls = finalValidToolCalls;
              finalCleaned.push(cleanedMessage);
            } else if (typeof message.content === "string" && message.content.trim()) {
              const cleanedMessage = { ...message };
              delete cleanedMessage.tool_calls;
              finalCleaned.push(cleanedMessage);
            }
          } else {
            finalCleaned.push(message);
          }
        }
        return finalCleaned;
      }
      /**
       * Merge consecutive assistant messages to combine split text and tool calls
       */
      mergeConsecutiveAssistantMessages(messages) {
        const merged = [];
        for (const message of messages) {
          if (message.role === "assistant" && merged.length > 0) {
            const lastMessage = merged[merged.length - 1];
            if (lastMessage.role === "assistant") {
              const combinedContent = [
                typeof lastMessage.content === "string" ? lastMessage.content : "",
                typeof message.content === "string" ? message.content : ""
              ].filter(Boolean).join("");
              const lastToolCalls = "tool_calls" in lastMessage ? lastMessage.tool_calls || [] : [];
              const currentToolCalls = "tool_calls" in message ? message.tool_calls || [] : [];
              const combinedToolCalls = [...lastToolCalls, ...currentToolCalls];
              lastMessage.content = combinedContent || null;
              if (combinedToolCalls.length > 0) {
                lastMessage.tool_calls = combinedToolCalls;
              }
              continue;
            }
          }
          merged.push(message);
        }
        return merged;
      }
    };
  }
});

// packages/core/dist/src/core/openaiContentGenerator/pipeline.js
var ContentGenerationPipeline;
var init_pipeline = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/pipeline.js"() {
    "use strict";
    init_esbuild_shims();
    init_node();
    init_converter2();
    ContentGenerationPipeline = class {
      static {
        __name(this, "ContentGenerationPipeline");
      }
      config;
      client;
      converter;
      contentGeneratorConfig;
      constructor(config) {
        this.config = config;
        this.contentGeneratorConfig = config.contentGeneratorConfig;
        this.client = this.config.provider.buildClient();
        this.converter = new OpenAIContentConverter(this.contentGeneratorConfig.model);
      }
      async execute(request4, userPromptId) {
        return this.executeWithErrorHandling(request4, userPromptId, false, async (openaiRequest, context2) => {
          const openaiResponse = await this.client.chat.completions.create(openaiRequest, {
            signal: request4.config?.abortSignal
          });
          const geminiResponse = this.converter.convertOpenAIResponseToGemini(openaiResponse);
          await this.config.telemetryService.logSuccess(context2, geminiResponse, openaiRequest, openaiResponse);
          return geminiResponse;
        });
      }
      async executeStream(request4, userPromptId) {
        return this.executeWithErrorHandling(request4, userPromptId, true, async (openaiRequest, context2) => {
          const stream2 = await this.client.chat.completions.create(openaiRequest, {
            signal: request4.config?.abortSignal
          });
          return this.processStreamWithLogging(stream2, context2, openaiRequest, request4);
        });
      }
      /**
       * Stage 2: Process OpenAI stream with conversion and logging
       * This method handles the complete stream processing pipeline:
       * 1. Convert OpenAI chunks to Gemini format while preserving original chunks
       * 2. Filter empty responses
       * 3. Handle chunk merging for providers that send finishReason and usageMetadata separately
       * 4. Collect both formats for logging
       * 5. Handle success/error logging
       */
      async *processStreamWithLogging(stream2, context2, openaiRequest, request4) {
        const collectedGeminiResponses = [];
        const collectedOpenAIChunks = [];
        this.converter.resetStreamingToolCalls();
        let pendingFinishResponse = null;
        try {
          for await (const chunk of stream2) {
            collectedOpenAIChunks.push(chunk);
            const response = this.converter.convertOpenAIChunkToGemini(chunk);
            if (response.candidates?.[0]?.content?.parts?.length === 0 && !response.candidates?.[0]?.finishReason && !response.usageMetadata) {
              continue;
            }
            const shouldYield = this.handleChunkMerging(response, collectedGeminiResponses, (mergedResponse) => {
              pendingFinishResponse = mergedResponse;
            });
            if (shouldYield) {
              if (pendingFinishResponse) {
                yield pendingFinishResponse;
                pendingFinishResponse = null;
              } else {
                yield response;
              }
            }
          }
          if (pendingFinishResponse) {
            yield pendingFinishResponse;
          }
          context2.duration = Date.now() - context2.startTime;
          await this.config.telemetryService.logStreamingSuccess(context2, collectedGeminiResponses, openaiRequest, collectedOpenAIChunks);
        } catch (error) {
          this.converter.resetStreamingToolCalls();
          await this.handleError(error, context2, request4);
        }
      }
      /**
       * Handle chunk merging for providers that send finishReason and usageMetadata separately.
       *
       * Strategy: When we encounter a finishReason chunk, we hold it and merge all subsequent
       * chunks into it until the stream ends. This ensures the final chunk contains both
       * finishReason and the most up-to-date usage information from any provider pattern.
       *
       * @param response Current Gemini response
       * @param collectedGeminiResponses Array to collect responses for logging
       * @param setPendingFinish Callback to set pending finish response
       * @returns true if the response should be yielded, false if it should be held for merging
       */
      handleChunkMerging(response, collectedGeminiResponses, setPendingFinish) {
        const isFinishChunk = response.candidates?.[0]?.finishReason;
        const hasPendingFinish = collectedGeminiResponses.length > 0 && collectedGeminiResponses[collectedGeminiResponses.length - 1].candidates?.[0]?.finishReason;
        if (isFinishChunk) {
          collectedGeminiResponses.push(response);
          setPendingFinish(response);
          return false;
        } else if (hasPendingFinish) {
          const lastResponse = collectedGeminiResponses[collectedGeminiResponses.length - 1];
          const mergedResponse = new GenerateContentResponse();
          mergedResponse.candidates = lastResponse.candidates;
          if (response.usageMetadata) {
            mergedResponse.usageMetadata = response.usageMetadata;
          } else {
            mergedResponse.usageMetadata = lastResponse.usageMetadata;
          }
          mergedResponse.responseId = response.responseId;
          mergedResponse.createTime = response.createTime;
          mergedResponse.modelVersion = response.modelVersion;
          mergedResponse.promptFeedback = response.promptFeedback;
          collectedGeminiResponses[collectedGeminiResponses.length - 1] = mergedResponse;
          setPendingFinish(mergedResponse);
          return true;
        }
        collectedGeminiResponses.push(response);
        return true;
      }
      async buildRequest(request4, userPromptId, streaming = false) {
        const messages = this.converter.convertGeminiRequestToOpenAI(request4);
        const baseRequest = {
          model: this.contentGeneratorConfig.model,
          messages,
          ...this.buildSamplingParameters(request4)
        };
        if (streaming) {
          baseRequest.stream = true;
          baseRequest.stream_options = { include_usage: true };
        }
        if (request4.config?.tools) {
          baseRequest.tools = await this.converter.convertGeminiToolsToOpenAI(request4.config.tools);
        }
        return this.config.provider.buildRequest(baseRequest, userPromptId);
      }
      buildSamplingParameters(request4) {
        const configSamplingParams = this.contentGeneratorConfig.samplingParams;
        const getParameterValue = /* @__PURE__ */ __name((configKey, requestKey, defaultValue) => {
          const configValue = configSamplingParams?.[configKey];
          const requestValue = request4.config?.[requestKey];
          if (configValue !== void 0)
            return configValue;
          if (requestValue !== void 0)
            return requestValue;
          return defaultValue;
        }, "getParameterValue");
        const addParameterIfDefined = /* @__PURE__ */ __name((key, configKey, requestKey, defaultValue) => {
          const value = requestKey ? getParameterValue(configKey, requestKey, defaultValue) : configSamplingParams?.[configKey] ?? defaultValue;
          return value !== void 0 ? { [key]: value } : {};
        }, "addParameterIfDefined");
        const params = {
          // Parameters with request fallback but no defaults
          ...addParameterIfDefined("temperature", "temperature", "temperature"),
          ...addParameterIfDefined("top_p", "top_p", "topP"),
          // Max tokens (special case: different property names)
          ...addParameterIfDefined("max_tokens", "max_tokens", "maxOutputTokens"),
          // Config-only parameters (no request fallback)
          ...addParameterIfDefined("top_k", "top_k"),
          ...addParameterIfDefined("repetition_penalty", "repetition_penalty"),
          ...addParameterIfDefined("presence_penalty", "presence_penalty"),
          ...addParameterIfDefined("frequency_penalty", "frequency_penalty")
        };
        return params;
      }
      /**
       * Common error handling wrapper for execute methods
       */
      async executeWithErrorHandling(request4, userPromptId, isStreaming, executor) {
        const context2 = this.createRequestContext(userPromptId, isStreaming);
        try {
          const openaiRequest = await this.buildRequest(request4, userPromptId, isStreaming);
          const result = await executor(openaiRequest, context2);
          context2.duration = Date.now() - context2.startTime;
          return result;
        } catch (error) {
          return await this.handleError(error, context2, request4, userPromptId, isStreaming);
        }
      }
      /**
       * Shared error handling logic for both executeWithErrorHandling and processStreamWithLogging
       * This centralizes the common error processing steps to avoid duplication
       */
      async handleError(error, context2, request4, userPromptId, isStreaming) {
        context2.duration = Date.now() - context2.startTime;
        let openaiRequest;
        try {
          if (userPromptId !== void 0 && isStreaming !== void 0) {
            openaiRequest = await this.buildRequest(request4, userPromptId, isStreaming);
          } else {
            openaiRequest = {
              model: this.contentGeneratorConfig.model,
              messages: []
            };
          }
        } catch (_buildError) {
          openaiRequest = {
            model: this.contentGeneratorConfig.model,
            messages: []
          };
        }
        await this.config.telemetryService.logError(context2, error, openaiRequest);
        this.config.errorHandler.handle(error, context2, request4);
      }
      /**
       * Create request context with common properties
       */
      createRequestContext(userPromptId, isStreaming) {
        return {
          userPromptId,
          model: this.contentGeneratorConfig.model,
          authType: this.contentGeneratorConfig.authType || "unknown",
          startTime: Date.now(),
          duration: 0,
          isStreaming
        };
      }
    };
  }
});

// packages/core/dist/src/utils/openaiLogger.js
import * as path12 from "node:path";
import { promises as fs16 } from "node:fs";
import * as os10 from "os";
var OpenAILogger, openaiLogger;
var init_openaiLogger = __esm({
  "packages/core/dist/src/utils/openaiLogger.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm_node();
    OpenAILogger = class {
      static {
        __name(this, "OpenAILogger");
      }
      logDir;
      initialized = false;
      /**
       * Creates a new OpenAI logger
       * @param customLogDir Optional custom log directory path (supports relative paths, absolute paths, and ~ expansion)
       */
      constructor(customLogDir) {
        if (customLogDir) {
          let resolvedPath = customLogDir;
          if (customLogDir === "~" || customLogDir.startsWith("~/")) {
            resolvedPath = path12.join(os10.homedir(), customLogDir.slice(1));
          } else if (!path12.isAbsolute(customLogDir)) {
            resolvedPath = path12.resolve(process.cwd(), customLogDir);
          }
          this.logDir = path12.normalize(resolvedPath);
        } else {
          this.logDir = path12.join(process.cwd(), "logs", "openai");
        }
      }
      /**
       * Initialize the logger by creating the log directory if it doesn't exist
       */
      async initialize() {
        if (this.initialized)
          return;
        try {
          await fs16.mkdir(this.logDir, { recursive: true });
          this.initialized = true;
        } catch (error) {
          console.error("Failed to initialize OpenAI logger:", error);
          throw new Error(`Failed to initialize OpenAI logger: ${error}`);
        }
      }
      /**
       * Logs an OpenAI API request and its response
       * @param request The request sent to OpenAI
       * @param response The response received from OpenAI
       * @param error Optional error if the request failed
       * @returns The file path where the log was written
       */
      async logInteraction(request4, response, error) {
        if (!this.initialized) {
          await this.initialize();
        }
        const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-");
        const id = v4_default().slice(0, 8);
        const filename = `openai-${timestamp}-${id}.json`;
        const filePath = path12.join(this.logDir, filename);
        const logData = {
          timestamp: (/* @__PURE__ */ new Date()).toISOString(),
          request: request4,
          response: response || null,
          error: error ? {
            message: error.message,
            stack: error.stack
          } : null,
          system: {
            hostname: os10.hostname(),
            platform: os10.platform(),
            release: os10.release(),
            nodeVersion: process.version
          }
        };
        try {
          await fs16.writeFile(filePath, JSON.stringify(logData, null, 2), "utf-8");
          return filePath;
        } catch (writeError) {
          console.error("Failed to write OpenAI log file:", writeError);
          throw new Error(`Failed to write OpenAI log file: ${writeError}`);
        }
      }
      /**
       * Get all logged interactions
       * @param limit Optional limit on the number of log files to return (sorted by most recent first)
       * @returns Array of log file paths
       */
      async getLogFiles(limit2) {
        if (!this.initialized) {
          await this.initialize();
        }
        try {
          const files = await fs16.readdir(this.logDir);
          const logFiles = files.filter((file) => file.startsWith("openai-") && file.endsWith(".json")).map((file) => path12.join(this.logDir, file)).sort().reverse();
          return limit2 ? logFiles.slice(0, limit2) : logFiles;
        } catch (error) {
          if (error.code === "ENOENT") {
            return [];
          }
          console.error("Failed to read OpenAI log directory:", error);
          return [];
        }
      }
      /**
       * Read a specific log file
       * @param filePath The path to the log file
       * @returns The log file content
       */
      async readLogFile(filePath) {
        try {
          const content = await fs16.readFile(filePath, "utf-8");
          return JSON.parse(content);
        } catch (error) {
          console.error(`Failed to read log file ${filePath}:`, error);
          throw new Error(`Failed to read log file: ${error}`);
        }
      }
    };
    openaiLogger = new OpenAILogger();
  }
});

// packages/core/dist/src/core/openaiContentGenerator/telemetryService.js
var DefaultTelemetryService;
var init_telemetryService = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/telemetryService.js"() {
    "use strict";
    init_esbuild_shims();
    init_loggers();
    init_types3();
    init_openaiLogger();
    DefaultTelemetryService = class {
      static {
        __name(this, "DefaultTelemetryService");
      }
      config;
      enableOpenAILogging;
      logger;
      constructor(config, enableOpenAILogging = false, openAILoggingDir) {
        this.config = config;
        this.enableOpenAILogging = enableOpenAILogging;
        this.logger = new OpenAILogger(openAILoggingDir);
      }
      async logSuccess(context2, response, openaiRequest, openaiResponse) {
        const responseEvent = new ApiResponseEvent(response.responseId || "unknown", context2.model, context2.duration, context2.userPromptId, context2.authType, response.usageMetadata);
        logApiResponse(this.config, responseEvent);
        if (this.enableOpenAILogging && openaiRequest && openaiResponse) {
          await this.logger.logInteraction(openaiRequest, openaiResponse);
        }
      }
      async logError(context2, error, openaiRequest) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        const errorEvent = new ApiErrorEvent(
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          error?.requestID || "unknown",
          context2.model,
          errorMessage,
          context2.duration,
          context2.userPromptId,
          context2.authType,
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          error?.type,
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          error?.code
        );
        logApiError(this.config, errorEvent);
        if (this.enableOpenAILogging && openaiRequest) {
          await this.logger.logInteraction(openaiRequest, void 0, error);
        }
      }
      async logStreamingSuccess(context2, responses, openaiRequest, openaiChunks) {
        const finalUsageMetadata = responses.slice().reverse().find((r3) => r3.usageMetadata)?.usageMetadata;
        const responseEvent = new ApiResponseEvent(responses[responses.length - 1]?.responseId || "unknown", context2.model, context2.duration, context2.userPromptId, context2.authType, finalUsageMetadata);
        logApiResponse(this.config, responseEvent);
        if (this.enableOpenAILogging && openaiRequest && openaiChunks && openaiChunks.length > 0) {
          const combinedResponse = this.combineOpenAIChunksForLogging(openaiChunks);
          await this.logger.logInteraction(openaiRequest, combinedResponse);
        }
      }
      /**
       * Combine OpenAI chunks for logging purposes
       * This method consolidates all OpenAI stream chunks into a single ChatCompletion response
       * for telemetry and logging purposes, avoiding unnecessary format conversions
       */
      combineOpenAIChunksForLogging(chunks) {
        if (chunks.length === 0) {
          throw new Error("No chunks to combine");
        }
        const firstChunk = chunks[0];
        let combinedContent = "";
        const toolCalls = [];
        let finishReason = null;
        let usage2;
        for (const chunk of chunks) {
          const choice2 = chunk.choices?.[0];
          if (choice2) {
            if (choice2.delta?.content) {
              combinedContent += choice2.delta.content;
            }
            if (choice2.delta?.tool_calls) {
              for (const toolCall of choice2.delta.tool_calls) {
                if (toolCall.index !== void 0) {
                  if (!toolCalls[toolCall.index]) {
                    toolCalls[toolCall.index] = {
                      id: toolCall.id || "",
                      type: toolCall.type || "function",
                      function: { name: "", arguments: "" }
                    };
                  }
                  if (toolCall.function?.name) {
                    toolCalls[toolCall.index].function.name += toolCall.function.name;
                  }
                  if (toolCall.function?.arguments) {
                    toolCalls[toolCall.index].function.arguments += toolCall.function.arguments;
                  }
                }
              }
            }
            if (choice2.finish_reason) {
              finishReason = choice2.finish_reason;
            }
          }
          if (chunk.usage) {
            usage2 = chunk.usage;
          }
        }
        const message = {
          role: "assistant",
          content: combinedContent || null,
          refusal: null
        };
        if (toolCalls.length > 0) {
          message.tool_calls = toolCalls.filter((tc) => tc.id);
        }
        const combinedResponse = {
          id: firstChunk.id,
          object: "chat.completion",
          created: firstChunk.created,
          model: firstChunk.model,
          choices: [
            {
              index: 0,
              message,
              finish_reason: finishReason || "stop",
              logprobs: null
            }
          ],
          usage: usage2 || {
            prompt_tokens: 0,
            completion_tokens: 0,
            total_tokens: 0
          },
          system_fingerprint: firstChunk.system_fingerprint
        };
        return combinedResponse;
      }
    };
  }
});

// packages/core/dist/src/core/openaiContentGenerator/errorHandler.js
var EnhancedErrorHandler;
var init_errorHandler = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/errorHandler.js"() {
    "use strict";
    init_esbuild_shims();
    EnhancedErrorHandler = class {
      static {
        __name(this, "EnhancedErrorHandler");
      }
      shouldSuppressLogging;
      constructor(shouldSuppressLogging = () => false) {
        this.shouldSuppressLogging = shouldSuppressLogging;
      }
      handle(error, context2, request4) {
        const isTimeoutError = this.isTimeoutError(error);
        const errorMessage = this.buildErrorMessage(error, context2, isTimeoutError);
        if (!this.shouldSuppressErrorLogging(error, request4)) {
          const logPrefix = context2.isStreaming ? "OpenAI API Streaming Error:" : "OpenAI API Error:";
          console.error(logPrefix, errorMessage);
        }
        if (isTimeoutError) {
          throw new Error(`${errorMessage}

${this.getTimeoutTroubleshootingTips(context2)}`);
        }
        throw error;
      }
      shouldSuppressErrorLogging(error, request4) {
        return this.shouldSuppressLogging(error, request4);
      }
      isTimeoutError(error) {
        if (!error)
          return false;
        const errorMessage = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
        const errorCode = error?.code;
        const errorType = error?.type;
        return errorMessage.includes("timeout") || errorMessage.includes("timed out") || errorMessage.includes("connection timeout") || errorMessage.includes("request timeout") || errorMessage.includes("read timeout") || errorMessage.includes("etimedout") || errorMessage.includes("esockettimedout") || errorCode === "ETIMEDOUT" || errorCode === "ESOCKETTIMEDOUT" || errorType === "timeout" || errorMessage.includes("request timed out") || errorMessage.includes("deadline exceeded");
      }
      buildErrorMessage(error, context2, isTimeoutError) {
        const durationSeconds = Math.round(context2.duration / 1e3);
        if (isTimeoutError) {
          const prefix = context2.isStreaming ? "Streaming request timeout" : "Request timeout";
          return `${prefix} after ${durationSeconds}s. Try reducing input length or increasing timeout in config.`;
        }
        return error instanceof Error ? error.message : String(error);
      }
      getTimeoutTroubleshootingTips(context2) {
        const baseTitle = context2.isStreaming ? "Streaming timeout troubleshooting:" : "Troubleshooting tips:";
        const baseTips = [
          "- Reduce input length or complexity",
          "- Increase timeout in config: contentGenerator.timeout",
          "- Check network connectivity"
        ];
        const streamingSpecificTips = context2.isStreaming ? [
          "- Check network stability for streaming connections",
          "- Consider using non-streaming mode for very long inputs"
        ] : ["- Consider using streaming mode for long responses"];
        return `${baseTitle}
${[...baseTips, ...streamingSpecificTips].join("\n")}`;
      }
    };
  }
});

// packages/core/dist/src/utils/request-tokenizer/textTokenizer.js
import { get_encoding } from "tiktoken";
var TextTokenizer;
var init_textTokenizer = __esm({
  "packages/core/dist/src/utils/request-tokenizer/textTokenizer.js"() {
    "use strict";
    init_esbuild_shims();
    TextTokenizer = class {
      static {
        __name(this, "TextTokenizer");
      }
      encoding = null;
      encodingName;
      constructor(encodingName = "cl100k_base") {
        this.encodingName = encodingName;
      }
      /**
       * Initialize the tokenizer (lazy loading)
       */
      async ensureEncoding() {
        if (this.encoding)
          return;
        try {
          this.encoding = get_encoding(this.encodingName);
        } catch (error) {
          console.warn(`Failed to load tiktoken with encoding ${this.encodingName}:`, error);
          this.encoding = null;
        }
      }
      /**
       * Calculate tokens for text content
       */
      async calculateTokens(text) {
        if (!text)
          return 0;
        await this.ensureEncoding();
        if (this.encoding) {
          try {
            return this.encoding.encode(text).length;
          } catch (error) {
            console.warn("Error encoding text with tiktoken:", error);
          }
        }
        return Math.ceil(text.length / 4);
      }
      /**
       * Calculate tokens for multiple text strings in parallel
       */
      async calculateTokensBatch(texts) {
        await this.ensureEncoding();
        if (this.encoding) {
          try {
            return texts.map((text) => {
              if (!text)
                return 0;
              return this.encoding ? this.encoding.encode(text).length : 0;
            });
          } catch (error) {
            console.warn("Error encoding texts with tiktoken:", error);
            return texts.map((text) => Math.ceil((text || "").length / 4));
          }
        }
        return texts.map((text) => Math.ceil((text || "").length / 4));
      }
      /**
       * Dispose of resources
       */
      dispose() {
        if (this.encoding) {
          try {
            this.encoding.free();
          } catch (error) {
            console.warn("Error freeing tiktoken encoding:", error);
          }
          this.encoding = null;
        }
      }
    };
  }
});

// packages/core/dist/src/utils/request-tokenizer/supportedImageFormats.js
function isSupportedImageMimeType(mimeType) {
  return SUPPORTED_IMAGE_MIME_TYPES.includes(mimeType);
}
function getSupportedImageFormatsString() {
  return SUPPORTED_IMAGE_MIME_TYPES.map((type) => type.replace("image/", "").toUpperCase()).join(", ");
}
function getUnsupportedImageFormatWarning() {
  return `Only the following image formats are supported: ${getSupportedImageFormatsString()}. Other formats may not work as expected.`;
}
var SUPPORTED_IMAGE_MIME_TYPES;
var init_supportedImageFormats = __esm({
  "packages/core/dist/src/utils/request-tokenizer/supportedImageFormats.js"() {
    "use strict";
    init_esbuild_shims();
    SUPPORTED_IMAGE_MIME_TYPES = [
      "image/bmp",
      "image/jpeg",
      "image/jpg",
      // Alternative MIME type for JPEG
      "image/png",
      "image/tiff",
      "image/webp",
      "image/heic"
    ];
    __name(isSupportedImageMimeType, "isSupportedImageMimeType");
    __name(getSupportedImageFormatsString, "getSupportedImageFormatsString");
    __name(getUnsupportedImageFormatWarning, "getUnsupportedImageFormatWarning");
  }
});

// packages/core/dist/src/utils/request-tokenizer/imageTokenizer.js
var ImageTokenizer;
var init_imageTokenizer = __esm({
  "packages/core/dist/src/utils/request-tokenizer/imageTokenizer.js"() {
    "use strict";
    init_esbuild_shims();
    init_supportedImageFormats();
    ImageTokenizer = class _ImageTokenizer {
      static {
        __name(this, "ImageTokenizer");
      }
      /** 28x28 pixels = 1 token */
      static PIXELS_PER_TOKEN = 28 * 28;
      /** Minimum tokens per image */
      static MIN_TOKENS_PER_IMAGE = 4;
      /** Maximum tokens per image */
      static MAX_TOKENS_PER_IMAGE = 16384;
      /** Special tokens for vision markers */
      static VISION_SPECIAL_TOKENS = 2;
      /**
       * Extract image metadata from base64 data
       *
       * @param base64Data Base64-encoded image data (with or without data URL prefix)
       * @param mimeType MIME type of the image
       * @returns Promise resolving to ImageMetadata with dimensions and format info
       */
      async extractImageMetadata(base64Data, mimeType) {
        try {
          if (!isSupportedImageMimeType(mimeType)) {
            console.warn(`Unsupported image format: ${mimeType}`);
            return {
              width: 512,
              height: 512,
              mimeType,
              dataSize: Math.floor(base64Data.length * 0.75)
            };
          }
          const cleanBase64 = base64Data.replace(/^data:[^;]+;base64,/, "");
          const buffer = Buffer.from(cleanBase64, "base64");
          const dimensions = await this.extractDimensions(buffer, mimeType);
          return {
            width: dimensions.width,
            height: dimensions.height,
            mimeType,
            dataSize: buffer.length
          };
        } catch (error) {
          console.warn("Failed to extract image metadata:", error);
          return {
            width: 512,
            height: 512,
            mimeType,
            dataSize: Math.floor(base64Data.length * 0.75)
          };
        }
      }
      /**
       * Extract image dimensions from buffer based on format
       *
       * @param buffer Binary image data buffer
       * @param mimeType MIME type to determine parsing strategy
       * @returns Promise resolving to width and height dimensions
       */
      async extractDimensions(buffer, mimeType) {
        if (mimeType.includes("png")) {
          return this.extractPngDimensions(buffer);
        }
        if (mimeType.includes("jpeg") || mimeType.includes("jpg")) {
          return this.extractJpegDimensions(buffer);
        }
        if (mimeType.includes("webp")) {
          return this.extractWebpDimensions(buffer);
        }
        if (mimeType.includes("gif")) {
          return this.extractGifDimensions(buffer);
        }
        if (mimeType.includes("bmp")) {
          return this.extractBmpDimensions(buffer);
        }
        if (mimeType.includes("tiff")) {
          return this.extractTiffDimensions(buffer);
        }
        if (mimeType.includes("heic")) {
          return this.extractHeicDimensions(buffer);
        }
        return { width: 512, height: 512 };
      }
      /**
       * Extract PNG dimensions from IHDR chunk
       * PNG signature: 89 50 4E 47 0D 0A 1A 0A
       * Width/height at bytes 16-19 and 20-23 (big-endian)
       */
      extractPngDimensions(buffer) {
        if (buffer.length < 24) {
          throw new Error("Invalid PNG: buffer too short");
        }
        const signature = buffer.subarray(0, 8);
        const expectedSignature = Buffer.from([
          137,
          80,
          78,
          71,
          13,
          10,
          26,
          10
        ]);
        if (!signature.equals(expectedSignature)) {
          throw new Error("Invalid PNG signature");
        }
        const width = buffer.readUInt32BE(16);
        const height = buffer.readUInt32BE(20);
        return { width, height };
      }
      /**
       * Extract JPEG dimensions from SOF (Start of Frame) markers
       * JPEG starts with FF D8, SOF markers: 0xC0-0xC3, 0xC5-0xC7, 0xC9-0xCB, 0xCD-0xCF
       * Dimensions at offset +5 (height) and +7 (width) from SOF marker
       */
      extractJpegDimensions(buffer) {
        if (buffer.length < 4 || buffer[0] !== 255 || buffer[1] !== 216) {
          throw new Error("Invalid JPEG signature");
        }
        let offset = 2;
        while (offset < buffer.length - 8) {
          if (buffer[offset] !== 255) {
            offset++;
            continue;
          }
          const marker = buffer[offset + 1];
          if (marker >= 192 && marker <= 195 || marker >= 197 && marker <= 199 || marker >= 201 && marker <= 203 || marker >= 205 && marker <= 207) {
            const height = buffer.readUInt16BE(offset + 5);
            const width = buffer.readUInt16BE(offset + 7);
            return { width, height };
          }
          const segmentLength = buffer.readUInt16BE(offset + 2);
          offset += 2 + segmentLength;
        }
        throw new Error("Could not find JPEG dimensions");
      }
      /**
       * Extract WebP dimensions from RIFF container
       * Supports VP8, VP8L, and VP8X formats
       */
      extractWebpDimensions(buffer) {
        if (buffer.length < 30) {
          throw new Error("Invalid WebP: too short");
        }
        const riffSignature = buffer.subarray(0, 4).toString("ascii");
        const webpSignature = buffer.subarray(8, 12).toString("ascii");
        if (riffSignature !== "RIFF" || webpSignature !== "WEBP") {
          throw new Error("Invalid WebP signature");
        }
        const format4 = buffer.subarray(12, 16).toString("ascii");
        if (format4 === "VP8 ") {
          const width = buffer.readUInt16LE(26) & 16383;
          const height = buffer.readUInt16LE(28) & 16383;
          return { width, height };
        } else if (format4 === "VP8L") {
          const bits = buffer.readUInt32LE(21);
          const width = (bits & 16383) + 1;
          const height = (bits >> 14 & 16383) + 1;
          return { width, height };
        } else if (format4 === "VP8X") {
          const width = (buffer.readUInt32LE(24) & 16777215) + 1;
          const height = (buffer.readUInt32LE(26) & 16777215) + 1;
          return { width, height };
        }
        throw new Error("Unsupported WebP format");
      }
      /**
       * Extract GIF dimensions from header
       * Supports GIF87a and GIF89a formats
       */
      extractGifDimensions(buffer) {
        if (buffer.length < 10) {
          throw new Error("Invalid GIF: too short");
        }
        const signature = buffer.subarray(0, 6).toString("ascii");
        if (signature !== "GIF87a" && signature !== "GIF89a") {
          throw new Error("Invalid GIF signature");
        }
        const width = buffer.readUInt16LE(6);
        const height = buffer.readUInt16LE(8);
        return { width, height };
      }
      /**
       * Calculate tokens for an image based on its metadata
       *
       * @param metadata Image metadata containing width, height, and format info
       * @returns Total token count including base image tokens and special tokens
       */
      calculateTokens(metadata) {
        return this.calculateTokensWithScaling(metadata.width, metadata.height);
      }
      /**
       * Calculate tokens with scaling logic
       *
       * Steps:
       * 1. Normalize to 28-pixel multiples
       * 2. Scale large images down, small images up
       * 3. Calculate tokens: pixels / 784 + 2 special tokens
       *
       * @param width Original image width in pixels
       * @param height Original image height in pixels
       * @returns Total token count for the image
       */
      calculateTokensWithScaling(width, height) {
        let hBar = Math.round(height / 28) * 28;
        let wBar = Math.round(width / 28) * 28;
        const minPixels = _ImageTokenizer.MIN_TOKENS_PER_IMAGE * _ImageTokenizer.PIXELS_PER_TOKEN;
        const maxPixels = _ImageTokenizer.MAX_TOKENS_PER_IMAGE * _ImageTokenizer.PIXELS_PER_TOKEN;
        if (hBar * wBar > maxPixels) {
          const beta = Math.sqrt(height * width / maxPixels);
          hBar = Math.floor(height / beta / 28) * 28;
          wBar = Math.floor(width / beta / 28) * 28;
        } else if (hBar * wBar < minPixels) {
          const beta = Math.sqrt(minPixels / (height * width));
          hBar = Math.ceil(height * beta / 28) * 28;
          wBar = Math.ceil(width * beta / 28) * 28;
        }
        const imageTokens = Math.floor(hBar * wBar / _ImageTokenizer.PIXELS_PER_TOKEN);
        return imageTokens + _ImageTokenizer.VISION_SPECIAL_TOKENS;
      }
      /**
       * Calculate tokens for multiple images serially
       *
       * @param base64DataArray Array of image data with MIME type information
       * @returns Promise resolving to array of token counts in same order as input
       */
      async calculateTokensBatch(base64DataArray) {
        const results = [];
        for (const { data, mimeType } of base64DataArray) {
          try {
            const metadata = await this.extractImageMetadata(data, mimeType);
            results.push(this.calculateTokens(metadata));
          } catch (error) {
            console.warn("Error calculating tokens for image:", error);
            results.push(_ImageTokenizer.MIN_TOKENS_PER_IMAGE + _ImageTokenizer.VISION_SPECIAL_TOKENS);
          }
        }
        return results;
      }
      /**
       * Extract BMP dimensions from header
       * BMP signature: 42 4D (BM)
       * Width/height at bytes 18-21 and 22-25 (little-endian)
       */
      extractBmpDimensions(buffer) {
        if (buffer.length < 26) {
          throw new Error("Invalid BMP: buffer too short");
        }
        if (buffer[0] !== 66 || buffer[1] !== 77) {
          throw new Error("Invalid BMP signature");
        }
        const width = buffer.readUInt32LE(18);
        const height = buffer.readUInt32LE(22);
        return { width, height: Math.abs(height) };
      }
      /**
       * Extract TIFF dimensions from IFD (Image File Directory)
       * TIFF can be little-endian (II) or big-endian (MM)
       * Width/height are stored in IFD entries with tags 0x0100 and 0x0101
       */
      extractTiffDimensions(buffer) {
        if (buffer.length < 8) {
          throw new Error("Invalid TIFF: buffer too short");
        }
        const byteOrder = buffer.subarray(0, 2).toString("ascii");
        const isLittleEndian = byteOrder === "II";
        const isBigEndian = byteOrder === "MM";
        if (!isLittleEndian && !isBigEndian) {
          throw new Error("Invalid TIFF byte order");
        }
        const magic = isLittleEndian ? buffer.readUInt16LE(2) : buffer.readUInt16BE(2);
        if (magic !== 42) {
          throw new Error("Invalid TIFF magic number");
        }
        const ifdOffset = isLittleEndian ? buffer.readUInt32LE(4) : buffer.readUInt32BE(4);
        if (ifdOffset >= buffer.length) {
          throw new Error("Invalid TIFF IFD offset");
        }
        const numEntries = isLittleEndian ? buffer.readUInt16LE(ifdOffset) : buffer.readUInt16BE(ifdOffset);
        let width = 0;
        let height = 0;
        for (let i = 0; i < numEntries; i++) {
          const entryOffset = ifdOffset + 2 + i * 12;
          if (entryOffset + 12 > buffer.length)
            break;
          const tag2 = isLittleEndian ? buffer.readUInt16LE(entryOffset) : buffer.readUInt16BE(entryOffset);
          const type = isLittleEndian ? buffer.readUInt16LE(entryOffset + 2) : buffer.readUInt16BE(entryOffset + 2);
          const value = isLittleEndian ? buffer.readUInt32LE(entryOffset + 8) : buffer.readUInt32BE(entryOffset + 8);
          if (tag2 === 256) {
            width = type === 3 ? value : value;
          } else if (tag2 === 257) {
            height = type === 3 ? value : value;
          }
          if (width > 0 && height > 0)
            break;
        }
        if (width === 0 || height === 0) {
          throw new Error("Could not find TIFF dimensions");
        }
        return { width, height };
      }
      /**
       * Extract HEIC dimensions from meta box
       * HEIC is based on ISO Base Media File Format
       * This is a simplified implementation that looks for 'ispe' (Image Spatial Extents) box
       */
      extractHeicDimensions(buffer) {
        if (buffer.length < 12) {
          throw new Error("Invalid HEIC: buffer too short");
        }
        const ftypBox = buffer.subarray(4, 8).toString("ascii");
        if (ftypBox !== "ftyp") {
          throw new Error("Invalid HEIC: missing ftyp box");
        }
        const brand = buffer.subarray(8, 12).toString("ascii");
        if (!["heic", "heix", "hevc", "hevx"].includes(brand)) {
          throw new Error("Invalid HEIC brand");
        }
        let offset = 0;
        while (offset < buffer.length - 8) {
          const boxSize = buffer.readUInt32BE(offset);
          const boxType = buffer.subarray(offset + 4, offset + 8).toString("ascii");
          if (boxType === "meta") {
            const metaOffset = offset + 8;
            let innerOffset = metaOffset + 4;
            while (innerOffset < offset + boxSize - 8) {
              const innerBoxSize = buffer.readUInt32BE(innerOffset);
              const innerBoxType = buffer.subarray(innerOffset + 4, innerOffset + 8).toString("ascii");
              if (innerBoxType === "ispe") {
                if (innerOffset + 20 <= buffer.length) {
                  const width = buffer.readUInt32BE(innerOffset + 12);
                  const height = buffer.readUInt32BE(innerOffset + 16);
                  return { width, height };
                }
              }
              if (innerBoxSize === 0)
                break;
              innerOffset += innerBoxSize;
            }
          }
          if (boxSize === 0)
            break;
          offset += boxSize;
        }
        console.warn("Could not extract HEIC dimensions, using default");
        return { width: 512, height: 512 };
      }
    };
  }
});

// packages/core/dist/src/utils/request-tokenizer/requestTokenizer.js
var DefaultRequestTokenizer;
var init_requestTokenizer = __esm({
  "packages/core/dist/src/utils/request-tokenizer/requestTokenizer.js"() {
    "use strict";
    init_esbuild_shims();
    init_textTokenizer();
    init_imageTokenizer();
    DefaultRequestTokenizer = class {
      static {
        __name(this, "DefaultRequestTokenizer");
      }
      textTokenizer;
      imageTokenizer;
      constructor() {
        this.textTokenizer = new TextTokenizer();
        this.imageTokenizer = new ImageTokenizer();
      }
      /**
       * Calculate tokens for a request using serial processing
       */
      async calculateTokens(request4, config = {}) {
        const startTime = performance.now();
        if (config.textEncoding) {
          this.textTokenizer = new TextTokenizer(config.textEncoding);
        }
        try {
          const { textContents, imageContents, audioContents, otherContents } = this.processAndGroupContents(request4);
          if (textContents.length === 0 && imageContents.length === 0 && audioContents.length === 0 && otherContents.length === 0) {
            return {
              totalTokens: 0,
              breakdown: {
                textTokens: 0,
                imageTokens: 0,
                audioTokens: 0,
                otherTokens: 0
              },
              processingTime: performance.now() - startTime
            };
          }
          const textTokens = await this.calculateTextTokens(textContents);
          const imageTokens = await this.calculateImageTokens(imageContents);
          const audioTokens = await this.calculateAudioTokens(audioContents);
          const otherTokens = await this.calculateOtherTokens(otherContents);
          const totalTokens = textTokens + imageTokens + audioTokens + otherTokens;
          const processingTime = performance.now() - startTime;
          return {
            totalTokens,
            breakdown: {
              textTokens,
              imageTokens,
              audioTokens,
              otherTokens
            },
            processingTime
          };
        } catch (error) {
          console.error("Error calculating tokens:", error);
          const fallbackTokens = this.calculateFallbackTokens(request4);
          return {
            totalTokens: fallbackTokens,
            breakdown: {
              textTokens: fallbackTokens,
              imageTokens: 0,
              audioTokens: 0,
              otherTokens: 0
            },
            processingTime: performance.now() - startTime
          };
        }
      }
      /**
       * Calculate tokens for text contents
       */
      async calculateTextTokens(textContents) {
        if (textContents.length === 0)
          return 0;
        try {
          const tokenCounts = await this.textTokenizer.calculateTokensBatch(textContents);
          return tokenCounts.reduce((sum, count) => sum + count, 0);
        } catch (error) {
          console.warn("Error calculating text tokens:", error);
          const totalChars = textContents.join("").length;
          return Math.ceil(totalChars / 4);
        }
      }
      /**
       * Calculate tokens for image contents using serial processing
       */
      async calculateImageTokens(imageContents) {
        if (imageContents.length === 0)
          return 0;
        try {
          const tokenCounts = await this.imageTokenizer.calculateTokensBatch(imageContents);
          return tokenCounts.reduce((sum, count) => sum + count, 0);
        } catch (error) {
          console.warn("Error calculating image tokens:", error);
          return imageContents.length * 6;
        }
      }
      /**
       * Calculate tokens for audio contents
       * TODO: Implement proper audio token calculation
       */
      async calculateAudioTokens(audioContents) {
        if (audioContents.length === 0)
          return 0;
        let totalTokens = 0;
        for (const audioContent of audioContents) {
          try {
            const dataSize = Math.floor(audioContent.data.length * 0.75);
            totalTokens += Math.max(Math.ceil(dataSize / 100), 10);
          } catch (error) {
            console.warn("Error calculating audio tokens:", error);
            totalTokens += 10;
          }
        }
        return totalTokens;
      }
      /**
       * Calculate tokens for other content types (functions, files, etc.)
       */
      async calculateOtherTokens(otherContents) {
        if (otherContents.length === 0)
          return 0;
        try {
          const tokenCounts = await this.textTokenizer.calculateTokensBatch(otherContents);
          return tokenCounts.reduce((sum, count) => sum + count, 0);
        } catch (error) {
          console.warn("Error calculating other content tokens:", error);
          const totalChars = otherContents.join("").length;
          return Math.ceil(totalChars / 4);
        }
      }
      /**
       * Fallback token calculation using simple string serialization
       */
      calculateFallbackTokens(request4) {
        try {
          const content = JSON.stringify(request4.contents);
          return Math.ceil(content.length / 4);
        } catch (error) {
          console.warn("Error in fallback token calculation:", error);
          return 100;
        }
      }
      /**
       * Process request contents and group by type
       */
      processAndGroupContents(request4) {
        const textContents = [];
        const imageContents = [];
        const audioContents = [];
        const otherContents = [];
        if (!request4.contents) {
          return { textContents, imageContents, audioContents, otherContents };
        }
        const contents = Array.isArray(request4.contents) ? request4.contents : [request4.contents];
        for (const content of contents) {
          this.processContent(content, textContents, imageContents, audioContents, otherContents);
        }
        return { textContents, imageContents, audioContents, otherContents };
      }
      /**
       * Process a single content item and add to appropriate arrays
       */
      processContent(content, textContents, imageContents, audioContents, otherContents) {
        if (typeof content === "string") {
          if (content.trim()) {
            textContents.push(content);
          }
          return;
        }
        if ("parts" in content && content.parts) {
          for (const part of content.parts) {
            this.processPart(part, textContents, imageContents, audioContents, otherContents);
          }
        }
      }
      /**
       * Process a single part and add to appropriate arrays
       */
      processPart(part, textContents, imageContents, audioContents, otherContents) {
        if (typeof part === "string") {
          if (part.trim()) {
            textContents.push(part);
          }
          return;
        }
        if ("text" in part && part.text) {
          textContents.push(part.text);
          return;
        }
        if ("inlineData" in part && part.inlineData) {
          const { data, mimeType } = part.inlineData;
          if (mimeType && mimeType.startsWith("image/")) {
            imageContents.push({ data: data || "", mimeType });
            return;
          }
          if (mimeType && mimeType.startsWith("audio/")) {
            audioContents.push({ data: data || "", mimeType });
            return;
          }
        }
        if ("fileData" in part && part.fileData) {
          otherContents.push(JSON.stringify(part.fileData));
          return;
        }
        if ("functionCall" in part && part.functionCall) {
          otherContents.push(JSON.stringify(part.functionCall));
          return;
        }
        if ("functionResponse" in part && part.functionResponse) {
          otherContents.push(JSON.stringify(part.functionResponse));
          return;
        }
        try {
          const serialized = JSON.stringify(part);
          if (serialized && serialized !== "{}") {
            otherContents.push(serialized);
          }
        } catch (error) {
          console.warn("Failed to serialize unknown part type:", error);
        }
      }
      /**
       * Dispose of resources
       */
      async dispose() {
        try {
          this.textTokenizer.dispose();
        } catch (error) {
          console.warn("Error disposing request tokenizer:", error);
        }
      }
    };
  }
});

// packages/core/dist/src/utils/request-tokenizer/index.js
function getDefaultTokenizer() {
  if (!defaultTokenizer) {
    defaultTokenizer = new DefaultRequestTokenizer();
  }
  return defaultTokenizer;
}
var defaultTokenizer;
var init_request_tokenizer = __esm({
  "packages/core/dist/src/utils/request-tokenizer/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_requestTokenizer();
    init_requestTokenizer();
    init_textTokenizer();
    init_imageTokenizer();
    defaultTokenizer = null;
    __name(getDefaultTokenizer, "getDefaultTokenizer");
  }
});

// packages/core/dist/src/core/openaiContentGenerator/openaiContentGenerator.js
var OpenAIContentGenerator;
var init_openaiContentGenerator = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/openaiContentGenerator.js"() {
    "use strict";
    init_esbuild_shims();
    init_provider();
    init_pipeline();
    init_telemetryService();
    init_errorHandler();
    init_request_tokenizer();
    OpenAIContentGenerator = class {
      static {
        __name(this, "OpenAIContentGenerator");
      }
      pipeline;
      constructor(contentGeneratorConfig, cliConfig, provider) {
        const pipelineConfig = {
          cliConfig,
          provider,
          contentGeneratorConfig,
          telemetryService: new DefaultTelemetryService(cliConfig, contentGeneratorConfig.enableOpenAILogging, contentGeneratorConfig.openAILoggingDir),
          errorHandler: new EnhancedErrorHandler((error, request4) => this.shouldSuppressErrorLogging(error, request4))
        };
        this.pipeline = new ContentGenerationPipeline(pipelineConfig);
      }
      /**
       * Hook for subclasses to customize error handling behavior
       * @param error The error that occurred
       * @param request The original request
       * @returns true if error logging should be suppressed, false otherwise
       */
      shouldSuppressErrorLogging(_error, _request) {
        return false;
      }
      async generateContent(request4, userPromptId) {
        return this.pipeline.execute(request4, userPromptId);
      }
      async generateContentStream(request4, userPromptId) {
        return this.pipeline.executeStream(request4, userPromptId);
      }
      async countTokens(request4) {
        try {
          const tokenizer = getDefaultTokenizer();
          const result = await tokenizer.calculateTokens(request4, {
            textEncoding: "cl100k_base"
            // Use GPT-4 encoding for consistency
          });
          return {
            totalTokens: result.totalTokens
          };
        } catch (error) {
          console.warn("Failed to calculate tokens with new tokenizer, falling back to simple method:", error);
          const content = JSON.stringify(request4.contents);
          const totalTokens = Math.ceil(content.length / 4);
          return {
            totalTokens
          };
        }
      }
      async embedContent(request4) {
        let text = "";
        if (Array.isArray(request4.contents)) {
          text = request4.contents.map((content) => {
            if (typeof content === "string")
              return content;
            if ("parts" in content && content.parts) {
              return content.parts.map((part) => typeof part === "string" ? part : "text" in part ? part.text || "" : "").join(" ");
            }
            return "";
          }).join(" ");
        } else if (request4.contents) {
          if (typeof request4.contents === "string") {
            text = request4.contents;
          } else if ("parts" in request4.contents && request4.contents.parts) {
            text = request4.contents.parts.map((part) => typeof part === "string" ? part : "text" in part ? part.text : "").join(" ");
          }
        }
        try {
          const embedding = await this.pipeline.client.embeddings.create({
            model: "text-embedding-ada-002",
            // Default embedding model
            input: text
          });
          return {
            embeddings: [
              {
                values: embedding.data[0].embedding
              }
            ]
          };
        } catch (error) {
          console.error("OpenAI API Embedding Error:", error);
          throw new Error(`OpenAI API error: ${error instanceof Error ? error.message : String(error)}`);
        }
      }
    };
  }
});

// packages/core/dist/src/core/openaiContentGenerator/index.js
var openaiContentGenerator_exports = {};
__export(openaiContentGenerator_exports, {
  ContentGenerationPipeline: () => ContentGenerationPipeline,
  DashScopeOpenAICompatibleProvider: () => DashScopeOpenAICompatibleProvider,
  DeepSeekOpenAICompatibleProvider: () => DeepSeekOpenAICompatibleProvider,
  DefaultTelemetryService: () => DefaultTelemetryService,
  EnhancedErrorHandler: () => EnhancedErrorHandler,
  OpenAIContentConverter: () => OpenAIContentConverter,
  OpenAIContentGenerator: () => OpenAIContentGenerator,
  OpenRouterOpenAICompatibleProvider: () => OpenRouterOpenAICompatibleProvider,
  createOpenAIContentGenerator: () => createOpenAIContentGenerator,
  determineProvider: () => determineProvider
});
function createOpenAIContentGenerator(contentGeneratorConfig, cliConfig) {
  const provider = determineProvider(contentGeneratorConfig, cliConfig);
  return new OpenAIContentGenerator(contentGeneratorConfig, cliConfig, provider);
}
function determineProvider(contentGeneratorConfig, cliConfig) {
  const config = contentGeneratorConfig || cliConfig.getContentGeneratorConfig();
  if (DashScopeOpenAICompatibleProvider.isDashScopeProvider(config)) {
    return new DashScopeOpenAICompatibleProvider(contentGeneratorConfig, cliConfig);
  }
  if (DeepSeekOpenAICompatibleProvider.isDeepSeekProvider(config)) {
    return new DeepSeekOpenAICompatibleProvider(contentGeneratorConfig, cliConfig);
  }
  if (OpenRouterOpenAICompatibleProvider.isOpenRouterProvider(config)) {
    return new OpenRouterOpenAICompatibleProvider(contentGeneratorConfig, cliConfig);
  }
  if (ModelScopeOpenAICompatibleProvider.isModelScopeProvider(config)) {
    return new ModelScopeOpenAICompatibleProvider(contentGeneratorConfig, cliConfig);
  }
  return new DefaultOpenAICompatibleProvider(contentGeneratorConfig, cliConfig);
}
var init_openaiContentGenerator2 = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_openaiContentGenerator();
    init_provider();
    init_openaiContentGenerator();
    init_pipeline();
    init_provider();
    init_converter2();
    init_telemetryService();
    init_errorHandler();
    __name(createOpenAIContentGenerator, "createOpenAIContentGenerator");
    __name(determineProvider, "determineProvider");
  }
});

// packages/core/dist/src/qwen/qwenContentGenerator.js
var qwenContentGenerator_exports = {};
__export(qwenContentGenerator_exports, {
  QwenContentGenerator: () => QwenContentGenerator
});
var QwenContentGenerator;
var init_qwenContentGenerator = __esm({
  "packages/core/dist/src/qwen/qwenContentGenerator.js"() {
    "use strict";
    init_esbuild_shims();
    init_openaiContentGenerator2();
    init_dashscope();
    init_sharedTokenManager();
    init_config3();
    init_constants2();
    QwenContentGenerator = class extends OpenAIContentGenerator {
      static {
        __name(this, "QwenContentGenerator");
      }
      qwenClient;
      sharedManager;
      currentToken;
      constructor(qwenClient, contentGeneratorConfig, cliConfig) {
        const dashscopeProvider = new DashScopeOpenAICompatibleProvider(contentGeneratorConfig, cliConfig);
        super(contentGeneratorConfig, cliConfig, dashscopeProvider);
        this.qwenClient = qwenClient;
        this.sharedManager = SharedTokenManager.getInstance();
        if (contentGeneratorConfig?.baseUrl && contentGeneratorConfig?.apiKey) {
          this.pipeline.client.baseURL = contentGeneratorConfig?.baseUrl;
          this.pipeline.client.apiKey = contentGeneratorConfig?.apiKey;
        }
      }
      /**
       * Get the current endpoint URL with proper protocol and /v1 suffix
       */
      getCurrentEndpoint(resourceUrl) {
        const baseEndpoint = resourceUrl || DEFAULT_DASHSCOPE_BASE_URL;
        const suffix = "/v1";
        const normalizedUrl = baseEndpoint.startsWith("http") ? baseEndpoint : `https://${baseEndpoint}`;
        return normalizedUrl.endsWith(suffix) ? normalizedUrl : `${normalizedUrl}${suffix}`;
      }
      /**
       * Override error logging behavior to suppress auth errors during token refresh
       */
      shouldSuppressErrorLogging(error, _request) {
        return this.isAuthError(error);
      }
      /**
       * Get valid token and endpoint using the shared token manager
       */
      async getValidToken() {
        try {
          const credentials = await this.sharedManager.getValidCredentials(this.qwenClient);
          if (!credentials.access_token) {
            throw new Error("No access token available");
          }
          return {
            token: credentials.access_token,
            endpoint: this.getCurrentEndpoint(credentials.resource_url)
          };
        } catch (error) {
          if (this.isAuthError(error)) {
            throw error;
          }
          console.warn("Failed to get token from shared manager:", error);
          throw new Error("Failed to obtain valid Qwen access token. Please re-authenticate.");
        }
      }
      /**
       * Execute an operation with automatic credential management and retry logic.
       * This method handles:
       * - Dynamic token and endpoint retrieval
       * - Client configuration updates
       * - Retry logic on authentication errors with token refresh
       *
       * @param operation - The operation to execute with updated client configuration
       * @returns The result of the operation
       */
      async executeWithCredentialManagement(operation) {
        const attemptOperation = /* @__PURE__ */ __name(async () => {
          const { token: token2, endpoint } = await this.getValidToken();
          this.pipeline.client.apiKey = token2;
          this.pipeline.client.baseURL = endpoint;
          return await operation();
        }, "attemptOperation");
        try {
          return await attemptOperation();
        } catch (error) {
          if (this.isAuthError(error)) {
            await this.sharedManager.getValidCredentials(this.qwenClient, true);
            return await attemptOperation();
          }
          throw error;
        }
      }
      /**
       * Override to use dynamic token and endpoint with automatic retry
       */
      async generateContent(request4, userPromptId) {
        return this.executeWithCredentialManagement(() => super.generateContent(request4, userPromptId));
      }
      /**
       * Override to use dynamic token and endpoint with automatic retry
       */
      async generateContentStream(request4, userPromptId) {
        return this.executeWithCredentialManagement(() => super.generateContentStream(request4, userPromptId));
      }
      /**
       * Override to use dynamic token and endpoint with automatic retry
       */
      async countTokens(request4) {
        return super.countTokens(request4);
      }
      /**
       * Override to use dynamic token and endpoint with automatic retry
       */
      async embedContent(request4) {
        return this.executeWithCredentialManagement(() => super.embedContent(request4));
      }
      /**
       * Check if an error is related to authentication/authorization
       */
      isAuthError(error) {
        if (!error)
          return false;
        const errorMessage = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
        const errorWithCode = error;
        const errorCode = errorWithCode?.status || errorWithCode?.code;
        return errorCode === 401 || errorCode === 403 || errorCode === "401" || errorCode === "403" || errorMessage.includes("unauthorized") || errorMessage.includes("forbidden") || errorMessage.includes("invalid api key") || errorMessage.includes("invalid access token") || errorMessage.includes("token expired") || errorMessage.includes("authentication") || errorMessage.includes("access denied") || errorMessage.includes("token") && errorMessage.includes("expired");
      }
      /**
       * Get the current cached token (may be expired)
       */
      getCurrentToken() {
        if (this.currentToken) {
          return this.currentToken;
        }
        const credentials = this.sharedManager.getCurrentCredentials();
        return credentials?.access_token || null;
      }
      /**
       * Clear the cached token
       */
      clearToken() {
        this.currentToken = void 0;
        this.sharedManager.clearCache();
      }
    };
  }
});

// packages/core/dist/src/core/contentGenerator.js
function createContentGeneratorConfig(config, authType, generationConfig) {
  const newContentGeneratorConfig = {
    ...generationConfig || {},
    authType,
    proxy: config?.getProxy()
  };
  if (authType === AuthType2.QWEN_OAUTH) {
    return {
      ...newContentGeneratorConfig,
      model: DEFAULT_QWEN_MODEL,
      apiKey: "QWEN_OAUTH_DYNAMIC_TOKEN"
    };
  }
  if (authType === AuthType2.USE_OPENAI) {
    if (!newContentGeneratorConfig.apiKey) {
      throw new Error("OpenAI API key is required");
    }
    return {
      ...newContentGeneratorConfig,
      model: newContentGeneratorConfig?.model || "qwen3-coder-plus"
    };
  }
  return {
    ...newContentGeneratorConfig,
    model: newContentGeneratorConfig?.model || DEFAULT_QWEN_MODEL
  };
}
async function createContentGenerator(config, gcConfig, sessionId2, isInitialAuth) {
  const version2 = "0.2.3";
  const userAgent2 = `QwenCode/${version2} (${process.platform}; ${process.arch})`;
  const baseHeaders = {
    "User-Agent": userAgent2
  };
  if (config.authType === AuthType2.LOGIN_WITH_GOOGLE || config.authType === AuthType2.CLOUD_SHELL) {
    const httpOptions = { headers: baseHeaders };
    return new LoggingContentGenerator(await createCodeAssistContentGenerator(httpOptions, config.authType, gcConfig, sessionId2), gcConfig);
  }
  if (config.authType === AuthType2.USE_GEMINI || config.authType === AuthType2.USE_VERTEX_AI) {
    let headers = { ...baseHeaders };
    if (gcConfig?.getUsageStatisticsEnabled()) {
      const installationManager = new InstallationManager();
      const installationId = installationManager.getInstallationId();
      headers = {
        ...headers,
        "x-gemini-api-privileged-user-id": `${installationId}`
      };
    }
    const httpOptions = { headers };
    const googleGenAI = new GoogleGenAI({
      apiKey: config.apiKey === "" ? void 0 : config.apiKey,
      vertexai: config.vertexai,
      httpOptions
    });
    return new LoggingContentGenerator(googleGenAI.models, gcConfig);
  }
  if (config.authType === AuthType2.USE_OPENAI) {
    if (!config.apiKey) {
      throw new Error("OpenAI API key is required");
    }
    const { createOpenAIContentGenerator: createOpenAIContentGenerator2 } = await Promise.resolve().then(() => (init_openaiContentGenerator2(), openaiContentGenerator_exports));
    return createOpenAIContentGenerator2(config, gcConfig);
  }
  if (config.authType === AuthType2.QWEN_OAUTH) {
    const { getQwenOAuthClient: getQwenOauthClient } = await Promise.resolve().then(() => (init_qwenOAuth2(), qwenOAuth2_exports));
    const { QwenContentGenerator: QwenContentGenerator2 } = await Promise.resolve().then(() => (init_qwenContentGenerator(), qwenContentGenerator_exports));
    try {
      const qwenClient = await getQwenOauthClient(gcConfig, isInitialAuth ? { requireCachedCredentials: true } : void 0);
      return new QwenContentGenerator2(qwenClient, config, gcConfig);
    } catch (error) {
      throw new Error(`${error instanceof Error ? error.message : String(error)}`);
    }
  }
  throw new Error(`Error creating contentGenerator: Unsupported authType: ${config.authType}`);
}
var AuthType2;
var init_contentGenerator = __esm({
  "packages/core/dist/src/core/contentGenerator.js"() {
    "use strict";
    init_esbuild_shims();
    init_node();
    init_codeAssist();
    init_models();
    init_installationManager();
    init_loggingContentGenerator();
    (function(AuthType3) {
      AuthType3["LOGIN_WITH_GOOGLE"] = "oauth-personal";
      AuthType3["USE_GEMINI"] = "gemini-api-key";
      AuthType3["USE_VERTEX_AI"] = "vertex-ai";
      AuthType3["CLOUD_SHELL"] = "cloud-shell";
      AuthType3["USE_OPENAI"] = "openai";
      AuthType3["QWEN_OAUTH"] = "qwen-oauth";
    })(AuthType2 || (AuthType2 = {}));
    __name(createContentGeneratorConfig, "createContentGeneratorConfig");
    __name(createContentGenerator, "createContentGenerator");
  }
});

// packages/core/dist/src/utils/retry.js
function defaultShouldRetry(error) {
  if (error && typeof error.status === "number") {
    const status = error.status;
    if (status === 429 || status >= 500 && status < 600) {
      return true;
    }
  }
  if (error instanceof Error && error.message) {
    if (error.message.includes("429"))
      return true;
    if (error.message.match(/5\d{2}/))
      return true;
  }
  return false;
}
function delay(ms) {
  return new Promise((resolve24) => setTimeout(resolve24, ms));
}
async function retryWithBackoff(fn, options2) {
  if (options2?.maxAttempts !== void 0 && options2.maxAttempts <= 0) {
    throw new Error("maxAttempts must be a positive number.");
  }
  const cleanOptions = options2 ? Object.fromEntries(Object.entries(options2).filter(([_, v]) => v != null)) : {};
  const { maxAttempts, initialDelayMs, maxDelayMs, onPersistent429, authType, shouldRetryOnError, shouldRetryOnContent } = {
    ...DEFAULT_RETRY_OPTIONS,
    ...cleanOptions
  };
  let attempt = 0;
  let currentDelay = initialDelayMs;
  let consecutive429Count = 0;
  while (attempt < maxAttempts) {
    attempt++;
    try {
      const result = await fn();
      if (shouldRetryOnContent && shouldRetryOnContent(result)) {
        const jitter = currentDelay * 0.3 * (Math.random() * 2 - 1);
        const delayWithJitter = Math.max(0, currentDelay + jitter);
        await delay(delayWithJitter);
        currentDelay = Math.min(maxDelayMs, currentDelay * 2);
        continue;
      }
      return result;
    } catch (error) {
      const errorStatus = getErrorStatus(error);
      if (errorStatus === 429 && authType === AuthType2.LOGIN_WITH_GOOGLE && isProQuotaExceededError(error) && onPersistent429) {
        try {
          const fallbackModel = await onPersistent429(authType, error);
          if (fallbackModel !== false && fallbackModel !== null) {
            attempt = 0;
            consecutive429Count = 0;
            currentDelay = initialDelayMs;
            continue;
          } else {
            throw error;
          }
        } catch (fallbackError) {
          console.warn("Fallback to Flash model failed:", fallbackError);
        }
      }
      if (errorStatus === 429 && authType === AuthType2.LOGIN_WITH_GOOGLE && !isProQuotaExceededError(error) && isGenericQuotaExceededError(error) && onPersistent429) {
        try {
          const fallbackModel = await onPersistent429(authType, error);
          if (fallbackModel !== false && fallbackModel !== null) {
            attempt = 0;
            consecutive429Count = 0;
            currentDelay = initialDelayMs;
            continue;
          } else {
            throw error;
          }
        } catch (fallbackError) {
          console.warn("Fallback to Flash model failed:", fallbackError);
        }
      }
      if (authType === AuthType2.QWEN_OAUTH && isQwenQuotaExceededError(error)) {
        throw new Error(`Qwen API quota exceeded: Your Qwen API quota has been exhausted. Please wait for your quota to reset.`);
      }
      if (errorStatus === 429) {
        if (authType === AuthType2.QWEN_OAUTH && isQwenThrottlingError(error)) {
          consecutive429Count = 0;
        } else {
          consecutive429Count++;
        }
      } else {
        consecutive429Count = 0;
      }
      if (consecutive429Count >= 2 && onPersistent429 && authType === AuthType2.LOGIN_WITH_GOOGLE) {
        try {
          const fallbackModel = await onPersistent429(authType, error);
          if (fallbackModel !== false && fallbackModel !== null) {
            attempt = 0;
            consecutive429Count = 0;
            currentDelay = initialDelayMs;
            continue;
          } else {
            throw error;
          }
        } catch (fallbackError) {
          console.warn("Fallback to Flash model failed:", fallbackError);
        }
      }
      if (attempt >= maxAttempts || !shouldRetryOnError(error)) {
        throw error;
      }
      const { delayDurationMs, errorStatus: delayErrorStatus } = getDelayDurationAndStatus(error);
      if (delayDurationMs > 0) {
        console.warn(`Attempt ${attempt} failed with status ${delayErrorStatus ?? "unknown"}. Retrying after explicit delay of ${delayDurationMs}ms...`, error);
        await delay(delayDurationMs);
        currentDelay = initialDelayMs;
      } else {
        logRetryAttempt(attempt, error, errorStatus);
        const jitter = currentDelay * 0.3 * (Math.random() * 2 - 1);
        const delayWithJitter = Math.max(0, currentDelay + jitter);
        await delay(delayWithJitter);
        currentDelay = Math.min(maxDelayMs, currentDelay * 2);
      }
    }
  }
  throw new Error("Retry attempts exhausted");
}
function getErrorStatus(error) {
  if (typeof error === "object" && error !== null) {
    if ("status" in error && typeof error.status === "number") {
      return error.status;
    }
    if ("response" in error && typeof error.response === "object" && error.response !== null) {
      const response = error.response;
      if ("status" in response && typeof response.status === "number") {
        return response.status;
      }
    }
  }
  return void 0;
}
function getRetryAfterDelayMs(error) {
  if (typeof error === "object" && error !== null) {
    if ("response" in error && typeof error.response === "object" && error.response !== null) {
      const response = error.response;
      if ("headers" in response && typeof response.headers === "object" && response.headers !== null) {
        const headers = response.headers;
        const retryAfterHeader = headers["retry-after"];
        if (typeof retryAfterHeader === "string") {
          const retryAfterSeconds = parseInt(retryAfterHeader, 10);
          if (!isNaN(retryAfterSeconds)) {
            return retryAfterSeconds * 1e3;
          }
          const retryAfterDate = new Date(retryAfterHeader);
          if (!isNaN(retryAfterDate.getTime())) {
            return Math.max(0, retryAfterDate.getTime() - Date.now());
          }
        }
      }
    }
  }
  return 0;
}
function getDelayDurationAndStatus(error) {
  const errorStatus = getErrorStatus(error);
  let delayDurationMs = 0;
  if (errorStatus === 429) {
    delayDurationMs = getRetryAfterDelayMs(error);
  }
  return { delayDurationMs, errorStatus };
}
function logRetryAttempt(attempt, error, errorStatus) {
  let message = `Attempt ${attempt} failed. Retrying with backoff...`;
  if (errorStatus) {
    message = `Attempt ${attempt} failed with status ${errorStatus}. Retrying with backoff...`;
  }
  if (errorStatus === 429) {
    console.warn(message, error);
  } else if (errorStatus && errorStatus >= 500 && errorStatus < 600) {
    console.error(message, error);
  } else if (error instanceof Error) {
    if (error.message.includes("429")) {
      console.warn(`Attempt ${attempt} failed with 429 error (no Retry-After header). Retrying with backoff...`, error);
    } else if (error.message.match(/5\d{2}/)) {
      console.error(`Attempt ${attempt} failed with 5xx error. Retrying with backoff...`, error);
    } else {
      console.warn(message, error);
    }
  } else {
    console.warn(message, error);
  }
}
var DEFAULT_RETRY_OPTIONS;
var init_retry = __esm({
  "packages/core/dist/src/utils/retry.js"() {
    "use strict";
    init_esbuild_shims();
    init_contentGenerator();
    init_quotaErrorDetection();
    DEFAULT_RETRY_OPTIONS = {
      maxAttempts: 5,
      initialDelayMs: 5e3,
      maxDelayMs: 3e4,
      // 30 seconds
      shouldRetryOnError: defaultShouldRetry
    };
    __name(defaultShouldRetry, "defaultShouldRetry");
    __name(delay, "delay");
    __name(retryWithBackoff, "retryWithBackoff");
    __name(getErrorStatus, "getErrorStatus");
    __name(getRetryAfterDelayMs, "getRetryAfterDelayMs");
    __name(getDelayDurationAndStatus, "getDelayDurationAndStatus");
    __name(logRetryAttempt, "logRetryAttempt");
  }
});

// packages/core/dist/src/utils/partUtils.js
function partToString(value, options2) {
  if (!value) {
    return "";
  }
  if (typeof value === "string") {
    return value;
  }
  if (Array.isArray(value)) {
    return value.map((part2) => partToString(part2, options2)).join("");
  }
  const part = value;
  if (options2?.verbose) {
    if (part.videoMetadata !== void 0) {
      return `[Video Metadata]`;
    }
    if (part.thought !== void 0) {
      return `[Thought: ${part.thought}]`;
    }
    if (part.codeExecutionResult !== void 0) {
      return `[Code Execution Result]`;
    }
    if (part.executableCode !== void 0) {
      return `[Executable Code]`;
    }
    if (part.fileData !== void 0) {
      return `[File Data]`;
    }
    if (part.functionCall !== void 0) {
      return `[Function Call: ${part.functionCall.name}]`;
    }
    if (part.functionResponse !== void 0) {
      return `[Function Response: ${part.functionResponse.name}]`;
    }
    if (part.inlineData !== void 0) {
      return `<${part.inlineData.mimeType}>`;
    }
  }
  return part.text ?? "";
}
function getResponseText(response) {
  if (response.candidates && response.candidates.length > 0) {
    const candidate = response.candidates[0];
    if (candidate.content && candidate.content.parts && candidate.content.parts.length > 0) {
      return candidate.content.parts.filter((part) => part.text).map((part) => part.text).join("");
    }
  }
  return null;
}
async function flatMapTextParts(parts, transform) {
  const result = [];
  const partArray = Array.isArray(parts) ? parts : typeof parts === "string" ? [{ text: parts }] : [parts];
  for (const part of partArray) {
    let textToProcess;
    if (typeof part === "string") {
      textToProcess = part;
    } else if ("text" in part) {
      textToProcess = part.text;
    }
    if (textToProcess !== void 0) {
      const transformedParts = await transform(textToProcess);
      result.push(...transformedParts);
    } else {
      result.push(part);
    }
  }
  return result;
}
function appendToLastTextPart(prompt, textToAppend, separator = "\n\n") {
  if (!textToAppend) {
    return prompt;
  }
  if (prompt.length === 0) {
    return [{ text: textToAppend }];
  }
  const newPrompt = [...prompt];
  const lastPart = newPrompt.at(-1);
  if (typeof lastPart === "string") {
    newPrompt[newPrompt.length - 1] = `${lastPart}${separator}${textToAppend}`;
  } else if (lastPart && "text" in lastPart) {
    newPrompt[newPrompt.length - 1] = {
      ...lastPart,
      text: `${lastPart.text}${separator}${textToAppend}`
    };
  } else {
    newPrompt.push({ text: `${separator}${textToAppend}` });
  }
  return newPrompt;
}
var init_partUtils = __esm({
  "packages/core/dist/src/utils/partUtils.js"() {
    "use strict";
    init_esbuild_shims();
    __name(partToString, "partToString");
    __name(getResponseText, "getResponseText");
    __name(flatMapTextParts, "flatMapTextParts");
    __name(appendToLastTextPart, "appendToLastTextPart");
  }
});

// packages/core/dist/src/utils/generateContentResponseUtilities.js
function getResponseTextFromParts(parts) {
  if (!parts) {
    return void 0;
  }
  const textSegments = parts.map((part) => part.text).filter((text) => typeof text === "string");
  if (textSegments.length === 0) {
    return void 0;
  }
  return textSegments.join("");
}
function getFunctionCalls(response) {
  const parts = response.candidates?.[0]?.content?.parts;
  if (!parts) {
    return void 0;
  }
  const functionCallParts = parts.filter((part) => !!part.functionCall).map((part) => part.functionCall);
  return functionCallParts.length > 0 ? functionCallParts : void 0;
}
var init_generateContentResponseUtilities = __esm({
  "packages/core/dist/src/utils/generateContentResponseUtilities.js"() {
    "use strict";
    init_esbuild_shims();
    init_partUtils();
    __name(getResponseTextFromParts, "getResponseTextFromParts");
    __name(getFunctionCalls, "getFunctionCalls");
  }
});

// packages/core/dist/src/core/baseLlmClient.js
var DEFAULT_MAX_ATTEMPTS, BaseLlmClient;
var init_baseLlmClient = __esm({
  "packages/core/dist/src/core/baseLlmClient.js"() {
    "use strict";
    init_esbuild_shims();
    init_errorReporting();
    init_errors();
    init_retry();
    init_generateContentResponseUtilities();
    DEFAULT_MAX_ATTEMPTS = 5;
    BaseLlmClient = class {
      static {
        __name(this, "BaseLlmClient");
      }
      contentGenerator;
      config;
      // Default configuration for utility tasks
      defaultUtilityConfig = {
        temperature: 0,
        topP: 1
      };
      constructor(contentGenerator, config) {
        this.contentGenerator = contentGenerator;
        this.config = config;
      }
      async generateJson(options2) {
        const { contents, schema, model, abortSignal, systemInstruction, promptId, maxAttempts } = options2;
        const requestConfig = {
          abortSignal,
          ...this.defaultUtilityConfig,
          ...options2.config,
          ...systemInstruction && { systemInstruction }
        };
        const functionDeclaration = {
          name: "respond_in_schema",
          description: "Provide the response in provided schema",
          parameters: schema
        };
        const tools = [
          {
            functionDeclarations: [functionDeclaration]
          }
        ];
        try {
          const apiCall = /* @__PURE__ */ __name(() => this.contentGenerator.generateContent({
            model,
            config: {
              ...requestConfig,
              tools
            },
            contents
          }, promptId ?? ""), "apiCall");
          const result = await retryWithBackoff(apiCall, {
            maxAttempts: maxAttempts ?? DEFAULT_MAX_ATTEMPTS
          });
          const functionCalls = getFunctionCalls(result);
          if (functionCalls && functionCalls.length > 0) {
            const functionCall = functionCalls.find((call) => call.name === "respond_in_schema");
            if (functionCall && functionCall.args) {
              return functionCall.args;
            }
          }
          return {};
        } catch (error) {
          if (abortSignal.aborted) {
            throw error;
          }
          if (error instanceof Error && error.message === "API returned an empty response for generateJson.") {
            throw error;
          }
          await reportError2(error, "Error generating JSON content via API.", contents, "generateJson-api");
          throw new Error(`Failed to generate JSON content: ${getErrorMessage(error)}`);
        }
      }
      async generateEmbedding(texts) {
        if (!texts || texts.length === 0) {
          return [];
        }
        const embedModelParams = {
          model: this.config.getEmbeddingModel(),
          contents: texts
        };
        const embedContentResponse = await this.contentGenerator.embedContent(embedModelParams);
        if (!embedContentResponse.embeddings || embedContentResponse.embeddings.length === 0) {
          throw new Error("No embeddings found in API response.");
        }
        if (embedContentResponse.embeddings.length !== texts.length) {
          throw new Error(`API returned a mismatched number of embeddings. Expected ${texts.length}, got ${embedContentResponse.embeddings.length}.`);
        }
        return embedContentResponse.embeddings.map((embedding, index) => {
          const values = embedding.values;
          if (!values || values.length === 0) {
            throw new Error(`API returned an empty embedding for input text at index ${index}: "${texts[index]}"`);
          }
          return values;
        });
      }
    };
  }
});

// packages/core/dist/src/utils/editor.js
import { execSync, spawn, spawnSync } from "node:child_process";
function isValidEditorType(editor) {
  return [
    "vscode",
    "vscodium",
    "windsurf",
    "cursor",
    "vim",
    "neovim",
    "zed",
    "emacs",
    "trae"
  ].includes(editor);
}
function commandExists(cmd) {
  try {
    execSync(process.platform === "win32" ? `where.exe ${cmd}` : `command -v ${cmd}`, { stdio: "ignore" });
    return true;
  } catch {
    return false;
  }
}
function checkHasEditorType(editor) {
  const commandConfig = editorCommands[editor];
  const commands = process.platform === "win32" ? commandConfig.win32 : commandConfig.default;
  return commands.some((cmd) => commandExists(cmd));
}
function allowEditorTypeInSandbox(editor) {
  const notUsingSandbox = !process.env["SANDBOX"];
  if (["vscode", "vscodium", "windsurf", "cursor", "zed", "trae"].includes(editor)) {
    return notUsingSandbox;
  }
  return true;
}
function isEditorAvailable(editor) {
  if (editor && isValidEditorType(editor)) {
    return checkHasEditorType(editor) && allowEditorTypeInSandbox(editor);
  }
  return false;
}
function getDiffCommand(oldPath, newPath, editor) {
  if (!isValidEditorType(editor)) {
    return null;
  }
  const commandConfig = editorCommands[editor];
  const commands = process.platform === "win32" ? commandConfig.win32 : commandConfig.default;
  const command2 = commands.slice(0, -1).find((cmd) => commandExists(cmd)) || commands[commands.length - 1];
  switch (editor) {
    case "vscode":
    case "vscodium":
    case "windsurf":
    case "cursor":
    case "zed":
    case "trae":
      return { command: command2, args: ["--wait", "--diff", oldPath, newPath] };
    case "vim":
    case "neovim":
      return {
        command: command2,
        args: [
          "-d",
          // skip viminfo file to avoid E138 errors
          "-i",
          "NONE",
          // make the left window read-only and the right window editable
          "-c",
          "wincmd h | set readonly | wincmd l",
          // set up colors for diffs
          "-c",
          "highlight DiffAdd cterm=bold ctermbg=22 guibg=#005f00 | highlight DiffChange cterm=bold ctermbg=24 guibg=#005f87 | highlight DiffText ctermbg=21 guibg=#0000af | highlight DiffDelete ctermbg=52 guibg=#5f0000",
          // Show helpful messages
          "-c",
          "set showtabline=2 | set tabline=[Instructions]\\ :wqa(save\\ &\\ quit)\\ \\|\\ i/esc(toggle\\ edit\\ mode)",
          "-c",
          "wincmd h | setlocal statusline=OLD\\ FILE",
          "-c",
          "wincmd l | setlocal statusline=%#StatusBold#NEW\\ FILE\\ :wqa(save\\ &\\ quit)\\ \\|\\ i/esc(toggle\\ edit\\ mode)",
          // Auto close all windows when one is closed
          "-c",
          "autocmd BufWritePost * wqa",
          oldPath,
          newPath
        ]
      };
    case "emacs":
      return {
        command: "emacs",
        args: ["--eval", `(ediff "${oldPath}" "${newPath}")`]
      };
    default:
      return null;
  }
}
async function openDiff(oldPath, newPath, editor, onEditorClose) {
  const diffCommand = getDiffCommand(oldPath, newPath, editor);
  if (!diffCommand) {
    console.error("No diff tool available. Install a supported editor.");
    return;
  }
  try {
    const isTerminalEditor = ["vim", "emacs", "neovim"].includes(editor);
    if (isTerminalEditor) {
      try {
        const result = spawnSync(diffCommand.command, diffCommand.args, {
          stdio: "inherit"
        });
        if (result.error) {
          throw result.error;
        }
        if (result.status !== 0) {
          throw new Error(`${editor} exited with code ${result.status}`);
        }
      } finally {
        onEditorClose();
      }
      return;
    }
    return new Promise((resolve24, reject) => {
      const childProcess3 = spawn(diffCommand.command, diffCommand.args, {
        stdio: "inherit",
        shell: process.platform === "win32"
      });
      childProcess3.on("close", (code2) => {
        if (code2 === 0) {
          resolve24();
        } else {
          reject(new Error(`${editor} exited with code ${code2}`));
        }
      });
      childProcess3.on("error", (error) => {
        reject(error);
      });
    });
  } catch (error) {
    console.error(error);
    throw error;
  }
}
var editorCommands;
var init_editor = __esm({
  "packages/core/dist/src/utils/editor.js"() {
    "use strict";
    init_esbuild_shims();
    __name(isValidEditorType, "isValidEditorType");
    __name(commandExists, "commandExists");
    editorCommands = {
      vscode: { win32: ["code.cmd"], default: ["code"] },
      vscodium: { win32: ["codium.cmd"], default: ["codium"] },
      windsurf: { win32: ["windsurf"], default: ["windsurf"] },
      cursor: { win32: ["cursor"], default: ["cursor"] },
      vim: { win32: ["vim"], default: ["vim"] },
      neovim: { win32: ["nvim"], default: ["nvim"] },
      zed: { win32: ["zed"], default: ["zed", "zeditor"] },
      emacs: { win32: ["emacs.exe"], default: ["emacs"] },
      trae: { win32: ["trae"], default: ["trae"] }
    };
    __name(checkHasEditorType, "checkHasEditorType");
    __name(allowEditorTypeInSandbox, "allowEditorTypeInSandbox");
    __name(isEditorAvailable, "isEditorAvailable");
    __name(getDiffCommand, "getDiffCommand");
    __name(openDiff, "openDiff");
  }
});

// node_modules/diff/lib/index.mjs
function Diff() {
}
function buildValues(diff4, lastComponent, newString, oldString, useLongestToken) {
  var components = [];
  var nextComponent;
  while (lastComponent) {
    components.push(lastComponent);
    nextComponent = lastComponent.previousComponent;
    delete lastComponent.previousComponent;
    lastComponent = nextComponent;
  }
  components.reverse();
  var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0;
  for (; componentPos < componentLen; componentPos++) {
    var component = components[componentPos];
    if (!component.removed) {
      if (!component.added && useLongestToken) {
        var value = newString.slice(newPos, newPos + component.count);
        value = value.map(function(value2, i) {
          var oldValue = oldString[oldPos + i];
          return oldValue.length > value2.length ? oldValue : value2;
        });
        component.value = diff4.join(value);
      } else {
        component.value = diff4.join(newString.slice(newPos, newPos + component.count));
      }
      newPos += component.count;
      if (!component.added) {
        oldPos += component.count;
      }
    } else {
      component.value = diff4.join(oldString.slice(oldPos, oldPos + component.count));
      oldPos += component.count;
    }
  }
  return components;
}
function longestCommonPrefix(str1, str2) {
  var i;
  for (i = 0; i < str1.length && i < str2.length; i++) {
    if (str1[i] != str2[i]) {
      return str1.slice(0, i);
    }
  }
  return str1.slice(0, i);
}
function longestCommonSuffix(str1, str2) {
  var i;
  if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) {
    return "";
  }
  for (i = 0; i < str1.length && i < str2.length; i++) {
    if (str1[str1.length - (i + 1)] != str2[str2.length - (i + 1)]) {
      return str1.slice(-i);
    }
  }
  return str1.slice(-i);
}
function replacePrefix(string, oldPrefix, newPrefix) {
  if (string.slice(0, oldPrefix.length) != oldPrefix) {
    throw Error("string ".concat(JSON.stringify(string), " doesn't start with prefix ").concat(JSON.stringify(oldPrefix), "; this is a bug"));
  }
  return newPrefix + string.slice(oldPrefix.length);
}
function replaceSuffix(string, oldSuffix, newSuffix) {
  if (!oldSuffix) {
    return string + newSuffix;
  }
  if (string.slice(-oldSuffix.length) != oldSuffix) {
    throw Error("string ".concat(JSON.stringify(string), " doesn't end with suffix ").concat(JSON.stringify(oldSuffix), "; this is a bug"));
  }
  return string.slice(0, -oldSuffix.length) + newSuffix;
}
function removePrefix(string, oldPrefix) {
  return replacePrefix(string, oldPrefix, "");
}
function removeSuffix(string, oldSuffix) {
  return replaceSuffix(string, oldSuffix, "");
}
function maximumOverlap(string12, string22) {
  return string22.slice(0, overlapCount(string12, string22));
}
function overlapCount(a, b) {
  var startA = 0;
  if (a.length > b.length) {
    startA = a.length - b.length;
  }
  var endB = b.length;
  if (a.length < b.length) {
    endB = a.length;
  }
  var map2 = Array(endB);
  var k = 0;
  map2[0] = 0;
  for (var j = 1; j < endB; j++) {
    if (b[j] == b[k]) {
      map2[j] = map2[k];
    } else {
      map2[j] = k;
    }
    while (k > 0 && b[j] != b[k]) {
      k = map2[k];
    }
    if (b[j] == b[k]) {
      k++;
    }
  }
  k = 0;
  for (var i = startA; i < a.length; i++) {
    while (k > 0 && a[i] != b[k]) {
      k = map2[k];
    }
    if (a[i] == b[k]) {
      k++;
    }
  }
  return k;
}
function dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep) {
  if (deletion && insertion) {
    var oldWsPrefix = deletion.value.match(/^\s*/)[0];
    var oldWsSuffix = deletion.value.match(/\s*$/)[0];
    var newWsPrefix = insertion.value.match(/^\s*/)[0];
    var newWsSuffix = insertion.value.match(/\s*$/)[0];
    if (startKeep) {
      var commonWsPrefix = longestCommonPrefix(oldWsPrefix, newWsPrefix);
      startKeep.value = replaceSuffix(startKeep.value, newWsPrefix, commonWsPrefix);
      deletion.value = removePrefix(deletion.value, commonWsPrefix);
      insertion.value = removePrefix(insertion.value, commonWsPrefix);
    }
    if (endKeep) {
      var commonWsSuffix = longestCommonSuffix(oldWsSuffix, newWsSuffix);
      endKeep.value = replacePrefix(endKeep.value, newWsSuffix, commonWsSuffix);
      deletion.value = removeSuffix(deletion.value, commonWsSuffix);
      insertion.value = removeSuffix(insertion.value, commonWsSuffix);
    }
  } else if (insertion) {
    if (startKeep) {
      insertion.value = insertion.value.replace(/^\s*/, "");
    }
    if (endKeep) {
      endKeep.value = endKeep.value.replace(/^\s*/, "");
    }
  } else if (startKeep && endKeep) {
    var newWsFull = endKeep.value.match(/^\s*/)[0], delWsStart = deletion.value.match(/^\s*/)[0], delWsEnd = deletion.value.match(/\s*$/)[0];
    var newWsStart = longestCommonPrefix(newWsFull, delWsStart);
    deletion.value = removePrefix(deletion.value, newWsStart);
    var newWsEnd = longestCommonSuffix(removePrefix(newWsFull, newWsStart), delWsEnd);
    deletion.value = removeSuffix(deletion.value, newWsEnd);
    endKeep.value = replacePrefix(endKeep.value, newWsFull, newWsEnd);
    startKeep.value = replaceSuffix(startKeep.value, newWsFull, newWsFull.slice(0, newWsFull.length - newWsEnd.length));
  } else if (endKeep) {
    var endKeepWsPrefix = endKeep.value.match(/^\s*/)[0];
    var deletionWsSuffix = deletion.value.match(/\s*$/)[0];
    var overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix);
    deletion.value = removeSuffix(deletion.value, overlap);
  } else if (startKeep) {
    var startKeepWsSuffix = startKeep.value.match(/\s*$/)[0];
    var deletionWsPrefix = deletion.value.match(/^\s*/)[0];
    var _overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix);
    deletion.value = removePrefix(deletion.value, _overlap);
  }
}
function diffLines(oldStr, newStr, callback) {
  return lineDiff.diff(oldStr, newStr, callback);
}
function ownKeys(e2, r3) {
  var t2 = Object.keys(e2);
  if (Object.getOwnPropertySymbols) {
    var o2 = Object.getOwnPropertySymbols(e2);
    r3 && (o2 = o2.filter(function(r4) {
      return Object.getOwnPropertyDescriptor(e2, r4).enumerable;
    })), t2.push.apply(t2, o2);
  }
  return t2;
}
function _objectSpread2(e2) {
  for (var r3 = 1; r3 < arguments.length; r3++) {
    var t2 = null != arguments[r3] ? arguments[r3] : {};
    r3 % 2 ? ownKeys(Object(t2), true).forEach(function(r4) {
      _defineProperty(e2, r4, t2[r4]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(t2)) : ownKeys(Object(t2)).forEach(function(r4) {
      Object.defineProperty(e2, r4, Object.getOwnPropertyDescriptor(t2, r4));
    });
  }
  return e2;
}
function _toPrimitive(t2, r3) {
  if ("object" != typeof t2 || !t2) return t2;
  var e2 = t2[Symbol.toPrimitive];
  if (void 0 !== e2) {
    var i = e2.call(t2, r3 || "default");
    if ("object" != typeof i) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r3 ? String : Number)(t2);
}
function _toPropertyKey(t2) {
  var i = _toPrimitive(t2, "string");
  return "symbol" == typeof i ? i : i + "";
}
function _typeof(o2) {
  "@babel/helpers - typeof";
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o3) {
    return typeof o3;
  } : function(o3) {
    return o3 && "function" == typeof Symbol && o3.constructor === Symbol && o3 !== Symbol.prototype ? "symbol" : typeof o3;
  }, _typeof(o2);
}
function _defineProperty(obj, key, value) {
  key = _toPropertyKey(key);
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _toConsumableArray(arr) {
  return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray(o2, minLen) {
  if (!o2) return;
  if (typeof o2 === "string") return _arrayLikeToArray(o2, minLen);
  var n2 = Object.prototype.toString.call(o2).slice(8, -1);
  if (n2 === "Object" && o2.constructor) n2 = o2.constructor.name;
  if (n2 === "Map" || n2 === "Set") return Array.from(o2);
  if (n2 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n2)) return _arrayLikeToArray(o2, minLen);
}
function _arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function canonicalize(obj, stack, replacementStack, replacer, key) {
  stack = stack || [];
  replacementStack = replacementStack || [];
  if (replacer) {
    obj = replacer(key, obj);
  }
  var i;
  for (i = 0; i < stack.length; i += 1) {
    if (stack[i] === obj) {
      return replacementStack[i];
    }
  }
  var canonicalizedObj;
  if ("[object Array]" === Object.prototype.toString.call(obj)) {
    stack.push(obj);
    canonicalizedObj = new Array(obj.length);
    replacementStack.push(canonicalizedObj);
    for (i = 0; i < obj.length; i += 1) {
      canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
    }
    stack.pop();
    replacementStack.pop();
    return canonicalizedObj;
  }
  if (obj && obj.toJSON) {
    obj = obj.toJSON();
  }
  if (_typeof(obj) === "object" && obj !== null) {
    stack.push(obj);
    canonicalizedObj = {};
    replacementStack.push(canonicalizedObj);
    var sortedKeys = [], _key;
    for (_key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, _key)) {
        sortedKeys.push(_key);
      }
    }
    sortedKeys.sort();
    for (i = 0; i < sortedKeys.length; i += 1) {
      _key = sortedKeys[i];
      canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
    }
    stack.pop();
    replacementStack.pop();
  } else {
    canonicalizedObj = obj;
  }
  return canonicalizedObj;
}
function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options2) {
  if (!options2) {
    options2 = {};
  }
  if (typeof options2 === "function") {
    options2 = {
      callback: options2
    };
  }
  if (typeof options2.context === "undefined") {
    options2.context = 4;
  }
  if (options2.newlineIsToken) {
    throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");
  }
  if (!options2.callback) {
    return diffLinesResultToPatch(diffLines(oldStr, newStr, options2));
  } else {
    var _options = options2, _callback = _options.callback;
    diffLines(oldStr, newStr, _objectSpread2(_objectSpread2({}, options2), {}, {
      callback: /* @__PURE__ */ __name(function callback(diff4) {
        var patch = diffLinesResultToPatch(diff4);
        _callback(patch);
      }, "callback")
    }));
  }
  function diffLinesResultToPatch(diff4) {
    if (!diff4) {
      return;
    }
    diff4.push({
      value: "",
      lines: []
    });
    function contextLines(lines) {
      return lines.map(function(entry) {
        return " " + entry;
      });
    }
    __name(contextLines, "contextLines");
    var hunks = [];
    var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1;
    var _loop = /* @__PURE__ */ __name(function _loop2() {
      var current = diff4[i], lines = current.lines || splitLines(current.value);
      current.lines = lines;
      if (current.added || current.removed) {
        var _curRange;
        if (!oldRangeStart) {
          var prev = diff4[i - 1];
          oldRangeStart = oldLine;
          newRangeStart = newLine;
          if (prev) {
            curRange = options2.context > 0 ? contextLines(prev.lines.slice(-options2.context)) : [];
            oldRangeStart -= curRange.length;
            newRangeStart -= curRange.length;
          }
        }
        (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function(entry) {
          return (current.added ? "+" : "-") + entry;
        })));
        if (current.added) {
          newLine += lines.length;
        } else {
          oldLine += lines.length;
        }
      } else {
        if (oldRangeStart) {
          if (lines.length <= options2.context * 2 && i < diff4.length - 2) {
            var _curRange2;
            (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
          } else {
            var _curRange3;
            var contextSize = Math.min(lines.length, options2.context);
            (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
            var _hunk = {
              oldStart: oldRangeStart,
              oldLines: oldLine - oldRangeStart + contextSize,
              newStart: newRangeStart,
              newLines: newLine - newRangeStart + contextSize,
              lines: curRange
            };
            hunks.push(_hunk);
            oldRangeStart = 0;
            newRangeStart = 0;
            curRange = [];
          }
        }
        oldLine += lines.length;
        newLine += lines.length;
      }
    }, "_loop");
    for (var i = 0; i < diff4.length; i++) {
      _loop();
    }
    for (var _i = 0, _hunks = hunks; _i < _hunks.length; _i++) {
      var hunk = _hunks[_i];
      for (var _i2 = 0; _i2 < hunk.lines.length; _i2++) {
        if (hunk.lines[_i2].endsWith("\n")) {
          hunk.lines[_i2] = hunk.lines[_i2].slice(0, -1);
        } else {
          hunk.lines.splice(_i2 + 1, 0, "\\ No newline at end of file");
          _i2++;
        }
      }
    }
    return {
      oldFileName,
      newFileName,
      oldHeader,
      newHeader,
      hunks
    };
  }
  __name(diffLinesResultToPatch, "diffLinesResultToPatch");
}
function formatPatch(diff4) {
  if (Array.isArray(diff4)) {
    return diff4.map(formatPatch).join("\n");
  }
  var ret = [];
  if (diff4.oldFileName == diff4.newFileName) {
    ret.push("Index: " + diff4.oldFileName);
  }
  ret.push("===================================================================");
  ret.push("--- " + diff4.oldFileName + (typeof diff4.oldHeader === "undefined" ? "" : "	" + diff4.oldHeader));
  ret.push("+++ " + diff4.newFileName + (typeof diff4.newHeader === "undefined" ? "" : "	" + diff4.newHeader));
  for (var i = 0; i < diff4.hunks.length; i++) {
    var hunk = diff4.hunks[i];
    if (hunk.oldLines === 0) {
      hunk.oldStart -= 1;
    }
    if (hunk.newLines === 0) {
      hunk.newStart -= 1;
    }
    ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@");
    ret.push.apply(ret, hunk.lines);
  }
  return ret.join("\n") + "\n";
}
function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options2) {
  var _options2;
  if (typeof options2 === "function") {
    options2 = {
      callback: options2
    };
  }
  if (!((_options2 = options2) !== null && _options2 !== void 0 && _options2.callback)) {
    var patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options2);
    if (!patchObj) {
      return;
    }
    return formatPatch(patchObj);
  } else {
    var _options3 = options2, _callback2 = _options3.callback;
    structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, _objectSpread2(_objectSpread2({}, options2), {}, {
      callback: /* @__PURE__ */ __name(function callback(patchObj2) {
        if (!patchObj2) {
          _callback2();
        } else {
          _callback2(formatPatch(patchObj2));
        }
      }, "callback")
    }));
  }
}
function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options2) {
  return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options2);
}
function splitLines(text) {
  var hasTrailingNl = text.endsWith("\n");
  var result = text.split("\n").map(function(line) {
    return line + "\n";
  });
  if (hasTrailingNl) {
    result.pop();
  } else {
    result.push(result.pop().slice(0, -1));
  }
  return result;
}
var characterDiff, extendedWordChars, tokenizeIncludingWhitespace, wordDiff, wordWithSpaceDiff, lineDiff, sentenceDiff, cssDiff, jsonDiff, arrayDiff;
var init_lib = __esm({
  "node_modules/diff/lib/index.mjs"() {
    init_esbuild_shims();
    __name(Diff, "Diff");
    Diff.prototype = {
      diff: /* @__PURE__ */ __name(function diff2(oldString, newString) {
        var _options$timeout;
        var options2 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
        var callback = options2.callback;
        if (typeof options2 === "function") {
          callback = options2;
          options2 = {};
        }
        var self2 = this;
        function done(value) {
          value = self2.postProcess(value, options2);
          if (callback) {
            setTimeout(function() {
              callback(value);
            }, 0);
            return true;
          } else {
            return value;
          }
        }
        __name(done, "done");
        oldString = this.castInput(oldString, options2);
        newString = this.castInput(newString, options2);
        oldString = this.removeEmpty(this.tokenize(oldString, options2));
        newString = this.removeEmpty(this.tokenize(newString, options2));
        var newLen = newString.length, oldLen = oldString.length;
        var editLength = 1;
        var maxEditLength = newLen + oldLen;
        if (options2.maxEditLength != null) {
          maxEditLength = Math.min(maxEditLength, options2.maxEditLength);
        }
        var maxExecutionTime = (_options$timeout = options2.timeout) !== null && _options$timeout !== void 0 ? _options$timeout : Infinity;
        var abortAfterTimestamp = Date.now() + maxExecutionTime;
        var bestPath = [{
          oldPos: -1,
          lastComponent: void 0
        }];
        var newPos = this.extractCommon(bestPath[0], newString, oldString, 0, options2);
        if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
          return done(buildValues(self2, bestPath[0].lastComponent, newString, oldString, self2.useLongestToken));
        }
        var minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
        function execEditLength() {
          for (var diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
            var basePath = void 0;
            var removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
            if (removePath) {
              bestPath[diagonalPath - 1] = void 0;
            }
            var canAdd = false;
            if (addPath) {
              var addPathNewPos = addPath.oldPos - diagonalPath;
              canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
            }
            var canRemove = removePath && removePath.oldPos + 1 < oldLen;
            if (!canAdd && !canRemove) {
              bestPath[diagonalPath] = void 0;
              continue;
            }
            if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {
              basePath = self2.addToPath(addPath, true, false, 0, options2);
            } else {
              basePath = self2.addToPath(removePath, false, true, 1, options2);
            }
            newPos = self2.extractCommon(basePath, newString, oldString, diagonalPath, options2);
            if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
              return done(buildValues(self2, basePath.lastComponent, newString, oldString, self2.useLongestToken));
            } else {
              bestPath[diagonalPath] = basePath;
              if (basePath.oldPos + 1 >= oldLen) {
                maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
              }
              if (newPos + 1 >= newLen) {
                minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
              }
            }
          }
          editLength++;
        }
        __name(execEditLength, "execEditLength");
        if (callback) {
          (/* @__PURE__ */ __name(function exec5() {
            setTimeout(function() {
              if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
                return callback();
              }
              if (!execEditLength()) {
                exec5();
              }
            }, 0);
          }, "exec"))();
        } else {
          while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
            var ret = execEditLength();
            if (ret) {
              return ret;
            }
          }
        }
      }, "diff"),
      addToPath: /* @__PURE__ */ __name(function addToPath(path108, added, removed, oldPosInc, options2) {
        var last2 = path108.lastComponent;
        if (last2 && !options2.oneChangePerToken && last2.added === added && last2.removed === removed) {
          return {
            oldPos: path108.oldPos + oldPosInc,
            lastComponent: {
              count: last2.count + 1,
              added,
              removed,
              previousComponent: last2.previousComponent
            }
          };
        } else {
          return {
            oldPos: path108.oldPos + oldPosInc,
            lastComponent: {
              count: 1,
              added,
              removed,
              previousComponent: last2
            }
          };
        }
      }, "addToPath"),
      extractCommon: /* @__PURE__ */ __name(function extractCommon(basePath, newString, oldString, diagonalPath, options2) {
        var newLen = newString.length, oldLen = oldString.length, oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
        while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldString[oldPos + 1], newString[newPos + 1], options2)) {
          newPos++;
          oldPos++;
          commonCount++;
          if (options2.oneChangePerToken) {
            basePath.lastComponent = {
              count: 1,
              previousComponent: basePath.lastComponent,
              added: false,
              removed: false
            };
          }
        }
        if (commonCount && !options2.oneChangePerToken) {
          basePath.lastComponent = {
            count: commonCount,
            previousComponent: basePath.lastComponent,
            added: false,
            removed: false
          };
        }
        basePath.oldPos = oldPos;
        return newPos;
      }, "extractCommon"),
      equals: /* @__PURE__ */ __name(function equals(left3, right3, options2) {
        if (options2.comparator) {
          return options2.comparator(left3, right3);
        } else {
          return left3 === right3 || options2.ignoreCase && left3.toLowerCase() === right3.toLowerCase();
        }
      }, "equals"),
      removeEmpty: /* @__PURE__ */ __name(function removeEmpty(array) {
        var ret = [];
        for (var i = 0; i < array.length; i++) {
          if (array[i]) {
            ret.push(array[i]);
          }
        }
        return ret;
      }, "removeEmpty"),
      castInput: /* @__PURE__ */ __name(function castInput(value) {
        return value;
      }, "castInput"),
      tokenize: /* @__PURE__ */ __name(function tokenize3(value) {
        return Array.from(value);
      }, "tokenize"),
      join: /* @__PURE__ */ __name(function join5(chars) {
        return chars.join("");
      }, "join"),
      postProcess: /* @__PURE__ */ __name(function postProcess(changeObjects) {
        return changeObjects;
      }, "postProcess")
    };
    __name(buildValues, "buildValues");
    characterDiff = new Diff();
    __name(longestCommonPrefix, "longestCommonPrefix");
    __name(longestCommonSuffix, "longestCommonSuffix");
    __name(replacePrefix, "replacePrefix");
    __name(replaceSuffix, "replaceSuffix");
    __name(removePrefix, "removePrefix");
    __name(removeSuffix, "removeSuffix");
    __name(maximumOverlap, "maximumOverlap");
    __name(overlapCount, "overlapCount");
    extendedWordChars = "a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}";
    tokenizeIncludingWhitespace = new RegExp("[".concat(extendedWordChars, "]+|\\s+|[^").concat(extendedWordChars, "]"), "ug");
    wordDiff = new Diff();
    wordDiff.equals = function(left3, right3, options2) {
      if (options2.ignoreCase) {
        left3 = left3.toLowerCase();
        right3 = right3.toLowerCase();
      }
      return left3.trim() === right3.trim();
    };
    wordDiff.tokenize = function(value) {
      var options2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      var parts;
      if (options2.intlSegmenter) {
        if (options2.intlSegmenter.resolvedOptions().granularity != "word") {
          throw new Error('The segmenter passed must have a granularity of "word"');
        }
        parts = Array.from(options2.intlSegmenter.segment(value), function(segment) {
          return segment.segment;
        });
      } else {
        parts = value.match(tokenizeIncludingWhitespace) || [];
      }
      var tokens = [];
      var prevPart = null;
      parts.forEach(function(part) {
        if (/\s/.test(part)) {
          if (prevPart == null) {
            tokens.push(part);
          } else {
            tokens.push(tokens.pop() + part);
          }
        } else if (/\s/.test(prevPart)) {
          if (tokens[tokens.length - 1] == prevPart) {
            tokens.push(tokens.pop() + part);
          } else {
            tokens.push(prevPart + part);
          }
        } else {
          tokens.push(part);
        }
        prevPart = part;
      });
      return tokens;
    };
    wordDiff.join = function(tokens) {
      return tokens.map(function(token2, i) {
        if (i == 0) {
          return token2;
        } else {
          return token2.replace(/^\s+/, "");
        }
      }).join("");
    };
    wordDiff.postProcess = function(changes, options2) {
      if (!changes || options2.oneChangePerToken) {
        return changes;
      }
      var lastKeep = null;
      var insertion = null;
      var deletion = null;
      changes.forEach(function(change) {
        if (change.added) {
          insertion = change;
        } else if (change.removed) {
          deletion = change;
        } else {
          if (insertion || deletion) {
            dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, change);
          }
          lastKeep = change;
          insertion = null;
          deletion = null;
        }
      });
      if (insertion || deletion) {
        dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null);
      }
      return changes;
    };
    __name(dedupeWhitespaceInChangeObjects, "dedupeWhitespaceInChangeObjects");
    wordWithSpaceDiff = new Diff();
    wordWithSpaceDiff.tokenize = function(value) {
      var regex3 = new RegExp("(\\r?\\n)|[".concat(extendedWordChars, "]+|[^\\S\\n\\r]+|[^").concat(extendedWordChars, "]"), "ug");
      return value.match(regex3) || [];
    };
    lineDiff = new Diff();
    lineDiff.tokenize = function(value, options2) {
      if (options2.stripTrailingCr) {
        value = value.replace(/\r\n/g, "\n");
      }
      var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
      if (!linesAndNewlines[linesAndNewlines.length - 1]) {
        linesAndNewlines.pop();
      }
      for (var i = 0; i < linesAndNewlines.length; i++) {
        var line = linesAndNewlines[i];
        if (i % 2 && !options2.newlineIsToken) {
          retLines[retLines.length - 1] += line;
        } else {
          retLines.push(line);
        }
      }
      return retLines;
    };
    lineDiff.equals = function(left3, right3, options2) {
      if (options2.ignoreWhitespace) {
        if (!options2.newlineIsToken || !left3.includes("\n")) {
          left3 = left3.trim();
        }
        if (!options2.newlineIsToken || !right3.includes("\n")) {
          right3 = right3.trim();
        }
      } else if (options2.ignoreNewlineAtEof && !options2.newlineIsToken) {
        if (left3.endsWith("\n")) {
          left3 = left3.slice(0, -1);
        }
        if (right3.endsWith("\n")) {
          right3 = right3.slice(0, -1);
        }
      }
      return Diff.prototype.equals.call(this, left3, right3, options2);
    };
    __name(diffLines, "diffLines");
    sentenceDiff = new Diff();
    sentenceDiff.tokenize = function(value) {
      return value.split(/(\S.+?[.!?])(?=\s+|$)/);
    };
    cssDiff = new Diff();
    cssDiff.tokenize = function(value) {
      return value.split(/([{}:;,]|\s+)/);
    };
    __name(ownKeys, "ownKeys");
    __name(_objectSpread2, "_objectSpread2");
    __name(_toPrimitive, "_toPrimitive");
    __name(_toPropertyKey, "_toPropertyKey");
    __name(_typeof, "_typeof");
    __name(_defineProperty, "_defineProperty");
    __name(_toConsumableArray, "_toConsumableArray");
    __name(_arrayWithoutHoles, "_arrayWithoutHoles");
    __name(_iterableToArray, "_iterableToArray");
    __name(_unsupportedIterableToArray, "_unsupportedIterableToArray");
    __name(_arrayLikeToArray, "_arrayLikeToArray");
    __name(_nonIterableSpread, "_nonIterableSpread");
    jsonDiff = new Diff();
    jsonDiff.useLongestToken = true;
    jsonDiff.tokenize = lineDiff.tokenize;
    jsonDiff.castInput = function(value, options2) {
      var undefinedReplacement = options2.undefinedReplacement, _options$stringifyRep = options2.stringifyReplacer, stringifyReplacer = _options$stringifyRep === void 0 ? function(k, v) {
        return typeof v === "undefined" ? undefinedReplacement : v;
      } : _options$stringifyRep;
      return typeof value === "string" ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, "  ");
    };
    jsonDiff.equals = function(left3, right3, options2) {
      return Diff.prototype.equals.call(jsonDiff, left3.replace(/,([\r\n])/g, "$1"), right3.replace(/,([\r\n])/g, "$1"), options2);
    };
    __name(canonicalize, "canonicalize");
    arrayDiff = new Diff();
    arrayDiff.tokenize = function(value) {
      return value.slice();
    };
    arrayDiff.join = arrayDiff.removeEmpty = function(value) {
      return value;
    };
    __name(structuredPatch, "structuredPatch");
    __name(formatPatch, "formatPatch");
    __name(createTwoFilesPatch, "createTwoFilesPatch");
    __name(createPatch, "createPatch");
    __name(splitLines, "splitLines");
  }
});

// packages/core/dist/src/tools/diffOptions.js
function getDiffStat(fileName, oldStr, aiStr, userStr) {
  const getStats = /* @__PURE__ */ __name((patch) => {
    let addedLines = 0;
    let removedLines = 0;
    let addedChars = 0;
    let removedChars = 0;
    patch.hunks.forEach((hunk) => {
      hunk.lines.forEach((line) => {
        if (line.startsWith("+")) {
          addedLines++;
          addedChars += line.length - 1;
        } else if (line.startsWith("-")) {
          removedLines++;
          removedChars += line.length - 1;
        }
      });
    });
    return { addedLines, removedLines, addedChars, removedChars };
  }, "getStats");
  const modelPatch = structuredPatch(fileName, fileName, oldStr, aiStr, "Current", "Proposed", DEFAULT_DIFF_OPTIONS);
  const modelStats = getStats(modelPatch);
  const userPatch = structuredPatch(fileName, fileName, aiStr, userStr, "Proposed", "User", DEFAULT_DIFF_OPTIONS);
  const userStats = getStats(userPatch);
  return {
    model_added_lines: modelStats.addedLines,
    model_removed_lines: modelStats.removedLines,
    model_added_chars: modelStats.addedChars,
    model_removed_chars: modelStats.removedChars,
    user_added_lines: userStats.addedLines,
    user_removed_lines: userStats.removedLines,
    user_added_chars: userStats.addedChars,
    user_removed_chars: userStats.removedChars
  };
}
var DEFAULT_DIFF_OPTIONS;
var init_diffOptions = __esm({
  "packages/core/dist/src/tools/diffOptions.js"() {
    "use strict";
    init_esbuild_shims();
    init_lib();
    DEFAULT_DIFF_OPTIONS = {
      context: 3,
      ignoreWhitespace: true
    };
    __name(getDiffStat, "getDiffStat");
  }
});

// packages/core/dist/src/tools/modifiable-tool.js
import os11 from "node:os";
import path13 from "node:path";
import fs17 from "node:fs";
function isModifiableDeclarativeTool(tool) {
  return "getModifyContext" in tool;
}
function createTempFilesForModify(currentContent, proposedContent, file_path) {
  const tempDir = os11.tmpdir();
  const diffDir = path13.join(tempDir, "qwen-code-tool-modify-diffs");
  if (!fs17.existsSync(diffDir)) {
    fs17.mkdirSync(diffDir, { recursive: true });
  }
  const ext2 = path13.extname(file_path);
  const fileName = path13.basename(file_path, ext2);
  const timestamp = Date.now();
  const tempOldPath = path13.join(diffDir, `qwen-code-modify-${fileName}-old-${timestamp}${ext2}`);
  const tempNewPath = path13.join(diffDir, `qwen-code-modify-${fileName}-new-${timestamp}${ext2}`);
  fs17.writeFileSync(tempOldPath, currentContent, "utf8");
  fs17.writeFileSync(tempNewPath, proposedContent, "utf8");
  return { oldPath: tempOldPath, newPath: tempNewPath };
}
function getUpdatedParams(tmpOldPath, tempNewPath, originalParams, modifyContext) {
  let oldContent = "";
  let newContent = "";
  try {
    oldContent = fs17.readFileSync(tmpOldPath, "utf8");
  } catch (err) {
    if (!isNodeError(err) || err.code !== "ENOENT")
      throw err;
    oldContent = "";
  }
  try {
    newContent = fs17.readFileSync(tempNewPath, "utf8");
  } catch (err) {
    if (!isNodeError(err) || err.code !== "ENOENT")
      throw err;
    newContent = "";
  }
  const updatedParams = modifyContext.createUpdatedParams(oldContent, newContent, originalParams);
  const updatedDiff = createPatch(path13.basename(modifyContext.getFilePath(originalParams)), oldContent, newContent, "Current", "Proposed", DEFAULT_DIFF_OPTIONS);
  return { updatedParams, updatedDiff };
}
function deleteTempFiles(oldPath, newPath) {
  try {
    fs17.unlinkSync(oldPath);
  } catch {
    console.error(`Error deleting temp diff file: ${oldPath}`);
  }
  try {
    fs17.unlinkSync(newPath);
  } catch {
    console.error(`Error deleting temp diff file: ${newPath}`);
  }
}
async function modifyWithEditor(originalParams, modifyContext, editorType, _abortSignal, onEditorClose) {
  const currentContent = await modifyContext.getCurrentContent(originalParams);
  const proposedContent = await modifyContext.getProposedContent(originalParams);
  const { oldPath, newPath } = createTempFilesForModify(currentContent, proposedContent, modifyContext.getFilePath(originalParams));
  try {
    await openDiff(oldPath, newPath, editorType, onEditorClose);
    const result = getUpdatedParams(oldPath, newPath, originalParams, modifyContext);
    return result;
  } finally {
    deleteTempFiles(oldPath, newPath);
  }
}
var init_modifiable_tool = __esm({
  "packages/core/dist/src/tools/modifiable-tool.js"() {
    "use strict";
    init_esbuild_shims();
    init_editor();
    init_lib();
    init_diffOptions();
    init_errors();
    __name(isModifiableDeclarativeTool, "isModifiableDeclarativeTool");
    __name(createTempFilesForModify, "createTempFilesForModify");
    __name(getUpdatedParams, "getUpdatedParams");
    __name(deleteTempFiles, "deleteTempFiles");
    __name(modifyWithEditor, "modifyWithEditor");
  }
});

// packages/core/dist/src/tools/tool-names.js
var ToolNames, ToolDisplayNames, ToolNamesMigration, ToolDisplayNamesMigration;
var init_tool_names = __esm({
  "packages/core/dist/src/tools/tool-names.js"() {
    "use strict";
    init_esbuild_shims();
    ToolNames = {
      EDIT: "edit",
      WRITE_FILE: "write_file",
      READ_FILE: "read_file",
      READ_MANY_FILES: "read_many_files",
      GREP: "grep_search",
      GLOB: "glob",
      SHELL: "run_shell_command",
      TODO_WRITE: "todo_write",
      MEMORY: "save_memory",
      TASK: "task",
      EXIT_PLAN_MODE: "exit_plan_mode",
      WEB_FETCH: "web_fetch",
      WEB_SEARCH: "web_search",
      LS: "list_directory"
    };
    ToolDisplayNames = {
      EDIT: "Edit",
      WRITE_FILE: "WriteFile",
      READ_FILE: "ReadFile",
      READ_MANY_FILES: "ReadManyFiles",
      GREP: "Grep",
      GLOB: "Glob",
      SHELL: "Shell",
      TODO_WRITE: "TodoWrite",
      MEMORY: "SaveMemory",
      TASK: "Task",
      EXIT_PLAN_MODE: "ExitPlanMode",
      WEB_FETCH: "WebFetch",
      WEB_SEARCH: "WebSearch",
      LS: "ListFiles"
    };
    ToolNamesMigration = {
      search_file_content: ToolNames.GREP,
      // Legacy name from grep tool
      replace: ToolNames.EDIT
      // Legacy name from edit tool
    };
    ToolDisplayNamesMigration = {
      SearchFiles: ToolDisplayNames.GREP,
      // Old display name for Grep
      FindFiles: ToolDisplayNames.GLOB,
      // Old display name for Glob
      ReadFolder: ToolDisplayNames.LS
      // Old display name for ListFiles
    };
  }
});

// packages/core/dist/src/utils/tool-utils.js
function isToolEnabled(toolName, coreTools, excludeTools) {
  const aliasSet = getAliasSetForTool(toolName);
  const matchesIdentifier = /* @__PURE__ */ __name((value) => aliasSet.has(sanitizeExactIdentifier(value)), "matchesIdentifier");
  const matchesIdentifierWithArgs = /* @__PURE__ */ __name((value) => aliasSet.has(sanitizePatternIdentifier(value)), "matchesIdentifierWithArgs");
  const filteredCore = filterList(coreTools);
  const filteredExclude = filterList(excludeTools);
  if (filteredCore.length === 0) {
    return !filteredExclude.some((entry) => matchesIdentifier(entry));
  }
  const isExplicitlyEnabled = filteredCore.some((entry) => matchesIdentifier(entry) || matchesIdentifierWithArgs(entry));
  if (!isExplicitlyEnabled) {
    return false;
  }
  return !filteredExclude.some((entry) => matchesIdentifier(entry));
}
function doesToolInvocationMatch(toolOrToolName, invocation, patterns) {
  let toolNames;
  if (isTool(toolOrToolName)) {
    toolNames = [toolOrToolName.name, toolOrToolName.constructor.name];
  } else {
    toolNames = [toolOrToolName];
  }
  if (toolNames.some((name3) => SHELL_TOOL_NAMES.includes(name3))) {
    toolNames = [.../* @__PURE__ */ new Set([...toolNames, ...SHELL_TOOL_NAMES])];
  }
  for (const pattern of patterns) {
    const openParen = pattern.indexOf("(");
    if (openParen === -1) {
      if (toolNames.includes(pattern)) {
        return true;
      }
      continue;
    }
    const patternToolName = pattern.substring(0, openParen);
    if (!toolNames.includes(patternToolName)) {
      continue;
    }
    if (!pattern.endsWith(")")) {
      continue;
    }
    const argPattern = pattern.substring(openParen + 1, pattern.length - 1);
    if ("command" in invocation.params && toolNames.includes("run_shell_command")) {
      const argValue = String(invocation.params.command);
      if (argValue === argPattern || argValue.startsWith(argPattern + " ")) {
        return true;
      }
    }
  }
  return false;
}
var normalizeIdentifier, toolNameKeys, TOOL_ALIAS_MAP, getAliasSetForTool, sanitizeExactIdentifier, sanitizePatternIdentifier, filterList, SHELL_TOOL_NAMES;
var init_tool_utils = __esm({
  "packages/core/dist/src/utils/tool-utils.js"() {
    "use strict";
    init_esbuild_shims();
    init_src();
    init_tool_names();
    normalizeIdentifier = /* @__PURE__ */ __name((identifier2) => identifier2.trim().replace(/^_+/, ""), "normalizeIdentifier");
    toolNameKeys = Object.keys(ToolNames);
    TOOL_ALIAS_MAP = (() => {
      const map2 = /* @__PURE__ */ new Map();
      const addAlias = /* @__PURE__ */ __name((set, alias) => {
        if (!alias) {
          return;
        }
        set.add(normalizeIdentifier(alias));
      }, "addAlias");
      for (const key of toolNameKeys) {
        const canonicalName = ToolNames[key];
        const displayName = ToolDisplayNames[key];
        const aliases = /* @__PURE__ */ new Set();
        addAlias(aliases, canonicalName);
        addAlias(aliases, displayName);
        addAlias(aliases, `${displayName}Tool`);
        for (const [legacyName, mappedName] of Object.entries(ToolNamesMigration)) {
          if (mappedName === canonicalName) {
            addAlias(aliases, legacyName);
          }
        }
        for (const [legacyDisplay, mappedDisplay] of Object.entries(ToolDisplayNamesMigration)) {
          if (mappedDisplay === displayName) {
            addAlias(aliases, legacyDisplay);
          }
        }
        map2.set(canonicalName, aliases);
      }
      return map2;
    })();
    getAliasSetForTool = /* @__PURE__ */ __name((toolName) => {
      const aliases = TOOL_ALIAS_MAP.get(toolName);
      if (!aliases) {
        return /* @__PURE__ */ new Set([normalizeIdentifier(toolName)]);
      }
      return aliases;
    }, "getAliasSetForTool");
    sanitizeExactIdentifier = /* @__PURE__ */ __name((value) => normalizeIdentifier(value), "sanitizeExactIdentifier");
    sanitizePatternIdentifier = /* @__PURE__ */ __name((value) => {
      const openParenIndex = value.indexOf("(");
      if (openParenIndex === -1) {
        return normalizeIdentifier(value);
      }
      return normalizeIdentifier(value.slice(0, openParenIndex));
    }, "sanitizePatternIdentifier");
    filterList = /* @__PURE__ */ __name((list3) => (list3 ?? []).filter((entry) => Boolean(entry && entry.trim())), "filterList");
    __name(isToolEnabled, "isToolEnabled");
    SHELL_TOOL_NAMES = ["run_shell_command", "ShellTool"];
    __name(doesToolInvocationMatch, "doesToolInvocationMatch");
  }
});

// node_modules/fast-levenshtein/levenshtein.js
var require_levenshtein = __commonJS({
  "node_modules/fast-levenshtein/levenshtein.js"(exports2, module2) {
    init_esbuild_shims();
    (function() {
      "use strict";
      var collator;
      try {
        collator = typeof Intl !== "undefined" && typeof Intl.Collator !== "undefined" ? Intl.Collator("generic", { sensitivity: "base" }) : null;
      } catch (err) {
        console.log("Collator could not be initialized and wouldn't be used");
      }
      var prevRow = [], str2Char = [];
      var Levenshtein = {
        /**
         * Calculate levenshtein distance of the two strings.
         *
         * @param str1 String the first string.
         * @param str2 String the second string.
         * @param [options] Additional options.
         * @param [options.useCollator] Use `Intl.Collator` for locale-sensitive string comparison.
         * @return Integer the levenshtein distance (0 and above).
         */
        get: /* @__PURE__ */ __name(function(str1, str2, options2) {
          var useCollator = options2 && collator && options2.useCollator;
          var str1Len = str1.length, str2Len = str2.length;
          if (str1Len === 0) return str2Len;
          if (str2Len === 0) return str1Len;
          var curCol, nextCol, i, j, tmp;
          for (i = 0; i < str2Len; ++i) {
            prevRow[i] = i;
            str2Char[i] = str2.charCodeAt(i);
          }
          prevRow[str2Len] = str2Len;
          var strCmp;
          if (useCollator) {
            for (i = 0; i < str1Len; ++i) {
              nextCol = i + 1;
              for (j = 0; j < str2Len; ++j) {
                curCol = nextCol;
                strCmp = 0 === collator.compare(str1.charAt(i), String.fromCharCode(str2Char[j]));
                nextCol = prevRow[j] + (strCmp ? 0 : 1);
                tmp = curCol + 1;
                if (nextCol > tmp) {
                  nextCol = tmp;
                }
                tmp = prevRow[j + 1] + 1;
                if (nextCol > tmp) {
                  nextCol = tmp;
                }
                prevRow[j] = curCol;
              }
              prevRow[j] = nextCol;
            }
          } else {
            for (i = 0; i < str1Len; ++i) {
              nextCol = i + 1;
              for (j = 0; j < str2Len; ++j) {
                curCol = nextCol;
                strCmp = str1.charCodeAt(i) === str2Char[j];
                nextCol = prevRow[j] + (strCmp ? 0 : 1);
                tmp = curCol + 1;
                if (nextCol > tmp) {
                  nextCol = tmp;
                }
                tmp = prevRow[j + 1] + 1;
                if (nextCol > tmp) {
                  nextCol = tmp;
                }
                prevRow[j] = curCol;
              }
              prevRow[j] = nextCol;
            }
          }
          return nextCol;
        }, "get")
      };
      if (typeof define !== "undefined" && define !== null && define.amd) {
        define(function() {
          return Levenshtein;
        });
      } else if (typeof module2 !== "undefined" && module2 !== null && typeof exports2 !== "undefined" && module2.exports === exports2) {
        module2.exports = Levenshtein;
      } else if (typeof self !== "undefined" && typeof self.postMessage === "function" && typeof self.importScripts === "function") {
        self.Levenshtein = Levenshtein;
      } else if (typeof window !== "undefined" && window !== null) {
        window.Levenshtein = Levenshtein;
      }
    })();
  }
});

// packages/core/dist/src/utils/gitUtils.js
import * as fs18 from "node:fs";
import * as path14 from "node:path";
function isGitRepository(directory) {
  try {
    let currentDir = path14.resolve(directory);
    while (true) {
      const gitDir = path14.join(currentDir, ".git");
      if (fs18.existsSync(gitDir)) {
        return true;
      }
      const parentDir = path14.dirname(currentDir);
      if (parentDir === currentDir) {
        break;
      }
      currentDir = parentDir;
    }
    return false;
  } catch (_error) {
    return false;
  }
}
var init_gitUtils = __esm({
  "packages/core/dist/src/utils/gitUtils.js"() {
    "use strict";
    init_esbuild_shims();
    __name(isGitRepository, "isGitRepository");
  }
});

// packages/core/dist/src/utils/paths.js
import fs19 from "node:fs";
import path15 from "node:path";
import os12 from "node:os";
import * as crypto11 from "node:crypto";
function tildeifyPath(path108) {
  const homeDir = os12.homedir();
  if (path108.startsWith(homeDir)) {
    return path108.replace(homeDir, "~");
  }
  return path108;
}
function shortenPath(filePath, maxLen = 35) {
  if (filePath.length <= maxLen) {
    return filePath;
  }
  const parsedPath = path15.parse(filePath);
  const root = parsedPath.root;
  const separator = path15.sep;
  const relativePath = filePath.substring(root.length);
  const segments = relativePath.split(separator).filter((s2) => s2 !== "");
  if (segments.length <= 1) {
    const keepLen = Math.floor((maxLen - 3) / 2);
    if (keepLen <= 0) {
      return filePath.substring(0, maxLen - 3) + "...";
    }
    const start = filePath.substring(0, keepLen);
    const end = filePath.substring(filePath.length - keepLen);
    return `${start}...${end}`;
  }
  const firstDir = segments[0];
  const lastSegment = segments[segments.length - 1];
  const startComponent = root + firstDir;
  const endPartSegments = [];
  let currentLength = separator.length + lastSegment.length;
  for (let i = segments.length - 2; i >= 0; i--) {
    const segment = segments[i];
    const lengthWithSegment = currentLength + separator.length + segment.length;
    if (lengthWithSegment <= maxLen) {
      endPartSegments.unshift(segment);
      currentLength = lengthWithSegment;
    } else {
      break;
    }
  }
  let result = endPartSegments.join(separator) + separator + lastSegment;
  if (currentLength > maxLen) {
    return result;
  }
  result = startComponent + separator + result;
  if (result.length > maxLen) {
    return "..." + result.substring(result.length - maxLen - 3);
  }
  return result;
}
function makeRelative(targetPath, rootDirectory) {
  const resolvedTargetPath = path15.resolve(targetPath);
  const resolvedRootDirectory = path15.resolve(rootDirectory);
  const relativePath = path15.relative(resolvedRootDirectory, resolvedTargetPath);
  return relativePath || ".";
}
function escapePath(filePath) {
  let result = "";
  for (let i = 0; i < filePath.length; i++) {
    const char = filePath[i];
    let backslashCount = 0;
    for (let j = i - 1; j >= 0 && filePath[j] === "\\"; j--) {
      backslashCount++;
    }
    const isAlreadyEscaped = backslashCount % 2 === 1;
    if (!isAlreadyEscaped && SHELL_SPECIAL_CHARS.test(char)) {
      result += "\\" + char;
    } else {
      result += char;
    }
  }
  return result;
}
function unescapePath(filePath) {
  return filePath.replace(new RegExp(`\\\\([${SHELL_SPECIAL_CHARS.source.slice(1, -1)}])`, "g"), "$1");
}
function getProjectHash(projectRoot) {
  return crypto11.createHash("sha256").update(projectRoot).digest("hex");
}
function isSubpath(parentPath, childPath) {
  const isWindows8 = os12.platform() === "win32";
  const pathModule2 = isWindows8 ? path15.win32 : path15;
  const relative10 = pathModule2.relative(parentPath, childPath);
  return !relative10.startsWith(`..${pathModule2.sep}`) && relative10 !== ".." && !pathModule2.isAbsolute(relative10);
}
function resolvePath(baseDir = process.cwd(), relativePath) {
  const homeDir = os12.homedir();
  if (relativePath === "~") {
    return homeDir;
  } else if (relativePath.startsWith("~/")) {
    return path15.join(homeDir, relativePath.slice(2));
  } else if (path15.isAbsolute(relativePath)) {
    return relativePath;
  } else {
    return path15.resolve(baseDir, relativePath);
  }
}
function validatePath(config, resolvedPath, options2 = {}) {
  const { allowFiles = false } = options2;
  const workspaceContext = config.getWorkspaceContext();
  if (!workspaceContext.isPathWithinWorkspace(resolvedPath)) {
    throw new Error("Path is not within workspace");
  }
  try {
    const stats = fs19.statSync(resolvedPath);
    if (!allowFiles && !stats.isDirectory()) {
      throw new Error(`Path is not a directory: ${resolvedPath}`);
    }
  } catch (error) {
    if (isNodeError(error) && error.code === "ENOENT") {
      throw new Error(`Path does not exist: ${resolvedPath}`);
    }
    throw error;
  }
}
function resolveAndValidatePath(config, relativePath, options2 = {}) {
  const targetDir = config.getTargetDir();
  if (!relativePath) {
    return targetDir;
  }
  const resolvedPath = resolvePath(targetDir, relativePath);
  validatePath(config, resolvedPath, options2);
  return resolvedPath;
}
var QWEN_DIR5, SHELL_SPECIAL_CHARS;
var init_paths = __esm({
  "packages/core/dist/src/utils/paths.js"() {
    "use strict";
    init_esbuild_shims();
    init_errors();
    QWEN_DIR5 = ".qwen";
    SHELL_SPECIAL_CHARS = /[ \t()[\]{};|*?$`'"#&<>!~]/;
    __name(tildeifyPath, "tildeifyPath");
    __name(shortenPath, "shortenPath");
    __name(makeRelative, "makeRelative");
    __name(escapePath, "escapePath");
    __name(unescapePath, "unescapePath");
    __name(getProjectHash, "getProjectHash");
    __name(isSubpath, "isSubpath");
    __name(resolvePath, "resolvePath");
    __name(validatePath, "validatePath");
    __name(resolveAndValidatePath, "resolveAndValidatePath");
  }
});

// packages/core/dist/src/tools/memoryTool.js
import * as fs20 from "node:fs/promises";
import * as path16 from "node:path";
function setGeminiMdFilename(newFilename) {
  if (Array.isArray(newFilename)) {
    if (newFilename.length > 0) {
      currentGeminiMdFilename = newFilename.map((name3) => name3.trim());
    }
  } else if (newFilename && newFilename.trim() !== "") {
    currentGeminiMdFilename = newFilename.trim();
  }
}
function getCurrentGeminiMdFilename() {
  if (Array.isArray(currentGeminiMdFilename)) {
    return currentGeminiMdFilename[0];
  }
  return currentGeminiMdFilename;
}
function getAllGeminiMdFilenames() {
  if (Array.isArray(currentGeminiMdFilename)) {
    return currentGeminiMdFilename;
  }
  return [currentGeminiMdFilename];
}
function getGlobalMemoryFilePath() {
  return path16.join(Storage.getGlobalQwenDir(), getCurrentGeminiMdFilename());
}
function getProjectMemoryFilePath() {
  return path16.join(process.cwd(), getCurrentGeminiMdFilename());
}
function getMemoryFilePath(scope = "global") {
  return scope === "project" ? getProjectMemoryFilePath() : getGlobalMemoryFilePath();
}
function ensureNewlineSeparation(currentContent) {
  if (currentContent.length === 0)
    return "";
  if (currentContent.endsWith("\n\n") || currentContent.endsWith("\r\n\r\n"))
    return "";
  if (currentContent.endsWith("\n") || currentContent.endsWith("\r\n"))
    return "\n";
  return "\n\n";
}
async function readMemoryFileContent(scope = "global") {
  try {
    return await fs20.readFile(getMemoryFilePath(scope), "utf-8");
  } catch (err) {
    const error = err;
    if (!(error instanceof Error) || error.code !== "ENOENT")
      throw err;
    return "";
  }
}
function computeNewContent(currentContent, fact) {
  let processedText = fact.trim();
  processedText = processedText.replace(/^(-+\s*)+/, "").trim();
  const newMemoryItem = `- ${processedText}`;
  const headerIndex = currentContent.indexOf(MEMORY_SECTION_HEADER);
  if (headerIndex === -1) {
    const separator = ensureNewlineSeparation(currentContent);
    return currentContent + `${separator}${MEMORY_SECTION_HEADER}
${newMemoryItem}
`;
  } else {
    const startOfSectionContent = headerIndex + MEMORY_SECTION_HEADER.length;
    let endOfSectionIndex = currentContent.indexOf("\n## ", startOfSectionContent);
    if (endOfSectionIndex === -1) {
      endOfSectionIndex = currentContent.length;
    }
    const beforeSectionMarker = currentContent.substring(0, startOfSectionContent).trimEnd();
    let sectionContent = currentContent.substring(startOfSectionContent, endOfSectionIndex).trimEnd();
    const afterSectionMarker = currentContent.substring(endOfSectionIndex);
    sectionContent += `
${newMemoryItem}`;
    return `${beforeSectionMarker}
${sectionContent.trimStart()}
${afterSectionMarker}`.trimEnd() + "\n";
  }
}
var memoryToolSchemaData, memoryToolDescription, QWEN_CONFIG_DIR, DEFAULT_CONTEXT_FILENAME, MEMORY_SECTION_HEADER, currentGeminiMdFilename, MemoryToolInvocation, MemoryTool;
var init_memoryTool = __esm({
  "packages/core/dist/src/tools/memoryTool.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    init_storage();
    init_lib();
    init_diffOptions();
    init_paths();
    init_tool_names();
    init_tool_error();
    memoryToolSchemaData = {
      name: "save_memory",
      description: "Saves a specific piece of information or fact to your long-term memory. Use this when the user explicitly asks you to remember something, or when they state a clear, concise fact that seems important to retain for future interactions.",
      parametersJsonSchema: {
        type: "object",
        properties: {
          fact: {
            type: "string",
            description: "The specific fact or piece of information to remember. Should be a clear, self-contained statement."
          },
          scope: {
            type: "string",
            description: `Where to save the memory: "global" saves to user-level ~/.qwen/QWEN.md (shared across all projects), "project" saves to current project's QWEN.md (project-specific). If not specified, will prompt user to choose.`,
            enum: ["global", "project"]
          }
        },
        required: ["fact"]
      }
    };
    memoryToolDescription = `
Saves a specific piece of information or fact to your long-term memory.

Use this tool:

- When the user explicitly asks you to remember something (e.g., "Remember that I like pineapple on pizza", "Please save this: my cat's name is Whiskers").
- When the user states a clear, concise fact about themselves, their preferences, or their environment that seems important for you to retain for future interactions to provide a more personalized and effective assistance.

Do NOT use this tool:

- To remember conversational context that is only relevant for the current session.
- To save long, complex, or rambling pieces of text. The fact should be relatively short and to the point.
- If you are unsure whether the information is a fact worth remembering long-term. If in doubt, you can ask the user, "Should I remember that for you?"

## Parameters

- \`fact\` (string, required): The specific fact or piece of information to remember. This should be a clear, self-contained statement. For example, if the user says "My favorite color is blue", the fact would be "My favorite color is blue".
- \`scope\` (string, optional): Where to save the memory:
  - "global": Saves to user-level ~/.qwen/QWEN.md (shared across all projects)
  - "project": Saves to current project's QWEN.md (project-specific)
  - If not specified, the tool will ask the user where they want to save the memory.
`;
    QWEN_CONFIG_DIR = ".qwen";
    DEFAULT_CONTEXT_FILENAME = "QWEN.md";
    MEMORY_SECTION_HEADER = "## Qwen Added Memories";
    currentGeminiMdFilename = DEFAULT_CONTEXT_FILENAME;
    __name(setGeminiMdFilename, "setGeminiMdFilename");
    __name(getCurrentGeminiMdFilename, "getCurrentGeminiMdFilename");
    __name(getAllGeminiMdFilenames, "getAllGeminiMdFilenames");
    __name(getGlobalMemoryFilePath, "getGlobalMemoryFilePath");
    __name(getProjectMemoryFilePath, "getProjectMemoryFilePath");
    __name(getMemoryFilePath, "getMemoryFilePath");
    __name(ensureNewlineSeparation, "ensureNewlineSeparation");
    __name(readMemoryFileContent, "readMemoryFileContent");
    __name(computeNewContent, "computeNewContent");
    MemoryToolInvocation = class _MemoryToolInvocation extends BaseToolInvocation {
      static {
        __name(this, "MemoryToolInvocation");
      }
      static allowlist = /* @__PURE__ */ new Set();
      getDescription() {
        if (!this.params.scope) {
          const globalPath = tildeifyPath(getMemoryFilePath("global"));
          const projectPath = tildeifyPath(getMemoryFilePath("project"));
          return `CHOOSE: ${globalPath} (global) OR ${projectPath} (project)`;
        }
        const scope = this.params.scope;
        const memoryFilePath = getMemoryFilePath(scope);
        return `${tildeifyPath(memoryFilePath)} (${scope})`;
      }
      async shouldConfirmExecute(_abortSignal) {
        if (!this.params.scope) {
          const defaultScope = "global";
          const currentContent2 = await readMemoryFileContent(defaultScope);
          const newContent2 = computeNewContent(currentContent2, this.params.fact);
          const globalPath = tildeifyPath(getMemoryFilePath("global"));
          const projectPath = tildeifyPath(getMemoryFilePath("project"));
          const fileName2 = path16.basename(getMemoryFilePath(defaultScope));
          const choiceText = `Choose where to save this memory:

"${this.params.fact}"

Options:
- Global: ${globalPath} (shared across all projects)
- Project: ${projectPath} (current project only)

Preview of changes to be made to GLOBAL memory:
`;
          const fileDiff2 = choiceText + createPatch(fileName2, currentContent2, newContent2, "Current", "Proposed (Global)", DEFAULT_DIFF_OPTIONS);
          const confirmationDetails2 = {
            type: "edit",
            title: `Choose Memory Location: GLOBAL (${globalPath}) or PROJECT (${projectPath})`,
            fileName: fileName2,
            filePath: getMemoryFilePath(defaultScope),
            fileDiff: fileDiff2,
            originalContent: `scope: global

# INSTRUCTIONS:
# - Click "Yes" to save to GLOBAL memory: ${globalPath}
# - Click "Modify with external editor" and change "global" to "project" to save to PROJECT memory: ${projectPath}

${currentContent2}`,
            newContent: `scope: global

# INSTRUCTIONS:
# - Click "Yes" to save to GLOBAL memory: ${globalPath}
# - Click "Modify with external editor" and change "global" to "project" to save to PROJECT memory: ${projectPath}

${newContent2}`,
            onConfirm: /* @__PURE__ */ __name(async (_outcome) => {
            }, "onConfirm")
          };
          return confirmationDetails2;
        }
        const scope = this.params.scope;
        const memoryFilePath = getMemoryFilePath(scope);
        const allowlistKey = `${memoryFilePath}_${scope}`;
        if (_MemoryToolInvocation.allowlist.has(allowlistKey)) {
          return false;
        }
        const currentContent = await readMemoryFileContent(scope);
        const newContent = computeNewContent(currentContent, this.params.fact);
        const fileName = path16.basename(memoryFilePath);
        const fileDiff = createPatch(fileName, currentContent, newContent, "Current", "Proposed", DEFAULT_DIFF_OPTIONS);
        const confirmationDetails = {
          type: "edit",
          title: `Confirm Memory Save: ${tildeifyPath(memoryFilePath)} (${scope})`,
          fileName: memoryFilePath,
          filePath: memoryFilePath,
          fileDiff,
          originalContent: currentContent,
          newContent,
          onConfirm: /* @__PURE__ */ __name(async (outcome) => {
            if (outcome === ToolConfirmationOutcome.ProceedAlways) {
              _MemoryToolInvocation.allowlist.add(allowlistKey);
            }
          }, "onConfirm")
        };
        return confirmationDetails;
      }
      async execute(_signal) {
        const { fact, modified_by_user, modified_content } = this.params;
        if (!fact || typeof fact !== "string" || fact.trim() === "") {
          const errorMessage = 'Parameter "fact" must be a non-empty string.';
          return {
            llmContent: `Error: ${errorMessage}`,
            returnDisplay: `Error: ${errorMessage}`
          };
        }
        if (!this.params.scope && !modified_by_user) {
          const globalPath = tildeifyPath(getMemoryFilePath("global"));
          const projectPath = tildeifyPath(getMemoryFilePath("project"));
          const errorMessage = `Please specify where to save this memory:

Global: ${globalPath} (shared across all projects)
Project: ${projectPath} (current project only)`;
          return {
            llmContent: errorMessage,
            returnDisplay: errorMessage
          };
        }
        const scope = this.params.scope || "global";
        const memoryFilePath = getMemoryFilePath(scope);
        try {
          if (modified_by_user && modified_content !== void 0) {
            await fs20.mkdir(path16.dirname(memoryFilePath), {
              recursive: true
            });
            await fs20.writeFile(memoryFilePath, modified_content, "utf-8");
            const successMessage = `Okay, I've updated the ${scope} memory file with your modifications.`;
            return {
              llmContent: successMessage,
              returnDisplay: successMessage
            };
          } else {
            await MemoryTool.performAddMemoryEntry(fact, memoryFilePath, {
              readFile: fs20.readFile,
              writeFile: fs20.writeFile,
              mkdir: fs20.mkdir
            });
            const successMessage = `Okay, I've remembered that in ${scope} memory: "${fact}"`;
            return {
              llmContent: successMessage,
              returnDisplay: successMessage
            };
          }
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : String(error);
          console.error(`[MemoryTool] Error executing save_memory for fact "${fact}" in ${scope}: ${errorMessage}`);
          return {
            llmContent: `Error saving memory: ${errorMessage}`,
            returnDisplay: `Error saving memory: ${errorMessage}`,
            error: {
              message: errorMessage,
              type: ToolErrorType.MEMORY_TOOL_EXECUTION_ERROR
            }
          };
        }
      }
    };
    MemoryTool = class _MemoryTool extends BaseDeclarativeTool {
      static {
        __name(this, "MemoryTool");
      }
      static Name = ToolNames.MEMORY;
      constructor() {
        super(_MemoryTool.Name, ToolDisplayNames.MEMORY, memoryToolDescription, Kind.Think, memoryToolSchemaData.parametersJsonSchema);
      }
      validateToolParamValues(params) {
        if (params.fact.trim() === "") {
          return 'Parameter "fact" must be a non-empty string.';
        }
        return null;
      }
      createInvocation(params) {
        return new MemoryToolInvocation(params);
      }
      static async performAddMemoryEntry(text, memoryFilePath, fsAdapter) {
        try {
          await fsAdapter.mkdir(path16.dirname(memoryFilePath), { recursive: true });
          let currentContent = "";
          try {
            currentContent = await fsAdapter.readFile(memoryFilePath, "utf-8");
          } catch (_e) {
          }
          const newContent = computeNewContent(currentContent, text);
          await fsAdapter.writeFile(memoryFilePath, newContent, "utf-8");
        } catch (error) {
          console.error(`[MemoryTool] Error adding memory entry to ${memoryFilePath}:`, error);
          throw new Error(`[MemoryTool] Failed to add memory entry: ${error instanceof Error ? error.message : String(error)}`);
        }
      }
      getModifyContext(_abortSignal) {
        return {
          getFilePath: /* @__PURE__ */ __name((params) => {
            let scope = params.scope || "global";
            if (params.modified_content) {
              const scopeMatch = params.modified_content.match(/^scope:\s*(global|project)\s*\n/i);
              if (scopeMatch) {
                scope = scopeMatch[1].toLowerCase();
              }
            }
            return getMemoryFilePath(scope);
          }, "getFilePath"),
          getCurrentContent: /* @__PURE__ */ __name(async (params) => {
            if (params.modified_content) {
              const scopeMatch = params.modified_content.match(/^scope:\s*(global|project)\s*\n/i);
              if (scopeMatch) {
                const scope2 = scopeMatch[1].toLowerCase();
                const content2 = await readMemoryFileContent(scope2);
                const globalPath2 = tildeifyPath(getMemoryFilePath("global"));
                const projectPath2 = tildeifyPath(getMemoryFilePath("project"));
                return `scope: ${scope2}

# INSTRUCTIONS:
# - Save as "global" for GLOBAL memory: ${globalPath2}
# - Save as "project" for PROJECT memory: ${projectPath2}

${content2}`;
              }
            }
            const scope = params.scope || "global";
            const content = await readMemoryFileContent(scope);
            const globalPath = tildeifyPath(getMemoryFilePath("global"));
            const projectPath = tildeifyPath(getMemoryFilePath("project"));
            return `scope: ${scope}

# INSTRUCTIONS:
# - Save as "global" for GLOBAL memory: ${globalPath}
# - Save as "project" for PROJECT memory: ${projectPath}

${content}`;
          }, "getCurrentContent"),
          getProposedContent: /* @__PURE__ */ __name(async (params) => {
            let scope = params.scope || "global";
            if (params.modified_content) {
              const scopeMatch = params.modified_content.match(/^scope:\s*(global|project)\s*\n/i);
              if (scopeMatch) {
                scope = scopeMatch[1].toLowerCase();
              }
            }
            const currentContent = await readMemoryFileContent(scope);
            const newContent = computeNewContent(currentContent, params.fact);
            const globalPath = tildeifyPath(getMemoryFilePath("global"));
            const projectPath = tildeifyPath(getMemoryFilePath("project"));
            return `scope: ${scope}

# INSTRUCTIONS:
# - Save as "global" for GLOBAL memory: ${globalPath}
# - Save as "project" for PROJECT memory: ${projectPath}

${newContent}`;
          }, "getProposedContent"),
          createUpdatedParams: /* @__PURE__ */ __name((_oldContent, modifiedProposedContent, originalParams) => {
            const scopeMatch = modifiedProposedContent.match(/^scope:\s*(global|project)/i);
            const scope = scopeMatch ? scopeMatch[1].toLowerCase() : "global";
            const contentWithoutScope = modifiedProposedContent.replace(/^scope:\s*(global|project)\s*\n/, "");
            const actualContent = contentWithoutScope.replace(/^#[^\n]*\n/gm, "").replace(/^\s*\n/gm, "").trim();
            return {
              ...originalParams,
              scope,
              modified_by_user: true,
              modified_content: actualContent
            };
          }, "createUpdatedParams")
        };
      }
    };
  }
});

// packages/core/dist/src/core/prompts.js
import path17 from "node:path";
import fs21 from "node:fs";
import os13 from "node:os";
import process18 from "node:process";
function resolvePathFromEnv(envVar) {
  const trimmedEnvVar = envVar?.trim();
  if (!trimmedEnvVar) {
    return { isSwitch: false, value: null, isDisabled: false };
  }
  const lowerEnvVar = trimmedEnvVar.toLowerCase();
  if (["0", "false", "1", "true"].includes(lowerEnvVar)) {
    const isDisabled = ["0", "false"].includes(lowerEnvVar);
    return { isSwitch: true, value: lowerEnvVar, isDisabled };
  }
  let customPath = trimmedEnvVar;
  if (customPath.startsWith("~/") || customPath === "~") {
    try {
      const home = os13.homedir();
      if (customPath === "~") {
        customPath = home;
      } else {
        customPath = path17.join(home, customPath.slice(2));
      }
    } catch (error) {
      console.warn(`Could not resolve home directory for path: ${trimmedEnvVar}`, error);
      return { isSwitch: false, value: null, isDisabled: false };
    }
  }
  return {
    isSwitch: false,
    value: path17.resolve(customPath),
    isDisabled: false
  };
}
function getCustomSystemPrompt(customInstruction, userMemory) {
  let instructionText = "";
  if (typeof customInstruction === "string") {
    instructionText = customInstruction;
  } else if (Array.isArray(customInstruction)) {
    instructionText = customInstruction.map((part) => typeof part === "string" ? part : part.text || "").join("");
  } else if (customInstruction && "parts" in customInstruction) {
    instructionText = customInstruction.parts?.map((part) => typeof part === "string" ? part : part.text || "").join("") || "";
  } else if (customInstruction && "text" in customInstruction) {
    instructionText = customInstruction.text || "";
  }
  const memorySuffix = userMemory && userMemory.trim().length > 0 ? `

---

${userMemory.trim()}` : "";
  return `${instructionText}${memorySuffix}`;
}
function getCoreSystemPrompt(userMemory, model) {
  let systemMdEnabled = false;
  let systemMdPath = path17.resolve(path17.join(QWEN_CONFIG_DIR, "system.md"));
  const systemMdResolution = resolvePathFromEnv(process18.env["QWEN_SYSTEM_MD"]);
  if (systemMdResolution.value && !systemMdResolution.isDisabled) {
    systemMdEnabled = true;
    if (!systemMdResolution.isSwitch) {
      systemMdPath = systemMdResolution.value;
    }
    if (!fs21.existsSync(systemMdPath)) {
      throw new Error(`missing system prompt file '${systemMdPath}'`);
    }
  }
  const basePrompt = systemMdEnabled ? fs21.readFileSync(systemMdPath, "utf8") : `
You are Qwen Code, an interactive CLI agent developed by Alibaba Group, specializing in software engineering tasks. Your primary goal is to help users safely and efficiently, adhering strictly to the following instructions and utilizing your available tools.

# Core Mandates

- **Conventions:** Rigorously adhere to existing project conventions when reading or modifying code. Analyze surrounding code, tests, and configuration first.
- **Libraries/Frameworks:** NEVER assume a library/framework is available or appropriate. Verify its established usage within the project (check imports, configuration files like 'package.json', 'Cargo.toml', 'requirements.txt', 'build.gradle', etc., or observe neighboring files) before employing it.
- **Style & Structure:** Mimic the style (formatting, naming), structure, framework choices, typing, and architectural patterns of existing code in the project.
- **Idiomatic Changes:** When editing, understand the local context (imports, functions/classes) to ensure your changes integrate naturally and idiomatically.
- **Comments:** Add code comments sparingly. Focus on *why* something is done, especially for complex logic, rather than *what* is done. Only add high-value comments if necessary for clarity or if requested by the user. Do not edit comments that are separate from the code you are changing. *NEVER* talk to the user or describe your changes through comments.
- **Proactiveness:** Fulfill the user's request thoroughly. When adding features or fixing bugs, this includes adding tests to ensure quality. Consider all created files, especially tests, to be permanent artifacts unless the user says otherwise.
- **Confirm Ambiguity/Expansion:** Do not take significant actions beyond the clear scope of the request without confirming with the user. If asked *how* to do something, explain first, don't just do it.
- **Explaining Changes:** After completing a code modification or file operation *do not* provide summaries unless asked.
- **Path Construction:** Before using any file system tool (e.g., ${ToolNames.READ_FILE}' or '${ToolNames.WRITE_FILE}'), you must construct the full absolute path for the file_path argument. Always combine the absolute path of the project's root directory with the file's path relative to the root. For example, if the project root is /path/to/project/ and the file is foo/bar/baz.txt, the final path you must use is /path/to/project/foo/bar/baz.txt. If the user provides a relative path, you must resolve it against the root directory to create an absolute path.
- **Do Not revert changes:** Do not revert changes to the codebase unless asked to do so by the user. Only revert changes made by you if they have resulted in an error or if the user has explicitly asked you to revert the changes.

# Task Management
You have access to the ${ToolNames.TODO_WRITE} tool to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.
These tools are also EXTREMELY helpful for planning tasks, and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks - and that is unacceptable.

It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.

Examples:

<example>
user: Run the build and fix any type errors
assistant: I'm going to use the ${ToolNames.TODO_WRITE} tool to write the following items to the todo list: 
- Run the build
- Fix any type errors

I'm now going to run the build using Bash.

Looks like I found 10 type errors. I'm going to use the ${ToolNames.TODO_WRITE} tool to write 10 items to the todo list.

marking the first todo as in_progress

Let me start working on the first item...

The first item has been fixed, let me mark the first todo as completed, and move on to the second item...
..
..
</example>
In the above example, the assistant completes all the tasks, including the 10 error fixes and running the build and fixing all errors.

<example>
user: Help me write a new feature that allows users to track their usage metrics and export them to various formats

A: I'll help you implement a usage metrics tracking and export feature. Let me first use the ${ToolNames.TODO_WRITE} tool to plan this task.
Adding the following todos to the todo list:
1. Research existing metrics tracking in the codebase
2. Design the metrics collection system
3. Implement core metrics tracking functionality
4. Create export functionality for different formats

Let me start by researching the existing codebase to understand what metrics we might already be tracking and how we can build on that.

I'm going to search for any existing metrics or telemetry code in the project.

I've found some existing telemetry code. Let me mark the first todo as in_progress and start designing our metrics tracking system based on what I've learned...

[Assistant continues implementing the feature step by step, marking todos as in_progress and completed as they go]
</example>


# Primary Workflows

## Software Engineering Tasks
When requested to perform tasks like fixing bugs, adding features, refactoring, or explaining code, follow this iterative approach:
- **Plan:** After understanding the user's request, create an initial plan based on your existing knowledge and any immediately obvious context. Use the '${ToolNames.TODO_WRITE}' tool to capture this rough plan for complex or multi-step work. Don't wait for complete understanding - start with what you know.
- **Implement:** Begin implementing the plan while gathering additional context as needed. Use '${ToolNames.GREP}', '${ToolNames.GLOB}', '${ToolNames.READ_FILE}', and '${ToolNames.READ_MANY_FILES}' tools strategically when you encounter specific unknowns during implementation. Use the available tools (e.g., '${ToolNames.EDIT}', '${ToolNames.WRITE_FILE}' '${ToolNames.SHELL}' ...) to act on the plan, strictly adhering to the project's established conventions (detailed under 'Core Mandates').
- **Adapt:** As you discover new information or encounter obstacles, update your plan and todos accordingly. Mark todos as in_progress when starting and completed when finishing each task. Add new todos if the scope expands. Refine your approach based on what you learn.
- **Verify (Tests):** If applicable and feasible, verify the changes using the project's testing procedures. Identify the correct test commands and frameworks by examining 'README' files, build/package configuration (e.g., 'package.json'), or existing test execution patterns. NEVER assume standard test commands.
- **Verify (Standards):** VERY IMPORTANT: After making code changes, execute the project-specific build, linting and type-checking commands (e.g., 'tsc', 'npm run lint', 'ruff check .') that you have identified for this project (or obtained from the user). This ensures code quality and adherence to standards. If unsure about these commands, you can ask the user if they'd like you to run them and if so how to.

**Key Principle:** Start with a reasonable plan based on available information, then adapt as you learn. Users prefer seeing progress quickly rather than waiting for perfect understanding.

- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.

IMPORTANT: Always use the ${ToolNames.TODO_WRITE} tool to plan and track tasks throughout the conversation.

## New Applications

**Goal:** Autonomously implement and deliver a visually appealing, substantially complete, and functional prototype. Utilize all tools at your disposal to implement the application. Some tools you may especially find useful are '${ToolNames.WRITE_FILE}', '${ToolNames.EDIT}' and '${ToolNames.SHELL}'.

1. **Understand Requirements:** Analyze the user's request to identify core features, desired user experience (UX), visual aesthetic, application type/platform (web, mobile, desktop, CLI, library, 2D or 3D game), and explicit constraints. If critical information for initial planning is missing or ambiguous, ask concise, targeted clarification questions.
2. **Propose Plan:** Formulate an internal development plan. Present a clear, concise, high-level summary to the user. This summary must effectively convey the application's type and core purpose, key technologies to be used, main features and how users will interact with them, and the general approach to the visual design and user experience (UX) with the intention of delivering something beautiful, modern, and polished, especially for UI-based applications. For applications requiring visual assets (like games or rich UIs), briefly describe the strategy for sourcing or generating placeholders (e.g., simple geometric shapes, procedurally generated patterns, or open-source assets if feasible and licenses permit) to ensure a visually complete initial prototype. Ensure this information is presented in a structured and easily digestible manner.
  - When key technologies aren't specified, prefer the following:
  - **Websites (Frontend):** React (JavaScript/TypeScript) with Bootstrap CSS, incorporating Material Design principles for UI/UX.
  - **Back-End APIs:** Node.js with Express.js (JavaScript/TypeScript) or Python with FastAPI.
  - **Full-stack:** Next.js (React/Node.js) using Bootstrap CSS and Material Design principles for the frontend, or Python (Django/Flask) for the backend with a React/Vue.js frontend styled with Bootstrap CSS and Material Design principles.
  - **CLIs:** Python or Go.
  - **Mobile App:** Compose Multiplatform (Kotlin Multiplatform) or Flutter (Dart) using Material Design libraries and principles, when sharing code between Android and iOS. Jetpack Compose (Kotlin JVM) with Material Design principles or SwiftUI (Swift) for native apps targeted at either Android or iOS, respectively.
  - **3d Games:** HTML/CSS/JavaScript with Three.js.
  - **2d Games:** HTML/CSS/JavaScript.
3. **User Approval:** Obtain user approval for the proposed plan.
4. **Implementation:** Use the '${ToolNames.TODO_WRITE}' tool to convert the approved plan into a structured todo list with specific, actionable tasks, then autonomously implement each task utilizing all available tools. When starting ensure you scaffold the application using '${ToolNames.SHELL}' for commands like 'npm init', 'npx create-react-app'. Aim for full scope completion. Proactively create or source necessary placeholder assets (e.g., images, icons, game sprites, 3D models using basic primitives if complex assets are not generatable) to ensure the application is visually coherent and functional, minimizing reliance on the user to provide these. If the model can generate simple assets (e.g., a uniformly colored square sprite, a simple 3D cube), it should do so. Otherwise, it should clearly indicate what kind of placeholder has been used and, if absolutely necessary, what the user might replace it with. Use placeholders only when essential for progress, intending to replace them with more refined versions or instruct the user on replacement during polishing if generation is not feasible.
5. **Verify:** Review work against the original request, the approved plan. Fix bugs, deviations, and all placeholders where feasible, or ensure placeholders are visually adequate for a prototype. Ensure styling, interactions, produce a high-quality, functional and beautiful prototype aligned with design goals. Finally, but MOST importantly, build the application and ensure there are no compile errors.
6. **Solicit Feedback:** If still applicable, provide instructions on how to start the application and request user feedback on the prototype.

# Operational Guidelines

## Tone and Style (CLI Interaction)
- **Concise & Direct:** Adopt a professional, direct, and concise tone suitable for a CLI environment.
- **Minimal Output:** Aim for fewer than 3 lines of text output (excluding tool use/code generation) per response whenever practical. Focus strictly on the user's query.
- **Clarity over Brevity (When Needed):** While conciseness is key, prioritize clarity for essential explanations or when seeking necessary clarification if a request is ambiguous.
- **No Chitchat:** Avoid conversational filler, preambles ("Okay, I will now..."), or postambles ("I have finished the changes..."). Get straight to the action or answer.
- **Formatting:** Use GitHub-flavored Markdown. Responses will be rendered in monospace.
- **Tools vs. Text:** Use tools for actions, text output *only* for communication. Do not add explanatory comments within tool calls or code blocks unless specifically part of the required code/command itself.
- **Handling Inability:** If unable/unwilling to fulfill a request, state so briefly (1-2 sentences) without excessive justification. Offer alternatives if appropriate.

## Security and Safety Rules
- **Explain Critical Commands:** Before executing commands with '${ToolNames.SHELL}' that modify the file system, codebase, or system state, you *must* provide a brief explanation of the command's purpose and potential impact. Prioritize user understanding and safety. You should not ask permission to use the tool; the user will be presented with a confirmation dialogue upon use (you do not need to tell them this).
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.

## Tool Usage
- **File Paths:** Always use absolute paths when referring to files with tools like '${ToolNames.READ_FILE}' or '${ToolNames.WRITE_FILE}'. Relative paths are not supported. You must provide an absolute path.
- **Parallelism:** Execute multiple independent tool calls in parallel when feasible (i.e. searching the codebase).
- **Command Execution:** Use the '${ToolNames.SHELL}' tool for running shell commands, remembering the safety rule to explain modifying commands first.
- **Background Processes:** Use background processes (via \`&\`) for commands that are unlikely to stop on their own, e.g. \`node server.js &\`. If unsure, ask the user.
- **Interactive Commands:** Try to avoid shell commands that are likely to require user interaction (e.g. \`git rebase -i\`). Use non-interactive versions of commands (e.g. \`npm init -y\` instead of \`npm init\`) when available, and otherwise remind the user that interactive shell commands are not supported and may cause hangs until canceled by the user.
- **Task Management:** Use the '${ToolNames.TODO_WRITE}' tool proactively for complex, multi-step tasks to track progress and provide visibility to users. This tool helps organize work systematically and ensures no requirements are missed.
- **Subagent Delegation:** When doing file search, prefer to use the '${ToolNames.TASK}' tool in order to reduce context usage. You should proactively use the '${ToolNames.TASK}' tool with specialized agents when the task at hand matches the agent's description.
- **Remembering Facts:** Use the '${ToolNames.MEMORY}' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.

## Interaction Details
- **Help Command:** The user can use '/help' to display help information.
- **Feedback:** To report a bug or provide feedback, please use the /bug command.

${function() {
    const isSandboxExec = process18.env["SANDBOX"] === "sandbox-exec";
    const isGenericSandbox = !!process18.env["SANDBOX"];
    if (isSandboxExec) {
      return `
# macOS Seatbelt
You are running under macos seatbelt with limited access to files outside the project directory or system temp directory, and with limited access to host system resources such as ports. If you encounter failures that could be due to MacOS Seatbelt (e.g. if a command fails with 'Operation not permitted' or similar error), as you report the error to the user, also explain why you think it could be due to MacOS Seatbelt, and how the user may need to adjust their Seatbelt profile.
`;
    } else if (isGenericSandbox) {
      return `
# Sandbox
You are running in a sandbox container with limited access to files outside the project directory or system temp directory, and with limited access to host system resources such as ports. If you encounter failures that could be due to sandboxing (e.g. if a command fails with 'Operation not permitted' or similar error), when you report the error to the user, also explain why you think it could be due to sandboxing, and how the user may need to adjust their sandbox configuration.
`;
    } else {
      return `
# Outside of Sandbox
You are running outside of a sandbox container, directly on the user's system. For critical commands that are particularly likely to modify the user's system outside of the project directory or system temp directory, as you explain the command to the user (per the Explain Critical Commands rule above), also remind the user to consider enabling sandboxing.
`;
    }
  }()}

${function() {
    if (isGitRepository(process18.cwd())) {
      return `
# Git Repository
- The current working (project) directory is being managed by a git repository.
- When asked to commit changes or prepare a commit, always start by gathering information using shell commands:
  - \`git status\` to ensure that all relevant files are tracked and staged, using \`git add ...\` as needed.
  - \`git diff HEAD\` to review all changes (including unstaged changes) to tracked files in work tree since last commit.
    - \`git diff --staged\` to review only staged changes when a partial commit makes sense or was requested by the user.
  - \`git log -n 3\` to review recent commit messages and match their style (verbosity, formatting, signature line, etc.)
- Combine shell commands whenever possible to save time/steps, e.g. \`git status && git diff HEAD && git log -n 3\`.
- Always propose a draft commit message. Never just ask the user to give you the full commit message.
- Prefer commit messages that are clear, concise, and focused more on "why" and less on "what".
- Keep the user informed and ask for clarification or confirmation where needed.
- After each commit, confirm that it was successful by running \`git status\`.
- If a commit fails, never attempt to work around the issues without being asked to do so.
- Never push changes to a remote repository without being asked explicitly by the user.
`;
    }
    return "";
  }()}

${getToolCallExamples(model || "")}

# Final Reminder
Your core function is efficient and safe assistance. Balance extreme conciseness with the crucial need for clarity, especially regarding safety and potential system modifications. Always prioritize user control and project conventions. Never make assumptions about the contents of files; instead use '${ToolNames.READ_FILE}' or '${ToolNames.READ_MANY_FILES}' to ensure you aren't making broad assumptions. Finally, you are an agent - please keep going until the user's query is completely resolved.
`.trim();
  const writeSystemMdResolution = resolvePathFromEnv(process18.env["QWEN_WRITE_SYSTEM_MD"]);
  if (writeSystemMdResolution.value && !writeSystemMdResolution.isDisabled) {
    const writePath = writeSystemMdResolution.isSwitch ? systemMdPath : writeSystemMdResolution.value;
    fs21.mkdirSync(path17.dirname(writePath), { recursive: true });
    fs21.writeFileSync(writePath, basePrompt);
  }
  const memorySuffix = userMemory && userMemory.trim().length > 0 ? `

---

${userMemory.trim()}` : "";
  return `${basePrompt}${memorySuffix}`;
}
function getCompressionPrompt() {
  return `
You are the component that summarizes internal chat history into a given structure.

When the conversation history grows too large, you will be invoked to distill the entire history into a concise, structured XML snapshot. This snapshot is CRITICAL, as it will become the agent's *only* memory of the past. The agent will resume its work based solely on this snapshot. All crucial details, plans, errors, and user directives MUST be preserved.

First, you will think through the entire history in a private <scratchpad>. Review the user's overall goal, the agent's actions, tool outputs, file modifications, and any unresolved questions. Identify every piece of information that is essential for future actions.

After your reasoning is complete, generate the final <state_snapshot> XML object. Be incredibly dense with information. Omit any irrelevant conversational filler.

The structure MUST be as follows:

<state_snapshot>
    <overall_goal>
        <!-- A single, concise sentence describing the user's high-level objective. -->
        <!-- Example: "Refactor the authentication service to use a new JWT library." -->
    </overall_goal>

    <key_knowledge>
        <!-- Crucial facts, conventions, and constraints the agent must remember based on the conversation history and interaction with the user. Use bullet points. -->
        <!-- Example:
         - Build Command: \`npm run build\`
         - Testing: Tests are run with \`npm test\`. Test files must end in \`.test.ts\`.
         - API Endpoint: The primary API endpoint is \`https://api.example.com/v2\`.
         
        -->
    </key_knowledge>

    <file_system_state>
        <!-- List files that have been created, read, modified, or deleted. Note their status and critical learnings. -->
        <!-- Example:
         - CWD: \`/home/user/project/src\`
         - READ: \`package.json\` - Confirmed 'axios' is a dependency.
         - MODIFIED: \`services/auth.ts\` - Replaced 'jsonwebtoken' with 'jose'.
         - CREATED: \`tests/new-feature.test.ts\` - Initial test structure for the new feature.
        -->
    </file_system_state>

    <recent_actions>
        <!-- A summary of the last few significant agent actions and their outcomes. Focus on facts. -->
        <!-- Example:
         - Ran \`grep 'old_function'\` which returned 3 results in 2 files.
         - Ran \`npm run test\`, which failed due to a snapshot mismatch in \`UserProfile.test.ts\`.
         - Ran \`ls -F static/\` and discovered image assets are stored as \`.webp\`.
        -->
    </recent_actions>

    <current_plan>
        <!-- The agent's step-by-step plan. Mark completed steps. -->
        <!-- Example:
         1. [DONE] Identify all files using the deprecated 'UserAPI'.
         2. [IN PROGRESS] Refactor \`src/components/UserProfile.tsx\` to use the new 'ProfileAPI'.
         3. [TODO] Refactor the remaining files.
         4. [TODO] Update tests to reflect the API change.
        -->
    </current_plan>
</state_snapshot>
`.trim();
}
function getProjectSummaryPrompt() {
  return `Please analyze the conversation history above and generate a comprehensive project summary in markdown format. Focus on extracting the most important context, decisions, and progress that would be valuable for future sessions. Generate the summary directly without using any tools.
You are a specialized context summarizer that creates a comprehensive markdown summary from chat history for future reference. The markdown format is as follows:

# Project Summary

## Overall Goal
<!-- A single, concise sentence describing the user's high-level objective -->

## Key Knowledge
<!-- Crucial facts, conventions, and constraints the agent must remember -->
<!-- Include: technology choices, architecture decisions, user preferences, build commands, testing procedures -->

## Recent Actions
<!-- Summary of significant recent work and outcomes -->
<!-- Include: accomplishments, discoveries, recent changes -->

## Current Plan
<!-- The current development roadmap and next steps -->
<!-- Use status markers: [DONE], [IN PROGRESS], [TODO] -->
<!-- Example: 1. [DONE] Set up WebSocket server -->

`.trim();
}
function getToolCallExamples(model) {
  const toolCallStyle = process18.env["QWEN_CODE_TOOL_CALL_STYLE"];
  if (toolCallStyle) {
    switch (toolCallStyle.toLowerCase()) {
      case "qwen-coder":
        return qwenCoderToolCallExamples;
      case "qwen-vl":
        return qwenVlToolCallExamples;
      case "general":
        return generalToolCallExamples;
      default:
        console.warn(`Unknown QWEN_CODE_TOOL_CALL_STYLE value: ${toolCallStyle}. Using model-based detection.`);
        break;
    }
  }
  if (model && model.length < 100) {
    if (/qwen[^-]*-coder/i.test(model)) {
      return qwenCoderToolCallExamples;
    }
    if (/qwen[^-]*-vl/i.test(model)) {
      return qwenVlToolCallExamples;
    }
    if (/coder-model/i.test(model)) {
      return qwenCoderToolCallExamples;
    }
    if (/vision-model/i.test(model)) {
      return qwenVlToolCallExamples;
    }
  }
  return generalToolCallExamples;
}
function getSubagentSystemReminder(agentTypes) {
  return `<system-reminder>You have powerful specialized agents at your disposal, available agent types are: ${agentTypes.join(", ")}. PROACTIVELY use the ${ToolNames.TASK} tool to delegate user's task to appropriate agent when user's task matches agent capabilities. Ignore this message if user's task is not relevant to any agent. This message is for internal use only. Do not mention this to user in your response.</system-reminder>`;
}
function getPlanModeSystemReminder() {
  return `<system-reminder>
Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supercedes any other instructions you have received (for example, to make edits). Instead, you should:
1. Answer the user's query comprehensively
2. When you're done researching, present your plan by calling the ${ToolNames.EXIT_PLAN_MODE} tool, which will prompt the user to confirm the plan. Do NOT make any file changes or run any tools that modify the system state in any way until the user has confirmed the plan.
</system-reminder>`;
}
var generalToolCallExamples, qwenCoderToolCallExamples, qwenVlToolCallExamples;
var init_prompts = __esm({
  "packages/core/dist/src/core/prompts.js"() {
    "use strict";
    init_esbuild_shims();
    init_tool_names();
    init_gitUtils();
    init_memoryTool();
    __name(resolvePathFromEnv, "resolvePathFromEnv");
    __name(getCustomSystemPrompt, "getCustomSystemPrompt");
    __name(getCoreSystemPrompt, "getCoreSystemPrompt");
    __name(getCompressionPrompt, "getCompressionPrompt");
    __name(getProjectSummaryPrompt, "getProjectSummaryPrompt");
    generalToolCallExamples = `
# Examples (Illustrating Tone and Workflow)
<example>
user: 1 + 2
model: 3
</example>

<example>
user: is 13 a prime number?
model: true
</example>

<example>
user: start the server implemented in server.js
model: [tool_call: ${ToolNames.SHELL} for 'node server.js &' because it must run in the background]
</example>

<example>
user: Refactor the auth logic in src/auth.py to use the requests library instead of urllib.
model: Okay, I can refactor 'src/auth.py'.
First, I'll analyze the code and check for a test safety net before planning any changes.
[tool_call: ${ToolNames.GLOB} for path 'tests/test_auth.py']
[tool_call: ${ToolNames.READ_FILE} for path '/path/to/tests/test_auth.py' with offset 0 and limit 10]
(After analysis)
Great, 'tests/test_auth.py' exists and covers the core authentication logic. With this safety net in place, I can safely plan the refactoring.
I'll also confirm 'requests' is a dependency.
[tool_call: ${ToolNames.READ_FILE} for path '/path/to/requirements.txt']
(After analysis)
Looks good, 'requests' is available.

Here's the plan:
1.  Replace the 'urllib' calls with 'requests'.
2.  Add proper 'try...except' error handling for the new network calls.
3.  Remove the old 'urllib' import.
4.  Run the project's linter and tests to verify the changes.

[tool_call: ${ToolNames.EDIT} for path 'src/auth.py' replacing old content with new content]
Refactoring complete. Running verification...
[tool_call: ${ToolNames.SHELL} for 'ruff check src/auth.py && pytest']
(After verification passes)
All checks passed. This is a stable checkpoint.
Would you like me to write a commit message and commit these changes?
</example>

<example>
user: Delete the temp directory.
model: I can run \`rm -rf /path/to/project/temp\`. This will permanently delete the directory and all its contents.
</example>

<example>
user: Write tests for someFile.ts
model:
Okay, I can write those tests. First, I'll read someFile.ts to understand its functionality.
[tool_call: ${ToolNames.READ_FILE} for path '/path/to/someFile.ts']
Now I'll look for existing or related test files to understand current testing conventions and dependencies.
[tool_call: ${ToolNames.READ_MANY_FILES} for paths ['**/*.test.ts', 'src/**/*.spec.ts']]
(After reviewing existing tests and the file content)
[tool_call: ${ToolNames.WRITE_FILE} for path '/path/to/someFile.test.ts']
I've written the tests. Now I'll run the project's test command to verify them.
[tool_call: ${ToolNames.SHELL} for 'npm run test']
(After verification passes)
All checks passed. This is a stable checkpoint.
</example>

<example>
user: Where are all the 'app.config' files in this project? I need to check their settings.
model:
[tool_call: ${ToolNames.GLOB} for pattern './**/app.config']
(Assuming GlobTool returns a list of paths like ['/path/to/moduleA/app.config', '/path/to/moduleB/app.config'])
I found the following 'app.config' files:
- /path/to/moduleA/app.config
- /path/to/moduleB/app.config
To help you check their settings, I can read their contents. Which one would you like to start with, or should I read all of them?
</example>
`.trim();
    qwenCoderToolCallExamples = `
# Examples (Illustrating Tone and Workflow)
<example>
user: 1 + 2
model: 3
</example>

<example>
user: is 13 a prime number?
model: true
</example>

<example>
user: start the server implemented in server.js
model: 
<tool_call>
<function=${ToolNames.SHELL}>
<parameter=command>
node server.js &
</parameter>
</function>
</tool_call>
</example>

<example>
user: Refactor the auth logic in src/auth.py to use the requests library instead of urllib.
model: Okay, I can refactor 'src/auth.py'.
First, I'll analyze the code and check for a test safety net before planning any changes.
<tool_call>
<function=${ToolNames.GLOB}>
<parameter=path>
tests/test_auth.py
</parameter>
</function>
</tool_call>
<tool_call>
<function=${ToolNames.READ_FILE}>
<parameter=path>
/path/to/tests/test_auth.py
</parameter>
<parameter=offset>
0
</parameter>
<parameter=limit>
10
</parameter>
</function>
</tool_call>
(After analysis)
Great, 'tests/test_auth.py' exists and covers the core authentication logic. With this safety net in place, I can safely plan the refactoring.
I'll also confirm 'requests' is a dependency.
<tool_call>
<function=${ToolNames.READ_FILE}>
<parameter=path>
/path/to/requirements.txt
</parameter>
</function>
</tool_call>
(After analysis)
Looks good, 'requests' is available.

Here's the plan:
1.  Replace the 'urllib' calls with 'requests'.
2.  Add proper 'try...except' error handling for the new network calls.
3.  Remove the old 'urllib' import.
4.  Run the project's linter and tests to verify the changes.

<tool_call>
<function=${ToolNames.EDIT}>
<parameter=path>
src/auth.py
</parameter>
<parameter=old_content>
(old code content)
</parameter>
<parameter=new_content>
(new code content)
</parameter>
</function>
</tool_call>
Refactoring complete. Running verification...
<tool_call>
<function=${ToolNames.SHELL}>
<parameter=command>
ruff check src/auth.py && pytest
</parameter>
</function>
</tool_call>
(After verification passes)
All checks passed. This is a stable checkpoint.
Would you like me to write a commit message and commit these changes?
</example>

<example>
user: Delete the temp directory.
model: I can run \`rm -rf /path/to/project/temp\`. This will permanently delete the directory and all its contents.
</example>

<example>
user: Write tests for someFile.ts
model:
Okay, I can write those tests. First, I'll read someFile.ts to understand its functionality.
<tool_call>
<function=${ToolNames.READ_FILE}>
<parameter=path>
/path/to/someFile.ts
</parameter>
</function>
</tool_call>
Now I'll look for existing or related test files to understand current testing conventions and dependencies.
<tool_call>
<function=${ToolNames.READ_MANY_FILES}>
<parameter=paths>
['**/*.test.ts', 'src/**/*.spec.ts']
</parameter>
</function>
</tool_call>
(After reviewing existing tests and the file content)
<tool_call>
<function=${ToolNames.WRITE_FILE}>
<parameter=path>
/path/to/someFile.test.ts
</parameter>
</function>
</tool_call>
I've written the tests. Now I'll run the project's test command to verify them.
<tool_call>
<function=${ToolNames.SHELL}>
<parameter=command>
npm run test
</parameter>
</function>
</tool_call>
(After verification passes)
All checks passed. This is a stable checkpoint.
</example>

<example>
user: Where are all the 'app.config' files in this project? I need to check their settings.
model:
<tool_call>
<function=${ToolNames.GLOB}>
<parameter=pattern>
./**/app.config
</parameter>
</function>
</tool_call>
(Assuming GlobTool returns a list of paths like ['/path/to/moduleA/app.config', '/path/to/moduleB/app.config'])
I found the following 'app.config' files:
- /path/to/moduleA/app.config
- /path/to/moduleB/app.config
To help you check their settings, I can read their contents. Which one would you like to start with, or should I read all of them?
</example>
`.trim();
    qwenVlToolCallExamples = `
# Examples (Illustrating Tone and Workflow)
<example>
user: 1 + 2
model: 3
</example>

<example>
user: is 13 a prime number?
model: true
</example>

<example>
user: start the server implemented in server.js
model: 
<tool_call>
{"name": "${ToolNames.SHELL}", "arguments": {"command": "node server.js &"}}
</tool_call>
</example>

<example>
user: Refactor the auth logic in src/auth.py to use the requests library instead of urllib.
model: Okay, I can refactor 'src/auth.py'.
First, I'll analyze the code and check for a test safety net before planning any changes.
<tool_call>
{"name": "${ToolNames.GLOB}", "arguments": {"path": "tests/test_auth.py"}}
</tool_call>
<tool_call>
{"name": "${ToolNames.READ_FILE}", "arguments": {"path": "/path/to/tests/test_auth.py", "offset": 0, "limit": 10}}
</tool_call>
(After analysis)
Great, 'tests/test_auth.py' exists and covers the core authentication logic. With this safety net in place, I can safely plan the refactoring.
I'll also confirm 'requests' is a dependency.
<tool_call>
{"name": "${ToolNames.READ_FILE}", "arguments": {"path": "/path/to/requirements.txt"}}
</tool_call>
(After analysis)
Looks good, 'requests' is available.

Here's the plan:
1.  Replace the 'urllib' calls with 'requests'.
2.  Add proper 'try...except' error handling for the new network calls.
3.  Remove the old 'urllib' import.
4.  Run the project's linter and tests to verify the changes.

<tool_call>
{"name": "${ToolNames.EDIT}", "arguments": {"path": "src/auth.py", "old_content": "(old code content)", "new_content": "(new code content)"}}
</tool_call>
Refactoring complete. Running verification...
<tool_call>
{"name": "${ToolNames.SHELL}", "arguments": {"command": "ruff check src/auth.py && pytest"}}
</tool_call>
(After verification passes)
All checks passed. This is a stable checkpoint.
Would you like me to write a commit message and commit these changes?
</example>

<example>
user: Delete the temp directory.
model: I can run \`rm -rf /path/to/project/temp\`. This will permanently delete the directory and all its contents.
</example>

<example>
user: Write tests for someFile.ts
model:
Okay, I can write those tests. First, I'll read someFile.ts to understand its functionality.
<tool_call>
{"name": "${ToolNames.READ_FILE}", "arguments": {"path": "/path/to/someFile.ts"}}
</tool_call>
Now I'll look for existing or related test files to understand current testing conventions and dependencies.
<tool_call>
{"name": "${ToolNames.READ_MANY_FILES}", "arguments": {"paths": ["**/*.test.ts", "src/**/*.spec.ts"]}}
</tool_call>
(After reviewing existing tests and the file content)
<tool_call>
{"name": "${ToolNames.WRITE_FILE}", "arguments": {"path": "/path/to/someFile.test.ts"}}
</tool_call>
I've written the tests. Now I'll run the project's test command to verify them.
<tool_call>
{"name": "${ToolNames.SHELL}", "arguments": {"command": "npm run test"}}
</tool_call>
(After verification passes)
All checks passed. This is a stable checkpoint.
</example>

<example>
user: Where are all the 'app.config' files in this project? I need to check their settings.
model:
<tool_call>
{"name": "${ToolNames.GLOB}", "arguments": {"pattern": "./**/app.config"}}
</tool_call>
(Assuming GlobTool returns a list of paths like ['/path/to/moduleA/app.config', '/path/to/moduleB/app.config'])
I found the following 'app.config' files:
- /path/to/moduleA/app.config
- /path/to/moduleB/app.config
To help you check their settings, I can read their contents. Which one would you like to start with, or should I read all of them?
</example>
`.trim();
    __name(getToolCallExamples, "getToolCallExamples");
    __name(getSubagentSystemReminder, "getSubagentSystemReminder");
    __name(getPlanModeSystemReminder, "getPlanModeSystemReminder");
  }
});

// packages/core/dist/src/utils/summarizer.js
async function summarizeToolOutput(textToSummarize, geminiClient, abortSignal, maxOutputTokens = 2e3) {
  if (!textToSummarize || textToSummarize.length < maxOutputTokens) {
    return textToSummarize;
  }
  const prompt = SUMMARIZE_TOOL_OUTPUT_PROMPT.replace("{maxOutputTokens}", String(maxOutputTokens)).replace("{textToSummarize}", textToSummarize);
  const contents = [{ role: "user", parts: [{ text: prompt }] }];
  const toolOutputSummarizerConfig = {
    maxOutputTokens
  };
  try {
    const parsedResponse = await geminiClient.generateContent(contents, toolOutputSummarizerConfig, abortSignal, DEFAULT_GEMINI_FLASH_LITE_MODEL);
    return getResponseText(parsedResponse) || textToSummarize;
  } catch (error) {
    console.error("Failed to summarize tool output.", error);
    return textToSummarize;
  }
}
var SUMMARIZE_TOOL_OUTPUT_PROMPT;
var init_summarizer = __esm({
  "packages/core/dist/src/utils/summarizer.js"() {
    "use strict";
    init_esbuild_shims();
    init_models();
    init_partUtils();
    SUMMARIZE_TOOL_OUTPUT_PROMPT = `Summarize the following tool output to be a maximum of {maxOutputTokens} tokens. The summary should be concise and capture the main points of the tool output.

The summarization should be done based on the content that is provided. Here are the basic rules to follow:
1. If the text is a directory listing or any output that is structural, use the history of the conversation to understand the context. Using this context try to understand what information we need from the tool output and return that as a response.
2. If the text is text content and there is nothing structural that we need, summarize the text.
3. If the text is the output of a shell command, use the history of the conversation to understand the context. Using this context try to understand what information we need from the tool output and return a summarization along with the stack trace of any error within the <error></error> tags. The stack trace should be complete and not truncated. If there are warnings, you should include them in the summary within <warning></warning> tags.


Text to summarize:
"{textToSummarize}"

Return the summary string which should first contain an overall summarization of text followed by the full stack trace of errors and warnings in the tool output.
`;
    __name(summarizeToolOutput, "summarizeToolOutput");
  }
});

// packages/core/dist/src/utils/getPty.js
var getPty;
var init_getPty = __esm({
  "packages/core/dist/src/utils/getPty.js"() {
    "use strict";
    init_esbuild_shims();
    getPty = /* @__PURE__ */ __name(async () => {
      try {
        const lydell = "@lydell/node-pty";
        const module2 = await import(lydell);
        return { module: module2, name: "lydell-node-pty" };
      } catch (_e) {
        try {
          const nodePty = "node-pty";
          const module2 = await import(nodePty);
          return { module: module2, name: "node-pty" };
        } catch (_e2) {
          return null;
        }
      }
    }, "getPty");
  }
});

// node_modules/chardet/lib/fs/node.js
var require_node16 = __commonJS({
  "node_modules/chardet/lib/fs/node.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var fsModule;
    exports2.default = () => {
      if (typeof module2 === "object" && typeof module2.exports === "object") {
        fsModule = fsModule ? fsModule : __require("fs");
        return fsModule;
      }
      throw new Error("File system is not available");
    };
  }
});

// node_modules/chardet/lib/match.js
var require_match = __commonJS({
  "node_modules/chardet/lib/match.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.default = (ctx, rec, confidence) => ({
      confidence,
      name: rec.name(ctx),
      lang: rec.language ? rec.language() : void 0
    });
  }
});

// node_modules/chardet/lib/encoding/ascii.js
var require_ascii2 = __commonJS({
  "node_modules/chardet/lib/encoding/ascii.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
      return mod2 && mod2.__esModule ? mod2 : { "default": mod2 };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    var match_1 = __importDefault(require_match());
    var Ascii = class {
      static {
        __name(this, "Ascii");
      }
      name() {
        return "ASCII";
      }
      match(det) {
        const input = det.rawInput;
        for (let i = 0; i < det.rawLen; i++) {
          const b = input[i];
          if (b < 32 || b > 126) {
            return (0, match_1.default)(det, this, 0);
          }
        }
        return (0, match_1.default)(det, this, 100);
      }
    };
    exports2.default = Ascii;
  }
});

// node_modules/chardet/lib/encoding/utf8.js
var require_utf82 = __commonJS({
  "node_modules/chardet/lib/encoding/utf8.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
      return mod2 && mod2.__esModule ? mod2 : { "default": mod2 };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    var match_1 = __importDefault(require_match());
    var Utf8 = class {
      static {
        __name(this, "Utf8");
      }
      name() {
        return "UTF-8";
      }
      match(det) {
        let hasBOM = false, numValid = 0, numInvalid = 0, trailBytes = 0, confidence;
        const input = det.rawInput;
        if (det.rawLen >= 3 && (input[0] & 255) == 239 && (input[1] & 255) == 187 && (input[2] & 255) == 191) {
          hasBOM = true;
        }
        for (let i = 0; i < det.rawLen; i++) {
          const b = input[i];
          if ((b & 128) == 0)
            continue;
          if ((b & 224) == 192) {
            trailBytes = 1;
          } else if ((b & 240) == 224) {
            trailBytes = 2;
          } else if ((b & 248) == 240) {
            trailBytes = 3;
          } else {
            numInvalid++;
            if (numInvalid > 5)
              break;
            trailBytes = 0;
          }
          for (; ; ) {
            i++;
            if (i >= det.rawLen)
              break;
            if ((input[i] & 192) != 128) {
              numInvalid++;
              break;
            }
            if (--trailBytes == 0) {
              numValid++;
              break;
            }
          }
        }
        confidence = 0;
        if (hasBOM && numInvalid == 0)
          confidence = 100;
        else if (hasBOM && numValid > numInvalid * 10)
          confidence = 80;
        else if (numValid > 3 && numInvalid == 0)
          confidence = 100;
        else if (numValid > 0 && numInvalid == 0)
          confidence = 80;
        else if (numValid == 0 && numInvalid == 0)
          confidence = 10;
        else if (numValid > numInvalid * 10)
          confidence = 25;
        else
          return null;
        return (0, match_1.default)(det, this, confidence);
      }
    };
    exports2.default = Utf8;
  }
});

// node_modules/chardet/lib/encoding/unicode.js
var require_unicode = __commonJS({
  "node_modules/chardet/lib/encoding/unicode.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
      return mod2 && mod2.__esModule ? mod2 : { "default": mod2 };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.UTF_32LE = exports2.UTF_32BE = exports2.UTF_16LE = exports2.UTF_16BE = void 0;
    var match_1 = __importDefault(require_match());
    var UTF_16BE = class {
      static {
        __name(this, "UTF_16BE");
      }
      name() {
        return "UTF-16BE";
      }
      match(det) {
        const input = det.rawInput;
        if (input.length >= 2 && (input[0] & 255) == 254 && (input[1] & 255) == 255) {
          return (0, match_1.default)(det, this, 100);
        }
        return null;
      }
    };
    exports2.UTF_16BE = UTF_16BE;
    var UTF_16LE = class {
      static {
        __name(this, "UTF_16LE");
      }
      name() {
        return "UTF-16LE";
      }
      match(det) {
        const input = det.rawInput;
        if (input.length >= 2 && (input[0] & 255) == 255 && (input[1] & 255) == 254) {
          if (input.length >= 4 && input[2] == 0 && input[3] == 0) {
            return null;
          }
          return (0, match_1.default)(det, this, 100);
        }
        return null;
      }
    };
    exports2.UTF_16LE = UTF_16LE;
    var UTF_32 = class {
      static {
        __name(this, "UTF_32");
      }
      name() {
        return "UTF-32";
      }
      getChar(_input, _index) {
        return -1;
      }
      match(det) {
        let numValid = 0, numInvalid = 0, hasBOM = false, confidence = 0;
        const limit2 = det.rawLen / 4 * 4;
        const input = det.rawInput;
        if (limit2 == 0) {
          return null;
        }
        if (this.getChar(input, 0) == 65279) {
          hasBOM = true;
        }
        for (let i = 0; i < limit2; i += 4) {
          const ch = this.getChar(input, i);
          if (ch < 0 || ch >= 1114111 || ch >= 55296 && ch <= 57343) {
            numInvalid += 1;
          } else {
            numValid += 1;
          }
        }
        if (hasBOM && numInvalid == 0) {
          confidence = 100;
        } else if (hasBOM && numValid > numInvalid * 10) {
          confidence = 80;
        } else if (numValid > 3 && numInvalid == 0) {
          confidence = 100;
        } else if (numValid > 0 && numInvalid == 0) {
          confidence = 80;
        } else if (numValid > numInvalid * 10) {
          confidence = 25;
        }
        return confidence == 0 ? null : (0, match_1.default)(det, this, confidence);
      }
    };
    var UTF_32BE = class extends UTF_32 {
      static {
        __name(this, "UTF_32BE");
      }
      name() {
        return "UTF-32BE";
      }
      getChar(input, index) {
        return (input[index + 0] & 255) << 24 | (input[index + 1] & 255) << 16 | (input[index + 2] & 255) << 8 | input[index + 3] & 255;
      }
    };
    exports2.UTF_32BE = UTF_32BE;
    var UTF_32LE = class extends UTF_32 {
      static {
        __name(this, "UTF_32LE");
      }
      name() {
        return "UTF-32LE";
      }
      getChar(input, index) {
        return (input[index + 3] & 255) << 24 | (input[index + 2] & 255) << 16 | (input[index + 1] & 255) << 8 | input[index + 0] & 255;
      }
    };
    exports2.UTF_32LE = UTF_32LE;
  }
});

// node_modules/chardet/lib/encoding/mbcs.js
var require_mbcs = __commonJS({
  "node_modules/chardet/lib/encoding/mbcs.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
      return mod2 && mod2.__esModule ? mod2 : { "default": mod2 };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.gb_18030 = exports2.euc_kr = exports2.euc_jp = exports2.big5 = exports2.sjis = void 0;
    var match_1 = __importDefault(require_match());
    function binarySearch(arr, searchValue) {
      const find = /* @__PURE__ */ __name((arr2, searchValue2, left3, right3) => {
        if (right3 < left3)
          return -1;
        const mid = Math.floor(left3 + right3 >>> 1);
        if (searchValue2 > arr2[mid])
          return find(arr2, searchValue2, mid + 1, right3);
        if (searchValue2 < arr2[mid])
          return find(arr2, searchValue2, left3, mid - 1);
        return mid;
      }, "find");
      return find(arr, searchValue, 0, arr.length - 1);
    }
    __name(binarySearch, "binarySearch");
    var IteratedChar = class {
      static {
        __name(this, "IteratedChar");
      }
      constructor() {
        this.charValue = 0;
        this.index = 0;
        this.nextIndex = 0;
        this.error = false;
        this.done = false;
      }
      reset() {
        this.charValue = 0;
        this.index = -1;
        this.nextIndex = 0;
        this.error = false;
        this.done = false;
      }
      nextByte(det) {
        if (this.nextIndex >= det.rawLen) {
          this.done = true;
          return -1;
        }
        const byteValue = det.rawInput[this.nextIndex++] & 255;
        return byteValue;
      }
    };
    var mbcs = class {
      static {
        __name(this, "mbcs");
      }
      constructor() {
        this.commonChars = [];
      }
      name() {
        return "mbcs";
      }
      match(det) {
        let doubleByteCharCount = 0, commonCharCount = 0, badCharCount = 0, totalCharCount = 0, confidence = 0;
        const iter = new IteratedChar();
        detectBlock: {
          for (iter.reset(); this.nextChar(iter, det); ) {
            totalCharCount++;
            if (iter.error) {
              badCharCount++;
            } else {
              const cv = iter.charValue & 4294967295;
              if (cv > 255) {
                doubleByteCharCount++;
                if (this.commonChars != null) {
                  if (binarySearch(this.commonChars, cv) >= 0) {
                    commonCharCount++;
                  }
                }
              }
            }
            if (badCharCount >= 2 && badCharCount * 5 >= doubleByteCharCount) {
              break detectBlock;
            }
          }
          if (doubleByteCharCount <= 10 && badCharCount == 0) {
            if (doubleByteCharCount == 0 && totalCharCount < 10) {
              confidence = 0;
            } else {
              confidence = 10;
            }
            break detectBlock;
          }
          if (doubleByteCharCount < 20 * badCharCount) {
            confidence = 0;
            break detectBlock;
          }
          if (this.commonChars == null) {
            confidence = 30 + doubleByteCharCount - 20 * badCharCount;
            if (confidence > 100) {
              confidence = 100;
            }
          } else {
            const maxVal = Math.log(doubleByteCharCount / 4);
            const scaleFactor = 90 / maxVal;
            confidence = Math.floor(Math.log(commonCharCount + 1) * scaleFactor + 10);
            confidence = Math.min(confidence, 100);
          }
        }
        return confidence == 0 ? null : (0, match_1.default)(det, this, confidence);
      }
      nextChar(_iter, _det) {
        return true;
      }
    };
    var sjis = class extends mbcs {
      static {
        __name(this, "sjis");
      }
      constructor() {
        super(...arguments);
        this.commonChars = [
          33088,
          33089,
          33090,
          33093,
          33115,
          33129,
          33130,
          33141,
          33142,
          33440,
          33442,
          33444,
          33449,
          33450,
          33451,
          33453,
          33455,
          33457,
          33459,
          33461,
          33463,
          33469,
          33470,
          33473,
          33476,
          33477,
          33478,
          33480,
          33481,
          33484,
          33485,
          33500,
          33504,
          33511,
          33512,
          33513,
          33514,
          33520,
          33521,
          33601,
          33603,
          33614,
          33615,
          33624,
          33630,
          33634,
          33639,
          33653,
          33654,
          33673,
          33674,
          33675,
          33677,
          33683,
          36502,
          37882,
          38314
        ];
      }
      name() {
        return "Shift_JIS";
      }
      language() {
        return "ja";
      }
      nextChar(iter, det) {
        iter.index = iter.nextIndex;
        iter.error = false;
        const firstByte = iter.charValue = iter.nextByte(det);
        if (firstByte < 0)
          return false;
        if (firstByte <= 127 || firstByte > 160 && firstByte <= 223)
          return true;
        const secondByte = iter.nextByte(det);
        if (secondByte < 0)
          return false;
        iter.charValue = firstByte << 8 | secondByte;
        if (!(secondByte >= 64 && secondByte <= 127 || secondByte >= 128 && secondByte <= 255)) {
          iter.error = true;
        }
        return true;
      }
    };
    exports2.sjis = sjis;
    var big5 = class extends mbcs {
      static {
        __name(this, "big5");
      }
      constructor() {
        super(...arguments);
        this.commonChars = [
          41280,
          41281,
          41282,
          41283,
          41287,
          41289,
          41333,
          41334,
          42048,
          42054,
          42055,
          42056,
          42065,
          42068,
          42071,
          42084,
          42090,
          42092,
          42103,
          42147,
          42148,
          42151,
          42177,
          42190,
          42193,
          42207,
          42216,
          42237,
          42304,
          42312,
          42328,
          42345,
          42445,
          42471,
          42583,
          42593,
          42594,
          42600,
          42608,
          42664,
          42675,
          42681,
          42707,
          42715,
          42726,
          42738,
          42816,
          42833,
          42841,
          42970,
          43171,
          43173,
          43181,
          43217,
          43219,
          43236,
          43260,
          43456,
          43474,
          43507,
          43627,
          43706,
          43710,
          43724,
          43772,
          44103,
          44111,
          44208,
          44242,
          44377,
          44745,
          45024,
          45290,
          45423,
          45747,
          45764,
          45935,
          46156,
          46158,
          46412,
          46501,
          46525,
          46544,
          46552,
          46705,
          47085,
          47207,
          47428,
          47832,
          47940,
          48033,
          48593,
          49860,
          50105,
          50240,
          50271
        ];
      }
      name() {
        return "Big5";
      }
      language() {
        return "zh";
      }
      nextChar(iter, det) {
        iter.index = iter.nextIndex;
        iter.error = false;
        const firstByte = iter.charValue = iter.nextByte(det);
        if (firstByte < 0)
          return false;
        if (firstByte <= 127 || firstByte == 255)
          return true;
        const secondByte = iter.nextByte(det);
        if (secondByte < 0)
          return false;
        iter.charValue = iter.charValue << 8 | secondByte;
        if (secondByte < 64 || secondByte == 127 || secondByte == 255)
          iter.error = true;
        return true;
      }
    };
    exports2.big5 = big5;
    function eucNextChar(iter, det) {
      iter.index = iter.nextIndex;
      iter.error = false;
      let firstByte = 0;
      let secondByte = 0;
      let thirdByte = 0;
      buildChar: {
        firstByte = iter.charValue = iter.nextByte(det);
        if (firstByte < 0) {
          iter.done = true;
          break buildChar;
        }
        if (firstByte <= 141) {
          break buildChar;
        }
        secondByte = iter.nextByte(det);
        iter.charValue = iter.charValue << 8 | secondByte;
        if (firstByte >= 161 && firstByte <= 254) {
          if (secondByte < 161) {
            iter.error = true;
          }
          break buildChar;
        }
        if (firstByte == 142) {
          if (secondByte < 161) {
            iter.error = true;
          }
          break buildChar;
        }
        if (firstByte == 143) {
          thirdByte = iter.nextByte(det);
          iter.charValue = iter.charValue << 8 | thirdByte;
          if (thirdByte < 161) {
            iter.error = true;
          }
        }
      }
      return iter.done == false;
    }
    __name(eucNextChar, "eucNextChar");
    var euc_jp = class extends mbcs {
      static {
        __name(this, "euc_jp");
      }
      constructor() {
        super(...arguments);
        this.commonChars = [
          41377,
          41378,
          41379,
          41382,
          41404,
          41418,
          41419,
          41430,
          41431,
          42146,
          42148,
          42150,
          42152,
          42154,
          42155,
          42156,
          42157,
          42159,
          42161,
          42163,
          42165,
          42167,
          42169,
          42171,
          42173,
          42175,
          42176,
          42177,
          42179,
          42180,
          42182,
          42183,
          42184,
          42185,
          42186,
          42187,
          42190,
          42191,
          42192,
          42206,
          42207,
          42209,
          42210,
          42212,
          42216,
          42217,
          42218,
          42219,
          42220,
          42223,
          42226,
          42227,
          42402,
          42403,
          42404,
          42406,
          42407,
          42410,
          42413,
          42415,
          42416,
          42419,
          42421,
          42423,
          42424,
          42425,
          42431,
          42435,
          42438,
          42439,
          42440,
          42441,
          42443,
          42448,
          42453,
          42454,
          42455,
          42462,
          42464,
          42465,
          42469,
          42473,
          42474,
          42475,
          42476,
          42477,
          42483,
          47273,
          47572,
          47854,
          48072,
          48880,
          49079,
          50410,
          50940,
          51133,
          51896,
          51955,
          52188,
          52689
        ];
        this.nextChar = eucNextChar;
      }
      name() {
        return "EUC-JP";
      }
      language() {
        return "ja";
      }
    };
    exports2.euc_jp = euc_jp;
    var euc_kr = class extends mbcs {
      static {
        __name(this, "euc_kr");
      }
      constructor() {
        super(...arguments);
        this.commonChars = [
          45217,
          45235,
          45253,
          45261,
          45268,
          45286,
          45293,
          45304,
          45306,
          45308,
          45496,
          45497,
          45511,
          45527,
          45538,
          45994,
          46011,
          46274,
          46287,
          46297,
          46315,
          46501,
          46517,
          46527,
          46535,
          46569,
          46835,
          47023,
          47042,
          47054,
          47270,
          47278,
          47286,
          47288,
          47291,
          47337,
          47531,
          47534,
          47564,
          47566,
          47613,
          47800,
          47822,
          47824,
          47857,
          48103,
          48115,
          48125,
          48301,
          48314,
          48338,
          48374,
          48570,
          48576,
          48579,
          48581,
          48838,
          48840,
          48863,
          48878,
          48888,
          48890,
          49057,
          49065,
          49088,
          49124,
          49131,
          49132,
          49144,
          49319,
          49327,
          49336,
          49338,
          49339,
          49341,
          49351,
          49356,
          49358,
          49359,
          49366,
          49370,
          49381,
          49403,
          49404,
          49572,
          49574,
          49590,
          49622,
          49631,
          49654,
          49656,
          50337,
          50637,
          50862,
          51151,
          51153,
          51154,
          51160,
          51173,
          51373
        ];
        this.nextChar = eucNextChar;
      }
      name() {
        return "EUC-KR";
      }
      language() {
        return "ko";
      }
    };
    exports2.euc_kr = euc_kr;
    var gb_18030 = class extends mbcs {
      static {
        __name(this, "gb_18030");
      }
      constructor() {
        super(...arguments);
        this.commonChars = [
          41377,
          41378,
          41379,
          41380,
          41392,
          41393,
          41457,
          41459,
          41889,
          41900,
          41914,
          45480,
          45496,
          45502,
          45755,
          46025,
          46070,
          46323,
          46525,
          46532,
          46563,
          46767,
          46804,
          46816,
          47010,
          47016,
          47037,
          47062,
          47069,
          47284,
          47327,
          47350,
          47531,
          47561,
          47576,
          47610,
          47613,
          47821,
          48039,
          48086,
          48097,
          48122,
          48316,
          48347,
          48382,
          48588,
          48845,
          48861,
          49076,
          49094,
          49097,
          49332,
          49389,
          49611,
          49883,
          50119,
          50396,
          50410,
          50636,
          50935,
          51192,
          51371,
          51403,
          51413,
          51431,
          51663,
          51706,
          51889,
          51893,
          51911,
          51920,
          51926,
          51957,
          51965,
          52460,
          52728,
          52906,
          52932,
          52946,
          52965,
          53173,
          53186,
          53206,
          53442,
          53445,
          53456,
          53460,
          53671,
          53930,
          53938,
          53941,
          53947,
          53972,
          54211,
          54224,
          54269,
          54466,
          54490,
          54754,
          54992
        ];
      }
      name() {
        return "GB18030";
      }
      language() {
        return "zh";
      }
      nextChar(iter, det) {
        iter.index = iter.nextIndex;
        iter.error = false;
        let firstByte = 0;
        let secondByte = 0;
        let thirdByte = 0;
        let fourthByte = 0;
        buildChar: {
          firstByte = iter.charValue = iter.nextByte(det);
          if (firstByte < 0) {
            iter.done = true;
            break buildChar;
          }
          if (firstByte <= 128) {
            break buildChar;
          }
          secondByte = iter.nextByte(det);
          iter.charValue = iter.charValue << 8 | secondByte;
          if (firstByte >= 129 && firstByte <= 254) {
            if (secondByte >= 64 && secondByte <= 126 || secondByte >= 80 && secondByte <= 254) {
              break buildChar;
            }
            if (secondByte >= 48 && secondByte <= 57) {
              thirdByte = iter.nextByte(det);
              if (thirdByte >= 129 && thirdByte <= 254) {
                fourthByte = iter.nextByte(det);
                if (fourthByte >= 48 && fourthByte <= 57) {
                  iter.charValue = iter.charValue << 16 | thirdByte << 8 | fourthByte;
                  break buildChar;
                }
              }
            }
            iter.error = true;
            break buildChar;
          }
        }
        return iter.done == false;
      }
    };
    exports2.gb_18030 = gb_18030;
  }
});

// node_modules/chardet/lib/encoding/sbcs.js
var require_sbcs = __commonJS({
  "node_modules/chardet/lib/encoding/sbcs.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
      return mod2 && mod2.__esModule ? mod2 : { "default": mod2 };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.KOI8_R = exports2.windows_1256 = exports2.windows_1251 = exports2.ISO_8859_9 = exports2.ISO_8859_8 = exports2.ISO_8859_7 = exports2.ISO_8859_6 = exports2.ISO_8859_5 = exports2.ISO_8859_2 = exports2.ISO_8859_1 = void 0;
    var match_1 = __importDefault(require_match());
    var N_GRAM_MASK = 16777215;
    var NGramParser = class {
      static {
        __name(this, "NGramParser");
      }
      constructor(theNgramList, theByteMap) {
        this.byteIndex = 0;
        this.ngram = 0;
        this.ngramCount = 0;
        this.hitCount = 0;
        this.spaceChar = 32;
        this.ngramList = theNgramList;
        this.byteMap = theByteMap;
      }
      search(table, value) {
        let index = 0;
        if (table[index + 32] <= value)
          index += 32;
        if (table[index + 16] <= value)
          index += 16;
        if (table[index + 8] <= value)
          index += 8;
        if (table[index + 4] <= value)
          index += 4;
        if (table[index + 2] <= value)
          index += 2;
        if (table[index + 1] <= value)
          index += 1;
        if (table[index] > value)
          index -= 1;
        if (index < 0 || table[index] != value)
          return -1;
        return index;
      }
      lookup(thisNgram) {
        this.ngramCount += 1;
        if (this.search(this.ngramList, thisNgram) >= 0) {
          this.hitCount += 1;
        }
      }
      addByte(b) {
        this.ngram = (this.ngram << 8) + (b & 255) & N_GRAM_MASK;
        this.lookup(this.ngram);
      }
      nextByte(det) {
        if (this.byteIndex >= det.inputLen)
          return -1;
        return det.inputBytes[this.byteIndex++] & 255;
      }
      parse(det, spaceCh) {
        let b, ignoreSpace = false;
        this.spaceChar = spaceCh;
        while ((b = this.nextByte(det)) >= 0) {
          const mb = this.byteMap[b];
          if (mb != 0) {
            if (!(mb == this.spaceChar && ignoreSpace)) {
              this.addByte(mb);
            }
            ignoreSpace = mb == this.spaceChar;
          }
        }
        this.addByte(this.spaceChar);
        const rawPercent = this.hitCount / this.ngramCount;
        if (rawPercent > 0.33)
          return 98;
        return Math.floor(rawPercent * 300);
      }
    };
    var NGramsPlusLang = class {
      static {
        __name(this, "NGramsPlusLang");
      }
      constructor(la, ng) {
        this.fLang = la;
        this.fNGrams = ng;
      }
    };
    var isFlatNgrams = /* @__PURE__ */ __name((val) => Array.isArray(val) && isFinite(val[0]), "isFlatNgrams");
    var sbcs = class {
      static {
        __name(this, "sbcs");
      }
      constructor() {
        this.spaceChar = 32;
        this.nGramLang = void 0;
      }
      ngrams() {
        return [];
      }
      byteMap() {
        return [];
      }
      name(_input) {
        return "sbcs";
      }
      language() {
        return this.nGramLang;
      }
      match(det) {
        this.nGramLang = void 0;
        const ngrams = this.ngrams();
        if (isFlatNgrams(ngrams)) {
          const parser6 = new NGramParser(ngrams, this.byteMap());
          const confidence = parser6.parse(det, this.spaceChar);
          return confidence <= 0 ? null : (0, match_1.default)(det, this, confidence);
        }
        let bestConfidence = -1;
        for (let i = ngrams.length - 1; i >= 0; i--) {
          const ngl = ngrams[i];
          const parser6 = new NGramParser(ngl.fNGrams, this.byteMap());
          const confidence = parser6.parse(det, this.spaceChar);
          if (confidence > bestConfidence) {
            bestConfidence = confidence;
            this.nGramLang = ngl.fLang;
          }
        }
        return bestConfidence <= 0 ? null : (0, match_1.default)(det, this, bestConfidence);
      }
    };
    var ISO_8859_1 = class extends sbcs {
      static {
        __name(this, "ISO_8859_1");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          170,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          181,
          32,
          32,
          32,
          32,
          186,
          32,
          32,
          32,
          32,
          32,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          32,
          248,
          249,
          250,
          251,
          252,
          253,
          254,
          223,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          32,
          248,
          249,
          250,
          251,
          252,
          253,
          254,
          255
        ];
      }
      ngrams() {
        return [
          new NGramsPlusLang("da", [
            2122086,
            2122100,
            2122853,
            2123118,
            2123122,
            2123375,
            2123873,
            2124064,
            2125157,
            2125671,
            2126053,
            2126697,
            2126708,
            2126953,
            2127465,
            6383136,
            6385184,
            6385252,
            6386208,
            6386720,
            6579488,
            6579566,
            6579570,
            6579572,
            6627443,
            6644768,
            6644837,
            6647328,
            6647396,
            6648352,
            6648421,
            6648608,
            6648864,
            6713202,
            6776096,
            6776174,
            6776178,
            6907749,
            6908960,
            6909543,
            7038240,
            7039845,
            7103858,
            7104871,
            7105637,
            7169380,
            7234661,
            7234848,
            7235360,
            7235429,
            7300896,
            7302432,
            7303712,
            7398688,
            7479396,
            7479397,
            7479411,
            7496992,
            7566437,
            7610483,
            7628064,
            7628146,
            7629164,
            7759218
          ]),
          new NGramsPlusLang("de", [
            2122094,
            2122101,
            2122341,
            2122849,
            2122853,
            2122857,
            2123113,
            2123621,
            2123873,
            2124142,
            2125161,
            2126691,
            2126693,
            2127214,
            2127461,
            2127471,
            2127717,
            2128501,
            6448498,
            6514720,
            6514789,
            6514804,
            6578547,
            6579566,
            6579570,
            6580581,
            6627428,
            6627443,
            6646126,
            6646132,
            6647328,
            6648352,
            6648608,
            6776174,
            6841710,
            6845472,
            6906728,
            6907168,
            6909472,
            6909541,
            6911008,
            7104867,
            7105637,
            7217249,
            7217252,
            7217267,
            7234592,
            7234661,
            7234848,
            7235360,
            7235429,
            7238757,
            7479396,
            7496805,
            7497065,
            7562088,
            7566437,
            7610468,
            7628064,
            7628142,
            7628146,
            7695972,
            7695975,
            7759218
          ]),
          new NGramsPlusLang("en", [
            2122016,
            2122094,
            2122341,
            2122607,
            2123375,
            2123873,
            2123877,
            2124142,
            2125153,
            2125670,
            2125938,
            2126437,
            2126689,
            2126708,
            2126952,
            2126959,
            2127720,
            6383972,
            6384672,
            6385184,
            6385252,
            6386464,
            6386720,
            6386789,
            6386793,
            6561889,
            6561908,
            6627425,
            6627443,
            6627444,
            6644768,
            6647412,
            6648352,
            6648608,
            6713202,
            6840692,
            6841632,
            6841714,
            6906912,
            6909472,
            6909543,
            6909806,
            6910752,
            7217249,
            7217268,
            7234592,
            7235360,
            7238688,
            7300640,
            7302688,
            7303712,
            7496992,
            7500576,
            7544929,
            7544948,
            7561577,
            7566368,
            7610484,
            7628146,
            7628897,
            7628901,
            7629167,
            7630624,
            7631648
          ]),
          new NGramsPlusLang("es", [
            2122016,
            2122593,
            2122607,
            2122853,
            2123116,
            2123118,
            2123123,
            2124142,
            2124897,
            2124911,
            2125921,
            2125935,
            2125938,
            2126197,
            2126437,
            2126693,
            2127214,
            2128160,
            6365283,
            6365284,
            6365285,
            6365292,
            6365296,
            6382441,
            6382703,
            6384672,
            6386208,
            6386464,
            6515187,
            6516590,
            6579488,
            6579564,
            6582048,
            6627428,
            6627429,
            6627436,
            6646816,
            6647328,
            6647412,
            6648608,
            6648692,
            6907246,
            6943598,
            7102752,
            7106419,
            7217253,
            7238757,
            7282788,
            7282789,
            7302688,
            7303712,
            7303968,
            7364978,
            7435621,
            7495968,
            7497075,
            7544932,
            7544933,
            7544944,
            7562528,
            7628064,
            7630624,
            7693600,
            15953440
          ]),
          new NGramsPlusLang("fr", [
            2122101,
            2122607,
            2122849,
            2122853,
            2122869,
            2123118,
            2123124,
            2124897,
            2124901,
            2125921,
            2125935,
            2125938,
            2126197,
            2126693,
            2126703,
            2127214,
            2154528,
            6385268,
            6386793,
            6513952,
            6516590,
            6579488,
            6579571,
            6583584,
            6627425,
            6627427,
            6627428,
            6627429,
            6627436,
            6627440,
            6627443,
            6647328,
            6647412,
            6648352,
            6648608,
            6648864,
            6649202,
            6909806,
            6910752,
            6911008,
            7102752,
            7103776,
            7103859,
            7169390,
            7217252,
            7234848,
            7238432,
            7238688,
            7302688,
            7302772,
            7304562,
            7435621,
            7479404,
            7496992,
            7544929,
            7544932,
            7544933,
            7544940,
            7544944,
            7610468,
            7628064,
            7629167,
            7693600,
            7696928
          ]),
          new NGramsPlusLang("it", [
            2122092,
            2122600,
            2122607,
            2122853,
            2122857,
            2123040,
            2124140,
            2124142,
            2124897,
            2125925,
            2125938,
            2127214,
            6365283,
            6365284,
            6365296,
            6365299,
            6386799,
            6514789,
            6516590,
            6579564,
            6580512,
            6627425,
            6627427,
            6627428,
            6627433,
            6627436,
            6627440,
            6627443,
            6646816,
            6646892,
            6647412,
            6648352,
            6841632,
            6889569,
            6889571,
            6889572,
            6889587,
            6906144,
            6908960,
            6909472,
            6909806,
            7102752,
            7103776,
            7104800,
            7105633,
            7234848,
            7235872,
            7237408,
            7238757,
            7282785,
            7282788,
            7282793,
            7282803,
            7302688,
            7302757,
            7366002,
            7495968,
            7496992,
            7563552,
            7627040,
            7628064,
            7629088,
            7630624,
            8022383
          ]),
          new NGramsPlusLang("nl", [
            2122092,
            2122341,
            2122849,
            2122853,
            2122857,
            2123109,
            2123118,
            2123621,
            2123877,
            2124142,
            2125153,
            2125157,
            2125680,
            2126949,
            2127457,
            2127461,
            2127471,
            2127717,
            2128489,
            6381934,
            6381938,
            6385184,
            6385252,
            6386208,
            6386720,
            6514804,
            6579488,
            6579566,
            6579570,
            6627426,
            6627446,
            6645102,
            6645106,
            6647328,
            6648352,
            6648435,
            6648864,
            6776174,
            6841716,
            6907168,
            6909472,
            6909543,
            6910752,
            7217250,
            7217252,
            7217253,
            7217256,
            7217263,
            7217270,
            7234661,
            7235360,
            7302756,
            7303026,
            7303200,
            7303712,
            7562088,
            7566437,
            7610468,
            7628064,
            7628142,
            7628146,
            7758190,
            7759218,
            7761775
          ]),
          new NGramsPlusLang("no", [
            2122100,
            2122102,
            2122853,
            2123118,
            2123122,
            2123375,
            2123873,
            2124064,
            2125157,
            2125671,
            2126053,
            2126693,
            2126699,
            2126703,
            2126708,
            2126953,
            2127465,
            2155808,
            6385252,
            6386208,
            6386720,
            6579488,
            6579566,
            6579572,
            6627443,
            6644768,
            6647328,
            6647397,
            6648352,
            6648421,
            6648864,
            6648948,
            6713202,
            6776174,
            6908779,
            6908960,
            6909543,
            7038240,
            7039845,
            7103776,
            7105637,
            7169380,
            7169390,
            7217267,
            7234848,
            7235360,
            7235429,
            7237221,
            7300896,
            7302432,
            7303712,
            7398688,
            7479411,
            7496992,
            7565165,
            7566437,
            7610483,
            7628064,
            7628142,
            7628146,
            7629164,
            7631904,
            7631973,
            7759218
          ]),
          new NGramsPlusLang("pt", [
            2122016,
            2122607,
            2122849,
            2122853,
            2122863,
            2123040,
            2123123,
            2125153,
            2125423,
            2125600,
            2125921,
            2125935,
            2125938,
            2126197,
            2126437,
            2126693,
            2127213,
            6365281,
            6365283,
            6365284,
            6365296,
            6382693,
            6382703,
            6384672,
            6386208,
            6386273,
            6386464,
            6516589,
            6516590,
            6578464,
            6579488,
            6582048,
            6582131,
            6627425,
            6627428,
            6647072,
            6647412,
            6648608,
            6648692,
            6906144,
            6906721,
            7169390,
            7238757,
            7238767,
            7282785,
            7282787,
            7282788,
            7282789,
            7282800,
            7303968,
            7364978,
            7435621,
            7495968,
            7497075,
            7544929,
            7544932,
            7544933,
            7544944,
            7566433,
            7628064,
            7630624,
            7693600,
            14905120,
            15197039
          ]),
          new NGramsPlusLang("sv", [
            2122100,
            2122102,
            2122853,
            2123118,
            2123510,
            2123873,
            2124064,
            2124142,
            2124655,
            2125157,
            2125667,
            2126053,
            2126699,
            2126703,
            2126708,
            2126953,
            2127457,
            2127465,
            2155634,
            6382693,
            6385184,
            6385252,
            6386208,
            6386804,
            6514720,
            6579488,
            6579566,
            6579570,
            6579572,
            6644768,
            6647328,
            6648352,
            6648864,
            6747762,
            6776174,
            6909036,
            6909543,
            7037216,
            7105568,
            7169380,
            7217267,
            7233824,
            7234661,
            7235360,
            7235429,
            7235950,
            7299944,
            7302432,
            7302688,
            7398688,
            7479393,
            7479411,
            7495968,
            7564129,
            7565165,
            7610483,
            7627040,
            7628064,
            7628146,
            7629164,
            7631904,
            7758194,
            14971424,
            16151072
          ])
        ];
      }
      name(input) {
        return input && input.c1Bytes ? "windows-1252" : "ISO-8859-1";
      }
    };
    exports2.ISO_8859_1 = ISO_8859_1;
    var ISO_8859_2 = class extends sbcs {
      static {
        __name(this, "ISO_8859_2");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          177,
          32,
          179,
          32,
          181,
          182,
          32,
          32,
          185,
          186,
          187,
          188,
          32,
          190,
          191,
          32,
          177,
          32,
          179,
          32,
          181,
          182,
          183,
          32,
          185,
          186,
          187,
          188,
          32,
          190,
          191,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          32,
          248,
          249,
          250,
          251,
          252,
          253,
          254,
          223,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          32,
          248,
          249,
          250,
          251,
          252,
          253,
          254,
          32
        ];
      }
      ngrams() {
        return [
          new NGramsPlusLang("cs", [
            2122016,
            2122361,
            2122863,
            2124389,
            2125409,
            2125413,
            2125600,
            2125668,
            2125935,
            2125938,
            2126072,
            2126447,
            2126693,
            2126703,
            2126708,
            2126959,
            2127392,
            2127481,
            2128481,
            6365296,
            6513952,
            6514720,
            6627440,
            6627443,
            6627446,
            6647072,
            6647533,
            6844192,
            6844260,
            6910836,
            6972704,
            7042149,
            7103776,
            7104800,
            7233824,
            7268640,
            7269408,
            7269664,
            7282800,
            7300206,
            7301737,
            7304052,
            7304480,
            7304801,
            7368548,
            7368554,
            7369327,
            7403621,
            7562528,
            7565173,
            7566433,
            7566441,
            7566446,
            7628146,
            7630573,
            7630624,
            7676016,
            12477728,
            14773997,
            15296623,
            15540336,
            15540339,
            15559968,
            16278884
          ]),
          new NGramsPlusLang("hu", [
            2122016,
            2122106,
            2122341,
            2123111,
            2123116,
            2123365,
            2123873,
            2123887,
            2124147,
            2124645,
            2124649,
            2124790,
            2124901,
            2125153,
            2125157,
            2125161,
            2125413,
            2126714,
            2126949,
            2156915,
            6365281,
            6365291,
            6365293,
            6365299,
            6384416,
            6385184,
            6388256,
            6447470,
            6448494,
            6645625,
            6646560,
            6646816,
            6646885,
            6647072,
            6647328,
            6648421,
            6648864,
            6648933,
            6648948,
            6781216,
            6844263,
            6909556,
            6910752,
            7020641,
            7075450,
            7169383,
            7170414,
            7217249,
            7233899,
            7234923,
            7234925,
            7238688,
            7300985,
            7544929,
            7567973,
            7567988,
            7568097,
            7596391,
            7610465,
            7631904,
            7659891,
            8021362,
            14773792,
            15299360
          ]),
          new NGramsPlusLang("pl", [
            2122618,
            2122863,
            2124064,
            2124389,
            2124655,
            2125153,
            2125161,
            2125409,
            2125417,
            2125668,
            2125935,
            2125938,
            2126697,
            2127648,
            2127721,
            2127737,
            2128416,
            2128481,
            6365296,
            6365303,
            6385257,
            6514720,
            6519397,
            6519417,
            6582048,
            6584937,
            6627440,
            6627443,
            6627447,
            6627450,
            6645615,
            6646304,
            6647072,
            6647401,
            6778656,
            6906144,
            6907168,
            6907242,
            7037216,
            7039264,
            7039333,
            7170405,
            7233824,
            7235937,
            7235941,
            7282800,
            7305057,
            7305065,
            7368556,
            7369313,
            7369327,
            7369338,
            7502437,
            7502457,
            7563754,
            7564137,
            7566433,
            7825765,
            7955304,
            7957792,
            8021280,
            8022373,
            8026400,
            15955744
          ]),
          new NGramsPlusLang("ro", [
            2122016,
            2122083,
            2122593,
            2122597,
            2122607,
            2122613,
            2122853,
            2122857,
            2124897,
            2125153,
            2125925,
            2125938,
            2126693,
            2126819,
            2127214,
            2144873,
            2158190,
            6365283,
            6365284,
            6386277,
            6386720,
            6386789,
            6386976,
            6513010,
            6516590,
            6518048,
            6546208,
            6579488,
            6627425,
            6627427,
            6627428,
            6627440,
            6627443,
            6644e3,
            6646048,
            6646885,
            6647412,
            6648692,
            6889569,
            6889571,
            6889572,
            6889584,
            6907168,
            6908192,
            6909472,
            7102752,
            7103776,
            7106418,
            7107945,
            7234848,
            7238770,
            7303712,
            7365998,
            7496992,
            7497057,
            7501088,
            7594784,
            7628064,
            7631477,
            7660320,
            7694624,
            7695392,
            12216608,
            15625760
          ])
        ];
      }
      name(det) {
        return det && det.c1Bytes ? "windows-1250" : "ISO-8859-2";
      }
    };
    exports2.ISO_8859_2 = ISO_8859_2;
    var ISO_8859_5 = class extends sbcs {
      static {
        __name(this, "ISO_8859_5");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          241,
          242,
          243,
          244,
          245,
          246,
          247,
          248,
          249,
          250,
          251,
          252,
          32,
          254,
          255,
          208,
          209,
          210,
          211,
          212,
          213,
          214,
          215,
          216,
          217,
          218,
          219,
          220,
          221,
          222,
          223,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          208,
          209,
          210,
          211,
          212,
          213,
          214,
          215,
          216,
          217,
          218,
          219,
          220,
          221,
          222,
          223,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          32,
          241,
          242,
          243,
          244,
          245,
          246,
          247,
          248,
          249,
          250,
          251,
          252,
          32,
          254,
          255
        ];
      }
      ngrams() {
        return [
          2150944,
          2151134,
          2151646,
          2152400,
          2152480,
          2153168,
          2153182,
          2153936,
          2153941,
          2154193,
          2154462,
          2154464,
          2154704,
          2154974,
          2154978,
          2155230,
          2156514,
          2158050,
          13688280,
          13689580,
          13884960,
          14015468,
          14015960,
          14016994,
          14017056,
          14164191,
          14210336,
          14211104,
          14216992,
          14407133,
          14407712,
          14413021,
          14536736,
          14538016,
          14538965,
          14538991,
          14540320,
          14540498,
          14557394,
          14557407,
          14557409,
          14602784,
          14602960,
          14603230,
          14604576,
          14605292,
          14605344,
          14606818,
          14671579,
          14672085,
          14672088,
          14672094,
          14733522,
          14734804,
          14803664,
          14803666,
          14803672,
          14806816,
          14865883,
          14868e3,
          14868192,
          14871584,
          15196894,
          15459616
        ];
      }
      name() {
        return "ISO-8859-5";
      }
      language() {
        return "ru";
      }
    };
    exports2.ISO_8859_5 = ISO_8859_5;
    var ISO_8859_6 = class extends sbcs {
      static {
        __name(this, "ISO_8859_6");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          193,
          194,
          195,
          196,
          197,
          198,
          199,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          208,
          209,
          210,
          211,
          212,
          213,
          214,
          215,
          216,
          217,
          218,
          32,
          32,
          32,
          32,
          32,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32
        ];
      }
      ngrams() {
        return [
          2148324,
          2148326,
          2148551,
          2152932,
          2154986,
          2155748,
          2156006,
          2156743,
          13050055,
          13091104,
          13093408,
          13095200,
          13100064,
          13100227,
          13100231,
          13100232,
          13100234,
          13100236,
          13100237,
          13100239,
          13100243,
          13100249,
          13100258,
          13100261,
          13100264,
          13100266,
          13100320,
          13100576,
          13100746,
          13115591,
          13181127,
          13181153,
          13181156,
          13181157,
          13181160,
          13246663,
          13574343,
          13617440,
          13705415,
          13748512,
          13836487,
          14229703,
          14279913,
          14805536,
          14950599,
          14993696,
          15001888,
          15002144,
          15016135,
          15058720,
          15059232,
          15066656,
          15081671,
          15147207,
          15189792,
          15255524,
          15263264,
          15278279,
          15343815,
          15343845,
          15343848,
          15386912,
          15388960,
          15394336
        ];
      }
      name() {
        return "ISO-8859-6";
      }
      language() {
        return "ar";
      }
    };
    exports2.ISO_8859_6 = ISO_8859_6;
    var ISO_8859_7 = class extends sbcs {
      static {
        __name(this, "ISO_8859_7");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          161,
          162,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          220,
          32,
          221,
          222,
          223,
          32,
          252,
          32,
          253,
          254,
          192,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          32,
          243,
          244,
          245,
          246,
          247,
          248,
          249,
          250,
          251,
          220,
          221,
          222,
          223,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          247,
          248,
          249,
          250,
          251,
          252,
          253,
          254,
          32
        ];
      }
      ngrams() {
        return [
          2154989,
          2154992,
          2155497,
          2155753,
          2156016,
          2156320,
          2157281,
          2157797,
          2158049,
          2158368,
          2158817,
          2158831,
          2158833,
          2159604,
          2159605,
          2159847,
          2159855,
          14672160,
          14754017,
          14754036,
          14805280,
          14806304,
          14807292,
          14807584,
          14936545,
          15067424,
          15069728,
          15147252,
          15199520,
          15200800,
          15278324,
          15327520,
          15330014,
          15331872,
          15393257,
          15393268,
          15525152,
          15540449,
          15540453,
          15540464,
          15589664,
          15725088,
          15725856,
          15790069,
          15790575,
          15793184,
          15868129,
          15868133,
          15868138,
          15868144,
          15868148,
          15983904,
          15984416,
          15987951,
          16048416,
          16048617,
          16050157,
          16050162,
          16050666,
          16052e3,
          16052213,
          16054765,
          16379168,
          16706848
        ];
      }
      name(det) {
        return det && det.c1Bytes ? "windows-1253" : "ISO-8859-7";
      }
      language() {
        return "el";
      }
    };
    exports2.ISO_8859_7 = ISO_8859_7;
    var ISO_8859_8 = class extends sbcs {
      static {
        __name(this, "ISO_8859_8");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          181,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          247,
          248,
          249,
          250,
          32,
          32,
          32,
          32,
          32
        ];
      }
      ngrams() {
        return [
          new NGramsPlusLang("he", [
            2154725,
            2154727,
            2154729,
            2154746,
            2154985,
            2154990,
            2155744,
            2155749,
            2155753,
            2155758,
            2155762,
            2155769,
            2155770,
            2157792,
            2157796,
            2158304,
            2159340,
            2161132,
            14744096,
            14950624,
            14950625,
            14950628,
            14950636,
            14950638,
            14950649,
            15001056,
            15065120,
            15068448,
            15068960,
            15071264,
            15071776,
            15278308,
            15328288,
            15328762,
            15329773,
            15330592,
            15331104,
            15333408,
            15333920,
            15474912,
            15474916,
            15523872,
            15524896,
            15540448,
            15540449,
            15540452,
            15540460,
            15540462,
            15540473,
            15655968,
            15671524,
            15787040,
            15788320,
            15788525,
            15920160,
            16261348,
            16312813,
            16378912,
            16392416,
            16392417,
            16392420,
            16392428,
            16392430,
            16392441
          ]),
          new NGramsPlusLang("he", [
            2154725,
            2154732,
            2155753,
            2155756,
            2155758,
            2155760,
            2157040,
            2157810,
            2157817,
            2158053,
            2158057,
            2158565,
            2158569,
            2160869,
            2160873,
            2161376,
            2161381,
            2161385,
            14688484,
            14688492,
            14688493,
            14688506,
            14738464,
            14738916,
            14740512,
            14741024,
            14754020,
            14754029,
            14754042,
            14950628,
            14950633,
            14950636,
            14950637,
            14950639,
            14950648,
            14950650,
            15002656,
            15065120,
            15066144,
            15196192,
            15327264,
            15327520,
            15328288,
            15474916,
            15474925,
            15474938,
            15528480,
            15530272,
            15591913,
            15591920,
            15591928,
            15605988,
            15605997,
            15606010,
            15655200,
            15655968,
            15918112,
            16326884,
            16326893,
            16326906,
            16376864,
            16441376,
            16442400,
            16442857
          ])
        ];
      }
      name(det) {
        return det && det.c1Bytes ? "windows-1255" : "ISO-8859-8";
      }
      language() {
        return "he";
      }
    };
    exports2.ISO_8859_8 = ISO_8859_8;
    var ISO_8859_9 = class extends sbcs {
      static {
        __name(this, "ISO_8859_9");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          170,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          181,
          32,
          32,
          32,
          32,
          186,
          32,
          32,
          32,
          32,
          32,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          32,
          248,
          249,
          250,
          251,
          252,
          105,
          254,
          223,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          32,
          248,
          249,
          250,
          251,
          252,
          253,
          254,
          255
        ];
      }
      ngrams() {
        return [
          2122337,
          2122345,
          2122357,
          2122849,
          2122853,
          2123621,
          2123873,
          2124140,
          2124641,
          2124655,
          2125153,
          2125676,
          2126689,
          2126945,
          2127461,
          2128225,
          6365282,
          6384416,
          6384737,
          6384993,
          6385184,
          6385405,
          6386208,
          6386273,
          6386429,
          6386685,
          6388065,
          6449522,
          6578464,
          6579488,
          6580512,
          6627426,
          6627435,
          6644841,
          6647328,
          6648352,
          6648425,
          6648681,
          6909029,
          6909472,
          6909545,
          6910496,
          7102830,
          7102834,
          7103776,
          7103858,
          7217249,
          7217250,
          7217259,
          7234657,
          7234661,
          7234848,
          7235872,
          7235950,
          7273760,
          7498094,
          7535982,
          7759136,
          7954720,
          7958386,
          16608800,
          16608868,
          16609021,
          16642301
        ];
      }
      name(det) {
        return det && det.c1Bytes ? "windows-1254" : "ISO-8859-9";
      }
      language() {
        return "tr";
      }
    };
    exports2.ISO_8859_9 = ISO_8859_9;
    var windows_1251 = class extends sbcs {
      static {
        __name(this, "windows_1251");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          144,
          131,
          32,
          131,
          32,
          32,
          32,
          32,
          32,
          32,
          154,
          32,
          156,
          157,
          158,
          159,
          144,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          154,
          32,
          156,
          157,
          158,
          159,
          32,
          162,
          162,
          188,
          32,
          180,
          32,
          32,
          184,
          32,
          186,
          32,
          32,
          32,
          32,
          191,
          32,
          32,
          179,
          179,
          180,
          181,
          32,
          32,
          184,
          32,
          186,
          32,
          188,
          190,
          190,
          191,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          247,
          248,
          249,
          250,
          251,
          252,
          253,
          254,
          255,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          247,
          248,
          249,
          250,
          251,
          252,
          253,
          254,
          255
        ];
      }
      ngrams() {
        return [
          2155040,
          2155246,
          2155758,
          2156512,
          2156576,
          2157280,
          2157294,
          2158048,
          2158053,
          2158305,
          2158574,
          2158576,
          2158816,
          2159086,
          2159090,
          2159342,
          2160626,
          2162162,
          14740968,
          14742268,
          14937632,
          15068156,
          15068648,
          15069682,
          15069728,
          15212783,
          15263008,
          15263776,
          15269664,
          15459821,
          15460384,
          15465709,
          15589408,
          15590688,
          15591653,
          15591679,
          15592992,
          15593186,
          15605986,
          15605999,
          15606001,
          15655456,
          15655648,
          15655918,
          15657248,
          15657980,
          15658016,
          15659506,
          15724267,
          15724773,
          15724776,
          15724782,
          15786210,
          15787492,
          15856352,
          15856354,
          15856360,
          15859488,
          15918571,
          15920672,
          15920880,
          15924256,
          16249582,
          16512288
        ];
      }
      name() {
        return "windows-1251";
      }
      language() {
        return "ru";
      }
    };
    exports2.windows_1251 = windows_1251;
    var windows_1256 = class extends sbcs {
      static {
        __name(this, "windows_1256");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          129,
          32,
          131,
          32,
          32,
          32,
          32,
          136,
          32,
          138,
          32,
          156,
          141,
          142,
          143,
          144,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          152,
          32,
          154,
          32,
          156,
          32,
          32,
          159,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          170,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          181,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          192,
          193,
          194,
          195,
          196,
          197,
          198,
          199,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          208,
          209,
          210,
          211,
          212,
          213,
          214,
          32,
          216,
          217,
          218,
          219,
          220,
          221,
          222,
          223,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          32,
          32,
          32,
          32,
          244,
          32,
          32,
          32,
          32,
          249,
          32,
          251,
          252,
          32,
          32,
          255
        ];
      }
      ngrams() {
        return [
          2148321,
          2148324,
          2148551,
          2153185,
          2153965,
          2154977,
          2155492,
          2156231,
          13050055,
          13091104,
          13093408,
          13095200,
          13099296,
          13099459,
          13099463,
          13099464,
          13099466,
          13099468,
          13099469,
          13099471,
          13099475,
          13099482,
          13099486,
          13099491,
          13099494,
          13099501,
          13099808,
          13100064,
          13100234,
          13115591,
          13181127,
          13181149,
          13181153,
          13181155,
          13181158,
          13246663,
          13574343,
          13617440,
          13705415,
          13748512,
          13836487,
          14295239,
          14344684,
          14544160,
          14753991,
          14797088,
          14806048,
          14806304,
          14885063,
          14927648,
          14928160,
          14935072,
          14950599,
          15016135,
          15058720,
          15124449,
          15131680,
          15474887,
          15540423,
          15540451,
          15540454,
          15583520,
          15585568,
          15590432
        ];
      }
      name() {
        return "windows-1256";
      }
      language() {
        return "ar";
      }
    };
    exports2.windows_1256 = windows_1256;
    var KOI8_R = class extends sbcs {
      static {
        __name(this, "KOI8_R");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          163,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          163,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          192,
          193,
          194,
          195,
          196,
          197,
          198,
          199,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          208,
          209,
          210,
          211,
          212,
          213,
          214,
          215,
          216,
          217,
          218,
          219,
          220,
          221,
          222,
          223,
          192,
          193,
          194,
          195,
          196,
          197,
          198,
          199,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          208,
          209,
          210,
          211,
          212,
          213,
          214,
          215,
          216,
          217,
          218,
          219,
          220,
          221,
          222,
          223
        ];
      }
      ngrams() {
        return [
          2147535,
          2148640,
          2149313,
          2149327,
          2150081,
          2150085,
          2150338,
          2150607,
          2150610,
          2151105,
          2151375,
          2151380,
          2151631,
          2152224,
          2152399,
          2153153,
          2153684,
          2154196,
          12701385,
          12702936,
          12963032,
          12963529,
          12964820,
          12964896,
          13094688,
          13181136,
          13223200,
          13224224,
          13226272,
          13419982,
          13420832,
          13424846,
          13549856,
          13550880,
          13552069,
          13552081,
          13553440,
          13553623,
          13574352,
          13574355,
          13574359,
          13617103,
          13617696,
          13618392,
          13618464,
          13620180,
          13621024,
          13621185,
          13684684,
          13685445,
          13685449,
          13685455,
          13812183,
          13813188,
          13881632,
          13882561,
          13882569,
          13882583,
          13944268,
          13946656,
          13946834,
          13948960,
          14272544,
          14603471
        ];
      }
      name() {
        return "KOI8-R";
      }
      language() {
        return "ru";
      }
    };
    exports2.KOI8_R = KOI8_R;
  }
});

// node_modules/chardet/lib/encoding/iso2022.js
var require_iso2022 = __commonJS({
  "node_modules/chardet/lib/encoding/iso2022.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
      return mod2 && mod2.__esModule ? mod2 : { "default": mod2 };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ISO_2022_CN = exports2.ISO_2022_KR = exports2.ISO_2022_JP = void 0;
    var match_1 = __importDefault(require_match());
    var ISO_2022 = class {
      static {
        __name(this, "ISO_2022");
      }
      constructor() {
        this.escapeSequences = [];
      }
      name() {
        return "ISO_2022";
      }
      match(det) {
        let i, j;
        let escN;
        let hits = 0;
        let misses = 0;
        let shifts = 0;
        let confidence;
        const text = det.inputBytes;
        const textLen = det.inputLen;
        scanInput: for (i = 0; i < textLen; i++) {
          if (text[i] == 27) {
            checkEscapes: for (escN = 0; escN < this.escapeSequences.length; escN++) {
              const seq = this.escapeSequences[escN];
              if (textLen - i < seq.length)
                continue checkEscapes;
              for (j = 1; j < seq.length; j++)
                if (seq[j] != text[i + j])
                  continue checkEscapes;
              hits++;
              i += seq.length - 1;
              continue scanInput;
            }
            misses++;
          }
          if (text[i] == 14 || text[i] == 15)
            shifts++;
        }
        if (hits == 0)
          return null;
        confidence = (100 * hits - 100 * misses) / (hits + misses);
        if (hits + shifts < 5)
          confidence -= (5 - (hits + shifts)) * 10;
        return confidence <= 0 ? null : (0, match_1.default)(det, this, confidence);
      }
    };
    var ISO_2022_JP = class extends ISO_2022 {
      static {
        __name(this, "ISO_2022_JP");
      }
      constructor() {
        super(...arguments);
        this.escapeSequences = [
          [27, 36, 40, 67],
          [27, 36, 40, 68],
          [27, 36, 64],
          [27, 36, 65],
          [27, 36, 66],
          [27, 38, 64],
          [27, 40, 66],
          [27, 40, 72],
          [27, 40, 73],
          [27, 40, 74],
          [27, 46, 65],
          [27, 46, 70]
        ];
      }
      name() {
        return "ISO-2022-JP";
      }
      language() {
        return "ja";
      }
    };
    exports2.ISO_2022_JP = ISO_2022_JP;
    var ISO_2022_KR = class extends ISO_2022 {
      static {
        __name(this, "ISO_2022_KR");
      }
      constructor() {
        super(...arguments);
        this.escapeSequences = [[27, 36, 41, 67]];
      }
      name() {
        return "ISO-2022-KR";
      }
      language() {
        return "kr";
      }
    };
    exports2.ISO_2022_KR = ISO_2022_KR;
    var ISO_2022_CN = class extends ISO_2022 {
      static {
        __name(this, "ISO_2022_CN");
      }
      constructor() {
        super(...arguments);
        this.escapeSequences = [
          [27, 36, 41, 65],
          [27, 36, 41, 71],
          [27, 36, 42, 72],
          [27, 36, 41, 69],
          [27, 36, 43, 73],
          [27, 36, 43, 74],
          [27, 36, 43, 75],
          [27, 36, 43, 76],
          [27, 36, 43, 77],
          [27, 78],
          [27, 79]
        ];
      }
      name() {
        return "ISO-2022-CN";
      }
      language() {
        return "zh";
      }
    };
    exports2.ISO_2022_CN = ISO_2022_CN;
  }
});

// node_modules/chardet/lib/utils.js
var require_utils13 = __commonJS({
  "node_modules/chardet/lib/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isByteArray = void 0;
    var isByteArray = /* @__PURE__ */ __name((input) => {
      if (input == null || typeof input != "object")
        return false;
      return isFinite(input.length) && input.length >= 0;
    }, "isByteArray");
    exports2.isByteArray = isByteArray;
  }
});

// node_modules/chardet/lib/index.js
var require_lib3 = __commonJS({
  "node_modules/chardet/lib/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc2 = Object.getOwnPropertyDescriptor(m, k);
      if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m[k];
        }, "get") };
      }
      Object.defineProperty(o2, k2, desc2);
    } : function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o2[k2] = m[k];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v) {
      Object.defineProperty(o2, "default", { enumerable: true, value: v });
    } : function(o2, v) {
      o2["default"] = v;
    });
    var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ function() {
      var ownKeys2 = /* @__PURE__ */ __name(function(o2) {
        ownKeys2 = Object.getOwnPropertyNames || function(o3) {
          var ar = [];
          for (var k in o3) if (Object.prototype.hasOwnProperty.call(o3, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys2(o2);
      }, "ownKeys");
      return function(mod2) {
        if (mod2 && mod2.__esModule) return mod2;
        var result = {};
        if (mod2 != null) {
          for (var k = ownKeys2(mod2), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod2, k[i]);
        }
        __setModuleDefault(result, mod2);
        return result;
      };
    }();
    var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
      return mod2 && mod2.__esModule ? mod2 : { "default": mod2 };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.detectFileSync = exports2.detectFile = exports2.analyse = exports2.detect = void 0;
    var node_1 = __importDefault(require_node16());
    var ascii_1 = __importDefault(require_ascii2());
    var utf8_1 = __importDefault(require_utf82());
    var unicode2 = __importStar(require_unicode());
    var mbcs = __importStar(require_mbcs());
    var sbcs = __importStar(require_sbcs());
    var iso2022 = __importStar(require_iso2022());
    var utils_1 = require_utils13();
    var recognisers = [
      new utf8_1.default(),
      new unicode2.UTF_16BE(),
      new unicode2.UTF_16LE(),
      new unicode2.UTF_32BE(),
      new unicode2.UTF_32LE(),
      new mbcs.sjis(),
      new mbcs.big5(),
      new mbcs.euc_jp(),
      new mbcs.euc_kr(),
      new mbcs.gb_18030(),
      new iso2022.ISO_2022_JP(),
      new iso2022.ISO_2022_KR(),
      new iso2022.ISO_2022_CN(),
      new sbcs.ISO_8859_1(),
      new sbcs.ISO_8859_2(),
      new sbcs.ISO_8859_5(),
      new sbcs.ISO_8859_6(),
      new sbcs.ISO_8859_7(),
      new sbcs.ISO_8859_8(),
      new sbcs.ISO_8859_9(),
      new sbcs.windows_1251(),
      new sbcs.windows_1256(),
      new sbcs.KOI8_R(),
      new ascii_1.default()
    ];
    var detect = /* @__PURE__ */ __name((buffer) => {
      const matches = (0, exports2.analyse)(buffer);
      return matches.length > 0 ? matches[0].name : null;
    }, "detect");
    exports2.detect = detect;
    var analyse = /* @__PURE__ */ __name((buffer) => {
      if (!(0, utils_1.isByteArray)(buffer)) {
        throw new Error("Input must be a byte array, e.g. Buffer or Uint8Array");
      }
      const byteStats = [];
      for (let i = 0; i < 256; i++)
        byteStats[i] = 0;
      for (let i = buffer.length - 1; i >= 0; i--)
        byteStats[buffer[i] & 255]++;
      let c1Bytes = false;
      for (let i = 128; i <= 159; i += 1) {
        if (byteStats[i] !== 0) {
          c1Bytes = true;
          break;
        }
      }
      const context2 = {
        byteStats,
        c1Bytes,
        rawInput: buffer,
        rawLen: buffer.length,
        inputBytes: buffer,
        inputLen: buffer.length
      };
      const matches = recognisers.map((rec) => {
        return rec.match(context2);
      }).filter((match2) => {
        return !!match2;
      }).sort((a, b) => {
        return b.confidence - a.confidence;
      });
      return matches;
    }, "analyse");
    exports2.analyse = analyse;
    var detectFile = /* @__PURE__ */ __name((filepath, opts = {}) => new Promise((resolve24, reject) => {
      let fd;
      const fs95 = (0, node_1.default)();
      const handler = /* @__PURE__ */ __name((err, buffer) => {
        if (fd) {
          fs95.closeSync(fd);
        }
        if (err) {
          reject(err);
        } else {
          resolve24((0, exports2.detect)(buffer));
        }
      }, "handler");
      if (opts && opts.sampleSize) {
        fd = fs95.openSync(filepath, "r");
        const sample = Buffer.allocUnsafe(opts.sampleSize);
        fs95.read(fd, sample, 0, opts.sampleSize, opts.offset, (err) => {
          handler(err, sample);
        });
        return;
      }
      fs95.readFile(filepath, handler);
    }), "detectFile");
    exports2.detectFile = detectFile;
    var detectFileSync = /* @__PURE__ */ __name((filepath, opts = {}) => {
      const fs95 = (0, node_1.default)();
      if (opts && opts.sampleSize) {
        const fd = fs95.openSync(filepath, "r");
        const sample = Buffer.allocUnsafe(opts.sampleSize);
        fs95.readSync(fd, sample, 0, opts.sampleSize, opts.offset);
        fs95.closeSync(fd);
        return (0, exports2.detect)(sample);
      }
      return (0, exports2.detect)(fs95.readFileSync(filepath));
    }, "detectFileSync");
    exports2.detectFileSync = detectFileSync;
    exports2.default = {
      analyse: exports2.analyse,
      detect: exports2.detect,
      detectFileSync: exports2.detectFileSync,
      detectFile: exports2.detectFile
    };
  }
});

// packages/core/dist/src/utils/systemEncoding.js
import { execSync as execSync2 } from "node:child_process";
import os14 from "node:os";
function getCachedEncodingForBuffer(buffer) {
  if (cachedSystemEncoding === void 0) {
    cachedSystemEncoding = getSystemEncoding();
  }
  if (cachedSystemEncoding) {
    return cachedSystemEncoding;
  }
  return detectEncodingFromBuffer(buffer) || "utf-8";
}
function getSystemEncoding() {
  if (os14.platform() === "win32") {
    try {
      const output = execSync2("chcp", { encoding: "utf8" });
      const match3 = output.match(/:\s*(\d+)/);
      if (match3) {
        const codePage = parseInt(match3[1], 10);
        if (!isNaN(codePage)) {
          return windowsCodePageToEncoding(codePage);
        }
      }
      throw new Error(`Unable to parse Windows code page from 'chcp' output "${output.trim()}". `);
    } catch (error) {
      console.warn(`Failed to get Windows code page using 'chcp' command: ${error instanceof Error ? error.message : String(error)}. Will attempt to detect encoding from command output instead.`);
    }
    return null;
  }
  const env7 = process.env;
  let locale = env7["LC_ALL"] || env7["LC_CTYPE"] || env7["LANG"] || "";
  if (!locale) {
    try {
      locale = execSync2("locale charmap", { encoding: "utf8" }).toString().trim();
    } catch (_e) {
      console.warn("Failed to get locale charmap.");
      return null;
    }
  }
  const match2 = locale.match(/\.(.+)/);
  if (match2 && match2[1]) {
    return match2[1].toLowerCase();
  }
  if (locale && !locale.includes(".")) {
    return locale.toLowerCase();
  }
  return null;
}
function windowsCodePageToEncoding(cp2) {
  const map2 = {
    437: "cp437",
    850: "cp850",
    852: "cp852",
    866: "cp866",
    874: "windows-874",
    932: "shift_jis",
    936: "gb2312",
    949: "euc-kr",
    950: "big5",
    1200: "utf-16le",
    1201: "utf-16be",
    1250: "windows-1250",
    1251: "windows-1251",
    1252: "windows-1252",
    1253: "windows-1253",
    1254: "windows-1254",
    1255: "windows-1255",
    1256: "windows-1256",
    1257: "windows-1257",
    1258: "windows-1258",
    65001: "utf-8"
  };
  if (map2[cp2]) {
    return map2[cp2];
  }
  console.warn(`Unable to determine encoding for windows code page ${cp2}.`);
  return null;
}
function detectEncodingFromBuffer(buffer) {
  try {
    const detected = (0, import_chardet.detect)(buffer);
    if (detected && typeof detected === "string") {
      return detected.toLowerCase();
    }
  } catch (error) {
    console.warn("Failed to detect encoding with chardet:", error);
  }
  return null;
}
var import_chardet, cachedSystemEncoding;
var init_systemEncoding = __esm({
  "packages/core/dist/src/utils/systemEncoding.js"() {
    "use strict";
    init_esbuild_shims();
    import_chardet = __toESM(require_lib3(), 1);
    cachedSystemEncoding = void 0;
    __name(getCachedEncodingForBuffer, "getCachedEncodingForBuffer");
    __name(getSystemEncoding, "getSystemEncoding");
    __name(windowsCodePageToEncoding, "windowsCodePageToEncoding");
    __name(detectEncodingFromBuffer, "detectEncodingFromBuffer");
  }
});

// packages/core/dist/src/utils/textUtils.js
function safeLiteralReplace(str2, oldString, newString) {
  if (oldString === "" || !str2.includes(oldString)) {
    return str2;
  }
  if (!newString.includes("$")) {
    return str2.replaceAll(oldString, newString);
  }
  const escapedNewString = newString.replaceAll("$", "$$$$");
  return str2.replaceAll(oldString, escapedNewString);
}
function isBinary(data, sampleSize = 512) {
  if (!data) {
    return false;
  }
  const sample = data.length > sampleSize ? data.subarray(0, sampleSize) : data;
  for (const byte of sample) {
    if (byte === 0) {
      return true;
    }
  }
  return false;
}
var init_textUtils = __esm({
  "packages/core/dist/src/utils/textUtils.js"() {
    "use strict";
    init_esbuild_shims();
    __name(safeLiteralReplace, "safeLiteralReplace");
    __name(isBinary, "isBinary");
  }
});

// node_modules/@xterm/headless/lib-headless/xterm-headless.js
var require_xterm_headless = __commonJS({
  "node_modules/@xterm/headless/lib-headless/xterm-headless.js"(exports2) {
    init_esbuild_shims();
    (() => {
      "use strict";
      var e2 = { 349: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.CircularList = void 0;
        const s3 = i2(460), r4 = i2(844);
        class n3 extends r4.Disposable {
          static {
            __name(this, "n");
          }
          constructor(e4) {
            super(), this._maxLength = e4, this.onDeleteEmitter = this.register(new s3.EventEmitter()), this.onDelete = this.onDeleteEmitter.event, this.onInsertEmitter = this.register(new s3.EventEmitter()), this.onInsert = this.onInsertEmitter.event, this.onTrimEmitter = this.register(new s3.EventEmitter()), this.onTrim = this.onTrimEmitter.event, this._array = new Array(this._maxLength), this._startIndex = 0, this._length = 0;
          }
          get maxLength() {
            return this._maxLength;
          }
          set maxLength(e4) {
            if (this._maxLength === e4) return;
            const t4 = new Array(e4);
            for (let i3 = 0; i3 < Math.min(e4, this.length); i3++) t4[i3] = this._array[this._getCyclicIndex(i3)];
            this._array = t4, this._maxLength = e4, this._startIndex = 0;
          }
          get length() {
            return this._length;
          }
          set length(e4) {
            if (e4 > this._length) for (let t4 = this._length; t4 < e4; t4++) this._array[t4] = void 0;
            this._length = e4;
          }
          get(e4) {
            return this._array[this._getCyclicIndex(e4)];
          }
          set(e4, t4) {
            this._array[this._getCyclicIndex(e4)] = t4;
          }
          push(e4) {
            this._array[this._getCyclicIndex(this._length)] = e4, this._length === this._maxLength ? (this._startIndex = ++this._startIndex % this._maxLength, this.onTrimEmitter.fire(1)) : this._length++;
          }
          recycle() {
            if (this._length !== this._maxLength) throw new Error("Can only recycle when the buffer is full");
            return this._startIndex = ++this._startIndex % this._maxLength, this.onTrimEmitter.fire(1), this._array[this._getCyclicIndex(this._length - 1)];
          }
          get isFull() {
            return this._length === this._maxLength;
          }
          pop() {
            return this._array[this._getCyclicIndex(this._length-- - 1)];
          }
          splice(e4, t4, ...i3) {
            if (t4) {
              for (let i4 = e4; i4 < this._length - t4; i4++) this._array[this._getCyclicIndex(i4)] = this._array[this._getCyclicIndex(i4 + t4)];
              this._length -= t4, this.onDeleteEmitter.fire({ index: e4, amount: t4 });
            }
            for (let t5 = this._length - 1; t5 >= e4; t5--) this._array[this._getCyclicIndex(t5 + i3.length)] = this._array[this._getCyclicIndex(t5)];
            for (let t5 = 0; t5 < i3.length; t5++) this._array[this._getCyclicIndex(e4 + t5)] = i3[t5];
            if (i3.length && this.onInsertEmitter.fire({ index: e4, amount: i3.length }), this._length + i3.length > this._maxLength) {
              const e5 = this._length + i3.length - this._maxLength;
              this._startIndex += e5, this._length = this._maxLength, this.onTrimEmitter.fire(e5);
            } else this._length += i3.length;
          }
          trimStart(e4) {
            e4 > this._length && (e4 = this._length), this._startIndex += e4, this._length -= e4, this.onTrimEmitter.fire(e4);
          }
          shiftElements(e4, t4, i3) {
            if (!(t4 <= 0)) {
              if (e4 < 0 || e4 >= this._length) throw new Error("start argument out of range");
              if (e4 + i3 < 0) throw new Error("Cannot shift elements in list beyond index 0");
              if (i3 > 0) {
                for (let s5 = t4 - 1; s5 >= 0; s5--) this.set(e4 + s5 + i3, this.get(e4 + s5));
                const s4 = e4 + t4 + i3 - this._length;
                if (s4 > 0) for (this._length += s4; this._length > this._maxLength; ) this._length--, this._startIndex++, this.onTrimEmitter.fire(1);
              } else for (let s4 = 0; s4 < t4; s4++) this.set(e4 + s4 + i3, this.get(e4 + s4));
            }
          }
          _getCyclicIndex(e4) {
            return (this._startIndex + e4) % this._maxLength;
          }
        }
        t3.CircularList = n3;
      }, 439: (e3, t3) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.clone = void 0, t3.clone = /* @__PURE__ */ __name(function e4(t4, i2 = 5) {
          if ("object" != typeof t4) return t4;
          const s3 = Array.isArray(t4) ? [] : {};
          for (const r4 in t4) s3[r4] = i2 <= 1 ? t4[r4] : t4[r4] && e4(t4[r4], i2 - 1);
          return s3;
        }, "e");
      }, 969: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.CoreTerminal = void 0;
        const s3 = i2(844), r4 = i2(585), n3 = i2(348), a = i2(866), o2 = i2(744), h = i2(302), c3 = i2(83), l2 = i2(460), _ = i2(753), d = i2(480), f = i2(994), u = i2(282), p = i2(435), g = i2(981), v = i2(660);
        let b = false;
        class S extends s3.Disposable {
          static {
            __name(this, "S");
          }
          get onScroll() {
            return this._onScrollApi || (this._onScrollApi = this.register(new l2.EventEmitter()), this._onScroll.event((e4) => {
              this._onScrollApi?.fire(e4.position);
            })), this._onScrollApi.event;
          }
          get cols() {
            return this._bufferService.cols;
          }
          get rows() {
            return this._bufferService.rows;
          }
          get buffers() {
            return this._bufferService.buffers;
          }
          get options() {
            return this.optionsService.options;
          }
          set options(e4) {
            for (const t4 in e4) this.optionsService.options[t4] = e4[t4];
          }
          constructor(e4) {
            super(), this._windowsWrappingHeuristics = this.register(new s3.MutableDisposable()), this._onBinary = this.register(new l2.EventEmitter()), this.onBinary = this._onBinary.event, this._onData = this.register(new l2.EventEmitter()), this.onData = this._onData.event, this._onLineFeed = this.register(new l2.EventEmitter()), this.onLineFeed = this._onLineFeed.event, this._onResize = this.register(new l2.EventEmitter()), this.onResize = this._onResize.event, this._onWriteParsed = this.register(new l2.EventEmitter()), this.onWriteParsed = this._onWriteParsed.event, this._onScroll = this.register(new l2.EventEmitter()), this._instantiationService = new n3.InstantiationService(), this.optionsService = this.register(new h.OptionsService(e4)), this._instantiationService.setService(r4.IOptionsService, this.optionsService), this._bufferService = this.register(this._instantiationService.createInstance(o2.BufferService)), this._instantiationService.setService(r4.IBufferService, this._bufferService), this._logService = this.register(this._instantiationService.createInstance(a.LogService)), this._instantiationService.setService(r4.ILogService, this._logService), this.coreService = this.register(this._instantiationService.createInstance(c3.CoreService)), this._instantiationService.setService(r4.ICoreService, this.coreService), this.coreMouseService = this.register(this._instantiationService.createInstance(_.CoreMouseService)), this._instantiationService.setService(r4.ICoreMouseService, this.coreMouseService), this.unicodeService = this.register(this._instantiationService.createInstance(d.UnicodeService)), this._instantiationService.setService(r4.IUnicodeService, this.unicodeService), this._charsetService = this._instantiationService.createInstance(f.CharsetService), this._instantiationService.setService(r4.ICharsetService, this._charsetService), this._oscLinkService = this._instantiationService.createInstance(v.OscLinkService), this._instantiationService.setService(r4.IOscLinkService, this._oscLinkService), this._inputHandler = this.register(new p.InputHandler(this._bufferService, this._charsetService, this.coreService, this._logService, this.optionsService, this._oscLinkService, this.coreMouseService, this.unicodeService)), this.register((0, l2.forwardEvent)(this._inputHandler.onLineFeed, this._onLineFeed)), this.register(this._inputHandler), this.register((0, l2.forwardEvent)(this._bufferService.onResize, this._onResize)), this.register((0, l2.forwardEvent)(this.coreService.onData, this._onData)), this.register((0, l2.forwardEvent)(this.coreService.onBinary, this._onBinary)), this.register(this.coreService.onRequestScrollToBottom(() => this.scrollToBottom())), this.register(this.coreService.onUserInput(() => this._writeBuffer.handleUserInput())), this.register(this.optionsService.onMultipleOptionChange(["windowsMode", "windowsPty"], () => this._handleWindowsPtyOptionChange())), this.register(this._bufferService.onScroll((e5) => {
              this._onScroll.fire({ position: this._bufferService.buffer.ydisp, source: 0 }), this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop, this._bufferService.buffer.scrollBottom);
            })), this.register(this._inputHandler.onScroll((e5) => {
              this._onScroll.fire({ position: this._bufferService.buffer.ydisp, source: 0 }), this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop, this._bufferService.buffer.scrollBottom);
            })), this._writeBuffer = this.register(new g.WriteBuffer((e5, t4) => this._inputHandler.parse(e5, t4))), this.register((0, l2.forwardEvent)(this._writeBuffer.onWriteParsed, this._onWriteParsed));
          }
          write(e4, t4) {
            this._writeBuffer.write(e4, t4);
          }
          writeSync(e4, t4) {
            this._logService.logLevel <= r4.LogLevelEnum.WARN && !b && (this._logService.warn("writeSync is unreliable and will be removed soon."), b = true), this._writeBuffer.writeSync(e4, t4);
          }
          input(e4, t4 = true) {
            this.coreService.triggerDataEvent(e4, t4);
          }
          resize(e4, t4) {
            isNaN(e4) || isNaN(t4) || (e4 = Math.max(e4, o2.MINIMUM_COLS), t4 = Math.max(t4, o2.MINIMUM_ROWS), this._bufferService.resize(e4, t4));
          }
          scroll(e4, t4 = false) {
            this._bufferService.scroll(e4, t4);
          }
          scrollLines(e4, t4, i3) {
            this._bufferService.scrollLines(e4, t4, i3);
          }
          scrollPages(e4) {
            this.scrollLines(e4 * (this.rows - 1));
          }
          scrollToTop() {
            this.scrollLines(-this._bufferService.buffer.ydisp);
          }
          scrollToBottom() {
            this.scrollLines(this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp);
          }
          scrollToLine(e4) {
            const t4 = e4 - this._bufferService.buffer.ydisp;
            0 !== t4 && this.scrollLines(t4);
          }
          registerEscHandler(e4, t4) {
            return this._inputHandler.registerEscHandler(e4, t4);
          }
          registerDcsHandler(e4, t4) {
            return this._inputHandler.registerDcsHandler(e4, t4);
          }
          registerCsiHandler(e4, t4) {
            return this._inputHandler.registerCsiHandler(e4, t4);
          }
          registerOscHandler(e4, t4) {
            return this._inputHandler.registerOscHandler(e4, t4);
          }
          _setup() {
            this._handleWindowsPtyOptionChange();
          }
          reset() {
            this._inputHandler.reset(), this._bufferService.reset(), this._charsetService.reset(), this.coreService.reset(), this.coreMouseService.reset();
          }
          _handleWindowsPtyOptionChange() {
            let e4 = false;
            const t4 = this.optionsService.rawOptions.windowsPty;
            t4 && void 0 !== t4.buildNumber && void 0 !== t4.buildNumber ? e4 = !!("conpty" === t4.backend && t4.buildNumber < 21376) : this.optionsService.rawOptions.windowsMode && (e4 = true), e4 ? this._enableWindowsWrappingHeuristics() : this._windowsWrappingHeuristics.clear();
          }
          _enableWindowsWrappingHeuristics() {
            if (!this._windowsWrappingHeuristics.value) {
              const e4 = [];
              e4.push(this.onLineFeed(u.updateWindowsModeWrappedState.bind(null, this._bufferService))), e4.push(this.registerCsiHandler({ final: "H" }, () => ((0, u.updateWindowsModeWrappedState)(this._bufferService), false))), this._windowsWrappingHeuristics.value = (0, s3.toDisposable)(() => {
                for (const t4 of e4) t4.dispose();
              });
            }
          }
        }
        t3.CoreTerminal = S;
      }, 460: (e3, t3) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.runAndSubscribe = t3.forwardEvent = t3.EventEmitter = void 0, t3.EventEmitter = class {
          constructor() {
            this._listeners = [], this._disposed = false;
          }
          get event() {
            return this._event || (this._event = (e4) => {
              this._listeners.push(e4);
              const t4 = { dispose: /* @__PURE__ */ __name(() => {
                if (!this._disposed) {
                  for (let t5 = 0; t5 < this._listeners.length; t5++) if (this._listeners[t5] === e4) return void this._listeners.splice(t5, 1);
                }
              }, "dispose") };
              return t4;
            }), this._event;
          }
          fire(e4, t4) {
            const i2 = [];
            for (let e5 = 0; e5 < this._listeners.length; e5++) i2.push(this._listeners[e5]);
            for (let s3 = 0; s3 < i2.length; s3++) i2[s3].call(void 0, e4, t4);
          }
          dispose() {
            this.clearListeners(), this._disposed = true;
          }
          clearListeners() {
            this._listeners && (this._listeners.length = 0);
          }
        }, t3.forwardEvent = function(e4, t4) {
          return e4((e5) => t4.fire(e5));
        }, t3.runAndSubscribe = function(e4, t4) {
          return t4(void 0), e4((e5) => t4(e5));
        };
      }, 435: function(e3, t3, i2) {
        var s3 = this && this.__decorate || function(e4, t4, i3, s4) {
          var r5, n4 = arguments.length, a2 = n4 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i3) : s4;
          if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a2 = Reflect.decorate(e4, t4, i3, s4);
          else for (var o3 = e4.length - 1; o3 >= 0; o3--) (r5 = e4[o3]) && (a2 = (n4 < 3 ? r5(a2) : n4 > 3 ? r5(t4, i3, a2) : r5(t4, i3)) || a2);
          return n4 > 3 && a2 && Object.defineProperty(t4, i3, a2), a2;
        }, r4 = this && this.__param || function(e4, t4) {
          return function(i3, s4) {
            t4(i3, s4, e4);
          };
        };
        Object.defineProperty(t3, "__esModule", { value: true }), t3.InputHandler = t3.WindowsOptionsReportType = void 0;
        const n3 = i2(584), a = i2(116), o2 = i2(15), h = i2(844), c3 = i2(482), l2 = i2(437), _ = i2(460), d = i2(643), f = i2(511), u = i2(734), p = i2(585), g = i2(480), v = i2(242), b = i2(351), S = i2(941), m = { "(": 0, ")": 1, "*": 2, "+": 3, "-": 1, ".": 2 }, C = 131072;
        function y(e4, t4) {
          if (e4 > 24) return t4.setWinLines || false;
          switch (e4) {
            case 1:
              return !!t4.restoreWin;
            case 2:
              return !!t4.minimizeWin;
            case 3:
              return !!t4.setWinPosition;
            case 4:
              return !!t4.setWinSizePixels;
            case 5:
              return !!t4.raiseWin;
            case 6:
              return !!t4.lowerWin;
            case 7:
              return !!t4.refreshWin;
            case 8:
              return !!t4.setWinSizeChars;
            case 9:
              return !!t4.maximizeWin;
            case 10:
              return !!t4.fullscreenWin;
            case 11:
              return !!t4.getWinState;
            case 13:
              return !!t4.getWinPosition;
            case 14:
              return !!t4.getWinSizePixels;
            case 15:
              return !!t4.getScreenSizePixels;
            case 16:
              return !!t4.getCellSizePixels;
            case 18:
              return !!t4.getWinSizeChars;
            case 19:
              return !!t4.getScreenSizeChars;
            case 20:
              return !!t4.getIconTitle;
            case 21:
              return !!t4.getWinTitle;
            case 22:
              return !!t4.pushTitle;
            case 23:
              return !!t4.popTitle;
            case 24:
              return !!t4.setWinLines;
          }
          return false;
        }
        __name(y, "y");
        var w;
        !function(e4) {
          e4[e4.GET_WIN_SIZE_PIXELS = 0] = "GET_WIN_SIZE_PIXELS", e4[e4.GET_CELL_SIZE_PIXELS = 1] = "GET_CELL_SIZE_PIXELS";
        }(w || (t3.WindowsOptionsReportType = w = {}));
        let B = 0;
        class E extends h.Disposable {
          static {
            __name(this, "E");
          }
          getAttrData() {
            return this._curAttrData;
          }
          constructor(e4, t4, i3, s4, r5, h2, d2, u2, p2 = new o2.EscapeSequenceParser()) {
            super(), this._bufferService = e4, this._charsetService = t4, this._coreService = i3, this._logService = s4, this._optionsService = r5, this._oscLinkService = h2, this._coreMouseService = d2, this._unicodeService = u2, this._parser = p2, this._parseBuffer = new Uint32Array(4096), this._stringDecoder = new c3.StringToUtf32(), this._utf8Decoder = new c3.Utf8ToUtf32(), this._workCell = new f.CellData(), this._windowTitle = "", this._iconName = "", this._windowTitleStack = [], this._iconNameStack = [], this._curAttrData = l2.DEFAULT_ATTR_DATA.clone(), this._eraseAttrDataInternal = l2.DEFAULT_ATTR_DATA.clone(), this._onRequestBell = this.register(new _.EventEmitter()), this.onRequestBell = this._onRequestBell.event, this._onRequestRefreshRows = this.register(new _.EventEmitter()), this.onRequestRefreshRows = this._onRequestRefreshRows.event, this._onRequestReset = this.register(new _.EventEmitter()), this.onRequestReset = this._onRequestReset.event, this._onRequestSendFocus = this.register(new _.EventEmitter()), this.onRequestSendFocus = this._onRequestSendFocus.event, this._onRequestSyncScrollBar = this.register(new _.EventEmitter()), this.onRequestSyncScrollBar = this._onRequestSyncScrollBar.event, this._onRequestWindowsOptionsReport = this.register(new _.EventEmitter()), this.onRequestWindowsOptionsReport = this._onRequestWindowsOptionsReport.event, this._onA11yChar = this.register(new _.EventEmitter()), this.onA11yChar = this._onA11yChar.event, this._onA11yTab = this.register(new _.EventEmitter()), this.onA11yTab = this._onA11yTab.event, this._onCursorMove = this.register(new _.EventEmitter()), this.onCursorMove = this._onCursorMove.event, this._onLineFeed = this.register(new _.EventEmitter()), this.onLineFeed = this._onLineFeed.event, this._onScroll = this.register(new _.EventEmitter()), this.onScroll = this._onScroll.event, this._onTitleChange = this.register(new _.EventEmitter()), this.onTitleChange = this._onTitleChange.event, this._onColor = this.register(new _.EventEmitter()), this.onColor = this._onColor.event, this._parseStack = { paused: false, cursorStartX: 0, cursorStartY: 0, decodedLength: 0, position: 0 }, this._specialColors = [256, 257, 258], this.register(this._parser), this._dirtyRowTracker = new A(this._bufferService), this._activeBuffer = this._bufferService.buffer, this.register(this._bufferService.buffers.onBufferActivate((e5) => this._activeBuffer = e5.activeBuffer)), this._parser.setCsiHandlerFallback((e5, t5) => {
              this._logService.debug("Unknown CSI code: ", { identifier: this._parser.identToString(e5), params: t5.toArray() });
            }), this._parser.setEscHandlerFallback((e5) => {
              this._logService.debug("Unknown ESC code: ", { identifier: this._parser.identToString(e5) });
            }), this._parser.setExecuteHandlerFallback((e5) => {
              this._logService.debug("Unknown EXECUTE code: ", { code: e5 });
            }), this._parser.setOscHandlerFallback((e5, t5, i4) => {
              this._logService.debug("Unknown OSC code: ", { identifier: e5, action: t5, data: i4 });
            }), this._parser.setDcsHandlerFallback((e5, t5, i4) => {
              "HOOK" === t5 && (i4 = i4.toArray()), this._logService.debug("Unknown DCS code: ", { identifier: this._parser.identToString(e5), action: t5, payload: i4 });
            }), this._parser.setPrintHandler((e5, t5, i4) => this.print(e5, t5, i4)), this._parser.registerCsiHandler({ final: "@" }, (e5) => this.insertChars(e5)), this._parser.registerCsiHandler({ intermediates: " ", final: "@" }, (e5) => this.scrollLeft(e5)), this._parser.registerCsiHandler({ final: "A" }, (e5) => this.cursorUp(e5)), this._parser.registerCsiHandler({ intermediates: " ", final: "A" }, (e5) => this.scrollRight(e5)), this._parser.registerCsiHandler({ final: "B" }, (e5) => this.cursorDown(e5)), this._parser.registerCsiHandler({ final: "C" }, (e5) => this.cursorForward(e5)), this._parser.registerCsiHandler({ final: "D" }, (e5) => this.cursorBackward(e5)), this._parser.registerCsiHandler({ final: "E" }, (e5) => this.cursorNextLine(e5)), this._parser.registerCsiHandler({ final: "F" }, (e5) => this.cursorPrecedingLine(e5)), this._parser.registerCsiHandler({ final: "G" }, (e5) => this.cursorCharAbsolute(e5)), this._parser.registerCsiHandler({ final: "H" }, (e5) => this.cursorPosition(e5)), this._parser.registerCsiHandler({ final: "I" }, (e5) => this.cursorForwardTab(e5)), this._parser.registerCsiHandler({ final: "J" }, (e5) => this.eraseInDisplay(e5, false)), this._parser.registerCsiHandler({ prefix: "?", final: "J" }, (e5) => this.eraseInDisplay(e5, true)), this._parser.registerCsiHandler({ final: "K" }, (e5) => this.eraseInLine(e5, false)), this._parser.registerCsiHandler({ prefix: "?", final: "K" }, (e5) => this.eraseInLine(e5, true)), this._parser.registerCsiHandler({ final: "L" }, (e5) => this.insertLines(e5)), this._parser.registerCsiHandler({ final: "M" }, (e5) => this.deleteLines(e5)), this._parser.registerCsiHandler({ final: "P" }, (e5) => this.deleteChars(e5)), this._parser.registerCsiHandler({ final: "S" }, (e5) => this.scrollUp(e5)), this._parser.registerCsiHandler({ final: "T" }, (e5) => this.scrollDown(e5)), this._parser.registerCsiHandler({ final: "X" }, (e5) => this.eraseChars(e5)), this._parser.registerCsiHandler({ final: "Z" }, (e5) => this.cursorBackwardTab(e5)), this._parser.registerCsiHandler({ final: "`" }, (e5) => this.charPosAbsolute(e5)), this._parser.registerCsiHandler({ final: "a" }, (e5) => this.hPositionRelative(e5)), this._parser.registerCsiHandler({ final: "b" }, (e5) => this.repeatPrecedingCharacter(e5)), this._parser.registerCsiHandler({ final: "c" }, (e5) => this.sendDeviceAttributesPrimary(e5)), this._parser.registerCsiHandler({ prefix: ">", final: "c" }, (e5) => this.sendDeviceAttributesSecondary(e5)), this._parser.registerCsiHandler({ final: "d" }, (e5) => this.linePosAbsolute(e5)), this._parser.registerCsiHandler({ final: "e" }, (e5) => this.vPositionRelative(e5)), this._parser.registerCsiHandler({ final: "f" }, (e5) => this.hVPosition(e5)), this._parser.registerCsiHandler({ final: "g" }, (e5) => this.tabClear(e5)), this._parser.registerCsiHandler({ final: "h" }, (e5) => this.setMode(e5)), this._parser.registerCsiHandler({ prefix: "?", final: "h" }, (e5) => this.setModePrivate(e5)), this._parser.registerCsiHandler({ final: "l" }, (e5) => this.resetMode(e5)), this._parser.registerCsiHandler({ prefix: "?", final: "l" }, (e5) => this.resetModePrivate(e5)), this._parser.registerCsiHandler({ final: "m" }, (e5) => this.charAttributes(e5)), this._parser.registerCsiHandler({ final: "n" }, (e5) => this.deviceStatus(e5)), this._parser.registerCsiHandler({ prefix: "?", final: "n" }, (e5) => this.deviceStatusPrivate(e5)), this._parser.registerCsiHandler({ intermediates: "!", final: "p" }, (e5) => this.softReset(e5)), this._parser.registerCsiHandler({ intermediates: " ", final: "q" }, (e5) => this.setCursorStyle(e5)), this._parser.registerCsiHandler({ final: "r" }, (e5) => this.setScrollRegion(e5)), this._parser.registerCsiHandler({ final: "s" }, (e5) => this.saveCursor(e5)), this._parser.registerCsiHandler({ final: "t" }, (e5) => this.windowOptions(e5)), this._parser.registerCsiHandler({ final: "u" }, (e5) => this.restoreCursor(e5)), this._parser.registerCsiHandler({ intermediates: "'", final: "}" }, (e5) => this.insertColumns(e5)), this._parser.registerCsiHandler({ intermediates: "'", final: "~" }, (e5) => this.deleteColumns(e5)), this._parser.registerCsiHandler({ intermediates: '"', final: "q" }, (e5) => this.selectProtected(e5)), this._parser.registerCsiHandler({ intermediates: "$", final: "p" }, (e5) => this.requestMode(e5, true)), this._parser.registerCsiHandler({ prefix: "?", intermediates: "$", final: "p" }, (e5) => this.requestMode(e5, false)), this._parser.setExecuteHandler(n3.C0.BEL, () => this.bell()), this._parser.setExecuteHandler(n3.C0.LF, () => this.lineFeed()), this._parser.setExecuteHandler(n3.C0.VT, () => this.lineFeed()), this._parser.setExecuteHandler(n3.C0.FF, () => this.lineFeed()), this._parser.setExecuteHandler(n3.C0.CR, () => this.carriageReturn()), this._parser.setExecuteHandler(n3.C0.BS, () => this.backspace()), this._parser.setExecuteHandler(n3.C0.HT, () => this.tab()), this._parser.setExecuteHandler(n3.C0.SO, () => this.shiftOut()), this._parser.setExecuteHandler(n3.C0.SI, () => this.shiftIn()), this._parser.setExecuteHandler(n3.C1.IND, () => this.index()), this._parser.setExecuteHandler(n3.C1.NEL, () => this.nextLine()), this._parser.setExecuteHandler(n3.C1.HTS, () => this.tabSet()), this._parser.registerOscHandler(0, new v.OscHandler((e5) => (this.setTitle(e5), this.setIconName(e5), true))), this._parser.registerOscHandler(1, new v.OscHandler((e5) => this.setIconName(e5))), this._parser.registerOscHandler(2, new v.OscHandler((e5) => this.setTitle(e5))), this._parser.registerOscHandler(4, new v.OscHandler((e5) => this.setOrReportIndexedColor(e5))), this._parser.registerOscHandler(8, new v.OscHandler((e5) => this.setHyperlink(e5))), this._parser.registerOscHandler(10, new v.OscHandler((e5) => this.setOrReportFgColor(e5))), this._parser.registerOscHandler(11, new v.OscHandler((e5) => this.setOrReportBgColor(e5))), this._parser.registerOscHandler(12, new v.OscHandler((e5) => this.setOrReportCursorColor(e5))), this._parser.registerOscHandler(104, new v.OscHandler((e5) => this.restoreIndexedColor(e5))), this._parser.registerOscHandler(110, new v.OscHandler((e5) => this.restoreFgColor(e5))), this._parser.registerOscHandler(111, new v.OscHandler((e5) => this.restoreBgColor(e5))), this._parser.registerOscHandler(112, new v.OscHandler((e5) => this.restoreCursorColor(e5))), this._parser.registerEscHandler({ final: "7" }, () => this.saveCursor()), this._parser.registerEscHandler({ final: "8" }, () => this.restoreCursor()), this._parser.registerEscHandler({ final: "D" }, () => this.index()), this._parser.registerEscHandler({ final: "E" }, () => this.nextLine()), this._parser.registerEscHandler({ final: "H" }, () => this.tabSet()), this._parser.registerEscHandler({ final: "M" }, () => this.reverseIndex()), this._parser.registerEscHandler({ final: "=" }, () => this.keypadApplicationMode()), this._parser.registerEscHandler({ final: ">" }, () => this.keypadNumericMode()), this._parser.registerEscHandler({ final: "c" }, () => this.fullReset()), this._parser.registerEscHandler({ final: "n" }, () => this.setgLevel(2)), this._parser.registerEscHandler({ final: "o" }, () => this.setgLevel(3)), this._parser.registerEscHandler({ final: "|" }, () => this.setgLevel(3)), this._parser.registerEscHandler({ final: "}" }, () => this.setgLevel(2)), this._parser.registerEscHandler({ final: "~" }, () => this.setgLevel(1)), this._parser.registerEscHandler({ intermediates: "%", final: "@" }, () => this.selectDefaultCharset()), this._parser.registerEscHandler({ intermediates: "%", final: "G" }, () => this.selectDefaultCharset());
            for (const e5 in a.CHARSETS) this._parser.registerEscHandler({ intermediates: "(", final: e5 }, () => this.selectCharset("(" + e5)), this._parser.registerEscHandler({ intermediates: ")", final: e5 }, () => this.selectCharset(")" + e5)), this._parser.registerEscHandler({ intermediates: "*", final: e5 }, () => this.selectCharset("*" + e5)), this._parser.registerEscHandler({ intermediates: "+", final: e5 }, () => this.selectCharset("+" + e5)), this._parser.registerEscHandler({ intermediates: "-", final: e5 }, () => this.selectCharset("-" + e5)), this._parser.registerEscHandler({ intermediates: ".", final: e5 }, () => this.selectCharset("." + e5)), this._parser.registerEscHandler({ intermediates: "/", final: e5 }, () => this.selectCharset("/" + e5));
            this._parser.registerEscHandler({ intermediates: "#", final: "8" }, () => this.screenAlignmentPattern()), this._parser.setErrorHandler((e5) => (this._logService.error("Parsing error: ", e5), e5)), this._parser.registerDcsHandler({ intermediates: "$", final: "q" }, new b.DcsHandler((e5, t5) => this.requestStatusString(e5, t5)));
          }
          _preserveStack(e4, t4, i3, s4) {
            this._parseStack.paused = true, this._parseStack.cursorStartX = e4, this._parseStack.cursorStartY = t4, this._parseStack.decodedLength = i3, this._parseStack.position = s4;
          }
          _logSlowResolvingAsync(e4) {
            this._logService.logLevel <= p.LogLevelEnum.WARN && Promise.race([e4, new Promise((e5, t4) => setTimeout(() => t4("#SLOW_TIMEOUT"), 5e3))]).catch((e5) => {
              if ("#SLOW_TIMEOUT" !== e5) throw e5;
              console.warn("async parser handler taking longer than 5000 ms");
            });
          }
          _getCurrentLinkId() {
            return this._curAttrData.extended.urlId;
          }
          parse(e4, t4) {
            let i3, s4 = this._activeBuffer.x, r5 = this._activeBuffer.y, n4 = 0;
            const a2 = this._parseStack.paused;
            if (a2) {
              if (i3 = this._parser.parse(this._parseBuffer, this._parseStack.decodedLength, t4)) return this._logSlowResolvingAsync(i3), i3;
              s4 = this._parseStack.cursorStartX, r5 = this._parseStack.cursorStartY, this._parseStack.paused = false, e4.length > C && (n4 = this._parseStack.position + C);
            }
            if (this._logService.logLevel <= p.LogLevelEnum.DEBUG && this._logService.debug("parsing data" + ("string" == typeof e4 ? ` "${e4}"` : ` "${Array.prototype.map.call(e4, (e5) => String.fromCharCode(e5)).join("")}"`), "string" == typeof e4 ? e4.split("").map((e5) => e5.charCodeAt(0)) : e4), this._parseBuffer.length < e4.length && this._parseBuffer.length < C && (this._parseBuffer = new Uint32Array(Math.min(e4.length, C))), a2 || this._dirtyRowTracker.clearRange(), e4.length > C) for (let t5 = n4; t5 < e4.length; t5 += C) {
              const n5 = t5 + C < e4.length ? t5 + C : e4.length, a3 = "string" == typeof e4 ? this._stringDecoder.decode(e4.substring(t5, n5), this._parseBuffer) : this._utf8Decoder.decode(e4.subarray(t5, n5), this._parseBuffer);
              if (i3 = this._parser.parse(this._parseBuffer, a3)) return this._preserveStack(s4, r5, a3, t5), this._logSlowResolvingAsync(i3), i3;
            }
            else if (!a2) {
              const t5 = "string" == typeof e4 ? this._stringDecoder.decode(e4, this._parseBuffer) : this._utf8Decoder.decode(e4, this._parseBuffer);
              if (i3 = this._parser.parse(this._parseBuffer, t5)) return this._preserveStack(s4, r5, t5, 0), this._logSlowResolvingAsync(i3), i3;
            }
            this._activeBuffer.x === s4 && this._activeBuffer.y === r5 || this._onCursorMove.fire();
            const o3 = this._dirtyRowTracker.end + (this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp), h2 = this._dirtyRowTracker.start + (this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp);
            h2 < this._bufferService.rows && this._onRequestRefreshRows.fire(Math.min(h2, this._bufferService.rows - 1), Math.min(o3, this._bufferService.rows - 1));
          }
          print(e4, t4, i3) {
            let s4, r5;
            const n4 = this._charsetService.charset, a2 = this._optionsService.rawOptions.screenReaderMode, o3 = this._bufferService.cols, h2 = this._coreService.decPrivateModes.wraparound, _2 = this._coreService.modes.insertMode, f2 = this._curAttrData;
            let u2 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);
            this._dirtyRowTracker.markDirty(this._activeBuffer.y), this._activeBuffer.x && i3 - t4 > 0 && 2 === u2.getWidth(this._activeBuffer.x - 1) && u2.setCellFromCodepoint(this._activeBuffer.x - 1, 0, 1, f2);
            let p2 = this._parser.precedingJoinState;
            for (let v2 = t4; v2 < i3; ++v2) {
              if (s4 = e4[v2], s4 < 127 && n4) {
                const e5 = n4[String.fromCharCode(s4)];
                e5 && (s4 = e5.charCodeAt(0));
              }
              const t5 = this._unicodeService.charProperties(s4, p2);
              r5 = g.UnicodeService.extractWidth(t5);
              const i4 = g.UnicodeService.extractShouldJoin(t5), b2 = i4 ? g.UnicodeService.extractWidth(p2) : 0;
              if (p2 = t5, a2 && this._onA11yChar.fire((0, c3.stringFromCodePoint)(s4)), this._getCurrentLinkId() && this._oscLinkService.addLineToLink(this._getCurrentLinkId(), this._activeBuffer.ybase + this._activeBuffer.y), this._activeBuffer.x + r5 - b2 > o3) {
                if (h2) {
                  const e5 = u2;
                  let t6 = this._activeBuffer.x - b2;
                  for (this._activeBuffer.x = b2, this._activeBuffer.y++, this._activeBuffer.y === this._activeBuffer.scrollBottom + 1 ? (this._activeBuffer.y--, this._bufferService.scroll(this._eraseAttrData(), true)) : (this._activeBuffer.y >= this._bufferService.rows && (this._activeBuffer.y = this._bufferService.rows - 1), this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y).isWrapped = true), u2 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y), b2 > 0 && u2 instanceof l2.BufferLine && u2.copyCellsFrom(e5, t6, 0, b2, false); t6 < o3; ) e5.setCellFromCodepoint(t6++, 0, 1, f2);
                } else if (this._activeBuffer.x = o3 - 1, 2 === r5) continue;
              }
              if (i4 && this._activeBuffer.x) {
                const e5 = u2.getWidth(this._activeBuffer.x - 1) ? 1 : 2;
                u2.addCodepointToCell(this._activeBuffer.x - e5, s4, r5);
                for (let e6 = r5 - b2; --e6 >= 0; ) u2.setCellFromCodepoint(this._activeBuffer.x++, 0, 0, f2);
              } else if (_2 && (u2.insertCells(this._activeBuffer.x, r5 - b2, this._activeBuffer.getNullCell(f2)), 2 === u2.getWidth(o3 - 1) && u2.setCellFromCodepoint(o3 - 1, d.NULL_CELL_CODE, d.NULL_CELL_WIDTH, f2)), u2.setCellFromCodepoint(this._activeBuffer.x++, s4, r5, f2), r5 > 0) for (; --r5; ) u2.setCellFromCodepoint(this._activeBuffer.x++, 0, 0, f2);
            }
            this._parser.precedingJoinState = p2, this._activeBuffer.x < o3 && i3 - t4 > 0 && 0 === u2.getWidth(this._activeBuffer.x) && !u2.hasContent(this._activeBuffer.x) && u2.setCellFromCodepoint(this._activeBuffer.x, 0, 1, f2), this._dirtyRowTracker.markDirty(this._activeBuffer.y);
          }
          registerCsiHandler(e4, t4) {
            return "t" !== e4.final || e4.prefix || e4.intermediates ? this._parser.registerCsiHandler(e4, t4) : this._parser.registerCsiHandler(e4, (e5) => !y(e5.params[0], this._optionsService.rawOptions.windowOptions) || t4(e5));
          }
          registerDcsHandler(e4, t4) {
            return this._parser.registerDcsHandler(e4, new b.DcsHandler(t4));
          }
          registerEscHandler(e4, t4) {
            return this._parser.registerEscHandler(e4, t4);
          }
          registerOscHandler(e4, t4) {
            return this._parser.registerOscHandler(e4, new v.OscHandler(t4));
          }
          bell() {
            return this._onRequestBell.fire(), true;
          }
          lineFeed() {
            return this._dirtyRowTracker.markDirty(this._activeBuffer.y), this._optionsService.rawOptions.convertEol && (this._activeBuffer.x = 0), this._activeBuffer.y++, this._activeBuffer.y === this._activeBuffer.scrollBottom + 1 ? (this._activeBuffer.y--, this._bufferService.scroll(this._eraseAttrData())) : this._activeBuffer.y >= this._bufferService.rows ? this._activeBuffer.y = this._bufferService.rows - 1 : this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y).isWrapped = false, this._activeBuffer.x >= this._bufferService.cols && this._activeBuffer.x--, this._dirtyRowTracker.markDirty(this._activeBuffer.y), this._onLineFeed.fire(), true;
          }
          carriageReturn() {
            return this._activeBuffer.x = 0, true;
          }
          backspace() {
            if (!this._coreService.decPrivateModes.reverseWraparound) return this._restrictCursor(), this._activeBuffer.x > 0 && this._activeBuffer.x--, true;
            if (this._restrictCursor(this._bufferService.cols), this._activeBuffer.x > 0) this._activeBuffer.x--;
            else if (0 === this._activeBuffer.x && this._activeBuffer.y > this._activeBuffer.scrollTop && this._activeBuffer.y <= this._activeBuffer.scrollBottom && this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)?.isWrapped) {
              this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y).isWrapped = false, this._activeBuffer.y--, this._activeBuffer.x = this._bufferService.cols - 1;
              const e4 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);
              e4.hasWidth(this._activeBuffer.x) && !e4.hasContent(this._activeBuffer.x) && this._activeBuffer.x--;
            }
            return this._restrictCursor(), true;
          }
          tab() {
            if (this._activeBuffer.x >= this._bufferService.cols) return true;
            const e4 = this._activeBuffer.x;
            return this._activeBuffer.x = this._activeBuffer.nextStop(), this._optionsService.rawOptions.screenReaderMode && this._onA11yTab.fire(this._activeBuffer.x - e4), true;
          }
          shiftOut() {
            return this._charsetService.setgLevel(1), true;
          }
          shiftIn() {
            return this._charsetService.setgLevel(0), true;
          }
          _restrictCursor(e4 = this._bufferService.cols - 1) {
            this._activeBuffer.x = Math.min(e4, Math.max(0, this._activeBuffer.x)), this._activeBuffer.y = this._coreService.decPrivateModes.origin ? Math.min(this._activeBuffer.scrollBottom, Math.max(this._activeBuffer.scrollTop, this._activeBuffer.y)) : Math.min(this._bufferService.rows - 1, Math.max(0, this._activeBuffer.y)), this._dirtyRowTracker.markDirty(this._activeBuffer.y);
          }
          _setCursor(e4, t4) {
            this._dirtyRowTracker.markDirty(this._activeBuffer.y), this._coreService.decPrivateModes.origin ? (this._activeBuffer.x = e4, this._activeBuffer.y = this._activeBuffer.scrollTop + t4) : (this._activeBuffer.x = e4, this._activeBuffer.y = t4), this._restrictCursor(), this._dirtyRowTracker.markDirty(this._activeBuffer.y);
          }
          _moveCursor(e4, t4) {
            this._restrictCursor(), this._setCursor(this._activeBuffer.x + e4, this._activeBuffer.y + t4);
          }
          cursorUp(e4) {
            const t4 = this._activeBuffer.y - this._activeBuffer.scrollTop;
            return t4 >= 0 ? this._moveCursor(0, -Math.min(t4, e4.params[0] || 1)) : this._moveCursor(0, -(e4.params[0] || 1)), true;
          }
          cursorDown(e4) {
            const t4 = this._activeBuffer.scrollBottom - this._activeBuffer.y;
            return t4 >= 0 ? this._moveCursor(0, Math.min(t4, e4.params[0] || 1)) : this._moveCursor(0, e4.params[0] || 1), true;
          }
          cursorForward(e4) {
            return this._moveCursor(e4.params[0] || 1, 0), true;
          }
          cursorBackward(e4) {
            return this._moveCursor(-(e4.params[0] || 1), 0), true;
          }
          cursorNextLine(e4) {
            return this.cursorDown(e4), this._activeBuffer.x = 0, true;
          }
          cursorPrecedingLine(e4) {
            return this.cursorUp(e4), this._activeBuffer.x = 0, true;
          }
          cursorCharAbsolute(e4) {
            return this._setCursor((e4.params[0] || 1) - 1, this._activeBuffer.y), true;
          }
          cursorPosition(e4) {
            return this._setCursor(e4.length >= 2 ? (e4.params[1] || 1) - 1 : 0, (e4.params[0] || 1) - 1), true;
          }
          charPosAbsolute(e4) {
            return this._setCursor((e4.params[0] || 1) - 1, this._activeBuffer.y), true;
          }
          hPositionRelative(e4) {
            return this._moveCursor(e4.params[0] || 1, 0), true;
          }
          linePosAbsolute(e4) {
            return this._setCursor(this._activeBuffer.x, (e4.params[0] || 1) - 1), true;
          }
          vPositionRelative(e4) {
            return this._moveCursor(0, e4.params[0] || 1), true;
          }
          hVPosition(e4) {
            return this.cursorPosition(e4), true;
          }
          tabClear(e4) {
            const t4 = e4.params[0];
            return 0 === t4 ? delete this._activeBuffer.tabs[this._activeBuffer.x] : 3 === t4 && (this._activeBuffer.tabs = {}), true;
          }
          cursorForwardTab(e4) {
            if (this._activeBuffer.x >= this._bufferService.cols) return true;
            let t4 = e4.params[0] || 1;
            for (; t4--; ) this._activeBuffer.x = this._activeBuffer.nextStop();
            return true;
          }
          cursorBackwardTab(e4) {
            if (this._activeBuffer.x >= this._bufferService.cols) return true;
            let t4 = e4.params[0] || 1;
            for (; t4--; ) this._activeBuffer.x = this._activeBuffer.prevStop();
            return true;
          }
          selectProtected(e4) {
            const t4 = e4.params[0];
            return 1 === t4 && (this._curAttrData.bg |= 536870912), 2 !== t4 && 0 !== t4 || (this._curAttrData.bg &= -536870913), true;
          }
          _eraseInBufferLine(e4, t4, i3, s4 = false, r5 = false) {
            const n4 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e4);
            n4.replaceCells(t4, i3, this._activeBuffer.getNullCell(this._eraseAttrData()), r5), s4 && (n4.isWrapped = false);
          }
          _resetBufferLine(e4, t4 = false) {
            const i3 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e4);
            i3 && (i3.fill(this._activeBuffer.getNullCell(this._eraseAttrData()), t4), this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase + e4), i3.isWrapped = false);
          }
          eraseInDisplay(e4, t4 = false) {
            let i3;
            switch (this._restrictCursor(this._bufferService.cols), e4.params[0]) {
              case 0:
                for (i3 = this._activeBuffer.y, this._dirtyRowTracker.markDirty(i3), this._eraseInBufferLine(i3++, this._activeBuffer.x, this._bufferService.cols, 0 === this._activeBuffer.x, t4); i3 < this._bufferService.rows; i3++) this._resetBufferLine(i3, t4);
                this._dirtyRowTracker.markDirty(i3);
                break;
              case 1:
                for (i3 = this._activeBuffer.y, this._dirtyRowTracker.markDirty(i3), this._eraseInBufferLine(i3, 0, this._activeBuffer.x + 1, true, t4), this._activeBuffer.x + 1 >= this._bufferService.cols && (this._activeBuffer.lines.get(i3 + 1).isWrapped = false); i3--; ) this._resetBufferLine(i3, t4);
                this._dirtyRowTracker.markDirty(0);
                break;
              case 2:
                for (i3 = this._bufferService.rows, this._dirtyRowTracker.markDirty(i3 - 1); i3--; ) this._resetBufferLine(i3, t4);
                this._dirtyRowTracker.markDirty(0);
                break;
              case 3:
                const e5 = this._activeBuffer.lines.length - this._bufferService.rows;
                e5 > 0 && (this._activeBuffer.lines.trimStart(e5), this._activeBuffer.ybase = Math.max(this._activeBuffer.ybase - e5, 0), this._activeBuffer.ydisp = Math.max(this._activeBuffer.ydisp - e5, 0), this._onScroll.fire(0));
            }
            return true;
          }
          eraseInLine(e4, t4 = false) {
            switch (this._restrictCursor(this._bufferService.cols), e4.params[0]) {
              case 0:
                this._eraseInBufferLine(this._activeBuffer.y, this._activeBuffer.x, this._bufferService.cols, 0 === this._activeBuffer.x, t4);
                break;
              case 1:
                this._eraseInBufferLine(this._activeBuffer.y, 0, this._activeBuffer.x + 1, false, t4);
                break;
              case 2:
                this._eraseInBufferLine(this._activeBuffer.y, 0, this._bufferService.cols, true, t4);
            }
            return this._dirtyRowTracker.markDirty(this._activeBuffer.y), true;
          }
          insertLines(e4) {
            this._restrictCursor();
            let t4 = e4.params[0] || 1;
            if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true;
            const i3 = this._activeBuffer.ybase + this._activeBuffer.y, s4 = this._bufferService.rows - 1 - this._activeBuffer.scrollBottom, r5 = this._bufferService.rows - 1 + this._activeBuffer.ybase - s4 + 1;
            for (; t4--; ) this._activeBuffer.lines.splice(r5 - 1, 1), this._activeBuffer.lines.splice(i3, 0, this._activeBuffer.getBlankLine(this._eraseAttrData()));
            return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y, this._activeBuffer.scrollBottom), this._activeBuffer.x = 0, true;
          }
          deleteLines(e4) {
            this._restrictCursor();
            let t4 = e4.params[0] || 1;
            if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true;
            const i3 = this._activeBuffer.ybase + this._activeBuffer.y;
            let s4;
            for (s4 = this._bufferService.rows - 1 - this._activeBuffer.scrollBottom, s4 = this._bufferService.rows - 1 + this._activeBuffer.ybase - s4; t4--; ) this._activeBuffer.lines.splice(i3, 1), this._activeBuffer.lines.splice(s4, 0, this._activeBuffer.getBlankLine(this._eraseAttrData()));
            return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y, this._activeBuffer.scrollBottom), this._activeBuffer.x = 0, true;
          }
          insertChars(e4) {
            this._restrictCursor();
            const t4 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);
            return t4 && (t4.insertCells(this._activeBuffer.x, e4.params[0] || 1, this._activeBuffer.getNullCell(this._eraseAttrData())), this._dirtyRowTracker.markDirty(this._activeBuffer.y)), true;
          }
          deleteChars(e4) {
            this._restrictCursor();
            const t4 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);
            return t4 && (t4.deleteCells(this._activeBuffer.x, e4.params[0] || 1, this._activeBuffer.getNullCell(this._eraseAttrData())), this._dirtyRowTracker.markDirty(this._activeBuffer.y)), true;
          }
          scrollUp(e4) {
            let t4 = e4.params[0] || 1;
            for (; t4--; ) this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollTop, 1), this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollBottom, 0, this._activeBuffer.getBlankLine(this._eraseAttrData()));
            return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true;
          }
          scrollDown(e4) {
            let t4 = e4.params[0] || 1;
            for (; t4--; ) this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollBottom, 1), this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollTop, 0, this._activeBuffer.getBlankLine(l2.DEFAULT_ATTR_DATA));
            return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true;
          }
          scrollLeft(e4) {
            if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true;
            const t4 = e4.params[0] || 1;
            for (let e5 = this._activeBuffer.scrollTop; e5 <= this._activeBuffer.scrollBottom; ++e5) {
              const i3 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e5);
              i3.deleteCells(0, t4, this._activeBuffer.getNullCell(this._eraseAttrData())), i3.isWrapped = false;
            }
            return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true;
          }
          scrollRight(e4) {
            if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true;
            const t4 = e4.params[0] || 1;
            for (let e5 = this._activeBuffer.scrollTop; e5 <= this._activeBuffer.scrollBottom; ++e5) {
              const i3 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e5);
              i3.insertCells(0, t4, this._activeBuffer.getNullCell(this._eraseAttrData())), i3.isWrapped = false;
            }
            return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true;
          }
          insertColumns(e4) {
            if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true;
            const t4 = e4.params[0] || 1;
            for (let e5 = this._activeBuffer.scrollTop; e5 <= this._activeBuffer.scrollBottom; ++e5) {
              const i3 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e5);
              i3.insertCells(this._activeBuffer.x, t4, this._activeBuffer.getNullCell(this._eraseAttrData())), i3.isWrapped = false;
            }
            return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true;
          }
          deleteColumns(e4) {
            if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true;
            const t4 = e4.params[0] || 1;
            for (let e5 = this._activeBuffer.scrollTop; e5 <= this._activeBuffer.scrollBottom; ++e5) {
              const i3 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e5);
              i3.deleteCells(this._activeBuffer.x, t4, this._activeBuffer.getNullCell(this._eraseAttrData())), i3.isWrapped = false;
            }
            return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true;
          }
          eraseChars(e4) {
            this._restrictCursor();
            const t4 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);
            return t4 && (t4.replaceCells(this._activeBuffer.x, this._activeBuffer.x + (e4.params[0] || 1), this._activeBuffer.getNullCell(this._eraseAttrData())), this._dirtyRowTracker.markDirty(this._activeBuffer.y)), true;
          }
          repeatPrecedingCharacter(e4) {
            const t4 = this._parser.precedingJoinState;
            if (!t4) return true;
            const i3 = e4.params[0] || 1, s4 = g.UnicodeService.extractWidth(t4), r5 = this._activeBuffer.x - s4, n4 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y).getString(r5), a2 = new Uint32Array(n4.length * i3);
            let o3 = 0;
            for (let e5 = 0; e5 < n4.length; ) {
              const t5 = n4.codePointAt(e5) || 0;
              a2[o3++] = t5, e5 += t5 > 65535 ? 2 : 1;
            }
            let h2 = o3;
            for (let e5 = 1; e5 < i3; ++e5) a2.copyWithin(h2, 0, o3), h2 += o3;
            return this.print(a2, 0, h2), true;
          }
          sendDeviceAttributesPrimary(e4) {
            return e4.params[0] > 0 || (this._is("xterm") || this._is("rxvt-unicode") || this._is("screen") ? this._coreService.triggerDataEvent(n3.C0.ESC + "[?1;2c") : this._is("linux") && this._coreService.triggerDataEvent(n3.C0.ESC + "[?6c")), true;
          }
          sendDeviceAttributesSecondary(e4) {
            return e4.params[0] > 0 || (this._is("xterm") ? this._coreService.triggerDataEvent(n3.C0.ESC + "[>0;276;0c") : this._is("rxvt-unicode") ? this._coreService.triggerDataEvent(n3.C0.ESC + "[>85;95;0c") : this._is("linux") ? this._coreService.triggerDataEvent(e4.params[0] + "c") : this._is("screen") && this._coreService.triggerDataEvent(n3.C0.ESC + "[>83;40003;0c")), true;
          }
          _is(e4) {
            return 0 === (this._optionsService.rawOptions.termName + "").indexOf(e4);
          }
          setMode(e4) {
            for (let t4 = 0; t4 < e4.length; t4++) switch (e4.params[t4]) {
              case 4:
                this._coreService.modes.insertMode = true;
                break;
              case 20:
                this._optionsService.options.convertEol = true;
            }
            return true;
          }
          setModePrivate(e4) {
            for (let t4 = 0; t4 < e4.length; t4++) switch (e4.params[t4]) {
              case 1:
                this._coreService.decPrivateModes.applicationCursorKeys = true;
                break;
              case 2:
                this._charsetService.setgCharset(0, a.DEFAULT_CHARSET), this._charsetService.setgCharset(1, a.DEFAULT_CHARSET), this._charsetService.setgCharset(2, a.DEFAULT_CHARSET), this._charsetService.setgCharset(3, a.DEFAULT_CHARSET);
                break;
              case 3:
                this._optionsService.rawOptions.windowOptions.setWinLines && (this._bufferService.resize(132, this._bufferService.rows), this._onRequestReset.fire());
                break;
              case 6:
                this._coreService.decPrivateModes.origin = true, this._setCursor(0, 0);
                break;
              case 7:
                this._coreService.decPrivateModes.wraparound = true;
                break;
              case 12:
                this._optionsService.options.cursorBlink = true;
                break;
              case 45:
                this._coreService.decPrivateModes.reverseWraparound = true;
                break;
              case 66:
                this._logService.debug("Serial port requested application keypad."), this._coreService.decPrivateModes.applicationKeypad = true, this._onRequestSyncScrollBar.fire();
                break;
              case 9:
                this._coreMouseService.activeProtocol = "X10";
                break;
              case 1e3:
                this._coreMouseService.activeProtocol = "VT200";
                break;
              case 1002:
                this._coreMouseService.activeProtocol = "DRAG";
                break;
              case 1003:
                this._coreMouseService.activeProtocol = "ANY";
                break;
              case 1004:
                this._coreService.decPrivateModes.sendFocus = true, this._onRequestSendFocus.fire();
                break;
              case 1005:
                this._logService.debug("DECSET 1005 not supported (see #2507)");
                break;
              case 1006:
                this._coreMouseService.activeEncoding = "SGR";
                break;
              case 1015:
                this._logService.debug("DECSET 1015 not supported (see #2507)");
                break;
              case 1016:
                this._coreMouseService.activeEncoding = "SGR_PIXELS";
                break;
              case 25:
                this._coreService.isCursorHidden = false;
                break;
              case 1048:
                this.saveCursor();
                break;
              case 1049:
                this.saveCursor();
              case 47:
              case 1047:
                this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()), this._coreService.isCursorInitialized = true, this._onRequestRefreshRows.fire(0, this._bufferService.rows - 1), this._onRequestSyncScrollBar.fire();
                break;
              case 2004:
                this._coreService.decPrivateModes.bracketedPasteMode = true;
            }
            return true;
          }
          resetMode(e4) {
            for (let t4 = 0; t4 < e4.length; t4++) switch (e4.params[t4]) {
              case 4:
                this._coreService.modes.insertMode = false;
                break;
              case 20:
                this._optionsService.options.convertEol = false;
            }
            return true;
          }
          resetModePrivate(e4) {
            for (let t4 = 0; t4 < e4.length; t4++) switch (e4.params[t4]) {
              case 1:
                this._coreService.decPrivateModes.applicationCursorKeys = false;
                break;
              case 3:
                this._optionsService.rawOptions.windowOptions.setWinLines && (this._bufferService.resize(80, this._bufferService.rows), this._onRequestReset.fire());
                break;
              case 6:
                this._coreService.decPrivateModes.origin = false, this._setCursor(0, 0);
                break;
              case 7:
                this._coreService.decPrivateModes.wraparound = false;
                break;
              case 12:
                this._optionsService.options.cursorBlink = false;
                break;
              case 45:
                this._coreService.decPrivateModes.reverseWraparound = false;
                break;
              case 66:
                this._logService.debug("Switching back to normal keypad."), this._coreService.decPrivateModes.applicationKeypad = false, this._onRequestSyncScrollBar.fire();
                break;
              case 9:
              case 1e3:
              case 1002:
              case 1003:
                this._coreMouseService.activeProtocol = "NONE";
                break;
              case 1004:
                this._coreService.decPrivateModes.sendFocus = false;
                break;
              case 1005:
                this._logService.debug("DECRST 1005 not supported (see #2507)");
                break;
              case 1006:
              case 1016:
                this._coreMouseService.activeEncoding = "DEFAULT";
                break;
              case 1015:
                this._logService.debug("DECRST 1015 not supported (see #2507)");
                break;
              case 25:
                this._coreService.isCursorHidden = true;
                break;
              case 1048:
                this.restoreCursor();
                break;
              case 1049:
              case 47:
              case 1047:
                this._bufferService.buffers.activateNormalBuffer(), 1049 === e4.params[t4] && this.restoreCursor(), this._coreService.isCursorInitialized = true, this._onRequestRefreshRows.fire(0, this._bufferService.rows - 1), this._onRequestSyncScrollBar.fire();
                break;
              case 2004:
                this._coreService.decPrivateModes.bracketedPasteMode = false;
            }
            return true;
          }
          requestMode(e4, t4) {
            const i3 = this._coreService.decPrivateModes, { activeProtocol: s4, activeEncoding: r5 } = this._coreMouseService, a2 = this._coreService, { buffers: o3, cols: h2 } = this._bufferService, { active: c4, alt: l3 } = o3, _2 = this._optionsService.rawOptions, d2 = /* @__PURE__ */ __name((e5) => e5 ? 1 : 2, "d"), f2 = e4.params[0];
            return u2 = f2, p2 = t4 ? 2 === f2 ? 4 : 4 === f2 ? d2(a2.modes.insertMode) : 12 === f2 ? 3 : 20 === f2 ? d2(_2.convertEol) : 0 : 1 === f2 ? d2(i3.applicationCursorKeys) : 3 === f2 ? _2.windowOptions.setWinLines ? 80 === h2 ? 2 : 132 === h2 ? 1 : 0 : 0 : 6 === f2 ? d2(i3.origin) : 7 === f2 ? d2(i3.wraparound) : 8 === f2 ? 3 : 9 === f2 ? d2("X10" === s4) : 12 === f2 ? d2(_2.cursorBlink) : 25 === f2 ? d2(!a2.isCursorHidden) : 45 === f2 ? d2(i3.reverseWraparound) : 66 === f2 ? d2(i3.applicationKeypad) : 67 === f2 ? 4 : 1e3 === f2 ? d2("VT200" === s4) : 1002 === f2 ? d2("DRAG" === s4) : 1003 === f2 ? d2("ANY" === s4) : 1004 === f2 ? d2(i3.sendFocus) : 1005 === f2 ? 4 : 1006 === f2 ? d2("SGR" === r5) : 1015 === f2 ? 4 : 1016 === f2 ? d2("SGR_PIXELS" === r5) : 1048 === f2 ? 1 : 47 === f2 || 1047 === f2 || 1049 === f2 ? d2(c4 === l3) : 2004 === f2 ? d2(i3.bracketedPasteMode) : 0, a2.triggerDataEvent(`${n3.C0.ESC}[${t4 ? "" : "?"}${u2};${p2}$y`), true;
            var u2, p2;
          }
          _updateAttrColor(e4, t4, i3, s4, r5) {
            return 2 === t4 ? (e4 |= 50331648, e4 &= -16777216, e4 |= u.AttributeData.fromColorRGB([i3, s4, r5])) : 5 === t4 && (e4 &= -50331904, e4 |= 33554432 | 255 & i3), e4;
          }
          _extractColor(e4, t4, i3) {
            const s4 = [0, 0, -1, 0, 0, 0];
            let r5 = 0, n4 = 0;
            do {
              if (s4[n4 + r5] = e4.params[t4 + n4], e4.hasSubParams(t4 + n4)) {
                const i4 = e4.getSubParams(t4 + n4);
                let a2 = 0;
                do {
                  5 === s4[1] && (r5 = 1), s4[n4 + a2 + 1 + r5] = i4[a2];
                } while (++a2 < i4.length && a2 + n4 + 1 + r5 < s4.length);
                break;
              }
              if (5 === s4[1] && n4 + r5 >= 2 || 2 === s4[1] && n4 + r5 >= 5) break;
              s4[1] && (r5 = 1);
            } while (++n4 + t4 < e4.length && n4 + r5 < s4.length);
            for (let e5 = 2; e5 < s4.length; ++e5) -1 === s4[e5] && (s4[e5] = 0);
            switch (s4[0]) {
              case 38:
                i3.fg = this._updateAttrColor(i3.fg, s4[1], s4[3], s4[4], s4[5]);
                break;
              case 48:
                i3.bg = this._updateAttrColor(i3.bg, s4[1], s4[3], s4[4], s4[5]);
                break;
              case 58:
                i3.extended = i3.extended.clone(), i3.extended.underlineColor = this._updateAttrColor(i3.extended.underlineColor, s4[1], s4[3], s4[4], s4[5]);
            }
            return n4;
          }
          _processUnderline(e4, t4) {
            t4.extended = t4.extended.clone(), (!~e4 || e4 > 5) && (e4 = 1), t4.extended.underlineStyle = e4, t4.fg |= 268435456, 0 === e4 && (t4.fg &= -268435457), t4.updateExtended();
          }
          _processSGR0(e4) {
            e4.fg = l2.DEFAULT_ATTR_DATA.fg, e4.bg = l2.DEFAULT_ATTR_DATA.bg, e4.extended = e4.extended.clone(), e4.extended.underlineStyle = 0, e4.extended.underlineColor &= -67108864, e4.updateExtended();
          }
          charAttributes(e4) {
            if (1 === e4.length && 0 === e4.params[0]) return this._processSGR0(this._curAttrData), true;
            const t4 = e4.length;
            let i3;
            const s4 = this._curAttrData;
            for (let r5 = 0; r5 < t4; r5++) i3 = e4.params[r5], i3 >= 30 && i3 <= 37 ? (s4.fg &= -50331904, s4.fg |= 16777216 | i3 - 30) : i3 >= 40 && i3 <= 47 ? (s4.bg &= -50331904, s4.bg |= 16777216 | i3 - 40) : i3 >= 90 && i3 <= 97 ? (s4.fg &= -50331904, s4.fg |= 16777224 | i3 - 90) : i3 >= 100 && i3 <= 107 ? (s4.bg &= -50331904, s4.bg |= 16777224 | i3 - 100) : 0 === i3 ? this._processSGR0(s4) : 1 === i3 ? s4.fg |= 134217728 : 3 === i3 ? s4.bg |= 67108864 : 4 === i3 ? (s4.fg |= 268435456, this._processUnderline(e4.hasSubParams(r5) ? e4.getSubParams(r5)[0] : 1, s4)) : 5 === i3 ? s4.fg |= 536870912 : 7 === i3 ? s4.fg |= 67108864 : 8 === i3 ? s4.fg |= 1073741824 : 9 === i3 ? s4.fg |= 2147483648 : 2 === i3 ? s4.bg |= 134217728 : 21 === i3 ? this._processUnderline(2, s4) : 22 === i3 ? (s4.fg &= -134217729, s4.bg &= -134217729) : 23 === i3 ? s4.bg &= -67108865 : 24 === i3 ? (s4.fg &= -268435457, this._processUnderline(0, s4)) : 25 === i3 ? s4.fg &= -536870913 : 27 === i3 ? s4.fg &= -67108865 : 28 === i3 ? s4.fg &= -1073741825 : 29 === i3 ? s4.fg &= 2147483647 : 39 === i3 ? (s4.fg &= -67108864, s4.fg |= 16777215 & l2.DEFAULT_ATTR_DATA.fg) : 49 === i3 ? (s4.bg &= -67108864, s4.bg |= 16777215 & l2.DEFAULT_ATTR_DATA.bg) : 38 === i3 || 48 === i3 || 58 === i3 ? r5 += this._extractColor(e4, r5, s4) : 53 === i3 ? s4.bg |= 1073741824 : 55 === i3 ? s4.bg &= -1073741825 : 59 === i3 ? (s4.extended = s4.extended.clone(), s4.extended.underlineColor = -1, s4.updateExtended()) : 100 === i3 ? (s4.fg &= -67108864, s4.fg |= 16777215 & l2.DEFAULT_ATTR_DATA.fg, s4.bg &= -67108864, s4.bg |= 16777215 & l2.DEFAULT_ATTR_DATA.bg) : this._logService.debug("Unknown SGR attribute: %d.", i3);
            return true;
          }
          deviceStatus(e4) {
            switch (e4.params[0]) {
              case 5:
                this._coreService.triggerDataEvent(`${n3.C0.ESC}[0n`);
                break;
              case 6:
                const e5 = this._activeBuffer.y + 1, t4 = this._activeBuffer.x + 1;
                this._coreService.triggerDataEvent(`${n3.C0.ESC}[${e5};${t4}R`);
            }
            return true;
          }
          deviceStatusPrivate(e4) {
            if (6 === e4.params[0]) {
              const e5 = this._activeBuffer.y + 1, t4 = this._activeBuffer.x + 1;
              this._coreService.triggerDataEvent(`${n3.C0.ESC}[?${e5};${t4}R`);
            }
            return true;
          }
          softReset(e4) {
            return this._coreService.isCursorHidden = false, this._onRequestSyncScrollBar.fire(), this._activeBuffer.scrollTop = 0, this._activeBuffer.scrollBottom = this._bufferService.rows - 1, this._curAttrData = l2.DEFAULT_ATTR_DATA.clone(), this._coreService.reset(), this._charsetService.reset(), this._activeBuffer.savedX = 0, this._activeBuffer.savedY = this._activeBuffer.ybase, this._activeBuffer.savedCurAttrData.fg = this._curAttrData.fg, this._activeBuffer.savedCurAttrData.bg = this._curAttrData.bg, this._activeBuffer.savedCharset = this._charsetService.charset, this._coreService.decPrivateModes.origin = false, true;
          }
          setCursorStyle(e4) {
            const t4 = e4.params[0] || 1;
            switch (t4) {
              case 1:
              case 2:
                this._optionsService.options.cursorStyle = "block";
                break;
              case 3:
              case 4:
                this._optionsService.options.cursorStyle = "underline";
                break;
              case 5:
              case 6:
                this._optionsService.options.cursorStyle = "bar";
            }
            const i3 = t4 % 2 == 1;
            return this._optionsService.options.cursorBlink = i3, true;
          }
          setScrollRegion(e4) {
            const t4 = e4.params[0] || 1;
            let i3;
            return (e4.length < 2 || (i3 = e4.params[1]) > this._bufferService.rows || 0 === i3) && (i3 = this._bufferService.rows), i3 > t4 && (this._activeBuffer.scrollTop = t4 - 1, this._activeBuffer.scrollBottom = i3 - 1, this._setCursor(0, 0)), true;
          }
          windowOptions(e4) {
            if (!y(e4.params[0], this._optionsService.rawOptions.windowOptions)) return true;
            const t4 = e4.length > 1 ? e4.params[1] : 0;
            switch (e4.params[0]) {
              case 14:
                2 !== t4 && this._onRequestWindowsOptionsReport.fire(w.GET_WIN_SIZE_PIXELS);
                break;
              case 16:
                this._onRequestWindowsOptionsReport.fire(w.GET_CELL_SIZE_PIXELS);
                break;
              case 18:
                this._bufferService && this._coreService.triggerDataEvent(`${n3.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);
                break;
              case 22:
                0 !== t4 && 2 !== t4 || (this._windowTitleStack.push(this._windowTitle), this._windowTitleStack.length > 10 && this._windowTitleStack.shift()), 0 !== t4 && 1 !== t4 || (this._iconNameStack.push(this._iconName), this._iconNameStack.length > 10 && this._iconNameStack.shift());
                break;
              case 23:
                0 !== t4 && 2 !== t4 || this._windowTitleStack.length && this.setTitle(this._windowTitleStack.pop()), 0 !== t4 && 1 !== t4 || this._iconNameStack.length && this.setIconName(this._iconNameStack.pop());
            }
            return true;
          }
          saveCursor(e4) {
            return this._activeBuffer.savedX = this._activeBuffer.x, this._activeBuffer.savedY = this._activeBuffer.ybase + this._activeBuffer.y, this._activeBuffer.savedCurAttrData.fg = this._curAttrData.fg, this._activeBuffer.savedCurAttrData.bg = this._curAttrData.bg, this._activeBuffer.savedCharset = this._charsetService.charset, true;
          }
          restoreCursor(e4) {
            return this._activeBuffer.x = this._activeBuffer.savedX || 0, this._activeBuffer.y = Math.max(this._activeBuffer.savedY - this._activeBuffer.ybase, 0), this._curAttrData.fg = this._activeBuffer.savedCurAttrData.fg, this._curAttrData.bg = this._activeBuffer.savedCurAttrData.bg, this._charsetService.charset = this._savedCharset, this._activeBuffer.savedCharset && (this._charsetService.charset = this._activeBuffer.savedCharset), this._restrictCursor(), true;
          }
          setTitle(e4) {
            return this._windowTitle = e4, this._onTitleChange.fire(e4), true;
          }
          setIconName(e4) {
            return this._iconName = e4, true;
          }
          setOrReportIndexedColor(e4) {
            const t4 = [], i3 = e4.split(";");
            for (; i3.length > 1; ) {
              const e5 = i3.shift(), s4 = i3.shift();
              if (/^\d+$/.exec(e5)) {
                const i4 = parseInt(e5);
                if (L(i4)) if ("?" === s4) t4.push({ type: 0, index: i4 });
                else {
                  const e6 = (0, S.parseColor)(s4);
                  e6 && t4.push({ type: 1, index: i4, color: e6 });
                }
              }
            }
            return t4.length && this._onColor.fire(t4), true;
          }
          setHyperlink(e4) {
            const t4 = e4.split(";");
            return !(t4.length < 2) && (t4[1] ? this._createHyperlink(t4[0], t4[1]) : !t4[0] && this._finishHyperlink());
          }
          _createHyperlink(e4, t4) {
            this._getCurrentLinkId() && this._finishHyperlink();
            const i3 = e4.split(":");
            let s4;
            const r5 = i3.findIndex((e5) => e5.startsWith("id="));
            return -1 !== r5 && (s4 = i3[r5].slice(3) || void 0), this._curAttrData.extended = this._curAttrData.extended.clone(), this._curAttrData.extended.urlId = this._oscLinkService.registerLink({ id: s4, uri: t4 }), this._curAttrData.updateExtended(), true;
          }
          _finishHyperlink() {
            return this._curAttrData.extended = this._curAttrData.extended.clone(), this._curAttrData.extended.urlId = 0, this._curAttrData.updateExtended(), true;
          }
          _setOrReportSpecialColor(e4, t4) {
            const i3 = e4.split(";");
            for (let e5 = 0; e5 < i3.length && !(t4 >= this._specialColors.length); ++e5, ++t4) if ("?" === i3[e5]) this._onColor.fire([{ type: 0, index: this._specialColors[t4] }]);
            else {
              const s4 = (0, S.parseColor)(i3[e5]);
              s4 && this._onColor.fire([{ type: 1, index: this._specialColors[t4], color: s4 }]);
            }
            return true;
          }
          setOrReportFgColor(e4) {
            return this._setOrReportSpecialColor(e4, 0);
          }
          setOrReportBgColor(e4) {
            return this._setOrReportSpecialColor(e4, 1);
          }
          setOrReportCursorColor(e4) {
            return this._setOrReportSpecialColor(e4, 2);
          }
          restoreIndexedColor(e4) {
            if (!e4) return this._onColor.fire([{ type: 2 }]), true;
            const t4 = [], i3 = e4.split(";");
            for (let e5 = 0; e5 < i3.length; ++e5) if (/^\d+$/.exec(i3[e5])) {
              const s4 = parseInt(i3[e5]);
              L(s4) && t4.push({ type: 2, index: s4 });
            }
            return t4.length && this._onColor.fire(t4), true;
          }
          restoreFgColor(e4) {
            return this._onColor.fire([{ type: 2, index: 256 }]), true;
          }
          restoreBgColor(e4) {
            return this._onColor.fire([{ type: 2, index: 257 }]), true;
          }
          restoreCursorColor(e4) {
            return this._onColor.fire([{ type: 2, index: 258 }]), true;
          }
          nextLine() {
            return this._activeBuffer.x = 0, this.index(), true;
          }
          keypadApplicationMode() {
            return this._logService.debug("Serial port requested application keypad."), this._coreService.decPrivateModes.applicationKeypad = true, this._onRequestSyncScrollBar.fire(), true;
          }
          keypadNumericMode() {
            return this._logService.debug("Switching back to normal keypad."), this._coreService.decPrivateModes.applicationKeypad = false, this._onRequestSyncScrollBar.fire(), true;
          }
          selectDefaultCharset() {
            return this._charsetService.setgLevel(0), this._charsetService.setgCharset(0, a.DEFAULT_CHARSET), true;
          }
          selectCharset(e4) {
            return 2 !== e4.length ? (this.selectDefaultCharset(), true) : ("/" === e4[0] || this._charsetService.setgCharset(m[e4[0]], a.CHARSETS[e4[1]] || a.DEFAULT_CHARSET), true);
          }
          index() {
            return this._restrictCursor(), this._activeBuffer.y++, this._activeBuffer.y === this._activeBuffer.scrollBottom + 1 ? (this._activeBuffer.y--, this._bufferService.scroll(this._eraseAttrData())) : this._activeBuffer.y >= this._bufferService.rows && (this._activeBuffer.y = this._bufferService.rows - 1), this._restrictCursor(), true;
          }
          tabSet() {
            return this._activeBuffer.tabs[this._activeBuffer.x] = true, true;
          }
          reverseIndex() {
            if (this._restrictCursor(), this._activeBuffer.y === this._activeBuffer.scrollTop) {
              const e4 = this._activeBuffer.scrollBottom - this._activeBuffer.scrollTop;
              this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase + this._activeBuffer.y, e4, 1), this._activeBuffer.lines.set(this._activeBuffer.ybase + this._activeBuffer.y, this._activeBuffer.getBlankLine(this._eraseAttrData())), this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);
            } else this._activeBuffer.y--, this._restrictCursor();
            return true;
          }
          fullReset() {
            return this._parser.reset(), this._onRequestReset.fire(), true;
          }
          reset() {
            this._curAttrData = l2.DEFAULT_ATTR_DATA.clone(), this._eraseAttrDataInternal = l2.DEFAULT_ATTR_DATA.clone();
          }
          _eraseAttrData() {
            return this._eraseAttrDataInternal.bg &= -67108864, this._eraseAttrDataInternal.bg |= 67108863 & this._curAttrData.bg, this._eraseAttrDataInternal;
          }
          setgLevel(e4) {
            return this._charsetService.setgLevel(e4), true;
          }
          screenAlignmentPattern() {
            const e4 = new f.CellData();
            e4.content = 1 << 22 | "E".charCodeAt(0), e4.fg = this._curAttrData.fg, e4.bg = this._curAttrData.bg, this._setCursor(0, 0);
            for (let t4 = 0; t4 < this._bufferService.rows; ++t4) {
              const i3 = this._activeBuffer.ybase + this._activeBuffer.y + t4, s4 = this._activeBuffer.lines.get(i3);
              s4 && (s4.fill(e4), s4.isWrapped = false);
            }
            return this._dirtyRowTracker.markAllDirty(), this._setCursor(0, 0), true;
          }
          requestStatusString(e4, t4) {
            const i3 = this._bufferService.buffer, s4 = this._optionsService.rawOptions;
            return ((e5) => (this._coreService.triggerDataEvent(`${n3.C0.ESC}${e5}${n3.C0.ESC}\\`), true))('"q' === e4 ? `P1$r${this._curAttrData.isProtected() ? 1 : 0}"q` : '"p' === e4 ? 'P1$r61;1"p' : "r" === e4 ? `P1$r${i3.scrollTop + 1};${i3.scrollBottom + 1}r` : "m" === e4 ? "P1$r0m" : " q" === e4 ? `P1$r${{ block: 2, underline: 4, bar: 6 }[s4.cursorStyle] - (s4.cursorBlink ? 1 : 0)} q` : "P0$r");
          }
          markRangeDirty(e4, t4) {
            this._dirtyRowTracker.markRangeDirty(e4, t4);
          }
        }
        t3.InputHandler = E;
        let A = class {
          static {
            __name(this, "A");
          }
          constructor(e4) {
            this._bufferService = e4, this.clearRange();
          }
          clearRange() {
            this.start = this._bufferService.buffer.y, this.end = this._bufferService.buffer.y;
          }
          markDirty(e4) {
            e4 < this.start ? this.start = e4 : e4 > this.end && (this.end = e4);
          }
          markRangeDirty(e4, t4) {
            e4 > t4 && (B = e4, e4 = t4, t4 = B), e4 < this.start && (this.start = e4), t4 > this.end && (this.end = t4);
          }
          markAllDirty() {
            this.markRangeDirty(0, this._bufferService.rows - 1);
          }
        };
        function L(e4) {
          return 0 <= e4 && e4 < 256;
        }
        __name(L, "L");
        A = s3([r4(0, p.IBufferService)], A);
      }, 844: (e3, t3) => {
        function i2(e4) {
          for (const t4 of e4) t4.dispose();
          e4.length = 0;
        }
        __name(i2, "i");
        Object.defineProperty(t3, "__esModule", { value: true }), t3.getDisposeArrayDisposable = t3.disposeArray = t3.toDisposable = t3.MutableDisposable = t3.Disposable = void 0, t3.Disposable = class {
          constructor() {
            this._disposables = [], this._isDisposed = false;
          }
          dispose() {
            this._isDisposed = true;
            for (const e4 of this._disposables) e4.dispose();
            this._disposables.length = 0;
          }
          register(e4) {
            return this._disposables.push(e4), e4;
          }
          unregister(e4) {
            const t4 = this._disposables.indexOf(e4);
            -1 !== t4 && this._disposables.splice(t4, 1);
          }
        }, t3.MutableDisposable = class {
          constructor() {
            this._isDisposed = false;
          }
          get value() {
            return this._isDisposed ? void 0 : this._value;
          }
          set value(e4) {
            this._isDisposed || e4 === this._value || (this._value?.dispose(), this._value = e4);
          }
          clear() {
            this.value = void 0;
          }
          dispose() {
            this._isDisposed = true, this._value?.dispose(), this._value = void 0;
          }
        }, t3.toDisposable = function(e4) {
          return { dispose: e4 };
        }, t3.disposeArray = i2, t3.getDisposeArrayDisposable = function(e4) {
          return { dispose: /* @__PURE__ */ __name(() => i2(e4), "dispose") };
        };
      }, 114: (e3, t3) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.isChromeOS = t3.isLinux = t3.isWindows = t3.isIphone = t3.isIpad = t3.isMac = t3.getSafariVersion = t3.isSafari = t3.isLegacyEdge = t3.isFirefox = t3.isNode = void 0, t3.isNode = "undefined" != typeof process && "title" in process;
        const i2 = t3.isNode ? "node" : navigator.userAgent, s3 = t3.isNode ? "node" : navigator.platform;
        t3.isFirefox = i2.includes("Firefox"), t3.isLegacyEdge = i2.includes("Edge"), t3.isSafari = /^((?!chrome|android).)*safari/i.test(i2), t3.getSafariVersion = function() {
          if (!t3.isSafari) return 0;
          const e4 = i2.match(/Version\/(\d+)/);
          return null === e4 || e4.length < 2 ? 0 : parseInt(e4[1]);
        }, t3.isMac = ["Macintosh", "MacIntel", "MacPPC", "Mac68K"].includes(s3), t3.isIpad = "iPad" === s3, t3.isIphone = "iPhone" === s3, t3.isWindows = ["Windows", "Win16", "Win32", "WinCE"].includes(s3), t3.isLinux = s3.indexOf("Linux") >= 0, t3.isChromeOS = /\bCrOS\b/.test(i2);
      }, 226: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.DebouncedIdleTask = t3.IdleTaskQueue = t3.PriorityTaskQueue = void 0;
        const s3 = i2(114);
        class r4 {
          static {
            __name(this, "r");
          }
          constructor() {
            this._tasks = [], this._i = 0;
          }
          enqueue(e4) {
            this._tasks.push(e4), this._start();
          }
          flush() {
            for (; this._i < this._tasks.length; ) this._tasks[this._i]() || this._i++;
            this.clear();
          }
          clear() {
            this._idleCallback && (this._cancelCallback(this._idleCallback), this._idleCallback = void 0), this._i = 0, this._tasks.length = 0;
          }
          _start() {
            this._idleCallback || (this._idleCallback = this._requestCallback(this._process.bind(this)));
          }
          _process(e4) {
            this._idleCallback = void 0;
            let t4 = 0, i3 = 0, s4 = e4.timeRemaining(), r5 = 0;
            for (; this._i < this._tasks.length; ) {
              if (t4 = Date.now(), this._tasks[this._i]() || this._i++, t4 = Math.max(1, Date.now() - t4), i3 = Math.max(t4, i3), r5 = e4.timeRemaining(), 1.5 * i3 > r5) return s4 - t4 < -20 && console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s4 - t4))}ms`), void this._start();
              s4 = r5;
            }
            this.clear();
          }
        }
        class n3 extends r4 {
          static {
            __name(this, "n");
          }
          _requestCallback(e4) {
            return setTimeout(() => e4(this._createDeadline(16)));
          }
          _cancelCallback(e4) {
            clearTimeout(e4);
          }
          _createDeadline(e4) {
            const t4 = Date.now() + e4;
            return { timeRemaining: /* @__PURE__ */ __name(() => Math.max(0, t4 - Date.now()), "timeRemaining") };
          }
        }
        t3.PriorityTaskQueue = n3, t3.IdleTaskQueue = !s3.isNode && "requestIdleCallback" in window ? class extends r4 {
          _requestCallback(e4) {
            return requestIdleCallback(e4);
          }
          _cancelCallback(e4) {
            cancelIdleCallback(e4);
          }
        } : n3, t3.DebouncedIdleTask = class {
          constructor() {
            this._queue = new t3.IdleTaskQueue();
          }
          set(e4) {
            this._queue.clear(), this._queue.enqueue(e4);
          }
          flush() {
            this._queue.flush();
          }
        };
      }, 282: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.updateWindowsModeWrappedState = void 0;
        const s3 = i2(643);
        t3.updateWindowsModeWrappedState = function(e4) {
          const t4 = e4.buffer.lines.get(e4.buffer.ybase + e4.buffer.y - 1), i3 = t4?.get(e4.cols - 1), r4 = e4.buffer.lines.get(e4.buffer.ybase + e4.buffer.y);
          r4 && i3 && (r4.isWrapped = i3[s3.CHAR_DATA_CODE_INDEX] !== s3.NULL_CELL_CODE && i3[s3.CHAR_DATA_CODE_INDEX] !== s3.WHITESPACE_CELL_CODE);
        };
      }, 734: (e3, t3) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.ExtendedAttrs = t3.AttributeData = void 0;
        class i2 {
          static {
            __name(this, "i");
          }
          constructor() {
            this.fg = 0, this.bg = 0, this.extended = new s3();
          }
          static toColorRGB(e4) {
            return [e4 >>> 16 & 255, e4 >>> 8 & 255, 255 & e4];
          }
          static fromColorRGB(e4) {
            return (255 & e4[0]) << 16 | (255 & e4[1]) << 8 | 255 & e4[2];
          }
          clone() {
            const e4 = new i2();
            return e4.fg = this.fg, e4.bg = this.bg, e4.extended = this.extended.clone(), e4;
          }
          isInverse() {
            return 67108864 & this.fg;
          }
          isBold() {
            return 134217728 & this.fg;
          }
          isUnderline() {
            return this.hasExtendedAttrs() && 0 !== this.extended.underlineStyle ? 1 : 268435456 & this.fg;
          }
          isBlink() {
            return 536870912 & this.fg;
          }
          isInvisible() {
            return 1073741824 & this.fg;
          }
          isItalic() {
            return 67108864 & this.bg;
          }
          isDim() {
            return 134217728 & this.bg;
          }
          isStrikethrough() {
            return 2147483648 & this.fg;
          }
          isProtected() {
            return 536870912 & this.bg;
          }
          isOverline() {
            return 1073741824 & this.bg;
          }
          getFgColorMode() {
            return 50331648 & this.fg;
          }
          getBgColorMode() {
            return 50331648 & this.bg;
          }
          isFgRGB() {
            return 50331648 == (50331648 & this.fg);
          }
          isBgRGB() {
            return 50331648 == (50331648 & this.bg);
          }
          isFgPalette() {
            return 16777216 == (50331648 & this.fg) || 33554432 == (50331648 & this.fg);
          }
          isBgPalette() {
            return 16777216 == (50331648 & this.bg) || 33554432 == (50331648 & this.bg);
          }
          isFgDefault() {
            return 0 == (50331648 & this.fg);
          }
          isBgDefault() {
            return 0 == (50331648 & this.bg);
          }
          isAttributeDefault() {
            return 0 === this.fg && 0 === this.bg;
          }
          getFgColor() {
            switch (50331648 & this.fg) {
              case 16777216:
              case 33554432:
                return 255 & this.fg;
              case 50331648:
                return 16777215 & this.fg;
              default:
                return -1;
            }
          }
          getBgColor() {
            switch (50331648 & this.bg) {
              case 16777216:
              case 33554432:
                return 255 & this.bg;
              case 50331648:
                return 16777215 & this.bg;
              default:
                return -1;
            }
          }
          hasExtendedAttrs() {
            return 268435456 & this.bg;
          }
          updateExtended() {
            this.extended.isEmpty() ? this.bg &= -268435457 : this.bg |= 268435456;
          }
          getUnderlineColor() {
            if (268435456 & this.bg && ~this.extended.underlineColor) switch (50331648 & this.extended.underlineColor) {
              case 16777216:
              case 33554432:
                return 255 & this.extended.underlineColor;
              case 50331648:
                return 16777215 & this.extended.underlineColor;
              default:
                return this.getFgColor();
            }
            return this.getFgColor();
          }
          getUnderlineColorMode() {
            return 268435456 & this.bg && ~this.extended.underlineColor ? 50331648 & this.extended.underlineColor : this.getFgColorMode();
          }
          isUnderlineColorRGB() {
            return 268435456 & this.bg && ~this.extended.underlineColor ? 50331648 == (50331648 & this.extended.underlineColor) : this.isFgRGB();
          }
          isUnderlineColorPalette() {
            return 268435456 & this.bg && ~this.extended.underlineColor ? 16777216 == (50331648 & this.extended.underlineColor) || 33554432 == (50331648 & this.extended.underlineColor) : this.isFgPalette();
          }
          isUnderlineColorDefault() {
            return 268435456 & this.bg && ~this.extended.underlineColor ? 0 == (50331648 & this.extended.underlineColor) : this.isFgDefault();
          }
          getUnderlineStyle() {
            return 268435456 & this.fg ? 268435456 & this.bg ? this.extended.underlineStyle : 1 : 0;
          }
          getUnderlineVariantOffset() {
            return this.extended.underlineVariantOffset;
          }
        }
        t3.AttributeData = i2;
        class s3 {
          static {
            __name(this, "s");
          }
          get ext() {
            return this._urlId ? -469762049 & this._ext | this.underlineStyle << 26 : this._ext;
          }
          set ext(e4) {
            this._ext = e4;
          }
          get underlineStyle() {
            return this._urlId ? 5 : (469762048 & this._ext) >> 26;
          }
          set underlineStyle(e4) {
            this._ext &= -469762049, this._ext |= e4 << 26 & 469762048;
          }
          get underlineColor() {
            return 67108863 & this._ext;
          }
          set underlineColor(e4) {
            this._ext &= -67108864, this._ext |= 67108863 & e4;
          }
          get urlId() {
            return this._urlId;
          }
          set urlId(e4) {
            this._urlId = e4;
          }
          get underlineVariantOffset() {
            const e4 = (3758096384 & this._ext) >> 29;
            return e4 < 0 ? 4294967288 ^ e4 : e4;
          }
          set underlineVariantOffset(e4) {
            this._ext &= 536870911, this._ext |= e4 << 29 & 3758096384;
          }
          constructor(e4 = 0, t4 = 0) {
            this._ext = 0, this._urlId = 0, this._ext = e4, this._urlId = t4;
          }
          clone() {
            return new s3(this._ext, this._urlId);
          }
          isEmpty() {
            return 0 === this.underlineStyle && 0 === this._urlId;
          }
        }
        t3.ExtendedAttrs = s3;
      }, 92: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.Buffer = t3.MAX_BUFFER_SIZE = void 0;
        const s3 = i2(349), r4 = i2(226), n3 = i2(734), a = i2(437), o2 = i2(634), h = i2(511), c3 = i2(643), l2 = i2(863), _ = i2(116);
        t3.MAX_BUFFER_SIZE = 4294967295, t3.Buffer = class {
          constructor(e4, t4, i3) {
            this._hasScrollback = e4, this._optionsService = t4, this._bufferService = i3, this.ydisp = 0, this.ybase = 0, this.y = 0, this.x = 0, this.tabs = {}, this.savedY = 0, this.savedX = 0, this.savedCurAttrData = a.DEFAULT_ATTR_DATA.clone(), this.savedCharset = _.DEFAULT_CHARSET, this.markers = [], this._nullCell = h.CellData.fromCharData([0, c3.NULL_CELL_CHAR, c3.NULL_CELL_WIDTH, c3.NULL_CELL_CODE]), this._whitespaceCell = h.CellData.fromCharData([0, c3.WHITESPACE_CELL_CHAR, c3.WHITESPACE_CELL_WIDTH, c3.WHITESPACE_CELL_CODE]), this._isClearing = false, this._memoryCleanupQueue = new r4.IdleTaskQueue(), this._memoryCleanupPosition = 0, this._cols = this._bufferService.cols, this._rows = this._bufferService.rows, this.lines = new s3.CircularList(this._getCorrectBufferLength(this._rows)), this.scrollTop = 0, this.scrollBottom = this._rows - 1, this.setupTabStops();
          }
          getNullCell(e4) {
            return e4 ? (this._nullCell.fg = e4.fg, this._nullCell.bg = e4.bg, this._nullCell.extended = e4.extended) : (this._nullCell.fg = 0, this._nullCell.bg = 0, this._nullCell.extended = new n3.ExtendedAttrs()), this._nullCell;
          }
          getWhitespaceCell(e4) {
            return e4 ? (this._whitespaceCell.fg = e4.fg, this._whitespaceCell.bg = e4.bg, this._whitespaceCell.extended = e4.extended) : (this._whitespaceCell.fg = 0, this._whitespaceCell.bg = 0, this._whitespaceCell.extended = new n3.ExtendedAttrs()), this._whitespaceCell;
          }
          getBlankLine(e4, t4) {
            return new a.BufferLine(this._bufferService.cols, this.getNullCell(e4), t4);
          }
          get hasScrollback() {
            return this._hasScrollback && this.lines.maxLength > this._rows;
          }
          get isCursorInViewport() {
            const e4 = this.ybase + this.y - this.ydisp;
            return e4 >= 0 && e4 < this._rows;
          }
          _getCorrectBufferLength(e4) {
            if (!this._hasScrollback) return e4;
            const i3 = e4 + this._optionsService.rawOptions.scrollback;
            return i3 > t3.MAX_BUFFER_SIZE ? t3.MAX_BUFFER_SIZE : i3;
          }
          fillViewportRows(e4) {
            if (0 === this.lines.length) {
              void 0 === e4 && (e4 = a.DEFAULT_ATTR_DATA);
              let t4 = this._rows;
              for (; t4--; ) this.lines.push(this.getBlankLine(e4));
            }
          }
          clear() {
            this.ydisp = 0, this.ybase = 0, this.y = 0, this.x = 0, this.lines = new s3.CircularList(this._getCorrectBufferLength(this._rows)), this.scrollTop = 0, this.scrollBottom = this._rows - 1, this.setupTabStops();
          }
          resize(e4, t4) {
            const i3 = this.getNullCell(a.DEFAULT_ATTR_DATA);
            let s4 = 0;
            const r5 = this._getCorrectBufferLength(t4);
            if (r5 > this.lines.maxLength && (this.lines.maxLength = r5), this.lines.length > 0) {
              if (this._cols < e4) for (let t5 = 0; t5 < this.lines.length; t5++) s4 += +this.lines.get(t5).resize(e4, i3);
              let n4 = 0;
              if (this._rows < t4) for (let s5 = this._rows; s5 < t4; s5++) this.lines.length < t4 + this.ybase && (this._optionsService.rawOptions.windowsMode || void 0 !== this._optionsService.rawOptions.windowsPty.backend || void 0 !== this._optionsService.rawOptions.windowsPty.buildNumber ? this.lines.push(new a.BufferLine(e4, i3)) : this.ybase > 0 && this.lines.length <= this.ybase + this.y + n4 + 1 ? (this.ybase--, n4++, this.ydisp > 0 && this.ydisp--) : this.lines.push(new a.BufferLine(e4, i3)));
              else for (let e5 = this._rows; e5 > t4; e5--) this.lines.length > t4 + this.ybase && (this.lines.length > this.ybase + this.y + 1 ? this.lines.pop() : (this.ybase++, this.ydisp++));
              if (r5 < this.lines.maxLength) {
                const e5 = this.lines.length - r5;
                e5 > 0 && (this.lines.trimStart(e5), this.ybase = Math.max(this.ybase - e5, 0), this.ydisp = Math.max(this.ydisp - e5, 0), this.savedY = Math.max(this.savedY - e5, 0)), this.lines.maxLength = r5;
              }
              this.x = Math.min(this.x, e4 - 1), this.y = Math.min(this.y, t4 - 1), n4 && (this.y += n4), this.savedX = Math.min(this.savedX, e4 - 1), this.scrollTop = 0;
            }
            if (this.scrollBottom = t4 - 1, this._isReflowEnabled && (this._reflow(e4, t4), this._cols > e4)) for (let t5 = 0; t5 < this.lines.length; t5++) s4 += +this.lines.get(t5).resize(e4, i3);
            this._cols = e4, this._rows = t4, this._memoryCleanupQueue.clear(), s4 > 0.1 * this.lines.length && (this._memoryCleanupPosition = 0, this._memoryCleanupQueue.enqueue(() => this._batchedMemoryCleanup()));
          }
          _batchedMemoryCleanup() {
            let e4 = true;
            this._memoryCleanupPosition >= this.lines.length && (this._memoryCleanupPosition = 0, e4 = false);
            let t4 = 0;
            for (; this._memoryCleanupPosition < this.lines.length; ) if (t4 += this.lines.get(this._memoryCleanupPosition++).cleanupMemory(), t4 > 100) return true;
            return e4;
          }
          get _isReflowEnabled() {
            const e4 = this._optionsService.rawOptions.windowsPty;
            return e4 && e4.buildNumber ? this._hasScrollback && "conpty" === e4.backend && e4.buildNumber >= 21376 : this._hasScrollback && !this._optionsService.rawOptions.windowsMode;
          }
          _reflow(e4, t4) {
            this._cols !== e4 && (e4 > this._cols ? this._reflowLarger(e4, t4) : this._reflowSmaller(e4, t4));
          }
          _reflowLarger(e4, t4) {
            const i3 = (0, o2.reflowLargerGetLinesToRemove)(this.lines, this._cols, e4, this.ybase + this.y, this.getNullCell(a.DEFAULT_ATTR_DATA));
            if (i3.length > 0) {
              const s4 = (0, o2.reflowLargerCreateNewLayout)(this.lines, i3);
              (0, o2.reflowLargerApplyNewLayout)(this.lines, s4.layout), this._reflowLargerAdjustViewport(e4, t4, s4.countRemoved);
            }
          }
          _reflowLargerAdjustViewport(e4, t4, i3) {
            const s4 = this.getNullCell(a.DEFAULT_ATTR_DATA);
            let r5 = i3;
            for (; r5-- > 0; ) 0 === this.ybase ? (this.y > 0 && this.y--, this.lines.length < t4 && this.lines.push(new a.BufferLine(e4, s4))) : (this.ydisp === this.ybase && this.ydisp--, this.ybase--);
            this.savedY = Math.max(this.savedY - i3, 0);
          }
          _reflowSmaller(e4, t4) {
            const i3 = this.getNullCell(a.DEFAULT_ATTR_DATA), s4 = [];
            let r5 = 0;
            for (let n4 = this.lines.length - 1; n4 >= 0; n4--) {
              let h2 = this.lines.get(n4);
              if (!h2 || !h2.isWrapped && h2.getTrimmedLength() <= e4) continue;
              const c4 = [h2];
              for (; h2.isWrapped && n4 > 0; ) h2 = this.lines.get(--n4), c4.unshift(h2);
              const l3 = this.ybase + this.y;
              if (l3 >= n4 && l3 < n4 + c4.length) continue;
              const _2 = c4[c4.length - 1].getTrimmedLength(), d = (0, o2.reflowSmallerGetNewLineLengths)(c4, this._cols, e4), f = d.length - c4.length;
              let u;
              u = 0 === this.ybase && this.y !== this.lines.length - 1 ? Math.max(0, this.y - this.lines.maxLength + f) : Math.max(0, this.lines.length - this.lines.maxLength + f);
              const p = [];
              for (let e5 = 0; e5 < f; e5++) {
                const e6 = this.getBlankLine(a.DEFAULT_ATTR_DATA, true);
                p.push(e6);
              }
              p.length > 0 && (s4.push({ start: n4 + c4.length + r5, newLines: p }), r5 += p.length), c4.push(...p);
              let g = d.length - 1, v = d[g];
              0 === v && (g--, v = d[g]);
              let b = c4.length - f - 1, S = _2;
              for (; b >= 0; ) {
                const e5 = Math.min(S, v);
                if (void 0 === c4[g]) break;
                if (c4[g].copyCellsFrom(c4[b], S - e5, v - e5, e5, true), v -= e5, 0 === v && (g--, v = d[g]), S -= e5, 0 === S) {
                  b--;
                  const e6 = Math.max(b, 0);
                  S = (0, o2.getWrappedLineTrimmedLength)(c4, e6, this._cols);
                }
              }
              for (let t5 = 0; t5 < c4.length; t5++) d[t5] < e4 && c4[t5].setCell(d[t5], i3);
              let m = f - u;
              for (; m-- > 0; ) 0 === this.ybase ? this.y < t4 - 1 ? (this.y++, this.lines.pop()) : (this.ybase++, this.ydisp++) : this.ybase < Math.min(this.lines.maxLength, this.lines.length + r5) - t4 && (this.ybase === this.ydisp && this.ydisp++, this.ybase++);
              this.savedY = Math.min(this.savedY + f, this.ybase + t4 - 1);
            }
            if (s4.length > 0) {
              const e5 = [], t5 = [];
              for (let e6 = 0; e6 < this.lines.length; e6++) t5.push(this.lines.get(e6));
              const i4 = this.lines.length;
              let n4 = i4 - 1, a2 = 0, o3 = s4[a2];
              this.lines.length = Math.min(this.lines.maxLength, this.lines.length + r5);
              let h2 = 0;
              for (let c5 = Math.min(this.lines.maxLength - 1, i4 + r5 - 1); c5 >= 0; c5--) if (o3 && o3.start > n4 + h2) {
                for (let e6 = o3.newLines.length - 1; e6 >= 0; e6--) this.lines.set(c5--, o3.newLines[e6]);
                c5++, e5.push({ index: n4 + 1, amount: o3.newLines.length }), h2 += o3.newLines.length, o3 = s4[++a2];
              } else this.lines.set(c5, t5[n4--]);
              let c4 = 0;
              for (let t6 = e5.length - 1; t6 >= 0; t6--) e5[t6].index += c4, this.lines.onInsertEmitter.fire(e5[t6]), c4 += e5[t6].amount;
              const l3 = Math.max(0, i4 + r5 - this.lines.maxLength);
              l3 > 0 && this.lines.onTrimEmitter.fire(l3);
            }
          }
          translateBufferLineToString(e4, t4, i3 = 0, s4) {
            const r5 = this.lines.get(e4);
            return r5 ? r5.translateToString(t4, i3, s4) : "";
          }
          getWrappedRangeForLine(e4) {
            let t4 = e4, i3 = e4;
            for (; t4 > 0 && this.lines.get(t4).isWrapped; ) t4--;
            for (; i3 + 1 < this.lines.length && this.lines.get(i3 + 1).isWrapped; ) i3++;
            return { first: t4, last: i3 };
          }
          setupTabStops(e4) {
            for (null != e4 ? this.tabs[e4] || (e4 = this.prevStop(e4)) : (this.tabs = {}, e4 = 0); e4 < this._cols; e4 += this._optionsService.rawOptions.tabStopWidth) this.tabs[e4] = true;
          }
          prevStop(e4) {
            for (null == e4 && (e4 = this.x); !this.tabs[--e4] && e4 > 0; ) ;
            return e4 >= this._cols ? this._cols - 1 : e4 < 0 ? 0 : e4;
          }
          nextStop(e4) {
            for (null == e4 && (e4 = this.x); !this.tabs[++e4] && e4 < this._cols; ) ;
            return e4 >= this._cols ? this._cols - 1 : e4 < 0 ? 0 : e4;
          }
          clearMarkers(e4) {
            this._isClearing = true;
            for (let t4 = 0; t4 < this.markers.length; t4++) this.markers[t4].line === e4 && (this.markers[t4].dispose(), this.markers.splice(t4--, 1));
            this._isClearing = false;
          }
          clearAllMarkers() {
            this._isClearing = true;
            for (let e4 = 0; e4 < this.markers.length; e4++) this.markers[e4].dispose(), this.markers.splice(e4--, 1);
            this._isClearing = false;
          }
          addMarker(e4) {
            const t4 = new l2.Marker(e4);
            return this.markers.push(t4), t4.register(this.lines.onTrim((e5) => {
              t4.line -= e5, t4.line < 0 && t4.dispose();
            })), t4.register(this.lines.onInsert((e5) => {
              t4.line >= e5.index && (t4.line += e5.amount);
            })), t4.register(this.lines.onDelete((e5) => {
              t4.line >= e5.index && t4.line < e5.index + e5.amount && t4.dispose(), t4.line > e5.index && (t4.line -= e5.amount);
            })), t4.register(t4.onDispose(() => this._removeMarker(t4))), t4;
          }
          _removeMarker(e4) {
            this._isClearing || this.markers.splice(this.markers.indexOf(e4), 1);
          }
        };
      }, 437: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.BufferLine = t3.DEFAULT_ATTR_DATA = void 0;
        const s3 = i2(734), r4 = i2(511), n3 = i2(643), a = i2(482);
        t3.DEFAULT_ATTR_DATA = Object.freeze(new s3.AttributeData());
        let o2 = 0;
        class h {
          static {
            __name(this, "h");
          }
          constructor(e4, t4, i3 = false) {
            this.isWrapped = i3, this._combined = {}, this._extendedAttrs = {}, this._data = new Uint32Array(3 * e4);
            const s4 = t4 || r4.CellData.fromCharData([0, n3.NULL_CELL_CHAR, n3.NULL_CELL_WIDTH, n3.NULL_CELL_CODE]);
            for (let t5 = 0; t5 < e4; ++t5) this.setCell(t5, s4);
            this.length = e4;
          }
          get(e4) {
            const t4 = this._data[3 * e4 + 0], i3 = 2097151 & t4;
            return [this._data[3 * e4 + 1], 2097152 & t4 ? this._combined[e4] : i3 ? (0, a.stringFromCodePoint)(i3) : "", t4 >> 22, 2097152 & t4 ? this._combined[e4].charCodeAt(this._combined[e4].length - 1) : i3];
          }
          set(e4, t4) {
            this._data[3 * e4 + 1] = t4[n3.CHAR_DATA_ATTR_INDEX], t4[n3.CHAR_DATA_CHAR_INDEX].length > 1 ? (this._combined[e4] = t4[1], this._data[3 * e4 + 0] = 2097152 | e4 | t4[n3.CHAR_DATA_WIDTH_INDEX] << 22) : this._data[3 * e4 + 0] = t4[n3.CHAR_DATA_CHAR_INDEX].charCodeAt(0) | t4[n3.CHAR_DATA_WIDTH_INDEX] << 22;
          }
          getWidth(e4) {
            return this._data[3 * e4 + 0] >> 22;
          }
          hasWidth(e4) {
            return 12582912 & this._data[3 * e4 + 0];
          }
          getFg(e4) {
            return this._data[3 * e4 + 1];
          }
          getBg(e4) {
            return this._data[3 * e4 + 2];
          }
          hasContent(e4) {
            return 4194303 & this._data[3 * e4 + 0];
          }
          getCodePoint(e4) {
            const t4 = this._data[3 * e4 + 0];
            return 2097152 & t4 ? this._combined[e4].charCodeAt(this._combined[e4].length - 1) : 2097151 & t4;
          }
          isCombined(e4) {
            return 2097152 & this._data[3 * e4 + 0];
          }
          getString(e4) {
            const t4 = this._data[3 * e4 + 0];
            return 2097152 & t4 ? this._combined[e4] : 2097151 & t4 ? (0, a.stringFromCodePoint)(2097151 & t4) : "";
          }
          isProtected(e4) {
            return 536870912 & this._data[3 * e4 + 2];
          }
          loadCell(e4, t4) {
            return o2 = 3 * e4, t4.content = this._data[o2 + 0], t4.fg = this._data[o2 + 1], t4.bg = this._data[o2 + 2], 2097152 & t4.content && (t4.combinedData = this._combined[e4]), 268435456 & t4.bg && (t4.extended = this._extendedAttrs[e4]), t4;
          }
          setCell(e4, t4) {
            2097152 & t4.content && (this._combined[e4] = t4.combinedData), 268435456 & t4.bg && (this._extendedAttrs[e4] = t4.extended), this._data[3 * e4 + 0] = t4.content, this._data[3 * e4 + 1] = t4.fg, this._data[3 * e4 + 2] = t4.bg;
          }
          setCellFromCodepoint(e4, t4, i3, s4) {
            268435456 & s4.bg && (this._extendedAttrs[e4] = s4.extended), this._data[3 * e4 + 0] = t4 | i3 << 22, this._data[3 * e4 + 1] = s4.fg, this._data[3 * e4 + 2] = s4.bg;
          }
          addCodepointToCell(e4, t4, i3) {
            let s4 = this._data[3 * e4 + 0];
            2097152 & s4 ? this._combined[e4] += (0, a.stringFromCodePoint)(t4) : 2097151 & s4 ? (this._combined[e4] = (0, a.stringFromCodePoint)(2097151 & s4) + (0, a.stringFromCodePoint)(t4), s4 &= -2097152, s4 |= 2097152) : s4 = t4 | 1 << 22, i3 && (s4 &= -12582913, s4 |= i3 << 22), this._data[3 * e4 + 0] = s4;
          }
          insertCells(e4, t4, i3) {
            if ((e4 %= this.length) && 2 === this.getWidth(e4 - 1) && this.setCellFromCodepoint(e4 - 1, 0, 1, i3), t4 < this.length - e4) {
              const s4 = new r4.CellData();
              for (let i4 = this.length - e4 - t4 - 1; i4 >= 0; --i4) this.setCell(e4 + t4 + i4, this.loadCell(e4 + i4, s4));
              for (let s5 = 0; s5 < t4; ++s5) this.setCell(e4 + s5, i3);
            } else for (let t5 = e4; t5 < this.length; ++t5) this.setCell(t5, i3);
            2 === this.getWidth(this.length - 1) && this.setCellFromCodepoint(this.length - 1, 0, 1, i3);
          }
          deleteCells(e4, t4, i3) {
            if (e4 %= this.length, t4 < this.length - e4) {
              const s4 = new r4.CellData();
              for (let i4 = 0; i4 < this.length - e4 - t4; ++i4) this.setCell(e4 + i4, this.loadCell(e4 + t4 + i4, s4));
              for (let e5 = this.length - t4; e5 < this.length; ++e5) this.setCell(e5, i3);
            } else for (let t5 = e4; t5 < this.length; ++t5) this.setCell(t5, i3);
            e4 && 2 === this.getWidth(e4 - 1) && this.setCellFromCodepoint(e4 - 1, 0, 1, i3), 0 !== this.getWidth(e4) || this.hasContent(e4) || this.setCellFromCodepoint(e4, 0, 1, i3);
          }
          replaceCells(e4, t4, i3, s4 = false) {
            if (s4) for (e4 && 2 === this.getWidth(e4 - 1) && !this.isProtected(e4 - 1) && this.setCellFromCodepoint(e4 - 1, 0, 1, i3), t4 < this.length && 2 === this.getWidth(t4 - 1) && !this.isProtected(t4) && this.setCellFromCodepoint(t4, 0, 1, i3); e4 < t4 && e4 < this.length; ) this.isProtected(e4) || this.setCell(e4, i3), e4++;
            else for (e4 && 2 === this.getWidth(e4 - 1) && this.setCellFromCodepoint(e4 - 1, 0, 1, i3), t4 < this.length && 2 === this.getWidth(t4 - 1) && this.setCellFromCodepoint(t4, 0, 1, i3); e4 < t4 && e4 < this.length; ) this.setCell(e4++, i3);
          }
          resize(e4, t4) {
            if (e4 === this.length) return 4 * this._data.length * 2 < this._data.buffer.byteLength;
            const i3 = 3 * e4;
            if (e4 > this.length) {
              if (this._data.buffer.byteLength >= 4 * i3) this._data = new Uint32Array(this._data.buffer, 0, i3);
              else {
                const e5 = new Uint32Array(i3);
                e5.set(this._data), this._data = e5;
              }
              for (let i4 = this.length; i4 < e4; ++i4) this.setCell(i4, t4);
            } else {
              this._data = this._data.subarray(0, i3);
              const t5 = Object.keys(this._combined);
              for (let i4 = 0; i4 < t5.length; i4++) {
                const s5 = parseInt(t5[i4], 10);
                s5 >= e4 && delete this._combined[s5];
              }
              const s4 = Object.keys(this._extendedAttrs);
              for (let t6 = 0; t6 < s4.length; t6++) {
                const i4 = parseInt(s4[t6], 10);
                i4 >= e4 && delete this._extendedAttrs[i4];
              }
            }
            return this.length = e4, 4 * i3 * 2 < this._data.buffer.byteLength;
          }
          cleanupMemory() {
            if (4 * this._data.length * 2 < this._data.buffer.byteLength) {
              const e4 = new Uint32Array(this._data.length);
              return e4.set(this._data), this._data = e4, 1;
            }
            return 0;
          }
          fill(e4, t4 = false) {
            if (t4) for (let t5 = 0; t5 < this.length; ++t5) this.isProtected(t5) || this.setCell(t5, e4);
            else {
              this._combined = {}, this._extendedAttrs = {};
              for (let t5 = 0; t5 < this.length; ++t5) this.setCell(t5, e4);
            }
          }
          copyFrom(e4) {
            this.length !== e4.length ? this._data = new Uint32Array(e4._data) : this._data.set(e4._data), this.length = e4.length, this._combined = {};
            for (const t4 in e4._combined) this._combined[t4] = e4._combined[t4];
            this._extendedAttrs = {};
            for (const t4 in e4._extendedAttrs) this._extendedAttrs[t4] = e4._extendedAttrs[t4];
            this.isWrapped = e4.isWrapped;
          }
          clone() {
            const e4 = new h(0);
            e4._data = new Uint32Array(this._data), e4.length = this.length;
            for (const t4 in this._combined) e4._combined[t4] = this._combined[t4];
            for (const t4 in this._extendedAttrs) e4._extendedAttrs[t4] = this._extendedAttrs[t4];
            return e4.isWrapped = this.isWrapped, e4;
          }
          getTrimmedLength() {
            for (let e4 = this.length - 1; e4 >= 0; --e4) if (4194303 & this._data[3 * e4 + 0]) return e4 + (this._data[3 * e4 + 0] >> 22);
            return 0;
          }
          getNoBgTrimmedLength() {
            for (let e4 = this.length - 1; e4 >= 0; --e4) if (4194303 & this._data[3 * e4 + 0] || 50331648 & this._data[3 * e4 + 2]) return e4 + (this._data[3 * e4 + 0] >> 22);
            return 0;
          }
          copyCellsFrom(e4, t4, i3, s4, r5) {
            const n4 = e4._data;
            if (r5) for (let r6 = s4 - 1; r6 >= 0; r6--) {
              for (let e5 = 0; e5 < 3; e5++) this._data[3 * (i3 + r6) + e5] = n4[3 * (t4 + r6) + e5];
              268435456 & n4[3 * (t4 + r6) + 2] && (this._extendedAttrs[i3 + r6] = e4._extendedAttrs[t4 + r6]);
            }
            else for (let r6 = 0; r6 < s4; r6++) {
              for (let e5 = 0; e5 < 3; e5++) this._data[3 * (i3 + r6) + e5] = n4[3 * (t4 + r6) + e5];
              268435456 & n4[3 * (t4 + r6) + 2] && (this._extendedAttrs[i3 + r6] = e4._extendedAttrs[t4 + r6]);
            }
            const a2 = Object.keys(e4._combined);
            for (let s5 = 0; s5 < a2.length; s5++) {
              const r6 = parseInt(a2[s5], 10);
              r6 >= t4 && (this._combined[r6 - t4 + i3] = e4._combined[r6]);
            }
          }
          translateToString(e4, t4, i3, s4) {
            t4 = t4 ?? 0, i3 = i3 ?? this.length, e4 && (i3 = Math.min(i3, this.getTrimmedLength())), s4 && (s4.length = 0);
            let r5 = "";
            for (; t4 < i3; ) {
              const e5 = this._data[3 * t4 + 0], i4 = 2097151 & e5, o3 = 2097152 & e5 ? this._combined[t4] : i4 ? (0, a.stringFromCodePoint)(i4) : n3.WHITESPACE_CELL_CHAR;
              if (r5 += o3, s4) for (let e6 = 0; e6 < o3.length; ++e6) s4.push(t4);
              t4 += e5 >> 22 || 1;
            }
            return s4 && s4.push(t4), r5;
          }
        }
        t3.BufferLine = h;
      }, 634: (e3, t3) => {
        function i2(e4, t4, i3) {
          if (t4 === e4.length - 1) return e4[t4].getTrimmedLength();
          const s3 = !e4[t4].hasContent(i3 - 1) && 1 === e4[t4].getWidth(i3 - 1), r4 = 2 === e4[t4 + 1].getWidth(0);
          return s3 && r4 ? i3 - 1 : i3;
        }
        __name(i2, "i");
        Object.defineProperty(t3, "__esModule", { value: true }), t3.getWrappedLineTrimmedLength = t3.reflowSmallerGetNewLineLengths = t3.reflowLargerApplyNewLayout = t3.reflowLargerCreateNewLayout = t3.reflowLargerGetLinesToRemove = void 0, t3.reflowLargerGetLinesToRemove = function(e4, t4, s3, r4, n3) {
          const a = [];
          for (let o2 = 0; o2 < e4.length - 1; o2++) {
            let h = o2, c3 = e4.get(++h);
            if (!c3.isWrapped) continue;
            const l2 = [e4.get(o2)];
            for (; h < e4.length && c3.isWrapped; ) l2.push(c3), c3 = e4.get(++h);
            if (r4 >= o2 && r4 < h) {
              o2 += l2.length - 1;
              continue;
            }
            let _ = 0, d = i2(l2, _, t4), f = 1, u = 0;
            for (; f < l2.length; ) {
              const e5 = i2(l2, f, t4), r5 = e5 - u, a2 = s3 - d, o3 = Math.min(r5, a2);
              l2[_].copyCellsFrom(l2[f], u, d, o3, false), d += o3, d === s3 && (_++, d = 0), u += o3, u === e5 && (f++, u = 0), 0 === d && 0 !== _ && 2 === l2[_ - 1].getWidth(s3 - 1) && (l2[_].copyCellsFrom(l2[_ - 1], s3 - 1, d++, 1, false), l2[_ - 1].setCell(s3 - 1, n3));
            }
            l2[_].replaceCells(d, s3, n3);
            let p = 0;
            for (let e5 = l2.length - 1; e5 > 0 && (e5 > _ || 0 === l2[e5].getTrimmedLength()); e5--) p++;
            p > 0 && (a.push(o2 + l2.length - p), a.push(p)), o2 += l2.length - 1;
          }
          return a;
        }, t3.reflowLargerCreateNewLayout = function(e4, t4) {
          const i3 = [];
          let s3 = 0, r4 = t4[s3], n3 = 0;
          for (let a = 0; a < e4.length; a++) if (r4 === a) {
            const i4 = t4[++s3];
            e4.onDeleteEmitter.fire({ index: a - n3, amount: i4 }), a += i4 - 1, n3 += i4, r4 = t4[++s3];
          } else i3.push(a);
          return { layout: i3, countRemoved: n3 };
        }, t3.reflowLargerApplyNewLayout = function(e4, t4) {
          const i3 = [];
          for (let s3 = 0; s3 < t4.length; s3++) i3.push(e4.get(t4[s3]));
          for (let t5 = 0; t5 < i3.length; t5++) e4.set(t5, i3[t5]);
          e4.length = t4.length;
        }, t3.reflowSmallerGetNewLineLengths = function(e4, t4, s3) {
          const r4 = [], n3 = e4.map((s4, r5) => i2(e4, r5, t4)).reduce((e5, t5) => e5 + t5);
          let a = 0, o2 = 0, h = 0;
          for (; h < n3; ) {
            if (n3 - h < s3) {
              r4.push(n3 - h);
              break;
            }
            a += s3;
            const c3 = i2(e4, o2, t4);
            a > c3 && (a -= c3, o2++);
            const l2 = 2 === e4[o2].getWidth(a - 1);
            l2 && a--;
            const _ = l2 ? s3 - 1 : s3;
            r4.push(_), h += _;
          }
          return r4;
        }, t3.getWrappedLineTrimmedLength = i2;
      }, 295: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.BufferSet = void 0;
        const s3 = i2(460), r4 = i2(844), n3 = i2(92);
        class a extends r4.Disposable {
          static {
            __name(this, "a");
          }
          constructor(e4, t4) {
            super(), this._optionsService = e4, this._bufferService = t4, this._onBufferActivate = this.register(new s3.EventEmitter()), this.onBufferActivate = this._onBufferActivate.event, this.reset(), this.register(this._optionsService.onSpecificOptionChange("scrollback", () => this.resize(this._bufferService.cols, this._bufferService.rows))), this.register(this._optionsService.onSpecificOptionChange("tabStopWidth", () => this.setupTabStops()));
          }
          reset() {
            this._normal = new n3.Buffer(true, this._optionsService, this._bufferService), this._normal.fillViewportRows(), this._alt = new n3.Buffer(false, this._optionsService, this._bufferService), this._activeBuffer = this._normal, this._onBufferActivate.fire({ activeBuffer: this._normal, inactiveBuffer: this._alt }), this.setupTabStops();
          }
          get alt() {
            return this._alt;
          }
          get active() {
            return this._activeBuffer;
          }
          get normal() {
            return this._normal;
          }
          activateNormalBuffer() {
            this._activeBuffer !== this._normal && (this._normal.x = this._alt.x, this._normal.y = this._alt.y, this._alt.clearAllMarkers(), this._alt.clear(), this._activeBuffer = this._normal, this._onBufferActivate.fire({ activeBuffer: this._normal, inactiveBuffer: this._alt }));
          }
          activateAltBuffer(e4) {
            this._activeBuffer !== this._alt && (this._alt.fillViewportRows(e4), this._alt.x = this._normal.x, this._alt.y = this._normal.y, this._activeBuffer = this._alt, this._onBufferActivate.fire({ activeBuffer: this._alt, inactiveBuffer: this._normal }));
          }
          resize(e4, t4) {
            this._normal.resize(e4, t4), this._alt.resize(e4, t4), this.setupTabStops(e4);
          }
          setupTabStops(e4) {
            this._normal.setupTabStops(e4), this._alt.setupTabStops(e4);
          }
        }
        t3.BufferSet = a;
      }, 511: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.CellData = void 0;
        const s3 = i2(482), r4 = i2(643), n3 = i2(734);
        class a extends n3.AttributeData {
          static {
            __name(this, "a");
          }
          constructor() {
            super(...arguments), this.content = 0, this.fg = 0, this.bg = 0, this.extended = new n3.ExtendedAttrs(), this.combinedData = "";
          }
          static fromCharData(e4) {
            const t4 = new a();
            return t4.setFromCharData(e4), t4;
          }
          isCombined() {
            return 2097152 & this.content;
          }
          getWidth() {
            return this.content >> 22;
          }
          getChars() {
            return 2097152 & this.content ? this.combinedData : 2097151 & this.content ? (0, s3.stringFromCodePoint)(2097151 & this.content) : "";
          }
          getCode() {
            return this.isCombined() ? this.combinedData.charCodeAt(this.combinedData.length - 1) : 2097151 & this.content;
          }
          setFromCharData(e4) {
            this.fg = e4[r4.CHAR_DATA_ATTR_INDEX], this.bg = 0;
            let t4 = false;
            if (e4[r4.CHAR_DATA_CHAR_INDEX].length > 2) t4 = true;
            else if (2 === e4[r4.CHAR_DATA_CHAR_INDEX].length) {
              const i3 = e4[r4.CHAR_DATA_CHAR_INDEX].charCodeAt(0);
              if (55296 <= i3 && i3 <= 56319) {
                const s4 = e4[r4.CHAR_DATA_CHAR_INDEX].charCodeAt(1);
                56320 <= s4 && s4 <= 57343 ? this.content = 1024 * (i3 - 55296) + s4 - 56320 + 65536 | e4[r4.CHAR_DATA_WIDTH_INDEX] << 22 : t4 = true;
              } else t4 = true;
            } else this.content = e4[r4.CHAR_DATA_CHAR_INDEX].charCodeAt(0) | e4[r4.CHAR_DATA_WIDTH_INDEX] << 22;
            t4 && (this.combinedData = e4[r4.CHAR_DATA_CHAR_INDEX], this.content = 2097152 | e4[r4.CHAR_DATA_WIDTH_INDEX] << 22);
          }
          getAsCharData() {
            return [this.fg, this.getChars(), this.getWidth(), this.getCode()];
          }
        }
        t3.CellData = a;
      }, 643: (e3, t3) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.WHITESPACE_CELL_CODE = t3.WHITESPACE_CELL_WIDTH = t3.WHITESPACE_CELL_CHAR = t3.NULL_CELL_CODE = t3.NULL_CELL_WIDTH = t3.NULL_CELL_CHAR = t3.CHAR_DATA_CODE_INDEX = t3.CHAR_DATA_WIDTH_INDEX = t3.CHAR_DATA_CHAR_INDEX = t3.CHAR_DATA_ATTR_INDEX = t3.DEFAULT_EXT = t3.DEFAULT_ATTR = t3.DEFAULT_COLOR = void 0, t3.DEFAULT_COLOR = 0, t3.DEFAULT_ATTR = 256 | t3.DEFAULT_COLOR << 9, t3.DEFAULT_EXT = 0, t3.CHAR_DATA_ATTR_INDEX = 0, t3.CHAR_DATA_CHAR_INDEX = 1, t3.CHAR_DATA_WIDTH_INDEX = 2, t3.CHAR_DATA_CODE_INDEX = 3, t3.NULL_CELL_CHAR = "", t3.NULL_CELL_WIDTH = 1, t3.NULL_CELL_CODE = 0, t3.WHITESPACE_CELL_CHAR = " ", t3.WHITESPACE_CELL_WIDTH = 1, t3.WHITESPACE_CELL_CODE = 32;
      }, 863: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.Marker = void 0;
        const s3 = i2(460), r4 = i2(844);
        class n3 {
          static {
            __name(this, "n");
          }
          get id() {
            return this._id;
          }
          constructor(e4) {
            this.line = e4, this.isDisposed = false, this._disposables = [], this._id = n3._nextId++, this._onDispose = this.register(new s3.EventEmitter()), this.onDispose = this._onDispose.event;
          }
          dispose() {
            this.isDisposed || (this.isDisposed = true, this.line = -1, this._onDispose.fire(), (0, r4.disposeArray)(this._disposables), this._disposables.length = 0);
          }
          register(e4) {
            return this._disposables.push(e4), e4;
          }
        }
        t3.Marker = n3, n3._nextId = 1;
      }, 116: (e3, t3) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.DEFAULT_CHARSET = t3.CHARSETS = void 0, t3.CHARSETS = {}, t3.DEFAULT_CHARSET = t3.CHARSETS.B, t3.CHARSETS[0] = { "`": "\u25C6", a: "\u2592", b: "\u2409", c: "\u240C", d: "\u240D", e: "\u240A", f: "\xB0", g: "\xB1", h: "\u2424", i: "\u240B", j: "\u2518", k: "\u2510", l: "\u250C", m: "\u2514", n: "\u253C", o: "\u23BA", p: "\u23BB", q: "\u2500", r: "\u23BC", s: "\u23BD", t: "\u251C", u: "\u2524", v: "\u2534", w: "\u252C", x: "\u2502", y: "\u2264", z: "\u2265", "{": "\u03C0", "|": "\u2260", "}": "\xA3", "~": "\xB7" }, t3.CHARSETS.A = { "#": "\xA3" }, t3.CHARSETS.B = void 0, t3.CHARSETS[4] = { "#": "\xA3", "@": "\xBE", "[": "ij", "\\": "\xBD", "]": "|", "{": "\xA8", "|": "f", "}": "\xBC", "~": "\xB4" }, t3.CHARSETS.C = t3.CHARSETS[5] = { "[": "\xC4", "\\": "\xD6", "]": "\xC5", "^": "\xDC", "`": "\xE9", "{": "\xE4", "|": "\xF6", "}": "\xE5", "~": "\xFC" }, t3.CHARSETS.R = { "#": "\xA3", "@": "\xE0", "[": "\xB0", "\\": "\xE7", "]": "\xA7", "{": "\xE9", "|": "\xF9", "}": "\xE8", "~": "\xA8" }, t3.CHARSETS.Q = { "@": "\xE0", "[": "\xE2", "\\": "\xE7", "]": "\xEA", "^": "\xEE", "`": "\xF4", "{": "\xE9", "|": "\xF9", "}": "\xE8", "~": "\xFB" }, t3.CHARSETS.K = { "@": "\xA7", "[": "\xC4", "\\": "\xD6", "]": "\xDC", "{": "\xE4", "|": "\xF6", "}": "\xFC", "~": "\xDF" }, t3.CHARSETS.Y = { "#": "\xA3", "@": "\xA7", "[": "\xB0", "\\": "\xE7", "]": "\xE9", "`": "\xF9", "{": "\xE0", "|": "\xF2", "}": "\xE8", "~": "\xEC" }, t3.CHARSETS.E = t3.CHARSETS[6] = { "@": "\xC4", "[": "\xC6", "\\": "\xD8", "]": "\xC5", "^": "\xDC", "`": "\xE4", "{": "\xE6", "|": "\xF8", "}": "\xE5", "~": "\xFC" }, t3.CHARSETS.Z = { "#": "\xA3", "@": "\xA7", "[": "\xA1", "\\": "\xD1", "]": "\xBF", "{": "\xB0", "|": "\xF1", "}": "\xE7" }, t3.CHARSETS.H = t3.CHARSETS[7] = { "@": "\xC9", "[": "\xC4", "\\": "\xD6", "]": "\xC5", "^": "\xDC", "`": "\xE9", "{": "\xE4", "|": "\xF6", "}": "\xE5", "~": "\xFC" }, t3.CHARSETS["="] = { "#": "\xF9", "@": "\xE0", "[": "\xE9", "\\": "\xE7", "]": "\xEA", "^": "\xEE", _: "\xE8", "`": "\xF4", "{": "\xE4", "|": "\xF6", "}": "\xFC", "~": "\xFB" };
      }, 584: (e3, t3) => {
        var i2, s3, r4;
        Object.defineProperty(t3, "__esModule", { value: true }), t3.C1_ESCAPED = t3.C1 = t3.C0 = void 0, function(e4) {
          e4.NUL = "\0", e4.SOH = "", e4.STX = "", e4.ETX = "", e4.EOT = "", e4.ENQ = "", e4.ACK = "", e4.BEL = "\x07", e4.BS = "\b", e4.HT = "	", e4.LF = "\n", e4.VT = "\v", e4.FF = "\f", e4.CR = "\r", e4.SO = "", e4.SI = "", e4.DLE = "", e4.DC1 = "", e4.DC2 = "", e4.DC3 = "", e4.DC4 = "", e4.NAK = "", e4.SYN = "", e4.ETB = "", e4.CAN = "", e4.EM = "", e4.SUB = "", e4.ESC = "\x1B", e4.FS = "", e4.GS = "", e4.RS = "", e4.US = "", e4.SP = " ", e4.DEL = "\x7F";
        }(i2 || (t3.C0 = i2 = {})), function(e4) {
          e4.PAD = "\x80", e4.HOP = "\x81", e4.BPH = "\x82", e4.NBH = "\x83", e4.IND = "\x84", e4.NEL = "\x85", e4.SSA = "\x86", e4.ESA = "\x87", e4.HTS = "\x88", e4.HTJ = "\x89", e4.VTS = "\x8A", e4.PLD = "\x8B", e4.PLU = "\x8C", e4.RI = "\x8D", e4.SS2 = "\x8E", e4.SS3 = "\x8F", e4.DCS = "\x90", e4.PU1 = "\x91", e4.PU2 = "\x92", e4.STS = "\x93", e4.CCH = "\x94", e4.MW = "\x95", e4.SPA = "\x96", e4.EPA = "\x97", e4.SOS = "\x98", e4.SGCI = "\x99", e4.SCI = "\x9A", e4.CSI = "\x9B", e4.ST = "\x9C", e4.OSC = "\x9D", e4.PM = "\x9E", e4.APC = "\x9F";
        }(s3 || (t3.C1 = s3 = {})), function(e4) {
          e4.ST = `${i2.ESC}\\`;
        }(r4 || (t3.C1_ESCAPED = r4 = {}));
      }, 482: (e3, t3) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.Utf8ToUtf32 = t3.StringToUtf32 = t3.utf32ToString = t3.stringFromCodePoint = void 0, t3.stringFromCodePoint = function(e4) {
          return e4 > 65535 ? (e4 -= 65536, String.fromCharCode(55296 + (e4 >> 10)) + String.fromCharCode(e4 % 1024 + 56320)) : String.fromCharCode(e4);
        }, t3.utf32ToString = function(e4, t4 = 0, i2 = e4.length) {
          let s3 = "";
          for (let r4 = t4; r4 < i2; ++r4) {
            let t5 = e4[r4];
            t5 > 65535 ? (t5 -= 65536, s3 += String.fromCharCode(55296 + (t5 >> 10)) + String.fromCharCode(t5 % 1024 + 56320)) : s3 += String.fromCharCode(t5);
          }
          return s3;
        }, t3.StringToUtf32 = class {
          constructor() {
            this._interim = 0;
          }
          clear() {
            this._interim = 0;
          }
          decode(e4, t4) {
            const i2 = e4.length;
            if (!i2) return 0;
            let s3 = 0, r4 = 0;
            if (this._interim) {
              const i3 = e4.charCodeAt(r4++);
              56320 <= i3 && i3 <= 57343 ? t4[s3++] = 1024 * (this._interim - 55296) + i3 - 56320 + 65536 : (t4[s3++] = this._interim, t4[s3++] = i3), this._interim = 0;
            }
            for (let n3 = r4; n3 < i2; ++n3) {
              const r5 = e4.charCodeAt(n3);
              if (55296 <= r5 && r5 <= 56319) {
                if (++n3 >= i2) return this._interim = r5, s3;
                const a = e4.charCodeAt(n3);
                56320 <= a && a <= 57343 ? t4[s3++] = 1024 * (r5 - 55296) + a - 56320 + 65536 : (t4[s3++] = r5, t4[s3++] = a);
              } else 65279 !== r5 && (t4[s3++] = r5);
            }
            return s3;
          }
        }, t3.Utf8ToUtf32 = class {
          constructor() {
            this.interim = new Uint8Array(3);
          }
          clear() {
            this.interim.fill(0);
          }
          decode(e4, t4) {
            const i2 = e4.length;
            if (!i2) return 0;
            let s3, r4, n3, a, o2 = 0, h = 0, c3 = 0;
            if (this.interim[0]) {
              let s4 = false, r5 = this.interim[0];
              r5 &= 192 == (224 & r5) ? 31 : 224 == (240 & r5) ? 15 : 7;
              let n4, a2 = 0;
              for (; (n4 = 63 & this.interim[++a2]) && a2 < 4; ) r5 <<= 6, r5 |= n4;
              const h2 = 192 == (224 & this.interim[0]) ? 2 : 224 == (240 & this.interim[0]) ? 3 : 4, l3 = h2 - a2;
              for (; c3 < l3; ) {
                if (c3 >= i2) return 0;
                if (n4 = e4[c3++], 128 != (192 & n4)) {
                  c3--, s4 = true;
                  break;
                }
                this.interim[a2++] = n4, r5 <<= 6, r5 |= 63 & n4;
              }
              s4 || (2 === h2 ? r5 < 128 ? c3-- : t4[o2++] = r5 : 3 === h2 ? r5 < 2048 || r5 >= 55296 && r5 <= 57343 || 65279 === r5 || (t4[o2++] = r5) : r5 < 65536 || r5 > 1114111 || (t4[o2++] = r5)), this.interim.fill(0);
            }
            const l2 = i2 - 4;
            let _ = c3;
            for (; _ < i2; ) {
              for (; !(!(_ < l2) || 128 & (s3 = e4[_]) || 128 & (r4 = e4[_ + 1]) || 128 & (n3 = e4[_ + 2]) || 128 & (a = e4[_ + 3])); ) t4[o2++] = s3, t4[o2++] = r4, t4[o2++] = n3, t4[o2++] = a, _ += 4;
              if (s3 = e4[_++], s3 < 128) t4[o2++] = s3;
              else if (192 == (224 & s3)) {
                if (_ >= i2) return this.interim[0] = s3, o2;
                if (r4 = e4[_++], 128 != (192 & r4)) {
                  _--;
                  continue;
                }
                if (h = (31 & s3) << 6 | 63 & r4, h < 128) {
                  _--;
                  continue;
                }
                t4[o2++] = h;
              } else if (224 == (240 & s3)) {
                if (_ >= i2) return this.interim[0] = s3, o2;
                if (r4 = e4[_++], 128 != (192 & r4)) {
                  _--;
                  continue;
                }
                if (_ >= i2) return this.interim[0] = s3, this.interim[1] = r4, o2;
                if (n3 = e4[_++], 128 != (192 & n3)) {
                  _--;
                  continue;
                }
                if (h = (15 & s3) << 12 | (63 & r4) << 6 | 63 & n3, h < 2048 || h >= 55296 && h <= 57343 || 65279 === h) continue;
                t4[o2++] = h;
              } else if (240 == (248 & s3)) {
                if (_ >= i2) return this.interim[0] = s3, o2;
                if (r4 = e4[_++], 128 != (192 & r4)) {
                  _--;
                  continue;
                }
                if (_ >= i2) return this.interim[0] = s3, this.interim[1] = r4, o2;
                if (n3 = e4[_++], 128 != (192 & n3)) {
                  _--;
                  continue;
                }
                if (_ >= i2) return this.interim[0] = s3, this.interim[1] = r4, this.interim[2] = n3, o2;
                if (a = e4[_++], 128 != (192 & a)) {
                  _--;
                  continue;
                }
                if (h = (7 & s3) << 18 | (63 & r4) << 12 | (63 & n3) << 6 | 63 & a, h < 65536 || h > 1114111) continue;
                t4[o2++] = h;
              }
            }
            return o2;
          }
        };
      }, 225: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.UnicodeV6 = void 0;
        const s3 = i2(480), r4 = [[768, 879], [1155, 1158], [1160, 1161], [1425, 1469], [1471, 1471], [1473, 1474], [1476, 1477], [1479, 1479], [1536, 1539], [1552, 1557], [1611, 1630], [1648, 1648], [1750, 1764], [1767, 1768], [1770, 1773], [1807, 1807], [1809, 1809], [1840, 1866], [1958, 1968], [2027, 2035], [2305, 2306], [2364, 2364], [2369, 2376], [2381, 2381], [2385, 2388], [2402, 2403], [2433, 2433], [2492, 2492], [2497, 2500], [2509, 2509], [2530, 2531], [2561, 2562], [2620, 2620], [2625, 2626], [2631, 2632], [2635, 2637], [2672, 2673], [2689, 2690], [2748, 2748], [2753, 2757], [2759, 2760], [2765, 2765], [2786, 2787], [2817, 2817], [2876, 2876], [2879, 2879], [2881, 2883], [2893, 2893], [2902, 2902], [2946, 2946], [3008, 3008], [3021, 3021], [3134, 3136], [3142, 3144], [3146, 3149], [3157, 3158], [3260, 3260], [3263, 3263], [3270, 3270], [3276, 3277], [3298, 3299], [3393, 3395], [3405, 3405], [3530, 3530], [3538, 3540], [3542, 3542], [3633, 3633], [3636, 3642], [3655, 3662], [3761, 3761], [3764, 3769], [3771, 3772], [3784, 3789], [3864, 3865], [3893, 3893], [3895, 3895], [3897, 3897], [3953, 3966], [3968, 3972], [3974, 3975], [3984, 3991], [3993, 4028], [4038, 4038], [4141, 4144], [4146, 4146], [4150, 4151], [4153, 4153], [4184, 4185], [4448, 4607], [4959, 4959], [5906, 5908], [5938, 5940], [5970, 5971], [6002, 6003], [6068, 6069], [6071, 6077], [6086, 6086], [6089, 6099], [6109, 6109], [6155, 6157], [6313, 6313], [6432, 6434], [6439, 6440], [6450, 6450], [6457, 6459], [6679, 6680], [6912, 6915], [6964, 6964], [6966, 6970], [6972, 6972], [6978, 6978], [7019, 7027], [7616, 7626], [7678, 7679], [8203, 8207], [8234, 8238], [8288, 8291], [8298, 8303], [8400, 8431], [12330, 12335], [12441, 12442], [43014, 43014], [43019, 43019], [43045, 43046], [64286, 64286], [65024, 65039], [65056, 65059], [65279, 65279], [65529, 65531]], n3 = [[68097, 68099], [68101, 68102], [68108, 68111], [68152, 68154], [68159, 68159], [119143, 119145], [119155, 119170], [119173, 119179], [119210, 119213], [119362, 119364], [917505, 917505], [917536, 917631], [917760, 917999]];
        let a;
        t3.UnicodeV6 = class {
          constructor() {
            if (this.version = "6", !a) {
              a = new Uint8Array(65536), a.fill(1), a[0] = 0, a.fill(0, 1, 32), a.fill(0, 127, 160), a.fill(2, 4352, 4448), a[9001] = 2, a[9002] = 2, a.fill(2, 11904, 42192), a[12351] = 1, a.fill(2, 44032, 55204), a.fill(2, 63744, 64256), a.fill(2, 65040, 65050), a.fill(2, 65072, 65136), a.fill(2, 65280, 65377), a.fill(2, 65504, 65511);
              for (let e4 = 0; e4 < r4.length; ++e4) a.fill(0, r4[e4][0], r4[e4][1] + 1);
            }
          }
          wcwidth(e4) {
            return e4 < 32 ? 0 : e4 < 127 ? 1 : e4 < 65536 ? a[e4] : function(e5, t4) {
              let i3, s4 = 0, r5 = t4.length - 1;
              if (e5 < t4[0][0] || e5 > t4[r5][1]) return false;
              for (; r5 >= s4; ) if (i3 = s4 + r5 >> 1, e5 > t4[i3][1]) s4 = i3 + 1;
              else {
                if (!(e5 < t4[i3][0])) return true;
                r5 = i3 - 1;
              }
              return false;
            }(e4, n3) ? 0 : e4 >= 131072 && e4 <= 196605 || e4 >= 196608 && e4 <= 262141 ? 2 : 1;
          }
          charProperties(e4, t4) {
            let i3 = this.wcwidth(e4), r5 = 0 === i3 && 0 !== t4;
            if (r5) {
              const e5 = s3.UnicodeService.extractWidth(t4);
              0 === e5 ? r5 = false : e5 > i3 && (i3 = e5);
            }
            return s3.UnicodeService.createPropertyValue(0, i3, r5);
          }
        };
      }, 981: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.WriteBuffer = void 0;
        const s3 = i2(460), r4 = i2(844);
        class n3 extends r4.Disposable {
          static {
            __name(this, "n");
          }
          constructor(e4) {
            super(), this._action = e4, this._writeBuffer = [], this._callbacks = [], this._pendingData = 0, this._bufferOffset = 0, this._isSyncWriting = false, this._syncCalls = 0, this._didUserInput = false, this._onWriteParsed = this.register(new s3.EventEmitter()), this.onWriteParsed = this._onWriteParsed.event;
          }
          handleUserInput() {
            this._didUserInput = true;
          }
          writeSync(e4, t4) {
            if (void 0 !== t4 && this._syncCalls > t4) return void (this._syncCalls = 0);
            if (this._pendingData += e4.length, this._writeBuffer.push(e4), this._callbacks.push(void 0), this._syncCalls++, this._isSyncWriting) return;
            let i3;
            for (this._isSyncWriting = true; i3 = this._writeBuffer.shift(); ) {
              this._action(i3);
              const e5 = this._callbacks.shift();
              e5 && e5();
            }
            this._pendingData = 0, this._bufferOffset = 2147483647, this._isSyncWriting = false, this._syncCalls = 0;
          }
          write(e4, t4) {
            if (this._pendingData > 5e7) throw new Error("write data discarded, use flow control to avoid losing data");
            if (!this._writeBuffer.length) {
              if (this._bufferOffset = 0, this._didUserInput) return this._didUserInput = false, this._pendingData += e4.length, this._writeBuffer.push(e4), this._callbacks.push(t4), void this._innerWrite();
              setTimeout(() => this._innerWrite());
            }
            this._pendingData += e4.length, this._writeBuffer.push(e4), this._callbacks.push(t4);
          }
          _innerWrite(e4 = 0, t4 = true) {
            const i3 = e4 || Date.now();
            for (; this._writeBuffer.length > this._bufferOffset; ) {
              const e5 = this._writeBuffer[this._bufferOffset], s4 = this._action(e5, t4);
              if (s4) {
                const e6 = /* @__PURE__ */ __name((e7) => Date.now() - i3 >= 12 ? setTimeout(() => this._innerWrite(0, e7)) : this._innerWrite(i3, e7), "e");
                return void s4.catch((e7) => (queueMicrotask(() => {
                  throw e7;
                }), Promise.resolve(false))).then(e6);
              }
              const r5 = this._callbacks[this._bufferOffset];
              if (r5 && r5(), this._bufferOffset++, this._pendingData -= e5.length, Date.now() - i3 >= 12) break;
            }
            this._writeBuffer.length > this._bufferOffset ? (this._bufferOffset > 50 && (this._writeBuffer = this._writeBuffer.slice(this._bufferOffset), this._callbacks = this._callbacks.slice(this._bufferOffset), this._bufferOffset = 0), setTimeout(() => this._innerWrite())) : (this._writeBuffer.length = 0, this._callbacks.length = 0, this._pendingData = 0, this._bufferOffset = 0), this._onWriteParsed.fire();
          }
        }
        t3.WriteBuffer = n3;
      }, 941: (e3, t3) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.toRgbString = t3.parseColor = void 0;
        const i2 = /^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/, s3 = /^[\da-f]+$/;
        function r4(e4, t4) {
          const i3 = e4.toString(16), s4 = i3.length < 2 ? "0" + i3 : i3;
          switch (t4) {
            case 4:
              return i3[0];
            case 8:
              return s4;
            case 12:
              return (s4 + s4).slice(0, 3);
            default:
              return s4 + s4;
          }
        }
        __name(r4, "r");
        t3.parseColor = function(e4) {
          if (!e4) return;
          let t4 = e4.toLowerCase();
          if (0 === t4.indexOf("rgb:")) {
            t4 = t4.slice(4);
            const e5 = i2.exec(t4);
            if (e5) {
              const t5 = e5[1] ? 15 : e5[4] ? 255 : e5[7] ? 4095 : 65535;
              return [Math.round(parseInt(e5[1] || e5[4] || e5[7] || e5[10], 16) / t5 * 255), Math.round(parseInt(e5[2] || e5[5] || e5[8] || e5[11], 16) / t5 * 255), Math.round(parseInt(e5[3] || e5[6] || e5[9] || e5[12], 16) / t5 * 255)];
            }
          } else if (0 === t4.indexOf("#") && (t4 = t4.slice(1), s3.exec(t4) && [3, 6, 9, 12].includes(t4.length))) {
            const e5 = t4.length / 3, i3 = [0, 0, 0];
            for (let s4 = 0; s4 < 3; ++s4) {
              const r5 = parseInt(t4.slice(e5 * s4, e5 * s4 + e5), 16);
              i3[s4] = 1 === e5 ? r5 << 4 : 2 === e5 ? r5 : 3 === e5 ? r5 >> 4 : r5 >> 8;
            }
            return i3;
          }
        }, t3.toRgbString = function(e4, t4 = 16) {
          const [i3, s4, n3] = e4;
          return `rgb:${r4(i3, t4)}/${r4(s4, t4)}/${r4(n3, t4)}`;
        };
      }, 770: (e3, t3) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.PAYLOAD_LIMIT = void 0, t3.PAYLOAD_LIMIT = 1e7;
      }, 351: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.DcsHandler = t3.DcsParser = void 0;
        const s3 = i2(482), r4 = i2(742), n3 = i2(770), a = [];
        t3.DcsParser = class {
          constructor() {
            this._handlers = /* @__PURE__ */ Object.create(null), this._active = a, this._ident = 0, this._handlerFb = () => {
            }, this._stack = { paused: false, loopPosition: 0, fallThrough: false };
          }
          dispose() {
            this._handlers = /* @__PURE__ */ Object.create(null), this._handlerFb = () => {
            }, this._active = a;
          }
          registerHandler(e4, t4) {
            void 0 === this._handlers[e4] && (this._handlers[e4] = []);
            const i3 = this._handlers[e4];
            return i3.push(t4), { dispose: /* @__PURE__ */ __name(() => {
              const e5 = i3.indexOf(t4);
              -1 !== e5 && i3.splice(e5, 1);
            }, "dispose") };
          }
          clearHandler(e4) {
            this._handlers[e4] && delete this._handlers[e4];
          }
          setHandlerFallback(e4) {
            this._handlerFb = e4;
          }
          reset() {
            if (this._active.length) for (let e4 = this._stack.paused ? this._stack.loopPosition - 1 : this._active.length - 1; e4 >= 0; --e4) this._active[e4].unhook(false);
            this._stack.paused = false, this._active = a, this._ident = 0;
          }
          hook(e4, t4) {
            if (this.reset(), this._ident = e4, this._active = this._handlers[e4] || a, this._active.length) for (let e5 = this._active.length - 1; e5 >= 0; e5--) this._active[e5].hook(t4);
            else this._handlerFb(this._ident, "HOOK", t4);
          }
          put(e4, t4, i3) {
            if (this._active.length) for (let s4 = this._active.length - 1; s4 >= 0; s4--) this._active[s4].put(e4, t4, i3);
            else this._handlerFb(this._ident, "PUT", (0, s3.utf32ToString)(e4, t4, i3));
          }
          unhook(e4, t4 = true) {
            if (this._active.length) {
              let i3 = false, s4 = this._active.length - 1, r5 = false;
              if (this._stack.paused && (s4 = this._stack.loopPosition - 1, i3 = t4, r5 = this._stack.fallThrough, this._stack.paused = false), !r5 && false === i3) {
                for (; s4 >= 0 && (i3 = this._active[s4].unhook(e4), true !== i3); s4--) if (i3 instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = s4, this._stack.fallThrough = false, i3;
                s4--;
              }
              for (; s4 >= 0; s4--) if (i3 = this._active[s4].unhook(false), i3 instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = s4, this._stack.fallThrough = true, i3;
            } else this._handlerFb(this._ident, "UNHOOK", e4);
            this._active = a, this._ident = 0;
          }
        };
        const o2 = new r4.Params();
        o2.addParam(0), t3.DcsHandler = class {
          constructor(e4) {
            this._handler = e4, this._data = "", this._params = o2, this._hitLimit = false;
          }
          hook(e4) {
            this._params = e4.length > 1 || e4.params[0] ? e4.clone() : o2, this._data = "", this._hitLimit = false;
          }
          put(e4, t4, i3) {
            this._hitLimit || (this._data += (0, s3.utf32ToString)(e4, t4, i3), this._data.length > n3.PAYLOAD_LIMIT && (this._data = "", this._hitLimit = true));
          }
          unhook(e4) {
            let t4 = false;
            if (this._hitLimit) t4 = false;
            else if (e4 && (t4 = this._handler(this._data, this._params), t4 instanceof Promise)) return t4.then((e5) => (this._params = o2, this._data = "", this._hitLimit = false, e5));
            return this._params = o2, this._data = "", this._hitLimit = false, t4;
          }
        };
      }, 15: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.EscapeSequenceParser = t3.VT500_TRANSITION_TABLE = t3.TransitionTable = void 0;
        const s3 = i2(844), r4 = i2(742), n3 = i2(242), a = i2(351);
        class o2 {
          static {
            __name(this, "o");
          }
          constructor(e4) {
            this.table = new Uint8Array(e4);
          }
          setDefault(e4, t4) {
            this.table.fill(e4 << 4 | t4);
          }
          add(e4, t4, i3, s4) {
            this.table[t4 << 8 | e4] = i3 << 4 | s4;
          }
          addMany(e4, t4, i3, s4) {
            for (let r5 = 0; r5 < e4.length; r5++) this.table[t4 << 8 | e4[r5]] = i3 << 4 | s4;
          }
        }
        t3.TransitionTable = o2;
        const h = 160;
        t3.VT500_TRANSITION_TABLE = function() {
          const e4 = new o2(4095), t4 = Array.apply(null, Array(256)).map((e5, t5) => t5), i3 = /* @__PURE__ */ __name((e5, i4) => t4.slice(e5, i4), "i"), s4 = i3(32, 127), r5 = i3(0, 24);
          r5.push(25), r5.push.apply(r5, i3(28, 32));
          const n4 = i3(0, 14);
          let a2;
          for (a2 in e4.setDefault(1, 0), e4.addMany(s4, 0, 2, 0), n4) e4.addMany([24, 26, 153, 154], a2, 3, 0), e4.addMany(i3(128, 144), a2, 3, 0), e4.addMany(i3(144, 152), a2, 3, 0), e4.add(156, a2, 0, 0), e4.add(27, a2, 11, 1), e4.add(157, a2, 4, 8), e4.addMany([152, 158, 159], a2, 0, 7), e4.add(155, a2, 11, 3), e4.add(144, a2, 11, 9);
          return e4.addMany(r5, 0, 3, 0), e4.addMany(r5, 1, 3, 1), e4.add(127, 1, 0, 1), e4.addMany(r5, 8, 0, 8), e4.addMany(r5, 3, 3, 3), e4.add(127, 3, 0, 3), e4.addMany(r5, 4, 3, 4), e4.add(127, 4, 0, 4), e4.addMany(r5, 6, 3, 6), e4.addMany(r5, 5, 3, 5), e4.add(127, 5, 0, 5), e4.addMany(r5, 2, 3, 2), e4.add(127, 2, 0, 2), e4.add(93, 1, 4, 8), e4.addMany(s4, 8, 5, 8), e4.add(127, 8, 5, 8), e4.addMany([156, 27, 24, 26, 7], 8, 6, 0), e4.addMany(i3(28, 32), 8, 0, 8), e4.addMany([88, 94, 95], 1, 0, 7), e4.addMany(s4, 7, 0, 7), e4.addMany(r5, 7, 0, 7), e4.add(156, 7, 0, 0), e4.add(127, 7, 0, 7), e4.add(91, 1, 11, 3), e4.addMany(i3(64, 127), 3, 7, 0), e4.addMany(i3(48, 60), 3, 8, 4), e4.addMany([60, 61, 62, 63], 3, 9, 4), e4.addMany(i3(48, 60), 4, 8, 4), e4.addMany(i3(64, 127), 4, 7, 0), e4.addMany([60, 61, 62, 63], 4, 0, 6), e4.addMany(i3(32, 64), 6, 0, 6), e4.add(127, 6, 0, 6), e4.addMany(i3(64, 127), 6, 0, 0), e4.addMany(i3(32, 48), 3, 9, 5), e4.addMany(i3(32, 48), 5, 9, 5), e4.addMany(i3(48, 64), 5, 0, 6), e4.addMany(i3(64, 127), 5, 7, 0), e4.addMany(i3(32, 48), 4, 9, 5), e4.addMany(i3(32, 48), 1, 9, 2), e4.addMany(i3(32, 48), 2, 9, 2), e4.addMany(i3(48, 127), 2, 10, 0), e4.addMany(i3(48, 80), 1, 10, 0), e4.addMany(i3(81, 88), 1, 10, 0), e4.addMany([89, 90, 92], 1, 10, 0), e4.addMany(i3(96, 127), 1, 10, 0), e4.add(80, 1, 11, 9), e4.addMany(r5, 9, 0, 9), e4.add(127, 9, 0, 9), e4.addMany(i3(28, 32), 9, 0, 9), e4.addMany(i3(32, 48), 9, 9, 12), e4.addMany(i3(48, 60), 9, 8, 10), e4.addMany([60, 61, 62, 63], 9, 9, 10), e4.addMany(r5, 11, 0, 11), e4.addMany(i3(32, 128), 11, 0, 11), e4.addMany(i3(28, 32), 11, 0, 11), e4.addMany(r5, 10, 0, 10), e4.add(127, 10, 0, 10), e4.addMany(i3(28, 32), 10, 0, 10), e4.addMany(i3(48, 60), 10, 8, 10), e4.addMany([60, 61, 62, 63], 10, 0, 11), e4.addMany(i3(32, 48), 10, 9, 12), e4.addMany(r5, 12, 0, 12), e4.add(127, 12, 0, 12), e4.addMany(i3(28, 32), 12, 0, 12), e4.addMany(i3(32, 48), 12, 9, 12), e4.addMany(i3(48, 64), 12, 0, 11), e4.addMany(i3(64, 127), 12, 12, 13), e4.addMany(i3(64, 127), 10, 12, 13), e4.addMany(i3(64, 127), 9, 12, 13), e4.addMany(r5, 13, 13, 13), e4.addMany(s4, 13, 13, 13), e4.add(127, 13, 0, 13), e4.addMany([27, 156, 24, 26], 13, 14, 0), e4.add(h, 0, 2, 0), e4.add(h, 8, 5, 8), e4.add(h, 6, 0, 6), e4.add(h, 11, 0, 11), e4.add(h, 13, 13, 13), e4;
        }();
        class c3 extends s3.Disposable {
          static {
            __name(this, "c");
          }
          constructor(e4 = t3.VT500_TRANSITION_TABLE) {
            super(), this._transitions = e4, this._parseStack = { state: 0, handlers: [], handlerPos: 0, transition: 0, chunkPos: 0 }, this.initialState = 0, this.currentState = this.initialState, this._params = new r4.Params(), this._params.addParam(0), this._collect = 0, this.precedingJoinState = 0, this._printHandlerFb = (e5, t4, i3) => {
            }, this._executeHandlerFb = (e5) => {
            }, this._csiHandlerFb = (e5, t4) => {
            }, this._escHandlerFb = (e5) => {
            }, this._errorHandlerFb = (e5) => e5, this._printHandler = this._printHandlerFb, this._executeHandlers = /* @__PURE__ */ Object.create(null), this._csiHandlers = /* @__PURE__ */ Object.create(null), this._escHandlers = /* @__PURE__ */ Object.create(null), this.register((0, s3.toDisposable)(() => {
              this._csiHandlers = /* @__PURE__ */ Object.create(null), this._executeHandlers = /* @__PURE__ */ Object.create(null), this._escHandlers = /* @__PURE__ */ Object.create(null);
            })), this._oscParser = this.register(new n3.OscParser()), this._dcsParser = this.register(new a.DcsParser()), this._errorHandler = this._errorHandlerFb, this.registerEscHandler({ final: "\\" }, () => true);
          }
          _identifier(e4, t4 = [64, 126]) {
            let i3 = 0;
            if (e4.prefix) {
              if (e4.prefix.length > 1) throw new Error("only one byte as prefix supported");
              if (i3 = e4.prefix.charCodeAt(0), i3 && 60 > i3 || i3 > 63) throw new Error("prefix must be in range 0x3c .. 0x3f");
            }
            if (e4.intermediates) {
              if (e4.intermediates.length > 2) throw new Error("only two bytes as intermediates are supported");
              for (let t5 = 0; t5 < e4.intermediates.length; ++t5) {
                const s5 = e4.intermediates.charCodeAt(t5);
                if (32 > s5 || s5 > 47) throw new Error("intermediate must be in range 0x20 .. 0x2f");
                i3 <<= 8, i3 |= s5;
              }
            }
            if (1 !== e4.final.length) throw new Error("final must be a single byte");
            const s4 = e4.final.charCodeAt(0);
            if (t4[0] > s4 || s4 > t4[1]) throw new Error(`final must be in range ${t4[0]} .. ${t4[1]}`);
            return i3 <<= 8, i3 |= s4, i3;
          }
          identToString(e4) {
            const t4 = [];
            for (; e4; ) t4.push(String.fromCharCode(255 & e4)), e4 >>= 8;
            return t4.reverse().join("");
          }
          setPrintHandler(e4) {
            this._printHandler = e4;
          }
          clearPrintHandler() {
            this._printHandler = this._printHandlerFb;
          }
          registerEscHandler(e4, t4) {
            const i3 = this._identifier(e4, [48, 126]);
            void 0 === this._escHandlers[i3] && (this._escHandlers[i3] = []);
            const s4 = this._escHandlers[i3];
            return s4.push(t4), { dispose: /* @__PURE__ */ __name(() => {
              const e5 = s4.indexOf(t4);
              -1 !== e5 && s4.splice(e5, 1);
            }, "dispose") };
          }
          clearEscHandler(e4) {
            this._escHandlers[this._identifier(e4, [48, 126])] && delete this._escHandlers[this._identifier(e4, [48, 126])];
          }
          setEscHandlerFallback(e4) {
            this._escHandlerFb = e4;
          }
          setExecuteHandler(e4, t4) {
            this._executeHandlers[e4.charCodeAt(0)] = t4;
          }
          clearExecuteHandler(e4) {
            this._executeHandlers[e4.charCodeAt(0)] && delete this._executeHandlers[e4.charCodeAt(0)];
          }
          setExecuteHandlerFallback(e4) {
            this._executeHandlerFb = e4;
          }
          registerCsiHandler(e4, t4) {
            const i3 = this._identifier(e4);
            void 0 === this._csiHandlers[i3] && (this._csiHandlers[i3] = []);
            const s4 = this._csiHandlers[i3];
            return s4.push(t4), { dispose: /* @__PURE__ */ __name(() => {
              const e5 = s4.indexOf(t4);
              -1 !== e5 && s4.splice(e5, 1);
            }, "dispose") };
          }
          clearCsiHandler(e4) {
            this._csiHandlers[this._identifier(e4)] && delete this._csiHandlers[this._identifier(e4)];
          }
          setCsiHandlerFallback(e4) {
            this._csiHandlerFb = e4;
          }
          registerDcsHandler(e4, t4) {
            return this._dcsParser.registerHandler(this._identifier(e4), t4);
          }
          clearDcsHandler(e4) {
            this._dcsParser.clearHandler(this._identifier(e4));
          }
          setDcsHandlerFallback(e4) {
            this._dcsParser.setHandlerFallback(e4);
          }
          registerOscHandler(e4, t4) {
            return this._oscParser.registerHandler(e4, t4);
          }
          clearOscHandler(e4) {
            this._oscParser.clearHandler(e4);
          }
          setOscHandlerFallback(e4) {
            this._oscParser.setHandlerFallback(e4);
          }
          setErrorHandler(e4) {
            this._errorHandler = e4;
          }
          clearErrorHandler() {
            this._errorHandler = this._errorHandlerFb;
          }
          reset() {
            this.currentState = this.initialState, this._oscParser.reset(), this._dcsParser.reset(), this._params.reset(), this._params.addParam(0), this._collect = 0, this.precedingJoinState = 0, 0 !== this._parseStack.state && (this._parseStack.state = 2, this._parseStack.handlers = []);
          }
          _preserveStack(e4, t4, i3, s4, r5) {
            this._parseStack.state = e4, this._parseStack.handlers = t4, this._parseStack.handlerPos = i3, this._parseStack.transition = s4, this._parseStack.chunkPos = r5;
          }
          parse(e4, t4, i3) {
            let s4, r5 = 0, n4 = 0, a2 = 0;
            if (this._parseStack.state) if (2 === this._parseStack.state) this._parseStack.state = 0, a2 = this._parseStack.chunkPos + 1;
            else {
              if (void 0 === i3 || 1 === this._parseStack.state) throw this._parseStack.state = 1, new Error("improper continuation due to previous async handler, giving up parsing");
              const t5 = this._parseStack.handlers;
              let n5 = this._parseStack.handlerPos - 1;
              switch (this._parseStack.state) {
                case 3:
                  if (false === i3 && n5 > -1) {
                    for (; n5 >= 0 && (s4 = t5[n5](this._params), true !== s4); n5--) if (s4 instanceof Promise) return this._parseStack.handlerPos = n5, s4;
                  }
                  this._parseStack.handlers = [];
                  break;
                case 4:
                  if (false === i3 && n5 > -1) {
                    for (; n5 >= 0 && (s4 = t5[n5](), true !== s4); n5--) if (s4 instanceof Promise) return this._parseStack.handlerPos = n5, s4;
                  }
                  this._parseStack.handlers = [];
                  break;
                case 6:
                  if (r5 = e4[this._parseStack.chunkPos], s4 = this._dcsParser.unhook(24 !== r5 && 26 !== r5, i3), s4) return s4;
                  27 === r5 && (this._parseStack.transition |= 1), this._params.reset(), this._params.addParam(0), this._collect = 0;
                  break;
                case 5:
                  if (r5 = e4[this._parseStack.chunkPos], s4 = this._oscParser.end(24 !== r5 && 26 !== r5, i3), s4) return s4;
                  27 === r5 && (this._parseStack.transition |= 1), this._params.reset(), this._params.addParam(0), this._collect = 0;
              }
              this._parseStack.state = 0, a2 = this._parseStack.chunkPos + 1, this.precedingJoinState = 0, this.currentState = 15 & this._parseStack.transition;
            }
            for (let i4 = a2; i4 < t4; ++i4) {
              switch (r5 = e4[i4], n4 = this._transitions.table[this.currentState << 8 | (r5 < 160 ? r5 : h)], n4 >> 4) {
                case 2:
                  for (let s5 = i4 + 1; ; ++s5) {
                    if (s5 >= t4 || (r5 = e4[s5]) < 32 || r5 > 126 && r5 < h) {
                      this._printHandler(e4, i4, s5), i4 = s5 - 1;
                      break;
                    }
                    if (++s5 >= t4 || (r5 = e4[s5]) < 32 || r5 > 126 && r5 < h) {
                      this._printHandler(e4, i4, s5), i4 = s5 - 1;
                      break;
                    }
                    if (++s5 >= t4 || (r5 = e4[s5]) < 32 || r5 > 126 && r5 < h) {
                      this._printHandler(e4, i4, s5), i4 = s5 - 1;
                      break;
                    }
                    if (++s5 >= t4 || (r5 = e4[s5]) < 32 || r5 > 126 && r5 < h) {
                      this._printHandler(e4, i4, s5), i4 = s5 - 1;
                      break;
                    }
                  }
                  break;
                case 3:
                  this._executeHandlers[r5] ? this._executeHandlers[r5]() : this._executeHandlerFb(r5), this.precedingJoinState = 0;
                  break;
                case 0:
                  break;
                case 1:
                  if (this._errorHandler({ position: i4, code: r5, currentState: this.currentState, collect: this._collect, params: this._params, abort: false }).abort) return;
                  break;
                case 7:
                  const a3 = this._csiHandlers[this._collect << 8 | r5];
                  let o3 = a3 ? a3.length - 1 : -1;
                  for (; o3 >= 0 && (s4 = a3[o3](this._params), true !== s4); o3--) if (s4 instanceof Promise) return this._preserveStack(3, a3, o3, n4, i4), s4;
                  o3 < 0 && this._csiHandlerFb(this._collect << 8 | r5, this._params), this.precedingJoinState = 0;
                  break;
                case 8:
                  do {
                    switch (r5) {
                      case 59:
                        this._params.addParam(0);
                        break;
                      case 58:
                        this._params.addSubParam(-1);
                        break;
                      default:
                        this._params.addDigit(r5 - 48);
                    }
                  } while (++i4 < t4 && (r5 = e4[i4]) > 47 && r5 < 60);
                  i4--;
                  break;
                case 9:
                  this._collect <<= 8, this._collect |= r5;
                  break;
                case 10:
                  const c4 = this._escHandlers[this._collect << 8 | r5];
                  let l2 = c4 ? c4.length - 1 : -1;
                  for (; l2 >= 0 && (s4 = c4[l2](), true !== s4); l2--) if (s4 instanceof Promise) return this._preserveStack(4, c4, l2, n4, i4), s4;
                  l2 < 0 && this._escHandlerFb(this._collect << 8 | r5), this.precedingJoinState = 0;
                  break;
                case 11:
                  this._params.reset(), this._params.addParam(0), this._collect = 0;
                  break;
                case 12:
                  this._dcsParser.hook(this._collect << 8 | r5, this._params);
                  break;
                case 13:
                  for (let s5 = i4 + 1; ; ++s5) if (s5 >= t4 || 24 === (r5 = e4[s5]) || 26 === r5 || 27 === r5 || r5 > 127 && r5 < h) {
                    this._dcsParser.put(e4, i4, s5), i4 = s5 - 1;
                    break;
                  }
                  break;
                case 14:
                  if (s4 = this._dcsParser.unhook(24 !== r5 && 26 !== r5), s4) return this._preserveStack(6, [], 0, n4, i4), s4;
                  27 === r5 && (n4 |= 1), this._params.reset(), this._params.addParam(0), this._collect = 0, this.precedingJoinState = 0;
                  break;
                case 4:
                  this._oscParser.start();
                  break;
                case 5:
                  for (let s5 = i4 + 1; ; s5++) if (s5 >= t4 || (r5 = e4[s5]) < 32 || r5 > 127 && r5 < h) {
                    this._oscParser.put(e4, i4, s5), i4 = s5 - 1;
                    break;
                  }
                  break;
                case 6:
                  if (s4 = this._oscParser.end(24 !== r5 && 26 !== r5), s4) return this._preserveStack(5, [], 0, n4, i4), s4;
                  27 === r5 && (n4 |= 1), this._params.reset(), this._params.addParam(0), this._collect = 0, this.precedingJoinState = 0;
              }
              this.currentState = 15 & n4;
            }
          }
        }
        t3.EscapeSequenceParser = c3;
      }, 242: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.OscHandler = t3.OscParser = void 0;
        const s3 = i2(770), r4 = i2(482), n3 = [];
        t3.OscParser = class {
          constructor() {
            this._state = 0, this._active = n3, this._id = -1, this._handlers = /* @__PURE__ */ Object.create(null), this._handlerFb = () => {
            }, this._stack = { paused: false, loopPosition: 0, fallThrough: false };
          }
          registerHandler(e4, t4) {
            void 0 === this._handlers[e4] && (this._handlers[e4] = []);
            const i3 = this._handlers[e4];
            return i3.push(t4), { dispose: /* @__PURE__ */ __name(() => {
              const e5 = i3.indexOf(t4);
              -1 !== e5 && i3.splice(e5, 1);
            }, "dispose") };
          }
          clearHandler(e4) {
            this._handlers[e4] && delete this._handlers[e4];
          }
          setHandlerFallback(e4) {
            this._handlerFb = e4;
          }
          dispose() {
            this._handlers = /* @__PURE__ */ Object.create(null), this._handlerFb = () => {
            }, this._active = n3;
          }
          reset() {
            if (2 === this._state) for (let e4 = this._stack.paused ? this._stack.loopPosition - 1 : this._active.length - 1; e4 >= 0; --e4) this._active[e4].end(false);
            this._stack.paused = false, this._active = n3, this._id = -1, this._state = 0;
          }
          _start() {
            if (this._active = this._handlers[this._id] || n3, this._active.length) for (let e4 = this._active.length - 1; e4 >= 0; e4--) this._active[e4].start();
            else this._handlerFb(this._id, "START");
          }
          _put(e4, t4, i3) {
            if (this._active.length) for (let s4 = this._active.length - 1; s4 >= 0; s4--) this._active[s4].put(e4, t4, i3);
            else this._handlerFb(this._id, "PUT", (0, r4.utf32ToString)(e4, t4, i3));
          }
          start() {
            this.reset(), this._state = 1;
          }
          put(e4, t4, i3) {
            if (3 !== this._state) {
              if (1 === this._state) for (; t4 < i3; ) {
                const i4 = e4[t4++];
                if (59 === i4) {
                  this._state = 2, this._start();
                  break;
                }
                if (i4 < 48 || 57 < i4) return void (this._state = 3);
                -1 === this._id && (this._id = 0), this._id = 10 * this._id + i4 - 48;
              }
              2 === this._state && i3 - t4 > 0 && this._put(e4, t4, i3);
            }
          }
          end(e4, t4 = true) {
            if (0 !== this._state) {
              if (3 !== this._state) if (1 === this._state && this._start(), this._active.length) {
                let i3 = false, s4 = this._active.length - 1, r5 = false;
                if (this._stack.paused && (s4 = this._stack.loopPosition - 1, i3 = t4, r5 = this._stack.fallThrough, this._stack.paused = false), !r5 && false === i3) {
                  for (; s4 >= 0 && (i3 = this._active[s4].end(e4), true !== i3); s4--) if (i3 instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = s4, this._stack.fallThrough = false, i3;
                  s4--;
                }
                for (; s4 >= 0; s4--) if (i3 = this._active[s4].end(false), i3 instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = s4, this._stack.fallThrough = true, i3;
              } else this._handlerFb(this._id, "END", e4);
              this._active = n3, this._id = -1, this._state = 0;
            }
          }
        }, t3.OscHandler = class {
          constructor(e4) {
            this._handler = e4, this._data = "", this._hitLimit = false;
          }
          start() {
            this._data = "", this._hitLimit = false;
          }
          put(e4, t4, i3) {
            this._hitLimit || (this._data += (0, r4.utf32ToString)(e4, t4, i3), this._data.length > s3.PAYLOAD_LIMIT && (this._data = "", this._hitLimit = true));
          }
          end(e4) {
            let t4 = false;
            if (this._hitLimit) t4 = false;
            else if (e4 && (t4 = this._handler(this._data), t4 instanceof Promise)) return t4.then((e5) => (this._data = "", this._hitLimit = false, e5));
            return this._data = "", this._hitLimit = false, t4;
          }
        };
      }, 742: (e3, t3) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.Params = void 0;
        const i2 = 2147483647;
        class s3 {
          static {
            __name(this, "s");
          }
          static fromArray(e4) {
            const t4 = new s3();
            if (!e4.length) return t4;
            for (let i3 = Array.isArray(e4[0]) ? 1 : 0; i3 < e4.length; ++i3) {
              const s4 = e4[i3];
              if (Array.isArray(s4)) for (let e5 = 0; e5 < s4.length; ++e5) t4.addSubParam(s4[e5]);
              else t4.addParam(s4);
            }
            return t4;
          }
          constructor(e4 = 32, t4 = 32) {
            if (this.maxLength = e4, this.maxSubParamsLength = t4, t4 > 256) throw new Error("maxSubParamsLength must not be greater than 256");
            this.params = new Int32Array(e4), this.length = 0, this._subParams = new Int32Array(t4), this._subParamsLength = 0, this._subParamsIdx = new Uint16Array(e4), this._rejectDigits = false, this._rejectSubDigits = false, this._digitIsSub = false;
          }
          clone() {
            const e4 = new s3(this.maxLength, this.maxSubParamsLength);
            return e4.params.set(this.params), e4.length = this.length, e4._subParams.set(this._subParams), e4._subParamsLength = this._subParamsLength, e4._subParamsIdx.set(this._subParamsIdx), e4._rejectDigits = this._rejectDigits, e4._rejectSubDigits = this._rejectSubDigits, e4._digitIsSub = this._digitIsSub, e4;
          }
          toArray() {
            const e4 = [];
            for (let t4 = 0; t4 < this.length; ++t4) {
              e4.push(this.params[t4]);
              const i3 = this._subParamsIdx[t4] >> 8, s4 = 255 & this._subParamsIdx[t4];
              s4 - i3 > 0 && e4.push(Array.prototype.slice.call(this._subParams, i3, s4));
            }
            return e4;
          }
          reset() {
            this.length = 0, this._subParamsLength = 0, this._rejectDigits = false, this._rejectSubDigits = false, this._digitIsSub = false;
          }
          addParam(e4) {
            if (this._digitIsSub = false, this.length >= this.maxLength) this._rejectDigits = true;
            else {
              if (e4 < -1) throw new Error("values lesser than -1 are not allowed");
              this._subParamsIdx[this.length] = this._subParamsLength << 8 | this._subParamsLength, this.params[this.length++] = e4 > i2 ? i2 : e4;
            }
          }
          addSubParam(e4) {
            if (this._digitIsSub = true, this.length) if (this._rejectDigits || this._subParamsLength >= this.maxSubParamsLength) this._rejectSubDigits = true;
            else {
              if (e4 < -1) throw new Error("values lesser than -1 are not allowed");
              this._subParams[this._subParamsLength++] = e4 > i2 ? i2 : e4, this._subParamsIdx[this.length - 1]++;
            }
          }
          hasSubParams(e4) {
            return (255 & this._subParamsIdx[e4]) - (this._subParamsIdx[e4] >> 8) > 0;
          }
          getSubParams(e4) {
            const t4 = this._subParamsIdx[e4] >> 8, i3 = 255 & this._subParamsIdx[e4];
            return i3 - t4 > 0 ? this._subParams.subarray(t4, i3) : null;
          }
          getSubParamsAll() {
            const e4 = {};
            for (let t4 = 0; t4 < this.length; ++t4) {
              const i3 = this._subParamsIdx[t4] >> 8, s4 = 255 & this._subParamsIdx[t4];
              s4 - i3 > 0 && (e4[t4] = this._subParams.slice(i3, s4));
            }
            return e4;
          }
          addDigit(e4) {
            let t4;
            if (this._rejectDigits || !(t4 = this._digitIsSub ? this._subParamsLength : this.length) || this._digitIsSub && this._rejectSubDigits) return;
            const s4 = this._digitIsSub ? this._subParams : this.params, r4 = s4[t4 - 1];
            s4[t4 - 1] = ~r4 ? Math.min(10 * r4 + e4, i2) : e4;
          }
        }
        t3.Params = s3;
      }, 741: (e3, t3) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.AddonManager = void 0, t3.AddonManager = class {
          constructor() {
            this._addons = [];
          }
          dispose() {
            for (let e4 = this._addons.length - 1; e4 >= 0; e4--) this._addons[e4].instance.dispose();
          }
          loadAddon(e4, t4) {
            const i2 = { instance: t4, dispose: t4.dispose, isDisposed: false };
            this._addons.push(i2), t4.dispose = () => this._wrappedAddonDispose(i2), t4.activate(e4);
          }
          _wrappedAddonDispose(e4) {
            if (e4.isDisposed) return;
            let t4 = -1;
            for (let i2 = 0; i2 < this._addons.length; i2++) if (this._addons[i2] === e4) {
              t4 = i2;
              break;
            }
            if (-1 === t4) throw new Error("Could not dispose an addon that has not been loaded");
            e4.isDisposed = true, e4.dispose.apply(e4.instance), this._addons.splice(t4, 1);
          }
        };
      }, 771: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.BufferApiView = void 0;
        const s3 = i2(785), r4 = i2(511);
        t3.BufferApiView = class {
          constructor(e4, t4) {
            this._buffer = e4, this.type = t4;
          }
          init(e4) {
            return this._buffer = e4, this;
          }
          get cursorY() {
            return this._buffer.y;
          }
          get cursorX() {
            return this._buffer.x;
          }
          get viewportY() {
            return this._buffer.ydisp;
          }
          get baseY() {
            return this._buffer.ybase;
          }
          get length() {
            return this._buffer.lines.length;
          }
          getLine(e4) {
            const t4 = this._buffer.lines.get(e4);
            if (t4) return new s3.BufferLineApiView(t4);
          }
          getNullCell() {
            return new r4.CellData();
          }
        };
      }, 785: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.BufferLineApiView = void 0;
        const s3 = i2(511);
        t3.BufferLineApiView = class {
          constructor(e4) {
            this._line = e4;
          }
          get isWrapped() {
            return this._line.isWrapped;
          }
          get length() {
            return this._line.length;
          }
          getCell(e4, t4) {
            if (!(e4 < 0 || e4 >= this._line.length)) return t4 ? (this._line.loadCell(e4, t4), t4) : this._line.loadCell(e4, new s3.CellData());
          }
          translateToString(e4, t4, i3) {
            return this._line.translateToString(e4, t4, i3);
          }
        };
      }, 285: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.BufferNamespaceApi = void 0;
        const s3 = i2(771), r4 = i2(460), n3 = i2(844);
        class a extends n3.Disposable {
          static {
            __name(this, "a");
          }
          constructor(e4) {
            super(), this._core = e4, this._onBufferChange = this.register(new r4.EventEmitter()), this.onBufferChange = this._onBufferChange.event, this._normal = new s3.BufferApiView(this._core.buffers.normal, "normal"), this._alternate = new s3.BufferApiView(this._core.buffers.alt, "alternate"), this._core.buffers.onBufferActivate(() => this._onBufferChange.fire(this.active));
          }
          get active() {
            if (this._core.buffers.active === this._core.buffers.normal) return this.normal;
            if (this._core.buffers.active === this._core.buffers.alt) return this.alternate;
            throw new Error("Active buffer is neither normal nor alternate");
          }
          get normal() {
            return this._normal.init(this._core.buffers.normal);
          }
          get alternate() {
            return this._alternate.init(this._core.buffers.alt);
          }
        }
        t3.BufferNamespaceApi = a;
      }, 975: (e3, t3) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.ParserApi = void 0, t3.ParserApi = class {
          constructor(e4) {
            this._core = e4;
          }
          registerCsiHandler(e4, t4) {
            return this._core.registerCsiHandler(e4, (e5) => t4(e5.toArray()));
          }
          addCsiHandler(e4, t4) {
            return this.registerCsiHandler(e4, t4);
          }
          registerDcsHandler(e4, t4) {
            return this._core.registerDcsHandler(e4, (e5, i2) => t4(e5, i2.toArray()));
          }
          addDcsHandler(e4, t4) {
            return this.registerDcsHandler(e4, t4);
          }
          registerEscHandler(e4, t4) {
            return this._core.registerEscHandler(e4, t4);
          }
          addEscHandler(e4, t4) {
            return this.registerEscHandler(e4, t4);
          }
          registerOscHandler(e4, t4) {
            return this._core.registerOscHandler(e4, t4);
          }
          addOscHandler(e4, t4) {
            return this.registerOscHandler(e4, t4);
          }
        };
      }, 90: (e3, t3) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.UnicodeApi = void 0, t3.UnicodeApi = class {
          constructor(e4) {
            this._core = e4;
          }
          register(e4) {
            this._core.unicodeService.register(e4);
          }
          get versions() {
            return this._core.unicodeService.versions;
          }
          get activeVersion() {
            return this._core.unicodeService.activeVersion;
          }
          set activeVersion(e4) {
            this._core.unicodeService.activeVersion = e4;
          }
        };
      }, 744: function(e3, t3, i2) {
        var s3 = this && this.__decorate || function(e4, t4, i3, s4) {
          var r5, n4 = arguments.length, a2 = n4 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i3) : s4;
          if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a2 = Reflect.decorate(e4, t4, i3, s4);
          else for (var o3 = e4.length - 1; o3 >= 0; o3--) (r5 = e4[o3]) && (a2 = (n4 < 3 ? r5(a2) : n4 > 3 ? r5(t4, i3, a2) : r5(t4, i3)) || a2);
          return n4 > 3 && a2 && Object.defineProperty(t4, i3, a2), a2;
        }, r4 = this && this.__param || function(e4, t4) {
          return function(i3, s4) {
            t4(i3, s4, e4);
          };
        };
        Object.defineProperty(t3, "__esModule", { value: true }), t3.BufferService = t3.MINIMUM_ROWS = t3.MINIMUM_COLS = void 0;
        const n3 = i2(460), a = i2(844), o2 = i2(295), h = i2(585);
        t3.MINIMUM_COLS = 2, t3.MINIMUM_ROWS = 1;
        let c3 = t3.BufferService = class extends a.Disposable {
          get buffer() {
            return this.buffers.active;
          }
          constructor(e4) {
            super(), this.isUserScrolling = false, this._onResize = this.register(new n3.EventEmitter()), this.onResize = this._onResize.event, this._onScroll = this.register(new n3.EventEmitter()), this.onScroll = this._onScroll.event, this.cols = Math.max(e4.rawOptions.cols || 0, t3.MINIMUM_COLS), this.rows = Math.max(e4.rawOptions.rows || 0, t3.MINIMUM_ROWS), this.buffers = this.register(new o2.BufferSet(e4, this));
          }
          resize(e4, t4) {
            this.cols = e4, this.rows = t4, this.buffers.resize(e4, t4), this._onResize.fire({ cols: e4, rows: t4 });
          }
          reset() {
            this.buffers.reset(), this.isUserScrolling = false;
          }
          scroll(e4, t4 = false) {
            const i3 = this.buffer;
            let s4;
            s4 = this._cachedBlankLine, s4 && s4.length === this.cols && s4.getFg(0) === e4.fg && s4.getBg(0) === e4.bg || (s4 = i3.getBlankLine(e4, t4), this._cachedBlankLine = s4), s4.isWrapped = t4;
            const r5 = i3.ybase + i3.scrollTop, n4 = i3.ybase + i3.scrollBottom;
            if (0 === i3.scrollTop) {
              const e5 = i3.lines.isFull;
              n4 === i3.lines.length - 1 ? e5 ? i3.lines.recycle().copyFrom(s4) : i3.lines.push(s4.clone()) : i3.lines.splice(n4 + 1, 0, s4.clone()), e5 ? this.isUserScrolling && (i3.ydisp = Math.max(i3.ydisp - 1, 0)) : (i3.ybase++, this.isUserScrolling || i3.ydisp++);
            } else {
              const e5 = n4 - r5 + 1;
              i3.lines.shiftElements(r5 + 1, e5 - 1, -1), i3.lines.set(n4, s4.clone());
            }
            this.isUserScrolling || (i3.ydisp = i3.ybase), this._onScroll.fire(i3.ydisp);
          }
          scrollLines(e4, t4, i3) {
            const s4 = this.buffer;
            if (e4 < 0) {
              if (0 === s4.ydisp) return;
              this.isUserScrolling = true;
            } else e4 + s4.ydisp >= s4.ybase && (this.isUserScrolling = false);
            const r5 = s4.ydisp;
            s4.ydisp = Math.max(Math.min(s4.ydisp + e4, s4.ybase), 0), r5 !== s4.ydisp && (t4 || this._onScroll.fire(s4.ydisp));
          }
        };
        t3.BufferService = c3 = s3([r4(0, h.IOptionsService)], c3);
      }, 994: (e3, t3) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.CharsetService = void 0, t3.CharsetService = class {
          constructor() {
            this.glevel = 0, this._charsets = [];
          }
          reset() {
            this.charset = void 0, this._charsets = [], this.glevel = 0;
          }
          setgLevel(e4) {
            this.glevel = e4, this.charset = this._charsets[e4];
          }
          setgCharset(e4, t4) {
            this._charsets[e4] = t4, this.glevel === e4 && (this.charset = t4);
          }
        };
      }, 753: function(e3, t3, i2) {
        var s3 = this && this.__decorate || function(e4, t4, i3, s4) {
          var r5, n4 = arguments.length, a2 = n4 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i3) : s4;
          if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a2 = Reflect.decorate(e4, t4, i3, s4);
          else for (var o3 = e4.length - 1; o3 >= 0; o3--) (r5 = e4[o3]) && (a2 = (n4 < 3 ? r5(a2) : n4 > 3 ? r5(t4, i3, a2) : r5(t4, i3)) || a2);
          return n4 > 3 && a2 && Object.defineProperty(t4, i3, a2), a2;
        }, r4 = this && this.__param || function(e4, t4) {
          return function(i3, s4) {
            t4(i3, s4, e4);
          };
        };
        Object.defineProperty(t3, "__esModule", { value: true }), t3.CoreMouseService = void 0;
        const n3 = i2(585), a = i2(460), o2 = i2(844), h = { NONE: { events: 0, restrict: /* @__PURE__ */ __name(() => false, "restrict") }, X10: { events: 1, restrict: /* @__PURE__ */ __name((e4) => 4 !== e4.button && 1 === e4.action && (e4.ctrl = false, e4.alt = false, e4.shift = false, true), "restrict") }, VT200: { events: 19, restrict: /* @__PURE__ */ __name((e4) => 32 !== e4.action, "restrict") }, DRAG: { events: 23, restrict: /* @__PURE__ */ __name((e4) => 32 !== e4.action || 3 !== e4.button, "restrict") }, ANY: { events: 31, restrict: /* @__PURE__ */ __name((e4) => true, "restrict") } };
        function c3(e4, t4) {
          let i3 = (e4.ctrl ? 16 : 0) | (e4.shift ? 4 : 0) | (e4.alt ? 8 : 0);
          return 4 === e4.button ? (i3 |= 64, i3 |= e4.action) : (i3 |= 3 & e4.button, 4 & e4.button && (i3 |= 64), 8 & e4.button && (i3 |= 128), 32 === e4.action ? i3 |= 32 : 0 !== e4.action || t4 || (i3 |= 3)), i3;
        }
        __name(c3, "c");
        const l2 = String.fromCharCode, _ = { DEFAULT: /* @__PURE__ */ __name((e4) => {
          const t4 = [c3(e4, false) + 32, e4.col + 32, e4.row + 32];
          return t4[0] > 255 || t4[1] > 255 || t4[2] > 255 ? "" : `\x1B[M${l2(t4[0])}${l2(t4[1])}${l2(t4[2])}`;
        }, "DEFAULT"), SGR: /* @__PURE__ */ __name((e4) => {
          const t4 = 0 === e4.action && 4 !== e4.button ? "m" : "M";
          return `\x1B[<${c3(e4, true)};${e4.col};${e4.row}${t4}`;
        }, "SGR"), SGR_PIXELS: /* @__PURE__ */ __name((e4) => {
          const t4 = 0 === e4.action && 4 !== e4.button ? "m" : "M";
          return `\x1B[<${c3(e4, true)};${e4.x};${e4.y}${t4}`;
        }, "SGR_PIXELS") };
        let d = t3.CoreMouseService = class extends o2.Disposable {
          constructor(e4, t4) {
            super(), this._bufferService = e4, this._coreService = t4, this._protocols = {}, this._encodings = {}, this._activeProtocol = "", this._activeEncoding = "", this._lastEvent = null, this._onProtocolChange = this.register(new a.EventEmitter()), this.onProtocolChange = this._onProtocolChange.event;
            for (const e5 of Object.keys(h)) this.addProtocol(e5, h[e5]);
            for (const e5 of Object.keys(_)) this.addEncoding(e5, _[e5]);
            this.reset();
          }
          addProtocol(e4, t4) {
            this._protocols[e4] = t4;
          }
          addEncoding(e4, t4) {
            this._encodings[e4] = t4;
          }
          get activeProtocol() {
            return this._activeProtocol;
          }
          get areMouseEventsActive() {
            return 0 !== this._protocols[this._activeProtocol].events;
          }
          set activeProtocol(e4) {
            if (!this._protocols[e4]) throw new Error(`unknown protocol "${e4}"`);
            this._activeProtocol = e4, this._onProtocolChange.fire(this._protocols[e4].events);
          }
          get activeEncoding() {
            return this._activeEncoding;
          }
          set activeEncoding(e4) {
            if (!this._encodings[e4]) throw new Error(`unknown encoding "${e4}"`);
            this._activeEncoding = e4;
          }
          reset() {
            this.activeProtocol = "NONE", this.activeEncoding = "DEFAULT", this._lastEvent = null;
          }
          triggerMouseEvent(e4) {
            if (e4.col < 0 || e4.col >= this._bufferService.cols || e4.row < 0 || e4.row >= this._bufferService.rows) return false;
            if (4 === e4.button && 32 === e4.action) return false;
            if (3 === e4.button && 32 !== e4.action) return false;
            if (4 !== e4.button && (2 === e4.action || 3 === e4.action)) return false;
            if (e4.col++, e4.row++, 32 === e4.action && this._lastEvent && this._equalEvents(this._lastEvent, e4, "SGR_PIXELS" === this._activeEncoding)) return false;
            if (!this._protocols[this._activeProtocol].restrict(e4)) return false;
            const t4 = this._encodings[this._activeEncoding](e4);
            return t4 && ("DEFAULT" === this._activeEncoding ? this._coreService.triggerBinaryEvent(t4) : this._coreService.triggerDataEvent(t4, true)), this._lastEvent = e4, true;
          }
          explainEvents(e4) {
            return { down: !!(1 & e4), up: !!(2 & e4), drag: !!(4 & e4), move: !!(8 & e4), wheel: !!(16 & e4) };
          }
          _equalEvents(e4, t4, i3) {
            if (i3) {
              if (e4.x !== t4.x) return false;
              if (e4.y !== t4.y) return false;
            } else {
              if (e4.col !== t4.col) return false;
              if (e4.row !== t4.row) return false;
            }
            return e4.button === t4.button && e4.action === t4.action && e4.ctrl === t4.ctrl && e4.alt === t4.alt && e4.shift === t4.shift;
          }
        };
        t3.CoreMouseService = d = s3([r4(0, n3.IBufferService), r4(1, n3.ICoreService)], d);
      }, 83: function(e3, t3, i2) {
        var s3 = this && this.__decorate || function(e4, t4, i3, s4) {
          var r5, n4 = arguments.length, a2 = n4 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i3) : s4;
          if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a2 = Reflect.decorate(e4, t4, i3, s4);
          else for (var o3 = e4.length - 1; o3 >= 0; o3--) (r5 = e4[o3]) && (a2 = (n4 < 3 ? r5(a2) : n4 > 3 ? r5(t4, i3, a2) : r5(t4, i3)) || a2);
          return n4 > 3 && a2 && Object.defineProperty(t4, i3, a2), a2;
        }, r4 = this && this.__param || function(e4, t4) {
          return function(i3, s4) {
            t4(i3, s4, e4);
          };
        };
        Object.defineProperty(t3, "__esModule", { value: true }), t3.CoreService = void 0;
        const n3 = i2(439), a = i2(460), o2 = i2(844), h = i2(585), c3 = Object.freeze({ insertMode: false }), l2 = Object.freeze({ applicationCursorKeys: false, applicationKeypad: false, bracketedPasteMode: false, origin: false, reverseWraparound: false, sendFocus: false, wraparound: true });
        let _ = t3.CoreService = class extends o2.Disposable {
          constructor(e4, t4, i3) {
            super(), this._bufferService = e4, this._logService = t4, this._optionsService = i3, this.isCursorInitialized = false, this.isCursorHidden = false, this._onData = this.register(new a.EventEmitter()), this.onData = this._onData.event, this._onUserInput = this.register(new a.EventEmitter()), this.onUserInput = this._onUserInput.event, this._onBinary = this.register(new a.EventEmitter()), this.onBinary = this._onBinary.event, this._onRequestScrollToBottom = this.register(new a.EventEmitter()), this.onRequestScrollToBottom = this._onRequestScrollToBottom.event, this.modes = (0, n3.clone)(c3), this.decPrivateModes = (0, n3.clone)(l2);
          }
          reset() {
            this.modes = (0, n3.clone)(c3), this.decPrivateModes = (0, n3.clone)(l2);
          }
          triggerDataEvent(e4, t4 = false) {
            if (this._optionsService.rawOptions.disableStdin) return;
            const i3 = this._bufferService.buffer;
            t4 && this._optionsService.rawOptions.scrollOnUserInput && i3.ybase !== i3.ydisp && this._onRequestScrollToBottom.fire(), t4 && this._onUserInput.fire(), this._logService.debug(`sending data "${e4}"`, () => e4.split("").map((e5) => e5.charCodeAt(0))), this._onData.fire(e4);
          }
          triggerBinaryEvent(e4) {
            this._optionsService.rawOptions.disableStdin || (this._logService.debug(`sending binary "${e4}"`, () => e4.split("").map((e5) => e5.charCodeAt(0))), this._onBinary.fire(e4));
          }
        };
        t3.CoreService = _ = s3([r4(0, h.IBufferService), r4(1, h.ILogService), r4(2, h.IOptionsService)], _);
      }, 348: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.InstantiationService = t3.ServiceCollection = void 0;
        const s3 = i2(585), r4 = i2(343);
        class n3 {
          static {
            __name(this, "n");
          }
          constructor(...e4) {
            this._entries = /* @__PURE__ */ new Map();
            for (const [t4, i3] of e4) this.set(t4, i3);
          }
          set(e4, t4) {
            const i3 = this._entries.get(e4);
            return this._entries.set(e4, t4), i3;
          }
          forEach(e4) {
            for (const [t4, i3] of this._entries.entries()) e4(t4, i3);
          }
          has(e4) {
            return this._entries.has(e4);
          }
          get(e4) {
            return this._entries.get(e4);
          }
        }
        t3.ServiceCollection = n3, t3.InstantiationService = class {
          constructor() {
            this._services = new n3(), this._services.set(s3.IInstantiationService, this);
          }
          setService(e4, t4) {
            this._services.set(e4, t4);
          }
          getService(e4) {
            return this._services.get(e4);
          }
          createInstance(e4, ...t4) {
            const i3 = (0, r4.getServiceDependencies)(e4).sort((e5, t5) => e5.index - t5.index), s4 = [];
            for (const t5 of i3) {
              const i4 = this._services.get(t5.id);
              if (!i4) throw new Error(`[createInstance] ${e4.name} depends on UNKNOWN service ${t5.id}.`);
              s4.push(i4);
            }
            const n4 = i3.length > 0 ? i3[0].index : t4.length;
            if (t4.length !== n4) throw new Error(`[createInstance] First service dependency of ${e4.name} at position ${n4 + 1} conflicts with ${t4.length} static arguments`);
            return new e4(...[...t4, ...s4]);
          }
        };
      }, 866: function(e3, t3, i2) {
        var s3 = this && this.__decorate || function(e4, t4, i3, s4) {
          var r5, n4 = arguments.length, a2 = n4 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i3) : s4;
          if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a2 = Reflect.decorate(e4, t4, i3, s4);
          else for (var o3 = e4.length - 1; o3 >= 0; o3--) (r5 = e4[o3]) && (a2 = (n4 < 3 ? r5(a2) : n4 > 3 ? r5(t4, i3, a2) : r5(t4, i3)) || a2);
          return n4 > 3 && a2 && Object.defineProperty(t4, i3, a2), a2;
        }, r4 = this && this.__param || function(e4, t4) {
          return function(i3, s4) {
            t4(i3, s4, e4);
          };
        };
        Object.defineProperty(t3, "__esModule", { value: true }), t3.traceCall = t3.setTraceLogger = t3.LogService = void 0;
        const n3 = i2(844), a = i2(585), o2 = { trace: a.LogLevelEnum.TRACE, debug: a.LogLevelEnum.DEBUG, info: a.LogLevelEnum.INFO, warn: a.LogLevelEnum.WARN, error: a.LogLevelEnum.ERROR, off: a.LogLevelEnum.OFF };
        let h, c3 = t3.LogService = class extends n3.Disposable {
          get logLevel() {
            return this._logLevel;
          }
          constructor(e4) {
            super(), this._optionsService = e4, this._logLevel = a.LogLevelEnum.OFF, this._updateLogLevel(), this.register(this._optionsService.onSpecificOptionChange("logLevel", () => this._updateLogLevel())), h = this;
          }
          _updateLogLevel() {
            this._logLevel = o2[this._optionsService.rawOptions.logLevel];
          }
          _evalLazyOptionalParams(e4) {
            for (let t4 = 0; t4 < e4.length; t4++) "function" == typeof e4[t4] && (e4[t4] = e4[t4]());
          }
          _log(e4, t4, i3) {
            this._evalLazyOptionalParams(i3), e4.call(console, (this._optionsService.options.logger ? "" : "xterm.js: ") + t4, ...i3);
          }
          trace(e4, ...t4) {
            this._logLevel <= a.LogLevelEnum.TRACE && this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger) ?? console.log, e4, t4);
          }
          debug(e4, ...t4) {
            this._logLevel <= a.LogLevelEnum.DEBUG && this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger) ?? console.log, e4, t4);
          }
          info(e4, ...t4) {
            this._logLevel <= a.LogLevelEnum.INFO && this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger) ?? console.info, e4, t4);
          }
          warn(e4, ...t4) {
            this._logLevel <= a.LogLevelEnum.WARN && this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger) ?? console.warn, e4, t4);
          }
          error(e4, ...t4) {
            this._logLevel <= a.LogLevelEnum.ERROR && this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger) ?? console.error, e4, t4);
          }
        };
        t3.LogService = c3 = s3([r4(0, a.IOptionsService)], c3), t3.setTraceLogger = function(e4) {
          h = e4;
        }, t3.traceCall = function(e4, t4, i3) {
          if ("function" != typeof i3.value) throw new Error("not supported");
          const s4 = i3.value;
          i3.value = function(...e5) {
            if (h.logLevel !== a.LogLevelEnum.TRACE) return s4.apply(this, e5);
            h.trace(`GlyphRenderer#${s4.name}(${e5.map((e6) => JSON.stringify(e6)).join(", ")})`);
            const t5 = s4.apply(this, e5);
            return h.trace(`GlyphRenderer#${s4.name} return`, t5), t5;
          };
        };
      }, 302: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.OptionsService = t3.DEFAULT_OPTIONS = void 0;
        const s3 = i2(460), r4 = i2(844), n3 = i2(114);
        t3.DEFAULT_OPTIONS = { cols: 80, rows: 24, cursorBlink: false, cursorStyle: "block", cursorWidth: 1, cursorInactiveStyle: "outline", customGlyphs: true, drawBoldTextInBrightColors: true, documentOverride: null, fastScrollModifier: "alt", fastScrollSensitivity: 5, fontFamily: "courier-new, courier, monospace", fontSize: 15, fontWeight: "normal", fontWeightBold: "bold", ignoreBracketedPasteMode: false, lineHeight: 1, letterSpacing: 0, linkHandler: null, logLevel: "info", logger: null, scrollback: 1e3, scrollOnUserInput: true, scrollSensitivity: 1, screenReaderMode: false, smoothScrollDuration: 0, macOptionIsMeta: false, macOptionClickForcesSelection: false, minimumContrastRatio: 1, disableStdin: false, allowProposedApi: false, allowTransparency: false, tabStopWidth: 8, theme: {}, rescaleOverlappingGlyphs: false, rightClickSelectsWord: n3.isMac, windowOptions: {}, windowsMode: false, windowsPty: {}, wordSeparator: " ()[]{}',\"`", altClickMovesCursor: true, convertEol: false, termName: "xterm", cancelEvents: false, overviewRulerWidth: 0 };
        const a = ["normal", "bold", "100", "200", "300", "400", "500", "600", "700", "800", "900"];
        class o2 extends r4.Disposable {
          static {
            __name(this, "o");
          }
          constructor(e4) {
            super(), this._onOptionChange = this.register(new s3.EventEmitter()), this.onOptionChange = this._onOptionChange.event;
            const i3 = { ...t3.DEFAULT_OPTIONS };
            for (const t4 in e4) if (t4 in i3) try {
              const s4 = e4[t4];
              i3[t4] = this._sanitizeAndValidateOption(t4, s4);
            } catch (e5) {
              console.error(e5);
            }
            this.rawOptions = i3, this.options = { ...i3 }, this._setupOptions(), this.register((0, r4.toDisposable)(() => {
              this.rawOptions.linkHandler = null, this.rawOptions.documentOverride = null;
            }));
          }
          onSpecificOptionChange(e4, t4) {
            return this.onOptionChange((i3) => {
              i3 === e4 && t4(this.rawOptions[e4]);
            });
          }
          onMultipleOptionChange(e4, t4) {
            return this.onOptionChange((i3) => {
              -1 !== e4.indexOf(i3) && t4();
            });
          }
          _setupOptions() {
            const e4 = /* @__PURE__ */ __name((e5) => {
              if (!(e5 in t3.DEFAULT_OPTIONS)) throw new Error(`No option with key "${e5}"`);
              return this.rawOptions[e5];
            }, "e"), i3 = /* @__PURE__ */ __name((e5, i4) => {
              if (!(e5 in t3.DEFAULT_OPTIONS)) throw new Error(`No option with key "${e5}"`);
              i4 = this._sanitizeAndValidateOption(e5, i4), this.rawOptions[e5] !== i4 && (this.rawOptions[e5] = i4, this._onOptionChange.fire(e5));
            }, "i");
            for (const t4 in this.rawOptions) {
              const s4 = { get: e4.bind(this, t4), set: i3.bind(this, t4) };
              Object.defineProperty(this.options, t4, s4);
            }
          }
          _sanitizeAndValidateOption(e4, i3) {
            switch (e4) {
              case "cursorStyle":
                if (i3 || (i3 = t3.DEFAULT_OPTIONS[e4]), !/* @__PURE__ */ function(e5) {
                  return "block" === e5 || "underline" === e5 || "bar" === e5;
                }(i3)) throw new Error(`"${i3}" is not a valid value for ${e4}`);
                break;
              case "wordSeparator":
                i3 || (i3 = t3.DEFAULT_OPTIONS[e4]);
                break;
              case "fontWeight":
              case "fontWeightBold":
                if ("number" == typeof i3 && 1 <= i3 && i3 <= 1e3) break;
                i3 = a.includes(i3) ? i3 : t3.DEFAULT_OPTIONS[e4];
                break;
              case "cursorWidth":
                i3 = Math.floor(i3);
              case "lineHeight":
              case "tabStopWidth":
                if (i3 < 1) throw new Error(`${e4} cannot be less than 1, value: ${i3}`);
                break;
              case "minimumContrastRatio":
                i3 = Math.max(1, Math.min(21, Math.round(10 * i3) / 10));
                break;
              case "scrollback":
                if ((i3 = Math.min(i3, 4294967295)) < 0) throw new Error(`${e4} cannot be less than 0, value: ${i3}`);
                break;
              case "fastScrollSensitivity":
              case "scrollSensitivity":
                if (i3 <= 0) throw new Error(`${e4} cannot be less than or equal to 0, value: ${i3}`);
                break;
              case "rows":
              case "cols":
                if (!i3 && 0 !== i3) throw new Error(`${e4} must be numeric, value: ${i3}`);
                break;
              case "windowsPty":
                i3 = i3 ?? {};
            }
            return i3;
          }
        }
        t3.OptionsService = o2;
      }, 660: function(e3, t3, i2) {
        var s3 = this && this.__decorate || function(e4, t4, i3, s4) {
          var r5, n4 = arguments.length, a2 = n4 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i3) : s4;
          if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a2 = Reflect.decorate(e4, t4, i3, s4);
          else for (var o2 = e4.length - 1; o2 >= 0; o2--) (r5 = e4[o2]) && (a2 = (n4 < 3 ? r5(a2) : n4 > 3 ? r5(t4, i3, a2) : r5(t4, i3)) || a2);
          return n4 > 3 && a2 && Object.defineProperty(t4, i3, a2), a2;
        }, r4 = this && this.__param || function(e4, t4) {
          return function(i3, s4) {
            t4(i3, s4, e4);
          };
        };
        Object.defineProperty(t3, "__esModule", { value: true }), t3.OscLinkService = void 0;
        const n3 = i2(585);
        let a = t3.OscLinkService = class {
          constructor(e4) {
            this._bufferService = e4, this._nextId = 1, this._entriesWithId = /* @__PURE__ */ new Map(), this._dataByLinkId = /* @__PURE__ */ new Map();
          }
          registerLink(e4) {
            const t4 = this._bufferService.buffer;
            if (void 0 === e4.id) {
              const i4 = t4.addMarker(t4.ybase + t4.y), s5 = { data: e4, id: this._nextId++, lines: [i4] };
              return i4.onDispose(() => this._removeMarkerFromLink(s5, i4)), this._dataByLinkId.set(s5.id, s5), s5.id;
            }
            const i3 = e4, s4 = this._getEntryIdKey(i3), r5 = this._entriesWithId.get(s4);
            if (r5) return this.addLineToLink(r5.id, t4.ybase + t4.y), r5.id;
            const n4 = t4.addMarker(t4.ybase + t4.y), a2 = { id: this._nextId++, key: this._getEntryIdKey(i3), data: i3, lines: [n4] };
            return n4.onDispose(() => this._removeMarkerFromLink(a2, n4)), this._entriesWithId.set(a2.key, a2), this._dataByLinkId.set(a2.id, a2), a2.id;
          }
          addLineToLink(e4, t4) {
            const i3 = this._dataByLinkId.get(e4);
            if (i3 && i3.lines.every((e5) => e5.line !== t4)) {
              const e5 = this._bufferService.buffer.addMarker(t4);
              i3.lines.push(e5), e5.onDispose(() => this._removeMarkerFromLink(i3, e5));
            }
          }
          getLinkData(e4) {
            return this._dataByLinkId.get(e4)?.data;
          }
          _getEntryIdKey(e4) {
            return `${e4.id};;${e4.uri}`;
          }
          _removeMarkerFromLink(e4, t4) {
            const i3 = e4.lines.indexOf(t4);
            -1 !== i3 && (e4.lines.splice(i3, 1), 0 === e4.lines.length && (void 0 !== e4.data.id && this._entriesWithId.delete(e4.key), this._dataByLinkId.delete(e4.id)));
          }
        };
        t3.OscLinkService = a = s3([r4(0, n3.IBufferService)], a);
      }, 343: (e3, t3) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.createDecorator = t3.getServiceDependencies = t3.serviceRegistry = void 0;
        const i2 = "di$target", s3 = "di$dependencies";
        t3.serviceRegistry = /* @__PURE__ */ new Map(), t3.getServiceDependencies = function(e4) {
          return e4[s3] || [];
        }, t3.createDecorator = function(e4) {
          if (t3.serviceRegistry.has(e4)) return t3.serviceRegistry.get(e4);
          const r4 = /* @__PURE__ */ __name(function(e5, t4, n3) {
            if (3 !== arguments.length) throw new Error("@IServiceName-decorator can only be used to decorate a parameter");
            !function(e6, t5, r5) {
              t5[i2] === t5 ? t5[s3].push({ id: e6, index: r5 }) : (t5[s3] = [{ id: e6, index: r5 }], t5[i2] = t5);
            }(r4, e5, n3);
          }, "r");
          return r4.toString = () => e4, t3.serviceRegistry.set(e4, r4), r4;
        };
      }, 585: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.IDecorationService = t3.IUnicodeService = t3.IOscLinkService = t3.IOptionsService = t3.ILogService = t3.LogLevelEnum = t3.IInstantiationService = t3.ICharsetService = t3.ICoreService = t3.ICoreMouseService = t3.IBufferService = void 0;
        const s3 = i2(343);
        var r4;
        t3.IBufferService = (0, s3.createDecorator)("BufferService"), t3.ICoreMouseService = (0, s3.createDecorator)("CoreMouseService"), t3.ICoreService = (0, s3.createDecorator)("CoreService"), t3.ICharsetService = (0, s3.createDecorator)("CharsetService"), t3.IInstantiationService = (0, s3.createDecorator)("InstantiationService"), function(e4) {
          e4[e4.TRACE = 0] = "TRACE", e4[e4.DEBUG = 1] = "DEBUG", e4[e4.INFO = 2] = "INFO", e4[e4.WARN = 3] = "WARN", e4[e4.ERROR = 4] = "ERROR", e4[e4.OFF = 5] = "OFF";
        }(r4 || (t3.LogLevelEnum = r4 = {})), t3.ILogService = (0, s3.createDecorator)("LogService"), t3.IOptionsService = (0, s3.createDecorator)("OptionsService"), t3.IOscLinkService = (0, s3.createDecorator)("OscLinkService"), t3.IUnicodeService = (0, s3.createDecorator)("UnicodeService"), t3.IDecorationService = (0, s3.createDecorator)("DecorationService");
      }, 480: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.UnicodeService = void 0;
        const s3 = i2(460), r4 = i2(225);
        class n3 {
          static {
            __name(this, "n");
          }
          static extractShouldJoin(e4) {
            return 0 != (1 & e4);
          }
          static extractWidth(e4) {
            return e4 >> 1 & 3;
          }
          static extractCharKind(e4) {
            return e4 >> 3;
          }
          static createPropertyValue(e4, t4, i3 = false) {
            return (16777215 & e4) << 3 | (3 & t4) << 1 | (i3 ? 1 : 0);
          }
          constructor() {
            this._providers = /* @__PURE__ */ Object.create(null), this._active = "", this._onChange = new s3.EventEmitter(), this.onChange = this._onChange.event;
            const e4 = new r4.UnicodeV6();
            this.register(e4), this._active = e4.version, this._activeProvider = e4;
          }
          dispose() {
            this._onChange.dispose();
          }
          get versions() {
            return Object.keys(this._providers);
          }
          get activeVersion() {
            return this._active;
          }
          set activeVersion(e4) {
            if (!this._providers[e4]) throw new Error(`unknown Unicode version "${e4}"`);
            this._active = e4, this._activeProvider = this._providers[e4], this._onChange.fire(e4);
          }
          register(e4) {
            this._providers[e4.version] = e4;
          }
          wcwidth(e4) {
            return this._activeProvider.wcwidth(e4);
          }
          getStringCellWidth(e4) {
            let t4 = 0, i3 = 0;
            const s4 = e4.length;
            for (let r5 = 0; r5 < s4; ++r5) {
              let a = e4.charCodeAt(r5);
              if (55296 <= a && a <= 56319) {
                if (++r5 >= s4) return t4 + this.wcwidth(a);
                const i4 = e4.charCodeAt(r5);
                56320 <= i4 && i4 <= 57343 ? a = 1024 * (a - 55296) + i4 - 56320 + 65536 : t4 += this.wcwidth(i4);
              }
              const o2 = this.charProperties(a, i3);
              let h = n3.extractWidth(o2);
              n3.extractShouldJoin(o2) && (h -= n3.extractWidth(i3)), t4 += h, i3 = o2;
            }
            return t4;
          }
          charProperties(e4, t4) {
            return this._activeProvider.charProperties(e4, t4);
          }
        }
        t3.UnicodeService = n3;
      }, 781: (e3, t3, i2) => {
        Object.defineProperty(t3, "__esModule", { value: true }), t3.Terminal = void 0;
        const s3 = i2(437), r4 = i2(969), n3 = i2(460);
        class a extends r4.CoreTerminal {
          static {
            __name(this, "a");
          }
          constructor(e4 = {}) {
            super(e4), this._onBell = this.register(new n3.EventEmitter()), this.onBell = this._onBell.event, this._onCursorMove = this.register(new n3.EventEmitter()), this.onCursorMove = this._onCursorMove.event, this._onTitleChange = this.register(new n3.EventEmitter()), this.onTitleChange = this._onTitleChange.event, this._onA11yCharEmitter = this.register(new n3.EventEmitter()), this.onA11yChar = this._onA11yCharEmitter.event, this._onA11yTabEmitter = this.register(new n3.EventEmitter()), this.onA11yTab = this._onA11yTabEmitter.event, this._setup(), this.register(this._inputHandler.onRequestBell(() => this.bell())), this.register(this._inputHandler.onRequestReset(() => this.reset())), this.register((0, n3.forwardEvent)(this._inputHandler.onCursorMove, this._onCursorMove)), this.register((0, n3.forwardEvent)(this._inputHandler.onTitleChange, this._onTitleChange)), this.register((0, n3.forwardEvent)(this._inputHandler.onA11yChar, this._onA11yCharEmitter)), this.register((0, n3.forwardEvent)(this._inputHandler.onA11yTab, this._onA11yTabEmitter));
          }
          get buffer() {
            return this.buffers.active;
          }
          get markers() {
            return this.buffer.markers;
          }
          addMarker(e4) {
            if (this.buffer === this.buffers.normal) return this.buffer.addMarker(this.buffer.ybase + this.buffer.y + e4);
          }
          bell() {
            this._onBell.fire();
          }
          input(e4, t4 = true) {
            this.coreService.triggerDataEvent(e4, t4);
          }
          resize(e4, t4) {
            e4 === this.cols && t4 === this.rows || super.resize(e4, t4);
          }
          clear() {
            if (0 !== this.buffer.ybase || 0 !== this.buffer.y) {
              this.buffer.lines.set(0, this.buffer.lines.get(this.buffer.ybase + this.buffer.y)), this.buffer.lines.length = 1, this.buffer.ydisp = 0, this.buffer.ybase = 0, this.buffer.y = 0;
              for (let e4 = 1; e4 < this.rows; e4++) this.buffer.lines.push(this.buffer.getBlankLine(s3.DEFAULT_ATTR_DATA));
              this._onScroll.fire({ position: this.buffer.ydisp, source: 0 });
            }
          }
          reset() {
            this.options.rows = this.rows, this.options.cols = this.cols, this._setup(), super.reset();
          }
        }
        t3.Terminal = a;
      } }, t2 = {};
      function i(s3) {
        var r4 = t2[s3];
        if (void 0 !== r4) return r4.exports;
        var n3 = t2[s3] = { exports: {} };
        return e2[s3].call(n3.exports, n3, n3.exports, i), n3.exports;
      }
      __name(i, "i");
      var s2 = {};
      (() => {
        var e3 = s2;
        Object.defineProperty(e3, "__esModule", { value: true }), e3.Terminal = void 0;
        const t3 = i(285), r4 = i(975), n3 = i(90), a = i(781), o2 = i(741), h = i(844), c3 = ["cols", "rows"];
        class l2 extends h.Disposable {
          static {
            __name(this, "l");
          }
          constructor(e4) {
            super(), this._core = this.register(new a.Terminal(e4)), this._addonManager = this.register(new o2.AddonManager()), this._publicOptions = { ...this._core.options };
            const t4 = /* @__PURE__ */ __name((e5) => this._core.options[e5], "t"), i2 = /* @__PURE__ */ __name((e5, t5) => {
              this._checkReadonlyOptions(e5), this._core.options[e5] = t5;
            }, "i");
            for (const e5 in this._core.options) {
              Object.defineProperty(this._publicOptions, e5, { get: /* @__PURE__ */ __name(() => this._core.options[e5], "get"), set: /* @__PURE__ */ __name((t5) => {
                this._checkReadonlyOptions(e5), this._core.options[e5] = t5;
              }, "set") });
              const s3 = { get: t4.bind(this, e5), set: i2.bind(this, e5) };
              Object.defineProperty(this._publicOptions, e5, s3);
            }
          }
          _checkReadonlyOptions(e4) {
            if (c3.includes(e4)) throw new Error(`Option "${e4}" can only be set in the constructor`);
          }
          _checkProposedApi() {
            if (!this._core.optionsService.options.allowProposedApi) throw new Error("You must set the allowProposedApi option to true to use proposed API");
          }
          get onBell() {
            return this._core.onBell;
          }
          get onBinary() {
            return this._core.onBinary;
          }
          get onCursorMove() {
            return this._core.onCursorMove;
          }
          get onData() {
            return this._core.onData;
          }
          get onLineFeed() {
            return this._core.onLineFeed;
          }
          get onResize() {
            return this._core.onResize;
          }
          get onScroll() {
            return this._core.onScroll;
          }
          get onTitleChange() {
            return this._core.onTitleChange;
          }
          get parser() {
            return this._checkProposedApi(), this._parser || (this._parser = new r4.ParserApi(this._core)), this._parser;
          }
          get unicode() {
            return this._checkProposedApi(), new n3.UnicodeApi(this._core);
          }
          get rows() {
            return this._core.rows;
          }
          get cols() {
            return this._core.cols;
          }
          get buffer() {
            return this._checkProposedApi(), this._buffer || (this._buffer = this.register(new t3.BufferNamespaceApi(this._core))), this._buffer;
          }
          get markers() {
            return this._checkProposedApi(), this._core.markers;
          }
          get modes() {
            const e4 = this._core.coreService.decPrivateModes;
            let t4 = "none";
            switch (this._core.coreMouseService.activeProtocol) {
              case "X10":
                t4 = "x10";
                break;
              case "VT200":
                t4 = "vt200";
                break;
              case "DRAG":
                t4 = "drag";
                break;
              case "ANY":
                t4 = "any";
            }
            return { applicationCursorKeysMode: e4.applicationCursorKeys, applicationKeypadMode: e4.applicationKeypad, bracketedPasteMode: e4.bracketedPasteMode, insertMode: this._core.coreService.modes.insertMode, mouseTrackingMode: t4, originMode: e4.origin, reverseWraparoundMode: e4.reverseWraparound, sendFocusMode: e4.sendFocus, wraparoundMode: e4.wraparound };
          }
          get options() {
            return this._publicOptions;
          }
          set options(e4) {
            for (const t4 in e4) this._publicOptions[t4] = e4[t4];
          }
          input(e4, t4 = true) {
            this._core.input(e4, t4);
          }
          resize(e4, t4) {
            this._verifyIntegers(e4, t4), this._core.resize(e4, t4);
          }
          registerMarker(e4 = 0) {
            return this._checkProposedApi(), this._verifyIntegers(e4), this._core.addMarker(e4);
          }
          addMarker(e4) {
            return this.registerMarker(e4);
          }
          dispose() {
            super.dispose();
          }
          scrollLines(e4) {
            this._verifyIntegers(e4), this._core.scrollLines(e4);
          }
          scrollPages(e4) {
            this._verifyIntegers(e4), this._core.scrollPages(e4);
          }
          scrollToTop() {
            this._core.scrollToTop();
          }
          scrollToBottom() {
            this._core.scrollToBottom();
          }
          scrollToLine(e4) {
            this._verifyIntegers(e4), this._core.scrollToLine(e4);
          }
          clear() {
            this._core.clear();
          }
          write(e4, t4) {
            this._core.write(e4, t4);
          }
          writeln(e4, t4) {
            this._core.write(e4), this._core.write("\r\n", t4);
          }
          reset() {
            this._core.reset();
          }
          loadAddon(e4) {
            this._addonManager.loadAddon(this, e4);
          }
          _verifyIntegers(...e4) {
            for (const t4 of e4) if (t4 === 1 / 0 || isNaN(t4) || t4 % 1 != 0) throw new Error("This API only accepts integers");
          }
        }
        e3.Terminal = l2;
      })();
      var r3 = exports2;
      for (var n2 in s2) r3[n2] = s2[n2];
      s2.__esModule && Object.defineProperty(r3, "__esModule", { value: true });
    })();
  }
});

// packages/core/dist/src/utils/terminalSerializer.js
function serializeTerminalToObject(terminal) {
  const buffer = terminal.buffer.active;
  const cursorX = buffer.cursorX;
  const cursorY = buffer.cursorY;
  const defaultFg = "";
  const defaultBg = "";
  const result = [];
  for (let y = 0; y < terminal.rows; y++) {
    const line = buffer.getLine(buffer.viewportY + y);
    const currentLine = [];
    if (!line) {
      result.push(currentLine);
      continue;
    }
    let lastCell = new Cell(null, -1, -1, cursorX, cursorY);
    let currentText = "";
    for (let x = 0; x < terminal.cols; x++) {
      const cellData = line.getCell(x);
      const cell = new Cell(cellData || null, x, y, cursorX, cursorY);
      if (x > 0 && !cell.equals(lastCell)) {
        if (currentText) {
          const token2 = {
            text: currentText,
            bold: lastCell.isAttribute(Attribute.bold),
            italic: lastCell.isAttribute(Attribute.italic),
            underline: lastCell.isAttribute(Attribute.underline),
            dim: lastCell.isAttribute(Attribute.dim),
            inverse: lastCell.isAttribute(Attribute.inverse) || lastCell.isCursor(),
            fg: convertColorToHex(lastCell.fg, lastCell.fgColorMode, defaultFg),
            bg: convertColorToHex(lastCell.bg, lastCell.bgColorMode, defaultBg)
          };
          currentLine.push(token2);
        }
        currentText = "";
      }
      currentText += cell.getChars();
      lastCell = cell;
    }
    if (currentText) {
      const token2 = {
        text: currentText,
        bold: lastCell.isAttribute(Attribute.bold),
        italic: lastCell.isAttribute(Attribute.italic),
        underline: lastCell.isAttribute(Attribute.underline),
        dim: lastCell.isAttribute(Attribute.dim),
        inverse: lastCell.isAttribute(Attribute.inverse) || lastCell.isCursor(),
        fg: convertColorToHex(lastCell.fg, lastCell.fgColorMode, defaultFg),
        bg: convertColorToHex(lastCell.bg, lastCell.bgColorMode, defaultBg)
      };
      currentLine.push(token2);
    }
    result.push(currentLine);
  }
  return result;
}
function convertColorToHex(color, colorMode, defaultColor) {
  if (colorMode === ColorMode.RGB) {
    const r3 = color >> 16 & 255;
    const g = color >> 8 & 255;
    const b = color & 255;
    return `#${r3.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
  }
  if (colorMode === ColorMode.PALETTE) {
    return ANSI_COLORS[color] || defaultColor;
  }
  return defaultColor;
}
var Attribute, ColorMode, Cell, ANSI_COLORS;
var init_terminalSerializer = __esm({
  "packages/core/dist/src/utils/terminalSerializer.js"() {
    "use strict";
    init_esbuild_shims();
    (function(Attribute2) {
      Attribute2[Attribute2["inverse"] = 1] = "inverse";
      Attribute2[Attribute2["bold"] = 2] = "bold";
      Attribute2[Attribute2["italic"] = 4] = "italic";
      Attribute2[Attribute2["underline"] = 8] = "underline";
      Attribute2[Attribute2["dim"] = 16] = "dim";
    })(Attribute || (Attribute = {}));
    (function(ColorMode2) {
      ColorMode2[ColorMode2["DEFAULT"] = 0] = "DEFAULT";
      ColorMode2[ColorMode2["PALETTE"] = 1] = "PALETTE";
      ColorMode2[ColorMode2["RGB"] = 2] = "RGB";
    })(ColorMode || (ColorMode = {}));
    Cell = class {
      static {
        __name(this, "Cell");
      }
      cell;
      x;
      y;
      cursorX;
      cursorY;
      attributes = 0;
      fg = 0;
      bg = 0;
      fgColorMode = ColorMode.DEFAULT;
      bgColorMode = ColorMode.DEFAULT;
      constructor(cell, x, y, cursorX, cursorY) {
        this.cell = cell;
        this.x = x;
        this.y = y;
        this.cursorX = cursorX;
        this.cursorY = cursorY;
        if (!cell) {
          return;
        }
        if (cell.isInverse()) {
          this.attributes += Attribute.inverse;
        }
        if (cell.isBold()) {
          this.attributes += Attribute.bold;
        }
        if (cell.isItalic()) {
          this.attributes += Attribute.italic;
        }
        if (cell.isUnderline()) {
          this.attributes += Attribute.underline;
        }
        if (cell.isDim()) {
          this.attributes += Attribute.dim;
        }
        if (cell.isFgRGB()) {
          this.fgColorMode = ColorMode.RGB;
        } else if (cell.isFgPalette()) {
          this.fgColorMode = ColorMode.PALETTE;
        } else {
          this.fgColorMode = ColorMode.DEFAULT;
        }
        if (cell.isBgRGB()) {
          this.bgColorMode = ColorMode.RGB;
        } else if (cell.isBgPalette()) {
          this.bgColorMode = ColorMode.PALETTE;
        } else {
          this.bgColorMode = ColorMode.DEFAULT;
        }
        if (this.fgColorMode === ColorMode.DEFAULT) {
          this.fg = -1;
        } else {
          this.fg = cell.getFgColor();
        }
        if (this.bgColorMode === ColorMode.DEFAULT) {
          this.bg = -1;
        } else {
          this.bg = cell.getBgColor();
        }
      }
      isCursor() {
        return this.x === this.cursorX && this.y === this.cursorY;
      }
      getChars() {
        return this.cell?.getChars() || " ";
      }
      isAttribute(attribute) {
        return (this.attributes & attribute) !== 0;
      }
      equals(other2) {
        return this.attributes === other2.attributes && this.fg === other2.fg && this.bg === other2.bg && this.fgColorMode === other2.fgColorMode && this.bgColorMode === other2.bgColorMode && this.isCursor() === other2.isCursor();
      }
    };
    __name(serializeTerminalToObject, "serializeTerminalToObject");
    ANSI_COLORS = [
      "#000000",
      "#800000",
      "#008000",
      "#808000",
      "#000080",
      "#800080",
      "#008080",
      "#c0c0c0",
      "#808080",
      "#ff0000",
      "#00ff00",
      "#ffff00",
      "#0000ff",
      "#ff00ff",
      "#00ffff",
      "#ffffff",
      "#000000",
      "#00005f",
      "#000087",
      "#0000af",
      "#0000d7",
      "#0000ff",
      "#005f00",
      "#005f5f",
      "#005f87",
      "#005faf",
      "#005fd7",
      "#005fff",
      "#008700",
      "#00875f",
      "#008787",
      "#0087af",
      "#0087d7",
      "#0087ff",
      "#00af00",
      "#00af5f",
      "#00af87",
      "#00afaf",
      "#00afd7",
      "#00afff",
      "#00d700",
      "#00d75f",
      "#00d787",
      "#00d7af",
      "#00d7d7",
      "#00d7ff",
      "#00ff00",
      "#00ff5f",
      "#00ff87",
      "#00ffaf",
      "#00ffd7",
      "#00ffff",
      "#5f0000",
      "#5f005f",
      "#5f0087",
      "#5f00af",
      "#5f00d7",
      "#5f00ff",
      "#5f5f00",
      "#5f5f5f",
      "#5f5f87",
      "#5f5faf",
      "#5f5fd7",
      "#5f5fff",
      "#5f8700",
      "#5f875f",
      "#5f8787",
      "#5f87af",
      "#5f87d7",
      "#5f87ff",
      "#5faf00",
      "#5faf5f",
      "#5faf87",
      "#5fafaf",
      "#5fafd7",
      "#5fafff",
      "#5fd700",
      "#5fd75f",
      "#5fd787",
      "#5fd7af",
      "#5fd7d7",
      "#5fd7ff",
      "#5fff00",
      "#5fff5f",
      "#5fff87",
      "#5fffaf",
      "#5fffd7",
      "#5fffff",
      "#870000",
      "#87005f",
      "#870087",
      "#8700af",
      "#8700d7",
      "#8700ff",
      "#875f00",
      "#875f5f",
      "#875f87",
      "#875faf",
      "#875fd7",
      "#875fff",
      "#878700",
      "#87875f",
      "#878787",
      "#8787af",
      "#8787d7",
      "#8787ff",
      "#87af00",
      "#87af5f",
      "#87af87",
      "#87afaf",
      "#87afd7",
      "#87afff",
      "#87d700",
      "#87d75f",
      "#87d787",
      "#87d7af",
      "#87d7d7",
      "#87d7ff",
      "#87ff00",
      "#87ff5f",
      "#87ff87",
      "#87ffaf",
      "#87ffd7",
      "#87ffff",
      "#af0000",
      "#af005f",
      "#af0087",
      "#af00af",
      "#af00d7",
      "#af00ff",
      "#af5f00",
      "#af5f5f",
      "#af5f87",
      "#af5faf",
      "#af5fd7",
      "#af5fff",
      "#af8700",
      "#af875f",
      "#af8787",
      "#af87af",
      "#af87d7",
      "#af87ff",
      "#afaf00",
      "#afaf5f",
      "#afaf87",
      "#afafaf",
      "#afafd7",
      "#afafff",
      "#afd700",
      "#afd75f",
      "#afd787",
      "#afd7af",
      "#afd7d7",
      "#afd7ff",
      "#afff00",
      "#afff5f",
      "#afff87",
      "#afffaf",
      "#afffd7",
      "#afffff",
      "#d70000",
      "#d7005f",
      "#d70087",
      "#d700af",
      "#d700d7",
      "#d700ff",
      "#d75f00",
      "#d75f5f",
      "#d75f87",
      "#d75faf",
      "#d75fd7",
      "#d75fff",
      "#d78700",
      "#d7875f",
      "#d78787",
      "#d787af",
      "#d787d7",
      "#d787ff",
      "#d7af00",
      "#d7af5f",
      "#d7af87",
      "#d7afaf",
      "#d7afd7",
      "#d7afff",
      "#d7d700",
      "#d7d75f",
      "#d7d787",
      "#d7d7af",
      "#d7d7d7",
      "#d7d7ff",
      "#d7ff00",
      "#d7ff5f",
      "#d7ff87",
      "#d7ffaf",
      "#d7ffd7",
      "#d7ffff",
      "#ff0000",
      "#ff005f",
      "#ff0087",
      "#ff00af",
      "#ff00d7",
      "#ff00ff",
      "#ff5f00",
      "#ff5f5f",
      "#ff5f87",
      "#ff5faf",
      "#ff5fd7",
      "#ff5fff",
      "#ff8700",
      "#ff875f",
      "#ff8787",
      "#ff87af",
      "#ff87d7",
      "#ff87ff",
      "#ffaf00",
      "#ffaf5f",
      "#ffaf87",
      "#ffafaf",
      "#ffafd7",
      "#ffafff",
      "#ffd700",
      "#ffd75f",
      "#ffd787",
      "#ffd7af",
      "#ffd7d7",
      "#ffd7ff",
      "#ffff00",
      "#ffff5f",
      "#ffff87",
      "#ffffaf",
      "#ffffd7",
      "#ffffff",
      "#080808",
      "#121212",
      "#1c1c1c",
      "#262626",
      "#303030",
      "#3a3a3a",
      "#444444",
      "#4e4e4e",
      "#585858",
      "#626262",
      "#6c6c6c",
      "#767676",
      "#808080",
      "#8a8a8a",
      "#949494",
      "#9e9e9e",
      "#a8a8a8",
      "#b2b2b2",
      "#bcbcbc",
      "#c6c6c6",
      "#d0d0d0",
      "#dadada",
      "#e4e4e4",
      "#eeeeee"
    ];
    __name(convertColorToHex, "convertColorToHex");
  }
});

// packages/core/dist/src/services/shellExecutionService.js
import { spawn as cpSpawn } from "node:child_process";
import { TextDecoder as TextDecoder2 } from "node:util";
import os15 from "node:os";
var import_headless, Terminal, SIGKILL_TIMEOUT_MS, getFullBufferText, ShellExecutionService;
var init_shellExecutionService = __esm({
  "packages/core/dist/src/services/shellExecutionService.js"() {
    "use strict";
    init_esbuild_shims();
    init_strip_ansi();
    init_getPty();
    init_systemEncoding();
    init_textUtils();
    import_headless = __toESM(require_xterm_headless(), 1);
    init_terminalSerializer();
    ({ Terminal } = import_headless.default);
    SIGKILL_TIMEOUT_MS = 200;
    getFullBufferText = /* @__PURE__ */ __name((terminal) => {
      const buffer = terminal.buffer.active;
      const lines = [];
      for (let i = 0; i < buffer.length; i++) {
        const line = buffer.getLine(i);
        const lineContent = line ? line.translateToString() : "";
        lines.push(lineContent);
      }
      return lines.join("\n").trimEnd();
    }, "getFullBufferText");
    ShellExecutionService = class {
      static {
        __name(this, "ShellExecutionService");
      }
      static activePtys = /* @__PURE__ */ new Map();
      /**
       * Executes a shell command using `node-pty`, capturing all output and lifecycle events.
       *
       * @param commandToExecute The exact command string to run.
       * @param cwd The working directory to execute the command in.
       * @param onOutputEvent A callback for streaming structured events about the execution, including data chunks and status updates.
       * @param abortSignal An AbortSignal to terminate the process and its children.
       * @returns An object containing the process ID (pid) and a promise that
       *          resolves with the complete execution result.
       */
      static async execute(commandToExecute, cwd7, onOutputEvent, abortSignal, shouldUseNodePty, shellExecutionConfig) {
        if (shouldUseNodePty) {
          const ptyInfo = await getPty();
          if (ptyInfo) {
            try {
              return this.executeWithPty(commandToExecute, cwd7, onOutputEvent, abortSignal, shellExecutionConfig, ptyInfo);
            } catch (_e) {
            }
          }
        }
        return this.childProcessFallback(commandToExecute, cwd7, onOutputEvent, abortSignal);
      }
      static childProcessFallback(commandToExecute, cwd7, onOutputEvent, abortSignal) {
        try {
          const isWindows8 = os15.platform() === "win32";
          const child = cpSpawn(commandToExecute, [], {
            cwd: cwd7,
            stdio: ["ignore", "pipe", "pipe"],
            windowsVerbatimArguments: true,
            shell: isWindows8 ? true : "bash",
            detached: !isWindows8,
            env: {
              ...process.env,
              QWEN_CODE: "1",
              TERM: "xterm-256color",
              PAGER: "cat"
            }
          });
          const result = new Promise((resolve24) => {
            let stdoutDecoder = null;
            let stderrDecoder = null;
            let stdout = "";
            let stderr = "";
            const outputChunks = [];
            let error = null;
            let exited = false;
            let isStreamingRawContent = true;
            const MAX_SNIFF_SIZE = 4096;
            let sniffedBytes = 0;
            const handleOutput = /* @__PURE__ */ __name((data, stream2) => {
              if (!stdoutDecoder || !stderrDecoder) {
                const encoding = getCachedEncodingForBuffer(data);
                try {
                  stdoutDecoder = new TextDecoder2(encoding);
                  stderrDecoder = new TextDecoder2(encoding);
                } catch {
                  stdoutDecoder = new TextDecoder2("utf-8");
                  stderrDecoder = new TextDecoder2("utf-8");
                }
              }
              outputChunks.push(data);
              if (isStreamingRawContent && sniffedBytes < MAX_SNIFF_SIZE) {
                const sniffBuffer = Buffer.concat(outputChunks.slice(0, 20));
                sniffedBytes = sniffBuffer.length;
                if (isBinary(sniffBuffer)) {
                  isStreamingRawContent = false;
                }
              }
              if (isStreamingRawContent) {
                const decoder = stream2 === "stdout" ? stdoutDecoder : stderrDecoder;
                const decodedChunk = decoder.decode(data, { stream: true });
                if (stream2 === "stdout") {
                  stdout += decodedChunk;
                } else {
                  stderr += decodedChunk;
                }
              }
            }, "handleOutput");
            const handleExit = /* @__PURE__ */ __name((code2, signal) => {
              const { finalBuffer } = cleanup();
              const separator = stdout.endsWith("\n") ? "" : "\n";
              const combinedOutput = stdout + (stderr ? (stdout ? separator : "") + stderr : "");
              const finalStrippedOutput = stripAnsi(combinedOutput).trim();
              if (isStreamingRawContent) {
                if (finalStrippedOutput) {
                  onOutputEvent({ type: "data", chunk: finalStrippedOutput });
                }
              } else {
                onOutputEvent({ type: "binary_detected" });
              }
              resolve24({
                rawOutput: finalBuffer,
                output: finalStrippedOutput,
                exitCode: code2,
                signal: signal ? os15.constants.signals[signal] : null,
                error,
                aborted: abortSignal.aborted,
                pid: void 0,
                executionMethod: "child_process"
              });
            }, "handleExit");
            child.stdout.on("data", (data) => handleOutput(data, "stdout"));
            child.stderr.on("data", (data) => handleOutput(data, "stderr"));
            child.on("error", (err) => {
              error = err;
              handleExit(1, null);
            });
            const abortHandler = /* @__PURE__ */ __name(async () => {
              if (child.pid && !exited) {
                if (isWindows8) {
                  cpSpawn("taskkill", ["/pid", child.pid.toString(), "/f", "/t"]);
                } else {
                  try {
                    process.kill(-child.pid, "SIGTERM");
                    await new Promise((res) => setTimeout(res, SIGKILL_TIMEOUT_MS));
                    if (!exited) {
                      process.kill(-child.pid, "SIGKILL");
                    }
                  } catch (_e) {
                    if (!exited)
                      child.kill("SIGKILL");
                  }
                }
              }
            }, "abortHandler");
            abortSignal.addEventListener("abort", abortHandler, { once: true });
            child.on("exit", (code2, signal) => {
              if (child.pid) {
                this.activePtys.delete(child.pid);
              }
              handleExit(code2, signal);
            });
            function cleanup() {
              exited = true;
              abortSignal.removeEventListener("abort", abortHandler);
              if (stdoutDecoder) {
                const remaining = stdoutDecoder.decode();
                if (remaining) {
                  stdout += remaining;
                }
              }
              if (stderrDecoder) {
                const remaining = stderrDecoder.decode();
                if (remaining) {
                  stderr += remaining;
                }
              }
              const finalBuffer = Buffer.concat(outputChunks);
              return { stdout, stderr, finalBuffer };
            }
            __name(cleanup, "cleanup");
          });
          return { pid: void 0, result };
        } catch (e2) {
          const error = e2;
          return {
            pid: void 0,
            result: Promise.resolve({
              error,
              rawOutput: Buffer.from(""),
              output: "",
              exitCode: 1,
              signal: null,
              aborted: false,
              pid: void 0,
              executionMethod: "none"
            })
          };
        }
      }
      static executeWithPty(commandToExecute, cwd7, onOutputEvent, abortSignal, shellExecutionConfig, ptyInfo) {
        if (!ptyInfo) {
          throw new Error("PTY implementation not found");
        }
        try {
          const cols = shellExecutionConfig.terminalWidth ?? 80;
          const rows = shellExecutionConfig.terminalHeight ?? 30;
          const isWindows8 = os15.platform() === "win32";
          const shell2 = isWindows8 ? "cmd.exe" : "bash";
          const args = isWindows8 ? `/c ${commandToExecute}` : ["-c", commandToExecute];
          const ptyProcess = ptyInfo.module.spawn(shell2, args, {
            cwd: cwd7,
            name: "xterm",
            cols,
            rows,
            env: {
              ...process.env,
              QWEN_CODE: "1",
              TERM: "xterm-256color",
              PAGER: shellExecutionConfig.pager ?? "cat"
            },
            handleFlowControl: true
          });
          const result = new Promise((resolve24) => {
            const headlessTerminal = new Terminal({
              allowProposedApi: true,
              cols,
              rows
            });
            headlessTerminal.scrollToTop();
            this.activePtys.set(ptyProcess.pid, { ptyProcess, headlessTerminal });
            let processingChain = Promise.resolve();
            let decoder = null;
            let output = null;
            const outputChunks = [];
            const error = null;
            let exited = false;
            let isStreamingRawContent = true;
            const MAX_SNIFF_SIZE = 4096;
            let sniffedBytes = 0;
            let isWriting = false;
            let hasStartedOutput = false;
            let renderTimeout = null;
            const render3 = /* @__PURE__ */ __name((finalRender = false) => {
              if (renderTimeout) {
                clearTimeout(renderTimeout);
              }
              const renderFn = /* @__PURE__ */ __name(() => {
                if (!isStreamingRawContent) {
                  return;
                }
                if (!shellExecutionConfig.disableDynamicLineTrimming) {
                  if (!hasStartedOutput) {
                    const bufferText = getFullBufferText(headlessTerminal);
                    if (bufferText.trim().length === 0) {
                      return;
                    }
                    hasStartedOutput = true;
                  }
                }
                let newOutput;
                if (shellExecutionConfig.showColor) {
                  newOutput = serializeTerminalToObject(headlessTerminal);
                } else {
                  const buffer = headlessTerminal.buffer.active;
                  const lines = [];
                  for (let y = 0; y < headlessTerminal.rows; y++) {
                    const line = buffer.getLine(buffer.viewportY + y);
                    const lineContent = line ? line.translateToString(true) : "";
                    lines.push([
                      {
                        text: lineContent,
                        bold: false,
                        italic: false,
                        underline: false,
                        dim: false,
                        inverse: false,
                        fg: "",
                        bg: ""
                      }
                    ]);
                  }
                  newOutput = lines;
                }
                let lastNonEmptyLine = -1;
                for (let i = newOutput.length - 1; i >= 0; i--) {
                  const line = newOutput[i];
                  if (line.map((segment) => segment.text).join("").trim().length > 0) {
                    lastNonEmptyLine = i;
                    break;
                  }
                }
                const trimmedOutput = newOutput.slice(0, lastNonEmptyLine + 1);
                const finalOutput = shellExecutionConfig.disableDynamicLineTrimming ? newOutput : trimmedOutput;
                if (JSON.stringify(output) !== JSON.stringify(finalOutput)) {
                  output = finalOutput;
                  onOutputEvent({
                    type: "data",
                    chunk: finalOutput
                  });
                }
              }, "renderFn");
              if (finalRender) {
                renderFn();
              } else {
                renderTimeout = setTimeout(renderFn, 17);
              }
            }, "render");
            headlessTerminal.onScroll(() => {
              if (!isWriting) {
                render3();
              }
            });
            const handleOutput = /* @__PURE__ */ __name((data) => {
              processingChain = processingChain.then(() => new Promise((resolve25) => {
                if (!decoder) {
                  const encoding = getCachedEncodingForBuffer(data);
                  try {
                    decoder = new TextDecoder2(encoding);
                  } catch {
                    decoder = new TextDecoder2("utf-8");
                  }
                }
                outputChunks.push(data);
                if (isStreamingRawContent && sniffedBytes < MAX_SNIFF_SIZE) {
                  const sniffBuffer = Buffer.concat(outputChunks.slice(0, 20));
                  sniffedBytes = sniffBuffer.length;
                  if (isBinary(sniffBuffer)) {
                    isStreamingRawContent = false;
                    onOutputEvent({ type: "binary_detected" });
                  }
                }
                if (isStreamingRawContent) {
                  const decodedChunk = decoder.decode(data, { stream: true });
                  isWriting = true;
                  headlessTerminal.write(decodedChunk, () => {
                    render3();
                    isWriting = false;
                    resolve25();
                  });
                } else {
                  const totalBytes = outputChunks.reduce((sum, chunk) => sum + chunk.length, 0);
                  onOutputEvent({
                    type: "binary_progress",
                    bytesReceived: totalBytes
                  });
                  resolve25();
                }
              }));
            }, "handleOutput");
            ptyProcess.onData((data) => {
              const bufferData = Buffer.from(data, "utf-8");
              handleOutput(bufferData);
            });
            ptyProcess.onExit(({ exitCode, signal }) => {
              exited = true;
              abortSignal.removeEventListener("abort", abortHandler);
              this.activePtys.delete(ptyProcess.pid);
              processingChain.then(() => {
                render3(true);
                const finalBuffer = Buffer.concat(outputChunks);
                resolve24({
                  rawOutput: finalBuffer,
                  output: getFullBufferText(headlessTerminal),
                  exitCode,
                  signal: signal ?? null,
                  error,
                  aborted: abortSignal.aborted,
                  pid: ptyProcess.pid,
                  executionMethod: ptyInfo?.name ?? "node-pty"
                });
              });
            });
            const abortHandler = /* @__PURE__ */ __name(async () => {
              if (ptyProcess.pid && !exited) {
                if (os15.platform() === "win32") {
                  ptyProcess.kill();
                } else {
                  try {
                    process.kill(-ptyProcess.pid, "SIGINT");
                  } catch (_e) {
                    ptyProcess.kill("SIGINT");
                  }
                }
              }
            }, "abortHandler");
            abortSignal.addEventListener("abort", abortHandler, { once: true });
          });
          return { pid: ptyProcess.pid, result };
        } catch (e2) {
          const error = e2;
          return {
            pid: void 0,
            result: Promise.resolve({
              error,
              rawOutput: Buffer.from(""),
              output: "",
              exitCode: 1,
              signal: null,
              aborted: false,
              pid: void 0,
              executionMethod: "none"
            })
          };
        }
      }
      /**
       * Writes a string to the pseudo-terminal (PTY) of a running process.
       *
       * @param pid The process ID of the target PTY.
       * @param input The string to write to the terminal.
       */
      static writeToPty(pid, input) {
        if (!this.isPtyActive(pid)) {
          return;
        }
        const activePty = this.activePtys.get(pid);
        if (activePty) {
          activePty.ptyProcess.write(input);
        }
      }
      static isPtyActive(pid) {
        try {
          return process.kill(pid, 0);
        } catch (_) {
          return false;
        }
      }
      /**
       * Resizes the pseudo-terminal (PTY) of a running process.
       *
       * @param pid The process ID of the target PTY.
       * @param cols The new number of columns.
       * @param rows The new number of rows.
       */
      static resizePty(pid, cols, rows) {
        if (!this.isPtyActive(pid)) {
          return;
        }
        const activePty = this.activePtys.get(pid);
        if (activePty) {
          try {
            activePty.ptyProcess.resize(cols, rows);
            activePty.headlessTerminal.resize(cols, rows);
          } catch (e2) {
            if (e2 instanceof Error && "code" in e2 && e2.code === "ESRCH") {
            } else {
              throw e2;
            }
          }
        }
      }
      /**
       * Scrolls the pseudo-terminal (PTY) of a running process.
       *
       * @param pid The process ID of the target PTY.
       * @param lines The number of lines to scroll.
       */
      static scrollPty(pid, lines) {
        if (!this.isPtyActive(pid)) {
          return;
        }
        const activePty = this.activePtys.get(pid);
        if (activePty) {
          try {
            activePty.headlessTerminal.scrollLines(lines);
            if (activePty.headlessTerminal.buffer.active.viewportY < 0) {
              activePty.headlessTerminal.scrollToTop();
            }
          } catch (e2) {
            if (e2 instanceof Error && "code" in e2 && e2.code === "ESRCH") {
            } else {
              throw e2;
            }
          }
        }
      }
    };
  }
});

// packages/core/dist/src/utils/formatters.js
var formatMemoryUsage;
var init_formatters = __esm({
  "packages/core/dist/src/utils/formatters.js"() {
    "use strict";
    init_esbuild_shims();
    formatMemoryUsage = /* @__PURE__ */ __name((bytes) => {
      const gb = bytes / (1024 * 1024 * 1024);
      if (bytes < 1024 * 1024) {
        return `${(bytes / 1024).toFixed(1)} KB`;
      }
      if (bytes < 1024 * 1024 * 1024) {
        return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
      }
      return `${gb.toFixed(2)} GB`;
    }, "formatMemoryUsage");
  }
});

// node_modules/shell-quote/quote.js
var require_quote = __commonJS({
  "node_modules/shell-quote/quote.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function quote3(xs) {
      return xs.map(function(s2) {
        if (s2 === "") {
          return "''";
        }
        if (s2 && typeof s2 === "object") {
          return s2.op.replace(/(.)/g, "\\$1");
        }
        if (/["\s\\]/.test(s2) && !/'/.test(s2)) {
          return "'" + s2.replace(/(['])/g, "\\$1") + "'";
        }
        if (/["'\s]/.test(s2)) {
          return '"' + s2.replace(/(["\\$`!])/g, "\\$1") + '"';
        }
        return String(s2).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g, "$1\\$2");
      }).join(" ");
    }, "quote");
  }
});

// node_modules/shell-quote/parse.js
var require_parse4 = __commonJS({
  "node_modules/shell-quote/parse.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var CONTROL = "(?:" + [
      "\\|\\|",
      "\\&\\&",
      ";;",
      "\\|\\&",
      "\\<\\(",
      "\\<\\<\\<",
      ">>",
      ">\\&",
      "<\\&",
      "[&;()|<>]"
    ].join("|") + ")";
    var controlRE = new RegExp("^" + CONTROL + "$");
    var META2 = "|&;()<> \\t";
    var SINGLE_QUOTE2 = '"((\\\\"|[^"])*?)"';
    var DOUBLE_QUOTE2 = "'((\\\\'|[^'])*?)'";
    var hash = /^#$/;
    var SQ = "'";
    var DQ = '"';
    var DS = "$";
    var TOKEN = "";
    var mult = 4294967296;
    for (i = 0; i < 4; i++) {
      TOKEN += (mult * Math.random()).toString(16);
    }
    var i;
    var startsWithToken = new RegExp("^" + TOKEN);
    function matchAll(s2, r3) {
      var origIndex = r3.lastIndex;
      var matches = [];
      var matchObj;
      while (matchObj = r3.exec(s2)) {
        matches.push(matchObj);
        if (r3.lastIndex === matchObj.index) {
          r3.lastIndex += 1;
        }
      }
      r3.lastIndex = origIndex;
      return matches;
    }
    __name(matchAll, "matchAll");
    function getVar(env7, pre, key) {
      var r3 = typeof env7 === "function" ? env7(key) : env7[key];
      if (typeof r3 === "undefined" && key != "") {
        r3 = "";
      } else if (typeof r3 === "undefined") {
        r3 = "$";
      }
      if (typeof r3 === "object") {
        return pre + TOKEN + JSON.stringify(r3) + TOKEN;
      }
      return pre + r3;
    }
    __name(getVar, "getVar");
    function parseInternal(string, env7, opts) {
      if (!opts) {
        opts = {};
      }
      var BS = opts.escape || "\\";
      var BAREWORD = "(\\" + BS + `['"` + META2 + `]|[^\\s'"` + META2 + "])+";
      var chunker = new RegExp([
        "(" + CONTROL + ")",
        // control chars
        "(" + BAREWORD + "|" + SINGLE_QUOTE2 + "|" + DOUBLE_QUOTE2 + ")+"
      ].join("|"), "g");
      var matches = matchAll(string, chunker);
      if (matches.length === 0) {
        return [];
      }
      if (!env7) {
        env7 = {};
      }
      var commented = false;
      return matches.map(function(match2) {
        var s2 = match2[0];
        if (!s2 || commented) {
          return void 0;
        }
        if (controlRE.test(s2)) {
          return { op: s2 };
        }
        var quote3 = false;
        var esc = false;
        var out = "";
        var isGlob = false;
        var i2;
        function parseEnvVar() {
          i2 += 1;
          var varend;
          var varname;
          var char = s2.charAt(i2);
          if (char === "{") {
            i2 += 1;
            if (s2.charAt(i2) === "}") {
              throw new Error("Bad substitution: " + s2.slice(i2 - 2, i2 + 1));
            }
            varend = s2.indexOf("}", i2);
            if (varend < 0) {
              throw new Error("Bad substitution: " + s2.slice(i2));
            }
            varname = s2.slice(i2, varend);
            i2 = varend;
          } else if (/[*@#?$!_-]/.test(char)) {
            varname = char;
            i2 += 1;
          } else {
            var slicedFromI = s2.slice(i2);
            varend = slicedFromI.match(/[^\w\d_]/);
            if (!varend) {
              varname = slicedFromI;
              i2 = s2.length;
            } else {
              varname = slicedFromI.slice(0, varend.index);
              i2 += varend.index - 1;
            }
          }
          return getVar(env7, "", varname);
        }
        __name(parseEnvVar, "parseEnvVar");
        for (i2 = 0; i2 < s2.length; i2++) {
          var c3 = s2.charAt(i2);
          isGlob = isGlob || !quote3 && (c3 === "*" || c3 === "?");
          if (esc) {
            out += c3;
            esc = false;
          } else if (quote3) {
            if (c3 === quote3) {
              quote3 = false;
            } else if (quote3 == SQ) {
              out += c3;
            } else {
              if (c3 === BS) {
                i2 += 1;
                c3 = s2.charAt(i2);
                if (c3 === DQ || c3 === BS || c3 === DS) {
                  out += c3;
                } else {
                  out += BS + c3;
                }
              } else if (c3 === DS) {
                out += parseEnvVar();
              } else {
                out += c3;
              }
            }
          } else if (c3 === DQ || c3 === SQ) {
            quote3 = c3;
          } else if (controlRE.test(c3)) {
            return { op: s2 };
          } else if (hash.test(c3)) {
            commented = true;
            var commentObj = { comment: string.slice(match2.index + i2 + 1) };
            if (out.length) {
              return [out, commentObj];
            }
            return [commentObj];
          } else if (c3 === BS) {
            esc = true;
          } else if (c3 === DS) {
            out += parseEnvVar();
          } else {
            out += c3;
          }
        }
        if (isGlob) {
          return { op: "glob", pattern: out };
        }
        return out;
      }).reduce(function(prev, arg) {
        return typeof arg === "undefined" ? prev : prev.concat(arg);
      }, []);
    }
    __name(parseInternal, "parseInternal");
    module2.exports = /* @__PURE__ */ __name(function parse12(s2, env7, opts) {
      var mapped = parseInternal(s2, env7, opts);
      if (typeof env7 !== "function") {
        return mapped;
      }
      return mapped.reduce(function(acc, s3) {
        if (typeof s3 === "object") {
          return acc.concat(s3);
        }
        var xs = s3.split(RegExp("(" + TOKEN + ".*?" + TOKEN + ")", "g"));
        if (xs.length === 1) {
          return acc.concat(xs[0]);
        }
        return acc.concat(xs.filter(Boolean).map(function(x) {
          if (startsWithToken.test(x)) {
            return JSON.parse(x.split(TOKEN)[1]);
          }
          return x;
        }));
      }, []);
    }, "parse");
  }
});

// node_modules/shell-quote/index.js
var require_shell_quote = __commonJS({
  "node_modules/shell-quote/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    exports2.quote = require_quote();
    exports2.parse = require_parse4();
  }
});

// packages/core/dist/src/utils/shellReadOnlyChecker.js
function containsWriteRedirection(command2) {
  let inSingleQuotes = false;
  let inDoubleQuotes = false;
  let escapeNext = false;
  for (const char of command2) {
    if (escapeNext) {
      escapeNext = false;
      continue;
    }
    if (char === "\\" && !inSingleQuotes) {
      escapeNext = true;
      continue;
    }
    if (char === "'" && !inDoubleQuotes) {
      inSingleQuotes = !inSingleQuotes;
      continue;
    }
    if (char === '"' && !inSingleQuotes) {
      inDoubleQuotes = !inDoubleQuotes;
      continue;
    }
    if (!inSingleQuotes && !inDoubleQuotes && char === ">") {
      return true;
    }
  }
  return false;
}
function normalizeTokens(segment) {
  const parsed = (0, import_shell_quote.parse)(segment);
  const tokens = [];
  for (const token2 of parsed) {
    if (typeof token2 === "string") {
      tokens.push(token2);
    }
  }
  return tokens;
}
function skipEnvironmentAssignments(tokens) {
  let index = 0;
  while (index < tokens.length && ENV_ASSIGNMENT_REGEX.test(tokens[index])) {
    index++;
  }
  if (index >= tokens.length) {
    return { args: [] };
  }
  return {
    root: tokens[index],
    args: tokens.slice(index + 1)
  };
}
function evaluateFindCommand(tokens) {
  const [, ...rest] = tokens;
  for (const token2 of rest) {
    const lower = token2.toLowerCase();
    if (BLOCKED_FIND_FLAGS.has(lower)) {
      return false;
    }
    if (BLOCKED_FIND_PREFIXES.some((prefix) => lower.startsWith(prefix))) {
      return false;
    }
  }
  return true;
}
function evaluateSedCommand(tokens) {
  const [, ...rest] = tokens;
  for (const token2 of rest) {
    if (BLOCKED_SED_PREFIXES.some((prefix) => token2.startsWith(prefix)) || token2 === "--in-place") {
      return false;
    }
  }
  return true;
}
function evaluateGitRemoteArgs(args) {
  for (const arg of args) {
    if (BLOCKED_GIT_REMOTE_ACTIONS.has(arg.toLowerCase())) {
      return false;
    }
  }
  return true;
}
function evaluateGitBranchArgs(args) {
  for (const arg of args) {
    if (BLOCKED_GIT_BRANCH_FLAGS.has(arg)) {
      return false;
    }
  }
  return true;
}
function evaluateGitCommand(tokens) {
  let index = 1;
  while (index < tokens.length && tokens[index].startsWith("-")) {
    const flag = tokens[index].toLowerCase();
    if (flag === "--version" || flag === "--help") {
      return true;
    }
    index++;
  }
  if (index >= tokens.length) {
    return true;
  }
  const subcommand = tokens[index].toLowerCase();
  if (!READ_ONLY_GIT_SUBCOMMANDS.has(subcommand)) {
    return false;
  }
  const args = tokens.slice(index + 1);
  if (subcommand === "remote") {
    return evaluateGitRemoteArgs(args);
  }
  if (subcommand === "branch") {
    return evaluateGitBranchArgs(args);
  }
  return true;
}
function evaluateShellSegment(segment) {
  if (!segment.trim()) {
    return true;
  }
  const stripped = stripShellWrapper(segment);
  if (!stripped) {
    return true;
  }
  if (detectCommandSubstitution(stripped)) {
    return false;
  }
  if (containsWriteRedirection(stripped)) {
    return false;
  }
  const tokens = normalizeTokens(stripped);
  if (tokens.length === 0) {
    return true;
  }
  const { root, args } = skipEnvironmentAssignments(tokens);
  if (!root) {
    return true;
  }
  const normalizedRoot = root.toLowerCase();
  if (!READ_ONLY_ROOT_COMMANDS.has(normalizedRoot)) {
    return false;
  }
  if (normalizedRoot === "find") {
    return evaluateFindCommand([normalizedRoot, ...args]);
  }
  if (normalizedRoot === "sed") {
    return evaluateSedCommand([normalizedRoot, ...args]);
  }
  if (normalizedRoot === "git") {
    return evaluateGitCommand([normalizedRoot, ...args]);
  }
  return true;
}
function isShellCommandReadOnly(command2) {
  if (typeof command2 !== "string" || !command2.trim()) {
    return false;
  }
  const segments = splitCommands(command2);
  for (const segment of segments) {
    const isAllowed = evaluateShellSegment(segment);
    if (!isAllowed) {
      return false;
    }
  }
  return true;
}
var import_shell_quote, READ_ONLY_ROOT_COMMANDS, BLOCKED_FIND_FLAGS, BLOCKED_FIND_PREFIXES, READ_ONLY_GIT_SUBCOMMANDS, BLOCKED_GIT_REMOTE_ACTIONS, BLOCKED_GIT_BRANCH_FLAGS, BLOCKED_SED_PREFIXES, ENV_ASSIGNMENT_REGEX;
var init_shellReadOnlyChecker = __esm({
  "packages/core/dist/src/utils/shellReadOnlyChecker.js"() {
    "use strict";
    init_esbuild_shims();
    import_shell_quote = __toESM(require_shell_quote(), 1);
    init_shell_utils();
    READ_ONLY_ROOT_COMMANDS = /* @__PURE__ */ new Set([
      "awk",
      "basename",
      "cat",
      "cd",
      "column",
      "cut",
      "df",
      "dirname",
      "du",
      "echo",
      "env",
      "find",
      "git",
      "grep",
      "head",
      "less",
      "ls",
      "more",
      "printenv",
      "printf",
      "ps",
      "pwd",
      "rg",
      "ripgrep",
      "sed",
      "sort",
      "stat",
      "tail",
      "tree",
      "uniq",
      "wc",
      "which",
      "where",
      "whoami"
    ]);
    BLOCKED_FIND_FLAGS = /* @__PURE__ */ new Set([
      "-delete",
      "-exec",
      "-execdir",
      "-ok",
      "-okdir"
    ]);
    BLOCKED_FIND_PREFIXES = ["-fprint", "-fprintf"];
    READ_ONLY_GIT_SUBCOMMANDS = /* @__PURE__ */ new Set([
      "blame",
      "branch",
      "cat-file",
      "diff",
      "grep",
      "log",
      "ls-files",
      "remote",
      "rev-parse",
      "show",
      "status",
      "describe"
    ]);
    BLOCKED_GIT_REMOTE_ACTIONS = /* @__PURE__ */ new Set([
      "add",
      "remove",
      "rename",
      "set-url",
      "prune",
      "update"
    ]);
    BLOCKED_GIT_BRANCH_FLAGS = /* @__PURE__ */ new Set([
      "-d",
      "-D",
      "--delete",
      "--move",
      "-m"
    ]);
    BLOCKED_SED_PREFIXES = ["-i"];
    ENV_ASSIGNMENT_REGEX = /^[A-Za-z_][A-Za-z0-9_]*=/;
    __name(containsWriteRedirection, "containsWriteRedirection");
    __name(normalizeTokens, "normalizeTokens");
    __name(skipEnvironmentAssignments, "skipEnvironmentAssignments");
    __name(evaluateFindCommand, "evaluateFindCommand");
    __name(evaluateSedCommand, "evaluateSedCommand");
    __name(evaluateGitRemoteArgs, "evaluateGitRemoteArgs");
    __name(evaluateGitBranchArgs, "evaluateGitBranchArgs");
    __name(evaluateGitCommand, "evaluateGitCommand");
    __name(evaluateShellSegment, "evaluateShellSegment");
    __name(isShellCommandReadOnly, "isShellCommandReadOnly");
  }
});

// packages/core/dist/src/utils/shell-utils.js
import os16 from "node:os";
import { execFile as execFile6, execFileSync as execFileSync2 } from "node:child_process";
import { accessSync, constants as fsConstants2 } from "node:fs";
function getShellConfiguration() {
  if (isWindows3()) {
    const comSpec = process.env["ComSpec"] || "cmd.exe";
    const executable = comSpec.toLowerCase();
    if (executable.endsWith("powershell.exe") || executable.endsWith("pwsh.exe")) {
      return {
        executable: comSpec,
        argsPrefix: ["-NoProfile", "-Command"],
        shell: "powershell"
      };
    }
    return {
      executable: comSpec,
      argsPrefix: ["/d", "/s", "/c"],
      shell: "cmd"
    };
  }
  return { executable: "bash", argsPrefix: ["-c"], shell: "bash" };
}
function escapeShellArg(arg, shell2) {
  if (!arg) {
    return "";
  }
  switch (shell2) {
    case "powershell":
      return `'${arg.replace(/'/g, "''")}'`;
    case "cmd":
      return `"${arg.replace(/"/g, '""')}"`;
    case "bash":
    default:
      return (0, import_shell_quote2.quote)([arg]);
  }
}
function splitCommands(command2) {
  const commands = [];
  let currentCommand = "";
  let inSingleQuotes = false;
  let inDoubleQuotes = false;
  let i = 0;
  while (i < command2.length) {
    const char = command2[i];
    const nextChar = command2[i + 1];
    if (char === "\\" && i < command2.length - 1) {
      currentCommand += char + command2[i + 1];
      i += 2;
      continue;
    }
    if (char === "'" && !inDoubleQuotes) {
      inSingleQuotes = !inSingleQuotes;
    } else if (char === '"' && !inSingleQuotes) {
      inDoubleQuotes = !inDoubleQuotes;
    }
    if (!inSingleQuotes && !inDoubleQuotes) {
      if (char === "&" && nextChar === "&" || char === "|" && nextChar === "|") {
        commands.push(currentCommand.trim());
        currentCommand = "";
        i++;
      } else if (char === ";" || char === "&" || char === "|") {
        commands.push(currentCommand.trim());
        currentCommand = "";
      } else {
        currentCommand += char;
      }
    } else {
      currentCommand += char;
    }
    i++;
  }
  if (currentCommand.trim()) {
    commands.push(currentCommand.trim());
  }
  return commands.filter(Boolean);
}
function getCommandRoot(command2) {
  const trimmedCommand = command2.trim();
  if (!trimmedCommand) {
    return void 0;
  }
  const match2 = trimmedCommand.match(/^"([^"]+)"|^'([^']+)'|^(\S+)/);
  if (match2) {
    const commandRoot = match2[1] || match2[2] || match2[3];
    if (commandRoot) {
      return commandRoot.split(/[\\/]/).pop();
    }
  }
  return void 0;
}
function getCommandRoots(command2) {
  if (!command2) {
    return [];
  }
  return splitCommands(command2).map((c3) => getCommandRoot(c3)).filter((c3) => !!c3);
}
function stripShellWrapper(command2) {
  const pattern = /^\s*(?:sh|bash|zsh|cmd.exe)\s+(?:\/c|-c)\s+/;
  const match2 = command2.match(pattern);
  if (match2) {
    let newCommand2 = command2.substring(match2[0].length).trim();
    if (newCommand2.startsWith('"') && newCommand2.endsWith('"') || newCommand2.startsWith("'") && newCommand2.endsWith("'")) {
      newCommand2 = newCommand2.substring(1, newCommand2.length - 1);
    }
    return newCommand2;
  }
  return command2.trim();
}
function detectCommandSubstitution(command2) {
  let inSingleQuotes = false;
  let inDoubleQuotes = false;
  let inBackticks = false;
  let i = 0;
  while (i < command2.length) {
    const char = command2[i];
    const nextChar = command2[i + 1];
    if (char === "\\" && !inSingleQuotes) {
      i += 2;
      continue;
    }
    if (char === "'" && !inDoubleQuotes && !inBackticks) {
      inSingleQuotes = !inSingleQuotes;
    } else if (char === '"' && !inSingleQuotes && !inBackticks) {
      inDoubleQuotes = !inDoubleQuotes;
    } else if (char === "`" && !inSingleQuotes) {
      inBackticks = !inBackticks;
    }
    if (!inSingleQuotes) {
      if (char === "$" && nextChar === "(") {
        return true;
      }
      if (char === "<" && nextChar === "(" && !inDoubleQuotes && !inBackticks) {
        return true;
      }
      if (char === ">" && nextChar === "(" && !inDoubleQuotes && !inBackticks) {
        return true;
      }
      if (char === "`" && !inBackticks) {
        return true;
      }
    }
    i++;
  }
  return false;
}
function checkCommandPermissions(command2, config, sessionAllowlist) {
  if (detectCommandSubstitution(command2)) {
    return {
      allAllowed: false,
      disallowedCommands: [command2],
      blockReason: "Command substitution using $(), `` ` ``, <(), or >() is not allowed for security reasons",
      isHardDenial: true
    };
  }
  const normalize10 = /* @__PURE__ */ __name((cmd) => cmd.trim().replace(/\s+/g, " "), "normalize");
  const commandsToValidate = splitCommands(command2).map(normalize10);
  const invocation = {
    params: { command: "" }
  };
  const excludeTools = config.getExcludeTools() || [];
  const isWildcardBlocked = SHELL_TOOL_NAMES2.some((name3) => excludeTools.includes(name3));
  if (isWildcardBlocked) {
    return {
      allAllowed: false,
      disallowedCommands: commandsToValidate,
      blockReason: "Shell tool is globally disabled in configuration",
      isHardDenial: true
    };
  }
  for (const cmd of commandsToValidate) {
    invocation.params["command"] = cmd;
    if (doesToolInvocationMatch("run_shell_command", invocation, excludeTools)) {
      return {
        allAllowed: false,
        disallowedCommands: [cmd],
        blockReason: `Command '${cmd}' is blocked by configuration`,
        isHardDenial: true
      };
    }
  }
  const coreTools = config.getCoreTools() || [];
  const isWildcardAllowed = SHELL_TOOL_NAMES2.some((name3) => coreTools.includes(name3));
  if (isWildcardAllowed) {
    return { allAllowed: true, disallowedCommands: [] };
  }
  const disallowedCommands = [];
  if (sessionAllowlist) {
    const normalizedSessionAllowlist = new Set([...sessionAllowlist].flatMap((cmd) => SHELL_TOOL_NAMES2.map((name3) => `${name3}(${cmd})`)));
    for (const cmd of commandsToValidate) {
      invocation.params["command"] = cmd;
      const isSessionAllowed = doesToolInvocationMatch("run_shell_command", invocation, [...normalizedSessionAllowlist]);
      if (isSessionAllowed)
        continue;
      const isGloballyAllowed = doesToolInvocationMatch("run_shell_command", invocation, coreTools);
      if (isGloballyAllowed)
        continue;
      disallowedCommands.push(cmd);
    }
    if (disallowedCommands.length > 0) {
      return {
        allAllowed: false,
        disallowedCommands,
        blockReason: `Command(s) not on the global or session allowlist. Disallowed commands: ${disallowedCommands.map((c3) => JSON.stringify(c3)).join(", ")}`,
        isHardDenial: false
        // This is a soft denial; confirmation is possible.
      };
    }
  } else {
    const hasSpecificAllowedCommands = coreTools.filter((tool) => SHELL_TOOL_NAMES2.some((name3) => tool.startsWith(`${name3}(`))).length > 0;
    if (hasSpecificAllowedCommands) {
      for (const cmd of commandsToValidate) {
        invocation.params["command"] = cmd;
        const isGloballyAllowed = doesToolInvocationMatch("run_shell_command", invocation, coreTools);
        if (!isGloballyAllowed) {
          disallowedCommands.push(cmd);
        }
      }
      if (disallowedCommands.length > 0) {
        return {
          allAllowed: false,
          disallowedCommands,
          blockReason: `Command(s) not in the allowed commands list. Disallowed commands: ${disallowedCommands.map((c3) => JSON.stringify(c3)).join(", ")}`,
          isHardDenial: false
          // This is a soft denial.
        };
      }
    }
  }
  return { allAllowed: true, disallowedCommands: [] };
}
function execCommand(command2, args, options2 = {}) {
  return new Promise((resolve24, reject) => {
    const child = execFile6(command2, args, { encoding: "utf8", ...options2 }, (error, stdout, stderr) => {
      if (error) {
        if (!options2.preserveOutputOnError) {
          reject(error);
        } else {
          resolve24({
            stdout: stdout ?? "",
            stderr: stderr ?? "",
            code: typeof error.code === "number" ? error.code : 1
          });
        }
        return;
      }
      resolve24({ stdout: stdout ?? "", stderr: stderr ?? "", code: 0 });
    });
    child.on("error", reject);
  });
}
function resolveCommandPath(command2) {
  try {
    const isWin = process.platform === "win32";
    const checkCommand = isWin ? "where" : "command";
    const checkArgs = isWin ? [command2] : ["-v", command2];
    let result = null;
    try {
      result = execFileSync2(checkCommand, checkArgs, {
        encoding: "utf8",
        shell: isWin
      }).trim();
    } catch {
      console.warn(`Command ${checkCommand} not found`);
    }
    if (!result)
      return { path: null, error: void 0 };
    if (!isWin) {
      accessSync(result, fsConstants2.X_OK);
    }
    return { path: result, error: void 0 };
  } catch (error) {
    return {
      path: null,
      error: error instanceof Error ? error : new Error(String(error))
    };
  }
}
function isCommandAvailable(command2) {
  const { path: path108, error } = resolveCommandPath(command2);
  return { available: path108 !== null, error };
}
function isCommandAllowed(command2, config) {
  const { allAllowed, blockReason } = checkCommandPermissions(command2, config);
  if (allAllowed) {
    return { allowed: true };
  }
  return { allowed: false, reason: blockReason };
}
function isCommandNeedsPermission(command2) {
  const isAllowed = isShellCommandReadOnly(command2);
  if (isAllowed) {
    return { requiresPermission: false };
  }
  return {
    requiresPermission: true,
    reason: "Command requires permission to execute."
  };
}
var import_shell_quote2, SHELL_TOOL_NAMES2, isWindows3;
var init_shell_utils = __esm({
  "packages/core/dist/src/utils/shell-utils.js"() {
    "use strict";
    init_esbuild_shims();
    import_shell_quote2 = __toESM(require_shell_quote(), 1);
    init_tool_utils();
    init_shellReadOnlyChecker();
    SHELL_TOOL_NAMES2 = ["run_shell_command", "ShellTool"];
    __name(getShellConfiguration, "getShellConfiguration");
    isWindows3 = /* @__PURE__ */ __name(() => os16.platform() === "win32", "isWindows");
    __name(escapeShellArg, "escapeShellArg");
    __name(splitCommands, "splitCommands");
    __name(getCommandRoot, "getCommandRoot");
    __name(getCommandRoots, "getCommandRoots");
    __name(stripShellWrapper, "stripShellWrapper");
    __name(detectCommandSubstitution, "detectCommandSubstitution");
    __name(checkCommandPermissions, "checkCommandPermissions");
    __name(execCommand, "execCommand");
    __name(resolveCommandPath, "resolveCommandPath");
    __name(isCommandAvailable, "isCommandAvailable");
    __name(isCommandAllowed, "isCommandAllowed");
    __name(isCommandNeedsPermission, "isCommandNeedsPermission");
  }
});

// packages/core/dist/src/tools/shell.js
import fs22 from "node:fs";
import path18 from "node:path";
import os17, { EOL } from "node:os";
import crypto12 from "node:crypto";
function getShellToolDescription() {
  const toolDescription = `

      **Background vs Foreground Execution:**
      You should decide whether commands should run in background or foreground based on their nature:
      
      **Use background execution (is_background: true) for:**
      - Long-running development servers: \`npm run start\`, \`npm run dev\`, \`yarn dev\`, \`bun run start\`
      - Build watchers: \`npm run watch\`, \`webpack --watch\`
      - Database servers: \`mongod\`, \`mysql\`, \`redis-server\`
      - Web servers: \`python -m http.server\`, \`php -S localhost:8000\`
      - Any command expected to run indefinitely until manually stopped
      
      **Use foreground execution (is_background: false) for:**
      - One-time commands: \`ls\`, \`cat\`, \`grep\`
      - Build commands: \`npm run build\`, \`make\`
      - Installation commands: \`npm install\`, \`pip install\`
      - Git operations: \`git commit\`, \`git push\`
      - Test runs: \`npm test\`, \`pytest\`
      
      The following information is returned:

      Command: Executed command.
      Directory: Directory where command was executed, or \`(root)\`.
      Stdout: Output on stdout stream. Can be \`(empty)\` or partial on error and for any unwaited background processes.
      Stderr: Output on stderr stream. Can be \`(empty)\` or partial on error and for any unwaited background processes.
      Error: Error or \`(none)\` if no error was reported for the subprocess.
      Exit Code: Exit code or \`(none)\` if terminated by signal.
      Signal: Signal number or \`(none)\` if no signal was received.
      Background PIDs: List of background processes started or \`(none)\`.
      Process Group PGID: Process group started or \`(none)\``;
  if (os17.platform() === "win32") {
    return `This tool executes a given shell command as \`cmd.exe /c <command>\`. Command can start background processes using \`start /b\`.${toolDescription}`;
  } else {
    return `This tool executes a given shell command as \`bash -c <command>\`. Command can start background processes using \`&\`. Command is executed as a subprocess that leads its own process group. Command process group can be terminated as \`kill -- -PGID\` or signaled as \`kill -s SIGNAL -- -PGID\`.${toolDescription}`;
  }
}
function getCommandDescription() {
  const cmd_substitution_warning = "\n*** WARNING: Command substitution using $(), `` ` ``, <(), or >() is not allowed for security reasons.";
  if (os17.platform() === "win32") {
    return "Exact command to execute as `cmd.exe /c <command>`" + cmd_substitution_warning;
  } else {
    return "Exact bash command to execute as `bash -c <command>`" + cmd_substitution_warning;
  }
}
var OUTPUT_UPDATE_INTERVAL_MS, ShellToolInvocation, ShellTool;
var init_shell = __esm({
  "packages/core/dist/src/tools/shell.js"() {
    "use strict";
    init_esbuild_shims();
    init_tool_names();
    init_tool_error();
    init_tools();
    init_errors();
    init_summarizer();
    init_shellExecutionService();
    init_formatters();
    init_shell_utils();
    OUTPUT_UPDATE_INTERVAL_MS = 1e3;
    ShellToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "ShellToolInvocation");
      }
      config;
      allowlist;
      constructor(config, params, allowlist) {
        super(params);
        this.config = config;
        this.allowlist = allowlist;
      }
      getDescription() {
        let description = `${this.params.command}`;
        if (this.params.directory) {
          description += ` [in ${this.params.directory}]`;
        }
        if (this.params.is_background) {
          description += ` [background]`;
        }
        if (this.params.description) {
          description += ` (${this.params.description.replace(/\n/g, " ")})`;
        }
        return description;
      }
      async shouldConfirmExecute(_abortSignal) {
        const command2 = stripShellWrapper(this.params.command);
        const rootCommands = [...new Set(getCommandRoots(command2))];
        const commandsToConfirm = rootCommands.filter((command3) => !this.allowlist.has(command3));
        if (commandsToConfirm.length === 0) {
          return false;
        }
        const permissionCheck = isCommandNeedsPermission(command2);
        if (!permissionCheck.requiresPermission) {
          return false;
        }
        const confirmationDetails = {
          type: "exec",
          title: "Confirm Shell Command",
          command: this.params.command,
          rootCommand: commandsToConfirm.join(", "),
          onConfirm: /* @__PURE__ */ __name(async (outcome) => {
            if (outcome === ToolConfirmationOutcome.ProceedAlways) {
              commandsToConfirm.forEach((command3) => this.allowlist.add(command3));
            }
          }, "onConfirm")
        };
        return confirmationDetails;
      }
      async execute(signal, updateOutput2, shellExecutionConfig, setPidCallback) {
        const strippedCommand = stripShellWrapper(this.params.command);
        if (signal.aborted) {
          return {
            llmContent: "Command was cancelled by user before it could start.",
            returnDisplay: "Command cancelled by user."
          };
        }
        const isWindows8 = os17.platform() === "win32";
        const tempFileName = `shell_pgrep_${crypto12.randomBytes(6).toString("hex")}.tmp`;
        const tempFilePath = path18.join(os17.tmpdir(), tempFileName);
        try {
          const processedCommand = this.addCoAuthorToGitCommit(strippedCommand);
          const shouldRunInBackground = this.params.is_background;
          let finalCommand = processedCommand;
          if (shouldRunInBackground && !finalCommand.trim().endsWith("&")) {
            finalCommand = finalCommand.trim() + " &";
          }
          const commandToExecute = isWindows8 ? finalCommand : (() => {
            let command2 = finalCommand.trim();
            if (!command2.endsWith("&"))
              command2 += ";";
            return `{ ${command2} }; __code=$?; pgrep -g 0 >${tempFilePath} 2>&1; exit $__code;`;
          })();
          const cwd7 = this.params.directory || this.config.getTargetDir();
          let cumulativeOutput = "";
          let lastUpdateTime = Date.now();
          let isBinaryStream = false;
          const { result: resultPromise, pid } = await ShellExecutionService.execute(commandToExecute, cwd7, (event) => {
            if (!updateOutput2) {
              return;
            }
            let shouldUpdate = false;
            switch (event.type) {
              case "data":
                if (isBinaryStream)
                  break;
                cumulativeOutput = event.chunk;
                shouldUpdate = true;
                break;
              case "binary_detected":
                isBinaryStream = true;
                cumulativeOutput = "[Binary output detected. Halting stream...]";
                shouldUpdate = true;
                break;
              case "binary_progress":
                isBinaryStream = true;
                cumulativeOutput = `[Receiving binary output... ${formatMemoryUsage(event.bytesReceived)} received]`;
                if (Date.now() - lastUpdateTime > OUTPUT_UPDATE_INTERVAL_MS) {
                  shouldUpdate = true;
                }
                break;
              default: {
                throw new Error("An unhandled ShellOutputEvent was found.");
              }
            }
            if (shouldUpdate) {
              updateOutput2(typeof cumulativeOutput === "string" ? cumulativeOutput : { ansiOutput: cumulativeOutput });
              lastUpdateTime = Date.now();
            }
          }, signal, this.config.getShouldUseNodePtyShell(), shellExecutionConfig ?? {});
          if (pid && setPidCallback) {
            setPidCallback(pid);
          }
          const result = await resultPromise;
          const backgroundPIDs = [];
          if (os17.platform() !== "win32") {
            if (fs22.existsSync(tempFilePath)) {
              const pgrepLines = fs22.readFileSync(tempFilePath, "utf8").split(EOL).filter(Boolean);
              for (const line of pgrepLines) {
                if (!/^\d+$/.test(line)) {
                  console.error(`pgrep: ${line}`);
                }
                const pid2 = Number(line);
                if (pid2 !== result.pid) {
                  backgroundPIDs.push(pid2);
                }
              }
            } else {
              if (!signal.aborted) {
                console.error("missing pgrep output");
              }
            }
          }
          let llmContent = "";
          if (result.aborted) {
            llmContent = "Command was cancelled by user before it could complete.";
            if (result.output.trim()) {
              llmContent += ` Below is the output before it was cancelled:
${result.output}`;
            } else {
              llmContent += " There was no output before it was cancelled.";
            }
          } else {
            const finalError = result.error ? result.error.message.replace(commandToExecute, this.params.command) : "(none)";
            llmContent = [
              `Command: ${this.params.command}`,
              `Directory: ${this.params.directory || "(root)"}`,
              `Output: ${result.output || "(empty)"}`,
              `Error: ${finalError}`,
              // Use the cleaned error string.
              `Exit Code: ${result.exitCode ?? "(none)"}`,
              `Signal: ${result.signal ?? "(none)"}`,
              `Background PIDs: ${backgroundPIDs.length ? backgroundPIDs.join(", ") : "(none)"}`,
              `Process Group PGID: ${result.pid ?? "(none)"}`
            ].join("\n");
          }
          let returnDisplayMessage = "";
          if (this.config.getDebugMode()) {
            returnDisplayMessage = llmContent;
          } else {
            if (result.output.trim()) {
              returnDisplayMessage = result.output;
            } else {
              if (result.aborted) {
                returnDisplayMessage = "Command cancelled by user.";
              } else if (result.signal) {
                returnDisplayMessage = `Command terminated by signal: ${result.signal}`;
              } else if (result.error) {
                returnDisplayMessage = `Command failed: ${getErrorMessage(result.error)}`;
              } else if (result.exitCode !== null && result.exitCode !== 0) {
                returnDisplayMessage = `Command exited with code: ${result.exitCode}`;
              }
            }
          }
          const summarizeConfig = this.config.getSummarizeToolOutputConfig();
          const executionError = result.error ? {
            error: {
              message: result.error.message,
              type: ToolErrorType.SHELL_EXECUTE_ERROR
            }
          } : {};
          if (summarizeConfig && summarizeConfig[ShellTool.Name]) {
            const summary = await summarizeToolOutput(llmContent, this.config.getGeminiClient(), signal, summarizeConfig[ShellTool.Name].tokenBudget);
            return {
              llmContent: summary,
              returnDisplay: returnDisplayMessage,
              ...executionError
            };
          }
          return {
            llmContent,
            returnDisplay: returnDisplayMessage,
            ...executionError
          };
        } finally {
          if (fs22.existsSync(tempFilePath)) {
            fs22.unlinkSync(tempFilePath);
          }
        }
      }
      addCoAuthorToGitCommit(command2) {
        const gitCoAuthorSettings = this.config.getGitCoAuthor();
        if (!gitCoAuthorSettings.enabled) {
          return command2;
        }
        const gitCommitPattern = /^git\s+commit/;
        if (!gitCommitPattern.test(command2.trim())) {
          return command2;
        }
        const coAuthor = `

Co-authored-by: ${gitCoAuthorSettings.name} <${gitCoAuthorSettings.email}>`;
        const messagePattern = /(-m\s+)(['"])((?:\\.|[^\\])*?)(\2)/;
        const match2 = command2.match(messagePattern);
        if (match2) {
          const [fullMatch, prefix, quote3, existingMessage, closingQuote] = match2;
          const newMessage = existingMessage + coAuthor;
          const replacement = prefix + quote3 + newMessage + closingQuote;
          return command2.replace(fullMatch, replacement);
        }
        return command2;
      }
    };
    __name(getShellToolDescription, "getShellToolDescription");
    __name(getCommandDescription, "getCommandDescription");
    ShellTool = class _ShellTool extends BaseDeclarativeTool {
      static {
        __name(this, "ShellTool");
      }
      config;
      static Name = ToolNames.SHELL;
      allowlist = /* @__PURE__ */ new Set();
      constructor(config) {
        super(
          _ShellTool.Name,
          ToolDisplayNames.SHELL,
          getShellToolDescription(),
          Kind.Execute,
          {
            type: "object",
            properties: {
              command: {
                type: "string",
                description: getCommandDescription()
              },
              is_background: {
                type: "boolean",
                description: "Whether to run the command in background. Default is false. Set to true for long-running processes like development servers, watchers, or daemons that should continue running without blocking further commands."
              },
              description: {
                type: "string",
                description: "Brief description of the command for the user. Be specific and concise. Ideally a single sentence. Can be up to 3 sentences for clarity. No line breaks."
              },
              directory: {
                type: "string",
                description: "(OPTIONAL) The absolute path of the directory to run the command in. If not provided, the project root directory is used. Must be a directory within the workspace and must already exist."
              }
            },
            required: ["command", "is_background"]
          },
          false,
          // output is not markdown
          true
        );
        this.config = config;
      }
      validateToolParamValues(params) {
        const commandCheck = isCommandAllowed(params.command, this.config);
        if (!commandCheck.allowed) {
          if (!commandCheck.reason) {
            console.error("Unexpected: isCommandAllowed returned false without a reason");
            return `Command is not allowed: ${params.command}`;
          }
          return commandCheck.reason;
        }
        if (!params.command.trim()) {
          return "Command cannot be empty.";
        }
        if (getCommandRoots(params.command).length === 0) {
          return "Could not identify command root to obtain permission from user.";
        }
        if (params.directory) {
          if (!path18.isAbsolute(params.directory)) {
            return "Directory must be an absolute path.";
          }
          const workspaceDirs = this.config.getWorkspaceContext().getDirectories();
          const isWithinWorkspace = workspaceDirs.some((wsDir) => params.directory.startsWith(wsDir));
          if (!isWithinWorkspace) {
            return `Directory '${params.directory}' is not within any of the registered workspace directories.`;
          }
        }
        return null;
      }
      createInvocation(params) {
        return new ShellToolInvocation(this.config, params, this.allowlist);
      }
    };
  }
});

// packages/core/dist/src/core/coreToolScheduler.js
import * as fs23 from "node:fs/promises";
import * as path19 from "node:path";
function createFunctionResponsePart(callId, toolName, output) {
  return {
    functionResponse: {
      id: callId,
      name: toolName,
      response: { output }
    }
  };
}
function convertToFunctionResponse(toolName, callId, llmContent) {
  const contentToProcess = Array.isArray(llmContent) && llmContent.length === 1 ? llmContent[0] : llmContent;
  if (typeof contentToProcess === "string") {
    return [createFunctionResponsePart(callId, toolName, contentToProcess)];
  }
  if (Array.isArray(contentToProcess)) {
    const functionResponse = createFunctionResponsePart(callId, toolName, "Tool execution succeeded.");
    return [functionResponse, ...toParts2(contentToProcess)];
  }
  if (contentToProcess.functionResponse) {
    if (contentToProcess.functionResponse.response?.["content"]) {
      const stringifiedOutput = getResponseTextFromParts(contentToProcess.functionResponse.response["content"]) || "";
      return [createFunctionResponsePart(callId, toolName, stringifiedOutput)];
    }
    return [contentToProcess];
  }
  if (contentToProcess.inlineData || contentToProcess.fileData) {
    const mimeType = contentToProcess.inlineData?.mimeType || contentToProcess.fileData?.mimeType || "unknown";
    const functionResponse = createFunctionResponsePart(callId, toolName, `Binary content of type ${mimeType} was processed.`);
    return [functionResponse, contentToProcess];
  }
  if (contentToProcess.text !== void 0) {
    return [
      createFunctionResponsePart(callId, toolName, contentToProcess.text)
    ];
  }
  return [
    createFunctionResponsePart(callId, toolName, "Tool execution succeeded.")
  ];
}
function toParts2(input) {
  const parts = [];
  for (const part of Array.isArray(input) ? input : [input]) {
    if (typeof part === "string") {
      parts.push({ text: part });
    } else if (part) {
      parts.push(part);
    }
  }
  return parts;
}
async function truncateAndSaveToFile(content, callId, projectTempDir, threshold, truncateLines) {
  if (content.length <= threshold) {
    return { content };
  }
  let lines = content.split("\n");
  let fileContent = content;
  if (lines.length <= truncateLines) {
    const wrapWidth = 120;
    const wrappedLines = [];
    for (const line of lines) {
      if (line.length > wrapWidth) {
        for (let i = 0; i < line.length; i += wrapWidth) {
          wrappedLines.push(line.substring(i, i + wrapWidth));
        }
      } else {
        wrappedLines.push(line);
      }
    }
    lines = wrappedLines;
    fileContent = lines.join("\n");
  }
  const head = Math.floor(truncateLines / 5);
  const beginning = lines.slice(0, head);
  const end = lines.slice(-(truncateLines - head));
  const truncatedContent = beginning.join("\n") + "\n... [CONTENT TRUNCATED] ...\n" + end.join("\n");
  const safeFileName = `${path19.basename(callId)}.output`;
  const outputFile = path19.join(projectTempDir, safeFileName);
  try {
    await fs23.writeFile(outputFile, fileContent);
    return {
      content: `Tool output was too large and has been truncated.
The full output has been saved to: ${outputFile}
To read the complete output, use the ${ReadFileTool.Name} tool with the absolute file path above.
The truncated output below shows the beginning and end of the content. The marker '... [CONTENT TRUNCATED] ...' indicates where content was removed.
This allows you to efficiently examine different parts of the output without loading the entire file.
Truncated part of the output:
${truncatedContent}`,
      outputFile
    };
  } catch (_error) {
    return {
      content: truncatedContent + `
[Note: Could not save full output to file]`
    };
  }
}
var import_fast_levenshtein, createErrorResponse, CoreToolScheduler;
var init_coreToolScheduler = __esm({
  "packages/core/dist/src/core/coreToolScheduler.js"() {
    "use strict";
    init_esbuild_shims();
    init_src();
    init_generateContentResponseUtilities();
    init_modifiable_tool();
    init_lib();
    init_tool_utils();
    import_fast_levenshtein = __toESM(require_levenshtein(), 1);
    init_prompts();
    init_shell();
    __name(createFunctionResponsePart, "createFunctionResponsePart");
    __name(convertToFunctionResponse, "convertToFunctionResponse");
    __name(toParts2, "toParts");
    createErrorResponse = /* @__PURE__ */ __name((request4, error, errorType) => ({
      callId: request4.callId,
      error,
      responseParts: [
        {
          functionResponse: {
            id: request4.callId,
            name: request4.name,
            response: { error: error.message }
          }
        }
      ],
      resultDisplay: error.message,
      errorType,
      contentLength: error.message.length
    }), "createErrorResponse");
    __name(truncateAndSaveToFile, "truncateAndSaveToFile");
    CoreToolScheduler = class {
      static {
        __name(this, "CoreToolScheduler");
      }
      toolRegistry;
      toolCalls = [];
      outputUpdateHandler;
      onAllToolCallsComplete;
      onToolCallsUpdate;
      getPreferredEditor;
      config;
      onEditorClose;
      isFinalizingToolCalls = false;
      isScheduling = false;
      requestQueue = [];
      constructor(options2) {
        this.config = options2.config;
        this.toolRegistry = options2.config.getToolRegistry();
        this.outputUpdateHandler = options2.outputUpdateHandler;
        this.onAllToolCallsComplete = options2.onAllToolCallsComplete;
        this.onToolCallsUpdate = options2.onToolCallsUpdate;
        this.getPreferredEditor = options2.getPreferredEditor;
        this.onEditorClose = options2.onEditorClose;
      }
      setStatusInternal(targetCallId, newStatus, auxiliaryData) {
        this.toolCalls = this.toolCalls.map((currentCall) => {
          if (currentCall.request.callId !== targetCallId || currentCall.status === "success" || currentCall.status === "error" || currentCall.status === "cancelled") {
            return currentCall;
          }
          const existingStartTime = currentCall.startTime;
          const toolInstance = currentCall.tool;
          const invocation = currentCall.invocation;
          const outcome = currentCall.outcome;
          switch (newStatus) {
            case "success": {
              const durationMs = existingStartTime ? Date.now() - existingStartTime : void 0;
              return {
                request: currentCall.request,
                tool: toolInstance,
                invocation,
                status: "success",
                response: auxiliaryData,
                durationMs,
                outcome
              };
            }
            case "error": {
              const durationMs = existingStartTime ? Date.now() - existingStartTime : void 0;
              return {
                request: currentCall.request,
                status: "error",
                tool: toolInstance,
                response: auxiliaryData,
                durationMs,
                outcome
              };
            }
            case "awaiting_approval":
              return {
                request: currentCall.request,
                tool: toolInstance,
                status: "awaiting_approval",
                confirmationDetails: auxiliaryData,
                startTime: existingStartTime,
                outcome,
                invocation
              };
            case "scheduled":
              return {
                request: currentCall.request,
                tool: toolInstance,
                status: "scheduled",
                startTime: existingStartTime,
                outcome,
                invocation
              };
            case "cancelled": {
              const durationMs = existingStartTime ? Date.now() - existingStartTime : void 0;
              let resultDisplay = void 0;
              if (currentCall.status === "awaiting_approval") {
                const waitingCall = currentCall;
                if (waitingCall.confirmationDetails.type === "edit") {
                  resultDisplay = {
                    fileDiff: waitingCall.confirmationDetails.fileDiff,
                    fileName: waitingCall.confirmationDetails.fileName,
                    originalContent: waitingCall.confirmationDetails.originalContent,
                    newContent: waitingCall.confirmationDetails.newContent
                  };
                }
              } else if (currentCall.status === "executing") {
                const executingCall = currentCall;
                if (executingCall.liveOutput !== void 0) {
                  resultDisplay = executingCall.liveOutput;
                }
              }
              const errorMessage = `[Operation Cancelled] Reason: ${auxiliaryData}`;
              return {
                request: currentCall.request,
                tool: toolInstance,
                invocation,
                status: "cancelled",
                response: {
                  callId: currentCall.request.callId,
                  responseParts: [
                    {
                      functionResponse: {
                        id: currentCall.request.callId,
                        name: currentCall.request.name,
                        response: {
                          error: errorMessage
                        }
                      }
                    }
                  ],
                  resultDisplay,
                  error: void 0,
                  errorType: void 0,
                  contentLength: errorMessage.length
                },
                durationMs,
                outcome
              };
            }
            case "validating":
              return {
                request: currentCall.request,
                tool: toolInstance,
                status: "validating",
                startTime: existingStartTime,
                outcome,
                invocation
              };
            case "executing":
              return {
                request: currentCall.request,
                tool: toolInstance,
                status: "executing",
                startTime: existingStartTime,
                outcome,
                invocation
              };
            default: {
              const exhaustiveCheck = newStatus;
              return exhaustiveCheck;
            }
          }
        });
        this.notifyToolCallsUpdate();
        this.checkAndNotifyCompletion();
      }
      setArgsInternal(targetCallId, args) {
        this.toolCalls = this.toolCalls.map((call) => {
          if (call.request.callId !== targetCallId || call.status === "error") {
            return call;
          }
          const invocationOrError = this.buildInvocation(call.tool, args);
          if (invocationOrError instanceof Error) {
            const response = createErrorResponse(call.request, invocationOrError, ToolErrorType.INVALID_TOOL_PARAMS);
            return {
              request: { ...call.request, args },
              status: "error",
              tool: call.tool,
              response
            };
          }
          return {
            ...call,
            request: { ...call.request, args },
            invocation: invocationOrError
          };
        });
      }
      isRunning() {
        return this.isFinalizingToolCalls || this.toolCalls.some((call) => call.status === "executing" || call.status === "awaiting_approval");
      }
      buildInvocation(tool, args) {
        try {
          return tool.build(args);
        } catch (e2) {
          if (e2 instanceof Error) {
            return e2;
          }
          return new Error(String(e2));
        }
      }
      /**
       * Generates a suggestion string for a tool name that was not found in the registry.
       * It finds the closest matches based on Levenshtein distance.
       * @param unknownToolName The tool name that was not found.
       * @param topN The number of suggestions to return. Defaults to 3.
       * @returns A suggestion string like " Did you mean 'tool'?" or " Did you mean one of: 'tool1', 'tool2'?", or an empty string if no suggestions are found.
       */
      getToolSuggestion(unknownToolName, topN = 3) {
        const allToolNames = this.toolRegistry.getAllToolNames();
        const matches = allToolNames.map((toolName) => ({
          name: toolName,
          distance: import_fast_levenshtein.default.get(unknownToolName, toolName)
        }));
        matches.sort((a, b) => a.distance - b.distance);
        const topNResults = matches.slice(0, topN);
        if (topNResults.length === 0) {
          return "";
        }
        const suggestedNames = topNResults.map((match2) => `"${match2.name}"`).join(", ");
        if (topNResults.length > 1) {
          return ` Did you mean one of: ${suggestedNames}?`;
        } else {
          return ` Did you mean ${suggestedNames}?`;
        }
      }
      schedule(request4, signal) {
        if (this.isRunning() || this.isScheduling) {
          return new Promise((resolve24, reject) => {
            const abortHandler = /* @__PURE__ */ __name(() => {
              const index = this.requestQueue.findIndex((item) => item.request === request4);
              if (index > -1) {
                this.requestQueue.splice(index, 1);
                reject(new Error("Tool call cancelled while in queue."));
              }
            }, "abortHandler");
            signal.addEventListener("abort", abortHandler, { once: true });
            this.requestQueue.push({
              request: request4,
              signal,
              resolve: /* @__PURE__ */ __name(() => {
                signal.removeEventListener("abort", abortHandler);
                resolve24();
              }, "resolve"),
              reject: /* @__PURE__ */ __name((reason) => {
                signal.removeEventListener("abort", abortHandler);
                reject(reason);
              }, "reject")
            });
          });
        }
        return this._schedule(request4, signal);
      }
      async _schedule(request4, signal) {
        this.isScheduling = true;
        try {
          if (this.isRunning()) {
            throw new Error("Cannot schedule new tool calls while other tool calls are actively running (executing or awaiting approval).");
          }
          const requestsToProcess = Array.isArray(request4) ? request4 : [request4];
          const newToolCalls = requestsToProcess.map((reqInfo) => {
            const toolInstance = this.toolRegistry.getTool(reqInfo.name);
            if (!toolInstance) {
              const suggestion = this.getToolSuggestion(reqInfo.name);
              const errorMessage = `Tool "${reqInfo.name}" not found in registry. Tools must use the exact names that are registered.${suggestion}`;
              return {
                status: "error",
                request: reqInfo,
                response: createErrorResponse(reqInfo, new Error(errorMessage), ToolErrorType.TOOL_NOT_REGISTERED),
                durationMs: 0
              };
            }
            const invocationOrError = this.buildInvocation(toolInstance, reqInfo.args);
            if (invocationOrError instanceof Error) {
              return {
                status: "error",
                request: reqInfo,
                tool: toolInstance,
                response: createErrorResponse(reqInfo, invocationOrError, ToolErrorType.INVALID_TOOL_PARAMS),
                durationMs: 0
              };
            }
            return {
              status: "validating",
              request: reqInfo,
              tool: toolInstance,
              invocation: invocationOrError,
              startTime: Date.now()
            };
          });
          this.toolCalls = this.toolCalls.concat(newToolCalls);
          this.notifyToolCallsUpdate();
          for (const toolCall of newToolCalls) {
            if (toolCall.status !== "validating") {
              continue;
            }
            const { request: reqInfo, invocation } = toolCall;
            try {
              if (signal.aborted) {
                this.setStatusInternal(reqInfo.callId, "cancelled", "Tool call cancelled by user.");
                continue;
              }
              const confirmationDetails = await invocation.shouldConfirmExecute(signal);
              if (!confirmationDetails) {
                this.setToolCallOutcome(reqInfo.callId, ToolConfirmationOutcome.ProceedAlways);
                this.setStatusInternal(reqInfo.callId, "scheduled");
                continue;
              }
              const allowedTools = this.config.getAllowedTools() || [];
              const isPlanMode = this.config.getApprovalMode() === ApprovalMode.PLAN;
              const isExitPlanModeTool = reqInfo.name === "exit_plan_mode";
              if (isPlanMode && !isExitPlanModeTool) {
                if (confirmationDetails) {
                  this.setStatusInternal(reqInfo.callId, "error", {
                    callId: reqInfo.callId,
                    responseParts: convertToFunctionResponse(reqInfo.name, reqInfo.callId, getPlanModeSystemReminder()),
                    resultDisplay: "Plan mode blocked a non-read-only tool call.",
                    error: void 0,
                    errorType: void 0
                  });
                } else {
                  this.setStatusInternal(reqInfo.callId, "scheduled");
                }
              } else if (this.config.getApprovalMode() === ApprovalMode.YOLO || doesToolInvocationMatch(toolCall.tool, invocation, allowedTools)) {
                this.setToolCallOutcome(reqInfo.callId, ToolConfirmationOutcome.ProceedAlways);
                this.setStatusInternal(reqInfo.callId, "scheduled");
              } else {
                if (confirmationDetails.type === "edit" && confirmationDetails.ideConfirmation) {
                  confirmationDetails.ideConfirmation.then((resolution) => {
                    if (resolution.status === "accepted") {
                      this.handleConfirmationResponse(reqInfo.callId, confirmationDetails.onConfirm, ToolConfirmationOutcome.ProceedOnce, signal);
                    } else {
                      this.handleConfirmationResponse(reqInfo.callId, confirmationDetails.onConfirm, ToolConfirmationOutcome.Cancel, signal);
                    }
                  });
                }
                const originalOnConfirm = confirmationDetails.onConfirm;
                const wrappedConfirmationDetails = {
                  ...confirmationDetails,
                  onConfirm: /* @__PURE__ */ __name((outcome, payload) => this.handleConfirmationResponse(reqInfo.callId, originalOnConfirm, outcome, signal, payload), "onConfirm")
                };
                this.setStatusInternal(reqInfo.callId, "awaiting_approval", wrappedConfirmationDetails);
              }
            } catch (error) {
              if (signal.aborted) {
                this.setStatusInternal(reqInfo.callId, "cancelled", "Tool call cancelled by user.");
                continue;
              }
              this.setStatusInternal(reqInfo.callId, "error", createErrorResponse(reqInfo, error instanceof Error ? error : new Error(String(error)), ToolErrorType.UNHANDLED_EXCEPTION));
            }
          }
          await this.attemptExecutionOfScheduledCalls(signal);
          void this.checkAndNotifyCompletion();
        } finally {
          this.isScheduling = false;
        }
      }
      async handleConfirmationResponse(callId, originalOnConfirm, outcome, signal, payload) {
        const toolCall = this.toolCalls.find((c3) => c3.request.callId === callId && c3.status === "awaiting_approval");
        if (toolCall && toolCall.status === "awaiting_approval") {
          await originalOnConfirm(outcome);
        }
        if (outcome === ToolConfirmationOutcome.ProceedAlways) {
          await this.autoApproveCompatiblePendingTools(signal, callId);
        }
        this.setToolCallOutcome(callId, outcome);
        if (outcome === ToolConfirmationOutcome.Cancel || signal.aborted) {
          this.setStatusInternal(callId, "cancelled", "User did not allow tool call");
        } else if (outcome === ToolConfirmationOutcome.ModifyWithEditor) {
          const waitingToolCall = toolCall;
          if (isModifiableDeclarativeTool(waitingToolCall.tool)) {
            const modifyContext = waitingToolCall.tool.getModifyContext(signal);
            const editorType = this.getPreferredEditor();
            if (!editorType) {
              return;
            }
            this.setStatusInternal(callId, "awaiting_approval", {
              ...waitingToolCall.confirmationDetails,
              isModifying: true
            });
            const { updatedParams, updatedDiff } = await modifyWithEditor(waitingToolCall.request.args, modifyContext, editorType, signal, this.onEditorClose);
            this.setArgsInternal(callId, updatedParams);
            this.setStatusInternal(callId, "awaiting_approval", {
              ...waitingToolCall.confirmationDetails,
              fileDiff: updatedDiff,
              isModifying: false
            });
          }
        } else {
          if (payload?.newContent && toolCall) {
            await this._applyInlineModify(toolCall, payload, signal);
          }
          this.setStatusInternal(callId, "scheduled");
        }
        await this.attemptExecutionOfScheduledCalls(signal);
      }
      /**
       * Applies user-provided content changes to a tool call that is awaiting confirmation.
       * This method updates the tool's arguments and refreshes the confirmation prompt with a new diff
       * before the tool is scheduled for execution.
       * @private
       */
      async _applyInlineModify(toolCall, payload, signal) {
        if (toolCall.confirmationDetails.type !== "edit" || !isModifiableDeclarativeTool(toolCall.tool)) {
          return;
        }
        const modifyContext = toolCall.tool.getModifyContext(signal);
        const currentContent = await modifyContext.getCurrentContent(toolCall.request.args);
        const updatedParams = modifyContext.createUpdatedParams(currentContent, payload.newContent, toolCall.request.args);
        const updatedDiff = createPatch(modifyContext.getFilePath(toolCall.request.args), currentContent, payload.newContent, "Current", "Proposed");
        this.setArgsInternal(toolCall.request.callId, updatedParams);
        this.setStatusInternal(toolCall.request.callId, "awaiting_approval", {
          ...toolCall.confirmationDetails,
          fileDiff: updatedDiff
        });
      }
      async attemptExecutionOfScheduledCalls(signal) {
        const allCallsFinalOrScheduled = this.toolCalls.every((call) => call.status === "scheduled" || call.status === "cancelled" || call.status === "success" || call.status === "error");
        if (allCallsFinalOrScheduled) {
          const callsToExecute = this.toolCalls.filter((call) => call.status === "scheduled");
          for (const toolCall of callsToExecute) {
            if (toolCall.status !== "scheduled")
              continue;
            const scheduledCall = toolCall;
            const { callId, name: toolName } = scheduledCall.request;
            const invocation = scheduledCall.invocation;
            this.setStatusInternal(callId, "executing");
            const liveOutputCallback = scheduledCall.tool.canUpdateOutput ? (outputChunk) => {
              if (this.outputUpdateHandler) {
                this.outputUpdateHandler(callId, outputChunk);
              }
              this.toolCalls = this.toolCalls.map((tc) => tc.request.callId === callId && tc.status === "executing" ? { ...tc, liveOutput: outputChunk } : tc);
              this.notifyToolCallsUpdate();
            } : void 0;
            const shellExecutionConfig = this.config.getShellExecutionConfig();
            let promise;
            if (invocation instanceof ShellToolInvocation) {
              const setPidCallback = /* @__PURE__ */ __name((pid) => {
                this.toolCalls = this.toolCalls.map((tc) => tc.request.callId === callId && tc.status === "executing" ? { ...tc, pid } : tc);
                this.notifyToolCallsUpdate();
              }, "setPidCallback");
              promise = invocation.execute(signal, liveOutputCallback, shellExecutionConfig, setPidCallback);
            } else {
              promise = invocation.execute(signal, liveOutputCallback, shellExecutionConfig);
            }
            try {
              const toolResult = await promise;
              if (signal.aborted) {
                this.setStatusInternal(callId, "cancelled", "User cancelled tool execution.");
                continue;
              }
              if (toolResult.error === void 0) {
                let content = toolResult.llmContent;
                let outputFile = void 0;
                const contentLength = typeof content === "string" ? content.length : void 0;
                if (typeof content === "string" && toolName === ShellTool.Name && this.config.getEnableToolOutputTruncation() && this.config.getTruncateToolOutputThreshold() > 0 && this.config.getTruncateToolOutputLines() > 0) {
                  const originalContentLength = content.length;
                  const threshold = this.config.getTruncateToolOutputThreshold();
                  const lines = this.config.getTruncateToolOutputLines();
                  const truncatedResult = await truncateAndSaveToFile(content, callId, this.config.storage.getProjectTempDir(), threshold, lines);
                  content = truncatedResult.content;
                  outputFile = truncatedResult.outputFile;
                  if (outputFile) {
                    logToolOutputTruncated(this.config, new ToolOutputTruncatedEvent(scheduledCall.request.prompt_id, {
                      toolName,
                      originalContentLength,
                      truncatedContentLength: content.length,
                      threshold,
                      lines
                    }));
                  }
                }
                const response = convertToFunctionResponse(toolName, callId, content);
                const successResponse = {
                  callId,
                  responseParts: response,
                  resultDisplay: toolResult.returnDisplay,
                  error: void 0,
                  errorType: void 0,
                  outputFile,
                  contentLength
                };
                this.setStatusInternal(callId, "success", successResponse);
              } else {
                const error = new Error(toolResult.error.message);
                const errorResponse = createErrorResponse(scheduledCall.request, error, toolResult.error.type);
                this.setStatusInternal(callId, "error", errorResponse);
              }
            } catch (executionError) {
              if (signal.aborted) {
                this.setStatusInternal(callId, "cancelled", "User cancelled tool execution.");
              } else {
                this.setStatusInternal(callId, "error", createErrorResponse(scheduledCall.request, executionError instanceof Error ? executionError : new Error(String(executionError)), ToolErrorType.UNHANDLED_EXCEPTION));
              }
            }
          }
        }
      }
      async checkAndNotifyCompletion() {
        const allCallsAreTerminal = this.toolCalls.every((call) => call.status === "success" || call.status === "error" || call.status === "cancelled");
        if (this.toolCalls.length > 0 && allCallsAreTerminal) {
          const completedCalls = [...this.toolCalls];
          this.toolCalls = [];
          for (const call of completedCalls) {
            logToolCall(this.config, new ToolCallEvent(call));
          }
          if (this.onAllToolCallsComplete) {
            this.isFinalizingToolCalls = true;
            await this.onAllToolCallsComplete(completedCalls);
            this.isFinalizingToolCalls = false;
          }
          this.notifyToolCallsUpdate();
          if (this.requestQueue.length > 0) {
            const next = this.requestQueue.shift();
            this._schedule(next.request, next.signal).then(next.resolve).catch(next.reject);
          }
        }
      }
      notifyToolCallsUpdate() {
        if (this.onToolCallsUpdate) {
          this.onToolCallsUpdate([...this.toolCalls]);
        }
      }
      setToolCallOutcome(callId, outcome) {
        this.toolCalls = this.toolCalls.map((call) => {
          if (call.request.callId !== callId)
            return call;
          return {
            ...call,
            outcome
          };
        });
      }
      async autoApproveCompatiblePendingTools(signal, triggeringCallId) {
        const pendingTools = this.toolCalls.filter((call) => call.status === "awaiting_approval" && call.request.callId !== triggeringCallId);
        for (const pendingTool of pendingTools) {
          try {
            const stillNeedsConfirmation = await pendingTool.invocation.shouldConfirmExecute(signal);
            if (!stillNeedsConfirmation) {
              this.setToolCallOutcome(pendingTool.request.callId, ToolConfirmationOutcome.ProceedAlways);
              this.setStatusInternal(pendingTool.request.callId, "scheduled");
            }
          } catch (error) {
            console.error(`Error checking confirmation for tool ${pendingTool.request.callId}:`, error);
          }
        }
      }
    };
  }
});

// packages/core/dist/src/utils/thoughtUtils.js
function parseThought(rawText) {
  const startIndex = rawText.indexOf(START_DELIMITER);
  if (startIndex === -1) {
    return { subject: "", description: rawText.trim() };
  }
  const endIndex = rawText.indexOf(END_DELIMITER, startIndex + START_DELIMITER.length);
  if (endIndex === -1) {
    return { subject: "", description: rawText.trim() };
  }
  const subject = rawText.substring(startIndex + START_DELIMITER.length, endIndex).trim();
  const description = (rawText.substring(0, startIndex) + rawText.substring(endIndex + END_DELIMITER.length)).trim();
  return { subject, description };
}
var START_DELIMITER, END_DELIMITER;
var init_thoughtUtils = __esm({
  "packages/core/dist/src/utils/thoughtUtils.js"() {
    "use strict";
    init_esbuild_shims();
    START_DELIMITER = "**";
    END_DELIMITER = "**";
    __name(parseThought, "parseThought");
  }
});

// packages/core/dist/src/services/chatRecordingService.js
import path20 from "node:path";
import fs24 from "node:fs";
import { randomUUID as randomUUID4 } from "node:crypto";
var ChatRecordingService;
var init_chatRecordingService = __esm({
  "packages/core/dist/src/services/chatRecordingService.js"() {
    "use strict";
    init_esbuild_shims();
    init_config3();
    init_coreToolScheduler();
    init_thoughtUtils();
    init_paths();
    ChatRecordingService = class {
      static {
        __name(this, "ChatRecordingService");
      }
      conversationFile = null;
      cachedLastConvData = null;
      sessionId;
      projectHash;
      queuedThoughts = [];
      queuedTokens = null;
      config;
      constructor(config) {
        this.config = config;
        this.sessionId = config.getSessionId();
        this.projectHash = getProjectHash(config.getProjectRoot());
      }
      /**
       * Initializes the chat recording service: creates a new conversation file and associates it with
       * this service instance, or resumes from an existing session if resumedSessionData is provided.
       */
      initialize(resumedSessionData) {
        try {
          if (resumedSessionData) {
            this.conversationFile = resumedSessionData.filePath;
            this.sessionId = resumedSessionData.conversation.sessionId;
            this.updateConversation((conversation) => {
              conversation.sessionId = this.sessionId;
            });
            this.cachedLastConvData = null;
          } else {
            const chatsDir = path20.join(this.config.storage.getProjectTempDir(), "chats");
            fs24.mkdirSync(chatsDir, { recursive: true });
            const timestamp = (/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace(/:/g, "-");
            const filename = `session-${timestamp}-${this.sessionId.slice(0, 8)}.json`;
            this.conversationFile = path20.join(chatsDir, filename);
            this.writeConversation({
              sessionId: this.sessionId,
              projectHash: this.projectHash,
              startTime: (/* @__PURE__ */ new Date()).toISOString(),
              lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
              messages: []
            });
          }
          this.queuedThoughts = [];
          this.queuedTokens = null;
        } catch (error) {
          console.error("Error initializing chat recording service:", error);
          throw error;
        }
      }
      getLastMessage(conversation) {
        return conversation.messages.at(-1);
      }
      newMessage(type, content) {
        return {
          id: randomUUID4(),
          timestamp: (/* @__PURE__ */ new Date()).toISOString(),
          type,
          content
        };
      }
      /**
       * Records a message in the conversation.
       */
      recordMessage(message) {
        if (!this.conversationFile)
          return;
        try {
          this.updateConversation((conversation) => {
            const msg = this.newMessage(message.type, message.content);
            if (msg.type === "qwen") {
              conversation.messages.push({
                ...msg,
                thoughts: this.queuedThoughts,
                tokens: this.queuedTokens,
                model: message.model
              });
              this.queuedThoughts = [];
              this.queuedTokens = null;
            } else {
              conversation.messages.push(msg);
            }
          });
        } catch (error) {
          console.error("Error saving message:", error);
          throw error;
        }
      }
      /**
       * Records a thought from the assistant's reasoning process.
       */
      recordThought(thought) {
        if (!this.conversationFile)
          return;
        try {
          this.queuedThoughts.push({
            ...thought,
            timestamp: (/* @__PURE__ */ new Date()).toISOString()
          });
        } catch (error) {
          console.error("Error saving thought:", error);
          throw error;
        }
      }
      /**
       * Updates the tokens for the last message in the conversation (which should be by Gemini).
       */
      recordMessageTokens(respUsageMetadata) {
        if (!this.conversationFile)
          return;
        try {
          const tokens = {
            input: respUsageMetadata.promptTokenCount ?? 0,
            output: respUsageMetadata.candidatesTokenCount ?? 0,
            cached: respUsageMetadata.cachedContentTokenCount ?? 0,
            thoughts: respUsageMetadata.thoughtsTokenCount ?? 0,
            tool: respUsageMetadata.toolUsePromptTokenCount ?? 0,
            total: respUsageMetadata.totalTokenCount ?? 0
          };
          this.updateConversation((conversation) => {
            const lastMsg = this.getLastMessage(conversation);
            if (lastMsg && lastMsg.type === "qwen" && !lastMsg.tokens) {
              lastMsg.tokens = tokens;
              this.queuedTokens = null;
            } else {
              this.queuedTokens = tokens;
            }
          });
        } catch (error) {
          console.error("Error updating message tokens:", error);
          throw error;
        }
      }
      /**
       * Adds tool calls to the last message in the conversation (which should be by Gemini).
       * This method enriches tool calls with metadata from the ToolRegistry.
       */
      recordToolCalls(model, toolCalls) {
        if (!this.conversationFile)
          return;
        const toolRegistry = this.config.getToolRegistry();
        const enrichedToolCalls = toolCalls.map((toolCall) => {
          const toolInstance = toolRegistry.getTool(toolCall.name);
          return {
            ...toolCall,
            displayName: toolInstance?.displayName || toolCall.name,
            description: toolInstance?.description || "",
            renderOutputAsMarkdown: toolInstance?.isOutputMarkdown || false
          };
        });
        try {
          this.updateConversation((conversation) => {
            const lastMsg = this.getLastMessage(conversation);
            if (!lastMsg || lastMsg.type !== "qwen" || this.queuedThoughts.length > 0) {
              const newMsg = {
                ...this.newMessage("qwen", ""),
                // This isn't strictly necessary, but TypeScript apparently can't
                // tell that the first parameter to newMessage() becomes the
                // resulting message's type, and so it thinks that toolCalls may
                // not be present.  Confirming the type here satisfies it.
                type: "qwen",
                toolCalls: enrichedToolCalls,
                thoughts: this.queuedThoughts,
                model
              };
              if (this.queuedThoughts.length > 0) {
                newMsg.thoughts = this.queuedThoughts;
                this.queuedThoughts = [];
              }
              if (this.queuedTokens) {
                newMsg.tokens = this.queuedTokens;
                this.queuedTokens = null;
              }
              conversation.messages.push(newMsg);
            } else {
              if (!lastMsg.toolCalls) {
                lastMsg.toolCalls = [];
              }
              lastMsg.toolCalls = lastMsg.toolCalls.map((toolCall) => {
                const incomingToolCall = toolCalls.find((tc) => tc.id === toolCall.id);
                if (incomingToolCall) {
                  return { ...toolCall, ...incomingToolCall };
                } else {
                  return toolCall;
                }
              });
              for (const toolCall of enrichedToolCalls) {
                const existingToolCall = lastMsg.toolCalls.find((tc) => tc.id === toolCall.id);
                if (!existingToolCall) {
                  lastMsg.toolCalls.push(toolCall);
                }
              }
            }
          });
        } catch (error) {
          console.error("Error adding tool call to message:", error);
          throw error;
        }
      }
      /**
       * Loads up the conversation record from disk.
       */
      readConversation() {
        try {
          this.cachedLastConvData = fs24.readFileSync(this.conversationFile, "utf8");
          return JSON.parse(this.cachedLastConvData);
        } catch (error) {
          if (error.code !== "ENOENT") {
            console.error("Error reading conversation file:", error);
            throw error;
          }
          return {
            sessionId: this.sessionId,
            projectHash: this.projectHash,
            startTime: (/* @__PURE__ */ new Date()).toISOString(),
            lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
            messages: []
          };
        }
      }
      /**
       * Saves the conversation record; overwrites the file.
       */
      writeConversation(conversation) {
        try {
          if (!this.conversationFile)
            return;
          if (conversation.messages.length === 0)
            return;
          if (this.cachedLastConvData !== JSON.stringify(conversation, null, 2)) {
            conversation.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
            const newContent = JSON.stringify(conversation, null, 2);
            this.cachedLastConvData = newContent;
            fs24.writeFileSync(this.conversationFile, newContent);
          }
        } catch (error) {
          console.error("Error writing conversation file:", error);
          throw error;
        }
      }
      /**
       * Convenient helper for updating the conversation without file reading and writing and time
       * updating boilerplate.
       */
      updateConversation(updateFn) {
        const conversation = this.readConversation();
        updateFn(conversation);
        this.writeConversation(conversation);
      }
      /**
       * Deletes a session file by session ID.
       */
      deleteSession(sessionId2) {
        try {
          const chatsDir = path20.join(this.config.storage.getProjectTempDir(), "chats");
          const sessionPath = path20.join(chatsDir, `${sessionId2}.json`);
          fs24.unlinkSync(sessionPath);
        } catch (error) {
          console.error("Error deleting session:", error);
          throw error;
        }
      }
    };
  }
});

// packages/core/dist/src/telemetry/config.js
function parseBooleanEnvFlag(value) {
  if (value === void 0)
    return void 0;
  return value === "true" || value === "1";
}
function parseTelemetryTargetValue(value) {
  if (value === void 0)
    return void 0;
  if (value === TelemetryTarget.LOCAL || value === "local") {
    return TelemetryTarget.LOCAL;
  }
  if (value === TelemetryTarget.GCP || value === "gcp") {
    return TelemetryTarget.GCP;
  }
  return void 0;
}
async function resolveTelemetrySettings(options2) {
  const argv = options2.argv ?? {};
  const env7 = options2.env ?? {};
  const settings = options2.settings ?? {};
  const enabled = argv.telemetry ?? parseBooleanEnvFlag(env7["GEMINI_TELEMETRY_ENABLED"]) ?? settings.enabled;
  const rawTarget = argv.telemetryTarget ?? env7["GEMINI_TELEMETRY_TARGET"] ?? settings.target;
  const target = parseTelemetryTargetValue(rawTarget);
  if (rawTarget !== void 0 && target === void 0) {
    throw new FatalConfigError(`Invalid telemetry target: ${String(rawTarget)}. Valid values are: local, gcp`);
  }
  const otlpEndpoint = argv.telemetryOtlpEndpoint ?? env7["GEMINI_TELEMETRY_OTLP_ENDPOINT"] ?? env7["OTEL_EXPORTER_OTLP_ENDPOINT"] ?? settings.otlpEndpoint;
  const rawProtocol = argv.telemetryOtlpProtocol ?? env7["GEMINI_TELEMETRY_OTLP_PROTOCOL"] ?? settings.otlpProtocol;
  const otlpProtocol = ["grpc", "http"].find((p) => p === rawProtocol);
  if (rawProtocol !== void 0 && otlpProtocol === void 0) {
    throw new FatalConfigError(`Invalid telemetry OTLP protocol: ${String(rawProtocol)}. Valid values are: grpc, http`);
  }
  const logPrompts = argv.telemetryLogPrompts ?? parseBooleanEnvFlag(env7["GEMINI_TELEMETRY_LOG_PROMPTS"]) ?? settings.logPrompts;
  const outfile = argv.telemetryOutfile ?? env7["GEMINI_TELEMETRY_OUTFILE"] ?? settings.outfile;
  const useCollector = parseBooleanEnvFlag(env7["GEMINI_TELEMETRY_USE_COLLECTOR"]) ?? settings.useCollector;
  return {
    enabled,
    target,
    otlpEndpoint,
    otlpProtocol,
    logPrompts,
    outfile,
    useCollector
  };
}
var init_config = __esm({
  "packages/core/dist/src/telemetry/config.js"() {
    "use strict";
    init_esbuild_shims();
    init_errors();
    init_telemetry();
    __name(parseBooleanEnvFlag, "parseBooleanEnvFlag");
    __name(parseTelemetryTargetValue, "parseTelemetryTargetValue");
    __name(resolveTelemetrySettings, "resolveTelemetrySettings");
  }
});

// packages/core/dist/src/telemetry/index.js
var TelemetryTarget, DEFAULT_TELEMETRY_TARGET, DEFAULT_OTLP_ENDPOINT;
var init_telemetry = __esm({
  "packages/core/dist/src/telemetry/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_sdk();
    init_config();
    init_loggers();
    init_types3();
    init_types3();
    init_uiTelemetry();
    init_metrics2();
    init_qwen_logger();
    (function(TelemetryTarget2) {
      TelemetryTarget2["GCP"] = "gcp";
      TelemetryTarget2["LOCAL"] = "local";
      TelemetryTarget2["QWEN"] = "qwen";
    })(TelemetryTarget || (TelemetryTarget = {}));
    DEFAULT_TELEMETRY_TARGET = TelemetryTarget.LOCAL;
    DEFAULT_OTLP_ENDPOINT = "http://localhost:4317";
  }
});

// packages/core/dist/src/fallback/handler.js
async function handleFallback(config, failedModel, authType, error) {
  if (authType === AuthType2.QWEN_OAUTH) {
    return handleQwenOAuthError(error);
  }
  if (authType !== AuthType2.LOGIN_WITH_GOOGLE)
    return null;
  const fallbackModel = DEFAULT_GEMINI_FLASH_MODEL;
  if (failedModel === fallbackModel)
    return null;
  const fallbackModelHandler = config.fallbackModelHandler;
  if (typeof fallbackModelHandler !== "function")
    return null;
  try {
    const intent = await fallbackModelHandler(failedModel, fallbackModel, error);
    switch (intent) {
      case "retry":
        activateFallbackMode(config, authType);
        return true;
      // Signal retryWithBackoff to continue.
      case "stop":
        activateFallbackMode(config, authType);
        return false;
      case "auth":
        return false;
      default:
        throw new Error(`Unexpected fallback intent received from fallbackModelHandler: "${intent}"`);
    }
  } catch (handlerError) {
    console.error("Fallback UI handler failed:", handlerError);
    return null;
  }
}
async function handleQwenOAuthError(error) {
  if (!error) {
    return null;
  }
  const errorMessage = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
  const errorCode = error?.status || error?.code;
  const isAuthError = errorCode === 401 || errorCode === 403 || errorMessage.includes("unauthorized") || errorMessage.includes("forbidden") || errorMessage.includes("invalid api key") || errorMessage.includes("authentication") || errorMessage.includes("access denied") || errorMessage.includes("token") && errorMessage.includes("expired");
  const isRateLimitError = errorCode === 429 || errorMessage.includes("429") || errorMessage.includes("rate limit") || errorMessage.includes("too many requests");
  if (isAuthError) {
    console.warn("Qwen OAuth authentication error detected:", errorMessage);
    console.log("Note: If this persists, you may need to re-authenticate with Qwen OAuth");
    return null;
  }
  if (isRateLimitError) {
    console.warn("Qwen API rate limit encountered:", errorMessage);
    return null;
  }
  return null;
}
function activateFallbackMode(config, authType) {
  if (!config.isInFallbackMode()) {
    config.setFallbackMode(true);
    if (authType) {
      logFlashFallback(config, new FlashFallbackEvent(authType));
    }
  }
}
var init_handler = __esm({
  "packages/core/dist/src/fallback/handler.js"() {
    "use strict";
    init_esbuild_shims();
    init_contentGenerator();
    init_models();
    init_telemetry();
    __name(handleFallback, "handleFallback");
    __name(handleQwenOAuthError, "handleQwenOAuthError");
    __name(activateFallbackMode, "activateFallbackMode");
  }
});

// packages/core/dist/src/utils/messageInspectors.js
function isFunctionResponse(content) {
  return content.role === "user" && !!content.parts && content.parts.every((part) => !!part.functionResponse);
}
function isFunctionCall(content) {
  return content.role === "model" && !!content.parts && content.parts.every((part) => !!part.functionCall);
}
var init_messageInspectors = __esm({
  "packages/core/dist/src/utils/messageInspectors.js"() {
    "use strict";
    init_esbuild_shims();
    __name(isFunctionResponse, "isFunctionResponse");
    __name(isFunctionCall, "isFunctionCall");
  }
});

// packages/core/dist/src/core/geminiRequest.js
function partListUnionToString(value) {
  return partToString(value, { verbose: true });
}
var init_geminiRequest = __esm({
  "packages/core/dist/src/core/geminiRequest.js"() {
    "use strict";
    init_esbuild_shims();
    init_node();
    init_partUtils();
    __name(partListUnionToString, "partListUnionToString");
  }
});

// packages/core/dist/src/core/geminiChat.js
function isValidResponse2(response) {
  if (response.usageMetadata) {
    return true;
  }
  if (response.candidates === void 0 || response.candidates.length === 0) {
    return false;
  }
  if (response.candidates.some((candidate) => candidate.finishReason)) {
    return true;
  }
  const content = response.candidates[0]?.content;
  return content !== void 0 && isValidContent2(content);
}
function isValidNonThoughtTextPart(part) {
  return typeof part.text === "string" && !part.thought && // Technically, the model should never generate parts that have text and
  //  any of these but we don't trust them so check anyways.
  !part.functionCall && !part.functionResponse && !part.inlineData && !part.fileData;
}
function isValidContent2(content) {
  if (content.parts === void 0 || content.parts.length === 0) {
    return false;
  }
  for (const part of content.parts) {
    if (part === void 0 || Object.keys(part).length === 0) {
      return false;
    }
    if (!part.thought && part.text !== void 0 && part.text === "" && part.functionCall === void 0) {
      return false;
    }
  }
  return true;
}
function validateHistory2(history) {
  for (const content of history) {
    if (content.role !== "user" && content.role !== "model") {
      throw new Error(`Role must be user or model, but got ${content.role}.`);
    }
  }
}
function extractCuratedHistory2(comprehensiveHistory) {
  if (comprehensiveHistory === void 0 || comprehensiveHistory.length === 0) {
    return [];
  }
  const curatedHistory = [];
  const length = comprehensiveHistory.length;
  let i = 0;
  while (i < length) {
    if (comprehensiveHistory[i].role === "user") {
      curatedHistory.push(comprehensiveHistory[i]);
      i++;
    } else {
      const modelOutput = [];
      let isValid2 = true;
      while (i < length && comprehensiveHistory[i].role === "model") {
        modelOutput.push(comprehensiveHistory[i]);
        if (isValid2 && !isValidContent2(comprehensiveHistory[i])) {
          isValid2 = false;
        }
        i++;
      }
      if (isValid2) {
        curatedHistory.push(...modelOutput);
      }
    }
  }
  return curatedHistory;
}
function isSchemaDepthError(errorMessage) {
  return errorMessage.includes("maximum schema depth exceeded");
}
function isInvalidArgumentError(errorMessage) {
  return errorMessage.includes("Request contains an invalid argument");
}
var StreamEventType, INVALID_CONTENT_RETRY_OPTIONS, InvalidStreamError, GeminiChat;
var init_geminiChat = __esm({
  "packages/core/dist/src/core/geminiChat.js"() {
    "use strict";
    init_esbuild_shims();
    init_node();
    init_converter();
    init_node();
    init_retry();
    init_models();
    init_tools();
    init_loggers();
    init_chatRecordingService();
    init_types3();
    init_handler();
    init_messageInspectors();
    init_geminiRequest();
    init_uiTelemetry();
    (function(StreamEventType2) {
      StreamEventType2["CHUNK"] = "chunk";
      StreamEventType2["RETRY"] = "retry";
    })(StreamEventType || (StreamEventType = {}));
    INVALID_CONTENT_RETRY_OPTIONS = {
      maxAttempts: 2,
      // 1 initial call + 1 retry
      initialDelayMs: 500
    };
    __name(isValidResponse2, "isValidResponse");
    __name(isValidNonThoughtTextPart, "isValidNonThoughtTextPart");
    __name(isValidContent2, "isValidContent");
    __name(validateHistory2, "validateHistory");
    __name(extractCuratedHistory2, "extractCuratedHistory");
    InvalidStreamError = class extends Error {
      static {
        __name(this, "InvalidStreamError");
      }
      type;
      constructor(message, type) {
        super(message);
        this.name = "InvalidStreamError";
        this.type = type;
      }
    };
    GeminiChat = class {
      static {
        __name(this, "GeminiChat");
      }
      config;
      generationConfig;
      history;
      // A promise to represent the current state of the message being sent to the
      // model.
      sendPromise = Promise.resolve();
      chatRecordingService;
      constructor(config, generationConfig = {}, history = []) {
        this.config = config;
        this.generationConfig = generationConfig;
        this.history = history;
        validateHistory2(history);
        this.chatRecordingService = new ChatRecordingService(config);
        this.chatRecordingService.initialize();
      }
      setSystemInstruction(sysInstr) {
        this.generationConfig.systemInstruction = sysInstr;
      }
      /**
       * Sends a message to the model and returns the response in chunks.
       *
       * @remarks
       * This method will wait for the previous message to be processed before
       * sending the next message.
       *
       * @see {@link Chat#sendMessage} for non-streaming method.
       * @param params - parameters for sending the message.
       * @return The model's response.
       *
       * @example
       * ```ts
       * const chat = ai.chats.create({model: 'gemini-2.0-flash'});
       * const response = await chat.sendMessageStream({
       * message: 'Why is the sky blue?'
       * });
       * for await (const chunk of response) {
       * console.log(chunk.text);
       * }
       * ```
       */
      async sendMessageStream(model, params, prompt_id) {
        await this.sendPromise;
        let streamDoneResolver;
        const streamDonePromise = new Promise((resolve24) => {
          streamDoneResolver = resolve24;
        });
        this.sendPromise = streamDonePromise;
        const userContent = createUserContent(params.message);
        if (!isFunctionResponse(userContent)) {
          const userMessage = Array.isArray(params.message) ? params.message : [params.message];
          const userMessageContent = partListUnionToString(toParts(userMessage));
          this.chatRecordingService.recordMessage({
            model,
            type: "user",
            content: userMessageContent
          });
        }
        this.history.push(userContent);
        const requestContents = this.getHistory(true);
        const self2 = this;
        return async function* () {
          try {
            let lastError = new Error("Request failed after all retries.");
            for (let attempt = 0; attempt < INVALID_CONTENT_RETRY_OPTIONS.maxAttempts; attempt++) {
              try {
                if (attempt > 0) {
                  yield { type: StreamEventType.RETRY };
                }
                const stream2 = await self2.makeApiCallAndProcessStream(model, requestContents, params, prompt_id);
                for await (const chunk of stream2) {
                  yield { type: StreamEventType.CHUNK, value: chunk };
                }
                lastError = null;
                break;
              } catch (error) {
                lastError = error;
                const isContentError = error instanceof InvalidStreamError;
                if (isContentError) {
                  if (attempt < INVALID_CONTENT_RETRY_OPTIONS.maxAttempts - 1) {
                    logContentRetry(self2.config, new ContentRetryEvent(attempt, error.type, INVALID_CONTENT_RETRY_OPTIONS.initialDelayMs, model));
                    await new Promise((res) => setTimeout(res, INVALID_CONTENT_RETRY_OPTIONS.initialDelayMs * (attempt + 1)));
                    continue;
                  }
                }
                break;
              }
            }
            if (lastError) {
              if (lastError instanceof InvalidStreamError) {
                logContentRetryFailure(self2.config, new ContentRetryFailureEvent(INVALID_CONTENT_RETRY_OPTIONS.maxAttempts, lastError.type, model));
              }
              throw lastError;
            }
          } finally {
            streamDoneResolver();
          }
        }();
      }
      async makeApiCallAndProcessStream(model, requestContents, params, prompt_id) {
        const apiCall = /* @__PURE__ */ __name(() => {
          const modelToUse = getEffectiveModel(this.config.isInFallbackMode(), model);
          if (this.config.getQuotaErrorOccurred() && modelToUse === DEFAULT_GEMINI_FLASH_MODEL) {
            throw new Error("Please submit a new query to continue with the Flash model.");
          }
          return this.config.getContentGenerator().generateContentStream({
            model: modelToUse,
            contents: requestContents,
            config: { ...this.generationConfig, ...params.config }
          }, prompt_id);
        }, "apiCall");
        const onPersistent429Callback = /* @__PURE__ */ __name(async (authType, error) => await handleFallback(this.config, model, authType, error), "onPersistent429Callback");
        const streamResponse2 = await retryWithBackoff(apiCall, {
          shouldRetryOnError: /* @__PURE__ */ __name((error) => {
            if (error instanceof ApiError && error.message) {
              if (error.status === 400)
                return false;
              if (isSchemaDepthError(error.message))
                return false;
              if (error.status === 429)
                return true;
              if (error.status >= 500 && error.status < 600)
                return true;
            }
            return false;
          }, "shouldRetryOnError"),
          onPersistent429: onPersistent429Callback,
          authType: this.config.getContentGeneratorConfig()?.authType
        });
        return this.processStreamResponse(model, streamResponse2);
      }
      /**
       * Returns the chat history.
       *
       * @remarks
       * The history is a list of contents alternating between user and model.
       *
       * There are two types of history:
       * - The `curated history` contains only the valid turns between user and
       * model, which will be included in the subsequent requests sent to the model.
       * - The `comprehensive history` contains all turns, including invalid or
       * empty model outputs, providing a complete record of the history.
       *
       * The history is updated after receiving the response from the model,
       * for streaming response, it means receiving the last chunk of the response.
       *
       * The `comprehensive history` is returned by default. To get the `curated
       * history`, set the `curated` parameter to `true`.
       *
       * @param curated - whether to return the curated history or the comprehensive
       * history.
       * @return History contents alternating between user and model for the entire
       * chat session.
       */
      getHistory(curated = false) {
        const history = curated ? extractCuratedHistory2(this.history) : this.history;
        return structuredClone(history);
      }
      /**
       * Clears the chat history.
       */
      clearHistory() {
        this.history = [];
      }
      /**
       * Adds a new entry to the chat history.
       */
      addHistory(content) {
        this.history.push(content);
      }
      setHistory(history) {
        this.history = history;
      }
      stripThoughtsFromHistory() {
        this.history = this.history.map((content) => {
          const newContent = { ...content };
          if (newContent.parts) {
            newContent.parts = newContent.parts.map((part) => {
              if (part && typeof part === "object" && "thoughtSignature" in part) {
                const newPart = { ...part };
                delete newPart.thoughtSignature;
                return newPart;
              }
              return part;
            });
          }
          return newContent;
        });
      }
      setTools(tools) {
        this.generationConfig.tools = tools;
      }
      async maybeIncludeSchemaDepthContext(error) {
        if (isSchemaDepthError(error.message) || isInvalidArgumentError(error.message)) {
          const tools = this.config.getToolRegistry().getAllTools();
          const cyclicSchemaTools = [];
          for (const tool of tools) {
            if (tool.schema.parametersJsonSchema && hasCycleInSchema(tool.schema.parametersJsonSchema) || tool.schema.parameters && hasCycleInSchema(tool.schema.parameters)) {
              cyclicSchemaTools.push(tool.displayName);
            }
          }
          if (cyclicSchemaTools.length > 0) {
            const extraDetails = `

This error was probably caused by cyclic schema references in one of the following tools, try disabling them with excludeTools:

 - ` + cyclicSchemaTools.join(`
 - `) + `
`;
            error.message += extraDetails;
          }
        }
      }
      async *processStreamResponse(model, streamResponse2) {
        const modelResponseParts = [];
        let hasToolCall = false;
        let hasFinishReason = false;
        for await (const chunk of streamResponse2) {
          hasFinishReason = chunk?.candidates?.some((candidate) => candidate.finishReason) ?? false;
          if (isValidResponse2(chunk)) {
            const content = chunk.candidates?.[0]?.content;
            if (content?.parts) {
              if (content.parts.some((part) => part.thought)) {
                this.recordThoughtFromContent(content);
              }
              if (content.parts.some((part) => part.functionCall)) {
                hasToolCall = true;
              }
              modelResponseParts.push(...content.parts.filter((part) => !part.thought));
            }
          }
          if (chunk.usageMetadata) {
            this.chatRecordingService.recordMessageTokens(chunk.usageMetadata);
            if (chunk.usageMetadata.promptTokenCount !== void 0) {
              uiTelemetryService.setLastPromptTokenCount(chunk.usageMetadata.promptTokenCount);
            }
          }
          yield chunk;
        }
        const consolidatedParts = [];
        for (const part of modelResponseParts) {
          const lastPart = consolidatedParts[consolidatedParts.length - 1];
          if (lastPart?.text && isValidNonThoughtTextPart(lastPart) && isValidNonThoughtTextPart(part)) {
            lastPart.text += part.text;
          } else {
            consolidatedParts.push(part);
          }
        }
        const responseText = consolidatedParts.filter((part) => part.text).map((part) => part.text).join("").trim();
        if (responseText) {
          this.chatRecordingService.recordMessage({
            model,
            type: "qwen",
            content: responseText
          });
        }
        if (!hasToolCall && (!hasFinishReason || !responseText)) {
          if (!hasFinishReason) {
            throw new InvalidStreamError("Model stream ended without a finish reason.", "NO_FINISH_REASON");
          } else {
            throw new InvalidStreamError("Model stream ended with empty response text.", "NO_RESPONSE_TEXT");
          }
        }
        this.history.push({ role: "model", parts: consolidatedParts });
      }
      /**
       * Gets the chat recording service instance.
       */
      getChatRecordingService() {
        return this.chatRecordingService;
      }
      /**
       * Extracts and records thought from thought content.
       */
      recordThoughtFromContent(content) {
        if (!content.parts || content.parts.length === 0) {
          return;
        }
        const thoughtPart = content.parts[0];
        if (thoughtPart.text) {
          const rawText = thoughtPart.text;
          const subjectStringMatches = rawText.match(/\*\*(.*?)\*\*/s);
          const subject = subjectStringMatches ? subjectStringMatches[1].trim() : "";
          const description = rawText.replace(/\*\*(.*?)\*\*/s, "").trim();
          this.chatRecordingService.recordThought({
            subject,
            description
          });
        }
      }
    };
    __name(isSchemaDepthError, "isSchemaDepthError");
    __name(isInvalidArgumentError, "isInvalidArgumentError");
  }
});

// packages/core/dist/src/core/turn.js
function getCitations(resp) {
  return (resp.candidates?.[0]?.citationMetadata?.citations ?? []).filter((citation) => citation.uri !== void 0).map((citation) => {
    if (citation.title) {
      return `(${citation.title}) ${citation.uri}`;
    }
    return citation.uri;
  });
}
var GeminiEventType, CompressionStatus, Turn;
var init_turn = __esm({
  "packages/core/dist/src/core/turn.js"() {
    "use strict";
    init_esbuild_shims();
    init_partUtils();
    init_errorReporting();
    init_errors();
    init_thoughtUtils();
    (function(GeminiEventType2) {
      GeminiEventType2["Content"] = "content";
      GeminiEventType2["ToolCallRequest"] = "tool_call_request";
      GeminiEventType2["ToolCallResponse"] = "tool_call_response";
      GeminiEventType2["ToolCallConfirmation"] = "tool_call_confirmation";
      GeminiEventType2["UserCancelled"] = "user_cancelled";
      GeminiEventType2["Error"] = "error";
      GeminiEventType2["ChatCompressed"] = "chat_compressed";
      GeminiEventType2["Thought"] = "thought";
      GeminiEventType2["MaxSessionTurns"] = "max_session_turns";
      GeminiEventType2["SessionTokenLimitExceeded"] = "session_token_limit_exceeded";
      GeminiEventType2["Finished"] = "finished";
      GeminiEventType2["LoopDetected"] = "loop_detected";
      GeminiEventType2["Citation"] = "citation";
      GeminiEventType2["Retry"] = "retry";
    })(GeminiEventType || (GeminiEventType = {}));
    (function(CompressionStatus2) {
      CompressionStatus2[CompressionStatus2["COMPRESSED"] = 1] = "COMPRESSED";
      CompressionStatus2[CompressionStatus2["COMPRESSION_FAILED_INFLATED_TOKEN_COUNT"] = 2] = "COMPRESSION_FAILED_INFLATED_TOKEN_COUNT";
      CompressionStatus2[CompressionStatus2["COMPRESSION_FAILED_TOKEN_COUNT_ERROR"] = 3] = "COMPRESSION_FAILED_TOKEN_COUNT_ERROR";
      CompressionStatus2[CompressionStatus2["COMPRESSION_FAILED_EMPTY_SUMMARY"] = 4] = "COMPRESSION_FAILED_EMPTY_SUMMARY";
      CompressionStatus2[CompressionStatus2["NOOP"] = 5] = "NOOP";
    })(CompressionStatus || (CompressionStatus = {}));
    Turn = class {
      static {
        __name(this, "Turn");
      }
      chat;
      prompt_id;
      pendingToolCalls = [];
      debugResponses = [];
      pendingCitations = /* @__PURE__ */ new Set();
      finishReason = void 0;
      currentResponseId;
      constructor(chat, prompt_id) {
        this.chat = chat;
        this.prompt_id = prompt_id;
      }
      // The run method yields simpler events suitable for server logic
      async *run(model, req, signal) {
        try {
          const responseStream = await this.chat.sendMessageStream(model, {
            message: req,
            config: {
              abortSignal: signal
            }
          }, this.prompt_id);
          for await (const streamEvent of responseStream) {
            if (signal?.aborted) {
              yield { type: GeminiEventType.UserCancelled };
              return;
            }
            if (streamEvent.type === "retry") {
              yield { type: GeminiEventType.Retry };
              continue;
            }
            const resp = streamEvent.value;
            if (!resp)
              continue;
            this.debugResponses.push(resp);
            if (resp.responseId) {
              this.currentResponseId = resp.responseId;
            }
            const thoughtPart = resp.candidates?.[0]?.content?.parts?.[0];
            if (thoughtPart?.thought) {
              const thought = parseThought(thoughtPart.text ?? "");
              yield {
                type: GeminiEventType.Thought,
                value: thought
              };
              continue;
            }
            const text = getResponseText(resp);
            if (text) {
              yield { type: GeminiEventType.Content, value: text };
            }
            const functionCalls = resp.functionCalls ?? [];
            for (const fnCall of functionCalls) {
              const event = this.handlePendingFunctionCall(fnCall);
              if (event) {
                yield event;
              }
            }
            for (const citation of getCitations(resp)) {
              this.pendingCitations.add(citation);
            }
            const finishReason = resp.candidates?.[0]?.finishReason;
            if (finishReason) {
              if (this.pendingCitations.size > 0) {
                yield {
                  type: GeminiEventType.Citation,
                  value: `Citations:
${[...this.pendingCitations].sort().join("\n")}`
                };
                this.pendingCitations.clear();
              }
              this.finishReason = finishReason;
              yield {
                type: GeminiEventType.Finished,
                value: {
                  reason: finishReason,
                  usageMetadata: resp.usageMetadata
                }
              };
            }
          }
        } catch (e2) {
          if (signal.aborted) {
            yield { type: GeminiEventType.UserCancelled };
            return;
          }
          const error = toFriendlyError(e2);
          if (error instanceof UnauthorizedError) {
            throw error;
          }
          const contextForReport = [...this.chat.getHistory(
            /*curated*/
            true
          ), req];
          await reportError2(error, "Error when talking to API", contextForReport, "Turn.run-sendMessageStream");
          const status = typeof error === "object" && error !== null && "status" in error && typeof error.status === "number" ? error.status : void 0;
          const structuredError = {
            message: getErrorMessage(error),
            status
          };
          await this.chat.maybeIncludeSchemaDepthContext(structuredError);
          yield { type: GeminiEventType.Error, value: { error: structuredError } };
          return;
        }
      }
      handlePendingFunctionCall(fnCall) {
        const callId = fnCall.id ?? `${fnCall.name}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
        const name3 = fnCall.name || "undefined_tool_name";
        const args = fnCall.args || {};
        const toolCallRequest = {
          callId,
          name: name3,
          args,
          isClientInitiated: false,
          prompt_id: this.prompt_id,
          response_id: this.currentResponseId
        };
        this.pendingToolCalls.push(toolCallRequest);
        return { type: GeminiEventType.ToolCallRequest, value: toolCallRequest };
      }
      getDebugResponses() {
        return this.debugResponses;
      }
    };
    __name(getCitations, "getCitations");
  }
});

// packages/core/dist/src/config/constants.js
var DEFAULT_MEMORY_FILE_FILTERING_OPTIONS, DEFAULT_FILE_FILTERING_OPTIONS;
var init_constants3 = __esm({
  "packages/core/dist/src/config/constants.js"() {
    "use strict";
    init_esbuild_shims();
    DEFAULT_MEMORY_FILE_FILTERING_OPTIONS = {
      respectGitIgnore: false,
      respectQwenIgnore: true
    };
    DEFAULT_FILE_FILTERING_OPTIONS = {
      respectGitIgnore: true,
      respectQwenIgnore: true
    };
  }
});

// packages/core/dist/src/utils/getFolderStructure.js
import * as fs25 from "node:fs/promises";
import * as path21 from "node:path";
async function readFullStructure(rootPath, options2) {
  const rootName = path21.basename(rootPath);
  const rootNode = {
    name: rootName,
    path: rootPath,
    files: [],
    subFolders: [],
    totalChildren: 0,
    totalFiles: 0
  };
  const queue = [
    { folderInfo: rootNode, currentPath: rootPath }
  ];
  let currentItemCount = 0;
  const processedPaths = /* @__PURE__ */ new Set();
  while (queue.length > 0) {
    const { folderInfo, currentPath } = queue.shift();
    if (processedPaths.has(currentPath)) {
      continue;
    }
    processedPaths.add(currentPath);
    if (currentItemCount >= options2.maxItems) {
      continue;
    }
    let entries;
    try {
      const rawEntries = await fs25.readdir(currentPath, { withFileTypes: true });
      entries = rawEntries.sort((a, b) => a.name.localeCompare(b.name));
    } catch (error) {
      if (isNodeError(error) && (error.code === "EACCES" || error.code === "ENOENT")) {
        console.warn(`Warning: Could not read directory ${currentPath}: ${error.message}`);
        if (currentPath === rootPath && error.code === "ENOENT") {
          return null;
        }
        continue;
      }
      throw error;
    }
    const filesInCurrentDir = [];
    const subFoldersInCurrentDir = [];
    for (const entry of entries) {
      if (entry.isFile()) {
        if (currentItemCount >= options2.maxItems) {
          folderInfo.hasMoreFiles = true;
          break;
        }
        const fileName = entry.name;
        const filePath = path21.join(currentPath, fileName);
        if (options2.fileService) {
          const shouldIgnore = options2.fileFilteringOptions.respectGitIgnore && options2.fileService.shouldGitIgnoreFile(filePath) || options2.fileFilteringOptions.respectQwenIgnore && options2.fileService.shouldQwenIgnoreFile(filePath);
          if (shouldIgnore) {
            continue;
          }
        }
        if (!options2.fileIncludePattern || options2.fileIncludePattern.test(fileName)) {
          filesInCurrentDir.push(fileName);
          currentItemCount++;
          folderInfo.totalFiles++;
          folderInfo.totalChildren++;
        }
      }
    }
    folderInfo.files = filesInCurrentDir;
    for (const entry of entries) {
      if (entry.isDirectory()) {
        if (currentItemCount >= options2.maxItems) {
          folderInfo.hasMoreSubfolders = true;
          break;
        }
        const subFolderName = entry.name;
        const subFolderPath = path21.join(currentPath, subFolderName);
        let isIgnored = false;
        if (options2.fileService) {
          isIgnored = options2.fileFilteringOptions.respectGitIgnore && options2.fileService.shouldGitIgnoreFile(subFolderPath) || options2.fileFilteringOptions.respectQwenIgnore && options2.fileService.shouldQwenIgnoreFile(subFolderPath);
        }
        if (options2.ignoredFolders.has(subFolderName) || isIgnored) {
          const ignoredSubFolder = {
            name: subFolderName,
            path: subFolderPath,
            files: [],
            subFolders: [],
            totalChildren: 0,
            totalFiles: 0,
            isIgnored: true
          };
          subFoldersInCurrentDir.push(ignoredSubFolder);
          currentItemCount++;
          folderInfo.totalChildren++;
          continue;
        }
        const subFolderNode = {
          name: subFolderName,
          path: subFolderPath,
          files: [],
          subFolders: [],
          totalChildren: 0,
          totalFiles: 0
        };
        subFoldersInCurrentDir.push(subFolderNode);
        currentItemCount++;
        folderInfo.totalChildren++;
        queue.push({ folderInfo: subFolderNode, currentPath: subFolderPath });
      }
    }
    folderInfo.subFolders = subFoldersInCurrentDir;
  }
  return rootNode;
}
function formatStructure(node, currentIndent, isLastChildOfParent, isProcessingRootNode, builder) {
  const connector = isLastChildOfParent ? "\u2514\u2500\u2500\u2500" : "\u251C\u2500\u2500\u2500";
  if (!isProcessingRootNode || node.isIgnored) {
    builder.push(`${currentIndent}${connector}${node.name}${path21.sep}${node.isIgnored ? TRUNCATION_INDICATOR : ""}`);
  }
  const indentForChildren = isProcessingRootNode ? "" : currentIndent + (isLastChildOfParent ? "    " : "\u2502   ");
  const fileCount = node.files.length;
  for (let i = 0; i < fileCount; i++) {
    const isLastFileAmongSiblings = i === fileCount - 1 && node.subFolders.length === 0 && !node.hasMoreSubfolders;
    const fileConnector = isLastFileAmongSiblings ? "\u2514\u2500\u2500\u2500" : "\u251C\u2500\u2500\u2500";
    builder.push(`${indentForChildren}${fileConnector}${node.files[i]}`);
  }
  if (node.hasMoreFiles) {
    const isLastIndicatorAmongSiblings = node.subFolders.length === 0 && !node.hasMoreSubfolders;
    const fileConnector = isLastIndicatorAmongSiblings ? "\u2514\u2500\u2500\u2500" : "\u251C\u2500\u2500\u2500";
    builder.push(`${indentForChildren}${fileConnector}${TRUNCATION_INDICATOR}`);
  }
  const subFolderCount = node.subFolders.length;
  for (let i = 0; i < subFolderCount; i++) {
    const isLastSubfolderAmongSiblings = i === subFolderCount - 1 && !node.hasMoreSubfolders;
    formatStructure(node.subFolders[i], indentForChildren, isLastSubfolderAmongSiblings, false, builder);
  }
  if (node.hasMoreSubfolders) {
    builder.push(`${indentForChildren}\u2514\u2500\u2500\u2500${TRUNCATION_INDICATOR}`);
  }
}
async function getFolderStructure(directory, options2) {
  const resolvedPath = path21.resolve(directory);
  const mergedOptions = {
    maxItems: options2?.maxItems ?? MAX_ITEMS,
    ignoredFolders: options2?.ignoredFolders ?? DEFAULT_IGNORED_FOLDERS,
    fileIncludePattern: options2?.fileIncludePattern,
    fileService: options2?.fileService,
    fileFilteringOptions: options2?.fileFilteringOptions ?? DEFAULT_FILE_FILTERING_OPTIONS
  };
  try {
    let isTruncated2 = function(node) {
      if (node.hasMoreFiles || node.hasMoreSubfolders || node.isIgnored) {
        return true;
      }
      for (const sub of node.subFolders) {
        if (isTruncated2(sub)) {
          return true;
        }
      }
      return false;
    };
    var isTruncated = isTruncated2;
    __name(isTruncated2, "isTruncated");
    const structureRoot = await readFullStructure(resolvedPath, mergedOptions);
    if (!structureRoot) {
      return `Error: Could not read directory "${resolvedPath}". Check path and permissions.`;
    }
    const structureLines = [];
    formatStructure(structureRoot, "", true, true, structureLines);
    let summary = `Showing up to ${mergedOptions.maxItems} items (files + folders).`;
    if (isTruncated2(structureRoot)) {
      summary += ` Folders or files indicated with ${TRUNCATION_INDICATOR} contain more items not shown, were ignored, or the display limit (${mergedOptions.maxItems} items) was reached.`;
    }
    return `${summary}

${resolvedPath}${path21.sep}
${structureLines.join("\n")}`;
  } catch (error) {
    console.error(`Error getting folder structure for ${resolvedPath}:`, error);
    return `Error processing directory "${resolvedPath}": ${getErrorMessage(error)}`;
  }
}
var MAX_ITEMS, TRUNCATION_INDICATOR, DEFAULT_IGNORED_FOLDERS;
var init_getFolderStructure = __esm({
  "packages/core/dist/src/utils/getFolderStructure.js"() {
    "use strict";
    init_esbuild_shims();
    init_errors();
    init_constants3();
    MAX_ITEMS = 20;
    TRUNCATION_INDICATOR = "...";
    DEFAULT_IGNORED_FOLDERS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist"]);
    __name(readFullStructure, "readFullStructure");
    __name(formatStructure, "formatStructure");
    __name(getFolderStructure, "getFolderStructure");
  }
});

// packages/core/dist/src/utils/environmentContext.js
async function getDirectoryContextString(config) {
  const workspaceContext = config.getWorkspaceContext();
  const workspaceDirectories = workspaceContext.getDirectories();
  const folderStructures = await Promise.all(workspaceDirectories.map((dir) => getFolderStructure(dir, {
    fileService: config.getFileService()
  })));
  const folderStructure = folderStructures.join("\n");
  let workingDirPreamble;
  if (workspaceDirectories.length === 1) {
    workingDirPreamble = `I'm currently working in the directory: ${workspaceDirectories[0]}`;
  } else {
    const dirList = workspaceDirectories.map((dir) => `  - ${dir}`).join("\n");
    workingDirPreamble = `I'm currently working in the following directories:
${dirList}`;
  }
  return `${workingDirPreamble}
Here is the folder structure of the current working directories:

${folderStructure}`;
}
async function getEnvironmentContext(config) {
  const today = (/* @__PURE__ */ new Date()).toLocaleDateString(void 0, {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric"
  });
  const platform15 = process.platform;
  const directoryContext = await getDirectoryContextString(config);
  const context2 = `
This is the Qwen Code. We are setting up the context for our chat.
Today's date is ${today} (formatted according to the user's locale).
My operating system is: ${platform15}
${directoryContext}
        `.trim();
  const initialParts = [{ text: context2 }];
  const toolRegistry = config.getToolRegistry();
  if (config.getFullContext()) {
    try {
      const readManyFilesTool = toolRegistry.getTool("read_many_files");
      if (readManyFilesTool) {
        const invocation = readManyFilesTool.build({
          paths: ["**/*"],
          // Read everything recursively
          useDefaultExcludes: true
          // Use default excludes
        });
        const result = await invocation.execute(AbortSignal.timeout(3e4));
        if (result.llmContent) {
          initialParts.push({
            text: `
--- Full File Context ---
${result.llmContent}`
          });
        } else {
          console.warn("Full context requested, but read_many_files returned no content.");
        }
      } else {
        console.warn("Full context requested, but read_many_files tool not found.");
      }
    } catch (error) {
      console.error("Error reading full file context:", error);
      initialParts.push({
        text: "\n--- Error reading full file context ---"
      });
    }
  }
  return initialParts;
}
async function getInitialChatHistory(config, extraHistory) {
  if (config.getSkipStartupContext()) {
    return extraHistory ? [...extraHistory] : [];
  }
  const envParts = await getEnvironmentContext(config);
  const envContextString = envParts.map((part) => part.text || "").join("\n\n");
  return [
    {
      role: "user",
      parts: [{ text: envContextString }]
    },
    {
      role: "model",
      parts: [{ text: "Got it. Thanks for the context!" }]
    },
    ...extraHistory ?? []
  ];
}
var init_environmentContext = __esm({
  "packages/core/dist/src/utils/environmentContext.js"() {
    "use strict";
    init_esbuild_shims();
    init_getFolderStructure();
    __name(getDirectoryContextString, "getDirectoryContextString");
    __name(getEnvironmentContext, "getEnvironmentContext");
    __name(getInitialChatHistory, "getInitialChatHistory");
  }
});

// packages/core/dist/src/services/chatCompressionService.js
function findCompressSplitPoint(contents, fraction) {
  if (fraction <= 0 || fraction >= 1) {
    throw new Error("Fraction must be between 0 and 1");
  }
  const charCounts = contents.map((content) => JSON.stringify(content).length);
  const totalCharCount = charCounts.reduce((a, b) => a + b, 0);
  const targetCharCount = totalCharCount * fraction;
  let lastSplitPoint = 0;
  let cumulativeCharCount = 0;
  for (let i = 0; i < contents.length; i++) {
    const content = contents[i];
    if (content.role === "user" && !content.parts?.some((part) => !!part.functionResponse)) {
      if (cumulativeCharCount >= targetCharCount) {
        return i;
      }
      lastSplitPoint = i;
    }
    cumulativeCharCount += charCounts[i];
  }
  const lastContent = contents[contents.length - 1];
  if (lastContent?.role === "model" && !lastContent?.parts?.some((part) => part.functionCall)) {
    return contents.length;
  }
  return lastSplitPoint;
}
var COMPRESSION_TOKEN_THRESHOLD, COMPRESSION_PRESERVE_THRESHOLD, ChatCompressionService;
var init_chatCompressionService = __esm({
  "packages/core/dist/src/services/chatCompressionService.js"() {
    "use strict";
    init_esbuild_shims();
    init_turn();
    init_uiTelemetry();
    init_tokenLimits();
    init_prompts();
    init_partUtils();
    init_loggers();
    init_types3();
    init_environmentContext();
    COMPRESSION_TOKEN_THRESHOLD = 0.7;
    COMPRESSION_PRESERVE_THRESHOLD = 0.3;
    __name(findCompressSplitPoint, "findCompressSplitPoint");
    ChatCompressionService = class {
      static {
        __name(this, "ChatCompressionService");
      }
      async compress(chat, promptId, force, model, config, hasFailedCompressionAttempt) {
        const curatedHistory = chat.getHistory(true);
        const threshold = config.getChatCompression()?.contextPercentageThreshold ?? COMPRESSION_TOKEN_THRESHOLD;
        if (curatedHistory.length === 0 || threshold <= 0 || hasFailedCompressionAttempt && !force) {
          return {
            newHistory: null,
            info: {
              originalTokenCount: 0,
              newTokenCount: 0,
              compressionStatus: CompressionStatus.NOOP
            }
          };
        }
        const originalTokenCount = uiTelemetryService.getLastPromptTokenCount();
        if (!force) {
          if (originalTokenCount < threshold * tokenLimit(model)) {
            return {
              newHistory: null,
              info: {
                originalTokenCount,
                newTokenCount: originalTokenCount,
                compressionStatus: CompressionStatus.NOOP
              }
            };
          }
        }
        const splitPoint = findCompressSplitPoint(curatedHistory, 1 - COMPRESSION_PRESERVE_THRESHOLD);
        const historyToCompress = curatedHistory.slice(0, splitPoint);
        const historyToKeep = curatedHistory.slice(splitPoint);
        if (historyToCompress.length === 0) {
          return {
            newHistory: null,
            info: {
              originalTokenCount,
              newTokenCount: originalTokenCount,
              compressionStatus: CompressionStatus.NOOP
            }
          };
        }
        const summaryResponse = await config.getContentGenerator().generateContent({
          model,
          contents: [
            ...historyToCompress,
            {
              role: "user",
              parts: [
                {
                  text: "First, reason in your scratchpad. Then, generate the <state_snapshot>."
                }
              ]
            }
          ],
          config: {
            systemInstruction: getCompressionPrompt()
          }
        }, promptId);
        const summary = getResponseText(summaryResponse) ?? "";
        const isSummaryEmpty = !summary || summary.trim().length === 0;
        let newTokenCount = originalTokenCount;
        let extraHistory = [];
        if (!isSummaryEmpty) {
          extraHistory = [
            {
              role: "user",
              parts: [{ text: summary }]
            },
            {
              role: "model",
              parts: [{ text: "Got it. Thanks for the additional context!" }]
            },
            ...historyToKeep
          ];
          const fullNewHistory = await getInitialChatHistory(config, extraHistory);
          newTokenCount = Math.floor(fullNewHistory.reduce((total, content) => total + JSON.stringify(content).length, 0) / 4);
        }
        logChatCompression(config, makeChatCompressionEvent({
          tokens_before: originalTokenCount,
          tokens_after: newTokenCount
        }));
        if (isSummaryEmpty) {
          return {
            newHistory: null,
            info: {
              originalTokenCount,
              newTokenCount: originalTokenCount,
              compressionStatus: CompressionStatus.COMPRESSION_FAILED_EMPTY_SUMMARY
            }
          };
        } else if (newTokenCount > originalTokenCount) {
          return {
            newHistory: null,
            info: {
              originalTokenCount,
              newTokenCount,
              compressionStatus: CompressionStatus.COMPRESSION_FAILED_INFLATED_TOKEN_COUNT
            }
          };
        } else {
          uiTelemetryService.setLastPromptTokenCount(newTokenCount);
          return {
            newHistory: extraHistory,
            info: {
              originalTokenCount,
              newTokenCount,
              compressionStatus: CompressionStatus.COMPRESSED
            }
          };
        }
      }
    };
  }
});

// packages/core/dist/src/services/loopDetectionService.js
import { createHash as createHash3 } from "node:crypto";
var TOOL_CALL_LOOP_THRESHOLD, CONTENT_LOOP_THRESHOLD, CONTENT_CHUNK_SIZE, MAX_HISTORY_LENGTH, LLM_LOOP_CHECK_HISTORY_COUNT, LLM_CHECK_AFTER_TURNS, DEFAULT_LLM_CHECK_INTERVAL, MIN_LLM_CHECK_INTERVAL, MAX_LLM_CHECK_INTERVAL, LOOP_DETECTION_SYSTEM_PROMPT, LoopDetectionService;
var init_loopDetectionService = __esm({
  "packages/core/dist/src/services/loopDetectionService.js"() {
    "use strict";
    init_esbuild_shims();
    init_turn();
    init_loggers();
    init_types3();
    init_messageInspectors();
    init_models();
    TOOL_CALL_LOOP_THRESHOLD = 5;
    CONTENT_LOOP_THRESHOLD = 10;
    CONTENT_CHUNK_SIZE = 50;
    MAX_HISTORY_LENGTH = 1e3;
    LLM_LOOP_CHECK_HISTORY_COUNT = 20;
    LLM_CHECK_AFTER_TURNS = 30;
    DEFAULT_LLM_CHECK_INTERVAL = 3;
    MIN_LLM_CHECK_INTERVAL = 5;
    MAX_LLM_CHECK_INTERVAL = 15;
    LOOP_DETECTION_SYSTEM_PROMPT = `You are a sophisticated AI diagnostic agent specializing in identifying when a conversational AI is stuck in an unproductive state. Your task is to analyze the provided conversation history and determine if the assistant has ceased to make meaningful progress.

An unproductive state is characterized by one or more of the following patterns over the last 5 or more assistant turns:

Repetitive Actions: The assistant repeats the same tool calls or conversational responses a decent number of times. This includes simple loops (e.g., tool_A, tool_A, tool_A) and alternating patterns (e.g., tool_A, tool_B, tool_A, tool_B, ...).

Cognitive Loop: The assistant seems unable to determine the next logical step. It might express confusion, repeatedly ask the same questions, or generate responses that don't logically follow from the previous turns, indicating it's stuck and not advancing the task.

Crucially, differentiate between a true unproductive state and legitimate, incremental progress.
For example, a series of 'tool_A' or 'tool_B' tool calls that make small, distinct changes to the same file (like adding docstrings to functions one by one) is considered forward progress and is NOT a loop. A loop would be repeatedly replacing the same text with the same content, or cycling between a small set of files with no net change.`;
    LoopDetectionService = class {
      static {
        __name(this, "LoopDetectionService");
      }
      config;
      promptId = "";
      // Tool call tracking
      lastToolCallKey = null;
      toolCallRepetitionCount = 0;
      // Content streaming tracking
      streamContentHistory = "";
      contentStats = /* @__PURE__ */ new Map();
      lastContentIndex = 0;
      loopDetected = false;
      inCodeBlock = false;
      // LLM loop track tracking
      turnsInCurrentPrompt = 0;
      llmCheckInterval = DEFAULT_LLM_CHECK_INTERVAL;
      lastCheckTurn = 0;
      // Session-level disable flag
      disabledForSession = false;
      constructor(config) {
        this.config = config;
      }
      /**
       * Disables loop detection for the current session.
       */
      disableForSession() {
        this.disabledForSession = true;
        logLoopDetectionDisabled(this.config, new LoopDetectionDisabledEvent(this.promptId));
      }
      getToolCallKey(toolCall) {
        const argsString = JSON.stringify(toolCall.args);
        const keyString = `${toolCall.name}:${argsString}`;
        return createHash3("sha256").update(keyString).digest("hex");
      }
      /**
       * Processes a stream event and checks for loop conditions.
       * @param event - The stream event to process
       * @returns true if a loop is detected, false otherwise
       */
      addAndCheck(event) {
        if (this.loopDetected || this.disabledForSession) {
          return this.loopDetected;
        }
        switch (event.type) {
          case GeminiEventType.ToolCallRequest:
            this.resetContentTracking();
            this.loopDetected = this.checkToolCallLoop(event.value);
            break;
          case GeminiEventType.Content:
            this.loopDetected = this.checkContentLoop(event.value);
            break;
          default:
            break;
        }
        return this.loopDetected;
      }
      /**
       * Signals the start of a new turn in the conversation.
       *
       * This method increments the turn counter and, if specific conditions are met,
       * triggers an LLM-based check to detect potential conversation loops. The check
       * is performed periodically based on the `llmCheckInterval`.
       *
       * @param signal - An AbortSignal to allow for cancellation of the asynchronous LLM check.
       * @returns A promise that resolves to `true` if a loop is detected, and `false` otherwise.
       */
      async turnStarted(signal) {
        if (this.disabledForSession) {
          return false;
        }
        this.turnsInCurrentPrompt++;
        if (this.turnsInCurrentPrompt >= LLM_CHECK_AFTER_TURNS && this.turnsInCurrentPrompt - this.lastCheckTurn >= this.llmCheckInterval) {
          this.lastCheckTurn = this.turnsInCurrentPrompt;
          return await this.checkForLoopWithLLM(signal);
        }
        return false;
      }
      checkToolCallLoop(toolCall) {
        const key = this.getToolCallKey(toolCall);
        if (this.lastToolCallKey === key) {
          this.toolCallRepetitionCount++;
        } else {
          this.lastToolCallKey = key;
          this.toolCallRepetitionCount = 1;
        }
        if (this.toolCallRepetitionCount >= TOOL_CALL_LOOP_THRESHOLD) {
          logLoopDetected(this.config, new LoopDetectedEvent(LoopType.CONSECUTIVE_IDENTICAL_TOOL_CALLS, this.promptId));
          return true;
        }
        return false;
      }
      /**
       * Detects content loops by analyzing streaming text for repetitive patterns.
       *
       * The algorithm works by:
       * 1. Appending new content to the streaming history
       * 2. Truncating history if it exceeds the maximum length
       * 3. Analyzing content chunks for repetitive patterns using hashing
       * 4. Detecting loops when identical chunks appear frequently within a short distance
       * 5. Disabling loop detection within code blocks to prevent false positives,
       *    as repetitive code structures are common and not necessarily loops.
       */
      checkContentLoop(content) {
        const numFences = (content.match(/```/g) ?? []).length;
        const hasTable = /(^|\n)\s*(\|.*\||[|+-]{3,})/.test(content);
        const hasListItem = /(^|\n)\s*[*-+]\s/.test(content) || /(^|\n)\s*\d+\.\s/.test(content);
        const hasHeading = /(^|\n)#+\s/.test(content);
        const hasBlockquote = /(^|\n)>\s/.test(content);
        const isDivider = /^[+-_=*\u2500-\u257F]+$/.test(content);
        if (numFences || hasTable || hasListItem || hasHeading || hasBlockquote || isDivider) {
          this.resetContentTracking();
        }
        const wasInCodeBlock = this.inCodeBlock;
        this.inCodeBlock = numFences % 2 === 0 ? this.inCodeBlock : !this.inCodeBlock;
        if (wasInCodeBlock || this.inCodeBlock || isDivider) {
          return false;
        }
        this.streamContentHistory += content;
        this.truncateAndUpdate();
        return this.analyzeContentChunksForLoop();
      }
      /**
       * Truncates the content history to prevent unbounded memory growth.
       * When truncating, adjusts all stored indices to maintain their relative positions.
       */
      truncateAndUpdate() {
        if (this.streamContentHistory.length <= MAX_HISTORY_LENGTH) {
          return;
        }
        const truncationAmount = this.streamContentHistory.length - MAX_HISTORY_LENGTH;
        this.streamContentHistory = this.streamContentHistory.slice(truncationAmount);
        this.lastContentIndex = Math.max(0, this.lastContentIndex - truncationAmount);
        for (const [hash, oldIndices] of this.contentStats.entries()) {
          const adjustedIndices = oldIndices.map((index) => index - truncationAmount).filter((index) => index >= 0);
          if (adjustedIndices.length > 0) {
            this.contentStats.set(hash, adjustedIndices);
          } else {
            this.contentStats.delete(hash);
          }
        }
      }
      /**
       * Analyzes content in fixed-size chunks to detect repetitive patterns.
       *
       * Uses a sliding window approach:
       * 1. Extract chunks of fixed size (CONTENT_CHUNK_SIZE)
       * 2. Hash each chunk for efficient comparison
       * 3. Track positions where identical chunks appear
       * 4. Detect loops when chunks repeat frequently within a short distance
       */
      analyzeContentChunksForLoop() {
        while (this.hasMoreChunksToProcess()) {
          const currentChunk = this.streamContentHistory.substring(this.lastContentIndex, this.lastContentIndex + CONTENT_CHUNK_SIZE);
          const chunkHash = createHash3("sha256").update(currentChunk).digest("hex");
          if (this.isLoopDetectedForChunk(currentChunk, chunkHash)) {
            logLoopDetected(this.config, new LoopDetectedEvent(LoopType.CHANTING_IDENTICAL_SENTENCES, this.promptId));
            return true;
          }
          this.lastContentIndex++;
        }
        return false;
      }
      hasMoreChunksToProcess() {
        return this.lastContentIndex + CONTENT_CHUNK_SIZE <= this.streamContentHistory.length;
      }
      /**
       * Determines if a content chunk indicates a loop pattern.
       *
       * Loop detection logic:
       * 1. Check if we've seen this hash before (new chunks are stored for future comparison)
       * 2. Verify actual content matches to prevent hash collisions
       * 3. Track all positions where this chunk appears
       * 4. A loop is detected when the same chunk appears CONTENT_LOOP_THRESHOLD times
       *    within a small average distance (≤ 1.5 * chunk size)
       */
      isLoopDetectedForChunk(chunk, hash) {
        const existingIndices = this.contentStats.get(hash);
        if (!existingIndices) {
          this.contentStats.set(hash, [this.lastContentIndex]);
          return false;
        }
        if (!this.isActualContentMatch(chunk, existingIndices[0])) {
          return false;
        }
        existingIndices.push(this.lastContentIndex);
        if (existingIndices.length < CONTENT_LOOP_THRESHOLD) {
          return false;
        }
        const recentIndices = existingIndices.slice(-CONTENT_LOOP_THRESHOLD);
        const totalDistance = recentIndices[recentIndices.length - 1] - recentIndices[0];
        const averageDistance = totalDistance / (CONTENT_LOOP_THRESHOLD - 1);
        const maxAllowedDistance = CONTENT_CHUNK_SIZE * 1.5;
        return averageDistance <= maxAllowedDistance;
      }
      /**
       * Verifies that two chunks with the same hash actually contain identical content.
       * This prevents false positives from hash collisions.
       */
      isActualContentMatch(currentChunk, originalIndex) {
        const originalChunk = this.streamContentHistory.substring(originalIndex, originalIndex + CONTENT_CHUNK_SIZE);
        return originalChunk === currentChunk;
      }
      trimRecentHistory(recentHistory) {
        while (recentHistory.length > 0 && isFunctionCall(recentHistory[recentHistory.length - 1])) {
          recentHistory.pop();
        }
        while (recentHistory.length > 0 && isFunctionResponse(recentHistory[0])) {
          recentHistory.shift();
        }
        return recentHistory;
      }
      async checkForLoopWithLLM(signal) {
        const recentHistory = this.config.getGeminiClient().getHistory().slice(-LLM_LOOP_CHECK_HISTORY_COUNT);
        const trimmedHistory = this.trimRecentHistory(recentHistory);
        const taskPrompt = `Please analyze the conversation history to determine the possibility that the conversation is stuck in a repetitive, non-productive state. Provide your response in the requested JSON format.`;
        const contents = [
          ...trimmedHistory,
          { role: "user", parts: [{ text: taskPrompt }] }
        ];
        const schema = {
          type: "object",
          properties: {
            reasoning: {
              type: "string",
              description: "Your reasoning on if the conversation is looping without forward progress."
            },
            confidence: {
              type: "number",
              description: "A number between 0.0 and 1.0 representing your confidence that the conversation is in an unproductive state."
            }
          },
          required: ["reasoning", "confidence"]
        };
        let result;
        try {
          result = await this.config.getBaseLlmClient().generateJson({
            contents,
            schema,
            model: this.config.getModel() || DEFAULT_QWEN_MODEL,
            systemInstruction: LOOP_DETECTION_SYSTEM_PROMPT,
            abortSignal: signal,
            promptId: this.promptId
          });
        } catch (e2) {
          this.config.getDebugMode() ? console.error(e2) : console.debug(e2);
          return false;
        }
        if (typeof result["confidence"] === "number") {
          if (result["confidence"] > 0.9) {
            if (typeof result["reasoning"] === "string" && result["reasoning"]) {
              console.warn(result["reasoning"]);
            }
            logLoopDetected(this.config, new LoopDetectedEvent(LoopType.LLM_DETECTED_LOOP, this.promptId));
            return true;
          } else {
            this.llmCheckInterval = Math.round(MIN_LLM_CHECK_INTERVAL + (MAX_LLM_CHECK_INTERVAL - MIN_LLM_CHECK_INTERVAL) * (1 - result["confidence"]));
          }
        }
        return false;
      }
      /**
       * Resets all loop detection state.
       */
      reset(promptId) {
        this.promptId = promptId;
        this.resetToolCallCount();
        this.resetContentTracking();
        this.resetLlmCheckTracking();
        this.loopDetected = false;
      }
      resetToolCallCount() {
        this.lastToolCallKey = null;
        this.toolCallRepetitionCount = 0;
      }
      resetContentTracking(resetHistory = true) {
        if (resetHistory) {
          this.streamContentHistory = "";
        }
        this.contentStats.clear();
        this.lastContentIndex = 0;
      }
      resetLlmCheckTracking() {
        this.turnsInCurrentPrompt = 0;
        this.llmCheckInterval = DEFAULT_LLM_CHECK_INTERVAL;
        this.lastCheckTurn = 0;
      }
    };
  }
});

// packages/core/dist/src/subagents/types.js
var SubagentError, SubagentErrorCode, SubagentTerminateMode;
var init_types6 = __esm({
  "packages/core/dist/src/subagents/types.js"() {
    "use strict";
    init_esbuild_shims();
    SubagentError = class extends Error {
      static {
        __name(this, "SubagentError");
      }
      code;
      subagentName;
      constructor(message, code2, subagentName) {
        super(message);
        this.code = code2;
        this.subagentName = subagentName;
        this.name = "SubagentError";
      }
    };
    SubagentErrorCode = {
      NOT_FOUND: "NOT_FOUND",
      ALREADY_EXISTS: "ALREADY_EXISTS",
      INVALID_CONFIG: "INVALID_CONFIG",
      INVALID_NAME: "INVALID_NAME",
      FILE_ERROR: "FILE_ERROR",
      VALIDATION_ERROR: "VALIDATION_ERROR",
      TOOL_NOT_FOUND: "TOOL_NOT_FOUND"
    };
    (function(SubagentTerminateMode2) {
      SubagentTerminateMode2["ERROR"] = "ERROR";
      SubagentTerminateMode2["TIMEOUT"] = "TIMEOUT";
      SubagentTerminateMode2["GOAL"] = "GOAL";
      SubagentTerminateMode2["MAX_TURNS"] = "MAX_TURNS";
      SubagentTerminateMode2["CANCELLED"] = "CANCELLED";
    })(SubagentTerminateMode || (SubagentTerminateMode = {}));
  }
});

// packages/core/dist/src/subagents/subagent-events.js
import { EventEmitter as EventEmitter5 } from "events";
var SubAgentEventType, SubAgentEventEmitter;
var init_subagent_events = __esm({
  "packages/core/dist/src/subagents/subagent-events.js"() {
    "use strict";
    init_esbuild_shims();
    (function(SubAgentEventType2) {
      SubAgentEventType2["START"] = "start";
      SubAgentEventType2["ROUND_START"] = "round_start";
      SubAgentEventType2["ROUND_END"] = "round_end";
      SubAgentEventType2["STREAM_TEXT"] = "stream_text";
      SubAgentEventType2["TOOL_CALL"] = "tool_call";
      SubAgentEventType2["TOOL_RESULT"] = "tool_result";
      SubAgentEventType2["TOOL_WAITING_APPROVAL"] = "tool_waiting_approval";
      SubAgentEventType2["FINISH"] = "finish";
      SubAgentEventType2["ERROR"] = "error";
    })(SubAgentEventType || (SubAgentEventType = {}));
    SubAgentEventEmitter = class {
      static {
        __name(this, "SubAgentEventEmitter");
      }
      ee = new EventEmitter5();
      on(event, listener) {
        this.ee.on(event, listener);
      }
      off(event, listener) {
        this.ee.off(event, listener);
      }
      emit(event, payload) {
        this.ee.emit(event, payload);
      }
    };
  }
});

// packages/core/dist/src/subagents/subagent.js
function templateString(template, context2) {
  const placeholderRegex = /\$\{(\w+)\}/g;
  const requiredKeys = new Set(Array.from(template.matchAll(placeholderRegex), (match2) => match2[1]));
  const contextKeys = new Set(context2.get_keys());
  const missingKeys = Array.from(requiredKeys).filter((key) => !contextKeys.has(key));
  if (missingKeys.length > 0) {
    throw new Error(`Missing context values for the following keys: ${missingKeys.join(", ")}`);
  }
  return template.replace(placeholderRegex, (_match, key) => String(context2.get(key)));
}
var ContextState, SubAgentScope;
var init_subagent = __esm({
  "packages/core/dist/src/subagents/subagent.js"() {
    "use strict";
    init_esbuild_shims();
    init_errorReporting();
    init_turn();
    init_coreToolScheduler();
    init_environmentContext();
    init_geminiChat();
    init_types6();
    init_subagent_events();
    init_subagent_statistics();
    init_loggers();
    init_types3();
    init_task();
    init_models();
    ContextState = class {
      static {
        __name(this, "ContextState");
      }
      state = {};
      /**
       * Retrieves a value from the context state.
       *
       * @param key - The key of the value to retrieve.
       * @returns The value associated with the key, or undefined if the key is not found.
       */
      get(key) {
        return this.state[key];
      }
      /**
       * Sets a value in the context state.
       *
       * @param key - The key to set the value under.
       * @param value - The value to set.
       */
      set(key, value) {
        this.state[key] = value;
      }
      /**
       * Retrieves all keys in the context state.
       *
       * @returns An array of all keys in the context state.
       */
      get_keys() {
        return Object.keys(this.state);
      }
    };
    __name(templateString, "templateString");
    SubAgentScope = class _SubAgentScope {
      static {
        __name(this, "SubAgentScope");
      }
      name;
      runtimeContext;
      promptConfig;
      modelConfig;
      runConfig;
      toolConfig;
      executionStats = {
        startTimeMs: 0,
        totalDurationMs: 0,
        rounds: 0,
        totalToolCalls: 0,
        successfulToolCalls: 0,
        failedToolCalls: 0,
        inputTokens: 0,
        outputTokens: 0,
        totalTokens: 0,
        estimatedCost: 0
      };
      toolUsage = /* @__PURE__ */ new Map();
      eventEmitter;
      finalText = "";
      terminateMode = SubagentTerminateMode.ERROR;
      stats = new SubagentStatistics();
      hooks;
      subagentId;
      /**
       * Constructs a new SubAgentScope instance.
       * @param name - The name for the subagent, used for logging and identification.
       * @param runtimeContext - The shared runtime configuration and services.
       * @param promptConfig - Configuration for the subagent's prompt and behavior.
       * @param modelConfig - Configuration for the generative model parameters.
       * @param runConfig - Configuration for the subagent's execution environment.
       * @param toolConfig - Optional configuration for tools available to the subagent.
       */
      constructor(name3, runtimeContext, promptConfig, modelConfig, runConfig, toolConfig, eventEmitter, hooks) {
        this.name = name3;
        this.runtimeContext = runtimeContext;
        this.promptConfig = promptConfig;
        this.modelConfig = modelConfig;
        this.runConfig = runConfig;
        this.toolConfig = toolConfig;
        const randomPart = Math.random().toString(36).slice(2, 8);
        this.subagentId = `${this.name}-${randomPart}`;
        this.eventEmitter = eventEmitter;
        this.hooks = hooks;
      }
      /**
       * Creates and validates a new SubAgentScope instance.
       * This factory method ensures that all tools provided in the prompt configuration
       * are valid for non-interactive use before creating the subagent instance.
       * @param {string} name - The name of the subagent.
       * @param {Config} runtimeContext - The shared runtime configuration and services.
       * @param {PromptConfig} promptConfig - Configuration for the subagent's prompt and behavior.
       * @param {ModelConfig} modelConfig - Configuration for the generative model parameters.
       * @param {RunConfig} runConfig - Configuration for the subagent's execution environment.
       * @param {ToolConfig} [toolConfig] - Optional configuration for tools.
       * @returns {Promise<SubAgentScope>} A promise that resolves to a valid SubAgentScope instance.
       * @throws {Error} If any tool requires user confirmation.
       */
      static async create(name3, runtimeContext, promptConfig, modelConfig, runConfig, toolConfig, eventEmitter, hooks) {
        return new _SubAgentScope(name3, runtimeContext, promptConfig, modelConfig, runConfig, toolConfig, eventEmitter, hooks);
      }
      /**
       * Runs the subagent in a non-interactive mode.
       * This method orchestrates the subagent's execution loop, including prompt templating,
       * tool execution, and termination conditions.
       * @param {ContextState} context - The current context state containing variables for prompt templating.
       * @returns {Promise<void>} A promise that resolves when the subagent has completed its execution.
       */
      async runNonInteractive(context2, externalSignal) {
        const chat = await this.createChatObject(context2);
        if (!chat) {
          this.terminateMode = SubagentTerminateMode.ERROR;
          return;
        }
        const abortController = new AbortController();
        const onAbort = /* @__PURE__ */ __name(() => abortController.abort(), "onAbort");
        if (externalSignal) {
          if (externalSignal.aborted) {
            abortController.abort();
            this.terminateMode = SubagentTerminateMode.CANCELLED;
            return;
          }
          externalSignal.addEventListener("abort", onAbort, { once: true });
        }
        const toolRegistry = this.runtimeContext.getToolRegistry();
        const toolsList = [];
        if (this.toolConfig) {
          const asStrings = this.toolConfig.tools.filter((t2) => typeof t2 === "string");
          const hasWildcard = asStrings.includes("*");
          const onlyInlineDecls = this.toolConfig.tools.filter((t2) => typeof t2 !== "string");
          if (hasWildcard || asStrings.length === 0) {
            toolsList.push(...toolRegistry.getFunctionDeclarations().filter((t2) => t2.name !== TaskTool.Name));
          } else {
            toolsList.push(...toolRegistry.getFunctionDeclarationsFiltered(asStrings));
          }
          toolsList.push(...onlyInlineDecls);
        } else {
          toolsList.push(...toolRegistry.getFunctionDeclarations().filter((t2) => t2.name !== TaskTool.Name));
        }
        const initialTaskText = String(context2.get("task_prompt") ?? "Get Started!");
        let currentMessages = [
          { role: "user", parts: [{ text: initialTaskText }] }
        ];
        const startTime = Date.now();
        this.executionStats.startTimeMs = startTime;
        this.stats.start(startTime);
        let turnCounter = 0;
        try {
          this.eventEmitter?.emit(SubAgentEventType.START, {
            subagentId: this.subagentId,
            name: this.name,
            model: this.modelConfig.model || this.runtimeContext.getModel() || DEFAULT_QWEN_MODEL,
            tools: (this.toolConfig?.tools || ["*"]).map((t2) => typeof t2 === "string" ? t2 : t2.name),
            timestamp: Date.now()
          });
          const startEvent = new SubagentExecutionEvent(this.name, "started");
          logSubagentExecution(this.runtimeContext, startEvent);
          while (true) {
            if (this.runConfig.max_turns && turnCounter >= this.runConfig.max_turns) {
              this.terminateMode = SubagentTerminateMode.MAX_TURNS;
              break;
            }
            let durationMin = (Date.now() - startTime) / (1e3 * 60);
            if (this.runConfig.max_time_minutes && durationMin >= this.runConfig.max_time_minutes) {
              this.terminateMode = SubagentTerminateMode.TIMEOUT;
              break;
            }
            const promptId = `${this.runtimeContext.getSessionId()}#${this.subagentId}#${turnCounter++}`;
            const messageParams = {
              message: currentMessages[0]?.parts || [],
              config: {
                abortSignal: abortController.signal,
                tools: [{ functionDeclarations: toolsList }]
              }
            };
            const responseStream = await chat.sendMessageStream(this.modelConfig.model || this.runtimeContext.getModel() || DEFAULT_QWEN_MODEL, messageParams, promptId);
            this.eventEmitter?.emit(SubAgentEventType.ROUND_START, {
              subagentId: this.subagentId,
              round: turnCounter,
              promptId,
              timestamp: Date.now()
            });
            const functionCalls = [];
            let roundText = "";
            let lastUsage = void 0;
            let currentResponseId = void 0;
            for await (const streamEvent of responseStream) {
              if (abortController.signal.aborted) {
                this.terminateMode = SubagentTerminateMode.CANCELLED;
                return;
              }
              if (streamEvent.type === "retry") {
                continue;
              }
              if (streamEvent.type === "chunk") {
                const resp = streamEvent.value;
                if (resp.responseId) {
                  currentResponseId = resp.responseId;
                }
                if (resp.functionCalls)
                  functionCalls.push(...resp.functionCalls);
                const content = resp.candidates?.[0]?.content;
                const parts = content?.parts || [];
                for (const p of parts) {
                  const txt = p.text;
                  if (txt)
                    roundText += txt;
                  if (txt)
                    this.eventEmitter?.emit(SubAgentEventType.STREAM_TEXT, {
                      subagentId: this.subagentId,
                      round: turnCounter,
                      text: txt,
                      timestamp: Date.now()
                    });
                }
                if (resp.usageMetadata)
                  lastUsage = resp.usageMetadata;
              }
            }
            this.executionStats.rounds = turnCounter;
            this.stats.setRounds(turnCounter);
            durationMin = (Date.now() - startTime) / (1e3 * 60);
            if (this.runConfig.max_time_minutes && durationMin >= this.runConfig.max_time_minutes) {
              this.terminateMode = SubagentTerminateMode.TIMEOUT;
              break;
            }
            if (lastUsage) {
              const inTok = Number(lastUsage.promptTokenCount || 0);
              const outTok = Number(lastUsage.candidatesTokenCount || 0);
              if (isFinite(inTok) || isFinite(outTok)) {
                this.stats.recordTokens(isFinite(inTok) ? inTok : 0, isFinite(outTok) ? outTok : 0);
                this.executionStats.inputTokens = (this.executionStats.inputTokens || 0) + (isFinite(inTok) ? inTok : 0);
                this.executionStats.outputTokens = (this.executionStats.outputTokens || 0) + (isFinite(outTok) ? outTok : 0);
                this.executionStats.totalTokens = (this.executionStats.inputTokens || 0) + (this.executionStats.outputTokens || 0);
                this.executionStats.estimatedCost = (this.executionStats.inputTokens || 0) * 3e-5 + (this.executionStats.outputTokens || 0) * 6e-5;
              }
            }
            if (functionCalls.length > 0) {
              currentMessages = await this.processFunctionCalls(functionCalls, abortController, promptId, turnCounter, currentResponseId);
            } else {
              if (roundText && roundText.trim().length > 0) {
                this.finalText = roundText.trim();
                this.terminateMode = SubagentTerminateMode.GOAL;
                break;
              }
              currentMessages = [
                {
                  role: "user",
                  parts: [
                    {
                      text: "Please provide the final result now and stop calling tools."
                    }
                  ]
                }
              ];
            }
            this.eventEmitter?.emit(SubAgentEventType.ROUND_END, {
              subagentId: this.subagentId,
              round: turnCounter,
              promptId,
              timestamp: Date.now()
            });
          }
        } catch (error) {
          console.error("Error during subagent execution:", error);
          this.terminateMode = SubagentTerminateMode.ERROR;
          this.eventEmitter?.emit(SubAgentEventType.ERROR, {
            subagentId: this.subagentId,
            error: error instanceof Error ? error.message : String(error),
            timestamp: Date.now()
          });
          throw error;
        } finally {
          if (externalSignal)
            externalSignal.removeEventListener("abort", onAbort);
          this.executionStats.totalDurationMs = Date.now() - startTime;
          const summary = this.stats.getSummary(Date.now());
          this.eventEmitter?.emit(SubAgentEventType.FINISH, {
            subagentId: this.subagentId,
            terminateReason: this.terminateMode,
            timestamp: Date.now(),
            rounds: summary.rounds,
            totalDurationMs: summary.totalDurationMs,
            totalToolCalls: summary.totalToolCalls,
            successfulToolCalls: summary.successfulToolCalls,
            failedToolCalls: summary.failedToolCalls,
            inputTokens: summary.inputTokens,
            outputTokens: summary.outputTokens,
            totalTokens: summary.totalTokens
          });
          const completionEvent = new SubagentExecutionEvent(this.name, this.terminateMode === SubagentTerminateMode.GOAL ? "completed" : "failed", {
            terminate_reason: this.terminateMode,
            result: this.finalText,
            execution_summary: this.stats.formatCompact("Subagent execution completed")
          });
          logSubagentExecution(this.runtimeContext, completionEvent);
          await this.hooks?.onStop?.({
            subagentId: this.subagentId,
            name: this.name,
            terminateReason: this.terminateMode,
            summary,
            timestamp: Date.now()
          });
        }
      }
      /**
       * Processes a list of function calls, executing each one and collecting their responses.
       * This method iterates through the provided function calls, executes them using the
       * `executeToolCall` function (or handles `self.emitvalue` internally), and aggregates
       * their results. It also manages error reporting for failed tool executions.
       * @param {FunctionCall[]} functionCalls - An array of `FunctionCall` objects to process.
       * @param {ToolRegistry} toolRegistry - The tool registry to look up and execute tools.
       * @param {AbortController} abortController - An `AbortController` to signal cancellation of tool executions.
       * @param {string} responseId - Optional API response ID for correlation with tool calls.
       * @returns {Promise<Content[]>} A promise that resolves to an array of `Content` parts representing the tool responses,
       *          which are then used to update the chat history.
       */
      async processFunctionCalls(functionCalls, abortController, promptId, currentRound, responseId) {
        const toolResponseParts = [];
        const responded = /* @__PURE__ */ new Set();
        let resolveBatch = null;
        const scheduler = new CoreToolScheduler({
          outputUpdateHandler: void 0,
          onAllToolCallsComplete: /* @__PURE__ */ __name(async (completedCalls) => {
            for (const call of completedCalls) {
              const toolName = call.request.name;
              const duration = call.durationMs ?? 0;
              const success = call.status === "success";
              const errorMessage = call.status === "error" || call.status === "cancelled" ? call.response.error?.message : void 0;
              this.executionStats.totalToolCalls += 1;
              if (success) {
                this.executionStats.successfulToolCalls += 1;
              } else {
                this.executionStats.failedToolCalls += 1;
              }
              const tu = this.toolUsage.get(toolName) || {
                count: 0,
                success: 0,
                failure: 0,
                totalDurationMs: 0,
                averageDurationMs: 0
              };
              tu.count += 1;
              if (success) {
                tu.success += 1;
              } else {
                tu.failure += 1;
                tu.lastError = errorMessage || "Unknown error";
              }
              tu.totalDurationMs = (tu.totalDurationMs || 0) + duration;
              tu.averageDurationMs = tu.count > 0 ? tu.totalDurationMs / tu.count : 0;
              this.toolUsage.set(toolName, tu);
              this.eventEmitter?.emit(SubAgentEventType.TOOL_RESULT, {
                subagentId: this.subagentId,
                round: currentRound,
                callId: call.request.callId,
                name: toolName,
                success,
                error: errorMessage,
                resultDisplay: call.response.resultDisplay ? typeof call.response.resultDisplay === "string" ? call.response.resultDisplay : JSON.stringify(call.response.resultDisplay) : void 0,
                durationMs: duration,
                timestamp: Date.now()
              });
              this.stats.recordToolCall(toolName, success, duration, this.toolUsage.get(toolName)?.lastError);
              await this.hooks?.postToolUse?.({
                subagentId: this.subagentId,
                name: this.name,
                toolName,
                args: call.request.args,
                success,
                durationMs: duration,
                errorMessage,
                timestamp: Date.now()
              });
              const respParts = call.response.responseParts;
              if (respParts) {
                const parts = Array.isArray(respParts) ? respParts : [respParts];
                for (const part of parts) {
                  if (typeof part === "string") {
                    toolResponseParts.push({ text: part });
                  } else if (part) {
                    toolResponseParts.push(part);
                  }
                }
              }
            }
            resolveBatch?.();
          }, "onAllToolCallsComplete"),
          onToolCallsUpdate: /* @__PURE__ */ __name((calls) => {
            for (const call of calls) {
              if (call.status !== "awaiting_approval")
                continue;
              const waiting = call;
              try {
                const { confirmationDetails } = waiting;
                const { onConfirm: _onConfirm, ...rest } = confirmationDetails;
                this.eventEmitter?.emit(SubAgentEventType.TOOL_WAITING_APPROVAL, {
                  subagentId: this.subagentId,
                  round: currentRound,
                  callId: waiting.request.callId,
                  name: waiting.request.name,
                  description: this.getToolDescription(waiting.request.name, waiting.request.args),
                  confirmationDetails: rest,
                  respond: /* @__PURE__ */ __name(async (outcome, payload) => {
                    if (responded.has(waiting.request.callId))
                      return;
                    responded.add(waiting.request.callId);
                    await waiting.confirmationDetails.onConfirm(outcome, payload);
                  }, "respond"),
                  timestamp: Date.now()
                });
              } catch {
              }
            }
          }, "onToolCallsUpdate"),
          getPreferredEditor: /* @__PURE__ */ __name(() => void 0, "getPreferredEditor"),
          config: this.runtimeContext,
          onEditorClose: /* @__PURE__ */ __name(() => {
          }, "onEditorClose")
        });
        const requests = functionCalls.map((fc) => {
          const toolName = String(fc.name || "unknown");
          const callId = fc.id ?? `${fc.name}-${Date.now()}`;
          const args = fc.args ?? {};
          const request4 = {
            callId,
            name: toolName,
            args,
            isClientInitiated: true,
            prompt_id: promptId,
            response_id: responseId
          };
          const description = this.getToolDescription(toolName, args);
          this.eventEmitter?.emit(SubAgentEventType.TOOL_CALL, {
            subagentId: this.subagentId,
            round: currentRound,
            callId,
            name: toolName,
            args,
            description,
            timestamp: Date.now()
          });
          void this.hooks?.preToolUse?.({
            subagentId: this.subagentId,
            name: this.name,
            toolName,
            args,
            timestamp: Date.now()
          });
          return request4;
        });
        if (requests.length > 0) {
          const batchDone = new Promise((resolve24) => {
            resolveBatch = /* @__PURE__ */ __name(() => {
              resolve24();
              resolveBatch = null;
            }, "resolveBatch");
          });
          await scheduler.schedule(requests, abortController.signal);
          await batchDone;
        }
        if (functionCalls.length > 0 && toolResponseParts.length === 0) {
          toolResponseParts.push({
            text: "All tool calls failed. Please analyze the errors and try an alternative approach."
          });
        }
        return [{ role: "user", parts: toolResponseParts }];
      }
      getEventEmitter() {
        return this.eventEmitter;
      }
      getStatistics() {
        const total = this.executionStats.totalToolCalls;
        const successRate = total > 0 ? this.executionStats.successfulToolCalls / total * 100 : 0;
        return {
          ...this.executionStats,
          successRate,
          toolUsage: Array.from(this.toolUsage.entries()).map(([name3, v]) => ({
            name: name3,
            ...v
          }))
        };
      }
      getExecutionSummary() {
        return this.stats.getSummary();
      }
      getFinalText() {
        return this.finalText;
      }
      getTerminateMode() {
        return this.terminateMode;
      }
      async createChatObject(context2) {
        if (!this.promptConfig.systemPrompt && !this.promptConfig.initialMessages) {
          throw new Error("PromptConfig must have either `systemPrompt` or `initialMessages` defined.");
        }
        if (this.promptConfig.systemPrompt && this.promptConfig.initialMessages) {
          throw new Error("PromptConfig cannot have both `systemPrompt` and `initialMessages` defined.");
        }
        const envHistory = await getInitialChatHistory(this.runtimeContext);
        const start_history = [
          ...envHistory,
          ...this.promptConfig.initialMessages ?? []
        ];
        const systemInstruction = this.promptConfig.systemPrompt ? this.buildChatSystemPrompt(context2) : void 0;
        try {
          const generationConfig = {
            temperature: this.modelConfig.temp,
            topP: this.modelConfig.top_p
          };
          if (systemInstruction) {
            generationConfig.systemInstruction = systemInstruction;
          }
          return new GeminiChat(this.runtimeContext, generationConfig, start_history);
        } catch (error) {
          await reportError2(error, "Error initializing chat session.", start_history, "startChat");
          return void 0;
        }
      }
      /**
       * Safely retrieves the description of a tool by attempting to build it.
       * Returns an empty string if any error occurs during the process.
       *
       * @param toolName The name of the tool to get description for.
       * @param args The arguments that would be passed to the tool.
       * @returns The tool description or empty string if error occurs.
       */
      getToolDescription(toolName, args) {
        try {
          const toolRegistry = this.runtimeContext.getToolRegistry();
          const tool = toolRegistry.getTool(toolName);
          if (!tool) {
            return "";
          }
          const toolInstance = tool.build(args);
          return toolInstance.getDescription() || "";
        } catch {
          return "";
        }
      }
      buildChatSystemPrompt(context2) {
        if (!this.promptConfig.systemPrompt) {
          return "";
        }
        let finalPrompt = templateString(this.promptConfig.systemPrompt, context2);
        finalPrompt += `

Important Rules:
 - You operate in non-interactive mode: do not ask the user questions; proceed with available context.
 - Use tools only when necessary to obtain facts or make changes.
 - When the task is complete, return the final result as a normal model response (not a tool call) and stop.`;
        return finalPrompt;
      }
    };
  }
});

// packages/core/dist/src/tools/task.js
var TaskTool, TaskToolInvocation;
var init_task = __esm({
  "packages/core/dist/src/tools/task.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    init_tool_names();
    init_tools();
    init_types6();
    init_subagent();
    init_subagent_events();
    TaskTool = class _TaskTool extends BaseDeclarativeTool {
      static {
        __name(this, "TaskTool");
      }
      config;
      static Name = ToolNames.TASK;
      subagentManager;
      availableSubagents = [];
      constructor(config) {
        const initialSchema = {
          type: "object",
          properties: {
            description: {
              type: "string",
              description: "A short (3-5 word) description of the task"
            },
            prompt: {
              type: "string",
              description: "The task for the agent to perform"
            },
            subagent_type: {
              type: "string",
              description: "The type of specialized agent to use for this task"
            }
          },
          required: ["description", "prompt", "subagent_type"],
          additionalProperties: false,
          $schema: "http://json-schema.org/draft-07/schema#"
        };
        super(
          _TaskTool.Name,
          ToolDisplayNames.TASK,
          "Delegate tasks to specialized subagents. Loading available subagents...",
          // Initial description
          Kind.Other,
          initialSchema,
          true,
          // isOutputMarkdown
          true
        );
        this.config = config;
        this.subagentManager = config.getSubagentManager();
        this.subagentManager.addChangeListener(() => {
          void this.refreshSubagents();
        });
        this.refreshSubagents();
      }
      /**
       * Asynchronously initializes the tool by loading available subagents
       * and updating the description and schema.
       */
      async refreshSubagents() {
        try {
          this.availableSubagents = await this.subagentManager.listSubagents();
          this.updateDescriptionAndSchema();
        } catch (error) {
          console.warn("Failed to load subagents for Task tool:", error);
          this.availableSubagents = [];
          this.updateDescriptionAndSchema();
        } finally {
          const geminiClient = this.config.getGeminiClient();
          if (geminiClient && geminiClient.isInitialized()) {
            await geminiClient.setTools();
          }
        }
      }
      /**
       * Updates the tool's description and schema based on available subagents.
       */
      updateDescriptionAndSchema() {
        let subagentDescriptions = "";
        if (this.availableSubagents.length === 0) {
          subagentDescriptions = "No subagents are currently configured. You can create subagents using the /agents command.";
        } else {
          subagentDescriptions = this.availableSubagents.map((subagent) => `- **${subagent.name}**: ${subagent.description}`).join("\n");
        }
        const baseDescription = `Launch a new agent to handle complex, multi-step tasks autonomously. 

Available agent types and the tools they have access to:
${subagentDescriptions}

When using the Task tool, you must specify a subagent_type parameter to select which agent type to use.

When NOT to use the Agent tool:
- If you want to read a specific file path, use the Read or Glob tool instead of the Agent tool, to find the match more quickly
- If you are searching for a specific class definition like "class Foo", use the Glob tool instead, to find the match more quickly
- If you are searching for code within a specific file or set of 2-3 files, use the Read tool instead of the Agent tool, to find the match more quickly
- Other tasks that are not related to the agent descriptions above

Usage notes:
1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.
3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.
4. The agent's outputs should generally be trusted
5. Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent
6. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.

Example usage:
<example_agent_descriptions>
"code-reviewer": use this agent after you are done writing a signficant piece of code
"greeting-responder": use this agent when to respond to user greetings with a friendly joke
</example_agent_description>

<example>
user: "Please write a function that checks if a number is prime"
assistant: Sure let me write a function that checks if a number is prime
assistant: First let me use the Write tool to write a function that checks if a number is prime
assistant: I'm going to use the Write tool to write the following code:
<code>
function isPrime(n) {
  if (n <= 1) return false
  for (let i = 2; i * i <= n; i++) {
    if (n % i === 0) return false
  }
  return true
}
</code>
<commentary>
Since a signficant piece of code was written and the task was completed, now use the code-reviewer agent to review the code
</commentary>
assistant: Now let me use the code-reviewer agent to review the code
assistant: Uses the Task tool to launch the with the code-reviewer agent 
</example>

<example>
user: "Hello"
<commentary>
Since the user is greeting, use the greeting-responder agent to respond with a friendly joke
</commentary>
assistant: "I'm going to use the Task tool to launch the with the greeting-responder agent"
</example>
`;
        this.description = baseDescription + subagentDescriptions;
        const subagentNames = this.availableSubagents.map((s2) => s2.name);
        const schema = this.parameterSchema;
        if (schema.properties && schema.properties.subagent_type) {
          if (subagentNames.length > 0) {
            schema.properties.subagent_type.enum = subagentNames;
          } else {
            delete schema.properties.subagent_type.enum;
          }
        }
      }
      validateToolParams(params) {
        if (!params.description || typeof params.description !== "string" || params.description.trim() === "") {
          return 'Parameter "description" must be a non-empty string.';
        }
        if (!params.prompt || typeof params.prompt !== "string" || params.prompt.trim() === "") {
          return 'Parameter "prompt" must be a non-empty string.';
        }
        if (!params.subagent_type || typeof params.subagent_type !== "string" || params.subagent_type.trim() === "") {
          return 'Parameter "subagent_type" must be a non-empty string.';
        }
        const subagentExists = this.availableSubagents.some((subagent) => subagent.name === params.subagent_type);
        if (!subagentExists) {
          const availableNames = this.availableSubagents.map((s2) => s2.name);
          return `Subagent "${params.subagent_type}" not found. Available subagents: ${availableNames.join(", ")}`;
        }
        return null;
      }
      createInvocation(params) {
        return new TaskToolInvocation(this.config, this.subagentManager, params);
      }
    };
    TaskToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "TaskToolInvocation");
      }
      config;
      subagentManager;
      _eventEmitter;
      currentDisplay = null;
      currentToolCalls = [];
      constructor(config, subagentManager, params) {
        super(params);
        this.config = config;
        this.subagentManager = subagentManager;
        this._eventEmitter = new SubAgentEventEmitter();
      }
      get eventEmitter() {
        return this._eventEmitter;
      }
      /**
       * Updates the current display state and calls updateOutput if provided
       */
      updateDisplay(updates, updateOutput2) {
        if (!this.currentDisplay)
          return;
        this.currentDisplay = {
          ...this.currentDisplay,
          ...updates
        };
        if (updateOutput2) {
          updateOutput2(this.currentDisplay);
        }
      }
      /**
       * Sets up event listeners for real-time subagent progress updates
       */
      setupEventListeners(updateOutput2) {
        this.eventEmitter.on(SubAgentEventType.START, () => {
          this.updateDisplay({ status: "running" }, updateOutput2);
        });
        this.eventEmitter.on(SubAgentEventType.TOOL_CALL, (...args) => {
          const event = args[0];
          const newToolCall = {
            callId: event.callId,
            name: event.name,
            status: "executing",
            args: event.args,
            description: event.description
          };
          this.currentToolCalls.push(newToolCall);
          this.updateDisplay({
            toolCalls: [...this.currentToolCalls]
          }, updateOutput2);
        });
        this.eventEmitter.on(SubAgentEventType.TOOL_RESULT, (...args) => {
          const event = args[0];
          const toolCallIndex = this.currentToolCalls.findIndex((call) => call.callId === event.callId);
          if (toolCallIndex >= 0) {
            this.currentToolCalls[toolCallIndex] = {
              ...this.currentToolCalls[toolCallIndex],
              status: event.success ? "success" : "failed",
              error: event.error,
              resultDisplay: event.resultDisplay
            };
            this.updateDisplay({
              toolCalls: [...this.currentToolCalls]
            }, updateOutput2);
          }
        });
        this.eventEmitter.on(SubAgentEventType.FINISH, (...args) => {
          const event = args[0];
          this.updateDisplay({
            status: event.terminateReason === "GOAL" ? "completed" : "failed",
            terminateReason: event.terminateReason
          }, updateOutput2);
        });
        this.eventEmitter.on(SubAgentEventType.ERROR, (...args) => {
          const event = args[0];
          this.updateDisplay({
            status: "failed",
            terminateReason: event.error
          }, updateOutput2);
        });
        this.eventEmitter.on(SubAgentEventType.TOOL_WAITING_APPROVAL, (...args) => {
          const event = args[0];
          const idx = this.currentToolCalls.findIndex((c3) => c3.callId === event.callId);
          if (idx >= 0) {
            this.currentToolCalls[idx] = {
              ...this.currentToolCalls[idx],
              status: "awaiting_approval"
            };
          } else {
            this.currentToolCalls.push({
              callId: event.callId,
              name: event.name,
              status: "awaiting_approval",
              description: event.description
            });
          }
          const details = {
            ...event.confirmationDetails,
            onConfirm: /* @__PURE__ */ __name(async (outcome, payload) => {
              const proceedOutcomes = /* @__PURE__ */ new Set([
                ToolConfirmationOutcome.ProceedOnce,
                ToolConfirmationOutcome.ProceedAlways,
                ToolConfirmationOutcome.ProceedAlwaysServer,
                ToolConfirmationOutcome.ProceedAlwaysTool
              ]);
              if (proceedOutcomes.has(outcome)) {
                const idx2 = this.currentToolCalls.findIndex((c3) => c3.callId === event.callId);
                if (idx2 >= 0) {
                  this.currentToolCalls[idx2] = {
                    ...this.currentToolCalls[idx2],
                    status: "executing"
                  };
                }
                this.updateDisplay({
                  toolCalls: [...this.currentToolCalls],
                  pendingConfirmation: void 0
                }, updateOutput2);
              } else {
                this.updateDisplay({ pendingConfirmation: void 0 }, updateOutput2);
              }
              await event.respond(outcome, payload);
            }, "onConfirm")
          };
          this.updateDisplay({
            toolCalls: [...this.currentToolCalls],
            pendingConfirmation: details
          }, updateOutput2);
        });
      }
      getDescription() {
        return `${this.params.subagent_type} subagent: "${this.params.description}"`;
      }
      async shouldConfirmExecute() {
        return false;
      }
      async execute(signal, updateOutput2) {
        try {
          const subagentConfig = await this.subagentManager.loadSubagent(this.params.subagent_type);
          if (!subagentConfig) {
            const errorDisplay = {
              type: "task_execution",
              subagentName: this.params.subagent_type,
              taskDescription: this.params.description,
              taskPrompt: this.params.prompt,
              status: "failed",
              terminateReason: `Subagent "${this.params.subagent_type}" not found`
            };
            return {
              llmContent: `Subagent "${this.params.subagent_type}" not found`,
              returnDisplay: errorDisplay
            };
          }
          this.currentDisplay = {
            type: "task_execution",
            subagentName: subagentConfig.name,
            taskDescription: this.params.description,
            taskPrompt: this.params.prompt,
            status: "running",
            subagentColor: subagentConfig.color
          };
          this.setupEventListeners(updateOutput2);
          if (updateOutput2) {
            updateOutput2(this.currentDisplay);
          }
          const subagentScope = await this.subagentManager.createSubagentScope(subagentConfig, this.config, { eventEmitter: this.eventEmitter });
          const contextState = new ContextState();
          contextState.set("task_prompt", this.params.prompt);
          await subagentScope.runNonInteractive(contextState, signal);
          const finalText = subagentScope.getFinalText();
          const terminateMode = subagentScope.getTerminateMode();
          const success = terminateMode === SubagentTerminateMode.GOAL;
          const executionSummary = subagentScope.getExecutionSummary();
          if (signal?.aborted) {
            this.updateDisplay({
              status: "cancelled",
              terminateReason: "Task was cancelled by user",
              executionSummary
            }, updateOutput2);
          } else {
            this.updateDisplay({
              status: success ? "completed" : "failed",
              terminateReason: terminateMode,
              result: finalText,
              executionSummary
            }, updateOutput2);
          }
          return {
            llmContent: [{ text: finalText }],
            returnDisplay: this.currentDisplay
          };
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : String(error);
          console.error(`[TaskTool] Error running subagent: ${errorMessage}`);
          const errorDisplay = {
            ...this.currentDisplay,
            status: "failed",
            terminateReason: `Failed to run subagent: ${errorMessage}`
          };
          return {
            llmContent: `Failed to run subagent: ${errorMessage}`,
            returnDisplay: errorDisplay
          };
        }
      }
    };
  }
});

// packages/core/dist/src/utils/nextSpeakerChecker.js
async function checkNextSpeaker(chat, config, abortSignal, promptId) {
  const curatedHistory = chat.getHistory(
    /* curated */
    true
  );
  if (curatedHistory.length === 0) {
    return null;
  }
  const comprehensiveHistory = chat.getHistory();
  if (comprehensiveHistory.length === 0) {
    return null;
  }
  const lastComprehensiveMessage = comprehensiveHistory[comprehensiveHistory.length - 1];
  if (lastComprehensiveMessage && isFunctionResponse(lastComprehensiveMessage)) {
    return {
      reasoning: "The last message was a function response, so the model should speak next.",
      next_speaker: "model"
    };
  }
  if (lastComprehensiveMessage && lastComprehensiveMessage.role === "model" && lastComprehensiveMessage.parts && lastComprehensiveMessage.parts.length === 0) {
    lastComprehensiveMessage.parts.push({ text: "" });
    return {
      reasoning: "The last message was a filler model message with no content (nothing for user to act on), model should speak next.",
      next_speaker: "model"
    };
  }
  const lastMessage = curatedHistory[curatedHistory.length - 1];
  if (!lastMessage || lastMessage.role !== "model") {
    return null;
  }
  const contents = [
    ...curatedHistory,
    { role: "user", parts: [{ text: CHECK_PROMPT }] }
  ];
  try {
    const parsedResponse = await config.getBaseLlmClient().generateJson({
      contents,
      schema: RESPONSE_SCHEMA,
      model: config.getModel() || DEFAULT_QWEN_MODEL,
      abortSignal,
      promptId
    });
    if (parsedResponse && parsedResponse.next_speaker && ["user", "model"].includes(parsedResponse.next_speaker)) {
      return parsedResponse;
    }
    return null;
  } catch (error) {
    console.warn("Failed to talk to Gemini endpoint when seeing if conversation should continue.", error);
    return null;
  }
}
var CHECK_PROMPT, RESPONSE_SCHEMA;
var init_nextSpeakerChecker = __esm({
  "packages/core/dist/src/utils/nextSpeakerChecker.js"() {
    "use strict";
    init_esbuild_shims();
    init_models();
    init_messageInspectors();
    CHECK_PROMPT = `Analyze *only* the content and structure of your immediately preceding response (your last turn in the conversation history). Based *strictly* on that response, determine who should logically speak next: the 'user' or the 'model' (you).
**Decision Rules (apply in order):**
1.  **Model Continues:** If your last response explicitly states an immediate next action *you* intend to take (e.g., "Next, I will...", "Now I'll process...", "Moving on to analyze...", indicates an intended tool call that didn't execute), OR if the response seems clearly incomplete (cut off mid-thought without a natural conclusion), then the **'model'** should speak next.
2.  **Question to User:** If your last response ends with a direct question specifically addressed *to the user*, then the **'user'** should speak next.
3.  **Waiting for User:** If your last response completed a thought, statement, or task *and* does not meet the criteria for Rule 1 (Model Continues) or Rule 2 (Question to User), it implies a pause expecting user input or reaction. In this case, the **'user'** should speak next.`;
    RESPONSE_SCHEMA = {
      type: "object",
      properties: {
        reasoning: {
          type: "string",
          description: "Brief explanation justifying the 'next_speaker' choice based *strictly* on the applicable rule and the content/structure of the preceding turn."
        },
        next_speaker: {
          type: "string",
          enum: ["user", "model"],
          description: "Who should speak next based *only* on the preceding turn and the decision rules"
        }
      },
      required: ["reasoning", "next_speaker"]
    };
    __name(checkNextSpeaker, "checkNextSpeaker");
  }
});

// packages/core/dist/src/ide/constants.js
var QWEN_CODE_COMPANION_EXTENSION_NAME, IDE_MAX_OPEN_FILES, IDE_MAX_SELECTED_TEXT_LENGTH, IDE_REQUEST_TIMEOUT_MS;
var init_constants4 = __esm({
  "packages/core/dist/src/ide/constants.js"() {
    "use strict";
    init_esbuild_shims();
    QWEN_CODE_COMPANION_EXTENSION_NAME = "Qwen Code Companion";
    IDE_MAX_OPEN_FILES = 10;
    IDE_MAX_SELECTED_TEXT_LENGTH = 16384;
    IDE_REQUEST_TIMEOUT_MS = 10 * 60 * 1e3;
  }
});

// packages/core/dist/src/ide/ideContext.js
var IdeContextStore, ideContextStore;
var init_ideContext = __esm({
  "packages/core/dist/src/ide/ideContext.js"() {
    "use strict";
    init_esbuild_shims();
    init_constants4();
    IdeContextStore = class {
      static {
        __name(this, "IdeContextStore");
      }
      ideContextState;
      subscribers = /* @__PURE__ */ new Set();
      /**
       * Notifies all registered subscribers about the current IDE context.
       */
      notifySubscribers() {
        for (const subscriber of this.subscribers) {
          subscriber(this.ideContextState);
        }
      }
      /**
       * Sets the IDE context and notifies all registered subscribers of the change.
       * @param newIdeContext The new IDE context from the IDE.
       */
      set(newIdeContext) {
        const { workspaceState } = newIdeContext;
        if (!workspaceState) {
          this.ideContextState = newIdeContext;
          this.notifySubscribers();
          return;
        }
        const { openFiles } = workspaceState;
        if (openFiles && openFiles.length > 0) {
          openFiles.sort((a, b) => b.timestamp - a.timestamp);
          const mostRecentFile = openFiles[0];
          if (!mostRecentFile.isActive) {
            openFiles.forEach((file) => {
              file.isActive = false;
              file.cursor = void 0;
              file.selectedText = void 0;
            });
          } else {
            openFiles.forEach((file, index) => {
              if (index !== 0) {
                file.isActive = false;
                file.cursor = void 0;
                file.selectedText = void 0;
              }
            });
            if (mostRecentFile.selectedText && mostRecentFile.selectedText.length > IDE_MAX_SELECTED_TEXT_LENGTH) {
              mostRecentFile.selectedText = mostRecentFile.selectedText.substring(0, IDE_MAX_SELECTED_TEXT_LENGTH) + "... [TRUNCATED]";
            }
          }
          if (openFiles.length > IDE_MAX_OPEN_FILES) {
            workspaceState.openFiles = openFiles.slice(0, IDE_MAX_OPEN_FILES);
          }
        }
        this.ideContextState = newIdeContext;
        this.notifySubscribers();
      }
      /**
       * Clears the IDE context and notifies all registered subscribers of the change.
       */
      clear() {
        this.ideContextState = void 0;
        this.notifySubscribers();
      }
      /**
       * Retrieves the current IDE context.
       * @returns The `IdeContext` object if a file is active; otherwise, `undefined`.
       */
      get() {
        return this.ideContextState;
      }
      /**
       * Subscribes to changes in the IDE context.
       *
       * When the IDE context changes, the provided `subscriber` function will be called.
       * Note: The subscriber is not called with the current value upon subscription.
       *
       * @param subscriber The function to be called when the IDE context changes.
       * @returns A function that, when called, will unsubscribe the provided subscriber.
       */
      subscribe(subscriber) {
        this.subscribers.add(subscriber);
        return () => {
          this.subscribers.delete(subscriber);
        };
      }
    };
    ideContextStore = new IdeContextStore();
  }
});

// node_modules/zod/v3/helpers/util.js
var util2, objectUtil, ZodParsedType, getParsedType;
var init_util2 = __esm({
  "node_modules/zod/v3/helpers/util.js"() {
    init_esbuild_shims();
    (function(util4) {
      util4.assertEqual = (_) => {
      };
      function assertIs(_arg) {
      }
      __name(assertIs, "assertIs");
      util4.assertIs = assertIs;
      function assertNever3(_x) {
        throw new Error();
      }
      __name(assertNever3, "assertNever");
      util4.assertNever = assertNever3;
      util4.arrayToEnum = (items) => {
        const obj = {};
        for (const item of items) {
          obj[item] = item;
        }
        return obj;
      };
      util4.getValidEnumValues = (obj) => {
        const validKeys = util4.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
        const filtered = {};
        for (const k of validKeys) {
          filtered[k] = obj[k];
        }
        return util4.objectValues(filtered);
      };
      util4.objectValues = (obj) => {
        return util4.objectKeys(obj).map(function(e2) {
          return obj[e2];
        });
      };
      util4.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
        const keys = [];
        for (const key in object) {
          if (Object.prototype.hasOwnProperty.call(object, key)) {
            keys.push(key);
          }
        }
        return keys;
      };
      util4.find = (arr, checker) => {
        for (const item of arr) {
          if (checker(item))
            return item;
        }
        return void 0;
      };
      util4.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
      function joinValues(array, separator = " | ") {
        return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
      }
      __name(joinValues, "joinValues");
      util4.joinValues = joinValues;
      util4.jsonStringifyReplacer = (_, value) => {
        if (typeof value === "bigint") {
          return value.toString();
        }
        return value;
      };
    })(util2 || (util2 = {}));
    (function(objectUtil2) {
      objectUtil2.mergeShapes = (first2, second) => {
        return {
          ...first2,
          ...second
          // second overwrites first
        };
      };
    })(objectUtil || (objectUtil = {}));
    ZodParsedType = util2.arrayToEnum([
      "string",
      "nan",
      "number",
      "integer",
      "float",
      "boolean",
      "date",
      "bigint",
      "symbol",
      "function",
      "undefined",
      "null",
      "array",
      "object",
      "unknown",
      "promise",
      "void",
      "never",
      "map",
      "set"
    ]);
    getParsedType = /* @__PURE__ */ __name((data) => {
      const t2 = typeof data;
      switch (t2) {
        case "undefined":
          return ZodParsedType.undefined;
        case "string":
          return ZodParsedType.string;
        case "number":
          return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
        case "boolean":
          return ZodParsedType.boolean;
        case "function":
          return ZodParsedType.function;
        case "bigint":
          return ZodParsedType.bigint;
        case "symbol":
          return ZodParsedType.symbol;
        case "object":
          if (Array.isArray(data)) {
            return ZodParsedType.array;
          }
          if (data === null) {
            return ZodParsedType.null;
          }
          if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
            return ZodParsedType.promise;
          }
          if (typeof Map !== "undefined" && data instanceof Map) {
            return ZodParsedType.map;
          }
          if (typeof Set !== "undefined" && data instanceof Set) {
            return ZodParsedType.set;
          }
          if (typeof Date !== "undefined" && data instanceof Date) {
            return ZodParsedType.date;
          }
          return ZodParsedType.object;
        default:
          return ZodParsedType.unknown;
      }
    }, "getParsedType");
  }
});

// node_modules/zod/v3/ZodError.js
var ZodIssueCode, quotelessJson, ZodError;
var init_ZodError = __esm({
  "node_modules/zod/v3/ZodError.js"() {
    init_esbuild_shims();
    init_util2();
    ZodIssueCode = util2.arrayToEnum([
      "invalid_type",
      "invalid_literal",
      "custom",
      "invalid_union",
      "invalid_union_discriminator",
      "invalid_enum_value",
      "unrecognized_keys",
      "invalid_arguments",
      "invalid_return_type",
      "invalid_date",
      "invalid_string",
      "too_small",
      "too_big",
      "invalid_intersection_types",
      "not_multiple_of",
      "not_finite"
    ]);
    quotelessJson = /* @__PURE__ */ __name((obj) => {
      const json2 = JSON.stringify(obj, null, 2);
      return json2.replace(/"([^"]+)":/g, "$1:");
    }, "quotelessJson");
    ZodError = class _ZodError extends Error {
      static {
        __name(this, "ZodError");
      }
      get errors() {
        return this.issues;
      }
      constructor(issues) {
        super();
        this.issues = [];
        this.addIssue = (sub) => {
          this.issues = [...this.issues, sub];
        };
        this.addIssues = (subs = []) => {
          this.issues = [...this.issues, ...subs];
        };
        const actualProto = new.target.prototype;
        if (Object.setPrototypeOf) {
          Object.setPrototypeOf(this, actualProto);
        } else {
          this.__proto__ = actualProto;
        }
        this.name = "ZodError";
        this.issues = issues;
      }
      format(_mapper) {
        const mapper = _mapper || function(issue) {
          return issue.message;
        };
        const fieldErrors = { _errors: [] };
        const processError = /* @__PURE__ */ __name((error) => {
          for (const issue of error.issues) {
            if (issue.code === "invalid_union") {
              issue.unionErrors.map(processError);
            } else if (issue.code === "invalid_return_type") {
              processError(issue.returnTypeError);
            } else if (issue.code === "invalid_arguments") {
              processError(issue.argumentsError);
            } else if (issue.path.length === 0) {
              fieldErrors._errors.push(mapper(issue));
            } else {
              let curr = fieldErrors;
              let i = 0;
              while (i < issue.path.length) {
                const el = issue.path[i];
                const terminal = i === issue.path.length - 1;
                if (!terminal) {
                  curr[el] = curr[el] || { _errors: [] };
                } else {
                  curr[el] = curr[el] || { _errors: [] };
                  curr[el]._errors.push(mapper(issue));
                }
                curr = curr[el];
                i++;
              }
            }
          }
        }, "processError");
        processError(this);
        return fieldErrors;
      }
      static assert(value) {
        if (!(value instanceof _ZodError)) {
          throw new Error(`Not a ZodError: ${value}`);
        }
      }
      toString() {
        return this.message;
      }
      get message() {
        return JSON.stringify(this.issues, util2.jsonStringifyReplacer, 2);
      }
      get isEmpty() {
        return this.issues.length === 0;
      }
      flatten(mapper = (issue) => issue.message) {
        const fieldErrors = {};
        const formErrors = [];
        for (const sub of this.issues) {
          if (sub.path.length > 0) {
            const firstEl = sub.path[0];
            fieldErrors[firstEl] = fieldErrors[firstEl] || [];
            fieldErrors[firstEl].push(mapper(sub));
          } else {
            formErrors.push(mapper(sub));
          }
        }
        return { formErrors, fieldErrors };
      }
      get formErrors() {
        return this.flatten();
      }
    };
    ZodError.create = (issues) => {
      const error = new ZodError(issues);
      return error;
    };
  }
});

// node_modules/zod/v3/locales/en.js
var errorMap, en_default;
var init_en = __esm({
  "node_modules/zod/v3/locales/en.js"() {
    init_esbuild_shims();
    init_ZodError();
    init_util2();
    errorMap = /* @__PURE__ */ __name((issue, _ctx) => {
      let message;
      switch (issue.code) {
        case ZodIssueCode.invalid_type:
          if (issue.received === ZodParsedType.undefined) {
            message = "Required";
          } else {
            message = `Expected ${issue.expected}, received ${issue.received}`;
          }
          break;
        case ZodIssueCode.invalid_literal:
          message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util2.jsonStringifyReplacer)}`;
          break;
        case ZodIssueCode.unrecognized_keys:
          message = `Unrecognized key(s) in object: ${util2.joinValues(issue.keys, ", ")}`;
          break;
        case ZodIssueCode.invalid_union:
          message = `Invalid input`;
          break;
        case ZodIssueCode.invalid_union_discriminator:
          message = `Invalid discriminator value. Expected ${util2.joinValues(issue.options)}`;
          break;
        case ZodIssueCode.invalid_enum_value:
          message = `Invalid enum value. Expected ${util2.joinValues(issue.options)}, received '${issue.received}'`;
          break;
        case ZodIssueCode.invalid_arguments:
          message = `Invalid function arguments`;
          break;
        case ZodIssueCode.invalid_return_type:
          message = `Invalid function return type`;
          break;
        case ZodIssueCode.invalid_date:
          message = `Invalid date`;
          break;
        case ZodIssueCode.invalid_string:
          if (typeof issue.validation === "object") {
            if ("includes" in issue.validation) {
              message = `Invalid input: must include "${issue.validation.includes}"`;
              if (typeof issue.validation.position === "number") {
                message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
              }
            } else if ("startsWith" in issue.validation) {
              message = `Invalid input: must start with "${issue.validation.startsWith}"`;
            } else if ("endsWith" in issue.validation) {
              message = `Invalid input: must end with "${issue.validation.endsWith}"`;
            } else {
              util2.assertNever(issue.validation);
            }
          } else if (issue.validation !== "regex") {
            message = `Invalid ${issue.validation}`;
          } else {
            message = "Invalid";
          }
          break;
        case ZodIssueCode.too_small:
          if (issue.type === "array")
            message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
          else if (issue.type === "string")
            message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
          else if (issue.type === "number")
            message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
          else if (issue.type === "bigint")
            message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
          else if (issue.type === "date")
            message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
          else
            message = "Invalid input";
          break;
        case ZodIssueCode.too_big:
          if (issue.type === "array")
            message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
          else if (issue.type === "string")
            message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
          else if (issue.type === "number")
            message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
          else if (issue.type === "bigint")
            message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
          else if (issue.type === "date")
            message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
          else
            message = "Invalid input";
          break;
        case ZodIssueCode.custom:
          message = `Invalid input`;
          break;
        case ZodIssueCode.invalid_intersection_types:
          message = `Intersection results could not be merged`;
          break;
        case ZodIssueCode.not_multiple_of:
          message = `Number must be a multiple of ${issue.multipleOf}`;
          break;
        case ZodIssueCode.not_finite:
          message = "Number must be finite";
          break;
        default:
          message = _ctx.defaultError;
          util2.assertNever(issue);
      }
      return { message };
    }, "errorMap");
    en_default = errorMap;
  }
});

// node_modules/zod/v3/errors.js
function setErrorMap(map2) {
  overrideErrorMap = map2;
}
function getErrorMap() {
  return overrideErrorMap;
}
var overrideErrorMap;
var init_errors3 = __esm({
  "node_modules/zod/v3/errors.js"() {
    init_esbuild_shims();
    init_en();
    overrideErrorMap = en_default;
    __name(setErrorMap, "setErrorMap");
    __name(getErrorMap, "getErrorMap");
  }
});

// node_modules/zod/v3/helpers/parseUtil.js
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      // contextual error map is first priority
      ctx.schemaErrorMap,
      // then schema-bound map if available
      overrideMap,
      // then global override map
      overrideMap === en_default ? void 0 : en_default
      // then global default map
    ].filter((x) => !!x)
  });
  ctx.common.issues.push(issue);
}
var makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync;
var init_parseUtil = __esm({
  "node_modules/zod/v3/helpers/parseUtil.js"() {
    init_esbuild_shims();
    init_errors3();
    init_en();
    makeIssue = /* @__PURE__ */ __name((params) => {
      const { data, path: path108, errorMaps, issueData } = params;
      const fullPath = [...path108, ...issueData.path || []];
      const fullIssue = {
        ...issueData,
        path: fullPath
      };
      if (issueData.message !== void 0) {
        return {
          ...issueData,
          path: fullPath,
          message: issueData.message
        };
      }
      let errorMessage = "";
      const maps = errorMaps.filter((m) => !!m).slice().reverse();
      for (const map2 of maps) {
        errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message;
      }
      return {
        ...issueData,
        path: fullPath,
        message: errorMessage
      };
    }, "makeIssue");
    EMPTY_PATH = [];
    __name(addIssueToContext, "addIssueToContext");
    ParseStatus = class _ParseStatus {
      static {
        __name(this, "ParseStatus");
      }
      constructor() {
        this.value = "valid";
      }
      dirty() {
        if (this.value === "valid")
          this.value = "dirty";
      }
      abort() {
        if (this.value !== "aborted")
          this.value = "aborted";
      }
      static mergeArray(status, results) {
        const arrayValue = [];
        for (const s2 of results) {
          if (s2.status === "aborted")
            return INVALID;
          if (s2.status === "dirty")
            status.dirty();
          arrayValue.push(s2.value);
        }
        return { status: status.value, value: arrayValue };
      }
      static async mergeObjectAsync(status, pairs) {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value
          });
        }
        return _ParseStatus.mergeObjectSync(status, syncPairs);
      }
      static mergeObjectSync(status, pairs) {
        const finalObject = {};
        for (const pair of pairs) {
          const { key, value } = pair;
          if (key.status === "aborted")
            return INVALID;
          if (value.status === "aborted")
            return INVALID;
          if (key.status === "dirty")
            status.dirty();
          if (value.status === "dirty")
            status.dirty();
          if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
            finalObject[key.value] = value.value;
          }
        }
        return { status: status.value, value: finalObject };
      }
    };
    INVALID = Object.freeze({
      status: "aborted"
    });
    DIRTY = /* @__PURE__ */ __name((value) => ({ status: "dirty", value }), "DIRTY");
    OK = /* @__PURE__ */ __name((value) => ({ status: "valid", value }), "OK");
    isAborted = /* @__PURE__ */ __name((x) => x.status === "aborted", "isAborted");
    isDirty = /* @__PURE__ */ __name((x) => x.status === "dirty", "isDirty");
    isValid = /* @__PURE__ */ __name((x) => x.status === "valid", "isValid");
    isAsync = /* @__PURE__ */ __name((x) => typeof Promise !== "undefined" && x instanceof Promise, "isAsync");
  }
});

// node_modules/zod/v3/helpers/typeAliases.js
var init_typeAliases = __esm({
  "node_modules/zod/v3/helpers/typeAliases.js"() {
    init_esbuild_shims();
  }
});

// node_modules/zod/v3/helpers/errorUtil.js
var errorUtil;
var init_errorUtil = __esm({
  "node_modules/zod/v3/helpers/errorUtil.js"() {
    init_esbuild_shims();
    (function(errorUtil2) {
      errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
      errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
    })(errorUtil || (errorUtil = {}));
  }
});

// node_modules/zod/v3/types.js
function processCreateParams(params) {
  if (!params)
    return {};
  const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
  if (errorMap2 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap2)
    return { errorMap: errorMap2, description };
  const customMap = /* @__PURE__ */ __name((iss, ctx) => {
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message ?? ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: message ?? required_error ?? ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: message ?? invalid_type_error ?? ctx.defaultError };
  }, "customMap");
  return { errorMap: customMap, description };
}
function timeRegexSource(args) {
  let secondsRegexSource = `[0-5]\\d`;
  if (args.precision) {
    secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  }
  const secondsQuantifier = args.precision ? "+" : "?";
  return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
  return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
  let regex3 = `${dateRegexSource}T${timeRegexSource(args)}`;
  const opts = [];
  opts.push(args.local ? `Z?` : `Z`);
  if (args.offset)
    opts.push(`([+-]\\d{2}:?\\d{2})`);
  regex3 = `${regex3}(${opts.join("|")})`;
  return new RegExp(`^${regex3}$`);
}
function isValidIP(ip, version2) {
  if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
function isValidJWT(jwt, alg) {
  if (!jwtRegex.test(jwt))
    return false;
  try {
    const [header] = jwt.split(".");
    if (!header)
      return false;
    const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base64));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if ("typ" in decoded && decoded?.typ !== "JWT")
      return false;
    if (!decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch {
    return false;
  }
}
function isValidCidr(ip, version2) {
  if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}
function floatSafeRemainder(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  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 / 10 ** decCount;
}
function deepPartialify(schema) {
  if (schema instanceof ZodObject) {
    const newShape = {};
    for (const key in schema.shape) {
      const fieldSchema = schema.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema._def,
      shape: /* @__PURE__ */ __name(() => newShape, "shape")
    });
  } else if (schema instanceof ZodArray) {
    return new ZodArray({
      ...schema._def,
      type: deepPartialify(schema.element)
    });
  } else if (schema instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodTuple) {
    return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
  } else {
    return schema;
  }
}
function mergeValues(a, b) {
  const aType = getParsedType(a);
  const bType = getParsedType(b);
  if (a === b) {
    return { valid: true, data: a };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util2.objectKeys(b);
    const sharedKeys = util2.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a, ...b };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a[key], b[key]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
    if (a.length !== b.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index = 0; index < a.length; index++) {
      const itemA = a[index];
      const itemB = b[index];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
    return { valid: true, data: a };
  } else {
    return { valid: false };
  }
}
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
function cleanParams(params, data) {
  const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
  const p2 = typeof p === "string" ? { message: p } : p;
  return p2;
}
function custom(check, _params = {}, fatal) {
  if (check)
    return ZodAny.create().superRefine((data, ctx) => {
      const r3 = check(data);
      if (r3 instanceof Promise) {
        return r3.then((r4) => {
          if (!r4) {
            const params = cleanParams(_params, data);
            const _fatal = params.fatal ?? fatal ?? true;
            ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
          }
        });
      }
      if (!r3) {
        const params = cleanParams(_params, data);
        const _fatal = params.fatal ?? fatal ?? true;
        ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
      }
      return;
    });
  return ZodAny.create();
}
var ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex4, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER;
var init_types7 = __esm({
  "node_modules/zod/v3/types.js"() {
    init_esbuild_shims();
    init_ZodError();
    init_errors3();
    init_errorUtil();
    init_parseUtil();
    init_util2();
    ParseInputLazyPath = class {
      static {
        __name(this, "ParseInputLazyPath");
      }
      constructor(parent, value, path108, key) {
        this._cachedPath = [];
        this.parent = parent;
        this.data = value;
        this._path = path108;
        this._key = key;
      }
      get path() {
        if (!this._cachedPath.length) {
          if (Array.isArray(this._key)) {
            this._cachedPath.push(...this._path, ...this._key);
          } else {
            this._cachedPath.push(...this._path, this._key);
          }
        }
        return this._cachedPath;
      }
    };
    handleResult = /* @__PURE__ */ __name((ctx, result) => {
      if (isValid(result)) {
        return { success: true, data: result.value };
      } else {
        if (!ctx.common.issues.length) {
          throw new Error("Validation failed but no issues detected.");
        }
        return {
          success: false,
          get error() {
            if (this._error)
              return this._error;
            const error = new ZodError(ctx.common.issues);
            this._error = error;
            return this._error;
          }
        };
      }
    }, "handleResult");
    __name(processCreateParams, "processCreateParams");
    ZodType = class {
      static {
        __name(this, "ZodType");
      }
      get description() {
        return this._def.description;
      }
      _getType(input) {
        return getParsedType(input.data);
      }
      _getOrReturnCtx(input, ctx) {
        return ctx || {
          common: input.parent.common,
          data: input.data,
          parsedType: getParsedType(input.data),
          schemaErrorMap: this._def.errorMap,
          path: input.path,
          parent: input.parent
        };
      }
      _processInputParams(input) {
        return {
          status: new ParseStatus(),
          ctx: {
            common: input.parent.common,
            data: input.data,
            parsedType: getParsedType(input.data),
            schemaErrorMap: this._def.errorMap,
            path: input.path,
            parent: input.parent
          }
        };
      }
      _parseSync(input) {
        const result = this._parse(input);
        if (isAsync(result)) {
          throw new Error("Synchronous parse encountered promise.");
        }
        return result;
      }
      _parseAsync(input) {
        const result = this._parse(input);
        return Promise.resolve(result);
      }
      parse(data, params) {
        const result = this.safeParse(data, params);
        if (result.success)
          return result.data;
        throw result.error;
      }
      safeParse(data, params) {
        const ctx = {
          common: {
            issues: [],
            async: params?.async ?? false,
            contextualErrorMap: params?.errorMap
          },
          path: params?.path || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        const result = this._parseSync({ data, path: ctx.path, parent: ctx });
        return handleResult(ctx, result);
      }
      "~validate"(data) {
        const ctx = {
          common: {
            issues: [],
            async: !!this["~standard"].async
          },
          path: [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        if (!this["~standard"].async) {
          try {
            const result = this._parseSync({ data, path: [], parent: ctx });
            return isValid(result) ? {
              value: result.value
            } : {
              issues: ctx.common.issues
            };
          } catch (err) {
            if (err?.message?.toLowerCase()?.includes("encountered")) {
              this["~standard"].async = true;
            }
            ctx.common = {
              issues: [],
              async: true
            };
          }
        }
        return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        });
      }
      async parseAsync(data, params) {
        const result = await this.safeParseAsync(data, params);
        if (result.success)
          return result.data;
        throw result.error;
      }
      async safeParseAsync(data, params) {
        const ctx = {
          common: {
            issues: [],
            contextualErrorMap: params?.errorMap,
            async: true
          },
          path: params?.path || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        const maybeAsyncResult2 = this._parse({ data, path: ctx.path, parent: ctx });
        const result = await (isAsync(maybeAsyncResult2) ? maybeAsyncResult2 : Promise.resolve(maybeAsyncResult2));
        return handleResult(ctx, result);
      }
      refine(check, message) {
        const getIssueProperties = /* @__PURE__ */ __name((val) => {
          if (typeof message === "string" || typeof message === "undefined") {
            return { message };
          } else if (typeof message === "function") {
            return message(val);
          } else {
            return message;
          }
        }, "getIssueProperties");
        return this._refinement((val, ctx) => {
          const result = check(val);
          const setError = /* @__PURE__ */ __name(() => ctx.addIssue({
            code: ZodIssueCode.custom,
            ...getIssueProperties(val)
          }), "setError");
          if (typeof Promise !== "undefined" && result instanceof Promise) {
            return result.then((data) => {
              if (!data) {
                setError();
                return false;
              } else {
                return true;
              }
            });
          }
          if (!result) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      refinement(check, refinementData) {
        return this._refinement((val, ctx) => {
          if (!check(val)) {
            ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
            return false;
          } else {
            return true;
          }
        });
      }
      _refinement(refinement) {
        return new ZodEffects({
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "refinement", refinement }
        });
      }
      superRefine(refinement) {
        return this._refinement(refinement);
      }
      constructor(def2) {
        this.spa = this.safeParseAsync;
        this._def = def2;
        this.parse = this.parse.bind(this);
        this.safeParse = this.safeParse.bind(this);
        this.parseAsync = this.parseAsync.bind(this);
        this.safeParseAsync = this.safeParseAsync.bind(this);
        this.spa = this.spa.bind(this);
        this.refine = this.refine.bind(this);
        this.refinement = this.refinement.bind(this);
        this.superRefine = this.superRefine.bind(this);
        this.optional = this.optional.bind(this);
        this.nullable = this.nullable.bind(this);
        this.nullish = this.nullish.bind(this);
        this.array = this.array.bind(this);
        this.promise = this.promise.bind(this);
        this.or = this.or.bind(this);
        this.and = this.and.bind(this);
        this.transform = this.transform.bind(this);
        this.brand = this.brand.bind(this);
        this.default = this.default.bind(this);
        this.catch = this.catch.bind(this);
        this.describe = this.describe.bind(this);
        this.pipe = this.pipe.bind(this);
        this.readonly = this.readonly.bind(this);
        this.isNullable = this.isNullable.bind(this);
        this.isOptional = this.isOptional.bind(this);
        this["~standard"] = {
          version: 1,
          vendor: "zod",
          validate: /* @__PURE__ */ __name((data) => this["~validate"](data), "validate")
        };
      }
      optional() {
        return ZodOptional.create(this, this._def);
      }
      nullable() {
        return ZodNullable.create(this, this._def);
      }
      nullish() {
        return this.nullable().optional();
      }
      array() {
        return ZodArray.create(this);
      }
      promise() {
        return ZodPromise.create(this, this._def);
      }
      or(option2) {
        return ZodUnion.create([this, option2], this._def);
      }
      and(incoming) {
        return ZodIntersection.create(this, incoming, this._def);
      }
      transform(transform) {
        return new ZodEffects({
          ...processCreateParams(this._def),
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "transform", transform }
        });
      }
      default(def2) {
        const defaultValueFunc = typeof def2 === "function" ? def2 : () => def2;
        return new ZodDefault({
          ...processCreateParams(this._def),
          innerType: this,
          defaultValue: defaultValueFunc,
          typeName: ZodFirstPartyTypeKind.ZodDefault
        });
      }
      brand() {
        return new ZodBranded({
          typeName: ZodFirstPartyTypeKind.ZodBranded,
          type: this,
          ...processCreateParams(this._def)
        });
      }
      catch(def2) {
        const catchValueFunc = typeof def2 === "function" ? def2 : () => def2;
        return new ZodCatch({
          ...processCreateParams(this._def),
          innerType: this,
          catchValue: catchValueFunc,
          typeName: ZodFirstPartyTypeKind.ZodCatch
        });
      }
      describe(description) {
        const This = this.constructor;
        return new This({
          ...this._def,
          description
        });
      }
      pipe(target) {
        return ZodPipeline.create(this, target);
      }
      readonly() {
        return ZodReadonly.create(this);
      }
      isOptional() {
        return this.safeParse(void 0).success;
      }
      isNullable() {
        return this.safeParse(null).success;
      }
    };
    cuidRegex = /^c[^\s-]{8,}$/i;
    cuid2Regex = /^[0-9a-z]+$/;
    ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
    uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
    nanoidRegex = /^[a-z0-9_-]{21}$/i;
    jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
    durationRegex = /^[-+]?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)?)??$/;
    emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
    _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
    ipv4Regex = /^(?:(?: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])$/;
    ipv4CidrRegex = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/;
    ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
    ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
    base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
    base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
    dateRegexSource = `((\\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])))`;
    dateRegex = new RegExp(`^${dateRegexSource}$`);
    __name(timeRegexSource, "timeRegexSource");
    __name(timeRegex, "timeRegex");
    __name(datetimeRegex, "datetimeRegex");
    __name(isValidIP, "isValidIP");
    __name(isValidJWT, "isValidJWT");
    __name(isValidCidr, "isValidCidr");
    ZodString = class _ZodString extends ZodType {
      static {
        __name(this, "ZodString");
      }
      _parse(input) {
        if (this._def.coerce) {
          input.data = String(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.string) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.string,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        const status = new ParseStatus();
        let ctx = void 0;
        for (const check of this._def.checks) {
          if (check.kind === "min") {
            if (input.data.length < check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            if (input.data.length > check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "length") {
            const tooBig = input.data.length > check.value;
            const tooSmall = input.data.length < check.value;
            if (tooBig || tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              if (tooBig) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_big,
                  maximum: check.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check.message
                });
              } else if (tooSmall) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_small,
                  minimum: check.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check.message
                });
              }
              status.dirty();
            }
          } else if (check.kind === "email") {
            if (!emailRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "email",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "emoji") {
            if (!emojiRegex4) {
              emojiRegex4 = new RegExp(_emojiRegex, "u");
            }
            if (!emojiRegex4.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "emoji",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "uuid") {
            if (!uuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "uuid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "nanoid") {
            if (!nanoidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "nanoid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cuid") {
            if (!cuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cuid2") {
            if (!cuid2Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid2",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "ulid") {
            if (!ulidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ulid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "url") {
            try {
              new URL(input.data);
            } catch {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "url",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "regex") {
            check.regex.lastIndex = 0;
            const testResult = check.regex.test(input.data);
            if (!testResult) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "regex",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "trim") {
            input.data = input.data.trim();
          } else if (check.kind === "includes") {
            if (!input.data.includes(check.value, check.position)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { includes: check.value, position: check.position },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "toLowerCase") {
            input.data = input.data.toLowerCase();
          } else if (check.kind === "toUpperCase") {
            input.data = input.data.toUpperCase();
          } else if (check.kind === "startsWith") {
            if (!input.data.startsWith(check.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { startsWith: check.value },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "endsWith") {
            if (!input.data.endsWith(check.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { endsWith: check.value },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "datetime") {
            const regex3 = datetimeRegex(check);
            if (!regex3.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "datetime",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "date") {
            const regex3 = dateRegex;
            if (!regex3.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "date",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "time") {
            const regex3 = timeRegex(check);
            if (!regex3.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "time",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "duration") {
            if (!durationRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "duration",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "ip") {
            if (!isValidIP(input.data, check.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ip",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "jwt") {
            if (!isValidJWT(input.data, check.alg)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "jwt",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cidr") {
            if (!isValidCidr(input.data, check.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cidr",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "base64") {
            if (!base64Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "base64url") {
            if (!base64urlRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64url",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util2.assertNever(check);
          }
        }
        return { status: status.value, value: input.data };
      }
      _regex(regex3, validation2, message) {
        return this.refinement((data) => regex3.test(data), {
          validation: validation2,
          code: ZodIssueCode.invalid_string,
          ...errorUtil.errToObj(message)
        });
      }
      _addCheck(check) {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      email(message) {
        return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
      }
      url(message) {
        return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
      }
      emoji(message) {
        return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
      }
      uuid(message) {
        return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
      }
      nanoid(message) {
        return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
      }
      cuid(message) {
        return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
      }
      cuid2(message) {
        return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
      }
      ulid(message) {
        return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
      }
      base64(message) {
        return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
      }
      base64url(message) {
        return this._addCheck({
          kind: "base64url",
          ...errorUtil.errToObj(message)
        });
      }
      jwt(options2) {
        return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options2) });
      }
      ip(options2) {
        return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options2) });
      }
      cidr(options2) {
        return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options2) });
      }
      datetime(options2) {
        if (typeof options2 === "string") {
          return this._addCheck({
            kind: "datetime",
            precision: null,
            offset: false,
            local: false,
            message: options2
          });
        }
        return this._addCheck({
          kind: "datetime",
          precision: typeof options2?.precision === "undefined" ? null : options2?.precision,
          offset: options2?.offset ?? false,
          local: options2?.local ?? false,
          ...errorUtil.errToObj(options2?.message)
        });
      }
      date(message) {
        return this._addCheck({ kind: "date", message });
      }
      time(options2) {
        if (typeof options2 === "string") {
          return this._addCheck({
            kind: "time",
            precision: null,
            message: options2
          });
        }
        return this._addCheck({
          kind: "time",
          precision: typeof options2?.precision === "undefined" ? null : options2?.precision,
          ...errorUtil.errToObj(options2?.message)
        });
      }
      duration(message) {
        return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
      }
      regex(regex3, message) {
        return this._addCheck({
          kind: "regex",
          regex: regex3,
          ...errorUtil.errToObj(message)
        });
      }
      includes(value, options2) {
        return this._addCheck({
          kind: "includes",
          value,
          position: options2?.position,
          ...errorUtil.errToObj(options2?.message)
        });
      }
      startsWith(value, message) {
        return this._addCheck({
          kind: "startsWith",
          value,
          ...errorUtil.errToObj(message)
        });
      }
      endsWith(value, message) {
        return this._addCheck({
          kind: "endsWith",
          value,
          ...errorUtil.errToObj(message)
        });
      }
      min(minLength, message) {
        return this._addCheck({
          kind: "min",
          value: minLength,
          ...errorUtil.errToObj(message)
        });
      }
      max(maxLength, message) {
        return this._addCheck({
          kind: "max",
          value: maxLength,
          ...errorUtil.errToObj(message)
        });
      }
      length(len, message) {
        return this._addCheck({
          kind: "length",
          value: len,
          ...errorUtil.errToObj(message)
        });
      }
      /**
       * Equivalent to `.min(1)`
       */
      nonempty(message) {
        return this.min(1, errorUtil.errToObj(message));
      }
      trim() {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "trim" }]
        });
      }
      toLowerCase() {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "toLowerCase" }]
        });
      }
      toUpperCase() {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "toUpperCase" }]
        });
      }
      get isDatetime() {
        return !!this._def.checks.find((ch) => ch.kind === "datetime");
      }
      get isDate() {
        return !!this._def.checks.find((ch) => ch.kind === "date");
      }
      get isTime() {
        return !!this._def.checks.find((ch) => ch.kind === "time");
      }
      get isDuration() {
        return !!this._def.checks.find((ch) => ch.kind === "duration");
      }
      get isEmail() {
        return !!this._def.checks.find((ch) => ch.kind === "email");
      }
      get isURL() {
        return !!this._def.checks.find((ch) => ch.kind === "url");
      }
      get isEmoji() {
        return !!this._def.checks.find((ch) => ch.kind === "emoji");
      }
      get isUUID() {
        return !!this._def.checks.find((ch) => ch.kind === "uuid");
      }
      get isNANOID() {
        return !!this._def.checks.find((ch) => ch.kind === "nanoid");
      }
      get isCUID() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid");
      }
      get isCUID2() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid2");
      }
      get isULID() {
        return !!this._def.checks.find((ch) => ch.kind === "ulid");
      }
      get isIP() {
        return !!this._def.checks.find((ch) => ch.kind === "ip");
      }
      get isCIDR() {
        return !!this._def.checks.find((ch) => ch.kind === "cidr");
      }
      get isBase64() {
        return !!this._def.checks.find((ch) => ch.kind === "base64");
      }
      get isBase64url() {
        return !!this._def.checks.find((ch) => ch.kind === "base64url");
      }
      get minLength() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min;
      }
      get maxLength() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
    };
    ZodString.create = (params) => {
      return new ZodString({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodString,
        coerce: params?.coerce ?? false,
        ...processCreateParams(params)
      });
    };
    __name(floatSafeRemainder, "floatSafeRemainder");
    ZodNumber = class _ZodNumber extends ZodType {
      static {
        __name(this, "ZodNumber");
      }
      constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
        this.step = this.multipleOf;
      }
      _parse(input) {
        if (this._def.coerce) {
          input.data = Number(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.number) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.number,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check of this._def.checks) {
          if (check.kind === "int") {
            if (!util2.isInteger(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: "integer",
                received: "float",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "min") {
            const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check.value,
                type: "number",
                inclusive: check.inclusive,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check.value,
                type: "number",
                inclusive: check.inclusive,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "multipleOf") {
            if (floatSafeRemainder(input.data, check.value) !== 0) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check.value,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "finite") {
            if (!Number.isFinite(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_finite,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util2.assertNever(check);
          }
        }
        return { status: status.value, value: input.data };
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
      }
      setLimit(kind, value, inclusive, message) {
        return new _ZodNumber({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check) {
        return new _ZodNumber({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      int(message) {
        return this._addCheck({
          kind: "int",
          message: errorUtil.toString(message)
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      finite(message) {
        return this._addCheck({
          kind: "finite",
          message: errorUtil.toString(message)
        });
      }
      safe(message) {
        return this._addCheck({
          kind: "min",
          inclusive: true,
          value: Number.MIN_SAFE_INTEGER,
          message: errorUtil.toString(message)
        })._addCheck({
          kind: "max",
          inclusive: true,
          value: Number.MAX_SAFE_INTEGER,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min;
      }
      get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
      get isInt() {
        return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util2.isInteger(ch.value));
      }
      get isFinite() {
        let max = null;
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
            return true;
          } else if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          } else if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return Number.isFinite(min) && Number.isFinite(max);
      }
    };
    ZodNumber.create = (params) => {
      return new ZodNumber({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodNumber,
        coerce: params?.coerce || false,
        ...processCreateParams(params)
      });
    };
    ZodBigInt = class _ZodBigInt extends ZodType {
      static {
        __name(this, "ZodBigInt");
      }
      constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
      }
      _parse(input) {
        if (this._def.coerce) {
          try {
            input.data = BigInt(input.data);
          } catch {
            return this._getInvalidInput(input);
          }
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.bigint) {
          return this._getInvalidInput(input);
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check of this._def.checks) {
          if (check.kind === "min") {
            const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                type: "bigint",
                minimum: check.value,
                inclusive: check.inclusive,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                type: "bigint",
                maximum: check.value,
                inclusive: check.inclusive,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "multipleOf") {
            if (input.data % check.value !== BigInt(0)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check.value,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util2.assertNever(check);
          }
        }
        return { status: status.value, value: input.data };
      }
      _getInvalidInput(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_type,
          expected: ZodParsedType.bigint,
          received: ctx.parsedType
        });
        return INVALID;
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
      }
      setLimit(kind, value, inclusive, message) {
        return new _ZodBigInt({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check) {
        return new _ZodBigInt({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min;
      }
      get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
    };
    ZodBigInt.create = (params) => {
      return new ZodBigInt({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodBigInt,
        coerce: params?.coerce ?? false,
        ...processCreateParams(params)
      });
    };
    ZodBoolean = class extends ZodType {
      static {
        __name(this, "ZodBoolean");
      }
      _parse(input) {
        if (this._def.coerce) {
          input.data = Boolean(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.boolean) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.boolean,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodBoolean.create = (params) => {
      return new ZodBoolean({
        typeName: ZodFirstPartyTypeKind.ZodBoolean,
        coerce: params?.coerce || false,
        ...processCreateParams(params)
      });
    };
    ZodDate = class _ZodDate extends ZodType {
      static {
        __name(this, "ZodDate");
      }
      _parse(input) {
        if (this._def.coerce) {
          input.data = new Date(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.date) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.date,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        if (Number.isNaN(input.data.getTime())) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_date
          });
          return INVALID;
        }
        const status = new ParseStatus();
        let ctx = void 0;
        for (const check of this._def.checks) {
          if (check.kind === "min") {
            if (input.data.getTime() < check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                message: check.message,
                inclusive: true,
                exact: false,
                minimum: check.value,
                type: "date"
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            if (input.data.getTime() > check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                message: check.message,
                inclusive: true,
                exact: false,
                maximum: check.value,
                type: "date"
              });
              status.dirty();
            }
          } else {
            util2.assertNever(check);
          }
        }
        return {
          status: status.value,
          value: new Date(input.data.getTime())
        };
      }
      _addCheck(check) {
        return new _ZodDate({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      min(minDate, message) {
        return this._addCheck({
          kind: "min",
          value: minDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      max(maxDate, message) {
        return this._addCheck({
          kind: "max",
          value: maxDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      get minDate() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min != null ? new Date(min) : null;
      }
      get maxDate() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max != null ? new Date(max) : null;
      }
    };
    ZodDate.create = (params) => {
      return new ZodDate({
        checks: [],
        coerce: params?.coerce || false,
        typeName: ZodFirstPartyTypeKind.ZodDate,
        ...processCreateParams(params)
      });
    };
    ZodSymbol = class extends ZodType {
      static {
        __name(this, "ZodSymbol");
      }
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.symbol) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.symbol,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodSymbol.create = (params) => {
      return new ZodSymbol({
        typeName: ZodFirstPartyTypeKind.ZodSymbol,
        ...processCreateParams(params)
      });
    };
    ZodUndefined = class extends ZodType {
      static {
        __name(this, "ZodUndefined");
      }
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.undefined,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodUndefined.create = (params) => {
      return new ZodUndefined({
        typeName: ZodFirstPartyTypeKind.ZodUndefined,
        ...processCreateParams(params)
      });
    };
    ZodNull = class extends ZodType {
      static {
        __name(this, "ZodNull");
      }
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.null) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.null,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodNull.create = (params) => {
      return new ZodNull({
        typeName: ZodFirstPartyTypeKind.ZodNull,
        ...processCreateParams(params)
      });
    };
    ZodAny = class extends ZodType {
      static {
        __name(this, "ZodAny");
      }
      constructor() {
        super(...arguments);
        this._any = true;
      }
      _parse(input) {
        return OK(input.data);
      }
    };
    ZodAny.create = (params) => {
      return new ZodAny({
        typeName: ZodFirstPartyTypeKind.ZodAny,
        ...processCreateParams(params)
      });
    };
    ZodUnknown = class extends ZodType {
      static {
        __name(this, "ZodUnknown");
      }
      constructor() {
        super(...arguments);
        this._unknown = true;
      }
      _parse(input) {
        return OK(input.data);
      }
    };
    ZodUnknown.create = (params) => {
      return new ZodUnknown({
        typeName: ZodFirstPartyTypeKind.ZodUnknown,
        ...processCreateParams(params)
      });
    };
    ZodNever = class extends ZodType {
      static {
        __name(this, "ZodNever");
      }
      _parse(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_type,
          expected: ZodParsedType.never,
          received: ctx.parsedType
        });
        return INVALID;
      }
    };
    ZodNever.create = (params) => {
      return new ZodNever({
        typeName: ZodFirstPartyTypeKind.ZodNever,
        ...processCreateParams(params)
      });
    };
    ZodVoid = class extends ZodType {
      static {
        __name(this, "ZodVoid");
      }
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.void,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodVoid.create = (params) => {
      return new ZodVoid({
        typeName: ZodFirstPartyTypeKind.ZodVoid,
        ...processCreateParams(params)
      });
    };
    ZodArray = class _ZodArray extends ZodType {
      static {
        __name(this, "ZodArray");
      }
      _parse(input) {
        const { ctx, status } = this._processInputParams(input);
        const def2 = this._def;
        if (ctx.parsedType !== ZodParsedType.array) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.array,
            received: ctx.parsedType
          });
          return INVALID;
        }
        if (def2.exactLength !== null) {
          const tooBig = ctx.data.length > def2.exactLength.value;
          const tooSmall = ctx.data.length < def2.exactLength.value;
          if (tooBig || tooSmall) {
            addIssueToContext(ctx, {
              code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
              minimum: tooSmall ? def2.exactLength.value : void 0,
              maximum: tooBig ? def2.exactLength.value : void 0,
              type: "array",
              inclusive: true,
              exact: true,
              message: def2.exactLength.message
            });
            status.dirty();
          }
        }
        if (def2.minLength !== null) {
          if (ctx.data.length < def2.minLength.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: def2.minLength.value,
              type: "array",
              inclusive: true,
              exact: false,
              message: def2.minLength.message
            });
            status.dirty();
          }
        }
        if (def2.maxLength !== null) {
          if (ctx.data.length > def2.maxLength.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: def2.maxLength.value,
              type: "array",
              inclusive: true,
              exact: false,
              message: def2.maxLength.message
            });
            status.dirty();
          }
        }
        if (ctx.common.async) {
          return Promise.all([...ctx.data].map((item, i) => {
            return def2.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
          })).then((result2) => {
            return ParseStatus.mergeArray(status, result2);
          });
        }
        const result = [...ctx.data].map((item, i) => {
          return def2.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
        });
        return ParseStatus.mergeArray(status, result);
      }
      get element() {
        return this._def.type;
      }
      min(minLength, message) {
        return new _ZodArray({
          ...this._def,
          minLength: { value: minLength, message: errorUtil.toString(message) }
        });
      }
      max(maxLength, message) {
        return new _ZodArray({
          ...this._def,
          maxLength: { value: maxLength, message: errorUtil.toString(message) }
        });
      }
      length(len, message) {
        return new _ZodArray({
          ...this._def,
          exactLength: { value: len, message: errorUtil.toString(message) }
        });
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    ZodArray.create = (schema, params) => {
      return new ZodArray({
        type: schema,
        minLength: null,
        maxLength: null,
        exactLength: null,
        typeName: ZodFirstPartyTypeKind.ZodArray,
        ...processCreateParams(params)
      });
    };
    __name(deepPartialify, "deepPartialify");
    ZodObject = class _ZodObject extends ZodType {
      static {
        __name(this, "ZodObject");
      }
      constructor() {
        super(...arguments);
        this._cached = null;
        this.nonstrict = this.passthrough;
        this.augment = this.extend;
      }
      _getCached() {
        if (this._cached !== null)
          return this._cached;
        const shape = this._def.shape();
        const keys = util2.objectKeys(shape);
        this._cached = { shape, keys };
        return this._cached;
      }
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.object) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        const { status, ctx } = this._processInputParams(input);
        const { shape, keys: shapeKeys } = this._getCached();
        const extraKeys = [];
        if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
          for (const key in ctx.data) {
            if (!shapeKeys.includes(key)) {
              extraKeys.push(key);
            }
          }
        }
        const pairs = [];
        for (const key of shapeKeys) {
          const keyValidator = shape[key];
          const value = ctx.data[key];
          pairs.push({
            key: { status: "valid", value: key },
            value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
            alwaysSet: key in ctx.data
          });
        }
        if (this._def.catchall instanceof ZodNever) {
          const unknownKeys = this._def.unknownKeys;
          if (unknownKeys === "passthrough") {
            for (const key of extraKeys) {
              pairs.push({
                key: { status: "valid", value: key },
                value: { status: "valid", value: ctx.data[key] }
              });
            }
          } else if (unknownKeys === "strict") {
            if (extraKeys.length > 0) {
              addIssueToContext(ctx, {
                code: ZodIssueCode.unrecognized_keys,
                keys: extraKeys
              });
              status.dirty();
            }
          } else if (unknownKeys === "strip") {
          } else {
            throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
          }
        } else {
          const catchall = this._def.catchall;
          for (const key of extraKeys) {
            const value = ctx.data[key];
            pairs.push({
              key: { status: "valid", value: key },
              value: catchall._parse(
                new ParseInputLazyPath(ctx, value, ctx.path, key)
                //, ctx.child(key), value, getParsedType(value)
              ),
              alwaysSet: key in ctx.data
            });
          }
        }
        if (ctx.common.async) {
          return Promise.resolve().then(async () => {
            const syncPairs = [];
            for (const pair of pairs) {
              const key = await pair.key;
              const value = await pair.value;
              syncPairs.push({
                key,
                value,
                alwaysSet: pair.alwaysSet
              });
            }
            return syncPairs;
          }).then((syncPairs) => {
            return ParseStatus.mergeObjectSync(status, syncPairs);
          });
        } else {
          return ParseStatus.mergeObjectSync(status, pairs);
        }
      }
      get shape() {
        return this._def.shape();
      }
      strict(message) {
        errorUtil.errToObj;
        return new _ZodObject({
          ...this._def,
          unknownKeys: "strict",
          ...message !== void 0 ? {
            errorMap: /* @__PURE__ */ __name((issue, ctx) => {
              const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
              if (issue.code === "unrecognized_keys")
                return {
                  message: errorUtil.errToObj(message).message ?? defaultError
                };
              return {
                message: defaultError
              };
            }, "errorMap")
          } : {}
        });
      }
      strip() {
        return new _ZodObject({
          ...this._def,
          unknownKeys: "strip"
        });
      }
      passthrough() {
        return new _ZodObject({
          ...this._def,
          unknownKeys: "passthrough"
        });
      }
      // const AugmentFactory =
      //   <Def extends ZodObjectDef>(def: Def) =>
      //   <Augmentation extends ZodRawShape>(
      //     augmentation: Augmentation
      //   ): ZodObject<
      //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
      //     Def["unknownKeys"],
      //     Def["catchall"]
      //   > => {
      //     return new ZodObject({
      //       ...def,
      //       shape: () => ({
      //         ...def.shape(),
      //         ...augmentation,
      //       }),
      //     }) as any;
      //   };
      extend(augmentation) {
        return new _ZodObject({
          ...this._def,
          shape: /* @__PURE__ */ __name(() => ({
            ...this._def.shape(),
            ...augmentation
          }), "shape")
        });
      }
      /**
       * Prior to zod@1.0.12 there was a bug in the
       * inferred type of merged objects. Please
       * upgrade if you are experiencing issues.
       */
      merge(merging) {
        const merged = new _ZodObject({
          unknownKeys: merging._def.unknownKeys,
          catchall: merging._def.catchall,
          shape: /* @__PURE__ */ __name(() => ({
            ...this._def.shape(),
            ...merging._def.shape()
          }), "shape"),
          typeName: ZodFirstPartyTypeKind.ZodObject
        });
        return merged;
      }
      // merge<
      //   Incoming extends AnyZodObject,
      //   Augmentation extends Incoming["shape"],
      //   NewOutput extends {
      //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
      //       ? Augmentation[k]["_output"]
      //       : k extends keyof Output
      //       ? Output[k]
      //       : never;
      //   },
      //   NewInput extends {
      //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
      //       ? Augmentation[k]["_input"]
      //       : k extends keyof Input
      //       ? Input[k]
      //       : never;
      //   }
      // >(
      //   merging: Incoming
      // ): ZodObject<
      //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
      //   Incoming["_def"]["unknownKeys"],
      //   Incoming["_def"]["catchall"],
      //   NewOutput,
      //   NewInput
      // > {
      //   const merged: any = new ZodObject({
      //     unknownKeys: merging._def.unknownKeys,
      //     catchall: merging._def.catchall,
      //     shape: () =>
      //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
      //     typeName: ZodFirstPartyTypeKind.ZodObject,
      //   }) as any;
      //   return merged;
      // }
      setKey(key, schema) {
        return this.augment({ [key]: schema });
      }
      // merge<Incoming extends AnyZodObject>(
      //   merging: Incoming
      // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
      // ZodObject<
      //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
      //   Incoming["_def"]["unknownKeys"],
      //   Incoming["_def"]["catchall"]
      // > {
      //   // const mergedShape = objectUtil.mergeShapes(
      //   //   this._def.shape(),
      //   //   merging._def.shape()
      //   // );
      //   const merged: any = new ZodObject({
      //     unknownKeys: merging._def.unknownKeys,
      //     catchall: merging._def.catchall,
      //     shape: () =>
      //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
      //     typeName: ZodFirstPartyTypeKind.ZodObject,
      //   }) as any;
      //   return merged;
      // }
      catchall(index) {
        return new _ZodObject({
          ...this._def,
          catchall: index
        });
      }
      pick(mask) {
        const shape = {};
        for (const key of util2.objectKeys(mask)) {
          if (mask[key] && this.shape[key]) {
            shape[key] = this.shape[key];
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: /* @__PURE__ */ __name(() => shape, "shape")
        });
      }
      omit(mask) {
        const shape = {};
        for (const key of util2.objectKeys(this.shape)) {
          if (!mask[key]) {
            shape[key] = this.shape[key];
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: /* @__PURE__ */ __name(() => shape, "shape")
        });
      }
      /**
       * @deprecated
       */
      deepPartial() {
        return deepPartialify(this);
      }
      partial(mask) {
        const newShape = {};
        for (const key of util2.objectKeys(this.shape)) {
          const fieldSchema = this.shape[key];
          if (mask && !mask[key]) {
            newShape[key] = fieldSchema;
          } else {
            newShape[key] = fieldSchema.optional();
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: /* @__PURE__ */ __name(() => newShape, "shape")
        });
      }
      required(mask) {
        const newShape = {};
        for (const key of util2.objectKeys(this.shape)) {
          if (mask && !mask[key]) {
            newShape[key] = this.shape[key];
          } else {
            const fieldSchema = this.shape[key];
            let newField = fieldSchema;
            while (newField instanceof ZodOptional) {
              newField = newField._def.innerType;
            }
            newShape[key] = newField;
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: /* @__PURE__ */ __name(() => newShape, "shape")
        });
      }
      keyof() {
        return createZodEnum(util2.objectKeys(this.shape));
      }
    };
    ZodObject.create = (shape, params) => {
      return new ZodObject({
        shape: /* @__PURE__ */ __name(() => shape, "shape"),
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodObject.strictCreate = (shape, params) => {
      return new ZodObject({
        shape: /* @__PURE__ */ __name(() => shape, "shape"),
        unknownKeys: "strict",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodObject.lazycreate = (shape, params) => {
      return new ZodObject({
        shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodUnion = class extends ZodType {
      static {
        __name(this, "ZodUnion");
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const options2 = this._def.options;
        function handleResults(results) {
          for (const result of results) {
            if (result.result.status === "valid") {
              return result.result;
            }
          }
          for (const result of results) {
            if (result.result.status === "dirty") {
              ctx.common.issues.push(...result.ctx.common.issues);
              return result.result;
            }
          }
          const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union,
            unionErrors
          });
          return INVALID;
        }
        __name(handleResults, "handleResults");
        if (ctx.common.async) {
          return Promise.all(options2.map(async (option2) => {
            const childCtx = {
              ...ctx,
              common: {
                ...ctx.common,
                issues: []
              },
              parent: null
            };
            return {
              result: await option2._parseAsync({
                data: ctx.data,
                path: ctx.path,
                parent: childCtx
              }),
              ctx: childCtx
            };
          })).then(handleResults);
        } else {
          let dirty = void 0;
          const issues = [];
          for (const option2 of options2) {
            const childCtx = {
              ...ctx,
              common: {
                ...ctx.common,
                issues: []
              },
              parent: null
            };
            const result = option2._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: childCtx
            });
            if (result.status === "valid") {
              return result;
            } else if (result.status === "dirty" && !dirty) {
              dirty = { result, ctx: childCtx };
            }
            if (childCtx.common.issues.length) {
              issues.push(childCtx.common.issues);
            }
          }
          if (dirty) {
            ctx.common.issues.push(...dirty.ctx.common.issues);
            return dirty.result;
          }
          const unionErrors = issues.map((issues2) => new ZodError(issues2));
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union,
            unionErrors
          });
          return INVALID;
        }
      }
      get options() {
        return this._def.options;
      }
    };
    ZodUnion.create = (types3, params) => {
      return new ZodUnion({
        options: types3,
        typeName: ZodFirstPartyTypeKind.ZodUnion,
        ...processCreateParams(params)
      });
    };
    getDiscriminator = /* @__PURE__ */ __name((type) => {
      if (type instanceof ZodLazy) {
        return getDiscriminator(type.schema);
      } else if (type instanceof ZodEffects) {
        return getDiscriminator(type.innerType());
      } else if (type instanceof ZodLiteral) {
        return [type.value];
      } else if (type instanceof ZodEnum) {
        return type.options;
      } else if (type instanceof ZodNativeEnum) {
        return util2.objectValues(type.enum);
      } else if (type instanceof ZodDefault) {
        return getDiscriminator(type._def.innerType);
      } else if (type instanceof ZodUndefined) {
        return [void 0];
      } else if (type instanceof ZodNull) {
        return [null];
      } else if (type instanceof ZodOptional) {
        return [void 0, ...getDiscriminator(type.unwrap())];
      } else if (type instanceof ZodNullable) {
        return [null, ...getDiscriminator(type.unwrap())];
      } else if (type instanceof ZodBranded) {
        return getDiscriminator(type.unwrap());
      } else if (type instanceof ZodReadonly) {
        return getDiscriminator(type.unwrap());
      } else if (type instanceof ZodCatch) {
        return getDiscriminator(type._def.innerType);
      } else {
        return [];
      }
    }, "getDiscriminator");
    ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
      static {
        __name(this, "ZodDiscriminatedUnion");
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const discriminator = this.discriminator;
        const discriminatorValue = ctx.data[discriminator];
        const option2 = this.optionsMap.get(discriminatorValue);
        if (!option2) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union_discriminator,
            options: Array.from(this.optionsMap.keys()),
            path: [discriminator]
          });
          return INVALID;
        }
        if (ctx.common.async) {
          return option2._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
        } else {
          return option2._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
        }
      }
      get discriminator() {
        return this._def.discriminator;
      }
      get options() {
        return this._def.options;
      }
      get optionsMap() {
        return this._def.optionsMap;
      }
      /**
       * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
       * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
       * have a different value for each object in the union.
       * @param discriminator the name of the discriminator property
       * @param types an array of object schemas
       * @param params
       */
      static create(discriminator, options2, params) {
        const optionsMap = /* @__PURE__ */ new Map();
        for (const type of options2) {
          const discriminatorValues = getDiscriminator(type.shape[discriminator]);
          if (!discriminatorValues.length) {
            throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
          }
          for (const value of discriminatorValues) {
            if (optionsMap.has(value)) {
              throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
            }
            optionsMap.set(value, type);
          }
        }
        return new _ZodDiscriminatedUnion({
          typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
          discriminator,
          options: options2,
          optionsMap,
          ...processCreateParams(params)
        });
      }
    };
    __name(mergeValues, "mergeValues");
    ZodIntersection = class extends ZodType {
      static {
        __name(this, "ZodIntersection");
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const handleParsed = /* @__PURE__ */ __name((parsedLeft, parsedRight) => {
          if (isAborted(parsedLeft) || isAborted(parsedRight)) {
            return INVALID;
          }
          const merged = mergeValues(parsedLeft.value, parsedRight.value);
          if (!merged.valid) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.invalid_intersection_types
            });
            return INVALID;
          }
          if (isDirty(parsedLeft) || isDirty(parsedRight)) {
            status.dirty();
          }
          return { status: status.value, value: merged.data };
        }, "handleParsed");
        if (ctx.common.async) {
          return Promise.all([
            this._def.left._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            }),
            this._def.right._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            })
          ]).then(([left3, right3]) => handleParsed(left3, right3));
        } else {
          return handleParsed(this._def.left._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          }), this._def.right._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          }));
        }
      }
    };
    ZodIntersection.create = (left3, right3, params) => {
      return new ZodIntersection({
        left: left3,
        right: right3,
        typeName: ZodFirstPartyTypeKind.ZodIntersection,
        ...processCreateParams(params)
      });
    };
    ZodTuple = class _ZodTuple extends ZodType {
      static {
        __name(this, "ZodTuple");
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.array) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.array,
            received: ctx.parsedType
          });
          return INVALID;
        }
        if (ctx.data.length < this._def.items.length) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: this._def.items.length,
            inclusive: true,
            exact: false,
            type: "array"
          });
          return INVALID;
        }
        const rest = this._def.rest;
        if (!rest && ctx.data.length > this._def.items.length) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: this._def.items.length,
            inclusive: true,
            exact: false,
            type: "array"
          });
          status.dirty();
        }
        const items = [...ctx.data].map((item, itemIndex) => {
          const schema = this._def.items[itemIndex] || this._def.rest;
          if (!schema)
            return null;
          return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
        }).filter((x) => !!x);
        if (ctx.common.async) {
          return Promise.all(items).then((results) => {
            return ParseStatus.mergeArray(status, results);
          });
        } else {
          return ParseStatus.mergeArray(status, items);
        }
      }
      get items() {
        return this._def.items;
      }
      rest(rest) {
        return new _ZodTuple({
          ...this._def,
          rest
        });
      }
    };
    ZodTuple.create = (schemas, params) => {
      if (!Array.isArray(schemas)) {
        throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
      }
      return new ZodTuple({
        items: schemas,
        typeName: ZodFirstPartyTypeKind.ZodTuple,
        rest: null,
        ...processCreateParams(params)
      });
    };
    ZodRecord = class _ZodRecord extends ZodType {
      static {
        __name(this, "ZodRecord");
      }
      get keySchema() {
        return this._def.keyType;
      }
      get valueSchema() {
        return this._def.valueType;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const pairs = [];
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        for (const key in ctx.data) {
          pairs.push({
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
            value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
            alwaysSet: key in ctx.data
          });
        }
        if (ctx.common.async) {
          return ParseStatus.mergeObjectAsync(status, pairs);
        } else {
          return ParseStatus.mergeObjectSync(status, pairs);
        }
      }
      get element() {
        return this._def.valueType;
      }
      static create(first2, second, third) {
        if (second instanceof ZodType) {
          return new _ZodRecord({
            keyType: first2,
            valueType: second,
            typeName: ZodFirstPartyTypeKind.ZodRecord,
            ...processCreateParams(third)
          });
        }
        return new _ZodRecord({
          keyType: ZodString.create(),
          valueType: first2,
          typeName: ZodFirstPartyTypeKind.ZodRecord,
          ...processCreateParams(second)
        });
      }
    };
    ZodMap = class extends ZodType {
      static {
        __name(this, "ZodMap");
      }
      get keySchema() {
        return this._def.keyType;
      }
      get valueSchema() {
        return this._def.valueType;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.map) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.map,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        const pairs = [...ctx.data.entries()].map(([key, value], index) => {
          return {
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
            value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
          };
        });
        if (ctx.common.async) {
          const finalMap = /* @__PURE__ */ new Map();
          return Promise.resolve().then(async () => {
            for (const pair of pairs) {
              const key = await pair.key;
              const value = await pair.value;
              if (key.status === "aborted" || value.status === "aborted") {
                return INVALID;
              }
              if (key.status === "dirty" || value.status === "dirty") {
                status.dirty();
              }
              finalMap.set(key.value, value.value);
            }
            return { status: status.value, value: finalMap };
          });
        } else {
          const finalMap = /* @__PURE__ */ new Map();
          for (const pair of pairs) {
            const key = pair.key;
            const value = pair.value;
            if (key.status === "aborted" || value.status === "aborted") {
              return INVALID;
            }
            if (key.status === "dirty" || value.status === "dirty") {
              status.dirty();
            }
            finalMap.set(key.value, value.value);
          }
          return { status: status.value, value: finalMap };
        }
      }
    };
    ZodMap.create = (keyType, valueType, params) => {
      return new ZodMap({
        valueType,
        keyType,
        typeName: ZodFirstPartyTypeKind.ZodMap,
        ...processCreateParams(params)
      });
    };
    ZodSet = class _ZodSet extends ZodType {
      static {
        __name(this, "ZodSet");
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.set) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.set,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const def2 = this._def;
        if (def2.minSize !== null) {
          if (ctx.data.size < def2.minSize.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: def2.minSize.value,
              type: "set",
              inclusive: true,
              exact: false,
              message: def2.minSize.message
            });
            status.dirty();
          }
        }
        if (def2.maxSize !== null) {
          if (ctx.data.size > def2.maxSize.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: def2.maxSize.value,
              type: "set",
              inclusive: true,
              exact: false,
              message: def2.maxSize.message
            });
            status.dirty();
          }
        }
        const valueType = this._def.valueType;
        function finalizeSet(elements2) {
          const parsedSet = /* @__PURE__ */ new Set();
          for (const element of elements2) {
            if (element.status === "aborted")
              return INVALID;
            if (element.status === "dirty")
              status.dirty();
            parsedSet.add(element.value);
          }
          return { status: status.value, value: parsedSet };
        }
        __name(finalizeSet, "finalizeSet");
        const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
        if (ctx.common.async) {
          return Promise.all(elements).then((elements2) => finalizeSet(elements2));
        } else {
          return finalizeSet(elements);
        }
      }
      min(minSize, message) {
        return new _ZodSet({
          ...this._def,
          minSize: { value: minSize, message: errorUtil.toString(message) }
        });
      }
      max(maxSize, message) {
        return new _ZodSet({
          ...this._def,
          maxSize: { value: maxSize, message: errorUtil.toString(message) }
        });
      }
      size(size, message) {
        return this.min(size, message).max(size, message);
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    ZodSet.create = (valueType, params) => {
      return new ZodSet({
        valueType,
        minSize: null,
        maxSize: null,
        typeName: ZodFirstPartyTypeKind.ZodSet,
        ...processCreateParams(params)
      });
    };
    ZodFunction = class _ZodFunction extends ZodType {
      static {
        __name(this, "ZodFunction");
      }
      constructor() {
        super(...arguments);
        this.validate = this.implement;
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.function) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.function,
            received: ctx.parsedType
          });
          return INVALID;
        }
        function makeArgsIssue(args, error) {
          return makeIssue({
            data: args,
            path: ctx.path,
            errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
            issueData: {
              code: ZodIssueCode.invalid_arguments,
              argumentsError: error
            }
          });
        }
        __name(makeArgsIssue, "makeArgsIssue");
        function makeReturnsIssue(returns, error) {
          return makeIssue({
            data: returns,
            path: ctx.path,
            errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
            issueData: {
              code: ZodIssueCode.invalid_return_type,
              returnTypeError: error
            }
          });
        }
        __name(makeReturnsIssue, "makeReturnsIssue");
        const params = { errorMap: ctx.common.contextualErrorMap };
        const fn = ctx.data;
        if (this._def.returns instanceof ZodPromise) {
          const me = this;
          return OK(async function(...args) {
            const error = new ZodError([]);
            const parsedArgs = await me._def.args.parseAsync(args, params).catch((e2) => {
              error.addIssue(makeArgsIssue(args, e2));
              throw error;
            });
            const result = await Reflect.apply(fn, this, parsedArgs);
            const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e2) => {
              error.addIssue(makeReturnsIssue(result, e2));
              throw error;
            });
            return parsedReturns;
          });
        } else {
          const me = this;
          return OK(function(...args) {
            const parsedArgs = me._def.args.safeParse(args, params);
            if (!parsedArgs.success) {
              throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
            }
            const result = Reflect.apply(fn, this, parsedArgs.data);
            const parsedReturns = me._def.returns.safeParse(result, params);
            if (!parsedReturns.success) {
              throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
            }
            return parsedReturns.data;
          });
        }
      }
      parameters() {
        return this._def.args;
      }
      returnType() {
        return this._def.returns;
      }
      args(...items) {
        return new _ZodFunction({
          ...this._def,
          args: ZodTuple.create(items).rest(ZodUnknown.create())
        });
      }
      returns(returnType) {
        return new _ZodFunction({
          ...this._def,
          returns: returnType
        });
      }
      implement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
      }
      strictImplement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
      }
      static create(args, returns, params) {
        return new _ZodFunction({
          args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
          returns: returns || ZodUnknown.create(),
          typeName: ZodFirstPartyTypeKind.ZodFunction,
          ...processCreateParams(params)
        });
      }
    };
    ZodLazy = class extends ZodType {
      static {
        __name(this, "ZodLazy");
      }
      get schema() {
        return this._def.getter();
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const lazySchema = this._def.getter();
        return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
      }
    };
    ZodLazy.create = (getter, params) => {
      return new ZodLazy({
        getter,
        typeName: ZodFirstPartyTypeKind.ZodLazy,
        ...processCreateParams(params)
      });
    };
    ZodLiteral = class extends ZodType {
      static {
        __name(this, "ZodLiteral");
      }
      _parse(input) {
        if (input.data !== this._def.value) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_literal,
            expected: this._def.value
          });
          return INVALID;
        }
        return { status: "valid", value: input.data };
      }
      get value() {
        return this._def.value;
      }
    };
    ZodLiteral.create = (value, params) => {
      return new ZodLiteral({
        value,
        typeName: ZodFirstPartyTypeKind.ZodLiteral,
        ...processCreateParams(params)
      });
    };
    __name(createZodEnum, "createZodEnum");
    ZodEnum = class _ZodEnum extends ZodType {
      static {
        __name(this, "ZodEnum");
      }
      _parse(input) {
        if (typeof input.data !== "string") {
          const ctx = this._getOrReturnCtx(input);
          const expectedValues = this._def.values;
          addIssueToContext(ctx, {
            expected: util2.joinValues(expectedValues),
            received: ctx.parsedType,
            code: ZodIssueCode.invalid_type
          });
          return INVALID;
        }
        if (!this._cache) {
          this._cache = new Set(this._def.values);
        }
        if (!this._cache.has(input.data)) {
          const ctx = this._getOrReturnCtx(input);
          const expectedValues = this._def.values;
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_enum_value,
            options: expectedValues
          });
          return INVALID;
        }
        return OK(input.data);
      }
      get options() {
        return this._def.values;
      }
      get enum() {
        const enumValues = {};
        for (const val of this._def.values) {
          enumValues[val] = val;
        }
        return enumValues;
      }
      get Values() {
        const enumValues = {};
        for (const val of this._def.values) {
          enumValues[val] = val;
        }
        return enumValues;
      }
      get Enum() {
        const enumValues = {};
        for (const val of this._def.values) {
          enumValues[val] = val;
        }
        return enumValues;
      }
      extract(values, newDef = this._def) {
        return _ZodEnum.create(values, {
          ...this._def,
          ...newDef
        });
      }
      exclude(values, newDef = this._def) {
        return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
          ...this._def,
          ...newDef
        });
      }
    };
    ZodEnum.create = createZodEnum;
    ZodNativeEnum = class extends ZodType {
      static {
        __name(this, "ZodNativeEnum");
      }
      _parse(input) {
        const nativeEnumValues = util2.getValidEnumValues(this._def.values);
        const ctx = this._getOrReturnCtx(input);
        if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
          const expectedValues = util2.objectValues(nativeEnumValues);
          addIssueToContext(ctx, {
            expected: util2.joinValues(expectedValues),
            received: ctx.parsedType,
            code: ZodIssueCode.invalid_type
          });
          return INVALID;
        }
        if (!this._cache) {
          this._cache = new Set(util2.getValidEnumValues(this._def.values));
        }
        if (!this._cache.has(input.data)) {
          const expectedValues = util2.objectValues(nativeEnumValues);
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_enum_value,
            options: expectedValues
          });
          return INVALID;
        }
        return OK(input.data);
      }
      get enum() {
        return this._def.values;
      }
    };
    ZodNativeEnum.create = (values, params) => {
      return new ZodNativeEnum({
        values,
        typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
        ...processCreateParams(params)
      });
    };
    ZodPromise = class extends ZodType {
      static {
        __name(this, "ZodPromise");
      }
      unwrap() {
        return this._def.type;
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.promise,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
        return OK(promisified.then((data) => {
          return this._def.type.parseAsync(data, {
            path: ctx.path,
            errorMap: ctx.common.contextualErrorMap
          });
        }));
      }
    };
    ZodPromise.create = (schema, params) => {
      return new ZodPromise({
        type: schema,
        typeName: ZodFirstPartyTypeKind.ZodPromise,
        ...processCreateParams(params)
      });
    };
    ZodEffects = class extends ZodType {
      static {
        __name(this, "ZodEffects");
      }
      innerType() {
        return this._def.schema;
      }
      sourceType() {
        return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const effect = this._def.effect || null;
        const checkCtx = {
          addIssue: /* @__PURE__ */ __name((arg) => {
            addIssueToContext(ctx, arg);
            if (arg.fatal) {
              status.abort();
            } else {
              status.dirty();
            }
          }, "addIssue"),
          get path() {
            return ctx.path;
          }
        };
        checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
        if (effect.type === "preprocess") {
          const processed = effect.transform(ctx.data, checkCtx);
          if (ctx.common.async) {
            return Promise.resolve(processed).then(async (processed2) => {
              if (status.value === "aborted")
                return INVALID;
              const result = await this._def.schema._parseAsync({
                data: processed2,
                path: ctx.path,
                parent: ctx
              });
              if (result.status === "aborted")
                return INVALID;
              if (result.status === "dirty")
                return DIRTY(result.value);
              if (status.value === "dirty")
                return DIRTY(result.value);
              return result;
            });
          } else {
            if (status.value === "aborted")
              return INVALID;
            const result = this._def.schema._parseSync({
              data: processed,
              path: ctx.path,
              parent: ctx
            });
            if (result.status === "aborted")
              return INVALID;
            if (result.status === "dirty")
              return DIRTY(result.value);
            if (status.value === "dirty")
              return DIRTY(result.value);
            return result;
          }
        }
        if (effect.type === "refinement") {
          const executeRefinement = /* @__PURE__ */ __name((acc) => {
            const result = effect.refinement(acc, checkCtx);
            if (ctx.common.async) {
              return Promise.resolve(result);
            }
            if (result instanceof Promise) {
              throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
            }
            return acc;
          }, "executeRefinement");
          if (ctx.common.async === false) {
            const inner = this._def.schema._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (inner.status === "aborted")
              return INVALID;
            if (inner.status === "dirty")
              status.dirty();
            executeRefinement(inner.value);
            return { status: status.value, value: inner.value };
          } else {
            return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
              if (inner.status === "aborted")
                return INVALID;
              if (inner.status === "dirty")
                status.dirty();
              return executeRefinement(inner.value).then(() => {
                return { status: status.value, value: inner.value };
              });
            });
          }
        }
        if (effect.type === "transform") {
          if (ctx.common.async === false) {
            const base = this._def.schema._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (!isValid(base))
              return INVALID;
            const result = effect.transform(base.value, checkCtx);
            if (result instanceof Promise) {
              throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
            }
            return { status: status.value, value: result };
          } else {
            return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
              if (!isValid(base))
                return INVALID;
              return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
                status: status.value,
                value: result
              }));
            });
          }
        }
        util2.assertNever(effect);
      }
    };
    ZodEffects.create = (schema, effect, params) => {
      return new ZodEffects({
        schema,
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        effect,
        ...processCreateParams(params)
      });
    };
    ZodEffects.createWithPreprocess = (preprocess2, schema, params) => {
      return new ZodEffects({
        schema,
        effect: { type: "preprocess", transform: preprocess2 },
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        ...processCreateParams(params)
      });
    };
    ZodOptional = class extends ZodType {
      static {
        __name(this, "ZodOptional");
      }
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.undefined) {
          return OK(void 0);
        }
        return this._def.innerType._parse(input);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodOptional.create = (type, params) => {
      return new ZodOptional({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodOptional,
        ...processCreateParams(params)
      });
    };
    ZodNullable = class extends ZodType {
      static {
        __name(this, "ZodNullable");
      }
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.null) {
          return OK(null);
        }
        return this._def.innerType._parse(input);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodNullable.create = (type, params) => {
      return new ZodNullable({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodNullable,
        ...processCreateParams(params)
      });
    };
    ZodDefault = class extends ZodType {
      static {
        __name(this, "ZodDefault");
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        let data = ctx.data;
        if (ctx.parsedType === ZodParsedType.undefined) {
          data = this._def.defaultValue();
        }
        return this._def.innerType._parse({
          data,
          path: ctx.path,
          parent: ctx
        });
      }
      removeDefault() {
        return this._def.innerType;
      }
    };
    ZodDefault.create = (type, params) => {
      return new ZodDefault({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodDefault,
        defaultValue: typeof params.default === "function" ? params.default : () => params.default,
        ...processCreateParams(params)
      });
    };
    ZodCatch = class extends ZodType {
      static {
        __name(this, "ZodCatch");
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const newCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          }
        };
        const result = this._def.innerType._parse({
          data: newCtx.data,
          path: newCtx.path,
          parent: {
            ...newCtx
          }
        });
        if (isAsync(result)) {
          return result.then((result2) => {
            return {
              status: "valid",
              value: result2.status === "valid" ? result2.value : this._def.catchValue({
                get error() {
                  return new ZodError(newCtx.common.issues);
                },
                input: newCtx.data
              })
            };
          });
        } else {
          return {
            status: "valid",
            value: result.status === "valid" ? result.value : this._def.catchValue({
              get error() {
                return new ZodError(newCtx.common.issues);
              },
              input: newCtx.data
            })
          };
        }
      }
      removeCatch() {
        return this._def.innerType;
      }
    };
    ZodCatch.create = (type, params) => {
      return new ZodCatch({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodCatch,
        catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
        ...processCreateParams(params)
      });
    };
    ZodNaN = class extends ZodType {
      static {
        __name(this, "ZodNaN");
      }
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.nan) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.nan,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return { status: "valid", value: input.data };
      }
    };
    ZodNaN.create = (params) => {
      return new ZodNaN({
        typeName: ZodFirstPartyTypeKind.ZodNaN,
        ...processCreateParams(params)
      });
    };
    BRAND = Symbol("zod_brand");
    ZodBranded = class extends ZodType {
      static {
        __name(this, "ZodBranded");
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const data = ctx.data;
        return this._def.type._parse({
          data,
          path: ctx.path,
          parent: ctx
        });
      }
      unwrap() {
        return this._def.type;
      }
    };
    ZodPipeline = class _ZodPipeline extends ZodType {
      static {
        __name(this, "ZodPipeline");
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.common.async) {
          const handleAsync = /* @__PURE__ */ __name(async () => {
            const inResult = await this._def.in._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (inResult.status === "aborted")
              return INVALID;
            if (inResult.status === "dirty") {
              status.dirty();
              return DIRTY(inResult.value);
            } else {
              return this._def.out._parseAsync({
                data: inResult.value,
                path: ctx.path,
                parent: ctx
              });
            }
          }, "handleAsync");
          return handleAsync();
        } else {
          const inResult = this._def.in._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
          if (inResult.status === "aborted")
            return INVALID;
          if (inResult.status === "dirty") {
            status.dirty();
            return {
              status: "dirty",
              value: inResult.value
            };
          } else {
            return this._def.out._parseSync({
              data: inResult.value,
              path: ctx.path,
              parent: ctx
            });
          }
        }
      }
      static create(a, b) {
        return new _ZodPipeline({
          in: a,
          out: b,
          typeName: ZodFirstPartyTypeKind.ZodPipeline
        });
      }
    };
    ZodReadonly = class extends ZodType {
      static {
        __name(this, "ZodReadonly");
      }
      _parse(input) {
        const result = this._def.innerType._parse(input);
        const freeze = /* @__PURE__ */ __name((data) => {
          if (isValid(data)) {
            data.value = Object.freeze(data.value);
          }
          return data;
        }, "freeze");
        return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodReadonly.create = (type, params) => {
      return new ZodReadonly({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodReadonly,
        ...processCreateParams(params)
      });
    };
    __name(cleanParams, "cleanParams");
    __name(custom, "custom");
    late = {
      object: ZodObject.lazycreate
    };
    (function(ZodFirstPartyTypeKind2) {
      ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
      ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
      ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
      ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
      ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
      ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
      ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
      ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
      ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
      ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
      ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
      ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
      ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
      ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
      ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
      ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
      ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
      ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
      ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
      ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
      ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
      ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
      ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
      ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
      ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
      ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
      ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
      ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
      ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
      ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
      ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
      ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
      ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
      ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
      ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
      ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
    })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
    instanceOfType = /* @__PURE__ */ __name((cls, params = {
      message: `Input not instance of ${cls.name}`
    }) => custom((data) => data instanceof cls, params), "instanceOfType");
    stringType = ZodString.create;
    numberType = ZodNumber.create;
    nanType = ZodNaN.create;
    bigIntType = ZodBigInt.create;
    booleanType = ZodBoolean.create;
    dateType = ZodDate.create;
    symbolType = ZodSymbol.create;
    undefinedType = ZodUndefined.create;
    nullType = ZodNull.create;
    anyType = ZodAny.create;
    unknownType = ZodUnknown.create;
    neverType = ZodNever.create;
    voidType = ZodVoid.create;
    arrayType = ZodArray.create;
    objectType = ZodObject.create;
    strictObjectType = ZodObject.strictCreate;
    unionType = ZodUnion.create;
    discriminatedUnionType = ZodDiscriminatedUnion.create;
    intersectionType = ZodIntersection.create;
    tupleType = ZodTuple.create;
    recordType = ZodRecord.create;
    mapType = ZodMap.create;
    setType = ZodSet.create;
    functionType = ZodFunction.create;
    lazyType = ZodLazy.create;
    literalType = ZodLiteral.create;
    enumType = ZodEnum.create;
    nativeEnumType = ZodNativeEnum.create;
    promiseType = ZodPromise.create;
    effectsType = ZodEffects.create;
    optionalType = ZodOptional.create;
    nullableType = ZodNullable.create;
    preprocessType = ZodEffects.createWithPreprocess;
    pipelineType = ZodPipeline.create;
    ostring = /* @__PURE__ */ __name(() => stringType().optional(), "ostring");
    onumber = /* @__PURE__ */ __name(() => numberType().optional(), "onumber");
    oboolean = /* @__PURE__ */ __name(() => booleanType().optional(), "oboolean");
    coerce = {
      string: /* @__PURE__ */ __name((arg) => ZodString.create({ ...arg, coerce: true }), "string"),
      number: /* @__PURE__ */ __name((arg) => ZodNumber.create({ ...arg, coerce: true }), "number"),
      boolean: /* @__PURE__ */ __name((arg) => ZodBoolean.create({
        ...arg,
        coerce: true
      }), "boolean"),
      bigint: /* @__PURE__ */ __name((arg) => ZodBigInt.create({ ...arg, coerce: true }), "bigint"),
      date: /* @__PURE__ */ __name((arg) => ZodDate.create({ ...arg, coerce: true }), "date")
    };
    NEVER = INVALID;
  }
});

// node_modules/zod/v3/external.js
var external_exports = {};
__export(external_exports, {
  BRAND: () => BRAND,
  DIRTY: () => DIRTY,
  EMPTY_PATH: () => EMPTY_PATH,
  INVALID: () => INVALID,
  NEVER: () => NEVER,
  OK: () => OK,
  ParseStatus: () => ParseStatus,
  Schema: () => ZodType,
  ZodAny: () => ZodAny,
  ZodArray: () => ZodArray,
  ZodBigInt: () => ZodBigInt,
  ZodBoolean: () => ZodBoolean,
  ZodBranded: () => ZodBranded,
  ZodCatch: () => ZodCatch,
  ZodDate: () => ZodDate,
  ZodDefault: () => ZodDefault,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
  ZodEffects: () => ZodEffects,
  ZodEnum: () => ZodEnum,
  ZodError: () => ZodError,
  ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
  ZodFunction: () => ZodFunction,
  ZodIntersection: () => ZodIntersection,
  ZodIssueCode: () => ZodIssueCode,
  ZodLazy: () => ZodLazy,
  ZodLiteral: () => ZodLiteral,
  ZodMap: () => ZodMap,
  ZodNaN: () => ZodNaN,
  ZodNativeEnum: () => ZodNativeEnum,
  ZodNever: () => ZodNever,
  ZodNull: () => ZodNull,
  ZodNullable: () => ZodNullable,
  ZodNumber: () => ZodNumber,
  ZodObject: () => ZodObject,
  ZodOptional: () => ZodOptional,
  ZodParsedType: () => ZodParsedType,
  ZodPipeline: () => ZodPipeline,
  ZodPromise: () => ZodPromise,
  ZodReadonly: () => ZodReadonly,
  ZodRecord: () => ZodRecord,
  ZodSchema: () => ZodType,
  ZodSet: () => ZodSet,
  ZodString: () => ZodString,
  ZodSymbol: () => ZodSymbol,
  ZodTransformer: () => ZodEffects,
  ZodTuple: () => ZodTuple,
  ZodType: () => ZodType,
  ZodUndefined: () => ZodUndefined,
  ZodUnion: () => ZodUnion,
  ZodUnknown: () => ZodUnknown,
  ZodVoid: () => ZodVoid,
  addIssueToContext: () => addIssueToContext,
  any: () => anyType,
  array: () => arrayType,
  bigint: () => bigIntType,
  boolean: () => booleanType,
  coerce: () => coerce,
  custom: () => custom,
  date: () => dateType,
  datetimeRegex: () => datetimeRegex,
  defaultErrorMap: () => en_default,
  discriminatedUnion: () => discriminatedUnionType,
  effect: () => effectsType,
  enum: () => enumType,
  function: () => functionType,
  getErrorMap: () => getErrorMap,
  getParsedType: () => getParsedType,
  instanceof: () => instanceOfType,
  intersection: () => intersectionType,
  isAborted: () => isAborted,
  isAsync: () => isAsync,
  isDirty: () => isDirty,
  isValid: () => isValid,
  late: () => late,
  lazy: () => lazyType,
  literal: () => literalType,
  makeIssue: () => makeIssue,
  map: () => mapType,
  nan: () => nanType,
  nativeEnum: () => nativeEnumType,
  never: () => neverType,
  null: () => nullType,
  nullable: () => nullableType,
  number: () => numberType,
  object: () => objectType,
  objectUtil: () => objectUtil,
  oboolean: () => oboolean,
  onumber: () => onumber,
  optional: () => optionalType,
  ostring: () => ostring,
  pipeline: () => pipelineType,
  preprocess: () => preprocessType,
  promise: () => promiseType,
  quotelessJson: () => quotelessJson,
  record: () => recordType,
  set: () => setType,
  setErrorMap: () => setErrorMap,
  strictObject: () => strictObjectType,
  string: () => stringType,
  symbol: () => symbolType,
  transformer: () => effectsType,
  tuple: () => tupleType,
  undefined: () => undefinedType,
  union: () => unionType,
  unknown: () => unknownType,
  util: () => util2,
  void: () => voidType
});
var init_external = __esm({
  "node_modules/zod/v3/external.js"() {
    init_esbuild_shims();
    init_errors3();
    init_parseUtil();
    init_typeAliases();
    init_util2();
    init_types7();
    init_ZodError();
  }
});

// node_modules/zod/index.js
var init_zod = __esm({
  "node_modules/zod/index.js"() {
    init_esbuild_shims();
    init_external();
    init_external();
  }
});

// packages/core/dist/src/ide/types.js
var FileSchema, IdeContextSchema, IdeContextNotificationSchema, IdeDiffAcceptedNotificationSchema, IdeDiffRejectedNotificationSchema, IdeDiffClosedNotificationSchema, OpenDiffRequestSchema, CloseDiffRequestSchema;
var init_types8 = __esm({
  "packages/core/dist/src/ide/types.js"() {
    "use strict";
    init_esbuild_shims();
    init_zod();
    FileSchema = external_exports.object({
      /**
       * The absolute path to the file.
       */
      path: external_exports.string(),
      /**
       * The unix timestamp of when the file was last focused.
       */
      timestamp: external_exports.number(),
      /**
       * Whether the file is the currently active file. Only one file can be active at a time.
       */
      isActive: external_exports.boolean().optional(),
      /**
       * The text that is currently selected in the active file.
       */
      selectedText: external_exports.string().optional(),
      /**
       * The cursor position in the active file.
       */
      cursor: external_exports.object({
        /**
         * The 1-based line number.
         */
        line: external_exports.number(),
        /**
         * The 1-based character offset.
         */
        character: external_exports.number()
      }).optional()
    });
    IdeContextSchema = external_exports.object({
      workspaceState: external_exports.object({
        /**
         * The list of files that are currently open.
         */
        openFiles: external_exports.array(FileSchema).optional(),
        /**
         * Whether the workspace is trusted.
         */
        isTrusted: external_exports.boolean().optional()
      }).optional()
    });
    IdeContextNotificationSchema = external_exports.object({
      jsonrpc: external_exports.literal("2.0"),
      method: external_exports.literal("ide/contextUpdate"),
      params: IdeContextSchema
    });
    IdeDiffAcceptedNotificationSchema = external_exports.object({
      jsonrpc: external_exports.literal("2.0"),
      method: external_exports.literal("ide/diffAccepted"),
      params: external_exports.object({
        /**
         * The absolute path to the file that was diffed.
         */
        filePath: external_exports.string(),
        /**
         * The full content of the file after the diff was accepted, which includes any manual edits the user may have made.
         */
        content: external_exports.string()
      })
    });
    IdeDiffRejectedNotificationSchema = external_exports.object({
      jsonrpc: external_exports.literal("2.0"),
      method: external_exports.literal("ide/diffRejected"),
      params: external_exports.object({
        /**
         * The absolute path to the file that was diffed.
         */
        filePath: external_exports.string()
      })
    });
    IdeDiffClosedNotificationSchema = external_exports.object({
      jsonrpc: external_exports.literal("2.0"),
      method: external_exports.literal("ide/diffClosed"),
      params: external_exports.object({
        filePath: external_exports.string(),
        content: external_exports.string().optional()
      })
    });
    OpenDiffRequestSchema = external_exports.object({
      /**
       * The absolute path to the file to be diffed.
       */
      filePath: external_exports.string(),
      /**
       * The proposed new content for the file.
       */
      newContent: external_exports.string()
    });
    CloseDiffRequestSchema = external_exports.object({
      /**
       * The absolute path to the file to be diffed.
       */
      filePath: external_exports.string(),
      /**
       * @deprecated
       */
      suppressNotification: external_exports.boolean().optional()
    });
  }
});

// packages/core/dist/src/core/client.js
function isThinkingSupported(model) {
  return model.startsWith("gemini-2.5") || model === DEFAULT_GEMINI_MODEL_AUTO;
}
var MAX_TURNS, GeminiClient;
var init_client2 = __esm({
  "packages/core/dist/src/core/client.js"() {
    "use strict";
    init_esbuild_shims();
    init_config3();
    init_models();
    init_geminiChat();
    init_prompts();
    init_turn();
    init_chatRecordingService();
    init_chatCompressionService();
    init_loopDetectionService();
    init_task();
    init_telemetry();
    init_environmentContext();
    init_errorReporting();
    init_errors();
    init_nextSpeakerChecker();
    init_partUtils();
    init_retry();
    init_ideContext();
    init_types8();
    init_handler();
    __name(isThinkingSupported, "isThinkingSupported");
    MAX_TURNS = 100;
    GeminiClient = class {
      static {
        __name(this, "GeminiClient");
      }
      config;
      chat;
      generateContentConfig = {
        temperature: 0,
        topP: 1
      };
      sessionTurnCount = 0;
      loopDetector;
      lastPromptId;
      lastSentIdeContext;
      forceFullIdeContext = true;
      /**
       * At any point in this conversation, was compression triggered without
       * being forced and did it fail?
       */
      hasFailedCompressionAttempt = false;
      constructor(config) {
        this.config = config;
        this.loopDetector = new LoopDetectionService(config);
        this.lastPromptId = this.config.getSessionId();
      }
      async initialize() {
        this.chat = await this.startChat();
      }
      getContentGeneratorOrFail() {
        if (!this.config.getContentGenerator()) {
          throw new Error("Content generator not initialized");
        }
        return this.config.getContentGenerator();
      }
      async addHistory(content) {
        this.getChat().addHistory(content);
      }
      getChat() {
        if (!this.chat) {
          throw new Error("Chat not initialized");
        }
        return this.chat;
      }
      isInitialized() {
        return this.chat !== void 0;
      }
      getHistory() {
        return this.getChat().getHistory();
      }
      stripThoughtsFromHistory() {
        this.getChat().stripThoughtsFromHistory();
      }
      setHistory(history) {
        this.getChat().setHistory(history);
        this.forceFullIdeContext = true;
      }
      async setTools() {
        const toolRegistry = this.config.getToolRegistry();
        const toolDeclarations = toolRegistry.getFunctionDeclarations();
        const tools = [{ functionDeclarations: toolDeclarations }];
        this.getChat().setTools(tools);
      }
      async resetChat() {
        this.chat = await this.startChat();
      }
      getChatRecordingService() {
        return this.chat?.getChatRecordingService();
      }
      getLoopDetectionService() {
        return this.loopDetector;
      }
      async addDirectoryContext() {
        if (!this.chat) {
          return;
        }
        this.getChat().addHistory({
          role: "user",
          parts: [{ text: await getDirectoryContextString(this.config) }]
        });
      }
      async startChat(extraHistory) {
        this.forceFullIdeContext = true;
        this.hasFailedCompressionAttempt = false;
        const toolRegistry = this.config.getToolRegistry();
        const toolDeclarations = toolRegistry.getFunctionDeclarations();
        const tools = [{ functionDeclarations: toolDeclarations }];
        const history = await getInitialChatHistory(this.config, extraHistory);
        try {
          const userMemory = this.config.getUserMemory();
          const model = this.config.getModel();
          const systemInstruction = getCoreSystemPrompt(userMemory, model);
          const config = { ...this.generateContentConfig };
          if (isThinkingSupported(model)) {
            config.thinkingConfig = {
              includeThoughts: true,
              thinkingBudget: DEFAULT_THINKING_MODE
            };
          }
          return new GeminiChat(this.config, {
            systemInstruction,
            ...config,
            tools
          }, history);
        } catch (error) {
          await reportError2(error, "Error initializing chat session.", history, "startChat");
          throw new Error(`Failed to initialize chat: ${getErrorMessage(error)}`);
        }
      }
      getIdeContextParts(forceFullContext) {
        const currentIdeContext = ideContextStore.get();
        if (!currentIdeContext) {
          return { contextParts: [], newIdeContext: void 0 };
        }
        if (forceFullContext || !this.lastSentIdeContext) {
          const openFiles = currentIdeContext.workspaceState?.openFiles || [];
          const activeFile = openFiles.find((f) => f.isActive);
          const otherOpenFiles = openFiles.filter((f) => !f.isActive).map((f) => f.path);
          const contextData = {};
          if (activeFile) {
            contextData["activeFile"] = {
              path: activeFile.path,
              cursor: activeFile.cursor ? {
                line: activeFile.cursor.line,
                character: activeFile.cursor.character
              } : void 0,
              selectedText: activeFile.selectedText || void 0
            };
          }
          if (otherOpenFiles.length > 0) {
            contextData["otherOpenFiles"] = otherOpenFiles;
          }
          if (Object.keys(contextData).length === 0) {
            return { contextParts: [], newIdeContext: currentIdeContext };
          }
          const jsonString = JSON.stringify(contextData, null, 2);
          const contextParts = [
            "Here is the user's editor context as a JSON object. This is for your information only.",
            "```json",
            jsonString,
            "```"
          ];
          if (this.config.getDebugMode()) {
            console.log(contextParts.join("\n"));
          }
          return {
            contextParts,
            newIdeContext: currentIdeContext
          };
        } else {
          const delta = {};
          const changes = {};
          const lastFiles = new Map((this.lastSentIdeContext.workspaceState?.openFiles || []).map((f) => [f.path, f]));
          const currentFiles = new Map((currentIdeContext.workspaceState?.openFiles || []).map((f) => [
            f.path,
            f
          ]));
          const openedFiles = [];
          for (const [path108] of currentFiles.entries()) {
            if (!lastFiles.has(path108)) {
              openedFiles.push(path108);
            }
          }
          if (openedFiles.length > 0) {
            changes["filesOpened"] = openedFiles;
          }
          const closedFiles = [];
          for (const [path108] of lastFiles.entries()) {
            if (!currentFiles.has(path108)) {
              closedFiles.push(path108);
            }
          }
          if (closedFiles.length > 0) {
            changes["filesClosed"] = closedFiles;
          }
          const lastActiveFile = (this.lastSentIdeContext.workspaceState?.openFiles || []).find((f) => f.isActive);
          const currentActiveFile = (currentIdeContext.workspaceState?.openFiles || []).find((f) => f.isActive);
          if (currentActiveFile) {
            if (!lastActiveFile || lastActiveFile.path !== currentActiveFile.path) {
              changes["activeFileChanged"] = {
                path: currentActiveFile.path,
                cursor: currentActiveFile.cursor ? {
                  line: currentActiveFile.cursor.line,
                  character: currentActiveFile.cursor.character
                } : void 0,
                selectedText: currentActiveFile.selectedText || void 0
              };
            } else {
              const lastCursor = lastActiveFile.cursor;
              const currentCursor = currentActiveFile.cursor;
              if (currentCursor && (!lastCursor || lastCursor.line !== currentCursor.line || lastCursor.character !== currentCursor.character)) {
                changes["cursorMoved"] = {
                  path: currentActiveFile.path,
                  cursor: {
                    line: currentCursor.line,
                    character: currentCursor.character
                  }
                };
              }
              const lastSelectedText = lastActiveFile.selectedText || "";
              const currentSelectedText = currentActiveFile.selectedText || "";
              if (lastSelectedText !== currentSelectedText) {
                changes["selectionChanged"] = {
                  path: currentActiveFile.path,
                  selectedText: currentSelectedText
                };
              }
            }
          } else if (lastActiveFile) {
            changes["activeFileChanged"] = {
              path: null,
              previousPath: lastActiveFile.path
            };
          }
          if (Object.keys(changes).length === 0) {
            return { contextParts: [], newIdeContext: currentIdeContext };
          }
          delta["changes"] = changes;
          const jsonString = JSON.stringify(delta, null, 2);
          const contextParts = [
            "Here is a summary of changes in the user's editor context, in JSON format. This is for your information only.",
            "```json",
            jsonString,
            "```"
          ];
          if (this.config.getDebugMode()) {
            console.log(contextParts.join("\n"));
          }
          return {
            contextParts,
            newIdeContext: currentIdeContext
          };
        }
      }
      async *sendMessageStream(request4, signal, prompt_id, turns = MAX_TURNS) {
        const isNewPrompt = this.lastPromptId !== prompt_id;
        if (isNewPrompt) {
          this.loopDetector.reset(prompt_id);
          this.lastPromptId = prompt_id;
        }
        this.sessionTurnCount++;
        if (this.config.getMaxSessionTurns() > 0 && this.sessionTurnCount > this.config.getMaxSessionTurns()) {
          yield { type: GeminiEventType.MaxSessionTurns };
          return new Turn(this.getChat(), prompt_id);
        }
        const boundedTurns = Math.min(turns, MAX_TURNS);
        if (!boundedTurns) {
          return new Turn(this.getChat(), prompt_id);
        }
        const compressed = await this.tryCompressChat(prompt_id, false);
        if (compressed.compressionStatus === CompressionStatus.COMPRESSED) {
          yield { type: GeminiEventType.ChatCompressed, value: compressed };
        }
        const sessionTokenLimit = this.config.getSessionTokenLimit();
        if (sessionTokenLimit > 0) {
          const currentHistory = this.getChat().getHistory(true);
          const userMemory = this.config.getUserMemory();
          const systemPrompt = getCoreSystemPrompt(userMemory, this.config.getModel());
          const initialHistory = await getInitialChatHistory(this.config);
          const mockRequestContent = [
            {
              role: "system",
              parts: [{ text: systemPrompt }]
            },
            ...initialHistory,
            ...currentHistory
          ];
          const { totalTokens: totalRequestTokens } = await this.config.getContentGenerator().countTokens({
            model: this.config.getModel(),
            contents: mockRequestContent
          });
          if (totalRequestTokens !== void 0 && totalRequestTokens > sessionTokenLimit) {
            yield {
              type: GeminiEventType.SessionTokenLimitExceeded,
              value: {
                currentTokens: totalRequestTokens,
                limit: sessionTokenLimit,
                message: `Session token limit exceeded: ${totalRequestTokens} tokens > ${sessionTokenLimit} limit. Please start a new session or increase the sessionTokenLimit in your settings.json.`
              }
            };
            return new Turn(this.getChat(), prompt_id);
          }
        }
        const history = this.getHistory();
        const lastMessage = history.length > 0 ? history[history.length - 1] : void 0;
        const hasPendingToolCall = !!lastMessage && lastMessage.role === "model" && (lastMessage.parts?.some((p) => "functionCall" in p) || false);
        if (this.config.getIdeMode() && !hasPendingToolCall) {
          const { contextParts, newIdeContext } = this.getIdeContextParts(this.forceFullIdeContext || history.length === 0);
          if (contextParts.length > 0) {
            this.getChat().addHistory({
              role: "user",
              parts: [{ text: contextParts.join("\n") }]
            });
          }
          this.lastSentIdeContext = newIdeContext;
          this.forceFullIdeContext = false;
        }
        const turn = new Turn(this.getChat(), prompt_id);
        if (!this.config.getSkipLoopDetection()) {
          const loopDetected = await this.loopDetector.turnStarted(signal);
          if (loopDetected) {
            yield { type: GeminiEventType.LoopDetected };
            return turn;
          }
        }
        let requestToSent = await flatMapTextParts(request4, async (text) => [text]);
        if (isNewPrompt) {
          const systemReminders = [];
          const hasTaskTool = this.config.getToolRegistry().getTool(TaskTool.Name);
          const subagents = (await this.config.getSubagentManager().listSubagents()).filter((subagent) => subagent.level !== "builtin").map((subagent) => subagent.name);
          if (hasTaskTool && subagents.length > 0) {
            systemReminders.push(getSubagentSystemReminder(subagents));
          }
          if (this.config.getApprovalMode() === ApprovalMode.PLAN) {
            systemReminders.push(getPlanModeSystemReminder());
          }
          requestToSent = [...systemReminders, ...requestToSent];
        }
        const resultStream = turn.run(this.config.getModel(), requestToSent, signal);
        for await (const event of resultStream) {
          if (!this.config.getSkipLoopDetection()) {
            if (this.loopDetector.addAndCheck(event)) {
              yield { type: GeminiEventType.LoopDetected };
              return turn;
            }
          }
          yield event;
          if (event.type === GeminiEventType.Error) {
            return turn;
          }
        }
        if (!turn.pendingToolCalls.length && signal && !signal.aborted) {
          if (this.config.getQuotaErrorOccurred()) {
            return turn;
          }
          if (this.config.getSkipNextSpeakerCheck()) {
            return turn;
          }
          const nextSpeakerCheck = await checkNextSpeaker(this.getChat(), this.config, signal, prompt_id);
          logNextSpeakerCheck(this.config, new NextSpeakerCheckEvent(prompt_id, turn.finishReason?.toString() || "", nextSpeakerCheck?.next_speaker || ""));
          if (nextSpeakerCheck?.next_speaker === "model") {
            const nextRequest = [{ text: "Please continue." }];
            yield* this.sendMessageStream(nextRequest, signal, prompt_id, boundedTurns - 1);
          }
        }
        return turn;
      }
      async generateContent(contents, generationConfig, abortSignal, model) {
        let currentAttemptModel = model;
        const configToUse = {
          ...this.generateContentConfig,
          ...generationConfig
        };
        try {
          const userMemory = this.config.getUserMemory();
          const finalSystemInstruction = generationConfig.systemInstruction ? getCustomSystemPrompt(generationConfig.systemInstruction, userMemory) : getCoreSystemPrompt(userMemory, this.config.getModel());
          const requestConfig = {
            abortSignal,
            ...configToUse,
            systemInstruction: finalSystemInstruction
          };
          const apiCall = /* @__PURE__ */ __name(() => {
            const modelToUse = this.config.isInFallbackMode() ? DEFAULT_GEMINI_FLASH_MODEL : model;
            currentAttemptModel = modelToUse;
            return this.getContentGeneratorOrFail().generateContent({
              model: modelToUse,
              config: requestConfig,
              contents
            }, this.lastPromptId);
          }, "apiCall");
          const onPersistent429Callback = /* @__PURE__ */ __name(async (authType, error) => (
            // Pass the captured model to the centralized handler.
            await handleFallback(this.config, currentAttemptModel, authType, error)
          ), "onPersistent429Callback");
          const result = await retryWithBackoff(apiCall, {
            onPersistent429: onPersistent429Callback,
            authType: this.config.getContentGeneratorConfig()?.authType
          });
          return result;
        } catch (error) {
          if (abortSignal.aborted) {
            throw error;
          }
          await reportError2(error, `Error generating content via API with model ${currentAttemptModel}.`, {
            requestContents: contents,
            requestConfig: configToUse
          }, "generateContent-api");
          throw new Error(`Failed to generate content with model ${currentAttemptModel}: ${getErrorMessage(error)}`);
        }
      }
      async tryCompressChat(prompt_id, force = false) {
        const compressionService = new ChatCompressionService();
        const { newHistory, info } = await compressionService.compress(this.getChat(), prompt_id, force, this.config.getModel(), this.config, this.hasFailedCompressionAttempt);
        if (info.compressionStatus === CompressionStatus.COMPRESSED) {
          if (newHistory) {
            this.chat = await this.startChat(newHistory);
            this.forceFullIdeContext = true;
          }
        } else if (info.compressionStatus === CompressionStatus.COMPRESSION_FAILED_INFLATED_TOKEN_COUNT || info.compressionStatus === CompressionStatus.COMPRESSION_FAILED_EMPTY_SUMMARY) {
          if (!force) {
            this.hasFailedCompressionAttempt = true;
          }
        }
        return info;
      }
    };
  }
});

// packages/core/node_modules/ignore/index.js
var require_ignore = __commonJS({
  "packages/core/node_modules/ignore/index.js"(exports2, module2) {
    init_esbuild_shims();
    function makeArray(subject) {
      return Array.isArray(subject) ? subject : [subject];
    }
    __name(makeArray, "makeArray");
    var UNDEFINED = void 0;
    var EMPTY2 = "";
    var SPACE = " ";
    var ESCAPE = "\\";
    var REGEX_TEST_BLANK_LINE = /^\s+$/;
    var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
    var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
    var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
    var REGEX_SPLITALL_CRLF = /\r?\n/g;
    var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
    var REGEX_TEST_TRAILING_SLASH = /\/$/;
    var SLASH = "/";
    var TMP_KEY_IGNORE = "node-ignore";
    if (typeof Symbol !== "undefined") {
      TMP_KEY_IGNORE = Symbol.for("node-ignore");
    }
    var KEY_IGNORE = TMP_KEY_IGNORE;
    var define2 = /* @__PURE__ */ __name((object, key, value) => {
      Object.defineProperty(object, key, { value });
      return value;
    }, "define");
    var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
    var RETURN_FALSE = /* @__PURE__ */ __name(() => false, "RETURN_FALSE");
    var sanitizeRange = /* @__PURE__ */ __name((range) => range.replace(
      REGEX_REGEXP_RANGE,
      (match2, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match2 : EMPTY2
    ), "sanitizeRange");
    var cleanRangeBackSlash = /* @__PURE__ */ __name((slashes) => {
      const { length } = slashes;
      return slashes.slice(0, length - length % 2);
    }, "cleanRangeBackSlash");
    var REPLACERS = [
      [
        // Remove BOM
        // TODO:
        // Other similar zero-width characters?
        /^\uFEFF/,
        () => EMPTY2
      ],
      // > Trailing spaces are ignored unless they are quoted with backslash ("\")
      [
        // (a\ ) -> (a )
        // (a  ) -> (a)
        // (a ) -> (a)
        // (a \ ) -> (a  )
        /((?:\\\\)*?)(\\?\s+)$/,
        (_, m1, m2) => m1 + (m2.indexOf("\\") === 0 ? SPACE : EMPTY2)
      ],
      // Replace (\ ) with ' '
      // (\ ) -> ' '
      // (\\ ) -> '\\ '
      // (\\\ ) -> '\\ '
      [
        /(\\+?)\s/g,
        (_, m1) => {
          const { length } = m1;
          return m1.slice(0, length - length % 2) + SPACE;
        }
      ],
      // Escape metacharacters
      // which is written down by users but means special for regular expressions.
      // > There are 12 characters with special meanings:
      // > - the backslash \,
      // > - the caret ^,
      // > - the dollar sign $,
      // > - the period or dot .,
      // > - the vertical bar or pipe symbol |,
      // > - the question mark ?,
      // > - the asterisk or star *,
      // > - the plus sign +,
      // > - the opening parenthesis (,
      // > - the closing parenthesis ),
      // > - and the opening square bracket [,
      // > - the opening curly brace {,
      // > These special characters are often called "metacharacters".
      [
        /[\\$.|*+(){^]/g,
        (match2) => `\\${match2}`
      ],
      [
        // > a question mark (?) matches a single character
        /(?!\\)\?/g,
        () => "[^/]"
      ],
      // leading slash
      [
        // > A leading slash matches the beginning of the pathname.
        // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
        // A leading slash matches the beginning of the pathname
        /^\//,
        () => "^"
      ],
      // replace special metacharacter slash after the leading slash
      [
        /\//g,
        () => "\\/"
      ],
      [
        // > A leading "**" followed by a slash means match in all directories.
        // > For example, "**/foo" matches file or directory "foo" anywhere,
        // > the same as pattern "foo".
        // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
        // >   under directory "foo".
        // Notice that the '*'s have been replaced as '\\*'
        /^\^*\\\*\\\*\\\//,
        // '**/foo' <-> 'foo'
        () => "^(?:.*\\/)?"
      ],
      // starting
      [
        // there will be no leading '/'
        //   (which has been replaced by section "leading slash")
        // If starts with '**', adding a '^' to the regular expression also works
        /^(?=[^^])/,
        /* @__PURE__ */ __name(function startingReplacer() {
          return !/\/(?!$)/.test(this) ? "(?:^|\\/)" : "^";
        }, "startingReplacer")
      ],
      // two globstars
      [
        // Use lookahead assertions so that we could match more than one `'/**'`
        /\\\/\\\*\\\*(?=\\\/|$)/g,
        // Zero, one or several directories
        // should not use '*', or it will be replaced by the next replacer
        // Check if it is not the last `'/**'`
        (_, index, str2) => index + 6 < str2.length ? "(?:\\/[^\\/]+)*" : "\\/.+"
      ],
      // normal intermediate wildcards
      [
        // Never replace escaped '*'
        // ignore rule '\*' will match the path '*'
        // 'abc.*/' -> go
        // 'abc.*'  -> skip this rule,
        //    coz trailing single wildcard will be handed by [trailing wildcard]
        /(^|[^\\]+)(\\\*)+(?=.+)/g,
        // '*.js' matches '.js'
        // '*.js' doesn't match 'abc'
        (_, p1, p2) => {
          const unescaped = p2.replace(/\\\*/g, "[^\\/]*");
          return p1 + unescaped;
        }
      ],
      [
        // unescape, revert step 3 except for back slash
        // For example, if a user escape a '\\*',
        // after step 3, the result will be '\\\\\\*'
        /\\\\\\(?=[$.|*+(){^])/g,
        () => ESCAPE
      ],
      [
        // '\\\\' -> '\\'
        /\\\\/g,
        () => ESCAPE
      ],
      [
        // > The range notation, e.g. [a-zA-Z],
        // > can be used to match one of the characters in a range.
        // `\` is escaped by step 3
        /(\\)?\[([^\]/]*?)(\\*)($|\])/g,
        (match2, leadEscape, range, endEscape, close) => leadEscape === ESCAPE ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === "]" ? endEscape.length % 2 === 0 ? `[${sanitizeRange(range)}${endEscape}]` : "[]" : "[]"
      ],
      // ending
      [
        // 'js' will not match 'js.'
        // 'ab' will not match 'abc'
        /(?:[^*])$/,
        // WTF!
        // https://git-scm.com/docs/gitignore
        // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
        // which re-fixes #24, #38
        // > If there is a separator at the end of the pattern then the pattern
        // > will only match directories, otherwise the pattern can match both
        // > files and directories.
        // 'js*' will not match 'a.js'
        // 'js/' will not match 'a.js'
        // 'js' will match 'a.js' and 'a.js/'
        (match2) => /\/$/.test(match2) ? `${match2}$` : `${match2}(?=$|\\/$)`
      ]
    ];
    var REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\\\*$/;
    var MODE_IGNORE = "regex";
    var MODE_CHECK_IGNORE = "checkRegex";
    var UNDERSCORE = "_";
    var TRAILING_WILD_CARD_REPLACERS = {
      [MODE_IGNORE](_, p1) {
        const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
        return `${prefix}(?=$|\\/$)`;
      },
      [MODE_CHECK_IGNORE](_, p1) {
        const prefix = p1 ? `${p1}[^/]*` : "[^/]*";
        return `${prefix}(?=$|\\/$)`;
      }
    };
    var makeRegexPrefix = /* @__PURE__ */ __name((pattern) => REPLACERS.reduce(
      (prev, [matcher, replacer]) => prev.replace(matcher, replacer.bind(pattern)),
      pattern
    ), "makeRegexPrefix");
    var isString2 = /* @__PURE__ */ __name((subject) => typeof subject === "string", "isString");
    var checkPattern = /* @__PURE__ */ __name((pattern) => pattern && isString2(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0, "checkPattern");
    var splitPattern = /* @__PURE__ */ __name((pattern) => pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean), "splitPattern");
    var IgnoreRule = class {
      static {
        __name(this, "IgnoreRule");
      }
      constructor(pattern, mark, body, ignoreCase, negative, prefix) {
        this.pattern = pattern;
        this.mark = mark;
        this.negative = negative;
        define2(this, "body", body);
        define2(this, "ignoreCase", ignoreCase);
        define2(this, "regexPrefix", prefix);
      }
      get regex() {
        const key = UNDERSCORE + MODE_IGNORE;
        if (this[key]) {
          return this[key];
        }
        return this._make(MODE_IGNORE, key);
      }
      get checkRegex() {
        const key = UNDERSCORE + MODE_CHECK_IGNORE;
        if (this[key]) {
          return this[key];
        }
        return this._make(MODE_CHECK_IGNORE, key);
      }
      _make(mode, key) {
        const str2 = this.regexPrefix.replace(
          REGEX_REPLACE_TRAILING_WILDCARD,
          // It does not need to bind pattern
          TRAILING_WILD_CARD_REPLACERS[mode]
        );
        const regex3 = this.ignoreCase ? new RegExp(str2, "i") : new RegExp(str2);
        return define2(this, key, regex3);
      }
    };
    var createRule = /* @__PURE__ */ __name(({
      pattern,
      mark
    }, ignoreCase) => {
      let negative = false;
      let body = pattern;
      if (body.indexOf("!") === 0) {
        negative = true;
        body = body.substr(1);
      }
      body = body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
      const regexPrefix = makeRegexPrefix(body);
      return new IgnoreRule(
        pattern,
        mark,
        body,
        ignoreCase,
        negative,
        regexPrefix
      );
    }, "createRule");
    var RuleManager = class {
      static {
        __name(this, "RuleManager");
      }
      constructor(ignoreCase) {
        this._ignoreCase = ignoreCase;
        this._rules = [];
      }
      _add(pattern) {
        if (pattern && pattern[KEY_IGNORE]) {
          this._rules = this._rules.concat(pattern._rules._rules);
          this._added = true;
          return;
        }
        if (isString2(pattern)) {
          pattern = {
            pattern
          };
        }
        if (checkPattern(pattern.pattern)) {
          const rule = createRule(pattern, this._ignoreCase);
          this._added = true;
          this._rules.push(rule);
        }
      }
      // @param {Array<string> | string | Ignore} pattern
      add(pattern) {
        this._added = false;
        makeArray(
          isString2(pattern) ? splitPattern(pattern) : pattern
        ).forEach(this._add, this);
        return this._added;
      }
      // Test one single path without recursively checking parent directories
      //
      // - checkUnignored `boolean` whether should check if the path is unignored,
      //   setting `checkUnignored` to `false` could reduce additional
      //   path matching.
      // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`
      // @returns {TestResult} true if a file is ignored
      test(path108, checkUnignored, mode) {
        let ignored = false;
        let unignored = false;
        let matchedRule;
        this._rules.forEach((rule) => {
          const { negative } = rule;
          if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
            return;
          }
          const matched = rule[mode].test(path108);
          if (!matched) {
            return;
          }
          ignored = !negative;
          unignored = negative;
          matchedRule = negative ? UNDEFINED : rule;
        });
        const ret = {
          ignored,
          unignored
        };
        if (matchedRule) {
          ret.rule = matchedRule;
        }
        return ret;
      }
    };
    var throwError = /* @__PURE__ */ __name((message, Ctor) => {
      throw new Ctor(message);
    }, "throwError");
    var checkPath = /* @__PURE__ */ __name((path108, originalPath, doThrow) => {
      if (!isString2(path108)) {
        return doThrow(
          `path must be a string, but got \`${originalPath}\``,
          TypeError
        );
      }
      if (!path108) {
        return doThrow(`path must not be empty`, TypeError);
      }
      if (checkPath.isNotRelative(path108)) {
        const r3 = "`path.relative()`d";
        return doThrow(
          `path should be a ${r3} string, but got "${originalPath}"`,
          RangeError
        );
      }
      return true;
    }, "checkPath");
    var isNotRelative = /* @__PURE__ */ __name((path108) => REGEX_TEST_INVALID_PATH.test(path108), "isNotRelative");
    checkPath.isNotRelative = isNotRelative;
    checkPath.convert = (p) => p;
    var Ignore3 = class {
      static {
        __name(this, "Ignore");
      }
      constructor({
        ignorecase = true,
        ignoreCase = ignorecase,
        allowRelativePaths = false
      } = {}) {
        define2(this, KEY_IGNORE, true);
        this._rules = new RuleManager(ignoreCase);
        this._strictPathCheck = !allowRelativePaths;
        this._initCache();
      }
      _initCache() {
        this._ignoreCache = /* @__PURE__ */ Object.create(null);
        this._testCache = /* @__PURE__ */ Object.create(null);
      }
      add(pattern) {
        if (this._rules.add(pattern)) {
          this._initCache();
        }
        return this;
      }
      // legacy
      addPattern(pattern) {
        return this.add(pattern);
      }
      // @returns {TestResult}
      _test(originalPath, cache5, checkUnignored, slices) {
        const path108 = originalPath && checkPath.convert(originalPath);
        checkPath(
          path108,
          originalPath,
          this._strictPathCheck ? throwError : RETURN_FALSE
        );
        return this._t(path108, cache5, checkUnignored, slices);
      }
      checkIgnore(path108) {
        if (!REGEX_TEST_TRAILING_SLASH.test(path108)) {
          return this.test(path108);
        }
        const slices = path108.split(SLASH).filter(Boolean);
        slices.pop();
        if (slices.length) {
          const parent = this._t(
            slices.join(SLASH) + SLASH,
            this._testCache,
            true,
            slices
          );
          if (parent.ignored) {
            return parent;
          }
        }
        return this._rules.test(path108, false, MODE_CHECK_IGNORE);
      }
      _t(path108, cache5, checkUnignored, slices) {
        if (path108 in cache5) {
          return cache5[path108];
        }
        if (!slices) {
          slices = path108.split(SLASH).filter(Boolean);
        }
        slices.pop();
        if (!slices.length) {
          return cache5[path108] = this._rules.test(path108, checkUnignored, MODE_IGNORE);
        }
        const parent = this._t(
          slices.join(SLASH) + SLASH,
          cache5,
          checkUnignored,
          slices
        );
        return cache5[path108] = parent.ignored ? parent : this._rules.test(path108, checkUnignored, MODE_IGNORE);
      }
      ignores(path108) {
        return this._test(path108, this._ignoreCache, false).ignored;
      }
      createFilter() {
        return (path108) => !this.ignores(path108);
      }
      filter(paths) {
        return makeArray(paths).filter(this.createFilter());
      }
      // @returns {TestResult}
      test(path108) {
        return this._test(path108, this._testCache, true);
      }
    };
    var factory = /* @__PURE__ */ __name((options2) => new Ignore3(options2), "factory");
    var isPathValid = /* @__PURE__ */ __name((path108) => checkPath(path108 && checkPath.convert(path108), path108, RETURN_FALSE), "isPathValid");
    var setupWindows = /* @__PURE__ */ __name(() => {
      const makePosix = /* @__PURE__ */ __name((str2) => /^\\\\\?\\/.test(str2) || /["<>|\u0000-\u001F]+/u.test(str2) ? str2 : str2.replace(/\\/g, "/"), "makePosix");
      checkPath.convert = makePosix;
      const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
      checkPath.isNotRelative = (path108) => REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path108) || isNotRelative(path108);
    }, "setupWindows");
    if (
      // Detect `process` so that it can run in browsers.
      typeof process !== "undefined" && process.platform === "win32"
    ) {
      setupWindows();
    }
    module2.exports = factory;
    factory.default = factory;
    module2.exports.isPathValid = isPathValid;
    define2(module2.exports, Symbol.for("setupWindows"), setupWindows);
  }
});

// packages/core/dist/src/utils/gitIgnoreParser.js
import * as fs26 from "node:fs";
import * as path22 from "node:path";
var import_ignore, GitIgnoreParser;
var init_gitIgnoreParser = __esm({
  "packages/core/dist/src/utils/gitIgnoreParser.js"() {
    "use strict";
    init_esbuild_shims();
    import_ignore = __toESM(require_ignore(), 1);
    GitIgnoreParser = class {
      static {
        __name(this, "GitIgnoreParser");
      }
      projectRoot;
      cache = /* @__PURE__ */ new Map();
      globalPatterns;
      constructor(projectRoot) {
        this.projectRoot = path22.resolve(projectRoot);
      }
      loadPatternsForFile(patternsFilePath) {
        let content;
        try {
          content = fs26.readFileSync(patternsFilePath, "utf-8");
        } catch (_error) {
          return [];
        }
        const isExcludeFile = patternsFilePath.endsWith(path22.join(".git", "info", "exclude"));
        const relativeBaseDir = isExcludeFile ? "." : path22.dirname(path22.relative(this.projectRoot, patternsFilePath));
        return content.split("\n").map((p) => p.trim()).filter((p) => p !== "" && !p.startsWith("#")).map((p) => {
          const isNegative = p.startsWith("!");
          if (isNegative) {
            p = p.substring(1);
          }
          const isAnchoredInFile = p.startsWith("/");
          if (isAnchoredInFile) {
            p = p.substring(1);
          }
          if (p === "") {
            return "";
          }
          let newPattern = p;
          if (relativeBaseDir && relativeBaseDir !== ".") {
            if (!isAnchoredInFile && !p.includes("/")) {
              newPattern = path22.join("**", p);
            }
            newPattern = path22.join(relativeBaseDir, newPattern);
            if (!newPattern.startsWith("/")) {
              newPattern = "/" + newPattern;
            }
          }
          if (isAnchoredInFile && !newPattern.startsWith("/")) {
            newPattern = "/" + newPattern;
          }
          if (isNegative) {
            newPattern = "!" + newPattern;
          }
          newPattern = newPattern.replace(/\\/g, "/");
          return newPattern;
        }).filter((p) => p !== "");
      }
      isIgnored(filePath) {
        if (!filePath || typeof filePath !== "string") {
          return false;
        }
        const absoluteFilePath = path22.resolve(this.projectRoot, filePath);
        if (!absoluteFilePath.startsWith(this.projectRoot)) {
          return false;
        }
        try {
          const resolved = path22.resolve(this.projectRoot, filePath);
          const relativePath = path22.relative(this.projectRoot, resolved);
          if (relativePath === "" || relativePath.startsWith("..")) {
            return false;
          }
          const normalizedPath = relativePath.replace(/\\/g, "/");
          if (normalizedPath.startsWith("/") || normalizedPath === "") {
            return false;
          }
          const ig = (0, import_ignore.default)();
          ig.add(".git");
          if (this.globalPatterns === void 0) {
            const excludeFile = path22.join(this.projectRoot, ".git", "info", "exclude");
            this.globalPatterns = fs26.existsSync(excludeFile) ? this.loadPatternsForFile(excludeFile) : [];
          }
          ig.add(this.globalPatterns);
          const pathParts = relativePath.split(path22.sep);
          const dirsToVisit = [this.projectRoot];
          let currentAbsDir = this.projectRoot;
          for (let i = 0; i < pathParts.length - 1; i++) {
            currentAbsDir = path22.join(currentAbsDir, pathParts[i]);
            dirsToVisit.push(currentAbsDir);
          }
          for (const dir of dirsToVisit) {
            const relativeDir = path22.relative(this.projectRoot, dir);
            if (relativeDir) {
              const normalizedRelativeDir = relativeDir.replace(/\\/g, "/");
              if (ig.ignores(normalizedRelativeDir)) {
                break;
              }
            }
            if (this.cache.has(dir)) {
              const patterns = this.cache.get(dir);
              if (patterns) {
                ig.add(patterns);
              }
            } else {
              const gitignorePath = path22.join(dir, ".gitignore");
              if (fs26.existsSync(gitignorePath)) {
                const patterns = this.loadPatternsForFile(gitignorePath);
                this.cache.set(dir, patterns);
                ig.add(patterns);
              } else {
                this.cache.set(dir, []);
              }
            }
          }
          return ig.ignores(normalizedPath);
        } catch (_error) {
          return false;
        }
      }
    };
  }
});

// packages/core/dist/src/utils/qwenIgnoreParser.js
import * as fs27 from "node:fs";
import * as path23 from "node:path";
var import_ignore2, QwenIgnoreParser;
var init_qwenIgnoreParser = __esm({
  "packages/core/dist/src/utils/qwenIgnoreParser.js"() {
    "use strict";
    init_esbuild_shims();
    import_ignore2 = __toESM(require_ignore(), 1);
    QwenIgnoreParser = class {
      static {
        __name(this, "QwenIgnoreParser");
      }
      projectRoot;
      patterns = [];
      ig = (0, import_ignore2.default)();
      constructor(projectRoot) {
        this.projectRoot = path23.resolve(projectRoot);
        this.loadPatterns();
      }
      loadPatterns() {
        const patternsFilePath = path23.join(this.projectRoot, ".qwenignore");
        let content;
        try {
          content = fs27.readFileSync(patternsFilePath, "utf-8");
        } catch (_error) {
          return;
        }
        this.patterns = (content ?? "").split("\n").map((p) => p.trim()).filter((p) => p !== "" && !p.startsWith("#"));
        this.ig.add(this.patterns);
      }
      isIgnored(filePath) {
        if (this.patterns.length === 0) {
          return false;
        }
        if (!filePath || typeof filePath !== "string") {
          return false;
        }
        if (filePath.startsWith("\\") || filePath === "/" || filePath.includes("\0")) {
          return false;
        }
        const resolved = path23.resolve(this.projectRoot, filePath);
        const relativePath = path23.relative(this.projectRoot, resolved);
        if (relativePath === "" || relativePath.startsWith("..")) {
          return false;
        }
        const normalizedPath = relativePath.replace(/\\/g, "/");
        if (normalizedPath.startsWith("/") || normalizedPath === "") {
          return false;
        }
        return this.ig.ignores(normalizedPath);
      }
      getPatterns() {
        return this.patterns;
      }
    };
  }
});

// packages/core/dist/src/services/fileDiscoveryService.js
import * as path24 from "node:path";
var FileDiscoveryService;
var init_fileDiscoveryService = __esm({
  "packages/core/dist/src/services/fileDiscoveryService.js"() {
    "use strict";
    init_esbuild_shims();
    init_gitIgnoreParser();
    init_qwenIgnoreParser();
    init_gitUtils();
    FileDiscoveryService = class {
      static {
        __name(this, "FileDiscoveryService");
      }
      gitIgnoreFilter = null;
      qwenIgnoreFilter = null;
      projectRoot;
      constructor(projectRoot) {
        this.projectRoot = path24.resolve(projectRoot);
        if (isGitRepository(this.projectRoot)) {
          this.gitIgnoreFilter = new GitIgnoreParser(this.projectRoot);
        }
        this.qwenIgnoreFilter = new QwenIgnoreParser(this.projectRoot);
      }
      /**
       * Filters a list of file paths based on git ignore rules
       */
      filterFiles(filePaths, options2 = {
        respectGitIgnore: true,
        respectQwenIgnore: true
      }) {
        return filePaths.filter((filePath) => {
          if (options2.respectGitIgnore && this.shouldGitIgnoreFile(filePath)) {
            return false;
          }
          if (options2.respectQwenIgnore && this.shouldQwenIgnoreFile(filePath)) {
            return false;
          }
          return true;
        });
      }
      /**
       * Filters a list of file paths based on git ignore rules and returns a report
       * with counts of ignored files.
       */
      filterFilesWithReport(filePaths, opts = {
        respectGitIgnore: true,
        respectQwenIgnore: true
      }) {
        const filteredPaths = [];
        let gitIgnoredCount = 0;
        let qwenIgnoredCount = 0;
        for (const filePath of filePaths) {
          if (opts.respectGitIgnore && this.shouldGitIgnoreFile(filePath)) {
            gitIgnoredCount++;
            continue;
          }
          if (opts.respectQwenIgnore && this.shouldQwenIgnoreFile(filePath)) {
            qwenIgnoredCount++;
            continue;
          }
          filteredPaths.push(filePath);
        }
        return {
          filteredPaths,
          gitIgnoredCount,
          qwenIgnoredCount
        };
      }
      /**
       * Checks if a single file should be git-ignored
       */
      shouldGitIgnoreFile(filePath) {
        if (this.gitIgnoreFilter) {
          return this.gitIgnoreFilter.isIgnored(filePath);
        }
        return false;
      }
      /**
       * Checks if a single file should be qwen-ignored
       */
      shouldQwenIgnoreFile(filePath) {
        if (this.qwenIgnoreFilter) {
          return this.qwenIgnoreFilter.isIgnored(filePath);
        }
        return false;
      }
      /**
       * Unified method to check if a file should be ignored based on filtering options
       */
      shouldIgnoreFile(filePath, options2 = {}) {
        const { respectGitIgnore = true, respectQwenIgnore = true } = options2;
        if (respectGitIgnore && this.shouldGitIgnoreFile(filePath)) {
          return true;
        }
        if (respectQwenIgnore && this.shouldQwenIgnoreFile(filePath)) {
          return true;
        }
        return false;
      }
      /**
       * Returns loaded patterns from .qwenignore
       */
      getQwenIgnorePatterns() {
        return this.qwenIgnoreFilter?.getPatterns() ?? [];
      }
    };
  }
});

// node_modules/balanced-match/index.js
var require_balanced_match = __commonJS({
  "node_modules/balanced-match/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = balanced;
    function balanced(a, b, str2) {
      if (a instanceof RegExp) a = maybeMatch(a, str2);
      if (b instanceof RegExp) b = maybeMatch(b, str2);
      var r3 = range(a, b, str2);
      return r3 && {
        start: r3[0],
        end: r3[1],
        pre: str2.slice(0, r3[0]),
        body: str2.slice(r3[0] + a.length, r3[1]),
        post: str2.slice(r3[1] + b.length)
      };
    }
    __name(balanced, "balanced");
    function maybeMatch(reg, str2) {
      var m = str2.match(reg);
      return m ? m[0] : null;
    }
    __name(maybeMatch, "maybeMatch");
    balanced.range = range;
    function range(a, b, str2) {
      var begs, beg, left3, right3, result;
      var ai = str2.indexOf(a);
      var bi = str2.indexOf(b, ai + 1);
      var i = ai;
      if (ai >= 0 && bi > 0) {
        if (a === b) {
          return [ai, bi];
        }
        begs = [];
        left3 = str2.length;
        while (i >= 0 && !result) {
          if (i == ai) {
            begs.push(i);
            ai = str2.indexOf(a, i + 1);
          } else if (begs.length == 1) {
            result = [begs.pop(), bi];
          } else {
            beg = begs.pop();
            if (beg < left3) {
              left3 = beg;
              right3 = bi;
            }
            bi = str2.indexOf(b, i + 1);
          }
          i = ai < bi && ai >= 0 ? ai : bi;
        }
        if (begs.length) {
          result = [left3, right3];
        }
      }
      return result;
    }
    __name(range, "range");
  }
});

// node_modules/glob/node_modules/brace-expansion/index.js
var require_brace_expansion = __commonJS({
  "node_modules/glob/node_modules/brace-expansion/index.js"(exports2, module2) {
    init_esbuild_shims();
    var balanced = require_balanced_match();
    module2.exports = expandTop;
    var escSlash = "\0SLASH" + Math.random() + "\0";
    var escOpen = "\0OPEN" + Math.random() + "\0";
    var escClose = "\0CLOSE" + Math.random() + "\0";
    var escComma = "\0COMMA" + Math.random() + "\0";
    var escPeriod = "\0PERIOD" + Math.random() + "\0";
    function numeric(str2) {
      return parseInt(str2, 10) == str2 ? parseInt(str2, 10) : str2.charCodeAt(0);
    }
    __name(numeric, "numeric");
    function escapeBraces(str2) {
      return str2.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
    }
    __name(escapeBraces, "escapeBraces");
    function unescapeBraces(str2) {
      return str2.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
    }
    __name(unescapeBraces, "unescapeBraces");
    function parseCommaParts(str2) {
      if (!str2)
        return [""];
      var parts = [];
      var m = balanced("{", "}", str2);
      if (!m)
        return str2.split(",");
      var pre = m.pre;
      var body = m.body;
      var post = m.post;
      var p = pre.split(",");
      p[p.length - 1] += "{" + body + "}";
      var postParts = parseCommaParts(post);
      if (post.length) {
        p[p.length - 1] += postParts.shift();
        p.push.apply(p, postParts);
      }
      parts.push.apply(parts, p);
      return parts;
    }
    __name(parseCommaParts, "parseCommaParts");
    function expandTop(str2) {
      if (!str2)
        return [];
      if (str2.substr(0, 2) === "{}") {
        str2 = "\\{\\}" + str2.substr(2);
      }
      return expand2(escapeBraces(str2), true).map(unescapeBraces);
    }
    __name(expandTop, "expandTop");
    function embrace(str2) {
      return "{" + str2 + "}";
    }
    __name(embrace, "embrace");
    function isPadded(el) {
      return /^-?0\d/.test(el);
    }
    __name(isPadded, "isPadded");
    function lte(i, y) {
      return i <= y;
    }
    __name(lte, "lte");
    function gte(i, y) {
      return i >= y;
    }
    __name(gte, "gte");
    function expand2(str2, isTop) {
      var expansions = [];
      var m = balanced("{", "}", str2);
      if (!m) return [str2];
      var pre = m.pre;
      var post = m.post.length ? expand2(m.post, false) : [""];
      if (/\$$/.test(m.pre)) {
        for (var k = 0; k < post.length; k++) {
          var expansion = pre + "{" + m.body + "}" + post[k];
          expansions.push(expansion);
        }
      } else {
        var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
        var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
        var isSequence = isNumericSequence || isAlphaSequence;
        var isOptions = m.body.indexOf(",") >= 0;
        if (!isSequence && !isOptions) {
          if (m.post.match(/,(?!,).*\}/)) {
            str2 = m.pre + "{" + m.body + escClose + m.post;
            return expand2(str2);
          }
          return [str2];
        }
        var n2;
        if (isSequence) {
          n2 = m.body.split(/\.\./);
        } else {
          n2 = parseCommaParts(m.body);
          if (n2.length === 1) {
            n2 = expand2(n2[0], false).map(embrace);
            if (n2.length === 1) {
              return post.map(function(p) {
                return m.pre + n2[0] + p;
              });
            }
          }
        }
        var N;
        if (isSequence) {
          var x = numeric(n2[0]);
          var y = numeric(n2[1]);
          var width = Math.max(n2[0].length, n2[1].length);
          var incr = n2.length == 3 ? Math.abs(numeric(n2[2])) : 1;
          var test = lte;
          var reverse = y < x;
          if (reverse) {
            incr *= -1;
            test = gte;
          }
          var pad = n2.some(isPadded);
          N = [];
          for (var i = x; test(i, y); i += incr) {
            var c3;
            if (isAlphaSequence) {
              c3 = String.fromCharCode(i);
              if (c3 === "\\")
                c3 = "";
            } else {
              c3 = String(i);
              if (pad) {
                var need = width - c3.length;
                if (need > 0) {
                  var z = new Array(need + 1).join("0");
                  if (i < 0)
                    c3 = "-" + z + c3.slice(1);
                  else
                    c3 = z + c3;
                }
              }
            }
            N.push(c3);
          }
        } else {
          N = [];
          for (var j = 0; j < n2.length; j++) {
            N.push.apply(N, expand2(n2[j], false));
          }
        }
        for (var j = 0; j < N.length; j++) {
          for (var k = 0; k < post.length; k++) {
            var expansion = pre + N[j] + post[k];
            if (!isTop || isSequence || expansion)
              expansions.push(expansion);
          }
        }
      }
      return expansions;
    }
    __name(expand2, "expand");
  }
});

// node_modules/glob/node_modules/minimatch/dist/esm/assert-valid-pattern.js
var MAX_PATTERN_LENGTH, assertValidPattern;
var init_assert_valid_pattern = __esm({
  "node_modules/glob/node_modules/minimatch/dist/esm/assert-valid-pattern.js"() {
    init_esbuild_shims();
    MAX_PATTERN_LENGTH = 1024 * 64;
    assertValidPattern = /* @__PURE__ */ __name((pattern) => {
      if (typeof pattern !== "string") {
        throw new TypeError("invalid pattern");
      }
      if (pattern.length > MAX_PATTERN_LENGTH) {
        throw new TypeError("pattern is too long");
      }
    }, "assertValidPattern");
  }
});

// node_modules/glob/node_modules/minimatch/dist/esm/brace-expressions.js
var posixClasses, braceEscape, regexpEscape, rangesToString, parseClass;
var init_brace_expressions = __esm({
  "node_modules/glob/node_modules/minimatch/dist/esm/brace-expressions.js"() {
    init_esbuild_shims();
    posixClasses = {
      "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
      "[:alpha:]": ["\\p{L}\\p{Nl}", true],
      "[:ascii:]": ["\\x00-\\x7f", false],
      "[:blank:]": ["\\p{Zs}\\t", true],
      "[:cntrl:]": ["\\p{Cc}", true],
      "[:digit:]": ["\\p{Nd}", true],
      "[:graph:]": ["\\p{Z}\\p{C}", true, true],
      "[:lower:]": ["\\p{Ll}", true],
      "[:print:]": ["\\p{C}", true],
      "[:punct:]": ["\\p{P}", true],
      "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true],
      "[:upper:]": ["\\p{Lu}", true],
      "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true],
      "[:xdigit:]": ["A-Fa-f0-9", false]
    };
    braceEscape = /* @__PURE__ */ __name((s2) => s2.replace(/[[\]\\-]/g, "\\$&"), "braceEscape");
    regexpEscape = /* @__PURE__ */ __name((s2) => s2.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "regexpEscape");
    rangesToString = /* @__PURE__ */ __name((ranges2) => ranges2.join(""), "rangesToString");
    parseClass = /* @__PURE__ */ __name((glob2, position) => {
      const pos2 = position;
      if (glob2.charAt(pos2) !== "[") {
        throw new Error("not in a brace expression");
      }
      const ranges2 = [];
      const negs = [];
      let i = pos2 + 1;
      let sawStart = false;
      let uflag = false;
      let escaping = false;
      let negate = false;
      let endPos = pos2;
      let rangeStart = "";
      WHILE: while (i < glob2.length) {
        const c3 = glob2.charAt(i);
        if ((c3 === "!" || c3 === "^") && i === pos2 + 1) {
          negate = true;
          i++;
          continue;
        }
        if (c3 === "]" && sawStart && !escaping) {
          endPos = i + 1;
          break;
        }
        sawStart = true;
        if (c3 === "\\") {
          if (!escaping) {
            escaping = true;
            i++;
            continue;
          }
        }
        if (c3 === "[" && !escaping) {
          for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
            if (glob2.startsWith(cls, i)) {
              if (rangeStart) {
                return ["$.", false, glob2.length - pos2, true];
              }
              i += cls.length;
              if (neg)
                negs.push(unip);
              else
                ranges2.push(unip);
              uflag = uflag || u;
              continue WHILE;
            }
          }
        }
        escaping = false;
        if (rangeStart) {
          if (c3 > rangeStart) {
            ranges2.push(braceEscape(rangeStart) + "-" + braceEscape(c3));
          } else if (c3 === rangeStart) {
            ranges2.push(braceEscape(c3));
          }
          rangeStart = "";
          i++;
          continue;
        }
        if (glob2.startsWith("-]", i + 1)) {
          ranges2.push(braceEscape(c3 + "-"));
          i += 2;
          continue;
        }
        if (glob2.startsWith("-", i + 1)) {
          rangeStart = c3;
          i += 2;
          continue;
        }
        ranges2.push(braceEscape(c3));
        i++;
      }
      if (endPos < i) {
        return ["", false, 0, false];
      }
      if (!ranges2.length && !negs.length) {
        return ["$.", false, glob2.length - pos2, true];
      }
      if (negs.length === 0 && ranges2.length === 1 && /^\\?.$/.test(ranges2[0]) && !negate) {
        const r3 = ranges2[0].length === 2 ? ranges2[0].slice(-1) : ranges2[0];
        return [regexpEscape(r3), false, endPos - pos2, false];
      }
      const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges2) + "]";
      const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";
      const comb = ranges2.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges2.length ? sranges : snegs;
      return [comb, uflag, endPos - pos2, true];
    }, "parseClass");
  }
});

// node_modules/glob/node_modules/minimatch/dist/esm/unescape.js
var unescape2;
var init_unescape = __esm({
  "node_modules/glob/node_modules/minimatch/dist/esm/unescape.js"() {
    init_esbuild_shims();
    unescape2 = /* @__PURE__ */ __name((s2, { windowsPathsNoEscape = false } = {}) => {
      return windowsPathsNoEscape ? s2.replace(/\[([^\/\\])\]/g, "$1") : s2.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
    }, "unescape");
  }
});

// node_modules/glob/node_modules/minimatch/dist/esm/ast.js
var types, isExtglobType, startNoTraversal, startNoDot, addPatternStart, justDots, reSpecials, regExpEscape, qmark, star, starNoEmpty, AST;
var init_ast = __esm({
  "node_modules/glob/node_modules/minimatch/dist/esm/ast.js"() {
    init_esbuild_shims();
    init_brace_expressions();
    init_unescape();
    types = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]);
    isExtglobType = /* @__PURE__ */ __name((c3) => types.has(c3), "isExtglobType");
    startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))";
    startNoDot = "(?!\\.)";
    addPatternStart = /* @__PURE__ */ new Set(["[", "."]);
    justDots = /* @__PURE__ */ new Set(["..", "."]);
    reSpecials = new Set("().*{}+?[]^$\\!");
    regExpEscape = /* @__PURE__ */ __name((s2) => s2.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "regExpEscape");
    qmark = "[^/]";
    star = qmark + "*?";
    starNoEmpty = qmark + "+?";
    AST = class _AST {
      static {
        __name(this, "AST");
      }
      type;
      #root;
      #hasMagic;
      #uflag = false;
      #parts = [];
      #parent;
      #parentIndex;
      #negs;
      #filledNegs = false;
      #options;
      #toString;
      // set to true if it's an extglob with no children
      // (which really means one child of '')
      #emptyExt = false;
      constructor(type, parent, options2 = {}) {
        this.type = type;
        if (type)
          this.#hasMagic = true;
        this.#parent = parent;
        this.#root = this.#parent ? this.#parent.#root : this;
        this.#options = this.#root === this ? options2 : this.#root.#options;
        this.#negs = this.#root === this ? [] : this.#root.#negs;
        if (type === "!" && !this.#root.#filledNegs)
          this.#negs.push(this);
        this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
      }
      get hasMagic() {
        if (this.#hasMagic !== void 0)
          return this.#hasMagic;
        for (const p of this.#parts) {
          if (typeof p === "string")
            continue;
          if (p.type || p.hasMagic)
            return this.#hasMagic = true;
        }
        return this.#hasMagic;
      }
      // reconstructs the pattern
      toString() {
        if (this.#toString !== void 0)
          return this.#toString;
        if (!this.type) {
          return this.#toString = this.#parts.map((p) => String(p)).join("");
        } else {
          return this.#toString = this.type + "(" + this.#parts.map((p) => String(p)).join("|") + ")";
        }
      }
      #fillNegs() {
        if (this !== this.#root)
          throw new Error("should only call on root");
        if (this.#filledNegs)
          return this;
        this.toString();
        this.#filledNegs = true;
        let n2;
        while (n2 = this.#negs.pop()) {
          if (n2.type !== "!")
            continue;
          let p = n2;
          let pp = p.#parent;
          while (pp) {
            for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
              for (const part of n2.#parts) {
                if (typeof part === "string") {
                  throw new Error("string part in extglob AST??");
                }
                part.copyIn(pp.#parts[i]);
              }
            }
            p = pp;
            pp = p.#parent;
          }
        }
        return this;
      }
      push(...parts) {
        for (const p of parts) {
          if (p === "")
            continue;
          if (typeof p !== "string" && !(p instanceof _AST && p.#parent === this)) {
            throw new Error("invalid part: " + p);
          }
          this.#parts.push(p);
        }
      }
      toJSON() {
        const ret = this.type === null ? this.#parts.slice().map((p) => typeof p === "string" ? p : p.toJSON()) : [this.type, ...this.#parts.map((p) => p.toJSON())];
        if (this.isStart() && !this.type)
          ret.unshift([]);
        if (this.isEnd() && (this === this.#root || this.#root.#filledNegs && this.#parent?.type === "!")) {
          ret.push({});
        }
        return ret;
      }
      isStart() {
        if (this.#root === this)
          return true;
        if (!this.#parent?.isStart())
          return false;
        if (this.#parentIndex === 0)
          return true;
        const p = this.#parent;
        for (let i = 0; i < this.#parentIndex; i++) {
          const pp = p.#parts[i];
          if (!(pp instanceof _AST && pp.type === "!")) {
            return false;
          }
        }
        return true;
      }
      isEnd() {
        if (this.#root === this)
          return true;
        if (this.#parent?.type === "!")
          return true;
        if (!this.#parent?.isEnd())
          return false;
        if (!this.type)
          return this.#parent?.isEnd();
        const pl = this.#parent ? this.#parent.#parts.length : 0;
        return this.#parentIndex === pl - 1;
      }
      copyIn(part) {
        if (typeof part === "string")
          this.push(part);
        else
          this.push(part.clone(this));
      }
      clone(parent) {
        const c3 = new _AST(this.type, parent);
        for (const p of this.#parts) {
          c3.copyIn(p);
        }
        return c3;
      }
      static #parseAST(str2, ast, pos2, opt) {
        let escaping = false;
        let inBrace = false;
        let braceStart = -1;
        let braceNeg = false;
        if (ast.type === null) {
          let i2 = pos2;
          let acc2 = "";
          while (i2 < str2.length) {
            const c3 = str2.charAt(i2++);
            if (escaping || c3 === "\\") {
              escaping = !escaping;
              acc2 += c3;
              continue;
            }
            if (inBrace) {
              if (i2 === braceStart + 1) {
                if (c3 === "^" || c3 === "!") {
                  braceNeg = true;
                }
              } else if (c3 === "]" && !(i2 === braceStart + 2 && braceNeg)) {
                inBrace = false;
              }
              acc2 += c3;
              continue;
            } else if (c3 === "[") {
              inBrace = true;
              braceStart = i2;
              braceNeg = false;
              acc2 += c3;
              continue;
            }
            if (!opt.noext && isExtglobType(c3) && str2.charAt(i2) === "(") {
              ast.push(acc2);
              acc2 = "";
              const ext2 = new _AST(c3, ast);
              i2 = _AST.#parseAST(str2, ext2, i2, opt);
              ast.push(ext2);
              continue;
            }
            acc2 += c3;
          }
          ast.push(acc2);
          return i2;
        }
        let i = pos2 + 1;
        let part = new _AST(null, ast);
        const parts = [];
        let acc = "";
        while (i < str2.length) {
          const c3 = str2.charAt(i++);
          if (escaping || c3 === "\\") {
            escaping = !escaping;
            acc += c3;
            continue;
          }
          if (inBrace) {
            if (i === braceStart + 1) {
              if (c3 === "^" || c3 === "!") {
                braceNeg = true;
              }
            } else if (c3 === "]" && !(i === braceStart + 2 && braceNeg)) {
              inBrace = false;
            }
            acc += c3;
            continue;
          } else if (c3 === "[") {
            inBrace = true;
            braceStart = i;
            braceNeg = false;
            acc += c3;
            continue;
          }
          if (isExtglobType(c3) && str2.charAt(i) === "(") {
            part.push(acc);
            acc = "";
            const ext2 = new _AST(c3, part);
            part.push(ext2);
            i = _AST.#parseAST(str2, ext2, i, opt);
            continue;
          }
          if (c3 === "|") {
            part.push(acc);
            acc = "";
            parts.push(part);
            part = new _AST(null, ast);
            continue;
          }
          if (c3 === ")") {
            if (acc === "" && ast.#parts.length === 0) {
              ast.#emptyExt = true;
            }
            part.push(acc);
            acc = "";
            ast.push(...parts, part);
            return i;
          }
          acc += c3;
        }
        ast.type = null;
        ast.#hasMagic = void 0;
        ast.#parts = [str2.substring(pos2 - 1)];
        return i;
      }
      static fromGlob(pattern, options2 = {}) {
        const ast = new _AST(null, void 0, options2);
        _AST.#parseAST(pattern, ast, 0, options2);
        return ast;
      }
      // returns the regular expression if there's magic, or the unescaped
      // string if not.
      toMMPattern() {
        if (this !== this.#root)
          return this.#root.toMMPattern();
        const glob2 = this.toString();
        const [re2, body, hasMagic2, uflag] = this.toRegExpSource();
        const anyMagic = hasMagic2 || this.#hasMagic || this.#options.nocase && !this.#options.nocaseMagicOnly && glob2.toUpperCase() !== glob2.toLowerCase();
        if (!anyMagic) {
          return body;
        }
        const flags = (this.#options.nocase ? "i" : "") + (uflag ? "u" : "");
        return Object.assign(new RegExp(`^${re2}$`, flags), {
          _src: re2,
          _glob: glob2
        });
      }
      get options() {
        return this.#options;
      }
      // returns the string match, the regexp source, whether there's magic
      // in the regexp (so a regular expression is required) and whether or
      // not the uflag is needed for the regular expression (for posix classes)
      // TODO: instead of injecting the start/end at this point, just return
      // the BODY of the regexp, along with the start/end portions suitable
      // for binding the start/end in either a joined full-path makeRe context
      // (where we bind to (^|/), or a standalone matchPart context (where
      // we bind to ^, and not /).  Otherwise slashes get duped!
      //
      // In part-matching mode, the start is:
      // - if not isStart: nothing
      // - if traversal possible, but not allowed: ^(?!\.\.?$)
      // - if dots allowed or not possible: ^
      // - if dots possible and not allowed: ^(?!\.)
      // end is:
      // - if not isEnd(): nothing
      // - else: $
      //
      // In full-path matching mode, we put the slash at the START of the
      // pattern, so start is:
      // - if first pattern: same as part-matching mode
      // - if not isStart(): nothing
      // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
      // - if dots allowed or not possible: /
      // - if dots possible and not allowed: /(?!\.)
      // end is:
      // - if last pattern, same as part-matching mode
      // - else nothing
      //
      // Always put the (?:$|/) on negated tails, though, because that has to be
      // there to bind the end of the negated pattern portion, and it's easier to
      // just stick it in now rather than try to inject it later in the middle of
      // the pattern.
      //
      // We can just always return the same end, and leave it up to the caller
      // to know whether it's going to be used joined or in parts.
      // And, if the start is adjusted slightly, can do the same there:
      // - if not isStart: nothing
      // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
      // - if dots allowed or not possible: (?:/|^)
      // - if dots possible and not allowed: (?:/|^)(?!\.)
      //
      // But it's better to have a simpler binding without a conditional, for
      // performance, so probably better to return both start options.
      //
      // Then the caller just ignores the end if it's not the first pattern,
      // and the start always gets applied.
      //
      // But that's always going to be $ if it's the ending pattern, or nothing,
      // so the caller can just attach $ at the end of the pattern when building.
      //
      // So the todo is:
      // - better detect what kind of start is needed
      // - return both flavors of starting pattern
      // - attach $ at the end of the pattern when creating the actual RegExp
      //
      // Ah, but wait, no, that all only applies to the root when the first pattern
      // is not an extglob. If the first pattern IS an extglob, then we need all
      // that dot prevention biz to live in the extglob portions, because eg
      // +(*|.x*) can match .xy but not .yx.
      //
      // So, return the two flavors if it's #root and the first child is not an
      // AST, otherwise leave it to the child AST to handle it, and there,
      // use the (?:^|/) style of start binding.
      //
      // Even simplified further:
      // - Since the start for a join is eg /(?!\.) and the start for a part
      // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
      // or start or whatever) and prepend ^ or / at the Regexp construction.
      toRegExpSource(allowDot) {
        const dot = allowDot ?? !!this.#options.dot;
        if (this.#root === this)
          this.#fillNegs();
        if (!this.type) {
          const noEmpty = this.isStart() && this.isEnd();
          const src = this.#parts.map((p) => {
            const [re2, _, hasMagic2, uflag] = typeof p === "string" ? _AST.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource(allowDot);
            this.#hasMagic = this.#hasMagic || hasMagic2;
            this.#uflag = this.#uflag || uflag;
            return re2;
          }).join("");
          let start2 = "";
          if (this.isStart()) {
            if (typeof this.#parts[0] === "string") {
              const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
              if (!dotTravAllowed) {
                const aps = addPatternStart;
                const needNoTrav = (
                  // dots are allowed, and the pattern starts with [ or .
                  dot && aps.has(src.charAt(0)) || // the pattern starts with \., and then [ or .
                  src.startsWith("\\.") && aps.has(src.charAt(2)) || // the pattern starts with \.\., and then [ or .
                  src.startsWith("\\.\\.") && aps.has(src.charAt(4))
                );
                const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
                start2 = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : "";
              }
            }
          }
          let end = "";
          if (this.isEnd() && this.#root.#filledNegs && this.#parent?.type === "!") {
            end = "(?:$|\\/)";
          }
          const final2 = start2 + src + end;
          return [
            final2,
            unescape2(src),
            this.#hasMagic = !!this.#hasMagic,
            this.#uflag
          ];
        }
        const repeated = this.type === "*" || this.type === "+";
        const start = this.type === "!" ? "(?:(?!(?:" : "(?:";
        let body = this.#partsToRegExp(dot);
        if (this.isStart() && this.isEnd() && !body && this.type !== "!") {
          const s2 = this.toString();
          this.#parts = [s2];
          this.type = null;
          this.#hasMagic = void 0;
          return [s2, unescape2(this.toString()), false, false];
        }
        let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? "" : this.#partsToRegExp(true);
        if (bodyDotAllowed === body) {
          bodyDotAllowed = "";
        }
        if (bodyDotAllowed) {
          body = `(?:${body})(?:${bodyDotAllowed})*?`;
        }
        let final = "";
        if (this.type === "!" && this.#emptyExt) {
          final = (this.isStart() && !dot ? startNoDot : "") + starNoEmpty;
        } else {
          const close = this.type === "!" ? (
            // !() must match something,but !(x) can match ''
            "))" + (this.isStart() && !dot && !allowDot ? startNoDot : "") + star + ")"
          ) : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && bodyDotAllowed ? ")" : this.type === "*" && bodyDotAllowed ? `)?` : `)${this.type}`;
          final = start + body + close;
        }
        return [
          final,
          unescape2(body),
          this.#hasMagic = !!this.#hasMagic,
          this.#uflag
        ];
      }
      #partsToRegExp(dot) {
        return this.#parts.map((p) => {
          if (typeof p === "string") {
            throw new Error("string type in extglob ast??");
          }
          const [re2, _, _hasMagic, uflag] = p.toRegExpSource(dot);
          this.#uflag = this.#uflag || uflag;
          return re2;
        }).filter((p) => !(this.isStart() && this.isEnd()) || !!p).join("|");
      }
      static #parseGlob(glob2, hasMagic2, noEmpty = false) {
        let escaping = false;
        let re2 = "";
        let uflag = false;
        for (let i = 0; i < glob2.length; i++) {
          const c3 = glob2.charAt(i);
          if (escaping) {
            escaping = false;
            re2 += (reSpecials.has(c3) ? "\\" : "") + c3;
            continue;
          }
          if (c3 === "\\") {
            if (i === glob2.length - 1) {
              re2 += "\\\\";
            } else {
              escaping = true;
            }
            continue;
          }
          if (c3 === "[") {
            const [src, needUflag, consumed, magic] = parseClass(glob2, i);
            if (consumed) {
              re2 += src;
              uflag = uflag || needUflag;
              i += consumed - 1;
              hasMagic2 = hasMagic2 || magic;
              continue;
            }
          }
          if (c3 === "*") {
            if (noEmpty && glob2 === "*")
              re2 += starNoEmpty;
            else
              re2 += star;
            hasMagic2 = true;
            continue;
          }
          if (c3 === "?") {
            re2 += qmark;
            hasMagic2 = true;
            continue;
          }
          re2 += regExpEscape(c3);
        }
        return [re2, unescape2(glob2), !!hasMagic2, uflag];
      }
    };
  }
});

// node_modules/glob/node_modules/minimatch/dist/esm/escape.js
var escape3;
var init_escape = __esm({
  "node_modules/glob/node_modules/minimatch/dist/esm/escape.js"() {
    init_esbuild_shims();
    escape3 = /* @__PURE__ */ __name((s2, { windowsPathsNoEscape = false } = {}) => {
      return windowsPathsNoEscape ? s2.replace(/[?*()[\]]/g, "[$&]") : s2.replace(/[?*()[\]\\]/g, "\\$&");
    }, "escape");
  }
});

// node_modules/glob/node_modules/minimatch/dist/esm/index.js
var import_brace_expansion, minimatch, starDotExtRE, starDotExtTest, starDotExtTestDot, starDotExtTestNocase, starDotExtTestNocaseDot, starDotStarRE, starDotStarTest, starDotStarTestDot, dotStarRE, dotStarTest, starRE, starTest, starTestDot, qmarksRE, qmarksTestNocase, qmarksTestNocaseDot, qmarksTestDot, qmarksTest, qmarksTestNoExt, qmarksTestNoExtDot, defaultPlatform, path25, sep3, GLOBSTAR, qmark2, star2, twoStarDot, twoStarNoDot, filter, ext, defaults2, braceExpand, makeRe, match, globMagic, regExpEscape2, Minimatch;
var init_esm5 = __esm({
  "node_modules/glob/node_modules/minimatch/dist/esm/index.js"() {
    init_esbuild_shims();
    import_brace_expansion = __toESM(require_brace_expansion(), 1);
    init_assert_valid_pattern();
    init_ast();
    init_escape();
    init_unescape();
    init_ast();
    init_escape();
    init_unescape();
    minimatch = /* @__PURE__ */ __name((p, pattern, options2 = {}) => {
      assertValidPattern(pattern);
      if (!options2.nocomment && pattern.charAt(0) === "#") {
        return false;
      }
      return new Minimatch(pattern, options2).match(p);
    }, "minimatch");
    starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
    starDotExtTest = /* @__PURE__ */ __name((ext2) => (f) => !f.startsWith(".") && f.endsWith(ext2), "starDotExtTest");
    starDotExtTestDot = /* @__PURE__ */ __name((ext2) => (f) => f.endsWith(ext2), "starDotExtTestDot");
    starDotExtTestNocase = /* @__PURE__ */ __name((ext2) => {
      ext2 = ext2.toLowerCase();
      return (f) => !f.startsWith(".") && f.toLowerCase().endsWith(ext2);
    }, "starDotExtTestNocase");
    starDotExtTestNocaseDot = /* @__PURE__ */ __name((ext2) => {
      ext2 = ext2.toLowerCase();
      return (f) => f.toLowerCase().endsWith(ext2);
    }, "starDotExtTestNocaseDot");
    starDotStarRE = /^\*+\.\*+$/;
    starDotStarTest = /* @__PURE__ */ __name((f) => !f.startsWith(".") && f.includes("."), "starDotStarTest");
    starDotStarTestDot = /* @__PURE__ */ __name((f) => f !== "." && f !== ".." && f.includes("."), "starDotStarTestDot");
    dotStarRE = /^\.\*+$/;
    dotStarTest = /* @__PURE__ */ __name((f) => f !== "." && f !== ".." && f.startsWith("."), "dotStarTest");
    starRE = /^\*+$/;
    starTest = /* @__PURE__ */ __name((f) => f.length !== 0 && !f.startsWith("."), "starTest");
    starTestDot = /* @__PURE__ */ __name((f) => f.length !== 0 && f !== "." && f !== "..", "starTestDot");
    qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
    qmarksTestNocase = /* @__PURE__ */ __name(([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExt([$0]);
      if (!ext2)
        return noext;
      ext2 = ext2.toLowerCase();
      return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
    }, "qmarksTestNocase");
    qmarksTestNocaseDot = /* @__PURE__ */ __name(([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExtDot([$0]);
      if (!ext2)
        return noext;
      ext2 = ext2.toLowerCase();
      return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
    }, "qmarksTestNocaseDot");
    qmarksTestDot = /* @__PURE__ */ __name(([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExtDot([$0]);
      return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
    }, "qmarksTestDot");
    qmarksTest = /* @__PURE__ */ __name(([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExt([$0]);
      return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
    }, "qmarksTest");
    qmarksTestNoExt = /* @__PURE__ */ __name(([$0]) => {
      const len = $0.length;
      return (f) => f.length === len && !f.startsWith(".");
    }, "qmarksTestNoExt");
    qmarksTestNoExtDot = /* @__PURE__ */ __name(([$0]) => {
      const len = $0.length;
      return (f) => f.length === len && f !== "." && f !== "..";
    }, "qmarksTestNoExtDot");
    defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
    path25 = {
      win32: { sep: "\\" },
      posix: { sep: "/" }
    };
    sep3 = defaultPlatform === "win32" ? path25.win32.sep : path25.posix.sep;
    minimatch.sep = sep3;
    GLOBSTAR = Symbol("globstar **");
    minimatch.GLOBSTAR = GLOBSTAR;
    qmark2 = "[^/]";
    star2 = qmark2 + "*?";
    twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
    twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
    filter = /* @__PURE__ */ __name((pattern, options2 = {}) => (p) => minimatch(p, pattern, options2), "filter");
    minimatch.filter = filter;
    ext = /* @__PURE__ */ __name((a, b = {}) => Object.assign({}, a, b), "ext");
    defaults2 = /* @__PURE__ */ __name((def2) => {
      if (!def2 || typeof def2 !== "object" || !Object.keys(def2).length) {
        return minimatch;
      }
      const orig = minimatch;
      const m = /* @__PURE__ */ __name((p, pattern, options2 = {}) => orig(p, pattern, ext(def2, options2)), "m");
      return Object.assign(m, {
        Minimatch: class Minimatch extends orig.Minimatch {
          static {
            __name(this, "Minimatch");
          }
          constructor(pattern, options2 = {}) {
            super(pattern, ext(def2, options2));
          }
          static defaults(options2) {
            return orig.defaults(ext(def2, options2)).Minimatch;
          }
        },
        AST: class AST extends orig.AST {
          static {
            __name(this, "AST");
          }
          /* c8 ignore start */
          constructor(type, parent, options2 = {}) {
            super(type, parent, ext(def2, options2));
          }
          /* c8 ignore stop */
          static fromGlob(pattern, options2 = {}) {
            return orig.AST.fromGlob(pattern, ext(def2, options2));
          }
        },
        unescape: /* @__PURE__ */ __name((s2, options2 = {}) => orig.unescape(s2, ext(def2, options2)), "unescape"),
        escape: /* @__PURE__ */ __name((s2, options2 = {}) => orig.escape(s2, ext(def2, options2)), "escape"),
        filter: /* @__PURE__ */ __name((pattern, options2 = {}) => orig.filter(pattern, ext(def2, options2)), "filter"),
        defaults: /* @__PURE__ */ __name((options2) => orig.defaults(ext(def2, options2)), "defaults"),
        makeRe: /* @__PURE__ */ __name((pattern, options2 = {}) => orig.makeRe(pattern, ext(def2, options2)), "makeRe"),
        braceExpand: /* @__PURE__ */ __name((pattern, options2 = {}) => orig.braceExpand(pattern, ext(def2, options2)), "braceExpand"),
        match: /* @__PURE__ */ __name((list3, pattern, options2 = {}) => orig.match(list3, pattern, ext(def2, options2)), "match"),
        sep: orig.sep,
        GLOBSTAR
      });
    }, "defaults");
    minimatch.defaults = defaults2;
    braceExpand = /* @__PURE__ */ __name((pattern, options2 = {}) => {
      assertValidPattern(pattern);
      if (options2.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
        return [pattern];
      }
      return (0, import_brace_expansion.default)(pattern);
    }, "braceExpand");
    minimatch.braceExpand = braceExpand;
    makeRe = /* @__PURE__ */ __name((pattern, options2 = {}) => new Minimatch(pattern, options2).makeRe(), "makeRe");
    minimatch.makeRe = makeRe;
    match = /* @__PURE__ */ __name((list3, pattern, options2 = {}) => {
      const mm = new Minimatch(pattern, options2);
      list3 = list3.filter((f) => mm.match(f));
      if (mm.options.nonull && !list3.length) {
        list3.push(pattern);
      }
      return list3;
    }, "match");
    minimatch.match = match;
    globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
    regExpEscape2 = /* @__PURE__ */ __name((s2) => s2.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "regExpEscape");
    Minimatch = class {
      static {
        __name(this, "Minimatch");
      }
      options;
      set;
      pattern;
      windowsPathsNoEscape;
      nonegate;
      negate;
      comment;
      empty;
      preserveMultipleSlashes;
      partial;
      globSet;
      globParts;
      nocase;
      isWindows;
      platform;
      windowsNoMagicRoot;
      regexp;
      constructor(pattern, options2 = {}) {
        assertValidPattern(pattern);
        options2 = options2 || {};
        this.options = options2;
        this.pattern = pattern;
        this.platform = options2.platform || defaultPlatform;
        this.isWindows = this.platform === "win32";
        this.windowsPathsNoEscape = !!options2.windowsPathsNoEscape || options2.allowWindowsEscape === false;
        if (this.windowsPathsNoEscape) {
          this.pattern = this.pattern.replace(/\\/g, "/");
        }
        this.preserveMultipleSlashes = !!options2.preserveMultipleSlashes;
        this.regexp = null;
        this.negate = false;
        this.nonegate = !!options2.nonegate;
        this.comment = false;
        this.empty = false;
        this.partial = !!options2.partial;
        this.nocase = !!this.options.nocase;
        this.windowsNoMagicRoot = options2.windowsNoMagicRoot !== void 0 ? options2.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
        this.globSet = [];
        this.globParts = [];
        this.set = [];
        this.make();
      }
      hasMagic() {
        if (this.options.magicalBraces && this.set.length > 1) {
          return true;
        }
        for (const pattern of this.set) {
          for (const part of pattern) {
            if (typeof part !== "string")
              return true;
          }
        }
        return false;
      }
      debug(..._) {
      }
      make() {
        const pattern = this.pattern;
        const options2 = this.options;
        if (!options2.nocomment && pattern.charAt(0) === "#") {
          this.comment = true;
          return;
        }
        if (!pattern) {
          this.empty = true;
          return;
        }
        this.parseNegate();
        this.globSet = [...new Set(this.braceExpand())];
        if (options2.debug) {
          this.debug = (...args) => console.error(...args);
        }
        this.debug(this.pattern, this.globSet);
        const rawGlobParts = this.globSet.map((s2) => this.slashSplit(s2));
        this.globParts = this.preprocess(rawGlobParts);
        this.debug(this.pattern, this.globParts);
        let set = this.globParts.map((s2, _, __) => {
          if (this.isWindows && this.windowsNoMagicRoot) {
            const isUNC = s2[0] === "" && s2[1] === "" && (s2[2] === "?" || !globMagic.test(s2[2])) && !globMagic.test(s2[3]);
            const isDrive = /^[a-z]:/i.test(s2[0]);
            if (isUNC) {
              return [...s2.slice(0, 4), ...s2.slice(4).map((ss) => this.parse(ss))];
            } else if (isDrive) {
              return [s2[0], ...s2.slice(1).map((ss) => this.parse(ss))];
            }
          }
          return s2.map((ss) => this.parse(ss));
        });
        this.debug(this.pattern, set);
        this.set = set.filter((s2) => s2.indexOf(false) === -1);
        if (this.isWindows) {
          for (let i = 0; i < this.set.length; i++) {
            const p = this.set[i];
            if (p[0] === "" && p[1] === "" && this.globParts[i][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) {
              p[2] = "?";
            }
          }
        }
        this.debug(this.pattern, this.set);
      }
      // various transforms to equivalent pattern sets that are
      // faster to process in a filesystem walk.  The goal is to
      // eliminate what we can, and push all ** patterns as far
      // to the right as possible, even if it increases the number
      // of patterns that we have to process.
      preprocess(globParts) {
        if (this.options.noglobstar) {
          for (let i = 0; i < globParts.length; i++) {
            for (let j = 0; j < globParts[i].length; j++) {
              if (globParts[i][j] === "**") {
                globParts[i][j] = "*";
              }
            }
          }
        }
        const { optimizationLevel = 1 } = this.options;
        if (optimizationLevel >= 2) {
          globParts = this.firstPhasePreProcess(globParts);
          globParts = this.secondPhasePreProcess(globParts);
        } else if (optimizationLevel >= 1) {
          globParts = this.levelOneOptimize(globParts);
        } else {
          globParts = this.adjascentGlobstarOptimize(globParts);
        }
        return globParts;
      }
      // just get rid of adjascent ** portions
      adjascentGlobstarOptimize(globParts) {
        return globParts.map((parts) => {
          let gs = -1;
          while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
            let i = gs;
            while (parts[i + 1] === "**") {
              i++;
            }
            if (i !== gs) {
              parts.splice(gs, i - gs);
            }
          }
          return parts;
        });
      }
      // get rid of adjascent ** and resolve .. portions
      levelOneOptimize(globParts) {
        return globParts.map((parts) => {
          parts = parts.reduce((set, part) => {
            const prev = set[set.length - 1];
            if (part === "**" && prev === "**") {
              return set;
            }
            if (part === "..") {
              if (prev && prev !== ".." && prev !== "." && prev !== "**") {
                set.pop();
                return set;
              }
            }
            set.push(part);
            return set;
          }, []);
          return parts.length === 0 ? [""] : parts;
        });
      }
      levelTwoFileOptimize(parts) {
        if (!Array.isArray(parts)) {
          parts = this.slashSplit(parts);
        }
        let didSomething = false;
        do {
          didSomething = false;
          if (!this.preserveMultipleSlashes) {
            for (let i = 1; i < parts.length - 1; i++) {
              const p = parts[i];
              if (i === 1 && p === "" && parts[0] === "")
                continue;
              if (p === "." || p === "") {
                didSomething = true;
                parts.splice(i, 1);
                i--;
              }
            }
            if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
              didSomething = true;
              parts.pop();
            }
          }
          let dd = 0;
          while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
            const p = parts[dd - 1];
            if (p && p !== "." && p !== ".." && p !== "**") {
              didSomething = true;
              parts.splice(dd - 1, 2);
              dd -= 2;
            }
          }
        } while (didSomething);
        return parts.length === 0 ? [""] : parts;
      }
      // First phase: single-pattern processing
      // <pre> is 1 or more portions
      // <rest> is 1 or more portions
      // <p> is any portion other than ., .., '', or **
      // <e> is . or ''
      //
      // **/.. is *brutal* for filesystem walking performance, because
      // it effectively resets the recursive walk each time it occurs,
      // and ** cannot be reduced out by a .. pattern part like a regexp
      // or most strings (other than .., ., and '') can be.
      //
      // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
      // <pre>/<e>/<rest> -> <pre>/<rest>
      // <pre>/<p>/../<rest> -> <pre>/<rest>
      // **/**/<rest> -> **/<rest>
      //
      // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
      // this WOULD be allowed if ** did follow symlinks, or * didn't
      firstPhasePreProcess(globParts) {
        let didSomething = false;
        do {
          didSomething = false;
          for (let parts of globParts) {
            let gs = -1;
            while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
              let gss = gs;
              while (parts[gss + 1] === "**") {
                gss++;
              }
              if (gss > gs) {
                parts.splice(gs + 1, gss - gs);
              }
              let next = parts[gs + 1];
              const p = parts[gs + 2];
              const p2 = parts[gs + 3];
              if (next !== "..")
                continue;
              if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") {
                continue;
              }
              didSomething = true;
              parts.splice(gs, 1);
              const other2 = parts.slice(0);
              other2[gs] = "**";
              globParts.push(other2);
              gs--;
            }
            if (!this.preserveMultipleSlashes) {
              for (let i = 1; i < parts.length - 1; i++) {
                const p = parts[i];
                if (i === 1 && p === "" && parts[0] === "")
                  continue;
                if (p === "." || p === "") {
                  didSomething = true;
                  parts.splice(i, 1);
                  i--;
                }
              }
              if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
                didSomething = true;
                parts.pop();
              }
            }
            let dd = 0;
            while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
              const p = parts[dd - 1];
              if (p && p !== "." && p !== ".." && p !== "**") {
                didSomething = true;
                const needDot = dd === 1 && parts[dd + 1] === "**";
                const splin = needDot ? ["."] : [];
                parts.splice(dd - 1, 2, ...splin);
                if (parts.length === 0)
                  parts.push("");
                dd -= 2;
              }
            }
          }
        } while (didSomething);
        return globParts;
      }
      // second phase: multi-pattern dedupes
      // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
      // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
      // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
      //
      // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
      // ^-- not valid because ** doens't follow symlinks
      secondPhasePreProcess(globParts) {
        for (let i = 0; i < globParts.length - 1; i++) {
          for (let j = i + 1; j < globParts.length; j++) {
            const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
            if (matched) {
              globParts[i] = [];
              globParts[j] = matched;
              break;
            }
          }
        }
        return globParts.filter((gs) => gs.length);
      }
      partsMatch(a, b, emptyGSMatch = false) {
        let ai = 0;
        let bi = 0;
        let result = [];
        let which = "";
        while (ai < a.length && bi < b.length) {
          if (a[ai] === b[bi]) {
            result.push(which === "b" ? b[bi] : a[ai]);
            ai++;
            bi++;
          } else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {
            result.push(a[ai]);
            ai++;
          } else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {
            result.push(b[bi]);
            bi++;
          } else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {
            if (which === "b")
              return false;
            which = "a";
            result.push(a[ai]);
            ai++;
            bi++;
          } else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {
            if (which === "a")
              return false;
            which = "b";
            result.push(b[bi]);
            ai++;
            bi++;
          } else {
            return false;
          }
        }
        return a.length === b.length && result;
      }
      parseNegate() {
        if (this.nonegate)
          return;
        const pattern = this.pattern;
        let negate = false;
        let negateOffset = 0;
        for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {
          negate = !negate;
          negateOffset++;
        }
        if (negateOffset)
          this.pattern = pattern.slice(negateOffset);
        this.negate = negate;
      }
      // set partial to true to test if, for example,
      // "/a/b" matches the start of "/*/b/*/d"
      // Partial means, if you run out of file before you run
      // out of pattern, then that's fine, as long as all
      // the parts match.
      matchOne(file, pattern, partial = false) {
        const options2 = this.options;
        if (this.isWindows) {
          const fileDrive = typeof file[0] === "string" && /^[a-z]:$/i.test(file[0]);
          const fileUNC = !fileDrive && file[0] === "" && file[1] === "" && file[2] === "?" && /^[a-z]:$/i.test(file[3]);
          const patternDrive = typeof pattern[0] === "string" && /^[a-z]:$/i.test(pattern[0]);
          const patternUNC = !patternDrive && pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
          const fdi = fileUNC ? 3 : fileDrive ? 0 : void 0;
          const pdi = patternUNC ? 3 : patternDrive ? 0 : void 0;
          if (typeof fdi === "number" && typeof pdi === "number") {
            const [fd, pd] = [file[fdi], pattern[pdi]];
            if (fd.toLowerCase() === pd.toLowerCase()) {
              pattern[pdi] = fd;
              if (pdi > fdi) {
                pattern = pattern.slice(pdi);
              } else if (fdi > pdi) {
                file = file.slice(fdi);
              }
            }
          }
        }
        const { optimizationLevel = 1 } = this.options;
        if (optimizationLevel >= 2) {
          file = this.levelTwoFileOptimize(file);
        }
        this.debug("matchOne", this, { file, pattern });
        this.debug("matchOne", file.length, pattern.length);
        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
          this.debug("matchOne loop");
          var p = pattern[pi];
          var f = file[fi];
          this.debug(pattern, p, f);
          if (p === false) {
            return false;
          }
          if (p === GLOBSTAR) {
            this.debug("GLOBSTAR", [pattern, p, f]);
            var fr = fi;
            var pr = pi + 1;
            if (pr === pl) {
              this.debug("** at the end");
              for (; fi < fl; fi++) {
                if (file[fi] === "." || file[fi] === ".." || !options2.dot && file[fi].charAt(0) === ".")
                  return false;
              }
              return true;
            }
            while (fr < fl) {
              var swallowee = file[fr];
              this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
              if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
                this.debug("globstar found match!", fr, fl, swallowee);
                return true;
              } else {
                if (swallowee === "." || swallowee === ".." || !options2.dot && swallowee.charAt(0) === ".") {
                  this.debug("dot detected!", file, fr, pattern, pr);
                  break;
                }
                this.debug("globstar swallow a segment, and continue");
                fr++;
              }
            }
            if (partial) {
              this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
              if (fr === fl) {
                return true;
              }
            }
            return false;
          }
          let hit;
          if (typeof p === "string") {
            hit = f === p;
            this.debug("string match", p, f, hit);
          } else {
            hit = p.test(f);
            this.debug("pattern match", p, f, hit);
          }
          if (!hit)
            return false;
        }
        if (fi === fl && pi === pl) {
          return true;
        } else if (fi === fl) {
          return partial;
        } else if (pi === pl) {
          return fi === fl - 1 && file[fi] === "";
        } else {
          throw new Error("wtf?");
        }
      }
      braceExpand() {
        return braceExpand(this.pattern, this.options);
      }
      parse(pattern) {
        assertValidPattern(pattern);
        const options2 = this.options;
        if (pattern === "**")
          return GLOBSTAR;
        if (pattern === "")
          return "";
        let m;
        let fastTest = null;
        if (m = pattern.match(starRE)) {
          fastTest = options2.dot ? starTestDot : starTest;
        } else if (m = pattern.match(starDotExtRE)) {
          fastTest = (options2.nocase ? options2.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options2.dot ? starDotExtTestDot : starDotExtTest)(m[1]);
        } else if (m = pattern.match(qmarksRE)) {
          fastTest = (options2.nocase ? options2.dot ? qmarksTestNocaseDot : qmarksTestNocase : options2.dot ? qmarksTestDot : qmarksTest)(m);
        } else if (m = pattern.match(starDotStarRE)) {
          fastTest = options2.dot ? starDotStarTestDot : starDotStarTest;
        } else if (m = pattern.match(dotStarRE)) {
          fastTest = dotStarTest;
        }
        const re2 = AST.fromGlob(pattern, this.options).toMMPattern();
        if (fastTest && typeof re2 === "object") {
          Reflect.defineProperty(re2, "test", { value: fastTest });
        }
        return re2;
      }
      makeRe() {
        if (this.regexp || this.regexp === false)
          return this.regexp;
        const set = this.set;
        if (!set.length) {
          this.regexp = false;
          return this.regexp;
        }
        const options2 = this.options;
        const twoStar = options2.noglobstar ? star2 : options2.dot ? twoStarDot : twoStarNoDot;
        const flags = new Set(options2.nocase ? ["i"] : []);
        let re2 = set.map((pattern) => {
          const pp = pattern.map((p) => {
            if (p instanceof RegExp) {
              for (const f of p.flags.split(""))
                flags.add(f);
            }
            return typeof p === "string" ? regExpEscape2(p) : p === GLOBSTAR ? GLOBSTAR : p._src;
          });
          pp.forEach((p, i) => {
            const next = pp[i + 1];
            const prev = pp[i - 1];
            if (p !== GLOBSTAR || prev === GLOBSTAR) {
              return;
            }
            if (prev === void 0) {
              if (next !== void 0 && next !== GLOBSTAR) {
                pp[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
              } else {
                pp[i] = twoStar;
              }
            } else if (next === void 0) {
              pp[i - 1] = prev + "(?:\\/|" + twoStar + ")?";
            } else if (next !== GLOBSTAR) {
              pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
              pp[i + 1] = GLOBSTAR;
            }
          });
          return pp.filter((p) => p !== GLOBSTAR).join("/");
        }).join("|");
        const [open3, close] = set.length > 1 ? ["(?:", ")"] : ["", ""];
        re2 = "^" + open3 + re2 + close + "$";
        if (this.negate)
          re2 = "^(?!" + re2 + ").+$";
        try {
          this.regexp = new RegExp(re2, [...flags].join(""));
        } catch (ex) {
          this.regexp = false;
        }
        return this.regexp;
      }
      slashSplit(p) {
        if (this.preserveMultipleSlashes) {
          return p.split("/");
        } else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
          return ["", ...p.split(/\/+/)];
        } else {
          return p.split(/\/+/);
        }
      }
      match(f, partial = this.partial) {
        this.debug("match", f, this.pattern);
        if (this.comment) {
          return false;
        }
        if (this.empty) {
          return f === "";
        }
        if (f === "/" && partial) {
          return true;
        }
        const options2 = this.options;
        if (this.isWindows) {
          f = f.split("\\").join("/");
        }
        const ff = this.slashSplit(f);
        this.debug(this.pattern, "split", ff);
        const set = this.set;
        this.debug(this.pattern, "set", set);
        let filename = ff[ff.length - 1];
        if (!filename) {
          for (let i = ff.length - 2; !filename && i >= 0; i--) {
            filename = ff[i];
          }
        }
        for (let i = 0; i < set.length; i++) {
          const pattern = set[i];
          let file = ff;
          if (options2.matchBase && pattern.length === 1) {
            file = [filename];
          }
          const hit = this.matchOne(file, pattern, partial);
          if (hit) {
            if (options2.flipNegate) {
              return true;
            }
            return !this.negate;
          }
        }
        if (options2.flipNegate) {
          return false;
        }
        return this.negate;
      }
      static defaults(def2) {
        return minimatch.defaults(def2).Minimatch;
      }
    };
    minimatch.AST = AST;
    minimatch.Minimatch = Minimatch;
    minimatch.escape = escape3;
    minimatch.unescape = unescape2;
  }
});

// node_modules/lru-cache/dist/esm/index.js
var perf, warned, PROCESS, emitWarning, AC, AS, shouldWarn, TYPE, isPosInt, getUintArray, ZeroArray, Stack, LRUCache;
var init_esm6 = __esm({
  "node_modules/lru-cache/dist/esm/index.js"() {
    init_esbuild_shims();
    perf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
    warned = /* @__PURE__ */ new Set();
    PROCESS = typeof process === "object" && !!process ? process : {};
    emitWarning = /* @__PURE__ */ __name((msg, type, code2, fn) => {
      typeof PROCESS.emitWarning === "function" ? PROCESS.emitWarning(msg, type, code2, fn) : console.error(`[${code2}] ${type}: ${msg}`);
    }, "emitWarning");
    AC = globalThis.AbortController;
    AS = globalThis.AbortSignal;
    if (typeof AC === "undefined") {
      AS = class AbortSignal {
        static {
          __name(this, "AbortSignal");
        }
        onabort;
        _onabort = [];
        reason;
        aborted = false;
        addEventListener(_, fn) {
          this._onabort.push(fn);
        }
      };
      AC = class AbortController {
        static {
          __name(this, "AbortController");
        }
        constructor() {
          warnACPolyfill();
        }
        signal = new AS();
        abort(reason) {
          if (this.signal.aborted)
            return;
          this.signal.reason = reason;
          this.signal.aborted = true;
          for (const fn of this.signal._onabort) {
            fn(reason);
          }
          this.signal.onabort?.(reason);
        }
      };
      let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== "1";
      const warnACPolyfill = /* @__PURE__ */ __name(() => {
        if (!printACPolyfillWarning)
          return;
        printACPolyfillWarning = false;
        emitWarning("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", warnACPolyfill);
      }, "warnACPolyfill");
    }
    shouldWarn = /* @__PURE__ */ __name((code2) => !warned.has(code2), "shouldWarn");
    TYPE = Symbol("type");
    isPosInt = /* @__PURE__ */ __name((n2) => n2 && n2 === Math.floor(n2) && n2 > 0 && isFinite(n2), "isPosInt");
    getUintArray = /* @__PURE__ */ __name((max) => !isPosInt(max) ? null : max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray : null, "getUintArray");
    ZeroArray = class extends Array {
      static {
        __name(this, "ZeroArray");
      }
      constructor(size) {
        super(size);
        this.fill(0);
      }
    };
    Stack = class _Stack {
      static {
        __name(this, "Stack");
      }
      heap;
      length;
      // private constructor
      static #constructing = false;
      static create(max) {
        const HeapCls = getUintArray(max);
        if (!HeapCls)
          return [];
        _Stack.#constructing = true;
        const s2 = new _Stack(max, HeapCls);
        _Stack.#constructing = false;
        return s2;
      }
      constructor(max, HeapCls) {
        if (!_Stack.#constructing) {
          throw new TypeError("instantiate Stack using Stack.create(n)");
        }
        this.heap = new HeapCls(max);
        this.length = 0;
      }
      push(n2) {
        this.heap[this.length++] = n2;
      }
      pop() {
        return this.heap[--this.length];
      }
    };
    LRUCache = class _LRUCache {
      static {
        __name(this, "LRUCache");
      }
      // options that cannot be changed without disaster
      #max;
      #maxSize;
      #dispose;
      #disposeAfter;
      #fetchMethod;
      #memoMethod;
      /**
       * {@link LRUCache.OptionsBase.ttl}
       */
      ttl;
      /**
       * {@link LRUCache.OptionsBase.ttlResolution}
       */
      ttlResolution;
      /**
       * {@link LRUCache.OptionsBase.ttlAutopurge}
       */
      ttlAutopurge;
      /**
       * {@link LRUCache.OptionsBase.updateAgeOnGet}
       */
      updateAgeOnGet;
      /**
       * {@link LRUCache.OptionsBase.updateAgeOnHas}
       */
      updateAgeOnHas;
      /**
       * {@link LRUCache.OptionsBase.allowStale}
       */
      allowStale;
      /**
       * {@link LRUCache.OptionsBase.noDisposeOnSet}
       */
      noDisposeOnSet;
      /**
       * {@link LRUCache.OptionsBase.noUpdateTTL}
       */
      noUpdateTTL;
      /**
       * {@link LRUCache.OptionsBase.maxEntrySize}
       */
      maxEntrySize;
      /**
       * {@link LRUCache.OptionsBase.sizeCalculation}
       */
      sizeCalculation;
      /**
       * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
       */
      noDeleteOnFetchRejection;
      /**
       * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
       */
      noDeleteOnStaleGet;
      /**
       * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
       */
      allowStaleOnFetchAbort;
      /**
       * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
       */
      allowStaleOnFetchRejection;
      /**
       * {@link LRUCache.OptionsBase.ignoreFetchAbort}
       */
      ignoreFetchAbort;
      // computed properties
      #size;
      #calculatedSize;
      #keyMap;
      #keyList;
      #valList;
      #next;
      #prev;
      #head;
      #tail;
      #free;
      #disposed;
      #sizes;
      #starts;
      #ttls;
      #hasDispose;
      #hasFetchMethod;
      #hasDisposeAfter;
      /**
       * Do not call this method unless you need to inspect the
       * inner workings of the cache.  If anything returned by this
       * object is modified in any way, strange breakage may occur.
       *
       * These fields are private for a reason!
       *
       * @internal
       */
      static unsafeExposeInternals(c3) {
        return {
          // properties
          starts: c3.#starts,
          ttls: c3.#ttls,
          sizes: c3.#sizes,
          keyMap: c3.#keyMap,
          keyList: c3.#keyList,
          valList: c3.#valList,
          next: c3.#next,
          prev: c3.#prev,
          get head() {
            return c3.#head;
          },
          get tail() {
            return c3.#tail;
          },
          free: c3.#free,
          // methods
          isBackgroundFetch: /* @__PURE__ */ __name((p) => c3.#isBackgroundFetch(p), "isBackgroundFetch"),
          backgroundFetch: /* @__PURE__ */ __name((k, index, options2, context2) => c3.#backgroundFetch(k, index, options2, context2), "backgroundFetch"),
          moveToTail: /* @__PURE__ */ __name((index) => c3.#moveToTail(index), "moveToTail"),
          indexes: /* @__PURE__ */ __name((options2) => c3.#indexes(options2), "indexes"),
          rindexes: /* @__PURE__ */ __name((options2) => c3.#rindexes(options2), "rindexes"),
          isStale: /* @__PURE__ */ __name((index) => c3.#isStale(index), "isStale")
        };
      }
      // Protected read-only members
      /**
       * {@link LRUCache.OptionsBase.max} (read-only)
       */
      get max() {
        return this.#max;
      }
      /**
       * {@link LRUCache.OptionsBase.maxSize} (read-only)
       */
      get maxSize() {
        return this.#maxSize;
      }
      /**
       * The total computed size of items in the cache (read-only)
       */
      get calculatedSize() {
        return this.#calculatedSize;
      }
      /**
       * The number of items stored in the cache (read-only)
       */
      get size() {
        return this.#size;
      }
      /**
       * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
       */
      get fetchMethod() {
        return this.#fetchMethod;
      }
      get memoMethod() {
        return this.#memoMethod;
      }
      /**
       * {@link LRUCache.OptionsBase.dispose} (read-only)
       */
      get dispose() {
        return this.#dispose;
      }
      /**
       * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
       */
      get disposeAfter() {
        return this.#disposeAfter;
      }
      constructor(options2) {
        const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort } = options2;
        if (max !== 0 && !isPosInt(max)) {
          throw new TypeError("max option must be a nonnegative integer");
        }
        const UintArray = max ? getUintArray(max) : Array;
        if (!UintArray) {
          throw new Error("invalid max value: " + max);
        }
        this.#max = max;
        this.#maxSize = maxSize;
        this.maxEntrySize = maxEntrySize || this.#maxSize;
        this.sizeCalculation = sizeCalculation;
        if (this.sizeCalculation) {
          if (!this.#maxSize && !this.maxEntrySize) {
            throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
          }
          if (typeof this.sizeCalculation !== "function") {
            throw new TypeError("sizeCalculation set to non-function");
          }
        }
        if (memoMethod !== void 0 && typeof memoMethod !== "function") {
          throw new TypeError("memoMethod must be a function if defined");
        }
        this.#memoMethod = memoMethod;
        if (fetchMethod !== void 0 && typeof fetchMethod !== "function") {
          throw new TypeError("fetchMethod must be a function if specified");
        }
        this.#fetchMethod = fetchMethod;
        this.#hasFetchMethod = !!fetchMethod;
        this.#keyMap = /* @__PURE__ */ new Map();
        this.#keyList = new Array(max).fill(void 0);
        this.#valList = new Array(max).fill(void 0);
        this.#next = new UintArray(max);
        this.#prev = new UintArray(max);
        this.#head = 0;
        this.#tail = 0;
        this.#free = Stack.create(max);
        this.#size = 0;
        this.#calculatedSize = 0;
        if (typeof dispose === "function") {
          this.#dispose = dispose;
        }
        if (typeof disposeAfter === "function") {
          this.#disposeAfter = disposeAfter;
          this.#disposed = [];
        } else {
          this.#disposeAfter = void 0;
          this.#disposed = void 0;
        }
        this.#hasDispose = !!this.#dispose;
        this.#hasDisposeAfter = !!this.#disposeAfter;
        this.noDisposeOnSet = !!noDisposeOnSet;
        this.noUpdateTTL = !!noUpdateTTL;
        this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
        this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
        this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
        this.ignoreFetchAbort = !!ignoreFetchAbort;
        if (this.maxEntrySize !== 0) {
          if (this.#maxSize !== 0) {
            if (!isPosInt(this.#maxSize)) {
              throw new TypeError("maxSize must be a positive integer if specified");
            }
          }
          if (!isPosInt(this.maxEntrySize)) {
            throw new TypeError("maxEntrySize must be a positive integer if specified");
          }
          this.#initializeSizeTracking();
        }
        this.allowStale = !!allowStale;
        this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
        this.updateAgeOnGet = !!updateAgeOnGet;
        this.updateAgeOnHas = !!updateAgeOnHas;
        this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1;
        this.ttlAutopurge = !!ttlAutopurge;
        this.ttl = ttl || 0;
        if (this.ttl) {
          if (!isPosInt(this.ttl)) {
            throw new TypeError("ttl must be a positive integer if specified");
          }
          this.#initializeTTLTracking();
        }
        if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
          throw new TypeError("At least one of max, maxSize, or ttl is required");
        }
        if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
          const code2 = "LRU_CACHE_UNBOUNDED";
          if (shouldWarn(code2)) {
            warned.add(code2);
            const msg = "TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.";
            emitWarning(msg, "UnboundedCacheWarning", code2, _LRUCache);
          }
        }
      }
      /**
       * Return the number of ms left in the item's TTL. If item is not in cache,
       * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
       */
      getRemainingTTL(key) {
        return this.#keyMap.has(key) ? Infinity : 0;
      }
      #initializeTTLTracking() {
        const ttls = new ZeroArray(this.#max);
        const starts = new ZeroArray(this.#max);
        this.#ttls = ttls;
        this.#starts = starts;
        this.#setItemTTL = (index, ttl, start = perf.now()) => {
          starts[index] = ttl !== 0 ? start : 0;
          ttls[index] = ttl;
          if (ttl !== 0 && this.ttlAutopurge) {
            const t2 = setTimeout(() => {
              if (this.#isStale(index)) {
                this.#delete(this.#keyList[index], "expire");
              }
            }, ttl + 1);
            if (t2.unref) {
              t2.unref();
            }
          }
        };
        this.#updateItemAge = (index) => {
          starts[index] = ttls[index] !== 0 ? perf.now() : 0;
        };
        this.#statusTTL = (status, index) => {
          if (ttls[index]) {
            const ttl = ttls[index];
            const start = starts[index];
            if (!ttl || !start)
              return;
            status.ttl = ttl;
            status.start = start;
            status.now = cachedNow || getNow();
            const age = status.now - start;
            status.remainingTTL = ttl - age;
          }
        };
        let cachedNow = 0;
        const getNow = /* @__PURE__ */ __name(() => {
          const n2 = perf.now();
          if (this.ttlResolution > 0) {
            cachedNow = n2;
            const t2 = setTimeout(() => cachedNow = 0, this.ttlResolution);
            if (t2.unref) {
              t2.unref();
            }
          }
          return n2;
        }, "getNow");
        this.getRemainingTTL = (key) => {
          const index = this.#keyMap.get(key);
          if (index === void 0) {
            return 0;
          }
          const ttl = ttls[index];
          const start = starts[index];
          if (!ttl || !start) {
            return Infinity;
          }
          const age = (cachedNow || getNow()) - start;
          return ttl - age;
        };
        this.#isStale = (index) => {
          const s2 = starts[index];
          const t2 = ttls[index];
          return !!t2 && !!s2 && (cachedNow || getNow()) - s2 > t2;
        };
      }
      // conditionally set private methods related to TTL
      #updateItemAge = /* @__PURE__ */ __name(() => {
      }, "#updateItemAge");
      #statusTTL = /* @__PURE__ */ __name(() => {
      }, "#statusTTL");
      #setItemTTL = /* @__PURE__ */ __name(() => {
      }, "#setItemTTL");
      /* c8 ignore stop */
      #isStale = /* @__PURE__ */ __name(() => false, "#isStale");
      #initializeSizeTracking() {
        const sizes = new ZeroArray(this.#max);
        this.#calculatedSize = 0;
        this.#sizes = sizes;
        this.#removeItemSize = (index) => {
          this.#calculatedSize -= sizes[index];
          sizes[index] = 0;
        };
        this.#requireSize = (k, v, size, sizeCalculation) => {
          if (this.#isBackgroundFetch(v)) {
            return 0;
          }
          if (!isPosInt(size)) {
            if (sizeCalculation) {
              if (typeof sizeCalculation !== "function") {
                throw new TypeError("sizeCalculation must be a function");
              }
              size = sizeCalculation(v, k);
              if (!isPosInt(size)) {
                throw new TypeError("sizeCalculation return invalid (expect positive integer)");
              }
            } else {
              throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");
            }
          }
          return size;
        };
        this.#addItemSize = (index, size, status) => {
          sizes[index] = size;
          if (this.#maxSize) {
            const maxSize = this.#maxSize - sizes[index];
            while (this.#calculatedSize > maxSize) {
              this.#evict(true);
            }
          }
          this.#calculatedSize += sizes[index];
          if (status) {
            status.entrySize = size;
            status.totalCalculatedSize = this.#calculatedSize;
          }
        };
      }
      #removeItemSize = /* @__PURE__ */ __name((_i) => {
      }, "#removeItemSize");
      #addItemSize = /* @__PURE__ */ __name((_i, _s, _st) => {
      }, "#addItemSize");
      #requireSize = /* @__PURE__ */ __name((_k, _v, size, sizeCalculation) => {
        if (size || sizeCalculation) {
          throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
        }
        return 0;
      }, "#requireSize");
      *#indexes({ allowStale = this.allowStale } = {}) {
        if (this.#size) {
          for (let i = this.#tail; true; ) {
            if (!this.#isValidIndex(i)) {
              break;
            }
            if (allowStale || !this.#isStale(i)) {
              yield i;
            }
            if (i === this.#head) {
              break;
            } else {
              i = this.#prev[i];
            }
          }
        }
      }
      *#rindexes({ allowStale = this.allowStale } = {}) {
        if (this.#size) {
          for (let i = this.#head; true; ) {
            if (!this.#isValidIndex(i)) {
              break;
            }
            if (allowStale || !this.#isStale(i)) {
              yield i;
            }
            if (i === this.#tail) {
              break;
            } else {
              i = this.#next[i];
            }
          }
        }
      }
      #isValidIndex(index) {
        return index !== void 0 && this.#keyMap.get(this.#keyList[index]) === index;
      }
      /**
       * Return a generator yielding `[key, value]` pairs,
       * in order from most recently used to least recently used.
       */
      *entries() {
        for (const i of this.#indexes()) {
          if (this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
            yield [this.#keyList[i], this.#valList[i]];
          }
        }
      }
      /**
       * Inverse order version of {@link LRUCache.entries}
       *
       * Return a generator yielding `[key, value]` pairs,
       * in order from least recently used to most recently used.
       */
      *rentries() {
        for (const i of this.#rindexes()) {
          if (this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
            yield [this.#keyList[i], this.#valList[i]];
          }
        }
      }
      /**
       * Return a generator yielding the keys in the cache,
       * in order from most recently used to least recently used.
       */
      *keys() {
        for (const i of this.#indexes()) {
          const k = this.#keyList[i];
          if (k !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
            yield k;
          }
        }
      }
      /**
       * Inverse order version of {@link LRUCache.keys}
       *
       * Return a generator yielding the keys in the cache,
       * in order from least recently used to most recently used.
       */
      *rkeys() {
        for (const i of this.#rindexes()) {
          const k = this.#keyList[i];
          if (k !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
            yield k;
          }
        }
      }
      /**
       * Return a generator yielding the values in the cache,
       * in order from most recently used to least recently used.
       */
      *values() {
        for (const i of this.#indexes()) {
          const v = this.#valList[i];
          if (v !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
            yield this.#valList[i];
          }
        }
      }
      /**
       * Inverse order version of {@link LRUCache.values}
       *
       * Return a generator yielding the values in the cache,
       * in order from least recently used to most recently used.
       */
      *rvalues() {
        for (const i of this.#rindexes()) {
          const v = this.#valList[i];
          if (v !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
            yield this.#valList[i];
          }
        }
      }
      /**
       * Iterating over the cache itself yields the same results as
       * {@link LRUCache.entries}
       */
      [Symbol.iterator]() {
        return this.entries();
      }
      /**
       * A String value that is used in the creation of the default string
       * description of an object. Called by the built-in method
       * `Object.prototype.toString`.
       */
      [Symbol.toStringTag] = "LRUCache";
      /**
       * Find a value for which the supplied fn method returns a truthy value,
       * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.
       */
      find(fn, getOptions2 = {}) {
        for (const i of this.#indexes()) {
          const v = this.#valList[i];
          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0)
            continue;
          if (fn(value, this.#keyList[i], this)) {
            return this.get(this.#keyList[i], getOptions2);
          }
        }
      }
      /**
       * Call the supplied function on each item in the cache, in order from most
       * recently used to least recently used.
       *
       * `fn` is called as `fn(value, key, cache)`.
       *
       * If `thisp` is provided, function will be called in the `this`-context of
       * the provided object, or the cache if no `thisp` object is provided.
       *
       * Does not update age or recenty of use, or iterate over stale values.
       */
      forEach(fn, thisp = this) {
        for (const i of this.#indexes()) {
          const v = this.#valList[i];
          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0)
            continue;
          fn.call(thisp, value, this.#keyList[i], this);
        }
      }
      /**
       * The same as {@link LRUCache.forEach} but items are iterated over in
       * reverse order.  (ie, less recently used items are iterated over first.)
       */
      rforEach(fn, thisp = this) {
        for (const i of this.#rindexes()) {
          const v = this.#valList[i];
          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0)
            continue;
          fn.call(thisp, value, this.#keyList[i], this);
        }
      }
      /**
       * Delete any stale entries. Returns true if anything was removed,
       * false otherwise.
       */
      purgeStale() {
        let deleted = false;
        for (const i of this.#rindexes({ allowStale: true })) {
          if (this.#isStale(i)) {
            this.#delete(this.#keyList[i], "expire");
            deleted = true;
          }
        }
        return deleted;
      }
      /**
       * Get the extended info about a given entry, to get its value, size, and
       * TTL info simultaneously. Returns `undefined` if the key is not present.
       *
       * Unlike {@link LRUCache#dump}, which is designed to be portable and survive
       * serialization, the `start` value is always the current timestamp, and the
       * `ttl` is a calculated remaining time to live (negative if expired).
       *
       * Always returns stale values, if their info is found in the cache, so be
       * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
       * if relevant.
       */
      info(key) {
        const i = this.#keyMap.get(key);
        if (i === void 0)
          return void 0;
        const v = this.#valList[i];
        const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
        if (value === void 0)
          return void 0;
        const entry = { value };
        if (this.#ttls && this.#starts) {
          const ttl = this.#ttls[i];
          const start = this.#starts[i];
          if (ttl && start) {
            const remain = ttl - (perf.now() - start);
            entry.ttl = remain;
            entry.start = Date.now();
          }
        }
        if (this.#sizes) {
          entry.size = this.#sizes[i];
        }
        return entry;
      }
      /**
       * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
       * passed to {@link LRLUCache#load}.
       *
       * The `start` fields are calculated relative to a portable `Date.now()`
       * timestamp, even if `performance.now()` is available.
       *
       * Stale entries are always included in the `dump`, even if
       * {@link LRUCache.OptionsBase.allowStale} is false.
       *
       * Note: this returns an actual array, not a generator, so it can be more
       * easily passed around.
       */
      dump() {
        const arr = [];
        for (const i of this.#indexes({ allowStale: true })) {
          const key = this.#keyList[i];
          const v = this.#valList[i];
          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0 || key === void 0)
            continue;
          const entry = { value };
          if (this.#ttls && this.#starts) {
            entry.ttl = this.#ttls[i];
            const age = perf.now() - this.#starts[i];
            entry.start = Math.floor(Date.now() - age);
          }
          if (this.#sizes) {
            entry.size = this.#sizes[i];
          }
          arr.unshift([key, entry]);
        }
        return arr;
      }
      /**
       * Reset the cache and load in the items in entries in the order listed.
       *
       * The shape of the resulting cache may be different if the same options are
       * not used in both caches.
       *
       * The `start` fields are assumed to be calculated relative to a portable
       * `Date.now()` timestamp, even if `performance.now()` is available.
       */
      load(arr) {
        this.clear();
        for (const [key, entry] of arr) {
          if (entry.start) {
            const age = Date.now() - entry.start;
            entry.start = perf.now() - age;
          }
          this.set(key, entry.value, entry);
        }
      }
      /**
       * Add a value to the cache.
       *
       * Note: if `undefined` is specified as a value, this is an alias for
       * {@link LRUCache#delete}
       *
       * Fields on the {@link LRUCache.SetOptions} options param will override
       * their corresponding values in the constructor options for the scope
       * of this single `set()` operation.
       *
       * If `start` is provided, then that will set the effective start
       * time for the TTL calculation. Note that this must be a previous
       * value of `performance.now()` if supported, or a previous value of
       * `Date.now()` if not.
       *
       * Options object may also include `size`, which will prevent
       * calling the `sizeCalculation` function and just use the specified
       * number if it is a positive integer, and `noDisposeOnSet` which
       * will prevent calling a `dispose` function in the case of
       * overwrites.
       *
       * If the `size` (or return value of `sizeCalculation`) for a given
       * entry is greater than `maxEntrySize`, then the item will not be
       * added to the cache.
       *
       * Will update the recency of the entry.
       *
       * If the value is `undefined`, then this is an alias for
       * `cache.delete(key)`. `undefined` is never stored in the cache.
       */
      set(k, v, setOptions2 = {}) {
        if (v === void 0) {
          this.delete(k);
          return this;
        }
        const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions2;
        let { noUpdateTTL = this.noUpdateTTL } = setOptions2;
        const size = this.#requireSize(k, v, setOptions2.size || 0, sizeCalculation);
        if (this.maxEntrySize && size > this.maxEntrySize) {
          if (status) {
            status.set = "miss";
            status.maxEntrySizeExceeded = true;
          }
          this.#delete(k, "set");
          return this;
        }
        let index = this.#size === 0 ? void 0 : this.#keyMap.get(k);
        if (index === void 0) {
          index = this.#size === 0 ? this.#tail : this.#free.length !== 0 ? this.#free.pop() : this.#size === this.#max ? this.#evict(false) : this.#size;
          this.#keyList[index] = k;
          this.#valList[index] = v;
          this.#keyMap.set(k, index);
          this.#next[this.#tail] = index;
          this.#prev[index] = this.#tail;
          this.#tail = index;
          this.#size++;
          this.#addItemSize(index, size, status);
          if (status)
            status.set = "add";
          noUpdateTTL = false;
        } else {
          this.#moveToTail(index);
          const oldVal = this.#valList[index];
          if (v !== oldVal) {
            if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
              oldVal.__abortController.abort(new Error("replaced"));
              const { __staleWhileFetching: s2 } = oldVal;
              if (s2 !== void 0 && !noDisposeOnSet) {
                if (this.#hasDispose) {
                  this.#dispose?.(s2, k, "set");
                }
                if (this.#hasDisposeAfter) {
                  this.#disposed?.push([s2, k, "set"]);
                }
              }
            } else if (!noDisposeOnSet) {
              if (this.#hasDispose) {
                this.#dispose?.(oldVal, k, "set");
              }
              if (this.#hasDisposeAfter) {
                this.#disposed?.push([oldVal, k, "set"]);
              }
            }
            this.#removeItemSize(index);
            this.#addItemSize(index, size, status);
            this.#valList[index] = v;
            if (status) {
              status.set = "replace";
              const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal;
              if (oldValue !== void 0)
                status.oldValue = oldValue;
            }
          } else if (status) {
            status.set = "update";
          }
        }
        if (ttl !== 0 && !this.#ttls) {
          this.#initializeTTLTracking();
        }
        if (this.#ttls) {
          if (!noUpdateTTL) {
            this.#setItemTTL(index, ttl, start);
          }
          if (status)
            this.#statusTTL(status, index);
        }
        if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
          const dt = this.#disposed;
          let task;
          while (task = dt?.shift()) {
            this.#disposeAfter?.(...task);
          }
        }
        return this;
      }
      /**
       * Evict the least recently used item, returning its value or
       * `undefined` if cache is empty.
       */
      pop() {
        try {
          while (this.#size) {
            const val = this.#valList[this.#head];
            this.#evict(true);
            if (this.#isBackgroundFetch(val)) {
              if (val.__staleWhileFetching) {
                return val.__staleWhileFetching;
              }
            } else if (val !== void 0) {
              return val;
            }
          }
        } finally {
          if (this.#hasDisposeAfter && this.#disposed) {
            const dt = this.#disposed;
            let task;
            while (task = dt?.shift()) {
              this.#disposeAfter?.(...task);
            }
          }
        }
      }
      #evict(free) {
        const head = this.#head;
        const k = this.#keyList[head];
        const v = this.#valList[head];
        if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
          v.__abortController.abort(new Error("evicted"));
        } else if (this.#hasDispose || this.#hasDisposeAfter) {
          if (this.#hasDispose) {
            this.#dispose?.(v, k, "evict");
          }
          if (this.#hasDisposeAfter) {
            this.#disposed?.push([v, k, "evict"]);
          }
        }
        this.#removeItemSize(head);
        if (free) {
          this.#keyList[head] = void 0;
          this.#valList[head] = void 0;
          this.#free.push(head);
        }
        if (this.#size === 1) {
          this.#head = this.#tail = 0;
          this.#free.length = 0;
        } else {
          this.#head = this.#next[head];
        }
        this.#keyMap.delete(k);
        this.#size--;
        return head;
      }
      /**
       * Check if a key is in the cache, without updating the recency of use.
       * Will return false if the item is stale, even though it is technically
       * in the cache.
       *
       * Check if a key is in the cache, without updating the recency of
       * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
       * to `true` in either the options or the constructor.
       *
       * Will return `false` if the item is stale, even though it is technically in
       * the cache. The difference can be determined (if it matters) by using a
       * `status` argument, and inspecting the `has` field.
       *
       * Will not update item age unless
       * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
       */
      has(k, hasOptions = {}) {
        const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
        const index = this.#keyMap.get(k);
        if (index !== void 0) {
          const v = this.#valList[index];
          if (this.#isBackgroundFetch(v) && v.__staleWhileFetching === void 0) {
            return false;
          }
          if (!this.#isStale(index)) {
            if (updateAgeOnHas) {
              this.#updateItemAge(index);
            }
            if (status) {
              status.has = "hit";
              this.#statusTTL(status, index);
            }
            return true;
          } else if (status) {
            status.has = "stale";
            this.#statusTTL(status, index);
          }
        } else if (status) {
          status.has = "miss";
        }
        return false;
      }
      /**
       * Like {@link LRUCache#get} but doesn't update recency or delete stale
       * items.
       *
       * Returns `undefined` if the item is stale, unless
       * {@link LRUCache.OptionsBase.allowStale} is set.
       */
      peek(k, peekOptions = {}) {
        const { allowStale = this.allowStale } = peekOptions;
        const index = this.#keyMap.get(k);
        if (index === void 0 || !allowStale && this.#isStale(index)) {
          return;
        }
        const v = this.#valList[index];
        return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
      }
      #backgroundFetch(k, index, options2, context2) {
        const v = index === void 0 ? void 0 : this.#valList[index];
        if (this.#isBackgroundFetch(v)) {
          return v;
        }
        const ac = new AC();
        const { signal } = options2;
        signal?.addEventListener("abort", () => ac.abort(signal.reason), {
          signal: ac.signal
        });
        const fetchOpts = {
          signal: ac.signal,
          options: options2,
          context: context2
        };
        const cb = /* @__PURE__ */ __name((v2, updateCache = false) => {
          const { aborted } = ac.signal;
          const ignoreAbort = options2.ignoreFetchAbort && v2 !== void 0;
          if (options2.status) {
            if (aborted && !updateCache) {
              options2.status.fetchAborted = true;
              options2.status.fetchError = ac.signal.reason;
              if (ignoreAbort)
                options2.status.fetchAbortIgnored = true;
            } else {
              options2.status.fetchResolved = true;
            }
          }
          if (aborted && !ignoreAbort && !updateCache) {
            return fetchFail(ac.signal.reason);
          }
          const bf2 = p;
          if (this.#valList[index] === p) {
            if (v2 === void 0) {
              if (bf2.__staleWhileFetching) {
                this.#valList[index] = bf2.__staleWhileFetching;
              } else {
                this.#delete(k, "fetch");
              }
            } else {
              if (options2.status)
                options2.status.fetchUpdated = true;
              this.set(k, v2, fetchOpts.options);
            }
          }
          return v2;
        }, "cb");
        const eb = /* @__PURE__ */ __name((er) => {
          if (options2.status) {
            options2.status.fetchRejected = true;
            options2.status.fetchError = er;
          }
          return fetchFail(er);
        }, "eb");
        const fetchFail = /* @__PURE__ */ __name((er) => {
          const { aborted } = ac.signal;
          const allowStaleAborted = aborted && options2.allowStaleOnFetchAbort;
          const allowStale = allowStaleAborted || options2.allowStaleOnFetchRejection;
          const noDelete = allowStale || options2.noDeleteOnFetchRejection;
          const bf2 = p;
          if (this.#valList[index] === p) {
            const del = !noDelete || bf2.__staleWhileFetching === void 0;
            if (del) {
              this.#delete(k, "fetch");
            } else if (!allowStaleAborted) {
              this.#valList[index] = bf2.__staleWhileFetching;
            }
          }
          if (allowStale) {
            if (options2.status && bf2.__staleWhileFetching !== void 0) {
              options2.status.returnedStale = true;
            }
            return bf2.__staleWhileFetching;
          } else if (bf2.__returned === bf2) {
            throw er;
          }
        }, "fetchFail");
        const pcall = /* @__PURE__ */ __name((res, rej) => {
          const fmp = this.#fetchMethod?.(k, v, fetchOpts);
          if (fmp && fmp instanceof Promise) {
            fmp.then((v2) => res(v2 === void 0 ? void 0 : v2), rej);
          }
          ac.signal.addEventListener("abort", () => {
            if (!options2.ignoreFetchAbort || options2.allowStaleOnFetchAbort) {
              res(void 0);
              if (options2.allowStaleOnFetchAbort) {
                res = /* @__PURE__ */ __name((v2) => cb(v2, true), "res");
              }
            }
          });
        }, "pcall");
        if (options2.status)
          options2.status.fetchDispatched = true;
        const p = new Promise(pcall).then(cb, eb);
        const bf = Object.assign(p, {
          __abortController: ac,
          __staleWhileFetching: v,
          __returned: void 0
        });
        if (index === void 0) {
          this.set(k, bf, { ...fetchOpts.options, status: void 0 });
          index = this.#keyMap.get(k);
        } else {
          this.#valList[index] = bf;
        }
        return bf;
      }
      #isBackgroundFetch(p) {
        if (!this.#hasFetchMethod)
          return false;
        const b = p;
        return !!b && b instanceof Promise && b.hasOwnProperty("__staleWhileFetching") && b.__abortController instanceof AC;
      }
      async fetch(k, fetchOptions = {}) {
        const {
          // get options
          allowStale = this.allowStale,
          updateAgeOnGet = this.updateAgeOnGet,
          noDeleteOnStaleGet = this.noDeleteOnStaleGet,
          // set options
          ttl = this.ttl,
          noDisposeOnSet = this.noDisposeOnSet,
          size = 0,
          sizeCalculation = this.sizeCalculation,
          noUpdateTTL = this.noUpdateTTL,
          // fetch exclusive options
          noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
          allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
          ignoreFetchAbort = this.ignoreFetchAbort,
          allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
          context: context2,
          forceRefresh = false,
          status,
          signal
        } = fetchOptions;
        if (!this.#hasFetchMethod) {
          if (status)
            status.fetch = "get";
          return this.get(k, {
            allowStale,
            updateAgeOnGet,
            noDeleteOnStaleGet,
            status
          });
        }
        const options2 = {
          allowStale,
          updateAgeOnGet,
          noDeleteOnStaleGet,
          ttl,
          noDisposeOnSet,
          size,
          sizeCalculation,
          noUpdateTTL,
          noDeleteOnFetchRejection,
          allowStaleOnFetchRejection,
          allowStaleOnFetchAbort,
          ignoreFetchAbort,
          status,
          signal
        };
        let index = this.#keyMap.get(k);
        if (index === void 0) {
          if (status)
            status.fetch = "miss";
          const p = this.#backgroundFetch(k, index, options2, context2);
          return p.__returned = p;
        } else {
          const v = this.#valList[index];
          if (this.#isBackgroundFetch(v)) {
            const stale = allowStale && v.__staleWhileFetching !== void 0;
            if (status) {
              status.fetch = "inflight";
              if (stale)
                status.returnedStale = true;
            }
            return stale ? v.__staleWhileFetching : v.__returned = v;
          }
          const isStale = this.#isStale(index);
          if (!forceRefresh && !isStale) {
            if (status)
              status.fetch = "hit";
            this.#moveToTail(index);
            if (updateAgeOnGet) {
              this.#updateItemAge(index);
            }
            if (status)
              this.#statusTTL(status, index);
            return v;
          }
          const p = this.#backgroundFetch(k, index, options2, context2);
          const hasStale = p.__staleWhileFetching !== void 0;
          const staleVal = hasStale && allowStale;
          if (status) {
            status.fetch = isStale ? "stale" : "refresh";
            if (staleVal && isStale)
              status.returnedStale = true;
          }
          return staleVal ? p.__staleWhileFetching : p.__returned = p;
        }
      }
      async forceFetch(k, fetchOptions = {}) {
        const v = await this.fetch(k, fetchOptions);
        if (v === void 0)
          throw new Error("fetch() returned undefined");
        return v;
      }
      memo(k, memoOptions = {}) {
        const memoMethod = this.#memoMethod;
        if (!memoMethod) {
          throw new Error("no memoMethod provided to constructor");
        }
        const { context: context2, forceRefresh, ...options2 } = memoOptions;
        const v = this.get(k, options2);
        if (!forceRefresh && v !== void 0)
          return v;
        const vv = memoMethod(k, v, {
          options: options2,
          context: context2
        });
        this.set(k, vv, options2);
        return vv;
      }
      /**
       * Return a value from the cache. Will update the recency of the cache
       * entry found.
       *
       * If the key is not found, get() will return `undefined`.
       */
      get(k, getOptions2 = {}) {
        const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions2;
        const index = this.#keyMap.get(k);
        if (index !== void 0) {
          const value = this.#valList[index];
          const fetching = this.#isBackgroundFetch(value);
          if (status)
            this.#statusTTL(status, index);
          if (this.#isStale(index)) {
            if (status)
              status.get = "stale";
            if (!fetching) {
              if (!noDeleteOnStaleGet) {
                this.#delete(k, "expire");
              }
              if (status && allowStale)
                status.returnedStale = true;
              return allowStale ? value : void 0;
            } else {
              if (status && allowStale && value.__staleWhileFetching !== void 0) {
                status.returnedStale = true;
              }
              return allowStale ? value.__staleWhileFetching : void 0;
            }
          } else {
            if (status)
              status.get = "hit";
            if (fetching) {
              return value.__staleWhileFetching;
            }
            this.#moveToTail(index);
            if (updateAgeOnGet) {
              this.#updateItemAge(index);
            }
            return value;
          }
        } else if (status) {
          status.get = "miss";
        }
      }
      #connect(p, n2) {
        this.#prev[n2] = p;
        this.#next[p] = n2;
      }
      #moveToTail(index) {
        if (index !== this.#tail) {
          if (index === this.#head) {
            this.#head = this.#next[index];
          } else {
            this.#connect(this.#prev[index], this.#next[index]);
          }
          this.#connect(this.#tail, index);
          this.#tail = index;
        }
      }
      /**
       * Deletes a key out of the cache.
       *
       * Returns true if the key was deleted, false otherwise.
       */
      delete(k) {
        return this.#delete(k, "delete");
      }
      #delete(k, reason) {
        let deleted = false;
        if (this.#size !== 0) {
          const index = this.#keyMap.get(k);
          if (index !== void 0) {
            deleted = true;
            if (this.#size === 1) {
              this.#clear(reason);
            } else {
              this.#removeItemSize(index);
              const v = this.#valList[index];
              if (this.#isBackgroundFetch(v)) {
                v.__abortController.abort(new Error("deleted"));
              } else if (this.#hasDispose || this.#hasDisposeAfter) {
                if (this.#hasDispose) {
                  this.#dispose?.(v, k, reason);
                }
                if (this.#hasDisposeAfter) {
                  this.#disposed?.push([v, k, reason]);
                }
              }
              this.#keyMap.delete(k);
              this.#keyList[index] = void 0;
              this.#valList[index] = void 0;
              if (index === this.#tail) {
                this.#tail = this.#prev[index];
              } else if (index === this.#head) {
                this.#head = this.#next[index];
              } else {
                const pi = this.#prev[index];
                this.#next[pi] = this.#next[index];
                const ni = this.#next[index];
                this.#prev[ni] = this.#prev[index];
              }
              this.#size--;
              this.#free.push(index);
            }
          }
        }
        if (this.#hasDisposeAfter && this.#disposed?.length) {
          const dt = this.#disposed;
          let task;
          while (task = dt?.shift()) {
            this.#disposeAfter?.(...task);
          }
        }
        return deleted;
      }
      /**
       * Clear the cache entirely, throwing away all values.
       */
      clear() {
        return this.#clear("delete");
      }
      #clear(reason) {
        for (const index of this.#rindexes({ allowStale: true })) {
          const v = this.#valList[index];
          if (this.#isBackgroundFetch(v)) {
            v.__abortController.abort(new Error("deleted"));
          } else {
            const k = this.#keyList[index];
            if (this.#hasDispose) {
              this.#dispose?.(v, k, reason);
            }
            if (this.#hasDisposeAfter) {
              this.#disposed?.push([v, k, reason]);
            }
          }
        }
        this.#keyMap.clear();
        this.#valList.fill(void 0);
        this.#keyList.fill(void 0);
        if (this.#ttls && this.#starts) {
          this.#ttls.fill(0);
          this.#starts.fill(0);
        }
        if (this.#sizes) {
          this.#sizes.fill(0);
        }
        this.#head = 0;
        this.#tail = 0;
        this.#free.length = 0;
        this.#calculatedSize = 0;
        this.#size = 0;
        if (this.#hasDisposeAfter && this.#disposed) {
          const dt = this.#disposed;
          let task;
          while (task = dt?.shift()) {
            this.#disposeAfter?.(...task);
          }
        }
      }
    };
  }
});

// node_modules/minipass/dist/esm/index.js
import { EventEmitter as EventEmitter6 } from "node:events";
import Stream3 from "node:stream";
import { StringDecoder } from "node:string_decoder";
var proc, isStream, isReadable, isWritable, EOF, MAYBE_EMIT_END, EMITTED_END, EMITTING_END, EMITTED_ERROR, CLOSED, READ, FLUSH, FLUSHCHUNK, ENCODING, DECODER, FLOWING, PAUSED, RESUME, BUFFER, PIPES, BUFFERLENGTH, BUFFERPUSH, BUFFERSHIFT, OBJECTMODE, DESTROYED, ERROR, EMITDATA, EMITEND, EMITEND2, ASYNC, ABORT, ABORTED, SIGNAL, DATALISTENERS, DISCARDED, defer, nodefer, isEndish, isArrayBufferLike, isArrayBufferView, Pipe, PipeProxyErrors, isObjectModeOptions, isEncodingOptions, Minipass;
var init_esm7 = __esm({
  "node_modules/minipass/dist/esm/index.js"() {
    init_esbuild_shims();
    proc = typeof process === "object" && process ? process : {
      stdout: null,
      stderr: null
    };
    isStream = /* @__PURE__ */ __name((s2) => !!s2 && typeof s2 === "object" && (s2 instanceof Minipass || s2 instanceof Stream3 || isReadable(s2) || isWritable(s2)), "isStream");
    isReadable = /* @__PURE__ */ __name((s2) => !!s2 && typeof s2 === "object" && s2 instanceof EventEmitter6 && typeof s2.pipe === "function" && // node core Writable streams have a pipe() method, but it throws
    s2.pipe !== Stream3.Writable.prototype.pipe, "isReadable");
    isWritable = /* @__PURE__ */ __name((s2) => !!s2 && typeof s2 === "object" && s2 instanceof EventEmitter6 && typeof s2.write === "function" && typeof s2.end === "function", "isWritable");
    EOF = Symbol("EOF");
    MAYBE_EMIT_END = Symbol("maybeEmitEnd");
    EMITTED_END = Symbol("emittedEnd");
    EMITTING_END = Symbol("emittingEnd");
    EMITTED_ERROR = Symbol("emittedError");
    CLOSED = Symbol("closed");
    READ = Symbol("read");
    FLUSH = Symbol("flush");
    FLUSHCHUNK = Symbol("flushChunk");
    ENCODING = Symbol("encoding");
    DECODER = Symbol("decoder");
    FLOWING = Symbol("flowing");
    PAUSED = Symbol("paused");
    RESUME = Symbol("resume");
    BUFFER = Symbol("buffer");
    PIPES = Symbol("pipes");
    BUFFERLENGTH = Symbol("bufferLength");
    BUFFERPUSH = Symbol("bufferPush");
    BUFFERSHIFT = Symbol("bufferShift");
    OBJECTMODE = Symbol("objectMode");
    DESTROYED = Symbol("destroyed");
    ERROR = Symbol("error");
    EMITDATA = Symbol("emitData");
    EMITEND = Symbol("emitEnd");
    EMITEND2 = Symbol("emitEnd2");
    ASYNC = Symbol("async");
    ABORT = Symbol("abort");
    ABORTED = Symbol("aborted");
    SIGNAL = Symbol("signal");
    DATALISTENERS = Symbol("dataListeners");
    DISCARDED = Symbol("discarded");
    defer = /* @__PURE__ */ __name((fn) => Promise.resolve().then(fn), "defer");
    nodefer = /* @__PURE__ */ __name((fn) => fn(), "nodefer");
    isEndish = /* @__PURE__ */ __name((ev) => ev === "end" || ev === "finish" || ev === "prefinish", "isEndish");
    isArrayBufferLike = /* @__PURE__ */ __name((b) => b instanceof ArrayBuffer || !!b && typeof b === "object" && b.constructor && b.constructor.name === "ArrayBuffer" && b.byteLength >= 0, "isArrayBufferLike");
    isArrayBufferView = /* @__PURE__ */ __name((b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b), "isArrayBufferView");
    Pipe = class {
      static {
        __name(this, "Pipe");
      }
      src;
      dest;
      opts;
      ondrain;
      constructor(src, dest, opts) {
        this.src = src;
        this.dest = dest;
        this.opts = opts;
        this.ondrain = () => src[RESUME]();
        this.dest.on("drain", this.ondrain);
      }
      unpipe() {
        this.dest.removeListener("drain", this.ondrain);
      }
      // only here for the prototype
      /* c8 ignore start */
      proxyErrors(_er) {
      }
      /* c8 ignore stop */
      end() {
        this.unpipe();
        if (this.opts.end)
          this.dest.end();
      }
    };
    PipeProxyErrors = class extends Pipe {
      static {
        __name(this, "PipeProxyErrors");
      }
      unpipe() {
        this.src.removeListener("error", this.proxyErrors);
        super.unpipe();
      }
      constructor(src, dest, opts) {
        super(src, dest, opts);
        this.proxyErrors = (er) => dest.emit("error", er);
        src.on("error", this.proxyErrors);
      }
    };
    isObjectModeOptions = /* @__PURE__ */ __name((o2) => !!o2.objectMode, "isObjectModeOptions");
    isEncodingOptions = /* @__PURE__ */ __name((o2) => !o2.objectMode && !!o2.encoding && o2.encoding !== "buffer", "isEncodingOptions");
    Minipass = class extends EventEmitter6 {
      static {
        __name(this, "Minipass");
      }
      [FLOWING] = false;
      [PAUSED] = false;
      [PIPES] = [];
      [BUFFER] = [];
      [OBJECTMODE];
      [ENCODING];
      [ASYNC];
      [DECODER];
      [EOF] = false;
      [EMITTED_END] = false;
      [EMITTING_END] = false;
      [CLOSED] = false;
      [EMITTED_ERROR] = null;
      [BUFFERLENGTH] = 0;
      [DESTROYED] = false;
      [SIGNAL];
      [ABORTED] = false;
      [DATALISTENERS] = 0;
      [DISCARDED] = false;
      /**
       * true if the stream can be written
       */
      writable = true;
      /**
       * true if the stream can be read
       */
      readable = true;
      /**
       * If `RType` is Buffer, then options do not need to be provided.
       * Otherwise, an options object must be provided to specify either
       * {@link Minipass.SharedOptions.objectMode} or
       * {@link Minipass.SharedOptions.encoding}, as appropriate.
       */
      constructor(...args) {
        const options2 = args[0] || {};
        super();
        if (options2.objectMode && typeof options2.encoding === "string") {
          throw new TypeError("Encoding and objectMode may not be used together");
        }
        if (isObjectModeOptions(options2)) {
          this[OBJECTMODE] = true;
          this[ENCODING] = null;
        } else if (isEncodingOptions(options2)) {
          this[ENCODING] = options2.encoding;
          this[OBJECTMODE] = false;
        } else {
          this[OBJECTMODE] = false;
          this[ENCODING] = null;
        }
        this[ASYNC] = !!options2.async;
        this[DECODER] = this[ENCODING] ? new StringDecoder(this[ENCODING]) : null;
        if (options2 && options2.debugExposeBuffer === true) {
          Object.defineProperty(this, "buffer", { get: /* @__PURE__ */ __name(() => this[BUFFER], "get") });
        }
        if (options2 && options2.debugExposePipes === true) {
          Object.defineProperty(this, "pipes", { get: /* @__PURE__ */ __name(() => this[PIPES], "get") });
        }
        const { signal } = options2;
        if (signal) {
          this[SIGNAL] = signal;
          if (signal.aborted) {
            this[ABORT]();
          } else {
            signal.addEventListener("abort", () => this[ABORT]());
          }
        }
      }
      /**
       * The amount of data stored in the buffer waiting to be read.
       *
       * For Buffer strings, this will be the total byte length.
       * For string encoding streams, this will be the string character length,
       * according to JavaScript's `string.length` logic.
       * For objectMode streams, this is a count of the items waiting to be
       * emitted.
       */
      get bufferLength() {
        return this[BUFFERLENGTH];
      }
      /**
       * The `BufferEncoding` currently in use, or `null`
       */
      get encoding() {
        return this[ENCODING];
      }
      /**
       * @deprecated - This is a read only property
       */
      set encoding(_enc) {
        throw new Error("Encoding must be set at instantiation time");
      }
      /**
       * @deprecated - Encoding may only be set at instantiation time
       */
      setEncoding(_enc) {
        throw new Error("Encoding must be set at instantiation time");
      }
      /**
       * True if this is an objectMode stream
       */
      get objectMode() {
        return this[OBJECTMODE];
      }
      /**
       * @deprecated - This is a read-only property
       */
      set objectMode(_om) {
        throw new Error("objectMode must be set at instantiation time");
      }
      /**
       * true if this is an async stream
       */
      get ["async"]() {
        return this[ASYNC];
      }
      /**
       * Set to true to make this stream async.
       *
       * Once set, it cannot be unset, as this would potentially cause incorrect
       * behavior.  Ie, a sync stream can be made async, but an async stream
       * cannot be safely made sync.
       */
      set ["async"](a) {
        this[ASYNC] = this[ASYNC] || !!a;
      }
      // drop everything and get out of the flow completely
      [ABORT]() {
        this[ABORTED] = true;
        this.emit("abort", this[SIGNAL]?.reason);
        this.destroy(this[SIGNAL]?.reason);
      }
      /**
       * True if the stream has been aborted.
       */
      get aborted() {
        return this[ABORTED];
      }
      /**
       * No-op setter. Stream aborted status is set via the AbortSignal provided
       * in the constructor options.
       */
      set aborted(_) {
      }
      write(chunk, encoding, cb) {
        if (this[ABORTED])
          return false;
        if (this[EOF])
          throw new Error("write after end");
        if (this[DESTROYED]) {
          this.emit("error", Object.assign(new Error("Cannot call write after a stream was destroyed"), { code: "ERR_STREAM_DESTROYED" }));
          return true;
        }
        if (typeof encoding === "function") {
          cb = encoding;
          encoding = "utf8";
        }
        if (!encoding)
          encoding = "utf8";
        const fn = this[ASYNC] ? defer : nodefer;
        if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
          if (isArrayBufferView(chunk)) {
            chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
          } else if (isArrayBufferLike(chunk)) {
            chunk = Buffer.from(chunk);
          } else if (typeof chunk !== "string") {
            throw new Error("Non-contiguous data written to non-objectMode stream");
          }
        }
        if (this[OBJECTMODE]) {
          if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
            this[FLUSH](true);
          if (this[FLOWING])
            this.emit("data", chunk);
          else
            this[BUFFERPUSH](chunk);
          if (this[BUFFERLENGTH] !== 0)
            this.emit("readable");
          if (cb)
            fn(cb);
          return this[FLOWING];
        }
        if (!chunk.length) {
          if (this[BUFFERLENGTH] !== 0)
            this.emit("readable");
          if (cb)
            fn(cb);
          return this[FLOWING];
        }
        if (typeof chunk === "string" && // unless it is a string already ready for us to use
        !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)) {
          chunk = Buffer.from(chunk, encoding);
        }
        if (Buffer.isBuffer(chunk) && this[ENCODING]) {
          chunk = this[DECODER].write(chunk);
        }
        if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
          this[FLUSH](true);
        if (this[FLOWING])
          this.emit("data", chunk);
        else
          this[BUFFERPUSH](chunk);
        if (this[BUFFERLENGTH] !== 0)
          this.emit("readable");
        if (cb)
          fn(cb);
        return this[FLOWING];
      }
      /**
       * Low-level explicit read method.
       *
       * In objectMode, the argument is ignored, and one item is returned if
       * available.
       *
       * `n` is the number of bytes (or in the case of encoding streams,
       * characters) to consume. If `n` is not provided, then the entire buffer
       * is returned, or `null` is returned if no data is available.
       *
       * If `n` is greater that the amount of data in the internal buffer,
       * then `null` is returned.
       */
      read(n2) {
        if (this[DESTROYED])
          return null;
        this[DISCARDED] = false;
        if (this[BUFFERLENGTH] === 0 || n2 === 0 || n2 && n2 > this[BUFFERLENGTH]) {
          this[MAYBE_EMIT_END]();
          return null;
        }
        if (this[OBJECTMODE])
          n2 = null;
        if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {
          this[BUFFER] = [
            this[ENCODING] ? this[BUFFER].join("") : Buffer.concat(this[BUFFER], this[BUFFERLENGTH])
          ];
        }
        const ret = this[READ](n2 || null, this[BUFFER][0]);
        this[MAYBE_EMIT_END]();
        return ret;
      }
      [READ](n2, chunk) {
        if (this[OBJECTMODE])
          this[BUFFERSHIFT]();
        else {
          const c3 = chunk;
          if (n2 === c3.length || n2 === null)
            this[BUFFERSHIFT]();
          else if (typeof c3 === "string") {
            this[BUFFER][0] = c3.slice(n2);
            chunk = c3.slice(0, n2);
            this[BUFFERLENGTH] -= n2;
          } else {
            this[BUFFER][0] = c3.subarray(n2);
            chunk = c3.subarray(0, n2);
            this[BUFFERLENGTH] -= n2;
          }
        }
        this.emit("data", chunk);
        if (!this[BUFFER].length && !this[EOF])
          this.emit("drain");
        return chunk;
      }
      end(chunk, encoding, cb) {
        if (typeof chunk === "function") {
          cb = chunk;
          chunk = void 0;
        }
        if (typeof encoding === "function") {
          cb = encoding;
          encoding = "utf8";
        }
        if (chunk !== void 0)
          this.write(chunk, encoding);
        if (cb)
          this.once("end", cb);
        this[EOF] = true;
        this.writable = false;
        if (this[FLOWING] || !this[PAUSED])
          this[MAYBE_EMIT_END]();
        return this;
      }
      // don't let the internal resume be overwritten
      [RESUME]() {
        if (this[DESTROYED])
          return;
        if (!this[DATALISTENERS] && !this[PIPES].length) {
          this[DISCARDED] = true;
        }
        this[PAUSED] = false;
        this[FLOWING] = true;
        this.emit("resume");
        if (this[BUFFER].length)
          this[FLUSH]();
        else if (this[EOF])
          this[MAYBE_EMIT_END]();
        else
          this.emit("drain");
      }
      /**
       * Resume the stream if it is currently in a paused state
       *
       * If called when there are no pipe destinations or `data` event listeners,
       * this will place the stream in a "discarded" state, where all data will
       * be thrown away. The discarded state is removed if a pipe destination or
       * data handler is added, if pause() is called, or if any synchronous or
       * asynchronous iteration is started.
       */
      resume() {
        return this[RESUME]();
      }
      /**
       * Pause the stream
       */
      pause() {
        this[FLOWING] = false;
        this[PAUSED] = true;
        this[DISCARDED] = false;
      }
      /**
       * true if the stream has been forcibly destroyed
       */
      get destroyed() {
        return this[DESTROYED];
      }
      /**
       * true if the stream is currently in a flowing state, meaning that
       * any writes will be immediately emitted.
       */
      get flowing() {
        return this[FLOWING];
      }
      /**
       * true if the stream is currently in a paused state
       */
      get paused() {
        return this[PAUSED];
      }
      [BUFFERPUSH](chunk) {
        if (this[OBJECTMODE])
          this[BUFFERLENGTH] += 1;
        else
          this[BUFFERLENGTH] += chunk.length;
        this[BUFFER].push(chunk);
      }
      [BUFFERSHIFT]() {
        if (this[OBJECTMODE])
          this[BUFFERLENGTH] -= 1;
        else
          this[BUFFERLENGTH] -= this[BUFFER][0].length;
        return this[BUFFER].shift();
      }
      [FLUSH](noDrain = false) {
        do {
        } while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) && this[BUFFER].length);
        if (!noDrain && !this[BUFFER].length && !this[EOF])
          this.emit("drain");
      }
      [FLUSHCHUNK](chunk) {
        this.emit("data", chunk);
        return this[FLOWING];
      }
      /**
       * Pipe all data emitted by this stream into the destination provided.
       *
       * Triggers the flow of data.
       */
      pipe(dest, opts) {
        if (this[DESTROYED])
          return dest;
        this[DISCARDED] = false;
        const ended = this[EMITTED_END];
        opts = opts || {};
        if (dest === proc.stdout || dest === proc.stderr)
          opts.end = false;
        else
          opts.end = opts.end !== false;
        opts.proxyErrors = !!opts.proxyErrors;
        if (ended) {
          if (opts.end)
            dest.end();
        } else {
          this[PIPES].push(!opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts));
          if (this[ASYNC])
            defer(() => this[RESUME]());
          else
            this[RESUME]();
        }
        return dest;
      }
      /**
       * Fully unhook a piped destination stream.
       *
       * If the destination stream was the only consumer of this stream (ie,
       * there are no other piped destinations or `'data'` event listeners)
       * then the flow of data will stop until there is another consumer or
       * {@link Minipass#resume} is explicitly called.
       */
      unpipe(dest) {
        const p = this[PIPES].find((p2) => p2.dest === dest);
        if (p) {
          if (this[PIPES].length === 1) {
            if (this[FLOWING] && this[DATALISTENERS] === 0) {
              this[FLOWING] = false;
            }
            this[PIPES] = [];
          } else
            this[PIPES].splice(this[PIPES].indexOf(p), 1);
          p.unpipe();
        }
      }
      /**
       * Alias for {@link Minipass#on}
       */
      addListener(ev, handler) {
        return this.on(ev, handler);
      }
      /**
       * Mostly identical to `EventEmitter.on`, with the following
       * behavior differences to prevent data loss and unnecessary hangs:
       *
       * - Adding a 'data' event handler will trigger the flow of data
       *
       * - Adding a 'readable' event handler when there is data waiting to be read
       *   will cause 'readable' to be emitted immediately.
       *
       * - Adding an 'endish' event handler ('end', 'finish', etc.) which has
       *   already passed will cause the event to be emitted immediately and all
       *   handlers removed.
       *
       * - Adding an 'error' event handler after an error has been emitted will
       *   cause the event to be re-emitted immediately with the error previously
       *   raised.
       */
      on(ev, handler) {
        const ret = super.on(ev, handler);
        if (ev === "data") {
          this[DISCARDED] = false;
          this[DATALISTENERS]++;
          if (!this[PIPES].length && !this[FLOWING]) {
            this[RESUME]();
          }
        } else if (ev === "readable" && this[BUFFERLENGTH] !== 0) {
          super.emit("readable");
        } else if (isEndish(ev) && this[EMITTED_END]) {
          super.emit(ev);
          this.removeAllListeners(ev);
        } else if (ev === "error" && this[EMITTED_ERROR]) {
          const h = handler;
          if (this[ASYNC])
            defer(() => h.call(this, this[EMITTED_ERROR]));
          else
            h.call(this, this[EMITTED_ERROR]);
        }
        return ret;
      }
      /**
       * Alias for {@link Minipass#off}
       */
      removeListener(ev, handler) {
        return this.off(ev, handler);
      }
      /**
       * Mostly identical to `EventEmitter.off`
       *
       * If a 'data' event handler is removed, and it was the last consumer
       * (ie, there are no pipe destinations or other 'data' event listeners),
       * then the flow of data will stop until there is another consumer or
       * {@link Minipass#resume} is explicitly called.
       */
      off(ev, handler) {
        const ret = super.off(ev, handler);
        if (ev === "data") {
          this[DATALISTENERS] = this.listeners("data").length;
          if (this[DATALISTENERS] === 0 && !this[DISCARDED] && !this[PIPES].length) {
            this[FLOWING] = false;
          }
        }
        return ret;
      }
      /**
       * Mostly identical to `EventEmitter.removeAllListeners`
       *
       * If all 'data' event handlers are removed, and they were the last consumer
       * (ie, there are no pipe destinations), then the flow of data will stop
       * until there is another consumer or {@link Minipass#resume} is explicitly
       * called.
       */
      removeAllListeners(ev) {
        const ret = super.removeAllListeners(ev);
        if (ev === "data" || ev === void 0) {
          this[DATALISTENERS] = 0;
          if (!this[DISCARDED] && !this[PIPES].length) {
            this[FLOWING] = false;
          }
        }
        return ret;
      }
      /**
       * true if the 'end' event has been emitted
       */
      get emittedEnd() {
        return this[EMITTED_END];
      }
      [MAYBE_EMIT_END]() {
        if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this[BUFFER].length === 0 && this[EOF]) {
          this[EMITTING_END] = true;
          this.emit("end");
          this.emit("prefinish");
          this.emit("finish");
          if (this[CLOSED])
            this.emit("close");
          this[EMITTING_END] = false;
        }
      }
      /**
       * Mostly identical to `EventEmitter.emit`, with the following
       * behavior differences to prevent data loss and unnecessary hangs:
       *
       * If the stream has been destroyed, and the event is something other
       * than 'close' or 'error', then `false` is returned and no handlers
       * are called.
       *
       * If the event is 'end', and has already been emitted, then the event
       * is ignored. If the stream is in a paused or non-flowing state, then
       * the event will be deferred until data flow resumes. If the stream is
       * async, then handlers will be called on the next tick rather than
       * immediately.
       *
       * If the event is 'close', and 'end' has not yet been emitted, then
       * the event will be deferred until after 'end' is emitted.
       *
       * If the event is 'error', and an AbortSignal was provided for the stream,
       * and there are no listeners, then the event is ignored, matching the
       * behavior of node core streams in the presense of an AbortSignal.
       *
       * If the event is 'finish' or 'prefinish', then all listeners will be
       * removed after emitting the event, to prevent double-firing.
       */
      emit(ev, ...args) {
        const data = args[0];
        if (ev !== "error" && ev !== "close" && ev !== DESTROYED && this[DESTROYED]) {
          return false;
        } else if (ev === "data") {
          return !this[OBJECTMODE] && !data ? false : this[ASYNC] ? (defer(() => this[EMITDATA](data)), true) : this[EMITDATA](data);
        } else if (ev === "end") {
          return this[EMITEND]();
        } else if (ev === "close") {
          this[CLOSED] = true;
          if (!this[EMITTED_END] && !this[DESTROYED])
            return false;
          const ret2 = super.emit("close");
          this.removeAllListeners("close");
          return ret2;
        } else if (ev === "error") {
          this[EMITTED_ERROR] = data;
          super.emit(ERROR, data);
          const ret2 = !this[SIGNAL] || this.listeners("error").length ? super.emit("error", data) : false;
          this[MAYBE_EMIT_END]();
          return ret2;
        } else if (ev === "resume") {
          const ret2 = super.emit("resume");
          this[MAYBE_EMIT_END]();
          return ret2;
        } else if (ev === "finish" || ev === "prefinish") {
          const ret2 = super.emit(ev);
          this.removeAllListeners(ev);
          return ret2;
        }
        const ret = super.emit(ev, ...args);
        this[MAYBE_EMIT_END]();
        return ret;
      }
      [EMITDATA](data) {
        for (const p of this[PIPES]) {
          if (p.dest.write(data) === false)
            this.pause();
        }
        const ret = this[DISCARDED] ? false : super.emit("data", data);
        this[MAYBE_EMIT_END]();
        return ret;
      }
      [EMITEND]() {
        if (this[EMITTED_END])
          return false;
        this[EMITTED_END] = true;
        this.readable = false;
        return this[ASYNC] ? (defer(() => this[EMITEND2]()), true) : this[EMITEND2]();
      }
      [EMITEND2]() {
        if (this[DECODER]) {
          const data = this[DECODER].end();
          if (data) {
            for (const p of this[PIPES]) {
              p.dest.write(data);
            }
            if (!this[DISCARDED])
              super.emit("data", data);
          }
        }
        for (const p of this[PIPES]) {
          p.end();
        }
        const ret = super.emit("end");
        this.removeAllListeners("end");
        return ret;
      }
      /**
       * Return a Promise that resolves to an array of all emitted data once
       * the stream ends.
       */
      async collect() {
        const buf = Object.assign([], {
          dataLength: 0
        });
        if (!this[OBJECTMODE])
          buf.dataLength = 0;
        const p = this.promise();
        this.on("data", (c3) => {
          buf.push(c3);
          if (!this[OBJECTMODE])
            buf.dataLength += c3.length;
        });
        await p;
        return buf;
      }
      /**
       * Return a Promise that resolves to the concatenation of all emitted data
       * once the stream ends.
       *
       * Not allowed on objectMode streams.
       */
      async concat() {
        if (this[OBJECTMODE]) {
          throw new Error("cannot concat in objectMode");
        }
        const buf = await this.collect();
        return this[ENCODING] ? buf.join("") : Buffer.concat(buf, buf.dataLength);
      }
      /**
       * Return a void Promise that resolves once the stream ends.
       */
      async promise() {
        return new Promise((resolve24, reject) => {
          this.on(DESTROYED, () => reject(new Error("stream destroyed")));
          this.on("error", (er) => reject(er));
          this.on("end", () => resolve24());
        });
      }
      /**
       * Asynchronous `for await of` iteration.
       *
       * This will continue emitting all chunks until the stream terminates.
       */
      [Symbol.asyncIterator]() {
        this[DISCARDED] = false;
        let stopped = false;
        const stop2 = /* @__PURE__ */ __name(async () => {
          this.pause();
          stopped = true;
          return { value: void 0, done: true };
        }, "stop");
        const next = /* @__PURE__ */ __name(() => {
          if (stopped)
            return stop2();
          const res = this.read();
          if (res !== null)
            return Promise.resolve({ done: false, value: res });
          if (this[EOF])
            return stop2();
          let resolve24;
          let reject;
          const onerr = /* @__PURE__ */ __name((er) => {
            this.off("data", ondata);
            this.off("end", onend);
            this.off(DESTROYED, ondestroy);
            stop2();
            reject(er);
          }, "onerr");
          const ondata = /* @__PURE__ */ __name((value) => {
            this.off("error", onerr);
            this.off("end", onend);
            this.off(DESTROYED, ondestroy);
            this.pause();
            resolve24({ value, done: !!this[EOF] });
          }, "ondata");
          const onend = /* @__PURE__ */ __name(() => {
            this.off("error", onerr);
            this.off("data", ondata);
            this.off(DESTROYED, ondestroy);
            stop2();
            resolve24({ done: true, value: void 0 });
          }, "onend");
          const ondestroy = /* @__PURE__ */ __name(() => onerr(new Error("stream destroyed")), "ondestroy");
          return new Promise((res2, rej) => {
            reject = rej;
            resolve24 = res2;
            this.once(DESTROYED, ondestroy);
            this.once("error", onerr);
            this.once("end", onend);
            this.once("data", ondata);
          });
        }, "next");
        return {
          next,
          throw: stop2,
          return: stop2,
          [Symbol.asyncIterator]() {
            return this;
          }
        };
      }
      /**
       * Synchronous `for of` iteration.
       *
       * The iteration will terminate when the internal buffer runs out, even
       * if the stream has not yet terminated.
       */
      [Symbol.iterator]() {
        this[DISCARDED] = false;
        let stopped = false;
        const stop2 = /* @__PURE__ */ __name(() => {
          this.pause();
          this.off(ERROR, stop2);
          this.off(DESTROYED, stop2);
          this.off("end", stop2);
          stopped = true;
          return { done: true, value: void 0 };
        }, "stop");
        const next = /* @__PURE__ */ __name(() => {
          if (stopped)
            return stop2();
          const value = this.read();
          return value === null ? stop2() : { done: false, value };
        }, "next");
        this.once("end", stop2);
        this.once(ERROR, stop2);
        this.once(DESTROYED, stop2);
        return {
          next,
          throw: stop2,
          return: stop2,
          [Symbol.iterator]() {
            return this;
          }
        };
      }
      /**
       * Destroy a stream, preventing it from being used for any further purpose.
       *
       * If the stream has a `close()` method, then it will be called on
       * destruction.
       *
       * After destruction, any attempt to write data, read data, or emit most
       * events will be ignored.
       *
       * If an error argument is provided, then it will be emitted in an
       * 'error' event.
       */
      destroy(er) {
        if (this[DESTROYED]) {
          if (er)
            this.emit("error", er);
          else
            this.emit(DESTROYED);
          return this;
        }
        this[DESTROYED] = true;
        this[DISCARDED] = true;
        this[BUFFER].length = 0;
        this[BUFFERLENGTH] = 0;
        const wc = this;
        if (typeof wc.close === "function" && !this[CLOSED])
          wc.close();
        if (er)
          this.emit("error", er);
        else
          this.emit(DESTROYED);
        return this;
      }
      /**
       * Alias for {@link isStream}
       *
       * Former export location, maintained for backwards compatibility.
       *
       * @deprecated
       */
      static get isStream() {
        return isStream;
      }
    };
  }
});

// node_modules/path-scurry/dist/esm/index.js
import { posix, win32 } from "node:path";
import { fileURLToPath as fileURLToPath3 } from "node:url";
import { lstatSync, readdir as readdirCB, readdirSync, readlinkSync, realpathSync as rps } from "fs";
import * as actualFS from "node:fs";
import { lstat, readdir as readdir2, readlink, realpath } from "node:fs/promises";
var realpathSync, defaultFS, fsFromOption, uncDriveRegexp, uncToDrive, eitherSep, UNKNOWN, IFIFO, IFCHR, IFDIR, IFBLK, IFREG, IFLNK, IFSOCK, IFMT, IFMT_UNKNOWN, READDIR_CALLED, LSTAT_CALLED, ENOTDIR, ENOENT, ENOREADLINK, ENOREALPATH, ENOCHILD, TYPEMASK, entToType, normalizeCache, normalize3, normalizeNocaseCache, normalizeNocase, ResolveCache, ChildrenCache, setAsCwd, PathBase, PathWin32, PathPosix, PathScurryBase, PathScurryWin32, PathScurryPosix, PathScurryDarwin, Path, PathScurry;
var init_esm8 = __esm({
  "node_modules/path-scurry/dist/esm/index.js"() {
    init_esbuild_shims();
    init_esm6();
    init_esm7();
    realpathSync = rps.native;
    defaultFS = {
      lstatSync,
      readdir: readdirCB,
      readdirSync,
      readlinkSync,
      realpathSync,
      promises: {
        lstat,
        readdir: readdir2,
        readlink,
        realpath
      }
    };
    fsFromOption = /* @__PURE__ */ __name((fsOption) => !fsOption || fsOption === defaultFS || fsOption === actualFS ? defaultFS : {
      ...defaultFS,
      ...fsOption,
      promises: {
        ...defaultFS.promises,
        ...fsOption.promises || {}
      }
    }, "fsFromOption");
    uncDriveRegexp = /^\\\\\?\\([a-z]:)\\?$/i;
    uncToDrive = /* @__PURE__ */ __name((rootPath) => rootPath.replace(/\//g, "\\").replace(uncDriveRegexp, "$1\\"), "uncToDrive");
    eitherSep = /[\\\/]/;
    UNKNOWN = 0;
    IFIFO = 1;
    IFCHR = 2;
    IFDIR = 4;
    IFBLK = 6;
    IFREG = 8;
    IFLNK = 10;
    IFSOCK = 12;
    IFMT = 15;
    IFMT_UNKNOWN = ~IFMT;
    READDIR_CALLED = 16;
    LSTAT_CALLED = 32;
    ENOTDIR = 64;
    ENOENT = 128;
    ENOREADLINK = 256;
    ENOREALPATH = 512;
    ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH;
    TYPEMASK = 1023;
    entToType = /* @__PURE__ */ __name((s2) => s2.isFile() ? IFREG : s2.isDirectory() ? IFDIR : s2.isSymbolicLink() ? IFLNK : s2.isCharacterDevice() ? IFCHR : s2.isBlockDevice() ? IFBLK : s2.isSocket() ? IFSOCK : s2.isFIFO() ? IFIFO : UNKNOWN, "entToType");
    normalizeCache = /* @__PURE__ */ new Map();
    normalize3 = /* @__PURE__ */ __name((s2) => {
      const c3 = normalizeCache.get(s2);
      if (c3)
        return c3;
      const n2 = s2.normalize("NFKD");
      normalizeCache.set(s2, n2);
      return n2;
    }, "normalize");
    normalizeNocaseCache = /* @__PURE__ */ new Map();
    normalizeNocase = /* @__PURE__ */ __name((s2) => {
      const c3 = normalizeNocaseCache.get(s2);
      if (c3)
        return c3;
      const n2 = normalize3(s2.toLowerCase());
      normalizeNocaseCache.set(s2, n2);
      return n2;
    }, "normalizeNocase");
    ResolveCache = class extends LRUCache {
      static {
        __name(this, "ResolveCache");
      }
      constructor() {
        super({ max: 256 });
      }
    };
    ChildrenCache = class extends LRUCache {
      static {
        __name(this, "ChildrenCache");
      }
      constructor(maxSize = 16 * 1024) {
        super({
          maxSize,
          // parent + children
          sizeCalculation: /* @__PURE__ */ __name((a) => a.length + 1, "sizeCalculation")
        });
      }
    };
    setAsCwd = Symbol("PathScurry setAsCwd");
    PathBase = class {
      static {
        __name(this, "PathBase");
      }
      /**
       * the basename of this path
       *
       * **Important**: *always* test the path name against any test string
       * usingthe {@link isNamed} method, and not by directly comparing this
       * string. Otherwise, unicode path strings that the system sees as identical
       * will not be properly treated as the same path, leading to incorrect
       * behavior and possible security issues.
       */
      name;
      /**
       * the Path entry corresponding to the path root.
       *
       * @internal
       */
      root;
      /**
       * All roots found within the current PathScurry family
       *
       * @internal
       */
      roots;
      /**
       * a reference to the parent path, or undefined in the case of root entries
       *
       * @internal
       */
      parent;
      /**
       * boolean indicating whether paths are compared case-insensitively
       * @internal
       */
      nocase;
      /**
       * boolean indicating that this path is the current working directory
       * of the PathScurry collection that contains it.
       */
      isCWD = false;
      // potential default fs override
      #fs;
      // Stats fields
      #dev;
      get dev() {
        return this.#dev;
      }
      #mode;
      get mode() {
        return this.#mode;
      }
      #nlink;
      get nlink() {
        return this.#nlink;
      }
      #uid;
      get uid() {
        return this.#uid;
      }
      #gid;
      get gid() {
        return this.#gid;
      }
      #rdev;
      get rdev() {
        return this.#rdev;
      }
      #blksize;
      get blksize() {
        return this.#blksize;
      }
      #ino;
      get ino() {
        return this.#ino;
      }
      #size;
      get size() {
        return this.#size;
      }
      #blocks;
      get blocks() {
        return this.#blocks;
      }
      #atimeMs;
      get atimeMs() {
        return this.#atimeMs;
      }
      #mtimeMs;
      get mtimeMs() {
        return this.#mtimeMs;
      }
      #ctimeMs;
      get ctimeMs() {
        return this.#ctimeMs;
      }
      #birthtimeMs;
      get birthtimeMs() {
        return this.#birthtimeMs;
      }
      #atime;
      get atime() {
        return this.#atime;
      }
      #mtime;
      get mtime() {
        return this.#mtime;
      }
      #ctime;
      get ctime() {
        return this.#ctime;
      }
      #birthtime;
      get birthtime() {
        return this.#birthtime;
      }
      #matchName;
      #depth;
      #fullpath;
      #fullpathPosix;
      #relative;
      #relativePosix;
      #type;
      #children;
      #linkTarget;
      #realpath;
      /**
       * This property is for compatibility with the Dirent class as of
       * Node v20, where Dirent['parentPath'] refers to the path of the
       * directory that was passed to readdir. For root entries, it's the path
       * to the entry itself.
       */
      get parentPath() {
        return (this.parent || this).fullpath();
      }
      /**
       * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,
       * this property refers to the *parent* path, not the path object itself.
       */
      get path() {
        return this.parentPath;
      }
      /**
       * Do not create new Path objects directly.  They should always be accessed
       * via the PathScurry class or other methods on the Path class.
       *
       * @internal
       */
      constructor(name3, type = UNKNOWN, root, roots, nocase, children, opts) {
        this.name = name3;
        this.#matchName = nocase ? normalizeNocase(name3) : normalize3(name3);
        this.#type = type & TYPEMASK;
        this.nocase = nocase;
        this.roots = roots;
        this.root = root || this;
        this.#children = children;
        this.#fullpath = opts.fullpath;
        this.#relative = opts.relative;
        this.#relativePosix = opts.relativePosix;
        this.parent = opts.parent;
        if (this.parent) {
          this.#fs = this.parent.#fs;
        } else {
          this.#fs = fsFromOption(opts.fs);
        }
      }
      /**
       * Returns the depth of the Path object from its root.
       *
       * For example, a path at `/foo/bar` would have a depth of 2.
       */
      depth() {
        if (this.#depth !== void 0)
          return this.#depth;
        if (!this.parent)
          return this.#depth = 0;
        return this.#depth = this.parent.depth() + 1;
      }
      /**
       * @internal
       */
      childrenCache() {
        return this.#children;
      }
      /**
       * Get the Path object referenced by the string path, resolved from this Path
       */
      resolve(path108) {
        if (!path108) {
          return this;
        }
        const rootPath = this.getRootString(path108);
        const dir = path108.substring(rootPath.length);
        const dirParts = dir.split(this.splitSep);
        const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
        return result;
      }
      #resolveParts(dirParts) {
        let p = this;
        for (const part of dirParts) {
          p = p.child(part);
        }
        return p;
      }
      /**
       * Returns the cached children Path objects, if still available.  If they
       * have fallen out of the cache, then returns an empty array, and resets the
       * READDIR_CALLED bit, so that future calls to readdir() will require an fs
       * lookup.
       *
       * @internal
       */
      children() {
        const cached = this.#children.get(this);
        if (cached) {
          return cached;
        }
        const children = Object.assign([], { provisional: 0 });
        this.#children.set(this, children);
        this.#type &= ~READDIR_CALLED;
        return children;
      }
      /**
       * Resolves a path portion and returns or creates the child Path.
       *
       * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is
       * `'..'`.
       *
       * This should not be called directly.  If `pathPart` contains any path
       * separators, it will lead to unsafe undefined behavior.
       *
       * Use `Path.resolve()` instead.
       *
       * @internal
       */
      child(pathPart, opts) {
        if (pathPart === "" || pathPart === ".") {
          return this;
        }
        if (pathPart === "..") {
          return this.parent || this;
        }
        const children = this.children();
        const name3 = this.nocase ? normalizeNocase(pathPart) : normalize3(pathPart);
        for (const p of children) {
          if (p.#matchName === name3) {
            return p;
          }
        }
        const s2 = this.parent ? this.sep : "";
        const fullpath = this.#fullpath ? this.#fullpath + s2 + pathPart : void 0;
        const pchild = this.newChild(pathPart, UNKNOWN, {
          ...opts,
          parent: this,
          fullpath
        });
        if (!this.canReaddir()) {
          pchild.#type |= ENOENT;
        }
        children.push(pchild);
        return pchild;
      }
      /**
       * The relative path from the cwd. If it does not share an ancestor with
       * the cwd, then this ends up being equivalent to the fullpath()
       */
      relative() {
        if (this.isCWD)
          return "";
        if (this.#relative !== void 0) {
          return this.#relative;
        }
        const name3 = this.name;
        const p = this.parent;
        if (!p) {
          return this.#relative = this.name;
        }
        const pv = p.relative();
        return pv + (!pv || !p.parent ? "" : this.sep) + name3;
      }
      /**
       * The relative path from the cwd, using / as the path separator.
       * If it does not share an ancestor with
       * the cwd, then this ends up being equivalent to the fullpathPosix()
       * On posix systems, this is identical to relative().
       */
      relativePosix() {
        if (this.sep === "/")
          return this.relative();
        if (this.isCWD)
          return "";
        if (this.#relativePosix !== void 0)
          return this.#relativePosix;
        const name3 = this.name;
        const p = this.parent;
        if (!p) {
          return this.#relativePosix = this.fullpathPosix();
        }
        const pv = p.relativePosix();
        return pv + (!pv || !p.parent ? "" : "/") + name3;
      }
      /**
       * The fully resolved path string for this Path entry
       */
      fullpath() {
        if (this.#fullpath !== void 0) {
          return this.#fullpath;
        }
        const name3 = this.name;
        const p = this.parent;
        if (!p) {
          return this.#fullpath = this.name;
        }
        const pv = p.fullpath();
        const fp = pv + (!p.parent ? "" : this.sep) + name3;
        return this.#fullpath = fp;
      }
      /**
       * On platforms other than windows, this is identical to fullpath.
       *
       * On windows, this is overridden to return the forward-slash form of the
       * full UNC path.
       */
      fullpathPosix() {
        if (this.#fullpathPosix !== void 0)
          return this.#fullpathPosix;
        if (this.sep === "/")
          return this.#fullpathPosix = this.fullpath();
        if (!this.parent) {
          const p2 = this.fullpath().replace(/\\/g, "/");
          if (/^[a-z]:\//i.test(p2)) {
            return this.#fullpathPosix = `//?/${p2}`;
          } else {
            return this.#fullpathPosix = p2;
          }
        }
        const p = this.parent;
        const pfpp = p.fullpathPosix();
        const fpp = pfpp + (!pfpp || !p.parent ? "" : "/") + this.name;
        return this.#fullpathPosix = fpp;
      }
      /**
       * Is the Path of an unknown type?
       *
       * Note that we might know *something* about it if there has been a previous
       * filesystem operation, for example that it does not exist, or is not a
       * link, or whether it has child entries.
       */
      isUnknown() {
        return (this.#type & IFMT) === UNKNOWN;
      }
      isType(type) {
        return this[`is${type}`]();
      }
      getType() {
        return this.isUnknown() ? "Unknown" : this.isDirectory() ? "Directory" : this.isFile() ? "File" : this.isSymbolicLink() ? "SymbolicLink" : this.isFIFO() ? "FIFO" : this.isCharacterDevice() ? "CharacterDevice" : this.isBlockDevice() ? "BlockDevice" : (
          /* c8 ignore start */
          this.isSocket() ? "Socket" : "Unknown"
        );
      }
      /**
       * Is the Path a regular file?
       */
      isFile() {
        return (this.#type & IFMT) === IFREG;
      }
      /**
       * Is the Path a directory?
       */
      isDirectory() {
        return (this.#type & IFMT) === IFDIR;
      }
      /**
       * Is the path a character device?
       */
      isCharacterDevice() {
        return (this.#type & IFMT) === IFCHR;
      }
      /**
       * Is the path a block device?
       */
      isBlockDevice() {
        return (this.#type & IFMT) === IFBLK;
      }
      /**
       * Is the path a FIFO pipe?
       */
      isFIFO() {
        return (this.#type & IFMT) === IFIFO;
      }
      /**
       * Is the path a socket?
       */
      isSocket() {
        return (this.#type & IFMT) === IFSOCK;
      }
      /**
       * Is the path a symbolic link?
       */
      isSymbolicLink() {
        return (this.#type & IFLNK) === IFLNK;
      }
      /**
       * Return the entry if it has been subject of a successful lstat, or
       * undefined otherwise.
       *
       * Does not read the filesystem, so an undefined result *could* simply
       * mean that we haven't called lstat on it.
       */
      lstatCached() {
        return this.#type & LSTAT_CALLED ? this : void 0;
      }
      /**
       * Return the cached link target if the entry has been the subject of a
       * successful readlink, or undefined otherwise.
       *
       * Does not read the filesystem, so an undefined result *could* just mean we
       * don't have any cached data. Only use it if you are very sure that a
       * readlink() has been called at some point.
       */
      readlinkCached() {
        return this.#linkTarget;
      }
      /**
       * Returns the cached realpath target if the entry has been the subject
       * of a successful realpath, or undefined otherwise.
       *
       * Does not read the filesystem, so an undefined result *could* just mean we
       * don't have any cached data. Only use it if you are very sure that a
       * realpath() has been called at some point.
       */
      realpathCached() {
        return this.#realpath;
      }
      /**
       * Returns the cached child Path entries array if the entry has been the
       * subject of a successful readdir(), or [] otherwise.
       *
       * Does not read the filesystem, so an empty array *could* just mean we
       * don't have any cached data. Only use it if you are very sure that a
       * readdir() has been called recently enough to still be valid.
       */
      readdirCached() {
        const children = this.children();
        return children.slice(0, children.provisional);
      }
      /**
       * Return true if it's worth trying to readlink.  Ie, we don't (yet) have
       * any indication that readlink will definitely fail.
       *
       * Returns false if the path is known to not be a symlink, if a previous
       * readlink failed, or if the entry does not exist.
       */
      canReadlink() {
        if (this.#linkTarget)
          return true;
        if (!this.parent)
          return false;
        const ifmt = this.#type & IFMT;
        return !(ifmt !== UNKNOWN && ifmt !== IFLNK || this.#type & ENOREADLINK || this.#type & ENOENT);
      }
      /**
       * Return true if readdir has previously been successfully called on this
       * path, indicating that cachedReaddir() is likely valid.
       */
      calledReaddir() {
        return !!(this.#type & READDIR_CALLED);
      }
      /**
       * Returns true if the path is known to not exist. That is, a previous lstat
       * or readdir failed to verify its existence when that would have been
       * expected, or a parent entry was marked either enoent or enotdir.
       */
      isENOENT() {
        return !!(this.#type & ENOENT);
      }
      /**
       * Return true if the path is a match for the given path name.  This handles
       * case sensitivity and unicode normalization.
       *
       * Note: even on case-sensitive systems, it is **not** safe to test the
       * equality of the `.name` property to determine whether a given pathname
       * matches, due to unicode normalization mismatches.
       *
       * Always use this method instead of testing the `path.name` property
       * directly.
       */
      isNamed(n2) {
        return !this.nocase ? this.#matchName === normalize3(n2) : this.#matchName === normalizeNocase(n2);
      }
      /**
       * Return the Path object corresponding to the target of a symbolic link.
       *
       * If the Path is not a symbolic link, or if the readlink call fails for any
       * reason, `undefined` is returned.
       *
       * Result is cached, and thus may be outdated if the filesystem is mutated.
       */
      async readlink() {
        const target = this.#linkTarget;
        if (target) {
          return target;
        }
        if (!this.canReadlink()) {
          return void 0;
        }
        if (!this.parent) {
          return void 0;
        }
        try {
          const read2 = await this.#fs.promises.readlink(this.fullpath());
          const linkTarget = (await this.parent.realpath())?.resolve(read2);
          if (linkTarget) {
            return this.#linkTarget = linkTarget;
          }
        } catch (er) {
          this.#readlinkFail(er.code);
          return void 0;
        }
      }
      /**
       * Synchronous {@link PathBase.readlink}
       */
      readlinkSync() {
        const target = this.#linkTarget;
        if (target) {
          return target;
        }
        if (!this.canReadlink()) {
          return void 0;
        }
        if (!this.parent) {
          return void 0;
        }
        try {
          const read2 = this.#fs.readlinkSync(this.fullpath());
          const linkTarget = this.parent.realpathSync()?.resolve(read2);
          if (linkTarget) {
            return this.#linkTarget = linkTarget;
          }
        } catch (er) {
          this.#readlinkFail(er.code);
          return void 0;
        }
      }
      #readdirSuccess(children) {
        this.#type |= READDIR_CALLED;
        for (let p = children.provisional; p < children.length; p++) {
          const c3 = children[p];
          if (c3)
            c3.#markENOENT();
        }
      }
      #markENOENT() {
        if (this.#type & ENOENT)
          return;
        this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN;
        this.#markChildrenENOENT();
      }
      #markChildrenENOENT() {
        const children = this.children();
        children.provisional = 0;
        for (const p of children) {
          p.#markENOENT();
        }
      }
      #markENOREALPATH() {
        this.#type |= ENOREALPATH;
        this.#markENOTDIR();
      }
      // save the information when we know the entry is not a dir
      #markENOTDIR() {
        if (this.#type & ENOTDIR)
          return;
        let t2 = this.#type;
        if ((t2 & IFMT) === IFDIR)
          t2 &= IFMT_UNKNOWN;
        this.#type = t2 | ENOTDIR;
        this.#markChildrenENOENT();
      }
      #readdirFail(code2 = "") {
        if (code2 === "ENOTDIR" || code2 === "EPERM") {
          this.#markENOTDIR();
        } else if (code2 === "ENOENT") {
          this.#markENOENT();
        } else {
          this.children().provisional = 0;
        }
      }
      #lstatFail(code2 = "") {
        if (code2 === "ENOTDIR") {
          const p = this.parent;
          p.#markENOTDIR();
        } else if (code2 === "ENOENT") {
          this.#markENOENT();
        }
      }
      #readlinkFail(code2 = "") {
        let ter = this.#type;
        ter |= ENOREADLINK;
        if (code2 === "ENOENT")
          ter |= ENOENT;
        if (code2 === "EINVAL" || code2 === "UNKNOWN") {
          ter &= IFMT_UNKNOWN;
        }
        this.#type = ter;
        if (code2 === "ENOTDIR" && this.parent) {
          this.parent.#markENOTDIR();
        }
      }
      #readdirAddChild(e2, c3) {
        return this.#readdirMaybePromoteChild(e2, c3) || this.#readdirAddNewChild(e2, c3);
      }
      #readdirAddNewChild(e2, c3) {
        const type = entToType(e2);
        const child = this.newChild(e2.name, type, { parent: this });
        const ifmt = child.#type & IFMT;
        if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {
          child.#type |= ENOTDIR;
        }
        c3.unshift(child);
        c3.provisional++;
        return child;
      }
      #readdirMaybePromoteChild(e2, c3) {
        for (let p = c3.provisional; p < c3.length; p++) {
          const pchild = c3[p];
          const name3 = this.nocase ? normalizeNocase(e2.name) : normalize3(e2.name);
          if (name3 !== pchild.#matchName) {
            continue;
          }
          return this.#readdirPromoteChild(e2, pchild, p, c3);
        }
      }
      #readdirPromoteChild(e2, p, index, c3) {
        const v = p.name;
        p.#type = p.#type & IFMT_UNKNOWN | entToType(e2);
        if (v !== e2.name)
          p.name = e2.name;
        if (index !== c3.provisional) {
          if (index === c3.length - 1)
            c3.pop();
          else
            c3.splice(index, 1);
          c3.unshift(p);
        }
        c3.provisional++;
        return p;
      }
      /**
       * Call lstat() on this Path, and update all known information that can be
       * determined.
       *
       * Note that unlike `fs.lstat()`, the returned value does not contain some
       * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that
       * information is required, you will need to call `fs.lstat` yourself.
       *
       * If the Path refers to a nonexistent file, or if the lstat call fails for
       * any reason, `undefined` is returned.  Otherwise the updated Path object is
       * returned.
       *
       * Results are cached, and thus may be out of date if the filesystem is
       * mutated.
       */
      async lstat() {
        if ((this.#type & ENOENT) === 0) {
          try {
            this.#applyStat(await this.#fs.promises.lstat(this.fullpath()));
            return this;
          } catch (er) {
            this.#lstatFail(er.code);
          }
        }
      }
      /**
       * synchronous {@link PathBase.lstat}
       */
      lstatSync() {
        if ((this.#type & ENOENT) === 0) {
          try {
            this.#applyStat(this.#fs.lstatSync(this.fullpath()));
            return this;
          } catch (er) {
            this.#lstatFail(er.code);
          }
        }
      }
      #applyStat(st) {
        const { atime, atimeMs, birthtime, birthtimeMs, blksize, blocks, ctime, ctimeMs, dev, gid, ino, mode, mtime, mtimeMs, nlink, rdev, size, uid } = st;
        this.#atime = atime;
        this.#atimeMs = atimeMs;
        this.#birthtime = birthtime;
        this.#birthtimeMs = birthtimeMs;
        this.#blksize = blksize;
        this.#blocks = blocks;
        this.#ctime = ctime;
        this.#ctimeMs = ctimeMs;
        this.#dev = dev;
        this.#gid = gid;
        this.#ino = ino;
        this.#mode = mode;
        this.#mtime = mtime;
        this.#mtimeMs = mtimeMs;
        this.#nlink = nlink;
        this.#rdev = rdev;
        this.#size = size;
        this.#uid = uid;
        const ifmt = entToType(st);
        this.#type = this.#type & IFMT_UNKNOWN | ifmt | LSTAT_CALLED;
        if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {
          this.#type |= ENOTDIR;
        }
      }
      #onReaddirCB = [];
      #readdirCBInFlight = false;
      #callOnReaddirCB(children) {
        this.#readdirCBInFlight = false;
        const cbs = this.#onReaddirCB.slice();
        this.#onReaddirCB.length = 0;
        cbs.forEach((cb) => cb(null, children));
      }
      /**
       * Standard node-style callback interface to get list of directory entries.
       *
       * If the Path cannot or does not contain any children, then an empty array
       * is returned.
       *
       * Results are cached, and thus may be out of date if the filesystem is
       * mutated.
       *
       * @param cb The callback called with (er, entries).  Note that the `er`
       * param is somewhat extraneous, as all readdir() errors are handled and
       * simply result in an empty set of entries being returned.
       * @param allowZalgo Boolean indicating that immediately known results should
       * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release
       * zalgo at your peril, the dark pony lord is devious and unforgiving.
       */
      readdirCB(cb, allowZalgo = false) {
        if (!this.canReaddir()) {
          if (allowZalgo)
            cb(null, []);
          else
            queueMicrotask(() => cb(null, []));
          return;
        }
        const children = this.children();
        if (this.calledReaddir()) {
          const c3 = children.slice(0, children.provisional);
          if (allowZalgo)
            cb(null, c3);
          else
            queueMicrotask(() => cb(null, c3));
          return;
        }
        this.#onReaddirCB.push(cb);
        if (this.#readdirCBInFlight) {
          return;
        }
        this.#readdirCBInFlight = true;
        const fullpath = this.fullpath();
        this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {
          if (er) {
            this.#readdirFail(er.code);
            children.provisional = 0;
          } else {
            for (const e2 of entries) {
              this.#readdirAddChild(e2, children);
            }
            this.#readdirSuccess(children);
          }
          this.#callOnReaddirCB(children.slice(0, children.provisional));
          return;
        });
      }
      #asyncReaddirInFlight;
      /**
       * Return an array of known child entries.
       *
       * If the Path cannot or does not contain any children, then an empty array
       * is returned.
       *
       * Results are cached, and thus may be out of date if the filesystem is
       * mutated.
       */
      async readdir() {
        if (!this.canReaddir()) {
          return [];
        }
        const children = this.children();
        if (this.calledReaddir()) {
          return children.slice(0, children.provisional);
        }
        const fullpath = this.fullpath();
        if (this.#asyncReaddirInFlight) {
          await this.#asyncReaddirInFlight;
        } else {
          let resolve24 = /* @__PURE__ */ __name(() => {
          }, "resolve");
          this.#asyncReaddirInFlight = new Promise((res) => resolve24 = res);
          try {
            for (const e2 of await this.#fs.promises.readdir(fullpath, {
              withFileTypes: true
            })) {
              this.#readdirAddChild(e2, children);
            }
            this.#readdirSuccess(children);
          } catch (er) {
            this.#readdirFail(er.code);
            children.provisional = 0;
          }
          this.#asyncReaddirInFlight = void 0;
          resolve24();
        }
        return children.slice(0, children.provisional);
      }
      /**
       * synchronous {@link PathBase.readdir}
       */
      readdirSync() {
        if (!this.canReaddir()) {
          return [];
        }
        const children = this.children();
        if (this.calledReaddir()) {
          return children.slice(0, children.provisional);
        }
        const fullpath = this.fullpath();
        try {
          for (const e2 of this.#fs.readdirSync(fullpath, {
            withFileTypes: true
          })) {
            this.#readdirAddChild(e2, children);
          }
          this.#readdirSuccess(children);
        } catch (er) {
          this.#readdirFail(er.code);
          children.provisional = 0;
        }
        return children.slice(0, children.provisional);
      }
      canReaddir() {
        if (this.#type & ENOCHILD)
          return false;
        const ifmt = IFMT & this.#type;
        if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {
          return false;
        }
        return true;
      }
      shouldWalk(dirs, walkFilter) {
        return (this.#type & IFDIR) === IFDIR && !(this.#type & ENOCHILD) && !dirs.has(this) && (!walkFilter || walkFilter(this));
      }
      /**
       * Return the Path object corresponding to path as resolved
       * by realpath(3).
       *
       * If the realpath call fails for any reason, `undefined` is returned.
       *
       * Result is cached, and thus may be outdated if the filesystem is mutated.
       * On success, returns a Path object.
       */
      async realpath() {
        if (this.#realpath)
          return this.#realpath;
        if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type)
          return void 0;
        try {
          const rp = await this.#fs.promises.realpath(this.fullpath());
          return this.#realpath = this.resolve(rp);
        } catch (_) {
          this.#markENOREALPATH();
        }
      }
      /**
       * Synchronous {@link realpath}
       */
      realpathSync() {
        if (this.#realpath)
          return this.#realpath;
        if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type)
          return void 0;
        try {
          const rp = this.#fs.realpathSync(this.fullpath());
          return this.#realpath = this.resolve(rp);
        } catch (_) {
          this.#markENOREALPATH();
        }
      }
      /**
       * Internal method to mark this Path object as the scurry cwd,
       * called by {@link PathScurry#chdir}
       *
       * @internal
       */
      [setAsCwd](oldCwd) {
        if (oldCwd === this)
          return;
        oldCwd.isCWD = false;
        this.isCWD = true;
        const changed = /* @__PURE__ */ new Set([]);
        let rp = [];
        let p = this;
        while (p && p.parent) {
          changed.add(p);
          p.#relative = rp.join(this.sep);
          p.#relativePosix = rp.join("/");
          p = p.parent;
          rp.push("..");
        }
        p = oldCwd;
        while (p && p.parent && !changed.has(p)) {
          p.#relative = void 0;
          p.#relativePosix = void 0;
          p = p.parent;
        }
      }
    };
    PathWin32 = class _PathWin32 extends PathBase {
      static {
        __name(this, "PathWin32");
      }
      /**
       * Separator for generating path strings.
       */
      sep = "\\";
      /**
       * Separator for parsing path strings.
       */
      splitSep = eitherSep;
      /**
       * Do not create new Path objects directly.  They should always be accessed
       * via the PathScurry class or other methods on the Path class.
       *
       * @internal
       */
      constructor(name3, type = UNKNOWN, root, roots, nocase, children, opts) {
        super(name3, type, root, roots, nocase, children, opts);
      }
      /**
       * @internal
       */
      newChild(name3, type = UNKNOWN, opts = {}) {
        return new _PathWin32(name3, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
      }
      /**
       * @internal
       */
      getRootString(path108) {
        return win32.parse(path108).root;
      }
      /**
       * @internal
       */
      getRoot(rootPath) {
        rootPath = uncToDrive(rootPath.toUpperCase());
        if (rootPath === this.root.name) {
          return this.root;
        }
        for (const [compare, root] of Object.entries(this.roots)) {
          if (this.sameRoot(rootPath, compare)) {
            return this.roots[rootPath] = root;
          }
        }
        return this.roots[rootPath] = new PathScurryWin32(rootPath, this).root;
      }
      /**
       * @internal
       */
      sameRoot(rootPath, compare = this.root.name) {
        rootPath = rootPath.toUpperCase().replace(/\//g, "\\").replace(uncDriveRegexp, "$1\\");
        return rootPath === compare;
      }
    };
    PathPosix = class _PathPosix extends PathBase {
      static {
        __name(this, "PathPosix");
      }
      /**
       * separator for parsing path strings
       */
      splitSep = "/";
      /**
       * separator for generating path strings
       */
      sep = "/";
      /**
       * Do not create new Path objects directly.  They should always be accessed
       * via the PathScurry class or other methods on the Path class.
       *
       * @internal
       */
      constructor(name3, type = UNKNOWN, root, roots, nocase, children, opts) {
        super(name3, type, root, roots, nocase, children, opts);
      }
      /**
       * @internal
       */
      getRootString(path108) {
        return path108.startsWith("/") ? "/" : "";
      }
      /**
       * @internal
       */
      getRoot(_rootPath) {
        return this.root;
      }
      /**
       * @internal
       */
      newChild(name3, type = UNKNOWN, opts = {}) {
        return new _PathPosix(name3, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
      }
    };
    PathScurryBase = class {
      static {
        __name(this, "PathScurryBase");
      }
      /**
       * The root Path entry for the current working directory of this Scurry
       */
      root;
      /**
       * The string path for the root of this Scurry's current working directory
       */
      rootPath;
      /**
       * A collection of all roots encountered, referenced by rootPath
       */
      roots;
      /**
       * The Path entry corresponding to this PathScurry's current working directory.
       */
      cwd;
      #resolveCache;
      #resolvePosixCache;
      #children;
      /**
       * Perform path comparisons case-insensitively.
       *
       * Defaults true on Darwin and Windows systems, false elsewhere.
       */
      nocase;
      #fs;
      /**
       * This class should not be instantiated directly.
       *
       * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry
       *
       * @internal
       */
      constructor(cwd7 = process.cwd(), pathImpl, sep7, { nocase, childrenCacheSize = 16 * 1024, fs: fs95 = defaultFS } = {}) {
        this.#fs = fsFromOption(fs95);
        if (cwd7 instanceof URL || cwd7.startsWith("file://")) {
          cwd7 = fileURLToPath3(cwd7);
        }
        const cwdPath = pathImpl.resolve(cwd7);
        this.roots = /* @__PURE__ */ Object.create(null);
        this.rootPath = this.parseRootPath(cwdPath);
        this.#resolveCache = new ResolveCache();
        this.#resolvePosixCache = new ResolveCache();
        this.#children = new ChildrenCache(childrenCacheSize);
        const split = cwdPath.substring(this.rootPath.length).split(sep7);
        if (split.length === 1 && !split[0]) {
          split.pop();
        }
        if (nocase === void 0) {
          throw new TypeError("must provide nocase setting to PathScurryBase ctor");
        }
        this.nocase = nocase;
        this.root = this.newRoot(this.#fs);
        this.roots[this.rootPath] = this.root;
        let prev = this.root;
        let len = split.length - 1;
        const joinSep = pathImpl.sep;
        let abs = this.rootPath;
        let sawFirst = false;
        for (const part of split) {
          const l2 = len--;
          prev = prev.child(part, {
            relative: new Array(l2).fill("..").join(joinSep),
            relativePosix: new Array(l2).fill("..").join("/"),
            fullpath: abs += (sawFirst ? "" : joinSep) + part
          });
          sawFirst = true;
        }
        this.cwd = prev;
      }
      /**
       * Get the depth of a provided path, string, or the cwd
       */
      depth(path108 = this.cwd) {
        if (typeof path108 === "string") {
          path108 = this.cwd.resolve(path108);
        }
        return path108.depth();
      }
      /**
       * Return the cache of child entries.  Exposed so subclasses can create
       * child Path objects in a platform-specific way.
       *
       * @internal
       */
      childrenCache() {
        return this.#children;
      }
      /**
       * Resolve one or more path strings to a resolved string
       *
       * Same interface as require('path').resolve.
       *
       * Much faster than path.resolve() when called multiple times for the same
       * path, because the resolved Path objects are cached.  Much slower
       * otherwise.
       */
      resolve(...paths) {
        let r3 = "";
        for (let i = paths.length - 1; i >= 0; i--) {
          const p = paths[i];
          if (!p || p === ".")
            continue;
          r3 = r3 ? `${p}/${r3}` : p;
          if (this.isAbsolute(p)) {
            break;
          }
        }
        const cached = this.#resolveCache.get(r3);
        if (cached !== void 0) {
          return cached;
        }
        const result = this.cwd.resolve(r3).fullpath();
        this.#resolveCache.set(r3, result);
        return result;
      }
      /**
       * Resolve one or more path strings to a resolved string, returning
       * the posix path.  Identical to .resolve() on posix systems, but on
       * windows will return a forward-slash separated UNC path.
       *
       * Same interface as require('path').resolve.
       *
       * Much faster than path.resolve() when called multiple times for the same
       * path, because the resolved Path objects are cached.  Much slower
       * otherwise.
       */
      resolvePosix(...paths) {
        let r3 = "";
        for (let i = paths.length - 1; i >= 0; i--) {
          const p = paths[i];
          if (!p || p === ".")
            continue;
          r3 = r3 ? `${p}/${r3}` : p;
          if (this.isAbsolute(p)) {
            break;
          }
        }
        const cached = this.#resolvePosixCache.get(r3);
        if (cached !== void 0) {
          return cached;
        }
        const result = this.cwd.resolve(r3).fullpathPosix();
        this.#resolvePosixCache.set(r3, result);
        return result;
      }
      /**
       * find the relative path from the cwd to the supplied path string or entry
       */
      relative(entry = this.cwd) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        }
        return entry.relative();
      }
      /**
       * find the relative path from the cwd to the supplied path string or
       * entry, using / as the path delimiter, even on Windows.
       */
      relativePosix(entry = this.cwd) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        }
        return entry.relativePosix();
      }
      /**
       * Return the basename for the provided string or Path object
       */
      basename(entry = this.cwd) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        }
        return entry.name;
      }
      /**
       * Return the dirname for the provided string or Path object
       */
      dirname(entry = this.cwd) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        }
        return (entry.parent || entry).fullpath();
      }
      async readdir(entry = this.cwd, opts = {
        withFileTypes: true
      }) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        } else if (!(entry instanceof PathBase)) {
          opts = entry;
          entry = this.cwd;
        }
        const { withFileTypes } = opts;
        if (!entry.canReaddir()) {
          return [];
        } else {
          const p = await entry.readdir();
          return withFileTypes ? p : p.map((e2) => e2.name);
        }
      }
      readdirSync(entry = this.cwd, opts = {
        withFileTypes: true
      }) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        } else if (!(entry instanceof PathBase)) {
          opts = entry;
          entry = this.cwd;
        }
        const { withFileTypes = true } = opts;
        if (!entry.canReaddir()) {
          return [];
        } else if (withFileTypes) {
          return entry.readdirSync();
        } else {
          return entry.readdirSync().map((e2) => e2.name);
        }
      }
      /**
       * Call lstat() on the string or Path object, and update all known
       * information that can be determined.
       *
       * Note that unlike `fs.lstat()`, the returned value does not contain some
       * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that
       * information is required, you will need to call `fs.lstat` yourself.
       *
       * If the Path refers to a nonexistent file, or if the lstat call fails for
       * any reason, `undefined` is returned.  Otherwise the updated Path object is
       * returned.
       *
       * Results are cached, and thus may be out of date if the filesystem is
       * mutated.
       */
      async lstat(entry = this.cwd) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        }
        return entry.lstat();
      }
      /**
       * synchronous {@link PathScurryBase.lstat}
       */
      lstatSync(entry = this.cwd) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        }
        return entry.lstatSync();
      }
      async readlink(entry = this.cwd, { withFileTypes } = {
        withFileTypes: false
      }) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        } else if (!(entry instanceof PathBase)) {
          withFileTypes = entry.withFileTypes;
          entry = this.cwd;
        }
        const e2 = await entry.readlink();
        return withFileTypes ? e2 : e2?.fullpath();
      }
      readlinkSync(entry = this.cwd, { withFileTypes } = {
        withFileTypes: false
      }) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        } else if (!(entry instanceof PathBase)) {
          withFileTypes = entry.withFileTypes;
          entry = this.cwd;
        }
        const e2 = entry.readlinkSync();
        return withFileTypes ? e2 : e2?.fullpath();
      }
      async realpath(entry = this.cwd, { withFileTypes } = {
        withFileTypes: false
      }) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        } else if (!(entry instanceof PathBase)) {
          withFileTypes = entry.withFileTypes;
          entry = this.cwd;
        }
        const e2 = await entry.realpath();
        return withFileTypes ? e2 : e2?.fullpath();
      }
      realpathSync(entry = this.cwd, { withFileTypes } = {
        withFileTypes: false
      }) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        } else if (!(entry instanceof PathBase)) {
          withFileTypes = entry.withFileTypes;
          entry = this.cwd;
        }
        const e2 = entry.realpathSync();
        return withFileTypes ? e2 : e2?.fullpath();
      }
      async walk(entry = this.cwd, opts = {}) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        } else if (!(entry instanceof PathBase)) {
          opts = entry;
          entry = this.cwd;
        }
        const { withFileTypes = true, follow = false, filter: filter4, walkFilter } = opts;
        const results = [];
        if (!filter4 || filter4(entry)) {
          results.push(withFileTypes ? entry : entry.fullpath());
        }
        const dirs = /* @__PURE__ */ new Set();
        const walk = /* @__PURE__ */ __name((dir, cb) => {
          dirs.add(dir);
          dir.readdirCB((er, entries) => {
            if (er) {
              return cb(er);
            }
            let len = entries.length;
            if (!len)
              return cb();
            const next = /* @__PURE__ */ __name(() => {
              if (--len === 0) {
                cb();
              }
            }, "next");
            for (const e2 of entries) {
              if (!filter4 || filter4(e2)) {
                results.push(withFileTypes ? e2 : e2.fullpath());
              }
              if (follow && e2.isSymbolicLink()) {
                e2.realpath().then((r3) => r3?.isUnknown() ? r3.lstat() : r3).then((r3) => r3?.shouldWalk(dirs, walkFilter) ? walk(r3, next) : next());
              } else {
                if (e2.shouldWalk(dirs, walkFilter)) {
                  walk(e2, next);
                } else {
                  next();
                }
              }
            }
          }, true);
        }, "walk");
        const start = entry;
        return new Promise((res, rej) => {
          walk(start, (er) => {
            if (er)
              return rej(er);
            res(results);
          });
        });
      }
      walkSync(entry = this.cwd, opts = {}) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        } else if (!(entry instanceof PathBase)) {
          opts = entry;
          entry = this.cwd;
        }
        const { withFileTypes = true, follow = false, filter: filter4, walkFilter } = opts;
        const results = [];
        if (!filter4 || filter4(entry)) {
          results.push(withFileTypes ? entry : entry.fullpath());
        }
        const dirs = /* @__PURE__ */ new Set([entry]);
        for (const dir of dirs) {
          const entries = dir.readdirSync();
          for (const e2 of entries) {
            if (!filter4 || filter4(e2)) {
              results.push(withFileTypes ? e2 : e2.fullpath());
            }
            let r3 = e2;
            if (e2.isSymbolicLink()) {
              if (!(follow && (r3 = e2.realpathSync())))
                continue;
              if (r3.isUnknown())
                r3.lstatSync();
            }
            if (r3.shouldWalk(dirs, walkFilter)) {
              dirs.add(r3);
            }
          }
        }
        return results;
      }
      /**
       * Support for `for await`
       *
       * Alias for {@link PathScurryBase.iterate}
       *
       * Note: As of Node 19, this is very slow, compared to other methods of
       * walking.  Consider using {@link PathScurryBase.stream} if memory overhead
       * and backpressure are concerns, or {@link PathScurryBase.walk} if not.
       */
      [Symbol.asyncIterator]() {
        return this.iterate();
      }
      iterate(entry = this.cwd, options2 = {}) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        } else if (!(entry instanceof PathBase)) {
          options2 = entry;
          entry = this.cwd;
        }
        return this.stream(entry, options2)[Symbol.asyncIterator]();
      }
      /**
       * Iterating over a PathScurry performs a synchronous walk.
       *
       * Alias for {@link PathScurryBase.iterateSync}
       */
      [Symbol.iterator]() {
        return this.iterateSync();
      }
      *iterateSync(entry = this.cwd, opts = {}) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        } else if (!(entry instanceof PathBase)) {
          opts = entry;
          entry = this.cwd;
        }
        const { withFileTypes = true, follow = false, filter: filter4, walkFilter } = opts;
        if (!filter4 || filter4(entry)) {
          yield withFileTypes ? entry : entry.fullpath();
        }
        const dirs = /* @__PURE__ */ new Set([entry]);
        for (const dir of dirs) {
          const entries = dir.readdirSync();
          for (const e2 of entries) {
            if (!filter4 || filter4(e2)) {
              yield withFileTypes ? e2 : e2.fullpath();
            }
            let r3 = e2;
            if (e2.isSymbolicLink()) {
              if (!(follow && (r3 = e2.realpathSync())))
                continue;
              if (r3.isUnknown())
                r3.lstatSync();
            }
            if (r3.shouldWalk(dirs, walkFilter)) {
              dirs.add(r3);
            }
          }
        }
      }
      stream(entry = this.cwd, opts = {}) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        } else if (!(entry instanceof PathBase)) {
          opts = entry;
          entry = this.cwd;
        }
        const { withFileTypes = true, follow = false, filter: filter4, walkFilter } = opts;
        const results = new Minipass({ objectMode: true });
        if (!filter4 || filter4(entry)) {
          results.write(withFileTypes ? entry : entry.fullpath());
        }
        const dirs = /* @__PURE__ */ new Set();
        const queue = [entry];
        let processing = 0;
        const process51 = /* @__PURE__ */ __name(() => {
          let paused = false;
          while (!paused) {
            const dir = queue.shift();
            if (!dir) {
              if (processing === 0)
                results.end();
              return;
            }
            processing++;
            dirs.add(dir);
            const onReaddir = /* @__PURE__ */ __name((er, entries, didRealpaths = false) => {
              if (er)
                return results.emit("error", er);
              if (follow && !didRealpaths) {
                const promises6 = [];
                for (const e2 of entries) {
                  if (e2.isSymbolicLink()) {
                    promises6.push(e2.realpath().then((r3) => r3?.isUnknown() ? r3.lstat() : r3));
                  }
                }
                if (promises6.length) {
                  Promise.all(promises6).then(() => onReaddir(null, entries, true));
                  return;
                }
              }
              for (const e2 of entries) {
                if (e2 && (!filter4 || filter4(e2))) {
                  if (!results.write(withFileTypes ? e2 : e2.fullpath())) {
                    paused = true;
                  }
                }
              }
              processing--;
              for (const e2 of entries) {
                const r3 = e2.realpathCached() || e2;
                if (r3.shouldWalk(dirs, walkFilter)) {
                  queue.push(r3);
                }
              }
              if (paused && !results.flowing) {
                results.once("drain", process51);
              } else if (!sync2) {
                process51();
              }
            }, "onReaddir");
            let sync2 = true;
            dir.readdirCB(onReaddir, true);
            sync2 = false;
          }
        }, "process");
        process51();
        return results;
      }
      streamSync(entry = this.cwd, opts = {}) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        } else if (!(entry instanceof PathBase)) {
          opts = entry;
          entry = this.cwd;
        }
        const { withFileTypes = true, follow = false, filter: filter4, walkFilter } = opts;
        const results = new Minipass({ objectMode: true });
        const dirs = /* @__PURE__ */ new Set();
        if (!filter4 || filter4(entry)) {
          results.write(withFileTypes ? entry : entry.fullpath());
        }
        const queue = [entry];
        let processing = 0;
        const process51 = /* @__PURE__ */ __name(() => {
          let paused = false;
          while (!paused) {
            const dir = queue.shift();
            if (!dir) {
              if (processing === 0)
                results.end();
              return;
            }
            processing++;
            dirs.add(dir);
            const entries = dir.readdirSync();
            for (const e2 of entries) {
              if (!filter4 || filter4(e2)) {
                if (!results.write(withFileTypes ? e2 : e2.fullpath())) {
                  paused = true;
                }
              }
            }
            processing--;
            for (const e2 of entries) {
              let r3 = e2;
              if (e2.isSymbolicLink()) {
                if (!(follow && (r3 = e2.realpathSync())))
                  continue;
                if (r3.isUnknown())
                  r3.lstatSync();
              }
              if (r3.shouldWalk(dirs, walkFilter)) {
                queue.push(r3);
              }
            }
          }
          if (paused && !results.flowing)
            results.once("drain", process51);
        }, "process");
        process51();
        return results;
      }
      chdir(path108 = this.cwd) {
        const oldCwd = this.cwd;
        this.cwd = typeof path108 === "string" ? this.cwd.resolve(path108) : path108;
        this.cwd[setAsCwd](oldCwd);
      }
    };
    PathScurryWin32 = class extends PathScurryBase {
      static {
        __name(this, "PathScurryWin32");
      }
      /**
       * separator for generating path strings
       */
      sep = "\\";
      constructor(cwd7 = process.cwd(), opts = {}) {
        const { nocase = true } = opts;
        super(cwd7, win32, "\\", { ...opts, nocase });
        this.nocase = nocase;
        for (let p = this.cwd; p; p = p.parent) {
          p.nocase = this.nocase;
        }
      }
      /**
       * @internal
       */
      parseRootPath(dir) {
        return win32.parse(dir).root.toUpperCase();
      }
      /**
       * @internal
       */
      newRoot(fs95) {
        return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs95 });
      }
      /**
       * Return true if the provided path string is an absolute path
       */
      isAbsolute(p) {
        return p.startsWith("/") || p.startsWith("\\") || /^[a-z]:(\/|\\)/i.test(p);
      }
    };
    PathScurryPosix = class extends PathScurryBase {
      static {
        __name(this, "PathScurryPosix");
      }
      /**
       * separator for generating path strings
       */
      sep = "/";
      constructor(cwd7 = process.cwd(), opts = {}) {
        const { nocase = false } = opts;
        super(cwd7, posix, "/", { ...opts, nocase });
        this.nocase = nocase;
      }
      /**
       * @internal
       */
      parseRootPath(_dir) {
        return "/";
      }
      /**
       * @internal
       */
      newRoot(fs95) {
        return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs95 });
      }
      /**
       * Return true if the provided path string is an absolute path
       */
      isAbsolute(p) {
        return p.startsWith("/");
      }
    };
    PathScurryDarwin = class extends PathScurryPosix {
      static {
        __name(this, "PathScurryDarwin");
      }
      constructor(cwd7 = process.cwd(), opts = {}) {
        const { nocase = true } = opts;
        super(cwd7, { ...opts, nocase });
      }
    };
    Path = process.platform === "win32" ? PathWin32 : PathPosix;
    PathScurry = process.platform === "win32" ? PathScurryWin32 : process.platform === "darwin" ? PathScurryDarwin : PathScurryPosix;
  }
});

// node_modules/glob/dist/esm/pattern.js
var isPatternList, isGlobList, Pattern;
var init_pattern = __esm({
  "node_modules/glob/dist/esm/pattern.js"() {
    init_esbuild_shims();
    init_esm5();
    isPatternList = /* @__PURE__ */ __name((pl) => pl.length >= 1, "isPatternList");
    isGlobList = /* @__PURE__ */ __name((gl) => gl.length >= 1, "isGlobList");
    Pattern = class _Pattern {
      static {
        __name(this, "Pattern");
      }
      #patternList;
      #globList;
      #index;
      length;
      #platform;
      #rest;
      #globString;
      #isDrive;
      #isUNC;
      #isAbsolute;
      #followGlobstar = true;
      constructor(patternList, globList, index, platform15) {
        if (!isPatternList(patternList)) {
          throw new TypeError("empty pattern list");
        }
        if (!isGlobList(globList)) {
          throw new TypeError("empty glob list");
        }
        if (globList.length !== patternList.length) {
          throw new TypeError("mismatched pattern list and glob list lengths");
        }
        this.length = patternList.length;
        if (index < 0 || index >= this.length) {
          throw new TypeError("index out of range");
        }
        this.#patternList = patternList;
        this.#globList = globList;
        this.#index = index;
        this.#platform = platform15;
        if (this.#index === 0) {
          if (this.isUNC()) {
            const [p0, p1, p2, p3, ...prest] = this.#patternList;
            const [g0, g1, g2, g3, ...grest] = this.#globList;
            if (prest[0] === "") {
              prest.shift();
              grest.shift();
            }
            const p = [p0, p1, p2, p3, ""].join("/");
            const g = [g0, g1, g2, g3, ""].join("/");
            this.#patternList = [p, ...prest];
            this.#globList = [g, ...grest];
            this.length = this.#patternList.length;
          } else if (this.isDrive() || this.isAbsolute()) {
            const [p1, ...prest] = this.#patternList;
            const [g1, ...grest] = this.#globList;
            if (prest[0] === "") {
              prest.shift();
              grest.shift();
            }
            const p = p1 + "/";
            const g = g1 + "/";
            this.#patternList = [p, ...prest];
            this.#globList = [g, ...grest];
            this.length = this.#patternList.length;
          }
        }
      }
      /**
       * The first entry in the parsed list of patterns
       */
      pattern() {
        return this.#patternList[this.#index];
      }
      /**
       * true of if pattern() returns a string
       */
      isString() {
        return typeof this.#patternList[this.#index] === "string";
      }
      /**
       * true of if pattern() returns GLOBSTAR
       */
      isGlobstar() {
        return this.#patternList[this.#index] === GLOBSTAR;
      }
      /**
       * true if pattern() returns a regexp
       */
      isRegExp() {
        return this.#patternList[this.#index] instanceof RegExp;
      }
      /**
       * The /-joined set of glob parts that make up this pattern
       */
      globString() {
        return this.#globString = this.#globString || (this.#index === 0 ? this.isAbsolute() ? this.#globList[0] + this.#globList.slice(1).join("/") : this.#globList.join("/") : this.#globList.slice(this.#index).join("/"));
      }
      /**
       * true if there are more pattern parts after this one
       */
      hasMore() {
        return this.length > this.#index + 1;
      }
      /**
       * The rest of the pattern after this part, or null if this is the end
       */
      rest() {
        if (this.#rest !== void 0)
          return this.#rest;
        if (!this.hasMore())
          return this.#rest = null;
        this.#rest = new _Pattern(this.#patternList, this.#globList, this.#index + 1, this.#platform);
        this.#rest.#isAbsolute = this.#isAbsolute;
        this.#rest.#isUNC = this.#isUNC;
        this.#rest.#isDrive = this.#isDrive;
        return this.#rest;
      }
      /**
       * true if the pattern represents a //unc/path/ on windows
       */
      isUNC() {
        const pl = this.#patternList;
        return this.#isUNC !== void 0 ? this.#isUNC : this.#isUNC = this.#platform === "win32" && this.#index === 0 && pl[0] === "" && pl[1] === "" && typeof pl[2] === "string" && !!pl[2] && typeof pl[3] === "string" && !!pl[3];
      }
      // pattern like C:/...
      // split = ['C:', ...]
      // XXX: would be nice to handle patterns like `c:*` to test the cwd
      // in c: for *, but I don't know of a way to even figure out what that
      // cwd is without actually chdir'ing into it?
      /**
       * True if the pattern starts with a drive letter on Windows
       */
      isDrive() {
        const pl = this.#patternList;
        return this.#isDrive !== void 0 ? this.#isDrive : this.#isDrive = this.#platform === "win32" && this.#index === 0 && this.length > 1 && typeof pl[0] === "string" && /^[a-z]:$/i.test(pl[0]);
      }
      // pattern = '/' or '/...' or '/x/...'
      // split = ['', ''] or ['', ...] or ['', 'x', ...]
      // Drive and UNC both considered absolute on windows
      /**
       * True if the pattern is rooted on an absolute path
       */
      isAbsolute() {
        const pl = this.#patternList;
        return this.#isAbsolute !== void 0 ? this.#isAbsolute : this.#isAbsolute = pl[0] === "" && pl.length > 1 || this.isDrive() || this.isUNC();
      }
      /**
       * consume the root of the pattern, and return it
       */
      root() {
        const p = this.#patternList[0];
        return typeof p === "string" && this.isAbsolute() && this.#index === 0 ? p : "";
      }
      /**
       * Check to see if the current globstar pattern is allowed to follow
       * a symbolic link.
       */
      checkFollowGlobstar() {
        return !(this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar);
      }
      /**
       * Mark that the current globstar pattern is following a symbolic link
       */
      markFollowGlobstar() {
        if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)
          return false;
        this.#followGlobstar = false;
        return true;
      }
    };
  }
});

// node_modules/glob/dist/esm/ignore.js
var defaultPlatform2, Ignore;
var init_ignore = __esm({
  "node_modules/glob/dist/esm/ignore.js"() {
    init_esbuild_shims();
    init_esm5();
    init_pattern();
    defaultPlatform2 = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
    Ignore = class {
      static {
        __name(this, "Ignore");
      }
      relative;
      relativeChildren;
      absolute;
      absoluteChildren;
      platform;
      mmopts;
      constructor(ignored, { nobrace, nocase, noext, noglobstar, platform: platform15 = defaultPlatform2 }) {
        this.relative = [];
        this.absolute = [];
        this.relativeChildren = [];
        this.absoluteChildren = [];
        this.platform = platform15;
        this.mmopts = {
          dot: true,
          nobrace,
          nocase,
          noext,
          noglobstar,
          optimizationLevel: 2,
          platform: platform15,
          nocomment: true,
          nonegate: true
        };
        for (const ign of ignored)
          this.add(ign);
      }
      add(ign) {
        const mm = new Minimatch(ign, this.mmopts);
        for (let i = 0; i < mm.set.length; i++) {
          const parsed = mm.set[i];
          const globParts = mm.globParts[i];
          if (!parsed || !globParts) {
            throw new Error("invalid pattern object");
          }
          while (parsed[0] === "." && globParts[0] === ".") {
            parsed.shift();
            globParts.shift();
          }
          const p = new Pattern(parsed, globParts, 0, this.platform);
          const m = new Minimatch(p.globString(), this.mmopts);
          const children = globParts[globParts.length - 1] === "**";
          const absolute = p.isAbsolute();
          if (absolute)
            this.absolute.push(m);
          else
            this.relative.push(m);
          if (children) {
            if (absolute)
              this.absoluteChildren.push(m);
            else
              this.relativeChildren.push(m);
          }
        }
      }
      ignored(p) {
        const fullpath = p.fullpath();
        const fullpaths = `${fullpath}/`;
        const relative10 = p.relative() || ".";
        const relatives = `${relative10}/`;
        for (const m of this.relative) {
          if (m.match(relative10) || m.match(relatives))
            return true;
        }
        for (const m of this.absolute) {
          if (m.match(fullpath) || m.match(fullpaths))
            return true;
        }
        return false;
      }
      childrenIgnored(p) {
        const fullpath = p.fullpath() + "/";
        const relative10 = (p.relative() || ".") + "/";
        for (const m of this.relativeChildren) {
          if (m.match(relative10))
            return true;
        }
        for (const m of this.absoluteChildren) {
          if (m.match(fullpath))
            return true;
        }
        return false;
      }
    };
  }
});

// node_modules/glob/dist/esm/processor.js
var HasWalkedCache, MatchRecord, SubWalks, Processor;
var init_processor = __esm({
  "node_modules/glob/dist/esm/processor.js"() {
    init_esbuild_shims();
    init_esm5();
    HasWalkedCache = class _HasWalkedCache {
      static {
        __name(this, "HasWalkedCache");
      }
      store;
      constructor(store = /* @__PURE__ */ new Map()) {
        this.store = store;
      }
      copy() {
        return new _HasWalkedCache(new Map(this.store));
      }
      hasWalked(target, pattern) {
        return this.store.get(target.fullpath())?.has(pattern.globString());
      }
      storeWalked(target, pattern) {
        const fullpath = target.fullpath();
        const cached = this.store.get(fullpath);
        if (cached)
          cached.add(pattern.globString());
        else
          this.store.set(fullpath, /* @__PURE__ */ new Set([pattern.globString()]));
      }
    };
    MatchRecord = class {
      static {
        __name(this, "MatchRecord");
      }
      store = /* @__PURE__ */ new Map();
      add(target, absolute, ifDir) {
        const n2 = (absolute ? 2 : 0) | (ifDir ? 1 : 0);
        const current = this.store.get(target);
        this.store.set(target, current === void 0 ? n2 : n2 & current);
      }
      // match, absolute, ifdir
      entries() {
        return [...this.store.entries()].map(([path108, n2]) => [
          path108,
          !!(n2 & 2),
          !!(n2 & 1)
        ]);
      }
    };
    SubWalks = class {
      static {
        __name(this, "SubWalks");
      }
      store = /* @__PURE__ */ new Map();
      add(target, pattern) {
        if (!target.canReaddir()) {
          return;
        }
        const subs = this.store.get(target);
        if (subs) {
          if (!subs.find((p) => p.globString() === pattern.globString())) {
            subs.push(pattern);
          }
        } else
          this.store.set(target, [pattern]);
      }
      get(target) {
        const subs = this.store.get(target);
        if (!subs) {
          throw new Error("attempting to walk unknown path");
        }
        return subs;
      }
      entries() {
        return this.keys().map((k) => [k, this.store.get(k)]);
      }
      keys() {
        return [...this.store.keys()].filter((t2) => t2.canReaddir());
      }
    };
    Processor = class _Processor {
      static {
        __name(this, "Processor");
      }
      hasWalkedCache;
      matches = new MatchRecord();
      subwalks = new SubWalks();
      patterns;
      follow;
      dot;
      opts;
      constructor(opts, hasWalkedCache) {
        this.opts = opts;
        this.follow = !!opts.follow;
        this.dot = !!opts.dot;
        this.hasWalkedCache = hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache();
      }
      processPatterns(target, patterns) {
        this.patterns = patterns;
        const processingSet = patterns.map((p) => [target, p]);
        for (let [t2, pattern] of processingSet) {
          this.hasWalkedCache.storeWalked(t2, pattern);
          const root = pattern.root();
          const absolute = pattern.isAbsolute() && this.opts.absolute !== false;
          if (root) {
            t2 = t2.resolve(root === "/" && this.opts.root !== void 0 ? this.opts.root : root);
            const rest2 = pattern.rest();
            if (!rest2) {
              this.matches.add(t2, true, false);
              continue;
            } else {
              pattern = rest2;
            }
          }
          if (t2.isENOENT())
            continue;
          let p;
          let rest;
          let changed = false;
          while (typeof (p = pattern.pattern()) === "string" && (rest = pattern.rest())) {
            const c3 = t2.resolve(p);
            t2 = c3;
            pattern = rest;
            changed = true;
          }
          p = pattern.pattern();
          rest = pattern.rest();
          if (changed) {
            if (this.hasWalkedCache.hasWalked(t2, pattern))
              continue;
            this.hasWalkedCache.storeWalked(t2, pattern);
          }
          if (typeof p === "string") {
            const ifDir = p === ".." || p === "" || p === ".";
            this.matches.add(t2.resolve(p), absolute, ifDir);
            continue;
          } else if (p === GLOBSTAR) {
            if (!t2.isSymbolicLink() || this.follow || pattern.checkFollowGlobstar()) {
              this.subwalks.add(t2, pattern);
            }
            const rp = rest?.pattern();
            const rrest = rest?.rest();
            if (!rest || (rp === "" || rp === ".") && !rrest) {
              this.matches.add(t2, absolute, rp === "" || rp === ".");
            } else {
              if (rp === "..") {
                const tp = t2.parent || t2;
                if (!rrest)
                  this.matches.add(tp, absolute, true);
                else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {
                  this.subwalks.add(tp, rrest);
                }
              }
            }
          } else if (p instanceof RegExp) {
            this.subwalks.add(t2, pattern);
          }
        }
        return this;
      }
      subwalkTargets() {
        return this.subwalks.keys();
      }
      child() {
        return new _Processor(this.opts, this.hasWalkedCache);
      }
      // return a new Processor containing the subwalks for each
      // child entry, and a set of matches, and
      // a hasWalkedCache that's a copy of this one
      // then we're going to call
      filterEntries(parent, entries) {
        const patterns = this.subwalks.get(parent);
        const results = this.child();
        for (const e2 of entries) {
          for (const pattern of patterns) {
            const absolute = pattern.isAbsolute();
            const p = pattern.pattern();
            const rest = pattern.rest();
            if (p === GLOBSTAR) {
              results.testGlobstar(e2, pattern, rest, absolute);
            } else if (p instanceof RegExp) {
              results.testRegExp(e2, p, rest, absolute);
            } else {
              results.testString(e2, p, rest, absolute);
            }
          }
        }
        return results;
      }
      testGlobstar(e2, pattern, rest, absolute) {
        if (this.dot || !e2.name.startsWith(".")) {
          if (!pattern.hasMore()) {
            this.matches.add(e2, absolute, false);
          }
          if (e2.canReaddir()) {
            if (this.follow || !e2.isSymbolicLink()) {
              this.subwalks.add(e2, pattern);
            } else if (e2.isSymbolicLink()) {
              if (rest && pattern.checkFollowGlobstar()) {
                this.subwalks.add(e2, rest);
              } else if (pattern.markFollowGlobstar()) {
                this.subwalks.add(e2, pattern);
              }
            }
          }
        }
        if (rest) {
          const rp = rest.pattern();
          if (typeof rp === "string" && // dots and empty were handled already
          rp !== ".." && rp !== "" && rp !== ".") {
            this.testString(e2, rp, rest.rest(), absolute);
          } else if (rp === "..") {
            const ep = e2.parent || e2;
            this.subwalks.add(ep, rest);
          } else if (rp instanceof RegExp) {
            this.testRegExp(e2, rp, rest.rest(), absolute);
          }
        }
      }
      testRegExp(e2, p, rest, absolute) {
        if (!p.test(e2.name))
          return;
        if (!rest) {
          this.matches.add(e2, absolute, false);
        } else {
          this.subwalks.add(e2, rest);
        }
      }
      testString(e2, p, rest, absolute) {
        if (!e2.isNamed(p))
          return;
        if (!rest) {
          this.matches.add(e2, absolute, false);
        } else {
          this.subwalks.add(e2, rest);
        }
      }
    };
  }
});

// node_modules/glob/dist/esm/walker.js
var makeIgnore, GlobUtil, GlobWalker, GlobStream;
var init_walker = __esm({
  "node_modules/glob/dist/esm/walker.js"() {
    init_esbuild_shims();
    init_esm7();
    init_ignore();
    init_processor();
    makeIgnore = /* @__PURE__ */ __name((ignore4, opts) => typeof ignore4 === "string" ? new Ignore([ignore4], opts) : Array.isArray(ignore4) ? new Ignore(ignore4, opts) : ignore4, "makeIgnore");
    GlobUtil = class {
      static {
        __name(this, "GlobUtil");
      }
      path;
      patterns;
      opts;
      seen = /* @__PURE__ */ new Set();
      paused = false;
      aborted = false;
      #onResume = [];
      #ignore;
      #sep;
      signal;
      maxDepth;
      includeChildMatches;
      constructor(patterns, path108, opts) {
        this.patterns = patterns;
        this.path = path108;
        this.opts = opts;
        this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
        this.includeChildMatches = opts.includeChildMatches !== false;
        if (opts.ignore || !this.includeChildMatches) {
          this.#ignore = makeIgnore(opts.ignore ?? [], opts);
          if (!this.includeChildMatches && typeof this.#ignore.add !== "function") {
            const m = "cannot ignore child matches, ignore lacks add() method.";
            throw new Error(m);
          }
        }
        this.maxDepth = opts.maxDepth || Infinity;
        if (opts.signal) {
          this.signal = opts.signal;
          this.signal.addEventListener("abort", () => {
            this.#onResume.length = 0;
          });
        }
      }
      #ignored(path108) {
        return this.seen.has(path108) || !!this.#ignore?.ignored?.(path108);
      }
      #childrenIgnored(path108) {
        return !!this.#ignore?.childrenIgnored?.(path108);
      }
      // backpressure mechanism
      pause() {
        this.paused = true;
      }
      resume() {
        if (this.signal?.aborted)
          return;
        this.paused = false;
        let fn = void 0;
        while (!this.paused && (fn = this.#onResume.shift())) {
          fn();
        }
      }
      onResume(fn) {
        if (this.signal?.aborted)
          return;
        if (!this.paused) {
          fn();
        } else {
          this.#onResume.push(fn);
        }
      }
      // do the requisite realpath/stat checking, and return the path
      // to add or undefined to filter it out.
      async matchCheck(e2, ifDir) {
        if (ifDir && this.opts.nodir)
          return void 0;
        let rpc;
        if (this.opts.realpath) {
          rpc = e2.realpathCached() || await e2.realpath();
          if (!rpc)
            return void 0;
          e2 = rpc;
        }
        const needStat = e2.isUnknown() || this.opts.stat;
        const s2 = needStat ? await e2.lstat() : e2;
        if (this.opts.follow && this.opts.nodir && s2?.isSymbolicLink()) {
          const target = await s2.realpath();
          if (target && (target.isUnknown() || this.opts.stat)) {
            await target.lstat();
          }
        }
        return this.matchCheckTest(s2, ifDir);
      }
      matchCheckTest(e2, ifDir) {
        return e2 && (this.maxDepth === Infinity || e2.depth() <= this.maxDepth) && (!ifDir || e2.canReaddir()) && (!this.opts.nodir || !e2.isDirectory()) && (!this.opts.nodir || !this.opts.follow || !e2.isSymbolicLink() || !e2.realpathCached()?.isDirectory()) && !this.#ignored(e2) ? e2 : void 0;
      }
      matchCheckSync(e2, ifDir) {
        if (ifDir && this.opts.nodir)
          return void 0;
        let rpc;
        if (this.opts.realpath) {
          rpc = e2.realpathCached() || e2.realpathSync();
          if (!rpc)
            return void 0;
          e2 = rpc;
        }
        const needStat = e2.isUnknown() || this.opts.stat;
        const s2 = needStat ? e2.lstatSync() : e2;
        if (this.opts.follow && this.opts.nodir && s2?.isSymbolicLink()) {
          const target = s2.realpathSync();
          if (target && (target?.isUnknown() || this.opts.stat)) {
            target.lstatSync();
          }
        }
        return this.matchCheckTest(s2, ifDir);
      }
      matchFinish(e2, absolute) {
        if (this.#ignored(e2))
          return;
        if (!this.includeChildMatches && this.#ignore?.add) {
          const ign = `${e2.relativePosix()}/**`;
          this.#ignore.add(ign);
        }
        const abs = this.opts.absolute === void 0 ? absolute : this.opts.absolute;
        this.seen.add(e2);
        const mark = this.opts.mark && e2.isDirectory() ? this.#sep : "";
        if (this.opts.withFileTypes) {
          this.matchEmit(e2);
        } else if (abs) {
          const abs2 = this.opts.posix ? e2.fullpathPosix() : e2.fullpath();
          this.matchEmit(abs2 + mark);
        } else {
          const rel = this.opts.posix ? e2.relativePosix() : e2.relative();
          const pre = this.opts.dotRelative && !rel.startsWith(".." + this.#sep) ? "." + this.#sep : "";
          this.matchEmit(!rel ? "." + mark : pre + rel + mark);
        }
      }
      async match(e2, absolute, ifDir) {
        const p = await this.matchCheck(e2, ifDir);
        if (p)
          this.matchFinish(p, absolute);
      }
      matchSync(e2, absolute, ifDir) {
        const p = this.matchCheckSync(e2, ifDir);
        if (p)
          this.matchFinish(p, absolute);
      }
      walkCB(target, patterns, cb) {
        if (this.signal?.aborted)
          cb();
        this.walkCB2(target, patterns, new Processor(this.opts), cb);
      }
      walkCB2(target, patterns, processor, cb) {
        if (this.#childrenIgnored(target))
          return cb();
        if (this.signal?.aborted)
          cb();
        if (this.paused) {
          this.onResume(() => this.walkCB2(target, patterns, processor, cb));
          return;
        }
        processor.processPatterns(target, patterns);
        let tasks = 1;
        const next = /* @__PURE__ */ __name(() => {
          if (--tasks === 0)
            cb();
        }, "next");
        for (const [m, absolute, ifDir] of processor.matches.entries()) {
          if (this.#ignored(m))
            continue;
          tasks++;
          this.match(m, absolute, ifDir).then(() => next());
        }
        for (const t2 of processor.subwalkTargets()) {
          if (this.maxDepth !== Infinity && t2.depth() >= this.maxDepth) {
            continue;
          }
          tasks++;
          const childrenCached = t2.readdirCached();
          if (t2.calledReaddir())
            this.walkCB3(t2, childrenCached, processor, next);
          else {
            t2.readdirCB((_, entries) => this.walkCB3(t2, entries, processor, next), true);
          }
        }
        next();
      }
      walkCB3(target, entries, processor, cb) {
        processor = processor.filterEntries(target, entries);
        let tasks = 1;
        const next = /* @__PURE__ */ __name(() => {
          if (--tasks === 0)
            cb();
        }, "next");
        for (const [m, absolute, ifDir] of processor.matches.entries()) {
          if (this.#ignored(m))
            continue;
          tasks++;
          this.match(m, absolute, ifDir).then(() => next());
        }
        for (const [target2, patterns] of processor.subwalks.entries()) {
          tasks++;
          this.walkCB2(target2, patterns, processor.child(), next);
        }
        next();
      }
      walkCBSync(target, patterns, cb) {
        if (this.signal?.aborted)
          cb();
        this.walkCB2Sync(target, patterns, new Processor(this.opts), cb);
      }
      walkCB2Sync(target, patterns, processor, cb) {
        if (this.#childrenIgnored(target))
          return cb();
        if (this.signal?.aborted)
          cb();
        if (this.paused) {
          this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb));
          return;
        }
        processor.processPatterns(target, patterns);
        let tasks = 1;
        const next = /* @__PURE__ */ __name(() => {
          if (--tasks === 0)
            cb();
        }, "next");
        for (const [m, absolute, ifDir] of processor.matches.entries()) {
          if (this.#ignored(m))
            continue;
          this.matchSync(m, absolute, ifDir);
        }
        for (const t2 of processor.subwalkTargets()) {
          if (this.maxDepth !== Infinity && t2.depth() >= this.maxDepth) {
            continue;
          }
          tasks++;
          const children = t2.readdirSync();
          this.walkCB3Sync(t2, children, processor, next);
        }
        next();
      }
      walkCB3Sync(target, entries, processor, cb) {
        processor = processor.filterEntries(target, entries);
        let tasks = 1;
        const next = /* @__PURE__ */ __name(() => {
          if (--tasks === 0)
            cb();
        }, "next");
        for (const [m, absolute, ifDir] of processor.matches.entries()) {
          if (this.#ignored(m))
            continue;
          this.matchSync(m, absolute, ifDir);
        }
        for (const [target2, patterns] of processor.subwalks.entries()) {
          tasks++;
          this.walkCB2Sync(target2, patterns, processor.child(), next);
        }
        next();
      }
    };
    GlobWalker = class extends GlobUtil {
      static {
        __name(this, "GlobWalker");
      }
      matches = /* @__PURE__ */ new Set();
      constructor(patterns, path108, opts) {
        super(patterns, path108, opts);
      }
      matchEmit(e2) {
        this.matches.add(e2);
      }
      async walk() {
        if (this.signal?.aborted)
          throw this.signal.reason;
        if (this.path.isUnknown()) {
          await this.path.lstat();
        }
        await new Promise((res, rej) => {
          this.walkCB(this.path, this.patterns, () => {
            if (this.signal?.aborted) {
              rej(this.signal.reason);
            } else {
              res(this.matches);
            }
          });
        });
        return this.matches;
      }
      walkSync() {
        if (this.signal?.aborted)
          throw this.signal.reason;
        if (this.path.isUnknown()) {
          this.path.lstatSync();
        }
        this.walkCBSync(this.path, this.patterns, () => {
          if (this.signal?.aborted)
            throw this.signal.reason;
        });
        return this.matches;
      }
    };
    GlobStream = class extends GlobUtil {
      static {
        __name(this, "GlobStream");
      }
      results;
      constructor(patterns, path108, opts) {
        super(patterns, path108, opts);
        this.results = new Minipass({
          signal: this.signal,
          objectMode: true
        });
        this.results.on("drain", () => this.resume());
        this.results.on("resume", () => this.resume());
      }
      matchEmit(e2) {
        this.results.write(e2);
        if (!this.results.flowing)
          this.pause();
      }
      stream() {
        const target = this.path;
        if (target.isUnknown()) {
          target.lstat().then(() => {
            this.walkCB(target, this.patterns, () => this.results.end());
          });
        } else {
          this.walkCB(target, this.patterns, () => this.results.end());
        }
        return this.results;
      }
      streamSync() {
        if (this.path.isUnknown()) {
          this.path.lstatSync();
        }
        this.walkCBSync(this.path, this.patterns, () => this.results.end());
        return this.results;
      }
    };
  }
});

// node_modules/glob/dist/esm/glob.js
import { fileURLToPath as fileURLToPath4 } from "node:url";
var defaultPlatform3, Glob;
var init_glob = __esm({
  "node_modules/glob/dist/esm/glob.js"() {
    init_esbuild_shims();
    init_esm5();
    init_esm8();
    init_pattern();
    init_walker();
    defaultPlatform3 = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
    Glob = class {
      static {
        __name(this, "Glob");
      }
      absolute;
      cwd;
      root;
      dot;
      dotRelative;
      follow;
      ignore;
      magicalBraces;
      mark;
      matchBase;
      maxDepth;
      nobrace;
      nocase;
      nodir;
      noext;
      noglobstar;
      pattern;
      platform;
      realpath;
      scurry;
      stat;
      signal;
      windowsPathsNoEscape;
      withFileTypes;
      includeChildMatches;
      /**
       * The options provided to the constructor.
       */
      opts;
      /**
       * An array of parsed immutable {@link Pattern} objects.
       */
      patterns;
      /**
       * All options are stored as properties on the `Glob` object.
       *
       * See {@link GlobOptions} for full options descriptions.
       *
       * Note that a previous `Glob` object can be passed as the
       * `GlobOptions` to another `Glob` instantiation to re-use settings
       * and caches with a new pattern.
       *
       * Traversal functions can be called multiple times to run the walk
       * again.
       */
      constructor(pattern, opts) {
        if (!opts)
          throw new TypeError("glob options required");
        this.withFileTypes = !!opts.withFileTypes;
        this.signal = opts.signal;
        this.follow = !!opts.follow;
        this.dot = !!opts.dot;
        this.dotRelative = !!opts.dotRelative;
        this.nodir = !!opts.nodir;
        this.mark = !!opts.mark;
        if (!opts.cwd) {
          this.cwd = "";
        } else if (opts.cwd instanceof URL || opts.cwd.startsWith("file://")) {
          opts.cwd = fileURLToPath4(opts.cwd);
        }
        this.cwd = opts.cwd || "";
        this.root = opts.root;
        this.magicalBraces = !!opts.magicalBraces;
        this.nobrace = !!opts.nobrace;
        this.noext = !!opts.noext;
        this.realpath = !!opts.realpath;
        this.absolute = opts.absolute;
        this.includeChildMatches = opts.includeChildMatches !== false;
        this.noglobstar = !!opts.noglobstar;
        this.matchBase = !!opts.matchBase;
        this.maxDepth = typeof opts.maxDepth === "number" ? opts.maxDepth : Infinity;
        this.stat = !!opts.stat;
        this.ignore = opts.ignore;
        if (this.withFileTypes && this.absolute !== void 0) {
          throw new Error("cannot set absolute and withFileTypes:true");
        }
        if (typeof pattern === "string") {
          pattern = [pattern];
        }
        this.windowsPathsNoEscape = !!opts.windowsPathsNoEscape || opts.allowWindowsEscape === false;
        if (this.windowsPathsNoEscape) {
          pattern = pattern.map((p) => p.replace(/\\/g, "/"));
        }
        if (this.matchBase) {
          if (opts.noglobstar) {
            throw new TypeError("base matching requires globstar");
          }
          pattern = pattern.map((p) => p.includes("/") ? p : `./**/${p}`);
        }
        this.pattern = pattern;
        this.platform = opts.platform || defaultPlatform3;
        this.opts = { ...opts, platform: this.platform };
        if (opts.scurry) {
          this.scurry = opts.scurry;
          if (opts.nocase !== void 0 && opts.nocase !== opts.scurry.nocase) {
            throw new Error("nocase option contradicts provided scurry option");
          }
        } else {
          const Scurry = opts.platform === "win32" ? PathScurryWin32 : opts.platform === "darwin" ? PathScurryDarwin : opts.platform ? PathScurryPosix : PathScurry;
          this.scurry = new Scurry(this.cwd, {
            nocase: opts.nocase,
            fs: opts.fs
          });
        }
        this.nocase = this.scurry.nocase;
        const nocaseMagicOnly = this.platform === "darwin" || this.platform === "win32";
        const mmo = {
          // default nocase based on platform
          ...opts,
          dot: this.dot,
          matchBase: this.matchBase,
          nobrace: this.nobrace,
          nocase: this.nocase,
          nocaseMagicOnly,
          nocomment: true,
          noext: this.noext,
          nonegate: true,
          optimizationLevel: 2,
          platform: this.platform,
          windowsPathsNoEscape: this.windowsPathsNoEscape,
          debug: !!this.opts.debug
        };
        const mms = this.pattern.map((p) => new Minimatch(p, mmo));
        const [matchSet, globParts] = mms.reduce((set, m) => {
          set[0].push(...m.set);
          set[1].push(...m.globParts);
          return set;
        }, [[], []]);
        this.patterns = matchSet.map((set, i) => {
          const g = globParts[i];
          if (!g)
            throw new Error("invalid pattern object");
          return new Pattern(set, g, 0, this.platform);
        });
      }
      async walk() {
        return [
          ...await new GlobWalker(this.patterns, this.scurry.cwd, {
            ...this.opts,
            maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
            platform: this.platform,
            nocase: this.nocase,
            includeChildMatches: this.includeChildMatches
          }).walk()
        ];
      }
      walkSync() {
        return [
          ...new GlobWalker(this.patterns, this.scurry.cwd, {
            ...this.opts,
            maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
            platform: this.platform,
            nocase: this.nocase,
            includeChildMatches: this.includeChildMatches
          }).walkSync()
        ];
      }
      stream() {
        return new GlobStream(this.patterns, this.scurry.cwd, {
          ...this.opts,
          maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
          platform: this.platform,
          nocase: this.nocase,
          includeChildMatches: this.includeChildMatches
        }).stream();
      }
      streamSync() {
        return new GlobStream(this.patterns, this.scurry.cwd, {
          ...this.opts,
          maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
          platform: this.platform,
          nocase: this.nocase,
          includeChildMatches: this.includeChildMatches
        }).streamSync();
      }
      /**
       * Default sync iteration function. Returns a Generator that
       * iterates over the results.
       */
      iterateSync() {
        return this.streamSync()[Symbol.iterator]();
      }
      [Symbol.iterator]() {
        return this.iterateSync();
      }
      /**
       * Default async iteration function. Returns an AsyncGenerator that
       * iterates over the results.
       */
      iterate() {
        return this.stream()[Symbol.asyncIterator]();
      }
      [Symbol.asyncIterator]() {
        return this.iterate();
      }
    };
  }
});

// node_modules/glob/dist/esm/has-magic.js
var hasMagic;
var init_has_magic = __esm({
  "node_modules/glob/dist/esm/has-magic.js"() {
    init_esbuild_shims();
    init_esm5();
    hasMagic = /* @__PURE__ */ __name((pattern, options2 = {}) => {
      if (!Array.isArray(pattern)) {
        pattern = [pattern];
      }
      for (const p of pattern) {
        if (new Minimatch(p, options2).hasMagic())
          return true;
      }
      return false;
    }, "hasMagic");
  }
});

// node_modules/glob/dist/esm/index.js
function globStreamSync(pattern, options2 = {}) {
  return new Glob(pattern, options2).streamSync();
}
function globStream(pattern, options2 = {}) {
  return new Glob(pattern, options2).stream();
}
function globSync(pattern, options2 = {}) {
  return new Glob(pattern, options2).walkSync();
}
async function glob_(pattern, options2 = {}) {
  return new Glob(pattern, options2).walk();
}
function globIterateSync(pattern, options2 = {}) {
  return new Glob(pattern, options2).iterateSync();
}
function globIterate(pattern, options2 = {}) {
  return new Glob(pattern, options2).iterate();
}
var streamSync, stream, iterateSync, iterate, sync, glob;
var init_esm9 = __esm({
  "node_modules/glob/dist/esm/index.js"() {
    init_esbuild_shims();
    init_esm5();
    init_glob();
    init_has_magic();
    init_esm5();
    init_glob();
    init_has_magic();
    init_ignore();
    __name(globStreamSync, "globStreamSync");
    __name(globStream, "globStream");
    __name(globSync, "globSync");
    __name(glob_, "glob_");
    __name(globIterateSync, "globIterateSync");
    __name(globIterate, "globIterate");
    streamSync = globStreamSync;
    stream = Object.assign(globStream, { sync: globStreamSync });
    iterateSync = globIterateSync;
    iterate = Object.assign(globIterate, {
      sync: globIterateSync
    });
    sync = Object.assign(globSync, {
      stream: globStreamSync,
      iterate: globIterateSync
    });
    glob = Object.assign(glob_, {
      glob: glob_,
      globSync,
      sync,
      globStream,
      stream,
      globStreamSync,
      streamSync,
      globIterate,
      iterate,
      globIterateSync,
      iterateSync,
      Glob,
      hasMagic,
      escape: escape3,
      unescape: unescape2
    });
    glob.glob = glob;
  }
});

// packages/core/dist/src/services/fileSystemService.js
import fs28 from "node:fs/promises";
import * as path26 from "node:path";
var StandardFileSystemService;
var init_fileSystemService = __esm({
  "packages/core/dist/src/services/fileSystemService.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm9();
    StandardFileSystemService = class {
      static {
        __name(this, "StandardFileSystemService");
      }
      async readTextFile(filePath) {
        return fs28.readFile(filePath, "utf-8");
      }
      async writeTextFile(filePath, content) {
        await fs28.writeFile(filePath, content, "utf-8");
      }
      findFiles(fileName, searchPaths) {
        return searchPaths.flatMap((searchPath) => {
          const pattern = path26.posix.join(searchPath, "**", fileName);
          return globSync(pattern, {
            nodir: true,
            absolute: true
          });
        });
      }
    };
  }
});

// node_modules/@kwsites/file-exists/dist/src/index.js
var require_src36 = __commonJS({
  "node_modules/@kwsites/file-exists/dist/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
      return mod2 && mod2.__esModule ? mod2 : { "default": mod2 };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    var fs_1 = __require("fs");
    var debug_1 = __importDefault(require_src());
    var log = debug_1.default("@kwsites/file-exists");
    function check(path108, isFile2, isDirectory) {
      log(`checking %s`, path108);
      try {
        const stat7 = fs_1.statSync(path108);
        if (stat7.isFile() && isFile2) {
          log(`[OK] path represents a file`);
          return true;
        }
        if (stat7.isDirectory() && isDirectory) {
          log(`[OK] path represents a directory`);
          return true;
        }
        log(`[FAIL] path represents something other than a file or directory`);
        return false;
      } catch (e2) {
        if (e2.code === "ENOENT") {
          log(`[FAIL] path is not accessible: %o`, e2);
          return false;
        }
        log(`[FATAL] %o`, e2);
        throw e2;
      }
    }
    __name(check, "check");
    function exists2(path108, type = exports2.READABLE) {
      return check(path108, (type & exports2.FILE) > 0, (type & exports2.FOLDER) > 0);
    }
    __name(exists2, "exists");
    exports2.exists = exists2;
    exports2.FILE = 1;
    exports2.FOLDER = 2;
    exports2.READABLE = exports2.FILE + exports2.FOLDER;
  }
});

// node_modules/@kwsites/file-exists/dist/index.js
var require_dist4 = __commonJS({
  "node_modules/@kwsites/file-exists/dist/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    function __export3(m) {
      for (var p in m) if (!exports2.hasOwnProperty(p)) exports2[p] = m[p];
    }
    __name(__export3, "__export");
    Object.defineProperty(exports2, "__esModule", { value: true });
    __export3(require_src36());
  }
});

// node_modules/@kwsites/promise-deferred/dist/index.js
var require_dist5 = __commonJS({
  "node_modules/@kwsites/promise-deferred/dist/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createDeferred = exports2.deferred = void 0;
    function deferred2() {
      let done;
      let fail;
      let status = "pending";
      const promise = new Promise((_done, _fail) => {
        done = _done;
        fail = _fail;
      });
      return {
        promise,
        done(result) {
          if (status === "pending") {
            status = "resolved";
            done(result);
          }
        },
        fail(error) {
          if (status === "pending") {
            status = "rejected";
            fail(error);
          }
        },
        get fulfilled() {
          return status !== "pending";
        },
        get status() {
          return status;
        }
      };
    }
    __name(deferred2, "deferred");
    exports2.deferred = deferred2;
    exports2.createDeferred = deferred2;
    exports2.default = deferred2;
  }
});

// node_modules/simple-git/dist/esm/index.js
import { Buffer as Buffer22 } from "node:buffer";
import { spawn as spawn2 } from "child_process";
import { EventEmitter as EventEmitter7 } from "node:events";
function pathspec(...paths) {
  const key = new String(paths);
  cache3.set(key, paths);
  return key;
}
function isPathSpec(path108) {
  return path108 instanceof String && cache3.has(path108);
}
function toPaths(pathSpec) {
  return cache3.get(pathSpec) || [];
}
function asFunction(source2) {
  if (typeof source2 !== "function") {
    return NOOP;
  }
  return source2;
}
function isUserFunction(source2) {
  return typeof source2 === "function" && source2 !== NOOP;
}
function splitOn(input, char) {
  const index = input.indexOf(char);
  if (index <= 0) {
    return [input, ""];
  }
  return [input.substr(0, index), input.substr(index + 1)];
}
function first(input, offset = 0) {
  return isArrayLike(input) && input.length > offset ? input[offset] : void 0;
}
function last(input, offset = 0) {
  if (isArrayLike(input) && input.length > offset) {
    return input[input.length - 1 - offset];
  }
}
function isArrayLike(input) {
  return !!(input && typeof input.length === "number");
}
function toLinesWithContent(input = "", trimmed2 = true, separator = "\n") {
  return input.split(separator).reduce((output, line) => {
    const lineContent = trimmed2 ? line.trim() : line;
    if (lineContent) {
      output.push(lineContent);
    }
    return output;
  }, []);
}
function forEachLineWithContent(input, callback) {
  return toLinesWithContent(input, true).map((line) => callback(line));
}
function folderExists(path108) {
  return (0, import_file_exists.exists)(path108, import_file_exists.FOLDER);
}
function append(target, item) {
  if (Array.isArray(target)) {
    if (!target.includes(item)) {
      target.push(item);
    }
  } else {
    target.add(item);
  }
  return item;
}
function including(target, item) {
  if (Array.isArray(target) && !target.includes(item)) {
    target.push(item);
  }
  return target;
}
function remove(target, item) {
  if (Array.isArray(target)) {
    const index = target.indexOf(item);
    if (index >= 0) {
      target.splice(index, 1);
    }
  } else {
    target.delete(item);
  }
  return item;
}
function asArray(source2) {
  return Array.isArray(source2) ? source2 : [source2];
}
function asCamelCase(str2) {
  return str2.replace(/[\s-]+(.)/g, (_all, chr) => {
    return chr.toUpperCase();
  });
}
function asStringArray(source2) {
  return asArray(source2).map(String);
}
function asNumber(source2, onNaN = 0) {
  if (source2 == null) {
    return onNaN;
  }
  const num = parseInt(source2, 10);
  return isNaN(num) ? onNaN : num;
}
function prefixedArray(input, prefix) {
  const output = [];
  for (let i = 0, max = input.length; i < max; i++) {
    output.push(prefix, input[i]);
  }
  return output;
}
function bufferToString(input) {
  return (Array.isArray(input) ? Buffer22.concat(input) : input).toString("utf-8");
}
function pick(source2, properties) {
  return Object.assign(
    {},
    ...properties.map((property) => property in source2 ? { [property]: source2[property] } : {})
  );
}
function delay2(duration = 0) {
  return new Promise((done) => setTimeout(done, duration));
}
function orVoid(input) {
  if (input === false) {
    return void 0;
  }
  return input;
}
function filterType(input, filter4, def2) {
  if (filter4(input)) {
    return input;
  }
  return arguments.length > 2 ? def2 : void 0;
}
function filterPrimitives(input, omit) {
  const type = isPathSpec(input) ? "string" : typeof input;
  return /number|string|boolean/.test(type) && (!omit || !omit.includes(type));
}
function filterPlainObject(input) {
  return !!input && objectToString(input) === "[object Object]";
}
function filterFunction(input) {
  return typeof input === "function";
}
function createInstanceConfig(...options2) {
  const baseDir = process.cwd();
  const config = Object.assign(
    { baseDir, ...defaultOptions },
    ...options2.filter((o2) => typeof o2 === "object" && o2)
  );
  config.baseDir = config.baseDir || baseDir;
  config.trimmed = config.trimmed === true;
  return config;
}
function appendTaskOptions(options2, commands = []) {
  if (!filterPlainObject(options2)) {
    return commands;
  }
  return Object.keys(options2).reduce((commands2, key) => {
    const value = options2[key];
    if (isPathSpec(value)) {
      commands2.push(value);
    } else if (filterPrimitives(value, ["boolean"])) {
      commands2.push(key + "=" + value);
    } else if (Array.isArray(value)) {
      for (const v of value) {
        if (!filterPrimitives(v, ["string", "number"])) {
          commands2.push(key + "=" + v);
        }
      }
    } else {
      commands2.push(key);
    }
    return commands2;
  }, commands);
}
function getTrailingOptions(args, initialPrimitive = 0, objectOnly = false) {
  const command2 = [];
  for (let i = 0, max = initialPrimitive < 0 ? args.length : initialPrimitive; i < max; i++) {
    if ("string|number".includes(typeof args[i])) {
      command2.push(String(args[i]));
    }
  }
  appendTaskOptions(trailingOptionsArgument(args), command2);
  if (!objectOnly) {
    command2.push(...trailingArrayArgument(args));
  }
  return command2;
}
function trailingArrayArgument(args) {
  const hasTrailingCallback = typeof last(args) === "function";
  return filterType(last(args, hasTrailingCallback ? 1 : 0), filterArray, []);
}
function trailingOptionsArgument(args) {
  const hasTrailingCallback = filterFunction(last(args));
  return filterType(last(args, hasTrailingCallback ? 1 : 0), filterPlainObject);
}
function trailingFunctionArgument(args, includeNoop = true) {
  const callback = asFunction(last(args));
  return includeNoop || isUserFunction(callback) ? callback : void 0;
}
function callTaskParser(parser42, streams) {
  return parser42(streams.stdOut, streams.stdErr);
}
function parseStringResponse(result, parsers12, texts, trim = true) {
  asArray(texts).forEach((text) => {
    for (let lines = toLinesWithContent(text, trim), i = 0, max = lines.length; i < max; i++) {
      const line = /* @__PURE__ */ __name((offset = 0) => {
        if (i + offset >= max) {
          return;
        }
        return lines[i + offset];
      }, "line");
      parsers12.some(({ parse: parse12 }) => parse12(line, result));
    }
  });
  return result;
}
function checkIsRepoTask(action) {
  switch (action) {
    case "bare":
      return checkIsBareRepoTask();
    case "root":
      return checkIsRepoRootTask();
  }
  const commands = ["rev-parse", "--is-inside-work-tree"];
  return {
    commands,
    format: "utf-8",
    onError,
    parser
  };
}
function checkIsRepoRootTask() {
  const commands = ["rev-parse", "--git-dir"];
  return {
    commands,
    format: "utf-8",
    onError,
    parser(path108) {
      return /^\.(git)?$/.test(path108.trim());
    }
  };
}
function checkIsBareRepoTask() {
  const commands = ["rev-parse", "--is-bare-repository"];
  return {
    commands,
    format: "utf-8",
    onError,
    parser
  };
}
function isNotRepoMessage(error) {
  return /(Not a git repository|Kein Git-Repository)/i.test(String(error));
}
function cleanSummaryParser(dryRun, text) {
  const summary = new CleanResponse(dryRun);
  const regexp = dryRun ? dryRunRemovalRegexp : removalRegexp;
  toLinesWithContent(text).forEach((line) => {
    const removed = line.replace(regexp, "");
    summary.paths.push(removed);
    (isFolderRegexp.test(removed) ? summary.folders : summary.files).push(removed);
  });
  return summary;
}
function adhocExecTask(parser42) {
  return {
    commands: EMPTY_COMMANDS,
    format: "empty",
    parser: parser42
  };
}
function configurationErrorTask(error) {
  return {
    commands: EMPTY_COMMANDS,
    format: "empty",
    parser() {
      throw typeof error === "string" ? new TaskConfigurationError(error) : error;
    }
  };
}
function straightThroughStringTask(commands, trimmed2 = false) {
  return {
    commands,
    format: "utf-8",
    parser(text) {
      return trimmed2 ? String(text).trim() : text;
    }
  };
}
function straightThroughBufferTask(commands) {
  return {
    commands,
    format: "buffer",
    parser(buffer) {
      return buffer;
    }
  };
}
function isBufferTask(task) {
  return task.format === "buffer";
}
function isEmptyTask(task) {
  return task.format === "empty" || !task.commands.length;
}
function cleanWithOptionsTask(mode, customArgs) {
  const { cleanMode, options: options2, valid } = getCleanOptions(mode);
  if (!cleanMode) {
    return configurationErrorTask(CONFIG_ERROR_MODE_REQUIRED);
  }
  if (!valid.options) {
    return configurationErrorTask(CONFIG_ERROR_UNKNOWN_OPTION + JSON.stringify(mode));
  }
  options2.push(...customArgs);
  if (options2.some(isInteractiveMode)) {
    return configurationErrorTask(CONFIG_ERROR_INTERACTIVE_MODE);
  }
  return cleanTask(cleanMode, options2);
}
function cleanTask(mode, customArgs) {
  const commands = ["clean", `-${mode}`, ...customArgs];
  return {
    commands,
    format: "utf-8",
    parser(text) {
      return cleanSummaryParser(mode === "n", text);
    }
  };
}
function isCleanOptionsArray(input) {
  return Array.isArray(input) && input.every((test) => CleanOptionValues.has(test));
}
function getCleanOptions(input) {
  let cleanMode;
  let options2 = [];
  let valid = { cleanMode: false, options: true };
  input.replace(/[^a-z]i/g, "").split("").forEach((char) => {
    if (isCleanMode(char)) {
      cleanMode = char;
      valid.cleanMode = true;
    } else {
      valid.options = valid.options && isKnownOption(options2[options2.length] = `-${char}`);
    }
  });
  return {
    cleanMode,
    options: options2,
    valid
  };
}
function isCleanMode(cleanMode) {
  return cleanMode === "f" || cleanMode === "n";
}
function isKnownOption(option2) {
  return /^-[a-z]$/i.test(option2) && CleanOptionValues.has(option2.charAt(1));
}
function isInteractiveMode(option2) {
  if (/^-[^\-]/.test(option2)) {
    return option2.indexOf("i") > 0;
  }
  return option2 === "--interactive";
}
function configListParser(text) {
  const config = new ConfigList();
  for (const item of configParser(text)) {
    config.addValue(item.file, String(item.key), item.value);
  }
  return config;
}
function configGetParser(text, key) {
  let value = null;
  const values = [];
  const scopes = /* @__PURE__ */ new Map();
  for (const item of configParser(text, key)) {
    if (item.key !== key) {
      continue;
    }
    values.push(value = item.value);
    if (!scopes.has(item.file)) {
      scopes.set(item.file, []);
    }
    scopes.get(item.file).push(value);
  }
  return {
    key,
    paths: Array.from(scopes.keys()),
    scopes,
    value,
    values
  };
}
function configFilePath(filePath) {
  return filePath.replace(/^(file):/, "");
}
function* configParser(text, requestedKey = null) {
  const lines = text.split("\0");
  for (let i = 0, max = lines.length - 1; i < max; ) {
    const file = configFilePath(lines[i++]);
    let value = lines[i++];
    let key = requestedKey;
    if (value.includes("\n")) {
      const line = splitOn(value, "\n");
      key = line[0];
      value = line[1];
    }
    yield { file, key, value };
  }
}
function asConfigScope(scope, fallback) {
  if (typeof scope === "string" && GitConfigScope.hasOwnProperty(scope)) {
    return scope;
  }
  return fallback;
}
function addConfigTask(key, value, append2, scope) {
  const commands = ["config", `--${scope}`];
  if (append2) {
    commands.push("--add");
  }
  commands.push(key, value);
  return {
    commands,
    format: "utf-8",
    parser(text) {
      return text;
    }
  };
}
function getConfigTask(key, scope) {
  const commands = ["config", "--null", "--show-origin", "--get-all", key];
  if (scope) {
    commands.splice(1, 0, `--${scope}`);
  }
  return {
    commands,
    format: "utf-8",
    parser(text) {
      return configGetParser(text, key);
    }
  };
}
function listConfigTask(scope) {
  const commands = ["config", "--list", "--show-origin", "--null"];
  if (scope) {
    commands.push(`--${scope}`);
  }
  return {
    commands,
    format: "utf-8",
    parser(text) {
      return configListParser(text);
    }
  };
}
function config_default() {
  return {
    addConfig(key, value, ...rest) {
      return this._runTask(
        addConfigTask(
          key,
          value,
          rest[0] === true,
          asConfigScope(
            rest[1],
            "local"
            /* local */
          )
        ),
        trailingFunctionArgument(arguments)
      );
    },
    getConfig(key, scope) {
      return this._runTask(
        getConfigTask(key, asConfigScope(scope, void 0)),
        trailingFunctionArgument(arguments)
      );
    },
    listConfig(...rest) {
      return this._runTask(
        listConfigTask(asConfigScope(rest[0], void 0)),
        trailingFunctionArgument(arguments)
      );
    }
  };
}
function isDiffNameStatus(input) {
  return diffNameStatus.has(input);
}
function grepQueryBuilder(...params) {
  return new GrepQuery().param(...params);
}
function parseGrep(grep) {
  const paths = /* @__PURE__ */ new Set();
  const results = {};
  forEachLineWithContent(grep, (input) => {
    const [path108, line, preview] = input.split(NULL2);
    paths.add(path108);
    (results[path108] = results[path108] || []).push({
      line: asNumber(line),
      path: path108,
      preview
    });
  });
  return {
    paths,
    results
  };
}
function grep_default() {
  return {
    grep(searchTerm) {
      const then = trailingFunctionArgument(arguments);
      const options2 = getTrailingOptions(arguments);
      for (const option2 of disallowedOptions) {
        if (options2.includes(option2)) {
          return this._runTask(
            configurationErrorTask(`git.grep: use of "${option2}" is not supported.`),
            then
          );
        }
      }
      if (typeof searchTerm === "string") {
        searchTerm = grepQueryBuilder().param(searchTerm);
      }
      const commands = ["grep", "--null", "-n", "--full-name", ...options2, ...searchTerm];
      return this._runTask(
        {
          commands,
          format: "utf-8",
          parser(stdOut) {
            return parseGrep(stdOut);
          }
        },
        then
      );
    }
  };
}
function resetTask(mode, customArgs) {
  const commands = ["reset"];
  if (isValidResetMode(mode)) {
    commands.push(`--${mode}`);
  }
  commands.push(...customArgs);
  return straightThroughStringTask(commands);
}
function getResetMode(mode) {
  if (isValidResetMode(mode)) {
    return mode;
  }
  switch (typeof mode) {
    case "string":
    case "undefined":
      return "soft";
  }
  return;
}
function isValidResetMode(mode) {
  return ResetModes.includes(mode);
}
function createLog() {
  return (0, import_debug.default)("simple-git");
}
function prefixedLogger(to, prefix, forward) {
  if (!prefix || !String(prefix).replace(/\s*/, "")) {
    return !forward ? to : (message, ...args) => {
      to(message, ...args);
      forward(message, ...args);
    };
  }
  return (message, ...args) => {
    to(`%s ${message}`, prefix, ...args);
    if (forward) {
      forward(message, ...args);
    }
  };
}
function childLoggerName(name3, childDebugger, { namespace: parentNamespace }) {
  if (typeof name3 === "string") {
    return name3;
  }
  const childNamespace = childDebugger && childDebugger.namespace || "";
  if (childNamespace.startsWith(parentNamespace)) {
    return childNamespace.substr(parentNamespace.length + 1);
  }
  return childNamespace || parentNamespace;
}
function createLogger(label, verbose, initialStep, infoDebugger = createLog()) {
  const labelPrefix = label && `[${label}]` || "";
  const spawned = [];
  const debugDebugger = typeof verbose === "string" ? infoDebugger.extend(verbose) : verbose;
  const key = childLoggerName(filterType(verbose, filterString), debugDebugger, infoDebugger);
  return step(initialStep);
  function sibling(name3, initial) {
    return append(
      spawned,
      createLogger(label, key.replace(/^[^:]+/, name3), initial, infoDebugger)
    );
  }
  __name(sibling, "sibling");
  function step(phase) {
    const stepPrefix = phase && `[${phase}]` || "";
    const debug2 = debugDebugger && prefixedLogger(debugDebugger, stepPrefix) || NOOP;
    const info = prefixedLogger(infoDebugger, `${labelPrefix} ${stepPrefix}`, debug2);
    return Object.assign(debugDebugger ? debug2 : info, {
      label,
      sibling,
      info,
      step
    });
  }
  __name(step, "step");
}
function pluginContext(task, commands) {
  return {
    method: first(task.commands) || "",
    commands
  };
}
function onErrorReceived(target, logger6) {
  return (err) => {
    logger6(`[ERROR] child process exception %o`, err);
    target.push(Buffer.from(String(err.stack), "ascii"));
  };
}
function onDataReceived(target, name3, logger6, output) {
  return (buffer) => {
    logger6(`%s received %L bytes`, name3, buffer);
    output(`%B`, buffer);
    target.push(buffer);
  };
}
function taskCallback(task, response, callback = NOOP) {
  const onSuccess = /* @__PURE__ */ __name((data) => {
    callback(null, data);
  }, "onSuccess");
  const onError2 = /* @__PURE__ */ __name((err) => {
    if (err?.task === task) {
      callback(
        err instanceof GitResponseError ? addDeprecationNoticeToError(err) : err,
        void 0
      );
    }
  }, "onError2");
  response.then(onSuccess, onError2);
}
function addDeprecationNoticeToError(err) {
  let log = /* @__PURE__ */ __name((name3) => {
    console.warn(
      `simple-git deprecation notice: accessing GitResponseError.${name3} should be GitResponseError.git.${name3}, this will no longer be available in version 3`
    );
    log = NOOP;
  }, "log");
  return Object.create(err, Object.getOwnPropertyNames(err.git).reduce(descriptorReducer, {}));
  function descriptorReducer(all2, name3) {
    if (name3 in err) {
      return all2;
    }
    all2[name3] = {
      enumerable: false,
      configurable: false,
      get() {
        log(name3);
        return err.git[name3];
      }
    };
    return all2;
  }
  __name(descriptorReducer, "descriptorReducer");
}
function changeWorkingDirectoryTask(directory, root) {
  return adhocExecTask((instance) => {
    if (!folderExists(directory)) {
      throw new Error(`Git.cwd: cannot change to non-directory "${directory}"`);
    }
    return (root || instance).cwd = directory;
  });
}
function checkoutTask(args) {
  const commands = ["checkout", ...args];
  if (commands[1] === "-b" && commands.includes("-B")) {
    commands[1] = remove(commands, "-B");
  }
  return straightThroughStringTask(commands);
}
function checkout_default() {
  return {
    checkout() {
      return this._runTask(
        checkoutTask(getTrailingOptions(arguments, 1)),
        trailingFunctionArgument(arguments)
      );
    },
    checkoutBranch(branchName, startPoint) {
      return this._runTask(
        checkoutTask(["-b", branchName, startPoint, ...getTrailingOptions(arguments)]),
        trailingFunctionArgument(arguments)
      );
    },
    checkoutLocalBranch(branchName) {
      return this._runTask(
        checkoutTask(["-b", branchName, ...getTrailingOptions(arguments)]),
        trailingFunctionArgument(arguments)
      );
    }
  };
}
function countObjectsResponse() {
  return {
    count: 0,
    garbage: 0,
    inPack: 0,
    packs: 0,
    prunePackable: 0,
    size: 0,
    sizeGarbage: 0,
    sizePack: 0
  };
}
function count_objects_default() {
  return {
    countObjects() {
      return this._runTask({
        commands: ["count-objects", "--verbose"],
        format: "utf-8",
        parser(stdOut) {
          return parseStringResponse(countObjectsResponse(), [parser2], stdOut);
        }
      });
    }
  };
}
function parseCommitResult(stdOut) {
  const result = {
    author: null,
    branch: "",
    commit: "",
    root: false,
    summary: {
      changes: 0,
      insertions: 0,
      deletions: 0
    }
  };
  return parseStringResponse(result, parsers, stdOut);
}
function commitTask(message, files, customArgs) {
  const commands = [
    "-c",
    "core.abbrev=40",
    "commit",
    ...prefixedArray(message, "-m"),
    ...files,
    ...customArgs
  ];
  return {
    commands,
    format: "utf-8",
    parser: parseCommitResult
  };
}
function commit_default() {
  return {
    commit(message, ...rest) {
      const next = trailingFunctionArgument(arguments);
      const task = rejectDeprecatedSignatures(message) || commitTask(
        asArray(message),
        asArray(filterType(rest[0], filterStringOrStringArray, [])),
        [...filterType(rest[1], filterArray, []), ...getTrailingOptions(arguments, 0, true)]
      );
      return this._runTask(task, next);
    }
  };
  function rejectDeprecatedSignatures(message) {
    return !filterStringOrStringArray(message) && configurationErrorTask(
      `git.commit: requires the commit message to be supplied as a string/string[]`
    );
  }
  __name(rejectDeprecatedSignatures, "rejectDeprecatedSignatures");
}
function first_commit_default() {
  return {
    firstCommit() {
      return this._runTask(
        straightThroughStringTask(["rev-list", "--max-parents=0", "HEAD"], true),
        trailingFunctionArgument(arguments)
      );
    }
  };
}
function hashObjectTask(filePath, write2) {
  const commands = ["hash-object", filePath];
  if (write2) {
    commands.push("-w");
  }
  return straightThroughStringTask(commands, true);
}
function parseInit(bare, path108, text) {
  const response = String(text).trim();
  let result;
  if (result = initResponseRegex.exec(response)) {
    return new InitSummary(bare, path108, false, result[1]);
  }
  if (result = reInitResponseRegex.exec(response)) {
    return new InitSummary(bare, path108, true, result[1]);
  }
  let gitDir = "";
  const tokens = response.split(" ");
  while (tokens.length) {
    const token2 = tokens.shift();
    if (token2 === "in") {
      gitDir = tokens.join(" ");
      break;
    }
  }
  return new InitSummary(bare, path108, /^re/i.test(response), gitDir);
}
function hasBareCommand(command2) {
  return command2.includes(bareCommand);
}
function initTask(bare = false, path108, customArgs) {
  const commands = ["init", ...customArgs];
  if (bare && !hasBareCommand(commands)) {
    commands.splice(1, 0, bareCommand);
  }
  return {
    commands,
    format: "utf-8",
    parser(text) {
      return parseInit(commands.includes("--bare"), path108, text);
    }
  };
}
function logFormatFromCommand(customArgs) {
  for (let i = 0; i < customArgs.length; i++) {
    const format4 = logFormatRegex.exec(customArgs[i]);
    if (format4) {
      return `--${format4[1]}`;
    }
  }
  return "";
}
function isLogFormat(customArg) {
  return logFormatRegex.test(customArg);
}
function getDiffParser(format4 = "") {
  const parser42 = diffSummaryParsers[format4];
  return (stdOut) => parseStringResponse(new DiffSummary(), parser42, stdOut, false);
}
function lineBuilder(tokens, fields) {
  return fields.reduce(
    (line, field, index) => {
      line[field] = tokens[index] || "";
      return line;
    },
    /* @__PURE__ */ Object.create({ diff: null })
  );
}
function createListLogSummaryParser(splitter = SPLITTER, fields = defaultFieldNames, logFormat = "") {
  const parseDiffResult = getDiffParser(logFormat);
  return function(stdOut) {
    const all2 = toLinesWithContent(
      stdOut.trim(),
      false,
      START_BOUNDARY
    ).map(function(item) {
      const lineDetail = item.split(COMMIT_BOUNDARY);
      const listLogLine = lineBuilder(lineDetail[0].split(splitter), fields);
      if (lineDetail.length > 1 && !!lineDetail[1].trim()) {
        listLogLine.diff = parseDiffResult(lineDetail[1]);
      }
      return listLogLine;
    });
    return {
      all: all2,
      latest: all2.length && all2[0] || null,
      total: all2.length
    };
  };
}
function diffSummaryTask(customArgs) {
  let logFormat = logFormatFromCommand(customArgs);
  const commands = ["diff"];
  if (logFormat === "") {
    logFormat = "--stat";
    commands.push("--stat=4096");
  }
  commands.push(...customArgs);
  return validateLogFormatConfig(commands) || {
    commands,
    format: "utf-8",
    parser: getDiffParser(logFormat)
  };
}
function validateLogFormatConfig(customArgs) {
  const flags = customArgs.filter(isLogFormat);
  if (flags.length > 1) {
    return configurationErrorTask(
      `Summary flags are mutually exclusive - pick one of ${flags.join(",")}`
    );
  }
  if (flags.length && customArgs.includes("-z")) {
    return configurationErrorTask(
      `Summary flag ${flags} parsing is not compatible with null termination option '-z'`
    );
  }
}
function prettyFormat(format4, splitter) {
  const fields = [];
  const formatStr = [];
  Object.keys(format4).forEach((field) => {
    fields.push(field);
    formatStr.push(String(format4[field]));
  });
  return [fields, formatStr.join(splitter)];
}
function userOptions(input) {
  return Object.keys(input).reduce((out, key) => {
    if (!(key in excludeOptions)) {
      out[key] = input[key];
    }
    return out;
  }, {});
}
function parseLogOptions(opt = {}, customArgs = []) {
  const splitter = filterType(opt.splitter, filterString, SPLITTER);
  const format4 = filterPlainObject(opt.format) ? opt.format : {
    hash: "%H",
    date: opt.strictDate === false ? "%ai" : "%aI",
    message: "%s",
    refs: "%D",
    body: opt.multiLine ? "%B" : "%b",
    author_name: opt.mailMap !== false ? "%aN" : "%an",
    author_email: opt.mailMap !== false ? "%aE" : "%ae"
  };
  const [fields, formatStr] = prettyFormat(format4, splitter);
  const suffix = [];
  const command2 = [
    `--pretty=format:${START_BOUNDARY}${formatStr}${COMMIT_BOUNDARY}`,
    ...customArgs
  ];
  const maxCount = opt.n || opt["max-count"] || opt.maxCount;
  if (maxCount) {
    command2.push(`--max-count=${maxCount}`);
  }
  if (opt.from || opt.to) {
    const rangeOperator = opt.symmetric !== false ? "..." : "..";
    suffix.push(`${opt.from || ""}${rangeOperator}${opt.to || ""}`);
  }
  if (filterString(opt.file)) {
    command2.push("--follow", pathspec(opt.file));
  }
  appendTaskOptions(userOptions(opt), command2);
  return {
    fields,
    splitter,
    commands: [...command2, ...suffix]
  };
}
function logTask(splitter, fields, customArgs) {
  const parser42 = createListLogSummaryParser(splitter, fields, logFormatFromCommand(customArgs));
  return {
    commands: ["log", ...customArgs],
    format: "utf-8",
    parser: parser42
  };
}
function log_default() {
  return {
    log(...rest) {
      const next = trailingFunctionArgument(arguments);
      const options2 = parseLogOptions(
        trailingOptionsArgument(arguments),
        filterType(arguments[0], filterArray)
      );
      const task = rejectDeprecatedSignatures(...rest) || validateLogFormatConfig(options2.commands) || createLogTask(options2);
      return this._runTask(task, next);
    }
  };
  function createLogTask(options2) {
    return logTask(options2.splitter, options2.fields, options2.commands);
  }
  __name(createLogTask, "createLogTask");
  function rejectDeprecatedSignatures(from, to) {
    return filterString(from) && filterString(to) && configurationErrorTask(
      `git.log(string, string) should be replaced with git.log({ from: string, to: string })`
    );
  }
  __name(rejectDeprecatedSignatures, "rejectDeprecatedSignatures");
}
function objectEnumerationResult(remoteMessages) {
  return remoteMessages.objects = remoteMessages.objects || {
    compressing: 0,
    counting: 0,
    enumerating: 0,
    packReused: 0,
    reused: { count: 0, delta: 0 },
    total: { count: 0, delta: 0 }
  };
}
function asObjectCount(source2) {
  const count = /^\s*(\d+)/.exec(source2);
  const delta = /delta (\d+)/i.exec(source2);
  return {
    count: asNumber(count && count[1] || "0"),
    delta: asNumber(delta && delta[1] || "0")
  };
}
function parseRemoteMessages(_stdOut, stdErr) {
  return parseStringResponse({ remoteMessages: new RemoteMessageSummary() }, parsers2, stdErr);
}
function parsePullErrorResult(stdOut, stdErr) {
  const pullError = parseStringResponse(new PullFailedSummary(), errorParsers, [stdOut, stdErr]);
  return pullError.message && pullError;
}
function mergeTask(customArgs) {
  if (!customArgs.length) {
    return configurationErrorTask("Git.merge requires at least one option");
  }
  return {
    commands: ["merge", ...customArgs],
    format: "utf-8",
    parser(stdOut, stdErr) {
      const merge3 = parseMergeResult(stdOut, stdErr);
      if (merge3.failed) {
        throw new GitResponseError(merge3);
      }
      return merge3;
    }
  };
}
function pushResultPushedItem(local, remote, status) {
  const deleted = status.includes("deleted");
  const tag2 = status.includes("tag") || /^refs\/tags/.test(local);
  const alreadyUpdated = !status.includes("new");
  return {
    deleted,
    tag: tag2,
    branch: !tag2,
    new: !alreadyUpdated,
    alreadyUpdated,
    local,
    remote
  };
}
function pushTagsTask(ref = {}, customArgs) {
  append(customArgs, "--tags");
  return pushTask(ref, customArgs);
}
function pushTask(ref = {}, customArgs) {
  const commands = ["push", ...customArgs];
  if (ref.branch) {
    commands.splice(1, 0, ref.branch);
  }
  if (ref.remote) {
    commands.splice(1, 0, ref.remote);
  }
  remove(commands, "-v");
  append(commands, "--verbose");
  append(commands, "--porcelain");
  return {
    commands,
    format: "utf-8",
    parser: parsePushResult
  };
}
function show_default() {
  return {
    showBuffer() {
      const commands = ["show", ...getTrailingOptions(arguments, 1)];
      if (!commands.includes("--binary")) {
        commands.splice(1, 0, "--binary");
      }
      return this._runTask(
        straightThroughBufferTask(commands),
        trailingFunctionArgument(arguments)
      );
    },
    show() {
      const commands = ["show", ...getTrailingOptions(arguments, 1)];
      return this._runTask(
        straightThroughStringTask(commands),
        trailingFunctionArgument(arguments)
      );
    }
  };
}
function renamedFile(line) {
  const [to, from] = line.split(NULL2);
  return {
    from: from || to,
    to
  };
}
function parser3(indexX, indexY, handler) {
  return [`${indexX}${indexY}`, handler];
}
function conflicts(indexX, ...indexY) {
  return indexY.map((y) => parser3(indexX, y, (result, file) => append(result.conflicted, file)));
}
function splitLine(result, lineStr) {
  const trimmed2 = lineStr.trim();
  switch (" ") {
    case trimmed2.charAt(2):
      return data(trimmed2.charAt(0), trimmed2.charAt(1), trimmed2.substr(3));
    case trimmed2.charAt(1):
      return data(" ", trimmed2.charAt(0), trimmed2.substr(2));
    default:
      return;
  }
  function data(index, workingDir, path108) {
    const raw2 = `${index}${workingDir}`;
    const handler = parsers6.get(raw2);
    if (handler) {
      handler(result, path108);
    }
    if (raw2 !== "##" && raw2 !== "!!") {
      result.files.push(new FileStatusSummary(path108, index, workingDir));
    }
  }
  __name(data, "data");
}
function statusTask(customArgs) {
  const commands = [
    "status",
    "--porcelain",
    "-b",
    "-u",
    "--null",
    ...customArgs.filter((arg) => !ignoredOptions.includes(arg))
  ];
  return {
    format: "utf-8",
    commands,
    parser(text) {
      return parseStatusSummary(text);
    }
  };
}
function versionResponse(major2 = 0, minor = 0, patch = 0, agent = "", installed = true) {
  return Object.defineProperty(
    {
      major: major2,
      minor,
      patch,
      agent,
      installed
    },
    "toString",
    {
      value() {
        return `${this.major}.${this.minor}.${this.patch}`;
      },
      configurable: false,
      enumerable: false
    }
  );
}
function notInstalledResponse() {
  return versionResponse(0, 0, 0, "", false);
}
function version_default2() {
  return {
    version() {
      return this._runTask({
        commands: ["--version"],
        format: "utf-8",
        parser: versionParser,
        onError(result, error, done, fail) {
          if (result.exitCode === -2) {
            return done(Buffer.from(NOT_INSTALLED));
          }
          fail(error);
        }
      });
    }
  };
}
function versionParser(stdOut) {
  if (stdOut === NOT_INSTALLED) {
    return notInstalledResponse();
  }
  return parseStringResponse(versionResponse(0, 0, 0, stdOut), parsers7, stdOut);
}
function applyPatchTask(patches, customArgs) {
  return straightThroughStringTask(["apply", ...customArgs, ...patches]);
}
function branchDeletionSuccess(branch, hash) {
  return {
    branch,
    hash,
    success: true
  };
}
function branchDeletionFailure(branch) {
  return {
    branch,
    hash: null,
    success: false
  };
}
function hasBranchDeletionError(data, processExitCode) {
  return processExitCode === 1 && deleteErrorRegex.test(data);
}
function branchStatus(input) {
  return input ? input.charAt(0) : "";
}
function parseBranchSummary(stdOut) {
  return parseStringResponse(new BranchSummaryResult(), parsers9, stdOut);
}
function containsDeleteBranchCommand(commands) {
  const deleteCommands = ["-d", "-D", "--delete"];
  return commands.some((command2) => deleteCommands.includes(command2));
}
function branchTask(customArgs) {
  const isDelete = containsDeleteBranchCommand(customArgs);
  const commands = ["branch", ...customArgs];
  if (commands.length === 1) {
    commands.push("-a");
  }
  if (!commands.includes("-v")) {
    commands.splice(1, 0, "-v");
  }
  return {
    format: "utf-8",
    commands,
    parser(stdOut, stdErr) {
      if (isDelete) {
        return parseBranchDeletions(stdOut, stdErr).all[0];
      }
      return parseBranchSummary(stdOut);
    }
  };
}
function branchLocalTask() {
  const parser42 = parseBranchSummary;
  return {
    format: "utf-8",
    commands: ["branch", "-v"],
    parser: parser42
  };
}
function deleteBranchesTask(branches, forceDelete = false) {
  return {
    format: "utf-8",
    commands: ["branch", "-v", forceDelete ? "-D" : "-d", ...branches],
    parser(stdOut, stdErr) {
      return parseBranchDeletions(stdOut, stdErr);
    },
    onError({ exitCode, stdOut }, error, done, fail) {
      if (!hasBranchDeletionError(String(error), exitCode)) {
        return fail(error);
      }
      done(stdOut);
    }
  };
}
function deleteBranchTask(branch, forceDelete = false) {
  const task = {
    format: "utf-8",
    commands: ["branch", "-v", forceDelete ? "-D" : "-d", branch],
    parser(stdOut, stdErr) {
      return parseBranchDeletions(stdOut, stdErr).branches[branch];
    },
    onError({ exitCode, stdErr, stdOut }, error, _, fail) {
      if (!hasBranchDeletionError(String(error), exitCode)) {
        return fail(error);
      }
      throw new GitResponseError(
        task.parser(bufferToString(stdOut), bufferToString(stdErr)),
        String(error)
      );
    }
  };
  return task;
}
function checkIgnoreTask(paths) {
  return {
    commands: ["check-ignore", ...paths],
    format: "utf-8",
    parser: parseCheckIgnore
  };
}
function disallowedCommand(command2) {
  return /^--upload-pack(=|$)/.test(command2);
}
function cloneTask(repo, directory, customArgs) {
  const commands = ["clone", ...customArgs];
  filterString(repo) && commands.push(repo);
  filterString(directory) && commands.push(directory);
  const banned = commands.find(disallowedCommand);
  if (banned) {
    return configurationErrorTask(`git.fetch: potential exploit argument blocked.`);
  }
  return straightThroughStringTask(commands);
}
function cloneMirrorTask(repo, directory, customArgs) {
  append(customArgs, "--mirror");
  return cloneTask(repo, directory, customArgs);
}
function parseFetchResult(stdOut, stdErr) {
  const result = {
    raw: stdOut,
    remote: null,
    branches: [],
    tags: [],
    updated: [],
    deleted: []
  };
  return parseStringResponse(result, parsers10, [stdOut, stdErr]);
}
function disallowedCommand2(command2) {
  return /^--upload-pack(=|$)/.test(command2);
}
function fetchTask(remote, branch, customArgs) {
  const commands = ["fetch", ...customArgs];
  if (remote && branch) {
    commands.push(remote, branch);
  }
  const banned = commands.find(disallowedCommand2);
  if (banned) {
    return configurationErrorTask(`git.fetch: potential exploit argument blocked.`);
  }
  return {
    commands,
    format: "utf-8",
    parser: parseFetchResult
  };
}
function parseMoveResult(stdOut) {
  return parseStringResponse({ moves: [] }, parsers11, stdOut);
}
function moveTask(from, to) {
  return {
    commands: ["mv", "-v", ...asArray(from), to],
    format: "utf-8",
    parser: parseMoveResult
  };
}
function pullTask(remote, branch, customArgs) {
  const commands = ["pull", ...customArgs];
  if (remote && branch) {
    commands.splice(1, 0, remote, branch);
  }
  return {
    commands,
    format: "utf-8",
    parser(stdOut, stdErr) {
      return parsePullResult(stdOut, stdErr);
    },
    onError(result, _error, _done, fail) {
      const pullError = parsePullErrorResult(
        bufferToString(result.stdOut),
        bufferToString(result.stdErr)
      );
      if (pullError) {
        return fail(new GitResponseError(pullError));
      }
      fail(_error);
    }
  };
}
function parseGetRemotes(text) {
  const remotes = {};
  forEach(text, ([name3]) => remotes[name3] = { name: name3 });
  return Object.values(remotes);
}
function parseGetRemotesVerbose(text) {
  const remotes = {};
  forEach(text, ([name3, url2, purpose]) => {
    if (!remotes.hasOwnProperty(name3)) {
      remotes[name3] = {
        name: name3,
        refs: { fetch: "", push: "" }
      };
    }
    if (purpose && url2) {
      remotes[name3].refs[purpose.replace(/[^a-z]/g, "")] = url2;
    }
  });
  return Object.values(remotes);
}
function forEach(text, handler) {
  forEachLineWithContent(text, (line) => handler(line.split(/\s+/)));
}
function addRemoteTask(remoteName, remoteRepo, customArgs) {
  return straightThroughStringTask(["remote", "add", ...customArgs, remoteName, remoteRepo]);
}
function getRemotesTask(verbose) {
  const commands = ["remote"];
  if (verbose) {
    commands.push("-v");
  }
  return {
    commands,
    format: "utf-8",
    parser: verbose ? parseGetRemotesVerbose : parseGetRemotes
  };
}
function listRemotesTask(customArgs) {
  const commands = [...customArgs];
  if (commands[0] !== "ls-remote") {
    commands.unshift("ls-remote");
  }
  return straightThroughStringTask(commands);
}
function remoteTask(customArgs) {
  const commands = [...customArgs];
  if (commands[0] !== "remote") {
    commands.unshift("remote");
  }
  return straightThroughStringTask(commands);
}
function removeRemoteTask(remoteName) {
  return straightThroughStringTask(["remote", "remove", remoteName]);
}
function stashListTask(opt = {}, customArgs) {
  const options2 = parseLogOptions(opt);
  const commands = ["stash", "list", ...options2.commands, ...customArgs];
  const parser42 = createListLogSummaryParser(
    options2.splitter,
    options2.fields,
    logFormatFromCommand(commands)
  );
  return validateLogFormatConfig(commands) || {
    commands,
    format: "utf-8",
    parser: parser42
  };
}
function addSubModuleTask(repo, path108) {
  return subModuleTask(["add", repo, path108]);
}
function initSubModuleTask(customArgs) {
  return subModuleTask(["init", ...customArgs]);
}
function subModuleTask(customArgs) {
  const commands = [...customArgs];
  if (commands[0] !== "submodule") {
    commands.unshift("submodule");
  }
  return straightThroughStringTask(commands);
}
function updateSubModuleTask(customArgs) {
  return subModuleTask(["update", ...customArgs]);
}
function singleSorted(a, b) {
  const aIsNum = isNaN(a);
  const bIsNum = isNaN(b);
  if (aIsNum !== bIsNum) {
    return aIsNum ? 1 : -1;
  }
  return aIsNum ? sorted(a, b) : 0;
}
function sorted(a, b) {
  return a === b ? 0 : a > b ? 1 : -1;
}
function trimmed(input) {
  return input.trim();
}
function toNumber(input) {
  if (typeof input === "string") {
    return parseInt(input.replace(/^\D+/g, ""), 10) || 0;
  }
  return 0;
}
function tagListTask(customArgs = []) {
  const hasCustomSort = customArgs.some((option2) => /^--sort=/.test(option2));
  return {
    format: "utf-8",
    commands: ["tag", "-l", ...customArgs],
    parser(text) {
      return parseTagList(text, hasCustomSort);
    }
  };
}
function addTagTask(name3) {
  return {
    format: "utf-8",
    commands: ["tag", name3],
    parser() {
      return { name: name3 };
    }
  };
}
function addAnnotatedTagTask(name3, tagMessage) {
  return {
    format: "utf-8",
    commands: ["tag", "-a", "-m", tagMessage, name3],
    parser() {
      return { name: name3 };
    }
  };
}
function abortPlugin(signal) {
  if (!signal) {
    return;
  }
  const onSpawnAfter = {
    type: "spawn.after",
    action(_data, context2) {
      function kill() {
        context2.kill(new GitPluginError(void 0, "abort", "Abort signal received"));
      }
      __name(kill, "kill");
      signal.addEventListener("abort", kill);
      context2.spawned.on("close", () => signal.removeEventListener("abort", kill));
    }
  };
  const onSpawnBefore = {
    type: "spawn.before",
    action(_data, context2) {
      if (signal.aborted) {
        context2.kill(new GitPluginError(void 0, "abort", "Abort already signaled"));
      }
    }
  };
  return [onSpawnBefore, onSpawnAfter];
}
function isConfigSwitch(arg) {
  return typeof arg === "string" && arg.trim().toLowerCase() === "-c";
}
function preventProtocolOverride(arg, next) {
  if (!isConfigSwitch(arg)) {
    return;
  }
  if (!/^\s*protocol(.[a-z]+)?.allow/.test(next)) {
    return;
  }
  throw new GitPluginError(
    void 0,
    "unsafe",
    "Configuring protocol.allow is not permitted without enabling allowUnsafeExtProtocol"
  );
}
function preventUploadPack(arg, method) {
  if (/^\s*--(upload|receive)-pack/.test(arg)) {
    throw new GitPluginError(
      void 0,
      "unsafe",
      `Use of --upload-pack or --receive-pack is not permitted without enabling allowUnsafePack`
    );
  }
  if (method === "clone" && /^\s*-u\b/.test(arg)) {
    throw new GitPluginError(
      void 0,
      "unsafe",
      `Use of clone with option -u is not permitted without enabling allowUnsafePack`
    );
  }
  if (method === "push" && /^\s*--exec\b/.test(arg)) {
    throw new GitPluginError(
      void 0,
      "unsafe",
      `Use of push with option --exec is not permitted without enabling allowUnsafePack`
    );
  }
}
function blockUnsafeOperationsPlugin({
  allowUnsafeProtocolOverride = false,
  allowUnsafePack = false
} = {}) {
  return {
    type: "spawn.args",
    action(args, context2) {
      args.forEach((current, index) => {
        const next = index < args.length ? args[index + 1] : "";
        allowUnsafeProtocolOverride || preventProtocolOverride(current, next);
        allowUnsafePack || preventUploadPack(current, context2.method);
      });
      return args;
    }
  };
}
function commandConfigPrefixingPlugin(configuration) {
  const prefix = prefixedArray(configuration, "-c");
  return {
    type: "spawn.args",
    action(data) {
      return [...prefix, ...data];
    }
  };
}
function completionDetectionPlugin({
  onClose = true,
  onExit = 50
} = {}) {
  function createEvents() {
    let exitCode = -1;
    const events = {
      close: (0, import_promise_deferred2.deferred)(),
      closeTimeout: (0, import_promise_deferred2.deferred)(),
      exit: (0, import_promise_deferred2.deferred)(),
      exitTimeout: (0, import_promise_deferred2.deferred)()
    };
    const result = Promise.race([
      onClose === false ? never : events.closeTimeout.promise,
      onExit === false ? never : events.exitTimeout.promise
    ]);
    configureTimeout(onClose, events.close, events.closeTimeout);
    configureTimeout(onExit, events.exit, events.exitTimeout);
    return {
      close(code2) {
        exitCode = code2;
        events.close.done();
      },
      exit(code2) {
        exitCode = code2;
        events.exit.done();
      },
      get exitCode() {
        return exitCode;
      },
      result
    };
  }
  __name(createEvents, "createEvents");
  function configureTimeout(flag, event, timeout2) {
    if (flag === false) {
      return;
    }
    (flag === true ? event.promise : event.promise.then(() => delay2(flag))).then(timeout2.done);
  }
  __name(configureTimeout, "configureTimeout");
  return {
    type: "spawn.after",
    async action(_data, { spawned, close }) {
      const events = createEvents();
      let deferClose = true;
      let quickClose = /* @__PURE__ */ __name(() => void (deferClose = false), "quickClose");
      spawned.stdout?.on("data", quickClose);
      spawned.stderr?.on("data", quickClose);
      spawned.on("error", quickClose);
      spawned.on("close", (code2) => events.close(code2));
      spawned.on("exit", (code2) => events.exit(code2));
      try {
        await events.result;
        if (deferClose) {
          await delay2(50);
        }
        close(events.exitCode);
      } catch (err) {
        close(events.exitCode, err);
      }
    }
  };
}
function isBadArgument(arg) {
  return !arg || !/^([a-z]:)?([a-z0-9/.\\_-]+)$/i.test(arg);
}
function toBinaryConfig(input, allowUnsafe) {
  if (input.length < 1 || input.length > 2) {
    throw new GitPluginError(void 0, "binary", WRONG_NUMBER_ERR);
  }
  const isBad = input.some(isBadArgument);
  if (isBad) {
    if (allowUnsafe) {
      console.warn(WRONG_CHARS_ERR);
    } else {
      throw new GitPluginError(void 0, "binary", WRONG_CHARS_ERR);
    }
  }
  const [binary, prefix] = input;
  return {
    binary,
    prefix
  };
}
function customBinaryPlugin(plugins, input = ["git"], allowUnsafe = false) {
  let config = toBinaryConfig(asArray(input), allowUnsafe);
  plugins.on("binary", (input2) => {
    config = toBinaryConfig(asArray(input2), allowUnsafe);
  });
  plugins.append("spawn.binary", () => {
    return config.binary;
  });
  plugins.append("spawn.args", (data) => {
    return config.prefix ? [config.prefix, ...data] : data;
  });
}
function isTaskError(result) {
  return !!(result.exitCode && result.stdErr.length);
}
function getErrorMessage2(result) {
  return Buffer.concat([...result.stdOut, ...result.stdErr]);
}
function errorDetectionHandler(overwrite = false, isError = isTaskError, errorMessage = getErrorMessage2) {
  return (error, result) => {
    if (!overwrite && error || !isError(result)) {
      return error;
    }
    return errorMessage(result);
  };
}
function errorDetectionPlugin(config) {
  return {
    type: "task.error",
    action(data, context2) {
      const error = config(data.error, {
        stdErr: context2.stdErr,
        stdOut: context2.stdOut,
        exitCode: context2.exitCode
      });
      if (Buffer.isBuffer(error)) {
        return { error: new GitError(void 0, error.toString("utf-8")) };
      }
      return {
        error
      };
    }
  };
}
function progressMonitorPlugin(progress) {
  const progressCommand = "--progress";
  const progressMethods = ["checkout", "clone", "fetch", "pull", "push"];
  const onProgress = {
    type: "spawn.after",
    action(_data, context2) {
      if (!context2.commands.includes(progressCommand)) {
        return;
      }
      context2.spawned.stderr?.on("data", (chunk) => {
        const message = /^([\s\S]+?):\s*(\d+)% \((\d+)\/(\d+)\)/.exec(chunk.toString("utf8"));
        if (!message) {
          return;
        }
        progress({
          method: context2.method,
          stage: progressEventStage(message[1]),
          progress: asNumber(message[2]),
          processed: asNumber(message[3]),
          total: asNumber(message[4])
        });
      });
    }
  };
  const onArgs = {
    type: "spawn.args",
    action(args, context2) {
      if (!progressMethods.includes(context2.method)) {
        return args;
      }
      return including(args, progressCommand);
    }
  };
  return [onArgs, onProgress];
}
function progressEventStage(input) {
  return String(input.toLowerCase().split(" ", 1)) || "unknown";
}
function spawnOptionsPlugin(spawnOptions) {
  const options2 = pick(spawnOptions, ["uid", "gid"]);
  return {
    type: "spawn.options",
    action(data) {
      return { ...options2, ...data };
    }
  };
}
function timeoutPlugin({
  block: block2,
  stdErr = true,
  stdOut = true
}) {
  if (block2 > 0) {
    return {
      type: "spawn.after",
      action(_data, context2) {
        let timeout2;
        function wait() {
          timeout2 && clearTimeout(timeout2);
          timeout2 = setTimeout(kill, block2);
        }
        __name(wait, "wait");
        function stop2() {
          context2.spawned.stdout?.off("data", wait);
          context2.spawned.stderr?.off("data", wait);
          context2.spawned.off("exit", stop2);
          context2.spawned.off("close", stop2);
          timeout2 && clearTimeout(timeout2);
        }
        __name(stop2, "stop");
        function kill() {
          stop2();
          context2.kill(new GitPluginError(void 0, "timeout", `block timeout reached`));
        }
        __name(kill, "kill");
        stdOut && context2.spawned.stdout?.on("data", wait);
        stdErr && context2.spawned.stderr?.on("data", wait);
        context2.spawned.on("exit", stop2);
        context2.spawned.on("close", stop2);
        wait();
      }
    };
  }
}
function suffixPathsPlugin() {
  return {
    type: "spawn.args",
    action(data) {
      const prefix = [];
      let suffix;
      function append2(args) {
        (suffix = suffix || []).push(...args);
      }
      __name(append2, "append2");
      for (let i = 0; i < data.length; i++) {
        const param = data[i];
        if (isPathSpec(param)) {
          append2(toPaths(param));
          continue;
        }
        if (param === "--") {
          append2(
            data.slice(i + 1).flatMap((item) => isPathSpec(item) && toPaths(item) || item)
          );
          break;
        }
        prefix.push(param);
      }
      return !suffix ? prefix : [...prefix, "--", ...suffix.map(String)];
    }
  };
}
function gitInstanceFactory(baseDir, options2) {
  const plugins = new PluginStore();
  const config = createInstanceConfig(
    baseDir && (typeof baseDir === "string" ? { baseDir } : baseDir) || {},
    options2
  );
  if (!folderExists(config.baseDir)) {
    throw new GitConstructError(
      config,
      `Cannot use simple-git on a directory that does not exist`
    );
  }
  if (Array.isArray(config.config)) {
    plugins.add(commandConfigPrefixingPlugin(config.config));
  }
  plugins.add(blockUnsafeOperationsPlugin(config.unsafe));
  plugins.add(suffixPathsPlugin());
  plugins.add(completionDetectionPlugin(config.completion));
  config.abort && plugins.add(abortPlugin(config.abort));
  config.progress && plugins.add(progressMonitorPlugin(config.progress));
  config.timeout && plugins.add(timeoutPlugin(config.timeout));
  config.spawnOptions && plugins.add(spawnOptionsPlugin(config.spawnOptions));
  plugins.add(errorDetectionPlugin(errorDetectionHandler(true)));
  config.errors && plugins.add(errorDetectionPlugin(config.errors));
  customBinaryPlugin(plugins, config.binary, config.unsafe?.allowUnsafeCustomBinary);
  return new Git(config, plugins);
}
var import_file_exists, import_debug, import_promise_deferred, import_promise_deferred2, __defProp2, __getOwnPropDesc2, __getOwnPropNames2, __hasOwnProp2, __esm2, __commonJS2, __export2, __copyProps2, __toCommonJS2, cache3, init_pathspec, GitError, init_git_error, GitResponseError, init_git_response_error, TaskConfigurationError, init_task_configuration_error, NULL2, NOOP, objectToString, init_util3, filterArray, filterString, filterStringArray, filterStringOrStringArray, filterHasLength, init_argument_filters, ExitCodes, init_exit_codes, GitOutputStreams, init_git_output_streams, LineParser, RemoteLineParser, init_line_parser, defaultOptions, init_simple_git_options, init_task_options, init_task_parser, utils_exports, init_utils6, check_is_repo_exports, CheckRepoActions, onError, parser, init_check_is_repo, CleanResponse, removalRegexp, dryRunRemovalRegexp, isFolderRegexp, init_CleanSummary, task_exports, EMPTY_COMMANDS, init_task2, clean_exports, CONFIG_ERROR_INTERACTIVE_MODE, CONFIG_ERROR_MODE_REQUIRED, CONFIG_ERROR_UNKNOWN_OPTION, CleanOptions, CleanOptionValues, init_clean, ConfigList, init_ConfigList, GitConfigScope, init_config2, DiffNameStatus, diffNameStatus, init_diff_name_status, disallowedOptions, Query, _a3, GrepQuery, init_grep, reset_exports, ResetMode, ResetModes, init_reset, init_git_logger, TasksPendingQueue, init_tasks_pending_queue, GitExecutorChain, init_git_executor_chain, git_executor_exports, GitExecutor, init_git_executor, init_task_callback, init_change_working_directory, init_checkout, parser2, init_count_objects, parsers, init_parse_commit, init_commit, init_first_commit, init_hash_object, InitSummary, initResponseRegex, reInitResponseRegex, init_InitSummary, bareCommand, init_init, logFormatRegex, init_log_format, DiffSummary, init_DiffSummary, statParser, numStatParser, nameOnlyParser, nameStatusParser, diffSummaryParsers, init_parse_diff_summary, START_BOUNDARY, COMMIT_BOUNDARY, SPLITTER, defaultFieldNames, init_parse_list_log_summary, diff_exports, init_diff, excludeOptions, init_log2, MergeSummaryConflict, MergeSummaryDetail, init_MergeSummary, PullSummary, PullFailedSummary, init_PullSummary, remoteMessagesObjectParsers, init_parse_remote_objects, parsers2, RemoteMessageSummary, init_parse_remote_messages, FILE_UPDATE_REGEX, SUMMARY_REGEX, ACTION_REGEX, parsers3, errorParsers, parsePullDetail, parsePullResult, init_parse_pull, parsers4, parseMergeResult, parseMergeDetail, init_parse_merge, init_merge, parsers5, parsePushResult, parsePushDetail, init_parse_push, push_exports, init_push, init_show, fromPathRegex, FileStatusSummary, init_FileStatusSummary, StatusSummary, parsers6, parseStatusSummary, init_StatusSummary, ignoredOptions, init_status2, NOT_INSTALLED, parsers7, init_version4, simple_git_api_exports, SimpleGitApi, init_simple_git_api, scheduler_exports, createScheduledTask, Scheduler, init_scheduler, apply_patch_exports, init_apply_patch, BranchDeletionBatch, init_BranchDeleteSummary, deleteSuccessRegex, deleteErrorRegex, parsers8, parseBranchDeletions, init_parse_branch_delete, BranchSummaryResult, init_BranchSummary, parsers9, init_parse_branch, branch_exports, init_branch, parseCheckIgnore, init_CheckIgnore, check_ignore_exports, init_check_ignore, clone_exports, init_clone, parsers10, init_parse_fetch, fetch_exports, init_fetch, parsers11, init_parse_move, move_exports, init_move, pull_exports, init_pull, init_GetRemoteSummary, remote_exports, init_remote, stash_list_exports, init_stash_list, sub_module_exports, init_sub_module, TagList, parseTagList, init_TagList, tag_exports, init_tag, require_git, GitConstructError, GitPluginError, never, WRONG_NUMBER_ERR, WRONG_CHARS_ERR, PluginStore, Git, simpleGit;
var init_esm10 = __esm({
  "node_modules/simple-git/dist/esm/index.js"() {
    init_esbuild_shims();
    import_file_exists = __toESM(require_dist4(), 1);
    import_debug = __toESM(require_src(), 1);
    import_promise_deferred = __toESM(require_dist5(), 1);
    import_promise_deferred2 = __toESM(require_dist5(), 1);
    __defProp2 = Object.defineProperty;
    __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
    __getOwnPropNames2 = Object.getOwnPropertyNames;
    __hasOwnProp2 = Object.prototype.hasOwnProperty;
    __esm2 = /* @__PURE__ */ __name((fn, res) => /* @__PURE__ */ __name(function __init() {
      return fn && (res = (0, fn[__getOwnPropNames2(fn)[0]])(fn = 0)), res;
    }, "__init"), "__esm");
    __commonJS2 = /* @__PURE__ */ __name((cb, mod2) => /* @__PURE__ */ __name(function __require2() {
      return mod2 || (0, cb[__getOwnPropNames2(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
    }, "__require"), "__commonJS");
    __export2 = /* @__PURE__ */ __name((target, all2) => {
      for (var name3 in all2)
        __defProp2(target, name3, { get: all2[name3], enumerable: true });
    }, "__export");
    __copyProps2 = /* @__PURE__ */ __name((to, from, except, desc2) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames2(from))
          if (!__hasOwnProp2.call(to, key) && key !== except)
            __defProp2(to, key, { get: /* @__PURE__ */ __name(() => from[key], "get"), enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable });
      }
      return to;
    }, "__copyProps");
    __toCommonJS2 = /* @__PURE__ */ __name((mod2) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod2), "__toCommonJS");
    __name(pathspec, "pathspec");
    __name(isPathSpec, "isPathSpec");
    __name(toPaths, "toPaths");
    init_pathspec = __esm2({
      "src/lib/args/pathspec.ts"() {
        "use strict";
        cache3 = /* @__PURE__ */ new WeakMap();
      }
    });
    init_git_error = __esm2({
      "src/lib/errors/git-error.ts"() {
        "use strict";
        GitError = class extends Error {
          static {
            __name(this, "GitError");
          }
          constructor(task, message) {
            super(message);
            this.task = task;
            Object.setPrototypeOf(this, new.target.prototype);
          }
        };
      }
    });
    init_git_response_error = __esm2({
      "src/lib/errors/git-response-error.ts"() {
        "use strict";
        init_git_error();
        GitResponseError = class extends GitError {
          static {
            __name(this, "GitResponseError");
          }
          constructor(git, message) {
            super(void 0, message || String(git));
            this.git = git;
          }
        };
      }
    });
    init_task_configuration_error = __esm2({
      "src/lib/errors/task-configuration-error.ts"() {
        "use strict";
        init_git_error();
        TaskConfigurationError = class extends GitError {
          static {
            __name(this, "TaskConfigurationError");
          }
          constructor(message) {
            super(void 0, message);
          }
        };
      }
    });
    __name(asFunction, "asFunction");
    __name(isUserFunction, "isUserFunction");
    __name(splitOn, "splitOn");
    __name(first, "first");
    __name(last, "last");
    __name(isArrayLike, "isArrayLike");
    __name(toLinesWithContent, "toLinesWithContent");
    __name(forEachLineWithContent, "forEachLineWithContent");
    __name(folderExists, "folderExists");
    __name(append, "append");
    __name(including, "including");
    __name(remove, "remove");
    __name(asArray, "asArray");
    __name(asCamelCase, "asCamelCase");
    __name(asStringArray, "asStringArray");
    __name(asNumber, "asNumber");
    __name(prefixedArray, "prefixedArray");
    __name(bufferToString, "bufferToString");
    __name(pick, "pick");
    __name(delay2, "delay");
    __name(orVoid, "orVoid");
    init_util3 = __esm2({
      "src/lib/utils/util.ts"() {
        "use strict";
        NULL2 = "\0";
        NOOP = /* @__PURE__ */ __name(() => {
        }, "NOOP");
        objectToString = Object.prototype.toString.call.bind(Object.prototype.toString);
      }
    });
    __name(filterType, "filterType");
    __name(filterPrimitives, "filterPrimitives");
    __name(filterPlainObject, "filterPlainObject");
    __name(filterFunction, "filterFunction");
    init_argument_filters = __esm2({
      "src/lib/utils/argument-filters.ts"() {
        "use strict";
        init_util3();
        init_pathspec();
        filterArray = /* @__PURE__ */ __name((input) => {
          return Array.isArray(input);
        }, "filterArray");
        filterString = /* @__PURE__ */ __name((input) => {
          return typeof input === "string";
        }, "filterString");
        filterStringArray = /* @__PURE__ */ __name((input) => {
          return Array.isArray(input) && input.every(filterString);
        }, "filterStringArray");
        filterStringOrStringArray = /* @__PURE__ */ __name((input) => {
          return filterString(input) || Array.isArray(input) && input.every(filterString);
        }, "filterStringOrStringArray");
        filterHasLength = /* @__PURE__ */ __name((input) => {
          if (input == null || "number|boolean|function".includes(typeof input)) {
            return false;
          }
          return Array.isArray(input) || typeof input === "string" || typeof input.length === "number";
        }, "filterHasLength");
      }
    });
    init_exit_codes = __esm2({
      "src/lib/utils/exit-codes.ts"() {
        "use strict";
        ExitCodes = /* @__PURE__ */ ((ExitCodes2) => {
          ExitCodes2[ExitCodes2["SUCCESS"] = 0] = "SUCCESS";
          ExitCodes2[ExitCodes2["ERROR"] = 1] = "ERROR";
          ExitCodes2[ExitCodes2["NOT_FOUND"] = -2] = "NOT_FOUND";
          ExitCodes2[ExitCodes2["UNCLEAN"] = 128] = "UNCLEAN";
          return ExitCodes2;
        })(ExitCodes || {});
      }
    });
    init_git_output_streams = __esm2({
      "src/lib/utils/git-output-streams.ts"() {
        "use strict";
        GitOutputStreams = class _GitOutputStreams {
          static {
            __name(this, "_GitOutputStreams");
          }
          constructor(stdOut, stdErr) {
            this.stdOut = stdOut;
            this.stdErr = stdErr;
          }
          asStrings() {
            return new _GitOutputStreams(this.stdOut.toString("utf8"), this.stdErr.toString("utf8"));
          }
        };
      }
    });
    init_line_parser = __esm2({
      "src/lib/utils/line-parser.ts"() {
        "use strict";
        LineParser = class {
          static {
            __name(this, "LineParser");
          }
          constructor(regExp, useMatches) {
            this.matches = [];
            this.parse = (line, target) => {
              this.resetMatches();
              if (!this._regExp.every((reg, index) => this.addMatch(reg, index, line(index)))) {
                return false;
              }
              return this.useMatches(target, this.prepareMatches()) !== false;
            };
            this._regExp = Array.isArray(regExp) ? regExp : [regExp];
            if (useMatches) {
              this.useMatches = useMatches;
            }
          }
          // @ts-ignore
          useMatches(target, match2) {
            throw new Error(`LineParser:useMatches not implemented`);
          }
          resetMatches() {
            this.matches.length = 0;
          }
          prepareMatches() {
            return this.matches;
          }
          addMatch(reg, index, line) {
            const matched = line && reg.exec(line);
            if (matched) {
              this.pushMatch(index, matched);
            }
            return !!matched;
          }
          pushMatch(_index, matched) {
            this.matches.push(...matched.slice(1));
          }
        };
        RemoteLineParser = class extends LineParser {
          static {
            __name(this, "RemoteLineParser");
          }
          addMatch(reg, index, line) {
            return /^remote:\s/.test(String(line)) && super.addMatch(reg, index, line);
          }
          pushMatch(index, matched) {
            if (index > 0 || matched.length > 1) {
              super.pushMatch(index, matched);
            }
          }
        };
      }
    });
    __name(createInstanceConfig, "createInstanceConfig");
    init_simple_git_options = __esm2({
      "src/lib/utils/simple-git-options.ts"() {
        "use strict";
        defaultOptions = {
          binary: "git",
          maxConcurrentProcesses: 5,
          config: [],
          trimmed: false
        };
      }
    });
    __name(appendTaskOptions, "appendTaskOptions");
    __name(getTrailingOptions, "getTrailingOptions");
    __name(trailingArrayArgument, "trailingArrayArgument");
    __name(trailingOptionsArgument, "trailingOptionsArgument");
    __name(trailingFunctionArgument, "trailingFunctionArgument");
    init_task_options = __esm2({
      "src/lib/utils/task-options.ts"() {
        "use strict";
        init_argument_filters();
        init_util3();
        init_pathspec();
      }
    });
    __name(callTaskParser, "callTaskParser");
    __name(parseStringResponse, "parseStringResponse");
    init_task_parser = __esm2({
      "src/lib/utils/task-parser.ts"() {
        "use strict";
        init_util3();
      }
    });
    utils_exports = {};
    __export2(utils_exports, {
      ExitCodes: /* @__PURE__ */ __name(() => ExitCodes, "ExitCodes"),
      GitOutputStreams: /* @__PURE__ */ __name(() => GitOutputStreams, "GitOutputStreams"),
      LineParser: /* @__PURE__ */ __name(() => LineParser, "LineParser"),
      NOOP: /* @__PURE__ */ __name(() => NOOP, "NOOP"),
      NULL: /* @__PURE__ */ __name(() => NULL2, "NULL"),
      RemoteLineParser: /* @__PURE__ */ __name(() => RemoteLineParser, "RemoteLineParser"),
      append: /* @__PURE__ */ __name(() => append, "append"),
      appendTaskOptions: /* @__PURE__ */ __name(() => appendTaskOptions, "appendTaskOptions"),
      asArray: /* @__PURE__ */ __name(() => asArray, "asArray"),
      asCamelCase: /* @__PURE__ */ __name(() => asCamelCase, "asCamelCase"),
      asFunction: /* @__PURE__ */ __name(() => asFunction, "asFunction"),
      asNumber: /* @__PURE__ */ __name(() => asNumber, "asNumber"),
      asStringArray: /* @__PURE__ */ __name(() => asStringArray, "asStringArray"),
      bufferToString: /* @__PURE__ */ __name(() => bufferToString, "bufferToString"),
      callTaskParser: /* @__PURE__ */ __name(() => callTaskParser, "callTaskParser"),
      createInstanceConfig: /* @__PURE__ */ __name(() => createInstanceConfig, "createInstanceConfig"),
      delay: /* @__PURE__ */ __name(() => delay2, "delay"),
      filterArray: /* @__PURE__ */ __name(() => filterArray, "filterArray"),
      filterFunction: /* @__PURE__ */ __name(() => filterFunction, "filterFunction"),
      filterHasLength: /* @__PURE__ */ __name(() => filterHasLength, "filterHasLength"),
      filterPlainObject: /* @__PURE__ */ __name(() => filterPlainObject, "filterPlainObject"),
      filterPrimitives: /* @__PURE__ */ __name(() => filterPrimitives, "filterPrimitives"),
      filterString: /* @__PURE__ */ __name(() => filterString, "filterString"),
      filterStringArray: /* @__PURE__ */ __name(() => filterStringArray, "filterStringArray"),
      filterStringOrStringArray: /* @__PURE__ */ __name(() => filterStringOrStringArray, "filterStringOrStringArray"),
      filterType: /* @__PURE__ */ __name(() => filterType, "filterType"),
      first: /* @__PURE__ */ __name(() => first, "first"),
      folderExists: /* @__PURE__ */ __name(() => folderExists, "folderExists"),
      forEachLineWithContent: /* @__PURE__ */ __name(() => forEachLineWithContent, "forEachLineWithContent"),
      getTrailingOptions: /* @__PURE__ */ __name(() => getTrailingOptions, "getTrailingOptions"),
      including: /* @__PURE__ */ __name(() => including, "including"),
      isUserFunction: /* @__PURE__ */ __name(() => isUserFunction, "isUserFunction"),
      last: /* @__PURE__ */ __name(() => last, "last"),
      objectToString: /* @__PURE__ */ __name(() => objectToString, "objectToString"),
      orVoid: /* @__PURE__ */ __name(() => orVoid, "orVoid"),
      parseStringResponse: /* @__PURE__ */ __name(() => parseStringResponse, "parseStringResponse"),
      pick: /* @__PURE__ */ __name(() => pick, "pick"),
      prefixedArray: /* @__PURE__ */ __name(() => prefixedArray, "prefixedArray"),
      remove: /* @__PURE__ */ __name(() => remove, "remove"),
      splitOn: /* @__PURE__ */ __name(() => splitOn, "splitOn"),
      toLinesWithContent: /* @__PURE__ */ __name(() => toLinesWithContent, "toLinesWithContent"),
      trailingFunctionArgument: /* @__PURE__ */ __name(() => trailingFunctionArgument, "trailingFunctionArgument"),
      trailingOptionsArgument: /* @__PURE__ */ __name(() => trailingOptionsArgument, "trailingOptionsArgument")
    });
    init_utils6 = __esm2({
      "src/lib/utils/index.ts"() {
        "use strict";
        init_argument_filters();
        init_exit_codes();
        init_git_output_streams();
        init_line_parser();
        init_simple_git_options();
        init_task_options();
        init_task_parser();
        init_util3();
      }
    });
    check_is_repo_exports = {};
    __export2(check_is_repo_exports, {
      CheckRepoActions: /* @__PURE__ */ __name(() => CheckRepoActions, "CheckRepoActions"),
      checkIsBareRepoTask: /* @__PURE__ */ __name(() => checkIsBareRepoTask, "checkIsBareRepoTask"),
      checkIsRepoRootTask: /* @__PURE__ */ __name(() => checkIsRepoRootTask, "checkIsRepoRootTask"),
      checkIsRepoTask: /* @__PURE__ */ __name(() => checkIsRepoTask, "checkIsRepoTask")
    });
    __name(checkIsRepoTask, "checkIsRepoTask");
    __name(checkIsRepoRootTask, "checkIsRepoRootTask");
    __name(checkIsBareRepoTask, "checkIsBareRepoTask");
    __name(isNotRepoMessage, "isNotRepoMessage");
    init_check_is_repo = __esm2({
      "src/lib/tasks/check-is-repo.ts"() {
        "use strict";
        init_utils6();
        CheckRepoActions = /* @__PURE__ */ ((CheckRepoActions2) => {
          CheckRepoActions2["BARE"] = "bare";
          CheckRepoActions2["IN_TREE"] = "tree";
          CheckRepoActions2["IS_REPO_ROOT"] = "root";
          return CheckRepoActions2;
        })(CheckRepoActions || {});
        onError = /* @__PURE__ */ __name(({ exitCode }, error, done, fail) => {
          if (exitCode === 128 && isNotRepoMessage(error)) {
            return done(Buffer.from("false"));
          }
          fail(error);
        }, "onError");
        parser = /* @__PURE__ */ __name((text) => {
          return text.trim() === "true";
        }, "parser");
      }
    });
    __name(cleanSummaryParser, "cleanSummaryParser");
    init_CleanSummary = __esm2({
      "src/lib/responses/CleanSummary.ts"() {
        "use strict";
        init_utils6();
        CleanResponse = class {
          static {
            __name(this, "CleanResponse");
          }
          constructor(dryRun) {
            this.dryRun = dryRun;
            this.paths = [];
            this.files = [];
            this.folders = [];
          }
        };
        removalRegexp = /^[a-z]+\s*/i;
        dryRunRemovalRegexp = /^[a-z]+\s+[a-z]+\s*/i;
        isFolderRegexp = /\/$/;
      }
    });
    task_exports = {};
    __export2(task_exports, {
      EMPTY_COMMANDS: /* @__PURE__ */ __name(() => EMPTY_COMMANDS, "EMPTY_COMMANDS"),
      adhocExecTask: /* @__PURE__ */ __name(() => adhocExecTask, "adhocExecTask"),
      configurationErrorTask: /* @__PURE__ */ __name(() => configurationErrorTask, "configurationErrorTask"),
      isBufferTask: /* @__PURE__ */ __name(() => isBufferTask, "isBufferTask"),
      isEmptyTask: /* @__PURE__ */ __name(() => isEmptyTask, "isEmptyTask"),
      straightThroughBufferTask: /* @__PURE__ */ __name(() => straightThroughBufferTask, "straightThroughBufferTask"),
      straightThroughStringTask: /* @__PURE__ */ __name(() => straightThroughStringTask, "straightThroughStringTask")
    });
    __name(adhocExecTask, "adhocExecTask");
    __name(configurationErrorTask, "configurationErrorTask");
    __name(straightThroughStringTask, "straightThroughStringTask");
    __name(straightThroughBufferTask, "straightThroughBufferTask");
    __name(isBufferTask, "isBufferTask");
    __name(isEmptyTask, "isEmptyTask");
    init_task2 = __esm2({
      "src/lib/tasks/task.ts"() {
        "use strict";
        init_task_configuration_error();
        EMPTY_COMMANDS = [];
      }
    });
    clean_exports = {};
    __export2(clean_exports, {
      CONFIG_ERROR_INTERACTIVE_MODE: /* @__PURE__ */ __name(() => CONFIG_ERROR_INTERACTIVE_MODE, "CONFIG_ERROR_INTERACTIVE_MODE"),
      CONFIG_ERROR_MODE_REQUIRED: /* @__PURE__ */ __name(() => CONFIG_ERROR_MODE_REQUIRED, "CONFIG_ERROR_MODE_REQUIRED"),
      CONFIG_ERROR_UNKNOWN_OPTION: /* @__PURE__ */ __name(() => CONFIG_ERROR_UNKNOWN_OPTION, "CONFIG_ERROR_UNKNOWN_OPTION"),
      CleanOptions: /* @__PURE__ */ __name(() => CleanOptions, "CleanOptions"),
      cleanTask: /* @__PURE__ */ __name(() => cleanTask, "cleanTask"),
      cleanWithOptionsTask: /* @__PURE__ */ __name(() => cleanWithOptionsTask, "cleanWithOptionsTask"),
      isCleanOptionsArray: /* @__PURE__ */ __name(() => isCleanOptionsArray, "isCleanOptionsArray")
    });
    __name(cleanWithOptionsTask, "cleanWithOptionsTask");
    __name(cleanTask, "cleanTask");
    __name(isCleanOptionsArray, "isCleanOptionsArray");
    __name(getCleanOptions, "getCleanOptions");
    __name(isCleanMode, "isCleanMode");
    __name(isKnownOption, "isKnownOption");
    __name(isInteractiveMode, "isInteractiveMode");
    init_clean = __esm2({
      "src/lib/tasks/clean.ts"() {
        "use strict";
        init_CleanSummary();
        init_utils6();
        init_task2();
        CONFIG_ERROR_INTERACTIVE_MODE = "Git clean interactive mode is not supported";
        CONFIG_ERROR_MODE_REQUIRED = 'Git clean mode parameter ("n" or "f") is required';
        CONFIG_ERROR_UNKNOWN_OPTION = "Git clean unknown option found in: ";
        CleanOptions = /* @__PURE__ */ ((CleanOptions2) => {
          CleanOptions2["DRY_RUN"] = "n";
          CleanOptions2["FORCE"] = "f";
          CleanOptions2["IGNORED_INCLUDED"] = "x";
          CleanOptions2["IGNORED_ONLY"] = "X";
          CleanOptions2["EXCLUDING"] = "e";
          CleanOptions2["QUIET"] = "q";
          CleanOptions2["RECURSIVE"] = "d";
          return CleanOptions2;
        })(CleanOptions || {});
        CleanOptionValues = /* @__PURE__ */ new Set([
          "i",
          ...asStringArray(Object.values(CleanOptions))
        ]);
      }
    });
    __name(configListParser, "configListParser");
    __name(configGetParser, "configGetParser");
    __name(configFilePath, "configFilePath");
    __name(configParser, "configParser");
    init_ConfigList = __esm2({
      "src/lib/responses/ConfigList.ts"() {
        "use strict";
        init_utils6();
        ConfigList = class {
          static {
            __name(this, "ConfigList");
          }
          constructor() {
            this.files = [];
            this.values = /* @__PURE__ */ Object.create(null);
          }
          get all() {
            if (!this._all) {
              this._all = this.files.reduce((all2, file) => {
                return Object.assign(all2, this.values[file]);
              }, {});
            }
            return this._all;
          }
          addFile(file) {
            if (!(file in this.values)) {
              const latest = last(this.files);
              this.values[file] = latest ? Object.create(this.values[latest]) : {};
              this.files.push(file);
            }
            return this.values[file];
          }
          addValue(file, key, value) {
            const values = this.addFile(file);
            if (!values.hasOwnProperty(key)) {
              values[key] = value;
            } else if (Array.isArray(values[key])) {
              values[key].push(value);
            } else {
              values[key] = [values[key], value];
            }
            this._all = void 0;
          }
        };
      }
    });
    __name(asConfigScope, "asConfigScope");
    __name(addConfigTask, "addConfigTask");
    __name(getConfigTask, "getConfigTask");
    __name(listConfigTask, "listConfigTask");
    __name(config_default, "config_default");
    init_config2 = __esm2({
      "src/lib/tasks/config.ts"() {
        "use strict";
        init_ConfigList();
        init_utils6();
        GitConfigScope = /* @__PURE__ */ ((GitConfigScope2) => {
          GitConfigScope2["system"] = "system";
          GitConfigScope2["global"] = "global";
          GitConfigScope2["local"] = "local";
          GitConfigScope2["worktree"] = "worktree";
          return GitConfigScope2;
        })(GitConfigScope || {});
      }
    });
    __name(isDiffNameStatus, "isDiffNameStatus");
    init_diff_name_status = __esm2({
      "src/lib/tasks/diff-name-status.ts"() {
        "use strict";
        DiffNameStatus = /* @__PURE__ */ ((DiffNameStatus2) => {
          DiffNameStatus2["ADDED"] = "A";
          DiffNameStatus2["COPIED"] = "C";
          DiffNameStatus2["DELETED"] = "D";
          DiffNameStatus2["MODIFIED"] = "M";
          DiffNameStatus2["RENAMED"] = "R";
          DiffNameStatus2["CHANGED"] = "T";
          DiffNameStatus2["UNMERGED"] = "U";
          DiffNameStatus2["UNKNOWN"] = "X";
          DiffNameStatus2["BROKEN"] = "B";
          return DiffNameStatus2;
        })(DiffNameStatus || {});
        diffNameStatus = new Set(Object.values(DiffNameStatus));
      }
    });
    __name(grepQueryBuilder, "grepQueryBuilder");
    __name(parseGrep, "parseGrep");
    __name(grep_default, "grep_default");
    init_grep = __esm2({
      "src/lib/tasks/grep.ts"() {
        "use strict";
        init_utils6();
        init_task2();
        disallowedOptions = ["-h"];
        Query = Symbol("grepQuery");
        GrepQuery = class {
          static {
            __name(this, "GrepQuery");
          }
          constructor() {
            this[_a3] = [];
          }
          *[(_a3 = Query, Symbol.iterator)]() {
            for (const query of this[Query]) {
              yield query;
            }
          }
          and(...and) {
            and.length && this[Query].push("--and", "(", ...prefixedArray(and, "-e"), ")");
            return this;
          }
          param(...param) {
            this[Query].push(...prefixedArray(param, "-e"));
            return this;
          }
        };
      }
    });
    reset_exports = {};
    __export2(reset_exports, {
      ResetMode: /* @__PURE__ */ __name(() => ResetMode, "ResetMode"),
      getResetMode: /* @__PURE__ */ __name(() => getResetMode, "getResetMode"),
      resetTask: /* @__PURE__ */ __name(() => resetTask, "resetTask")
    });
    __name(resetTask, "resetTask");
    __name(getResetMode, "getResetMode");
    __name(isValidResetMode, "isValidResetMode");
    init_reset = __esm2({
      "src/lib/tasks/reset.ts"() {
        "use strict";
        init_task2();
        ResetMode = /* @__PURE__ */ ((ResetMode2) => {
          ResetMode2["MIXED"] = "mixed";
          ResetMode2["SOFT"] = "soft";
          ResetMode2["HARD"] = "hard";
          ResetMode2["MERGE"] = "merge";
          ResetMode2["KEEP"] = "keep";
          return ResetMode2;
        })(ResetMode || {});
        ResetModes = Array.from(Object.values(ResetMode));
      }
    });
    __name(createLog, "createLog");
    __name(prefixedLogger, "prefixedLogger");
    __name(childLoggerName, "childLoggerName");
    __name(createLogger, "createLogger");
    init_git_logger = __esm2({
      "src/lib/git-logger.ts"() {
        "use strict";
        init_utils6();
        import_debug.default.formatters.L = (value) => String(filterHasLength(value) ? value.length : "-");
        import_debug.default.formatters.B = (value) => {
          if (Buffer.isBuffer(value)) {
            return value.toString("utf8");
          }
          return objectToString(value);
        };
      }
    });
    init_tasks_pending_queue = __esm2({
      "src/lib/runners/tasks-pending-queue.ts"() {
        "use strict";
        init_git_error();
        init_git_logger();
        TasksPendingQueue = class _TasksPendingQueue {
          static {
            __name(this, "_TasksPendingQueue");
          }
          constructor(logLabel = "GitExecutor") {
            this.logLabel = logLabel;
            this._queue = /* @__PURE__ */ new Map();
          }
          withProgress(task) {
            return this._queue.get(task);
          }
          createProgress(task) {
            const name3 = _TasksPendingQueue.getName(task.commands[0]);
            const logger6 = createLogger(this.logLabel, name3);
            return {
              task,
              logger: logger6,
              name: name3
            };
          }
          push(task) {
            const progress = this.createProgress(task);
            progress.logger("Adding task to the queue, commands = %o", task.commands);
            this._queue.set(task, progress);
            return progress;
          }
          fatal(err) {
            for (const [task, { logger: logger6 }] of Array.from(this._queue.entries())) {
              if (task === err.task) {
                logger6.info(`Failed %o`, err);
                logger6(
                  `Fatal exception, any as-yet un-started tasks run through this executor will not be attempted`
                );
              } else {
                logger6.info(
                  `A fatal exception occurred in a previous task, the queue has been purged: %o`,
                  err.message
                );
              }
              this.complete(task);
            }
            if (this._queue.size !== 0) {
              throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`);
            }
          }
          complete(task) {
            const progress = this.withProgress(task);
            if (progress) {
              this._queue.delete(task);
            }
          }
          attempt(task) {
            const progress = this.withProgress(task);
            if (!progress) {
              throw new GitError(void 0, "TasksPendingQueue: attempt called for an unknown task");
            }
            progress.logger("Starting task");
            return progress;
          }
          static getName(name3 = "empty") {
            return `task:${name3}:${++_TasksPendingQueue.counter}`;
          }
          static {
            this.counter = 0;
          }
        };
      }
    });
    __name(pluginContext, "pluginContext");
    __name(onErrorReceived, "onErrorReceived");
    __name(onDataReceived, "onDataReceived");
    init_git_executor_chain = __esm2({
      "src/lib/runners/git-executor-chain.ts"() {
        "use strict";
        init_git_error();
        init_task2();
        init_utils6();
        init_tasks_pending_queue();
        GitExecutorChain = class {
          static {
            __name(this, "GitExecutorChain");
          }
          constructor(_executor, _scheduler, _plugins) {
            this._executor = _executor;
            this._scheduler = _scheduler;
            this._plugins = _plugins;
            this._chain = Promise.resolve();
            this._queue = new TasksPendingQueue();
          }
          get cwd() {
            return this._cwd || this._executor.cwd;
          }
          set cwd(cwd7) {
            this._cwd = cwd7;
          }
          get env() {
            return this._executor.env;
          }
          get outputHandler() {
            return this._executor.outputHandler;
          }
          chain() {
            return this;
          }
          push(task) {
            this._queue.push(task);
            return this._chain = this._chain.then(() => this.attemptTask(task));
          }
          async attemptTask(task) {
            const onScheduleComplete = await this._scheduler.next();
            const onQueueComplete = /* @__PURE__ */ __name(() => this._queue.complete(task), "onQueueComplete");
            try {
              const { logger: logger6 } = this._queue.attempt(task);
              return await (isEmptyTask(task) ? this.attemptEmptyTask(task, logger6) : this.attemptRemoteTask(task, logger6));
            } catch (e2) {
              throw this.onFatalException(task, e2);
            } finally {
              onQueueComplete();
              onScheduleComplete();
            }
          }
          onFatalException(task, e2) {
            const gitError = e2 instanceof GitError ? Object.assign(e2, { task }) : new GitError(task, e2 && String(e2));
            this._chain = Promise.resolve();
            this._queue.fatal(gitError);
            return gitError;
          }
          async attemptRemoteTask(task, logger6) {
            const binary = this._plugins.exec("spawn.binary", "", pluginContext(task, task.commands));
            const args = this._plugins.exec(
              "spawn.args",
              [...task.commands],
              pluginContext(task, task.commands)
            );
            const raw2 = await this.gitResponse(
              task,
              binary,
              args,
              this.outputHandler,
              logger6.step("SPAWN")
            );
            const outputStreams = await this.handleTaskData(task, args, raw2, logger6.step("HANDLE"));
            logger6(`passing response to task's parser as a %s`, task.format);
            if (isBufferTask(task)) {
              return callTaskParser(task.parser, outputStreams);
            }
            return callTaskParser(task.parser, outputStreams.asStrings());
          }
          async attemptEmptyTask(task, logger6) {
            logger6(`empty task bypassing child process to call to task's parser`);
            return task.parser(this);
          }
          handleTaskData(task, args, result, logger6) {
            const { exitCode, rejection, stdOut, stdErr } = result;
            return new Promise((done, fail) => {
              logger6(`Preparing to handle process response exitCode=%d stdOut=`, exitCode);
              const { error } = this._plugins.exec(
                "task.error",
                { error: rejection },
                {
                  ...pluginContext(task, args),
                  ...result
                }
              );
              if (error && task.onError) {
                logger6.info(`exitCode=%s handling with custom error handler`);
                return task.onError(
                  result,
                  error,
                  (newStdOut) => {
                    logger6.info(`custom error handler treated as success`);
                    logger6(`custom error returned a %s`, objectToString(newStdOut));
                    done(
                      new GitOutputStreams(
                        Array.isArray(newStdOut) ? Buffer.concat(newStdOut) : newStdOut,
                        Buffer.concat(stdErr)
                      )
                    );
                  },
                  fail
                );
              }
              if (error) {
                logger6.info(
                  `handling as error: exitCode=%s stdErr=%s rejection=%o`,
                  exitCode,
                  stdErr.length,
                  rejection
                );
                return fail(error);
              }
              logger6.info(`retrieving task output complete`);
              done(new GitOutputStreams(Buffer.concat(stdOut), Buffer.concat(stdErr)));
            });
          }
          async gitResponse(task, command2, args, outputHandler, logger6) {
            const outputLogger = logger6.sibling("output");
            const spawnOptions = this._plugins.exec(
              "spawn.options",
              {
                cwd: this.cwd,
                env: this.env,
                windowsHide: true
              },
              pluginContext(task, task.commands)
            );
            return new Promise((done) => {
              const stdOut = [];
              const stdErr = [];
              logger6.info(`%s %o`, command2, args);
              logger6("%O", spawnOptions);
              let rejection = this._beforeSpawn(task, args);
              if (rejection) {
                return done({
                  stdOut,
                  stdErr,
                  exitCode: 9901,
                  rejection
                });
              }
              this._plugins.exec("spawn.before", void 0, {
                ...pluginContext(task, args),
                kill(reason) {
                  rejection = reason || rejection;
                }
              });
              const spawned = spawn2(command2, args, spawnOptions);
              spawned.stdout.on(
                "data",
                onDataReceived(stdOut, "stdOut", logger6, outputLogger.step("stdOut"))
              );
              spawned.stderr.on(
                "data",
                onDataReceived(stdErr, "stdErr", logger6, outputLogger.step("stdErr"))
              );
              spawned.on("error", onErrorReceived(stdErr, logger6));
              if (outputHandler) {
                logger6(`Passing child process stdOut/stdErr to custom outputHandler`);
                outputHandler(command2, spawned.stdout, spawned.stderr, [...args]);
              }
              this._plugins.exec("spawn.after", void 0, {
                ...pluginContext(task, args),
                spawned,
                close(exitCode, reason) {
                  done({
                    stdOut,
                    stdErr,
                    exitCode,
                    rejection: rejection || reason
                  });
                },
                kill(reason) {
                  if (spawned.killed) {
                    return;
                  }
                  rejection = reason;
                  spawned.kill("SIGINT");
                }
              });
            });
          }
          _beforeSpawn(task, args) {
            let rejection;
            this._plugins.exec("spawn.before", void 0, {
              ...pluginContext(task, args),
              kill(reason) {
                rejection = reason || rejection;
              }
            });
            return rejection;
          }
        };
      }
    });
    git_executor_exports = {};
    __export2(git_executor_exports, {
      GitExecutor: /* @__PURE__ */ __name(() => GitExecutor, "GitExecutor")
    });
    init_git_executor = __esm2({
      "src/lib/runners/git-executor.ts"() {
        "use strict";
        init_git_executor_chain();
        GitExecutor = class {
          static {
            __name(this, "GitExecutor");
          }
          constructor(cwd7, _scheduler, _plugins) {
            this.cwd = cwd7;
            this._scheduler = _scheduler;
            this._plugins = _plugins;
            this._chain = new GitExecutorChain(this, this._scheduler, this._plugins);
          }
          chain() {
            return new GitExecutorChain(this, this._scheduler, this._plugins);
          }
          push(task) {
            return this._chain.push(task);
          }
        };
      }
    });
    __name(taskCallback, "taskCallback");
    __name(addDeprecationNoticeToError, "addDeprecationNoticeToError");
    init_task_callback = __esm2({
      "src/lib/task-callback.ts"() {
        "use strict";
        init_git_response_error();
        init_utils6();
      }
    });
    __name(changeWorkingDirectoryTask, "changeWorkingDirectoryTask");
    init_change_working_directory = __esm2({
      "src/lib/tasks/change-working-directory.ts"() {
        "use strict";
        init_utils6();
        init_task2();
      }
    });
    __name(checkoutTask, "checkoutTask");
    __name(checkout_default, "checkout_default");
    init_checkout = __esm2({
      "src/lib/tasks/checkout.ts"() {
        "use strict";
        init_utils6();
        init_task2();
      }
    });
    __name(countObjectsResponse, "countObjectsResponse");
    __name(count_objects_default, "count_objects_default");
    init_count_objects = __esm2({
      "src/lib/tasks/count-objects.ts"() {
        "use strict";
        init_utils6();
        parser2 = new LineParser(
          /([a-z-]+): (\d+)$/,
          (result, [key, value]) => {
            const property = asCamelCase(key);
            if (result.hasOwnProperty(property)) {
              result[property] = asNumber(value);
            }
          }
        );
      }
    });
    __name(parseCommitResult, "parseCommitResult");
    init_parse_commit = __esm2({
      "src/lib/parsers/parse-commit.ts"() {
        "use strict";
        init_utils6();
        parsers = [
          new LineParser(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/, (result, [branch, root, commit]) => {
            result.branch = branch;
            result.commit = commit;
            result.root = !!root;
          }),
          new LineParser(/\s*Author:\s(.+)/i, (result, [author]) => {
            const parts = author.split("<");
            const email = parts.pop();
            if (!email || !email.includes("@")) {
              return;
            }
            result.author = {
              email: email.substr(0, email.length - 1),
              name: parts.join("<").trim()
            };
          }),
          new LineParser(
            /(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g,
            (result, [changes, insertions, deletions]) => {
              result.summary.changes = parseInt(changes, 10) || 0;
              result.summary.insertions = parseInt(insertions, 10) || 0;
              result.summary.deletions = parseInt(deletions, 10) || 0;
            }
          ),
          new LineParser(
            /^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/,
            (result, [changes, lines, direction]) => {
              result.summary.changes = parseInt(changes, 10) || 0;
              const count = parseInt(lines, 10) || 0;
              if (direction === "-") {
                result.summary.deletions = count;
              } else if (direction === "+") {
                result.summary.insertions = count;
              }
            }
          )
        ];
      }
    });
    __name(commitTask, "commitTask");
    __name(commit_default, "commit_default");
    init_commit = __esm2({
      "src/lib/tasks/commit.ts"() {
        "use strict";
        init_parse_commit();
        init_utils6();
        init_task2();
      }
    });
    __name(first_commit_default, "first_commit_default");
    init_first_commit = __esm2({
      "src/lib/tasks/first-commit.ts"() {
        "use strict";
        init_utils6();
        init_task2();
      }
    });
    __name(hashObjectTask, "hashObjectTask");
    init_hash_object = __esm2({
      "src/lib/tasks/hash-object.ts"() {
        "use strict";
        init_task2();
      }
    });
    __name(parseInit, "parseInit");
    init_InitSummary = __esm2({
      "src/lib/responses/InitSummary.ts"() {
        "use strict";
        InitSummary = class {
          static {
            __name(this, "InitSummary");
          }
          constructor(bare, path108, existing, gitDir) {
            this.bare = bare;
            this.path = path108;
            this.existing = existing;
            this.gitDir = gitDir;
          }
        };
        initResponseRegex = /^Init.+ repository in (.+)$/;
        reInitResponseRegex = /^Rein.+ in (.+)$/;
      }
    });
    __name(hasBareCommand, "hasBareCommand");
    __name(initTask, "initTask");
    init_init = __esm2({
      "src/lib/tasks/init.ts"() {
        "use strict";
        init_InitSummary();
        bareCommand = "--bare";
      }
    });
    __name(logFormatFromCommand, "logFormatFromCommand");
    __name(isLogFormat, "isLogFormat");
    init_log_format = __esm2({
      "src/lib/args/log-format.ts"() {
        "use strict";
        logFormatRegex = /^--(stat|numstat|name-only|name-status)(=|$)/;
      }
    });
    init_DiffSummary = __esm2({
      "src/lib/responses/DiffSummary.ts"() {
        "use strict";
        DiffSummary = class {
          static {
            __name(this, "DiffSummary");
          }
          constructor() {
            this.changed = 0;
            this.deletions = 0;
            this.insertions = 0;
            this.files = [];
          }
        };
      }
    });
    __name(getDiffParser, "getDiffParser");
    init_parse_diff_summary = __esm2({
      "src/lib/parsers/parse-diff-summary.ts"() {
        "use strict";
        init_log_format();
        init_DiffSummary();
        init_diff_name_status();
        init_utils6();
        statParser = [
          new LineParser(
            /^(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/,
            (result, [file, changes, alterations = ""]) => {
              result.files.push({
                file: file.trim(),
                changes: asNumber(changes),
                insertions: alterations.replace(/[^+]/g, "").length,
                deletions: alterations.replace(/[^-]/g, "").length,
                binary: false
              });
            }
          ),
          new LineParser(
            /^(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/,
            (result, [file, before, after]) => {
              result.files.push({
                file: file.trim(),
                before: asNumber(before),
                after: asNumber(after),
                binary: true
              });
            }
          ),
          new LineParser(
            /(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/,
            (result, [changed, summary]) => {
              const inserted = /(\d+) i/.exec(summary);
              const deleted = /(\d+) d/.exec(summary);
              result.changed = asNumber(changed);
              result.insertions = asNumber(inserted?.[1]);
              result.deletions = asNumber(deleted?.[1]);
            }
          )
        ];
        numStatParser = [
          new LineParser(
            /(\d+)\t(\d+)\t(.+)$/,
            (result, [changesInsert, changesDelete, file]) => {
              const insertions = asNumber(changesInsert);
              const deletions = asNumber(changesDelete);
              result.changed++;
              result.insertions += insertions;
              result.deletions += deletions;
              result.files.push({
                file,
                changes: insertions + deletions,
                insertions,
                deletions,
                binary: false
              });
            }
          ),
          new LineParser(/-\t-\t(.+)$/, (result, [file]) => {
            result.changed++;
            result.files.push({
              file,
              after: 0,
              before: 0,
              binary: true
            });
          })
        ];
        nameOnlyParser = [
          new LineParser(/(.+)$/, (result, [file]) => {
            result.changed++;
            result.files.push({
              file,
              changes: 0,
              insertions: 0,
              deletions: 0,
              binary: false
            });
          })
        ];
        nameStatusParser = [
          new LineParser(
            /([ACDMRTUXB])([0-9]{0,3})\t(.[^\t]*)(\t(.[^\t]*))?$/,
            (result, [status, similarity, from, _to, to]) => {
              result.changed++;
              result.files.push({
                file: to ?? from,
                changes: 0,
                insertions: 0,
                deletions: 0,
                binary: false,
                status: orVoid(isDiffNameStatus(status) && status),
                from: orVoid(!!to && from !== to && from),
                similarity: asNumber(similarity)
              });
            }
          )
        ];
        diffSummaryParsers = {
          [
            ""
            /* NONE */
          ]: statParser,
          [
            "--stat"
            /* STAT */
          ]: statParser,
          [
            "--numstat"
            /* NUM_STAT */
          ]: numStatParser,
          [
            "--name-status"
            /* NAME_STATUS */
          ]: nameStatusParser,
          [
            "--name-only"
            /* NAME_ONLY */
          ]: nameOnlyParser
        };
      }
    });
    __name(lineBuilder, "lineBuilder");
    __name(createListLogSummaryParser, "createListLogSummaryParser");
    init_parse_list_log_summary = __esm2({
      "src/lib/parsers/parse-list-log-summary.ts"() {
        "use strict";
        init_utils6();
        init_parse_diff_summary();
        init_log_format();
        START_BOUNDARY = "\xF2\xF2\xF2\xF2\xF2\xF2 ";
        COMMIT_BOUNDARY = " \xF2\xF2";
        SPLITTER = " \xF2 ";
        defaultFieldNames = ["hash", "date", "message", "refs", "author_name", "author_email"];
      }
    });
    diff_exports = {};
    __export2(diff_exports, {
      diffSummaryTask: /* @__PURE__ */ __name(() => diffSummaryTask, "diffSummaryTask"),
      validateLogFormatConfig: /* @__PURE__ */ __name(() => validateLogFormatConfig, "validateLogFormatConfig")
    });
    __name(diffSummaryTask, "diffSummaryTask");
    __name(validateLogFormatConfig, "validateLogFormatConfig");
    init_diff = __esm2({
      "src/lib/tasks/diff.ts"() {
        "use strict";
        init_log_format();
        init_parse_diff_summary();
        init_task2();
      }
    });
    __name(prettyFormat, "prettyFormat");
    __name(userOptions, "userOptions");
    __name(parseLogOptions, "parseLogOptions");
    __name(logTask, "logTask");
    __name(log_default, "log_default");
    init_log2 = __esm2({
      "src/lib/tasks/log.ts"() {
        "use strict";
        init_log_format();
        init_pathspec();
        init_parse_list_log_summary();
        init_utils6();
        init_task2();
        init_diff();
        excludeOptions = /* @__PURE__ */ ((excludeOptions2) => {
          excludeOptions2[excludeOptions2["--pretty"] = 0] = "--pretty";
          excludeOptions2[excludeOptions2["max-count"] = 1] = "max-count";
          excludeOptions2[excludeOptions2["maxCount"] = 2] = "maxCount";
          excludeOptions2[excludeOptions2["n"] = 3] = "n";
          excludeOptions2[excludeOptions2["file"] = 4] = "file";
          excludeOptions2[excludeOptions2["format"] = 5] = "format";
          excludeOptions2[excludeOptions2["from"] = 6] = "from";
          excludeOptions2[excludeOptions2["to"] = 7] = "to";
          excludeOptions2[excludeOptions2["splitter"] = 8] = "splitter";
          excludeOptions2[excludeOptions2["symmetric"] = 9] = "symmetric";
          excludeOptions2[excludeOptions2["mailMap"] = 10] = "mailMap";
          excludeOptions2[excludeOptions2["multiLine"] = 11] = "multiLine";
          excludeOptions2[excludeOptions2["strictDate"] = 12] = "strictDate";
          return excludeOptions2;
        })(excludeOptions || {});
      }
    });
    init_MergeSummary = __esm2({
      "src/lib/responses/MergeSummary.ts"() {
        "use strict";
        MergeSummaryConflict = class {
          static {
            __name(this, "MergeSummaryConflict");
          }
          constructor(reason, file = null, meta) {
            this.reason = reason;
            this.file = file;
            this.meta = meta;
          }
          toString() {
            return `${this.file}:${this.reason}`;
          }
        };
        MergeSummaryDetail = class {
          static {
            __name(this, "MergeSummaryDetail");
          }
          constructor() {
            this.conflicts = [];
            this.merges = [];
            this.result = "success";
          }
          get failed() {
            return this.conflicts.length > 0;
          }
          get reason() {
            return this.result;
          }
          toString() {
            if (this.conflicts.length) {
              return `CONFLICTS: ${this.conflicts.join(", ")}`;
            }
            return "OK";
          }
        };
      }
    });
    init_PullSummary = __esm2({
      "src/lib/responses/PullSummary.ts"() {
        "use strict";
        PullSummary = class {
          static {
            __name(this, "PullSummary");
          }
          constructor() {
            this.remoteMessages = {
              all: []
            };
            this.created = [];
            this.deleted = [];
            this.files = [];
            this.deletions = {};
            this.insertions = {};
            this.summary = {
              changes: 0,
              deletions: 0,
              insertions: 0
            };
          }
        };
        PullFailedSummary = class {
          static {
            __name(this, "PullFailedSummary");
          }
          constructor() {
            this.remote = "";
            this.hash = {
              local: "",
              remote: ""
            };
            this.branch = {
              local: "",
              remote: ""
            };
            this.message = "";
          }
          toString() {
            return this.message;
          }
        };
      }
    });
    __name(objectEnumerationResult, "objectEnumerationResult");
    __name(asObjectCount, "asObjectCount");
    init_parse_remote_objects = __esm2({
      "src/lib/parsers/parse-remote-objects.ts"() {
        "use strict";
        init_utils6();
        remoteMessagesObjectParsers = [
          new RemoteLineParser(
            /^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i,
            (result, [action, count]) => {
              const key = action.toLowerCase();
              const enumeration = objectEnumerationResult(result.remoteMessages);
              Object.assign(enumeration, { [key]: asNumber(count) });
            }
          ),
          new RemoteLineParser(
            /^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i,
            (result, [action, count]) => {
              const key = action.toLowerCase();
              const enumeration = objectEnumerationResult(result.remoteMessages);
              Object.assign(enumeration, { [key]: asNumber(count) });
            }
          ),
          new RemoteLineParser(
            /total ([^,]+), reused ([^,]+), pack-reused (\d+)/i,
            (result, [total, reused, packReused]) => {
              const objects = objectEnumerationResult(result.remoteMessages);
              objects.total = asObjectCount(total);
              objects.reused = asObjectCount(reused);
              objects.packReused = asNumber(packReused);
            }
          )
        ];
      }
    });
    __name(parseRemoteMessages, "parseRemoteMessages");
    init_parse_remote_messages = __esm2({
      "src/lib/parsers/parse-remote-messages.ts"() {
        "use strict";
        init_utils6();
        init_parse_remote_objects();
        parsers2 = [
          new RemoteLineParser(/^remote:\s*(.+)$/, (result, [text]) => {
            result.remoteMessages.all.push(text.trim());
            return false;
          }),
          ...remoteMessagesObjectParsers,
          new RemoteLineParser(
            [/create a (?:pull|merge) request/i, /\s(https?:\/\/\S+)$/],
            (result, [pullRequestUrl]) => {
              result.remoteMessages.pullRequestUrl = pullRequestUrl;
            }
          ),
          new RemoteLineParser(
            [/found (\d+) vulnerabilities.+\(([^)]+)\)/i, /\s(https?:\/\/\S+)$/],
            (result, [count, summary, url2]) => {
              result.remoteMessages.vulnerabilities = {
                count: asNumber(count),
                summary,
                url: url2
              };
            }
          )
        ];
        RemoteMessageSummary = class {
          static {
            __name(this, "RemoteMessageSummary");
          }
          constructor() {
            this.all = [];
          }
        };
      }
    });
    __name(parsePullErrorResult, "parsePullErrorResult");
    init_parse_pull = __esm2({
      "src/lib/parsers/parse-pull.ts"() {
        "use strict";
        init_PullSummary();
        init_utils6();
        init_parse_remote_messages();
        FILE_UPDATE_REGEX = /^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/;
        SUMMARY_REGEX = /(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/;
        ACTION_REGEX = /^(create|delete) mode \d+ (.+)/;
        parsers3 = [
          new LineParser(FILE_UPDATE_REGEX, (result, [file, insertions, deletions]) => {
            result.files.push(file);
            if (insertions) {
              result.insertions[file] = insertions.length;
            }
            if (deletions) {
              result.deletions[file] = deletions.length;
            }
          }),
          new LineParser(SUMMARY_REGEX, (result, [changes, , insertions, , deletions]) => {
            if (insertions !== void 0 || deletions !== void 0) {
              result.summary.changes = +changes || 0;
              result.summary.insertions = +insertions || 0;
              result.summary.deletions = +deletions || 0;
              return true;
            }
            return false;
          }),
          new LineParser(ACTION_REGEX, (result, [action, file]) => {
            append(result.files, file);
            append(action === "create" ? result.created : result.deleted, file);
          })
        ];
        errorParsers = [
          new LineParser(/^from\s(.+)$/i, (result, [remote]) => void (result.remote = remote)),
          new LineParser(/^fatal:\s(.+)$/, (result, [message]) => void (result.message = message)),
          new LineParser(
            /([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/,
            (result, [hashLocal, hashRemote, branchLocal, branchRemote]) => {
              result.branch.local = branchLocal;
              result.hash.local = hashLocal;
              result.branch.remote = branchRemote;
              result.hash.remote = hashRemote;
            }
          )
        ];
        parsePullDetail = /* @__PURE__ */ __name((stdOut, stdErr) => {
          return parseStringResponse(new PullSummary(), parsers3, [stdOut, stdErr]);
        }, "parsePullDetail");
        parsePullResult = /* @__PURE__ */ __name((stdOut, stdErr) => {
          return Object.assign(
            new PullSummary(),
            parsePullDetail(stdOut, stdErr),
            parseRemoteMessages(stdOut, stdErr)
          );
        }, "parsePullResult");
      }
    });
    init_parse_merge = __esm2({
      "src/lib/parsers/parse-merge.ts"() {
        "use strict";
        init_MergeSummary();
        init_utils6();
        init_parse_pull();
        parsers4 = [
          new LineParser(/^Auto-merging\s+(.+)$/, (summary, [autoMerge]) => {
            summary.merges.push(autoMerge);
          }),
          new LineParser(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/, (summary, [reason, file]) => {
            summary.conflicts.push(new MergeSummaryConflict(reason, file));
          }),
          new LineParser(
            /^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/,
            (summary, [reason, file, deleteRef]) => {
              summary.conflicts.push(new MergeSummaryConflict(reason, file, { deleteRef }));
            }
          ),
          new LineParser(/^CONFLICT\s+\((.+)\):/, (summary, [reason]) => {
            summary.conflicts.push(new MergeSummaryConflict(reason, null));
          }),
          new LineParser(/^Automatic merge failed;\s+(.+)$/, (summary, [result]) => {
            summary.result = result;
          })
        ];
        parseMergeResult = /* @__PURE__ */ __name((stdOut, stdErr) => {
          return Object.assign(parseMergeDetail(stdOut, stdErr), parsePullResult(stdOut, stdErr));
        }, "parseMergeResult");
        parseMergeDetail = /* @__PURE__ */ __name((stdOut) => {
          return parseStringResponse(new MergeSummaryDetail(), parsers4, stdOut);
        }, "parseMergeDetail");
      }
    });
    __name(mergeTask, "mergeTask");
    init_merge = __esm2({
      "src/lib/tasks/merge.ts"() {
        "use strict";
        init_git_response_error();
        init_parse_merge();
        init_task2();
      }
    });
    __name(pushResultPushedItem, "pushResultPushedItem");
    init_parse_push = __esm2({
      "src/lib/parsers/parse-push.ts"() {
        "use strict";
        init_utils6();
        init_parse_remote_messages();
        parsers5 = [
          new LineParser(/^Pushing to (.+)$/, (result, [repo]) => {
            result.repo = repo;
          }),
          new LineParser(/^updating local tracking ref '(.+)'/, (result, [local]) => {
            result.ref = {
              ...result.ref || {},
              local
            };
          }),
          new LineParser(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/, (result, [local, remote, type]) => {
            result.pushed.push(pushResultPushedItem(local, remote, type));
          }),
          new LineParser(
            /^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/,
            (result, [local, remote, remoteName]) => {
              result.branch = {
                ...result.branch || {},
                local,
                remote,
                remoteName
              };
            }
          ),
          new LineParser(
            /^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/,
            (result, [local, remote, from, to]) => {
              result.update = {
                head: {
                  local,
                  remote
                },
                hash: {
                  from,
                  to
                }
              };
            }
          )
        ];
        parsePushResult = /* @__PURE__ */ __name((stdOut, stdErr) => {
          const pushDetail = parsePushDetail(stdOut, stdErr);
          const responseDetail = parseRemoteMessages(stdOut, stdErr);
          return {
            ...pushDetail,
            ...responseDetail
          };
        }, "parsePushResult");
        parsePushDetail = /* @__PURE__ */ __name((stdOut, stdErr) => {
          return parseStringResponse({ pushed: [] }, parsers5, [stdOut, stdErr]);
        }, "parsePushDetail");
      }
    });
    push_exports = {};
    __export2(push_exports, {
      pushTagsTask: /* @__PURE__ */ __name(() => pushTagsTask, "pushTagsTask"),
      pushTask: /* @__PURE__ */ __name(() => pushTask, "pushTask")
    });
    __name(pushTagsTask, "pushTagsTask");
    __name(pushTask, "pushTask");
    init_push = __esm2({
      "src/lib/tasks/push.ts"() {
        "use strict";
        init_parse_push();
        init_utils6();
      }
    });
    __name(show_default, "show_default");
    init_show = __esm2({
      "src/lib/tasks/show.ts"() {
        "use strict";
        init_utils6();
        init_task2();
      }
    });
    init_FileStatusSummary = __esm2({
      "src/lib/responses/FileStatusSummary.ts"() {
        "use strict";
        fromPathRegex = /^(.+)\0(.+)$/;
        FileStatusSummary = class {
          static {
            __name(this, "FileStatusSummary");
          }
          constructor(path108, index, working_dir) {
            this.path = path108;
            this.index = index;
            this.working_dir = working_dir;
            if (index === "R" || working_dir === "R") {
              const detail = fromPathRegex.exec(path108) || [null, path108, path108];
              this.from = detail[2] || "";
              this.path = detail[1] || "";
            }
          }
        };
      }
    });
    __name(renamedFile, "renamedFile");
    __name(parser3, "parser3");
    __name(conflicts, "conflicts");
    __name(splitLine, "splitLine");
    init_StatusSummary = __esm2({
      "src/lib/responses/StatusSummary.ts"() {
        "use strict";
        init_utils6();
        init_FileStatusSummary();
        StatusSummary = class {
          static {
            __name(this, "StatusSummary");
          }
          constructor() {
            this.not_added = [];
            this.conflicted = [];
            this.created = [];
            this.deleted = [];
            this.ignored = void 0;
            this.modified = [];
            this.renamed = [];
            this.files = [];
            this.staged = [];
            this.ahead = 0;
            this.behind = 0;
            this.current = null;
            this.tracking = null;
            this.detached = false;
            this.isClean = () => {
              return !this.files.length;
            };
          }
        };
        parsers6 = new Map([
          parser3(
            " ",
            "A",
            (result, file) => append(result.created, file)
          ),
          parser3(
            " ",
            "D",
            (result, file) => append(result.deleted, file)
          ),
          parser3(
            " ",
            "M",
            (result, file) => append(result.modified, file)
          ),
          parser3(
            "A",
            " ",
            (result, file) => append(result.created, file) && append(result.staged, file)
          ),
          parser3(
            "A",
            "M",
            (result, file) => append(result.created, file) && append(result.staged, file) && append(result.modified, file)
          ),
          parser3(
            "D",
            " ",
            (result, file) => append(result.deleted, file) && append(result.staged, file)
          ),
          parser3(
            "M",
            " ",
            (result, file) => append(result.modified, file) && append(result.staged, file)
          ),
          parser3(
            "M",
            "M",
            (result, file) => append(result.modified, file) && append(result.staged, file)
          ),
          parser3("R", " ", (result, file) => {
            append(result.renamed, renamedFile(file));
          }),
          parser3("R", "M", (result, file) => {
            const renamed = renamedFile(file);
            append(result.renamed, renamed);
            append(result.modified, renamed.to);
          }),
          parser3("!", "!", (_result, _file) => {
            append(_result.ignored = _result.ignored || [], _file);
          }),
          parser3(
            "?",
            "?",
            (result, file) => append(result.not_added, file)
          ),
          ...conflicts(
            "A",
            "A",
            "U"
            /* UNMERGED */
          ),
          ...conflicts(
            "D",
            "D",
            "U"
            /* UNMERGED */
          ),
          ...conflicts(
            "U",
            "A",
            "D",
            "U"
            /* UNMERGED */
          ),
          [
            "##",
            (result, line) => {
              const aheadReg = /ahead (\d+)/;
              const behindReg = /behind (\d+)/;
              const currentReg = /^(.+?(?=(?:\.{3}|\s|$)))/;
              const trackingReg = /\.{3}(\S*)/;
              const onEmptyBranchReg = /\son\s([\S]+)$/;
              let regexResult;
              regexResult = aheadReg.exec(line);
              result.ahead = regexResult && +regexResult[1] || 0;
              regexResult = behindReg.exec(line);
              result.behind = regexResult && +regexResult[1] || 0;
              regexResult = currentReg.exec(line);
              result.current = regexResult && regexResult[1];
              regexResult = trackingReg.exec(line);
              result.tracking = regexResult && regexResult[1];
              regexResult = onEmptyBranchReg.exec(line);
              result.current = regexResult && regexResult[1] || result.current;
              result.detached = /\(no branch\)/.test(line);
            }
          ]
        ]);
        parseStatusSummary = /* @__PURE__ */ __name(function(text) {
          const lines = text.split(NULL2);
          const status = new StatusSummary();
          for (let i = 0, l2 = lines.length; i < l2; ) {
            let line = lines[i++].trim();
            if (!line) {
              continue;
            }
            if (line.charAt(0) === "R") {
              line += NULL2 + (lines[i++] || "");
            }
            splitLine(status, line);
          }
          return status;
        }, "parseStatusSummary");
      }
    });
    __name(statusTask, "statusTask");
    init_status2 = __esm2({
      "src/lib/tasks/status.ts"() {
        "use strict";
        init_StatusSummary();
        ignoredOptions = ["--null", "-z"];
      }
    });
    __name(versionResponse, "versionResponse");
    __name(notInstalledResponse, "notInstalledResponse");
    __name(version_default2, "version_default");
    __name(versionParser, "versionParser");
    init_version4 = __esm2({
      "src/lib/tasks/version.ts"() {
        "use strict";
        init_utils6();
        NOT_INSTALLED = "installed=false";
        parsers7 = [
          new LineParser(
            /version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/,
            (result, [major2, minor, patch, agent = ""]) => {
              Object.assign(
                result,
                versionResponse(asNumber(major2), asNumber(minor), asNumber(patch), agent)
              );
            }
          ),
          new LineParser(
            /version (\d+)\.(\d+)\.(\D+)(.+)?$/,
            (result, [major2, minor, patch, agent = ""]) => {
              Object.assign(result, versionResponse(asNumber(major2), asNumber(minor), patch, agent));
            }
          )
        ];
      }
    });
    simple_git_api_exports = {};
    __export2(simple_git_api_exports, {
      SimpleGitApi: /* @__PURE__ */ __name(() => SimpleGitApi, "SimpleGitApi")
    });
    init_simple_git_api = __esm2({
      "src/lib/simple-git-api.ts"() {
        "use strict";
        init_task_callback();
        init_change_working_directory();
        init_checkout();
        init_count_objects();
        init_commit();
        init_config2();
        init_first_commit();
        init_grep();
        init_hash_object();
        init_init();
        init_log2();
        init_merge();
        init_push();
        init_show();
        init_status2();
        init_task2();
        init_version4();
        init_utils6();
        SimpleGitApi = class {
          static {
            __name(this, "SimpleGitApi");
          }
          constructor(_executor) {
            this._executor = _executor;
          }
          _runTask(task, then) {
            const chain2 = this._executor.chain();
            const promise = chain2.push(task);
            if (then) {
              taskCallback(task, promise, then);
            }
            return Object.create(this, {
              then: { value: promise.then.bind(promise) },
              catch: { value: promise.catch.bind(promise) },
              _executor: { value: chain2 }
            });
          }
          add(files) {
            return this._runTask(
              straightThroughStringTask(["add", ...asArray(files)]),
              trailingFunctionArgument(arguments)
            );
          }
          cwd(directory) {
            const next = trailingFunctionArgument(arguments);
            if (typeof directory === "string") {
              return this._runTask(changeWorkingDirectoryTask(directory, this._executor), next);
            }
            if (typeof directory?.path === "string") {
              return this._runTask(
                changeWorkingDirectoryTask(
                  directory.path,
                  directory.root && this._executor || void 0
                ),
                next
              );
            }
            return this._runTask(
              configurationErrorTask("Git.cwd: workingDirectory must be supplied as a string"),
              next
            );
          }
          hashObject(path108, write2) {
            return this._runTask(
              hashObjectTask(path108, write2 === true),
              trailingFunctionArgument(arguments)
            );
          }
          init(bare) {
            return this._runTask(
              initTask(bare === true, this._executor.cwd, getTrailingOptions(arguments)),
              trailingFunctionArgument(arguments)
            );
          }
          merge() {
            return this._runTask(
              mergeTask(getTrailingOptions(arguments)),
              trailingFunctionArgument(arguments)
            );
          }
          mergeFromTo(remote, branch) {
            if (!(filterString(remote) && filterString(branch))) {
              return this._runTask(
                configurationErrorTask(
                  `Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings`
                )
              );
            }
            return this._runTask(
              mergeTask([remote, branch, ...getTrailingOptions(arguments)]),
              trailingFunctionArgument(arguments, false)
            );
          }
          outputHandler(handler) {
            this._executor.outputHandler = handler;
            return this;
          }
          push() {
            const task = pushTask(
              {
                remote: filterType(arguments[0], filterString),
                branch: filterType(arguments[1], filterString)
              },
              getTrailingOptions(arguments)
            );
            return this._runTask(task, trailingFunctionArgument(arguments));
          }
          stash() {
            return this._runTask(
              straightThroughStringTask(["stash", ...getTrailingOptions(arguments)]),
              trailingFunctionArgument(arguments)
            );
          }
          status() {
            return this._runTask(
              statusTask(getTrailingOptions(arguments)),
              trailingFunctionArgument(arguments)
            );
          }
        };
        Object.assign(
          SimpleGitApi.prototype,
          checkout_default(),
          commit_default(),
          config_default(),
          count_objects_default(),
          first_commit_default(),
          grep_default(),
          log_default(),
          show_default(),
          version_default2()
        );
      }
    });
    scheduler_exports = {};
    __export2(scheduler_exports, {
      Scheduler: /* @__PURE__ */ __name(() => Scheduler, "Scheduler")
    });
    init_scheduler = __esm2({
      "src/lib/runners/scheduler.ts"() {
        "use strict";
        init_utils6();
        init_git_logger();
        createScheduledTask = /* @__PURE__ */ (() => {
          let id = 0;
          return () => {
            id++;
            const { promise, done } = (0, import_promise_deferred.createDeferred)();
            return {
              promise,
              done,
              id
            };
          };
        })();
        Scheduler = class {
          static {
            __name(this, "Scheduler");
          }
          constructor(concurrency = 2) {
            this.concurrency = concurrency;
            this.logger = createLogger("", "scheduler");
            this.pending = [];
            this.running = [];
            this.logger(`Constructed, concurrency=%s`, concurrency);
          }
          schedule() {
            if (!this.pending.length || this.running.length >= this.concurrency) {
              this.logger(
                `Schedule attempt ignored, pending=%s running=%s concurrency=%s`,
                this.pending.length,
                this.running.length,
                this.concurrency
              );
              return;
            }
            const task = append(this.running, this.pending.shift());
            this.logger(`Attempting id=%s`, task.id);
            task.done(() => {
              this.logger(`Completing id=`, task.id);
              remove(this.running, task);
              this.schedule();
            });
          }
          next() {
            const { promise, id } = append(this.pending, createScheduledTask());
            this.logger(`Scheduling id=%s`, id);
            this.schedule();
            return promise;
          }
        };
      }
    });
    apply_patch_exports = {};
    __export2(apply_patch_exports, {
      applyPatchTask: /* @__PURE__ */ __name(() => applyPatchTask, "applyPatchTask")
    });
    __name(applyPatchTask, "applyPatchTask");
    init_apply_patch = __esm2({
      "src/lib/tasks/apply-patch.ts"() {
        "use strict";
        init_task2();
      }
    });
    __name(branchDeletionSuccess, "branchDeletionSuccess");
    __name(branchDeletionFailure, "branchDeletionFailure");
    init_BranchDeleteSummary = __esm2({
      "src/lib/responses/BranchDeleteSummary.ts"() {
        "use strict";
        BranchDeletionBatch = class {
          static {
            __name(this, "BranchDeletionBatch");
          }
          constructor() {
            this.all = [];
            this.branches = {};
            this.errors = [];
          }
          get success() {
            return !this.errors.length;
          }
        };
      }
    });
    __name(hasBranchDeletionError, "hasBranchDeletionError");
    init_parse_branch_delete = __esm2({
      "src/lib/parsers/parse-branch-delete.ts"() {
        "use strict";
        init_BranchDeleteSummary();
        init_utils6();
        deleteSuccessRegex = /(\S+)\s+\(\S+\s([^)]+)\)/;
        deleteErrorRegex = /^error[^']+'([^']+)'/m;
        parsers8 = [
          new LineParser(deleteSuccessRegex, (result, [branch, hash]) => {
            const deletion = branchDeletionSuccess(branch, hash);
            result.all.push(deletion);
            result.branches[branch] = deletion;
          }),
          new LineParser(deleteErrorRegex, (result, [branch]) => {
            const deletion = branchDeletionFailure(branch);
            result.errors.push(deletion);
            result.all.push(deletion);
            result.branches[branch] = deletion;
          })
        ];
        parseBranchDeletions = /* @__PURE__ */ __name((stdOut, stdErr) => {
          return parseStringResponse(new BranchDeletionBatch(), parsers8, [stdOut, stdErr]);
        }, "parseBranchDeletions");
      }
    });
    init_BranchSummary = __esm2({
      "src/lib/responses/BranchSummary.ts"() {
        "use strict";
        BranchSummaryResult = class {
          static {
            __name(this, "BranchSummaryResult");
          }
          constructor() {
            this.all = [];
            this.branches = {};
            this.current = "";
            this.detached = false;
          }
          push(status, detached, name3, commit, label) {
            if (status === "*") {
              this.detached = detached;
              this.current = name3;
            }
            this.all.push(name3);
            this.branches[name3] = {
              current: status === "*",
              linkedWorkTree: status === "+",
              name: name3,
              commit,
              label
            };
          }
        };
      }
    });
    __name(branchStatus, "branchStatus");
    __name(parseBranchSummary, "parseBranchSummary");
    init_parse_branch = __esm2({
      "src/lib/parsers/parse-branch.ts"() {
        "use strict";
        init_BranchSummary();
        init_utils6();
        parsers9 = [
          new LineParser(
            /^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/,
            (result, [current, name3, commit, label]) => {
              result.push(branchStatus(current), true, name3, commit, label);
            }
          ),
          new LineParser(
            /^([*+]\s)?(\S+)\s+([a-z0-9]+)\s?(.*)$/s,
            (result, [current, name3, commit, label]) => {
              result.push(branchStatus(current), false, name3, commit, label);
            }
          )
        ];
      }
    });
    branch_exports = {};
    __export2(branch_exports, {
      branchLocalTask: /* @__PURE__ */ __name(() => branchLocalTask, "branchLocalTask"),
      branchTask: /* @__PURE__ */ __name(() => branchTask, "branchTask"),
      containsDeleteBranchCommand: /* @__PURE__ */ __name(() => containsDeleteBranchCommand, "containsDeleteBranchCommand"),
      deleteBranchTask: /* @__PURE__ */ __name(() => deleteBranchTask, "deleteBranchTask"),
      deleteBranchesTask: /* @__PURE__ */ __name(() => deleteBranchesTask, "deleteBranchesTask")
    });
    __name(containsDeleteBranchCommand, "containsDeleteBranchCommand");
    __name(branchTask, "branchTask");
    __name(branchLocalTask, "branchLocalTask");
    __name(deleteBranchesTask, "deleteBranchesTask");
    __name(deleteBranchTask, "deleteBranchTask");
    init_branch = __esm2({
      "src/lib/tasks/branch.ts"() {
        "use strict";
        init_git_response_error();
        init_parse_branch_delete();
        init_parse_branch();
        init_utils6();
      }
    });
    init_CheckIgnore = __esm2({
      "src/lib/responses/CheckIgnore.ts"() {
        "use strict";
        parseCheckIgnore = /* @__PURE__ */ __name((text) => {
          return text.split(/\n/g).map((line) => line.trim()).filter((file) => !!file);
        }, "parseCheckIgnore");
      }
    });
    check_ignore_exports = {};
    __export2(check_ignore_exports, {
      checkIgnoreTask: /* @__PURE__ */ __name(() => checkIgnoreTask, "checkIgnoreTask")
    });
    __name(checkIgnoreTask, "checkIgnoreTask");
    init_check_ignore = __esm2({
      "src/lib/tasks/check-ignore.ts"() {
        "use strict";
        init_CheckIgnore();
      }
    });
    clone_exports = {};
    __export2(clone_exports, {
      cloneMirrorTask: /* @__PURE__ */ __name(() => cloneMirrorTask, "cloneMirrorTask"),
      cloneTask: /* @__PURE__ */ __name(() => cloneTask, "cloneTask")
    });
    __name(disallowedCommand, "disallowedCommand");
    __name(cloneTask, "cloneTask");
    __name(cloneMirrorTask, "cloneMirrorTask");
    init_clone = __esm2({
      "src/lib/tasks/clone.ts"() {
        "use strict";
        init_task2();
        init_utils6();
      }
    });
    __name(parseFetchResult, "parseFetchResult");
    init_parse_fetch = __esm2({
      "src/lib/parsers/parse-fetch.ts"() {
        "use strict";
        init_utils6();
        parsers10 = [
          new LineParser(/From (.+)$/, (result, [remote]) => {
            result.remote = remote;
          }),
          new LineParser(/\* \[new branch]\s+(\S+)\s*-> (.+)$/, (result, [name3, tracking]) => {
            result.branches.push({
              name: name3,
              tracking
            });
          }),
          new LineParser(/\* \[new tag]\s+(\S+)\s*-> (.+)$/, (result, [name3, tracking]) => {
            result.tags.push({
              name: name3,
              tracking
            });
          }),
          new LineParser(/- \[deleted]\s+\S+\s*-> (.+)$/, (result, [tracking]) => {
            result.deleted.push({
              tracking
            });
          }),
          new LineParser(
            /\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/,
            (result, [from, to, name3, tracking]) => {
              result.updated.push({
                name: name3,
                tracking,
                to,
                from
              });
            }
          )
        ];
      }
    });
    fetch_exports = {};
    __export2(fetch_exports, {
      fetchTask: /* @__PURE__ */ __name(() => fetchTask, "fetchTask")
    });
    __name(disallowedCommand2, "disallowedCommand2");
    __name(fetchTask, "fetchTask");
    init_fetch = __esm2({
      "src/lib/tasks/fetch.ts"() {
        "use strict";
        init_parse_fetch();
        init_task2();
      }
    });
    __name(parseMoveResult, "parseMoveResult");
    init_parse_move = __esm2({
      "src/lib/parsers/parse-move.ts"() {
        "use strict";
        init_utils6();
        parsers11 = [
          new LineParser(/^Renaming (.+) to (.+)$/, (result, [from, to]) => {
            result.moves.push({ from, to });
          })
        ];
      }
    });
    move_exports = {};
    __export2(move_exports, {
      moveTask: /* @__PURE__ */ __name(() => moveTask, "moveTask")
    });
    __name(moveTask, "moveTask");
    init_move = __esm2({
      "src/lib/tasks/move.ts"() {
        "use strict";
        init_parse_move();
        init_utils6();
      }
    });
    pull_exports = {};
    __export2(pull_exports, {
      pullTask: /* @__PURE__ */ __name(() => pullTask, "pullTask")
    });
    __name(pullTask, "pullTask");
    init_pull = __esm2({
      "src/lib/tasks/pull.ts"() {
        "use strict";
        init_git_response_error();
        init_parse_pull();
        init_utils6();
      }
    });
    __name(parseGetRemotes, "parseGetRemotes");
    __name(parseGetRemotesVerbose, "parseGetRemotesVerbose");
    __name(forEach, "forEach");
    init_GetRemoteSummary = __esm2({
      "src/lib/responses/GetRemoteSummary.ts"() {
        "use strict";
        init_utils6();
      }
    });
    remote_exports = {};
    __export2(remote_exports, {
      addRemoteTask: /* @__PURE__ */ __name(() => addRemoteTask, "addRemoteTask"),
      getRemotesTask: /* @__PURE__ */ __name(() => getRemotesTask, "getRemotesTask"),
      listRemotesTask: /* @__PURE__ */ __name(() => listRemotesTask, "listRemotesTask"),
      remoteTask: /* @__PURE__ */ __name(() => remoteTask, "remoteTask"),
      removeRemoteTask: /* @__PURE__ */ __name(() => removeRemoteTask, "removeRemoteTask")
    });
    __name(addRemoteTask, "addRemoteTask");
    __name(getRemotesTask, "getRemotesTask");
    __name(listRemotesTask, "listRemotesTask");
    __name(remoteTask, "remoteTask");
    __name(removeRemoteTask, "removeRemoteTask");
    init_remote = __esm2({
      "src/lib/tasks/remote.ts"() {
        "use strict";
        init_GetRemoteSummary();
        init_task2();
      }
    });
    stash_list_exports = {};
    __export2(stash_list_exports, {
      stashListTask: /* @__PURE__ */ __name(() => stashListTask, "stashListTask")
    });
    __name(stashListTask, "stashListTask");
    init_stash_list = __esm2({
      "src/lib/tasks/stash-list.ts"() {
        "use strict";
        init_log_format();
        init_parse_list_log_summary();
        init_diff();
        init_log2();
      }
    });
    sub_module_exports = {};
    __export2(sub_module_exports, {
      addSubModuleTask: /* @__PURE__ */ __name(() => addSubModuleTask, "addSubModuleTask"),
      initSubModuleTask: /* @__PURE__ */ __name(() => initSubModuleTask, "initSubModuleTask"),
      subModuleTask: /* @__PURE__ */ __name(() => subModuleTask, "subModuleTask"),
      updateSubModuleTask: /* @__PURE__ */ __name(() => updateSubModuleTask, "updateSubModuleTask")
    });
    __name(addSubModuleTask, "addSubModuleTask");
    __name(initSubModuleTask, "initSubModuleTask");
    __name(subModuleTask, "subModuleTask");
    __name(updateSubModuleTask, "updateSubModuleTask");
    init_sub_module = __esm2({
      "src/lib/tasks/sub-module.ts"() {
        "use strict";
        init_task2();
      }
    });
    __name(singleSorted, "singleSorted");
    __name(sorted, "sorted");
    __name(trimmed, "trimmed");
    __name(toNumber, "toNumber");
    init_TagList = __esm2({
      "src/lib/responses/TagList.ts"() {
        "use strict";
        TagList = class {
          static {
            __name(this, "TagList");
          }
          constructor(all2, latest) {
            this.all = all2;
            this.latest = latest;
          }
        };
        parseTagList = /* @__PURE__ */ __name(function(data, customSort = false) {
          const tags = data.split("\n").map(trimmed).filter(Boolean);
          if (!customSort) {
            tags.sort(function(tagA, tagB) {
              const partsA = tagA.split(".");
              const partsB = tagB.split(".");
              if (partsA.length === 1 || partsB.length === 1) {
                return singleSorted(toNumber(partsA[0]), toNumber(partsB[0]));
              }
              for (let i = 0, l2 = Math.max(partsA.length, partsB.length); i < l2; i++) {
                const diff4 = sorted(toNumber(partsA[i]), toNumber(partsB[i]));
                if (diff4) {
                  return diff4;
                }
              }
              return 0;
            });
          }
          const latest = customSort ? tags[0] : [...tags].reverse().find((tag2) => tag2.indexOf(".") >= 0);
          return new TagList(tags, latest);
        }, "parseTagList");
      }
    });
    tag_exports = {};
    __export2(tag_exports, {
      addAnnotatedTagTask: /* @__PURE__ */ __name(() => addAnnotatedTagTask, "addAnnotatedTagTask"),
      addTagTask: /* @__PURE__ */ __name(() => addTagTask, "addTagTask"),
      tagListTask: /* @__PURE__ */ __name(() => tagListTask, "tagListTask")
    });
    __name(tagListTask, "tagListTask");
    __name(addTagTask, "addTagTask");
    __name(addAnnotatedTagTask, "addAnnotatedTagTask");
    init_tag = __esm2({
      "src/lib/tasks/tag.ts"() {
        "use strict";
        init_TagList();
      }
    });
    require_git = __commonJS2({
      "src/git.js"(exports2, module2) {
        "use strict";
        var { GitExecutor: GitExecutor2 } = (init_git_executor(), __toCommonJS2(git_executor_exports));
        var { SimpleGitApi: SimpleGitApi2 } = (init_simple_git_api(), __toCommonJS2(simple_git_api_exports));
        var { Scheduler: Scheduler2 } = (init_scheduler(), __toCommonJS2(scheduler_exports));
        var { configurationErrorTask: configurationErrorTask2 } = (init_task2(), __toCommonJS2(task_exports));
        var {
          asArray: asArray2,
          filterArray: filterArray2,
          filterPrimitives: filterPrimitives2,
          filterString: filterString2,
          filterStringOrStringArray: filterStringOrStringArray2,
          filterType: filterType2,
          getTrailingOptions: getTrailingOptions2,
          trailingFunctionArgument: trailingFunctionArgument2,
          trailingOptionsArgument: trailingOptionsArgument2
        } = (init_utils6(), __toCommonJS2(utils_exports));
        var { applyPatchTask: applyPatchTask2 } = (init_apply_patch(), __toCommonJS2(apply_patch_exports));
        var {
          branchTask: branchTask2,
          branchLocalTask: branchLocalTask2,
          deleteBranchesTask: deleteBranchesTask2,
          deleteBranchTask: deleteBranchTask2
        } = (init_branch(), __toCommonJS2(branch_exports));
        var { checkIgnoreTask: checkIgnoreTask2 } = (init_check_ignore(), __toCommonJS2(check_ignore_exports));
        var { checkIsRepoTask: checkIsRepoTask2 } = (init_check_is_repo(), __toCommonJS2(check_is_repo_exports));
        var { cloneTask: cloneTask2, cloneMirrorTask: cloneMirrorTask2 } = (init_clone(), __toCommonJS2(clone_exports));
        var { cleanWithOptionsTask: cleanWithOptionsTask2, isCleanOptionsArray: isCleanOptionsArray2 } = (init_clean(), __toCommonJS2(clean_exports));
        var { diffSummaryTask: diffSummaryTask2 } = (init_diff(), __toCommonJS2(diff_exports));
        var { fetchTask: fetchTask2 } = (init_fetch(), __toCommonJS2(fetch_exports));
        var { moveTask: moveTask2 } = (init_move(), __toCommonJS2(move_exports));
        var { pullTask: pullTask2 } = (init_pull(), __toCommonJS2(pull_exports));
        var { pushTagsTask: pushTagsTask2 } = (init_push(), __toCommonJS2(push_exports));
        var {
          addRemoteTask: addRemoteTask2,
          getRemotesTask: getRemotesTask2,
          listRemotesTask: listRemotesTask2,
          remoteTask: remoteTask2,
          removeRemoteTask: removeRemoteTask2
        } = (init_remote(), __toCommonJS2(remote_exports));
        var { getResetMode: getResetMode2, resetTask: resetTask2 } = (init_reset(), __toCommonJS2(reset_exports));
        var { stashListTask: stashListTask2 } = (init_stash_list(), __toCommonJS2(stash_list_exports));
        var {
          addSubModuleTask: addSubModuleTask2,
          initSubModuleTask: initSubModuleTask2,
          subModuleTask: subModuleTask2,
          updateSubModuleTask: updateSubModuleTask2
        } = (init_sub_module(), __toCommonJS2(sub_module_exports));
        var { addAnnotatedTagTask: addAnnotatedTagTask2, addTagTask: addTagTask2, tagListTask: tagListTask2 } = (init_tag(), __toCommonJS2(tag_exports));
        var { straightThroughBufferTask: straightThroughBufferTask2, straightThroughStringTask: straightThroughStringTask2 } = (init_task2(), __toCommonJS2(task_exports));
        function Git2(options2, plugins) {
          this._plugins = plugins;
          this._executor = new GitExecutor2(
            options2.baseDir,
            new Scheduler2(options2.maxConcurrentProcesses),
            plugins
          );
          this._trimmed = options2.trimmed;
        }
        __name(Git2, "Git2");
        (Git2.prototype = Object.create(SimpleGitApi2.prototype)).constructor = Git2;
        Git2.prototype.customBinary = function(command2) {
          this._plugins.reconfigure("binary", command2);
          return this;
        };
        Git2.prototype.env = function(name3, value) {
          if (arguments.length === 1 && typeof name3 === "object") {
            this._executor.env = name3;
          } else {
            (this._executor.env = this._executor.env || {})[name3] = value;
          }
          return this;
        };
        Git2.prototype.stashList = function(options2) {
          return this._runTask(
            stashListTask2(
              trailingOptionsArgument2(arguments) || {},
              filterArray2(options2) && options2 || []
            ),
            trailingFunctionArgument2(arguments)
          );
        };
        function createCloneTask(api, task, repoPath, localPath) {
          if (typeof repoPath !== "string") {
            return configurationErrorTask2(`git.${api}() requires a string 'repoPath'`);
          }
          return task(repoPath, filterType2(localPath, filterString2), getTrailingOptions2(arguments));
        }
        __name(createCloneTask, "createCloneTask");
        Git2.prototype.clone = function() {
          return this._runTask(
            createCloneTask("clone", cloneTask2, ...arguments),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.mirror = function() {
          return this._runTask(
            createCloneTask("mirror", cloneMirrorTask2, ...arguments),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.mv = function(from, to) {
          return this._runTask(moveTask2(from, to), trailingFunctionArgument2(arguments));
        };
        Git2.prototype.checkoutLatestTag = function(then) {
          var git = this;
          return this.pull(function() {
            git.tags(function(err, tags) {
              git.checkout(tags.latest, then);
            });
          });
        };
        Git2.prototype.pull = function(remote, branch, options2, then) {
          return this._runTask(
            pullTask2(
              filterType2(remote, filterString2),
              filterType2(branch, filterString2),
              getTrailingOptions2(arguments)
            ),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.fetch = function(remote, branch) {
          return this._runTask(
            fetchTask2(
              filterType2(remote, filterString2),
              filterType2(branch, filterString2),
              getTrailingOptions2(arguments)
            ),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.silent = function(silence) {
          console.warn(
            "simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this will be an error in version 3"
          );
          return this;
        };
        Git2.prototype.tags = function(options2, then) {
          return this._runTask(
            tagListTask2(getTrailingOptions2(arguments)),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.rebase = function() {
          return this._runTask(
            straightThroughStringTask2(["rebase", ...getTrailingOptions2(arguments)]),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.reset = function(mode) {
          return this._runTask(
            resetTask2(getResetMode2(mode), getTrailingOptions2(arguments)),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.revert = function(commit) {
          const next = trailingFunctionArgument2(arguments);
          if (typeof commit !== "string") {
            return this._runTask(configurationErrorTask2("Commit must be a string"), next);
          }
          return this._runTask(
            straightThroughStringTask2(["revert", ...getTrailingOptions2(arguments, 0, true), commit]),
            next
          );
        };
        Git2.prototype.addTag = function(name3) {
          const task = typeof name3 === "string" ? addTagTask2(name3) : configurationErrorTask2("Git.addTag requires a tag name");
          return this._runTask(task, trailingFunctionArgument2(arguments));
        };
        Git2.prototype.addAnnotatedTag = function(tagName, tagMessage) {
          return this._runTask(
            addAnnotatedTagTask2(tagName, tagMessage),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.deleteLocalBranch = function(branchName, forceDelete, then) {
          return this._runTask(
            deleteBranchTask2(branchName, typeof forceDelete === "boolean" ? forceDelete : false),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.deleteLocalBranches = function(branchNames, forceDelete, then) {
          return this._runTask(
            deleteBranchesTask2(branchNames, typeof forceDelete === "boolean" ? forceDelete : false),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.branch = function(options2, then) {
          return this._runTask(
            branchTask2(getTrailingOptions2(arguments)),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.branchLocal = function(then) {
          return this._runTask(branchLocalTask2(), trailingFunctionArgument2(arguments));
        };
        Git2.prototype.raw = function(commands) {
          const createRestCommands = !Array.isArray(commands);
          const command2 = [].slice.call(createRestCommands ? arguments : commands, 0);
          for (let i = 0; i < command2.length && createRestCommands; i++) {
            if (!filterPrimitives2(command2[i])) {
              command2.splice(i, command2.length - i);
              break;
            }
          }
          command2.push(...getTrailingOptions2(arguments, 0, true));
          var next = trailingFunctionArgument2(arguments);
          if (!command2.length) {
            return this._runTask(
              configurationErrorTask2("Raw: must supply one or more command to execute"),
              next
            );
          }
          return this._runTask(straightThroughStringTask2(command2, this._trimmed), next);
        };
        Git2.prototype.submoduleAdd = function(repo, path108, then) {
          return this._runTask(addSubModuleTask2(repo, path108), trailingFunctionArgument2(arguments));
        };
        Git2.prototype.submoduleUpdate = function(args, then) {
          return this._runTask(
            updateSubModuleTask2(getTrailingOptions2(arguments, true)),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.submoduleInit = function(args, then) {
          return this._runTask(
            initSubModuleTask2(getTrailingOptions2(arguments, true)),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.subModule = function(options2, then) {
          return this._runTask(
            subModuleTask2(getTrailingOptions2(arguments)),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.listRemote = function() {
          return this._runTask(
            listRemotesTask2(getTrailingOptions2(arguments)),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.addRemote = function(remoteName, remoteRepo, then) {
          return this._runTask(
            addRemoteTask2(remoteName, remoteRepo, getTrailingOptions2(arguments)),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.removeRemote = function(remoteName, then) {
          return this._runTask(removeRemoteTask2(remoteName), trailingFunctionArgument2(arguments));
        };
        Git2.prototype.getRemotes = function(verbose, then) {
          return this._runTask(getRemotesTask2(verbose === true), trailingFunctionArgument2(arguments));
        };
        Git2.prototype.remote = function(options2, then) {
          return this._runTask(
            remoteTask2(getTrailingOptions2(arguments)),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.tag = function(options2, then) {
          const command2 = getTrailingOptions2(arguments);
          if (command2[0] !== "tag") {
            command2.unshift("tag");
          }
          return this._runTask(straightThroughStringTask2(command2), trailingFunctionArgument2(arguments));
        };
        Git2.prototype.updateServerInfo = function(then) {
          return this._runTask(
            straightThroughStringTask2(["update-server-info"]),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.pushTags = function(remote, then) {
          const task = pushTagsTask2(
            { remote: filterType2(remote, filterString2) },
            getTrailingOptions2(arguments)
          );
          return this._runTask(task, trailingFunctionArgument2(arguments));
        };
        Git2.prototype.rm = function(files) {
          return this._runTask(
            straightThroughStringTask2(["rm", "-f", ...asArray2(files)]),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.rmKeepLocal = function(files) {
          return this._runTask(
            straightThroughStringTask2(["rm", "--cached", ...asArray2(files)]),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.catFile = function(options2, then) {
          return this._catFile("utf-8", arguments);
        };
        Git2.prototype.binaryCatFile = function() {
          return this._catFile("buffer", arguments);
        };
        Git2.prototype._catFile = function(format4, args) {
          var handler = trailingFunctionArgument2(args);
          var command2 = ["cat-file"];
          var options2 = args[0];
          if (typeof options2 === "string") {
            return this._runTask(
              configurationErrorTask2("Git.catFile: options must be supplied as an array of strings"),
              handler
            );
          }
          if (Array.isArray(options2)) {
            command2.push.apply(command2, options2);
          }
          const task = format4 === "buffer" ? straightThroughBufferTask2(command2) : straightThroughStringTask2(command2);
          return this._runTask(task, handler);
        };
        Git2.prototype.diff = function(options2, then) {
          const task = filterString2(options2) ? configurationErrorTask2(
            "git.diff: supplying options as a single string is no longer supported, switch to an array of strings"
          ) : straightThroughStringTask2(["diff", ...getTrailingOptions2(arguments)]);
          return this._runTask(task, trailingFunctionArgument2(arguments));
        };
        Git2.prototype.diffSummary = function() {
          return this._runTask(
            diffSummaryTask2(getTrailingOptions2(arguments, 1)),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.applyPatch = function(patches) {
          const task = !filterStringOrStringArray2(patches) ? configurationErrorTask2(
            `git.applyPatch requires one or more string patches as the first argument`
          ) : applyPatchTask2(asArray2(patches), getTrailingOptions2([].slice.call(arguments, 1)));
          return this._runTask(task, trailingFunctionArgument2(arguments));
        };
        Git2.prototype.revparse = function() {
          const commands = ["rev-parse", ...getTrailingOptions2(arguments, true)];
          return this._runTask(
            straightThroughStringTask2(commands, true),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.clean = function(mode, options2, then) {
          const usingCleanOptionsArray = isCleanOptionsArray2(mode);
          const cleanMode = usingCleanOptionsArray && mode.join("") || filterType2(mode, filterString2) || "";
          const customArgs = getTrailingOptions2([].slice.call(arguments, usingCleanOptionsArray ? 1 : 0));
          return this._runTask(
            cleanWithOptionsTask2(cleanMode, customArgs),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.exec = function(then) {
          const task = {
            commands: [],
            format: "utf-8",
            parser() {
              if (typeof then === "function") {
                then();
              }
            }
          };
          return this._runTask(task);
        };
        Git2.prototype.clearQueue = function() {
          return this;
        };
        Git2.prototype.checkIgnore = function(pathnames, then) {
          return this._runTask(
            checkIgnoreTask2(asArray2(filterType2(pathnames, filterStringOrStringArray2, []))),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.checkIsRepo = function(checkType, then) {
          return this._runTask(
            checkIsRepoTask2(filterType2(checkType, filterString2)),
            trailingFunctionArgument2(arguments)
          );
        };
        module2.exports = Git2;
      }
    });
    init_pathspec();
    init_git_error();
    GitConstructError = class extends GitError {
      static {
        __name(this, "GitConstructError");
      }
      constructor(config, message) {
        super(void 0, message);
        this.config = config;
      }
    };
    init_git_error();
    init_git_error();
    GitPluginError = class extends GitError {
      static {
        __name(this, "GitPluginError");
      }
      constructor(task, plugin, message) {
        super(task, message);
        this.task = task;
        this.plugin = plugin;
        Object.setPrototypeOf(this, new.target.prototype);
      }
    };
    init_git_response_error();
    init_task_configuration_error();
    init_check_is_repo();
    init_clean();
    init_config2();
    init_diff_name_status();
    init_grep();
    init_reset();
    __name(abortPlugin, "abortPlugin");
    __name(isConfigSwitch, "isConfigSwitch");
    __name(preventProtocolOverride, "preventProtocolOverride");
    __name(preventUploadPack, "preventUploadPack");
    __name(blockUnsafeOperationsPlugin, "blockUnsafeOperationsPlugin");
    init_utils6();
    __name(commandConfigPrefixingPlugin, "commandConfigPrefixingPlugin");
    init_utils6();
    never = (0, import_promise_deferred2.deferred)().promise;
    __name(completionDetectionPlugin, "completionDetectionPlugin");
    init_utils6();
    WRONG_NUMBER_ERR = `Invalid value supplied for custom binary, requires a single string or an array containing either one or two strings`;
    WRONG_CHARS_ERR = `Invalid value supplied for custom binary, restricted characters must be removed or supply the unsafe.allowUnsafeCustomBinary option`;
    __name(isBadArgument, "isBadArgument");
    __name(toBinaryConfig, "toBinaryConfig");
    __name(customBinaryPlugin, "customBinaryPlugin");
    init_git_error();
    __name(isTaskError, "isTaskError");
    __name(getErrorMessage2, "getErrorMessage");
    __name(errorDetectionHandler, "errorDetectionHandler");
    __name(errorDetectionPlugin, "errorDetectionPlugin");
    init_utils6();
    PluginStore = class {
      static {
        __name(this, "PluginStore");
      }
      constructor() {
        this.plugins = /* @__PURE__ */ new Set();
        this.events = new EventEmitter7();
      }
      on(type, listener) {
        this.events.on(type, listener);
      }
      reconfigure(type, data) {
        this.events.emit(type, data);
      }
      append(type, action) {
        const plugin = append(this.plugins, { type, action });
        return () => this.plugins.delete(plugin);
      }
      add(plugin) {
        const plugins = [];
        asArray(plugin).forEach((plugin2) => plugin2 && this.plugins.add(append(plugins, plugin2)));
        return () => {
          plugins.forEach((plugin2) => this.plugins.delete(plugin2));
        };
      }
      exec(type, data, context2) {
        let output = data;
        const contextual = Object.freeze(Object.create(context2));
        for (const plugin of this.plugins) {
          if (plugin.type === type) {
            output = plugin.action(output, contextual);
          }
        }
        return output;
      }
    };
    init_utils6();
    __name(progressMonitorPlugin, "progressMonitorPlugin");
    __name(progressEventStage, "progressEventStage");
    init_utils6();
    __name(spawnOptionsPlugin, "spawnOptionsPlugin");
    __name(timeoutPlugin, "timeoutPlugin");
    init_pathspec();
    __name(suffixPathsPlugin, "suffixPathsPlugin");
    init_utils6();
    Git = require_git();
    __name(gitInstanceFactory, "gitInstanceFactory");
    init_git_response_error();
    simpleGit = gitInstanceFactory;
  }
});

// packages/core/dist/src/services/gitService.js
import * as fs29 from "node:fs/promises";
import * as path27 from "node:path";
var GitService;
var init_gitService = __esm({
  "packages/core/dist/src/services/gitService.js"() {
    "use strict";
    init_esbuild_shims();
    init_shell_utils();
    init_esm10();
    init_errors();
    GitService = class {
      static {
        __name(this, "GitService");
      }
      projectRoot;
      storage;
      constructor(projectRoot, storage) {
        this.projectRoot = path27.resolve(projectRoot);
        this.storage = storage;
      }
      getHistoryDir() {
        return this.storage.getHistoryDir();
      }
      async initialize() {
        const { available: gitAvailable } = isCommandAvailable("git");
        if (!gitAvailable) {
          throw new Error("Checkpointing is enabled, but Git is not installed. Please install Git or disable checkpointing to continue.");
        }
        try {
          await this.setupShadowGitRepository();
        } catch (error) {
          throw new Error(`Failed to initialize checkpointing: ${error instanceof Error ? error.message : "Unknown error"}. Please check that Git is working properly or disable checkpointing.`);
        }
      }
      /**
       * Creates a hidden git repository in the project root.
       * The Git repository is used to support checkpointing.
       */
      async setupShadowGitRepository() {
        const repoDir = this.getHistoryDir();
        const gitConfigPath = path27.join(repoDir, ".gitconfig");
        await fs29.mkdir(repoDir, { recursive: true });
        const gitConfigContent = "[user]\n  name = Qwen Code\n  email = qwen-code@qwen.ai\n[commit]\n  gpgsign = false\n";
        await fs29.writeFile(gitConfigPath, gitConfigContent);
        const repo = simpleGit(repoDir);
        const isRepoDefined = await repo.checkIsRepo(CheckRepoActions.IS_REPO_ROOT);
        if (!isRepoDefined) {
          await repo.init(false, {
            "--initial-branch": "main"
          });
          await repo.commit("Initial commit", { "--allow-empty": null });
        }
        const userGitIgnorePath = path27.join(this.projectRoot, ".gitignore");
        const shadowGitIgnorePath = path27.join(repoDir, ".gitignore");
        let userGitIgnoreContent = "";
        try {
          userGitIgnoreContent = await fs29.readFile(userGitIgnorePath, "utf-8");
        } catch (error) {
          if (isNodeError(error) && error.code !== "ENOENT") {
            throw error;
          }
        }
        await fs29.writeFile(shadowGitIgnorePath, userGitIgnoreContent);
      }
      get shadowGitRepository() {
        const repoDir = this.getHistoryDir();
        return simpleGit(this.projectRoot).env({
          GIT_DIR: path27.join(repoDir, ".git"),
          GIT_WORK_TREE: this.projectRoot,
          // Prevent git from using the user's global git config.
          HOME: repoDir,
          XDG_CONFIG_HOME: repoDir
        });
      }
      async getCurrentCommitHash() {
        const hash = await this.shadowGitRepository.raw("rev-parse", "HEAD");
        return hash.trim();
      }
      async createFileSnapshot(message) {
        try {
          const repo = this.shadowGitRepository;
          await repo.add(".");
          const commitResult = await repo.commit(message);
          return commitResult.commit;
        } catch (error) {
          throw new Error(`Failed to create checkpoint snapshot: ${error instanceof Error ? error.message : "Unknown error"}. Checkpointing may not be working properly.`);
        }
      }
      async restoreProjectFromSnapshot(commitHash) {
        const repo = this.shadowGitRepository;
        await repo.raw(["restore", "--source", commitHash, "."]);
        await repo.clean("f", ["-d"]);
      }
    };
  }
});

// packages/core/node_modules/mime/dist/types/standard.js
var types2, standard_default;
var init_standard = __esm({
  "packages/core/node_modules/mime/dist/types/standard.js"() {
    init_esbuild_shims();
    types2 = {
      "application/andrew-inset": ["ez"],
      "application/appinstaller": ["appinstaller"],
      "application/applixware": ["aw"],
      "application/appx": ["appx"],
      "application/appxbundle": ["appxbundle"],
      "application/atom+xml": ["atom"],
      "application/atomcat+xml": ["atomcat"],
      "application/atomdeleted+xml": ["atomdeleted"],
      "application/atomsvc+xml": ["atomsvc"],
      "application/atsc-dwd+xml": ["dwd"],
      "application/atsc-held+xml": ["held"],
      "application/atsc-rsat+xml": ["rsat"],
      "application/automationml-aml+xml": ["aml"],
      "application/automationml-amlx+zip": ["amlx"],
      "application/bdoc": ["bdoc"],
      "application/calendar+xml": ["xcs"],
      "application/ccxml+xml": ["ccxml"],
      "application/cdfx+xml": ["cdfx"],
      "application/cdmi-capability": ["cdmia"],
      "application/cdmi-container": ["cdmic"],
      "application/cdmi-domain": ["cdmid"],
      "application/cdmi-object": ["cdmio"],
      "application/cdmi-queue": ["cdmiq"],
      "application/cpl+xml": ["cpl"],
      "application/cu-seeme": ["cu"],
      "application/cwl": ["cwl"],
      "application/dash+xml": ["mpd"],
      "application/dash-patch+xml": ["mpp"],
      "application/davmount+xml": ["davmount"],
      "application/dicom": ["dcm"],
      "application/docbook+xml": ["dbk"],
      "application/dssc+der": ["dssc"],
      "application/dssc+xml": ["xdssc"],
      "application/ecmascript": ["ecma"],
      "application/emma+xml": ["emma"],
      "application/emotionml+xml": ["emotionml"],
      "application/epub+zip": ["epub"],
      "application/exi": ["exi"],
      "application/express": ["exp"],
      "application/fdf": ["fdf"],
      "application/fdt+xml": ["fdt"],
      "application/font-tdpfr": ["pfr"],
      "application/geo+json": ["geojson"],
      "application/gml+xml": ["gml"],
      "application/gpx+xml": ["gpx"],
      "application/gxf": ["gxf"],
      "application/gzip": ["gz"],
      "application/hjson": ["hjson"],
      "application/hyperstudio": ["stk"],
      "application/inkml+xml": ["ink", "inkml"],
      "application/ipfix": ["ipfix"],
      "application/its+xml": ["its"],
      "application/java-archive": ["jar", "war", "ear"],
      "application/java-serialized-object": ["ser"],
      "application/java-vm": ["class"],
      "application/javascript": ["*js"],
      "application/json": ["json", "map"],
      "application/json5": ["json5"],
      "application/jsonml+json": ["jsonml"],
      "application/ld+json": ["jsonld"],
      "application/lgr+xml": ["lgr"],
      "application/lost+xml": ["lostxml"],
      "application/mac-binhex40": ["hqx"],
      "application/mac-compactpro": ["cpt"],
      "application/mads+xml": ["mads"],
      "application/manifest+json": ["webmanifest"],
      "application/marc": ["mrc"],
      "application/marcxml+xml": ["mrcx"],
      "application/mathematica": ["ma", "nb", "mb"],
      "application/mathml+xml": ["mathml"],
      "application/mbox": ["mbox"],
      "application/media-policy-dataset+xml": ["mpf"],
      "application/mediaservercontrol+xml": ["mscml"],
      "application/metalink+xml": ["metalink"],
      "application/metalink4+xml": ["meta4"],
      "application/mets+xml": ["mets"],
      "application/mmt-aei+xml": ["maei"],
      "application/mmt-usd+xml": ["musd"],
      "application/mods+xml": ["mods"],
      "application/mp21": ["m21", "mp21"],
      "application/mp4": ["*mp4", "*mpg4", "mp4s", "m4p"],
      "application/msix": ["msix"],
      "application/msixbundle": ["msixbundle"],
      "application/msword": ["doc", "dot"],
      "application/mxf": ["mxf"],
      "application/n-quads": ["nq"],
      "application/n-triples": ["nt"],
      "application/node": ["cjs"],
      "application/octet-stream": [
        "bin",
        "dms",
        "lrf",
        "mar",
        "so",
        "dist",
        "distz",
        "pkg",
        "bpk",
        "dump",
        "elc",
        "deploy",
        "exe",
        "dll",
        "deb",
        "dmg",
        "iso",
        "img",
        "msi",
        "msp",
        "msm",
        "buffer"
      ],
      "application/oda": ["oda"],
      "application/oebps-package+xml": ["opf"],
      "application/ogg": ["ogx"],
      "application/omdoc+xml": ["omdoc"],
      "application/onenote": [
        "onetoc",
        "onetoc2",
        "onetmp",
        "onepkg",
        "one",
        "onea"
      ],
      "application/oxps": ["oxps"],
      "application/p2p-overlay+xml": ["relo"],
      "application/patch-ops-error+xml": ["xer"],
      "application/pdf": ["pdf"],
      "application/pgp-encrypted": ["pgp"],
      "application/pgp-keys": ["asc"],
      "application/pgp-signature": ["sig", "*asc"],
      "application/pics-rules": ["prf"],
      "application/pkcs10": ["p10"],
      "application/pkcs7-mime": ["p7m", "p7c"],
      "application/pkcs7-signature": ["p7s"],
      "application/pkcs8": ["p8"],
      "application/pkix-attr-cert": ["ac"],
      "application/pkix-cert": ["cer"],
      "application/pkix-crl": ["crl"],
      "application/pkix-pkipath": ["pkipath"],
      "application/pkixcmp": ["pki"],
      "application/pls+xml": ["pls"],
      "application/postscript": ["ai", "eps", "ps"],
      "application/provenance+xml": ["provx"],
      "application/pskc+xml": ["pskcxml"],
      "application/raml+yaml": ["raml"],
      "application/rdf+xml": ["rdf", "owl"],
      "application/reginfo+xml": ["rif"],
      "application/relax-ng-compact-syntax": ["rnc"],
      "application/resource-lists+xml": ["rl"],
      "application/resource-lists-diff+xml": ["rld"],
      "application/rls-services+xml": ["rs"],
      "application/route-apd+xml": ["rapd"],
      "application/route-s-tsid+xml": ["sls"],
      "application/route-usd+xml": ["rusd"],
      "application/rpki-ghostbusters": ["gbr"],
      "application/rpki-manifest": ["mft"],
      "application/rpki-roa": ["roa"],
      "application/rsd+xml": ["rsd"],
      "application/rss+xml": ["rss"],
      "application/rtf": ["rtf"],
      "application/sbml+xml": ["sbml"],
      "application/scvp-cv-request": ["scq"],
      "application/scvp-cv-response": ["scs"],
      "application/scvp-vp-request": ["spq"],
      "application/scvp-vp-response": ["spp"],
      "application/sdp": ["sdp"],
      "application/senml+xml": ["senmlx"],
      "application/sensml+xml": ["sensmlx"],
      "application/set-payment-initiation": ["setpay"],
      "application/set-registration-initiation": ["setreg"],
      "application/shf+xml": ["shf"],
      "application/sieve": ["siv", "sieve"],
      "application/smil+xml": ["smi", "smil"],
      "application/sparql-query": ["rq"],
      "application/sparql-results+xml": ["srx"],
      "application/sql": ["sql"],
      "application/srgs": ["gram"],
      "application/srgs+xml": ["grxml"],
      "application/sru+xml": ["sru"],
      "application/ssdl+xml": ["ssdl"],
      "application/ssml+xml": ["ssml"],
      "application/swid+xml": ["swidtag"],
      "application/tei+xml": ["tei", "teicorpus"],
      "application/thraud+xml": ["tfi"],
      "application/timestamped-data": ["tsd"],
      "application/toml": ["toml"],
      "application/trig": ["trig"],
      "application/ttml+xml": ["ttml"],
      "application/ubjson": ["ubj"],
      "application/urc-ressheet+xml": ["rsheet"],
      "application/urc-targetdesc+xml": ["td"],
      "application/voicexml+xml": ["vxml"],
      "application/wasm": ["wasm"],
      "application/watcherinfo+xml": ["wif"],
      "application/widget": ["wgt"],
      "application/winhlp": ["hlp"],
      "application/wsdl+xml": ["wsdl"],
      "application/wspolicy+xml": ["wspolicy"],
      "application/xaml+xml": ["xaml"],
      "application/xcap-att+xml": ["xav"],
      "application/xcap-caps+xml": ["xca"],
      "application/xcap-diff+xml": ["xdf"],
      "application/xcap-el+xml": ["xel"],
      "application/xcap-ns+xml": ["xns"],
      "application/xenc+xml": ["xenc"],
      "application/xfdf": ["xfdf"],
      "application/xhtml+xml": ["xhtml", "xht"],
      "application/xliff+xml": ["xlf"],
      "application/xml": ["xml", "xsl", "xsd", "rng"],
      "application/xml-dtd": ["dtd"],
      "application/xop+xml": ["xop"],
      "application/xproc+xml": ["xpl"],
      "application/xslt+xml": ["*xsl", "xslt"],
      "application/xspf+xml": ["xspf"],
      "application/xv+xml": ["mxml", "xhvml", "xvml", "xvm"],
      "application/yang": ["yang"],
      "application/yin+xml": ["yin"],
      "application/zip": ["zip"],
      "application/zip+dotlottie": ["lottie"],
      "audio/3gpp": ["*3gpp"],
      "audio/aac": ["adts", "aac"],
      "audio/adpcm": ["adp"],
      "audio/amr": ["amr"],
      "audio/basic": ["au", "snd"],
      "audio/midi": ["mid", "midi", "kar", "rmi"],
      "audio/mobile-xmf": ["mxmf"],
      "audio/mp3": ["*mp3"],
      "audio/mp4": ["m4a", "mp4a", "m4b"],
      "audio/mpeg": ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"],
      "audio/ogg": ["oga", "ogg", "spx", "opus"],
      "audio/s3m": ["s3m"],
      "audio/silk": ["sil"],
      "audio/wav": ["wav"],
      "audio/wave": ["*wav"],
      "audio/webm": ["weba"],
      "audio/xm": ["xm"],
      "font/collection": ["ttc"],
      "font/otf": ["otf"],
      "font/ttf": ["ttf"],
      "font/woff": ["woff"],
      "font/woff2": ["woff2"],
      "image/aces": ["exr"],
      "image/apng": ["apng"],
      "image/avci": ["avci"],
      "image/avcs": ["avcs"],
      "image/avif": ["avif"],
      "image/bmp": ["bmp", "dib"],
      "image/cgm": ["cgm"],
      "image/dicom-rle": ["drle"],
      "image/dpx": ["dpx"],
      "image/emf": ["emf"],
      "image/fits": ["fits"],
      "image/g3fax": ["g3"],
      "image/gif": ["gif"],
      "image/heic": ["heic"],
      "image/heic-sequence": ["heics"],
      "image/heif": ["heif"],
      "image/heif-sequence": ["heifs"],
      "image/hej2k": ["hej2"],
      "image/ief": ["ief"],
      "image/jaii": ["jaii"],
      "image/jais": ["jais"],
      "image/jls": ["jls"],
      "image/jp2": ["jp2", "jpg2"],
      "image/jpeg": ["jpg", "jpeg", "jpe"],
      "image/jph": ["jph"],
      "image/jphc": ["jhc"],
      "image/jpm": ["jpm", "jpgm"],
      "image/jpx": ["jpx", "jpf"],
      "image/jxl": ["jxl"],
      "image/jxr": ["jxr"],
      "image/jxra": ["jxra"],
      "image/jxrs": ["jxrs"],
      "image/jxs": ["jxs"],
      "image/jxsc": ["jxsc"],
      "image/jxsi": ["jxsi"],
      "image/jxss": ["jxss"],
      "image/ktx": ["ktx"],
      "image/ktx2": ["ktx2"],
      "image/pjpeg": ["jfif"],
      "image/png": ["png"],
      "image/sgi": ["sgi"],
      "image/svg+xml": ["svg", "svgz"],
      "image/t38": ["t38"],
      "image/tiff": ["tif", "tiff"],
      "image/tiff-fx": ["tfx"],
      "image/webp": ["webp"],
      "image/wmf": ["wmf"],
      "message/disposition-notification": ["disposition-notification"],
      "message/global": ["u8msg"],
      "message/global-delivery-status": ["u8dsn"],
      "message/global-disposition-notification": ["u8mdn"],
      "message/global-headers": ["u8hdr"],
      "message/rfc822": ["eml", "mime", "mht", "mhtml"],
      "model/3mf": ["3mf"],
      "model/gltf+json": ["gltf"],
      "model/gltf-binary": ["glb"],
      "model/iges": ["igs", "iges"],
      "model/jt": ["jt"],
      "model/mesh": ["msh", "mesh", "silo"],
      "model/mtl": ["mtl"],
      "model/obj": ["obj"],
      "model/prc": ["prc"],
      "model/step": ["step", "stp", "stpnc", "p21", "210"],
      "model/step+xml": ["stpx"],
      "model/step+zip": ["stpz"],
      "model/step-xml+zip": ["stpxz"],
      "model/stl": ["stl"],
      "model/u3d": ["u3d"],
      "model/vrml": ["wrl", "vrml"],
      "model/x3d+binary": ["*x3db", "x3dbz"],
      "model/x3d+fastinfoset": ["x3db"],
      "model/x3d+vrml": ["*x3dv", "x3dvz"],
      "model/x3d+xml": ["x3d", "x3dz"],
      "model/x3d-vrml": ["x3dv"],
      "text/cache-manifest": ["appcache", "manifest"],
      "text/calendar": ["ics", "ifb"],
      "text/coffeescript": ["coffee", "litcoffee"],
      "text/css": ["css"],
      "text/csv": ["csv"],
      "text/html": ["html", "htm", "shtml"],
      "text/jade": ["jade"],
      "text/javascript": ["js", "mjs"],
      "text/jsx": ["jsx"],
      "text/less": ["less"],
      "text/markdown": ["md", "markdown"],
      "text/mathml": ["mml"],
      "text/mdx": ["mdx"],
      "text/n3": ["n3"],
      "text/plain": ["txt", "text", "conf", "def", "list", "log", "in", "ini"],
      "text/richtext": ["rtx"],
      "text/rtf": ["*rtf"],
      "text/sgml": ["sgml", "sgm"],
      "text/shex": ["shex"],
      "text/slim": ["slim", "slm"],
      "text/spdx": ["spdx"],
      "text/stylus": ["stylus", "styl"],
      "text/tab-separated-values": ["tsv"],
      "text/troff": ["t", "tr", "roff", "man", "me", "ms"],
      "text/turtle": ["ttl"],
      "text/uri-list": ["uri", "uris", "urls"],
      "text/vcard": ["vcard"],
      "text/vtt": ["vtt"],
      "text/wgsl": ["wgsl"],
      "text/xml": ["*xml"],
      "text/yaml": ["yaml", "yml"],
      "video/3gpp": ["3gp", "3gpp"],
      "video/3gpp2": ["3g2"],
      "video/h261": ["h261"],
      "video/h263": ["h263"],
      "video/h264": ["h264"],
      "video/iso.segment": ["m4s"],
      "video/jpeg": ["jpgv"],
      "video/jpm": ["*jpm", "*jpgm"],
      "video/mj2": ["mj2", "mjp2"],
      "video/mp2t": ["ts", "m2t", "m2ts", "mts"],
      "video/mp4": ["mp4", "mp4v", "mpg4"],
      "video/mpeg": ["mpeg", "mpg", "mpe", "m1v", "m2v"],
      "video/ogg": ["ogv"],
      "video/quicktime": ["qt", "mov"],
      "video/webm": ["webm"]
    };
    Object.freeze(types2);
    standard_default = types2;
  }
});

// packages/core/node_modules/mime/dist/src/Mime.js
var __classPrivateFieldGet2, _Mime_extensionToType, _Mime_typeToExtension, _Mime_typeToExtensions, Mime, Mime_default;
var init_Mime = __esm({
  "packages/core/node_modules/mime/dist/src/Mime.js"() {
    init_esbuild_shims();
    __classPrivateFieldGet2 = function(receiver, state, kind, f) {
      if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    };
    Mime = class {
      static {
        __name(this, "Mime");
      }
      constructor(...args) {
        _Mime_extensionToType.set(this, /* @__PURE__ */ new Map());
        _Mime_typeToExtension.set(this, /* @__PURE__ */ new Map());
        _Mime_typeToExtensions.set(this, /* @__PURE__ */ new Map());
        for (const arg of args) {
          this.define(arg);
        }
      }
      define(typeMap, force = false) {
        for (let [type, extensions] of Object.entries(typeMap)) {
          type = type.toLowerCase();
          extensions = extensions.map((ext2) => ext2.toLowerCase());
          if (!__classPrivateFieldGet2(this, _Mime_typeToExtensions, "f").has(type)) {
            __classPrivateFieldGet2(this, _Mime_typeToExtensions, "f").set(type, /* @__PURE__ */ new Set());
          }
          const allExtensions = __classPrivateFieldGet2(this, _Mime_typeToExtensions, "f").get(type);
          let first2 = true;
          for (let extension of extensions) {
            const starred = extension.startsWith("*");
            extension = starred ? extension.slice(1) : extension;
            allExtensions?.add(extension);
            if (first2) {
              __classPrivateFieldGet2(this, _Mime_typeToExtension, "f").set(type, extension);
            }
            first2 = false;
            if (starred)
              continue;
            const currentType = __classPrivateFieldGet2(this, _Mime_extensionToType, "f").get(extension);
            if (currentType && currentType != type && !force) {
              throw new Error(`"${type} -> ${extension}" conflicts with "${currentType} -> ${extension}". Pass \`force=true\` to override this definition.`);
            }
            __classPrivateFieldGet2(this, _Mime_extensionToType, "f").set(extension, type);
          }
        }
        return this;
      }
      getType(path108) {
        if (typeof path108 !== "string")
          return null;
        const last2 = path108.replace(/^.*[/\\]/s, "").toLowerCase();
        const ext2 = last2.replace(/^.*\./s, "").toLowerCase();
        const hasPath = last2.length < path108.length;
        const hasDot = ext2.length < last2.length - 1;
        if (!hasDot && hasPath)
          return null;
        return __classPrivateFieldGet2(this, _Mime_extensionToType, "f").get(ext2) ?? null;
      }
      getExtension(type) {
        if (typeof type !== "string")
          return null;
        type = type?.split?.(";")[0];
        return (type && __classPrivateFieldGet2(this, _Mime_typeToExtension, "f").get(type.trim().toLowerCase())) ?? null;
      }
      getAllExtensions(type) {
        if (typeof type !== "string")
          return null;
        return __classPrivateFieldGet2(this, _Mime_typeToExtensions, "f").get(type.toLowerCase()) ?? null;
      }
      _freeze() {
        this.define = () => {
          throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances");
        };
        Object.freeze(this);
        for (const extensions of __classPrivateFieldGet2(this, _Mime_typeToExtensions, "f").values()) {
          Object.freeze(extensions);
        }
        return this;
      }
      _getTestState() {
        return {
          types: __classPrivateFieldGet2(this, _Mime_extensionToType, "f"),
          extensions: __classPrivateFieldGet2(this, _Mime_typeToExtension, "f")
        };
      }
    };
    _Mime_extensionToType = /* @__PURE__ */ new WeakMap(), _Mime_typeToExtension = /* @__PURE__ */ new WeakMap(), _Mime_typeToExtensions = /* @__PURE__ */ new WeakMap();
    Mime_default = Mime;
  }
});

// packages/core/node_modules/mime/dist/src/index_lite.js
var index_lite_default;
var init_index_lite = __esm({
  "packages/core/node_modules/mime/dist/src/index_lite.js"() {
    init_esbuild_shims();
    init_standard();
    init_Mime();
    init_Mime();
    index_lite_default = new Mime_default(standard_default)._freeze();
  }
});

// packages/core/dist/src/utils/ignorePatterns.js
import path28 from "node:path";
function extractExtensionsFromPatterns(patterns) {
  const extensions = new Set(patterns.filter((pattern) => pattern.includes("*.")).flatMap((pattern) => {
    const extPart = pattern.substring(pattern.lastIndexOf("*.") + 1);
    if (extPart.startsWith(".{") && extPart.endsWith("}")) {
      const inner = extPart.slice(2, -1);
      return inner.split(",").map((ext2) => `.${ext2.trim()}`).filter((ext2) => ext2 !== ".");
    }
    if (extPart.startsWith(".") && !extPart.includes("/") && !extPart.includes("{") && !extPart.includes("}")) {
      const extracted = path28.extname(`dummy${extPart}`);
      const result = extracted || extPart;
      return result && result !== "." && !result.substring(1).includes(".") ? [result] : [];
    }
    return [];
  }));
  return Array.from(extensions).sort();
}
var COMMON_IGNORE_PATTERNS, BINARY_FILE_PATTERNS, MEDIA_FILE_PATTERNS, COMMON_DIRECTORY_EXCLUDES, PYTHON_EXCLUDES, SYSTEM_FILE_EXCLUDES, DEFAULT_FILE_EXCLUDES, FileExclusions, BINARY_EXTENSIONS;
var init_ignorePatterns = __esm({
  "packages/core/dist/src/utils/ignorePatterns.js"() {
    "use strict";
    init_esbuild_shims();
    init_memoryTool();
    COMMON_IGNORE_PATTERNS = [
      "**/node_modules/**",
      "**/.git/**",
      "**/bower_components/**",
      "**/.svn/**",
      "**/.hg/**"
    ];
    BINARY_FILE_PATTERNS = [
      "**/*.bin",
      "**/*.exe",
      "**/*.dll",
      "**/*.so",
      "**/*.dylib",
      "**/*.class",
      "**/*.jar",
      "**/*.war",
      "**/*.zip",
      "**/*.tar",
      "**/*.gz",
      "**/*.bz2",
      "**/*.rar",
      "**/*.7z",
      "**/*.doc",
      "**/*.docx",
      "**/*.xls",
      "**/*.xlsx",
      "**/*.ppt",
      "**/*.pptx",
      "**/*.odt",
      "**/*.ods",
      "**/*.odp"
    ];
    MEDIA_FILE_PATTERNS = [
      "**/*.pdf",
      "**/*.png",
      "**/*.jpg",
      "**/*.jpeg",
      "**/*.gif",
      "**/*.webp",
      "**/*.bmp",
      "**/*.svg"
    ];
    COMMON_DIRECTORY_EXCLUDES = [
      "**/.vscode/**",
      "**/.idea/**",
      "**/dist/**",
      "**/build/**",
      "**/coverage/**",
      "**/__pycache__/**"
    ];
    PYTHON_EXCLUDES = ["**/*.pyc", "**/*.pyo"];
    SYSTEM_FILE_EXCLUDES = ["**/.DS_Store", "**/.env"];
    DEFAULT_FILE_EXCLUDES = [
      ...COMMON_IGNORE_PATTERNS,
      ...COMMON_DIRECTORY_EXCLUDES,
      ...BINARY_FILE_PATTERNS,
      ...PYTHON_EXCLUDES,
      ...SYSTEM_FILE_EXCLUDES
    ];
    FileExclusions = class {
      static {
        __name(this, "FileExclusions");
      }
      config;
      constructor(config) {
        this.config = config;
      }
      /**
       * Gets core ignore patterns for basic file operations like glob.
       * These are the minimal essential patterns that should almost always be excluded.
       */
      getCoreIgnorePatterns() {
        return [...COMMON_IGNORE_PATTERNS];
      }
      /**
       * Gets comprehensive default exclusion patterns for operations like read-many-files.
       * Includes all standard exclusions: directories, binary files, system files, etc.
       */
      getDefaultExcludePatterns(options2 = {}) {
        const { includeDefaults = true, customPatterns = [], runtimePatterns = [], includeDynamicPatterns = true } = options2;
        const patterns = [];
        if (includeDefaults) {
          patterns.push(...DEFAULT_FILE_EXCLUDES);
        }
        if (includeDynamicPatterns) {
          patterns.push(`**/${getCurrentGeminiMdFilename()}`);
        }
        if (this.config) {
          const configCustomExcludes = this.config.getCustomExcludes?.() ?? [];
          patterns.push(...configCustomExcludes);
        }
        patterns.push(...customPatterns);
        patterns.push(...runtimePatterns);
        return patterns;
      }
      /**
       * Gets exclude patterns for read-many-files tool with legacy compatibility.
       * This maintains the same behavior as the previous getDefaultExcludes() function.
       */
      getReadManyFilesExcludes(additionalExcludes = []) {
        return this.getDefaultExcludePatterns({
          includeDefaults: true,
          runtimePatterns: additionalExcludes,
          includeDynamicPatterns: true
        });
      }
      /**
       * Gets exclude patterns for glob tool operations.
       * Uses core patterns by default but can be extended with additional patterns.
       */
      getGlobExcludes(additionalExcludes = []) {
        const corePatterns = this.getCoreIgnorePatterns();
        const configPatterns = this.config?.getCustomExcludes?.() ?? [];
        return [...corePatterns, ...configPatterns, ...additionalExcludes];
      }
      /**
       * Builds exclude patterns with full customization options.
       * This is the most flexible method for advanced use cases.
       */
      buildExcludePatterns(options2) {
        return this.getDefaultExcludePatterns(options2);
      }
    };
    __name(extractExtensionsFromPatterns, "extractExtensionsFromPatterns");
    BINARY_EXTENSIONS = [
      ...extractExtensionsFromPatterns([
        ...BINARY_FILE_PATTERNS,
        ...MEDIA_FILE_PATTERNS,
        ...PYTHON_EXCLUDES
      ]),
      // Additional binary extensions not in the main patterns
      ".dat",
      ".obj",
      ".o",
      ".a",
      ".lib",
      ".wasm"
    ].sort();
  }
});

// packages/core/dist/src/utils/fileUtils.js
import fs30 from "node:fs";
import fsPromises from "node:fs/promises";
import path29 from "node:path";
function detectBOM(buf) {
  if (buf.length >= 4) {
    if (buf[0] === 255 && buf[1] === 254 && buf[2] === 0 && buf[3] === 0) {
      return { encoding: "utf32le", bomLength: 4 };
    }
    if (buf[0] === 0 && buf[1] === 0 && buf[2] === 254 && buf[3] === 255) {
      return { encoding: "utf32be", bomLength: 4 };
    }
  }
  if (buf.length >= 3) {
    if (buf[0] === 239 && buf[1] === 187 && buf[2] === 191) {
      return { encoding: "utf8", bomLength: 3 };
    }
  }
  if (buf.length >= 2) {
    if (buf[0] === 255 && buf[1] === 254 && (buf.length < 4 || buf[2] !== 0 || buf[3] !== 0)) {
      return { encoding: "utf16le", bomLength: 2 };
    }
    if (buf[0] === 254 && buf[1] === 255) {
      return { encoding: "utf16be", bomLength: 2 };
    }
  }
  return null;
}
function decodeUTF16BE(buf) {
  if (buf.length === 0)
    return "";
  const swapped = Buffer.from(buf);
  swapped.swap16();
  return swapped.toString("utf16le");
}
function decodeUTF32(buf, littleEndian) {
  if (buf.length < 4)
    return "";
  const usable = buf.length - buf.length % 4;
  let out = "";
  for (let i = 0; i < usable; i += 4) {
    const cp2 = littleEndian ? (buf[i] | buf[i + 1] << 8 | buf[i + 2] << 16 | buf[i + 3] << 24) >>> 0 : (buf[i + 3] | buf[i + 2] << 8 | buf[i + 1] << 16 | buf[i] << 24) >>> 0;
    if (cp2 <= 1114111 && !(cp2 >= 55296 && cp2 <= 57343)) {
      out += String.fromCodePoint(cp2);
    } else {
      out += "\uFFFD";
    }
  }
  return out;
}
async function readFileWithEncoding(filePath) {
  const full = await fs30.promises.readFile(filePath);
  if (full.length === 0)
    return "";
  const bom = detectBOM(full);
  if (!bom) {
    return full.toString("utf8");
  }
  const content = full.subarray(bom.bomLength);
  switch (bom.encoding) {
    case "utf8":
      return content.toString("utf8");
    case "utf16le":
      return content.toString("utf16le");
    case "utf16be":
      return decodeUTF16BE(content);
    case "utf32le":
      return decodeUTF32(content, true);
    case "utf32be":
      return decodeUTF32(content, false);
    default:
      return content.toString("utf8");
  }
}
function getSpecificMimeType(filePath) {
  const lookedUpMime = index_lite_default.getType(filePath);
  return typeof lookedUpMime === "string" ? lookedUpMime : void 0;
}
function isWithinRoot(pathToCheck, rootDirectory) {
  const normalizedPathToCheck = path29.resolve(pathToCheck);
  const normalizedRootDirectory = path29.resolve(rootDirectory);
  const rootWithSeparator = normalizedRootDirectory === path29.sep || normalizedRootDirectory.endsWith(path29.sep) ? normalizedRootDirectory : normalizedRootDirectory + path29.sep;
  return normalizedPathToCheck === normalizedRootDirectory || normalizedPathToCheck.startsWith(rootWithSeparator);
}
async function isBinaryFile(filePath) {
  let fh = null;
  try {
    fh = await fs30.promises.open(filePath, "r");
    const stats = await fh.stat();
    const fileSize = stats.size;
    if (fileSize === 0)
      return false;
    const sampleSize = Math.min(4096, fileSize);
    const buf = Buffer.alloc(sampleSize);
    const { bytesRead } = await fh.read(buf, 0, sampleSize, 0);
    if (bytesRead === 0)
      return false;
    const bom = detectBOM(buf.subarray(0, Math.min(4, bytesRead)));
    if (bom)
      return false;
    let nonPrintableCount = 0;
    for (let i = 0; i < bytesRead; i++) {
      if (buf[i] === 0)
        return true;
      if (buf[i] < 9 || buf[i] > 13 && buf[i] < 32) {
        nonPrintableCount++;
      }
    }
    return nonPrintableCount / bytesRead > 0.3;
  } catch (error) {
    console.warn(`Failed to check if file is binary: ${filePath}`, error instanceof Error ? error.message : String(error));
    return false;
  } finally {
    if (fh) {
      try {
        await fh.close();
      } catch (closeError) {
        console.warn(`Failed to close file handle for: ${filePath}`, closeError instanceof Error ? closeError.message : String(closeError));
      }
    }
  }
}
async function detectFileType(filePath) {
  const ext2 = path29.extname(filePath).toLowerCase();
  if ([".ts", ".mts", ".cts"].includes(ext2)) {
    return "text";
  }
  if (ext2 === ".svg") {
    return "svg";
  }
  const lookedUpMimeType = index_lite_default.getType(filePath);
  if (lookedUpMimeType) {
    if (lookedUpMimeType.startsWith("image/")) {
      return "image";
    }
    if (lookedUpMimeType.startsWith("audio/")) {
      return "audio";
    }
    if (lookedUpMimeType.startsWith("video/")) {
      return "video";
    }
    if (lookedUpMimeType === "application/pdf") {
      return "pdf";
    }
  }
  if (BINARY_EXTENSIONS.includes(ext2)) {
    return "binary";
  }
  if (await isBinaryFile(filePath)) {
    return "binary";
  }
  return "text";
}
async function processSingleFileContent(filePath, config, offset, limit2) {
  const rootDirectory = config.getTargetDir();
  try {
    if (!fs30.existsSync(filePath)) {
      return {
        llmContent: "Could not read file because no file was found at the specified path.",
        returnDisplay: "File not found.",
        error: `File not found: ${filePath}`,
        errorType: ToolErrorType.FILE_NOT_FOUND
      };
    }
    const stats = await fs30.promises.stat(filePath);
    if (stats.isDirectory()) {
      return {
        llmContent: "Could not read file because the provided path is a directory, not a file.",
        returnDisplay: "Path is a directory.",
        error: `Path is a directory, not a file: ${filePath}`,
        errorType: ToolErrorType.TARGET_IS_DIRECTORY
      };
    }
    const fileSizeInMB = stats.size / (1024 * 1024);
    if (fileSizeInMB > 20) {
      return {
        llmContent: "File size exceeds the 20MB limit.",
        returnDisplay: "File size exceeds the 20MB limit.",
        error: `File size exceeds the 20MB limit: ${filePath} (${fileSizeInMB.toFixed(2)}MB)`,
        errorType: ToolErrorType.FILE_TOO_LARGE
      };
    }
    const fileType = await detectFileType(filePath);
    const relativePathForDisplay = path29.relative(rootDirectory, filePath).replace(/\\/g, "/");
    switch (fileType) {
      case "binary": {
        return {
          llmContent: `Cannot display content of binary file: ${relativePathForDisplay}`,
          returnDisplay: `Skipped binary file: ${relativePathForDisplay}`
        };
      }
      case "svg": {
        const SVG_MAX_SIZE_BYTES = 1 * 1024 * 1024;
        if (stats.size > SVG_MAX_SIZE_BYTES) {
          return {
            llmContent: `Cannot display content of SVG file larger than 1MB: ${relativePathForDisplay}`,
            returnDisplay: `Skipped large SVG file (>1MB): ${relativePathForDisplay}`
          };
        }
        const content = await readFileWithEncoding(filePath);
        return {
          llmContent: content,
          returnDisplay: `Read SVG as text: ${relativePathForDisplay}`
        };
      }
      case "text": {
        const content = await readFileWithEncoding(filePath);
        const lines = content.split("\n").map((line) => line.trimEnd());
        const originalLineCount = lines.length;
        const startLine = offset || 0;
        const configLineLimit = config.getTruncateToolOutputLines();
        const configCharLimit = config.getTruncateToolOutputThreshold();
        const effectiveLimit = limit2 === void 0 ? configLineLimit : limit2;
        const endLine = Math.min(startLine + effectiveLimit, originalLineCount);
        const actualStartLine = Math.min(startLine, originalLineCount);
        const selectedLines = lines.slice(actualStartLine, endLine);
        let llmContent = "";
        let contentLengthTruncated = false;
        let linesIncluded = 0;
        if (Number.isFinite(configCharLimit)) {
          const formattedLines = [];
          let currentLength = 0;
          for (const line of selectedLines) {
            const sep7 = linesIncluded > 0 ? 1 : 0;
            linesIncluded++;
            const projectedLength = currentLength + line.length + sep7;
            if (projectedLength <= configCharLimit) {
              formattedLines.push(line);
              currentLength = projectedLength;
            } else {
              const remaining = Math.max(configCharLimit - currentLength - sep7, 10);
              formattedLines.push(line.substring(0, remaining) + "... [truncated]");
              contentLengthTruncated = true;
              break;
            }
          }
          llmContent = formattedLines.join("\n");
        } else {
          llmContent = selectedLines.join("\n");
          linesIncluded = selectedLines.length;
        }
        const actualEndLine = contentLengthTruncated ? actualStartLine + linesIncluded : endLine;
        const contentRangeTruncated = startLine > 0 || actualEndLine < originalLineCount;
        const isTruncated = contentRangeTruncated || contentLengthTruncated;
        let returnDisplay = "";
        if (isTruncated) {
          returnDisplay = `Read lines ${actualStartLine + 1}-${actualEndLine} of ${originalLineCount} from ${relativePathForDisplay}`;
          if (contentLengthTruncated) {
            returnDisplay += " (truncated)";
          }
        }
        return {
          llmContent,
          returnDisplay,
          isTruncated,
          originalLineCount,
          linesShown: [actualStartLine + 1, actualEndLine]
        };
      }
      case "image":
      case "pdf":
      case "audio":
      case "video": {
        const contentBuffer = await fs30.promises.readFile(filePath);
        const base64Data = contentBuffer.toString("base64");
        return {
          llmContent: {
            inlineData: {
              data: base64Data,
              mimeType: index_lite_default.getType(filePath) || "application/octet-stream"
            }
          },
          returnDisplay: `Read ${fileType} file: ${relativePathForDisplay}`
        };
      }
      default: {
        const exhaustiveCheck = fileType;
        return {
          llmContent: `Unhandled file type: ${exhaustiveCheck}`,
          returnDisplay: `Skipped unhandled file type: ${relativePathForDisplay}`,
          error: `Unhandled file type for ${filePath}`
        };
      }
    }
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    const displayPath = path29.relative(rootDirectory, filePath).replace(/\\/g, "/");
    return {
      llmContent: `Error reading file ${displayPath}: ${errorMessage}`,
      returnDisplay: `Error reading file ${displayPath}: ${errorMessage}`,
      error: `Error reading file ${filePath}: ${errorMessage}`,
      errorType: ToolErrorType.READ_CONTENT_FAILURE
    };
  }
}
async function fileExists(filePath) {
  try {
    await fsPromises.access(filePath, fs30.constants.F_OK);
    return true;
  } catch (_) {
    return false;
  }
}
var DEFAULT_ENCODING;
var init_fileUtils = __esm({
  "packages/core/dist/src/utils/fileUtils.js"() {
    "use strict";
    init_esbuild_shims();
    init_index_lite();
    init_tool_error();
    init_ignorePatterns();
    DEFAULT_ENCODING = "utf-8";
    __name(detectBOM, "detectBOM");
    __name(decodeUTF16BE, "decodeUTF16BE");
    __name(decodeUTF32, "decodeUTF32");
    __name(readFileWithEncoding, "readFileWithEncoding");
    __name(getSpecificMimeType, "getSpecificMimeType");
    __name(isWithinRoot, "isWithinRoot");
    __name(isBinaryFile, "isBinaryFile");
    __name(detectFileType, "detectFileType");
    __name(processSingleFileContent, "processSingleFileContent");
    __name(fileExists, "fileExists");
  }
});

// packages/core/dist/src/utils/language-detection.js
import * as path30 from "node:path";
function getLanguageFromFilePath(filePath) {
  const extension = path30.extname(filePath).toLowerCase();
  if (extension) {
    return extensionToLanguageMap[extension];
  }
  const filename = path30.basename(filePath).toLowerCase();
  return extensionToLanguageMap[`.${filename}`];
}
var extensionToLanguageMap;
var init_language_detection = __esm({
  "packages/core/dist/src/utils/language-detection.js"() {
    "use strict";
    init_esbuild_shims();
    extensionToLanguageMap = {
      ".ts": "TypeScript",
      ".js": "JavaScript",
      ".mjs": "JavaScript",
      ".cjs": "JavaScript",
      ".jsx": "JavaScript",
      ".tsx": "TypeScript",
      ".py": "Python",
      ".java": "Java",
      ".go": "Go",
      ".rb": "Ruby",
      ".php": "PHP",
      ".phtml": "PHP",
      ".cs": "C#",
      ".cpp": "C++",
      ".cxx": "C++",
      ".cc": "C++",
      ".c": "C",
      ".h": "C/C++",
      ".hpp": "C++",
      ".swift": "Swift",
      ".kt": "Kotlin",
      ".rs": "Rust",
      ".m": "Objective-C",
      ".mm": "Objective-C",
      ".pl": "Perl",
      ".pm": "Perl",
      ".lua": "Lua",
      ".r": "R",
      ".scala": "Scala",
      ".sc": "Scala",
      ".sh": "Shell",
      ".ps1": "PowerShell",
      ".bat": "Batch",
      ".cmd": "Batch",
      ".sql": "SQL",
      ".html": "HTML",
      ".htm": "HTML",
      ".css": "CSS",
      ".less": "Less",
      ".sass": "Sass",
      ".scss": "Sass",
      ".json": "JSON",
      ".xml": "XML",
      ".yaml": "YAML",
      ".yml": "YAML",
      ".md": "Markdown",
      ".markdown": "Markdown",
      ".dockerfile": "Dockerfile",
      ".vim": "Vim script",
      ".vb": "Visual Basic",
      ".fs": "F#",
      ".clj": "Clojure",
      ".cljs": "Clojure",
      ".dart": "Dart",
      ".ex": "Elixir",
      ".erl": "Erlang",
      ".hs": "Haskell",
      ".lisp": "Lisp",
      ".rkt": "Racket",
      ".groovy": "Groovy",
      ".jl": "Julia",
      ".tex": "LaTeX",
      ".ino": "Arduino",
      ".asm": "Assembly",
      ".s": "Assembly",
      ".toml": "TOML",
      ".vue": "Vue",
      ".svelte": "Svelte",
      ".gohtml": "Go Template",
      ".hbs": "Handlebars",
      ".ejs": "EJS",
      ".erb": "ERB",
      ".jsp": "JSP",
      ".dockerignore": "Docker",
      ".gitignore": "Git",
      ".npmignore": "npm",
      ".editorconfig": "EditorConfig",
      ".prettierrc": "Prettier",
      ".eslintrc": "ESLint",
      ".babelrc": "Babel",
      ".tsconfig": "TypeScript",
      ".flow": "Flow",
      ".graphql": "GraphQL",
      ".proto": "Protocol Buffers"
    };
    __name(getLanguageFromFilePath, "getLanguageFromFilePath");
  }
});

// packages/core/dist/src/telemetry/telemetry-utils.js
function getProgrammingLanguage(args) {
  const filePath = args["file_path"] || args["path"] || args["absolute_path"];
  if (typeof filePath === "string") {
    return getLanguageFromFilePath(filePath);
  }
  return void 0;
}
var init_telemetry_utils = __esm({
  "packages/core/dist/src/telemetry/telemetry-utils.js"() {
    "use strict";
    init_esbuild_shims();
    init_language_detection();
    __name(getProgrammingLanguage, "getProgrammingLanguage");
  }
});

// packages/core/dist/src/tools/read-file.js
import path31 from "node:path";
var ReadFileToolInvocation, ReadFileTool;
var init_read_file = __esm({
  "packages/core/dist/src/tools/read-file.js"() {
    "use strict";
    init_esbuild_shims();
    init_paths();
    init_tools();
    init_tool_names();
    init_fileUtils();
    init_metrics2();
    init_telemetry_utils();
    init_loggers();
    init_types3();
    ReadFileToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "ReadFileToolInvocation");
      }
      config;
      constructor(config, params) {
        super(params);
        this.config = config;
      }
      getDescription() {
        const relativePath = makeRelative(this.params.absolute_path, this.config.getTargetDir());
        return shortenPath(relativePath);
      }
      toolLocations() {
        return [{ path: this.params.absolute_path, line: this.params.offset }];
      }
      async execute() {
        const result = await processSingleFileContent(this.params.absolute_path, this.config, this.params.offset, this.params.limit);
        if (result.error) {
          return {
            llmContent: result.llmContent,
            returnDisplay: result.returnDisplay || "Error reading file",
            error: {
              message: result.error,
              type: result.errorType
            }
          };
        }
        let llmContent;
        if (result.isTruncated) {
          const [start, end] = result.linesShown;
          const total = result.originalLineCount;
          llmContent = `Showing lines ${start}-${end} of ${total} total lines.

---

${result.llmContent}`;
        } else {
          llmContent = result.llmContent || "";
        }
        const lines = typeof result.llmContent === "string" ? result.llmContent.split("\n").length : void 0;
        const mimetype = getSpecificMimeType(this.params.absolute_path);
        const programming_language = getProgrammingLanguage({
          absolute_path: this.params.absolute_path
        });
        logFileOperation(this.config, new FileOperationEvent(ReadFileTool.Name, FileOperation.READ, lines, mimetype, path31.extname(this.params.absolute_path), programming_language));
        return {
          llmContent,
          returnDisplay: result.returnDisplay || ""
        };
      }
    };
    ReadFileTool = class _ReadFileTool extends BaseDeclarativeTool {
      static {
        __name(this, "ReadFileTool");
      }
      config;
      static Name = ToolNames.READ_FILE;
      constructor(config) {
        super(_ReadFileTool.Name, ToolDisplayNames.READ_FILE, `Reads and returns the content of a specified file. If the file is large, the content will be truncated. The tool's response will clearly indicate if truncation has occurred and will provide details on how to read more of the file using the 'offset' and 'limit' parameters. Handles text, images (PNG, JPG, GIF, WEBP, SVG, BMP), and PDF files. For text files, it can read specific line ranges.`, Kind.Read, {
          properties: {
            absolute_path: {
              description: "The absolute path to the file to read (e.g., '/home/user/project/file.txt'). Relative paths are not supported. You must provide an absolute path.",
              type: "string"
            },
            offset: {
              description: "Optional: For text files, the 0-based line number to start reading from. Requires 'limit' to be set. Use for paginating through large files.",
              type: "number"
            },
            limit: {
              description: "Optional: For text files, maximum number of lines to read. Use with 'offset' to paginate through large files. If omitted, reads the entire file (if feasible, up to a default limit).",
              type: "number"
            }
          },
          required: ["absolute_path"],
          type: "object"
        });
        this.config = config;
      }
      validateToolParamValues(params) {
        const filePath = params.absolute_path;
        if (params.absolute_path.trim() === "") {
          return "The 'absolute_path' parameter must be non-empty.";
        }
        if (!path31.isAbsolute(filePath)) {
          return `File path must be absolute, but was relative: ${filePath}. You must provide an absolute path.`;
        }
        const workspaceContext = this.config.getWorkspaceContext();
        const projectTempDir = this.config.storage.getProjectTempDir();
        const resolvedFilePath = path31.resolve(filePath);
        const resolvedProjectTempDir = path31.resolve(projectTempDir);
        const isWithinTempDir = resolvedFilePath.startsWith(resolvedProjectTempDir + path31.sep) || resolvedFilePath === resolvedProjectTempDir;
        if (!workspaceContext.isPathWithinWorkspace(filePath) && !isWithinTempDir) {
          const directories = workspaceContext.getDirectories();
          return `File path must be within one of the workspace directories: ${directories.join(", ")} or within the project temp directory: ${projectTempDir}`;
        }
        if (params.offset !== void 0 && params.offset < 0) {
          return "Offset must be a non-negative number";
        }
        if (params.limit !== void 0 && params.limit <= 0) {
          return "Limit must be a positive number";
        }
        const fileService = this.config.getFileService();
        if (fileService.shouldQwenIgnoreFile(params.absolute_path)) {
          return `File path '${filePath}' is ignored by .qwenignore pattern(s).`;
        }
        return null;
      }
      createInvocation(params) {
        return new ReadFileToolInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/ide/detect-ide.js
function isCloudShell() {
  return !!(process.env["EDITOR_IN_CLOUD_SHELL"] || process.env["CLOUD_SHELL"]);
}
function detectIdeFromEnv() {
  if (process.env["__COG_BASHRC_SOURCED"]) {
    return IDE_DEFINITIONS.devin;
  }
  if (process.env["REPLIT_USER"]) {
    return IDE_DEFINITIONS.replit;
  }
  if (process.env["CURSOR_TRACE_ID"]) {
    return IDE_DEFINITIONS.cursor;
  }
  if (process.env["CODESPACES"]) {
    return IDE_DEFINITIONS.codespaces;
  }
  if (isCloudShell()) {
    return IDE_DEFINITIONS.cloudshell;
  }
  if (process.env["TERM_PRODUCT"] === "Trae") {
    return IDE_DEFINITIONS.trae;
  }
  if (process.env["MONOSPACE_ENV"]) {
    return IDE_DEFINITIONS.firebasestudio;
  }
  return IDE_DEFINITIONS.vscode;
}
function verifyVSCode(ide, ideProcessInfo) {
  if (ide.name !== IDE_DEFINITIONS.vscode.name) {
    return ide;
  }
  if (ideProcessInfo.command && ideProcessInfo.command.toLowerCase().includes("code")) {
    return IDE_DEFINITIONS.vscode;
  }
  return IDE_DEFINITIONS.vscodefork;
}
function detectIde(ideProcessInfo, ideInfoFromFile) {
  if (ideInfoFromFile?.name && ideInfoFromFile.displayName) {
    return {
      name: ideInfoFromFile.name,
      displayName: ideInfoFromFile.displayName
    };
  }
  if (process.env["TERM_PROGRAM"] !== "vscode") {
    return void 0;
  }
  const ide = detectIdeFromEnv();
  return verifyVSCode(ide, ideProcessInfo);
}
var IDE_DEFINITIONS;
var init_detect_ide = __esm({
  "packages/core/dist/src/ide/detect-ide.js"() {
    "use strict";
    init_esbuild_shims();
    IDE_DEFINITIONS = {
      devin: { name: "devin", displayName: "Devin" },
      replit: { name: "replit", displayName: "Replit" },
      cursor: { name: "cursor", displayName: "Cursor" },
      cloudshell: { name: "cloudshell", displayName: "Cloud Shell" },
      codespaces: { name: "codespaces", displayName: "GitHub Codespaces" },
      firebasestudio: { name: "firebasestudio", displayName: "Firebase Studio" },
      trae: { name: "trae", displayName: "Trae" },
      vscode: { name: "vscode", displayName: "VS Code" },
      vscodefork: { name: "vscodefork", displayName: "IDE" }
    };
    __name(isCloudShell, "isCloudShell");
    __name(detectIdeFromEnv, "detectIdeFromEnv");
    __name(verifyVSCode, "verifyVSCode");
    __name(detectIde, "detectIde");
  }
});

// packages/core/dist/src/ide/process-utils.js
import { exec as exec2 } from "node:child_process";
import { promisify as promisify5 } from "node:util";
import os18 from "node:os";
import path32 from "node:path";
async function getProcessInfo(pid) {
  try {
    const platform15 = os18.platform();
    if (platform15 === "win32") {
      const powershellCommand = [
        "$p = Get-CimInstance Win32_Process",
        `-Filter 'ProcessId=${pid}'`,
        "-ErrorAction SilentlyContinue;",
        "if ($p) {",
        "@{Name=$p.Name;ParentProcessId=$p.ParentProcessId;CommandLine=$p.CommandLine}",
        "| ConvertTo-Json",
        "}"
      ].join(" ");
      const { stdout } = await execAsync(`powershell "${powershellCommand}"`);
      const output = stdout.trim();
      if (!output)
        return { parentPid: 0, name: "", command: "" };
      const { Name = "", ParentProcessId = 0, CommandLine = "" } = JSON.parse(output);
      return {
        parentPid: ParentProcessId,
        name: Name,
        command: CommandLine ?? ""
      };
    } else {
      const command2 = `ps -o ppid=,command= -p ${pid}`;
      const { stdout } = await execAsync(command2);
      const trimmedStdout = stdout.trim();
      if (!trimmedStdout) {
        return { parentPid: 0, name: "", command: "" };
      }
      const ppidString = trimmedStdout.split(/\s+/)[0];
      const parentPid = parseInt(ppidString, 10);
      const fullCommand = trimmedStdout.substring(ppidString.length).trim();
      const processName = path32.basename(fullCommand.split(" ")[0]);
      return {
        parentPid: isNaN(parentPid) ? 1 : parentPid,
        name: processName,
        command: fullCommand
      };
    }
  } catch (_e) {
    console.debug(`Failed to get process info for pid ${pid}:`, _e);
    return { parentPid: 0, name: "", command: "" };
  }
}
async function getIdeProcessInfoForUnix() {
  const shells = ["zsh", "bash", "sh", "tcsh", "csh", "ksh", "fish", "dash"];
  let currentPid = process.pid;
  for (let i = 0; i < MAX_TRAVERSAL_DEPTH; i++) {
    try {
      const { parentPid, name: name3 } = await getProcessInfo(currentPid);
      const isShell = shells.some((shell2) => name3 === shell2);
      if (isShell) {
        let idePid = parentPid;
        try {
          const { parentPid: grandParentPid } = await getProcessInfo(parentPid);
          if (grandParentPid > 1) {
            idePid = grandParentPid;
          }
        } catch {
        }
        const { command: command3 } = await getProcessInfo(idePid);
        return { pid: idePid, command: command3 };
      }
      if (parentPid <= 1) {
        break;
      }
      currentPid = parentPid;
    } catch {
      break;
    }
  }
  const { command: command2 } = await getProcessInfo(currentPid);
  return { pid: currentPid, command: command2 };
}
async function getIdeProcessInfoForWindows() {
  let currentPid = process.pid;
  let previousPid = process.pid;
  for (let i = 0; i < MAX_TRAVERSAL_DEPTH; i++) {
    try {
      const { parentPid } = await getProcessInfo(currentPid);
      if (parentPid > 0) {
        try {
          const { parentPid: grandParentPid } = await getProcessInfo(parentPid);
          if (grandParentPid === 0) {
            const { command: command3 } = await getProcessInfo(previousPid);
            return { pid: previousPid, command: command3 };
          }
        } catch {
        }
      }
      if (parentPid <= 0) {
        break;
      }
      previousPid = currentPid;
      currentPid = parentPid;
    } catch {
      break;
    }
  }
  const { command: command2 } = await getProcessInfo(currentPid);
  return { pid: currentPid, command: command2 };
}
async function getIdeProcessInfo() {
  const platform15 = os18.platform();
  if (platform15 === "win32") {
    return getIdeProcessInfoForWindows();
  }
  return getIdeProcessInfoForUnix();
}
var execAsync, MAX_TRAVERSAL_DEPTH;
var init_process_utils = __esm({
  "packages/core/dist/src/ide/process-utils.js"() {
    "use strict";
    init_esbuild_shims();
    execAsync = promisify5(exec2);
    MAX_TRAVERSAL_DEPTH = 32;
    __name(getProcessInfo, "getProcessInfo");
    __name(getIdeProcessInfoForUnix, "getIdeProcessInfoForUnix");
    __name(getIdeProcessInfoForWindows, "getIdeProcessInfoForWindows");
    __name(getIdeProcessInfo, "getIdeProcessInfo");
  }
});

// node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
var LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, JSONRPC_VERSION, ProgressTokenSchema, CursorSchema, RequestMetaSchema, BaseRequestParamsSchema, RequestSchema, BaseNotificationParamsSchema, NotificationSchema, ResultSchema, RequestIdSchema, JSONRPCRequestSchema, isJSONRPCRequest, JSONRPCNotificationSchema, isJSONRPCNotification, JSONRPCResponseSchema, isJSONRPCResponse, ErrorCode, JSONRPCErrorSchema, isJSONRPCError, JSONRPCMessageSchema, EmptyResultSchema, CancelledNotificationSchema, BaseMetadataSchema, ImplementationSchema, ClientCapabilitiesSchema, InitializeRequestSchema, ServerCapabilitiesSchema, InitializeResultSchema, InitializedNotificationSchema, isInitializedNotification, PingRequestSchema, ProgressSchema, ProgressNotificationSchema, PaginatedRequestSchema, PaginatedResultSchema, ResourceContentsSchema, TextResourceContentsSchema, BlobResourceContentsSchema, ResourceSchema, ResourceTemplateSchema, ListResourcesRequestSchema, ListResourcesResultSchema, ListResourceTemplatesRequestSchema, ListResourceTemplatesResultSchema, ReadResourceRequestSchema, ReadResourceResultSchema, ResourceListChangedNotificationSchema, SubscribeRequestSchema, UnsubscribeRequestSchema, ResourceUpdatedNotificationSchema, PromptArgumentSchema, PromptSchema, ListPromptsRequestSchema, ListPromptsResultSchema, GetPromptRequestSchema, TextContentSchema, ImageContentSchema, AudioContentSchema, EmbeddedResourceSchema, ResourceLinkSchema, ContentBlockSchema, PromptMessageSchema, GetPromptResultSchema, PromptListChangedNotificationSchema, ToolAnnotationsSchema, ToolSchema, ListToolsRequestSchema, ListToolsResultSchema, CallToolResultSchema, CompatibilityCallToolResultSchema, CallToolRequestSchema, ToolListChangedNotificationSchema, LoggingLevelSchema, SetLevelRequestSchema, LoggingMessageNotificationSchema, ModelHintSchema, ModelPreferencesSchema, SamplingMessageSchema, CreateMessageRequestSchema, CreateMessageResultSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema, EnumSchemaSchema, PrimitiveSchemaDefinitionSchema, ElicitRequestSchema, ElicitResultSchema, ResourceTemplateReferenceSchema, PromptReferenceSchema, CompleteRequestSchema, CompleteResultSchema, RootSchema, ListRootsRequestSchema, ListRootsResultSchema, RootsListChangedNotificationSchema, ClientRequestSchema, ClientNotificationSchema, ClientResultSchema, ServerRequestSchema, ServerNotificationSchema, ServerResultSchema, McpError;
var init_types9 = __esm({
  "node_modules/@modelcontextprotocol/sdk/dist/esm/types.js"() {
    init_esbuild_shims();
    init_zod();
    LATEST_PROTOCOL_VERSION = "2025-06-18";
    SUPPORTED_PROTOCOL_VERSIONS = [
      LATEST_PROTOCOL_VERSION,
      "2025-03-26",
      "2024-11-05",
      "2024-10-07"
    ];
    JSONRPC_VERSION = "2.0";
    ProgressTokenSchema = external_exports.union([external_exports.string(), external_exports.number().int()]);
    CursorSchema = external_exports.string();
    RequestMetaSchema = external_exports.object({
      /**
       * 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: external_exports.optional(ProgressTokenSchema)
    }).passthrough();
    BaseRequestParamsSchema = external_exports.object({
      _meta: external_exports.optional(RequestMetaSchema)
    }).passthrough();
    RequestSchema = external_exports.object({
      method: external_exports.string(),
      params: external_exports.optional(BaseRequestParamsSchema)
    });
    BaseNotificationParamsSchema = external_exports.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: external_exports.optional(external_exports.object({}).passthrough())
    }).passthrough();
    NotificationSchema = external_exports.object({
      method: external_exports.string(),
      params: external_exports.optional(BaseNotificationParamsSchema)
    });
    ResultSchema = external_exports.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: external_exports.optional(external_exports.object({}).passthrough())
    }).passthrough();
    RequestIdSchema = external_exports.union([external_exports.string(), external_exports.number().int()]);
    JSONRPCRequestSchema = external_exports.object({
      jsonrpc: external_exports.literal(JSONRPC_VERSION),
      id: RequestIdSchema
    }).merge(RequestSchema).strict();
    isJSONRPCRequest = /* @__PURE__ */ __name((value) => JSONRPCRequestSchema.safeParse(value).success, "isJSONRPCRequest");
    JSONRPCNotificationSchema = external_exports.object({
      jsonrpc: external_exports.literal(JSONRPC_VERSION)
    }).merge(NotificationSchema).strict();
    isJSONRPCNotification = /* @__PURE__ */ __name((value) => JSONRPCNotificationSchema.safeParse(value).success, "isJSONRPCNotification");
    JSONRPCResponseSchema = external_exports.object({
      jsonrpc: external_exports.literal(JSONRPC_VERSION),
      id: RequestIdSchema,
      result: ResultSchema
    }).strict();
    isJSONRPCResponse = /* @__PURE__ */ __name((value) => JSONRPCResponseSchema.safeParse(value).success, "isJSONRPCResponse");
    (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";
    })(ErrorCode || (ErrorCode = {}));
    JSONRPCErrorSchema = external_exports.object({
      jsonrpc: external_exports.literal(JSONRPC_VERSION),
      id: RequestIdSchema,
      error: external_exports.object({
        /**
         * The error type that occurred.
         */
        code: external_exports.number().int(),
        /**
         * A short description of the error. The message SHOULD be limited to a concise single sentence.
         */
        message: external_exports.string(),
        /**
         * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
         */
        data: external_exports.optional(external_exports.unknown())
      })
    }).strict();
    isJSONRPCError = /* @__PURE__ */ __name((value) => JSONRPCErrorSchema.safeParse(value).success, "isJSONRPCError");
    JSONRPCMessageSchema = external_exports.union([
      JSONRPCRequestSchema,
      JSONRPCNotificationSchema,
      JSONRPCResponseSchema,
      JSONRPCErrorSchema
    ]);
    EmptyResultSchema = ResultSchema.strict();
    CancelledNotificationSchema = NotificationSchema.extend({
      method: external_exports.literal("notifications/cancelled"),
      params: BaseNotificationParamsSchema.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,
        /**
         * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
         */
        reason: external_exports.string().optional()
      })
    });
    BaseMetadataSchema = external_exports.object({
      /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */
      name: external_exports.string(),
      /**
      * 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: external_exports.optional(external_exports.string())
    }).passthrough();
    ImplementationSchema = BaseMetadataSchema.extend({
      version: external_exports.string()
    });
    ClientCapabilitiesSchema = external_exports.object({
      /**
       * Experimental, non-standard capabilities that the client supports.
       */
      experimental: external_exports.optional(external_exports.object({}).passthrough()),
      /**
       * Present if the client supports sampling from an LLM.
       */
      sampling: external_exports.optional(external_exports.object({}).passthrough()),
      /**
       * Present if the client supports eliciting user input.
       */
      elicitation: external_exports.optional(external_exports.object({}).passthrough()),
      /**
       * Present if the client supports listing roots.
       */
      roots: external_exports.optional(external_exports.object({
        /**
         * Whether the client supports issuing notifications for changes to the roots list.
         */
        listChanged: external_exports.optional(external_exports.boolean())
      }).passthrough())
    }).passthrough();
    InitializeRequestSchema = RequestSchema.extend({
      method: external_exports.literal("initialize"),
      params: 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: external_exports.string(),
        capabilities: ClientCapabilitiesSchema,
        clientInfo: ImplementationSchema
      })
    });
    ServerCapabilitiesSchema = external_exports.object({
      /**
       * Experimental, non-standard capabilities that the server supports.
       */
      experimental: external_exports.optional(external_exports.object({}).passthrough()),
      /**
       * Present if the server supports sending log messages to the client.
       */
      logging: external_exports.optional(external_exports.object({}).passthrough()),
      /**
       * Present if the server supports sending completions to the client.
       */
      completions: external_exports.optional(external_exports.object({}).passthrough()),
      /**
       * Present if the server offers any prompt templates.
       */
      prompts: external_exports.optional(external_exports.object({
        /**
         * Whether this server supports issuing notifications for changes to the prompt list.
         */
        listChanged: external_exports.optional(external_exports.boolean())
      }).passthrough()),
      /**
       * Present if the server offers any resources to read.
       */
      resources: external_exports.optional(external_exports.object({
        /**
         * Whether this server supports clients subscribing to resource updates.
         */
        subscribe: external_exports.optional(external_exports.boolean()),
        /**
         * Whether this server supports issuing notifications for changes to the resource list.
         */
        listChanged: external_exports.optional(external_exports.boolean())
      }).passthrough()),
      /**
       * Present if the server offers any tools to call.
       */
      tools: external_exports.optional(external_exports.object({
        /**
         * Whether this server supports issuing notifications for changes to the tool list.
         */
        listChanged: external_exports.optional(external_exports.boolean())
      }).passthrough())
    }).passthrough();
    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: external_exports.string(),
      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: external_exports.optional(external_exports.string())
    });
    InitializedNotificationSchema = NotificationSchema.extend({
      method: external_exports.literal("notifications/initialized")
    });
    isInitializedNotification = /* @__PURE__ */ __name((value) => InitializedNotificationSchema.safeParse(value).success, "isInitializedNotification");
    PingRequestSchema = RequestSchema.extend({
      method: external_exports.literal("ping")
    });
    ProgressSchema = external_exports.object({
      /**
       * The progress thus far. This should increase every time progress is made, even if the total is unknown.
       */
      progress: external_exports.number(),
      /**
       * Total number of items to process (or total progress required), if known.
       */
      total: external_exports.optional(external_exports.number()),
      /**
       * An optional message describing the current progress.
       */
      message: external_exports.optional(external_exports.string())
    }).passthrough();
    ProgressNotificationSchema = NotificationSchema.extend({
      method: external_exports.literal("notifications/progress"),
      params: BaseNotificationParamsSchema.merge(ProgressSchema).extend({
        /**
         * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
         */
        progressToken: ProgressTokenSchema
      })
    });
    PaginatedRequestSchema = RequestSchema.extend({
      params: BaseRequestParamsSchema.extend({
        /**
         * An opaque token representing the current pagination position.
         * If provided, the server should return results starting after this cursor.
         */
        cursor: external_exports.optional(CursorSchema)
      }).optional()
    });
    PaginatedResultSchema = ResultSchema.extend({
      /**
       * An opaque token representing the pagination position after the last returned result.
       * If present, there may be more results available.
       */
      nextCursor: external_exports.optional(CursorSchema)
    });
    ResourceContentsSchema = external_exports.object({
      /**
       * The URI of this resource.
       */
      uri: external_exports.string(),
      /**
       * The MIME type of this resource, if known.
       */
      mimeType: external_exports.optional(external_exports.string()),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: external_exports.optional(external_exports.object({}).passthrough())
    }).passthrough();
    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: external_exports.string()
    });
    BlobResourceContentsSchema = ResourceContentsSchema.extend({
      /**
       * A base64-encoded string representing the binary data of the item.
       */
      blob: external_exports.string().base64()
    });
    ResourceSchema = BaseMetadataSchema.extend({
      /**
       * The URI of this resource.
       */
      uri: external_exports.string(),
      /**
       * 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: external_exports.optional(external_exports.string()),
      /**
       * The MIME type of this resource, if known.
       */
      mimeType: external_exports.optional(external_exports.string()),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: external_exports.optional(external_exports.object({}).passthrough())
    });
    ResourceTemplateSchema = BaseMetadataSchema.extend({
      /**
       * A URI template (according to RFC 6570) that can be used to construct resource URIs.
       */
      uriTemplate: external_exports.string(),
      /**
       * 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: external_exports.optional(external_exports.string()),
      /**
       * 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: external_exports.optional(external_exports.string()),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: external_exports.optional(external_exports.object({}).passthrough())
    });
    ListResourcesRequestSchema = PaginatedRequestSchema.extend({
      method: external_exports.literal("resources/list")
    });
    ListResourcesResultSchema = PaginatedResultSchema.extend({
      resources: external_exports.array(ResourceSchema)
    });
    ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({
      method: external_exports.literal("resources/templates/list")
    });
    ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
      resourceTemplates: external_exports.array(ResourceTemplateSchema)
    });
    ReadResourceRequestSchema = RequestSchema.extend({
      method: external_exports.literal("resources/read"),
      params: 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.
         */
        uri: external_exports.string()
      })
    });
    ReadResourceResultSchema = ResultSchema.extend({
      contents: external_exports.array(external_exports.union([TextResourceContentsSchema, BlobResourceContentsSchema]))
    });
    ResourceListChangedNotificationSchema = NotificationSchema.extend({
      method: external_exports.literal("notifications/resources/list_changed")
    });
    SubscribeRequestSchema = RequestSchema.extend({
      method: external_exports.literal("resources/subscribe"),
      params: BaseRequestParamsSchema.extend({
        /**
         * The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it.
         */
        uri: external_exports.string()
      })
    });
    UnsubscribeRequestSchema = RequestSchema.extend({
      method: external_exports.literal("resources/unsubscribe"),
      params: BaseRequestParamsSchema.extend({
        /**
         * The URI of the resource to unsubscribe from.
         */
        uri: external_exports.string()
      })
    });
    ResourceUpdatedNotificationSchema = NotificationSchema.extend({
      method: external_exports.literal("notifications/resources/updated"),
      params: BaseNotificationParamsSchema.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: external_exports.string()
      })
    });
    PromptArgumentSchema = external_exports.object({
      /**
       * The name of the argument.
       */
      name: external_exports.string(),
      /**
       * A human-readable description of the argument.
       */
      description: external_exports.optional(external_exports.string()),
      /**
       * Whether this argument must be provided.
       */
      required: external_exports.optional(external_exports.boolean())
    }).passthrough();
    PromptSchema = BaseMetadataSchema.extend({
      /**
       * An optional description of what this prompt provides
       */
      description: external_exports.optional(external_exports.string()),
      /**
       * A list of arguments to use for templating the prompt.
       */
      arguments: external_exports.optional(external_exports.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: external_exports.optional(external_exports.object({}).passthrough())
    });
    ListPromptsRequestSchema = PaginatedRequestSchema.extend({
      method: external_exports.literal("prompts/list")
    });
    ListPromptsResultSchema = PaginatedResultSchema.extend({
      prompts: external_exports.array(PromptSchema)
    });
    GetPromptRequestSchema = RequestSchema.extend({
      method: external_exports.literal("prompts/get"),
      params: BaseRequestParamsSchema.extend({
        /**
         * The name of the prompt or prompt template.
         */
        name: external_exports.string(),
        /**
         * Arguments to use for templating the prompt.
         */
        arguments: external_exports.optional(external_exports.record(external_exports.string()))
      })
    });
    TextContentSchema = external_exports.object({
      type: external_exports.literal("text"),
      /**
       * The text content of the message.
       */
      text: external_exports.string(),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: external_exports.optional(external_exports.object({}).passthrough())
    }).passthrough();
    ImageContentSchema = external_exports.object({
      type: external_exports.literal("image"),
      /**
       * The base64-encoded image data.
       */
      data: external_exports.string().base64(),
      /**
       * The MIME type of the image. Different providers may support different image types.
       */
      mimeType: external_exports.string(),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: external_exports.optional(external_exports.object({}).passthrough())
    }).passthrough();
    AudioContentSchema = external_exports.object({
      type: external_exports.literal("audio"),
      /**
       * The base64-encoded audio data.
       */
      data: external_exports.string().base64(),
      /**
       * The MIME type of the audio. Different providers may support different audio types.
       */
      mimeType: external_exports.string(),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: external_exports.optional(external_exports.object({}).passthrough())
    }).passthrough();
    EmbeddedResourceSchema = external_exports.object({
      type: external_exports.literal("resource"),
      resource: external_exports.union([TextResourceContentsSchema, BlobResourceContentsSchema]),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: external_exports.optional(external_exports.object({}).passthrough())
    }).passthrough();
    ResourceLinkSchema = ResourceSchema.extend({
      type: external_exports.literal("resource_link")
    });
    ContentBlockSchema = external_exports.union([
      TextContentSchema,
      ImageContentSchema,
      AudioContentSchema,
      ResourceLinkSchema,
      EmbeddedResourceSchema
    ]);
    PromptMessageSchema = external_exports.object({
      role: external_exports.enum(["user", "assistant"]),
      content: ContentBlockSchema
    }).passthrough();
    GetPromptResultSchema = ResultSchema.extend({
      /**
       * An optional description for the prompt.
       */
      description: external_exports.optional(external_exports.string()),
      messages: external_exports.array(PromptMessageSchema)
    });
    PromptListChangedNotificationSchema = NotificationSchema.extend({
      method: external_exports.literal("notifications/prompts/list_changed")
    });
    ToolAnnotationsSchema = external_exports.object({
      /**
       * A human-readable title for the tool.
       */
      title: external_exports.optional(external_exports.string()),
      /**
       * If true, the tool does not modify its environment.
       *
       * Default: false
       */
      readOnlyHint: external_exports.optional(external_exports.boolean()),
      /**
       * 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: external_exports.optional(external_exports.boolean()),
      /**
       * 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: external_exports.optional(external_exports.boolean()),
      /**
       * 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: external_exports.optional(external_exports.boolean())
    }).passthrough();
    ToolSchema = BaseMetadataSchema.extend({
      /**
       * A human-readable description of the tool.
       */
      description: external_exports.optional(external_exports.string()),
      /**
       * A JSON Schema object defining the expected parameters for the tool.
       */
      inputSchema: external_exports.object({
        type: external_exports.literal("object"),
        properties: external_exports.optional(external_exports.object({}).passthrough()),
        required: external_exports.optional(external_exports.array(external_exports.string()))
      }).passthrough(),
      /**
       * An optional JSON Schema object defining the structure of the tool's output returned in
       * the structuredContent field of a CallToolResult.
       */
      outputSchema: external_exports.optional(external_exports.object({
        type: external_exports.literal("object"),
        properties: external_exports.optional(external_exports.object({}).passthrough()),
        required: external_exports.optional(external_exports.array(external_exports.string()))
      }).passthrough()),
      /**
       * Optional additional tool information.
       */
      annotations: external_exports.optional(ToolAnnotationsSchema),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: external_exports.optional(external_exports.object({}).passthrough())
    });
    ListToolsRequestSchema = PaginatedRequestSchema.extend({
      method: external_exports.literal("tools/list")
    });
    ListToolsResultSchema = PaginatedResultSchema.extend({
      tools: external_exports.array(ToolSchema)
    });
    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: external_exports.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: external_exports.object({}).passthrough().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: external_exports.optional(external_exports.boolean())
    });
    CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({
      toolResult: external_exports.unknown()
    }));
    CallToolRequestSchema = RequestSchema.extend({
      method: external_exports.literal("tools/call"),
      params: BaseRequestParamsSchema.extend({
        name: external_exports.string(),
        arguments: external_exports.optional(external_exports.record(external_exports.unknown()))
      })
    });
    ToolListChangedNotificationSchema = NotificationSchema.extend({
      method: external_exports.literal("notifications/tools/list_changed")
    });
    LoggingLevelSchema = external_exports.enum([
      "debug",
      "info",
      "notice",
      "warning",
      "error",
      "critical",
      "alert",
      "emergency"
    ]);
    SetLevelRequestSchema = RequestSchema.extend({
      method: external_exports.literal("logging/setLevel"),
      params: 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
      })
    });
    LoggingMessageNotificationSchema = NotificationSchema.extend({
      method: external_exports.literal("notifications/message"),
      params: BaseNotificationParamsSchema.extend({
        /**
         * The severity of this log message.
         */
        level: LoggingLevelSchema,
        /**
         * An optional name of the logger issuing this message.
         */
        logger: external_exports.optional(external_exports.string()),
        /**
         * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
         */
        data: external_exports.unknown()
      })
    });
    ModelHintSchema = external_exports.object({
      /**
       * A hint for a model name.
       */
      name: external_exports.string().optional()
    }).passthrough();
    ModelPreferencesSchema = external_exports.object({
      /**
       * Optional hints to use for model selection.
       */
      hints: external_exports.optional(external_exports.array(ModelHintSchema)),
      /**
       * How much to prioritize cost when selecting a model.
       */
      costPriority: external_exports.optional(external_exports.number().min(0).max(1)),
      /**
       * How much to prioritize sampling speed (latency) when selecting a model.
       */
      speedPriority: external_exports.optional(external_exports.number().min(0).max(1)),
      /**
       * How much to prioritize intelligence and capabilities when selecting a model.
       */
      intelligencePriority: external_exports.optional(external_exports.number().min(0).max(1))
    }).passthrough();
    SamplingMessageSchema = external_exports.object({
      role: external_exports.enum(["user", "assistant"]),
      content: external_exports.union([TextContentSchema, ImageContentSchema, AudioContentSchema])
    }).passthrough();
    CreateMessageRequestSchema = RequestSchema.extend({
      method: external_exports.literal("sampling/createMessage"),
      params: BaseRequestParamsSchema.extend({
        messages: external_exports.array(SamplingMessageSchema),
        /**
         * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
         */
        systemPrompt: external_exports.optional(external_exports.string()),
        /**
         * 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.
         */
        includeContext: external_exports.optional(external_exports.enum(["none", "thisServer", "allServers"])),
        temperature: external_exports.optional(external_exports.number()),
        /**
         * The maximum number of tokens to sample, as requested by the server. The client MAY choose to sample fewer tokens than requested.
         */
        maxTokens: external_exports.number().int(),
        stopSequences: external_exports.optional(external_exports.array(external_exports.string())),
        /**
         * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
         */
        metadata: external_exports.optional(external_exports.object({}).passthrough()),
        /**
         * The server's preferences for which model to select.
         */
        modelPreferences: external_exports.optional(ModelPreferencesSchema)
      })
    });
    CreateMessageResultSchema = ResultSchema.extend({
      /**
       * The name of the model that generated the message.
       */
      model: external_exports.string(),
      /**
       * The reason why sampling stopped.
       */
      stopReason: external_exports.optional(external_exports.enum(["endTurn", "stopSequence", "maxTokens"]).or(external_exports.string())),
      role: external_exports.enum(["user", "assistant"]),
      content: external_exports.discriminatedUnion("type", [
        TextContentSchema,
        ImageContentSchema,
        AudioContentSchema
      ])
    });
    BooleanSchemaSchema = external_exports.object({
      type: external_exports.literal("boolean"),
      title: external_exports.optional(external_exports.string()),
      description: external_exports.optional(external_exports.string()),
      default: external_exports.optional(external_exports.boolean())
    }).passthrough();
    StringSchemaSchema = external_exports.object({
      type: external_exports.literal("string"),
      title: external_exports.optional(external_exports.string()),
      description: external_exports.optional(external_exports.string()),
      minLength: external_exports.optional(external_exports.number()),
      maxLength: external_exports.optional(external_exports.number()),
      format: external_exports.optional(external_exports.enum(["email", "uri", "date", "date-time"]))
    }).passthrough();
    NumberSchemaSchema = external_exports.object({
      type: external_exports.enum(["number", "integer"]),
      title: external_exports.optional(external_exports.string()),
      description: external_exports.optional(external_exports.string()),
      minimum: external_exports.optional(external_exports.number()),
      maximum: external_exports.optional(external_exports.number())
    }).passthrough();
    EnumSchemaSchema = external_exports.object({
      type: external_exports.literal("string"),
      title: external_exports.optional(external_exports.string()),
      description: external_exports.optional(external_exports.string()),
      enum: external_exports.array(external_exports.string()),
      enumNames: external_exports.optional(external_exports.array(external_exports.string()))
    }).passthrough();
    PrimitiveSchemaDefinitionSchema = external_exports.union([
      BooleanSchemaSchema,
      StringSchemaSchema,
      NumberSchemaSchema,
      EnumSchemaSchema
    ]);
    ElicitRequestSchema = RequestSchema.extend({
      method: external_exports.literal("elicitation/create"),
      params: BaseRequestParamsSchema.extend({
        /**
         * The message to present to the user.
         */
        message: external_exports.string(),
        /**
         * The schema for the requested user input.
         */
        requestedSchema: external_exports.object({
          type: external_exports.literal("object"),
          properties: external_exports.record(external_exports.string(), PrimitiveSchemaDefinitionSchema),
          required: external_exports.optional(external_exports.array(external_exports.string()))
        }).passthrough()
      })
    });
    ElicitResultSchema = ResultSchema.extend({
      /**
       * The user's response action.
       */
      action: external_exports.enum(["accept", "decline", "cancel"]),
      /**
       * The collected user input content (only present if action is "accept").
       */
      content: external_exports.optional(external_exports.record(external_exports.string(), external_exports.unknown()))
    });
    ResourceTemplateReferenceSchema = external_exports.object({
      type: external_exports.literal("ref/resource"),
      /**
       * The URI or URI template of the resource.
       */
      uri: external_exports.string()
    }).passthrough();
    PromptReferenceSchema = external_exports.object({
      type: external_exports.literal("ref/prompt"),
      /**
       * The name of the prompt or prompt template
       */
      name: external_exports.string()
    }).passthrough();
    CompleteRequestSchema = RequestSchema.extend({
      method: external_exports.literal("completion/complete"),
      params: BaseRequestParamsSchema.extend({
        ref: external_exports.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
        /**
         * The argument's information
         */
        argument: external_exports.object({
          /**
           * The name of the argument
           */
          name: external_exports.string(),
          /**
           * The value of the argument to use for completion matching.
           */
          value: external_exports.string()
        }).passthrough(),
        context: external_exports.optional(external_exports.object({
          /**
           * Previously-resolved variables in a URI template or prompt.
           */
          arguments: external_exports.optional(external_exports.record(external_exports.string(), external_exports.string()))
        }))
      })
    });
    CompleteResultSchema = ResultSchema.extend({
      completion: external_exports.object({
        /**
         * An array of completion values. Must not exceed 100 items.
         */
        values: external_exports.array(external_exports.string()).max(100),
        /**
         * The total number of completion options available. This can exceed the number of values actually sent in the response.
         */
        total: external_exports.optional(external_exports.number().int()),
        /**
         * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
         */
        hasMore: external_exports.optional(external_exports.boolean())
      }).passthrough()
    });
    RootSchema = external_exports.object({
      /**
       * The URI identifying the root. This *must* start with file:// for now.
       */
      uri: external_exports.string().startsWith("file://"),
      /**
       * An optional name for the root.
       */
      name: external_exports.optional(external_exports.string()),
      /**
       * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
       * for notes on _meta usage.
       */
      _meta: external_exports.optional(external_exports.object({}).passthrough())
    }).passthrough();
    ListRootsRequestSchema = RequestSchema.extend({
      method: external_exports.literal("roots/list")
    });
    ListRootsResultSchema = ResultSchema.extend({
      roots: external_exports.array(RootSchema)
    });
    RootsListChangedNotificationSchema = NotificationSchema.extend({
      method: external_exports.literal("notifications/roots/list_changed")
    });
    ClientRequestSchema = external_exports.union([
      PingRequestSchema,
      InitializeRequestSchema,
      CompleteRequestSchema,
      SetLevelRequestSchema,
      GetPromptRequestSchema,
      ListPromptsRequestSchema,
      ListResourcesRequestSchema,
      ListResourceTemplatesRequestSchema,
      ReadResourceRequestSchema,
      SubscribeRequestSchema,
      UnsubscribeRequestSchema,
      CallToolRequestSchema,
      ListToolsRequestSchema
    ]);
    ClientNotificationSchema = external_exports.union([
      CancelledNotificationSchema,
      ProgressNotificationSchema,
      InitializedNotificationSchema,
      RootsListChangedNotificationSchema
    ]);
    ClientResultSchema = external_exports.union([
      EmptyResultSchema,
      CreateMessageResultSchema,
      ElicitResultSchema,
      ListRootsResultSchema
    ]);
    ServerRequestSchema = external_exports.union([
      PingRequestSchema,
      CreateMessageRequestSchema,
      ElicitRequestSchema,
      ListRootsRequestSchema
    ]);
    ServerNotificationSchema = external_exports.union([
      CancelledNotificationSchema,
      ProgressNotificationSchema,
      LoggingMessageNotificationSchema,
      ResourceUpdatedNotificationSchema,
      ResourceListChangedNotificationSchema,
      ToolListChangedNotificationSchema,
      PromptListChangedNotificationSchema
    ]);
    ServerResultSchema = external_exports.union([
      EmptyResultSchema,
      InitializeResultSchema,
      CompleteResultSchema,
      GetPromptResultSchema,
      ListPromptsResultSchema,
      ListResourcesResultSchema,
      ListResourceTemplatesResultSchema,
      ReadResourceResultSchema,
      CallToolResultSchema,
      ListToolsResultSchema
    ]);
    McpError = class extends Error {
      static {
        __name(this, "McpError");
      }
      constructor(code2, message, data) {
        super(`MCP error ${code2}: ${message}`);
        this.code = code2;
        this.data = data;
        this.name = "McpError";
      }
    };
  }
});

// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
function mergeCapabilities(base, additional) {
  return Object.entries(additional).reduce((acc, [key, value]) => {
    if (value && typeof value === "object") {
      acc[key] = acc[key] ? { ...acc[key], ...value } : value;
    } else {
      acc[key] = value;
    }
    return acc;
  }, { ...base });
}
var DEFAULT_REQUEST_TIMEOUT_MSEC, Protocol;
var init_protocol = __esm({
  "node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js"() {
    init_esbuild_shims();
    init_types9();
    DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4;
    Protocol = class {
      static {
        __name(this, "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.setNotificationHandler(CancelledNotificationSchema, (notification) => {
          const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
          controller === null || controller === void 0 ? void 0 : controller.abort(notification.params.reason);
        });
        this.setNotificationHandler(ProgressNotificationSchema, (notification) => {
          this._onprogress(notification);
        });
        this.setRequestHandler(
          PingRequestSchema,
          // Automatic pong by default.
          (_request) => ({})
        );
      }
      _setupTimeout(messageId, timeout2, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
        this._timeoutInfo.set(messageId, {
          timeoutId: setTimeout(onTimeout, timeout2),
          startTime: Date.now(),
          timeout: timeout2,
          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 new McpError(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.
       */
      async connect(transport) {
        var _a6, _b2, _c2;
        this._transport = transport;
        const _onclose = (_a6 = this.transport) === null || _a6 === void 0 ? void 0 : _a6.onclose;
        this._transport.onclose = () => {
          _onclose === null || _onclose === void 0 ? void 0 : _onclose();
          this._onclose();
        };
        const _onerror2 = (_b2 = this.transport) === null || _b2 === void 0 ? void 0 : _b2.onerror;
        this._transport.onerror = (error) => {
          _onerror2 === null || _onerror2 === void 0 ? void 0 : _onerror2(error);
          this._onerror(error);
        };
        const _onmessage = (_c2 = this._transport) === null || _c2 === void 0 ? void 0 : _c2.onmessage;
        this._transport.onmessage = (message, extra) => {
          _onmessage === null || _onmessage === void 0 ? void 0 : _onmessage(message, extra);
          if (isJSONRPCResponse(message) || isJSONRPCError(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)}`));
          }
        };
        await this._transport.start();
      }
      _onclose() {
        var _a6;
        const responseHandlers = this._responseHandlers;
        this._responseHandlers = /* @__PURE__ */ new Map();
        this._progressHandlers.clear();
        this._transport = void 0;
        (_a6 = this.onclose) === null || _a6 === void 0 ? void 0 : _a6.call(this);
        const error = new McpError(ErrorCode.ConnectionClosed, "Connection closed");
        for (const handler of responseHandlers.values()) {
          handler(error);
        }
      }
      _onerror(error) {
        var _a6;
        (_a6 = this.onerror) === null || _a6 === void 0 ? void 0 : _a6.call(this, error);
      }
      _onnotification(notification) {
        var _a6;
        const handler = (_a6 = this._notificationHandlers.get(notification.method)) !== null && _a6 !== void 0 ? _a6 : this.fallbackNotificationHandler;
        if (handler === void 0) {
          return;
        }
        Promise.resolve().then(() => handler(notification)).catch((error) => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));
      }
      _onrequest(request4, extra) {
        var _a6, _b2, _c2, _d;
        const handler = (_a6 = this._requestHandlers.get(request4.method)) !== null && _a6 !== void 0 ? _a6 : this.fallbackRequestHandler;
        if (handler === void 0) {
          (_b2 = this._transport) === null || _b2 === void 0 ? void 0 : _b2.send({
            jsonrpc: "2.0",
            id: request4.id,
            error: {
              code: ErrorCode.MethodNotFound,
              message: "Method not found"
            }
          }).catch((error) => this._onerror(new Error(`Failed to send an error response: ${error}`)));
          return;
        }
        const abortController = new AbortController();
        this._requestHandlerAbortControllers.set(request4.id, abortController);
        const fullExtra = {
          signal: abortController.signal,
          sessionId: (_c2 = this._transport) === null || _c2 === void 0 ? void 0 : _c2.sessionId,
          _meta: (_d = request4.params) === null || _d === void 0 ? void 0 : _d._meta,
          sendNotification: /* @__PURE__ */ __name((notification) => this.notification(notification, { relatedRequestId: request4.id }), "sendNotification"),
          sendRequest: /* @__PURE__ */ __name((r3, resultSchema, options2) => this.request(r3, resultSchema, { ...options2, relatedRequestId: request4.id }), "sendRequest"),
          authInfo: extra === null || extra === void 0 ? void 0 : extra.authInfo,
          requestId: request4.id,
          requestInfo: extra === null || extra === void 0 ? void 0 : extra.requestInfo
        };
        Promise.resolve().then(() => handler(request4, fullExtra)).then((result) => {
          var _a7;
          if (abortController.signal.aborted) {
            return;
          }
          return (_a7 = this._transport) === null || _a7 === void 0 ? void 0 : _a7.send({
            result,
            jsonrpc: "2.0",
            id: request4.id
          });
        }, (error) => {
          var _a7, _b3;
          if (abortController.signal.aborted) {
            return;
          }
          return (_a7 = this._transport) === null || _a7 === void 0 ? void 0 : _a7.send({
            jsonrpc: "2.0",
            id: request4.id,
            error: {
              code: Number.isSafeInteger(error["code"]) ? error["code"] : ErrorCode.InternalError,
              message: (_b3 = error.message) !== null && _b3 !== void 0 ? _b3 : "Internal error"
            }
          });
        }).catch((error) => this._onerror(new Error(`Failed to send response: ${error}`))).finally(() => {
          this._requestHandlerAbortControllers.delete(request4.id);
        });
      }
      _onprogress(notification) {
        const { progressToken, ...params } = notification.params;
        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 (error) {
            responseHandler(error);
            return;
          }
        }
        handler(params);
      }
      _onresponse(response) {
        const messageId = Number(response.id);
        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._progressHandlers.delete(messageId);
        this._cleanupTimeout(messageId);
        if (isJSONRPCResponse(response)) {
          handler(response);
        } else {
          const error = new McpError(response.error.code, response.error.message, response.error.data);
          handler(error);
        }
      }
      get transport() {
        return this._transport;
      }
      /**
       * Closes the connection.
       */
      async close() {
        var _a6;
        await ((_a6 = this._transport) === null || _a6 === void 0 ? void 0 : _a6.close());
      }
      /**
       * Sends a request and wait for a response.
       *
       * Do not use this method to emit notifications! Use notification() instead.
       */
      request(request4, resultSchema, options2) {
        const { relatedRequestId, resumptionToken, onresumptiontoken } = options2 !== null && options2 !== void 0 ? options2 : {};
        return new Promise((resolve24, reject) => {
          var _a6, _b2, _c2, _d, _e, _f;
          if (!this._transport) {
            reject(new Error("Not connected"));
            return;
          }
          if (((_a6 = this._options) === null || _a6 === void 0 ? void 0 : _a6.enforceStrictCapabilities) === true) {
            this.assertCapabilityForMethod(request4.method);
          }
          (_b2 = options2 === null || options2 === void 0 ? void 0 : options2.signal) === null || _b2 === void 0 ? void 0 : _b2.throwIfAborted();
          const messageId = this._requestMessageId++;
          const jsonrpcRequest = {
            ...request4,
            jsonrpc: "2.0",
            id: messageId
          };
          if (options2 === null || options2 === void 0 ? void 0 : options2.onprogress) {
            this._progressHandlers.set(messageId, options2.onprogress);
            jsonrpcRequest.params = {
              ...request4.params,
              _meta: {
                ...((_c2 = request4.params) === null || _c2 === void 0 ? void 0 : _c2._meta) || {},
                progressToken: messageId
              }
            };
          }
          const cancel = /* @__PURE__ */ __name((reason) => {
            var _a7;
            this._responseHandlers.delete(messageId);
            this._progressHandlers.delete(messageId);
            this._cleanupTimeout(messageId);
            (_a7 = this._transport) === null || _a7 === void 0 ? void 0 : _a7.send({
              jsonrpc: "2.0",
              method: "notifications/cancelled",
              params: {
                requestId: messageId,
                reason: String(reason)
              }
            }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => this._onerror(new Error(`Failed to send cancellation: ${error}`)));
            reject(reason);
          }, "cancel");
          this._responseHandlers.set(messageId, (response) => {
            var _a7;
            if ((_a7 = options2 === null || options2 === void 0 ? void 0 : options2.signal) === null || _a7 === void 0 ? void 0 : _a7.aborted) {
              return;
            }
            if (response instanceof Error) {
              return reject(response);
            }
            try {
              const result = resultSchema.parse(response.result);
              resolve24(result);
            } catch (error) {
              reject(error);
            }
          });
          (_d = options2 === null || options2 === void 0 ? void 0 : options2.signal) === null || _d === void 0 ? void 0 : _d.addEventListener("abort", () => {
            var _a7;
            cancel((_a7 = options2 === null || options2 === void 0 ? void 0 : options2.signal) === null || _a7 === void 0 ? void 0 : _a7.reason);
          });
          const timeout2 = (_e = options2 === null || options2 === void 0 ? void 0 : options2.timeout) !== null && _e !== void 0 ? _e : DEFAULT_REQUEST_TIMEOUT_MSEC;
          const timeoutHandler = /* @__PURE__ */ __name(() => cancel(new McpError(ErrorCode.RequestTimeout, "Request timed out", { timeout: timeout2 })), "timeoutHandler");
          this._setupTimeout(messageId, timeout2, options2 === null || options2 === void 0 ? void 0 : options2.maxTotalTimeout, timeoutHandler, (_f = options2 === null || options2 === void 0 ? void 0 : options2.resetTimeoutOnProgress) !== null && _f !== void 0 ? _f : false);
          this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => {
            this._cleanupTimeout(messageId);
            reject(error);
          });
        });
      }
      /**
       * Emits a notification, which is a one-way message that does not expect a response.
       */
      async notification(notification, options2) {
        if (!this._transport) {
          throw new Error("Not connected");
        }
        this.assertNotificationCapability(notification.method);
        const jsonrpcNotification = {
          ...notification,
          jsonrpc: "2.0"
        };
        await this._transport.send(jsonrpcNotification, options2);
      }
      /**
       * 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 = requestSchema.shape.method.value;
        this.assertRequestHandlerCapability(method);
        this._requestHandlers.set(method, (request4, extra) => {
          return Promise.resolve(handler(requestSchema.parse(request4), 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) {
        this._notificationHandlers.set(notificationSchema.shape.method.value, (notification) => Promise.resolve(handler(notificationSchema.parse(notification))));
      }
      /**
       * Removes the notification handler for the given method.
       */
      removeNotificationHandler(method) {
        this._notificationHandlers.delete(method);
      }
    };
    __name(mergeCapabilities, "mergeCapabilities");
  }
});

// node_modules/uri-js/dist/es5/uri.all.js
var require_uri_all = __commonJS({
  "node_modules/uri-js/dist/es5/uri.all.js"(exports2, module2) {
    init_esbuild_shims();
    (function(global2, factory) {
      typeof exports2 === "object" && typeof module2 !== "undefined" ? factory(exports2) : typeof define === "function" && define.amd ? define(["exports"], factory) : factory(global2.URI = global2.URI || {});
    })(exports2, function(exports3) {
      "use strict";
      function merge3() {
        for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) {
          sets[_key] = arguments[_key];
        }
        if (sets.length > 1) {
          sets[0] = sets[0].slice(0, -1);
          var xl = sets.length - 1;
          for (var x = 1; x < xl; ++x) {
            sets[x] = sets[x].slice(1, -1);
          }
          sets[xl] = sets[xl].slice(1);
          return sets.join("");
        } else {
          return sets[0];
        }
      }
      __name(merge3, "merge");
      function subexp(str2) {
        return "(?:" + str2 + ")";
      }
      __name(subexp, "subexp");
      function typeOf(o2) {
        return o2 === void 0 ? "undefined" : o2 === null ? "null" : Object.prototype.toString.call(o2).split(" ").pop().split("]").shift().toLowerCase();
      }
      __name(typeOf, "typeOf");
      function toUpperCase(str2) {
        return str2.toUpperCase();
      }
      __name(toUpperCase, "toUpperCase");
      function toArray(obj) {
        return obj !== void 0 && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : [];
      }
      __name(toArray, "toArray");
      function assign(target, source2) {
        var obj = target;
        if (source2) {
          for (var key in source2) {
            obj[key] = source2[key];
          }
        }
        return obj;
      }
      __name(assign, "assign");
      function buildExps(isIRI2) {
        var ALPHA$$ = "[A-Za-z]", CR$ = "[\\x0D]", DIGIT$$ = "[0-9]", DQUOTE$$ = "[\\x22]", HEXDIG$$2 = merge3(DIGIT$$, "[A-Fa-f]"), LF$$ = "[\\x0A]", SP$$ = "[\\x20]", PCT_ENCODED$2 = subexp(subexp("%[EFef]" + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2) + "|" + subexp("%" + HEXDIG$$2 + HEXDIG$$2)), GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", RESERVED$$ = merge3(GEN_DELIMS$$, SUB_DELIMS$$), UCSCHAR$$ = isIRI2 ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", IPRIVATE$$ = isIRI2 ? "[\\uE000-\\uF8FF]" : "[]", UNRESERVED$$2 = merge3(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$), SCHEME$ = subexp(ALPHA$$ + merge3(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"), USERINFO$ = subexp(subexp(PCT_ENCODED$2 + "|" + merge3(UNRESERVED$$2, SUB_DELIMS$$, "[\\:]")) + "*"), DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$), DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), H16$ = subexp(HEXDIG$$2 + "{1,4}"), LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), ZONEID$ = subexp(subexp(UNRESERVED$$2 + "|" + PCT_ENCODED$2) + "+"), IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$), IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$2 + "{2})") + ZONEID$), IPVFUTURE$ = subexp("[vV]" + HEXDIG$$2 + "+\\." + merge3(UNRESERVED$$2, SUB_DELIMS$$, "[\\:]") + "+"), IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"), REG_NAME$ = subexp(subexp(PCT_ENCODED$2 + "|" + merge3(UNRESERVED$$2, SUB_DELIMS$$)) + "*"), HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")|" + REG_NAME$), PORT$ = subexp(DIGIT$$ + "*"), AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"), PCHAR$ = subexp(PCT_ENCODED$2 + "|" + merge3(UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@]")), SEGMENT$ = subexp(PCHAR$ + "*"), SEGMENT_NZ$ = subexp(PCHAR$ + "+"), SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$2 + "|" + merge3(UNRESERVED$$2, SUB_DELIMS$$, "[\\@]")) + "+"), PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"), PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"), PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), PATH_EMPTY$ = "(?!" + PCHAR$ + ")", PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), QUERY$ = subexp(subexp(PCHAR$ + "|" + merge3("[\\/\\?]", IPRIVATE$$)) + "*"), FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"), HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$), RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$), ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"), GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$", SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$";
        return {
          NOT_SCHEME: new RegExp(merge3("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"),
          NOT_USERINFO: new RegExp(merge3("[^\\%\\:]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
          NOT_HOST: new RegExp(merge3("[^\\%\\[\\]\\:]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
          NOT_PATH: new RegExp(merge3("[^\\%\\/\\:\\@]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
          NOT_PATH_NOSCHEME: new RegExp(merge3("[^\\%\\/\\@]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
          NOT_QUERY: new RegExp(merge3("[^\\%]", UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"),
          NOT_FRAGMENT: new RegExp(merge3("[^\\%]", UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"),
          ESCAPE: new RegExp(merge3("[^]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
          UNRESERVED: new RegExp(UNRESERVED$$2, "g"),
          OTHER_CHARS: new RegExp(merge3("[^\\%]", UNRESERVED$$2, RESERVED$$), "g"),
          PCT_ENCODED: new RegExp(PCT_ENCODED$2, "g"),
          IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"),
          IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$2 + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$")
          //RFC 6874, with relaxed parsing rules
        };
      }
      __name(buildExps, "buildExps");
      var URI_PROTOCOL = buildExps(false);
      var IRI_PROTOCOL = buildExps(true);
      var slicedToArray = /* @__PURE__ */ function() {
        function sliceIterator(arr, i) {
          var _arr = [];
          var _n = true;
          var _d = false;
          var _e = void 0;
          try {
            for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
              _arr.push(_s.value);
              if (i && _arr.length === i) break;
            }
          } catch (err) {
            _d = true;
            _e = err;
          } finally {
            try {
              if (!_n && _i["return"]) _i["return"]();
            } finally {
              if (_d) throw _e;
            }
          }
          return _arr;
        }
        __name(sliceIterator, "sliceIterator");
        return function(arr, i) {
          if (Array.isArray(arr)) {
            return arr;
          } else if (Symbol.iterator in Object(arr)) {
            return sliceIterator(arr, i);
          } else {
            throw new TypeError("Invalid attempt to destructure non-iterable instance");
          }
        };
      }();
      var toConsumableArray = /* @__PURE__ */ __name(function(arr) {
        if (Array.isArray(arr)) {
          for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
          return arr2;
        } else {
          return Array.from(arr);
        }
      }, "toConsumableArray");
      var maxInt = 2147483647;
      var base = 36;
      var tMin = 1;
      var tMax = 26;
      var skew = 38;
      var damp = 700;
      var initialBias = 72;
      var initialN = 128;
      var delimiter2 = "-";
      var regexPunycode = /^xn--/;
      var regexNonASCII = /[^\0-\x7E]/;
      var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g;
      var errors = {
        "overflow": "Overflow: input needs wider integers to process",
        "not-basic": "Illegal input >= 0x80 (not a basic code point)",
        "invalid-input": "Invalid input"
      };
      var baseMinusTMin = base - tMin;
      var floor = Math.floor;
      var stringFromCharCode = String.fromCharCode;
      function error$1(type) {
        throw new RangeError(errors[type]);
      }
      __name(error$1, "error$1");
      function map2(array, fn) {
        var result = [];
        var length = array.length;
        while (length--) {
          result[length] = fn(array[length]);
        }
        return result;
      }
      __name(map2, "map");
      function mapDomain(string, fn) {
        var parts = string.split("@");
        var result = "";
        if (parts.length > 1) {
          result = parts[0] + "@";
          string = parts[1];
        }
        string = string.replace(regexSeparators, ".");
        var labels = string.split(".");
        var encoded = map2(labels, fn).join(".");
        return result + encoded;
      }
      __name(mapDomain, "mapDomain");
      function ucs2decode(string) {
        var output = [];
        var counter = 0;
        var length = string.length;
        while (counter < length) {
          var value = string.charCodeAt(counter++);
          if (value >= 55296 && value <= 56319 && counter < length) {
            var extra = string.charCodeAt(counter++);
            if ((extra & 64512) == 56320) {
              output.push(((value & 1023) << 10) + (extra & 1023) + 65536);
            } else {
              output.push(value);
              counter--;
            }
          } else {
            output.push(value);
          }
        }
        return output;
      }
      __name(ucs2decode, "ucs2decode");
      var ucs2encode = /* @__PURE__ */ __name(function ucs2encode2(array) {
        return String.fromCodePoint.apply(String, toConsumableArray(array));
      }, "ucs2encode");
      var basicToDigit = /* @__PURE__ */ __name(function basicToDigit2(codePoint) {
        if (codePoint - 48 < 10) {
          return codePoint - 22;
        }
        if (codePoint - 65 < 26) {
          return codePoint - 65;
        }
        if (codePoint - 97 < 26) {
          return codePoint - 97;
        }
        return base;
      }, "basicToDigit");
      var digitToBasic = /* @__PURE__ */ __name(function digitToBasic2(digit, flag) {
        return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
      }, "digitToBasic");
      var adapt = /* @__PURE__ */ __name(function adapt2(delta, numPoints, firstTime) {
        var k = 0;
        delta = firstTime ? floor(delta / damp) : delta >> 1;
        delta += floor(delta / numPoints);
        for (
          ;
          /* no initialization */
          delta > baseMinusTMin * tMax >> 1;
          k += base
        ) {
          delta = floor(delta / baseMinusTMin);
        }
        return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
      }, "adapt");
      var decode2 = /* @__PURE__ */ __name(function decode3(input) {
        var output = [];
        var inputLength = input.length;
        var i = 0;
        var n2 = initialN;
        var bias = initialBias;
        var basic = input.lastIndexOf(delimiter2);
        if (basic < 0) {
          basic = 0;
        }
        for (var j = 0; j < basic; ++j) {
          if (input.charCodeAt(j) >= 128) {
            error$1("not-basic");
          }
          output.push(input.charCodeAt(j));
        }
        for (var index = basic > 0 ? basic + 1 : 0; index < inputLength; ) {
          var oldi = i;
          for (
            var w = 1, k = base;
            ;
            /* no condition */
            k += base
          ) {
            if (index >= inputLength) {
              error$1("invalid-input");
            }
            var digit = basicToDigit(input.charCodeAt(index++));
            if (digit >= base || digit > floor((maxInt - i) / w)) {
              error$1("overflow");
            }
            i += digit * w;
            var t2 = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
            if (digit < t2) {
              break;
            }
            var baseMinusT = base - t2;
            if (w > floor(maxInt / baseMinusT)) {
              error$1("overflow");
            }
            w *= baseMinusT;
          }
          var out = output.length + 1;
          bias = adapt(i - oldi, out, oldi == 0);
          if (floor(i / out) > maxInt - n2) {
            error$1("overflow");
          }
          n2 += floor(i / out);
          i %= out;
          output.splice(i++, 0, n2);
        }
        return String.fromCodePoint.apply(String, output);
      }, "decode");
      var encode4 = /* @__PURE__ */ __name(function encode5(input) {
        var output = [];
        input = ucs2decode(input);
        var inputLength = input.length;
        var n2 = initialN;
        var delta = 0;
        var bias = initialBias;
        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = void 0;
        try {
          for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var _currentValue2 = _step.value;
            if (_currentValue2 < 128) {
              output.push(stringFromCharCode(_currentValue2));
            }
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator.return) {
              _iterator.return();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }
        var basicLength = output.length;
        var handledCPCount = basicLength;
        if (basicLength) {
          output.push(delimiter2);
        }
        while (handledCPCount < inputLength) {
          var m = maxInt;
          var _iteratorNormalCompletion2 = true;
          var _didIteratorError2 = false;
          var _iteratorError2 = void 0;
          try {
            for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
              var currentValue = _step2.value;
              if (currentValue >= n2 && currentValue < m) {
                m = currentValue;
              }
            }
          } catch (err) {
            _didIteratorError2 = true;
            _iteratorError2 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion2 && _iterator2.return) {
                _iterator2.return();
              }
            } finally {
              if (_didIteratorError2) {
                throw _iteratorError2;
              }
            }
          }
          var handledCPCountPlusOne = handledCPCount + 1;
          if (m - n2 > floor((maxInt - delta) / handledCPCountPlusOne)) {
            error$1("overflow");
          }
          delta += (m - n2) * handledCPCountPlusOne;
          n2 = m;
          var _iteratorNormalCompletion3 = true;
          var _didIteratorError3 = false;
          var _iteratorError3 = void 0;
          try {
            for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
              var _currentValue = _step3.value;
              if (_currentValue < n2 && ++delta > maxInt) {
                error$1("overflow");
              }
              if (_currentValue == n2) {
                var q = delta;
                for (
                  var k = base;
                  ;
                  /* no condition */
                  k += base
                ) {
                  var t2 = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
                  if (q < t2) {
                    break;
                  }
                  var qMinusT = q - t2;
                  var baseMinusT = base - t2;
                  output.push(stringFromCharCode(digitToBasic(t2 + qMinusT % baseMinusT, 0)));
                  q = floor(qMinusT / baseMinusT);
                }
                output.push(stringFromCharCode(digitToBasic(q, 0)));
                bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
                delta = 0;
                ++handledCPCount;
              }
            }
          } catch (err) {
            _didIteratorError3 = true;
            _iteratorError3 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion3 && _iterator3.return) {
                _iterator3.return();
              }
            } finally {
              if (_didIteratorError3) {
                throw _iteratorError3;
              }
            }
          }
          ++delta;
          ++n2;
        }
        return output.join("");
      }, "encode");
      var toUnicode = /* @__PURE__ */ __name(function toUnicode2(input) {
        return mapDomain(input, function(string) {
          return regexPunycode.test(string) ? decode2(string.slice(4).toLowerCase()) : string;
        });
      }, "toUnicode");
      var toASCII = /* @__PURE__ */ __name(function toASCII2(input) {
        return mapDomain(input, function(string) {
          return regexNonASCII.test(string) ? "xn--" + encode4(string) : string;
        });
      }, "toASCII");
      var punycode = {
        /**
         * A string representing the current Punycode.js version number.
         * @memberOf punycode
         * @type String
         */
        "version": "2.1.0",
        /**
         * An object of methods to convert from JavaScript's internal character
         * representation (UCS-2) to Unicode code points, and back.
         * @see <https://mathiasbynens.be/notes/javascript-encoding>
         * @memberOf punycode
         * @type Object
         */
        "ucs2": {
          "decode": ucs2decode,
          "encode": ucs2encode
        },
        "decode": decode2,
        "encode": encode4,
        "toASCII": toASCII,
        "toUnicode": toUnicode
      };
      var SCHEMES = {};
      function pctEncChar(chr) {
        var c3 = chr.charCodeAt(0);
        var e2 = void 0;
        if (c3 < 16) e2 = "%0" + c3.toString(16).toUpperCase();
        else if (c3 < 128) e2 = "%" + c3.toString(16).toUpperCase();
        else if (c3 < 2048) e2 = "%" + (c3 >> 6 | 192).toString(16).toUpperCase() + "%" + (c3 & 63 | 128).toString(16).toUpperCase();
        else e2 = "%" + (c3 >> 12 | 224).toString(16).toUpperCase() + "%" + (c3 >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c3 & 63 | 128).toString(16).toUpperCase();
        return e2;
      }
      __name(pctEncChar, "pctEncChar");
      function pctDecChars(str2) {
        var newStr = "";
        var i = 0;
        var il = str2.length;
        while (i < il) {
          var c3 = parseInt(str2.substr(i + 1, 2), 16);
          if (c3 < 128) {
            newStr += String.fromCharCode(c3);
            i += 3;
          } else if (c3 >= 194 && c3 < 224) {
            if (il - i >= 6) {
              var c22 = parseInt(str2.substr(i + 4, 2), 16);
              newStr += String.fromCharCode((c3 & 31) << 6 | c22 & 63);
            } else {
              newStr += str2.substr(i, 6);
            }
            i += 6;
          } else if (c3 >= 224) {
            if (il - i >= 9) {
              var _c2 = parseInt(str2.substr(i + 4, 2), 16);
              var c32 = parseInt(str2.substr(i + 7, 2), 16);
              newStr += String.fromCharCode((c3 & 15) << 12 | (_c2 & 63) << 6 | c32 & 63);
            } else {
              newStr += str2.substr(i, 9);
            }
            i += 9;
          } else {
            newStr += str2.substr(i, 3);
            i += 3;
          }
        }
        return newStr;
      }
      __name(pctDecChars, "pctDecChars");
      function _normalizeComponentEncoding(components, protocol) {
        function decodeUnreserved2(str2) {
          var decStr = pctDecChars(str2);
          return !decStr.match(protocol.UNRESERVED) ? str2 : decStr;
        }
        __name(decodeUnreserved2, "decodeUnreserved");
        if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved2).toLowerCase().replace(protocol.NOT_SCHEME, "");
        if (components.userinfo !== void 0) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
        if (components.host !== void 0) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved2).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
        if (components.path !== void 0) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
        if (components.query !== void 0) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
        if (components.fragment !== void 0) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
        return components;
      }
      __name(_normalizeComponentEncoding, "_normalizeComponentEncoding");
      function _stripLeadingZeros(str2) {
        return str2.replace(/^0*(.*)/, "$1") || "0";
      }
      __name(_stripLeadingZeros, "_stripLeadingZeros");
      function _normalizeIPv4(host, protocol) {
        var matches = host.match(protocol.IPV4ADDRESS) || [];
        var _matches = slicedToArray(matches, 2), address = _matches[1];
        if (address) {
          return address.split(".").map(_stripLeadingZeros).join(".");
        } else {
          return host;
        }
      }
      __name(_normalizeIPv4, "_normalizeIPv4");
      function _normalizeIPv6(host, protocol) {
        var matches = host.match(protocol.IPV6ADDRESS) || [];
        var _matches2 = slicedToArray(matches, 3), address = _matches2[1], zone = _matches2[2];
        if (address) {
          var _address$toLowerCase$ = address.toLowerCase().split("::").reverse(), _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), last2 = _address$toLowerCase$2[0], first2 = _address$toLowerCase$2[1];
          var firstFields = first2 ? first2.split(":").map(_stripLeadingZeros) : [];
          var lastFields = last2.split(":").map(_stripLeadingZeros);
          var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]);
          var fieldCount = isLastFieldIPv4Address ? 7 : 8;
          var lastFieldsStart = lastFields.length - fieldCount;
          var fields = Array(fieldCount);
          for (var x = 0; x < fieldCount; ++x) {
            fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || "";
          }
          if (isLastFieldIPv4Address) {
            fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol);
          }
          var allZeroFields = fields.reduce(function(acc, field, index) {
            if (!field || field === "0") {
              var lastLongest = acc[acc.length - 1];
              if (lastLongest && lastLongest.index + lastLongest.length === index) {
                lastLongest.length++;
              } else {
                acc.push({ index, length: 1 });
              }
            }
            return acc;
          }, []);
          var longestZeroFields = allZeroFields.sort(function(a, b) {
            return b.length - a.length;
          })[0];
          var newHost = void 0;
          if (longestZeroFields && longestZeroFields.length > 1) {
            var newFirst = fields.slice(0, longestZeroFields.index);
            var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length);
            newHost = newFirst.join(":") + "::" + newLast.join(":");
          } else {
            newHost = fields.join(":");
          }
          if (zone) {
            newHost += "%" + zone;
          }
          return newHost;
        } else {
          return host;
        }
      }
      __name(_normalizeIPv6, "_normalizeIPv6");
      var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i;
      var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === void 0;
      function parse12(uriString) {
        var options2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
        var components = {};
        var protocol = options2.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
        if (options2.reference === "suffix") uriString = (options2.scheme ? options2.scheme + ":" : "") + "//" + uriString;
        var matches = uriString.match(URI_PARSE);
        if (matches) {
          if (NO_MATCH_IS_UNDEFINED) {
            components.scheme = matches[1];
            components.userinfo = matches[3];
            components.host = matches[4];
            components.port = parseInt(matches[5], 10);
            components.path = matches[6] || "";
            components.query = matches[7];
            components.fragment = matches[8];
            if (isNaN(components.port)) {
              components.port = matches[5];
            }
          } else {
            components.scheme = matches[1] || void 0;
            components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : void 0;
            components.host = uriString.indexOf("//") !== -1 ? matches[4] : void 0;
            components.port = parseInt(matches[5], 10);
            components.path = matches[6] || "";
            components.query = uriString.indexOf("?") !== -1 ? matches[7] : void 0;
            components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : void 0;
            if (isNaN(components.port)) {
              components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : void 0;
            }
          }
          if (components.host) {
            components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol);
          }
          if (components.scheme === void 0 && components.userinfo === void 0 && components.host === void 0 && components.port === void 0 && !components.path && components.query === void 0) {
            components.reference = "same-document";
          } else if (components.scheme === void 0) {
            components.reference = "relative";
          } else if (components.fragment === void 0) {
            components.reference = "absolute";
          } else {
            components.reference = "uri";
          }
          if (options2.reference && options2.reference !== "suffix" && options2.reference !== components.reference) {
            components.error = components.error || "URI is not a " + options2.reference + " reference.";
          }
          var schemeHandler = SCHEMES[(options2.scheme || components.scheme || "").toLowerCase()];
          if (!options2.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
            if (components.host && (options2.domainHost || schemeHandler && schemeHandler.domainHost)) {
              try {
                components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());
              } catch (e2) {
                components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e2;
              }
            }
            _normalizeComponentEncoding(components, URI_PROTOCOL);
          } else {
            _normalizeComponentEncoding(components, protocol);
          }
          if (schemeHandler && schemeHandler.parse) {
            schemeHandler.parse(components, options2);
          }
        } else {
          components.error = components.error || "URI can not be parsed.";
        }
        return components;
      }
      __name(parse12, "parse");
      function _recomposeAuthority(components, options2) {
        var protocol = options2.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
        var uriTokens = [];
        if (components.userinfo !== void 0) {
          uriTokens.push(components.userinfo);
          uriTokens.push("@");
        }
        if (components.host !== void 0) {
          uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function(_, $1, $2) {
            return "[" + $1 + ($2 ? "%25" + $2 : "") + "]";
          }));
        }
        if (typeof components.port === "number" || typeof components.port === "string") {
          uriTokens.push(":");
          uriTokens.push(String(components.port));
        }
        return uriTokens.length ? uriTokens.join("") : void 0;
      }
      __name(_recomposeAuthority, "_recomposeAuthority");
      var RDS1 = /^\.\.?\//;
      var RDS2 = /^\/\.(\/|$)/;
      var RDS3 = /^\/\.\.(\/|$)/;
      var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/;
      function removeDotSegments(input) {
        var output = [];
        while (input.length) {
          if (input.match(RDS1)) {
            input = input.replace(RDS1, "");
          } else if (input.match(RDS2)) {
            input = input.replace(RDS2, "/");
          } else if (input.match(RDS3)) {
            input = input.replace(RDS3, "/");
            output.pop();
          } else if (input === "." || input === "..") {
            input = "";
          } else {
            var im = input.match(RDS5);
            if (im) {
              var s2 = im[0];
              input = input.slice(s2.length);
              output.push(s2);
            } else {
              throw new Error("Unexpected dot segment condition");
            }
          }
        }
        return output.join("");
      }
      __name(removeDotSegments, "removeDotSegments");
      function serialize2(components) {
        var options2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
        var protocol = options2.iri ? IRI_PROTOCOL : URI_PROTOCOL;
        var uriTokens = [];
        var schemeHandler = SCHEMES[(options2.scheme || components.scheme || "").toLowerCase()];
        if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options2);
        if (components.host) {
          if (protocol.IPV6ADDRESS.test(components.host)) {
          } else if (options2.domainHost || schemeHandler && schemeHandler.domainHost) {
            try {
              components.host = !options2.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host);
            } catch (e2) {
              components.error = components.error || "Host's domain name can not be converted to " + (!options2.iri ? "ASCII" : "Unicode") + " via punycode: " + e2;
            }
          }
        }
        _normalizeComponentEncoding(components, protocol);
        if (options2.reference !== "suffix" && components.scheme) {
          uriTokens.push(components.scheme);
          uriTokens.push(":");
        }
        var authority = _recomposeAuthority(components, options2);
        if (authority !== void 0) {
          if (options2.reference !== "suffix") {
            uriTokens.push("//");
          }
          uriTokens.push(authority);
          if (components.path && components.path.charAt(0) !== "/") {
            uriTokens.push("/");
          }
        }
        if (components.path !== void 0) {
          var s2 = components.path;
          if (!options2.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
            s2 = removeDotSegments(s2);
          }
          if (authority === void 0) {
            s2 = s2.replace(/^\/\//, "/%2F");
          }
          uriTokens.push(s2);
        }
        if (components.query !== void 0) {
          uriTokens.push("?");
          uriTokens.push(components.query);
        }
        if (components.fragment !== void 0) {
          uriTokens.push("#");
          uriTokens.push(components.fragment);
        }
        return uriTokens.join("");
      }
      __name(serialize2, "serialize");
      function resolveComponents(base2, relative10) {
        var options2 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
        var skipNormalization = arguments[3];
        var target = {};
        if (!skipNormalization) {
          base2 = parse12(serialize2(base2, options2), options2);
          relative10 = parse12(serialize2(relative10, options2), options2);
        }
        options2 = options2 || {};
        if (!options2.tolerant && relative10.scheme) {
          target.scheme = relative10.scheme;
          target.userinfo = relative10.userinfo;
          target.host = relative10.host;
          target.port = relative10.port;
          target.path = removeDotSegments(relative10.path || "");
          target.query = relative10.query;
        } else {
          if (relative10.userinfo !== void 0 || relative10.host !== void 0 || relative10.port !== void 0) {
            target.userinfo = relative10.userinfo;
            target.host = relative10.host;
            target.port = relative10.port;
            target.path = removeDotSegments(relative10.path || "");
            target.query = relative10.query;
          } else {
            if (!relative10.path) {
              target.path = base2.path;
              if (relative10.query !== void 0) {
                target.query = relative10.query;
              } else {
                target.query = base2.query;
              }
            } else {
              if (relative10.path.charAt(0) === "/") {
                target.path = removeDotSegments(relative10.path);
              } else {
                if ((base2.userinfo !== void 0 || base2.host !== void 0 || base2.port !== void 0) && !base2.path) {
                  target.path = "/" + relative10.path;
                } else if (!base2.path) {
                  target.path = relative10.path;
                } else {
                  target.path = base2.path.slice(0, base2.path.lastIndexOf("/") + 1) + relative10.path;
                }
                target.path = removeDotSegments(target.path);
              }
              target.query = relative10.query;
            }
            target.userinfo = base2.userinfo;
            target.host = base2.host;
            target.port = base2.port;
          }
          target.scheme = base2.scheme;
        }
        target.fragment = relative10.fragment;
        return target;
      }
      __name(resolveComponents, "resolveComponents");
      function resolve24(baseURI, relativeURI, options2) {
        var schemelessOptions = assign({ scheme: "null" }, options2);
        return serialize2(resolveComponents(parse12(baseURI, schemelessOptions), parse12(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);
      }
      __name(resolve24, "resolve");
      function normalize10(uri, options2) {
        if (typeof uri === "string") {
          uri = serialize2(parse12(uri, options2), options2);
        } else if (typeOf(uri) === "object") {
          uri = parse12(serialize2(uri, options2), options2);
        }
        return uri;
      }
      __name(normalize10, "normalize");
      function equal(uriA, uriB, options2) {
        if (typeof uriA === "string") {
          uriA = serialize2(parse12(uriA, options2), options2);
        } else if (typeOf(uriA) === "object") {
          uriA = serialize2(uriA, options2);
        }
        if (typeof uriB === "string") {
          uriB = serialize2(parse12(uriB, options2), options2);
        } else if (typeOf(uriB) === "object") {
          uriB = serialize2(uriB, options2);
        }
        return uriA === uriB;
      }
      __name(equal, "equal");
      function escapeComponent(str2, options2) {
        return str2 && str2.toString().replace(!options2 || !options2.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar);
      }
      __name(escapeComponent, "escapeComponent");
      function unescapeComponent(str2, options2) {
        return str2 && str2.toString().replace(!options2 || !options2.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars);
      }
      __name(unescapeComponent, "unescapeComponent");
      var handler = {
        scheme: "http",
        domainHost: true,
        parse: /* @__PURE__ */ __name(function parse13(components, options2) {
          if (!components.host) {
            components.error = components.error || "HTTP URIs must have a host.";
          }
          return components;
        }, "parse"),
        serialize: /* @__PURE__ */ __name(function serialize3(components, options2) {
          var secure = String(components.scheme).toLowerCase() === "https";
          if (components.port === (secure ? 443 : 80) || components.port === "") {
            components.port = void 0;
          }
          if (!components.path) {
            components.path = "/";
          }
          return components;
        }, "serialize")
      };
      var handler$1 = {
        scheme: "https",
        domainHost: handler.domainHost,
        parse: handler.parse,
        serialize: handler.serialize
      };
      function isSecure(wsComponents) {
        return typeof wsComponents.secure === "boolean" ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss";
      }
      __name(isSecure, "isSecure");
      var handler$2 = {
        scheme: "ws",
        domainHost: true,
        parse: /* @__PURE__ */ __name(function parse13(components, options2) {
          var wsComponents = components;
          wsComponents.secure = isSecure(wsComponents);
          wsComponents.resourceName = (wsComponents.path || "/") + (wsComponents.query ? "?" + wsComponents.query : "");
          wsComponents.path = void 0;
          wsComponents.query = void 0;
          return wsComponents;
        }, "parse"),
        serialize: /* @__PURE__ */ __name(function serialize3(wsComponents, options2) {
          if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") {
            wsComponents.port = void 0;
          }
          if (typeof wsComponents.secure === "boolean") {
            wsComponents.scheme = wsComponents.secure ? "wss" : "ws";
            wsComponents.secure = void 0;
          }
          if (wsComponents.resourceName) {
            var _wsComponents$resourc = wsComponents.resourceName.split("?"), _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), path108 = _wsComponents$resourc2[0], query = _wsComponents$resourc2[1];
            wsComponents.path = path108 && path108 !== "/" ? path108 : void 0;
            wsComponents.query = query;
            wsComponents.resourceName = void 0;
          }
          wsComponents.fragment = void 0;
          return wsComponents;
        }, "serialize")
      };
      var handler$3 = {
        scheme: "wss",
        domainHost: handler$2.domainHost,
        parse: handler$2.parse,
        serialize: handler$2.serialize
      };
      var O = {};
      var isIRI = true;
      var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]";
      var HEXDIG$$ = "[0-9A-Fa-f]";
      var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$));
      var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]";
      var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]";
      var VCHAR$$ = merge3(QTEXT$$, '[\\"\\\\]');
      var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]";
      var UNRESERVED = new RegExp(UNRESERVED$$, "g");
      var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g");
      var NOT_LOCAL_PART = new RegExp(merge3("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g");
      var NOT_HFNAME = new RegExp(merge3("[^]", UNRESERVED$$, SOME_DELIMS$$), "g");
      var NOT_HFVALUE = NOT_HFNAME;
      function decodeUnreserved(str2) {
        var decStr = pctDecChars(str2);
        return !decStr.match(UNRESERVED) ? str2 : decStr;
      }
      __name(decodeUnreserved, "decodeUnreserved");
      var handler$4 = {
        scheme: "mailto",
        parse: /* @__PURE__ */ __name(function parse$$1(components, options2) {
          var mailtoComponents = components;
          var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : [];
          mailtoComponents.path = void 0;
          if (mailtoComponents.query) {
            var unknownHeaders = false;
            var headers = {};
            var hfields = mailtoComponents.query.split("&");
            for (var x = 0, xl = hfields.length; x < xl; ++x) {
              var hfield = hfields[x].split("=");
              switch (hfield[0]) {
                case "to":
                  var toAddrs = hfield[1].split(",");
                  for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) {
                    to.push(toAddrs[_x]);
                  }
                  break;
                case "subject":
                  mailtoComponents.subject = unescapeComponent(hfield[1], options2);
                  break;
                case "body":
                  mailtoComponents.body = unescapeComponent(hfield[1], options2);
                  break;
                default:
                  unknownHeaders = true;
                  headers[unescapeComponent(hfield[0], options2)] = unescapeComponent(hfield[1], options2);
                  break;
              }
            }
            if (unknownHeaders) mailtoComponents.headers = headers;
          }
          mailtoComponents.query = void 0;
          for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) {
            var addr = to[_x2].split("@");
            addr[0] = unescapeComponent(addr[0]);
            if (!options2.unicodeSupport) {
              try {
                addr[1] = punycode.toASCII(unescapeComponent(addr[1], options2).toLowerCase());
              } catch (e2) {
                mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e2;
              }
            } else {
              addr[1] = unescapeComponent(addr[1], options2).toLowerCase();
            }
            to[_x2] = addr.join("@");
          }
          return mailtoComponents;
        }, "parse$$1"),
        serialize: /* @__PURE__ */ __name(function serialize$$1(mailtoComponents, options2) {
          var components = mailtoComponents;
          var to = toArray(mailtoComponents.to);
          if (to) {
            for (var x = 0, xl = to.length; x < xl; ++x) {
              var toAddr = String(to[x]);
              var atIdx = toAddr.lastIndexOf("@");
              var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);
              var domain = toAddr.slice(atIdx + 1);
              try {
                domain = !options2.iri ? punycode.toASCII(unescapeComponent(domain, options2).toLowerCase()) : punycode.toUnicode(domain);
              } catch (e2) {
                components.error = components.error || "Email address's domain name can not be converted to " + (!options2.iri ? "ASCII" : "Unicode") + " via punycode: " + e2;
              }
              to[x] = localPart + "@" + domain;
            }
            components.path = to.join(",");
          }
          var headers = mailtoComponents.headers = mailtoComponents.headers || {};
          if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject;
          if (mailtoComponents.body) headers["body"] = mailtoComponents.body;
          var fields = [];
          for (var name3 in headers) {
            if (headers[name3] !== O[name3]) {
              fields.push(name3.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name3].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar));
            }
          }
          if (fields.length) {
            components.query = fields.join("&");
          }
          return components;
        }, "serialize$$1")
      };
      var URN_PARSE = /^([^\:]+)\:(.*)/;
      var handler$5 = {
        scheme: "urn",
        parse: /* @__PURE__ */ __name(function parse$$1(components, options2) {
          var matches = components.path && components.path.match(URN_PARSE);
          var urnComponents = components;
          if (matches) {
            var scheme = options2.scheme || urnComponents.scheme || "urn";
            var nid = matches[1].toLowerCase();
            var nss = matches[2];
            var urnScheme = scheme + ":" + (options2.nid || nid);
            var schemeHandler = SCHEMES[urnScheme];
            urnComponents.nid = nid;
            urnComponents.nss = nss;
            urnComponents.path = void 0;
            if (schemeHandler) {
              urnComponents = schemeHandler.parse(urnComponents, options2);
            }
          } else {
            urnComponents.error = urnComponents.error || "URN can not be parsed.";
          }
          return urnComponents;
        }, "parse$$1"),
        serialize: /* @__PURE__ */ __name(function serialize$$1(urnComponents, options2) {
          var scheme = options2.scheme || urnComponents.scheme || "urn";
          var nid = urnComponents.nid;
          var urnScheme = scheme + ":" + (options2.nid || nid);
          var schemeHandler = SCHEMES[urnScheme];
          if (schemeHandler) {
            urnComponents = schemeHandler.serialize(urnComponents, options2);
          }
          var uriComponents = urnComponents;
          var nss = urnComponents.nss;
          uriComponents.path = (nid || options2.nid) + ":" + nss;
          return uriComponents;
        }, "serialize$$1")
      };
      var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/;
      var handler$6 = {
        scheme: "urn:uuid",
        parse: /* @__PURE__ */ __name(function parse13(urnComponents, options2) {
          var uuidComponents = urnComponents;
          uuidComponents.uuid = uuidComponents.nss;
          uuidComponents.nss = void 0;
          if (!options2.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) {
            uuidComponents.error = uuidComponents.error || "UUID is not valid.";
          }
          return uuidComponents;
        }, "parse"),
        serialize: /* @__PURE__ */ __name(function serialize3(uuidComponents, options2) {
          var urnComponents = uuidComponents;
          urnComponents.nss = (uuidComponents.uuid || "").toLowerCase();
          return urnComponents;
        }, "serialize")
      };
      SCHEMES[handler.scheme] = handler;
      SCHEMES[handler$1.scheme] = handler$1;
      SCHEMES[handler$2.scheme] = handler$2;
      SCHEMES[handler$3.scheme] = handler$3;
      SCHEMES[handler$4.scheme] = handler$4;
      SCHEMES[handler$5.scheme] = handler$5;
      SCHEMES[handler$6.scheme] = handler$6;
      exports3.SCHEMES = SCHEMES;
      exports3.pctEncChar = pctEncChar;
      exports3.pctDecChars = pctDecChars;
      exports3.parse = parse12;
      exports3.removeDotSegments = removeDotSegments;
      exports3.serialize = serialize2;
      exports3.resolveComponents = resolveComponents;
      exports3.resolve = resolve24;
      exports3.normalize = normalize10;
      exports3.equal = equal;
      exports3.escapeComponent = escapeComponent;
      exports3.unescapeComponent = unescapeComponent;
      Object.defineProperty(exports3, "__esModule", { value: true });
    });
  }
});

// node_modules/ajv/lib/compile/ucs2length.js
var require_ucs2length3 = __commonJS({
  "node_modules/ajv/lib/compile/ucs2length.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function ucs2length(str2) {
      var length = 0, len = str2.length, pos2 = 0, value;
      while (pos2 < len) {
        length++;
        value = str2.charCodeAt(pos2++);
        if (value >= 55296 && value <= 56319 && pos2 < len) {
          value = str2.charCodeAt(pos2);
          if ((value & 64512) == 56320) pos2++;
        }
      }
      return length;
    }, "ucs2length");
  }
});

// node_modules/ajv/lib/compile/util.js
var require_util15 = __commonJS({
  "node_modules/ajv/lib/compile/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      copy,
      checkDataType,
      checkDataTypes,
      coerceToTypes,
      toHash,
      getProperty: getProperty2,
      escapeQuotes,
      equal: require_fast_deep_equal(),
      ucs2length: require_ucs2length3(),
      varOccurences,
      varReplace,
      schemaHasRules,
      schemaHasRulesExcept,
      schemaUnknownRules,
      toQuotedString,
      getPathExpr,
      getPath,
      getData,
      unescapeFragment,
      unescapeJsonPointer,
      escapeFragment,
      escapeJsonPointer
    };
    function copy(o2, to) {
      to = to || {};
      for (var key in o2) to[key] = o2[key];
      return to;
    }
    __name(copy, "copy");
    function checkDataType(dataType, data, strictNumbers, negate) {
      var EQUAL = negate ? " !== " : " === ", AND = negate ? " || " : " && ", OK2 = negate ? "!" : "", NOT = negate ? "" : "!";
      switch (dataType) {
        case "null":
          return data + EQUAL + "null";
        case "array":
          return OK2 + "Array.isArray(" + data + ")";
        case "object":
          return "(" + OK2 + data + AND + "typeof " + data + EQUAL + '"object"' + AND + NOT + "Array.isArray(" + data + "))";
        case "integer":
          return "(typeof " + data + EQUAL + '"number"' + AND + NOT + "(" + data + " % 1)" + AND + data + EQUAL + data + (strictNumbers ? AND + OK2 + "isFinite(" + data + ")" : "") + ")";
        case "number":
          return "(typeof " + data + EQUAL + '"' + dataType + '"' + (strictNumbers ? AND + OK2 + "isFinite(" + data + ")" : "") + ")";
        default:
          return "typeof " + data + EQUAL + '"' + dataType + '"';
      }
    }
    __name(checkDataType, "checkDataType");
    function checkDataTypes(dataTypes, data, strictNumbers) {
      switch (dataTypes.length) {
        case 1:
          return checkDataType(dataTypes[0], data, strictNumbers, true);
        default:
          var code2 = "";
          var types3 = toHash(dataTypes);
          if (types3.array && types3.object) {
            code2 = types3.null ? "(" : "(!" + data + " || ";
            code2 += "typeof " + data + ' !== "object")';
            delete types3.null;
            delete types3.array;
            delete types3.object;
          }
          if (types3.number) delete types3.integer;
          for (var t2 in types3)
            code2 += (code2 ? " && " : "") + checkDataType(t2, data, strictNumbers, true);
          return code2;
      }
    }
    __name(checkDataTypes, "checkDataTypes");
    var COERCE_TO_TYPES = toHash(["string", "number", "integer", "boolean", "null"]);
    function coerceToTypes(optionCoerceTypes, dataTypes) {
      if (Array.isArray(dataTypes)) {
        var types3 = [];
        for (var i = 0; i < dataTypes.length; i++) {
          var t2 = dataTypes[i];
          if (COERCE_TO_TYPES[t2]) types3[types3.length] = t2;
          else if (optionCoerceTypes === "array" && t2 === "array") types3[types3.length] = t2;
        }
        if (types3.length) return types3;
      } else if (COERCE_TO_TYPES[dataTypes]) {
        return [dataTypes];
      } else if (optionCoerceTypes === "array" && dataTypes === "array") {
        return ["array"];
      }
    }
    __name(coerceToTypes, "coerceToTypes");
    function toHash(arr) {
      var hash = {};
      for (var i = 0; i < arr.length; i++) hash[arr[i]] = true;
      return hash;
    }
    __name(toHash, "toHash");
    var IDENTIFIER2 = /^[a-z$_][a-z$_0-9]*$/i;
    var SINGLE_QUOTE2 = /'|\\/g;
    function getProperty2(key) {
      return typeof key == "number" ? "[" + key + "]" : IDENTIFIER2.test(key) ? "." + key : "['" + escapeQuotes(key) + "']";
    }
    __name(getProperty2, "getProperty");
    function escapeQuotes(str2) {
      return str2.replace(SINGLE_QUOTE2, "\\$&").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\f/g, "\\f").replace(/\t/g, "\\t");
    }
    __name(escapeQuotes, "escapeQuotes");
    function varOccurences(str2, dataVar) {
      dataVar += "[^0-9]";
      var matches = str2.match(new RegExp(dataVar, "g"));
      return matches ? matches.length : 0;
    }
    __name(varOccurences, "varOccurences");
    function varReplace(str2, dataVar, expr) {
      dataVar += "([^0-9])";
      expr = expr.replace(/\$/g, "$$$$");
      return str2.replace(new RegExp(dataVar, "g"), expr + "$1");
    }
    __name(varReplace, "varReplace");
    function schemaHasRules(schema, rules) {
      if (typeof schema == "boolean") return !schema;
      for (var key in schema) if (rules[key]) return true;
    }
    __name(schemaHasRules, "schemaHasRules");
    function schemaHasRulesExcept(schema, rules, exceptKeyword) {
      if (typeof schema == "boolean") return !schema && exceptKeyword != "not";
      for (var key in schema) if (key != exceptKeyword && rules[key]) return true;
    }
    __name(schemaHasRulesExcept, "schemaHasRulesExcept");
    function schemaUnknownRules(schema, rules) {
      if (typeof schema == "boolean") return;
      for (var key in schema) if (!rules[key]) return key;
    }
    __name(schemaUnknownRules, "schemaUnknownRules");
    function toQuotedString(str2) {
      return "'" + escapeQuotes(str2) + "'";
    }
    __name(toQuotedString, "toQuotedString");
    function getPathExpr(currentPath, expr, jsonPointers, isNumber3) {
      var path108 = jsonPointers ? "'/' + " + expr + (isNumber3 ? "" : ".replace(/~/g, '~0').replace(/\\//g, '~1')") : isNumber3 ? "'[' + " + expr + " + ']'" : "'[\\'' + " + expr + " + '\\']'";
      return joinPaths(currentPath, path108);
    }
    __name(getPathExpr, "getPathExpr");
    function getPath(currentPath, prop, jsonPointers) {
      var path108 = jsonPointers ? toQuotedString("/" + escapeJsonPointer(prop)) : toQuotedString(getProperty2(prop));
      return joinPaths(currentPath, path108);
    }
    __name(getPath, "getPath");
    var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
    var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
    function getData($data, lvl, paths) {
      var up, jsonPointer, data, matches;
      if ($data === "") return "rootData";
      if ($data[0] == "/") {
        if (!JSON_POINTER.test($data)) throw new Error("Invalid JSON-pointer: " + $data);
        jsonPointer = $data;
        data = "rootData";
      } else {
        matches = $data.match(RELATIVE_JSON_POINTER);
        if (!matches) throw new Error("Invalid JSON-pointer: " + $data);
        up = +matches[1];
        jsonPointer = matches[2];
        if (jsonPointer == "#") {
          if (up >= lvl) throw new Error("Cannot access property/index " + up + " levels up, current level is " + lvl);
          return paths[lvl - up];
        }
        if (up > lvl) throw new Error("Cannot access data " + up + " levels up, current level is " + lvl);
        data = "data" + (lvl - up || "");
        if (!jsonPointer) return data;
      }
      var expr = data;
      var segments = jsonPointer.split("/");
      for (var i = 0; i < segments.length; i++) {
        var segment = segments[i];
        if (segment) {
          data += getProperty2(unescapeJsonPointer(segment));
          expr += " && " + data;
        }
      }
      return expr;
    }
    __name(getData, "getData");
    function joinPaths(a, b) {
      if (a == '""') return b;
      return (a + " + " + b).replace(/([^\\])' \+ '/g, "$1");
    }
    __name(joinPaths, "joinPaths");
    function unescapeFragment(str2) {
      return unescapeJsonPointer(decodeURIComponent(str2));
    }
    __name(unescapeFragment, "unescapeFragment");
    function escapeFragment(str2) {
      return encodeURIComponent(escapeJsonPointer(str2));
    }
    __name(escapeFragment, "escapeFragment");
    function escapeJsonPointer(str2) {
      return str2.replace(/~/g, "~0").replace(/\//g, "~1");
    }
    __name(escapeJsonPointer, "escapeJsonPointer");
    function unescapeJsonPointer(str2) {
      return str2.replace(/~1/g, "/").replace(/~0/g, "~");
    }
    __name(unescapeJsonPointer, "unescapeJsonPointer");
  }
});

// node_modules/ajv/lib/compile/schema_obj.js
var require_schema_obj = __commonJS({
  "node_modules/ajv/lib/compile/schema_obj.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var util4 = require_util15();
    module2.exports = SchemaObject;
    function SchemaObject(obj) {
      util4.copy(obj, this);
    }
    __name(SchemaObject, "SchemaObject");
  }
});

// node_modules/ajv/lib/compile/resolve.js
var require_resolve4 = __commonJS({
  "node_modules/ajv/lib/compile/resolve.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var URI = require_uri_all();
    var equal = require_fast_deep_equal();
    var util4 = require_util15();
    var SchemaObject = require_schema_obj();
    var traverse = require_json_schema_traverse();
    module2.exports = resolve24;
    resolve24.normalizeId = normalizeId;
    resolve24.fullPath = getFullPath;
    resolve24.url = resolveUrl;
    resolve24.ids = resolveIds;
    resolve24.inlineRef = inlineRef;
    resolve24.schema = resolveSchema;
    function resolve24(compile2, root, ref) {
      var refVal = this._refs[ref];
      if (typeof refVal == "string") {
        if (this._refs[refVal]) refVal = this._refs[refVal];
        else return resolve24.call(this, compile2, root, refVal);
      }
      refVal = refVal || this._schemas[ref];
      if (refVal instanceof SchemaObject) {
        return inlineRef(refVal.schema, this._opts.inlineRefs) ? refVal.schema : refVal.validate || this._compile(refVal);
      }
      var res = resolveSchema.call(this, root, ref);
      var schema, v, baseId;
      if (res) {
        schema = res.schema;
        root = res.root;
        baseId = res.baseId;
      }
      if (schema instanceof SchemaObject) {
        v = schema.validate || compile2.call(this, schema.schema, root, void 0, baseId);
      } else if (schema !== void 0) {
        v = inlineRef(schema, this._opts.inlineRefs) ? schema : compile2.call(this, schema, root, void 0, baseId);
      }
      return v;
    }
    __name(resolve24, "resolve");
    function resolveSchema(root, ref) {
      var p = URI.parse(ref), refPath = _getFullPath(p), baseId = getFullPath(this._getId(root.schema));
      if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
        var id = normalizeId(refPath);
        var refVal = this._refs[id];
        if (typeof refVal == "string") {
          return resolveRecursive.call(this, root, refVal, p);
        } else if (refVal instanceof SchemaObject) {
          if (!refVal.validate) this._compile(refVal);
          root = refVal;
        } else {
          refVal = this._schemas[id];
          if (refVal instanceof SchemaObject) {
            if (!refVal.validate) this._compile(refVal);
            if (id == normalizeId(ref))
              return { schema: refVal, root, baseId };
            root = refVal;
          } else {
            return;
          }
        }
        if (!root.schema) return;
        baseId = getFullPath(this._getId(root.schema));
      }
      return getJsonPointer.call(this, p, baseId, root.schema, root);
    }
    __name(resolveSchema, "resolveSchema");
    function resolveRecursive(root, ref, parsedRef) {
      var res = resolveSchema.call(this, root, ref);
      if (res) {
        var schema = res.schema;
        var baseId = res.baseId;
        root = res.root;
        var id = this._getId(schema);
        if (id) baseId = resolveUrl(baseId, id);
        return getJsonPointer.call(this, parsedRef, baseId, schema, root);
      }
    }
    __name(resolveRecursive, "resolveRecursive");
    var PREVENT_SCOPE_CHANGE = util4.toHash(["properties", "patternProperties", "enum", "dependencies", "definitions"]);
    function getJsonPointer(parsedRef, baseId, schema, root) {
      parsedRef.fragment = parsedRef.fragment || "";
      if (parsedRef.fragment.slice(0, 1) != "/") return;
      var parts = parsedRef.fragment.split("/");
      for (var i = 1; i < parts.length; i++) {
        var part = parts[i];
        if (part) {
          part = util4.unescapeFragment(part);
          schema = schema[part];
          if (schema === void 0) break;
          var id;
          if (!PREVENT_SCOPE_CHANGE[part]) {
            id = this._getId(schema);
            if (id) baseId = resolveUrl(baseId, id);
            if (schema.$ref) {
              var $ref = resolveUrl(baseId, schema.$ref);
              var res = resolveSchema.call(this, root, $ref);
              if (res) {
                schema = res.schema;
                root = res.root;
                baseId = res.baseId;
              }
            }
          }
        }
      }
      if (schema !== void 0 && schema !== root.schema)
        return { schema, root, baseId };
    }
    __name(getJsonPointer, "getJsonPointer");
    var SIMPLE_INLINED = util4.toHash([
      "type",
      "format",
      "pattern",
      "maxLength",
      "minLength",
      "maxProperties",
      "minProperties",
      "maxItems",
      "minItems",
      "maximum",
      "minimum",
      "uniqueItems",
      "multipleOf",
      "required",
      "enum"
    ]);
    function inlineRef(schema, limit2) {
      if (limit2 === false) return false;
      if (limit2 === void 0 || limit2 === true) return checkNoRef(schema);
      else if (limit2) return countKeys(schema) <= limit2;
    }
    __name(inlineRef, "inlineRef");
    function checkNoRef(schema) {
      var item;
      if (Array.isArray(schema)) {
        for (var i = 0; i < schema.length; i++) {
          item = schema[i];
          if (typeof item == "object" && !checkNoRef(item)) return false;
        }
      } else {
        for (var key in schema) {
          if (key == "$ref") return false;
          item = schema[key];
          if (typeof item == "object" && !checkNoRef(item)) return false;
        }
      }
      return true;
    }
    __name(checkNoRef, "checkNoRef");
    function countKeys(schema) {
      var count = 0, item;
      if (Array.isArray(schema)) {
        for (var i = 0; i < schema.length; i++) {
          item = schema[i];
          if (typeof item == "object") count += countKeys(item);
          if (count == Infinity) return Infinity;
        }
      } else {
        for (var key in schema) {
          if (key == "$ref") return Infinity;
          if (SIMPLE_INLINED[key]) {
            count++;
          } else {
            item = schema[key];
            if (typeof item == "object") count += countKeys(item) + 1;
            if (count == Infinity) return Infinity;
          }
        }
      }
      return count;
    }
    __name(countKeys, "countKeys");
    function getFullPath(id, normalize10) {
      if (normalize10 !== false) id = normalizeId(id);
      var p = URI.parse(id);
      return _getFullPath(p);
    }
    __name(getFullPath, "getFullPath");
    function _getFullPath(p) {
      return URI.serialize(p).split("#")[0] + "#";
    }
    __name(_getFullPath, "_getFullPath");
    var TRAILING_SLASH_HASH = /#\/?$/;
    function normalizeId(id) {
      return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
    }
    __name(normalizeId, "normalizeId");
    function resolveUrl(baseId, id) {
      id = normalizeId(id);
      return URI.resolve(baseId, id);
    }
    __name(resolveUrl, "resolveUrl");
    function resolveIds(schema) {
      var schemaId = normalizeId(this._getId(schema));
      var baseIds = { "": schemaId };
      var fullPaths = { "": getFullPath(schemaId, false) };
      var localRefs = {};
      var self2 = this;
      traverse(schema, { allKeys: true }, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
        if (jsonPtr === "") return;
        var id = self2._getId(sch);
        var baseId = baseIds[parentJsonPtr];
        var fullPath = fullPaths[parentJsonPtr] + "/" + parentKeyword;
        if (keyIndex !== void 0)
          fullPath += "/" + (typeof keyIndex == "number" ? keyIndex : util4.escapeFragment(keyIndex));
        if (typeof id == "string") {
          id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id);
          var refVal = self2._refs[id];
          if (typeof refVal == "string") refVal = self2._refs[refVal];
          if (refVal && refVal.schema) {
            if (!equal(sch, refVal.schema))
              throw new Error('id "' + id + '" resolves to more than one schema');
          } else if (id != normalizeId(fullPath)) {
            if (id[0] == "#") {
              if (localRefs[id] && !equal(sch, localRefs[id]))
                throw new Error('id "' + id + '" resolves to more than one schema');
              localRefs[id] = sch;
            } else {
              self2._refs[id] = fullPath;
            }
          }
        }
        baseIds[jsonPtr] = baseId;
        fullPaths[jsonPtr] = fullPath;
      });
      return localRefs;
    }
    __name(resolveIds, "resolveIds");
  }
});

// node_modules/ajv/lib/compile/error_classes.js
var require_error_classes = __commonJS({
  "node_modules/ajv/lib/compile/error_classes.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var resolve24 = require_resolve4();
    module2.exports = {
      Validation: errorSubclass(ValidationError),
      MissingRef: errorSubclass(MissingRefError)
    };
    function ValidationError(errors) {
      this.message = "validation failed";
      this.errors = errors;
      this.ajv = this.validation = true;
    }
    __name(ValidationError, "ValidationError");
    MissingRefError.message = function(baseId, ref) {
      return "can't resolve reference " + ref + " from id " + baseId;
    };
    function MissingRefError(baseId, ref, message) {
      this.message = message || MissingRefError.message(baseId, ref);
      this.missingRef = resolve24.url(baseId, ref);
      this.missingSchema = resolve24.normalizeId(resolve24.fullPath(this.missingRef));
    }
    __name(MissingRefError, "MissingRefError");
    function errorSubclass(Subclass) {
      Subclass.prototype = Object.create(Error.prototype);
      Subclass.prototype.constructor = Subclass;
      return Subclass;
    }
    __name(errorSubclass, "errorSubclass");
  }
});

// node_modules/fast-json-stable-stringify/index.js
var require_fast_json_stable_stringify = __commonJS({
  "node_modules/fast-json-stable-stringify/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = function(data, opts) {
      if (!opts) opts = {};
      if (typeof opts === "function") opts = { cmp: opts };
      var cycles = typeof opts.cycles === "boolean" ? opts.cycles : false;
      var cmp = opts.cmp && /* @__PURE__ */ function(f) {
        return function(node) {
          return function(a, b) {
            var aobj = { key: a, value: node[a] };
            var bobj = { key: b, value: node[b] };
            return f(aobj, bobj);
          };
        };
      }(opts.cmp);
      var seen = [];
      return (/* @__PURE__ */ __name(function stringify5(node) {
        if (node && node.toJSON && typeof node.toJSON === "function") {
          node = node.toJSON();
        }
        if (node === void 0) return;
        if (typeof node == "number") return isFinite(node) ? "" + node : "null";
        if (typeof node !== "object") return JSON.stringify(node);
        var i, out;
        if (Array.isArray(node)) {
          out = "[";
          for (i = 0; i < node.length; i++) {
            if (i) out += ",";
            out += stringify5(node[i]) || "null";
          }
          return out + "]";
        }
        if (node === null) return "null";
        if (seen.indexOf(node) !== -1) {
          if (cycles) return JSON.stringify("__cycle__");
          throw new TypeError("Converting circular structure to JSON");
        }
        var seenIndex = seen.push(node) - 1;
        var keys = Object.keys(node).sort(cmp && cmp(node));
        out = "";
        for (i = 0; i < keys.length; i++) {
          var key = keys[i];
          var value = stringify5(node[key]);
          if (!value) continue;
          if (out) out += ",";
          out += JSON.stringify(key) + ":" + value;
        }
        seen.splice(seenIndex, 1);
        return "{" + out + "}";
      }, "stringify"))(data);
    };
  }
});

// node_modules/ajv/lib/dotjs/validate.js
var require_validate3 = __commonJS({
  "node_modules/ajv/lib/dotjs/validate.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_validate(it, $keyword, $ruleType) {
      var out = "";
      var $async = it.schema.$async === true, $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, "$ref"), $id = it.self._getId(it.schema);
      if (it.opts.strictKeywords) {
        var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords);
        if ($unknownKwd) {
          var $keywordsMsg = "unknown keyword: " + $unknownKwd;
          if (it.opts.strictKeywords === "log") it.logger.warn($keywordsMsg);
          else throw new Error($keywordsMsg);
        }
      }
      if (it.isTop) {
        out += " var validate = ";
        if ($async) {
          it.async = true;
          out += "async ";
        }
        out += "function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ";
        if ($id && (it.opts.sourceCode || it.opts.processCode)) {
          out += " " + ("/*# sourceURL=" + $id + " */") + " ";
        }
      }
      if (typeof it.schema == "boolean" || !($refKeywords || it.schema.$ref)) {
        var $keyword = "false schema";
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $errorKeyword;
        var $data = "data" + ($dataLvl || "");
        var $valid = "valid" + $lvl;
        if (it.schema === false) {
          if (it.isTop) {
            $breakOnError = true;
          } else {
            out += " var " + $valid + " = false; ";
          }
          var $$outStack = $$outStack || [];
          $$outStack.push(out);
          out = "";
          if (it.createErrors !== false) {
            out += " { keyword: '" + ($errorKeyword || "false schema") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} ";
            if (it.opts.messages !== false) {
              out += " , message: 'boolean schema is false' ";
            }
            if (it.opts.verbose) {
              out += " , schema: false , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
            }
            out += " } ";
          } else {
            out += " {} ";
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it.compositeRule && $breakOnError) {
            if (it.async) {
              out += " throw new ValidationError([" + __err + "]); ";
            } else {
              out += " validate.errors = [" + __err + "]; return false; ";
            }
          } else {
            out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
          }
        } else {
          if (it.isTop) {
            if ($async) {
              out += " return data; ";
            } else {
              out += " validate.errors = null; return true; ";
            }
          } else {
            out += " var " + $valid + " = true; ";
          }
        }
        if (it.isTop) {
          out += " }; return validate; ";
        }
        return out;
      }
      if (it.isTop) {
        var $top = it.isTop, $lvl = it.level = 0, $dataLvl = it.dataLevel = 0, $data = "data";
        it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
        it.baseId = it.baseId || it.rootId;
        delete it.isTop;
        it.dataPathArr = [""];
        if (it.schema.default !== void 0 && it.opts.useDefaults && it.opts.strictDefaults) {
          var $defaultMsg = "default is ignored in the schema root";
          if (it.opts.strictDefaults === "log") it.logger.warn($defaultMsg);
          else throw new Error($defaultMsg);
        }
        out += " var vErrors = null; ";
        out += " var errors = 0;     ";
        out += " if (rootData === undefined) rootData = data; ";
      } else {
        var $lvl = it.level, $dataLvl = it.dataLevel, $data = "data" + ($dataLvl || "");
        if ($id) it.baseId = it.resolve.url(it.baseId, $id);
        if ($async && !it.async) throw new Error("async schema in sync schema");
        out += " var errs_" + $lvl + " = errors;";
      }
      var $valid = "valid" + $lvl, $breakOnError = !it.opts.allErrors, $closingBraces1 = "", $closingBraces2 = "";
      var $errorKeyword;
      var $typeSchema = it.schema.type, $typeIsArray = Array.isArray($typeSchema);
      if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
        if ($typeIsArray) {
          if ($typeSchema.indexOf("null") == -1) $typeSchema = $typeSchema.concat("null");
        } else if ($typeSchema != "null") {
          $typeSchema = [$typeSchema, "null"];
          $typeIsArray = true;
        }
      }
      if ($typeIsArray && $typeSchema.length == 1) {
        $typeSchema = $typeSchema[0];
        $typeIsArray = false;
      }
      if (it.schema.$ref && $refKeywords) {
        if (it.opts.extendRefs == "fail") {
          throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)');
        } else if (it.opts.extendRefs !== true) {
          $refKeywords = false;
          it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
        }
      }
      if (it.schema.$comment && it.opts.$comment) {
        out += " " + it.RULES.all.$comment.code(it, "$comment");
      }
      if ($typeSchema) {
        if (it.opts.coerceTypes) {
          var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
        }
        var $rulesGroup = it.RULES.types[$typeSchema];
        if ($coerceToTypes || $typeIsArray || $rulesGroup === true || $rulesGroup && !$shouldUseGroup($rulesGroup)) {
          var $schemaPath = it.schemaPath + ".type", $errSchemaPath = it.errSchemaPath + "/type";
          var $schemaPath = it.schemaPath + ".type", $errSchemaPath = it.errSchemaPath + "/type", $method = $typeIsArray ? "checkDataTypes" : "checkDataType";
          out += " if (" + it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true) + ") { ";
          if ($coerceToTypes) {
            var $dataType = "dataType" + $lvl, $coerced = "coerced" + $lvl;
            out += " var " + $dataType + " = typeof " + $data + "; var " + $coerced + " = undefined; ";
            if (it.opts.coerceTypes == "array") {
              out += " if (" + $dataType + " == 'object' && Array.isArray(" + $data + ") && " + $data + ".length == 1) { " + $data + " = " + $data + "[0]; " + $dataType + " = typeof " + $data + "; if (" + it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers) + ") " + $coerced + " = " + $data + "; } ";
            }
            out += " if (" + $coerced + " !== undefined) ; ";
            var arr1 = $coerceToTypes;
            if (arr1) {
              var $type, $i = -1, l1 = arr1.length - 1;
              while ($i < l1) {
                $type = arr1[$i += 1];
                if ($type == "string") {
                  out += " else if (" + $dataType + " == 'number' || " + $dataType + " == 'boolean') " + $coerced + " = '' + " + $data + "; else if (" + $data + " === null) " + $coerced + " = ''; ";
                } else if ($type == "number" || $type == "integer") {
                  out += " else if (" + $dataType + " == 'boolean' || " + $data + " === null || (" + $dataType + " == 'string' && " + $data + " && " + $data + " == +" + $data + " ";
                  if ($type == "integer") {
                    out += " && !(" + $data + " % 1)";
                  }
                  out += ")) " + $coerced + " = +" + $data + "; ";
                } else if ($type == "boolean") {
                  out += " else if (" + $data + " === 'false' || " + $data + " === 0 || " + $data + " === null) " + $coerced + " = false; else if (" + $data + " === 'true' || " + $data + " === 1) " + $coerced + " = true; ";
                } else if ($type == "null") {
                  out += " else if (" + $data + " === '' || " + $data + " === 0 || " + $data + " === false) " + $coerced + " = null; ";
                } else if (it.opts.coerceTypes == "array" && $type == "array") {
                  out += " else if (" + $dataType + " == 'string' || " + $dataType + " == 'number' || " + $dataType + " == 'boolean' || " + $data + " == null) " + $coerced + " = [" + $data + "]; ";
                }
              }
            }
            out += " else {   ";
            var $$outStack = $$outStack || [];
            $$outStack.push(out);
            out = "";
            if (it.createErrors !== false) {
              out += " { keyword: '" + ($errorKeyword || "type") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { type: '";
              if ($typeIsArray) {
                out += "" + $typeSchema.join(",");
              } else {
                out += "" + $typeSchema;
              }
              out += "' } ";
              if (it.opts.messages !== false) {
                out += " , message: 'should be ";
                if ($typeIsArray) {
                  out += "" + $typeSchema.join(",");
                } else {
                  out += "" + $typeSchema;
                }
                out += "' ";
              }
              if (it.opts.verbose) {
                out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
              }
              out += " } ";
            } else {
              out += " {} ";
            }
            var __err = out;
            out = $$outStack.pop();
            if (!it.compositeRule && $breakOnError) {
              if (it.async) {
                out += " throw new ValidationError([" + __err + "]); ";
              } else {
                out += " validate.errors = [" + __err + "]; return false; ";
              }
            } else {
              out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
            }
            out += " } if (" + $coerced + " !== undefined) {  ";
            var $parentData = $dataLvl ? "data" + ($dataLvl - 1 || "") : "parentData", $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : "parentDataProperty";
            out += " " + $data + " = " + $coerced + "; ";
            if (!$dataLvl) {
              out += "if (" + $parentData + " !== undefined)";
            }
            out += " " + $parentData + "[" + $parentDataProperty + "] = " + $coerced + "; } ";
          } else {
            var $$outStack = $$outStack || [];
            $$outStack.push(out);
            out = "";
            if (it.createErrors !== false) {
              out += " { keyword: '" + ($errorKeyword || "type") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { type: '";
              if ($typeIsArray) {
                out += "" + $typeSchema.join(",");
              } else {
                out += "" + $typeSchema;
              }
              out += "' } ";
              if (it.opts.messages !== false) {
                out += " , message: 'should be ";
                if ($typeIsArray) {
                  out += "" + $typeSchema.join(",");
                } else {
                  out += "" + $typeSchema;
                }
                out += "' ";
              }
              if (it.opts.verbose) {
                out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
              }
              out += " } ";
            } else {
              out += " {} ";
            }
            var __err = out;
            out = $$outStack.pop();
            if (!it.compositeRule && $breakOnError) {
              if (it.async) {
                out += " throw new ValidationError([" + __err + "]); ";
              } else {
                out += " validate.errors = [" + __err + "]; return false; ";
              }
            } else {
              out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
            }
          }
          out += " } ";
        }
      }
      if (it.schema.$ref && !$refKeywords) {
        out += " " + it.RULES.all.$ref.code(it, "$ref") + " ";
        if ($breakOnError) {
          out += " } if (errors === ";
          if ($top) {
            out += "0";
          } else {
            out += "errs_" + $lvl;
          }
          out += ") { ";
          $closingBraces2 += "}";
        }
      } else {
        var arr2 = it.RULES;
        if (arr2) {
          var $rulesGroup, i2 = -1, l2 = arr2.length - 1;
          while (i2 < l2) {
            $rulesGroup = arr2[i2 += 1];
            if ($shouldUseGroup($rulesGroup)) {
              if ($rulesGroup.type) {
                out += " if (" + it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers) + ") { ";
              }
              if (it.opts.useDefaults) {
                if ($rulesGroup.type == "object" && it.schema.properties) {
                  var $schema = it.schema.properties, $schemaKeys = Object.keys($schema);
                  var arr3 = $schemaKeys;
                  if (arr3) {
                    var $propertyKey, i3 = -1, l3 = arr3.length - 1;
                    while (i3 < l3) {
                      $propertyKey = arr3[i3 += 1];
                      var $sch = $schema[$propertyKey];
                      if ($sch.default !== void 0) {
                        var $passData = $data + it.util.getProperty($propertyKey);
                        if (it.compositeRule) {
                          if (it.opts.strictDefaults) {
                            var $defaultMsg = "default is ignored for: " + $passData;
                            if (it.opts.strictDefaults === "log") it.logger.warn($defaultMsg);
                            else throw new Error($defaultMsg);
                          }
                        } else {
                          out += " if (" + $passData + " === undefined ";
                          if (it.opts.useDefaults == "empty") {
                            out += " || " + $passData + " === null || " + $passData + " === '' ";
                          }
                          out += " ) " + $passData + " = ";
                          if (it.opts.useDefaults == "shared") {
                            out += " " + it.useDefault($sch.default) + " ";
                          } else {
                            out += " " + JSON.stringify($sch.default) + " ";
                          }
                          out += "; ";
                        }
                      }
                    }
                  }
                } else if ($rulesGroup.type == "array" && Array.isArray(it.schema.items)) {
                  var arr4 = it.schema.items;
                  if (arr4) {
                    var $sch, $i = -1, l4 = arr4.length - 1;
                    while ($i < l4) {
                      $sch = arr4[$i += 1];
                      if ($sch.default !== void 0) {
                        var $passData = $data + "[" + $i + "]";
                        if (it.compositeRule) {
                          if (it.opts.strictDefaults) {
                            var $defaultMsg = "default is ignored for: " + $passData;
                            if (it.opts.strictDefaults === "log") it.logger.warn($defaultMsg);
                            else throw new Error($defaultMsg);
                          }
                        } else {
                          out += " if (" + $passData + " === undefined ";
                          if (it.opts.useDefaults == "empty") {
                            out += " || " + $passData + " === null || " + $passData + " === '' ";
                          }
                          out += " ) " + $passData + " = ";
                          if (it.opts.useDefaults == "shared") {
                            out += " " + it.useDefault($sch.default) + " ";
                          } else {
                            out += " " + JSON.stringify($sch.default) + " ";
                          }
                          out += "; ";
                        }
                      }
                    }
                  }
                }
              }
              var arr5 = $rulesGroup.rules;
              if (arr5) {
                var $rule, i5 = -1, l5 = arr5.length - 1;
                while (i5 < l5) {
                  $rule = arr5[i5 += 1];
                  if ($shouldUseRule($rule)) {
                    var $code = $rule.code(it, $rule.keyword, $rulesGroup.type);
                    if ($code) {
                      out += " " + $code + " ";
                      if ($breakOnError) {
                        $closingBraces1 += "}";
                      }
                    }
                  }
                }
              }
              if ($breakOnError) {
                out += " " + $closingBraces1 + " ";
                $closingBraces1 = "";
              }
              if ($rulesGroup.type) {
                out += " } ";
                if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) {
                  out += " else { ";
                  var $schemaPath = it.schemaPath + ".type", $errSchemaPath = it.errSchemaPath + "/type";
                  var $$outStack = $$outStack || [];
                  $$outStack.push(out);
                  out = "";
                  if (it.createErrors !== false) {
                    out += " { keyword: '" + ($errorKeyword || "type") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { type: '";
                    if ($typeIsArray) {
                      out += "" + $typeSchema.join(",");
                    } else {
                      out += "" + $typeSchema;
                    }
                    out += "' } ";
                    if (it.opts.messages !== false) {
                      out += " , message: 'should be ";
                      if ($typeIsArray) {
                        out += "" + $typeSchema.join(",");
                      } else {
                        out += "" + $typeSchema;
                      }
                      out += "' ";
                    }
                    if (it.opts.verbose) {
                      out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
                    }
                    out += " } ";
                  } else {
                    out += " {} ";
                  }
                  var __err = out;
                  out = $$outStack.pop();
                  if (!it.compositeRule && $breakOnError) {
                    if (it.async) {
                      out += " throw new ValidationError([" + __err + "]); ";
                    } else {
                      out += " validate.errors = [" + __err + "]; return false; ";
                    }
                  } else {
                    out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
                  }
                  out += " } ";
                }
              }
              if ($breakOnError) {
                out += " if (errors === ";
                if ($top) {
                  out += "0";
                } else {
                  out += "errs_" + $lvl;
                }
                out += ") { ";
                $closingBraces2 += "}";
              }
            }
          }
        }
      }
      if ($breakOnError) {
        out += " " + $closingBraces2 + " ";
      }
      if ($top) {
        if ($async) {
          out += " if (errors === 0) return data;           ";
          out += " else throw new ValidationError(vErrors); ";
        } else {
          out += " validate.errors = vErrors; ";
          out += " return errors === 0;       ";
        }
        out += " }; return validate;";
      } else {
        out += " var " + $valid + " = errors === errs_" + $lvl + ";";
      }
      function $shouldUseGroup($rulesGroup2) {
        var rules = $rulesGroup2.rules;
        for (var i = 0; i < rules.length; i++)
          if ($shouldUseRule(rules[i])) return true;
      }
      __name($shouldUseGroup, "$shouldUseGroup");
      function $shouldUseRule($rule2) {
        return it.schema[$rule2.keyword] !== void 0 || $rule2.implements && $ruleImplementsSomeKeyword($rule2);
      }
      __name($shouldUseRule, "$shouldUseRule");
      function $ruleImplementsSomeKeyword($rule2) {
        var impl = $rule2.implements;
        for (var i = 0; i < impl.length; i++)
          if (it.schema[impl[i]] !== void 0) return true;
      }
      __name($ruleImplementsSomeKeyword, "$ruleImplementsSomeKeyword");
      return out;
    }, "generate_validate");
  }
});

// node_modules/ajv/lib/compile/index.js
var require_compile3 = __commonJS({
  "node_modules/ajv/lib/compile/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var resolve24 = require_resolve4();
    var util4 = require_util15();
    var errorClasses = require_error_classes();
    var stableStringify = require_fast_json_stable_stringify();
    var validateGenerator = require_validate3();
    var ucs2length = util4.ucs2length;
    var equal = require_fast_deep_equal();
    var ValidationError = errorClasses.Validation;
    module2.exports = compile2;
    function compile2(schema, root, localRefs, baseId) {
      var self2 = this, opts = this._opts, refVal = [void 0], refs = {}, patterns = [], patternsHash = {}, defaults3 = [], defaultsHash = {}, customRules = [];
      root = root || { schema, refVal, refs };
      var c3 = checkCompiling.call(this, schema, root, baseId);
      var compilation = this._compilations[c3.index];
      if (c3.compiling) return compilation.callValidate = callValidate;
      var formats = this._formats;
      var RULES = this.RULES;
      try {
        var v = localCompile(schema, root, localRefs, baseId);
        compilation.validate = v;
        var cv = compilation.callValidate;
        if (cv) {
          cv.schema = v.schema;
          cv.errors = null;
          cv.refs = v.refs;
          cv.refVal = v.refVal;
          cv.root = v.root;
          cv.$async = v.$async;
          if (opts.sourceCode) cv.source = v.source;
        }
        return v;
      } finally {
        endCompiling.call(this, schema, root, baseId);
      }
      function callValidate() {
        var validate4 = compilation.validate;
        var result = validate4.apply(this, arguments);
        callValidate.errors = validate4.errors;
        return result;
      }
      __name(callValidate, "callValidate");
      function localCompile(_schema, _root, localRefs2, baseId2) {
        var isRoot = !_root || _root && _root.schema == _schema;
        if (_root.schema != root.schema)
          return compile2.call(self2, _schema, _root, localRefs2, baseId2);
        var $async = _schema.$async === true;
        var sourceCode = validateGenerator({
          isTop: true,
          schema: _schema,
          isRoot,
          baseId: baseId2,
          root: _root,
          schemaPath: "",
          errSchemaPath: "#",
          errorPath: '""',
          MissingRefError: errorClasses.MissingRef,
          RULES,
          validate: validateGenerator,
          util: util4,
          resolve: resolve24,
          resolveRef,
          usePattern,
          useDefault,
          useCustomRule,
          opts,
          formats,
          logger: self2.logger,
          self: self2
        });
        sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + vars(defaults3, defaultCode) + vars(customRules, customRuleCode) + sourceCode;
        if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema);
        var validate4;
        try {
          var makeValidate = new Function(
            "self",
            "RULES",
            "formats",
            "root",
            "refVal",
            "defaults",
            "customRules",
            "equal",
            "ucs2length",
            "ValidationError",
            sourceCode
          );
          validate4 = makeValidate(
            self2,
            RULES,
            formats,
            root,
            refVal,
            defaults3,
            customRules,
            equal,
            ucs2length,
            ValidationError
          );
          refVal[0] = validate4;
        } catch (e2) {
          self2.logger.error("Error compiling schema, function code:", sourceCode);
          throw e2;
        }
        validate4.schema = _schema;
        validate4.errors = null;
        validate4.refs = refs;
        validate4.refVal = refVal;
        validate4.root = isRoot ? validate4 : _root;
        if ($async) validate4.$async = true;
        if (opts.sourceCode === true) {
          validate4.source = {
            code: sourceCode,
            patterns,
            defaults: defaults3
          };
        }
        return validate4;
      }
      __name(localCompile, "localCompile");
      function resolveRef(baseId2, ref, isRoot) {
        ref = resolve24.url(baseId2, ref);
        var refIndex = refs[ref];
        var _refVal, refCode;
        if (refIndex !== void 0) {
          _refVal = refVal[refIndex];
          refCode = "refVal[" + refIndex + "]";
          return resolvedRef(_refVal, refCode);
        }
        if (!isRoot && root.refs) {
          var rootRefId = root.refs[ref];
          if (rootRefId !== void 0) {
            _refVal = root.refVal[rootRefId];
            refCode = addLocalRef(ref, _refVal);
            return resolvedRef(_refVal, refCode);
          }
        }
        refCode = addLocalRef(ref);
        var v2 = resolve24.call(self2, localCompile, root, ref);
        if (v2 === void 0) {
          var localSchema = localRefs && localRefs[ref];
          if (localSchema) {
            v2 = resolve24.inlineRef(localSchema, opts.inlineRefs) ? localSchema : compile2.call(self2, localSchema, root, localRefs, baseId2);
          }
        }
        if (v2 === void 0) {
          removeLocalRef(ref);
        } else {
          replaceLocalRef(ref, v2);
          return resolvedRef(v2, refCode);
        }
      }
      __name(resolveRef, "resolveRef");
      function addLocalRef(ref, v2) {
        var refId = refVal.length;
        refVal[refId] = v2;
        refs[ref] = refId;
        return "refVal" + refId;
      }
      __name(addLocalRef, "addLocalRef");
      function removeLocalRef(ref) {
        delete refs[ref];
      }
      __name(removeLocalRef, "removeLocalRef");
      function replaceLocalRef(ref, v2) {
        var refId = refs[ref];
        refVal[refId] = v2;
      }
      __name(replaceLocalRef, "replaceLocalRef");
      function resolvedRef(refVal2, code2) {
        return typeof refVal2 == "object" || typeof refVal2 == "boolean" ? { code: code2, schema: refVal2, inline: true } : { code: code2, $async: refVal2 && !!refVal2.$async };
      }
      __name(resolvedRef, "resolvedRef");
      function usePattern(regexStr) {
        var index = patternsHash[regexStr];
        if (index === void 0) {
          index = patternsHash[regexStr] = patterns.length;
          patterns[index] = regexStr;
        }
        return "pattern" + index;
      }
      __name(usePattern, "usePattern");
      function useDefault(value) {
        switch (typeof value) {
          case "boolean":
          case "number":
            return "" + value;
          case "string":
            return util4.toQuotedString(value);
          case "object":
            if (value === null) return "null";
            var valueStr = stableStringify(value);
            var index = defaultsHash[valueStr];
            if (index === void 0) {
              index = defaultsHash[valueStr] = defaults3.length;
              defaults3[index] = value;
            }
            return "default" + index;
        }
      }
      __name(useDefault, "useDefault");
      function useCustomRule(rule, schema2, parentSchema, it) {
        if (self2._opts.validateSchema !== false) {
          var deps = rule.definition.dependencies;
          if (deps && !deps.every(function(keyword) {
            return Object.prototype.hasOwnProperty.call(parentSchema, keyword);
          }))
            throw new Error("parent schema must have all required keywords: " + deps.join(","));
          var validateSchema = rule.definition.validateSchema;
          if (validateSchema) {
            var valid = validateSchema(schema2);
            if (!valid) {
              var message = "keyword schema is invalid: " + self2.errorsText(validateSchema.errors);
              if (self2._opts.validateSchema == "log") self2.logger.error(message);
              else throw new Error(message);
            }
          }
        }
        var compile3 = rule.definition.compile, inline2 = rule.definition.inline, macro = rule.definition.macro;
        var validate4;
        if (compile3) {
          validate4 = compile3.call(self2, schema2, parentSchema, it);
        } else if (macro) {
          validate4 = macro.call(self2, schema2, parentSchema, it);
          if (opts.validateSchema !== false) self2.validateSchema(validate4, true);
        } else if (inline2) {
          validate4 = inline2.call(self2, it, rule.keyword, schema2, parentSchema);
        } else {
          validate4 = rule.definition.validate;
          if (!validate4) return;
        }
        if (validate4 === void 0)
          throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
        var index = customRules.length;
        customRules[index] = validate4;
        return {
          code: "customRule" + index,
          validate: validate4
        };
      }
      __name(useCustomRule, "useCustomRule");
    }
    __name(compile2, "compile");
    function checkCompiling(schema, root, baseId) {
      var index = compIndex.call(this, schema, root, baseId);
      if (index >= 0) return { index, compiling: true };
      index = this._compilations.length;
      this._compilations[index] = {
        schema,
        root,
        baseId
      };
      return { index, compiling: false };
    }
    __name(checkCompiling, "checkCompiling");
    function endCompiling(schema, root, baseId) {
      var i = compIndex.call(this, schema, root, baseId);
      if (i >= 0) this._compilations.splice(i, 1);
    }
    __name(endCompiling, "endCompiling");
    function compIndex(schema, root, baseId) {
      for (var i = 0; i < this._compilations.length; i++) {
        var c3 = this._compilations[i];
        if (c3.schema == schema && c3.root == root && c3.baseId == baseId) return i;
      }
      return -1;
    }
    __name(compIndex, "compIndex");
    function patternCode(i, patterns) {
      return "var pattern" + i + " = new RegExp(" + util4.toQuotedString(patterns[i]) + ");";
    }
    __name(patternCode, "patternCode");
    function defaultCode(i) {
      return "var default" + i + " = defaults[" + i + "];";
    }
    __name(defaultCode, "defaultCode");
    function refValCode(i, refVal) {
      return refVal[i] === void 0 ? "" : "var refVal" + i + " = refVal[" + i + "];";
    }
    __name(refValCode, "refValCode");
    function customRuleCode(i) {
      return "var customRule" + i + " = customRules[" + i + "];";
    }
    __name(customRuleCode, "customRuleCode");
    function vars(arr, statement) {
      if (!arr.length) return "";
      var code2 = "";
      for (var i = 0; i < arr.length; i++)
        code2 += statement(i, arr);
      return code2;
    }
    __name(vars, "vars");
  }
});

// node_modules/ajv/lib/cache.js
var require_cache4 = __commonJS({
  "node_modules/ajv/lib/cache.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Cache = module2.exports = /* @__PURE__ */ __name(function Cache2() {
      this._cache = {};
    }, "Cache");
    Cache.prototype.put = /* @__PURE__ */ __name(function Cache_put(key, value) {
      this._cache[key] = value;
    }, "Cache_put");
    Cache.prototype.get = /* @__PURE__ */ __name(function Cache_get(key) {
      return this._cache[key];
    }, "Cache_get");
    Cache.prototype.del = /* @__PURE__ */ __name(function Cache_del(key) {
      delete this._cache[key];
    }, "Cache_del");
    Cache.prototype.clear = /* @__PURE__ */ __name(function Cache_clear() {
      this._cache = {};
    }, "Cache_clear");
  }
});

// node_modules/ajv/lib/compile/formats.js
var require_formats2 = __commonJS({
  "node_modules/ajv/lib/compile/formats.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var util4 = require_util15();
    var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
    var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;
    var 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;
    var 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;
    var URIREF = /^(?:[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;
    var URITEMPLATE = /^(?:(?:[^\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;
    var URL6 = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;
    var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
    var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
    var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
    var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
    module2.exports = formats;
    function formats(mode) {
      mode = mode == "full" ? "full" : "fast";
      return util4.copy(formats[mode]);
    }
    __name(formats, "formats");
    formats.fast = {
      // date: http://tools.ietf.org/html/rfc3339#section-5.6
      date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
      // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
      time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,
      "date-time": /^\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,
      // 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,
      "uri-template": URITEMPLATE,
      url: URL6,
      // 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 'willful 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,
      hostname: HOSTNAME,
      // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
      ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
      // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
      ipv6: /^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,
      regex: regex3,
      // uuid: http://tools.ietf.org/html/rfc4122
      uuid: UUID,
      // JSON-pointer: https://tools.ietf.org/html/rfc6901
      // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
      "json-pointer": JSON_POINTER,
      "json-pointer-uri-fragment": JSON_POINTER_URI_FRAGMENT,
      // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
      "relative-json-pointer": RELATIVE_JSON_POINTER
    };
    formats.full = {
      date,
      time,
      "date-time": date_time,
      uri,
      "uri-reference": URIREF,
      "uri-template": URITEMPLATE,
      url: URL6,
      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: HOSTNAME,
      ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
      ipv6: /^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,
      regex: regex3,
      uuid: UUID,
      "json-pointer": JSON_POINTER,
      "json-pointer-uri-fragment": JSON_POINTER_URI_FRAGMENT,
      "relative-json-pointer": RELATIVE_JSON_POINTER
    };
    function isLeapYear(year) {
      return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    }
    __name(isLeapYear, "isLeapYear");
    function date(str2) {
      var matches = str2.match(DATE);
      if (!matches) return false;
      var year = +matches[1];
      var month = +matches[2];
      var day = +matches[3];
      return month >= 1 && month <= 12 && day >= 1 && day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]);
    }
    __name(date, "date");
    function time(str2, full) {
      var matches = str2.match(TIME);
      if (!matches) return false;
      var hour = matches[1];
      var minute = matches[2];
      var second = matches[3];
      var timeZone = matches[5];
      return (hour <= 23 && minute <= 59 && second <= 59 || hour == 23 && minute == 59 && second == 60) && (!full || timeZone);
    }
    __name(time, "time");
    var DATE_TIME_SEPARATOR = /t|\s/i;
    function date_time(str2) {
      var dateTime = str2.split(DATE_TIME_SEPARATOR);
      return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);
    }
    __name(date_time, "date_time");
    var NOT_URI_FRAGMENT = /\/|:/;
    function uri(str2) {
      return NOT_URI_FRAGMENT.test(str2) && URI.test(str2);
    }
    __name(uri, "uri");
    var Z_ANCHOR = /[^\\]\\Z/;
    function regex3(str2) {
      if (Z_ANCHOR.test(str2)) return false;
      try {
        new RegExp(str2);
        return true;
      } catch (e2) {
        return false;
      }
    }
    __name(regex3, "regex");
  }
});

// node_modules/ajv/lib/dotjs/ref.js
var require_ref3 = __commonJS({
  "node_modules/ajv/lib/dotjs/ref.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_ref(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $data = "data" + ($dataLvl || "");
      var $valid = "valid" + $lvl;
      var $async, $refCode;
      if ($schema == "#" || $schema == "#/") {
        if (it.isRoot) {
          $async = it.async;
          $refCode = "validate";
        } else {
          $async = it.root.schema.$async === true;
          $refCode = "root.refVal[0]";
        }
      } else {
        var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot);
        if ($refVal === void 0) {
          var $message = it.MissingRefError.message(it.baseId, $schema);
          if (it.opts.missingRefs == "fail") {
            it.logger.error($message);
            var $$outStack = $$outStack || [];
            $$outStack.push(out);
            out = "";
            if (it.createErrors !== false) {
              out += " { keyword: '$ref' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { ref: '" + it.util.escapeQuotes($schema) + "' } ";
              if (it.opts.messages !== false) {
                out += " , message: 'can\\'t resolve reference " + it.util.escapeQuotes($schema) + "' ";
              }
              if (it.opts.verbose) {
                out += " , schema: " + it.util.toQuotedString($schema) + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
              }
              out += " } ";
            } else {
              out += " {} ";
            }
            var __err = out;
            out = $$outStack.pop();
            if (!it.compositeRule && $breakOnError) {
              if (it.async) {
                out += " throw new ValidationError([" + __err + "]); ";
              } else {
                out += " validate.errors = [" + __err + "]; return false; ";
              }
            } else {
              out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
            }
            if ($breakOnError) {
              out += " if (false) { ";
            }
          } else if (it.opts.missingRefs == "ignore") {
            it.logger.warn($message);
            if ($breakOnError) {
              out += " if (true) { ";
            }
          } else {
            throw new it.MissingRefError(it.baseId, $schema, $message);
          }
        } else if ($refVal.inline) {
          var $it = it.util.copy(it);
          $it.level++;
          var $nextValid = "valid" + $it.level;
          $it.schema = $refVal.schema;
          $it.schemaPath = "";
          $it.errSchemaPath = $schema;
          var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code);
          out += " " + $code + " ";
          if ($breakOnError) {
            out += " if (" + $nextValid + ") { ";
          }
        } else {
          $async = $refVal.$async === true || it.async && $refVal.$async !== false;
          $refCode = $refVal.code;
        }
      }
      if ($refCode) {
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = "";
        if (it.opts.passContext) {
          out += " " + $refCode + ".call(this, ";
        } else {
          out += " " + $refCode + "( ";
        }
        out += " " + $data + ", (dataPath || '')";
        if (it.errorPath != '""') {
          out += " + " + it.errorPath;
        }
        var $parentData = $dataLvl ? "data" + ($dataLvl - 1 || "") : "parentData", $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : "parentDataProperty";
        out += " , " + $parentData + " , " + $parentDataProperty + ", rootData)  ";
        var __callValidate = out;
        out = $$outStack.pop();
        if ($async) {
          if (!it.async) throw new Error("async schema referenced by sync schema");
          if ($breakOnError) {
            out += " var " + $valid + "; ";
          }
          out += " try { await " + __callValidate + "; ";
          if ($breakOnError) {
            out += " " + $valid + " = true; ";
          }
          out += " } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ";
          if ($breakOnError) {
            out += " " + $valid + " = false; ";
          }
          out += " } ";
          if ($breakOnError) {
            out += " if (" + $valid + ") { ";
          }
        } else {
          out += " if (!" + __callValidate + ") { if (vErrors === null) vErrors = " + $refCode + ".errors; else vErrors = vErrors.concat(" + $refCode + ".errors); errors = vErrors.length; } ";
          if ($breakOnError) {
            out += " else { ";
          }
        }
      }
      return out;
    }, "generate_ref");
  }
});

// node_modules/ajv/lib/dotjs/allOf.js
var require_allOf3 = __commonJS({
  "node_modules/ajv/lib/dotjs/allOf.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_allOf(it, $keyword, $ruleType) {
      var out = " ";
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $it = it.util.copy(it);
      var $closingBraces = "";
      $it.level++;
      var $nextValid = "valid" + $it.level;
      var $currentBaseId = $it.baseId, $allSchemasEmpty = true;
      var arr1 = $schema;
      if (arr1) {
        var $sch, $i = -1, l1 = arr1.length - 1;
        while ($i < l1) {
          $sch = arr1[$i += 1];
          if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) {
            $allSchemasEmpty = false;
            $it.schema = $sch;
            $it.schemaPath = $schemaPath + "[" + $i + "]";
            $it.errSchemaPath = $errSchemaPath + "/" + $i;
            out += "  " + it.validate($it) + " ";
            $it.baseId = $currentBaseId;
            if ($breakOnError) {
              out += " if (" + $nextValid + ") { ";
              $closingBraces += "}";
            }
          }
        }
      }
      if ($breakOnError) {
        if ($allSchemasEmpty) {
          out += " if (true) { ";
        } else {
          out += " " + $closingBraces.slice(0, -1) + " ";
        }
      }
      return out;
    }, "generate_allOf");
  }
});

// node_modules/ajv/lib/dotjs/anyOf.js
var require_anyOf3 = __commonJS({
  "node_modules/ajv/lib/dotjs/anyOf.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_anyOf(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $data = "data" + ($dataLvl || "");
      var $valid = "valid" + $lvl;
      var $errs = "errs__" + $lvl;
      var $it = it.util.copy(it);
      var $closingBraces = "";
      $it.level++;
      var $nextValid = "valid" + $it.level;
      var $noEmptySchema = $schema.every(function($sch2) {
        return it.opts.strictKeywords ? typeof $sch2 == "object" && Object.keys($sch2).length > 0 || $sch2 === false : it.util.schemaHasRules($sch2, it.RULES.all);
      });
      if ($noEmptySchema) {
        var $currentBaseId = $it.baseId;
        out += " var " + $errs + " = errors; var " + $valid + " = false;  ";
        var $wasComposite = it.compositeRule;
        it.compositeRule = $it.compositeRule = true;
        var arr1 = $schema;
        if (arr1) {
          var $sch, $i = -1, l1 = arr1.length - 1;
          while ($i < l1) {
            $sch = arr1[$i += 1];
            $it.schema = $sch;
            $it.schemaPath = $schemaPath + "[" + $i + "]";
            $it.errSchemaPath = $errSchemaPath + "/" + $i;
            out += "  " + it.validate($it) + " ";
            $it.baseId = $currentBaseId;
            out += " " + $valid + " = " + $valid + " || " + $nextValid + "; if (!" + $valid + ") { ";
            $closingBraces += "}";
          }
        }
        it.compositeRule = $it.compositeRule = $wasComposite;
        out += " " + $closingBraces + " if (!" + $valid + ") {   var err =   ";
        if (it.createErrors !== false) {
          out += " { keyword: 'anyOf' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} ";
          if (it.opts.messages !== false) {
            out += " , message: 'should match some schema in anyOf' ";
          }
          if (it.opts.verbose) {
            out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
        if (!it.compositeRule && $breakOnError) {
          if (it.async) {
            out += " throw new ValidationError(vErrors); ";
          } else {
            out += " validate.errors = vErrors; return false; ";
          }
        }
        out += " } else {  errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; } ";
        if (it.opts.allErrors) {
          out += " } ";
        }
      } else {
        if ($breakOnError) {
          out += " if (true) { ";
        }
      }
      return out;
    }, "generate_anyOf");
  }
});

// node_modules/ajv/lib/dotjs/comment.js
var require_comment = __commonJS({
  "node_modules/ajv/lib/dotjs/comment.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_comment(it, $keyword, $ruleType) {
      var out = " ";
      var $schema = it.schema[$keyword];
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $comment = it.util.toQuotedString($schema);
      if (it.opts.$comment === true) {
        out += " console.log(" + $comment + ");";
      } else if (typeof it.opts.$comment == "function") {
        out += " self._opts.$comment(" + $comment + ", " + it.util.toQuotedString($errSchemaPath) + ", validate.root.schema);";
      }
      return out;
    }, "generate_comment");
  }
});

// node_modules/ajv/lib/dotjs/const.js
var require_const3 = __commonJS({
  "node_modules/ajv/lib/dotjs/const.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_const(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $data = "data" + ($dataLvl || "");
      var $valid = "valid" + $lvl;
      var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
      if ($isData) {
        out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; ";
        $schemaValue = "schema" + $lvl;
      } else {
        $schemaValue = $schema;
      }
      if (!$isData) {
        out += " var schema" + $lvl + " = validate.schema" + $schemaPath + ";";
      }
      out += "var " + $valid + " = equal(" + $data + ", schema" + $lvl + "); if (!" + $valid + ") {   ";
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it.createErrors !== false) {
        out += " { keyword: 'const' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { allowedValue: schema" + $lvl + " } ";
        if (it.opts.messages !== false) {
          out += " , message: 'should be equal to constant' ";
        }
        if (it.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError([" + __err + "]); ";
        } else {
          out += " validate.errors = [" + __err + "]; return false; ";
        }
      } else {
        out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      }
      out += " }";
      if ($breakOnError) {
        out += " else { ";
      }
      return out;
    }, "generate_const");
  }
});

// node_modules/ajv/lib/dotjs/contains.js
var require_contains3 = __commonJS({
  "node_modules/ajv/lib/dotjs/contains.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_contains(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $data = "data" + ($dataLvl || "");
      var $valid = "valid" + $lvl;
      var $errs = "errs__" + $lvl;
      var $it = it.util.copy(it);
      var $closingBraces = "";
      $it.level++;
      var $nextValid = "valid" + $it.level;
      var $idx = "i" + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = "data" + $dataNxt, $currentBaseId = it.baseId, $nonEmptySchema = it.opts.strictKeywords ? typeof $schema == "object" && Object.keys($schema).length > 0 || $schema === false : it.util.schemaHasRules($schema, it.RULES.all);
      out += "var " + $errs + " = errors;var " + $valid + ";";
      if ($nonEmptySchema) {
        var $wasComposite = it.compositeRule;
        it.compositeRule = $it.compositeRule = true;
        $it.schema = $schema;
        $it.schemaPath = $schemaPath;
        $it.errSchemaPath = $errSchemaPath;
        out += " var " + $nextValid + " = false; for (var " + $idx + " = 0; " + $idx + " < " + $data + ".length; " + $idx + "++) { ";
        $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
        var $passData = $data + "[" + $idx + "]";
        $it.dataPathArr[$dataNxt] = $idx;
        var $code = it.validate($it);
        $it.baseId = $currentBaseId;
        if (it.util.varOccurences($code, $nextData) < 2) {
          out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
        } else {
          out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
        }
        out += " if (" + $nextValid + ") break; }  ";
        it.compositeRule = $it.compositeRule = $wasComposite;
        out += " " + $closingBraces + " if (!" + $nextValid + ") {";
      } else {
        out += " if (" + $data + ".length == 0) {";
      }
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it.createErrors !== false) {
        out += " { keyword: 'contains' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} ";
        if (it.opts.messages !== false) {
          out += " , message: 'should contain a valid item' ";
        }
        if (it.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError([" + __err + "]); ";
        } else {
          out += " validate.errors = [" + __err + "]; return false; ";
        }
      } else {
        out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      }
      out += " } else { ";
      if ($nonEmptySchema) {
        out += "  errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; } ";
      }
      if (it.opts.allErrors) {
        out += " } ";
      }
      return out;
    }, "generate_contains");
  }
});

// node_modules/ajv/lib/dotjs/dependencies.js
var require_dependencies3 = __commonJS({
  "node_modules/ajv/lib/dotjs/dependencies.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_dependencies(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $data = "data" + ($dataLvl || "");
      var $errs = "errs__" + $lvl;
      var $it = it.util.copy(it);
      var $closingBraces = "";
      $it.level++;
      var $nextValid = "valid" + $it.level;
      var $schemaDeps = {}, $propertyDeps = {}, $ownProperties = it.opts.ownProperties;
      for ($property in $schema) {
        if ($property == "__proto__") continue;
        var $sch = $schema[$property];
        var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
        $deps[$property] = $sch;
      }
      out += "var " + $errs + " = errors;";
      var $currentErrorPath = it.errorPath;
      out += "var missing" + $lvl + ";";
      for (var $property in $propertyDeps) {
        $deps = $propertyDeps[$property];
        if ($deps.length) {
          out += " if ( " + $data + it.util.getProperty($property) + " !== undefined ";
          if ($ownProperties) {
            out += " && Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($property) + "') ";
          }
          if ($breakOnError) {
            out += " && ( ";
            var arr1 = $deps;
            if (arr1) {
              var $propertyKey, $i = -1, l1 = arr1.length - 1;
              while ($i < l1) {
                $propertyKey = arr1[$i += 1];
                if ($i) {
                  out += " || ";
                }
                var $prop = it.util.getProperty($propertyKey), $useData = $data + $prop;
                out += " ( ( " + $useData + " === undefined ";
                if ($ownProperties) {
                  out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
                }
                out += ") && (missing" + $lvl + " = " + it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) + ") ) ";
              }
            }
            out += ")) {  ";
            var $propertyPath = "missing" + $lvl, $missingProperty = "' + " + $propertyPath + " + '";
            if (it.opts._errorDataPathProperty) {
              it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + " + " + $propertyPath;
            }
            var $$outStack = $$outStack || [];
            $$outStack.push(out);
            out = "";
            if (it.createErrors !== false) {
              out += " { keyword: 'dependencies' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { property: '" + it.util.escapeQuotes($property) + "', missingProperty: '" + $missingProperty + "', depsCount: " + $deps.length + ", deps: '" + it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", ")) + "' } ";
              if (it.opts.messages !== false) {
                out += " , message: 'should have ";
                if ($deps.length == 1) {
                  out += "property " + it.util.escapeQuotes($deps[0]);
                } else {
                  out += "properties " + it.util.escapeQuotes($deps.join(", "));
                }
                out += " when property " + it.util.escapeQuotes($property) + " is present' ";
              }
              if (it.opts.verbose) {
                out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
              }
              out += " } ";
            } else {
              out += " {} ";
            }
            var __err = out;
            out = $$outStack.pop();
            if (!it.compositeRule && $breakOnError) {
              if (it.async) {
                out += " throw new ValidationError([" + __err + "]); ";
              } else {
                out += " validate.errors = [" + __err + "]; return false; ";
              }
            } else {
              out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
            }
          } else {
            out += " ) { ";
            var arr2 = $deps;
            if (arr2) {
              var $propertyKey, i2 = -1, l2 = arr2.length - 1;
              while (i2 < l2) {
                $propertyKey = arr2[i2 += 1];
                var $prop = it.util.getProperty($propertyKey), $missingProperty = it.util.escapeQuotes($propertyKey), $useData = $data + $prop;
                if (it.opts._errorDataPathProperty) {
                  it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
                }
                out += " if ( " + $useData + " === undefined ";
                if ($ownProperties) {
                  out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
                }
                out += ") {  var err =   ";
                if (it.createErrors !== false) {
                  out += " { keyword: 'dependencies' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { property: '" + it.util.escapeQuotes($property) + "', missingProperty: '" + $missingProperty + "', depsCount: " + $deps.length + ", deps: '" + it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", ")) + "' } ";
                  if (it.opts.messages !== false) {
                    out += " , message: 'should have ";
                    if ($deps.length == 1) {
                      out += "property " + it.util.escapeQuotes($deps[0]);
                    } else {
                      out += "properties " + it.util.escapeQuotes($deps.join(", "));
                    }
                    out += " when property " + it.util.escapeQuotes($property) + " is present' ";
                  }
                  if (it.opts.verbose) {
                    out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
                  }
                  out += " } ";
                } else {
                  out += " {} ";
                }
                out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ";
              }
            }
          }
          out += " }   ";
          if ($breakOnError) {
            $closingBraces += "}";
            out += " else { ";
          }
        }
      }
      it.errorPath = $currentErrorPath;
      var $currentBaseId = $it.baseId;
      for (var $property in $schemaDeps) {
        var $sch = $schemaDeps[$property];
        if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) {
          out += " " + $nextValid + " = true; if ( " + $data + it.util.getProperty($property) + " !== undefined ";
          if ($ownProperties) {
            out += " && Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($property) + "') ";
          }
          out += ") { ";
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + it.util.getProperty($property);
          $it.errSchemaPath = $errSchemaPath + "/" + it.util.escapeFragment($property);
          out += "  " + it.validate($it) + " ";
          $it.baseId = $currentBaseId;
          out += " }  ";
          if ($breakOnError) {
            out += " if (" + $nextValid + ") { ";
            $closingBraces += "}";
          }
        }
      }
      if ($breakOnError) {
        out += "   " + $closingBraces + " if (" + $errs + " == errors) {";
      }
      return out;
    }, "generate_dependencies");
  }
});

// node_modules/ajv/lib/dotjs/enum.js
var require_enum4 = __commonJS({
  "node_modules/ajv/lib/dotjs/enum.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_enum(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $data = "data" + ($dataLvl || "");
      var $valid = "valid" + $lvl;
      var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
      if ($isData) {
        out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; ";
        $schemaValue = "schema" + $lvl;
      } else {
        $schemaValue = $schema;
      }
      var $i = "i" + $lvl, $vSchema = "schema" + $lvl;
      if (!$isData) {
        out += " var " + $vSchema + " = validate.schema" + $schemaPath + ";";
      }
      out += "var " + $valid + ";";
      if ($isData) {
        out += " if (schema" + $lvl + " === undefined) " + $valid + " = true; else if (!Array.isArray(schema" + $lvl + ")) " + $valid + " = false; else {";
      }
      out += "" + $valid + " = false;for (var " + $i + "=0; " + $i + "<" + $vSchema + ".length; " + $i + "++) if (equal(" + $data + ", " + $vSchema + "[" + $i + "])) { " + $valid + " = true; break; }";
      if ($isData) {
        out += "  }  ";
      }
      out += " if (!" + $valid + ") {   ";
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it.createErrors !== false) {
        out += " { keyword: 'enum' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { allowedValues: schema" + $lvl + " } ";
        if (it.opts.messages !== false) {
          out += " , message: 'should be equal to one of the allowed values' ";
        }
        if (it.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError([" + __err + "]); ";
        } else {
          out += " validate.errors = [" + __err + "]; return false; ";
        }
      } else {
        out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      }
      out += " }";
      if ($breakOnError) {
        out += " else { ";
      }
      return out;
    }, "generate_enum");
  }
});

// node_modules/ajv/lib/dotjs/format.js
var require_format5 = __commonJS({
  "node_modules/ajv/lib/dotjs/format.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_format(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $data = "data" + ($dataLvl || "");
      if (it.opts.format === false) {
        if ($breakOnError) {
          out += " if (true) { ";
        }
        return out;
      }
      var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
      if ($isData) {
        out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; ";
        $schemaValue = "schema" + $lvl;
      } else {
        $schemaValue = $schema;
      }
      var $unknownFormats = it.opts.unknownFormats, $allowUnknown = Array.isArray($unknownFormats);
      if ($isData) {
        var $format = "format" + $lvl, $isObject = "isObject" + $lvl, $formatType = "formatType" + $lvl;
        out += " var " + $format + " = formats[" + $schemaValue + "]; var " + $isObject + " = typeof " + $format + " == 'object' && !(" + $format + " instanceof RegExp) && " + $format + ".validate; var " + $formatType + " = " + $isObject + " && " + $format + ".type || 'string'; if (" + $isObject + ") { ";
        if (it.async) {
          out += " var async" + $lvl + " = " + $format + ".async; ";
        }
        out += " " + $format + " = " + $format + ".validate; } if (  ";
        if ($isData) {
          out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'string') || ";
        }
        out += " (";
        if ($unknownFormats != "ignore") {
          out += " (" + $schemaValue + " && !" + $format + " ";
          if ($allowUnknown) {
            out += " && self._opts.unknownFormats.indexOf(" + $schemaValue + ") == -1 ";
          }
          out += ") || ";
        }
        out += " (" + $format + " && " + $formatType + " == '" + $ruleType + "' && !(typeof " + $format + " == 'function' ? ";
        if (it.async) {
          out += " (async" + $lvl + " ? await " + $format + "(" + $data + ") : " + $format + "(" + $data + ")) ";
        } else {
          out += " " + $format + "(" + $data + ") ";
        }
        out += " : " + $format + ".test(" + $data + "))))) {";
      } else {
        var $format = it.formats[$schema];
        if (!$format) {
          if ($unknownFormats == "ignore") {
            it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"');
            if ($breakOnError) {
              out += " if (true) { ";
            }
            return out;
          } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) {
            if ($breakOnError) {
              out += " if (true) { ";
            }
            return out;
          } else {
            throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"');
          }
        }
        var $isObject = typeof $format == "object" && !($format instanceof RegExp) && $format.validate;
        var $formatType = $isObject && $format.type || "string";
        if ($isObject) {
          var $async = $format.async === true;
          $format = $format.validate;
        }
        if ($formatType != $ruleType) {
          if ($breakOnError) {
            out += " if (true) { ";
          }
          return out;
        }
        if ($async) {
          if (!it.async) throw new Error("async format in sync schema");
          var $formatRef = "formats" + it.util.getProperty($schema) + ".validate";
          out += " if (!(await " + $formatRef + "(" + $data + "))) { ";
        } else {
          out += " if (! ";
          var $formatRef = "formats" + it.util.getProperty($schema);
          if ($isObject) $formatRef += ".validate";
          if (typeof $format == "function") {
            out += " " + $formatRef + "(" + $data + ") ";
          } else {
            out += " " + $formatRef + ".test(" + $data + ") ";
          }
          out += ") { ";
        }
      }
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it.createErrors !== false) {
        out += " { keyword: 'format' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { format:  ";
        if ($isData) {
          out += "" + $schemaValue;
        } else {
          out += "" + it.util.toQuotedString($schema);
        }
        out += "  } ";
        if (it.opts.messages !== false) {
          out += ` , message: 'should match format "`;
          if ($isData) {
            out += "' + " + $schemaValue + " + '";
          } else {
            out += "" + it.util.escapeQuotes($schema);
          }
          out += `"' `;
        }
        if (it.opts.verbose) {
          out += " , schema:  ";
          if ($isData) {
            out += "validate.schema" + $schemaPath;
          } else {
            out += "" + it.util.toQuotedString($schema);
          }
          out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError([" + __err + "]); ";
        } else {
          out += " validate.errors = [" + __err + "]; return false; ";
        }
      } else {
        out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      }
      out += " } ";
      if ($breakOnError) {
        out += " else { ";
      }
      return out;
    }, "generate_format");
  }
});

// node_modules/ajv/lib/dotjs/if.js
var require_if3 = __commonJS({
  "node_modules/ajv/lib/dotjs/if.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_if(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $data = "data" + ($dataLvl || "");
      var $valid = "valid" + $lvl;
      var $errs = "errs__" + $lvl;
      var $it = it.util.copy(it);
      $it.level++;
      var $nextValid = "valid" + $it.level;
      var $thenSch = it.schema["then"], $elseSch = it.schema["else"], $thenPresent = $thenSch !== void 0 && (it.opts.strictKeywords ? typeof $thenSch == "object" && Object.keys($thenSch).length > 0 || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)), $elsePresent = $elseSch !== void 0 && (it.opts.strictKeywords ? typeof $elseSch == "object" && Object.keys($elseSch).length > 0 || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)), $currentBaseId = $it.baseId;
      if ($thenPresent || $elsePresent) {
        var $ifClause;
        $it.createErrors = false;
        $it.schema = $schema;
        $it.schemaPath = $schemaPath;
        $it.errSchemaPath = $errSchemaPath;
        out += " var " + $errs + " = errors; var " + $valid + " = true;  ";
        var $wasComposite = it.compositeRule;
        it.compositeRule = $it.compositeRule = true;
        out += "  " + it.validate($it) + " ";
        $it.baseId = $currentBaseId;
        $it.createErrors = true;
        out += "  errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; }  ";
        it.compositeRule = $it.compositeRule = $wasComposite;
        if ($thenPresent) {
          out += " if (" + $nextValid + ") {  ";
          $it.schema = it.schema["then"];
          $it.schemaPath = it.schemaPath + ".then";
          $it.errSchemaPath = it.errSchemaPath + "/then";
          out += "  " + it.validate($it) + " ";
          $it.baseId = $currentBaseId;
          out += " " + $valid + " = " + $nextValid + "; ";
          if ($thenPresent && $elsePresent) {
            $ifClause = "ifClause" + $lvl;
            out += " var " + $ifClause + " = 'then'; ";
          } else {
            $ifClause = "'then'";
          }
          out += " } ";
          if ($elsePresent) {
            out += " else { ";
          }
        } else {
          out += " if (!" + $nextValid + ") { ";
        }
        if ($elsePresent) {
          $it.schema = it.schema["else"];
          $it.schemaPath = it.schemaPath + ".else";
          $it.errSchemaPath = it.errSchemaPath + "/else";
          out += "  " + it.validate($it) + " ";
          $it.baseId = $currentBaseId;
          out += " " + $valid + " = " + $nextValid + "; ";
          if ($thenPresent && $elsePresent) {
            $ifClause = "ifClause" + $lvl;
            out += " var " + $ifClause + " = 'else'; ";
          } else {
            $ifClause = "'else'";
          }
          out += " } ";
        }
        out += " if (!" + $valid + ") {   var err =   ";
        if (it.createErrors !== false) {
          out += " { keyword: 'if' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { failingKeyword: " + $ifClause + " } ";
          if (it.opts.messages !== false) {
            out += ` , message: 'should match "' + ` + $ifClause + ` + '" schema' `;
          }
          if (it.opts.verbose) {
            out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
        if (!it.compositeRule && $breakOnError) {
          if (it.async) {
            out += " throw new ValidationError(vErrors); ";
          } else {
            out += " validate.errors = vErrors; return false; ";
          }
        }
        out += " }   ";
        if ($breakOnError) {
          out += " else { ";
        }
      } else {
        if ($breakOnError) {
          out += " if (true) { ";
        }
      }
      return out;
    }, "generate_if");
  }
});

// node_modules/ajv/lib/dotjs/items.js
var require_items3 = __commonJS({
  "node_modules/ajv/lib/dotjs/items.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_items(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $data = "data" + ($dataLvl || "");
      var $valid = "valid" + $lvl;
      var $errs = "errs__" + $lvl;
      var $it = it.util.copy(it);
      var $closingBraces = "";
      $it.level++;
      var $nextValid = "valid" + $it.level;
      var $idx = "i" + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = "data" + $dataNxt, $currentBaseId = it.baseId;
      out += "var " + $errs + " = errors;var " + $valid + ";";
      if (Array.isArray($schema)) {
        var $additionalItems = it.schema.additionalItems;
        if ($additionalItems === false) {
          out += " " + $valid + " = " + $data + ".length <= " + $schema.length + "; ";
          var $currErrSchemaPath = $errSchemaPath;
          $errSchemaPath = it.errSchemaPath + "/additionalItems";
          out += "  if (!" + $valid + ") {   ";
          var $$outStack = $$outStack || [];
          $$outStack.push(out);
          out = "";
          if (it.createErrors !== false) {
            out += " { keyword: 'additionalItems' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schema.length + " } ";
            if (it.opts.messages !== false) {
              out += " , message: 'should NOT have more than " + $schema.length + " items' ";
            }
            if (it.opts.verbose) {
              out += " , schema: false , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
            }
            out += " } ";
          } else {
            out += " {} ";
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it.compositeRule && $breakOnError) {
            if (it.async) {
              out += " throw new ValidationError([" + __err + "]); ";
            } else {
              out += " validate.errors = [" + __err + "]; return false; ";
            }
          } else {
            out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
          }
          out += " } ";
          $errSchemaPath = $currErrSchemaPath;
          if ($breakOnError) {
            $closingBraces += "}";
            out += " else { ";
          }
        }
        var arr1 = $schema;
        if (arr1) {
          var $sch, $i = -1, l1 = arr1.length - 1;
          while ($i < l1) {
            $sch = arr1[$i += 1];
            if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) {
              out += " " + $nextValid + " = true; if (" + $data + ".length > " + $i + ") { ";
              var $passData = $data + "[" + $i + "]";
              $it.schema = $sch;
              $it.schemaPath = $schemaPath + "[" + $i + "]";
              $it.errSchemaPath = $errSchemaPath + "/" + $i;
              $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
              $it.dataPathArr[$dataNxt] = $i;
              var $code = it.validate($it);
              $it.baseId = $currentBaseId;
              if (it.util.varOccurences($code, $nextData) < 2) {
                out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
              } else {
                out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
              }
              out += " }  ";
              if ($breakOnError) {
                out += " if (" + $nextValid + ") { ";
                $closingBraces += "}";
              }
            }
          }
        }
        if (typeof $additionalItems == "object" && (it.opts.strictKeywords ? typeof $additionalItems == "object" && Object.keys($additionalItems).length > 0 || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) {
          $it.schema = $additionalItems;
          $it.schemaPath = it.schemaPath + ".additionalItems";
          $it.errSchemaPath = it.errSchemaPath + "/additionalItems";
          out += " " + $nextValid + " = true; if (" + $data + ".length > " + $schema.length + ") {  for (var " + $idx + " = " + $schema.length + "; " + $idx + " < " + $data + ".length; " + $idx + "++) { ";
          $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
          var $passData = $data + "[" + $idx + "]";
          $it.dataPathArr[$dataNxt] = $idx;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
          } else {
            out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
          }
          if ($breakOnError) {
            out += " if (!" + $nextValid + ") break; ";
          }
          out += " } }  ";
          if ($breakOnError) {
            out += " if (" + $nextValid + ") { ";
            $closingBraces += "}";
          }
        }
      } else if (it.opts.strictKeywords ? typeof $schema == "object" && Object.keys($schema).length > 0 || $schema === false : it.util.schemaHasRules($schema, it.RULES.all)) {
        $it.schema = $schema;
        $it.schemaPath = $schemaPath;
        $it.errSchemaPath = $errSchemaPath;
        out += "  for (var " + $idx + " = 0; " + $idx + " < " + $data + ".length; " + $idx + "++) { ";
        $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
        var $passData = $data + "[" + $idx + "]";
        $it.dataPathArr[$dataNxt] = $idx;
        var $code = it.validate($it);
        $it.baseId = $currentBaseId;
        if (it.util.varOccurences($code, $nextData) < 2) {
          out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
        } else {
          out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
        }
        if ($breakOnError) {
          out += " if (!" + $nextValid + ") break; ";
        }
        out += " }";
      }
      if ($breakOnError) {
        out += " " + $closingBraces + " if (" + $errs + " == errors) {";
      }
      return out;
    }, "generate_items");
  }
});

// node_modules/ajv/lib/dotjs/_limit.js
var require_limit2 = __commonJS({
  "node_modules/ajv/lib/dotjs/_limit.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate__limit(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $errorKeyword;
      var $data = "data" + ($dataLvl || "");
      var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
      if ($isData) {
        out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; ";
        $schemaValue = "schema" + $lvl;
      } else {
        $schemaValue = $schema;
      }
      var $isMax = $keyword == "maximum", $exclusiveKeyword = $isMax ? "exclusiveMaximum" : "exclusiveMinimum", $schemaExcl = it.schema[$exclusiveKeyword], $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, $op = $isMax ? "<" : ">", $notOp = $isMax ? ">" : "<", $errorKeyword = void 0;
      if (!($isData || typeof $schema == "number" || $schema === void 0)) {
        throw new Error($keyword + " must be number");
      }
      if (!($isDataExcl || $schemaExcl === void 0 || typeof $schemaExcl == "number" || typeof $schemaExcl == "boolean")) {
        throw new Error($exclusiveKeyword + " must be number or boolean");
      }
      if ($isDataExcl) {
        var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), $exclusive = "exclusive" + $lvl, $exclType = "exclType" + $lvl, $exclIsNumber = "exclIsNumber" + $lvl, $opExpr = "op" + $lvl, $opStr = "' + " + $opExpr + " + '";
        out += " var schemaExcl" + $lvl + " = " + $schemaValueExcl + "; ";
        $schemaValueExcl = "schemaExcl" + $lvl;
        out += " var " + $exclusive + "; var " + $exclType + " = typeof " + $schemaValueExcl + "; if (" + $exclType + " != 'boolean' && " + $exclType + " != 'undefined' && " + $exclType + " != 'number') { ";
        var $errorKeyword = $exclusiveKeyword;
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = "";
        if (it.createErrors !== false) {
          out += " { keyword: '" + ($errorKeyword || "_exclusiveLimit") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} ";
          if (it.opts.messages !== false) {
            out += " , message: '" + $exclusiveKeyword + " should be boolean' ";
          }
          if (it.opts.verbose) {
            out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          if (it.async) {
            out += " throw new ValidationError([" + __err + "]); ";
          } else {
            out += " validate.errors = [" + __err + "]; return false; ";
          }
        } else {
          out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
        }
        out += " } else if ( ";
        if ($isData) {
          out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
        }
        out += " " + $exclType + " == 'number' ? ( (" + $exclusive + " = " + $schemaValue + " === undefined || " + $schemaValueExcl + " " + $op + "= " + $schemaValue + ") ? " + $data + " " + $notOp + "= " + $schemaValueExcl + " : " + $data + " " + $notOp + " " + $schemaValue + " ) : ( (" + $exclusive + " = " + $schemaValueExcl + " === true) ? " + $data + " " + $notOp + "= " + $schemaValue + " : " + $data + " " + $notOp + " " + $schemaValue + " ) || " + $data + " !== " + $data + ") { var op" + $lvl + " = " + $exclusive + " ? '" + $op + "' : '" + $op + "='; ";
        if ($schema === void 0) {
          $errorKeyword = $exclusiveKeyword;
          $errSchemaPath = it.errSchemaPath + "/" + $exclusiveKeyword;
          $schemaValue = $schemaValueExcl;
          $isData = $isDataExcl;
        }
      } else {
        var $exclIsNumber = typeof $schemaExcl == "number", $opStr = $op;
        if ($exclIsNumber && $isData) {
          var $opExpr = "'" + $opStr + "'";
          out += " if ( ";
          if ($isData) {
            out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
          }
          out += " ( " + $schemaValue + " === undefined || " + $schemaExcl + " " + $op + "= " + $schemaValue + " ? " + $data + " " + $notOp + "= " + $schemaExcl + " : " + $data + " " + $notOp + " " + $schemaValue + " ) || " + $data + " !== " + $data + ") { ";
        } else {
          if ($exclIsNumber && $schema === void 0) {
            $exclusive = true;
            $errorKeyword = $exclusiveKeyword;
            $errSchemaPath = it.errSchemaPath + "/" + $exclusiveKeyword;
            $schemaValue = $schemaExcl;
            $notOp += "=";
          } else {
            if ($exclIsNumber) $schemaValue = Math[$isMax ? "min" : "max"]($schemaExcl, $schema);
            if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
              $exclusive = true;
              $errorKeyword = $exclusiveKeyword;
              $errSchemaPath = it.errSchemaPath + "/" + $exclusiveKeyword;
              $notOp += "=";
            } else {
              $exclusive = false;
              $opStr += "=";
            }
          }
          var $opExpr = "'" + $opStr + "'";
          out += " if ( ";
          if ($isData) {
            out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
          }
          out += " " + $data + " " + $notOp + " " + $schemaValue + " || " + $data + " !== " + $data + ") { ";
        }
      }
      $errorKeyword = $errorKeyword || $keyword;
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it.createErrors !== false) {
        out += " { keyword: '" + ($errorKeyword || "_limit") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { comparison: " + $opExpr + ", limit: " + $schemaValue + ", exclusive: " + $exclusive + " } ";
        if (it.opts.messages !== false) {
          out += " , message: 'should be " + $opStr + " ";
          if ($isData) {
            out += "' + " + $schemaValue;
          } else {
            out += "" + $schemaValue + "'";
          }
        }
        if (it.opts.verbose) {
          out += " , schema:  ";
          if ($isData) {
            out += "validate.schema" + $schemaPath;
          } else {
            out += "" + $schema;
          }
          out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError([" + __err + "]); ";
        } else {
          out += " validate.errors = [" + __err + "]; return false; ";
        }
      } else {
        out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      }
      out += " } ";
      if ($breakOnError) {
        out += " else { ";
      }
      return out;
    }, "generate__limit");
  }
});

// node_modules/ajv/lib/dotjs/_limitItems.js
var require_limitItems3 = __commonJS({
  "node_modules/ajv/lib/dotjs/_limitItems.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate__limitItems(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $errorKeyword;
      var $data = "data" + ($dataLvl || "");
      var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
      if ($isData) {
        out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; ";
        $schemaValue = "schema" + $lvl;
      } else {
        $schemaValue = $schema;
      }
      if (!($isData || typeof $schema == "number")) {
        throw new Error($keyword + " must be number");
      }
      var $op = $keyword == "maxItems" ? ">" : "<";
      out += "if ( ";
      if ($isData) {
        out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
      }
      out += " " + $data + ".length " + $op + " " + $schemaValue + ") { ";
      var $errorKeyword = $keyword;
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it.createErrors !== false) {
        out += " { keyword: '" + ($errorKeyword || "_limitItems") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schemaValue + " } ";
        if (it.opts.messages !== false) {
          out += " , message: 'should NOT have ";
          if ($keyword == "maxItems") {
            out += "more";
          } else {
            out += "fewer";
          }
          out += " than ";
          if ($isData) {
            out += "' + " + $schemaValue + " + '";
          } else {
            out += "" + $schema;
          }
          out += " items' ";
        }
        if (it.opts.verbose) {
          out += " , schema:  ";
          if ($isData) {
            out += "validate.schema" + $schemaPath;
          } else {
            out += "" + $schema;
          }
          out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError([" + __err + "]); ";
        } else {
          out += " validate.errors = [" + __err + "]; return false; ";
        }
      } else {
        out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      }
      out += "} ";
      if ($breakOnError) {
        out += " else { ";
      }
      return out;
    }, "generate__limitItems");
  }
});

// node_modules/ajv/lib/dotjs/_limitLength.js
var require_limitLength3 = __commonJS({
  "node_modules/ajv/lib/dotjs/_limitLength.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate__limitLength(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $errorKeyword;
      var $data = "data" + ($dataLvl || "");
      var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
      if ($isData) {
        out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; ";
        $schemaValue = "schema" + $lvl;
      } else {
        $schemaValue = $schema;
      }
      if (!($isData || typeof $schema == "number")) {
        throw new Error($keyword + " must be number");
      }
      var $op = $keyword == "maxLength" ? ">" : "<";
      out += "if ( ";
      if ($isData) {
        out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
      }
      if (it.opts.unicode === false) {
        out += " " + $data + ".length ";
      } else {
        out += " ucs2length(" + $data + ") ";
      }
      out += " " + $op + " " + $schemaValue + ") { ";
      var $errorKeyword = $keyword;
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it.createErrors !== false) {
        out += " { keyword: '" + ($errorKeyword || "_limitLength") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schemaValue + " } ";
        if (it.opts.messages !== false) {
          out += " , message: 'should NOT be ";
          if ($keyword == "maxLength") {
            out += "longer";
          } else {
            out += "shorter";
          }
          out += " than ";
          if ($isData) {
            out += "' + " + $schemaValue + " + '";
          } else {
            out += "" + $schema;
          }
          out += " characters' ";
        }
        if (it.opts.verbose) {
          out += " , schema:  ";
          if ($isData) {
            out += "validate.schema" + $schemaPath;
          } else {
            out += "" + $schema;
          }
          out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError([" + __err + "]); ";
        } else {
          out += " validate.errors = [" + __err + "]; return false; ";
        }
      } else {
        out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      }
      out += "} ";
      if ($breakOnError) {
        out += " else { ";
      }
      return out;
    }, "generate__limitLength");
  }
});

// node_modules/ajv/lib/dotjs/_limitProperties.js
var require_limitProperties3 = __commonJS({
  "node_modules/ajv/lib/dotjs/_limitProperties.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate__limitProperties(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $errorKeyword;
      var $data = "data" + ($dataLvl || "");
      var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
      if ($isData) {
        out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; ";
        $schemaValue = "schema" + $lvl;
      } else {
        $schemaValue = $schema;
      }
      if (!($isData || typeof $schema == "number")) {
        throw new Error($keyword + " must be number");
      }
      var $op = $keyword == "maxProperties" ? ">" : "<";
      out += "if ( ";
      if ($isData) {
        out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
      }
      out += " Object.keys(" + $data + ").length " + $op + " " + $schemaValue + ") { ";
      var $errorKeyword = $keyword;
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it.createErrors !== false) {
        out += " { keyword: '" + ($errorKeyword || "_limitProperties") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schemaValue + " } ";
        if (it.opts.messages !== false) {
          out += " , message: 'should NOT have ";
          if ($keyword == "maxProperties") {
            out += "more";
          } else {
            out += "fewer";
          }
          out += " than ";
          if ($isData) {
            out += "' + " + $schemaValue + " + '";
          } else {
            out += "" + $schema;
          }
          out += " properties' ";
        }
        if (it.opts.verbose) {
          out += " , schema:  ";
          if ($isData) {
            out += "validate.schema" + $schemaPath;
          } else {
            out += "" + $schema;
          }
          out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError([" + __err + "]); ";
        } else {
          out += " validate.errors = [" + __err + "]; return false; ";
        }
      } else {
        out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      }
      out += "} ";
      if ($breakOnError) {
        out += " else { ";
      }
      return out;
    }, "generate__limitProperties");
  }
});

// node_modules/ajv/lib/dotjs/multipleOf.js
var require_multipleOf3 = __commonJS({
  "node_modules/ajv/lib/dotjs/multipleOf.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_multipleOf(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $data = "data" + ($dataLvl || "");
      var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
      if ($isData) {
        out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; ";
        $schemaValue = "schema" + $lvl;
      } else {
        $schemaValue = $schema;
      }
      if (!($isData || typeof $schema == "number")) {
        throw new Error($keyword + " must be number");
      }
      out += "var division" + $lvl + ";if (";
      if ($isData) {
        out += " " + $schemaValue + " !== undefined && ( typeof " + $schemaValue + " != 'number' || ";
      }
      out += " (division" + $lvl + " = " + $data + " / " + $schemaValue + ", ";
      if (it.opts.multipleOfPrecision) {
        out += " Math.abs(Math.round(division" + $lvl + ") - division" + $lvl + ") > 1e-" + it.opts.multipleOfPrecision + " ";
      } else {
        out += " division" + $lvl + " !== parseInt(division" + $lvl + ") ";
      }
      out += " ) ";
      if ($isData) {
        out += "  )  ";
      }
      out += " ) {   ";
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it.createErrors !== false) {
        out += " { keyword: 'multipleOf' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { multipleOf: " + $schemaValue + " } ";
        if (it.opts.messages !== false) {
          out += " , message: 'should be multiple of ";
          if ($isData) {
            out += "' + " + $schemaValue;
          } else {
            out += "" + $schemaValue + "'";
          }
        }
        if (it.opts.verbose) {
          out += " , schema:  ";
          if ($isData) {
            out += "validate.schema" + $schemaPath;
          } else {
            out += "" + $schema;
          }
          out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError([" + __err + "]); ";
        } else {
          out += " validate.errors = [" + __err + "]; return false; ";
        }
      } else {
        out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      }
      out += "} ";
      if ($breakOnError) {
        out += " else { ";
      }
      return out;
    }, "generate_multipleOf");
  }
});

// node_modules/ajv/lib/dotjs/not.js
var require_not3 = __commonJS({
  "node_modules/ajv/lib/dotjs/not.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_not(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $data = "data" + ($dataLvl || "");
      var $errs = "errs__" + $lvl;
      var $it = it.util.copy(it);
      $it.level++;
      var $nextValid = "valid" + $it.level;
      if (it.opts.strictKeywords ? typeof $schema == "object" && Object.keys($schema).length > 0 || $schema === false : it.util.schemaHasRules($schema, it.RULES.all)) {
        $it.schema = $schema;
        $it.schemaPath = $schemaPath;
        $it.errSchemaPath = $errSchemaPath;
        out += " var " + $errs + " = errors;  ";
        var $wasComposite = it.compositeRule;
        it.compositeRule = $it.compositeRule = true;
        $it.createErrors = false;
        var $allErrorsOption;
        if ($it.opts.allErrors) {
          $allErrorsOption = $it.opts.allErrors;
          $it.opts.allErrors = false;
        }
        out += " " + it.validate($it) + " ";
        $it.createErrors = true;
        if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
        it.compositeRule = $it.compositeRule = $wasComposite;
        out += " if (" + $nextValid + ") {   ";
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = "";
        if (it.createErrors !== false) {
          out += " { keyword: 'not' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} ";
          if (it.opts.messages !== false) {
            out += " , message: 'should NOT be valid' ";
          }
          if (it.opts.verbose) {
            out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          if (it.async) {
            out += " throw new ValidationError([" + __err + "]); ";
          } else {
            out += " validate.errors = [" + __err + "]; return false; ";
          }
        } else {
          out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
        }
        out += " } else {  errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; } ";
        if (it.opts.allErrors) {
          out += " } ";
        }
      } else {
        out += "  var err =   ";
        if (it.createErrors !== false) {
          out += " { keyword: 'not' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} ";
          if (it.opts.messages !== false) {
            out += " , message: 'should NOT be valid' ";
          }
          if (it.opts.verbose) {
            out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
        if ($breakOnError) {
          out += " if (false) { ";
        }
      }
      return out;
    }, "generate_not");
  }
});

// node_modules/ajv/lib/dotjs/oneOf.js
var require_oneOf3 = __commonJS({
  "node_modules/ajv/lib/dotjs/oneOf.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_oneOf(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $data = "data" + ($dataLvl || "");
      var $valid = "valid" + $lvl;
      var $errs = "errs__" + $lvl;
      var $it = it.util.copy(it);
      var $closingBraces = "";
      $it.level++;
      var $nextValid = "valid" + $it.level;
      var $currentBaseId = $it.baseId, $prevValid = "prevValid" + $lvl, $passingSchemas = "passingSchemas" + $lvl;
      out += "var " + $errs + " = errors , " + $prevValid + " = false , " + $valid + " = false , " + $passingSchemas + " = null; ";
      var $wasComposite = it.compositeRule;
      it.compositeRule = $it.compositeRule = true;
      var arr1 = $schema;
      if (arr1) {
        var $sch, $i = -1, l1 = arr1.length - 1;
        while ($i < l1) {
          $sch = arr1[$i += 1];
          if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) {
            $it.schema = $sch;
            $it.schemaPath = $schemaPath + "[" + $i + "]";
            $it.errSchemaPath = $errSchemaPath + "/" + $i;
            out += "  " + it.validate($it) + " ";
            $it.baseId = $currentBaseId;
          } else {
            out += " var " + $nextValid + " = true; ";
          }
          if ($i) {
            out += " if (" + $nextValid + " && " + $prevValid + ") { " + $valid + " = false; " + $passingSchemas + " = [" + $passingSchemas + ", " + $i + "]; } else { ";
            $closingBraces += "}";
          }
          out += " if (" + $nextValid + ") { " + $valid + " = " + $prevValid + " = true; " + $passingSchemas + " = " + $i + "; }";
        }
      }
      it.compositeRule = $it.compositeRule = $wasComposite;
      out += "" + $closingBraces + "if (!" + $valid + ") {   var err =   ";
      if (it.createErrors !== false) {
        out += " { keyword: 'oneOf' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { passingSchemas: " + $passingSchemas + " } ";
        if (it.opts.messages !== false) {
          out += " , message: 'should match exactly one schema in oneOf' ";
        }
        if (it.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError(vErrors); ";
        } else {
          out += " validate.errors = vErrors; return false; ";
        }
      }
      out += "} else {  errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; }";
      if (it.opts.allErrors) {
        out += " } ";
      }
      return out;
    }, "generate_oneOf");
  }
});

// node_modules/ajv/lib/dotjs/pattern.js
var require_pattern3 = __commonJS({
  "node_modules/ajv/lib/dotjs/pattern.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_pattern(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $data = "data" + ($dataLvl || "");
      var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
      if ($isData) {
        out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; ";
        $schemaValue = "schema" + $lvl;
      } else {
        $schemaValue = $schema;
      }
      var $regexp = $isData ? "(new RegExp(" + $schemaValue + "))" : it.usePattern($schema);
      out += "if ( ";
      if ($isData) {
        out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'string') || ";
      }
      out += " !" + $regexp + ".test(" + $data + ") ) {   ";
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it.createErrors !== false) {
        out += " { keyword: 'pattern' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { pattern:  ";
        if ($isData) {
          out += "" + $schemaValue;
        } else {
          out += "" + it.util.toQuotedString($schema);
        }
        out += "  } ";
        if (it.opts.messages !== false) {
          out += ` , message: 'should match pattern "`;
          if ($isData) {
            out += "' + " + $schemaValue + " + '";
          } else {
            out += "" + it.util.escapeQuotes($schema);
          }
          out += `"' `;
        }
        if (it.opts.verbose) {
          out += " , schema:  ";
          if ($isData) {
            out += "validate.schema" + $schemaPath;
          } else {
            out += "" + it.util.toQuotedString($schema);
          }
          out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError([" + __err + "]); ";
        } else {
          out += " validate.errors = [" + __err + "]; return false; ";
        }
      } else {
        out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      }
      out += "} ";
      if ($breakOnError) {
        out += " else { ";
      }
      return out;
    }, "generate_pattern");
  }
});

// node_modules/ajv/lib/dotjs/properties.js
var require_properties3 = __commonJS({
  "node_modules/ajv/lib/dotjs/properties.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_properties(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $data = "data" + ($dataLvl || "");
      var $errs = "errs__" + $lvl;
      var $it = it.util.copy(it);
      var $closingBraces = "";
      $it.level++;
      var $nextValid = "valid" + $it.level;
      var $key = "key" + $lvl, $idx = "idx" + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = "data" + $dataNxt, $dataProperties = "dataProperties" + $lvl;
      var $schemaKeys = Object.keys($schema || {}).filter(notProto), $pProperties = it.schema.patternProperties || {}, $pPropertyKeys = Object.keys($pProperties).filter(notProto), $aProperties = it.schema.additionalProperties, $someProperties = $schemaKeys.length || $pPropertyKeys.length, $noAdditional = $aProperties === false, $additionalIsSchema = typeof $aProperties == "object" && Object.keys($aProperties).length, $removeAdditional = it.opts.removeAdditional, $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, $ownProperties = it.opts.ownProperties, $currentBaseId = it.baseId;
      var $required = it.schema.required;
      if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) {
        var $requiredHash = it.util.toHash($required);
      }
      function notProto(p) {
        return p !== "__proto__";
      }
      __name(notProto, "notProto");
      out += "var " + $errs + " = errors;var " + $nextValid + " = true;";
      if ($ownProperties) {
        out += " var " + $dataProperties + " = undefined;";
      }
      if ($checkAdditional) {
        if ($ownProperties) {
          out += " " + $dataProperties + " = " + $dataProperties + " || Object.keys(" + $data + "); for (var " + $idx + "=0; " + $idx + "<" + $dataProperties + ".length; " + $idx + "++) { var " + $key + " = " + $dataProperties + "[" + $idx + "]; ";
        } else {
          out += " for (var " + $key + " in " + $data + ") { ";
        }
        if ($someProperties) {
          out += " var isAdditional" + $lvl + " = !(false ";
          if ($schemaKeys.length) {
            if ($schemaKeys.length > 8) {
              out += " || validate.schema" + $schemaPath + ".hasOwnProperty(" + $key + ") ";
            } else {
              var arr1 = $schemaKeys;
              if (arr1) {
                var $propertyKey, i1 = -1, l1 = arr1.length - 1;
                while (i1 < l1) {
                  $propertyKey = arr1[i1 += 1];
                  out += " || " + $key + " == " + it.util.toQuotedString($propertyKey) + " ";
                }
              }
            }
          }
          if ($pPropertyKeys.length) {
            var arr2 = $pPropertyKeys;
            if (arr2) {
              var $pProperty, $i = -1, l2 = arr2.length - 1;
              while ($i < l2) {
                $pProperty = arr2[$i += 1];
                out += " || " + it.usePattern($pProperty) + ".test(" + $key + ") ";
              }
            }
          }
          out += " ); if (isAdditional" + $lvl + ") { ";
        }
        if ($removeAdditional == "all") {
          out += " delete " + $data + "[" + $key + "]; ";
        } else {
          var $currentErrorPath = it.errorPath;
          var $additionalProperty = "' + " + $key + " + '";
          if (it.opts._errorDataPathProperty) {
            it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          }
          if ($noAdditional) {
            if ($removeAdditional) {
              out += " delete " + $data + "[" + $key + "]; ";
            } else {
              out += " " + $nextValid + " = false; ";
              var $currErrSchemaPath = $errSchemaPath;
              $errSchemaPath = it.errSchemaPath + "/additionalProperties";
              var $$outStack = $$outStack || [];
              $$outStack.push(out);
              out = "";
              if (it.createErrors !== false) {
                out += " { keyword: 'additionalProperties' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { additionalProperty: '" + $additionalProperty + "' } ";
                if (it.opts.messages !== false) {
                  out += " , message: '";
                  if (it.opts._errorDataPathProperty) {
                    out += "is an invalid additional property";
                  } else {
                    out += "should NOT have additional properties";
                  }
                  out += "' ";
                }
                if (it.opts.verbose) {
                  out += " , schema: false , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
                }
                out += " } ";
              } else {
                out += " {} ";
              }
              var __err = out;
              out = $$outStack.pop();
              if (!it.compositeRule && $breakOnError) {
                if (it.async) {
                  out += " throw new ValidationError([" + __err + "]); ";
                } else {
                  out += " validate.errors = [" + __err + "]; return false; ";
                }
              } else {
                out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
              }
              $errSchemaPath = $currErrSchemaPath;
              if ($breakOnError) {
                out += " break; ";
              }
            }
          } else if ($additionalIsSchema) {
            if ($removeAdditional == "failing") {
              out += " var " + $errs + " = errors;  ";
              var $wasComposite = it.compositeRule;
              it.compositeRule = $it.compositeRule = true;
              $it.schema = $aProperties;
              $it.schemaPath = it.schemaPath + ".additionalProperties";
              $it.errSchemaPath = it.errSchemaPath + "/additionalProperties";
              $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
              var $passData = $data + "[" + $key + "]";
              $it.dataPathArr[$dataNxt] = $key;
              var $code = it.validate($it);
              $it.baseId = $currentBaseId;
              if (it.util.varOccurences($code, $nextData) < 2) {
                out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
              } else {
                out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
              }
              out += " if (!" + $nextValid + ") { errors = " + $errs + "; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete " + $data + "[" + $key + "]; }  ";
              it.compositeRule = $it.compositeRule = $wasComposite;
            } else {
              $it.schema = $aProperties;
              $it.schemaPath = it.schemaPath + ".additionalProperties";
              $it.errSchemaPath = it.errSchemaPath + "/additionalProperties";
              $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
              var $passData = $data + "[" + $key + "]";
              $it.dataPathArr[$dataNxt] = $key;
              var $code = it.validate($it);
              $it.baseId = $currentBaseId;
              if (it.util.varOccurences($code, $nextData) < 2) {
                out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
              } else {
                out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
              }
              if ($breakOnError) {
                out += " if (!" + $nextValid + ") break; ";
              }
            }
          }
          it.errorPath = $currentErrorPath;
        }
        if ($someProperties) {
          out += " } ";
        }
        out += " }  ";
        if ($breakOnError) {
          out += " if (" + $nextValid + ") { ";
          $closingBraces += "}";
        }
      }
      var $useDefaults = it.opts.useDefaults && !it.compositeRule;
      if ($schemaKeys.length) {
        var arr3 = $schemaKeys;
        if (arr3) {
          var $propertyKey, i3 = -1, l3 = arr3.length - 1;
          while (i3 < l3) {
            $propertyKey = arr3[i3 += 1];
            var $sch = $schema[$propertyKey];
            if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) {
              var $prop = it.util.getProperty($propertyKey), $passData = $data + $prop, $hasDefault = $useDefaults && $sch.default !== void 0;
              $it.schema = $sch;
              $it.schemaPath = $schemaPath + $prop;
              $it.errSchemaPath = $errSchemaPath + "/" + it.util.escapeFragment($propertyKey);
              $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
              $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
              var $code = it.validate($it);
              $it.baseId = $currentBaseId;
              if (it.util.varOccurences($code, $nextData) < 2) {
                $code = it.util.varReplace($code, $nextData, $passData);
                var $useData = $passData;
              } else {
                var $useData = $nextData;
                out += " var " + $nextData + " = " + $passData + "; ";
              }
              if ($hasDefault) {
                out += " " + $code + " ";
              } else {
                if ($requiredHash && $requiredHash[$propertyKey]) {
                  out += " if ( " + $useData + " === undefined ";
                  if ($ownProperties) {
                    out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
                  }
                  out += ") { " + $nextValid + " = false; ";
                  var $currentErrorPath = it.errorPath, $currErrSchemaPath = $errSchemaPath, $missingProperty = it.util.escapeQuotes($propertyKey);
                  if (it.opts._errorDataPathProperty) {
                    it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
                  }
                  $errSchemaPath = it.errSchemaPath + "/required";
                  var $$outStack = $$outStack || [];
                  $$outStack.push(out);
                  out = "";
                  if (it.createErrors !== false) {
                    out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
                    if (it.opts.messages !== false) {
                      out += " , message: '";
                      if (it.opts._errorDataPathProperty) {
                        out += "is a required property";
                      } else {
                        out += "should have required property \\'" + $missingProperty + "\\'";
                      }
                      out += "' ";
                    }
                    if (it.opts.verbose) {
                      out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
                    }
                    out += " } ";
                  } else {
                    out += " {} ";
                  }
                  var __err = out;
                  out = $$outStack.pop();
                  if (!it.compositeRule && $breakOnError) {
                    if (it.async) {
                      out += " throw new ValidationError([" + __err + "]); ";
                    } else {
                      out += " validate.errors = [" + __err + "]; return false; ";
                    }
                  } else {
                    out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
                  }
                  $errSchemaPath = $currErrSchemaPath;
                  it.errorPath = $currentErrorPath;
                  out += " } else { ";
                } else {
                  if ($breakOnError) {
                    out += " if ( " + $useData + " === undefined ";
                    if ($ownProperties) {
                      out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
                    }
                    out += ") { " + $nextValid + " = true; } else { ";
                  } else {
                    out += " if (" + $useData + " !== undefined ";
                    if ($ownProperties) {
                      out += " &&   Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
                    }
                    out += " ) { ";
                  }
                }
                out += " " + $code + " } ";
              }
            }
            if ($breakOnError) {
              out += " if (" + $nextValid + ") { ";
              $closingBraces += "}";
            }
          }
        }
      }
      if ($pPropertyKeys.length) {
        var arr4 = $pPropertyKeys;
        if (arr4) {
          var $pProperty, i4 = -1, l4 = arr4.length - 1;
          while (i4 < l4) {
            $pProperty = arr4[i4 += 1];
            var $sch = $pProperties[$pProperty];
            if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) {
              $it.schema = $sch;
              $it.schemaPath = it.schemaPath + ".patternProperties" + it.util.getProperty($pProperty);
              $it.errSchemaPath = it.errSchemaPath + "/patternProperties/" + it.util.escapeFragment($pProperty);
              if ($ownProperties) {
                out += " " + $dataProperties + " = " + $dataProperties + " || Object.keys(" + $data + "); for (var " + $idx + "=0; " + $idx + "<" + $dataProperties + ".length; " + $idx + "++) { var " + $key + " = " + $dataProperties + "[" + $idx + "]; ";
              } else {
                out += " for (var " + $key + " in " + $data + ") { ";
              }
              out += " if (" + it.usePattern($pProperty) + ".test(" + $key + ")) { ";
              $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
              var $passData = $data + "[" + $key + "]";
              $it.dataPathArr[$dataNxt] = $key;
              var $code = it.validate($it);
              $it.baseId = $currentBaseId;
              if (it.util.varOccurences($code, $nextData) < 2) {
                out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
              } else {
                out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
              }
              if ($breakOnError) {
                out += " if (!" + $nextValid + ") break; ";
              }
              out += " } ";
              if ($breakOnError) {
                out += " else " + $nextValid + " = true; ";
              }
              out += " }  ";
              if ($breakOnError) {
                out += " if (" + $nextValid + ") { ";
                $closingBraces += "}";
              }
            }
          }
        }
      }
      if ($breakOnError) {
        out += " " + $closingBraces + " if (" + $errs + " == errors) {";
      }
      return out;
    }, "generate_properties");
  }
});

// node_modules/ajv/lib/dotjs/propertyNames.js
var require_propertyNames3 = __commonJS({
  "node_modules/ajv/lib/dotjs/propertyNames.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_propertyNames(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $data = "data" + ($dataLvl || "");
      var $errs = "errs__" + $lvl;
      var $it = it.util.copy(it);
      var $closingBraces = "";
      $it.level++;
      var $nextValid = "valid" + $it.level;
      out += "var " + $errs + " = errors;";
      if (it.opts.strictKeywords ? typeof $schema == "object" && Object.keys($schema).length > 0 || $schema === false : it.util.schemaHasRules($schema, it.RULES.all)) {
        $it.schema = $schema;
        $it.schemaPath = $schemaPath;
        $it.errSchemaPath = $errSchemaPath;
        var $key = "key" + $lvl, $idx = "idx" + $lvl, $i = "i" + $lvl, $invalidName = "' + " + $key + " + '", $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = "data" + $dataNxt, $dataProperties = "dataProperties" + $lvl, $ownProperties = it.opts.ownProperties, $currentBaseId = it.baseId;
        if ($ownProperties) {
          out += " var " + $dataProperties + " = undefined; ";
        }
        if ($ownProperties) {
          out += " " + $dataProperties + " = " + $dataProperties + " || Object.keys(" + $data + "); for (var " + $idx + "=0; " + $idx + "<" + $dataProperties + ".length; " + $idx + "++) { var " + $key + " = " + $dataProperties + "[" + $idx + "]; ";
        } else {
          out += " for (var " + $key + " in " + $data + ") { ";
        }
        out += " var startErrs" + $lvl + " = errors; ";
        var $passData = $key;
        var $wasComposite = it.compositeRule;
        it.compositeRule = $it.compositeRule = true;
        var $code = it.validate($it);
        $it.baseId = $currentBaseId;
        if (it.util.varOccurences($code, $nextData) < 2) {
          out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
        } else {
          out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
        }
        it.compositeRule = $it.compositeRule = $wasComposite;
        out += " if (!" + $nextValid + ") { for (var " + $i + "=startErrs" + $lvl + "; " + $i + "<errors; " + $i + "++) { vErrors[" + $i + "].propertyName = " + $key + "; }   var err =   ";
        if (it.createErrors !== false) {
          out += " { keyword: 'propertyNames' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { propertyName: '" + $invalidName + "' } ";
          if (it.opts.messages !== false) {
            out += " , message: 'property name \\'" + $invalidName + "\\' is invalid' ";
          }
          if (it.opts.verbose) {
            out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
        if (!it.compositeRule && $breakOnError) {
          if (it.async) {
            out += " throw new ValidationError(vErrors); ";
          } else {
            out += " validate.errors = vErrors; return false; ";
          }
        }
        if ($breakOnError) {
          out += " break; ";
        }
        out += " } }";
      }
      if ($breakOnError) {
        out += " " + $closingBraces + " if (" + $errs + " == errors) {";
      }
      return out;
    }, "generate_propertyNames");
  }
});

// node_modules/ajv/lib/dotjs/required.js
var require_required3 = __commonJS({
  "node_modules/ajv/lib/dotjs/required.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_required(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $data = "data" + ($dataLvl || "");
      var $valid = "valid" + $lvl;
      var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
      if ($isData) {
        out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; ";
        $schemaValue = "schema" + $lvl;
      } else {
        $schemaValue = $schema;
      }
      var $vSchema = "schema" + $lvl;
      if (!$isData) {
        if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) {
          var $required = [];
          var arr1 = $schema;
          if (arr1) {
            var $property, i1 = -1, l1 = arr1.length - 1;
            while (i1 < l1) {
              $property = arr1[i1 += 1];
              var $propertySch = it.schema.properties[$property];
              if (!($propertySch && (it.opts.strictKeywords ? typeof $propertySch == "object" && Object.keys($propertySch).length > 0 || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) {
                $required[$required.length] = $property;
              }
            }
          }
        } else {
          var $required = $schema;
        }
      }
      if ($isData || $required.length) {
        var $currentErrorPath = it.errorPath, $loopRequired = $isData || $required.length >= it.opts.loopRequired, $ownProperties = it.opts.ownProperties;
        if ($breakOnError) {
          out += " var missing" + $lvl + "; ";
          if ($loopRequired) {
            if (!$isData) {
              out += " var " + $vSchema + " = validate.schema" + $schemaPath + "; ";
            }
            var $i = "i" + $lvl, $propertyPath = "schema" + $lvl + "[" + $i + "]", $missingProperty = "' + " + $propertyPath + " + '";
            if (it.opts._errorDataPathProperty) {
              it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
            }
            out += " var " + $valid + " = true; ";
            if ($isData) {
              out += " if (schema" + $lvl + " === undefined) " + $valid + " = true; else if (!Array.isArray(schema" + $lvl + ")) " + $valid + " = false; else {";
            }
            out += " for (var " + $i + " = 0; " + $i + " < " + $vSchema + ".length; " + $i + "++) { " + $valid + " = " + $data + "[" + $vSchema + "[" + $i + "]] !== undefined ";
            if ($ownProperties) {
              out += " &&   Object.prototype.hasOwnProperty.call(" + $data + ", " + $vSchema + "[" + $i + "]) ";
            }
            out += "; if (!" + $valid + ") break; } ";
            if ($isData) {
              out += "  }  ";
            }
            out += "  if (!" + $valid + ") {   ";
            var $$outStack = $$outStack || [];
            $$outStack.push(out);
            out = "";
            if (it.createErrors !== false) {
              out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
              if (it.opts.messages !== false) {
                out += " , message: '";
                if (it.opts._errorDataPathProperty) {
                  out += "is a required property";
                } else {
                  out += "should have required property \\'" + $missingProperty + "\\'";
                }
                out += "' ";
              }
              if (it.opts.verbose) {
                out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
              }
              out += " } ";
            } else {
              out += " {} ";
            }
            var __err = out;
            out = $$outStack.pop();
            if (!it.compositeRule && $breakOnError) {
              if (it.async) {
                out += " throw new ValidationError([" + __err + "]); ";
              } else {
                out += " validate.errors = [" + __err + "]; return false; ";
              }
            } else {
              out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
            }
            out += " } else { ";
          } else {
            out += " if ( ";
            var arr2 = $required;
            if (arr2) {
              var $propertyKey, $i = -1, l2 = arr2.length - 1;
              while ($i < l2) {
                $propertyKey = arr2[$i += 1];
                if ($i) {
                  out += " || ";
                }
                var $prop = it.util.getProperty($propertyKey), $useData = $data + $prop;
                out += " ( ( " + $useData + " === undefined ";
                if ($ownProperties) {
                  out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
                }
                out += ") && (missing" + $lvl + " = " + it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) + ") ) ";
              }
            }
            out += ") {  ";
            var $propertyPath = "missing" + $lvl, $missingProperty = "' + " + $propertyPath + " + '";
            if (it.opts._errorDataPathProperty) {
              it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + " + " + $propertyPath;
            }
            var $$outStack = $$outStack || [];
            $$outStack.push(out);
            out = "";
            if (it.createErrors !== false) {
              out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
              if (it.opts.messages !== false) {
                out += " , message: '";
                if (it.opts._errorDataPathProperty) {
                  out += "is a required property";
                } else {
                  out += "should have required property \\'" + $missingProperty + "\\'";
                }
                out += "' ";
              }
              if (it.opts.verbose) {
                out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
              }
              out += " } ";
            } else {
              out += " {} ";
            }
            var __err = out;
            out = $$outStack.pop();
            if (!it.compositeRule && $breakOnError) {
              if (it.async) {
                out += " throw new ValidationError([" + __err + "]); ";
              } else {
                out += " validate.errors = [" + __err + "]; return false; ";
              }
            } else {
              out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
            }
            out += " } else { ";
          }
        } else {
          if ($loopRequired) {
            if (!$isData) {
              out += " var " + $vSchema + " = validate.schema" + $schemaPath + "; ";
            }
            var $i = "i" + $lvl, $propertyPath = "schema" + $lvl + "[" + $i + "]", $missingProperty = "' + " + $propertyPath + " + '";
            if (it.opts._errorDataPathProperty) {
              it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
            }
            if ($isData) {
              out += " if (" + $vSchema + " && !Array.isArray(" + $vSchema + ")) {  var err =   ";
              if (it.createErrors !== false) {
                out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
                if (it.opts.messages !== false) {
                  out += " , message: '";
                  if (it.opts._errorDataPathProperty) {
                    out += "is a required property";
                  } else {
                    out += "should have required property \\'" + $missingProperty + "\\'";
                  }
                  out += "' ";
                }
                if (it.opts.verbose) {
                  out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
                }
                out += " } ";
              } else {
                out += " {} ";
              }
              out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (" + $vSchema + " !== undefined) { ";
            }
            out += " for (var " + $i + " = 0; " + $i + " < " + $vSchema + ".length; " + $i + "++) { if (" + $data + "[" + $vSchema + "[" + $i + "]] === undefined ";
            if ($ownProperties) {
              out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", " + $vSchema + "[" + $i + "]) ";
            }
            out += ") {  var err =   ";
            if (it.createErrors !== false) {
              out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
              if (it.opts.messages !== false) {
                out += " , message: '";
                if (it.opts._errorDataPathProperty) {
                  out += "is a required property";
                } else {
                  out += "should have required property \\'" + $missingProperty + "\\'";
                }
                out += "' ";
              }
              if (it.opts.verbose) {
                out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
              }
              out += " } ";
            } else {
              out += " {} ";
            }
            out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ";
            if ($isData) {
              out += "  }  ";
            }
          } else {
            var arr3 = $required;
            if (arr3) {
              var $propertyKey, i3 = -1, l3 = arr3.length - 1;
              while (i3 < l3) {
                $propertyKey = arr3[i3 += 1];
                var $prop = it.util.getProperty($propertyKey), $missingProperty = it.util.escapeQuotes($propertyKey), $useData = $data + $prop;
                if (it.opts._errorDataPathProperty) {
                  it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
                }
                out += " if ( " + $useData + " === undefined ";
                if ($ownProperties) {
                  out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
                }
                out += ") {  var err =   ";
                if (it.createErrors !== false) {
                  out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
                  if (it.opts.messages !== false) {
                    out += " , message: '";
                    if (it.opts._errorDataPathProperty) {
                      out += "is a required property";
                    } else {
                      out += "should have required property \\'" + $missingProperty + "\\'";
                    }
                    out += "' ";
                  }
                  if (it.opts.verbose) {
                    out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
                  }
                  out += " } ";
                } else {
                  out += " {} ";
                }
                out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ";
              }
            }
          }
        }
        it.errorPath = $currentErrorPath;
      } else if ($breakOnError) {
        out += " if (true) {";
      }
      return out;
    }, "generate_required");
  }
});

// node_modules/ajv/lib/dotjs/uniqueItems.js
var require_uniqueItems3 = __commonJS({
  "node_modules/ajv/lib/dotjs/uniqueItems.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_uniqueItems(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $data = "data" + ($dataLvl || "");
      var $valid = "valid" + $lvl;
      var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
      if ($isData) {
        out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; ";
        $schemaValue = "schema" + $lvl;
      } else {
        $schemaValue = $schema;
      }
      if (($schema || $isData) && it.opts.uniqueItems !== false) {
        if ($isData) {
          out += " var " + $valid + "; if (" + $schemaValue + " === false || " + $schemaValue + " === undefined) " + $valid + " = true; else if (typeof " + $schemaValue + " != 'boolean') " + $valid + " = false; else { ";
        }
        out += " var i = " + $data + ".length , " + $valid + " = true , j; if (i > 1) { ";
        var $itemType = it.schema.items && it.schema.items.type, $typeIsArray = Array.isArray($itemType);
        if (!$itemType || $itemType == "object" || $itemType == "array" || $typeIsArray && ($itemType.indexOf("object") >= 0 || $itemType.indexOf("array") >= 0)) {
          out += " outer: for (;i--;) { for (j = i; j--;) { if (equal(" + $data + "[i], " + $data + "[j])) { " + $valid + " = false; break outer; } } } ";
        } else {
          out += " var itemIndices = {}, item; for (;i--;) { var item = " + $data + "[i]; ";
          var $method = "checkDataType" + ($typeIsArray ? "s" : "");
          out += " if (" + it.util[$method]($itemType, "item", it.opts.strictNumbers, true) + ") continue; ";
          if ($typeIsArray) {
            out += ` if (typeof item == 'string') item = '"' + item; `;
          }
          out += " if (typeof itemIndices[item] == 'number') { " + $valid + " = false; j = itemIndices[item]; break; } itemIndices[item] = i; } ";
        }
        out += " } ";
        if ($isData) {
          out += "  }  ";
        }
        out += " if (!" + $valid + ") {   ";
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = "";
        if (it.createErrors !== false) {
          out += " { keyword: 'uniqueItems' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { i: i, j: j } ";
          if (it.opts.messages !== false) {
            out += " , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' ";
          }
          if (it.opts.verbose) {
            out += " , schema:  ";
            if ($isData) {
              out += "validate.schema" + $schemaPath;
            } else {
              out += "" + $schema;
            }
            out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          if (it.async) {
            out += " throw new ValidationError([" + __err + "]); ";
          } else {
            out += " validate.errors = [" + __err + "]; return false; ";
          }
        } else {
          out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
        }
        out += " } ";
        if ($breakOnError) {
          out += " else { ";
        }
      } else {
        if ($breakOnError) {
          out += " if (true) { ";
        }
      }
      return out;
    }, "generate_uniqueItems");
  }
});

// node_modules/ajv/lib/dotjs/index.js
var require_dotjs = __commonJS({
  "node_modules/ajv/lib/dotjs/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      "$ref": require_ref3(),
      allOf: require_allOf3(),
      anyOf: require_anyOf3(),
      "$comment": require_comment(),
      const: require_const3(),
      contains: require_contains3(),
      dependencies: require_dependencies3(),
      "enum": require_enum4(),
      format: require_format5(),
      "if": require_if3(),
      items: require_items3(),
      maximum: require_limit2(),
      minimum: require_limit2(),
      maxItems: require_limitItems3(),
      minItems: require_limitItems3(),
      maxLength: require_limitLength3(),
      minLength: require_limitLength3(),
      maxProperties: require_limitProperties3(),
      minProperties: require_limitProperties3(),
      multipleOf: require_multipleOf3(),
      not: require_not3(),
      oneOf: require_oneOf3(),
      pattern: require_pattern3(),
      properties: require_properties3(),
      propertyNames: require_propertyNames3(),
      required: require_required3(),
      uniqueItems: require_uniqueItems3(),
      validate: require_validate3()
    };
  }
});

// node_modules/ajv/lib/compile/rules.js
var require_rules3 = __commonJS({
  "node_modules/ajv/lib/compile/rules.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var ruleModules = require_dotjs();
    var toHash = require_util15().toHash;
    module2.exports = /* @__PURE__ */ __name(function rules() {
      var RULES = [
        {
          type: "number",
          rules: [
            { "maximum": ["exclusiveMaximum"] },
            { "minimum": ["exclusiveMinimum"] },
            "multipleOf",
            "format"
          ]
        },
        {
          type: "string",
          rules: ["maxLength", "minLength", "pattern", "format"]
        },
        {
          type: "array",
          rules: ["maxItems", "minItems", "items", "contains", "uniqueItems"]
        },
        {
          type: "object",
          rules: [
            "maxProperties",
            "minProperties",
            "required",
            "dependencies",
            "propertyNames",
            { "properties": ["additionalProperties", "patternProperties"] }
          ]
        },
        { rules: ["$ref", "const", "enum", "not", "anyOf", "oneOf", "allOf", "if"] }
      ];
      var ALL2 = ["type", "$comment"];
      var KEYWORDS3 = [
        "$schema",
        "$id",
        "id",
        "$data",
        "$async",
        "title",
        "description",
        "default",
        "definitions",
        "examples",
        "readOnly",
        "writeOnly",
        "contentMediaType",
        "contentEncoding",
        "additionalItems",
        "then",
        "else"
      ];
      var TYPES3 = ["number", "integer", "string", "array", "object", "boolean", "null"];
      RULES.all = toHash(ALL2);
      RULES.types = toHash(TYPES3);
      RULES.forEach(function(group) {
        group.rules = group.rules.map(function(keyword) {
          var implKeywords;
          if (typeof keyword == "object") {
            var key = Object.keys(keyword)[0];
            implKeywords = keyword[key];
            keyword = key;
            implKeywords.forEach(function(k) {
              ALL2.push(k);
              RULES.all[k] = true;
            });
          }
          ALL2.push(keyword);
          var rule = RULES.all[keyword] = {
            keyword,
            code: ruleModules[keyword],
            implements: implKeywords
          };
          return rule;
        });
        RULES.all.$comment = {
          keyword: "$comment",
          code: ruleModules.$comment
        };
        if (group.type) RULES.types[group.type] = group;
      });
      RULES.keywords = toHash(ALL2.concat(KEYWORDS3));
      RULES.custom = {};
      return RULES;
    }, "rules");
  }
});

// node_modules/ajv/lib/data.js
var require_data3 = __commonJS({
  "node_modules/ajv/lib/data.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var KEYWORDS3 = [
      "multipleOf",
      "maximum",
      "exclusiveMaximum",
      "minimum",
      "exclusiveMinimum",
      "maxLength",
      "minLength",
      "pattern",
      "additionalItems",
      "maxItems",
      "minItems",
      "uniqueItems",
      "maxProperties",
      "minProperties",
      "required",
      "additionalProperties",
      "enum",
      "format",
      "const"
    ];
    module2.exports = function(metaSchema, keywordsJsonPointers) {
      for (var i = 0; i < keywordsJsonPointers.length; i++) {
        metaSchema = JSON.parse(JSON.stringify(metaSchema));
        var segments = keywordsJsonPointers[i].split("/");
        var keywords2 = metaSchema;
        var j;
        for (j = 1; j < segments.length; j++)
          keywords2 = keywords2[segments[j]];
        for (j = 0; j < KEYWORDS3.length; j++) {
          var key = KEYWORDS3[j];
          var schema = keywords2[key];
          if (schema) {
            keywords2[key] = {
              anyOf: [
                schema,
                { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }
              ]
            };
          }
        }
      }
      return metaSchema;
    };
  }
});

// node_modules/ajv/lib/compile/async.js
var require_async2 = __commonJS({
  "node_modules/ajv/lib/compile/async.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var MissingRefError = require_error_classes().MissingRef;
    module2.exports = compileAsync;
    function compileAsync(schema, meta, callback) {
      var self2 = this;
      if (typeof this._opts.loadSchema != "function")
        throw new Error("options.loadSchema should be a function");
      if (typeof meta == "function") {
        callback = meta;
        meta = void 0;
      }
      var p = loadMetaSchemaOf(schema).then(function() {
        var schemaObj = self2._addSchema(schema, void 0, meta);
        return schemaObj.validate || _compileAsync(schemaObj);
      });
      if (callback) {
        p.then(
          function(v) {
            callback(null, v);
          },
          callback
        );
      }
      return p;
      function loadMetaSchemaOf(sch) {
        var $schema = sch.$schema;
        return $schema && !self2.getSchema($schema) ? compileAsync.call(self2, { $ref: $schema }, true) : Promise.resolve();
      }
      __name(loadMetaSchemaOf, "loadMetaSchemaOf");
      function _compileAsync(schemaObj) {
        try {
          return self2._compile(schemaObj);
        } catch (e2) {
          if (e2 instanceof MissingRefError) return loadMissingSchema(e2);
          throw e2;
        }
        function loadMissingSchema(e2) {
          var ref = e2.missingSchema;
          if (added(ref)) throw new Error("Schema " + ref + " is loaded but " + e2.missingRef + " cannot be resolved");
          var schemaPromise = self2._loadingSchemas[ref];
          if (!schemaPromise) {
            schemaPromise = self2._loadingSchemas[ref] = self2._opts.loadSchema(ref);
            schemaPromise.then(removePromise, removePromise);
          }
          return schemaPromise.then(function(sch) {
            if (!added(ref)) {
              return loadMetaSchemaOf(sch).then(function() {
                if (!added(ref)) self2.addSchema(sch, ref, void 0, meta);
              });
            }
          }).then(function() {
            return _compileAsync(schemaObj);
          });
          function removePromise() {
            delete self2._loadingSchemas[ref];
          }
          __name(removePromise, "removePromise");
          function added(ref2) {
            return self2._refs[ref2] || self2._schemas[ref2];
          }
          __name(added, "added");
        }
        __name(loadMissingSchema, "loadMissingSchema");
      }
      __name(_compileAsync, "_compileAsync");
    }
    __name(compileAsync, "compileAsync");
  }
});

// node_modules/ajv/lib/dotjs/custom.js
var require_custom = __commonJS({
  "node_modules/ajv/lib/dotjs/custom.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function generate_custom(it, $keyword, $ruleType) {
      var out = " ";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $errorKeyword;
      var $data = "data" + ($dataLvl || "");
      var $valid = "valid" + $lvl;
      var $errs = "errs__" + $lvl;
      var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
      if ($isData) {
        out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; ";
        $schemaValue = "schema" + $lvl;
      } else {
        $schemaValue = $schema;
      }
      var $rule = this, $definition = "definition" + $lvl, $rDef = $rule.definition, $closingBraces = "";
      var $compile, $inline, $macro, $ruleValidate, $validateCode;
      if ($isData && $rDef.$data) {
        $validateCode = "keywordValidate" + $lvl;
        var $validateSchema = $rDef.validateSchema;
        out += " var " + $definition + " = RULES.custom['" + $keyword + "'].definition; var " + $validateCode + " = " + $definition + ".validate;";
      } else {
        $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
        if (!$ruleValidate) return;
        $schemaValue = "validate.schema" + $schemaPath;
        $validateCode = $ruleValidate.code;
        $compile = $rDef.compile;
        $inline = $rDef.inline;
        $macro = $rDef.macro;
      }
      var $ruleErrs = $validateCode + ".errors", $i = "i" + $lvl, $ruleErr = "ruleErr" + $lvl, $asyncKeyword = $rDef.async;
      if ($asyncKeyword && !it.async) throw new Error("async keyword in sync schema");
      if (!($inline || $macro)) {
        out += "" + $ruleErrs + " = null;";
      }
      out += "var " + $errs + " = errors;var " + $valid + ";";
      if ($isData && $rDef.$data) {
        $closingBraces += "}";
        out += " if (" + $schemaValue + " === undefined) { " + $valid + " = true; } else { ";
        if ($validateSchema) {
          $closingBraces += "}";
          out += " " + $valid + " = " + $definition + ".validateSchema(" + $schemaValue + "); if (" + $valid + ") { ";
        }
      }
      if ($inline) {
        if ($rDef.statements) {
          out += " " + $ruleValidate.validate + " ";
        } else {
          out += " " + $valid + " = " + $ruleValidate.validate + "; ";
        }
      } else if ($macro) {
        var $it = it.util.copy(it);
        var $closingBraces = "";
        $it.level++;
        var $nextValid = "valid" + $it.level;
        $it.schema = $ruleValidate.validate;
        $it.schemaPath = "";
        var $wasComposite = it.compositeRule;
        it.compositeRule = $it.compositeRule = true;
        var $code = it.validate($it).replace(/validate\.schema/g, $validateCode);
        it.compositeRule = $it.compositeRule = $wasComposite;
        out += " " + $code;
      } else {
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = "";
        out += "  " + $validateCode + ".call( ";
        if (it.opts.passContext) {
          out += "this";
        } else {
          out += "self";
        }
        if ($compile || $rDef.schema === false) {
          out += " , " + $data + " ";
        } else {
          out += " , " + $schemaValue + " , " + $data + " , validate.schema" + it.schemaPath + " ";
        }
        out += " , (dataPath || '')";
        if (it.errorPath != '""') {
          out += " + " + it.errorPath;
        }
        var $parentData = $dataLvl ? "data" + ($dataLvl - 1 || "") : "parentData", $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : "parentDataProperty";
        out += " , " + $parentData + " , " + $parentDataProperty + " , rootData )  ";
        var def_callRuleValidate = out;
        out = $$outStack.pop();
        if ($rDef.errors === false) {
          out += " " + $valid + " = ";
          if ($asyncKeyword) {
            out += "await ";
          }
          out += "" + def_callRuleValidate + "; ";
        } else {
          if ($asyncKeyword) {
            $ruleErrs = "customErrors" + $lvl;
            out += " var " + $ruleErrs + " = null; try { " + $valid + " = await " + def_callRuleValidate + "; } catch (e) { " + $valid + " = false; if (e instanceof ValidationError) " + $ruleErrs + " = e.errors; else throw e; } ";
          } else {
            out += " " + $ruleErrs + " = null; " + $valid + " = " + def_callRuleValidate + "; ";
          }
        }
      }
      if ($rDef.modifying) {
        out += " if (" + $parentData + ") " + $data + " = " + $parentData + "[" + $parentDataProperty + "];";
      }
      out += "" + $closingBraces;
      if ($rDef.valid) {
        if ($breakOnError) {
          out += " if (true) { ";
        }
      } else {
        out += " if ( ";
        if ($rDef.valid === void 0) {
          out += " !";
          if ($macro) {
            out += "" + $nextValid;
          } else {
            out += "" + $valid;
          }
        } else {
          out += " " + !$rDef.valid + " ";
        }
        out += ") { ";
        $errorKeyword = $rule.keyword;
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = "";
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = "";
        if (it.createErrors !== false) {
          out += " { keyword: '" + ($errorKeyword || "custom") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { keyword: '" + $rule.keyword + "' } ";
          if (it.opts.messages !== false) {
            out += ` , message: 'should pass "` + $rule.keyword + `" keyword validation' `;
          }
          if (it.opts.verbose) {
            out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          if (it.async) {
            out += " throw new ValidationError([" + __err + "]); ";
          } else {
            out += " validate.errors = [" + __err + "]; return false; ";
          }
        } else {
          out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
        }
        var def_customError = out;
        out = $$outStack.pop();
        if ($inline) {
          if ($rDef.errors) {
            if ($rDef.errors != "full") {
              out += "  for (var " + $i + "=" + $errs + "; " + $i + "<errors; " + $i + "++) { var " + $ruleErr + " = vErrors[" + $i + "]; if (" + $ruleErr + ".dataPath === undefined) " + $ruleErr + ".dataPath = (dataPath || '') + " + it.errorPath + "; if (" + $ruleErr + ".schemaPath === undefined) { " + $ruleErr + '.schemaPath = "' + $errSchemaPath + '"; } ';
              if (it.opts.verbose) {
                out += " " + $ruleErr + ".schema = " + $schemaValue + "; " + $ruleErr + ".data = " + $data + "; ";
              }
              out += " } ";
            }
          } else {
            if ($rDef.errors === false) {
              out += " " + def_customError + " ";
            } else {
              out += " if (" + $errs + " == errors) { " + def_customError + " } else {  for (var " + $i + "=" + $errs + "; " + $i + "<errors; " + $i + "++) { var " + $ruleErr + " = vErrors[" + $i + "]; if (" + $ruleErr + ".dataPath === undefined) " + $ruleErr + ".dataPath = (dataPath || '') + " + it.errorPath + "; if (" + $ruleErr + ".schemaPath === undefined) { " + $ruleErr + '.schemaPath = "' + $errSchemaPath + '"; } ';
              if (it.opts.verbose) {
                out += " " + $ruleErr + ".schema = " + $schemaValue + "; " + $ruleErr + ".data = " + $data + "; ";
              }
              out += " } } ";
            }
          }
        } else if ($macro) {
          out += "   var err =   ";
          if (it.createErrors !== false) {
            out += " { keyword: '" + ($errorKeyword || "custom") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { keyword: '" + $rule.keyword + "' } ";
            if (it.opts.messages !== false) {
              out += ` , message: 'should pass "` + $rule.keyword + `" keyword validation' `;
            }
            if (it.opts.verbose) {
              out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
            }
            out += " } ";
          } else {
            out += " {} ";
          }
          out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
          if (!it.compositeRule && $breakOnError) {
            if (it.async) {
              out += " throw new ValidationError(vErrors); ";
            } else {
              out += " validate.errors = vErrors; return false; ";
            }
          }
        } else {
          if ($rDef.errors === false) {
            out += " " + def_customError + " ";
          } else {
            out += " if (Array.isArray(" + $ruleErrs + ")) { if (vErrors === null) vErrors = " + $ruleErrs + "; else vErrors = vErrors.concat(" + $ruleErrs + "); errors = vErrors.length;  for (var " + $i + "=" + $errs + "; " + $i + "<errors; " + $i + "++) { var " + $ruleErr + " = vErrors[" + $i + "]; if (" + $ruleErr + ".dataPath === undefined) " + $ruleErr + ".dataPath = (dataPath || '') + " + it.errorPath + ";  " + $ruleErr + '.schemaPath = "' + $errSchemaPath + '";  ';
            if (it.opts.verbose) {
              out += " " + $ruleErr + ".schema = " + $schemaValue + "; " + $ruleErr + ".data = " + $data + "; ";
            }
            out += " } } else { " + def_customError + " } ";
          }
        }
        out += " } ";
        if ($breakOnError) {
          out += " else { ";
        }
      }
      return out;
    }, "generate_custom");
  }
});

// node_modules/ajv/lib/refs/json-schema-draft-07.json
var require_json_schema_draft_073 = __commonJS({
  "node_modules/ajv/lib/refs/json-schema-draft-07.json"(exports2, module2) {
    module2.exports = {
      $schema: "http://json-schema.org/draft-07/schema#",
      $id: "http://json-schema.org/draft-07/schema#",
      title: "Core schema meta-schema",
      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: []
        }
      },
      type: ["object", "boolean"],
      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: "#" }
      },
      default: true
    };
  }
});

// node_modules/ajv/lib/definition_schema.js
var require_definition_schema = __commonJS({
  "node_modules/ajv/lib/definition_schema.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var metaSchema = require_json_schema_draft_073();
    module2.exports = {
      $id: "https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",
      definitions: {
        simpleTypes: metaSchema.definitions.simpleTypes
      },
      type: "object",
      dependencies: {
        schema: ["validate"],
        $data: ["validate"],
        statements: ["inline"],
        valid: { not: { required: ["macro"] } }
      },
      properties: {
        type: metaSchema.properties.type,
        schema: { type: "boolean" },
        statements: { type: "boolean" },
        dependencies: {
          type: "array",
          items: { type: "string" }
        },
        metaSchema: { type: "object" },
        modifying: { type: "boolean" },
        valid: { type: "boolean" },
        $data: { type: "boolean" },
        async: { type: "boolean" },
        errors: {
          anyOf: [
            { type: "boolean" },
            { const: "full" }
          ]
        }
      }
    };
  }
});

// node_modules/ajv/lib/keyword.js
var require_keyword3 = __commonJS({
  "node_modules/ajv/lib/keyword.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var IDENTIFIER2 = /^[a-z_$][a-z0-9_$-]*$/i;
    var customRuleCode = require_custom();
    var definitionSchema = require_definition_schema();
    module2.exports = {
      add: addKeyword,
      get: getKeyword,
      remove: removeKeyword,
      validate: validateKeyword
    };
    function addKeyword(keyword, definition) {
      var RULES = this.RULES;
      if (RULES.keywords[keyword])
        throw new Error("Keyword " + keyword + " is already defined");
      if (!IDENTIFIER2.test(keyword))
        throw new Error("Keyword " + keyword + " is not a valid identifier");
      if (definition) {
        this.validateKeyword(definition, true);
        var dataType = definition.type;
        if (Array.isArray(dataType)) {
          for (var i = 0; i < dataType.length; i++)
            _addRule(keyword, dataType[i], definition);
        } else {
          _addRule(keyword, dataType, definition);
        }
        var metaSchema = definition.metaSchema;
        if (metaSchema) {
          if (definition.$data && this._opts.$data) {
            metaSchema = {
              anyOf: [
                metaSchema,
                { "$ref": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }
              ]
            };
          }
          definition.validateSchema = this.compile(metaSchema, true);
        }
      }
      RULES.keywords[keyword] = RULES.all[keyword] = true;
      function _addRule(keyword2, dataType2, definition2) {
        var ruleGroup;
        for (var i2 = 0; i2 < RULES.length; i2++) {
          var rg = RULES[i2];
          if (rg.type == dataType2) {
            ruleGroup = rg;
            break;
          }
        }
        if (!ruleGroup) {
          ruleGroup = { type: dataType2, rules: [] };
          RULES.push(ruleGroup);
        }
        var rule = {
          keyword: keyword2,
          definition: definition2,
          custom: true,
          code: customRuleCode,
          implements: definition2.implements
        };
        ruleGroup.rules.push(rule);
        RULES.custom[keyword2] = rule;
      }
      __name(_addRule, "_addRule");
      return this;
    }
    __name(addKeyword, "addKeyword");
    function getKeyword(keyword) {
      var rule = this.RULES.custom[keyword];
      return rule ? rule.definition : this.RULES.keywords[keyword] || false;
    }
    __name(getKeyword, "getKeyword");
    function removeKeyword(keyword) {
      var RULES = this.RULES;
      delete RULES.keywords[keyword];
      delete RULES.all[keyword];
      delete RULES.custom[keyword];
      for (var i = 0; i < RULES.length; i++) {
        var rules = RULES[i].rules;
        for (var j = 0; j < rules.length; j++) {
          if (rules[j].keyword == keyword) {
            rules.splice(j, 1);
            break;
          }
        }
      }
      return this;
    }
    __name(removeKeyword, "removeKeyword");
    function validateKeyword(definition, throwError) {
      validateKeyword.errors = null;
      var v = this._validateKeyword = this._validateKeyword || this.compile(definitionSchema, true);
      if (v(definition)) return true;
      validateKeyword.errors = v.errors;
      if (throwError)
        throw new Error("custom keyword definition is invalid: " + this.errorsText(v.errors));
      else
        return false;
    }
    __name(validateKeyword, "validateKeyword");
  }
});

// node_modules/ajv/lib/refs/data.json
var require_data4 = __commonJS({
  "node_modules/ajv/lib/refs/data.json"(exports2, module2) {
    module2.exports = {
      $schema: "http://json-schema.org/draft-07/schema#",
      $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
      description: "Meta-schema for $data reference (JSON Schema extension proposal)",
      type: "object",
      required: ["$data"],
      properties: {
        $data: {
          type: "string",
          anyOf: [
            { format: "relative-json-pointer" },
            { format: "json-pointer" }
          ]
        }
      },
      additionalProperties: false
    };
  }
});

// node_modules/ajv/lib/ajv.js
var require_ajv3 = __commonJS({
  "node_modules/ajv/lib/ajv.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var compileSchema = require_compile3();
    var resolve24 = require_resolve4();
    var Cache = require_cache4();
    var SchemaObject = require_schema_obj();
    var stableStringify = require_fast_json_stable_stringify();
    var formats = require_formats2();
    var rules = require_rules3();
    var $dataMetaSchema = require_data3();
    var util4 = require_util15();
    module2.exports = Ajv2;
    Ajv2.prototype.validate = validate4;
    Ajv2.prototype.compile = compile2;
    Ajv2.prototype.addSchema = addSchema;
    Ajv2.prototype.addMetaSchema = addMetaSchema;
    Ajv2.prototype.validateSchema = validateSchema;
    Ajv2.prototype.getSchema = getSchema;
    Ajv2.prototype.removeSchema = removeSchema;
    Ajv2.prototype.addFormat = addFormat;
    Ajv2.prototype.errorsText = errorsText;
    Ajv2.prototype._addSchema = _addSchema;
    Ajv2.prototype._compile = _compile;
    Ajv2.prototype.compileAsync = require_async2();
    var customKeyword = require_keyword3();
    Ajv2.prototype.addKeyword = customKeyword.add;
    Ajv2.prototype.getKeyword = customKeyword.get;
    Ajv2.prototype.removeKeyword = customKeyword.remove;
    Ajv2.prototype.validateKeyword = customKeyword.validate;
    var errorClasses = require_error_classes();
    Ajv2.ValidationError = errorClasses.Validation;
    Ajv2.MissingRefError = errorClasses.MissingRef;
    Ajv2.$dataMetaSchema = $dataMetaSchema;
    var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
    var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes", "strictDefaults"];
    var META_SUPPORT_DATA = ["/properties"];
    function Ajv2(opts) {
      if (!(this instanceof Ajv2)) return new Ajv2(opts);
      opts = this._opts = util4.copy(opts) || {};
      setLogger(this);
      this._schemas = {};
      this._refs = {};
      this._fragments = {};
      this._formats = formats(opts.format);
      this._cache = opts.cache || new Cache();
      this._loadingSchemas = {};
      this._compilations = [];
      this.RULES = rules();
      this._getId = chooseGetId(opts);
      opts.loopRequired = opts.loopRequired || Infinity;
      if (opts.errorDataPath == "property") opts._errorDataPathProperty = true;
      if (opts.serialize === void 0) opts.serialize = stableStringify;
      this._metaOpts = getMetaSchemaOptions(this);
      if (opts.formats) addInitialFormats(this);
      if (opts.keywords) addInitialKeywords(this);
      addDefaultMetaSchema(this);
      if (typeof opts.meta == "object") this.addMetaSchema(opts.meta);
      if (opts.nullable) this.addKeyword("nullable", { metaSchema: { type: "boolean" } });
      addInitialSchemas(this);
    }
    __name(Ajv2, "Ajv");
    function validate4(schemaKeyRef, data) {
      var v;
      if (typeof schemaKeyRef == "string") {
        v = this.getSchema(schemaKeyRef);
        if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
      } else {
        var schemaObj = this._addSchema(schemaKeyRef);
        v = schemaObj.validate || this._compile(schemaObj);
      }
      var valid = v(data);
      if (v.$async !== true) this.errors = v.errors;
      return valid;
    }
    __name(validate4, "validate");
    function compile2(schema, _meta) {
      var schemaObj = this._addSchema(schema, void 0, _meta);
      return schemaObj.validate || this._compile(schemaObj);
    }
    __name(compile2, "compile");
    function addSchema(schema, key, _skipValidation, _meta) {
      if (Array.isArray(schema)) {
        for (var i = 0; i < schema.length; i++) this.addSchema(schema[i], void 0, _skipValidation, _meta);
        return this;
      }
      var id = this._getId(schema);
      if (id !== void 0 && typeof id != "string")
        throw new Error("schema id must be string");
      key = resolve24.normalizeId(key || id);
      checkUnique(this, key);
      this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
      return this;
    }
    __name(addSchema, "addSchema");
    function addMetaSchema(schema, key, skipValidation) {
      this.addSchema(schema, key, skipValidation, true);
      return this;
    }
    __name(addMetaSchema, "addMetaSchema");
    function validateSchema(schema, throwOrLogError) {
      var $schema = schema.$schema;
      if ($schema !== void 0 && typeof $schema != "string")
        throw new Error("$schema must be a string");
      $schema = $schema || this._opts.defaultMeta || defaultMeta(this);
      if (!$schema) {
        this.logger.warn("meta-schema not available");
        this.errors = null;
        return true;
      }
      var valid = this.validate($schema, schema);
      if (!valid && throwOrLogError) {
        var message = "schema is invalid: " + this.errorsText();
        if (this._opts.validateSchema == "log") this.logger.error(message);
        else throw new Error(message);
      }
      return valid;
    }
    __name(validateSchema, "validateSchema");
    function defaultMeta(self2) {
      var meta = self2._opts.meta;
      self2._opts.defaultMeta = typeof meta == "object" ? self2._getId(meta) || meta : self2.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0;
      return self2._opts.defaultMeta;
    }
    __name(defaultMeta, "defaultMeta");
    function getSchema(keyRef) {
      var schemaObj = _getSchemaObj(this, keyRef);
      switch (typeof schemaObj) {
        case "object":
          return schemaObj.validate || this._compile(schemaObj);
        case "string":
          return this.getSchema(schemaObj);
        case "undefined":
          return _getSchemaFragment(this, keyRef);
      }
    }
    __name(getSchema, "getSchema");
    function _getSchemaFragment(self2, ref) {
      var res = resolve24.schema.call(self2, { schema: {} }, ref);
      if (res) {
        var schema = res.schema, root = res.root, baseId = res.baseId;
        var v = compileSchema.call(self2, schema, root, void 0, baseId);
        self2._fragments[ref] = new SchemaObject({
          ref,
          fragment: true,
          schema,
          root,
          baseId,
          validate: v
        });
        return v;
      }
    }
    __name(_getSchemaFragment, "_getSchemaFragment");
    function _getSchemaObj(self2, keyRef) {
      keyRef = resolve24.normalizeId(keyRef);
      return self2._schemas[keyRef] || self2._refs[keyRef] || self2._fragments[keyRef];
    }
    __name(_getSchemaObj, "_getSchemaObj");
    function removeSchema(schemaKeyRef) {
      if (schemaKeyRef instanceof RegExp) {
        _removeAllSchemas(this, this._schemas, schemaKeyRef);
        _removeAllSchemas(this, this._refs, schemaKeyRef);
        return this;
      }
      switch (typeof schemaKeyRef) {
        case "undefined":
          _removeAllSchemas(this, this._schemas);
          _removeAllSchemas(this, this._refs);
          this._cache.clear();
          return this;
        case "string":
          var schemaObj = _getSchemaObj(this, schemaKeyRef);
          if (schemaObj) this._cache.del(schemaObj.cacheKey);
          delete this._schemas[schemaKeyRef];
          delete this._refs[schemaKeyRef];
          return this;
        case "object":
          var serialize2 = this._opts.serialize;
          var cacheKey = serialize2 ? serialize2(schemaKeyRef) : schemaKeyRef;
          this._cache.del(cacheKey);
          var id = this._getId(schemaKeyRef);
          if (id) {
            id = resolve24.normalizeId(id);
            delete this._schemas[id];
            delete this._refs[id];
          }
      }
      return this;
    }
    __name(removeSchema, "removeSchema");
    function _removeAllSchemas(self2, schemas, regex3) {
      for (var keyRef in schemas) {
        var schemaObj = schemas[keyRef];
        if (!schemaObj.meta && (!regex3 || regex3.test(keyRef))) {
          self2._cache.del(schemaObj.cacheKey);
          delete schemas[keyRef];
        }
      }
    }
    __name(_removeAllSchemas, "_removeAllSchemas");
    function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
      if (typeof schema != "object" && typeof schema != "boolean")
        throw new Error("schema should be object or boolean");
      var serialize2 = this._opts.serialize;
      var cacheKey = serialize2 ? serialize2(schema) : schema;
      var cached = this._cache.get(cacheKey);
      if (cached) return cached;
      shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;
      var id = resolve24.normalizeId(this._getId(schema));
      if (id && shouldAddSchema) checkUnique(this, id);
      var willValidate = this._opts.validateSchema !== false && !skipValidation;
      var recursiveMeta;
      if (willValidate && !(recursiveMeta = id && id == resolve24.normalizeId(schema.$schema)))
        this.validateSchema(schema, true);
      var localRefs = resolve24.ids.call(this, schema);
      var schemaObj = new SchemaObject({
        id,
        schema,
        localRefs,
        cacheKey,
        meta
      });
      if (id[0] != "#" && shouldAddSchema) this._refs[id] = schemaObj;
      this._cache.put(cacheKey, schemaObj);
      if (willValidate && recursiveMeta) this.validateSchema(schema, true);
      return schemaObj;
    }
    __name(_addSchema, "_addSchema");
    function _compile(schemaObj, root) {
      if (schemaObj.compiling) {
        schemaObj.validate = callValidate;
        callValidate.schema = schemaObj.schema;
        callValidate.errors = null;
        callValidate.root = root ? root : callValidate;
        if (schemaObj.schema.$async === true)
          callValidate.$async = true;
        return callValidate;
      }
      schemaObj.compiling = true;
      var currentOpts;
      if (schemaObj.meta) {
        currentOpts = this._opts;
        this._opts = this._metaOpts;
      }
      var v;
      try {
        v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs);
      } catch (e2) {
        delete schemaObj.validate;
        throw e2;
      } finally {
        schemaObj.compiling = false;
        if (schemaObj.meta) this._opts = currentOpts;
      }
      schemaObj.validate = v;
      schemaObj.refs = v.refs;
      schemaObj.refVal = v.refVal;
      schemaObj.root = v.root;
      return v;
      function callValidate() {
        var _validate = schemaObj.validate;
        var result = _validate.apply(this, arguments);
        callValidate.errors = _validate.errors;
        return result;
      }
      __name(callValidate, "callValidate");
    }
    __name(_compile, "_compile");
    function chooseGetId(opts) {
      switch (opts.schemaId) {
        case "auto":
          return _get$IdOrId;
        case "id":
          return _getId;
        default:
          return _get$Id;
      }
    }
    __name(chooseGetId, "chooseGetId");
    function _getId(schema) {
      if (schema.$id) this.logger.warn("schema $id ignored", schema.$id);
      return schema.id;
    }
    __name(_getId, "_getId");
    function _get$Id(schema) {
      if (schema.id) this.logger.warn("schema id ignored", schema.id);
      return schema.$id;
    }
    __name(_get$Id, "_get$Id");
    function _get$IdOrId(schema) {
      if (schema.$id && schema.id && schema.$id != schema.id)
        throw new Error("schema $id is different from id");
      return schema.$id || schema.id;
    }
    __name(_get$IdOrId, "_get$IdOrId");
    function errorsText(errors, options2) {
      errors = errors || this.errors;
      if (!errors) return "No errors";
      options2 = options2 || {};
      var separator = options2.separator === void 0 ? ", " : options2.separator;
      var dataVar = options2.dataVar === void 0 ? "data" : options2.dataVar;
      var text = "";
      for (var i = 0; i < errors.length; i++) {
        var e2 = errors[i];
        if (e2) text += dataVar + e2.dataPath + " " + e2.message + separator;
      }
      return text.slice(0, -separator.length);
    }
    __name(errorsText, "errorsText");
    function addFormat(name3, format4) {
      if (typeof format4 == "string") format4 = new RegExp(format4);
      this._formats[name3] = format4;
      return this;
    }
    __name(addFormat, "addFormat");
    function addDefaultMetaSchema(self2) {
      var $dataSchema;
      if (self2._opts.$data) {
        $dataSchema = require_data4();
        self2.addMetaSchema($dataSchema, $dataSchema.$id, true);
      }
      if (self2._opts.meta === false) return;
      var metaSchema = require_json_schema_draft_073();
      if (self2._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
      self2.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
      self2._refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
    }
    __name(addDefaultMetaSchema, "addDefaultMetaSchema");
    function addInitialSchemas(self2) {
      var optsSchemas = self2._opts.schemas;
      if (!optsSchemas) return;
      if (Array.isArray(optsSchemas)) self2.addSchema(optsSchemas);
      else for (var key in optsSchemas) self2.addSchema(optsSchemas[key], key);
    }
    __name(addInitialSchemas, "addInitialSchemas");
    function addInitialFormats(self2) {
      for (var name3 in self2._opts.formats) {
        var format4 = self2._opts.formats[name3];
        self2.addFormat(name3, format4);
      }
    }
    __name(addInitialFormats, "addInitialFormats");
    function addInitialKeywords(self2) {
      for (var name3 in self2._opts.keywords) {
        var keyword = self2._opts.keywords[name3];
        self2.addKeyword(name3, keyword);
      }
    }
    __name(addInitialKeywords, "addInitialKeywords");
    function checkUnique(self2, id) {
      if (self2._schemas[id] || self2._refs[id])
        throw new Error('schema with key or id "' + id + '" already exists');
    }
    __name(checkUnique, "checkUnique");
    function getMetaSchemaOptions(self2) {
      var metaOpts = util4.copy(self2._opts);
      for (var i = 0; i < META_IGNORE_OPTIONS.length; i++)
        delete metaOpts[META_IGNORE_OPTIONS[i]];
      return metaOpts;
    }
    __name(getMetaSchemaOptions, "getMetaSchemaOptions");
    function setLogger(self2) {
      var logger6 = self2._opts.logger;
      if (logger6 === false) {
        self2.logger = { log: noop6, warn: noop6, error: noop6 };
      } else {
        if (logger6 === void 0) logger6 = console;
        if (!(typeof logger6 == "object" && logger6.log && logger6.warn && logger6.error))
          throw new Error("logger must implement log, warn and error methods");
        self2.logger = logger6;
      }
    }
    __name(setLogger, "setLogger");
    function noop6() {
    }
    __name(noop6, "noop");
  }
});

// node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
var import_ajv2, Client;
var init_client3 = __esm({
  "node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"() {
    init_esbuild_shims();
    init_protocol();
    init_types9();
    import_ajv2 = __toESM(require_ajv3(), 1);
    Client = class extends Protocol {
      static {
        __name(this, "Client");
      }
      /**
       * Initializes this client with the given name and version information.
       */
      constructor(_clientInfo, options2) {
        var _a6;
        super(options2);
        this._clientInfo = _clientInfo;
        this._cachedToolOutputValidators = /* @__PURE__ */ new Map();
        this._capabilities = (_a6 = options2 === null || options2 === void 0 ? void 0 : options2.capabilities) !== null && _a6 !== void 0 ? _a6 : {};
        this._ajv = new import_ajv2.default();
      }
      /**
       * 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);
      }
      assertCapability(capability, method) {
        var _a6;
        if (!((_a6 = this._serverCapabilities) === null || _a6 === void 0 ? void 0 : _a6[capability])) {
          throw new Error(`Server does not support ${capability} (required for ${method})`);
        }
      }
      async connect(transport, options2) {
        await super.connect(transport);
        if (transport.sessionId !== void 0) {
          return;
        }
        try {
          const result = await this.request({
            method: "initialize",
            params: {
              protocolVersion: LATEST_PROTOCOL_VERSION,
              capabilities: this._capabilities,
              clientInfo: this._clientInfo
            }
          }, InitializeResultSchema, options2);
          if (result === void 0) {
            throw new Error(`Server sent invalid initialize result: ${result}`);
          }
          if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
            throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);
          }
          this._serverCapabilities = result.capabilities;
          this._serverVersion = result.serverInfo;
          if (transport.setProtocolVersion) {
            transport.setProtocolVersion(result.protocolVersion);
          }
          this._instructions = result.instructions;
          await this.notification({
            method: "notifications/initialized"
          });
        } catch (error) {
          void this.close();
          throw error;
        }
      }
      /**
       * After initialization has completed, this will be populated with the server's reported capabilities.
       */
      getServerCapabilities() {
        return this._serverCapabilities;
      }
      /**
       * After initialization has completed, this will be populated with information about the server's name and version.
       */
      getServerVersion() {
        return this._serverVersion;
      }
      /**
       * After initialization has completed, this may be populated with information about the server's instructions.
       */
      getInstructions() {
        return this._instructions;
      }
      assertCapabilityForMethod(method) {
        var _a6, _b2, _c2, _d, _e;
        switch (method) {
          case "logging/setLevel":
            if (!((_a6 = this._serverCapabilities) === null || _a6 === void 0 ? void 0 : _a6.logging)) {
              throw new Error(`Server does not support logging (required for ${method})`);
            }
            break;
          case "prompts/get":
          case "prompts/list":
            if (!((_b2 = this._serverCapabilities) === null || _b2 === void 0 ? void 0 : _b2.prompts)) {
              throw new Error(`Server does not support prompts (required for ${method})`);
            }
            break;
          case "resources/list":
          case "resources/templates/list":
          case "resources/read":
          case "resources/subscribe":
          case "resources/unsubscribe":
            if (!((_c2 = this._serverCapabilities) === null || _c2 === void 0 ? void 0 : _c2.resources)) {
              throw new Error(`Server does not support resources (required for ${method})`);
            }
            if (method === "resources/subscribe" && !this._serverCapabilities.resources.subscribe) {
              throw new Error(`Server does not support resource subscriptions (required for ${method})`);
            }
            break;
          case "tools/call":
          case "tools/list":
            if (!((_d = this._serverCapabilities) === null || _d === void 0 ? void 0 : _d.tools)) {
              throw new Error(`Server does not support tools (required for ${method})`);
            }
            break;
          case "completion/complete":
            if (!((_e = this._serverCapabilities) === null || _e === void 0 ? void 0 : _e.completions)) {
              throw new Error(`Server does not support completions (required for ${method})`);
            }
            break;
          case "initialize":
            break;
          case "ping":
            break;
        }
      }
      assertNotificationCapability(method) {
        var _a6;
        switch (method) {
          case "notifications/roots/list_changed":
            if (!((_a6 = this._capabilities.roots) === null || _a6 === void 0 ? void 0 : _a6.listChanged)) {
              throw new Error(`Client does not support roots list changed notifications (required for ${method})`);
            }
            break;
          case "notifications/initialized":
            break;
          case "notifications/cancelled":
            break;
          case "notifications/progress":
            break;
        }
      }
      assertRequestHandlerCapability(method) {
        switch (method) {
          case "sampling/createMessage":
            if (!this._capabilities.sampling) {
              throw new Error(`Client does not support sampling capability (required for ${method})`);
            }
            break;
          case "elicitation/create":
            if (!this._capabilities.elicitation) {
              throw new Error(`Client does not support elicitation capability (required for ${method})`);
            }
            break;
          case "roots/list":
            if (!this._capabilities.roots) {
              throw new Error(`Client does not support roots capability (required for ${method})`);
            }
            break;
          case "ping":
            break;
        }
      }
      async ping(options2) {
        return this.request({ method: "ping" }, EmptyResultSchema, options2);
      }
      async complete(params, options2) {
        return this.request({ method: "completion/complete", params }, CompleteResultSchema, options2);
      }
      async setLoggingLevel(level, options2) {
        return this.request({ method: "logging/setLevel", params: { level } }, EmptyResultSchema, options2);
      }
      async getPrompt(params, options2) {
        return this.request({ method: "prompts/get", params }, GetPromptResultSchema, options2);
      }
      async listPrompts(params, options2) {
        return this.request({ method: "prompts/list", params }, ListPromptsResultSchema, options2);
      }
      async listResources(params, options2) {
        return this.request({ method: "resources/list", params }, ListResourcesResultSchema, options2);
      }
      async listResourceTemplates(params, options2) {
        return this.request({ method: "resources/templates/list", params }, ListResourceTemplatesResultSchema, options2);
      }
      async readResource(params, options2) {
        return this.request({ method: "resources/read", params }, ReadResourceResultSchema, options2);
      }
      async subscribeResource(params, options2) {
        return this.request({ method: "resources/subscribe", params }, EmptyResultSchema, options2);
      }
      async unsubscribeResource(params, options2) {
        return this.request({ method: "resources/unsubscribe", params }, EmptyResultSchema, options2);
      }
      async callTool(params, resultSchema = CallToolResultSchema, options2) {
        const result = await this.request({ method: "tools/call", params }, resultSchema, options2);
        const validator = this.getToolOutputValidator(params.name);
        if (validator) {
          if (!result.structuredContent && !result.isError) {
            throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);
          }
          if (result.structuredContent) {
            try {
              const isValid2 = validator(result.structuredContent);
              if (!isValid2) {
                throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${this._ajv.errorsText(validator.errors)}`);
              }
            } catch (error) {
              if (error instanceof McpError) {
                throw error;
              }
              throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);
            }
          }
        }
        return result;
      }
      cacheToolOutputSchemas(tools) {
        this._cachedToolOutputValidators.clear();
        for (const tool of tools) {
          if (tool.outputSchema) {
            try {
              const validator = this._ajv.compile(tool.outputSchema);
              this._cachedToolOutputValidators.set(tool.name, validator);
            } catch (_a6) {
            }
          }
        }
      }
      getToolOutputValidator(toolName) {
        return this._cachedToolOutputValidators.get(toolName);
      }
      async listTools(params, options2) {
        const result = await this.request({ method: "tools/list", params }, ListToolsResultSchema, options2);
        this.cacheToolOutputSchemas(result.tools);
        return result;
      }
      async sendRootsListChanged() {
        return this.notification({ method: "notifications/roots/list_changed" });
      }
    };
  }
});

// node_modules/pkce-challenge/dist/index.node.js
async function getRandomValues(size) {
  return (await crypto13).getRandomValues(new Uint8Array(size));
}
async function random(size) {
  const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
  let result = "";
  const randomUints = await getRandomValues(size);
  for (let i = 0; i < size; i++) {
    const randomIndex = randomUints[i] % mask.length;
    result += mask[randomIndex];
  }
  return result;
}
async function generateVerifier(length) {
  return await random(length);
}
async function generateChallenge(code_verifier) {
  const buffer = await (await crypto13).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier));
  return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, "");
}
async function pkceChallenge(length) {
  if (!length)
    length = 43;
  if (length < 43 || length > 128) {
    throw `Expected a length between 43 and 128. Received ${length}.`;
  }
  const verifier = await generateVerifier(length);
  const challenge = await generateChallenge(verifier);
  return {
    code_verifier: verifier,
    code_challenge: challenge
  };
}
var crypto13;
var init_index_node = __esm({
  "node_modules/pkce-challenge/dist/index.node.js"() {
    init_esbuild_shims();
    crypto13 = globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL
    globalThis.crypto ?? // Node.js >18
    import("node:crypto").then((m) => m.webcrypto);
    __name(getRandomValues, "getRandomValues");
    __name(random, "random");
    __name(generateVerifier, "generateVerifier");
    __name(generateChallenge, "generateChallenge");
    __name(pkceChallenge, "pkceChallenge");
  }
});

// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js
var OAuthProtectedResourceMetadataSchema, OAuthMetadataSchema, OAuthTokensSchema, OAuthErrorResponseSchema, OAuthClientMetadataSchema, OAuthClientInformationSchema, OAuthClientInformationFullSchema, OAuthClientRegistrationErrorSchema, OAuthTokenRevocationRequestSchema;
var init_auth = __esm({
  "node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js"() {
    init_esbuild_shims();
    init_zod();
    OAuthProtectedResourceMetadataSchema = external_exports.object({
      resource: external_exports.string().url(),
      authorization_servers: external_exports.array(external_exports.string().url()).optional(),
      jwks_uri: external_exports.string().url().optional(),
      scopes_supported: external_exports.array(external_exports.string()).optional(),
      bearer_methods_supported: external_exports.array(external_exports.string()).optional(),
      resource_signing_alg_values_supported: external_exports.array(external_exports.string()).optional(),
      resource_name: external_exports.string().optional(),
      resource_documentation: external_exports.string().optional(),
      resource_policy_uri: external_exports.string().url().optional(),
      resource_tos_uri: external_exports.string().url().optional(),
      tls_client_certificate_bound_access_tokens: external_exports.boolean().optional(),
      authorization_details_types_supported: external_exports.array(external_exports.string()).optional(),
      dpop_signing_alg_values_supported: external_exports.array(external_exports.string()).optional(),
      dpop_bound_access_tokens_required: external_exports.boolean().optional()
    }).passthrough();
    OAuthMetadataSchema = external_exports.object({
      issuer: external_exports.string(),
      authorization_endpoint: external_exports.string(),
      token_endpoint: external_exports.string(),
      registration_endpoint: external_exports.string().optional(),
      scopes_supported: external_exports.array(external_exports.string()).optional(),
      response_types_supported: external_exports.array(external_exports.string()),
      response_modes_supported: external_exports.array(external_exports.string()).optional(),
      grant_types_supported: external_exports.array(external_exports.string()).optional(),
      token_endpoint_auth_methods_supported: external_exports.array(external_exports.string()).optional(),
      token_endpoint_auth_signing_alg_values_supported: external_exports.array(external_exports.string()).optional(),
      service_documentation: external_exports.string().optional(),
      revocation_endpoint: external_exports.string().optional(),
      revocation_endpoint_auth_methods_supported: external_exports.array(external_exports.string()).optional(),
      revocation_endpoint_auth_signing_alg_values_supported: external_exports.array(external_exports.string()).optional(),
      introspection_endpoint: external_exports.string().optional(),
      introspection_endpoint_auth_methods_supported: external_exports.array(external_exports.string()).optional(),
      introspection_endpoint_auth_signing_alg_values_supported: external_exports.array(external_exports.string()).optional(),
      code_challenge_methods_supported: external_exports.array(external_exports.string()).optional()
    }).passthrough();
    OAuthTokensSchema = external_exports.object({
      access_token: external_exports.string(),
      token_type: external_exports.string(),
      expires_in: external_exports.number().optional(),
      scope: external_exports.string().optional(),
      refresh_token: external_exports.string().optional()
    }).strip();
    OAuthErrorResponseSchema = external_exports.object({
      error: external_exports.string(),
      error_description: external_exports.string().optional(),
      error_uri: external_exports.string().optional()
    });
    OAuthClientMetadataSchema = external_exports.object({
      redirect_uris: external_exports.array(external_exports.string()).refine((uris) => uris.every((uri) => URL.canParse(uri)), { message: "redirect_uris must contain valid URLs" }),
      token_endpoint_auth_method: external_exports.string().optional(),
      grant_types: external_exports.array(external_exports.string()).optional(),
      response_types: external_exports.array(external_exports.string()).optional(),
      client_name: external_exports.string().optional(),
      client_uri: external_exports.string().optional(),
      logo_uri: external_exports.string().optional(),
      scope: external_exports.string().optional(),
      contacts: external_exports.array(external_exports.string()).optional(),
      tos_uri: external_exports.string().optional(),
      policy_uri: external_exports.string().optional(),
      jwks_uri: external_exports.string().optional(),
      jwks: external_exports.any().optional(),
      software_id: external_exports.string().optional(),
      software_version: external_exports.string().optional(),
      software_statement: external_exports.string().optional()
    }).strip();
    OAuthClientInformationSchema = external_exports.object({
      client_id: external_exports.string(),
      client_secret: external_exports.string().optional(),
      client_id_issued_at: external_exports.number().optional(),
      client_secret_expires_at: external_exports.number().optional()
    }).strip();
    OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
    OAuthClientRegistrationErrorSchema = external_exports.object({
      error: external_exports.string(),
      error_description: external_exports.string().optional()
    }).strip();
    OAuthTokenRevocationRequestSchema = external_exports.object({
      token: external_exports.string(),
      token_type_hint: external_exports.string().optional()
    }).strip();
  }
});

// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js
function resourceUrlFromServerUrl(url2) {
  const resourceURL = typeof url2 === "string" ? new URL(url2) : new URL(url2.href);
  resourceURL.hash = "";
  return resourceURL;
}
function checkResourceAllowed({ requestedResource, configuredResource }) {
  const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href);
  const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href);
  if (requested.origin !== configured.origin) {
    return false;
  }
  if (requested.pathname.length < configured.pathname.length) {
    return false;
  }
  const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/";
  const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/";
  return requestedPath.startsWith(configuredPath);
}
var init_auth_utils = __esm({
  "node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js"() {
    init_esbuild_shims();
    __name(resourceUrlFromServerUrl, "resourceUrlFromServerUrl");
    __name(checkResourceAllowed, "checkResourceAllowed");
  }
});

// node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
function selectClientAuthMethod(clientInformation, supportedMethods) {
  const hasClientSecret = clientInformation.client_secret !== void 0;
  if (supportedMethods.length === 0) {
    return hasClientSecret ? "client_secret_post" : "none";
  }
  if (hasClientSecret && supportedMethods.includes("client_secret_basic")) {
    return "client_secret_basic";
  }
  if (hasClientSecret && supportedMethods.includes("client_secret_post")) {
    return "client_secret_post";
  }
  if (supportedMethods.includes("none")) {
    return "none";
  }
  return hasClientSecret ? "client_secret_post" : "none";
}
function applyClientAuthentication(method, clientInformation, headers, params) {
  const { client_id, client_secret } = clientInformation;
  switch (method) {
    case "client_secret_basic":
      applyBasicAuth(client_id, client_secret, headers);
      return;
    case "client_secret_post":
      applyPostAuth(client_id, client_secret, params);
      return;
    case "none":
      applyPublicAuth(client_id, params);
      return;
    default:
      throw new Error(`Unsupported client authentication method: ${method}`);
  }
}
function applyBasicAuth(clientId, clientSecret, headers) {
  if (!clientSecret) {
    throw new Error("client_secret_basic authentication requires a client_secret");
  }
  const credentials = btoa(`${clientId}:${clientSecret}`);
  headers.set("Authorization", `Basic ${credentials}`);
}
function applyPostAuth(clientId, clientSecret, params) {
  params.set("client_id", clientId);
  if (clientSecret) {
    params.set("client_secret", clientSecret);
  }
}
function applyPublicAuth(clientId, params) {
  params.set("client_id", clientId);
}
async function auth(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl }) {
  let resourceMetadata;
  let authorizationServerUrl = serverUrl;
  try {
    resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl });
    if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {
      authorizationServerUrl = resourceMetadata.authorization_servers[0];
    }
  } catch (_a6) {
  }
  const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
  const metadata = await discoverOAuthMetadata(serverUrl, {
    authorizationServerUrl
  });
  let clientInformation = await Promise.resolve(provider.clientInformation());
  if (!clientInformation) {
    if (authorizationCode !== void 0) {
      throw new Error("Existing OAuth client information is required when exchanging an authorization code");
    }
    if (!provider.saveClientInformation) {
      throw new Error("OAuth client information must be saveable for dynamic registration");
    }
    const fullInformation = await registerClient(authorizationServerUrl, {
      metadata,
      clientMetadata: provider.clientMetadata
    });
    await provider.saveClientInformation(fullInformation);
    clientInformation = fullInformation;
  }
  if (authorizationCode !== void 0) {
    const codeVerifier2 = await provider.codeVerifier();
    const tokens2 = await exchangeAuthorization(authorizationServerUrl, {
      metadata,
      clientInformation,
      authorizationCode,
      codeVerifier: codeVerifier2,
      redirectUri: provider.redirectUrl,
      resource,
      addClientAuthentication: provider.addClientAuthentication
    });
    await provider.saveTokens(tokens2);
    return "AUTHORIZED";
  }
  const tokens = await provider.tokens();
  if (tokens === null || tokens === void 0 ? void 0 : tokens.refresh_token) {
    try {
      const newTokens = await refreshAuthorization(authorizationServerUrl, {
        metadata,
        clientInformation,
        refreshToken: tokens.refresh_token,
        resource,
        addClientAuthentication: provider.addClientAuthentication
      });
      await provider.saveTokens(newTokens);
      return "AUTHORIZED";
    } catch (_b2) {
    }
  }
  const state = provider.state ? await provider.state() : void 0;
  const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {
    metadata,
    clientInformation,
    state,
    redirectUrl: provider.redirectUrl,
    scope: scope || provider.clientMetadata.scope,
    resource
  });
  await provider.saveCodeVerifier(codeVerifier);
  await provider.redirectToAuthorization(authorizationUrl);
  return "REDIRECT";
}
async function selectResourceURL(serverUrl, provider, resourceMetadata) {
  const defaultResource = resourceUrlFromServerUrl(serverUrl);
  if (provider.validateResourceURL) {
    return await provider.validateResourceURL(defaultResource, resourceMetadata === null || resourceMetadata === void 0 ? void 0 : resourceMetadata.resource);
  }
  if (!resourceMetadata) {
    return void 0;
  }
  if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) {
    throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);
  }
  return new URL(resourceMetadata.resource);
}
function extractResourceMetadataUrl(res) {
  const authenticateHeader = res.headers.get("WWW-Authenticate");
  if (!authenticateHeader) {
    return void 0;
  }
  const [type, scheme] = authenticateHeader.split(" ");
  if (type.toLowerCase() !== "bearer" || !scheme) {
    return void 0;
  }
  const regex3 = /resource_metadata="([^"]*)"/;
  const match2 = regex3.exec(authenticateHeader);
  if (!match2) {
    return void 0;
  }
  try {
    return new URL(match2[1]);
  } catch (_a6) {
    return void 0;
  }
}
async function discoverOAuthProtectedResourceMetadata(serverUrl, opts) {
  const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", {
    protocolVersion: opts === null || opts === void 0 ? void 0 : opts.protocolVersion,
    metadataUrl: opts === null || opts === void 0 ? void 0 : opts.resourceMetadataUrl
  });
  if (!response || response.status === 404) {
    throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);
  }
  if (!response.ok) {
    throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);
  }
  return OAuthProtectedResourceMetadataSchema.parse(await response.json());
}
async function fetchWithCorsRetry(url2, headers) {
  try {
    return await fetch(url2, { headers });
  } catch (error) {
    if (error instanceof TypeError) {
      if (headers) {
        return fetchWithCorsRetry(url2);
      } else {
        return void 0;
      }
    }
    throw error;
  }
}
function buildWellKnownPath(wellKnownPrefix, pathname) {
  let wellKnownPath = `/.well-known/${wellKnownPrefix}${pathname}`;
  if (pathname.endsWith("/")) {
    wellKnownPath = wellKnownPath.slice(0, -1);
  }
  return wellKnownPath;
}
async function tryMetadataDiscovery(url2, protocolVersion) {
  const headers = {
    "MCP-Protocol-Version": protocolVersion
  };
  return await fetchWithCorsRetry(url2, headers);
}
function shouldAttemptFallback(response, pathname) {
  return !response || response.status === 404 && pathname !== "/";
}
async function discoverMetadataWithFallback(serverUrl, wellKnownType, opts) {
  var _a6, _b2;
  const issuer = new URL(serverUrl);
  const protocolVersion = (_a6 = opts === null || opts === void 0 ? void 0 : opts.protocolVersion) !== null && _a6 !== void 0 ? _a6 : LATEST_PROTOCOL_VERSION;
  let url2;
  if (opts === null || opts === void 0 ? void 0 : opts.metadataUrl) {
    url2 = new URL(opts.metadataUrl);
  } else {
    const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
    url2 = new URL(wellKnownPath, (_b2 = opts === null || opts === void 0 ? void 0 : opts.metadataServerUrl) !== null && _b2 !== void 0 ? _b2 : issuer);
    url2.search = issuer.search;
  }
  let response = await tryMetadataDiscovery(url2, protocolVersion);
  if (!(opts === null || opts === void 0 ? void 0 : opts.metadataUrl) && shouldAttemptFallback(response, issuer.pathname)) {
    const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);
    response = await tryMetadataDiscovery(rootUrl, protocolVersion);
  }
  return response;
}
async function discoverOAuthMetadata(issuer, { authorizationServerUrl, protocolVersion } = {}) {
  if (typeof issuer === "string") {
    issuer = new URL(issuer);
  }
  if (!authorizationServerUrl) {
    authorizationServerUrl = issuer;
  }
  if (typeof authorizationServerUrl === "string") {
    authorizationServerUrl = new URL(authorizationServerUrl);
  }
  protocolVersion !== null && protocolVersion !== void 0 ? protocolVersion : protocolVersion = LATEST_PROTOCOL_VERSION;
  const response = await discoverMetadataWithFallback(issuer, "oauth-authorization-server", {
    protocolVersion,
    metadataServerUrl: authorizationServerUrl
  });
  if (!response || response.status === 404) {
    return void 0;
  }
  if (!response.ok) {
    throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`);
  }
  return OAuthMetadataSchema.parse(await response.json());
}
async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {
  const responseType = "code";
  const codeChallengeMethod = "S256";
  let authorizationUrl;
  if (metadata) {
    authorizationUrl = new URL(metadata.authorization_endpoint);
    if (!metadata.response_types_supported.includes(responseType)) {
      throw new Error(`Incompatible auth server: does not support response type ${responseType}`);
    }
    if (!metadata.code_challenge_methods_supported || !metadata.code_challenge_methods_supported.includes(codeChallengeMethod)) {
      throw new Error(`Incompatible auth server: does not support code challenge method ${codeChallengeMethod}`);
    }
  } else {
    authorizationUrl = new URL("/authorize", authorizationServerUrl);
  }
  const challenge = await pkceChallenge();
  const codeVerifier = challenge.code_verifier;
  const codeChallenge = challenge.code_challenge;
  authorizationUrl.searchParams.set("response_type", responseType);
  authorizationUrl.searchParams.set("client_id", clientInformation.client_id);
  authorizationUrl.searchParams.set("code_challenge", codeChallenge);
  authorizationUrl.searchParams.set("code_challenge_method", codeChallengeMethod);
  authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl));
  if (state) {
    authorizationUrl.searchParams.set("state", state);
  }
  if (scope) {
    authorizationUrl.searchParams.set("scope", scope);
  }
  if (resource) {
    authorizationUrl.searchParams.set("resource", resource.href);
  }
  return { authorizationUrl, codeVerifier };
}
async function exchangeAuthorization(authorizationServerUrl, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication }) {
  var _a6;
  const grantType = "authorization_code";
  const tokenUrl = (metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint) ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl);
  if ((metadata === null || metadata === void 0 ? void 0 : metadata.grant_types_supported) && !metadata.grant_types_supported.includes(grantType)) {
    throw new Error(`Incompatible auth server: does not support grant type ${grantType}`);
  }
  const headers = new Headers({
    "Content-Type": "application/x-www-form-urlencoded"
  });
  const params = new URLSearchParams({
    grant_type: grantType,
    code: authorizationCode,
    code_verifier: codeVerifier,
    redirect_uri: String(redirectUri)
  });
  if (addClientAuthentication) {
    addClientAuthentication(headers, params, authorizationServerUrl, metadata);
  } else {
    const supportedMethods = (_a6 = metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint_auth_methods_supported) !== null && _a6 !== void 0 ? _a6 : [];
    const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
    applyClientAuthentication(authMethod, clientInformation, headers, params);
  }
  if (resource) {
    params.set("resource", resource.href);
  }
  const response = await fetch(tokenUrl, {
    method: "POST",
    headers,
    body: params
  });
  if (!response.ok) {
    throw new Error(`Token exchange failed: HTTP ${response.status}`);
  }
  return OAuthTokensSchema.parse(await response.json());
}
async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication }) {
  var _a6;
  const grantType = "refresh_token";
  let tokenUrl;
  if (metadata) {
    tokenUrl = new URL(metadata.token_endpoint);
    if (metadata.grant_types_supported && !metadata.grant_types_supported.includes(grantType)) {
      throw new Error(`Incompatible auth server: does not support grant type ${grantType}`);
    }
  } else {
    tokenUrl = new URL("/token", authorizationServerUrl);
  }
  const headers = new Headers({
    "Content-Type": "application/x-www-form-urlencoded"
  });
  const params = new URLSearchParams({
    grant_type: grantType,
    refresh_token: refreshToken
  });
  if (addClientAuthentication) {
    addClientAuthentication(headers, params, authorizationServerUrl, metadata);
  } else {
    const supportedMethods = (_a6 = metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint_auth_methods_supported) !== null && _a6 !== void 0 ? _a6 : [];
    const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
    applyClientAuthentication(authMethod, clientInformation, headers, params);
  }
  if (resource) {
    params.set("resource", resource.href);
  }
  const response = await fetch(tokenUrl, {
    method: "POST",
    headers,
    body: params
  });
  if (!response.ok) {
    throw new Error(`Token refresh failed: HTTP ${response.status}`);
  }
  return OAuthTokensSchema.parse({ refresh_token: refreshToken, ...await response.json() });
}
async function registerClient(authorizationServerUrl, { metadata, clientMetadata }) {
  let registrationUrl;
  if (metadata) {
    if (!metadata.registration_endpoint) {
      throw new Error("Incompatible auth server: does not support dynamic client registration");
    }
    registrationUrl = new URL(metadata.registration_endpoint);
  } else {
    registrationUrl = new URL("/register", authorizationServerUrl);
  }
  const response = await fetch(registrationUrl, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(clientMetadata)
  });
  if (!response.ok) {
    throw new Error(`Dynamic client registration failed: HTTP ${response.status}`);
  }
  return OAuthClientInformationFullSchema.parse(await response.json());
}
var UnauthorizedError2;
var init_auth2 = __esm({
  "node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"() {
    init_esbuild_shims();
    init_index_node();
    init_types9();
    init_auth();
    init_auth_utils();
    UnauthorizedError2 = class extends Error {
      static {
        __name(this, "UnauthorizedError");
      }
      constructor(message) {
        super(message !== null && message !== void 0 ? message : "Unauthorized");
      }
    };
    __name(selectClientAuthMethod, "selectClientAuthMethod");
    __name(applyClientAuthentication, "applyClientAuthentication");
    __name(applyBasicAuth, "applyBasicAuth");
    __name(applyPostAuth, "applyPostAuth");
    __name(applyPublicAuth, "applyPublicAuth");
    __name(auth, "auth");
    __name(selectResourceURL, "selectResourceURL");
    __name(extractResourceMetadataUrl, "extractResourceMetadataUrl");
    __name(discoverOAuthProtectedResourceMetadata, "discoverOAuthProtectedResourceMetadata");
    __name(fetchWithCorsRetry, "fetchWithCorsRetry");
    __name(buildWellKnownPath, "buildWellKnownPath");
    __name(tryMetadataDiscovery, "tryMetadataDiscovery");
    __name(shouldAttemptFallback, "shouldAttemptFallback");
    __name(discoverMetadataWithFallback, "discoverMetadataWithFallback");
    __name(discoverOAuthMetadata, "discoverOAuthMetadata");
    __name(startAuthorization, "startAuthorization");
    __name(exchangeAuthorization, "exchangeAuthorization");
    __name(refreshAuthorization, "refreshAuthorization");
    __name(registerClient, "registerClient");
  }
});

// node_modules/eventsource-parser/dist/index.js
function noop3(_arg) {
}
function createParser(callbacks) {
  if (typeof callbacks == "function")
    throw new TypeError(
      "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
    );
  const { onEvent = noop3, onError: onError2 = noop3, onRetry = noop3, onComment } = callbacks;
  let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
  function feed(newChunk) {
    const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines2(`${incompleteLine}${chunk}`);
    for (const line of complete)
      parseLine(line);
    incompleteLine = incomplete, isFirstChunk = false;
  }
  __name(feed, "feed");
  function parseLine(line) {
    if (line === "") {
      dispatchEvent();
      return;
    }
    if (line.startsWith(":")) {
      onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
      return;
    }
    const fieldSeparatorIndex = line.indexOf(":");
    if (fieldSeparatorIndex !== -1) {
      const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
      processField(field, value, line);
      return;
    }
    processField(line, "", line);
  }
  __name(parseLine, "parseLine");
  function processField(field, value, line) {
    switch (field) {
      case "event":
        eventType = value;
        break;
      case "data":
        data = `${data}${value}
`;
        break;
      case "id":
        id = value.includes("\0") ? void 0 : value;
        break;
      case "retry":
        /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError2(
          new ParseError(`Invalid \`retry\` value: "${value}"`, {
            type: "invalid-retry",
            value,
            line
          })
        );
        break;
      default:
        onError2(
          new ParseError(
            `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
            { type: "unknown-field", field, value, line }
          )
        );
        break;
    }
  }
  __name(processField, "processField");
  function dispatchEvent() {
    data.length > 0 && onEvent({
      id,
      event: eventType || void 0,
      // If the data buffer's last character is a U+000A LINE FEED (LF) character,
      // then remove the last character from the data buffer.
      data: data.endsWith(`
`) ? data.slice(0, -1) : data
    }), id = void 0, data = "", eventType = "";
  }
  __name(dispatchEvent, "dispatchEvent");
  function reset(options2 = {}) {
    incompleteLine && options2.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
  }
  __name(reset, "reset");
  return { feed, reset };
}
function splitLines2(chunk) {
  const lines = [];
  let incompleteLine = "", searchIndex = 0;
  for (; searchIndex < chunk.length; ) {
    const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
`, searchIndex);
    let lineEnd = -1;
    if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
      incompleteLine = chunk.slice(searchIndex);
      break;
    } else {
      const line = chunk.slice(searchIndex, lineEnd);
      lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
` && searchIndex++;
    }
  }
  return [lines, incompleteLine];
}
var ParseError;
var init_dist = __esm({
  "node_modules/eventsource-parser/dist/index.js"() {
    init_esbuild_shims();
    ParseError = class extends Error {
      static {
        __name(this, "ParseError");
      }
      constructor(message, options2) {
        super(message), this.name = "ParseError", this.type = options2.type, this.field = options2.field, this.value = options2.value, this.line = options2.line;
      }
    };
    __name(noop3, "noop");
    __name(createParser, "createParser");
    __name(splitLines2, "splitLines");
  }
});

// node_modules/eventsource-parser/dist/stream.js
var EventSourceParserStream;
var init_stream = __esm({
  "node_modules/eventsource-parser/dist/stream.js"() {
    init_esbuild_shims();
    init_dist();
    EventSourceParserStream = class extends TransformStream {
      static {
        __name(this, "EventSourceParserStream");
      }
      constructor({ onError: onError2, onRetry, onComment } = {}) {
        let parser6;
        super({
          start(controller) {
            parser6 = createParser({
              onEvent: /* @__PURE__ */ __name((event) => {
                controller.enqueue(event);
              }, "onEvent"),
              onError(error) {
                onError2 === "terminate" ? controller.error(error) : typeof onError2 == "function" && onError2(error);
              },
              onRetry,
              onComment
            });
          },
          transform(chunk) {
            parser6.feed(chunk);
          }
        });
      }
    };
  }
});

// node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
var DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS, StreamableHTTPError, StreamableHTTPClientTransport;
var init_streamableHttp = __esm({
  "node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js"() {
    init_esbuild_shims();
    init_types9();
    init_auth2();
    init_stream();
    DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
      initialReconnectionDelay: 1e3,
      maxReconnectionDelay: 3e4,
      reconnectionDelayGrowFactor: 1.5,
      maxRetries: 2
    };
    StreamableHTTPError = class extends Error {
      static {
        __name(this, "StreamableHTTPError");
      }
      constructor(code2, message) {
        super(`Streamable HTTP error: ${message}`);
        this.code = code2;
      }
    };
    StreamableHTTPClientTransport = class {
      static {
        __name(this, "StreamableHTTPClientTransport");
      }
      constructor(url2, opts) {
        var _a6;
        this._url = url2;
        this._resourceMetadataUrl = void 0;
        this._requestInit = opts === null || opts === void 0 ? void 0 : opts.requestInit;
        this._authProvider = opts === null || opts === void 0 ? void 0 : opts.authProvider;
        this._fetch = opts === null || opts === void 0 ? void 0 : opts.fetch;
        this._sessionId = opts === null || opts === void 0 ? void 0 : opts.sessionId;
        this._reconnectionOptions = (_a6 = opts === null || opts === void 0 ? void 0 : opts.reconnectionOptions) !== null && _a6 !== void 0 ? _a6 : DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
      }
      async _authThenStart() {
        var _a6;
        if (!this._authProvider) {
          throw new UnauthorizedError2("No auth provider");
        }
        let result;
        try {
          result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl });
        } catch (error) {
          (_a6 = this.onerror) === null || _a6 === void 0 ? void 0 : _a6.call(this, error);
          throw error;
        }
        if (result !== "AUTHORIZED") {
          throw new UnauthorizedError2();
        }
        return await this._startOrAuthSse({ resumptionToken: void 0 });
      }
      async _commonHeaders() {
        var _a6;
        const headers = {};
        if (this._authProvider) {
          const tokens = await this._authProvider.tokens();
          if (tokens) {
            headers["Authorization"] = `Bearer ${tokens.access_token}`;
          }
        }
        if (this._sessionId) {
          headers["mcp-session-id"] = this._sessionId;
        }
        if (this._protocolVersion) {
          headers["mcp-protocol-version"] = this._protocolVersion;
        }
        const extraHeaders = this._normalizeHeaders((_a6 = this._requestInit) === null || _a6 === void 0 ? void 0 : _a6.headers);
        return new Headers({
          ...headers,
          ...extraHeaders
        });
      }
      async _startOrAuthSse(options2) {
        var _a6, _b2, _c2;
        const { resumptionToken } = options2;
        try {
          const headers = await this._commonHeaders();
          headers.set("Accept", "text/event-stream");
          if (resumptionToken) {
            headers.set("last-event-id", resumptionToken);
          }
          const response = await ((_a6 = this._fetch) !== null && _a6 !== void 0 ? _a6 : fetch)(this._url, {
            method: "GET",
            headers,
            signal: (_b2 = this._abortController) === null || _b2 === void 0 ? void 0 : _b2.signal
          });
          if (!response.ok) {
            if (response.status === 401 && this._authProvider) {
              return await this._authThenStart();
            }
            if (response.status === 405) {
              return;
            }
            throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`);
          }
          this._handleSseStream(response.body, options2);
        } catch (error) {
          (_c2 = this.onerror) === null || _c2 === void 0 ? void 0 : _c2.call(this, error);
          throw error;
        }
      }
      /**
       * Calculates the next reconnection delay using  backoff algorithm
       *
       * @param attempt Current reconnection attempt count for the specific stream
       * @returns Time to wait in milliseconds before next reconnection attempt
       */
      _getNextReconnectionDelay(attempt) {
        const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
        const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
        const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
        return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
      }
      _normalizeHeaders(headers) {
        if (!headers)
          return {};
        if (headers instanceof Headers) {
          return Object.fromEntries(headers.entries());
        }
        if (Array.isArray(headers)) {
          return Object.fromEntries(headers);
        }
        return { ...headers };
      }
      /**
       * Schedule a reconnection attempt with exponential backoff
       *
       * @param lastEventId The ID of the last received event for resumability
       * @param attemptCount Current reconnection attempt count for this specific stream
       */
      _scheduleReconnection(options2, attemptCount = 0) {
        var _a6;
        const maxRetries = this._reconnectionOptions.maxRetries;
        if (maxRetries > 0 && attemptCount >= maxRetries) {
          (_a6 = this.onerror) === null || _a6 === void 0 ? void 0 : _a6.call(this, new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
          return;
        }
        const delay4 = this._getNextReconnectionDelay(attemptCount);
        setTimeout(() => {
          this._startOrAuthSse(options2).catch((error) => {
            var _a7;
            (_a7 = this.onerror) === null || _a7 === void 0 ? void 0 : _a7.call(this, new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));
            this._scheduleReconnection(options2, attemptCount + 1);
          });
        }, delay4);
      }
      _handleSseStream(stream2, options2) {
        if (!stream2) {
          return;
        }
        const { onresumptiontoken, replayMessageId } = options2;
        let lastEventId;
        const processStream = /* @__PURE__ */ __name(async () => {
          var _a6, _b2, _c2, _d;
          try {
            const reader = stream2.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).getReader();
            while (true) {
              const { value: event, done } = await reader.read();
              if (done) {
                break;
              }
              if (event.id) {
                lastEventId = event.id;
                onresumptiontoken === null || onresumptiontoken === void 0 ? void 0 : onresumptiontoken(event.id);
              }
              if (!event.event || event.event === "message") {
                try {
                  const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));
                  if (replayMessageId !== void 0 && isJSONRPCResponse(message)) {
                    message.id = replayMessageId;
                  }
                  (_a6 = this.onmessage) === null || _a6 === void 0 ? void 0 : _a6.call(this, message);
                } catch (error) {
                  (_b2 = this.onerror) === null || _b2 === void 0 ? void 0 : _b2.call(this, error);
                }
              }
            }
          } catch (error) {
            (_c2 = this.onerror) === null || _c2 === void 0 ? void 0 : _c2.call(this, new Error(`SSE stream disconnected: ${error}`));
            if (this._abortController && !this._abortController.signal.aborted) {
              if (lastEventId !== void 0) {
                try {
                  this._scheduleReconnection({
                    resumptionToken: lastEventId,
                    onresumptiontoken,
                    replayMessageId
                  }, 0);
                } catch (error2) {
                  (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, new Error(`Failed to reconnect: ${error2 instanceof Error ? error2.message : String(error2)}`));
                }
              }
            }
          }
        }, "processStream");
        processStream();
      }
      async start() {
        if (this._abortController) {
          throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");
        }
        this._abortController = new AbortController();
      }
      /**
       * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
       */
      async finishAuth(authorizationCode) {
        if (!this._authProvider) {
          throw new UnauthorizedError2("No auth provider");
        }
        const result = await auth(this._authProvider, { serverUrl: this._url, authorizationCode, resourceMetadataUrl: this._resourceMetadataUrl });
        if (result !== "AUTHORIZED") {
          throw new UnauthorizedError2("Failed to authorize");
        }
      }
      async close() {
        var _a6, _b2;
        (_a6 = this._abortController) === null || _a6 === void 0 ? void 0 : _a6.abort();
        (_b2 = this.onclose) === null || _b2 === void 0 ? void 0 : _b2.call(this);
      }
      async send(message, options2) {
        var _a6, _b2, _c2, _d;
        try {
          const { resumptionToken, onresumptiontoken } = options2 || {};
          if (resumptionToken) {
            this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : void 0 }).catch((err) => {
              var _a7;
              return (_a7 = this.onerror) === null || _a7 === void 0 ? void 0 : _a7.call(this, err);
            });
            return;
          }
          const headers = await this._commonHeaders();
          headers.set("content-type", "application/json");
          headers.set("accept", "application/json, text/event-stream");
          const init = {
            ...this._requestInit,
            method: "POST",
            headers,
            body: JSON.stringify(message),
            signal: (_a6 = this._abortController) === null || _a6 === void 0 ? void 0 : _a6.signal
          };
          const response = await ((_b2 = this._fetch) !== null && _b2 !== void 0 ? _b2 : fetch)(this._url, init);
          const sessionId2 = response.headers.get("mcp-session-id");
          if (sessionId2) {
            this._sessionId = sessionId2;
          }
          if (!response.ok) {
            if (response.status === 401 && this._authProvider) {
              this._resourceMetadataUrl = extractResourceMetadataUrl(response);
              const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl });
              if (result !== "AUTHORIZED") {
                throw new UnauthorizedError2();
              }
              return this.send(message);
            }
            const text = await response.text().catch(() => null);
            throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
          }
          if (response.status === 202) {
            if (isInitializedNotification(message)) {
              this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => {
                var _a7;
                return (_a7 = this.onerror) === null || _a7 === void 0 ? void 0 : _a7.call(this, err);
              });
            }
            return;
          }
          const messages = Array.isArray(message) ? message : [message];
          const hasRequests = messages.filter((msg) => "method" in msg && "id" in msg && msg.id !== void 0).length > 0;
          const contentType = response.headers.get("content-type");
          if (hasRequests) {
            if (contentType === null || contentType === void 0 ? void 0 : contentType.includes("text/event-stream")) {
              this._handleSseStream(response.body, { onresumptiontoken });
            } else if (contentType === null || contentType === void 0 ? void 0 : contentType.includes("application/json")) {
              const data = await response.json();
              const responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)];
              for (const msg of responseMessages) {
                (_c2 = this.onmessage) === null || _c2 === void 0 ? void 0 : _c2.call(this, msg);
              }
            } else {
              throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);
            }
          }
        } catch (error) {
          (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, error);
          throw error;
        }
      }
      get sessionId() {
        return this._sessionId;
      }
      /**
       * Terminates the current session by sending a DELETE request to the server.
       *
       * Clients that no longer need a particular session
       * (e.g., because the user is leaving the client application) SHOULD send an
       * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
       * terminate the session.
       *
       * The server MAY respond with HTTP 405 Method Not Allowed, indicating that
       * the server does not allow clients to terminate sessions.
       */
      async terminateSession() {
        var _a6, _b2, _c2;
        if (!this._sessionId) {
          return;
        }
        try {
          const headers = await this._commonHeaders();
          const init = {
            ...this._requestInit,
            method: "DELETE",
            headers,
            signal: (_a6 = this._abortController) === null || _a6 === void 0 ? void 0 : _a6.signal
          };
          const response = await ((_b2 = this._fetch) !== null && _b2 !== void 0 ? _b2 : fetch)(this._url, init);
          if (!response.ok && response.status !== 405) {
            throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);
          }
          this._sessionId = void 0;
        } catch (error) {
          (_c2 = this.onerror) === null || _c2 === void 0 ? void 0 : _c2.call(this, error);
          throw error;
        }
      }
      setProtocolVersion(version2) {
        this._protocolVersion = version2;
      }
      get protocolVersion() {
        return this._protocolVersion;
      }
    };
  }
});

// node_modules/isexe/windows.js
var require_windows = __commonJS({
  "node_modules/isexe/windows.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = isexe;
    isexe.sync = sync2;
    var fs95 = __require("fs");
    function checkPathExt(path108, options2) {
      var pathext = options2.pathExt !== void 0 ? options2.pathExt : process.env.PATHEXT;
      if (!pathext) {
        return true;
      }
      pathext = pathext.split(";");
      if (pathext.indexOf("") !== -1) {
        return true;
      }
      for (var i = 0; i < pathext.length; i++) {
        var p = pathext[i].toLowerCase();
        if (p && path108.substr(-p.length).toLowerCase() === p) {
          return true;
        }
      }
      return false;
    }
    __name(checkPathExt, "checkPathExt");
    function checkStat(stat7, path108, options2) {
      if (!stat7.isSymbolicLink() && !stat7.isFile()) {
        return false;
      }
      return checkPathExt(path108, options2);
    }
    __name(checkStat, "checkStat");
    function isexe(path108, options2, cb) {
      fs95.stat(path108, function(er, stat7) {
        cb(er, er ? false : checkStat(stat7, path108, options2));
      });
    }
    __name(isexe, "isexe");
    function sync2(path108, options2) {
      return checkStat(fs95.statSync(path108), path108, options2);
    }
    __name(sync2, "sync");
  }
});

// node_modules/isexe/mode.js
var require_mode = __commonJS({
  "node_modules/isexe/mode.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = isexe;
    isexe.sync = sync2;
    var fs95 = __require("fs");
    function isexe(path108, options2, cb) {
      fs95.stat(path108, function(er, stat7) {
        cb(er, er ? false : checkStat(stat7, options2));
      });
    }
    __name(isexe, "isexe");
    function sync2(path108, options2) {
      return checkStat(fs95.statSync(path108), options2);
    }
    __name(sync2, "sync");
    function checkStat(stat7, options2) {
      return stat7.isFile() && checkMode(stat7, options2);
    }
    __name(checkStat, "checkStat");
    function checkMode(stat7, options2) {
      var mod2 = stat7.mode;
      var uid = stat7.uid;
      var gid = stat7.gid;
      var myUid = options2.uid !== void 0 ? options2.uid : process.getuid && process.getuid();
      var myGid = options2.gid !== void 0 ? options2.gid : process.getgid && process.getgid();
      var u = parseInt("100", 8);
      var g = parseInt("010", 8);
      var o2 = parseInt("001", 8);
      var ug = u | g;
      var ret = mod2 & o2 || mod2 & g && gid === myGid || mod2 & u && uid === myUid || mod2 & ug && myUid === 0;
      return ret;
    }
    __name(checkMode, "checkMode");
  }
});

// node_modules/isexe/index.js
var require_isexe = __commonJS({
  "node_modules/isexe/index.js"(exports2, module2) {
    init_esbuild_shims();
    var fs95 = __require("fs");
    var core;
    if (process.platform === "win32" || globalThis.TESTING_WINDOWS) {
      core = require_windows();
    } else {
      core = require_mode();
    }
    module2.exports = isexe;
    isexe.sync = sync2;
    function isexe(path108, options2, cb) {
      if (typeof options2 === "function") {
        cb = options2;
        options2 = {};
      }
      if (!cb) {
        if (typeof Promise !== "function") {
          throw new TypeError("callback not provided");
        }
        return new Promise(function(resolve24, reject) {
          isexe(path108, options2 || {}, function(er, is) {
            if (er) {
              reject(er);
            } else {
              resolve24(is);
            }
          });
        });
      }
      core(path108, options2 || {}, function(er, is) {
        if (er) {
          if (er.code === "EACCES" || options2 && options2.ignoreErrors) {
            er = null;
            is = false;
          }
        }
        cb(er, is);
      });
    }
    __name(isexe, "isexe");
    function sync2(path108, options2) {
      try {
        return core.sync(path108, options2 || {});
      } catch (er) {
        if (options2 && options2.ignoreErrors || er.code === "EACCES") {
          return false;
        } else {
          throw er;
        }
      }
    }
    __name(sync2, "sync");
  }
});

// node_modules/which/which.js
var require_which = __commonJS({
  "node_modules/which/which.js"(exports2, module2) {
    init_esbuild_shims();
    var isWindows8 = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
    var path108 = __require("path");
    var COLON = isWindows8 ? ";" : ":";
    var isexe = require_isexe();
    var getNotFoundError = /* @__PURE__ */ __name((cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" }), "getNotFoundError");
    var getPathInfo = /* @__PURE__ */ __name((cmd, opt) => {
      const colon = opt.colon || COLON;
      const pathEnv = cmd.match(/\//) || isWindows8 && cmd.match(/\\/) ? [""] : [
        // windows always checks the cwd first
        ...isWindows8 ? [process.cwd()] : [],
        ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */
        "").split(colon)
      ];
      const pathExtExe = isWindows8 ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
      const pathExt = isWindows8 ? pathExtExe.split(colon) : [""];
      if (isWindows8) {
        if (cmd.indexOf(".") !== -1 && pathExt[0] !== "")
          pathExt.unshift("");
      }
      return {
        pathEnv,
        pathExt,
        pathExtExe
      };
    }, "getPathInfo");
    var which = /* @__PURE__ */ __name((cmd, opt, cb) => {
      if (typeof opt === "function") {
        cb = opt;
        opt = {};
      }
      if (!opt)
        opt = {};
      const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
      const found = [];
      const step = /* @__PURE__ */ __name((i) => new Promise((resolve24, reject) => {
        if (i === pathEnv.length)
          return opt.all && found.length ? resolve24(found) : reject(getNotFoundError(cmd));
        const ppRaw = pathEnv[i];
        const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
        const pCmd = path108.join(pathPart, cmd);
        const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
        resolve24(subStep(p, i, 0));
      }), "step");
      const subStep = /* @__PURE__ */ __name((p, i, ii) => new Promise((resolve24, reject) => {
        if (ii === pathExt.length)
          return resolve24(step(i + 1));
        const ext2 = pathExt[ii];
        isexe(p + ext2, { pathExt: pathExtExe }, (er, is) => {
          if (!er && is) {
            if (opt.all)
              found.push(p + ext2);
            else
              return resolve24(p + ext2);
          }
          return resolve24(subStep(p, i, ii + 1));
        });
      }), "subStep");
      return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
    }, "which");
    var whichSync = /* @__PURE__ */ __name((cmd, opt) => {
      opt = opt || {};
      const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
      const found = [];
      for (let i = 0; i < pathEnv.length; i++) {
        const ppRaw = pathEnv[i];
        const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
        const pCmd = path108.join(pathPart, cmd);
        const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
        for (let j = 0; j < pathExt.length; j++) {
          const cur = p + pathExt[j];
          try {
            const is = isexe.sync(cur, { pathExt: pathExtExe });
            if (is) {
              if (opt.all)
                found.push(cur);
              else
                return cur;
            }
          } catch (ex) {
          }
        }
      }
      if (opt.all && found.length)
        return found;
      if (opt.nothrow)
        return null;
      throw getNotFoundError(cmd);
    }, "whichSync");
    module2.exports = which;
    which.sync = whichSync;
  }
});

// node_modules/path-key/index.js
var require_path_key = __commonJS({
  "node_modules/path-key/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var pathKey = /* @__PURE__ */ __name((options2 = {}) => {
      const environment = options2.env || process.env;
      const platform15 = options2.platform || process.platform;
      if (platform15 !== "win32") {
        return "PATH";
      }
      return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
    }, "pathKey");
    module2.exports = pathKey;
    module2.exports.default = pathKey;
  }
});

// node_modules/cross-spawn/lib/util/resolveCommand.js
var require_resolveCommand = __commonJS({
  "node_modules/cross-spawn/lib/util/resolveCommand.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var path108 = __require("path");
    var which = require_which();
    var getPathKey = require_path_key();
    function resolveCommandAttempt(parsed, withoutPathExt) {
      const env7 = parsed.options.env || process.env;
      const cwd7 = process.cwd();
      const hasCustomCwd = parsed.options.cwd != null;
      const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
      if (shouldSwitchCwd) {
        try {
          process.chdir(parsed.options.cwd);
        } catch (err) {
        }
      }
      let resolved;
      try {
        resolved = which.sync(parsed.command, {
          path: env7[getPathKey({ env: env7 })],
          pathExt: withoutPathExt ? path108.delimiter : void 0
        });
      } catch (e2) {
      } finally {
        if (shouldSwitchCwd) {
          process.chdir(cwd7);
        }
      }
      if (resolved) {
        resolved = path108.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
      }
      return resolved;
    }
    __name(resolveCommandAttempt, "resolveCommandAttempt");
    function resolveCommand(parsed) {
      return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
    }
    __name(resolveCommand, "resolveCommand");
    module2.exports = resolveCommand;
  }
});

// node_modules/cross-spawn/lib/util/escape.js
var require_escape = __commonJS({
  "node_modules/cross-spawn/lib/util/escape.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
    function escapeCommand(arg) {
      arg = arg.replace(metaCharsRegExp, "^$1");
      return arg;
    }
    __name(escapeCommand, "escapeCommand");
    function escapeArgument(arg, doubleEscapeMetaChars) {
      arg = `${arg}`;
      arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
      arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
      arg = `"${arg}"`;
      arg = arg.replace(metaCharsRegExp, "^$1");
      if (doubleEscapeMetaChars) {
        arg = arg.replace(metaCharsRegExp, "^$1");
      }
      return arg;
    }
    __name(escapeArgument, "escapeArgument");
    module2.exports.command = escapeCommand;
    module2.exports.argument = escapeArgument;
  }
});

// node_modules/shebang-regex/index.js
var require_shebang_regex = __commonJS({
  "node_modules/shebang-regex/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /^#!(.*)/;
  }
});

// node_modules/shebang-command/index.js
var require_shebang_command = __commonJS({
  "node_modules/shebang-command/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var shebangRegex = require_shebang_regex();
    module2.exports = (string = "") => {
      const match2 = string.match(shebangRegex);
      if (!match2) {
        return null;
      }
      const [path108, argument] = match2[0].replace(/#! ?/, "").split(" ");
      const binary = path108.split("/").pop();
      if (binary === "env") {
        return argument;
      }
      return argument ? `${binary} ${argument}` : binary;
    };
  }
});

// node_modules/cross-spawn/lib/util/readShebang.js
var require_readShebang = __commonJS({
  "node_modules/cross-spawn/lib/util/readShebang.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var fs95 = __require("fs");
    var shebangCommand = require_shebang_command();
    function readShebang(command2) {
      const size = 150;
      const buffer = Buffer.alloc(size);
      let fd;
      try {
        fd = fs95.openSync(command2, "r");
        fs95.readSync(fd, buffer, 0, size, 0);
        fs95.closeSync(fd);
      } catch (e2) {
      }
      return shebangCommand(buffer.toString());
    }
    __name(readShebang, "readShebang");
    module2.exports = readShebang;
  }
});

// node_modules/cross-spawn/lib/parse.js
var require_parse5 = __commonJS({
  "node_modules/cross-spawn/lib/parse.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var path108 = __require("path");
    var resolveCommand = require_resolveCommand();
    var escape7 = require_escape();
    var readShebang = require_readShebang();
    var isWin = process.platform === "win32";
    var isExecutableRegExp = /\.(?:com|exe)$/i;
    var isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
    function detectShebang(parsed) {
      parsed.file = resolveCommand(parsed);
      const shebang = parsed.file && readShebang(parsed.file);
      if (shebang) {
        parsed.args.unshift(parsed.file);
        parsed.command = shebang;
        return resolveCommand(parsed);
      }
      return parsed.file;
    }
    __name(detectShebang, "detectShebang");
    function parseNonShell(parsed) {
      if (!isWin) {
        return parsed;
      }
      const commandFile = detectShebang(parsed);
      const needsShell = !isExecutableRegExp.test(commandFile);
      if (parsed.options.forceShell || needsShell) {
        const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
        parsed.command = path108.normalize(parsed.command);
        parsed.command = escape7.command(parsed.command);
        parsed.args = parsed.args.map((arg) => escape7.argument(arg, needsDoubleEscapeMetaChars));
        const shellCommand = [parsed.command].concat(parsed.args).join(" ");
        parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`];
        parsed.command = process.env.comspec || "cmd.exe";
        parsed.options.windowsVerbatimArguments = true;
      }
      return parsed;
    }
    __name(parseNonShell, "parseNonShell");
    function parse12(command2, args, options2) {
      if (args && !Array.isArray(args)) {
        options2 = args;
        args = null;
      }
      args = args ? args.slice(0) : [];
      options2 = Object.assign({}, options2);
      const parsed = {
        command: command2,
        args,
        options: options2,
        file: void 0,
        original: {
          command: command2,
          args
        }
      };
      return options2.shell ? parsed : parseNonShell(parsed);
    }
    __name(parse12, "parse");
    module2.exports = parse12;
  }
});

// node_modules/cross-spawn/lib/enoent.js
var require_enoent = __commonJS({
  "node_modules/cross-spawn/lib/enoent.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var isWin = process.platform === "win32";
    function notFoundError(original, syscall) {
      return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
        code: "ENOENT",
        errno: "ENOENT",
        syscall: `${syscall} ${original.command}`,
        path: original.command,
        spawnargs: original.args
      });
    }
    __name(notFoundError, "notFoundError");
    function hookChildProcess(cp2, parsed) {
      if (!isWin) {
        return;
      }
      const originalEmit = cp2.emit;
      cp2.emit = function(name3, arg1) {
        if (name3 === "exit") {
          const err = verifyENOENT(arg1, parsed);
          if (err) {
            return originalEmit.call(cp2, "error", err);
          }
        }
        return originalEmit.apply(cp2, arguments);
      };
    }
    __name(hookChildProcess, "hookChildProcess");
    function verifyENOENT(status, parsed) {
      if (isWin && status === 1 && !parsed.file) {
        return notFoundError(parsed.original, "spawn");
      }
      return null;
    }
    __name(verifyENOENT, "verifyENOENT");
    function verifyENOENTSync(status, parsed) {
      if (isWin && status === 1 && !parsed.file) {
        return notFoundError(parsed.original, "spawnSync");
      }
      return null;
    }
    __name(verifyENOENTSync, "verifyENOENTSync");
    module2.exports = {
      hookChildProcess,
      verifyENOENT,
      verifyENOENTSync,
      notFoundError
    };
  }
});

// node_modules/cross-spawn/index.js
var require_cross_spawn = __commonJS({
  "node_modules/cross-spawn/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var cp2 = __require("child_process");
    var parse12 = require_parse5();
    var enoent = require_enoent();
    function spawn11(command2, args, options2) {
      const parsed = parse12(command2, args, options2);
      const spawned = cp2.spawn(parsed.command, parsed.args, parsed.options);
      enoent.hookChildProcess(spawned, parsed);
      return spawned;
    }
    __name(spawn11, "spawn");
    function spawnSync5(command2, args, options2) {
      const parsed = parse12(command2, args, options2);
      const result = cp2.spawnSync(parsed.command, parsed.args, parsed.options);
      result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
      return result;
    }
    __name(spawnSync5, "spawnSync");
    module2.exports = spawn11;
    module2.exports.spawn = spawn11;
    module2.exports.sync = spawnSync5;
    module2.exports._parse = parse12;
    module2.exports._enoent = enoent;
  }
});

// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
function deserializeMessage(line) {
  return JSONRPCMessageSchema.parse(JSON.parse(line));
}
function serializeMessage(message) {
  return JSON.stringify(message) + "\n";
}
var ReadBuffer;
var init_stdio = __esm({
  "node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js"() {
    init_esbuild_shims();
    init_types9();
    ReadBuffer = class {
      static {
        __name(this, "ReadBuffer");
      }
      append(chunk) {
        this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
      }
      readMessage() {
        if (!this._buffer) {
          return null;
        }
        const index = this._buffer.indexOf("\n");
        if (index === -1) {
          return null;
        }
        const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");
        this._buffer = this._buffer.subarray(index + 1);
        return deserializeMessage(line);
      }
      clear() {
        this._buffer = void 0;
      }
    };
    __name(deserializeMessage, "deserializeMessage");
    __name(serializeMessage, "serializeMessage");
  }
});

// node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js
import process19 from "node:process";
import { PassThrough as PassThrough2 } from "node:stream";
function getDefaultEnvironment() {
  const env7 = {};
  for (const key of DEFAULT_INHERITED_ENV_VARS) {
    const value = process19.env[key];
    if (value === void 0) {
      continue;
    }
    if (value.startsWith("()")) {
      continue;
    }
    env7[key] = value;
  }
  return env7;
}
function isElectron2() {
  return "type" in process19;
}
var import_cross_spawn, DEFAULT_INHERITED_ENV_VARS, StdioClientTransport;
var init_stdio2 = __esm({
  "node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"() {
    init_esbuild_shims();
    import_cross_spawn = __toESM(require_cross_spawn(), 1);
    init_stdio();
    DEFAULT_INHERITED_ENV_VARS = process19.platform === "win32" ? [
      "APPDATA",
      "HOMEDRIVE",
      "HOMEPATH",
      "LOCALAPPDATA",
      "PATH",
      "PROCESSOR_ARCHITECTURE",
      "SYSTEMDRIVE",
      "SYSTEMROOT",
      "TEMP",
      "USERNAME",
      "USERPROFILE",
      "PROGRAMFILES"
    ] : (
      /* list inspired by the default env inheritance of sudo */
      ["HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER"]
    );
    __name(getDefaultEnvironment, "getDefaultEnvironment");
    StdioClientTransport = class {
      static {
        __name(this, "StdioClientTransport");
      }
      constructor(server) {
        this._abortController = new AbortController();
        this._readBuffer = new ReadBuffer();
        this._stderrStream = null;
        this._serverParams = server;
        if (server.stderr === "pipe" || server.stderr === "overlapped") {
          this._stderrStream = new PassThrough2();
        }
      }
      /**
       * Starts the server process and prepares to communicate with it.
       */
      async start() {
        if (this._process) {
          throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");
        }
        return new Promise((resolve24, reject) => {
          var _a6, _b2, _c2, _d, _e;
          this._process = (0, import_cross_spawn.default)(this._serverParams.command, (_a6 = this._serverParams.args) !== null && _a6 !== void 0 ? _a6 : [], {
            // merge default env with server env because mcp server needs some env vars
            env: {
              ...getDefaultEnvironment(),
              ...this._serverParams.env
            },
            stdio: ["pipe", "pipe", (_b2 = this._serverParams.stderr) !== null && _b2 !== void 0 ? _b2 : "inherit"],
            shell: false,
            signal: this._abortController.signal,
            windowsHide: process19.platform === "win32" && isElectron2(),
            cwd: this._serverParams.cwd
          });
          this._process.on("error", (error) => {
            var _a7, _b3;
            if (error.name === "AbortError") {
              (_a7 = this.onclose) === null || _a7 === void 0 ? void 0 : _a7.call(this);
              return;
            }
            reject(error);
            (_b3 = this.onerror) === null || _b3 === void 0 ? void 0 : _b3.call(this, error);
          });
          this._process.on("spawn", () => {
            resolve24();
          });
          this._process.on("close", (_code) => {
            var _a7;
            this._process = void 0;
            (_a7 = this.onclose) === null || _a7 === void 0 ? void 0 : _a7.call(this);
          });
          (_c2 = this._process.stdin) === null || _c2 === void 0 ? void 0 : _c2.on("error", (error) => {
            var _a7;
            (_a7 = this.onerror) === null || _a7 === void 0 ? void 0 : _a7.call(this, error);
          });
          (_d = this._process.stdout) === null || _d === void 0 ? void 0 : _d.on("data", (chunk) => {
            this._readBuffer.append(chunk);
            this.processReadBuffer();
          });
          (_e = this._process.stdout) === null || _e === void 0 ? void 0 : _e.on("error", (error) => {
            var _a7;
            (_a7 = this.onerror) === null || _a7 === void 0 ? void 0 : _a7.call(this, error);
          });
          if (this._stderrStream && this._process.stderr) {
            this._process.stderr.pipe(this._stderrStream);
          }
        });
      }
      /**
       * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped".
       *
       * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to
       * attach listeners before the start method is invoked. This prevents loss of any early
       * error output emitted by the child process.
       */
      get stderr() {
        var _a6, _b2;
        if (this._stderrStream) {
          return this._stderrStream;
        }
        return (_b2 = (_a6 = this._process) === null || _a6 === void 0 ? void 0 : _a6.stderr) !== null && _b2 !== void 0 ? _b2 : null;
      }
      /**
       * The child process pid spawned by this transport.
       *
       * This is only available after the transport has been started.
       */
      get pid() {
        var _a6, _b2;
        return (_b2 = (_a6 = this._process) === null || _a6 === void 0 ? void 0 : _a6.pid) !== null && _b2 !== void 0 ? _b2 : null;
      }
      processReadBuffer() {
        var _a6, _b2;
        while (true) {
          try {
            const message = this._readBuffer.readMessage();
            if (message === null) {
              break;
            }
            (_a6 = this.onmessage) === null || _a6 === void 0 ? void 0 : _a6.call(this, message);
          } catch (error) {
            (_b2 = this.onerror) === null || _b2 === void 0 ? void 0 : _b2.call(this, error);
          }
        }
      }
      async close() {
        this._abortController.abort();
        this._process = void 0;
        this._readBuffer.clear();
      }
      send(message) {
        return new Promise((resolve24) => {
          var _a6;
          if (!((_a6 = this._process) === null || _a6 === void 0 ? void 0 : _a6.stdin)) {
            throw new Error("Not connected");
          }
          const json2 = serializeMessage(message);
          if (this._process.stdin.write(json2)) {
            resolve24();
          } else {
            this._process.stdin.once("drain", resolve24);
          }
        });
      }
    };
    __name(isElectron2, "isElectron");
  }
});

// packages/core/dist/src/ide/ide-client.js
import * as fs31 from "node:fs";
import * as os19 from "node:os";
import * as path33 from "node:path";
function getRealPath(path108) {
  try {
    return fs31.realpathSync(path108);
  } catch (_e) {
    return path108;
  }
}
function getIdeServerHost() {
  const isInContainer = fs31.existsSync("/.dockerenv") || fs31.existsSync("/run/.containerenv");
  return isInContainer ? "host.docker.internal" : "127.0.0.1";
}
var import_undici, logger, IDEConnectionStatus, IdeClient;
var init_ide_client = __esm({
  "packages/core/dist/src/ide/ide-client.js"() {
    "use strict";
    init_esbuild_shims();
    init_paths();
    init_detect_ide();
    init_ideContext();
    init_types8();
    init_process_utils();
    init_client3();
    init_streamableHttp();
    init_stdio2();
    init_types9();
    import_undici = __toESM(require_undici(), 1);
    init_types9();
    init_constants4();
    logger = {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      debug: /* @__PURE__ */ __name((...args) => console.debug("[DEBUG] [IDEClient]", ...args), "debug"),
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      error: /* @__PURE__ */ __name((...args) => console.error("[ERROR] [IDEClient]", ...args), "error")
    };
    (function(IDEConnectionStatus2) {
      IDEConnectionStatus2["Connected"] = "connected";
      IDEConnectionStatus2["Disconnected"] = "disconnected";
      IDEConnectionStatus2["Connecting"] = "connecting";
    })(IDEConnectionStatus || (IDEConnectionStatus = {}));
    __name(getRealPath, "getRealPath");
    IdeClient = class _IdeClient {
      static {
        __name(this, "IdeClient");
      }
      static instancePromise = null;
      client = void 0;
      state = {
        status: IDEConnectionStatus.Disconnected,
        details: "IDE integration is currently disabled. To enable it, run /ide enable."
      };
      currentIde;
      ideProcessInfo;
      connectionConfig;
      authToken;
      diffResponses = /* @__PURE__ */ new Map();
      statusListeners = /* @__PURE__ */ new Set();
      trustChangeListeners = /* @__PURE__ */ new Set();
      availableTools = [];
      /**
       * A mutex to ensure that only one diff view is open in the IDE at a time.
       * This prevents race conditions and UI issues in IDEs like VSCode that
       * can't handle multiple diff views being opened simultaneously.
       */
      diffMutex = Promise.resolve();
      constructor() {
      }
      static getInstance() {
        if (!_IdeClient.instancePromise) {
          _IdeClient.instancePromise = (async () => {
            const client = new _IdeClient();
            client.ideProcessInfo = await getIdeProcessInfo();
            client.connectionConfig = await client.getConnectionConfigFromFile();
            client.currentIde = detectIde(client.ideProcessInfo, client.connectionConfig?.ideInfo);
            return client;
          })();
        }
        return _IdeClient.instancePromise;
      }
      addStatusChangeListener(listener) {
        this.statusListeners.add(listener);
      }
      removeStatusChangeListener(listener) {
        this.statusListeners.delete(listener);
      }
      addTrustChangeListener(listener) {
        this.trustChangeListeners.add(listener);
      }
      removeTrustChangeListener(listener) {
        this.trustChangeListeners.delete(listener);
      }
      async connect() {
        if (!this.currentIde) {
          this.setState(IDEConnectionStatus.Disconnected, `IDE integration is not supported in your current environment. To use this feature, run Qwen Code in one of these supported IDEs: VS Code or VS Code forks`, false);
          return;
        }
        this.setState(IDEConnectionStatus.Connecting);
        this.connectionConfig = await this.getConnectionConfigFromFile();
        if (this.connectionConfig?.authToken) {
          this.authToken = this.connectionConfig.authToken;
        }
        const workspacePath = this.connectionConfig?.workspacePath ?? process.env["QWEN_CODE_IDE_WORKSPACE_PATH"];
        const { isValid: isValid2, error } = _IdeClient.validateWorkspacePath(workspacePath, process.cwd());
        if (!isValid2) {
          this.setState(IDEConnectionStatus.Disconnected, error, true);
          return;
        }
        if (this.connectionConfig) {
          if (this.connectionConfig.port) {
            const connected = await this.establishHttpConnection(this.connectionConfig.port);
            if (connected) {
              return;
            }
          }
          if (this.connectionConfig.stdio) {
            const connected = await this.establishStdioConnection(this.connectionConfig.stdio);
            if (connected) {
              return;
            }
          }
        }
        const portFromEnv = this.getPortFromEnv();
        if (portFromEnv) {
          const connected = await this.establishHttpConnection(portFromEnv);
          if (connected) {
            return;
          }
        }
        const stdioConfigFromEnv = this.getStdioConfigFromEnv();
        if (stdioConfigFromEnv) {
          const connected = await this.establishStdioConnection(stdioConfigFromEnv);
          if (connected) {
            return;
          }
        }
        this.setState(IDEConnectionStatus.Disconnected, `Failed to connect to IDE companion extension in ${this.currentIde.displayName}. Please ensure the extension is running. To install the extension, run /ide install.`, true);
      }
      /**
       * Opens a diff view in the IDE, allowing the user to review and accept or
       * reject changes.
       *
       * This method sends a request to the IDE to display a diff between the
       * current content of a file and the new content provided. It then waits for
       * a notification from the IDE indicating that the user has either accepted
       * (potentially with manual edits) or rejected the diff.
       *
       * A mutex ensures that only one diff view can be open at a time to prevent
       * race conditions.
       *
       * @param filePath The absolute path to the file to be diffed.
       * @param newContent The proposed new content for the file.
       * @returns A promise that resolves with a `DiffUpdateResult`, indicating
       *   whether the diff was 'accepted' or 'rejected' and including the final
       *   content if accepted.
       */
      async openDiff(filePath, newContent) {
        const release3 = await this.acquireMutex();
        const promise = new Promise((resolve24, reject) => {
          if (!this.client) {
            return reject(new Error("IDE client is not connected."));
          }
          this.diffResponses.set(filePath, resolve24);
          this.client.request({
            method: "tools/call",
            params: {
              name: `openDiff`,
              arguments: {
                filePath,
                newContent
              }
            }
          }, CallToolResultSchema, { timeout: IDE_REQUEST_TIMEOUT_MS }).then((parsedResultData) => {
            if (parsedResultData.isError) {
              const textPart = parsedResultData.content.find((part) => part.type === "text");
              const errorMessage = textPart?.text ?? `Tool 'openDiff' reported an error.`;
              logger.debug(`Request for openDiff ${filePath} failed with isError:`, errorMessage);
              this.diffResponses.delete(filePath);
              reject(new Error(errorMessage));
            }
          }).catch((err) => {
            logger.debug(`Request for openDiff ${filePath} failed:`, err);
            this.diffResponses.delete(filePath);
            reject(err);
          });
        });
        promise.finally(release3);
        return promise;
      }
      /**
       * Acquires a lock to ensure sequential execution of critical sections.
       *
       * This method implements a promise-based mutex. It works by chaining promises.
       * Each call to `acquireMutex` gets the current `diffMutex` promise. It then
       * creates a *new* promise (`newMutex`) that will be resolved when the caller
       * invokes the returned `release` function. The `diffMutex` is immediately
       * updated to this `newMutex`.
       *
       * The method returns a promise that resolves with the `release` function only
       * *after* the *previous* `diffMutex` promise has resolved. This creates a
       * queue where each subsequent operation must wait for the previous one to release
       * the lock.
       *
       * @returns A promise that resolves to a function that must be called to
       *   release the lock.
       */
      acquireMutex() {
        let release3;
        const newMutex = new Promise((resolve24) => {
          release3 = resolve24;
        });
        const oldMutex = this.diffMutex;
        this.diffMutex = newMutex;
        return oldMutex.then(() => release3);
      }
      async closeDiff(filePath, options2) {
        try {
          if (!this.client) {
            return void 0;
          }
          const resultData = await this.client.request({
            method: "tools/call",
            params: {
              name: `closeDiff`,
              arguments: {
                filePath,
                suppressNotification: options2?.suppressNotification
              }
            }
          }, CallToolResultSchema, { timeout: IDE_REQUEST_TIMEOUT_MS });
          if (!resultData) {
            return void 0;
          }
          if (resultData.isError) {
            const textPart2 = resultData.content.find((part) => part.type === "text");
            const errorMessage = textPart2?.text ?? `Tool 'closeDiff' reported an error.`;
            logger.debug(`Request for closeDiff ${filePath} failed with isError:`, errorMessage);
            return void 0;
          }
          const textPart = resultData.content.find((part) => part.type === "text");
          if (textPart?.text) {
            try {
              const parsedJson = JSON.parse(textPart.text);
              if (parsedJson && typeof parsedJson.content === "string") {
                return parsedJson.content;
              }
              if (parsedJson && parsedJson.content === null) {
                return void 0;
              }
            } catch (_e) {
              logger.debug(`Invalid JSON in closeDiff response for ${filePath}:`, textPart.text);
            }
          }
        } catch (err) {
          logger.debug(`Request for closeDiff ${filePath} failed:`, err);
        }
        return void 0;
      }
      // Closes the diff. Instead of waiting for a notification,
      // manually resolves the diff resolver as the desired outcome.
      async resolveDiffFromCli(filePath, outcome) {
        const resolver = this.diffResponses.get(filePath);
        const content = await this.closeDiff(filePath, {
          // Suppress notification to avoid race where closing the diff rejects the
          // request.
          suppressNotification: true
        });
        if (resolver) {
          if (outcome === "accepted") {
            resolver({ status: "accepted", content });
          } else {
            resolver({ status: "rejected", content: void 0 });
          }
          this.diffResponses.delete(filePath);
        }
      }
      async disconnect() {
        if (this.state.status === IDEConnectionStatus.Disconnected) {
          return;
        }
        for (const filePath of this.diffResponses.keys()) {
          await this.closeDiff(filePath);
        }
        this.diffResponses.clear();
        this.setState(IDEConnectionStatus.Disconnected, "IDE integration disabled. To enable it again, run /ide enable.");
        this.client?.close();
      }
      getCurrentIde() {
        return this.currentIde;
      }
      getConnectionStatus() {
        return this.state;
      }
      getDetectedIdeDisplayName() {
        return this.currentIde?.displayName;
      }
      isDiffingEnabled() {
        return !!this.client && this.state.status === IDEConnectionStatus.Connected && this.availableTools.includes("openDiff") && this.availableTools.includes("closeDiff");
      }
      async discoverTools() {
        if (!this.client) {
          return;
        }
        try {
          logger.debug("Discovering tools from IDE...");
          const response = await this.client.request({ method: "tools/list", params: {} }, ListToolsResultSchema);
          this.availableTools = response.tools.map((tool) => tool.name);
          if (this.availableTools.length > 0) {
            logger.debug(`Discovered ${this.availableTools.length} tools from IDE: ${this.availableTools.join(", ")}`);
          } else {
            logger.debug("IDE supports tool discovery, but no tools are available.");
          }
        } catch (error) {
          if (error instanceof Error && !error.message?.includes("Method not found")) {
            logger.error(`Error discovering tools from IDE: ${error.message}`);
          } else {
            logger.debug("IDE does not support tool discovery.");
          }
          this.availableTools = [];
        }
      }
      setState(status, details, logToConsole = false) {
        const isAlreadyDisconnected = this.state.status === IDEConnectionStatus.Disconnected && status === IDEConnectionStatus.Disconnected;
        if (!isAlreadyDisconnected) {
          this.state = { status, details };
          for (const listener of this.statusListeners) {
            listener(this.state);
          }
          if (details) {
            if (logToConsole) {
              logger.error(details);
            } else {
              logger.debug(details);
            }
          }
        }
        if (status === IDEConnectionStatus.Disconnected) {
          ideContextStore.clear();
        }
      }
      static validateWorkspacePath(ideWorkspacePath, cwd7) {
        if (ideWorkspacePath === void 0) {
          return {
            isValid: false,
            error: `Failed to connect to IDE companion extension. Please ensure the extension is running. To install the extension, run /ide install.`
          };
        }
        if (ideWorkspacePath === "") {
          return {
            isValid: false,
            error: `To use this feature, please open a workspace folder in your IDE and try again.`
          };
        }
        const ideWorkspacePaths = ideWorkspacePath.split(path33.delimiter);
        const realCwd = getRealPath(cwd7);
        const isWithinWorkspace = ideWorkspacePaths.some((workspacePath) => {
          const idePath = getRealPath(workspacePath);
          return isSubpath(idePath, realCwd);
        });
        if (!isWithinWorkspace) {
          return {
            isValid: false,
            error: `Directory mismatch. Qwen Code is running in a different location than the open workspace in the IDE. Please run the CLI from one of the following directories: ${ideWorkspacePaths.join(", ")}`
          };
        }
        return { isValid: true };
      }
      getPortFromEnv() {
        const port = process.env["QWEN_CODE_IDE_SERVER_PORT"];
        if (!port) {
          return void 0;
        }
        return port;
      }
      getStdioConfigFromEnv() {
        const command2 = process.env["QWEN_CODE_IDE_SERVER_STDIO_COMMAND"];
        if (!command2) {
          return void 0;
        }
        const argsStr = process.env["QWEN_CODE_IDE_SERVER_STDIO_ARGS"];
        let args = [];
        if (argsStr) {
          try {
            const parsedArgs = JSON.parse(argsStr);
            if (Array.isArray(parsedArgs)) {
              args = parsedArgs;
            } else {
              logger.error("QWEN_CODE_IDE_SERVER_STDIO_ARGS must be a JSON array string.");
            }
          } catch (e2) {
            logger.error("Failed to parse QWEN_CODE_IDE_SERVER_STDIO_ARGS:", e2);
          }
        }
        return { command: command2, args };
      }
      async getConnectionConfigFromFile() {
        if (!this.ideProcessInfo) {
          return void 0;
        }
        try {
          const portFile = path33.join(os19.tmpdir(), `qwen-code-ide-server-${this.ideProcessInfo.pid}.json`);
          const portFileContents = await fs31.promises.readFile(portFile, "utf8");
          return JSON.parse(portFileContents);
        } catch (_) {
        }
        const portFileDir = path33.join(os19.tmpdir(), "gemini", "ide");
        let portFiles;
        try {
          portFiles = await fs31.promises.readdir(portFileDir);
        } catch (e2) {
          logger.debug("Failed to read IDE connection directory:", e2);
          return void 0;
        }
        if (!portFiles) {
          return void 0;
        }
        const fileRegex = new RegExp(`^qwen-code-ide-server-${this.ideProcessInfo.pid}-\\d+\\.json$`);
        const matchingFiles = portFiles.filter((file) => fileRegex.test(file)).sort();
        if (matchingFiles.length === 0) {
          return void 0;
        }
        let fileContents;
        try {
          fileContents = await Promise.all(matchingFiles.map((file) => fs31.promises.readFile(path33.join(portFileDir, file), "utf8")));
        } catch (e2) {
          logger.debug("Failed to read IDE connection config file(s):", e2);
          return void 0;
        }
        const parsedContents = fileContents.map((content) => {
          try {
            return JSON.parse(content);
          } catch (e2) {
            logger.debug("Failed to parse JSON from config file: ", e2);
            return void 0;
          }
        });
        const validWorkspaces = parsedContents.filter((content) => {
          if (!content) {
            return false;
          }
          const { isValid: isValid2 } = _IdeClient.validateWorkspacePath(content.workspacePath, process.cwd());
          return isValid2;
        });
        if (validWorkspaces.length === 0) {
          return void 0;
        }
        if (validWorkspaces.length === 1) {
          return validWorkspaces[0];
        }
        const portFromEnv = this.getPortFromEnv();
        if (portFromEnv) {
          const matchingPort = validWorkspaces.find((content) => String(content.port) === portFromEnv);
          if (matchingPort) {
            return matchingPort;
          }
        }
        return validWorkspaces[0];
      }
      createProxyAwareFetch() {
        const existingNoProxy = process.env["NO_PROXY"] || "";
        const agent = new import_undici.EnvHttpProxyAgent({
          noProxy: [existingNoProxy, "127.0.0.1"].filter(Boolean).join(",")
        });
        const undiciPromise = Promise.resolve().then(() => __toESM(require_undici(), 1));
        return async (url2, init) => {
          const { fetch: fetchFn } = await undiciPromise;
          const fetchOptions = {
            ...init,
            dispatcher: agent
          };
          const options2 = fetchOptions;
          const response = await fetchFn(url2, options2);
          const standardHeaders = new Headers();
          for (const [key, value] of response.headers.entries()) {
            standardHeaders.set(key, value);
          }
          return new Response(response.body, {
            status: response.status,
            statusText: response.statusText,
            headers: [...response.headers.entries()]
          });
        };
      }
      registerClientHandlers() {
        if (!this.client) {
          return;
        }
        this.client.setNotificationHandler(IdeContextNotificationSchema, (notification) => {
          ideContextStore.set(notification.params);
          const isTrusted = notification.params.workspaceState?.isTrusted;
          if (isTrusted !== void 0) {
            for (const listener of this.trustChangeListeners) {
              listener(isTrusted);
            }
          }
        });
        this.client.onerror = (_error) => {
          const errorMessage = _error instanceof Error ? _error.message : `_error`;
          this.setState(IDEConnectionStatus.Disconnected, `IDE connection error. The connection was lost unexpectedly. Please try reconnecting by running /ide enable
${errorMessage}`, true);
        };
        this.client.onclose = () => {
          this.setState(IDEConnectionStatus.Disconnected, `IDE connection closed. To reconnect, run /ide enable.`, true);
        };
        this.client.setNotificationHandler(IdeDiffAcceptedNotificationSchema, (notification) => {
          const { filePath, content } = notification.params;
          const resolver = this.diffResponses.get(filePath);
          if (resolver) {
            resolver({ status: "accepted", content });
            this.diffResponses.delete(filePath);
          } else {
            logger.debug(`No resolver found for ${filePath}`);
          }
        });
        this.client.setNotificationHandler(IdeDiffRejectedNotificationSchema, (notification) => {
          const { filePath } = notification.params;
          const resolver = this.diffResponses.get(filePath);
          if (resolver) {
            resolver({ status: "rejected", content: void 0 });
            this.diffResponses.delete(filePath);
          } else {
            logger.debug(`No resolver found for ${filePath}`);
          }
        });
        this.client.setNotificationHandler(IdeDiffClosedNotificationSchema, (notification) => {
          const { filePath } = notification.params;
          const resolver = this.diffResponses.get(filePath);
          if (resolver) {
            resolver({ status: "rejected", content: void 0 });
            this.diffResponses.delete(filePath);
          } else {
            logger.debug(`No resolver found for ${filePath}`);
          }
        });
      }
      async establishHttpConnection(port) {
        let transport;
        try {
          logger.debug("Attempting to connect to IDE via HTTP SSE");
          this.client = new Client({
            name: "streamable-http-client",
            // TODO(#3487): use the CLI version here.
            version: "1.0.0"
          });
          transport = new StreamableHTTPClientTransport(new URL(`http://${getIdeServerHost()}:${port}/mcp`), {
            fetch: this.createProxyAwareFetch(),
            requestInit: {
              headers: this.authToken ? { Authorization: `Bearer ${this.authToken}` } : {}
            }
          });
          this.registerClientHandlers();
          await this.client.connect(transport);
          this.registerClientHandlers();
          await this.discoverTools();
          this.setState(IDEConnectionStatus.Connected);
          return true;
        } catch (_error) {
          if (transport) {
            try {
              await transport.close();
            } catch (closeError) {
              logger.debug("Failed to close transport:", closeError);
            }
          }
          return false;
        }
      }
      async establishStdioConnection({ command: command2, args }) {
        let transport;
        try {
          logger.debug("Attempting to connect to IDE via stdio");
          this.client = new Client({
            name: "stdio-client",
            // TODO(#3487): use the CLI version here.
            version: "1.0.0"
          });
          transport = new StdioClientTransport({
            command: command2,
            args
          });
          await this.client.connect(transport);
          this.registerClientHandlers();
          await this.discoverTools();
          this.setState(IDEConnectionStatus.Connected);
          return true;
        } catch (_error) {
          if (transport) {
            try {
              await transport.close();
            } catch (closeError) {
              logger.debug("Failed to close transport:", closeError);
            }
          }
          return false;
        }
      }
    };
    __name(getIdeServerHost, "getIdeServerHost");
  }
});

// packages/core/dist/src/utils/editHelper.js
function normalizeBasicCharacters(text) {
  if (text === "") {
    return text;
  }
  let normalized2 = "";
  for (const char of text) {
    normalized2 += UNICODE_EQUIVALENT_MAP[char] ?? char;
  }
  return normalized2;
}
function stripTrailingWhitespacePreserveNewlines(text) {
  const pieces = text.split(/(\r\n|\n|\r)/);
  let result = "";
  for (let i = 0; i < pieces.length; i++) {
    const segment = pieces[i];
    if (segment === void 0) {
      continue;
    }
    if (i % 2 === 0) {
      result += segment.trimEnd();
    } else {
      result += segment;
    }
  }
  return result;
}
function normalizeLineForComparison(value) {
  return normalizeBasicCharacters(value).trimEnd();
}
function seekSequenceWithTransform(lines, pattern, transform) {
  if (pattern.length === 0) {
    return 0;
  }
  if (pattern.length > lines.length) {
    return null;
  }
  outer: for (let i = 0; i <= lines.length - pattern.length; i++) {
    for (let p = 0; p < pattern.length; p++) {
      if (transform(lines[i + p]) !== transform(pattern[p])) {
        continue outer;
      }
    }
    return i;
  }
  return null;
}
function buildLineIndex(text) {
  const lines = text.split("\n");
  const offsets = new Array(lines.length + 1);
  let cursor = 0;
  for (let i = 0; i < lines.length; i++) {
    offsets[i] = cursor;
    cursor += lines[i].length;
    if (i < lines.length - 1) {
      cursor += 1;
    }
  }
  offsets[lines.length] = text.length;
  return { lines, offsets };
}
function sliceFromLines(text, offsets, lines, startLine, lineCount, includeTrailingNewline) {
  if (lineCount === 0) {
    return includeTrailingNewline ? "\n" : "";
  }
  const startIndex = offsets[startLine] ?? 0;
  const lastLineIndex = startLine + lineCount - 1;
  const lastLineStart = offsets[lastLineIndex] ?? 0;
  let endIndex = lastLineStart + (lines[lastLineIndex]?.length ?? 0);
  if (includeTrailingNewline) {
    const nextLineStart = offsets[startLine + lineCount];
    if (nextLineStart !== void 0) {
      endIndex = nextLineStart;
    } else if (text.endsWith("\n")) {
      endIndex = text.length;
    }
  }
  return text.slice(startIndex, endIndex);
}
function findLineBasedMatch(haystack, needle) {
  const { lines, offsets } = buildLineIndex(haystack);
  const patternLines = needle.split("\n");
  const endsWithNewline = needle.endsWith("\n");
  if (patternLines.length === 0) {
    return null;
  }
  const attemptMatch = /* @__PURE__ */ __name((candidate) => {
    for (const pass of LINE_COMPARISON_PASSES) {
      const idx = seekSequenceWithTransform(lines, candidate, pass);
      if (idx !== null) {
        return idx;
      }
    }
    return seekSequenceWithTransform(lines, candidate, normalizeLineForComparison);
  }, "attemptMatch");
  let matchIndex = attemptMatch(patternLines);
  if (matchIndex !== null) {
    return {
      slice: sliceFromLines(haystack, offsets, lines, matchIndex, patternLines.length, endsWithNewline),
      removedTrailingFinalEmptyLine: false
    };
  }
  if (patternLines.at(-1) === "") {
    const trimmedPattern = patternLines.slice(0, -1);
    if (trimmedPattern.length === 0) {
      return null;
    }
    matchIndex = attemptMatch(trimmedPattern);
    if (matchIndex !== null) {
      return {
        slice: sliceFromLines(haystack, offsets, lines, matchIndex, trimmedPattern.length, false),
        removedTrailingFinalEmptyLine: true
      };
    }
  }
  return null;
}
function findMatchedSlice(haystack, needle) {
  if (needle === "") {
    return null;
  }
  const literalIndex = haystack.indexOf(needle);
  if (literalIndex !== -1) {
    return {
      slice: haystack.slice(literalIndex, literalIndex + needle.length),
      removedTrailingFinalEmptyLine: false
    };
  }
  const normalizedHaystack = normalizeBasicCharacters(haystack);
  const normalizedNeedleChars = normalizeBasicCharacters(needle);
  const normalizedIndex = normalizedHaystack.indexOf(normalizedNeedleChars);
  if (normalizedIndex !== -1) {
    return {
      slice: haystack.slice(normalizedIndex, normalizedIndex + needle.length),
      removedTrailingFinalEmptyLine: false
    };
  }
  return findLineBasedMatch(haystack, needle);
}
function removeTrailingNewline(text) {
  if (text.endsWith("\r\n")) {
    return text.slice(0, -2);
  }
  if (text.endsWith("\n") || text.endsWith("\r")) {
    return text.slice(0, -1);
  }
  return text;
}
function adjustNewStringForTrailingLine(newString, removedTrailingLine) {
  return removedTrailingLine ? removeTrailingNewline(newString) : newString;
}
function normalizeEditStrings(fileContent, oldString, newString) {
  const trimmedNewString = stripTrailingWhitespacePreserveNewlines(newString);
  if (fileContent === null || oldString === "") {
    return {
      oldString,
      newString: trimmedNewString
    };
  }
  const canonicalOriginal = findMatchedSlice(fileContent, oldString);
  if (canonicalOriginal !== null) {
    return {
      oldString: canonicalOriginal.slice,
      newString: adjustNewStringForTrailingLine(trimmedNewString, canonicalOriginal.removedTrailingFinalEmptyLine)
    };
  }
  return {
    oldString,
    newString: trimmedNewString
  };
}
function maybeAugmentOldStringForDeletion(fileContent, oldString, newString) {
  if (fileContent === null || oldString === "" || newString !== "" || oldString.endsWith("\n")) {
    return oldString;
  }
  const candidate = `${oldString}
`;
  return fileContent.includes(candidate) ? candidate : oldString;
}
function countOccurrences(source2, substr) {
  if (substr === "") {
    return 0;
  }
  let count = 0;
  let index = source2.indexOf(substr);
  while (index !== -1) {
    count++;
    index = source2.indexOf(substr, index + substr.length);
  }
  return count;
}
function extractEditSnippet(oldContent, newContent) {
  const newLines = newContent.split("\n");
  const totalLines = newLines.length;
  if (oldContent === null) {
    return {
      startLine: 1,
      endLine: totalLines,
      totalLines,
      content: newContent
    };
  }
  if (oldContent === newContent || !newContent) {
    return null;
  }
  const oldLines = oldContent.split("\n");
  let firstDiffLine = 0;
  const minLength = Math.min(oldLines.length, newLines.length);
  while (firstDiffLine < minLength) {
    if (oldLines[firstDiffLine] !== newLines[firstDiffLine]) {
      break;
    }
    firstDiffLine++;
  }
  let oldEndIndex = oldLines.length - 1;
  let newEndIndex = newLines.length - 1;
  while (oldEndIndex >= firstDiffLine && newEndIndex >= firstDiffLine) {
    if (oldLines[oldEndIndex] !== newLines[newEndIndex]) {
      break;
    }
    oldEndIndex--;
    newEndIndex--;
  }
  const changeStart = firstDiffLine + 1;
  const changeEnd = newEndIndex + 1;
  if (changeEnd - changeStart > SNIPPET_MAX_LINES) {
    return null;
  }
  const snippetStart = Math.max(1, changeStart - SNIPPET_CONTEXT_LINES);
  const snippetEnd = Math.min(totalLines, changeEnd + SNIPPET_CONTEXT_LINES);
  const snippetLines = newLines.slice(snippetStart - 1, snippetEnd);
  return {
    startLine: snippetStart,
    endLine: snippetEnd,
    totalLines,
    content: snippetLines.join("\n")
  };
}
var UNICODE_EQUIVALENT_MAP, LINE_COMPARISON_PASSES, SNIPPET_CONTEXT_LINES, SNIPPET_MAX_LINES;
var init_editHelper = __esm({
  "packages/core/dist/src/utils/editHelper.js"() {
    "use strict";
    init_esbuild_shims();
    UNICODE_EQUIVALENT_MAP = {
      // Hyphen variations → ASCII hyphen-minus.
      "\u2010": "-",
      "\u2011": "-",
      "\u2012": "-",
      "\u2013": "-",
      "\u2014": "-",
      "\u2015": "-",
      "\u2212": "-",
      // Curly single quotes → straight apostrophe.
      "\u2018": "'",
      "\u2019": "'",
      "\u201A": "'",
      "\u201B": "'",
      // Curly double quotes → straight double quote.
      "\u201C": '"',
      "\u201D": '"',
      "\u201E": '"',
      "\u201F": '"',
      // Whitespace variants → normal space.
      "\xA0": " ",
      "\u2002": " ",
      "\u2003": " ",
      "\u2004": " ",
      "\u2005": " ",
      "\u2006": " ",
      "\u2007": " ",
      "\u2008": " ",
      "\u2009": " ",
      "\u200A": " ",
      "\u202F": " ",
      "\u205F": " ",
      "\u3000": " "
    };
    __name(normalizeBasicCharacters, "normalizeBasicCharacters");
    __name(stripTrailingWhitespacePreserveNewlines, "stripTrailingWhitespacePreserveNewlines");
    LINE_COMPARISON_PASSES = [
      (value) => value,
      (value) => value.trimEnd()
    ];
    __name(normalizeLineForComparison, "normalizeLineForComparison");
    __name(seekSequenceWithTransform, "seekSequenceWithTransform");
    __name(buildLineIndex, "buildLineIndex");
    __name(sliceFromLines, "sliceFromLines");
    __name(findLineBasedMatch, "findLineBasedMatch");
    __name(findMatchedSlice, "findMatchedSlice");
    __name(removeTrailingNewline, "removeTrailingNewline");
    __name(adjustNewStringForTrailingLine, "adjustNewStringForTrailingLine");
    __name(normalizeEditStrings, "normalizeEditStrings");
    __name(maybeAugmentOldStringForDeletion, "maybeAugmentOldStringForDeletion");
    __name(countOccurrences, "countOccurrences");
    SNIPPET_CONTEXT_LINES = 4;
    SNIPPET_MAX_LINES = 1e3;
    __name(extractEditSnippet, "extractEditSnippet");
  }
});

// packages/core/dist/src/tools/edit.js
import * as fs32 from "node:fs";
import * as path34 from "node:path";
function applyReplacement(currentContent, oldString, newString, isNewFile) {
  if (isNewFile) {
    return newString;
  }
  if (currentContent === null) {
    return oldString === "" ? newString : "";
  }
  if (oldString === "" && !isNewFile) {
    return currentContent;
  }
  return safeLiteralReplace(currentContent, oldString, newString);
}
var EditToolInvocation, EditTool;
var init_edit = __esm({
  "packages/core/dist/src/tools/edit.js"() {
    "use strict";
    init_esbuild_shims();
    init_lib();
    init_tools();
    init_tool_error();
    init_paths();
    init_errors();
    init_config3();
    init_diffOptions();
    init_read_file();
    init_tool_names();
    init_loggers();
    init_types3();
    init_metrics2();
    init_fileUtils();
    init_language_detection();
    init_ide_client();
    init_textUtils();
    init_editHelper();
    __name(applyReplacement, "applyReplacement");
    EditToolInvocation = class {
      static {
        __name(this, "EditToolInvocation");
      }
      config;
      params;
      constructor(config, params) {
        this.config = config;
        this.params = params;
      }
      toolLocations() {
        return [{ path: this.params.file_path }];
      }
      /**
       * Calculates the potential outcome of an edit operation.
       * @param params Parameters for the edit operation
       * @returns An object describing the potential edit outcome
       * @throws File system errors if reading the file fails unexpectedly (e.g., permissions)
       */
      async calculateEdit(params) {
        const replaceAll = params.replace_all ?? false;
        let currentContent = null;
        let fileExists2 = false;
        let isNewFile = false;
        let finalNewString = params.new_string;
        let finalOldString = params.old_string;
        let occurrences = 0;
        let error = void 0;
        try {
          currentContent = await this.config.getFileSystemService().readTextFile(params.file_path);
          currentContent = currentContent.replace(/\r\n/g, "\n");
          fileExists2 = true;
        } catch (err) {
          if (!isNodeError(err) || err.code !== "ENOENT") {
            throw err;
          }
          fileExists2 = false;
        }
        const normalizedStrings = normalizeEditStrings(currentContent, finalOldString, finalNewString);
        finalOldString = normalizedStrings.oldString;
        finalNewString = normalizedStrings.newString;
        if (finalOldString === "" && !fileExists2) {
          isNewFile = true;
        } else if (!fileExists2) {
          error = {
            display: `File not found. Cannot apply edit. Use an empty old_string to create a new file.`,
            raw: `File not found: ${params.file_path}`,
            type: ToolErrorType.FILE_NOT_FOUND
          };
        } else if (currentContent !== null) {
          finalOldString = maybeAugmentOldStringForDeletion(currentContent, finalOldString, finalNewString);
          occurrences = countOccurrences(currentContent, finalOldString);
          if (params.old_string === "") {
            error = {
              display: `Failed to edit. Attempted to create a file that already exists.`,
              raw: `File already exists, cannot create: ${params.file_path}`,
              type: ToolErrorType.ATTEMPT_TO_CREATE_EXISTING_FILE
            };
          } else if (occurrences === 0) {
            error = {
              display: `Failed to edit, could not find the string to replace.`,
              raw: `Failed to edit, 0 occurrences found for old_string in ${params.file_path}. No edits made. The exact text in old_string was not found. Ensure you're not escaping content incorrectly and check whitespace, indentation, and context. Use ${ReadFileTool.Name} tool to verify.`,
              type: ToolErrorType.EDIT_NO_OCCURRENCE_FOUND
            };
          } else if (!replaceAll && occurrences > 1) {
            error = {
              display: `Failed to edit because the text matches multiple locations. Provide more context or set replace_all to true.`,
              raw: `Failed to edit. Found ${occurrences} occurrences for old_string in ${params.file_path} but replace_all was not enabled.`,
              type: ToolErrorType.EDIT_EXPECTED_OCCURRENCE_MISMATCH
            };
          } else if (finalOldString === finalNewString) {
            error = {
              display: `No changes to apply. The old_string and new_string are identical.`,
              raw: `No changes to apply. The old_string and new_string are identical in file: ${params.file_path}`,
              type: ToolErrorType.EDIT_NO_CHANGE
            };
          }
        } else {
          error = {
            display: `Failed to read content of file.`,
            raw: `Failed to read content of existing file: ${params.file_path}`,
            type: ToolErrorType.READ_CONTENT_FAILURE
          };
        }
        const newContent = !error ? applyReplacement(currentContent, finalOldString, finalNewString, isNewFile) : currentContent ?? "";
        if (!error && fileExists2 && currentContent === newContent) {
          error = {
            display: "No changes to apply. The new content is identical to the current content.",
            raw: `No changes to apply. The new content is identical to the current content in file: ${params.file_path}`,
            type: ToolErrorType.EDIT_NO_CHANGE
          };
        }
        return {
          currentContent,
          newContent,
          occurrences,
          error,
          isNewFile
        };
      }
      /**
       * Handles the confirmation prompt for the Edit tool in the CLI.
       * It needs to calculate the diff to show the user.
       */
      async shouldConfirmExecute(abortSignal) {
        if (this.config.getApprovalMode() === ApprovalMode.AUTO_EDIT) {
          return false;
        }
        let editData;
        try {
          editData = await this.calculateEdit(this.params);
        } catch (error) {
          if (abortSignal.aborted) {
            throw error;
          }
          const errorMsg = error instanceof Error ? error.message : String(error);
          console.log(`Error preparing edit: ${errorMsg}`);
          return false;
        }
        if (editData.error) {
          console.log(`Error: ${editData.error.display}`);
          return false;
        }
        const fileName = path34.basename(this.params.file_path);
        const fileDiff = createPatch(fileName, editData.currentContent ?? "", editData.newContent, "Current", "Proposed", DEFAULT_DIFF_OPTIONS);
        const ideClient = await IdeClient.getInstance();
        const ideConfirmation = this.config.getIdeMode() && ideClient.isDiffingEnabled() ? ideClient.openDiff(this.params.file_path, editData.newContent) : void 0;
        const confirmationDetails = {
          type: "edit",
          title: `Confirm Edit: ${shortenPath(makeRelative(this.params.file_path, this.config.getTargetDir()))}`,
          fileName,
          filePath: this.params.file_path,
          fileDiff,
          originalContent: editData.currentContent,
          newContent: editData.newContent,
          onConfirm: /* @__PURE__ */ __name(async (outcome) => {
            if (outcome === ToolConfirmationOutcome.ProceedAlways) {
              this.config.setApprovalMode(ApprovalMode.AUTO_EDIT);
            }
            if (ideConfirmation) {
              const result = await ideConfirmation;
              if (result.status === "accepted" && result.content) {
                this.params.old_string = editData.currentContent ?? "";
                this.params.new_string = result.content;
              }
            }
          }, "onConfirm"),
          ideConfirmation
        };
        return confirmationDetails;
      }
      getDescription() {
        const relativePath = makeRelative(this.params.file_path, this.config.getTargetDir());
        if (this.params.old_string === "") {
          return `Create ${shortenPath(relativePath)}`;
        }
        const oldStringSnippet = this.params.old_string.split("\n")[0].substring(0, 30) + (this.params.old_string.length > 30 ? "..." : "");
        const newStringSnippet = this.params.new_string.split("\n")[0].substring(0, 30) + (this.params.new_string.length > 30 ? "..." : "");
        if (this.params.old_string === this.params.new_string) {
          return `No file changes to ${shortenPath(relativePath)}`;
        }
        return `${shortenPath(relativePath)}: ${oldStringSnippet} => ${newStringSnippet}`;
      }
      /**
       * Executes the edit operation with the given parameters.
       * @param params Parameters for the edit operation
       * @returns Result of the edit operation
       */
      async execute(signal) {
        let editData;
        try {
          editData = await this.calculateEdit(this.params);
        } catch (error) {
          if (signal.aborted) {
            throw error;
          }
          const errorMsg = error instanceof Error ? error.message : String(error);
          return {
            llmContent: `Error preparing edit: ${errorMsg}`,
            returnDisplay: `Error preparing edit: ${errorMsg}`,
            error: {
              message: errorMsg,
              type: ToolErrorType.EDIT_PREPARATION_FAILURE
            }
          };
        }
        if (editData.error) {
          return {
            llmContent: editData.error.raw,
            returnDisplay: `Error: ${editData.error.display}`,
            error: {
              message: editData.error.raw,
              type: editData.error.type
            }
          };
        }
        try {
          this.ensureParentDirectoriesExist(this.params.file_path);
          await this.config.getFileSystemService().writeTextFile(this.params.file_path, editData.newContent);
          const fileName = path34.basename(this.params.file_path);
          const originallyProposedContent = this.params.ai_proposed_content || editData.newContent;
          const diffStat = getDiffStat(fileName, editData.currentContent ?? "", originallyProposedContent, editData.newContent);
          const fileDiff = createPatch(
            fileName,
            editData.currentContent ?? "",
            // Should not be null here if not isNewFile
            editData.newContent,
            "Current",
            "Proposed",
            DEFAULT_DIFF_OPTIONS
          );
          const displayResult = {
            fileDiff,
            fileName,
            originalContent: editData.currentContent,
            newContent: editData.newContent,
            diffStat
          };
          const mimetype = getSpecificMimeType(this.params.file_path);
          const programmingLanguage = getLanguageFromFilePath(this.params.file_path);
          const extension = path34.extname(this.params.file_path);
          const operation = editData.isNewFile ? FileOperation.CREATE : FileOperation.UPDATE;
          logFileOperation(this.config, new FileOperationEvent(EditTool.Name, operation, editData.newContent.split("\n").length, mimetype, extension, programmingLanguage));
          const llmSuccessMessageParts = [
            editData.isNewFile ? `Created new file: ${this.params.file_path} with provided content.` : `The file: ${this.params.file_path} has been updated.`
          ];
          const snippetResult = extractEditSnippet(editData.currentContent, editData.newContent);
          if (snippetResult) {
            const snippetText = `Showing lines ${snippetResult.startLine}-${snippetResult.endLine} of ${snippetResult.totalLines} from the edited file:

---

${snippetResult.content}`;
            llmSuccessMessageParts.push(snippetText);
          }
          return {
            llmContent: llmSuccessMessageParts.join(" "),
            returnDisplay: displayResult
          };
        } catch (error) {
          const errorMsg = error instanceof Error ? error.message : String(error);
          return {
            llmContent: `Error executing edit: ${errorMsg}`,
            returnDisplay: `Error writing file: ${errorMsg}`,
            error: {
              message: errorMsg,
              type: ToolErrorType.FILE_WRITE_FAILURE
            }
          };
        }
      }
      /**
       * Creates parent directories if they don't exist
       */
      ensureParentDirectoriesExist(filePath) {
        const dirName = path34.dirname(filePath);
        if (!fs32.existsSync(dirName)) {
          fs32.mkdirSync(dirName, { recursive: true });
        }
      }
    };
    EditTool = class _EditTool extends BaseDeclarativeTool {
      static {
        __name(this, "EditTool");
      }
      config;
      static Name = ToolNames.EDIT;
      constructor(config) {
        super(_EditTool.Name, ToolDisplayNames.EDIT, `Replaces text within a file. By default, replaces a single occurrence. Set \`replace_all\` to true when you intend to modify every instance of \`old_string\`. This tool requires providing significant context around the change to ensure precise targeting. Always use the ${ReadFileTool.Name} tool to examine the file's current content before attempting a text replacement.

      The user has the ability to modify the \`new_string\` content. If modified, this will be stated in the response.

Expectation for required parameters:
1. \`file_path\` MUST be an absolute path; otherwise an error will be thrown.
2. \`old_string\` MUST be the exact literal text to replace (including all whitespace, indentation, newlines, and surrounding code etc.).
3. \`new_string\` MUST be the exact literal text to replace \`old_string\` with (also including all whitespace, indentation, newlines, and surrounding code etc.). Ensure the resulting code is correct and idiomatic.
4. NEVER escape \`old_string\` or \`new_string\`, that would break the exact literal text requirement.
**Important:** If ANY of the above are not satisfied, the tool will fail. CRITICAL for \`old_string\`: Must uniquely identify the single instance to change. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string matches multiple locations, or does not match exactly, the tool will fail.
**Multiple replacements:** Set \`replace_all\` to true when you want to replace every occurrence that matches \`old_string\`.`, Kind.Edit, {
          properties: {
            file_path: {
              description: "The absolute path to the file to modify. Must start with '/'.",
              type: "string"
            },
            old_string: {
              description: "The exact literal text to replace, preferably unescaped. For single replacements (default), include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string is not the exact literal text (i.e. you escaped it) or does not match exactly, the tool will fail.",
              type: "string"
            },
            new_string: {
              description: "The exact literal text to replace `old_string` with, preferably unescaped. Provide the EXACT text. Ensure the resulting code is correct and idiomatic.",
              type: "string"
            },
            replace_all: {
              type: "boolean",
              description: "Replace all occurrences of old_string (default false)."
            }
          },
          required: ["file_path", "old_string", "new_string"],
          type: "object"
        });
        this.config = config;
      }
      /**
       * Validates the parameters for the Edit tool
       * @param params Parameters to validate
       * @returns Error message string or null if valid
       */
      validateToolParamValues(params) {
        if (!params.file_path) {
          return "The 'file_path' parameter must be non-empty.";
        }
        if (!path34.isAbsolute(params.file_path)) {
          return `File path must be absolute: ${params.file_path}`;
        }
        const workspaceContext = this.config.getWorkspaceContext();
        if (!workspaceContext.isPathWithinWorkspace(params.file_path)) {
          const directories = workspaceContext.getDirectories();
          return `File path must be within one of the workspace directories: ${directories.join(", ")}`;
        }
        return null;
      }
      createInvocation(params) {
        return new EditToolInvocation(this.config, params);
      }
      getModifyContext(_) {
        return {
          getFilePath: /* @__PURE__ */ __name((params) => params.file_path, "getFilePath"),
          getCurrentContent: /* @__PURE__ */ __name(async (params) => {
            try {
              return this.config.getFileSystemService().readTextFile(params.file_path);
            } catch (err) {
              if (!isNodeError(err) || err.code !== "ENOENT")
                throw err;
              return "";
            }
          }, "getCurrentContent"),
          getProposedContent: /* @__PURE__ */ __name(async (params) => {
            try {
              const currentContent = await this.config.getFileSystemService().readTextFile(params.file_path);
              return applyReplacement(currentContent, params.old_string, params.new_string, params.old_string === "" && currentContent === "");
            } catch (err) {
              if (!isNodeError(err) || err.code !== "ENOENT")
                throw err;
              return "";
            }
          }, "getProposedContent"),
          createUpdatedParams: /* @__PURE__ */ __name((oldContent, modifiedProposedContent, originalParams) => ({
            ...originalParams,
            ai_proposed_content: oldContent,
            old_string: oldContent,
            new_string: modifiedProposedContent,
            modified_by_user: true
          }), "createUpdatedParams")
        };
      }
    };
  }
});

// packages/core/dist/src/tools/exitPlanMode.js
var exitPlanModeToolDescription, exitPlanModeToolSchemaData, ExitPlanModeToolInvocation, ExitPlanModeTool;
var init_exitPlanMode = __esm({
  "packages/core/dist/src/tools/exitPlanMode.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    init_config3();
    init_tool_names();
    exitPlanModeToolDescription = `Use this tool when you are in plan mode and have finished presenting your plan and are ready to code. This will prompt the user to exit plan mode.
IMPORTANT: Only use this tool when the task requires planning the implementation steps of a task that requires writing code. For research tasks where you're gathering information, searching files, reading files or in general trying to understand the codebase - do NOT use this tool.

Eg.
1. Initial task: "Search for and understand the implementation of vim mode in the codebase" - Do not use the exit plan mode tool because you are not planning the implementation steps of a task.
2. Initial task: "Help me implement yank mode for vim" - Use the exit plan mode tool after you have finished planning the implementation steps of the task.
`;
    exitPlanModeToolSchemaData = {
      name: "exit_plan_mode",
      description: exitPlanModeToolDescription,
      parametersJsonSchema: {
        type: "object",
        properties: {
          plan: {
            type: "string",
            description: "The plan you came up with, that you want to run by the user for approval. Supports markdown. The plan should be pretty concise."
          }
        },
        required: ["plan"],
        additionalProperties: false,
        $schema: "http://json-schema.org/draft-07/schema#"
      }
    };
    ExitPlanModeToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "ExitPlanModeToolInvocation");
      }
      config;
      wasApproved = false;
      constructor(config, params) {
        super(params);
        this.config = config;
      }
      getDescription() {
        return "Present implementation plan for user approval";
      }
      async shouldConfirmExecute(_abortSignal) {
        const details = {
          type: "plan",
          title: "Would you like to proceed?",
          plan: this.params.plan,
          onConfirm: /* @__PURE__ */ __name(async (outcome) => {
            switch (outcome) {
              case ToolConfirmationOutcome.ProceedAlways:
                this.wasApproved = true;
                this.setApprovalModeSafely(ApprovalMode.AUTO_EDIT);
                break;
              case ToolConfirmationOutcome.ProceedOnce:
                this.wasApproved = true;
                this.setApprovalModeSafely(ApprovalMode.DEFAULT);
                break;
              case ToolConfirmationOutcome.Cancel:
                this.wasApproved = false;
                this.setApprovalModeSafely(ApprovalMode.PLAN);
                break;
              default:
                this.wasApproved = true;
                this.setApprovalModeSafely(ApprovalMode.DEFAULT);
                break;
            }
          }, "onConfirm")
        };
        return details;
      }
      setApprovalModeSafely(mode) {
        try {
          this.config.setApprovalMode(mode);
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : String(error);
          console.error(`[ExitPlanModeTool] Failed to set approval mode to "${mode}": ${errorMessage}`);
        }
      }
      async execute(_signal) {
        const { plan } = this.params;
        try {
          if (!this.wasApproved) {
            const rejectionMessage = "Plan execution was not approved. Remaining in plan mode.";
            return {
              llmContent: rejectionMessage,
              returnDisplay: rejectionMessage
            };
          }
          const llmMessage = `User has approved your plan. You can now start coding. Start with updating your todo list if applicable.`;
          const displayMessage = "User approved the plan.";
          return {
            llmContent: llmMessage,
            returnDisplay: {
              type: "plan_summary",
              message: displayMessage,
              plan
            }
          };
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : String(error);
          console.error(`[ExitPlanModeTool] Error executing exit_plan_mode: ${errorMessage}`);
          const errorLlmContent = `Failed to present plan: ${errorMessage}`;
          return {
            llmContent: errorLlmContent,
            returnDisplay: `Error presenting plan: ${errorMessage}`
          };
        }
      }
    };
    ExitPlanModeTool = class _ExitPlanModeTool extends BaseDeclarativeTool {
      static {
        __name(this, "ExitPlanModeTool");
      }
      config;
      static Name = ToolNames.EXIT_PLAN_MODE;
      constructor(config) {
        super(_ExitPlanModeTool.Name, ToolDisplayNames.EXIT_PLAN_MODE, exitPlanModeToolDescription, Kind.Think, exitPlanModeToolSchemaData.parametersJsonSchema);
        this.config = config;
      }
      validateToolParams(params) {
        if (!params.plan || typeof params.plan !== "string" || params.plan.trim() === "") {
          return 'Parameter "plan" must be a non-empty string.';
        }
        return null;
      }
      createInvocation(params) {
        return new ExitPlanModeToolInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/tools/glob.js
import fs33 from "node:fs";
import path35 from "node:path";
function sortFileEntries(entries, nowTimestamp, recencyThresholdMs) {
  const sortedEntries = [...entries];
  sortedEntries.sort((a, b) => {
    const mtimeA = a.mtimeMs ?? 0;
    const mtimeB = b.mtimeMs ?? 0;
    const aIsRecent = nowTimestamp - mtimeA < recencyThresholdMs;
    const bIsRecent = nowTimestamp - mtimeB < recencyThresholdMs;
    if (aIsRecent && bIsRecent) {
      return mtimeB - mtimeA;
    } else if (aIsRecent) {
      return -1;
    } else if (bIsRecent) {
      return 1;
    } else {
      return a.fullpath().localeCompare(b.fullpath());
    }
  });
  return sortedEntries;
}
var MAX_FILE_COUNT, GlobToolInvocation, GlobTool;
var init_glob2 = __esm({
  "packages/core/dist/src/tools/glob.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm9();
    init_tools();
    init_tool_names();
    init_paths();
    init_config3();
    init_constants3();
    init_tool_error();
    init_errors();
    MAX_FILE_COUNT = 100;
    __name(sortFileEntries, "sortFileEntries");
    GlobToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "GlobToolInvocation");
      }
      config;
      fileService;
      constructor(config, params) {
        super(params);
        this.config = config;
        this.fileService = config.getFileService();
      }
      getDescription() {
        let description = `'${this.params.pattern}'`;
        if (this.params.path) {
          description += ` in path '${this.params.path}'`;
        }
        return description;
      }
      async execute(signal) {
        try {
          const searchDirAbs = resolveAndValidatePath(this.config, this.params.path);
          const searchLocationDescription = this.params.path ? `within ${searchDirAbs}` : `in the workspace directory`;
          let pattern = this.params.pattern;
          const fullPath = path35.join(searchDirAbs, pattern);
          if (fs33.existsSync(fullPath)) {
            pattern = escape3(pattern);
          }
          const allEntries = await glob(pattern, {
            cwd: searchDirAbs,
            withFileTypes: true,
            nodir: true,
            stat: true,
            nocase: true,
            dot: true,
            follow: false,
            signal
          });
          const relativePaths = allEntries.map((p) => path35.relative(this.config.getTargetDir(), p.fullpath()));
          const { filteredPaths } = this.fileService.filterFilesWithReport(relativePaths, this.getFileFilteringOptions());
          const filteredAbsolutePaths = new Set(filteredPaths.map((p) => path35.resolve(this.config.getTargetDir(), p)));
          const filteredEntries = allEntries.filter((entry) => filteredAbsolutePaths.has(entry.fullpath()));
          if (!filteredEntries || filteredEntries.length === 0) {
            return {
              llmContent: `No files found matching pattern "${this.params.pattern}" ${searchLocationDescription}`,
              returnDisplay: `No files found`
            };
          }
          const oneDayInMs = 24 * 60 * 60 * 1e3;
          const nowTimestamp = (/* @__PURE__ */ new Date()).getTime();
          const sortedEntries = sortFileEntries(filteredEntries, nowTimestamp, oneDayInMs);
          const totalFileCount = sortedEntries.length;
          const fileLimit = Math.min(MAX_FILE_COUNT, this.config.getTruncateToolOutputLines());
          const truncated = totalFileCount > fileLimit;
          const entriesToShow = truncated ? sortedEntries.slice(0, fileLimit) : sortedEntries;
          const sortedAbsolutePaths = entriesToShow.map((entry) => entry.fullpath());
          const fileListDescription = sortedAbsolutePaths.join("\n");
          let resultMessage = `Found ${totalFileCount} file(s) matching "${this.params.pattern}" ${searchLocationDescription}`;
          resultMessage += `, sorted by modification time (newest first):
---
${fileListDescription}`;
          if (truncated) {
            const omittedFiles = totalFileCount - fileLimit;
            const fileTerm = omittedFiles === 1 ? "file" : "files";
            resultMessage += `
---
[${omittedFiles} ${fileTerm} truncated] ...`;
          }
          return {
            llmContent: resultMessage,
            returnDisplay: `Found ${totalFileCount} matching file(s)${truncated ? " (truncated)" : ""}`
          };
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : String(error);
          console.error(`GlobLogic execute Error: ${errorMessage}`, error);
          const rawError = `Error during glob search operation: ${errorMessage}`;
          return {
            llmContent: rawError,
            returnDisplay: `Error: ${errorMessage || "An unexpected error occurred."}`,
            error: {
              message: rawError,
              type: ToolErrorType.GLOB_EXECUTION_ERROR
            }
          };
        }
      }
      getFileFilteringOptions() {
        const options2 = this.config.getFileFilteringOptions?.();
        return {
          respectGitIgnore: options2?.respectGitIgnore ?? DEFAULT_FILE_FILTERING_OPTIONS.respectGitIgnore,
          respectQwenIgnore: options2?.respectQwenIgnore ?? DEFAULT_FILE_FILTERING_OPTIONS.respectQwenIgnore
        };
      }
    };
    GlobTool = class _GlobTool extends BaseDeclarativeTool {
      static {
        __name(this, "GlobTool");
      }
      config;
      static Name = ToolNames.GLOB;
      constructor(config) {
        super(_GlobTool.Name, ToolDisplayNames.GLOB, 'Fast file pattern matching tool that works with any codebase size\n- Supports glob patterns like "**/*.js" or "src/**/*.ts"\n- Returns matching file paths sorted by modification time\n- Use this tool when you need to find files by name patterns\n- When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Agent tool instead\n- You have the capability to call multiple tools in a single response. It is always better to speculatively perform multiple searches as a batch that are potentially useful.', Kind.Search, {
          properties: {
            pattern: {
              description: "The glob pattern to match files against",
              type: "string"
            },
            path: {
              description: 'The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior. Must be a valid directory path if provided.',
              type: "string"
            }
          },
          required: ["pattern"],
          type: "object"
        });
        this.config = config;
      }
      /**
       * Validates the parameters for the tool.
       */
      validateToolParamValues(params) {
        if (!params.pattern || typeof params.pattern !== "string" || params.pattern.trim() === "") {
          return "The 'pattern' parameter cannot be empty.";
        }
        if (params.path) {
          try {
            resolveAndValidatePath(this.config, params.path);
          } catch (error) {
            return getErrorMessage(error);
          }
        }
        return null;
      }
      createInvocation(params) {
        return new GlobToolInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/tools/grep.js
import fsPromises2 from "node:fs/promises";
import path36 from "node:path";
import { EOL as EOL2 } from "node:os";
import { spawn as spawn4 } from "node:child_process";
var GrepToolInvocation, GrepTool;
var init_grep2 = __esm({
  "packages/core/dist/src/tools/grep.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm9();
    init_tools();
    init_tool_names();
    init_paths();
    init_errors();
    init_gitUtils();
    init_tool_error();
    init_shell_utils();
    GrepToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "GrepToolInvocation");
      }
      config;
      fileExclusions;
      constructor(config, params) {
        super(params);
        this.config = config;
        this.fileExclusions = config.getFileExclusions();
      }
      async execute(signal) {
        try {
          const searchDirAbs = resolveAndValidatePath(this.config, this.params.path);
          const searchDirDisplay = this.params.path || ".";
          const rawMatches = await this.performGrepSearch({
            pattern: this.params.pattern,
            path: searchDirAbs,
            glob: this.params.glob,
            signal
          });
          const searchLocationDescription = this.params.path ? `in path "${searchDirDisplay}"` : `in the workspace directory`;
          const filterDescription = this.params.glob ? ` (filter: "${this.params.glob}")` : "";
          if (rawMatches.length === 0) {
            const noMatchMsg = `No matches found for pattern "${this.params.pattern}" ${searchLocationDescription}${filterDescription}.`;
            return { llmContent: noMatchMsg, returnDisplay: `No matches found` };
          }
          const charLimit = this.config.getTruncateToolOutputThreshold();
          const lineLimit = Math.min(this.config.getTruncateToolOutputLines(), this.params.limit ?? Number.POSITIVE_INFINITY);
          let truncatedByLineLimit = false;
          let matchesToInclude = rawMatches;
          if (rawMatches.length > lineLimit) {
            matchesToInclude = rawMatches.slice(0, lineLimit);
            truncatedByLineLimit = true;
          }
          const totalMatches = rawMatches.length;
          const matchTerm = totalMatches === 1 ? "match" : "matches";
          const header = `Found ${totalMatches} ${matchTerm} for pattern "${this.params.pattern}" ${searchLocationDescription}${filterDescription}:
---
`;
          const matchesByFile = matchesToInclude.reduce((acc, match2) => {
            const fileKey = match2.filePath;
            if (!acc[fileKey]) {
              acc[fileKey] = [];
            }
            acc[fileKey].push(match2);
            acc[fileKey].sort((a, b) => a.lineNumber - b.lineNumber);
            return acc;
          }, {});
          let grepOutput = "";
          for (const filePath in matchesByFile) {
            grepOutput += `File: ${filePath}
`;
            matchesByFile[filePath].forEach((match2) => {
              const trimmedLine = match2.line.trim();
              grepOutput += `L${match2.lineNumber}: ${trimmedLine}
`;
            });
            grepOutput += "---\n";
          }
          let truncatedByCharLimit = false;
          if (Number.isFinite(charLimit) && grepOutput.length > charLimit) {
            grepOutput = grepOutput.slice(0, charLimit) + "...";
            truncatedByCharLimit = true;
          }
          const finalLines = grepOutput.split("\n").filter((line) => line.trim() && !line.startsWith("File:") && !line.startsWith("---"));
          const includedLines = finalLines.length;
          let llmContent = header + grepOutput;
          if (truncatedByLineLimit || truncatedByCharLimit) {
            const omittedMatches = totalMatches - includedLines;
            llmContent += ` [${omittedMatches} ${omittedMatches === 1 ? "line" : "lines"} truncated] ...`;
          }
          let displayMessage = `Found ${totalMatches} ${matchTerm}`;
          if (truncatedByLineLimit || truncatedByCharLimit) {
            displayMessage += ` (truncated)`;
          }
          return {
            llmContent: llmContent.trim(),
            returnDisplay: displayMessage
          };
        } catch (error) {
          console.error(`Error during GrepLogic execution: ${error}`);
          const errorMessage = getErrorMessage(error);
          return {
            llmContent: `Error during grep search operation: ${errorMessage}`,
            returnDisplay: `Error: ${errorMessage}`,
            error: {
              message: errorMessage,
              type: ToolErrorType.GREP_EXECUTION_ERROR
            }
          };
        }
      }
      /**
       * Parses the standard output of grep-like commands (git grep, system grep).
       * Expects format: filePath:lineNumber:lineContent
       * Handles colons within file paths and line content correctly.
       * @param {string} output The raw stdout string.
       * @param {string} basePath The absolute directory the search was run from, for relative paths.
       * @returns {GrepMatch[]} Array of match objects.
       */
      parseGrepOutput(output, basePath) {
        const results = [];
        if (!output)
          return results;
        const lines = output.split(EOL2);
        for (const line of lines) {
          if (!line.trim())
            continue;
          const firstColonIndex = line.indexOf(":");
          if (firstColonIndex === -1)
            continue;
          const secondColonIndex = line.indexOf(":", firstColonIndex + 1);
          if (secondColonIndex === -1)
            continue;
          const filePathRaw = line.substring(0, firstColonIndex);
          const lineNumberStr = line.substring(firstColonIndex + 1, secondColonIndex);
          const lineContent = line.substring(secondColonIndex + 1);
          const lineNumber = parseInt(lineNumberStr, 10);
          if (!isNaN(lineNumber)) {
            const absoluteFilePath = path36.resolve(basePath, filePathRaw);
            const relativeFilePath = path36.relative(basePath, absoluteFilePath);
            results.push({
              filePath: relativeFilePath || path36.basename(absoluteFilePath),
              lineNumber,
              line: lineContent
            });
          }
        }
        return results;
      }
      /**
       * Gets a description of the grep operation
       * @returns A string describing the grep
       */
      getDescription() {
        let description = `'${this.params.pattern}' in path '${this.params.path || "./"}'`;
        if (this.params.glob) {
          description += ` (filter: '${this.params.glob}')`;
        }
        return description;
      }
      /**
       * Performs the actual search using the prioritized strategies.
       * @param options Search options including pattern, absolute path, and glob filter.
       * @returns A promise resolving to an array of match objects.
       */
      async performGrepSearch(options2) {
        const { pattern, path: absolutePath, glob: glob2 } = options2;
        let strategyUsed = "none";
        try {
          const isGit = isGitRepository(absolutePath);
          const gitAvailable = isGit && isCommandAvailable("git").available;
          if (gitAvailable) {
            strategyUsed = "git grep";
            const gitArgs = [
              "grep",
              "--untracked",
              "-n",
              "-E",
              "--ignore-case",
              pattern
            ];
            if (glob2) {
              gitArgs.push("--", glob2);
            }
            try {
              const output = await new Promise((resolve24, reject) => {
                const child = spawn4("git", gitArgs, {
                  cwd: absolutePath,
                  windowsHide: true
                });
                const stdoutChunks = [];
                const stderrChunks = [];
                child.stdout.on("data", (chunk) => stdoutChunks.push(chunk));
                child.stderr.on("data", (chunk) => stderrChunks.push(chunk));
                child.on("error", (err) => reject(new Error(`Failed to start git grep: ${err.message}`)));
                child.on("close", (code2) => {
                  const stdoutData = Buffer.concat(stdoutChunks).toString("utf8");
                  const stderrData = Buffer.concat(stderrChunks).toString("utf8");
                  if (code2 === 0)
                    resolve24(stdoutData);
                  else if (code2 === 1)
                    resolve24("");
                  else
                    reject(new Error(`git grep exited with code ${code2}: ${stderrData}`));
                });
              });
              return this.parseGrepOutput(output, absolutePath);
            } catch (gitError) {
              console.debug(`GrepLogic: git grep failed: ${getErrorMessage(gitError)}. Falling back...`);
            }
          }
          const { available: grepAvailable } = isCommandAvailable("grep");
          if (grepAvailable) {
            strategyUsed = "system grep";
            const grepArgs = ["-r", "-n", "-H", "-E"];
            const globExcludes = this.fileExclusions.getGlobExcludes();
            const commonExcludes = globExcludes.map((pattern2) => {
              let dir = pattern2;
              if (dir.startsWith("**/")) {
                dir = dir.substring(3);
              }
              if (dir.endsWith("/**")) {
                dir = dir.slice(0, -3);
              } else if (dir.endsWith("/")) {
                dir = dir.slice(0, -1);
              }
              if (dir && !dir.includes("/") && !dir.includes("*")) {
                return dir;
              }
              return null;
            }).filter((dir) => !!dir);
            commonExcludes.forEach((dir) => grepArgs.push(`--exclude-dir=${dir}`));
            if (glob2) {
              grepArgs.push(`--include=${glob2}`);
            }
            grepArgs.push(pattern);
            grepArgs.push(".");
            try {
              const output = await new Promise((resolve24, reject) => {
                const child = spawn4("grep", grepArgs, {
                  cwd: absolutePath,
                  windowsHide: true
                });
                const stdoutChunks = [];
                const stderrChunks = [];
                const onData = /* @__PURE__ */ __name((chunk) => stdoutChunks.push(chunk), "onData");
                const onStderr = /* @__PURE__ */ __name((chunk) => {
                  const stderrStr = chunk.toString();
                  if (!stderrStr.includes("Permission denied") && !/grep:.*: Is a directory/i.test(stderrStr)) {
                    stderrChunks.push(chunk);
                  }
                }, "onStderr");
                const onError2 = /* @__PURE__ */ __name((err) => {
                  cleanup();
                  reject(new Error(`Failed to start system grep: ${err.message}`));
                }, "onError");
                const onClose = /* @__PURE__ */ __name((code2) => {
                  const stdoutData = Buffer.concat(stdoutChunks).toString("utf8");
                  const stderrData = Buffer.concat(stderrChunks).toString("utf8").trim();
                  cleanup();
                  if (code2 === 0)
                    resolve24(stdoutData);
                  else if (code2 === 1)
                    resolve24("");
                  else {
                    if (stderrData)
                      reject(new Error(`System grep exited with code ${code2}: ${stderrData}`));
                    else
                      resolve24("");
                  }
                }, "onClose");
                const cleanup = /* @__PURE__ */ __name(() => {
                  child.stdout.removeListener("data", onData);
                  child.stderr.removeListener("data", onStderr);
                  child.removeListener("error", onError2);
                  child.removeListener("close", onClose);
                  if (child.connected) {
                    child.disconnect();
                  }
                }, "cleanup");
                child.stdout.on("data", onData);
                child.stderr.on("data", onStderr);
                child.on("error", onError2);
                child.on("close", onClose);
              });
              return this.parseGrepOutput(output, absolutePath);
            } catch (grepError) {
              console.debug(`GrepLogic: System grep failed: ${getErrorMessage(grepError)}. Falling back...`);
            }
          }
          console.debug("GrepLogic: Falling back to JavaScript grep implementation.");
          strategyUsed = "javascript fallback";
          const globPattern = glob2 ? glob2 : "**/*";
          const ignorePatterns = this.fileExclusions.getGlobExcludes();
          const filesIterator = globStream(globPattern, {
            cwd: absolutePath,
            dot: true,
            ignore: ignorePatterns,
            absolute: true,
            nodir: true,
            signal: options2.signal
          });
          const regex3 = new RegExp(pattern, "i");
          const allMatches = [];
          for await (const filePath of filesIterator) {
            const fileAbsolutePath = filePath;
            try {
              const content = await fsPromises2.readFile(fileAbsolutePath, "utf8");
              const lines = content.split(/\r?\n/);
              lines.forEach((line, index) => {
                if (regex3.test(line)) {
                  allMatches.push({
                    filePath: path36.relative(absolutePath, fileAbsolutePath) || path36.basename(fileAbsolutePath),
                    lineNumber: index + 1,
                    line
                  });
                }
              });
            } catch (readError) {
              if (!isNodeError(readError) || readError.code !== "ENOENT") {
                console.debug(`GrepLogic: Could not read/process ${fileAbsolutePath}: ${getErrorMessage(readError)}`);
              }
            }
          }
          return allMatches;
        } catch (error) {
          console.error(`GrepLogic: Error in performGrepSearch (Strategy: ${strategyUsed}): ${getErrorMessage(error)}`);
          throw error;
        }
      }
    };
    GrepTool = class _GrepTool extends BaseDeclarativeTool {
      static {
        __name(this, "GrepTool");
      }
      config;
      static Name = ToolNames.GREP;
      constructor(config) {
        super(_GrepTool.Name, ToolDisplayNames.GREP, 'A powerful search tool for finding patterns in files\n\n  Usage:\n  - ALWAYS use Grep for search tasks. NEVER invoke `grep` or `rg` as a Bash command. The Grep tool has been optimized for correct permissions and access.\n  - Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")\n  - Filter files with glob parameter (e.g., "*.js", "**/*.tsx")\n  - Case-insensitive by default\n  - Use Task tool for open-ended searches requiring multiple rounds\n', Kind.Search, {
          properties: {
            pattern: {
              type: "string",
              description: "The regular expression pattern to search for in file contents"
            },
            glob: {
              type: "string",
              description: 'Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}")'
            },
            path: {
              type: "string",
              description: "File or directory to search in. Defaults to current working directory."
            },
            limit: {
              type: "number",
              description: "Limit output to first N matching lines. Optional - shows all matches if not specified."
            }
          },
          required: ["pattern"],
          type: "object"
        });
        this.config = config;
      }
      /**
       * Validates the parameters for the tool
       * @param params Parameters to validate
       * @returns An error message string if invalid, null otherwise
       */
      validateToolParamValues(params) {
        try {
          new RegExp(params.pattern);
        } catch (error) {
          return `Invalid regular expression pattern: ${params.pattern}. Error: ${getErrorMessage(error)}`;
        }
        if (params.path) {
          try {
            resolveAndValidatePath(this.config, params.path);
          } catch (error) {
            return getErrorMessage(error);
          }
        }
        return null;
      }
      createInvocation(params) {
        return new GrepToolInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/tools/ls.js
import fs34 from "node:fs/promises";
import path37 from "node:path";
var LSToolInvocation, LSTool;
var init_ls = __esm({
  "packages/core/dist/src/tools/ls.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    init_paths();
    init_constants3();
    init_tool_error();
    init_tool_names();
    LSToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "LSToolInvocation");
      }
      config;
      constructor(config, params) {
        super(params);
        this.config = config;
      }
      /**
       * Checks if a filename matches any of the ignore patterns
       * @param filename Filename to check
       * @param patterns Array of glob patterns to check against
       * @returns True if the filename should be ignored
       */
      shouldIgnore(filename, patterns) {
        if (!patterns || patterns.length === 0) {
          return false;
        }
        for (const pattern of patterns) {
          const regexPattern = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
          const regex3 = new RegExp(`^${regexPattern}$`);
          if (regex3.test(filename)) {
            return true;
          }
        }
        return false;
      }
      /**
       * Gets a description of the file reading operation
       * @returns A string describing the file being read
       */
      getDescription() {
        const relativePath = makeRelative(this.params.path, this.config.getTargetDir());
        return shortenPath(relativePath);
      }
      // Helper for consistent error formatting
      errorResult(llmContent, returnDisplay, type) {
        return {
          llmContent,
          // Keep returnDisplay simpler in core logic
          returnDisplay: `Error: ${returnDisplay}`,
          error: {
            message: llmContent,
            type
          }
        };
      }
      /**
       * Executes the LS operation with the given parameters
       * @returns Result of the LS operation
       */
      async execute(_signal) {
        try {
          const stats = await fs34.stat(this.params.path);
          if (!stats) {
            return this.errorResult(`Error: Directory not found or inaccessible: ${this.params.path}`, `Directory not found or inaccessible.`, ToolErrorType.FILE_NOT_FOUND);
          }
          if (!stats.isDirectory()) {
            return this.errorResult(`Error: Path is not a directory: ${this.params.path}`, `Path is not a directory.`, ToolErrorType.PATH_IS_NOT_A_DIRECTORY);
          }
          const files = await fs34.readdir(this.params.path);
          if (files.length === 0) {
            return {
              llmContent: `Directory ${this.params.path} is empty.`,
              returnDisplay: `Directory is empty.`
            };
          }
          const relativePaths = files.map((file) => path37.relative(this.config.getTargetDir(), path37.join(this.params.path, file)));
          const fileDiscovery = this.config.getFileService();
          const { filteredPaths, gitIgnoredCount, qwenIgnoredCount } = fileDiscovery.filterFilesWithReport(relativePaths, {
            respectGitIgnore: this.params.file_filtering_options?.respect_git_ignore ?? this.config.getFileFilteringOptions().respectGitIgnore ?? DEFAULT_FILE_FILTERING_OPTIONS.respectGitIgnore,
            respectQwenIgnore: this.params.file_filtering_options?.respect_qwen_ignore ?? this.config.getFileFilteringOptions().respectQwenIgnore ?? DEFAULT_FILE_FILTERING_OPTIONS.respectQwenIgnore
          });
          const entries = [];
          for (const relativePath of filteredPaths) {
            const fullPath = path37.resolve(this.config.getTargetDir(), relativePath);
            if (this.shouldIgnore(path37.basename(fullPath), this.params.ignore)) {
              continue;
            }
            try {
              const stats2 = await fs34.stat(fullPath);
              const isDir = stats2.isDirectory();
              entries.push({
                name: path37.basename(fullPath),
                path: fullPath,
                isDirectory: isDir,
                size: isDir ? 0 : stats2.size,
                modifiedTime: stats2.mtime
              });
            } catch (error) {
              console.error(`Error accessing ${fullPath}: ${error}`);
            }
          }
          entries.sort((a, b) => {
            if (a.isDirectory && !b.isDirectory)
              return -1;
            if (!a.isDirectory && b.isDirectory)
              return 1;
            return a.name.localeCompare(b.name);
          });
          const directoryContent = entries.map((entry) => `${entry.isDirectory ? "[DIR] " : ""}${entry.name}`).join("\n");
          let resultMessage = `Directory listing for ${this.params.path}:
${directoryContent}`;
          const ignoredMessages = [];
          if (gitIgnoredCount > 0) {
            ignoredMessages.push(`${gitIgnoredCount} git-ignored`);
          }
          if (qwenIgnoredCount > 0) {
            ignoredMessages.push(`${qwenIgnoredCount} qwen-ignored`);
          }
          if (ignoredMessages.length > 0) {
            resultMessage += `

(${ignoredMessages.join(", ")})`;
          }
          let displayMessage = `Listed ${entries.length} item(s).`;
          if (ignoredMessages.length > 0) {
            displayMessage += ` (${ignoredMessages.join(", ")})`;
          }
          return {
            llmContent: resultMessage,
            returnDisplay: displayMessage
          };
        } catch (error) {
          const errorMsg = `Error listing directory: ${error instanceof Error ? error.message : String(error)}`;
          return this.errorResult(errorMsg, "Failed to list directory.", ToolErrorType.LS_EXECUTION_ERROR);
        }
      }
    };
    LSTool = class _LSTool extends BaseDeclarativeTool {
      static {
        __name(this, "LSTool");
      }
      config;
      static Name = ToolNames.LS;
      constructor(config) {
        super(_LSTool.Name, ToolDisplayNames.LS, "Lists the names of files and subdirectories directly within a specified directory path. Can optionally ignore entries matching provided glob patterns.", Kind.Search, {
          properties: {
            path: {
              description: "The absolute path to the directory to list (must be absolute, not relative)",
              type: "string"
            },
            ignore: {
              description: "List of glob patterns to ignore",
              items: {
                type: "string"
              },
              type: "array"
            },
            file_filtering_options: {
              description: "Optional: Whether to respect ignore patterns from .gitignore or .qwenignore",
              type: "object",
              properties: {
                respect_git_ignore: {
                  description: "Optional: Whether to respect .gitignore patterns when listing files. Only available in git repositories. Defaults to true.",
                  type: "boolean"
                },
                respect_qwen_ignore: {
                  description: "Optional: Whether to respect .qwenignore patterns when listing files. Defaults to true.",
                  type: "boolean"
                }
              }
            }
          },
          required: ["path"],
          type: "object"
        });
        this.config = config;
      }
      /**
       * Validates the parameters for the tool
       * @param params Parameters to validate
       * @returns An error message string if invalid, null otherwise
       */
      validateToolParamValues(params) {
        if (!path37.isAbsolute(params.path)) {
          return `Path must be absolute: ${params.path}`;
        }
        const workspaceContext = this.config.getWorkspaceContext();
        if (!workspaceContext.isPathWithinWorkspace(params.path)) {
          const directories = workspaceContext.getDirectories();
          return `Path must be within one of the workspace directories: ${directories.join(", ")}`;
        }
        return null;
      }
      createInvocation(params) {
        return new LSToolInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/tools/read-many-files.js
import * as fs35 from "node:fs";
import * as path38 from "node:path";
function getDefaultExcludes(config) {
  return config?.getFileExclusions().getReadManyFilesExcludes() ?? [];
}
var DEFAULT_OUTPUT_SEPARATOR_FORMAT, DEFAULT_OUTPUT_TERMINATOR, ReadManyFilesToolInvocation, ReadManyFilesTool;
var init_read_many_files = __esm({
  "packages/core/dist/src/tools/read-many-files.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    init_tool_names();
    init_errors();
    init_esm9();
    init_fileUtils();
    init_config3();
    init_metrics2();
    init_telemetry_utils();
    init_loggers();
    init_types3();
    init_tool_error();
    __name(getDefaultExcludes, "getDefaultExcludes");
    DEFAULT_OUTPUT_SEPARATOR_FORMAT = "--- {filePath} ---";
    DEFAULT_OUTPUT_TERMINATOR = "\n--- End of content ---";
    ReadManyFilesToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "ReadManyFilesToolInvocation");
      }
      config;
      constructor(config, params) {
        super(params);
        this.config = config;
      }
      getDescription() {
        const allPatterns = [...this.params.paths, ...this.params.include || []];
        const pathDesc = `using patterns: 
${allPatterns.join("`, `")}
 (within target directory: 
${this.config.getTargetDir()}
) `;
        const paramExcludes = this.params.exclude || [];
        const paramUseDefaultExcludes = this.params.useDefaultExcludes !== false;
        const qwenIgnorePatterns = this.config.getFileService().getQwenIgnorePatterns();
        const finalExclusionPatternsForDescription = paramUseDefaultExcludes ? [
          ...getDefaultExcludes(this.config),
          ...paramExcludes,
          ...qwenIgnorePatterns
        ] : [...paramExcludes, ...qwenIgnorePatterns];
        let excludeDesc = `Excluding: ${finalExclusionPatternsForDescription.length > 0 ? `patterns like 
${finalExclusionPatternsForDescription.slice(0, 2).join("`, `")}${finalExclusionPatternsForDescription.length > 2 ? "...`" : "`"}` : "none specified"}`;
        if (qwenIgnorePatterns.length > 0) {
          const geminiPatternsInEffect = qwenIgnorePatterns.filter((p) => finalExclusionPatternsForDescription.includes(p)).length;
          if (geminiPatternsInEffect > 0) {
            excludeDesc += ` (includes ${geminiPatternsInEffect} from .qwenignore)`;
          }
        }
        return `Will attempt to read and concatenate files ${pathDesc}. ${excludeDesc}. File encoding: ${DEFAULT_ENCODING}. Separator: "${DEFAULT_OUTPUT_SEPARATOR_FORMAT.replace("{filePath}", "path/to/file.ext")}".`;
      }
      async execute(signal) {
        const { paths: inputPatterns, include = [], exclude = [], useDefaultExcludes = true } = this.params;
        const filesToConsider = /* @__PURE__ */ new Set();
        const skippedFiles = [];
        const processedFilesRelativePaths = [];
        const contentParts = [];
        const effectiveExcludes = useDefaultExcludes ? [...getDefaultExcludes(this.config), ...exclude] : [...exclude];
        const searchPatterns = [...inputPatterns, ...include];
        try {
          const allEntries = /* @__PURE__ */ new Set();
          const workspaceDirs = this.config.getWorkspaceContext().getDirectories();
          for (const dir of workspaceDirs) {
            const processedPatterns = [];
            for (const p of searchPatterns) {
              const normalizedP = p.replace(/\\/g, "/");
              const fullPath = path38.join(dir, normalizedP);
              if (fs35.existsSync(fullPath)) {
                processedPatterns.push(escape3(normalizedP));
              } else {
                processedPatterns.push(normalizedP);
              }
            }
            const entriesInDir = await glob(processedPatterns, {
              cwd: dir,
              ignore: effectiveExcludes,
              nodir: true,
              dot: true,
              absolute: true,
              nocase: true,
              signal
            });
            for (const entry of entriesInDir) {
              allEntries.add(entry);
            }
          }
          const relativeEntries = Array.from(allEntries).map((p) => path38.relative(this.config.getTargetDir(), p));
          const fileDiscovery = this.config.getFileService();
          const { filteredPaths, gitIgnoredCount, qwenIgnoredCount } = fileDiscovery.filterFilesWithReport(relativeEntries, {
            respectGitIgnore: this.params.file_filtering_options?.respect_git_ignore ?? this.config.getFileFilteringOptions().respectGitIgnore ?? DEFAULT_FILE_FILTERING_OPTIONS.respectGitIgnore,
            respectQwenIgnore: this.params.file_filtering_options?.respect_qwen_ignore ?? this.config.getFileFilteringOptions().respectQwenIgnore ?? DEFAULT_FILE_FILTERING_OPTIONS.respectQwenIgnore
          });
          for (const relativePath of filteredPaths) {
            const fullPath = path38.resolve(this.config.getTargetDir(), relativePath);
            if (!this.config.getWorkspaceContext().isPathWithinWorkspace(fullPath)) {
              skippedFiles.push({
                path: fullPath,
                reason: `Security: Glob library returned path outside workspace. Path: ${fullPath}`
              });
              continue;
            }
            filesToConsider.add(fullPath);
          }
          if (gitIgnoredCount > 0) {
            skippedFiles.push({
              path: `${gitIgnoredCount} file(s)`,
              reason: "git ignored"
            });
          }
          if (qwenIgnoredCount > 0) {
            skippedFiles.push({
              path: `${qwenIgnoredCount} file(s)`,
              reason: "qwen ignored"
            });
          }
        } catch (error) {
          const errorMessage = `Error during file search: ${getErrorMessage(error)}`;
          return {
            llmContent: errorMessage,
            returnDisplay: `## File Search Error

An error occurred while searching for files:
\`\`\`
${getErrorMessage(error)}
\`\`\``,
            error: {
              message: errorMessage,
              type: ToolErrorType.READ_MANY_FILES_SEARCH_ERROR
            }
          };
        }
        const sortedFiles = Array.from(filesToConsider).sort();
        const truncateToolOutputLines = this.config.getTruncateToolOutputLines();
        const file_line_limit = Number.isFinite(truncateToolOutputLines) ? Math.floor(truncateToolOutputLines / Math.max(1, sortedFiles.length)) : void 0;
        const fileProcessingPromises = sortedFiles.map(async (filePath) => {
          try {
            const relativePathForDisplay = path38.relative(this.config.getTargetDir(), filePath).replace(/\\/g, "/");
            const fileType = await detectFileType(filePath);
            if (fileType === "image" || fileType === "pdf") {
              const fileExtension = path38.extname(filePath).toLowerCase();
              const fileNameWithoutExtension = path38.basename(filePath, fileExtension);
              const requestedExplicitly = inputPatterns.some((pattern) => pattern.toLowerCase().includes(fileExtension) || pattern.includes(fileNameWithoutExtension));
              if (!requestedExplicitly) {
                return {
                  success: false,
                  filePath,
                  relativePathForDisplay,
                  reason: "asset file (image/pdf) was not explicitly requested by name or extension"
                };
              }
            }
            const fileReadResult = await processSingleFileContent(filePath, this.config, 0, file_line_limit);
            if (fileReadResult.error) {
              return {
                success: false,
                filePath,
                relativePathForDisplay,
                reason: `Read error: ${fileReadResult.error}`
              };
            }
            return {
              success: true,
              filePath,
              relativePathForDisplay,
              fileReadResult
            };
          } catch (error) {
            const relativePathForDisplay = path38.relative(this.config.getTargetDir(), filePath).replace(/\\/g, "/");
            return {
              success: false,
              filePath,
              relativePathForDisplay,
              reason: `Unexpected error: ${error instanceof Error ? error.message : String(error)}`
            };
          }
        });
        const results = await Promise.allSettled(fileProcessingPromises);
        for (const result of results) {
          if (result.status === "fulfilled") {
            const fileResult = result.value;
            if (!fileResult.success) {
              skippedFiles.push({
                path: fileResult.relativePathForDisplay,
                reason: fileResult.reason
              });
            } else {
              const { filePath, relativePathForDisplay, fileReadResult } = fileResult;
              if (typeof fileReadResult.llmContent === "string") {
                const separator = DEFAULT_OUTPUT_SEPARATOR_FORMAT.replace("{filePath}", filePath);
                let fileContentForLlm = "";
                if (fileReadResult.isTruncated) {
                  const [start, end] = fileReadResult.linesShown;
                  const total = fileReadResult.originalLineCount;
                  fileContentForLlm = `Showing lines ${start}-${end} of ${total} total lines.
---
${fileReadResult.llmContent}`;
                } else {
                  fileContentForLlm = fileReadResult.llmContent;
                }
                contentParts.push(`${separator}

${fileContentForLlm}

`);
              } else {
                contentParts.push(fileReadResult.llmContent);
              }
              processedFilesRelativePaths.push(relativePathForDisplay);
              const lines = typeof fileReadResult.llmContent === "string" ? fileReadResult.llmContent.split("\n").length : void 0;
              const mimetype = getSpecificMimeType(filePath);
              const programming_language = getProgrammingLanguage({
                absolute_path: filePath
              });
              logFileOperation(this.config, new FileOperationEvent(ReadManyFilesTool.Name, FileOperation.READ, lines, mimetype, path38.extname(filePath), programming_language));
            }
          } else {
            skippedFiles.push({
              path: "unknown",
              reason: `Unexpected error: ${result.reason}`
            });
          }
        }
        let displayMessage = `### ReadManyFiles Result (Target Dir: \`${this.config.getTargetDir()}\`)

`;
        if (processedFilesRelativePaths.length > 0) {
          displayMessage += `Successfully read and concatenated content from **${processedFilesRelativePaths.length} file(s)**.
`;
          if (processedFilesRelativePaths.length <= 10) {
            displayMessage += `
**Processed Files:**
`;
            processedFilesRelativePaths.forEach((p) => displayMessage += `- \`${p}\`
`);
          } else {
            displayMessage += `
**Processed Files (first 10 shown):**
`;
            processedFilesRelativePaths.slice(0, 10).forEach((p) => displayMessage += `- \`${p}\`
`);
            displayMessage += `- ...and ${processedFilesRelativePaths.length - 10} more.
`;
          }
        }
        if (skippedFiles.length > 0) {
          if (processedFilesRelativePaths.length === 0) {
            displayMessage += `No files were read and concatenated based on the criteria.
`;
          }
          if (skippedFiles.length <= 5) {
            displayMessage += `
**Skipped ${skippedFiles.length} item(s):**
`;
          } else {
            displayMessage += `
**Skipped ${skippedFiles.length} item(s) (first 5 shown):**
`;
          }
          skippedFiles.slice(0, 5).forEach((f) => displayMessage += `- \`${f.path}\` (Reason: ${f.reason})
`);
          if (skippedFiles.length > 5) {
            displayMessage += `- ...and ${skippedFiles.length - 5} more.
`;
          }
        } else if (processedFilesRelativePaths.length === 0 && skippedFiles.length === 0) {
          displayMessage += `No files were read and concatenated based on the criteria.
`;
        }
        if (contentParts.length > 0) {
          contentParts.push(DEFAULT_OUTPUT_TERMINATOR);
        } else {
          contentParts.push("No files matching the criteria were found or all were skipped.");
        }
        return {
          llmContent: contentParts,
          returnDisplay: displayMessage.trim()
        };
      }
    };
    ReadManyFilesTool = class _ReadManyFilesTool extends BaseDeclarativeTool {
      static {
        __name(this, "ReadManyFilesTool");
      }
      config;
      static Name = ToolNames.READ_MANY_FILES;
      constructor(config) {
        const parameterSchema = {
          type: "object",
          properties: {
            paths: {
              type: "array",
              items: {
                type: "string",
                minLength: 1
              },
              minItems: 1,
              description: "Required. An array of glob patterns or paths relative to the tool's target directory. Examples: ['src/**/*.ts'], ['README.md', 'docs/']"
            },
            include: {
              type: "array",
              items: {
                type: "string",
                minLength: 1
              },
              description: 'Optional. Additional glob patterns to include. These are merged with `paths`. Example: "*.test.ts" to specifically add test files if they were broadly excluded.',
              default: []
            },
            exclude: {
              type: "array",
              items: {
                type: "string",
                minLength: 1
              },
              description: 'Optional. Glob patterns for files/directories to exclude. Added to default excludes if useDefaultExcludes is true. Example: "**/*.log", "temp/"',
              default: []
            },
            recursive: {
              type: "boolean",
              description: "Optional. Whether to search recursively (primarily controlled by `**` in glob patterns). Defaults to true.",
              default: true
            },
            useDefaultExcludes: {
              type: "boolean",
              description: "Optional. Whether to apply a list of default exclusion patterns (e.g., node_modules, .git, binary files). Defaults to true.",
              default: true
            },
            file_filtering_options: {
              description: "Whether to respect ignore patterns from .gitignore or .qwenignore",
              type: "object",
              properties: {
                respect_git_ignore: {
                  description: "Optional: Whether to respect .gitignore patterns when listing files. Only available in git repositories. Defaults to true.",
                  type: "boolean"
                },
                respect_qwen_ignore: {
                  description: "Optional: Whether to respect .qwenignore patterns when listing files. Defaults to true.",
                  type: "boolean"
                }
              }
            }
          },
          required: ["paths"]
        };
        super(_ReadManyFilesTool.Name, ToolDisplayNames.READ_MANY_FILES, `Reads content from multiple files specified by paths or glob patterns within a configured target directory. For text files, it concatenates their content into a single string. It is primarily designed for text-based files. However, it can also process image (e.g., .png, .jpg) and PDF (.pdf) files if their file names or extensions are explicitly included in the 'paths' argument. For these explicitly requested non-text files, their data is read and included in a format suitable for model consumption (e.g., base64 encoded).

This tool is useful when you need to understand or analyze a collection of files, such as:
- Getting an overview of a codebase or parts of it (e.g., all TypeScript files in the 'src' directory).
- Finding where specific functionality is implemented if the user asks broad questions about code.
- Reviewing documentation files (e.g., all Markdown files in the 'docs' directory).
- Gathering context from multiple configuration files.
- When the user asks to "read all files in X directory" or "show me the content of all Y files".

Use this tool when the user's query implies needing the content of several files simultaneously for context, analysis, or summarization. For text files, it uses default UTF-8 encoding and a '--- {filePath} ---' separator between file contents. The tool inserts a '--- End of content ---' after the last file. Ensure paths are relative to the target directory. Glob patterns like 'src/**/*.js' are supported. Avoid using for single files if a more specific single-file reading tool is available, unless the user specifically requests to process a list containing just one file via this tool. Other binary files (not explicitly requested as image/PDF) are generally skipped. Default excludes apply to common non-text files (except for explicitly requested images/PDFs) and large dependency directories unless 'useDefaultExcludes' is false.`, Kind.Read, parameterSchema);
        this.config = config;
      }
      createInvocation(params) {
        return new ReadManyFilesToolInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/utils/ripgrepUtils.js
import path39 from "node:path";
import { fileURLToPath as fileURLToPath5 } from "node:url";
import { execFile as execFile7 } from "node:child_process";
function wslTimeout() {
  return process.platform === "linux" && process.env["WSL_INTEROP"] ? RIPGREP_WSL_TIMEOUT_MS : RIPGREP_RUN_TIMEOUT_MS;
}
function getPlatformString(platform15) {
  switch (platform15) {
    case "darwin":
    case "linux":
    case "win32":
      return platform15;
    default:
      return void 0;
  }
}
function getArchitectureString(arch3) {
  switch (arch3) {
    case "x64":
    case "arm64":
      return arch3;
    default:
      return void 0;
  }
}
function getBuiltinRipgrep() {
  const platform15 = getPlatformString(process.platform);
  const arch3 = getArchitectureString(process.arch);
  if (!platform15 || !arch3) {
    return null;
  }
  const binaryName = platform15 === "win32" ? "rg.exe" : "rg";
  const isBundled = !__filename2.includes(path39.join("src", "utils"));
  const vendorPath = isBundled ? path39.join(__dirname3, "vendor", "ripgrep", `${arch3}-${platform15}`, binaryName) : path39.join(__dirname3, "..", "..", "..", "vendor", "ripgrep", `${arch3}-${platform15}`, binaryName);
  return vendorPath;
}
async function resolveRipgrep(useBuiltin = true) {
  if (cachedSelection)
    return cachedSelection;
  if (useBuiltin) {
    const rgPath = getBuiltinRipgrep();
    if (rgPath && await fileExists(rgPath)) {
      cachedSelection = { mode: "builtin", command: rgPath };
      return cachedSelection;
    }
  }
  const { available, error } = isCommandAvailable(RIPGREP_COMMAND);
  if (available) {
    cachedSelection = { mode: "system", command: RIPGREP_COMMAND };
    return cachedSelection;
  }
  if (error) {
    throw error;
  }
  return null;
}
async function ensureRipgrepHealthy(selection) {
  if (cachedHealth && cachedHealth.selection.command === selection.command && cachedHealth.working)
    return;
  try {
    const { stdout, code: code2 } = await execCommand(selection.command, ["--version"], {
      timeout: RIPGREP_TEST_TIMEOUT_MS
    });
    const working = code2 === 0 && stdout.startsWith("ripgrep");
    cachedHealth = { working, lastTested: Date.now(), selection };
  } catch (error) {
    cachedHealth = { working: false, lastTested: Date.now(), selection };
    throw error;
  }
}
async function canUseRipgrep(useBuiltin = true) {
  const selection = await resolveRipgrep(useBuiltin);
  if (!selection) {
    return false;
  }
  await ensureRipgrepHealthy(selection);
  return true;
}
async function runRipgrep(args, signal) {
  const selection = await resolveRipgrep();
  if (!selection) {
    throw new Error("ripgrep not found.");
  }
  await ensureRipgrepHealthy(selection);
  return new Promise((resolve24) => {
    const child = execFile7(selection.command, args, {
      maxBuffer: RIPGREP_BUFFER_LIMIT,
      timeout: wslTimeout(),
      signal
    }, (error, stdout = "", stderr = "") => {
      if (!error) {
        resolve24({
          stdout,
          truncated: false
        });
        return;
      }
      const errorCode = error.code;
      if (errorCode === 1) {
        resolve24({ stdout: "", truncated: false });
        return;
      }
      const wasKilled = error.signal === "SIGTERM" || error.name === "AbortError";
      const overflow = errorCode === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER";
      const syntaxError2 = errorCode === 2;
      const truncated = wasKilled || overflow;
      let partialOutput = stdout;
      if (truncated && partialOutput.length > 0) {
        const lines = partialOutput.split("\n");
        if (lines.length > 0) {
          lines.pop();
          partialOutput = lines.join("\n");
        }
      }
      if (!syntaxError2 && truncated) {
        console.warn(`ripgrep exited abnormally (signal=${error.signal} code=${error.code}) with stderr:
${stderr.trim() || "(empty)"}`);
      }
      resolve24({
        stdout: partialOutput,
        truncated,
        error: error instanceof Error ? error : void 0
      });
    });
    child.on("error", (err) => resolve24({ stdout: "", truncated: false, error: err }));
  });
}
var RIPGREP_COMMAND, RIPGREP_BUFFER_LIMIT, RIPGREP_TEST_TIMEOUT_MS, RIPGREP_RUN_TIMEOUT_MS, RIPGREP_WSL_TIMEOUT_MS, cachedSelection, cachedHealth, __filename2, __dirname3;
var init_ripgrepUtils = __esm({
  "packages/core/dist/src/utils/ripgrepUtils.js"() {
    "use strict";
    init_esbuild_shims();
    init_fileUtils();
    init_shell_utils();
    RIPGREP_COMMAND = "rg";
    RIPGREP_BUFFER_LIMIT = 2e7;
    RIPGREP_TEST_TIMEOUT_MS = 5e3;
    RIPGREP_RUN_TIMEOUT_MS = 1e4;
    RIPGREP_WSL_TIMEOUT_MS = 6e4;
    cachedSelection = null;
    cachedHealth = null;
    __name(wslTimeout, "wslTimeout");
    __filename2 = fileURLToPath5(import.meta.url);
    __dirname3 = path39.dirname(__filename2);
    __name(getPlatformString, "getPlatformString");
    __name(getArchitectureString, "getArchitectureString");
    __name(getBuiltinRipgrep, "getBuiltinRipgrep");
    __name(resolveRipgrep, "resolveRipgrep");
    __name(ensureRipgrepHealthy, "ensureRipgrepHealthy");
    __name(canUseRipgrep, "canUseRipgrep");
    __name(runRipgrep, "runRipgrep");
  }
});

// packages/core/dist/src/tools/ripGrep.js
import fs36 from "node:fs";
import path40 from "node:path";
var GrepToolInvocation2, RipGrepTool;
var init_ripGrep = __esm({
  "packages/core/dist/src/tools/ripGrep.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    init_tool_names();
    init_paths();
    init_errors();
    init_ripgrepUtils();
    init_schemaValidator();
    init_constants3();
    GrepToolInvocation2 = class extends BaseToolInvocation {
      static {
        __name(this, "GrepToolInvocation");
      }
      config;
      constructor(config, params) {
        super(params);
        this.config = config;
      }
      async execute(signal) {
        try {
          const searchDirAbs = resolveAndValidatePath(this.config, this.params.path, { allowFiles: true });
          const searchDirDisplay = this.params.path || ".";
          const rawOutput = await this.performRipgrepSearch({
            pattern: this.params.pattern,
            path: searchDirAbs,
            glob: this.params.glob,
            signal
          });
          const searchLocationDescription = this.params.path ? `in path "${searchDirDisplay}"` : `in the workspace directory`;
          const filterDescription = this.params.glob ? ` (filter: "${this.params.glob}")` : "";
          if (!rawOutput.trim()) {
            const noMatchMsg = `No matches found for pattern "${this.params.pattern}" ${searchLocationDescription}${filterDescription}.`;
            return { llmContent: noMatchMsg, returnDisplay: `No matches found` };
          }
          const allLines = rawOutput.split("\n").filter((line) => line.trim());
          const totalMatches = allLines.length;
          const matchTerm = totalMatches === 1 ? "match" : "matches";
          const header = `Found ${totalMatches} ${matchTerm} for pattern "${this.params.pattern}" ${searchLocationDescription}${filterDescription}:
---
`;
          const charLimit = this.config.getTruncateToolOutputThreshold();
          const lineLimit = Math.min(this.config.getTruncateToolOutputLines(), this.params.limit ?? Number.POSITIVE_INFINITY);
          let truncatedByLineLimit = false;
          let linesToInclude = allLines;
          if (allLines.length > lineLimit) {
            linesToInclude = allLines.slice(0, lineLimit);
            truncatedByLineLimit = true;
          }
          let grepOutput = "";
          let truncatedByCharLimit = false;
          let includedLines = 0;
          if (Number.isFinite(charLimit)) {
            const parts = [];
            let currentLength = 0;
            for (const line of linesToInclude) {
              const sep7 = includedLines > 0 ? 1 : 0;
              includedLines++;
              const projectedLength = currentLength + line.length + sep7;
              if (projectedLength <= charLimit) {
                parts.push(line);
                currentLength = projectedLength;
              } else {
                const remaining = Math.max(charLimit - currentLength - sep7, 10);
                parts.push(line.slice(0, remaining) + "...");
                truncatedByCharLimit = true;
                break;
              }
            }
            grepOutput = parts.join("\n");
          } else {
            grepOutput = linesToInclude.join("\n");
            includedLines = linesToInclude.length;
          }
          let llmContent = header + grepOutput;
          if (truncatedByLineLimit || truncatedByCharLimit) {
            const omittedMatches = totalMatches - includedLines;
            llmContent += `
---
[${omittedMatches} ${omittedMatches === 1 ? "line" : "lines"} truncated] ...`;
          }
          let displayMessage = `Found ${totalMatches} ${matchTerm}`;
          if (truncatedByLineLimit || truncatedByCharLimit) {
            displayMessage += ` (truncated)`;
          }
          return {
            llmContent: llmContent.trim(),
            returnDisplay: displayMessage
          };
        } catch (error) {
          console.error(`Error during ripgrep search operation: ${error}`);
          const errorMessage = getErrorMessage(error);
          return {
            llmContent: `Error during grep search operation: ${errorMessage}`,
            returnDisplay: `Error: ${errorMessage}`
          };
        }
      }
      async performRipgrepSearch(options2) {
        const { pattern, path: absolutePath, glob: glob2 } = options2;
        const rgArgs = [
          "--line-number",
          "--no-heading",
          "--with-filename",
          "--ignore-case",
          "--regexp",
          pattern
        ];
        const filteringOptions = this.getFileFilteringOptions();
        if (!filteringOptions.respectGitIgnore) {
          rgArgs.push("--no-ignore-vcs");
        }
        if (filteringOptions.respectQwenIgnore) {
          const qwenIgnorePath = path40.join(this.config.getTargetDir(), ".qwenignore");
          if (fs36.existsSync(qwenIgnorePath)) {
            rgArgs.push("--ignore-file", qwenIgnorePath);
          }
        }
        if (glob2) {
          rgArgs.push("--glob", glob2);
        }
        rgArgs.push("--threads", "4");
        rgArgs.push(absolutePath);
        const result = await runRipgrep(rgArgs, options2.signal);
        if (result.error && !result.stdout) {
          throw result.error;
        }
        return result.stdout;
      }
      getFileFilteringOptions() {
        const options2 = this.config.getFileFilteringOptions?.();
        return {
          respectGitIgnore: options2?.respectGitIgnore ?? DEFAULT_FILE_FILTERING_OPTIONS.respectGitIgnore,
          respectQwenIgnore: options2?.respectQwenIgnore ?? DEFAULT_FILE_FILTERING_OPTIONS.respectQwenIgnore
        };
      }
      /**
       * Gets a description of the grep operation
       * @returns A string describing the grep
       */
      getDescription() {
        let description = `'${this.params.pattern}'`;
        if (this.params.path) {
          description += ` in path '${this.params.path}'`;
        }
        if (this.params.glob) {
          description += ` (filter: '${this.params.glob}')`;
        }
        return description;
      }
    };
    RipGrepTool = class _RipGrepTool extends BaseDeclarativeTool {
      static {
        __name(this, "RipGrepTool");
      }
      config;
      static Name = ToolNames.GREP;
      constructor(config) {
        super(_RipGrepTool.Name, "Grep", 'A powerful search tool built on ripgrep\n\n  Usage:\n  - ALWAYS use Grep for search tasks. NEVER invoke `grep` or `rg` as a Bash command. The Grep tool has been optimized for correct permissions and access.\n  - Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")\n  - Filter files with glob parameter (e.g., "*.js", "**/*.tsx")\n  - Use Task tool for open-ended searches requiring multiple rounds\n  - Pattern syntax: Uses ripgrep (not grep) - special regex characters need escaping (use `interface\\{\\}` to find `interface{}` in Go code)\n', Kind.Search, {
          properties: {
            pattern: {
              type: "string",
              description: "The regular expression pattern to search for in file contents"
            },
            glob: {
              type: "string",
              description: 'Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}") - maps to rg --glob'
            },
            path: {
              type: "string",
              description: "File or directory to search in (rg PATH). Defaults to current working directory."
            },
            limit: {
              type: "number",
              description: "Limit output to first N lines/entries. Optional - shows all matches if not specified."
            }
          },
          required: ["pattern"],
          type: "object"
        });
        this.config = config;
      }
      /**
       * Validates the parameters for the tool
       * @param params Parameters to validate
       * @returns An error message string if invalid, null otherwise
       */
      validateToolParamValues(params) {
        const errors = SchemaValidator.validate(this.schema.parametersJsonSchema, params);
        if (errors) {
          return errors;
        }
        try {
          new RegExp(params.pattern);
        } catch (error) {
          return `Invalid regular expression pattern: ${params.pattern}. Error: ${getErrorMessage(error)}`;
        }
        if (params.path) {
          try {
            resolveAndValidatePath(this.config, params.path, { allowFiles: true });
          } catch (error) {
            return getErrorMessage(error);
          }
        }
        return null;
      }
      createInvocation(params) {
        return new GrepToolInvocation2(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/utils/LruCache.js
var LruCache;
var init_LruCache = __esm({
  "packages/core/dist/src/utils/LruCache.js"() {
    "use strict";
    init_esbuild_shims();
    LruCache = class {
      static {
        __name(this, "LruCache");
      }
      cache;
      maxSize;
      constructor(maxSize) {
        this.cache = /* @__PURE__ */ new Map();
        this.maxSize = maxSize;
      }
      get(key) {
        const value = this.cache.get(key);
        if (value) {
          this.cache.delete(key);
          this.cache.set(key, value);
        }
        return value;
      }
      set(key, value) {
        if (this.cache.has(key)) {
          this.cache.delete(key);
        } else if (this.cache.size >= this.maxSize) {
          const firstKey = this.cache.keys().next().value;
          if (firstKey !== void 0) {
            this.cache.delete(firstKey);
          }
        }
        this.cache.set(key, value);
      }
      clear() {
        this.cache.clear();
      }
    };
  }
});

// packages/core/dist/src/utils/promptIdContext.js
import { AsyncLocalStorage } from "node:async_hooks";
var promptIdContext;
var init_promptIdContext = __esm({
  "packages/core/dist/src/utils/promptIdContext.js"() {
    "use strict";
    init_esbuild_shims();
    promptIdContext = new AsyncLocalStorage();
  }
});

// packages/core/dist/src/utils/llm-edit-fixer.js
import { createHash as createHash4 } from "node:crypto";
async function FixLLMEditWithInstruction(instruction, old_string, new_string, error, current_content, baseLlmClient, abortSignal) {
  let promptId = promptIdContext.getStore();
  if (!promptId) {
    promptId = `llm-fixer-fallback-${Date.now()}-${Math.random().toString(16).slice(2)}`;
    console.warn(`Could not find promptId in context. This is unexpected. Using a fallback ID: ${promptId}`);
  }
  const cacheKey = createHash4("sha256").update(JSON.stringify([
    current_content,
    old_string,
    new_string,
    instruction,
    error
  ])).digest("hex");
  const cachedResult2 = editCorrectionWithInstructionCache.get(cacheKey);
  if (cachedResult2) {
    return cachedResult2;
  }
  const userPrompt = EDIT_USER_PROMPT.replace("{instruction}", instruction).replace("{old_string}", old_string).replace("{new_string}", new_string).replace("{error}", error).replace("{current_content}", current_content);
  const contents = [
    {
      role: "user",
      parts: [{ text: userPrompt }]
    }
  ];
  const result = await baseLlmClient.generateJson({
    contents,
    schema: SearchReplaceEditSchema,
    abortSignal,
    model: DEFAULT_GEMINI_FLASH_MODEL,
    systemInstruction: EDIT_SYS_PROMPT,
    promptId,
    maxAttempts: 1
  });
  editCorrectionWithInstructionCache.set(cacheKey, result);
  return result;
}
var MAX_CACHE_SIZE, EDIT_SYS_PROMPT, EDIT_USER_PROMPT, SearchReplaceEditSchema, editCorrectionWithInstructionCache;
var init_llm_edit_fixer = __esm({
  "packages/core/dist/src/utils/llm-edit-fixer.js"() {
    "use strict";
    init_esbuild_shims();
    init_node();
    init_baseLlmClient();
    init_LruCache();
    init_models();
    init_promptIdContext();
    MAX_CACHE_SIZE = 50;
    EDIT_SYS_PROMPT = `
You are an expert code-editing assistant specializing in debugging and correcting failed search-and-replace operations.

# Primary Goal
Your task is to analyze a failed edit attempt and provide a corrected \`search\` string that will match the text in the file precisely. The correction should be as minimal as possible, staying very close to the original, failed \`search\` string. Do NOT invent a completely new edit based on the instruction; your job is to fix the provided parameters.

It is important that you do no try to figure out if the instruction is correct. DO NOT GIVE ADVICE. Your only goal here is to do your best to perform the search and replace task! 

# Input Context
You will be given:
1. The high-level instruction for the original edit.
2. The exact \`search\` and \`replace\` strings that failed.
3. The error message that was produced.
4. The full content of the source file.

# Rules for Correction
1.  **Minimal Correction:** Your new \`search\` string must be a close variation of the original. Focus on fixing issues like whitespace, indentation, line endings, or small contextual differences.
2.  **Explain the Fix:** Your \`explanation\` MUST state exactly why the original \`search\` failed and how your new \`search\` string resolves that specific failure. (e.g., "The original search failed due to incorrect indentation; the new search corrects the indentation to match the source file.").
3.  **Preserve the \`replace\` String:** Do NOT modify the \`replace\` string unless the instruction explicitly requires it and it was the source of the error. Your primary focus is fixing the \`search\` string.
4.  **No Changes Case:** CRUCIAL: if the change is already present in the file,  set \`noChangesRequired\` to True and explain why in the \`explanation\`. It is crucial that you only do this if the changes outline in \`replace\` are alredy in the file and suits the instruction!! 
5.  **Exactness:** The final \`search\` field must be the EXACT literal text from the file. Do not escape characters.
`;
    EDIT_USER_PROMPT = `
# Goal of the Original Edit
<instruction>
{instruction}
</instruction>

# Failed Attempt Details
- **Original \`search\` parameter (failed):**
<search>
{old_string}
</search>
- **Original \`replace\` parameter:**
<replace>
{new_string}
</replace>
- **Error Encountered:**
<error>
{error}
</error>

# Full File Content
<file_content>
{current_content}
</file_content>

# Your Task
Based on the error and the file content, provide a corrected \`search\` string that will succeed. Remember to keep your correction minimal and explain the precise reason for the failure in your \`explanation\`.
`;
    SearchReplaceEditSchema = {
      type: Type.OBJECT,
      properties: {
        explanation: { type: Type.STRING },
        search: { type: Type.STRING },
        replace: { type: Type.STRING },
        noChangesRequired: { type: Type.BOOLEAN }
      },
      required: ["search", "replace", "explanation"]
    };
    editCorrectionWithInstructionCache = new LruCache(MAX_CACHE_SIZE);
    __name(FixLLMEditWithInstruction, "FixLLMEditWithInstruction");
  }
});

// packages/core/dist/src/tools/smart-edit.js
import * as fs37 from "node:fs";
import * as path41 from "node:path";
function restoreTrailingNewline(originalContent, modifiedContent) {
  const hadTrailingNewline = originalContent.endsWith("\n");
  if (hadTrailingNewline && !modifiedContent.endsWith("\n")) {
    return modifiedContent + "\n";
  } else if (!hadTrailingNewline && modifiedContent.endsWith("\n")) {
    return modifiedContent.replace(/\n$/, "");
  }
  return modifiedContent;
}
function escapeRegex(str2) {
  return str2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
async function calculateExactReplacement(context2) {
  const { currentContent, params } = context2;
  const { old_string, new_string } = params;
  const normalizedCode = currentContent;
  const normalizedSearch = old_string.replace(/\r\n/g, "\n");
  const normalizedReplace = new_string.replace(/\r\n/g, "\n");
  const exactOccurrences = normalizedCode.split(normalizedSearch).length - 1;
  if (exactOccurrences > 0) {
    let modifiedCode = safeLiteralReplace(normalizedCode, normalizedSearch, normalizedReplace);
    modifiedCode = restoreTrailingNewline(currentContent, modifiedCode);
    return {
      newContent: modifiedCode,
      occurrences: exactOccurrences,
      finalOldString: normalizedSearch,
      finalNewString: normalizedReplace
    };
  }
  return null;
}
async function calculateFlexibleReplacement(context2) {
  const { currentContent, params } = context2;
  const { old_string, new_string } = params;
  const normalizedCode = currentContent;
  const normalizedSearch = old_string.replace(/\r\n/g, "\n");
  const normalizedReplace = new_string.replace(/\r\n/g, "\n");
  const sourceLines = normalizedCode.match(/.*(?:\n|$)/g)?.slice(0, -1) ?? [];
  const searchLinesStripped = normalizedSearch.split("\n").map((line) => line.trim());
  const replaceLines = normalizedReplace.split("\n");
  let flexibleOccurrences = 0;
  let i = 0;
  while (i <= sourceLines.length - searchLinesStripped.length) {
    const window2 = sourceLines.slice(i, i + searchLinesStripped.length);
    const windowStripped = window2.map((line) => line.trim());
    const isMatch = windowStripped.every((line, index) => line === searchLinesStripped[index]);
    if (isMatch) {
      flexibleOccurrences++;
      const firstLineInMatch = window2[0];
      const indentationMatch = firstLineInMatch.match(/^(\s*)/);
      const indentation = indentationMatch ? indentationMatch[1] : "";
      const newBlockWithIndent = replaceLines.map((line) => `${indentation}${line}`);
      sourceLines.splice(i, searchLinesStripped.length, newBlockWithIndent.join("\n"));
      i += replaceLines.length;
    } else {
      i++;
    }
  }
  if (flexibleOccurrences > 0) {
    let modifiedCode = sourceLines.join("");
    modifiedCode = restoreTrailingNewline(currentContent, modifiedCode);
    return {
      newContent: modifiedCode,
      occurrences: flexibleOccurrences,
      finalOldString: normalizedSearch,
      finalNewString: normalizedReplace
    };
  }
  return null;
}
async function calculateRegexReplacement(context2) {
  const { currentContent, params } = context2;
  const { old_string, new_string } = params;
  const normalizedSearch = old_string.replace(/\r\n/g, "\n");
  const normalizedReplace = new_string.replace(/\r\n/g, "\n");
  const delimiters = ["(", ")", ":", "[", "]", "{", "}", ">", "<", "="];
  let processedString = normalizedSearch;
  for (const delim of delimiters) {
    processedString = processedString.split(delim).join(` ${delim} `);
  }
  const tokens = processedString.split(/\s+/).filter(Boolean);
  if (tokens.length === 0) {
    return null;
  }
  const escapedTokens = tokens.map(escapeRegex);
  const pattern = escapedTokens.join("\\s*");
  const finalPattern = `^(\\s*)${pattern}`;
  const flexibleRegex = new RegExp(finalPattern, "m");
  const match2 = flexibleRegex.exec(currentContent);
  if (!match2) {
    return null;
  }
  const indentation = match2[1] || "";
  const newLines = normalizedReplace.split("\n");
  const newBlockWithIndent = newLines.map((line) => `${indentation}${line}`).join("\n");
  const modifiedCode = currentContent.replace(flexibleRegex, newBlockWithIndent);
  return {
    newContent: restoreTrailingNewline(currentContent, modifiedCode),
    occurrences: 1,
    // This method is designed to find and replace only the first occurrence.
    finalOldString: normalizedSearch,
    finalNewString: normalizedReplace
  };
}
function detectLineEnding(content) {
  return content.includes("\r\n") ? "\r\n" : "\n";
}
async function calculateReplacement(context2) {
  const { currentContent, params } = context2;
  const { old_string, new_string } = params;
  const normalizedSearch = old_string.replace(/\r\n/g, "\n");
  const normalizedReplace = new_string.replace(/\r\n/g, "\n");
  if (normalizedSearch === "") {
    return {
      newContent: currentContent,
      occurrences: 0,
      finalOldString: normalizedSearch,
      finalNewString: normalizedReplace
    };
  }
  const exactResult = await calculateExactReplacement(context2);
  if (exactResult) {
    return exactResult;
  }
  const flexibleResult = await calculateFlexibleReplacement(context2);
  if (flexibleResult) {
    return flexibleResult;
  }
  const regexResult = await calculateRegexReplacement(context2);
  if (regexResult) {
    return regexResult;
  }
  return {
    newContent: currentContent,
    occurrences: 0,
    finalOldString: normalizedSearch,
    finalNewString: normalizedReplace
  };
}
function getErrorReplaceResult(params, occurrences, expectedReplacements, finalOldString, finalNewString) {
  let error = void 0;
  if (occurrences === 0) {
    error = {
      display: `Failed to edit, could not find the string to replace.`,
      raw: `Failed to edit, 0 occurrences found for old_string (${finalOldString}). Original old_string was (${params.old_string}) in ${params.file_path}. No edits made. The exact text in old_string was not found. Ensure you're not escaping content incorrectly and check whitespace, indentation, and context. Use ${ReadFileTool.Name} tool to verify.`,
      type: ToolErrorType.EDIT_NO_OCCURRENCE_FOUND
    };
  } else if (occurrences !== expectedReplacements) {
    const occurrenceTerm = expectedReplacements === 1 ? "occurrence" : "occurrences";
    error = {
      display: `Failed to edit, expected ${expectedReplacements} ${occurrenceTerm} but found ${occurrences}.`,
      raw: `Failed to edit, Expected ${expectedReplacements} ${occurrenceTerm} but found ${occurrences} for old_string in file: ${params.file_path}`,
      type: ToolErrorType.EDIT_EXPECTED_OCCURRENCE_MISMATCH
    };
  } else if (finalOldString === finalNewString) {
    error = {
      display: `No changes to apply. The old_string and new_string are identical.`,
      raw: `No changes to apply. The old_string and new_string are identical in file: ${params.file_path}`,
      type: ToolErrorType.EDIT_NO_CHANGE
    };
  }
  return error;
}
var EditToolInvocation2, SmartEditTool;
var init_smart_edit = __esm({
  "packages/core/dist/src/tools/smart-edit.js"() {
    "use strict";
    init_esbuild_shims();
    init_lib();
    init_tools();
    init_tool_names();
    init_tool_error();
    init_paths();
    init_errors();
    init_config3();
    init_diffOptions();
    init_read_file();
    init_modifiable_tool();
    init_ide_client();
    init_llm_edit_fixer();
    init_edit();
    init_textUtils();
    __name(restoreTrailingNewline, "restoreTrailingNewline");
    __name(escapeRegex, "escapeRegex");
    __name(calculateExactReplacement, "calculateExactReplacement");
    __name(calculateFlexibleReplacement, "calculateFlexibleReplacement");
    __name(calculateRegexReplacement, "calculateRegexReplacement");
    __name(detectLineEnding, "detectLineEnding");
    __name(calculateReplacement, "calculateReplacement");
    __name(getErrorReplaceResult, "getErrorReplaceResult");
    EditToolInvocation2 = class {
      static {
        __name(this, "EditToolInvocation");
      }
      config;
      params;
      constructor(config, params) {
        this.config = config;
        this.params = params;
      }
      toolLocations() {
        return [{ path: this.params.file_path }];
      }
      async attemptSelfCorrection(params, currentContent, initialError, abortSignal, originalLineEnding) {
        const fixedEdit = await FixLLMEditWithInstruction(params.instruction, params.old_string, params.new_string, initialError.raw, currentContent, this.config.getBaseLlmClient(), abortSignal);
        if (fixedEdit.noChangesRequired) {
          return {
            currentContent,
            newContent: currentContent,
            occurrences: 0,
            isNewFile: false,
            error: {
              display: `No changes required. The file already meets the specified conditions.`,
              raw: `A secondary check by an LLM determined that no changes were necessary to fulfill the instruction. Explanation: ${fixedEdit.explanation}. Original error with the parameters given: ${initialError.raw}`,
              type: ToolErrorType.EDIT_NO_CHANGE_LLM_JUDGEMENT
            },
            originalLineEnding
          };
        }
        const secondAttemptResult = await calculateReplacement({
          params: {
            ...params,
            old_string: fixedEdit.search,
            new_string: fixedEdit.replace
          },
          currentContent,
          abortSignal
        });
        const secondError = getErrorReplaceResult(
          params,
          secondAttemptResult.occurrences,
          1,
          // expectedReplacements is always 1 for smart_edit
          secondAttemptResult.finalOldString,
          secondAttemptResult.finalNewString
        );
        if (secondError) {
          return {
            currentContent,
            newContent: currentContent,
            occurrences: 0,
            isNewFile: false,
            error: initialError,
            originalLineEnding
          };
        }
        return {
          currentContent,
          newContent: secondAttemptResult.newContent,
          occurrences: secondAttemptResult.occurrences,
          isNewFile: false,
          error: void 0,
          originalLineEnding
        };
      }
      /**
       * Calculates the potential outcome of an edit operation.
       * @param params Parameters for the edit operation
       * @returns An object describing the potential edit outcome
       * @throws File system errors if reading the file fails unexpectedly (e.g., permissions)
       */
      async calculateEdit(params, abortSignal) {
        const expectedReplacements = 1;
        let currentContent = null;
        let fileExists2 = false;
        let originalLineEnding = "\n";
        try {
          currentContent = await this.config.getFileSystemService().readTextFile(params.file_path);
          originalLineEnding = detectLineEnding(currentContent);
          currentContent = currentContent.replace(/\r\n/g, "\n");
          fileExists2 = true;
        } catch (err) {
          if (!isNodeError(err) || err.code !== "ENOENT") {
            throw err;
          }
          fileExists2 = false;
        }
        const isNewFile = params.old_string === "" && !fileExists2;
        if (isNewFile) {
          return {
            currentContent,
            newContent: params.new_string,
            occurrences: 1,
            isNewFile: true,
            error: void 0,
            originalLineEnding
          };
        }
        if (!fileExists2) {
          return {
            currentContent,
            newContent: "",
            occurrences: 0,
            isNewFile: false,
            error: {
              display: `File not found. Cannot apply edit. Use an empty old_string to create a new file.`,
              raw: `File not found: ${params.file_path}`,
              type: ToolErrorType.FILE_NOT_FOUND
            },
            originalLineEnding
          };
        }
        if (currentContent === null) {
          return {
            currentContent,
            newContent: "",
            occurrences: 0,
            isNewFile: false,
            error: {
              display: `Failed to read content of file.`,
              raw: `Failed to read content of existing file: ${params.file_path}`,
              type: ToolErrorType.READ_CONTENT_FAILURE
            },
            originalLineEnding
          };
        }
        if (params.old_string === "") {
          return {
            currentContent,
            newContent: currentContent,
            occurrences: 0,
            isNewFile: false,
            error: {
              display: `Failed to edit. Attempted to create a file that already exists.`,
              raw: `File already exists, cannot create: ${params.file_path}`,
              type: ToolErrorType.ATTEMPT_TO_CREATE_EXISTING_FILE
            },
            originalLineEnding
          };
        }
        const replacementResult = await calculateReplacement({
          params,
          currentContent,
          abortSignal
        });
        const initialError = getErrorReplaceResult(params, replacementResult.occurrences, expectedReplacements, replacementResult.finalOldString, replacementResult.finalNewString);
        if (!initialError) {
          return {
            currentContent,
            newContent: replacementResult.newContent,
            occurrences: replacementResult.occurrences,
            isNewFile: false,
            error: void 0,
            originalLineEnding
          };
        }
        return this.attemptSelfCorrection(params, currentContent, initialError, abortSignal, originalLineEnding);
      }
      /**
       * Handles the confirmation prompt for the Edit tool in the CLI.
       * It needs to calculate the diff to show the user.
       */
      async shouldConfirmExecute(abortSignal) {
        if (this.config.getApprovalMode() === ApprovalMode.AUTO_EDIT) {
          return false;
        }
        let editData;
        try {
          editData = await this.calculateEdit(this.params, abortSignal);
        } catch (error) {
          if (abortSignal.aborted) {
            throw error;
          }
          const errorMsg = error instanceof Error ? error.message : String(error);
          console.log(`Error preparing edit: ${errorMsg}`);
          return false;
        }
        if (editData.error) {
          console.log(`Error: ${editData.error.display}`);
          return false;
        }
        const fileName = path41.basename(this.params.file_path);
        const fileDiff = createPatch(fileName, editData.currentContent ?? "", editData.newContent, "Current", "Proposed", DEFAULT_DIFF_OPTIONS);
        const ideClient = await IdeClient.getInstance();
        const ideConfirmation = this.config.getIdeMode() && ideClient.isDiffingEnabled() ? ideClient.openDiff(this.params.file_path, editData.newContent) : void 0;
        const confirmationDetails = {
          type: "edit",
          title: `Confirm Edit: ${shortenPath(makeRelative(this.params.file_path, this.config.getTargetDir()))}`,
          fileName,
          filePath: this.params.file_path,
          fileDiff,
          originalContent: editData.currentContent,
          newContent: editData.newContent,
          onConfirm: /* @__PURE__ */ __name(async (outcome) => {
            if (outcome === ToolConfirmationOutcome.ProceedAlways) {
              this.config.setApprovalMode(ApprovalMode.AUTO_EDIT);
            }
            if (ideConfirmation) {
              const result = await ideConfirmation;
              if (result.status === "accepted" && result.content) {
                this.params.old_string = editData.currentContent ?? "";
                this.params.new_string = result.content;
              }
            }
          }, "onConfirm"),
          ideConfirmation
        };
        return confirmationDetails;
      }
      getDescription() {
        const relativePath = makeRelative(this.params.file_path, this.config.getTargetDir());
        if (this.params.old_string === "") {
          return `Create ${shortenPath(relativePath)}`;
        }
        const oldStringSnippet = this.params.old_string.split("\n")[0].substring(0, 30) + (this.params.old_string.length > 30 ? "..." : "");
        const newStringSnippet = this.params.new_string.split("\n")[0].substring(0, 30) + (this.params.new_string.length > 30 ? "..." : "");
        if (this.params.old_string === this.params.new_string) {
          return `No file changes to ${shortenPath(relativePath)}`;
        }
        return `${shortenPath(relativePath)}: ${oldStringSnippet} => ${newStringSnippet}`;
      }
      /**
       * Executes the edit operation with the given parameters.
       * @param params Parameters for the edit operation
       * @returns Result of the edit operation
       */
      async execute(signal) {
        let editData;
        try {
          editData = await this.calculateEdit(this.params, signal);
        } catch (error) {
          if (signal.aborted) {
            throw error;
          }
          const errorMsg = error instanceof Error ? error.message : String(error);
          return {
            llmContent: `Error preparing edit: ${errorMsg}`,
            returnDisplay: `Error preparing edit: ${errorMsg}`,
            error: {
              message: errorMsg,
              type: ToolErrorType.EDIT_PREPARATION_FAILURE
            }
          };
        }
        if (editData.error) {
          return {
            llmContent: editData.error.raw,
            returnDisplay: `Error: ${editData.error.display}`,
            error: {
              message: editData.error.raw,
              type: editData.error.type
            }
          };
        }
        try {
          this.ensureParentDirectoriesExist(this.params.file_path);
          let finalContent = editData.newContent;
          if (!editData.isNewFile && editData.originalLineEnding === "\r\n") {
            finalContent = finalContent.replace(/\n/g, "\r\n");
          }
          await this.config.getFileSystemService().writeTextFile(this.params.file_path, finalContent);
          let displayResult;
          if (editData.isNewFile) {
            displayResult = `Created ${shortenPath(makeRelative(this.params.file_path, this.config.getTargetDir()))}`;
          } else {
            const fileName = path41.basename(this.params.file_path);
            const fileDiff = createPatch(
              fileName,
              editData.currentContent ?? "",
              // Should not be null here if not isNewFile
              editData.newContent,
              "Current",
              "Proposed",
              DEFAULT_DIFF_OPTIONS
            );
            const originallyProposedContent = this.params.ai_proposed_string || this.params.new_string;
            const diffStat = getDiffStat(fileName, editData.currentContent ?? "", originallyProposedContent, this.params.new_string);
            displayResult = {
              fileDiff,
              fileName,
              originalContent: editData.currentContent,
              newContent: editData.newContent,
              diffStat
            };
          }
          const llmSuccessMessageParts = [
            editData.isNewFile ? `Created new file: ${this.params.file_path} with provided content.` : `Successfully modified file: ${this.params.file_path} (${editData.occurrences} replacements).`
          ];
          if (this.params.modified_by_user) {
            llmSuccessMessageParts.push(`User modified the \`new_string\` content to be: ${this.params.new_string}.`);
          }
          return {
            llmContent: llmSuccessMessageParts.join(" "),
            returnDisplay: displayResult
          };
        } catch (error) {
          const errorMsg = error instanceof Error ? error.message : String(error);
          return {
            llmContent: `Error executing edit: ${errorMsg}`,
            returnDisplay: `Error writing file: ${errorMsg}`,
            error: {
              message: errorMsg,
              type: ToolErrorType.FILE_WRITE_FAILURE
            }
          };
        }
      }
      /**
       * Creates parent directories if they don't exist
       */
      ensureParentDirectoriesExist(filePath) {
        const dirName = path41.dirname(filePath);
        if (!fs37.existsSync(dirName)) {
          fs37.mkdirSync(dirName, { recursive: true });
        }
      }
    };
    SmartEditTool = class _SmartEditTool extends BaseDeclarativeTool {
      static {
        __name(this, "SmartEditTool");
      }
      config;
      static Name = ToolNames.EDIT;
      constructor(config) {
        super(_SmartEditTool.Name, "Edit", `Replaces text within a file. Replaces a single occurrence. This tool requires providing significant context around the change to ensure precise targeting. Always use the ${ReadFileTool.Name} tool to examine the file's current content before attempting a text replacement.
      
      The user has the ability to modify the \`new_string\` content. If modified, this will be stated in the response.
      
      Expectation for required parameters:
      1. \`file_path\` MUST be an absolute path; otherwise an error will be thrown.
      2. \`old_string\` MUST be the exact literal text to replace (including all whitespace, indentation, newlines, and surrounding code etc.).
      3. \`new_string\` MUST be the exact literal text to replace \`old_string\` with (also including all whitespace, indentation, newlines, and surrounding code etc.). Ensure the resulting code is correct and idiomatic and that \`old_string\` and \`new_string\` are different.
      4. \`instruction\` is the detailed instruction of what needs to be changed. It is important to Make it specific and detailed so developers or large language models can understand what needs to be changed and perform the changes on their own if necessary. 
      5. NEVER escape \`old_string\` or \`new_string\`, that would break the exact literal text requirement.
      **Important:** If ANY of the above are not satisfied, the tool will fail. CRITICAL for \`old_string\`: Must uniquely identify the single instance to change. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string matches multiple locations, or does not match exactly, the tool will fail.
      6. Prefer to break down complex and long changes into multiple smaller atomic calls to this tool. Always check the content of the file after changes or not finding a string to match.
      **Multiple replacements:** If there are multiple and ambiguous occurences of the \`old_string\` in the file, the tool will also fail.`, Kind.Edit, {
          properties: {
            file_path: {
              description: "The absolute path to the file to modify. Must start with '/'.",
              type: "string"
            },
            instruction: {
              description: `A clear, semantic instruction for the code change, acting as a high-quality prompt for an expert LLM assistant. It must be self-contained and explain the goal of the change.

A good instruction should concisely answer:
1.  WHY is the change needed? (e.g., "To fix a bug where users can be null...")
2.  WHERE should the change happen? (e.g., "...in the 'renderUserProfile' function...")
3.  WHAT is the high-level change? (e.g., "...add a null check for the 'user' object...")
4.  WHAT is the desired outcome? (e.g., "...so that it displays a loading spinner instead of crashing.")

**GOOD Example:** "In the 'calculateTotal' function, correct the sales tax calculation by updating the 'taxRate' constant from 0.05 to 0.075 to reflect the new regional tax laws."

**BAD Examples:**
- "Change the text." (Too vague)
- "Fix the bug." (Doesn't explain the bug or the fix)
- "Replace the line with this new line." (Brittle, just repeats the other parameters)
`,
              type: "string"
            },
            old_string: {
              description: "The exact literal text to replace, preferably unescaped. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string is not the exact literal text (i.e. you escaped it) or does not match exactly, the tool will fail.",
              type: "string"
            },
            new_string: {
              description: "The exact literal text to replace `old_string` with, preferably unescaped. Provide the EXACT text. Ensure the resulting code is correct and idiomatic.",
              type: "string"
            }
          },
          required: ["file_path", "instruction", "old_string", "new_string"],
          type: "object"
        });
        this.config = config;
      }
      /**
       * Quickly checks if the file path can be resolved directly against the workspace root.
       * @param filePath The relative file path to check.
       * @returns The absolute path if the file exists, otherwise null.
       */
      findDirectPath(filePath) {
        const directPath = path41.join(this.config.getTargetDir(), filePath);
        return fs37.existsSync(directPath) ? directPath : null;
      }
      /**
       * Searches for a file across all configured workspace directories.
       * @param filePath The file path (can be partial) to search for.
       * @returns A list of absolute paths for all matching files found.
       */
      findAmbiguousPaths(filePath) {
        const workspaceContext = this.config.getWorkspaceContext();
        const fileSystem = this.config.getFileSystemService();
        const searchPaths = workspaceContext.getDirectories();
        return fileSystem.findFiles(filePath, searchPaths);
      }
      /**
       * Attempts to correct a relative file path to an absolute path.
       * This function modifies `params.file_path` in place if successful.
       * @param params The tool parameters containing the file_path to correct.
       * @returns An error message string if correction fails, otherwise null.
       */
      correctPath(params) {
        const directPath = this.findDirectPath(params.file_path);
        if (directPath) {
          params.file_path = directPath;
          return null;
        }
        const foundFiles = this.findAmbiguousPaths(params.file_path);
        if (foundFiles.length === 0) {
          return `File not found for '${params.file_path}' and path is not absolute.`;
        }
        if (foundFiles.length > 1) {
          return `The file path '${params.file_path}' is too ambiguous and matches multiple files. Please provide a more specific path. Matches: ${foundFiles.join(", ")}`;
        }
        params.file_path = foundFiles[0];
        return null;
      }
      /**
       * Validates the parameters for the Edit tool
       * @param params Parameters to validate
       * @returns Error message string or null if valid
       */
      validateToolParamValues(params) {
        if (!params.file_path) {
          return "The 'file_path' parameter must be non-empty.";
        }
        if (!path41.isAbsolute(params.file_path)) {
          const error = this.correctPath(params);
          if (error)
            return error;
        }
        const workspaceContext = this.config.getWorkspaceContext();
        if (!workspaceContext.isPathWithinWorkspace(params.file_path)) {
          const directories = workspaceContext.getDirectories();
          return `File path must be within one of the workspace directories: ${directories.join(", ")}`;
        }
        return null;
      }
      createInvocation(params) {
        return new EditToolInvocation2(this.config, params);
      }
      getModifyContext(_) {
        return {
          getFilePath: /* @__PURE__ */ __name((params) => params.file_path, "getFilePath"),
          getCurrentContent: /* @__PURE__ */ __name(async (params) => {
            try {
              return this.config.getFileSystemService().readTextFile(params.file_path);
            } catch (err) {
              if (!isNodeError(err) || err.code !== "ENOENT")
                throw err;
              return "";
            }
          }, "getCurrentContent"),
          getProposedContent: /* @__PURE__ */ __name(async (params) => {
            try {
              const currentContent = await this.config.getFileSystemService().readTextFile(params.file_path);
              return applyReplacement(currentContent, params.old_string, params.new_string, params.old_string === "" && currentContent === "");
            } catch (err) {
              if (!isNodeError(err) || err.code !== "ENOENT")
                throw err;
              return "";
            }
          }, "getProposedContent"),
          createUpdatedParams: /* @__PURE__ */ __name((oldContent, modifiedProposedContent, originalParams) => {
            const content = originalParams.new_string;
            return {
              ...originalParams,
              ai_proposed_string: content,
              old_string: oldContent,
              new_string: modifiedProposedContent,
              modified_by_user: true
            };
          }, "createUpdatedParams")
        };
      }
    };
  }
});

// packages/core/dist/src/tools/todoWrite.js
import * as fs38 from "fs/promises";
import * as fsSync from "fs";
import * as path42 from "path";
import * as process20 from "process";
function getTodoFilePath(sessionId2) {
  const homeDir = process20.env["HOME"] || process20.env["USERPROFILE"] || process20.cwd();
  const todoDir = path42.join(homeDir, QWEN_DIR5, TODO_SUBDIR);
  const filename = `${sessionId2 || "default"}.json`;
  return path42.join(todoDir, filename);
}
async function writeTodosToFile(todos, sessionId2) {
  const todoFilePath = getTodoFilePath(sessionId2);
  const todoDir = path42.dirname(todoFilePath);
  await fs38.mkdir(todoDir, { recursive: true });
  const data = {
    todos,
    sessionId: sessionId2 || "default"
  };
  await fs38.writeFile(todoFilePath, JSON.stringify(data, null, 2), "utf-8");
}
var todoWriteToolSchemaData, todoWriteToolDescription, TODO_SUBDIR, TodoWriteToolInvocation, TodoWriteTool;
var init_todoWrite = __esm({
  "packages/core/dist/src/tools/todoWrite.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    init_paths();
    init_tool_names();
    todoWriteToolSchemaData = {
      name: "todo_write",
      description: "Creates and manages a structured task list for your current coding session. This helps track progress, organize complex tasks, and demonstrate thoroughness.",
      parametersJsonSchema: {
        type: "object",
        properties: {
          todos: {
            type: "array",
            items: {
              type: "object",
              properties: {
                content: {
                  type: "string",
                  minLength: 1
                },
                status: {
                  type: "string",
                  enum: ["pending", "in_progress", "completed"]
                },
                id: {
                  type: "string"
                }
              },
              required: ["content", "status", "id"],
              additionalProperties: false
            },
            description: "The updated todo list"
          }
        },
        required: ["todos"],
        $schema: "http://json-schema.org/draft-07/schema#"
      }
    };
    todoWriteToolDescription = `
Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
It also helps the user understand the progress of the task and overall progress of their requests.

## When to Use This Tool
Use this tool proactively in these scenarios:

1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
3. User explicitly requests todo list - When the user directly asks you to use the todo list
4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
5. After receiving new instructions - Immediately capture user requirements as todos
6. When you start working on a task - Mark it as in_progress BEFORE beginning work. Ideally you should only have one todo as in_progress at a time
7. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation

## When NOT to Use This Tool

Skip using this tool when:
1. There is only a single, straightforward task
2. The task is trivial and tracking it provides no organizational benefit
3. The task can be completed in less than 3 trivial steps
4. The task is purely conversational or informational

NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.

## Examples of When to Use the Todo List

<example>
User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!
Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.
*Creates todo list with the following items:*
1. Create dark mode toggle component in Settings page
2. Add dark mode state management (context/store)
3. Implement CSS-in-JS styles for dark theme
4. Update existing components to support theme switching
5. Run tests and build process, addressing any failures or errors that occur
*Begins working on the first task*

<reasoning>
The assistant used the todo list because:
1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes
2. The user explicitly requested tests and build be run afterward
3. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
</reasoning>
</example>

<example>
User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
*Uses grep or search tools to locate all instances of getCwd in the codebase*
Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
*Creates todo list with specific items for each file that needs updating*

<reasoning>
The assistant used the todo list because:
1. First, the assistant searched to understand the scope of the task
2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps
3. The todo list helps ensure every instance is tracked and updated systematically
4. This approach prevents missing any occurrences and maintains code consistency
</reasoning>
</example>


<example>
User: I need to implement these features for my e-commerce site: user registration, product catalog, shopping cart, and checkout flow.
Assistant: I'll help implement these features. First, let's add all the features to the todo list.
*Creates a todo list breaking down each feature into specific tasks based on the project architecture*
Assistant: Let's start with user registration. This will involve creating database models, API endpoints, and frontend forms that integrate with your existing authentication system.

<reasoning>
The assistant used the todo list because:
1. The user provided multiple complex features to implement in a comma separated list
2. The todo list helps organize these large features into manageable tasks
3. This approach allows for tracking progress across the entire implementation
</reasoning>
</example>

<example>
User: Can you help optimize my React application? It's rendering slowly and has performance issues.</user>
Assistant: I'll help optimize your React application. First, let me examine your codebase to identify potential performance bottlenecks.
*Reviews component structure, render patterns, state management, and data fetching*
Assistant: After analyzing your codebase, I've identified several performance issues. Let me create a todo list to track our optimization efforts.
*Creates todo list with items like: 1) Implement memoization for expensive calculations in ProductList, 2) Add virtualization for long lists in Dashboard, 3) Optimize image loading in Gallery component, 4) Fix state update loops in ShoppingCart, 5) Review bundle size and implement code splitting*
Let's start by implementing memoization for the expensive calculations in your ProductList component.</assistant>

<reasoning>
The assistant used the todo list because:
1. First, the assistant examined the codebase to identify specific performance issues
2. Based on this analysis, it identified multiple optimization opportunities
3. Performance optimization is a non-trivial task requiring multiple steps
4. The todo list helps methodically track improvements across different components
5. This systematic approach ensures all performance bottlenecks are addressed
</reasoning>
</example>

## Examples of When NOT to Use the Todo List

<example>
User: How do I print 'Hello World' in Python?
Assistant: In Python, you can print "Hello World" with this simple code:

python
print("Hello World")

This will output the text "Hello World" to the console when executed.</assistant>

<reasoning>
The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.
</reasoning>
</example>

<example>
User: What does the git status command do?
Assistant: The git status command shows the current state of your working directory and staging area. It displays which changes have been staged, which haven't, and which files aren't being tracked by Git. This is a fundamental command for understanding the current state of your repository before making commits.

<reasoning>
The assistant did not use the todo list because this is an informational request with no actual coding task to complete. The user is simply asking for an explanation, not for the assistant to perform multiple steps or tasks.
</reasoning>
</example>

<example>
User: Can you add a comment to the calculateTotal function to explain what it does?
Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
* Uses the Edit tool to add a comment to the calculateTotal function *

<reasoning>
The assistant did not use the todo list because this is a single, straightforward task confined to one location in the code. Adding a comment doesn't require tracking multiple steps or systematic organization.
</reasoning>
</example>

<example>
User: Run npm install for me and tell me what happens.
Assistant: I'll run the npm install command for you.

*Executes: npm install*

The command completed successfully. Here's the output:
[Output of npm install command]

All dependencies have been installed according to your package.json file.

<reasoning>
The assistant did not use the todo list because this is a single command execution with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward task.
</reasoning>
</example>

## Task States and Management

1. **Task States**: Use these states to track progress:
   - pending: Task not yet started
   - in_progress: Currently working on (limit to ONE task at a time)
   - completed: Task finished successfully

2. **Task Management**:
   - Update task status in real-time as you work
   - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
   - Only have ONE task in_progress at any time
   - Complete current tasks before starting new ones
   - Remove tasks that are no longer relevant from the list entirely

3. **Task Completion Requirements**:
   - ONLY mark a task as completed when you have FULLY accomplished it
   - If you encounter errors, blockers, or cannot finish, keep the task as in_progress
   - When blocked, create a new task describing what needs to be resolved
   - Never mark a task as completed if:
     - Tests are failing
     - Implementation is partial
     - You encountered unresolved errors
     - You couldn't find necessary files or dependencies

4. **Task Breakdown**:
   - Create specific, actionable items
   - Break complex tasks into smaller, manageable steps
   - Use clear, descriptive task names

When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.
`;
    TODO_SUBDIR = "todos";
    __name(getTodoFilePath, "getTodoFilePath");
    __name(writeTodosToFile, "writeTodosToFile");
    TodoWriteToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "TodoWriteToolInvocation");
      }
      config;
      operationType;
      constructor(config, params, operationType = "update") {
        super(params);
        this.config = config;
        this.operationType = operationType;
      }
      getDescription() {
        return this.operationType === "create" ? "Create todos" : "Update todos";
      }
      async shouldConfirmExecute(_abortSignal) {
        return false;
      }
      async execute(_signal) {
        const { todos, modified_by_user, modified_content } = this.params;
        const sessionId2 = this.config.getSessionId();
        try {
          let finalTodos;
          if (modified_by_user && modified_content !== void 0) {
            const data = JSON.parse(modified_content);
            finalTodos = Array.isArray(data.todos) ? data.todos : [];
          } else {
            finalTodos = todos;
          }
          await writeTodosToFile(finalTodos, sessionId2);
          const todoResultDisplay = {
            type: "todo_list",
            todos: finalTodos
          };
          const todosJson = JSON.stringify(finalTodos);
          let llmContent;
          if (finalTodos.length === 0) {
            llmContent = `Todo list has been cleared.

<system-reminder>
Your todo list is now empty. DO NOT mention this explicitly to the user. You have no pending tasks in your todo list.
</system-reminder>`;
          } else {
            llmContent = `Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable

<system-reminder>
Your todo list has changed. DO NOT mention this explicitly to the user. Here are the latest contents of your todo list: 

${todosJson}. Continue on with the tasks at hand if applicable.
</system-reminder>`;
          }
          return {
            llmContent,
            returnDisplay: todoResultDisplay
          };
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : String(error);
          console.error(`[TodoWriteTool] Error executing todo_write: ${errorMessage}`);
          const errorLlmContent = `Failed to modify todos. An error occurred during the operation.

<system-reminder>
Todo list modification failed with error: ${errorMessage}. You may need to retry or handle this error appropriately.
</system-reminder>`;
          return {
            llmContent: errorLlmContent,
            returnDisplay: `Error writing todos: ${errorMessage}`
          };
        }
      }
    };
    TodoWriteTool = class _TodoWriteTool extends BaseDeclarativeTool {
      static {
        __name(this, "TodoWriteTool");
      }
      config;
      static Name = ToolNames.TODO_WRITE;
      constructor(config) {
        super(_TodoWriteTool.Name, ToolDisplayNames.TODO_WRITE, todoWriteToolDescription, Kind.Think, todoWriteToolSchemaData.parametersJsonSchema);
        this.config = config;
      }
      validateToolParams(params) {
        if (!Array.isArray(params.todos)) {
          return 'Parameter "todos" must be an array.';
        }
        for (const todo of params.todos) {
          if (!todo.id || typeof todo.id !== "string" || todo.id.trim() === "") {
            return 'Each todo must have a non-empty "id" string.';
          }
          if (!todo.content || typeof todo.content !== "string" || todo.content.trim() === "") {
            return 'Each todo must have a non-empty "content" string.';
          }
          if (!["pending", "in_progress", "completed"].includes(todo.status)) {
            return 'Each todo must have a valid "status" (pending, in_progress, completed).';
          }
        }
        const ids = params.todos.map((todo) => todo.id);
        const uniqueIds = new Set(ids);
        if (ids.length !== uniqueIds.size) {
          return "Todo IDs must be unique within the array.";
        }
        return null;
      }
      createInvocation(params) {
        const sessionId2 = this.config.getSessionId();
        const todoFilePath = getTodoFilePath(sessionId2);
        const operationType = fsSync.existsSync(todoFilePath) ? "update" : "create";
        return new TodoWriteToolInvocation(this.config, params, operationType);
      }
    };
  }
});

// node_modules/eventsource/dist/index.js
function syntaxError(message) {
  const DomException = globalThis.DOMException;
  return typeof DomException == "function" ? new DomException(message, "SyntaxError") : new SyntaxError(message);
}
function flattenError(err) {
  return err instanceof Error ? "errors" in err && Array.isArray(err.errors) ? err.errors.map(flattenError).join(", ") : "cause" in err && err.cause instanceof Error ? `${err}: ${flattenError(err.cause)}` : err.message : `${err}`;
}
function inspectableError(err) {
  return {
    type: err.type,
    message: err.message,
    code: err.code,
    defaultPrevented: err.defaultPrevented,
    cancelable: err.cancelable,
    timeStamp: err.timeStamp
  };
}
function getBaseURL() {
  const doc = "document" in globalThis ? globalThis.document : void 0;
  return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0;
}
var ErrorEvent, __typeError, __accessCheck, __privateGet, __privateAdd, __privateSet, __privateMethod, _readyState, _url, _redirectUrl, _withCredentials, _fetch, _reconnectInterval, _reconnectTimer, _lastEventId, _controller, _parser, _onError, _onMessage, _onOpen, _EventSource_instances, connect_fn, _onFetchResponse, _onFetchError, getRequestOptions_fn, _onEvent, _onRetryChange, failConnection_fn, scheduleReconnect_fn, _reconnect, EventSource;
var init_dist2 = __esm({
  "node_modules/eventsource/dist/index.js"() {
    init_esbuild_shims();
    init_dist();
    ErrorEvent = class extends Event {
      static {
        __name(this, "ErrorEvent");
      }
      /**
       * Constructs a new `ErrorEvent` instance. This is typically not called directly,
       * but rather emitted by the `EventSource` object when an error occurs.
       *
       * @param type - The type of the event (should be "error")
       * @param errorEventInitDict - Optional properties to include in the error event
       */
      constructor(type, errorEventInitDict) {
        var _a6, _b2;
        super(type), this.code = (_a6 = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a6 : void 0, this.message = (_b2 = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b2 : void 0;
      }
      /**
       * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
       * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
       * we explicitly include the properties in the `inspect` method.
       *
       * This is automatically called by Node.js when you `console.log` an instance of this class.
       *
       * @param _depth - The current depth
       * @param options - The options passed to `util.inspect`
       * @param inspect - The inspect function to use (prevents having to import it from `util`)
       * @returns A string representation of the error
       */
      [Symbol.for("nodejs.util.inspect.custom")](_depth, options2, inspect2) {
        return inspect2(inspectableError(this), options2);
      }
      /**
       * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
       * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
       * we explicitly include the properties in the `inspect` method.
       *
       * This is automatically called by Deno when you `console.log` an instance of this class.
       *
       * @param inspect - The inspect function to use (prevents having to import it from `util`)
       * @param options - The options passed to `Deno.inspect`
       * @returns A string representation of the error
       */
      [Symbol.for("Deno.customInspect")](inspect2, options2) {
        return inspect2(inspectableError(this), options2);
      }
    };
    __name(syntaxError, "syntaxError");
    __name(flattenError, "flattenError");
    __name(inspectableError, "inspectableError");
    __typeError = /* @__PURE__ */ __name((msg) => {
      throw TypeError(msg);
    }, "__typeError");
    __accessCheck = /* @__PURE__ */ __name((obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg), "__accessCheck");
    __privateGet = /* @__PURE__ */ __name((obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), "__privateGet");
    __privateAdd = /* @__PURE__ */ __name((obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value), "__privateAdd");
    __privateSet = /* @__PURE__ */ __name((obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value), "__privateSet");
    __privateMethod = /* @__PURE__ */ __name((obj, member, method) => (__accessCheck(obj, member, "access private method"), method), "__privateMethod");
    EventSource = class extends EventTarget {
      static {
        __name(this, "EventSource");
      }
      constructor(url2, eventSourceInitDict) {
        var _a6, _b2;
        super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url), __privateAdd(this, _redirectUrl), __privateAdd(this, _withCredentials), __privateAdd(this, _fetch), __privateAdd(this, _reconnectInterval), __privateAdd(this, _reconnectTimer), __privateAdd(this, _lastEventId, null), __privateAdd(this, _controller), __privateAdd(this, _parser), __privateAdd(this, _onError, null), __privateAdd(this, _onMessage, null), __privateAdd(this, _onOpen, null), __privateAdd(this, _onFetchResponse, async (response) => {
          var _a22;
          __privateGet(this, _parser).reset();
          const { body, redirected, status, headers } = response;
          if (status === 204) {
            __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
            return;
          }
          if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) {
            __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status);
            return;
          }
          if (!(headers.get("content-type") || "").startsWith("text/event-stream")) {
            __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, 'Invalid content type, expected "text/event-stream"', status);
            return;
          }
          if (__privateGet(this, _readyState) === this.CLOSED)
            return;
          __privateSet(this, _readyState, this.OPEN);
          const openEvent = new Event("open");
          if ((_a22 = __privateGet(this, _onOpen)) == null || _a22.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) {
            __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close();
            return;
          }
          const decoder = new TextDecoder(), reader = body.getReader();
          let open3 = true;
          do {
            const { done, value } = await reader.read();
            value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open3 = false, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));
          } while (open3);
        }), __privateAdd(this, _onFetchError, (err) => {
          __privateSet(this, _controller, void 0), !(err.name === "AbortError" || err.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError(err));
        }), __privateAdd(this, _onEvent, (event) => {
          typeof event.id == "string" && __privateSet(this, _lastEventId, event.id);
          const messageEvent = new MessageEvent(event.event || "message", {
            data: event.data,
            origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url).origin,
            lastEventId: event.id || ""
          });
          __privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent);
        }), __privateAdd(this, _onRetryChange, (value) => {
          __privateSet(this, _reconnectInterval, value);
        }), __privateAdd(this, _reconnect, () => {
          __privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this);
        });
        try {
          if (url2 instanceof URL)
            __privateSet(this, _url, url2);
          else if (typeof url2 == "string")
            __privateSet(this, _url, new URL(url2, getBaseURL()));
          else
            throw new Error("Invalid URL");
        } catch {
          throw syntaxError("An invalid or illegal string was specified");
        }
        __privateSet(this, _parser, createParser({
          onEvent: __privateGet(this, _onEvent),
          onRetry: __privateGet(this, _onRetryChange)
        })), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a6 = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a6 : globalThis.fetch), __privateSet(this, _withCredentials, (_b2 = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b2 : false), __privateMethod(this, _EventSource_instances, connect_fn).call(this);
      }
      /**
       * Returns the state of this EventSource object's connection. It can have the values described below.
       *
       * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
       *
       * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
       * defined in the TypeScript `dom` library.
       *
       * @public
       */
      get readyState() {
        return __privateGet(this, _readyState);
      }
      /**
       * Returns the URL providing the event stream.
       *
       * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
       *
       * @public
       */
      get url() {
        return __privateGet(this, _url).href;
      }
      /**
       * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
       *
       * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
       */
      get withCredentials() {
        return __privateGet(this, _withCredentials);
      }
      /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
      get onerror() {
        return __privateGet(this, _onError);
      }
      set onerror(value) {
        __privateSet(this, _onError, value);
      }
      /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
      get onmessage() {
        return __privateGet(this, _onMessage);
      }
      set onmessage(value) {
        __privateSet(this, _onMessage, value);
      }
      /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
      get onopen() {
        return __privateGet(this, _onOpen);
      }
      set onopen(value) {
        __privateSet(this, _onOpen, value);
      }
      addEventListener(type, listener, options2) {
        const listen = listener;
        super.addEventListener(type, listen, options2);
      }
      removeEventListener(type, listener, options2) {
        const listen = listener;
        super.removeEventListener(type, listen, options2);
      }
      /**
       * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
       *
       * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
       *
       * @public
       */
      close() {
        __privateGet(this, _reconnectTimer) && clearTimeout(__privateGet(this, _reconnectTimer)), __privateGet(this, _readyState) !== this.CLOSED && (__privateGet(this, _controller) && __privateGet(this, _controller).abort(), __privateSet(this, _readyState, this.CLOSED), __privateSet(this, _controller, void 0));
      }
    };
    _readyState = /* @__PURE__ */ new WeakMap(), _url = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), /**
    * Connect to the given URL and start receiving events
    *
    * @internal
    */
    connect_fn = /* @__PURE__ */ __name(function() {
      __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError));
    }, "connect_fn"), _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), /**
    * Get request options for the `fetch()` request
    *
    * @returns The request options
    * @internal
    */
    getRequestOptions_fn = /* @__PURE__ */ __name(function() {
      var _a6;
      const init = {
        // [spec] Let `corsAttributeState` be `Anonymous`…
        // [spec] …will have their mode set to "cors"…
        mode: "cors",
        redirect: "follow",
        headers: { Accept: "text/event-stream", ...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0 },
        cache: "no-store",
        signal: (_a6 = __privateGet(this, _controller)) == null ? void 0 : _a6.signal
      };
      return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init;
    }, "getRequestOptions_fn"), _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), /**
    * Handles the process referred to in the EventSource specification as "failing a connection".
    *
    * @param error - The error causing the connection to fail
    * @param code - The HTTP status code, if available
    * @internal
    */
    failConnection_fn = /* @__PURE__ */ __name(function(message, code2) {
      var _a6;
      __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED);
      const errorEvent = new ErrorEvent("error", { code: code2, message });
      (_a6 = __privateGet(this, _onError)) == null || _a6.call(this, errorEvent), this.dispatchEvent(errorEvent);
    }, "failConnection_fn"), /**
    * Schedules a reconnection attempt against the EventSource endpoint.
    *
    * @param message - The error causing the connection to fail
    * @param code - The HTTP status code, if available
    * @internal
    */
    scheduleReconnect_fn = /* @__PURE__ */ __name(function(message, code2) {
      var _a6;
      if (__privateGet(this, _readyState) === this.CLOSED)
        return;
      __privateSet(this, _readyState, this.CONNECTING);
      const errorEvent = new ErrorEvent("error", { code: code2, message });
      (_a6 = __privateGet(this, _onError)) == null || _a6.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval)));
    }, "scheduleReconnect_fn"), _reconnect = /* @__PURE__ */ new WeakMap(), /**
    * ReadyState representing an EventSource currently trying to connect
    *
    * @public
    */
    EventSource.CONNECTING = 0, /**
    * ReadyState representing an EventSource connection that is open (eg connected)
    *
    * @public
    */
    EventSource.OPEN = 1, /**
    * ReadyState representing an EventSource connection that is closed (eg disconnected)
    *
    * @public
    */
    EventSource.CLOSED = 2;
    __name(getBaseURL, "getBaseURL");
  }
});

// node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
var SseError, SSEClientTransport;
var init_sse = __esm({
  "node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"() {
    init_esbuild_shims();
    init_dist2();
    init_types9();
    init_auth2();
    SseError = class extends Error {
      static {
        __name(this, "SseError");
      }
      constructor(code2, message, event) {
        super(`SSE error: ${message}`);
        this.code = code2;
        this.event = event;
      }
    };
    SSEClientTransport = class {
      static {
        __name(this, "SSEClientTransport");
      }
      constructor(url2, opts) {
        this._url = url2;
        this._resourceMetadataUrl = void 0;
        this._eventSourceInit = opts === null || opts === void 0 ? void 0 : opts.eventSourceInit;
        this._requestInit = opts === null || opts === void 0 ? void 0 : opts.requestInit;
        this._authProvider = opts === null || opts === void 0 ? void 0 : opts.authProvider;
        this._fetch = opts === null || opts === void 0 ? void 0 : opts.fetch;
      }
      async _authThenStart() {
        var _a6;
        if (!this._authProvider) {
          throw new UnauthorizedError2("No auth provider");
        }
        let result;
        try {
          result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl });
        } catch (error) {
          (_a6 = this.onerror) === null || _a6 === void 0 ? void 0 : _a6.call(this, error);
          throw error;
        }
        if (result !== "AUTHORIZED") {
          throw new UnauthorizedError2();
        }
        return await this._startOrAuth();
      }
      async _commonHeaders() {
        var _a6;
        const headers = {};
        if (this._authProvider) {
          const tokens = await this._authProvider.tokens();
          if (tokens) {
            headers["Authorization"] = `Bearer ${tokens.access_token}`;
          }
        }
        if (this._protocolVersion) {
          headers["mcp-protocol-version"] = this._protocolVersion;
        }
        return new Headers({ ...headers, ...(_a6 = this._requestInit) === null || _a6 === void 0 ? void 0 : _a6.headers });
      }
      _startOrAuth() {
        var _a6, _b2, _c2;
        const fetchImpl = (_c2 = (_b2 = (_a6 = this === null || this === void 0 ? void 0 : this._eventSourceInit) === null || _a6 === void 0 ? void 0 : _a6.fetch) !== null && _b2 !== void 0 ? _b2 : this._fetch) !== null && _c2 !== void 0 ? _c2 : fetch;
        return new Promise((resolve24, reject) => {
          this._eventSource = new EventSource(this._url.href, {
            ...this._eventSourceInit,
            fetch: /* @__PURE__ */ __name(async (url2, init) => {
              const headers = await this._commonHeaders();
              headers.set("Accept", "text/event-stream");
              const response = await fetchImpl(url2, {
                ...init,
                headers
              });
              if (response.status === 401 && response.headers.has("www-authenticate")) {
                this._resourceMetadataUrl = extractResourceMetadataUrl(response);
              }
              return response;
            }, "fetch")
          });
          this._abortController = new AbortController();
          this._eventSource.onerror = (event) => {
            var _a7;
            if (event.code === 401 && this._authProvider) {
              this._authThenStart().then(resolve24, reject);
              return;
            }
            const error = new SseError(event.code, event.message, event);
            reject(error);
            (_a7 = this.onerror) === null || _a7 === void 0 ? void 0 : _a7.call(this, error);
          };
          this._eventSource.onopen = () => {
          };
          this._eventSource.addEventListener("endpoint", (event) => {
            var _a7;
            const messageEvent = event;
            try {
              this._endpoint = new URL(messageEvent.data, this._url);
              if (this._endpoint.origin !== this._url.origin) {
                throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`);
              }
            } catch (error) {
              reject(error);
              (_a7 = this.onerror) === null || _a7 === void 0 ? void 0 : _a7.call(this, error);
              void this.close();
              return;
            }
            resolve24();
          });
          this._eventSource.onmessage = (event) => {
            var _a7, _b3;
            const messageEvent = event;
            let message;
            try {
              message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
            } catch (error) {
              (_a7 = this.onerror) === null || _a7 === void 0 ? void 0 : _a7.call(this, error);
              return;
            }
            (_b3 = this.onmessage) === null || _b3 === void 0 ? void 0 : _b3.call(this, message);
          };
        });
      }
      async start() {
        if (this._eventSource) {
          throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");
        }
        return await this._startOrAuth();
      }
      /**
       * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
       */
      async finishAuth(authorizationCode) {
        if (!this._authProvider) {
          throw new UnauthorizedError2("No auth provider");
        }
        const result = await auth(this._authProvider, { serverUrl: this._url, authorizationCode, resourceMetadataUrl: this._resourceMetadataUrl });
        if (result !== "AUTHORIZED") {
          throw new UnauthorizedError2("Failed to authorize");
        }
      }
      async close() {
        var _a6, _b2, _c2;
        (_a6 = this._abortController) === null || _a6 === void 0 ? void 0 : _a6.abort();
        (_b2 = this._eventSource) === null || _b2 === void 0 ? void 0 : _b2.close();
        (_c2 = this.onclose) === null || _c2 === void 0 ? void 0 : _c2.call(this);
      }
      async send(message) {
        var _a6, _b2, _c2;
        if (!this._endpoint) {
          throw new Error("Not connected");
        }
        try {
          const headers = await this._commonHeaders();
          headers.set("content-type", "application/json");
          const init = {
            ...this._requestInit,
            method: "POST",
            headers,
            body: JSON.stringify(message),
            signal: (_a6 = this._abortController) === null || _a6 === void 0 ? void 0 : _a6.signal
          };
          const response = await ((_b2 = this._fetch) !== null && _b2 !== void 0 ? _b2 : fetch)(this._endpoint, init);
          if (!response.ok) {
            if (response.status === 401 && this._authProvider) {
              this._resourceMetadataUrl = extractResourceMetadataUrl(response);
              const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl });
              if (result !== "AUTHORIZED") {
                throw new UnauthorizedError2();
              }
              return this.send(message);
            }
            const text = await response.text().catch(() => null);
            throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
          }
        } catch (error) {
          (_c2 = this.onerror) === null || _c2 === void 0 ? void 0 : _c2.call(this, error);
          throw error;
        }
      }
      setProtocolVersion(version2) {
        this._protocolVersion = version2;
      }
    };
  }
});

// packages/core/dist/src/mcp/google-auth-provider.js
var import_google_auth_library4, ALLOWED_HOSTS, GoogleCredentialProvider;
var init_google_auth_provider = __esm({
  "packages/core/dist/src/mcp/google-auth-provider.js"() {
    "use strict";
    init_esbuild_shims();
    import_google_auth_library4 = __toESM(require_src6(), 1);
    ALLOWED_HOSTS = [/^.+\.googleapis\.com$/, /^(.*\.)?luci\.app$/];
    GoogleCredentialProvider = class {
      static {
        __name(this, "GoogleCredentialProvider");
      }
      config;
      auth;
      // Properties required by OAuthClientProvider, with no-op values
      redirectUrl = "";
      clientMetadata = {
        client_name: "Gemini CLI (Google ADC)",
        redirect_uris: [],
        grant_types: [],
        response_types: [],
        token_endpoint_auth_method: "none"
      };
      _clientInformation;
      constructor(config) {
        this.config = config;
        const url2 = this.config?.url || this.config?.httpUrl;
        if (!url2) {
          throw new Error("URL must be provided in the config for Google Credentials provider");
        }
        const hostname3 = new URL(url2).hostname;
        if (!ALLOWED_HOSTS.some((pattern) => pattern.test(hostname3))) {
          throw new Error(`Host "${hostname3}" is not an allowed host for Google Credential provider.`);
        }
        const scopes = this.config?.oauth?.scopes;
        if (!scopes || scopes.length === 0) {
          throw new Error("Scopes must be provided in the oauth config for Google Credentials provider");
        }
        this.auth = new import_google_auth_library4.GoogleAuth({
          scopes
        });
      }
      clientInformation() {
        return this._clientInformation;
      }
      saveClientInformation(clientInformation) {
        this._clientInformation = clientInformation;
      }
      async tokens() {
        const client = await this.auth.getClient();
        const accessTokenResponse = await client.getAccessToken();
        if (!accessTokenResponse.token) {
          console.error("Failed to get access token from Google ADC");
          return void 0;
        }
        const tokens = {
          access_token: accessTokenResponse.token,
          token_type: "Bearer"
        };
        return tokens;
      }
      saveTokens(_tokens) {
      }
      redirectToAuthorization(_authorizationUrl) {
      }
      saveCodeVerifier(_codeVerifier) {
      }
      codeVerifier() {
        return "";
      }
    };
  }
});

// packages/core/dist/src/mcp/sa-impersonation-provider.js
function createIamApiUrl(targetSA) {
  return `https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(targetSA)}:generateIdToken`;
}
var import_google_auth_library5, fiveMinBufferMs, ServiceAccountImpersonationProvider;
var init_sa_impersonation_provider = __esm({
  "packages/core/dist/src/mcp/sa-impersonation-provider.js"() {
    "use strict";
    init_esbuild_shims();
    import_google_auth_library5 = __toESM(require_src6(), 1);
    fiveMinBufferMs = 5 * 60 * 1e3;
    __name(createIamApiUrl, "createIamApiUrl");
    ServiceAccountImpersonationProvider = class {
      static {
        __name(this, "ServiceAccountImpersonationProvider");
      }
      config;
      targetServiceAccount;
      targetAudience;
      // OAuth Client Id
      auth;
      cachedToken;
      tokenExpiryTime;
      // Properties required by OAuthClientProvider, with no-op values
      redirectUrl = "";
      clientMetadata = {
        client_name: "Gemini CLI (Service Account Impersonation)",
        redirect_uris: [],
        grant_types: [],
        response_types: [],
        token_endpoint_auth_method: "none"
      };
      _clientInformation;
      constructor(config) {
        this.config = config;
        if (!this.config.httpUrl && !this.config.url) {
          throw new Error("A url or httpUrl must be provided for the Service Account Impersonation provider");
        }
        if (!config.targetAudience) {
          throw new Error("targetAudience must be provided for the Service Account Impersonation provider");
        }
        this.targetAudience = config.targetAudience;
        if (!config.targetServiceAccount) {
          throw new Error("targetServiceAccount must be provided for the Service Account Impersonation provider");
        }
        this.targetServiceAccount = config.targetServiceAccount;
        this.auth = new import_google_auth_library5.GoogleAuth();
      }
      clientInformation() {
        return this._clientInformation;
      }
      saveClientInformation(clientInformation) {
        this._clientInformation = clientInformation;
      }
      async tokens() {
        if (this.cachedToken && this.tokenExpiryTime && Date.now() < this.tokenExpiryTime - fiveMinBufferMs) {
          return this.cachedToken;
        }
        this.cachedToken = void 0;
        this.tokenExpiryTime = void 0;
        const client = await this.auth.getClient();
        const url2 = createIamApiUrl(this.targetServiceAccount);
        let idToken;
        try {
          const res = await client.request({
            url: url2,
            method: "POST",
            data: {
              audience: this.targetAudience,
              includeEmail: true
            }
          });
          idToken = res.data.token;
          if (!idToken || idToken.length === 0) {
            console.error("Failed to get ID token from Google");
            return void 0;
          }
        } catch (e2) {
          console.error("Failed to fetch ID token from Google:", e2);
          return void 0;
        }
        const expiryTime = this.parseTokenExpiry(idToken);
        const newTokens = {
          access_token: idToken,
          token_type: "Bearer"
        };
        if (expiryTime) {
          this.tokenExpiryTime = expiryTime;
          this.cachedToken = newTokens;
        }
        return newTokens;
      }
      saveTokens(_tokens) {
      }
      redirectToAuthorization(_authorizationUrl) {
      }
      saveCodeVerifier(_codeVerifier) {
      }
      codeVerifier() {
        return "";
      }
      /**
       * Parses a JWT string to extract its expiry time.
       * @param idToken The JWT ID token.
       * @returns The expiry time in **milliseconds**, or undefined if parsing fails.
       */
      parseTokenExpiry(idToken) {
        try {
          const payload = JSON.parse(Buffer.from(idToken.split(".")[1], "base64").toString());
          if (payload && typeof payload.exp === "number") {
            return payload.exp * 1e3;
          }
        } catch (e2) {
          console.error("Failed to parse ID token for expiry time with error:", e2);
        }
        return void 0;
      }
    };
  }
});

// packages/core/dist/src/utils/secure-browser-launcher.js
import { execFile as execFile8 } from "node:child_process";
import { promisify as promisify6 } from "node:util";
import { platform as platform5 } from "node:os";
import { URL as URL3 } from "node:url";
function validateUrl(url2) {
  let parsedUrl;
  try {
    parsedUrl = new URL3(url2);
  } catch (_error) {
    throw new Error(`Invalid URL: ${url2}`);
  }
  if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
    throw new Error(`Unsafe protocol: ${parsedUrl.protocol}. Only HTTP and HTTPS are allowed.`);
  }
  if (/[\r\n\x00-\x1f]/.test(url2)) {
    throw new Error("URL contains invalid characters");
  }
}
async function openBrowserSecurely(url2) {
  validateUrl(url2);
  const platformName = platform5();
  let command2;
  let args;
  switch (platformName) {
    case "darwin":
      command2 = "open";
      args = [url2];
      break;
    case "win32":
      command2 = "powershell.exe";
      args = [
        "-NoProfile",
        "-NonInteractive",
        "-WindowStyle",
        "Hidden",
        "-Command",
        `Start-Process '${url2.replace(/'/g, "''")}'`
      ];
      break;
    case "linux":
    case "freebsd":
    case "openbsd":
      command2 = "xdg-open";
      args = [url2];
      break;
    default:
      throw new Error(`Unsupported platform: ${platformName}`);
  }
  const options2 = {
    // Don't inherit parent's environment to avoid potential issues
    env: {
      ...process.env,
      // Ensure we're not in a shell that might interpret special characters
      SHELL: void 0
    },
    // Detach the browser process so it doesn't block
    detached: true,
    stdio: "ignore"
  };
  try {
    await execFileAsync5(command2, args, options2);
  } catch (error) {
    if ((platformName === "linux" || platformName === "freebsd" || platformName === "openbsd") && command2 === "xdg-open") {
      const fallbackCommands = [
        "gnome-open",
        "kde-open",
        "firefox",
        "chromium",
        "google-chrome"
      ];
      for (const fallbackCommand of fallbackCommands) {
        try {
          await execFileAsync5(fallbackCommand, [url2], options2);
          return;
        } catch {
          continue;
        }
      }
    }
    throw new Error(`Failed to open browser: ${error instanceof Error ? error.message : "Unknown error"}`);
  }
}
var execFileAsync5;
var init_secure_browser_launcher = __esm({
  "packages/core/dist/src/utils/secure-browser-launcher.js"() {
    "use strict";
    init_esbuild_shims();
    execFileAsync5 = promisify6(execFile8);
    __name(validateUrl, "validateUrl");
    __name(openBrowserSecurely, "openBrowserSecurely");
  }
});

// packages/core/dist/src/mcp/oauth-token-storage.js
import { promises as fs39 } from "node:fs";
import * as path43 from "node:path";
var MCPOAuthTokenStorage;
var init_oauth_token_storage = __esm({
  "packages/core/dist/src/mcp/oauth-token-storage.js"() {
    "use strict";
    init_esbuild_shims();
    init_storage();
    init_errors();
    init_hybrid_token_storage();
    init_token_storage();
    MCPOAuthTokenStorage = class {
      static {
        __name(this, "MCPOAuthTokenStorage");
      }
      hybridTokenStorage = new HybridTokenStorage(DEFAULT_SERVICE_NAME);
      useEncryptedFile = process.env[FORCE_ENCRYPTED_FILE_ENV_VAR] === "true";
      /**
       * Get the path to the token storage file.
       *
       * @returns The full path to the token storage file
       */
      getTokenFilePath() {
        return Storage.getMcpOAuthTokensPath();
      }
      /**
       * Ensure the config directory exists.
       */
      async ensureConfigDir() {
        const configDir = path43.dirname(this.getTokenFilePath());
        await fs39.mkdir(configDir, { recursive: true });
      }
      /**
       * Load all stored MCP OAuth tokens.
       *
       * @returns A map of server names to credentials
       */
      async getAllCredentials() {
        if (this.useEncryptedFile) {
          return this.hybridTokenStorage.getAllCredentials();
        }
        const tokenMap = /* @__PURE__ */ new Map();
        try {
          const tokenFile = this.getTokenFilePath();
          const data = await fs39.readFile(tokenFile, "utf-8");
          const tokens = JSON.parse(data);
          for (const credential of tokens) {
            tokenMap.set(credential.serverName, credential);
          }
        } catch (error) {
          if (error.code !== "ENOENT") {
            console.error(`Failed to load MCP OAuth tokens: ${getErrorMessage(error)}`);
          }
        }
        return tokenMap;
      }
      async listServers() {
        if (this.useEncryptedFile) {
          return this.hybridTokenStorage.listServers();
        }
        const tokens = await this.getAllCredentials();
        return Array.from(tokens.keys());
      }
      async setCredentials(credentials) {
        if (this.useEncryptedFile) {
          return this.hybridTokenStorage.setCredentials(credentials);
        }
        const tokens = await this.getAllCredentials();
        tokens.set(credentials.serverName, credentials);
        const tokenArray = Array.from(tokens.values());
        const tokenFile = this.getTokenFilePath();
        try {
          await fs39.writeFile(tokenFile, JSON.stringify(tokenArray, null, 2), { mode: 384 });
        } catch (error) {
          console.error(`Failed to save MCP OAuth token: ${getErrorMessage(error)}`);
          throw error;
        }
      }
      /**
       * Save a token for a specific MCP server.
       *
       * @param serverName The name of the MCP server
       * @param token The OAuth token to save
       * @param clientId Optional client ID used for this token
       * @param tokenUrl Optional token URL used for this token
       * @param mcpServerUrl Optional MCP server URL
       */
      async saveToken(serverName, token2, clientId, tokenUrl, mcpServerUrl) {
        await this.ensureConfigDir();
        const credential = {
          serverName,
          token: token2,
          clientId,
          tokenUrl,
          mcpServerUrl,
          updatedAt: Date.now()
        };
        if (this.useEncryptedFile) {
          return this.hybridTokenStorage.setCredentials(credential);
        }
        await this.setCredentials(credential);
      }
      /**
       * Get a token for a specific MCP server.
       *
       * @param serverName The name of the MCP server
       * @returns The stored credentials or null if not found
       */
      async getCredentials(serverName) {
        if (this.useEncryptedFile) {
          return this.hybridTokenStorage.getCredentials(serverName);
        }
        const tokens = await this.getAllCredentials();
        return tokens.get(serverName) || null;
      }
      /**
       * Remove a token for a specific MCP server.
       *
       * @param serverName The name of the MCP server
       */
      async deleteCredentials(serverName) {
        if (this.useEncryptedFile) {
          return this.hybridTokenStorage.deleteCredentials(serverName);
        }
        const tokens = await this.getAllCredentials();
        if (tokens.delete(serverName)) {
          const tokenArray = Array.from(tokens.values());
          const tokenFile = this.getTokenFilePath();
          try {
            if (tokenArray.length === 0) {
              await fs39.unlink(tokenFile);
            } else {
              await fs39.writeFile(tokenFile, JSON.stringify(tokenArray, null, 2), {
                mode: 384
              });
            }
          } catch (error) {
            console.error(`Failed to remove MCP OAuth token: ${getErrorMessage(error)}`);
          }
        }
      }
      /**
       * Check if a token is expired.
       *
       * @param token The token to check
       * @returns True if the token is expired
       */
      isTokenExpired(token2) {
        if (!token2.expiresAt) {
          return false;
        }
        const bufferMs = 5 * 60 * 1e3;
        return Date.now() + bufferMs >= token2.expiresAt;
      }
      /**
       * Clear all stored MCP OAuth tokens.
       */
      async clearAll() {
        if (this.useEncryptedFile) {
          return this.hybridTokenStorage.clearAll();
        }
        try {
          const tokenFile = this.getTokenFilePath();
          await fs39.unlink(tokenFile);
        } catch (error) {
          if (error.code !== "ENOENT") {
            console.error(`Failed to clear MCP OAuth tokens: ${getErrorMessage(error)}`);
          }
        }
      }
    };
  }
});

// packages/core/dist/src/mcp/oauth-utils.js
var OAuthUtils;
var init_oauth_utils = __esm({
  "packages/core/dist/src/mcp/oauth-utils.js"() {
    "use strict";
    init_esbuild_shims();
    init_errors();
    OAuthUtils = class {
      static {
        __name(this, "OAuthUtils");
      }
      /**
       * Construct well-known OAuth endpoint URLs.
       * By default, uses standard root-based well-known URLs.
       * If includePathSuffix is true, appends any path from the base URL to the well-known endpoints.
       */
      static buildWellKnownUrls(baseUrl, includePathSuffix = false) {
        const serverUrl = new URL(baseUrl);
        const base = `${serverUrl.protocol}//${serverUrl.host}`;
        if (!includePathSuffix) {
          return {
            protectedResource: new URL("/.well-known/oauth-protected-resource", base).toString(),
            authorizationServer: new URL("/.well-known/oauth-authorization-server", base).toString()
          };
        }
        const pathSuffix = serverUrl.pathname.replace(/\/$/, "");
        return {
          protectedResource: new URL(`/.well-known/oauth-protected-resource${pathSuffix}`, base).toString(),
          authorizationServer: new URL(`/.well-known/oauth-authorization-server${pathSuffix}`, base).toString()
        };
      }
      /**
       * Fetch OAuth protected resource metadata.
       *
       * @param resourceMetadataUrl The protected resource metadata URL
       * @returns The protected resource metadata or null if not available
       */
      static async fetchProtectedResourceMetadata(resourceMetadataUrl) {
        try {
          const response = await fetch(resourceMetadataUrl);
          if (!response.ok) {
            return null;
          }
          return await response.json();
        } catch (error) {
          console.debug(`Failed to fetch protected resource metadata from ${resourceMetadataUrl}: ${getErrorMessage(error)}`);
          return null;
        }
      }
      /**
       * Fetch OAuth authorization server metadata.
       *
       * @param authServerMetadataUrl The authorization server metadata URL
       * @returns The authorization server metadata or null if not available
       */
      static async fetchAuthorizationServerMetadata(authServerMetadataUrl) {
        try {
          const response = await fetch(authServerMetadataUrl);
          if (!response.ok) {
            return null;
          }
          return await response.json();
        } catch (error) {
          console.debug(`Failed to fetch authorization server metadata from ${authServerMetadataUrl}: ${getErrorMessage(error)}`);
          return null;
        }
      }
      /**
       * Convert authorization server metadata to OAuth configuration.
       *
       * @param metadata The authorization server metadata
       * @returns The OAuth configuration
       */
      static metadataToOAuthConfig(metadata) {
        return {
          authorizationUrl: metadata.authorization_endpoint,
          tokenUrl: metadata.token_endpoint,
          scopes: metadata.scopes_supported || [],
          registrationUrl: metadata.registration_endpoint
        };
      }
      /**
       * Discover Oauth Authorization server metadata given an Auth server URL, by
       * trying the standard well-known endpoints.
       *
       * @param authServerUrl The authorization server URL
       * @returns The authorization server metadata or null if not found
       */
      static async discoverAuthorizationServerMetadata(authServerUrl) {
        const authServerUrlObj = new URL(authServerUrl);
        const base = `${authServerUrlObj.protocol}//${authServerUrlObj.host}`;
        const endpointsToTry = [];
        if (authServerUrlObj.pathname !== "/") {
          endpointsToTry.push(new URL(`/.well-known/oauth-authorization-server${authServerUrlObj.pathname}`, base).toString());
          endpointsToTry.push(new URL(`/.well-known/openid-configuration${authServerUrlObj.pathname}`, base).toString());
          endpointsToTry.push(new URL(`${authServerUrlObj.pathname}/.well-known/openid-configuration`, base).toString());
        }
        endpointsToTry.push(new URL("/.well-known/oauth-authorization-server", base).toString());
        endpointsToTry.push(new URL("/.well-known/openid-configuration", base).toString());
        for (const endpoint of endpointsToTry) {
          const authServerMetadata = await this.fetchAuthorizationServerMetadata(endpoint);
          if (authServerMetadata) {
            return authServerMetadata;
          }
        }
        console.debug(`Metadata discovery failed for authorization server ${authServerUrl}`);
        return null;
      }
      /**
       * Discover OAuth configuration using the standard well-known endpoints.
       *
       * @param serverUrl The base URL of the server
       * @returns The discovered OAuth configuration or null if not available
       */
      static async discoverOAuthConfig(serverUrl) {
        try {
          const wellKnownUrls = this.buildWellKnownUrls(serverUrl, false);
          let resourceMetadata = await this.fetchProtectedResourceMetadata(wellKnownUrls.protectedResource);
          if (!resourceMetadata) {
            const url2 = new URL(serverUrl);
            if (url2.pathname && url2.pathname !== "/") {
              const pathBasedUrls = this.buildWellKnownUrls(serverUrl, true);
              resourceMetadata = await this.fetchProtectedResourceMetadata(pathBasedUrls.protectedResource);
            }
          }
          if (resourceMetadata?.authorization_servers?.length) {
            const authServerUrl = resourceMetadata.authorization_servers[0];
            const authServerMetadata2 = await this.discoverAuthorizationServerMetadata(authServerUrl);
            if (authServerMetadata2) {
              const config = this.metadataToOAuthConfig(authServerMetadata2);
              if (authServerMetadata2.registration_endpoint) {
                console.log("Dynamic client registration is supported at:", authServerMetadata2.registration_endpoint);
              }
              return config;
            }
          }
          console.debug(`Trying OAuth discovery fallback at ${serverUrl}`);
          const authServerMetadata = await this.discoverAuthorizationServerMetadata(serverUrl);
          if (authServerMetadata) {
            const config = this.metadataToOAuthConfig(authServerMetadata);
            if (authServerMetadata.registration_endpoint) {
              console.log("Dynamic client registration is supported at:", authServerMetadata.registration_endpoint);
            }
            return config;
          }
          return null;
        } catch (error) {
          console.debug(`Failed to discover OAuth configuration: ${getErrorMessage(error)}`);
          return null;
        }
      }
      /**
       * Parse WWW-Authenticate header to extract OAuth information.
       *
       * @param header The WWW-Authenticate header value
       * @returns The resource metadata URI if found
       */
      static parseWWWAuthenticateHeader(header) {
        const match2 = header.match(/resource_metadata="([^"]+)"/);
        if (match2) {
          return match2[1];
        }
        return null;
      }
      /**
       * Discover OAuth configuration from WWW-Authenticate header.
       *
       * @param wwwAuthenticate The WWW-Authenticate header value
       * @returns The discovered OAuth configuration or null if not available
       */
      static async discoverOAuthFromWWWAuthenticate(wwwAuthenticate) {
        const resourceMetadataUri = this.parseWWWAuthenticateHeader(wwwAuthenticate);
        if (!resourceMetadataUri) {
          return null;
        }
        const resourceMetadata = await this.fetchProtectedResourceMetadata(resourceMetadataUri);
        if (!resourceMetadata?.authorization_servers?.length) {
          return null;
        }
        const authServerUrl = resourceMetadata.authorization_servers[0];
        const authServerMetadata = await this.discoverAuthorizationServerMetadata(authServerUrl);
        if (authServerMetadata) {
          return this.metadataToOAuthConfig(authServerMetadata);
        }
        return null;
      }
      /**
       * Extract base URL from an MCP server URL.
       *
       * @param mcpServerUrl The MCP server URL
       * @returns The base URL
       */
      static extractBaseUrl(mcpServerUrl) {
        const serverUrl = new URL(mcpServerUrl);
        return `${serverUrl.protocol}//${serverUrl.host}`;
      }
      /**
       * Check if a URL is an SSE endpoint.
       *
       * @param url The URL to check
       * @returns True if the URL appears to be an SSE endpoint
       */
      static isSSEEndpoint(url2) {
        return url2.includes("/sse") || !url2.includes("/mcp");
      }
      /**
       * Build a resource parameter for OAuth requests.
       *
       * @param endpointUrl The endpoint URL
       * @returns The resource parameter value
       */
      static buildResourceParameter(endpointUrl) {
        const url2 = new URL(endpointUrl);
        return `${url2.protocol}//${url2.host}`;
      }
    };
  }
});

// packages/core/dist/src/mcp/oauth-provider.js
import * as http3 from "node:http";
import * as crypto14 from "node:crypto";
import { URL as URL4 } from "node:url";
var OAUTH_DISPLAY_MESSAGE_EVENT, REDIRECT_PORT, REDIRECT_PATH, HTTP_OK, MCPOAuthProvider;
var init_oauth_provider = __esm({
  "packages/core/dist/src/mcp/oauth-provider.js"() {
    "use strict";
    init_esbuild_shims();
    init_secure_browser_launcher();
    init_oauth_token_storage();
    init_errors();
    init_oauth_utils();
    OAUTH_DISPLAY_MESSAGE_EVENT = "oauth-display-message";
    REDIRECT_PORT = 7777;
    REDIRECT_PATH = "/oauth/callback";
    HTTP_OK = 200;
    MCPOAuthProvider = class {
      static {
        __name(this, "MCPOAuthProvider");
      }
      tokenStorage;
      constructor(tokenStorage = new MCPOAuthTokenStorage()) {
        this.tokenStorage = tokenStorage;
      }
      /**
       * Register a client dynamically with the OAuth server.
       *
       * @param registrationUrl The client registration endpoint URL
       * @param config OAuth configuration
       * @returns The registered client information
       */
      async registerClient(registrationUrl, config) {
        const redirectUri = config.redirectUri || `http://localhost:${REDIRECT_PORT}${REDIRECT_PATH}`;
        const registrationRequest = {
          client_name: "Gemini CLI (Google ADC)",
          redirect_uris: [redirectUri],
          grant_types: ["authorization_code", "refresh_token"],
          response_types: ["code"],
          token_endpoint_auth_method: "none",
          // Public client
          code_challenge_method: ["S256"],
          scope: config.scopes?.join(" ") || ""
        };
        const response = await fetch(registrationUrl, {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify(registrationRequest)
        });
        if (!response.ok) {
          const errorText = await response.text();
          throw new Error(`Client registration failed: ${response.status} ${response.statusText} - ${errorText}`);
        }
        return await response.json();
      }
      /**
       * Discover OAuth configuration from an MCP server URL.
       *
       * @param mcpServerUrl The MCP server URL
       * @returns OAuth configuration if discovered, null otherwise
       */
      async discoverOAuthFromMCPServer(mcpServerUrl) {
        return OAuthUtils.discoverOAuthConfig(mcpServerUrl);
      }
      /**
       * Generate PKCE parameters for OAuth flow.
       *
       * @returns PKCE parameters including code verifier, challenge, and state
       */
      generatePKCEParams() {
        const codeVerifier = crypto14.randomBytes(32).toString("base64url");
        const codeChallenge = crypto14.createHash("sha256").update(codeVerifier).digest("base64url");
        const state = crypto14.randomBytes(16).toString("base64url");
        return { codeVerifier, codeChallenge, state };
      }
      /**
       * Start a local HTTP server to handle OAuth callback.
       *
       * @param expectedState The state parameter to validate
       * @returns Promise that resolves with the authorization code
       */
      async startCallbackServer(expectedState) {
        return new Promise((resolve24, reject) => {
          const server = http3.createServer(async (req, res) => {
            try {
              const url2 = new URL4(req.url, `http://localhost:${REDIRECT_PORT}`);
              if (url2.pathname !== REDIRECT_PATH) {
                res.writeHead(404);
                res.end("Not found");
                return;
              }
              const code2 = url2.searchParams.get("code");
              const state = url2.searchParams.get("state");
              const error = url2.searchParams.get("error");
              if (error) {
                res.writeHead(HTTP_OK, { "Content-Type": "text/html" });
                res.end(`
              <html>
                <body>
                  <h1>Authentication Failed</h1>
                  <p>Error: ${error.replace(/</g, "&lt;").replace(/>/g, "&gt;")}</p>
                  <p>${(url2.searchParams.get("error_description") || "").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</p>
                  <p>You can close this window.</p>
                </body>
              </html>
            `);
                server.close();
                reject(new Error(`OAuth error: ${error}`));
                return;
              }
              if (!code2 || !state) {
                res.writeHead(400);
                res.end("Missing code or state parameter");
                return;
              }
              if (state !== expectedState) {
                res.writeHead(400);
                res.end("Invalid state parameter");
                server.close();
                reject(new Error("State mismatch - possible CSRF attack"));
                return;
              }
              res.writeHead(HTTP_OK, { "Content-Type": "text/html" });
              res.end(`
            <html>
              <body>
                <h1>Authentication Successful!</h1>
                <p>You can close this window and return to Gemini CLI.</p>
                <script>window.close();</script>
              </body>
            </html>
          `);
              server.close();
              resolve24({ code: code2, state });
            } catch (error) {
              server.close();
              reject(error);
            }
          });
          server.on("error", reject);
          server.listen(REDIRECT_PORT, () => {
            console.log(`OAuth callback server listening on port ${REDIRECT_PORT}`);
          });
          setTimeout(() => {
            server.close();
            reject(new Error("OAuth callback timeout"));
          }, 5 * 60 * 1e3);
        });
      }
      /**
       * Build the authorization URL with PKCE parameters.
       *
       * @param config OAuth configuration
       * @param pkceParams PKCE parameters
       * @param mcpServerUrl The MCP server URL to use as the resource parameter
       * @returns The authorization URL
       */
      buildAuthorizationUrl(config, pkceParams, mcpServerUrl) {
        const redirectUri = config.redirectUri || `http://localhost:${REDIRECT_PORT}${REDIRECT_PATH}`;
        const params = new URLSearchParams({
          client_id: config.clientId,
          response_type: "code",
          redirect_uri: redirectUri,
          state: pkceParams.state,
          code_challenge: pkceParams.codeChallenge,
          code_challenge_method: "S256"
        });
        if (config.scopes && config.scopes.length > 0) {
          params.append("scope", config.scopes.join(" "));
        }
        if (config.audiences && config.audiences.length > 0) {
          params.append("audience", config.audiences.join(" "));
        }
        if (mcpServerUrl) {
          try {
            params.append("resource", OAuthUtils.buildResourceParameter(mcpServerUrl));
          } catch (error) {
            console.warn(`Could not add resource parameter: ${getErrorMessage(error)}`);
          }
        }
        const url2 = new URL4(config.authorizationUrl);
        params.forEach((value, key) => {
          url2.searchParams.append(key, value);
        });
        return url2.toString();
      }
      /**
       * Exchange authorization code for tokens.
       *
       * @param config OAuth configuration
       * @param code Authorization code
       * @param codeVerifier PKCE code verifier
       * @param mcpServerUrl The MCP server URL to use as the resource parameter
       * @returns The token response
       */
      async exchangeCodeForToken(config, code2, codeVerifier, mcpServerUrl) {
        const redirectUri = config.redirectUri || `http://localhost:${REDIRECT_PORT}${REDIRECT_PATH}`;
        const params = new URLSearchParams({
          grant_type: "authorization_code",
          code: code2,
          redirect_uri: redirectUri,
          code_verifier: codeVerifier,
          client_id: config.clientId
        });
        if (config.clientSecret) {
          params.append("client_secret", config.clientSecret);
        }
        if (config.audiences && config.audiences.length > 0) {
          params.append("audience", config.audiences.join(" "));
        }
        if (mcpServerUrl) {
          const resourceUrl = mcpServerUrl;
          try {
            params.append("resource", OAuthUtils.buildResourceParameter(resourceUrl));
          } catch (error) {
            console.warn(`Could not add resource parameter: ${getErrorMessage(error)}`);
          }
        }
        const response = await fetch(config.tokenUrl, {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            Accept: "application/json, application/x-www-form-urlencoded"
          },
          body: params.toString()
        });
        const responseText = await response.text();
        const contentType = response.headers.get("content-type") || "";
        if (!response.ok) {
          let errorMessage = null;
          try {
            const errorParams = new URLSearchParams(responseText);
            const error = errorParams.get("error");
            const errorDescription = errorParams.get("error_description");
            if (error) {
              errorMessage = `Token exchange failed: ${error} - ${errorDescription || "No description"}`;
            }
          } catch {
          }
          throw new Error(errorMessage || `Token exchange failed: ${response.status} - ${responseText}`);
        }
        if (!contentType.includes("application/json") && !contentType.includes("application/x-www-form-urlencoded")) {
          console.warn(`Token endpoint returned unexpected content-type: ${contentType}. Expected application/json or application/x-www-form-urlencoded. Will attempt to parse response.`);
        }
        try {
          return JSON.parse(responseText);
        } catch {
          const tokenParams = new URLSearchParams(responseText);
          const accessToken = tokenParams.get("access_token");
          const tokenType = tokenParams.get("token_type") || "Bearer";
          const expiresIn = tokenParams.get("expires_in");
          const refreshToken = tokenParams.get("refresh_token");
          const scope = tokenParams.get("scope");
          if (!accessToken) {
            const error = tokenParams.get("error");
            const errorDescription = tokenParams.get("error_description");
            throw new Error(`Token exchange failed: ${error || "no_access_token"} - ${errorDescription || responseText}`);
          }
          return {
            access_token: accessToken,
            token_type: tokenType,
            expires_in: expiresIn ? parseInt(expiresIn, 10) : void 0,
            refresh_token: refreshToken || void 0,
            scope: scope || void 0
          };
        }
      }
      /**
       * Refresh an access token using a refresh token.
       *
       * @param config OAuth configuration
       * @param refreshToken The refresh token
       * @param tokenUrl The token endpoint URL
       * @param mcpServerUrl The MCP server URL to use as the resource parameter
       * @returns The new token response
       */
      async refreshAccessToken(config, refreshToken, tokenUrl, mcpServerUrl) {
        const params = new URLSearchParams({
          grant_type: "refresh_token",
          refresh_token: refreshToken,
          client_id: config.clientId
        });
        if (config.clientSecret) {
          params.append("client_secret", config.clientSecret);
        }
        if (config.scopes && config.scopes.length > 0) {
          params.append("scope", config.scopes.join(" "));
        }
        if (config.audiences && config.audiences.length > 0) {
          params.append("audience", config.audiences.join(" "));
        }
        if (mcpServerUrl) {
          try {
            params.append("resource", OAuthUtils.buildResourceParameter(mcpServerUrl));
          } catch (error) {
            console.warn(`Could not add resource parameter: ${getErrorMessage(error)}`);
          }
        }
        const response = await fetch(tokenUrl, {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            Accept: "application/json, application/x-www-form-urlencoded"
          },
          body: params.toString()
        });
        const responseText = await response.text();
        const contentType = response.headers.get("content-type") || "";
        if (!response.ok) {
          let errorMessage = null;
          try {
            const errorParams = new URLSearchParams(responseText);
            const error = errorParams.get("error");
            const errorDescription = errorParams.get("error_description");
            if (error) {
              errorMessage = `Token refresh failed: ${error} - ${errorDescription || "No description"}`;
            }
          } catch {
          }
          throw new Error(errorMessage || `Token refresh failed: ${response.status} - ${responseText}`);
        }
        if (!contentType.includes("application/json") && !contentType.includes("application/x-www-form-urlencoded")) {
          console.warn(`Token refresh endpoint returned unexpected content-type: ${contentType}. Expected application/json or application/x-www-form-urlencoded. Will attempt to parse response.`);
        }
        try {
          return JSON.parse(responseText);
        } catch {
          const tokenParams = new URLSearchParams(responseText);
          const accessToken = tokenParams.get("access_token");
          const tokenType = tokenParams.get("token_type") || "Bearer";
          const expiresIn = tokenParams.get("expires_in");
          const refreshToken2 = tokenParams.get("refresh_token");
          const scope = tokenParams.get("scope");
          if (!accessToken) {
            const error = tokenParams.get("error");
            const errorDescription = tokenParams.get("error_description");
            throw new Error(`Token refresh failed: ${error || "unknown_error"} - ${errorDescription || responseText}`);
          }
          return {
            access_token: accessToken,
            token_type: tokenType,
            expires_in: expiresIn ? parseInt(expiresIn, 10) : void 0,
            refresh_token: refreshToken2 || void 0,
            scope: scope || void 0
          };
        }
      }
      /**
       * Perform the full OAuth authorization code flow with PKCE.
       *
       * @param serverName The name of the MCP server
       * @param config OAuth configuration
       * @param mcpServerUrl Optional MCP server URL for OAuth discovery
       * @param messageHandler Optional handler for displaying user-facing messages
       * @returns The obtained OAuth token
       */
      async authenticate(serverName, config, mcpServerUrl, events) {
        const displayMessage = /* @__PURE__ */ __name((message) => {
          if (events) {
            events.emit(OAUTH_DISPLAY_MESSAGE_EVENT, message);
          } else {
            console.log(message);
          }
        }, "displayMessage");
        if (!config.authorizationUrl && mcpServerUrl) {
          console.debug(`Starting OAuth for MCP server "${serverName}"\u2026
\u2713 No authorization URL; using OAuth discovery`);
          try {
            const headers = OAuthUtils.isSSEEndpoint(mcpServerUrl) ? { Accept: "text/event-stream" } : { Accept: "application/json" };
            const response = await fetch(mcpServerUrl, {
              method: "HEAD",
              headers
            });
            if (response.status === 401 || response.status === 307) {
              const wwwAuthenticate = response.headers.get("www-authenticate");
              if (wwwAuthenticate) {
                const discoveredConfig = await OAuthUtils.discoverOAuthFromWWWAuthenticate(wwwAuthenticate);
                if (discoveredConfig) {
                  config = {
                    ...config,
                    authorizationUrl: discoveredConfig.authorizationUrl,
                    tokenUrl: discoveredConfig.tokenUrl,
                    scopes: discoveredConfig.scopes || config.scopes || [],
                    // Preserve existing client credentials
                    clientId: config.clientId,
                    clientSecret: config.clientSecret
                  };
                }
              }
            }
          } catch (error) {
            console.debug(`Failed to check endpoint for authentication requirements: ${getErrorMessage(error)}`);
          }
          if (!config.authorizationUrl) {
            const discoveredConfig = await this.discoverOAuthFromMCPServer(mcpServerUrl);
            if (discoveredConfig) {
              config = {
                ...config,
                authorizationUrl: discoveredConfig.authorizationUrl,
                tokenUrl: discoveredConfig.tokenUrl,
                scopes: discoveredConfig.scopes || config.scopes || [],
                registrationUrl: discoveredConfig.registrationUrl,
                // Preserve existing client credentials
                clientId: config.clientId,
                clientSecret: config.clientSecret
              };
            } else {
              throw new Error("Failed to discover OAuth configuration from MCP server");
            }
          }
        }
        if (!config.clientId) {
          let registrationUrl = config.registrationUrl;
          if (!registrationUrl) {
            if (!config.authorizationUrl) {
              throw new Error("Cannot perform dynamic registration without authorization URL");
            }
            const authUrl2 = new URL4(config.authorizationUrl);
            const serverUrl = `${authUrl2.protocol}//${authUrl2.host}`;
            console.debug("\u2192 Attempting dynamic client registration...");
            const authServerMetadata = await OAuthUtils.discoverAuthorizationServerMetadata(serverUrl);
            if (!authServerMetadata) {
              throw new Error("Failed to fetch authorization server metadata for client registration");
            }
            registrationUrl = authServerMetadata.registration_endpoint;
          }
          if (registrationUrl) {
            const clientRegistration = await this.registerClient(registrationUrl, config);
            config.clientId = clientRegistration.client_id;
            if (clientRegistration.client_secret) {
              config.clientSecret = clientRegistration.client_secret;
            }
            console.debug("\u2713 Dynamic client registration successful");
          } else {
            throw new Error("No client ID provided and dynamic registration not supported");
          }
        }
        if (!config.clientId || !config.authorizationUrl || !config.tokenUrl) {
          throw new Error("Missing required OAuth configuration after discovery and registration");
        }
        const pkceParams = this.generatePKCEParams();
        const authUrl = this.buildAuthorizationUrl(config, pkceParams, mcpServerUrl);
        displayMessage(`\u2192 Opening your browser for OAuth sign-in...

If the browser does not open, copy and paste this URL into your browser:
${authUrl}

\u{1F4A1} TIP: Triple-click to select the entire URL, then copy and paste it into your browser.
\u26A0\uFE0F  Make sure to copy the COMPLETE URL - it may wrap across multiple lines.`);
        const callbackPromise = this.startCallbackServer(pkceParams.state);
        try {
          await openBrowserSecurely(authUrl);
        } catch (error) {
          console.warn("Failed to open browser automatically:", getErrorMessage(error));
        }
        const { code: code2 } = await callbackPromise;
        console.debug("\u2713 Authorization code received, exchanging for tokens...");
        const tokenResponse = await this.exchangeCodeForToken(config, code2, pkceParams.codeVerifier, mcpServerUrl);
        if (!tokenResponse.access_token) {
          throw new Error("No access token received from token endpoint");
        }
        const token2 = {
          accessToken: tokenResponse.access_token,
          tokenType: tokenResponse.token_type || "Bearer",
          refreshToken: tokenResponse.refresh_token,
          scope: tokenResponse.scope
        };
        if (tokenResponse.expires_in) {
          token2.expiresAt = Date.now() + tokenResponse.expires_in * 1e3;
        }
        try {
          await this.tokenStorage.saveToken(serverName, token2, config.clientId, config.tokenUrl, mcpServerUrl);
          console.debug("\u2713 Authentication successful! Token saved.");
          const savedToken = await this.tokenStorage.getCredentials(serverName);
          if (savedToken && savedToken.token && savedToken.token.accessToken) {
            const tokenFingerprint = crypto14.createHash("sha256").update(savedToken.token.accessToken).digest("hex").slice(0, 8);
            console.debug(`\u2713 Token verification successful (fingerprint: ${tokenFingerprint})`);
          } else {
            console.error("Token verification failed: token not found or invalid after save");
          }
        } catch (saveError) {
          console.error(`Failed to save token: ${getErrorMessage(saveError)}`);
          throw saveError;
        }
        return token2;
      }
      /**
       * Get a valid access token for an MCP server, refreshing if necessary.
       *
       * @param serverName The name of the MCP server
       * @param config OAuth configuration
       * @returns A valid access token or null if not authenticated
       */
      async getValidToken(serverName, config) {
        console.debug(`Getting valid token for server: ${serverName}`);
        const credentials = await this.tokenStorage.getCredentials(serverName);
        if (!credentials) {
          console.debug(`No credentials found for server: ${serverName}`);
          return null;
        }
        const { token: token2 } = credentials;
        console.debug(`Found token for server: ${serverName}, expired: ${this.tokenStorage.isTokenExpired(token2)}`);
        if (!this.tokenStorage.isTokenExpired(token2)) {
          console.debug(`Returning valid token for server: ${serverName}`);
          return token2.accessToken;
        }
        if (token2.refreshToken && config.clientId && credentials.tokenUrl) {
          try {
            console.log(`Refreshing expired token for MCP server: ${serverName}`);
            const newTokenResponse = await this.refreshAccessToken(config, token2.refreshToken, credentials.tokenUrl, credentials.mcpServerUrl);
            const newToken = {
              accessToken: newTokenResponse.access_token,
              tokenType: newTokenResponse.token_type,
              refreshToken: newTokenResponse.refresh_token || token2.refreshToken,
              scope: newTokenResponse.scope || token2.scope
            };
            if (newTokenResponse.expires_in) {
              newToken.expiresAt = Date.now() + newTokenResponse.expires_in * 1e3;
            }
            await this.tokenStorage.saveToken(serverName, newToken, config.clientId, credentials.tokenUrl, credentials.mcpServerUrl);
            return newToken.accessToken;
          } catch (error) {
            console.error(`Failed to refresh token: ${getErrorMessage(error)}`);
            await this.tokenStorage.deleteCredentials(serverName);
          }
        }
        return null;
      }
    };
  }
});

// packages/core/dist/src/tools/mcp-client.js
import { basename as basename8 } from "node:path";
import { pathToFileURL } from "node:url";
function updateMCPServerStatus(serverName, status) {
  serverStatuses.set(serverName, status);
  for (const listener of statusChangeListeners) {
    listener(serverName, status);
  }
}
function getMCPServerStatus(serverName) {
  return serverStatuses.get(serverName) || MCPServerStatus.DISCONNECTED;
}
function getMCPDiscoveryState() {
  return mcpDiscoveryState;
}
function extractWWWAuthenticateHeader(errorString) {
  const patterns = [
    /www-authenticate:\s*([^\n\r]+)/i,
    /WWW-Authenticate:\s*([^\n\r]+)/i,
    /"www-authenticate":\s*"([^"]+)"/i,
    /'www-authenticate':\s*'([^']+)'/i
  ];
  for (const pattern of patterns) {
    const match2 = errorString.match(pattern);
    if (match2) {
      return match2[1].trim();
    }
  }
  return null;
}
async function handleAutomaticOAuth(mcpServerName, mcpServerConfig, wwwAuthenticate) {
  try {
    console.log(`\u{1F510} '${mcpServerName}' requires OAuth authentication`);
    let oauthConfig;
    const resourceMetadataUri = OAuthUtils.parseWWWAuthenticateHeader(wwwAuthenticate);
    if (resourceMetadataUri) {
      oauthConfig = await OAuthUtils.discoverOAuthConfig(resourceMetadataUri);
    } else if (hasNetworkTransport(mcpServerConfig)) {
      const serverUrl2 = new URL(mcpServerConfig.httpUrl || mcpServerConfig.url);
      const baseUrl = `${serverUrl2.protocol}//${serverUrl2.host}`;
      oauthConfig = await OAuthUtils.discoverOAuthConfig(baseUrl);
    }
    if (!oauthConfig) {
      console.error(`\u274C Could not configure OAuth for '${mcpServerName}' - please authenticate manually with /mcp auth ${mcpServerName}`);
      return false;
    }
    const oauthAuthConfig = {
      enabled: true,
      authorizationUrl: oauthConfig.authorizationUrl,
      tokenUrl: oauthConfig.tokenUrl,
      scopes: oauthConfig.scopes || []
    };
    const serverUrl = mcpServerConfig.httpUrl || mcpServerConfig.url;
    console.log(`Starting OAuth authentication for server '${mcpServerName}'...`);
    const authProvider = new MCPOAuthProvider(new MCPOAuthTokenStorage());
    await authProvider.authenticate(mcpServerName, oauthAuthConfig, serverUrl);
    console.log(`OAuth authentication successful for server '${mcpServerName}'`);
    return true;
  } catch (error) {
    console.error(`Failed to handle automatic OAuth for server '${mcpServerName}': ${getErrorMessage(error)}`);
    return false;
  }
}
async function createTransportWithOAuth(mcpServerName, mcpServerConfig, accessToken) {
  try {
    if (mcpServerConfig.httpUrl) {
      const oauthTransportOptions = {
        requestInit: {
          headers: {
            ...mcpServerConfig.headers,
            Authorization: `Bearer ${accessToken}`
          }
        }
      };
      return new StreamableHTTPClientTransport(new URL(mcpServerConfig.httpUrl), oauthTransportOptions);
    } else if (mcpServerConfig.url) {
      return new SSEClientTransport(new URL(mcpServerConfig.url), {
        requestInit: {
          headers: {
            ...mcpServerConfig.headers,
            Authorization: `Bearer ${accessToken}`
          }
        }
      });
    }
    return null;
  } catch (error) {
    console.error(`Failed to create OAuth transport for server '${mcpServerName}': ${getErrorMessage(error)}`);
    return null;
  }
}
function populateMcpServerCommand(mcpServers, mcpServerCommand) {
  if (mcpServerCommand) {
    const cmd = mcpServerCommand;
    const args = (0, import_shell_quote3.parse)(cmd, process.env);
    if (args.some((arg) => typeof arg !== "string")) {
      throw new Error("failed to parse mcpServerCommand: " + cmd);
    }
    mcpServers["mcp"] = {
      command: args[0],
      args: args.slice(1)
    };
  }
  return mcpServers;
}
async function connectAndDiscover(mcpServerName, mcpServerConfig, toolRegistry, promptRegistry, debugMode, workspaceContext, cliConfig) {
  updateMCPServerStatus(mcpServerName, MCPServerStatus.CONNECTING);
  let mcpClient;
  try {
    mcpClient = await connectToMcpServer(mcpServerName, mcpServerConfig, debugMode, workspaceContext);
    mcpClient.onerror = (error) => {
      console.error(`MCP ERROR (${mcpServerName}):`, error.toString());
      updateMCPServerStatus(mcpServerName, MCPServerStatus.DISCONNECTED);
    };
    const prompts = await discoverPrompts(mcpServerName, mcpClient, promptRegistry);
    const tools = await discoverTools(mcpServerName, mcpServerConfig, mcpClient, cliConfig);
    if (prompts.length === 0 && tools.length === 0) {
      throw new Error("No prompts or tools found on the server.");
    }
    updateMCPServerStatus(mcpServerName, MCPServerStatus.CONNECTED);
    for (const tool of tools) {
      toolRegistry.registerTool(tool);
    }
  } catch (error) {
    if (mcpClient) {
      mcpClient.close();
    }
    console.error(`Error connecting to MCP server '${mcpServerName}': ${getErrorMessage(error)}`);
    updateMCPServerStatus(mcpServerName, MCPServerStatus.DISCONNECTED);
  }
}
async function discoverTools(mcpServerName, mcpServerConfig, mcpClient, cliConfig) {
  try {
    const mcpCallableTool = mcpToTool(mcpClient, {
      timeout: mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC
    });
    const tool = await mcpCallableTool.tool();
    if (!Array.isArray(tool.functionDeclarations)) {
      return [];
    }
    const discoveredTools = [];
    for (const funcDecl of tool.functionDeclarations) {
      try {
        if (!isEnabled(funcDecl, mcpServerName, mcpServerConfig)) {
          continue;
        }
        discoveredTools.push(new DiscoveredMCPTool(mcpCallableTool, mcpServerName, funcDecl.name, funcDecl.description ?? "", funcDecl.parametersJsonSchema ?? { type: "object", properties: {} }, mcpServerConfig.trust, void 0, cliConfig));
      } catch (error) {
        console.error(`Error discovering tool: '${funcDecl.name}' from MCP server '${mcpServerName}': ${error.message}`);
      }
    }
    return discoveredTools;
  } catch (error) {
    if (error instanceof Error && !error.message?.includes("Method not found")) {
      console.error(`Error discovering tools from ${mcpServerName}: ${getErrorMessage(error)}`);
    }
    return [];
  }
}
async function discoverPrompts(mcpServerName, mcpClient, promptRegistry) {
  try {
    if (mcpClient.getServerCapabilities()?.prompts == null)
      return [];
    const response = await mcpClient.request({ method: "prompts/list", params: {} }, ListPromptsResultSchema);
    for (const prompt of response.prompts) {
      promptRegistry.registerPrompt({
        ...prompt,
        serverName: mcpServerName,
        invoke: /* @__PURE__ */ __name((params) => invokeMcpPrompt(mcpServerName, mcpClient, prompt.name, params), "invoke")
      });
    }
    return response.prompts;
  } catch (error) {
    if (error instanceof Error && !error.message?.includes("Method not found")) {
      console.error(`Error discovering prompts from ${mcpServerName}: ${getErrorMessage(error)}`);
    }
    return [];
  }
}
async function invokeMcpPrompt(mcpServerName, mcpClient, promptName, promptParams) {
  try {
    const response = await mcpClient.request({
      method: "prompts/get",
      params: {
        name: promptName,
        arguments: promptParams
      }
    }, GetPromptResultSchema);
    return response;
  } catch (error) {
    if (error instanceof Error && !error.message?.includes("Method not found")) {
      console.error(`Error invoking prompt '${promptName}' from ${mcpServerName} ${promptParams}: ${getErrorMessage(error)}`);
    }
    throw error;
  }
}
function hasNetworkTransport(config) {
  return !!(config.url || config.httpUrl);
}
async function connectToMcpServer(mcpServerName, mcpServerConfig, debugMode, workspaceContext) {
  const mcpClient = new Client({
    name: "qwen-code-mcp-client",
    version: "0.0.1"
  });
  mcpClient.registerCapabilities({
    roots: {
      listChanged: true
    }
  });
  mcpClient.setRequestHandler(ListRootsRequestSchema, async () => {
    const roots = [];
    for (const dir of workspaceContext.getDirectories()) {
      roots.push({
        uri: pathToFileURL(dir).toString(),
        name: basename8(dir)
      });
    }
    return {
      roots
    };
  });
  let unlistenDirectories = workspaceContext.onDirectoriesChanged(async () => {
    try {
      await mcpClient.notification({
        method: "notifications/roots/list_changed"
      });
    } catch (_) {
      unlistenDirectories?.();
      unlistenDirectories = void 0;
    }
  });
  const oldOnClose = mcpClient.onclose;
  mcpClient.onclose = () => {
    oldOnClose?.();
    unlistenDirectories?.();
    unlistenDirectories = void 0;
  };
  try {
    const transport = await createTransport(mcpServerName, mcpServerConfig, debugMode);
    try {
      await mcpClient.connect(transport, {
        timeout: mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC
      });
      return mcpClient;
    } catch (error) {
      await transport.close();
      throw error;
    }
  } catch (error) {
    const errorString = String(error);
    if (errorString.includes("401") && hasNetworkTransport(mcpServerConfig)) {
      mcpServerRequiresOAuth.set(mcpServerName, true);
      const shouldTriggerOAuth = mcpServerConfig.httpUrl || mcpServerConfig.oauth?.enabled;
      if (!shouldTriggerOAuth) {
        const tokenStorage = new MCPOAuthTokenStorage();
        const credentials = await tokenStorage.getCredentials(mcpServerName);
        if (credentials) {
          const authProvider = new MCPOAuthProvider(tokenStorage);
          const hasStoredTokens = await authProvider.getValidToken(mcpServerName, {
            // Pass client ID if available
            clientId: credentials.clientId
          });
          if (hasStoredTokens) {
            console.log(`Stored OAuth token for SSE server '${mcpServerName}' was rejected. Please re-authenticate using: /mcp auth ${mcpServerName}`);
          } else {
            console.log(`401 error received for SSE server '${mcpServerName}' without OAuth configuration. Please authenticate using: /mcp auth ${mcpServerName}`);
          }
        }
        throw new Error(`401 error received for SSE server '${mcpServerName}' without OAuth configuration. Please authenticate using: /mcp auth ${mcpServerName}`);
      }
      let wwwAuthenticate = extractWWWAuthenticateHeader(errorString);
      if (!wwwAuthenticate && hasNetworkTransport(mcpServerConfig)) {
        console.log(`No www-authenticate header in error, trying to fetch it from server...`);
        try {
          const urlToFetch = mcpServerConfig.httpUrl || mcpServerConfig.url;
          const response = await fetch(urlToFetch, {
            method: "HEAD",
            headers: {
              Accept: mcpServerConfig.httpUrl ? "application/json" : "text/event-stream"
            },
            signal: AbortSignal.timeout(5e3)
          });
          if (response.status === 401) {
            wwwAuthenticate = response.headers.get("www-authenticate");
            if (wwwAuthenticate) {
              console.log(`Found www-authenticate header from server: ${wwwAuthenticate}`);
            }
          }
        } catch (fetchError) {
          console.debug(`Failed to fetch www-authenticate header: ${getErrorMessage(fetchError)}`);
        }
      }
      if (wwwAuthenticate) {
        console.log(`Received 401 with www-authenticate header: ${wwwAuthenticate}`);
        const oauthSuccess = await handleAutomaticOAuth(mcpServerName, mcpServerConfig, wwwAuthenticate);
        if (oauthSuccess) {
          console.log(`Retrying connection to '${mcpServerName}' with OAuth token...`);
          const tokenStorage = new MCPOAuthTokenStorage();
          const credentials = await tokenStorage.getCredentials(mcpServerName);
          if (credentials) {
            const authProvider = new MCPOAuthProvider(tokenStorage);
            const accessToken = await authProvider.getValidToken(mcpServerName, {
              // Pass client ID if available
              clientId: credentials.clientId
            });
            if (accessToken) {
              const oauthTransport = await createTransportWithOAuth(mcpServerName, mcpServerConfig, accessToken);
              if (oauthTransport) {
                try {
                  await mcpClient.connect(oauthTransport, {
                    timeout: mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC
                  });
                  return mcpClient;
                } catch (retryError) {
                  console.error(`Failed to connect with OAuth token: ${getErrorMessage(retryError)}`);
                  throw retryError;
                }
              } else {
                console.error(`Failed to create OAuth transport for server '${mcpServerName}'`);
                throw new Error(`Failed to create OAuth transport for server '${mcpServerName}'`);
              }
            } else {
              console.error(`Failed to get OAuth token for server '${mcpServerName}'`);
              throw new Error(`Failed to get OAuth token for server '${mcpServerName}'`);
            }
          } else {
            console.error(`Failed to get credentials for server '${mcpServerName}' after successful OAuth authentication`);
            throw new Error(`Failed to get credentials for server '${mcpServerName}' after successful OAuth authentication`);
          }
        } else {
          console.error(`Failed to handle automatic OAuth for server '${mcpServerName}'`);
          throw new Error(`Failed to handle automatic OAuth for server '${mcpServerName}'`);
        }
      } else {
        const shouldTryDiscovery = mcpServerConfig.httpUrl || mcpServerConfig.oauth?.enabled;
        if (!shouldTryDiscovery) {
          const tokenStorage = new MCPOAuthTokenStorage();
          const credentials = await tokenStorage.getCredentials(mcpServerName);
          if (credentials) {
            const authProvider = new MCPOAuthProvider(tokenStorage);
            const hasStoredTokens = await authProvider.getValidToken(mcpServerName, {
              // Pass client ID if available
              clientId: credentials.clientId
            });
            if (hasStoredTokens) {
              console.log(`Stored OAuth token for SSE server '${mcpServerName}' was rejected. Please re-authenticate using: /mcp auth ${mcpServerName}`);
            } else {
              console.log(`401 error received for SSE server '${mcpServerName}' without OAuth configuration. Please authenticate using: /mcp auth ${mcpServerName}`);
            }
          }
          throw new Error(`401 error received for SSE server '${mcpServerName}' without OAuth configuration. Please authenticate using: /mcp auth ${mcpServerName}`);
        }
        console.log(`\u{1F50D} Attempting OAuth discovery for '${mcpServerName}'...`);
        if (hasNetworkTransport(mcpServerConfig)) {
          const serverUrl = new URL(mcpServerConfig.httpUrl || mcpServerConfig.url);
          const baseUrl = `${serverUrl.protocol}//${serverUrl.host}`;
          try {
            const oauthConfig = await OAuthUtils.discoverOAuthConfig(baseUrl);
            if (oauthConfig) {
              console.log(`Discovered OAuth configuration from base URL for server '${mcpServerName}'`);
              const oauthAuthConfig = {
                enabled: true,
                authorizationUrl: oauthConfig.authorizationUrl,
                tokenUrl: oauthConfig.tokenUrl,
                scopes: oauthConfig.scopes || []
              };
              const authServerUrl = mcpServerConfig.httpUrl || mcpServerConfig.url;
              console.log(`Starting OAuth authentication for server '${mcpServerName}'...`);
              const authProvider = new MCPOAuthProvider(new MCPOAuthTokenStorage());
              await authProvider.authenticate(mcpServerName, oauthAuthConfig, authServerUrl);
              const tokenStorage = new MCPOAuthTokenStorage();
              const credentials = await tokenStorage.getCredentials(mcpServerName);
              if (credentials) {
                const authProvider2 = new MCPOAuthProvider(tokenStorage);
                const accessToken = await authProvider2.getValidToken(mcpServerName, {
                  // Pass client ID if available
                  clientId: credentials.clientId
                });
                if (accessToken) {
                  const oauthTransport = await createTransportWithOAuth(mcpServerName, mcpServerConfig, accessToken);
                  if (oauthTransport) {
                    try {
                      await mcpClient.connect(oauthTransport, {
                        timeout: mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC
                      });
                      return mcpClient;
                    } catch (retryError) {
                      console.error(`Failed to connect with OAuth token: ${getErrorMessage(retryError)}`);
                      throw retryError;
                    }
                  } else {
                    console.error(`Failed to create OAuth transport for server '${mcpServerName}'`);
                    throw new Error(`Failed to create OAuth transport for server '${mcpServerName}'`);
                  }
                } else {
                  console.error(`Failed to get OAuth token for server '${mcpServerName}'`);
                  throw new Error(`Failed to get OAuth token for server '${mcpServerName}'`);
                }
              } else {
                console.error(`Failed to get stored credentials for server '${mcpServerName}'`);
                throw new Error(`Failed to get stored credentials for server '${mcpServerName}'`);
              }
            } else {
              console.error(`\u274C Could not configure OAuth for '${mcpServerName}' - please authenticate manually with /mcp auth ${mcpServerName}`);
              throw new Error(`OAuth configuration failed for '${mcpServerName}'. Please authenticate manually with /mcp auth ${mcpServerName}`);
            }
          } catch (discoveryError) {
            console.error(`\u274C OAuth discovery failed for '${mcpServerName}' - please authenticate manually with /mcp auth ${mcpServerName}`);
            throw discoveryError;
          }
        } else {
          console.error(`\u274C '${mcpServerName}' requires authentication but no OAuth configuration found`);
          throw new Error(`MCP server '${mcpServerName}' requires authentication. Please configure OAuth or check server settings.`);
        }
      }
    } else {
      const errorMessage = error.message || String(error);
      const isNetworkError = errorMessage.includes("ENOTFOUND") || errorMessage.includes("ECONNREFUSED");
      let conciseError;
      if (isNetworkError) {
        conciseError = `Cannot connect to '${mcpServerName}' - server may be down or URL incorrect`;
      } else {
        conciseError = `Connection failed for '${mcpServerName}': ${errorMessage}`;
      }
      if (process.env["SANDBOX"]) {
        conciseError += ` (check sandbox availability)`;
      }
      throw new Error(conciseError);
    }
  }
}
async function createTransport(mcpServerName, mcpServerConfig, debugMode) {
  if (mcpServerConfig.authProviderType === AuthProviderType.SERVICE_ACCOUNT_IMPERSONATION) {
    const provider = new ServiceAccountImpersonationProvider(mcpServerConfig);
    const transportOptions = {
      authProvider: provider
    };
    if (mcpServerConfig.httpUrl) {
      return new StreamableHTTPClientTransport(new URL(mcpServerConfig.httpUrl), transportOptions);
    } else if (mcpServerConfig.url) {
      return new SSEClientTransport(new URL(mcpServerConfig.url), transportOptions);
    }
    throw new Error("No URL configured for ServiceAccountImpersonation MCP Server");
  }
  if (mcpServerConfig.authProviderType === AuthProviderType.GOOGLE_CREDENTIALS) {
    const provider = new GoogleCredentialProvider(mcpServerConfig);
    const transportOptions = {
      authProvider: provider
    };
    if (mcpServerConfig.httpUrl) {
      return new StreamableHTTPClientTransport(new URL(mcpServerConfig.httpUrl), transportOptions);
    } else if (mcpServerConfig.url) {
      return new SSEClientTransport(new URL(mcpServerConfig.url), transportOptions);
    }
    throw new Error("No URL configured for Google Credentials MCP server");
  }
  let accessToken = null;
  let hasOAuthConfig = mcpServerConfig.oauth?.enabled;
  if (hasOAuthConfig && mcpServerConfig.oauth) {
    const tokenStorage = new MCPOAuthTokenStorage();
    const authProvider = new MCPOAuthProvider(tokenStorage);
    accessToken = await authProvider.getValidToken(mcpServerName, mcpServerConfig.oauth);
    if (!accessToken) {
      console.error(`MCP server '${mcpServerName}' requires OAuth authentication. Please authenticate using the /mcp auth command.`);
      throw new Error(`MCP server '${mcpServerName}' requires OAuth authentication. Please authenticate using the /mcp auth command.`);
    }
  } else {
    const tokenStorage = new MCPOAuthTokenStorage();
    const credentials = await tokenStorage.getCredentials(mcpServerName);
    if (credentials) {
      const authProvider = new MCPOAuthProvider(tokenStorage);
      accessToken = await authProvider.getValidToken(mcpServerName, {
        // Pass client ID if available
        clientId: credentials.clientId
      });
      if (accessToken) {
        hasOAuthConfig = true;
        console.log(`Found stored OAuth token for server '${mcpServerName}'`);
      }
    }
  }
  if (mcpServerConfig.httpUrl) {
    const transportOptions = {};
    if (hasOAuthConfig && accessToken) {
      transportOptions.requestInit = {
        headers: {
          ...mcpServerConfig.headers,
          Authorization: `Bearer ${accessToken}`
        }
      };
    } else if (mcpServerConfig.headers) {
      transportOptions.requestInit = {
        headers: mcpServerConfig.headers
      };
    }
    return new StreamableHTTPClientTransport(new URL(mcpServerConfig.httpUrl), transportOptions);
  }
  if (mcpServerConfig.url) {
    const transportOptions = {};
    if (hasOAuthConfig && accessToken) {
      transportOptions.requestInit = {
        headers: {
          ...mcpServerConfig.headers,
          Authorization: `Bearer ${accessToken}`
        }
      };
    } else if (mcpServerConfig.headers) {
      transportOptions.requestInit = {
        headers: mcpServerConfig.headers
      };
    }
    return new SSEClientTransport(new URL(mcpServerConfig.url), transportOptions);
  }
  if (mcpServerConfig.command) {
    const transport = new StdioClientTransport({
      command: mcpServerConfig.command,
      args: mcpServerConfig.args || [],
      env: {
        ...process.env,
        ...mcpServerConfig.env || {}
      },
      cwd: mcpServerConfig.cwd,
      stderr: "pipe"
    });
    if (debugMode) {
      transport.stderr.on("data", (data) => {
        const stderrStr = data.toString().trim();
        console.debug(`[DEBUG] [MCP STDERR (${mcpServerName})]: `, stderrStr);
      });
    }
    return transport;
  }
  throw new Error(`Invalid configuration: missing httpUrl (for Streamable HTTP), url (for SSE), and command (for stdio).`);
}
function isEnabled(funcDecl, mcpServerName, mcpServerConfig) {
  if (!funcDecl.name) {
    console.warn(`Discovered a function declaration without a name from MCP server '${mcpServerName}'. Skipping.`);
    return false;
  }
  const { includeTools, excludeTools } = mcpServerConfig;
  if (excludeTools && excludeTools.includes(funcDecl.name)) {
    return false;
  }
  return !includeTools || includeTools.some((tool) => tool === funcDecl.name || tool.startsWith(`${funcDecl.name}(`));
}
var import_shell_quote3, MCP_DEFAULT_TIMEOUT_MSEC, MCPServerStatus, MCPDiscoveryState, McpClient, serverStatuses, mcpDiscoveryState, mcpServerRequiresOAuth, statusChangeListeners;
var init_mcp_client = __esm({
  "packages/core/dist/src/tools/mcp-client.js"() {
    "use strict";
    init_esbuild_shims();
    init_client3();
    init_sse();
    init_stdio2();
    init_streamableHttp();
    init_types9();
    import_shell_quote3 = __toESM(require_shell_quote(), 1);
    init_config3();
    init_google_auth_provider();
    init_sa_impersonation_provider();
    init_mcp_tool();
    init_node();
    init_oauth_provider();
    init_oauth_token_storage();
    init_oauth_utils();
    init_errors();
    MCP_DEFAULT_TIMEOUT_MSEC = 10 * 60 * 1e3;
    (function(MCPServerStatus2) {
      MCPServerStatus2["DISCONNECTED"] = "disconnected";
      MCPServerStatus2["CONNECTING"] = "connecting";
      MCPServerStatus2["CONNECTED"] = "connected";
    })(MCPServerStatus || (MCPServerStatus = {}));
    (function(MCPDiscoveryState2) {
      MCPDiscoveryState2["NOT_STARTED"] = "not_started";
      MCPDiscoveryState2["IN_PROGRESS"] = "in_progress";
      MCPDiscoveryState2["COMPLETED"] = "completed";
    })(MCPDiscoveryState || (MCPDiscoveryState = {}));
    McpClient = class {
      static {
        __name(this, "McpClient");
      }
      serverName;
      serverConfig;
      toolRegistry;
      promptRegistry;
      workspaceContext;
      debugMode;
      client;
      transport;
      status = MCPServerStatus.DISCONNECTED;
      isDisconnecting = false;
      constructor(serverName, serverConfig, toolRegistry, promptRegistry, workspaceContext, debugMode) {
        this.serverName = serverName;
        this.serverConfig = serverConfig;
        this.toolRegistry = toolRegistry;
        this.promptRegistry = promptRegistry;
        this.workspaceContext = workspaceContext;
        this.debugMode = debugMode;
        this.client = new Client({
          name: `qwen-cli-mcp-client-${this.serverName}`,
          version: "0.0.1"
        });
      }
      /**
       * Connects to the MCP server.
       */
      async connect() {
        this.isDisconnecting = false;
        this.updateStatus(MCPServerStatus.CONNECTING);
        try {
          this.transport = await this.createTransport();
          this.client.onerror = (error) => {
            if (this.isDisconnecting) {
              return;
            }
            console.error(`MCP ERROR (${this.serverName}):`, error.toString());
            this.updateStatus(MCPServerStatus.DISCONNECTED);
          };
          this.client.registerCapabilities({
            roots: {}
          });
          this.client.setRequestHandler(ListRootsRequestSchema, async () => {
            const roots = [];
            for (const dir of this.workspaceContext.getDirectories()) {
              roots.push({
                uri: pathToFileURL(dir).toString(),
                name: basename8(dir)
              });
            }
            return {
              roots
            };
          });
          await this.client.connect(this.transport, {
            timeout: this.serverConfig.timeout
          });
          this.updateStatus(MCPServerStatus.CONNECTED);
        } catch (error) {
          this.updateStatus(MCPServerStatus.DISCONNECTED);
          throw error;
        }
      }
      /**
       * Discovers tools and prompts from the MCP server.
       */
      async discover(cliConfig) {
        if (this.status !== MCPServerStatus.CONNECTED) {
          throw new Error("Client is not connected.");
        }
        const prompts = await this.discoverPrompts();
        const tools = await this.discoverTools(cliConfig);
        if (prompts.length === 0 && tools.length === 0) {
          throw new Error("No prompts or tools found on the server.");
        }
        for (const tool of tools) {
          this.toolRegistry.registerTool(tool);
        }
      }
      /**
       * Disconnects from the MCP server.
       */
      async disconnect() {
        this.isDisconnecting = true;
        if (this.transport) {
          await this.transport.close();
        }
        this.client.close();
        this.updateStatus(MCPServerStatus.DISCONNECTED);
      }
      /**
       * Returns the current status of the client.
       */
      getStatus() {
        return this.status;
      }
      updateStatus(status) {
        this.status = status;
        updateMCPServerStatus(this.serverName, status);
      }
      async createTransport() {
        return createTransport(this.serverName, this.serverConfig, this.debugMode);
      }
      async discoverTools(cliConfig) {
        return discoverTools(this.serverName, this.serverConfig, this.client, cliConfig);
      }
      async discoverPrompts() {
        return discoverPrompts(this.serverName, this.client, this.promptRegistry);
      }
    };
    serverStatuses = /* @__PURE__ */ new Map();
    mcpDiscoveryState = MCPDiscoveryState.NOT_STARTED;
    mcpServerRequiresOAuth = /* @__PURE__ */ new Map();
    statusChangeListeners = [];
    __name(updateMCPServerStatus, "updateMCPServerStatus");
    __name(getMCPServerStatus, "getMCPServerStatus");
    __name(getMCPDiscoveryState, "getMCPDiscoveryState");
    __name(extractWWWAuthenticateHeader, "extractWWWAuthenticateHeader");
    __name(handleAutomaticOAuth, "handleAutomaticOAuth");
    __name(createTransportWithOAuth, "createTransportWithOAuth");
    __name(populateMcpServerCommand, "populateMcpServerCommand");
    __name(connectAndDiscover, "connectAndDiscover");
    __name(discoverTools, "discoverTools");
    __name(discoverPrompts, "discoverPrompts");
    __name(invokeMcpPrompt, "invokeMcpPrompt");
    __name(hasNetworkTransport, "hasNetworkTransport");
    __name(connectToMcpServer, "connectToMcpServer");
    __name(createTransport, "createTransport");
    __name(isEnabled, "isEnabled");
  }
});

// packages/core/dist/src/tools/mcp-client-manager.js
var McpClientManager;
var init_mcp_client_manager = __esm({
  "packages/core/dist/src/tools/mcp-client-manager.js"() {
    "use strict";
    init_esbuild_shims();
    init_mcp_client();
    init_errors();
    McpClientManager = class {
      static {
        __name(this, "McpClientManager");
      }
      clients = /* @__PURE__ */ new Map();
      mcpServers;
      mcpServerCommand;
      toolRegistry;
      promptRegistry;
      debugMode;
      workspaceContext;
      discoveryState = MCPDiscoveryState.NOT_STARTED;
      eventEmitter;
      constructor(mcpServers, mcpServerCommand, toolRegistry, promptRegistry, debugMode, workspaceContext, eventEmitter) {
        this.mcpServers = mcpServers;
        this.mcpServerCommand = mcpServerCommand;
        this.toolRegistry = toolRegistry;
        this.promptRegistry = promptRegistry;
        this.debugMode = debugMode;
        this.workspaceContext = workspaceContext;
        this.eventEmitter = eventEmitter;
      }
      /**
       * Initiates the tool discovery process for all configured MCP servers.
       * It connects to each server, discovers its available tools, and registers
       * them with the `ToolRegistry`.
       */
      async discoverAllMcpTools(cliConfig) {
        if (!cliConfig.isTrustedFolder()) {
          return;
        }
        await this.stop();
        const servers = populateMcpServerCommand(this.mcpServers, this.mcpServerCommand);
        this.discoveryState = MCPDiscoveryState.IN_PROGRESS;
        this.eventEmitter?.emit("mcp-client-update", this.clients);
        const discoveryPromises = Object.entries(servers).map(async ([name3, config]) => {
          const client = new McpClient(name3, config, this.toolRegistry, this.promptRegistry, this.workspaceContext, this.debugMode);
          this.clients.set(name3, client);
          this.eventEmitter?.emit("mcp-client-update", this.clients);
          try {
            await client.connect();
            await client.discover(cliConfig);
            this.eventEmitter?.emit("mcp-client-update", this.clients);
          } catch (error) {
            this.eventEmitter?.emit("mcp-client-update", this.clients);
            console.error(`Error during discovery for server '${name3}': ${getErrorMessage(error)}`);
          }
        });
        await Promise.all(discoveryPromises);
        this.discoveryState = MCPDiscoveryState.COMPLETED;
      }
      /**
       * Stops all running local MCP servers and closes all client connections.
       * This is the cleanup method to be called on application exit.
       */
      async stop() {
        const disconnectionPromises = Array.from(this.clients.entries()).map(async ([name3, client]) => {
          try {
            await client.disconnect();
          } catch (error) {
            console.error(`Error stopping client '${name3}': ${getErrorMessage(error)}`);
          }
        });
        await Promise.all(disconnectionPromises);
        this.clients.clear();
      }
      getDiscoveryState() {
        return this.discoveryState;
      }
    };
  }
});

// packages/core/dist/src/tools/tool-registry.js
import { spawn as spawn5 } from "node:child_process";
import { StringDecoder as StringDecoder2 } from "node:string_decoder";
var import_shell_quote4, DiscoveredToolInvocation, DiscoveredTool, ToolRegistry;
var init_tool_registry = __esm({
  "packages/core/dist/src/tools/tool-registry.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    init_mcp_client();
    init_mcp_client_manager();
    init_mcp_tool();
    import_shell_quote4 = __toESM(require_shell_quote(), 1);
    init_tool_error();
    init_safeJsonStringify();
    DiscoveredToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "DiscoveredToolInvocation");
      }
      config;
      toolName;
      constructor(config, toolName, params) {
        super(params);
        this.config = config;
        this.toolName = toolName;
      }
      getDescription() {
        return safeJsonStringify(this.params);
      }
      async execute(_signal, _updateOutput) {
        const callCommand = this.config.getToolCallCommand();
        const child = spawn5(callCommand, [this.toolName]);
        child.stdin.write(JSON.stringify(this.params));
        child.stdin.end();
        let stdout = "";
        let stderr = "";
        let error = null;
        let code2 = null;
        let signal = null;
        await new Promise((resolve24) => {
          const onStdout = /* @__PURE__ */ __name((data) => {
            stdout += data?.toString();
          }, "onStdout");
          const onStderr = /* @__PURE__ */ __name((data) => {
            stderr += data?.toString();
          }, "onStderr");
          const onError2 = /* @__PURE__ */ __name((err) => {
            error = err;
          }, "onError");
          const onClose = /* @__PURE__ */ __name((_code, _signal2) => {
            code2 = _code;
            signal = _signal2;
            cleanup();
            resolve24();
          }, "onClose");
          const cleanup = /* @__PURE__ */ __name(() => {
            child.stdout.removeListener("data", onStdout);
            child.stderr.removeListener("data", onStderr);
            child.removeListener("error", onError2);
            child.removeListener("close", onClose);
            if (child.connected) {
              child.disconnect();
            }
          }, "cleanup");
          child.stdout.on("data", onStdout);
          child.stderr.on("data", onStderr);
          child.on("error", onError2);
          child.on("close", onClose);
        });
        if (error || code2 !== 0 || signal || stderr) {
          const llmContent = [
            `Stdout: ${stdout || "(empty)"}`,
            `Stderr: ${stderr || "(empty)"}`,
            `Error: ${error ?? "(none)"}`,
            `Exit Code: ${code2 ?? "(none)"}`,
            `Signal: ${signal ?? "(none)"}`
          ].join("\n");
          return {
            llmContent,
            returnDisplay: llmContent,
            error: {
              message: llmContent,
              type: ToolErrorType.DISCOVERED_TOOL_EXECUTION_ERROR
            }
          };
        }
        return {
          llmContent: stdout,
          returnDisplay: stdout
        };
      }
    };
    DiscoveredTool = class extends BaseDeclarativeTool {
      static {
        __name(this, "DiscoveredTool");
      }
      config;
      description;
      parameterSchema;
      constructor(config, name3, description, parameterSchema) {
        const discoveryCmd = config.getToolDiscoveryCommand();
        const callCommand = config.getToolCallCommand();
        description += `

This tool was discovered from the project by executing the command \`${discoveryCmd}\` on project root.
When called, this tool will execute the command \`${callCommand} ${name3}\` on project root.
Tool discovery and call commands can be configured in project or user settings.

When called, the tool call command is executed as a subprocess.
On success, tool output is returned as a json string.
Otherwise, the following information is returned:

Stdout: Output on stdout stream. Can be \`(empty)\` or partial.
Stderr: Output on stderr stream. Can be \`(empty)\` or partial.
Error: Error or \`(none)\` if no error was reported for the subprocess.
Exit Code: Exit code or \`(none)\` if terminated by signal.
Signal: Signal number or \`(none)\` if no signal was received.
`;
        super(
          name3,
          name3,
          description,
          Kind.Other,
          parameterSchema,
          false,
          // isOutputMarkdown
          false
        );
        this.config = config;
        this.description = description;
        this.parameterSchema = parameterSchema;
      }
      createInvocation(params) {
        return new DiscoveredToolInvocation(this.config, this.name, params);
      }
    };
    ToolRegistry = class {
      static {
        __name(this, "ToolRegistry");
      }
      // The tools keyed by tool name as seen by the LLM.
      tools = /* @__PURE__ */ new Map();
      config;
      mcpClientManager;
      constructor(config, eventEmitter) {
        this.config = config;
        this.mcpClientManager = new McpClientManager(this.config.getMcpServers() ?? {}, this.config.getMcpServerCommand(), this, this.config.getPromptRegistry(), this.config.getDebugMode(), this.config.getWorkspaceContext(), eventEmitter);
      }
      /**
       * Registers a tool definition.
       * @param tool - The tool object containing schema and execution logic.
       */
      registerTool(tool) {
        if (this.tools.has(tool.name)) {
          if (tool instanceof DiscoveredMCPTool) {
            tool = tool.asFullyQualifiedTool();
          } else {
            console.warn(`Tool with name "${tool.name}" is already registered. Overwriting.`);
          }
        }
        this.tools.set(tool.name, tool);
      }
      removeDiscoveredTools() {
        for (const tool of this.tools.values()) {
          if (tool instanceof DiscoveredTool || tool instanceof DiscoveredMCPTool) {
            this.tools.delete(tool.name);
          }
        }
      }
      /**
       * Removes all tools from a specific MCP server.
       * @param serverName The name of the server to remove tools from.
       */
      removeMcpToolsByServer(serverName) {
        for (const [name3, tool] of this.tools.entries()) {
          if (tool instanceof DiscoveredMCPTool && tool.serverName === serverName) {
            this.tools.delete(name3);
          }
        }
      }
      /**
       * Discovers tools from project (if available and configured).
       * Can be called multiple times to update discovered tools.
       * This will discover tools from the command line and from MCP servers.
       */
      async discoverAllTools() {
        this.removeDiscoveredTools();
        this.config.getPromptRegistry().clear();
        await this.discoverAndRegisterToolsFromCommand();
        await this.mcpClientManager.discoverAllMcpTools(this.config);
      }
      /**
       * Discovers tools from project (if available and configured).
       * Can be called multiple times to update discovered tools.
       * This will NOT discover tools from the command line, only from MCP servers.
       */
      async discoverMcpTools() {
        this.removeDiscoveredTools();
        this.config.getPromptRegistry().clear();
        await this.mcpClientManager.discoverAllMcpTools(this.config);
      }
      /**
       * Restarts all MCP servers and re-discovers tools.
       */
      async restartMcpServers() {
        await this.discoverMcpTools();
      }
      /**
       * Discover or re-discover tools for a single MCP server.
       * @param serverName - The name of the server to discover tools from.
       */
      async discoverToolsForServer(serverName) {
        for (const [name3, tool] of this.tools.entries()) {
          if (tool instanceof DiscoveredMCPTool && tool.serverName === serverName) {
            this.tools.delete(name3);
          }
        }
        this.config.getPromptRegistry().removePromptsByServer(serverName);
        const mcpServers = this.config.getMcpServers() ?? {};
        const serverConfig = mcpServers[serverName];
        if (serverConfig) {
          await connectAndDiscover(serverName, serverConfig, this, this.config.getPromptRegistry(), this.config.getDebugMode(), this.config.getWorkspaceContext(), this.config);
        }
      }
      async discoverAndRegisterToolsFromCommand() {
        const discoveryCmd = this.config.getToolDiscoveryCommand();
        if (!discoveryCmd) {
          return;
        }
        try {
          const cmdParts = (0, import_shell_quote4.parse)(discoveryCmd);
          if (cmdParts.length === 0) {
            throw new Error("Tool discovery command is empty or contains only whitespace.");
          }
          const proc2 = spawn5(cmdParts[0], cmdParts.slice(1));
          let stdout = "";
          const stdoutDecoder = new StringDecoder2("utf8");
          let stderr = "";
          const stderrDecoder = new StringDecoder2("utf8");
          let sizeLimitExceeded = false;
          const MAX_STDOUT_SIZE = 10 * 1024 * 1024;
          const MAX_STDERR_SIZE = 10 * 1024 * 1024;
          let stdoutByteLength = 0;
          let stderrByteLength = 0;
          proc2.stdout.on("data", (data) => {
            if (sizeLimitExceeded)
              return;
            if (stdoutByteLength + data.length > MAX_STDOUT_SIZE) {
              sizeLimitExceeded = true;
              proc2.kill();
              return;
            }
            stdoutByteLength += data.length;
            stdout += stdoutDecoder.write(data);
          });
          proc2.stderr.on("data", (data) => {
            if (sizeLimitExceeded)
              return;
            if (stderrByteLength + data.length > MAX_STDERR_SIZE) {
              sizeLimitExceeded = true;
              proc2.kill();
              return;
            }
            stderrByteLength += data.length;
            stderr += stderrDecoder.write(data);
          });
          await new Promise((resolve24, reject) => {
            proc2.on("error", reject);
            proc2.on("close", (code2) => {
              stdout += stdoutDecoder.end();
              stderr += stderrDecoder.end();
              if (sizeLimitExceeded) {
                return reject(new Error(`Tool discovery command output exceeded size limit of ${MAX_STDOUT_SIZE} bytes.`));
              }
              if (code2 !== 0) {
                console.error(`Command failed with code ${code2}`);
                console.error(stderr);
                return reject(new Error(`Tool discovery command failed with exit code ${code2}`));
              }
              resolve24();
            });
          });
          const functions = [];
          const discoveredItems = JSON.parse(stdout.trim());
          if (!discoveredItems || !Array.isArray(discoveredItems)) {
            throw new Error("Tool discovery command did not return a JSON array of tools.");
          }
          for (const tool of discoveredItems) {
            if (tool && typeof tool === "object") {
              if (Array.isArray(tool["function_declarations"])) {
                functions.push(...tool["function_declarations"]);
              } else if (Array.isArray(tool["functionDeclarations"])) {
                functions.push(...tool["functionDeclarations"]);
              } else if (tool["name"]) {
                functions.push(tool);
              }
            }
          }
          for (const func of functions) {
            if (!func.name) {
              console.warn("Discovered a tool with no name. Skipping.");
              continue;
            }
            const parameters = func.parametersJsonSchema && typeof func.parametersJsonSchema === "object" && !Array.isArray(func.parametersJsonSchema) ? func.parametersJsonSchema : {};
            this.registerTool(new DiscoveredTool(this.config, func.name, func.description ?? "", parameters));
          }
        } catch (e2) {
          console.error(`Tool discovery command "${discoveryCmd}" failed:`, e2);
          throw e2;
        }
      }
      /**
       * Retrieves the list of tool schemas (FunctionDeclaration array).
       * Extracts the declarations from the ToolListUnion structure.
       * Includes discovered (vs registered) tools if configured.
       * @returns An array of FunctionDeclarations.
       */
      getFunctionDeclarations() {
        const declarations = [];
        this.tools.forEach((tool) => {
          declarations.push(tool.schema);
        });
        return declarations;
      }
      /**
       * Retrieves a filtered list of tool schemas based on a list of tool names.
       * @param toolNames - An array of tool names to include.
       * @returns An array of FunctionDeclarations for the specified tools.
       */
      getFunctionDeclarationsFiltered(toolNames) {
        const declarations = [];
        for (const name3 of toolNames) {
          const tool = this.tools.get(name3);
          if (tool) {
            declarations.push(tool.schema);
          }
        }
        return declarations;
      }
      /**
       * Returns an array of all registered and discovered tool names.
       */
      getAllToolNames() {
        return Array.from(this.tools.keys());
      }
      /**
       * Returns an array of all registered and discovered tool instances.
       */
      getAllTools() {
        return Array.from(this.tools.values()).sort((a, b) => a.displayName.localeCompare(b.displayName));
      }
      /**
       * Returns an array of tools registered from a specific MCP server.
       */
      getToolsByServer(serverName) {
        const serverTools = [];
        for (const tool of this.tools.values()) {
          if (tool?.serverName === serverName) {
            serverTools.push(tool);
          }
        }
        return serverTools.sort((a, b) => a.name.localeCompare(b.name));
      }
      /**
       * Get the definition of a specific tool.
       */
      getTool(name3) {
        return this.tools.get(name3);
      }
    };
  }
});

// node_modules/domelementtype/lib/esm/index.js
function isTag(elem) {
  return elem.type === ElementType.Tag || elem.type === ElementType.Script || elem.type === ElementType.Style;
}
var ElementType, Root, Text2, Directive, Comment, Script, Style, Tag, CDATA, Doctype;
var init_esm11 = __esm({
  "node_modules/domelementtype/lib/esm/index.js"() {
    init_esbuild_shims();
    (function(ElementType2) {
      ElementType2["Root"] = "root";
      ElementType2["Text"] = "text";
      ElementType2["Directive"] = "directive";
      ElementType2["Comment"] = "comment";
      ElementType2["Script"] = "script";
      ElementType2["Style"] = "style";
      ElementType2["Tag"] = "tag";
      ElementType2["CDATA"] = "cdata";
      ElementType2["Doctype"] = "doctype";
    })(ElementType || (ElementType = {}));
    __name(isTag, "isTag");
    Root = ElementType.Root;
    Text2 = ElementType.Text;
    Directive = ElementType.Directive;
    Comment = ElementType.Comment;
    Script = ElementType.Script;
    Style = ElementType.Style;
    Tag = ElementType.Tag;
    CDATA = ElementType.CDATA;
    Doctype = ElementType.Doctype;
  }
});

// node_modules/domhandler/lib/esm/node.js
function isTag2(node) {
  return isTag(node);
}
function isCDATA(node) {
  return node.type === ElementType.CDATA;
}
function isText(node) {
  return node.type === ElementType.Text;
}
function isComment(node) {
  return node.type === ElementType.Comment;
}
function isDirective(node) {
  return node.type === ElementType.Directive;
}
function isDocument(node) {
  return node.type === ElementType.Root;
}
function cloneNode(node, recursive = false) {
  let result;
  if (isText(node)) {
    result = new Text3(node.data);
  } else if (isComment(node)) {
    result = new Comment2(node.data);
  } else if (isTag2(node)) {
    const children = recursive ? cloneChildren(node.children) : [];
    const clone = new Element(node.name, { ...node.attribs }, children);
    children.forEach((child) => child.parent = clone);
    if (node.namespace != null) {
      clone.namespace = node.namespace;
    }
    if (node["x-attribsNamespace"]) {
      clone["x-attribsNamespace"] = { ...node["x-attribsNamespace"] };
    }
    if (node["x-attribsPrefix"]) {
      clone["x-attribsPrefix"] = { ...node["x-attribsPrefix"] };
    }
    result = clone;
  } else if (isCDATA(node)) {
    const children = recursive ? cloneChildren(node.children) : [];
    const clone = new CDATA2(children);
    children.forEach((child) => child.parent = clone);
    result = clone;
  } else if (isDocument(node)) {
    const children = recursive ? cloneChildren(node.children) : [];
    const clone = new Document(children);
    children.forEach((child) => child.parent = clone);
    if (node["x-mode"]) {
      clone["x-mode"] = node["x-mode"];
    }
    result = clone;
  } else if (isDirective(node)) {
    const instruction = new ProcessingInstruction(node.name, node.data);
    if (node["x-name"] != null) {
      instruction["x-name"] = node["x-name"];
      instruction["x-publicId"] = node["x-publicId"];
      instruction["x-systemId"] = node["x-systemId"];
    }
    result = instruction;
  } else {
    throw new Error(`Not implemented yet: ${node.type}`);
  }
  result.startIndex = node.startIndex;
  result.endIndex = node.endIndex;
  if (node.sourceCodeLocation != null) {
    result.sourceCodeLocation = node.sourceCodeLocation;
  }
  return result;
}
function cloneChildren(childs) {
  const children = childs.map((child) => cloneNode(child, true));
  for (let i = 1; i < children.length; i++) {
    children[i].prev = children[i - 1];
    children[i - 1].next = children[i];
  }
  return children;
}
var Node2, DataNode, Text3, Comment2, ProcessingInstruction, NodeWithChildren, CDATA2, Document, Element;
var init_node3 = __esm({
  "node_modules/domhandler/lib/esm/node.js"() {
    init_esbuild_shims();
    init_esm11();
    Node2 = class {
      static {
        __name(this, "Node");
      }
      constructor() {
        this.parent = null;
        this.prev = null;
        this.next = null;
        this.startIndex = null;
        this.endIndex = null;
      }
      // Read-write aliases for properties
      /**
       * Same as {@link parent}.
       * [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
       */
      get parentNode() {
        return this.parent;
      }
      set parentNode(parent) {
        this.parent = parent;
      }
      /**
       * Same as {@link prev}.
       * [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
       */
      get previousSibling() {
        return this.prev;
      }
      set previousSibling(prev) {
        this.prev = prev;
      }
      /**
       * Same as {@link next}.
       * [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
       */
      get nextSibling() {
        return this.next;
      }
      set nextSibling(next) {
        this.next = next;
      }
      /**
       * Clone this node, and optionally its children.
       *
       * @param recursive Clone child nodes as well.
       * @returns A clone of the node.
       */
      cloneNode(recursive = false) {
        return cloneNode(this, recursive);
      }
    };
    DataNode = class extends Node2 {
      static {
        __name(this, "DataNode");
      }
      /**
       * @param data The content of the data node
       */
      constructor(data) {
        super();
        this.data = data;
      }
      /**
       * Same as {@link data}.
       * [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
       */
      get nodeValue() {
        return this.data;
      }
      set nodeValue(data) {
        this.data = data;
      }
    };
    Text3 = class extends DataNode {
      static {
        __name(this, "Text");
      }
      constructor() {
        super(...arguments);
        this.type = ElementType.Text;
      }
      get nodeType() {
        return 3;
      }
    };
    Comment2 = class extends DataNode {
      static {
        __name(this, "Comment");
      }
      constructor() {
        super(...arguments);
        this.type = ElementType.Comment;
      }
      get nodeType() {
        return 8;
      }
    };
    ProcessingInstruction = class extends DataNode {
      static {
        __name(this, "ProcessingInstruction");
      }
      constructor(name3, data) {
        super(data);
        this.name = name3;
        this.type = ElementType.Directive;
      }
      get nodeType() {
        return 1;
      }
    };
    NodeWithChildren = class extends Node2 {
      static {
        __name(this, "NodeWithChildren");
      }
      /**
       * @param children Children of the node. Only certain node types can have children.
       */
      constructor(children) {
        super();
        this.children = children;
      }
      // Aliases
      /** First child of the node. */
      get firstChild() {
        var _a6;
        return (_a6 = this.children[0]) !== null && _a6 !== void 0 ? _a6 : null;
      }
      /** Last child of the node. */
      get lastChild() {
        return this.children.length > 0 ? this.children[this.children.length - 1] : null;
      }
      /**
       * Same as {@link children}.
       * [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
       */
      get childNodes() {
        return this.children;
      }
      set childNodes(children) {
        this.children = children;
      }
    };
    CDATA2 = class extends NodeWithChildren {
      static {
        __name(this, "CDATA");
      }
      constructor() {
        super(...arguments);
        this.type = ElementType.CDATA;
      }
      get nodeType() {
        return 4;
      }
    };
    Document = class extends NodeWithChildren {
      static {
        __name(this, "Document");
      }
      constructor() {
        super(...arguments);
        this.type = ElementType.Root;
      }
      get nodeType() {
        return 9;
      }
    };
    Element = class extends NodeWithChildren {
      static {
        __name(this, "Element");
      }
      /**
       * @param name Name of the tag, eg. `div`, `span`.
       * @param attribs Object mapping attribute names to attribute values.
       * @param children Children of the node.
       */
      constructor(name3, attribs, children = [], type = name3 === "script" ? ElementType.Script : name3 === "style" ? ElementType.Style : ElementType.Tag) {
        super(children);
        this.name = name3;
        this.attribs = attribs;
        this.type = type;
      }
      get nodeType() {
        return 1;
      }
      // DOM Level 1 aliases
      /**
       * Same as {@link name}.
       * [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
       */
      get tagName() {
        return this.name;
      }
      set tagName(name3) {
        this.name = name3;
      }
      get attributes() {
        return Object.keys(this.attribs).map((name3) => {
          var _a6, _b2;
          return {
            name: name3,
            value: this.attribs[name3],
            namespace: (_a6 = this["x-attribsNamespace"]) === null || _a6 === void 0 ? void 0 : _a6[name3],
            prefix: (_b2 = this["x-attribsPrefix"]) === null || _b2 === void 0 ? void 0 : _b2[name3]
          };
        });
      }
    };
    __name(isTag2, "isTag");
    __name(isCDATA, "isCDATA");
    __name(isText, "isText");
    __name(isComment, "isComment");
    __name(isDirective, "isDirective");
    __name(isDocument, "isDocument");
    __name(cloneNode, "cloneNode");
    __name(cloneChildren, "cloneChildren");
  }
});

// node_modules/domhandler/lib/esm/index.js
var defaultOpts, DomHandler;
var init_esm12 = __esm({
  "node_modules/domhandler/lib/esm/index.js"() {
    init_esbuild_shims();
    init_esm11();
    init_node3();
    init_node3();
    defaultOpts = {
      withStartIndices: false,
      withEndIndices: false,
      xmlMode: false
    };
    DomHandler = class {
      static {
        __name(this, "DomHandler");
      }
      /**
       * @param callback Called once parsing has completed.
       * @param options Settings for the handler.
       * @param elementCB Callback whenever a tag is closed.
       */
      constructor(callback, options2, elementCB) {
        this.dom = [];
        this.root = new Document(this.dom);
        this.done = false;
        this.tagStack = [this.root];
        this.lastNode = null;
        this.parser = null;
        if (typeof options2 === "function") {
          elementCB = options2;
          options2 = defaultOpts;
        }
        if (typeof callback === "object") {
          options2 = callback;
          callback = void 0;
        }
        this.callback = callback !== null && callback !== void 0 ? callback : null;
        this.options = options2 !== null && options2 !== void 0 ? options2 : defaultOpts;
        this.elementCB = elementCB !== null && elementCB !== void 0 ? elementCB : null;
      }
      onparserinit(parser6) {
        this.parser = parser6;
      }
      // Resets the handler back to starting state
      onreset() {
        this.dom = [];
        this.root = new Document(this.dom);
        this.done = false;
        this.tagStack = [this.root];
        this.lastNode = null;
        this.parser = null;
      }
      // Signals the handler that parsing is done
      onend() {
        if (this.done)
          return;
        this.done = true;
        this.parser = null;
        this.handleCallback(null);
      }
      onerror(error) {
        this.handleCallback(error);
      }
      onclosetag() {
        this.lastNode = null;
        const elem = this.tagStack.pop();
        if (this.options.withEndIndices) {
          elem.endIndex = this.parser.endIndex;
        }
        if (this.elementCB)
          this.elementCB(elem);
      }
      onopentag(name3, attribs) {
        const type = this.options.xmlMode ? ElementType.Tag : void 0;
        const element = new Element(name3, attribs, void 0, type);
        this.addNode(element);
        this.tagStack.push(element);
      }
      ontext(data) {
        const { lastNode } = this;
        if (lastNode && lastNode.type === ElementType.Text) {
          lastNode.data += data;
          if (this.options.withEndIndices) {
            lastNode.endIndex = this.parser.endIndex;
          }
        } else {
          const node = new Text3(data);
          this.addNode(node);
          this.lastNode = node;
        }
      }
      oncomment(data) {
        if (this.lastNode && this.lastNode.type === ElementType.Comment) {
          this.lastNode.data += data;
          return;
        }
        const node = new Comment2(data);
        this.addNode(node);
        this.lastNode = node;
      }
      oncommentend() {
        this.lastNode = null;
      }
      oncdatastart() {
        const text = new Text3("");
        const node = new CDATA2([text]);
        this.addNode(node);
        text.parent = node;
        this.lastNode = text;
      }
      oncdataend() {
        this.lastNode = null;
      }
      onprocessinginstruction(name3, data) {
        const node = new ProcessingInstruction(name3, data);
        this.addNode(node);
      }
      handleCallback(error) {
        if (typeof this.callback === "function") {
          this.callback(error, this.dom);
        } else if (error) {
          throw error;
        }
      }
      addNode(node) {
        const parent = this.tagStack[this.tagStack.length - 1];
        const previousSibling = parent.children[parent.children.length - 1];
        if (this.options.withStartIndices) {
          node.startIndex = this.parser.startIndex;
        }
        if (this.options.withEndIndices) {
          node.endIndex = this.parser.endIndex;
        }
        parent.children.push(node);
        if (previousSibling) {
          node.prev = previousSibling;
          previousSibling.next = node;
        }
        node.parent = parent;
        this.lastNode = null;
      }
    };
  }
});

// node_modules/leac/lib/leac.mjs
function n(n2) {
  const o2 = [...n2.matchAll(e)].map((e2) => e2.index || 0);
  o2.unshift(-1);
  const s2 = t(o2, 0, o2.length);
  return (e2) => r(s2, e2);
}
function t(e2, n2, r3) {
  if (r3 - n2 == 1) return { offset: e2[n2], index: n2 + 1 };
  const o2 = Math.ceil((n2 + r3) / 2), s2 = t(e2, n2, o2), l2 = t(e2, o2, r3);
  return { offset: s2.offset, low: s2, high: l2 };
}
function r(e2, n2) {
  return function(e3) {
    return Object.prototype.hasOwnProperty.call(e3, "index");
  }(e2) ? { line: e2.index, column: n2 - e2.offset } : r(e2.high.offset < n2 ? e2.high : e2.low, n2);
}
function o(e2, t2 = "", r3 = {}) {
  const o2 = "string" != typeof t2 ? t2 : r3, l2 = "string" == typeof t2 ? t2 : "", c3 = e2.map(s), f = !!o2.lineNumbers;
  return function(e3, t3 = 0) {
    const r4 = f ? n(e3) : () => ({ line: 0, column: 0 });
    let o3 = t3;
    const s2 = [];
    e: for (; o3 < e3.length; ) {
      let n2 = false;
      for (const t4 of c3) {
        t4.regex.lastIndex = o3;
        const c4 = t4.regex.exec(e3);
        if (c4 && c4[0].length > 0) {
          if (!t4.discard) {
            const e4 = r4(o3), n3 = "string" == typeof t4.replace ? c4[0].replace(new RegExp(t4.regex.source, t4.regex.flags), t4.replace) : c4[0];
            s2.push({ state: l2, name: t4.name, text: n3, offset: o3, len: c4[0].length, line: e4.line, column: e4.column });
          }
          if (o3 = t4.regex.lastIndex, n2 = true, t4.push) {
            const n3 = t4.push(e3, o3);
            s2.push(...n3.tokens), o3 = n3.offset;
          }
          if (t4.pop) break e;
          break;
        }
      }
      if (!n2) break;
    }
    return { tokens: s2, offset: o3, complete: e3.length <= o3 };
  };
}
function s(e2, n2) {
  return { ...e2, regex: l(e2, n2) };
}
function l(e2, n2) {
  if (0 === e2.name.length) throw new Error(`Rule #${n2} has empty name, which is not allowed.`);
  if (function(e3) {
    return Object.prototype.hasOwnProperty.call(e3, "regex");
  }(e2)) return function(e3) {
    if (e3.global) throw new Error(`Regular expression /${e3.source}/${e3.flags} contains the global flag, which is not allowed.`);
    return e3.sticky ? e3 : new RegExp(e3.source, e3.flags + "y");
  }(e2.regex);
  if (function(e3) {
    return Object.prototype.hasOwnProperty.call(e3, "str");
  }(e2)) {
    if (0 === e2.str.length) throw new Error(`Rule #${n2} ("${e2.name}") has empty "str" property, which is not allowed.`);
    return new RegExp(c(e2.str), "y");
  }
  return new RegExp(c(e2.name), "y");
}
function c(e2) {
  return e2.replace(/[-[\]{}()*+!<=:?./\\^$|#\s,]/g, "\\$&");
}
var e;
var init_leac = __esm({
  "node_modules/leac/lib/leac.mjs"() {
    init_esbuild_shims();
    e = /\n/g;
    __name(n, "n");
    __name(t, "t");
    __name(r, "r");
    __name(o, "o");
    __name(s, "s");
    __name(l, "l");
    __name(c, "c");
  }
});

// node_modules/peberminta/lib/core.mjs
function token(onToken, onEnd) {
  return (data, i) => {
    let position = i;
    let value = void 0;
    if (i < data.tokens.length) {
      value = onToken(data.tokens[i], data, i);
      if (value !== void 0) {
        position++;
      }
    } else {
      onEnd?.(data, i);
    }
    return value === void 0 ? { matched: false } : {
      matched: true,
      position,
      value
    };
  };
}
function mapInner(r3, f) {
  return r3.matched ? {
    matched: true,
    position: r3.position,
    value: f(r3.value, r3.position)
  } : r3;
}
function mapOuter(r3, f) {
  return r3.matched ? f(r3) : r3;
}
function map(p, mapper) {
  return (data, i) => mapInner(p(data, i), (v, j) => mapper(v, data, i, j));
}
function option(p, def2) {
  return (data, i) => {
    const r3 = p(data, i);
    return r3.matched ? r3 : {
      matched: true,
      position: i,
      value: def2
    };
  };
}
function choice(...ps) {
  return (data, i) => {
    for (const p of ps) {
      const result = p(data, i);
      if (result.matched) {
        return result;
      }
    }
    return { matched: false };
  };
}
function otherwise(pa, pb) {
  return (data, i) => {
    const r1 = pa(data, i);
    return r1.matched ? r1 : pb(data, i);
  };
}
function takeWhile(p, test) {
  return (data, i) => {
    const values = [];
    let success = true;
    do {
      const r3 = p(data, i);
      if (r3.matched && test(r3.value, values.length + 1, data, i, r3.position)) {
        values.push(r3.value);
        i = r3.position;
      } else {
        success = false;
      }
    } while (success);
    return {
      matched: true,
      position: i,
      value: values
    };
  };
}
function many(p) {
  return takeWhile(p, () => true);
}
function many1(p) {
  return ab(p, many(p), (head, tail) => [head, ...tail]);
}
function ab(pa, pb, join35) {
  return (data, i) => mapOuter(pa(data, i), (ma) => mapInner(pb(data, ma.position), (vb, j) => join35(ma.value, vb, data, i, j)));
}
function left(pa, pb) {
  return ab(pa, pb, (va) => va);
}
function right(pa, pb) {
  return ab(pa, pb, (va, vb) => vb);
}
function abc(pa, pb, pc, join35) {
  return (data, i) => mapOuter(pa(data, i), (ma) => mapOuter(pb(data, ma.position), (mb) => mapInner(pc(data, mb.position), (vc, j) => join35(ma.value, mb.value, vc, data, i, j))));
}
function middle(pa, pb, pc) {
  return abc(pa, pb, pc, (ra, rb) => rb);
}
function all(...ps) {
  return (data, i) => {
    const result = [];
    let position = i;
    for (const p of ps) {
      const r1 = p(data, position);
      if (r1.matched) {
        result.push(r1.value);
        position = r1.position;
      } else {
        return { matched: false };
      }
    }
    return {
      matched: true,
      position,
      value: result
    };
  };
}
function flatten(...ps) {
  return flatten1(all(...ps));
}
function flatten1(p) {
  return map(p, (vs) => vs.flatMap((v) => v));
}
function chainReduce(acc, f) {
  return (data, i) => {
    let loop = true;
    let acc1 = acc;
    let pos2 = i;
    do {
      const r3 = f(acc1, data, pos2)(data, pos2);
      if (r3.matched) {
        acc1 = r3.value;
        pos2 = r3.position;
      } else {
        loop = false;
      }
    } while (loop);
    return {
      matched: true,
      position: pos2,
      value: acc1
    };
  };
}
function reduceLeft(acc, p, reducer) {
  return chainReduce(acc, (acc2) => map(p, (v, data, i, j) => reducer(acc2, v, data, i, j)));
}
function leftAssoc2(pLeft, pOper, pRight) {
  return chain(pLeft, (v0) => reduceLeft(v0, ab(pOper, pRight, (f, y) => [f, y]), (acc, [f, y]) => f(acc, y)));
}
function chain(p, f) {
  return (data, i) => mapOuter(p(data, i), (m1) => f(m1.value, data, i, m1.position)(data, m1.position));
}
var init_core = __esm({
  "node_modules/peberminta/lib/core.mjs"() {
    init_esbuild_shims();
    __name(token, "token");
    __name(mapInner, "mapInner");
    __name(mapOuter, "mapOuter");
    __name(map, "map");
    __name(option, "option");
    __name(choice, "choice");
    __name(otherwise, "otherwise");
    __name(takeWhile, "takeWhile");
    __name(many, "many");
    __name(many1, "many1");
    __name(ab, "ab");
    __name(left, "left");
    __name(right, "right");
    __name(abc, "abc");
    __name(middle, "middle");
    __name(all, "all");
    __name(flatten, "flatten");
    __name(flatten1, "flatten1");
    __name(chainReduce, "chainReduce");
    __name(reduceLeft, "reduceLeft");
    __name(leftAssoc2, "leftAssoc2");
    __name(chain, "chain");
  }
});

// node_modules/parseley/lib/parseley.mjs
function sumSpec([a0, a1, a2], [b0, b1, b2]) {
  return [a0 + b0, a1 + b1, a2 + b2];
}
function sumAllSpec(ss) {
  return ss.reduce(sumSpec, [0, 0, 0]);
}
function unescape3(escapedString) {
  const lexerResult = lexEscapedString(escapedString);
  const result = escapedString_({ tokens: lexerResult.tokens, options: void 0 }, 0);
  return result.value;
}
function literal(name3) {
  return token((t2) => t2.name === name3 ? true : void 0);
}
function optionallySpaced(parser6) {
  return middle(optionalWhitespace_, parser6, optionalWhitespace_);
}
function parse_(parser6, str2) {
  if (!(typeof str2 === "string" || str2 instanceof String)) {
    throw new Error("Expected a selector string. Actual input is not a string!");
  }
  const lexerResult = lexSelector(str2);
  if (!lexerResult.complete) {
    throw new Error(`The input "${str2}" was only partially tokenized, stopped at offset ${lexerResult.offset}!
` + prettyPrintPosition(str2, lexerResult.offset));
  }
  const result = optionallySpaced(parser6)({ tokens: lexerResult.tokens, options: void 0 }, 0);
  if (!result.matched) {
    throw new Error(`No match for "${str2}" input!`);
  }
  if (result.position < lexerResult.tokens.length) {
    const token2 = lexerResult.tokens[result.position];
    throw new Error(`The input "${str2}" was only partially parsed, stopped at offset ${token2.offset}!
` + prettyPrintPosition(str2, token2.offset, token2.len));
  }
  return result.value;
}
function prettyPrintPosition(str2, offset, len = 1) {
  return `${str2.replace(/(\t)|(\r)|(\n)/g, (m, t2, r3) => t2 ? "\u2409" : r3 ? "\u240D" : "\u240A")}
${"".padEnd(offset)}${"^".repeat(len)}`;
}
function parse1(str2) {
  return parse_(complexSelector_, str2);
}
function serialize(selector) {
  if (!selector.type) {
    throw new Error("This is not an AST node.");
  }
  switch (selector.type) {
    case "universal":
      return _serNs(selector.namespace) + "*";
    case "tag":
      return _serNs(selector.namespace) + _serIdent(selector.name);
    case "class":
      return "." + _serIdent(selector.name);
    case "id":
      return "#" + _serIdent(selector.name);
    case "attrPresence":
      return `[${_serNs(selector.namespace)}${_serIdent(selector.name)}]`;
    case "attrValue":
      return `[${_serNs(selector.namespace)}${_serIdent(selector.name)}${selector.matcher}"${_serStr(selector.value)}"${selector.modifier ? selector.modifier : ""}]`;
    case "combinator":
      return serialize(selector.left) + selector.combinator;
    case "compound":
      return selector.list.reduce((acc, node) => {
        if (node.type === "combinator") {
          return serialize(node) + acc;
        } else {
          return acc + serialize(node);
        }
      }, "");
    case "list":
      return selector.list.map(serialize).join(",");
  }
}
function _serNs(ns) {
  return ns || ns === "" ? _serIdent(ns) + "|" : "";
}
function _codePoint(char) {
  return `\\${char.codePointAt(0).toString(16)} `;
}
function _serIdent(str2) {
  return str2.replace(
    /(^[0-9])|(^-[0-9])|(^-$)|([-0-9a-zA-Z_]|[^\x00-\x7F])|(\x00)|([\x01-\x1f]|\x7f)|([\s\S])/g,
    (m, d1, d2, hy, safe, nl2, ctrl, other2) => d1 ? _codePoint(d1) : d2 ? "-" + _codePoint(d2.slice(1)) : hy ? "\\-" : safe ? safe : nl2 ? "\uFFFD" : ctrl ? _codePoint(ctrl) : "\\" + other2
  );
}
function _serStr(str2) {
  return str2.replace(
    /(")|(\\)|(\x00)|([\x01-\x1f]|\x7f)/g,
    (m, dq, bs, nl2, ctrl) => dq ? '\\"' : bs ? "\\\\" : nl2 ? "\uFFFD" : _codePoint(ctrl)
  );
}
function normalize4(selector) {
  if (!selector.type) {
    throw new Error("This is not an AST node.");
  }
  switch (selector.type) {
    case "compound": {
      selector.list.forEach(normalize4);
      selector.list.sort((a, b) => _compareArrays(_getSelectorPriority(a), _getSelectorPriority(b)));
      break;
    }
    case "combinator": {
      normalize4(selector.left);
      break;
    }
    case "list": {
      selector.list.forEach(normalize4);
      selector.list.sort((a, b) => serialize(a) < serialize(b) ? -1 : 1);
      break;
    }
  }
  return selector;
}
function _getSelectorPriority(selector) {
  switch (selector.type) {
    case "universal":
      return [1];
    case "tag":
      return [1];
    case "id":
      return [2];
    case "class":
      return [3, selector.name];
    case "attrPresence":
      return [4, serialize(selector)];
    case "attrValue":
      return [5, serialize(selector)];
    case "combinator":
      return [15, serialize(selector)];
  }
}
function compareSpecificity(a, b) {
  return _compareArrays(a, b);
}
function _compareArrays(a, b) {
  if (!Array.isArray(a) || !Array.isArray(b)) {
    throw new Error("Arguments must be arrays.");
  }
  const shorter = a.length < b.length ? a.length : b.length;
  for (let i = 0; i < shorter; i++) {
    if (a[i] === b[i]) {
      continue;
    }
    return a[i] < b[i] ? -1 : 1;
  }
  return a.length - b.length;
}
var ws, nl, nonascii, unicode, escape4, nmstart, nmchar, name, ident, string1, string2, lexSelector, lexEscapedString, unicodeEscapedSequence_, escapedSequence_, anyChar_, escapedString_, whitespace_, optionalWhitespace_, identifier_, hashId_, string_, namespace_, qualifiedName_, uniSelector_, tagSelector_, classSelector_, idSelector_, attrModifier_, attrValue_, attrMatcher_, attrPresenceSelector_, attrValueSelector_, attrSelector_, typeSelector_, subclassSelector_, compoundSelector_, combinator_, combinatorSeparator_, complexSelector_, listSelector_;
var init_parseley = __esm({
  "node_modules/parseley/lib/parseley.mjs"() {
    init_esbuild_shims();
    init_leac();
    init_core();
    ws = `(?:[ \\t\\r\\n\\f]*)`;
    nl = `(?:\\n|\\r\\n|\\r|\\f)`;
    nonascii = `[^\\x00-\\x7F]`;
    unicode = `(?:\\\\[0-9a-f]{1,6}(?:\\r\\n|[ \\n\\r\\t\\f])?)`;
    escape4 = `(?:\\\\[^\\n\\r\\f0-9a-f])`;
    nmstart = `(?:[_a-z]|${nonascii}|${unicode}|${escape4})`;
    nmchar = `(?:[_a-z0-9-]|${nonascii}|${unicode}|${escape4})`;
    name = `(?:${nmchar}+)`;
    ident = `(?:[-]?${nmstart}${nmchar}*)`;
    string1 = `'([^\\n\\r\\f\\\\']|\\\\${nl}|${nonascii}|${unicode}|${escape4})*'`;
    string2 = `"([^\\n\\r\\f\\\\"]|\\\\${nl}|${nonascii}|${unicode}|${escape4})*"`;
    lexSelector = o([
      { name: "ws", regex: new RegExp(ws) },
      { name: "hash", regex: new RegExp(`#${name}`, "i") },
      { name: "ident", regex: new RegExp(ident, "i") },
      { name: "str1", regex: new RegExp(string1, "i") },
      { name: "str2", regex: new RegExp(string2, "i") },
      { name: "*" },
      { name: "." },
      { name: "," },
      { name: "[" },
      { name: "]" },
      { name: "=" },
      { name: ">" },
      { name: "|" },
      { name: "+" },
      { name: "~" },
      { name: "^" },
      { name: "$" }
    ]);
    lexEscapedString = o([
      { name: "unicode", regex: new RegExp(unicode, "i") },
      { name: "escape", regex: new RegExp(escape4, "i") },
      { name: "any", regex: new RegExp("[\\s\\S]", "i") }
    ]);
    __name(sumSpec, "sumSpec");
    __name(sumAllSpec, "sumAllSpec");
    unicodeEscapedSequence_ = token((t2) => t2.name === "unicode" ? String.fromCodePoint(parseInt(t2.text.slice(1), 16)) : void 0);
    escapedSequence_ = token((t2) => t2.name === "escape" ? t2.text.slice(1) : void 0);
    anyChar_ = token((t2) => t2.name === "any" ? t2.text : void 0);
    escapedString_ = map(many(choice(unicodeEscapedSequence_, escapedSequence_, anyChar_)), (cs) => cs.join(""));
    __name(unescape3, "unescape");
    __name(literal, "literal");
    whitespace_ = token((t2) => t2.name === "ws" ? null : void 0);
    optionalWhitespace_ = option(whitespace_, null);
    __name(optionallySpaced, "optionallySpaced");
    identifier_ = token((t2) => t2.name === "ident" ? unescape3(t2.text) : void 0);
    hashId_ = token((t2) => t2.name === "hash" ? unescape3(t2.text.slice(1)) : void 0);
    string_ = token((t2) => t2.name.startsWith("str") ? unescape3(t2.text.slice(1, -1)) : void 0);
    namespace_ = left(option(identifier_, ""), literal("|"));
    qualifiedName_ = otherwise(ab(namespace_, identifier_, (ns, name3) => ({ name: name3, namespace: ns })), map(identifier_, (name3) => ({ name: name3, namespace: null })));
    uniSelector_ = otherwise(ab(namespace_, literal("*"), (ns) => ({ type: "universal", namespace: ns, specificity: [0, 0, 0] })), map(literal("*"), () => ({ type: "universal", namespace: null, specificity: [0, 0, 0] })));
    tagSelector_ = map(qualifiedName_, ({ name: name3, namespace }) => ({
      type: "tag",
      name: name3,
      namespace,
      specificity: [0, 0, 1]
    }));
    classSelector_ = ab(literal("."), identifier_, (fullstop, name3) => ({
      type: "class",
      name: name3,
      specificity: [0, 1, 0]
    }));
    idSelector_ = map(hashId_, (name3) => ({
      type: "id",
      name: name3,
      specificity: [1, 0, 0]
    }));
    attrModifier_ = token((t2) => {
      if (t2.name === "ident") {
        if (t2.text === "i" || t2.text === "I") {
          return "i";
        }
        if (t2.text === "s" || t2.text === "S") {
          return "s";
        }
      }
      return void 0;
    });
    attrValue_ = otherwise(ab(string_, option(right(optionalWhitespace_, attrModifier_), null), (v, mod2) => ({ value: v, modifier: mod2 })), ab(identifier_, option(right(whitespace_, attrModifier_), null), (v, mod2) => ({ value: v, modifier: mod2 })));
    attrMatcher_ = choice(map(literal("="), () => "="), ab(literal("~"), literal("="), () => "~="), ab(literal("|"), literal("="), () => "|="), ab(literal("^"), literal("="), () => "^="), ab(literal("$"), literal("="), () => "$="), ab(literal("*"), literal("="), () => "*="));
    attrPresenceSelector_ = abc(literal("["), optionallySpaced(qualifiedName_), literal("]"), (lbr, { name: name3, namespace }) => ({
      type: "attrPresence",
      name: name3,
      namespace,
      specificity: [0, 1, 0]
    }));
    attrValueSelector_ = middle(literal("["), abc(optionallySpaced(qualifiedName_), attrMatcher_, optionallySpaced(attrValue_), ({ name: name3, namespace }, matcher, { value, modifier }) => ({
      type: "attrValue",
      name: name3,
      namespace,
      matcher,
      value,
      modifier,
      specificity: [0, 1, 0]
    })), literal("]"));
    attrSelector_ = otherwise(attrPresenceSelector_, attrValueSelector_);
    typeSelector_ = otherwise(uniSelector_, tagSelector_);
    subclassSelector_ = choice(idSelector_, classSelector_, attrSelector_);
    compoundSelector_ = map(otherwise(flatten(typeSelector_, many(subclassSelector_)), many1(subclassSelector_)), (ss) => {
      return {
        type: "compound",
        list: ss,
        specificity: sumAllSpec(ss.map((s2) => s2.specificity))
      };
    });
    combinator_ = choice(map(literal(">"), () => ">"), map(literal("+"), () => "+"), map(literal("~"), () => "~"), ab(literal("|"), literal("|"), () => "||"));
    combinatorSeparator_ = otherwise(optionallySpaced(combinator_), map(whitespace_, () => " "));
    complexSelector_ = leftAssoc2(compoundSelector_, map(combinatorSeparator_, (c3) => (left3, right3) => ({
      type: "compound",
      list: [...right3.list, { type: "combinator", combinator: c3, left: left3, specificity: left3.specificity }],
      specificity: sumSpec(left3.specificity, right3.specificity)
    })), compoundSelector_);
    listSelector_ = leftAssoc2(map(complexSelector_, (s2) => ({ type: "list", list: [s2] })), map(optionallySpaced(literal(",")), () => (acc, next) => ({ type: "list", list: [...acc.list, next] })), complexSelector_);
    __name(parse_, "parse_");
    __name(prettyPrintPosition, "prettyPrintPosition");
    __name(parse1, "parse1");
    __name(serialize, "serialize");
    __name(_serNs, "_serNs");
    __name(_codePoint, "_codePoint");
    __name(_serIdent, "_serIdent");
    __name(_serStr, "_serStr");
    __name(normalize4, "normalize");
    __name(_getSelectorPriority, "_getSelectorPriority");
    __name(compareSpecificity, "compareSpecificity");
    __name(_compareArrays, "_compareArrays");
  }
});

// node_modules/selderee/lib/selderee.mjs
function toAstTerminalPairs(array) {
  const len = array.length;
  const results = new Array(len);
  for (let i = 0; i < len; i++) {
    const [selectorString, val] = array[i];
    const ast = preprocess(parse1(selectorString));
    results[i] = {
      ast,
      terminal: {
        type: "terminal",
        valueContainer: { index: i, value: val, specificity: ast.specificity }
      }
    };
  }
  return results;
}
function preprocess(ast) {
  reduceSelectorVariants(ast);
  normalize4(ast);
  return ast;
}
function reduceSelectorVariants(ast) {
  const newList = [];
  ast.list.forEach((sel) => {
    switch (sel.type) {
      case "class":
        newList.push({
          matcher: "~=",
          modifier: null,
          name: "class",
          namespace: null,
          specificity: sel.specificity,
          type: "attrValue",
          value: sel.name
        });
        break;
      case "id":
        newList.push({
          matcher: "=",
          modifier: null,
          name: "id",
          namespace: null,
          specificity: sel.specificity,
          type: "attrValue",
          value: sel.name
        });
        break;
      case "combinator":
        reduceSelectorVariants(sel.left);
        newList.push(sel);
        break;
      case "universal":
        break;
      default:
        newList.push(sel);
        break;
    }
  });
  ast.list = newList;
}
function weave(items) {
  const branches = [];
  while (items.length) {
    const topKind = findTopKey(items, (sel) => true, getSelectorKind);
    const { matches, nonmatches, empty } = breakByKind(items, topKind);
    items = nonmatches;
    if (matches.length) {
      branches.push(branchOfKind(topKind, matches));
    }
    if (empty.length) {
      branches.push(...terminate(empty));
    }
  }
  return branches;
}
function terminate(items) {
  const results = [];
  for (const item of items) {
    const terminal = item.terminal;
    if (terminal.type === "terminal") {
      results.push(terminal);
    } else {
      const { matches, rest } = partition2(terminal.cont, (node) => node.type === "terminal");
      matches.forEach((node) => results.push(node));
      if (rest.length) {
        terminal.cont = rest;
        results.push(terminal);
      }
    }
  }
  return results;
}
function breakByKind(items, selectedKind) {
  const matches = [];
  const nonmatches = [];
  const empty = [];
  for (const item of items) {
    const simpsels = item.ast.list;
    if (simpsels.length) {
      const isMatch = simpsels.some((node) => getSelectorKind(node) === selectedKind);
      (isMatch ? matches : nonmatches).push(item);
    } else {
      empty.push(item);
    }
  }
  return { matches, nonmatches, empty };
}
function getSelectorKind(sel) {
  switch (sel.type) {
    case "attrPresence":
      return `attrPresence ${sel.name}`;
    case "attrValue":
      return `attrValue ${sel.name}`;
    case "combinator":
      return `combinator ${sel.combinator}`;
    default:
      return sel.type;
  }
}
function branchOfKind(kind, items) {
  if (kind === "tag") {
    return tagNameBranch(items);
  }
  if (kind.startsWith("attrValue ")) {
    return attrValueBranch(kind.substring(10), items);
  }
  if (kind.startsWith("attrPresence ")) {
    return attrPresenceBranch(kind.substring(13), items);
  }
  if (kind === "combinator >") {
    return combinatorBranch(">", items);
  }
  if (kind === "combinator +") {
    return combinatorBranch("+", items);
  }
  throw new Error(`Unsupported selector kind: ${kind}`);
}
function tagNameBranch(items) {
  const groups = spliceAndGroup(items, (x) => x.type === "tag", (x) => x.name);
  const variants = Object.entries(groups).map(([name3, group]) => ({
    type: "variant",
    value: name3,
    cont: weave(group.items)
  }));
  return {
    type: "tagName",
    variants
  };
}
function attrPresenceBranch(name3, items) {
  for (const item of items) {
    spliceSimpleSelector(item, (x) => x.type === "attrPresence" && x.name === name3);
  }
  return {
    type: "attrPresence",
    name: name3,
    cont: weave(items)
  };
}
function attrValueBranch(name3, items) {
  const groups = spliceAndGroup(items, (x) => x.type === "attrValue" && x.name === name3, (x) => `${x.matcher} ${x.modifier || ""} ${x.value}`);
  const matchers = [];
  for (const group of Object.values(groups)) {
    const sel = group.oneSimpleSelector;
    const predicate = getAttrPredicate(sel);
    const continuation = weave(group.items);
    matchers.push({
      type: "matcher",
      matcher: sel.matcher,
      modifier: sel.modifier,
      value: sel.value,
      predicate,
      cont: continuation
    });
  }
  return {
    type: "attrValue",
    name: name3,
    matchers
  };
}
function getAttrPredicate(sel) {
  if (sel.modifier === "i") {
    const expected = sel.value.toLowerCase();
    switch (sel.matcher) {
      case "=":
        return (actual) => expected === actual.toLowerCase();
      case "~=":
        return (actual) => actual.toLowerCase().split(/[ \t]+/).includes(expected);
      case "^=":
        return (actual) => actual.toLowerCase().startsWith(expected);
      case "$=":
        return (actual) => actual.toLowerCase().endsWith(expected);
      case "*=":
        return (actual) => actual.toLowerCase().includes(expected);
      case "|=":
        return (actual) => {
          const lower = actual.toLowerCase();
          return expected === lower || lower.startsWith(expected) && lower[expected.length] === "-";
        };
    }
  } else {
    const expected = sel.value;
    switch (sel.matcher) {
      case "=":
        return (actual) => expected === actual;
      case "~=":
        return (actual) => actual.split(/[ \t]+/).includes(expected);
      case "^=":
        return (actual) => actual.startsWith(expected);
      case "$=":
        return (actual) => actual.endsWith(expected);
      case "*=":
        return (actual) => actual.includes(expected);
      case "|=":
        return (actual) => expected === actual || actual.startsWith(expected) && actual[expected.length] === "-";
    }
  }
}
function combinatorBranch(combinator, items) {
  const groups = spliceAndGroup(items, (x) => x.type === "combinator" && x.combinator === combinator, (x) => serialize(x.left));
  const leftItems = [];
  for (const group of Object.values(groups)) {
    const rightCont = weave(group.items);
    const leftAst = group.oneSimpleSelector.left;
    leftItems.push({
      ast: leftAst,
      terminal: { type: "popElement", cont: rightCont }
    });
  }
  return {
    type: "pushElement",
    combinator,
    cont: weave(leftItems)
  };
}
function spliceAndGroup(items, predicate, keyCallback) {
  const groups = {};
  while (items.length) {
    const bestKey = findTopKey(items, predicate, keyCallback);
    const bestKeyPredicate = /* @__PURE__ */ __name((sel) => predicate(sel) && keyCallback(sel) === bestKey, "bestKeyPredicate");
    const hasBestKeyPredicate = /* @__PURE__ */ __name((item) => item.ast.list.some(bestKeyPredicate), "hasBestKeyPredicate");
    const { matches, rest } = partition1(items, hasBestKeyPredicate);
    let oneSimpleSelector = null;
    for (const item of matches) {
      const splicedNode = spliceSimpleSelector(item, bestKeyPredicate);
      if (!oneSimpleSelector) {
        oneSimpleSelector = splicedNode;
      }
    }
    if (oneSimpleSelector == null) {
      throw new Error("No simple selector is found.");
    }
    groups[bestKey] = { oneSimpleSelector, items: matches };
    items = rest;
  }
  return groups;
}
function spliceSimpleSelector(item, predicate) {
  const simpsels = item.ast.list;
  const matches = new Array(simpsels.length);
  let firstIndex = -1;
  for (let i = simpsels.length; i-- > 0; ) {
    if (predicate(simpsels[i])) {
      matches[i] = true;
      firstIndex = i;
    }
  }
  if (firstIndex == -1) {
    throw new Error(`Couldn't find the required simple selector.`);
  }
  const result = simpsels[firstIndex];
  item.ast.list = simpsels.filter((sel, i) => !matches[i]);
  return result;
}
function findTopKey(items, predicate, keyCallback) {
  const candidates = {};
  for (const item of items) {
    const candidates1 = {};
    for (const node of item.ast.list.filter(predicate)) {
      candidates1[keyCallback(node)] = true;
    }
    for (const key of Object.keys(candidates1)) {
      if (candidates[key]) {
        candidates[key]++;
      } else {
        candidates[key] = 1;
      }
    }
  }
  let topKind = "";
  let topCounter = 0;
  for (const entry of Object.entries(candidates)) {
    if (entry[1] > topCounter) {
      topKind = entry[0];
      topCounter = entry[1];
    }
  }
  return topKind;
}
function partition2(src, predicate) {
  const matches = [];
  const rest = [];
  for (const x of src) {
    if (predicate(x)) {
      matches.push(x);
    } else {
      rest.push(x);
    }
  }
  return { matches, rest };
}
function partition1(src, predicate) {
  const matches = [];
  const rest = [];
  for (const x of src) {
    if (predicate(x)) {
      matches.push(x);
    } else {
      rest.push(x);
    }
  }
  return { matches, rest };
}
function comparatorPreferFirst(acc, next) {
  const diff4 = compareSpecificity(next.specificity, acc.specificity);
  return diff4 > 0 || diff4 === 0 && next.index < acc.index;
}
function comparatorPreferLast(acc, next) {
  const diff4 = compareSpecificity(next.specificity, acc.specificity);
  return diff4 > 0 || diff4 === 0 && next.index > acc.index;
}
var DecisionTree, Picker;
var init_selderee = __esm({
  "node_modules/selderee/lib/selderee.mjs"() {
    init_esbuild_shims();
    init_parseley();
    init_parseley();
    DecisionTree = class {
      static {
        __name(this, "DecisionTree");
      }
      constructor(input) {
        this.branches = weave(toAstTerminalPairs(input));
      }
      build(builder) {
        return builder(this.branches);
      }
    };
    __name(toAstTerminalPairs, "toAstTerminalPairs");
    __name(preprocess, "preprocess");
    __name(reduceSelectorVariants, "reduceSelectorVariants");
    __name(weave, "weave");
    __name(terminate, "terminate");
    __name(breakByKind, "breakByKind");
    __name(getSelectorKind, "getSelectorKind");
    __name(branchOfKind, "branchOfKind");
    __name(tagNameBranch, "tagNameBranch");
    __name(attrPresenceBranch, "attrPresenceBranch");
    __name(attrValueBranch, "attrValueBranch");
    __name(getAttrPredicate, "getAttrPredicate");
    __name(combinatorBranch, "combinatorBranch");
    __name(spliceAndGroup, "spliceAndGroup");
    __name(spliceSimpleSelector, "spliceSimpleSelector");
    __name(findTopKey, "findTopKey");
    __name(partition2, "partition");
    __name(partition1, "partition1");
    Picker = class {
      static {
        __name(this, "Picker");
      }
      constructor(f) {
        this.f = f;
      }
      pickAll(el) {
        return this.f(el);
      }
      pick1(el, preferFirst = false) {
        const results = this.f(el);
        const len = results.length;
        if (len === 0) {
          return null;
        }
        if (len === 1) {
          return results[0].value;
        }
        const comparator = preferFirst ? comparatorPreferFirst : comparatorPreferLast;
        let result = results[0];
        for (let i = 1; i < len; i++) {
          const next = results[i];
          if (comparator(result, next)) {
            result = next;
          }
        }
        return result.value;
      }
    };
    __name(comparatorPreferFirst, "comparatorPreferFirst");
    __name(comparatorPreferLast, "comparatorPreferLast");
  }
});

// node_modules/@selderee/plugin-htmlparser2/lib/hp2-builder.mjs
function hp2Builder(nodes) {
  return new Picker(handleArray(nodes));
}
function handleArray(nodes) {
  const matchers = nodes.map(handleNode);
  return (el, ...tail) => matchers.flatMap((m) => m(el, ...tail));
}
function handleNode(node) {
  switch (node.type) {
    case "terminal": {
      const result = [node.valueContainer];
      return (el, ...tail) => result;
    }
    case "tagName":
      return handleTagName(node);
    case "attrValue":
      return handleAttrValueName(node);
    case "attrPresence":
      return handleAttrPresenceName(node);
    case "pushElement":
      return handlePushElementNode(node);
    case "popElement":
      return handlePopElementNode(node);
  }
}
function handleTagName(node) {
  const variants = {};
  for (const variant of node.variants) {
    variants[variant.value] = handleArray(variant.cont);
  }
  return (el, ...tail) => {
    const continuation = variants[el.name];
    return continuation ? continuation(el, ...tail) : [];
  };
}
function handleAttrPresenceName(node) {
  const attrName = node.name;
  const continuation = handleArray(node.cont);
  return (el, ...tail) => Object.prototype.hasOwnProperty.call(el.attribs, attrName) ? continuation(el, ...tail) : [];
}
function handleAttrValueName(node) {
  const callbacks = [];
  for (const matcher of node.matchers) {
    const predicate = matcher.predicate;
    const continuation = handleArray(matcher.cont);
    callbacks.push((attr, el, ...tail) => predicate(attr) ? continuation(el, ...tail) : []);
  }
  const attrName = node.name;
  return (el, ...tail) => {
    const attr = el.attribs[attrName];
    return attr || attr === "" ? callbacks.flatMap((cb) => cb(attr, el, ...tail)) : [];
  };
}
function handlePushElementNode(node) {
  const continuation = handleArray(node.cont);
  const leftElementGetter = node.combinator === "+" ? getPrecedingElement : getParentElement;
  return (el, ...tail) => {
    const next = leftElementGetter(el);
    if (next === null) {
      return [];
    }
    return continuation(next, el, ...tail);
  };
}
function handlePopElementNode(node) {
  const continuation = handleArray(node.cont);
  return (el, next, ...tail) => continuation(next, ...tail);
}
var getPrecedingElement, getParentElement;
var init_hp2_builder = __esm({
  "node_modules/@selderee/plugin-htmlparser2/lib/hp2-builder.mjs"() {
    init_esbuild_shims();
    init_esm12();
    init_selderee();
    __name(hp2Builder, "hp2Builder");
    __name(handleArray, "handleArray");
    __name(handleNode, "handleNode");
    __name(handleTagName, "handleTagName");
    __name(handleAttrPresenceName, "handleAttrPresenceName");
    __name(handleAttrValueName, "handleAttrValueName");
    __name(handlePushElementNode, "handlePushElementNode");
    getPrecedingElement = /* @__PURE__ */ __name((el) => {
      const prev = el.prev;
      if (prev === null) {
        return null;
      }
      return isTag2(prev) ? prev : getPrecedingElement(prev);
    }, "getPrecedingElement");
    getParentElement = /* @__PURE__ */ __name((el) => {
      const parent = el.parent;
      return parent && isTag2(parent) ? parent : null;
    }, "getParentElement");
    __name(handlePopElementNode, "handlePopElementNode");
  }
});

// node_modules/entities/lib/esm/generated/decode-data-html.js
var decode_data_html_default;
var init_decode_data_html = __esm({
  "node_modules/entities/lib/esm/generated/decode-data-html.js"() {
    init_esbuild_shims();
    decode_data_html_default = new Uint16Array(
      // prettier-ignore
      '\u1D41<\xD5\u0131\u028A\u049D\u057B\u05D0\u0675\u06DE\u07A2\u07D6\u080F\u0A4A\u0A91\u0DA1\u0E6D\u0F09\u0F26\u10CA\u1228\u12E1\u1415\u149D\u14C3\u14DF\u1525\0\0\0\0\0\0\u156B\u16CD\u198D\u1C12\u1DDD\u1F7E\u2060\u21B0\u228D\u23C0\u23FB\u2442\u2824\u2912\u2D08\u2E48\u2FCE\u3016\u32BA\u3639\u37AC\u38FE\u3A28\u3A71\u3AE0\u3B2E\u0800EMabcfglmnoprstu\\bfms\x7F\x84\x8B\x90\x95\x98\xA6\xB3\xB9\xC8\xCFlig\u803B\xC6\u40C6P\u803B&\u4026cute\u803B\xC1\u40C1reve;\u4102\u0100iyx}rc\u803B\xC2\u40C2;\u4410r;\uC000\u{1D504}rave\u803B\xC0\u40C0pha;\u4391acr;\u4100d;\u6A53\u0100gp\x9D\xA1on;\u4104f;\uC000\u{1D538}plyFunction;\u6061ing\u803B\xC5\u40C5\u0100cs\xBE\xC3r;\uC000\u{1D49C}ign;\u6254ilde\u803B\xC3\u40C3ml\u803B\xC4\u40C4\u0400aceforsu\xE5\xFB\xFE\u0117\u011C\u0122\u0127\u012A\u0100cr\xEA\xF2kslash;\u6216\u0176\xF6\xF8;\u6AE7ed;\u6306y;\u4411\u0180crt\u0105\u010B\u0114ause;\u6235noullis;\u612Ca;\u4392r;\uC000\u{1D505}pf;\uC000\u{1D539}eve;\u42D8c\xF2\u0113mpeq;\u624E\u0700HOacdefhilorsu\u014D\u0151\u0156\u0180\u019E\u01A2\u01B5\u01B7\u01BA\u01DC\u0215\u0273\u0278\u027Ecy;\u4427PY\u803B\xA9\u40A9\u0180cpy\u015D\u0162\u017Aute;\u4106\u0100;i\u0167\u0168\u62D2talDifferentialD;\u6145leys;\u612D\u0200aeio\u0189\u018E\u0194\u0198ron;\u410Cdil\u803B\xC7\u40C7rc;\u4108nint;\u6230ot;\u410A\u0100dn\u01A7\u01ADilla;\u40B8terDot;\u40B7\xF2\u017Fi;\u43A7rcle\u0200DMPT\u01C7\u01CB\u01D1\u01D6ot;\u6299inus;\u6296lus;\u6295imes;\u6297o\u0100cs\u01E2\u01F8kwiseContourIntegral;\u6232eCurly\u0100DQ\u0203\u020FoubleQuote;\u601Duote;\u6019\u0200lnpu\u021E\u0228\u0247\u0255on\u0100;e\u0225\u0226\u6237;\u6A74\u0180git\u022F\u0236\u023Aruent;\u6261nt;\u622FourIntegral;\u622E\u0100fr\u024C\u024E;\u6102oduct;\u6210nterClockwiseContourIntegral;\u6233oss;\u6A2Fcr;\uC000\u{1D49E}p\u0100;C\u0284\u0285\u62D3ap;\u624D\u0580DJSZacefios\u02A0\u02AC\u02B0\u02B4\u02B8\u02CB\u02D7\u02E1\u02E6\u0333\u048D\u0100;o\u0179\u02A5trahd;\u6911cy;\u4402cy;\u4405cy;\u440F\u0180grs\u02BF\u02C4\u02C7ger;\u6021r;\u61A1hv;\u6AE4\u0100ay\u02D0\u02D5ron;\u410E;\u4414l\u0100;t\u02DD\u02DE\u6207a;\u4394r;\uC000\u{1D507}\u0100af\u02EB\u0327\u0100cm\u02F0\u0322ritical\u0200ADGT\u0300\u0306\u0316\u031Ccute;\u40B4o\u0174\u030B\u030D;\u42D9bleAcute;\u42DDrave;\u4060ilde;\u42DCond;\u62C4ferentialD;\u6146\u0470\u033D\0\0\0\u0342\u0354\0\u0405f;\uC000\u{1D53B}\u0180;DE\u0348\u0349\u034D\u40A8ot;\u60DCqual;\u6250ble\u0300CDLRUV\u0363\u0372\u0382\u03CF\u03E2\u03F8ontourIntegra\xEC\u0239o\u0274\u0379\0\0\u037B\xBB\u0349nArrow;\u61D3\u0100eo\u0387\u03A4ft\u0180ART\u0390\u0396\u03A1rrow;\u61D0ightArrow;\u61D4e\xE5\u02CAng\u0100LR\u03AB\u03C4eft\u0100AR\u03B3\u03B9rrow;\u67F8ightArrow;\u67FAightArrow;\u67F9ight\u0100AT\u03D8\u03DErrow;\u61D2ee;\u62A8p\u0241\u03E9\0\0\u03EFrrow;\u61D1ownArrow;\u61D5erticalBar;\u6225n\u0300ABLRTa\u0412\u042A\u0430\u045E\u047F\u037Crrow\u0180;BU\u041D\u041E\u0422\u6193ar;\u6913pArrow;\u61F5reve;\u4311eft\u02D2\u043A\0\u0446\0\u0450ightVector;\u6950eeVector;\u695Eector\u0100;B\u0459\u045A\u61BDar;\u6956ight\u01D4\u0467\0\u0471eeVector;\u695Fector\u0100;B\u047A\u047B\u61C1ar;\u6957ee\u0100;A\u0486\u0487\u62A4rrow;\u61A7\u0100ct\u0492\u0497r;\uC000\u{1D49F}rok;\u4110\u0800NTacdfglmopqstux\u04BD\u04C0\u04C4\u04CB\u04DE\u04E2\u04E7\u04EE\u04F5\u0521\u052F\u0536\u0552\u055D\u0560\u0565G;\u414AH\u803B\xD0\u40D0cute\u803B\xC9\u40C9\u0180aiy\u04D2\u04D7\u04DCron;\u411Arc\u803B\xCA\u40CA;\u442Dot;\u4116r;\uC000\u{1D508}rave\u803B\xC8\u40C8ement;\u6208\u0100ap\u04FA\u04FEcr;\u4112ty\u0253\u0506\0\0\u0512mallSquare;\u65FBerySmallSquare;\u65AB\u0100gp\u0526\u052Aon;\u4118f;\uC000\u{1D53C}silon;\u4395u\u0100ai\u053C\u0549l\u0100;T\u0542\u0543\u6A75ilde;\u6242librium;\u61CC\u0100ci\u0557\u055Ar;\u6130m;\u6A73a;\u4397ml\u803B\xCB\u40CB\u0100ip\u056A\u056Fsts;\u6203onentialE;\u6147\u0280cfios\u0585\u0588\u058D\u05B2\u05CCy;\u4424r;\uC000\u{1D509}lled\u0253\u0597\0\0\u05A3mallSquare;\u65FCerySmallSquare;\u65AA\u0370\u05BA\0\u05BF\0\0\u05C4f;\uC000\u{1D53D}All;\u6200riertrf;\u6131c\xF2\u05CB\u0600JTabcdfgorst\u05E8\u05EC\u05EF\u05FA\u0600\u0612\u0616\u061B\u061D\u0623\u066C\u0672cy;\u4403\u803B>\u403Emma\u0100;d\u05F7\u05F8\u4393;\u43DCreve;\u411E\u0180eiy\u0607\u060C\u0610dil;\u4122rc;\u411C;\u4413ot;\u4120r;\uC000\u{1D50A};\u62D9pf;\uC000\u{1D53E}eater\u0300EFGLST\u0635\u0644\u064E\u0656\u065B\u0666qual\u0100;L\u063E\u063F\u6265ess;\u62DBullEqual;\u6267reater;\u6AA2ess;\u6277lantEqual;\u6A7Eilde;\u6273cr;\uC000\u{1D4A2};\u626B\u0400Aacfiosu\u0685\u068B\u0696\u069B\u069E\u06AA\u06BE\u06CARDcy;\u442A\u0100ct\u0690\u0694ek;\u42C7;\u405Eirc;\u4124r;\u610ClbertSpace;\u610B\u01F0\u06AF\0\u06B2f;\u610DizontalLine;\u6500\u0100ct\u06C3\u06C5\xF2\u06A9rok;\u4126mp\u0144\u06D0\u06D8ownHum\xF0\u012Fqual;\u624F\u0700EJOacdfgmnostu\u06FA\u06FE\u0703\u0707\u070E\u071A\u071E\u0721\u0728\u0744\u0778\u078B\u078F\u0795cy;\u4415lig;\u4132cy;\u4401cute\u803B\xCD\u40CD\u0100iy\u0713\u0718rc\u803B\xCE\u40CE;\u4418ot;\u4130r;\u6111rave\u803B\xCC\u40CC\u0180;ap\u0720\u072F\u073F\u0100cg\u0734\u0737r;\u412AinaryI;\u6148lie\xF3\u03DD\u01F4\u0749\0\u0762\u0100;e\u074D\u074E\u622C\u0100gr\u0753\u0758ral;\u622Bsection;\u62C2isible\u0100CT\u076C\u0772omma;\u6063imes;\u6062\u0180gpt\u077F\u0783\u0788on;\u412Ef;\uC000\u{1D540}a;\u4399cr;\u6110ilde;\u4128\u01EB\u079A\0\u079Ecy;\u4406l\u803B\xCF\u40CF\u0280cfosu\u07AC\u07B7\u07BC\u07C2\u07D0\u0100iy\u07B1\u07B5rc;\u4134;\u4419r;\uC000\u{1D50D}pf;\uC000\u{1D541}\u01E3\u07C7\0\u07CCr;\uC000\u{1D4A5}rcy;\u4408kcy;\u4404\u0380HJacfos\u07E4\u07E8\u07EC\u07F1\u07FD\u0802\u0808cy;\u4425cy;\u440Cppa;\u439A\u0100ey\u07F6\u07FBdil;\u4136;\u441Ar;\uC000\u{1D50E}pf;\uC000\u{1D542}cr;\uC000\u{1D4A6}\u0580JTaceflmost\u0825\u0829\u082C\u0850\u0863\u09B3\u09B8\u09C7\u09CD\u0A37\u0A47cy;\u4409\u803B<\u403C\u0280cmnpr\u0837\u083C\u0841\u0844\u084Dute;\u4139bda;\u439Bg;\u67EAlacetrf;\u6112r;\u619E\u0180aey\u0857\u085C\u0861ron;\u413Ddil;\u413B;\u441B\u0100fs\u0868\u0970t\u0500ACDFRTUVar\u087E\u08A9\u08B1\u08E0\u08E6\u08FC\u092F\u095B\u0390\u096A\u0100nr\u0883\u088FgleBracket;\u67E8row\u0180;BR\u0899\u089A\u089E\u6190ar;\u61E4ightArrow;\u61C6eiling;\u6308o\u01F5\u08B7\0\u08C3bleBracket;\u67E6n\u01D4\u08C8\0\u08D2eeVector;\u6961ector\u0100;B\u08DB\u08DC\u61C3ar;\u6959loor;\u630Aight\u0100AV\u08EF\u08F5rrow;\u6194ector;\u694E\u0100er\u0901\u0917e\u0180;AV\u0909\u090A\u0910\u62A3rrow;\u61A4ector;\u695Aiangle\u0180;BE\u0924\u0925\u0929\u62B2ar;\u69CFqual;\u62B4p\u0180DTV\u0937\u0942\u094CownVector;\u6951eeVector;\u6960ector\u0100;B\u0956\u0957\u61BFar;\u6958ector\u0100;B\u0965\u0966\u61BCar;\u6952ight\xE1\u039Cs\u0300EFGLST\u097E\u098B\u0995\u099D\u09A2\u09ADqualGreater;\u62DAullEqual;\u6266reater;\u6276ess;\u6AA1lantEqual;\u6A7Dilde;\u6272r;\uC000\u{1D50F}\u0100;e\u09BD\u09BE\u62D8ftarrow;\u61DAidot;\u413F\u0180npw\u09D4\u0A16\u0A1Bg\u0200LRlr\u09DE\u09F7\u0A02\u0A10eft\u0100AR\u09E6\u09ECrrow;\u67F5ightArrow;\u67F7ightArrow;\u67F6eft\u0100ar\u03B3\u0A0Aight\xE1\u03BFight\xE1\u03CAf;\uC000\u{1D543}er\u0100LR\u0A22\u0A2CeftArrow;\u6199ightArrow;\u6198\u0180cht\u0A3E\u0A40\u0A42\xF2\u084C;\u61B0rok;\u4141;\u626A\u0400acefiosu\u0A5A\u0A5D\u0A60\u0A77\u0A7C\u0A85\u0A8B\u0A8Ep;\u6905y;\u441C\u0100dl\u0A65\u0A6FiumSpace;\u605Flintrf;\u6133r;\uC000\u{1D510}nusPlus;\u6213pf;\uC000\u{1D544}c\xF2\u0A76;\u439C\u0480Jacefostu\u0AA3\u0AA7\u0AAD\u0AC0\u0B14\u0B19\u0D91\u0D97\u0D9Ecy;\u440Acute;\u4143\u0180aey\u0AB4\u0AB9\u0ABEron;\u4147dil;\u4145;\u441D\u0180gsw\u0AC7\u0AF0\u0B0Eative\u0180MTV\u0AD3\u0ADF\u0AE8ediumSpace;\u600Bhi\u0100cn\u0AE6\u0AD8\xEB\u0AD9eryThi\xEE\u0AD9ted\u0100GL\u0AF8\u0B06reaterGreate\xF2\u0673essLes\xF3\u0A48Line;\u400Ar;\uC000\u{1D511}\u0200Bnpt\u0B22\u0B28\u0B37\u0B3Areak;\u6060BreakingSpace;\u40A0f;\u6115\u0680;CDEGHLNPRSTV\u0B55\u0B56\u0B6A\u0B7C\u0BA1\u0BEB\u0C04\u0C5E\u0C84\u0CA6\u0CD8\u0D61\u0D85\u6AEC\u0100ou\u0B5B\u0B64ngruent;\u6262pCap;\u626DoubleVerticalBar;\u6226\u0180lqx\u0B83\u0B8A\u0B9Bement;\u6209ual\u0100;T\u0B92\u0B93\u6260ilde;\uC000\u2242\u0338ists;\u6204reater\u0380;EFGLST\u0BB6\u0BB7\u0BBD\u0BC9\u0BD3\u0BD8\u0BE5\u626Fqual;\u6271ullEqual;\uC000\u2267\u0338reater;\uC000\u226B\u0338ess;\u6279lantEqual;\uC000\u2A7E\u0338ilde;\u6275ump\u0144\u0BF2\u0BFDownHump;\uC000\u224E\u0338qual;\uC000\u224F\u0338e\u0100fs\u0C0A\u0C27tTriangle\u0180;BE\u0C1A\u0C1B\u0C21\u62EAar;\uC000\u29CF\u0338qual;\u62ECs\u0300;EGLST\u0C35\u0C36\u0C3C\u0C44\u0C4B\u0C58\u626Equal;\u6270reater;\u6278ess;\uC000\u226A\u0338lantEqual;\uC000\u2A7D\u0338ilde;\u6274ested\u0100GL\u0C68\u0C79reaterGreater;\uC000\u2AA2\u0338essLess;\uC000\u2AA1\u0338recedes\u0180;ES\u0C92\u0C93\u0C9B\u6280qual;\uC000\u2AAF\u0338lantEqual;\u62E0\u0100ei\u0CAB\u0CB9verseElement;\u620CghtTriangle\u0180;BE\u0CCB\u0CCC\u0CD2\u62EBar;\uC000\u29D0\u0338qual;\u62ED\u0100qu\u0CDD\u0D0CuareSu\u0100bp\u0CE8\u0CF9set\u0100;E\u0CF0\u0CF3\uC000\u228F\u0338qual;\u62E2erset\u0100;E\u0D03\u0D06\uC000\u2290\u0338qual;\u62E3\u0180bcp\u0D13\u0D24\u0D4Eset\u0100;E\u0D1B\u0D1E\uC000\u2282\u20D2qual;\u6288ceeds\u0200;EST\u0D32\u0D33\u0D3B\u0D46\u6281qual;\uC000\u2AB0\u0338lantEqual;\u62E1ilde;\uC000\u227F\u0338erset\u0100;E\u0D58\u0D5B\uC000\u2283\u20D2qual;\u6289ilde\u0200;EFT\u0D6E\u0D6F\u0D75\u0D7F\u6241qual;\u6244ullEqual;\u6247ilde;\u6249erticalBar;\u6224cr;\uC000\u{1D4A9}ilde\u803B\xD1\u40D1;\u439D\u0700Eacdfgmoprstuv\u0DBD\u0DC2\u0DC9\u0DD5\u0DDB\u0DE0\u0DE7\u0DFC\u0E02\u0E20\u0E22\u0E32\u0E3F\u0E44lig;\u4152cute\u803B\xD3\u40D3\u0100iy\u0DCE\u0DD3rc\u803B\xD4\u40D4;\u441Eblac;\u4150r;\uC000\u{1D512}rave\u803B\xD2\u40D2\u0180aei\u0DEE\u0DF2\u0DF6cr;\u414Cga;\u43A9cron;\u439Fpf;\uC000\u{1D546}enCurly\u0100DQ\u0E0E\u0E1AoubleQuote;\u601Cuote;\u6018;\u6A54\u0100cl\u0E27\u0E2Cr;\uC000\u{1D4AA}ash\u803B\xD8\u40D8i\u016C\u0E37\u0E3Cde\u803B\xD5\u40D5es;\u6A37ml\u803B\xD6\u40D6er\u0100BP\u0E4B\u0E60\u0100ar\u0E50\u0E53r;\u603Eac\u0100ek\u0E5A\u0E5C;\u63DEet;\u63B4arenthesis;\u63DC\u0480acfhilors\u0E7F\u0E87\u0E8A\u0E8F\u0E92\u0E94\u0E9D\u0EB0\u0EFCrtialD;\u6202y;\u441Fr;\uC000\u{1D513}i;\u43A6;\u43A0usMinus;\u40B1\u0100ip\u0EA2\u0EADncareplan\xE5\u069Df;\u6119\u0200;eio\u0EB9\u0EBA\u0EE0\u0EE4\u6ABBcedes\u0200;EST\u0EC8\u0EC9\u0ECF\u0EDA\u627Aqual;\u6AAFlantEqual;\u627Cilde;\u627Eme;\u6033\u0100dp\u0EE9\u0EEEuct;\u620Fortion\u0100;a\u0225\u0EF9l;\u621D\u0100ci\u0F01\u0F06r;\uC000\u{1D4AB};\u43A8\u0200Ufos\u0F11\u0F16\u0F1B\u0F1FOT\u803B"\u4022r;\uC000\u{1D514}pf;\u611Acr;\uC000\u{1D4AC}\u0600BEacefhiorsu\u0F3E\u0F43\u0F47\u0F60\u0F73\u0FA7\u0FAA\u0FAD\u1096\u10A9\u10B4\u10BEarr;\u6910G\u803B\xAE\u40AE\u0180cnr\u0F4E\u0F53\u0F56ute;\u4154g;\u67EBr\u0100;t\u0F5C\u0F5D\u61A0l;\u6916\u0180aey\u0F67\u0F6C\u0F71ron;\u4158dil;\u4156;\u4420\u0100;v\u0F78\u0F79\u611Cerse\u0100EU\u0F82\u0F99\u0100lq\u0F87\u0F8Eement;\u620Builibrium;\u61CBpEquilibrium;\u696Fr\xBB\u0F79o;\u43A1ght\u0400ACDFTUVa\u0FC1\u0FEB\u0FF3\u1022\u1028\u105B\u1087\u03D8\u0100nr\u0FC6\u0FD2gleBracket;\u67E9row\u0180;BL\u0FDC\u0FDD\u0FE1\u6192ar;\u61E5eftArrow;\u61C4eiling;\u6309o\u01F5\u0FF9\0\u1005bleBracket;\u67E7n\u01D4\u100A\0\u1014eeVector;\u695Dector\u0100;B\u101D\u101E\u61C2ar;\u6955loor;\u630B\u0100er\u102D\u1043e\u0180;AV\u1035\u1036\u103C\u62A2rrow;\u61A6ector;\u695Biangle\u0180;BE\u1050\u1051\u1055\u62B3ar;\u69D0qual;\u62B5p\u0180DTV\u1063\u106E\u1078ownVector;\u694FeeVector;\u695Cector\u0100;B\u1082\u1083\u61BEar;\u6954ector\u0100;B\u1091\u1092\u61C0ar;\u6953\u0100pu\u109B\u109Ef;\u611DndImplies;\u6970ightarrow;\u61DB\u0100ch\u10B9\u10BCr;\u611B;\u61B1leDelayed;\u69F4\u0680HOacfhimoqstu\u10E4\u10F1\u10F7\u10FD\u1119\u111E\u1151\u1156\u1161\u1167\u11B5\u11BB\u11BF\u0100Cc\u10E9\u10EEHcy;\u4429y;\u4428FTcy;\u442Ccute;\u415A\u0280;aeiy\u1108\u1109\u110E\u1113\u1117\u6ABCron;\u4160dil;\u415Erc;\u415C;\u4421r;\uC000\u{1D516}ort\u0200DLRU\u112A\u1134\u113E\u1149ownArrow\xBB\u041EeftArrow\xBB\u089AightArrow\xBB\u0FDDpArrow;\u6191gma;\u43A3allCircle;\u6218pf;\uC000\u{1D54A}\u0272\u116D\0\0\u1170t;\u621Aare\u0200;ISU\u117B\u117C\u1189\u11AF\u65A1ntersection;\u6293u\u0100bp\u118F\u119Eset\u0100;E\u1197\u1198\u628Fqual;\u6291erset\u0100;E\u11A8\u11A9\u6290qual;\u6292nion;\u6294cr;\uC000\u{1D4AE}ar;\u62C6\u0200bcmp\u11C8\u11DB\u1209\u120B\u0100;s\u11CD\u11CE\u62D0et\u0100;E\u11CD\u11D5qual;\u6286\u0100ch\u11E0\u1205eeds\u0200;EST\u11ED\u11EE\u11F4\u11FF\u627Bqual;\u6AB0lantEqual;\u627Dilde;\u627FTh\xE1\u0F8C;\u6211\u0180;es\u1212\u1213\u1223\u62D1rset\u0100;E\u121C\u121D\u6283qual;\u6287et\xBB\u1213\u0580HRSacfhiors\u123E\u1244\u1249\u1255\u125E\u1271\u1276\u129F\u12C2\u12C8\u12D1ORN\u803B\xDE\u40DEADE;\u6122\u0100Hc\u124E\u1252cy;\u440By;\u4426\u0100bu\u125A\u125C;\u4009;\u43A4\u0180aey\u1265\u126A\u126Fron;\u4164dil;\u4162;\u4422r;\uC000\u{1D517}\u0100ei\u127B\u1289\u01F2\u1280\0\u1287efore;\u6234a;\u4398\u0100cn\u128E\u1298kSpace;\uC000\u205F\u200ASpace;\u6009lde\u0200;EFT\u12AB\u12AC\u12B2\u12BC\u623Cqual;\u6243ullEqual;\u6245ilde;\u6248pf;\uC000\u{1D54B}ipleDot;\u60DB\u0100ct\u12D6\u12DBr;\uC000\u{1D4AF}rok;\u4166\u0AE1\u12F7\u130E\u131A\u1326\0\u132C\u1331\0\0\0\0\0\u1338\u133D\u1377\u1385\0\u13FF\u1404\u140A\u1410\u0100cr\u12FB\u1301ute\u803B\xDA\u40DAr\u0100;o\u1307\u1308\u619Fcir;\u6949r\u01E3\u1313\0\u1316y;\u440Eve;\u416C\u0100iy\u131E\u1323rc\u803B\xDB\u40DB;\u4423blac;\u4170r;\uC000\u{1D518}rave\u803B\xD9\u40D9acr;\u416A\u0100di\u1341\u1369er\u0100BP\u1348\u135D\u0100ar\u134D\u1350r;\u405Fac\u0100ek\u1357\u1359;\u63DFet;\u63B5arenthesis;\u63DDon\u0100;P\u1370\u1371\u62C3lus;\u628E\u0100gp\u137B\u137Fon;\u4172f;\uC000\u{1D54C}\u0400ADETadps\u1395\u13AE\u13B8\u13C4\u03E8\u13D2\u13D7\u13F3rrow\u0180;BD\u1150\u13A0\u13A4ar;\u6912ownArrow;\u61C5ownArrow;\u6195quilibrium;\u696Eee\u0100;A\u13CB\u13CC\u62A5rrow;\u61A5own\xE1\u03F3er\u0100LR\u13DE\u13E8eftArrow;\u6196ightArrow;\u6197i\u0100;l\u13F9\u13FA\u43D2on;\u43A5ing;\u416Ecr;\uC000\u{1D4B0}ilde;\u4168ml\u803B\xDC\u40DC\u0480Dbcdefosv\u1427\u142C\u1430\u1433\u143E\u1485\u148A\u1490\u1496ash;\u62ABar;\u6AEBy;\u4412ash\u0100;l\u143B\u143C\u62A9;\u6AE6\u0100er\u1443\u1445;\u62C1\u0180bty\u144C\u1450\u147Aar;\u6016\u0100;i\u144F\u1455cal\u0200BLST\u1461\u1465\u146A\u1474ar;\u6223ine;\u407Ceparator;\u6758ilde;\u6240ThinSpace;\u600Ar;\uC000\u{1D519}pf;\uC000\u{1D54D}cr;\uC000\u{1D4B1}dash;\u62AA\u0280cefos\u14A7\u14AC\u14B1\u14B6\u14BCirc;\u4174dge;\u62C0r;\uC000\u{1D51A}pf;\uC000\u{1D54E}cr;\uC000\u{1D4B2}\u0200fios\u14CB\u14D0\u14D2\u14D8r;\uC000\u{1D51B};\u439Epf;\uC000\u{1D54F}cr;\uC000\u{1D4B3}\u0480AIUacfosu\u14F1\u14F5\u14F9\u14FD\u1504\u150F\u1514\u151A\u1520cy;\u442Fcy;\u4407cy;\u442Ecute\u803B\xDD\u40DD\u0100iy\u1509\u150Drc;\u4176;\u442Br;\uC000\u{1D51C}pf;\uC000\u{1D550}cr;\uC000\u{1D4B4}ml;\u4178\u0400Hacdefos\u1535\u1539\u153F\u154B\u154F\u155D\u1560\u1564cy;\u4416cute;\u4179\u0100ay\u1544\u1549ron;\u417D;\u4417ot;\u417B\u01F2\u1554\0\u155BoWidt\xE8\u0AD9a;\u4396r;\u6128pf;\u6124cr;\uC000\u{1D4B5}\u0BE1\u1583\u158A\u1590\0\u15B0\u15B6\u15BF\0\0\0\0\u15C6\u15DB\u15EB\u165F\u166D\0\u1695\u169B\u16B2\u16B9\0\u16BEcute\u803B\xE1\u40E1reve;\u4103\u0300;Ediuy\u159C\u159D\u15A1\u15A3\u15A8\u15AD\u623E;\uC000\u223E\u0333;\u623Frc\u803B\xE2\u40E2te\u80BB\xB4\u0306;\u4430lig\u803B\xE6\u40E6\u0100;r\xB2\u15BA;\uC000\u{1D51E}rave\u803B\xE0\u40E0\u0100ep\u15CA\u15D6\u0100fp\u15CF\u15D4sym;\u6135\xE8\u15D3ha;\u43B1\u0100ap\u15DFc\u0100cl\u15E4\u15E7r;\u4101g;\u6A3F\u0264\u15F0\0\0\u160A\u0280;adsv\u15FA\u15FB\u15FF\u1601\u1607\u6227nd;\u6A55;\u6A5Clope;\u6A58;\u6A5A\u0380;elmrsz\u1618\u1619\u161B\u161E\u163F\u164F\u1659\u6220;\u69A4e\xBB\u1619sd\u0100;a\u1625\u1626\u6221\u0461\u1630\u1632\u1634\u1636\u1638\u163A\u163C\u163E;\u69A8;\u69A9;\u69AA;\u69AB;\u69AC;\u69AD;\u69AE;\u69AFt\u0100;v\u1645\u1646\u621Fb\u0100;d\u164C\u164D\u62BE;\u699D\u0100pt\u1654\u1657h;\u6222\xBB\xB9arr;\u637C\u0100gp\u1663\u1667on;\u4105f;\uC000\u{1D552}\u0380;Eaeiop\u12C1\u167B\u167D\u1682\u1684\u1687\u168A;\u6A70cir;\u6A6F;\u624Ad;\u624Bs;\u4027rox\u0100;e\u12C1\u1692\xF1\u1683ing\u803B\xE5\u40E5\u0180cty\u16A1\u16A6\u16A8r;\uC000\u{1D4B6};\u402Amp\u0100;e\u12C1\u16AF\xF1\u0288ilde\u803B\xE3\u40E3ml\u803B\xE4\u40E4\u0100ci\u16C2\u16C8onin\xF4\u0272nt;\u6A11\u0800Nabcdefiklnoprsu\u16ED\u16F1\u1730\u173C\u1743\u1748\u1778\u177D\u17E0\u17E6\u1839\u1850\u170D\u193D\u1948\u1970ot;\u6AED\u0100cr\u16F6\u171Ek\u0200ceps\u1700\u1705\u170D\u1713ong;\u624Cpsilon;\u43F6rime;\u6035im\u0100;e\u171A\u171B\u623Dq;\u62CD\u0176\u1722\u1726ee;\u62BDed\u0100;g\u172C\u172D\u6305e\xBB\u172Drk\u0100;t\u135C\u1737brk;\u63B6\u0100oy\u1701\u1741;\u4431quo;\u601E\u0280cmprt\u1753\u175B\u1761\u1764\u1768aus\u0100;e\u010A\u0109ptyv;\u69B0s\xE9\u170Cno\xF5\u0113\u0180ahw\u176F\u1771\u1773;\u43B2;\u6136een;\u626Cr;\uC000\u{1D51F}g\u0380costuvw\u178D\u179D\u17B3\u17C1\u17D5\u17DB\u17DE\u0180aiu\u1794\u1796\u179A\xF0\u0760rc;\u65EFp\xBB\u1371\u0180dpt\u17A4\u17A8\u17ADot;\u6A00lus;\u6A01imes;\u6A02\u0271\u17B9\0\0\u17BEcup;\u6A06ar;\u6605riangle\u0100du\u17CD\u17D2own;\u65BDp;\u65B3plus;\u6A04e\xE5\u1444\xE5\u14ADarow;\u690D\u0180ako\u17ED\u1826\u1835\u0100cn\u17F2\u1823k\u0180lst\u17FA\u05AB\u1802ozenge;\u69EBriangle\u0200;dlr\u1812\u1813\u1818\u181D\u65B4own;\u65BEeft;\u65C2ight;\u65B8k;\u6423\u01B1\u182B\0\u1833\u01B2\u182F\0\u1831;\u6592;\u65914;\u6593ck;\u6588\u0100eo\u183E\u184D\u0100;q\u1843\u1846\uC000=\u20E5uiv;\uC000\u2261\u20E5t;\u6310\u0200ptwx\u1859\u185E\u1867\u186Cf;\uC000\u{1D553}\u0100;t\u13CB\u1863om\xBB\u13CCtie;\u62C8\u0600DHUVbdhmptuv\u1885\u1896\u18AA\u18BB\u18D7\u18DB\u18EC\u18FF\u1905\u190A\u1910\u1921\u0200LRlr\u188E\u1890\u1892\u1894;\u6557;\u6554;\u6556;\u6553\u0280;DUdu\u18A1\u18A2\u18A4\u18A6\u18A8\u6550;\u6566;\u6569;\u6564;\u6567\u0200LRlr\u18B3\u18B5\u18B7\u18B9;\u655D;\u655A;\u655C;\u6559\u0380;HLRhlr\u18CA\u18CB\u18CD\u18CF\u18D1\u18D3\u18D5\u6551;\u656C;\u6563;\u6560;\u656B;\u6562;\u655Fox;\u69C9\u0200LRlr\u18E4\u18E6\u18E8\u18EA;\u6555;\u6552;\u6510;\u650C\u0280;DUdu\u06BD\u18F7\u18F9\u18FB\u18FD;\u6565;\u6568;\u652C;\u6534inus;\u629Flus;\u629Eimes;\u62A0\u0200LRlr\u1919\u191B\u191D\u191F;\u655B;\u6558;\u6518;\u6514\u0380;HLRhlr\u1930\u1931\u1933\u1935\u1937\u1939\u193B\u6502;\u656A;\u6561;\u655E;\u653C;\u6524;\u651C\u0100ev\u0123\u1942bar\u803B\xA6\u40A6\u0200ceio\u1951\u1956\u195A\u1960r;\uC000\u{1D4B7}mi;\u604Fm\u0100;e\u171A\u171Cl\u0180;bh\u1968\u1969\u196B\u405C;\u69C5sub;\u67C8\u016C\u1974\u197El\u0100;e\u1979\u197A\u6022t\xBB\u197Ap\u0180;Ee\u012F\u1985\u1987;\u6AAE\u0100;q\u06DC\u06DB\u0CE1\u19A7\0\u19E8\u1A11\u1A15\u1A32\0\u1A37\u1A50\0\0\u1AB4\0\0\u1AC1\0\0\u1B21\u1B2E\u1B4D\u1B52\0\u1BFD\0\u1C0C\u0180cpr\u19AD\u19B2\u19DDute;\u4107\u0300;abcds\u19BF\u19C0\u19C4\u19CA\u19D5\u19D9\u6229nd;\u6A44rcup;\u6A49\u0100au\u19CF\u19D2p;\u6A4Bp;\u6A47ot;\u6A40;\uC000\u2229\uFE00\u0100eo\u19E2\u19E5t;\u6041\xEE\u0693\u0200aeiu\u19F0\u19FB\u1A01\u1A05\u01F0\u19F5\0\u19F8s;\u6A4Don;\u410Ddil\u803B\xE7\u40E7rc;\u4109ps\u0100;s\u1A0C\u1A0D\u6A4Cm;\u6A50ot;\u410B\u0180dmn\u1A1B\u1A20\u1A26il\u80BB\xB8\u01ADptyv;\u69B2t\u8100\xA2;e\u1A2D\u1A2E\u40A2r\xE4\u01B2r;\uC000\u{1D520}\u0180cei\u1A3D\u1A40\u1A4Dy;\u4447ck\u0100;m\u1A47\u1A48\u6713ark\xBB\u1A48;\u43C7r\u0380;Ecefms\u1A5F\u1A60\u1A62\u1A6B\u1AA4\u1AAA\u1AAE\u65CB;\u69C3\u0180;el\u1A69\u1A6A\u1A6D\u42C6q;\u6257e\u0261\u1A74\0\0\u1A88rrow\u0100lr\u1A7C\u1A81eft;\u61BAight;\u61BB\u0280RSacd\u1A92\u1A94\u1A96\u1A9A\u1A9F\xBB\u0F47;\u64C8st;\u629Birc;\u629Aash;\u629Dnint;\u6A10id;\u6AEFcir;\u69C2ubs\u0100;u\u1ABB\u1ABC\u6663it\xBB\u1ABC\u02EC\u1AC7\u1AD4\u1AFA\0\u1B0Aon\u0100;e\u1ACD\u1ACE\u403A\u0100;q\xC7\xC6\u026D\u1AD9\0\0\u1AE2a\u0100;t\u1ADE\u1ADF\u402C;\u4040\u0180;fl\u1AE8\u1AE9\u1AEB\u6201\xEE\u1160e\u0100mx\u1AF1\u1AF6ent\xBB\u1AE9e\xF3\u024D\u01E7\u1AFE\0\u1B07\u0100;d\u12BB\u1B02ot;\u6A6Dn\xF4\u0246\u0180fry\u1B10\u1B14\u1B17;\uC000\u{1D554}o\xE4\u0254\u8100\xA9;s\u0155\u1B1Dr;\u6117\u0100ao\u1B25\u1B29rr;\u61B5ss;\u6717\u0100cu\u1B32\u1B37r;\uC000\u{1D4B8}\u0100bp\u1B3C\u1B44\u0100;e\u1B41\u1B42\u6ACF;\u6AD1\u0100;e\u1B49\u1B4A\u6AD0;\u6AD2dot;\u62EF\u0380delprvw\u1B60\u1B6C\u1B77\u1B82\u1BAC\u1BD4\u1BF9arr\u0100lr\u1B68\u1B6A;\u6938;\u6935\u0270\u1B72\0\0\u1B75r;\u62DEc;\u62DFarr\u0100;p\u1B7F\u1B80\u61B6;\u693D\u0300;bcdos\u1B8F\u1B90\u1B96\u1BA1\u1BA5\u1BA8\u622Arcap;\u6A48\u0100au\u1B9B\u1B9Ep;\u6A46p;\u6A4Aot;\u628Dr;\u6A45;\uC000\u222A\uFE00\u0200alrv\u1BB5\u1BBF\u1BDE\u1BE3rr\u0100;m\u1BBC\u1BBD\u61B7;\u693Cy\u0180evw\u1BC7\u1BD4\u1BD8q\u0270\u1BCE\0\0\u1BD2re\xE3\u1B73u\xE3\u1B75ee;\u62CEedge;\u62CFen\u803B\xA4\u40A4earrow\u0100lr\u1BEE\u1BF3eft\xBB\u1B80ight\xBB\u1BBDe\xE4\u1BDD\u0100ci\u1C01\u1C07onin\xF4\u01F7nt;\u6231lcty;\u632D\u0980AHabcdefhijlorstuwz\u1C38\u1C3B\u1C3F\u1C5D\u1C69\u1C75\u1C8A\u1C9E\u1CAC\u1CB7\u1CFB\u1CFF\u1D0D\u1D7B\u1D91\u1DAB\u1DBB\u1DC6\u1DCDr\xF2\u0381ar;\u6965\u0200glrs\u1C48\u1C4D\u1C52\u1C54ger;\u6020eth;\u6138\xF2\u1133h\u0100;v\u1C5A\u1C5B\u6010\xBB\u090A\u016B\u1C61\u1C67arow;\u690Fa\xE3\u0315\u0100ay\u1C6E\u1C73ron;\u410F;\u4434\u0180;ao\u0332\u1C7C\u1C84\u0100gr\u02BF\u1C81r;\u61CAtseq;\u6A77\u0180glm\u1C91\u1C94\u1C98\u803B\xB0\u40B0ta;\u43B4ptyv;\u69B1\u0100ir\u1CA3\u1CA8sht;\u697F;\uC000\u{1D521}ar\u0100lr\u1CB3\u1CB5\xBB\u08DC\xBB\u101E\u0280aegsv\u1CC2\u0378\u1CD6\u1CDC\u1CE0m\u0180;os\u0326\u1CCA\u1CD4nd\u0100;s\u0326\u1CD1uit;\u6666amma;\u43DDin;\u62F2\u0180;io\u1CE7\u1CE8\u1CF8\u40F7de\u8100\xF7;o\u1CE7\u1CF0ntimes;\u62C7n\xF8\u1CF7cy;\u4452c\u026F\u1D06\0\0\u1D0Arn;\u631Eop;\u630D\u0280lptuw\u1D18\u1D1D\u1D22\u1D49\u1D55lar;\u4024f;\uC000\u{1D555}\u0280;emps\u030B\u1D2D\u1D37\u1D3D\u1D42q\u0100;d\u0352\u1D33ot;\u6251inus;\u6238lus;\u6214quare;\u62A1blebarwedg\xE5\xFAn\u0180adh\u112E\u1D5D\u1D67ownarrow\xF3\u1C83arpoon\u0100lr\u1D72\u1D76ef\xF4\u1CB4igh\xF4\u1CB6\u0162\u1D7F\u1D85karo\xF7\u0F42\u026F\u1D8A\0\0\u1D8Ern;\u631Fop;\u630C\u0180cot\u1D98\u1DA3\u1DA6\u0100ry\u1D9D\u1DA1;\uC000\u{1D4B9};\u4455l;\u69F6rok;\u4111\u0100dr\u1DB0\u1DB4ot;\u62F1i\u0100;f\u1DBA\u1816\u65BF\u0100ah\u1DC0\u1DC3r\xF2\u0429a\xF2\u0FA6angle;\u69A6\u0100ci\u1DD2\u1DD5y;\u445Fgrarr;\u67FF\u0900Dacdefglmnopqrstux\u1E01\u1E09\u1E19\u1E38\u0578\u1E3C\u1E49\u1E61\u1E7E\u1EA5\u1EAF\u1EBD\u1EE1\u1F2A\u1F37\u1F44\u1F4E\u1F5A\u0100Do\u1E06\u1D34o\xF4\u1C89\u0100cs\u1E0E\u1E14ute\u803B\xE9\u40E9ter;\u6A6E\u0200aioy\u1E22\u1E27\u1E31\u1E36ron;\u411Br\u0100;c\u1E2D\u1E2E\u6256\u803B\xEA\u40EAlon;\u6255;\u444Dot;\u4117\u0100Dr\u1E41\u1E45ot;\u6252;\uC000\u{1D522}\u0180;rs\u1E50\u1E51\u1E57\u6A9Aave\u803B\xE8\u40E8\u0100;d\u1E5C\u1E5D\u6A96ot;\u6A98\u0200;ils\u1E6A\u1E6B\u1E72\u1E74\u6A99nters;\u63E7;\u6113\u0100;d\u1E79\u1E7A\u6A95ot;\u6A97\u0180aps\u1E85\u1E89\u1E97cr;\u4113ty\u0180;sv\u1E92\u1E93\u1E95\u6205et\xBB\u1E93p\u01001;\u1E9D\u1EA4\u0133\u1EA1\u1EA3;\u6004;\u6005\u6003\u0100gs\u1EAA\u1EAC;\u414Bp;\u6002\u0100gp\u1EB4\u1EB8on;\u4119f;\uC000\u{1D556}\u0180als\u1EC4\u1ECE\u1ED2r\u0100;s\u1ECA\u1ECB\u62D5l;\u69E3us;\u6A71i\u0180;lv\u1EDA\u1EDB\u1EDF\u43B5on\xBB\u1EDB;\u43F5\u0200csuv\u1EEA\u1EF3\u1F0B\u1F23\u0100io\u1EEF\u1E31rc\xBB\u1E2E\u0269\u1EF9\0\0\u1EFB\xED\u0548ant\u0100gl\u1F02\u1F06tr\xBB\u1E5Dess\xBB\u1E7A\u0180aei\u1F12\u1F16\u1F1Als;\u403Dst;\u625Fv\u0100;D\u0235\u1F20D;\u6A78parsl;\u69E5\u0100Da\u1F2F\u1F33ot;\u6253rr;\u6971\u0180cdi\u1F3E\u1F41\u1EF8r;\u612Fo\xF4\u0352\u0100ah\u1F49\u1F4B;\u43B7\u803B\xF0\u40F0\u0100mr\u1F53\u1F57l\u803B\xEB\u40EBo;\u60AC\u0180cip\u1F61\u1F64\u1F67l;\u4021s\xF4\u056E\u0100eo\u1F6C\u1F74ctatio\xEE\u0559nential\xE5\u0579\u09E1\u1F92\0\u1F9E\0\u1FA1\u1FA7\0\0\u1FC6\u1FCC\0\u1FD3\0\u1FE6\u1FEA\u2000\0\u2008\u205Allingdotse\xF1\u1E44y;\u4444male;\u6640\u0180ilr\u1FAD\u1FB3\u1FC1lig;\u8000\uFB03\u0269\u1FB9\0\0\u1FBDg;\u8000\uFB00ig;\u8000\uFB04;\uC000\u{1D523}lig;\u8000\uFB01lig;\uC000fj\u0180alt\u1FD9\u1FDC\u1FE1t;\u666Dig;\u8000\uFB02ns;\u65B1of;\u4192\u01F0\u1FEE\0\u1FF3f;\uC000\u{1D557}\u0100ak\u05BF\u1FF7\u0100;v\u1FFC\u1FFD\u62D4;\u6AD9artint;\u6A0D\u0100ao\u200C\u2055\u0100cs\u2011\u2052\u03B1\u201A\u2030\u2038\u2045\u2048\0\u2050\u03B2\u2022\u2025\u2027\u202A\u202C\0\u202E\u803B\xBD\u40BD;\u6153\u803B\xBC\u40BC;\u6155;\u6159;\u615B\u01B3\u2034\0\u2036;\u6154;\u6156\u02B4\u203E\u2041\0\0\u2043\u803B\xBE\u40BE;\u6157;\u615C5;\u6158\u01B6\u204C\0\u204E;\u615A;\u615D8;\u615El;\u6044wn;\u6322cr;\uC000\u{1D4BB}\u0880Eabcdefgijlnorstv\u2082\u2089\u209F\u20A5\u20B0\u20B4\u20F0\u20F5\u20FA\u20FF\u2103\u2112\u2138\u0317\u213E\u2152\u219E\u0100;l\u064D\u2087;\u6A8C\u0180cmp\u2090\u2095\u209Dute;\u41F5ma\u0100;d\u209C\u1CDA\u43B3;\u6A86reve;\u411F\u0100iy\u20AA\u20AErc;\u411D;\u4433ot;\u4121\u0200;lqs\u063E\u0642\u20BD\u20C9\u0180;qs\u063E\u064C\u20C4lan\xF4\u0665\u0200;cdl\u0665\u20D2\u20D5\u20E5c;\u6AA9ot\u0100;o\u20DC\u20DD\u6A80\u0100;l\u20E2\u20E3\u6A82;\u6A84\u0100;e\u20EA\u20ED\uC000\u22DB\uFE00s;\u6A94r;\uC000\u{1D524}\u0100;g\u0673\u061Bmel;\u6137cy;\u4453\u0200;Eaj\u065A\u210C\u210E\u2110;\u6A92;\u6AA5;\u6AA4\u0200Eaes\u211B\u211D\u2129\u2134;\u6269p\u0100;p\u2123\u2124\u6A8Arox\xBB\u2124\u0100;q\u212E\u212F\u6A88\u0100;q\u212E\u211Bim;\u62E7pf;\uC000\u{1D558}\u0100ci\u2143\u2146r;\u610Am\u0180;el\u066B\u214E\u2150;\u6A8E;\u6A90\u8300>;cdlqr\u05EE\u2160\u216A\u216E\u2173\u2179\u0100ci\u2165\u2167;\u6AA7r;\u6A7Aot;\u62D7Par;\u6995uest;\u6A7C\u0280adels\u2184\u216A\u2190\u0656\u219B\u01F0\u2189\0\u218Epro\xF8\u209Er;\u6978q\u0100lq\u063F\u2196les\xF3\u2088i\xED\u066B\u0100en\u21A3\u21ADrtneqq;\uC000\u2269\uFE00\xC5\u21AA\u0500Aabcefkosy\u21C4\u21C7\u21F1\u21F5\u21FA\u2218\u221D\u222F\u2268\u227Dr\xF2\u03A0\u0200ilmr\u21D0\u21D4\u21D7\u21DBrs\xF0\u1484f\xBB\u2024il\xF4\u06A9\u0100dr\u21E0\u21E4cy;\u444A\u0180;cw\u08F4\u21EB\u21EFir;\u6948;\u61ADar;\u610Firc;\u4125\u0180alr\u2201\u220E\u2213rts\u0100;u\u2209\u220A\u6665it\xBB\u220Alip;\u6026con;\u62B9r;\uC000\u{1D525}s\u0100ew\u2223\u2229arow;\u6925arow;\u6926\u0280amopr\u223A\u223E\u2243\u225E\u2263rr;\u61FFtht;\u623Bk\u0100lr\u2249\u2253eftarrow;\u61A9ightarrow;\u61AAf;\uC000\u{1D559}bar;\u6015\u0180clt\u226F\u2274\u2278r;\uC000\u{1D4BD}as\xE8\u21F4rok;\u4127\u0100bp\u2282\u2287ull;\u6043hen\xBB\u1C5B\u0AE1\u22A3\0\u22AA\0\u22B8\u22C5\u22CE\0\u22D5\u22F3\0\0\u22F8\u2322\u2367\u2362\u237F\0\u2386\u23AA\u23B4cute\u803B\xED\u40ED\u0180;iy\u0771\u22B0\u22B5rc\u803B\xEE\u40EE;\u4438\u0100cx\u22BC\u22BFy;\u4435cl\u803B\xA1\u40A1\u0100fr\u039F\u22C9;\uC000\u{1D526}rave\u803B\xEC\u40EC\u0200;ino\u073E\u22DD\u22E9\u22EE\u0100in\u22E2\u22E6nt;\u6A0Ct;\u622Dfin;\u69DCta;\u6129lig;\u4133\u0180aop\u22FE\u231A\u231D\u0180cgt\u2305\u2308\u2317r;\u412B\u0180elp\u071F\u230F\u2313in\xE5\u078Ear\xF4\u0720h;\u4131f;\u62B7ed;\u41B5\u0280;cfot\u04F4\u232C\u2331\u233D\u2341are;\u6105in\u0100;t\u2338\u2339\u621Eie;\u69DDdo\xF4\u2319\u0280;celp\u0757\u234C\u2350\u235B\u2361al;\u62BA\u0100gr\u2355\u2359er\xF3\u1563\xE3\u234Darhk;\u6A17rod;\u6A3C\u0200cgpt\u236F\u2372\u2376\u237By;\u4451on;\u412Ff;\uC000\u{1D55A}a;\u43B9uest\u803B\xBF\u40BF\u0100ci\u238A\u238Fr;\uC000\u{1D4BE}n\u0280;Edsv\u04F4\u239B\u239D\u23A1\u04F3;\u62F9ot;\u62F5\u0100;v\u23A6\u23A7\u62F4;\u62F3\u0100;i\u0777\u23AElde;\u4129\u01EB\u23B8\0\u23BCcy;\u4456l\u803B\xEF\u40EF\u0300cfmosu\u23CC\u23D7\u23DC\u23E1\u23E7\u23F5\u0100iy\u23D1\u23D5rc;\u4135;\u4439r;\uC000\u{1D527}ath;\u4237pf;\uC000\u{1D55B}\u01E3\u23EC\0\u23F1r;\uC000\u{1D4BF}rcy;\u4458kcy;\u4454\u0400acfghjos\u240B\u2416\u2422\u2427\u242D\u2431\u2435\u243Bppa\u0100;v\u2413\u2414\u43BA;\u43F0\u0100ey\u241B\u2420dil;\u4137;\u443Ar;\uC000\u{1D528}reen;\u4138cy;\u4445cy;\u445Cpf;\uC000\u{1D55C}cr;\uC000\u{1D4C0}\u0B80ABEHabcdefghjlmnoprstuv\u2470\u2481\u2486\u248D\u2491\u250E\u253D\u255A\u2580\u264E\u265E\u2665\u2679\u267D\u269A\u26B2\u26D8\u275D\u2768\u278B\u27C0\u2801\u2812\u0180art\u2477\u247A\u247Cr\xF2\u09C6\xF2\u0395ail;\u691Barr;\u690E\u0100;g\u0994\u248B;\u6A8Bar;\u6962\u0963\u24A5\0\u24AA\0\u24B1\0\0\0\0\0\u24B5\u24BA\0\u24C6\u24C8\u24CD\0\u24F9ute;\u413Amptyv;\u69B4ra\xEE\u084Cbda;\u43BBg\u0180;dl\u088E\u24C1\u24C3;\u6991\xE5\u088E;\u6A85uo\u803B\xAB\u40ABr\u0400;bfhlpst\u0899\u24DE\u24E6\u24E9\u24EB\u24EE\u24F1\u24F5\u0100;f\u089D\u24E3s;\u691Fs;\u691D\xEB\u2252p;\u61ABl;\u6939im;\u6973l;\u61A2\u0180;ae\u24FF\u2500\u2504\u6AABil;\u6919\u0100;s\u2509\u250A\u6AAD;\uC000\u2AAD\uFE00\u0180abr\u2515\u2519\u251Drr;\u690Crk;\u6772\u0100ak\u2522\u252Cc\u0100ek\u2528\u252A;\u407B;\u405B\u0100es\u2531\u2533;\u698Bl\u0100du\u2539\u253B;\u698F;\u698D\u0200aeuy\u2546\u254B\u2556\u2558ron;\u413E\u0100di\u2550\u2554il;\u413C\xEC\u08B0\xE2\u2529;\u443B\u0200cqrs\u2563\u2566\u256D\u257Da;\u6936uo\u0100;r\u0E19\u1746\u0100du\u2572\u2577har;\u6967shar;\u694Bh;\u61B2\u0280;fgqs\u258B\u258C\u0989\u25F3\u25FF\u6264t\u0280ahlrt\u2598\u25A4\u25B7\u25C2\u25E8rrow\u0100;t\u0899\u25A1a\xE9\u24F6arpoon\u0100du\u25AF\u25B4own\xBB\u045Ap\xBB\u0966eftarrows;\u61C7ight\u0180ahs\u25CD\u25D6\u25DErrow\u0100;s\u08F4\u08A7arpoon\xF3\u0F98quigarro\xF7\u21F0hreetimes;\u62CB\u0180;qs\u258B\u0993\u25FAlan\xF4\u09AC\u0280;cdgs\u09AC\u260A\u260D\u261D\u2628c;\u6AA8ot\u0100;o\u2614\u2615\u6A7F\u0100;r\u261A\u261B\u6A81;\u6A83\u0100;e\u2622\u2625\uC000\u22DA\uFE00s;\u6A93\u0280adegs\u2633\u2639\u263D\u2649\u264Bppro\xF8\u24C6ot;\u62D6q\u0100gq\u2643\u2645\xF4\u0989gt\xF2\u248C\xF4\u099Bi\xED\u09B2\u0180ilr\u2655\u08E1\u265Asht;\u697C;\uC000\u{1D529}\u0100;E\u099C\u2663;\u6A91\u0161\u2669\u2676r\u0100du\u25B2\u266E\u0100;l\u0965\u2673;\u696Alk;\u6584cy;\u4459\u0280;acht\u0A48\u2688\u268B\u2691\u2696r\xF2\u25C1orne\xF2\u1D08ard;\u696Bri;\u65FA\u0100io\u269F\u26A4dot;\u4140ust\u0100;a\u26AC\u26AD\u63B0che\xBB\u26AD\u0200Eaes\u26BB\u26BD\u26C9\u26D4;\u6268p\u0100;p\u26C3\u26C4\u6A89rox\xBB\u26C4\u0100;q\u26CE\u26CF\u6A87\u0100;q\u26CE\u26BBim;\u62E6\u0400abnoptwz\u26E9\u26F4\u26F7\u271A\u272F\u2741\u2747\u2750\u0100nr\u26EE\u26F1g;\u67ECr;\u61FDr\xEB\u08C1g\u0180lmr\u26FF\u270D\u2714eft\u0100ar\u09E6\u2707ight\xE1\u09F2apsto;\u67FCight\xE1\u09FDparrow\u0100lr\u2725\u2729ef\xF4\u24EDight;\u61AC\u0180afl\u2736\u2739\u273Dr;\u6985;\uC000\u{1D55D}us;\u6A2Dimes;\u6A34\u0161\u274B\u274Fst;\u6217\xE1\u134E\u0180;ef\u2757\u2758\u1800\u65CAnge\xBB\u2758ar\u0100;l\u2764\u2765\u4028t;\u6993\u0280achmt\u2773\u2776\u277C\u2785\u2787r\xF2\u08A8orne\xF2\u1D8Car\u0100;d\u0F98\u2783;\u696D;\u600Eri;\u62BF\u0300achiqt\u2798\u279D\u0A40\u27A2\u27AE\u27BBquo;\u6039r;\uC000\u{1D4C1}m\u0180;eg\u09B2\u27AA\u27AC;\u6A8D;\u6A8F\u0100bu\u252A\u27B3o\u0100;r\u0E1F\u27B9;\u601Arok;\u4142\u8400<;cdhilqr\u082B\u27D2\u2639\u27DC\u27E0\u27E5\u27EA\u27F0\u0100ci\u27D7\u27D9;\u6AA6r;\u6A79re\xE5\u25F2mes;\u62C9arr;\u6976uest;\u6A7B\u0100Pi\u27F5\u27F9ar;\u6996\u0180;ef\u2800\u092D\u181B\u65C3r\u0100du\u2807\u280Dshar;\u694Ahar;\u6966\u0100en\u2817\u2821rtneqq;\uC000\u2268\uFE00\xC5\u281E\u0700Dacdefhilnopsu\u2840\u2845\u2882\u288E\u2893\u28A0\u28A5\u28A8\u28DA\u28E2\u28E4\u0A83\u28F3\u2902Dot;\u623A\u0200clpr\u284E\u2852\u2863\u287Dr\u803B\xAF\u40AF\u0100et\u2857\u2859;\u6642\u0100;e\u285E\u285F\u6720se\xBB\u285F\u0100;s\u103B\u2868to\u0200;dlu\u103B\u2873\u2877\u287Bow\xEE\u048Cef\xF4\u090F\xF0\u13D1ker;\u65AE\u0100oy\u2887\u288Cmma;\u6A29;\u443Cash;\u6014asuredangle\xBB\u1626r;\uC000\u{1D52A}o;\u6127\u0180cdn\u28AF\u28B4\u28C9ro\u803B\xB5\u40B5\u0200;acd\u1464\u28BD\u28C0\u28C4s\xF4\u16A7ir;\u6AF0ot\u80BB\xB7\u01B5us\u0180;bd\u28D2\u1903\u28D3\u6212\u0100;u\u1D3C\u28D8;\u6A2A\u0163\u28DE\u28E1p;\u6ADB\xF2\u2212\xF0\u0A81\u0100dp\u28E9\u28EEels;\u62A7f;\uC000\u{1D55E}\u0100ct\u28F8\u28FDr;\uC000\u{1D4C2}pos\xBB\u159D\u0180;lm\u2909\u290A\u290D\u43BCtimap;\u62B8\u0C00GLRVabcdefghijlmoprstuvw\u2942\u2953\u297E\u2989\u2998\u29DA\u29E9\u2A15\u2A1A\u2A58\u2A5D\u2A83\u2A95\u2AA4\u2AA8\u2B04\u2B07\u2B44\u2B7F\u2BAE\u2C34\u2C67\u2C7C\u2CE9\u0100gt\u2947\u294B;\uC000\u22D9\u0338\u0100;v\u2950\u0BCF\uC000\u226B\u20D2\u0180elt\u295A\u2972\u2976ft\u0100ar\u2961\u2967rrow;\u61CDightarrow;\u61CE;\uC000\u22D8\u0338\u0100;v\u297B\u0C47\uC000\u226A\u20D2ightarrow;\u61CF\u0100Dd\u298E\u2993ash;\u62AFash;\u62AE\u0280bcnpt\u29A3\u29A7\u29AC\u29B1\u29CCla\xBB\u02DEute;\u4144g;\uC000\u2220\u20D2\u0280;Eiop\u0D84\u29BC\u29C0\u29C5\u29C8;\uC000\u2A70\u0338d;\uC000\u224B\u0338s;\u4149ro\xF8\u0D84ur\u0100;a\u29D3\u29D4\u666El\u0100;s\u29D3\u0B38\u01F3\u29DF\0\u29E3p\u80BB\xA0\u0B37mp\u0100;e\u0BF9\u0C00\u0280aeouy\u29F4\u29FE\u2A03\u2A10\u2A13\u01F0\u29F9\0\u29FB;\u6A43on;\u4148dil;\u4146ng\u0100;d\u0D7E\u2A0Aot;\uC000\u2A6D\u0338p;\u6A42;\u443Dash;\u6013\u0380;Aadqsx\u0B92\u2A29\u2A2D\u2A3B\u2A41\u2A45\u2A50rr;\u61D7r\u0100hr\u2A33\u2A36k;\u6924\u0100;o\u13F2\u13F0ot;\uC000\u2250\u0338ui\xF6\u0B63\u0100ei\u2A4A\u2A4Ear;\u6928\xED\u0B98ist\u0100;s\u0BA0\u0B9Fr;\uC000\u{1D52B}\u0200Eest\u0BC5\u2A66\u2A79\u2A7C\u0180;qs\u0BBC\u2A6D\u0BE1\u0180;qs\u0BBC\u0BC5\u2A74lan\xF4\u0BE2i\xED\u0BEA\u0100;r\u0BB6\u2A81\xBB\u0BB7\u0180Aap\u2A8A\u2A8D\u2A91r\xF2\u2971rr;\u61AEar;\u6AF2\u0180;sv\u0F8D\u2A9C\u0F8C\u0100;d\u2AA1\u2AA2\u62FC;\u62FAcy;\u445A\u0380AEadest\u2AB7\u2ABA\u2ABE\u2AC2\u2AC5\u2AF6\u2AF9r\xF2\u2966;\uC000\u2266\u0338rr;\u619Ar;\u6025\u0200;fqs\u0C3B\u2ACE\u2AE3\u2AEFt\u0100ar\u2AD4\u2AD9rro\xF7\u2AC1ightarro\xF7\u2A90\u0180;qs\u0C3B\u2ABA\u2AEAlan\xF4\u0C55\u0100;s\u0C55\u2AF4\xBB\u0C36i\xED\u0C5D\u0100;r\u0C35\u2AFEi\u0100;e\u0C1A\u0C25i\xE4\u0D90\u0100pt\u2B0C\u2B11f;\uC000\u{1D55F}\u8180\xAC;in\u2B19\u2B1A\u2B36\u40ACn\u0200;Edv\u0B89\u2B24\u2B28\u2B2E;\uC000\u22F9\u0338ot;\uC000\u22F5\u0338\u01E1\u0B89\u2B33\u2B35;\u62F7;\u62F6i\u0100;v\u0CB8\u2B3C\u01E1\u0CB8\u2B41\u2B43;\u62FE;\u62FD\u0180aor\u2B4B\u2B63\u2B69r\u0200;ast\u0B7B\u2B55\u2B5A\u2B5Flle\xEC\u0B7Bl;\uC000\u2AFD\u20E5;\uC000\u2202\u0338lint;\u6A14\u0180;ce\u0C92\u2B70\u2B73u\xE5\u0CA5\u0100;c\u0C98\u2B78\u0100;e\u0C92\u2B7D\xF1\u0C98\u0200Aait\u2B88\u2B8B\u2B9D\u2BA7r\xF2\u2988rr\u0180;cw\u2B94\u2B95\u2B99\u619B;\uC000\u2933\u0338;\uC000\u219D\u0338ghtarrow\xBB\u2B95ri\u0100;e\u0CCB\u0CD6\u0380chimpqu\u2BBD\u2BCD\u2BD9\u2B04\u0B78\u2BE4\u2BEF\u0200;cer\u0D32\u2BC6\u0D37\u2BC9u\xE5\u0D45;\uC000\u{1D4C3}ort\u026D\u2B05\0\0\u2BD6ar\xE1\u2B56m\u0100;e\u0D6E\u2BDF\u0100;q\u0D74\u0D73su\u0100bp\u2BEB\u2BED\xE5\u0CF8\xE5\u0D0B\u0180bcp\u2BF6\u2C11\u2C19\u0200;Ees\u2BFF\u2C00\u0D22\u2C04\u6284;\uC000\u2AC5\u0338et\u0100;e\u0D1B\u2C0Bq\u0100;q\u0D23\u2C00c\u0100;e\u0D32\u2C17\xF1\u0D38\u0200;Ees\u2C22\u2C23\u0D5F\u2C27\u6285;\uC000\u2AC6\u0338et\u0100;e\u0D58\u2C2Eq\u0100;q\u0D60\u2C23\u0200gilr\u2C3D\u2C3F\u2C45\u2C47\xEC\u0BD7lde\u803B\xF1\u40F1\xE7\u0C43iangle\u0100lr\u2C52\u2C5Ceft\u0100;e\u0C1A\u2C5A\xF1\u0C26ight\u0100;e\u0CCB\u2C65\xF1\u0CD7\u0100;m\u2C6C\u2C6D\u43BD\u0180;es\u2C74\u2C75\u2C79\u4023ro;\u6116p;\u6007\u0480DHadgilrs\u2C8F\u2C94\u2C99\u2C9E\u2CA3\u2CB0\u2CB6\u2CD3\u2CE3ash;\u62ADarr;\u6904p;\uC000\u224D\u20D2ash;\u62AC\u0100et\u2CA8\u2CAC;\uC000\u2265\u20D2;\uC000>\u20D2nfin;\u69DE\u0180Aet\u2CBD\u2CC1\u2CC5rr;\u6902;\uC000\u2264\u20D2\u0100;r\u2CCA\u2CCD\uC000<\u20D2ie;\uC000\u22B4\u20D2\u0100At\u2CD8\u2CDCrr;\u6903rie;\uC000\u22B5\u20D2im;\uC000\u223C\u20D2\u0180Aan\u2CF0\u2CF4\u2D02rr;\u61D6r\u0100hr\u2CFA\u2CFDk;\u6923\u0100;o\u13E7\u13E5ear;\u6927\u1253\u1A95\0\0\0\0\0\0\0\0\0\0\0\0\0\u2D2D\0\u2D38\u2D48\u2D60\u2D65\u2D72\u2D84\u1B07\0\0\u2D8D\u2DAB\0\u2DC8\u2DCE\0\u2DDC\u2E19\u2E2B\u2E3E\u2E43\u0100cs\u2D31\u1A97ute\u803B\xF3\u40F3\u0100iy\u2D3C\u2D45r\u0100;c\u1A9E\u2D42\u803B\xF4\u40F4;\u443E\u0280abios\u1AA0\u2D52\u2D57\u01C8\u2D5Alac;\u4151v;\u6A38old;\u69BClig;\u4153\u0100cr\u2D69\u2D6Dir;\u69BF;\uC000\u{1D52C}\u036F\u2D79\0\0\u2D7C\0\u2D82n;\u42DBave\u803B\xF2\u40F2;\u69C1\u0100bm\u2D88\u0DF4ar;\u69B5\u0200acit\u2D95\u2D98\u2DA5\u2DA8r\xF2\u1A80\u0100ir\u2D9D\u2DA0r;\u69BEoss;\u69BBn\xE5\u0E52;\u69C0\u0180aei\u2DB1\u2DB5\u2DB9cr;\u414Dga;\u43C9\u0180cdn\u2DC0\u2DC5\u01CDron;\u43BF;\u69B6pf;\uC000\u{1D560}\u0180ael\u2DD4\u2DD7\u01D2r;\u69B7rp;\u69B9\u0380;adiosv\u2DEA\u2DEB\u2DEE\u2E08\u2E0D\u2E10\u2E16\u6228r\xF2\u1A86\u0200;efm\u2DF7\u2DF8\u2E02\u2E05\u6A5Dr\u0100;o\u2DFE\u2DFF\u6134f\xBB\u2DFF\u803B\xAA\u40AA\u803B\xBA\u40BAgof;\u62B6r;\u6A56lope;\u6A57;\u6A5B\u0180clo\u2E1F\u2E21\u2E27\xF2\u2E01ash\u803B\xF8\u40F8l;\u6298i\u016C\u2E2F\u2E34de\u803B\xF5\u40F5es\u0100;a\u01DB\u2E3As;\u6A36ml\u803B\xF6\u40F6bar;\u633D\u0AE1\u2E5E\0\u2E7D\0\u2E80\u2E9D\0\u2EA2\u2EB9\0\0\u2ECB\u0E9C\0\u2F13\0\0\u2F2B\u2FBC\0\u2FC8r\u0200;ast\u0403\u2E67\u2E72\u0E85\u8100\xB6;l\u2E6D\u2E6E\u40B6le\xEC\u0403\u0269\u2E78\0\0\u2E7Bm;\u6AF3;\u6AFDy;\u443Fr\u0280cimpt\u2E8B\u2E8F\u2E93\u1865\u2E97nt;\u4025od;\u402Eil;\u6030enk;\u6031r;\uC000\u{1D52D}\u0180imo\u2EA8\u2EB0\u2EB4\u0100;v\u2EAD\u2EAE\u43C6;\u43D5ma\xF4\u0A76ne;\u660E\u0180;tv\u2EBF\u2EC0\u2EC8\u43C0chfork\xBB\u1FFD;\u43D6\u0100au\u2ECF\u2EDFn\u0100ck\u2ED5\u2EDDk\u0100;h\u21F4\u2EDB;\u610E\xF6\u21F4s\u0480;abcdemst\u2EF3\u2EF4\u1908\u2EF9\u2EFD\u2F04\u2F06\u2F0A\u2F0E\u402Bcir;\u6A23ir;\u6A22\u0100ou\u1D40\u2F02;\u6A25;\u6A72n\u80BB\xB1\u0E9Dim;\u6A26wo;\u6A27\u0180ipu\u2F19\u2F20\u2F25ntint;\u6A15f;\uC000\u{1D561}nd\u803B\xA3\u40A3\u0500;Eaceinosu\u0EC8\u2F3F\u2F41\u2F44\u2F47\u2F81\u2F89\u2F92\u2F7E\u2FB6;\u6AB3p;\u6AB7u\xE5\u0ED9\u0100;c\u0ECE\u2F4C\u0300;acens\u0EC8\u2F59\u2F5F\u2F66\u2F68\u2F7Eppro\xF8\u2F43urlye\xF1\u0ED9\xF1\u0ECE\u0180aes\u2F6F\u2F76\u2F7Approx;\u6AB9qq;\u6AB5im;\u62E8i\xED\u0EDFme\u0100;s\u2F88\u0EAE\u6032\u0180Eas\u2F78\u2F90\u2F7A\xF0\u2F75\u0180dfp\u0EEC\u2F99\u2FAF\u0180als\u2FA0\u2FA5\u2FAAlar;\u632Eine;\u6312urf;\u6313\u0100;t\u0EFB\u2FB4\xEF\u0EFBrel;\u62B0\u0100ci\u2FC0\u2FC5r;\uC000\u{1D4C5};\u43C8ncsp;\u6008\u0300fiopsu\u2FDA\u22E2\u2FDF\u2FE5\u2FEB\u2FF1r;\uC000\u{1D52E}pf;\uC000\u{1D562}rime;\u6057cr;\uC000\u{1D4C6}\u0180aeo\u2FF8\u3009\u3013t\u0100ei\u2FFE\u3005rnion\xF3\u06B0nt;\u6A16st\u0100;e\u3010\u3011\u403F\xF1\u1F19\xF4\u0F14\u0A80ABHabcdefhilmnoprstux\u3040\u3051\u3055\u3059\u30E0\u310E\u312B\u3147\u3162\u3172\u318E\u3206\u3215\u3224\u3229\u3258\u326E\u3272\u3290\u32B0\u32B7\u0180art\u3047\u304A\u304Cr\xF2\u10B3\xF2\u03DDail;\u691Car\xF2\u1C65ar;\u6964\u0380cdenqrt\u3068\u3075\u3078\u307F\u308F\u3094\u30CC\u0100eu\u306D\u3071;\uC000\u223D\u0331te;\u4155i\xE3\u116Emptyv;\u69B3g\u0200;del\u0FD1\u3089\u308B\u308D;\u6992;\u69A5\xE5\u0FD1uo\u803B\xBB\u40BBr\u0580;abcfhlpstw\u0FDC\u30AC\u30AF\u30B7\u30B9\u30BC\u30BE\u30C0\u30C3\u30C7\u30CAp;\u6975\u0100;f\u0FE0\u30B4s;\u6920;\u6933s;\u691E\xEB\u225D\xF0\u272El;\u6945im;\u6974l;\u61A3;\u619D\u0100ai\u30D1\u30D5il;\u691Ao\u0100;n\u30DB\u30DC\u6236al\xF3\u0F1E\u0180abr\u30E7\u30EA\u30EEr\xF2\u17E5rk;\u6773\u0100ak\u30F3\u30FDc\u0100ek\u30F9\u30FB;\u407D;\u405D\u0100es\u3102\u3104;\u698Cl\u0100du\u310A\u310C;\u698E;\u6990\u0200aeuy\u3117\u311C\u3127\u3129ron;\u4159\u0100di\u3121\u3125il;\u4157\xEC\u0FF2\xE2\u30FA;\u4440\u0200clqs\u3134\u3137\u313D\u3144a;\u6937dhar;\u6969uo\u0100;r\u020E\u020Dh;\u61B3\u0180acg\u314E\u315F\u0F44l\u0200;ips\u0F78\u3158\u315B\u109Cn\xE5\u10BBar\xF4\u0FA9t;\u65AD\u0180ilr\u3169\u1023\u316Esht;\u697D;\uC000\u{1D52F}\u0100ao\u3177\u3186r\u0100du\u317D\u317F\xBB\u047B\u0100;l\u1091\u3184;\u696C\u0100;v\u318B\u318C\u43C1;\u43F1\u0180gns\u3195\u31F9\u31FCht\u0300ahlrst\u31A4\u31B0\u31C2\u31D8\u31E4\u31EErrow\u0100;t\u0FDC\u31ADa\xE9\u30C8arpoon\u0100du\u31BB\u31BFow\xEE\u317Ep\xBB\u1092eft\u0100ah\u31CA\u31D0rrow\xF3\u0FEAarpoon\xF3\u0551ightarrows;\u61C9quigarro\xF7\u30CBhreetimes;\u62CCg;\u42DAingdotse\xF1\u1F32\u0180ahm\u320D\u3210\u3213r\xF2\u0FEAa\xF2\u0551;\u600Foust\u0100;a\u321E\u321F\u63B1che\xBB\u321Fmid;\u6AEE\u0200abpt\u3232\u323D\u3240\u3252\u0100nr\u3237\u323Ag;\u67EDr;\u61FEr\xEB\u1003\u0180afl\u3247\u324A\u324Er;\u6986;\uC000\u{1D563}us;\u6A2Eimes;\u6A35\u0100ap\u325D\u3267r\u0100;g\u3263\u3264\u4029t;\u6994olint;\u6A12ar\xF2\u31E3\u0200achq\u327B\u3280\u10BC\u3285quo;\u603Ar;\uC000\u{1D4C7}\u0100bu\u30FB\u328Ao\u0100;r\u0214\u0213\u0180hir\u3297\u329B\u32A0re\xE5\u31F8mes;\u62CAi\u0200;efl\u32AA\u1059\u1821\u32AB\u65B9tri;\u69CEluhar;\u6968;\u611E\u0D61\u32D5\u32DB\u32DF\u332C\u3338\u3371\0\u337A\u33A4\0\0\u33EC\u33F0\0\u3428\u3448\u345A\u34AD\u34B1\u34CA\u34F1\0\u3616\0\0\u3633cute;\u415Bqu\xEF\u27BA\u0500;Eaceinpsy\u11ED\u32F3\u32F5\u32FF\u3302\u330B\u330F\u331F\u3326\u3329;\u6AB4\u01F0\u32FA\0\u32FC;\u6AB8on;\u4161u\xE5\u11FE\u0100;d\u11F3\u3307il;\u415Frc;\u415D\u0180Eas\u3316\u3318\u331B;\u6AB6p;\u6ABAim;\u62E9olint;\u6A13i\xED\u1204;\u4441ot\u0180;be\u3334\u1D47\u3335\u62C5;\u6A66\u0380Aacmstx\u3346\u334A\u3357\u335B\u335E\u3363\u336Drr;\u61D8r\u0100hr\u3350\u3352\xEB\u2228\u0100;o\u0A36\u0A34t\u803B\xA7\u40A7i;\u403Bwar;\u6929m\u0100in\u3369\xF0nu\xF3\xF1t;\u6736r\u0100;o\u3376\u2055\uC000\u{1D530}\u0200acoy\u3382\u3386\u3391\u33A0rp;\u666F\u0100hy\u338B\u338Fcy;\u4449;\u4448rt\u026D\u3399\0\0\u339Ci\xE4\u1464ara\xEC\u2E6F\u803B\xAD\u40AD\u0100gm\u33A8\u33B4ma\u0180;fv\u33B1\u33B2\u33B2\u43C3;\u43C2\u0400;deglnpr\u12AB\u33C5\u33C9\u33CE\u33D6\u33DE\u33E1\u33E6ot;\u6A6A\u0100;q\u12B1\u12B0\u0100;E\u33D3\u33D4\u6A9E;\u6AA0\u0100;E\u33DB\u33DC\u6A9D;\u6A9Fe;\u6246lus;\u6A24arr;\u6972ar\xF2\u113D\u0200aeit\u33F8\u3408\u340F\u3417\u0100ls\u33FD\u3404lsetm\xE9\u336Ahp;\u6A33parsl;\u69E4\u0100dl\u1463\u3414e;\u6323\u0100;e\u341C\u341D\u6AAA\u0100;s\u3422\u3423\u6AAC;\uC000\u2AAC\uFE00\u0180flp\u342E\u3433\u3442tcy;\u444C\u0100;b\u3438\u3439\u402F\u0100;a\u343E\u343F\u69C4r;\u633Ff;\uC000\u{1D564}a\u0100dr\u344D\u0402es\u0100;u\u3454\u3455\u6660it\xBB\u3455\u0180csu\u3460\u3479\u349F\u0100au\u3465\u346Fp\u0100;s\u1188\u346B;\uC000\u2293\uFE00p\u0100;s\u11B4\u3475;\uC000\u2294\uFE00u\u0100bp\u347F\u348F\u0180;es\u1197\u119C\u3486et\u0100;e\u1197\u348D\xF1\u119D\u0180;es\u11A8\u11AD\u3496et\u0100;e\u11A8\u349D\xF1\u11AE\u0180;af\u117B\u34A6\u05B0r\u0165\u34AB\u05B1\xBB\u117Car\xF2\u1148\u0200cemt\u34B9\u34BE\u34C2\u34C5r;\uC000\u{1D4C8}tm\xEE\xF1i\xEC\u3415ar\xE6\u11BE\u0100ar\u34CE\u34D5r\u0100;f\u34D4\u17BF\u6606\u0100an\u34DA\u34EDight\u0100ep\u34E3\u34EApsilo\xEE\u1EE0h\xE9\u2EAFs\xBB\u2852\u0280bcmnp\u34FB\u355E\u1209\u358B\u358E\u0480;Edemnprs\u350E\u350F\u3511\u3515\u351E\u3523\u352C\u3531\u3536\u6282;\u6AC5ot;\u6ABD\u0100;d\u11DA\u351Aot;\u6AC3ult;\u6AC1\u0100Ee\u3528\u352A;\u6ACB;\u628Alus;\u6ABFarr;\u6979\u0180eiu\u353D\u3552\u3555t\u0180;en\u350E\u3545\u354Bq\u0100;q\u11DA\u350Feq\u0100;q\u352B\u3528m;\u6AC7\u0100bp\u355A\u355C;\u6AD5;\u6AD3c\u0300;acens\u11ED\u356C\u3572\u3579\u357B\u3326ppro\xF8\u32FAurlye\xF1\u11FE\xF1\u11F3\u0180aes\u3582\u3588\u331Bppro\xF8\u331Aq\xF1\u3317g;\u666A\u0680123;Edehlmnps\u35A9\u35AC\u35AF\u121C\u35B2\u35B4\u35C0\u35C9\u35D5\u35DA\u35DF\u35E8\u35ED\u803B\xB9\u40B9\u803B\xB2\u40B2\u803B\xB3\u40B3;\u6AC6\u0100os\u35B9\u35BCt;\u6ABEub;\u6AD8\u0100;d\u1222\u35C5ot;\u6AC4s\u0100ou\u35CF\u35D2l;\u67C9b;\u6AD7arr;\u697Bult;\u6AC2\u0100Ee\u35E4\u35E6;\u6ACC;\u628Blus;\u6AC0\u0180eiu\u35F4\u3609\u360Ct\u0180;en\u121C\u35FC\u3602q\u0100;q\u1222\u35B2eq\u0100;q\u35E7\u35E4m;\u6AC8\u0100bp\u3611\u3613;\u6AD4;\u6AD6\u0180Aan\u361C\u3620\u362Drr;\u61D9r\u0100hr\u3626\u3628\xEB\u222E\u0100;o\u0A2B\u0A29war;\u692Alig\u803B\xDF\u40DF\u0BE1\u3651\u365D\u3660\u12CE\u3673\u3679\0\u367E\u36C2\0\0\0\0\0\u36DB\u3703\0\u3709\u376C\0\0\0\u3787\u0272\u3656\0\0\u365Bget;\u6316;\u43C4r\xEB\u0E5F\u0180aey\u3666\u366B\u3670ron;\u4165dil;\u4163;\u4442lrec;\u6315r;\uC000\u{1D531}\u0200eiko\u3686\u369D\u36B5\u36BC\u01F2\u368B\0\u3691e\u01004f\u1284\u1281a\u0180;sv\u3698\u3699\u369B\u43B8ym;\u43D1\u0100cn\u36A2\u36B2k\u0100as\u36A8\u36AEppro\xF8\u12C1im\xBB\u12ACs\xF0\u129E\u0100as\u36BA\u36AE\xF0\u12C1rn\u803B\xFE\u40FE\u01EC\u031F\u36C6\u22E7es\u8180\xD7;bd\u36CF\u36D0\u36D8\u40D7\u0100;a\u190F\u36D5r;\u6A31;\u6A30\u0180eps\u36E1\u36E3\u3700\xE1\u2A4D\u0200;bcf\u0486\u36EC\u36F0\u36F4ot;\u6336ir;\u6AF1\u0100;o\u36F9\u36FC\uC000\u{1D565}rk;\u6ADA\xE1\u3362rime;\u6034\u0180aip\u370F\u3712\u3764d\xE5\u1248\u0380adempst\u3721\u374D\u3740\u3751\u3757\u375C\u375Fngle\u0280;dlqr\u3730\u3731\u3736\u3740\u3742\u65B5own\xBB\u1DBBeft\u0100;e\u2800\u373E\xF1\u092E;\u625Cight\u0100;e\u32AA\u374B\xF1\u105Aot;\u65ECinus;\u6A3Alus;\u6A39b;\u69CDime;\u6A3Bezium;\u63E2\u0180cht\u3772\u377D\u3781\u0100ry\u3777\u377B;\uC000\u{1D4C9};\u4446cy;\u445Brok;\u4167\u0100io\u378B\u378Ex\xF4\u1777head\u0100lr\u3797\u37A0eftarro\xF7\u084Fightarrow\xBB\u0F5D\u0900AHabcdfghlmoprstuw\u37D0\u37D3\u37D7\u37E4\u37F0\u37FC\u380E\u381C\u3823\u3834\u3851\u385D\u386B\u38A9\u38CC\u38D2\u38EA\u38F6r\xF2\u03EDar;\u6963\u0100cr\u37DC\u37E2ute\u803B\xFA\u40FA\xF2\u1150r\u01E3\u37EA\0\u37EDy;\u445Eve;\u416D\u0100iy\u37F5\u37FArc\u803B\xFB\u40FB;\u4443\u0180abh\u3803\u3806\u380Br\xF2\u13ADlac;\u4171a\xF2\u13C3\u0100ir\u3813\u3818sht;\u697E;\uC000\u{1D532}rave\u803B\xF9\u40F9\u0161\u3827\u3831r\u0100lr\u382C\u382E\xBB\u0957\xBB\u1083lk;\u6580\u0100ct\u3839\u384D\u026F\u383F\0\0\u384Arn\u0100;e\u3845\u3846\u631Cr\xBB\u3846op;\u630Fri;\u65F8\u0100al\u3856\u385Acr;\u416B\u80BB\xA8\u0349\u0100gp\u3862\u3866on;\u4173f;\uC000\u{1D566}\u0300adhlsu\u114B\u3878\u387D\u1372\u3891\u38A0own\xE1\u13B3arpoon\u0100lr\u3888\u388Cef\xF4\u382Digh\xF4\u382Fi\u0180;hl\u3899\u389A\u389C\u43C5\xBB\u13FAon\xBB\u389Aparrows;\u61C8\u0180cit\u38B0\u38C4\u38C8\u026F\u38B6\0\0\u38C1rn\u0100;e\u38BC\u38BD\u631Dr\xBB\u38BDop;\u630Eng;\u416Fri;\u65F9cr;\uC000\u{1D4CA}\u0180dir\u38D9\u38DD\u38E2ot;\u62F0lde;\u4169i\u0100;f\u3730\u38E8\xBB\u1813\u0100am\u38EF\u38F2r\xF2\u38A8l\u803B\xFC\u40FCangle;\u69A7\u0780ABDacdeflnoprsz\u391C\u391F\u3929\u392D\u39B5\u39B8\u39BD\u39DF\u39E4\u39E8\u39F3\u39F9\u39FD\u3A01\u3A20r\xF2\u03F7ar\u0100;v\u3926\u3927\u6AE8;\u6AE9as\xE8\u03E1\u0100nr\u3932\u3937grt;\u699C\u0380eknprst\u34E3\u3946\u394B\u3952\u395D\u3964\u3996app\xE1\u2415othin\xE7\u1E96\u0180hir\u34EB\u2EC8\u3959op\xF4\u2FB5\u0100;h\u13B7\u3962\xEF\u318D\u0100iu\u3969\u396Dgm\xE1\u33B3\u0100bp\u3972\u3984setneq\u0100;q\u397D\u3980\uC000\u228A\uFE00;\uC000\u2ACB\uFE00setneq\u0100;q\u398F\u3992\uC000\u228B\uFE00;\uC000\u2ACC\uFE00\u0100hr\u399B\u399Fet\xE1\u369Ciangle\u0100lr\u39AA\u39AFeft\xBB\u0925ight\xBB\u1051y;\u4432ash\xBB\u1036\u0180elr\u39C4\u39D2\u39D7\u0180;be\u2DEA\u39CB\u39CFar;\u62BBq;\u625Alip;\u62EE\u0100bt\u39DC\u1468a\xF2\u1469r;\uC000\u{1D533}tr\xE9\u39AEsu\u0100bp\u39EF\u39F1\xBB\u0D1C\xBB\u0D59pf;\uC000\u{1D567}ro\xF0\u0EFBtr\xE9\u39B4\u0100cu\u3A06\u3A0Br;\uC000\u{1D4CB}\u0100bp\u3A10\u3A18n\u0100Ee\u3980\u3A16\xBB\u397En\u0100Ee\u3992\u3A1E\xBB\u3990igzag;\u699A\u0380cefoprs\u3A36\u3A3B\u3A56\u3A5B\u3A54\u3A61\u3A6Airc;\u4175\u0100di\u3A40\u3A51\u0100bg\u3A45\u3A49ar;\u6A5Fe\u0100;q\u15FA\u3A4F;\u6259erp;\u6118r;\uC000\u{1D534}pf;\uC000\u{1D568}\u0100;e\u1479\u3A66at\xE8\u1479cr;\uC000\u{1D4CC}\u0AE3\u178E\u3A87\0\u3A8B\0\u3A90\u3A9B\0\0\u3A9D\u3AA8\u3AAB\u3AAF\0\0\u3AC3\u3ACE\0\u3AD8\u17DC\u17DFtr\xE9\u17D1r;\uC000\u{1D535}\u0100Aa\u3A94\u3A97r\xF2\u03C3r\xF2\u09F6;\u43BE\u0100Aa\u3AA1\u3AA4r\xF2\u03B8r\xF2\u09EBa\xF0\u2713is;\u62FB\u0180dpt\u17A4\u3AB5\u3ABE\u0100fl\u3ABA\u17A9;\uC000\u{1D569}im\xE5\u17B2\u0100Aa\u3AC7\u3ACAr\xF2\u03CEr\xF2\u0A01\u0100cq\u3AD2\u17B8r;\uC000\u{1D4CD}\u0100pt\u17D6\u3ADCr\xE9\u17D4\u0400acefiosu\u3AF0\u3AFD\u3B08\u3B0C\u3B11\u3B15\u3B1B\u3B21c\u0100uy\u3AF6\u3AFBte\u803B\xFD\u40FD;\u444F\u0100iy\u3B02\u3B06rc;\u4177;\u444Bn\u803B\xA5\u40A5r;\uC000\u{1D536}cy;\u4457pf;\uC000\u{1D56A}cr;\uC000\u{1D4CE}\u0100cm\u3B26\u3B29y;\u444El\u803B\xFF\u40FF\u0500acdefhiosw\u3B42\u3B48\u3B54\u3B58\u3B64\u3B69\u3B6D\u3B74\u3B7A\u3B80cute;\u417A\u0100ay\u3B4D\u3B52ron;\u417E;\u4437ot;\u417C\u0100et\u3B5D\u3B61tr\xE6\u155Fa;\u43B6r;\uC000\u{1D537}cy;\u4436grarr;\u61DDpf;\uC000\u{1D56B}cr;\uC000\u{1D4CF}\u0100jn\u3B85\u3B87;\u600Dj;\u600C'.split("").map((c3) => c3.charCodeAt(0))
    );
  }
});

// node_modules/entities/lib/esm/generated/decode-data-xml.js
var decode_data_xml_default;
var init_decode_data_xml = __esm({
  "node_modules/entities/lib/esm/generated/decode-data-xml.js"() {
    init_esbuild_shims();
    decode_data_xml_default = new Uint16Array(
      // prettier-ignore
      "\u0200aglq	\x1B\u026D\0\0p;\u4026os;\u4027t;\u403Et;\u403Cuot;\u4022".split("").map((c3) => c3.charCodeAt(0))
    );
  }
});

// node_modules/entities/lib/esm/decode_codepoint.js
function replaceCodePoint(codePoint) {
  var _a6;
  if (codePoint >= 55296 && codePoint <= 57343 || codePoint > 1114111) {
    return 65533;
  }
  return (_a6 = decodeMap.get(codePoint)) !== null && _a6 !== void 0 ? _a6 : codePoint;
}
var _a4, decodeMap, fromCodePoint;
var init_decode_codepoint = __esm({
  "node_modules/entities/lib/esm/decode_codepoint.js"() {
    init_esbuild_shims();
    decodeMap = /* @__PURE__ */ new Map([
      [0, 65533],
      // C1 Unicode control character reference replacements
      [128, 8364],
      [130, 8218],
      [131, 402],
      [132, 8222],
      [133, 8230],
      [134, 8224],
      [135, 8225],
      [136, 710],
      [137, 8240],
      [138, 352],
      [139, 8249],
      [140, 338],
      [142, 381],
      [145, 8216],
      [146, 8217],
      [147, 8220],
      [148, 8221],
      [149, 8226],
      [150, 8211],
      [151, 8212],
      [152, 732],
      [153, 8482],
      [154, 353],
      [155, 8250],
      [156, 339],
      [158, 382],
      [159, 376]
    ]);
    fromCodePoint = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins
    (_a4 = String.fromCodePoint) !== null && _a4 !== void 0 ? _a4 : function(codePoint) {
      let output = "";
      if (codePoint > 65535) {
        codePoint -= 65536;
        output += String.fromCharCode(codePoint >>> 10 & 1023 | 55296);
        codePoint = 56320 | codePoint & 1023;
      }
      output += String.fromCharCode(codePoint);
      return output;
    };
    __name(replaceCodePoint, "replaceCodePoint");
  }
});

// node_modules/entities/lib/esm/decode.js
function isNumber(code2) {
  return code2 >= CharCodes.ZERO && code2 <= CharCodes.NINE;
}
function isHexadecimalCharacter(code2) {
  return code2 >= CharCodes.UPPER_A && code2 <= CharCodes.UPPER_F || code2 >= CharCodes.LOWER_A && code2 <= CharCodes.LOWER_F;
}
function isAsciiAlphaNumeric(code2) {
  return code2 >= CharCodes.UPPER_A && code2 <= CharCodes.UPPER_Z || code2 >= CharCodes.LOWER_A && code2 <= CharCodes.LOWER_Z || isNumber(code2);
}
function isEntityInAttributeInvalidEnd(code2) {
  return code2 === CharCodes.EQUALS || isAsciiAlphaNumeric(code2);
}
function getDecoder(decodeTree) {
  let ret = "";
  const decoder = new EntityDecoder(decodeTree, (str2) => ret += fromCodePoint(str2));
  return /* @__PURE__ */ __name(function decodeWithTrie(str2, decodeMode) {
    let lastIndex = 0;
    let offset = 0;
    while ((offset = str2.indexOf("&", offset)) >= 0) {
      ret += str2.slice(lastIndex, offset);
      decoder.startEntity(decodeMode);
      const len = decoder.write(
        str2,
        // Skip the "&"
        offset + 1
      );
      if (len < 0) {
        lastIndex = offset + decoder.end();
        break;
      }
      lastIndex = offset + len;
      offset = len === 0 ? lastIndex + 1 : lastIndex;
    }
    const result = ret + str2.slice(lastIndex);
    ret = "";
    return result;
  }, "decodeWithTrie");
}
function determineBranch(decodeTree, current, nodeIdx, char) {
  const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
  const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
  if (branchCount === 0) {
    return jumpOffset !== 0 && char === jumpOffset ? nodeIdx : -1;
  }
  if (jumpOffset) {
    const value = char - jumpOffset;
    return value < 0 || value >= branchCount ? -1 : decodeTree[nodeIdx + value] - 1;
  }
  let lo = nodeIdx;
  let hi = lo + branchCount - 1;
  while (lo <= hi) {
    const mid = lo + hi >>> 1;
    const midVal = decodeTree[mid];
    if (midVal < char) {
      lo = mid + 1;
    } else if (midVal > char) {
      hi = mid - 1;
    } else {
      return decodeTree[mid + branchCount];
    }
  }
  return -1;
}
var CharCodes, TO_LOWER_BIT, BinTrieFlags, EntityDecoderState, DecodingMode, EntityDecoder, htmlDecoder, xmlDecoder;
var init_decode = __esm({
  "node_modules/entities/lib/esm/decode.js"() {
    init_esbuild_shims();
    init_decode_data_html();
    init_decode_data_xml();
    init_decode_codepoint();
    init_decode_codepoint();
    (function(CharCodes3) {
      CharCodes3[CharCodes3["NUM"] = 35] = "NUM";
      CharCodes3[CharCodes3["SEMI"] = 59] = "SEMI";
      CharCodes3[CharCodes3["EQUALS"] = 61] = "EQUALS";
      CharCodes3[CharCodes3["ZERO"] = 48] = "ZERO";
      CharCodes3[CharCodes3["NINE"] = 57] = "NINE";
      CharCodes3[CharCodes3["LOWER_A"] = 97] = "LOWER_A";
      CharCodes3[CharCodes3["LOWER_F"] = 102] = "LOWER_F";
      CharCodes3[CharCodes3["LOWER_X"] = 120] = "LOWER_X";
      CharCodes3[CharCodes3["LOWER_Z"] = 122] = "LOWER_Z";
      CharCodes3[CharCodes3["UPPER_A"] = 65] = "UPPER_A";
      CharCodes3[CharCodes3["UPPER_F"] = 70] = "UPPER_F";
      CharCodes3[CharCodes3["UPPER_Z"] = 90] = "UPPER_Z";
    })(CharCodes || (CharCodes = {}));
    TO_LOWER_BIT = 32;
    (function(BinTrieFlags2) {
      BinTrieFlags2[BinTrieFlags2["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH";
      BinTrieFlags2[BinTrieFlags2["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH";
      BinTrieFlags2[BinTrieFlags2["JUMP_TABLE"] = 127] = "JUMP_TABLE";
    })(BinTrieFlags || (BinTrieFlags = {}));
    __name(isNumber, "isNumber");
    __name(isHexadecimalCharacter, "isHexadecimalCharacter");
    __name(isAsciiAlphaNumeric, "isAsciiAlphaNumeric");
    __name(isEntityInAttributeInvalidEnd, "isEntityInAttributeInvalidEnd");
    (function(EntityDecoderState2) {
      EntityDecoderState2[EntityDecoderState2["EntityStart"] = 0] = "EntityStart";
      EntityDecoderState2[EntityDecoderState2["NumericStart"] = 1] = "NumericStart";
      EntityDecoderState2[EntityDecoderState2["NumericDecimal"] = 2] = "NumericDecimal";
      EntityDecoderState2[EntityDecoderState2["NumericHex"] = 3] = "NumericHex";
      EntityDecoderState2[EntityDecoderState2["NamedEntity"] = 4] = "NamedEntity";
    })(EntityDecoderState || (EntityDecoderState = {}));
    (function(DecodingMode2) {
      DecodingMode2[DecodingMode2["Legacy"] = 0] = "Legacy";
      DecodingMode2[DecodingMode2["Strict"] = 1] = "Strict";
      DecodingMode2[DecodingMode2["Attribute"] = 2] = "Attribute";
    })(DecodingMode || (DecodingMode = {}));
    EntityDecoder = class {
      static {
        __name(this, "EntityDecoder");
      }
      constructor(decodeTree, emitCodePoint, errors) {
        this.decodeTree = decodeTree;
        this.emitCodePoint = emitCodePoint;
        this.errors = errors;
        this.state = EntityDecoderState.EntityStart;
        this.consumed = 1;
        this.result = 0;
        this.treeIndex = 0;
        this.excess = 1;
        this.decodeMode = DecodingMode.Strict;
      }
      /** Resets the instance to make it reusable. */
      startEntity(decodeMode) {
        this.decodeMode = decodeMode;
        this.state = EntityDecoderState.EntityStart;
        this.result = 0;
        this.treeIndex = 0;
        this.excess = 1;
        this.consumed = 1;
      }
      /**
       * Write an entity to the decoder. This can be called multiple times with partial entities.
       * If the entity is incomplete, the decoder will return -1.
       *
       * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the
       * entity is incomplete, and resume when the next string is written.
       *
       * @param string The string containing the entity (or a continuation of the entity).
       * @param offset The offset at which the entity begins. Should be 0 if this is not the first call.
       * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
       */
      write(str2, offset) {
        switch (this.state) {
          case EntityDecoderState.EntityStart: {
            if (str2.charCodeAt(offset) === CharCodes.NUM) {
              this.state = EntityDecoderState.NumericStart;
              this.consumed += 1;
              return this.stateNumericStart(str2, offset + 1);
            }
            this.state = EntityDecoderState.NamedEntity;
            return this.stateNamedEntity(str2, offset);
          }
          case EntityDecoderState.NumericStart: {
            return this.stateNumericStart(str2, offset);
          }
          case EntityDecoderState.NumericDecimal: {
            return this.stateNumericDecimal(str2, offset);
          }
          case EntityDecoderState.NumericHex: {
            return this.stateNumericHex(str2, offset);
          }
          case EntityDecoderState.NamedEntity: {
            return this.stateNamedEntity(str2, offset);
          }
        }
      }
      /**
       * Switches between the numeric decimal and hexadecimal states.
       *
       * Equivalent to the `Numeric character reference state` in the HTML spec.
       *
       * @param str The string containing the entity (or a continuation of the entity).
       * @param offset The current offset.
       * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
       */
      stateNumericStart(str2, offset) {
        if (offset >= str2.length) {
          return -1;
        }
        if ((str2.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) {
          this.state = EntityDecoderState.NumericHex;
          this.consumed += 1;
          return this.stateNumericHex(str2, offset + 1);
        }
        this.state = EntityDecoderState.NumericDecimal;
        return this.stateNumericDecimal(str2, offset);
      }
      addToNumericResult(str2, start, end, base) {
        if (start !== end) {
          const digitCount = end - start;
          this.result = this.result * Math.pow(base, digitCount) + parseInt(str2.substr(start, digitCount), base);
          this.consumed += digitCount;
        }
      }
      /**
       * Parses a hexadecimal numeric entity.
       *
       * Equivalent to the `Hexademical character reference state` in the HTML spec.
       *
       * @param str The string containing the entity (or a continuation of the entity).
       * @param offset The current offset.
       * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
       */
      stateNumericHex(str2, offset) {
        const startIdx = offset;
        while (offset < str2.length) {
          const char = str2.charCodeAt(offset);
          if (isNumber(char) || isHexadecimalCharacter(char)) {
            offset += 1;
          } else {
            this.addToNumericResult(str2, startIdx, offset, 16);
            return this.emitNumericEntity(char, 3);
          }
        }
        this.addToNumericResult(str2, startIdx, offset, 16);
        return -1;
      }
      /**
       * Parses a decimal numeric entity.
       *
       * Equivalent to the `Decimal character reference state` in the HTML spec.
       *
       * @param str The string containing the entity (or a continuation of the entity).
       * @param offset The current offset.
       * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
       */
      stateNumericDecimal(str2, offset) {
        const startIdx = offset;
        while (offset < str2.length) {
          const char = str2.charCodeAt(offset);
          if (isNumber(char)) {
            offset += 1;
          } else {
            this.addToNumericResult(str2, startIdx, offset, 10);
            return this.emitNumericEntity(char, 2);
          }
        }
        this.addToNumericResult(str2, startIdx, offset, 10);
        return -1;
      }
      /**
       * Validate and emit a numeric entity.
       *
       * Implements the logic from the `Hexademical character reference start
       * state` and `Numeric character reference end state` in the HTML spec.
       *
       * @param lastCp The last code point of the entity. Used to see if the
       *               entity was terminated with a semicolon.
       * @param expectedLength The minimum number of characters that should be
       *                       consumed. Used to validate that at least one digit
       *                       was consumed.
       * @returns The number of characters that were consumed.
       */
      emitNumericEntity(lastCp, expectedLength) {
        var _a6;
        if (this.consumed <= expectedLength) {
          (_a6 = this.errors) === null || _a6 === void 0 ? void 0 : _a6.absenceOfDigitsInNumericCharacterReference(this.consumed);
          return 0;
        }
        if (lastCp === CharCodes.SEMI) {
          this.consumed += 1;
        } else if (this.decodeMode === DecodingMode.Strict) {
          return 0;
        }
        this.emitCodePoint(replaceCodePoint(this.result), this.consumed);
        if (this.errors) {
          if (lastCp !== CharCodes.SEMI) {
            this.errors.missingSemicolonAfterCharacterReference();
          }
          this.errors.validateNumericCharacterReference(this.result);
        }
        return this.consumed;
      }
      /**
       * Parses a named entity.
       *
       * Equivalent to the `Named character reference state` in the HTML spec.
       *
       * @param str The string containing the entity (or a continuation of the entity).
       * @param offset The current offset.
       * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
       */
      stateNamedEntity(str2, offset) {
        const { decodeTree } = this;
        let current = decodeTree[this.treeIndex];
        let valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
        for (; offset < str2.length; offset++, this.excess++) {
          const char = str2.charCodeAt(offset);
          this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char);
          if (this.treeIndex < 0) {
            return this.result === 0 || // If we are parsing an attribute
            this.decodeMode === DecodingMode.Attribute && // We shouldn't have consumed any characters after the entity,
            (valueLength === 0 || // And there should be no invalid characters.
            isEntityInAttributeInvalidEnd(char)) ? 0 : this.emitNotTerminatedNamedEntity();
          }
          current = decodeTree[this.treeIndex];
          valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
          if (valueLength !== 0) {
            if (char === CharCodes.SEMI) {
              return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
            }
            if (this.decodeMode !== DecodingMode.Strict) {
              this.result = this.treeIndex;
              this.consumed += this.excess;
              this.excess = 0;
            }
          }
        }
        return -1;
      }
      /**
       * Emit a named entity that was not terminated with a semicolon.
       *
       * @returns The number of characters consumed.
       */
      emitNotTerminatedNamedEntity() {
        var _a6;
        const { result, decodeTree } = this;
        const valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14;
        this.emitNamedEntityData(result, valueLength, this.consumed);
        (_a6 = this.errors) === null || _a6 === void 0 ? void 0 : _a6.missingSemicolonAfterCharacterReference();
        return this.consumed;
      }
      /**
       * Emit a named entity.
       *
       * @param result The index of the entity in the decode tree.
       * @param valueLength The number of bytes in the entity.
       * @param consumed The number of characters consumed.
       *
       * @returns The number of characters consumed.
       */
      emitNamedEntityData(result, valueLength, consumed) {
        const { decodeTree } = this;
        this.emitCodePoint(valueLength === 1 ? decodeTree[result] & ~BinTrieFlags.VALUE_LENGTH : decodeTree[result + 1], consumed);
        if (valueLength === 3) {
          this.emitCodePoint(decodeTree[result + 2], consumed);
        }
        return consumed;
      }
      /**
       * Signal to the parser that the end of the input was reached.
       *
       * Remaining data will be emitted and relevant errors will be produced.
       *
       * @returns The number of characters consumed.
       */
      end() {
        var _a6;
        switch (this.state) {
          case EntityDecoderState.NamedEntity: {
            return this.result !== 0 && (this.decodeMode !== DecodingMode.Attribute || this.result === this.treeIndex) ? this.emitNotTerminatedNamedEntity() : 0;
          }
          // Otherwise, emit a numeric entity if we have one.
          case EntityDecoderState.NumericDecimal: {
            return this.emitNumericEntity(0, 2);
          }
          case EntityDecoderState.NumericHex: {
            return this.emitNumericEntity(0, 3);
          }
          case EntityDecoderState.NumericStart: {
            (_a6 = this.errors) === null || _a6 === void 0 ? void 0 : _a6.absenceOfDigitsInNumericCharacterReference(this.consumed);
            return 0;
          }
          case EntityDecoderState.EntityStart: {
            return 0;
          }
        }
      }
    };
    __name(getDecoder, "getDecoder");
    __name(determineBranch, "determineBranch");
    htmlDecoder = getDecoder(decode_data_html_default);
    xmlDecoder = getDecoder(decode_data_xml_default);
  }
});

// node_modules/htmlparser2/lib/esm/Tokenizer.js
function isWhitespace2(c3) {
  return c3 === CharCodes2.Space || c3 === CharCodes2.NewLine || c3 === CharCodes2.Tab || c3 === CharCodes2.FormFeed || c3 === CharCodes2.CarriageReturn;
}
function isEndOfTagSection(c3) {
  return c3 === CharCodes2.Slash || c3 === CharCodes2.Gt || isWhitespace2(c3);
}
function isNumber2(c3) {
  return c3 >= CharCodes2.Zero && c3 <= CharCodes2.Nine;
}
function isASCIIAlpha(c3) {
  return c3 >= CharCodes2.LowerA && c3 <= CharCodes2.LowerZ || c3 >= CharCodes2.UpperA && c3 <= CharCodes2.UpperZ;
}
function isHexDigit(c3) {
  return c3 >= CharCodes2.UpperA && c3 <= CharCodes2.UpperF || c3 >= CharCodes2.LowerA && c3 <= CharCodes2.LowerF;
}
var CharCodes2, State, QuoteType, Sequences, Tokenizer;
var init_Tokenizer = __esm({
  "node_modules/htmlparser2/lib/esm/Tokenizer.js"() {
    init_esbuild_shims();
    init_decode();
    (function(CharCodes3) {
      CharCodes3[CharCodes3["Tab"] = 9] = "Tab";
      CharCodes3[CharCodes3["NewLine"] = 10] = "NewLine";
      CharCodes3[CharCodes3["FormFeed"] = 12] = "FormFeed";
      CharCodes3[CharCodes3["CarriageReturn"] = 13] = "CarriageReturn";
      CharCodes3[CharCodes3["Space"] = 32] = "Space";
      CharCodes3[CharCodes3["ExclamationMark"] = 33] = "ExclamationMark";
      CharCodes3[CharCodes3["Number"] = 35] = "Number";
      CharCodes3[CharCodes3["Amp"] = 38] = "Amp";
      CharCodes3[CharCodes3["SingleQuote"] = 39] = "SingleQuote";
      CharCodes3[CharCodes3["DoubleQuote"] = 34] = "DoubleQuote";
      CharCodes3[CharCodes3["Dash"] = 45] = "Dash";
      CharCodes3[CharCodes3["Slash"] = 47] = "Slash";
      CharCodes3[CharCodes3["Zero"] = 48] = "Zero";
      CharCodes3[CharCodes3["Nine"] = 57] = "Nine";
      CharCodes3[CharCodes3["Semi"] = 59] = "Semi";
      CharCodes3[CharCodes3["Lt"] = 60] = "Lt";
      CharCodes3[CharCodes3["Eq"] = 61] = "Eq";
      CharCodes3[CharCodes3["Gt"] = 62] = "Gt";
      CharCodes3[CharCodes3["Questionmark"] = 63] = "Questionmark";
      CharCodes3[CharCodes3["UpperA"] = 65] = "UpperA";
      CharCodes3[CharCodes3["LowerA"] = 97] = "LowerA";
      CharCodes3[CharCodes3["UpperF"] = 70] = "UpperF";
      CharCodes3[CharCodes3["LowerF"] = 102] = "LowerF";
      CharCodes3[CharCodes3["UpperZ"] = 90] = "UpperZ";
      CharCodes3[CharCodes3["LowerZ"] = 122] = "LowerZ";
      CharCodes3[CharCodes3["LowerX"] = 120] = "LowerX";
      CharCodes3[CharCodes3["OpeningSquareBracket"] = 91] = "OpeningSquareBracket";
    })(CharCodes2 || (CharCodes2 = {}));
    (function(State2) {
      State2[State2["Text"] = 1] = "Text";
      State2[State2["BeforeTagName"] = 2] = "BeforeTagName";
      State2[State2["InTagName"] = 3] = "InTagName";
      State2[State2["InSelfClosingTag"] = 4] = "InSelfClosingTag";
      State2[State2["BeforeClosingTagName"] = 5] = "BeforeClosingTagName";
      State2[State2["InClosingTagName"] = 6] = "InClosingTagName";
      State2[State2["AfterClosingTagName"] = 7] = "AfterClosingTagName";
      State2[State2["BeforeAttributeName"] = 8] = "BeforeAttributeName";
      State2[State2["InAttributeName"] = 9] = "InAttributeName";
      State2[State2["AfterAttributeName"] = 10] = "AfterAttributeName";
      State2[State2["BeforeAttributeValue"] = 11] = "BeforeAttributeValue";
      State2[State2["InAttributeValueDq"] = 12] = "InAttributeValueDq";
      State2[State2["InAttributeValueSq"] = 13] = "InAttributeValueSq";
      State2[State2["InAttributeValueNq"] = 14] = "InAttributeValueNq";
      State2[State2["BeforeDeclaration"] = 15] = "BeforeDeclaration";
      State2[State2["InDeclaration"] = 16] = "InDeclaration";
      State2[State2["InProcessingInstruction"] = 17] = "InProcessingInstruction";
      State2[State2["BeforeComment"] = 18] = "BeforeComment";
      State2[State2["CDATASequence"] = 19] = "CDATASequence";
      State2[State2["InSpecialComment"] = 20] = "InSpecialComment";
      State2[State2["InCommentLike"] = 21] = "InCommentLike";
      State2[State2["BeforeSpecialS"] = 22] = "BeforeSpecialS";
      State2[State2["SpecialStartSequence"] = 23] = "SpecialStartSequence";
      State2[State2["InSpecialTag"] = 24] = "InSpecialTag";
      State2[State2["BeforeEntity"] = 25] = "BeforeEntity";
      State2[State2["BeforeNumericEntity"] = 26] = "BeforeNumericEntity";
      State2[State2["InNamedEntity"] = 27] = "InNamedEntity";
      State2[State2["InNumericEntity"] = 28] = "InNumericEntity";
      State2[State2["InHexEntity"] = 29] = "InHexEntity";
    })(State || (State = {}));
    __name(isWhitespace2, "isWhitespace");
    __name(isEndOfTagSection, "isEndOfTagSection");
    __name(isNumber2, "isNumber");
    __name(isASCIIAlpha, "isASCIIAlpha");
    __name(isHexDigit, "isHexDigit");
    (function(QuoteType2) {
      QuoteType2[QuoteType2["NoValue"] = 0] = "NoValue";
      QuoteType2[QuoteType2["Unquoted"] = 1] = "Unquoted";
      QuoteType2[QuoteType2["Single"] = 2] = "Single";
      QuoteType2[QuoteType2["Double"] = 3] = "Double";
    })(QuoteType || (QuoteType = {}));
    Sequences = {
      Cdata: new Uint8Array([67, 68, 65, 84, 65, 91]),
      CdataEnd: new Uint8Array([93, 93, 62]),
      CommentEnd: new Uint8Array([45, 45, 62]),
      ScriptEnd: new Uint8Array([60, 47, 115, 99, 114, 105, 112, 116]),
      StyleEnd: new Uint8Array([60, 47, 115, 116, 121, 108, 101]),
      TitleEnd: new Uint8Array([60, 47, 116, 105, 116, 108, 101])
      // `</title`
    };
    Tokenizer = class {
      static {
        __name(this, "Tokenizer");
      }
      constructor({ xmlMode = false, decodeEntities = true }, cbs) {
        this.cbs = cbs;
        this.state = State.Text;
        this.buffer = "";
        this.sectionStart = 0;
        this.index = 0;
        this.baseState = State.Text;
        this.isSpecial = false;
        this.running = true;
        this.offset = 0;
        this.currentSequence = void 0;
        this.sequenceIndex = 0;
        this.trieIndex = 0;
        this.trieCurrent = 0;
        this.entityResult = 0;
        this.entityExcess = 0;
        this.xmlMode = xmlMode;
        this.decodeEntities = decodeEntities;
        this.entityTrie = xmlMode ? decode_data_xml_default : decode_data_html_default;
      }
      reset() {
        this.state = State.Text;
        this.buffer = "";
        this.sectionStart = 0;
        this.index = 0;
        this.baseState = State.Text;
        this.currentSequence = void 0;
        this.running = true;
        this.offset = 0;
      }
      write(chunk) {
        this.offset += this.buffer.length;
        this.buffer = chunk;
        this.parse();
      }
      end() {
        if (this.running)
          this.finish();
      }
      pause() {
        this.running = false;
      }
      resume() {
        this.running = true;
        if (this.index < this.buffer.length + this.offset) {
          this.parse();
        }
      }
      /**
       * The current index within all of the written data.
       */
      getIndex() {
        return this.index;
      }
      /**
       * The start of the current section.
       */
      getSectionStart() {
        return this.sectionStart;
      }
      stateText(c3) {
        if (c3 === CharCodes2.Lt || !this.decodeEntities && this.fastForwardTo(CharCodes2.Lt)) {
          if (this.index > this.sectionStart) {
            this.cbs.ontext(this.sectionStart, this.index);
          }
          this.state = State.BeforeTagName;
          this.sectionStart = this.index;
        } else if (this.decodeEntities && c3 === CharCodes2.Amp) {
          this.state = State.BeforeEntity;
        }
      }
      stateSpecialStartSequence(c3) {
        const isEnd = this.sequenceIndex === this.currentSequence.length;
        const isMatch = isEnd ? (
          // If we are at the end of the sequence, make sure the tag name has ended
          isEndOfTagSection(c3)
        ) : (
          // Otherwise, do a case-insensitive comparison
          (c3 | 32) === this.currentSequence[this.sequenceIndex]
        );
        if (!isMatch) {
          this.isSpecial = false;
        } else if (!isEnd) {
          this.sequenceIndex++;
          return;
        }
        this.sequenceIndex = 0;
        this.state = State.InTagName;
        this.stateInTagName(c3);
      }
      /** Look for an end tag. For <title> tags, also decode entities. */
      stateInSpecialTag(c3) {
        if (this.sequenceIndex === this.currentSequence.length) {
          if (c3 === CharCodes2.Gt || isWhitespace2(c3)) {
            const endOfText = this.index - this.currentSequence.length;
            if (this.sectionStart < endOfText) {
              const actualIndex = this.index;
              this.index = endOfText;
              this.cbs.ontext(this.sectionStart, endOfText);
              this.index = actualIndex;
            }
            this.isSpecial = false;
            this.sectionStart = endOfText + 2;
            this.stateInClosingTagName(c3);
            return;
          }
          this.sequenceIndex = 0;
        }
        if ((c3 | 32) === this.currentSequence[this.sequenceIndex]) {
          this.sequenceIndex += 1;
        } else if (this.sequenceIndex === 0) {
          if (this.currentSequence === Sequences.TitleEnd) {
            if (this.decodeEntities && c3 === CharCodes2.Amp) {
              this.state = State.BeforeEntity;
            }
          } else if (this.fastForwardTo(CharCodes2.Lt)) {
            this.sequenceIndex = 1;
          }
        } else {
          this.sequenceIndex = Number(c3 === CharCodes2.Lt);
        }
      }
      stateCDATASequence(c3) {
        if (c3 === Sequences.Cdata[this.sequenceIndex]) {
          if (++this.sequenceIndex === Sequences.Cdata.length) {
            this.state = State.InCommentLike;
            this.currentSequence = Sequences.CdataEnd;
            this.sequenceIndex = 0;
            this.sectionStart = this.index + 1;
          }
        } else {
          this.sequenceIndex = 0;
          this.state = State.InDeclaration;
          this.stateInDeclaration(c3);
        }
      }
      /**
       * When we wait for one specific character, we can speed things up
       * by skipping through the buffer until we find it.
       *
       * @returns Whether the character was found.
       */
      fastForwardTo(c3) {
        while (++this.index < this.buffer.length + this.offset) {
          if (this.buffer.charCodeAt(this.index - this.offset) === c3) {
            return true;
          }
        }
        this.index = this.buffer.length + this.offset - 1;
        return false;
      }
      /**
       * Comments and CDATA end with `-->` and `]]>`.
       *
       * Their common qualities are:
       * - Their end sequences have a distinct character they start with.
       * - That character is then repeated, so we have to check multiple repeats.
       * - All characters but the start character of the sequence can be skipped.
       */
      stateInCommentLike(c3) {
        if (c3 === this.currentSequence[this.sequenceIndex]) {
          if (++this.sequenceIndex === this.currentSequence.length) {
            if (this.currentSequence === Sequences.CdataEnd) {
              this.cbs.oncdata(this.sectionStart, this.index, 2);
            } else {
              this.cbs.oncomment(this.sectionStart, this.index, 2);
            }
            this.sequenceIndex = 0;
            this.sectionStart = this.index + 1;
            this.state = State.Text;
          }
        } else if (this.sequenceIndex === 0) {
          if (this.fastForwardTo(this.currentSequence[0])) {
            this.sequenceIndex = 1;
          }
        } else if (c3 !== this.currentSequence[this.sequenceIndex - 1]) {
          this.sequenceIndex = 0;
        }
      }
      /**
       * HTML only allows ASCII alpha characters (a-z and A-Z) at the beginning of a tag name.
       *
       * XML allows a lot more characters here (@see https://www.w3.org/TR/REC-xml/#NT-NameStartChar).
       * We allow anything that wouldn't end the tag.
       */
      isTagStartChar(c3) {
        return this.xmlMode ? !isEndOfTagSection(c3) : isASCIIAlpha(c3);
      }
      startSpecial(sequence, offset) {
        this.isSpecial = true;
        this.currentSequence = sequence;
        this.sequenceIndex = offset;
        this.state = State.SpecialStartSequence;
      }
      stateBeforeTagName(c3) {
        if (c3 === CharCodes2.ExclamationMark) {
          this.state = State.BeforeDeclaration;
          this.sectionStart = this.index + 1;
        } else if (c3 === CharCodes2.Questionmark) {
          this.state = State.InProcessingInstruction;
          this.sectionStart = this.index + 1;
        } else if (this.isTagStartChar(c3)) {
          const lower = c3 | 32;
          this.sectionStart = this.index;
          if (!this.xmlMode && lower === Sequences.TitleEnd[2]) {
            this.startSpecial(Sequences.TitleEnd, 3);
          } else {
            this.state = !this.xmlMode && lower === Sequences.ScriptEnd[2] ? State.BeforeSpecialS : State.InTagName;
          }
        } else if (c3 === CharCodes2.Slash) {
          this.state = State.BeforeClosingTagName;
        } else {
          this.state = State.Text;
          this.stateText(c3);
        }
      }
      stateInTagName(c3) {
        if (isEndOfTagSection(c3)) {
          this.cbs.onopentagname(this.sectionStart, this.index);
          this.sectionStart = -1;
          this.state = State.BeforeAttributeName;
          this.stateBeforeAttributeName(c3);
        }
      }
      stateBeforeClosingTagName(c3) {
        if (isWhitespace2(c3)) {
        } else if (c3 === CharCodes2.Gt) {
          this.state = State.Text;
        } else {
          this.state = this.isTagStartChar(c3) ? State.InClosingTagName : State.InSpecialComment;
          this.sectionStart = this.index;
        }
      }
      stateInClosingTagName(c3) {
        if (c3 === CharCodes2.Gt || isWhitespace2(c3)) {
          this.cbs.onclosetag(this.sectionStart, this.index);
          this.sectionStart = -1;
          this.state = State.AfterClosingTagName;
          this.stateAfterClosingTagName(c3);
        }
      }
      stateAfterClosingTagName(c3) {
        if (c3 === CharCodes2.Gt || this.fastForwardTo(CharCodes2.Gt)) {
          this.state = State.Text;
          this.baseState = State.Text;
          this.sectionStart = this.index + 1;
        }
      }
      stateBeforeAttributeName(c3) {
        if (c3 === CharCodes2.Gt) {
          this.cbs.onopentagend(this.index);
          if (this.isSpecial) {
            this.state = State.InSpecialTag;
            this.sequenceIndex = 0;
          } else {
            this.state = State.Text;
          }
          this.baseState = this.state;
          this.sectionStart = this.index + 1;
        } else if (c3 === CharCodes2.Slash) {
          this.state = State.InSelfClosingTag;
        } else if (!isWhitespace2(c3)) {
          this.state = State.InAttributeName;
          this.sectionStart = this.index;
        }
      }
      stateInSelfClosingTag(c3) {
        if (c3 === CharCodes2.Gt) {
          this.cbs.onselfclosingtag(this.index);
          this.state = State.Text;
          this.baseState = State.Text;
          this.sectionStart = this.index + 1;
          this.isSpecial = false;
        } else if (!isWhitespace2(c3)) {
          this.state = State.BeforeAttributeName;
          this.stateBeforeAttributeName(c3);
        }
      }
      stateInAttributeName(c3) {
        if (c3 === CharCodes2.Eq || isEndOfTagSection(c3)) {
          this.cbs.onattribname(this.sectionStart, this.index);
          this.sectionStart = -1;
          this.state = State.AfterAttributeName;
          this.stateAfterAttributeName(c3);
        }
      }
      stateAfterAttributeName(c3) {
        if (c3 === CharCodes2.Eq) {
          this.state = State.BeforeAttributeValue;
        } else if (c3 === CharCodes2.Slash || c3 === CharCodes2.Gt) {
          this.cbs.onattribend(QuoteType.NoValue, this.index);
          this.state = State.BeforeAttributeName;
          this.stateBeforeAttributeName(c3);
        } else if (!isWhitespace2(c3)) {
          this.cbs.onattribend(QuoteType.NoValue, this.index);
          this.state = State.InAttributeName;
          this.sectionStart = this.index;
        }
      }
      stateBeforeAttributeValue(c3) {
        if (c3 === CharCodes2.DoubleQuote) {
          this.state = State.InAttributeValueDq;
          this.sectionStart = this.index + 1;
        } else if (c3 === CharCodes2.SingleQuote) {
          this.state = State.InAttributeValueSq;
          this.sectionStart = this.index + 1;
        } else if (!isWhitespace2(c3)) {
          this.sectionStart = this.index;
          this.state = State.InAttributeValueNq;
          this.stateInAttributeValueNoQuotes(c3);
        }
      }
      handleInAttributeValue(c3, quote3) {
        if (c3 === quote3 || !this.decodeEntities && this.fastForwardTo(quote3)) {
          this.cbs.onattribdata(this.sectionStart, this.index);
          this.sectionStart = -1;
          this.cbs.onattribend(quote3 === CharCodes2.DoubleQuote ? QuoteType.Double : QuoteType.Single, this.index);
          this.state = State.BeforeAttributeName;
        } else if (this.decodeEntities && c3 === CharCodes2.Amp) {
          this.baseState = this.state;
          this.state = State.BeforeEntity;
        }
      }
      stateInAttributeValueDoubleQuotes(c3) {
        this.handleInAttributeValue(c3, CharCodes2.DoubleQuote);
      }
      stateInAttributeValueSingleQuotes(c3) {
        this.handleInAttributeValue(c3, CharCodes2.SingleQuote);
      }
      stateInAttributeValueNoQuotes(c3) {
        if (isWhitespace2(c3) || c3 === CharCodes2.Gt) {
          this.cbs.onattribdata(this.sectionStart, this.index);
          this.sectionStart = -1;
          this.cbs.onattribend(QuoteType.Unquoted, this.index);
          this.state = State.BeforeAttributeName;
          this.stateBeforeAttributeName(c3);
        } else if (this.decodeEntities && c3 === CharCodes2.Amp) {
          this.baseState = this.state;
          this.state = State.BeforeEntity;
        }
      }
      stateBeforeDeclaration(c3) {
        if (c3 === CharCodes2.OpeningSquareBracket) {
          this.state = State.CDATASequence;
          this.sequenceIndex = 0;
        } else {
          this.state = c3 === CharCodes2.Dash ? State.BeforeComment : State.InDeclaration;
        }
      }
      stateInDeclaration(c3) {
        if (c3 === CharCodes2.Gt || this.fastForwardTo(CharCodes2.Gt)) {
          this.cbs.ondeclaration(this.sectionStart, this.index);
          this.state = State.Text;
          this.sectionStart = this.index + 1;
        }
      }
      stateInProcessingInstruction(c3) {
        if (c3 === CharCodes2.Gt || this.fastForwardTo(CharCodes2.Gt)) {
          this.cbs.onprocessinginstruction(this.sectionStart, this.index);
          this.state = State.Text;
          this.sectionStart = this.index + 1;
        }
      }
      stateBeforeComment(c3) {
        if (c3 === CharCodes2.Dash) {
          this.state = State.InCommentLike;
          this.currentSequence = Sequences.CommentEnd;
          this.sequenceIndex = 2;
          this.sectionStart = this.index + 1;
        } else {
          this.state = State.InDeclaration;
        }
      }
      stateInSpecialComment(c3) {
        if (c3 === CharCodes2.Gt || this.fastForwardTo(CharCodes2.Gt)) {
          this.cbs.oncomment(this.sectionStart, this.index, 0);
          this.state = State.Text;
          this.sectionStart = this.index + 1;
        }
      }
      stateBeforeSpecialS(c3) {
        const lower = c3 | 32;
        if (lower === Sequences.ScriptEnd[3]) {
          this.startSpecial(Sequences.ScriptEnd, 4);
        } else if (lower === Sequences.StyleEnd[3]) {
          this.startSpecial(Sequences.StyleEnd, 4);
        } else {
          this.state = State.InTagName;
          this.stateInTagName(c3);
        }
      }
      stateBeforeEntity(c3) {
        this.entityExcess = 1;
        this.entityResult = 0;
        if (c3 === CharCodes2.Number) {
          this.state = State.BeforeNumericEntity;
        } else if (c3 === CharCodes2.Amp) {
        } else {
          this.trieIndex = 0;
          this.trieCurrent = this.entityTrie[0];
          this.state = State.InNamedEntity;
          this.stateInNamedEntity(c3);
        }
      }
      stateInNamedEntity(c3) {
        this.entityExcess += 1;
        this.trieIndex = determineBranch(this.entityTrie, this.trieCurrent, this.trieIndex + 1, c3);
        if (this.trieIndex < 0) {
          this.emitNamedEntity();
          this.index--;
          return;
        }
        this.trieCurrent = this.entityTrie[this.trieIndex];
        const masked = this.trieCurrent & BinTrieFlags.VALUE_LENGTH;
        if (masked) {
          const valueLength = (masked >> 14) - 1;
          if (!this.allowLegacyEntity() && c3 !== CharCodes2.Semi) {
            this.trieIndex += valueLength;
          } else {
            const entityStart = this.index - this.entityExcess + 1;
            if (entityStart > this.sectionStart) {
              this.emitPartial(this.sectionStart, entityStart);
            }
            this.entityResult = this.trieIndex;
            this.trieIndex += valueLength;
            this.entityExcess = 0;
            this.sectionStart = this.index + 1;
            if (valueLength === 0) {
              this.emitNamedEntity();
            }
          }
        }
      }
      emitNamedEntity() {
        this.state = this.baseState;
        if (this.entityResult === 0) {
          return;
        }
        const valueLength = (this.entityTrie[this.entityResult] & BinTrieFlags.VALUE_LENGTH) >> 14;
        switch (valueLength) {
          case 1: {
            this.emitCodePoint(this.entityTrie[this.entityResult] & ~BinTrieFlags.VALUE_LENGTH);
            break;
          }
          case 2: {
            this.emitCodePoint(this.entityTrie[this.entityResult + 1]);
            break;
          }
          case 3: {
            this.emitCodePoint(this.entityTrie[this.entityResult + 1]);
            this.emitCodePoint(this.entityTrie[this.entityResult + 2]);
          }
        }
      }
      stateBeforeNumericEntity(c3) {
        if ((c3 | 32) === CharCodes2.LowerX) {
          this.entityExcess++;
          this.state = State.InHexEntity;
        } else {
          this.state = State.InNumericEntity;
          this.stateInNumericEntity(c3);
        }
      }
      emitNumericEntity(strict) {
        const entityStart = this.index - this.entityExcess - 1;
        const numberStart = entityStart + 2 + Number(this.state === State.InHexEntity);
        if (numberStart !== this.index) {
          if (entityStart > this.sectionStart) {
            this.emitPartial(this.sectionStart, entityStart);
          }
          this.sectionStart = this.index + Number(strict);
          this.emitCodePoint(replaceCodePoint(this.entityResult));
        }
        this.state = this.baseState;
      }
      stateInNumericEntity(c3) {
        if (c3 === CharCodes2.Semi) {
          this.emitNumericEntity(true);
        } else if (isNumber2(c3)) {
          this.entityResult = this.entityResult * 10 + (c3 - CharCodes2.Zero);
          this.entityExcess++;
        } else {
          if (this.allowLegacyEntity()) {
            this.emitNumericEntity(false);
          } else {
            this.state = this.baseState;
          }
          this.index--;
        }
      }
      stateInHexEntity(c3) {
        if (c3 === CharCodes2.Semi) {
          this.emitNumericEntity(true);
        } else if (isNumber2(c3)) {
          this.entityResult = this.entityResult * 16 + (c3 - CharCodes2.Zero);
          this.entityExcess++;
        } else if (isHexDigit(c3)) {
          this.entityResult = this.entityResult * 16 + ((c3 | 32) - CharCodes2.LowerA + 10);
          this.entityExcess++;
        } else {
          if (this.allowLegacyEntity()) {
            this.emitNumericEntity(false);
          } else {
            this.state = this.baseState;
          }
          this.index--;
        }
      }
      allowLegacyEntity() {
        return !this.xmlMode && (this.baseState === State.Text || this.baseState === State.InSpecialTag);
      }
      /**
       * Remove data that has already been consumed from the buffer.
       */
      cleanup() {
        if (this.running && this.sectionStart !== this.index) {
          if (this.state === State.Text || this.state === State.InSpecialTag && this.sequenceIndex === 0) {
            this.cbs.ontext(this.sectionStart, this.index);
            this.sectionStart = this.index;
          } else if (this.state === State.InAttributeValueDq || this.state === State.InAttributeValueSq || this.state === State.InAttributeValueNq) {
            this.cbs.onattribdata(this.sectionStart, this.index);
            this.sectionStart = this.index;
          }
        }
      }
      shouldContinue() {
        return this.index < this.buffer.length + this.offset && this.running;
      }
      /**
       * Iterates through the buffer, calling the function corresponding to the current state.
       *
       * States that are more likely to be hit are higher up, as a performance improvement.
       */
      parse() {
        while (this.shouldContinue()) {
          const c3 = this.buffer.charCodeAt(this.index - this.offset);
          switch (this.state) {
            case State.Text: {
              this.stateText(c3);
              break;
            }
            case State.SpecialStartSequence: {
              this.stateSpecialStartSequence(c3);
              break;
            }
            case State.InSpecialTag: {
              this.stateInSpecialTag(c3);
              break;
            }
            case State.CDATASequence: {
              this.stateCDATASequence(c3);
              break;
            }
            case State.InAttributeValueDq: {
              this.stateInAttributeValueDoubleQuotes(c3);
              break;
            }
            case State.InAttributeName: {
              this.stateInAttributeName(c3);
              break;
            }
            case State.InCommentLike: {
              this.stateInCommentLike(c3);
              break;
            }
            case State.InSpecialComment: {
              this.stateInSpecialComment(c3);
              break;
            }
            case State.BeforeAttributeName: {
              this.stateBeforeAttributeName(c3);
              break;
            }
            case State.InTagName: {
              this.stateInTagName(c3);
              break;
            }
            case State.InClosingTagName: {
              this.stateInClosingTagName(c3);
              break;
            }
            case State.BeforeTagName: {
              this.stateBeforeTagName(c3);
              break;
            }
            case State.AfterAttributeName: {
              this.stateAfterAttributeName(c3);
              break;
            }
            case State.InAttributeValueSq: {
              this.stateInAttributeValueSingleQuotes(c3);
              break;
            }
            case State.BeforeAttributeValue: {
              this.stateBeforeAttributeValue(c3);
              break;
            }
            case State.BeforeClosingTagName: {
              this.stateBeforeClosingTagName(c3);
              break;
            }
            case State.AfterClosingTagName: {
              this.stateAfterClosingTagName(c3);
              break;
            }
            case State.BeforeSpecialS: {
              this.stateBeforeSpecialS(c3);
              break;
            }
            case State.InAttributeValueNq: {
              this.stateInAttributeValueNoQuotes(c3);
              break;
            }
            case State.InSelfClosingTag: {
              this.stateInSelfClosingTag(c3);
              break;
            }
            case State.InDeclaration: {
              this.stateInDeclaration(c3);
              break;
            }
            case State.BeforeDeclaration: {
              this.stateBeforeDeclaration(c3);
              break;
            }
            case State.BeforeComment: {
              this.stateBeforeComment(c3);
              break;
            }
            case State.InProcessingInstruction: {
              this.stateInProcessingInstruction(c3);
              break;
            }
            case State.InNamedEntity: {
              this.stateInNamedEntity(c3);
              break;
            }
            case State.BeforeEntity: {
              this.stateBeforeEntity(c3);
              break;
            }
            case State.InHexEntity: {
              this.stateInHexEntity(c3);
              break;
            }
            case State.InNumericEntity: {
              this.stateInNumericEntity(c3);
              break;
            }
            default: {
              this.stateBeforeNumericEntity(c3);
            }
          }
          this.index++;
        }
        this.cleanup();
      }
      finish() {
        if (this.state === State.InNamedEntity) {
          this.emitNamedEntity();
        }
        if (this.sectionStart < this.index) {
          this.handleTrailingData();
        }
        this.cbs.onend();
      }
      /** Handle any trailing data. */
      handleTrailingData() {
        const endIndex = this.buffer.length + this.offset;
        if (this.state === State.InCommentLike) {
          if (this.currentSequence === Sequences.CdataEnd) {
            this.cbs.oncdata(this.sectionStart, endIndex, 0);
          } else {
            this.cbs.oncomment(this.sectionStart, endIndex, 0);
          }
        } else if (this.state === State.InNumericEntity && this.allowLegacyEntity()) {
          this.emitNumericEntity(false);
        } else if (this.state === State.InHexEntity && this.allowLegacyEntity()) {
          this.emitNumericEntity(false);
        } else if (this.state === State.InTagName || this.state === State.BeforeAttributeName || this.state === State.BeforeAttributeValue || this.state === State.AfterAttributeName || this.state === State.InAttributeName || this.state === State.InAttributeValueSq || this.state === State.InAttributeValueDq || this.state === State.InAttributeValueNq || this.state === State.InClosingTagName) {
        } else {
          this.cbs.ontext(this.sectionStart, endIndex);
        }
      }
      emitPartial(start, endIndex) {
        if (this.baseState !== State.Text && this.baseState !== State.InSpecialTag) {
          this.cbs.onattribdata(start, endIndex);
        } else {
          this.cbs.ontext(start, endIndex);
        }
      }
      emitCodePoint(cp2) {
        if (this.baseState !== State.Text && this.baseState !== State.InSpecialTag) {
          this.cbs.onattribentity(cp2);
        } else {
          this.cbs.ontextentity(cp2);
        }
      }
    };
  }
});

// node_modules/htmlparser2/lib/esm/Parser.js
var formTags, pTag, tableSectionTags, ddtTags, rtpTags, openImpliesClose, voidElements, foreignContextElements, htmlIntegrationElements, reNameEnd, Parser;
var init_Parser = __esm({
  "node_modules/htmlparser2/lib/esm/Parser.js"() {
    init_esbuild_shims();
    init_Tokenizer();
    init_decode();
    formTags = /* @__PURE__ */ new Set([
      "input",
      "option",
      "optgroup",
      "select",
      "button",
      "datalist",
      "textarea"
    ]);
    pTag = /* @__PURE__ */ new Set(["p"]);
    tableSectionTags = /* @__PURE__ */ new Set(["thead", "tbody"]);
    ddtTags = /* @__PURE__ */ new Set(["dd", "dt"]);
    rtpTags = /* @__PURE__ */ new Set(["rt", "rp"]);
    openImpliesClose = /* @__PURE__ */ new Map([
      ["tr", /* @__PURE__ */ new Set(["tr", "th", "td"])],
      ["th", /* @__PURE__ */ new Set(["th"])],
      ["td", /* @__PURE__ */ new Set(["thead", "th", "td"])],
      ["body", /* @__PURE__ */ new Set(["head", "link", "script"])],
      ["li", /* @__PURE__ */ new Set(["li"])],
      ["p", pTag],
      ["h1", pTag],
      ["h2", pTag],
      ["h3", pTag],
      ["h4", pTag],
      ["h5", pTag],
      ["h6", pTag],
      ["select", formTags],
      ["input", formTags],
      ["output", formTags],
      ["button", formTags],
      ["datalist", formTags],
      ["textarea", formTags],
      ["option", /* @__PURE__ */ new Set(["option"])],
      ["optgroup", /* @__PURE__ */ new Set(["optgroup", "option"])],
      ["dd", ddtTags],
      ["dt", ddtTags],
      ["address", pTag],
      ["article", pTag],
      ["aside", pTag],
      ["blockquote", pTag],
      ["details", pTag],
      ["div", pTag],
      ["dl", pTag],
      ["fieldset", pTag],
      ["figcaption", pTag],
      ["figure", pTag],
      ["footer", pTag],
      ["form", pTag],
      ["header", pTag],
      ["hr", pTag],
      ["main", pTag],
      ["nav", pTag],
      ["ol", pTag],
      ["pre", pTag],
      ["section", pTag],
      ["table", pTag],
      ["ul", pTag],
      ["rt", rtpTags],
      ["rp", rtpTags],
      ["tbody", tableSectionTags],
      ["tfoot", tableSectionTags]
    ]);
    voidElements = /* @__PURE__ */ new Set([
      "area",
      "base",
      "basefont",
      "br",
      "col",
      "command",
      "embed",
      "frame",
      "hr",
      "img",
      "input",
      "isindex",
      "keygen",
      "link",
      "meta",
      "param",
      "source",
      "track",
      "wbr"
    ]);
    foreignContextElements = /* @__PURE__ */ new Set(["math", "svg"]);
    htmlIntegrationElements = /* @__PURE__ */ new Set([
      "mi",
      "mo",
      "mn",
      "ms",
      "mtext",
      "annotation-xml",
      "foreignobject",
      "desc",
      "title"
    ]);
    reNameEnd = /\s|\//;
    Parser = class {
      static {
        __name(this, "Parser");
      }
      constructor(cbs, options2 = {}) {
        var _a6, _b2, _c2, _d, _e;
        this.options = options2;
        this.startIndex = 0;
        this.endIndex = 0;
        this.openTagStart = 0;
        this.tagname = "";
        this.attribname = "";
        this.attribvalue = "";
        this.attribs = null;
        this.stack = [];
        this.foreignContext = [];
        this.buffers = [];
        this.bufferOffset = 0;
        this.writeIndex = 0;
        this.ended = false;
        this.cbs = cbs !== null && cbs !== void 0 ? cbs : {};
        this.lowerCaseTagNames = (_a6 = options2.lowerCaseTags) !== null && _a6 !== void 0 ? _a6 : !options2.xmlMode;
        this.lowerCaseAttributeNames = (_b2 = options2.lowerCaseAttributeNames) !== null && _b2 !== void 0 ? _b2 : !options2.xmlMode;
        this.tokenizer = new ((_c2 = options2.Tokenizer) !== null && _c2 !== void 0 ? _c2 : Tokenizer)(this.options, this);
        (_e = (_d = this.cbs).onparserinit) === null || _e === void 0 ? void 0 : _e.call(_d, this);
      }
      // Tokenizer event handlers
      /** @internal */
      ontext(start, endIndex) {
        var _a6, _b2;
        const data = this.getSlice(start, endIndex);
        this.endIndex = endIndex - 1;
        (_b2 = (_a6 = this.cbs).ontext) === null || _b2 === void 0 ? void 0 : _b2.call(_a6, data);
        this.startIndex = endIndex;
      }
      /** @internal */
      ontextentity(cp2) {
        var _a6, _b2;
        const index = this.tokenizer.getSectionStart();
        this.endIndex = index - 1;
        (_b2 = (_a6 = this.cbs).ontext) === null || _b2 === void 0 ? void 0 : _b2.call(_a6, fromCodePoint(cp2));
        this.startIndex = index;
      }
      isVoidElement(name3) {
        return !this.options.xmlMode && voidElements.has(name3);
      }
      /** @internal */
      onopentagname(start, endIndex) {
        this.endIndex = endIndex;
        let name3 = this.getSlice(start, endIndex);
        if (this.lowerCaseTagNames) {
          name3 = name3.toLowerCase();
        }
        this.emitOpenTag(name3);
      }
      emitOpenTag(name3) {
        var _a6, _b2, _c2, _d;
        this.openTagStart = this.startIndex;
        this.tagname = name3;
        const impliesClose = !this.options.xmlMode && openImpliesClose.get(name3);
        if (impliesClose) {
          while (this.stack.length > 0 && impliesClose.has(this.stack[this.stack.length - 1])) {
            const element = this.stack.pop();
            (_b2 = (_a6 = this.cbs).onclosetag) === null || _b2 === void 0 ? void 0 : _b2.call(_a6, element, true);
          }
        }
        if (!this.isVoidElement(name3)) {
          this.stack.push(name3);
          if (foreignContextElements.has(name3)) {
            this.foreignContext.push(true);
          } else if (htmlIntegrationElements.has(name3)) {
            this.foreignContext.push(false);
          }
        }
        (_d = (_c2 = this.cbs).onopentagname) === null || _d === void 0 ? void 0 : _d.call(_c2, name3);
        if (this.cbs.onopentag)
          this.attribs = {};
      }
      endOpenTag(isImplied) {
        var _a6, _b2;
        this.startIndex = this.openTagStart;
        if (this.attribs) {
          (_b2 = (_a6 = this.cbs).onopentag) === null || _b2 === void 0 ? void 0 : _b2.call(_a6, this.tagname, this.attribs, isImplied);
          this.attribs = null;
        }
        if (this.cbs.onclosetag && this.isVoidElement(this.tagname)) {
          this.cbs.onclosetag(this.tagname, true);
        }
        this.tagname = "";
      }
      /** @internal */
      onopentagend(endIndex) {
        this.endIndex = endIndex;
        this.endOpenTag(false);
        this.startIndex = endIndex + 1;
      }
      /** @internal */
      onclosetag(start, endIndex) {
        var _a6, _b2, _c2, _d, _e, _f;
        this.endIndex = endIndex;
        let name3 = this.getSlice(start, endIndex);
        if (this.lowerCaseTagNames) {
          name3 = name3.toLowerCase();
        }
        if (foreignContextElements.has(name3) || htmlIntegrationElements.has(name3)) {
          this.foreignContext.pop();
        }
        if (!this.isVoidElement(name3)) {
          const pos2 = this.stack.lastIndexOf(name3);
          if (pos2 !== -1) {
            if (this.cbs.onclosetag) {
              let count = this.stack.length - pos2;
              while (count--) {
                this.cbs.onclosetag(this.stack.pop(), count !== 0);
              }
            } else
              this.stack.length = pos2;
          } else if (!this.options.xmlMode && name3 === "p") {
            this.emitOpenTag("p");
            this.closeCurrentTag(true);
          }
        } else if (!this.options.xmlMode && name3 === "br") {
          (_b2 = (_a6 = this.cbs).onopentagname) === null || _b2 === void 0 ? void 0 : _b2.call(_a6, "br");
          (_d = (_c2 = this.cbs).onopentag) === null || _d === void 0 ? void 0 : _d.call(_c2, "br", {}, true);
          (_f = (_e = this.cbs).onclosetag) === null || _f === void 0 ? void 0 : _f.call(_e, "br", false);
        }
        this.startIndex = endIndex + 1;
      }
      /** @internal */
      onselfclosingtag(endIndex) {
        this.endIndex = endIndex;
        if (this.options.xmlMode || this.options.recognizeSelfClosing || this.foreignContext[this.foreignContext.length - 1]) {
          this.closeCurrentTag(false);
          this.startIndex = endIndex + 1;
        } else {
          this.onopentagend(endIndex);
        }
      }
      closeCurrentTag(isOpenImplied) {
        var _a6, _b2;
        const name3 = this.tagname;
        this.endOpenTag(isOpenImplied);
        if (this.stack[this.stack.length - 1] === name3) {
          (_b2 = (_a6 = this.cbs).onclosetag) === null || _b2 === void 0 ? void 0 : _b2.call(_a6, name3, !isOpenImplied);
          this.stack.pop();
        }
      }
      /** @internal */
      onattribname(start, endIndex) {
        this.startIndex = start;
        const name3 = this.getSlice(start, endIndex);
        this.attribname = this.lowerCaseAttributeNames ? name3.toLowerCase() : name3;
      }
      /** @internal */
      onattribdata(start, endIndex) {
        this.attribvalue += this.getSlice(start, endIndex);
      }
      /** @internal */
      onattribentity(cp2) {
        this.attribvalue += fromCodePoint(cp2);
      }
      /** @internal */
      onattribend(quote3, endIndex) {
        var _a6, _b2;
        this.endIndex = endIndex;
        (_b2 = (_a6 = this.cbs).onattribute) === null || _b2 === void 0 ? void 0 : _b2.call(_a6, this.attribname, this.attribvalue, quote3 === QuoteType.Double ? '"' : quote3 === QuoteType.Single ? "'" : quote3 === QuoteType.NoValue ? void 0 : null);
        if (this.attribs && !Object.prototype.hasOwnProperty.call(this.attribs, this.attribname)) {
          this.attribs[this.attribname] = this.attribvalue;
        }
        this.attribvalue = "";
      }
      getInstructionName(value) {
        const index = value.search(reNameEnd);
        let name3 = index < 0 ? value : value.substr(0, index);
        if (this.lowerCaseTagNames) {
          name3 = name3.toLowerCase();
        }
        return name3;
      }
      /** @internal */
      ondeclaration(start, endIndex) {
        this.endIndex = endIndex;
        const value = this.getSlice(start, endIndex);
        if (this.cbs.onprocessinginstruction) {
          const name3 = this.getInstructionName(value);
          this.cbs.onprocessinginstruction(`!${name3}`, `!${value}`);
        }
        this.startIndex = endIndex + 1;
      }
      /** @internal */
      onprocessinginstruction(start, endIndex) {
        this.endIndex = endIndex;
        const value = this.getSlice(start, endIndex);
        if (this.cbs.onprocessinginstruction) {
          const name3 = this.getInstructionName(value);
          this.cbs.onprocessinginstruction(`?${name3}`, `?${value}`);
        }
        this.startIndex = endIndex + 1;
      }
      /** @internal */
      oncomment(start, endIndex, offset) {
        var _a6, _b2, _c2, _d;
        this.endIndex = endIndex;
        (_b2 = (_a6 = this.cbs).oncomment) === null || _b2 === void 0 ? void 0 : _b2.call(_a6, this.getSlice(start, endIndex - offset));
        (_d = (_c2 = this.cbs).oncommentend) === null || _d === void 0 ? void 0 : _d.call(_c2);
        this.startIndex = endIndex + 1;
      }
      /** @internal */
      oncdata(start, endIndex, offset) {
        var _a6, _b2, _c2, _d, _e, _f, _g, _h, _j, _k;
        this.endIndex = endIndex;
        const value = this.getSlice(start, endIndex - offset);
        if (this.options.xmlMode || this.options.recognizeCDATA) {
          (_b2 = (_a6 = this.cbs).oncdatastart) === null || _b2 === void 0 ? void 0 : _b2.call(_a6);
          (_d = (_c2 = this.cbs).ontext) === null || _d === void 0 ? void 0 : _d.call(_c2, value);
          (_f = (_e = this.cbs).oncdataend) === null || _f === void 0 ? void 0 : _f.call(_e);
        } else {
          (_h = (_g = this.cbs).oncomment) === null || _h === void 0 ? void 0 : _h.call(_g, `[CDATA[${value}]]`);
          (_k = (_j = this.cbs).oncommentend) === null || _k === void 0 ? void 0 : _k.call(_j);
        }
        this.startIndex = endIndex + 1;
      }
      /** @internal */
      onend() {
        var _a6, _b2;
        if (this.cbs.onclosetag) {
          this.endIndex = this.startIndex;
          for (let index = this.stack.length; index > 0; this.cbs.onclosetag(this.stack[--index], true))
            ;
        }
        (_b2 = (_a6 = this.cbs).onend) === null || _b2 === void 0 ? void 0 : _b2.call(_a6);
      }
      /**
       * Resets the parser to a blank state, ready to parse a new HTML document
       */
      reset() {
        var _a6, _b2, _c2, _d;
        (_b2 = (_a6 = this.cbs).onreset) === null || _b2 === void 0 ? void 0 : _b2.call(_a6);
        this.tokenizer.reset();
        this.tagname = "";
        this.attribname = "";
        this.attribs = null;
        this.stack.length = 0;
        this.startIndex = 0;
        this.endIndex = 0;
        (_d = (_c2 = this.cbs).onparserinit) === null || _d === void 0 ? void 0 : _d.call(_c2, this);
        this.buffers.length = 0;
        this.bufferOffset = 0;
        this.writeIndex = 0;
        this.ended = false;
      }
      /**
       * Resets the parser, then parses a complete document and
       * pushes it to the handler.
       *
       * @param data Document to parse.
       */
      parseComplete(data) {
        this.reset();
        this.end(data);
      }
      getSlice(start, end) {
        while (start - this.bufferOffset >= this.buffers[0].length) {
          this.shiftBuffer();
        }
        let slice = this.buffers[0].slice(start - this.bufferOffset, end - this.bufferOffset);
        while (end - this.bufferOffset > this.buffers[0].length) {
          this.shiftBuffer();
          slice += this.buffers[0].slice(0, end - this.bufferOffset);
        }
        return slice;
      }
      shiftBuffer() {
        this.bufferOffset += this.buffers[0].length;
        this.writeIndex--;
        this.buffers.shift();
      }
      /**
       * Parses a chunk of data and calls the corresponding callbacks.
       *
       * @param chunk Chunk to parse.
       */
      write(chunk) {
        var _a6, _b2;
        if (this.ended) {
          (_b2 = (_a6 = this.cbs).onerror) === null || _b2 === void 0 ? void 0 : _b2.call(_a6, new Error(".write() after done!"));
          return;
        }
        this.buffers.push(chunk);
        if (this.tokenizer.running) {
          this.tokenizer.write(chunk);
          this.writeIndex++;
        }
      }
      /**
       * Parses the end of the buffer and clears the stack, calls onend.
       *
       * @param chunk Optional final chunk to parse.
       */
      end(chunk) {
        var _a6, _b2;
        if (this.ended) {
          (_b2 = (_a6 = this.cbs).onerror) === null || _b2 === void 0 ? void 0 : _b2.call(_a6, new Error(".end() after done!"));
          return;
        }
        if (chunk)
          this.write(chunk);
        this.ended = true;
        this.tokenizer.end();
      }
      /**
       * Pauses parsing. The parser won't emit events until `resume` is called.
       */
      pause() {
        this.tokenizer.pause();
      }
      /**
       * Resumes parsing after `pause` was called.
       */
      resume() {
        this.tokenizer.resume();
        while (this.tokenizer.running && this.writeIndex < this.buffers.length) {
          this.tokenizer.write(this.buffers[this.writeIndex++]);
        }
        if (this.ended)
          this.tokenizer.end();
      }
      /**
       * Alias of `write`, for backwards compatibility.
       *
       * @param chunk Chunk to parse.
       * @deprecated
       */
      parseChunk(chunk) {
        this.write(chunk);
      }
      /**
       * Alias of `end`, for backwards compatibility.
       *
       * @param chunk Optional final chunk to parse.
       * @deprecated
       */
      done(chunk) {
        this.end(chunk);
      }
    };
  }
});

// node_modules/entities/lib/esm/generated/encode-html.js
function restoreDiff(arr) {
  for (let i = 1; i < arr.length; i++) {
    arr[i][0] += arr[i - 1][0] + 1;
  }
  return arr;
}
var encode_html_default;
var init_encode_html = __esm({
  "node_modules/entities/lib/esm/generated/encode-html.js"() {
    init_esbuild_shims();
    __name(restoreDiff, "restoreDiff");
    encode_html_default = new Map(/* @__PURE__ */ restoreDiff([[9, "&Tab;"], [0, "&NewLine;"], [22, "&excl;"], [0, "&quot;"], [0, "&num;"], [0, "&dollar;"], [0, "&percnt;"], [0, "&amp;"], [0, "&apos;"], [0, "&lpar;"], [0, "&rpar;"], [0, "&ast;"], [0, "&plus;"], [0, "&comma;"], [1, "&period;"], [0, "&sol;"], [10, "&colon;"], [0, "&semi;"], [0, { v: "&lt;", n: 8402, o: "&nvlt;" }], [0, { v: "&equals;", n: 8421, o: "&bne;" }], [0, { v: "&gt;", n: 8402, o: "&nvgt;" }], [0, "&quest;"], [0, "&commat;"], [26, "&lbrack;"], [0, "&bsol;"], [0, "&rbrack;"], [0, "&Hat;"], [0, "&lowbar;"], [0, "&DiacriticalGrave;"], [5, { n: 106, o: "&fjlig;" }], [20, "&lbrace;"], [0, "&verbar;"], [0, "&rbrace;"], [34, "&nbsp;"], [0, "&iexcl;"], [0, "&cent;"], [0, "&pound;"], [0, "&curren;"], [0, "&yen;"], [0, "&brvbar;"], [0, "&sect;"], [0, "&die;"], [0, "&copy;"], [0, "&ordf;"], [0, "&laquo;"], [0, "&not;"], [0, "&shy;"], [0, "&circledR;"], [0, "&macr;"], [0, "&deg;"], [0, "&PlusMinus;"], [0, "&sup2;"], [0, "&sup3;"], [0, "&acute;"], [0, "&micro;"], [0, "&para;"], [0, "&centerdot;"], [0, "&cedil;"], [0, "&sup1;"], [0, "&ordm;"], [0, "&raquo;"], [0, "&frac14;"], [0, "&frac12;"], [0, "&frac34;"], [0, "&iquest;"], [0, "&Agrave;"], [0, "&Aacute;"], [0, "&Acirc;"], [0, "&Atilde;"], [0, "&Auml;"], [0, "&angst;"], [0, "&AElig;"], [0, "&Ccedil;"], [0, "&Egrave;"], [0, "&Eacute;"], [0, "&Ecirc;"], [0, "&Euml;"], [0, "&Igrave;"], [0, "&Iacute;"], [0, "&Icirc;"], [0, "&Iuml;"], [0, "&ETH;"], [0, "&Ntilde;"], [0, "&Ograve;"], [0, "&Oacute;"], [0, "&Ocirc;"], [0, "&Otilde;"], [0, "&Ouml;"], [0, "&times;"], [0, "&Oslash;"], [0, "&Ugrave;"], [0, "&Uacute;"], [0, "&Ucirc;"], [0, "&Uuml;"], [0, "&Yacute;"], [0, "&THORN;"], [0, "&szlig;"], [0, "&agrave;"], [0, "&aacute;"], [0, "&acirc;"], [0, "&atilde;"], [0, "&auml;"], [0, "&aring;"], [0, "&aelig;"], [0, "&ccedil;"], [0, "&egrave;"], [0, "&eacute;"], [0, "&ecirc;"], [0, "&euml;"], [0, "&igrave;"], [0, "&iacute;"], [0, "&icirc;"], [0, "&iuml;"], [0, "&eth;"], [0, "&ntilde;"], [0, "&ograve;"], [0, "&oacute;"], [0, "&ocirc;"], [0, "&otilde;"], [0, "&ouml;"], [0, "&div;"], [0, "&oslash;"], [0, "&ugrave;"], [0, "&uacute;"], [0, "&ucirc;"], [0, "&uuml;"], [0, "&yacute;"], [0, "&thorn;"], [0, "&yuml;"], [0, "&Amacr;"], [0, "&amacr;"], [0, "&Abreve;"], [0, "&abreve;"], [0, "&Aogon;"], [0, "&aogon;"], [0, "&Cacute;"], [0, "&cacute;"], [0, "&Ccirc;"], [0, "&ccirc;"], [0, "&Cdot;"], [0, "&cdot;"], [0, "&Ccaron;"], [0, "&ccaron;"], [0, "&Dcaron;"], [0, "&dcaron;"], [0, "&Dstrok;"], [0, "&dstrok;"], [0, "&Emacr;"], [0, "&emacr;"], [2, "&Edot;"], [0, "&edot;"], [0, "&Eogon;"], [0, "&eogon;"], [0, "&Ecaron;"], [0, "&ecaron;"], [0, "&Gcirc;"], [0, "&gcirc;"], [0, "&Gbreve;"], [0, "&gbreve;"], [0, "&Gdot;"], [0, "&gdot;"], [0, "&Gcedil;"], [1, "&Hcirc;"], [0, "&hcirc;"], [0, "&Hstrok;"], [0, "&hstrok;"], [0, "&Itilde;"], [0, "&itilde;"], [0, "&Imacr;"], [0, "&imacr;"], [2, "&Iogon;"], [0, "&iogon;"], [0, "&Idot;"], [0, "&imath;"], [0, "&IJlig;"], [0, "&ijlig;"], [0, "&Jcirc;"], [0, "&jcirc;"], [0, "&Kcedil;"], [0, "&kcedil;"], [0, "&kgreen;"], [0, "&Lacute;"], [0, "&lacute;"], [0, "&Lcedil;"], [0, "&lcedil;"], [0, "&Lcaron;"], [0, "&lcaron;"], [0, "&Lmidot;"], [0, "&lmidot;"], [0, "&Lstrok;"], [0, "&lstrok;"], [0, "&Nacute;"], [0, "&nacute;"], [0, "&Ncedil;"], [0, "&ncedil;"], [0, "&Ncaron;"], [0, "&ncaron;"], [0, "&napos;"], [0, "&ENG;"], [0, "&eng;"], [0, "&Omacr;"], [0, "&omacr;"], [2, "&Odblac;"], [0, "&odblac;"], [0, "&OElig;"], [0, "&oelig;"], [0, "&Racute;"], [0, "&racute;"], [0, "&Rcedil;"], [0, "&rcedil;"], [0, "&Rcaron;"], [0, "&rcaron;"], [0, "&Sacute;"], [0, "&sacute;"], [0, "&Scirc;"], [0, "&scirc;"], [0, "&Scedil;"], [0, "&scedil;"], [0, "&Scaron;"], [0, "&scaron;"], [0, "&Tcedil;"], [0, "&tcedil;"], [0, "&Tcaron;"], [0, "&tcaron;"], [0, "&Tstrok;"], [0, "&tstrok;"], [0, "&Utilde;"], [0, "&utilde;"], [0, "&Umacr;"], [0, "&umacr;"], [0, "&Ubreve;"], [0, "&ubreve;"], [0, "&Uring;"], [0, "&uring;"], [0, "&Udblac;"], [0, "&udblac;"], [0, "&Uogon;"], [0, "&uogon;"], [0, "&Wcirc;"], [0, "&wcirc;"], [0, "&Ycirc;"], [0, "&ycirc;"], [0, "&Yuml;"], [0, "&Zacute;"], [0, "&zacute;"], [0, "&Zdot;"], [0, "&zdot;"], [0, "&Zcaron;"], [0, "&zcaron;"], [19, "&fnof;"], [34, "&imped;"], [63, "&gacute;"], [65, "&jmath;"], [142, "&circ;"], [0, "&caron;"], [16, "&breve;"], [0, "&DiacriticalDot;"], [0, "&ring;"], [0, "&ogon;"], [0, "&DiacriticalTilde;"], [0, "&dblac;"], [51, "&DownBreve;"], [127, "&Alpha;"], [0, "&Beta;"], [0, "&Gamma;"], [0, "&Delta;"], [0, "&Epsilon;"], [0, "&Zeta;"], [0, "&Eta;"], [0, "&Theta;"], [0, "&Iota;"], [0, "&Kappa;"], [0, "&Lambda;"], [0, "&Mu;"], [0, "&Nu;"], [0, "&Xi;"], [0, "&Omicron;"], [0, "&Pi;"], [0, "&Rho;"], [1, "&Sigma;"], [0, "&Tau;"], [0, "&Upsilon;"], [0, "&Phi;"], [0, "&Chi;"], [0, "&Psi;"], [0, "&ohm;"], [7, "&alpha;"], [0, "&beta;"], [0, "&gamma;"], [0, "&delta;"], [0, "&epsi;"], [0, "&zeta;"], [0, "&eta;"], [0, "&theta;"], [0, "&iota;"], [0, "&kappa;"], [0, "&lambda;"], [0, "&mu;"], [0, "&nu;"], [0, "&xi;"], [0, "&omicron;"], [0, "&pi;"], [0, "&rho;"], [0, "&sigmaf;"], [0, "&sigma;"], [0, "&tau;"], [0, "&upsi;"], [0, "&phi;"], [0, "&chi;"], [0, "&psi;"], [0, "&omega;"], [7, "&thetasym;"], [0, "&Upsi;"], [2, "&phiv;"], [0, "&piv;"], [5, "&Gammad;"], [0, "&digamma;"], [18, "&kappav;"], [0, "&rhov;"], [3, "&epsiv;"], [0, "&backepsilon;"], [10, "&IOcy;"], [0, "&DJcy;"], [0, "&GJcy;"], [0, "&Jukcy;"], [0, "&DScy;"], [0, "&Iukcy;"], [0, "&YIcy;"], [0, "&Jsercy;"], [0, "&LJcy;"], [0, "&NJcy;"], [0, "&TSHcy;"], [0, "&KJcy;"], [1, "&Ubrcy;"], [0, "&DZcy;"], [0, "&Acy;"], [0, "&Bcy;"], [0, "&Vcy;"], [0, "&Gcy;"], [0, "&Dcy;"], [0, "&IEcy;"], [0, "&ZHcy;"], [0, "&Zcy;"], [0, "&Icy;"], [0, "&Jcy;"], [0, "&Kcy;"], [0, "&Lcy;"], [0, "&Mcy;"], [0, "&Ncy;"], [0, "&Ocy;"], [0, "&Pcy;"], [0, "&Rcy;"], [0, "&Scy;"], [0, "&Tcy;"], [0, "&Ucy;"], [0, "&Fcy;"], [0, "&KHcy;"], [0, "&TScy;"], [0, "&CHcy;"], [0, "&SHcy;"], [0, "&SHCHcy;"], [0, "&HARDcy;"], [0, "&Ycy;"], [0, "&SOFTcy;"], [0, "&Ecy;"], [0, "&YUcy;"], [0, "&YAcy;"], [0, "&acy;"], [0, "&bcy;"], [0, "&vcy;"], [0, "&gcy;"], [0, "&dcy;"], [0, "&iecy;"], [0, "&zhcy;"], [0, "&zcy;"], [0, "&icy;"], [0, "&jcy;"], [0, "&kcy;"], [0, "&lcy;"], [0, "&mcy;"], [0, "&ncy;"], [0, "&ocy;"], [0, "&pcy;"], [0, "&rcy;"], [0, "&scy;"], [0, "&tcy;"], [0, "&ucy;"], [0, "&fcy;"], [0, "&khcy;"], [0, "&tscy;"], [0, "&chcy;"], [0, "&shcy;"], [0, "&shchcy;"], [0, "&hardcy;"], [0, "&ycy;"], [0, "&softcy;"], [0, "&ecy;"], [0, "&yucy;"], [0, "&yacy;"], [1, "&iocy;"], [0, "&djcy;"], [0, "&gjcy;"], [0, "&jukcy;"], [0, "&dscy;"], [0, "&iukcy;"], [0, "&yicy;"], [0, "&jsercy;"], [0, "&ljcy;"], [0, "&njcy;"], [0, "&tshcy;"], [0, "&kjcy;"], [1, "&ubrcy;"], [0, "&dzcy;"], [7074, "&ensp;"], [0, "&emsp;"], [0, "&emsp13;"], [0, "&emsp14;"], [1, "&numsp;"], [0, "&puncsp;"], [0, "&ThinSpace;"], [0, "&hairsp;"], [0, "&NegativeMediumSpace;"], [0, "&zwnj;"], [0, "&zwj;"], [0, "&lrm;"], [0, "&rlm;"], [0, "&dash;"], [2, "&ndash;"], [0, "&mdash;"], [0, "&horbar;"], [0, "&Verbar;"], [1, "&lsquo;"], [0, "&CloseCurlyQuote;"], [0, "&lsquor;"], [1, "&ldquo;"], [0, "&CloseCurlyDoubleQuote;"], [0, "&bdquo;"], [1, "&dagger;"], [0, "&Dagger;"], [0, "&bull;"], [2, "&nldr;"], [0, "&hellip;"], [9, "&permil;"], [0, "&pertenk;"], [0, "&prime;"], [0, "&Prime;"], [0, "&tprime;"], [0, "&backprime;"], [3, "&lsaquo;"], [0, "&rsaquo;"], [3, "&oline;"], [2, "&caret;"], [1, "&hybull;"], [0, "&frasl;"], [10, "&bsemi;"], [7, "&qprime;"], [7, { v: "&MediumSpace;", n: 8202, o: "&ThickSpace;" }], [0, "&NoBreak;"], [0, "&af;"], [0, "&InvisibleTimes;"], [0, "&ic;"], [72, "&euro;"], [46, "&tdot;"], [0, "&DotDot;"], [37, "&complexes;"], [2, "&incare;"], [4, "&gscr;"], [0, "&hamilt;"], [0, "&Hfr;"], [0, "&Hopf;"], [0, "&planckh;"], [0, "&hbar;"], [0, "&imagline;"], [0, "&Ifr;"], [0, "&lagran;"], [0, "&ell;"], [1, "&naturals;"], [0, "&numero;"], [0, "&copysr;"], [0, "&weierp;"], [0, "&Popf;"], [0, "&Qopf;"], [0, "&realine;"], [0, "&real;"], [0, "&reals;"], [0, "&rx;"], [3, "&trade;"], [1, "&integers;"], [2, "&mho;"], [0, "&zeetrf;"], [0, "&iiota;"], [2, "&bernou;"], [0, "&Cayleys;"], [1, "&escr;"], [0, "&Escr;"], [0, "&Fouriertrf;"], [1, "&Mellintrf;"], [0, "&order;"], [0, "&alefsym;"], [0, "&beth;"], [0, "&gimel;"], [0, "&daleth;"], [12, "&CapitalDifferentialD;"], [0, "&dd;"], [0, "&ee;"], [0, "&ii;"], [10, "&frac13;"], [0, "&frac23;"], [0, "&frac15;"], [0, "&frac25;"], [0, "&frac35;"], [0, "&frac45;"], [0, "&frac16;"], [0, "&frac56;"], [0, "&frac18;"], [0, "&frac38;"], [0, "&frac58;"], [0, "&frac78;"], [49, "&larr;"], [0, "&ShortUpArrow;"], [0, "&rarr;"], [0, "&darr;"], [0, "&harr;"], [0, "&updownarrow;"], [0, "&nwarr;"], [0, "&nearr;"], [0, "&LowerRightArrow;"], [0, "&LowerLeftArrow;"], [0, "&nlarr;"], [0, "&nrarr;"], [1, { v: "&rarrw;", n: 824, o: "&nrarrw;" }], [0, "&Larr;"], [0, "&Uarr;"], [0, "&Rarr;"], [0, "&Darr;"], [0, "&larrtl;"], [0, "&rarrtl;"], [0, "&LeftTeeArrow;"], [0, "&mapstoup;"], [0, "&map;"], [0, "&DownTeeArrow;"], [1, "&hookleftarrow;"], [0, "&hookrightarrow;"], [0, "&larrlp;"], [0, "&looparrowright;"], [0, "&harrw;"], [0, "&nharr;"], [1, "&lsh;"], [0, "&rsh;"], [0, "&ldsh;"], [0, "&rdsh;"], [1, "&crarr;"], [0, "&cularr;"], [0, "&curarr;"], [2, "&circlearrowleft;"], [0, "&circlearrowright;"], [0, "&leftharpoonup;"], [0, "&DownLeftVector;"], [0, "&RightUpVector;"], [0, "&LeftUpVector;"], [0, "&rharu;"], [0, "&DownRightVector;"], [0, "&dharr;"], [0, "&dharl;"], [0, "&RightArrowLeftArrow;"], [0, "&udarr;"], [0, "&LeftArrowRightArrow;"], [0, "&leftleftarrows;"], [0, "&upuparrows;"], [0, "&rightrightarrows;"], [0, "&ddarr;"], [0, "&leftrightharpoons;"], [0, "&Equilibrium;"], [0, "&nlArr;"], [0, "&nhArr;"], [0, "&nrArr;"], [0, "&DoubleLeftArrow;"], [0, "&DoubleUpArrow;"], [0, "&DoubleRightArrow;"], [0, "&dArr;"], [0, "&DoubleLeftRightArrow;"], [0, "&DoubleUpDownArrow;"], [0, "&nwArr;"], [0, "&neArr;"], [0, "&seArr;"], [0, "&swArr;"], [0, "&lAarr;"], [0, "&rAarr;"], [1, "&zigrarr;"], [6, "&larrb;"], [0, "&rarrb;"], [15, "&DownArrowUpArrow;"], [7, "&loarr;"], [0, "&roarr;"], [0, "&hoarr;"], [0, "&forall;"], [0, "&comp;"], [0, { v: "&part;", n: 824, o: "&npart;" }], [0, "&exist;"], [0, "&nexist;"], [0, "&empty;"], [1, "&Del;"], [0, "&Element;"], [0, "&NotElement;"], [1, "&ni;"], [0, "&notni;"], [2, "&prod;"], [0, "&coprod;"], [0, "&sum;"], [0, "&minus;"], [0, "&MinusPlus;"], [0, "&dotplus;"], [1, "&Backslash;"], [0, "&lowast;"], [0, "&compfn;"], [1, "&radic;"], [2, "&prop;"], [0, "&infin;"], [0, "&angrt;"], [0, { v: "&ang;", n: 8402, o: "&nang;" }], [0, "&angmsd;"], [0, "&angsph;"], [0, "&mid;"], [0, "&nmid;"], [0, "&DoubleVerticalBar;"], [0, "&NotDoubleVerticalBar;"], [0, "&and;"], [0, "&or;"], [0, { v: "&cap;", n: 65024, o: "&caps;" }], [0, { v: "&cup;", n: 65024, o: "&cups;" }], [0, "&int;"], [0, "&Int;"], [0, "&iiint;"], [0, "&conint;"], [0, "&Conint;"], [0, "&Cconint;"], [0, "&cwint;"], [0, "&ClockwiseContourIntegral;"], [0, "&awconint;"], [0, "&there4;"], [0, "&becaus;"], [0, "&ratio;"], [0, "&Colon;"], [0, "&dotminus;"], [1, "&mDDot;"], [0, "&homtht;"], [0, { v: "&sim;", n: 8402, o: "&nvsim;" }], [0, { v: "&backsim;", n: 817, o: "&race;" }], [0, { v: "&ac;", n: 819, o: "&acE;" }], [0, "&acd;"], [0, "&VerticalTilde;"], [0, "&NotTilde;"], [0, { v: "&eqsim;", n: 824, o: "&nesim;" }], [0, "&sime;"], [0, "&NotTildeEqual;"], [0, "&cong;"], [0, "&simne;"], [0, "&ncong;"], [0, "&ap;"], [0, "&nap;"], [0, "&ape;"], [0, { v: "&apid;", n: 824, o: "&napid;" }], [0, "&backcong;"], [0, { v: "&asympeq;", n: 8402, o: "&nvap;" }], [0, { v: "&bump;", n: 824, o: "&nbump;" }], [0, { v: "&bumpe;", n: 824, o: "&nbumpe;" }], [0, { v: "&doteq;", n: 824, o: "&nedot;" }], [0, "&doteqdot;"], [0, "&efDot;"], [0, "&erDot;"], [0, "&Assign;"], [0, "&ecolon;"], [0, "&ecir;"], [0, "&circeq;"], [1, "&wedgeq;"], [0, "&veeeq;"], [1, "&triangleq;"], [2, "&equest;"], [0, "&ne;"], [0, { v: "&Congruent;", n: 8421, o: "&bnequiv;" }], [0, "&nequiv;"], [1, { v: "&le;", n: 8402, o: "&nvle;" }], [0, { v: "&ge;", n: 8402, o: "&nvge;" }], [0, { v: "&lE;", n: 824, o: "&nlE;" }], [0, { v: "&gE;", n: 824, o: "&ngE;" }], [0, { v: "&lnE;", n: 65024, o: "&lvertneqq;" }], [0, { v: "&gnE;", n: 65024, o: "&gvertneqq;" }], [0, { v: "&ll;", n: new Map(/* @__PURE__ */ restoreDiff([[824, "&nLtv;"], [7577, "&nLt;"]])) }], [0, { v: "&gg;", n: new Map(/* @__PURE__ */ restoreDiff([[824, "&nGtv;"], [7577, "&nGt;"]])) }], [0, "&between;"], [0, "&NotCupCap;"], [0, "&nless;"], [0, "&ngt;"], [0, "&nle;"], [0, "&nge;"], [0, "&lesssim;"], [0, "&GreaterTilde;"], [0, "&nlsim;"], [0, "&ngsim;"], [0, "&LessGreater;"], [0, "&gl;"], [0, "&NotLessGreater;"], [0, "&NotGreaterLess;"], [0, "&pr;"], [0, "&sc;"], [0, "&prcue;"], [0, "&sccue;"], [0, "&PrecedesTilde;"], [0, { v: "&scsim;", n: 824, o: "&NotSucceedsTilde;" }], [0, "&NotPrecedes;"], [0, "&NotSucceeds;"], [0, { v: "&sub;", n: 8402, o: "&NotSubset;" }], [0, { v: "&sup;", n: 8402, o: "&NotSuperset;" }], [0, "&nsub;"], [0, "&nsup;"], [0, "&sube;"], [0, "&supe;"], [0, "&NotSubsetEqual;"], [0, "&NotSupersetEqual;"], [0, { v: "&subne;", n: 65024, o: "&varsubsetneq;" }], [0, { v: "&supne;", n: 65024, o: "&varsupsetneq;" }], [1, "&cupdot;"], [0, "&UnionPlus;"], [0, { v: "&sqsub;", n: 824, o: "&NotSquareSubset;" }], [0, { v: "&sqsup;", n: 824, o: "&NotSquareSuperset;" }], [0, "&sqsube;"], [0, "&sqsupe;"], [0, { v: "&sqcap;", n: 65024, o: "&sqcaps;" }], [0, { v: "&sqcup;", n: 65024, o: "&sqcups;" }], [0, "&CirclePlus;"], [0, "&CircleMinus;"], [0, "&CircleTimes;"], [0, "&osol;"], [0, "&CircleDot;"], [0, "&circledcirc;"], [0, "&circledast;"], [1, "&circleddash;"], [0, "&boxplus;"], [0, "&boxminus;"], [0, "&boxtimes;"], [0, "&dotsquare;"], [0, "&RightTee;"], [0, "&dashv;"], [0, "&DownTee;"], [0, "&bot;"], [1, "&models;"], [0, "&DoubleRightTee;"], [0, "&Vdash;"], [0, "&Vvdash;"], [0, "&VDash;"], [0, "&nvdash;"], [0, "&nvDash;"], [0, "&nVdash;"], [0, "&nVDash;"], [0, "&prurel;"], [1, "&LeftTriangle;"], [0, "&RightTriangle;"], [0, { v: "&LeftTriangleEqual;", n: 8402, o: "&nvltrie;" }], [0, { v: "&RightTriangleEqual;", n: 8402, o: "&nvrtrie;" }], [0, "&origof;"], [0, "&imof;"], [0, "&multimap;"], [0, "&hercon;"], [0, "&intcal;"], [0, "&veebar;"], [1, "&barvee;"], [0, "&angrtvb;"], [0, "&lrtri;"], [0, "&bigwedge;"], [0, "&bigvee;"], [0, "&bigcap;"], [0, "&bigcup;"], [0, "&diam;"], [0, "&sdot;"], [0, "&sstarf;"], [0, "&divideontimes;"], [0, "&bowtie;"], [0, "&ltimes;"], [0, "&rtimes;"], [0, "&leftthreetimes;"], [0, "&rightthreetimes;"], [0, "&backsimeq;"], [0, "&curlyvee;"], [0, "&curlywedge;"], [0, "&Sub;"], [0, "&Sup;"], [0, "&Cap;"], [0, "&Cup;"], [0, "&fork;"], [0, "&epar;"], [0, "&lessdot;"], [0, "&gtdot;"], [0, { v: "&Ll;", n: 824, o: "&nLl;" }], [0, { v: "&Gg;", n: 824, o: "&nGg;" }], [0, { v: "&leg;", n: 65024, o: "&lesg;" }], [0, { v: "&gel;", n: 65024, o: "&gesl;" }], [2, "&cuepr;"], [0, "&cuesc;"], [0, "&NotPrecedesSlantEqual;"], [0, "&NotSucceedsSlantEqual;"], [0, "&NotSquareSubsetEqual;"], [0, "&NotSquareSupersetEqual;"], [2, "&lnsim;"], [0, "&gnsim;"], [0, "&precnsim;"], [0, "&scnsim;"], [0, "&nltri;"], [0, "&NotRightTriangle;"], [0, "&nltrie;"], [0, "&NotRightTriangleEqual;"], [0, "&vellip;"], [0, "&ctdot;"], [0, "&utdot;"], [0, "&dtdot;"], [0, "&disin;"], [0, "&isinsv;"], [0, "&isins;"], [0, { v: "&isindot;", n: 824, o: "&notindot;" }], [0, "&notinvc;"], [0, "&notinvb;"], [1, { v: "&isinE;", n: 824, o: "&notinE;" }], [0, "&nisd;"], [0, "&xnis;"], [0, "&nis;"], [0, "&notnivc;"], [0, "&notnivb;"], [6, "&barwed;"], [0, "&Barwed;"], [1, "&lceil;"], [0, "&rceil;"], [0, "&LeftFloor;"], [0, "&rfloor;"], [0, "&drcrop;"], [0, "&dlcrop;"], [0, "&urcrop;"], [0, "&ulcrop;"], [0, "&bnot;"], [1, "&profline;"], [0, "&profsurf;"], [1, "&telrec;"], [0, "&target;"], [5, "&ulcorn;"], [0, "&urcorn;"], [0, "&dlcorn;"], [0, "&drcorn;"], [2, "&frown;"], [0, "&smile;"], [9, "&cylcty;"], [0, "&profalar;"], [7, "&topbot;"], [6, "&ovbar;"], [1, "&solbar;"], [60, "&angzarr;"], [51, "&lmoustache;"], [0, "&rmoustache;"], [2, "&OverBracket;"], [0, "&bbrk;"], [0, "&bbrktbrk;"], [37, "&OverParenthesis;"], [0, "&UnderParenthesis;"], [0, "&OverBrace;"], [0, "&UnderBrace;"], [2, "&trpezium;"], [4, "&elinters;"], [59, "&blank;"], [164, "&circledS;"], [55, "&boxh;"], [1, "&boxv;"], [9, "&boxdr;"], [3, "&boxdl;"], [3, "&boxur;"], [3, "&boxul;"], [3, "&boxvr;"], [7, "&boxvl;"], [7, "&boxhd;"], [7, "&boxhu;"], [7, "&boxvh;"], [19, "&boxH;"], [0, "&boxV;"], [0, "&boxdR;"], [0, "&boxDr;"], [0, "&boxDR;"], [0, "&boxdL;"], [0, "&boxDl;"], [0, "&boxDL;"], [0, "&boxuR;"], [0, "&boxUr;"], [0, "&boxUR;"], [0, "&boxuL;"], [0, "&boxUl;"], [0, "&boxUL;"], [0, "&boxvR;"], [0, "&boxVr;"], [0, "&boxVR;"], [0, "&boxvL;"], [0, "&boxVl;"], [0, "&boxVL;"], [0, "&boxHd;"], [0, "&boxhD;"], [0, "&boxHD;"], [0, "&boxHu;"], [0, "&boxhU;"], [0, "&boxHU;"], [0, "&boxvH;"], [0, "&boxVh;"], [0, "&boxVH;"], [19, "&uhblk;"], [3, "&lhblk;"], [3, "&block;"], [8, "&blk14;"], [0, "&blk12;"], [0, "&blk34;"], [13, "&square;"], [8, "&blacksquare;"], [0, "&EmptyVerySmallSquare;"], [1, "&rect;"], [0, "&marker;"], [2, "&fltns;"], [1, "&bigtriangleup;"], [0, "&blacktriangle;"], [0, "&triangle;"], [2, "&blacktriangleright;"], [0, "&rtri;"], [3, "&bigtriangledown;"], [0, "&blacktriangledown;"], [0, "&dtri;"], [2, "&blacktriangleleft;"], [0, "&ltri;"], [6, "&loz;"], [0, "&cir;"], [32, "&tridot;"], [2, "&bigcirc;"], [8, "&ultri;"], [0, "&urtri;"], [0, "&lltri;"], [0, "&EmptySmallSquare;"], [0, "&FilledSmallSquare;"], [8, "&bigstar;"], [0, "&star;"], [7, "&phone;"], [49, "&female;"], [1, "&male;"], [29, "&spades;"], [2, "&clubs;"], [1, "&hearts;"], [0, "&diamondsuit;"], [3, "&sung;"], [2, "&flat;"], [0, "&natural;"], [0, "&sharp;"], [163, "&check;"], [3, "&cross;"], [8, "&malt;"], [21, "&sext;"], [33, "&VerticalSeparator;"], [25, "&lbbrk;"], [0, "&rbbrk;"], [84, "&bsolhsub;"], [0, "&suphsol;"], [28, "&LeftDoubleBracket;"], [0, "&RightDoubleBracket;"], [0, "&lang;"], [0, "&rang;"], [0, "&Lang;"], [0, "&Rang;"], [0, "&loang;"], [0, "&roang;"], [7, "&longleftarrow;"], [0, "&longrightarrow;"], [0, "&longleftrightarrow;"], [0, "&DoubleLongLeftArrow;"], [0, "&DoubleLongRightArrow;"], [0, "&DoubleLongLeftRightArrow;"], [1, "&longmapsto;"], [2, "&dzigrarr;"], [258, "&nvlArr;"], [0, "&nvrArr;"], [0, "&nvHarr;"], [0, "&Map;"], [6, "&lbarr;"], [0, "&bkarow;"], [0, "&lBarr;"], [0, "&dbkarow;"], [0, "&drbkarow;"], [0, "&DDotrahd;"], [0, "&UpArrowBar;"], [0, "&DownArrowBar;"], [2, "&Rarrtl;"], [2, "&latail;"], [0, "&ratail;"], [0, "&lAtail;"], [0, "&rAtail;"], [0, "&larrfs;"], [0, "&rarrfs;"], [0, "&larrbfs;"], [0, "&rarrbfs;"], [2, "&nwarhk;"], [0, "&nearhk;"], [0, "&hksearow;"], [0, "&hkswarow;"], [0, "&nwnear;"], [0, "&nesear;"], [0, "&seswar;"], [0, "&swnwar;"], [8, { v: "&rarrc;", n: 824, o: "&nrarrc;" }], [1, "&cudarrr;"], [0, "&ldca;"], [0, "&rdca;"], [0, "&cudarrl;"], [0, "&larrpl;"], [2, "&curarrm;"], [0, "&cularrp;"], [7, "&rarrpl;"], [2, "&harrcir;"], [0, "&Uarrocir;"], [0, "&lurdshar;"], [0, "&ldrushar;"], [2, "&LeftRightVector;"], [0, "&RightUpDownVector;"], [0, "&DownLeftRightVector;"], [0, "&LeftUpDownVector;"], [0, "&LeftVectorBar;"], [0, "&RightVectorBar;"], [0, "&RightUpVectorBar;"], [0, "&RightDownVectorBar;"], [0, "&DownLeftVectorBar;"], [0, "&DownRightVectorBar;"], [0, "&LeftUpVectorBar;"], [0, "&LeftDownVectorBar;"], [0, "&LeftTeeVector;"], [0, "&RightTeeVector;"], [0, "&RightUpTeeVector;"], [0, "&RightDownTeeVector;"], [0, "&DownLeftTeeVector;"], [0, "&DownRightTeeVector;"], [0, "&LeftUpTeeVector;"], [0, "&LeftDownTeeVector;"], [0, "&lHar;"], [0, "&uHar;"], [0, "&rHar;"], [0, "&dHar;"], [0, "&luruhar;"], [0, "&ldrdhar;"], [0, "&ruluhar;"], [0, "&rdldhar;"], [0, "&lharul;"], [0, "&llhard;"], [0, "&rharul;"], [0, "&lrhard;"], [0, "&udhar;"], [0, "&duhar;"], [0, "&RoundImplies;"], [0, "&erarr;"], [0, "&simrarr;"], [0, "&larrsim;"], [0, "&rarrsim;"], [0, "&rarrap;"], [0, "&ltlarr;"], [1, "&gtrarr;"], [0, "&subrarr;"], [1, "&suplarr;"], [0, "&lfisht;"], [0, "&rfisht;"], [0, "&ufisht;"], [0, "&dfisht;"], [5, "&lopar;"], [0, "&ropar;"], [4, "&lbrke;"], [0, "&rbrke;"], [0, "&lbrkslu;"], [0, "&rbrksld;"], [0, "&lbrksld;"], [0, "&rbrkslu;"], [0, "&langd;"], [0, "&rangd;"], [0, "&lparlt;"], [0, "&rpargt;"], [0, "&gtlPar;"], [0, "&ltrPar;"], [3, "&vzigzag;"], [1, "&vangrt;"], [0, "&angrtvbd;"], [6, "&ange;"], [0, "&range;"], [0, "&dwangle;"], [0, "&uwangle;"], [0, "&angmsdaa;"], [0, "&angmsdab;"], [0, "&angmsdac;"], [0, "&angmsdad;"], [0, "&angmsdae;"], [0, "&angmsdaf;"], [0, "&angmsdag;"], [0, "&angmsdah;"], [0, "&bemptyv;"], [0, "&demptyv;"], [0, "&cemptyv;"], [0, "&raemptyv;"], [0, "&laemptyv;"], [0, "&ohbar;"], [0, "&omid;"], [0, "&opar;"], [1, "&operp;"], [1, "&olcross;"], [0, "&odsold;"], [1, "&olcir;"], [0, "&ofcir;"], [0, "&olt;"], [0, "&ogt;"], [0, "&cirscir;"], [0, "&cirE;"], [0, "&solb;"], [0, "&bsolb;"], [3, "&boxbox;"], [3, "&trisb;"], [0, "&rtriltri;"], [0, { v: "&LeftTriangleBar;", n: 824, o: "&NotLeftTriangleBar;" }], [0, { v: "&RightTriangleBar;", n: 824, o: "&NotRightTriangleBar;" }], [11, "&iinfin;"], [0, "&infintie;"], [0, "&nvinfin;"], [4, "&eparsl;"], [0, "&smeparsl;"], [0, "&eqvparsl;"], [5, "&blacklozenge;"], [8, "&RuleDelayed;"], [1, "&dsol;"], [9, "&bigodot;"], [0, "&bigoplus;"], [0, "&bigotimes;"], [1, "&biguplus;"], [1, "&bigsqcup;"], [5, "&iiiint;"], [0, "&fpartint;"], [2, "&cirfnint;"], [0, "&awint;"], [0, "&rppolint;"], [0, "&scpolint;"], [0, "&npolint;"], [0, "&pointint;"], [0, "&quatint;"], [0, "&intlarhk;"], [10, "&pluscir;"], [0, "&plusacir;"], [0, "&simplus;"], [0, "&plusdu;"], [0, "&plussim;"], [0, "&plustwo;"], [1, "&mcomma;"], [0, "&minusdu;"], [2, "&loplus;"], [0, "&roplus;"], [0, "&Cross;"], [0, "&timesd;"], [0, "&timesbar;"], [1, "&smashp;"], [0, "&lotimes;"], [0, "&rotimes;"], [0, "&otimesas;"], [0, "&Otimes;"], [0, "&odiv;"], [0, "&triplus;"], [0, "&triminus;"], [0, "&tritime;"], [0, "&intprod;"], [2, "&amalg;"], [0, "&capdot;"], [1, "&ncup;"], [0, "&ncap;"], [0, "&capand;"], [0, "&cupor;"], [0, "&cupcap;"], [0, "&capcup;"], [0, "&cupbrcap;"], [0, "&capbrcup;"], [0, "&cupcup;"], [0, "&capcap;"], [0, "&ccups;"], [0, "&ccaps;"], [2, "&ccupssm;"], [2, "&And;"], [0, "&Or;"], [0, "&andand;"], [0, "&oror;"], [0, "&orslope;"], [0, "&andslope;"], [1, "&andv;"], [0, "&orv;"], [0, "&andd;"], [0, "&ord;"], [1, "&wedbar;"], [6, "&sdote;"], [3, "&simdot;"], [2, { v: "&congdot;", n: 824, o: "&ncongdot;" }], [0, "&easter;"], [0, "&apacir;"], [0, { v: "&apE;", n: 824, o: "&napE;" }], [0, "&eplus;"], [0, "&pluse;"], [0, "&Esim;"], [0, "&Colone;"], [0, "&Equal;"], [1, "&ddotseq;"], [0, "&equivDD;"], [0, "&ltcir;"], [0, "&gtcir;"], [0, "&ltquest;"], [0, "&gtquest;"], [0, { v: "&leqslant;", n: 824, o: "&nleqslant;" }], [0, { v: "&geqslant;", n: 824, o: "&ngeqslant;" }], [0, "&lesdot;"], [0, "&gesdot;"], [0, "&lesdoto;"], [0, "&gesdoto;"], [0, "&lesdotor;"], [0, "&gesdotol;"], [0, "&lap;"], [0, "&gap;"], [0, "&lne;"], [0, "&gne;"], [0, "&lnap;"], [0, "&gnap;"], [0, "&lEg;"], [0, "&gEl;"], [0, "&lsime;"], [0, "&gsime;"], [0, "&lsimg;"], [0, "&gsiml;"], [0, "&lgE;"], [0, "&glE;"], [0, "&lesges;"], [0, "&gesles;"], [0, "&els;"], [0, "&egs;"], [0, "&elsdot;"], [0, "&egsdot;"], [0, "&el;"], [0, "&eg;"], [2, "&siml;"], [0, "&simg;"], [0, "&simlE;"], [0, "&simgE;"], [0, { v: "&LessLess;", n: 824, o: "&NotNestedLessLess;" }], [0, { v: "&GreaterGreater;", n: 824, o: "&NotNestedGreaterGreater;" }], [1, "&glj;"], [0, "&gla;"], [0, "&ltcc;"], [0, "&gtcc;"], [0, "&lescc;"], [0, "&gescc;"], [0, "&smt;"], [0, "&lat;"], [0, { v: "&smte;", n: 65024, o: "&smtes;" }], [0, { v: "&late;", n: 65024, o: "&lates;" }], [0, "&bumpE;"], [0, { v: "&PrecedesEqual;", n: 824, o: "&NotPrecedesEqual;" }], [0, { v: "&sce;", n: 824, o: "&NotSucceedsEqual;" }], [2, "&prE;"], [0, "&scE;"], [0, "&precneqq;"], [0, "&scnE;"], [0, "&prap;"], [0, "&scap;"], [0, "&precnapprox;"], [0, "&scnap;"], [0, "&Pr;"], [0, "&Sc;"], [0, "&subdot;"], [0, "&supdot;"], [0, "&subplus;"], [0, "&supplus;"], [0, "&submult;"], [0, "&supmult;"], [0, "&subedot;"], [0, "&supedot;"], [0, { v: "&subE;", n: 824, o: "&nsubE;" }], [0, { v: "&supE;", n: 824, o: "&nsupE;" }], [0, "&subsim;"], [0, "&supsim;"], [2, { v: "&subnE;", n: 65024, o: "&varsubsetneqq;" }], [0, { v: "&supnE;", n: 65024, o: "&varsupsetneqq;" }], [2, "&csub;"], [0, "&csup;"], [0, "&csube;"], [0, "&csupe;"], [0, "&subsup;"], [0, "&supsub;"], [0, "&subsub;"], [0, "&supsup;"], [0, "&suphsub;"], [0, "&supdsub;"], [0, "&forkv;"], [0, "&topfork;"], [0, "&mlcp;"], [8, "&Dashv;"], [1, "&Vdashl;"], [0, "&Barv;"], [0, "&vBar;"], [0, "&vBarv;"], [1, "&Vbar;"], [0, "&Not;"], [0, "&bNot;"], [0, "&rnmid;"], [0, "&cirmid;"], [0, "&midcir;"], [0, "&topcir;"], [0, "&nhpar;"], [0, "&parsim;"], [9, { v: "&parsl;", n: 8421, o: "&nparsl;" }], [44343, { n: new Map(/* @__PURE__ */ restoreDiff([[56476, "&Ascr;"], [1, "&Cscr;"], [0, "&Dscr;"], [2, "&Gscr;"], [2, "&Jscr;"], [0, "&Kscr;"], [2, "&Nscr;"], [0, "&Oscr;"], [0, "&Pscr;"], [0, "&Qscr;"], [1, "&Sscr;"], [0, "&Tscr;"], [0, "&Uscr;"], [0, "&Vscr;"], [0, "&Wscr;"], [0, "&Xscr;"], [0, "&Yscr;"], [0, "&Zscr;"], [0, "&ascr;"], [0, "&bscr;"], [0, "&cscr;"], [0, "&dscr;"], [1, "&fscr;"], [1, "&hscr;"], [0, "&iscr;"], [0, "&jscr;"], [0, "&kscr;"], [0, "&lscr;"], [0, "&mscr;"], [0, "&nscr;"], [1, "&pscr;"], [0, "&qscr;"], [0, "&rscr;"], [0, "&sscr;"], [0, "&tscr;"], [0, "&uscr;"], [0, "&vscr;"], [0, "&wscr;"], [0, "&xscr;"], [0, "&yscr;"], [0, "&zscr;"], [52, "&Afr;"], [0, "&Bfr;"], [1, "&Dfr;"], [0, "&Efr;"], [0, "&Ffr;"], [0, "&Gfr;"], [2, "&Jfr;"], [0, "&Kfr;"], [0, "&Lfr;"], [0, "&Mfr;"], [0, "&Nfr;"], [0, "&Ofr;"], [0, "&Pfr;"], [0, "&Qfr;"], [1, "&Sfr;"], [0, "&Tfr;"], [0, "&Ufr;"], [0, "&Vfr;"], [0, "&Wfr;"], [0, "&Xfr;"], [0, "&Yfr;"], [1, "&afr;"], [0, "&bfr;"], [0, "&cfr;"], [0, "&dfr;"], [0, "&efr;"], [0, "&ffr;"], [0, "&gfr;"], [0, "&hfr;"], [0, "&ifr;"], [0, "&jfr;"], [0, "&kfr;"], [0, "&lfr;"], [0, "&mfr;"], [0, "&nfr;"], [0, "&ofr;"], [0, "&pfr;"], [0, "&qfr;"], [0, "&rfr;"], [0, "&sfr;"], [0, "&tfr;"], [0, "&ufr;"], [0, "&vfr;"], [0, "&wfr;"], [0, "&xfr;"], [0, "&yfr;"], [0, "&zfr;"], [0, "&Aopf;"], [0, "&Bopf;"], [1, "&Dopf;"], [0, "&Eopf;"], [0, "&Fopf;"], [0, "&Gopf;"], [1, "&Iopf;"], [0, "&Jopf;"], [0, "&Kopf;"], [0, "&Lopf;"], [0, "&Mopf;"], [1, "&Oopf;"], [3, "&Sopf;"], [0, "&Topf;"], [0, "&Uopf;"], [0, "&Vopf;"], [0, "&Wopf;"], [0, "&Xopf;"], [0, "&Yopf;"], [1, "&aopf;"], [0, "&bopf;"], [0, "&copf;"], [0, "&dopf;"], [0, "&eopf;"], [0, "&fopf;"], [0, "&gopf;"], [0, "&hopf;"], [0, "&iopf;"], [0, "&jopf;"], [0, "&kopf;"], [0, "&lopf;"], [0, "&mopf;"], [0, "&nopf;"], [0, "&oopf;"], [0, "&popf;"], [0, "&qopf;"], [0, "&ropf;"], [0, "&sopf;"], [0, "&topf;"], [0, "&uopf;"], [0, "&vopf;"], [0, "&wopf;"], [0, "&xopf;"], [0, "&yopf;"], [0, "&zopf;"]])) }], [8906, "&fflig;"], [0, "&filig;"], [0, "&fllig;"], [0, "&ffilig;"], [0, "&ffllig;"]]));
  }
});

// node_modules/entities/lib/esm/escape.js
function encodeXML(str2) {
  let ret = "";
  let lastIdx = 0;
  let match2;
  while ((match2 = xmlReplacer.exec(str2)) !== null) {
    const i = match2.index;
    const char = str2.charCodeAt(i);
    const next = xmlCodeMap.get(char);
    if (next !== void 0) {
      ret += str2.substring(lastIdx, i) + next;
      lastIdx = i + 1;
    } else {
      ret += `${str2.substring(lastIdx, i)}&#x${getCodePoint(str2, i).toString(16)};`;
      lastIdx = xmlReplacer.lastIndex += Number((char & 64512) === 55296);
    }
  }
  return ret + str2.substr(lastIdx);
}
function getEscaper(regex3, map2) {
  return /* @__PURE__ */ __name(function escape7(data) {
    let match2;
    let lastIdx = 0;
    let result = "";
    while (match2 = regex3.exec(data)) {
      if (lastIdx !== match2.index) {
        result += data.substring(lastIdx, match2.index);
      }
      result += map2.get(match2[0].charCodeAt(0));
      lastIdx = match2.index + 1;
    }
    return result + data.substring(lastIdx);
  }, "escape");
}
var xmlReplacer, xmlCodeMap, getCodePoint, escapeUTF8, escapeAttribute, escapeText;
var init_escape2 = __esm({
  "node_modules/entities/lib/esm/escape.js"() {
    init_esbuild_shims();
    xmlReplacer = /["&'<>$\x80-\uFFFF]/g;
    xmlCodeMap = /* @__PURE__ */ new Map([
      [34, "&quot;"],
      [38, "&amp;"],
      [39, "&apos;"],
      [60, "&lt;"],
      [62, "&gt;"]
    ]);
    getCodePoint = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
    String.prototype.codePointAt != null ? (str2, index) => str2.codePointAt(index) : (
      // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
      (c3, index) => (c3.charCodeAt(index) & 64512) === 55296 ? (c3.charCodeAt(index) - 55296) * 1024 + c3.charCodeAt(index + 1) - 56320 + 65536 : c3.charCodeAt(index)
    );
    __name(encodeXML, "encodeXML");
    __name(getEscaper, "getEscaper");
    escapeUTF8 = getEscaper(/[&<>'"]/g, xmlCodeMap);
    escapeAttribute = getEscaper(/["&\u00A0]/g, /* @__PURE__ */ new Map([
      [34, "&quot;"],
      [38, "&amp;"],
      [160, "&nbsp;"]
    ]));
    escapeText = getEscaper(/[&<>\u00A0]/g, /* @__PURE__ */ new Map([
      [38, "&amp;"],
      [60, "&lt;"],
      [62, "&gt;"],
      [160, "&nbsp;"]
    ]));
  }
});

// node_modules/entities/lib/esm/encode.js
var init_encode = __esm({
  "node_modules/entities/lib/esm/encode.js"() {
    init_esbuild_shims();
    init_encode_html();
    init_escape2();
  }
});

// node_modules/entities/lib/esm/index.js
var EntityLevel, EncodingMode;
var init_esm13 = __esm({
  "node_modules/entities/lib/esm/index.js"() {
    init_esbuild_shims();
    init_decode();
    init_encode();
    init_escape2();
    init_escape2();
    init_encode();
    init_decode();
    (function(EntityLevel2) {
      EntityLevel2[EntityLevel2["XML"] = 0] = "XML";
      EntityLevel2[EntityLevel2["HTML"] = 1] = "HTML";
    })(EntityLevel || (EntityLevel = {}));
    (function(EncodingMode2) {
      EncodingMode2[EncodingMode2["UTF8"] = 0] = "UTF8";
      EncodingMode2[EncodingMode2["ASCII"] = 1] = "ASCII";
      EncodingMode2[EncodingMode2["Extensive"] = 2] = "Extensive";
      EncodingMode2[EncodingMode2["Attribute"] = 3] = "Attribute";
      EncodingMode2[EncodingMode2["Text"] = 4] = "Text";
    })(EncodingMode || (EncodingMode = {}));
  }
});

// node_modules/dom-serializer/lib/esm/foreignNames.js
var elementNames, attributeNames;
var init_foreignNames = __esm({
  "node_modules/dom-serializer/lib/esm/foreignNames.js"() {
    init_esbuild_shims();
    elementNames = new Map([
      "altGlyph",
      "altGlyphDef",
      "altGlyphItem",
      "animateColor",
      "animateMotion",
      "animateTransform",
      "clipPath",
      "feBlend",
      "feColorMatrix",
      "feComponentTransfer",
      "feComposite",
      "feConvolveMatrix",
      "feDiffuseLighting",
      "feDisplacementMap",
      "feDistantLight",
      "feDropShadow",
      "feFlood",
      "feFuncA",
      "feFuncB",
      "feFuncG",
      "feFuncR",
      "feGaussianBlur",
      "feImage",
      "feMerge",
      "feMergeNode",
      "feMorphology",
      "feOffset",
      "fePointLight",
      "feSpecularLighting",
      "feSpotLight",
      "feTile",
      "feTurbulence",
      "foreignObject",
      "glyphRef",
      "linearGradient",
      "radialGradient",
      "textPath"
    ].map((val) => [val.toLowerCase(), val]));
    attributeNames = new Map([
      "definitionURL",
      "attributeName",
      "attributeType",
      "baseFrequency",
      "baseProfile",
      "calcMode",
      "clipPathUnits",
      "diffuseConstant",
      "edgeMode",
      "filterUnits",
      "glyphRef",
      "gradientTransform",
      "gradientUnits",
      "kernelMatrix",
      "kernelUnitLength",
      "keyPoints",
      "keySplines",
      "keyTimes",
      "lengthAdjust",
      "limitingConeAngle",
      "markerHeight",
      "markerUnits",
      "markerWidth",
      "maskContentUnits",
      "maskUnits",
      "numOctaves",
      "pathLength",
      "patternContentUnits",
      "patternTransform",
      "patternUnits",
      "pointsAtX",
      "pointsAtY",
      "pointsAtZ",
      "preserveAlpha",
      "preserveAspectRatio",
      "primitiveUnits",
      "refX",
      "refY",
      "repeatCount",
      "repeatDur",
      "requiredExtensions",
      "requiredFeatures",
      "specularConstant",
      "specularExponent",
      "spreadMethod",
      "startOffset",
      "stdDeviation",
      "stitchTiles",
      "surfaceScale",
      "systemLanguage",
      "tableValues",
      "targetX",
      "targetY",
      "textLength",
      "viewBox",
      "viewTarget",
      "xChannelSelector",
      "yChannelSelector",
      "zoomAndPan"
    ].map((val) => [val.toLowerCase(), val]));
  }
});

// node_modules/dom-serializer/lib/esm/index.js
function replaceQuotes(value) {
  return value.replace(/"/g, "&quot;");
}
function formatAttributes(attributes, opts) {
  var _a6;
  if (!attributes)
    return;
  const encode4 = ((_a6 = opts.encodeEntities) !== null && _a6 !== void 0 ? _a6 : opts.decodeEntities) === false ? replaceQuotes : opts.xmlMode || opts.encodeEntities !== "utf8" ? encodeXML : escapeAttribute;
  return Object.keys(attributes).map((key) => {
    var _a7, _b2;
    const value = (_a7 = attributes[key]) !== null && _a7 !== void 0 ? _a7 : "";
    if (opts.xmlMode === "foreign") {
      key = (_b2 = attributeNames.get(key)) !== null && _b2 !== void 0 ? _b2 : key;
    }
    if (!opts.emptyAttrs && !opts.xmlMode && value === "") {
      return key;
    }
    return `${key}="${encode4(value)}"`;
  }).join(" ");
}
function render2(node, options2 = {}) {
  const nodes = "length" in node ? node : [node];
  let output = "";
  for (let i = 0; i < nodes.length; i++) {
    output += renderNode(nodes[i], options2);
  }
  return output;
}
function renderNode(node, options2) {
  switch (node.type) {
    case Root:
      return render2(node.children, options2);
    // @ts-expect-error We don't use `Doctype` yet
    case Doctype:
    case Directive:
      return renderDirective(node);
    case Comment:
      return renderComment(node);
    case CDATA:
      return renderCdata(node);
    case Script:
    case Style:
    case Tag:
      return renderTag(node, options2);
    case Text2:
      return renderText(node, options2);
  }
}
function renderTag(elem, opts) {
  var _a6;
  if (opts.xmlMode === "foreign") {
    elem.name = (_a6 = elementNames.get(elem.name)) !== null && _a6 !== void 0 ? _a6 : elem.name;
    if (elem.parent && foreignModeIntegrationPoints.has(elem.parent.name)) {
      opts = { ...opts, xmlMode: false };
    }
  }
  if (!opts.xmlMode && foreignElements.has(elem.name)) {
    opts = { ...opts, xmlMode: "foreign" };
  }
  let tag2 = `<${elem.name}`;
  const attribs = formatAttributes(elem.attribs, opts);
  if (attribs) {
    tag2 += ` ${attribs}`;
  }
  if (elem.children.length === 0 && (opts.xmlMode ? (
    // In XML mode or foreign mode, and user hasn't explicitly turned off self-closing tags
    opts.selfClosingTags !== false
  ) : (
    // User explicitly asked for self-closing tags, even in HTML mode
    opts.selfClosingTags && singleTag.has(elem.name)
  ))) {
    if (!opts.xmlMode)
      tag2 += " ";
    tag2 += "/>";
  } else {
    tag2 += ">";
    if (elem.children.length > 0) {
      tag2 += render2(elem.children, opts);
    }
    if (opts.xmlMode || !singleTag.has(elem.name)) {
      tag2 += `</${elem.name}>`;
    }
  }
  return tag2;
}
function renderDirective(elem) {
  return `<${elem.data}>`;
}
function renderText(elem, opts) {
  var _a6;
  let data = elem.data || "";
  if (((_a6 = opts.encodeEntities) !== null && _a6 !== void 0 ? _a6 : opts.decodeEntities) !== false && !(!opts.xmlMode && elem.parent && unencodedElements.has(elem.parent.name))) {
    data = opts.xmlMode || opts.encodeEntities !== "utf8" ? encodeXML(data) : escapeText(data);
  }
  return data;
}
function renderCdata(elem) {
  return `<![CDATA[${elem.children[0].data}]]>`;
}
function renderComment(elem) {
  return `<!--${elem.data}-->`;
}
var unencodedElements, singleTag, foreignModeIntegrationPoints, foreignElements;
var init_esm14 = __esm({
  "node_modules/dom-serializer/lib/esm/index.js"() {
    init_esbuild_shims();
    init_esm11();
    init_esm13();
    init_foreignNames();
    unencodedElements = /* @__PURE__ */ new Set([
      "style",
      "script",
      "xmp",
      "iframe",
      "noembed",
      "noframes",
      "plaintext",
      "noscript"
    ]);
    __name(replaceQuotes, "replaceQuotes");
    __name(formatAttributes, "formatAttributes");
    singleTag = /* @__PURE__ */ new Set([
      "area",
      "base",
      "basefont",
      "br",
      "col",
      "command",
      "embed",
      "frame",
      "hr",
      "img",
      "input",
      "isindex",
      "keygen",
      "link",
      "meta",
      "param",
      "source",
      "track",
      "wbr"
    ]);
    __name(render2, "render");
    __name(renderNode, "renderNode");
    foreignModeIntegrationPoints = /* @__PURE__ */ new Set([
      "mi",
      "mo",
      "mn",
      "ms",
      "mtext",
      "annotation-xml",
      "foreignObject",
      "desc",
      "title"
    ]);
    foreignElements = /* @__PURE__ */ new Set(["svg", "math"]);
    __name(renderTag, "renderTag");
    __name(renderDirective, "renderDirective");
    __name(renderText, "renderText");
    __name(renderCdata, "renderCdata");
    __name(renderComment, "renderComment");
  }
});

// node_modules/domutils/lib/esm/stringify.js
var init_stringify3 = __esm({
  "node_modules/domutils/lib/esm/stringify.js"() {
    init_esbuild_shims();
    init_esm12();
    init_esm14();
    init_esm11();
  }
});

// node_modules/domutils/lib/esm/traversal.js
var init_traversal = __esm({
  "node_modules/domutils/lib/esm/traversal.js"() {
    init_esbuild_shims();
    init_esm12();
  }
});

// node_modules/domutils/lib/esm/manipulation.js
var init_manipulation = __esm({
  "node_modules/domutils/lib/esm/manipulation.js"() {
    init_esbuild_shims();
  }
});

// node_modules/domutils/lib/esm/querying.js
var init_querying = __esm({
  "node_modules/domutils/lib/esm/querying.js"() {
    init_esbuild_shims();
    init_esm12();
  }
});

// node_modules/domutils/lib/esm/legacy.js
var init_legacy = __esm({
  "node_modules/domutils/lib/esm/legacy.js"() {
    init_esbuild_shims();
    init_esm12();
    init_querying();
  }
});

// node_modules/domutils/lib/esm/helpers.js
var DocumentPosition;
var init_helpers = __esm({
  "node_modules/domutils/lib/esm/helpers.js"() {
    init_esbuild_shims();
    init_esm12();
    (function(DocumentPosition2) {
      DocumentPosition2[DocumentPosition2["DISCONNECTED"] = 1] = "DISCONNECTED";
      DocumentPosition2[DocumentPosition2["PRECEDING"] = 2] = "PRECEDING";
      DocumentPosition2[DocumentPosition2["FOLLOWING"] = 4] = "FOLLOWING";
      DocumentPosition2[DocumentPosition2["CONTAINS"] = 8] = "CONTAINS";
      DocumentPosition2[DocumentPosition2["CONTAINED_BY"] = 16] = "CONTAINED_BY";
    })(DocumentPosition || (DocumentPosition = {}));
  }
});

// node_modules/domutils/lib/esm/feeds.js
var init_feeds = __esm({
  "node_modules/domutils/lib/esm/feeds.js"() {
    init_esbuild_shims();
    init_stringify3();
    init_legacy();
  }
});

// node_modules/domutils/lib/esm/index.js
var init_esm15 = __esm({
  "node_modules/domutils/lib/esm/index.js"() {
    init_esbuild_shims();
    init_stringify3();
    init_traversal();
    init_manipulation();
    init_querying();
    init_legacy();
    init_helpers();
    init_feeds();
    init_esm12();
  }
});

// node_modules/htmlparser2/lib/esm/index.js
function parseDocument(data, options2) {
  const handler = new DomHandler(void 0, options2);
  new Parser(handler, options2).end(data);
  return handler.root;
}
var init_esm16 = __esm({
  "node_modules/htmlparser2/lib/esm/index.js"() {
    init_esbuild_shims();
    init_Parser();
    init_Parser();
    init_esm12();
    init_esm12();
    init_Tokenizer();
    init_esm11();
    init_esm15();
    init_esm15();
    init_esm15();
    __name(parseDocument, "parseDocument");
  }
});

// node_modules/deepmerge/dist/cjs.js
var require_cjs2 = __commonJS({
  "node_modules/deepmerge/dist/cjs.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var isMergeableObject = /* @__PURE__ */ __name(function isMergeableObject2(value) {
      return isNonNullObject(value) && !isSpecial(value);
    }, "isMergeableObject");
    function isNonNullObject(value) {
      return !!value && typeof value === "object";
    }
    __name(isNonNullObject, "isNonNullObject");
    function isSpecial(value) {
      var stringValue = Object.prototype.toString.call(value);
      return stringValue === "[object RegExp]" || stringValue === "[object Date]" || isReactElement(value);
    }
    __name(isSpecial, "isSpecial");
    var canUseSymbol = typeof Symbol === "function" && Symbol.for;
    var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for("react.element") : 60103;
    function isReactElement(value) {
      return value.$$typeof === REACT_ELEMENT_TYPE;
    }
    __name(isReactElement, "isReactElement");
    function emptyTarget(val) {
      return Array.isArray(val) ? [] : {};
    }
    __name(emptyTarget, "emptyTarget");
    function cloneUnlessOtherwiseSpecified(value, options2) {
      return options2.clone !== false && options2.isMergeableObject(value) ? deepmerge(emptyTarget(value), value, options2) : value;
    }
    __name(cloneUnlessOtherwiseSpecified, "cloneUnlessOtherwiseSpecified");
    function defaultArrayMerge(target, source2, options2) {
      return target.concat(source2).map(function(element) {
        return cloneUnlessOtherwiseSpecified(element, options2);
      });
    }
    __name(defaultArrayMerge, "defaultArrayMerge");
    function getMergeFunction(key, options2) {
      if (!options2.customMerge) {
        return deepmerge;
      }
      var customMerge = options2.customMerge(key);
      return typeof customMerge === "function" ? customMerge : deepmerge;
    }
    __name(getMergeFunction, "getMergeFunction");
    function getEnumerableOwnPropertySymbols(target) {
      return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function(symbol) {
        return Object.propertyIsEnumerable.call(target, symbol);
      }) : [];
    }
    __name(getEnumerableOwnPropertySymbols, "getEnumerableOwnPropertySymbols");
    function getKeys(target) {
      return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target));
    }
    __name(getKeys, "getKeys");
    function propertyIsOnObject(object, property) {
      try {
        return property in object;
      } catch (_) {
        return false;
      }
    }
    __name(propertyIsOnObject, "propertyIsOnObject");
    function propertyIsUnsafe(target, key) {
      return propertyIsOnObject(target, key) && !(Object.hasOwnProperty.call(target, key) && Object.propertyIsEnumerable.call(target, key));
    }
    __name(propertyIsUnsafe, "propertyIsUnsafe");
    function mergeObject(target, source2, options2) {
      var destination = {};
      if (options2.isMergeableObject(target)) {
        getKeys(target).forEach(function(key) {
          destination[key] = cloneUnlessOtherwiseSpecified(target[key], options2);
        });
      }
      getKeys(source2).forEach(function(key) {
        if (propertyIsUnsafe(target, key)) {
          return;
        }
        if (propertyIsOnObject(target, key) && options2.isMergeableObject(source2[key])) {
          destination[key] = getMergeFunction(key, options2)(target[key], source2[key], options2);
        } else {
          destination[key] = cloneUnlessOtherwiseSpecified(source2[key], options2);
        }
      });
      return destination;
    }
    __name(mergeObject, "mergeObject");
    function deepmerge(target, source2, options2) {
      options2 = options2 || {};
      options2.arrayMerge = options2.arrayMerge || defaultArrayMerge;
      options2.isMergeableObject = options2.isMergeableObject || isMergeableObject;
      options2.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
      var sourceIsArray = Array.isArray(source2);
      var targetIsArray = Array.isArray(target);
      var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
      if (!sourceAndTargetTypesMatch) {
        return cloneUnlessOtherwiseSpecified(source2, options2);
      } else if (sourceIsArray) {
        return options2.arrayMerge(target, source2, options2);
      } else {
        return mergeObject(target, source2, options2);
      }
    }
    __name(deepmerge, "deepmerge");
    deepmerge.all = /* @__PURE__ */ __name(function deepmergeAll(array, options2) {
      if (!Array.isArray(array)) {
        throw new Error("first argument should be an array");
      }
      return array.reduce(function(prev, next) {
        return deepmerge(prev, next, options2);
      }, {});
    }, "deepmergeAll");
    var deepmerge_1 = deepmerge;
    module2.exports = deepmerge_1;
  }
});

// node_modules/html-to-text/lib/html-to-text.mjs
function limitedDepthRecursive(n2, f, g = () => void 0) {
  if (n2 === void 0) {
    const f1 = /* @__PURE__ */ __name(function(...args) {
      return f(f1, ...args);
    }, "f1");
    return f1;
  }
  if (n2 >= 0) {
    return function(...args) {
      return f(limitedDepthRecursive(n2 - 1, f, g), ...args);
    };
  }
  return g;
}
function trimCharacter(str2, char) {
  let start = 0;
  let end = str2.length;
  while (start < end && str2[start] === char) {
    ++start;
  }
  while (end > start && str2[end - 1] === char) {
    --end;
  }
  return start > 0 || end < str2.length ? str2.substring(start, end) : str2;
}
function trimCharacterEnd(str2, char) {
  let end = str2.length;
  while (end > 0 && str2[end - 1] === char) {
    --end;
  }
  return end < str2.length ? str2.substring(0, end) : str2;
}
function unicodeEscape(str2) {
  return str2.replace(/[\s\S]/g, (c3) => "\\u" + c3.charCodeAt().toString(16).padStart(4, "0"));
}
function mergeDuplicatesPreferLast(items, getKey) {
  const map2 = /* @__PURE__ */ new Map();
  for (let i = items.length; i-- > 0; ) {
    const item = items[i];
    const key = getKey(item);
    map2.set(
      key,
      map2.has(key) ? (0, import_deepmerge.default)(item, map2.get(key), { arrayMerge: overwriteMerge$1 }) : item
    );
  }
  return [...map2.values()].reverse();
}
function get(obj, path108) {
  for (const key of path108) {
    if (!obj) {
      return void 0;
    }
    obj = obj[key];
  }
  return obj;
}
function numberToLetterSequence(num, baseChar = "a", base = 26) {
  const digits2 = [];
  do {
    num -= 1;
    digits2.push(num % base);
    num = num / base >> 0;
  } while (num > 0);
  const baseCode = baseChar.charCodeAt(0);
  return digits2.reverse().map((n2) => String.fromCharCode(baseCode + n2)).join("");
}
function numberToRoman(num) {
  return [...num + ""].map((n2) => +n2).reverse().map((v, i) => v % 5 < 4 ? (v < 5 ? "" : V[i]) + I[i].repeat(v % 5) : I[i] + (v < 5 ? V[i] : I[i + 1])).reverse().join("");
}
function charactersToCodes(str2) {
  return [...str2].map((c3) => "\\u" + c3.charCodeAt(0).toString(16).padStart(4, "0")).join("");
}
function getText(stackItem) {
  if (!(stackItem instanceof BlockStackItem || stackItem instanceof ListItemStackItem || stackItem instanceof TableCellStackItem)) {
    throw new Error("Only blocks, list items and table cells can be requested for text contents.");
  }
  return stackItem.inlineTextBuilder.isEmpty() ? stackItem.rawText : stackItem.rawText + stackItem.inlineTextBuilder.toString();
}
function addText(stackItem, text, leadingLineBreaks, trailingLineBreaks) {
  if (!(stackItem instanceof BlockStackItem || stackItem instanceof ListItemStackItem || stackItem instanceof TableCellStackItem)) {
    throw new Error("Only blocks, list items and table cells can contain text.");
  }
  const parentText = getText(stackItem);
  const lineBreaks = Math.max(stackItem.stashedLineBreaks, leadingLineBreaks);
  stackItem.inlineTextBuilder.clear();
  if (parentText) {
    stackItem.rawText = parentText + "\n".repeat(lineBreaks) + text;
  } else {
    stackItem.rawText = text;
    stackItem.leadingLineBreaks = lineBreaks;
  }
  stackItem.stashedLineBreaks = trailingLineBreaks;
}
function applyTransformer(str2, transformer) {
  return transformer ? applyTransformer(transformer.transform(str2), transformer.next) : str2;
}
function compile$1(options2 = {}) {
  const selectorsWithoutFormat = options2.selectors.filter((s2) => !s2.format);
  if (selectorsWithoutFormat.length) {
    throw new Error(
      "Following selectors have no specified format: " + selectorsWithoutFormat.map((s2) => `\`${s2.selector}\``).join(", ")
    );
  }
  const picker = new DecisionTree(
    options2.selectors.map((s2) => [s2.selector, s2])
  ).build(hp2Builder);
  if (typeof options2.encodeCharacters !== "function") {
    options2.encodeCharacters = makeReplacerFromDict(options2.encodeCharacters);
  }
  const baseSelectorsPicker = new DecisionTree(
    options2.baseElements.selectors.map((s2, i) => [s2, i + 1])
  ).build(hp2Builder);
  function findBaseElements(dom) {
    return findBases(dom, options2, baseSelectorsPicker);
  }
  __name(findBaseElements, "findBaseElements");
  const limitedWalk = limitedDepthRecursive(
    options2.limits.maxDepth,
    recursiveWalk,
    function(dom, builder) {
      builder.addInline(options2.limits.ellipsis || "");
    }
  );
  return function(html2, metadata = void 0) {
    return process21(html2, metadata, options2, picker, findBaseElements, limitedWalk);
  };
}
function process21(html2, metadata, options2, picker, findBaseElements, walk) {
  const maxInputLength = options2.limits.maxInputLength;
  if (maxInputLength && html2 && html2.length > maxInputLength) {
    console.warn(
      `Input length ${html2.length} is above allowed limit of ${maxInputLength}. Truncating without ellipsis.`
    );
    html2 = html2.substring(0, maxInputLength);
  }
  const document2 = parseDocument(html2, { decodeEntities: options2.decodeEntities });
  const bases = findBaseElements(document2.children);
  const builder = new BlockTextBuilder(options2, picker, metadata);
  walk(bases, builder);
  return builder.toString();
}
function findBases(dom, options2, baseSelectorsPicker) {
  const results = [];
  function recursiveWalk2(walk, dom2) {
    dom2 = dom2.slice(0, options2.limits.maxChildNodes);
    for (const elem of dom2) {
      if (elem.type !== "tag") {
        continue;
      }
      const pickedSelectorIndex = baseSelectorsPicker.pick1(elem);
      if (pickedSelectorIndex > 0) {
        results.push({ selectorIndex: pickedSelectorIndex, element: elem });
      } else if (elem.children) {
        walk(elem.children);
      }
      if (results.length >= options2.limits.maxBaseElements) {
        return;
      }
    }
  }
  __name(recursiveWalk2, "recursiveWalk");
  const limitedWalk = limitedDepthRecursive(
    options2.limits.maxDepth,
    recursiveWalk2
  );
  limitedWalk(dom);
  if (options2.baseElements.orderBy !== "occurrence") {
    results.sort((a, b) => a.selectorIndex - b.selectorIndex);
  }
  return options2.baseElements.returnDomByDefault && results.length === 0 ? dom : results.map((x) => x.element);
}
function recursiveWalk(walk, dom, builder) {
  if (!dom) {
    return;
  }
  const options2 = builder.options;
  const tooManyChildNodes = dom.length > options2.limits.maxChildNodes;
  if (tooManyChildNodes) {
    dom = dom.slice(0, options2.limits.maxChildNodes);
    dom.push({
      data: options2.limits.ellipsis,
      type: "text"
    });
  }
  for (const elem of dom) {
    switch (elem.type) {
      case "text": {
        builder.addInline(elem.data);
        break;
      }
      case "tag": {
        const tagDefinition = builder.picker.pick1(elem);
        const format4 = options2.formatters[tagDefinition.format];
        format4(elem, walk, builder, tagDefinition.options || {});
        break;
      }
    }
  }
  return;
}
function makeReplacerFromDict(dict) {
  if (!dict || Object.keys(dict).length === 0) {
    return void 0;
  }
  const entries = Object.entries(dict).filter(([, v]) => v !== false);
  const regex3 = new RegExp(
    entries.map(([c3]) => `(${unicodeEscape([...c3][0])})`).join("|"),
    "g"
  );
  const values = entries.map(([, v]) => v);
  const replacer = /* @__PURE__ */ __name((m, ...cgs) => values[cgs.findIndex((cg) => cg)], "replacer");
  return (str2) => str2.replace(regex3, replacer);
}
function formatSkip(elem, walk, builder, formatOptions) {
}
function formatInlineString(elem, walk, builder, formatOptions) {
  builder.addLiteral(formatOptions.string || "");
}
function formatBlockString(elem, walk, builder, formatOptions) {
  builder.openBlock({ leadingLineBreaks: formatOptions.leadingLineBreaks || 2 });
  builder.addLiteral(formatOptions.string || "");
  builder.closeBlock({ trailingLineBreaks: formatOptions.trailingLineBreaks || 2 });
}
function formatInline(elem, walk, builder, formatOptions) {
  walk(elem.children, builder);
}
function formatBlock$1(elem, walk, builder, formatOptions) {
  builder.openBlock({ leadingLineBreaks: formatOptions.leadingLineBreaks || 2 });
  walk(elem.children, builder);
  builder.closeBlock({ trailingLineBreaks: formatOptions.trailingLineBreaks || 2 });
}
function renderOpenTag(elem) {
  const attrs = elem.attribs && elem.attribs.length ? " " + Object.entries(elem.attribs).map(([k, v]) => v === "" ? k : `${k}=${v.replace(/"/g, "&quot;")}`).join(" ") : "";
  return `<${elem.name}${attrs}>`;
}
function renderCloseTag(elem) {
  return `</${elem.name}>`;
}
function formatInlineTag(elem, walk, builder, formatOptions) {
  builder.startNoWrap();
  builder.addLiteral(renderOpenTag(elem));
  builder.stopNoWrap();
  walk(elem.children, builder);
  builder.startNoWrap();
  builder.addLiteral(renderCloseTag(elem));
  builder.stopNoWrap();
}
function formatBlockTag(elem, walk, builder, formatOptions) {
  builder.openBlock({ leadingLineBreaks: formatOptions.leadingLineBreaks || 2 });
  builder.startNoWrap();
  builder.addLiteral(renderOpenTag(elem));
  builder.stopNoWrap();
  walk(elem.children, builder);
  builder.startNoWrap();
  builder.addLiteral(renderCloseTag(elem));
  builder.stopNoWrap();
  builder.closeBlock({ trailingLineBreaks: formatOptions.trailingLineBreaks || 2 });
}
function formatInlineHtml(elem, walk, builder, formatOptions) {
  builder.startNoWrap();
  builder.addLiteral(
    render2(elem, { decodeEntities: builder.options.decodeEntities })
  );
  builder.stopNoWrap();
}
function formatBlockHtml(elem, walk, builder, formatOptions) {
  builder.openBlock({ leadingLineBreaks: formatOptions.leadingLineBreaks || 2 });
  builder.startNoWrap();
  builder.addLiteral(
    render2(elem, { decodeEntities: builder.options.decodeEntities })
  );
  builder.stopNoWrap();
  builder.closeBlock({ trailingLineBreaks: formatOptions.trailingLineBreaks || 2 });
}
function formatInlineSurround(elem, walk, builder, formatOptions) {
  builder.addLiteral(formatOptions.prefix || "");
  walk(elem.children, builder);
  builder.addLiteral(formatOptions.suffix || "");
}
function getRow(matrix, j) {
  if (!matrix[j]) {
    matrix[j] = [];
  }
  return matrix[j];
}
function findFirstVacantIndex(row, x = 0) {
  while (row[x]) {
    x++;
  }
  return x;
}
function transposeInPlace(matrix, maxSize) {
  for (let i = 0; i < maxSize; i++) {
    const rowI = getRow(matrix, i);
    for (let j = 0; j < i; j++) {
      const rowJ = getRow(matrix, j);
      if (rowI[j] || rowJ[i]) {
        const temp = rowI[j];
        rowI[j] = rowJ[i];
        rowJ[i] = temp;
      }
    }
  }
}
function putCellIntoLayout(cell, layout, baseRow, baseCol) {
  for (let r3 = 0; r3 < cell.rowspan; r3++) {
    const layoutRow = getRow(layout, baseRow + r3);
    for (let c3 = 0; c3 < cell.colspan; c3++) {
      layoutRow[baseCol + c3] = cell;
    }
  }
}
function getOrInitOffset(offsets, index) {
  if (offsets[index] === void 0) {
    offsets[index] = index === 0 ? 0 : 1 + getOrInitOffset(offsets, index - 1);
  }
  return offsets[index];
}
function updateOffset(offsets, base, span, value) {
  offsets[base + span] = Math.max(
    getOrInitOffset(offsets, base + span),
    getOrInitOffset(offsets, base) + value
  );
}
function tableToString(tableRows, rowSpacing, colSpacing) {
  const layout = [];
  let colNumber = 0;
  const rowNumber = tableRows.length;
  const rowOffsets = [0];
  for (let j = 0; j < rowNumber; j++) {
    const layoutRow = getRow(layout, j);
    const cells = tableRows[j];
    let x = 0;
    for (let i = 0; i < cells.length; i++) {
      const cell = cells[i];
      x = findFirstVacantIndex(layoutRow, x);
      putCellIntoLayout(cell, layout, j, x);
      x += cell.colspan;
      cell.lines = cell.text.split("\n");
      const cellHeight = cell.lines.length;
      updateOffset(rowOffsets, j, cell.rowspan, cellHeight + rowSpacing);
    }
    colNumber = layoutRow.length > colNumber ? layoutRow.length : colNumber;
  }
  transposeInPlace(layout, rowNumber > colNumber ? rowNumber : colNumber);
  const outputLines = [];
  const colOffsets = [0];
  for (let x = 0; x < colNumber; x++) {
    let y = 0;
    let cell;
    const rowsInThisColumn = Math.min(rowNumber, layout[x].length);
    while (y < rowsInThisColumn) {
      cell = layout[x][y];
      if (cell) {
        if (!cell.rendered) {
          let cellWidth = 0;
          for (let j = 0; j < cell.lines.length; j++) {
            const line = cell.lines[j];
            const lineOffset = rowOffsets[y] + j;
            outputLines[lineOffset] = (outputLines[lineOffset] || "").padEnd(colOffsets[x]) + line;
            cellWidth = line.length > cellWidth ? line.length : cellWidth;
          }
          updateOffset(colOffsets, x, cell.colspan, cellWidth + colSpacing);
          cell.rendered = true;
        }
        y += cell.rowspan;
      } else {
        const lineOffset = rowOffsets[y];
        outputLines[lineOffset] = outputLines[lineOffset] || "";
        y++;
      }
    }
  }
  return outputLines.join("\n");
}
function formatLineBreak(elem, walk, builder, formatOptions) {
  builder.addLineBreak();
}
function formatWbr(elem, walk, builder, formatOptions) {
  builder.addWordBreakOpportunity();
}
function formatHorizontalLine(elem, walk, builder, formatOptions) {
  builder.openBlock({ leadingLineBreaks: formatOptions.leadingLineBreaks || 2 });
  builder.addInline("-".repeat(formatOptions.length || builder.options.wordwrap || 40));
  builder.closeBlock({ trailingLineBreaks: formatOptions.trailingLineBreaks || 2 });
}
function formatParagraph(elem, walk, builder, formatOptions) {
  builder.openBlock({ leadingLineBreaks: formatOptions.leadingLineBreaks || 2 });
  walk(elem.children, builder);
  builder.closeBlock({ trailingLineBreaks: formatOptions.trailingLineBreaks || 2 });
}
function formatPre(elem, walk, builder, formatOptions) {
  builder.openBlock({
    isPre: true,
    leadingLineBreaks: formatOptions.leadingLineBreaks || 2
  });
  walk(elem.children, builder);
  builder.closeBlock({ trailingLineBreaks: formatOptions.trailingLineBreaks || 2 });
}
function formatHeading(elem, walk, builder, formatOptions) {
  builder.openBlock({ leadingLineBreaks: formatOptions.leadingLineBreaks || 2 });
  if (formatOptions.uppercase !== false) {
    builder.pushWordTransform((str2) => str2.toUpperCase());
    walk(elem.children, builder);
    builder.popWordTransform();
  } else {
    walk(elem.children, builder);
  }
  builder.closeBlock({ trailingLineBreaks: formatOptions.trailingLineBreaks || 2 });
}
function formatBlockquote(elem, walk, builder, formatOptions) {
  builder.openBlock({
    leadingLineBreaks: formatOptions.leadingLineBreaks || 2,
    reservedLineLength: 2
  });
  walk(elem.children, builder);
  builder.closeBlock({
    trailingLineBreaks: formatOptions.trailingLineBreaks || 2,
    blockTransform: /* @__PURE__ */ __name((str2) => (formatOptions.trimEmptyLines !== false ? trimCharacter(str2, "\n") : str2).split("\n").map((line) => "> " + line).join("\n"), "blockTransform")
  });
}
function withBrackets(str2, brackets) {
  if (!brackets) {
    return str2;
  }
  const lbr = typeof brackets[0] === "string" ? brackets[0] : "[";
  const rbr = typeof brackets[1] === "string" ? brackets[1] : "]";
  return lbr + str2 + rbr;
}
function pathRewrite(path108, rewriter, baseUrl, metadata, elem) {
  const modifiedPath = typeof rewriter === "function" ? rewriter(path108, metadata, elem) : path108;
  return modifiedPath[0] === "/" && baseUrl ? trimCharacterEnd(baseUrl, "/") + modifiedPath : modifiedPath;
}
function formatImage(elem, walk, builder, formatOptions) {
  const attribs = elem.attribs || {};
  const alt = attribs.alt ? attribs.alt : "";
  const src = !attribs.src ? "" : pathRewrite(attribs.src, formatOptions.pathRewrite, formatOptions.baseUrl, builder.metadata, elem);
  const text = !src ? alt : !alt ? withBrackets(src, formatOptions.linkBrackets) : alt + " " + withBrackets(src, formatOptions.linkBrackets);
  builder.addInline(text, { noWordTransform: true });
}
function formatAnchor(elem, walk, builder, formatOptions) {
  function getHref() {
    if (formatOptions.ignoreHref) {
      return "";
    }
    if (!elem.attribs || !elem.attribs.href) {
      return "";
    }
    let href2 = elem.attribs.href.replace(/^mailto:/, "");
    if (formatOptions.noAnchorUrl && href2[0] === "#") {
      return "";
    }
    href2 = pathRewrite(href2, formatOptions.pathRewrite, formatOptions.baseUrl, builder.metadata, elem);
    return href2;
  }
  __name(getHref, "getHref");
  const href = getHref();
  if (!href) {
    walk(elem.children, builder);
  } else {
    let text = "";
    builder.pushWordTransform(
      (str2) => {
        if (str2) {
          text += str2;
        }
        return str2;
      }
    );
    walk(elem.children, builder);
    builder.popWordTransform();
    const hideSameLink = formatOptions.hideLinkHrefIfSameAsText && href === text;
    if (!hideSameLink) {
      builder.addInline(
        !text ? href : " " + withBrackets(href, formatOptions.linkBrackets),
        { noWordTransform: true }
      );
    }
  }
}
function formatList(elem, walk, builder, formatOptions, nextPrefixCallback) {
  const isNestedList = get(elem, ["parent", "name"]) === "li";
  let maxPrefixLength = 0;
  const listItems = (elem.children || []).filter((child) => child.type !== "text" || !/^\s*$/.test(child.data)).map(function(child) {
    if (child.name !== "li") {
      return { node: child, prefix: "" };
    }
    const prefix = isNestedList ? nextPrefixCallback().trimStart() : nextPrefixCallback();
    if (prefix.length > maxPrefixLength) {
      maxPrefixLength = prefix.length;
    }
    return { node: child, prefix };
  });
  if (!listItems.length) {
    return;
  }
  builder.openList({
    interRowLineBreaks: 1,
    leadingLineBreaks: isNestedList ? 1 : formatOptions.leadingLineBreaks || 2,
    maxPrefixLength,
    prefixAlign: "left"
  });
  for (const { node, prefix } of listItems) {
    builder.openListItem({ prefix });
    walk([node], builder);
    builder.closeListItem();
  }
  builder.closeList({ trailingLineBreaks: isNestedList ? 1 : formatOptions.trailingLineBreaks || 2 });
}
function formatUnorderedList(elem, walk, builder, formatOptions) {
  const prefix = formatOptions.itemPrefix || " * ";
  return formatList(elem, walk, builder, formatOptions, () => prefix);
}
function formatOrderedList(elem, walk, builder, formatOptions) {
  let nextIndex = Number(elem.attribs.start || "1");
  const indexFunction = getOrderedListIndexFunction(elem.attribs.type);
  const nextPrefixCallback = /* @__PURE__ */ __name(() => " " + indexFunction(nextIndex++) + ". ", "nextPrefixCallback");
  return formatList(elem, walk, builder, formatOptions, nextPrefixCallback);
}
function getOrderedListIndexFunction(olType = "1") {
  switch (olType) {
    case "a":
      return (i) => numberToLetterSequence(i, "a");
    case "A":
      return (i) => numberToLetterSequence(i, "A");
    case "i":
      return (i) => numberToRoman(i).toLowerCase();
    case "I":
      return (i) => numberToRoman(i);
    case "1":
    default:
      return (i) => i.toString();
  }
}
function splitClassesAndIds(selectors) {
  const classes = [];
  const ids = [];
  for (const selector of selectors) {
    if (selector.startsWith(".")) {
      classes.push(selector.substring(1));
    } else if (selector.startsWith("#")) {
      ids.push(selector.substring(1));
    }
  }
  return { classes, ids };
}
function isDataTable(attr, tables) {
  if (tables === true) {
    return true;
  }
  if (!attr) {
    return false;
  }
  const { classes, ids } = splitClassesAndIds(tables);
  const attrClasses = (attr["class"] || "").split(" ");
  const attrIds = (attr["id"] || "").split(" ");
  return attrClasses.some((x) => classes.includes(x)) || attrIds.some((x) => ids.includes(x));
}
function formatTable(elem, walk, builder, formatOptions) {
  return isDataTable(elem.attribs, builder.options.tables) ? formatDataTable(elem, walk, builder, formatOptions) : formatBlock(elem, walk, builder, formatOptions);
}
function formatBlock(elem, walk, builder, formatOptions) {
  builder.openBlock({ leadingLineBreaks: formatOptions.leadingLineBreaks });
  walk(elem.children, builder);
  builder.closeBlock({ trailingLineBreaks: formatOptions.trailingLineBreaks });
}
function formatDataTable(elem, walk, builder, formatOptions) {
  builder.openTable();
  elem.children.forEach(walkTable);
  builder.closeTable({
    tableToString: /* @__PURE__ */ __name((rows) => tableToString(rows, formatOptions.rowSpacing ?? 0, formatOptions.colSpacing ?? 3), "tableToString"),
    leadingLineBreaks: formatOptions.leadingLineBreaks,
    trailingLineBreaks: formatOptions.trailingLineBreaks
  });
  function formatCell(cellNode) {
    const colspan = +get(cellNode, ["attribs", "colspan"]) || 1;
    const rowspan = +get(cellNode, ["attribs", "rowspan"]) || 1;
    builder.openTableCell({ maxColumnWidth: formatOptions.maxColumnWidth });
    walk(cellNode.children, builder);
    builder.closeTableCell({ colspan, rowspan });
  }
  __name(formatCell, "formatCell");
  function walkTable(elem2) {
    if (elem2.type !== "tag") {
      return;
    }
    const formatHeaderCell = formatOptions.uppercaseHeaderCells !== false ? (cellNode) => {
      builder.pushWordTransform((str2) => str2.toUpperCase());
      formatCell(cellNode);
      builder.popWordTransform();
    } : formatCell;
    switch (elem2.name) {
      case "thead":
      case "tbody":
      case "tfoot":
      case "center":
        elem2.children.forEach(walkTable);
        return;
      case "tr": {
        builder.openTableRow();
        for (const childOfTr of elem2.children) {
          if (childOfTr.type !== "tag") {
            continue;
          }
          switch (childOfTr.name) {
            case "th": {
              formatHeaderCell(childOfTr);
              break;
            }
            case "td": {
              formatCell(childOfTr);
              break;
            }
          }
        }
        builder.closeTableRow();
        break;
      }
    }
  }
  __name(walkTable, "walkTable");
}
function compile(options2 = {}) {
  options2 = (0, import_deepmerge.default)(
    DEFAULT_OPTIONS,
    options2,
    {
      arrayMerge: overwriteMerge,
      customMerge: /* @__PURE__ */ __name((key) => key === "selectors" ? selectorsMerge : void 0, "customMerge")
    }
  );
  options2.formatters = Object.assign({}, genericFormatters, textFormatters, options2.formatters);
  options2.selectors = mergeDuplicatesPreferLast(options2.selectors, (s2) => s2.selector);
  handleDeprecatedOptions(options2);
  return compile$1(options2);
}
function convert(html2, options2 = {}, metadata = void 0) {
  return compile(options2)(html2, metadata);
}
function handleDeprecatedOptions(options2) {
  if (options2.tags) {
    const tagDefinitions = Object.entries(options2.tags).map(
      ([selector, definition]) => ({ ...definition, selector: selector || "*" })
    );
    options2.selectors.push(...tagDefinitions);
    options2.selectors = mergeDuplicatesPreferLast(options2.selectors, (s2) => s2.selector);
  }
  function set(obj, path108, value) {
    const valueKey = path108.pop();
    for (const key of path108) {
      let nested = obj[key];
      if (!nested) {
        nested = {};
        obj[key] = nested;
      }
      obj = nested;
    }
    obj[valueKey] = value;
  }
  __name(set, "set");
  if (options2["baseElement"]) {
    const baseElement = options2["baseElement"];
    set(
      options2,
      ["baseElements", "selectors"],
      Array.isArray(baseElement) ? baseElement : [baseElement]
    );
  }
  if (options2["returnDomByDefault"] !== void 0) {
    set(options2, ["baseElements", "returnDomByDefault"], options2["returnDomByDefault"]);
  }
  for (const definition of options2.selectors) {
    if (definition.format === "anchor" && get(definition, ["options", "noLinkBrackets"])) {
      set(definition, ["options", "linkBrackets"], false);
    }
  }
}
var import_deepmerge, overwriteMerge$1, I, V, InlineTextBuilder, StackItem, BlockStackItem, ListStackItem, ListItemStackItem, TableStackItem, TableRowStackItem, TableCellStackItem, TransformerStackItem, WhitespaceProcessor, BlockTextBuilder, genericFormatters, textFormatters, DEFAULT_OPTIONS, concatMerge, overwriteMerge, selectorsMerge;
var init_html_to_text = __esm({
  "node_modules/html-to-text/lib/html-to-text.mjs"() {
    init_esbuild_shims();
    init_hp2_builder();
    init_esm16();
    init_selderee();
    import_deepmerge = __toESM(require_cjs2(), 1);
    init_esm14();
    __name(limitedDepthRecursive, "limitedDepthRecursive");
    __name(trimCharacter, "trimCharacter");
    __name(trimCharacterEnd, "trimCharacterEnd");
    __name(unicodeEscape, "unicodeEscape");
    __name(mergeDuplicatesPreferLast, "mergeDuplicatesPreferLast");
    overwriteMerge$1 = /* @__PURE__ */ __name((acc, src, options2) => [...src], "overwriteMerge$1");
    __name(get, "get");
    __name(numberToLetterSequence, "numberToLetterSequence");
    I = ["I", "X", "C", "M"];
    V = ["V", "L", "D"];
    __name(numberToRoman, "numberToRoman");
    InlineTextBuilder = class {
      static {
        __name(this, "InlineTextBuilder");
      }
      /**
       * Creates an instance of InlineTextBuilder.
       *
       * If `maxLineLength` is not provided then it is either `options.wordwrap` or unlimited.
       *
       * @param { Options } options           HtmlToText options.
       * @param { number }  [ maxLineLength ] This builder will try to wrap text to fit this line length.
       */
      constructor(options2, maxLineLength = void 0) {
        this.lines = [];
        this.nextLineWords = [];
        this.maxLineLength = maxLineLength || options2.wordwrap || Number.MAX_VALUE;
        this.nextLineAvailableChars = this.maxLineLength;
        this.wrapCharacters = get(options2, ["longWordSplit", "wrapCharacters"]) || [];
        this.forceWrapOnLimit = get(options2, ["longWordSplit", "forceWrapOnLimit"]) || false;
        this.stashedSpace = false;
        this.wordBreakOpportunity = false;
      }
      /**
       * Add a new word.
       *
       * @param { string } word A word to add.
       * @param { boolean } [noWrap] Don't wrap text even if the line is too long.
       */
      pushWord(word, noWrap = false) {
        if (this.nextLineAvailableChars <= 0 && !noWrap) {
          this.startNewLine();
        }
        const isLineStart = this.nextLineWords.length === 0;
        const cost = word.length + (isLineStart ? 0 : 1);
        if (cost <= this.nextLineAvailableChars || noWrap) {
          this.nextLineWords.push(word);
          this.nextLineAvailableChars -= cost;
        } else {
          const [first2, ...rest] = this.splitLongWord(word);
          if (!isLineStart) {
            this.startNewLine();
          }
          this.nextLineWords.push(first2);
          this.nextLineAvailableChars -= first2.length;
          for (const part of rest) {
            this.startNewLine();
            this.nextLineWords.push(part);
            this.nextLineAvailableChars -= part.length;
          }
        }
      }
      /**
       * Pop a word from the currently built line.
       * This doesn't affect completed lines.
       *
       * @returns { string }
       */
      popWord() {
        const lastWord = this.nextLineWords.pop();
        if (lastWord !== void 0) {
          const isLineStart = this.nextLineWords.length === 0;
          const cost = lastWord.length + (isLineStart ? 0 : 1);
          this.nextLineAvailableChars += cost;
        }
        return lastWord;
      }
      /**
       * Concat a word to the last word already in the builder.
       * Adds a new word in case there are no words yet in the last line.
       *
       * @param { string } word A word to be concatenated.
       * @param { boolean } [noWrap] Don't wrap text even if the line is too long.
       */
      concatWord(word, noWrap = false) {
        if (this.wordBreakOpportunity && word.length > this.nextLineAvailableChars) {
          this.pushWord(word, noWrap);
          this.wordBreakOpportunity = false;
        } else {
          const lastWord = this.popWord();
          this.pushWord(lastWord ? lastWord.concat(word) : word, noWrap);
        }
      }
      /**
       * Add current line (and more empty lines if provided argument > 1) to the list of complete lines and start a new one.
       *
       * @param { number } n Number of line breaks that will be added to the resulting string.
       */
      startNewLine(n2 = 1) {
        this.lines.push(this.nextLineWords);
        if (n2 > 1) {
          this.lines.push(...Array.from({ length: n2 - 1 }, () => []));
        }
        this.nextLineWords = [];
        this.nextLineAvailableChars = this.maxLineLength;
      }
      /**
       * No words in this builder.
       *
       * @returns { boolean }
       */
      isEmpty() {
        return this.lines.length === 0 && this.nextLineWords.length === 0;
      }
      clear() {
        this.lines.length = 0;
        this.nextLineWords.length = 0;
        this.nextLineAvailableChars = this.maxLineLength;
      }
      /**
       * Join all lines of words inside the InlineTextBuilder into a complete string.
       *
       * @returns { string }
       */
      toString() {
        return [...this.lines, this.nextLineWords].map((words) => words.join(" ")).join("\n");
      }
      /**
       * Split a long word up to fit within the word wrap limit.
       * Use either a character to split looking back from the word wrap limit,
       * or truncate to the word wrap limit.
       *
       * @param   { string }   word Input word.
       * @returns { string[] }      Parts of the word.
       */
      splitLongWord(word) {
        const parts = [];
        let idx = 0;
        while (word.length > this.maxLineLength) {
          const firstLine = word.substring(0, this.maxLineLength);
          const remainingChars = word.substring(this.maxLineLength);
          const splitIndex = firstLine.lastIndexOf(this.wrapCharacters[idx]);
          if (splitIndex > -1) {
            word = firstLine.substring(splitIndex + 1) + remainingChars;
            parts.push(firstLine.substring(0, splitIndex + 1));
          } else {
            idx++;
            if (idx < this.wrapCharacters.length) {
              word = firstLine + remainingChars;
            } else {
              if (this.forceWrapOnLimit) {
                parts.push(firstLine);
                word = remainingChars;
                if (word.length > this.maxLineLength) {
                  continue;
                }
              } else {
                word = firstLine + remainingChars;
              }
              break;
            }
          }
        }
        parts.push(word);
        return parts;
      }
    };
    StackItem = class {
      static {
        __name(this, "StackItem");
      }
      constructor(next = null) {
        this.next = next;
      }
      getRoot() {
        return this.next ? this.next : this;
      }
    };
    BlockStackItem = class extends StackItem {
      static {
        __name(this, "BlockStackItem");
      }
      constructor(options2, next = null, leadingLineBreaks = 1, maxLineLength = void 0) {
        super(next);
        this.leadingLineBreaks = leadingLineBreaks;
        this.inlineTextBuilder = new InlineTextBuilder(options2, maxLineLength);
        this.rawText = "";
        this.stashedLineBreaks = 0;
        this.isPre = next && next.isPre;
        this.isNoWrap = next && next.isNoWrap;
      }
    };
    ListStackItem = class extends BlockStackItem {
      static {
        __name(this, "ListStackItem");
      }
      constructor(options2, next = null, {
        interRowLineBreaks = 1,
        leadingLineBreaks = 2,
        maxLineLength = void 0,
        maxPrefixLength = 0,
        prefixAlign = "left"
      } = {}) {
        super(options2, next, leadingLineBreaks, maxLineLength);
        this.maxPrefixLength = maxPrefixLength;
        this.prefixAlign = prefixAlign;
        this.interRowLineBreaks = interRowLineBreaks;
      }
    };
    ListItemStackItem = class extends BlockStackItem {
      static {
        __name(this, "ListItemStackItem");
      }
      constructor(options2, next = null, {
        leadingLineBreaks = 1,
        maxLineLength = void 0,
        prefix = ""
      } = {}) {
        super(options2, next, leadingLineBreaks, maxLineLength);
        this.prefix = prefix;
      }
    };
    TableStackItem = class extends StackItem {
      static {
        __name(this, "TableStackItem");
      }
      constructor(next = null) {
        super(next);
        this.rows = [];
        this.isPre = next && next.isPre;
        this.isNoWrap = next && next.isNoWrap;
      }
    };
    TableRowStackItem = class extends StackItem {
      static {
        __name(this, "TableRowStackItem");
      }
      constructor(next = null) {
        super(next);
        this.cells = [];
        this.isPre = next && next.isPre;
        this.isNoWrap = next && next.isNoWrap;
      }
    };
    TableCellStackItem = class extends StackItem {
      static {
        __name(this, "TableCellStackItem");
      }
      constructor(options2, next = null, maxColumnWidth = void 0) {
        super(next);
        this.inlineTextBuilder = new InlineTextBuilder(options2, maxColumnWidth);
        this.rawText = "";
        this.stashedLineBreaks = 0;
        this.isPre = next && next.isPre;
        this.isNoWrap = next && next.isNoWrap;
      }
    };
    TransformerStackItem = class extends StackItem {
      static {
        __name(this, "TransformerStackItem");
      }
      constructor(next = null, transform) {
        super(next);
        this.transform = transform;
      }
    };
    __name(charactersToCodes, "charactersToCodes");
    WhitespaceProcessor = class {
      static {
        __name(this, "WhitespaceProcessor");
      }
      /**
       * Creates an instance of WhitespaceProcessor.
       *
       * @param { Options } options    HtmlToText options.
       * @memberof WhitespaceProcessor
       */
      constructor(options2) {
        this.whitespaceChars = options2.preserveNewlines ? options2.whitespaceCharacters.replace(/\n/g, "") : options2.whitespaceCharacters;
        const whitespaceCodes = charactersToCodes(this.whitespaceChars);
        this.leadingWhitespaceRe = new RegExp(`^[${whitespaceCodes}]`);
        this.trailingWhitespaceRe = new RegExp(`[${whitespaceCodes}]$`);
        this.allWhitespaceOrEmptyRe = new RegExp(`^[${whitespaceCodes}]*$`);
        this.newlineOrNonWhitespaceRe = new RegExp(`(\\n|[^\\n${whitespaceCodes}])`, "g");
        this.newlineOrNonNewlineStringRe = new RegExp(`(\\n|[^\\n]+)`, "g");
        if (options2.preserveNewlines) {
          const wordOrNewlineRe = new RegExp(`\\n|[^\\n${whitespaceCodes}]+`, "gm");
          this.shrinkWrapAdd = function(text, inlineTextBuilder, transform = (str2) => str2, noWrap = false) {
            if (!text) {
              return;
            }
            const previouslyStashedSpace = inlineTextBuilder.stashedSpace;
            let anyMatch = false;
            let m = wordOrNewlineRe.exec(text);
            if (m) {
              anyMatch = true;
              if (m[0] === "\n") {
                inlineTextBuilder.startNewLine();
              } else if (previouslyStashedSpace || this.testLeadingWhitespace(text)) {
                inlineTextBuilder.pushWord(transform(m[0]), noWrap);
              } else {
                inlineTextBuilder.concatWord(transform(m[0]), noWrap);
              }
              while ((m = wordOrNewlineRe.exec(text)) !== null) {
                if (m[0] === "\n") {
                  inlineTextBuilder.startNewLine();
                } else {
                  inlineTextBuilder.pushWord(transform(m[0]), noWrap);
                }
              }
            }
            inlineTextBuilder.stashedSpace = previouslyStashedSpace && !anyMatch || this.testTrailingWhitespace(text);
          };
        } else {
          const wordRe = new RegExp(`[^${whitespaceCodes}]+`, "g");
          this.shrinkWrapAdd = function(text, inlineTextBuilder, transform = (str2) => str2, noWrap = false) {
            if (!text) {
              return;
            }
            const previouslyStashedSpace = inlineTextBuilder.stashedSpace;
            let anyMatch = false;
            let m = wordRe.exec(text);
            if (m) {
              anyMatch = true;
              if (previouslyStashedSpace || this.testLeadingWhitespace(text)) {
                inlineTextBuilder.pushWord(transform(m[0]), noWrap);
              } else {
                inlineTextBuilder.concatWord(transform(m[0]), noWrap);
              }
              while ((m = wordRe.exec(text)) !== null) {
                inlineTextBuilder.pushWord(transform(m[0]), noWrap);
              }
            }
            inlineTextBuilder.stashedSpace = previouslyStashedSpace && !anyMatch || this.testTrailingWhitespace(text);
          };
        }
      }
      /**
       * Add text with only minimal processing.
       * Everything between newlines considered a single word.
       * No whitespace is trimmed.
       * Not affected by preserveNewlines option - `\n` always starts a new line.
       *
       * `noWrap` argument is `true` by default - this won't start a new line
       * even if there is not enough space left in the current line.
       *
       * @param { string }            text              Input text.
       * @param { InlineTextBuilder } inlineTextBuilder A builder to receive processed text.
       * @param { boolean }           [noWrap] Don't wrap text even if the line is too long.
       */
      addLiteral(text, inlineTextBuilder, noWrap = true) {
        if (!text) {
          return;
        }
        const previouslyStashedSpace = inlineTextBuilder.stashedSpace;
        let anyMatch = false;
        let m = this.newlineOrNonNewlineStringRe.exec(text);
        if (m) {
          anyMatch = true;
          if (m[0] === "\n") {
            inlineTextBuilder.startNewLine();
          } else if (previouslyStashedSpace) {
            inlineTextBuilder.pushWord(m[0], noWrap);
          } else {
            inlineTextBuilder.concatWord(m[0], noWrap);
          }
          while ((m = this.newlineOrNonNewlineStringRe.exec(text)) !== null) {
            if (m[0] === "\n") {
              inlineTextBuilder.startNewLine();
            } else {
              inlineTextBuilder.pushWord(m[0], noWrap);
            }
          }
        }
        inlineTextBuilder.stashedSpace = previouslyStashedSpace && !anyMatch;
      }
      /**
       * Test whether the given text starts with HTML whitespace character.
       *
       * @param   { string }  text  The string to test.
       * @returns { boolean }
       */
      testLeadingWhitespace(text) {
        return this.leadingWhitespaceRe.test(text);
      }
      /**
       * Test whether the given text ends with HTML whitespace character.
       *
       * @param   { string }  text  The string to test.
       * @returns { boolean }
       */
      testTrailingWhitespace(text) {
        return this.trailingWhitespaceRe.test(text);
      }
      /**
       * Test whether the given text contains any non-whitespace characters.
       *
       * @param   { string }  text  The string to test.
       * @returns { boolean }
       */
      testContainsWords(text) {
        return !this.allWhitespaceOrEmptyRe.test(text);
      }
      /**
       * Return the number of newlines if there are no words.
       *
       * If any word is found then return zero regardless of the actual number of newlines.
       *
       * @param   { string }  text  Input string.
       * @returns { number }
       */
      countNewlinesNoWords(text) {
        this.newlineOrNonWhitespaceRe.lastIndex = 0;
        let counter = 0;
        let match2;
        while ((match2 = this.newlineOrNonWhitespaceRe.exec(text)) !== null) {
          if (match2[0] === "\n") {
            counter++;
          } else {
            return 0;
          }
        }
        return counter;
      }
    };
    BlockTextBuilder = class {
      static {
        __name(this, "BlockTextBuilder");
      }
      /**
       * Creates an instance of BlockTextBuilder.
       *
       * @param { Options } options HtmlToText options.
       * @param { import('selderee').Picker<DomNode, TagDefinition> } picker Selectors decision tree picker.
       * @param { any} [metadata] Optional metadata for HTML document, for use in formatters.
       */
      constructor(options2, picker, metadata = void 0) {
        this.options = options2;
        this.picker = picker;
        this.metadata = metadata;
        this.whitespaceProcessor = new WhitespaceProcessor(options2);
        this._stackItem = new BlockStackItem(options2);
        this._wordTransformer = void 0;
      }
      /**
       * Put a word-by-word transform function onto the transformations stack.
       *
       * Mainly used for uppercasing. Can be bypassed to add unformatted text such as URLs.
       *
       * Word transformations applied before wrapping.
       *
       * @param { (str: string) => string } wordTransform Word transformation function.
       */
      pushWordTransform(wordTransform) {
        this._wordTransformer = new TransformerStackItem(this._wordTransformer, wordTransform);
      }
      /**
       * Remove a function from the word transformations stack.
       *
       * @returns { (str: string) => string } A function that was removed.
       */
      popWordTransform() {
        if (!this._wordTransformer) {
          return void 0;
        }
        const transform = this._wordTransformer.transform;
        this._wordTransformer = this._wordTransformer.next;
        return transform;
      }
      /**
       * Ignore wordwrap option in followup inline additions and disable automatic wrapping.
       */
      startNoWrap() {
        this._stackItem.isNoWrap = true;
      }
      /**
       * Return automatic wrapping to behavior defined by options.
       */
      stopNoWrap() {
        this._stackItem.isNoWrap = false;
      }
      /** @returns { (str: string) => string } */
      _getCombinedWordTransformer() {
        const wt = this._wordTransformer ? (str2) => applyTransformer(str2, this._wordTransformer) : void 0;
        const ce = this.options.encodeCharacters;
        return wt ? ce ? (str2) => ce(wt(str2)) : wt : ce;
      }
      _popStackItem() {
        const item = this._stackItem;
        this._stackItem = item.next;
        return item;
      }
      /**
       * Add a line break into currently built block.
       */
      addLineBreak() {
        if (!(this._stackItem instanceof BlockStackItem || this._stackItem instanceof ListItemStackItem || this._stackItem instanceof TableCellStackItem)) {
          return;
        }
        if (this._stackItem.isPre) {
          this._stackItem.rawText += "\n";
        } else {
          this._stackItem.inlineTextBuilder.startNewLine();
        }
      }
      /**
       * Allow to break line in case directly following text will not fit.
       */
      addWordBreakOpportunity() {
        if (this._stackItem instanceof BlockStackItem || this._stackItem instanceof ListItemStackItem || this._stackItem instanceof TableCellStackItem) {
          this._stackItem.inlineTextBuilder.wordBreakOpportunity = true;
        }
      }
      /**
       * Add a node inline into the currently built block.
       *
       * @param { string } str
       * Text content of a node to add.
       *
       * @param { object } [param1]
       * Object holding the parameters of the operation.
       *
       * @param { boolean } [param1.noWordTransform]
       * Ignore word transformers if there are any.
       * Don't encode characters as well.
       * (Use this for things like URL addresses).
       */
      addInline(str2, { noWordTransform = false } = {}) {
        if (!(this._stackItem instanceof BlockStackItem || this._stackItem instanceof ListItemStackItem || this._stackItem instanceof TableCellStackItem)) {
          return;
        }
        if (this._stackItem.isPre) {
          this._stackItem.rawText += str2;
          return;
        }
        if (str2.length === 0 || // empty string
        this._stackItem.stashedLineBreaks && // stashed linebreaks make whitespace irrelevant
        !this.whitespaceProcessor.testContainsWords(str2)) {
          return;
        }
        if (this.options.preserveNewlines) {
          const newlinesNumber = this.whitespaceProcessor.countNewlinesNoWords(str2);
          if (newlinesNumber > 0) {
            this._stackItem.inlineTextBuilder.startNewLine(newlinesNumber);
            return;
          }
        }
        if (this._stackItem.stashedLineBreaks) {
          this._stackItem.inlineTextBuilder.startNewLine(this._stackItem.stashedLineBreaks);
        }
        this.whitespaceProcessor.shrinkWrapAdd(
          str2,
          this._stackItem.inlineTextBuilder,
          noWordTransform ? void 0 : this._getCombinedWordTransformer(),
          this._stackItem.isNoWrap
        );
        this._stackItem.stashedLineBreaks = 0;
      }
      /**
       * Add a string inline into the currently built block.
       *
       * Use this for markup elements that don't have to adhere
       * to text layout rules.
       *
       * @param { string } str Text to add.
       */
      addLiteral(str2) {
        if (!(this._stackItem instanceof BlockStackItem || this._stackItem instanceof ListItemStackItem || this._stackItem instanceof TableCellStackItem)) {
          return;
        }
        if (str2.length === 0) {
          return;
        }
        if (this._stackItem.isPre) {
          this._stackItem.rawText += str2;
          return;
        }
        if (this._stackItem.stashedLineBreaks) {
          this._stackItem.inlineTextBuilder.startNewLine(this._stackItem.stashedLineBreaks);
        }
        this.whitespaceProcessor.addLiteral(
          str2,
          this._stackItem.inlineTextBuilder,
          this._stackItem.isNoWrap
        );
        this._stackItem.stashedLineBreaks = 0;
      }
      /**
       * Start building a new block.
       *
       * @param { object } [param0]
       * Object holding the parameters of the block.
       *
       * @param { number } [param0.leadingLineBreaks]
       * This block should have at least this number of line breaks to separate it from any preceding block.
       *
       * @param { number }  [param0.reservedLineLength]
       * Reserve this number of characters on each line for block markup.
       *
       * @param { boolean } [param0.isPre]
       * Should HTML whitespace be preserved inside this block.
       */
      openBlock({ leadingLineBreaks = 1, reservedLineLength = 0, isPre = false } = {}) {
        const maxLineLength = Math.max(20, this._stackItem.inlineTextBuilder.maxLineLength - reservedLineLength);
        this._stackItem = new BlockStackItem(
          this.options,
          this._stackItem,
          leadingLineBreaks,
          maxLineLength
        );
        if (isPre) {
          this._stackItem.isPre = true;
        }
      }
      /**
       * Finalize currently built block, add it's content to the parent block.
       *
       * @param { object } [param0]
       * Object holding the parameters of the block.
       *
       * @param { number } [param0.trailingLineBreaks]
       * This block should have at least this number of line breaks to separate it from any following block.
       *
       * @param { (str: string) => string } [param0.blockTransform]
       * A function to transform the block text before adding to the parent block.
       * This happens after word wrap and should be used in combination with reserved line length
       * in order to keep line lengths correct.
       * Used for whole block markup.
       */
      closeBlock({ trailingLineBreaks = 1, blockTransform = void 0 } = {}) {
        const block2 = this._popStackItem();
        const blockText2 = blockTransform ? blockTransform(getText(block2)) : getText(block2);
        addText(this._stackItem, blockText2, block2.leadingLineBreaks, Math.max(block2.stashedLineBreaks, trailingLineBreaks));
      }
      /**
       * Start building a new list.
       *
       * @param { object } [param0]
       * Object holding the parameters of the list.
       *
       * @param { number } [param0.maxPrefixLength]
       * Length of the longest list item prefix.
       * If not supplied or too small then list items won't be aligned properly.
       *
       * @param { 'left' | 'right' } [param0.prefixAlign]
       * Specify how prefixes of different lengths have to be aligned
       * within a column.
       *
       * @param { number } [param0.interRowLineBreaks]
       * Minimum number of line breaks between list items.
       *
       * @param { number } [param0.leadingLineBreaks]
       * This list should have at least this number of line breaks to separate it from any preceding block.
       */
      openList({ maxPrefixLength = 0, prefixAlign = "left", interRowLineBreaks = 1, leadingLineBreaks = 2 } = {}) {
        this._stackItem = new ListStackItem(this.options, this._stackItem, {
          interRowLineBreaks,
          leadingLineBreaks,
          maxLineLength: this._stackItem.inlineTextBuilder.maxLineLength,
          maxPrefixLength,
          prefixAlign
        });
      }
      /**
       * Start building a new list item.
       *
       * @param {object} param0
       * Object holding the parameters of the list item.
       *
       * @param { string } [param0.prefix]
       * Prefix for this list item (item number, bullet point, etc).
       */
      openListItem({ prefix = "" } = {}) {
        if (!(this._stackItem instanceof ListStackItem)) {
          throw new Error("Can't add a list item to something that is not a list! Check the formatter.");
        }
        const list3 = this._stackItem;
        const prefixLength = Math.max(prefix.length, list3.maxPrefixLength);
        const maxLineLength = Math.max(20, list3.inlineTextBuilder.maxLineLength - prefixLength);
        this._stackItem = new ListItemStackItem(this.options, list3, {
          prefix,
          maxLineLength,
          leadingLineBreaks: list3.interRowLineBreaks
        });
      }
      /**
       * Finalize currently built list item, add it's content to the parent list.
       */
      closeListItem() {
        const listItem = this._popStackItem();
        const list3 = listItem.next;
        const prefixLength = Math.max(listItem.prefix.length, list3.maxPrefixLength);
        const spacing = "\n" + " ".repeat(prefixLength);
        const prefix = list3.prefixAlign === "right" ? listItem.prefix.padStart(prefixLength) : listItem.prefix.padEnd(prefixLength);
        const text = prefix + getText(listItem).replace(/\n/g, spacing);
        addText(
          list3,
          text,
          listItem.leadingLineBreaks,
          Math.max(listItem.stashedLineBreaks, list3.interRowLineBreaks)
        );
      }
      /**
       * Finalize currently built list, add it's content to the parent block.
       *
       * @param { object } param0
       * Object holding the parameters of the list.
       *
       * @param { number } [param0.trailingLineBreaks]
       * This list should have at least this number of line breaks to separate it from any following block.
       */
      closeList({ trailingLineBreaks = 2 } = {}) {
        const list3 = this._popStackItem();
        const text = getText(list3);
        if (text) {
          addText(this._stackItem, text, list3.leadingLineBreaks, trailingLineBreaks);
        }
      }
      /**
       * Start building a table.
       */
      openTable() {
        this._stackItem = new TableStackItem(this._stackItem);
      }
      /**
       * Start building a table row.
       */
      openTableRow() {
        if (!(this._stackItem instanceof TableStackItem)) {
          throw new Error("Can't add a table row to something that is not a table! Check the formatter.");
        }
        this._stackItem = new TableRowStackItem(this._stackItem);
      }
      /**
       * Start building a table cell.
       *
       * @param { object } [param0]
       * Object holding the parameters of the cell.
       *
       * @param { number } [param0.maxColumnWidth]
       * Wrap cell content to this width. Fall back to global wordwrap value if undefined.
       */
      openTableCell({ maxColumnWidth = void 0 } = {}) {
        if (!(this._stackItem instanceof TableRowStackItem)) {
          throw new Error("Can't add a table cell to something that is not a table row! Check the formatter.");
        }
        this._stackItem = new TableCellStackItem(this.options, this._stackItem, maxColumnWidth);
      }
      /**
       * Finalize currently built table cell and add it to parent table row's cells.
       *
       * @param { object } [param0]
       * Object holding the parameters of the cell.
       *
       * @param { number } [param0.colspan] How many columns this cell should occupy.
       * @param { number } [param0.rowspan] How many rows this cell should occupy.
       */
      closeTableCell({ colspan = 1, rowspan = 1 } = {}) {
        const cell = this._popStackItem();
        const text = trimCharacter(getText(cell), "\n");
        cell.next.cells.push({ colspan, rowspan, text });
      }
      /**
       * Finalize currently built table row and add it to parent table's rows.
       */
      closeTableRow() {
        const row = this._popStackItem();
        row.next.rows.push(row.cells);
      }
      /**
       * Finalize currently built table and add the rendered text to the parent block.
       *
       * @param { object } param0
       * Object holding the parameters of the table.
       *
       * @param { TablePrinter } param0.tableToString
       * A function to convert a table of stringified cells into a complete table.
       *
       * @param { number } [param0.leadingLineBreaks]
       * This table should have at least this number of line breaks to separate if from any preceding block.
       *
       * @param { number } [param0.trailingLineBreaks]
       * This table should have at least this number of line breaks to separate it from any following block.
       */
      closeTable({ tableToString: tableToString2, leadingLineBreaks = 2, trailingLineBreaks = 2 }) {
        const table = this._popStackItem();
        const output = tableToString2(table.rows);
        if (output) {
          addText(this._stackItem, output, leadingLineBreaks, trailingLineBreaks);
        }
      }
      /**
       * Return the rendered text content of this builder.
       *
       * @returns { string }
       */
      toString() {
        return getText(this._stackItem.getRoot());
      }
    };
    __name(getText, "getText");
    __name(addText, "addText");
    __name(applyTransformer, "applyTransformer");
    __name(compile$1, "compile$1");
    __name(process21, "process");
    __name(findBases, "findBases");
    __name(recursiveWalk, "recursiveWalk");
    __name(makeReplacerFromDict, "makeReplacerFromDict");
    __name(formatSkip, "formatSkip");
    __name(formatInlineString, "formatInlineString");
    __name(formatBlockString, "formatBlockString");
    __name(formatInline, "formatInline");
    __name(formatBlock$1, "formatBlock$1");
    __name(renderOpenTag, "renderOpenTag");
    __name(renderCloseTag, "renderCloseTag");
    __name(formatInlineTag, "formatInlineTag");
    __name(formatBlockTag, "formatBlockTag");
    __name(formatInlineHtml, "formatInlineHtml");
    __name(formatBlockHtml, "formatBlockHtml");
    __name(formatInlineSurround, "formatInlineSurround");
    genericFormatters = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      block: formatBlock$1,
      blockHtml: formatBlockHtml,
      blockString: formatBlockString,
      blockTag: formatBlockTag,
      inline: formatInline,
      inlineHtml: formatInlineHtml,
      inlineString: formatInlineString,
      inlineSurround: formatInlineSurround,
      inlineTag: formatInlineTag,
      skip: formatSkip
    });
    __name(getRow, "getRow");
    __name(findFirstVacantIndex, "findFirstVacantIndex");
    __name(transposeInPlace, "transposeInPlace");
    __name(putCellIntoLayout, "putCellIntoLayout");
    __name(getOrInitOffset, "getOrInitOffset");
    __name(updateOffset, "updateOffset");
    __name(tableToString, "tableToString");
    __name(formatLineBreak, "formatLineBreak");
    __name(formatWbr, "formatWbr");
    __name(formatHorizontalLine, "formatHorizontalLine");
    __name(formatParagraph, "formatParagraph");
    __name(formatPre, "formatPre");
    __name(formatHeading, "formatHeading");
    __name(formatBlockquote, "formatBlockquote");
    __name(withBrackets, "withBrackets");
    __name(pathRewrite, "pathRewrite");
    __name(formatImage, "formatImage");
    __name(formatAnchor, "formatAnchor");
    __name(formatList, "formatList");
    __name(formatUnorderedList, "formatUnorderedList");
    __name(formatOrderedList, "formatOrderedList");
    __name(getOrderedListIndexFunction, "getOrderedListIndexFunction");
    __name(splitClassesAndIds, "splitClassesAndIds");
    __name(isDataTable, "isDataTable");
    __name(formatTable, "formatTable");
    __name(formatBlock, "formatBlock");
    __name(formatDataTable, "formatDataTable");
    textFormatters = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      anchor: formatAnchor,
      blockquote: formatBlockquote,
      dataTable: formatDataTable,
      heading: formatHeading,
      horizontalLine: formatHorizontalLine,
      image: formatImage,
      lineBreak: formatLineBreak,
      orderedList: formatOrderedList,
      paragraph: formatParagraph,
      pre: formatPre,
      table: formatTable,
      unorderedList: formatUnorderedList,
      wbr: formatWbr
    });
    DEFAULT_OPTIONS = {
      baseElements: {
        selectors: ["body"],
        orderBy: "selectors",
        // 'selectors' | 'occurrence'
        returnDomByDefault: true
      },
      decodeEntities: true,
      encodeCharacters: {},
      formatters: {},
      limits: {
        ellipsis: "...",
        maxBaseElements: void 0,
        maxChildNodes: void 0,
        maxDepth: void 0,
        maxInputLength: 1 << 24
        // 16_777_216
      },
      longWordSplit: {
        forceWrapOnLimit: false,
        wrapCharacters: []
      },
      preserveNewlines: false,
      selectors: [
        { selector: "*", format: "inline" },
        {
          selector: "a",
          format: "anchor",
          options: {
            baseUrl: null,
            hideLinkHrefIfSameAsText: false,
            ignoreHref: false,
            linkBrackets: ["[", "]"],
            noAnchorUrl: true
          }
        },
        { selector: "article", format: "block", options: { leadingLineBreaks: 1, trailingLineBreaks: 1 } },
        { selector: "aside", format: "block", options: { leadingLineBreaks: 1, trailingLineBreaks: 1 } },
        {
          selector: "blockquote",
          format: "blockquote",
          options: { leadingLineBreaks: 2, trailingLineBreaks: 2, trimEmptyLines: true }
        },
        { selector: "br", format: "lineBreak" },
        { selector: "div", format: "block", options: { leadingLineBreaks: 1, trailingLineBreaks: 1 } },
        { selector: "footer", format: "block", options: { leadingLineBreaks: 1, trailingLineBreaks: 1 } },
        { selector: "form", format: "block", options: { leadingLineBreaks: 1, trailingLineBreaks: 1 } },
        { selector: "h1", format: "heading", options: { leadingLineBreaks: 3, trailingLineBreaks: 2, uppercase: true } },
        { selector: "h2", format: "heading", options: { leadingLineBreaks: 3, trailingLineBreaks: 2, uppercase: true } },
        { selector: "h3", format: "heading", options: { leadingLineBreaks: 3, trailingLineBreaks: 2, uppercase: true } },
        { selector: "h4", format: "heading", options: { leadingLineBreaks: 2, trailingLineBreaks: 2, uppercase: true } },
        { selector: "h5", format: "heading", options: { leadingLineBreaks: 2, trailingLineBreaks: 2, uppercase: true } },
        { selector: "h6", format: "heading", options: { leadingLineBreaks: 2, trailingLineBreaks: 2, uppercase: true } },
        { selector: "header", format: "block", options: { leadingLineBreaks: 1, trailingLineBreaks: 1 } },
        {
          selector: "hr",
          format: "horizontalLine",
          options: { leadingLineBreaks: 2, length: void 0, trailingLineBreaks: 2 }
        },
        {
          selector: "img",
          format: "image",
          options: { baseUrl: null, linkBrackets: ["[", "]"] }
        },
        { selector: "main", format: "block", options: { leadingLineBreaks: 1, trailingLineBreaks: 1 } },
        { selector: "nav", format: "block", options: { leadingLineBreaks: 1, trailingLineBreaks: 1 } },
        {
          selector: "ol",
          format: "orderedList",
          options: { leadingLineBreaks: 2, trailingLineBreaks: 2 }
        },
        { selector: "p", format: "paragraph", options: { leadingLineBreaks: 2, trailingLineBreaks: 2 } },
        { selector: "pre", format: "pre", options: { leadingLineBreaks: 2, trailingLineBreaks: 2 } },
        { selector: "section", format: "block", options: { leadingLineBreaks: 1, trailingLineBreaks: 1 } },
        {
          selector: "table",
          format: "table",
          options: {
            colSpacing: 3,
            leadingLineBreaks: 2,
            maxColumnWidth: 60,
            rowSpacing: 0,
            trailingLineBreaks: 2,
            uppercaseHeaderCells: true
          }
        },
        {
          selector: "ul",
          format: "unorderedList",
          options: { itemPrefix: " * ", leadingLineBreaks: 2, trailingLineBreaks: 2 }
        },
        { selector: "wbr", format: "wbr" }
      ],
      tables: [],
      // deprecated
      whitespaceCharacters: " 	\r\n\f\u200B",
      wordwrap: 80
    };
    concatMerge = /* @__PURE__ */ __name((acc, src, options2) => [...acc, ...src], "concatMerge");
    overwriteMerge = /* @__PURE__ */ __name((acc, src, options2) => [...src], "overwriteMerge");
    selectorsMerge = /* @__PURE__ */ __name((acc, src, options2) => acc.some((s2) => typeof s2 === "object") ? concatMerge(acc, src) : overwriteMerge(acc, src), "selectorsMerge");
    __name(compile, "compile");
    __name(convert, "convert");
    __name(handleDeprecatedOptions, "handleDeprecatedOptions");
  }
});

// packages/core/dist/src/utils/fetch.js
import { URL as URL5 } from "node:url";
function isPrivateIp(url2) {
  try {
    const hostname3 = new URL5(url2).hostname;
    return PRIVATE_IP_RANGES.some((range) => range.test(hostname3));
  } catch (_e) {
    return false;
  }
}
async function fetchWithTimeout(url2, timeout2) {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), timeout2);
  try {
    const response = await fetch(url2, { signal: controller.signal });
    return response;
  } catch (error) {
    if (isNodeError(error) && error.code === "ABORT_ERR") {
      throw new FetchError(`Request timed out after ${timeout2}ms`, "ETIMEDOUT");
    }
    throw new FetchError(getErrorMessage(error));
  } finally {
    clearTimeout(timeoutId);
  }
}
var PRIVATE_IP_RANGES, FetchError;
var init_fetch2 = __esm({
  "packages/core/dist/src/utils/fetch.js"() {
    "use strict";
    init_esbuild_shims();
    init_errors();
    PRIVATE_IP_RANGES = [
      /^10\./,
      /^127\./,
      /^172\.(1[6-9]|2[0-9]|3[0-1])\./,
      /^192\.168\./,
      /^::1$/,
      /^fc00:/,
      /^fe80:/
    ];
    FetchError = class extends Error {
      static {
        __name(this, "FetchError");
      }
      code;
      constructor(message, code2) {
        super(message);
        this.code = code2;
        this.name = "FetchError";
      }
    };
    __name(isPrivateIp, "isPrivateIp");
    __name(fetchWithTimeout, "fetchWithTimeout");
  }
});

// packages/core/dist/src/tools/web-fetch.js
var import_undici2, URL_FETCH_TIMEOUT_MS, MAX_CONTENT_LENGTH, WebFetchToolInvocation, WebFetchTool;
var init_web_fetch = __esm({
  "packages/core/dist/src/tools/web-fetch.js"() {
    "use strict";
    init_esbuild_shims();
    init_html_to_text();
    import_undici2 = __toESM(require_undici(), 1);
    init_config3();
    init_fetch2();
    init_partUtils();
    init_tool_error();
    init_tools();
    init_models();
    init_tool_names();
    URL_FETCH_TIMEOUT_MS = 1e4;
    MAX_CONTENT_LENGTH = 1e5;
    WebFetchToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "WebFetchToolInvocation");
      }
      config;
      constructor(config, params) {
        super(params);
        this.config = config;
      }
      async executeDirectFetch(signal) {
        let url2 = this.params.url;
        if (url2.includes("github.com") && url2.includes("/blob/")) {
          url2 = url2.replace("github.com", "raw.githubusercontent.com").replace("/blob/", "/");
          console.debug(`[WebFetchTool] Converted GitHub blob URL to raw URL: ${url2}`);
        }
        try {
          console.debug(`[WebFetchTool] Fetching content from: ${url2}`);
          const response = await fetchWithTimeout(url2, URL_FETCH_TIMEOUT_MS);
          if (!response.ok) {
            const errorMessage = `Request failed with status code ${response.status} ${response.statusText}`;
            console.error(`[WebFetchTool] ${errorMessage}`);
            throw new Error(errorMessage);
          }
          console.debug(`[WebFetchTool] Successfully fetched content from ${url2}`);
          const html2 = await response.text();
          const textContent2 = convert(html2, {
            wordwrap: false,
            selectors: [
              { selector: "a", options: { ignoreHref: true } },
              { selector: "img", format: "skip" }
            ]
          }).substring(0, MAX_CONTENT_LENGTH);
          console.debug(`[WebFetchTool] Converted HTML to text (${textContent2.length} characters)`);
          const geminiClient = this.config.getGeminiClient();
          const fallbackPrompt = `The user requested the following: "${this.params.prompt}".

I have fetched the content from ${this.params.url}. Please use the following content to answer the user's request.

---
${textContent2}
---`;
          console.debug(`[WebFetchTool] Processing content with prompt: "${this.params.prompt}"`);
          const result = await geminiClient.generateContent([{ role: "user", parts: [{ text: fallbackPrompt }] }], {}, signal, this.config.getModel() || DEFAULT_QWEN_MODEL);
          const resultText = getResponseText(result) || "";
          console.debug(`[WebFetchTool] Successfully processed content from ${this.params.url}`);
          return {
            llmContent: resultText,
            returnDisplay: `Content from ${this.params.url} processed successfully.`
          };
        } catch (e2) {
          const error = e2;
          const errorMessage = `Error during fetch for ${url2}: ${error.message}`;
          console.error(`[WebFetchTool] ${errorMessage}`, error);
          return {
            llmContent: `Error: ${errorMessage}`,
            returnDisplay: `Error: ${errorMessage}`,
            error: {
              message: errorMessage,
              type: ToolErrorType.WEB_FETCH_FALLBACK_FAILED
            }
          };
        }
      }
      getDescription() {
        const displayPrompt = this.params.prompt.length > 100 ? this.params.prompt.substring(0, 97) + "..." : this.params.prompt;
        return `Fetching content from ${this.params.url} and processing with prompt: "${displayPrompt}"`;
      }
      async shouldConfirmExecute() {
        if (this.config.getApprovalMode() === ApprovalMode.AUTO_EDIT) {
          return false;
        }
        const confirmationDetails = {
          type: "info",
          title: `Confirm Web Fetch`,
          prompt: `Fetch content from ${this.params.url} and process with: ${this.params.prompt}`,
          urls: [this.params.url],
          onConfirm: /* @__PURE__ */ __name(async (outcome) => {
            if (outcome === ToolConfirmationOutcome.ProceedAlways) {
              this.config.setApprovalMode(ApprovalMode.AUTO_EDIT);
            }
          }, "onConfirm")
        };
        return confirmationDetails;
      }
      async execute(signal) {
        const isPrivate = isPrivateIp(this.params.url);
        if (isPrivate) {
          console.debug(`[WebFetchTool] Private IP detected for ${this.params.url}, using direct fetch`);
        } else {
          console.debug(`[WebFetchTool] Public URL detected for ${this.params.url}, using direct fetch`);
        }
        return this.executeDirectFetch(signal);
      }
    };
    WebFetchTool = class _WebFetchTool extends BaseDeclarativeTool {
      static {
        __name(this, "WebFetchTool");
      }
      config;
      static Name = ToolNames.WEB_FETCH;
      constructor(config) {
        super(_WebFetchTool.Name, ToolDisplayNames.WEB_FETCH, `Fetches content from a specified URL and processes it using an AI model
- Takes a URL and a prompt as input
- Fetches the URL content, converts HTML to markdown
- Processes the content with the prompt using a small, fast model
- Returns the model's response about the content
- Use this tool when you need to retrieve and analyze web content

Usage notes:
  - IMPORTANT: If an MCP-provided web fetch tool is available, prefer using that tool instead of this one, as it may have fewer restrictions. All MCP-provided tools start with "mcp__".
  - The URL must be a fully-formed valid URL
  - The prompt should describe what information you want to extract from the page
  - This tool is read-only and does not modify any files
  - Results may be summarized if the content is very large
  - Supports both public and private/localhost URLs using direct fetch`, Kind.Fetch, {
          properties: {
            url: {
              description: "The URL to fetch content from",
              type: "string"
            },
            prompt: {
              description: "The prompt to run on the fetched content",
              type: "string"
            }
          },
          required: ["url", "prompt"],
          type: "object"
        });
        this.config = config;
        const proxy = config.getProxy();
        if (proxy) {
          (0, import_undici2.setGlobalDispatcher)(new import_undici2.ProxyAgent(proxy));
        }
      }
      validateToolParamValues(params) {
        if (!params.url || params.url.trim() === "") {
          return "The 'url' parameter cannot be empty.";
        }
        if (!params.url.startsWith("http://") && !params.url.startsWith("https://")) {
          return "The 'url' must be a valid URL starting with http:// or https://.";
        }
        if (!params.prompt || params.prompt.trim() === "") {
          return "The 'prompt' parameter cannot be empty.";
        }
        return null;
      }
      createInvocation(params) {
        return new WebFetchToolInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/tools/web-search/utils.js
function buildContentWithSources(content, sources) {
  if (!sources.length)
    return content;
  const sourceList = sources.map((s2, i) => `[${i + 1}] ${s2.title || "Untitled"} (${s2.url})`).join("\n");
  return `${content}

Sources:
${sourceList}`;
}
var init_utils7 = __esm({
  "packages/core/dist/src/tools/web-search/utils.js"() {
    "use strict";
    init_esbuild_shims();
    __name(buildContentWithSources, "buildContentWithSources");
  }
});

// packages/core/dist/src/tools/web-search/base-provider.js
var BaseWebSearchProvider;
var init_base_provider = __esm({
  "packages/core/dist/src/tools/web-search/base-provider.js"() {
    "use strict";
    init_esbuild_shims();
    BaseWebSearchProvider = class {
      static {
        __name(this, "BaseWebSearchProvider");
      }
      /**
       * Execute a web search with error handling.
       * @param query The search query
       * @param signal Abort signal for cancellation
       * @returns Promise resolving to search results
       */
      async search(query, signal) {
        if (!this.isAvailable()) {
          throw new Error(`[${this.name}] Provider is not available. Please check your configuration.`);
        }
        try {
          return await this.performSearch(query, signal);
        } catch (error) {
          if (error instanceof Error && error.message.startsWith(`[${this.name}]`)) {
            throw error;
          }
          const message = error instanceof Error ? error.message : String(error);
          throw new Error(`[${this.name}] Search failed: ${message}`);
        }
      }
    };
  }
});

// packages/core/dist/src/tools/web-search/providers/tavily-provider.js
var TavilyProvider;
var init_tavily_provider = __esm({
  "packages/core/dist/src/tools/web-search/providers/tavily-provider.js"() {
    "use strict";
    init_esbuild_shims();
    init_base_provider();
    TavilyProvider = class extends BaseWebSearchProvider {
      static {
        __name(this, "TavilyProvider");
      }
      config;
      name = "Tavily";
      constructor(config) {
        super();
        this.config = config;
      }
      isAvailable() {
        return !!this.config.apiKey;
      }
      async performSearch(query, signal) {
        const response = await fetch("https://api.tavily.com/search", {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            api_key: this.config.apiKey,
            query,
            search_depth: this.config.searchDepth || "advanced",
            max_results: this.config.maxResults || 5,
            include_answer: this.config.includeAnswer !== false
          }),
          signal
        });
        if (!response.ok) {
          const text = await response.text().catch(() => "");
          throw new Error(`API error: ${response.status} ${response.statusText}${text ? ` - ${text}` : ""}`);
        }
        const data = await response.json();
        const results = (data.results || []).map((r3) => ({
          title: r3.title,
          url: r3.url,
          content: r3.content,
          score: r3.score,
          publishedDate: r3.published_date
        }));
        return {
          query,
          answer: data.answer?.trim(),
          results
        };
      }
    };
  }
});

// packages/core/dist/src/tools/web-search/providers/google-provider.js
var GoogleProvider;
var init_google_provider = __esm({
  "packages/core/dist/src/tools/web-search/providers/google-provider.js"() {
    "use strict";
    init_esbuild_shims();
    init_base_provider();
    GoogleProvider = class extends BaseWebSearchProvider {
      static {
        __name(this, "GoogleProvider");
      }
      config;
      name = "Google";
      constructor(config) {
        super();
        this.config = config;
      }
      isAvailable() {
        return !!(this.config.apiKey && this.config.searchEngineId);
      }
      async performSearch(query, signal) {
        const params = new URLSearchParams({
          key: this.config.apiKey,
          cx: this.config.searchEngineId,
          q: query,
          num: String(this.config.maxResults || 10),
          safe: this.config.safeSearch || "medium"
        });
        if (this.config.language) {
          params.append("lr", `lang_${this.config.language}`);
        }
        if (this.config.country) {
          params.append("cr", `country${this.config.country}`);
        }
        const url2 = `https://www.googleapis.com/customsearch/v1?${params.toString()}`;
        const response = await fetch(url2, {
          method: "GET",
          signal
        });
        if (!response.ok) {
          const text = await response.text().catch(() => "");
          throw new Error(`API error: ${response.status} ${response.statusText}${text ? ` - ${text}` : ""}`);
        }
        const data = await response.json();
        const results = (data.items || []).map((item) => ({
          title: item.title,
          url: item.link,
          content: item.snippet
        }));
        return {
          query,
          results
        };
      }
    };
  }
});

// packages/core/dist/src/tools/web-search/providers/dashscope-provider.js
import { promises as fs40 } from "node:fs";
import * as os20 from "os";
import * as path44 from "path";
function getQwenCachedCredentialPath2() {
  return path44.join(os20.homedir(), QWEN_DIR6, QWEN_CREDENTIAL_FILENAME3);
}
async function loadQwenCredentials() {
  try {
    const keyFile = getQwenCachedCredentialPath2();
    const creds = await fs40.readFile(keyFile, "utf-8");
    return JSON.parse(creds);
  } catch {
    return null;
  }
}
var QWEN_DIR6, QWEN_CREDENTIAL_FILENAME3, DashScopeProvider;
var init_dashscope_provider = __esm({
  "packages/core/dist/src/tools/web-search/providers/dashscope-provider.js"() {
    "use strict";
    init_esbuild_shims();
    init_base_provider();
    QWEN_DIR6 = ".qwen";
    QWEN_CREDENTIAL_FILENAME3 = "oauth_creds.json";
    __name(getQwenCachedCredentialPath2, "getQwenCachedCredentialPath");
    __name(loadQwenCredentials, "loadQwenCredentials");
    DashScopeProvider = class extends BaseWebSearchProvider {
      static {
        __name(this, "DashScopeProvider");
      }
      config;
      name = "DashScope";
      constructor(config) {
        super();
        this.config = config;
      }
      isAvailable() {
        return this.config.authType === "qwen-oauth";
      }
      /**
       * Get the access token and API endpoint for authentication and web search.
       * Tries OAuth credentials first, falls back to apiKey if OAuth is not available.
       * Returns both token and endpoint to avoid loading credentials multiple times.
       */
      async getAuthConfig() {
        const credentials = await loadQwenCredentials();
        let accessToken = null;
        if (credentials?.access_token) {
          if (credentials.expiry_date && credentials.expiry_date > Date.now()) {
            accessToken = credentials.access_token;
          }
        }
        if (!accessToken) {
          accessToken = this.config.apiKey || null;
        }
        if (!credentials?.resource_url) {
          throw new Error("No resource_url found in credentials. Please authenticate using OAuth");
        }
        const baseUrl = credentials.resource_url.startsWith("http") ? credentials.resource_url : `https://${credentials.resource_url}`;
        const normalizedBaseUrl = baseUrl.replace(/\/$/, "");
        const apiEndpoint = `${normalizedBaseUrl}/api/v1/indices/plugin/web_search`;
        return { accessToken, apiEndpoint };
      }
      async performSearch(query, signal) {
        const { accessToken, apiEndpoint } = await this.getAuthConfig();
        if (!accessToken) {
          throw new Error("No access token available. Please authenticate using OAuth");
        }
        const requestBody = {
          uq: query,
          page: 1,
          rows: this.config.maxResults || 10
        };
        const response = await fetch(apiEndpoint, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${accessToken}`
          },
          body: JSON.stringify(requestBody),
          signal
        });
        if (!response.ok) {
          const text = await response.text().catch(() => "");
          throw new Error(`API error: ${response.status} ${response.statusText}${text ? ` - ${text}` : ""}`);
        }
        const data = await response.json();
        if (data.status !== 0) {
          throw new Error(`API error: ${data.message || "Unknown error"}`);
        }
        const results = (data.data?.docs || []).map((item) => ({
          title: item.title,
          url: item.url,
          content: item.snippet,
          score: item._score,
          publishedDate: item.timestamp_format
        }));
        return {
          query,
          results
        };
      }
    };
  }
});

// packages/core/dist/src/tools/web-search/index.js
var WebSearchToolInvocation, WebSearchTool;
var init_web_search = __esm({
  "packages/core/dist/src/tools/web-search/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    init_tool_error();
    init_config3();
    init_errors();
    init_utils7();
    init_tavily_provider();
    init_google_provider();
    init_dashscope_provider();
    init_tool_names();
    WebSearchToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "WebSearchToolInvocation");
      }
      config;
      constructor(config, params) {
        super(params);
        this.config = config;
      }
      getDescription() {
        const webSearchConfig = this.config.getWebSearchConfig();
        if (!webSearchConfig) {
          return " (Web search is disabled - configure a provider in settings.json)";
        }
        const provider = this.params.provider || webSearchConfig.default;
        return ` (Searching the web via ${provider})`;
      }
      async shouldConfirmExecute(_abortSignal) {
        if (this.config.getApprovalMode() === ApprovalMode.AUTO_EDIT) {
          return false;
        }
        const confirmationDetails = {
          type: "info",
          title: "Confirm Web Search",
          prompt: `Search the web for: "${this.params.query}"`,
          onConfirm: /* @__PURE__ */ __name(async (outcome) => {
            if (outcome === ToolConfirmationOutcome.ProceedAlways) {
              this.config.setApprovalMode(ApprovalMode.AUTO_EDIT);
            }
          }, "onConfirm")
        };
        return confirmationDetails;
      }
      /**
       * Create a provider instance from configuration.
       */
      createProvider(config) {
        switch (config.type) {
          case "tavily":
            return new TavilyProvider(config);
          case "google":
            return new GoogleProvider(config);
          case "dashscope": {
            const authType = this.config.getAuthType();
            const dashscopeConfig = {
              ...config,
              authType
            };
            return new DashScopeProvider(dashscopeConfig);
          }
          default:
            throw new Error("Unknown provider type");
        }
      }
      /**
       * Create all configured providers.
       */
      createProviders(configs) {
        const providers = /* @__PURE__ */ new Map();
        for (const config of configs) {
          try {
            const provider = this.createProvider(config);
            if (provider.isAvailable()) {
              providers.set(config.type, provider);
            }
          } catch (error) {
            console.warn(`Failed to create ${config.type} provider:`, error);
          }
        }
        return providers;
      }
      /**
       * Select the appropriate provider based on configuration and parameters.
       * Throws error if provider not found.
       */
      selectProvider(providers, requestedProvider, defaultProvider) {
        if (requestedProvider) {
          const provider = providers.get(requestedProvider);
          if (!provider) {
            const available = Array.from(providers.keys()).join(", ");
            throw new Error(`The specified provider "${requestedProvider}" is not available. Available: ${available}`);
          }
          return provider;
        }
        if (defaultProvider && providers.has(defaultProvider)) {
          return providers.get(defaultProvider);
        }
        const firstProvider = providers.values().next().value;
        if (!firstProvider) {
          throw new Error("No web search providers are available.");
        }
        return firstProvider;
      }
      /**
       * Format search results into a content string.
       */
      formatSearchResults(searchResult) {
        const sources = searchResult.results.map((r3) => ({
          title: r3.title,
          url: r3.url
        }));
        let content = searchResult.answer?.trim() || "";
        if (!content) {
          content = searchResult.results.slice(0, 5).map((r3, i) => {
            const parts = [`${i + 1}. **${r3.title}**`];
            if (r3.content?.trim()) {
              parts.push(`   ${r3.content.trim()}`);
            }
            parts.push(`   Source: ${r3.url}`);
            if (r3.score !== void 0) {
              parts.push(`   Relevance: ${(r3.score * 100).toFixed(0)}%`);
            }
            if (r3.publishedDate) {
              parts.push(`   Published: ${r3.publishedDate}`);
            }
            return parts.join("\n");
          }).join("\n\n");
          if (content) {
            content += "\n\n*Note: For detailed content from any source above, use the web_fetch tool with the URL.*";
          }
        } else {
          content = buildContentWithSources(content, sources);
        }
        return { content, sources };
      }
      async execute(signal) {
        const webSearchConfig = this.config.getWebSearchConfig();
        if (!webSearchConfig) {
          return {
            llmContent: "Web search is disabled. Please configure a web search provider in your settings.",
            returnDisplay: "Web search is disabled.",
            error: {
              message: "Web search is disabled",
              type: ToolErrorType.EXECUTION_FAILED
            }
          };
        }
        try {
          const providers = this.createProviders(webSearchConfig.provider);
          const provider = this.selectProvider(providers, this.params.provider, webSearchConfig.default);
          const searchResult = await provider.search(this.params.query, signal);
          const { content, sources } = this.formatSearchResults(searchResult);
          if (!content.trim()) {
            return {
              llmContent: `No search results found for query: "${this.params.query}" (via ${provider.name})`,
              returnDisplay: `No information found for "${this.params.query}".`
            };
          }
          return {
            llmContent: `Web search results for "${this.params.query}" (via ${provider.name}):

${content}`,
            returnDisplay: `Search results for "${this.params.query}".`,
            sources
          };
        } catch (error) {
          const errorMessage = `Error during web search: ${getErrorMessage(error)}`;
          console.error(errorMessage, error);
          return {
            llmContent: errorMessage,
            returnDisplay: "Error performing web search.",
            error: {
              message: errorMessage,
              type: ToolErrorType.EXECUTION_FAILED
            }
          };
        }
      }
    };
    WebSearchTool = class _WebSearchTool extends BaseDeclarativeTool {
      static {
        __name(this, "WebSearchTool");
      }
      config;
      static Name = ToolNames.WEB_SEARCH;
      constructor(config) {
        super(_WebSearchTool.Name, ToolDisplayNames.WEB_SEARCH, "Allows searching the web and using results to inform responses. Provides up-to-date information for current events and recent data beyond the training data cutoff. Returns search results formatted with concise answers and source links. Use this tool when accessing information that may be outdated or beyond the knowledge cutoff.", Kind.Search, {
          type: "object",
          properties: {
            query: {
              type: "string",
              description: "The search query to find information on the web."
            },
            provider: {
              type: "string",
              description: 'Optional provider to use for the search (e.g., "tavily", "google", "dashscope"). IMPORTANT: Only specify this parameter if you explicitly know which provider to use. Otherwise, omit this parameter entirely and let the system automatically select the appropriate provider based on availability and configuration. The system will choose the best available provider automatically.'
            }
          },
          required: ["query"]
        });
        this.config = config;
      }
      /**
       * Validates the parameters for the WebSearchTool.
       * @param params The parameters to validate
       * @returns An error message string if validation fails, null if valid
       */
      validateToolParamValues(params) {
        if (!params.query || params.query.trim() === "") {
          return "The 'query' parameter cannot be empty.";
        }
        if (params.provider !== void 0 && params.provider.trim() === "") {
          return "The 'provider' parameter cannot be empty if specified.";
        }
        return null;
      }
      createInvocation(params) {
        return new WebSearchToolInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/tools/write-file.js
import fs41 from "node:fs";
import path45 from "node:path";
async function getCorrectedFileContent(config, filePath, proposedContent) {
  let originalContent = "";
  let fileExists2 = false;
  const correctedContent = proposedContent;
  try {
    originalContent = await config.getFileSystemService().readTextFile(filePath);
    fileExists2 = true;
  } catch (err) {
    if (isNodeError(err) && err.code === "ENOENT") {
      fileExists2 = false;
      originalContent = "";
    } else {
      fileExists2 = true;
      originalContent = "";
      const error = {
        message: getErrorMessage(err),
        code: isNodeError(err) ? err.code : void 0
      };
      return { originalContent, correctedContent, fileExists: fileExists2, error };
    }
  }
  return { originalContent, correctedContent, fileExists: fileExists2 };
}
var WriteFileToolInvocation, WriteFileTool;
var init_write_file = __esm({
  "packages/core/dist/src/tools/write-file.js"() {
    "use strict";
    init_esbuild_shims();
    init_lib();
    init_config3();
    init_tools();
    init_tool_error();
    init_paths();
    init_errors();
    init_diffOptions();
    init_tool_names();
    init_ide_client();
    init_loggers();
    init_types3();
    init_metrics2();
    init_fileUtils();
    init_language_detection();
    __name(getCorrectedFileContent, "getCorrectedFileContent");
    WriteFileToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "WriteFileToolInvocation");
      }
      config;
      constructor(config, params) {
        super(params);
        this.config = config;
      }
      toolLocations() {
        return [{ path: this.params.file_path }];
      }
      getDescription() {
        const relativePath = makeRelative(this.params.file_path, this.config.getTargetDir());
        return `Writing to ${shortenPath(relativePath)}`;
      }
      async shouldConfirmExecute(_abortSignal) {
        if (this.config.getApprovalMode() === ApprovalMode.AUTO_EDIT) {
          return false;
        }
        const correctedContentResult = await getCorrectedFileContent(this.config, this.params.file_path, this.params.content);
        if (correctedContentResult.error) {
          return false;
        }
        const { originalContent, correctedContent } = correctedContentResult;
        const relativePath = makeRelative(this.params.file_path, this.config.getTargetDir());
        const fileName = path45.basename(this.params.file_path);
        const fileDiff = createPatch(
          fileName,
          originalContent,
          // Original content (empty if new file or unreadable)
          correctedContent,
          // Content after potential correction
          "Current",
          "Proposed",
          DEFAULT_DIFF_OPTIONS
        );
        const ideClient = await IdeClient.getInstance();
        const ideConfirmation = this.config.getIdeMode() && ideClient.isDiffingEnabled() ? ideClient.openDiff(this.params.file_path, correctedContent) : void 0;
        const confirmationDetails = {
          type: "edit",
          title: `Confirm Write: ${shortenPath(relativePath)}`,
          fileName,
          filePath: this.params.file_path,
          fileDiff,
          originalContent,
          newContent: correctedContent,
          onConfirm: /* @__PURE__ */ __name(async (outcome) => {
            if (outcome === ToolConfirmationOutcome.ProceedAlways) {
              this.config.setApprovalMode(ApprovalMode.AUTO_EDIT);
            }
            if (ideConfirmation) {
              const result = await ideConfirmation;
              if (result.status === "accepted" && result.content) {
                this.params.content = result.content;
              }
            }
          }, "onConfirm"),
          ideConfirmation
        };
        return confirmationDetails;
      }
      async execute(_abortSignal) {
        const { file_path, content, ai_proposed_content, modified_by_user } = this.params;
        const correctedContentResult = await getCorrectedFileContent(this.config, file_path, content);
        if (correctedContentResult.error) {
          const errDetails = correctedContentResult.error;
          const errorMsg = errDetails.code ? `Error checking existing file '${file_path}': ${errDetails.message} (${errDetails.code})` : `Error checking existing file: ${errDetails.message}`;
          return {
            llmContent: errorMsg,
            returnDisplay: errorMsg,
            error: {
              message: errorMsg,
              type: ToolErrorType.FILE_WRITE_FAILURE
            }
          };
        }
        const { originalContent, correctedContent: fileContent, fileExists: fileExists2 } = correctedContentResult;
        const isNewFile = !fileExists2 || correctedContentResult.error !== void 0 && !correctedContentResult.fileExists;
        try {
          const dirName = path45.dirname(file_path);
          if (!fs41.existsSync(dirName)) {
            fs41.mkdirSync(dirName, { recursive: true });
          }
          await this.config.getFileSystemService().writeTextFile(file_path, fileContent);
          const fileName = path45.basename(file_path);
          const currentContentForDiff = correctedContentResult.error ? "" : originalContent;
          const fileDiff = createPatch(fileName, currentContentForDiff, fileContent, "Original", "Written", DEFAULT_DIFF_OPTIONS);
          const originallyProposedContent = ai_proposed_content || content;
          const diffStat = getDiffStat(fileName, currentContentForDiff, originallyProposedContent, content);
          const llmSuccessMessageParts = [
            isNewFile ? `Successfully created and wrote to new file: ${file_path}.` : `Successfully overwrote file: ${file_path}.`
          ];
          if (modified_by_user) {
            llmSuccessMessageParts.push(`User modified the \`content\` to be: ${content}`);
          }
          const mimetype = getSpecificMimeType(file_path);
          const programmingLanguage = getLanguageFromFilePath(file_path);
          const extension = path45.extname(file_path);
          const operation = isNewFile ? FileOperation.CREATE : FileOperation.UPDATE;
          logFileOperation(this.config, new FileOperationEvent(WriteFileTool.Name, operation, fileContent.split("\n").length, mimetype, extension, programmingLanguage));
          const displayResult = {
            fileDiff,
            fileName,
            originalContent: correctedContentResult.originalContent,
            newContent: correctedContentResult.correctedContent,
            diffStat
          };
          return {
            llmContent: llmSuccessMessageParts.join(" "),
            returnDisplay: displayResult
          };
        } catch (error) {
          let errorMsg;
          let errorType = ToolErrorType.FILE_WRITE_FAILURE;
          if (isNodeError(error)) {
            errorMsg = `Error writing to file '${file_path}': ${error.message} (${error.code})`;
            if (error.code === "EACCES") {
              errorMsg = `Permission denied writing to file: ${file_path} (${error.code})`;
              errorType = ToolErrorType.PERMISSION_DENIED;
            } else if (error.code === "ENOSPC") {
              errorMsg = `No space left on device: ${file_path} (${error.code})`;
              errorType = ToolErrorType.NO_SPACE_LEFT;
            } else if (error.code === "EISDIR") {
              errorMsg = `Target is a directory, not a file: ${file_path} (${error.code})`;
              errorType = ToolErrorType.TARGET_IS_DIRECTORY;
            }
            if (this.config.getDebugMode() && error.stack) {
              console.error("Write file error stack:", error.stack);
            }
          } else if (error instanceof Error) {
            errorMsg = `Error writing to file: ${error.message}`;
          } else {
            errorMsg = `Error writing to file: ${String(error)}`;
          }
          return {
            llmContent: errorMsg,
            returnDisplay: errorMsg,
            error: {
              message: errorMsg,
              type: errorType
            }
          };
        }
      }
    };
    WriteFileTool = class _WriteFileTool extends BaseDeclarativeTool {
      static {
        __name(this, "WriteFileTool");
      }
      config;
      static Name = ToolNames.WRITE_FILE;
      constructor(config) {
        super(_WriteFileTool.Name, ToolDisplayNames.WRITE_FILE, `Writes content to a specified file in the local filesystem.

      The user has the ability to modify \`content\`. If modified, this will be stated in the response.`, Kind.Edit, {
          properties: {
            file_path: {
              description: "The absolute path to the file to write to (e.g., '/home/user/project/file.txt'). Relative paths are not supported.",
              type: "string"
            },
            content: {
              description: "The content to write to the file.",
              type: "string"
            }
          },
          required: ["file_path", "content"],
          type: "object"
        });
        this.config = config;
      }
      validateToolParamValues(params) {
        const filePath = params.file_path;
        if (!filePath) {
          return `Missing or empty "file_path"`;
        }
        if (!path45.isAbsolute(filePath)) {
          return `File path must be absolute: ${filePath}`;
        }
        const workspaceContext = this.config.getWorkspaceContext();
        if (!workspaceContext.isPathWithinWorkspace(filePath)) {
          const directories = workspaceContext.getDirectories();
          return `File path must be within one of the workspace directories: ${directories.join(", ")}`;
        }
        try {
          if (fs41.existsSync(filePath)) {
            const stats = fs41.lstatSync(filePath);
            if (stats.isDirectory()) {
              return `Path is a directory, not a file: ${filePath}`;
            }
          }
        } catch (statError) {
          return `Error accessing path properties for validation: ${filePath}. Reason: ${statError instanceof Error ? statError.message : String(statError)}`;
        }
        return null;
      }
      createInvocation(params) {
        return new WriteFileToolInvocation(this.config, params);
      }
      getModifyContext(_abortSignal) {
        return {
          getFilePath: /* @__PURE__ */ __name((params) => params.file_path, "getFilePath"),
          getCurrentContent: /* @__PURE__ */ __name(async (params) => {
            const correctedContentResult = await getCorrectedFileContent(this.config, params.file_path, params.content);
            return correctedContentResult.originalContent;
          }, "getCurrentContent"),
          getProposedContent: /* @__PURE__ */ __name(async (params) => {
            const correctedContentResult = await getCorrectedFileContent(this.config, params.file_path, params.content);
            return correctedContentResult.correctedContent;
          }, "getProposedContent"),
          createUpdatedParams: /* @__PURE__ */ __name((_oldContent, modifiedProposedContent, originalParams) => {
            const content = originalParams.content;
            return {
              ...originalParams,
              ai_proposed_content: content,
              content: modifiedProposedContent,
              modified_by_user: true
            };
          }, "createUpdatedParams")
        };
      }
    };
  }
});

// packages/core/dist/src/output/types.js
var OutputFormat;
var init_types10 = __esm({
  "packages/core/dist/src/output/types.js"() {
    "use strict";
    init_esbuild_shims();
    (function(OutputFormat2) {
      OutputFormat2["TEXT"] = "text";
      OutputFormat2["JSON"] = "json";
    })(OutputFormat || (OutputFormat = {}));
  }
});

// packages/core/dist/src/prompts/prompt-registry.js
var PromptRegistry;
var init_prompt_registry = __esm({
  "packages/core/dist/src/prompts/prompt-registry.js"() {
    "use strict";
    init_esbuild_shims();
    PromptRegistry = class {
      static {
        __name(this, "PromptRegistry");
      }
      prompts = /* @__PURE__ */ new Map();
      /**
       * Registers a prompt definition.
       * @param prompt - The prompt object containing schema and execution logic.
       */
      registerPrompt(prompt) {
        if (this.prompts.has(prompt.name)) {
          const newName = `${prompt.serverName}_${prompt.name}`;
          console.warn(`Prompt with name "${prompt.name}" is already registered. Renaming to "${newName}".`);
          this.prompts.set(newName, { ...prompt, name: newName });
        } else {
          this.prompts.set(prompt.name, prompt);
        }
      }
      /**
       * Returns an array of all registered and discovered prompt instances.
       */
      getAllPrompts() {
        return Array.from(this.prompts.values()).sort((a, b) => a.name.localeCompare(b.name));
      }
      /**
       * Get the definition of a specific prompt.
       */
      getPrompt(name3) {
        return this.prompts.get(name3);
      }
      /**
       * Returns an array of prompts registered from a specific MCP server.
       */
      getPromptsByServer(serverName) {
        const serverPrompts = [];
        for (const prompt of this.prompts.values()) {
          if (prompt.serverName === serverName) {
            serverPrompts.push(prompt);
          }
        }
        return serverPrompts.sort((a, b) => a.name.localeCompare(b.name));
      }
      /**
       * Clears all the prompts from the registry.
       */
      clear() {
        this.prompts.clear();
      }
      /**
       * Removes all prompts from a specific server.
       */
      removePromptsByServer(serverName) {
        for (const [name3, prompt] of this.prompts.entries()) {
          if (prompt.serverName === serverName) {
            this.prompts.delete(name3);
          }
        }
      }
    };
  }
});

// packages/core/dist/src/utils/yaml-parser.js
function parse5(yamlString) {
  const lines = yamlString.split("\n").filter((line) => line.trim() && !line.trim().startsWith("#"));
  const result = {};
  let currentKey = "";
  let currentArray = [];
  let inArray = false;
  let currentObject = {};
  let inObject = false;
  let objectKey = "";
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    if (line.startsWith("  - ")) {
      if (!inArray) {
        inArray = true;
        currentArray = [];
      }
      const itemRaw = line.substring(4).trim();
      currentArray.push(parseValue(itemRaw));
      continue;
    }
    if (inArray && !line.startsWith("  - ")) {
      result[currentKey] = currentArray;
      inArray = false;
      currentArray = [];
      currentKey = "";
    }
    if (line.startsWith("  ") && inObject) {
      const [key, ...valueParts] = line.trim().split(":");
      const value = valueParts.join(":").trim();
      currentObject[key.trim()] = parseValue(value);
      continue;
    }
    if (inObject && !line.startsWith("  ")) {
      result[objectKey] = currentObject;
      inObject = false;
      currentObject = {};
      objectKey = "";
    }
    if (line.includes(":")) {
      const [key, ...valueParts] = line.split(":");
      const value = valueParts.join(":").trim();
      if (value === "") {
        currentKey = key.trim();
        if (i + 1 < lines.length) {
          const nextLine = lines[i + 1];
          if (nextLine.startsWith("  - ")) {
            continue;
          } else if (nextLine.startsWith("  ")) {
            inObject = true;
            objectKey = currentKey;
            currentObject = {};
            currentKey = "";
            continue;
          }
        }
      } else {
        result[key.trim()] = parseValue(value);
      }
    }
  }
  if (inArray) {
    result[currentKey] = currentArray;
  }
  if (inObject) {
    result[objectKey] = currentObject;
  }
  return result;
}
function stringify3(obj, _options) {
  const lines = [];
  for (const [key, value] of Object.entries(obj)) {
    if (Array.isArray(value)) {
      lines.push(`${key}:`);
      for (const item of value) {
        lines.push(`  - ${formatValue(item)}`);
      }
    } else if (typeof value === "object" && value !== null) {
      lines.push(`${key}:`);
      for (const [subKey, subValue] of Object.entries(value)) {
        lines.push(`  ${subKey}: ${formatValue(subValue)}`);
      }
    } else {
      lines.push(`${key}: ${formatValue(value)}`);
    }
  }
  return lines.join("\n");
}
function parseValue(value) {
  if (value === "true")
    return true;
  if (value === "false")
    return false;
  if (value === "null")
    return null;
  if (value === "")
    return "";
  if (value.startsWith('"') && value.endsWith('"') && value.length >= 2) {
    const unquoted = value.slice(1, -1);
    return unquoted.replace(/\\"/g, '"').replace(/\\\\/g, "\\");
  }
  const num = Number(value);
  if (!isNaN(num) && isFinite(num)) {
    return num;
  }
  return value;
}
function formatValue(value) {
  if (typeof value === "string") {
    if (value.includes(":") || value.includes("#") || value.includes('"') || value.includes("\\") || value.trim() !== value) {
      return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
    }
    return value;
  }
  return String(value);
}
var init_yaml_parser = __esm({
  "packages/core/dist/src/utils/yaml-parser.js"() {
    "use strict";
    init_esbuild_shims();
    __name(parse5, "parse");
    __name(stringify3, "stringify");
    __name(parseValue, "parseValue");
    __name(formatValue, "formatValue");
  }
});

// packages/core/dist/src/subagents/validation.js
var SubagentValidator;
var init_validation = __esm({
  "packages/core/dist/src/subagents/validation.js"() {
    "use strict";
    init_esbuild_shims();
    init_types6();
    SubagentValidator = class {
      static {
        __name(this, "SubagentValidator");
      }
      /**
       * Validates a complete subagent configuration.
       *
       * @param config - The subagent configuration to validate
       * @returns ValidationResult with errors and warnings
       */
      validateConfig(config) {
        const errors = [];
        const warnings = [];
        const nameValidation = this.validateName(config.name);
        if (!nameValidation.isValid) {
          errors.push(...nameValidation.errors);
        }
        if (!config.description || config.description.trim().length === 0) {
          errors.push("Description is required and cannot be empty");
        } else if (config.description.length > 500) {
          warnings.push("Description is quite long (>500 chars), consider shortening for better readability");
        }
        const promptValidation = this.validateSystemPrompt(config.systemPrompt);
        if (!promptValidation.isValid) {
          errors.push(...promptValidation.errors);
        }
        warnings.push(...promptValidation.warnings);
        if (config.tools) {
          const toolsValidation = this.validateTools(config.tools);
          if (!toolsValidation.isValid) {
            errors.push(...toolsValidation.errors);
          }
          warnings.push(...toolsValidation.warnings);
        }
        if (config.modelConfig) {
          const modelValidation = this.validateModelConfig(config.modelConfig);
          if (!modelValidation.isValid) {
            errors.push(...modelValidation.errors);
          }
          warnings.push(...modelValidation.warnings);
        }
        if (config.runConfig) {
          const runValidation = this.validateRunConfig(config.runConfig);
          if (!runValidation.isValid) {
            errors.push(...runValidation.errors);
          }
          warnings.push(...runValidation.warnings);
        }
        return {
          isValid: errors.length === 0,
          errors,
          warnings
        };
      }
      /**
       * Validates a subagent name.
       * Names must be valid identifiers that can be used in file paths and tool calls.
       *
       * @param name - The name to validate
       * @returns ValidationResult
       */
      validateName(name3) {
        const errors = [];
        const warnings = [];
        if (!name3 || name3.trim().length === 0) {
          errors.push("Name is required and cannot be empty");
          return { isValid: false, errors, warnings };
        }
        const trimmedName = name3.trim();
        if (trimmedName.length < 2) {
          errors.push("Name must be at least 2 characters long");
        }
        if (trimmedName.length > 50) {
          errors.push("Name must be 50 characters or less");
        }
        const validNameRegex = /^[a-zA-Z0-9_-]+$/;
        if (!validNameRegex.test(trimmedName)) {
          errors.push("Name can only contain letters, numbers, hyphens, and underscores");
        }
        if (trimmedName.startsWith("-") || trimmedName.startsWith("_")) {
          errors.push("Name cannot start with a hyphen or underscore");
        }
        if (trimmedName.endsWith("-") || trimmedName.endsWith("_")) {
          errors.push("Name cannot end with a hyphen or underscore");
        }
        const reservedNames = [
          "self",
          "system",
          "user",
          "model",
          "tool",
          "config",
          "default"
        ];
        if (reservedNames.includes(trimmedName.toLowerCase())) {
          errors.push(`"${trimmedName}" is a reserved name and cannot be used`);
        }
        if (trimmedName !== trimmedName.toLowerCase()) {
          warnings.push("Consider using lowercase names for consistency");
        }
        if (trimmedName.includes("_") && trimmedName.includes("-")) {
          warnings.push("Consider using either hyphens or underscores consistently, not both");
        }
        return {
          isValid: errors.length === 0,
          errors,
          warnings
        };
      }
      /**
       * Validates a system prompt.
       *
       * @param prompt - The system prompt to validate
       * @returns ValidationResult
       */
      validateSystemPrompt(prompt) {
        const errors = [];
        const warnings = [];
        if (!prompt || prompt.trim().length === 0) {
          errors.push("System prompt is required and cannot be empty");
          return { isValid: false, errors, warnings };
        }
        const trimmedPrompt = prompt.trim();
        if (trimmedPrompt.length < 10) {
          errors.push("System prompt must be at least 10 characters long");
        }
        if (trimmedPrompt.length > 1e4) {
          errors.push("System prompt is too long (>10,000 characters)");
        } else if (trimmedPrompt.length > 5e3) {
          warnings.push("System prompt is quite long (>5,000 characters), consider shortening");
        }
        return {
          isValid: errors.length === 0,
          errors,
          warnings
        };
      }
      /**
       * Validates a list of tool names.
       *
       * @param tools - Array of tool names to validate
       * @returns ValidationResult
       */
      validateTools(tools) {
        const errors = [];
        const warnings = [];
        if (!Array.isArray(tools)) {
          errors.push("Tools must be an array of strings");
          return { isValid: false, errors, warnings };
        }
        if (tools.length === 0) {
          warnings.push("Empty tools array - subagent will inherit all available tools");
          return { isValid: true, errors, warnings };
        }
        const uniqueTools = new Set(tools);
        if (uniqueTools.size !== tools.length) {
          warnings.push("Duplicate tool names found in tools array");
        }
        for (const tool of tools) {
          if (typeof tool !== "string") {
            errors.push(`Tool name must be a string, got: ${typeof tool}`);
            continue;
          }
          if (tool.trim().length === 0) {
            errors.push("Tool name cannot be empty");
            continue;
          }
        }
        return {
          isValid: errors.length === 0,
          errors,
          warnings
        };
      }
      /**
       * Validates model configuration.
       *
       * @param modelConfig - Partial model configuration to validate
       * @returns ValidationResult
       */
      validateModelConfig(modelConfig) {
        const errors = [];
        const warnings = [];
        if (modelConfig.model !== void 0) {
          if (typeof modelConfig.model !== "string" || modelConfig.model.trim().length === 0) {
            errors.push("Model name must be a non-empty string");
          }
        }
        if (modelConfig.temp !== void 0) {
          if (typeof modelConfig.temp !== "number") {
            errors.push("Temperature must be a number");
          } else if (modelConfig.temp < 0 || modelConfig.temp > 2) {
            errors.push("Temperature must be between 0 and 2");
          } else if (modelConfig.temp > 1) {
            warnings.push("High temperature (>1) may produce very creative but unpredictable results");
          }
        }
        if (modelConfig.top_p !== void 0) {
          if (typeof modelConfig.top_p !== "number") {
            errors.push("top_p must be a number");
          } else if (modelConfig.top_p < 0 || modelConfig.top_p > 1) {
            errors.push("top_p must be between 0 and 1");
          }
        }
        return {
          isValid: errors.length === 0,
          errors,
          warnings
        };
      }
      /**
       * Validates runtime configuration.
       *
       * @param runConfig - Partial run configuration to validate
       * @returns ValidationResult
       */
      validateRunConfig(runConfig) {
        const errors = [];
        const warnings = [];
        if (runConfig.max_time_minutes !== void 0) {
          if (typeof runConfig.max_time_minutes !== "number") {
            errors.push("max_time_minutes must be a number");
          } else if (runConfig.max_time_minutes <= 0) {
            errors.push("max_time_minutes must be greater than 0");
          } else if (runConfig.max_time_minutes > 60) {
            warnings.push("Very long execution time (>60 minutes) may cause resource issues");
          }
        }
        if (runConfig.max_turns !== void 0) {
          if (typeof runConfig.max_turns !== "number") {
            errors.push("max_turns must be a number");
          } else if (runConfig.max_turns <= 0) {
            errors.push("max_turns must be greater than 0");
          } else if (!Number.isInteger(runConfig.max_turns)) {
            errors.push("max_turns must be an integer");
          } else if (runConfig.max_turns > 100) {
            warnings.push("Very high turn limit (>100) may cause long execution times");
          }
        }
        return {
          isValid: errors.length === 0,
          errors,
          warnings
        };
      }
      /**
       * Throws a SubagentError if validation fails.
       *
       * @param config - Configuration to validate
       * @param subagentName - Name for error context
       * @throws SubagentError if validation fails
       */
      validateOrThrow(config, subagentName) {
        const result = this.validateConfig(config);
        if (!result.isValid) {
          throw new SubagentError(`Validation failed: ${result.errors.join(", ")}`, SubagentErrorCode.VALIDATION_ERROR, subagentName || config.name);
        }
      }
    };
  }
});

// packages/core/dist/src/subagents/builtin-agents.js
var BuiltinAgentRegistry;
var init_builtin_agents = __esm({
  "packages/core/dist/src/subagents/builtin-agents.js"() {
    "use strict";
    init_esbuild_shims();
    BuiltinAgentRegistry = class {
      static {
        __name(this, "BuiltinAgentRegistry");
      }
      static BUILTIN_AGENTS = [
        {
          name: "general-purpose",
          description: "General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.",
          systemPrompt: `You are a general-purpose research and code analysis agent. Given the user's message, you should use the tools available to complete the task. Do what has been asked; nothing more, nothing less. When you complete the task simply respond with a detailed writeup.

Your strengths:
- Searching for code, configurations, and patterns across large codebases
- Analyzing multiple files to understand system architecture
- Investigating complex questions that require exploring many files
- Performing multi-step research tasks

Guidelines:
- For file searches: Use Grep or Glob when you need to search broadly. Use Read when you know the specific file path.
- For analysis: Start broad and narrow down. Use multiple search strategies if the first doesn't yield results.
- Be thorough: Check multiple locations, consider different naming conventions, look for related files.
- NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one.
- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested.
- In your final response always share relevant file names and code snippets. Any file paths you return in your response MUST be absolute. Do NOT use relative paths.
- For clear communication, avoid using emojis.


Notes:
- NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one.
- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.
- In your final response always share relevant file names and code snippets. Any file paths you return in your response MUST be absolute. Do NOT use relative paths.
- For clear communication with the user the assistant MUST avoid using emojis.`
        }
      ];
      /**
       * Gets all built-in agent configurations.
       * @returns Array of built-in subagent configurations
       */
      static getBuiltinAgents() {
        return this.BUILTIN_AGENTS.map((agent) => ({
          ...agent,
          level: "builtin",
          filePath: `<builtin:${agent.name}>`,
          isBuiltin: true
        }));
      }
      /**
       * Gets a specific built-in agent by name.
       * @param name - Name of the built-in agent
       * @returns Built-in agent configuration or null if not found
       */
      static getBuiltinAgent(name3) {
        const agent = this.BUILTIN_AGENTS.find((a) => a.name === name3);
        if (!agent) {
          return null;
        }
        return {
          ...agent,
          level: "builtin",
          filePath: `<builtin:${name3}>`,
          isBuiltin: true
        };
      }
      /**
       * Checks if an agent name corresponds to a built-in agent.
       * @param name - Agent name to check
       * @returns True if the name is a built-in agent
       */
      static isBuiltinAgent(name3) {
        return this.BUILTIN_AGENTS.some((agent) => agent.name === name3);
      }
      /**
       * Gets the names of all built-in agents.
       * @returns Array of built-in agent names
       */
      static getBuiltinAgentNames() {
        return this.BUILTIN_AGENTS.map((agent) => agent.name);
      }
    };
  }
});

// packages/core/dist/src/subagents/subagent-manager.js
import * as fs42 from "fs/promises";
import * as path46 from "path";
import * as os21 from "os";
var QWEN_CONFIG_DIR2, AGENT_CONFIG_DIR, SubagentManager;
var init_subagent_manager = __esm({
  "packages/core/dist/src/subagents/subagent-manager.js"() {
    "use strict";
    init_esbuild_shims();
    init_yaml_parser();
    init_types6();
    init_validation();
    init_subagent();
    init_builtin_agents();
    init_tool_names();
    QWEN_CONFIG_DIR2 = ".qwen";
    AGENT_CONFIG_DIR = "agents";
    SubagentManager = class {
      static {
        __name(this, "SubagentManager");
      }
      config;
      validator;
      subagentsCache = null;
      changeListeners = /* @__PURE__ */ new Set();
      constructor(config) {
        this.config = config;
        this.validator = new SubagentValidator();
      }
      addChangeListener(listener) {
        this.changeListeners.add(listener);
        return () => {
          this.changeListeners.delete(listener);
        };
      }
      notifyChangeListeners() {
        for (const listener of this.changeListeners) {
          try {
            listener();
          } catch (error) {
            console.warn("Subagent change listener threw an error:", error);
          }
        }
      }
      /**
       * Creates a new subagent configuration.
       *
       * @param config - Subagent configuration to create
       * @param options - Creation options
       * @throws SubagentError if creation fails
       */
      async createSubagent(config, options2) {
        this.validator.validateOrThrow(config);
        const filePath = options2.customPath || this.getSubagentPath(config.name, options2.level);
        if (!options2.overwrite) {
          try {
            await fs42.access(filePath);
            throw new SubagentError(`Subagent "${config.name}" already exists at ${filePath}`, SubagentErrorCode.ALREADY_EXISTS, config.name);
          } catch (error) {
            if (error instanceof SubagentError)
              throw error;
          }
        }
        const dir = path46.dirname(filePath);
        await fs42.mkdir(dir, { recursive: true });
        const finalConfig = {
          ...config,
          level: options2.level,
          filePath
        };
        const content = this.serializeSubagent(finalConfig);
        try {
          await fs42.writeFile(filePath, content, "utf8");
          await this.refreshCache();
        } catch (error) {
          throw new SubagentError(`Failed to write subagent file: ${error instanceof Error ? error.message : "Unknown error"}`, SubagentErrorCode.FILE_ERROR, config.name);
        }
      }
      /**
       * Loads a subagent configuration by name.
       * If level is specified, only searches that level.
       * If level is omitted, searches project-level first, then user-level, then built-in.
       *
       * @param name - Name of the subagent to load
       * @param level - Optional level to limit search to specific level
       * @returns SubagentConfig or null if not found
       */
      async loadSubagent(name3, level) {
        if (level) {
          if (level === "builtin") {
            return BuiltinAgentRegistry.getBuiltinAgent(name3);
          }
          return this.findSubagentByNameAtLevel(name3, level);
        }
        const projectConfig = await this.findSubagentByNameAtLevel(name3, "project");
        if (projectConfig) {
          return projectConfig;
        }
        const userConfig = await this.findSubagentByNameAtLevel(name3, "user");
        if (userConfig) {
          return userConfig;
        }
        return BuiltinAgentRegistry.getBuiltinAgent(name3);
      }
      /**
       * Updates an existing subagent configuration.
       *
       * @param name - Name of the subagent to update
       * @param updates - Partial configuration updates
       * @throws SubagentError if subagent not found or update fails
       */
      async updateSubagent(name3, updates, level) {
        const existing = await this.loadSubagent(name3, level);
        if (!existing) {
          throw new SubagentError(`Subagent "${name3}" not found`, SubagentErrorCode.NOT_FOUND, name3);
        }
        if (existing.isBuiltin) {
          throw new SubagentError(`Cannot update built-in subagent "${name3}"`, SubagentErrorCode.INVALID_CONFIG, name3);
        }
        const updatedConfig = this.mergeConfigurations(existing, updates);
        this.validator.validateOrThrow(updatedConfig);
        const content = this.serializeSubagent(updatedConfig);
        try {
          await fs42.writeFile(existing.filePath, content, "utf8");
          await this.refreshCache();
        } catch (error) {
          throw new SubagentError(`Failed to update subagent file: ${error instanceof Error ? error.message : "Unknown error"}`, SubagentErrorCode.FILE_ERROR, name3);
        }
      }
      /**
       * Deletes a subagent configuration.
       *
       * @param name - Name of the subagent to delete
       * @param level - Specific level to delete from, or undefined to delete from both
       * @throws SubagentError if deletion fails
       */
      async deleteSubagent(name3, level) {
        if (BuiltinAgentRegistry.isBuiltinAgent(name3)) {
          throw new SubagentError(`Cannot delete built-in subagent "${name3}"`, SubagentErrorCode.INVALID_CONFIG, name3);
        }
        const levelsToCheck = level ? [level] : ["project", "user"];
        let deleted = false;
        for (const currentLevel of levelsToCheck) {
          if (currentLevel === "builtin") {
            continue;
          }
          const config = await this.findSubagentByNameAtLevel(name3, currentLevel);
          if (config && config.filePath) {
            try {
              await fs42.unlink(config.filePath);
              deleted = true;
            } catch (_error) {
            }
          }
        }
        if (!deleted) {
          throw new SubagentError(`Subagent "${name3}" not found`, SubagentErrorCode.NOT_FOUND, name3);
        }
        await this.refreshCache();
      }
      /**
       * Lists all available subagents.
       *
       * @param options - Filtering and sorting options
       * @returns Array of subagent metadata
       */
      async listSubagents(options2 = {}) {
        const subagents = [];
        const seenNames = /* @__PURE__ */ new Set();
        const levelsToCheck = options2.level ? [options2.level] : ["project", "user", "builtin"];
        const shouldUseCache = !options2.force && this.subagentsCache !== null;
        if (!shouldUseCache) {
          await this.refreshCache();
        }
        for (const level of levelsToCheck) {
          const levelSubagents = this.subagentsCache?.get(level) || [];
          for (const subagent of levelSubagents) {
            if (seenNames.has(subagent.name)) {
              continue;
            }
            if (options2.hasTool && (!subagent.tools || !subagent.tools.includes(options2.hasTool))) {
              continue;
            }
            subagents.push(subagent);
            seenNames.add(subagent.name);
          }
        }
        if (options2.sortBy) {
          subagents.sort((a, b) => {
            let comparison = 0;
            switch (options2.sortBy) {
              case "name":
                comparison = a.name.localeCompare(b.name);
                break;
              case "level": {
                const levelOrder = { project: 0, user: 1, builtin: 2 };
                comparison = levelOrder[a.level] - levelOrder[b.level];
                break;
              }
              default:
                comparison = 0;
                break;
            }
            return options2.sortOrder === "desc" ? -comparison : comparison;
          });
        }
        return subagents;
      }
      /**
       * Refreshes the subagents cache by loading all subagents from disk.
       * This method is called automatically when cache is null or when force=true.
       *
       * @private
       */
      async refreshCache() {
        const subagentsCache = /* @__PURE__ */ new Map();
        const levels = ["project", "user", "builtin"];
        for (const level of levels) {
          const levelSubagents = await this.listSubagentsAtLevel(level);
          subagentsCache.set(level, levelSubagents);
        }
        this.subagentsCache = subagentsCache;
        this.notifyChangeListeners();
      }
      /**
       * Finds a subagent by name and returns its metadata.
       *
       * @param name - Name of the subagent to find
       * @returns SubagentConfig or null if not found
       */
      async findSubagentByName(name3, level) {
        const config = await this.loadSubagent(name3, level);
        if (!config) {
          return null;
        }
        return config;
      }
      /**
       * Parses a subagent file and returns the configuration.
       *
       * @param filePath - Path to the subagent file
       * @returns SubagentConfig
       * @throws SubagentError if parsing fails
       */
      async parseSubagentFile(filePath, level) {
        let content;
        try {
          content = await fs42.readFile(filePath, "utf8");
        } catch (error) {
          throw new SubagentError(`Failed to read subagent file: ${error instanceof Error ? error.message : "Unknown error"}`, SubagentErrorCode.FILE_ERROR);
        }
        return this.parseSubagentContent(content, filePath, level);
      }
      /**
       * Parses subagent content from a string.
       *
       * @param content - File content
       * @param filePath - File path for error reporting
       * @returns SubagentConfig
       * @throws SubagentError if parsing fails
       */
      parseSubagentContent(content, filePath, level) {
        try {
          const frontmatterRegex = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/;
          const match2 = content.match(frontmatterRegex);
          if (!match2) {
            throw new Error("Invalid format: missing YAML frontmatter");
          }
          const [, frontmatterYaml, systemPrompt] = match2;
          const frontmatter = parse5(frontmatterYaml);
          const nameRaw = frontmatter["name"];
          const descriptionRaw = frontmatter["description"];
          if (nameRaw == null || nameRaw === "") {
            throw new Error('Missing "name" in frontmatter');
          }
          if (descriptionRaw == null || descriptionRaw === "") {
            throw new Error('Missing "description" in frontmatter');
          }
          const name3 = String(nameRaw);
          const description = String(descriptionRaw);
          const tools = frontmatter["tools"];
          const modelConfig = frontmatter["modelConfig"];
          const runConfig = frontmatter["runConfig"];
          const color = frontmatter["color"];
          const config = {
            name: name3,
            description,
            tools,
            systemPrompt: systemPrompt.trim(),
            filePath,
            modelConfig,
            runConfig,
            color,
            level
          };
          const validation2 = this.validator.validateConfig(config);
          if (!validation2.isValid) {
            throw new Error(`Validation failed: ${validation2.errors.join(", ")}`);
          }
          return config;
        } catch (error) {
          throw new SubagentError(`Failed to parse subagent file: ${error instanceof Error ? error.message : "Unknown error"}`, SubagentErrorCode.INVALID_CONFIG);
        }
      }
      /**
       * Serializes a subagent configuration to Markdown format.
       *
       * @param config - Configuration to serialize
       * @returns Markdown content with YAML frontmatter
       */
      serializeSubagent(config) {
        const frontmatter = {
          name: config.name,
          description: config.description
        };
        if (config.tools && config.tools.length > 0) {
          frontmatter["tools"] = config.tools;
        }
        if (config.modelConfig) {
          frontmatter["modelConfig"] = config.modelConfig;
        }
        if (config.runConfig) {
          frontmatter["runConfig"] = config.runConfig;
        }
        if (config.color && config.color !== "auto") {
          frontmatter["color"] = config.color;
        }
        const yamlContent = stringify3(frontmatter, {
          lineWidth: 0,
          // Disable line wrapping
          minContentWidth: 0
        }).trim();
        return `---
${yamlContent}
---

${config.systemPrompt}
`;
      }
      /**
       * Creates a SubAgentScope from a subagent configuration.
       *
       * @param config - Subagent configuration
       * @param runtimeContext - Runtime context
       * @returns Promise resolving to SubAgentScope
       */
      async createSubagentScope(config, runtimeContext, options2) {
        try {
          const runtimeConfig = this.convertToRuntimeConfig(config);
          return await SubAgentScope.create(config.name, runtimeContext, runtimeConfig.promptConfig, runtimeConfig.modelConfig, runtimeConfig.runConfig, runtimeConfig.toolConfig, options2?.eventEmitter, options2?.hooks);
        } catch (error) {
          if (error instanceof Error) {
            throw new SubagentError(`Failed to create SubAgentScope: ${error.message}`, SubagentErrorCode.INVALID_CONFIG, config.name);
          }
          throw error;
        }
      }
      /**
       * Converts a file-based SubagentConfig to runtime configuration
       * compatible with SubAgentScope.create().
       *
       * @param config - File-based subagent configuration
       * @returns Runtime configuration for SubAgentScope
       */
      convertToRuntimeConfig(config) {
        const promptConfig = {
          systemPrompt: config.systemPrompt
        };
        const modelConfig = {
          ...config.modelConfig
        };
        const runConfig = {
          ...config.runConfig
        };
        let toolConfig;
        if (config.tools && config.tools.length > 0) {
          const toolNames = this.transformToToolNames(config.tools);
          toolConfig = {
            tools: toolNames
          };
        }
        return {
          promptConfig,
          modelConfig,
          runConfig,
          toolConfig
        };
      }
      /**
       * Transforms a tools array that may contain tool names or display names
       * into an array containing only tool names.
       *
       * @param tools - Array of tool names or display names
       * @returns Array of tool names
       * @private
       */
      transformToToolNames(tools) {
        const toolRegistry = this.config.getToolRegistry();
        if (!toolRegistry) {
          return tools;
        }
        const allTools = toolRegistry.getAllTools();
        const result = [];
        for (const toolIdentifier of tools) {
          const exactNameMatch = allTools.find((tool) => tool.name === toolIdentifier);
          if (exactNameMatch) {
            result.push(exactNameMatch.name);
            continue;
          }
          const displayNameMatch = allTools.find((tool) => tool.displayName === toolIdentifier || tool.displayName === ToolDisplayNamesMigration[toolIdentifier]);
          if (displayNameMatch) {
            result.push(displayNameMatch.name);
            continue;
          }
          result.push(toolIdentifier);
          console.warn(`Tool "${toolIdentifier}" not found in tool registry, preserving as-is`);
        }
        return result;
      }
      /**
       * Merges partial configurations with defaults, useful for updating
       * existing configurations.
       *
       * @param base - Base configuration
       * @param updates - Partial updates to apply
       * @returns New configuration with updates applied
       */
      mergeConfigurations(base, updates) {
        return {
          ...base,
          ...updates,
          // Handle nested objects specially
          modelConfig: updates.modelConfig ? { ...base.modelConfig, ...updates.modelConfig } : base.modelConfig,
          runConfig: updates.runConfig ? { ...base.runConfig, ...updates.runConfig } : base.runConfig
        };
      }
      /**
       * Gets the file path for a subagent at a specific level.
       *
       * @param name - Subagent name
       * @param level - Storage level
       * @returns Absolute file path
       */
      getSubagentPath(name3, level) {
        if (level === "builtin") {
          return `<builtin:${name3}>`;
        }
        const baseDir = level === "project" ? path46.join(this.config.getProjectRoot(), QWEN_CONFIG_DIR2, AGENT_CONFIG_DIR) : path46.join(os21.homedir(), QWEN_CONFIG_DIR2, AGENT_CONFIG_DIR);
        return path46.join(baseDir, `${name3}.md`);
      }
      /**
       * Lists subagent files at a specific level.
       * Handles both builtin agents and file-based agents.
       *
       * @param level - Storage level to scan
       * @returns Array of subagent configurations
       */
      async listSubagentsAtLevel(level) {
        if (level === "builtin") {
          return BuiltinAgentRegistry.getBuiltinAgents();
        }
        const projectRoot = this.config.getProjectRoot();
        const homeDir = os21.homedir();
        const isHomeDirectory = path46.resolve(projectRoot) === path46.resolve(homeDir);
        if (level === "project" && isHomeDirectory) {
          return [];
        }
        let baseDir = level === "project" ? projectRoot : homeDir;
        baseDir = path46.join(baseDir, QWEN_CONFIG_DIR2, AGENT_CONFIG_DIR);
        try {
          const files = await fs42.readdir(baseDir);
          const subagents = [];
          for (const file of files) {
            if (!file.endsWith(".md"))
              continue;
            const filePath = path46.join(baseDir, file);
            try {
              const config = await this.parseSubagentFile(filePath, level);
              subagents.push(config);
            } catch (_error) {
              continue;
            }
          }
          return subagents;
        } catch (_error) {
          return [];
        }
      }
      /**
       * Finds a subagent by name at a specific level by scanning all files.
       * This method ensures we find subagents even if the filename doesn't match the name.
       *
       * @param name - Name of the subagent to find
       * @param level - Storage level to search
       * @returns SubagentConfig or null if not found
       */
      async findSubagentByNameAtLevel(name3, level) {
        const allSubagents = await this.listSubagentsAtLevel(level);
        for (const subagent of allSubagents) {
          if (subagent.name === name3) {
            return subagent;
          }
        }
        return null;
      }
      /**
       * Validates that a subagent name is available (not already in use).
       *
       * @param name - Name to check
       * @param level - Level to check, or undefined to check both
       * @returns True if name is available
       */
      async isNameAvailable(name3, level) {
        const existing = await this.loadSubagent(name3, level);
        if (!existing) {
          return true;
        }
        if (level && existing.level !== level) {
          return true;
        }
        return false;
      }
    };
  }
});

// packages/core/dist/src/utils/browser.js
function shouldAttemptBrowserLaunch() {
  const browserBlocklist = ["www-browser"];
  const browserEnv = process.env["BROWSER"];
  if (browserEnv && browserBlocklist.includes(browserEnv)) {
    return false;
  }
  if (process.env["CI"] || process.env["DEBIAN_FRONTEND"] === "noninteractive") {
    return false;
  }
  const isSSH = !!process.env["SSH_CONNECTION"];
  if (process.platform === "linux") {
    const displayVariables = ["DISPLAY", "WAYLAND_DISPLAY", "MIR_SOCKET"];
    const hasDisplay = displayVariables.some((v) => !!process.env[v]);
    if (!hasDisplay) {
      return false;
    }
  }
  if (isSSH && process.platform !== "linux") {
    return false;
  }
  return true;
}
var init_browser = __esm({
  "packages/core/dist/src/utils/browser.js"() {
    "use strict";
    init_esbuild_shims();
    __name(shouldAttemptBrowserLaunch, "shouldAttemptBrowserLaunch");
  }
});

// packages/core/dist/src/utils/workspaceContext.js
import * as fs43 from "node:fs";
import * as path47 from "node:path";
import * as process22 from "node:process";
var WorkspaceContext;
var init_workspaceContext = __esm({
  "packages/core/dist/src/utils/workspaceContext.js"() {
    "use strict";
    init_esbuild_shims();
    init_errors();
    WorkspaceContext = class {
      static {
        __name(this, "WorkspaceContext");
      }
      directories = /* @__PURE__ */ new Set();
      initialDirectories;
      onDirectoriesChangedListeners = /* @__PURE__ */ new Set();
      /**
       * Creates a new WorkspaceContext with the given initial directory and optional additional directories.
       * @param directory The initial working directory (usually cwd)
       * @param additionalDirectories Optional array of additional directories to include
       */
      constructor(directory, additionalDirectories = []) {
        this.addDirectory(directory);
        for (const additionalDirectory of additionalDirectories) {
          this.addDirectory(additionalDirectory);
        }
        this.initialDirectories = new Set(this.directories);
      }
      /**
       * Registers a listener that is called when the workspace directories change.
       * @param listener The listener to call.
       * @returns A function to unsubscribe the listener.
       */
      onDirectoriesChanged(listener) {
        this.onDirectoriesChangedListeners.add(listener);
        return () => {
          this.onDirectoriesChangedListeners.delete(listener);
        };
      }
      notifyDirectoriesChanged() {
        for (const listener of [...this.onDirectoriesChangedListeners]) {
          try {
            listener();
          } catch (e2) {
            console.error("Error in WorkspaceContext listener:", e2);
          }
        }
      }
      /**
       * Adds a directory to the workspace.
       * @param directory The directory path to add (can be relative or absolute)
       * @param basePath Optional base path for resolving relative paths (defaults to cwd)
       */
      addDirectory(directory, basePath = process22.cwd()) {
        try {
          const resolved = this.resolveAndValidateDir(directory, basePath);
          if (this.directories.has(resolved)) {
            return;
          }
          this.directories.add(resolved);
          this.notifyDirectoriesChanged();
        } catch (err) {
          console.warn(`[WARN] Skipping unreadable directory: ${directory} (${err instanceof Error ? err.message : String(err)})`);
        }
      }
      resolveAndValidateDir(directory, basePath = process22.cwd()) {
        const absolutePath = path47.isAbsolute(directory) ? directory : path47.resolve(basePath, directory);
        if (!fs43.existsSync(absolutePath)) {
          throw new Error(`Directory does not exist: ${absolutePath}`);
        }
        const stats = fs43.statSync(absolutePath);
        if (!stats.isDirectory()) {
          throw new Error(`Path is not a directory: ${absolutePath}`);
        }
        return fs43.realpathSync(absolutePath);
      }
      /**
       * Gets a copy of all workspace directories.
       * @returns Array of absolute directory paths
       */
      getDirectories() {
        return Array.from(this.directories);
      }
      getInitialDirectories() {
        return Array.from(this.initialDirectories);
      }
      setDirectories(directories) {
        const newDirectories = /* @__PURE__ */ new Set();
        for (const dir of directories) {
          newDirectories.add(this.resolveAndValidateDir(dir));
        }
        if (newDirectories.size !== this.directories.size || ![...newDirectories].every((d) => this.directories.has(d))) {
          this.directories = newDirectories;
          this.notifyDirectoriesChanged();
        }
      }
      /**
       * Checks if a given path is within any of the workspace directories.
       * @param pathToCheck The path to validate
       * @returns True if the path is within the workspace, false otherwise
       */
      isPathWithinWorkspace(pathToCheck) {
        try {
          const fullyResolvedPath = this.fullyResolvedPath(pathToCheck);
          for (const dir of this.directories) {
            if (this.isPathWithinRoot(fullyResolvedPath, dir)) {
              return true;
            }
          }
          return false;
        } catch (_error) {
          return false;
        }
      }
      /**
       * Fully resolves a path, including symbolic links.
       * If the path does not exist, it returns the fully resolved path as it would be
       * if it did exist.
       */
      fullyResolvedPath(pathToCheck) {
        try {
          return fs43.realpathSync(pathToCheck);
        } catch (e2) {
          if (isNodeError(e2) && e2.code === "ENOENT" && e2.path && // realpathSync does not set e.path correctly for symlinks to
          // non-existent files.
          !this.isFileSymlink(e2.path)) {
            return e2.path;
          }
          throw e2;
        }
      }
      /**
       * Checks if a path is within a given root directory.
       * @param pathToCheck The absolute path to check
       * @param rootDirectory The absolute root directory
       * @returns True if the path is within the root directory, false otherwise
       */
      isPathWithinRoot(pathToCheck, rootDirectory) {
        const relative10 = path47.relative(rootDirectory, pathToCheck);
        return !relative10.startsWith(`..${path47.sep}`) && relative10 !== ".." && !path47.isAbsolute(relative10);
      }
      /**
       * Checks if a file path is a symbolic link that points to a file.
       */
      isFileSymlink(filePath) {
        try {
          return !fs43.readlinkSync(filePath).endsWith("/");
        } catch (_error) {
          return false;
        }
      }
    };
  }
});

// packages/core/dist/src/config/config.js
import * as path48 from "node:path";
import process23 from "node:process";
var import_undici3, ApprovalMode, APPROVAL_MODES, DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD, DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES, MCPServerConfig, AuthProviderType, Config;
var init_config3 = __esm({
  "packages/core/dist/src/config/config.js"() {
    "use strict";
    init_esbuild_shims();
    import_undici3 = __toESM(require_undici(), 1);
    init_baseLlmClient();
    init_client2();
    init_contentGenerator();
    init_tokenLimits();
    init_fileDiscoveryService();
    init_fileSystemService();
    init_gitService();
    init_edit();
    init_exitPlanMode();
    init_glob2();
    init_grep2();
    init_ls();
    init_memoryTool();
    init_read_file();
    init_read_many_files();
    init_ripgrepUtils();
    init_ripGrep();
    init_shell();
    init_smart_edit();
    init_task();
    init_todoWrite();
    init_tool_registry();
    init_web_fetch();
    init_web_search();
    init_write_file();
    init_ideContext();
    init_types10();
    init_prompt_registry();
    init_subagent_manager();
    init_telemetry();
    init_browser();
    init_ignorePatterns();
    init_workspaceContext();
    init_tool_utils();
    init_errors();
    init_constants3();
    init_models();
    init_storage();
    init_constants2();
    (function(ApprovalMode2) {
      ApprovalMode2["PLAN"] = "plan";
      ApprovalMode2["DEFAULT"] = "default";
      ApprovalMode2["AUTO_EDIT"] = "auto-edit";
      ApprovalMode2["YOLO"] = "yolo";
    })(ApprovalMode || (ApprovalMode = {}));
    APPROVAL_MODES = Object.values(ApprovalMode);
    DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD = 25e3;
    DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES = 1e3;
    MCPServerConfig = class {
      static {
        __name(this, "MCPServerConfig");
      }
      command;
      args;
      env;
      cwd;
      url;
      httpUrl;
      headers;
      tcp;
      timeout;
      trust;
      description;
      includeTools;
      excludeTools;
      extensionName;
      oauth;
      authProviderType;
      targetAudience;
      targetServiceAccount;
      constructor(command2, args, env7, cwd7, url2, httpUrl, headers, tcp, timeout2, trust, description, includeTools, excludeTools, extensionName, oauth, authProviderType, targetAudience, targetServiceAccount) {
        this.command = command2;
        this.args = args;
        this.env = env7;
        this.cwd = cwd7;
        this.url = url2;
        this.httpUrl = httpUrl;
        this.headers = headers;
        this.tcp = tcp;
        this.timeout = timeout2;
        this.trust = trust;
        this.description = description;
        this.includeTools = includeTools;
        this.excludeTools = excludeTools;
        this.extensionName = extensionName;
        this.oauth = oauth;
        this.authProviderType = authProviderType;
        this.targetAudience = targetAudience;
        this.targetServiceAccount = targetServiceAccount;
      }
    };
    (function(AuthProviderType2) {
      AuthProviderType2["DYNAMIC_DISCOVERY"] = "dynamic_discovery";
      AuthProviderType2["GOOGLE_CREDENTIALS"] = "google_credentials";
      AuthProviderType2["SERVICE_ACCOUNT_IMPERSONATION"] = "service_account_impersonation";
    })(AuthProviderType || (AuthProviderType = {}));
    Config = class {
      static {
        __name(this, "Config");
      }
      toolRegistry;
      promptRegistry;
      subagentManager;
      sessionId;
      fileSystemService;
      contentGeneratorConfig;
      contentGenerator;
      _generationConfig;
      embeddingModel;
      sandbox;
      targetDir;
      workspaceContext;
      debugMode;
      question;
      fullContext;
      coreTools;
      allowedTools;
      excludeTools;
      toolDiscoveryCommand;
      toolCallCommand;
      mcpServerCommand;
      mcpServers;
      userMemory;
      geminiMdFileCount;
      approvalMode;
      showMemoryUsage;
      accessibility;
      telemetrySettings;
      gitCoAuthor;
      usageStatisticsEnabled;
      geminiClient;
      baseLlmClient;
      fileFiltering;
      fileDiscoveryService = null;
      gitService = void 0;
      checkpointing;
      proxy;
      cwd;
      bugCommand;
      extensionContextFilePaths;
      noBrowser;
      folderTrustFeature;
      folderTrust;
      ideMode;
      inFallbackMode = false;
      maxSessionTurns;
      sessionTokenLimit;
      listExtensions;
      _extensions;
      _blockedMcpServers;
      fallbackModelHandler;
      quotaErrorOccurred = false;
      summarizeToolOutput;
      cliVersion;
      experimentalZedIntegration = false;
      loadMemoryFromIncludeDirectories = false;
      webSearch;
      chatCompression;
      interactive;
      trustedFolder;
      useRipgrep;
      useBuiltinRipgrep;
      shouldUseNodePtyShell;
      skipNextSpeakerCheck;
      shellExecutionConfig;
      extensionManagement = true;
      skipLoopDetection;
      skipStartupContext;
      vlmSwitchMode;
      initialized = false;
      storage;
      fileExclusions;
      truncateToolOutputThreshold;
      truncateToolOutputLines;
      enableToolOutputTruncation;
      eventEmitter;
      useSmartEdit;
      outputSettings;
      constructor(params) {
        this.sessionId = params.sessionId;
        this.embeddingModel = params.embeddingModel ?? DEFAULT_QWEN_EMBEDDING_MODEL;
        this.fileSystemService = new StandardFileSystemService();
        this.sandbox = params.sandbox;
        this.targetDir = path48.resolve(params.targetDir);
        this.workspaceContext = new WorkspaceContext(this.targetDir, params.includeDirectories ?? []);
        this.debugMode = params.debugMode;
        this.question = params.question;
        this.fullContext = params.fullContext ?? false;
        this.coreTools = params.coreTools;
        this.allowedTools = params.allowedTools;
        this.excludeTools = params.excludeTools;
        this.toolDiscoveryCommand = params.toolDiscoveryCommand;
        this.toolCallCommand = params.toolCallCommand;
        this.mcpServerCommand = params.mcpServerCommand;
        this.mcpServers = params.mcpServers;
        this.userMemory = params.userMemory ?? "";
        this.geminiMdFileCount = params.geminiMdFileCount ?? 0;
        this.approvalMode = params.approvalMode ?? ApprovalMode.DEFAULT;
        this.showMemoryUsage = params.showMemoryUsage ?? false;
        this.accessibility = params.accessibility ?? {};
        this.telemetrySettings = {
          enabled: params.telemetry?.enabled ?? false,
          target: params.telemetry?.target ?? DEFAULT_TELEMETRY_TARGET,
          otlpEndpoint: params.telemetry?.otlpEndpoint ?? DEFAULT_OTLP_ENDPOINT,
          otlpProtocol: params.telemetry?.otlpProtocol,
          logPrompts: params.telemetry?.logPrompts ?? true,
          outfile: params.telemetry?.outfile,
          useCollector: params.telemetry?.useCollector
        };
        this.gitCoAuthor = {
          enabled: params.gitCoAuthor?.enabled ?? true,
          name: params.gitCoAuthor?.name ?? "Qwen-Coder",
          email: params.gitCoAuthor?.email ?? "qwen-coder@alibabacloud.com"
        };
        this.usageStatisticsEnabled = params.usageStatisticsEnabled ?? true;
        this.fileFiltering = {
          respectGitIgnore: params.fileFiltering?.respectGitIgnore ?? true,
          respectQwenIgnore: params.fileFiltering?.respectQwenIgnore ?? true,
          enableRecursiveFileSearch: params.fileFiltering?.enableRecursiveFileSearch ?? true,
          disableFuzzySearch: params.fileFiltering?.disableFuzzySearch ?? false
        };
        this.checkpointing = params.checkpointing ?? false;
        this.proxy = params.proxy;
        this.cwd = params.cwd ?? process23.cwd();
        this.fileDiscoveryService = params.fileDiscoveryService ?? null;
        this.bugCommand = params.bugCommand;
        this.extensionContextFilePaths = params.extensionContextFilePaths ?? [];
        this.maxSessionTurns = params.maxSessionTurns ?? -1;
        this.sessionTokenLimit = params.sessionTokenLimit ?? -1;
        this.experimentalZedIntegration = params.experimentalZedIntegration ?? false;
        this.listExtensions = params.listExtensions ?? false;
        this._extensions = params.extensions ?? [];
        this._blockedMcpServers = params.blockedMcpServers ?? [];
        this.noBrowser = params.noBrowser ?? false;
        this.summarizeToolOutput = params.summarizeToolOutput;
        this.folderTrustFeature = params.folderTrustFeature ?? false;
        this.folderTrust = params.folderTrust ?? false;
        this.ideMode = params.ideMode ?? false;
        this._generationConfig = {
          model: params.model,
          ...params.generationConfig || {},
          baseUrl: params.generationConfig?.baseUrl || DEFAULT_DASHSCOPE_BASE_URL
        };
        this.contentGeneratorConfig = this._generationConfig;
        this.cliVersion = params.cliVersion;
        this.loadMemoryFromIncludeDirectories = params.loadMemoryFromIncludeDirectories ?? false;
        this.chatCompression = params.chatCompression;
        this.interactive = params.interactive ?? false;
        this.trustedFolder = params.trustedFolder;
        this.skipLoopDetection = params.skipLoopDetection ?? false;
        this.skipStartupContext = params.skipStartupContext ?? false;
        this.webSearch = params.webSearch;
        this.useRipgrep = params.useRipgrep ?? true;
        this.useBuiltinRipgrep = params.useBuiltinRipgrep ?? true;
        this.shouldUseNodePtyShell = params.shouldUseNodePtyShell ?? false;
        this.skipNextSpeakerCheck = params.skipNextSpeakerCheck ?? true;
        this.shellExecutionConfig = {
          terminalWidth: params.shellExecutionConfig?.terminalWidth ?? 80,
          terminalHeight: params.shellExecutionConfig?.terminalHeight ?? 24,
          showColor: params.shellExecutionConfig?.showColor ?? false,
          pager: params.shellExecutionConfig?.pager ?? "cat"
        };
        this.truncateToolOutputThreshold = params.truncateToolOutputThreshold ?? DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD;
        this.truncateToolOutputLines = params.truncateToolOutputLines ?? DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES;
        this.enableToolOutputTruncation = params.enableToolOutputTruncation ?? true;
        this.useSmartEdit = params.useSmartEdit ?? false;
        this.extensionManagement = params.extensionManagement ?? true;
        this.storage = new Storage(this.targetDir);
        this.vlmSwitchMode = params.vlmSwitchMode;
        this.fileExclusions = new FileExclusions(this);
        this.eventEmitter = params.eventEmitter;
        this.outputSettings = {
          format: params.output?.format ?? OutputFormat.TEXT
        };
        if (params.contextFileName) {
          setGeminiMdFilename(params.contextFileName);
        }
        if (this.telemetrySettings.enabled) {
          initializeTelemetry(this);
        }
        if (this.getProxy()) {
          (0, import_undici3.setGlobalDispatcher)(new import_undici3.ProxyAgent(this.getProxy()));
        }
        this.geminiClient = new GeminiClient(this);
      }
      /**
       * Must only be called once, throws if called again.
       */
      async initialize() {
        if (this.initialized) {
          throw Error("Config was already initialized");
        }
        this.initialized = true;
        this.getFileService();
        if (this.getCheckpointingEnabled()) {
          await this.getGitService();
        }
        this.promptRegistry = new PromptRegistry();
        this.subagentManager = new SubagentManager(this);
        this.toolRegistry = await this.createToolRegistry();
        await this.geminiClient.initialize();
      }
      getContentGenerator() {
        return this.contentGenerator;
      }
      /**
       * Updates the credentials in the generation config.
       * This is needed when credentials are set after Config construction.
       */
      updateCredentials(credentials) {
        if (credentials.apiKey) {
          this._generationConfig.apiKey = credentials.apiKey;
        }
        if (credentials.baseUrl) {
          this._generationConfig.baseUrl = credentials.baseUrl;
        }
        if (credentials.model) {
          this._generationConfig.model = credentials.model;
        }
      }
      async refreshAuth(authMethod, isInitialAuth) {
        if (this.contentGeneratorConfig?.authType === AuthType2.USE_GEMINI && authMethod === AuthType2.LOGIN_WITH_GOOGLE) {
          this.geminiClient.stripThoughtsFromHistory();
        }
        const newContentGeneratorConfig = createContentGeneratorConfig(this, authMethod, this._generationConfig);
        this.contentGenerator = await createContentGenerator(newContentGeneratorConfig, this, this.getSessionId(), isInitialAuth);
        this.contentGeneratorConfig = newContentGeneratorConfig;
        this.baseLlmClient = new BaseLlmClient(this.contentGenerator, this);
        this.inFallbackMode = false;
        logCliConfiguration(this, new StartSessionEvent(this, this.toolRegistry));
      }
      /**
       * Provides access to the BaseLlmClient for stateless LLM operations.
       */
      getBaseLlmClient() {
        if (!this.baseLlmClient) {
          if (this.contentGenerator) {
            this.baseLlmClient = new BaseLlmClient(this.getContentGenerator(), this);
          } else {
            throw new Error("BaseLlmClient not initialized. Ensure authentication has occurred and ContentGenerator is ready.");
          }
        }
        return this.baseLlmClient;
      }
      getSessionId() {
        return this.sessionId;
      }
      shouldLoadMemoryFromIncludeDirectories() {
        return this.loadMemoryFromIncludeDirectories;
      }
      getContentGeneratorConfig() {
        return this.contentGeneratorConfig;
      }
      getModel() {
        return this.contentGeneratorConfig?.model || DEFAULT_QWEN_MODEL;
      }
      async setModel(newModel, _metadata) {
        if (this.contentGeneratorConfig) {
          this.contentGeneratorConfig.model = newModel;
        }
      }
      isInFallbackMode() {
        return this.inFallbackMode;
      }
      setFallbackMode(active) {
        this.inFallbackMode = active;
      }
      setFallbackModelHandler(handler) {
        this.fallbackModelHandler = handler;
      }
      getMaxSessionTurns() {
        return this.maxSessionTurns;
      }
      getSessionTokenLimit() {
        return this.sessionTokenLimit;
      }
      setQuotaErrorOccurred(value) {
        this.quotaErrorOccurred = value;
      }
      getQuotaErrorOccurred() {
        return this.quotaErrorOccurred;
      }
      getEmbeddingModel() {
        return this.embeddingModel;
      }
      getSandbox() {
        return this.sandbox;
      }
      isRestrictiveSandbox() {
        const sandboxConfig = this.getSandbox();
        const seatbeltProfile = process23.env["SEATBELT_PROFILE"];
        return !!sandboxConfig && sandboxConfig.command === "sandbox-exec" && !!seatbeltProfile && seatbeltProfile.startsWith("restrictive-");
      }
      getTargetDir() {
        return this.targetDir;
      }
      getProjectRoot() {
        return this.targetDir;
      }
      getWorkspaceContext() {
        return this.workspaceContext;
      }
      getToolRegistry() {
        return this.toolRegistry;
      }
      getPromptRegistry() {
        return this.promptRegistry;
      }
      getDebugMode() {
        return this.debugMode;
      }
      getQuestion() {
        return this.question;
      }
      getFullContext() {
        return this.fullContext;
      }
      getCoreTools() {
        return this.coreTools;
      }
      getAllowedTools() {
        return this.allowedTools;
      }
      getExcludeTools() {
        return this.excludeTools;
      }
      getToolDiscoveryCommand() {
        return this.toolDiscoveryCommand;
      }
      getToolCallCommand() {
        return this.toolCallCommand;
      }
      getMcpServerCommand() {
        return this.mcpServerCommand;
      }
      getMcpServers() {
        return this.mcpServers;
      }
      getUserMemory() {
        return this.userMemory;
      }
      setUserMemory(newUserMemory) {
        this.userMemory = newUserMemory;
      }
      getGeminiMdFileCount() {
        return this.geminiMdFileCount;
      }
      setGeminiMdFileCount(count) {
        this.geminiMdFileCount = count;
      }
      getApprovalMode() {
        return this.approvalMode;
      }
      setApprovalMode(mode) {
        if (!this.isTrustedFolder() && mode !== ApprovalMode.DEFAULT && mode !== ApprovalMode.PLAN) {
          throw new Error("Cannot enable privileged approval modes in an untrusted folder.");
        }
        this.approvalMode = mode;
      }
      getShowMemoryUsage() {
        return this.showMemoryUsage;
      }
      getAccessibility() {
        return this.accessibility;
      }
      getTelemetryEnabled() {
        return this.telemetrySettings.enabled ?? false;
      }
      getTelemetryLogPromptsEnabled() {
        return this.telemetrySettings.logPrompts ?? true;
      }
      getTelemetryOtlpEndpoint() {
        return this.telemetrySettings.otlpEndpoint ?? DEFAULT_OTLP_ENDPOINT;
      }
      getTelemetryOtlpProtocol() {
        return this.telemetrySettings.otlpProtocol ?? "grpc";
      }
      getTelemetryTarget() {
        return this.telemetrySettings.target ?? DEFAULT_TELEMETRY_TARGET;
      }
      getTelemetryOutfile() {
        return this.telemetrySettings.outfile;
      }
      getGitCoAuthor() {
        return this.gitCoAuthor;
      }
      getTelemetryUseCollector() {
        return this.telemetrySettings.useCollector ?? false;
      }
      getGeminiClient() {
        return this.geminiClient;
      }
      getEnableRecursiveFileSearch() {
        return this.fileFiltering.enableRecursiveFileSearch;
      }
      getFileFilteringDisableFuzzySearch() {
        return this.fileFiltering.disableFuzzySearch;
      }
      getFileFilteringRespectGitIgnore() {
        return this.fileFiltering.respectGitIgnore;
      }
      getFileFilteringRespectQwenIgnore() {
        return this.fileFiltering.respectQwenIgnore;
      }
      getFileFilteringOptions() {
        return {
          respectGitIgnore: this.fileFiltering.respectGitIgnore,
          respectQwenIgnore: this.fileFiltering.respectQwenIgnore
        };
      }
      /**
       * Gets custom file exclusion patterns from configuration.
       * TODO: This is a placeholder implementation. In the future, this could
       * read from settings files, CLI arguments, or environment variables.
       */
      getCustomExcludes() {
        return [];
      }
      getCheckpointingEnabled() {
        return this.checkpointing;
      }
      getProxy() {
        return this.proxy;
      }
      getWorkingDir() {
        return this.cwd;
      }
      getBugCommand() {
        return this.bugCommand;
      }
      getFileService() {
        if (!this.fileDiscoveryService) {
          this.fileDiscoveryService = new FileDiscoveryService(this.targetDir);
        }
        return this.fileDiscoveryService;
      }
      getUsageStatisticsEnabled() {
        return this.usageStatisticsEnabled;
      }
      getExtensionContextFilePaths() {
        return this.extensionContextFilePaths;
      }
      getExperimentalZedIntegration() {
        return this.experimentalZedIntegration;
      }
      getListExtensions() {
        return this.listExtensions;
      }
      getExtensionManagement() {
        return this.extensionManagement;
      }
      getExtensions() {
        return this._extensions;
      }
      getBlockedMcpServers() {
        return this._blockedMcpServers;
      }
      getNoBrowser() {
        return this.noBrowser;
      }
      isBrowserLaunchSuppressed() {
        return this.getNoBrowser() || !shouldAttemptBrowserLaunch();
      }
      getSummarizeToolOutputConfig() {
        return this.summarizeToolOutput;
      }
      // Web search provider configuration
      getWebSearchConfig() {
        return this.webSearch;
      }
      getIdeMode() {
        return this.ideMode;
      }
      getFolderTrustFeature() {
        return this.folderTrustFeature;
      }
      /**
       * Returns 'true' if the workspace is considered "trusted".
       * 'false' for untrusted.
       */
      getFolderTrust() {
        return this.folderTrust;
      }
      isTrustedFolder() {
        const context2 = ideContextStore.get();
        if (context2?.workspaceState?.isTrusted !== void 0) {
          return context2.workspaceState.isTrusted;
        }
        return this.trustedFolder ?? true;
      }
      setIdeMode(value) {
        this.ideMode = value;
      }
      getAuthType() {
        return this.contentGeneratorConfig.authType;
      }
      getCliVersion() {
        return this.cliVersion;
      }
      /**
       * Get the current FileSystemService
       */
      getFileSystemService() {
        return this.fileSystemService;
      }
      /**
       * Set a custom FileSystemService
       */
      setFileSystemService(fileSystemService) {
        this.fileSystemService = fileSystemService;
      }
      getChatCompression() {
        return this.chatCompression;
      }
      isInteractive() {
        return this.interactive;
      }
      getUseRipgrep() {
        return this.useRipgrep;
      }
      getUseBuiltinRipgrep() {
        return this.useBuiltinRipgrep;
      }
      getShouldUseNodePtyShell() {
        return this.shouldUseNodePtyShell;
      }
      getSkipNextSpeakerCheck() {
        return this.skipNextSpeakerCheck;
      }
      getShellExecutionConfig() {
        return this.shellExecutionConfig;
      }
      setShellExecutionConfig(config) {
        this.shellExecutionConfig = {
          terminalWidth: config.terminalWidth ?? this.shellExecutionConfig.terminalWidth,
          terminalHeight: config.terminalHeight ?? this.shellExecutionConfig.terminalHeight,
          showColor: config.showColor ?? this.shellExecutionConfig.showColor,
          pager: config.pager ?? this.shellExecutionConfig.pager
        };
      }
      getScreenReader() {
        return this.accessibility.screenReader ?? false;
      }
      getSkipLoopDetection() {
        return this.skipLoopDetection;
      }
      getSkipStartupContext() {
        return this.skipStartupContext;
      }
      getVlmSwitchMode() {
        return this.vlmSwitchMode;
      }
      getEnableToolOutputTruncation() {
        return this.enableToolOutputTruncation;
      }
      getTruncateToolOutputThreshold() {
        if (!this.enableToolOutputTruncation || this.truncateToolOutputThreshold <= 0) {
          return Number.POSITIVE_INFINITY;
        }
        return Math.min(
          // Estimate remaining context window in characters (1 token ~= 4 chars).
          4 * (tokenLimit(this.getModel()) - uiTelemetryService.getLastPromptTokenCount()),
          this.truncateToolOutputThreshold
        );
      }
      getTruncateToolOutputLines() {
        if (!this.enableToolOutputTruncation || this.truncateToolOutputLines <= 0) {
          return Number.POSITIVE_INFINITY;
        }
        return this.truncateToolOutputLines;
      }
      getUseSmartEdit() {
        return this.useSmartEdit;
      }
      getOutputFormat() {
        return this.outputSettings?.format ? this.outputSettings.format : OutputFormat.TEXT;
      }
      async getGitService() {
        if (!this.gitService) {
          this.gitService = new GitService(this.targetDir, this.storage);
          await this.gitService.initialize();
        }
        return this.gitService;
      }
      getFileExclusions() {
        return this.fileExclusions;
      }
      getSubagentManager() {
        return this.subagentManager;
      }
      async createToolRegistry() {
        const registry = new ToolRegistry(this, this.eventEmitter);
        const coreToolsConfig = this.getCoreTools();
        const excludeToolsConfig = this.getExcludeTools();
        const registerCoreTool = /* @__PURE__ */ __name((ToolClass, ...args) => {
          const toolName = ToolClass?.Name;
          const className = ToolClass?.name ?? "UnknownTool";
          if (!toolName) {
            console.warn(`[Config] Skipping tool registration: ${className} is missing static Name property. Tools must define a static Name property to be registered. Location: config.ts:registerCoreTool`);
            return;
          }
          if (isToolEnabled(toolName, coreToolsConfig, excludeToolsConfig)) {
            try {
              registry.registerTool(new ToolClass(...args));
            } catch (error) {
              console.error(`[Config] Failed to register tool ${className} (${toolName}):`, error);
              throw error;
            }
          }
        }, "registerCoreTool");
        registerCoreTool(TaskTool, this);
        registerCoreTool(LSTool, this);
        registerCoreTool(ReadFileTool, this);
        if (this.getUseRipgrep()) {
          let useRipgrep = false;
          let errorString = void 0;
          try {
            useRipgrep = await canUseRipgrep(this.getUseBuiltinRipgrep());
          } catch (error) {
            errorString = getErrorMessage(error);
          }
          if (useRipgrep) {
            registerCoreTool(RipGrepTool, this);
          } else {
            logRipgrepFallback(this, new RipgrepFallbackEvent(this.getUseRipgrep(), this.getUseBuiltinRipgrep(), errorString || "ripgrep is not available"));
            registerCoreTool(GrepTool, this);
          }
        } else {
          registerCoreTool(GrepTool, this);
        }
        registerCoreTool(GlobTool, this);
        if (this.getUseSmartEdit()) {
          registerCoreTool(SmartEditTool, this);
        } else {
          registerCoreTool(EditTool, this);
        }
        registerCoreTool(WriteFileTool, this);
        registerCoreTool(ReadManyFilesTool, this);
        registerCoreTool(ShellTool, this);
        registerCoreTool(MemoryTool);
        registerCoreTool(TodoWriteTool, this);
        registerCoreTool(ExitPlanModeTool, this);
        registerCoreTool(WebFetchTool, this);
        if (this.getWebSearchConfig()) {
          registerCoreTool(WebSearchTool, this);
        }
        await registry.discoverAllTools();
        return registry;
      }
    };
  }
});

// packages/core/dist/src/output/json-formatter.js
var JsonFormatter;
var init_json_formatter = __esm({
  "packages/core/dist/src/output/json-formatter.js"() {
    "use strict";
    init_esbuild_shims();
    init_strip_ansi();
    JsonFormatter = class {
      static {
        __name(this, "JsonFormatter");
      }
      format(response, stats, error) {
        const output = {};
        if (response !== void 0) {
          output.response = stripAnsi(response);
        }
        if (stats) {
          output.stats = stats;
        }
        if (error) {
          output.error = error;
        }
        return JSON.stringify(output, null, 2);
      }
      formatError(error, code2) {
        const jsonError = {
          type: error.constructor.name,
          message: stripAnsi(error.message),
          ...code2 && { code: code2 }
        };
        return this.format(void 0, void 0, jsonError);
      }
    };
  }
});

// packages/core/dist/src/core/logger.js
import path49 from "node:path";
import { promises as fs44 } from "node:fs";
function encodeTagName(str2) {
  return encodeURIComponent(str2);
}
function decodeTagName(str2) {
  try {
    return decodeURIComponent(str2);
  } catch (_e) {
    return str2.replace(/%([0-9A-F]{2})/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
  }
}
var LOG_FILE_NAME, MessageSenderType, Logger;
var init_logger = __esm({
  "packages/core/dist/src/core/logger.js"() {
    "use strict";
    init_esbuild_shims();
    LOG_FILE_NAME = "logs.json";
    (function(MessageSenderType2) {
      MessageSenderType2["USER"] = "user";
      MessageSenderType2["MODEL_SWITCH"] = "model_switch";
    })(MessageSenderType || (MessageSenderType = {}));
    __name(encodeTagName, "encodeTagName");
    __name(decodeTagName, "decodeTagName");
    Logger = class {
      static {
        __name(this, "Logger");
      }
      storage;
      qwenDir;
      logFilePath;
      sessionId;
      messageId = 0;
      // Instance-specific counter for the next messageId
      initialized = false;
      logs = [];
      // In-memory cache, ideally reflects the last known state of the file
      constructor(sessionId2, storage) {
        this.storage = storage;
        this.sessionId = sessionId2;
      }
      async _readLogFile() {
        if (!this.logFilePath) {
          throw new Error("Log file path not set during read attempt.");
        }
        try {
          const fileContent = await fs44.readFile(this.logFilePath, "utf-8");
          const parsedLogs = JSON.parse(fileContent);
          if (!Array.isArray(parsedLogs)) {
            console.debug(`Log file at ${this.logFilePath} is not a valid JSON array. Starting with empty logs.`);
            await this._backupCorruptedLogFile("malformed_array");
            return [];
          }
          return parsedLogs.filter((entry) => typeof entry.sessionId === "string" && typeof entry.messageId === "number" && typeof entry.timestamp === "string" && typeof entry.type === "string" && typeof entry.message === "string");
        } catch (error) {
          const nodeError = error;
          if (nodeError.code === "ENOENT") {
            return [];
          }
          if (error instanceof SyntaxError) {
            console.debug(`Invalid JSON in log file ${this.logFilePath}. Backing up and starting fresh.`, error);
            await this._backupCorruptedLogFile("invalid_json");
            return [];
          }
          console.debug(`Failed to read or parse log file ${this.logFilePath}:`, error);
          throw error;
        }
      }
      async _backupCorruptedLogFile(reason) {
        if (!this.logFilePath)
          return;
        const backupPath = `${this.logFilePath}.${reason}.${Date.now()}.bak`;
        try {
          await fs44.rename(this.logFilePath, backupPath);
          console.debug(`Backed up corrupted log file to ${backupPath}`);
        } catch (_backupError) {
        }
      }
      async initialize() {
        if (this.initialized) {
          return;
        }
        this.qwenDir = this.storage.getProjectTempDir();
        this.logFilePath = path49.join(this.qwenDir, LOG_FILE_NAME);
        try {
          await fs44.mkdir(this.qwenDir, { recursive: true });
          let fileExisted = true;
          try {
            await fs44.access(this.logFilePath);
          } catch (_e) {
            fileExisted = false;
          }
          this.logs = await this._readLogFile();
          if (!fileExisted && this.logs.length === 0) {
            await fs44.writeFile(this.logFilePath, "[]", "utf-8");
          }
          const sessionLogs = this.logs.filter((entry) => entry.sessionId === this.sessionId);
          this.messageId = sessionLogs.length > 0 ? Math.max(...sessionLogs.map((entry) => entry.messageId)) + 1 : 0;
          this.initialized = true;
        } catch (err) {
          console.error("Failed to initialize logger:", err);
          this.initialized = false;
        }
      }
      async _updateLogFile(entryToAppend) {
        if (!this.logFilePath) {
          console.debug("Log file path not set. Cannot persist log entry.");
          throw new Error("Log file path not set during update attempt.");
        }
        let currentLogsOnDisk;
        try {
          currentLogsOnDisk = await this._readLogFile();
        } catch (readError) {
          console.debug("Critical error reading log file before append:", readError);
          throw readError;
        }
        const sessionLogsOnDisk = currentLogsOnDisk.filter((e2) => e2.sessionId === entryToAppend.sessionId);
        const nextMessageIdForSession = sessionLogsOnDisk.length > 0 ? Math.max(...sessionLogsOnDisk.map((e2) => e2.messageId)) + 1 : 0;
        entryToAppend.messageId = nextMessageIdForSession;
        const entryExists = currentLogsOnDisk.some((e2) => e2.sessionId === entryToAppend.sessionId && e2.messageId === entryToAppend.messageId && e2.timestamp === entryToAppend.timestamp && // Timestamps are good for distinguishing
        e2.message === entryToAppend.message);
        if (entryExists) {
          console.debug(`Duplicate log entry detected and skipped: session ${entryToAppend.sessionId}, messageId ${entryToAppend.messageId}`);
          this.logs = currentLogsOnDisk;
          return null;
        }
        currentLogsOnDisk.push(entryToAppend);
        try {
          await fs44.writeFile(this.logFilePath, JSON.stringify(currentLogsOnDisk, null, 2), "utf-8");
          this.logs = currentLogsOnDisk;
          return entryToAppend;
        } catch (error) {
          console.debug("Error writing to log file:", error);
          throw error;
        }
      }
      async getPreviousUserMessages() {
        if (!this.initialized)
          return [];
        return this.logs.filter((entry) => entry.type === MessageSenderType.USER).sort((a, b) => {
          const dateA = new Date(a.timestamp).getTime();
          const dateB = new Date(b.timestamp).getTime();
          return dateB - dateA;
        }).map((entry) => entry.message);
      }
      async logMessage(type, message) {
        if (!this.initialized || this.sessionId === void 0) {
          console.debug("Logger not initialized or session ID missing. Cannot log message.");
          return;
        }
        const newEntryObject = {
          sessionId: this.sessionId,
          messageId: this.messageId,
          // This will be recalculated in _updateLogFile
          type,
          message,
          timestamp: (/* @__PURE__ */ new Date()).toISOString()
        };
        try {
          const writtenEntry = await this._updateLogFile(newEntryObject);
          if (writtenEntry) {
            this.messageId = writtenEntry.messageId + 1;
          }
        } catch (_error) {
        }
      }
      _checkpointPath(tag2) {
        if (!tag2.length) {
          throw new Error("No checkpoint tag specified.");
        }
        if (!this.qwenDir) {
          throw new Error("Checkpoint file path not set.");
        }
        const encodedTag = encodeTagName(tag2);
        return path49.join(this.qwenDir, `checkpoint-${encodedTag}.json`);
      }
      async _getCheckpointPath(tag2) {
        const newPath = this._checkpointPath(tag2);
        try {
          await fs44.access(newPath);
          return newPath;
        } catch (error) {
          const nodeError = error;
          if (nodeError.code !== "ENOENT") {
            throw error;
          }
        }
        const oldPath = path49.join(this.qwenDir, `checkpoint-${tag2}.json`);
        try {
          await fs44.access(oldPath);
          return oldPath;
        } catch (error) {
          const nodeError = error;
          if (nodeError.code !== "ENOENT") {
            throw error;
          }
        }
        return newPath;
      }
      async saveCheckpoint(conversation, tag2) {
        if (!this.initialized) {
          console.error("Logger not initialized or checkpoint file path not set. Cannot save a checkpoint.");
          return;
        }
        const path108 = this._checkpointPath(tag2);
        try {
          await fs44.writeFile(path108, JSON.stringify(conversation, null, 2), "utf-8");
        } catch (error) {
          console.error("Error writing to checkpoint file:", error);
        }
      }
      async loadCheckpoint(tag2) {
        if (!this.initialized) {
          console.error("Logger not initialized or checkpoint file path not set. Cannot load checkpoint.");
          return [];
        }
        const path108 = await this._getCheckpointPath(tag2);
        try {
          const fileContent = await fs44.readFile(path108, "utf-8");
          const parsedContent = JSON.parse(fileContent);
          if (!Array.isArray(parsedContent)) {
            console.warn(`Checkpoint file at ${path108} is not a valid JSON array. Returning empty checkpoint.`);
            return [];
          }
          return parsedContent;
        } catch (error) {
          const nodeError = error;
          if (nodeError.code === "ENOENT") {
            return [];
          }
          console.error(`Failed to read or parse checkpoint file ${path108}:`, error);
          return [];
        }
      }
      async deleteCheckpoint(tag2) {
        if (!this.initialized || !this.qwenDir) {
          console.error("Logger not initialized or checkpoint file path not set. Cannot delete checkpoint.");
          return false;
        }
        let deletedSomething = false;
        const newPath = this._checkpointPath(tag2);
        try {
          await fs44.unlink(newPath);
          deletedSomething = true;
        } catch (error) {
          const nodeError = error;
          if (nodeError.code !== "ENOENT") {
            console.error(`Failed to delete checkpoint file ${newPath}:`, error);
            throw error;
          }
        }
        const oldPath = path49.join(this.qwenDir, `checkpoint-${tag2}.json`);
        if (newPath !== oldPath) {
          try {
            await fs44.unlink(oldPath);
            deletedSomething = true;
          } catch (error) {
            const nodeError = error;
            if (nodeError.code !== "ENOENT") {
              console.error(`Failed to delete checkpoint file ${oldPath}:`, error);
              throw error;
            }
          }
        }
        return deletedSomething;
      }
      async checkpointExists(tag2) {
        if (!this.initialized) {
          throw new Error("Logger not initialized. Cannot check for checkpoint existence.");
        }
        let filePath;
        try {
          filePath = await this._getCheckpointPath(tag2);
          await fs44.access(filePath);
          return true;
        } catch (error) {
          const nodeError = error;
          if (nodeError.code === "ENOENT") {
            return false;
          }
          console.error(`Failed to check checkpoint existence for ${filePath ?? `path for tag "${tag2}"`}:`, error);
          throw error;
        }
      }
      close() {
        this.initialized = false;
        this.logFilePath = void 0;
        this.logs = [];
        this.sessionId = void 0;
        this.messageId = 0;
      }
    };
  }
});

// packages/core/dist/src/core/nonInteractiveToolExecutor.js
async function executeToolCall(config, toolCallRequest, abortSignal) {
  return new Promise((resolve24, reject) => {
    new CoreToolScheduler({
      config,
      getPreferredEditor: /* @__PURE__ */ __name(() => void 0, "getPreferredEditor"),
      onEditorClose: /* @__PURE__ */ __name(() => {
      }, "onEditorClose"),
      onAllToolCallsComplete: /* @__PURE__ */ __name(async (completedToolCalls) => {
        resolve24(completedToolCalls[0].response);
      }, "onAllToolCallsComplete")
    }).schedule(toolCallRequest, abortSignal).catch(reject);
  });
}
var init_nonInteractiveToolExecutor = __esm({
  "packages/core/dist/src/core/nonInteractiveToolExecutor.js"() {
    "use strict";
    init_esbuild_shims();
    init_coreToolScheduler();
    __name(executeToolCall, "executeToolCall");
  }
});

// packages/core/dist/src/fallback/types.js
var init_types11 = __esm({
  "packages/core/dist/src/fallback/types.js"() {
    "use strict";
    init_esbuild_shims();
  }
});

// packages/core/dist/src/utils/bfsFileSearch.js
import * as fs45 from "node:fs/promises";
import * as path50 from "node:path";
async function bfsFileSearch(rootDir, options2) {
  const { fileName, ignoreDirs = [], maxDirs = Infinity, debug: debug2 = false, fileService } = options2;
  const foundFiles = [];
  const queue = [rootDir];
  const visited = /* @__PURE__ */ new Set();
  let scannedDirCount = 0;
  let queueHead = 0;
  const ignoreDirsSet = new Set(ignoreDirs);
  const PARALLEL_BATCH_SIZE = 15;
  while (queueHead < queue.length && scannedDirCount < maxDirs) {
    const batchSize = Math.min(PARALLEL_BATCH_SIZE, maxDirs - scannedDirCount);
    const currentBatch = [];
    while (currentBatch.length < batchSize && queueHead < queue.length) {
      const currentDir = queue[queueHead];
      queueHead++;
      if (!visited.has(currentDir)) {
        visited.add(currentDir);
        currentBatch.push(currentDir);
      }
    }
    scannedDirCount += currentBatch.length;
    if (currentBatch.length === 0)
      continue;
    if (debug2) {
      logger2.debug(`Scanning [${scannedDirCount}/${maxDirs}]: batch of ${currentBatch.length}`);
    }
    const readPromises = currentBatch.map(async (currentDir) => {
      try {
        const entries = await fs45.readdir(currentDir, { withFileTypes: true });
        return { currentDir, entries };
      } catch (error) {
        const message = error?.message ?? "Unknown error";
        console.warn(`[WARN] Skipping unreadable directory: ${currentDir} (${message})`);
        if (debug2) {
          logger2.debug(`Full error for ${currentDir}:`, error);
        }
        return { currentDir, entries: [] };
      }
    });
    const results = await Promise.all(readPromises);
    for (const { currentDir, entries } of results) {
      for (const entry of entries) {
        const fullPath = path50.join(currentDir, entry.name);
        const isDirectory = entry.isDirectory();
        const isMatchingFile = entry.isFile() && entry.name === fileName;
        if (!isDirectory && !isMatchingFile) {
          continue;
        }
        if (isDirectory && ignoreDirsSet.has(entry.name)) {
          continue;
        }
        if (fileService?.shouldIgnoreFile(fullPath, {
          respectGitIgnore: options2.fileFilteringOptions?.respectGitIgnore,
          respectQwenIgnore: options2.fileFilteringOptions?.respectQwenIgnore
        })) {
          continue;
        }
        if (isDirectory) {
          queue.push(fullPath);
        } else {
          foundFiles.push(fullPath);
        }
      }
    }
  }
  return foundFiles;
}
var logger2;
var init_bfsFileSearch = __esm({
  "packages/core/dist/src/utils/bfsFileSearch.js"() {
    "use strict";
    init_esbuild_shims();
    logger2 = {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      debug: /* @__PURE__ */ __name((...args) => console.debug("[DEBUG] [BfsFileSearch]", ...args), "debug")
    };
    __name(bfsFileSearch, "bfsFileSearch");
  }
});

// node_modules/marked/lib/marked.esm.js
function _getDefaults() {
  return {
    async: false,
    breaks: false,
    extensions: null,
    gfm: true,
    hooks: null,
    pedantic: false,
    renderer: null,
    silent: false,
    tokenizer: null,
    walkTokens: null
  };
}
function changeDefaults(newDefaults) {
  _defaults = newDefaults;
}
function edit(regex3, opt = "") {
  let source2 = typeof regex3 === "string" ? regex3 : regex3.source;
  const obj = {
    replace: /* @__PURE__ */ __name((name3, val) => {
      let valSource = typeof val === "string" ? val : val.source;
      valSource = valSource.replace(other.caret, "$1");
      source2 = source2.replace(name3, valSource);
      return obj;
    }, "replace"),
    getRegex: /* @__PURE__ */ __name(() => {
      return new RegExp(source2, opt);
    }, "getRegex")
  };
  return obj;
}
function escape22(html2, encode4) {
  if (encode4) {
    if (other.escapeTest.test(html2)) {
      return html2.replace(other.escapeReplace, getEscapeReplacement);
    }
  } else {
    if (other.escapeTestNoEncode.test(html2)) {
      return html2.replace(other.escapeReplaceNoEncode, getEscapeReplacement);
    }
  }
  return html2;
}
function cleanUrl(href) {
  try {
    href = encodeURI(href).replace(other.percentDecode, "%");
  } catch {
    return null;
  }
  return href;
}
function splitCells(tableRow, count) {
  const row = tableRow.replace(other.findPipe, (match2, offset, str2) => {
    let escaped = false;
    let curr = offset;
    while (--curr >= 0 && str2[curr] === "\\") escaped = !escaped;
    if (escaped) {
      return "|";
    } else {
      return " |";
    }
  }), cells = row.split(other.splitPipe);
  let i = 0;
  if (!cells[0].trim()) {
    cells.shift();
  }
  if (cells.length > 0 && !cells.at(-1)?.trim()) {
    cells.pop();
  }
  if (count) {
    if (cells.length > count) {
      cells.splice(count);
    } else {
      while (cells.length < count) cells.push("");
    }
  }
  for (; i < cells.length; i++) {
    cells[i] = cells[i].trim().replace(other.slashPipe, "|");
  }
  return cells;
}
function rtrim(str2, c3, invert) {
  const l2 = str2.length;
  if (l2 === 0) {
    return "";
  }
  let suffLen = 0;
  while (suffLen < l2) {
    const currChar = str2.charAt(l2 - suffLen - 1);
    if (currChar === c3 && !invert) {
      suffLen++;
    } else if (currChar !== c3 && invert) {
      suffLen++;
    } else {
      break;
    }
  }
  return str2.slice(0, l2 - suffLen);
}
function findClosingBracket(str2, b) {
  if (str2.indexOf(b[1]) === -1) {
    return -1;
  }
  let level = 0;
  for (let i = 0; i < str2.length; i++) {
    if (str2[i] === "\\") {
      i++;
    } else if (str2[i] === b[0]) {
      level++;
    } else if (str2[i] === b[1]) {
      level--;
      if (level < 0) {
        return i;
      }
    }
  }
  if (level > 0) {
    return -2;
  }
  return -1;
}
function outputLink(cap, link22, raw2, lexer2, rules) {
  const href = link22.href;
  const title = link22.title || null;
  const text = cap[1].replace(rules.other.outputLinkReplace, "$1");
  lexer2.state.inLink = true;
  const token2 = {
    type: cap[0].charAt(0) === "!" ? "image" : "link",
    raw: raw2,
    href,
    title,
    text,
    tokens: lexer2.inlineTokens(text)
  };
  lexer2.state.inLink = false;
  return token2;
}
function indentCodeCompensation(raw2, text, rules) {
  const matchIndentToCode = raw2.match(rules.other.indentCodeCompensation);
  if (matchIndentToCode === null) {
    return text;
  }
  const indentToCode = matchIndentToCode[1];
  return text.split("\n").map((node) => {
    const matchIndentInNode = node.match(rules.other.beginningSpace);
    if (matchIndentInNode === null) {
      return node;
    }
    const [indentInNode] = matchIndentInNode;
    if (indentInNode.length >= indentToCode.length) {
      return node.slice(indentToCode.length);
    }
    return node;
  }).join("\n");
}
function marked(src, opt) {
  return markedInstance.parse(src, opt);
}
var _defaults, noopTest, other, newline, blockCode, fences, hr, heading, bullet, lheadingCore, lheading, lheadingGfm, _paragraph, blockText, _blockLabel, def, list, _tag, _comment, html, paragraph, blockquote, blockNormal, gfmTable, blockGfm, blockPedantic, escape6, inlineCode, br, inlineText, _punctuation, _punctuationOrSpace, _notPunctuationOrSpace, punctuation, _punctuationGfmStrongEm, _punctuationOrSpaceGfmStrongEm, _notPunctuationOrSpaceGfmStrongEm, blockSkip, emStrongLDelimCore, emStrongLDelim, emStrongLDelimGfm, emStrongRDelimAstCore, emStrongRDelimAst, emStrongRDelimAstGfm, emStrongRDelimUnd, anyPunctuation, autolink, _inlineComment, tag, _inlineLabel, link2, reflink, nolink, reflinkSearch, inlineNormal, inlinePedantic, inlineGfm, inlineBreaks, block, inline, escapeReplacements, getEscapeReplacement, _Tokenizer, _Lexer, _Renderer, _TextRenderer, _Parser, _Hooks, Marked, markedInstance, options, setOptions, use, walkTokens, parseInline, parser4, lexer;
var init_marked_esm = __esm({
  "node_modules/marked/lib/marked.esm.js"() {
    init_esbuild_shims();
    __name(_getDefaults, "_getDefaults");
    _defaults = _getDefaults();
    __name(changeDefaults, "changeDefaults");
    noopTest = { exec: /* @__PURE__ */ __name(() => null, "exec") };
    __name(edit, "edit");
    other = {
      codeRemoveIndent: /^(?: {1,4}| {0,3}\t)/gm,
      outputLinkReplace: /\\([\[\]])/g,
      indentCodeCompensation: /^(\s+)(?:```)/,
      beginningSpace: /^\s+/,
      endingHash: /#$/,
      startingSpaceChar: /^ /,
      endingSpaceChar: / $/,
      nonSpaceChar: /[^ ]/,
      newLineCharGlobal: /\n/g,
      tabCharGlobal: /\t/g,
      multipleSpaceGlobal: /\s+/g,
      blankLine: /^[ \t]*$/,
      doubleBlankLine: /\n[ \t]*\n[ \t]*$/,
      blockquoteStart: /^ {0,3}>/,
      blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g,
      blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm,
      listReplaceTabs: /^\t+/,
      listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g,
      listIsTask: /^\[[ xX]\] /,
      listReplaceTask: /^\[[ xX]\] +/,
      anyLine: /\n.*\n/,
      hrefBrackets: /^<(.*)>$/,
      tableDelimiter: /[:|]/,
      tableAlignChars: /^\||\| *$/g,
      tableRowBlankLine: /\n[ \t]*$/,
      tableAlignRight: /^ *-+: *$/,
      tableAlignCenter: /^ *:-+: *$/,
      tableAlignLeft: /^ *:-+ *$/,
      startATag: /^<a /i,
      endATag: /^<\/a>/i,
      startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i,
      endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i,
      startAngleBracket: /^</,
      endAngleBracket: />$/,
      pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/,
      unicodeAlphaNumeric: /[\p{L}\p{N}]/u,
      escapeTest: /[&<>"']/,
      escapeReplace: /[&<>"']/g,
      escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,
      escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,
      unescapeTest: /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,
      caret: /(^|[^\[])\^/g,
      percentDecode: /%25/g,
      findPipe: /\|/g,
      splitPipe: / \|/,
      slashPipe: /\\\|/g,
      carriageReturn: /\r\n|\r/g,
      spaceLine: /^ +$/gm,
      notSpaceStart: /^\S*/,
      endingNewline: /\n$/,
      listItemRegex: /* @__PURE__ */ __name((bull) => new RegExp(`^( {0,3}${bull})((?:[	 ][^\\n]*)?(?:\\n|$))`), "listItemRegex"),
      nextBulletRegex: /* @__PURE__ */ __name((indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ 	][^\\n]*)?(?:\\n|$))`), "nextBulletRegex"),
      hrRegex: /* @__PURE__ */ __name((indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`), "hrRegex"),
      fencesBeginRegex: /* @__PURE__ */ __name((indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`), "fencesBeginRegex"),
      headingBeginRegex: /* @__PURE__ */ __name((indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`), "headingBeginRegex"),
      htmlBeginRegex: /* @__PURE__ */ __name((indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, "i"), "htmlBeginRegex")
    };
    newline = /^(?:[ \t]*(?:\n|$))+/;
    blockCode = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/;
    fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
    hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
    heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
    bullet = /(?:[*+-]|\d{1,9}[.)])/;
    lheadingCore = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/;
    lheading = edit(lheadingCore).replace(/bull/g, bullet).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/\|table/g, "").getRegex();
    lheadingGfm = edit(lheadingCore).replace(/bull/g, bullet).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/table/g, / {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex();
    _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/;
    blockText = /^[^\n]+/;
    _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
    def = edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label", _blockLabel).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex();
    list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, bullet).getRegex();
    _tag = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";
    _comment = /<!--(?:-?>|[\s\S]*?(?:-->|$))/;
    html = edit(
      "^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ 	]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ 	]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ 	]*)+\\n|$))",
      "i"
    ).replace("comment", _comment).replace("tag", _tag).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
    paragraph = edit(_paragraph).replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex();
    blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", paragraph).getRegex();
    blockNormal = {
      blockquote,
      code: blockCode,
      def,
      fences,
      heading,
      hr,
      html,
      lheading,
      list,
      newline,
      paragraph,
      table: noopTest,
      text: blockText
    };
    gfmTable = edit(
      "^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"
    ).replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", "(?: {4}| {0,3}	)[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex();
    blockGfm = {
      ...blockNormal,
      lheading: lheadingGfm,
      table: gfmTable,
      paragraph: edit(_paragraph).replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", gfmTable).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex()
    };
    blockPedantic = {
      ...blockNormal,
      html: edit(
        `^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`
      ).replace("comment", _comment).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),
      def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
      heading: /^(#{1,6})(.*)(?:\n+|$)/,
      fences: noopTest,
      // fences not supported
      lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
      paragraph: edit(_paragraph).replace("hr", hr).replace("heading", " *#{1,6} *[^\n]").replace("lheading", lheading).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex()
    };
    escape6 = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
    inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
    br = /^( {2,}|\\)\n(?!\s*$)/;
    inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/;
    _punctuation = /[\p{P}\p{S}]/u;
    _punctuationOrSpace = /[\s\p{P}\p{S}]/u;
    _notPunctuationOrSpace = /[^\s\p{P}\p{S}]/u;
    punctuation = edit(/^((?![*_])punctSpace)/, "u").replace(/punctSpace/g, _punctuationOrSpace).getRegex();
    _punctuationGfmStrongEm = /(?!~)[\p{P}\p{S}]/u;
    _punctuationOrSpaceGfmStrongEm = /(?!~)[\s\p{P}\p{S}]/u;
    _notPunctuationOrSpaceGfmStrongEm = /(?:[^\s\p{P}\p{S}]|~)/u;
    blockSkip = /\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g;
    emStrongLDelimCore = /^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/;
    emStrongLDelim = edit(emStrongLDelimCore, "u").replace(/punct/g, _punctuation).getRegex();
    emStrongLDelimGfm = edit(emStrongLDelimCore, "u").replace(/punct/g, _punctuationGfmStrongEm).getRegex();
    emStrongRDelimAstCore = "^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)";
    emStrongRDelimAst = edit(emStrongRDelimAstCore, "gu").replace(/notPunctSpace/g, _notPunctuationOrSpace).replace(/punctSpace/g, _punctuationOrSpace).replace(/punct/g, _punctuation).getRegex();
    emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, "gu").replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm).replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm).replace(/punct/g, _punctuationGfmStrongEm).getRegex();
    emStrongRDelimUnd = edit(
      "^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)",
      "gu"
    ).replace(/notPunctSpace/g, _notPunctuationOrSpace).replace(/punctSpace/g, _punctuationOrSpace).replace(/punct/g, _punctuation).getRegex();
    anyPunctuation = edit(/\\(punct)/, "gu").replace(/punct/g, _punctuation).getRegex();
    autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[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])?)+(?![-_])/).getRegex();
    _inlineComment = edit(_comment).replace("(?:-->|$)", "-->").getRegex();
    tag = edit(
      "^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>"
    ).replace("comment", _inlineComment).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex();
    _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
    link2 = edit(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label", _inlineLabel).replace("href", /<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex();
    reflink = edit(/^!?\[(label)\]\[(ref)\]/).replace("label", _inlineLabel).replace("ref", _blockLabel).getRegex();
    nolink = edit(/^!?\[(ref)\](?:\[\])?/).replace("ref", _blockLabel).getRegex();
    reflinkSearch = edit("reflink|nolink(?!\\()", "g").replace("reflink", reflink).replace("nolink", nolink).getRegex();
    inlineNormal = {
      _backpedal: noopTest,
      // only used for GFM url
      anyPunctuation,
      autolink,
      blockSkip,
      br,
      code: inlineCode,
      del: noopTest,
      emStrongLDelim,
      emStrongRDelimAst,
      emStrongRDelimUnd,
      escape: escape6,
      link: link2,
      nolink,
      punctuation,
      reflink,
      reflinkSearch,
      tag,
      text: inlineText,
      url: noopTest
    };
    inlinePedantic = {
      ...inlineNormal,
      link: edit(/^!?\[(label)\]\((.*?)\)/).replace("label", _inlineLabel).getRegex(),
      reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", _inlineLabel).getRegex()
    };
    inlineGfm = {
      ...inlineNormal,
      emStrongRDelimAst: emStrongRDelimAstGfm,
      emStrongLDelim: emStrongLDelimGfm,
      url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, "i").replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),
      _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,
      del: /^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,
      text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/
    };
    inlineBreaks = {
      ...inlineGfm,
      br: edit(br).replace("{2,}", "*").getRegex(),
      text: edit(inlineGfm.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex()
    };
    block = {
      normal: blockNormal,
      gfm: blockGfm,
      pedantic: blockPedantic
    };
    inline = {
      normal: inlineNormal,
      gfm: inlineGfm,
      breaks: inlineBreaks,
      pedantic: inlinePedantic
    };
    escapeReplacements = {
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': "&quot;",
      "'": "&#39;"
    };
    getEscapeReplacement = /* @__PURE__ */ __name((ch) => escapeReplacements[ch], "getEscapeReplacement");
    __name(escape22, "escape2");
    __name(cleanUrl, "cleanUrl");
    __name(splitCells, "splitCells");
    __name(rtrim, "rtrim");
    __name(findClosingBracket, "findClosingBracket");
    __name(outputLink, "outputLink");
    __name(indentCodeCompensation, "indentCodeCompensation");
    _Tokenizer = class {
      static {
        __name(this, "_Tokenizer");
      }
      options;
      rules;
      // set by the lexer
      lexer;
      // set by the lexer
      constructor(options2) {
        this.options = options2 || _defaults;
      }
      space(src) {
        const cap = this.rules.block.newline.exec(src);
        if (cap && cap[0].length > 0) {
          return {
            type: "space",
            raw: cap[0]
          };
        }
      }
      code(src) {
        const cap = this.rules.block.code.exec(src);
        if (cap) {
          const text = cap[0].replace(this.rules.other.codeRemoveIndent, "");
          return {
            type: "code",
            raw: cap[0],
            codeBlockStyle: "indented",
            text: !this.options.pedantic ? rtrim(text, "\n") : text
          };
        }
      }
      fences(src) {
        const cap = this.rules.block.fences.exec(src);
        if (cap) {
          const raw2 = cap[0];
          const text = indentCodeCompensation(raw2, cap[3] || "", this.rules);
          return {
            type: "code",
            raw: raw2,
            lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : cap[2],
            text
          };
        }
      }
      heading(src) {
        const cap = this.rules.block.heading.exec(src);
        if (cap) {
          let text = cap[2].trim();
          if (this.rules.other.endingHash.test(text)) {
            const trimmed2 = rtrim(text, "#");
            if (this.options.pedantic) {
              text = trimmed2.trim();
            } else if (!trimmed2 || this.rules.other.endingSpaceChar.test(trimmed2)) {
              text = trimmed2.trim();
            }
          }
          return {
            type: "heading",
            raw: cap[0],
            depth: cap[1].length,
            text,
            tokens: this.lexer.inline(text)
          };
        }
      }
      hr(src) {
        const cap = this.rules.block.hr.exec(src);
        if (cap) {
          return {
            type: "hr",
            raw: rtrim(cap[0], "\n")
          };
        }
      }
      blockquote(src) {
        const cap = this.rules.block.blockquote.exec(src);
        if (cap) {
          let lines = rtrim(cap[0], "\n").split("\n");
          let raw2 = "";
          let text = "";
          const tokens = [];
          while (lines.length > 0) {
            let inBlockquote = false;
            const currentLines = [];
            let i;
            for (i = 0; i < lines.length; i++) {
              if (this.rules.other.blockquoteStart.test(lines[i])) {
                currentLines.push(lines[i]);
                inBlockquote = true;
              } else if (!inBlockquote) {
                currentLines.push(lines[i]);
              } else {
                break;
              }
            }
            lines = lines.slice(i);
            const currentRaw = currentLines.join("\n");
            const currentText = currentRaw.replace(this.rules.other.blockquoteSetextReplace, "\n    $1").replace(this.rules.other.blockquoteSetextReplace2, "");
            raw2 = raw2 ? `${raw2}
${currentRaw}` : currentRaw;
            text = text ? `${text}
${currentText}` : currentText;
            const top2 = this.lexer.state.top;
            this.lexer.state.top = true;
            this.lexer.blockTokens(currentText, tokens, true);
            this.lexer.state.top = top2;
            if (lines.length === 0) {
              break;
            }
            const lastToken = tokens.at(-1);
            if (lastToken?.type === "code") {
              break;
            } else if (lastToken?.type === "blockquote") {
              const oldToken = lastToken;
              const newText = oldToken.raw + "\n" + lines.join("\n");
              const newToken = this.blockquote(newText);
              tokens[tokens.length - 1] = newToken;
              raw2 = raw2.substring(0, raw2.length - oldToken.raw.length) + newToken.raw;
              text = text.substring(0, text.length - oldToken.text.length) + newToken.text;
              break;
            } else if (lastToken?.type === "list") {
              const oldToken = lastToken;
              const newText = oldToken.raw + "\n" + lines.join("\n");
              const newToken = this.list(newText);
              tokens[tokens.length - 1] = newToken;
              raw2 = raw2.substring(0, raw2.length - lastToken.raw.length) + newToken.raw;
              text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;
              lines = newText.substring(tokens.at(-1).raw.length).split("\n");
              continue;
            }
          }
          return {
            type: "blockquote",
            raw: raw2,
            tokens,
            text
          };
        }
      }
      list(src) {
        let cap = this.rules.block.list.exec(src);
        if (cap) {
          let bull = cap[1].trim();
          const isordered = bull.length > 1;
          const list22 = {
            type: "list",
            raw: "",
            ordered: isordered,
            start: isordered ? +bull.slice(0, -1) : "",
            loose: false,
            items: []
          };
          bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`;
          if (this.options.pedantic) {
            bull = isordered ? bull : "[*+-]";
          }
          const itemRegex = this.rules.other.listItemRegex(bull);
          let endsWithBlankLine = false;
          while (src) {
            let endEarly = false;
            let raw2 = "";
            let itemContents = "";
            if (!(cap = itemRegex.exec(src))) {
              break;
            }
            if (this.rules.block.hr.test(src)) {
              break;
            }
            raw2 = cap[0];
            src = src.substring(raw2.length);
            let line = cap[2].split("\n", 1)[0].replace(this.rules.other.listReplaceTabs, (t2) => " ".repeat(3 * t2.length));
            let nextLine = src.split("\n", 1)[0];
            let blankLine = !line.trim();
            let indent = 0;
            if (this.options.pedantic) {
              indent = 2;
              itemContents = line.trimStart();
            } else if (blankLine) {
              indent = cap[1].length + 1;
            } else {
              indent = cap[2].search(this.rules.other.nonSpaceChar);
              indent = indent > 4 ? 1 : indent;
              itemContents = line.slice(indent);
              indent += cap[1].length;
            }
            if (blankLine && this.rules.other.blankLine.test(nextLine)) {
              raw2 += nextLine + "\n";
              src = src.substring(nextLine.length + 1);
              endEarly = true;
            }
            if (!endEarly) {
              const nextBulletRegex = this.rules.other.nextBulletRegex(indent);
              const hrRegex = this.rules.other.hrRegex(indent);
              const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent);
              const headingBeginRegex = this.rules.other.headingBeginRegex(indent);
              const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent);
              while (src) {
                const rawLine = src.split("\n", 1)[0];
                let nextLineWithoutTabs;
                nextLine = rawLine;
                if (this.options.pedantic) {
                  nextLine = nextLine.replace(this.rules.other.listReplaceNesting, "  ");
                  nextLineWithoutTabs = nextLine;
                } else {
                  nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, "    ");
                }
                if (fencesBeginRegex.test(nextLine)) {
                  break;
                }
                if (headingBeginRegex.test(nextLine)) {
                  break;
                }
                if (htmlBeginRegex.test(nextLine)) {
                  break;
                }
                if (nextBulletRegex.test(nextLine)) {
                  break;
                }
                if (hrRegex.test(nextLine)) {
                  break;
                }
                if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) {
                  itemContents += "\n" + nextLineWithoutTabs.slice(indent);
                } else {
                  if (blankLine) {
                    break;
                  }
                  if (line.replace(this.rules.other.tabCharGlobal, "    ").search(this.rules.other.nonSpaceChar) >= 4) {
                    break;
                  }
                  if (fencesBeginRegex.test(line)) {
                    break;
                  }
                  if (headingBeginRegex.test(line)) {
                    break;
                  }
                  if (hrRegex.test(line)) {
                    break;
                  }
                  itemContents += "\n" + nextLine;
                }
                if (!blankLine && !nextLine.trim()) {
                  blankLine = true;
                }
                raw2 += rawLine + "\n";
                src = src.substring(rawLine.length + 1);
                line = nextLineWithoutTabs.slice(indent);
              }
            }
            if (!list22.loose) {
              if (endsWithBlankLine) {
                list22.loose = true;
              } else if (this.rules.other.doubleBlankLine.test(raw2)) {
                endsWithBlankLine = true;
              }
            }
            let istask = null;
            let ischecked;
            if (this.options.gfm) {
              istask = this.rules.other.listIsTask.exec(itemContents);
              if (istask) {
                ischecked = istask[0] !== "[ ] ";
                itemContents = itemContents.replace(this.rules.other.listReplaceTask, "");
              }
            }
            list22.items.push({
              type: "list_item",
              raw: raw2,
              task: !!istask,
              checked: ischecked,
              loose: false,
              text: itemContents,
              tokens: []
            });
            list22.raw += raw2;
          }
          const lastItem = list22.items.at(-1);
          if (lastItem) {
            lastItem.raw = lastItem.raw.trimEnd();
            lastItem.text = lastItem.text.trimEnd();
          } else {
            return;
          }
          list22.raw = list22.raw.trimEnd();
          for (let i = 0; i < list22.items.length; i++) {
            this.lexer.state.top = false;
            list22.items[i].tokens = this.lexer.blockTokens(list22.items[i].text, []);
            if (!list22.loose) {
              const spacers = list22.items[i].tokens.filter((t2) => t2.type === "space");
              const hasMultipleLineBreaks = spacers.length > 0 && spacers.some((t2) => this.rules.other.anyLine.test(t2.raw));
              list22.loose = hasMultipleLineBreaks;
            }
          }
          if (list22.loose) {
            for (let i = 0; i < list22.items.length; i++) {
              list22.items[i].loose = true;
            }
          }
          return list22;
        }
      }
      html(src) {
        const cap = this.rules.block.html.exec(src);
        if (cap) {
          const token2 = {
            type: "html",
            block: true,
            raw: cap[0],
            pre: cap[1] === "pre" || cap[1] === "script" || cap[1] === "style",
            text: cap[0]
          };
          return token2;
        }
      }
      def(src) {
        const cap = this.rules.block.def.exec(src);
        if (cap) {
          const tag2 = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, " ");
          const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "";
          const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : cap[3];
          return {
            type: "def",
            tag: tag2,
            raw: cap[0],
            href,
            title
          };
        }
      }
      table(src) {
        const cap = this.rules.block.table.exec(src);
        if (!cap) {
          return;
        }
        if (!this.rules.other.tableDelimiter.test(cap[2])) {
          return;
        }
        const headers = splitCells(cap[1]);
        const aligns = cap[2].replace(this.rules.other.tableAlignChars, "").split("|");
        const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, "").split("\n") : [];
        const item = {
          type: "table",
          raw: cap[0],
          header: [],
          align: [],
          rows: []
        };
        if (headers.length !== aligns.length) {
          return;
        }
        for (const align2 of aligns) {
          if (this.rules.other.tableAlignRight.test(align2)) {
            item.align.push("right");
          } else if (this.rules.other.tableAlignCenter.test(align2)) {
            item.align.push("center");
          } else if (this.rules.other.tableAlignLeft.test(align2)) {
            item.align.push("left");
          } else {
            item.align.push(null);
          }
        }
        for (let i = 0; i < headers.length; i++) {
          item.header.push({
            text: headers[i],
            tokens: this.lexer.inline(headers[i]),
            header: true,
            align: item.align[i]
          });
        }
        for (const row of rows) {
          item.rows.push(splitCells(row, item.header.length).map((cell, i) => {
            return {
              text: cell,
              tokens: this.lexer.inline(cell),
              header: false,
              align: item.align[i]
            };
          }));
        }
        return item;
      }
      lheading(src) {
        const cap = this.rules.block.lheading.exec(src);
        if (cap) {
          return {
            type: "heading",
            raw: cap[0],
            depth: cap[2].charAt(0) === "=" ? 1 : 2,
            text: cap[1],
            tokens: this.lexer.inline(cap[1])
          };
        }
      }
      paragraph(src) {
        const cap = this.rules.block.paragraph.exec(src);
        if (cap) {
          const text = cap[1].charAt(cap[1].length - 1) === "\n" ? cap[1].slice(0, -1) : cap[1];
          return {
            type: "paragraph",
            raw: cap[0],
            text,
            tokens: this.lexer.inline(text)
          };
        }
      }
      text(src) {
        const cap = this.rules.block.text.exec(src);
        if (cap) {
          return {
            type: "text",
            raw: cap[0],
            text: cap[0],
            tokens: this.lexer.inline(cap[0])
          };
        }
      }
      escape(src) {
        const cap = this.rules.inline.escape.exec(src);
        if (cap) {
          return {
            type: "escape",
            raw: cap[0],
            text: cap[1]
          };
        }
      }
      tag(src) {
        const cap = this.rules.inline.tag.exec(src);
        if (cap) {
          if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) {
            this.lexer.state.inLink = true;
          } else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) {
            this.lexer.state.inLink = false;
          }
          if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) {
            this.lexer.state.inRawBlock = true;
          } else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) {
            this.lexer.state.inRawBlock = false;
          }
          return {
            type: "html",
            raw: cap[0],
            inLink: this.lexer.state.inLink,
            inRawBlock: this.lexer.state.inRawBlock,
            block: false,
            text: cap[0]
          };
        }
      }
      link(src) {
        const cap = this.rules.inline.link.exec(src);
        if (cap) {
          const trimmedUrl = cap[2].trim();
          if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) {
            if (!this.rules.other.endAngleBracket.test(trimmedUrl)) {
              return;
            }
            const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), "\\");
            if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
              return;
            }
          } else {
            const lastParenIndex = findClosingBracket(cap[2], "()");
            if (lastParenIndex === -2) {
              return;
            }
            if (lastParenIndex > -1) {
              const start = cap[0].indexOf("!") === 0 ? 5 : 4;
              const linkLen = start + cap[1].length + lastParenIndex;
              cap[2] = cap[2].substring(0, lastParenIndex);
              cap[0] = cap[0].substring(0, linkLen).trim();
              cap[3] = "";
            }
          }
          let href = cap[2];
          let title = "";
          if (this.options.pedantic) {
            const link22 = this.rules.other.pedanticHrefTitle.exec(href);
            if (link22) {
              href = link22[1];
              title = link22[3];
            }
          } else {
            title = cap[3] ? cap[3].slice(1, -1) : "";
          }
          href = href.trim();
          if (this.rules.other.startAngleBracket.test(href)) {
            if (this.options.pedantic && !this.rules.other.endAngleBracket.test(trimmedUrl)) {
              href = href.slice(1);
            } else {
              href = href.slice(1, -1);
            }
          }
          return outputLink(cap, {
            href: href ? href.replace(this.rules.inline.anyPunctuation, "$1") : href,
            title: title ? title.replace(this.rules.inline.anyPunctuation, "$1") : title
          }, cap[0], this.lexer, this.rules);
        }
      }
      reflink(src, links) {
        let cap;
        if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) {
          const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, " ");
          const link22 = links[linkString.toLowerCase()];
          if (!link22) {
            const text = cap[0].charAt(0);
            return {
              type: "text",
              raw: text,
              text
            };
          }
          return outputLink(cap, link22, cap[0], this.lexer, this.rules);
        }
      }
      emStrong(src, maskedSrc, prevChar = "") {
        let match2 = this.rules.inline.emStrongLDelim.exec(src);
        if (!match2) return;
        if (match2[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric)) return;
        const nextChar = match2[1] || match2[2] || "";
        if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {
          const lLength = [...match2[0]].length - 1;
          let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;
          const endReg = match2[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
          endReg.lastIndex = 0;
          maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
          while ((match2 = endReg.exec(maskedSrc)) != null) {
            rDelim = match2[1] || match2[2] || match2[3] || match2[4] || match2[5] || match2[6];
            if (!rDelim) continue;
            rLength = [...rDelim].length;
            if (match2[3] || match2[4]) {
              delimTotal += rLength;
              continue;
            } else if (match2[5] || match2[6]) {
              if (lLength % 3 && !((lLength + rLength) % 3)) {
                midDelimTotal += rLength;
                continue;
              }
            }
            delimTotal -= rLength;
            if (delimTotal > 0) continue;
            rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);
            const lastCharLength = [...match2[0]][0].length;
            const raw2 = src.slice(0, lLength + match2.index + lastCharLength + rLength);
            if (Math.min(lLength, rLength) % 2) {
              const text2 = raw2.slice(1, -1);
              return {
                type: "em",
                raw: raw2,
                text: text2,
                tokens: this.lexer.inlineTokens(text2)
              };
            }
            const text = raw2.slice(2, -2);
            return {
              type: "strong",
              raw: raw2,
              text,
              tokens: this.lexer.inlineTokens(text)
            };
          }
        }
      }
      codespan(src) {
        const cap = this.rules.inline.code.exec(src);
        if (cap) {
          let text = cap[2].replace(this.rules.other.newLineCharGlobal, " ");
          const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text);
          const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text);
          if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
            text = text.substring(1, text.length - 1);
          }
          return {
            type: "codespan",
            raw: cap[0],
            text
          };
        }
      }
      br(src) {
        const cap = this.rules.inline.br.exec(src);
        if (cap) {
          return {
            type: "br",
            raw: cap[0]
          };
        }
      }
      del(src) {
        const cap = this.rules.inline.del.exec(src);
        if (cap) {
          return {
            type: "del",
            raw: cap[0],
            text: cap[2],
            tokens: this.lexer.inlineTokens(cap[2])
          };
        }
      }
      autolink(src) {
        const cap = this.rules.inline.autolink.exec(src);
        if (cap) {
          let text, href;
          if (cap[2] === "@") {
            text = cap[1];
            href = "mailto:" + text;
          } else {
            text = cap[1];
            href = text;
          }
          return {
            type: "link",
            raw: cap[0],
            text,
            href,
            tokens: [
              {
                type: "text",
                raw: text,
                text
              }
            ]
          };
        }
      }
      url(src) {
        let cap;
        if (cap = this.rules.inline.url.exec(src)) {
          let text, href;
          if (cap[2] === "@") {
            text = cap[0];
            href = "mailto:" + text;
          } else {
            let prevCapZero;
            do {
              prevCapZero = cap[0];
              cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? "";
            } while (prevCapZero !== cap[0]);
            text = cap[0];
            if (cap[1] === "www.") {
              href = "http://" + cap[0];
            } else {
              href = cap[0];
            }
          }
          return {
            type: "link",
            raw: cap[0],
            text,
            href,
            tokens: [
              {
                type: "text",
                raw: text,
                text
              }
            ]
          };
        }
      }
      inlineText(src) {
        const cap = this.rules.inline.text.exec(src);
        if (cap) {
          const escaped = this.lexer.state.inRawBlock;
          return {
            type: "text",
            raw: cap[0],
            text: cap[0],
            escaped
          };
        }
      }
    };
    _Lexer = class __Lexer {
      static {
        __name(this, "__Lexer");
      }
      tokens;
      options;
      state;
      tokenizer;
      inlineQueue;
      constructor(options2) {
        this.tokens = [];
        this.tokens.links = /* @__PURE__ */ Object.create(null);
        this.options = options2 || _defaults;
        this.options.tokenizer = this.options.tokenizer || new _Tokenizer();
        this.tokenizer = this.options.tokenizer;
        this.tokenizer.options = this.options;
        this.tokenizer.lexer = this;
        this.inlineQueue = [];
        this.state = {
          inLink: false,
          inRawBlock: false,
          top: true
        };
        const rules = {
          other,
          block: block.normal,
          inline: inline.normal
        };
        if (this.options.pedantic) {
          rules.block = block.pedantic;
          rules.inline = inline.pedantic;
        } else if (this.options.gfm) {
          rules.block = block.gfm;
          if (this.options.breaks) {
            rules.inline = inline.breaks;
          } else {
            rules.inline = inline.gfm;
          }
        }
        this.tokenizer.rules = rules;
      }
      /**
       * Expose Rules
       */
      static get rules() {
        return {
          block,
          inline
        };
      }
      /**
       * Static Lex Method
       */
      static lex(src, options2) {
        const lexer2 = new __Lexer(options2);
        return lexer2.lex(src);
      }
      /**
       * Static Lex Inline Method
       */
      static lexInline(src, options2) {
        const lexer2 = new __Lexer(options2);
        return lexer2.inlineTokens(src);
      }
      /**
       * Preprocessing
       */
      lex(src) {
        src = src.replace(other.carriageReturn, "\n");
        this.blockTokens(src, this.tokens);
        for (let i = 0; i < this.inlineQueue.length; i++) {
          const next = this.inlineQueue[i];
          this.inlineTokens(next.src, next.tokens);
        }
        this.inlineQueue = [];
        return this.tokens;
      }
      blockTokens(src, tokens = [], lastParagraphClipped = false) {
        if (this.options.pedantic) {
          src = src.replace(other.tabCharGlobal, "    ").replace(other.spaceLine, "");
        }
        while (src) {
          let token2;
          if (this.options.extensions?.block?.some((extTokenizer) => {
            if (token2 = extTokenizer.call({ lexer: this }, src, tokens)) {
              src = src.substring(token2.raw.length);
              tokens.push(token2);
              return true;
            }
            return false;
          })) {
            continue;
          }
          if (token2 = this.tokenizer.space(src)) {
            src = src.substring(token2.raw.length);
            const lastToken = tokens.at(-1);
            if (token2.raw.length === 1 && lastToken !== void 0) {
              lastToken.raw += "\n";
            } else {
              tokens.push(token2);
            }
            continue;
          }
          if (token2 = this.tokenizer.code(src)) {
            src = src.substring(token2.raw.length);
            const lastToken = tokens.at(-1);
            if (lastToken?.type === "paragraph" || lastToken?.type === "text") {
              lastToken.raw += "\n" + token2.raw;
              lastToken.text += "\n" + token2.text;
              this.inlineQueue.at(-1).src = lastToken.text;
            } else {
              tokens.push(token2);
            }
            continue;
          }
          if (token2 = this.tokenizer.fences(src)) {
            src = src.substring(token2.raw.length);
            tokens.push(token2);
            continue;
          }
          if (token2 = this.tokenizer.heading(src)) {
            src = src.substring(token2.raw.length);
            tokens.push(token2);
            continue;
          }
          if (token2 = this.tokenizer.hr(src)) {
            src = src.substring(token2.raw.length);
            tokens.push(token2);
            continue;
          }
          if (token2 = this.tokenizer.blockquote(src)) {
            src = src.substring(token2.raw.length);
            tokens.push(token2);
            continue;
          }
          if (token2 = this.tokenizer.list(src)) {
            src = src.substring(token2.raw.length);
            tokens.push(token2);
            continue;
          }
          if (token2 = this.tokenizer.html(src)) {
            src = src.substring(token2.raw.length);
            tokens.push(token2);
            continue;
          }
          if (token2 = this.tokenizer.def(src)) {
            src = src.substring(token2.raw.length);
            const lastToken = tokens.at(-1);
            if (lastToken?.type === "paragraph" || lastToken?.type === "text") {
              lastToken.raw += "\n" + token2.raw;
              lastToken.text += "\n" + token2.raw;
              this.inlineQueue.at(-1).src = lastToken.text;
            } else if (!this.tokens.links[token2.tag]) {
              this.tokens.links[token2.tag] = {
                href: token2.href,
                title: token2.title
              };
            }
            continue;
          }
          if (token2 = this.tokenizer.table(src)) {
            src = src.substring(token2.raw.length);
            tokens.push(token2);
            continue;
          }
          if (token2 = this.tokenizer.lheading(src)) {
            src = src.substring(token2.raw.length);
            tokens.push(token2);
            continue;
          }
          let cutSrc = src;
          if (this.options.extensions?.startBlock) {
            let startIndex = Infinity;
            const tempSrc = src.slice(1);
            let tempStart;
            this.options.extensions.startBlock.forEach((getStartIndex) => {
              tempStart = getStartIndex.call({ lexer: this }, tempSrc);
              if (typeof tempStart === "number" && tempStart >= 0) {
                startIndex = Math.min(startIndex, tempStart);
              }
            });
            if (startIndex < Infinity && startIndex >= 0) {
              cutSrc = src.substring(0, startIndex + 1);
            }
          }
          if (this.state.top && (token2 = this.tokenizer.paragraph(cutSrc))) {
            const lastToken = tokens.at(-1);
            if (lastParagraphClipped && lastToken?.type === "paragraph") {
              lastToken.raw += "\n" + token2.raw;
              lastToken.text += "\n" + token2.text;
              this.inlineQueue.pop();
              this.inlineQueue.at(-1).src = lastToken.text;
            } else {
              tokens.push(token2);
            }
            lastParagraphClipped = cutSrc.length !== src.length;
            src = src.substring(token2.raw.length);
            continue;
          }
          if (token2 = this.tokenizer.text(src)) {
            src = src.substring(token2.raw.length);
            const lastToken = tokens.at(-1);
            if (lastToken?.type === "text") {
              lastToken.raw += "\n" + token2.raw;
              lastToken.text += "\n" + token2.text;
              this.inlineQueue.pop();
              this.inlineQueue.at(-1).src = lastToken.text;
            } else {
              tokens.push(token2);
            }
            continue;
          }
          if (src) {
            const errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
            if (this.options.silent) {
              console.error(errMsg);
              break;
            } else {
              throw new Error(errMsg);
            }
          }
        }
        this.state.top = true;
        return tokens;
      }
      inline(src, tokens = []) {
        this.inlineQueue.push({ src, tokens });
        return tokens;
      }
      /**
       * Lexing/Compiling
       */
      inlineTokens(src, tokens = []) {
        let maskedSrc = src;
        let match2 = null;
        if (this.tokens.links) {
          const links = Object.keys(this.tokens.links);
          if (links.length > 0) {
            while ((match2 = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
              if (links.includes(match2[0].slice(match2[0].lastIndexOf("[") + 1, -1))) {
                maskedSrc = maskedSrc.slice(0, match2.index) + "[" + "a".repeat(match2[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
              }
            }
          }
        }
        while ((match2 = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {
          maskedSrc = maskedSrc.slice(0, match2.index) + "++" + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
        }
        while ((match2 = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
          maskedSrc = maskedSrc.slice(0, match2.index) + "[" + "a".repeat(match2[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
        }
        let keepPrevChar = false;
        let prevChar = "";
        while (src) {
          if (!keepPrevChar) {
            prevChar = "";
          }
          keepPrevChar = false;
          let token2;
          if (this.options.extensions?.inline?.some((extTokenizer) => {
            if (token2 = extTokenizer.call({ lexer: this }, src, tokens)) {
              src = src.substring(token2.raw.length);
              tokens.push(token2);
              return true;
            }
            return false;
          })) {
            continue;
          }
          if (token2 = this.tokenizer.escape(src)) {
            src = src.substring(token2.raw.length);
            tokens.push(token2);
            continue;
          }
          if (token2 = this.tokenizer.tag(src)) {
            src = src.substring(token2.raw.length);
            tokens.push(token2);
            continue;
          }
          if (token2 = this.tokenizer.link(src)) {
            src = src.substring(token2.raw.length);
            tokens.push(token2);
            continue;
          }
          if (token2 = this.tokenizer.reflink(src, this.tokens.links)) {
            src = src.substring(token2.raw.length);
            const lastToken = tokens.at(-1);
            if (token2.type === "text" && lastToken?.type === "text") {
              lastToken.raw += token2.raw;
              lastToken.text += token2.text;
            } else {
              tokens.push(token2);
            }
            continue;
          }
          if (token2 = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {
            src = src.substring(token2.raw.length);
            tokens.push(token2);
            continue;
          }
          if (token2 = this.tokenizer.codespan(src)) {
            src = src.substring(token2.raw.length);
            tokens.push(token2);
            continue;
          }
          if (token2 = this.tokenizer.br(src)) {
            src = src.substring(token2.raw.length);
            tokens.push(token2);
            continue;
          }
          if (token2 = this.tokenizer.del(src)) {
            src = src.substring(token2.raw.length);
            tokens.push(token2);
            continue;
          }
          if (token2 = this.tokenizer.autolink(src)) {
            src = src.substring(token2.raw.length);
            tokens.push(token2);
            continue;
          }
          if (!this.state.inLink && (token2 = this.tokenizer.url(src))) {
            src = src.substring(token2.raw.length);
            tokens.push(token2);
            continue;
          }
          let cutSrc = src;
          if (this.options.extensions?.startInline) {
            let startIndex = Infinity;
            const tempSrc = src.slice(1);
            let tempStart;
            this.options.extensions.startInline.forEach((getStartIndex) => {
              tempStart = getStartIndex.call({ lexer: this }, tempSrc);
              if (typeof tempStart === "number" && tempStart >= 0) {
                startIndex = Math.min(startIndex, tempStart);
              }
            });
            if (startIndex < Infinity && startIndex >= 0) {
              cutSrc = src.substring(0, startIndex + 1);
            }
          }
          if (token2 = this.tokenizer.inlineText(cutSrc)) {
            src = src.substring(token2.raw.length);
            if (token2.raw.slice(-1) !== "_") {
              prevChar = token2.raw.slice(-1);
            }
            keepPrevChar = true;
            const lastToken = tokens.at(-1);
            if (lastToken?.type === "text") {
              lastToken.raw += token2.raw;
              lastToken.text += token2.text;
            } else {
              tokens.push(token2);
            }
            continue;
          }
          if (src) {
            const errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
            if (this.options.silent) {
              console.error(errMsg);
              break;
            } else {
              throw new Error(errMsg);
            }
          }
        }
        return tokens;
      }
    };
    _Renderer = class {
      static {
        __name(this, "_Renderer");
      }
      options;
      parser;
      // set by the parser
      constructor(options2) {
        this.options = options2 || _defaults;
      }
      space(token2) {
        return "";
      }
      code({ text, lang, escaped }) {
        const langString = (lang || "").match(other.notSpaceStart)?.[0];
        const code2 = text.replace(other.endingNewline, "") + "\n";
        if (!langString) {
          return "<pre><code>" + (escaped ? code2 : escape22(code2, true)) + "</code></pre>\n";
        }
        return '<pre><code class="language-' + escape22(langString) + '">' + (escaped ? code2 : escape22(code2, true)) + "</code></pre>\n";
      }
      blockquote({ tokens }) {
        const body = this.parser.parse(tokens);
        return `<blockquote>
${body}</blockquote>
`;
      }
      html({ text }) {
        return text;
      }
      heading({ tokens, depth }) {
        return `<h${depth}>${this.parser.parseInline(tokens)}</h${depth}>
`;
      }
      hr(token2) {
        return "<hr>\n";
      }
      list(token2) {
        const ordered = token2.ordered;
        const start = token2.start;
        let body = "";
        for (let j = 0; j < token2.items.length; j++) {
          const item = token2.items[j];
          body += this.listitem(item);
        }
        const type = ordered ? "ol" : "ul";
        const startAttr = ordered && start !== 1 ? ' start="' + start + '"' : "";
        return "<" + type + startAttr + ">\n" + body + "</" + type + ">\n";
      }
      listitem(item) {
        let itemBody = "";
        if (item.task) {
          const checkbox = this.checkbox({ checked: !!item.checked });
          if (item.loose) {
            if (item.tokens[0]?.type === "paragraph") {
              item.tokens[0].text = checkbox + " " + item.tokens[0].text;
              if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === "text") {
                item.tokens[0].tokens[0].text = checkbox + " " + escape22(item.tokens[0].tokens[0].text);
                item.tokens[0].tokens[0].escaped = true;
              }
            } else {
              item.tokens.unshift({
                type: "text",
                raw: checkbox + " ",
                text: checkbox + " ",
                escaped: true
              });
            }
          } else {
            itemBody += checkbox + " ";
          }
        }
        itemBody += this.parser.parse(item.tokens, !!item.loose);
        return `<li>${itemBody}</li>
`;
      }
      checkbox({ checked }) {
        return "<input " + (checked ? 'checked="" ' : "") + 'disabled="" type="checkbox">';
      }
      paragraph({ tokens }) {
        return `<p>${this.parser.parseInline(tokens)}</p>
`;
      }
      table(token2) {
        let header = "";
        let cell = "";
        for (let j = 0; j < token2.header.length; j++) {
          cell += this.tablecell(token2.header[j]);
        }
        header += this.tablerow({ text: cell });
        let body = "";
        for (let j = 0; j < token2.rows.length; j++) {
          const row = token2.rows[j];
          cell = "";
          for (let k = 0; k < row.length; k++) {
            cell += this.tablecell(row[k]);
          }
          body += this.tablerow({ text: cell });
        }
        if (body) body = `<tbody>${body}</tbody>`;
        return "<table>\n<thead>\n" + header + "</thead>\n" + body + "</table>\n";
      }
      tablerow({ text }) {
        return `<tr>
${text}</tr>
`;
      }
      tablecell(token2) {
        const content = this.parser.parseInline(token2.tokens);
        const type = token2.header ? "th" : "td";
        const tag2 = token2.align ? `<${type} align="${token2.align}">` : `<${type}>`;
        return tag2 + content + `</${type}>
`;
      }
      /**
       * span level renderer
       */
      strong({ tokens }) {
        return `<strong>${this.parser.parseInline(tokens)}</strong>`;
      }
      em({ tokens }) {
        return `<em>${this.parser.parseInline(tokens)}</em>`;
      }
      codespan({ text }) {
        return `<code>${escape22(text, true)}</code>`;
      }
      br(token2) {
        return "<br>";
      }
      del({ tokens }) {
        return `<del>${this.parser.parseInline(tokens)}</del>`;
      }
      link({ href, title, tokens }) {
        const text = this.parser.parseInline(tokens);
        const cleanHref = cleanUrl(href);
        if (cleanHref === null) {
          return text;
        }
        href = cleanHref;
        let out = '<a href="' + href + '"';
        if (title) {
          out += ' title="' + escape22(title) + '"';
        }
        out += ">" + text + "</a>";
        return out;
      }
      image({ href, title, text, tokens }) {
        if (tokens) {
          text = this.parser.parseInline(tokens, this.parser.textRenderer);
        }
        const cleanHref = cleanUrl(href);
        if (cleanHref === null) {
          return escape22(text);
        }
        href = cleanHref;
        let out = `<img src="${href}" alt="${text}"`;
        if (title) {
          out += ` title="${escape22(title)}"`;
        }
        out += ">";
        return out;
      }
      text(token2) {
        return "tokens" in token2 && token2.tokens ? this.parser.parseInline(token2.tokens) : "escaped" in token2 && token2.escaped ? token2.text : escape22(token2.text);
      }
    };
    _TextRenderer = class {
      static {
        __name(this, "_TextRenderer");
      }
      // no need for block level renderers
      strong({ text }) {
        return text;
      }
      em({ text }) {
        return text;
      }
      codespan({ text }) {
        return text;
      }
      del({ text }) {
        return text;
      }
      html({ text }) {
        return text;
      }
      text({ text }) {
        return text;
      }
      link({ text }) {
        return "" + text;
      }
      image({ text }) {
        return "" + text;
      }
      br() {
        return "";
      }
    };
    _Parser = class __Parser {
      static {
        __name(this, "__Parser");
      }
      options;
      renderer;
      textRenderer;
      constructor(options2) {
        this.options = options2 || _defaults;
        this.options.renderer = this.options.renderer || new _Renderer();
        this.renderer = this.options.renderer;
        this.renderer.options = this.options;
        this.renderer.parser = this;
        this.textRenderer = new _TextRenderer();
      }
      /**
       * Static Parse Method
       */
      static parse(tokens, options2) {
        const parser22 = new __Parser(options2);
        return parser22.parse(tokens);
      }
      /**
       * Static Parse Inline Method
       */
      static parseInline(tokens, options2) {
        const parser22 = new __Parser(options2);
        return parser22.parseInline(tokens);
      }
      /**
       * Parse Loop
       */
      parse(tokens, top2 = true) {
        let out = "";
        for (let i = 0; i < tokens.length; i++) {
          const anyToken = tokens[i];
          if (this.options.extensions?.renderers?.[anyToken.type]) {
            const genericToken = anyToken;
            const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);
            if (ret !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "paragraph", "text"].includes(genericToken.type)) {
              out += ret || "";
              continue;
            }
          }
          const token2 = anyToken;
          switch (token2.type) {
            case "space": {
              out += this.renderer.space(token2);
              continue;
            }
            case "hr": {
              out += this.renderer.hr(token2);
              continue;
            }
            case "heading": {
              out += this.renderer.heading(token2);
              continue;
            }
            case "code": {
              out += this.renderer.code(token2);
              continue;
            }
            case "table": {
              out += this.renderer.table(token2);
              continue;
            }
            case "blockquote": {
              out += this.renderer.blockquote(token2);
              continue;
            }
            case "list": {
              out += this.renderer.list(token2);
              continue;
            }
            case "html": {
              out += this.renderer.html(token2);
              continue;
            }
            case "paragraph": {
              out += this.renderer.paragraph(token2);
              continue;
            }
            case "text": {
              let textToken = token2;
              let body = this.renderer.text(textToken);
              while (i + 1 < tokens.length && tokens[i + 1].type === "text") {
                textToken = tokens[++i];
                body += "\n" + this.renderer.text(textToken);
              }
              if (top2) {
                out += this.renderer.paragraph({
                  type: "paragraph",
                  raw: body,
                  text: body,
                  tokens: [{ type: "text", raw: body, text: body, escaped: true }]
                });
              } else {
                out += body;
              }
              continue;
            }
            default: {
              const errMsg = 'Token with "' + token2.type + '" type was not found.';
              if (this.options.silent) {
                console.error(errMsg);
                return "";
              } else {
                throw new Error(errMsg);
              }
            }
          }
        }
        return out;
      }
      /**
       * Parse Inline Tokens
       */
      parseInline(tokens, renderer2 = this.renderer) {
        let out = "";
        for (let i = 0; i < tokens.length; i++) {
          const anyToken = tokens[i];
          if (this.options.extensions?.renderers?.[anyToken.type]) {
            const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);
            if (ret !== false || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(anyToken.type)) {
              out += ret || "";
              continue;
            }
          }
          const token2 = anyToken;
          switch (token2.type) {
            case "escape": {
              out += renderer2.text(token2);
              break;
            }
            case "html": {
              out += renderer2.html(token2);
              break;
            }
            case "link": {
              out += renderer2.link(token2);
              break;
            }
            case "image": {
              out += renderer2.image(token2);
              break;
            }
            case "strong": {
              out += renderer2.strong(token2);
              break;
            }
            case "em": {
              out += renderer2.em(token2);
              break;
            }
            case "codespan": {
              out += renderer2.codespan(token2);
              break;
            }
            case "br": {
              out += renderer2.br(token2);
              break;
            }
            case "del": {
              out += renderer2.del(token2);
              break;
            }
            case "text": {
              out += renderer2.text(token2);
              break;
            }
            default: {
              const errMsg = 'Token with "' + token2.type + '" type was not found.';
              if (this.options.silent) {
                console.error(errMsg);
                return "";
              } else {
                throw new Error(errMsg);
              }
            }
          }
        }
        return out;
      }
    };
    _Hooks = class {
      static {
        __name(this, "_Hooks");
      }
      options;
      block;
      constructor(options2) {
        this.options = options2 || _defaults;
      }
      static passThroughHooks = /* @__PURE__ */ new Set([
        "preprocess",
        "postprocess",
        "processAllTokens"
      ]);
      /**
       * Process markdown before marked
       */
      preprocess(markdown2) {
        return markdown2;
      }
      /**
       * Process HTML after marked is finished
       */
      postprocess(html2) {
        return html2;
      }
      /**
       * Process all tokens before walk tokens
       */
      processAllTokens(tokens) {
        return tokens;
      }
      /**
       * Provide function to tokenize markdown
       */
      provideLexer() {
        return this.block ? _Lexer.lex : _Lexer.lexInline;
      }
      /**
       * Provide function to parse tokens
       */
      provideParser() {
        return this.block ? _Parser.parse : _Parser.parseInline;
      }
    };
    Marked = class {
      static {
        __name(this, "Marked");
      }
      defaults = _getDefaults();
      options = this.setOptions;
      parse = this.parseMarkdown(true);
      parseInline = this.parseMarkdown(false);
      Parser = _Parser;
      Renderer = _Renderer;
      TextRenderer = _TextRenderer;
      Lexer = _Lexer;
      Tokenizer = _Tokenizer;
      Hooks = _Hooks;
      constructor(...args) {
        this.use(...args);
      }
      /**
       * Run callback for every token
       */
      walkTokens(tokens, callback) {
        let values = [];
        for (const token2 of tokens) {
          values = values.concat(callback.call(this, token2));
          switch (token2.type) {
            case "table": {
              const tableToken = token2;
              for (const cell of tableToken.header) {
                values = values.concat(this.walkTokens(cell.tokens, callback));
              }
              for (const row of tableToken.rows) {
                for (const cell of row) {
                  values = values.concat(this.walkTokens(cell.tokens, callback));
                }
              }
              break;
            }
            case "list": {
              const listToken = token2;
              values = values.concat(this.walkTokens(listToken.items, callback));
              break;
            }
            default: {
              const genericToken = token2;
              if (this.defaults.extensions?.childTokens?.[genericToken.type]) {
                this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {
                  const tokens2 = genericToken[childTokens].flat(Infinity);
                  values = values.concat(this.walkTokens(tokens2, callback));
                });
              } else if (genericToken.tokens) {
                values = values.concat(this.walkTokens(genericToken.tokens, callback));
              }
            }
          }
        }
        return values;
      }
      use(...args) {
        const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };
        args.forEach((pack) => {
          const opts = { ...pack };
          opts.async = this.defaults.async || opts.async || false;
          if (pack.extensions) {
            pack.extensions.forEach((ext2) => {
              if (!ext2.name) {
                throw new Error("extension name required");
              }
              if ("renderer" in ext2) {
                const prevRenderer = extensions.renderers[ext2.name];
                if (prevRenderer) {
                  extensions.renderers[ext2.name] = function(...args2) {
                    let ret = ext2.renderer.apply(this, args2);
                    if (ret === false) {
                      ret = prevRenderer.apply(this, args2);
                    }
                    return ret;
                  };
                } else {
                  extensions.renderers[ext2.name] = ext2.renderer;
                }
              }
              if ("tokenizer" in ext2) {
                if (!ext2.level || ext2.level !== "block" && ext2.level !== "inline") {
                  throw new Error("extension level must be 'block' or 'inline'");
                }
                const extLevel = extensions[ext2.level];
                if (extLevel) {
                  extLevel.unshift(ext2.tokenizer);
                } else {
                  extensions[ext2.level] = [ext2.tokenizer];
                }
                if (ext2.start) {
                  if (ext2.level === "block") {
                    if (extensions.startBlock) {
                      extensions.startBlock.push(ext2.start);
                    } else {
                      extensions.startBlock = [ext2.start];
                    }
                  } else if (ext2.level === "inline") {
                    if (extensions.startInline) {
                      extensions.startInline.push(ext2.start);
                    } else {
                      extensions.startInline = [ext2.start];
                    }
                  }
                }
              }
              if ("childTokens" in ext2 && ext2.childTokens) {
                extensions.childTokens[ext2.name] = ext2.childTokens;
              }
            });
            opts.extensions = extensions;
          }
          if (pack.renderer) {
            const renderer2 = this.defaults.renderer || new _Renderer(this.defaults);
            for (const prop in pack.renderer) {
              if (!(prop in renderer2)) {
                throw new Error(`renderer '${prop}' does not exist`);
              }
              if (["options", "parser"].includes(prop)) {
                continue;
              }
              const rendererProp = prop;
              const rendererFunc = pack.renderer[rendererProp];
              const prevRenderer = renderer2[rendererProp];
              renderer2[rendererProp] = (...args2) => {
                let ret = rendererFunc.apply(renderer2, args2);
                if (ret === false) {
                  ret = prevRenderer.apply(renderer2, args2);
                }
                return ret || "";
              };
            }
            opts.renderer = renderer2;
          }
          if (pack.tokenizer) {
            const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);
            for (const prop in pack.tokenizer) {
              if (!(prop in tokenizer)) {
                throw new Error(`tokenizer '${prop}' does not exist`);
              }
              if (["options", "rules", "lexer"].includes(prop)) {
                continue;
              }
              const tokenizerProp = prop;
              const tokenizerFunc = pack.tokenizer[tokenizerProp];
              const prevTokenizer = tokenizer[tokenizerProp];
              tokenizer[tokenizerProp] = (...args2) => {
                let ret = tokenizerFunc.apply(tokenizer, args2);
                if (ret === false) {
                  ret = prevTokenizer.apply(tokenizer, args2);
                }
                return ret;
              };
            }
            opts.tokenizer = tokenizer;
          }
          if (pack.hooks) {
            const hooks = this.defaults.hooks || new _Hooks();
            for (const prop in pack.hooks) {
              if (!(prop in hooks)) {
                throw new Error(`hook '${prop}' does not exist`);
              }
              if (["options", "block"].includes(prop)) {
                continue;
              }
              const hooksProp = prop;
              const hooksFunc = pack.hooks[hooksProp];
              const prevHook = hooks[hooksProp];
              if (_Hooks.passThroughHooks.has(prop)) {
                hooks[hooksProp] = (arg) => {
                  if (this.defaults.async) {
                    return Promise.resolve(hooksFunc.call(hooks, arg)).then((ret2) => {
                      return prevHook.call(hooks, ret2);
                    });
                  }
                  const ret = hooksFunc.call(hooks, arg);
                  return prevHook.call(hooks, ret);
                };
              } else {
                hooks[hooksProp] = (...args2) => {
                  let ret = hooksFunc.apply(hooks, args2);
                  if (ret === false) {
                    ret = prevHook.apply(hooks, args2);
                  }
                  return ret;
                };
              }
            }
            opts.hooks = hooks;
          }
          if (pack.walkTokens) {
            const walkTokens2 = this.defaults.walkTokens;
            const packWalktokens = pack.walkTokens;
            opts.walkTokens = function(token2) {
              let values = [];
              values.push(packWalktokens.call(this, token2));
              if (walkTokens2) {
                values = values.concat(walkTokens2.call(this, token2));
              }
              return values;
            };
          }
          this.defaults = { ...this.defaults, ...opts };
        });
        return this;
      }
      setOptions(opt) {
        this.defaults = { ...this.defaults, ...opt };
        return this;
      }
      lexer(src, options2) {
        return _Lexer.lex(src, options2 ?? this.defaults);
      }
      parser(tokens, options2) {
        return _Parser.parse(tokens, options2 ?? this.defaults);
      }
      parseMarkdown(blockType) {
        const parse22 = /* @__PURE__ */ __name((src, options2) => {
          const origOpt = { ...options2 };
          const opt = { ...this.defaults, ...origOpt };
          const throwError = this.onError(!!opt.silent, !!opt.async);
          if (this.defaults.async === true && origOpt.async === false) {
            return throwError(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));
          }
          if (typeof src === "undefined" || src === null) {
            return throwError(new Error("marked(): input parameter is undefined or null"));
          }
          if (typeof src !== "string") {
            return throwError(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(src) + ", string expected"));
          }
          if (opt.hooks) {
            opt.hooks.options = opt;
            opt.hooks.block = blockType;
          }
          const lexer2 = opt.hooks ? opt.hooks.provideLexer() : blockType ? _Lexer.lex : _Lexer.lexInline;
          const parser22 = opt.hooks ? opt.hooks.provideParser() : blockType ? _Parser.parse : _Parser.parseInline;
          if (opt.async) {
            return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src).then((src2) => lexer2(src2, opt)).then((tokens) => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens).then((tokens) => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens).then((tokens) => parser22(tokens, opt)).then((html2) => opt.hooks ? opt.hooks.postprocess(html2) : html2).catch(throwError);
          }
          try {
            if (opt.hooks) {
              src = opt.hooks.preprocess(src);
            }
            let tokens = lexer2(src, opt);
            if (opt.hooks) {
              tokens = opt.hooks.processAllTokens(tokens);
            }
            if (opt.walkTokens) {
              this.walkTokens(tokens, opt.walkTokens);
            }
            let html2 = parser22(tokens, opt);
            if (opt.hooks) {
              html2 = opt.hooks.postprocess(html2);
            }
            return html2;
          } catch (e2) {
            return throwError(e2);
          }
        }, "parse2");
        return parse22;
      }
      onError(silent, async) {
        return (e2) => {
          e2.message += "\nPlease report this to https://github.com/markedjs/marked.";
          if (silent) {
            const msg = "<p>An error occurred:</p><pre>" + escape22(e2.message + "", true) + "</pre>";
            if (async) {
              return Promise.resolve(msg);
            }
            return msg;
          }
          if (async) {
            return Promise.reject(e2);
          }
          throw e2;
        };
      }
    };
    markedInstance = new Marked();
    __name(marked, "marked");
    marked.options = marked.setOptions = function(options2) {
      markedInstance.setOptions(options2);
      marked.defaults = markedInstance.defaults;
      changeDefaults(marked.defaults);
      return marked;
    };
    marked.getDefaults = _getDefaults;
    marked.defaults = _defaults;
    marked.use = function(...args) {
      markedInstance.use(...args);
      marked.defaults = markedInstance.defaults;
      changeDefaults(marked.defaults);
      return marked;
    };
    marked.walkTokens = function(tokens, callback) {
      return markedInstance.walkTokens(tokens, callback);
    };
    marked.parseInline = markedInstance.parseInline;
    marked.Parser = _Parser;
    marked.parser = _Parser.parse;
    marked.Renderer = _Renderer;
    marked.TextRenderer = _TextRenderer;
    marked.Lexer = _Lexer;
    marked.lexer = _Lexer.lex;
    marked.Tokenizer = _Tokenizer;
    marked.Hooks = _Hooks;
    marked.parse = marked;
    options = marked.options;
    setOptions = marked.setOptions;
    use = marked.use;
    walkTokens = marked.walkTokens;
    parseInline = marked.parseInline;
    parser4 = _Parser.parse;
    lexer = _Lexer.lex;
  }
});

// packages/core/dist/src/utils/memoryImportProcessor.js
import * as fs46 from "node:fs/promises";
import * as path51 from "node:path";
async function findProjectRoot(startDir) {
  let currentDir = path51.resolve(startDir);
  while (true) {
    const gitPath = path51.join(currentDir, ".git");
    try {
      const stats = await fs46.lstat(gitPath);
      if (stats.isDirectory()) {
        return currentDir;
      }
    } catch {
    }
    const parentDir = path51.dirname(currentDir);
    if (parentDir === currentDir) {
      break;
    }
    currentDir = parentDir;
  }
  return path51.resolve(startDir);
}
function hasMessage(err) {
  return typeof err === "object" && err !== null && "message" in err && typeof err.message === "string";
}
function findImports(content) {
  const imports = [];
  let i = 0;
  const len = content.length;
  while (i < len) {
    i = content.indexOf("@", i);
    if (i === -1)
      break;
    if (i > 0 && !isWhitespace3(content[i - 1])) {
      i++;
      continue;
    }
    let j = i + 1;
    while (j < len && !isWhitespace3(content[j]) && content[j] !== "\n" && content[j] !== "\r") {
      j++;
    }
    const importPath = content.slice(i + 1, j);
    if (importPath.length > 0 && (importPath[0] === "." || importPath[0] === "/" || isLetter(importPath[0]))) {
      imports.push({
        start: i,
        _end: j,
        path: importPath
      });
    }
    i = j + 1;
  }
  return imports;
}
function isWhitespace3(char) {
  return char === " " || char === "	" || char === "\n" || char === "\r";
}
function isLetter(char) {
  const code2 = char.charCodeAt(0);
  return code2 >= 65 && code2 <= 90 || // A-Z
  code2 >= 97 && code2 <= 122;
}
function findCodeRegions(content) {
  const regions = [];
  const tokens = marked.lexer(content);
  let offset = 0;
  function walk(token2, baseOffset) {
    if (token2.type === "code" || token2.type === "codespan") {
      regions.push([baseOffset, baseOffset + token2.raw.length]);
    }
    if ("tokens" in token2 && token2.tokens) {
      let childOffset = 0;
      for (const child of token2.tokens) {
        const childIndexInParent = token2.raw.indexOf(child.raw, childOffset);
        if (childIndexInParent === -1) {
          logger3.error(`Could not find child token in parent raw content. Aborting parsing for this branch. Child raw: "${child.raw}"`);
          break;
        }
        walk(child, baseOffset + childIndexInParent);
        childOffset = childIndexInParent + child.raw.length;
      }
    }
  }
  __name(walk, "walk");
  for (const token2 of tokens) {
    walk(token2, offset);
    offset += token2.raw.length;
  }
  return regions;
}
async function processImports(content, basePath, debugMode = false, importState = {
  processedFiles: /* @__PURE__ */ new Set(),
  maxDepth: 5,
  currentDepth: 0
}, projectRoot, importFormat = "tree") {
  if (!projectRoot) {
    projectRoot = await findProjectRoot(basePath);
  }
  if (importState.currentDepth >= importState.maxDepth) {
    if (debugMode) {
      logger3.warn(`Maximum import depth (${importState.maxDepth}) reached. Stopping import processing.`);
    }
    return {
      content,
      importTree: { path: importState.currentFile || "unknown" }
    };
  }
  if (importFormat === "flat") {
    const flatFiles = [];
    const processedFiles = /* @__PURE__ */ new Set();
    async function processFlat(fileContent, fileBasePath, filePath, depth) {
      const normalizedPath = path51.normalize(filePath);
      if (processedFiles.has(normalizedPath))
        return;
      processedFiles.add(normalizedPath);
      flatFiles.push({ path: normalizedPath, content: fileContent });
      const codeRegions2 = findCodeRegions(fileContent);
      const imports2 = findImports(fileContent);
      for (let i = imports2.length - 1; i >= 0; i--) {
        const { start, path: importPath } = imports2[i];
        if (codeRegions2.some(([regionStart, regionEnd]) => start >= regionStart && start < regionEnd)) {
          continue;
        }
        if (!validateImportPath(importPath, fileBasePath, [projectRoot || ""])) {
          continue;
        }
        const fullPath = path51.resolve(fileBasePath, importPath);
        const normalizedFullPath = path51.normalize(fullPath);
        if (processedFiles.has(normalizedFullPath))
          continue;
        try {
          await fs46.access(fullPath);
          const importedContent = await fs46.readFile(fullPath, "utf-8");
          await processFlat(importedContent, path51.dirname(fullPath), normalizedFullPath, depth + 1);
        } catch (error) {
          if (debugMode) {
            logger3.warn(`Failed to import ${fullPath}: ${hasMessage(error) ? error.message : "Unknown error"}`);
          }
        }
      }
    }
    __name(processFlat, "processFlat");
    const rootPath = path51.normalize(importState.currentFile || path51.resolve(basePath));
    await processFlat(content, basePath, rootPath, 0);
    const flatContent = flatFiles.map((f) => `--- File: ${f.path} ---
${f.content.trim()}
--- End of File: ${f.path} ---`).join("\n\n");
    return {
      content: flatContent,
      importTree: { path: rootPath }
      // Tree not meaningful in flat mode
    };
  }
  const codeRegions = findCodeRegions(content);
  let result = "";
  let lastIndex = 0;
  const imports = [];
  const importsList = findImports(content);
  for (const { start, _end, path: importPath } of importsList) {
    result += content.substring(lastIndex, start);
    lastIndex = _end;
    if (codeRegions.some(([s2, e2]) => start >= s2 && start < e2)) {
      result += `@${importPath}`;
      continue;
    }
    if (!validateImportPath(importPath, basePath, [projectRoot || ""])) {
      result += `<!-- Import failed: ${importPath} - Path traversal attempt -->`;
      continue;
    }
    const fullPath = path51.resolve(basePath, importPath);
    if (importState.processedFiles.has(fullPath)) {
      result += `<!-- File already processed: ${importPath} -->`;
      continue;
    }
    try {
      await fs46.access(fullPath);
      const fileContent = await fs46.readFile(fullPath, "utf-8");
      const newImportState = {
        ...importState,
        processedFiles: new Set(importState.processedFiles),
        currentDepth: importState.currentDepth + 1,
        currentFile: fullPath
      };
      newImportState.processedFiles.add(fullPath);
      const imported = await processImports(fileContent, path51.dirname(fullPath), debugMode, newImportState, projectRoot, importFormat);
      result += `<!-- Imported from: ${importPath} -->
${imported.content}
<!-- End of import from: ${importPath} -->`;
      imports.push(imported.importTree);
    } catch (err) {
      let message = "Unknown error";
      if (hasMessage(err)) {
        message = err.message;
      } else if (typeof err === "string") {
        message = err;
      }
      logger3.error(`Failed to import ${importPath}: ${message}`);
      result += `<!-- Import failed: ${importPath} - ${message} -->`;
    }
  }
  result += content.substring(lastIndex);
  return {
    content: result,
    importTree: {
      path: importState.currentFile || "unknown",
      imports: imports.length > 0 ? imports : void 0
    }
  };
}
function validateImportPath(importPath, basePath, allowedDirectories) {
  if (/^(file|https?):\/\//.test(importPath)) {
    return false;
  }
  const resolvedPath = path51.resolve(basePath, importPath);
  return allowedDirectories.some((allowedDir) => isSubpath(allowedDir, resolvedPath));
}
var logger3;
var init_memoryImportProcessor = __esm({
  "packages/core/dist/src/utils/memoryImportProcessor.js"() {
    "use strict";
    init_esbuild_shims();
    init_paths();
    init_marked_esm();
    logger3 = {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      debug: /* @__PURE__ */ __name((...args) => console.debug("[DEBUG] [ImportProcessor]", ...args), "debug"),
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      warn: /* @__PURE__ */ __name((...args) => console.warn("[WARN] [ImportProcessor]", ...args), "warn"),
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      error: /* @__PURE__ */ __name((...args) => console.error("[ERROR] [ImportProcessor]", ...args), "error")
    };
    __name(findProjectRoot, "findProjectRoot");
    __name(hasMessage, "hasMessage");
    __name(findImports, "findImports");
    __name(isWhitespace3, "isWhitespace");
    __name(isLetter, "isLetter");
    __name(findCodeRegions, "findCodeRegions");
    __name(processImports, "processImports");
    __name(validateImportPath, "validateImportPath");
  }
});

// packages/core/dist/src/utils/memoryDiscovery.js
import * as fs47 from "node:fs/promises";
import * as fsSync2 from "node:fs";
import * as path52 from "node:path";
import { homedir as homedir9 } from "node:os";
async function findProjectRoot2(startDir) {
  let currentDir = path52.resolve(startDir);
  while (true) {
    const gitPath = path52.join(currentDir, ".git");
    try {
      const stats = await fs47.lstat(gitPath);
      if (stats.isDirectory()) {
        return currentDir;
      }
    } catch (error) {
      const isENOENT = typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
      const isTestEnv = process.env["NODE_ENV"] === "test" || process.env["VITEST"];
      if (!isENOENT && !isTestEnv) {
        if (typeof error === "object" && error !== null && "code" in error) {
          const fsError = error;
          logger4.warn(`Error checking for .git directory at ${gitPath}: ${fsError.message}`);
        } else {
          logger4.warn(`Non-standard error checking for .git directory at ${gitPath}: ${String(error)}`);
        }
      }
    }
    const parentDir = path52.dirname(currentDir);
    if (parentDir === currentDir) {
      return null;
    }
    currentDir = parentDir;
  }
}
async function getGeminiMdFilePathsInternal(currentWorkingDirectory, includeDirectoriesToReadGemini, userHomePath, debugMode, fileService, extensionContextFilePaths = [], folderTrust, fileFilteringOptions, maxDirs) {
  const dirs = /* @__PURE__ */ new Set([
    ...includeDirectoriesToReadGemini,
    currentWorkingDirectory
  ]);
  const CONCURRENT_LIMIT = 10;
  const dirsArray = Array.from(dirs);
  const pathsArrays = [];
  for (let i = 0; i < dirsArray.length; i += CONCURRENT_LIMIT) {
    const batch = dirsArray.slice(i, i + CONCURRENT_LIMIT);
    const batchPromises = batch.map((dir) => getGeminiMdFilePathsInternalForEachDir(dir, userHomePath, debugMode, fileService, extensionContextFilePaths, folderTrust, fileFilteringOptions, maxDirs));
    const batchResults = await Promise.allSettled(batchPromises);
    for (const result of batchResults) {
      if (result.status === "fulfilled") {
        pathsArrays.push(result.value);
      } else {
        const error = result.reason;
        const message = error instanceof Error ? error.message : String(error);
        logger4.error(`Error discovering files in directory: ${message}`);
      }
    }
  }
  const paths = pathsArrays.flat();
  return Array.from(new Set(paths));
}
async function getGeminiMdFilePathsInternalForEachDir(dir, userHomePath, debugMode, fileService, extensionContextFilePaths = [], folderTrust, fileFilteringOptions, maxDirs) {
  const allPaths = /* @__PURE__ */ new Set();
  const geminiMdFilenames = getAllGeminiMdFilenames();
  for (const geminiMdFilename of geminiMdFilenames) {
    const resolvedHome = path52.resolve(userHomePath);
    const globalMemoryPath = path52.join(resolvedHome, QWEN_DIR5, geminiMdFilename);
    try {
      await fs47.access(globalMemoryPath, fsSync2.constants.R_OK);
      allPaths.add(globalMemoryPath);
      if (debugMode)
        logger4.debug(`Found readable global ${geminiMdFilename}: ${globalMemoryPath}`);
    } catch {
    }
    const resolvedDir = dir ? path52.resolve(dir) : resolvedHome;
    const isHomeDirectory = resolvedDir === resolvedHome;
    if (isHomeDirectory) {
      const homeContextPath = path52.join(resolvedHome, geminiMdFilename);
      try {
        await fs47.access(homeContextPath, fsSync2.constants.R_OK);
        if (homeContextPath !== globalMemoryPath) {
          allPaths.add(homeContextPath);
          if (debugMode)
            logger4.debug(`Found readable home ${geminiMdFilename}: ${homeContextPath}`);
        }
      } catch {
      }
    } else if (dir && folderTrust) {
      const resolvedCwd = path52.resolve(dir);
      if (debugMode)
        logger4.debug(`Searching for ${geminiMdFilename} starting from CWD: ${resolvedCwd}`);
      const projectRoot = await findProjectRoot2(resolvedCwd);
      if (debugMode)
        logger4.debug(`Determined project root: ${projectRoot ?? "None"}`);
      const upwardPaths = [];
      let currentDir = resolvedCwd;
      const ultimateStopDir = projectRoot ? path52.dirname(projectRoot) : path52.dirname(resolvedHome);
      while (currentDir && currentDir !== path52.dirname(currentDir)) {
        if (currentDir === path52.join(resolvedHome, QWEN_DIR5)) {
          break;
        }
        const potentialPath = path52.join(currentDir, geminiMdFilename);
        try {
          await fs47.access(potentialPath, fsSync2.constants.R_OK);
          if (potentialPath !== globalMemoryPath) {
            upwardPaths.unshift(potentialPath);
          }
        } catch {
        }
        if (currentDir === ultimateStopDir) {
          break;
        }
        currentDir = path52.dirname(currentDir);
      }
      upwardPaths.forEach((p) => allPaths.add(p));
      const mergedOptions = {
        ...DEFAULT_MEMORY_FILE_FILTERING_OPTIONS,
        ...fileFilteringOptions
      };
      const downwardPaths = await bfsFileSearch(resolvedCwd, {
        fileName: geminiMdFilename,
        maxDirs,
        debug: debugMode,
        fileService,
        fileFilteringOptions: mergedOptions
      });
      downwardPaths.sort();
      for (const dPath of downwardPaths) {
        allPaths.add(dPath);
      }
    }
  }
  for (const extensionPath of extensionContextFilePaths) {
    allPaths.add(extensionPath);
  }
  const finalPaths = Array.from(allPaths);
  if (debugMode)
    logger4.debug(`Final ordered ${getAllGeminiMdFilenames()} paths to read: ${JSON.stringify(finalPaths)}`);
  return finalPaths;
}
async function readGeminiMdFiles(filePaths, debugMode, importFormat = "tree") {
  const CONCURRENT_LIMIT = 20;
  const results = [];
  for (let i = 0; i < filePaths.length; i += CONCURRENT_LIMIT) {
    const batch = filePaths.slice(i, i + CONCURRENT_LIMIT);
    const batchPromises = batch.map(async (filePath) => {
      try {
        const content = await fs47.readFile(filePath, "utf-8");
        const processedResult = await processImports(content, path52.dirname(filePath), debugMode, void 0, void 0, importFormat);
        if (debugMode)
          logger4.debug(`Successfully read and processed imports: ${filePath} (Length: ${processedResult.content.length})`);
        return { filePath, content: processedResult.content };
      } catch (error) {
        const isTestEnv = process.env["NODE_ENV"] === "test" || process.env["VITEST"];
        if (!isTestEnv) {
          const message = error instanceof Error ? error.message : String(error);
          logger4.warn(`Warning: Could not read ${getAllGeminiMdFilenames()} file at ${filePath}. Error: ${message}`);
        }
        if (debugMode)
          logger4.debug(`Failed to read: ${filePath}`);
        return { filePath, content: null };
      }
    });
    const batchResults = await Promise.allSettled(batchPromises);
    for (const result of batchResults) {
      if (result.status === "fulfilled") {
        results.push(result.value);
      } else {
        const error = result.reason;
        const message = error instanceof Error ? error.message : String(error);
        logger4.error(`Unexpected error processing file: ${message}`);
      }
    }
  }
  return results;
}
function concatenateInstructions(instructionContents, currentWorkingDirectoryForDisplay) {
  return instructionContents.filter((item) => typeof item.content === "string").map((item) => {
    const trimmedContent = item.content.trim();
    if (trimmedContent.length === 0) {
      return null;
    }
    const displayPath = path52.isAbsolute(item.filePath) ? path52.relative(currentWorkingDirectoryForDisplay, item.filePath) : item.filePath;
    return `--- Context from: ${displayPath} ---
${trimmedContent}
--- End of Context from: ${displayPath} ---`;
  }).filter((block2) => block2 !== null).join("\n\n");
}
async function loadServerHierarchicalMemory(currentWorkingDirectory, includeDirectoriesToReadGemini, debugMode, fileService, extensionContextFilePaths = [], folderTrust, importFormat = "tree", fileFilteringOptions, maxDirs = 200) {
  if (debugMode)
    logger4.debug(`Loading server hierarchical memory for CWD: ${currentWorkingDirectory} (importFormat: ${importFormat})`);
  const userHomePath = homedir9();
  const filePaths = await getGeminiMdFilePathsInternal(currentWorkingDirectory, includeDirectoriesToReadGemini, userHomePath, debugMode, fileService, extensionContextFilePaths, folderTrust, fileFilteringOptions || DEFAULT_MEMORY_FILE_FILTERING_OPTIONS, maxDirs);
  if (filePaths.length === 0) {
    if (debugMode)
      logger4.debug("No QWEN.md files found in hierarchy.");
    return { memoryContent: "", fileCount: 0 };
  }
  const contentsWithPaths = await readGeminiMdFiles(filePaths, debugMode, importFormat);
  const combinedInstructions = concatenateInstructions(contentsWithPaths, currentWorkingDirectory);
  if (debugMode)
    logger4.debug(`Combined instructions length: ${combinedInstructions.length}`);
  if (debugMode && combinedInstructions.length > 0)
    logger4.debug(`Combined instructions (snippet): ${combinedInstructions.substring(0, 500)}...`);
  return {
    memoryContent: combinedInstructions,
    fileCount: contentsWithPaths.length
  };
}
var logger4;
var init_memoryDiscovery = __esm({
  "packages/core/dist/src/utils/memoryDiscovery.js"() {
    "use strict";
    init_esbuild_shims();
    init_bfsFileSearch();
    init_memoryTool();
    init_memoryImportProcessor();
    init_constants3();
    init_paths();
    logger4 = {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      debug: /* @__PURE__ */ __name((...args) => console.debug("[DEBUG] [MemoryDiscovery]", ...args), "debug"),
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      warn: /* @__PURE__ */ __name((...args) => console.warn("[WARN] [MemoryDiscovery]", ...args), "warn"),
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      error: /* @__PURE__ */ __name((...args) => console.error("[ERROR] [MemoryDiscovery]", ...args), "error")
    };
    __name(findProjectRoot2, "findProjectRoot");
    __name(getGeminiMdFilePathsInternal, "getGeminiMdFilePathsInternal");
    __name(getGeminiMdFilePathsInternalForEachDir, "getGeminiMdFilePathsInternalForEachDir");
    __name(readGeminiMdFiles, "readGeminiMdFiles");
    __name(concatenateInstructions, "concatenateInstructions");
    __name(loadServerHierarchicalMemory, "loadServerHierarchicalMemory");
  }
});

// packages/core/node_modules/picomatch/lib/constants.js
var require_constants11 = __commonJS({
  "packages/core/node_modules/picomatch/lib/constants.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var WIN_SLASH = "\\\\/";
    var WIN_NO_SLASH = `[^${WIN_SLASH}]`;
    var DOT_LITERAL = "\\.";
    var PLUS_LITERAL = "\\+";
    var QMARK_LITERAL = "\\?";
    var SLASH_LITERAL = "\\/";
    var ONE_CHAR = "(?=.)";
    var QMARK = "[^/]";
    var END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
    var START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
    var DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
    var NO_DOT = `(?!${DOT_LITERAL})`;
    var NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
    var NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
    var NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
    var QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
    var STAR = `${QMARK}*?`;
    var SEP3 = "/";
    var POSIX_CHARS = {
      DOT_LITERAL,
      PLUS_LITERAL,
      QMARK_LITERAL,
      SLASH_LITERAL,
      ONE_CHAR,
      QMARK,
      END_ANCHOR,
      DOTS_SLASH,
      NO_DOT,
      NO_DOTS,
      NO_DOT_SLASH,
      NO_DOTS_SLASH,
      QMARK_NO_DOT,
      STAR,
      START_ANCHOR,
      SEP: SEP3
    };
    var WINDOWS_CHARS = {
      ...POSIX_CHARS,
      SLASH_LITERAL: `[${WIN_SLASH}]`,
      QMARK: WIN_NO_SLASH,
      STAR: `${WIN_NO_SLASH}*?`,
      DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
      NO_DOT: `(?!${DOT_LITERAL})`,
      NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
      NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
      NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
      QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
      START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
      END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
      SEP: "\\"
    };
    var POSIX_REGEX_SOURCE = {
      alnum: "a-zA-Z0-9",
      alpha: "a-zA-Z",
      ascii: "\\x00-\\x7F",
      blank: " \\t",
      cntrl: "\\x00-\\x1F\\x7F",
      digit: "0-9",
      graph: "\\x21-\\x7E",
      lower: "a-z",
      print: "\\x20-\\x7E ",
      punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",
      space: " \\t\\r\\n\\v\\f",
      upper: "A-Z",
      word: "A-Za-z0-9_",
      xdigit: "A-Fa-f0-9"
    };
    module2.exports = {
      MAX_LENGTH: 1024 * 64,
      POSIX_REGEX_SOURCE,
      // regular expressions
      REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
      REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
      REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
      REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
      REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
      REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
      // Replace globs with equivalent patterns to reduce parsing time.
      REPLACEMENTS: {
        __proto__: null,
        "***": "*",
        "**/**": "**",
        "**/**/**": "**"
      },
      // Digits
      CHAR_0: 48,
      /* 0 */
      CHAR_9: 57,
      /* 9 */
      // Alphabet chars.
      CHAR_UPPERCASE_A: 65,
      /* A */
      CHAR_LOWERCASE_A: 97,
      /* a */
      CHAR_UPPERCASE_Z: 90,
      /* Z */
      CHAR_LOWERCASE_Z: 122,
      /* z */
      CHAR_LEFT_PARENTHESES: 40,
      /* ( */
      CHAR_RIGHT_PARENTHESES: 41,
      /* ) */
      CHAR_ASTERISK: 42,
      /* * */
      // Non-alphabetic chars.
      CHAR_AMPERSAND: 38,
      /* & */
      CHAR_AT: 64,
      /* @ */
      CHAR_BACKWARD_SLASH: 92,
      /* \ */
      CHAR_CARRIAGE_RETURN: 13,
      /* \r */
      CHAR_CIRCUMFLEX_ACCENT: 94,
      /* ^ */
      CHAR_COLON: 58,
      /* : */
      CHAR_COMMA: 44,
      /* , */
      CHAR_DOT: 46,
      /* . */
      CHAR_DOUBLE_QUOTE: 34,
      /* " */
      CHAR_EQUAL: 61,
      /* = */
      CHAR_EXCLAMATION_MARK: 33,
      /* ! */
      CHAR_FORM_FEED: 12,
      /* \f */
      CHAR_FORWARD_SLASH: 47,
      /* / */
      CHAR_GRAVE_ACCENT: 96,
      /* ` */
      CHAR_HASH: 35,
      /* # */
      CHAR_HYPHEN_MINUS: 45,
      /* - */
      CHAR_LEFT_ANGLE_BRACKET: 60,
      /* < */
      CHAR_LEFT_CURLY_BRACE: 123,
      /* { */
      CHAR_LEFT_SQUARE_BRACKET: 91,
      /* [ */
      CHAR_LINE_FEED: 10,
      /* \n */
      CHAR_NO_BREAK_SPACE: 160,
      /* \u00A0 */
      CHAR_PERCENT: 37,
      /* % */
      CHAR_PLUS: 43,
      /* + */
      CHAR_QUESTION_MARK: 63,
      /* ? */
      CHAR_RIGHT_ANGLE_BRACKET: 62,
      /* > */
      CHAR_RIGHT_CURLY_BRACE: 125,
      /* } */
      CHAR_RIGHT_SQUARE_BRACKET: 93,
      /* ] */
      CHAR_SEMICOLON: 59,
      /* ; */
      CHAR_SINGLE_QUOTE: 39,
      /* ' */
      CHAR_SPACE: 32,
      /*   */
      CHAR_TAB: 9,
      /* \t */
      CHAR_UNDERSCORE: 95,
      /* _ */
      CHAR_VERTICAL_LINE: 124,
      /* | */
      CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
      /* \uFEFF */
      /**
       * Create EXTGLOB_CHARS
       */
      extglobChars(chars) {
        return {
          "!": { type: "negate", open: "(?:(?!(?:", close: `))${chars.STAR})` },
          "?": { type: "qmark", open: "(?:", close: ")?" },
          "+": { type: "plus", open: "(?:", close: ")+" },
          "*": { type: "star", open: "(?:", close: ")*" },
          "@": { type: "at", open: "(?:", close: ")" }
        };
      },
      /**
       * Create GLOB_CHARS
       */
      globChars(win323) {
        return win323 === true ? WINDOWS_CHARS : POSIX_CHARS;
      }
    };
  }
});

// packages/core/node_modules/picomatch/lib/utils.js
var require_utils14 = __commonJS({
  "packages/core/node_modules/picomatch/lib/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var {
      REGEX_BACKSLASH,
      REGEX_REMOVE_BACKSLASH,
      REGEX_SPECIAL_CHARS,
      REGEX_SPECIAL_CHARS_GLOBAL
    } = require_constants11();
    exports2.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
    exports2.hasRegexChars = (str2) => REGEX_SPECIAL_CHARS.test(str2);
    exports2.isRegexChar = (str2) => str2.length === 1 && exports2.hasRegexChars(str2);
    exports2.escapeRegex = (str2) => str2.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1");
    exports2.toPosixSlashes = (str2) => str2.replace(REGEX_BACKSLASH, "/");
    exports2.isWindows = () => {
      if (typeof navigator !== "undefined" && navigator.platform) {
        const platform15 = navigator.platform.toLowerCase();
        return platform15 === "win32" || platform15 === "windows";
      }
      if (typeof process !== "undefined" && process.platform) {
        return process.platform === "win32";
      }
      return false;
    };
    exports2.removeBackslashes = (str2) => {
      return str2.replace(REGEX_REMOVE_BACKSLASH, (match2) => {
        return match2 === "\\" ? "" : match2;
      });
    };
    exports2.escapeLast = (input, char, lastIdx) => {
      const idx = input.lastIndexOf(char, lastIdx);
      if (idx === -1) return input;
      if (input[idx - 1] === "\\") return exports2.escapeLast(input, char, idx - 1);
      return `${input.slice(0, idx)}\\${input.slice(idx)}`;
    };
    exports2.removePrefix = (input, state = {}) => {
      let output = input;
      if (output.startsWith("./")) {
        output = output.slice(2);
        state.prefix = "./";
      }
      return output;
    };
    exports2.wrapOutput = (input, state = {}, options2 = {}) => {
      const prepend = options2.contains ? "" : "^";
      const append2 = options2.contains ? "" : "$";
      let output = `${prepend}(?:${input})${append2}`;
      if (state.negated === true) {
        output = `(?:^(?!${output}).*$)`;
      }
      return output;
    };
    exports2.basename = (path108, { windows } = {}) => {
      const segs = path108.split(windows ? /[\\/]/ : "/");
      const last2 = segs[segs.length - 1];
      if (last2 === "") {
        return segs[segs.length - 2];
      }
      return last2;
    };
  }
});

// packages/core/node_modules/picomatch/lib/scan.js
var require_scan = __commonJS({
  "packages/core/node_modules/picomatch/lib/scan.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var utils = require_utils14();
    var {
      CHAR_ASTERISK,
      /* * */
      CHAR_AT,
      /* @ */
      CHAR_BACKWARD_SLASH,
      /* \ */
      CHAR_COMMA: CHAR_COMMA2,
      /* , */
      CHAR_DOT,
      /* . */
      CHAR_EXCLAMATION_MARK,
      /* ! */
      CHAR_FORWARD_SLASH,
      /* / */
      CHAR_LEFT_CURLY_BRACE,
      /* { */
      CHAR_LEFT_PARENTHESES,
      /* ( */
      CHAR_LEFT_SQUARE_BRACKET,
      /* [ */
      CHAR_PLUS: CHAR_PLUS2,
      /* + */
      CHAR_QUESTION_MARK,
      /* ? */
      CHAR_RIGHT_CURLY_BRACE,
      /* } */
      CHAR_RIGHT_PARENTHESES,
      /* ) */
      CHAR_RIGHT_SQUARE_BRACKET
      /* ] */
    } = require_constants11();
    var isPathSeparator = /* @__PURE__ */ __name((code2) => {
      return code2 === CHAR_FORWARD_SLASH || code2 === CHAR_BACKWARD_SLASH;
    }, "isPathSeparator");
    var depth = /* @__PURE__ */ __name((token2) => {
      if (token2.isPrefix !== true) {
        token2.depth = token2.isGlobstar ? Infinity : 1;
      }
    }, "depth");
    var scan = /* @__PURE__ */ __name((input, options2) => {
      const opts = options2 || {};
      const length = input.length - 1;
      const scanToEnd = opts.parts === true || opts.scanToEnd === true;
      const slashes = [];
      const tokens = [];
      const parts = [];
      let str2 = input;
      let index = -1;
      let start = 0;
      let lastIndex = 0;
      let isBrace = false;
      let isBracket = false;
      let isGlob = false;
      let isExtglob = false;
      let isGlobstar = false;
      let braceEscaped = false;
      let backslashes = false;
      let negated = false;
      let negatedExtglob = false;
      let finished = false;
      let braces = 0;
      let prev;
      let code2;
      let token2 = { value: "", depth: 0, isGlob: false };
      const eos = /* @__PURE__ */ __name(() => index >= length, "eos");
      const peek = /* @__PURE__ */ __name(() => str2.charCodeAt(index + 1), "peek");
      const advance = /* @__PURE__ */ __name(() => {
        prev = code2;
        return str2.charCodeAt(++index);
      }, "advance");
      while (index < length) {
        code2 = advance();
        let next;
        if (code2 === CHAR_BACKWARD_SLASH) {
          backslashes = token2.backslashes = true;
          code2 = advance();
          if (code2 === CHAR_LEFT_CURLY_BRACE) {
            braceEscaped = true;
          }
          continue;
        }
        if (braceEscaped === true || code2 === CHAR_LEFT_CURLY_BRACE) {
          braces++;
          while (eos() !== true && (code2 = advance())) {
            if (code2 === CHAR_BACKWARD_SLASH) {
              backslashes = token2.backslashes = true;
              advance();
              continue;
            }
            if (code2 === CHAR_LEFT_CURLY_BRACE) {
              braces++;
              continue;
            }
            if (braceEscaped !== true && code2 === CHAR_DOT && (code2 = advance()) === CHAR_DOT) {
              isBrace = token2.isBrace = true;
              isGlob = token2.isGlob = true;
              finished = true;
              if (scanToEnd === true) {
                continue;
              }
              break;
            }
            if (braceEscaped !== true && code2 === CHAR_COMMA2) {
              isBrace = token2.isBrace = true;
              isGlob = token2.isGlob = true;
              finished = true;
              if (scanToEnd === true) {
                continue;
              }
              break;
            }
            if (code2 === CHAR_RIGHT_CURLY_BRACE) {
              braces--;
              if (braces === 0) {
                braceEscaped = false;
                isBrace = token2.isBrace = true;
                finished = true;
                break;
              }
            }
          }
          if (scanToEnd === true) {
            continue;
          }
          break;
        }
        if (code2 === CHAR_FORWARD_SLASH) {
          slashes.push(index);
          tokens.push(token2);
          token2 = { value: "", depth: 0, isGlob: false };
          if (finished === true) continue;
          if (prev === CHAR_DOT && index === start + 1) {
            start += 2;
            continue;
          }
          lastIndex = index + 1;
          continue;
        }
        if (opts.noext !== true) {
          const isExtglobChar = code2 === CHAR_PLUS2 || code2 === CHAR_AT || code2 === CHAR_ASTERISK || code2 === CHAR_QUESTION_MARK || code2 === CHAR_EXCLAMATION_MARK;
          if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
            isGlob = token2.isGlob = true;
            isExtglob = token2.isExtglob = true;
            finished = true;
            if (code2 === CHAR_EXCLAMATION_MARK && index === start) {
              negatedExtglob = true;
            }
            if (scanToEnd === true) {
              while (eos() !== true && (code2 = advance())) {
                if (code2 === CHAR_BACKWARD_SLASH) {
                  backslashes = token2.backslashes = true;
                  code2 = advance();
                  continue;
                }
                if (code2 === CHAR_RIGHT_PARENTHESES) {
                  isGlob = token2.isGlob = true;
                  finished = true;
                  break;
                }
              }
              continue;
            }
            break;
          }
        }
        if (code2 === CHAR_ASTERISK) {
          if (prev === CHAR_ASTERISK) isGlobstar = token2.isGlobstar = true;
          isGlob = token2.isGlob = true;
          finished = true;
          if (scanToEnd === true) {
            continue;
          }
          break;
        }
        if (code2 === CHAR_QUESTION_MARK) {
          isGlob = token2.isGlob = true;
          finished = true;
          if (scanToEnd === true) {
            continue;
          }
          break;
        }
        if (code2 === CHAR_LEFT_SQUARE_BRACKET) {
          while (eos() !== true && (next = advance())) {
            if (next === CHAR_BACKWARD_SLASH) {
              backslashes = token2.backslashes = true;
              advance();
              continue;
            }
            if (next === CHAR_RIGHT_SQUARE_BRACKET) {
              isBracket = token2.isBracket = true;
              isGlob = token2.isGlob = true;
              finished = true;
              break;
            }
          }
          if (scanToEnd === true) {
            continue;
          }
          break;
        }
        if (opts.nonegate !== true && code2 === CHAR_EXCLAMATION_MARK && index === start) {
          negated = token2.negated = true;
          start++;
          continue;
        }
        if (opts.noparen !== true && code2 === CHAR_LEFT_PARENTHESES) {
          isGlob = token2.isGlob = true;
          if (scanToEnd === true) {
            while (eos() !== true && (code2 = advance())) {
              if (code2 === CHAR_LEFT_PARENTHESES) {
                backslashes = token2.backslashes = true;
                code2 = advance();
                continue;
              }
              if (code2 === CHAR_RIGHT_PARENTHESES) {
                finished = true;
                break;
              }
            }
            continue;
          }
          break;
        }
        if (isGlob === true) {
          finished = true;
          if (scanToEnd === true) {
            continue;
          }
          break;
        }
      }
      if (opts.noext === true) {
        isExtglob = false;
        isGlob = false;
      }
      let base = str2;
      let prefix = "";
      let glob2 = "";
      if (start > 0) {
        prefix = str2.slice(0, start);
        str2 = str2.slice(start);
        lastIndex -= start;
      }
      if (base && isGlob === true && lastIndex > 0) {
        base = str2.slice(0, lastIndex);
        glob2 = str2.slice(lastIndex);
      } else if (isGlob === true) {
        base = "";
        glob2 = str2;
      } else {
        base = str2;
      }
      if (base && base !== "" && base !== "/" && base !== str2) {
        if (isPathSeparator(base.charCodeAt(base.length - 1))) {
          base = base.slice(0, -1);
        }
      }
      if (opts.unescape === true) {
        if (glob2) glob2 = utils.removeBackslashes(glob2);
        if (base && backslashes === true) {
          base = utils.removeBackslashes(base);
        }
      }
      const state = {
        prefix,
        input,
        start,
        base,
        glob: glob2,
        isBrace,
        isBracket,
        isGlob,
        isExtglob,
        isGlobstar,
        negated,
        negatedExtglob
      };
      if (opts.tokens === true) {
        state.maxDepth = 0;
        if (!isPathSeparator(code2)) {
          tokens.push(token2);
        }
        state.tokens = tokens;
      }
      if (opts.parts === true || opts.tokens === true) {
        let prevIndex;
        for (let idx = 0; idx < slashes.length; idx++) {
          const n2 = prevIndex ? prevIndex + 1 : start;
          const i = slashes[idx];
          const value = input.slice(n2, i);
          if (opts.tokens) {
            if (idx === 0 && start !== 0) {
              tokens[idx].isPrefix = true;
              tokens[idx].value = prefix;
            } else {
              tokens[idx].value = value;
            }
            depth(tokens[idx]);
            state.maxDepth += tokens[idx].depth;
          }
          if (idx !== 0 || value !== "") {
            parts.push(value);
          }
          prevIndex = i;
        }
        if (prevIndex && prevIndex + 1 < input.length) {
          const value = input.slice(prevIndex + 1);
          parts.push(value);
          if (opts.tokens) {
            tokens[tokens.length - 1].value = value;
            depth(tokens[tokens.length - 1]);
            state.maxDepth += tokens[tokens.length - 1].depth;
          }
        }
        state.slashes = slashes;
        state.parts = parts;
      }
      return state;
    }, "scan");
    module2.exports = scan;
  }
});

// packages/core/node_modules/picomatch/lib/parse.js
var require_parse6 = __commonJS({
  "packages/core/node_modules/picomatch/lib/parse.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var constants4 = require_constants11();
    var utils = require_utils14();
    var {
      MAX_LENGTH,
      POSIX_REGEX_SOURCE,
      REGEX_NON_SPECIAL_CHARS,
      REGEX_SPECIAL_CHARS_BACKREF,
      REPLACEMENTS
    } = constants4;
    var expandRange = /* @__PURE__ */ __name((args, options2) => {
      if (typeof options2.expandRange === "function") {
        return options2.expandRange(...args, options2);
      }
      args.sort();
      const value = `[${args.join("-")}]`;
      try {
        new RegExp(value);
      } catch (ex) {
        return args.map((v) => utils.escapeRegex(v)).join("..");
      }
      return value;
    }, "expandRange");
    var syntaxError2 = /* @__PURE__ */ __name((type, char) => {
      return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
    }, "syntaxError");
    var parse12 = /* @__PURE__ */ __name((input, options2) => {
      if (typeof input !== "string") {
        throw new TypeError("Expected a string");
      }
      input = REPLACEMENTS[input] || input;
      const opts = { ...options2 };
      const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
      let len = input.length;
      if (len > max) {
        throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
      }
      const bos = { type: "bos", value: "", output: opts.prepend || "" };
      const tokens = [bos];
      const capture = opts.capture ? "" : "?:";
      const PLATFORM_CHARS = constants4.globChars(opts.windows);
      const EXTGLOB_CHARS = constants4.extglobChars(PLATFORM_CHARS);
      const {
        DOT_LITERAL,
        PLUS_LITERAL,
        SLASH_LITERAL,
        ONE_CHAR,
        DOTS_SLASH,
        NO_DOT,
        NO_DOT_SLASH,
        NO_DOTS_SLASH,
        QMARK,
        QMARK_NO_DOT,
        STAR,
        START_ANCHOR
      } = PLATFORM_CHARS;
      const globstar = /* @__PURE__ */ __name((opts2) => {
        return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
      }, "globstar");
      const nodot = opts.dot ? "" : NO_DOT;
      const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
      let star3 = opts.bash === true ? globstar(opts) : STAR;
      if (opts.capture) {
        star3 = `(${star3})`;
      }
      if (typeof opts.noext === "boolean") {
        opts.noextglob = opts.noext;
      }
      const state = {
        input,
        index: -1,
        start: 0,
        dot: opts.dot === true,
        consumed: "",
        output: "",
        prefix: "",
        backtrack: false,
        negated: false,
        brackets: 0,
        braces: 0,
        parens: 0,
        quotes: 0,
        globstar: false,
        tokens
      };
      input = utils.removePrefix(input, state);
      len = input.length;
      const extglobs = [];
      const braces = [];
      const stack = [];
      let prev = bos;
      let value;
      const eos = /* @__PURE__ */ __name(() => state.index === len - 1, "eos");
      const peek = state.peek = (n2 = 1) => input[state.index + n2];
      const advance = state.advance = () => input[++state.index] || "";
      const remaining = /* @__PURE__ */ __name(() => input.slice(state.index + 1), "remaining");
      const consume = /* @__PURE__ */ __name((value2 = "", num = 0) => {
        state.consumed += value2;
        state.index += num;
      }, "consume");
      const append2 = /* @__PURE__ */ __name((token2) => {
        state.output += token2.output != null ? token2.output : token2.value;
        consume(token2.value);
      }, "append");
      const negate = /* @__PURE__ */ __name(() => {
        let count = 1;
        while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) {
          advance();
          state.start++;
          count++;
        }
        if (count % 2 === 0) {
          return false;
        }
        state.negated = true;
        state.start++;
        return true;
      }, "negate");
      const increment2 = /* @__PURE__ */ __name((type) => {
        state[type]++;
        stack.push(type);
      }, "increment");
      const decrement = /* @__PURE__ */ __name((type) => {
        state[type]--;
        stack.pop();
      }, "decrement");
      const push2 = /* @__PURE__ */ __name((tok) => {
        if (prev.type === "globstar") {
          const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace");
          const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren");
          if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) {
            state.output = state.output.slice(0, -prev.output.length);
            prev.type = "star";
            prev.value = "*";
            prev.output = star3;
            state.output += prev.output;
          }
        }
        if (extglobs.length && tok.type !== "paren") {
          extglobs[extglobs.length - 1].inner += tok.value;
        }
        if (tok.value || tok.output) append2(tok);
        if (prev && prev.type === "text" && tok.type === "text") {
          prev.output = (prev.output || prev.value) + tok.value;
          prev.value += tok.value;
          return;
        }
        tok.prev = prev;
        tokens.push(tok);
        prev = tok;
      }, "push");
      const extglobOpen = /* @__PURE__ */ __name((type, value2) => {
        const token2 = { ...EXTGLOB_CHARS[value2], conditions: 1, inner: "" };
        token2.prev = prev;
        token2.parens = state.parens;
        token2.output = state.output;
        const output = (opts.capture ? "(" : "") + token2.open;
        increment2("parens");
        push2({ type, value: value2, output: state.output ? "" : ONE_CHAR });
        push2({ type: "paren", extglob: true, value: advance(), output });
        extglobs.push(token2);
      }, "extglobOpen");
      const extglobClose = /* @__PURE__ */ __name((token2) => {
        let output = token2.close + (opts.capture ? ")" : "");
        let rest;
        if (token2.type === "negate") {
          let extglobStar = star3;
          if (token2.inner && token2.inner.length > 1 && token2.inner.includes("/")) {
            extglobStar = globstar(opts);
          }
          if (extglobStar !== star3 || eos() || /^\)+$/.test(remaining())) {
            output = token2.close = `)$))${extglobStar}`;
          }
          if (token2.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
            const expression = parse12(rest, { ...options2, fastpaths: false }).output;
            output = token2.close = `)${expression})${extglobStar})`;
          }
          if (token2.prev.type === "bos") {
            state.negatedExtglob = true;
          }
        }
        push2({ type: "paren", extglob: true, value, output });
        decrement("parens");
      }, "extglobClose");
      if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
        let backslashes = false;
        let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first2, rest, index) => {
          if (first2 === "\\") {
            backslashes = true;
            return m;
          }
          if (first2 === "?") {
            if (esc) {
              return esc + first2 + (rest ? QMARK.repeat(rest.length) : "");
            }
            if (index === 0) {
              return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : "");
            }
            return QMARK.repeat(chars.length);
          }
          if (first2 === ".") {
            return DOT_LITERAL.repeat(chars.length);
          }
          if (first2 === "*") {
            if (esc) {
              return esc + first2 + (rest ? star3 : "");
            }
            return star3;
          }
          return esc ? m : `\\${m}`;
        });
        if (backslashes === true) {
          if (opts.unescape === true) {
            output = output.replace(/\\/g, "");
          } else {
            output = output.replace(/\\+/g, (m) => {
              return m.length % 2 === 0 ? "\\\\" : m ? "\\" : "";
            });
          }
        }
        if (output === input && opts.contains === true) {
          state.output = input;
          return state;
        }
        state.output = utils.wrapOutput(output, state, options2);
        return state;
      }
      while (!eos()) {
        value = advance();
        if (value === "\0") {
          continue;
        }
        if (value === "\\") {
          const next = peek();
          if (next === "/" && opts.bash !== true) {
            continue;
          }
          if (next === "." || next === ";") {
            continue;
          }
          if (!next) {
            value += "\\";
            push2({ type: "text", value });
            continue;
          }
          const match2 = /^\\+/.exec(remaining());
          let slashes = 0;
          if (match2 && match2[0].length > 2) {
            slashes = match2[0].length;
            state.index += slashes;
            if (slashes % 2 !== 0) {
              value += "\\";
            }
          }
          if (opts.unescape === true) {
            value = advance();
          } else {
            value += advance();
          }
          if (state.brackets === 0) {
            push2({ type: "text", value });
            continue;
          }
        }
        if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) {
          if (opts.posix !== false && value === ":") {
            const inner = prev.value.slice(1);
            if (inner.includes("[")) {
              prev.posix = true;
              if (inner.includes(":")) {
                const idx = prev.value.lastIndexOf("[");
                const pre = prev.value.slice(0, idx);
                const rest2 = prev.value.slice(idx + 2);
                const posix3 = POSIX_REGEX_SOURCE[rest2];
                if (posix3) {
                  prev.value = pre + posix3;
                  state.backtrack = true;
                  advance();
                  if (!bos.output && tokens.indexOf(prev) === 1) {
                    bos.output = ONE_CHAR;
                  }
                  continue;
                }
              }
            }
          }
          if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") {
            value = `\\${value}`;
          }
          if (value === "]" && (prev.value === "[" || prev.value === "[^")) {
            value = `\\${value}`;
          }
          if (opts.posix === true && value === "!" && prev.value === "[") {
            value = "^";
          }
          prev.value += value;
          append2({ value });
          continue;
        }
        if (state.quotes === 1 && value !== '"') {
          value = utils.escapeRegex(value);
          prev.value += value;
          append2({ value });
          continue;
        }
        if (value === '"') {
          state.quotes = state.quotes === 1 ? 0 : 1;
          if (opts.keepQuotes === true) {
            push2({ type: "text", value });
          }
          continue;
        }
        if (value === "(") {
          increment2("parens");
          push2({ type: "paren", value });
          continue;
        }
        if (value === ")") {
          if (state.parens === 0 && opts.strictBrackets === true) {
            throw new SyntaxError(syntaxError2("opening", "("));
          }
          const extglob = extglobs[extglobs.length - 1];
          if (extglob && state.parens === extglob.parens + 1) {
            extglobClose(extglobs.pop());
            continue;
          }
          push2({ type: "paren", value, output: state.parens ? ")" : "\\)" });
          decrement("parens");
          continue;
        }
        if (value === "[") {
          if (opts.nobracket === true || !remaining().includes("]")) {
            if (opts.nobracket !== true && opts.strictBrackets === true) {
              throw new SyntaxError(syntaxError2("closing", "]"));
            }
            value = `\\${value}`;
          } else {
            increment2("brackets");
          }
          push2({ type: "bracket", value });
          continue;
        }
        if (value === "]") {
          if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) {
            push2({ type: "text", value, output: `\\${value}` });
            continue;
          }
          if (state.brackets === 0) {
            if (opts.strictBrackets === true) {
              throw new SyntaxError(syntaxError2("opening", "["));
            }
            push2({ type: "text", value, output: `\\${value}` });
            continue;
          }
          decrement("brackets");
          const prevValue = prev.value.slice(1);
          if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) {
            value = `/${value}`;
          }
          prev.value += value;
          append2({ value });
          if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
            continue;
          }
          const escaped = utils.escapeRegex(prev.value);
          state.output = state.output.slice(0, -prev.value.length);
          if (opts.literalBrackets === true) {
            state.output += escaped;
            prev.value = escaped;
            continue;
          }
          prev.value = `(${capture}${escaped}|${prev.value})`;
          state.output += prev.value;
          continue;
        }
        if (value === "{" && opts.nobrace !== true) {
          increment2("braces");
          const open3 = {
            type: "brace",
            value,
            output: "(",
            outputIndex: state.output.length,
            tokensIndex: state.tokens.length
          };
          braces.push(open3);
          push2(open3);
          continue;
        }
        if (value === "}") {
          const brace = braces[braces.length - 1];
          if (opts.nobrace === true || !brace) {
            push2({ type: "text", value, output: value });
            continue;
          }
          let output = ")";
          if (brace.dots === true) {
            const arr = tokens.slice();
            const range = [];
            for (let i = arr.length - 1; i >= 0; i--) {
              tokens.pop();
              if (arr[i].type === "brace") {
                break;
              }
              if (arr[i].type !== "dots") {
                range.unshift(arr[i].value);
              }
            }
            output = expandRange(range, opts);
            state.backtrack = true;
          }
          if (brace.comma !== true && brace.dots !== true) {
            const out = state.output.slice(0, brace.outputIndex);
            const toks = state.tokens.slice(brace.tokensIndex);
            brace.value = brace.output = "\\{";
            value = output = "\\}";
            state.output = out;
            for (const t2 of toks) {
              state.output += t2.output || t2.value;
            }
          }
          push2({ type: "brace", value, output });
          decrement("braces");
          braces.pop();
          continue;
        }
        if (value === "|") {
          if (extglobs.length > 0) {
            extglobs[extglobs.length - 1].conditions++;
          }
          push2({ type: "text", value });
          continue;
        }
        if (value === ",") {
          let output = value;
          const brace = braces[braces.length - 1];
          if (brace && stack[stack.length - 1] === "braces") {
            brace.comma = true;
            output = "|";
          }
          push2({ type: "comma", value, output });
          continue;
        }
        if (value === "/") {
          if (prev.type === "dot" && state.index === state.start + 1) {
            state.start = state.index + 1;
            state.consumed = "";
            state.output = "";
            tokens.pop();
            prev = bos;
            continue;
          }
          push2({ type: "slash", value, output: SLASH_LITERAL });
          continue;
        }
        if (value === ".") {
          if (state.braces > 0 && prev.type === "dot") {
            if (prev.value === ".") prev.output = DOT_LITERAL;
            const brace = braces[braces.length - 1];
            prev.type = "dots";
            prev.output += value;
            prev.value += value;
            brace.dots = true;
            continue;
          }
          if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") {
            push2({ type: "text", value, output: DOT_LITERAL });
            continue;
          }
          push2({ type: "dot", value, output: DOT_LITERAL });
          continue;
        }
        if (value === "?") {
          const isGroup = prev && prev.value === "(";
          if (!isGroup && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
            extglobOpen("qmark", value);
            continue;
          }
          if (prev && prev.type === "paren") {
            const next = peek();
            let output = value;
            if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) {
              output = `\\${value}`;
            }
            push2({ type: "text", value, output });
            continue;
          }
          if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) {
            push2({ type: "qmark", value, output: QMARK_NO_DOT });
            continue;
          }
          push2({ type: "qmark", value, output: QMARK });
          continue;
        }
        if (value === "!") {
          if (opts.noextglob !== true && peek() === "(") {
            if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) {
              extglobOpen("negate", value);
              continue;
            }
          }
          if (opts.nonegate !== true && state.index === 0) {
            negate();
            continue;
          }
        }
        if (value === "+") {
          if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
            extglobOpen("plus", value);
            continue;
          }
          if (prev && prev.value === "(" || opts.regex === false) {
            push2({ type: "plus", value, output: PLUS_LITERAL });
            continue;
          }
          if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) {
            push2({ type: "plus", value });
            continue;
          }
          push2({ type: "plus", value: PLUS_LITERAL });
          continue;
        }
        if (value === "@") {
          if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
            push2({ type: "at", extglob: true, value, output: "" });
            continue;
          }
          push2({ type: "text", value });
          continue;
        }
        if (value !== "*") {
          if (value === "$" || value === "^") {
            value = `\\${value}`;
          }
          const match2 = REGEX_NON_SPECIAL_CHARS.exec(remaining());
          if (match2) {
            value += match2[0];
            state.index += match2[0].length;
          }
          push2({ type: "text", value });
          continue;
        }
        if (prev && (prev.type === "globstar" || prev.star === true)) {
          prev.type = "star";
          prev.star = true;
          prev.value += value;
          prev.output = star3;
          state.backtrack = true;
          state.globstar = true;
          consume(value);
          continue;
        }
        let rest = remaining();
        if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
          extglobOpen("star", value);
          continue;
        }
        if (prev.type === "star") {
          if (opts.noglobstar === true) {
            consume(value);
            continue;
          }
          const prior = prev.prev;
          const before = prior.prev;
          const isStart = prior.type === "slash" || prior.type === "bos";
          const afterStar = before && (before.type === "star" || before.type === "globstar");
          if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) {
            push2({ type: "star", value, output: "" });
            continue;
          }
          const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace");
          const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren");
          if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) {
            push2({ type: "star", value, output: "" });
            continue;
          }
          while (rest.slice(0, 3) === "/**") {
            const after = input[state.index + 4];
            if (after && after !== "/") {
              break;
            }
            rest = rest.slice(3);
            consume("/**", 3);
          }
          if (prior.type === "bos" && eos()) {
            prev.type = "globstar";
            prev.value += value;
            prev.output = globstar(opts);
            state.output = prev.output;
            state.globstar = true;
            consume(value);
            continue;
          }
          if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) {
            state.output = state.output.slice(0, -(prior.output + prev.output).length);
            prior.output = `(?:${prior.output}`;
            prev.type = "globstar";
            prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)");
            prev.value += value;
            state.globstar = true;
            state.output += prior.output + prev.output;
            consume(value);
            continue;
          }
          if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") {
            const end = rest[1] !== void 0 ? "|$" : "";
            state.output = state.output.slice(0, -(prior.output + prev.output).length);
            prior.output = `(?:${prior.output}`;
            prev.type = "globstar";
            prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
            prev.value += value;
            state.output += prior.output + prev.output;
            state.globstar = true;
            consume(value + advance());
            push2({ type: "slash", value: "/", output: "" });
            continue;
          }
          if (prior.type === "bos" && rest[0] === "/") {
            prev.type = "globstar";
            prev.value += value;
            prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
            state.output = prev.output;
            state.globstar = true;
            consume(value + advance());
            push2({ type: "slash", value: "/", output: "" });
            continue;
          }
          state.output = state.output.slice(0, -prev.output.length);
          prev.type = "globstar";
          prev.output = globstar(opts);
          prev.value += value;
          state.output += prev.output;
          state.globstar = true;
          consume(value);
          continue;
        }
        const token2 = { type: "star", value, output: star3 };
        if (opts.bash === true) {
          token2.output = ".*?";
          if (prev.type === "bos" || prev.type === "slash") {
            token2.output = nodot + token2.output;
          }
          push2(token2);
          continue;
        }
        if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) {
          token2.output = value;
          push2(token2);
          continue;
        }
        if (state.index === state.start || prev.type === "slash" || prev.type === "dot") {
          if (prev.type === "dot") {
            state.output += NO_DOT_SLASH;
            prev.output += NO_DOT_SLASH;
          } else if (opts.dot === true) {
            state.output += NO_DOTS_SLASH;
            prev.output += NO_DOTS_SLASH;
          } else {
            state.output += nodot;
            prev.output += nodot;
          }
          if (peek() !== "*") {
            state.output += ONE_CHAR;
            prev.output += ONE_CHAR;
          }
        }
        push2(token2);
      }
      while (state.brackets > 0) {
        if (opts.strictBrackets === true) throw new SyntaxError(syntaxError2("closing", "]"));
        state.output = utils.escapeLast(state.output, "[");
        decrement("brackets");
      }
      while (state.parens > 0) {
        if (opts.strictBrackets === true) throw new SyntaxError(syntaxError2("closing", ")"));
        state.output = utils.escapeLast(state.output, "(");
        decrement("parens");
      }
      while (state.braces > 0) {
        if (opts.strictBrackets === true) throw new SyntaxError(syntaxError2("closing", "}"));
        state.output = utils.escapeLast(state.output, "{");
        decrement("braces");
      }
      if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) {
        push2({ type: "maybe_slash", value: "", output: `${SLASH_LITERAL}?` });
      }
      if (state.backtrack === true) {
        state.output = "";
        for (const token2 of state.tokens) {
          state.output += token2.output != null ? token2.output : token2.value;
          if (token2.suffix) {
            state.output += token2.suffix;
          }
        }
      }
      return state;
    }, "parse");
    parse12.fastpaths = (input, options2) => {
      const opts = { ...options2 };
      const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
      const len = input.length;
      if (len > max) {
        throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
      }
      input = REPLACEMENTS[input] || input;
      const {
        DOT_LITERAL,
        SLASH_LITERAL,
        ONE_CHAR,
        DOTS_SLASH,
        NO_DOT,
        NO_DOTS,
        NO_DOTS_SLASH,
        STAR,
        START_ANCHOR
      } = constants4.globChars(opts.windows);
      const nodot = opts.dot ? NO_DOTS : NO_DOT;
      const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
      const capture = opts.capture ? "" : "?:";
      const state = { negated: false, prefix: "" };
      let star3 = opts.bash === true ? ".*?" : STAR;
      if (opts.capture) {
        star3 = `(${star3})`;
      }
      const globstar = /* @__PURE__ */ __name((opts2) => {
        if (opts2.noglobstar === true) return star3;
        return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
      }, "globstar");
      const create3 = /* @__PURE__ */ __name((str2) => {
        switch (str2) {
          case "*":
            return `${nodot}${ONE_CHAR}${star3}`;
          case ".*":
            return `${DOT_LITERAL}${ONE_CHAR}${star3}`;
          case "*.*":
            return `${nodot}${star3}${DOT_LITERAL}${ONE_CHAR}${star3}`;
          case "*/*":
            return `${nodot}${star3}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star3}`;
          case "**":
            return nodot + globstar(opts);
          case "**/*":
            return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star3}`;
          case "**/*.*":
            return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star3}${DOT_LITERAL}${ONE_CHAR}${star3}`;
          case "**/.*":
            return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star3}`;
          default: {
            const match2 = /^(.*?)\.(\w+)$/.exec(str2);
            if (!match2) return;
            const source3 = create3(match2[1]);
            if (!source3) return;
            return source3 + DOT_LITERAL + match2[2];
          }
        }
      }, "create");
      const output = utils.removePrefix(input, state);
      let source2 = create3(output);
      if (source2 && opts.strictSlashes !== true) {
        source2 += `${SLASH_LITERAL}?`;
      }
      return source2;
    };
    module2.exports = parse12;
  }
});

// packages/core/node_modules/picomatch/lib/picomatch.js
var require_picomatch = __commonJS({
  "packages/core/node_modules/picomatch/lib/picomatch.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var scan = require_scan();
    var parse12 = require_parse6();
    var utils = require_utils14();
    var constants4 = require_constants11();
    var isObject3 = /* @__PURE__ */ __name((val) => val && typeof val === "object" && !Array.isArray(val), "isObject");
    var picomatch3 = /* @__PURE__ */ __name((glob2, options2, returnState = false) => {
      if (Array.isArray(glob2)) {
        const fns = glob2.map((input) => picomatch3(input, options2, returnState));
        const arrayMatcher = /* @__PURE__ */ __name((str2) => {
          for (const isMatch of fns) {
            const state2 = isMatch(str2);
            if (state2) return state2;
          }
          return false;
        }, "arrayMatcher");
        return arrayMatcher;
      }
      const isState = isObject3(glob2) && glob2.tokens && glob2.input;
      if (glob2 === "" || typeof glob2 !== "string" && !isState) {
        throw new TypeError("Expected pattern to be a non-empty string");
      }
      const opts = options2 || {};
      const posix3 = opts.windows;
      const regex3 = isState ? picomatch3.compileRe(glob2, options2) : picomatch3.makeRe(glob2, options2, false, true);
      const state = regex3.state;
      delete regex3.state;
      let isIgnored = /* @__PURE__ */ __name(() => false, "isIgnored");
      if (opts.ignore) {
        const ignoreOpts = { ...options2, ignore: null, onMatch: null, onResult: null };
        isIgnored = picomatch3(opts.ignore, ignoreOpts, returnState);
      }
      const matcher = /* @__PURE__ */ __name((input, returnObject = false) => {
        const { isMatch, match: match2, output } = picomatch3.test(input, regex3, options2, { glob: glob2, posix: posix3 });
        const result = { glob: glob2, state, regex: regex3, posix: posix3, input, output, match: match2, isMatch };
        if (typeof opts.onResult === "function") {
          opts.onResult(result);
        }
        if (isMatch === false) {
          result.isMatch = false;
          return returnObject ? result : false;
        }
        if (isIgnored(input)) {
          if (typeof opts.onIgnore === "function") {
            opts.onIgnore(result);
          }
          result.isMatch = false;
          return returnObject ? result : false;
        }
        if (typeof opts.onMatch === "function") {
          opts.onMatch(result);
        }
        return returnObject ? result : true;
      }, "matcher");
      if (returnState) {
        matcher.state = state;
      }
      return matcher;
    }, "picomatch");
    picomatch3.test = (input, regex3, options2, { glob: glob2, posix: posix3 } = {}) => {
      if (typeof input !== "string") {
        throw new TypeError("Expected input to be a string");
      }
      if (input === "") {
        return { isMatch: false, output: "" };
      }
      const opts = options2 || {};
      const format4 = opts.format || (posix3 ? utils.toPosixSlashes : null);
      let match2 = input === glob2;
      let output = match2 && format4 ? format4(input) : input;
      if (match2 === false) {
        output = format4 ? format4(input) : input;
        match2 = output === glob2;
      }
      if (match2 === false || opts.capture === true) {
        if (opts.matchBase === true || opts.basename === true) {
          match2 = picomatch3.matchBase(input, regex3, options2, posix3);
        } else {
          match2 = regex3.exec(output);
        }
      }
      return { isMatch: Boolean(match2), match: match2, output };
    };
    picomatch3.matchBase = (input, glob2, options2) => {
      const regex3 = glob2 instanceof RegExp ? glob2 : picomatch3.makeRe(glob2, options2);
      return regex3.test(utils.basename(input));
    };
    picomatch3.isMatch = (str2, patterns, options2) => picomatch3(patterns, options2)(str2);
    picomatch3.parse = (pattern, options2) => {
      if (Array.isArray(pattern)) return pattern.map((p) => picomatch3.parse(p, options2));
      return parse12(pattern, { ...options2, fastpaths: false });
    };
    picomatch3.scan = (input, options2) => scan(input, options2);
    picomatch3.compileRe = (state, options2, returnOutput = false, returnState = false) => {
      if (returnOutput === true) {
        return state.output;
      }
      const opts = options2 || {};
      const prepend = opts.contains ? "" : "^";
      const append2 = opts.contains ? "" : "$";
      let source2 = `${prepend}(?:${state.output})${append2}`;
      if (state && state.negated === true) {
        source2 = `^(?!${source2}).*$`;
      }
      const regex3 = picomatch3.toRegex(source2, options2);
      if (returnState === true) {
        regex3.state = state;
      }
      return regex3;
    };
    picomatch3.makeRe = (input, options2 = {}, returnOutput = false, returnState = false) => {
      if (!input || typeof input !== "string") {
        throw new TypeError("Expected a non-empty string");
      }
      let parsed = { negated: false, fastpaths: true };
      if (options2.fastpaths !== false && (input[0] === "." || input[0] === "*")) {
        parsed.output = parse12.fastpaths(input, options2);
      }
      if (!parsed.output) {
        parsed = parse12(input, options2);
      }
      return picomatch3.compileRe(parsed, options2, returnOutput, returnState);
    };
    picomatch3.toRegex = (source2, options2) => {
      try {
        const opts = options2 || {};
        return new RegExp(source2, opts.flags || (opts.nocase ? "i" : ""));
      } catch (err) {
        if (options2 && options2.debug === true) throw err;
        return /$^/;
      }
    };
    picomatch3.constants = constants4;
    module2.exports = picomatch3;
  }
});

// packages/core/node_modules/picomatch/index.js
var require_picomatch2 = __commonJS({
  "packages/core/node_modules/picomatch/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var pico = require_picomatch();
    var utils = require_utils14();
    function picomatch3(glob2, options2, returnState = false) {
      if (options2 && (options2.windows === null || options2.windows === void 0)) {
        options2 = { ...options2, windows: utils.isWindows() };
      }
      return pico(glob2, options2, returnState);
    }
    __name(picomatch3, "picomatch");
    Object.assign(picomatch3, pico);
    module2.exports = picomatch3;
  }
});

// packages/core/dist/src/utils/filesearch/ignore.js
import fs48 from "node:fs";
import path53 from "node:path";
function loadIgnoreRules(options2) {
  const ignorer = new Ignore2();
  if (options2.useGitignore) {
    const gitignorePath = path53.join(options2.projectRoot, ".gitignore");
    if (fs48.existsSync(gitignorePath)) {
      ignorer.add(fs48.readFileSync(gitignorePath, "utf8"));
    }
  }
  if (options2.useQwenignore) {
    const qwenignorePath = path53.join(options2.projectRoot, ".qwenignore");
    if (fs48.existsSync(qwenignorePath)) {
      ignorer.add(fs48.readFileSync(qwenignorePath, "utf8"));
    }
  }
  const ignoreDirs = [".git", ...options2.ignoreDirs];
  ignorer.add(ignoreDirs.map((dir) => {
    if (dir.endsWith("/")) {
      return dir;
    }
    return `${dir}/`;
  }));
  return ignorer;
}
var import_ignore5, import_picomatch, hasFileExtension, Ignore2;
var init_ignore2 = __esm({
  "packages/core/dist/src/utils/filesearch/ignore.js"() {
    "use strict";
    init_esbuild_shims();
    import_ignore5 = __toESM(require_ignore(), 1);
    import_picomatch = __toESM(require_picomatch2(), 1);
    hasFileExtension = (0, import_picomatch.default)("**/*[*.]*");
    __name(loadIgnoreRules, "loadIgnoreRules");
    Ignore2 = class {
      static {
        __name(this, "Ignore");
      }
      allPatterns = [];
      dirIgnorer = (0, import_ignore5.default)();
      fileIgnorer = (0, import_ignore5.default)();
      /**
       * Adds one or more ignore patterns.
       * @param patterns A single pattern string or an array of pattern strings.
       *                 Each pattern can be a glob-like string similar to .gitignore rules.
       * @returns The `Ignore` instance for chaining.
       */
      add(patterns) {
        if (typeof patterns === "string") {
          patterns = patterns.split(/\r?\n/);
        }
        for (const p of patterns) {
          const pattern = p.trim();
          if (pattern === "" || pattern.startsWith("#")) {
            continue;
          }
          this.allPatterns.push(pattern);
          const isPositiveDirPattern = pattern.endsWith("/") && !pattern.startsWith("!");
          if (isPositiveDirPattern) {
            this.dirIgnorer.add(pattern);
          } else {
            this.fileIgnorer.add(pattern);
            if (!hasFileExtension(pattern)) {
              this.dirIgnorer.add(pattern);
            }
          }
        }
        return this;
      }
      /**
       * Returns a predicate that matches explicit directory ignore patterns (patterns ending with '/').
       * @returns {(dirPath: string) => boolean}
       */
      getDirectoryFilter() {
        return (dirPath) => this.dirIgnorer.ignores(dirPath);
      }
      /**
       * Returns a predicate that matches file ignore patterns (all patterns not ending with '/').
       * Note: This may also match directories if a file pattern matches a directory name, but all explicit directory patterns are handled by getDirectoryFilter.
       * @returns {(filePath: string) => boolean}
       */
      getFileFilter() {
        return (filePath) => this.fileIgnorer.ignores(filePath);
      }
      /**
       * Returns a string representing the current set of ignore patterns.
       * This can be used to generate a unique identifier for the ignore configuration,
       * useful for caching purposes.
       * @returns A string fingerprint of the ignore patterns.
       */
      getFingerprint() {
        return this.allPatterns.join("\n");
      }
    };
  }
});

// packages/core/dist/src/utils/filesearch/result-cache.js
var ResultCache;
var init_result_cache = __esm({
  "packages/core/dist/src/utils/filesearch/result-cache.js"() {
    "use strict";
    init_esbuild_shims();
    ResultCache = class {
      static {
        __name(this, "ResultCache");
      }
      allFiles;
      cache;
      hits = 0;
      misses = 0;
      constructor(allFiles) {
        this.allFiles = allFiles;
        this.cache = /* @__PURE__ */ new Map();
      }
      /**
       * Retrieves cached search results for a given query, or provides a base set
       * of files to search from.
       * @param query The search query pattern.
       * @returns An object containing the files to search and a boolean indicating
       *          if the result is an exact cache hit.
       */
      async get(query) {
        const isCacheHit = this.cache.has(query);
        if (isCacheHit) {
          this.hits++;
          return { files: this.cache.get(query), isExactMatch: true };
        }
        this.misses++;
        let bestBaseQuery = "";
        for (const key of this.cache?.keys?.() ?? []) {
          if (query.startsWith(key) && key.length > bestBaseQuery.length) {
            bestBaseQuery = key;
          }
        }
        const filesToSearch = bestBaseQuery ? this.cache.get(bestBaseQuery) : this.allFiles;
        return { files: filesToSearch, isExactMatch: false };
      }
      /**
       * Stores search results in the cache.
       * @param query The search query pattern.
       * @param results The matching file paths to cache.
       */
      set(query, results) {
        this.cache.set(query, results);
      }
    };
  }
});

// packages/core/node_modules/fdir/dist/utils.js
var require_utils15 = __commonJS({
  "packages/core/node_modules/fdir/dist/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.normalizePath = exports2.isRootDirectory = exports2.convertSlashes = exports2.cleanPath = void 0;
    var path_1 = __require("path");
    function cleanPath(path108) {
      let normalized2 = (0, path_1.normalize)(path108);
      if (normalized2.length > 1 && normalized2[normalized2.length - 1] === path_1.sep)
        normalized2 = normalized2.substring(0, normalized2.length - 1);
      return normalized2;
    }
    __name(cleanPath, "cleanPath");
    exports2.cleanPath = cleanPath;
    var SLASHES_REGEX = /[\\/]/g;
    function convertSlashes(path108, separator) {
      return path108.replace(SLASHES_REGEX, separator);
    }
    __name(convertSlashes, "convertSlashes");
    exports2.convertSlashes = convertSlashes;
    var WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i;
    function isRootDirectory(path108) {
      return path108 === "/" || WINDOWS_ROOT_DIR_REGEX.test(path108);
    }
    __name(isRootDirectory, "isRootDirectory");
    exports2.isRootDirectory = isRootDirectory;
    function normalizePath(path108, options2) {
      const { resolvePaths, normalizePath: normalizePath2, pathSeparator } = options2;
      const pathNeedsCleaning = process.platform === "win32" && path108.includes("/") || path108.startsWith(".");
      if (resolvePaths)
        path108 = (0, path_1.resolve)(path108);
      if (normalizePath2 || pathNeedsCleaning)
        path108 = cleanPath(path108);
      if (path108 === ".")
        return "";
      const needsSeperator = path108[path108.length - 1] !== pathSeparator;
      return convertSlashes(needsSeperator ? path108 + pathSeparator : path108, pathSeparator);
    }
    __name(normalizePath, "normalizePath");
    exports2.normalizePath = normalizePath;
  }
});

// packages/core/node_modules/fdir/dist/api/functions/join-path.js
var require_join_path = __commonJS({
  "packages/core/node_modules/fdir/dist/api/functions/join-path.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.build = exports2.joinDirectoryPath = exports2.joinPathWithBasePath = void 0;
    var path_1 = __require("path");
    var utils_1 = require_utils15();
    function joinPathWithBasePath(filename, directoryPath) {
      return directoryPath + filename;
    }
    __name(joinPathWithBasePath, "joinPathWithBasePath");
    exports2.joinPathWithBasePath = joinPathWithBasePath;
    function joinPathWithRelativePath(root, options2) {
      return function(filename, directoryPath) {
        const sameRoot = directoryPath.startsWith(root);
        if (sameRoot)
          return directoryPath.replace(root, "") + filename;
        else
          return (0, utils_1.convertSlashes)((0, path_1.relative)(root, directoryPath), options2.pathSeparator) + options2.pathSeparator + filename;
      };
    }
    __name(joinPathWithRelativePath, "joinPathWithRelativePath");
    function joinPath(filename) {
      return filename;
    }
    __name(joinPath, "joinPath");
    function joinDirectoryPath(filename, directoryPath, separator) {
      return directoryPath + filename + separator;
    }
    __name(joinDirectoryPath, "joinDirectoryPath");
    exports2.joinDirectoryPath = joinDirectoryPath;
    function build(root, options2) {
      const { relativePaths, includeBasePath } = options2;
      return relativePaths && root ? joinPathWithRelativePath(root, options2) : includeBasePath ? joinPathWithBasePath : joinPath;
    }
    __name(build, "build");
    exports2.build = build;
  }
});

// packages/core/node_modules/fdir/dist/api/functions/push-directory.js
var require_push_directory = __commonJS({
  "packages/core/node_modules/fdir/dist/api/functions/push-directory.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.build = void 0;
    function pushDirectoryWithRelativePath(root) {
      return function(directoryPath, paths) {
        paths.push(directoryPath.substring(root.length) || ".");
      };
    }
    __name(pushDirectoryWithRelativePath, "pushDirectoryWithRelativePath");
    function pushDirectoryFilterWithRelativePath(root) {
      return function(directoryPath, paths, filters) {
        const relativePath = directoryPath.substring(root.length) || ".";
        if (filters.every((filter4) => filter4(relativePath, true))) {
          paths.push(relativePath);
        }
      };
    }
    __name(pushDirectoryFilterWithRelativePath, "pushDirectoryFilterWithRelativePath");
    var pushDirectory = /* @__PURE__ */ __name((directoryPath, paths) => {
      paths.push(directoryPath || ".");
    }, "pushDirectory");
    var pushDirectoryFilter = /* @__PURE__ */ __name((directoryPath, paths, filters) => {
      const path108 = directoryPath || ".";
      if (filters.every((filter4) => filter4(path108, true))) {
        paths.push(path108);
      }
    }, "pushDirectoryFilter");
    var empty = /* @__PURE__ */ __name(() => {
    }, "empty");
    function build(root, options2) {
      const { includeDirs, filters, relativePaths } = options2;
      if (!includeDirs)
        return empty;
      if (relativePaths)
        return filters && filters.length ? pushDirectoryFilterWithRelativePath(root) : pushDirectoryWithRelativePath(root);
      return filters && filters.length ? pushDirectoryFilter : pushDirectory;
    }
    __name(build, "build");
    exports2.build = build;
  }
});

// packages/core/node_modules/fdir/dist/api/functions/push-file.js
var require_push_file = __commonJS({
  "packages/core/node_modules/fdir/dist/api/functions/push-file.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.build = void 0;
    var pushFileFilterAndCount = /* @__PURE__ */ __name((filename, _paths, counts, filters) => {
      if (filters.every((filter4) => filter4(filename, false)))
        counts.files++;
    }, "pushFileFilterAndCount");
    var pushFileFilter = /* @__PURE__ */ __name((filename, paths, _counts, filters) => {
      if (filters.every((filter4) => filter4(filename, false)))
        paths.push(filename);
    }, "pushFileFilter");
    var pushFileCount = /* @__PURE__ */ __name((_filename, _paths, counts, _filters) => {
      counts.files++;
    }, "pushFileCount");
    var pushFile = /* @__PURE__ */ __name((filename, paths) => {
      paths.push(filename);
    }, "pushFile");
    var empty = /* @__PURE__ */ __name(() => {
    }, "empty");
    function build(options2) {
      const { excludeFiles, filters, onlyCounts } = options2;
      if (excludeFiles)
        return empty;
      if (filters && filters.length) {
        return onlyCounts ? pushFileFilterAndCount : pushFileFilter;
      } else if (onlyCounts) {
        return pushFileCount;
      } else {
        return pushFile;
      }
    }
    __name(build, "build");
    exports2.build = build;
  }
});

// packages/core/node_modules/fdir/dist/api/functions/get-array.js
var require_get_array = __commonJS({
  "packages/core/node_modules/fdir/dist/api/functions/get-array.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.build = void 0;
    var getArray = /* @__PURE__ */ __name((paths) => {
      return paths;
    }, "getArray");
    var getArrayGroup = /* @__PURE__ */ __name(() => {
      return [""].slice(0, 0);
    }, "getArrayGroup");
    function build(options2) {
      return options2.group ? getArrayGroup : getArray;
    }
    __name(build, "build");
    exports2.build = build;
  }
});

// packages/core/node_modules/fdir/dist/api/functions/group-files.js
var require_group_files = __commonJS({
  "packages/core/node_modules/fdir/dist/api/functions/group-files.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.build = void 0;
    var groupFiles = /* @__PURE__ */ __name((groups, directory, files) => {
      groups.push({ directory, files, dir: directory });
    }, "groupFiles");
    var empty = /* @__PURE__ */ __name(() => {
    }, "empty");
    function build(options2) {
      return options2.group ? groupFiles : empty;
    }
    __name(build, "build");
    exports2.build = build;
  }
});

// packages/core/node_modules/fdir/dist/api/functions/resolve-symlink.js
var require_resolve_symlink = __commonJS({
  "packages/core/node_modules/fdir/dist/api/functions/resolve-symlink.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
      return mod2 && mod2.__esModule ? mod2 : { "default": mod2 };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.build = void 0;
    var fs_1 = __importDefault(__require("fs"));
    var path_1 = __require("path");
    var resolveSymlinksAsync = /* @__PURE__ */ __name(function(path108, state, callback) {
      const { queue, options: { suppressErrors } } = state;
      queue.enqueue();
      fs_1.default.realpath(path108, (error, resolvedPath) => {
        if (error)
          return queue.dequeue(suppressErrors ? null : error, state);
        fs_1.default.stat(resolvedPath, (error2, stat7) => {
          if (error2)
            return queue.dequeue(suppressErrors ? null : error2, state);
          if (stat7.isDirectory() && isRecursive(path108, resolvedPath, state))
            return queue.dequeue(null, state);
          callback(stat7, resolvedPath);
          queue.dequeue(null, state);
        });
      });
    }, "resolveSymlinksAsync");
    var resolveSymlinks = /* @__PURE__ */ __name(function(path108, state, callback) {
      const { queue, options: { suppressErrors } } = state;
      queue.enqueue();
      try {
        const resolvedPath = fs_1.default.realpathSync(path108);
        const stat7 = fs_1.default.statSync(resolvedPath);
        if (stat7.isDirectory() && isRecursive(path108, resolvedPath, state))
          return;
        callback(stat7, resolvedPath);
      } catch (e2) {
        if (!suppressErrors)
          throw e2;
      }
    }, "resolveSymlinks");
    function build(options2, isSynchronous) {
      if (!options2.resolveSymlinks || options2.excludeSymlinks)
        return null;
      return isSynchronous ? resolveSymlinks : resolveSymlinksAsync;
    }
    __name(build, "build");
    exports2.build = build;
    function isRecursive(path108, resolved, state) {
      if (state.options.useRealPaths)
        return isRecursiveUsingRealPaths(resolved, state);
      let parent = (0, path_1.dirname)(path108);
      let depth = 1;
      while (parent !== state.root && depth < 2) {
        const resolvedPath = state.symlinks.get(parent);
        const isSameRoot = !!resolvedPath && (resolvedPath === resolved || resolvedPath.startsWith(resolved) || resolved.startsWith(resolvedPath));
        if (isSameRoot)
          depth++;
        else
          parent = (0, path_1.dirname)(parent);
      }
      state.symlinks.set(path108, resolved);
      return depth > 1;
    }
    __name(isRecursive, "isRecursive");
    function isRecursiveUsingRealPaths(resolved, state) {
      return state.visited.includes(resolved + state.options.pathSeparator);
    }
    __name(isRecursiveUsingRealPaths, "isRecursiveUsingRealPaths");
  }
});

// packages/core/node_modules/fdir/dist/api/functions/invoke-callback.js
var require_invoke_callback = __commonJS({
  "packages/core/node_modules/fdir/dist/api/functions/invoke-callback.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.build = void 0;
    var onlyCountsSync = /* @__PURE__ */ __name((state) => {
      return state.counts;
    }, "onlyCountsSync");
    var groupsSync = /* @__PURE__ */ __name((state) => {
      return state.groups;
    }, "groupsSync");
    var defaultSync = /* @__PURE__ */ __name((state) => {
      return state.paths;
    }, "defaultSync");
    var limitFilesSync = /* @__PURE__ */ __name((state) => {
      return state.paths.slice(0, state.options.maxFiles);
    }, "limitFilesSync");
    var onlyCountsAsync = /* @__PURE__ */ __name((state, error, callback) => {
      report(error, callback, state.counts, state.options.suppressErrors);
      return null;
    }, "onlyCountsAsync");
    var defaultAsync = /* @__PURE__ */ __name((state, error, callback) => {
      report(error, callback, state.paths, state.options.suppressErrors);
      return null;
    }, "defaultAsync");
    var limitFilesAsync = /* @__PURE__ */ __name((state, error, callback) => {
      report(error, callback, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors);
      return null;
    }, "limitFilesAsync");
    var groupsAsync = /* @__PURE__ */ __name((state, error, callback) => {
      report(error, callback, state.groups, state.options.suppressErrors);
      return null;
    }, "groupsAsync");
    function report(error, callback, output, suppressErrors) {
      if (error && !suppressErrors)
        callback(error, output);
      else
        callback(null, output);
    }
    __name(report, "report");
    function build(options2, isSynchronous) {
      const { onlyCounts, group, maxFiles } = options2;
      if (onlyCounts)
        return isSynchronous ? onlyCountsSync : onlyCountsAsync;
      else if (group)
        return isSynchronous ? groupsSync : groupsAsync;
      else if (maxFiles)
        return isSynchronous ? limitFilesSync : limitFilesAsync;
      else
        return isSynchronous ? defaultSync : defaultAsync;
    }
    __name(build, "build");
    exports2.build = build;
  }
});

// packages/core/node_modules/fdir/dist/api/functions/walk-directory.js
var require_walk_directory = __commonJS({
  "packages/core/node_modules/fdir/dist/api/functions/walk-directory.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
      return mod2 && mod2.__esModule ? mod2 : { "default": mod2 };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.build = void 0;
    var fs_1 = __importDefault(__require("fs"));
    var readdirOpts = { withFileTypes: true };
    var walkAsync = /* @__PURE__ */ __name((state, crawlPath, directoryPath, currentDepth, callback) => {
      state.queue.enqueue();
      if (currentDepth < 0)
        return state.queue.dequeue(null, state);
      state.visited.push(crawlPath);
      state.counts.directories++;
      fs_1.default.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => {
        callback(entries, directoryPath, currentDepth);
        state.queue.dequeue(state.options.suppressErrors ? null : error, state);
      });
    }, "walkAsync");
    var walkSync = /* @__PURE__ */ __name((state, crawlPath, directoryPath, currentDepth, callback) => {
      if (currentDepth < 0)
        return;
      state.visited.push(crawlPath);
      state.counts.directories++;
      let entries = [];
      try {
        entries = fs_1.default.readdirSync(crawlPath || ".", readdirOpts);
      } catch (e2) {
        if (!state.options.suppressErrors)
          throw e2;
      }
      callback(entries, directoryPath, currentDepth);
    }, "walkSync");
    function build(isSynchronous) {
      return isSynchronous ? walkSync : walkAsync;
    }
    __name(build, "build");
    exports2.build = build;
  }
});

// packages/core/node_modules/fdir/dist/api/queue.js
var require_queue = __commonJS({
  "packages/core/node_modules/fdir/dist/api/queue.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Queue = void 0;
    var Queue = class {
      static {
        __name(this, "Queue");
      }
      onQueueEmpty;
      count = 0;
      constructor(onQueueEmpty) {
        this.onQueueEmpty = onQueueEmpty;
      }
      enqueue() {
        this.count++;
        return this.count;
      }
      dequeue(error, output) {
        if (this.onQueueEmpty && (--this.count <= 0 || error)) {
          this.onQueueEmpty(error, output);
          if (error) {
            output.controller.abort();
            this.onQueueEmpty = void 0;
          }
        }
      }
    };
    exports2.Queue = Queue;
  }
});

// packages/core/node_modules/fdir/dist/api/counter.js
var require_counter = __commonJS({
  "packages/core/node_modules/fdir/dist/api/counter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Counter = void 0;
    var Counter = class {
      static {
        __name(this, "Counter");
      }
      _files = 0;
      _directories = 0;
      set files(num) {
        this._files = num;
      }
      get files() {
        return this._files;
      }
      set directories(num) {
        this._directories = num;
      }
      get directories() {
        return this._directories;
      }
      /**
       * @deprecated use `directories` instead
       */
      /* c8 ignore next 3 */
      get dirs() {
        return this._directories;
      }
    };
    exports2.Counter = Counter;
  }
});

// packages/core/node_modules/fdir/dist/api/walker.js
var require_walker = __commonJS({
  "packages/core/node_modules/fdir/dist/api/walker.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc2 = Object.getOwnPropertyDescriptor(m, k);
      if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m[k];
        }, "get") };
      }
      Object.defineProperty(o2, k2, desc2);
    } : function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o2[k2] = m[k];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v) {
      Object.defineProperty(o2, "default", { enumerable: true, value: v });
    } : function(o2, v) {
      o2["default"] = v;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod2) {
      if (mod2 && mod2.__esModule) return mod2;
      var result = {};
      if (mod2 != null) {
        for (var k in mod2) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod2, k)) __createBinding(result, mod2, k);
      }
      __setModuleDefault(result, mod2);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Walker = void 0;
    var path_1 = __require("path");
    var utils_1 = require_utils15();
    var joinPath = __importStar(require_join_path());
    var pushDirectory = __importStar(require_push_directory());
    var pushFile = __importStar(require_push_file());
    var getArray = __importStar(require_get_array());
    var groupFiles = __importStar(require_group_files());
    var resolveSymlink = __importStar(require_resolve_symlink());
    var invokeCallback = __importStar(require_invoke_callback());
    var walkDirectory = __importStar(require_walk_directory());
    var queue_1 = require_queue();
    var counter_1 = require_counter();
    var Walker = class {
      static {
        __name(this, "Walker");
      }
      root;
      isSynchronous;
      state;
      joinPath;
      pushDirectory;
      pushFile;
      getArray;
      groupFiles;
      resolveSymlink;
      walkDirectory;
      callbackInvoker;
      constructor(root, options2, callback) {
        this.isSynchronous = !callback;
        this.callbackInvoker = invokeCallback.build(options2, this.isSynchronous);
        this.root = (0, utils_1.normalizePath)(root, options2);
        this.state = {
          root: (0, utils_1.isRootDirectory)(this.root) ? this.root : this.root.slice(0, -1),
          // Perf: we explicitly tell the compiler to optimize for String arrays
          paths: [""].slice(0, 0),
          groups: [],
          counts: new counter_1.Counter(),
          options: options2,
          queue: new queue_1.Queue((error, state) => this.callbackInvoker(state, error, callback)),
          symlinks: /* @__PURE__ */ new Map(),
          visited: [""].slice(0, 0),
          controller: new AbortController()
        };
        this.joinPath = joinPath.build(this.root, options2);
        this.pushDirectory = pushDirectory.build(this.root, options2);
        this.pushFile = pushFile.build(options2);
        this.getArray = getArray.build(options2);
        this.groupFiles = groupFiles.build(options2);
        this.resolveSymlink = resolveSymlink.build(options2, this.isSynchronous);
        this.walkDirectory = walkDirectory.build(this.isSynchronous);
      }
      start() {
        this.pushDirectory(this.root, this.state.paths, this.state.options.filters);
        this.walkDirectory(this.state, this.root, this.root, this.state.options.maxDepth, this.walk);
        return this.isSynchronous ? this.callbackInvoker(this.state, null) : null;
      }
      walk = /* @__PURE__ */ __name((entries, directoryPath, depth) => {
        const { paths, options: { filters, resolveSymlinks, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator }, controller } = this.state;
        if (controller.signal.aborted || signal && signal.aborted || maxFiles && paths.length > maxFiles)
          return;
        const files = this.getArray(this.state.paths);
        for (let i = 0; i < entries.length; ++i) {
          const entry = entries[i];
          if (entry.isFile() || entry.isSymbolicLink() && !resolveSymlinks && !excludeSymlinks) {
            const filename = this.joinPath(entry.name, directoryPath);
            this.pushFile(filename, files, this.state.counts, filters);
          } else if (entry.isDirectory()) {
            let path108 = joinPath.joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator);
            if (exclude && exclude(entry.name, path108))
              continue;
            this.pushDirectory(path108, paths, filters);
            this.walkDirectory(this.state, path108, path108, depth - 1, this.walk);
          } else if (this.resolveSymlink && entry.isSymbolicLink()) {
            let path108 = joinPath.joinPathWithBasePath(entry.name, directoryPath);
            this.resolveSymlink(path108, this.state, (stat7, resolvedPath) => {
              if (stat7.isDirectory()) {
                resolvedPath = (0, utils_1.normalizePath)(resolvedPath, this.state.options);
                if (exclude && exclude(entry.name, useRealPaths ? resolvedPath : path108 + pathSeparator))
                  return;
                this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path108 + pathSeparator, depth - 1, this.walk);
              } else {
                resolvedPath = useRealPaths ? resolvedPath : path108;
                const filename = (0, path_1.basename)(resolvedPath);
                const directoryPath2 = (0, utils_1.normalizePath)((0, path_1.dirname)(resolvedPath), this.state.options);
                resolvedPath = this.joinPath(filename, directoryPath2);
                this.pushFile(resolvedPath, files, this.state.counts, filters);
              }
            });
          }
        }
        this.groupFiles(this.state.groups, directoryPath, files);
      }, "walk");
    };
    exports2.Walker = Walker;
  }
});

// packages/core/node_modules/fdir/dist/api/async.js
var require_async3 = __commonJS({
  "packages/core/node_modules/fdir/dist/api/async.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.callback = exports2.promise = void 0;
    var walker_1 = require_walker();
    function promise(root, options2) {
      return new Promise((resolve24, reject) => {
        callback(root, options2, (err, output) => {
          if (err)
            return reject(err);
          resolve24(output);
        });
      });
    }
    __name(promise, "promise");
    exports2.promise = promise;
    function callback(root, options2, callback2) {
      let walker = new walker_1.Walker(root, options2, callback2);
      walker.start();
    }
    __name(callback, "callback");
    exports2.callback = callback;
  }
});

// packages/core/node_modules/fdir/dist/api/sync.js
var require_sync2 = __commonJS({
  "packages/core/node_modules/fdir/dist/api/sync.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.sync = void 0;
    var walker_1 = require_walker();
    function sync2(root, options2) {
      const walker = new walker_1.Walker(root, options2);
      return walker.start();
    }
    __name(sync2, "sync");
    exports2.sync = sync2;
  }
});

// packages/core/node_modules/fdir/dist/builder/api-builder.js
var require_api_builder = __commonJS({
  "packages/core/node_modules/fdir/dist/builder/api-builder.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.APIBuilder = void 0;
    var async_1 = require_async3();
    var sync_1 = require_sync2();
    var APIBuilder = class {
      static {
        __name(this, "APIBuilder");
      }
      root;
      options;
      constructor(root, options2) {
        this.root = root;
        this.options = options2;
      }
      withPromise() {
        return (0, async_1.promise)(this.root, this.options);
      }
      withCallback(cb) {
        (0, async_1.callback)(this.root, this.options, cb);
      }
      sync() {
        return (0, sync_1.sync)(this.root, this.options);
      }
    };
    exports2.APIBuilder = APIBuilder;
  }
});

// packages/core/node_modules/fdir/dist/builder/index.js
var require_builder = __commonJS({
  "packages/core/node_modules/fdir/dist/builder/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Builder = void 0;
    var path_1 = __require("path");
    var api_builder_1 = require_api_builder();
    var pm = null;
    try {
      __require.resolve("picomatch");
      pm = require_picomatch2();
    } catch (_e) {
    }
    var Builder = class {
      static {
        __name(this, "Builder");
      }
      globCache = {};
      options = {
        maxDepth: Infinity,
        suppressErrors: true,
        pathSeparator: path_1.sep,
        filters: []
      };
      globFunction;
      constructor(options2) {
        this.options = { ...this.options, ...options2 };
        this.globFunction = this.options.globFunction;
      }
      group() {
        this.options.group = true;
        return this;
      }
      withPathSeparator(separator) {
        this.options.pathSeparator = separator;
        return this;
      }
      withBasePath() {
        this.options.includeBasePath = true;
        return this;
      }
      withRelativePaths() {
        this.options.relativePaths = true;
        return this;
      }
      withDirs() {
        this.options.includeDirs = true;
        return this;
      }
      withMaxDepth(depth) {
        this.options.maxDepth = depth;
        return this;
      }
      withMaxFiles(limit2) {
        this.options.maxFiles = limit2;
        return this;
      }
      withFullPaths() {
        this.options.resolvePaths = true;
        this.options.includeBasePath = true;
        return this;
      }
      withErrors() {
        this.options.suppressErrors = false;
        return this;
      }
      withSymlinks({ resolvePaths = true } = {}) {
        this.options.resolveSymlinks = true;
        this.options.useRealPaths = resolvePaths;
        return this.withFullPaths();
      }
      withAbortSignal(signal) {
        this.options.signal = signal;
        return this;
      }
      normalize() {
        this.options.normalizePath = true;
        return this;
      }
      filter(predicate) {
        this.options.filters.push(predicate);
        return this;
      }
      onlyDirs() {
        this.options.excludeFiles = true;
        this.options.includeDirs = true;
        return this;
      }
      exclude(predicate) {
        this.options.exclude = predicate;
        return this;
      }
      onlyCounts() {
        this.options.onlyCounts = true;
        return this;
      }
      crawl(root) {
        return new api_builder_1.APIBuilder(root || ".", this.options);
      }
      withGlobFunction(fn) {
        this.globFunction = fn;
        return this;
      }
      /**
       * @deprecated Pass options using the constructor instead:
       * ```ts
       * new fdir(options).crawl("/path/to/root");
       * ```
       * This method will be removed in v7.0
       */
      /* c8 ignore next 4 */
      crawlWithOptions(root, options2) {
        this.options = { ...this.options, ...options2 };
        return new api_builder_1.APIBuilder(root || ".", this.options);
      }
      glob(...patterns) {
        if (this.globFunction) {
          return this.globWithOptions(patterns);
        }
        return this.globWithOptions(patterns, ...[{ dot: true }]);
      }
      globWithOptions(patterns, ...options2) {
        const globFn = this.globFunction || pm;
        if (!globFn) {
          throw new Error("Please specify a glob function to use glob matching.");
        }
        var isMatch = this.globCache[patterns.join("\0")];
        if (!isMatch) {
          isMatch = globFn(patterns, ...options2);
          this.globCache[patterns.join("\0")] = isMatch;
        }
        this.options.filters.push((path108) => isMatch(path108));
        return this;
      }
    };
    exports2.Builder = Builder;
  }
});

// packages/core/node_modules/fdir/dist/types.js
var require_types8 = __commonJS({
  "packages/core/node_modules/fdir/dist/types.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
  }
});

// packages/core/node_modules/fdir/dist/index.js
var require_dist6 = __commonJS({
  "packages/core/node_modules/fdir/dist/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc2 = Object.getOwnPropertyDescriptor(m, k);
      if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m[k];
        }, "get") };
      }
      Object.defineProperty(o2, k2, desc2);
    } : function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o2[k2] = m[k];
    });
    var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.fdir = void 0;
    var builder_1 = require_builder();
    Object.defineProperty(exports2, "fdir", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return builder_1.Builder;
    }, "get") });
    __exportStar(require_types8(), exports2);
  }
});

// packages/core/dist/src/utils/filesearch/crawlCache.js
import crypto15 from "node:crypto";
var crawlCache, cacheTimers, getCacheKey, read, write;
var init_crawlCache = __esm({
  "packages/core/dist/src/utils/filesearch/crawlCache.js"() {
    "use strict";
    init_esbuild_shims();
    crawlCache = /* @__PURE__ */ new Map();
    cacheTimers = /* @__PURE__ */ new Map();
    getCacheKey = /* @__PURE__ */ __name((directory, ignoreContent, maxDepth) => {
      const hash = crypto15.createHash("sha256");
      hash.update(directory);
      hash.update(ignoreContent);
      if (maxDepth !== void 0) {
        hash.update(String(maxDepth));
      }
      return hash.digest("hex");
    }, "getCacheKey");
    read = /* @__PURE__ */ __name((key) => crawlCache.get(key), "read");
    write = /* @__PURE__ */ __name((key, results, ttlMs) => {
      if (cacheTimers.has(key)) {
        clearTimeout(cacheTimers.get(key));
      }
      crawlCache.set(key, results);
      const timerId = setTimeout(() => {
        crawlCache.delete(key);
        cacheTimers.delete(key);
      }, ttlMs);
      cacheTimers.set(key, timerId);
    }, "write");
  }
});

// packages/core/dist/src/utils/filesearch/crawler.js
import path54 from "node:path";
function toPosixPath(p) {
  return p.split(path54.sep).join(path54.posix.sep);
}
async function crawl(options2) {
  if (options2.cache) {
    const cacheKey = getCacheKey(options2.crawlDirectory, options2.ignore.getFingerprint(), options2.maxDepth);
    const cachedResults = read(cacheKey);
    if (cachedResults) {
      return cachedResults;
    }
  }
  const posixCwd = toPosixPath(options2.cwd);
  const posixCrawlDirectory = toPosixPath(options2.crawlDirectory);
  let results;
  try {
    const dirFilter = options2.ignore.getDirectoryFilter();
    const api = new import_fdir.fdir().withRelativePaths().withDirs().withPathSeparator("/").exclude((_, dirPath) => {
      const relativePath = path54.posix.relative(posixCrawlDirectory, dirPath);
      return dirFilter(`${relativePath}/`);
    });
    if (options2.maxDepth !== void 0) {
      api.withMaxDepth(options2.maxDepth);
    }
    results = await api.crawl(options2.crawlDirectory).withPromise();
  } catch (_e) {
    return [];
  }
  const relativeToCrawlDir = path54.posix.relative(posixCwd, posixCrawlDirectory);
  const relativeToCwdResults = results.map((p) => path54.posix.join(relativeToCrawlDir, p));
  if (options2.cache) {
    const cacheKey = getCacheKey(options2.crawlDirectory, options2.ignore.getFingerprint(), options2.maxDepth);
    write(cacheKey, relativeToCwdResults, options2.cacheTtl * 1e3);
  }
  return relativeToCwdResults;
}
var import_fdir;
var init_crawler = __esm({
  "packages/core/dist/src/utils/filesearch/crawler.js"() {
    "use strict";
    init_esbuild_shims();
    import_fdir = __toESM(require_dist6(), 1);
    init_crawlCache();
    __name(toPosixPath, "toPosixPath");
    __name(crawl, "crawl");
  }
});

// node_modules/fzf/dist/fzf.es.js
function normalizeRune(rune) {
  if (rune < 192 || rune > 8580) {
    return rune;
  }
  const normalizedChar = normalized[rune];
  if (normalizedChar !== void 0)
    return normalizedChar.codePointAt(0);
  return rune;
}
function toShort(number) {
  return number;
}
function toInt(number) {
  return number;
}
function maxInt16(num1, num2) {
  return num1 > num2 ? num1 : num2;
}
function indexAt(index, max, forward) {
  if (forward) {
    return index;
  }
  return max - index - 1;
}
function createPosSet(withPos) {
  if (withPos) {
    return /* @__PURE__ */ new Set();
  }
  return null;
}
function alloc16(offset, slab2, size) {
  if (slab2 !== null && slab2.i16.length > offset + size) {
    const subarray = slab2.i16.subarray(offset, offset + size);
    return [offset + size, subarray];
  }
  return [offset, new Int16Array(size)];
}
function alloc32(offset, slab2, size) {
  if (slab2 !== null && slab2.i32.length > offset + size) {
    const subarray = slab2.i32.subarray(offset, offset + size);
    return [offset + size, subarray];
  }
  return [offset, new Int32Array(size)];
}
function charClassOfAscii(rune) {
  if (rune >= SMALL_A_RUNE && rune <= SMALL_Z_RUNE) {
    return 1;
  } else if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) {
    return 2;
  } else if (rune >= NUMERAL_ZERO_RUNE && rune <= NUMERAL_NINE_RUNE) {
    return 4;
  } else {
    return 0;
  }
}
function charClassOfNonAscii(rune) {
  const char = String.fromCodePoint(rune);
  if (char !== char.toUpperCase()) {
    return 1;
  } else if (char !== char.toLowerCase()) {
    return 2;
  } else if (char.match(new RegExp("\\p{Number}", "gu")) !== null) {
    return 4;
  } else if (char.match(new RegExp("\\p{Letter}", "gu")) !== null) {
    return 3;
  }
  return 0;
}
function charClassOf(rune) {
  if (rune <= MAX_ASCII) {
    return charClassOfAscii(rune);
  }
  return charClassOfNonAscii(rune);
}
function bonusFor(prevClass, currClass) {
  if (prevClass === 0 && currClass !== 0) {
    return BONUS_BOUNDARY;
  } else if (prevClass === 1 && currClass === 2 || prevClass !== 4 && currClass === 4) {
    return BONUS_CAMEL_123;
  } else if (currClass === 0) {
    return BONUS_NON_WORD;
  }
  return 0;
}
function bonusAt(input, idx) {
  if (idx === 0) {
    return BONUS_BOUNDARY;
  }
  return bonusFor(charClassOf(input[idx - 1]), charClassOf(input[idx]));
}
function trySkip(input, caseSensitive, char, from) {
  let rest = input.slice(from);
  let idx = rest.indexOf(char);
  if (idx === 0) {
    return from;
  }
  if (!caseSensitive && char >= SMALL_A_RUNE && char <= SMALL_Z_RUNE) {
    if (idx > 0) {
      rest = rest.slice(0, idx);
    }
    const uidx = rest.indexOf(char - 32);
    if (uidx >= 0) {
      idx = uidx;
    }
  }
  if (idx < 0) {
    return -1;
  }
  return from + idx;
}
function isAscii(runes) {
  for (const rune of runes) {
    if (rune >= 128) {
      return false;
    }
  }
  return true;
}
function asciiFuzzyIndex(input, pattern, caseSensitive) {
  if (!isAscii(input)) {
    return 0;
  }
  if (!isAscii(pattern)) {
    return -1;
  }
  let firstIdx = 0, idx = 0;
  for (let pidx = 0; pidx < pattern.length; pidx++) {
    idx = trySkip(input, caseSensitive, pattern[pidx], idx);
    if (idx < 0) {
      return -1;
    }
    if (pidx === 0 && idx > 0) {
      firstIdx = idx - 1;
    }
    idx++;
  }
  return firstIdx;
}
function calculateScore(caseSensitive, normalize10, text, pattern, sidx, eidx, withPos) {
  let pidx = 0, score = 0, inGap = false, consecutive = 0, firstBonus = toShort(0);
  const pos2 = createPosSet(withPos);
  let prevCharClass = 0;
  if (sidx > 0) {
    prevCharClass = charClassOf(text[sidx - 1]);
  }
  for (let idx = sidx; idx < eidx; idx++) {
    let rune = text[idx];
    const charClass = charClassOf(rune);
    if (!caseSensitive) {
      if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) {
        rune += 32;
      } else if (rune > MAX_ASCII) {
        rune = String.fromCodePoint(rune).toLowerCase().codePointAt(0);
      }
    }
    if (normalize10) {
      rune = normalizeRune(rune);
    }
    if (rune === pattern[pidx]) {
      if (withPos && pos2 !== null) {
        pos2.add(idx);
      }
      score += SCORE_MATCH;
      let bonus = bonusFor(prevCharClass, charClass);
      if (consecutive === 0) {
        firstBonus = bonus;
      } else {
        if (bonus === BONUS_BOUNDARY) {
          firstBonus = bonus;
        }
        bonus = maxInt16(maxInt16(bonus, firstBonus), BONUS_CONSECUTIVE);
      }
      if (pidx === 0) {
        score += bonus * BONUS_FIRST_CHAR_MULTIPLIER;
      } else {
        score += bonus;
      }
      inGap = false;
      consecutive++;
      pidx++;
    } else {
      if (inGap) {
        score += SCORE_GAP_EXTENTION;
      } else {
        score += SCORE_GAP_START;
      }
      inGap = true;
      consecutive = 0;
      firstBonus = 0;
    }
    prevCharClass = charClass;
  }
  return [score, pos2];
}
function makeSlab(size16, size32) {
  return {
    i16: new Int16Array(size16),
    i32: new Int32Array(size32)
  };
}
function getResultFromScoreMap(scoreMap, limit2) {
  const scoresInDesc = Object.keys(scoreMap).map((v) => parseInt(v, 10)).sort((a, b) => b - a);
  let result = [];
  for (const score of scoresInDesc) {
    result = result.concat(scoreMap[score]);
    if (result.length >= limit2) {
      break;
    }
  }
  return result;
}
function getBasicMatchIter(scoreMap, queryRunes, caseSensitive) {
  return (idx) => {
    const itemRunes = this.runesList[idx];
    if (queryRunes.length > itemRunes.length)
      return;
    let [match2, positions] = this.algoFn(
      caseSensitive,
      this.opts.normalize,
      this.opts.forward,
      itemRunes,
      queryRunes,
      true,
      slab
    );
    if (match2.start === -1)
      return;
    if (this.opts.fuzzy === false) {
      positions = /* @__PURE__ */ new Set();
      for (let position = match2.start; position < match2.end; ++position) {
        positions.add(position);
      }
    }
    const scoreKey = this.opts.sort ? match2.score : 0;
    if (scoreMap[scoreKey] === void 0) {
      scoreMap[scoreKey] = [];
    }
    scoreMap[scoreKey].push({
      item: this.items[idx],
      ...match2,
      positions: positions != null ? positions : /* @__PURE__ */ new Set()
    });
  };
}
function basicMatch(query) {
  const { queryRunes, caseSensitive } = buildPatternForBasicMatch(
    query,
    this.opts.casing,
    this.opts.normalize
  );
  const scoreMap = {};
  const iter2 = getBasicMatchIter.bind(this)(
    scoreMap,
    queryRunes,
    caseSensitive
  );
  for (let i = 0, len = this.runesList.length; i < len; ++i) {
    iter2(i);
  }
  return getResultFromScoreMap(scoreMap, this.opts.limit);
}
function asyncMatcher(token2, len, iter2, onFinish) {
  return new Promise((resolve24, reject) => {
    const INCREMENT = 1e3;
    let i = 0, end = Math.min(INCREMENT, len);
    const step = /* @__PURE__ */ __name(() => {
      if (token2.cancelled)
        return reject("search cancelled");
      for (; i < end; ++i) {
        iter2(i);
      }
      if (end < len) {
        end = Math.min(end + INCREMENT, len);
        isNode2 ? setImmediate(step) : setTimeout(step);
      } else {
        resolve24(onFinish());
      }
    }, "step");
    step();
  });
}
function asyncBasicMatch(query, token2) {
  const { queryRunes, caseSensitive } = buildPatternForBasicMatch(
    query,
    this.opts.casing,
    this.opts.normalize
  );
  const scoreMap = {};
  return asyncMatcher(
    token2,
    this.runesList.length,
    getBasicMatchIter.bind(this)(scoreMap, queryRunes, caseSensitive),
    () => getResultFromScoreMap(scoreMap, this.opts.limit)
  );
}
function postProcessResultItems(result, opts) {
  if (opts.sort) {
    const { selector } = opts;
    result.sort((a, b) => {
      if (a.score === b.score) {
        for (const tiebreaker of opts.tiebreakers) {
          const diff4 = tiebreaker(a, b, selector);
          if (diff4 !== 0) {
            return diff4;
          }
        }
      }
      return 0;
    });
  }
  if (Number.isFinite(opts.limit)) {
    result.splice(opts.limit);
  }
  return result;
}
var normalized, ranges, strToRunes, whitespaceRunes, MAX_ASCII, CAPITAL_A_RUNE, CAPITAL_Z_RUNE, SMALL_A_RUNE, SMALL_Z_RUNE, NUMERAL_ZERO_RUNE, NUMERAL_NINE_RUNE, SCORE_MATCH, SCORE_GAP_START, SCORE_GAP_EXTENTION, BONUS_BOUNDARY, BONUS_NON_WORD, BONUS_CAMEL_123, BONUS_CONSECUTIVE, BONUS_FIRST_CHAR_MULTIPLIER, fuzzyMatchV2, fuzzyMatchV1, exactMatchNaive, SLAB_16_SIZE, SLAB_32_SIZE, slab, buildPatternForBasicMatch, isNode2, defaultOpts2, BaseFinder, syncDefaultOpts, asyncDefaultOpts, AsyncFinder, createResultItemWithEmptyPos, AsyncFzf;
var init_fzf_es = __esm({
  "node_modules/fzf/dist/fzf.es.js"() {
    init_esbuild_shims();
    normalized = {
      216: "O",
      223: "s",
      248: "o",
      273: "d",
      295: "h",
      305: "i",
      320: "l",
      322: "l",
      359: "t",
      383: "s",
      384: "b",
      385: "B",
      387: "b",
      390: "O",
      392: "c",
      393: "D",
      394: "D",
      396: "d",
      398: "E",
      400: "E",
      402: "f",
      403: "G",
      407: "I",
      409: "k",
      410: "l",
      412: "M",
      413: "N",
      414: "n",
      415: "O",
      421: "p",
      427: "t",
      429: "t",
      430: "T",
      434: "V",
      436: "y",
      438: "z",
      477: "e",
      485: "g",
      544: "N",
      545: "d",
      549: "z",
      564: "l",
      565: "n",
      566: "t",
      567: "j",
      570: "A",
      571: "C",
      572: "c",
      573: "L",
      574: "T",
      575: "s",
      576: "z",
      579: "B",
      580: "U",
      581: "V",
      582: "E",
      583: "e",
      584: "J",
      585: "j",
      586: "Q",
      587: "q",
      588: "R",
      589: "r",
      590: "Y",
      591: "y",
      592: "a",
      593: "a",
      595: "b",
      596: "o",
      597: "c",
      598: "d",
      599: "d",
      600: "e",
      603: "e",
      604: "e",
      605: "e",
      606: "e",
      607: "j",
      608: "g",
      609: "g",
      610: "G",
      613: "h",
      614: "h",
      616: "i",
      618: "I",
      619: "l",
      620: "l",
      621: "l",
      623: "m",
      624: "m",
      625: "m",
      626: "n",
      627: "n",
      628: "N",
      629: "o",
      633: "r",
      634: "r",
      635: "r",
      636: "r",
      637: "r",
      638: "r",
      639: "r",
      640: "R",
      641: "R",
      642: "s",
      647: "t",
      648: "t",
      649: "u",
      651: "v",
      652: "v",
      653: "w",
      654: "y",
      655: "Y",
      656: "z",
      657: "z",
      663: "c",
      665: "B",
      666: "e",
      667: "G",
      668: "H",
      669: "j",
      670: "k",
      671: "L",
      672: "q",
      686: "h",
      867: "a",
      868: "e",
      869: "i",
      870: "o",
      871: "u",
      872: "c",
      873: "d",
      874: "h",
      875: "m",
      876: "r",
      877: "t",
      878: "v",
      879: "x",
      7424: "A",
      7427: "B",
      7428: "C",
      7429: "D",
      7431: "E",
      7432: "e",
      7433: "i",
      7434: "J",
      7435: "K",
      7436: "L",
      7437: "M",
      7438: "N",
      7439: "O",
      7440: "O",
      7441: "o",
      7442: "o",
      7443: "o",
      7446: "o",
      7447: "o",
      7448: "P",
      7449: "R",
      7450: "R",
      7451: "T",
      7452: "U",
      7453: "u",
      7454: "u",
      7455: "m",
      7456: "V",
      7457: "W",
      7458: "Z",
      7522: "i",
      7523: "r",
      7524: "u",
      7525: "v",
      7834: "a",
      7835: "s",
      8305: "i",
      8341: "h",
      8342: "k",
      8343: "l",
      8344: "m",
      8345: "n",
      8346: "p",
      8347: "s",
      8348: "t",
      8580: "c"
    };
    for (let i = "\u0300".codePointAt(0); i <= "\u036F".codePointAt(0); ++i) {
      const diacritic = String.fromCodePoint(i);
      for (const asciiChar of "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") {
        const withDiacritic = (asciiChar + diacritic).normalize();
        const withDiacriticCodePoint = withDiacritic.codePointAt(0);
        if (withDiacriticCodePoint > 126) {
          normalized[withDiacriticCodePoint] = asciiChar;
        }
      }
    }
    ranges = {
      a: [7844, 7863],
      e: [7870, 7879],
      o: [7888, 7907],
      u: [7912, 7921]
    };
    for (const lowerChar of Object.keys(ranges)) {
      const upperChar = lowerChar.toUpperCase();
      for (let i = ranges[lowerChar][0]; i <= ranges[lowerChar][1]; ++i) {
        normalized[i] = i % 2 === 0 ? upperChar : lowerChar;
      }
    }
    __name(normalizeRune, "normalizeRune");
    __name(toShort, "toShort");
    __name(toInt, "toInt");
    __name(maxInt16, "maxInt16");
    strToRunes = /* @__PURE__ */ __name((str2) => str2.split("").map((s2) => s2.codePointAt(0)), "strToRunes");
    whitespaceRunes = new Set(
      " \f\n\r	\v\xA0\u1680\u2028\u2029\u202F\u205F\u3000\uFEFF".split("").map((v) => v.codePointAt(0))
    );
    for (let codePoint = "\u2000".codePointAt(0); codePoint <= "\u200A".codePointAt(0); codePoint++) {
      whitespaceRunes.add(codePoint);
    }
    MAX_ASCII = "\x7F".codePointAt(0);
    CAPITAL_A_RUNE = "A".codePointAt(0);
    CAPITAL_Z_RUNE = "Z".codePointAt(0);
    SMALL_A_RUNE = "a".codePointAt(0);
    SMALL_Z_RUNE = "z".codePointAt(0);
    NUMERAL_ZERO_RUNE = "0".codePointAt(0);
    NUMERAL_NINE_RUNE = "9".codePointAt(0);
    __name(indexAt, "indexAt");
    SCORE_MATCH = 16;
    SCORE_GAP_START = -3;
    SCORE_GAP_EXTENTION = -1;
    BONUS_BOUNDARY = SCORE_MATCH / 2;
    BONUS_NON_WORD = SCORE_MATCH / 2;
    BONUS_CAMEL_123 = BONUS_BOUNDARY + SCORE_GAP_EXTENTION;
    BONUS_CONSECUTIVE = -(SCORE_GAP_START + SCORE_GAP_EXTENTION);
    BONUS_FIRST_CHAR_MULTIPLIER = 2;
    __name(createPosSet, "createPosSet");
    __name(alloc16, "alloc16");
    __name(alloc32, "alloc32");
    __name(charClassOfAscii, "charClassOfAscii");
    __name(charClassOfNonAscii, "charClassOfNonAscii");
    __name(charClassOf, "charClassOf");
    __name(bonusFor, "bonusFor");
    __name(bonusAt, "bonusAt");
    __name(trySkip, "trySkip");
    __name(isAscii, "isAscii");
    __name(asciiFuzzyIndex, "asciiFuzzyIndex");
    fuzzyMatchV2 = /* @__PURE__ */ __name((caseSensitive, normalize10, forward, input, pattern, withPos, slab2) => {
      const M = pattern.length;
      if (M === 0) {
        return [{ start: 0, end: 0, score: 0 }, createPosSet(withPos)];
      }
      const N = input.length;
      if (slab2 !== null && N * M > slab2.i16.length) {
        return fuzzyMatchV1(caseSensitive, normalize10, forward, input, pattern, withPos);
      }
      const idx = asciiFuzzyIndex(input, pattern, caseSensitive);
      if (idx < 0) {
        return [{ start: -1, end: -1, score: 0 }, null];
      }
      let offset16 = 0, offset32 = 0, H0 = null, C0 = null, B = null, F = null;
      [offset16, H0] = alloc16(offset16, slab2, N);
      [offset16, C0] = alloc16(offset16, slab2, N);
      [offset16, B] = alloc16(offset16, slab2, N);
      [offset32, F] = alloc32(offset32, slab2, M);
      const [, T] = alloc32(offset32, slab2, N);
      for (let i = 0; i < T.length; i++) {
        T[i] = input[i];
      }
      let maxScore = toShort(0), maxScorePos = 0;
      let pidx = 0, lastIdx = 0;
      const pchar0 = pattern[0];
      let pchar = pattern[0], prevH0 = toShort(0), prevCharClass = 0, inGap = false;
      let Tsub = T.subarray(idx);
      let H0sub = H0.subarray(idx).subarray(0, Tsub.length), C0sub = C0.subarray(idx).subarray(0, Tsub.length), Bsub = B.subarray(idx).subarray(0, Tsub.length);
      for (let [off, char] of Tsub.entries()) {
        let charClass = null;
        if (char <= MAX_ASCII) {
          charClass = charClassOfAscii(char);
          if (!caseSensitive && charClass === 2) {
            char += 32;
          }
        } else {
          charClass = charClassOfNonAscii(char);
          if (!caseSensitive && charClass === 2) {
            char = String.fromCodePoint(char).toLowerCase().codePointAt(0);
          }
          if (normalize10) {
            char = normalizeRune(char);
          }
        }
        Tsub[off] = char;
        const bonus = bonusFor(prevCharClass, charClass);
        Bsub[off] = bonus;
        prevCharClass = charClass;
        if (char === pchar) {
          if (pidx < M) {
            F[pidx] = toInt(idx + off);
            pidx++;
            pchar = pattern[Math.min(pidx, M - 1)];
          }
          lastIdx = idx + off;
        }
        if (char === pchar0) {
          const score = SCORE_MATCH + bonus * BONUS_FIRST_CHAR_MULTIPLIER;
          H0sub[off] = score;
          C0sub[off] = 1;
          if (M === 1 && (forward && score > maxScore || !forward && score >= maxScore)) {
            maxScore = score;
            maxScorePos = idx + off;
            if (forward && bonus === BONUS_BOUNDARY) {
              break;
            }
          }
          inGap = false;
        } else {
          if (inGap) {
            H0sub[off] = maxInt16(prevH0 + SCORE_GAP_EXTENTION, 0);
          } else {
            H0sub[off] = maxInt16(prevH0 + SCORE_GAP_START, 0);
          }
          C0sub[off] = 0;
          inGap = true;
        }
        prevH0 = H0sub[off];
      }
      if (pidx !== M) {
        return [{ start: -1, end: -1, score: 0 }, null];
      }
      if (M === 1) {
        const result = {
          start: maxScorePos,
          end: maxScorePos + 1,
          score: maxScore
        };
        if (!withPos) {
          return [result, null];
        }
        const pos22 = /* @__PURE__ */ new Set();
        pos22.add(maxScorePos);
        return [result, pos22];
      }
      const f0 = F[0];
      const width = lastIdx - f0 + 1;
      let H = null;
      [offset16, H] = alloc16(offset16, slab2, width * M);
      {
        const toCopy = H0.subarray(f0, lastIdx + 1);
        for (const [i, v] of toCopy.entries()) {
          H[i] = v;
        }
      }
      let [, C] = alloc16(offset16, slab2, width * M);
      {
        const toCopy = C0.subarray(f0, lastIdx + 1);
        for (const [i, v] of toCopy.entries()) {
          C[i] = v;
        }
      }
      const Fsub = F.subarray(1);
      const Psub = pattern.slice(1).slice(0, Fsub.length);
      for (const [off, f] of Fsub.entries()) {
        let inGap2 = false;
        const pchar2 = Psub[off], pidx2 = off + 1, row = pidx2 * width, Tsub2 = T.subarray(f, lastIdx + 1), Bsub2 = B.subarray(f).subarray(0, Tsub2.length), Csub = C.subarray(row + f - f0).subarray(0, Tsub2.length), Cdiag = C.subarray(row + f - f0 - 1 - width).subarray(0, Tsub2.length), Hsub = H.subarray(row + f - f0).subarray(0, Tsub2.length), Hdiag = H.subarray(row + f - f0 - 1 - width).subarray(0, Tsub2.length), Hleft = H.subarray(row + f - f0 - 1).subarray(0, Tsub2.length);
        Hleft[0] = 0;
        for (const [off2, char] of Tsub2.entries()) {
          const col = off2 + f;
          let s1 = 0, s2 = 0, consecutive = 0;
          if (inGap2) {
            s2 = Hleft[off2] + SCORE_GAP_EXTENTION;
          } else {
            s2 = Hleft[off2] + SCORE_GAP_START;
          }
          if (pchar2 === char) {
            s1 = Hdiag[off2] + SCORE_MATCH;
            let b = Bsub2[off2];
            consecutive = Cdiag[off2] + 1;
            if (b === BONUS_BOUNDARY) {
              consecutive = 1;
            } else if (consecutive > 1) {
              b = maxInt16(b, maxInt16(BONUS_CONSECUTIVE, B[col - consecutive + 1]));
            }
            if (s1 + b < s2) {
              s1 += Bsub2[off2];
              consecutive = 0;
            } else {
              s1 += b;
            }
          }
          Csub[off2] = consecutive;
          inGap2 = s1 < s2;
          const score = maxInt16(maxInt16(s1, s2), 0);
          if (pidx2 === M - 1 && (forward && score > maxScore || !forward && score >= maxScore)) {
            maxScore = score;
            maxScorePos = col;
          }
          Hsub[off2] = score;
        }
      }
      const pos2 = createPosSet(withPos);
      let j = f0;
      if (withPos && pos2 !== null) {
        let i = M - 1;
        j = maxScorePos;
        let preferMatch = true;
        while (true) {
          const I2 = i * width, j0 = j - f0, s2 = H[I2 + j0];
          let s1 = 0, s22 = 0;
          if (i > 0 && j >= F[i]) {
            s1 = H[I2 - width + j0 - 1];
          }
          if (j > F[i]) {
            s22 = H[I2 + j0 - 1];
          }
          if (s2 > s1 && (s2 > s22 || s2 === s22 && preferMatch)) {
            pos2.add(j);
            if (i === 0) {
              break;
            }
            i--;
          }
          preferMatch = C[I2 + j0] > 1 || I2 + width + j0 + 1 < C.length && C[I2 + width + j0 + 1] > 0;
          j--;
        }
      }
      return [{ start: j, end: maxScorePos + 1, score: maxScore }, pos2];
    }, "fuzzyMatchV2");
    __name(calculateScore, "calculateScore");
    fuzzyMatchV1 = /* @__PURE__ */ __name((caseSensitive, normalize10, forward, text, pattern, withPos, slab2) => {
      if (pattern.length === 0) {
        return [{ start: 0, end: 0, score: 0 }, null];
      }
      if (asciiFuzzyIndex(text, pattern, caseSensitive) < 0) {
        return [{ start: -1, end: -1, score: 0 }, null];
      }
      let pidx = 0, sidx = -1, eidx = -1;
      const lenRunes = text.length;
      const lenPattern = pattern.length;
      for (let index = 0; index < lenRunes; index++) {
        let rune = text[indexAt(index, lenRunes, forward)];
        if (!caseSensitive) {
          if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) {
            rune += 32;
          } else if (rune > MAX_ASCII) {
            rune = String.fromCodePoint(rune).toLowerCase().codePointAt(0);
          }
        }
        if (normalize10) {
          rune = normalizeRune(rune);
        }
        const pchar = pattern[indexAt(pidx, lenPattern, forward)];
        if (rune === pchar) {
          if (sidx < 0) {
            sidx = index;
          }
          pidx++;
          if (pidx === lenPattern) {
            eidx = index + 1;
            break;
          }
        }
      }
      if (sidx >= 0 && eidx >= 0) {
        pidx--;
        for (let index = eidx - 1; index >= sidx; index--) {
          const tidx = indexAt(index, lenRunes, forward);
          let rune = text[tidx];
          if (!caseSensitive) {
            if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) {
              rune += 32;
            } else if (rune > MAX_ASCII) {
              rune = String.fromCodePoint(rune).toLowerCase().codePointAt(0);
            }
          }
          const pidx_ = indexAt(pidx, lenPattern, forward);
          const pchar = pattern[pidx_];
          if (rune === pchar) {
            pidx--;
            if (pidx < 0) {
              sidx = index;
              break;
            }
          }
        }
        if (!forward) {
          const sidxTemp = sidx;
          sidx = lenRunes - eidx;
          eidx = lenRunes - sidxTemp;
        }
        const [score, pos2] = calculateScore(
          caseSensitive,
          normalize10,
          text,
          pattern,
          sidx,
          eidx,
          withPos
        );
        return [{ start: sidx, end: eidx, score }, pos2];
      }
      return [{ start: -1, end: -1, score: 0 }, null];
    }, "fuzzyMatchV1");
    exactMatchNaive = /* @__PURE__ */ __name((caseSensitive, normalize10, forward, text, pattern, withPos, slab2) => {
      if (pattern.length === 0) {
        return [{ start: 0, end: 0, score: 0 }, null];
      }
      const lenRunes = text.length;
      const lenPattern = pattern.length;
      if (lenRunes < lenPattern) {
        return [{ start: -1, end: -1, score: 0 }, null];
      }
      if (asciiFuzzyIndex(text, pattern, caseSensitive) < 0) {
        return [{ start: -1, end: -1, score: 0 }, null];
      }
      let pidx = 0;
      let bestPos = -1, bonus = toShort(0), bestBonus = toShort(-1);
      for (let index = 0; index < lenRunes; index++) {
        const index_ = indexAt(index, lenRunes, forward);
        let rune = text[index_];
        if (!caseSensitive) {
          if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) {
            rune += 32;
          } else if (rune > MAX_ASCII) {
            rune = String.fromCodePoint(rune).toLowerCase().codePointAt(0);
          }
        }
        if (normalize10) {
          rune = normalizeRune(rune);
        }
        const pidx_ = indexAt(pidx, lenPattern, forward);
        const pchar = pattern[pidx_];
        if (pchar === rune) {
          if (pidx_ === 0) {
            bonus = bonusAt(text, index_);
          }
          pidx++;
          if (pidx === lenPattern) {
            if (bonus > bestBonus) {
              bestPos = index;
              bestBonus = bonus;
            }
            if (bonus === BONUS_BOUNDARY) {
              break;
            }
            index -= pidx - 1;
            pidx = 0;
            bonus = 0;
          }
        } else {
          index -= pidx;
          pidx = 0;
          bonus = 0;
        }
      }
      if (bestPos >= 0) {
        let sidx = 0, eidx = 0;
        if (forward) {
          sidx = bestPos - lenPattern + 1;
          eidx = bestPos + 1;
        } else {
          sidx = lenRunes - (bestPos + 1);
          eidx = lenRunes - (bestPos - lenPattern + 1);
        }
        const [score] = calculateScore(caseSensitive, normalize10, text, pattern, sidx, eidx, false);
        return [{ start: sidx, end: eidx, score }, null];
      }
      return [{ start: -1, end: -1, score: 0 }, null];
    }, "exactMatchNaive");
    SLAB_16_SIZE = 100 * 1024;
    SLAB_32_SIZE = 2048;
    __name(makeSlab, "makeSlab");
    slab = makeSlab(SLAB_16_SIZE, SLAB_32_SIZE);
    buildPatternForBasicMatch = /* @__PURE__ */ __name((query, casing, normalize10) => {
      let caseSensitive = false;
      switch (casing) {
        case "smart-case":
          if (query.toLowerCase() !== query) {
            caseSensitive = true;
          }
          break;
        case "case-sensitive":
          caseSensitive = true;
          break;
        case "case-insensitive":
          query = query.toLowerCase();
          caseSensitive = false;
          break;
      }
      let queryRunes = strToRunes(query);
      if (normalize10) {
        queryRunes = queryRunes.map(normalizeRune);
      }
      return {
        queryRunes,
        caseSensitive
      };
    }, "buildPatternForBasicMatch");
    __name(getResultFromScoreMap, "getResultFromScoreMap");
    __name(getBasicMatchIter, "getBasicMatchIter");
    __name(basicMatch, "basicMatch");
    isNode2 = typeof __require !== "undefined" && typeof window === "undefined";
    __name(asyncMatcher, "asyncMatcher");
    __name(asyncBasicMatch, "asyncBasicMatch");
    defaultOpts2 = {
      limit: Infinity,
      selector: /* @__PURE__ */ __name((v) => v, "selector"),
      casing: "smart-case",
      normalize: true,
      fuzzy: "v2",
      tiebreakers: [],
      sort: true,
      forward: true
    };
    BaseFinder = class {
      static {
        __name(this, "BaseFinder");
      }
      constructor(list3, ...optionsTuple) {
        this.opts = { ...defaultOpts2, ...optionsTuple[0] };
        this.items = list3;
        this.runesList = list3.map((item) => strToRunes(this.opts.selector(item).normalize()));
        this.algoFn = exactMatchNaive;
        switch (this.opts.fuzzy) {
          case "v2":
            this.algoFn = fuzzyMatchV2;
            break;
          case "v1":
            this.algoFn = fuzzyMatchV1;
            break;
        }
      }
    };
    syncDefaultOpts = {
      ...defaultOpts2,
      match: basicMatch
    };
    asyncDefaultOpts = {
      ...defaultOpts2,
      match: asyncBasicMatch
    };
    AsyncFinder = class extends BaseFinder {
      static {
        __name(this, "AsyncFinder");
      }
      constructor(list3, ...optionsTuple) {
        super(list3, ...optionsTuple);
        this.opts = { ...asyncDefaultOpts, ...optionsTuple[0] };
        this.token = { cancelled: false };
      }
      async find(query) {
        this.token.cancelled = true;
        this.token = { cancelled: false };
        if (query.length === 0 || this.items.length === 0)
          return this.items.slice(0, this.opts.limit).map(createResultItemWithEmptyPos);
        query = query.normalize();
        let result = await this.opts.match.bind(this)(query, this.token);
        return postProcessResultItems(result, this.opts);
      }
    };
    createResultItemWithEmptyPos = /* @__PURE__ */ __name((item) => ({
      item,
      start: -1,
      end: -1,
      score: 0,
      positions: /* @__PURE__ */ new Set()
    }), "createResultItemWithEmptyPos");
    __name(postProcessResultItems, "postProcessResultItems");
    AsyncFzf = class {
      static {
        __name(this, "AsyncFzf");
      }
      constructor(list3, ...optionsTuple) {
        this.finder = new AsyncFinder(list3, ...optionsTuple);
        this.find = this.finder.find.bind(this.finder);
      }
    };
  }
});

// packages/core/dist/src/utils/filesearch/fileSearch.js
import path55 from "node:path";
async function filter3(allPaths, pattern, signal) {
  const patternFilter = (0, import_picomatch2.default)(pattern, {
    dot: true,
    contains: true,
    nocase: true
  });
  const results = [];
  for (const [i, p] of allPaths.entries()) {
    if (i % 1e3 === 0) {
      await new Promise((resolve24) => setImmediate(resolve24));
      if (signal?.aborted) {
        throw new AbortError();
      }
    }
    if (patternFilter(p)) {
      results.push(p);
    }
  }
  results.sort((a, b) => {
    const aIsDir = a.endsWith("/");
    const bIsDir = b.endsWith("/");
    if (aIsDir && !bIsDir)
      return -1;
    if (!aIsDir && bIsDir)
      return 1;
    return a < b ? -1 : a > b ? 1 : 0;
  });
  return results;
}
var import_picomatch2, AbortError, RecursiveFileSearch, DirectoryFileSearch, FileSearchFactory;
var init_fileSearch = __esm({
  "packages/core/dist/src/utils/filesearch/fileSearch.js"() {
    "use strict";
    init_esbuild_shims();
    import_picomatch2 = __toESM(require_picomatch2(), 1);
    init_ignore2();
    init_result_cache();
    init_crawler();
    init_fzf_es();
    init_paths();
    AbortError = class extends Error {
      static {
        __name(this, "AbortError");
      }
      constructor(message = "Search aborted") {
        super(message);
        this.name = "AbortError";
      }
    };
    __name(filter3, "filter");
    RecursiveFileSearch = class {
      static {
        __name(this, "RecursiveFileSearch");
      }
      options;
      ignore;
      resultCache;
      allFiles = [];
      fzf;
      constructor(options2) {
        this.options = options2;
      }
      async initialize() {
        this.ignore = loadIgnoreRules(this.options);
        this.allFiles = await crawl({
          crawlDirectory: this.options.projectRoot,
          cwd: this.options.projectRoot,
          ignore: this.ignore,
          cache: this.options.cache,
          cacheTtl: this.options.cacheTtl,
          maxDepth: this.options.maxDepth
        });
        this.buildResultCache();
      }
      async search(pattern, options2 = {}) {
        if (!this.resultCache || !this.fzf && !this.options.disableFuzzySearch || !this.ignore) {
          throw new Error("Engine not initialized. Call initialize() first.");
        }
        pattern = unescapePath(pattern) || "*";
        let filteredCandidates;
        const { files: candidates, isExactMatch } = await this.resultCache.get(pattern);
        if (isExactMatch) {
          filteredCandidates = candidates;
        } else {
          let shouldCache = true;
          if (pattern.includes("*") || !this.fzf) {
            filteredCandidates = await filter3(candidates, pattern, options2.signal);
          } else {
            filteredCandidates = await this.fzf.find(pattern).then((results2) => results2.map((entry) => entry.item)).catch(() => {
              shouldCache = false;
              return [];
            });
          }
          if (shouldCache) {
            this.resultCache.set(pattern, filteredCandidates);
          }
        }
        const fileFilter = this.ignore.getFileFilter();
        const results = [];
        for (const [i, candidate] of filteredCandidates.entries()) {
          if (i % 1e3 === 0) {
            await new Promise((resolve24) => setImmediate(resolve24));
            if (options2.signal?.aborted) {
              throw new AbortError();
            }
          }
          if (results.length >= (options2.maxResults ?? Infinity)) {
            break;
          }
          if (candidate === ".") {
            continue;
          }
          if (!fileFilter(candidate)) {
            results.push(candidate);
          }
        }
        return results;
      }
      buildResultCache() {
        this.resultCache = new ResultCache(this.allFiles);
        if (!this.options.disableFuzzySearch) {
          this.fzf = new AsyncFzf(this.allFiles, {
            fuzzy: this.allFiles.length > 2e4 ? "v1" : "v2"
          });
        }
      }
    };
    DirectoryFileSearch = class {
      static {
        __name(this, "DirectoryFileSearch");
      }
      options;
      ignore;
      constructor(options2) {
        this.options = options2;
      }
      async initialize() {
        this.ignore = loadIgnoreRules(this.options);
      }
      async search(pattern, options2 = {}) {
        if (!this.ignore) {
          throw new Error("Engine not initialized. Call initialize() first.");
        }
        pattern = pattern || "*";
        const dir = pattern.endsWith("/") ? pattern : path55.dirname(pattern);
        const results = await crawl({
          crawlDirectory: path55.join(this.options.projectRoot, dir),
          cwd: this.options.projectRoot,
          maxDepth: 0,
          ignore: this.ignore,
          cache: this.options.cache,
          cacheTtl: this.options.cacheTtl
        });
        const filteredResults = await filter3(results, pattern, options2.signal);
        const fileFilter = this.ignore.getFileFilter();
        const finalResults = [];
        for (const candidate of filteredResults) {
          if (finalResults.length >= (options2.maxResults ?? Infinity)) {
            break;
          }
          if (candidate === ".") {
            continue;
          }
          if (!fileFilter(candidate)) {
            finalResults.push(candidate);
          }
        }
        return finalResults;
      }
    };
    FileSearchFactory = class {
      static {
        __name(this, "FileSearchFactory");
      }
      static create(options2) {
        if (options2.enableRecursiveFileSearch) {
          return new RecursiveFileSearch(options2);
        }
        return new DirectoryFileSearch(options2);
      }
    };
  }
});

// packages/core/dist/src/utils/errorParsing.js
function getRateLimitMessage(authType, error, userTier, currentModel, fallbackModel) {
  switch (authType) {
    case AuthType2.LOGIN_WITH_GOOGLE: {
      const isPaidTier = userTier === UserTierId.LEGACY || userTier === UserTierId.STANDARD;
      if (isProQuotaExceededError(error)) {
        return isPaidTier ? getRateLimitErrorMessageGoogleProQuotaPaid(currentModel || DEFAULT_GEMINI_MODEL, fallbackModel) : getRateLimitErrorMessageGoogleProQuotaFree(currentModel || DEFAULT_GEMINI_MODEL, fallbackModel);
      } else if (isGenericQuotaExceededError(error)) {
        return isPaidTier ? getRateLimitErrorMessageGoogleGenericQuotaPaid(currentModel || DEFAULT_GEMINI_MODEL) : getRateLimitErrorMessageGoogleGenericQuotaFree();
      } else {
        return isPaidTier ? getRateLimitErrorMessageGooglePaid(fallbackModel) : getRateLimitErrorMessageGoogleFree(fallbackModel);
      }
    }
    case AuthType2.USE_GEMINI:
      return RATE_LIMIT_ERROR_MESSAGE_USE_GEMINI;
    case AuthType2.USE_VERTEX_AI:
      return RATE_LIMIT_ERROR_MESSAGE_VERTEX;
    default:
      return getRateLimitErrorMessageDefault(fallbackModel);
  }
}
function parseAndFormatApiError(error, authType, userTier, currentModel, fallbackModel) {
  if (isStructuredError(error)) {
    let text = `[API Error: ${error.message}]`;
    if (error.status === 429) {
      text += getRateLimitMessage(authType, error, userTier, currentModel, fallbackModel);
    }
    return text;
  }
  if (typeof error === "string") {
    const jsonStart = error.indexOf("{");
    if (jsonStart === -1) {
      return `[API Error: ${error}]`;
    }
    const jsonString = error.substring(jsonStart);
    try {
      const parsedError = JSON.parse(jsonString);
      if (isApiError(parsedError)) {
        let finalMessage = parsedError.error.message;
        try {
          const nestedError = JSON.parse(finalMessage);
          if (isApiError(nestedError)) {
            finalMessage = nestedError.error.message;
          }
        } catch (_e) {
        }
        let text = `[API Error: ${finalMessage} (Status: ${parsedError.error.status})]`;
        if (parsedError.error.code === 429) {
          text += getRateLimitMessage(authType, parsedError, userTier, currentModel, fallbackModel);
        }
        return text;
      }
    } catch (_e) {
    }
    return `[API Error: ${error}]`;
  }
  return "[API Error: An unknown error occurred.]";
}
var getRateLimitErrorMessageGoogleFree, getRateLimitErrorMessageGoogleProQuotaFree, getRateLimitErrorMessageGoogleGenericQuotaFree, getRateLimitErrorMessageGooglePaid, getRateLimitErrorMessageGoogleProQuotaPaid, getRateLimitErrorMessageGoogleGenericQuotaPaid, RATE_LIMIT_ERROR_MESSAGE_USE_GEMINI, RATE_LIMIT_ERROR_MESSAGE_VERTEX, getRateLimitErrorMessageDefault;
var init_errorParsing = __esm({
  "packages/core/dist/src/utils/errorParsing.js"() {
    "use strict";
    init_esbuild_shims();
    init_quotaErrorDetection();
    init_models();
    init_types2();
    init_contentGenerator();
    getRateLimitErrorMessageGoogleFree = /* @__PURE__ */ __name((fallbackModel = DEFAULT_GEMINI_FLASH_MODEL) => `
Possible quota limitations in place or slow response times detected. Switching to the ${fallbackModel} model for the rest of this session.`, "getRateLimitErrorMessageGoogleFree");
    getRateLimitErrorMessageGoogleProQuotaFree = /* @__PURE__ */ __name((currentModel = DEFAULT_GEMINI_MODEL, fallbackModel = DEFAULT_GEMINI_FLASH_MODEL) => `
You have reached your daily ${currentModel} quota limit. You will be switched to the ${fallbackModel} model for the rest of this session. To increase your limits, upgrade to get higher limits at https://goo.gle/set-up-gemini-code-assist, or use /auth to switch to using a paid API key from AI Studio at https://aistudio.google.com/apikey`, "getRateLimitErrorMessageGoogleProQuotaFree");
    getRateLimitErrorMessageGoogleGenericQuotaFree = /* @__PURE__ */ __name(() => `
You have reached your daily quota limit. To increase your limits, upgrade to get higher limits at https://goo.gle/set-up-gemini-code-assist, or use /auth to switch to using a paid API key from AI Studio at https://aistudio.google.com/apikey`, "getRateLimitErrorMessageGoogleGenericQuotaFree");
    getRateLimitErrorMessageGooglePaid = /* @__PURE__ */ __name((fallbackModel = DEFAULT_GEMINI_FLASH_MODEL) => `
Possible quota limitations in place or slow response times detected. Switching to the ${fallbackModel} model for the rest of this session. We appreciate you for choosing Gemini Code Assist and the Gemini CLI.`, "getRateLimitErrorMessageGooglePaid");
    getRateLimitErrorMessageGoogleProQuotaPaid = /* @__PURE__ */ __name((currentModel = DEFAULT_GEMINI_MODEL, fallbackModel = DEFAULT_GEMINI_FLASH_MODEL) => `
You have reached your daily ${currentModel} quota limit. You will be switched to the ${fallbackModel} model for the rest of this session. We appreciate you for choosing Gemini Code Assist and the Gemini CLI. To continue accessing the ${currentModel} model today, consider using /auth to switch to using a paid API key from AI Studio at https://aistudio.google.com/apikey`, "getRateLimitErrorMessageGoogleProQuotaPaid");
    getRateLimitErrorMessageGoogleGenericQuotaPaid = /* @__PURE__ */ __name((currentModel = DEFAULT_GEMINI_MODEL) => `
You have reached your daily quota limit. We appreciate you for choosing Gemini Code Assist and the Gemini CLI. To continue accessing the ${currentModel} model today, consider using /auth to switch to using a paid API key from AI Studio at https://aistudio.google.com/apikey`, "getRateLimitErrorMessageGoogleGenericQuotaPaid");
    RATE_LIMIT_ERROR_MESSAGE_USE_GEMINI = "\nPlease wait and try again later. To increase your limits, request a quota increase through AI Studio, or switch to another /auth method";
    RATE_LIMIT_ERROR_MESSAGE_VERTEX = "\nPlease wait and try again later. To increase your limits, request a quota increase through Vertex, or switch to another /auth method";
    getRateLimitErrorMessageDefault = /* @__PURE__ */ __name((fallbackModel = DEFAULT_GEMINI_FLASH_MODEL) => `
Possible quota limitations in place or slow response times detected. Switching to the ${fallbackModel} model for the rest of this session.`, "getRateLimitErrorMessageDefault");
    __name(getRateLimitMessage, "getRateLimitMessage");
    __name(parseAndFormatApiError, "parseAndFormatApiError");
  }
});

// packages/core/dist/src/utils/subagentGenerator.js
async function subagentGenerator(userDescription, config, abortSignal) {
  if (!userDescription.trim()) {
    throw new Error("User description cannot be empty");
  }
  const userPrompt = createUserPrompt(userDescription);
  const contents = [{ role: "user", parts: [{ text: userPrompt }] }];
  const parsedResponse = await config.getBaseLlmClient().generateJson({
    model: config.getModel() || DEFAULT_QWEN_MODEL,
    contents,
    schema: RESPONSE_SCHEMA2,
    abortSignal,
    systemInstruction: SYSTEM_PROMPT
  });
  if (!parsedResponse || !parsedResponse.name || !parsedResponse.description || !parsedResponse.systemPrompt) {
    throw new Error("Invalid response from LLM: missing required fields");
  }
  return parsedResponse;
}
var SYSTEM_PROMPT, createUserPrompt, RESPONSE_SCHEMA2;
var init_subagentGenerator = __esm({
  "packages/core/dist/src/utils/subagentGenerator.js"() {
    "use strict";
    init_esbuild_shims();
    init_models();
    SYSTEM_PROMPT = `You are an elite AI agent architect specializing in crafting high-performance agent configurations. Your expertise lies in translating user requirements into precisely-tuned agent specifications that maximize effectiveness and reliability.

**Important Context**: You may have access to project-specific instructions from QWEN.md files and other context that may include coding standards, project structure, and custom requirements. Consider this context when creating agents to ensure they align with the project's established patterns and practices.

When a user describes what they want an agent to do, you will:

1. **Extract Core Intent**: Identify the fundamental purpose, key responsibilities, and success criteria for the agent. Look for both explicit requirements and implicit needs. Consider any project-specific context from QWEN.md files. For agents that are meant to review code, you should assume that the user is asking to review recently written code and not the whole codebase, unless the user has explicitly instructed you otherwise.

2. **Design Expert Persona**: Create a compelling expert identity that embodies deep domain knowledge relevant to the task. The persona should inspire confidence and guide the agent's decision-making approach.

3. **Architect Comprehensive Instructions**: Develop a system prompt that:
   - Establishes clear behavioral boundaries and operational parameters
   - Provides specific methodologies and best practices for task execution
   - Anticipates edge cases and provides guidance for handling them
   - Incorporates any specific requirements or preferences mentioned by the user
   - Defines output format expectations when relevant
   - Aligns with project-specific coding standards and patterns from QWEN.md

4. **Optimize for Performance**: Include:
   - Decision-making frameworks appropriate to the domain
   - Quality control mechanisms and self-verification steps
   - Efficient workflow patterns
   - Clear escalation or fallback strategies

5. **Create Identifier**: Design a concise, descriptive identifier that:
   - Uses lowercase letters, numbers, and hyphens only
   - Is typically 2-4 words joined by hyphens
   - Clearly indicates the agent's primary function
   - Is memorable and easy to type
   - Avoids generic terms like "helper" or "assistant"

6 **Example agent descriptions**:
 - in the 'whenToUse' field of the JSON object, you should include examples of when this agent should be used.
 - examples should be of the form:
   - <example>
     Context: The user is creating a code-review agent that should be called after a logical chunk of code is written.
     user: "Please write a function that checks if a number is prime"
     assistant: "Here is the relevant function: "
     <function call omitted for brevity only for this example>
     <commentary>
     Since the user is greeting, use the Task tool to launch the greeting-responder agent to respond with a friendly joke. 
     </commentary>
     assistant: "Now let me use the code-reviewer agent to review the code"
   </example>
   - <example>
     Context: User is creating an agent to respond to the word "hello" with a friendly jok.
     user: "Hello"
     assistant: "I'm going to use the Task tool to launch the greeting-responder agent to respond with a friendly joke"
     <commentary>
     Since the user is greeting, use the greeting-responder agent to respond with a friendly joke. 
     </commentary>
   </example>
 - If the user mentioned or implied that the agent should be used proactively, you should include examples of this.
- NOTE: Ensure that in the examples, you are making the assistant use the Agent tool and not simply respond directly to the task.

Key principles for your system prompts:
- Be specific rather than generic - avoid vague instructions
- Include concrete examples when they would clarify behavior
- Balance comprehensiveness with clarity - every instruction should add value
- Ensure the agent has enough context to handle variations of the core task
- Make the agent proactive in seeking clarification when needed
- Build in quality assurance and self-correction mechanisms

Remember: The agents you create should be autonomous experts capable of handling their designated tasks with minimal additional guidance. Your system prompts are their complete operational manual.
`;
    createUserPrompt = /* @__PURE__ */ __name((userInput) => `Create an agent configuration based on this request: "${userInput}"`, "createUserPrompt");
    RESPONSE_SCHEMA2 = {
      type: "object",
      properties: {
        name: {
          type: "string",
          description: "A unique, descriptive identifier using lowercase letters, numbers, and hyphens (e.g., 'code-reviewer', 'api-docs-writer', 'test-generator')"
        },
        description: {
          type: "string",
          description: "A precise, actionable description starting with 'Use this agent when...' that clearly defines the triggering conditions and use cases"
        },
        systemPrompt: {
          type: "string",
          description: "The complete system prompt that will govern the agent's behavior, written in second person ('You are...', 'You will...') and structured for maximum clarity and effectiveness"
        }
      },
      required: ["name", "description", "systemPrompt"]
    };
    __name(subagentGenerator, "subagentGenerator");
  }
});

// packages/core/dist/src/utils/projectSummary.js
import * as fs49 from "fs/promises";
import * as path56 from "path";
async function getProjectSummaryInfo() {
  const summaryPath = path56.join(process.cwd(), ".qwen", "PROJECT_SUMMARY.md");
  try {
    await fs49.access(summaryPath);
  } catch {
    return {
      hasHistory: false
    };
  }
  try {
    const content = await fs49.readFile(summaryPath, "utf-8");
    const timestampMatch = content.match(/\*\*Update time\*\*: (.+)/);
    const timestamp = timestampMatch ? timestampMatch[1] : (/* @__PURE__ */ new Date()).toISOString();
    const getTimeAgo = /* @__PURE__ */ __name((timestamp2) => {
      const date = new Date(timestamp2);
      const now = /* @__PURE__ */ new Date();
      const diffMs = now.getTime() - date.getTime();
      const diffMinutes = Math.floor(diffMs / (1e3 * 60));
      const diffHours = Math.floor(diffMs / (1e3 * 60 * 60));
      const diffDays = Math.floor(diffMs / (1e3 * 60 * 60 * 24));
      if (diffDays > 0) {
        return `${diffDays} day${diffDays > 1 ? "s" : ""} ago`;
      } else if (diffHours > 0) {
        return `${diffHours} hour${diffHours > 1 ? "s" : ""} ago`;
      } else if (diffMinutes > 0) {
        return `${diffMinutes} minute${diffMinutes > 1 ? "s" : ""} ago`;
      } else {
        return "just now";
      }
    }, "getTimeAgo");
    const timeAgo = getTimeAgo(timestamp);
    const goalSection = content.match(/## Overall Goal\s*\n?([\s\S]*?)(?=\n## |$)/);
    const goalContent = goalSection ? goalSection[1].trim() : "";
    const planSection = content.match(/## Current Plan\s*\n?([\s\S]*?)(?=\n## |$)/);
    const planContent = planSection ? planSection[1] : "";
    const planLines = planContent.split("\n").filter((line) => line.trim());
    const doneCount = planLines.filter((line) => line.includes("[DONE]")).length;
    const inProgressCount = planLines.filter((line) => line.includes("[IN PROGRESS]")).length;
    const todoCount = planLines.filter((line) => line.includes("[TODO]")).length;
    const totalTasks = doneCount + inProgressCount + todoCount;
    const pendingTasks = planLines.filter((line) => line.includes("[TODO]") || line.includes("[IN PROGRESS]")).map((line) => line.replace(/^\d+\.\s*/, "").trim()).slice(0, 3);
    return {
      hasHistory: true,
      content,
      timestamp,
      timeAgo,
      goalContent,
      planContent,
      totalTasks,
      doneCount,
      inProgressCount,
      todoCount,
      pendingTasks
    };
  } catch (_error) {
    return {
      hasHistory: false
    };
  }
}
var init_projectSummary = __esm({
  "packages/core/dist/src/utils/projectSummary.js"() {
    "use strict";
    init_esbuild_shims();
    __name(getProjectSummaryInfo, "getProjectSummaryInfo");
  }
});

// packages/core/dist/src/ide/ide-installer.js
import * as child_process from "node:child_process";
import * as process24 from "node:process";
import * as path57 from "node:path";
import * as fs50 from "node:fs";
import * as os22 from "node:os";
function getVsCodeCommand(platform15 = process24.platform) {
  return platform15 === "win32" ? "code.cmd" : "code";
}
async function findVsCodeCommand(platform15 = process24.platform) {
  const vscodeCommand = getVsCodeCommand(platform15);
  try {
    if (platform15 === "win32") {
      const result = child_process.execSync(`where.exe ${vscodeCommand}`).toString().trim();
      const firstPath = result.split(/\r?\n/)[0];
      if (firstPath) {
        return firstPath;
      }
    } else {
      child_process.execSync(`command -v ${vscodeCommand}`, {
        stdio: "ignore"
      });
      return vscodeCommand;
    }
  } catch {
  }
  const locations = [];
  const homeDir = os22.homedir();
  if (platform15 === "darwin") {
    locations.push("/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code", path57.join(homeDir, "Library/Application Support/Code/bin/code"));
  } else if (platform15 === "linux") {
    locations.push("/usr/share/code/bin/code", "/snap/bin/code", path57.join(homeDir, ".local/share/code/bin/code"));
  } else if (platform15 === "win32") {
    locations.push(path57.join(process24.env["ProgramFiles"] || "C:\\Program Files", "Microsoft VS Code", "bin", "code.cmd"), path57.join(homeDir, "AppData", "Local", "Programs", "Microsoft VS Code", "bin", "code.cmd"));
  }
  for (const location of locations) {
    if (fs50.existsSync(location)) {
      return location;
    }
  }
  return null;
}
function getIdeInstaller(ide, platform15 = process24.platform) {
  switch (ide.name) {
    case IDE_DEFINITIONS.vscode.name:
    case IDE_DEFINITIONS.firebasestudio.name:
      return new VsCodeInstaller(ide, platform15);
    default:
      return null;
  }
}
var VsCodeInstaller;
var init_ide_installer = __esm({
  "packages/core/dist/src/ide/ide-installer.js"() {
    "use strict";
    init_esbuild_shims();
    init_detect_ide();
    init_constants4();
    __name(getVsCodeCommand, "getVsCodeCommand");
    __name(findVsCodeCommand, "findVsCodeCommand");
    VsCodeInstaller = class {
      static {
        __name(this, "VsCodeInstaller");
      }
      ideInfo;
      platform;
      vsCodeCommand;
      constructor(ideInfo, platform15 = process24.platform) {
        this.ideInfo = ideInfo;
        this.platform = platform15;
        this.vsCodeCommand = findVsCodeCommand(platform15);
      }
      async install() {
        const commandPath = await this.vsCodeCommand;
        if (!commandPath) {
          return {
            success: false,
            message: `${this.ideInfo.displayName} CLI not found. Please ensure 'code' is in your system's PATH. For help, see https://code.visualstudio.com/docs/configure/command-line#_code-is-not-recognized-as-an-internal-or-external-command. You can also install the '${QWEN_CODE_COMPANION_EXTENSION_NAME}' extension manually from the VS Code marketplace.`
          };
        }
        const isWindows8 = process24.platform === "win32";
        try {
          const result = child_process.spawnSync(isWindows8 ? `"${commandPath}"` : commandPath, [
            "--install-extension",
            "qwenlm.qwen-code-vscode-ide-companion",
            "--force"
          ], { stdio: "pipe", shell: isWindows8 });
          if (result.status !== 0) {
            throw new Error(`Failed to install extension: ${result.stderr?.toString()}`);
          }
          return {
            success: true,
            message: `${this.ideInfo.displayName} companion extension was installed successfully.`
          };
        } catch (_error) {
          return {
            success: false,
            message: `Failed to install ${this.ideInfo.displayName} companion extension. Please try installing '${QWEN_CODE_COMPANION_EXTENSION_NAME}' manually from the ${this.ideInfo.displayName} extension marketplace.`
          };
        }
      }
    };
    __name(getIdeInstaller, "getIdeInstaller");
  }
});

// packages/core/dist/src/subagents/index.js
var init_subagents = __esm({
  "packages/core/dist/src/subagents/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_types6();
    init_builtin_agents();
    init_validation();
    init_subagent_manager();
    init_subagent();
    init_subagent_events();
  }
});

// packages/core/dist/src/prompts/mcp-prompts.js
function getMCPServerPrompts(config, serverName) {
  const promptRegistry = config.getPromptRegistry();
  if (!promptRegistry) {
    return [];
  }
  return promptRegistry.getPromptsByServer(serverName);
}
var init_mcp_prompts = __esm({
  "packages/core/dist/src/prompts/mcp-prompts.js"() {
    "use strict";
    init_esbuild_shims();
    __name(getMCPServerPrompts, "getMCPServerPrompts");
  }
});

// packages/core/dist/src/utils/session.js
import { randomUUID as randomUUID5 } from "node:crypto";
var sessionId;
var init_session = __esm({
  "packages/core/dist/src/utils/session.js"() {
    "use strict";
    init_esbuild_shims();
    sessionId = randomUUID5();
  }
});

// packages/core/dist/src/test-utils/mock-tool.js
var init_mock_tool = __esm({
  "packages/core/dist/src/test-utils/mock-tool.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
  }
});

// packages/core/dist/src/test-utils/index.js
var init_test_utils = __esm({
  "packages/core/dist/src/test-utils/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_mock_tool();
  }
});

// packages/core/dist/src/index.js
var init_src = __esm({
  "packages/core/dist/src/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_config3();
    init_types10();
    init_json_formatter();
    init_client2();
    init_contentGenerator();
    init_loggingContentGenerator();
    init_geminiChat();
    init_logger();
    init_prompts();
    init_tokenLimits();
    init_turn();
    init_geminiRequest();
    init_coreToolScheduler();
    init_nonInteractiveToolExecutor();
    init_types11();
    init_codeAssist();
    init_oauth2();
    init_qwenOAuth2();
    init_server();
    init_types2();
    init_paths();
    init_schemaValidator();
    init_errors();
    init_getFolderStructure();
    init_memoryDiscovery();
    init_gitIgnoreParser();
    init_gitUtils();
    init_editor();
    init_quotaErrorDetection();
    init_fileUtils();
    init_retry();
    init_shell_utils();
    init_terminalSerializer();
    init_systemEncoding();
    init_textUtils();
    init_formatters();
    init_generateContentResponseUtilities();
    init_ripgrepUtils();
    init_fileSearch();
    init_errorParsing();
    init_workspaceContext();
    init_ignorePatterns();
    init_partUtils();
    init_subagentGenerator();
    init_projectSummary();
    init_promptIdContext();
    init_thoughtUtils();
    init_fileDiscoveryService();
    init_gitService();
    init_chatRecordingService();
    init_fileSystemService();
    init_ide_client();
    init_ideContext();
    init_ide_installer();
    init_detect_ide();
    init_constants4();
    init_types8();
    init_shellExecutionService();
    init_tools();
    init_tool_error();
    init_tool_registry();
    init_subagents();
    init_mcp_prompts();
    init_read_file();
    init_ls();
    init_grep2();
    init_ripGrep();
    init_glob2();
    init_edit();
    init_write_file();
    init_web_fetch();
    init_memoryTool();
    init_shell();
    init_web_search();
    init_read_many_files();
    init_mcp_client();
    init_mcp_tool();
    init_task();
    init_todoWrite();
    init_oauth_provider();
    init_oauth_token_storage();
    init_oauth_utils();
    init_telemetry();
    init_session();
    init_browser();
    init_openaiLogger();
    init_storage();
    init_test_utils();
  }
});

// node_modules/strip-json-comments/index.js
var require_strip_json_comments = __commonJS({
  "node_modules/strip-json-comments/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var singleComment = Symbol("singleComment");
    var multiComment = Symbol("multiComment");
    var stripWithoutWhitespace = /* @__PURE__ */ __name(() => "", "stripWithoutWhitespace");
    var stripWithWhitespace = /* @__PURE__ */ __name((string, start, end) => string.slice(start, end).replace(/\S/g, " "), "stripWithWhitespace");
    var isEscaped = /* @__PURE__ */ __name((jsonString, quotePosition) => {
      let index = quotePosition - 1;
      let backslashCount = 0;
      while (jsonString[index] === "\\") {
        index -= 1;
        backslashCount += 1;
      }
      return Boolean(backslashCount % 2);
    }, "isEscaped");
    module2.exports = (jsonString, options2 = {}) => {
      if (typeof jsonString !== "string") {
        throw new TypeError(`Expected argument \`jsonString\` to be a \`string\`, got \`${typeof jsonString}\``);
      }
      const strip = options2.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace;
      let insideString = false;
      let insideComment = false;
      let offset = 0;
      let result = "";
      for (let i = 0; i < jsonString.length; i++) {
        const currentCharacter = jsonString[i];
        const nextCharacter = jsonString[i + 1];
        if (!insideComment && currentCharacter === '"') {
          const escaped = isEscaped(jsonString, i);
          if (!escaped) {
            insideString = !insideString;
          }
        }
        if (insideString) {
          continue;
        }
        if (!insideComment && currentCharacter + nextCharacter === "//") {
          result += jsonString.slice(offset, i);
          offset = i;
          insideComment = singleComment;
          i++;
        } else if (insideComment === singleComment && currentCharacter + nextCharacter === "\r\n") {
          i++;
          insideComment = false;
          result += strip(jsonString, offset, i);
          offset = i;
          continue;
        } else if (insideComment === singleComment && currentCharacter === "\n") {
          insideComment = false;
          result += strip(jsonString, offset, i);
          offset = i;
        } else if (!insideComment && currentCharacter + nextCharacter === "/*") {
          result += jsonString.slice(offset, i);
          offset = i;
          insideComment = multiComment;
          i++;
          continue;
        } else if (insideComment === multiComment && currentCharacter + nextCharacter === "*/") {
          i++;
          insideComment = false;
          result += strip(jsonString, offset, i + 1);
          offset = i + 1;
          continue;
        }
      }
      return result + (insideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
    };
  }
});

// node_modules/emoji-regex/index.js
var require_emoji_regex4 = __commonJS({
  "node_modules/emoji-regex/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = function() {
      return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
    };
  }
});

// node_modules/react/cjs/react-jsx-runtime.production.js
var require_react_jsx_runtime_production = __commonJS({
  "node_modules/react/cjs/react-jsx-runtime.production.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element");
    var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
    function jsxProd(type, config, maybeKey) {
      var key = null;
      void 0 !== maybeKey && (key = "" + maybeKey);
      void 0 !== config.key && (key = "" + config.key);
      if ("key" in config) {
        maybeKey = {};
        for (var propName in config)
          "key" !== propName && (maybeKey[propName] = config[propName]);
      } else maybeKey = config;
      config = maybeKey.ref;
      return {
        $$typeof: REACT_ELEMENT_TYPE,
        type,
        key,
        ref: void 0 !== config ? config : null,
        props: maybeKey
      };
    }
    __name(jsxProd, "jsxProd");
    exports2.Fragment = REACT_FRAGMENT_TYPE;
    exports2.jsx = jsxProd;
    exports2.jsxs = jsxProd;
  }
});

// node_modules/react/cjs/react-jsx-runtime.development.js
var require_react_jsx_runtime_development = __commonJS({
  "node_modules/react/cjs/react-jsx-runtime.development.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    "production" !== process.env.NODE_ENV && function() {
      function getComponentNameFromType(type) {
        if (null == type) return null;
        if ("function" === typeof type)
          return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
        if ("string" === typeof type) return type;
        switch (type) {
          case REACT_FRAGMENT_TYPE:
            return "Fragment";
          case REACT_PROFILER_TYPE:
            return "Profiler";
          case REACT_STRICT_MODE_TYPE:
            return "StrictMode";
          case REACT_SUSPENSE_TYPE:
            return "Suspense";
          case REACT_SUSPENSE_LIST_TYPE:
            return "SuspenseList";
          case REACT_ACTIVITY_TYPE:
            return "Activity";
        }
        if ("object" === typeof type)
          switch ("number" === typeof type.tag && console.error(
            "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
          ), type.$$typeof) {
            case REACT_PORTAL_TYPE:
              return "Portal";
            case REACT_CONTEXT_TYPE:
              return (type.displayName || "Context") + ".Provider";
            case REACT_CONSUMER_TYPE:
              return (type._context.displayName || "Context") + ".Consumer";
            case REACT_FORWARD_REF_TYPE:
              var innerType = type.render;
              type = type.displayName;
              type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
              return type;
            case REACT_MEMO_TYPE:
              return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
            case REACT_LAZY_TYPE:
              innerType = type._payload;
              type = type._init;
              try {
                return getComponentNameFromType(type(innerType));
              } catch (x) {
              }
          }
        return null;
      }
      __name(getComponentNameFromType, "getComponentNameFromType");
      function testStringCoercion(value) {
        return "" + value;
      }
      __name(testStringCoercion, "testStringCoercion");
      function checkKeyStringCoercion(value) {
        try {
          testStringCoercion(value);
          var JSCompiler_inline_result = false;
        } catch (e2) {
          JSCompiler_inline_result = true;
        }
        if (JSCompiler_inline_result) {
          JSCompiler_inline_result = console;
          var JSCompiler_temp_const = JSCompiler_inline_result.error;
          var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
          JSCompiler_temp_const.call(
            JSCompiler_inline_result,
            "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
            JSCompiler_inline_result$jscomp$0
          );
          return testStringCoercion(value);
        }
      }
      __name(checkKeyStringCoercion, "checkKeyStringCoercion");
      function getTaskName(type) {
        if (type === REACT_FRAGMENT_TYPE) return "<>";
        if ("object" === typeof type && null !== type && type.$$typeof === REACT_LAZY_TYPE)
          return "<...>";
        try {
          var name3 = getComponentNameFromType(type);
          return name3 ? "<" + name3 + ">" : "<...>";
        } catch (x) {
          return "<...>";
        }
      }
      __name(getTaskName, "getTaskName");
      function getOwner() {
        var dispatcher = ReactSharedInternals.A;
        return null === dispatcher ? null : dispatcher.getOwner();
      }
      __name(getOwner, "getOwner");
      function UnknownOwner() {
        return Error("react-stack-top-frame");
      }
      __name(UnknownOwner, "UnknownOwner");
      function hasValidKey(config) {
        if (hasOwnProperty2.call(config, "key")) {
          var getter = Object.getOwnPropertyDescriptor(config, "key").get;
          if (getter && getter.isReactWarning) return false;
        }
        return void 0 !== config.key;
      }
      __name(hasValidKey, "hasValidKey");
      function defineKeyPropWarningGetter(props, displayName) {
        function warnAboutAccessingKey() {
          specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error(
            "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
            displayName
          ));
        }
        __name(warnAboutAccessingKey, "warnAboutAccessingKey");
        warnAboutAccessingKey.isReactWarning = true;
        Object.defineProperty(props, "key", {
          get: warnAboutAccessingKey,
          configurable: true
        });
      }
      __name(defineKeyPropWarningGetter, "defineKeyPropWarningGetter");
      function elementRefGetterWithDeprecationWarning() {
        var componentName = getComponentNameFromType(this.type);
        didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error(
          "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
        ));
        componentName = this.props.ref;
        return void 0 !== componentName ? componentName : null;
      }
      __name(elementRefGetterWithDeprecationWarning, "elementRefGetterWithDeprecationWarning");
      function ReactElement(type, key, self2, source2, owner, props, debugStack, debugTask) {
        self2 = props.ref;
        type = {
          $$typeof: REACT_ELEMENT_TYPE,
          type,
          key,
          props,
          _owner: owner
        };
        null !== (void 0 !== self2 ? self2 : null) ? Object.defineProperty(type, "ref", {
          enumerable: false,
          get: elementRefGetterWithDeprecationWarning
        }) : Object.defineProperty(type, "ref", { enumerable: false, value: null });
        type._store = {};
        Object.defineProperty(type._store, "validated", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: 0
        });
        Object.defineProperty(type, "_debugInfo", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: null
        });
        Object.defineProperty(type, "_debugStack", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: debugStack
        });
        Object.defineProperty(type, "_debugTask", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: debugTask
        });
        Object.freeze && (Object.freeze(type.props), Object.freeze(type));
        return type;
      }
      __name(ReactElement, "ReactElement");
      function jsxDEVImpl(type, config, maybeKey, isStaticChildren, source2, self2, debugStack, debugTask) {
        var children = config.children;
        if (void 0 !== children)
          if (isStaticChildren)
            if (isArrayImpl(children)) {
              for (isStaticChildren = 0; isStaticChildren < children.length; isStaticChildren++)
                validateChildKeys(children[isStaticChildren]);
              Object.freeze && Object.freeze(children);
            } else
              console.error(
                "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."
              );
          else validateChildKeys(children);
        if (hasOwnProperty2.call(config, "key")) {
          children = getComponentNameFromType(type);
          var keys = Object.keys(config).filter(function(k) {
            return "key" !== k;
          });
          isStaticChildren = 0 < keys.length ? "{key: someKey, " + keys.join(": ..., ") + ": ...}" : "{key: someKey}";
          didWarnAboutKeySpread[children + isStaticChildren] || (keys = 0 < keys.length ? "{" + keys.join(": ..., ") + ": ...}" : "{}", console.error(
            'A props object containing a "key" prop is being spread into JSX:\n  let props = %s;\n  <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n  let props = %s;\n  <%s key={someKey} {...props} />',
            isStaticChildren,
            children,
            keys,
            children
          ), didWarnAboutKeySpread[children + isStaticChildren] = true);
        }
        children = null;
        void 0 !== maybeKey && (checkKeyStringCoercion(maybeKey), children = "" + maybeKey);
        hasValidKey(config) && (checkKeyStringCoercion(config.key), children = "" + config.key);
        if ("key" in config) {
          maybeKey = {};
          for (var propName in config)
            "key" !== propName && (maybeKey[propName] = config[propName]);
        } else maybeKey = config;
        children && defineKeyPropWarningGetter(
          maybeKey,
          "function" === typeof type ? type.displayName || type.name || "Unknown" : type
        );
        return ReactElement(
          type,
          children,
          self2,
          source2,
          getOwner(),
          maybeKey,
          debugStack,
          debugTask
        );
      }
      __name(jsxDEVImpl, "jsxDEVImpl");
      function validateChildKeys(node) {
        "object" === typeof node && null !== node && node.$$typeof === REACT_ELEMENT_TYPE && node._store && (node._store.validated = 1);
      }
      __name(validateChildKeys, "validateChildKeys");
      var React29 = require_react(), REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler");
      Symbol.for("react.provider");
      var REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), ReactSharedInternals = React29.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, hasOwnProperty2 = Object.prototype.hasOwnProperty, isArrayImpl = Array.isArray, createTask = console.createTask ? console.createTask : function() {
        return null;
      };
      React29 = {
        "react-stack-bottom-frame": /* @__PURE__ */ __name(function(callStackForError) {
          return callStackForError();
        }, "react-stack-bottom-frame")
      };
      var specialPropKeyWarningShown;
      var didWarnAboutElementRef = {};
      var unknownOwnerDebugStack = React29["react-stack-bottom-frame"].bind(
        React29,
        UnknownOwner
      )();
      var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
      var didWarnAboutKeySpread = {};
      exports2.Fragment = REACT_FRAGMENT_TYPE;
      exports2.jsx = function(type, config, maybeKey, source2, self2) {
        var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
        return jsxDEVImpl(
          type,
          config,
          maybeKey,
          false,
          source2,
          self2,
          trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
          trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask
        );
      };
      exports2.jsxs = function(type, config, maybeKey, source2, self2) {
        var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
        return jsxDEVImpl(
          type,
          config,
          maybeKey,
          true,
          source2,
          self2,
          trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
          trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask
        );
      };
    }();
  }
});

// node_modules/react/jsx-runtime.js
var require_jsx_runtime = __commonJS({
  "node_modules/react/jsx-runtime.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    if (process.env.NODE_ENV === "production") {
      module2.exports = require_react_jsx_runtime_production();
    } else {
      module2.exports = require_react_jsx_runtime_development();
    }
  }
});

// node_modules/highlight.js/lib/core.js
var require_core8 = __commonJS({
  "node_modules/highlight.js/lib/core.js"(exports2, module2) {
    init_esbuild_shims();
    function deepFreeze(obj) {
      if (obj instanceof Map) {
        obj.clear = obj.delete = obj.set = function() {
          throw new Error("map is read-only");
        };
      } else if (obj instanceof Set) {
        obj.add = obj.clear = obj.delete = function() {
          throw new Error("set is read-only");
        };
      }
      Object.freeze(obj);
      Object.getOwnPropertyNames(obj).forEach((name3) => {
        const prop = obj[name3];
        const type = typeof prop;
        if ((type === "object" || type === "function") && !Object.isFrozen(prop)) {
          deepFreeze(prop);
        }
      });
      return obj;
    }
    __name(deepFreeze, "deepFreeze");
    var Response2 = class {
      static {
        __name(this, "Response");
      }
      /**
       * @param {CompiledMode} mode
       */
      constructor(mode) {
        if (mode.data === void 0) mode.data = {};
        this.data = mode.data;
        this.isMatchIgnored = false;
      }
      ignoreMatch() {
        this.isMatchIgnored = true;
      }
    };
    function escapeHTML(value) {
      return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;");
    }
    __name(escapeHTML, "escapeHTML");
    function inherit$1(original, ...objects) {
      const result = /* @__PURE__ */ Object.create(null);
      for (const key in original) {
        result[key] = original[key];
      }
      objects.forEach(function(obj) {
        for (const key in obj) {
          result[key] = obj[key];
        }
      });
      return (
        /** @type {T} */
        result
      );
    }
    __name(inherit$1, "inherit$1");
    var SPAN_CLOSE = "</span>";
    var emitsWrappingTags = /* @__PURE__ */ __name((node) => {
      return !!node.scope;
    }, "emitsWrappingTags");
    var scopeToCSSClass = /* @__PURE__ */ __name((name3, { prefix }) => {
      if (name3.startsWith("language:")) {
        return name3.replace("language:", "language-");
      }
      if (name3.includes(".")) {
        const pieces = name3.split(".");
        return [
          `${prefix}${pieces.shift()}`,
          ...pieces.map((x, i) => `${x}${"_".repeat(i + 1)}`)
        ].join(" ");
      }
      return `${prefix}${name3}`;
    }, "scopeToCSSClass");
    var HTMLRenderer = class {
      static {
        __name(this, "HTMLRenderer");
      }
      /**
       * Creates a new HTMLRenderer
       *
       * @param {Tree} parseTree - the parse tree (must support `walk` API)
       * @param {{classPrefix: string}} options
       */
      constructor(parseTree, options2) {
        this.buffer = "";
        this.classPrefix = options2.classPrefix;
        parseTree.walk(this);
      }
      /**
       * Adds texts to the output stream
       *
       * @param {string} text */
      addText(text) {
        this.buffer += escapeHTML(text);
      }
      /**
       * Adds a node open to the output stream (if needed)
       *
       * @param {Node} node */
      openNode(node) {
        if (!emitsWrappingTags(node)) return;
        const className = scopeToCSSClass(
          node.scope,
          { prefix: this.classPrefix }
        );
        this.span(className);
      }
      /**
       * Adds a node close to the output stream (if needed)
       *
       * @param {Node} node */
      closeNode(node) {
        if (!emitsWrappingTags(node)) return;
        this.buffer += SPAN_CLOSE;
      }
      /**
       * returns the accumulated buffer
      */
      value() {
        return this.buffer;
      }
      // helpers
      /**
       * Builds a span element
       *
       * @param {string} className */
      span(className) {
        this.buffer += `<span class="${className}">`;
      }
    };
    var newNode = /* @__PURE__ */ __name((opts = {}) => {
      const result = { children: [] };
      Object.assign(result, opts);
      return result;
    }, "newNode");
    var TokenTree = class _TokenTree {
      static {
        __name(this, "TokenTree");
      }
      constructor() {
        this.rootNode = newNode();
        this.stack = [this.rootNode];
      }
      get top() {
        return this.stack[this.stack.length - 1];
      }
      get root() {
        return this.rootNode;
      }
      /** @param {Node} node */
      add(node) {
        this.top.children.push(node);
      }
      /** @param {string} scope */
      openNode(scope) {
        const node = newNode({ scope });
        this.add(node);
        this.stack.push(node);
      }
      closeNode() {
        if (this.stack.length > 1) {
          return this.stack.pop();
        }
        return void 0;
      }
      closeAllNodes() {
        while (this.closeNode()) ;
      }
      toJSON() {
        return JSON.stringify(this.rootNode, null, 4);
      }
      /**
       * @typedef { import("./html_renderer").Renderer } Renderer
       * @param {Renderer} builder
       */
      walk(builder) {
        return this.constructor._walk(builder, this.rootNode);
      }
      /**
       * @param {Renderer} builder
       * @param {Node} node
       */
      static _walk(builder, node) {
        if (typeof node === "string") {
          builder.addText(node);
        } else if (node.children) {
          builder.openNode(node);
          node.children.forEach((child) => this._walk(builder, child));
          builder.closeNode(node);
        }
        return builder;
      }
      /**
       * @param {Node} node
       */
      static _collapse(node) {
        if (typeof node === "string") return;
        if (!node.children) return;
        if (node.children.every((el) => typeof el === "string")) {
          node.children = [node.children.join("")];
        } else {
          node.children.forEach((child) => {
            _TokenTree._collapse(child);
          });
        }
      }
    };
    var TokenTreeEmitter = class extends TokenTree {
      static {
        __name(this, "TokenTreeEmitter");
      }
      /**
       * @param {*} options
       */
      constructor(options2) {
        super();
        this.options = options2;
      }
      /**
       * @param {string} text
       */
      addText(text) {
        if (text === "") {
          return;
        }
        this.add(text);
      }
      /** @param {string} scope */
      startScope(scope) {
        this.openNode(scope);
      }
      endScope() {
        this.closeNode();
      }
      /**
       * @param {Emitter & {root: DataNode}} emitter
       * @param {string} name
       */
      __addSublanguage(emitter, name3) {
        const node = emitter.root;
        if (name3) node.scope = `language:${name3}`;
        this.add(node);
      }
      toHTML() {
        const renderer2 = new HTMLRenderer(this, this.options);
        return renderer2.value();
      }
      finalize() {
        this.closeAllNodes();
        return true;
      }
    };
    function source2(re2) {
      if (!re2) return null;
      if (typeof re2 === "string") return re2;
      return re2.source;
    }
    __name(source2, "source");
    function lookahead2(re2) {
      return concat2("(?=", re2, ")");
    }
    __name(lookahead2, "lookahead");
    function anyNumberOfTimes(re2) {
      return concat2("(?:", re2, ")*");
    }
    __name(anyNumberOfTimes, "anyNumberOfTimes");
    function optional(re2) {
      return concat2("(?:", re2, ")?");
    }
    __name(optional, "optional");
    function concat2(...args) {
      const joined = args.map((x) => source2(x)).join("");
      return joined;
    }
    __name(concat2, "concat");
    function stripOptionsFromArgs2(args) {
      const opts = args[args.length - 1];
      if (typeof opts === "object" && opts.constructor === Object) {
        args.splice(args.length - 1, 1);
        return opts;
      } else {
        return {};
      }
    }
    __name(stripOptionsFromArgs2, "stripOptionsFromArgs");
    function either2(...args) {
      const opts = stripOptionsFromArgs2(args);
      const joined = "(" + (opts.capture ? "" : "?:") + args.map((x) => source2(x)).join("|") + ")";
      return joined;
    }
    __name(either2, "either");
    function countMatchGroups(re2) {
      return new RegExp(re2.toString() + "|").exec("").length - 1;
    }
    __name(countMatchGroups, "countMatchGroups");
    function startsWith(re2, lexeme) {
      const match2 = re2 && re2.exec(lexeme);
      return match2 && match2.index === 0;
    }
    __name(startsWith, "startsWith");
    var BACKREF_RE = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;
    function _rewriteBackreferences(regexps, { joinWith }) {
      let numCaptures = 0;
      return regexps.map((regex3) => {
        numCaptures += 1;
        const offset = numCaptures;
        let re2 = source2(regex3);
        let out = "";
        while (re2.length > 0) {
          const match2 = BACKREF_RE.exec(re2);
          if (!match2) {
            out += re2;
            break;
          }
          out += re2.substring(0, match2.index);
          re2 = re2.substring(match2.index + match2[0].length);
          if (match2[0][0] === "\\" && match2[1]) {
            out += "\\" + String(Number(match2[1]) + offset);
          } else {
            out += match2[0];
            if (match2[0] === "(") {
              numCaptures++;
            }
          }
        }
        return out;
      }).map((re2) => `(${re2})`).join(joinWith);
    }
    __name(_rewriteBackreferences, "_rewriteBackreferences");
    var MATCH_NOTHING_RE = /\b\B/;
    var IDENT_RE3 = "[a-zA-Z]\\w*";
    var UNDERSCORE_IDENT_RE = "[a-zA-Z_]\\w*";
    var NUMBER_RE = "\\b\\d+(\\.\\d+)?";
    var C_NUMBER_RE = "(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)";
    var BINARY_NUMBER_RE = "\\b(0b[01]+)";
    var RE_STARTERS_RE = "!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~";
    var SHEBANG = /* @__PURE__ */ __name((opts = {}) => {
      const beginShebang = /^#![ ]*\//;
      if (opts.binary) {
        opts.begin = concat2(
          beginShebang,
          /.*\b/,
          opts.binary,
          /\b.*/
        );
      }
      return inherit$1({
        scope: "meta",
        begin: beginShebang,
        end: /$/,
        relevance: 0,
        /** @type {ModeCallback} */
        "on:begin": /* @__PURE__ */ __name((m, resp) => {
          if (m.index !== 0) resp.ignoreMatch();
        }, "on:begin")
      }, opts);
    }, "SHEBANG");
    var BACKSLASH_ESCAPE = {
      begin: "\\\\[\\s\\S]",
      relevance: 0
    };
    var APOS_STRING_MODE = {
      scope: "string",
      begin: "'",
      end: "'",
      illegal: "\\n",
      contains: [BACKSLASH_ESCAPE]
    };
    var QUOTE_STRING_MODE = {
      scope: "string",
      begin: '"',
      end: '"',
      illegal: "\\n",
      contains: [BACKSLASH_ESCAPE]
    };
    var PHRASAL_WORDS_MODE = {
      begin: /\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/
    };
    var COMMENT = /* @__PURE__ */ __name(function(begin, end, modeOptions = {}) {
      const mode = inherit$1(
        {
          scope: "comment",
          begin,
          end,
          contains: []
        },
        modeOptions
      );
      mode.contains.push({
        scope: "doctag",
        // hack to avoid the space from being included. the space is necessary to
        // match here to prevent the plain text rule below from gobbling up doctags
        begin: "[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",
        end: /(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,
        excludeBegin: true,
        relevance: 0
      });
      const ENGLISH_WORD = either2(
        // list of common 1 and 2 letter words in English
        "I",
        "a",
        "is",
        "so",
        "us",
        "to",
        "at",
        "if",
        "in",
        "it",
        "on",
        // note: this is not an exhaustive list of contractions, just popular ones
        /[A-Za-z]+['](d|ve|re|ll|t|s|n)/,
        // contractions - can't we'd they're let's, etc
        /[A-Za-z]+[-][a-z]+/,
        // `no-way`, etc.
        /[A-Za-z][a-z]{2,}/
        // allow capitalized words at beginning of sentences
      );
      mode.contains.push(
        {
          // TODO: how to include ", (, ) without breaking grammars that use these for
          // comment delimiters?
          // begin: /[ ]+([()"]?([A-Za-z'-]{3,}|is|a|I|so|us|[tT][oO]|at|if|in|it|on)[.]?[()":]?([.][ ]|[ ]|\))){3}/
          // ---
          // this tries to find sequences of 3 english words in a row (without any
          // "programming" type syntax) this gives us a strong signal that we've
          // TRULY found a comment - vs perhaps scanning with the wrong language.
          // It's possible to find something that LOOKS like the start of the
          // comment - but then if there is no readable text - good chance it is a
          // false match and not a comment.
          //
          // for a visual example please see:
          // https://github.com/highlightjs/highlight.js/issues/2827
          begin: concat2(
            /[ ]+/,
            // necessary to prevent us gobbling up doctags like /* @author Bob Mcgill */
            "(",
            ENGLISH_WORD,
            /[.]?[:]?([.][ ]|[ ])/,
            "){3}"
          )
          // look for 3 words in a row
        }
      );
      return mode;
    }, "COMMENT");
    var C_LINE_COMMENT_MODE = COMMENT("//", "$");
    var C_BLOCK_COMMENT_MODE = COMMENT("/\\*", "\\*/");
    var HASH_COMMENT_MODE = COMMENT("#", "$");
    var NUMBER_MODE = {
      scope: "number",
      begin: NUMBER_RE,
      relevance: 0
    };
    var C_NUMBER_MODE = {
      scope: "number",
      begin: C_NUMBER_RE,
      relevance: 0
    };
    var BINARY_NUMBER_MODE = {
      scope: "number",
      begin: BINARY_NUMBER_RE,
      relevance: 0
    };
    var REGEXP_MODE = {
      scope: "regexp",
      begin: /\/(?=[^/\n]*\/)/,
      end: /\/[gimuy]*/,
      contains: [
        BACKSLASH_ESCAPE,
        {
          begin: /\[/,
          end: /\]/,
          relevance: 0,
          contains: [BACKSLASH_ESCAPE]
        }
      ]
    };
    var TITLE_MODE = {
      scope: "title",
      begin: IDENT_RE3,
      relevance: 0
    };
    var UNDERSCORE_TITLE_MODE = {
      scope: "title",
      begin: UNDERSCORE_IDENT_RE,
      relevance: 0
    };
    var METHOD_GUARD = {
      // excludes method names from keyword processing
      begin: "\\.\\s*" + UNDERSCORE_IDENT_RE,
      relevance: 0
    };
    var END_SAME_AS_BEGIN = /* @__PURE__ */ __name(function(mode) {
      return Object.assign(
        mode,
        {
          /** @type {ModeCallback} */
          "on:begin": /* @__PURE__ */ __name((m, resp) => {
            resp.data._beginMatch = m[1];
          }, "on:begin"),
          /** @type {ModeCallback} */
          "on:end": /* @__PURE__ */ __name((m, resp) => {
            if (resp.data._beginMatch !== m[1]) resp.ignoreMatch();
          }, "on:end")
        }
      );
    }, "END_SAME_AS_BEGIN");
    var MODES4 = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      APOS_STRING_MODE,
      BACKSLASH_ESCAPE,
      BINARY_NUMBER_MODE,
      BINARY_NUMBER_RE,
      COMMENT,
      C_BLOCK_COMMENT_MODE,
      C_LINE_COMMENT_MODE,
      C_NUMBER_MODE,
      C_NUMBER_RE,
      END_SAME_AS_BEGIN,
      HASH_COMMENT_MODE,
      IDENT_RE: IDENT_RE3,
      MATCH_NOTHING_RE,
      METHOD_GUARD,
      NUMBER_MODE,
      NUMBER_RE,
      PHRASAL_WORDS_MODE,
      QUOTE_STRING_MODE,
      REGEXP_MODE,
      RE_STARTERS_RE,
      SHEBANG,
      TITLE_MODE,
      UNDERSCORE_IDENT_RE,
      UNDERSCORE_TITLE_MODE
    });
    function skipIfHasPrecedingDot(match2, response) {
      const before = match2.input[match2.index - 1];
      if (before === ".") {
        response.ignoreMatch();
      }
    }
    __name(skipIfHasPrecedingDot, "skipIfHasPrecedingDot");
    function scopeClassName(mode, _parent) {
      if (mode.className !== void 0) {
        mode.scope = mode.className;
        delete mode.className;
      }
    }
    __name(scopeClassName, "scopeClassName");
    function beginKeywords(mode, parent) {
      if (!parent) return;
      if (!mode.beginKeywords) return;
      mode.begin = "\\b(" + mode.beginKeywords.split(" ").join("|") + ")(?!\\.)(?=\\b|\\s)";
      mode.__beforeBegin = skipIfHasPrecedingDot;
      mode.keywords = mode.keywords || mode.beginKeywords;
      delete mode.beginKeywords;
      if (mode.relevance === void 0) mode.relevance = 0;
    }
    __name(beginKeywords, "beginKeywords");
    function compileIllegal(mode, _parent) {
      if (!Array.isArray(mode.illegal)) return;
      mode.illegal = either2(...mode.illegal);
    }
    __name(compileIllegal, "compileIllegal");
    function compileMatch(mode, _parent) {
      if (!mode.match) return;
      if (mode.begin || mode.end) throw new Error("begin & end are not supported with match");
      mode.begin = mode.match;
      delete mode.match;
    }
    __name(compileMatch, "compileMatch");
    function compileRelevance(mode, _parent) {
      if (mode.relevance === void 0) mode.relevance = 1;
    }
    __name(compileRelevance, "compileRelevance");
    var beforeMatchExt = /* @__PURE__ */ __name((mode, parent) => {
      if (!mode.beforeMatch) return;
      if (mode.starts) throw new Error("beforeMatch cannot be used with starts");
      const originalMode = Object.assign({}, mode);
      Object.keys(mode).forEach((key) => {
        delete mode[key];
      });
      mode.keywords = originalMode.keywords;
      mode.begin = concat2(originalMode.beforeMatch, lookahead2(originalMode.begin));
      mode.starts = {
        relevance: 0,
        contains: [
          Object.assign(originalMode, { endsParent: true })
        ]
      };
      mode.relevance = 0;
      delete originalMode.beforeMatch;
    }, "beforeMatchExt");
    var COMMON_KEYWORDS = [
      "of",
      "and",
      "for",
      "in",
      "not",
      "or",
      "if",
      "then",
      "parent",
      // common variable name
      "list",
      // common variable name
      "value"
      // common variable name
    ];
    var DEFAULT_KEYWORD_SCOPE = "keyword";
    function compileKeywords(rawKeywords, caseInsensitive, scopeName = DEFAULT_KEYWORD_SCOPE) {
      const compiledKeywords = /* @__PURE__ */ Object.create(null);
      if (typeof rawKeywords === "string") {
        compileList(scopeName, rawKeywords.split(" "));
      } else if (Array.isArray(rawKeywords)) {
        compileList(scopeName, rawKeywords);
      } else {
        Object.keys(rawKeywords).forEach(function(scopeName2) {
          Object.assign(
            compiledKeywords,
            compileKeywords(rawKeywords[scopeName2], caseInsensitive, scopeName2)
          );
        });
      }
      return compiledKeywords;
      function compileList(scopeName2, keywordList) {
        if (caseInsensitive) {
          keywordList = keywordList.map((x) => x.toLowerCase());
        }
        keywordList.forEach(function(keyword) {
          const pair = keyword.split("|");
          compiledKeywords[pair[0]] = [scopeName2, scoreForKeyword(pair[0], pair[1])];
        });
      }
      __name(compileList, "compileList");
    }
    __name(compileKeywords, "compileKeywords");
    function scoreForKeyword(keyword, providedScore) {
      if (providedScore) {
        return Number(providedScore);
      }
      return commonKeyword(keyword) ? 0 : 1;
    }
    __name(scoreForKeyword, "scoreForKeyword");
    function commonKeyword(keyword) {
      return COMMON_KEYWORDS.includes(keyword.toLowerCase());
    }
    __name(commonKeyword, "commonKeyword");
    var seenDeprecations = {};
    var error = /* @__PURE__ */ __name((message) => {
      console.error(message);
    }, "error");
    var warn = /* @__PURE__ */ __name((message, ...args) => {
      console.log(`WARN: ${message}`, ...args);
    }, "warn");
    var deprecated = /* @__PURE__ */ __name((version3, message) => {
      if (seenDeprecations[`${version3}/${message}`]) return;
      console.log(`Deprecated as of ${version3}. ${message}`);
      seenDeprecations[`${version3}/${message}`] = true;
    }, "deprecated");
    var MultiClassError = new Error();
    function remapScopeNames(mode, regexes, { key }) {
      let offset = 0;
      const scopeNames = mode[key];
      const emit = {};
      const positions = {};
      for (let i = 1; i <= regexes.length; i++) {
        positions[i + offset] = scopeNames[i];
        emit[i + offset] = true;
        offset += countMatchGroups(regexes[i - 1]);
      }
      mode[key] = positions;
      mode[key]._emit = emit;
      mode[key]._multi = true;
    }
    __name(remapScopeNames, "remapScopeNames");
    function beginMultiClass(mode) {
      if (!Array.isArray(mode.begin)) return;
      if (mode.skip || mode.excludeBegin || mode.returnBegin) {
        error("skip, excludeBegin, returnBegin not compatible with beginScope: {}");
        throw MultiClassError;
      }
      if (typeof mode.beginScope !== "object" || mode.beginScope === null) {
        error("beginScope must be object");
        throw MultiClassError;
      }
      remapScopeNames(mode, mode.begin, { key: "beginScope" });
      mode.begin = _rewriteBackreferences(mode.begin, { joinWith: "" });
    }
    __name(beginMultiClass, "beginMultiClass");
    function endMultiClass(mode) {
      if (!Array.isArray(mode.end)) return;
      if (mode.skip || mode.excludeEnd || mode.returnEnd) {
        error("skip, excludeEnd, returnEnd not compatible with endScope: {}");
        throw MultiClassError;
      }
      if (typeof mode.endScope !== "object" || mode.endScope === null) {
        error("endScope must be object");
        throw MultiClassError;
      }
      remapScopeNames(mode, mode.end, { key: "endScope" });
      mode.end = _rewriteBackreferences(mode.end, { joinWith: "" });
    }
    __name(endMultiClass, "endMultiClass");
    function scopeSugar(mode) {
      if (mode.scope && typeof mode.scope === "object" && mode.scope !== null) {
        mode.beginScope = mode.scope;
        delete mode.scope;
      }
    }
    __name(scopeSugar, "scopeSugar");
    function MultiClass(mode) {
      scopeSugar(mode);
      if (typeof mode.beginScope === "string") {
        mode.beginScope = { _wrap: mode.beginScope };
      }
      if (typeof mode.endScope === "string") {
        mode.endScope = { _wrap: mode.endScope };
      }
      beginMultiClass(mode);
      endMultiClass(mode);
    }
    __name(MultiClass, "MultiClass");
    function compileLanguage(language) {
      function langRe(value, global2) {
        return new RegExp(
          source2(value),
          "m" + (language.case_insensitive ? "i" : "") + (language.unicodeRegex ? "u" : "") + (global2 ? "g" : "")
        );
      }
      __name(langRe, "langRe");
      class MultiRegex {
        static {
          __name(this, "MultiRegex");
        }
        constructor() {
          this.matchIndexes = {};
          this.regexes = [];
          this.matchAt = 1;
          this.position = 0;
        }
        // @ts-ignore
        addRule(re2, opts) {
          opts.position = this.position++;
          this.matchIndexes[this.matchAt] = opts;
          this.regexes.push([opts, re2]);
          this.matchAt += countMatchGroups(re2) + 1;
        }
        compile() {
          if (this.regexes.length === 0) {
            this.exec = () => null;
          }
          const terminators = this.regexes.map((el) => el[1]);
          this.matcherRe = langRe(_rewriteBackreferences(terminators, { joinWith: "|" }), true);
          this.lastIndex = 0;
        }
        /** @param {string} s */
        exec(s2) {
          this.matcherRe.lastIndex = this.lastIndex;
          const match2 = this.matcherRe.exec(s2);
          if (!match2) {
            return null;
          }
          const i = match2.findIndex((el, i2) => i2 > 0 && el !== void 0);
          const matchData = this.matchIndexes[i];
          match2.splice(0, i);
          return Object.assign(match2, matchData);
        }
      }
      class ResumableMultiRegex {
        static {
          __name(this, "ResumableMultiRegex");
        }
        constructor() {
          this.rules = [];
          this.multiRegexes = [];
          this.count = 0;
          this.lastIndex = 0;
          this.regexIndex = 0;
        }
        // @ts-ignore
        getMatcher(index) {
          if (this.multiRegexes[index]) return this.multiRegexes[index];
          const matcher = new MultiRegex();
          this.rules.slice(index).forEach(([re2, opts]) => matcher.addRule(re2, opts));
          matcher.compile();
          this.multiRegexes[index] = matcher;
          return matcher;
        }
        resumingScanAtSamePosition() {
          return this.regexIndex !== 0;
        }
        considerAll() {
          this.regexIndex = 0;
        }
        // @ts-ignore
        addRule(re2, opts) {
          this.rules.push([re2, opts]);
          if (opts.type === "begin") this.count++;
        }
        /** @param {string} s */
        exec(s2) {
          const m = this.getMatcher(this.regexIndex);
          m.lastIndex = this.lastIndex;
          let result = m.exec(s2);
          if (this.resumingScanAtSamePosition()) {
            if (result && result.index === this.lastIndex) ;
            else {
              const m2 = this.getMatcher(0);
              m2.lastIndex = this.lastIndex + 1;
              result = m2.exec(s2);
            }
          }
          if (result) {
            this.regexIndex += result.position + 1;
            if (this.regexIndex === this.count) {
              this.considerAll();
            }
          }
          return result;
        }
      }
      function buildModeRegex(mode) {
        const mm = new ResumableMultiRegex();
        mode.contains.forEach((term) => mm.addRule(term.begin, { rule: term, type: "begin" }));
        if (mode.terminatorEnd) {
          mm.addRule(mode.terminatorEnd, { type: "end" });
        }
        if (mode.illegal) {
          mm.addRule(mode.illegal, { type: "illegal" });
        }
        return mm;
      }
      __name(buildModeRegex, "buildModeRegex");
      function compileMode(mode, parent) {
        const cmode = (
          /** @type CompiledMode */
          mode
        );
        if (mode.isCompiled) return cmode;
        [
          scopeClassName,
          // do this early so compiler extensions generally don't have to worry about
          // the distinction between match/begin
          compileMatch,
          MultiClass,
          beforeMatchExt
        ].forEach((ext2) => ext2(mode, parent));
        language.compilerExtensions.forEach((ext2) => ext2(mode, parent));
        mode.__beforeBegin = null;
        [
          beginKeywords,
          // do this later so compiler extensions that come earlier have access to the
          // raw array if they wanted to perhaps manipulate it, etc.
          compileIllegal,
          // default to 1 relevance if not specified
          compileRelevance
        ].forEach((ext2) => ext2(mode, parent));
        mode.isCompiled = true;
        let keywordPattern = null;
        if (typeof mode.keywords === "object" && mode.keywords.$pattern) {
          mode.keywords = Object.assign({}, mode.keywords);
          keywordPattern = mode.keywords.$pattern;
          delete mode.keywords.$pattern;
        }
        keywordPattern = keywordPattern || /\w+/;
        if (mode.keywords) {
          mode.keywords = compileKeywords(mode.keywords, language.case_insensitive);
        }
        cmode.keywordPatternRe = langRe(keywordPattern, true);
        if (parent) {
          if (!mode.begin) mode.begin = /\B|\b/;
          cmode.beginRe = langRe(cmode.begin);
          if (!mode.end && !mode.endsWithParent) mode.end = /\B|\b/;
          if (mode.end) cmode.endRe = langRe(cmode.end);
          cmode.terminatorEnd = source2(cmode.end) || "";
          if (mode.endsWithParent && parent.terminatorEnd) {
            cmode.terminatorEnd += (mode.end ? "|" : "") + parent.terminatorEnd;
          }
        }
        if (mode.illegal) cmode.illegalRe = langRe(
          /** @type {RegExp | string} */
          mode.illegal
        );
        if (!mode.contains) mode.contains = [];
        mode.contains = [].concat(...mode.contains.map(function(c3) {
          return expandOrCloneMode(c3 === "self" ? mode : c3);
        }));
        mode.contains.forEach(function(c3) {
          compileMode(
            /** @type Mode */
            c3,
            cmode
          );
        });
        if (mode.starts) {
          compileMode(mode.starts, parent);
        }
        cmode.matcher = buildModeRegex(cmode);
        return cmode;
      }
      __name(compileMode, "compileMode");
      if (!language.compilerExtensions) language.compilerExtensions = [];
      if (language.contains && language.contains.includes("self")) {
        throw new Error("ERR: contains `self` is not supported at the top-level of a language.  See documentation.");
      }
      language.classNameAliases = inherit$1(language.classNameAliases || {});
      return compileMode(
        /** @type Mode */
        language
      );
    }
    __name(compileLanguage, "compileLanguage");
    function dependencyOnParent(mode) {
      if (!mode) return false;
      return mode.endsWithParent || dependencyOnParent(mode.starts);
    }
    __name(dependencyOnParent, "dependencyOnParent");
    function expandOrCloneMode(mode) {
      if (mode.variants && !mode.cachedVariants) {
        mode.cachedVariants = mode.variants.map(function(variant) {
          return inherit$1(mode, { variants: null }, variant);
        });
      }
      if (mode.cachedVariants) {
        return mode.cachedVariants;
      }
      if (dependencyOnParent(mode)) {
        return inherit$1(mode, { starts: mode.starts ? inherit$1(mode.starts) : null });
      }
      if (Object.isFrozen(mode)) {
        return inherit$1(mode);
      }
      return mode;
    }
    __name(expandOrCloneMode, "expandOrCloneMode");
    var version2 = "11.11.1";
    var HTMLInjectionError = class extends Error {
      static {
        __name(this, "HTMLInjectionError");
      }
      constructor(reason, html2) {
        super(reason);
        this.name = "HTMLInjectionError";
        this.html = html2;
      }
    };
    var escape7 = escapeHTML;
    var inherit = inherit$1;
    var NO_MATCH = Symbol("nomatch");
    var MAX_KEYWORD_HITS = 7;
    var HLJS = /* @__PURE__ */ __name(function(hljs) {
      const languages = /* @__PURE__ */ Object.create(null);
      const aliases = /* @__PURE__ */ Object.create(null);
      const plugins = [];
      let SAFE_MODE = true;
      const LANGUAGE_NOT_FOUND = "Could not find the language '{}', did you forget to load/include a language module?";
      const PLAINTEXT_LANGUAGE = { disableAutodetect: true, name: "Plain text", contains: [] };
      let options2 = {
        ignoreUnescapedHTML: false,
        throwUnescapedHTML: false,
        noHighlightRe: /^(no-?highlight)$/i,
        languageDetectRe: /\blang(?:uage)?-([\w-]+)\b/i,
        classPrefix: "hljs-",
        cssSelector: "pre code",
        languages: null,
        // beta configuration options, subject to change, welcome to discuss
        // https://github.com/highlightjs/highlight.js/issues/1086
        __emitter: TokenTreeEmitter
      };
      function shouldNotHighlight(languageName) {
        return options2.noHighlightRe.test(languageName);
      }
      __name(shouldNotHighlight, "shouldNotHighlight");
      function blockLanguage(block2) {
        let classes = block2.className + " ";
        classes += block2.parentNode ? block2.parentNode.className : "";
        const match2 = options2.languageDetectRe.exec(classes);
        if (match2) {
          const language = getLanguage(match2[1]);
          if (!language) {
            warn(LANGUAGE_NOT_FOUND.replace("{}", match2[1]));
            warn("Falling back to no-highlight mode for this block.", block2);
          }
          return language ? match2[1] : "no-highlight";
        }
        return classes.split(/\s+/).find((_class) => shouldNotHighlight(_class) || getLanguage(_class));
      }
      __name(blockLanguage, "blockLanguage");
      function highlight2(codeOrLanguageName, optionsOrCode, ignoreIllegals) {
        let code2 = "";
        let languageName = "";
        if (typeof optionsOrCode === "object") {
          code2 = codeOrLanguageName;
          ignoreIllegals = optionsOrCode.ignoreIllegals;
          languageName = optionsOrCode.language;
        } else {
          deprecated("10.7.0", "highlight(lang, code, ...args) has been deprecated.");
          deprecated("10.7.0", "Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277");
          languageName = codeOrLanguageName;
          code2 = optionsOrCode;
        }
        if (ignoreIllegals === void 0) {
          ignoreIllegals = true;
        }
        const context2 = {
          code: code2,
          language: languageName
        };
        fire("before:highlight", context2);
        const result = context2.result ? context2.result : _highlight(context2.language, context2.code, ignoreIllegals);
        result.code = context2.code;
        fire("after:highlight", result);
        return result;
      }
      __name(highlight2, "highlight");
      function _highlight(languageName, codeToHighlight, ignoreIllegals, continuation) {
        const keywordHits = /* @__PURE__ */ Object.create(null);
        function keywordData(mode, matchText) {
          return mode.keywords[matchText];
        }
        __name(keywordData, "keywordData");
        function processKeywords() {
          if (!top2.keywords) {
            emitter.addText(modeBuffer);
            return;
          }
          let lastIndex = 0;
          top2.keywordPatternRe.lastIndex = 0;
          let match2 = top2.keywordPatternRe.exec(modeBuffer);
          let buf = "";
          while (match2) {
            buf += modeBuffer.substring(lastIndex, match2.index);
            const word = language.case_insensitive ? match2[0].toLowerCase() : match2[0];
            const data = keywordData(top2, word);
            if (data) {
              const [kind, keywordRelevance] = data;
              emitter.addText(buf);
              buf = "";
              keywordHits[word] = (keywordHits[word] || 0) + 1;
              if (keywordHits[word] <= MAX_KEYWORD_HITS) relevance += keywordRelevance;
              if (kind.startsWith("_")) {
                buf += match2[0];
              } else {
                const cssClass = language.classNameAliases[kind] || kind;
                emitKeyword(match2[0], cssClass);
              }
            } else {
              buf += match2[0];
            }
            lastIndex = top2.keywordPatternRe.lastIndex;
            match2 = top2.keywordPatternRe.exec(modeBuffer);
          }
          buf += modeBuffer.substring(lastIndex);
          emitter.addText(buf);
        }
        __name(processKeywords, "processKeywords");
        function processSubLanguage() {
          if (modeBuffer === "") return;
          let result2 = null;
          if (typeof top2.subLanguage === "string") {
            if (!languages[top2.subLanguage]) {
              emitter.addText(modeBuffer);
              return;
            }
            result2 = _highlight(top2.subLanguage, modeBuffer, true, continuations[top2.subLanguage]);
            continuations[top2.subLanguage] = /** @type {CompiledMode} */
            result2._top;
          } else {
            result2 = highlightAuto(modeBuffer, top2.subLanguage.length ? top2.subLanguage : null);
          }
          if (top2.relevance > 0) {
            relevance += result2.relevance;
          }
          emitter.__addSublanguage(result2._emitter, result2.language);
        }
        __name(processSubLanguage, "processSubLanguage");
        function processBuffer() {
          if (top2.subLanguage != null) {
            processSubLanguage();
          } else {
            processKeywords();
          }
          modeBuffer = "";
        }
        __name(processBuffer, "processBuffer");
        function emitKeyword(keyword, scope) {
          if (keyword === "") return;
          emitter.startScope(scope);
          emitter.addText(keyword);
          emitter.endScope();
        }
        __name(emitKeyword, "emitKeyword");
        function emitMultiClass(scope, match2) {
          let i = 1;
          const max = match2.length - 1;
          while (i <= max) {
            if (!scope._emit[i]) {
              i++;
              continue;
            }
            const klass = language.classNameAliases[scope[i]] || scope[i];
            const text = match2[i];
            if (klass) {
              emitKeyword(text, klass);
            } else {
              modeBuffer = text;
              processKeywords();
              modeBuffer = "";
            }
            i++;
          }
        }
        __name(emitMultiClass, "emitMultiClass");
        function startNewMode(mode, match2) {
          if (mode.scope && typeof mode.scope === "string") {
            emitter.openNode(language.classNameAliases[mode.scope] || mode.scope);
          }
          if (mode.beginScope) {
            if (mode.beginScope._wrap) {
              emitKeyword(modeBuffer, language.classNameAliases[mode.beginScope._wrap] || mode.beginScope._wrap);
              modeBuffer = "";
            } else if (mode.beginScope._multi) {
              emitMultiClass(mode.beginScope, match2);
              modeBuffer = "";
            }
          }
          top2 = Object.create(mode, { parent: { value: top2 } });
          return top2;
        }
        __name(startNewMode, "startNewMode");
        function endOfMode(mode, match2, matchPlusRemainder) {
          let matched = startsWith(mode.endRe, matchPlusRemainder);
          if (matched) {
            if (mode["on:end"]) {
              const resp = new Response2(mode);
              mode["on:end"](match2, resp);
              if (resp.isMatchIgnored) matched = false;
            }
            if (matched) {
              while (mode.endsParent && mode.parent) {
                mode = mode.parent;
              }
              return mode;
            }
          }
          if (mode.endsWithParent) {
            return endOfMode(mode.parent, match2, matchPlusRemainder);
          }
        }
        __name(endOfMode, "endOfMode");
        function doIgnore(lexeme) {
          if (top2.matcher.regexIndex === 0) {
            modeBuffer += lexeme[0];
            return 1;
          } else {
            resumeScanAtSamePosition = true;
            return 0;
          }
        }
        __name(doIgnore, "doIgnore");
        function doBeginMatch(match2) {
          const lexeme = match2[0];
          const newMode = match2.rule;
          const resp = new Response2(newMode);
          const beforeCallbacks = [newMode.__beforeBegin, newMode["on:begin"]];
          for (const cb of beforeCallbacks) {
            if (!cb) continue;
            cb(match2, resp);
            if (resp.isMatchIgnored) return doIgnore(lexeme);
          }
          if (newMode.skip) {
            modeBuffer += lexeme;
          } else {
            if (newMode.excludeBegin) {
              modeBuffer += lexeme;
            }
            processBuffer();
            if (!newMode.returnBegin && !newMode.excludeBegin) {
              modeBuffer = lexeme;
            }
          }
          startNewMode(newMode, match2);
          return newMode.returnBegin ? 0 : lexeme.length;
        }
        __name(doBeginMatch, "doBeginMatch");
        function doEndMatch(match2) {
          const lexeme = match2[0];
          const matchPlusRemainder = codeToHighlight.substring(match2.index);
          const endMode = endOfMode(top2, match2, matchPlusRemainder);
          if (!endMode) {
            return NO_MATCH;
          }
          const origin = top2;
          if (top2.endScope && top2.endScope._wrap) {
            processBuffer();
            emitKeyword(lexeme, top2.endScope._wrap);
          } else if (top2.endScope && top2.endScope._multi) {
            processBuffer();
            emitMultiClass(top2.endScope, match2);
          } else if (origin.skip) {
            modeBuffer += lexeme;
          } else {
            if (!(origin.returnEnd || origin.excludeEnd)) {
              modeBuffer += lexeme;
            }
            processBuffer();
            if (origin.excludeEnd) {
              modeBuffer = lexeme;
            }
          }
          do {
            if (top2.scope) {
              emitter.closeNode();
            }
            if (!top2.skip && !top2.subLanguage) {
              relevance += top2.relevance;
            }
            top2 = top2.parent;
          } while (top2 !== endMode.parent);
          if (endMode.starts) {
            startNewMode(endMode.starts, match2);
          }
          return origin.returnEnd ? 0 : lexeme.length;
        }
        __name(doEndMatch, "doEndMatch");
        function processContinuations() {
          const list3 = [];
          for (let current = top2; current !== language; current = current.parent) {
            if (current.scope) {
              list3.unshift(current.scope);
            }
          }
          list3.forEach((item) => emitter.openNode(item));
        }
        __name(processContinuations, "processContinuations");
        let lastMatch = {};
        function processLexeme(textBeforeMatch, match2) {
          const lexeme = match2 && match2[0];
          modeBuffer += textBeforeMatch;
          if (lexeme == null) {
            processBuffer();
            return 0;
          }
          if (lastMatch.type === "begin" && match2.type === "end" && lastMatch.index === match2.index && lexeme === "") {
            modeBuffer += codeToHighlight.slice(match2.index, match2.index + 1);
            if (!SAFE_MODE) {
              const err = new Error(`0 width match regex (${languageName})`);
              err.languageName = languageName;
              err.badRule = lastMatch.rule;
              throw err;
            }
            return 1;
          }
          lastMatch = match2;
          if (match2.type === "begin") {
            return doBeginMatch(match2);
          } else if (match2.type === "illegal" && !ignoreIllegals) {
            const err = new Error('Illegal lexeme "' + lexeme + '" for mode "' + (top2.scope || "<unnamed>") + '"');
            err.mode = top2;
            throw err;
          } else if (match2.type === "end") {
            const processed = doEndMatch(match2);
            if (processed !== NO_MATCH) {
              return processed;
            }
          }
          if (match2.type === "illegal" && lexeme === "") {
            modeBuffer += "\n";
            return 1;
          }
          if (iterations > 1e5 && iterations > match2.index * 3) {
            const err = new Error("potential infinite loop, way more iterations than matches");
            throw err;
          }
          modeBuffer += lexeme;
          return lexeme.length;
        }
        __name(processLexeme, "processLexeme");
        const language = getLanguage(languageName);
        if (!language) {
          error(LANGUAGE_NOT_FOUND.replace("{}", languageName));
          throw new Error('Unknown language: "' + languageName + '"');
        }
        const md = compileLanguage(language);
        let result = "";
        let top2 = continuation || md;
        const continuations = {};
        const emitter = new options2.__emitter(options2);
        processContinuations();
        let modeBuffer = "";
        let relevance = 0;
        let index = 0;
        let iterations = 0;
        let resumeScanAtSamePosition = false;
        try {
          if (!language.__emitTokens) {
            top2.matcher.considerAll();
            for (; ; ) {
              iterations++;
              if (resumeScanAtSamePosition) {
                resumeScanAtSamePosition = false;
              } else {
                top2.matcher.considerAll();
              }
              top2.matcher.lastIndex = index;
              const match2 = top2.matcher.exec(codeToHighlight);
              if (!match2) break;
              const beforeMatch = codeToHighlight.substring(index, match2.index);
              const processedCount = processLexeme(beforeMatch, match2);
              index = match2.index + processedCount;
            }
            processLexeme(codeToHighlight.substring(index));
          } else {
            language.__emitTokens(codeToHighlight, emitter);
          }
          emitter.finalize();
          result = emitter.toHTML();
          return {
            language: languageName,
            value: result,
            relevance,
            illegal: false,
            _emitter: emitter,
            _top: top2
          };
        } catch (err) {
          if (err.message && err.message.includes("Illegal")) {
            return {
              language: languageName,
              value: escape7(codeToHighlight),
              illegal: true,
              relevance: 0,
              _illegalBy: {
                message: err.message,
                index,
                context: codeToHighlight.slice(index - 100, index + 100),
                mode: err.mode,
                resultSoFar: result
              },
              _emitter: emitter
            };
          } else if (SAFE_MODE) {
            return {
              language: languageName,
              value: escape7(codeToHighlight),
              illegal: false,
              relevance: 0,
              errorRaised: err,
              _emitter: emitter,
              _top: top2
            };
          } else {
            throw err;
          }
        }
      }
      __name(_highlight, "_highlight");
      function justTextHighlightResult(code2) {
        const result = {
          value: escape7(code2),
          illegal: false,
          relevance: 0,
          _top: PLAINTEXT_LANGUAGE,
          _emitter: new options2.__emitter(options2)
        };
        result._emitter.addText(code2);
        return result;
      }
      __name(justTextHighlightResult, "justTextHighlightResult");
      function highlightAuto(code2, languageSubset) {
        languageSubset = languageSubset || options2.languages || Object.keys(languages);
        const plaintext2 = justTextHighlightResult(code2);
        const results = languageSubset.filter(getLanguage).filter(autoDetection).map(
          (name3) => _highlight(name3, code2, false)
        );
        results.unshift(plaintext2);
        const sorted2 = results.sort((a, b) => {
          if (a.relevance !== b.relevance) return b.relevance - a.relevance;
          if (a.language && b.language) {
            if (getLanguage(a.language).supersetOf === b.language) {
              return 1;
            } else if (getLanguage(b.language).supersetOf === a.language) {
              return -1;
            }
          }
          return 0;
        });
        const [best, secondBest] = sorted2;
        const result = best;
        result.secondBest = secondBest;
        return result;
      }
      __name(highlightAuto, "highlightAuto");
      function updateClassName(element, currentLang, resultLang) {
        const language = currentLang && aliases[currentLang] || resultLang;
        element.classList.add("hljs");
        element.classList.add(`language-${language}`);
      }
      __name(updateClassName, "updateClassName");
      function highlightElement(element) {
        let node = null;
        const language = blockLanguage(element);
        if (shouldNotHighlight(language)) return;
        fire(
          "before:highlightElement",
          { el: element, language }
        );
        if (element.dataset.highlighted) {
          console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.", element);
          return;
        }
        if (element.children.length > 0) {
          if (!options2.ignoreUnescapedHTML) {
            console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk.");
            console.warn("https://github.com/highlightjs/highlight.js/wiki/security");
            console.warn("The element with unescaped HTML:");
            console.warn(element);
          }
          if (options2.throwUnescapedHTML) {
            const err = new HTMLInjectionError(
              "One of your code blocks includes unescaped HTML.",
              element.innerHTML
            );
            throw err;
          }
        }
        node = element;
        const text = node.textContent;
        const result = language ? highlight2(text, { language, ignoreIllegals: true }) : highlightAuto(text);
        element.innerHTML = result.value;
        element.dataset.highlighted = "yes";
        updateClassName(element, language, result.language);
        element.result = {
          language: result.language,
          // TODO: remove with version 11.0
          re: result.relevance,
          relevance: result.relevance
        };
        if (result.secondBest) {
          element.secondBest = {
            language: result.secondBest.language,
            relevance: result.secondBest.relevance
          };
        }
        fire("after:highlightElement", { el: element, result, text });
      }
      __name(highlightElement, "highlightElement");
      function configure(userOptions2) {
        options2 = inherit(options2, userOptions2);
      }
      __name(configure, "configure");
      const initHighlighting = /* @__PURE__ */ __name(() => {
        highlightAll();
        deprecated("10.6.0", "initHighlighting() deprecated.  Use highlightAll() now.");
      }, "initHighlighting");
      function initHighlightingOnLoad() {
        highlightAll();
        deprecated("10.6.0", "initHighlightingOnLoad() deprecated.  Use highlightAll() now.");
      }
      __name(initHighlightingOnLoad, "initHighlightingOnLoad");
      let wantsHighlight = false;
      function highlightAll() {
        function boot() {
          highlightAll();
        }
        __name(boot, "boot");
        if (document.readyState === "loading") {
          if (!wantsHighlight) {
            window.addEventListener("DOMContentLoaded", boot, false);
          }
          wantsHighlight = true;
          return;
        }
        const blocks = document.querySelectorAll(options2.cssSelector);
        blocks.forEach(highlightElement);
      }
      __name(highlightAll, "highlightAll");
      function registerLanguage(languageName, languageDefinition) {
        let lang = null;
        try {
          lang = languageDefinition(hljs);
        } catch (error$1) {
          error("Language definition for '{}' could not be registered.".replace("{}", languageName));
          if (!SAFE_MODE) {
            throw error$1;
          } else {
            error(error$1);
          }
          lang = PLAINTEXT_LANGUAGE;
        }
        if (!lang.name) lang.name = languageName;
        languages[languageName] = lang;
        lang.rawDefinition = languageDefinition.bind(null, hljs);
        if (lang.aliases) {
          registerAliases(lang.aliases, { languageName });
        }
      }
      __name(registerLanguage, "registerLanguage");
      function unregisterLanguage(languageName) {
        delete languages[languageName];
        for (const alias of Object.keys(aliases)) {
          if (aliases[alias] === languageName) {
            delete aliases[alias];
          }
        }
      }
      __name(unregisterLanguage, "unregisterLanguage");
      function listLanguages() {
        return Object.keys(languages);
      }
      __name(listLanguages, "listLanguages");
      function getLanguage(name3) {
        name3 = (name3 || "").toLowerCase();
        return languages[name3] || languages[aliases[name3]];
      }
      __name(getLanguage, "getLanguage");
      function registerAliases(aliasList, { languageName }) {
        if (typeof aliasList === "string") {
          aliasList = [aliasList];
        }
        aliasList.forEach((alias) => {
          aliases[alias.toLowerCase()] = languageName;
        });
      }
      __name(registerAliases, "registerAliases");
      function autoDetection(name3) {
        const lang = getLanguage(name3);
        return lang && !lang.disableAutodetect;
      }
      __name(autoDetection, "autoDetection");
      function upgradePluginAPI(plugin) {
        if (plugin["before:highlightBlock"] && !plugin["before:highlightElement"]) {
          plugin["before:highlightElement"] = (data) => {
            plugin["before:highlightBlock"](
              Object.assign({ block: data.el }, data)
            );
          };
        }
        if (plugin["after:highlightBlock"] && !plugin["after:highlightElement"]) {
          plugin["after:highlightElement"] = (data) => {
            plugin["after:highlightBlock"](
              Object.assign({ block: data.el }, data)
            );
          };
        }
      }
      __name(upgradePluginAPI, "upgradePluginAPI");
      function addPlugin(plugin) {
        upgradePluginAPI(plugin);
        plugins.push(plugin);
      }
      __name(addPlugin, "addPlugin");
      function removePlugin(plugin) {
        const index = plugins.indexOf(plugin);
        if (index !== -1) {
          plugins.splice(index, 1);
        }
      }
      __name(removePlugin, "removePlugin");
      function fire(event, args) {
        const cb = event;
        plugins.forEach(function(plugin) {
          if (plugin[cb]) {
            plugin[cb](args);
          }
        });
      }
      __name(fire, "fire");
      function deprecateHighlightBlock(el) {
        deprecated("10.7.0", "highlightBlock will be removed entirely in v12.0");
        deprecated("10.7.0", "Please use highlightElement now.");
        return highlightElement(el);
      }
      __name(deprecateHighlightBlock, "deprecateHighlightBlock");
      Object.assign(hljs, {
        highlight: highlight2,
        highlightAuto,
        highlightAll,
        highlightElement,
        // TODO: Remove with v12 API
        highlightBlock: deprecateHighlightBlock,
        configure,
        initHighlighting,
        initHighlightingOnLoad,
        registerLanguage,
        unregisterLanguage,
        listLanguages,
        getLanguage,
        registerAliases,
        autoDetection,
        inherit,
        addPlugin,
        removePlugin
      });
      hljs.debugMode = function() {
        SAFE_MODE = false;
      };
      hljs.safeMode = function() {
        SAFE_MODE = true;
      };
      hljs.versionString = version2;
      hljs.regex = {
        concat: concat2,
        lookahead: lookahead2,
        either: either2,
        optional,
        anyNumberOfTimes
      };
      for (const key in MODES4) {
        if (typeof MODES4[key] === "object") {
          deepFreeze(MODES4[key]);
        }
      }
      Object.assign(hljs, MODES4);
      return hljs;
    }, "HLJS");
    var highlight = HLJS({});
    highlight.newInstance = () => HLJS({});
    module2.exports = highlight;
    highlight.HighlightJS = highlight;
    highlight.default = highlight;
  }
});

// node_modules/cli-spinners/spinners.json
var require_spinners = __commonJS({
  "node_modules/cli-spinners/spinners.json"(exports2, module2) {
    module2.exports = {
      dots: {
        interval: 80,
        frames: [
          "\u280B",
          "\u2819",
          "\u2839",
          "\u2838",
          "\u283C",
          "\u2834",
          "\u2826",
          "\u2827",
          "\u2807",
          "\u280F"
        ]
      },
      dots2: {
        interval: 80,
        frames: [
          "\u28FE",
          "\u28FD",
          "\u28FB",
          "\u28BF",
          "\u287F",
          "\u28DF",
          "\u28EF",
          "\u28F7"
        ]
      },
      dots3: {
        interval: 80,
        frames: [
          "\u280B",
          "\u2819",
          "\u281A",
          "\u281E",
          "\u2816",
          "\u2826",
          "\u2834",
          "\u2832",
          "\u2833",
          "\u2813"
        ]
      },
      dots4: {
        interval: 80,
        frames: [
          "\u2804",
          "\u2806",
          "\u2807",
          "\u280B",
          "\u2819",
          "\u2838",
          "\u2830",
          "\u2820",
          "\u2830",
          "\u2838",
          "\u2819",
          "\u280B",
          "\u2807",
          "\u2806"
        ]
      },
      dots5: {
        interval: 80,
        frames: [
          "\u280B",
          "\u2819",
          "\u281A",
          "\u2812",
          "\u2802",
          "\u2802",
          "\u2812",
          "\u2832",
          "\u2834",
          "\u2826",
          "\u2816",
          "\u2812",
          "\u2810",
          "\u2810",
          "\u2812",
          "\u2813",
          "\u280B"
        ]
      },
      dots6: {
        interval: 80,
        frames: [
          "\u2801",
          "\u2809",
          "\u2819",
          "\u281A",
          "\u2812",
          "\u2802",
          "\u2802",
          "\u2812",
          "\u2832",
          "\u2834",
          "\u2824",
          "\u2804",
          "\u2804",
          "\u2824",
          "\u2834",
          "\u2832",
          "\u2812",
          "\u2802",
          "\u2802",
          "\u2812",
          "\u281A",
          "\u2819",
          "\u2809",
          "\u2801"
        ]
      },
      dots7: {
        interval: 80,
        frames: [
          "\u2808",
          "\u2809",
          "\u280B",
          "\u2813",
          "\u2812",
          "\u2810",
          "\u2810",
          "\u2812",
          "\u2816",
          "\u2826",
          "\u2824",
          "\u2820",
          "\u2820",
          "\u2824",
          "\u2826",
          "\u2816",
          "\u2812",
          "\u2810",
          "\u2810",
          "\u2812",
          "\u2813",
          "\u280B",
          "\u2809",
          "\u2808"
        ]
      },
      dots8: {
        interval: 80,
        frames: [
          "\u2801",
          "\u2801",
          "\u2809",
          "\u2819",
          "\u281A",
          "\u2812",
          "\u2802",
          "\u2802",
          "\u2812",
          "\u2832",
          "\u2834",
          "\u2824",
          "\u2804",
          "\u2804",
          "\u2824",
          "\u2820",
          "\u2820",
          "\u2824",
          "\u2826",
          "\u2816",
          "\u2812",
          "\u2810",
          "\u2810",
          "\u2812",
          "\u2813",
          "\u280B",
          "\u2809",
          "\u2808",
          "\u2808"
        ]
      },
      dots9: {
        interval: 80,
        frames: [
          "\u28B9",
          "\u28BA",
          "\u28BC",
          "\u28F8",
          "\u28C7",
          "\u2867",
          "\u2857",
          "\u284F"
        ]
      },
      dots10: {
        interval: 80,
        frames: [
          "\u2884",
          "\u2882",
          "\u2881",
          "\u2841",
          "\u2848",
          "\u2850",
          "\u2860"
        ]
      },
      dots11: {
        interval: 100,
        frames: [
          "\u2801",
          "\u2802",
          "\u2804",
          "\u2840",
          "\u2880",
          "\u2820",
          "\u2810",
          "\u2808"
        ]
      },
      dots12: {
        interval: 80,
        frames: [
          "\u2880\u2800",
          "\u2840\u2800",
          "\u2804\u2800",
          "\u2882\u2800",
          "\u2842\u2800",
          "\u2805\u2800",
          "\u2883\u2800",
          "\u2843\u2800",
          "\u280D\u2800",
          "\u288B\u2800",
          "\u284B\u2800",
          "\u280D\u2801",
          "\u288B\u2801",
          "\u284B\u2801",
          "\u280D\u2809",
          "\u280B\u2809",
          "\u280B\u2809",
          "\u2809\u2819",
          "\u2809\u2819",
          "\u2809\u2829",
          "\u2808\u2899",
          "\u2808\u2859",
          "\u2888\u2829",
          "\u2840\u2899",
          "\u2804\u2859",
          "\u2882\u2829",
          "\u2842\u2898",
          "\u2805\u2858",
          "\u2883\u2828",
          "\u2843\u2890",
          "\u280D\u2850",
          "\u288B\u2820",
          "\u284B\u2880",
          "\u280D\u2841",
          "\u288B\u2801",
          "\u284B\u2801",
          "\u280D\u2809",
          "\u280B\u2809",
          "\u280B\u2809",
          "\u2809\u2819",
          "\u2809\u2819",
          "\u2809\u2829",
          "\u2808\u2899",
          "\u2808\u2859",
          "\u2808\u2829",
          "\u2800\u2899",
          "\u2800\u2859",
          "\u2800\u2829",
          "\u2800\u2898",
          "\u2800\u2858",
          "\u2800\u2828",
          "\u2800\u2890",
          "\u2800\u2850",
          "\u2800\u2820",
          "\u2800\u2880",
          "\u2800\u2840"
        ]
      },
      dots13: {
        interval: 80,
        frames: [
          "\u28FC",
          "\u28F9",
          "\u28BB",
          "\u283F",
          "\u285F",
          "\u28CF",
          "\u28E7",
          "\u28F6"
        ]
      },
      dots8Bit: {
        interval: 80,
        frames: [
          "\u2800",
          "\u2801",
          "\u2802",
          "\u2803",
          "\u2804",
          "\u2805",
          "\u2806",
          "\u2807",
          "\u2840",
          "\u2841",
          "\u2842",
          "\u2843",
          "\u2844",
          "\u2845",
          "\u2846",
          "\u2847",
          "\u2808",
          "\u2809",
          "\u280A",
          "\u280B",
          "\u280C",
          "\u280D",
          "\u280E",
          "\u280F",
          "\u2848",
          "\u2849",
          "\u284A",
          "\u284B",
          "\u284C",
          "\u284D",
          "\u284E",
          "\u284F",
          "\u2810",
          "\u2811",
          "\u2812",
          "\u2813",
          "\u2814",
          "\u2815",
          "\u2816",
          "\u2817",
          "\u2850",
          "\u2851",
          "\u2852",
          "\u2853",
          "\u2854",
          "\u2855",
          "\u2856",
          "\u2857",
          "\u2818",
          "\u2819",
          "\u281A",
          "\u281B",
          "\u281C",
          "\u281D",
          "\u281E",
          "\u281F",
          "\u2858",
          "\u2859",
          "\u285A",
          "\u285B",
          "\u285C",
          "\u285D",
          "\u285E",
          "\u285F",
          "\u2820",
          "\u2821",
          "\u2822",
          "\u2823",
          "\u2824",
          "\u2825",
          "\u2826",
          "\u2827",
          "\u2860",
          "\u2861",
          "\u2862",
          "\u2863",
          "\u2864",
          "\u2865",
          "\u2866",
          "\u2867",
          "\u2828",
          "\u2829",
          "\u282A",
          "\u282B",
          "\u282C",
          "\u282D",
          "\u282E",
          "\u282F",
          "\u2868",
          "\u2869",
          "\u286A",
          "\u286B",
          "\u286C",
          "\u286D",
          "\u286E",
          "\u286F",
          "\u2830",
          "\u2831",
          "\u2832",
          "\u2833",
          "\u2834",
          "\u2835",
          "\u2836",
          "\u2837",
          "\u2870",
          "\u2871",
          "\u2872",
          "\u2873",
          "\u2874",
          "\u2875",
          "\u2876",
          "\u2877",
          "\u2838",
          "\u2839",
          "\u283A",
          "\u283B",
          "\u283C",
          "\u283D",
          "\u283E",
          "\u283F",
          "\u2878",
          "\u2879",
          "\u287A",
          "\u287B",
          "\u287C",
          "\u287D",
          "\u287E",
          "\u287F",
          "\u2880",
          "\u2881",
          "\u2882",
          "\u2883",
          "\u2884",
          "\u2885",
          "\u2886",
          "\u2887",
          "\u28C0",
          "\u28C1",
          "\u28C2",
          "\u28C3",
          "\u28C4",
          "\u28C5",
          "\u28C6",
          "\u28C7",
          "\u2888",
          "\u2889",
          "\u288A",
          "\u288B",
          "\u288C",
          "\u288D",
          "\u288E",
          "\u288F",
          "\u28C8",
          "\u28C9",
          "\u28CA",
          "\u28CB",
          "\u28CC",
          "\u28CD",
          "\u28CE",
          "\u28CF",
          "\u2890",
          "\u2891",
          "\u2892",
          "\u2893",
          "\u2894",
          "\u2895",
          "\u2896",
          "\u2897",
          "\u28D0",
          "\u28D1",
          "\u28D2",
          "\u28D3",
          "\u28D4",
          "\u28D5",
          "\u28D6",
          "\u28D7",
          "\u2898",
          "\u2899",
          "\u289A",
          "\u289B",
          "\u289C",
          "\u289D",
          "\u289E",
          "\u289F",
          "\u28D8",
          "\u28D9",
          "\u28DA",
          "\u28DB",
          "\u28DC",
          "\u28DD",
          "\u28DE",
          "\u28DF",
          "\u28A0",
          "\u28A1",
          "\u28A2",
          "\u28A3",
          "\u28A4",
          "\u28A5",
          "\u28A6",
          "\u28A7",
          "\u28E0",
          "\u28E1",
          "\u28E2",
          "\u28E3",
          "\u28E4",
          "\u28E5",
          "\u28E6",
          "\u28E7",
          "\u28A8",
          "\u28A9",
          "\u28AA",
          "\u28AB",
          "\u28AC",
          "\u28AD",
          "\u28AE",
          "\u28AF",
          "\u28E8",
          "\u28E9",
          "\u28EA",
          "\u28EB",
          "\u28EC",
          "\u28ED",
          "\u28EE",
          "\u28EF",
          "\u28B0",
          "\u28B1",
          "\u28B2",
          "\u28B3",
          "\u28B4",
          "\u28B5",
          "\u28B6",
          "\u28B7",
          "\u28F0",
          "\u28F1",
          "\u28F2",
          "\u28F3",
          "\u28F4",
          "\u28F5",
          "\u28F6",
          "\u28F7",
          "\u28B8",
          "\u28B9",
          "\u28BA",
          "\u28BB",
          "\u28BC",
          "\u28BD",
          "\u28BE",
          "\u28BF",
          "\u28F8",
          "\u28F9",
          "\u28FA",
          "\u28FB",
          "\u28FC",
          "\u28FD",
          "\u28FE",
          "\u28FF"
        ]
      },
      sand: {
        interval: 80,
        frames: [
          "\u2801",
          "\u2802",
          "\u2804",
          "\u2840",
          "\u2848",
          "\u2850",
          "\u2860",
          "\u28C0",
          "\u28C1",
          "\u28C2",
          "\u28C4",
          "\u28CC",
          "\u28D4",
          "\u28E4",
          "\u28E5",
          "\u28E6",
          "\u28EE",
          "\u28F6",
          "\u28F7",
          "\u28FF",
          "\u287F",
          "\u283F",
          "\u289F",
          "\u281F",
          "\u285B",
          "\u281B",
          "\u282B",
          "\u288B",
          "\u280B",
          "\u280D",
          "\u2849",
          "\u2809",
          "\u2811",
          "\u2821",
          "\u2881"
        ]
      },
      line: {
        interval: 130,
        frames: [
          "-",
          "\\",
          "|",
          "/"
        ]
      },
      line2: {
        interval: 100,
        frames: [
          "\u2802",
          "-",
          "\u2013",
          "\u2014",
          "\u2013",
          "-"
        ]
      },
      pipe: {
        interval: 100,
        frames: [
          "\u2524",
          "\u2518",
          "\u2534",
          "\u2514",
          "\u251C",
          "\u250C",
          "\u252C",
          "\u2510"
        ]
      },
      simpleDots: {
        interval: 400,
        frames: [
          ".  ",
          ".. ",
          "...",
          "   "
        ]
      },
      simpleDotsScrolling: {
        interval: 200,
        frames: [
          ".  ",
          ".. ",
          "...",
          " ..",
          "  .",
          "   "
        ]
      },
      star: {
        interval: 70,
        frames: [
          "\u2736",
          "\u2738",
          "\u2739",
          "\u273A",
          "\u2739",
          "\u2737"
        ]
      },
      star2: {
        interval: 80,
        frames: [
          "+",
          "x",
          "*"
        ]
      },
      flip: {
        interval: 70,
        frames: [
          "_",
          "_",
          "_",
          "-",
          "`",
          "`",
          "'",
          "\xB4",
          "-",
          "_",
          "_",
          "_"
        ]
      },
      hamburger: {
        interval: 100,
        frames: [
          "\u2631",
          "\u2632",
          "\u2634"
        ]
      },
      growVertical: {
        interval: 120,
        frames: [
          "\u2581",
          "\u2583",
          "\u2584",
          "\u2585",
          "\u2586",
          "\u2587",
          "\u2586",
          "\u2585",
          "\u2584",
          "\u2583"
        ]
      },
      growHorizontal: {
        interval: 120,
        frames: [
          "\u258F",
          "\u258E",
          "\u258D",
          "\u258C",
          "\u258B",
          "\u258A",
          "\u2589",
          "\u258A",
          "\u258B",
          "\u258C",
          "\u258D",
          "\u258E"
        ]
      },
      balloon: {
        interval: 140,
        frames: [
          " ",
          ".",
          "o",
          "O",
          "@",
          "*",
          " "
        ]
      },
      balloon2: {
        interval: 120,
        frames: [
          ".",
          "o",
          "O",
          "\xB0",
          "O",
          "o",
          "."
        ]
      },
      noise: {
        interval: 100,
        frames: [
          "\u2593",
          "\u2592",
          "\u2591"
        ]
      },
      bounce: {
        interval: 120,
        frames: [
          "\u2801",
          "\u2802",
          "\u2804",
          "\u2802"
        ]
      },
      boxBounce: {
        interval: 120,
        frames: [
          "\u2596",
          "\u2598",
          "\u259D",
          "\u2597"
        ]
      },
      boxBounce2: {
        interval: 100,
        frames: [
          "\u258C",
          "\u2580",
          "\u2590",
          "\u2584"
        ]
      },
      triangle: {
        interval: 50,
        frames: [
          "\u25E2",
          "\u25E3",
          "\u25E4",
          "\u25E5"
        ]
      },
      binary: {
        interval: 80,
        frames: [
          "010010",
          "001100",
          "100101",
          "111010",
          "111101",
          "010111",
          "101011",
          "111000",
          "110011",
          "110101"
        ]
      },
      arc: {
        interval: 100,
        frames: [
          "\u25DC",
          "\u25E0",
          "\u25DD",
          "\u25DE",
          "\u25E1",
          "\u25DF"
        ]
      },
      circle: {
        interval: 120,
        frames: [
          "\u25E1",
          "\u2299",
          "\u25E0"
        ]
      },
      squareCorners: {
        interval: 180,
        frames: [
          "\u25F0",
          "\u25F3",
          "\u25F2",
          "\u25F1"
        ]
      },
      circleQuarters: {
        interval: 120,
        frames: [
          "\u25F4",
          "\u25F7",
          "\u25F6",
          "\u25F5"
        ]
      },
      circleHalves: {
        interval: 50,
        frames: [
          "\u25D0",
          "\u25D3",
          "\u25D1",
          "\u25D2"
        ]
      },
      squish: {
        interval: 100,
        frames: [
          "\u256B",
          "\u256A"
        ]
      },
      toggle: {
        interval: 250,
        frames: [
          "\u22B6",
          "\u22B7"
        ]
      },
      toggle2: {
        interval: 80,
        frames: [
          "\u25AB",
          "\u25AA"
        ]
      },
      toggle3: {
        interval: 120,
        frames: [
          "\u25A1",
          "\u25A0"
        ]
      },
      toggle4: {
        interval: 100,
        frames: [
          "\u25A0",
          "\u25A1",
          "\u25AA",
          "\u25AB"
        ]
      },
      toggle5: {
        interval: 100,
        frames: [
          "\u25AE",
          "\u25AF"
        ]
      },
      toggle6: {
        interval: 300,
        frames: [
          "\u101D",
          "\u1040"
        ]
      },
      toggle7: {
        interval: 80,
        frames: [
          "\u29BE",
          "\u29BF"
        ]
      },
      toggle8: {
        interval: 100,
        frames: [
          "\u25CD",
          "\u25CC"
        ]
      },
      toggle9: {
        interval: 100,
        frames: [
          "\u25C9",
          "\u25CE"
        ]
      },
      toggle10: {
        interval: 100,
        frames: [
          "\u3282",
          "\u3280",
          "\u3281"
        ]
      },
      toggle11: {
        interval: 50,
        frames: [
          "\u29C7",
          "\u29C6"
        ]
      },
      toggle12: {
        interval: 120,
        frames: [
          "\u2617",
          "\u2616"
        ]
      },
      toggle13: {
        interval: 80,
        frames: [
          "=",
          "*",
          "-"
        ]
      },
      arrow: {
        interval: 100,
        frames: [
          "\u2190",
          "\u2196",
          "\u2191",
          "\u2197",
          "\u2192",
          "\u2198",
          "\u2193",
          "\u2199"
        ]
      },
      arrow2: {
        interval: 80,
        frames: [
          "\u2B06\uFE0F ",
          "\u2197\uFE0F ",
          "\u27A1\uFE0F ",
          "\u2198\uFE0F ",
          "\u2B07\uFE0F ",
          "\u2199\uFE0F ",
          "\u2B05\uFE0F ",
          "\u2196\uFE0F "
        ]
      },
      arrow3: {
        interval: 120,
        frames: [
          "\u25B9\u25B9\u25B9\u25B9\u25B9",
          "\u25B8\u25B9\u25B9\u25B9\u25B9",
          "\u25B9\u25B8\u25B9\u25B9\u25B9",
          "\u25B9\u25B9\u25B8\u25B9\u25B9",
          "\u25B9\u25B9\u25B9\u25B8\u25B9",
          "\u25B9\u25B9\u25B9\u25B9\u25B8"
        ]
      },
      bouncingBar: {
        interval: 80,
        frames: [
          "[    ]",
          "[=   ]",
          "[==  ]",
          "[=== ]",
          "[====]",
          "[ ===]",
          "[  ==]",
          "[   =]",
          "[    ]",
          "[   =]",
          "[  ==]",
          "[ ===]",
          "[====]",
          "[=== ]",
          "[==  ]",
          "[=   ]"
        ]
      },
      bouncingBall: {
        interval: 80,
        frames: [
          "( \u25CF    )",
          "(  \u25CF   )",
          "(   \u25CF  )",
          "(    \u25CF )",
          "(     \u25CF)",
          "(    \u25CF )",
          "(   \u25CF  )",
          "(  \u25CF   )",
          "( \u25CF    )",
          "(\u25CF     )"
        ]
      },
      smiley: {
        interval: 200,
        frames: [
          "\u{1F604} ",
          "\u{1F61D} "
        ]
      },
      monkey: {
        interval: 300,
        frames: [
          "\u{1F648} ",
          "\u{1F648} ",
          "\u{1F649} ",
          "\u{1F64A} "
        ]
      },
      hearts: {
        interval: 100,
        frames: [
          "\u{1F49B} ",
          "\u{1F499} ",
          "\u{1F49C} ",
          "\u{1F49A} ",
          "\u2764\uFE0F "
        ]
      },
      clock: {
        interval: 100,
        frames: [
          "\u{1F55B} ",
          "\u{1F550} ",
          "\u{1F551} ",
          "\u{1F552} ",
          "\u{1F553} ",
          "\u{1F554} ",
          "\u{1F555} ",
          "\u{1F556} ",
          "\u{1F557} ",
          "\u{1F558} ",
          "\u{1F559} ",
          "\u{1F55A} "
        ]
      },
      earth: {
        interval: 180,
        frames: [
          "\u{1F30D} ",
          "\u{1F30E} ",
          "\u{1F30F} "
        ]
      },
      material: {
        interval: 17,
        frames: [
          "\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588",
          "\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588",
          "\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588",
          "\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588",
          "\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588",
          "\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588",
          "\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588",
          "\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581"
        ]
      },
      moon: {
        interval: 80,
        frames: [
          "\u{1F311} ",
          "\u{1F312} ",
          "\u{1F313} ",
          "\u{1F314} ",
          "\u{1F315} ",
          "\u{1F316} ",
          "\u{1F317} ",
          "\u{1F318} "
        ]
      },
      runner: {
        interval: 140,
        frames: [
          "\u{1F6B6} ",
          "\u{1F3C3} "
        ]
      },
      pong: {
        interval: 80,
        frames: [
          "\u2590\u2802       \u258C",
          "\u2590\u2808       \u258C",
          "\u2590 \u2802      \u258C",
          "\u2590 \u2820      \u258C",
          "\u2590  \u2840     \u258C",
          "\u2590  \u2820     \u258C",
          "\u2590   \u2802    \u258C",
          "\u2590   \u2808    \u258C",
          "\u2590    \u2802   \u258C",
          "\u2590    \u2820   \u258C",
          "\u2590     \u2840  \u258C",
          "\u2590     \u2820  \u258C",
          "\u2590      \u2802 \u258C",
          "\u2590      \u2808 \u258C",
          "\u2590       \u2802\u258C",
          "\u2590       \u2820\u258C",
          "\u2590       \u2840\u258C",
          "\u2590      \u2820 \u258C",
          "\u2590      \u2802 \u258C",
          "\u2590     \u2808  \u258C",
          "\u2590     \u2802  \u258C",
          "\u2590    \u2820   \u258C",
          "\u2590    \u2840   \u258C",
          "\u2590   \u2820    \u258C",
          "\u2590   \u2802    \u258C",
          "\u2590  \u2808     \u258C",
          "\u2590  \u2802     \u258C",
          "\u2590 \u2820      \u258C",
          "\u2590 \u2840      \u258C",
          "\u2590\u2820       \u258C"
        ]
      },
      shark: {
        interval: 120,
        frames: [
          "\u2590|\\____________\u258C",
          "\u2590_|\\___________\u258C",
          "\u2590__|\\__________\u258C",
          "\u2590___|\\_________\u258C",
          "\u2590____|\\________\u258C",
          "\u2590_____|\\_______\u258C",
          "\u2590______|\\______\u258C",
          "\u2590_______|\\_____\u258C",
          "\u2590________|\\____\u258C",
          "\u2590_________|\\___\u258C",
          "\u2590__________|\\__\u258C",
          "\u2590___________|\\_\u258C",
          "\u2590____________|\\\u258C",
          "\u2590____________/|\u258C",
          "\u2590___________/|_\u258C",
          "\u2590__________/|__\u258C",
          "\u2590_________/|___\u258C",
          "\u2590________/|____\u258C",
          "\u2590_______/|_____\u258C",
          "\u2590______/|______\u258C",
          "\u2590_____/|_______\u258C",
          "\u2590____/|________\u258C",
          "\u2590___/|_________\u258C",
          "\u2590__/|__________\u258C",
          "\u2590_/|___________\u258C",
          "\u2590/|____________\u258C"
        ]
      },
      dqpb: {
        interval: 100,
        frames: [
          "d",
          "q",
          "p",
          "b"
        ]
      },
      weather: {
        interval: 100,
        frames: [
          "\u2600\uFE0F ",
          "\u2600\uFE0F ",
          "\u2600\uFE0F ",
          "\u{1F324} ",
          "\u26C5\uFE0F ",
          "\u{1F325} ",
          "\u2601\uFE0F ",
          "\u{1F327} ",
          "\u{1F328} ",
          "\u{1F327} ",
          "\u{1F328} ",
          "\u{1F327} ",
          "\u{1F328} ",
          "\u26C8 ",
          "\u{1F328} ",
          "\u{1F327} ",
          "\u{1F328} ",
          "\u2601\uFE0F ",
          "\u{1F325} ",
          "\u26C5\uFE0F ",
          "\u{1F324} ",
          "\u2600\uFE0F ",
          "\u2600\uFE0F "
        ]
      },
      christmas: {
        interval: 400,
        frames: [
          "\u{1F332}",
          "\u{1F384}"
        ]
      },
      grenade: {
        interval: 80,
        frames: [
          "\u060C  ",
          "\u2032  ",
          " \xB4 ",
          " \u203E ",
          "  \u2E0C",
          "  \u2E0A",
          "  |",
          "  \u204E",
          "  \u2055",
          " \u0DF4 ",
          "  \u2053",
          "   ",
          "   ",
          "   "
        ]
      },
      point: {
        interval: 125,
        frames: [
          "\u2219\u2219\u2219",
          "\u25CF\u2219\u2219",
          "\u2219\u25CF\u2219",
          "\u2219\u2219\u25CF",
          "\u2219\u2219\u2219"
        ]
      },
      layer: {
        interval: 150,
        frames: [
          "-",
          "=",
          "\u2261"
        ]
      },
      betaWave: {
        interval: 80,
        frames: [
          "\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2",
          "\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2",
          "\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2",
          "\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2",
          "\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2",
          "\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2",
          "\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1"
        ]
      },
      fingerDance: {
        interval: 160,
        frames: [
          "\u{1F918} ",
          "\u{1F91F} ",
          "\u{1F596} ",
          "\u270B ",
          "\u{1F91A} ",
          "\u{1F446} "
        ]
      },
      fistBump: {
        interval: 80,
        frames: [
          "\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ",
          "\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ",
          "\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ",
          "\u3000\u{1F91C}\u3000\u3000\u{1F91B}\u3000 ",
          "\u3000\u3000\u{1F91C}\u{1F91B}\u3000\u3000 ",
          "\u3000\u{1F91C}\u2728\u{1F91B}\u3000\u3000 ",
          "\u{1F91C}\u3000\u2728\u3000\u{1F91B}\u3000 "
        ]
      },
      soccerHeader: {
        interval: 80,
        frames: [
          " \u{1F9D1}\u26BD\uFE0F       \u{1F9D1} ",
          "\u{1F9D1}  \u26BD\uFE0F      \u{1F9D1} ",
          "\u{1F9D1}   \u26BD\uFE0F     \u{1F9D1} ",
          "\u{1F9D1}    \u26BD\uFE0F    \u{1F9D1} ",
          "\u{1F9D1}     \u26BD\uFE0F   \u{1F9D1} ",
          "\u{1F9D1}      \u26BD\uFE0F  \u{1F9D1} ",
          "\u{1F9D1}       \u26BD\uFE0F\u{1F9D1}  ",
          "\u{1F9D1}      \u26BD\uFE0F  \u{1F9D1} ",
          "\u{1F9D1}     \u26BD\uFE0F   \u{1F9D1} ",
          "\u{1F9D1}    \u26BD\uFE0F    \u{1F9D1} ",
          "\u{1F9D1}   \u26BD\uFE0F     \u{1F9D1} ",
          "\u{1F9D1}  \u26BD\uFE0F      \u{1F9D1} "
        ]
      },
      mindblown: {
        interval: 160,
        frames: [
          "\u{1F610} ",
          "\u{1F610} ",
          "\u{1F62E} ",
          "\u{1F62E} ",
          "\u{1F626} ",
          "\u{1F626} ",
          "\u{1F627} ",
          "\u{1F627} ",
          "\u{1F92F} ",
          "\u{1F4A5} ",
          "\u2728 ",
          "\u3000 ",
          "\u3000 ",
          "\u3000 "
        ]
      },
      speaker: {
        interval: 160,
        frames: [
          "\u{1F508} ",
          "\u{1F509} ",
          "\u{1F50A} ",
          "\u{1F509} "
        ]
      },
      orangePulse: {
        interval: 100,
        frames: [
          "\u{1F538} ",
          "\u{1F536} ",
          "\u{1F7E0} ",
          "\u{1F7E0} ",
          "\u{1F536} "
        ]
      },
      bluePulse: {
        interval: 100,
        frames: [
          "\u{1F539} ",
          "\u{1F537} ",
          "\u{1F535} ",
          "\u{1F535} ",
          "\u{1F537} "
        ]
      },
      orangeBluePulse: {
        interval: 100,
        frames: [
          "\u{1F538} ",
          "\u{1F536} ",
          "\u{1F7E0} ",
          "\u{1F7E0} ",
          "\u{1F536} ",
          "\u{1F539} ",
          "\u{1F537} ",
          "\u{1F535} ",
          "\u{1F535} ",
          "\u{1F537} "
        ]
      },
      timeTravel: {
        interval: 100,
        frames: [
          "\u{1F55B} ",
          "\u{1F55A} ",
          "\u{1F559} ",
          "\u{1F558} ",
          "\u{1F557} ",
          "\u{1F556} ",
          "\u{1F555} ",
          "\u{1F554} ",
          "\u{1F553} ",
          "\u{1F552} ",
          "\u{1F551} ",
          "\u{1F550} "
        ]
      },
      aesthetic: {
        interval: 80,
        frames: [
          "\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1",
          "\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1",
          "\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1",
          "\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1",
          "\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1",
          "\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1",
          "\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0",
          "\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1"
        ]
      },
      dwarfFortress: {
        interval: 80,
        frames: [
          " \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "\u263A \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u263A \u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u263A \u2588\u2588\u2588\xA3\xA3\xA3  ",
          "   \u263A\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "   \u263A\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "   \u263A\u2593\u2588\u2588\xA3\xA3\xA3  ",
          "   \u263A\u2593\u2588\u2588\xA3\xA3\xA3  ",
          "   \u263A\u2592\u2588\u2588\xA3\xA3\xA3  ",
          "   \u263A\u2592\u2588\u2588\xA3\xA3\xA3  ",
          "   \u263A\u2591\u2588\u2588\xA3\xA3\xA3  ",
          "   \u263A\u2591\u2588\u2588\xA3\xA3\xA3  ",
          "   \u263A \u2588\u2588\xA3\xA3\xA3  ",
          "    \u263A\u2588\u2588\xA3\xA3\xA3  ",
          "    \u263A\u2588\u2588\xA3\xA3\xA3  ",
          "    \u263A\u2593\u2588\xA3\xA3\xA3  ",
          "    \u263A\u2593\u2588\xA3\xA3\xA3  ",
          "    \u263A\u2592\u2588\xA3\xA3\xA3  ",
          "    \u263A\u2592\u2588\xA3\xA3\xA3  ",
          "    \u263A\u2591\u2588\xA3\xA3\xA3  ",
          "    \u263A\u2591\u2588\xA3\xA3\xA3  ",
          "    \u263A \u2588\xA3\xA3\xA3  ",
          "     \u263A\u2588\xA3\xA3\xA3  ",
          "     \u263A\u2588\xA3\xA3\xA3  ",
          "     \u263A\u2593\xA3\xA3\xA3  ",
          "     \u263A\u2593\xA3\xA3\xA3  ",
          "     \u263A\u2592\xA3\xA3\xA3  ",
          "     \u263A\u2592\xA3\xA3\xA3  ",
          "     \u263A\u2591\xA3\xA3\xA3  ",
          "     \u263A\u2591\xA3\xA3\xA3  ",
          "     \u263A \xA3\xA3\xA3  ",
          "      \u263A\xA3\xA3\xA3  ",
          "      \u263A\xA3\xA3\xA3  ",
          "      \u263A\u2593\xA3\xA3  ",
          "      \u263A\u2593\xA3\xA3  ",
          "      \u263A\u2592\xA3\xA3  ",
          "      \u263A\u2592\xA3\xA3  ",
          "      \u263A\u2591\xA3\xA3  ",
          "      \u263A\u2591\xA3\xA3  ",
          "      \u263A \xA3\xA3  ",
          "       \u263A\xA3\xA3  ",
          "       \u263A\xA3\xA3  ",
          "       \u263A\u2593\xA3  ",
          "       \u263A\u2593\xA3  ",
          "       \u263A\u2592\xA3  ",
          "       \u263A\u2592\xA3  ",
          "       \u263A\u2591\xA3  ",
          "       \u263A\u2591\xA3  ",
          "       \u263A \xA3  ",
          "        \u263A\xA3  ",
          "        \u263A\xA3  ",
          "        \u263A\u2593  ",
          "        \u263A\u2593  ",
          "        \u263A\u2592  ",
          "        \u263A\u2592  ",
          "        \u263A\u2591  ",
          "        \u263A\u2591  ",
          "        \u263A   ",
          "        \u263A  &",
          "        \u263A \u263C&",
          "       \u263A \u263C &",
          "       \u263A\u263C  &",
          "      \u263A\u263C  & ",
          "      \u203C   & ",
          "     \u263A   &  ",
          "    \u203C    &  ",
          "   \u263A    &   ",
          "  \u203C     &   ",
          " \u263A     &    ",
          "\u203C      &    ",
          "      &     ",
          "      &     ",
          "     &   \u2591  ",
          "     &   \u2592  ",
          "    &    \u2593  ",
          "    &    \xA3  ",
          "   &    \u2591\xA3  ",
          "   &    \u2592\xA3  ",
          "  &     \u2593\xA3  ",
          "  &     \xA3\xA3  ",
          " &     \u2591\xA3\xA3  ",
          " &     \u2592\xA3\xA3  ",
          "&      \u2593\xA3\xA3  ",
          "&      \xA3\xA3\xA3  ",
          "      \u2591\xA3\xA3\xA3  ",
          "      \u2592\xA3\xA3\xA3  ",
          "      \u2593\xA3\xA3\xA3  ",
          "      \u2588\xA3\xA3\xA3  ",
          "     \u2591\u2588\xA3\xA3\xA3  ",
          "     \u2592\u2588\xA3\xA3\xA3  ",
          "     \u2593\u2588\xA3\xA3\xA3  ",
          "     \u2588\u2588\xA3\xA3\xA3  ",
          "    \u2591\u2588\u2588\xA3\xA3\xA3  ",
          "    \u2592\u2588\u2588\xA3\xA3\xA3  ",
          "    \u2593\u2588\u2588\xA3\xA3\xA3  ",
          "    \u2588\u2588\u2588\xA3\xA3\xA3  ",
          "   \u2591\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "   \u2592\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "   \u2593\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "   \u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  "
        ]
      }
    };
  }
});

// node_modules/cli-spinners/index.js
var require_cli_spinners = __commonJS({
  "node_modules/cli-spinners/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var spinners2 = Object.assign({}, require_spinners());
    var spinnersList = Object.keys(spinners2);
    Object.defineProperty(spinners2, "random", {
      get() {
        const randomIndex = Math.floor(Math.random() * spinnersList.length);
        const spinnerName = spinnersList[randomIndex];
        return spinners2[spinnerName];
      }
    });
    module2.exports = spinners2;
  }
});

// node_modules/color-name/index.js
var require_color_name = __commonJS({
  "node_modules/color-name/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      "aliceblue": [240, 248, 255],
      "antiquewhite": [250, 235, 215],
      "aqua": [0, 255, 255],
      "aquamarine": [127, 255, 212],
      "azure": [240, 255, 255],
      "beige": [245, 245, 220],
      "bisque": [255, 228, 196],
      "black": [0, 0, 0],
      "blanchedalmond": [255, 235, 205],
      "blue": [0, 0, 255],
      "blueviolet": [138, 43, 226],
      "brown": [165, 42, 42],
      "burlywood": [222, 184, 135],
      "cadetblue": [95, 158, 160],
      "chartreuse": [127, 255, 0],
      "chocolate": [210, 105, 30],
      "coral": [255, 127, 80],
      "cornflowerblue": [100, 149, 237],
      "cornsilk": [255, 248, 220],
      "crimson": [220, 20, 60],
      "cyan": [0, 255, 255],
      "darkblue": [0, 0, 139],
      "darkcyan": [0, 139, 139],
      "darkgoldenrod": [184, 134, 11],
      "darkgray": [169, 169, 169],
      "darkgreen": [0, 100, 0],
      "darkgrey": [169, 169, 169],
      "darkkhaki": [189, 183, 107],
      "darkmagenta": [139, 0, 139],
      "darkolivegreen": [85, 107, 47],
      "darkorange": [255, 140, 0],
      "darkorchid": [153, 50, 204],
      "darkred": [139, 0, 0],
      "darksalmon": [233, 150, 122],
      "darkseagreen": [143, 188, 143],
      "darkslateblue": [72, 61, 139],
      "darkslategray": [47, 79, 79],
      "darkslategrey": [47, 79, 79],
      "darkturquoise": [0, 206, 209],
      "darkviolet": [148, 0, 211],
      "deeppink": [255, 20, 147],
      "deepskyblue": [0, 191, 255],
      "dimgray": [105, 105, 105],
      "dimgrey": [105, 105, 105],
      "dodgerblue": [30, 144, 255],
      "firebrick": [178, 34, 34],
      "floralwhite": [255, 250, 240],
      "forestgreen": [34, 139, 34],
      "fuchsia": [255, 0, 255],
      "gainsboro": [220, 220, 220],
      "ghostwhite": [248, 248, 255],
      "gold": [255, 215, 0],
      "goldenrod": [218, 165, 32],
      "gray": [128, 128, 128],
      "green": [0, 128, 0],
      "greenyellow": [173, 255, 47],
      "grey": [128, 128, 128],
      "honeydew": [240, 255, 240],
      "hotpink": [255, 105, 180],
      "indianred": [205, 92, 92],
      "indigo": [75, 0, 130],
      "ivory": [255, 255, 240],
      "khaki": [240, 230, 140],
      "lavender": [230, 230, 250],
      "lavenderblush": [255, 240, 245],
      "lawngreen": [124, 252, 0],
      "lemonchiffon": [255, 250, 205],
      "lightblue": [173, 216, 230],
      "lightcoral": [240, 128, 128],
      "lightcyan": [224, 255, 255],
      "lightgoldenrodyellow": [250, 250, 210],
      "lightgray": [211, 211, 211],
      "lightgreen": [144, 238, 144],
      "lightgrey": [211, 211, 211],
      "lightpink": [255, 182, 193],
      "lightsalmon": [255, 160, 122],
      "lightseagreen": [32, 178, 170],
      "lightskyblue": [135, 206, 250],
      "lightslategray": [119, 136, 153],
      "lightslategrey": [119, 136, 153],
      "lightsteelblue": [176, 196, 222],
      "lightyellow": [255, 255, 224],
      "lime": [0, 255, 0],
      "limegreen": [50, 205, 50],
      "linen": [250, 240, 230],
      "magenta": [255, 0, 255],
      "maroon": [128, 0, 0],
      "mediumaquamarine": [102, 205, 170],
      "mediumblue": [0, 0, 205],
      "mediumorchid": [186, 85, 211],
      "mediumpurple": [147, 112, 219],
      "mediumseagreen": [60, 179, 113],
      "mediumslateblue": [123, 104, 238],
      "mediumspringgreen": [0, 250, 154],
      "mediumturquoise": [72, 209, 204],
      "mediumvioletred": [199, 21, 133],
      "midnightblue": [25, 25, 112],
      "mintcream": [245, 255, 250],
      "mistyrose": [255, 228, 225],
      "moccasin": [255, 228, 181],
      "navajowhite": [255, 222, 173],
      "navy": [0, 0, 128],
      "oldlace": [253, 245, 230],
      "olive": [128, 128, 0],
      "olivedrab": [107, 142, 35],
      "orange": [255, 165, 0],
      "orangered": [255, 69, 0],
      "orchid": [218, 112, 214],
      "palegoldenrod": [238, 232, 170],
      "palegreen": [152, 251, 152],
      "paleturquoise": [175, 238, 238],
      "palevioletred": [219, 112, 147],
      "papayawhip": [255, 239, 213],
      "peachpuff": [255, 218, 185],
      "peru": [205, 133, 63],
      "pink": [255, 192, 203],
      "plum": [221, 160, 221],
      "powderblue": [176, 224, 230],
      "purple": [128, 0, 128],
      "rebeccapurple": [102, 51, 153],
      "red": [255, 0, 0],
      "rosybrown": [188, 143, 143],
      "royalblue": [65, 105, 225],
      "saddlebrown": [139, 69, 19],
      "salmon": [250, 128, 114],
      "sandybrown": [244, 164, 96],
      "seagreen": [46, 139, 87],
      "seashell": [255, 245, 238],
      "sienna": [160, 82, 45],
      "silver": [192, 192, 192],
      "skyblue": [135, 206, 235],
      "slateblue": [106, 90, 205],
      "slategray": [112, 128, 144],
      "slategrey": [112, 128, 144],
      "snow": [255, 250, 250],
      "springgreen": [0, 255, 127],
      "steelblue": [70, 130, 180],
      "tan": [210, 180, 140],
      "teal": [0, 128, 128],
      "thistle": [216, 191, 216],
      "tomato": [255, 99, 71],
      "turquoise": [64, 224, 208],
      "violet": [238, 130, 238],
      "wheat": [245, 222, 179],
      "white": [255, 255, 255],
      "whitesmoke": [245, 245, 245],
      "yellow": [255, 255, 0],
      "yellowgreen": [154, 205, 50]
    };
  }
});

// node_modules/color-convert/conversions.js
var require_conversions = __commonJS({
  "node_modules/color-convert/conversions.js"(exports2, module2) {
    init_esbuild_shims();
    var cssKeywords = require_color_name();
    var reverseKeywords = {};
    for (const key of Object.keys(cssKeywords)) {
      reverseKeywords[cssKeywords[key]] = key;
    }
    var convert2 = {
      rgb: { channels: 3, labels: "rgb" },
      hsl: { channels: 3, labels: "hsl" },
      hsv: { channels: 3, labels: "hsv" },
      hwb: { channels: 3, labels: "hwb" },
      cmyk: { channels: 4, labels: "cmyk" },
      xyz: { channels: 3, labels: "xyz" },
      lab: { channels: 3, labels: "lab" },
      lch: { channels: 3, labels: "lch" },
      hex: { channels: 1, labels: ["hex"] },
      keyword: { channels: 1, labels: ["keyword"] },
      ansi16: { channels: 1, labels: ["ansi16"] },
      ansi256: { channels: 1, labels: ["ansi256"] },
      hcg: { channels: 3, labels: ["h", "c", "g"] },
      apple: { channels: 3, labels: ["r16", "g16", "b16"] },
      gray: { channels: 1, labels: ["gray"] }
    };
    module2.exports = convert2;
    for (const model of Object.keys(convert2)) {
      if (!("channels" in convert2[model])) {
        throw new Error("missing channels property: " + model);
      }
      if (!("labels" in convert2[model])) {
        throw new Error("missing channel labels property: " + model);
      }
      if (convert2[model].labels.length !== convert2[model].channels) {
        throw new Error("channel and label counts mismatch: " + model);
      }
      const { channels, labels } = convert2[model];
      delete convert2[model].channels;
      delete convert2[model].labels;
      Object.defineProperty(convert2[model], "channels", { value: channels });
      Object.defineProperty(convert2[model], "labels", { value: labels });
    }
    convert2.rgb.hsl = function(rgb) {
      const r3 = rgb[0] / 255;
      const g = rgb[1] / 255;
      const b = rgb[2] / 255;
      const min = Math.min(r3, g, b);
      const max = Math.max(r3, g, b);
      const delta = max - min;
      let h;
      let s2;
      if (max === min) {
        h = 0;
      } else if (r3 === max) {
        h = (g - b) / delta;
      } else if (g === max) {
        h = 2 + (b - r3) / delta;
      } else if (b === max) {
        h = 4 + (r3 - g) / delta;
      }
      h = Math.min(h * 60, 360);
      if (h < 0) {
        h += 360;
      }
      const l2 = (min + max) / 2;
      if (max === min) {
        s2 = 0;
      } else if (l2 <= 0.5) {
        s2 = delta / (max + min);
      } else {
        s2 = delta / (2 - max - min);
      }
      return [h, s2 * 100, l2 * 100];
    };
    convert2.rgb.hsv = function(rgb) {
      let rdif;
      let gdif;
      let bdif;
      let h;
      let s2;
      const r3 = rgb[0] / 255;
      const g = rgb[1] / 255;
      const b = rgb[2] / 255;
      const v = Math.max(r3, g, b);
      const diff4 = v - Math.min(r3, g, b);
      const diffc = /* @__PURE__ */ __name(function(c3) {
        return (v - c3) / 6 / diff4 + 1 / 2;
      }, "diffc");
      if (diff4 === 0) {
        h = 0;
        s2 = 0;
      } else {
        s2 = diff4 / v;
        rdif = diffc(r3);
        gdif = diffc(g);
        bdif = diffc(b);
        if (r3 === v) {
          h = bdif - gdif;
        } else if (g === v) {
          h = 1 / 3 + rdif - bdif;
        } else if (b === v) {
          h = 2 / 3 + gdif - rdif;
        }
        if (h < 0) {
          h += 1;
        } else if (h > 1) {
          h -= 1;
        }
      }
      return [
        h * 360,
        s2 * 100,
        v * 100
      ];
    };
    convert2.rgb.hwb = function(rgb) {
      const r3 = rgb[0];
      const g = rgb[1];
      let b = rgb[2];
      const h = convert2.rgb.hsl(rgb)[0];
      const w = 1 / 255 * Math.min(r3, Math.min(g, b));
      b = 1 - 1 / 255 * Math.max(r3, Math.max(g, b));
      return [h, w * 100, b * 100];
    };
    convert2.rgb.cmyk = function(rgb) {
      const r3 = rgb[0] / 255;
      const g = rgb[1] / 255;
      const b = rgb[2] / 255;
      const k = Math.min(1 - r3, 1 - g, 1 - b);
      const c3 = (1 - r3 - k) / (1 - k) || 0;
      const m = (1 - g - k) / (1 - k) || 0;
      const y = (1 - b - k) / (1 - k) || 0;
      return [c3 * 100, m * 100, y * 100, k * 100];
    };
    function comparativeDistance(x, y) {
      return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2;
    }
    __name(comparativeDistance, "comparativeDistance");
    convert2.rgb.keyword = function(rgb) {
      const reversed = reverseKeywords[rgb];
      if (reversed) {
        return reversed;
      }
      let currentClosestDistance = Infinity;
      let currentClosestKeyword;
      for (const keyword of Object.keys(cssKeywords)) {
        const value = cssKeywords[keyword];
        const distance = comparativeDistance(rgb, value);
        if (distance < currentClosestDistance) {
          currentClosestDistance = distance;
          currentClosestKeyword = keyword;
        }
      }
      return currentClosestKeyword;
    };
    convert2.keyword.rgb = function(keyword) {
      return cssKeywords[keyword];
    };
    convert2.rgb.xyz = function(rgb) {
      let r3 = rgb[0] / 255;
      let g = rgb[1] / 255;
      let b = rgb[2] / 255;
      r3 = r3 > 0.04045 ? ((r3 + 0.055) / 1.055) ** 2.4 : r3 / 12.92;
      g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92;
      b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92;
      const x = r3 * 0.4124 + g * 0.3576 + b * 0.1805;
      const y = r3 * 0.2126 + g * 0.7152 + b * 0.0722;
      const z = r3 * 0.0193 + g * 0.1192 + b * 0.9505;
      return [x * 100, y * 100, z * 100];
    };
    convert2.rgb.lab = function(rgb) {
      const xyz = convert2.rgb.xyz(rgb);
      let x = xyz[0];
      let y = xyz[1];
      let z = xyz[2];
      x /= 95.047;
      y /= 100;
      z /= 108.883;
      x = x > 8856e-6 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
      y = y > 8856e-6 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
      z = z > 8856e-6 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
      const l2 = 116 * y - 16;
      const a = 500 * (x - y);
      const b = 200 * (y - z);
      return [l2, a, b];
    };
    convert2.hsl.rgb = function(hsl) {
      const h = hsl[0] / 360;
      const s2 = hsl[1] / 100;
      const l2 = hsl[2] / 100;
      let t2;
      let t3;
      let val;
      if (s2 === 0) {
        val = l2 * 255;
        return [val, val, val];
      }
      if (l2 < 0.5) {
        t2 = l2 * (1 + s2);
      } else {
        t2 = l2 + s2 - l2 * s2;
      }
      const t1 = 2 * l2 - t2;
      const rgb = [0, 0, 0];
      for (let i = 0; i < 3; i++) {
        t3 = h + 1 / 3 * -(i - 1);
        if (t3 < 0) {
          t3++;
        }
        if (t3 > 1) {
          t3--;
        }
        if (6 * t3 < 1) {
          val = t1 + (t2 - t1) * 6 * t3;
        } else if (2 * t3 < 1) {
          val = t2;
        } else if (3 * t3 < 2) {
          val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
        } else {
          val = t1;
        }
        rgb[i] = val * 255;
      }
      return rgb;
    };
    convert2.hsl.hsv = function(hsl) {
      const h = hsl[0];
      let s2 = hsl[1] / 100;
      let l2 = hsl[2] / 100;
      let smin = s2;
      const lmin = Math.max(l2, 0.01);
      l2 *= 2;
      s2 *= l2 <= 1 ? l2 : 2 - l2;
      smin *= lmin <= 1 ? lmin : 2 - lmin;
      const v = (l2 + s2) / 2;
      const sv = l2 === 0 ? 2 * smin / (lmin + smin) : 2 * s2 / (l2 + s2);
      return [h, sv * 100, v * 100];
    };
    convert2.hsv.rgb = function(hsv) {
      const h = hsv[0] / 60;
      const s2 = hsv[1] / 100;
      let v = hsv[2] / 100;
      const hi = Math.floor(h) % 6;
      const f = h - Math.floor(h);
      const p = 255 * v * (1 - s2);
      const q = 255 * v * (1 - s2 * f);
      const t2 = 255 * v * (1 - s2 * (1 - f));
      v *= 255;
      switch (hi) {
        case 0:
          return [v, t2, p];
        case 1:
          return [q, v, p];
        case 2:
          return [p, v, t2];
        case 3:
          return [p, q, v];
        case 4:
          return [t2, p, v];
        case 5:
          return [v, p, q];
      }
    };
    convert2.hsv.hsl = function(hsv) {
      const h = hsv[0];
      const s2 = hsv[1] / 100;
      const v = hsv[2] / 100;
      const vmin = Math.max(v, 0.01);
      let sl;
      let l2;
      l2 = (2 - s2) * v;
      const lmin = (2 - s2) * vmin;
      sl = s2 * vmin;
      sl /= lmin <= 1 ? lmin : 2 - lmin;
      sl = sl || 0;
      l2 /= 2;
      return [h, sl * 100, l2 * 100];
    };
    convert2.hwb.rgb = function(hwb) {
      const h = hwb[0] / 360;
      let wh = hwb[1] / 100;
      let bl = hwb[2] / 100;
      const ratio = wh + bl;
      let f;
      if (ratio > 1) {
        wh /= ratio;
        bl /= ratio;
      }
      const i = Math.floor(6 * h);
      const v = 1 - bl;
      f = 6 * h - i;
      if ((i & 1) !== 0) {
        f = 1 - f;
      }
      const n2 = wh + f * (v - wh);
      let r3;
      let g;
      let b;
      switch (i) {
        default:
        case 6:
        case 0:
          r3 = v;
          g = n2;
          b = wh;
          break;
        case 1:
          r3 = n2;
          g = v;
          b = wh;
          break;
        case 2:
          r3 = wh;
          g = v;
          b = n2;
          break;
        case 3:
          r3 = wh;
          g = n2;
          b = v;
          break;
        case 4:
          r3 = n2;
          g = wh;
          b = v;
          break;
        case 5:
          r3 = v;
          g = wh;
          b = n2;
          break;
      }
      return [r3 * 255, g * 255, b * 255];
    };
    convert2.cmyk.rgb = function(cmyk) {
      const c3 = cmyk[0] / 100;
      const m = cmyk[1] / 100;
      const y = cmyk[2] / 100;
      const k = cmyk[3] / 100;
      const r3 = 1 - Math.min(1, c3 * (1 - k) + k);
      const g = 1 - Math.min(1, m * (1 - k) + k);
      const b = 1 - Math.min(1, y * (1 - k) + k);
      return [r3 * 255, g * 255, b * 255];
    };
    convert2.xyz.rgb = function(xyz) {
      const x = xyz[0] / 100;
      const y = xyz[1] / 100;
      const z = xyz[2] / 100;
      let r3;
      let g;
      let b;
      r3 = x * 3.2406 + y * -1.5372 + z * -0.4986;
      g = x * -0.9689 + y * 1.8758 + z * 0.0415;
      b = x * 0.0557 + y * -0.204 + z * 1.057;
      r3 = r3 > 31308e-7 ? 1.055 * r3 ** (1 / 2.4) - 0.055 : r3 * 12.92;
      g = g > 31308e-7 ? 1.055 * g ** (1 / 2.4) - 0.055 : g * 12.92;
      b = b > 31308e-7 ? 1.055 * b ** (1 / 2.4) - 0.055 : b * 12.92;
      r3 = Math.min(Math.max(0, r3), 1);
      g = Math.min(Math.max(0, g), 1);
      b = Math.min(Math.max(0, b), 1);
      return [r3 * 255, g * 255, b * 255];
    };
    convert2.xyz.lab = function(xyz) {
      let x = xyz[0];
      let y = xyz[1];
      let z = xyz[2];
      x /= 95.047;
      y /= 100;
      z /= 108.883;
      x = x > 8856e-6 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
      y = y > 8856e-6 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
      z = z > 8856e-6 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
      const l2 = 116 * y - 16;
      const a = 500 * (x - y);
      const b = 200 * (y - z);
      return [l2, a, b];
    };
    convert2.lab.xyz = function(lab) {
      const l2 = lab[0];
      const a = lab[1];
      const b = lab[2];
      let x;
      let y;
      let z;
      y = (l2 + 16) / 116;
      x = a / 500 + y;
      z = y - b / 200;
      const y2 = y ** 3;
      const x2 = x ** 3;
      const z2 = z ** 3;
      y = y2 > 8856e-6 ? y2 : (y - 16 / 116) / 7.787;
      x = x2 > 8856e-6 ? x2 : (x - 16 / 116) / 7.787;
      z = z2 > 8856e-6 ? z2 : (z - 16 / 116) / 7.787;
      x *= 95.047;
      y *= 100;
      z *= 108.883;
      return [x, y, z];
    };
    convert2.lab.lch = function(lab) {
      const l2 = lab[0];
      const a = lab[1];
      const b = lab[2];
      let h;
      const hr2 = Math.atan2(b, a);
      h = hr2 * 360 / 2 / Math.PI;
      if (h < 0) {
        h += 360;
      }
      const c3 = Math.sqrt(a * a + b * b);
      return [l2, c3, h];
    };
    convert2.lch.lab = function(lch) {
      const l2 = lch[0];
      const c3 = lch[1];
      const h = lch[2];
      const hr2 = h / 360 * 2 * Math.PI;
      const a = c3 * Math.cos(hr2);
      const b = c3 * Math.sin(hr2);
      return [l2, a, b];
    };
    convert2.rgb.ansi16 = function(args, saturation = null) {
      const [r3, g, b] = args;
      let value = saturation === null ? convert2.rgb.hsv(args)[2] : saturation;
      value = Math.round(value / 50);
      if (value === 0) {
        return 30;
      }
      let ansi2 = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r3 / 255));
      if (value === 2) {
        ansi2 += 60;
      }
      return ansi2;
    };
    convert2.hsv.ansi16 = function(args) {
      return convert2.rgb.ansi16(convert2.hsv.rgb(args), args[2]);
    };
    convert2.rgb.ansi256 = function(args) {
      const r3 = args[0];
      const g = args[1];
      const b = args[2];
      if (r3 === g && g === b) {
        if (r3 < 8) {
          return 16;
        }
        if (r3 > 248) {
          return 231;
        }
        return Math.round((r3 - 8) / 247 * 24) + 232;
      }
      const ansi2 = 16 + 36 * Math.round(r3 / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
      return ansi2;
    };
    convert2.ansi16.rgb = function(args) {
      let color = args % 10;
      if (color === 0 || color === 7) {
        if (args > 50) {
          color += 3.5;
        }
        color = color / 10.5 * 255;
        return [color, color, color];
      }
      const mult = (~~(args > 50) + 1) * 0.5;
      const r3 = (color & 1) * mult * 255;
      const g = (color >> 1 & 1) * mult * 255;
      const b = (color >> 2 & 1) * mult * 255;
      return [r3, g, b];
    };
    convert2.ansi256.rgb = function(args) {
      if (args >= 232) {
        const c3 = (args - 232) * 10 + 8;
        return [c3, c3, c3];
      }
      args -= 16;
      let rem;
      const r3 = Math.floor(args / 36) / 5 * 255;
      const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
      const b = rem % 6 / 5 * 255;
      return [r3, g, b];
    };
    convert2.rgb.hex = function(args) {
      const integer = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255);
      const string = integer.toString(16).toUpperCase();
      return "000000".substring(string.length) + string;
    };
    convert2.hex.rgb = function(args) {
      const match2 = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
      if (!match2) {
        return [0, 0, 0];
      }
      let colorString = match2[0];
      if (match2[0].length === 3) {
        colorString = colorString.split("").map((char) => {
          return char + char;
        }).join("");
      }
      const integer = parseInt(colorString, 16);
      const r3 = integer >> 16 & 255;
      const g = integer >> 8 & 255;
      const b = integer & 255;
      return [r3, g, b];
    };
    convert2.rgb.hcg = function(rgb) {
      const r3 = rgb[0] / 255;
      const g = rgb[1] / 255;
      const b = rgb[2] / 255;
      const max = Math.max(Math.max(r3, g), b);
      const min = Math.min(Math.min(r3, g), b);
      const chroma = max - min;
      let grayscale;
      let hue;
      if (chroma < 1) {
        grayscale = min / (1 - chroma);
      } else {
        grayscale = 0;
      }
      if (chroma <= 0) {
        hue = 0;
      } else if (max === r3) {
        hue = (g - b) / chroma % 6;
      } else if (max === g) {
        hue = 2 + (b - r3) / chroma;
      } else {
        hue = 4 + (r3 - g) / chroma;
      }
      hue /= 6;
      hue %= 1;
      return [hue * 360, chroma * 100, grayscale * 100];
    };
    convert2.hsl.hcg = function(hsl) {
      const s2 = hsl[1] / 100;
      const l2 = hsl[2] / 100;
      const c3 = l2 < 0.5 ? 2 * s2 * l2 : 2 * s2 * (1 - l2);
      let f = 0;
      if (c3 < 1) {
        f = (l2 - 0.5 * c3) / (1 - c3);
      }
      return [hsl[0], c3 * 100, f * 100];
    };
    convert2.hsv.hcg = function(hsv) {
      const s2 = hsv[1] / 100;
      const v = hsv[2] / 100;
      const c3 = s2 * v;
      let f = 0;
      if (c3 < 1) {
        f = (v - c3) / (1 - c3);
      }
      return [hsv[0], c3 * 100, f * 100];
    };
    convert2.hcg.rgb = function(hcg) {
      const h = hcg[0] / 360;
      const c3 = hcg[1] / 100;
      const g = hcg[2] / 100;
      if (c3 === 0) {
        return [g * 255, g * 255, g * 255];
      }
      const pure = [0, 0, 0];
      const hi = h % 1 * 6;
      const v = hi % 1;
      const w = 1 - v;
      let mg = 0;
      switch (Math.floor(hi)) {
        case 0:
          pure[0] = 1;
          pure[1] = v;
          pure[2] = 0;
          break;
        case 1:
          pure[0] = w;
          pure[1] = 1;
          pure[2] = 0;
          break;
        case 2:
          pure[0] = 0;
          pure[1] = 1;
          pure[2] = v;
          break;
        case 3:
          pure[0] = 0;
          pure[1] = w;
          pure[2] = 1;
          break;
        case 4:
          pure[0] = v;
          pure[1] = 0;
          pure[2] = 1;
          break;
        default:
          pure[0] = 1;
          pure[1] = 0;
          pure[2] = w;
      }
      mg = (1 - c3) * g;
      return [
        (c3 * pure[0] + mg) * 255,
        (c3 * pure[1] + mg) * 255,
        (c3 * pure[2] + mg) * 255
      ];
    };
    convert2.hcg.hsv = function(hcg) {
      const c3 = hcg[1] / 100;
      const g = hcg[2] / 100;
      const v = c3 + g * (1 - c3);
      let f = 0;
      if (v > 0) {
        f = c3 / v;
      }
      return [hcg[0], f * 100, v * 100];
    };
    convert2.hcg.hsl = function(hcg) {
      const c3 = hcg[1] / 100;
      const g = hcg[2] / 100;
      const l2 = g * (1 - c3) + 0.5 * c3;
      let s2 = 0;
      if (l2 > 0 && l2 < 0.5) {
        s2 = c3 / (2 * l2);
      } else if (l2 >= 0.5 && l2 < 1) {
        s2 = c3 / (2 * (1 - l2));
      }
      return [hcg[0], s2 * 100, l2 * 100];
    };
    convert2.hcg.hwb = function(hcg) {
      const c3 = hcg[1] / 100;
      const g = hcg[2] / 100;
      const v = c3 + g * (1 - c3);
      return [hcg[0], (v - c3) * 100, (1 - v) * 100];
    };
    convert2.hwb.hcg = function(hwb) {
      const w = hwb[1] / 100;
      const b = hwb[2] / 100;
      const v = 1 - b;
      const c3 = v - w;
      let g = 0;
      if (c3 < 1) {
        g = (v - c3) / (1 - c3);
      }
      return [hwb[0], c3 * 100, g * 100];
    };
    convert2.apple.rgb = function(apple) {
      return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
    };
    convert2.rgb.apple = function(rgb) {
      return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
    };
    convert2.gray.rgb = function(args) {
      return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
    };
    convert2.gray.hsl = function(args) {
      return [0, 0, args[0]];
    };
    convert2.gray.hsv = convert2.gray.hsl;
    convert2.gray.hwb = function(gray) {
      return [0, 100, gray[0]];
    };
    convert2.gray.cmyk = function(gray) {
      return [0, 0, 0, gray[0]];
    };
    convert2.gray.lab = function(gray) {
      return [gray[0], 0, 0];
    };
    convert2.gray.hex = function(gray) {
      const val = Math.round(gray[0] / 100 * 255) & 255;
      const integer = (val << 16) + (val << 8) + val;
      const string = integer.toString(16).toUpperCase();
      return "000000".substring(string.length) + string;
    };
    convert2.rgb.gray = function(rgb) {
      const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
      return [val / 255 * 100];
    };
  }
});

// node_modules/color-convert/route.js
var require_route = __commonJS({
  "node_modules/color-convert/route.js"(exports2, module2) {
    init_esbuild_shims();
    var conversions = require_conversions();
    function buildGraph() {
      const graph = {};
      const models = Object.keys(conversions);
      for (let len = models.length, i = 0; i < len; i++) {
        graph[models[i]] = {
          // http://jsperf.com/1-vs-infinity
          // micro-opt, but this is simple.
          distance: -1,
          parent: null
        };
      }
      return graph;
    }
    __name(buildGraph, "buildGraph");
    function deriveBFS(fromModel) {
      const graph = buildGraph();
      const queue = [fromModel];
      graph[fromModel].distance = 0;
      while (queue.length) {
        const current = queue.pop();
        const adjacents = Object.keys(conversions[current]);
        for (let len = adjacents.length, i = 0; i < len; i++) {
          const adjacent = adjacents[i];
          const node = graph[adjacent];
          if (node.distance === -1) {
            node.distance = graph[current].distance + 1;
            node.parent = current;
            queue.unshift(adjacent);
          }
        }
      }
      return graph;
    }
    __name(deriveBFS, "deriveBFS");
    function link3(from, to) {
      return function(args) {
        return to(from(args));
      };
    }
    __name(link3, "link");
    function wrapConversion(toModel, graph) {
      const path108 = [graph[toModel].parent, toModel];
      let fn = conversions[graph[toModel].parent][toModel];
      let cur = graph[toModel].parent;
      while (graph[cur].parent) {
        path108.unshift(graph[cur].parent);
        fn = link3(conversions[graph[cur].parent][cur], fn);
        cur = graph[cur].parent;
      }
      fn.conversion = path108;
      return fn;
    }
    __name(wrapConversion, "wrapConversion");
    module2.exports = function(fromModel) {
      const graph = deriveBFS(fromModel);
      const conversion = {};
      const models = Object.keys(graph);
      for (let len = models.length, i = 0; i < len; i++) {
        const toModel = models[i];
        const node = graph[toModel];
        if (node.parent === null) {
          continue;
        }
        conversion[toModel] = wrapConversion(toModel, graph);
      }
      return conversion;
    };
  }
});

// node_modules/color-convert/index.js
var require_color_convert = __commonJS({
  "node_modules/color-convert/index.js"(exports2, module2) {
    init_esbuild_shims();
    var conversions = require_conversions();
    var route = require_route();
    var convert2 = {};
    var models = Object.keys(conversions);
    function wrapRaw(fn) {
      const wrappedFn = /* @__PURE__ */ __name(function(...args) {
        const arg0 = args[0];
        if (arg0 === void 0 || arg0 === null) {
          return arg0;
        }
        if (arg0.length > 1) {
          args = arg0;
        }
        return fn(args);
      }, "wrappedFn");
      if ("conversion" in fn) {
        wrappedFn.conversion = fn.conversion;
      }
      return wrappedFn;
    }
    __name(wrapRaw, "wrapRaw");
    function wrapRounded(fn) {
      const wrappedFn = /* @__PURE__ */ __name(function(...args) {
        const arg0 = args[0];
        if (arg0 === void 0 || arg0 === null) {
          return arg0;
        }
        if (arg0.length > 1) {
          args = arg0;
        }
        const result = fn(args);
        if (typeof result === "object") {
          for (let len = result.length, i = 0; i < len; i++) {
            result[i] = Math.round(result[i]);
          }
        }
        return result;
      }, "wrappedFn");
      if ("conversion" in fn) {
        wrappedFn.conversion = fn.conversion;
      }
      return wrappedFn;
    }
    __name(wrapRounded, "wrapRounded");
    models.forEach((fromModel) => {
      convert2[fromModel] = {};
      Object.defineProperty(convert2[fromModel], "channels", { value: conversions[fromModel].channels });
      Object.defineProperty(convert2[fromModel], "labels", { value: conversions[fromModel].labels });
      const routes = route(fromModel);
      const routeModels = Object.keys(routes);
      routeModels.forEach((toModel) => {
        const fn = routes[toModel];
        convert2[fromModel][toModel] = wrapRounded(fn);
        convert2[fromModel][toModel].raw = wrapRaw(fn);
      });
    });
    module2.exports = convert2;
  }
});

// node_modules/ansi-styles/index.js
var require_ansi_styles = __commonJS({
  "node_modules/ansi-styles/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var wrapAnsi167 = /* @__PURE__ */ __name((fn, offset) => (...args) => {
      const code2 = fn(...args);
      return `\x1B[${code2 + offset}m`;
    }, "wrapAnsi16");
    var wrapAnsi2567 = /* @__PURE__ */ __name((fn, offset) => (...args) => {
      const code2 = fn(...args);
      return `\x1B[${38 + offset};5;${code2}m`;
    }, "wrapAnsi256");
    var wrapAnsi16m7 = /* @__PURE__ */ __name((fn, offset) => (...args) => {
      const rgb = fn(...args);
      return `\x1B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
    }, "wrapAnsi16m");
    var ansi2ansi = /* @__PURE__ */ __name((n2) => n2, "ansi2ansi");
    var rgb2rgb = /* @__PURE__ */ __name((r3, g, b) => [r3, g, b], "rgb2rgb");
    var setLazyProperty = /* @__PURE__ */ __name((object, property, get3) => {
      Object.defineProperty(object, property, {
        get: /* @__PURE__ */ __name(() => {
          const value = get3();
          Object.defineProperty(object, property, {
            value,
            enumerable: true,
            configurable: true
          });
          return value;
        }, "get"),
        enumerable: true,
        configurable: true
      });
    }, "setLazyProperty");
    var colorConvert;
    var makeDynamicStyles = /* @__PURE__ */ __name((wrap2, targetSpace, identity, isBackground) => {
      if (colorConvert === void 0) {
        colorConvert = require_color_convert();
      }
      const offset = isBackground ? 10 : 0;
      const styles10 = {};
      for (const [sourceSpace, suite] of Object.entries(colorConvert)) {
        const name3 = sourceSpace === "ansi16" ? "ansi" : sourceSpace;
        if (sourceSpace === targetSpace) {
          styles10[name3] = wrap2(identity, offset);
        } else if (typeof suite === "object") {
          styles10[name3] = wrap2(suite[targetSpace], offset);
        }
      }
      return styles10;
    }, "makeDynamicStyles");
    function assembleStyles7() {
      const codes = /* @__PURE__ */ new Map();
      const styles10 = {
        modifier: {
          reset: [0, 0],
          // 21 isn't widely supported and 22 does the same thing
          bold: [1, 22],
          dim: [2, 22],
          italic: [3, 23],
          underline: [4, 24],
          inverse: [7, 27],
          hidden: [8, 28],
          strikethrough: [9, 29]
        },
        color: {
          black: [30, 39],
          red: [31, 39],
          green: [32, 39],
          yellow: [33, 39],
          blue: [34, 39],
          magenta: [35, 39],
          cyan: [36, 39],
          white: [37, 39],
          // Bright color
          blackBright: [90, 39],
          redBright: [91, 39],
          greenBright: [92, 39],
          yellowBright: [93, 39],
          blueBright: [94, 39],
          magentaBright: [95, 39],
          cyanBright: [96, 39],
          whiteBright: [97, 39]
        },
        bgColor: {
          bgBlack: [40, 49],
          bgRed: [41, 49],
          bgGreen: [42, 49],
          bgYellow: [43, 49],
          bgBlue: [44, 49],
          bgMagenta: [45, 49],
          bgCyan: [46, 49],
          bgWhite: [47, 49],
          // Bright color
          bgBlackBright: [100, 49],
          bgRedBright: [101, 49],
          bgGreenBright: [102, 49],
          bgYellowBright: [103, 49],
          bgBlueBright: [104, 49],
          bgMagentaBright: [105, 49],
          bgCyanBright: [106, 49],
          bgWhiteBright: [107, 49]
        }
      };
      styles10.color.gray = styles10.color.blackBright;
      styles10.bgColor.bgGray = styles10.bgColor.bgBlackBright;
      styles10.color.grey = styles10.color.blackBright;
      styles10.bgColor.bgGrey = styles10.bgColor.bgBlackBright;
      for (const [groupName, group] of Object.entries(styles10)) {
        for (const [styleName, style] of Object.entries(group)) {
          styles10[styleName] = {
            open: `\x1B[${style[0]}m`,
            close: `\x1B[${style[1]}m`
          };
          group[styleName] = styles10[styleName];
          codes.set(style[0], style[1]);
        }
        Object.defineProperty(styles10, groupName, {
          value: group,
          enumerable: false
        });
      }
      Object.defineProperty(styles10, "codes", {
        value: codes,
        enumerable: false
      });
      styles10.color.close = "\x1B[39m";
      styles10.bgColor.close = "\x1B[49m";
      setLazyProperty(styles10.color, "ansi", () => makeDynamicStyles(wrapAnsi167, "ansi16", ansi2ansi, false));
      setLazyProperty(styles10.color, "ansi256", () => makeDynamicStyles(wrapAnsi2567, "ansi256", ansi2ansi, false));
      setLazyProperty(styles10.color, "ansi16m", () => makeDynamicStyles(wrapAnsi16m7, "rgb", rgb2rgb, false));
      setLazyProperty(styles10.bgColor, "ansi", () => makeDynamicStyles(wrapAnsi167, "ansi16", ansi2ansi, true));
      setLazyProperty(styles10.bgColor, "ansi256", () => makeDynamicStyles(wrapAnsi2567, "ansi256", ansi2ansi, true));
      setLazyProperty(styles10.bgColor, "ansi16m", () => makeDynamicStyles(wrapAnsi16m7, "rgb", rgb2rgb, true));
      return styles10;
    }
    __name(assembleStyles7, "assembleStyles");
    Object.defineProperty(module2, "exports", {
      enumerable: true,
      get: assembleStyles7
    });
  }
});

// node_modules/has-flag/index.js
var require_has_flag2 = __commonJS({
  "node_modules/has-flag/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = (flag, argv = process.argv) => {
      const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
      const position = argv.indexOf(prefix + flag);
      const terminatorPosition = argv.indexOf("--");
      return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
    };
  }
});

// node_modules/chalk/node_modules/supports-color/index.js
var require_supports_color2 = __commonJS({
  "node_modules/chalk/node_modules/supports-color/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var os43 = __require("os");
    var tty3 = __require("tty");
    var hasFlag3 = require_has_flag2();
    var { env: env7 } = process;
    var forceColor;
    if (hasFlag3("no-color") || hasFlag3("no-colors") || hasFlag3("color=false") || hasFlag3("color=never")) {
      forceColor = 0;
    } else if (hasFlag3("color") || hasFlag3("colors") || hasFlag3("color=true") || hasFlag3("color=always")) {
      forceColor = 1;
    }
    if ("FORCE_COLOR" in env7) {
      if (env7.FORCE_COLOR === "true") {
        forceColor = 1;
      } else if (env7.FORCE_COLOR === "false") {
        forceColor = 0;
      } else {
        forceColor = env7.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env7.FORCE_COLOR, 10), 3);
      }
    }
    function translateLevel3(level) {
      if (level === 0) {
        return false;
      }
      return {
        level,
        hasBasic: true,
        has256: level >= 2,
        has16m: level >= 3
      };
    }
    __name(translateLevel3, "translateLevel");
    function supportsColor3(haveStream, streamIsTTY) {
      if (forceColor === 0) {
        return 0;
      }
      if (hasFlag3("color=16m") || hasFlag3("color=full") || hasFlag3("color=truecolor")) {
        return 3;
      }
      if (hasFlag3("color=256")) {
        return 2;
      }
      if (haveStream && !streamIsTTY && forceColor === void 0) {
        return 0;
      }
      const min = forceColor || 0;
      if (env7.TERM === "dumb") {
        return min;
      }
      if (process.platform === "win32") {
        const osRelease = os43.release().split(".");
        if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
          return Number(osRelease[2]) >= 14931 ? 3 : 2;
        }
        return 1;
      }
      if ("CI" in env7) {
        if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env7) || env7.CI_NAME === "codeship") {
          return 1;
        }
        return min;
      }
      if ("TEAMCITY_VERSION" in env7) {
        return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env7.TEAMCITY_VERSION) ? 1 : 0;
      }
      if (env7.COLORTERM === "truecolor") {
        return 3;
      }
      if ("TERM_PROGRAM" in env7) {
        const version2 = parseInt((env7.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
        switch (env7.TERM_PROGRAM) {
          case "iTerm.app":
            return version2 >= 3 ? 3 : 2;
          case "Apple_Terminal":
            return 2;
        }
      }
      if (/-256(color)?$/i.test(env7.TERM)) {
        return 2;
      }
      if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env7.TERM)) {
        return 1;
      }
      if ("COLORTERM" in env7) {
        return 1;
      }
      return min;
    }
    __name(supportsColor3, "supportsColor");
    function getSupportLevel(stream2) {
      const level = supportsColor3(stream2, stream2 && stream2.isTTY);
      return translateLevel3(level);
    }
    __name(getSupportLevel, "getSupportLevel");
    module2.exports = {
      supportsColor: getSupportLevel,
      stdout: translateLevel3(supportsColor3(true, tty3.isatty(1))),
      stderr: translateLevel3(supportsColor3(true, tty3.isatty(2)))
    };
  }
});

// node_modules/chalk/source/util.js
var require_util16 = __commonJS({
  "node_modules/chalk/source/util.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var stringReplaceAll3 = /* @__PURE__ */ __name((string, substring, replacer) => {
      let index = string.indexOf(substring);
      if (index === -1) {
        return string;
      }
      const substringLength = substring.length;
      let endIndex = 0;
      let returnValue = "";
      do {
        returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
        endIndex = index + substringLength;
        index = string.indexOf(substring, endIndex);
      } while (index !== -1);
      returnValue += string.substr(endIndex);
      return returnValue;
    }, "stringReplaceAll");
    var stringEncaseCRLFWithFirstIndex3 = /* @__PURE__ */ __name((string, prefix, postfix, index) => {
      let endIndex = 0;
      let returnValue = "";
      do {
        const gotCR = string[index - 1] === "\r";
        returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
        endIndex = index + 1;
        index = string.indexOf("\n", endIndex);
      } while (index !== -1);
      returnValue += string.substr(endIndex);
      return returnValue;
    }, "stringEncaseCRLFWithFirstIndex");
    module2.exports = {
      stringReplaceAll: stringReplaceAll3,
      stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex3
    };
  }
});

// node_modules/chalk/source/templates.js
var require_templates = __commonJS({
  "node_modules/chalk/source/templates.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
    var STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
    var STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
    var ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
    var ESCAPES5 = /* @__PURE__ */ new Map([
      ["n", "\n"],
      ["r", "\r"],
      ["t", "	"],
      ["b", "\b"],
      ["f", "\f"],
      ["v", "\v"],
      ["0", "\0"],
      ["\\", "\\"],
      ["e", "\x1B"],
      ["a", "\x07"]
    ]);
    function unescape4(c3) {
      const u = c3[0] === "u";
      const bracket = c3[1] === "{";
      if (u && !bracket && c3.length === 5 || c3[0] === "x" && c3.length === 3) {
        return String.fromCharCode(parseInt(c3.slice(1), 16));
      }
      if (u && bracket) {
        return String.fromCodePoint(parseInt(c3.slice(2, -1), 16));
      }
      return ESCAPES5.get(c3) || c3;
    }
    __name(unescape4, "unescape");
    function parseArguments2(name3, arguments_) {
      const results = [];
      const chunks = arguments_.trim().split(/\s*,\s*/g);
      let matches;
      for (const chunk of chunks) {
        const number = Number(chunk);
        if (!Number.isNaN(number)) {
          results.push(number);
        } else if (matches = chunk.match(STRING_REGEX)) {
          results.push(matches[2].replace(ESCAPE_REGEX, (m, escape7, character) => escape7 ? unescape4(escape7) : character));
        } else {
          throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name3}')`);
        }
      }
      return results;
    }
    __name(parseArguments2, "parseArguments");
    function parseStyle(style) {
      STYLE_REGEX.lastIndex = 0;
      const results = [];
      let matches;
      while ((matches = STYLE_REGEX.exec(style)) !== null) {
        const name3 = matches[1];
        if (matches[2]) {
          const args = parseArguments2(name3, matches[2]);
          results.push([name3].concat(args));
        } else {
          results.push([name3]);
        }
      }
      return results;
    }
    __name(parseStyle, "parseStyle");
    function buildStyle(chalk7, styles10) {
      const enabled = {};
      for (const layer of styles10) {
        for (const style of layer.styles) {
          enabled[style[0]] = layer.inverse ? null : style.slice(1);
        }
      }
      let current = chalk7;
      for (const [styleName, styles11] of Object.entries(enabled)) {
        if (!Array.isArray(styles11)) {
          continue;
        }
        if (!(styleName in current)) {
          throw new Error(`Unknown Chalk style: ${styleName}`);
        }
        current = styles11.length > 0 ? current[styleName](...styles11) : current[styleName];
      }
      return current;
    }
    __name(buildStyle, "buildStyle");
    module2.exports = (chalk7, temporary) => {
      const styles10 = [];
      const chunks = [];
      let chunk = [];
      temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
        if (escapeCharacter) {
          chunk.push(unescape4(escapeCharacter));
        } else if (style) {
          const string = chunk.join("");
          chunk = [];
          chunks.push(styles10.length === 0 ? string : buildStyle(chalk7, styles10)(string));
          styles10.push({ inverse, styles: parseStyle(style) });
        } else if (close) {
          if (styles10.length === 0) {
            throw new Error("Found extraneous } in Chalk template literal");
          }
          chunks.push(buildStyle(chalk7, styles10)(chunk.join("")));
          chunk = [];
          styles10.pop();
        } else {
          chunk.push(character);
        }
      });
      chunks.push(chunk.join(""));
      if (styles10.length > 0) {
        const errMessage = `Chalk template literal is missing ${styles10.length} closing bracket${styles10.length === 1 ? "" : "s"} (\`}\`)`;
        throw new Error(errMessage);
      }
      return chunks.join("");
    };
  }
});

// node_modules/chalk/source/index.js
var require_source = __commonJS({
  "node_modules/chalk/source/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var ansiStyles7 = require_ansi_styles();
    var { stdout: stdoutColor3, stderr: stderrColor3 } = require_supports_color2();
    var {
      stringReplaceAll: stringReplaceAll3,
      stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex3
    } = require_util16();
    var { isArray: isArray2 } = Array;
    var levelMapping3 = [
      "ansi",
      "ansi",
      "ansi256",
      "ansi16m"
    ];
    var styles10 = /* @__PURE__ */ Object.create(null);
    var applyOptions3 = /* @__PURE__ */ __name((object, options2 = {}) => {
      if (options2.level && !(Number.isInteger(options2.level) && options2.level >= 0 && options2.level <= 3)) {
        throw new Error("The `level` option should be an integer from 0 to 3");
      }
      const colorLevel = stdoutColor3 ? stdoutColor3.level : 0;
      object.level = options2.level === void 0 ? colorLevel : options2.level;
    }, "applyOptions");
    var ChalkClass = class {
      static {
        __name(this, "ChalkClass");
      }
      constructor(options2) {
        return chalkFactory3(options2);
      }
    };
    var chalkFactory3 = /* @__PURE__ */ __name((options2) => {
      const chalk8 = {};
      applyOptions3(chalk8, options2);
      chalk8.template = (...arguments_) => chalkTag(chalk8.template, ...arguments_);
      Object.setPrototypeOf(chalk8, Chalk.prototype);
      Object.setPrototypeOf(chalk8.template, chalk8);
      chalk8.template.constructor = () => {
        throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.");
      };
      chalk8.template.Instance = ChalkClass;
      return chalk8.template;
    }, "chalkFactory");
    function Chalk(options2) {
      return chalkFactory3(options2);
    }
    __name(Chalk, "Chalk");
    for (const [styleName, style] of Object.entries(ansiStyles7)) {
      styles10[styleName] = {
        get() {
          const builder = createBuilder3(this, createStyler3(style.open, style.close, this._styler), this._isEmpty);
          Object.defineProperty(this, styleName, { value: builder });
          return builder;
        }
      };
    }
    styles10.visible = {
      get() {
        const builder = createBuilder3(this, this._styler, true);
        Object.defineProperty(this, "visible", { value: builder });
        return builder;
      }
    };
    var usedModels3 = ["rgb", "hex", "keyword", "hsl", "hsv", "hwb", "ansi", "ansi256"];
    for (const model of usedModels3) {
      styles10[model] = {
        get() {
          const { level } = this;
          return function(...arguments_) {
            const styler = createStyler3(ansiStyles7.color[levelMapping3[level]][model](...arguments_), ansiStyles7.color.close, this._styler);
            return createBuilder3(this, styler, this._isEmpty);
          };
        }
      };
    }
    for (const model of usedModels3) {
      const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
      styles10[bgModel] = {
        get() {
          const { level } = this;
          return function(...arguments_) {
            const styler = createStyler3(ansiStyles7.bgColor[levelMapping3[level]][model](...arguments_), ansiStyles7.bgColor.close, this._styler);
            return createBuilder3(this, styler, this._isEmpty);
          };
        }
      };
    }
    var proto3 = Object.defineProperties(() => {
    }, {
      ...styles10,
      level: {
        enumerable: true,
        get() {
          return this._generator.level;
        },
        set(level) {
          this._generator.level = level;
        }
      }
    });
    var createStyler3 = /* @__PURE__ */ __name((open3, close, parent) => {
      let openAll;
      let closeAll;
      if (parent === void 0) {
        openAll = open3;
        closeAll = close;
      } else {
        openAll = parent.openAll + open3;
        closeAll = close + parent.closeAll;
      }
      return {
        open: open3,
        close,
        openAll,
        closeAll,
        parent
      };
    }, "createStyler");
    var createBuilder3 = /* @__PURE__ */ __name((self2, _styler, _isEmpty) => {
      const builder = /* @__PURE__ */ __name((...arguments_) => {
        if (isArray2(arguments_[0]) && isArray2(arguments_[0].raw)) {
          return applyStyle3(builder, chalkTag(builder, ...arguments_));
        }
        return applyStyle3(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
      }, "builder");
      Object.setPrototypeOf(builder, proto3);
      builder._generator = self2;
      builder._styler = _styler;
      builder._isEmpty = _isEmpty;
      return builder;
    }, "createBuilder");
    var applyStyle3 = /* @__PURE__ */ __name((self2, string) => {
      if (self2.level <= 0 || !string) {
        return self2._isEmpty ? "" : string;
      }
      let styler = self2._styler;
      if (styler === void 0) {
        return string;
      }
      const { openAll, closeAll } = styler;
      if (string.indexOf("\x1B") !== -1) {
        while (styler !== void 0) {
          string = stringReplaceAll3(string, styler.close, styler.open);
          styler = styler.parent;
        }
      }
      const lfIndex = string.indexOf("\n");
      if (lfIndex !== -1) {
        string = stringEncaseCRLFWithFirstIndex3(string, closeAll, openAll, lfIndex);
      }
      return openAll + string + closeAll;
    }, "applyStyle");
    var template;
    var chalkTag = /* @__PURE__ */ __name((chalk8, ...strings) => {
      const [firstString] = strings;
      if (!isArray2(firstString) || !isArray2(firstString.raw)) {
        return strings.join(" ");
      }
      const arguments_ = strings.slice(1);
      const parts = [firstString.raw[0]];
      for (let i = 1; i < firstString.length; i++) {
        parts.push(
          String(arguments_[i - 1]).replace(/[{}\\]/g, "\\$&"),
          String(firstString.raw[i])
        );
      }
      if (template === void 0) {
        template = require_templates();
      }
      return template(chalk8, parts.join(""));
    }, "chalkTag");
    Object.defineProperties(Chalk.prototype, styles10);
    var chalk7 = Chalk();
    chalk7.supportsColor = stdoutColor3;
    chalk7.stderr = Chalk({ level: stderrColor3 ? stderrColor3.level : 0 });
    chalk7.stderr.supportsColor = stderrColor3;
    module2.exports = chalk7;
  }
});

// node_modules/react-is/cjs/react-is.production.min.js
var require_react_is_production_min = __commonJS({
  "node_modules/react-is/cjs/react-is.production.min.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var b = "function" === typeof Symbol && Symbol.for;
    var c3 = b ? Symbol.for("react.element") : 60103;
    var d = b ? Symbol.for("react.portal") : 60106;
    var e2 = b ? Symbol.for("react.fragment") : 60107;
    var f = b ? Symbol.for("react.strict_mode") : 60108;
    var g = b ? Symbol.for("react.profiler") : 60114;
    var h = b ? Symbol.for("react.provider") : 60109;
    var k = b ? Symbol.for("react.context") : 60110;
    var l2 = b ? Symbol.for("react.async_mode") : 60111;
    var m = b ? Symbol.for("react.concurrent_mode") : 60111;
    var n2 = b ? Symbol.for("react.forward_ref") : 60112;
    var p = b ? Symbol.for("react.suspense") : 60113;
    var q = b ? Symbol.for("react.suspense_list") : 60120;
    var r3 = b ? Symbol.for("react.memo") : 60115;
    var t2 = b ? Symbol.for("react.lazy") : 60116;
    var v = b ? Symbol.for("react.block") : 60121;
    var w = b ? Symbol.for("react.fundamental") : 60117;
    var x = b ? Symbol.for("react.responder") : 60118;
    var y = b ? Symbol.for("react.scope") : 60119;
    function z(a) {
      if ("object" === typeof a && null !== a) {
        var u = a.$$typeof;
        switch (u) {
          case c3:
            switch (a = a.type, a) {
              case l2:
              case m:
              case e2:
              case g:
              case f:
              case p:
                return a;
              default:
                switch (a = a && a.$$typeof, a) {
                  case k:
                  case n2:
                  case t2:
                  case r3:
                  case h:
                    return a;
                  default:
                    return u;
                }
            }
          case d:
            return u;
        }
      }
    }
    __name(z, "z");
    function A(a) {
      return z(a) === m;
    }
    __name(A, "A");
    exports2.AsyncMode = l2;
    exports2.ConcurrentMode = m;
    exports2.ContextConsumer = k;
    exports2.ContextProvider = h;
    exports2.Element = c3;
    exports2.ForwardRef = n2;
    exports2.Fragment = e2;
    exports2.Lazy = t2;
    exports2.Memo = r3;
    exports2.Portal = d;
    exports2.Profiler = g;
    exports2.StrictMode = f;
    exports2.Suspense = p;
    exports2.isAsyncMode = function(a) {
      return A(a) || z(a) === l2;
    };
    exports2.isConcurrentMode = A;
    exports2.isContextConsumer = function(a) {
      return z(a) === k;
    };
    exports2.isContextProvider = function(a) {
      return z(a) === h;
    };
    exports2.isElement = function(a) {
      return "object" === typeof a && null !== a && a.$$typeof === c3;
    };
    exports2.isForwardRef = function(a) {
      return z(a) === n2;
    };
    exports2.isFragment = function(a) {
      return z(a) === e2;
    };
    exports2.isLazy = function(a) {
      return z(a) === t2;
    };
    exports2.isMemo = function(a) {
      return z(a) === r3;
    };
    exports2.isPortal = function(a) {
      return z(a) === d;
    };
    exports2.isProfiler = function(a) {
      return z(a) === g;
    };
    exports2.isStrictMode = function(a) {
      return z(a) === f;
    };
    exports2.isSuspense = function(a) {
      return z(a) === p;
    };
    exports2.isValidElementType = function(a) {
      return "string" === typeof a || "function" === typeof a || a === e2 || a === m || a === g || a === f || a === p || a === q || "object" === typeof a && null !== a && (a.$$typeof === t2 || a.$$typeof === r3 || a.$$typeof === h || a.$$typeof === k || a.$$typeof === n2 || a.$$typeof === w || a.$$typeof === x || a.$$typeof === y || a.$$typeof === v);
    };
    exports2.typeOf = z;
  }
});

// node_modules/react-is/cjs/react-is.development.js
var require_react_is_development = __commonJS({
  "node_modules/react-is/cjs/react-is.development.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    if (process.env.NODE_ENV !== "production") {
      (function() {
        "use strict";
        var hasSymbol = typeof Symbol === "function" && Symbol.for;
        var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for("react.element") : 60103;
        var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for("react.portal") : 60106;
        var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for("react.fragment") : 60107;
        var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for("react.strict_mode") : 60108;
        var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for("react.profiler") : 60114;
        var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for("react.provider") : 60109;
        var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for("react.context") : 60110;
        var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for("react.async_mode") : 60111;
        var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for("react.concurrent_mode") : 60111;
        var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for("react.forward_ref") : 60112;
        var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for("react.suspense") : 60113;
        var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for("react.suspense_list") : 60120;
        var REACT_MEMO_TYPE = hasSymbol ? Symbol.for("react.memo") : 60115;
        var REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116;
        var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for("react.block") : 60121;
        var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for("react.fundamental") : 60117;
        var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for("react.responder") : 60118;
        var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for("react.scope") : 60119;
        function isValidElementType(type) {
          return typeof type === "string" || typeof type === "function" || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
          type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === "object" && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);
        }
        __name(isValidElementType, "isValidElementType");
        function typeOf(object) {
          if (typeof object === "object" && object !== null) {
            var $$typeof = object.$$typeof;
            switch ($$typeof) {
              case REACT_ELEMENT_TYPE:
                var type = object.type;
                switch (type) {
                  case REACT_ASYNC_MODE_TYPE:
                  case REACT_CONCURRENT_MODE_TYPE:
                  case REACT_FRAGMENT_TYPE:
                  case REACT_PROFILER_TYPE:
                  case REACT_STRICT_MODE_TYPE:
                  case REACT_SUSPENSE_TYPE:
                    return type;
                  default:
                    var $$typeofType = type && type.$$typeof;
                    switch ($$typeofType) {
                      case REACT_CONTEXT_TYPE:
                      case REACT_FORWARD_REF_TYPE:
                      case REACT_LAZY_TYPE:
                      case REACT_MEMO_TYPE:
                      case REACT_PROVIDER_TYPE:
                        return $$typeofType;
                      default:
                        return $$typeof;
                    }
                }
              case REACT_PORTAL_TYPE:
                return $$typeof;
            }
          }
          return void 0;
        }
        __name(typeOf, "typeOf");
        var AsyncMode = REACT_ASYNC_MODE_TYPE;
        var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
        var ContextConsumer = REACT_CONTEXT_TYPE;
        var ContextProvider = REACT_PROVIDER_TYPE;
        var Element2 = REACT_ELEMENT_TYPE;
        var ForwardRef = REACT_FORWARD_REF_TYPE;
        var Fragment14 = REACT_FRAGMENT_TYPE;
        var Lazy = REACT_LAZY_TYPE;
        var Memo = REACT_MEMO_TYPE;
        var Portal = REACT_PORTAL_TYPE;
        var Profiler = REACT_PROFILER_TYPE;
        var StrictMode = REACT_STRICT_MODE_TYPE;
        var Suspense = REACT_SUSPENSE_TYPE;
        var hasWarnedAboutDeprecatedIsAsyncMode = false;
        function isAsyncMode(object) {
          {
            if (!hasWarnedAboutDeprecatedIsAsyncMode) {
              hasWarnedAboutDeprecatedIsAsyncMode = true;
              console["warn"]("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API.");
            }
          }
          return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
        }
        __name(isAsyncMode, "isAsyncMode");
        function isConcurrentMode(object) {
          return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
        }
        __name(isConcurrentMode, "isConcurrentMode");
        function isContextConsumer(object) {
          return typeOf(object) === REACT_CONTEXT_TYPE;
        }
        __name(isContextConsumer, "isContextConsumer");
        function isContextProvider(object) {
          return typeOf(object) === REACT_PROVIDER_TYPE;
        }
        __name(isContextProvider, "isContextProvider");
        function isElement(object) {
          return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
        }
        __name(isElement, "isElement");
        function isForwardRef(object) {
          return typeOf(object) === REACT_FORWARD_REF_TYPE;
        }
        __name(isForwardRef, "isForwardRef");
        function isFragment(object) {
          return typeOf(object) === REACT_FRAGMENT_TYPE;
        }
        __name(isFragment, "isFragment");
        function isLazy(object) {
          return typeOf(object) === REACT_LAZY_TYPE;
        }
        __name(isLazy, "isLazy");
        function isMemo(object) {
          return typeOf(object) === REACT_MEMO_TYPE;
        }
        __name(isMemo, "isMemo");
        function isPortal(object) {
          return typeOf(object) === REACT_PORTAL_TYPE;
        }
        __name(isPortal, "isPortal");
        function isProfiler(object) {
          return typeOf(object) === REACT_PROFILER_TYPE;
        }
        __name(isProfiler, "isProfiler");
        function isStrictMode(object) {
          return typeOf(object) === REACT_STRICT_MODE_TYPE;
        }
        __name(isStrictMode, "isStrictMode");
        function isSuspense(object) {
          return typeOf(object) === REACT_SUSPENSE_TYPE;
        }
        __name(isSuspense, "isSuspense");
        exports2.AsyncMode = AsyncMode;
        exports2.ConcurrentMode = ConcurrentMode;
        exports2.ContextConsumer = ContextConsumer;
        exports2.ContextProvider = ContextProvider;
        exports2.Element = Element2;
        exports2.ForwardRef = ForwardRef;
        exports2.Fragment = Fragment14;
        exports2.Lazy = Lazy;
        exports2.Memo = Memo;
        exports2.Portal = Portal;
        exports2.Profiler = Profiler;
        exports2.StrictMode = StrictMode;
        exports2.Suspense = Suspense;
        exports2.isAsyncMode = isAsyncMode;
        exports2.isConcurrentMode = isConcurrentMode;
        exports2.isContextConsumer = isContextConsumer;
        exports2.isContextProvider = isContextProvider;
        exports2.isElement = isElement;
        exports2.isForwardRef = isForwardRef;
        exports2.isFragment = isFragment;
        exports2.isLazy = isLazy;
        exports2.isMemo = isMemo;
        exports2.isPortal = isPortal;
        exports2.isProfiler = isProfiler;
        exports2.isStrictMode = isStrictMode;
        exports2.isSuspense = isSuspense;
        exports2.isValidElementType = isValidElementType;
        exports2.typeOf = typeOf;
      })();
    }
  }
});

// node_modules/react-is/index.js
var require_react_is = __commonJS({
  "node_modules/react-is/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    if (process.env.NODE_ENV === "production") {
      module2.exports = require_react_is_production_min();
    } else {
      module2.exports = require_react_is_development();
    }
  }
});

// node_modules/object-assign/index.js
var require_object_assign = __commonJS({
  "node_modules/object-assign/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var getOwnPropertySymbols = Object.getOwnPropertySymbols;
    var hasOwnProperty2 = Object.prototype.hasOwnProperty;
    var propIsEnumerable = Object.prototype.propertyIsEnumerable;
    function toObject(val) {
      if (val === null || val === void 0) {
        throw new TypeError("Object.assign cannot be called with null or undefined");
      }
      return Object(val);
    }
    __name(toObject, "toObject");
    function shouldUseNative() {
      try {
        if (!Object.assign) {
          return false;
        }
        var test1 = new String("abc");
        test1[5] = "de";
        if (Object.getOwnPropertyNames(test1)[0] === "5") {
          return false;
        }
        var test2 = {};
        for (var i = 0; i < 10; i++) {
          test2["_" + String.fromCharCode(i)] = i;
        }
        var order2 = Object.getOwnPropertyNames(test2).map(function(n2) {
          return test2[n2];
        });
        if (order2.join("") !== "0123456789") {
          return false;
        }
        var test3 = {};
        "abcdefghijklmnopqrst".split("").forEach(function(letter) {
          test3[letter] = letter;
        });
        if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") {
          return false;
        }
        return true;
      } catch (err) {
        return false;
      }
    }
    __name(shouldUseNative, "shouldUseNative");
    module2.exports = shouldUseNative() ? Object.assign : function(target, source2) {
      var from;
      var to = toObject(target);
      var symbols;
      for (var s2 = 1; s2 < arguments.length; s2++) {
        from = Object(arguments[s2]);
        for (var key in from) {
          if (hasOwnProperty2.call(from, key)) {
            to[key] = from[key];
          }
        }
        if (getOwnPropertySymbols) {
          symbols = getOwnPropertySymbols(from);
          for (var i = 0; i < symbols.length; i++) {
            if (propIsEnumerable.call(from, symbols[i])) {
              to[symbols[i]] = from[symbols[i]];
            }
          }
        }
      }
      return to;
    };
  }
});

// node_modules/prop-types/lib/ReactPropTypesSecret.js
var require_ReactPropTypesSecret = __commonJS({
  "node_modules/prop-types/lib/ReactPropTypesSecret.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var ReactPropTypesSecret = "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";
    module2.exports = ReactPropTypesSecret;
  }
});

// node_modules/prop-types/lib/has.js
var require_has = __commonJS({
  "node_modules/prop-types/lib/has.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = Function.call.bind(Object.prototype.hasOwnProperty);
  }
});

// node_modules/prop-types/checkPropTypes.js
var require_checkPropTypes = __commonJS({
  "node_modules/prop-types/checkPropTypes.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var printWarning = /* @__PURE__ */ __name(function() {
    }, "printWarning");
    if (process.env.NODE_ENV !== "production") {
      ReactPropTypesSecret = require_ReactPropTypesSecret();
      loggedTypeFailures = {};
      has2 = require_has();
      printWarning = /* @__PURE__ */ __name(function(text) {
        var message = "Warning: " + text;
        if (typeof console !== "undefined") {
          console.error(message);
        }
        try {
          throw new Error(message);
        } catch (x) {
        }
      }, "printWarning");
    }
    var ReactPropTypesSecret;
    var loggedTypeFailures;
    var has2;
    function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
      if (process.env.NODE_ENV !== "production") {
        for (var typeSpecName in typeSpecs) {
          if (has2(typeSpecs, typeSpecName)) {
            var error;
            try {
              if (typeof typeSpecs[typeSpecName] !== "function") {
                var err = Error(
                  (componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."
                );
                err.name = "Invariant Violation";
                throw err;
              }
              error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
            } catch (ex) {
              error = ex;
            }
            if (error && !(error instanceof Error)) {
              printWarning(
                (componentName || "React class") + ": type specification of " + location + " `" + typeSpecName + "` is invalid; the type checker function must return `null` or an `Error` but returned a " + typeof error + ". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)."
              );
            }
            if (error instanceof Error && !(error.message in loggedTypeFailures)) {
              loggedTypeFailures[error.message] = true;
              var stack = getStack ? getStack() : "";
              printWarning(
                "Failed " + location + " type: " + error.message + (stack != null ? stack : "")
              );
            }
          }
        }
      }
    }
    __name(checkPropTypes, "checkPropTypes");
    checkPropTypes.resetWarningCache = function() {
      if (process.env.NODE_ENV !== "production") {
        loggedTypeFailures = {};
      }
    };
    module2.exports = checkPropTypes;
  }
});

// node_modules/prop-types/factoryWithTypeCheckers.js
var require_factoryWithTypeCheckers = __commonJS({
  "node_modules/prop-types/factoryWithTypeCheckers.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var ReactIs = require_react_is();
    var assign = require_object_assign();
    var ReactPropTypesSecret = require_ReactPropTypesSecret();
    var has2 = require_has();
    var checkPropTypes = require_checkPropTypes();
    var printWarning = /* @__PURE__ */ __name(function() {
    }, "printWarning");
    if (process.env.NODE_ENV !== "production") {
      printWarning = /* @__PURE__ */ __name(function(text) {
        var message = "Warning: " + text;
        if (typeof console !== "undefined") {
          console.error(message);
        }
        try {
          throw new Error(message);
        } catch (x) {
        }
      }, "printWarning");
    }
    function emptyFunctionThatReturnsNull() {
      return null;
    }
    __name(emptyFunctionThatReturnsNull, "emptyFunctionThatReturnsNull");
    module2.exports = function(isValidElement, throwOnDirectAccess) {
      var ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator;
      var FAUX_ITERATOR_SYMBOL = "@@iterator";
      function getIteratorFn(maybeIterable) {
        var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
        if (typeof iteratorFn === "function") {
          return iteratorFn;
        }
      }
      __name(getIteratorFn, "getIteratorFn");
      var ANONYMOUS = "<<anonymous>>";
      var ReactPropTypes = {
        array: createPrimitiveTypeChecker("array"),
        bigint: createPrimitiveTypeChecker("bigint"),
        bool: createPrimitiveTypeChecker("boolean"),
        func: createPrimitiveTypeChecker("function"),
        number: createPrimitiveTypeChecker("number"),
        object: createPrimitiveTypeChecker("object"),
        string: createPrimitiveTypeChecker("string"),
        symbol: createPrimitiveTypeChecker("symbol"),
        any: createAnyTypeChecker(),
        arrayOf: createArrayOfTypeChecker,
        element: createElementTypeChecker(),
        elementType: createElementTypeTypeChecker(),
        instanceOf: createInstanceTypeChecker,
        node: createNodeChecker(),
        objectOf: createObjectOfTypeChecker,
        oneOf: createEnumTypeChecker,
        oneOfType: createUnionTypeChecker,
        shape: createShapeTypeChecker,
        exact: createStrictShapeTypeChecker
      };
      function is(x, y) {
        if (x === y) {
          return x !== 0 || 1 / x === 1 / y;
        } else {
          return x !== x && y !== y;
        }
      }
      __name(is, "is");
      function PropTypeError(message, data) {
        this.message = message;
        this.data = data && typeof data === "object" ? data : {};
        this.stack = "";
      }
      __name(PropTypeError, "PropTypeError");
      PropTypeError.prototype = Error.prototype;
      function createChainableTypeChecker(validate4) {
        if (process.env.NODE_ENV !== "production") {
          var manualPropTypeCallCache = {};
          var manualPropTypeWarningCount = 0;
        }
        function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
          componentName = componentName || ANONYMOUS;
          propFullName = propFullName || propName;
          if (secret !== ReactPropTypesSecret) {
            if (throwOnDirectAccess) {
              var err = new Error(
                "Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types"
              );
              err.name = "Invariant Violation";
              throw err;
            } else if (process.env.NODE_ENV !== "production" && typeof console !== "undefined") {
              var cacheKey = componentName + ":" + propName;
              if (!manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors
              manualPropTypeWarningCount < 3) {
                printWarning(
                  "You are manually calling a React.PropTypes validation function for the `" + propFullName + "` prop on `" + componentName + "`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."
                );
                manualPropTypeCallCache[cacheKey] = true;
                manualPropTypeWarningCount++;
              }
            }
          }
          if (props[propName] == null) {
            if (isRequired) {
              if (props[propName] === null) {
                return new PropTypeError("The " + location + " `" + propFullName + "` is marked as required " + ("in `" + componentName + "`, but its value is `null`."));
              }
              return new PropTypeError("The " + location + " `" + propFullName + "` is marked as required in " + ("`" + componentName + "`, but its value is `undefined`."));
            }
            return null;
          } else {
            return validate4(props, propName, componentName, location, propFullName);
          }
        }
        __name(checkType, "checkType");
        var chainedCheckType = checkType.bind(null, false);
        chainedCheckType.isRequired = checkType.bind(null, true);
        return chainedCheckType;
      }
      __name(createChainableTypeChecker, "createChainableTypeChecker");
      function createPrimitiveTypeChecker(expectedType) {
        function validate4(props, propName, componentName, location, propFullName, secret) {
          var propValue = props[propName];
          var propType = getPropType(propValue);
          if (propType !== expectedType) {
            var preciseType = getPreciseType(propValue);
            return new PropTypeError(
              "Invalid " + location + " `" + propFullName + "` of type " + ("`" + preciseType + "` supplied to `" + componentName + "`, expected ") + ("`" + expectedType + "`."),
              { expectedType }
            );
          }
          return null;
        }
        __name(validate4, "validate");
        return createChainableTypeChecker(validate4);
      }
      __name(createPrimitiveTypeChecker, "createPrimitiveTypeChecker");
      function createAnyTypeChecker() {
        return createChainableTypeChecker(emptyFunctionThatReturnsNull);
      }
      __name(createAnyTypeChecker, "createAnyTypeChecker");
      function createArrayOfTypeChecker(typeChecker) {
        function validate4(props, propName, componentName, location, propFullName) {
          if (typeof typeChecker !== "function") {
            return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside arrayOf.");
          }
          var propValue = props[propName];
          if (!Array.isArray(propValue)) {
            var propType = getPropType(propValue);
            return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an array."));
          }
          for (var i = 0; i < propValue.length; i++) {
            var error = typeChecker(propValue, i, componentName, location, propFullName + "[" + i + "]", ReactPropTypesSecret);
            if (error instanceof Error) {
              return error;
            }
          }
          return null;
        }
        __name(validate4, "validate");
        return createChainableTypeChecker(validate4);
      }
      __name(createArrayOfTypeChecker, "createArrayOfTypeChecker");
      function createElementTypeChecker() {
        function validate4(props, propName, componentName, location, propFullName) {
          var propValue = props[propName];
          if (!isValidElement(propValue)) {
            var propType = getPropType(propValue);
            return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement."));
          }
          return null;
        }
        __name(validate4, "validate");
        return createChainableTypeChecker(validate4);
      }
      __name(createElementTypeChecker, "createElementTypeChecker");
      function createElementTypeTypeChecker() {
        function validate4(props, propName, componentName, location, propFullName) {
          var propValue = props[propName];
          if (!ReactIs.isValidElementType(propValue)) {
            var propType = getPropType(propValue);
            return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement type."));
          }
          return null;
        }
        __name(validate4, "validate");
        return createChainableTypeChecker(validate4);
      }
      __name(createElementTypeTypeChecker, "createElementTypeTypeChecker");
      function createInstanceTypeChecker(expectedClass) {
        function validate4(props, propName, componentName, location, propFullName) {
          if (!(props[propName] instanceof expectedClass)) {
            var expectedClassName = expectedClass.name || ANONYMOUS;
            var actualClassName = getClassName(props[propName]);
            return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + actualClassName + "` supplied to `" + componentName + "`, expected ") + ("instance of `" + expectedClassName + "`."));
          }
          return null;
        }
        __name(validate4, "validate");
        return createChainableTypeChecker(validate4);
      }
      __name(createInstanceTypeChecker, "createInstanceTypeChecker");
      function createEnumTypeChecker(expectedValues) {
        if (!Array.isArray(expectedValues)) {
          if (process.env.NODE_ENV !== "production") {
            if (arguments.length > 1) {
              printWarning(
                "Invalid arguments supplied to oneOf, expected an array, got " + arguments.length + " arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z])."
              );
            } else {
              printWarning("Invalid argument supplied to oneOf, expected an array.");
            }
          }
          return emptyFunctionThatReturnsNull;
        }
        function validate4(props, propName, componentName, location, propFullName) {
          var propValue = props[propName];
          for (var i = 0; i < expectedValues.length; i++) {
            if (is(propValue, expectedValues[i])) {
              return null;
            }
          }
          var valuesString = JSON.stringify(expectedValues, /* @__PURE__ */ __name(function replacer(key, value) {
            var type = getPreciseType(value);
            if (type === "symbol") {
              return String(value);
            }
            return value;
          }, "replacer"));
          return new PropTypeError("Invalid " + location + " `" + propFullName + "` of value `" + String(propValue) + "` " + ("supplied to `" + componentName + "`, expected one of " + valuesString + "."));
        }
        __name(validate4, "validate");
        return createChainableTypeChecker(validate4);
      }
      __name(createEnumTypeChecker, "createEnumTypeChecker");
      function createObjectOfTypeChecker(typeChecker) {
        function validate4(props, propName, componentName, location, propFullName) {
          if (typeof typeChecker !== "function") {
            return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside objectOf.");
          }
          var propValue = props[propName];
          var propType = getPropType(propValue);
          if (propType !== "object") {
            return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an object."));
          }
          for (var key in propValue) {
            if (has2(propValue, key)) {
              var error = typeChecker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
              if (error instanceof Error) {
                return error;
              }
            }
          }
          return null;
        }
        __name(validate4, "validate");
        return createChainableTypeChecker(validate4);
      }
      __name(createObjectOfTypeChecker, "createObjectOfTypeChecker");
      function createUnionTypeChecker(arrayOfTypeCheckers) {
        if (!Array.isArray(arrayOfTypeCheckers)) {
          process.env.NODE_ENV !== "production" ? printWarning("Invalid argument supplied to oneOfType, expected an instance of array.") : void 0;
          return emptyFunctionThatReturnsNull;
        }
        for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
          var checker = arrayOfTypeCheckers[i];
          if (typeof checker !== "function") {
            printWarning(
              "Invalid argument supplied to oneOfType. Expected an array of check functions, but received " + getPostfixForTypeWarning(checker) + " at index " + i + "."
            );
            return emptyFunctionThatReturnsNull;
          }
        }
        function validate4(props, propName, componentName, location, propFullName) {
          var expectedTypes = [];
          for (var i2 = 0; i2 < arrayOfTypeCheckers.length; i2++) {
            var checker2 = arrayOfTypeCheckers[i2];
            var checkerResult = checker2(props, propName, componentName, location, propFullName, ReactPropTypesSecret);
            if (checkerResult == null) {
              return null;
            }
            if (checkerResult.data && has2(checkerResult.data, "expectedType")) {
              expectedTypes.push(checkerResult.data.expectedType);
            }
          }
          var expectedTypesMessage = expectedTypes.length > 0 ? ", expected one of type [" + expectedTypes.join(", ") + "]" : "";
          return new PropTypeError("Invalid " + location + " `" + propFullName + "` supplied to " + ("`" + componentName + "`" + expectedTypesMessage + "."));
        }
        __name(validate4, "validate");
        return createChainableTypeChecker(validate4);
      }
      __name(createUnionTypeChecker, "createUnionTypeChecker");
      function createNodeChecker() {
        function validate4(props, propName, componentName, location, propFullName) {
          if (!isNode3(props[propName])) {
            return new PropTypeError("Invalid " + location + " `" + propFullName + "` supplied to " + ("`" + componentName + "`, expected a ReactNode."));
          }
          return null;
        }
        __name(validate4, "validate");
        return createChainableTypeChecker(validate4);
      }
      __name(createNodeChecker, "createNodeChecker");
      function invalidValidatorError(componentName, location, propFullName, key, type) {
        return new PropTypeError(
          (componentName || "React class") + ": " + location + " type `" + propFullName + "." + key + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + type + "`."
        );
      }
      __name(invalidValidatorError, "invalidValidatorError");
      function createShapeTypeChecker(shapeTypes) {
        function validate4(props, propName, componentName, location, propFullName) {
          var propValue = props[propName];
          var propType = getPropType(propValue);
          if (propType !== "object") {
            return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`."));
          }
          for (var key in shapeTypes) {
            var checker = shapeTypes[key];
            if (typeof checker !== "function") {
              return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker));
            }
            var error = checker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
            if (error) {
              return error;
            }
          }
          return null;
        }
        __name(validate4, "validate");
        return createChainableTypeChecker(validate4);
      }
      __name(createShapeTypeChecker, "createShapeTypeChecker");
      function createStrictShapeTypeChecker(shapeTypes) {
        function validate4(props, propName, componentName, location, propFullName) {
          var propValue = props[propName];
          var propType = getPropType(propValue);
          if (propType !== "object") {
            return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`."));
          }
          var allKeys = assign({}, props[propName], shapeTypes);
          for (var key in allKeys) {
            var checker = shapeTypes[key];
            if (has2(shapeTypes, key) && typeof checker !== "function") {
              return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker));
            }
            if (!checker) {
              return new PropTypeError(
                "Invalid " + location + " `" + propFullName + "` key `" + key + "` supplied to `" + componentName + "`.\nBad object: " + JSON.stringify(props[propName], null, "  ") + "\nValid keys: " + JSON.stringify(Object.keys(shapeTypes), null, "  ")
              );
            }
            var error = checker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
            if (error) {
              return error;
            }
          }
          return null;
        }
        __name(validate4, "validate");
        return createChainableTypeChecker(validate4);
      }
      __name(createStrictShapeTypeChecker, "createStrictShapeTypeChecker");
      function isNode3(propValue) {
        switch (typeof propValue) {
          case "number":
          case "string":
          case "undefined":
            return true;
          case "boolean":
            return !propValue;
          case "object":
            if (Array.isArray(propValue)) {
              return propValue.every(isNode3);
            }
            if (propValue === null || isValidElement(propValue)) {
              return true;
            }
            var iteratorFn = getIteratorFn(propValue);
            if (iteratorFn) {
              var iterator = iteratorFn.call(propValue);
              var step;
              if (iteratorFn !== propValue.entries) {
                while (!(step = iterator.next()).done) {
                  if (!isNode3(step.value)) {
                    return false;
                  }
                }
              } else {
                while (!(step = iterator.next()).done) {
                  var entry = step.value;
                  if (entry) {
                    if (!isNode3(entry[1])) {
                      return false;
                    }
                  }
                }
              }
            } else {
              return false;
            }
            return true;
          default:
            return false;
        }
      }
      __name(isNode3, "isNode");
      function isSymbol(propType, propValue) {
        if (propType === "symbol") {
          return true;
        }
        if (!propValue) {
          return false;
        }
        if (propValue["@@toStringTag"] === "Symbol") {
          return true;
        }
        if (typeof Symbol === "function" && propValue instanceof Symbol) {
          return true;
        }
        return false;
      }
      __name(isSymbol, "isSymbol");
      function getPropType(propValue) {
        var propType = typeof propValue;
        if (Array.isArray(propValue)) {
          return "array";
        }
        if (propValue instanceof RegExp) {
          return "object";
        }
        if (isSymbol(propType, propValue)) {
          return "symbol";
        }
        return propType;
      }
      __name(getPropType, "getPropType");
      function getPreciseType(propValue) {
        if (typeof propValue === "undefined" || propValue === null) {
          return "" + propValue;
        }
        var propType = getPropType(propValue);
        if (propType === "object") {
          if (propValue instanceof Date) {
            return "date";
          } else if (propValue instanceof RegExp) {
            return "regexp";
          }
        }
        return propType;
      }
      __name(getPreciseType, "getPreciseType");
      function getPostfixForTypeWarning(value) {
        var type = getPreciseType(value);
        switch (type) {
          case "array":
          case "object":
            return "an " + type;
          case "boolean":
          case "date":
          case "regexp":
            return "a " + type;
          default:
            return type;
        }
      }
      __name(getPostfixForTypeWarning, "getPostfixForTypeWarning");
      function getClassName(propValue) {
        if (!propValue.constructor || !propValue.constructor.name) {
          return ANONYMOUS;
        }
        return propValue.constructor.name;
      }
      __name(getClassName, "getClassName");
      ReactPropTypes.checkPropTypes = checkPropTypes;
      ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache;
      ReactPropTypes.PropTypes = ReactPropTypes;
      return ReactPropTypes;
    };
  }
});

// node_modules/prop-types/factoryWithThrowingShims.js
var require_factoryWithThrowingShims = __commonJS({
  "node_modules/prop-types/factoryWithThrowingShims.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var ReactPropTypesSecret = require_ReactPropTypesSecret();
    function emptyFunction() {
    }
    __name(emptyFunction, "emptyFunction");
    function emptyFunctionWithReset() {
    }
    __name(emptyFunctionWithReset, "emptyFunctionWithReset");
    emptyFunctionWithReset.resetWarningCache = emptyFunction;
    module2.exports = function() {
      function shim3(props, propName, componentName, location, propFullName, secret) {
        if (secret === ReactPropTypesSecret) {
          return;
        }
        var err = new Error(
          "Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types"
        );
        err.name = "Invariant Violation";
        throw err;
      }
      __name(shim3, "shim");
      ;
      shim3.isRequired = shim3;
      function getShim() {
        return shim3;
      }
      __name(getShim, "getShim");
      ;
      var ReactPropTypes = {
        array: shim3,
        bigint: shim3,
        bool: shim3,
        func: shim3,
        number: shim3,
        object: shim3,
        string: shim3,
        symbol: shim3,
        any: shim3,
        arrayOf: getShim,
        element: shim3,
        elementType: shim3,
        instanceOf: getShim,
        node: shim3,
        objectOf: getShim,
        oneOf: getShim,
        oneOfType: getShim,
        shape: getShim,
        exact: getShim,
        checkPropTypes: emptyFunctionWithReset,
        resetWarningCache: emptyFunction
      };
      ReactPropTypes.PropTypes = ReactPropTypes;
      return ReactPropTypes;
    };
  }
});

// node_modules/prop-types/index.js
var require_prop_types = __commonJS({
  "node_modules/prop-types/index.js"(exports2, module2) {
    init_esbuild_shims();
    if (process.env.NODE_ENV !== "production") {
      ReactIs = require_react_is();
      throwOnDirectAccess = true;
      module2.exports = require_factoryWithTypeCheckers()(ReactIs.isElement, throwOnDirectAccess);
    } else {
      module2.exports = require_factoryWithThrowingShims()();
    }
    var ReactIs;
    var throwOnDirectAccess;
  }
});

// node_modules/tinycolor2/cjs/tinycolor.js
var require_tinycolor = __commonJS({
  "node_modules/tinycolor2/cjs/tinycolor.js"(exports2, module2) {
    init_esbuild_shims();
    (function(global2, factory) {
      typeof exports2 === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.tinycolor = factory());
    })(exports2, function() {
      "use strict";
      function _typeof2(obj) {
        "@babel/helpers - typeof";
        return _typeof2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj2) {
          return typeof obj2;
        } : function(obj2) {
          return obj2 && "function" == typeof Symbol && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
        }, _typeof2(obj);
      }
      __name(_typeof2, "_typeof");
      var trimLeft = /^\s+/;
      var trimRight = /\s+$/;
      function tinycolor(color, opts) {
        color = color ? color : "";
        opts = opts || {};
        if (color instanceof tinycolor) {
          return color;
        }
        if (!(this instanceof tinycolor)) {
          return new tinycolor(color, opts);
        }
        var rgb = inputToRGB(color);
        this._originalInput = color, this._r = rgb.r, this._g = rgb.g, this._b = rgb.b, this._a = rgb.a, this._roundA = Math.round(100 * this._a) / 100, this._format = opts.format || rgb.format;
        this._gradientType = opts.gradientType;
        if (this._r < 1) this._r = Math.round(this._r);
        if (this._g < 1) this._g = Math.round(this._g);
        if (this._b < 1) this._b = Math.round(this._b);
        this._ok = rgb.ok;
      }
      __name(tinycolor, "tinycolor");
      tinycolor.prototype = {
        isDark: /* @__PURE__ */ __name(function isDark() {
          return this.getBrightness() < 128;
        }, "isDark"),
        isLight: /* @__PURE__ */ __name(function isLight() {
          return !this.isDark();
        }, "isLight"),
        isValid: /* @__PURE__ */ __name(function isValid2() {
          return this._ok;
        }, "isValid"),
        getOriginalInput: /* @__PURE__ */ __name(function getOriginalInput() {
          return this._originalInput;
        }, "getOriginalInput"),
        getFormat: /* @__PURE__ */ __name(function getFormat() {
          return this._format;
        }, "getFormat"),
        getAlpha: /* @__PURE__ */ __name(function getAlpha() {
          return this._a;
        }, "getAlpha"),
        getBrightness: /* @__PURE__ */ __name(function getBrightness() {
          var rgb = this.toRgb();
          return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1e3;
        }, "getBrightness"),
        getLuminance: /* @__PURE__ */ __name(function getLuminance() {
          var rgb = this.toRgb();
          var RsRGB, GsRGB, BsRGB, R, G, B;
          RsRGB = rgb.r / 255;
          GsRGB = rgb.g / 255;
          BsRGB = rgb.b / 255;
          if (RsRGB <= 0.03928) R = RsRGB / 12.92;
          else R = Math.pow((RsRGB + 0.055) / 1.055, 2.4);
          if (GsRGB <= 0.03928) G = GsRGB / 12.92;
          else G = Math.pow((GsRGB + 0.055) / 1.055, 2.4);
          if (BsRGB <= 0.03928) B = BsRGB / 12.92;
          else B = Math.pow((BsRGB + 0.055) / 1.055, 2.4);
          return 0.2126 * R + 0.7152 * G + 0.0722 * B;
        }, "getLuminance"),
        setAlpha: /* @__PURE__ */ __name(function setAlpha(value) {
          this._a = boundAlpha(value);
          this._roundA = Math.round(100 * this._a) / 100;
          return this;
        }, "setAlpha"),
        toHsv: /* @__PURE__ */ __name(function toHsv() {
          var hsv = rgbToHsv(this._r, this._g, this._b);
          return {
            h: hsv.h * 360,
            s: hsv.s,
            v: hsv.v,
            a: this._a
          };
        }, "toHsv"),
        toHsvString: /* @__PURE__ */ __name(function toHsvString() {
          var hsv = rgbToHsv(this._r, this._g, this._b);
          var h = Math.round(hsv.h * 360), s2 = Math.round(hsv.s * 100), v = Math.round(hsv.v * 100);
          return this._a == 1 ? "hsv(" + h + ", " + s2 + "%, " + v + "%)" : "hsva(" + h + ", " + s2 + "%, " + v + "%, " + this._roundA + ")";
        }, "toHsvString"),
        toHsl: /* @__PURE__ */ __name(function toHsl() {
          var hsl = rgbToHsl(this._r, this._g, this._b);
          return {
            h: hsl.h * 360,
            s: hsl.s,
            l: hsl.l,
            a: this._a
          };
        }, "toHsl"),
        toHslString: /* @__PURE__ */ __name(function toHslString() {
          var hsl = rgbToHsl(this._r, this._g, this._b);
          var h = Math.round(hsl.h * 360), s2 = Math.round(hsl.s * 100), l2 = Math.round(hsl.l * 100);
          return this._a == 1 ? "hsl(" + h + ", " + s2 + "%, " + l2 + "%)" : "hsla(" + h + ", " + s2 + "%, " + l2 + "%, " + this._roundA + ")";
        }, "toHslString"),
        toHex: /* @__PURE__ */ __name(function toHex(allow3Char) {
          return rgbToHex(this._r, this._g, this._b, allow3Char);
        }, "toHex"),
        toHexString: /* @__PURE__ */ __name(function toHexString(allow3Char) {
          return "#" + this.toHex(allow3Char);
        }, "toHexString"),
        toHex8: /* @__PURE__ */ __name(function toHex8(allow4Char) {
          return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);
        }, "toHex8"),
        toHex8String: /* @__PURE__ */ __name(function toHex8String(allow4Char) {
          return "#" + this.toHex8(allow4Char);
        }, "toHex8String"),
        toRgb: /* @__PURE__ */ __name(function toRgb() {
          return {
            r: Math.round(this._r),
            g: Math.round(this._g),
            b: Math.round(this._b),
            a: this._a
          };
        }, "toRgb"),
        toRgbString: /* @__PURE__ */ __name(function toRgbString() {
          return this._a == 1 ? "rgb(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ")" : "rgba(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ", " + this._roundA + ")";
        }, "toRgbString"),
        toPercentageRgb: /* @__PURE__ */ __name(function toPercentageRgb() {
          return {
            r: Math.round(bound01(this._r, 255) * 100) + "%",
            g: Math.round(bound01(this._g, 255) * 100) + "%",
            b: Math.round(bound01(this._b, 255) * 100) + "%",
            a: this._a
          };
        }, "toPercentageRgb"),
        toPercentageRgbString: /* @__PURE__ */ __name(function toPercentageRgbString() {
          return this._a == 1 ? "rgb(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%)" : "rgba(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
        }, "toPercentageRgbString"),
        toName: /* @__PURE__ */ __name(function toName() {
          if (this._a === 0) {
            return "transparent";
          }
          if (this._a < 1) {
            return false;
          }
          return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
        }, "toName"),
        toFilter: /* @__PURE__ */ __name(function toFilter(secondColor) {
          var hex8String = "#" + rgbaToArgbHex(this._r, this._g, this._b, this._a);
          var secondHex8String = hex8String;
          var gradientType = this._gradientType ? "GradientType = 1, " : "";
          if (secondColor) {
            var s2 = tinycolor(secondColor);
            secondHex8String = "#" + rgbaToArgbHex(s2._r, s2._g, s2._b, s2._a);
          }
          return "progid:DXImageTransform.Microsoft.gradient(" + gradientType + "startColorstr=" + hex8String + ",endColorstr=" + secondHex8String + ")";
        }, "toFilter"),
        toString: /* @__PURE__ */ __name(function toString(format4) {
          var formatSet = !!format4;
          format4 = format4 || this._format;
          var formattedString = false;
          var hasAlpha = this._a < 1 && this._a >= 0;
          var needsAlphaFormat = !formatSet && hasAlpha && (format4 === "hex" || format4 === "hex6" || format4 === "hex3" || format4 === "hex4" || format4 === "hex8" || format4 === "name");
          if (needsAlphaFormat) {
            if (format4 === "name" && this._a === 0) {
              return this.toName();
            }
            return this.toRgbString();
          }
          if (format4 === "rgb") {
            formattedString = this.toRgbString();
          }
          if (format4 === "prgb") {
            formattedString = this.toPercentageRgbString();
          }
          if (format4 === "hex" || format4 === "hex6") {
            formattedString = this.toHexString();
          }
          if (format4 === "hex3") {
            formattedString = this.toHexString(true);
          }
          if (format4 === "hex4") {
            formattedString = this.toHex8String(true);
          }
          if (format4 === "hex8") {
            formattedString = this.toHex8String();
          }
          if (format4 === "name") {
            formattedString = this.toName();
          }
          if (format4 === "hsl") {
            formattedString = this.toHslString();
          }
          if (format4 === "hsv") {
            formattedString = this.toHsvString();
          }
          return formattedString || this.toHexString();
        }, "toString"),
        clone: /* @__PURE__ */ __name(function clone() {
          return tinycolor(this.toString());
        }, "clone"),
        _applyModification: /* @__PURE__ */ __name(function _applyModification(fn, args) {
          var color = fn.apply(null, [this].concat([].slice.call(args)));
          this._r = color._r;
          this._g = color._g;
          this._b = color._b;
          this.setAlpha(color._a);
          return this;
        }, "_applyModification"),
        lighten: /* @__PURE__ */ __name(function lighten() {
          return this._applyModification(_lighten, arguments);
        }, "lighten"),
        brighten: /* @__PURE__ */ __name(function brighten() {
          return this._applyModification(_brighten, arguments);
        }, "brighten"),
        darken: /* @__PURE__ */ __name(function darken() {
          return this._applyModification(_darken, arguments);
        }, "darken"),
        desaturate: /* @__PURE__ */ __name(function desaturate() {
          return this._applyModification(_desaturate, arguments);
        }, "desaturate"),
        saturate: /* @__PURE__ */ __name(function saturate() {
          return this._applyModification(_saturate, arguments);
        }, "saturate"),
        greyscale: /* @__PURE__ */ __name(function greyscale() {
          return this._applyModification(_greyscale, arguments);
        }, "greyscale"),
        spin: /* @__PURE__ */ __name(function spin() {
          return this._applyModification(_spin, arguments);
        }, "spin"),
        _applyCombination: /* @__PURE__ */ __name(function _applyCombination(fn, args) {
          return fn.apply(null, [this].concat([].slice.call(args)));
        }, "_applyCombination"),
        analogous: /* @__PURE__ */ __name(function analogous() {
          return this._applyCombination(_analogous, arguments);
        }, "analogous"),
        complement: /* @__PURE__ */ __name(function complement() {
          return this._applyCombination(_complement, arguments);
        }, "complement"),
        monochromatic: /* @__PURE__ */ __name(function monochromatic() {
          return this._applyCombination(_monochromatic, arguments);
        }, "monochromatic"),
        splitcomplement: /* @__PURE__ */ __name(function splitcomplement() {
          return this._applyCombination(_splitcomplement, arguments);
        }, "splitcomplement"),
        // Disabled until https://github.com/bgrins/TinyColor/issues/254
        // polyad: function (number) {
        //   return this._applyCombination(polyad, [number]);
        // },
        triad: /* @__PURE__ */ __name(function triad() {
          return this._applyCombination(polyad, [3]);
        }, "triad"),
        tetrad: /* @__PURE__ */ __name(function tetrad() {
          return this._applyCombination(polyad, [4]);
        }, "tetrad")
      };
      tinycolor.fromRatio = function(color, opts) {
        if (_typeof2(color) == "object") {
          var newColor = {};
          for (var i in color) {
            if (color.hasOwnProperty(i)) {
              if (i === "a") {
                newColor[i] = color[i];
              } else {
                newColor[i] = convertToPercentage(color[i]);
              }
            }
          }
          color = newColor;
        }
        return tinycolor(color, opts);
      };
      function inputToRGB(color) {
        var rgb = {
          r: 0,
          g: 0,
          b: 0
        };
        var a = 1;
        var s2 = null;
        var v = null;
        var l2 = null;
        var ok2 = false;
        var format4 = false;
        if (typeof color == "string") {
          color = stringInputToObject(color);
        }
        if (_typeof2(color) == "object") {
          if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {
            rgb = rgbToRgb(color.r, color.g, color.b);
            ok2 = true;
            format4 = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
          } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {
            s2 = convertToPercentage(color.s);
            v = convertToPercentage(color.v);
            rgb = hsvToRgb(color.h, s2, v);
            ok2 = true;
            format4 = "hsv";
          } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
            s2 = convertToPercentage(color.s);
            l2 = convertToPercentage(color.l);
            rgb = hslToRgb(color.h, s2, l2);
            ok2 = true;
            format4 = "hsl";
          }
          if (color.hasOwnProperty("a")) {
            a = color.a;
          }
        }
        a = boundAlpha(a);
        return {
          ok: ok2,
          format: color.format || format4,
          r: Math.min(255, Math.max(rgb.r, 0)),
          g: Math.min(255, Math.max(rgb.g, 0)),
          b: Math.min(255, Math.max(rgb.b, 0)),
          a
        };
      }
      __name(inputToRGB, "inputToRGB");
      function rgbToRgb(r3, g, b) {
        return {
          r: bound01(r3, 255) * 255,
          g: bound01(g, 255) * 255,
          b: bound01(b, 255) * 255
        };
      }
      __name(rgbToRgb, "rgbToRgb");
      function rgbToHsl(r3, g, b) {
        r3 = bound01(r3, 255);
        g = bound01(g, 255);
        b = bound01(b, 255);
        var max = Math.max(r3, g, b), min = Math.min(r3, g, b);
        var h, s2, l2 = (max + min) / 2;
        if (max == min) {
          h = s2 = 0;
        } else {
          var d = max - min;
          s2 = l2 > 0.5 ? d / (2 - max - min) : d / (max + min);
          switch (max) {
            case r3:
              h = (g - b) / d + (g < b ? 6 : 0);
              break;
            case g:
              h = (b - r3) / d + 2;
              break;
            case b:
              h = (r3 - g) / d + 4;
              break;
          }
          h /= 6;
        }
        return {
          h,
          s: s2,
          l: l2
        };
      }
      __name(rgbToHsl, "rgbToHsl");
      function hslToRgb(h, s2, l2) {
        var r3, g, b;
        h = bound01(h, 360);
        s2 = bound01(s2, 100);
        l2 = bound01(l2, 100);
        function hue2rgb(p2, q2, t2) {
          if (t2 < 0) t2 += 1;
          if (t2 > 1) t2 -= 1;
          if (t2 < 1 / 6) return p2 + (q2 - p2) * 6 * t2;
          if (t2 < 1 / 2) return q2;
          if (t2 < 2 / 3) return p2 + (q2 - p2) * (2 / 3 - t2) * 6;
          return p2;
        }
        __name(hue2rgb, "hue2rgb");
        if (s2 === 0) {
          r3 = g = b = l2;
        } else {
          var q = l2 < 0.5 ? l2 * (1 + s2) : l2 + s2 - l2 * s2;
          var p = 2 * l2 - q;
          r3 = hue2rgb(p, q, h + 1 / 3);
          g = hue2rgb(p, q, h);
          b = hue2rgb(p, q, h - 1 / 3);
        }
        return {
          r: r3 * 255,
          g: g * 255,
          b: b * 255
        };
      }
      __name(hslToRgb, "hslToRgb");
      function rgbToHsv(r3, g, b) {
        r3 = bound01(r3, 255);
        g = bound01(g, 255);
        b = bound01(b, 255);
        var max = Math.max(r3, g, b), min = Math.min(r3, g, b);
        var h, s2, v = max;
        var d = max - min;
        s2 = max === 0 ? 0 : d / max;
        if (max == min) {
          h = 0;
        } else {
          switch (max) {
            case r3:
              h = (g - b) / d + (g < b ? 6 : 0);
              break;
            case g:
              h = (b - r3) / d + 2;
              break;
            case b:
              h = (r3 - g) / d + 4;
              break;
          }
          h /= 6;
        }
        return {
          h,
          s: s2,
          v
        };
      }
      __name(rgbToHsv, "rgbToHsv");
      function hsvToRgb(h, s2, v) {
        h = bound01(h, 360) * 6;
        s2 = bound01(s2, 100);
        v = bound01(v, 100);
        var i = Math.floor(h), f = h - i, p = v * (1 - s2), q = v * (1 - f * s2), t2 = v * (1 - (1 - f) * s2), mod2 = i % 6, r3 = [v, q, p, p, t2, v][mod2], g = [t2, v, v, q, p, p][mod2], b = [p, p, t2, v, v, q][mod2];
        return {
          r: r3 * 255,
          g: g * 255,
          b: b * 255
        };
      }
      __name(hsvToRgb, "hsvToRgb");
      function rgbToHex(r3, g, b, allow3Char) {
        var hex = [pad2(Math.round(r3).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))];
        if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
          return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
        }
        return hex.join("");
      }
      __name(rgbToHex, "rgbToHex");
      function rgbaToHex(r3, g, b, a, allow4Char) {
        var hex = [pad2(Math.round(r3).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16)), pad2(convertDecimalToHex(a))];
        if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) {
          return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);
        }
        return hex.join("");
      }
      __name(rgbaToHex, "rgbaToHex");
      function rgbaToArgbHex(r3, g, b, a) {
        var hex = [pad2(convertDecimalToHex(a)), pad2(Math.round(r3).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))];
        return hex.join("");
      }
      __name(rgbaToArgbHex, "rgbaToArgbHex");
      tinycolor.equals = function(color1, color2) {
        if (!color1 || !color2) return false;
        return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
      };
      tinycolor.random = function() {
        return tinycolor.fromRatio({
          r: Math.random(),
          g: Math.random(),
          b: Math.random()
        });
      };
      function _desaturate(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var hsl = tinycolor(color).toHsl();
        hsl.s -= amount / 100;
        hsl.s = clamp01(hsl.s);
        return tinycolor(hsl);
      }
      __name(_desaturate, "_desaturate");
      function _saturate(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var hsl = tinycolor(color).toHsl();
        hsl.s += amount / 100;
        hsl.s = clamp01(hsl.s);
        return tinycolor(hsl);
      }
      __name(_saturate, "_saturate");
      function _greyscale(color) {
        return tinycolor(color).desaturate(100);
      }
      __name(_greyscale, "_greyscale");
      function _lighten(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var hsl = tinycolor(color).toHsl();
        hsl.l += amount / 100;
        hsl.l = clamp01(hsl.l);
        return tinycolor(hsl);
      }
      __name(_lighten, "_lighten");
      function _brighten(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var rgb = tinycolor(color).toRgb();
        rgb.r = Math.max(0, Math.min(255, rgb.r - Math.round(255 * -(amount / 100))));
        rgb.g = Math.max(0, Math.min(255, rgb.g - Math.round(255 * -(amount / 100))));
        rgb.b = Math.max(0, Math.min(255, rgb.b - Math.round(255 * -(amount / 100))));
        return tinycolor(rgb);
      }
      __name(_brighten, "_brighten");
      function _darken(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var hsl = tinycolor(color).toHsl();
        hsl.l -= amount / 100;
        hsl.l = clamp01(hsl.l);
        return tinycolor(hsl);
      }
      __name(_darken, "_darken");
      function _spin(color, amount) {
        var hsl = tinycolor(color).toHsl();
        var hue = (hsl.h + amount) % 360;
        hsl.h = hue < 0 ? 360 + hue : hue;
        return tinycolor(hsl);
      }
      __name(_spin, "_spin");
      function _complement(color) {
        var hsl = tinycolor(color).toHsl();
        hsl.h = (hsl.h + 180) % 360;
        return tinycolor(hsl);
      }
      __name(_complement, "_complement");
      function polyad(color, number) {
        if (isNaN(number) || number <= 0) {
          throw new Error("Argument to polyad must be a positive number");
        }
        var hsl = tinycolor(color).toHsl();
        var result = [tinycolor(color)];
        var step = 360 / number;
        for (var i = 1; i < number; i++) {
          result.push(tinycolor({
            h: (hsl.h + i * step) % 360,
            s: hsl.s,
            l: hsl.l
          }));
        }
        return result;
      }
      __name(polyad, "polyad");
      function _splitcomplement(color) {
        var hsl = tinycolor(color).toHsl();
        var h = hsl.h;
        return [tinycolor(color), tinycolor({
          h: (h + 72) % 360,
          s: hsl.s,
          l: hsl.l
        }), tinycolor({
          h: (h + 216) % 360,
          s: hsl.s,
          l: hsl.l
        })];
      }
      __name(_splitcomplement, "_splitcomplement");
      function _analogous(color, results, slices) {
        results = results || 6;
        slices = slices || 30;
        var hsl = tinycolor(color).toHsl();
        var part = 360 / slices;
        var ret = [tinycolor(color)];
        for (hsl.h = (hsl.h - (part * results >> 1) + 720) % 360; --results; ) {
          hsl.h = (hsl.h + part) % 360;
          ret.push(tinycolor(hsl));
        }
        return ret;
      }
      __name(_analogous, "_analogous");
      function _monochromatic(color, results) {
        results = results || 6;
        var hsv = tinycolor(color).toHsv();
        var h = hsv.h, s2 = hsv.s, v = hsv.v;
        var ret = [];
        var modification = 1 / results;
        while (results--) {
          ret.push(tinycolor({
            h,
            s: s2,
            v
          }));
          v = (v + modification) % 1;
        }
        return ret;
      }
      __name(_monochromatic, "_monochromatic");
      tinycolor.mix = function(color1, color2, amount) {
        amount = amount === 0 ? 0 : amount || 50;
        var rgb1 = tinycolor(color1).toRgb();
        var rgb2 = tinycolor(color2).toRgb();
        var p = amount / 100;
        var rgba = {
          r: (rgb2.r - rgb1.r) * p + rgb1.r,
          g: (rgb2.g - rgb1.g) * p + rgb1.g,
          b: (rgb2.b - rgb1.b) * p + rgb1.b,
          a: (rgb2.a - rgb1.a) * p + rgb1.a
        };
        return tinycolor(rgba);
      };
      tinycolor.readability = function(color1, color2) {
        var c1 = tinycolor(color1);
        var c22 = tinycolor(color2);
        return (Math.max(c1.getLuminance(), c22.getLuminance()) + 0.05) / (Math.min(c1.getLuminance(), c22.getLuminance()) + 0.05);
      };
      tinycolor.isReadable = function(color1, color2, wcag2) {
        var readability = tinycolor.readability(color1, color2);
        var wcag2Parms, out;
        out = false;
        wcag2Parms = validateWCAG2Parms(wcag2);
        switch (wcag2Parms.level + wcag2Parms.size) {
          case "AAsmall":
          case "AAAlarge":
            out = readability >= 4.5;
            break;
          case "AAlarge":
            out = readability >= 3;
            break;
          case "AAAsmall":
            out = readability >= 7;
            break;
        }
        return out;
      };
      tinycolor.mostReadable = function(baseColor, colorList, args) {
        var bestColor = null;
        var bestScore = 0;
        var readability;
        var includeFallbackColors, level, size;
        args = args || {};
        includeFallbackColors = args.includeFallbackColors;
        level = args.level;
        size = args.size;
        for (var i = 0; i < colorList.length; i++) {
          readability = tinycolor.readability(baseColor, colorList[i]);
          if (readability > bestScore) {
            bestScore = readability;
            bestColor = tinycolor(colorList[i]);
          }
        }
        if (tinycolor.isReadable(baseColor, bestColor, {
          level,
          size
        }) || !includeFallbackColors) {
          return bestColor;
        } else {
          args.includeFallbackColors = false;
          return tinycolor.mostReadable(baseColor, ["#fff", "#000"], args);
        }
      };
      var names = tinycolor.names = {
        aliceblue: "f0f8ff",
        antiquewhite: "faebd7",
        aqua: "0ff",
        aquamarine: "7fffd4",
        azure: "f0ffff",
        beige: "f5f5dc",
        bisque: "ffe4c4",
        black: "000",
        blanchedalmond: "ffebcd",
        blue: "00f",
        blueviolet: "8a2be2",
        brown: "a52a2a",
        burlywood: "deb887",
        burntsienna: "ea7e5d",
        cadetblue: "5f9ea0",
        chartreuse: "7fff00",
        chocolate: "d2691e",
        coral: "ff7f50",
        cornflowerblue: "6495ed",
        cornsilk: "fff8dc",
        crimson: "dc143c",
        cyan: "0ff",
        darkblue: "00008b",
        darkcyan: "008b8b",
        darkgoldenrod: "b8860b",
        darkgray: "a9a9a9",
        darkgreen: "006400",
        darkgrey: "a9a9a9",
        darkkhaki: "bdb76b",
        darkmagenta: "8b008b",
        darkolivegreen: "556b2f",
        darkorange: "ff8c00",
        darkorchid: "9932cc",
        darkred: "8b0000",
        darksalmon: "e9967a",
        darkseagreen: "8fbc8f",
        darkslateblue: "483d8b",
        darkslategray: "2f4f4f",
        darkslategrey: "2f4f4f",
        darkturquoise: "00ced1",
        darkviolet: "9400d3",
        deeppink: "ff1493",
        deepskyblue: "00bfff",
        dimgray: "696969",
        dimgrey: "696969",
        dodgerblue: "1e90ff",
        firebrick: "b22222",
        floralwhite: "fffaf0",
        forestgreen: "228b22",
        fuchsia: "f0f",
        gainsboro: "dcdcdc",
        ghostwhite: "f8f8ff",
        gold: "ffd700",
        goldenrod: "daa520",
        gray: "808080",
        green: "008000",
        greenyellow: "adff2f",
        grey: "808080",
        honeydew: "f0fff0",
        hotpink: "ff69b4",
        indianred: "cd5c5c",
        indigo: "4b0082",
        ivory: "fffff0",
        khaki: "f0e68c",
        lavender: "e6e6fa",
        lavenderblush: "fff0f5",
        lawngreen: "7cfc00",
        lemonchiffon: "fffacd",
        lightblue: "add8e6",
        lightcoral: "f08080",
        lightcyan: "e0ffff",
        lightgoldenrodyellow: "fafad2",
        lightgray: "d3d3d3",
        lightgreen: "90ee90",
        lightgrey: "d3d3d3",
        lightpink: "ffb6c1",
        lightsalmon: "ffa07a",
        lightseagreen: "20b2aa",
        lightskyblue: "87cefa",
        lightslategray: "789",
        lightslategrey: "789",
        lightsteelblue: "b0c4de",
        lightyellow: "ffffe0",
        lime: "0f0",
        limegreen: "32cd32",
        linen: "faf0e6",
        magenta: "f0f",
        maroon: "800000",
        mediumaquamarine: "66cdaa",
        mediumblue: "0000cd",
        mediumorchid: "ba55d3",
        mediumpurple: "9370db",
        mediumseagreen: "3cb371",
        mediumslateblue: "7b68ee",
        mediumspringgreen: "00fa9a",
        mediumturquoise: "48d1cc",
        mediumvioletred: "c71585",
        midnightblue: "191970",
        mintcream: "f5fffa",
        mistyrose: "ffe4e1",
        moccasin: "ffe4b5",
        navajowhite: "ffdead",
        navy: "000080",
        oldlace: "fdf5e6",
        olive: "808000",
        olivedrab: "6b8e23",
        orange: "ffa500",
        orangered: "ff4500",
        orchid: "da70d6",
        palegoldenrod: "eee8aa",
        palegreen: "98fb98",
        paleturquoise: "afeeee",
        palevioletred: "db7093",
        papayawhip: "ffefd5",
        peachpuff: "ffdab9",
        peru: "cd853f",
        pink: "ffc0cb",
        plum: "dda0dd",
        powderblue: "b0e0e6",
        purple: "800080",
        rebeccapurple: "663399",
        red: "f00",
        rosybrown: "bc8f8f",
        royalblue: "4169e1",
        saddlebrown: "8b4513",
        salmon: "fa8072",
        sandybrown: "f4a460",
        seagreen: "2e8b57",
        seashell: "fff5ee",
        sienna: "a0522d",
        silver: "c0c0c0",
        skyblue: "87ceeb",
        slateblue: "6a5acd",
        slategray: "708090",
        slategrey: "708090",
        snow: "fffafa",
        springgreen: "00ff7f",
        steelblue: "4682b4",
        tan: "d2b48c",
        teal: "008080",
        thistle: "d8bfd8",
        tomato: "ff6347",
        turquoise: "40e0d0",
        violet: "ee82ee",
        wheat: "f5deb3",
        white: "fff",
        whitesmoke: "f5f5f5",
        yellow: "ff0",
        yellowgreen: "9acd32"
      };
      var hexNames = tinycolor.hexNames = flip(names);
      function flip(o2) {
        var flipped = {};
        for (var i in o2) {
          if (o2.hasOwnProperty(i)) {
            flipped[o2[i]] = i;
          }
        }
        return flipped;
      }
      __name(flip, "flip");
      function boundAlpha(a) {
        a = parseFloat(a);
        if (isNaN(a) || a < 0 || a > 1) {
          a = 1;
        }
        return a;
      }
      __name(boundAlpha, "boundAlpha");
      function bound01(n2, max) {
        if (isOnePointZero(n2)) n2 = "100%";
        var processPercent = isPercentage(n2);
        n2 = Math.min(max, Math.max(0, parseFloat(n2)));
        if (processPercent) {
          n2 = parseInt(n2 * max, 10) / 100;
        }
        if (Math.abs(n2 - max) < 1e-6) {
          return 1;
        }
        return n2 % max / parseFloat(max);
      }
      __name(bound01, "bound01");
      function clamp01(val) {
        return Math.min(1, Math.max(0, val));
      }
      __name(clamp01, "clamp01");
      function parseIntFromHex(val) {
        return parseInt(val, 16);
      }
      __name(parseIntFromHex, "parseIntFromHex");
      function isOnePointZero(n2) {
        return typeof n2 == "string" && n2.indexOf(".") != -1 && parseFloat(n2) === 1;
      }
      __name(isOnePointZero, "isOnePointZero");
      function isPercentage(n2) {
        return typeof n2 === "string" && n2.indexOf("%") != -1;
      }
      __name(isPercentage, "isPercentage");
      function pad2(c3) {
        return c3.length == 1 ? "0" + c3 : "" + c3;
      }
      __name(pad2, "pad2");
      function convertToPercentage(n2) {
        if (n2 <= 1) {
          n2 = n2 * 100 + "%";
        }
        return n2;
      }
      __name(convertToPercentage, "convertToPercentage");
      function convertDecimalToHex(d) {
        return Math.round(parseFloat(d) * 255).toString(16);
      }
      __name(convertDecimalToHex, "convertDecimalToHex");
      function convertHexToDecimal(h) {
        return parseIntFromHex(h) / 255;
      }
      __name(convertHexToDecimal, "convertHexToDecimal");
      var matchers = function() {
        var CSS_INTEGER = "[-\\+]?\\d+%?";
        var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
        var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
        var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
        var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
        return {
          CSS_UNIT: new RegExp(CSS_UNIT),
          rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
          rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
          hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
          hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
          hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
          hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
          hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
          hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
          hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
          hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
        };
      }();
      function isValidCSSUnit(color) {
        return !!matchers.CSS_UNIT.exec(color);
      }
      __name(isValidCSSUnit, "isValidCSSUnit");
      function stringInputToObject(color) {
        color = color.replace(trimLeft, "").replace(trimRight, "").toLowerCase();
        var named = false;
        if (names[color]) {
          color = names[color];
          named = true;
        } else if (color == "transparent") {
          return {
            r: 0,
            g: 0,
            b: 0,
            a: 0,
            format: "name"
          };
        }
        var match2;
        if (match2 = matchers.rgb.exec(color)) {
          return {
            r: match2[1],
            g: match2[2],
            b: match2[3]
          };
        }
        if (match2 = matchers.rgba.exec(color)) {
          return {
            r: match2[1],
            g: match2[2],
            b: match2[3],
            a: match2[4]
          };
        }
        if (match2 = matchers.hsl.exec(color)) {
          return {
            h: match2[1],
            s: match2[2],
            l: match2[3]
          };
        }
        if (match2 = matchers.hsla.exec(color)) {
          return {
            h: match2[1],
            s: match2[2],
            l: match2[3],
            a: match2[4]
          };
        }
        if (match2 = matchers.hsv.exec(color)) {
          return {
            h: match2[1],
            s: match2[2],
            v: match2[3]
          };
        }
        if (match2 = matchers.hsva.exec(color)) {
          return {
            h: match2[1],
            s: match2[2],
            v: match2[3],
            a: match2[4]
          };
        }
        if (match2 = matchers.hex8.exec(color)) {
          return {
            r: parseIntFromHex(match2[1]),
            g: parseIntFromHex(match2[2]),
            b: parseIntFromHex(match2[3]),
            a: convertHexToDecimal(match2[4]),
            format: named ? "name" : "hex8"
          };
        }
        if (match2 = matchers.hex6.exec(color)) {
          return {
            r: parseIntFromHex(match2[1]),
            g: parseIntFromHex(match2[2]),
            b: parseIntFromHex(match2[3]),
            format: named ? "name" : "hex"
          };
        }
        if (match2 = matchers.hex4.exec(color)) {
          return {
            r: parseIntFromHex(match2[1] + "" + match2[1]),
            g: parseIntFromHex(match2[2] + "" + match2[2]),
            b: parseIntFromHex(match2[3] + "" + match2[3]),
            a: convertHexToDecimal(match2[4] + "" + match2[4]),
            format: named ? "name" : "hex8"
          };
        }
        if (match2 = matchers.hex3.exec(color)) {
          return {
            r: parseIntFromHex(match2[1] + "" + match2[1]),
            g: parseIntFromHex(match2[2] + "" + match2[2]),
            b: parseIntFromHex(match2[3] + "" + match2[3]),
            format: named ? "name" : "hex"
          };
        }
        return false;
      }
      __name(stringInputToObject, "stringInputToObject");
      function validateWCAG2Parms(parms) {
        var level, size;
        parms = parms || {
          level: "AA",
          size: "small"
        };
        level = (parms.level || "AA").toUpperCase();
        size = (parms.size || "small").toLowerCase();
        if (level !== "AA" && level !== "AAA") {
          level = "AA";
        }
        if (size !== "small" && size !== "large") {
          size = "small";
        }
        return {
          level,
          size
        };
      }
      __name(validateWCAG2Parms, "validateWCAG2Parms");
      return tinycolor;
    });
  }
});

// node_modules/tinygradient/index.js
var require_tinygradient = __commonJS({
  "node_modules/tinygradient/index.js"(exports2, module2) {
    init_esbuild_shims();
    var tinycolor = require_tinycolor();
    var RGBA_MAX = { r: 256, g: 256, b: 256, a: 1 };
    var HSVA_MAX = { h: 360, s: 1, v: 1, a: 1 };
    function stepize(start, end, steps) {
      let step = {};
      for (let k in start) {
        if (start.hasOwnProperty(k)) {
          step[k] = steps === 0 ? 0 : (end[k] - start[k]) / steps;
        }
      }
      return step;
    }
    __name(stepize, "stepize");
    function interpolate(step, start, i, max) {
      let color = {};
      for (let k in start) {
        if (start.hasOwnProperty(k)) {
          color[k] = step[k] * i + start[k];
          color[k] = color[k] < 0 ? color[k] + max[k] : max[k] !== 1 ? color[k] % max[k] : color[k];
        }
      }
      return color;
    }
    __name(interpolate, "interpolate");
    function interpolateRgb(stop1, stop2, steps) {
      const start = stop1.color.toRgb();
      const end = stop2.color.toRgb();
      const step = stepize(start, end, steps);
      let gradient = [stop1.color];
      for (let i = 1; i < steps; i++) {
        const color = interpolate(step, start, i, RGBA_MAX);
        gradient.push(tinycolor(color));
      }
      return gradient;
    }
    __name(interpolateRgb, "interpolateRgb");
    function interpolateHsv(stop1, stop2, steps, mode) {
      const start = stop1.color.toHsv();
      const end = stop2.color.toHsv();
      if (start.s === 0 || end.s === 0) {
        return interpolateRgb(stop1, stop2, steps);
      }
      let trigonometric;
      if (typeof mode === "boolean") {
        trigonometric = mode;
      } else {
        const trigShortest = start.h < end.h && end.h - start.h < 180 || start.h > end.h && start.h - end.h > 180;
        trigonometric = mode === "long" && trigShortest || mode === "short" && !trigShortest;
      }
      const step = stepize(start, end, steps);
      let gradient = [stop1.color];
      let diff4;
      if (start.h <= end.h && !trigonometric || start.h >= end.h && trigonometric) {
        diff4 = end.h - start.h;
      } else if (trigonometric) {
        diff4 = 360 - end.h + start.h;
      } else {
        diff4 = 360 - start.h + end.h;
      }
      step.h = Math.pow(-1, trigonometric ? 1 : 0) * Math.abs(diff4) / steps;
      for (let i = 1; i < steps; i++) {
        const color = interpolate(step, start, i, HSVA_MAX);
        gradient.push(tinycolor(color));
      }
      return gradient;
    }
    __name(interpolateHsv, "interpolateHsv");
    function computeSubsteps(stops, steps) {
      const l2 = stops.length;
      steps = parseInt(steps, 10);
      if (isNaN(steps) || steps < 2) {
        throw new Error("Invalid number of steps (< 2)");
      }
      if (steps < l2) {
        throw new Error("Number of steps cannot be inferior to number of stops");
      }
      let substeps = [];
      for (let i = 1; i < l2; i++) {
        const step = (steps - 1) * (stops[i].pos - stops[i - 1].pos);
        substeps.push(Math.max(1, Math.round(step)));
      }
      let totalSubsteps = 1;
      for (let n2 = l2 - 1; n2--; ) totalSubsteps += substeps[n2];
      while (totalSubsteps !== steps) {
        if (totalSubsteps < steps) {
          const min = Math.min.apply(null, substeps);
          substeps[substeps.indexOf(min)]++;
          totalSubsteps++;
        } else {
          const max = Math.max.apply(null, substeps);
          substeps[substeps.indexOf(max)]--;
          totalSubsteps--;
        }
      }
      return substeps;
    }
    __name(computeSubsteps, "computeSubsteps");
    function computeAt(stops, pos2, method, max) {
      if (pos2 < 0 || pos2 > 1) {
        throw new Error("Position must be between 0 and 1");
      }
      let start, end;
      for (let i = 0, l2 = stops.length; i < l2 - 1; i++) {
        if (pos2 >= stops[i].pos && pos2 < stops[i + 1].pos) {
          start = stops[i];
          end = stops[i + 1];
          break;
        }
      }
      if (!start) {
        start = end = stops[stops.length - 1];
      }
      const step = stepize(start.color[method](), end.color[method](), (end.pos - start.pos) * 100);
      const color = interpolate(step, start.color[method](), (pos2 - start.pos) * 100, max);
      return tinycolor(color);
    }
    __name(computeAt, "computeAt");
    var TinyGradient = class _TinyGradient {
      static {
        __name(this, "TinyGradient");
      }
      /**
       * @param {StopInput[]|ColorInput[]} stops
       * @returns {TinyGradient}
       */
      constructor(stops) {
        if (stops.length < 2) {
          throw new Error("Invalid number of stops (< 2)");
        }
        const havingPositions = stops[0].pos !== void 0;
        let l2 = stops.length;
        let p = -1;
        let lastColorLess = false;
        this.stops = stops.map((stop2, i) => {
          const hasPosition = stop2.pos !== void 0;
          if (havingPositions ^ hasPosition) {
            throw new Error("Cannot mix positionned and not posionned color stops");
          }
          if (hasPosition) {
            const hasColor = stop2.color !== void 0;
            if (!hasColor && (lastColorLess || i === 0 || i === l2 - 1)) {
              throw new Error("Cannot define two consecutive position-only stops");
            }
            lastColorLess = !hasColor;
            stop2 = {
              color: hasColor ? tinycolor(stop2.color) : null,
              colorLess: !hasColor,
              pos: stop2.pos
            };
            if (stop2.pos < 0 || stop2.pos > 1) {
              throw new Error("Color stops positions must be between 0 and 1");
            } else if (stop2.pos < p) {
              throw new Error("Color stops positions are not ordered");
            }
            p = stop2.pos;
          } else {
            stop2 = {
              color: tinycolor(stop2.color !== void 0 ? stop2.color : stop2),
              pos: i / (l2 - 1)
            };
          }
          return stop2;
        });
        if (this.stops[0].pos !== 0) {
          this.stops.unshift({
            color: this.stops[0].color,
            pos: 0
          });
          l2++;
        }
        if (this.stops[l2 - 1].pos !== 1) {
          this.stops.push({
            color: this.stops[l2 - 1].color,
            pos: 1
          });
        }
      }
      /**
       * Return new instance with reversed stops
       * @return {TinyGradient}
       */
      reverse() {
        let stops = [];
        this.stops.forEach(function(stop2) {
          stops.push({
            color: stop2.color,
            pos: 1 - stop2.pos
          });
        });
        return new _TinyGradient(stops.reverse());
      }
      /**
       * Return new instance with looped stops
       * @return {TinyGradient}
       */
      loop() {
        let stops1 = [];
        let stops2 = [];
        this.stops.forEach((stop2) => {
          stops1.push({
            color: stop2.color,
            pos: stop2.pos / 2
          });
        });
        this.stops.slice(0, -1).forEach((stop2) => {
          stops2.push({
            color: stop2.color,
            pos: 1 - stop2.pos / 2
          });
        });
        return new _TinyGradient(stops1.concat(stops2.reverse()));
      }
      /**
       * Generate gradient with RGBa interpolation
       * @param {number} steps
       * @return {tinycolor[]}
       */
      rgb(steps) {
        const substeps = computeSubsteps(this.stops, steps);
        let gradient = [];
        this.stops.forEach((stop2, i) => {
          if (stop2.colorLess) {
            stop2.color = interpolateRgb(this.stops[i - 1], this.stops[i + 1], 2)[1];
          }
        });
        for (let i = 0, l2 = this.stops.length; i < l2 - 1; i++) {
          const rgb = interpolateRgb(this.stops[i], this.stops[i + 1], substeps[i]);
          gradient.splice(gradient.length, 0, ...rgb);
        }
        gradient.push(this.stops[this.stops.length - 1].color);
        return gradient;
      }
      /**
       * Generate gradient with HSVa interpolation
       * @param {number} steps
       * @param {boolean|'long'|'short'} [mode=false]
       *    - false to step in clockwise
       *    - true to step in trigonometric order
       *    - 'short' to use the shortest way
       *    - 'long' to use the longest way
       * @return {tinycolor[]}
       */
      hsv(steps, mode) {
        const substeps = computeSubsteps(this.stops, steps);
        let gradient = [];
        this.stops.forEach((stop2, i) => {
          if (stop2.colorLess) {
            stop2.color = interpolateHsv(this.stops[i - 1], this.stops[i + 1], 2, mode)[1];
          }
        });
        for (let i = 0, l2 = this.stops.length; i < l2 - 1; i++) {
          const hsv = interpolateHsv(this.stops[i], this.stops[i + 1], substeps[i], mode);
          gradient.splice(gradient.length, 0, ...hsv);
        }
        gradient.push(this.stops[this.stops.length - 1].color);
        return gradient;
      }
      /**
       * Generate CSS3 command (no prefix) for this gradient
       * @param {String} [mode=linear] - 'linear' or 'radial'
       * @param {String} [direction] - default is 'to right' or 'ellipse at center'
       * @return {String}
       */
      css(mode, direction) {
        mode = mode || "linear";
        direction = direction || (mode === "linear" ? "to right" : "ellipse at center");
        let css2 = mode + "-gradient(" + direction;
        this.stops.forEach(function(stop2) {
          css2 += ", " + (stop2.colorLess ? "" : stop2.color.toRgbString() + " ") + stop2.pos * 100 + "%";
        });
        css2 += ")";
        return css2;
      }
      /**
       * Returns the color at specific position with RGBa interpolation
       * @param {number} pos, between 0 and 1
       * @return {tinycolor}
       */
      rgbAt(pos2) {
        return computeAt(this.stops, pos2, "toRgb", RGBA_MAX);
      }
      /**
       * Returns the color at specific position with HSVa interpolation
       * @param {number} pos, between 0 and 1
       * @return {tinycolor}
       */
      hsvAt(pos2) {
        return computeAt(this.stops, pos2, "toHsv", HSVA_MAX);
      }
    };
    module2.exports = function(stops) {
      if (arguments.length === 1) {
        if (!Array.isArray(arguments[0])) {
          throw new Error('"stops" is not an array');
        }
        stops = arguments[0];
      } else {
        stops = Array.prototype.slice.call(arguments);
      }
      return new TinyGradient(stops);
    };
  }
});

// node_modules/gradient-string/index.js
var require_gradient_string = __commonJS({
  "node_modules/gradient-string/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var chalk7 = require_source();
    var tinygradient = require_tinygradient();
    var forbiddenChars = /\s/g;
    function InitGradient(...args) {
      const grad = tinygradient.apply(this, args);
      const ret = /* @__PURE__ */ __name((str2, opts) => applyGradient(str2 ? str2.toString() : "", grad, opts), "ret");
      ret.multiline = (str2, opts) => multilineGradient(str2 ? str2.toString() : "", grad, opts);
      return ret;
    }
    __name(InitGradient, "InitGradient");
    var getColors = /* @__PURE__ */ __name((gradient, options2, count) => options2.interpolation.toLowerCase() === "hsv" ? gradient.hsv(count, options2.hsvSpin.toLowerCase()) : gradient.rgb(count), "getColors");
    function applyGradient(str2, gradient, opts) {
      const options2 = validateOptions(opts);
      const colorsCount = Math.max(str2.replace(forbiddenChars, "").length, gradient.stops.length);
      const colors = getColors(gradient, options2, colorsCount);
      let result = "";
      for (const s2 of str2) {
        result += s2.match(forbiddenChars) ? s2 : chalk7.hex(colors.shift().toHex())(s2);
      }
      return result;
    }
    __name(applyGradient, "applyGradient");
    function multilineGradient(str2, gradient, opts) {
      const options2 = validateOptions(opts);
      const lines = str2.split("\n");
      const maxLength = Math.max.apply(null, lines.map((l2) => l2.length).concat([gradient.stops.length]));
      const colors = getColors(gradient, options2, maxLength);
      const results = [];
      for (const line of lines) {
        const lineColors = colors.slice(0);
        let lineResult = "";
        for (const l2 of line) {
          lineResult += chalk7.hex(lineColors.shift().toHex())(l2);
        }
        results.push(lineResult);
      }
      return results.join("\n");
    }
    __name(multilineGradient, "multilineGradient");
    function validateOptions(opts) {
      const options2 = { interpolation: "rgb", hsvSpin: "short", ...opts };
      if (opts !== void 0 && typeof opts !== "object") {
        throw new TypeError(`Expected \`options\` to be an \`object\`, got \`${typeof opts}\``);
      }
      if (typeof options2.interpolation !== "string") {
        throw new TypeError(`Expected \`options.interpolation\` to be a \`string\`, got \`${typeof options2.interpolation}\``);
      }
      if (options2.interpolation.toLowerCase() === "hsv" && typeof options2.hsvSpin !== "string") {
        throw new TypeError(`Expected \`options.hsvSpin\` to be a \`string\`, got \`${typeof options2.hsvSpin}\``);
      }
      return options2;
    }
    __name(validateOptions, "validateOptions");
    var aliases = {
      atlas: { colors: ["#feac5e", "#c779d0", "#4bc0c8"], options: {} },
      cristal: { colors: ["#bdfff3", "#4ac29a"], options: {} },
      teen: { colors: ["#77a1d3", "#79cbca", "#e684ae"], options: {} },
      mind: { colors: ["#473b7b", "#3584a7", "#30d2be"], options: {} },
      morning: { colors: ["#ff5f6d", "#ffc371"], options: { interpolation: "hsv" } },
      vice: { colors: ["#5ee7df", "#b490ca"], options: { interpolation: "hsv" } },
      passion: { colors: ["#f43b47", "#453a94"], options: {} },
      fruit: { colors: ["#ff4e50", "#f9d423"], options: {} },
      instagram: { colors: ["#833ab4", "#fd1d1d", "#fcb045"], options: {} },
      retro: { colors: ["#3f51b1", "#5a55ae", "#7b5fac", "#8f6aae", "#a86aa4", "#cc6b8e", "#f18271", "#f3a469", "#f7c978"], options: {} },
      summer: { colors: ["#fdbb2d", "#22c1c3"], options: {} },
      rainbow: { colors: ["#ff0000", "#ff0100"], options: { interpolation: "hsv", hsvSpin: "long" } },
      pastel: { colors: ["#74ebd5", "#74ecd5"], options: { interpolation: "hsv", hsvSpin: "long" } }
    };
    module2.exports = InitGradient;
    for (const a in aliases) {
      module2.exports[a] = (str2) => new InitGradient(aliases[a].colors)(str2, aliases[a].options);
      module2.exports[a].multiline = (str2) => new InitGradient(aliases[a].colors).multiline(str2, aliases[a].options);
    }
  }
});

// node_modules/dotenv/package.json
var require_package5 = __commonJS({
  "node_modules/dotenv/package.json"(exports2, module2) {
    module2.exports = {
      name: "dotenv",
      version: "17.1.0",
      description: "Loads environment variables from .env file",
      main: "lib/main.js",
      types: "lib/main.d.ts",
      exports: {
        ".": {
          types: "./lib/main.d.ts",
          require: "./lib/main.js",
          default: "./lib/main.js"
        },
        "./config": "./config.js",
        "./config.js": "./config.js",
        "./lib/env-options": "./lib/env-options.js",
        "./lib/env-options.js": "./lib/env-options.js",
        "./lib/cli-options": "./lib/cli-options.js",
        "./lib/cli-options.js": "./lib/cli-options.js",
        "./package.json": "./package.json"
      },
      scripts: {
        "dts-check": "tsc --project tests/types/tsconfig.json",
        lint: "standard",
        pretest: "npm run lint && npm run dts-check",
        test: "tap run --allow-empty-coverage --disable-coverage --timeout=60000",
        "test:coverage": "tap run --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",
        prerelease: "npm test",
        release: "standard-version"
      },
      repository: {
        type: "git",
        url: "git://github.com/motdotla/dotenv.git"
      },
      homepage: "https://github.com/motdotla/dotenv#readme",
      funding: "https://dotenvx.com",
      keywords: [
        "dotenv",
        "env",
        ".env",
        "environment",
        "variables",
        "config",
        "settings"
      ],
      readmeFilename: "README.md",
      license: "BSD-2-Clause",
      devDependencies: {
        "@types/node": "^18.11.3",
        decache: "^4.6.2",
        sinon: "^14.0.1",
        standard: "^17.0.0",
        "standard-version": "^9.5.0",
        tap: "^19.2.0",
        typescript: "^4.8.4"
      },
      engines: {
        node: ">=12"
      },
      browser: {
        fs: false
      }
    };
  }
});

// node_modules/dotenv/lib/main.js
var require_main = __commonJS({
  "node_modules/dotenv/lib/main.js"(exports2, module2) {
    init_esbuild_shims();
    var fs95 = __require("fs");
    var path108 = __require("path");
    var os43 = __require("os");
    var crypto18 = __require("crypto");
    var packageJson4 = require_package5();
    var version2 = packageJson4.version;
    var TIPS = [
      "\u{1F510} encrypt with dotenvx: https://dotenvx.com",
      "\u{1F510} prevent committing .env to code: https://dotenvx.com/precommit",
      "\u{1F510} prevent building .env in docker: https://dotenvx.com/prebuild",
      "\u{1F6E0}\uFE0F  run anywhere with `dotenvx run -- yourcommand`",
      "\u2699\uFE0F  specify custom .env file path with { path: '/custom/path/.env' }",
      "\u2699\uFE0F  enable debug logging with { debug: true }",
      "\u2699\uFE0F  override existing env vars with { override: true }",
      "\u2699\uFE0F  suppress all logs with { quiet: true }",
      "\u2699\uFE0F  write to custom object with { processEnv: myObject }",
      "\u2699\uFE0F  load multiple .env files with { path: ['.env.local', '.env'] }"
    ];
    function _getRandomTip() {
      return TIPS[Math.floor(Math.random() * TIPS.length)];
    }
    __name(_getRandomTip, "_getRandomTip");
    function supportsAnsi() {
      return process.stdout.isTTY;
    }
    __name(supportsAnsi, "supportsAnsi");
    function dim(text) {
      return supportsAnsi() ? `\x1B[2m${text}\x1B[0m` : text;
    }
    __name(dim, "dim");
    var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
    function parse12(src) {
      const obj = {};
      let lines = src.toString();
      lines = lines.replace(/\r\n?/mg, "\n");
      let match2;
      while ((match2 = LINE.exec(lines)) != null) {
        const key = match2[1];
        let value = match2[2] || "";
        value = value.trim();
        const maybeQuote = value[0];
        value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
        if (maybeQuote === '"') {
          value = value.replace(/\\n/g, "\n");
          value = value.replace(/\\r/g, "\r");
        }
        obj[key] = value;
      }
      return obj;
    }
    __name(parse12, "parse");
    function _parseVault(options2) {
      options2 = options2 || {};
      const vaultPath = _vaultPath(options2);
      options2.path = vaultPath;
      const result = DotenvModule.configDotenv(options2);
      if (!result.parsed) {
        const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
        err.code = "MISSING_DATA";
        throw err;
      }
      const keys = _dotenvKey(options2).split(",");
      const length = keys.length;
      let decrypted;
      for (let i = 0; i < length; i++) {
        try {
          const key = keys[i].trim();
          const attrs = _instructions(result, key);
          decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
          break;
        } catch (error) {
          if (i + 1 >= length) {
            throw error;
          }
        }
      }
      return DotenvModule.parse(decrypted);
    }
    __name(_parseVault, "_parseVault");
    function _warn(message) {
      console.error(`[dotenv@${version2}][WARN] ${message}`);
    }
    __name(_warn, "_warn");
    function _debug(message) {
      console.log(`[dotenv@${version2}][DEBUG] ${message}`);
    }
    __name(_debug, "_debug");
    function _log(message) {
      console.log(`[dotenv@${version2}] ${message}`);
    }
    __name(_log, "_log");
    function _dotenvKey(options2) {
      if (options2 && options2.DOTENV_KEY && options2.DOTENV_KEY.length > 0) {
        return options2.DOTENV_KEY;
      }
      if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
        return process.env.DOTENV_KEY;
      }
      return "";
    }
    __name(_dotenvKey, "_dotenvKey");
    function _instructions(result, dotenvKey) {
      let uri;
      try {
        uri = new URL(dotenvKey);
      } catch (error) {
        if (error.code === "ERR_INVALID_URL") {
          const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
          err.code = "INVALID_DOTENV_KEY";
          throw err;
        }
        throw error;
      }
      const key = uri.password;
      if (!key) {
        const err = new Error("INVALID_DOTENV_KEY: Missing key part");
        err.code = "INVALID_DOTENV_KEY";
        throw err;
      }
      const environment = uri.searchParams.get("environment");
      if (!environment) {
        const err = new Error("INVALID_DOTENV_KEY: Missing environment part");
        err.code = "INVALID_DOTENV_KEY";
        throw err;
      }
      const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
      const ciphertext = result.parsed[environmentKey];
      if (!ciphertext) {
        const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
        err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
        throw err;
      }
      return { ciphertext, key };
    }
    __name(_instructions, "_instructions");
    function _vaultPath(options2) {
      let possibleVaultPath = null;
      if (options2 && options2.path && options2.path.length > 0) {
        if (Array.isArray(options2.path)) {
          for (const filepath of options2.path) {
            if (fs95.existsSync(filepath)) {
              possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
            }
          }
        } else {
          possibleVaultPath = options2.path.endsWith(".vault") ? options2.path : `${options2.path}.vault`;
        }
      } else {
        possibleVaultPath = path108.resolve(process.cwd(), ".env.vault");
      }
      if (fs95.existsSync(possibleVaultPath)) {
        return possibleVaultPath;
      }
      return null;
    }
    __name(_vaultPath, "_vaultPath");
    function _resolveHome(envPath) {
      return envPath[0] === "~" ? path108.join(os43.homedir(), envPath.slice(1)) : envPath;
    }
    __name(_resolveHome, "_resolveHome");
    function _configVault(options2) {
      const debug2 = Boolean(options2 && options2.debug);
      const quiet = Boolean(options2 && options2.quiet);
      if (debug2 || !quiet) {
        _log("Loading env from encrypted .env.vault");
      }
      const parsed = DotenvModule._parseVault(options2);
      let processEnv = process.env;
      if (options2 && options2.processEnv != null) {
        processEnv = options2.processEnv;
      }
      DotenvModule.populate(processEnv, parsed, options2);
      return { parsed };
    }
    __name(_configVault, "_configVault");
    function configDotenv(options2) {
      const dotenvPath = path108.resolve(process.cwd(), ".env");
      let encoding = "utf8";
      const debug2 = Boolean(options2 && options2.debug);
      const quiet = Boolean(options2 && options2.quiet);
      if (options2 && options2.encoding) {
        encoding = options2.encoding;
      } else {
        if (debug2) {
          _debug("No encoding is specified. UTF-8 is used by default");
        }
      }
      let optionPaths = [dotenvPath];
      if (options2 && options2.path) {
        if (!Array.isArray(options2.path)) {
          optionPaths = [_resolveHome(options2.path)];
        } else {
          optionPaths = [];
          for (const filepath of options2.path) {
            optionPaths.push(_resolveHome(filepath));
          }
        }
      }
      let lastError;
      const parsedAll = {};
      for (const path109 of optionPaths) {
        try {
          const parsed = DotenvModule.parse(fs95.readFileSync(path109, { encoding }));
          DotenvModule.populate(parsedAll, parsed, options2);
        } catch (e2) {
          if (debug2) {
            _debug(`Failed to load ${path109} ${e2.message}`);
          }
          lastError = e2;
        }
      }
      let processEnv = process.env;
      if (options2 && options2.processEnv != null) {
        processEnv = options2.processEnv;
      }
      const populated = DotenvModule.populate(processEnv, parsedAll, options2);
      if (debug2 || !quiet) {
        const keysCount = Object.keys(populated).length;
        const shortPaths = [];
        for (const filePath of optionPaths) {
          try {
            const relative10 = path108.relative(process.cwd(), filePath);
            shortPaths.push(relative10);
          } catch (e2) {
            if (debug2) {
              _debug(`Failed to load ${filePath} ${e2.message}`);
            }
            lastError = e2;
          }
        }
        _log(`injecting env (${keysCount}) from ${shortPaths.join(",")} ${dim(`(tip: ${_getRandomTip()})`)}`);
      }
      if (lastError) {
        return { parsed: parsedAll, error: lastError };
      } else {
        return { parsed: parsedAll };
      }
    }
    __name(configDotenv, "configDotenv");
    function config(options2) {
      if (_dotenvKey(options2).length === 0) {
        return DotenvModule.configDotenv(options2);
      }
      const vaultPath = _vaultPath(options2);
      if (!vaultPath) {
        _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
        return DotenvModule.configDotenv(options2);
      }
      return DotenvModule._configVault(options2);
    }
    __name(config, "config");
    function decrypt(encrypted, keyStr) {
      const key = Buffer.from(keyStr.slice(-64), "hex");
      let ciphertext = Buffer.from(encrypted, "base64");
      const nonce = ciphertext.subarray(0, 12);
      const authTag = ciphertext.subarray(-16);
      ciphertext = ciphertext.subarray(12, -16);
      try {
        const aesgcm = crypto18.createDecipheriv("aes-256-gcm", key, nonce);
        aesgcm.setAuthTag(authTag);
        return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
      } catch (error) {
        const isRange = error instanceof RangeError;
        const invalidKeyLength = error.message === "Invalid key length";
        const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
        if (isRange || invalidKeyLength) {
          const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
          err.code = "INVALID_DOTENV_KEY";
          throw err;
        } else if (decryptionFailed) {
          const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
          err.code = "DECRYPTION_FAILED";
          throw err;
        } else {
          throw error;
        }
      }
    }
    __name(decrypt, "decrypt");
    function populate(processEnv, parsed, options2 = {}) {
      const debug2 = Boolean(options2 && options2.debug);
      const override = Boolean(options2 && options2.override);
      const populated = {};
      if (typeof parsed !== "object") {
        const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
        err.code = "OBJECT_REQUIRED";
        throw err;
      }
      for (const key of Object.keys(parsed)) {
        if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
          if (override === true) {
            processEnv[key] = parsed[key];
            populated[key] = parsed[key];
          }
          if (debug2) {
            if (override === true) {
              _debug(`"${key}" is already defined and WAS overwritten`);
            } else {
              _debug(`"${key}" is already defined and was NOT overwritten`);
            }
          }
        } else {
          processEnv[key] = parsed[key];
          populated[key] = parsed[key];
        }
      }
      return populated;
    }
    __name(populate, "populate");
    var DotenvModule = {
      configDotenv,
      _configVault,
      _parseVault,
      config,
      decrypt,
      parse: parse12,
      populate
    };
    module2.exports.configDotenv = DotenvModule.configDotenv;
    module2.exports._configVault = DotenvModule._configVault;
    module2.exports._parseVault = DotenvModule._parseVault;
    module2.exports.config = DotenvModule.config;
    module2.exports.decrypt = DotenvModule.decrypt;
    module2.exports.parse = DotenvModule.parse;
    module2.exports.populate = DotenvModule.populate;
    module2.exports = DotenvModule;
  }
});

// node_modules/esprima/dist/esprima.js
var require_esprima = __commonJS({
  "node_modules/esprima/dist/esprima.js"(exports2, module2) {
    init_esbuild_shims();
    (/* @__PURE__ */ __name(function webpackUniversalModuleDefinition(root, factory) {
      if (typeof exports2 === "object" && typeof module2 === "object")
        module2.exports = factory();
      else if (typeof define === "function" && define.amd)
        define([], factory);
      else if (typeof exports2 === "object")
        exports2["esprima"] = factory();
      else
        root["esprima"] = factory();
    }, "webpackUniversalModuleDefinition"))(exports2, function() {
      return (
        /******/
        function(modules) {
          var installedModules = {};
          function __webpack_require__(moduleId) {
            if (installedModules[moduleId])
              return installedModules[moduleId].exports;
            var module3 = installedModules[moduleId] = {
              /******/
              exports: {},
              /******/
              id: moduleId,
              /******/
              loaded: false
              /******/
            };
            modules[moduleId].call(module3.exports, module3, module3.exports, __webpack_require__);
            module3.loaded = true;
            return module3.exports;
          }
          __name(__webpack_require__, "__webpack_require__");
          __webpack_require__.m = modules;
          __webpack_require__.c = installedModules;
          __webpack_require__.p = "";
          return __webpack_require__(0);
        }([
          /* 0 */
          /***/
          function(module3, exports3, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var comment_handler_1 = __webpack_require__(1);
            var jsx_parser_1 = __webpack_require__(3);
            var parser_1 = __webpack_require__(8);
            var tokenizer_1 = __webpack_require__(15);
            function parse12(code2, options2, delegate) {
              var commentHandler = null;
              var proxyDelegate = /* @__PURE__ */ __name(function(node, metadata) {
                if (delegate) {
                  delegate(node, metadata);
                }
                if (commentHandler) {
                  commentHandler.visit(node, metadata);
                }
              }, "proxyDelegate");
              var parserDelegate = typeof delegate === "function" ? proxyDelegate : null;
              var collectComment = false;
              if (options2) {
                collectComment = typeof options2.comment === "boolean" && options2.comment;
                var attachComment = typeof options2.attachComment === "boolean" && options2.attachComment;
                if (collectComment || attachComment) {
                  commentHandler = new comment_handler_1.CommentHandler();
                  commentHandler.attach = attachComment;
                  options2.comment = true;
                  parserDelegate = proxyDelegate;
                }
              }
              var isModule = false;
              if (options2 && typeof options2.sourceType === "string") {
                isModule = options2.sourceType === "module";
              }
              var parser6;
              if (options2 && typeof options2.jsx === "boolean" && options2.jsx) {
                parser6 = new jsx_parser_1.JSXParser(code2, options2, parserDelegate);
              } else {
                parser6 = new parser_1.Parser(code2, options2, parserDelegate);
              }
              var program = isModule ? parser6.parseModule() : parser6.parseScript();
              var ast = program;
              if (collectComment && commentHandler) {
                ast.comments = commentHandler.comments;
              }
              if (parser6.config.tokens) {
                ast.tokens = parser6.tokens;
              }
              if (parser6.config.tolerant) {
                ast.errors = parser6.errorHandler.errors;
              }
              return ast;
            }
            __name(parse12, "parse");
            exports3.parse = parse12;
            function parseModule(code2, options2, delegate) {
              var parsingOptions = options2 || {};
              parsingOptions.sourceType = "module";
              return parse12(code2, parsingOptions, delegate);
            }
            __name(parseModule, "parseModule");
            exports3.parseModule = parseModule;
            function parseScript(code2, options2, delegate) {
              var parsingOptions = options2 || {};
              parsingOptions.sourceType = "script";
              return parse12(code2, parsingOptions, delegate);
            }
            __name(parseScript, "parseScript");
            exports3.parseScript = parseScript;
            function tokenize4(code2, options2, delegate) {
              var tokenizer = new tokenizer_1.Tokenizer(code2, options2);
              var tokens;
              tokens = [];
              try {
                while (true) {
                  var token2 = tokenizer.getNextToken();
                  if (!token2) {
                    break;
                  }
                  if (delegate) {
                    token2 = delegate(token2);
                  }
                  tokens.push(token2);
                }
              } catch (e2) {
                tokenizer.errorHandler.tolerate(e2);
              }
              if (tokenizer.errorHandler.tolerant) {
                tokens.errors = tokenizer.errors();
              }
              return tokens;
            }
            __name(tokenize4, "tokenize");
            exports3.tokenize = tokenize4;
            var syntax_1 = __webpack_require__(2);
            exports3.Syntax = syntax_1.Syntax;
            exports3.version = "4.0.1";
          },
          /* 1 */
          /***/
          function(module3, exports3, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var syntax_1 = __webpack_require__(2);
            var CommentHandler = function() {
              function CommentHandler2() {
                this.attach = false;
                this.comments = [];
                this.stack = [];
                this.leading = [];
                this.trailing = [];
              }
              __name(CommentHandler2, "CommentHandler");
              CommentHandler2.prototype.insertInnerComments = function(node, metadata) {
                if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) {
                  var innerComments = [];
                  for (var i = this.leading.length - 1; i >= 0; --i) {
                    var entry = this.leading[i];
                    if (metadata.end.offset >= entry.start) {
                      innerComments.unshift(entry.comment);
                      this.leading.splice(i, 1);
                      this.trailing.splice(i, 1);
                    }
                  }
                  if (innerComments.length) {
                    node.innerComments = innerComments;
                  }
                }
              };
              CommentHandler2.prototype.findTrailingComments = function(metadata) {
                var trailingComments = [];
                if (this.trailing.length > 0) {
                  for (var i = this.trailing.length - 1; i >= 0; --i) {
                    var entry_1 = this.trailing[i];
                    if (entry_1.start >= metadata.end.offset) {
                      trailingComments.unshift(entry_1.comment);
                    }
                  }
                  this.trailing.length = 0;
                  return trailingComments;
                }
                var entry = this.stack[this.stack.length - 1];
                if (entry && entry.node.trailingComments) {
                  var firstComment = entry.node.trailingComments[0];
                  if (firstComment && firstComment.range[0] >= metadata.end.offset) {
                    trailingComments = entry.node.trailingComments;
                    delete entry.node.trailingComments;
                  }
                }
                return trailingComments;
              };
              CommentHandler2.prototype.findLeadingComments = function(metadata) {
                var leadingComments = [];
                var target;
                while (this.stack.length > 0) {
                  var entry = this.stack[this.stack.length - 1];
                  if (entry && entry.start >= metadata.start.offset) {
                    target = entry.node;
                    this.stack.pop();
                  } else {
                    break;
                  }
                }
                if (target) {
                  var count = target.leadingComments ? target.leadingComments.length : 0;
                  for (var i = count - 1; i >= 0; --i) {
                    var comment = target.leadingComments[i];
                    if (comment.range[1] <= metadata.start.offset) {
                      leadingComments.unshift(comment);
                      target.leadingComments.splice(i, 1);
                    }
                  }
                  if (target.leadingComments && target.leadingComments.length === 0) {
                    delete target.leadingComments;
                  }
                  return leadingComments;
                }
                for (var i = this.leading.length - 1; i >= 0; --i) {
                  var entry = this.leading[i];
                  if (entry.start <= metadata.start.offset) {
                    leadingComments.unshift(entry.comment);
                    this.leading.splice(i, 1);
                  }
                }
                return leadingComments;
              };
              CommentHandler2.prototype.visitNode = function(node, metadata) {
                if (node.type === syntax_1.Syntax.Program && node.body.length > 0) {
                  return;
                }
                this.insertInnerComments(node, metadata);
                var trailingComments = this.findTrailingComments(metadata);
                var leadingComments = this.findLeadingComments(metadata);
                if (leadingComments.length > 0) {
                  node.leadingComments = leadingComments;
                }
                if (trailingComments.length > 0) {
                  node.trailingComments = trailingComments;
                }
                this.stack.push({
                  node,
                  start: metadata.start.offset
                });
              };
              CommentHandler2.prototype.visitComment = function(node, metadata) {
                var type = node.type[0] === "L" ? "Line" : "Block";
                var comment = {
                  type,
                  value: node.value
                };
                if (node.range) {
                  comment.range = node.range;
                }
                if (node.loc) {
                  comment.loc = node.loc;
                }
                this.comments.push(comment);
                if (this.attach) {
                  var entry = {
                    comment: {
                      type,
                      value: node.value,
                      range: [metadata.start.offset, metadata.end.offset]
                    },
                    start: metadata.start.offset
                  };
                  if (node.loc) {
                    entry.comment.loc = node.loc;
                  }
                  node.type = type;
                  this.leading.push(entry);
                  this.trailing.push(entry);
                }
              };
              CommentHandler2.prototype.visit = function(node, metadata) {
                if (node.type === "LineComment") {
                  this.visitComment(node, metadata);
                } else if (node.type === "BlockComment") {
                  this.visitComment(node, metadata);
                } else if (this.attach) {
                  this.visitNode(node, metadata);
                }
              };
              return CommentHandler2;
            }();
            exports3.CommentHandler = CommentHandler;
          },
          /* 2 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            exports3.Syntax = {
              AssignmentExpression: "AssignmentExpression",
              AssignmentPattern: "AssignmentPattern",
              ArrayExpression: "ArrayExpression",
              ArrayPattern: "ArrayPattern",
              ArrowFunctionExpression: "ArrowFunctionExpression",
              AwaitExpression: "AwaitExpression",
              BlockStatement: "BlockStatement",
              BinaryExpression: "BinaryExpression",
              BreakStatement: "BreakStatement",
              CallExpression: "CallExpression",
              CatchClause: "CatchClause",
              ClassBody: "ClassBody",
              ClassDeclaration: "ClassDeclaration",
              ClassExpression: "ClassExpression",
              ConditionalExpression: "ConditionalExpression",
              ContinueStatement: "ContinueStatement",
              DoWhileStatement: "DoWhileStatement",
              DebuggerStatement: "DebuggerStatement",
              EmptyStatement: "EmptyStatement",
              ExportAllDeclaration: "ExportAllDeclaration",
              ExportDefaultDeclaration: "ExportDefaultDeclaration",
              ExportNamedDeclaration: "ExportNamedDeclaration",
              ExportSpecifier: "ExportSpecifier",
              ExpressionStatement: "ExpressionStatement",
              ForStatement: "ForStatement",
              ForOfStatement: "ForOfStatement",
              ForInStatement: "ForInStatement",
              FunctionDeclaration: "FunctionDeclaration",
              FunctionExpression: "FunctionExpression",
              Identifier: "Identifier",
              IfStatement: "IfStatement",
              ImportDeclaration: "ImportDeclaration",
              ImportDefaultSpecifier: "ImportDefaultSpecifier",
              ImportNamespaceSpecifier: "ImportNamespaceSpecifier",
              ImportSpecifier: "ImportSpecifier",
              Literal: "Literal",
              LabeledStatement: "LabeledStatement",
              LogicalExpression: "LogicalExpression",
              MemberExpression: "MemberExpression",
              MetaProperty: "MetaProperty",
              MethodDefinition: "MethodDefinition",
              NewExpression: "NewExpression",
              ObjectExpression: "ObjectExpression",
              ObjectPattern: "ObjectPattern",
              Program: "Program",
              Property: "Property",
              RestElement: "RestElement",
              ReturnStatement: "ReturnStatement",
              SequenceExpression: "SequenceExpression",
              SpreadElement: "SpreadElement",
              Super: "Super",
              SwitchCase: "SwitchCase",
              SwitchStatement: "SwitchStatement",
              TaggedTemplateExpression: "TaggedTemplateExpression",
              TemplateElement: "TemplateElement",
              TemplateLiteral: "TemplateLiteral",
              ThisExpression: "ThisExpression",
              ThrowStatement: "ThrowStatement",
              TryStatement: "TryStatement",
              UnaryExpression: "UnaryExpression",
              UpdateExpression: "UpdateExpression",
              VariableDeclaration: "VariableDeclaration",
              VariableDeclarator: "VariableDeclarator",
              WhileStatement: "WhileStatement",
              WithStatement: "WithStatement",
              YieldExpression: "YieldExpression"
            };
          },
          /* 3 */
          /***/
          function(module3, exports3, __webpack_require__) {
            "use strict";
            var __extends2 = this && this.__extends || function() {
              var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d, b) {
                d.__proto__ = b;
              } || function(d, b) {
                for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
              };
              return function(d, b) {
                extendStatics(d, b);
                function __() {
                  this.constructor = d;
                }
                __name(__, "__");
                d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
              };
            }();
            Object.defineProperty(exports3, "__esModule", { value: true });
            var character_1 = __webpack_require__(4);
            var JSXNode = __webpack_require__(5);
            var jsx_syntax_1 = __webpack_require__(6);
            var Node4 = __webpack_require__(7);
            var parser_1 = __webpack_require__(8);
            var token_1 = __webpack_require__(13);
            var xhtml_entities_1 = __webpack_require__(14);
            token_1.TokenName[
              100
              /* Identifier */
            ] = "JSXIdentifier";
            token_1.TokenName[
              101
              /* Text */
            ] = "JSXText";
            function getQualifiedElementName(elementName) {
              var qualifiedName;
              switch (elementName.type) {
                case jsx_syntax_1.JSXSyntax.JSXIdentifier:
                  var id = elementName;
                  qualifiedName = id.name;
                  break;
                case jsx_syntax_1.JSXSyntax.JSXNamespacedName:
                  var ns = elementName;
                  qualifiedName = getQualifiedElementName(ns.namespace) + ":" + getQualifiedElementName(ns.name);
                  break;
                case jsx_syntax_1.JSXSyntax.JSXMemberExpression:
                  var expr = elementName;
                  qualifiedName = getQualifiedElementName(expr.object) + "." + getQualifiedElementName(expr.property);
                  break;
                /* istanbul ignore next */
                default:
                  break;
              }
              return qualifiedName;
            }
            __name(getQualifiedElementName, "getQualifiedElementName");
            var JSXParser = function(_super) {
              __extends2(JSXParser2, _super);
              function JSXParser2(code2, options2, delegate) {
                return _super.call(this, code2, options2, delegate) || this;
              }
              __name(JSXParser2, "JSXParser");
              JSXParser2.prototype.parsePrimaryExpression = function() {
                return this.match("<") ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this);
              };
              JSXParser2.prototype.startJSX = function() {
                this.scanner.index = this.startMarker.index;
                this.scanner.lineNumber = this.startMarker.line;
                this.scanner.lineStart = this.startMarker.index - this.startMarker.column;
              };
              JSXParser2.prototype.finishJSX = function() {
                this.nextToken();
              };
              JSXParser2.prototype.reenterJSX = function() {
                this.startJSX();
                this.expectJSX("}");
                if (this.config.tokens) {
                  this.tokens.pop();
                }
              };
              JSXParser2.prototype.createJSXNode = function() {
                this.collectComments();
                return {
                  index: this.scanner.index,
                  line: this.scanner.lineNumber,
                  column: this.scanner.index - this.scanner.lineStart
                };
              };
              JSXParser2.prototype.createJSXChildNode = function() {
                return {
                  index: this.scanner.index,
                  line: this.scanner.lineNumber,
                  column: this.scanner.index - this.scanner.lineStart
                };
              };
              JSXParser2.prototype.scanXHTMLEntity = function(quote3) {
                var result = "&";
                var valid = true;
                var terminated = false;
                var numeric = false;
                var hex = false;
                while (!this.scanner.eof() && valid && !terminated) {
                  var ch = this.scanner.source[this.scanner.index];
                  if (ch === quote3) {
                    break;
                  }
                  terminated = ch === ";";
                  result += ch;
                  ++this.scanner.index;
                  if (!terminated) {
                    switch (result.length) {
                      case 2:
                        numeric = ch === "#";
                        break;
                      case 3:
                        if (numeric) {
                          hex = ch === "x";
                          valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0));
                          numeric = numeric && !hex;
                        }
                        break;
                      default:
                        valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0)));
                        valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0)));
                        break;
                    }
                  }
                }
                if (valid && terminated && result.length > 2) {
                  var str2 = result.substr(1, result.length - 2);
                  if (numeric && str2.length > 1) {
                    result = String.fromCharCode(parseInt(str2.substr(1), 10));
                  } else if (hex && str2.length > 2) {
                    result = String.fromCharCode(parseInt("0" + str2.substr(1), 16));
                  } else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str2]) {
                    result = xhtml_entities_1.XHTMLEntities[str2];
                  }
                }
                return result;
              };
              JSXParser2.prototype.lexJSX = function() {
                var cp2 = this.scanner.source.charCodeAt(this.scanner.index);
                if (cp2 === 60 || cp2 === 62 || cp2 === 47 || cp2 === 58 || cp2 === 61 || cp2 === 123 || cp2 === 125) {
                  var value = this.scanner.source[this.scanner.index++];
                  return {
                    type: 7,
                    value,
                    lineNumber: this.scanner.lineNumber,
                    lineStart: this.scanner.lineStart,
                    start: this.scanner.index - 1,
                    end: this.scanner.index
                  };
                }
                if (cp2 === 34 || cp2 === 39) {
                  var start = this.scanner.index;
                  var quote3 = this.scanner.source[this.scanner.index++];
                  var str2 = "";
                  while (!this.scanner.eof()) {
                    var ch = this.scanner.source[this.scanner.index++];
                    if (ch === quote3) {
                      break;
                    } else if (ch === "&") {
                      str2 += this.scanXHTMLEntity(quote3);
                    } else {
                      str2 += ch;
                    }
                  }
                  return {
                    type: 8,
                    value: str2,
                    lineNumber: this.scanner.lineNumber,
                    lineStart: this.scanner.lineStart,
                    start,
                    end: this.scanner.index
                  };
                }
                if (cp2 === 46) {
                  var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1);
                  var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2);
                  var value = n1 === 46 && n2 === 46 ? "..." : ".";
                  var start = this.scanner.index;
                  this.scanner.index += value.length;
                  return {
                    type: 7,
                    value,
                    lineNumber: this.scanner.lineNumber,
                    lineStart: this.scanner.lineStart,
                    start,
                    end: this.scanner.index
                  };
                }
                if (cp2 === 96) {
                  return {
                    type: 10,
                    value: "",
                    lineNumber: this.scanner.lineNumber,
                    lineStart: this.scanner.lineStart,
                    start: this.scanner.index,
                    end: this.scanner.index
                  };
                }
                if (character_1.Character.isIdentifierStart(cp2) && cp2 !== 92) {
                  var start = this.scanner.index;
                  ++this.scanner.index;
                  while (!this.scanner.eof()) {
                    var ch = this.scanner.source.charCodeAt(this.scanner.index);
                    if (character_1.Character.isIdentifierPart(ch) && ch !== 92) {
                      ++this.scanner.index;
                    } else if (ch === 45) {
                      ++this.scanner.index;
                    } else {
                      break;
                    }
                  }
                  var id = this.scanner.source.slice(start, this.scanner.index);
                  return {
                    type: 100,
                    value: id,
                    lineNumber: this.scanner.lineNumber,
                    lineStart: this.scanner.lineStart,
                    start,
                    end: this.scanner.index
                  };
                }
                return this.scanner.lex();
              };
              JSXParser2.prototype.nextJSXToken = function() {
                this.collectComments();
                this.startMarker.index = this.scanner.index;
                this.startMarker.line = this.scanner.lineNumber;
                this.startMarker.column = this.scanner.index - this.scanner.lineStart;
                var token2 = this.lexJSX();
                this.lastMarker.index = this.scanner.index;
                this.lastMarker.line = this.scanner.lineNumber;
                this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
                if (this.config.tokens) {
                  this.tokens.push(this.convertToken(token2));
                }
                return token2;
              };
              JSXParser2.prototype.nextJSXText = function() {
                this.startMarker.index = this.scanner.index;
                this.startMarker.line = this.scanner.lineNumber;
                this.startMarker.column = this.scanner.index - this.scanner.lineStart;
                var start = this.scanner.index;
                var text = "";
                while (!this.scanner.eof()) {
                  var ch = this.scanner.source[this.scanner.index];
                  if (ch === "{" || ch === "<") {
                    break;
                  }
                  ++this.scanner.index;
                  text += ch;
                  if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                    ++this.scanner.lineNumber;
                    if (ch === "\r" && this.scanner.source[this.scanner.index] === "\n") {
                      ++this.scanner.index;
                    }
                    this.scanner.lineStart = this.scanner.index;
                  }
                }
                this.lastMarker.index = this.scanner.index;
                this.lastMarker.line = this.scanner.lineNumber;
                this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
                var token2 = {
                  type: 101,
                  value: text,
                  lineNumber: this.scanner.lineNumber,
                  lineStart: this.scanner.lineStart,
                  start,
                  end: this.scanner.index
                };
                if (text.length > 0 && this.config.tokens) {
                  this.tokens.push(this.convertToken(token2));
                }
                return token2;
              };
              JSXParser2.prototype.peekJSXToken = function() {
                var state = this.scanner.saveState();
                this.scanner.scanComments();
                var next = this.lexJSX();
                this.scanner.restoreState(state);
                return next;
              };
              JSXParser2.prototype.expectJSX = function(value) {
                var token2 = this.nextJSXToken();
                if (token2.type !== 7 || token2.value !== value) {
                  this.throwUnexpectedToken(token2);
                }
              };
              JSXParser2.prototype.matchJSX = function(value) {
                var next = this.peekJSXToken();
                return next.type === 7 && next.value === value;
              };
              JSXParser2.prototype.parseJSXIdentifier = function() {
                var node = this.createJSXNode();
                var token2 = this.nextJSXToken();
                if (token2.type !== 100) {
                  this.throwUnexpectedToken(token2);
                }
                return this.finalize(node, new JSXNode.JSXIdentifier(token2.value));
              };
              JSXParser2.prototype.parseJSXElementName = function() {
                var node = this.createJSXNode();
                var elementName = this.parseJSXIdentifier();
                if (this.matchJSX(":")) {
                  var namespace = elementName;
                  this.expectJSX(":");
                  var name_1 = this.parseJSXIdentifier();
                  elementName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_1));
                } else if (this.matchJSX(".")) {
                  while (this.matchJSX(".")) {
                    var object = elementName;
                    this.expectJSX(".");
                    var property = this.parseJSXIdentifier();
                    elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object, property));
                  }
                }
                return elementName;
              };
              JSXParser2.prototype.parseJSXAttributeName = function() {
                var node = this.createJSXNode();
                var attributeName;
                var identifier2 = this.parseJSXIdentifier();
                if (this.matchJSX(":")) {
                  var namespace = identifier2;
                  this.expectJSX(":");
                  var name_2 = this.parseJSXIdentifier();
                  attributeName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_2));
                } else {
                  attributeName = identifier2;
                }
                return attributeName;
              };
              JSXParser2.prototype.parseJSXStringLiteralAttribute = function() {
                var node = this.createJSXNode();
                var token2 = this.nextJSXToken();
                if (token2.type !== 8) {
                  this.throwUnexpectedToken(token2);
                }
                var raw2 = this.getTokenRaw(token2);
                return this.finalize(node, new Node4.Literal(token2.value, raw2));
              };
              JSXParser2.prototype.parseJSXExpressionAttribute = function() {
                var node = this.createJSXNode();
                this.expectJSX("{");
                this.finishJSX();
                if (this.match("}")) {
                  this.tolerateError("JSX attributes must only be assigned a non-empty expression");
                }
                var expression = this.parseAssignmentExpression();
                this.reenterJSX();
                return this.finalize(node, new JSXNode.JSXExpressionContainer(expression));
              };
              JSXParser2.prototype.parseJSXAttributeValue = function() {
                return this.matchJSX("{") ? this.parseJSXExpressionAttribute() : this.matchJSX("<") ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute();
              };
              JSXParser2.prototype.parseJSXNameValueAttribute = function() {
                var node = this.createJSXNode();
                var name3 = this.parseJSXAttributeName();
                var value = null;
                if (this.matchJSX("=")) {
                  this.expectJSX("=");
                  value = this.parseJSXAttributeValue();
                }
                return this.finalize(node, new JSXNode.JSXAttribute(name3, value));
              };
              JSXParser2.prototype.parseJSXSpreadAttribute = function() {
                var node = this.createJSXNode();
                this.expectJSX("{");
                this.expectJSX("...");
                this.finishJSX();
                var argument = this.parseAssignmentExpression();
                this.reenterJSX();
                return this.finalize(node, new JSXNode.JSXSpreadAttribute(argument));
              };
              JSXParser2.prototype.parseJSXAttributes = function() {
                var attributes = [];
                while (!this.matchJSX("/") && !this.matchJSX(">")) {
                  var attribute = this.matchJSX("{") ? this.parseJSXSpreadAttribute() : this.parseJSXNameValueAttribute();
                  attributes.push(attribute);
                }
                return attributes;
              };
              JSXParser2.prototype.parseJSXOpeningElement = function() {
                var node = this.createJSXNode();
                this.expectJSX("<");
                var name3 = this.parseJSXElementName();
                var attributes = this.parseJSXAttributes();
                var selfClosing = this.matchJSX("/");
                if (selfClosing) {
                  this.expectJSX("/");
                }
                this.expectJSX(">");
                return this.finalize(node, new JSXNode.JSXOpeningElement(name3, selfClosing, attributes));
              };
              JSXParser2.prototype.parseJSXBoundaryElement = function() {
                var node = this.createJSXNode();
                this.expectJSX("<");
                if (this.matchJSX("/")) {
                  this.expectJSX("/");
                  var name_3 = this.parseJSXElementName();
                  this.expectJSX(">");
                  return this.finalize(node, new JSXNode.JSXClosingElement(name_3));
                }
                var name3 = this.parseJSXElementName();
                var attributes = this.parseJSXAttributes();
                var selfClosing = this.matchJSX("/");
                if (selfClosing) {
                  this.expectJSX("/");
                }
                this.expectJSX(">");
                return this.finalize(node, new JSXNode.JSXOpeningElement(name3, selfClosing, attributes));
              };
              JSXParser2.prototype.parseJSXEmptyExpression = function() {
                var node = this.createJSXChildNode();
                this.collectComments();
                this.lastMarker.index = this.scanner.index;
                this.lastMarker.line = this.scanner.lineNumber;
                this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
                return this.finalize(node, new JSXNode.JSXEmptyExpression());
              };
              JSXParser2.prototype.parseJSXExpressionContainer = function() {
                var node = this.createJSXNode();
                this.expectJSX("{");
                var expression;
                if (this.matchJSX("}")) {
                  expression = this.parseJSXEmptyExpression();
                  this.expectJSX("}");
                } else {
                  this.finishJSX();
                  expression = this.parseAssignmentExpression();
                  this.reenterJSX();
                }
                return this.finalize(node, new JSXNode.JSXExpressionContainer(expression));
              };
              JSXParser2.prototype.parseJSXChildren = function() {
                var children = [];
                while (!this.scanner.eof()) {
                  var node = this.createJSXChildNode();
                  var token2 = this.nextJSXText();
                  if (token2.start < token2.end) {
                    var raw2 = this.getTokenRaw(token2);
                    var child = this.finalize(node, new JSXNode.JSXText(token2.value, raw2));
                    children.push(child);
                  }
                  if (this.scanner.source[this.scanner.index] === "{") {
                    var container = this.parseJSXExpressionContainer();
                    children.push(container);
                  } else {
                    break;
                  }
                }
                return children;
              };
              JSXParser2.prototype.parseComplexJSXElement = function(el) {
                var stack = [];
                while (!this.scanner.eof()) {
                  el.children = el.children.concat(this.parseJSXChildren());
                  var node = this.createJSXChildNode();
                  var element = this.parseJSXBoundaryElement();
                  if (element.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) {
                    var opening = element;
                    if (opening.selfClosing) {
                      var child = this.finalize(node, new JSXNode.JSXElement(opening, [], null));
                      el.children.push(child);
                    } else {
                      stack.push(el);
                      el = { node, opening, closing: null, children: [] };
                    }
                  }
                  if (element.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) {
                    el.closing = element;
                    var open_1 = getQualifiedElementName(el.opening.name);
                    var close_1 = getQualifiedElementName(el.closing.name);
                    if (open_1 !== close_1) {
                      this.tolerateError("Expected corresponding JSX closing tag for %0", open_1);
                    }
                    if (stack.length > 0) {
                      var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing));
                      el = stack[stack.length - 1];
                      el.children.push(child);
                      stack.pop();
                    } else {
                      break;
                    }
                  }
                }
                return el;
              };
              JSXParser2.prototype.parseJSXElement = function() {
                var node = this.createJSXNode();
                var opening = this.parseJSXOpeningElement();
                var children = [];
                var closing = null;
                if (!opening.selfClosing) {
                  var el = this.parseComplexJSXElement({ node, opening, closing, children });
                  children = el.children;
                  closing = el.closing;
                }
                return this.finalize(node, new JSXNode.JSXElement(opening, children, closing));
              };
              JSXParser2.prototype.parseJSXRoot = function() {
                if (this.config.tokens) {
                  this.tokens.pop();
                }
                this.startJSX();
                var element = this.parseJSXElement();
                this.finishJSX();
                return element;
              };
              JSXParser2.prototype.isStartOfExpression = function() {
                return _super.prototype.isStartOfExpression.call(this) || this.match("<");
              };
              return JSXParser2;
            }(parser_1.Parser);
            exports3.JSXParser = JSXParser;
          },
          /* 4 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var Regex = {
              // Unicode v8.0.0 NonAsciiIdentifierStart:
              NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,
              // Unicode v8.0.0 NonAsciiIdentifierPart:
              NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
            };
            exports3.Character = {
              /* tslint:disable:no-bitwise */
              fromCodePoint: /* @__PURE__ */ __name(function(cp2) {
                return cp2 < 65536 ? String.fromCharCode(cp2) : String.fromCharCode(55296 + (cp2 - 65536 >> 10)) + String.fromCharCode(56320 + (cp2 - 65536 & 1023));
              }, "fromCodePoint"),
              // https://tc39.github.io/ecma262/#sec-white-space
              isWhiteSpace: /* @__PURE__ */ __name(function(cp2) {
                return cp2 === 32 || cp2 === 9 || cp2 === 11 || cp2 === 12 || cp2 === 160 || cp2 >= 5760 && [5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8239, 8287, 12288, 65279].indexOf(cp2) >= 0;
              }, "isWhiteSpace"),
              // https://tc39.github.io/ecma262/#sec-line-terminators
              isLineTerminator: /* @__PURE__ */ __name(function(cp2) {
                return cp2 === 10 || cp2 === 13 || cp2 === 8232 || cp2 === 8233;
              }, "isLineTerminator"),
              // https://tc39.github.io/ecma262/#sec-names-and-keywords
              isIdentifierStart: /* @__PURE__ */ __name(function(cp2) {
                return cp2 === 36 || cp2 === 95 || cp2 >= 65 && cp2 <= 90 || cp2 >= 97 && cp2 <= 122 || cp2 === 92 || cp2 >= 128 && Regex.NonAsciiIdentifierStart.test(exports3.Character.fromCodePoint(cp2));
              }, "isIdentifierStart"),
              isIdentifierPart: /* @__PURE__ */ __name(function(cp2) {
                return cp2 === 36 || cp2 === 95 || cp2 >= 65 && cp2 <= 90 || cp2 >= 97 && cp2 <= 122 || cp2 >= 48 && cp2 <= 57 || cp2 === 92 || cp2 >= 128 && Regex.NonAsciiIdentifierPart.test(exports3.Character.fromCodePoint(cp2));
              }, "isIdentifierPart"),
              // https://tc39.github.io/ecma262/#sec-literals-numeric-literals
              isDecimalDigit: /* @__PURE__ */ __name(function(cp2) {
                return cp2 >= 48 && cp2 <= 57;
              }, "isDecimalDigit"),
              isHexDigit: /* @__PURE__ */ __name(function(cp2) {
                return cp2 >= 48 && cp2 <= 57 || cp2 >= 65 && cp2 <= 70 || cp2 >= 97 && cp2 <= 102;
              }, "isHexDigit"),
              isOctalDigit: /* @__PURE__ */ __name(function(cp2) {
                return cp2 >= 48 && cp2 <= 55;
              }, "isOctalDigit")
            };
          },
          /* 5 */
          /***/
          function(module3, exports3, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var jsx_syntax_1 = __webpack_require__(6);
            var JSXClosingElement = /* @__PURE__ */ function() {
              function JSXClosingElement2(name3) {
                this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement;
                this.name = name3;
              }
              __name(JSXClosingElement2, "JSXClosingElement");
              return JSXClosingElement2;
            }();
            exports3.JSXClosingElement = JSXClosingElement;
            var JSXElement = /* @__PURE__ */ function() {
              function JSXElement2(openingElement, children, closingElement) {
                this.type = jsx_syntax_1.JSXSyntax.JSXElement;
                this.openingElement = openingElement;
                this.children = children;
                this.closingElement = closingElement;
              }
              __name(JSXElement2, "JSXElement");
              return JSXElement2;
            }();
            exports3.JSXElement = JSXElement;
            var JSXEmptyExpression = /* @__PURE__ */ function() {
              function JSXEmptyExpression2() {
                this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression;
              }
              __name(JSXEmptyExpression2, "JSXEmptyExpression");
              return JSXEmptyExpression2;
            }();
            exports3.JSXEmptyExpression = JSXEmptyExpression;
            var JSXExpressionContainer = /* @__PURE__ */ function() {
              function JSXExpressionContainer2(expression) {
                this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer;
                this.expression = expression;
              }
              __name(JSXExpressionContainer2, "JSXExpressionContainer");
              return JSXExpressionContainer2;
            }();
            exports3.JSXExpressionContainer = JSXExpressionContainer;
            var JSXIdentifier = /* @__PURE__ */ function() {
              function JSXIdentifier2(name3) {
                this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier;
                this.name = name3;
              }
              __name(JSXIdentifier2, "JSXIdentifier");
              return JSXIdentifier2;
            }();
            exports3.JSXIdentifier = JSXIdentifier;
            var JSXMemberExpression = /* @__PURE__ */ function() {
              function JSXMemberExpression2(object, property) {
                this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression;
                this.object = object;
                this.property = property;
              }
              __name(JSXMemberExpression2, "JSXMemberExpression");
              return JSXMemberExpression2;
            }();
            exports3.JSXMemberExpression = JSXMemberExpression;
            var JSXAttribute = /* @__PURE__ */ function() {
              function JSXAttribute2(name3, value) {
                this.type = jsx_syntax_1.JSXSyntax.JSXAttribute;
                this.name = name3;
                this.value = value;
              }
              __name(JSXAttribute2, "JSXAttribute");
              return JSXAttribute2;
            }();
            exports3.JSXAttribute = JSXAttribute;
            var JSXNamespacedName = /* @__PURE__ */ function() {
              function JSXNamespacedName2(namespace, name3) {
                this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName;
                this.namespace = namespace;
                this.name = name3;
              }
              __name(JSXNamespacedName2, "JSXNamespacedName");
              return JSXNamespacedName2;
            }();
            exports3.JSXNamespacedName = JSXNamespacedName;
            var JSXOpeningElement = /* @__PURE__ */ function() {
              function JSXOpeningElement2(name3, selfClosing, attributes) {
                this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement;
                this.name = name3;
                this.selfClosing = selfClosing;
                this.attributes = attributes;
              }
              __name(JSXOpeningElement2, "JSXOpeningElement");
              return JSXOpeningElement2;
            }();
            exports3.JSXOpeningElement = JSXOpeningElement;
            var JSXSpreadAttribute = /* @__PURE__ */ function() {
              function JSXSpreadAttribute2(argument) {
                this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute;
                this.argument = argument;
              }
              __name(JSXSpreadAttribute2, "JSXSpreadAttribute");
              return JSXSpreadAttribute2;
            }();
            exports3.JSXSpreadAttribute = JSXSpreadAttribute;
            var JSXText = /* @__PURE__ */ function() {
              function JSXText2(value, raw2) {
                this.type = jsx_syntax_1.JSXSyntax.JSXText;
                this.value = value;
                this.raw = raw2;
              }
              __name(JSXText2, "JSXText");
              return JSXText2;
            }();
            exports3.JSXText = JSXText;
          },
          /* 6 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            exports3.JSXSyntax = {
              JSXAttribute: "JSXAttribute",
              JSXClosingElement: "JSXClosingElement",
              JSXElement: "JSXElement",
              JSXEmptyExpression: "JSXEmptyExpression",
              JSXExpressionContainer: "JSXExpressionContainer",
              JSXIdentifier: "JSXIdentifier",
              JSXMemberExpression: "JSXMemberExpression",
              JSXNamespacedName: "JSXNamespacedName",
              JSXOpeningElement: "JSXOpeningElement",
              JSXSpreadAttribute: "JSXSpreadAttribute",
              JSXText: "JSXText"
            };
          },
          /* 7 */
          /***/
          function(module3, exports3, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var syntax_1 = __webpack_require__(2);
            var ArrayExpression = /* @__PURE__ */ function() {
              function ArrayExpression2(elements) {
                this.type = syntax_1.Syntax.ArrayExpression;
                this.elements = elements;
              }
              __name(ArrayExpression2, "ArrayExpression");
              return ArrayExpression2;
            }();
            exports3.ArrayExpression = ArrayExpression;
            var ArrayPattern = /* @__PURE__ */ function() {
              function ArrayPattern2(elements) {
                this.type = syntax_1.Syntax.ArrayPattern;
                this.elements = elements;
              }
              __name(ArrayPattern2, "ArrayPattern");
              return ArrayPattern2;
            }();
            exports3.ArrayPattern = ArrayPattern;
            var ArrowFunctionExpression = /* @__PURE__ */ function() {
              function ArrowFunctionExpression2(params, body, expression) {
                this.type = syntax_1.Syntax.ArrowFunctionExpression;
                this.id = null;
                this.params = params;
                this.body = body;
                this.generator = false;
                this.expression = expression;
                this.async = false;
              }
              __name(ArrowFunctionExpression2, "ArrowFunctionExpression");
              return ArrowFunctionExpression2;
            }();
            exports3.ArrowFunctionExpression = ArrowFunctionExpression;
            var AssignmentExpression = /* @__PURE__ */ function() {
              function AssignmentExpression2(operator2, left3, right3) {
                this.type = syntax_1.Syntax.AssignmentExpression;
                this.operator = operator2;
                this.left = left3;
                this.right = right3;
              }
              __name(AssignmentExpression2, "AssignmentExpression");
              return AssignmentExpression2;
            }();
            exports3.AssignmentExpression = AssignmentExpression;
            var AssignmentPattern = /* @__PURE__ */ function() {
              function AssignmentPattern2(left3, right3) {
                this.type = syntax_1.Syntax.AssignmentPattern;
                this.left = left3;
                this.right = right3;
              }
              __name(AssignmentPattern2, "AssignmentPattern");
              return AssignmentPattern2;
            }();
            exports3.AssignmentPattern = AssignmentPattern;
            var AsyncArrowFunctionExpression = /* @__PURE__ */ function() {
              function AsyncArrowFunctionExpression2(params, body, expression) {
                this.type = syntax_1.Syntax.ArrowFunctionExpression;
                this.id = null;
                this.params = params;
                this.body = body;
                this.generator = false;
                this.expression = expression;
                this.async = true;
              }
              __name(AsyncArrowFunctionExpression2, "AsyncArrowFunctionExpression");
              return AsyncArrowFunctionExpression2;
            }();
            exports3.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression;
            var AsyncFunctionDeclaration = /* @__PURE__ */ function() {
              function AsyncFunctionDeclaration2(id, params, body) {
                this.type = syntax_1.Syntax.FunctionDeclaration;
                this.id = id;
                this.params = params;
                this.body = body;
                this.generator = false;
                this.expression = false;
                this.async = true;
              }
              __name(AsyncFunctionDeclaration2, "AsyncFunctionDeclaration");
              return AsyncFunctionDeclaration2;
            }();
            exports3.AsyncFunctionDeclaration = AsyncFunctionDeclaration;
            var AsyncFunctionExpression = /* @__PURE__ */ function() {
              function AsyncFunctionExpression2(id, params, body) {
                this.type = syntax_1.Syntax.FunctionExpression;
                this.id = id;
                this.params = params;
                this.body = body;
                this.generator = false;
                this.expression = false;
                this.async = true;
              }
              __name(AsyncFunctionExpression2, "AsyncFunctionExpression");
              return AsyncFunctionExpression2;
            }();
            exports3.AsyncFunctionExpression = AsyncFunctionExpression;
            var AwaitExpression = /* @__PURE__ */ function() {
              function AwaitExpression2(argument) {
                this.type = syntax_1.Syntax.AwaitExpression;
                this.argument = argument;
              }
              __name(AwaitExpression2, "AwaitExpression");
              return AwaitExpression2;
            }();
            exports3.AwaitExpression = AwaitExpression;
            var BinaryExpression = /* @__PURE__ */ function() {
              function BinaryExpression2(operator2, left3, right3) {
                var logical = operator2 === "||" || operator2 === "&&";
                this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression;
                this.operator = operator2;
                this.left = left3;
                this.right = right3;
              }
              __name(BinaryExpression2, "BinaryExpression");
              return BinaryExpression2;
            }();
            exports3.BinaryExpression = BinaryExpression;
            var BlockStatement = /* @__PURE__ */ function() {
              function BlockStatement2(body) {
                this.type = syntax_1.Syntax.BlockStatement;
                this.body = body;
              }
              __name(BlockStatement2, "BlockStatement");
              return BlockStatement2;
            }();
            exports3.BlockStatement = BlockStatement;
            var BreakStatement = /* @__PURE__ */ function() {
              function BreakStatement2(label) {
                this.type = syntax_1.Syntax.BreakStatement;
                this.label = label;
              }
              __name(BreakStatement2, "BreakStatement");
              return BreakStatement2;
            }();
            exports3.BreakStatement = BreakStatement;
            var CallExpression = /* @__PURE__ */ function() {
              function CallExpression2(callee, args) {
                this.type = syntax_1.Syntax.CallExpression;
                this.callee = callee;
                this.arguments = args;
              }
              __name(CallExpression2, "CallExpression");
              return CallExpression2;
            }();
            exports3.CallExpression = CallExpression;
            var CatchClause = /* @__PURE__ */ function() {
              function CatchClause2(param, body) {
                this.type = syntax_1.Syntax.CatchClause;
                this.param = param;
                this.body = body;
              }
              __name(CatchClause2, "CatchClause");
              return CatchClause2;
            }();
            exports3.CatchClause = CatchClause;
            var ClassBody = /* @__PURE__ */ function() {
              function ClassBody2(body) {
                this.type = syntax_1.Syntax.ClassBody;
                this.body = body;
              }
              __name(ClassBody2, "ClassBody");
              return ClassBody2;
            }();
            exports3.ClassBody = ClassBody;
            var ClassDeclaration = /* @__PURE__ */ function() {
              function ClassDeclaration2(id, superClass, body) {
                this.type = syntax_1.Syntax.ClassDeclaration;
                this.id = id;
                this.superClass = superClass;
                this.body = body;
              }
              __name(ClassDeclaration2, "ClassDeclaration");
              return ClassDeclaration2;
            }();
            exports3.ClassDeclaration = ClassDeclaration;
            var ClassExpression = /* @__PURE__ */ function() {
              function ClassExpression2(id, superClass, body) {
                this.type = syntax_1.Syntax.ClassExpression;
                this.id = id;
                this.superClass = superClass;
                this.body = body;
              }
              __name(ClassExpression2, "ClassExpression");
              return ClassExpression2;
            }();
            exports3.ClassExpression = ClassExpression;
            var ComputedMemberExpression = /* @__PURE__ */ function() {
              function ComputedMemberExpression2(object, property) {
                this.type = syntax_1.Syntax.MemberExpression;
                this.computed = true;
                this.object = object;
                this.property = property;
              }
              __name(ComputedMemberExpression2, "ComputedMemberExpression");
              return ComputedMemberExpression2;
            }();
            exports3.ComputedMemberExpression = ComputedMemberExpression;
            var ConditionalExpression = /* @__PURE__ */ function() {
              function ConditionalExpression2(test, consequent, alternate) {
                this.type = syntax_1.Syntax.ConditionalExpression;
                this.test = test;
                this.consequent = consequent;
                this.alternate = alternate;
              }
              __name(ConditionalExpression2, "ConditionalExpression");
              return ConditionalExpression2;
            }();
            exports3.ConditionalExpression = ConditionalExpression;
            var ContinueStatement = /* @__PURE__ */ function() {
              function ContinueStatement2(label) {
                this.type = syntax_1.Syntax.ContinueStatement;
                this.label = label;
              }
              __name(ContinueStatement2, "ContinueStatement");
              return ContinueStatement2;
            }();
            exports3.ContinueStatement = ContinueStatement;
            var DebuggerStatement = /* @__PURE__ */ function() {
              function DebuggerStatement2() {
                this.type = syntax_1.Syntax.DebuggerStatement;
              }
              __name(DebuggerStatement2, "DebuggerStatement");
              return DebuggerStatement2;
            }();
            exports3.DebuggerStatement = DebuggerStatement;
            var Directive2 = /* @__PURE__ */ function() {
              function Directive3(expression, directive) {
                this.type = syntax_1.Syntax.ExpressionStatement;
                this.expression = expression;
                this.directive = directive;
              }
              __name(Directive3, "Directive");
              return Directive3;
            }();
            exports3.Directive = Directive2;
            var DoWhileStatement = /* @__PURE__ */ function() {
              function DoWhileStatement2(body, test) {
                this.type = syntax_1.Syntax.DoWhileStatement;
                this.body = body;
                this.test = test;
              }
              __name(DoWhileStatement2, "DoWhileStatement");
              return DoWhileStatement2;
            }();
            exports3.DoWhileStatement = DoWhileStatement;
            var EmptyStatement = /* @__PURE__ */ function() {
              function EmptyStatement2() {
                this.type = syntax_1.Syntax.EmptyStatement;
              }
              __name(EmptyStatement2, "EmptyStatement");
              return EmptyStatement2;
            }();
            exports3.EmptyStatement = EmptyStatement;
            var ExportAllDeclaration = /* @__PURE__ */ function() {
              function ExportAllDeclaration2(source2) {
                this.type = syntax_1.Syntax.ExportAllDeclaration;
                this.source = source2;
              }
              __name(ExportAllDeclaration2, "ExportAllDeclaration");
              return ExportAllDeclaration2;
            }();
            exports3.ExportAllDeclaration = ExportAllDeclaration;
            var ExportDefaultDeclaration = /* @__PURE__ */ function() {
              function ExportDefaultDeclaration2(declaration) {
                this.type = syntax_1.Syntax.ExportDefaultDeclaration;
                this.declaration = declaration;
              }
              __name(ExportDefaultDeclaration2, "ExportDefaultDeclaration");
              return ExportDefaultDeclaration2;
            }();
            exports3.ExportDefaultDeclaration = ExportDefaultDeclaration;
            var ExportNamedDeclaration = /* @__PURE__ */ function() {
              function ExportNamedDeclaration2(declaration, specifiers, source2) {
                this.type = syntax_1.Syntax.ExportNamedDeclaration;
                this.declaration = declaration;
                this.specifiers = specifiers;
                this.source = source2;
              }
              __name(ExportNamedDeclaration2, "ExportNamedDeclaration");
              return ExportNamedDeclaration2;
            }();
            exports3.ExportNamedDeclaration = ExportNamedDeclaration;
            var ExportSpecifier = /* @__PURE__ */ function() {
              function ExportSpecifier2(local, exported) {
                this.type = syntax_1.Syntax.ExportSpecifier;
                this.exported = exported;
                this.local = local;
              }
              __name(ExportSpecifier2, "ExportSpecifier");
              return ExportSpecifier2;
            }();
            exports3.ExportSpecifier = ExportSpecifier;
            var ExpressionStatement = /* @__PURE__ */ function() {
              function ExpressionStatement2(expression) {
                this.type = syntax_1.Syntax.ExpressionStatement;
                this.expression = expression;
              }
              __name(ExpressionStatement2, "ExpressionStatement");
              return ExpressionStatement2;
            }();
            exports3.ExpressionStatement = ExpressionStatement;
            var ForInStatement = /* @__PURE__ */ function() {
              function ForInStatement2(left3, right3, body) {
                this.type = syntax_1.Syntax.ForInStatement;
                this.left = left3;
                this.right = right3;
                this.body = body;
                this.each = false;
              }
              __name(ForInStatement2, "ForInStatement");
              return ForInStatement2;
            }();
            exports3.ForInStatement = ForInStatement;
            var ForOfStatement = /* @__PURE__ */ function() {
              function ForOfStatement2(left3, right3, body) {
                this.type = syntax_1.Syntax.ForOfStatement;
                this.left = left3;
                this.right = right3;
                this.body = body;
              }
              __name(ForOfStatement2, "ForOfStatement");
              return ForOfStatement2;
            }();
            exports3.ForOfStatement = ForOfStatement;
            var ForStatement = /* @__PURE__ */ function() {
              function ForStatement2(init, test, update2, body) {
                this.type = syntax_1.Syntax.ForStatement;
                this.init = init;
                this.test = test;
                this.update = update2;
                this.body = body;
              }
              __name(ForStatement2, "ForStatement");
              return ForStatement2;
            }();
            exports3.ForStatement = ForStatement;
            var FunctionDeclaration = /* @__PURE__ */ function() {
              function FunctionDeclaration2(id, params, body, generator) {
                this.type = syntax_1.Syntax.FunctionDeclaration;
                this.id = id;
                this.params = params;
                this.body = body;
                this.generator = generator;
                this.expression = false;
                this.async = false;
              }
              __name(FunctionDeclaration2, "FunctionDeclaration");
              return FunctionDeclaration2;
            }();
            exports3.FunctionDeclaration = FunctionDeclaration;
            var FunctionExpression = /* @__PURE__ */ function() {
              function FunctionExpression2(id, params, body, generator) {
                this.type = syntax_1.Syntax.FunctionExpression;
                this.id = id;
                this.params = params;
                this.body = body;
                this.generator = generator;
                this.expression = false;
                this.async = false;
              }
              __name(FunctionExpression2, "FunctionExpression");
              return FunctionExpression2;
            }();
            exports3.FunctionExpression = FunctionExpression;
            var Identifier = /* @__PURE__ */ function() {
              function Identifier2(name3) {
                this.type = syntax_1.Syntax.Identifier;
                this.name = name3;
              }
              __name(Identifier2, "Identifier");
              return Identifier2;
            }();
            exports3.Identifier = Identifier;
            var IfStatement = /* @__PURE__ */ function() {
              function IfStatement2(test, consequent, alternate) {
                this.type = syntax_1.Syntax.IfStatement;
                this.test = test;
                this.consequent = consequent;
                this.alternate = alternate;
              }
              __name(IfStatement2, "IfStatement");
              return IfStatement2;
            }();
            exports3.IfStatement = IfStatement;
            var ImportDeclaration = /* @__PURE__ */ function() {
              function ImportDeclaration2(specifiers, source2) {
                this.type = syntax_1.Syntax.ImportDeclaration;
                this.specifiers = specifiers;
                this.source = source2;
              }
              __name(ImportDeclaration2, "ImportDeclaration");
              return ImportDeclaration2;
            }();
            exports3.ImportDeclaration = ImportDeclaration;
            var ImportDefaultSpecifier = /* @__PURE__ */ function() {
              function ImportDefaultSpecifier2(local) {
                this.type = syntax_1.Syntax.ImportDefaultSpecifier;
                this.local = local;
              }
              __name(ImportDefaultSpecifier2, "ImportDefaultSpecifier");
              return ImportDefaultSpecifier2;
            }();
            exports3.ImportDefaultSpecifier = ImportDefaultSpecifier;
            var ImportNamespaceSpecifier = /* @__PURE__ */ function() {
              function ImportNamespaceSpecifier2(local) {
                this.type = syntax_1.Syntax.ImportNamespaceSpecifier;
                this.local = local;
              }
              __name(ImportNamespaceSpecifier2, "ImportNamespaceSpecifier");
              return ImportNamespaceSpecifier2;
            }();
            exports3.ImportNamespaceSpecifier = ImportNamespaceSpecifier;
            var ImportSpecifier = /* @__PURE__ */ function() {
              function ImportSpecifier2(local, imported) {
                this.type = syntax_1.Syntax.ImportSpecifier;
                this.local = local;
                this.imported = imported;
              }
              __name(ImportSpecifier2, "ImportSpecifier");
              return ImportSpecifier2;
            }();
            exports3.ImportSpecifier = ImportSpecifier;
            var LabeledStatement = /* @__PURE__ */ function() {
              function LabeledStatement2(label, body) {
                this.type = syntax_1.Syntax.LabeledStatement;
                this.label = label;
                this.body = body;
              }
              __name(LabeledStatement2, "LabeledStatement");
              return LabeledStatement2;
            }();
            exports3.LabeledStatement = LabeledStatement;
            var Literal = /* @__PURE__ */ function() {
              function Literal2(value, raw2) {
                this.type = syntax_1.Syntax.Literal;
                this.value = value;
                this.raw = raw2;
              }
              __name(Literal2, "Literal");
              return Literal2;
            }();
            exports3.Literal = Literal;
            var MetaProperty = /* @__PURE__ */ function() {
              function MetaProperty2(meta, property) {
                this.type = syntax_1.Syntax.MetaProperty;
                this.meta = meta;
                this.property = property;
              }
              __name(MetaProperty2, "MetaProperty");
              return MetaProperty2;
            }();
            exports3.MetaProperty = MetaProperty;
            var MethodDefinition = /* @__PURE__ */ function() {
              function MethodDefinition2(key, computed, value, kind, isStatic) {
                this.type = syntax_1.Syntax.MethodDefinition;
                this.key = key;
                this.computed = computed;
                this.value = value;
                this.kind = kind;
                this.static = isStatic;
              }
              __name(MethodDefinition2, "MethodDefinition");
              return MethodDefinition2;
            }();
            exports3.MethodDefinition = MethodDefinition;
            var Module = /* @__PURE__ */ function() {
              function Module2(body) {
                this.type = syntax_1.Syntax.Program;
                this.body = body;
                this.sourceType = "module";
              }
              __name(Module2, "Module");
              return Module2;
            }();
            exports3.Module = Module;
            var NewExpression = /* @__PURE__ */ function() {
              function NewExpression2(callee, args) {
                this.type = syntax_1.Syntax.NewExpression;
                this.callee = callee;
                this.arguments = args;
              }
              __name(NewExpression2, "NewExpression");
              return NewExpression2;
            }();
            exports3.NewExpression = NewExpression;
            var ObjectExpression = /* @__PURE__ */ function() {
              function ObjectExpression2(properties) {
                this.type = syntax_1.Syntax.ObjectExpression;
                this.properties = properties;
              }
              __name(ObjectExpression2, "ObjectExpression");
              return ObjectExpression2;
            }();
            exports3.ObjectExpression = ObjectExpression;
            var ObjectPattern = /* @__PURE__ */ function() {
              function ObjectPattern2(properties) {
                this.type = syntax_1.Syntax.ObjectPattern;
                this.properties = properties;
              }
              __name(ObjectPattern2, "ObjectPattern");
              return ObjectPattern2;
            }();
            exports3.ObjectPattern = ObjectPattern;
            var Property = /* @__PURE__ */ function() {
              function Property2(kind, key, computed, value, method, shorthand) {
                this.type = syntax_1.Syntax.Property;
                this.key = key;
                this.computed = computed;
                this.value = value;
                this.kind = kind;
                this.method = method;
                this.shorthand = shorthand;
              }
              __name(Property2, "Property");
              return Property2;
            }();
            exports3.Property = Property;
            var RegexLiteral = /* @__PURE__ */ function() {
              function RegexLiteral2(value, raw2, pattern, flags) {
                this.type = syntax_1.Syntax.Literal;
                this.value = value;
                this.raw = raw2;
                this.regex = { pattern, flags };
              }
              __name(RegexLiteral2, "RegexLiteral");
              return RegexLiteral2;
            }();
            exports3.RegexLiteral = RegexLiteral;
            var RestElement = /* @__PURE__ */ function() {
              function RestElement2(argument) {
                this.type = syntax_1.Syntax.RestElement;
                this.argument = argument;
              }
              __name(RestElement2, "RestElement");
              return RestElement2;
            }();
            exports3.RestElement = RestElement;
            var ReturnStatement = /* @__PURE__ */ function() {
              function ReturnStatement2(argument) {
                this.type = syntax_1.Syntax.ReturnStatement;
                this.argument = argument;
              }
              __name(ReturnStatement2, "ReturnStatement");
              return ReturnStatement2;
            }();
            exports3.ReturnStatement = ReturnStatement;
            var Script2 = /* @__PURE__ */ function() {
              function Script3(body) {
                this.type = syntax_1.Syntax.Program;
                this.body = body;
                this.sourceType = "script";
              }
              __name(Script3, "Script");
              return Script3;
            }();
            exports3.Script = Script2;
            var SequenceExpression = /* @__PURE__ */ function() {
              function SequenceExpression2(expressions) {
                this.type = syntax_1.Syntax.SequenceExpression;
                this.expressions = expressions;
              }
              __name(SequenceExpression2, "SequenceExpression");
              return SequenceExpression2;
            }();
            exports3.SequenceExpression = SequenceExpression;
            var SpreadElement = /* @__PURE__ */ function() {
              function SpreadElement2(argument) {
                this.type = syntax_1.Syntax.SpreadElement;
                this.argument = argument;
              }
              __name(SpreadElement2, "SpreadElement");
              return SpreadElement2;
            }();
            exports3.SpreadElement = SpreadElement;
            var StaticMemberExpression = /* @__PURE__ */ function() {
              function StaticMemberExpression2(object, property) {
                this.type = syntax_1.Syntax.MemberExpression;
                this.computed = false;
                this.object = object;
                this.property = property;
              }
              __name(StaticMemberExpression2, "StaticMemberExpression");
              return StaticMemberExpression2;
            }();
            exports3.StaticMemberExpression = StaticMemberExpression;
            var Super = /* @__PURE__ */ function() {
              function Super2() {
                this.type = syntax_1.Syntax.Super;
              }
              __name(Super2, "Super");
              return Super2;
            }();
            exports3.Super = Super;
            var SwitchCase = /* @__PURE__ */ function() {
              function SwitchCase2(test, consequent) {
                this.type = syntax_1.Syntax.SwitchCase;
                this.test = test;
                this.consequent = consequent;
              }
              __name(SwitchCase2, "SwitchCase");
              return SwitchCase2;
            }();
            exports3.SwitchCase = SwitchCase;
            var SwitchStatement = /* @__PURE__ */ function() {
              function SwitchStatement2(discriminant, cases) {
                this.type = syntax_1.Syntax.SwitchStatement;
                this.discriminant = discriminant;
                this.cases = cases;
              }
              __name(SwitchStatement2, "SwitchStatement");
              return SwitchStatement2;
            }();
            exports3.SwitchStatement = SwitchStatement;
            var TaggedTemplateExpression = /* @__PURE__ */ function() {
              function TaggedTemplateExpression2(tag2, quasi) {
                this.type = syntax_1.Syntax.TaggedTemplateExpression;
                this.tag = tag2;
                this.quasi = quasi;
              }
              __name(TaggedTemplateExpression2, "TaggedTemplateExpression");
              return TaggedTemplateExpression2;
            }();
            exports3.TaggedTemplateExpression = TaggedTemplateExpression;
            var TemplateElement = /* @__PURE__ */ function() {
              function TemplateElement2(value, tail) {
                this.type = syntax_1.Syntax.TemplateElement;
                this.value = value;
                this.tail = tail;
              }
              __name(TemplateElement2, "TemplateElement");
              return TemplateElement2;
            }();
            exports3.TemplateElement = TemplateElement;
            var TemplateLiteral = /* @__PURE__ */ function() {
              function TemplateLiteral2(quasis, expressions) {
                this.type = syntax_1.Syntax.TemplateLiteral;
                this.quasis = quasis;
                this.expressions = expressions;
              }
              __name(TemplateLiteral2, "TemplateLiteral");
              return TemplateLiteral2;
            }();
            exports3.TemplateLiteral = TemplateLiteral;
            var ThisExpression = /* @__PURE__ */ function() {
              function ThisExpression2() {
                this.type = syntax_1.Syntax.ThisExpression;
              }
              __name(ThisExpression2, "ThisExpression");
              return ThisExpression2;
            }();
            exports3.ThisExpression = ThisExpression;
            var ThrowStatement = /* @__PURE__ */ function() {
              function ThrowStatement2(argument) {
                this.type = syntax_1.Syntax.ThrowStatement;
                this.argument = argument;
              }
              __name(ThrowStatement2, "ThrowStatement");
              return ThrowStatement2;
            }();
            exports3.ThrowStatement = ThrowStatement;
            var TryStatement = /* @__PURE__ */ function() {
              function TryStatement2(block2, handler, finalizer) {
                this.type = syntax_1.Syntax.TryStatement;
                this.block = block2;
                this.handler = handler;
                this.finalizer = finalizer;
              }
              __name(TryStatement2, "TryStatement");
              return TryStatement2;
            }();
            exports3.TryStatement = TryStatement;
            var UnaryExpression = /* @__PURE__ */ function() {
              function UnaryExpression2(operator2, argument) {
                this.type = syntax_1.Syntax.UnaryExpression;
                this.operator = operator2;
                this.argument = argument;
                this.prefix = true;
              }
              __name(UnaryExpression2, "UnaryExpression");
              return UnaryExpression2;
            }();
            exports3.UnaryExpression = UnaryExpression;
            var UpdateExpression = /* @__PURE__ */ function() {
              function UpdateExpression2(operator2, argument, prefix) {
                this.type = syntax_1.Syntax.UpdateExpression;
                this.operator = operator2;
                this.argument = argument;
                this.prefix = prefix;
              }
              __name(UpdateExpression2, "UpdateExpression");
              return UpdateExpression2;
            }();
            exports3.UpdateExpression = UpdateExpression;
            var VariableDeclaration = /* @__PURE__ */ function() {
              function VariableDeclaration2(declarations, kind) {
                this.type = syntax_1.Syntax.VariableDeclaration;
                this.declarations = declarations;
                this.kind = kind;
              }
              __name(VariableDeclaration2, "VariableDeclaration");
              return VariableDeclaration2;
            }();
            exports3.VariableDeclaration = VariableDeclaration;
            var VariableDeclarator = /* @__PURE__ */ function() {
              function VariableDeclarator2(id, init) {
                this.type = syntax_1.Syntax.VariableDeclarator;
                this.id = id;
                this.init = init;
              }
              __name(VariableDeclarator2, "VariableDeclarator");
              return VariableDeclarator2;
            }();
            exports3.VariableDeclarator = VariableDeclarator;
            var WhileStatement = /* @__PURE__ */ function() {
              function WhileStatement2(test, body) {
                this.type = syntax_1.Syntax.WhileStatement;
                this.test = test;
                this.body = body;
              }
              __name(WhileStatement2, "WhileStatement");
              return WhileStatement2;
            }();
            exports3.WhileStatement = WhileStatement;
            var WithStatement = /* @__PURE__ */ function() {
              function WithStatement2(object, body) {
                this.type = syntax_1.Syntax.WithStatement;
                this.object = object;
                this.body = body;
              }
              __name(WithStatement2, "WithStatement");
              return WithStatement2;
            }();
            exports3.WithStatement = WithStatement;
            var YieldExpression = /* @__PURE__ */ function() {
              function YieldExpression2(argument, delegate) {
                this.type = syntax_1.Syntax.YieldExpression;
                this.argument = argument;
                this.delegate = delegate;
              }
              __name(YieldExpression2, "YieldExpression");
              return YieldExpression2;
            }();
            exports3.YieldExpression = YieldExpression;
          },
          /* 8 */
          /***/
          function(module3, exports3, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var assert_1 = __webpack_require__(9);
            var error_handler_1 = __webpack_require__(10);
            var messages_1 = __webpack_require__(11);
            var Node4 = __webpack_require__(7);
            var scanner_1 = __webpack_require__(12);
            var syntax_1 = __webpack_require__(2);
            var token_1 = __webpack_require__(13);
            var ArrowParameterPlaceHolder = "ArrowParameterPlaceHolder";
            var Parser4 = function() {
              function Parser5(code2, options2, delegate) {
                if (options2 === void 0) {
                  options2 = {};
                }
                this.config = {
                  range: typeof options2.range === "boolean" && options2.range,
                  loc: typeof options2.loc === "boolean" && options2.loc,
                  source: null,
                  tokens: typeof options2.tokens === "boolean" && options2.tokens,
                  comment: typeof options2.comment === "boolean" && options2.comment,
                  tolerant: typeof options2.tolerant === "boolean" && options2.tolerant
                };
                if (this.config.loc && options2.source && options2.source !== null) {
                  this.config.source = String(options2.source);
                }
                this.delegate = delegate;
                this.errorHandler = new error_handler_1.ErrorHandler();
                this.errorHandler.tolerant = this.config.tolerant;
                this.scanner = new scanner_1.Scanner(code2, this.errorHandler);
                this.scanner.trackComment = this.config.comment;
                this.operatorPrecedence = {
                  ")": 0,
                  ";": 0,
                  ",": 0,
                  "=": 0,
                  "]": 0,
                  "||": 1,
                  "&&": 2,
                  "|": 3,
                  "^": 4,
                  "&": 5,
                  "==": 6,
                  "!=": 6,
                  "===": 6,
                  "!==": 6,
                  "<": 7,
                  ">": 7,
                  "<=": 7,
                  ">=": 7,
                  "<<": 8,
                  ">>": 8,
                  ">>>": 8,
                  "+": 9,
                  "-": 9,
                  "*": 11,
                  "/": 11,
                  "%": 11
                };
                this.lookahead = {
                  type: 2,
                  value: "",
                  lineNumber: this.scanner.lineNumber,
                  lineStart: 0,
                  start: 0,
                  end: 0
                };
                this.hasLineTerminator = false;
                this.context = {
                  isModule: false,
                  await: false,
                  allowIn: true,
                  allowStrictDirective: true,
                  allowYield: true,
                  firstCoverInitializedNameError: null,
                  isAssignmentTarget: false,
                  isBindingElement: false,
                  inFunctionBody: false,
                  inIteration: false,
                  inSwitch: false,
                  labelSet: {},
                  strict: false
                };
                this.tokens = [];
                this.startMarker = {
                  index: 0,
                  line: this.scanner.lineNumber,
                  column: 0
                };
                this.lastMarker = {
                  index: 0,
                  line: this.scanner.lineNumber,
                  column: 0
                };
                this.nextToken();
                this.lastMarker = {
                  index: this.scanner.index,
                  line: this.scanner.lineNumber,
                  column: this.scanner.index - this.scanner.lineStart
                };
              }
              __name(Parser5, "Parser");
              Parser5.prototype.throwError = function(messageFormat) {
                var values = [];
                for (var _i = 1; _i < arguments.length; _i++) {
                  values[_i - 1] = arguments[_i];
                }
                var args = Array.prototype.slice.call(arguments, 1);
                var msg = messageFormat.replace(/%(\d)/g, function(whole, idx) {
                  assert_1.assert(idx < args.length, "Message reference must be in range");
                  return args[idx];
                });
                var index = this.lastMarker.index;
                var line = this.lastMarker.line;
                var column = this.lastMarker.column + 1;
                throw this.errorHandler.createError(index, line, column, msg);
              };
              Parser5.prototype.tolerateError = function(messageFormat) {
                var values = [];
                for (var _i = 1; _i < arguments.length; _i++) {
                  values[_i - 1] = arguments[_i];
                }
                var args = Array.prototype.slice.call(arguments, 1);
                var msg = messageFormat.replace(/%(\d)/g, function(whole, idx) {
                  assert_1.assert(idx < args.length, "Message reference must be in range");
                  return args[idx];
                });
                var index = this.lastMarker.index;
                var line = this.scanner.lineNumber;
                var column = this.lastMarker.column + 1;
                this.errorHandler.tolerateError(index, line, column, msg);
              };
              Parser5.prototype.unexpectedTokenError = function(token2, message) {
                var msg = message || messages_1.Messages.UnexpectedToken;
                var value;
                if (token2) {
                  if (!message) {
                    msg = token2.type === 2 ? messages_1.Messages.UnexpectedEOS : token2.type === 3 ? messages_1.Messages.UnexpectedIdentifier : token2.type === 6 ? messages_1.Messages.UnexpectedNumber : token2.type === 8 ? messages_1.Messages.UnexpectedString : token2.type === 10 ? messages_1.Messages.UnexpectedTemplate : messages_1.Messages.UnexpectedToken;
                    if (token2.type === 4) {
                      if (this.scanner.isFutureReservedWord(token2.value)) {
                        msg = messages_1.Messages.UnexpectedReserved;
                      } else if (this.context.strict && this.scanner.isStrictModeReservedWord(token2.value)) {
                        msg = messages_1.Messages.StrictReservedWord;
                      }
                    }
                  }
                  value = token2.value;
                } else {
                  value = "ILLEGAL";
                }
                msg = msg.replace("%0", value);
                if (token2 && typeof token2.lineNumber === "number") {
                  var index = token2.start;
                  var line = token2.lineNumber;
                  var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column;
                  var column = token2.start - lastMarkerLineStart + 1;
                  return this.errorHandler.createError(index, line, column, msg);
                } else {
                  var index = this.lastMarker.index;
                  var line = this.lastMarker.line;
                  var column = this.lastMarker.column + 1;
                  return this.errorHandler.createError(index, line, column, msg);
                }
              };
              Parser5.prototype.throwUnexpectedToken = function(token2, message) {
                throw this.unexpectedTokenError(token2, message);
              };
              Parser5.prototype.tolerateUnexpectedToken = function(token2, message) {
                this.errorHandler.tolerate(this.unexpectedTokenError(token2, message));
              };
              Parser5.prototype.collectComments = function() {
                if (!this.config.comment) {
                  this.scanner.scanComments();
                } else {
                  var comments = this.scanner.scanComments();
                  if (comments.length > 0 && this.delegate) {
                    for (var i = 0; i < comments.length; ++i) {
                      var e2 = comments[i];
                      var node = void 0;
                      node = {
                        type: e2.multiLine ? "BlockComment" : "LineComment",
                        value: this.scanner.source.slice(e2.slice[0], e2.slice[1])
                      };
                      if (this.config.range) {
                        node.range = e2.range;
                      }
                      if (this.config.loc) {
                        node.loc = e2.loc;
                      }
                      var metadata = {
                        start: {
                          line: e2.loc.start.line,
                          column: e2.loc.start.column,
                          offset: e2.range[0]
                        },
                        end: {
                          line: e2.loc.end.line,
                          column: e2.loc.end.column,
                          offset: e2.range[1]
                        }
                      };
                      this.delegate(node, metadata);
                    }
                  }
                }
              };
              Parser5.prototype.getTokenRaw = function(token2) {
                return this.scanner.source.slice(token2.start, token2.end);
              };
              Parser5.prototype.convertToken = function(token2) {
                var t2 = {
                  type: token_1.TokenName[token2.type],
                  value: this.getTokenRaw(token2)
                };
                if (this.config.range) {
                  t2.range = [token2.start, token2.end];
                }
                if (this.config.loc) {
                  t2.loc = {
                    start: {
                      line: this.startMarker.line,
                      column: this.startMarker.column
                    },
                    end: {
                      line: this.scanner.lineNumber,
                      column: this.scanner.index - this.scanner.lineStart
                    }
                  };
                }
                if (token2.type === 9) {
                  var pattern = token2.pattern;
                  var flags = token2.flags;
                  t2.regex = { pattern, flags };
                }
                return t2;
              };
              Parser5.prototype.nextToken = function() {
                var token2 = this.lookahead;
                this.lastMarker.index = this.scanner.index;
                this.lastMarker.line = this.scanner.lineNumber;
                this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
                this.collectComments();
                if (this.scanner.index !== this.startMarker.index) {
                  this.startMarker.index = this.scanner.index;
                  this.startMarker.line = this.scanner.lineNumber;
                  this.startMarker.column = this.scanner.index - this.scanner.lineStart;
                }
                var next = this.scanner.lex();
                this.hasLineTerminator = token2.lineNumber !== next.lineNumber;
                if (next && this.context.strict && next.type === 3) {
                  if (this.scanner.isStrictModeReservedWord(next.value)) {
                    next.type = 4;
                  }
                }
                this.lookahead = next;
                if (this.config.tokens && next.type !== 2) {
                  this.tokens.push(this.convertToken(next));
                }
                return token2;
              };
              Parser5.prototype.nextRegexToken = function() {
                this.collectComments();
                var token2 = this.scanner.scanRegExp();
                if (this.config.tokens) {
                  this.tokens.pop();
                  this.tokens.push(this.convertToken(token2));
                }
                this.lookahead = token2;
                this.nextToken();
                return token2;
              };
              Parser5.prototype.createNode = function() {
                return {
                  index: this.startMarker.index,
                  line: this.startMarker.line,
                  column: this.startMarker.column
                };
              };
              Parser5.prototype.startNode = function(token2, lastLineStart) {
                if (lastLineStart === void 0) {
                  lastLineStart = 0;
                }
                var column = token2.start - token2.lineStart;
                var line = token2.lineNumber;
                if (column < 0) {
                  column += lastLineStart;
                  line--;
                }
                return {
                  index: token2.start,
                  line,
                  column
                };
              };
              Parser5.prototype.finalize = function(marker, node) {
                if (this.config.range) {
                  node.range = [marker.index, this.lastMarker.index];
                }
                if (this.config.loc) {
                  node.loc = {
                    start: {
                      line: marker.line,
                      column: marker.column
                    },
                    end: {
                      line: this.lastMarker.line,
                      column: this.lastMarker.column
                    }
                  };
                  if (this.config.source) {
                    node.loc.source = this.config.source;
                  }
                }
                if (this.delegate) {
                  var metadata = {
                    start: {
                      line: marker.line,
                      column: marker.column,
                      offset: marker.index
                    },
                    end: {
                      line: this.lastMarker.line,
                      column: this.lastMarker.column,
                      offset: this.lastMarker.index
                    }
                  };
                  this.delegate(node, metadata);
                }
                return node;
              };
              Parser5.prototype.expect = function(value) {
                var token2 = this.nextToken();
                if (token2.type !== 7 || token2.value !== value) {
                  this.throwUnexpectedToken(token2);
                }
              };
              Parser5.prototype.expectCommaSeparator = function() {
                if (this.config.tolerant) {
                  var token2 = this.lookahead;
                  if (token2.type === 7 && token2.value === ",") {
                    this.nextToken();
                  } else if (token2.type === 7 && token2.value === ";") {
                    this.nextToken();
                    this.tolerateUnexpectedToken(token2);
                  } else {
                    this.tolerateUnexpectedToken(token2, messages_1.Messages.UnexpectedToken);
                  }
                } else {
                  this.expect(",");
                }
              };
              Parser5.prototype.expectKeyword = function(keyword) {
                var token2 = this.nextToken();
                if (token2.type !== 4 || token2.value !== keyword) {
                  this.throwUnexpectedToken(token2);
                }
              };
              Parser5.prototype.match = function(value) {
                return this.lookahead.type === 7 && this.lookahead.value === value;
              };
              Parser5.prototype.matchKeyword = function(keyword) {
                return this.lookahead.type === 4 && this.lookahead.value === keyword;
              };
              Parser5.prototype.matchContextualKeyword = function(keyword) {
                return this.lookahead.type === 3 && this.lookahead.value === keyword;
              };
              Parser5.prototype.matchAssign = function() {
                if (this.lookahead.type !== 7) {
                  return false;
                }
                var op = this.lookahead.value;
                return op === "=" || op === "*=" || op === "**=" || op === "/=" || op === "%=" || op === "+=" || op === "-=" || op === "<<=" || op === ">>=" || op === ">>>=" || op === "&=" || op === "^=" || op === "|=";
              };
              Parser5.prototype.isolateCoverGrammar = function(parseFunction) {
                var previousIsBindingElement = this.context.isBindingElement;
                var previousIsAssignmentTarget = this.context.isAssignmentTarget;
                var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
                this.context.isBindingElement = true;
                this.context.isAssignmentTarget = true;
                this.context.firstCoverInitializedNameError = null;
                var result = parseFunction.call(this);
                if (this.context.firstCoverInitializedNameError !== null) {
                  this.throwUnexpectedToken(this.context.firstCoverInitializedNameError);
                }
                this.context.isBindingElement = previousIsBindingElement;
                this.context.isAssignmentTarget = previousIsAssignmentTarget;
                this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError;
                return result;
              };
              Parser5.prototype.inheritCoverGrammar = function(parseFunction) {
                var previousIsBindingElement = this.context.isBindingElement;
                var previousIsAssignmentTarget = this.context.isAssignmentTarget;
                var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
                this.context.isBindingElement = true;
                this.context.isAssignmentTarget = true;
                this.context.firstCoverInitializedNameError = null;
                var result = parseFunction.call(this);
                this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement;
                this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget;
                this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError;
                return result;
              };
              Parser5.prototype.consumeSemicolon = function() {
                if (this.match(";")) {
                  this.nextToken();
                } else if (!this.hasLineTerminator) {
                  if (this.lookahead.type !== 2 && !this.match("}")) {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                  this.lastMarker.index = this.startMarker.index;
                  this.lastMarker.line = this.startMarker.line;
                  this.lastMarker.column = this.startMarker.column;
                }
              };
              Parser5.prototype.parsePrimaryExpression = function() {
                var node = this.createNode();
                var expr;
                var token2, raw2;
                switch (this.lookahead.type) {
                  case 3:
                    if ((this.context.isModule || this.context.await) && this.lookahead.value === "await") {
                      this.tolerateUnexpectedToken(this.lookahead);
                    }
                    expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node, new Node4.Identifier(this.nextToken().value));
                    break;
                  case 6:
                  case 8:
                    if (this.context.strict && this.lookahead.octal) {
                      this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral);
                    }
                    this.context.isAssignmentTarget = false;
                    this.context.isBindingElement = false;
                    token2 = this.nextToken();
                    raw2 = this.getTokenRaw(token2);
                    expr = this.finalize(node, new Node4.Literal(token2.value, raw2));
                    break;
                  case 1:
                    this.context.isAssignmentTarget = false;
                    this.context.isBindingElement = false;
                    token2 = this.nextToken();
                    raw2 = this.getTokenRaw(token2);
                    expr = this.finalize(node, new Node4.Literal(token2.value === "true", raw2));
                    break;
                  case 5:
                    this.context.isAssignmentTarget = false;
                    this.context.isBindingElement = false;
                    token2 = this.nextToken();
                    raw2 = this.getTokenRaw(token2);
                    expr = this.finalize(node, new Node4.Literal(null, raw2));
                    break;
                  case 10:
                    expr = this.parseTemplateLiteral();
                    break;
                  case 7:
                    switch (this.lookahead.value) {
                      case "(":
                        this.context.isBindingElement = false;
                        expr = this.inheritCoverGrammar(this.parseGroupExpression);
                        break;
                      case "[":
                        expr = this.inheritCoverGrammar(this.parseArrayInitializer);
                        break;
                      case "{":
                        expr = this.inheritCoverGrammar(this.parseObjectInitializer);
                        break;
                      case "/":
                      case "/=":
                        this.context.isAssignmentTarget = false;
                        this.context.isBindingElement = false;
                        this.scanner.index = this.startMarker.index;
                        token2 = this.nextRegexToken();
                        raw2 = this.getTokenRaw(token2);
                        expr = this.finalize(node, new Node4.RegexLiteral(token2.regex, raw2, token2.pattern, token2.flags));
                        break;
                      default:
                        expr = this.throwUnexpectedToken(this.nextToken());
                    }
                    break;
                  case 4:
                    if (!this.context.strict && this.context.allowYield && this.matchKeyword("yield")) {
                      expr = this.parseIdentifierName();
                    } else if (!this.context.strict && this.matchKeyword("let")) {
                      expr = this.finalize(node, new Node4.Identifier(this.nextToken().value));
                    } else {
                      this.context.isAssignmentTarget = false;
                      this.context.isBindingElement = false;
                      if (this.matchKeyword("function")) {
                        expr = this.parseFunctionExpression();
                      } else if (this.matchKeyword("this")) {
                        this.nextToken();
                        expr = this.finalize(node, new Node4.ThisExpression());
                      } else if (this.matchKeyword("class")) {
                        expr = this.parseClassExpression();
                      } else {
                        expr = this.throwUnexpectedToken(this.nextToken());
                      }
                    }
                    break;
                  default:
                    expr = this.throwUnexpectedToken(this.nextToken());
                }
                return expr;
              };
              Parser5.prototype.parseSpreadElement = function() {
                var node = this.createNode();
                this.expect("...");
                var arg = this.inheritCoverGrammar(this.parseAssignmentExpression);
                return this.finalize(node, new Node4.SpreadElement(arg));
              };
              Parser5.prototype.parseArrayInitializer = function() {
                var node = this.createNode();
                var elements = [];
                this.expect("[");
                while (!this.match("]")) {
                  if (this.match(",")) {
                    this.nextToken();
                    elements.push(null);
                  } else if (this.match("...")) {
                    var element = this.parseSpreadElement();
                    if (!this.match("]")) {
                      this.context.isAssignmentTarget = false;
                      this.context.isBindingElement = false;
                      this.expect(",");
                    }
                    elements.push(element);
                  } else {
                    elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
                    if (!this.match("]")) {
                      this.expect(",");
                    }
                  }
                }
                this.expect("]");
                return this.finalize(node, new Node4.ArrayExpression(elements));
              };
              Parser5.prototype.parsePropertyMethod = function(params) {
                this.context.isAssignmentTarget = false;
                this.context.isBindingElement = false;
                var previousStrict = this.context.strict;
                var previousAllowStrictDirective = this.context.allowStrictDirective;
                this.context.allowStrictDirective = params.simple;
                var body = this.isolateCoverGrammar(this.parseFunctionSourceElements);
                if (this.context.strict && params.firstRestricted) {
                  this.tolerateUnexpectedToken(params.firstRestricted, params.message);
                }
                if (this.context.strict && params.stricted) {
                  this.tolerateUnexpectedToken(params.stricted, params.message);
                }
                this.context.strict = previousStrict;
                this.context.allowStrictDirective = previousAllowStrictDirective;
                return body;
              };
              Parser5.prototype.parsePropertyMethodFunction = function() {
                var isGenerator = false;
                var node = this.createNode();
                var previousAllowYield = this.context.allowYield;
                this.context.allowYield = true;
                var params = this.parseFormalParameters();
                var method = this.parsePropertyMethod(params);
                this.context.allowYield = previousAllowYield;
                return this.finalize(node, new Node4.FunctionExpression(null, params.params, method, isGenerator));
              };
              Parser5.prototype.parsePropertyMethodAsyncFunction = function() {
                var node = this.createNode();
                var previousAllowYield = this.context.allowYield;
                var previousAwait = this.context.await;
                this.context.allowYield = false;
                this.context.await = true;
                var params = this.parseFormalParameters();
                var method = this.parsePropertyMethod(params);
                this.context.allowYield = previousAllowYield;
                this.context.await = previousAwait;
                return this.finalize(node, new Node4.AsyncFunctionExpression(null, params.params, method));
              };
              Parser5.prototype.parseObjectPropertyKey = function() {
                var node = this.createNode();
                var token2 = this.nextToken();
                var key;
                switch (token2.type) {
                  case 8:
                  case 6:
                    if (this.context.strict && token2.octal) {
                      this.tolerateUnexpectedToken(token2, messages_1.Messages.StrictOctalLiteral);
                    }
                    var raw2 = this.getTokenRaw(token2);
                    key = this.finalize(node, new Node4.Literal(token2.value, raw2));
                    break;
                  case 3:
                  case 1:
                  case 5:
                  case 4:
                    key = this.finalize(node, new Node4.Identifier(token2.value));
                    break;
                  case 7:
                    if (token2.value === "[") {
                      key = this.isolateCoverGrammar(this.parseAssignmentExpression);
                      this.expect("]");
                    } else {
                      key = this.throwUnexpectedToken(token2);
                    }
                    break;
                  default:
                    key = this.throwUnexpectedToken(token2);
                }
                return key;
              };
              Parser5.prototype.isPropertyKey = function(key, value) {
                return key.type === syntax_1.Syntax.Identifier && key.name === value || key.type === syntax_1.Syntax.Literal && key.value === value;
              };
              Parser5.prototype.parseObjectProperty = function(hasProto) {
                var node = this.createNode();
                var token2 = this.lookahead;
                var kind;
                var key = null;
                var value = null;
                var computed = false;
                var method = false;
                var shorthand = false;
                var isAsync2 = false;
                if (token2.type === 3) {
                  var id = token2.value;
                  this.nextToken();
                  computed = this.match("[");
                  isAsync2 = !this.hasLineTerminator && id === "async" && !this.match(":") && !this.match("(") && !this.match("*") && !this.match(",");
                  key = isAsync2 ? this.parseObjectPropertyKey() : this.finalize(node, new Node4.Identifier(id));
                } else if (this.match("*")) {
                  this.nextToken();
                } else {
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                }
                var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
                if (token2.type === 3 && !isAsync2 && token2.value === "get" && lookaheadPropertyKey) {
                  kind = "get";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  this.context.allowYield = false;
                  value = this.parseGetterMethod();
                } else if (token2.type === 3 && !isAsync2 && token2.value === "set" && lookaheadPropertyKey) {
                  kind = "set";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  value = this.parseSetterMethod();
                } else if (token2.type === 7 && token2.value === "*" && lookaheadPropertyKey) {
                  kind = "init";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  value = this.parseGeneratorMethod();
                  method = true;
                } else {
                  if (!key) {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                  kind = "init";
                  if (this.match(":") && !isAsync2) {
                    if (!computed && this.isPropertyKey(key, "__proto__")) {
                      if (hasProto.value) {
                        this.tolerateError(messages_1.Messages.DuplicateProtoProperty);
                      }
                      hasProto.value = true;
                    }
                    this.nextToken();
                    value = this.inheritCoverGrammar(this.parseAssignmentExpression);
                  } else if (this.match("(")) {
                    value = isAsync2 ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
                    method = true;
                  } else if (token2.type === 3) {
                    var id = this.finalize(node, new Node4.Identifier(token2.value));
                    if (this.match("=")) {
                      this.context.firstCoverInitializedNameError = this.lookahead;
                      this.nextToken();
                      shorthand = true;
                      var init = this.isolateCoverGrammar(this.parseAssignmentExpression);
                      value = this.finalize(node, new Node4.AssignmentPattern(id, init));
                    } else {
                      shorthand = true;
                      value = id;
                    }
                  } else {
                    this.throwUnexpectedToken(this.nextToken());
                  }
                }
                return this.finalize(node, new Node4.Property(kind, key, computed, value, method, shorthand));
              };
              Parser5.prototype.parseObjectInitializer = function() {
                var node = this.createNode();
                this.expect("{");
                var properties = [];
                var hasProto = { value: false };
                while (!this.match("}")) {
                  properties.push(this.parseObjectProperty(hasProto));
                  if (!this.match("}")) {
                    this.expectCommaSeparator();
                  }
                }
                this.expect("}");
                return this.finalize(node, new Node4.ObjectExpression(properties));
              };
              Parser5.prototype.parseTemplateHead = function() {
                assert_1.assert(this.lookahead.head, "Template literal must start with a template head");
                var node = this.createNode();
                var token2 = this.nextToken();
                var raw2 = token2.value;
                var cooked = token2.cooked;
                return this.finalize(node, new Node4.TemplateElement({ raw: raw2, cooked }, token2.tail));
              };
              Parser5.prototype.parseTemplateElement = function() {
                if (this.lookahead.type !== 10) {
                  this.throwUnexpectedToken();
                }
                var node = this.createNode();
                var token2 = this.nextToken();
                var raw2 = token2.value;
                var cooked = token2.cooked;
                return this.finalize(node, new Node4.TemplateElement({ raw: raw2, cooked }, token2.tail));
              };
              Parser5.prototype.parseTemplateLiteral = function() {
                var node = this.createNode();
                var expressions = [];
                var quasis = [];
                var quasi = this.parseTemplateHead();
                quasis.push(quasi);
                while (!quasi.tail) {
                  expressions.push(this.parseExpression());
                  quasi = this.parseTemplateElement();
                  quasis.push(quasi);
                }
                return this.finalize(node, new Node4.TemplateLiteral(quasis, expressions));
              };
              Parser5.prototype.reinterpretExpressionAsPattern = function(expr) {
                switch (expr.type) {
                  case syntax_1.Syntax.Identifier:
                  case syntax_1.Syntax.MemberExpression:
                  case syntax_1.Syntax.RestElement:
                  case syntax_1.Syntax.AssignmentPattern:
                    break;
                  case syntax_1.Syntax.SpreadElement:
                    expr.type = syntax_1.Syntax.RestElement;
                    this.reinterpretExpressionAsPattern(expr.argument);
                    break;
                  case syntax_1.Syntax.ArrayExpression:
                    expr.type = syntax_1.Syntax.ArrayPattern;
                    for (var i = 0; i < expr.elements.length; i++) {
                      if (expr.elements[i] !== null) {
                        this.reinterpretExpressionAsPattern(expr.elements[i]);
                      }
                    }
                    break;
                  case syntax_1.Syntax.ObjectExpression:
                    expr.type = syntax_1.Syntax.ObjectPattern;
                    for (var i = 0; i < expr.properties.length; i++) {
                      this.reinterpretExpressionAsPattern(expr.properties[i].value);
                    }
                    break;
                  case syntax_1.Syntax.AssignmentExpression:
                    expr.type = syntax_1.Syntax.AssignmentPattern;
                    delete expr.operator;
                    this.reinterpretExpressionAsPattern(expr.left);
                    break;
                  default:
                    break;
                }
              };
              Parser5.prototype.parseGroupExpression = function() {
                var expr;
                this.expect("(");
                if (this.match(")")) {
                  this.nextToken();
                  if (!this.match("=>")) {
                    this.expect("=>");
                  }
                  expr = {
                    type: ArrowParameterPlaceHolder,
                    params: [],
                    async: false
                  };
                } else {
                  var startToken = this.lookahead;
                  var params = [];
                  if (this.match("...")) {
                    expr = this.parseRestElement(params);
                    this.expect(")");
                    if (!this.match("=>")) {
                      this.expect("=>");
                    }
                    expr = {
                      type: ArrowParameterPlaceHolder,
                      params: [expr],
                      async: false
                    };
                  } else {
                    var arrow = false;
                    this.context.isBindingElement = true;
                    expr = this.inheritCoverGrammar(this.parseAssignmentExpression);
                    if (this.match(",")) {
                      var expressions = [];
                      this.context.isAssignmentTarget = false;
                      expressions.push(expr);
                      while (this.lookahead.type !== 2) {
                        if (!this.match(",")) {
                          break;
                        }
                        this.nextToken();
                        if (this.match(")")) {
                          this.nextToken();
                          for (var i = 0; i < expressions.length; i++) {
                            this.reinterpretExpressionAsPattern(expressions[i]);
                          }
                          arrow = true;
                          expr = {
                            type: ArrowParameterPlaceHolder,
                            params: expressions,
                            async: false
                          };
                        } else if (this.match("...")) {
                          if (!this.context.isBindingElement) {
                            this.throwUnexpectedToken(this.lookahead);
                          }
                          expressions.push(this.parseRestElement(params));
                          this.expect(")");
                          if (!this.match("=>")) {
                            this.expect("=>");
                          }
                          this.context.isBindingElement = false;
                          for (var i = 0; i < expressions.length; i++) {
                            this.reinterpretExpressionAsPattern(expressions[i]);
                          }
                          arrow = true;
                          expr = {
                            type: ArrowParameterPlaceHolder,
                            params: expressions,
                            async: false
                          };
                        } else {
                          expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
                        }
                        if (arrow) {
                          break;
                        }
                      }
                      if (!arrow) {
                        expr = this.finalize(this.startNode(startToken), new Node4.SequenceExpression(expressions));
                      }
                    }
                    if (!arrow) {
                      this.expect(")");
                      if (this.match("=>")) {
                        if (expr.type === syntax_1.Syntax.Identifier && expr.name === "yield") {
                          arrow = true;
                          expr = {
                            type: ArrowParameterPlaceHolder,
                            params: [expr],
                            async: false
                          };
                        }
                        if (!arrow) {
                          if (!this.context.isBindingElement) {
                            this.throwUnexpectedToken(this.lookahead);
                          }
                          if (expr.type === syntax_1.Syntax.SequenceExpression) {
                            for (var i = 0; i < expr.expressions.length; i++) {
                              this.reinterpretExpressionAsPattern(expr.expressions[i]);
                            }
                          } else {
                            this.reinterpretExpressionAsPattern(expr);
                          }
                          var parameters = expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr];
                          expr = {
                            type: ArrowParameterPlaceHolder,
                            params: parameters,
                            async: false
                          };
                        }
                      }
                      this.context.isBindingElement = false;
                    }
                  }
                }
                return expr;
              };
              Parser5.prototype.parseArguments = function() {
                this.expect("(");
                var args = [];
                if (!this.match(")")) {
                  while (true) {
                    var expr = this.match("...") ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAssignmentExpression);
                    args.push(expr);
                    if (this.match(")")) {
                      break;
                    }
                    this.expectCommaSeparator();
                    if (this.match(")")) {
                      break;
                    }
                  }
                }
                this.expect(")");
                return args;
              };
              Parser5.prototype.isIdentifierName = function(token2) {
                return token2.type === 3 || token2.type === 4 || token2.type === 1 || token2.type === 5;
              };
              Parser5.prototype.parseIdentifierName = function() {
                var node = this.createNode();
                var token2 = this.nextToken();
                if (!this.isIdentifierName(token2)) {
                  this.throwUnexpectedToken(token2);
                }
                return this.finalize(node, new Node4.Identifier(token2.value));
              };
              Parser5.prototype.parseNewExpression = function() {
                var node = this.createNode();
                var id = this.parseIdentifierName();
                assert_1.assert(id.name === "new", "New expression must start with `new`");
                var expr;
                if (this.match(".")) {
                  this.nextToken();
                  if (this.lookahead.type === 3 && this.context.inFunctionBody && this.lookahead.value === "target") {
                    var property = this.parseIdentifierName();
                    expr = new Node4.MetaProperty(id, property);
                  } else {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                } else {
                  var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression);
                  var args = this.match("(") ? this.parseArguments() : [];
                  expr = new Node4.NewExpression(callee, args);
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                }
                return this.finalize(node, expr);
              };
              Parser5.prototype.parseAsyncArgument = function() {
                var arg = this.parseAssignmentExpression();
                this.context.firstCoverInitializedNameError = null;
                return arg;
              };
              Parser5.prototype.parseAsyncArguments = function() {
                this.expect("(");
                var args = [];
                if (!this.match(")")) {
                  while (true) {
                    var expr = this.match("...") ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAsyncArgument);
                    args.push(expr);
                    if (this.match(")")) {
                      break;
                    }
                    this.expectCommaSeparator();
                    if (this.match(")")) {
                      break;
                    }
                  }
                }
                this.expect(")");
                return args;
              };
              Parser5.prototype.parseLeftHandSideExpressionAllowCall = function() {
                var startToken = this.lookahead;
                var maybeAsync = this.matchContextualKeyword("async");
                var previousAllowIn = this.context.allowIn;
                this.context.allowIn = true;
                var expr;
                if (this.matchKeyword("super") && this.context.inFunctionBody) {
                  expr = this.createNode();
                  this.nextToken();
                  expr = this.finalize(expr, new Node4.Super());
                  if (!this.match("(") && !this.match(".") && !this.match("[")) {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                } else {
                  expr = this.inheritCoverGrammar(this.matchKeyword("new") ? this.parseNewExpression : this.parsePrimaryExpression);
                }
                while (true) {
                  if (this.match(".")) {
                    this.context.isBindingElement = false;
                    this.context.isAssignmentTarget = true;
                    this.expect(".");
                    var property = this.parseIdentifierName();
                    expr = this.finalize(this.startNode(startToken), new Node4.StaticMemberExpression(expr, property));
                  } else if (this.match("(")) {
                    var asyncArrow = maybeAsync && startToken.lineNumber === this.lookahead.lineNumber;
                    this.context.isBindingElement = false;
                    this.context.isAssignmentTarget = false;
                    var args = asyncArrow ? this.parseAsyncArguments() : this.parseArguments();
                    expr = this.finalize(this.startNode(startToken), new Node4.CallExpression(expr, args));
                    if (asyncArrow && this.match("=>")) {
                      for (var i = 0; i < args.length; ++i) {
                        this.reinterpretExpressionAsPattern(args[i]);
                      }
                      expr = {
                        type: ArrowParameterPlaceHolder,
                        params: args,
                        async: true
                      };
                    }
                  } else if (this.match("[")) {
                    this.context.isBindingElement = false;
                    this.context.isAssignmentTarget = true;
                    this.expect("[");
                    var property = this.isolateCoverGrammar(this.parseExpression);
                    this.expect("]");
                    expr = this.finalize(this.startNode(startToken), new Node4.ComputedMemberExpression(expr, property));
                  } else if (this.lookahead.type === 10 && this.lookahead.head) {
                    var quasi = this.parseTemplateLiteral();
                    expr = this.finalize(this.startNode(startToken), new Node4.TaggedTemplateExpression(expr, quasi));
                  } else {
                    break;
                  }
                }
                this.context.allowIn = previousAllowIn;
                return expr;
              };
              Parser5.prototype.parseSuper = function() {
                var node = this.createNode();
                this.expectKeyword("super");
                if (!this.match("[") && !this.match(".")) {
                  this.throwUnexpectedToken(this.lookahead);
                }
                return this.finalize(node, new Node4.Super());
              };
              Parser5.prototype.parseLeftHandSideExpression = function() {
                assert_1.assert(this.context.allowIn, "callee of new expression always allow in keyword.");
                var node = this.startNode(this.lookahead);
                var expr = this.matchKeyword("super") && this.context.inFunctionBody ? this.parseSuper() : this.inheritCoverGrammar(this.matchKeyword("new") ? this.parseNewExpression : this.parsePrimaryExpression);
                while (true) {
                  if (this.match("[")) {
                    this.context.isBindingElement = false;
                    this.context.isAssignmentTarget = true;
                    this.expect("[");
                    var property = this.isolateCoverGrammar(this.parseExpression);
                    this.expect("]");
                    expr = this.finalize(node, new Node4.ComputedMemberExpression(expr, property));
                  } else if (this.match(".")) {
                    this.context.isBindingElement = false;
                    this.context.isAssignmentTarget = true;
                    this.expect(".");
                    var property = this.parseIdentifierName();
                    expr = this.finalize(node, new Node4.StaticMemberExpression(expr, property));
                  } else if (this.lookahead.type === 10 && this.lookahead.head) {
                    var quasi = this.parseTemplateLiteral();
                    expr = this.finalize(node, new Node4.TaggedTemplateExpression(expr, quasi));
                  } else {
                    break;
                  }
                }
                return expr;
              };
              Parser5.prototype.parseUpdateExpression = function() {
                var expr;
                var startToken = this.lookahead;
                if (this.match("++") || this.match("--")) {
                  var node = this.startNode(startToken);
                  var token2 = this.nextToken();
                  expr = this.inheritCoverGrammar(this.parseUnaryExpression);
                  if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
                    this.tolerateError(messages_1.Messages.StrictLHSPrefix);
                  }
                  if (!this.context.isAssignmentTarget) {
                    this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
                  }
                  var prefix = true;
                  expr = this.finalize(node, new Node4.UpdateExpression(token2.value, expr, prefix));
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                } else {
                  expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
                  if (!this.hasLineTerminator && this.lookahead.type === 7) {
                    if (this.match("++") || this.match("--")) {
                      if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
                        this.tolerateError(messages_1.Messages.StrictLHSPostfix);
                      }
                      if (!this.context.isAssignmentTarget) {
                        this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
                      }
                      this.context.isAssignmentTarget = false;
                      this.context.isBindingElement = false;
                      var operator2 = this.nextToken().value;
                      var prefix = false;
                      expr = this.finalize(this.startNode(startToken), new Node4.UpdateExpression(operator2, expr, prefix));
                    }
                  }
                }
                return expr;
              };
              Parser5.prototype.parseAwaitExpression = function() {
                var node = this.createNode();
                this.nextToken();
                var argument = this.parseUnaryExpression();
                return this.finalize(node, new Node4.AwaitExpression(argument));
              };
              Parser5.prototype.parseUnaryExpression = function() {
                var expr;
                if (this.match("+") || this.match("-") || this.match("~") || this.match("!") || this.matchKeyword("delete") || this.matchKeyword("void") || this.matchKeyword("typeof")) {
                  var node = this.startNode(this.lookahead);
                  var token2 = this.nextToken();
                  expr = this.inheritCoverGrammar(this.parseUnaryExpression);
                  expr = this.finalize(node, new Node4.UnaryExpression(token2.value, expr));
                  if (this.context.strict && expr.operator === "delete" && expr.argument.type === syntax_1.Syntax.Identifier) {
                    this.tolerateError(messages_1.Messages.StrictDelete);
                  }
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                } else if (this.context.await && this.matchContextualKeyword("await")) {
                  expr = this.parseAwaitExpression();
                } else {
                  expr = this.parseUpdateExpression();
                }
                return expr;
              };
              Parser5.prototype.parseExponentiationExpression = function() {
                var startToken = this.lookahead;
                var expr = this.inheritCoverGrammar(this.parseUnaryExpression);
                if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match("**")) {
                  this.nextToken();
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                  var left3 = expr;
                  var right3 = this.isolateCoverGrammar(this.parseExponentiationExpression);
                  expr = this.finalize(this.startNode(startToken), new Node4.BinaryExpression("**", left3, right3));
                }
                return expr;
              };
              Parser5.prototype.binaryPrecedence = function(token2) {
                var op = token2.value;
                var precedence;
                if (token2.type === 7) {
                  precedence = this.operatorPrecedence[op] || 0;
                } else if (token2.type === 4) {
                  precedence = op === "instanceof" || this.context.allowIn && op === "in" ? 7 : 0;
                } else {
                  precedence = 0;
                }
                return precedence;
              };
              Parser5.prototype.parseBinaryExpression = function() {
                var startToken = this.lookahead;
                var expr = this.inheritCoverGrammar(this.parseExponentiationExpression);
                var token2 = this.lookahead;
                var prec = this.binaryPrecedence(token2);
                if (prec > 0) {
                  this.nextToken();
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                  var markers = [startToken, this.lookahead];
                  var left3 = expr;
                  var right3 = this.isolateCoverGrammar(this.parseExponentiationExpression);
                  var stack = [left3, token2.value, right3];
                  var precedences = [prec];
                  while (true) {
                    prec = this.binaryPrecedence(this.lookahead);
                    if (prec <= 0) {
                      break;
                    }
                    while (stack.length > 2 && prec <= precedences[precedences.length - 1]) {
                      right3 = stack.pop();
                      var operator2 = stack.pop();
                      precedences.pop();
                      left3 = stack.pop();
                      markers.pop();
                      var node = this.startNode(markers[markers.length - 1]);
                      stack.push(this.finalize(node, new Node4.BinaryExpression(operator2, left3, right3)));
                    }
                    stack.push(this.nextToken().value);
                    precedences.push(prec);
                    markers.push(this.lookahead);
                    stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression));
                  }
                  var i = stack.length - 1;
                  expr = stack[i];
                  var lastMarker = markers.pop();
                  while (i > 1) {
                    var marker = markers.pop();
                    var lastLineStart = lastMarker && lastMarker.lineStart;
                    var node = this.startNode(marker, lastLineStart);
                    var operator2 = stack[i - 1];
                    expr = this.finalize(node, new Node4.BinaryExpression(operator2, stack[i - 2], expr));
                    i -= 2;
                    lastMarker = marker;
                  }
                }
                return expr;
              };
              Parser5.prototype.parseConditionalExpression = function() {
                var startToken = this.lookahead;
                var expr = this.inheritCoverGrammar(this.parseBinaryExpression);
                if (this.match("?")) {
                  this.nextToken();
                  var previousAllowIn = this.context.allowIn;
                  this.context.allowIn = true;
                  var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression);
                  this.context.allowIn = previousAllowIn;
                  this.expect(":");
                  var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression);
                  expr = this.finalize(this.startNode(startToken), new Node4.ConditionalExpression(expr, consequent, alternate));
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                }
                return expr;
              };
              Parser5.prototype.checkPatternParam = function(options2, param) {
                switch (param.type) {
                  case syntax_1.Syntax.Identifier:
                    this.validateParam(options2, param, param.name);
                    break;
                  case syntax_1.Syntax.RestElement:
                    this.checkPatternParam(options2, param.argument);
                    break;
                  case syntax_1.Syntax.AssignmentPattern:
                    this.checkPatternParam(options2, param.left);
                    break;
                  case syntax_1.Syntax.ArrayPattern:
                    for (var i = 0; i < param.elements.length; i++) {
                      if (param.elements[i] !== null) {
                        this.checkPatternParam(options2, param.elements[i]);
                      }
                    }
                    break;
                  case syntax_1.Syntax.ObjectPattern:
                    for (var i = 0; i < param.properties.length; i++) {
                      this.checkPatternParam(options2, param.properties[i].value);
                    }
                    break;
                  default:
                    break;
                }
                options2.simple = options2.simple && param instanceof Node4.Identifier;
              };
              Parser5.prototype.reinterpretAsCoverFormalsList = function(expr) {
                var params = [expr];
                var options2;
                var asyncArrow = false;
                switch (expr.type) {
                  case syntax_1.Syntax.Identifier:
                    break;
                  case ArrowParameterPlaceHolder:
                    params = expr.params;
                    asyncArrow = expr.async;
                    break;
                  default:
                    return null;
                }
                options2 = {
                  simple: true,
                  paramSet: {}
                };
                for (var i = 0; i < params.length; ++i) {
                  var param = params[i];
                  if (param.type === syntax_1.Syntax.AssignmentPattern) {
                    if (param.right.type === syntax_1.Syntax.YieldExpression) {
                      if (param.right.argument) {
                        this.throwUnexpectedToken(this.lookahead);
                      }
                      param.right.type = syntax_1.Syntax.Identifier;
                      param.right.name = "yield";
                      delete param.right.argument;
                      delete param.right.delegate;
                    }
                  } else if (asyncArrow && param.type === syntax_1.Syntax.Identifier && param.name === "await") {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                  this.checkPatternParam(options2, param);
                  params[i] = param;
                }
                if (this.context.strict || !this.context.allowYield) {
                  for (var i = 0; i < params.length; ++i) {
                    var param = params[i];
                    if (param.type === syntax_1.Syntax.YieldExpression) {
                      this.throwUnexpectedToken(this.lookahead);
                    }
                  }
                }
                if (options2.message === messages_1.Messages.StrictParamDupe) {
                  var token2 = this.context.strict ? options2.stricted : options2.firstRestricted;
                  this.throwUnexpectedToken(token2, options2.message);
                }
                return {
                  simple: options2.simple,
                  params,
                  stricted: options2.stricted,
                  firstRestricted: options2.firstRestricted,
                  message: options2.message
                };
              };
              Parser5.prototype.parseAssignmentExpression = function() {
                var expr;
                if (!this.context.allowYield && this.matchKeyword("yield")) {
                  expr = this.parseYieldExpression();
                } else {
                  var startToken = this.lookahead;
                  var token2 = startToken;
                  expr = this.parseConditionalExpression();
                  if (token2.type === 3 && token2.lineNumber === this.lookahead.lineNumber && token2.value === "async") {
                    if (this.lookahead.type === 3 || this.matchKeyword("yield")) {
                      var arg = this.parsePrimaryExpression();
                      this.reinterpretExpressionAsPattern(arg);
                      expr = {
                        type: ArrowParameterPlaceHolder,
                        params: [arg],
                        async: true
                      };
                    }
                  }
                  if (expr.type === ArrowParameterPlaceHolder || this.match("=>")) {
                    this.context.isAssignmentTarget = false;
                    this.context.isBindingElement = false;
                    var isAsync2 = expr.async;
                    var list3 = this.reinterpretAsCoverFormalsList(expr);
                    if (list3) {
                      if (this.hasLineTerminator) {
                        this.tolerateUnexpectedToken(this.lookahead);
                      }
                      this.context.firstCoverInitializedNameError = null;
                      var previousStrict = this.context.strict;
                      var previousAllowStrictDirective = this.context.allowStrictDirective;
                      this.context.allowStrictDirective = list3.simple;
                      var previousAllowYield = this.context.allowYield;
                      var previousAwait = this.context.await;
                      this.context.allowYield = true;
                      this.context.await = isAsync2;
                      var node = this.startNode(startToken);
                      this.expect("=>");
                      var body = void 0;
                      if (this.match("{")) {
                        var previousAllowIn = this.context.allowIn;
                        this.context.allowIn = true;
                        body = this.parseFunctionSourceElements();
                        this.context.allowIn = previousAllowIn;
                      } else {
                        body = this.isolateCoverGrammar(this.parseAssignmentExpression);
                      }
                      var expression = body.type !== syntax_1.Syntax.BlockStatement;
                      if (this.context.strict && list3.firstRestricted) {
                        this.throwUnexpectedToken(list3.firstRestricted, list3.message);
                      }
                      if (this.context.strict && list3.stricted) {
                        this.tolerateUnexpectedToken(list3.stricted, list3.message);
                      }
                      expr = isAsync2 ? this.finalize(node, new Node4.AsyncArrowFunctionExpression(list3.params, body, expression)) : this.finalize(node, new Node4.ArrowFunctionExpression(list3.params, body, expression));
                      this.context.strict = previousStrict;
                      this.context.allowStrictDirective = previousAllowStrictDirective;
                      this.context.allowYield = previousAllowYield;
                      this.context.await = previousAwait;
                    }
                  } else {
                    if (this.matchAssign()) {
                      if (!this.context.isAssignmentTarget) {
                        this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
                      }
                      if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) {
                        var id = expr;
                        if (this.scanner.isRestrictedWord(id.name)) {
                          this.tolerateUnexpectedToken(token2, messages_1.Messages.StrictLHSAssignment);
                        }
                        if (this.scanner.isStrictModeReservedWord(id.name)) {
                          this.tolerateUnexpectedToken(token2, messages_1.Messages.StrictReservedWord);
                        }
                      }
                      if (!this.match("=")) {
                        this.context.isAssignmentTarget = false;
                        this.context.isBindingElement = false;
                      } else {
                        this.reinterpretExpressionAsPattern(expr);
                      }
                      token2 = this.nextToken();
                      var operator2 = token2.value;
                      var right3 = this.isolateCoverGrammar(this.parseAssignmentExpression);
                      expr = this.finalize(this.startNode(startToken), new Node4.AssignmentExpression(operator2, expr, right3));
                      this.context.firstCoverInitializedNameError = null;
                    }
                  }
                }
                return expr;
              };
              Parser5.prototype.parseExpression = function() {
                var startToken = this.lookahead;
                var expr = this.isolateCoverGrammar(this.parseAssignmentExpression);
                if (this.match(",")) {
                  var expressions = [];
                  expressions.push(expr);
                  while (this.lookahead.type !== 2) {
                    if (!this.match(",")) {
                      break;
                    }
                    this.nextToken();
                    expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
                  }
                  expr = this.finalize(this.startNode(startToken), new Node4.SequenceExpression(expressions));
                }
                return expr;
              };
              Parser5.prototype.parseStatementListItem = function() {
                var statement;
                this.context.isAssignmentTarget = true;
                this.context.isBindingElement = true;
                if (this.lookahead.type === 4) {
                  switch (this.lookahead.value) {
                    case "export":
                      if (!this.context.isModule) {
                        this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration);
                      }
                      statement = this.parseExportDeclaration();
                      break;
                    case "import":
                      if (!this.context.isModule) {
                        this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration);
                      }
                      statement = this.parseImportDeclaration();
                      break;
                    case "const":
                      statement = this.parseLexicalDeclaration({ inFor: false });
                      break;
                    case "function":
                      statement = this.parseFunctionDeclaration();
                      break;
                    case "class":
                      statement = this.parseClassDeclaration();
                      break;
                    case "let":
                      statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement();
                      break;
                    default:
                      statement = this.parseStatement();
                      break;
                  }
                } else {
                  statement = this.parseStatement();
                }
                return statement;
              };
              Parser5.prototype.parseBlock = function() {
                var node = this.createNode();
                this.expect("{");
                var block2 = [];
                while (true) {
                  if (this.match("}")) {
                    break;
                  }
                  block2.push(this.parseStatementListItem());
                }
                this.expect("}");
                return this.finalize(node, new Node4.BlockStatement(block2));
              };
              Parser5.prototype.parseLexicalBinding = function(kind, options2) {
                var node = this.createNode();
                var params = [];
                var id = this.parsePattern(params, kind);
                if (this.context.strict && id.type === syntax_1.Syntax.Identifier) {
                  if (this.scanner.isRestrictedWord(id.name)) {
                    this.tolerateError(messages_1.Messages.StrictVarName);
                  }
                }
                var init = null;
                if (kind === "const") {
                  if (!this.matchKeyword("in") && !this.matchContextualKeyword("of")) {
                    if (this.match("=")) {
                      this.nextToken();
                      init = this.isolateCoverGrammar(this.parseAssignmentExpression);
                    } else {
                      this.throwError(messages_1.Messages.DeclarationMissingInitializer, "const");
                    }
                  }
                } else if (!options2.inFor && id.type !== syntax_1.Syntax.Identifier || this.match("=")) {
                  this.expect("=");
                  init = this.isolateCoverGrammar(this.parseAssignmentExpression);
                }
                return this.finalize(node, new Node4.VariableDeclarator(id, init));
              };
              Parser5.prototype.parseBindingList = function(kind, options2) {
                var list3 = [this.parseLexicalBinding(kind, options2)];
                while (this.match(",")) {
                  this.nextToken();
                  list3.push(this.parseLexicalBinding(kind, options2));
                }
                return list3;
              };
              Parser5.prototype.isLexicalDeclaration = function() {
                var state = this.scanner.saveState();
                this.scanner.scanComments();
                var next = this.scanner.lex();
                this.scanner.restoreState(state);
                return next.type === 3 || next.type === 7 && next.value === "[" || next.type === 7 && next.value === "{" || next.type === 4 && next.value === "let" || next.type === 4 && next.value === "yield";
              };
              Parser5.prototype.parseLexicalDeclaration = function(options2) {
                var node = this.createNode();
                var kind = this.nextToken().value;
                assert_1.assert(kind === "let" || kind === "const", "Lexical declaration must be either let or const");
                var declarations = this.parseBindingList(kind, options2);
                this.consumeSemicolon();
                return this.finalize(node, new Node4.VariableDeclaration(declarations, kind));
              };
              Parser5.prototype.parseBindingRestElement = function(params, kind) {
                var node = this.createNode();
                this.expect("...");
                var arg = this.parsePattern(params, kind);
                return this.finalize(node, new Node4.RestElement(arg));
              };
              Parser5.prototype.parseArrayPattern = function(params, kind) {
                var node = this.createNode();
                this.expect("[");
                var elements = [];
                while (!this.match("]")) {
                  if (this.match(",")) {
                    this.nextToken();
                    elements.push(null);
                  } else {
                    if (this.match("...")) {
                      elements.push(this.parseBindingRestElement(params, kind));
                      break;
                    } else {
                      elements.push(this.parsePatternWithDefault(params, kind));
                    }
                    if (!this.match("]")) {
                      this.expect(",");
                    }
                  }
                }
                this.expect("]");
                return this.finalize(node, new Node4.ArrayPattern(elements));
              };
              Parser5.prototype.parsePropertyPattern = function(params, kind) {
                var node = this.createNode();
                var computed = false;
                var shorthand = false;
                var method = false;
                var key;
                var value;
                if (this.lookahead.type === 3) {
                  var keyToken = this.lookahead;
                  key = this.parseVariableIdentifier();
                  var init = this.finalize(node, new Node4.Identifier(keyToken.value));
                  if (this.match("=")) {
                    params.push(keyToken);
                    shorthand = true;
                    this.nextToken();
                    var expr = this.parseAssignmentExpression();
                    value = this.finalize(this.startNode(keyToken), new Node4.AssignmentPattern(init, expr));
                  } else if (!this.match(":")) {
                    params.push(keyToken);
                    shorthand = true;
                    value = init;
                  } else {
                    this.expect(":");
                    value = this.parsePatternWithDefault(params, kind);
                  }
                } else {
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  this.expect(":");
                  value = this.parsePatternWithDefault(params, kind);
                }
                return this.finalize(node, new Node4.Property("init", key, computed, value, method, shorthand));
              };
              Parser5.prototype.parseObjectPattern = function(params, kind) {
                var node = this.createNode();
                var properties = [];
                this.expect("{");
                while (!this.match("}")) {
                  properties.push(this.parsePropertyPattern(params, kind));
                  if (!this.match("}")) {
                    this.expect(",");
                  }
                }
                this.expect("}");
                return this.finalize(node, new Node4.ObjectPattern(properties));
              };
              Parser5.prototype.parsePattern = function(params, kind) {
                var pattern;
                if (this.match("[")) {
                  pattern = this.parseArrayPattern(params, kind);
                } else if (this.match("{")) {
                  pattern = this.parseObjectPattern(params, kind);
                } else {
                  if (this.matchKeyword("let") && (kind === "const" || kind === "let")) {
                    this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding);
                  }
                  params.push(this.lookahead);
                  pattern = this.parseVariableIdentifier(kind);
                }
                return pattern;
              };
              Parser5.prototype.parsePatternWithDefault = function(params, kind) {
                var startToken = this.lookahead;
                var pattern = this.parsePattern(params, kind);
                if (this.match("=")) {
                  this.nextToken();
                  var previousAllowYield = this.context.allowYield;
                  this.context.allowYield = true;
                  var right3 = this.isolateCoverGrammar(this.parseAssignmentExpression);
                  this.context.allowYield = previousAllowYield;
                  pattern = this.finalize(this.startNode(startToken), new Node4.AssignmentPattern(pattern, right3));
                }
                return pattern;
              };
              Parser5.prototype.parseVariableIdentifier = function(kind) {
                var node = this.createNode();
                var token2 = this.nextToken();
                if (token2.type === 4 && token2.value === "yield") {
                  if (this.context.strict) {
                    this.tolerateUnexpectedToken(token2, messages_1.Messages.StrictReservedWord);
                  } else if (!this.context.allowYield) {
                    this.throwUnexpectedToken(token2);
                  }
                } else if (token2.type !== 3) {
                  if (this.context.strict && token2.type === 4 && this.scanner.isStrictModeReservedWord(token2.value)) {
                    this.tolerateUnexpectedToken(token2, messages_1.Messages.StrictReservedWord);
                  } else {
                    if (this.context.strict || token2.value !== "let" || kind !== "var") {
                      this.throwUnexpectedToken(token2);
                    }
                  }
                } else if ((this.context.isModule || this.context.await) && token2.type === 3 && token2.value === "await") {
                  this.tolerateUnexpectedToken(token2);
                }
                return this.finalize(node, new Node4.Identifier(token2.value));
              };
              Parser5.prototype.parseVariableDeclaration = function(options2) {
                var node = this.createNode();
                var params = [];
                var id = this.parsePattern(params, "var");
                if (this.context.strict && id.type === syntax_1.Syntax.Identifier) {
                  if (this.scanner.isRestrictedWord(id.name)) {
                    this.tolerateError(messages_1.Messages.StrictVarName);
                  }
                }
                var init = null;
                if (this.match("=")) {
                  this.nextToken();
                  init = this.isolateCoverGrammar(this.parseAssignmentExpression);
                } else if (id.type !== syntax_1.Syntax.Identifier && !options2.inFor) {
                  this.expect("=");
                }
                return this.finalize(node, new Node4.VariableDeclarator(id, init));
              };
              Parser5.prototype.parseVariableDeclarationList = function(options2) {
                var opt = { inFor: options2.inFor };
                var list3 = [];
                list3.push(this.parseVariableDeclaration(opt));
                while (this.match(",")) {
                  this.nextToken();
                  list3.push(this.parseVariableDeclaration(opt));
                }
                return list3;
              };
              Parser5.prototype.parseVariableStatement = function() {
                var node = this.createNode();
                this.expectKeyword("var");
                var declarations = this.parseVariableDeclarationList({ inFor: false });
                this.consumeSemicolon();
                return this.finalize(node, new Node4.VariableDeclaration(declarations, "var"));
              };
              Parser5.prototype.parseEmptyStatement = function() {
                var node = this.createNode();
                this.expect(";");
                return this.finalize(node, new Node4.EmptyStatement());
              };
              Parser5.prototype.parseExpressionStatement = function() {
                var node = this.createNode();
                var expr = this.parseExpression();
                this.consumeSemicolon();
                return this.finalize(node, new Node4.ExpressionStatement(expr));
              };
              Parser5.prototype.parseIfClause = function() {
                if (this.context.strict && this.matchKeyword("function")) {
                  this.tolerateError(messages_1.Messages.StrictFunction);
                }
                return this.parseStatement();
              };
              Parser5.prototype.parseIfStatement = function() {
                var node = this.createNode();
                var consequent;
                var alternate = null;
                this.expectKeyword("if");
                this.expect("(");
                var test = this.parseExpression();
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                  consequent = this.finalize(this.createNode(), new Node4.EmptyStatement());
                } else {
                  this.expect(")");
                  consequent = this.parseIfClause();
                  if (this.matchKeyword("else")) {
                    this.nextToken();
                    alternate = this.parseIfClause();
                  }
                }
                return this.finalize(node, new Node4.IfStatement(test, consequent, alternate));
              };
              Parser5.prototype.parseDoWhileStatement = function() {
                var node = this.createNode();
                this.expectKeyword("do");
                var previousInIteration = this.context.inIteration;
                this.context.inIteration = true;
                var body = this.parseStatement();
                this.context.inIteration = previousInIteration;
                this.expectKeyword("while");
                this.expect("(");
                var test = this.parseExpression();
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                } else {
                  this.expect(")");
                  if (this.match(";")) {
                    this.nextToken();
                  }
                }
                return this.finalize(node, new Node4.DoWhileStatement(body, test));
              };
              Parser5.prototype.parseWhileStatement = function() {
                var node = this.createNode();
                var body;
                this.expectKeyword("while");
                this.expect("(");
                var test = this.parseExpression();
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                  body = this.finalize(this.createNode(), new Node4.EmptyStatement());
                } else {
                  this.expect(")");
                  var previousInIteration = this.context.inIteration;
                  this.context.inIteration = true;
                  body = this.parseStatement();
                  this.context.inIteration = previousInIteration;
                }
                return this.finalize(node, new Node4.WhileStatement(test, body));
              };
              Parser5.prototype.parseForStatement = function() {
                var init = null;
                var test = null;
                var update2 = null;
                var forIn = true;
                var left3, right3;
                var node = this.createNode();
                this.expectKeyword("for");
                this.expect("(");
                if (this.match(";")) {
                  this.nextToken();
                } else {
                  if (this.matchKeyword("var")) {
                    init = this.createNode();
                    this.nextToken();
                    var previousAllowIn = this.context.allowIn;
                    this.context.allowIn = false;
                    var declarations = this.parseVariableDeclarationList({ inFor: true });
                    this.context.allowIn = previousAllowIn;
                    if (declarations.length === 1 && this.matchKeyword("in")) {
                      var decl = declarations[0];
                      if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) {
                        this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, "for-in");
                      }
                      init = this.finalize(init, new Node4.VariableDeclaration(declarations, "var"));
                      this.nextToken();
                      left3 = init;
                      right3 = this.parseExpression();
                      init = null;
                    } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword("of")) {
                      init = this.finalize(init, new Node4.VariableDeclaration(declarations, "var"));
                      this.nextToken();
                      left3 = init;
                      right3 = this.parseAssignmentExpression();
                      init = null;
                      forIn = false;
                    } else {
                      init = this.finalize(init, new Node4.VariableDeclaration(declarations, "var"));
                      this.expect(";");
                    }
                  } else if (this.matchKeyword("const") || this.matchKeyword("let")) {
                    init = this.createNode();
                    var kind = this.nextToken().value;
                    if (!this.context.strict && this.lookahead.value === "in") {
                      init = this.finalize(init, new Node4.Identifier(kind));
                      this.nextToken();
                      left3 = init;
                      right3 = this.parseExpression();
                      init = null;
                    } else {
                      var previousAllowIn = this.context.allowIn;
                      this.context.allowIn = false;
                      var declarations = this.parseBindingList(kind, { inFor: true });
                      this.context.allowIn = previousAllowIn;
                      if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword("in")) {
                        init = this.finalize(init, new Node4.VariableDeclaration(declarations, kind));
                        this.nextToken();
                        left3 = init;
                        right3 = this.parseExpression();
                        init = null;
                      } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword("of")) {
                        init = this.finalize(init, new Node4.VariableDeclaration(declarations, kind));
                        this.nextToken();
                        left3 = init;
                        right3 = this.parseAssignmentExpression();
                        init = null;
                        forIn = false;
                      } else {
                        this.consumeSemicolon();
                        init = this.finalize(init, new Node4.VariableDeclaration(declarations, kind));
                      }
                    }
                  } else {
                    var initStartToken = this.lookahead;
                    var previousAllowIn = this.context.allowIn;
                    this.context.allowIn = false;
                    init = this.inheritCoverGrammar(this.parseAssignmentExpression);
                    this.context.allowIn = previousAllowIn;
                    if (this.matchKeyword("in")) {
                      if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) {
                        this.tolerateError(messages_1.Messages.InvalidLHSInForIn);
                      }
                      this.nextToken();
                      this.reinterpretExpressionAsPattern(init);
                      left3 = init;
                      right3 = this.parseExpression();
                      init = null;
                    } else if (this.matchContextualKeyword("of")) {
                      if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) {
                        this.tolerateError(messages_1.Messages.InvalidLHSInForLoop);
                      }
                      this.nextToken();
                      this.reinterpretExpressionAsPattern(init);
                      left3 = init;
                      right3 = this.parseAssignmentExpression();
                      init = null;
                      forIn = false;
                    } else {
                      if (this.match(",")) {
                        var initSeq = [init];
                        while (this.match(",")) {
                          this.nextToken();
                          initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
                        }
                        init = this.finalize(this.startNode(initStartToken), new Node4.SequenceExpression(initSeq));
                      }
                      this.expect(";");
                    }
                  }
                }
                if (typeof left3 === "undefined") {
                  if (!this.match(";")) {
                    test = this.parseExpression();
                  }
                  this.expect(";");
                  if (!this.match(")")) {
                    update2 = this.parseExpression();
                  }
                }
                var body;
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                  body = this.finalize(this.createNode(), new Node4.EmptyStatement());
                } else {
                  this.expect(")");
                  var previousInIteration = this.context.inIteration;
                  this.context.inIteration = true;
                  body = this.isolateCoverGrammar(this.parseStatement);
                  this.context.inIteration = previousInIteration;
                }
                return typeof left3 === "undefined" ? this.finalize(node, new Node4.ForStatement(init, test, update2, body)) : forIn ? this.finalize(node, new Node4.ForInStatement(left3, right3, body)) : this.finalize(node, new Node4.ForOfStatement(left3, right3, body));
              };
              Parser5.prototype.parseContinueStatement = function() {
                var node = this.createNode();
                this.expectKeyword("continue");
                var label = null;
                if (this.lookahead.type === 3 && !this.hasLineTerminator) {
                  var id = this.parseVariableIdentifier();
                  label = id;
                  var key = "$" + id.name;
                  if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
                    this.throwError(messages_1.Messages.UnknownLabel, id.name);
                  }
                }
                this.consumeSemicolon();
                if (label === null && !this.context.inIteration) {
                  this.throwError(messages_1.Messages.IllegalContinue);
                }
                return this.finalize(node, new Node4.ContinueStatement(label));
              };
              Parser5.prototype.parseBreakStatement = function() {
                var node = this.createNode();
                this.expectKeyword("break");
                var label = null;
                if (this.lookahead.type === 3 && !this.hasLineTerminator) {
                  var id = this.parseVariableIdentifier();
                  var key = "$" + id.name;
                  if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
                    this.throwError(messages_1.Messages.UnknownLabel, id.name);
                  }
                  label = id;
                }
                this.consumeSemicolon();
                if (label === null && !this.context.inIteration && !this.context.inSwitch) {
                  this.throwError(messages_1.Messages.IllegalBreak);
                }
                return this.finalize(node, new Node4.BreakStatement(label));
              };
              Parser5.prototype.parseReturnStatement = function() {
                if (!this.context.inFunctionBody) {
                  this.tolerateError(messages_1.Messages.IllegalReturn);
                }
                var node = this.createNode();
                this.expectKeyword("return");
                var hasArgument = !this.match(";") && !this.match("}") && !this.hasLineTerminator && this.lookahead.type !== 2 || this.lookahead.type === 8 || this.lookahead.type === 10;
                var argument = hasArgument ? this.parseExpression() : null;
                this.consumeSemicolon();
                return this.finalize(node, new Node4.ReturnStatement(argument));
              };
              Parser5.prototype.parseWithStatement = function() {
                if (this.context.strict) {
                  this.tolerateError(messages_1.Messages.StrictModeWith);
                }
                var node = this.createNode();
                var body;
                this.expectKeyword("with");
                this.expect("(");
                var object = this.parseExpression();
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                  body = this.finalize(this.createNode(), new Node4.EmptyStatement());
                } else {
                  this.expect(")");
                  body = this.parseStatement();
                }
                return this.finalize(node, new Node4.WithStatement(object, body));
              };
              Parser5.prototype.parseSwitchCase = function() {
                var node = this.createNode();
                var test;
                if (this.matchKeyword("default")) {
                  this.nextToken();
                  test = null;
                } else {
                  this.expectKeyword("case");
                  test = this.parseExpression();
                }
                this.expect(":");
                var consequent = [];
                while (true) {
                  if (this.match("}") || this.matchKeyword("default") || this.matchKeyword("case")) {
                    break;
                  }
                  consequent.push(this.parseStatementListItem());
                }
                return this.finalize(node, new Node4.SwitchCase(test, consequent));
              };
              Parser5.prototype.parseSwitchStatement = function() {
                var node = this.createNode();
                this.expectKeyword("switch");
                this.expect("(");
                var discriminant = this.parseExpression();
                this.expect(")");
                var previousInSwitch = this.context.inSwitch;
                this.context.inSwitch = true;
                var cases = [];
                var defaultFound = false;
                this.expect("{");
                while (true) {
                  if (this.match("}")) {
                    break;
                  }
                  var clause = this.parseSwitchCase();
                  if (clause.test === null) {
                    if (defaultFound) {
                      this.throwError(messages_1.Messages.MultipleDefaultsInSwitch);
                    }
                    defaultFound = true;
                  }
                  cases.push(clause);
                }
                this.expect("}");
                this.context.inSwitch = previousInSwitch;
                return this.finalize(node, new Node4.SwitchStatement(discriminant, cases));
              };
              Parser5.prototype.parseLabelledStatement = function() {
                var node = this.createNode();
                var expr = this.parseExpression();
                var statement;
                if (expr.type === syntax_1.Syntax.Identifier && this.match(":")) {
                  this.nextToken();
                  var id = expr;
                  var key = "$" + id.name;
                  if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
                    this.throwError(messages_1.Messages.Redeclaration, "Label", id.name);
                  }
                  this.context.labelSet[key] = true;
                  var body = void 0;
                  if (this.matchKeyword("class")) {
                    this.tolerateUnexpectedToken(this.lookahead);
                    body = this.parseClassDeclaration();
                  } else if (this.matchKeyword("function")) {
                    var token2 = this.lookahead;
                    var declaration = this.parseFunctionDeclaration();
                    if (this.context.strict) {
                      this.tolerateUnexpectedToken(token2, messages_1.Messages.StrictFunction);
                    } else if (declaration.generator) {
                      this.tolerateUnexpectedToken(token2, messages_1.Messages.GeneratorInLegacyContext);
                    }
                    body = declaration;
                  } else {
                    body = this.parseStatement();
                  }
                  delete this.context.labelSet[key];
                  statement = new Node4.LabeledStatement(id, body);
                } else {
                  this.consumeSemicolon();
                  statement = new Node4.ExpressionStatement(expr);
                }
                return this.finalize(node, statement);
              };
              Parser5.prototype.parseThrowStatement = function() {
                var node = this.createNode();
                this.expectKeyword("throw");
                if (this.hasLineTerminator) {
                  this.throwError(messages_1.Messages.NewlineAfterThrow);
                }
                var argument = this.parseExpression();
                this.consumeSemicolon();
                return this.finalize(node, new Node4.ThrowStatement(argument));
              };
              Parser5.prototype.parseCatchClause = function() {
                var node = this.createNode();
                this.expectKeyword("catch");
                this.expect("(");
                if (this.match(")")) {
                  this.throwUnexpectedToken(this.lookahead);
                }
                var params = [];
                var param = this.parsePattern(params);
                var paramMap = {};
                for (var i = 0; i < params.length; i++) {
                  var key = "$" + params[i].value;
                  if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
                    this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value);
                  }
                  paramMap[key] = true;
                }
                if (this.context.strict && param.type === syntax_1.Syntax.Identifier) {
                  if (this.scanner.isRestrictedWord(param.name)) {
                    this.tolerateError(messages_1.Messages.StrictCatchVariable);
                  }
                }
                this.expect(")");
                var body = this.parseBlock();
                return this.finalize(node, new Node4.CatchClause(param, body));
              };
              Parser5.prototype.parseFinallyClause = function() {
                this.expectKeyword("finally");
                return this.parseBlock();
              };
              Parser5.prototype.parseTryStatement = function() {
                var node = this.createNode();
                this.expectKeyword("try");
                var block2 = this.parseBlock();
                var handler = this.matchKeyword("catch") ? this.parseCatchClause() : null;
                var finalizer = this.matchKeyword("finally") ? this.parseFinallyClause() : null;
                if (!handler && !finalizer) {
                  this.throwError(messages_1.Messages.NoCatchOrFinally);
                }
                return this.finalize(node, new Node4.TryStatement(block2, handler, finalizer));
              };
              Parser5.prototype.parseDebuggerStatement = function() {
                var node = this.createNode();
                this.expectKeyword("debugger");
                this.consumeSemicolon();
                return this.finalize(node, new Node4.DebuggerStatement());
              };
              Parser5.prototype.parseStatement = function() {
                var statement;
                switch (this.lookahead.type) {
                  case 1:
                  case 5:
                  case 6:
                  case 8:
                  case 10:
                  case 9:
                    statement = this.parseExpressionStatement();
                    break;
                  case 7:
                    var value = this.lookahead.value;
                    if (value === "{") {
                      statement = this.parseBlock();
                    } else if (value === "(") {
                      statement = this.parseExpressionStatement();
                    } else if (value === ";") {
                      statement = this.parseEmptyStatement();
                    } else {
                      statement = this.parseExpressionStatement();
                    }
                    break;
                  case 3:
                    statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement();
                    break;
                  case 4:
                    switch (this.lookahead.value) {
                      case "break":
                        statement = this.parseBreakStatement();
                        break;
                      case "continue":
                        statement = this.parseContinueStatement();
                        break;
                      case "debugger":
                        statement = this.parseDebuggerStatement();
                        break;
                      case "do":
                        statement = this.parseDoWhileStatement();
                        break;
                      case "for":
                        statement = this.parseForStatement();
                        break;
                      case "function":
                        statement = this.parseFunctionDeclaration();
                        break;
                      case "if":
                        statement = this.parseIfStatement();
                        break;
                      case "return":
                        statement = this.parseReturnStatement();
                        break;
                      case "switch":
                        statement = this.parseSwitchStatement();
                        break;
                      case "throw":
                        statement = this.parseThrowStatement();
                        break;
                      case "try":
                        statement = this.parseTryStatement();
                        break;
                      case "var":
                        statement = this.parseVariableStatement();
                        break;
                      case "while":
                        statement = this.parseWhileStatement();
                        break;
                      case "with":
                        statement = this.parseWithStatement();
                        break;
                      default:
                        statement = this.parseExpressionStatement();
                        break;
                    }
                    break;
                  default:
                    statement = this.throwUnexpectedToken(this.lookahead);
                }
                return statement;
              };
              Parser5.prototype.parseFunctionSourceElements = function() {
                var node = this.createNode();
                this.expect("{");
                var body = this.parseDirectivePrologues();
                var previousLabelSet = this.context.labelSet;
                var previousInIteration = this.context.inIteration;
                var previousInSwitch = this.context.inSwitch;
                var previousInFunctionBody = this.context.inFunctionBody;
                this.context.labelSet = {};
                this.context.inIteration = false;
                this.context.inSwitch = false;
                this.context.inFunctionBody = true;
                while (this.lookahead.type !== 2) {
                  if (this.match("}")) {
                    break;
                  }
                  body.push(this.parseStatementListItem());
                }
                this.expect("}");
                this.context.labelSet = previousLabelSet;
                this.context.inIteration = previousInIteration;
                this.context.inSwitch = previousInSwitch;
                this.context.inFunctionBody = previousInFunctionBody;
                return this.finalize(node, new Node4.BlockStatement(body));
              };
              Parser5.prototype.validateParam = function(options2, param, name3) {
                var key = "$" + name3;
                if (this.context.strict) {
                  if (this.scanner.isRestrictedWord(name3)) {
                    options2.stricted = param;
                    options2.message = messages_1.Messages.StrictParamName;
                  }
                  if (Object.prototype.hasOwnProperty.call(options2.paramSet, key)) {
                    options2.stricted = param;
                    options2.message = messages_1.Messages.StrictParamDupe;
                  }
                } else if (!options2.firstRestricted) {
                  if (this.scanner.isRestrictedWord(name3)) {
                    options2.firstRestricted = param;
                    options2.message = messages_1.Messages.StrictParamName;
                  } else if (this.scanner.isStrictModeReservedWord(name3)) {
                    options2.firstRestricted = param;
                    options2.message = messages_1.Messages.StrictReservedWord;
                  } else if (Object.prototype.hasOwnProperty.call(options2.paramSet, key)) {
                    options2.stricted = param;
                    options2.message = messages_1.Messages.StrictParamDupe;
                  }
                }
                if (typeof Object.defineProperty === "function") {
                  Object.defineProperty(options2.paramSet, key, { value: true, enumerable: true, writable: true, configurable: true });
                } else {
                  options2.paramSet[key] = true;
                }
              };
              Parser5.prototype.parseRestElement = function(params) {
                var node = this.createNode();
                this.expect("...");
                var arg = this.parsePattern(params);
                if (this.match("=")) {
                  this.throwError(messages_1.Messages.DefaultRestParameter);
                }
                if (!this.match(")")) {
                  this.throwError(messages_1.Messages.ParameterAfterRestParameter);
                }
                return this.finalize(node, new Node4.RestElement(arg));
              };
              Parser5.prototype.parseFormalParameter = function(options2) {
                var params = [];
                var param = this.match("...") ? this.parseRestElement(params) : this.parsePatternWithDefault(params);
                for (var i = 0; i < params.length; i++) {
                  this.validateParam(options2, params[i], params[i].value);
                }
                options2.simple = options2.simple && param instanceof Node4.Identifier;
                options2.params.push(param);
              };
              Parser5.prototype.parseFormalParameters = function(firstRestricted) {
                var options2;
                options2 = {
                  simple: true,
                  params: [],
                  firstRestricted
                };
                this.expect("(");
                if (!this.match(")")) {
                  options2.paramSet = {};
                  while (this.lookahead.type !== 2) {
                    this.parseFormalParameter(options2);
                    if (this.match(")")) {
                      break;
                    }
                    this.expect(",");
                    if (this.match(")")) {
                      break;
                    }
                  }
                }
                this.expect(")");
                return {
                  simple: options2.simple,
                  params: options2.params,
                  stricted: options2.stricted,
                  firstRestricted: options2.firstRestricted,
                  message: options2.message
                };
              };
              Parser5.prototype.matchAsyncFunction = function() {
                var match2 = this.matchContextualKeyword("async");
                if (match2) {
                  var state = this.scanner.saveState();
                  this.scanner.scanComments();
                  var next = this.scanner.lex();
                  this.scanner.restoreState(state);
                  match2 = state.lineNumber === next.lineNumber && next.type === 4 && next.value === "function";
                }
                return match2;
              };
              Parser5.prototype.parseFunctionDeclaration = function(identifierIsOptional) {
                var node = this.createNode();
                var isAsync2 = this.matchContextualKeyword("async");
                if (isAsync2) {
                  this.nextToken();
                }
                this.expectKeyword("function");
                var isGenerator = isAsync2 ? false : this.match("*");
                if (isGenerator) {
                  this.nextToken();
                }
                var message;
                var id = null;
                var firstRestricted = null;
                if (!identifierIsOptional || !this.match("(")) {
                  var token2 = this.lookahead;
                  id = this.parseVariableIdentifier();
                  if (this.context.strict) {
                    if (this.scanner.isRestrictedWord(token2.value)) {
                      this.tolerateUnexpectedToken(token2, messages_1.Messages.StrictFunctionName);
                    }
                  } else {
                    if (this.scanner.isRestrictedWord(token2.value)) {
                      firstRestricted = token2;
                      message = messages_1.Messages.StrictFunctionName;
                    } else if (this.scanner.isStrictModeReservedWord(token2.value)) {
                      firstRestricted = token2;
                      message = messages_1.Messages.StrictReservedWord;
                    }
                  }
                }
                var previousAllowAwait = this.context.await;
                var previousAllowYield = this.context.allowYield;
                this.context.await = isAsync2;
                this.context.allowYield = !isGenerator;
                var formalParameters = this.parseFormalParameters(firstRestricted);
                var params = formalParameters.params;
                var stricted = formalParameters.stricted;
                firstRestricted = formalParameters.firstRestricted;
                if (formalParameters.message) {
                  message = formalParameters.message;
                }
                var previousStrict = this.context.strict;
                var previousAllowStrictDirective = this.context.allowStrictDirective;
                this.context.allowStrictDirective = formalParameters.simple;
                var body = this.parseFunctionSourceElements();
                if (this.context.strict && firstRestricted) {
                  this.throwUnexpectedToken(firstRestricted, message);
                }
                if (this.context.strict && stricted) {
                  this.tolerateUnexpectedToken(stricted, message);
                }
                this.context.strict = previousStrict;
                this.context.allowStrictDirective = previousAllowStrictDirective;
                this.context.await = previousAllowAwait;
                this.context.allowYield = previousAllowYield;
                return isAsync2 ? this.finalize(node, new Node4.AsyncFunctionDeclaration(id, params, body)) : this.finalize(node, new Node4.FunctionDeclaration(id, params, body, isGenerator));
              };
              Parser5.prototype.parseFunctionExpression = function() {
                var node = this.createNode();
                var isAsync2 = this.matchContextualKeyword("async");
                if (isAsync2) {
                  this.nextToken();
                }
                this.expectKeyword("function");
                var isGenerator = isAsync2 ? false : this.match("*");
                if (isGenerator) {
                  this.nextToken();
                }
                var message;
                var id = null;
                var firstRestricted;
                var previousAllowAwait = this.context.await;
                var previousAllowYield = this.context.allowYield;
                this.context.await = isAsync2;
                this.context.allowYield = !isGenerator;
                if (!this.match("(")) {
                  var token2 = this.lookahead;
                  id = !this.context.strict && !isGenerator && this.matchKeyword("yield") ? this.parseIdentifierName() : this.parseVariableIdentifier();
                  if (this.context.strict) {
                    if (this.scanner.isRestrictedWord(token2.value)) {
                      this.tolerateUnexpectedToken(token2, messages_1.Messages.StrictFunctionName);
                    }
                  } else {
                    if (this.scanner.isRestrictedWord(token2.value)) {
                      firstRestricted = token2;
                      message = messages_1.Messages.StrictFunctionName;
                    } else if (this.scanner.isStrictModeReservedWord(token2.value)) {
                      firstRestricted = token2;
                      message = messages_1.Messages.StrictReservedWord;
                    }
                  }
                }
                var formalParameters = this.parseFormalParameters(firstRestricted);
                var params = formalParameters.params;
                var stricted = formalParameters.stricted;
                firstRestricted = formalParameters.firstRestricted;
                if (formalParameters.message) {
                  message = formalParameters.message;
                }
                var previousStrict = this.context.strict;
                var previousAllowStrictDirective = this.context.allowStrictDirective;
                this.context.allowStrictDirective = formalParameters.simple;
                var body = this.parseFunctionSourceElements();
                if (this.context.strict && firstRestricted) {
                  this.throwUnexpectedToken(firstRestricted, message);
                }
                if (this.context.strict && stricted) {
                  this.tolerateUnexpectedToken(stricted, message);
                }
                this.context.strict = previousStrict;
                this.context.allowStrictDirective = previousAllowStrictDirective;
                this.context.await = previousAllowAwait;
                this.context.allowYield = previousAllowYield;
                return isAsync2 ? this.finalize(node, new Node4.AsyncFunctionExpression(id, params, body)) : this.finalize(node, new Node4.FunctionExpression(id, params, body, isGenerator));
              };
              Parser5.prototype.parseDirective = function() {
                var token2 = this.lookahead;
                var node = this.createNode();
                var expr = this.parseExpression();
                var directive = expr.type === syntax_1.Syntax.Literal ? this.getTokenRaw(token2).slice(1, -1) : null;
                this.consumeSemicolon();
                return this.finalize(node, directive ? new Node4.Directive(expr, directive) : new Node4.ExpressionStatement(expr));
              };
              Parser5.prototype.parseDirectivePrologues = function() {
                var firstRestricted = null;
                var body = [];
                while (true) {
                  var token2 = this.lookahead;
                  if (token2.type !== 8) {
                    break;
                  }
                  var statement = this.parseDirective();
                  body.push(statement);
                  var directive = statement.directive;
                  if (typeof directive !== "string") {
                    break;
                  }
                  if (directive === "use strict") {
                    this.context.strict = true;
                    if (firstRestricted) {
                      this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral);
                    }
                    if (!this.context.allowStrictDirective) {
                      this.tolerateUnexpectedToken(token2, messages_1.Messages.IllegalLanguageModeDirective);
                    }
                  } else {
                    if (!firstRestricted && token2.octal) {
                      firstRestricted = token2;
                    }
                  }
                }
                return body;
              };
              Parser5.prototype.qualifiedPropertyName = function(token2) {
                switch (token2.type) {
                  case 3:
                  case 8:
                  case 1:
                  case 5:
                  case 6:
                  case 4:
                    return true;
                  case 7:
                    return token2.value === "[";
                  default:
                    break;
                }
                return false;
              };
              Parser5.prototype.parseGetterMethod = function() {
                var node = this.createNode();
                var isGenerator = false;
                var previousAllowYield = this.context.allowYield;
                this.context.allowYield = !isGenerator;
                var formalParameters = this.parseFormalParameters();
                if (formalParameters.params.length > 0) {
                  this.tolerateError(messages_1.Messages.BadGetterArity);
                }
                var method = this.parsePropertyMethod(formalParameters);
                this.context.allowYield = previousAllowYield;
                return this.finalize(node, new Node4.FunctionExpression(null, formalParameters.params, method, isGenerator));
              };
              Parser5.prototype.parseSetterMethod = function() {
                var node = this.createNode();
                var isGenerator = false;
                var previousAllowYield = this.context.allowYield;
                this.context.allowYield = !isGenerator;
                var formalParameters = this.parseFormalParameters();
                if (formalParameters.params.length !== 1) {
                  this.tolerateError(messages_1.Messages.BadSetterArity);
                } else if (formalParameters.params[0] instanceof Node4.RestElement) {
                  this.tolerateError(messages_1.Messages.BadSetterRestParameter);
                }
                var method = this.parsePropertyMethod(formalParameters);
                this.context.allowYield = previousAllowYield;
                return this.finalize(node, new Node4.FunctionExpression(null, formalParameters.params, method, isGenerator));
              };
              Parser5.prototype.parseGeneratorMethod = function() {
                var node = this.createNode();
                var isGenerator = true;
                var previousAllowYield = this.context.allowYield;
                this.context.allowYield = true;
                var params = this.parseFormalParameters();
                this.context.allowYield = false;
                var method = this.parsePropertyMethod(params);
                this.context.allowYield = previousAllowYield;
                return this.finalize(node, new Node4.FunctionExpression(null, params.params, method, isGenerator));
              };
              Parser5.prototype.isStartOfExpression = function() {
                var start = true;
                var value = this.lookahead.value;
                switch (this.lookahead.type) {
                  case 7:
                    start = value === "[" || value === "(" || value === "{" || value === "+" || value === "-" || value === "!" || value === "~" || value === "++" || value === "--" || value === "/" || value === "/=";
                    break;
                  case 4:
                    start = value === "class" || value === "delete" || value === "function" || value === "let" || value === "new" || value === "super" || value === "this" || value === "typeof" || value === "void" || value === "yield";
                    break;
                  default:
                    break;
                }
                return start;
              };
              Parser5.prototype.parseYieldExpression = function() {
                var node = this.createNode();
                this.expectKeyword("yield");
                var argument = null;
                var delegate = false;
                if (!this.hasLineTerminator) {
                  var previousAllowYield = this.context.allowYield;
                  this.context.allowYield = false;
                  delegate = this.match("*");
                  if (delegate) {
                    this.nextToken();
                    argument = this.parseAssignmentExpression();
                  } else if (this.isStartOfExpression()) {
                    argument = this.parseAssignmentExpression();
                  }
                  this.context.allowYield = previousAllowYield;
                }
                return this.finalize(node, new Node4.YieldExpression(argument, delegate));
              };
              Parser5.prototype.parseClassElement = function(hasConstructor) {
                var token2 = this.lookahead;
                var node = this.createNode();
                var kind = "";
                var key = null;
                var value = null;
                var computed = false;
                var method = false;
                var isStatic = false;
                var isAsync2 = false;
                if (this.match("*")) {
                  this.nextToken();
                } else {
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  var id = key;
                  if (id.name === "static" && (this.qualifiedPropertyName(this.lookahead) || this.match("*"))) {
                    token2 = this.lookahead;
                    isStatic = true;
                    computed = this.match("[");
                    if (this.match("*")) {
                      this.nextToken();
                    } else {
                      key = this.parseObjectPropertyKey();
                    }
                  }
                  if (token2.type === 3 && !this.hasLineTerminator && token2.value === "async") {
                    var punctuator = this.lookahead.value;
                    if (punctuator !== ":" && punctuator !== "(" && punctuator !== "*") {
                      isAsync2 = true;
                      token2 = this.lookahead;
                      key = this.parseObjectPropertyKey();
                      if (token2.type === 3 && token2.value === "constructor") {
                        this.tolerateUnexpectedToken(token2, messages_1.Messages.ConstructorIsAsync);
                      }
                    }
                  }
                }
                var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
                if (token2.type === 3) {
                  if (token2.value === "get" && lookaheadPropertyKey) {
                    kind = "get";
                    computed = this.match("[");
                    key = this.parseObjectPropertyKey();
                    this.context.allowYield = false;
                    value = this.parseGetterMethod();
                  } else if (token2.value === "set" && lookaheadPropertyKey) {
                    kind = "set";
                    computed = this.match("[");
                    key = this.parseObjectPropertyKey();
                    value = this.parseSetterMethod();
                  }
                } else if (token2.type === 7 && token2.value === "*" && lookaheadPropertyKey) {
                  kind = "init";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  value = this.parseGeneratorMethod();
                  method = true;
                }
                if (!kind && key && this.match("(")) {
                  kind = "init";
                  value = isAsync2 ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
                  method = true;
                }
                if (!kind) {
                  this.throwUnexpectedToken(this.lookahead);
                }
                if (kind === "init") {
                  kind = "method";
                }
                if (!computed) {
                  if (isStatic && this.isPropertyKey(key, "prototype")) {
                    this.throwUnexpectedToken(token2, messages_1.Messages.StaticPrototype);
                  }
                  if (!isStatic && this.isPropertyKey(key, "constructor")) {
                    if (kind !== "method" || !method || value && value.generator) {
                      this.throwUnexpectedToken(token2, messages_1.Messages.ConstructorSpecialMethod);
                    }
                    if (hasConstructor.value) {
                      this.throwUnexpectedToken(token2, messages_1.Messages.DuplicateConstructor);
                    } else {
                      hasConstructor.value = true;
                    }
                    kind = "constructor";
                  }
                }
                return this.finalize(node, new Node4.MethodDefinition(key, computed, value, kind, isStatic));
              };
              Parser5.prototype.parseClassElementList = function() {
                var body = [];
                var hasConstructor = { value: false };
                this.expect("{");
                while (!this.match("}")) {
                  if (this.match(";")) {
                    this.nextToken();
                  } else {
                    body.push(this.parseClassElement(hasConstructor));
                  }
                }
                this.expect("}");
                return body;
              };
              Parser5.prototype.parseClassBody = function() {
                var node = this.createNode();
                var elementList = this.parseClassElementList();
                return this.finalize(node, new Node4.ClassBody(elementList));
              };
              Parser5.prototype.parseClassDeclaration = function(identifierIsOptional) {
                var node = this.createNode();
                var previousStrict = this.context.strict;
                this.context.strict = true;
                this.expectKeyword("class");
                var id = identifierIsOptional && this.lookahead.type !== 3 ? null : this.parseVariableIdentifier();
                var superClass = null;
                if (this.matchKeyword("extends")) {
                  this.nextToken();
                  superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
                }
                var classBody = this.parseClassBody();
                this.context.strict = previousStrict;
                return this.finalize(node, new Node4.ClassDeclaration(id, superClass, classBody));
              };
              Parser5.prototype.parseClassExpression = function() {
                var node = this.createNode();
                var previousStrict = this.context.strict;
                this.context.strict = true;
                this.expectKeyword("class");
                var id = this.lookahead.type === 3 ? this.parseVariableIdentifier() : null;
                var superClass = null;
                if (this.matchKeyword("extends")) {
                  this.nextToken();
                  superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
                }
                var classBody = this.parseClassBody();
                this.context.strict = previousStrict;
                return this.finalize(node, new Node4.ClassExpression(id, superClass, classBody));
              };
              Parser5.prototype.parseModule = function() {
                this.context.strict = true;
                this.context.isModule = true;
                this.scanner.isModule = true;
                var node = this.createNode();
                var body = this.parseDirectivePrologues();
                while (this.lookahead.type !== 2) {
                  body.push(this.parseStatementListItem());
                }
                return this.finalize(node, new Node4.Module(body));
              };
              Parser5.prototype.parseScript = function() {
                var node = this.createNode();
                var body = this.parseDirectivePrologues();
                while (this.lookahead.type !== 2) {
                  body.push(this.parseStatementListItem());
                }
                return this.finalize(node, new Node4.Script(body));
              };
              Parser5.prototype.parseModuleSpecifier = function() {
                var node = this.createNode();
                if (this.lookahead.type !== 8) {
                  this.throwError(messages_1.Messages.InvalidModuleSpecifier);
                }
                var token2 = this.nextToken();
                var raw2 = this.getTokenRaw(token2);
                return this.finalize(node, new Node4.Literal(token2.value, raw2));
              };
              Parser5.prototype.parseImportSpecifier = function() {
                var node = this.createNode();
                var imported;
                var local;
                if (this.lookahead.type === 3) {
                  imported = this.parseVariableIdentifier();
                  local = imported;
                  if (this.matchContextualKeyword("as")) {
                    this.nextToken();
                    local = this.parseVariableIdentifier();
                  }
                } else {
                  imported = this.parseIdentifierName();
                  local = imported;
                  if (this.matchContextualKeyword("as")) {
                    this.nextToken();
                    local = this.parseVariableIdentifier();
                  } else {
                    this.throwUnexpectedToken(this.nextToken());
                  }
                }
                return this.finalize(node, new Node4.ImportSpecifier(local, imported));
              };
              Parser5.prototype.parseNamedImports = function() {
                this.expect("{");
                var specifiers = [];
                while (!this.match("}")) {
                  specifiers.push(this.parseImportSpecifier());
                  if (!this.match("}")) {
                    this.expect(",");
                  }
                }
                this.expect("}");
                return specifiers;
              };
              Parser5.prototype.parseImportDefaultSpecifier = function() {
                var node = this.createNode();
                var local = this.parseIdentifierName();
                return this.finalize(node, new Node4.ImportDefaultSpecifier(local));
              };
              Parser5.prototype.parseImportNamespaceSpecifier = function() {
                var node = this.createNode();
                this.expect("*");
                if (!this.matchContextualKeyword("as")) {
                  this.throwError(messages_1.Messages.NoAsAfterImportNamespace);
                }
                this.nextToken();
                var local = this.parseIdentifierName();
                return this.finalize(node, new Node4.ImportNamespaceSpecifier(local));
              };
              Parser5.prototype.parseImportDeclaration = function() {
                if (this.context.inFunctionBody) {
                  this.throwError(messages_1.Messages.IllegalImportDeclaration);
                }
                var node = this.createNode();
                this.expectKeyword("import");
                var src;
                var specifiers = [];
                if (this.lookahead.type === 8) {
                  src = this.parseModuleSpecifier();
                } else {
                  if (this.match("{")) {
                    specifiers = specifiers.concat(this.parseNamedImports());
                  } else if (this.match("*")) {
                    specifiers.push(this.parseImportNamespaceSpecifier());
                  } else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword("default")) {
                    specifiers.push(this.parseImportDefaultSpecifier());
                    if (this.match(",")) {
                      this.nextToken();
                      if (this.match("*")) {
                        specifiers.push(this.parseImportNamespaceSpecifier());
                      } else if (this.match("{")) {
                        specifiers = specifiers.concat(this.parseNamedImports());
                      } else {
                        this.throwUnexpectedToken(this.lookahead);
                      }
                    }
                  } else {
                    this.throwUnexpectedToken(this.nextToken());
                  }
                  if (!this.matchContextualKeyword("from")) {
                    var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
                    this.throwError(message, this.lookahead.value);
                  }
                  this.nextToken();
                  src = this.parseModuleSpecifier();
                }
                this.consumeSemicolon();
                return this.finalize(node, new Node4.ImportDeclaration(specifiers, src));
              };
              Parser5.prototype.parseExportSpecifier = function() {
                var node = this.createNode();
                var local = this.parseIdentifierName();
                var exported = local;
                if (this.matchContextualKeyword("as")) {
                  this.nextToken();
                  exported = this.parseIdentifierName();
                }
                return this.finalize(node, new Node4.ExportSpecifier(local, exported));
              };
              Parser5.prototype.parseExportDeclaration = function() {
                if (this.context.inFunctionBody) {
                  this.throwError(messages_1.Messages.IllegalExportDeclaration);
                }
                var node = this.createNode();
                this.expectKeyword("export");
                var exportDeclaration;
                if (this.matchKeyword("default")) {
                  this.nextToken();
                  if (this.matchKeyword("function")) {
                    var declaration = this.parseFunctionDeclaration(true);
                    exportDeclaration = this.finalize(node, new Node4.ExportDefaultDeclaration(declaration));
                  } else if (this.matchKeyword("class")) {
                    var declaration = this.parseClassDeclaration(true);
                    exportDeclaration = this.finalize(node, new Node4.ExportDefaultDeclaration(declaration));
                  } else if (this.matchContextualKeyword("async")) {
                    var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression();
                    exportDeclaration = this.finalize(node, new Node4.ExportDefaultDeclaration(declaration));
                  } else {
                    if (this.matchContextualKeyword("from")) {
                      this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value);
                    }
                    var declaration = this.match("{") ? this.parseObjectInitializer() : this.match("[") ? this.parseArrayInitializer() : this.parseAssignmentExpression();
                    this.consumeSemicolon();
                    exportDeclaration = this.finalize(node, new Node4.ExportDefaultDeclaration(declaration));
                  }
                } else if (this.match("*")) {
                  this.nextToken();
                  if (!this.matchContextualKeyword("from")) {
                    var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
                    this.throwError(message, this.lookahead.value);
                  }
                  this.nextToken();
                  var src = this.parseModuleSpecifier();
                  this.consumeSemicolon();
                  exportDeclaration = this.finalize(node, new Node4.ExportAllDeclaration(src));
                } else if (this.lookahead.type === 4) {
                  var declaration = void 0;
                  switch (this.lookahead.value) {
                    case "let":
                    case "const":
                      declaration = this.parseLexicalDeclaration({ inFor: false });
                      break;
                    case "var":
                    case "class":
                    case "function":
                      declaration = this.parseStatementListItem();
                      break;
                    default:
                      this.throwUnexpectedToken(this.lookahead);
                  }
                  exportDeclaration = this.finalize(node, new Node4.ExportNamedDeclaration(declaration, [], null));
                } else if (this.matchAsyncFunction()) {
                  var declaration = this.parseFunctionDeclaration();
                  exportDeclaration = this.finalize(node, new Node4.ExportNamedDeclaration(declaration, [], null));
                } else {
                  var specifiers = [];
                  var source2 = null;
                  var isExportFromIdentifier = false;
                  this.expect("{");
                  while (!this.match("}")) {
                    isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword("default");
                    specifiers.push(this.parseExportSpecifier());
                    if (!this.match("}")) {
                      this.expect(",");
                    }
                  }
                  this.expect("}");
                  if (this.matchContextualKeyword("from")) {
                    this.nextToken();
                    source2 = this.parseModuleSpecifier();
                    this.consumeSemicolon();
                  } else if (isExportFromIdentifier) {
                    var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
                    this.throwError(message, this.lookahead.value);
                  } else {
                    this.consumeSemicolon();
                  }
                  exportDeclaration = this.finalize(node, new Node4.ExportNamedDeclaration(null, specifiers, source2));
                }
                return exportDeclaration;
              };
              return Parser5;
            }();
            exports3.Parser = Parser4;
          },
          /* 9 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            function assert3(condition, message) {
              if (!condition) {
                throw new Error("ASSERT: " + message);
              }
            }
            __name(assert3, "assert");
            exports3.assert = assert3;
          },
          /* 10 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var ErrorHandler = function() {
              function ErrorHandler2() {
                this.errors = [];
                this.tolerant = false;
              }
              __name(ErrorHandler2, "ErrorHandler");
              ErrorHandler2.prototype.recordError = function(error) {
                this.errors.push(error);
              };
              ErrorHandler2.prototype.tolerate = function(error) {
                if (this.tolerant) {
                  this.recordError(error);
                } else {
                  throw error;
                }
              };
              ErrorHandler2.prototype.constructError = function(msg, column) {
                var error = new Error(msg);
                try {
                  throw error;
                } catch (base) {
                  if (Object.create && Object.defineProperty) {
                    error = Object.create(base);
                    Object.defineProperty(error, "column", { value: column });
                  }
                }
                return error;
              };
              ErrorHandler2.prototype.createError = function(index, line, col, description) {
                var msg = "Line " + line + ": " + description;
                var error = this.constructError(msg, col);
                error.index = index;
                error.lineNumber = line;
                error.description = description;
                return error;
              };
              ErrorHandler2.prototype.throwError = function(index, line, col, description) {
                throw this.createError(index, line, col, description);
              };
              ErrorHandler2.prototype.tolerateError = function(index, line, col, description) {
                var error = this.createError(index, line, col, description);
                if (this.tolerant) {
                  this.recordError(error);
                } else {
                  throw error;
                }
              };
              return ErrorHandler2;
            }();
            exports3.ErrorHandler = ErrorHandler;
          },
          /* 11 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            exports3.Messages = {
              BadGetterArity: "Getter must not have any formal parameters",
              BadSetterArity: "Setter must have exactly one formal parameter",
              BadSetterRestParameter: "Setter function argument must not be a rest parameter",
              ConstructorIsAsync: "Class constructor may not be an async method",
              ConstructorSpecialMethod: "Class constructor may not be an accessor",
              DeclarationMissingInitializer: "Missing initializer in %0 declaration",
              DefaultRestParameter: "Unexpected token =",
              DuplicateBinding: "Duplicate binding %0",
              DuplicateConstructor: "A class may only have one constructor",
              DuplicateProtoProperty: "Duplicate __proto__ fields are not allowed in object literals",
              ForInOfLoopInitializer: "%0 loop variable declaration may not have an initializer",
              GeneratorInLegacyContext: "Generator declarations are not allowed in legacy contexts",
              IllegalBreak: "Illegal break statement",
              IllegalContinue: "Illegal continue statement",
              IllegalExportDeclaration: "Unexpected token",
              IllegalImportDeclaration: "Unexpected token",
              IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list",
              IllegalReturn: "Illegal return statement",
              InvalidEscapedReservedWord: "Keyword must not contain escaped characters",
              InvalidHexEscapeSequence: "Invalid hexadecimal escape sequence",
              InvalidLHSInAssignment: "Invalid left-hand side in assignment",
              InvalidLHSInForIn: "Invalid left-hand side in for-in",
              InvalidLHSInForLoop: "Invalid left-hand side in for-loop",
              InvalidModuleSpecifier: "Unexpected token",
              InvalidRegExp: "Invalid regular expression",
              LetInLexicalBinding: "let is disallowed as a lexically bound name",
              MissingFromClause: "Unexpected token",
              MultipleDefaultsInSwitch: "More than one default clause in switch statement",
              NewlineAfterThrow: "Illegal newline after throw",
              NoAsAfterImportNamespace: "Unexpected token",
              NoCatchOrFinally: "Missing catch or finally after try",
              ParameterAfterRestParameter: "Rest parameter must be last formal parameter",
              Redeclaration: "%0 '%1' has already been declared",
              StaticPrototype: "Classes may not have static property named prototype",
              StrictCatchVariable: "Catch variable may not be eval or arguments in strict mode",
              StrictDelete: "Delete of an unqualified identifier in strict mode.",
              StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block",
              StrictFunctionName: "Function name may not be eval or arguments in strict mode",
              StrictLHSAssignment: "Assignment to eval or arguments is not allowed in strict mode",
              StrictLHSPostfix: "Postfix increment/decrement may not have eval or arguments operand in strict mode",
              StrictLHSPrefix: "Prefix increment/decrement may not have eval or arguments operand in strict mode",
              StrictModeWith: "Strict mode code may not include a with statement",
              StrictOctalLiteral: "Octal literals are not allowed in strict mode.",
              StrictParamDupe: "Strict mode function may not have duplicate parameter names",
              StrictParamName: "Parameter name eval or arguments is not allowed in strict mode",
              StrictReservedWord: "Use of future reserved word in strict mode",
              StrictVarName: "Variable name may not be eval or arguments in strict mode",
              TemplateOctalLiteral: "Octal literals are not allowed in template strings.",
              UnexpectedEOS: "Unexpected end of input",
              UnexpectedIdentifier: "Unexpected identifier",
              UnexpectedNumber: "Unexpected number",
              UnexpectedReserved: "Unexpected reserved word",
              UnexpectedString: "Unexpected string",
              UnexpectedTemplate: "Unexpected quasi %0",
              UnexpectedToken: "Unexpected token %0",
              UnexpectedTokenIllegal: "Unexpected token ILLEGAL",
              UnknownLabel: "Undefined label '%0'",
              UnterminatedRegExp: "Invalid regular expression: missing /"
            };
          },
          /* 12 */
          /***/
          function(module3, exports3, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var assert_1 = __webpack_require__(9);
            var character_1 = __webpack_require__(4);
            var messages_1 = __webpack_require__(11);
            function hexValue(ch) {
              return "0123456789abcdef".indexOf(ch.toLowerCase());
            }
            __name(hexValue, "hexValue");
            function octalValue(ch) {
              return "01234567".indexOf(ch);
            }
            __name(octalValue, "octalValue");
            var Scanner = function() {
              function Scanner2(code2, handler) {
                this.source = code2;
                this.errorHandler = handler;
                this.trackComment = false;
                this.isModule = false;
                this.length = code2.length;
                this.index = 0;
                this.lineNumber = code2.length > 0 ? 1 : 0;
                this.lineStart = 0;
                this.curlyStack = [];
              }
              __name(Scanner2, "Scanner");
              Scanner2.prototype.saveState = function() {
                return {
                  index: this.index,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart
                };
              };
              Scanner2.prototype.restoreState = function(state) {
                this.index = state.index;
                this.lineNumber = state.lineNumber;
                this.lineStart = state.lineStart;
              };
              Scanner2.prototype.eof = function() {
                return this.index >= this.length;
              };
              Scanner2.prototype.throwUnexpectedToken = function(message) {
                if (message === void 0) {
                  message = messages_1.Messages.UnexpectedTokenIllegal;
                }
                return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
              };
              Scanner2.prototype.tolerateUnexpectedToken = function(message) {
                if (message === void 0) {
                  message = messages_1.Messages.UnexpectedTokenIllegal;
                }
                this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
              };
              Scanner2.prototype.skipSingleLineComment = function(offset) {
                var comments = [];
                var start, loc;
                if (this.trackComment) {
                  comments = [];
                  start = this.index - offset;
                  loc = {
                    start: {
                      line: this.lineNumber,
                      column: this.index - this.lineStart - offset
                    },
                    end: {}
                  };
                }
                while (!this.eof()) {
                  var ch = this.source.charCodeAt(this.index);
                  ++this.index;
                  if (character_1.Character.isLineTerminator(ch)) {
                    if (this.trackComment) {
                      loc.end = {
                        line: this.lineNumber,
                        column: this.index - this.lineStart - 1
                      };
                      var entry = {
                        multiLine: false,
                        slice: [start + offset, this.index - 1],
                        range: [start, this.index - 1],
                        loc
                      };
                      comments.push(entry);
                    }
                    if (ch === 13 && this.source.charCodeAt(this.index) === 10) {
                      ++this.index;
                    }
                    ++this.lineNumber;
                    this.lineStart = this.index;
                    return comments;
                  }
                }
                if (this.trackComment) {
                  loc.end = {
                    line: this.lineNumber,
                    column: this.index - this.lineStart
                  };
                  var entry = {
                    multiLine: false,
                    slice: [start + offset, this.index],
                    range: [start, this.index],
                    loc
                  };
                  comments.push(entry);
                }
                return comments;
              };
              Scanner2.prototype.skipMultiLineComment = function() {
                var comments = [];
                var start, loc;
                if (this.trackComment) {
                  comments = [];
                  start = this.index - 2;
                  loc = {
                    start: {
                      line: this.lineNumber,
                      column: this.index - this.lineStart - 2
                    },
                    end: {}
                  };
                }
                while (!this.eof()) {
                  var ch = this.source.charCodeAt(this.index);
                  if (character_1.Character.isLineTerminator(ch)) {
                    if (ch === 13 && this.source.charCodeAt(this.index + 1) === 10) {
                      ++this.index;
                    }
                    ++this.lineNumber;
                    ++this.index;
                    this.lineStart = this.index;
                  } else if (ch === 42) {
                    if (this.source.charCodeAt(this.index + 1) === 47) {
                      this.index += 2;
                      if (this.trackComment) {
                        loc.end = {
                          line: this.lineNumber,
                          column: this.index - this.lineStart
                        };
                        var entry = {
                          multiLine: true,
                          slice: [start + 2, this.index - 2],
                          range: [start, this.index],
                          loc
                        };
                        comments.push(entry);
                      }
                      return comments;
                    }
                    ++this.index;
                  } else {
                    ++this.index;
                  }
                }
                if (this.trackComment) {
                  loc.end = {
                    line: this.lineNumber,
                    column: this.index - this.lineStart
                  };
                  var entry = {
                    multiLine: true,
                    slice: [start + 2, this.index],
                    range: [start, this.index],
                    loc
                  };
                  comments.push(entry);
                }
                this.tolerateUnexpectedToken();
                return comments;
              };
              Scanner2.prototype.scanComments = function() {
                var comments;
                if (this.trackComment) {
                  comments = [];
                }
                var start = this.index === 0;
                while (!this.eof()) {
                  var ch = this.source.charCodeAt(this.index);
                  if (character_1.Character.isWhiteSpace(ch)) {
                    ++this.index;
                  } else if (character_1.Character.isLineTerminator(ch)) {
                    ++this.index;
                    if (ch === 13 && this.source.charCodeAt(this.index) === 10) {
                      ++this.index;
                    }
                    ++this.lineNumber;
                    this.lineStart = this.index;
                    start = true;
                  } else if (ch === 47) {
                    ch = this.source.charCodeAt(this.index + 1);
                    if (ch === 47) {
                      this.index += 2;
                      var comment = this.skipSingleLineComment(2);
                      if (this.trackComment) {
                        comments = comments.concat(comment);
                      }
                      start = true;
                    } else if (ch === 42) {
                      this.index += 2;
                      var comment = this.skipMultiLineComment();
                      if (this.trackComment) {
                        comments = comments.concat(comment);
                      }
                    } else {
                      break;
                    }
                  } else if (start && ch === 45) {
                    if (this.source.charCodeAt(this.index + 1) === 45 && this.source.charCodeAt(this.index + 2) === 62) {
                      this.index += 3;
                      var comment = this.skipSingleLineComment(3);
                      if (this.trackComment) {
                        comments = comments.concat(comment);
                      }
                    } else {
                      break;
                    }
                  } else if (ch === 60 && !this.isModule) {
                    if (this.source.slice(this.index + 1, this.index + 4) === "!--") {
                      this.index += 4;
                      var comment = this.skipSingleLineComment(4);
                      if (this.trackComment) {
                        comments = comments.concat(comment);
                      }
                    } else {
                      break;
                    }
                  } else {
                    break;
                  }
                }
                return comments;
              };
              Scanner2.prototype.isFutureReservedWord = function(id) {
                switch (id) {
                  case "enum":
                  case "export":
                  case "import":
                  case "super":
                    return true;
                  default:
                    return false;
                }
              };
              Scanner2.prototype.isStrictModeReservedWord = function(id) {
                switch (id) {
                  case "implements":
                  case "interface":
                  case "package":
                  case "private":
                  case "protected":
                  case "public":
                  case "static":
                  case "yield":
                  case "let":
                    return true;
                  default:
                    return false;
                }
              };
              Scanner2.prototype.isRestrictedWord = function(id) {
                return id === "eval" || id === "arguments";
              };
              Scanner2.prototype.isKeyword = function(id) {
                switch (id.length) {
                  case 2:
                    return id === "if" || id === "in" || id === "do";
                  case 3:
                    return id === "var" || id === "for" || id === "new" || id === "try" || id === "let";
                  case 4:
                    return id === "this" || id === "else" || id === "case" || id === "void" || id === "with" || id === "enum";
                  case 5:
                    return id === "while" || id === "break" || id === "catch" || id === "throw" || id === "const" || id === "yield" || id === "class" || id === "super";
                  case 6:
                    return id === "return" || id === "typeof" || id === "delete" || id === "switch" || id === "export" || id === "import";
                  case 7:
                    return id === "default" || id === "finally" || id === "extends";
                  case 8:
                    return id === "function" || id === "continue" || id === "debugger";
                  case 10:
                    return id === "instanceof";
                  default:
                    return false;
                }
              };
              Scanner2.prototype.codePointAt = function(i) {
                var cp2 = this.source.charCodeAt(i);
                if (cp2 >= 55296 && cp2 <= 56319) {
                  var second = this.source.charCodeAt(i + 1);
                  if (second >= 56320 && second <= 57343) {
                    var first2 = cp2;
                    cp2 = (first2 - 55296) * 1024 + second - 56320 + 65536;
                  }
                }
                return cp2;
              };
              Scanner2.prototype.scanHexEscape = function(prefix) {
                var len = prefix === "u" ? 4 : 2;
                var code2 = 0;
                for (var i = 0; i < len; ++i) {
                  if (!this.eof() && character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
                    code2 = code2 * 16 + hexValue(this.source[this.index++]);
                  } else {
                    return null;
                  }
                }
                return String.fromCharCode(code2);
              };
              Scanner2.prototype.scanUnicodeCodePointEscape = function() {
                var ch = this.source[this.index];
                var code2 = 0;
                if (ch === "}") {
                  this.throwUnexpectedToken();
                }
                while (!this.eof()) {
                  ch = this.source[this.index++];
                  if (!character_1.Character.isHexDigit(ch.charCodeAt(0))) {
                    break;
                  }
                  code2 = code2 * 16 + hexValue(ch);
                }
                if (code2 > 1114111 || ch !== "}") {
                  this.throwUnexpectedToken();
                }
                return character_1.Character.fromCodePoint(code2);
              };
              Scanner2.prototype.getIdentifier = function() {
                var start = this.index++;
                while (!this.eof()) {
                  var ch = this.source.charCodeAt(this.index);
                  if (ch === 92) {
                    this.index = start;
                    return this.getComplexIdentifier();
                  } else if (ch >= 55296 && ch < 57343) {
                    this.index = start;
                    return this.getComplexIdentifier();
                  }
                  if (character_1.Character.isIdentifierPart(ch)) {
                    ++this.index;
                  } else {
                    break;
                  }
                }
                return this.source.slice(start, this.index);
              };
              Scanner2.prototype.getComplexIdentifier = function() {
                var cp2 = this.codePointAt(this.index);
                var id = character_1.Character.fromCodePoint(cp2);
                this.index += id.length;
                var ch;
                if (cp2 === 92) {
                  if (this.source.charCodeAt(this.index) !== 117) {
                    this.throwUnexpectedToken();
                  }
                  ++this.index;
                  if (this.source[this.index] === "{") {
                    ++this.index;
                    ch = this.scanUnicodeCodePointEscape();
                  } else {
                    ch = this.scanHexEscape("u");
                    if (ch === null || ch === "\\" || !character_1.Character.isIdentifierStart(ch.charCodeAt(0))) {
                      this.throwUnexpectedToken();
                    }
                  }
                  id = ch;
                }
                while (!this.eof()) {
                  cp2 = this.codePointAt(this.index);
                  if (!character_1.Character.isIdentifierPart(cp2)) {
                    break;
                  }
                  ch = character_1.Character.fromCodePoint(cp2);
                  id += ch;
                  this.index += ch.length;
                  if (cp2 === 92) {
                    id = id.substr(0, id.length - 1);
                    if (this.source.charCodeAt(this.index) !== 117) {
                      this.throwUnexpectedToken();
                    }
                    ++this.index;
                    if (this.source[this.index] === "{") {
                      ++this.index;
                      ch = this.scanUnicodeCodePointEscape();
                    } else {
                      ch = this.scanHexEscape("u");
                      if (ch === null || ch === "\\" || !character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
                        this.throwUnexpectedToken();
                      }
                    }
                    id += ch;
                  }
                }
                return id;
              };
              Scanner2.prototype.octalToDecimal = function(ch) {
                var octal = ch !== "0";
                var code2 = octalValue(ch);
                if (!this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
                  octal = true;
                  code2 = code2 * 8 + octalValue(this.source[this.index++]);
                  if ("0123".indexOf(ch) >= 0 && !this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
                    code2 = code2 * 8 + octalValue(this.source[this.index++]);
                  }
                }
                return {
                  code: code2,
                  octal
                };
              };
              Scanner2.prototype.scanIdentifier = function() {
                var type;
                var start = this.index;
                var id = this.source.charCodeAt(start) === 92 ? this.getComplexIdentifier() : this.getIdentifier();
                if (id.length === 1) {
                  type = 3;
                } else if (this.isKeyword(id)) {
                  type = 4;
                } else if (id === "null") {
                  type = 5;
                } else if (id === "true" || id === "false") {
                  type = 1;
                } else {
                  type = 3;
                }
                if (type !== 3 && start + id.length !== this.index) {
                  var restore = this.index;
                  this.index = start;
                  this.tolerateUnexpectedToken(messages_1.Messages.InvalidEscapedReservedWord);
                  this.index = restore;
                }
                return {
                  type,
                  value: id,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanPunctuator = function() {
                var start = this.index;
                var str2 = this.source[this.index];
                switch (str2) {
                  case "(":
                  case "{":
                    if (str2 === "{") {
                      this.curlyStack.push("{");
                    }
                    ++this.index;
                    break;
                  case ".":
                    ++this.index;
                    if (this.source[this.index] === "." && this.source[this.index + 1] === ".") {
                      this.index += 2;
                      str2 = "...";
                    }
                    break;
                  case "}":
                    ++this.index;
                    this.curlyStack.pop();
                    break;
                  case ")":
                  case ";":
                  case ",":
                  case "[":
                  case "]":
                  case ":":
                  case "?":
                  case "~":
                    ++this.index;
                    break;
                  default:
                    str2 = this.source.substr(this.index, 4);
                    if (str2 === ">>>=") {
                      this.index += 4;
                    } else {
                      str2 = str2.substr(0, 3);
                      if (str2 === "===" || str2 === "!==" || str2 === ">>>" || str2 === "<<=" || str2 === ">>=" || str2 === "**=") {
                        this.index += 3;
                      } else {
                        str2 = str2.substr(0, 2);
                        if (str2 === "&&" || str2 === "||" || str2 === "==" || str2 === "!=" || str2 === "+=" || str2 === "-=" || str2 === "*=" || str2 === "/=" || str2 === "++" || str2 === "--" || str2 === "<<" || str2 === ">>" || str2 === "&=" || str2 === "|=" || str2 === "^=" || str2 === "%=" || str2 === "<=" || str2 === ">=" || str2 === "=>" || str2 === "**") {
                          this.index += 2;
                        } else {
                          str2 = this.source[this.index];
                          if ("<>=!+-*%&|^/".indexOf(str2) >= 0) {
                            ++this.index;
                          }
                        }
                      }
                    }
                }
                if (this.index === start) {
                  this.throwUnexpectedToken();
                }
                return {
                  type: 7,
                  value: str2,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanHexLiteral = function(start) {
                var num = "";
                while (!this.eof()) {
                  if (!character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
                    break;
                  }
                  num += this.source[this.index++];
                }
                if (num.length === 0) {
                  this.throwUnexpectedToken();
                }
                if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
                  this.throwUnexpectedToken();
                }
                return {
                  type: 6,
                  value: parseInt("0x" + num, 16),
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanBinaryLiteral = function(start) {
                var num = "";
                var ch;
                while (!this.eof()) {
                  ch = this.source[this.index];
                  if (ch !== "0" && ch !== "1") {
                    break;
                  }
                  num += this.source[this.index++];
                }
                if (num.length === 0) {
                  this.throwUnexpectedToken();
                }
                if (!this.eof()) {
                  ch = this.source.charCodeAt(this.index);
                  if (character_1.Character.isIdentifierStart(ch) || character_1.Character.isDecimalDigit(ch)) {
                    this.throwUnexpectedToken();
                  }
                }
                return {
                  type: 6,
                  value: parseInt(num, 2),
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanOctalLiteral = function(prefix, start) {
                var num = "";
                var octal = false;
                if (character_1.Character.isOctalDigit(prefix.charCodeAt(0))) {
                  octal = true;
                  num = "0" + this.source[this.index++];
                } else {
                  ++this.index;
                }
                while (!this.eof()) {
                  if (!character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
                    break;
                  }
                  num += this.source[this.index++];
                }
                if (!octal && num.length === 0) {
                  this.throwUnexpectedToken();
                }
                if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index)) || character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                  this.throwUnexpectedToken();
                }
                return {
                  type: 6,
                  value: parseInt(num, 8),
                  octal,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.isImplicitOctalLiteral = function() {
                for (var i = this.index + 1; i < this.length; ++i) {
                  var ch = this.source[i];
                  if (ch === "8" || ch === "9") {
                    return false;
                  }
                  if (!character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
                    return true;
                  }
                }
                return true;
              };
              Scanner2.prototype.scanNumericLiteral = function() {
                var start = this.index;
                var ch = this.source[start];
                assert_1.assert(character_1.Character.isDecimalDigit(ch.charCodeAt(0)) || ch === ".", "Numeric literal must start with a decimal digit or a decimal point");
                var num = "";
                if (ch !== ".") {
                  num = this.source[this.index++];
                  ch = this.source[this.index];
                  if (num === "0") {
                    if (ch === "x" || ch === "X") {
                      ++this.index;
                      return this.scanHexLiteral(start);
                    }
                    if (ch === "b" || ch === "B") {
                      ++this.index;
                      return this.scanBinaryLiteral(start);
                    }
                    if (ch === "o" || ch === "O") {
                      return this.scanOctalLiteral(ch, start);
                    }
                    if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
                      if (this.isImplicitOctalLiteral()) {
                        return this.scanOctalLiteral(ch, start);
                      }
                    }
                  }
                  while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                    num += this.source[this.index++];
                  }
                  ch = this.source[this.index];
                }
                if (ch === ".") {
                  num += this.source[this.index++];
                  while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                    num += this.source[this.index++];
                  }
                  ch = this.source[this.index];
                }
                if (ch === "e" || ch === "E") {
                  num += this.source[this.index++];
                  ch = this.source[this.index];
                  if (ch === "+" || ch === "-") {
                    num += this.source[this.index++];
                  }
                  if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                    while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                      num += this.source[this.index++];
                    }
                  } else {
                    this.throwUnexpectedToken();
                  }
                }
                if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
                  this.throwUnexpectedToken();
                }
                return {
                  type: 6,
                  value: parseFloat(num),
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanStringLiteral = function() {
                var start = this.index;
                var quote3 = this.source[start];
                assert_1.assert(quote3 === "'" || quote3 === '"', "String literal must starts with a quote");
                ++this.index;
                var octal = false;
                var str2 = "";
                while (!this.eof()) {
                  var ch = this.source[this.index++];
                  if (ch === quote3) {
                    quote3 = "";
                    break;
                  } else if (ch === "\\") {
                    ch = this.source[this.index++];
                    if (!ch || !character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                      switch (ch) {
                        case "u":
                          if (this.source[this.index] === "{") {
                            ++this.index;
                            str2 += this.scanUnicodeCodePointEscape();
                          } else {
                            var unescaped_1 = this.scanHexEscape(ch);
                            if (unescaped_1 === null) {
                              this.throwUnexpectedToken();
                            }
                            str2 += unescaped_1;
                          }
                          break;
                        case "x":
                          var unescaped = this.scanHexEscape(ch);
                          if (unescaped === null) {
                            this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
                          }
                          str2 += unescaped;
                          break;
                        case "n":
                          str2 += "\n";
                          break;
                        case "r":
                          str2 += "\r";
                          break;
                        case "t":
                          str2 += "	";
                          break;
                        case "b":
                          str2 += "\b";
                          break;
                        case "f":
                          str2 += "\f";
                          break;
                        case "v":
                          str2 += "\v";
                          break;
                        case "8":
                        case "9":
                          str2 += ch;
                          this.tolerateUnexpectedToken();
                          break;
                        default:
                          if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
                            var octToDec = this.octalToDecimal(ch);
                            octal = octToDec.octal || octal;
                            str2 += String.fromCharCode(octToDec.code);
                          } else {
                            str2 += ch;
                          }
                          break;
                      }
                    } else {
                      ++this.lineNumber;
                      if (ch === "\r" && this.source[this.index] === "\n") {
                        ++this.index;
                      }
                      this.lineStart = this.index;
                    }
                  } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                    break;
                  } else {
                    str2 += ch;
                  }
                }
                if (quote3 !== "") {
                  this.index = start;
                  this.throwUnexpectedToken();
                }
                return {
                  type: 8,
                  value: str2,
                  octal,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanTemplate = function() {
                var cooked = "";
                var terminated = false;
                var start = this.index;
                var head = this.source[start] === "`";
                var tail = false;
                var rawOffset = 2;
                ++this.index;
                while (!this.eof()) {
                  var ch = this.source[this.index++];
                  if (ch === "`") {
                    rawOffset = 1;
                    tail = true;
                    terminated = true;
                    break;
                  } else if (ch === "$") {
                    if (this.source[this.index] === "{") {
                      this.curlyStack.push("${");
                      ++this.index;
                      terminated = true;
                      break;
                    }
                    cooked += ch;
                  } else if (ch === "\\") {
                    ch = this.source[this.index++];
                    if (!character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                      switch (ch) {
                        case "n":
                          cooked += "\n";
                          break;
                        case "r":
                          cooked += "\r";
                          break;
                        case "t":
                          cooked += "	";
                          break;
                        case "u":
                          if (this.source[this.index] === "{") {
                            ++this.index;
                            cooked += this.scanUnicodeCodePointEscape();
                          } else {
                            var restore = this.index;
                            var unescaped_2 = this.scanHexEscape(ch);
                            if (unescaped_2 !== null) {
                              cooked += unescaped_2;
                            } else {
                              this.index = restore;
                              cooked += ch;
                            }
                          }
                          break;
                        case "x":
                          var unescaped = this.scanHexEscape(ch);
                          if (unescaped === null) {
                            this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
                          }
                          cooked += unescaped;
                          break;
                        case "b":
                          cooked += "\b";
                          break;
                        case "f":
                          cooked += "\f";
                          break;
                        case "v":
                          cooked += "\v";
                          break;
                        default:
                          if (ch === "0") {
                            if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                              this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
                            }
                            cooked += "\0";
                          } else if (character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
                            this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
                          } else {
                            cooked += ch;
                          }
                          break;
                      }
                    } else {
                      ++this.lineNumber;
                      if (ch === "\r" && this.source[this.index] === "\n") {
                        ++this.index;
                      }
                      this.lineStart = this.index;
                    }
                  } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                    ++this.lineNumber;
                    if (ch === "\r" && this.source[this.index] === "\n") {
                      ++this.index;
                    }
                    this.lineStart = this.index;
                    cooked += "\n";
                  } else {
                    cooked += ch;
                  }
                }
                if (!terminated) {
                  this.throwUnexpectedToken();
                }
                if (!head) {
                  this.curlyStack.pop();
                }
                return {
                  type: 10,
                  value: this.source.slice(start + 1, this.index - rawOffset),
                  cooked,
                  head,
                  tail,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.testRegExp = function(pattern, flags) {
                var astralSubstitute = "\uFFFF";
                var tmp = pattern;
                var self2 = this;
                if (flags.indexOf("u") >= 0) {
                  tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function($0, $1, $2) {
                    var codePoint = parseInt($1 || $2, 16);
                    if (codePoint > 1114111) {
                      self2.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
                    }
                    if (codePoint <= 65535) {
                      return String.fromCharCode(codePoint);
                    }
                    return astralSubstitute;
                  }).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, astralSubstitute);
                }
                try {
                  RegExp(tmp);
                } catch (e2) {
                  this.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
                }
                try {
                  return new RegExp(pattern, flags);
                } catch (exception) {
                  return null;
                }
              };
              Scanner2.prototype.scanRegExpBody = function() {
                var ch = this.source[this.index];
                assert_1.assert(ch === "/", "Regular expression literal must start with a slash");
                var str2 = this.source[this.index++];
                var classMarker = false;
                var terminated = false;
                while (!this.eof()) {
                  ch = this.source[this.index++];
                  str2 += ch;
                  if (ch === "\\") {
                    ch = this.source[this.index++];
                    if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                      this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
                    }
                    str2 += ch;
                  } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                    this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
                  } else if (classMarker) {
                    if (ch === "]") {
                      classMarker = false;
                    }
                  } else {
                    if (ch === "/") {
                      terminated = true;
                      break;
                    } else if (ch === "[") {
                      classMarker = true;
                    }
                  }
                }
                if (!terminated) {
                  this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
                }
                return str2.substr(1, str2.length - 2);
              };
              Scanner2.prototype.scanRegExpFlags = function() {
                var str2 = "";
                var flags = "";
                while (!this.eof()) {
                  var ch = this.source[this.index];
                  if (!character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
                    break;
                  }
                  ++this.index;
                  if (ch === "\\" && !this.eof()) {
                    ch = this.source[this.index];
                    if (ch === "u") {
                      ++this.index;
                      var restore = this.index;
                      var char = this.scanHexEscape("u");
                      if (char !== null) {
                        flags += char;
                        for (str2 += "\\u"; restore < this.index; ++restore) {
                          str2 += this.source[restore];
                        }
                      } else {
                        this.index = restore;
                        flags += "u";
                        str2 += "\\u";
                      }
                      this.tolerateUnexpectedToken();
                    } else {
                      str2 += "\\";
                      this.tolerateUnexpectedToken();
                    }
                  } else {
                    flags += ch;
                    str2 += ch;
                  }
                }
                return flags;
              };
              Scanner2.prototype.scanRegExp = function() {
                var start = this.index;
                var pattern = this.scanRegExpBody();
                var flags = this.scanRegExpFlags();
                var value = this.testRegExp(pattern, flags);
                return {
                  type: 9,
                  value: "",
                  pattern,
                  flags,
                  regex: value,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.lex = function() {
                if (this.eof()) {
                  return {
                    type: 2,
                    value: "",
                    lineNumber: this.lineNumber,
                    lineStart: this.lineStart,
                    start: this.index,
                    end: this.index
                  };
                }
                var cp2 = this.source.charCodeAt(this.index);
                if (character_1.Character.isIdentifierStart(cp2)) {
                  return this.scanIdentifier();
                }
                if (cp2 === 40 || cp2 === 41 || cp2 === 59) {
                  return this.scanPunctuator();
                }
                if (cp2 === 39 || cp2 === 34) {
                  return this.scanStringLiteral();
                }
                if (cp2 === 46) {
                  if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index + 1))) {
                    return this.scanNumericLiteral();
                  }
                  return this.scanPunctuator();
                }
                if (character_1.Character.isDecimalDigit(cp2)) {
                  return this.scanNumericLiteral();
                }
                if (cp2 === 96 || cp2 === 125 && this.curlyStack[this.curlyStack.length - 1] === "${") {
                  return this.scanTemplate();
                }
                if (cp2 >= 55296 && cp2 < 57343) {
                  if (character_1.Character.isIdentifierStart(this.codePointAt(this.index))) {
                    return this.scanIdentifier();
                  }
                }
                return this.scanPunctuator();
              };
              return Scanner2;
            }();
            exports3.Scanner = Scanner;
          },
          /* 13 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            exports3.TokenName = {};
            exports3.TokenName[
              1
              /* BooleanLiteral */
            ] = "Boolean";
            exports3.TokenName[
              2
              /* EOF */
            ] = "<end>";
            exports3.TokenName[
              3
              /* Identifier */
            ] = "Identifier";
            exports3.TokenName[
              4
              /* Keyword */
            ] = "Keyword";
            exports3.TokenName[
              5
              /* NullLiteral */
            ] = "Null";
            exports3.TokenName[
              6
              /* NumericLiteral */
            ] = "Numeric";
            exports3.TokenName[
              7
              /* Punctuator */
            ] = "Punctuator";
            exports3.TokenName[
              8
              /* StringLiteral */
            ] = "String";
            exports3.TokenName[
              9
              /* RegularExpression */
            ] = "RegularExpression";
            exports3.TokenName[
              10
              /* Template */
            ] = "Template";
          },
          /* 14 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            exports3.XHTMLEntities = {
              quot: '"',
              amp: "&",
              apos: "'",
              gt: ">",
              nbsp: "\xA0",
              iexcl: "\xA1",
              cent: "\xA2",
              pound: "\xA3",
              curren: "\xA4",
              yen: "\xA5",
              brvbar: "\xA6",
              sect: "\xA7",
              uml: "\xA8",
              copy: "\xA9",
              ordf: "\xAA",
              laquo: "\xAB",
              not: "\xAC",
              shy: "\xAD",
              reg: "\xAE",
              macr: "\xAF",
              deg: "\xB0",
              plusmn: "\xB1",
              sup2: "\xB2",
              sup3: "\xB3",
              acute: "\xB4",
              micro: "\xB5",
              para: "\xB6",
              middot: "\xB7",
              cedil: "\xB8",
              sup1: "\xB9",
              ordm: "\xBA",
              raquo: "\xBB",
              frac14: "\xBC",
              frac12: "\xBD",
              frac34: "\xBE",
              iquest: "\xBF",
              Agrave: "\xC0",
              Aacute: "\xC1",
              Acirc: "\xC2",
              Atilde: "\xC3",
              Auml: "\xC4",
              Aring: "\xC5",
              AElig: "\xC6",
              Ccedil: "\xC7",
              Egrave: "\xC8",
              Eacute: "\xC9",
              Ecirc: "\xCA",
              Euml: "\xCB",
              Igrave: "\xCC",
              Iacute: "\xCD",
              Icirc: "\xCE",
              Iuml: "\xCF",
              ETH: "\xD0",
              Ntilde: "\xD1",
              Ograve: "\xD2",
              Oacute: "\xD3",
              Ocirc: "\xD4",
              Otilde: "\xD5",
              Ouml: "\xD6",
              times: "\xD7",
              Oslash: "\xD8",
              Ugrave: "\xD9",
              Uacute: "\xDA",
              Ucirc: "\xDB",
              Uuml: "\xDC",
              Yacute: "\xDD",
              THORN: "\xDE",
              szlig: "\xDF",
              agrave: "\xE0",
              aacute: "\xE1",
              acirc: "\xE2",
              atilde: "\xE3",
              auml: "\xE4",
              aring: "\xE5",
              aelig: "\xE6",
              ccedil: "\xE7",
              egrave: "\xE8",
              eacute: "\xE9",
              ecirc: "\xEA",
              euml: "\xEB",
              igrave: "\xEC",
              iacute: "\xED",
              icirc: "\xEE",
              iuml: "\xEF",
              eth: "\xF0",
              ntilde: "\xF1",
              ograve: "\xF2",
              oacute: "\xF3",
              ocirc: "\xF4",
              otilde: "\xF5",
              ouml: "\xF6",
              divide: "\xF7",
              oslash: "\xF8",
              ugrave: "\xF9",
              uacute: "\xFA",
              ucirc: "\xFB",
              uuml: "\xFC",
              yacute: "\xFD",
              thorn: "\xFE",
              yuml: "\xFF",
              OElig: "\u0152",
              oelig: "\u0153",
              Scaron: "\u0160",
              scaron: "\u0161",
              Yuml: "\u0178",
              fnof: "\u0192",
              circ: "\u02C6",
              tilde: "\u02DC",
              Alpha: "\u0391",
              Beta: "\u0392",
              Gamma: "\u0393",
              Delta: "\u0394",
              Epsilon: "\u0395",
              Zeta: "\u0396",
              Eta: "\u0397",
              Theta: "\u0398",
              Iota: "\u0399",
              Kappa: "\u039A",
              Lambda: "\u039B",
              Mu: "\u039C",
              Nu: "\u039D",
              Xi: "\u039E",
              Omicron: "\u039F",
              Pi: "\u03A0",
              Rho: "\u03A1",
              Sigma: "\u03A3",
              Tau: "\u03A4",
              Upsilon: "\u03A5",
              Phi: "\u03A6",
              Chi: "\u03A7",
              Psi: "\u03A8",
              Omega: "\u03A9",
              alpha: "\u03B1",
              beta: "\u03B2",
              gamma: "\u03B3",
              delta: "\u03B4",
              epsilon: "\u03B5",
              zeta: "\u03B6",
              eta: "\u03B7",
              theta: "\u03B8",
              iota: "\u03B9",
              kappa: "\u03BA",
              lambda: "\u03BB",
              mu: "\u03BC",
              nu: "\u03BD",
              xi: "\u03BE",
              omicron: "\u03BF",
              pi: "\u03C0",
              rho: "\u03C1",
              sigmaf: "\u03C2",
              sigma: "\u03C3",
              tau: "\u03C4",
              upsilon: "\u03C5",
              phi: "\u03C6",
              chi: "\u03C7",
              psi: "\u03C8",
              omega: "\u03C9",
              thetasym: "\u03D1",
              upsih: "\u03D2",
              piv: "\u03D6",
              ensp: "\u2002",
              emsp: "\u2003",
              thinsp: "\u2009",
              zwnj: "\u200C",
              zwj: "\u200D",
              lrm: "\u200E",
              rlm: "\u200F",
              ndash: "\u2013",
              mdash: "\u2014",
              lsquo: "\u2018",
              rsquo: "\u2019",
              sbquo: "\u201A",
              ldquo: "\u201C",
              rdquo: "\u201D",
              bdquo: "\u201E",
              dagger: "\u2020",
              Dagger: "\u2021",
              bull: "\u2022",
              hellip: "\u2026",
              permil: "\u2030",
              prime: "\u2032",
              Prime: "\u2033",
              lsaquo: "\u2039",
              rsaquo: "\u203A",
              oline: "\u203E",
              frasl: "\u2044",
              euro: "\u20AC",
              image: "\u2111",
              weierp: "\u2118",
              real: "\u211C",
              trade: "\u2122",
              alefsym: "\u2135",
              larr: "\u2190",
              uarr: "\u2191",
              rarr: "\u2192",
              darr: "\u2193",
              harr: "\u2194",
              crarr: "\u21B5",
              lArr: "\u21D0",
              uArr: "\u21D1",
              rArr: "\u21D2",
              dArr: "\u21D3",
              hArr: "\u21D4",
              forall: "\u2200",
              part: "\u2202",
              exist: "\u2203",
              empty: "\u2205",
              nabla: "\u2207",
              isin: "\u2208",
              notin: "\u2209",
              ni: "\u220B",
              prod: "\u220F",
              sum: "\u2211",
              minus: "\u2212",
              lowast: "\u2217",
              radic: "\u221A",
              prop: "\u221D",
              infin: "\u221E",
              ang: "\u2220",
              and: "\u2227",
              or: "\u2228",
              cap: "\u2229",
              cup: "\u222A",
              int: "\u222B",
              there4: "\u2234",
              sim: "\u223C",
              cong: "\u2245",
              asymp: "\u2248",
              ne: "\u2260",
              equiv: "\u2261",
              le: "\u2264",
              ge: "\u2265",
              sub: "\u2282",
              sup: "\u2283",
              nsub: "\u2284",
              sube: "\u2286",
              supe: "\u2287",
              oplus: "\u2295",
              otimes: "\u2297",
              perp: "\u22A5",
              sdot: "\u22C5",
              lceil: "\u2308",
              rceil: "\u2309",
              lfloor: "\u230A",
              rfloor: "\u230B",
              loz: "\u25CA",
              spades: "\u2660",
              clubs: "\u2663",
              hearts: "\u2665",
              diams: "\u2666",
              lang: "\u27E8",
              rang: "\u27E9"
            };
          },
          /* 15 */
          /***/
          function(module3, exports3, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var error_handler_1 = __webpack_require__(10);
            var scanner_1 = __webpack_require__(12);
            var token_1 = __webpack_require__(13);
            var Reader = function() {
              function Reader2() {
                this.values = [];
                this.curly = this.paren = -1;
              }
              __name(Reader2, "Reader");
              Reader2.prototype.beforeFunctionExpression = function(t2) {
                return [
                  "(",
                  "{",
                  "[",
                  "in",
                  "typeof",
                  "instanceof",
                  "new",
                  "return",
                  "case",
                  "delete",
                  "throw",
                  "void",
                  // assignment operators
                  "=",
                  "+=",
                  "-=",
                  "*=",
                  "**=",
                  "/=",
                  "%=",
                  "<<=",
                  ">>=",
                  ">>>=",
                  "&=",
                  "|=",
                  "^=",
                  ",",
                  // binary/unary operators
                  "+",
                  "-",
                  "*",
                  "**",
                  "/",
                  "%",
                  "++",
                  "--",
                  "<<",
                  ">>",
                  ">>>",
                  "&",
                  "|",
                  "^",
                  "!",
                  "~",
                  "&&",
                  "||",
                  "?",
                  ":",
                  "===",
                  "==",
                  ">=",
                  "<=",
                  "<",
                  ">",
                  "!=",
                  "!=="
                ].indexOf(t2) >= 0;
              };
              Reader2.prototype.isRegexStart = function() {
                var previous = this.values[this.values.length - 1];
                var regex3 = previous !== null;
                switch (previous) {
                  case "this":
                  case "]":
                    regex3 = false;
                    break;
                  case ")":
                    var keyword = this.values[this.paren - 1];
                    regex3 = keyword === "if" || keyword === "while" || keyword === "for" || keyword === "with";
                    break;
                  case "}":
                    regex3 = false;
                    if (this.values[this.curly - 3] === "function") {
                      var check = this.values[this.curly - 4];
                      regex3 = check ? !this.beforeFunctionExpression(check) : false;
                    } else if (this.values[this.curly - 4] === "function") {
                      var check = this.values[this.curly - 5];
                      regex3 = check ? !this.beforeFunctionExpression(check) : true;
                    }
                    break;
                  default:
                    break;
                }
                return regex3;
              };
              Reader2.prototype.push = function(token2) {
                if (token2.type === 7 || token2.type === 4) {
                  if (token2.value === "{") {
                    this.curly = this.values.length;
                  } else if (token2.value === "(") {
                    this.paren = this.values.length;
                  }
                  this.values.push(token2.value);
                } else {
                  this.values.push(null);
                }
              };
              return Reader2;
            }();
            var Tokenizer2 = function() {
              function Tokenizer3(code2, config) {
                this.errorHandler = new error_handler_1.ErrorHandler();
                this.errorHandler.tolerant = config ? typeof config.tolerant === "boolean" && config.tolerant : false;
                this.scanner = new scanner_1.Scanner(code2, this.errorHandler);
                this.scanner.trackComment = config ? typeof config.comment === "boolean" && config.comment : false;
                this.trackRange = config ? typeof config.range === "boolean" && config.range : false;
                this.trackLoc = config ? typeof config.loc === "boolean" && config.loc : false;
                this.buffer = [];
                this.reader = new Reader();
              }
              __name(Tokenizer3, "Tokenizer");
              Tokenizer3.prototype.errors = function() {
                return this.errorHandler.errors;
              };
              Tokenizer3.prototype.getNextToken = function() {
                if (this.buffer.length === 0) {
                  var comments = this.scanner.scanComments();
                  if (this.scanner.trackComment) {
                    for (var i = 0; i < comments.length; ++i) {
                      var e2 = comments[i];
                      var value = this.scanner.source.slice(e2.slice[0], e2.slice[1]);
                      var comment = {
                        type: e2.multiLine ? "BlockComment" : "LineComment",
                        value
                      };
                      if (this.trackRange) {
                        comment.range = e2.range;
                      }
                      if (this.trackLoc) {
                        comment.loc = e2.loc;
                      }
                      this.buffer.push(comment);
                    }
                  }
                  if (!this.scanner.eof()) {
                    var loc = void 0;
                    if (this.trackLoc) {
                      loc = {
                        start: {
                          line: this.scanner.lineNumber,
                          column: this.scanner.index - this.scanner.lineStart
                        },
                        end: {}
                      };
                    }
                    var startRegex = this.scanner.source[this.scanner.index] === "/" && this.reader.isRegexStart();
                    var token2 = startRegex ? this.scanner.scanRegExp() : this.scanner.lex();
                    this.reader.push(token2);
                    var entry = {
                      type: token_1.TokenName[token2.type],
                      value: this.scanner.source.slice(token2.start, token2.end)
                    };
                    if (this.trackRange) {
                      entry.range = [token2.start, token2.end];
                    }
                    if (this.trackLoc) {
                      loc.end = {
                        line: this.scanner.lineNumber,
                        column: this.scanner.index - this.scanner.lineStart
                      };
                      entry.loc = loc;
                    }
                    if (token2.type === 9) {
                      var pattern = token2.pattern;
                      var flags = token2.flags;
                      entry.regex = { pattern, flags };
                    }
                    this.buffer.push(entry);
                  }
                }
                return this.buffer.shift();
              };
              return Tokenizer3;
            }();
            exports3.Tokenizer = Tokenizer2;
          }
          /******/
        ])
      );
    });
  }
});

// node_modules/core-util-is/lib/util.js
var require_util17 = __commonJS({
  "node_modules/core-util-is/lib/util.js"(exports2) {
    init_esbuild_shims();
    function isArray2(arg) {
      if (Array.isArray) {
        return Array.isArray(arg);
      }
      return objectToString2(arg) === "[object Array]";
    }
    __name(isArray2, "isArray");
    exports2.isArray = isArray2;
    function isBoolean2(arg) {
      return typeof arg === "boolean";
    }
    __name(isBoolean2, "isBoolean");
    exports2.isBoolean = isBoolean2;
    function isNull(arg) {
      return arg === null;
    }
    __name(isNull, "isNull");
    exports2.isNull = isNull;
    function isNullOrUndefined(arg) {
      return arg == null;
    }
    __name(isNullOrUndefined, "isNullOrUndefined");
    exports2.isNullOrUndefined = isNullOrUndefined;
    function isNumber3(arg) {
      return typeof arg === "number";
    }
    __name(isNumber3, "isNumber");
    exports2.isNumber = isNumber3;
    function isString2(arg) {
      return typeof arg === "string";
    }
    __name(isString2, "isString");
    exports2.isString = isString2;
    function isSymbol(arg) {
      return typeof arg === "symbol";
    }
    __name(isSymbol, "isSymbol");
    exports2.isSymbol = isSymbol;
    function isUndefined2(arg) {
      return arg === void 0;
    }
    __name(isUndefined2, "isUndefined");
    exports2.isUndefined = isUndefined2;
    function isRegExp(re2) {
      return objectToString2(re2) === "[object RegExp]";
    }
    __name(isRegExp, "isRegExp");
    exports2.isRegExp = isRegExp;
    function isObject3(arg) {
      return typeof arg === "object" && arg !== null;
    }
    __name(isObject3, "isObject");
    exports2.isObject = isObject3;
    function isDate(d) {
      return objectToString2(d) === "[object Date]";
    }
    __name(isDate, "isDate");
    exports2.isDate = isDate;
    function isError(e2) {
      return objectToString2(e2) === "[object Error]" || e2 instanceof Error;
    }
    __name(isError, "isError");
    exports2.isError = isError;
    function isFunction3(arg) {
      return typeof arg === "function";
    }
    __name(isFunction3, "isFunction");
    exports2.isFunction = isFunction3;
    function isPrimitive(arg) {
      return arg === null || typeof arg === "boolean" || typeof arg === "number" || typeof arg === "string" || typeof arg === "symbol" || // ES6 symbol
      typeof arg === "undefined";
    }
    __name(isPrimitive, "isPrimitive");
    exports2.isPrimitive = isPrimitive;
    exports2.isBuffer = __require("buffer").Buffer.isBuffer;
    function objectToString2(o2) {
      return Object.prototype.toString.call(o2);
    }
    __name(objectToString2, "objectToString");
  }
});

// node_modules/array-timsort/src/index.js
var require_src37 = __commonJS({
  "node_modules/array-timsort/src/index.js"(exports2, module2) {
    init_esbuild_shims();
    var DEFAULT_MIN_MERGE = 32;
    var DEFAULT_MIN_GALLOPING = 7;
    var DEFAULT_TMP_STORAGE_LENGTH = 256;
    var POWERS_OF_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9];
    var results;
    var log10 = /* @__PURE__ */ __name((x) => x < 1e5 ? x < 100 ? x < 10 ? 0 : 1 : x < 1e4 ? x < 1e3 ? 2 : 3 : 4 : x < 1e7 ? x < 1e6 ? 5 : 6 : x < 1e9 ? x < 1e8 ? 7 : 8 : 9, "log10");
    function alphabeticalCompare(a, b) {
      if (a === b) {
        return 0;
      }
      if (~~a === a && ~~b === b) {
        if (a === 0 || b === 0) {
          return a < b ? -1 : 1;
        }
        if (a < 0 || b < 0) {
          if (b >= 0) {
            return -1;
          }
          if (a >= 0) {
            return 1;
          }
          a = -a;
          b = -b;
        }
        const al = log10(a);
        const bl = log10(b);
        let t2 = 0;
        if (al < bl) {
          a *= POWERS_OF_TEN[bl - al - 1];
          b /= 10;
          t2 = -1;
        } else if (al > bl) {
          b *= POWERS_OF_TEN[al - bl - 1];
          a /= 10;
          t2 = 1;
        }
        if (a === b) {
          return t2;
        }
        return a < b ? -1 : 1;
      }
      const aStr = String(a);
      const bStr = String(b);
      if (aStr === bStr) {
        return 0;
      }
      return aStr < bStr ? -1 : 1;
    }
    __name(alphabeticalCompare, "alphabeticalCompare");
    function minRunLength(n2) {
      let r3 = 0;
      while (n2 >= DEFAULT_MIN_MERGE) {
        r3 |= n2 & 1;
        n2 >>= 1;
      }
      return n2 + r3;
    }
    __name(minRunLength, "minRunLength");
    function makeAscendingRun(array, lo, hi, compare) {
      let runHi = lo + 1;
      if (runHi === hi) {
        return 1;
      }
      if (compare(array[runHi++], array[lo]) < 0) {
        while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
          runHi++;
        }
        reverseRun(array, lo, runHi);
        reverseRun(results, lo, runHi);
      } else {
        while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
          runHi++;
        }
      }
      return runHi - lo;
    }
    __name(makeAscendingRun, "makeAscendingRun");
    function reverseRun(array, lo, hi) {
      hi--;
      while (lo < hi) {
        const t2 = array[lo];
        array[lo++] = array[hi];
        array[hi--] = t2;
      }
    }
    __name(reverseRun, "reverseRun");
    function binaryInsertionSort(array, lo, hi, start, compare) {
      if (start === lo) {
        start++;
      }
      for (; start < hi; start++) {
        const pivot = array[start];
        const pivotIndex = results[start];
        let left3 = lo;
        let right3 = start;
        while (left3 < right3) {
          const mid = left3 + right3 >>> 1;
          if (compare(pivot, array[mid]) < 0) {
            right3 = mid;
          } else {
            left3 = mid + 1;
          }
        }
        let n2 = start - left3;
        switch (n2) {
          case 3:
            array[left3 + 3] = array[left3 + 2];
            results[left3 + 3] = results[left3 + 2];
          /* falls through */
          case 2:
            array[left3 + 2] = array[left3 + 1];
            results[left3 + 2] = results[left3 + 1];
          /* falls through */
          case 1:
            array[left3 + 1] = array[left3];
            results[left3 + 1] = results[left3];
            break;
          default:
            while (n2 > 0) {
              array[left3 + n2] = array[left3 + n2 - 1];
              results[left3 + n2] = results[left3 + n2 - 1];
              n2--;
            }
        }
        array[left3] = pivot;
        results[left3] = pivotIndex;
      }
    }
    __name(binaryInsertionSort, "binaryInsertionSort");
    function gallopLeft(value, array, start, length, hint, compare) {
      let lastOffset = 0;
      let maxOffset = 0;
      let offset = 1;
      if (compare(value, array[start + hint]) > 0) {
        maxOffset = length - hint;
        while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
          lastOffset = offset;
          offset = (offset << 1) + 1;
          if (offset <= 0) {
            offset = maxOffset;
          }
        }
        if (offset > maxOffset) {
          offset = maxOffset;
        }
        lastOffset += hint;
        offset += hint;
      } else {
        maxOffset = hint + 1;
        while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
          lastOffset = offset;
          offset = (offset << 1) + 1;
          if (offset <= 0) {
            offset = maxOffset;
          }
        }
        if (offset > maxOffset) {
          offset = maxOffset;
        }
        const tmp = lastOffset;
        lastOffset = hint - offset;
        offset = hint - tmp;
      }
      lastOffset++;
      while (lastOffset < offset) {
        const m = lastOffset + (offset - lastOffset >>> 1);
        if (compare(value, array[start + m]) > 0) {
          lastOffset = m + 1;
        } else {
          offset = m;
        }
      }
      return offset;
    }
    __name(gallopLeft, "gallopLeft");
    function gallopRight(value, array, start, length, hint, compare) {
      let lastOffset = 0;
      let maxOffset = 0;
      let offset = 1;
      if (compare(value, array[start + hint]) < 0) {
        maxOffset = hint + 1;
        while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
          lastOffset = offset;
          offset = (offset << 1) + 1;
          if (offset <= 0) {
            offset = maxOffset;
          }
        }
        if (offset > maxOffset) {
          offset = maxOffset;
        }
        const tmp = lastOffset;
        lastOffset = hint - offset;
        offset = hint - tmp;
      } else {
        maxOffset = length - hint;
        while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
          lastOffset = offset;
          offset = (offset << 1) + 1;
          if (offset <= 0) {
            offset = maxOffset;
          }
        }
        if (offset > maxOffset) {
          offset = maxOffset;
        }
        lastOffset += hint;
        offset += hint;
      }
      lastOffset++;
      while (lastOffset < offset) {
        const m = lastOffset + (offset - lastOffset >>> 1);
        if (compare(value, array[start + m]) < 0) {
          offset = m;
        } else {
          lastOffset = m + 1;
        }
      }
      return offset;
    }
    __name(gallopRight, "gallopRight");
    var TimSort = class {
      static {
        __name(this, "TimSort");
      }
      constructor(array, compare) {
        this.array = array;
        this.compare = compare;
        const { length } = array;
        this.length = length;
        this.minGallop = DEFAULT_MIN_GALLOPING;
        this.tmpStorageLength = length < 2 * DEFAULT_TMP_STORAGE_LENGTH ? length >>> 1 : DEFAULT_TMP_STORAGE_LENGTH;
        this.tmp = new Array(this.tmpStorageLength);
        this.tmpIndex = new Array(this.tmpStorageLength);
        this.stackLength = length < 120 ? 5 : length < 1542 ? 10 : length < 119151 ? 19 : 40;
        this.runStart = new Array(this.stackLength);
        this.runLength = new Array(this.stackLength);
        this.stackSize = 0;
      }
      /**
       * Push a new run on TimSort's stack.
       *
       * @param {number} runStart - Start index of the run in the original array.
       * @param {number} runLength - Length of the run;
       */
      pushRun(runStart, runLength) {
        this.runStart[this.stackSize] = runStart;
        this.runLength[this.stackSize] = runLength;
        this.stackSize += 1;
      }
      /**
       * Merge runs on TimSort's stack so that the following holds for all i:
       * 1) runLength[i - 3] > runLength[i - 2] + runLength[i - 1]
       * 2) runLength[i - 2] > runLength[i - 1]
       */
      mergeRuns() {
        while (this.stackSize > 1) {
          let n2 = this.stackSize - 2;
          if (n2 >= 1 && this.runLength[n2 - 1] <= this.runLength[n2] + this.runLength[n2 + 1] || n2 >= 2 && this.runLength[n2 - 2] <= this.runLength[n2] + this.runLength[n2 - 1]) {
            if (this.runLength[n2 - 1] < this.runLength[n2 + 1]) {
              n2--;
            }
          } else if (this.runLength[n2] > this.runLength[n2 + 1]) {
            break;
          }
          this.mergeAt(n2);
        }
      }
      /**
       * Merge all runs on TimSort's stack until only one remains.
       */
      forceMergeRuns() {
        while (this.stackSize > 1) {
          let n2 = this.stackSize - 2;
          if (n2 > 0 && this.runLength[n2 - 1] < this.runLength[n2 + 1]) {
            n2--;
          }
          this.mergeAt(n2);
        }
      }
      /**
       * Merge the runs on the stack at positions i and i+1. Must be always be called
       * with i=stackSize-2 or i=stackSize-3 (that is, we merge on top of the stack).
       *
       * @param {number} i - Index of the run to merge in TimSort's stack.
       */
      mergeAt(i) {
        const { compare } = this;
        const { array } = this;
        let start1 = this.runStart[i];
        let length1 = this.runLength[i];
        const start2 = this.runStart[i + 1];
        let length2 = this.runLength[i + 1];
        this.runLength[i] = length1 + length2;
        if (i === this.stackSize - 3) {
          this.runStart[i + 1] = this.runStart[i + 2];
          this.runLength[i + 1] = this.runLength[i + 2];
        }
        this.stackSize--;
        const k = gallopRight(array[start2], array, start1, length1, 0, compare);
        start1 += k;
        length1 -= k;
        if (length1 === 0) {
          return;
        }
        length2 = gallopLeft(
          array[start1 + length1 - 1],
          array,
          start2,
          length2,
          length2 - 1,
          compare
        );
        if (length2 === 0) {
          return;
        }
        if (length1 <= length2) {
          this.mergeLow(start1, length1, start2, length2);
        } else {
          this.mergeHigh(start1, length1, start2, length2);
        }
      }
      /**
       * Merge two adjacent runs in a stable way. The runs must be such that the
       * first element of run1 is bigger than the first element in run2 and the
       * last element of run1 is greater than all the elements in run2.
       * The method should be called when run1.length <= run2.length as it uses
       * TimSort temporary array to store run1. Use mergeHigh if run1.length >
       * run2.length.
       *
       * @param {number} start1 - First element in run1.
       * @param {number} length1 - Length of run1.
       * @param {number} start2 - First element in run2.
       * @param {number} length2 - Length of run2.
       */
      mergeLow(start1, length1, start2, length2) {
        const { compare } = this;
        const { array } = this;
        const { tmp } = this;
        const { tmpIndex } = this;
        let i = 0;
        for (i = 0; i < length1; i++) {
          tmp[i] = array[start1 + i];
          tmpIndex[i] = results[start1 + i];
        }
        let cursor1 = 0;
        let cursor2 = start2;
        let dest = start1;
        array[dest] = array[cursor2];
        results[dest] = results[cursor2];
        dest++;
        cursor2++;
        if (--length2 === 0) {
          for (i = 0; i < length1; i++) {
            array[dest + i] = tmp[cursor1 + i];
            results[dest + i] = tmpIndex[cursor1 + i];
          }
          return;
        }
        if (length1 === 1) {
          for (i = 0; i < length2; i++) {
            array[dest + i] = array[cursor2 + i];
            results[dest + i] = results[cursor2 + i];
          }
          array[dest + length2] = tmp[cursor1];
          results[dest + length2] = tmpIndex[cursor1];
          return;
        }
        let { minGallop } = this;
        while (true) {
          let count1 = 0;
          let count2 = 0;
          let exit = false;
          do {
            if (compare(array[cursor2], tmp[cursor1]) < 0) {
              array[dest] = array[cursor2];
              results[dest] = results[cursor2];
              dest++;
              cursor2++;
              count2++;
              count1 = 0;
              if (--length2 === 0) {
                exit = true;
                break;
              }
            } else {
              array[dest] = tmp[cursor1];
              results[dest] = tmpIndex[cursor1];
              dest++;
              cursor1++;
              count1++;
              count2 = 0;
              if (--length1 === 1) {
                exit = true;
                break;
              }
            }
          } while ((count1 | count2) < minGallop);
          if (exit) {
            break;
          }
          do {
            count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
            if (count1 !== 0) {
              for (i = 0; i < count1; i++) {
                array[dest + i] = tmp[cursor1 + i];
                results[dest + i] = tmpIndex[cursor1 + i];
              }
              dest += count1;
              cursor1 += count1;
              length1 -= count1;
              if (length1 <= 1) {
                exit = true;
                break;
              }
            }
            array[dest] = array[cursor2];
            results[dest] = results[cursor2];
            dest++;
            cursor2++;
            if (--length2 === 0) {
              exit = true;
              break;
            }
            count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
            if (count2 !== 0) {
              for (i = 0; i < count2; i++) {
                array[dest + i] = array[cursor2 + i];
                results[dest + i] = results[cursor2 + i];
              }
              dest += count2;
              cursor2 += count2;
              length2 -= count2;
              if (length2 === 0) {
                exit = true;
                break;
              }
            }
            array[dest] = tmp[cursor1];
            results[dest] = tmpIndex[cursor1];
            dest++;
            cursor1++;
            if (--length1 === 1) {
              exit = true;
              break;
            }
            minGallop--;
          } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
          if (exit) {
            break;
          }
          if (minGallop < 0) {
            minGallop = 0;
          }
          minGallop += 2;
        }
        this.minGallop = minGallop;
        if (minGallop < 1) {
          this.minGallop = 1;
        }
        if (length1 === 1) {
          for (i = 0; i < length2; i++) {
            array[dest + i] = array[cursor2 + i];
            results[dest + i] = results[cursor2 + i];
          }
          array[dest + length2] = tmp[cursor1];
          results[dest + length2] = tmpIndex[cursor1];
        } else if (length1 === 0) {
          throw new Error("mergeLow preconditions were not respected");
        } else {
          for (i = 0; i < length1; i++) {
            array[dest + i] = tmp[cursor1 + i];
            results[dest + i] = tmpIndex[cursor1 + i];
          }
        }
      }
      /**
       * Merge two adjacent runs in a stable way. The runs must be such that the
       * first element of run1 is bigger than the first element in run2 and the
       * last element of run1 is greater than all the elements in run2.
       * The method should be called when run1.length > run2.length as it uses
       * TimSort temporary array to store run2. Use mergeLow if run1.length <=
       * run2.length.
       *
       * @param {number} start1 - First element in run1.
       * @param {number} length1 - Length of run1.
       * @param {number} start2 - First element in run2.
       * @param {number} length2 - Length of run2.
       */
      mergeHigh(start1, length1, start2, length2) {
        const { compare } = this;
        const { array } = this;
        const { tmp } = this;
        const { tmpIndex } = this;
        let i = 0;
        for (i = 0; i < length2; i++) {
          tmp[i] = array[start2 + i];
          tmpIndex[i] = results[start2 + i];
        }
        let cursor1 = start1 + length1 - 1;
        let cursor2 = length2 - 1;
        let dest = start2 + length2 - 1;
        let customCursor = 0;
        let customDest = 0;
        array[dest] = array[cursor1];
        results[dest] = results[cursor1];
        dest--;
        cursor1--;
        if (--length1 === 0) {
          customCursor = dest - (length2 - 1);
          for (i = 0; i < length2; i++) {
            array[customCursor + i] = tmp[i];
            results[customCursor + i] = tmpIndex[i];
          }
          return;
        }
        if (length2 === 1) {
          dest -= length1;
          cursor1 -= length1;
          customDest = dest + 1;
          customCursor = cursor1 + 1;
          for (i = length1 - 1; i >= 0; i--) {
            array[customDest + i] = array[customCursor + i];
            results[customDest + i] = results[customCursor + i];
          }
          array[dest] = tmp[cursor2];
          results[dest] = tmpIndex[cursor2];
          return;
        }
        let { minGallop } = this;
        while (true) {
          let count1 = 0;
          let count2 = 0;
          let exit = false;
          do {
            if (compare(tmp[cursor2], array[cursor1]) < 0) {
              array[dest] = array[cursor1];
              results[dest] = results[cursor1];
              dest--;
              cursor1--;
              count1++;
              count2 = 0;
              if (--length1 === 0) {
                exit = true;
                break;
              }
            } else {
              array[dest] = tmp[cursor2];
              results[dest] = tmpIndex[cursor2];
              dest--;
              cursor2--;
              count2++;
              count1 = 0;
              if (--length2 === 1) {
                exit = true;
                break;
              }
            }
          } while ((count1 | count2) < minGallop);
          if (exit) {
            break;
          }
          do {
            count1 = length1 - gallopRight(
              tmp[cursor2],
              array,
              start1,
              length1,
              length1 - 1,
              compare
            );
            if (count1 !== 0) {
              dest -= count1;
              cursor1 -= count1;
              length1 -= count1;
              customDest = dest + 1;
              customCursor = cursor1 + 1;
              for (i = count1 - 1; i >= 0; i--) {
                array[customDest + i] = array[customCursor + i];
                results[customDest + i] = results[customCursor + i];
              }
              if (length1 === 0) {
                exit = true;
                break;
              }
            }
            array[dest] = tmp[cursor2];
            results[dest] = tmpIndex[cursor2];
            dest--;
            cursor2--;
            if (--length2 === 1) {
              exit = true;
              break;
            }
            count2 = length2 - gallopLeft(
              array[cursor1],
              tmp,
              0,
              length2,
              length2 - 1,
              compare
            );
            if (count2 !== 0) {
              dest -= count2;
              cursor2 -= count2;
              length2 -= count2;
              customDest = dest + 1;
              customCursor = cursor2 + 1;
              for (i = 0; i < count2; i++) {
                array[customDest + i] = tmp[customCursor + i];
                results[customDest + i] = tmpIndex[customCursor + i];
              }
              if (length2 <= 1) {
                exit = true;
                break;
              }
            }
            array[dest] = array[cursor1];
            results[dest] = results[cursor1];
            dest--;
            cursor1--;
            if (--length1 === 0) {
              exit = true;
              break;
            }
            minGallop--;
          } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
          if (exit) {
            break;
          }
          if (minGallop < 0) {
            minGallop = 0;
          }
          minGallop += 2;
        }
        this.minGallop = minGallop;
        if (minGallop < 1) {
          this.minGallop = 1;
        }
        if (length2 === 1) {
          dest -= length1;
          cursor1 -= length1;
          customDest = dest + 1;
          customCursor = cursor1 + 1;
          for (i = length1 - 1; i >= 0; i--) {
            array[customDest + i] = array[customCursor + i];
            results[customDest + i] = results[customCursor + i];
          }
          array[dest] = tmp[cursor2];
          results[dest] = tmpIndex[cursor2];
        } else if (length2 === 0) {
          throw new Error("mergeHigh preconditions were not respected");
        } else {
          customCursor = dest - (length2 - 1);
          for (i = 0; i < length2; i++) {
            array[customCursor + i] = tmp[i];
            results[customCursor + i] = tmpIndex[i];
          }
        }
      }
    };
    function sort(array, compare, lo, hi) {
      if (!Array.isArray(array)) {
        throw new TypeError(
          `The "array" argument must be an array. Received ${array}`
        );
      }
      results = [];
      const { length } = array;
      let i = 0;
      while (i < length) {
        results[i] = i++;
      }
      if (!compare) {
        compare = alphabeticalCompare;
      } else if (typeof compare !== "function") {
        hi = lo;
        lo = compare;
        compare = alphabeticalCompare;
      }
      if (!lo) {
        lo = 0;
      }
      if (!hi) {
        hi = length;
      }
      let remaining = hi - lo;
      if (remaining < 2) {
        return results;
      }
      let runLength = 0;
      if (remaining < DEFAULT_MIN_MERGE) {
        runLength = makeAscendingRun(array, lo, hi, compare);
        binaryInsertionSort(array, lo, hi, lo + runLength, compare);
        return results;
      }
      const ts = new TimSort(array, compare);
      const minRun = minRunLength(remaining);
      do {
        runLength = makeAscendingRun(array, lo, hi, compare);
        if (runLength < minRun) {
          let force = remaining;
          if (force > minRun) {
            force = minRun;
          }
          binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
          runLength = force;
        }
        ts.pushRun(lo, runLength);
        ts.mergeRuns();
        remaining -= runLength;
        lo += runLength;
      } while (remaining !== 0);
      ts.forceMergeRuns();
      return results;
    }
    __name(sort, "sort");
    module2.exports = {
      sort
    };
  }
});

// node_modules/has-own-prop/index.js
var require_has_own_prop = __commonJS({
  "node_modules/has-own-prop/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var hasOwnProp = Object.prototype.hasOwnProperty;
    module2.exports = (object, property) => hasOwnProp.call(object, property);
  }
});

// node_modules/comment-json/src/common.js
var require_common5 = __commonJS({
  "node_modules/comment-json/src/common.js"(exports2, module2) {
    init_esbuild_shims();
    var hasOwnProperty2 = require_has_own_prop();
    var {
      isObject: isObject3,
      isArray: isArray2,
      isString: isString2,
      isNumber: isNumber3
    } = require_util17();
    var PREFIX_BEFORE = "before";
    var PREFIX_AFTER_PROP = "after-prop";
    var PREFIX_AFTER_COLON = "after-colon";
    var PREFIX_AFTER_VALUE = "after-value";
    var PREFIX_AFTER = "after";
    var PREFIX_BEFORE_ALL = "before-all";
    var PREFIX_AFTER_ALL = "after-all";
    var BRACKET_OPEN = "[";
    var BRACKET_CLOSE = "]";
    var CURLY_BRACKET_OPEN = "{";
    var CURLY_BRACKET_CLOSE = "}";
    var COMMA = ",";
    var EMPTY2 = "";
    var MINUS = "-";
    var SYMBOL_PREFIXES = [
      PREFIX_BEFORE,
      PREFIX_AFTER_PROP,
      PREFIX_AFTER_COLON,
      PREFIX_AFTER_VALUE,
      PREFIX_AFTER
    ];
    var NON_PROP_SYMBOL_KEYS = [
      PREFIX_BEFORE,
      PREFIX_BEFORE_ALL,
      PREFIX_AFTER_ALL
    ].map(Symbol.for);
    var COLON = ":";
    var UNDEFINED = void 0;
    var symbol = /* @__PURE__ */ __name((prefix, key) => Symbol.for(prefix + COLON + key), "symbol");
    var define2 = /* @__PURE__ */ __name((target, key, value) => Object.defineProperty(target, key, {
      value,
      writable: true,
      configurable: true
    }), "define");
    var copy_comments_by_kind = /* @__PURE__ */ __name((target, source2, target_key, source_key, prefix, remove_source) => {
      const source_prop = symbol(prefix, source_key);
      if (!hasOwnProperty2(source2, source_prop)) {
        return;
      }
      const target_prop = target_key === source_key ? source_prop : symbol(prefix, target_key);
      define2(target, target_prop, source2[source_prop]);
      if (remove_source) {
        delete source2[source_prop];
      }
    }, "copy_comments_by_kind");
    var copy_comments = /* @__PURE__ */ __name((target, source2, target_key, source_key, remove_source) => {
      SYMBOL_PREFIXES.forEach((prefix) => {
        copy_comments_by_kind(
          target,
          source2,
          target_key,
          source_key,
          prefix,
          remove_source
        );
      });
    }, "copy_comments");
    var swap_comments = /* @__PURE__ */ __name((array, from, to) => {
      if (from === to) {
        return;
      }
      SYMBOL_PREFIXES.forEach((prefix) => {
        const target_prop = symbol(prefix, to);
        if (!hasOwnProperty2(array, target_prop)) {
          copy_comments_by_kind(array, array, to, from, prefix, true);
          return;
        }
        const comments = array[target_prop];
        delete array[target_prop];
        copy_comments_by_kind(array, array, to, from, prefix, true);
        define2(array, symbol(prefix, from), comments);
      });
    }, "swap_comments");
    var assign_non_prop_comments = /* @__PURE__ */ __name((target, source2) => {
      NON_PROP_SYMBOL_KEYS.forEach((key) => {
        const comments = source2[key];
        if (comments) {
          define2(target, key, comments);
        }
      });
    }, "assign_non_prop_comments");
    var assign = /* @__PURE__ */ __name((target, source2, keys) => {
      keys.forEach((key) => {
        if (!isString2(key) && !isNumber3(key)) {
          return;
        }
        if (!hasOwnProperty2(source2, key)) {
          return;
        }
        target[key] = source2[key];
        copy_comments(target, source2, key, key);
      });
      return target;
    }, "assign");
    module2.exports = {
      SYMBOL_PREFIXES,
      PREFIX_BEFORE,
      PREFIX_AFTER_PROP,
      PREFIX_AFTER_COLON,
      PREFIX_AFTER_VALUE,
      PREFIX_AFTER,
      PREFIX_BEFORE_ALL,
      PREFIX_AFTER_ALL,
      BRACKET_OPEN,
      BRACKET_CLOSE,
      CURLY_BRACKET_OPEN,
      CURLY_BRACKET_CLOSE,
      COLON,
      COMMA,
      MINUS,
      EMPTY: EMPTY2,
      UNDEFINED,
      symbol,
      define: define2,
      copy_comments,
      swap_comments,
      assign_non_prop_comments,
      assign(target, source2, keys) {
        if (!isObject3(target)) {
          throw new TypeError("Cannot convert undefined or null to object");
        }
        if (!isObject3(source2)) {
          return target;
        }
        if (keys === UNDEFINED) {
          keys = Object.keys(source2);
          assign_non_prop_comments(target, source2);
        } else if (!isArray2(keys)) {
          throw new TypeError("keys must be array or undefined");
        } else if (keys.length === 0) {
          assign_non_prop_comments(target, source2);
        }
        return assign(target, source2, keys);
      }
    };
  }
});

// node_modules/comment-json/src/array.js
var require_array = __commonJS({
  "node_modules/comment-json/src/array.js"(exports2, module2) {
    init_esbuild_shims();
    var { isArray: isArray2 } = require_util17();
    var { sort } = require_src37();
    var {
      SYMBOL_PREFIXES,
      UNDEFINED,
      symbol,
      copy_comments,
      swap_comments
    } = require_common5();
    var reverse_comments = /* @__PURE__ */ __name((array) => {
      const { length } = array;
      let i = 0;
      const max = length / 2;
      for (; i < max; i++) {
        swap_comments(array, i, length - i - 1);
      }
    }, "reverse_comments");
    var move_comment = /* @__PURE__ */ __name((target, source2, i, offset, remove2) => {
      copy_comments(target, source2, i + offset, i, remove2);
    }, "move_comment");
    var move_comments = /* @__PURE__ */ __name((target, source2, start, count, offset, remove2) => {
      if (offset > 0) {
        let i2 = count;
        while (i2-- > 0) {
          move_comment(target, source2, start + i2, offset, remove2);
        }
        return;
      }
      let i = 0;
      while (i < count) {
        const ii = i++;
        move_comment(target, source2, start + ii, offset, remove2);
      }
    }, "move_comments");
    var remove_comments = /* @__PURE__ */ __name((array, key) => {
      SYMBOL_PREFIXES.forEach((prefix) => {
        const prop = symbol(prefix, key);
        delete array[prop];
      });
    }, "remove_comments");
    var get_mapped = /* @__PURE__ */ __name((map2, key) => {
      let mapped = key;
      while (mapped in map2) {
        mapped = map2[mapped];
      }
      return mapped;
    }, "get_mapped");
    var CommentArray = class _CommentArray extends Array {
      static {
        __name(this, "CommentArray");
      }
      // - deleteCount + items.length
      // We should avoid `splice(begin, deleteCount, ...items)`,
      // because `splice(0, undefined)` is not equivalent to `splice(0)`,
      // as well as:
      // - slice
      splice(...args) {
        const { length } = this;
        const ret = super.splice(...args);
        let [begin, deleteCount, ...items] = args;
        if (begin < 0) {
          begin += length;
        }
        if (arguments.length === 1) {
          deleteCount = length - begin;
        } else {
          deleteCount = Math.min(length - begin, deleteCount);
        }
        const {
          length: item_length
        } = items;
        const offset = item_length - deleteCount;
        const start = begin + deleteCount;
        const count = length - start;
        move_comments(this, this, start, count, offset, true);
        return ret;
      }
      slice(...args) {
        const { length } = this;
        const array = super.slice(...args);
        if (!array.length) {
          return new _CommentArray();
        }
        let [begin, before] = args;
        if (before === UNDEFINED) {
          before = length;
        } else if (before < 0) {
          before += length;
        }
        if (begin < 0) {
          begin += length;
        } else if (begin === UNDEFINED) {
          begin = 0;
        }
        move_comments(array, this, begin, before - begin, -begin);
        return array;
      }
      unshift(...items) {
        const { length } = this;
        const ret = super.unshift(...items);
        const {
          length: items_length
        } = items;
        if (items_length > 0) {
          move_comments(this, this, 0, length, items_length, true);
        }
        return ret;
      }
      shift() {
        const ret = super.shift();
        const { length } = this;
        remove_comments(this, 0);
        move_comments(this, this, 1, length, -1, true);
        return ret;
      }
      reverse() {
        super.reverse();
        reverse_comments(this);
        return this;
      }
      pop() {
        const ret = super.pop();
        remove_comments(this, this.length);
        return ret;
      }
      concat(...items) {
        let { length } = this;
        const ret = super.concat(...items);
        if (!items.length) {
          return ret;
        }
        move_comments(ret, this, 0, this.length, 0);
        items.forEach((item) => {
          const prev = length;
          length += isArray2(item) ? item.length : 1;
          if (!(item instanceof _CommentArray)) {
            return;
          }
          move_comments(ret, item, 0, item.length, prev);
        });
        return ret;
      }
      sort(...args) {
        const result = sort(
          this,
          ...args.slice(0, 1)
        );
        const map2 = /* @__PURE__ */ Object.create(null);
        result.forEach((source_index, index) => {
          if (source_index === index) {
            return;
          }
          const real_source_index = get_mapped(map2, source_index);
          if (real_source_index === index) {
            return;
          }
          map2[index] = real_source_index;
          swap_comments(this, index, real_source_index);
        });
        return this;
      }
    };
    module2.exports = {
      CommentArray
    };
  }
});

// node_modules/comment-json/src/parse.js
var require_parse7 = __commonJS({
  "node_modules/comment-json/src/parse.js"(exports2, module2) {
    init_esbuild_shims();
    var esprima = require_esprima();
    var {
      CommentArray
    } = require_array();
    var {
      PREFIX_BEFORE,
      PREFIX_AFTER_PROP,
      PREFIX_AFTER_COLON,
      PREFIX_AFTER_VALUE,
      PREFIX_AFTER,
      PREFIX_BEFORE_ALL,
      PREFIX_AFTER_ALL,
      BRACKET_OPEN,
      BRACKET_CLOSE,
      CURLY_BRACKET_OPEN,
      CURLY_BRACKET_CLOSE,
      COLON,
      COMMA,
      MINUS,
      EMPTY: EMPTY2,
      UNDEFINED,
      define: define2,
      assign_non_prop_comments
    } = require_common5();
    var tokenize4 = /* @__PURE__ */ __name((code2) => esprima.tokenize(code2, {
      comment: true,
      loc: true
    }), "tokenize");
    var previous_hosts = [];
    var comments_host = null;
    var unassigned_comments = null;
    var previous_props = [];
    var last_prop;
    var remove_comments = false;
    var inline2 = false;
    var tokens = null;
    var last2 = null;
    var current = null;
    var index;
    var reviver = null;
    var clean = /* @__PURE__ */ __name(() => {
      previous_props.length = previous_hosts.length = 0;
      last2 = null;
      last_prop = UNDEFINED;
    }, "clean");
    var free = /* @__PURE__ */ __name(() => {
      clean();
      tokens.length = 0;
      unassigned_comments = comments_host = tokens = last2 = current = reviver = null;
    }, "free");
    var symbolFor = /* @__PURE__ */ __name((prefix) => Symbol.for(
      last_prop !== UNDEFINED ? prefix + COLON + last_prop : prefix
    ), "symbolFor");
    var transform = /* @__PURE__ */ __name((k, v) => reviver ? reviver(k, v) : v, "transform");
    var unexpected = /* @__PURE__ */ __name(() => {
      const error = new SyntaxError(`Unexpected token ${current.value.slice(0, 1)}`);
      Object.assign(error, current.loc.start);
      throw error;
    }, "unexpected");
    var unexpected_end = /* @__PURE__ */ __name(() => {
      const error = new SyntaxError("Unexpected end of JSON input");
      Object.assign(error, last2 ? last2.loc.end : {
        line: 1,
        column: 0
      });
      throw error;
    }, "unexpected_end");
    var next = /* @__PURE__ */ __name(() => {
      const new_token = tokens[++index];
      inline2 = current && new_token && current.loc.end.line === new_token.loc.start.line || false;
      last2 = current;
      current = new_token;
    }, "next");
    var type = /* @__PURE__ */ __name(() => {
      if (!current) {
        unexpected_end();
      }
      return current.type === "Punctuator" ? current.value : current.type;
    }, "type");
    var is = /* @__PURE__ */ __name((t2) => type() === t2, "is");
    var expect = /* @__PURE__ */ __name((a) => {
      if (!is(a)) {
        unexpected();
      }
    }, "expect");
    var set_comments_host = /* @__PURE__ */ __name((new_host) => {
      previous_hosts.push(comments_host);
      comments_host = new_host;
    }, "set_comments_host");
    var restore_comments_host = /* @__PURE__ */ __name(() => {
      comments_host = previous_hosts.pop();
    }, "restore_comments_host");
    var assign_after_comments = /* @__PURE__ */ __name(() => {
      if (!unassigned_comments) {
        return;
      }
      const after_comments = [];
      for (const comment of unassigned_comments) {
        if (comment.inline) {
          after_comments.push(comment);
        } else {
          break;
        }
      }
      const { length } = after_comments;
      if (!length) {
        return;
      }
      if (length === unassigned_comments.length) {
        unassigned_comments = null;
      } else {
        unassigned_comments.splice(0, length);
      }
      define2(comments_host, symbolFor(PREFIX_AFTER), after_comments);
    }, "assign_after_comments");
    var assign_comments = /* @__PURE__ */ __name((prefix) => {
      if (!unassigned_comments) {
        return;
      }
      define2(comments_host, symbolFor(prefix), unassigned_comments);
      unassigned_comments = null;
    }, "assign_comments");
    var parse_comments = /* @__PURE__ */ __name((prefix) => {
      const comments = [];
      while (current && (is("LineComment") || is("BlockComment"))) {
        const comment = {
          ...current,
          inline: inline2
        };
        comments.push(comment);
        next();
      }
      if (remove_comments) {
        return;
      }
      if (!comments.length) {
        return;
      }
      if (prefix) {
        define2(comments_host, symbolFor(prefix), comments);
        return;
      }
      unassigned_comments = comments;
    }, "parse_comments");
    var set_prop = /* @__PURE__ */ __name((prop, push2) => {
      if (push2) {
        previous_props.push(last_prop);
      }
      last_prop = prop;
    }, "set_prop");
    var restore_prop = /* @__PURE__ */ __name(() => {
      last_prop = previous_props.pop();
    }, "restore_prop");
    var parse_object = /* @__PURE__ */ __name(() => {
      const obj = {};
      set_comments_host(obj);
      set_prop(UNDEFINED, true);
      let started = false;
      let name3;
      parse_comments();
      while (!is(CURLY_BRACKET_CLOSE)) {
        if (started) {
          assign_comments(PREFIX_AFTER_VALUE);
          expect(COMMA);
          next();
          parse_comments();
          assign_after_comments();
          if (is(CURLY_BRACKET_CLOSE)) {
            break;
          }
        }
        started = true;
        expect("String");
        name3 = JSON.parse(current.value);
        set_prop(name3);
        assign_comments(PREFIX_BEFORE);
        next();
        parse_comments(PREFIX_AFTER_PROP);
        expect(COLON);
        next();
        parse_comments(PREFIX_AFTER_COLON);
        obj[name3] = transform(name3, walk());
        parse_comments();
      }
      if (started) {
        assign_comments(PREFIX_AFTER);
      }
      next();
      last_prop = void 0;
      if (!started) {
        assign_comments(PREFIX_BEFORE);
      }
      restore_comments_host();
      restore_prop();
      return obj;
    }, "parse_object");
    var parse_array = /* @__PURE__ */ __name(() => {
      const array = new CommentArray();
      set_comments_host(array);
      set_prop(UNDEFINED, true);
      let started = false;
      let i = 0;
      parse_comments();
      while (!is(BRACKET_CLOSE)) {
        if (started) {
          assign_comments(PREFIX_AFTER_VALUE);
          expect(COMMA);
          next();
          parse_comments();
          assign_after_comments();
          if (is(BRACKET_CLOSE)) {
            break;
          }
        }
        started = true;
        set_prop(i);
        assign_comments(PREFIX_BEFORE);
        array[i] = transform(i, walk());
        i++;
        parse_comments();
      }
      if (started) {
        assign_comments(PREFIX_AFTER);
      }
      next();
      last_prop = void 0;
      if (!started) {
        assign_comments(PREFIX_BEFORE);
      }
      restore_comments_host();
      restore_prop();
      return array;
    }, "parse_array");
    function walk() {
      let tt = type();
      if (tt === CURLY_BRACKET_OPEN) {
        next();
        return parse_object();
      }
      if (tt === BRACKET_OPEN) {
        next();
        return parse_array();
      }
      let negative = EMPTY2;
      if (tt === MINUS) {
        next();
        tt = type();
        negative = MINUS;
      }
      let v;
      switch (tt) {
        case "String":
        case "Boolean":
        case "Null":
        case "Numeric":
          v = current.value;
          next();
          return JSON.parse(negative + v);
        default:
      }
    }
    __name(walk, "walk");
    var isObject3 = /* @__PURE__ */ __name((subject) => Object(subject) === subject, "isObject");
    var parse12 = /* @__PURE__ */ __name((code2, rev, no_comments) => {
      clean();
      tokens = tokenize4(code2);
      reviver = rev;
      remove_comments = no_comments;
      if (!tokens.length) {
        unexpected_end();
      }
      index = -1;
      next();
      set_comments_host({});
      parse_comments(PREFIX_BEFORE_ALL);
      let result = walk();
      parse_comments(PREFIX_AFTER_ALL);
      if (current) {
        unexpected();
      }
      if (!no_comments && result !== null) {
        if (!isObject3(result)) {
          result = new Object(result);
        }
        assign_non_prop_comments(result, comments_host);
      }
      restore_comments_host();
      result = transform("", result);
      free();
      return result;
    }, "parse");
    module2.exports = {
      parse: parse12,
      tokenize: tokenize4
    };
  }
});

// node_modules/repeat-string/index.js
var require_repeat_string = __commonJS({
  "node_modules/repeat-string/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var res = "";
    var cache5;
    module2.exports = repeat;
    function repeat(str2, num) {
      if (typeof str2 !== "string") {
        throw new TypeError("expected a string");
      }
      if (num === 1) return str2;
      if (num === 2) return str2 + str2;
      var max = str2.length * num;
      if (cache5 !== str2 || typeof cache5 === "undefined") {
        cache5 = str2;
        res = "";
      } else if (res.length >= max) {
        return res.substr(0, max);
      }
      while (max > res.length && num > 1) {
        if (num & 1) {
          res += str2;
        }
        num >>= 1;
        str2 += str2;
      }
      res += str2;
      res = res.substr(0, max);
      return res;
    }
    __name(repeat, "repeat");
  }
});

// node_modules/comment-json/src/stringify.js
var require_stringify2 = __commonJS({
  "node_modules/comment-json/src/stringify.js"(exports2, module2) {
    init_esbuild_shims();
    var {
      isArray: isArray2,
      isObject: isObject3,
      isFunction: isFunction3,
      isNumber: isNumber3,
      isString: isString2
    } = require_util17();
    var repeat = require_repeat_string();
    var {
      PREFIX_BEFORE_ALL,
      PREFIX_BEFORE,
      PREFIX_AFTER_PROP,
      PREFIX_AFTER_COLON,
      PREFIX_AFTER_VALUE,
      PREFIX_AFTER,
      PREFIX_AFTER_ALL,
      BRACKET_OPEN,
      BRACKET_CLOSE,
      CURLY_BRACKET_OPEN,
      CURLY_BRACKET_CLOSE,
      COLON,
      COMMA,
      EMPTY: EMPTY2,
      UNDEFINED
    } = require_common5();
    var ESCAPABLE = /[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
    var SPACE = " ";
    var LF = "\n";
    var STR_NULL = "null";
    var BEFORE = /* @__PURE__ */ __name((prop) => `${PREFIX_BEFORE}:${prop}`, "BEFORE");
    var AFTER_PROP = /* @__PURE__ */ __name((prop) => `${PREFIX_AFTER_PROP}:${prop}`, "AFTER_PROP");
    var AFTER_COLON = /* @__PURE__ */ __name((prop) => `${PREFIX_AFTER_COLON}:${prop}`, "AFTER_COLON");
    var AFTER_VALUE = /* @__PURE__ */ __name((prop) => `${PREFIX_AFTER_VALUE}:${prop}`, "AFTER_VALUE");
    var AFTER = /* @__PURE__ */ __name((prop) => `${PREFIX_AFTER}:${prop}`, "AFTER");
    var meta = {
      "\b": "\\b",
      "	": "\\t",
      "\n": "\\n",
      "\f": "\\f",
      "\r": "\\r",
      '"': '\\"',
      "\\": "\\\\"
    };
    var escape7 = /* @__PURE__ */ __name((string) => {
      ESCAPABLE.lastIndex = 0;
      if (!ESCAPABLE.test(string)) {
        return string;
      }
      return string.replace(ESCAPABLE, (a) => {
        const c3 = meta[a];
        return typeof c3 === "string" ? c3 : a;
      });
    }, "escape");
    var quote3 = /* @__PURE__ */ __name((string) => `"${escape7(string)}"`, "quote");
    var comment_stringify = /* @__PURE__ */ __name((value, line) => line ? `//${value}` : `/*${value}*/`, "comment_stringify");
    var process_comments = /* @__PURE__ */ __name((host, symbol_tag, deeper_gap, display_block) => {
      const comments = host[Symbol.for(symbol_tag)];
      if (!comments || !comments.length) {
        return EMPTY2;
      }
      let is_line_comment = false;
      const str2 = comments.reduce((prev, {
        inline: inline2,
        type,
        value
      }) => {
        const delimiter2 = inline2 ? SPACE : LF + deeper_gap;
        is_line_comment = type === "LineComment";
        return prev + delimiter2 + comment_stringify(value, is_line_comment);
      }, EMPTY2);
      return display_block || is_line_comment ? str2 + LF + deeper_gap : str2;
    }, "process_comments");
    var replacer = null;
    var indent = EMPTY2;
    var clean = /* @__PURE__ */ __name(() => {
      replacer = null;
      indent = EMPTY2;
    }, "clean");
    var join35 = /* @__PURE__ */ __name((one, two, gap) => one ? two ? one + two.trim() + LF + gap : one.trimRight() + LF + gap : two ? two.trimRight() + LF + gap : EMPTY2, "join");
    var join_content = /* @__PURE__ */ __name((inside, value, gap) => {
      const comment = process_comments(value, PREFIX_BEFORE, gap + indent, true);
      return join35(comment, inside, gap);
    }, "join_content");
    var array_stringify = /* @__PURE__ */ __name((value, gap) => {
      const deeper_gap = gap + indent;
      const { length } = value;
      let inside = EMPTY2;
      let after_comma = EMPTY2;
      for (let i = 0; i < length; i++) {
        if (i !== 0) {
          inside += COMMA;
        }
        const before = join35(
          after_comma,
          process_comments(value, BEFORE(i), deeper_gap),
          deeper_gap
        );
        inside += before || LF + deeper_gap;
        inside += stringify5(i, value, deeper_gap) || STR_NULL;
        inside += process_comments(value, AFTER_VALUE(i), deeper_gap);
        after_comma = process_comments(value, AFTER(i), deeper_gap);
      }
      inside += join35(
        after_comma,
        process_comments(value, PREFIX_AFTER, deeper_gap),
        deeper_gap
      );
      return BRACKET_OPEN + join_content(inside, value, gap) + BRACKET_CLOSE;
    }, "array_stringify");
    var object_stringify = /* @__PURE__ */ __name((value, gap) => {
      if (!value) {
        return "null";
      }
      const deeper_gap = gap + indent;
      let inside = EMPTY2;
      let after_comma = EMPTY2;
      let first2 = true;
      const keys = isArray2(replacer) ? replacer : Object.keys(value);
      const iteratee = /* @__PURE__ */ __name((key) => {
        const sv = stringify5(key, value, deeper_gap);
        if (sv === UNDEFINED) {
          return;
        }
        if (!first2) {
          inside += COMMA;
        }
        first2 = false;
        const before = join35(
          after_comma,
          process_comments(value, BEFORE(key), deeper_gap),
          deeper_gap
        );
        inside += before || LF + deeper_gap;
        inside += quote3(key) + process_comments(value, AFTER_PROP(key), deeper_gap) + COLON + process_comments(value, AFTER_COLON(key), deeper_gap) + SPACE + sv + process_comments(value, AFTER_VALUE(key), deeper_gap);
        after_comma = process_comments(value, AFTER(key), deeper_gap);
      }, "iteratee");
      keys.forEach(iteratee);
      inside += join35(
        after_comma,
        process_comments(value, PREFIX_AFTER, deeper_gap),
        deeper_gap
      );
      return CURLY_BRACKET_OPEN + join_content(inside, value, gap) + CURLY_BRACKET_CLOSE;
    }, "object_stringify");
    function stringify5(key, holder, gap) {
      let value = holder[key];
      if (isObject3(value) && isFunction3(value.toJSON)) {
        value = value.toJSON(key);
      }
      if (isFunction3(replacer)) {
        value = replacer.call(holder, key, value);
      }
      switch (typeof value) {
        case "string":
          return quote3(value);
        case "number":
          return Number.isFinite(value) ? String(value) : STR_NULL;
        case "boolean":
        case "null":
          return String(value);
        // If the type is 'object', we might be dealing with an object or an array or
        // null.
        case "object":
          return isArray2(value) ? array_stringify(value, gap) : object_stringify(value, gap);
        // undefined
        default:
      }
    }
    __name(stringify5, "stringify");
    var get_indent = /* @__PURE__ */ __name((space) => isString2(space) ? space : isNumber3(space) ? repeat(SPACE, space) : EMPTY2, "get_indent");
    var { toString } = Object.prototype;
    var PRIMITIVE_OBJECT_TYPES = [
      "[object Number]",
      "[object String]",
      "[object Boolean]"
    ];
    var is_primitive_object = /* @__PURE__ */ __name((subject) => {
      if (typeof subject !== "object") {
        return false;
      }
      const str2 = toString.call(subject);
      return PRIMITIVE_OBJECT_TYPES.includes(str2);
    }, "is_primitive_object");
    module2.exports = (value, replacer_, space) => {
      const indent_ = get_indent(space);
      if (!indent_) {
        return JSON.stringify(value, replacer_);
      }
      if (!isFunction3(replacer_) && !isArray2(replacer_)) {
        replacer_ = null;
      }
      replacer = replacer_;
      indent = indent_;
      const str2 = is_primitive_object(value) ? JSON.stringify(value) : stringify5("", { "": value }, EMPTY2);
      clean();
      return isObject3(value) ? process_comments(value, PREFIX_BEFORE_ALL, EMPTY2).trimLeft() + str2 + process_comments(value, PREFIX_AFTER_ALL, EMPTY2).trimRight() : str2;
    };
  }
});

// node_modules/comment-json/src/index.js
var require_src38 = __commonJS({
  "node_modules/comment-json/src/index.js"(exports2, module2) {
    init_esbuild_shims();
    var { parse: parse12, tokenize: tokenize4 } = require_parse7();
    var stringify5 = require_stringify2();
    var { CommentArray } = require_array();
    var { assign } = require_common5();
    module2.exports = {
      parse: parse12,
      stringify: stringify5,
      tokenize: tokenize4,
      CommentArray,
      assign
    };
  }
});

// node_modules/wrappy/wrappy.js
var require_wrappy = __commonJS({
  "node_modules/wrappy/wrappy.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = wrappy;
    function wrappy(fn, cb) {
      if (fn && cb) return wrappy(fn)(cb);
      if (typeof fn !== "function")
        throw new TypeError("need wrapper function");
      Object.keys(fn).forEach(function(k) {
        wrapper[k] = fn[k];
      });
      return wrapper;
      function wrapper() {
        var args = new Array(arguments.length);
        for (var i = 0; i < args.length; i++) {
          args[i] = arguments[i];
        }
        var ret = fn.apply(this, args);
        var cb2 = args[args.length - 1];
        if (typeof ret === "function" && ret !== cb2) {
          Object.keys(cb2).forEach(function(k) {
            ret[k] = cb2[k];
          });
        }
        return ret;
      }
      __name(wrapper, "wrapper");
    }
    __name(wrappy, "wrappy");
  }
});

// node_modules/once/once.js
var require_once = __commonJS({
  "node_modules/once/once.js"(exports2, module2) {
    init_esbuild_shims();
    var wrappy = require_wrappy();
    module2.exports = wrappy(once);
    module2.exports.strict = wrappy(onceStrict);
    once.proto = once(function() {
      Object.defineProperty(Function.prototype, "once", {
        value: /* @__PURE__ */ __name(function() {
          return once(this);
        }, "value"),
        configurable: true
      });
      Object.defineProperty(Function.prototype, "onceStrict", {
        value: /* @__PURE__ */ __name(function() {
          return onceStrict(this);
        }, "value"),
        configurable: true
      });
    });
    function once(fn) {
      var f = /* @__PURE__ */ __name(function() {
        if (f.called) return f.value;
        f.called = true;
        return f.value = fn.apply(this, arguments);
      }, "f");
      f.called = false;
      return f;
    }
    __name(once, "once");
    function onceStrict(fn) {
      var f = /* @__PURE__ */ __name(function() {
        if (f.called)
          throw new Error(f.onceError);
        f.called = true;
        return f.value = fn.apply(this, arguments);
      }, "f");
      var name3 = fn.name || "Function wrapped with `once`";
      f.onceError = name3 + " shouldn't be called more than once";
      f.called = false;
      return f;
    }
    __name(onceStrict, "onceStrict");
  }
});

// node_modules/end-of-stream/index.js
var require_end_of_stream = __commonJS({
  "node_modules/end-of-stream/index.js"(exports2, module2) {
    init_esbuild_shims();
    var once = require_once();
    var noop6 = /* @__PURE__ */ __name(function() {
    }, "noop");
    var qnt = globalThis.Bare ? queueMicrotask : process.nextTick.bind(process);
    var isRequest = /* @__PURE__ */ __name(function(stream2) {
      return stream2.setHeader && typeof stream2.abort === "function";
    }, "isRequest");
    var isChildProcess = /* @__PURE__ */ __name(function(stream2) {
      return stream2.stdio && Array.isArray(stream2.stdio) && stream2.stdio.length === 3;
    }, "isChildProcess");
    var eos = /* @__PURE__ */ __name(function(stream2, opts, callback) {
      if (typeof opts === "function") return eos(stream2, null, opts);
      if (!opts) opts = {};
      callback = once(callback || noop6);
      var ws2 = stream2._writableState;
      var rs = stream2._readableState;
      var readable = opts.readable || opts.readable !== false && stream2.readable;
      var writable = opts.writable || opts.writable !== false && stream2.writable;
      var cancelled = false;
      var onlegacyfinish = /* @__PURE__ */ __name(function() {
        if (!stream2.writable) onfinish();
      }, "onlegacyfinish");
      var onfinish = /* @__PURE__ */ __name(function() {
        writable = false;
        if (!readable) callback.call(stream2);
      }, "onfinish");
      var onend = /* @__PURE__ */ __name(function() {
        readable = false;
        if (!writable) callback.call(stream2);
      }, "onend");
      var onexit = /* @__PURE__ */ __name(function(exitCode) {
        callback.call(stream2, exitCode ? new Error("exited with error code: " + exitCode) : null);
      }, "onexit");
      var onerror = /* @__PURE__ */ __name(function(err) {
        callback.call(stream2, err);
      }, "onerror");
      var onclose = /* @__PURE__ */ __name(function() {
        qnt(onclosenexttick);
      }, "onclose");
      var onclosenexttick = /* @__PURE__ */ __name(function() {
        if (cancelled) return;
        if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream2, new Error("premature close"));
        if (writable && !(ws2 && (ws2.ended && !ws2.destroyed))) return callback.call(stream2, new Error("premature close"));
      }, "onclosenexttick");
      var onrequest = /* @__PURE__ */ __name(function() {
        stream2.req.on("finish", onfinish);
      }, "onrequest");
      if (isRequest(stream2)) {
        stream2.on("complete", onfinish);
        stream2.on("abort", onclose);
        if (stream2.req) onrequest();
        else stream2.on("request", onrequest);
      } else if (writable && !ws2) {
        stream2.on("end", onlegacyfinish);
        stream2.on("close", onlegacyfinish);
      }
      if (isChildProcess(stream2)) stream2.on("exit", onexit);
      stream2.on("end", onend);
      stream2.on("finish", onfinish);
      if (opts.error !== false) stream2.on("error", onerror);
      stream2.on("close", onclose);
      return function() {
        cancelled = true;
        stream2.removeListener("complete", onfinish);
        stream2.removeListener("abort", onclose);
        stream2.removeListener("request", onrequest);
        if (stream2.req) stream2.req.removeListener("finish", onfinish);
        stream2.removeListener("end", onlegacyfinish);
        stream2.removeListener("close", onlegacyfinish);
        stream2.removeListener("finish", onfinish);
        stream2.removeListener("exit", onexit);
        stream2.removeListener("end", onend);
        stream2.removeListener("error", onerror);
        stream2.removeListener("close", onclose);
      };
    }, "eos");
    module2.exports = eos;
  }
});

// node_modules/pump/index.js
var require_pump = __commonJS({
  "node_modules/pump/index.js"(exports2, module2) {
    init_esbuild_shims();
    var once = require_once();
    var eos = require_end_of_stream();
    var fs95;
    try {
      fs95 = __require("fs");
    } catch (e2) {
    }
    var noop6 = /* @__PURE__ */ __name(function() {
    }, "noop");
    var ancient = typeof process === "undefined" ? false : /^v?\.0/.test(process.version);
    var isFn = /* @__PURE__ */ __name(function(fn) {
      return typeof fn === "function";
    }, "isFn");
    var isFS = /* @__PURE__ */ __name(function(stream2) {
      if (!ancient) return false;
      if (!fs95) return false;
      return (stream2 instanceof (fs95.ReadStream || noop6) || stream2 instanceof (fs95.WriteStream || noop6)) && isFn(stream2.close);
    }, "isFS");
    var isRequest = /* @__PURE__ */ __name(function(stream2) {
      return stream2.setHeader && isFn(stream2.abort);
    }, "isRequest");
    var destroyer = /* @__PURE__ */ __name(function(stream2, reading, writing, callback) {
      callback = once(callback);
      var closed = false;
      stream2.on("close", function() {
        closed = true;
      });
      eos(stream2, { readable: reading, writable: writing }, function(err) {
        if (err) return callback(err);
        closed = true;
        callback();
      });
      var destroyed = false;
      return function(err) {
        if (closed) return;
        if (destroyed) return;
        destroyed = true;
        if (isFS(stream2)) return stream2.close(noop6);
        if (isRequest(stream2)) return stream2.abort();
        if (isFn(stream2.destroy)) return stream2.destroy();
        callback(err || new Error("stream was destroyed"));
      };
    }, "destroyer");
    var call = /* @__PURE__ */ __name(function(fn) {
      fn();
    }, "call");
    var pipe = /* @__PURE__ */ __name(function(from, to) {
      return from.pipe(to);
    }, "pipe");
    var pump = /* @__PURE__ */ __name(function() {
      var streams = Array.prototype.slice.call(arguments);
      var callback = isFn(streams[streams.length - 1] || noop6) && streams.pop() || noop6;
      if (Array.isArray(streams[0])) streams = streams[0];
      if (streams.length < 2) throw new Error("pump requires two streams per minimum");
      var error;
      var destroys = streams.map(function(stream2, i) {
        var reading = i < streams.length - 1;
        var writing = i > 0;
        return destroyer(stream2, reading, writing, function(err) {
          if (!error) error = err;
          if (err) destroys.forEach(call);
          if (reading) return;
          destroys.forEach(call);
          callback(error);
        });
      });
      return streams.reduce(pipe);
    }, "pump");
    module2.exports = pump;
  }
});

// node_modules/extract-zip/node_modules/get-stream/buffer-stream.js
var require_buffer_stream = __commonJS({
  "node_modules/extract-zip/node_modules/get-stream/buffer-stream.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { PassThrough: PassThroughStream } = __require("stream");
    module2.exports = (options2) => {
      options2 = { ...options2 };
      const { array } = options2;
      let { encoding } = options2;
      const isBuffer = encoding === "buffer";
      let objectMode = false;
      if (array) {
        objectMode = !(encoding || isBuffer);
      } else {
        encoding = encoding || "utf8";
      }
      if (isBuffer) {
        encoding = null;
      }
      const stream2 = new PassThroughStream({ objectMode });
      if (encoding) {
        stream2.setEncoding(encoding);
      }
      let length = 0;
      const chunks = [];
      stream2.on("data", (chunk) => {
        chunks.push(chunk);
        if (objectMode) {
          length = chunks.length;
        } else {
          length += chunk.length;
        }
      });
      stream2.getBufferedValue = () => {
        if (array) {
          return chunks;
        }
        return isBuffer ? Buffer.concat(chunks, length) : chunks.join("");
      };
      stream2.getBufferedLength = () => length;
      return stream2;
    };
  }
});

// node_modules/extract-zip/node_modules/get-stream/index.js
var require_get_stream = __commonJS({
  "node_modules/extract-zip/node_modules/get-stream/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { constants: BufferConstants } = __require("buffer");
    var pump = require_pump();
    var bufferStream = require_buffer_stream();
    var MaxBufferError = class extends Error {
      static {
        __name(this, "MaxBufferError");
      }
      constructor() {
        super("maxBuffer exceeded");
        this.name = "MaxBufferError";
      }
    };
    async function getStream(inputStream, options2) {
      if (!inputStream) {
        return Promise.reject(new Error("Expected a stream"));
      }
      options2 = {
        maxBuffer: Infinity,
        ...options2
      };
      const { maxBuffer } = options2;
      let stream2;
      await new Promise((resolve24, reject) => {
        const rejectPromise = /* @__PURE__ */ __name((error) => {
          if (error && stream2.getBufferedLength() <= BufferConstants.MAX_LENGTH) {
            error.bufferedData = stream2.getBufferedValue();
          }
          reject(error);
        }, "rejectPromise");
        stream2 = pump(inputStream, bufferStream(options2), (error) => {
          if (error) {
            rejectPromise(error);
            return;
          }
          resolve24();
        });
        stream2.on("data", () => {
          if (stream2.getBufferedLength() > maxBuffer) {
            rejectPromise(new MaxBufferError());
          }
        });
      });
      return stream2.getBufferedValue();
    }
    __name(getStream, "getStream");
    module2.exports = getStream;
    module2.exports.default = getStream;
    module2.exports.buffer = (stream2, options2) => getStream(stream2, { ...options2, encoding: "buffer" });
    module2.exports.array = (stream2, options2) => getStream(stream2, { ...options2, array: true });
    module2.exports.MaxBufferError = MaxBufferError;
  }
});

// node_modules/pend/index.js
var require_pend = __commonJS({
  "node_modules/pend/index.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = Pend;
    function Pend() {
      this.pending = 0;
      this.max = Infinity;
      this.listeners = [];
      this.waiting = [];
      this.error = null;
    }
    __name(Pend, "Pend");
    Pend.prototype.go = function(fn) {
      if (this.pending < this.max) {
        pendGo(this, fn);
      } else {
        this.waiting.push(fn);
      }
    };
    Pend.prototype.wait = function(cb) {
      if (this.pending === 0) {
        cb(this.error);
      } else {
        this.listeners.push(cb);
      }
    };
    Pend.prototype.hold = function() {
      return pendHold(this);
    };
    function pendHold(self2) {
      self2.pending += 1;
      var called = false;
      return onCb;
      function onCb(err) {
        if (called) throw new Error("callback called twice");
        called = true;
        self2.error = self2.error || err;
        self2.pending -= 1;
        if (self2.waiting.length > 0 && self2.pending < self2.max) {
          pendGo(self2, self2.waiting.shift());
        } else if (self2.pending === 0) {
          var listeners = self2.listeners;
          self2.listeners = [];
          listeners.forEach(cbListener);
        }
      }
      __name(onCb, "onCb");
      function cbListener(listener) {
        listener(self2.error);
      }
      __name(cbListener, "cbListener");
    }
    __name(pendHold, "pendHold");
    function pendGo(self2, fn) {
      fn(pendHold(self2));
    }
    __name(pendGo, "pendGo");
  }
});

// node_modules/fd-slicer/index.js
var require_fd_slicer = __commonJS({
  "node_modules/fd-slicer/index.js"(exports2) {
    init_esbuild_shims();
    var fs95 = __require("fs");
    var util4 = __require("util");
    var stream2 = __require("stream");
    var Readable4 = stream2.Readable;
    var Writable3 = stream2.Writable;
    var PassThrough4 = stream2.PassThrough;
    var Pend = require_pend();
    var EventEmitter10 = __require("events").EventEmitter;
    exports2.createFromBuffer = createFromBuffer;
    exports2.createFromFd = createFromFd;
    exports2.BufferSlicer = BufferSlicer;
    exports2.FdSlicer = FdSlicer;
    util4.inherits(FdSlicer, EventEmitter10);
    function FdSlicer(fd, options2) {
      options2 = options2 || {};
      EventEmitter10.call(this);
      this.fd = fd;
      this.pend = new Pend();
      this.pend.max = 1;
      this.refCount = 0;
      this.autoClose = !!options2.autoClose;
    }
    __name(FdSlicer, "FdSlicer");
    FdSlicer.prototype.read = function(buffer, offset, length, position, callback) {
      var self2 = this;
      self2.pend.go(function(cb) {
        fs95.read(self2.fd, buffer, offset, length, position, function(err, bytesRead, buffer2) {
          cb();
          callback(err, bytesRead, buffer2);
        });
      });
    };
    FdSlicer.prototype.write = function(buffer, offset, length, position, callback) {
      var self2 = this;
      self2.pend.go(function(cb) {
        fs95.write(self2.fd, buffer, offset, length, position, function(err, written, buffer2) {
          cb();
          callback(err, written, buffer2);
        });
      });
    };
    FdSlicer.prototype.createReadStream = function(options2) {
      return new ReadStream2(this, options2);
    };
    FdSlicer.prototype.createWriteStream = function(options2) {
      return new WriteStream2(this, options2);
    };
    FdSlicer.prototype.ref = function() {
      this.refCount += 1;
    };
    FdSlicer.prototype.unref = function() {
      var self2 = this;
      self2.refCount -= 1;
      if (self2.refCount > 0) return;
      if (self2.refCount < 0) throw new Error("invalid unref");
      if (self2.autoClose) {
        fs95.close(self2.fd, onCloseDone);
      }
      function onCloseDone(err) {
        if (err) {
          self2.emit("error", err);
        } else {
          self2.emit("close");
        }
      }
      __name(onCloseDone, "onCloseDone");
    };
    util4.inherits(ReadStream2, Readable4);
    function ReadStream2(context2, options2) {
      options2 = options2 || {};
      Readable4.call(this, options2);
      this.context = context2;
      this.context.ref();
      this.start = options2.start || 0;
      this.endOffset = options2.end;
      this.pos = this.start;
      this.destroyed = false;
    }
    __name(ReadStream2, "ReadStream");
    ReadStream2.prototype._read = function(n2) {
      var self2 = this;
      if (self2.destroyed) return;
      var toRead = Math.min(self2._readableState.highWaterMark, n2);
      if (self2.endOffset != null) {
        toRead = Math.min(toRead, self2.endOffset - self2.pos);
      }
      if (toRead <= 0) {
        self2.destroyed = true;
        self2.push(null);
        self2.context.unref();
        return;
      }
      self2.context.pend.go(function(cb) {
        if (self2.destroyed) return cb();
        var buffer = new Buffer(toRead);
        fs95.read(self2.context.fd, buffer, 0, toRead, self2.pos, function(err, bytesRead) {
          if (err) {
            self2.destroy(err);
          } else if (bytesRead === 0) {
            self2.destroyed = true;
            self2.push(null);
            self2.context.unref();
          } else {
            self2.pos += bytesRead;
            self2.push(buffer.slice(0, bytesRead));
          }
          cb();
        });
      });
    };
    ReadStream2.prototype.destroy = function(err) {
      if (this.destroyed) return;
      err = err || new Error("stream destroyed");
      this.destroyed = true;
      this.emit("error", err);
      this.context.unref();
    };
    util4.inherits(WriteStream2, Writable3);
    function WriteStream2(context2, options2) {
      options2 = options2 || {};
      Writable3.call(this, options2);
      this.context = context2;
      this.context.ref();
      this.start = options2.start || 0;
      this.endOffset = options2.end == null ? Infinity : +options2.end;
      this.bytesWritten = 0;
      this.pos = this.start;
      this.destroyed = false;
      this.on("finish", this.destroy.bind(this));
    }
    __name(WriteStream2, "WriteStream");
    WriteStream2.prototype._write = function(buffer, encoding, callback) {
      var self2 = this;
      if (self2.destroyed) return;
      if (self2.pos + buffer.length > self2.endOffset) {
        var err = new Error("maximum file length exceeded");
        err.code = "ETOOBIG";
        self2.destroy();
        callback(err);
        return;
      }
      self2.context.pend.go(function(cb) {
        if (self2.destroyed) return cb();
        fs95.write(self2.context.fd, buffer, 0, buffer.length, self2.pos, function(err2, bytes) {
          if (err2) {
            self2.destroy();
            cb();
            callback(err2);
          } else {
            self2.bytesWritten += bytes;
            self2.pos += bytes;
            self2.emit("progress");
            cb();
            callback();
          }
        });
      });
    };
    WriteStream2.prototype.destroy = function() {
      if (this.destroyed) return;
      this.destroyed = true;
      this.context.unref();
    };
    util4.inherits(BufferSlicer, EventEmitter10);
    function BufferSlicer(buffer, options2) {
      EventEmitter10.call(this);
      options2 = options2 || {};
      this.refCount = 0;
      this.buffer = buffer;
      this.maxChunkSize = options2.maxChunkSize || Number.MAX_SAFE_INTEGER;
    }
    __name(BufferSlicer, "BufferSlicer");
    BufferSlicer.prototype.read = function(buffer, offset, length, position, callback) {
      var end = position + length;
      var delta = end - this.buffer.length;
      var written = delta > 0 ? delta : length;
      this.buffer.copy(buffer, offset, position, end);
      setImmediate(function() {
        callback(null, written);
      });
    };
    BufferSlicer.prototype.write = function(buffer, offset, length, position, callback) {
      buffer.copy(this.buffer, position, offset, offset + length);
      setImmediate(function() {
        callback(null, length, buffer);
      });
    };
    BufferSlicer.prototype.createReadStream = function(options2) {
      options2 = options2 || {};
      var readStream = new PassThrough4(options2);
      readStream.destroyed = false;
      readStream.start = options2.start || 0;
      readStream.endOffset = options2.end;
      readStream.pos = readStream.endOffset || this.buffer.length;
      var entireSlice = this.buffer.slice(readStream.start, readStream.pos);
      var offset = 0;
      while (true) {
        var nextOffset = offset + this.maxChunkSize;
        if (nextOffset >= entireSlice.length) {
          if (offset < entireSlice.length) {
            readStream.write(entireSlice.slice(offset, entireSlice.length));
          }
          break;
        }
        readStream.write(entireSlice.slice(offset, nextOffset));
        offset = nextOffset;
      }
      readStream.end();
      readStream.destroy = function() {
        readStream.destroyed = true;
      };
      return readStream;
    };
    BufferSlicer.prototype.createWriteStream = function(options2) {
      var bufferSlicer = this;
      options2 = options2 || {};
      var writeStream = new Writable3(options2);
      writeStream.start = options2.start || 0;
      writeStream.endOffset = options2.end == null ? this.buffer.length : +options2.end;
      writeStream.bytesWritten = 0;
      writeStream.pos = writeStream.start;
      writeStream.destroyed = false;
      writeStream._write = function(buffer, encoding, callback) {
        if (writeStream.destroyed) return;
        var end = writeStream.pos + buffer.length;
        if (end > writeStream.endOffset) {
          var err = new Error("maximum file length exceeded");
          err.code = "ETOOBIG";
          writeStream.destroyed = true;
          callback(err);
          return;
        }
        buffer.copy(bufferSlicer.buffer, writeStream.pos, 0, buffer.length);
        writeStream.bytesWritten += buffer.length;
        writeStream.pos = end;
        writeStream.emit("progress");
        callback();
      };
      writeStream.destroy = function() {
        writeStream.destroyed = true;
      };
      return writeStream;
    };
    BufferSlicer.prototype.ref = function() {
      this.refCount += 1;
    };
    BufferSlicer.prototype.unref = function() {
      this.refCount -= 1;
      if (this.refCount < 0) {
        throw new Error("invalid unref");
      }
    };
    function createFromBuffer(buffer, options2) {
      return new BufferSlicer(buffer, options2);
    }
    __name(createFromBuffer, "createFromBuffer");
    function createFromFd(fd, options2) {
      return new FdSlicer(fd, options2);
    }
    __name(createFromFd, "createFromFd");
  }
});

// node_modules/buffer-crc32/index.js
var require_buffer_crc32 = __commonJS({
  "node_modules/buffer-crc32/index.js"(exports2, module2) {
    init_esbuild_shims();
    var Buffer5 = __require("buffer").Buffer;
    var CRC_TABLE = [
      0,
      1996959894,
      3993919788,
      2567524794,
      124634137,
      1886057615,
      3915621685,
      2657392035,
      249268274,
      2044508324,
      3772115230,
      2547177864,
      162941995,
      2125561021,
      3887607047,
      2428444049,
      498536548,
      1789927666,
      4089016648,
      2227061214,
      450548861,
      1843258603,
      4107580753,
      2211677639,
      325883990,
      1684777152,
      4251122042,
      2321926636,
      335633487,
      1661365465,
      4195302755,
      2366115317,
      997073096,
      1281953886,
      3579855332,
      2724688242,
      1006888145,
      1258607687,
      3524101629,
      2768942443,
      901097722,
      1119000684,
      3686517206,
      2898065728,
      853044451,
      1172266101,
      3705015759,
      2882616665,
      651767980,
      1373503546,
      3369554304,
      3218104598,
      565507253,
      1454621731,
      3485111705,
      3099436303,
      671266974,
      1594198024,
      3322730930,
      2970347812,
      795835527,
      1483230225,
      3244367275,
      3060149565,
      1994146192,
      31158534,
      2563907772,
      4023717930,
      1907459465,
      112637215,
      2680153253,
      3904427059,
      2013776290,
      251722036,
      2517215374,
      3775830040,
      2137656763,
      141376813,
      2439277719,
      3865271297,
      1802195444,
      476864866,
      2238001368,
      4066508878,
      1812370925,
      453092731,
      2181625025,
      4111451223,
      1706088902,
      314042704,
      2344532202,
      4240017532,
      1658658271,
      366619977,
      2362670323,
      4224994405,
      1303535960,
      984961486,
      2747007092,
      3569037538,
      1256170817,
      1037604311,
      2765210733,
      3554079995,
      1131014506,
      879679996,
      2909243462,
      3663771856,
      1141124467,
      855842277,
      2852801631,
      3708648649,
      1342533948,
      654459306,
      3188396048,
      3373015174,
      1466479909,
      544179635,
      3110523913,
      3462522015,
      1591671054,
      702138776,
      2966460450,
      3352799412,
      1504918807,
      783551873,
      3082640443,
      3233442989,
      3988292384,
      2596254646,
      62317068,
      1957810842,
      3939845945,
      2647816111,
      81470997,
      1943803523,
      3814918930,
      2489596804,
      225274430,
      2053790376,
      3826175755,
      2466906013,
      167816743,
      2097651377,
      4027552580,
      2265490386,
      503444072,
      1762050814,
      4150417245,
      2154129355,
      426522225,
      1852507879,
      4275313526,
      2312317920,
      282753626,
      1742555852,
      4189708143,
      2394877945,
      397917763,
      1622183637,
      3604390888,
      2714866558,
      953729732,
      1340076626,
      3518719985,
      2797360999,
      1068828381,
      1219638859,
      3624741850,
      2936675148,
      906185462,
      1090812512,
      3747672003,
      2825379669,
      829329135,
      1181335161,
      3412177804,
      3160834842,
      628085408,
      1382605366,
      3423369109,
      3138078467,
      570562233,
      1426400815,
      3317316542,
      2998733608,
      733239954,
      1555261956,
      3268935591,
      3050360625,
      752459403,
      1541320221,
      2607071920,
      3965973030,
      1969922972,
      40735498,
      2617837225,
      3943577151,
      1913087877,
      83908371,
      2512341634,
      3803740692,
      2075208622,
      213261112,
      2463272603,
      3855990285,
      2094854071,
      198958881,
      2262029012,
      4057260610,
      1759359992,
      534414190,
      2176718541,
      4139329115,
      1873836001,
      414664567,
      2282248934,
      4279200368,
      1711684554,
      285281116,
      2405801727,
      4167216745,
      1634467795,
      376229701,
      2685067896,
      3608007406,
      1308918612,
      956543938,
      2808555105,
      3495958263,
      1231636301,
      1047427035,
      2932959818,
      3654703836,
      1088359270,
      936918e3,
      2847714899,
      3736837829,
      1202900863,
      817233897,
      3183342108,
      3401237130,
      1404277552,
      615818150,
      3134207493,
      3453421203,
      1423857449,
      601450431,
      3009837614,
      3294710456,
      1567103746,
      711928724,
      3020668471,
      3272380065,
      1510334235,
      755167117
    ];
    if (typeof Int32Array !== "undefined") {
      CRC_TABLE = new Int32Array(CRC_TABLE);
    }
    function ensureBuffer(input) {
      if (Buffer5.isBuffer(input)) {
        return input;
      }
      var hasNewBufferAPI = typeof Buffer5.alloc === "function" && typeof Buffer5.from === "function";
      if (typeof input === "number") {
        return hasNewBufferAPI ? Buffer5.alloc(input) : new Buffer5(input);
      } else if (typeof input === "string") {
        return hasNewBufferAPI ? Buffer5.from(input) : new Buffer5(input);
      } else {
        throw new Error("input must be buffer, number, or string, received " + typeof input);
      }
    }
    __name(ensureBuffer, "ensureBuffer");
    function bufferizeInt(num) {
      var tmp = ensureBuffer(4);
      tmp.writeInt32BE(num, 0);
      return tmp;
    }
    __name(bufferizeInt, "bufferizeInt");
    function _crc32(buf, previous) {
      buf = ensureBuffer(buf);
      if (Buffer5.isBuffer(previous)) {
        previous = previous.readUInt32BE(0);
      }
      var crc = ~~previous ^ -1;
      for (var n2 = 0; n2 < buf.length; n2++) {
        crc = CRC_TABLE[(crc ^ buf[n2]) & 255] ^ crc >>> 8;
      }
      return crc ^ -1;
    }
    __name(_crc32, "_crc32");
    function crc32() {
      return bufferizeInt(_crc32.apply(null, arguments));
    }
    __name(crc32, "crc32");
    crc32.signed = function() {
      return _crc32.apply(null, arguments);
    };
    crc32.unsigned = function() {
      return _crc32.apply(null, arguments) >>> 0;
    };
    module2.exports = crc32;
  }
});

// node_modules/yauzl/index.js
var require_yauzl = __commonJS({
  "node_modules/yauzl/index.js"(exports2) {
    init_esbuild_shims();
    var fs95 = __require("fs");
    var zlib2 = __require("zlib");
    var fd_slicer = require_fd_slicer();
    var crc32 = require_buffer_crc32();
    var util4 = __require("util");
    var EventEmitter10 = __require("events").EventEmitter;
    var Transform2 = __require("stream").Transform;
    var PassThrough4 = __require("stream").PassThrough;
    var Writable3 = __require("stream").Writable;
    exports2.open = open3;
    exports2.fromFd = fromFd;
    exports2.fromBuffer = fromBuffer;
    exports2.fromRandomAccessReader = fromRandomAccessReader;
    exports2.dosDateTimeToDate = dosDateTimeToDate;
    exports2.validateFileName = validateFileName;
    exports2.ZipFile = ZipFile;
    exports2.Entry = Entry;
    exports2.RandomAccessReader = RandomAccessReader;
    function open3(path108, options2, callback) {
      if (typeof options2 === "function") {
        callback = options2;
        options2 = null;
      }
      if (options2 == null) options2 = {};
      if (options2.autoClose == null) options2.autoClose = true;
      if (options2.lazyEntries == null) options2.lazyEntries = false;
      if (options2.decodeStrings == null) options2.decodeStrings = true;
      if (options2.validateEntrySizes == null) options2.validateEntrySizes = true;
      if (options2.strictFileNames == null) options2.strictFileNames = false;
      if (callback == null) callback = defaultCallback;
      fs95.open(path108, "r", function(err, fd) {
        if (err) return callback(err);
        fromFd(fd, options2, function(err2, zipfile) {
          if (err2) fs95.close(fd, defaultCallback);
          callback(err2, zipfile);
        });
      });
    }
    __name(open3, "open");
    function fromFd(fd, options2, callback) {
      if (typeof options2 === "function") {
        callback = options2;
        options2 = null;
      }
      if (options2 == null) options2 = {};
      if (options2.autoClose == null) options2.autoClose = false;
      if (options2.lazyEntries == null) options2.lazyEntries = false;
      if (options2.decodeStrings == null) options2.decodeStrings = true;
      if (options2.validateEntrySizes == null) options2.validateEntrySizes = true;
      if (options2.strictFileNames == null) options2.strictFileNames = false;
      if (callback == null) callback = defaultCallback;
      fs95.fstat(fd, function(err, stats) {
        if (err) return callback(err);
        var reader = fd_slicer.createFromFd(fd, { autoClose: true });
        fromRandomAccessReader(reader, stats.size, options2, callback);
      });
    }
    __name(fromFd, "fromFd");
    function fromBuffer(buffer, options2, callback) {
      if (typeof options2 === "function") {
        callback = options2;
        options2 = null;
      }
      if (options2 == null) options2 = {};
      options2.autoClose = false;
      if (options2.lazyEntries == null) options2.lazyEntries = false;
      if (options2.decodeStrings == null) options2.decodeStrings = true;
      if (options2.validateEntrySizes == null) options2.validateEntrySizes = true;
      if (options2.strictFileNames == null) options2.strictFileNames = false;
      var reader = fd_slicer.createFromBuffer(buffer, { maxChunkSize: 65536 });
      fromRandomAccessReader(reader, buffer.length, options2, callback);
    }
    __name(fromBuffer, "fromBuffer");
    function fromRandomAccessReader(reader, totalSize, options2, callback) {
      if (typeof options2 === "function") {
        callback = options2;
        options2 = null;
      }
      if (options2 == null) options2 = {};
      if (options2.autoClose == null) options2.autoClose = true;
      if (options2.lazyEntries == null) options2.lazyEntries = false;
      if (options2.decodeStrings == null) options2.decodeStrings = true;
      var decodeStrings = !!options2.decodeStrings;
      if (options2.validateEntrySizes == null) options2.validateEntrySizes = true;
      if (options2.strictFileNames == null) options2.strictFileNames = false;
      if (callback == null) callback = defaultCallback;
      if (typeof totalSize !== "number") throw new Error("expected totalSize parameter to be a number");
      if (totalSize > Number.MAX_SAFE_INTEGER) {
        throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.");
      }
      reader.ref();
      var eocdrWithoutCommentSize = 22;
      var maxCommentSize = 65535;
      var bufferSize = Math.min(eocdrWithoutCommentSize + maxCommentSize, totalSize);
      var buffer = newBuffer(bufferSize);
      var bufferReadStart = totalSize - buffer.length;
      readAndAssertNoEof(reader, buffer, 0, bufferSize, bufferReadStart, function(err) {
        if (err) return callback(err);
        for (var i = bufferSize - eocdrWithoutCommentSize; i >= 0; i -= 1) {
          if (buffer.readUInt32LE(i) !== 101010256) continue;
          var eocdrBuffer = buffer.slice(i);
          var diskNumber = eocdrBuffer.readUInt16LE(4);
          if (diskNumber !== 0) {
            return callback(new Error("multi-disk zip files are not supported: found disk number: " + diskNumber));
          }
          var entryCount = eocdrBuffer.readUInt16LE(10);
          var centralDirectoryOffset = eocdrBuffer.readUInt32LE(16);
          var commentLength = eocdrBuffer.readUInt16LE(20);
          var expectedCommentLength = eocdrBuffer.length - eocdrWithoutCommentSize;
          if (commentLength !== expectedCommentLength) {
            return callback(new Error("invalid comment length. expected: " + expectedCommentLength + ". found: " + commentLength));
          }
          var comment = decodeStrings ? decodeBuffer(eocdrBuffer, 22, eocdrBuffer.length, false) : eocdrBuffer.slice(22);
          if (!(entryCount === 65535 || centralDirectoryOffset === 4294967295)) {
            return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options2.autoClose, options2.lazyEntries, decodeStrings, options2.validateEntrySizes, options2.strictFileNames));
          }
          var zip64EocdlBuffer = newBuffer(20);
          var zip64EocdlOffset = bufferReadStart + i - zip64EocdlBuffer.length;
          readAndAssertNoEof(reader, zip64EocdlBuffer, 0, zip64EocdlBuffer.length, zip64EocdlOffset, function(err2) {
            if (err2) return callback(err2);
            if (zip64EocdlBuffer.readUInt32LE(0) !== 117853008) {
              return callback(new Error("invalid zip64 end of central directory locator signature"));
            }
            var zip64EocdrOffset = readUInt64LE(zip64EocdlBuffer, 8);
            var zip64EocdrBuffer = newBuffer(56);
            readAndAssertNoEof(reader, zip64EocdrBuffer, 0, zip64EocdrBuffer.length, zip64EocdrOffset, function(err3) {
              if (err3) return callback(err3);
              if (zip64EocdrBuffer.readUInt32LE(0) !== 101075792) {
                return callback(new Error("invalid zip64 end of central directory record signature"));
              }
              entryCount = readUInt64LE(zip64EocdrBuffer, 32);
              centralDirectoryOffset = readUInt64LE(zip64EocdrBuffer, 48);
              return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options2.autoClose, options2.lazyEntries, decodeStrings, options2.validateEntrySizes, options2.strictFileNames));
            });
          });
          return;
        }
        callback(new Error("end of central directory record signature not found"));
      });
    }
    __name(fromRandomAccessReader, "fromRandomAccessReader");
    util4.inherits(ZipFile, EventEmitter10);
    function ZipFile(reader, centralDirectoryOffset, fileSize, entryCount, comment, autoClose, lazyEntries, decodeStrings, validateEntrySizes, strictFileNames) {
      var self2 = this;
      EventEmitter10.call(self2);
      self2.reader = reader;
      self2.reader.on("error", function(err) {
        emitError(self2, err);
      });
      self2.reader.once("close", function() {
        self2.emit("close");
      });
      self2.readEntryCursor = centralDirectoryOffset;
      self2.fileSize = fileSize;
      self2.entryCount = entryCount;
      self2.comment = comment;
      self2.entriesRead = 0;
      self2.autoClose = !!autoClose;
      self2.lazyEntries = !!lazyEntries;
      self2.decodeStrings = !!decodeStrings;
      self2.validateEntrySizes = !!validateEntrySizes;
      self2.strictFileNames = !!strictFileNames;
      self2.isOpen = true;
      self2.emittedError = false;
      if (!self2.lazyEntries) self2._readEntry();
    }
    __name(ZipFile, "ZipFile");
    ZipFile.prototype.close = function() {
      if (!this.isOpen) return;
      this.isOpen = false;
      this.reader.unref();
    };
    function emitErrorAndAutoClose(self2, err) {
      if (self2.autoClose) self2.close();
      emitError(self2, err);
    }
    __name(emitErrorAndAutoClose, "emitErrorAndAutoClose");
    function emitError(self2, err) {
      if (self2.emittedError) return;
      self2.emittedError = true;
      self2.emit("error", err);
    }
    __name(emitError, "emitError");
    ZipFile.prototype.readEntry = function() {
      if (!this.lazyEntries) throw new Error("readEntry() called without lazyEntries:true");
      this._readEntry();
    };
    ZipFile.prototype._readEntry = function() {
      var self2 = this;
      if (self2.entryCount === self2.entriesRead) {
        setImmediate(function() {
          if (self2.autoClose) self2.close();
          if (self2.emittedError) return;
          self2.emit("end");
        });
        return;
      }
      if (self2.emittedError) return;
      var buffer = newBuffer(46);
      readAndAssertNoEof(self2.reader, buffer, 0, buffer.length, self2.readEntryCursor, function(err) {
        if (err) return emitErrorAndAutoClose(self2, err);
        if (self2.emittedError) return;
        var entry = new Entry();
        var signature = buffer.readUInt32LE(0);
        if (signature !== 33639248) return emitErrorAndAutoClose(self2, new Error("invalid central directory file header signature: 0x" + signature.toString(16)));
        entry.versionMadeBy = buffer.readUInt16LE(4);
        entry.versionNeededToExtract = buffer.readUInt16LE(6);
        entry.generalPurposeBitFlag = buffer.readUInt16LE(8);
        entry.compressionMethod = buffer.readUInt16LE(10);
        entry.lastModFileTime = buffer.readUInt16LE(12);
        entry.lastModFileDate = buffer.readUInt16LE(14);
        entry.crc32 = buffer.readUInt32LE(16);
        entry.compressedSize = buffer.readUInt32LE(20);
        entry.uncompressedSize = buffer.readUInt32LE(24);
        entry.fileNameLength = buffer.readUInt16LE(28);
        entry.extraFieldLength = buffer.readUInt16LE(30);
        entry.fileCommentLength = buffer.readUInt16LE(32);
        entry.internalFileAttributes = buffer.readUInt16LE(36);
        entry.externalFileAttributes = buffer.readUInt32LE(38);
        entry.relativeOffsetOfLocalHeader = buffer.readUInt32LE(42);
        if (entry.generalPurposeBitFlag & 64) return emitErrorAndAutoClose(self2, new Error("strong encryption is not supported"));
        self2.readEntryCursor += 46;
        buffer = newBuffer(entry.fileNameLength + entry.extraFieldLength + entry.fileCommentLength);
        readAndAssertNoEof(self2.reader, buffer, 0, buffer.length, self2.readEntryCursor, function(err2) {
          if (err2) return emitErrorAndAutoClose(self2, err2);
          if (self2.emittedError) return;
          var isUtf8 = (entry.generalPurposeBitFlag & 2048) !== 0;
          entry.fileName = self2.decodeStrings ? decodeBuffer(buffer, 0, entry.fileNameLength, isUtf8) : buffer.slice(0, entry.fileNameLength);
          var fileCommentStart = entry.fileNameLength + entry.extraFieldLength;
          var extraFieldBuffer = buffer.slice(entry.fileNameLength, fileCommentStart);
          entry.extraFields = [];
          var i = 0;
          while (i < extraFieldBuffer.length - 3) {
            var headerId = extraFieldBuffer.readUInt16LE(i + 0);
            var dataSize = extraFieldBuffer.readUInt16LE(i + 2);
            var dataStart = i + 4;
            var dataEnd = dataStart + dataSize;
            if (dataEnd > extraFieldBuffer.length) return emitErrorAndAutoClose(self2, new Error("extra field length exceeds extra field buffer size"));
            var dataBuffer = newBuffer(dataSize);
            extraFieldBuffer.copy(dataBuffer, 0, dataStart, dataEnd);
            entry.extraFields.push({
              id: headerId,
              data: dataBuffer
            });
            i = dataEnd;
          }
          entry.fileComment = self2.decodeStrings ? decodeBuffer(buffer, fileCommentStart, fileCommentStart + entry.fileCommentLength, isUtf8) : buffer.slice(fileCommentStart, fileCommentStart + entry.fileCommentLength);
          entry.comment = entry.fileComment;
          self2.readEntryCursor += buffer.length;
          self2.entriesRead += 1;
          if (entry.uncompressedSize === 4294967295 || entry.compressedSize === 4294967295 || entry.relativeOffsetOfLocalHeader === 4294967295) {
            var zip64EiefBuffer = null;
            for (var i = 0; i < entry.extraFields.length; i++) {
              var extraField = entry.extraFields[i];
              if (extraField.id === 1) {
                zip64EiefBuffer = extraField.data;
                break;
              }
            }
            if (zip64EiefBuffer == null) {
              return emitErrorAndAutoClose(self2, new Error("expected zip64 extended information extra field"));
            }
            var index = 0;
            if (entry.uncompressedSize === 4294967295) {
              if (index + 8 > zip64EiefBuffer.length) {
                return emitErrorAndAutoClose(self2, new Error("zip64 extended information extra field does not include uncompressed size"));
              }
              entry.uncompressedSize = readUInt64LE(zip64EiefBuffer, index);
              index += 8;
            }
            if (entry.compressedSize === 4294967295) {
              if (index + 8 > zip64EiefBuffer.length) {
                return emitErrorAndAutoClose(self2, new Error("zip64 extended information extra field does not include compressed size"));
              }
              entry.compressedSize = readUInt64LE(zip64EiefBuffer, index);
              index += 8;
            }
            if (entry.relativeOffsetOfLocalHeader === 4294967295) {
              if (index + 8 > zip64EiefBuffer.length) {
                return emitErrorAndAutoClose(self2, new Error("zip64 extended information extra field does not include relative header offset"));
              }
              entry.relativeOffsetOfLocalHeader = readUInt64LE(zip64EiefBuffer, index);
              index += 8;
            }
          }
          if (self2.decodeStrings) {
            for (var i = 0; i < entry.extraFields.length; i++) {
              var extraField = entry.extraFields[i];
              if (extraField.id === 28789) {
                if (extraField.data.length < 6) {
                  continue;
                }
                if (extraField.data.readUInt8(0) !== 1) {
                  continue;
                }
                var oldNameCrc32 = extraField.data.readUInt32LE(1);
                if (crc32.unsigned(buffer.slice(0, entry.fileNameLength)) !== oldNameCrc32) {
                  continue;
                }
                entry.fileName = decodeBuffer(extraField.data, 5, extraField.data.length, true);
                break;
              }
            }
          }
          if (self2.validateEntrySizes && entry.compressionMethod === 0) {
            var expectedCompressedSize = entry.uncompressedSize;
            if (entry.isEncrypted()) {
              expectedCompressedSize += 12;
            }
            if (entry.compressedSize !== expectedCompressedSize) {
              var msg = "compressed/uncompressed size mismatch for stored file: " + entry.compressedSize + " != " + entry.uncompressedSize;
              return emitErrorAndAutoClose(self2, new Error(msg));
            }
          }
          if (self2.decodeStrings) {
            if (!self2.strictFileNames) {
              entry.fileName = entry.fileName.replace(/\\/g, "/");
            }
            var errorMessage = validateFileName(entry.fileName, self2.validateFileNameOptions);
            if (errorMessage != null) return emitErrorAndAutoClose(self2, new Error(errorMessage));
          }
          self2.emit("entry", entry);
          if (!self2.lazyEntries) self2._readEntry();
        });
      });
    };
    ZipFile.prototype.openReadStream = function(entry, options2, callback) {
      var self2 = this;
      var relativeStart = 0;
      var relativeEnd = entry.compressedSize;
      if (callback == null) {
        callback = options2;
        options2 = {};
      } else {
        if (options2.decrypt != null) {
          if (!entry.isEncrypted()) {
            throw new Error("options.decrypt can only be specified for encrypted entries");
          }
          if (options2.decrypt !== false) throw new Error("invalid options.decrypt value: " + options2.decrypt);
          if (entry.isCompressed()) {
            if (options2.decompress !== false) throw new Error("entry is encrypted and compressed, and options.decompress !== false");
          }
        }
        if (options2.decompress != null) {
          if (!entry.isCompressed()) {
            throw new Error("options.decompress can only be specified for compressed entries");
          }
          if (!(options2.decompress === false || options2.decompress === true)) {
            throw new Error("invalid options.decompress value: " + options2.decompress);
          }
        }
        if (options2.start != null || options2.end != null) {
          if (entry.isCompressed() && options2.decompress !== false) {
            throw new Error("start/end range not allowed for compressed entry without options.decompress === false");
          }
          if (entry.isEncrypted() && options2.decrypt !== false) {
            throw new Error("start/end range not allowed for encrypted entry without options.decrypt === false");
          }
        }
        if (options2.start != null) {
          relativeStart = options2.start;
          if (relativeStart < 0) throw new Error("options.start < 0");
          if (relativeStart > entry.compressedSize) throw new Error("options.start > entry.compressedSize");
        }
        if (options2.end != null) {
          relativeEnd = options2.end;
          if (relativeEnd < 0) throw new Error("options.end < 0");
          if (relativeEnd > entry.compressedSize) throw new Error("options.end > entry.compressedSize");
          if (relativeEnd < relativeStart) throw new Error("options.end < options.start");
        }
      }
      if (!self2.isOpen) return callback(new Error("closed"));
      if (entry.isEncrypted()) {
        if (options2.decrypt !== false) return callback(new Error("entry is encrypted, and options.decrypt !== false"));
      }
      self2.reader.ref();
      var buffer = newBuffer(30);
      readAndAssertNoEof(self2.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader, function(err) {
        try {
          if (err) return callback(err);
          var signature = buffer.readUInt32LE(0);
          if (signature !== 67324752) {
            return callback(new Error("invalid local file header signature: 0x" + signature.toString(16)));
          }
          var fileNameLength = buffer.readUInt16LE(26);
          var extraFieldLength = buffer.readUInt16LE(28);
          var localFileHeaderEnd = entry.relativeOffsetOfLocalHeader + buffer.length + fileNameLength + extraFieldLength;
          var decompress;
          if (entry.compressionMethod === 0) {
            decompress = false;
          } else if (entry.compressionMethod === 8) {
            decompress = options2.decompress != null ? options2.decompress : true;
          } else {
            return callback(new Error("unsupported compression method: " + entry.compressionMethod));
          }
          var fileDataStart = localFileHeaderEnd;
          var fileDataEnd = fileDataStart + entry.compressedSize;
          if (entry.compressedSize !== 0) {
            if (fileDataEnd > self2.fileSize) {
              return callback(new Error("file data overflows file bounds: " + fileDataStart + " + " + entry.compressedSize + " > " + self2.fileSize));
            }
          }
          var readStream = self2.reader.createReadStream({
            start: fileDataStart + relativeStart,
            end: fileDataStart + relativeEnd
          });
          var endpointStream = readStream;
          if (decompress) {
            var destroyed = false;
            var inflateFilter = zlib2.createInflateRaw();
            readStream.on("error", function(err2) {
              setImmediate(function() {
                if (!destroyed) inflateFilter.emit("error", err2);
              });
            });
            readStream.pipe(inflateFilter);
            if (self2.validateEntrySizes) {
              endpointStream = new AssertByteCountStream(entry.uncompressedSize);
              inflateFilter.on("error", function(err2) {
                setImmediate(function() {
                  if (!destroyed) endpointStream.emit("error", err2);
                });
              });
              inflateFilter.pipe(endpointStream);
            } else {
              endpointStream = inflateFilter;
            }
            endpointStream.destroy = function() {
              destroyed = true;
              if (inflateFilter !== endpointStream) inflateFilter.unpipe(endpointStream);
              readStream.unpipe(inflateFilter);
              readStream.destroy();
            };
          }
          callback(null, endpointStream);
        } finally {
          self2.reader.unref();
        }
      });
    };
    function Entry() {
    }
    __name(Entry, "Entry");
    Entry.prototype.getLastModDate = function() {
      return dosDateTimeToDate(this.lastModFileDate, this.lastModFileTime);
    };
    Entry.prototype.isEncrypted = function() {
      return (this.generalPurposeBitFlag & 1) !== 0;
    };
    Entry.prototype.isCompressed = function() {
      return this.compressionMethod === 8;
    };
    function dosDateTimeToDate(date, time) {
      var day = date & 31;
      var month = (date >> 5 & 15) - 1;
      var year = (date >> 9 & 127) + 1980;
      var millisecond = 0;
      var second = (time & 31) * 2;
      var minute = time >> 5 & 63;
      var hour = time >> 11 & 31;
      return new Date(year, month, day, hour, minute, second, millisecond);
    }
    __name(dosDateTimeToDate, "dosDateTimeToDate");
    function validateFileName(fileName) {
      if (fileName.indexOf("\\") !== -1) {
        return "invalid characters in fileName: " + fileName;
      }
      if (/^[a-zA-Z]:/.test(fileName) || /^\//.test(fileName)) {
        return "absolute path: " + fileName;
      }
      if (fileName.split("/").indexOf("..") !== -1) {
        return "invalid relative path: " + fileName;
      }
      return null;
    }
    __name(validateFileName, "validateFileName");
    function readAndAssertNoEof(reader, buffer, offset, length, position, callback) {
      if (length === 0) {
        return setImmediate(function() {
          callback(null, newBuffer(0));
        });
      }
      reader.read(buffer, offset, length, position, function(err, bytesRead) {
        if (err) return callback(err);
        if (bytesRead < length) {
          return callback(new Error("unexpected EOF"));
        }
        callback();
      });
    }
    __name(readAndAssertNoEof, "readAndAssertNoEof");
    util4.inherits(AssertByteCountStream, Transform2);
    function AssertByteCountStream(byteCount) {
      Transform2.call(this);
      this.actualByteCount = 0;
      this.expectedByteCount = byteCount;
    }
    __name(AssertByteCountStream, "AssertByteCountStream");
    AssertByteCountStream.prototype._transform = function(chunk, encoding, cb) {
      this.actualByteCount += chunk.length;
      if (this.actualByteCount > this.expectedByteCount) {
        var msg = "too many bytes in the stream. expected " + this.expectedByteCount + ". got at least " + this.actualByteCount;
        return cb(new Error(msg));
      }
      cb(null, chunk);
    };
    AssertByteCountStream.prototype._flush = function(cb) {
      if (this.actualByteCount < this.expectedByteCount) {
        var msg = "not enough bytes in the stream. expected " + this.expectedByteCount + ". got only " + this.actualByteCount;
        return cb(new Error(msg));
      }
      cb();
    };
    util4.inherits(RandomAccessReader, EventEmitter10);
    function RandomAccessReader() {
      EventEmitter10.call(this);
      this.refCount = 0;
    }
    __name(RandomAccessReader, "RandomAccessReader");
    RandomAccessReader.prototype.ref = function() {
      this.refCount += 1;
    };
    RandomAccessReader.prototype.unref = function() {
      var self2 = this;
      self2.refCount -= 1;
      if (self2.refCount > 0) return;
      if (self2.refCount < 0) throw new Error("invalid unref");
      self2.close(onCloseDone);
      function onCloseDone(err) {
        if (err) return self2.emit("error", err);
        self2.emit("close");
      }
      __name(onCloseDone, "onCloseDone");
    };
    RandomAccessReader.prototype.createReadStream = function(options2) {
      var start = options2.start;
      var end = options2.end;
      if (start === end) {
        var emptyStream = new PassThrough4();
        setImmediate(function() {
          emptyStream.end();
        });
        return emptyStream;
      }
      var stream2 = this._readStreamForRange(start, end);
      var destroyed = false;
      var refUnrefFilter = new RefUnrefFilter(this);
      stream2.on("error", function(err) {
        setImmediate(function() {
          if (!destroyed) refUnrefFilter.emit("error", err);
        });
      });
      refUnrefFilter.destroy = function() {
        stream2.unpipe(refUnrefFilter);
        refUnrefFilter.unref();
        stream2.destroy();
      };
      var byteCounter = new AssertByteCountStream(end - start);
      refUnrefFilter.on("error", function(err) {
        setImmediate(function() {
          if (!destroyed) byteCounter.emit("error", err);
        });
      });
      byteCounter.destroy = function() {
        destroyed = true;
        refUnrefFilter.unpipe(byteCounter);
        refUnrefFilter.destroy();
      };
      return stream2.pipe(refUnrefFilter).pipe(byteCounter);
    };
    RandomAccessReader.prototype._readStreamForRange = function(start, end) {
      throw new Error("not implemented");
    };
    RandomAccessReader.prototype.read = function(buffer, offset, length, position, callback) {
      var readStream = this.createReadStream({ start: position, end: position + length });
      var writeStream = new Writable3();
      var written = 0;
      writeStream._write = function(chunk, encoding, cb) {
        chunk.copy(buffer, offset + written, 0, chunk.length);
        written += chunk.length;
        cb();
      };
      writeStream.on("finish", callback);
      readStream.on("error", function(error) {
        callback(error);
      });
      readStream.pipe(writeStream);
    };
    RandomAccessReader.prototype.close = function(callback) {
      setImmediate(callback);
    };
    util4.inherits(RefUnrefFilter, PassThrough4);
    function RefUnrefFilter(context2) {
      PassThrough4.call(this);
      this.context = context2;
      this.context.ref();
      this.unreffedYet = false;
    }
    __name(RefUnrefFilter, "RefUnrefFilter");
    RefUnrefFilter.prototype._flush = function(cb) {
      this.unref();
      cb();
    };
    RefUnrefFilter.prototype.unref = function(cb) {
      if (this.unreffedYet) return;
      this.unreffedYet = true;
      this.context.unref();
    };
    var cp437 = "\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0";
    function decodeBuffer(buffer, start, end, isUtf8) {
      if (isUtf8) {
        return buffer.toString("utf8", start, end);
      } else {
        var result = "";
        for (var i = start; i < end; i++) {
          result += cp437[buffer[i]];
        }
        return result;
      }
    }
    __name(decodeBuffer, "decodeBuffer");
    function readUInt64LE(buffer, offset) {
      var lower32 = buffer.readUInt32LE(offset);
      var upper32 = buffer.readUInt32LE(offset + 4);
      return upper32 * 4294967296 + lower32;
    }
    __name(readUInt64LE, "readUInt64LE");
    var newBuffer;
    if (typeof Buffer.allocUnsafe === "function") {
      newBuffer = /* @__PURE__ */ __name(function(len) {
        return Buffer.allocUnsafe(len);
      }, "newBuffer");
    } else {
      newBuffer = /* @__PURE__ */ __name(function(len) {
        return new Buffer(len);
      }, "newBuffer");
    }
    function defaultCallback(err) {
      if (err) throw err;
    }
    __name(defaultCallback, "defaultCallback");
  }
});

// node_modules/extract-zip/index.js
var require_extract_zip = __commonJS({
  "node_modules/extract-zip/index.js"(exports2, module2) {
    init_esbuild_shims();
    var debug2 = require_src()("extract-zip");
    var { createWriteStream: createWriteStream5, promises: fs95 } = __require("fs");
    var getStream = require_get_stream();
    var path108 = __require("path");
    var { promisify: promisify10 } = __require("util");
    var stream2 = __require("stream");
    var yauzl = require_yauzl();
    var openZip = promisify10(yauzl.open);
    var pipeline = promisify10(stream2.pipeline);
    var Extractor = class {
      static {
        __name(this, "Extractor");
      }
      constructor(zipPath, opts) {
        this.zipPath = zipPath;
        this.opts = opts;
      }
      async extract() {
        debug2("opening", this.zipPath, "with opts", this.opts);
        this.zipfile = await openZip(this.zipPath, { lazyEntries: true });
        this.canceled = false;
        return new Promise((resolve24, reject) => {
          this.zipfile.on("error", (err) => {
            this.canceled = true;
            reject(err);
          });
          this.zipfile.readEntry();
          this.zipfile.on("close", () => {
            if (!this.canceled) {
              debug2("zip extraction complete");
              resolve24();
            }
          });
          this.zipfile.on("entry", async (entry) => {
            if (this.canceled) {
              debug2("skipping entry", entry.fileName, { cancelled: this.canceled });
              return;
            }
            debug2("zipfile entry", entry.fileName);
            if (entry.fileName.startsWith("__MACOSX/")) {
              this.zipfile.readEntry();
              return;
            }
            const destDir = path108.dirname(path108.join(this.opts.dir, entry.fileName));
            try {
              await fs95.mkdir(destDir, { recursive: true });
              const canonicalDestDir = await fs95.realpath(destDir);
              const relativeDestDir = path108.relative(this.opts.dir, canonicalDestDir);
              if (relativeDestDir.split(path108.sep).includes("..")) {
                throw new Error(`Out of bound path "${canonicalDestDir}" found while processing file ${entry.fileName}`);
              }
              await this.extractEntry(entry);
              debug2("finished processing", entry.fileName);
              this.zipfile.readEntry();
            } catch (err) {
              this.canceled = true;
              this.zipfile.close();
              reject(err);
            }
          });
        });
      }
      async extractEntry(entry) {
        if (this.canceled) {
          debug2("skipping entry extraction", entry.fileName, { cancelled: this.canceled });
          return;
        }
        if (this.opts.onEntry) {
          this.opts.onEntry(entry, this.zipfile);
        }
        const dest = path108.join(this.opts.dir, entry.fileName);
        const mode = entry.externalFileAttributes >> 16 & 65535;
        const IFMT2 = 61440;
        const IFDIR2 = 16384;
        const IFLNK2 = 40960;
        const symlink = (mode & IFMT2) === IFLNK2;
        let isDir = (mode & IFMT2) === IFDIR2;
        if (!isDir && entry.fileName.endsWith("/")) {
          isDir = true;
        }
        const madeBy = entry.versionMadeBy >> 8;
        if (!isDir) isDir = madeBy === 0 && entry.externalFileAttributes === 16;
        debug2("extracting entry", { filename: entry.fileName, isDir, isSymlink: symlink });
        const procMode = this.getExtractedMode(mode, isDir) & 511;
        const destDir = isDir ? dest : path108.dirname(dest);
        const mkdirOptions2 = { recursive: true };
        if (isDir) {
          mkdirOptions2.mode = procMode;
        }
        debug2("mkdir", { dir: destDir, ...mkdirOptions2 });
        await fs95.mkdir(destDir, mkdirOptions2);
        if (isDir) return;
        debug2("opening read stream", dest);
        const readStream = await promisify10(this.zipfile.openReadStream.bind(this.zipfile))(entry);
        if (symlink) {
          const link3 = await getStream(readStream);
          debug2("creating symlink", link3, dest);
          await fs95.symlink(link3, dest);
        } else {
          await pipeline(readStream, createWriteStream5(dest, { mode: procMode }));
        }
      }
      getExtractedMode(entryMode, isDir) {
        let mode = entryMode;
        if (mode === 0) {
          if (isDir) {
            if (this.opts.defaultDirMode) {
              mode = parseInt(this.opts.defaultDirMode, 10);
            }
            if (!mode) {
              mode = 493;
            }
          } else {
            if (this.opts.defaultFileMode) {
              mode = parseInt(this.opts.defaultFileMode, 10);
            }
            if (!mode) {
              mode = 420;
            }
          }
        }
        return mode;
      }
    };
    module2.exports = async function(zipPath, opts) {
      debug2("creating target directory", opts.dir);
      if (!path108.isAbsolute(opts.dir)) {
        throw new Error("Target directory is expected to be absolute");
      }
      await fs95.mkdir(opts.dir, { recursive: true });
      opts.dir = await fs95.realpath(opts.dir);
      return new Extractor(zipPath, opts).extract();
    };
  }
});

// node_modules/ink-link/node_modules/supports-color/index.js
var require_supports_color3 = __commonJS({
  "node_modules/ink-link/node_modules/supports-color/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var os43 = __require("os");
    var tty3 = __require("tty");
    var hasFlag3 = require_has_flag2();
    var { env: env7 } = process;
    var forceColor;
    if (hasFlag3("no-color") || hasFlag3("no-colors") || hasFlag3("color=false") || hasFlag3("color=never")) {
      forceColor = 0;
    } else if (hasFlag3("color") || hasFlag3("colors") || hasFlag3("color=true") || hasFlag3("color=always")) {
      forceColor = 1;
    }
    if ("FORCE_COLOR" in env7) {
      if (env7.FORCE_COLOR === "true") {
        forceColor = 1;
      } else if (env7.FORCE_COLOR === "false") {
        forceColor = 0;
      } else {
        forceColor = env7.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env7.FORCE_COLOR, 10), 3);
      }
    }
    function translateLevel3(level) {
      if (level === 0) {
        return false;
      }
      return {
        level,
        hasBasic: true,
        has256: level >= 2,
        has16m: level >= 3
      };
    }
    __name(translateLevel3, "translateLevel");
    function supportsColor3(haveStream, streamIsTTY) {
      if (forceColor === 0) {
        return 0;
      }
      if (hasFlag3("color=16m") || hasFlag3("color=full") || hasFlag3("color=truecolor")) {
        return 3;
      }
      if (hasFlag3("color=256")) {
        return 2;
      }
      if (haveStream && !streamIsTTY && forceColor === void 0) {
        return 0;
      }
      const min = forceColor || 0;
      if (env7.TERM === "dumb") {
        return min;
      }
      if (process.platform === "win32") {
        const osRelease = os43.release().split(".");
        if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
          return Number(osRelease[2]) >= 14931 ? 3 : 2;
        }
        return 1;
      }
      if ("CI" in env7) {
        if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env7) || env7.CI_NAME === "codeship") {
          return 1;
        }
        return min;
      }
      if ("TEAMCITY_VERSION" in env7) {
        return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env7.TEAMCITY_VERSION) ? 1 : 0;
      }
      if (env7.COLORTERM === "truecolor") {
        return 3;
      }
      if ("TERM_PROGRAM" in env7) {
        const version2 = parseInt((env7.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
        switch (env7.TERM_PROGRAM) {
          case "iTerm.app":
            return version2 >= 3 ? 3 : 2;
          case "Apple_Terminal":
            return 2;
        }
      }
      if (/-256(color)?$/i.test(env7.TERM)) {
        return 2;
      }
      if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env7.TERM)) {
        return 1;
      }
      if ("COLORTERM" in env7) {
        return 1;
      }
      return min;
    }
    __name(supportsColor3, "supportsColor");
    function getSupportLevel(stream2) {
      const level = supportsColor3(stream2, stream2 && stream2.isTTY);
      return translateLevel3(level);
    }
    __name(getSupportLevel, "getSupportLevel");
    module2.exports = {
      supportsColor: getSupportLevel,
      stdout: translateLevel3(supportsColor3(true, tty3.isatty(1))),
      stderr: translateLevel3(supportsColor3(true, tty3.isatty(2)))
    };
  }
});

// node_modules/ink-link/node_modules/supports-hyperlinks/index.js
var require_supports_hyperlinks = __commonJS({
  "node_modules/ink-link/node_modules/supports-hyperlinks/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var supportsColor3 = require_supports_color3();
    var hasFlag3 = require_has_flag2();
    function parseVersion(versionString) {
      if (/^\d{3,4}$/.test(versionString)) {
        const m = /(\d{1,2})(\d{2})/.exec(versionString);
        return {
          major: 0,
          minor: parseInt(m[1], 10),
          patch: parseInt(m[2], 10)
        };
      }
      const versions = (versionString || "").split(".").map((n2) => parseInt(n2, 10));
      return {
        major: versions[0],
        minor: versions[1],
        patch: versions[2]
      };
    }
    __name(parseVersion, "parseVersion");
    function supportsHyperlink(stream2) {
      const { env: env7 } = process;
      if ("FORCE_HYPERLINK" in env7) {
        return !(env7.FORCE_HYPERLINK.length > 0 && parseInt(env7.FORCE_HYPERLINK, 10) === 0);
      }
      if (hasFlag3("no-hyperlink") || hasFlag3("no-hyperlinks") || hasFlag3("hyperlink=false") || hasFlag3("hyperlink=never")) {
        return false;
      }
      if (hasFlag3("hyperlink=true") || hasFlag3("hyperlink=always")) {
        return true;
      }
      if ("NETLIFY" in env7) {
        return true;
      }
      if (!supportsColor3.supportsColor(stream2)) {
        return false;
      }
      if (stream2 && !stream2.isTTY) {
        return false;
      }
      if (process.platform === "win32") {
        return false;
      }
      if ("CI" in env7) {
        return false;
      }
      if ("TEAMCITY_VERSION" in env7) {
        return false;
      }
      if ("TERM_PROGRAM" in env7) {
        const version2 = parseVersion(env7.TERM_PROGRAM_VERSION);
        switch (env7.TERM_PROGRAM) {
          case "iTerm.app":
            if (version2.major === 3) {
              return version2.minor >= 1;
            }
            return version2.major > 3;
          case "WezTerm":
            return version2.major >= 20200620;
          case "vscode":
            return version2.major > 1 || version2.major === 1 && version2.minor >= 72;
        }
      }
      if ("VTE_VERSION" in env7) {
        if (env7.VTE_VERSION === "0.50.0") {
          return false;
        }
        const version2 = parseVersion(env7.VTE_VERSION);
        return version2.major > 0 || version2.minor >= 50;
      }
      return false;
    }
    __name(supportsHyperlink, "supportsHyperlink");
    module2.exports = {
      supportsHyperlink,
      stdout: supportsHyperlink(process.stdout),
      stderr: supportsHyperlink(process.stderr)
    };
  }
});

// node_modules/qrcode-terminal/vendor/QRCode/QRMode.js
var require_QRMode = __commonJS({
  "node_modules/qrcode-terminal/vendor/QRCode/QRMode.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = {
      MODE_NUMBER: 1 << 0,
      MODE_ALPHA_NUM: 1 << 1,
      MODE_8BIT_BYTE: 1 << 2,
      MODE_KANJI: 1 << 3
    };
  }
});

// node_modules/qrcode-terminal/vendor/QRCode/QR8bitByte.js
var require_QR8bitByte = __commonJS({
  "node_modules/qrcode-terminal/vendor/QRCode/QR8bitByte.js"(exports2, module2) {
    init_esbuild_shims();
    var QRMode = require_QRMode();
    function QR8bitByte(data) {
      this.mode = QRMode.MODE_8BIT_BYTE;
      this.data = data;
    }
    __name(QR8bitByte, "QR8bitByte");
    QR8bitByte.prototype = {
      getLength: /* @__PURE__ */ __name(function() {
        return this.data.length;
      }, "getLength"),
      write: /* @__PURE__ */ __name(function(buffer) {
        for (var i = 0; i < this.data.length; i++) {
          buffer.put(this.data.charCodeAt(i), 8);
        }
      }, "write")
    };
    module2.exports = QR8bitByte;
  }
});

// node_modules/qrcode-terminal/vendor/QRCode/QRMath.js
var require_QRMath = __commonJS({
  "node_modules/qrcode-terminal/vendor/QRCode/QRMath.js"(exports2, module2) {
    init_esbuild_shims();
    var QRMath = {
      glog: /* @__PURE__ */ __name(function(n2) {
        if (n2 < 1) {
          throw new Error("glog(" + n2 + ")");
        }
        return QRMath.LOG_TABLE[n2];
      }, "glog"),
      gexp: /* @__PURE__ */ __name(function(n2) {
        while (n2 < 0) {
          n2 += 255;
        }
        while (n2 >= 256) {
          n2 -= 255;
        }
        return QRMath.EXP_TABLE[n2];
      }, "gexp"),
      EXP_TABLE: new Array(256),
      LOG_TABLE: new Array(256)
    };
    for (i = 0; i < 8; i++) {
      QRMath.EXP_TABLE[i] = 1 << i;
    }
    var i;
    for (i = 8; i < 256; i++) {
      QRMath.EXP_TABLE[i] = QRMath.EXP_TABLE[i - 4] ^ QRMath.EXP_TABLE[i - 5] ^ QRMath.EXP_TABLE[i - 6] ^ QRMath.EXP_TABLE[i - 8];
    }
    var i;
    for (i = 0; i < 255; i++) {
      QRMath.LOG_TABLE[QRMath.EXP_TABLE[i]] = i;
    }
    var i;
    module2.exports = QRMath;
  }
});

// node_modules/qrcode-terminal/vendor/QRCode/QRPolynomial.js
var require_QRPolynomial = __commonJS({
  "node_modules/qrcode-terminal/vendor/QRCode/QRPolynomial.js"(exports2, module2) {
    init_esbuild_shims();
    var QRMath = require_QRMath();
    function QRPolynomial(num, shift) {
      if (num.length === void 0) {
        throw new Error(num.length + "/" + shift);
      }
      var offset = 0;
      while (offset < num.length && num[offset] === 0) {
        offset++;
      }
      this.num = new Array(num.length - offset + shift);
      for (var i = 0; i < num.length - offset; i++) {
        this.num[i] = num[i + offset];
      }
    }
    __name(QRPolynomial, "QRPolynomial");
    QRPolynomial.prototype = {
      get: /* @__PURE__ */ __name(function(index) {
        return this.num[index];
      }, "get"),
      getLength: /* @__PURE__ */ __name(function() {
        return this.num.length;
      }, "getLength"),
      multiply: /* @__PURE__ */ __name(function(e2) {
        var num = new Array(this.getLength() + e2.getLength() - 1);
        for (var i = 0; i < this.getLength(); i++) {
          for (var j = 0; j < e2.getLength(); j++) {
            num[i + j] ^= QRMath.gexp(QRMath.glog(this.get(i)) + QRMath.glog(e2.get(j)));
          }
        }
        return new QRPolynomial(num, 0);
      }, "multiply"),
      mod: /* @__PURE__ */ __name(function(e2) {
        if (this.getLength() - e2.getLength() < 0) {
          return this;
        }
        var ratio = QRMath.glog(this.get(0)) - QRMath.glog(e2.get(0));
        var num = new Array(this.getLength());
        for (var i = 0; i < this.getLength(); i++) {
          num[i] = this.get(i);
        }
        for (var x = 0; x < e2.getLength(); x++) {
          num[x] ^= QRMath.gexp(QRMath.glog(e2.get(x)) + ratio);
        }
        return new QRPolynomial(num, 0).mod(e2);
      }, "mod")
    };
    module2.exports = QRPolynomial;
  }
});

// node_modules/qrcode-terminal/vendor/QRCode/QRMaskPattern.js
var require_QRMaskPattern = __commonJS({
  "node_modules/qrcode-terminal/vendor/QRCode/QRMaskPattern.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = {
      PATTERN000: 0,
      PATTERN001: 1,
      PATTERN010: 2,
      PATTERN011: 3,
      PATTERN100: 4,
      PATTERN101: 5,
      PATTERN110: 6,
      PATTERN111: 7
    };
  }
});

// node_modules/qrcode-terminal/vendor/QRCode/QRUtil.js
var require_QRUtil = __commonJS({
  "node_modules/qrcode-terminal/vendor/QRCode/QRUtil.js"(exports2, module2) {
    init_esbuild_shims();
    var QRMode = require_QRMode();
    var QRPolynomial = require_QRPolynomial();
    var QRMath = require_QRMath();
    var QRMaskPattern = require_QRMaskPattern();
    var QRUtil = {
      PATTERN_POSITION_TABLE: [
        [],
        [6, 18],
        [6, 22],
        [6, 26],
        [6, 30],
        [6, 34],
        [6, 22, 38],
        [6, 24, 42],
        [6, 26, 46],
        [6, 28, 50],
        [6, 30, 54],
        [6, 32, 58],
        [6, 34, 62],
        [6, 26, 46, 66],
        [6, 26, 48, 70],
        [6, 26, 50, 74],
        [6, 30, 54, 78],
        [6, 30, 56, 82],
        [6, 30, 58, 86],
        [6, 34, 62, 90],
        [6, 28, 50, 72, 94],
        [6, 26, 50, 74, 98],
        [6, 30, 54, 78, 102],
        [6, 28, 54, 80, 106],
        [6, 32, 58, 84, 110],
        [6, 30, 58, 86, 114],
        [6, 34, 62, 90, 118],
        [6, 26, 50, 74, 98, 122],
        [6, 30, 54, 78, 102, 126],
        [6, 26, 52, 78, 104, 130],
        [6, 30, 56, 82, 108, 134],
        [6, 34, 60, 86, 112, 138],
        [6, 30, 58, 86, 114, 142],
        [6, 34, 62, 90, 118, 146],
        [6, 30, 54, 78, 102, 126, 150],
        [6, 24, 50, 76, 102, 128, 154],
        [6, 28, 54, 80, 106, 132, 158],
        [6, 32, 58, 84, 110, 136, 162],
        [6, 26, 54, 82, 110, 138, 166],
        [6, 30, 58, 86, 114, 142, 170]
      ],
      G15: 1 << 10 | 1 << 8 | 1 << 5 | 1 << 4 | 1 << 2 | 1 << 1 | 1 << 0,
      G18: 1 << 12 | 1 << 11 | 1 << 10 | 1 << 9 | 1 << 8 | 1 << 5 | 1 << 2 | 1 << 0,
      G15_MASK: 1 << 14 | 1 << 12 | 1 << 10 | 1 << 4 | 1 << 1,
      getBCHTypeInfo: /* @__PURE__ */ __name(function(data) {
        var d = data << 10;
        while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0) {
          d ^= QRUtil.G15 << QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15);
        }
        return (data << 10 | d) ^ QRUtil.G15_MASK;
      }, "getBCHTypeInfo"),
      getBCHTypeNumber: /* @__PURE__ */ __name(function(data) {
        var d = data << 12;
        while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0) {
          d ^= QRUtil.G18 << QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18);
        }
        return data << 12 | d;
      }, "getBCHTypeNumber"),
      getBCHDigit: /* @__PURE__ */ __name(function(data) {
        var digit = 0;
        while (data !== 0) {
          digit++;
          data >>>= 1;
        }
        return digit;
      }, "getBCHDigit"),
      getPatternPosition: /* @__PURE__ */ __name(function(typeNumber) {
        return QRUtil.PATTERN_POSITION_TABLE[typeNumber - 1];
      }, "getPatternPosition"),
      getMask: /* @__PURE__ */ __name(function(maskPattern, i, j) {
        switch (maskPattern) {
          case QRMaskPattern.PATTERN000:
            return (i + j) % 2 === 0;
          case QRMaskPattern.PATTERN001:
            return i % 2 === 0;
          case QRMaskPattern.PATTERN010:
            return j % 3 === 0;
          case QRMaskPattern.PATTERN011:
            return (i + j) % 3 === 0;
          case QRMaskPattern.PATTERN100:
            return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0;
          case QRMaskPattern.PATTERN101:
            return i * j % 2 + i * j % 3 === 0;
          case QRMaskPattern.PATTERN110:
            return (i * j % 2 + i * j % 3) % 2 === 0;
          case QRMaskPattern.PATTERN111:
            return (i * j % 3 + (i + j) % 2) % 2 === 0;
          default:
            throw new Error("bad maskPattern:" + maskPattern);
        }
      }, "getMask"),
      getErrorCorrectPolynomial: /* @__PURE__ */ __name(function(errorCorrectLength) {
        var a = new QRPolynomial([1], 0);
        for (var i = 0; i < errorCorrectLength; i++) {
          a = a.multiply(new QRPolynomial([1, QRMath.gexp(i)], 0));
        }
        return a;
      }, "getErrorCorrectPolynomial"),
      getLengthInBits: /* @__PURE__ */ __name(function(mode, type) {
        if (1 <= type && type < 10) {
          switch (mode) {
            case QRMode.MODE_NUMBER:
              return 10;
            case QRMode.MODE_ALPHA_NUM:
              return 9;
            case QRMode.MODE_8BIT_BYTE:
              return 8;
            case QRMode.MODE_KANJI:
              return 8;
            default:
              throw new Error("mode:" + mode);
          }
        } else if (type < 27) {
          switch (mode) {
            case QRMode.MODE_NUMBER:
              return 12;
            case QRMode.MODE_ALPHA_NUM:
              return 11;
            case QRMode.MODE_8BIT_BYTE:
              return 16;
            case QRMode.MODE_KANJI:
              return 10;
            default:
              throw new Error("mode:" + mode);
          }
        } else if (type < 41) {
          switch (mode) {
            case QRMode.MODE_NUMBER:
              return 14;
            case QRMode.MODE_ALPHA_NUM:
              return 13;
            case QRMode.MODE_8BIT_BYTE:
              return 16;
            case QRMode.MODE_KANJI:
              return 12;
            default:
              throw new Error("mode:" + mode);
          }
        } else {
          throw new Error("type:" + type);
        }
      }, "getLengthInBits"),
      getLostPoint: /* @__PURE__ */ __name(function(qrCode) {
        var moduleCount = qrCode.getModuleCount();
        var lostPoint = 0;
        var row = 0;
        var col = 0;
        for (row = 0; row < moduleCount; row++) {
          for (col = 0; col < moduleCount; col++) {
            var sameCount = 0;
            var dark = qrCode.isDark(row, col);
            for (var r3 = -1; r3 <= 1; r3++) {
              if (row + r3 < 0 || moduleCount <= row + r3) {
                continue;
              }
              for (var c3 = -1; c3 <= 1; c3++) {
                if (col + c3 < 0 || moduleCount <= col + c3) {
                  continue;
                }
                if (r3 === 0 && c3 === 0) {
                  continue;
                }
                if (dark === qrCode.isDark(row + r3, col + c3)) {
                  sameCount++;
                }
              }
            }
            if (sameCount > 5) {
              lostPoint += 3 + sameCount - 5;
            }
          }
        }
        for (row = 0; row < moduleCount - 1; row++) {
          for (col = 0; col < moduleCount - 1; col++) {
            var count = 0;
            if (qrCode.isDark(row, col)) count++;
            if (qrCode.isDark(row + 1, col)) count++;
            if (qrCode.isDark(row, col + 1)) count++;
            if (qrCode.isDark(row + 1, col + 1)) count++;
            if (count === 0 || count === 4) {
              lostPoint += 3;
            }
          }
        }
        for (row = 0; row < moduleCount; row++) {
          for (col = 0; col < moduleCount - 6; col++) {
            if (qrCode.isDark(row, col) && !qrCode.isDark(row, col + 1) && qrCode.isDark(row, col + 2) && qrCode.isDark(row, col + 3) && qrCode.isDark(row, col + 4) && !qrCode.isDark(row, col + 5) && qrCode.isDark(row, col + 6)) {
              lostPoint += 40;
            }
          }
        }
        for (col = 0; col < moduleCount; col++) {
          for (row = 0; row < moduleCount - 6; row++) {
            if (qrCode.isDark(row, col) && !qrCode.isDark(row + 1, col) && qrCode.isDark(row + 2, col) && qrCode.isDark(row + 3, col) && qrCode.isDark(row + 4, col) && !qrCode.isDark(row + 5, col) && qrCode.isDark(row + 6, col)) {
              lostPoint += 40;
            }
          }
        }
        var darkCount = 0;
        for (col = 0; col < moduleCount; col++) {
          for (row = 0; row < moduleCount; row++) {
            if (qrCode.isDark(row, col)) {
              darkCount++;
            }
          }
        }
        var ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5;
        lostPoint += ratio * 10;
        return lostPoint;
      }, "getLostPoint")
    };
    module2.exports = QRUtil;
  }
});

// node_modules/qrcode-terminal/vendor/QRCode/QRErrorCorrectLevel.js
var require_QRErrorCorrectLevel = __commonJS({
  "node_modules/qrcode-terminal/vendor/QRCode/QRErrorCorrectLevel.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = {
      L: 1,
      M: 0,
      Q: 3,
      H: 2
    };
  }
});

// node_modules/qrcode-terminal/vendor/QRCode/QRRSBlock.js
var require_QRRSBlock = __commonJS({
  "node_modules/qrcode-terminal/vendor/QRCode/QRRSBlock.js"(exports2, module2) {
    init_esbuild_shims();
    var QRErrorCorrectLevel = require_QRErrorCorrectLevel();
    function QRRSBlock(totalCount, dataCount) {
      this.totalCount = totalCount;
      this.dataCount = dataCount;
    }
    __name(QRRSBlock, "QRRSBlock");
    QRRSBlock.RS_BLOCK_TABLE = [
      // L
      // M
      // Q
      // H
      // 1
      [1, 26, 19],
      [1, 26, 16],
      [1, 26, 13],
      [1, 26, 9],
      // 2
      [1, 44, 34],
      [1, 44, 28],
      [1, 44, 22],
      [1, 44, 16],
      // 3
      [1, 70, 55],
      [1, 70, 44],
      [2, 35, 17],
      [2, 35, 13],
      // 4		
      [1, 100, 80],
      [2, 50, 32],
      [2, 50, 24],
      [4, 25, 9],
      // 5
      [1, 134, 108],
      [2, 67, 43],
      [2, 33, 15, 2, 34, 16],
      [2, 33, 11, 2, 34, 12],
      // 6
      [2, 86, 68],
      [4, 43, 27],
      [4, 43, 19],
      [4, 43, 15],
      // 7		
      [2, 98, 78],
      [4, 49, 31],
      [2, 32, 14, 4, 33, 15],
      [4, 39, 13, 1, 40, 14],
      // 8
      [2, 121, 97],
      [2, 60, 38, 2, 61, 39],
      [4, 40, 18, 2, 41, 19],
      [4, 40, 14, 2, 41, 15],
      // 9
      [2, 146, 116],
      [3, 58, 36, 2, 59, 37],
      [4, 36, 16, 4, 37, 17],
      [4, 36, 12, 4, 37, 13],
      // 10		
      [2, 86, 68, 2, 87, 69],
      [4, 69, 43, 1, 70, 44],
      [6, 43, 19, 2, 44, 20],
      [6, 43, 15, 2, 44, 16],
      // 11
      [4, 101, 81],
      [1, 80, 50, 4, 81, 51],
      [4, 50, 22, 4, 51, 23],
      [3, 36, 12, 8, 37, 13],
      // 12
      [2, 116, 92, 2, 117, 93],
      [6, 58, 36, 2, 59, 37],
      [4, 46, 20, 6, 47, 21],
      [7, 42, 14, 4, 43, 15],
      // 13
      [4, 133, 107],
      [8, 59, 37, 1, 60, 38],
      [8, 44, 20, 4, 45, 21],
      [12, 33, 11, 4, 34, 12],
      // 14
      [3, 145, 115, 1, 146, 116],
      [4, 64, 40, 5, 65, 41],
      [11, 36, 16, 5, 37, 17],
      [11, 36, 12, 5, 37, 13],
      // 15
      [5, 109, 87, 1, 110, 88],
      [5, 65, 41, 5, 66, 42],
      [5, 54, 24, 7, 55, 25],
      [11, 36, 12],
      // 16
      [5, 122, 98, 1, 123, 99],
      [7, 73, 45, 3, 74, 46],
      [15, 43, 19, 2, 44, 20],
      [3, 45, 15, 13, 46, 16],
      // 17
      [1, 135, 107, 5, 136, 108],
      [10, 74, 46, 1, 75, 47],
      [1, 50, 22, 15, 51, 23],
      [2, 42, 14, 17, 43, 15],
      // 18
      [5, 150, 120, 1, 151, 121],
      [9, 69, 43, 4, 70, 44],
      [17, 50, 22, 1, 51, 23],
      [2, 42, 14, 19, 43, 15],
      // 19
      [3, 141, 113, 4, 142, 114],
      [3, 70, 44, 11, 71, 45],
      [17, 47, 21, 4, 48, 22],
      [9, 39, 13, 16, 40, 14],
      // 20
      [3, 135, 107, 5, 136, 108],
      [3, 67, 41, 13, 68, 42],
      [15, 54, 24, 5, 55, 25],
      [15, 43, 15, 10, 44, 16],
      // 21
      [4, 144, 116, 4, 145, 117],
      [17, 68, 42],
      [17, 50, 22, 6, 51, 23],
      [19, 46, 16, 6, 47, 17],
      // 22
      [2, 139, 111, 7, 140, 112],
      [17, 74, 46],
      [7, 54, 24, 16, 55, 25],
      [34, 37, 13],
      // 23
      [4, 151, 121, 5, 152, 122],
      [4, 75, 47, 14, 76, 48],
      [11, 54, 24, 14, 55, 25],
      [16, 45, 15, 14, 46, 16],
      // 24
      [6, 147, 117, 4, 148, 118],
      [6, 73, 45, 14, 74, 46],
      [11, 54, 24, 16, 55, 25],
      [30, 46, 16, 2, 47, 17],
      // 25
      [8, 132, 106, 4, 133, 107],
      [8, 75, 47, 13, 76, 48],
      [7, 54, 24, 22, 55, 25],
      [22, 45, 15, 13, 46, 16],
      // 26
      [10, 142, 114, 2, 143, 115],
      [19, 74, 46, 4, 75, 47],
      [28, 50, 22, 6, 51, 23],
      [33, 46, 16, 4, 47, 17],
      // 27
      [8, 152, 122, 4, 153, 123],
      [22, 73, 45, 3, 74, 46],
      [8, 53, 23, 26, 54, 24],
      [12, 45, 15, 28, 46, 16],
      // 28
      [3, 147, 117, 10, 148, 118],
      [3, 73, 45, 23, 74, 46],
      [4, 54, 24, 31, 55, 25],
      [11, 45, 15, 31, 46, 16],
      // 29
      [7, 146, 116, 7, 147, 117],
      [21, 73, 45, 7, 74, 46],
      [1, 53, 23, 37, 54, 24],
      [19, 45, 15, 26, 46, 16],
      // 30
      [5, 145, 115, 10, 146, 116],
      [19, 75, 47, 10, 76, 48],
      [15, 54, 24, 25, 55, 25],
      [23, 45, 15, 25, 46, 16],
      // 31
      [13, 145, 115, 3, 146, 116],
      [2, 74, 46, 29, 75, 47],
      [42, 54, 24, 1, 55, 25],
      [23, 45, 15, 28, 46, 16],
      // 32
      [17, 145, 115],
      [10, 74, 46, 23, 75, 47],
      [10, 54, 24, 35, 55, 25],
      [19, 45, 15, 35, 46, 16],
      // 33
      [17, 145, 115, 1, 146, 116],
      [14, 74, 46, 21, 75, 47],
      [29, 54, 24, 19, 55, 25],
      [11, 45, 15, 46, 46, 16],
      // 34
      [13, 145, 115, 6, 146, 116],
      [14, 74, 46, 23, 75, 47],
      [44, 54, 24, 7, 55, 25],
      [59, 46, 16, 1, 47, 17],
      // 35
      [12, 151, 121, 7, 152, 122],
      [12, 75, 47, 26, 76, 48],
      [39, 54, 24, 14, 55, 25],
      [22, 45, 15, 41, 46, 16],
      // 36
      [6, 151, 121, 14, 152, 122],
      [6, 75, 47, 34, 76, 48],
      [46, 54, 24, 10, 55, 25],
      [2, 45, 15, 64, 46, 16],
      // 37
      [17, 152, 122, 4, 153, 123],
      [29, 74, 46, 14, 75, 47],
      [49, 54, 24, 10, 55, 25],
      [24, 45, 15, 46, 46, 16],
      // 38
      [4, 152, 122, 18, 153, 123],
      [13, 74, 46, 32, 75, 47],
      [48, 54, 24, 14, 55, 25],
      [42, 45, 15, 32, 46, 16],
      // 39
      [20, 147, 117, 4, 148, 118],
      [40, 75, 47, 7, 76, 48],
      [43, 54, 24, 22, 55, 25],
      [10, 45, 15, 67, 46, 16],
      // 40
      [19, 148, 118, 6, 149, 119],
      [18, 75, 47, 31, 76, 48],
      [34, 54, 24, 34, 55, 25],
      [20, 45, 15, 61, 46, 16]
    ];
    QRRSBlock.getRSBlocks = function(typeNumber, errorCorrectLevel) {
      var rsBlock = QRRSBlock.getRsBlockTable(typeNumber, errorCorrectLevel);
      if (rsBlock === void 0) {
        throw new Error("bad rs block @ typeNumber:" + typeNumber + "/errorCorrectLevel:" + errorCorrectLevel);
      }
      var length = rsBlock.length / 3;
      var list3 = [];
      for (var i = 0; i < length; i++) {
        var count = rsBlock[i * 3 + 0];
        var totalCount = rsBlock[i * 3 + 1];
        var dataCount = rsBlock[i * 3 + 2];
        for (var j = 0; j < count; j++) {
          list3.push(new QRRSBlock(totalCount, dataCount));
        }
      }
      return list3;
    };
    QRRSBlock.getRsBlockTable = function(typeNumber, errorCorrectLevel) {
      switch (errorCorrectLevel) {
        case QRErrorCorrectLevel.L:
          return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 0];
        case QRErrorCorrectLevel.M:
          return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 1];
        case QRErrorCorrectLevel.Q:
          return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 2];
        case QRErrorCorrectLevel.H:
          return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 3];
        default:
          return void 0;
      }
    };
    module2.exports = QRRSBlock;
  }
});

// node_modules/qrcode-terminal/vendor/QRCode/QRBitBuffer.js
var require_QRBitBuffer = __commonJS({
  "node_modules/qrcode-terminal/vendor/QRCode/QRBitBuffer.js"(exports2, module2) {
    init_esbuild_shims();
    function QRBitBuffer() {
      this.buffer = [];
      this.length = 0;
    }
    __name(QRBitBuffer, "QRBitBuffer");
    QRBitBuffer.prototype = {
      get: /* @__PURE__ */ __name(function(index) {
        var bufIndex = Math.floor(index / 8);
        return (this.buffer[bufIndex] >>> 7 - index % 8 & 1) == 1;
      }, "get"),
      put: /* @__PURE__ */ __name(function(num, length) {
        for (var i = 0; i < length; i++) {
          this.putBit((num >>> length - i - 1 & 1) == 1);
        }
      }, "put"),
      getLengthInBits: /* @__PURE__ */ __name(function() {
        return this.length;
      }, "getLengthInBits"),
      putBit: /* @__PURE__ */ __name(function(bit) {
        var bufIndex = Math.floor(this.length / 8);
        if (this.buffer.length <= bufIndex) {
          this.buffer.push(0);
        }
        if (bit) {
          this.buffer[bufIndex] |= 128 >>> this.length % 8;
        }
        this.length++;
      }, "putBit")
    };
    module2.exports = QRBitBuffer;
  }
});

// node_modules/qrcode-terminal/vendor/QRCode/index.js
var require_QRCode = __commonJS({
  "node_modules/qrcode-terminal/vendor/QRCode/index.js"(exports2, module2) {
    init_esbuild_shims();
    var QR8bitByte = require_QR8bitByte();
    var QRUtil = require_QRUtil();
    var QRPolynomial = require_QRPolynomial();
    var QRRSBlock = require_QRRSBlock();
    var QRBitBuffer = require_QRBitBuffer();
    function QRCode(typeNumber, errorCorrectLevel) {
      this.typeNumber = typeNumber;
      this.errorCorrectLevel = errorCorrectLevel;
      this.modules = null;
      this.moduleCount = 0;
      this.dataCache = null;
      this.dataList = [];
    }
    __name(QRCode, "QRCode");
    QRCode.prototype = {
      addData: /* @__PURE__ */ __name(function(data) {
        var newData = new QR8bitByte(data);
        this.dataList.push(newData);
        this.dataCache = null;
      }, "addData"),
      isDark: /* @__PURE__ */ __name(function(row, col) {
        if (row < 0 || this.moduleCount <= row || col < 0 || this.moduleCount <= col) {
          throw new Error(row + "," + col);
        }
        return this.modules[row][col];
      }, "isDark"),
      getModuleCount: /* @__PURE__ */ __name(function() {
        return this.moduleCount;
      }, "getModuleCount"),
      make: /* @__PURE__ */ __name(function() {
        if (this.typeNumber < 1) {
          var typeNumber = 1;
          for (typeNumber = 1; typeNumber < 40; typeNumber++) {
            var rsBlocks = QRRSBlock.getRSBlocks(typeNumber, this.errorCorrectLevel);
            var buffer = new QRBitBuffer();
            var totalDataCount = 0;
            for (var i = 0; i < rsBlocks.length; i++) {
              totalDataCount += rsBlocks[i].dataCount;
            }
            for (var x = 0; x < this.dataList.length; x++) {
              var data = this.dataList[x];
              buffer.put(data.mode, 4);
              buffer.put(data.getLength(), QRUtil.getLengthInBits(data.mode, typeNumber));
              data.write(buffer);
            }
            if (buffer.getLengthInBits() <= totalDataCount * 8)
              break;
          }
          this.typeNumber = typeNumber;
        }
        this.makeImpl(false, this.getBestMaskPattern());
      }, "make"),
      makeImpl: /* @__PURE__ */ __name(function(test, maskPattern) {
        this.moduleCount = this.typeNumber * 4 + 17;
        this.modules = new Array(this.moduleCount);
        for (var row = 0; row < this.moduleCount; row++) {
          this.modules[row] = new Array(this.moduleCount);
          for (var col = 0; col < this.moduleCount; col++) {
            this.modules[row][col] = null;
          }
        }
        this.setupPositionProbePattern(0, 0);
        this.setupPositionProbePattern(this.moduleCount - 7, 0);
        this.setupPositionProbePattern(0, this.moduleCount - 7);
        this.setupPositionAdjustPattern();
        this.setupTimingPattern();
        this.setupTypeInfo(test, maskPattern);
        if (this.typeNumber >= 7) {
          this.setupTypeNumber(test);
        }
        if (this.dataCache === null) {
          this.dataCache = QRCode.createData(this.typeNumber, this.errorCorrectLevel, this.dataList);
        }
        this.mapData(this.dataCache, maskPattern);
      }, "makeImpl"),
      setupPositionProbePattern: /* @__PURE__ */ __name(function(row, col) {
        for (var r3 = -1; r3 <= 7; r3++) {
          if (row + r3 <= -1 || this.moduleCount <= row + r3) continue;
          for (var c3 = -1; c3 <= 7; c3++) {
            if (col + c3 <= -1 || this.moduleCount <= col + c3) continue;
            if (0 <= r3 && r3 <= 6 && (c3 === 0 || c3 === 6) || 0 <= c3 && c3 <= 6 && (r3 === 0 || r3 === 6) || 2 <= r3 && r3 <= 4 && 2 <= c3 && c3 <= 4) {
              this.modules[row + r3][col + c3] = true;
            } else {
              this.modules[row + r3][col + c3] = false;
            }
          }
        }
      }, "setupPositionProbePattern"),
      getBestMaskPattern: /* @__PURE__ */ __name(function() {
        var minLostPoint = 0;
        var pattern = 0;
        for (var i = 0; i < 8; i++) {
          this.makeImpl(true, i);
          var lostPoint = QRUtil.getLostPoint(this);
          if (i === 0 || minLostPoint > lostPoint) {
            minLostPoint = lostPoint;
            pattern = i;
          }
        }
        return pattern;
      }, "getBestMaskPattern"),
      createMovieClip: /* @__PURE__ */ __name(function(target_mc, instance_name, depth) {
        var qr_mc = target_mc.createEmptyMovieClip(instance_name, depth);
        var cs = 1;
        this.make();
        for (var row = 0; row < this.modules.length; row++) {
          var y = row * cs;
          for (var col = 0; col < this.modules[row].length; col++) {
            var x = col * cs;
            var dark = this.modules[row][col];
            if (dark) {
              qr_mc.beginFill(0, 100);
              qr_mc.moveTo(x, y);
              qr_mc.lineTo(x + cs, y);
              qr_mc.lineTo(x + cs, y + cs);
              qr_mc.lineTo(x, y + cs);
              qr_mc.endFill();
            }
          }
        }
        return qr_mc;
      }, "createMovieClip"),
      setupTimingPattern: /* @__PURE__ */ __name(function() {
        for (var r3 = 8; r3 < this.moduleCount - 8; r3++) {
          if (this.modules[r3][6] !== null) {
            continue;
          }
          this.modules[r3][6] = r3 % 2 === 0;
        }
        for (var c3 = 8; c3 < this.moduleCount - 8; c3++) {
          if (this.modules[6][c3] !== null) {
            continue;
          }
          this.modules[6][c3] = c3 % 2 === 0;
        }
      }, "setupTimingPattern"),
      setupPositionAdjustPattern: /* @__PURE__ */ __name(function() {
        var pos2 = QRUtil.getPatternPosition(this.typeNumber);
        for (var i = 0; i < pos2.length; i++) {
          for (var j = 0; j < pos2.length; j++) {
            var row = pos2[i];
            var col = pos2[j];
            if (this.modules[row][col] !== null) {
              continue;
            }
            for (var r3 = -2; r3 <= 2; r3++) {
              for (var c3 = -2; c3 <= 2; c3++) {
                if (Math.abs(r3) === 2 || Math.abs(c3) === 2 || r3 === 0 && c3 === 0) {
                  this.modules[row + r3][col + c3] = true;
                } else {
                  this.modules[row + r3][col + c3] = false;
                }
              }
            }
          }
        }
      }, "setupPositionAdjustPattern"),
      setupTypeNumber: /* @__PURE__ */ __name(function(test) {
        var bits = QRUtil.getBCHTypeNumber(this.typeNumber);
        var mod2;
        for (var i = 0; i < 18; i++) {
          mod2 = !test && (bits >> i & 1) === 1;
          this.modules[Math.floor(i / 3)][i % 3 + this.moduleCount - 8 - 3] = mod2;
        }
        for (var x = 0; x < 18; x++) {
          mod2 = !test && (bits >> x & 1) === 1;
          this.modules[x % 3 + this.moduleCount - 8 - 3][Math.floor(x / 3)] = mod2;
        }
      }, "setupTypeNumber"),
      setupTypeInfo: /* @__PURE__ */ __name(function(test, maskPattern) {
        var data = this.errorCorrectLevel << 3 | maskPattern;
        var bits = QRUtil.getBCHTypeInfo(data);
        var mod2;
        for (var v = 0; v < 15; v++) {
          mod2 = !test && (bits >> v & 1) === 1;
          if (v < 6) {
            this.modules[v][8] = mod2;
          } else if (v < 8) {
            this.modules[v + 1][8] = mod2;
          } else {
            this.modules[this.moduleCount - 15 + v][8] = mod2;
          }
        }
        for (var h = 0; h < 15; h++) {
          mod2 = !test && (bits >> h & 1) === 1;
          if (h < 8) {
            this.modules[8][this.moduleCount - h - 1] = mod2;
          } else if (h < 9) {
            this.modules[8][15 - h - 1 + 1] = mod2;
          } else {
            this.modules[8][15 - h - 1] = mod2;
          }
        }
        this.modules[this.moduleCount - 8][8] = !test;
      }, "setupTypeInfo"),
      mapData: /* @__PURE__ */ __name(function(data, maskPattern) {
        var inc = -1;
        var row = this.moduleCount - 1;
        var bitIndex = 7;
        var byteIndex = 0;
        for (var col = this.moduleCount - 1; col > 0; col -= 2) {
          if (col === 6) col--;
          while (true) {
            for (var c3 = 0; c3 < 2; c3++) {
              if (this.modules[row][col - c3] === null) {
                var dark = false;
                if (byteIndex < data.length) {
                  dark = (data[byteIndex] >>> bitIndex & 1) === 1;
                }
                var mask = QRUtil.getMask(maskPattern, row, col - c3);
                if (mask) {
                  dark = !dark;
                }
                this.modules[row][col - c3] = dark;
                bitIndex--;
                if (bitIndex === -1) {
                  byteIndex++;
                  bitIndex = 7;
                }
              }
            }
            row += inc;
            if (row < 0 || this.moduleCount <= row) {
              row -= inc;
              inc = -inc;
              break;
            }
          }
        }
      }, "mapData")
    };
    QRCode.PAD0 = 236;
    QRCode.PAD1 = 17;
    QRCode.createData = function(typeNumber, errorCorrectLevel, dataList) {
      var rsBlocks = QRRSBlock.getRSBlocks(typeNumber, errorCorrectLevel);
      var buffer = new QRBitBuffer();
      for (var i = 0; i < dataList.length; i++) {
        var data = dataList[i];
        buffer.put(data.mode, 4);
        buffer.put(data.getLength(), QRUtil.getLengthInBits(data.mode, typeNumber));
        data.write(buffer);
      }
      var totalDataCount = 0;
      for (var x = 0; x < rsBlocks.length; x++) {
        totalDataCount += rsBlocks[x].dataCount;
      }
      if (buffer.getLengthInBits() > totalDataCount * 8) {
        throw new Error("code length overflow. (" + buffer.getLengthInBits() + ">" + totalDataCount * 8 + ")");
      }
      if (buffer.getLengthInBits() + 4 <= totalDataCount * 8) {
        buffer.put(0, 4);
      }
      while (buffer.getLengthInBits() % 8 !== 0) {
        buffer.putBit(false);
      }
      while (true) {
        if (buffer.getLengthInBits() >= totalDataCount * 8) {
          break;
        }
        buffer.put(QRCode.PAD0, 8);
        if (buffer.getLengthInBits() >= totalDataCount * 8) {
          break;
        }
        buffer.put(QRCode.PAD1, 8);
      }
      return QRCode.createBytes(buffer, rsBlocks);
    };
    QRCode.createBytes = function(buffer, rsBlocks) {
      var offset = 0;
      var maxDcCount = 0;
      var maxEcCount = 0;
      var dcdata = new Array(rsBlocks.length);
      var ecdata = new Array(rsBlocks.length);
      for (var r3 = 0; r3 < rsBlocks.length; r3++) {
        var dcCount = rsBlocks[r3].dataCount;
        var ecCount = rsBlocks[r3].totalCount - dcCount;
        maxDcCount = Math.max(maxDcCount, dcCount);
        maxEcCount = Math.max(maxEcCount, ecCount);
        dcdata[r3] = new Array(dcCount);
        for (var i = 0; i < dcdata[r3].length; i++) {
          dcdata[r3][i] = 255 & buffer.buffer[i + offset];
        }
        offset += dcCount;
        var rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount);
        var rawPoly = new QRPolynomial(dcdata[r3], rsPoly.getLength() - 1);
        var modPoly = rawPoly.mod(rsPoly);
        ecdata[r3] = new Array(rsPoly.getLength() - 1);
        for (var x = 0; x < ecdata[r3].length; x++) {
          var modIndex = x + modPoly.getLength() - ecdata[r3].length;
          ecdata[r3][x] = modIndex >= 0 ? modPoly.get(modIndex) : 0;
        }
      }
      var totalCodeCount = 0;
      for (var y = 0; y < rsBlocks.length; y++) {
        totalCodeCount += rsBlocks[y].totalCount;
      }
      var data = new Array(totalCodeCount);
      var index = 0;
      for (var z = 0; z < maxDcCount; z++) {
        for (var s2 = 0; s2 < rsBlocks.length; s2++) {
          if (z < dcdata[s2].length) {
            data[index++] = dcdata[s2][z];
          }
        }
      }
      for (var xx = 0; xx < maxEcCount; xx++) {
        for (var t2 = 0; t2 < rsBlocks.length; t2++) {
          if (xx < ecdata[t2].length) {
            data[index++] = ecdata[t2][xx];
          }
        }
      }
      return data;
    };
    module2.exports = QRCode;
  }
});

// node_modules/qrcode-terminal/lib/main.js
var require_main2 = __commonJS({
  "node_modules/qrcode-terminal/lib/main.js"(exports2, module2) {
    init_esbuild_shims();
    var QRCode = require_QRCode();
    var QRErrorCorrectLevel = require_QRErrorCorrectLevel();
    var black = "\x1B[40m  \x1B[0m";
    var white = "\x1B[47m  \x1B[0m";
    var toCell = /* @__PURE__ */ __name(function(isBlack) {
      return isBlack ? black : white;
    }, "toCell");
    var repeat = /* @__PURE__ */ __name(function(color) {
      return {
        times: /* @__PURE__ */ __name(function(count) {
          return new Array(count).join(color);
        }, "times")
      };
    }, "repeat");
    var fill = /* @__PURE__ */ __name(function(length, value) {
      var arr = new Array(length);
      for (var i = 0; i < length; i++) {
        arr[i] = value;
      }
      return arr;
    }, "fill");
    module2.exports = {
      error: QRErrorCorrectLevel.L,
      generate: /* @__PURE__ */ __name(function(input, opts, cb) {
        if (typeof opts === "function") {
          cb = opts;
          opts = {};
        }
        var qrcode2 = new QRCode(-1, this.error);
        qrcode2.addData(input);
        qrcode2.make();
        var output = "";
        if (opts && opts.small) {
          var BLACK = true, WHITE = false;
          var moduleCount = qrcode2.getModuleCount();
          var moduleData = qrcode2.modules.slice();
          var oddRow = moduleCount % 2 === 1;
          if (oddRow) {
            moduleData.push(fill(moduleCount, WHITE));
          }
          var platte = {
            WHITE_ALL: "\u2588",
            WHITE_BLACK: "\u2580",
            BLACK_WHITE: "\u2584",
            BLACK_ALL: " "
          };
          var borderTop = repeat(platte.BLACK_WHITE).times(moduleCount + 3);
          var borderBottom = repeat(platte.WHITE_BLACK).times(moduleCount + 3);
          output += borderTop + "\n";
          for (var row = 0; row < moduleCount; row += 2) {
            output += platte.WHITE_ALL;
            for (var col = 0; col < moduleCount; col++) {
              if (moduleData[row][col] === WHITE && moduleData[row + 1][col] === WHITE) {
                output += platte.WHITE_ALL;
              } else if (moduleData[row][col] === WHITE && moduleData[row + 1][col] === BLACK) {
                output += platte.WHITE_BLACK;
              } else if (moduleData[row][col] === BLACK && moduleData[row + 1][col] === WHITE) {
                output += platte.BLACK_WHITE;
              } else {
                output += platte.BLACK_ALL;
              }
            }
            output += platte.WHITE_ALL + "\n";
          }
          if (!oddRow) {
            output += borderBottom;
          }
        } else {
          var border = repeat(white).times(qrcode2.getModuleCount() + 3);
          output += border + "\n";
          qrcode2.modules.forEach(function(row2) {
            output += white;
            output += row2.map(toCell).join("");
            output += white + "\n";
          });
          output += border;
        }
        if (cb) cb(output);
        else console.log(output);
      }, "generate"),
      setErrorLevel: /* @__PURE__ */ __name(function(error) {
        this.error = QRErrorCorrectLevel[error] || this.error;
      }, "setErrorLevel")
    };
  }
});

// node_modules/picocolors/picocolors.js
var require_picocolors = __commonJS({
  "node_modules/picocolors/picocolors.js"(exports2, module2) {
    init_esbuild_shims();
    var p = process || {};
    var argv = p.argv || [];
    var env7 = p.env || {};
    var isColorSupported = !(!!env7.NO_COLOR || argv.includes("--no-color")) && (!!env7.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env7.TERM !== "dumb" || !!env7.CI);
    var formatter = /* @__PURE__ */ __name((open3, close, replace2 = open3) => (input) => {
      let string = "" + input, index = string.indexOf(close, open3.length);
      return ~index ? open3 + replaceClose(string, close, replace2, index) + close : open3 + string + close;
    }, "formatter");
    var replaceClose = /* @__PURE__ */ __name((string, close, replace2, index) => {
      let result = "", cursor = 0;
      do {
        result += string.substring(cursor, index) + replace2;
        cursor = index + close.length;
        index = string.indexOf(close, cursor);
      } while (~index);
      return result + string.substring(cursor);
    }, "replaceClose");
    var createColors = /* @__PURE__ */ __name((enabled = isColorSupported) => {
      let f = enabled ? formatter : () => String;
      return {
        isColorSupported: enabled,
        reset: f("\x1B[0m", "\x1B[0m"),
        bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
        dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
        italic: f("\x1B[3m", "\x1B[23m"),
        underline: f("\x1B[4m", "\x1B[24m"),
        inverse: f("\x1B[7m", "\x1B[27m"),
        hidden: f("\x1B[8m", "\x1B[28m"),
        strikethrough: f("\x1B[9m", "\x1B[29m"),
        black: f("\x1B[30m", "\x1B[39m"),
        red: f("\x1B[31m", "\x1B[39m"),
        green: f("\x1B[32m", "\x1B[39m"),
        yellow: f("\x1B[33m", "\x1B[39m"),
        blue: f("\x1B[34m", "\x1B[39m"),
        magenta: f("\x1B[35m", "\x1B[39m"),
        cyan: f("\x1B[36m", "\x1B[39m"),
        white: f("\x1B[37m", "\x1B[39m"),
        gray: f("\x1B[90m", "\x1B[39m"),
        bgBlack: f("\x1B[40m", "\x1B[49m"),
        bgRed: f("\x1B[41m", "\x1B[49m"),
        bgGreen: f("\x1B[42m", "\x1B[49m"),
        bgYellow: f("\x1B[43m", "\x1B[49m"),
        bgBlue: f("\x1B[44m", "\x1B[49m"),
        bgMagenta: f("\x1B[45m", "\x1B[49m"),
        bgCyan: f("\x1B[46m", "\x1B[49m"),
        bgWhite: f("\x1B[47m", "\x1B[49m"),
        blackBright: f("\x1B[90m", "\x1B[39m"),
        redBright: f("\x1B[91m", "\x1B[39m"),
        greenBright: f("\x1B[92m", "\x1B[39m"),
        yellowBright: f("\x1B[93m", "\x1B[39m"),
        blueBright: f("\x1B[94m", "\x1B[39m"),
        magentaBright: f("\x1B[95m", "\x1B[39m"),
        cyanBright: f("\x1B[96m", "\x1B[39m"),
        whiteBright: f("\x1B[97m", "\x1B[39m"),
        bgBlackBright: f("\x1B[100m", "\x1B[49m"),
        bgRedBright: f("\x1B[101m", "\x1B[49m"),
        bgGreenBright: f("\x1B[102m", "\x1B[49m"),
        bgYellowBright: f("\x1B[103m", "\x1B[49m"),
        bgBlueBright: f("\x1B[104m", "\x1B[49m"),
        bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
        bgCyanBright: f("\x1B[106m", "\x1B[49m"),
        bgWhiteBright: f("\x1B[107m", "\x1B[49m")
      };
    }, "createColors");
    module2.exports = createColors();
    module2.exports.createColors = createColors;
  }
});

// node_modules/@babel/code-frame/node_modules/js-tokens/index.js
var require_js_tokens = __commonJS({
  "node_modules/@babel/code-frame/node_modules/js-tokens/index.js"(exports2) {
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g;
    exports2.matchToToken = function(match2) {
      var token2 = { type: "invalid", value: match2[0], closed: void 0 };
      if (match2[1]) token2.type = "string", token2.closed = !!(match2[3] || match2[4]);
      else if (match2[5]) token2.type = "comment";
      else if (match2[6]) token2.type = "comment", token2.closed = !!match2[7];
      else if (match2[8]) token2.type = "regex";
      else if (match2[9]) token2.type = "number";
      else if (match2[10]) token2.type = "name";
      else if (match2[11]) token2.type = "punctuator";
      else if (match2[12]) token2.type = "whitespace";
      return token2;
    };
  }
});

// node_modules/@babel/helper-validator-identifier/lib/identifier.js
var require_identifier = __commonJS({
  "node_modules/@babel/helper-validator-identifier/lib/identifier.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.isIdentifierChar = isIdentifierChar;
    exports2.isIdentifierName = isIdentifierName;
    exports2.isIdentifierStart = isIdentifierStart;
    var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC";
    var nonASCIIidentifierChars = "\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ACE\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65";
    var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
    var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
    nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
    var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 2, 60, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 42, 9, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 496, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191];
    var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 80, 3, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 343, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 726, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
    function isInAstralSet(code2, set) {
      let pos2 = 65536;
      for (let i = 0, length = set.length; i < length; i += 2) {
        pos2 += set[i];
        if (pos2 > code2) return false;
        pos2 += set[i + 1];
        if (pos2 >= code2) return true;
      }
      return false;
    }
    __name(isInAstralSet, "isInAstralSet");
    function isIdentifierStart(code2) {
      if (code2 < 65) return code2 === 36;
      if (code2 <= 90) return true;
      if (code2 < 97) return code2 === 95;
      if (code2 <= 122) return true;
      if (code2 <= 65535) {
        return code2 >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code2));
      }
      return isInAstralSet(code2, astralIdentifierStartCodes);
    }
    __name(isIdentifierStart, "isIdentifierStart");
    function isIdentifierChar(code2) {
      if (code2 < 48) return code2 === 36;
      if (code2 < 58) return true;
      if (code2 < 65) return false;
      if (code2 <= 90) return true;
      if (code2 < 97) return code2 === 95;
      if (code2 <= 122) return true;
      if (code2 <= 65535) {
        return code2 >= 170 && nonASCIIidentifier.test(String.fromCharCode(code2));
      }
      return isInAstralSet(code2, astralIdentifierStartCodes) || isInAstralSet(code2, astralIdentifierCodes);
    }
    __name(isIdentifierChar, "isIdentifierChar");
    function isIdentifierName(name3) {
      let isFirst = true;
      for (let i = 0; i < name3.length; i++) {
        let cp2 = name3.charCodeAt(i);
        if ((cp2 & 64512) === 55296 && i + 1 < name3.length) {
          const trail = name3.charCodeAt(++i);
          if ((trail & 64512) === 56320) {
            cp2 = 65536 + ((cp2 & 1023) << 10) + (trail & 1023);
          }
        }
        if (isFirst) {
          isFirst = false;
          if (!isIdentifierStart(cp2)) {
            return false;
          }
        } else if (!isIdentifierChar(cp2)) {
          return false;
        }
      }
      return !isFirst;
    }
    __name(isIdentifierName, "isIdentifierName");
  }
});

// node_modules/@babel/helper-validator-identifier/lib/keyword.js
var require_keyword4 = __commonJS({
  "node_modules/@babel/helper-validator-identifier/lib/keyword.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    exports2.isKeyword = isKeyword;
    exports2.isReservedWord = isReservedWord;
    exports2.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord;
    exports2.isStrictBindReservedWord = isStrictBindReservedWord;
    exports2.isStrictReservedWord = isStrictReservedWord;
    var reservedWords = {
      keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
      strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
      strictBind: ["eval", "arguments"]
    };
    var keywords2 = new Set(reservedWords.keyword);
    var reservedWordsStrictSet = new Set(reservedWords.strict);
    var reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
    function isReservedWord(word, inModule) {
      return inModule && word === "await" || word === "enum";
    }
    __name(isReservedWord, "isReservedWord");
    function isStrictReservedWord(word, inModule) {
      return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
    }
    __name(isStrictReservedWord, "isStrictReservedWord");
    function isStrictBindOnlyReservedWord(word) {
      return reservedWordsStrictBindSet.has(word);
    }
    __name(isStrictBindOnlyReservedWord, "isStrictBindOnlyReservedWord");
    function isStrictBindReservedWord(word, inModule) {
      return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
    }
    __name(isStrictBindReservedWord, "isStrictBindReservedWord");
    function isKeyword(word) {
      return keywords2.has(word);
    }
    __name(isKeyword, "isKeyword");
  }
});

// node_modules/@babel/helper-validator-identifier/lib/index.js
var require_lib4 = __commonJS({
  "node_modules/@babel/helper-validator-identifier/lib/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    Object.defineProperty(exports2, "isIdentifierChar", {
      enumerable: true,
      get: /* @__PURE__ */ __name(function() {
        return _identifier.isIdentifierChar;
      }, "get")
    });
    Object.defineProperty(exports2, "isIdentifierName", {
      enumerable: true,
      get: /* @__PURE__ */ __name(function() {
        return _identifier.isIdentifierName;
      }, "get")
    });
    Object.defineProperty(exports2, "isIdentifierStart", {
      enumerable: true,
      get: /* @__PURE__ */ __name(function() {
        return _identifier.isIdentifierStart;
      }, "get")
    });
    Object.defineProperty(exports2, "isKeyword", {
      enumerable: true,
      get: /* @__PURE__ */ __name(function() {
        return _keyword.isKeyword;
      }, "get")
    });
    Object.defineProperty(exports2, "isReservedWord", {
      enumerable: true,
      get: /* @__PURE__ */ __name(function() {
        return _keyword.isReservedWord;
      }, "get")
    });
    Object.defineProperty(exports2, "isStrictBindOnlyReservedWord", {
      enumerable: true,
      get: /* @__PURE__ */ __name(function() {
        return _keyword.isStrictBindOnlyReservedWord;
      }, "get")
    });
    Object.defineProperty(exports2, "isStrictBindReservedWord", {
      enumerable: true,
      get: /* @__PURE__ */ __name(function() {
        return _keyword.isStrictBindReservedWord;
      }, "get")
    });
    Object.defineProperty(exports2, "isStrictReservedWord", {
      enumerable: true,
      get: /* @__PURE__ */ __name(function() {
        return _keyword.isStrictReservedWord;
      }, "get")
    });
    var _identifier = require_identifier();
    var _keyword = require_keyword4();
  }
});

// node_modules/@babel/code-frame/lib/index.js
var require_lib5 = __commonJS({
  "node_modules/@babel/code-frame/lib/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var picocolors = require_picocolors();
    var jsTokens = require_js_tokens();
    var helperValidatorIdentifier = require_lib4();
    function isColorSupported() {
      return typeof process === "object" && (process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false") ? false : picocolors.isColorSupported;
    }
    __name(isColorSupported, "isColorSupported");
    var compose = /* @__PURE__ */ __name((f, g) => (v) => f(g(v)), "compose");
    function buildDefs(colors) {
      return {
        keyword: colors.cyan,
        capitalized: colors.yellow,
        jsxIdentifier: colors.yellow,
        punctuator: colors.yellow,
        number: colors.magenta,
        string: colors.green,
        regex: colors.magenta,
        comment: colors.gray,
        invalid: compose(compose(colors.white, colors.bgRed), colors.bold),
        gutter: colors.gray,
        marker: compose(colors.red, colors.bold),
        message: compose(colors.red, colors.bold),
        reset: colors.reset
      };
    }
    __name(buildDefs, "buildDefs");
    var defsOn = buildDefs(picocolors.createColors(true));
    var defsOff = buildDefs(picocolors.createColors(false));
    function getDefs(enabled) {
      return enabled ? defsOn : defsOff;
    }
    __name(getDefs, "getDefs");
    var sometimesKeywords = /* @__PURE__ */ new Set(["as", "async", "from", "get", "of", "set"]);
    var NEWLINE$1 = /\r\n|[\n\r\u2028\u2029]/;
    var BRACKET = /^[()[\]{}]$/;
    var tokenize4;
    {
      const JSX_TAG = /^[a-z][\w-]*$/i;
      const getTokenType = /* @__PURE__ */ __name(function(token2, offset, text) {
        if (token2.type === "name") {
          if (helperValidatorIdentifier.isKeyword(token2.value) || helperValidatorIdentifier.isStrictReservedWord(token2.value, true) || sometimesKeywords.has(token2.value)) {
            return "keyword";
          }
          if (JSX_TAG.test(token2.value) && (text[offset - 1] === "<" || text.slice(offset - 2, offset) === "</")) {
            return "jsxIdentifier";
          }
          if (token2.value[0] !== token2.value[0].toLowerCase()) {
            return "capitalized";
          }
        }
        if (token2.type === "punctuator" && BRACKET.test(token2.value)) {
          return "bracket";
        }
        if (token2.type === "invalid" && (token2.value === "@" || token2.value === "#")) {
          return "punctuator";
        }
        return token2.type;
      }, "getTokenType");
      tokenize4 = /* @__PURE__ */ __name(function* (text) {
        let match2;
        while (match2 = jsTokens.default.exec(text)) {
          const token2 = jsTokens.matchToToken(match2);
          yield {
            type: getTokenType(token2, match2.index, text),
            value: token2.value
          };
        }
      }, "tokenize");
    }
    function highlight(text) {
      if (text === "") return "";
      const defs = getDefs(true);
      let highlighted = "";
      for (const {
        type,
        value
      } of tokenize4(text)) {
        if (type in defs) {
          highlighted += value.split(NEWLINE$1).map((str2) => defs[type](str2)).join("\n");
        } else {
          highlighted += value;
        }
      }
      return highlighted;
    }
    __name(highlight, "highlight");
    var deprecationWarningShown = false;
    var NEWLINE2 = /\r\n|[\n\r\u2028\u2029]/;
    function getMarkerLines(loc, source2, opts) {
      const startLoc = Object.assign({
        column: 0,
        line: -1
      }, loc.start);
      const endLoc = Object.assign({}, startLoc, loc.end);
      const {
        linesAbove = 2,
        linesBelow = 3
      } = opts || {};
      const startLine = startLoc.line;
      const startColumn = startLoc.column;
      const endLine = endLoc.line;
      const endColumn = endLoc.column;
      let start = Math.max(startLine - (linesAbove + 1), 0);
      let end = Math.min(source2.length, endLine + linesBelow);
      if (startLine === -1) {
        start = 0;
      }
      if (endLine === -1) {
        end = source2.length;
      }
      const lineDiff2 = endLine - startLine;
      const markerLines = {};
      if (lineDiff2) {
        for (let i = 0; i <= lineDiff2; i++) {
          const lineNumber = i + startLine;
          if (!startColumn) {
            markerLines[lineNumber] = true;
          } else if (i === 0) {
            const sourceLength = source2[lineNumber - 1].length;
            markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
          } else if (i === lineDiff2) {
            markerLines[lineNumber] = [0, endColumn];
          } else {
            const sourceLength = source2[lineNumber - i].length;
            markerLines[lineNumber] = [0, sourceLength];
          }
        }
      } else {
        if (startColumn === endColumn) {
          if (startColumn) {
            markerLines[startLine] = [startColumn, 0];
          } else {
            markerLines[startLine] = true;
          }
        } else {
          markerLines[startLine] = [startColumn, endColumn - startColumn];
        }
      }
      return {
        start,
        end,
        markerLines
      };
    }
    __name(getMarkerLines, "getMarkerLines");
    function codeFrameColumns2(rawLines, loc, opts = {}) {
      const shouldHighlight = opts.forceColor || isColorSupported() && opts.highlightCode;
      const defs = getDefs(shouldHighlight);
      const lines = rawLines.split(NEWLINE2);
      const {
        start,
        end,
        markerLines
      } = getMarkerLines(loc, lines, opts);
      const hasColumns = loc.start && typeof loc.start.column === "number";
      const numberMaxWidth = String(end).length;
      const highlightedLines = shouldHighlight ? highlight(rawLines) : rawLines;
      let frame = highlightedLines.split(NEWLINE2, end).slice(start, end).map((line, index2) => {
        const number = start + 1 + index2;
        const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
        const gutter = ` ${paddedNumber} |`;
        const hasMarker = markerLines[number];
        const lastMarkerLine = !markerLines[number + 1];
        if (hasMarker) {
          let markerLine = "";
          if (Array.isArray(hasMarker)) {
            const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
            const numberOfMarkers = hasMarker[1] || 1;
            markerLine = ["\n ", defs.gutter(gutter.replace(/\d/g, " ")), " ", markerSpacing, defs.marker("^").repeat(numberOfMarkers)].join("");
            if (lastMarkerLine && opts.message) {
              markerLine += " " + defs.message(opts.message);
            }
          }
          return [defs.marker(">"), defs.gutter(gutter), line.length > 0 ? ` ${line}` : "", markerLine].join("");
        } else {
          return ` ${defs.gutter(gutter)}${line.length > 0 ? ` ${line}` : ""}`;
        }
      }).join("\n");
      if (opts.message && !hasColumns) {
        frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}
${frame}`;
      }
      if (shouldHighlight) {
        return defs.reset(frame);
      } else {
        return frame;
      }
    }
    __name(codeFrameColumns2, "codeFrameColumns");
    function index(rawLines, lineNumber, colNumber, opts = {}) {
      if (!deprecationWarningShown) {
        deprecationWarningShown = true;
        const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
        if (process.emitWarning) {
          process.emitWarning(message, "DeprecationWarning");
        } else {
          const deprecationError = new Error(message);
          deprecationError.name = "DeprecationWarning";
          console.warn(new Error(message));
        }
      }
      colNumber = Math.max(colNumber, 0);
      const location = {
        start: {
          column: colNumber,
          line: lineNumber
        }
      };
      return codeFrameColumns2(rawLines, location, opts);
    }
    __name(index, "index");
    exports2.codeFrameColumns = codeFrameColumns2;
    exports2.default = index;
    exports2.highlight = highlight;
  }
});

// node_modules/semver/internal/debug.js
var require_debug = __commonJS({
  "node_modules/semver/internal/debug.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var debug2 = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {
    };
    module2.exports = debug2;
  }
});

// node_modules/semver/internal/constants.js
var require_constants12 = __commonJS({
  "node_modules/semver/internal/constants.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var SEMVER_SPEC_VERSION = "2.0.0";
    var MAX_LENGTH = 256;
    var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */
    9007199254740991;
    var MAX_SAFE_COMPONENT_LENGTH = 16;
    var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
    var RELEASE_TYPES = [
      "major",
      "premajor",
      "minor",
      "preminor",
      "patch",
      "prepatch",
      "prerelease"
    ];
    module2.exports = {
      MAX_LENGTH,
      MAX_SAFE_COMPONENT_LENGTH,
      MAX_SAFE_BUILD_LENGTH,
      MAX_SAFE_INTEGER,
      RELEASE_TYPES,
      SEMVER_SPEC_VERSION,
      FLAG_INCLUDE_PRERELEASE: 1,
      FLAG_LOOSE: 2
    };
  }
});

// node_modules/semver/internal/re.js
var require_re = __commonJS({
  "node_modules/semver/internal/re.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var {
      MAX_SAFE_COMPONENT_LENGTH,
      MAX_SAFE_BUILD_LENGTH,
      MAX_LENGTH
    } = require_constants12();
    var debug2 = require_debug();
    exports2 = module2.exports = {};
    var re2 = exports2.re = [];
    var safeRe = exports2.safeRe = [];
    var src = exports2.src = [];
    var safeSrc = exports2.safeSrc = [];
    var t2 = exports2.t = {};
    var R = 0;
    var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
    var safeRegexReplacements = [
      ["\\s", 1],
      ["\\d", MAX_LENGTH],
      [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
    ];
    var makeSafeRegex = /* @__PURE__ */ __name((value) => {
      for (const [token2, max] of safeRegexReplacements) {
        value = value.split(`${token2}*`).join(`${token2}{0,${max}}`).split(`${token2}+`).join(`${token2}{1,${max}}`);
      }
      return value;
    }, "makeSafeRegex");
    var createToken = /* @__PURE__ */ __name((name3, value, isGlobal) => {
      const safe = makeSafeRegex(value);
      const index = R++;
      debug2(name3, index, value);
      t2[name3] = index;
      src[index] = value;
      safeSrc[index] = safe;
      re2[index] = new RegExp(value, isGlobal ? "g" : void 0);
      safeRe[index] = new RegExp(safe, isGlobal ? "g" : void 0);
    }, "createToken");
    createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
    createToken("NUMERICIDENTIFIERLOOSE", "\\d+");
    createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
    createToken("MAINVERSION", `(${src[t2.NUMERICIDENTIFIER]})\\.(${src[t2.NUMERICIDENTIFIER]})\\.(${src[t2.NUMERICIDENTIFIER]})`);
    createToken("MAINVERSIONLOOSE", `(${src[t2.NUMERICIDENTIFIERLOOSE]})\\.(${src[t2.NUMERICIDENTIFIERLOOSE]})\\.(${src[t2.NUMERICIDENTIFIERLOOSE]})`);
    createToken("PRERELEASEIDENTIFIER", `(?:${src[t2.NONNUMERICIDENTIFIER]}|${src[t2.NUMERICIDENTIFIER]})`);
    createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t2.NONNUMERICIDENTIFIER]}|${src[t2.NUMERICIDENTIFIERLOOSE]})`);
    createToken("PRERELEASE", `(?:-(${src[t2.PRERELEASEIDENTIFIER]}(?:\\.${src[t2.PRERELEASEIDENTIFIER]})*))`);
    createToken("PRERELEASELOOSE", `(?:-?(${src[t2.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t2.PRERELEASEIDENTIFIERLOOSE]})*))`);
    createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
    createToken("BUILD", `(?:\\+(${src[t2.BUILDIDENTIFIER]}(?:\\.${src[t2.BUILDIDENTIFIER]})*))`);
    createToken("FULLPLAIN", `v?${src[t2.MAINVERSION]}${src[t2.PRERELEASE]}?${src[t2.BUILD]}?`);
    createToken("FULL", `^${src[t2.FULLPLAIN]}$`);
    createToken("LOOSEPLAIN", `[v=\\s]*${src[t2.MAINVERSIONLOOSE]}${src[t2.PRERELEASELOOSE]}?${src[t2.BUILD]}?`);
    createToken("LOOSE", `^${src[t2.LOOSEPLAIN]}$`);
    createToken("GTLT", "((?:<|>)?=?)");
    createToken("XRANGEIDENTIFIERLOOSE", `${src[t2.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
    createToken("XRANGEIDENTIFIER", `${src[t2.NUMERICIDENTIFIER]}|x|X|\\*`);
    createToken("XRANGEPLAIN", `[v=\\s]*(${src[t2.XRANGEIDENTIFIER]})(?:\\.(${src[t2.XRANGEIDENTIFIER]})(?:\\.(${src[t2.XRANGEIDENTIFIER]})(?:${src[t2.PRERELEASE]})?${src[t2.BUILD]}?)?)?`);
    createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t2.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t2.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t2.XRANGEIDENTIFIERLOOSE]})(?:${src[t2.PRERELEASELOOSE]})?${src[t2.BUILD]}?)?)?`);
    createToken("XRANGE", `^${src[t2.GTLT]}\\s*${src[t2.XRANGEPLAIN]}$`);
    createToken("XRANGELOOSE", `^${src[t2.GTLT]}\\s*${src[t2.XRANGEPLAINLOOSE]}$`);
    createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
    createToken("COERCE", `${src[t2.COERCEPLAIN]}(?:$|[^\\d])`);
    createToken("COERCEFULL", src[t2.COERCEPLAIN] + `(?:${src[t2.PRERELEASE]})?(?:${src[t2.BUILD]})?(?:$|[^\\d])`);
    createToken("COERCERTL", src[t2.COERCE], true);
    createToken("COERCERTLFULL", src[t2.COERCEFULL], true);
    createToken("LONETILDE", "(?:~>?)");
    createToken("TILDETRIM", `(\\s*)${src[t2.LONETILDE]}\\s+`, true);
    exports2.tildeTrimReplace = "$1~";
    createToken("TILDE", `^${src[t2.LONETILDE]}${src[t2.XRANGEPLAIN]}$`);
    createToken("TILDELOOSE", `^${src[t2.LONETILDE]}${src[t2.XRANGEPLAINLOOSE]}$`);
    createToken("LONECARET", "(?:\\^)");
    createToken("CARETTRIM", `(\\s*)${src[t2.LONECARET]}\\s+`, true);
    exports2.caretTrimReplace = "$1^";
    createToken("CARET", `^${src[t2.LONECARET]}${src[t2.XRANGEPLAIN]}$`);
    createToken("CARETLOOSE", `^${src[t2.LONECARET]}${src[t2.XRANGEPLAINLOOSE]}$`);
    createToken("COMPARATORLOOSE", `^${src[t2.GTLT]}\\s*(${src[t2.LOOSEPLAIN]})$|^$`);
    createToken("COMPARATOR", `^${src[t2.GTLT]}\\s*(${src[t2.FULLPLAIN]})$|^$`);
    createToken("COMPARATORTRIM", `(\\s*)${src[t2.GTLT]}\\s*(${src[t2.LOOSEPLAIN]}|${src[t2.XRANGEPLAIN]})`, true);
    exports2.comparatorTrimReplace = "$1$2$3";
    createToken("HYPHENRANGE", `^\\s*(${src[t2.XRANGEPLAIN]})\\s+-\\s+(${src[t2.XRANGEPLAIN]})\\s*$`);
    createToken("HYPHENRANGELOOSE", `^\\s*(${src[t2.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t2.XRANGEPLAINLOOSE]})\\s*$`);
    createToken("STAR", "(<|>)?=?\\s*\\*");
    createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");
    createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");
  }
});

// node_modules/semver/internal/parse-options.js
var require_parse_options = __commonJS({
  "node_modules/semver/internal/parse-options.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var looseOption = Object.freeze({ loose: true });
    var emptyOpts = Object.freeze({});
    var parseOptions = /* @__PURE__ */ __name((options2) => {
      if (!options2) {
        return emptyOpts;
      }
      if (typeof options2 !== "object") {
        return looseOption;
      }
      return options2;
    }, "parseOptions");
    module2.exports = parseOptions;
  }
});

// node_modules/semver/internal/identifiers.js
var require_identifiers = __commonJS({
  "node_modules/semver/internal/identifiers.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var numeric = /^[0-9]+$/;
    var compareIdentifiers = /* @__PURE__ */ __name((a, b) => {
      const anum = numeric.test(a);
      const bnum = numeric.test(b);
      if (anum && bnum) {
        a = +a;
        b = +b;
      }
      return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
    }, "compareIdentifiers");
    var rcompareIdentifiers = /* @__PURE__ */ __name((a, b) => compareIdentifiers(b, a), "rcompareIdentifiers");
    module2.exports = {
      compareIdentifiers,
      rcompareIdentifiers
    };
  }
});

// node_modules/semver/classes/semver.js
var require_semver2 = __commonJS({
  "node_modules/semver/classes/semver.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var debug2 = require_debug();
    var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants12();
    var { safeRe: re2, t: t2 } = require_re();
    var parseOptions = require_parse_options();
    var { compareIdentifiers } = require_identifiers();
    var SemVer = class _SemVer {
      static {
        __name(this, "SemVer");
      }
      constructor(version2, options2) {
        options2 = parseOptions(options2);
        if (version2 instanceof _SemVer) {
          if (version2.loose === !!options2.loose && version2.includePrerelease === !!options2.includePrerelease) {
            return version2;
          } else {
            version2 = version2.version;
          }
        } else if (typeof version2 !== "string") {
          throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version2}".`);
        }
        if (version2.length > MAX_LENGTH) {
          throw new TypeError(
            `version is longer than ${MAX_LENGTH} characters`
          );
        }
        debug2("SemVer", version2, options2);
        this.options = options2;
        this.loose = !!options2.loose;
        this.includePrerelease = !!options2.includePrerelease;
        const m = version2.trim().match(options2.loose ? re2[t2.LOOSE] : re2[t2.FULL]);
        if (!m) {
          throw new TypeError(`Invalid Version: ${version2}`);
        }
        this.raw = version2;
        this.major = +m[1];
        this.minor = +m[2];
        this.patch = +m[3];
        if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
          throw new TypeError("Invalid major version");
        }
        if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
          throw new TypeError("Invalid minor version");
        }
        if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
          throw new TypeError("Invalid patch version");
        }
        if (!m[4]) {
          this.prerelease = [];
        } else {
          this.prerelease = m[4].split(".").map((id) => {
            if (/^[0-9]+$/.test(id)) {
              const num = +id;
              if (num >= 0 && num < MAX_SAFE_INTEGER) {
                return num;
              }
            }
            return id;
          });
        }
        this.build = m[5] ? m[5].split(".") : [];
        this.format();
      }
      format() {
        this.version = `${this.major}.${this.minor}.${this.patch}`;
        if (this.prerelease.length) {
          this.version += `-${this.prerelease.join(".")}`;
        }
        return this.version;
      }
      toString() {
        return this.version;
      }
      compare(other2) {
        debug2("SemVer.compare", this.version, this.options, other2);
        if (!(other2 instanceof _SemVer)) {
          if (typeof other2 === "string" && other2 === this.version) {
            return 0;
          }
          other2 = new _SemVer(other2, this.options);
        }
        if (other2.version === this.version) {
          return 0;
        }
        return this.compareMain(other2) || this.comparePre(other2);
      }
      compareMain(other2) {
        if (!(other2 instanceof _SemVer)) {
          other2 = new _SemVer(other2, this.options);
        }
        return compareIdentifiers(this.major, other2.major) || compareIdentifiers(this.minor, other2.minor) || compareIdentifiers(this.patch, other2.patch);
      }
      comparePre(other2) {
        if (!(other2 instanceof _SemVer)) {
          other2 = new _SemVer(other2, this.options);
        }
        if (this.prerelease.length && !other2.prerelease.length) {
          return -1;
        } else if (!this.prerelease.length && other2.prerelease.length) {
          return 1;
        } else if (!this.prerelease.length && !other2.prerelease.length) {
          return 0;
        }
        let i = 0;
        do {
          const a = this.prerelease[i];
          const b = other2.prerelease[i];
          debug2("prerelease compare", i, a, b);
          if (a === void 0 && b === void 0) {
            return 0;
          } else if (b === void 0) {
            return 1;
          } else if (a === void 0) {
            return -1;
          } else if (a === b) {
            continue;
          } else {
            return compareIdentifiers(a, b);
          }
        } while (++i);
      }
      compareBuild(other2) {
        if (!(other2 instanceof _SemVer)) {
          other2 = new _SemVer(other2, this.options);
        }
        let i = 0;
        do {
          const a = this.build[i];
          const b = other2.build[i];
          debug2("build compare", i, a, b);
          if (a === void 0 && b === void 0) {
            return 0;
          } else if (b === void 0) {
            return 1;
          } else if (a === void 0) {
            return -1;
          } else if (a === b) {
            continue;
          } else {
            return compareIdentifiers(a, b);
          }
        } while (++i);
      }
      // preminor will bump the version up to the next minor release, and immediately
      // down to pre-release. premajor and prepatch work the same way.
      inc(release3, identifier2, identifierBase) {
        if (release3.startsWith("pre")) {
          if (!identifier2 && identifierBase === false) {
            throw new Error("invalid increment argument: identifier is empty");
          }
          if (identifier2) {
            const match2 = `-${identifier2}`.match(this.options.loose ? re2[t2.PRERELEASELOOSE] : re2[t2.PRERELEASE]);
            if (!match2 || match2[1] !== identifier2) {
              throw new Error(`invalid identifier: ${identifier2}`);
            }
          }
        }
        switch (release3) {
          case "premajor":
            this.prerelease.length = 0;
            this.patch = 0;
            this.minor = 0;
            this.major++;
            this.inc("pre", identifier2, identifierBase);
            break;
          case "preminor":
            this.prerelease.length = 0;
            this.patch = 0;
            this.minor++;
            this.inc("pre", identifier2, identifierBase);
            break;
          case "prepatch":
            this.prerelease.length = 0;
            this.inc("patch", identifier2, identifierBase);
            this.inc("pre", identifier2, identifierBase);
            break;
          // If the input is a non-prerelease version, this acts the same as
          // prepatch.
          case "prerelease":
            if (this.prerelease.length === 0) {
              this.inc("patch", identifier2, identifierBase);
            }
            this.inc("pre", identifier2, identifierBase);
            break;
          case "release":
            if (this.prerelease.length === 0) {
              throw new Error(`version ${this.raw} is not a prerelease`);
            }
            this.prerelease.length = 0;
            break;
          case "major":
            if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
              this.major++;
            }
            this.minor = 0;
            this.patch = 0;
            this.prerelease = [];
            break;
          case "minor":
            if (this.patch !== 0 || this.prerelease.length === 0) {
              this.minor++;
            }
            this.patch = 0;
            this.prerelease = [];
            break;
          case "patch":
            if (this.prerelease.length === 0) {
              this.patch++;
            }
            this.prerelease = [];
            break;
          // This probably shouldn't be used publicly.
          // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
          case "pre": {
            const base = Number(identifierBase) ? 1 : 0;
            if (this.prerelease.length === 0) {
              this.prerelease = [base];
            } else {
              let i = this.prerelease.length;
              while (--i >= 0) {
                if (typeof this.prerelease[i] === "number") {
                  this.prerelease[i]++;
                  i = -2;
                }
              }
              if (i === -1) {
                if (identifier2 === this.prerelease.join(".") && identifierBase === false) {
                  throw new Error("invalid increment argument: identifier already exists");
                }
                this.prerelease.push(base);
              }
            }
            if (identifier2) {
              let prerelease = [identifier2, base];
              if (identifierBase === false) {
                prerelease = [identifier2];
              }
              if (compareIdentifiers(this.prerelease[0], identifier2) === 0) {
                if (isNaN(this.prerelease[1])) {
                  this.prerelease = prerelease;
                }
              } else {
                this.prerelease = prerelease;
              }
            }
            break;
          }
          default:
            throw new Error(`invalid increment argument: ${release3}`);
        }
        this.raw = this.format();
        if (this.build.length) {
          this.raw += `+${this.build.join(".")}`;
        }
        return this;
      }
    };
    module2.exports = SemVer;
  }
});

// node_modules/semver/functions/parse.js
var require_parse8 = __commonJS({
  "node_modules/semver/functions/parse.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var SemVer = require_semver2();
    var parse12 = /* @__PURE__ */ __name((version2, options2, throwErrors = false) => {
      if (version2 instanceof SemVer) {
        return version2;
      }
      try {
        return new SemVer(version2, options2);
      } catch (er) {
        if (!throwErrors) {
          return null;
        }
        throw er;
      }
    }, "parse");
    module2.exports = parse12;
  }
});

// node_modules/semver/functions/valid.js
var require_valid = __commonJS({
  "node_modules/semver/functions/valid.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var parse12 = require_parse8();
    var valid = /* @__PURE__ */ __name((version2, options2) => {
      const v = parse12(version2, options2);
      return v ? v.version : null;
    }, "valid");
    module2.exports = valid;
  }
});

// node_modules/semver/functions/clean.js
var require_clean = __commonJS({
  "node_modules/semver/functions/clean.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var parse12 = require_parse8();
    var clean = /* @__PURE__ */ __name((version2, options2) => {
      const s2 = parse12(version2.trim().replace(/^[=v]+/, ""), options2);
      return s2 ? s2.version : null;
    }, "clean");
    module2.exports = clean;
  }
});

// node_modules/spdx-license-ids/index.json
var require_spdx_license_ids = __commonJS({
  "node_modules/spdx-license-ids/index.json"(exports2, module2) {
    module2.exports = [
      "0BSD",
      "3D-Slicer-1.0",
      "AAL",
      "ADSL",
      "AFL-1.1",
      "AFL-1.2",
      "AFL-2.0",
      "AFL-2.1",
      "AFL-3.0",
      "AGPL-1.0-only",
      "AGPL-1.0-or-later",
      "AGPL-3.0-only",
      "AGPL-3.0-or-later",
      "AMD-newlib",
      "AMDPLPA",
      "AML",
      "AML-glslang",
      "AMPAS",
      "ANTLR-PD",
      "ANTLR-PD-fallback",
      "APAFML",
      "APL-1.0",
      "APSL-1.0",
      "APSL-1.1",
      "APSL-1.2",
      "APSL-2.0",
      "ASWF-Digital-Assets-1.0",
      "ASWF-Digital-Assets-1.1",
      "Abstyles",
      "AdaCore-doc",
      "Adobe-2006",
      "Adobe-Display-PostScript",
      "Adobe-Glyph",
      "Adobe-Utopia",
      "Afmparse",
      "Aladdin",
      "Apache-1.0",
      "Apache-1.1",
      "Apache-2.0",
      "App-s2p",
      "Arphic-1999",
      "Artistic-1.0",
      "Artistic-1.0-Perl",
      "Artistic-1.0-cl8",
      "Artistic-2.0",
      "BSD-1-Clause",
      "BSD-2-Clause",
      "BSD-2-Clause-Darwin",
      "BSD-2-Clause-Patent",
      "BSD-2-Clause-Views",
      "BSD-2-Clause-first-lines",
      "BSD-3-Clause",
      "BSD-3-Clause-Attribution",
      "BSD-3-Clause-Clear",
      "BSD-3-Clause-HP",
      "BSD-3-Clause-LBNL",
      "BSD-3-Clause-Modification",
      "BSD-3-Clause-No-Military-License",
      "BSD-3-Clause-No-Nuclear-License",
      "BSD-3-Clause-No-Nuclear-License-2014",
      "BSD-3-Clause-No-Nuclear-Warranty",
      "BSD-3-Clause-Open-MPI",
      "BSD-3-Clause-Sun",
      "BSD-3-Clause-acpica",
      "BSD-3-Clause-flex",
      "BSD-4-Clause",
      "BSD-4-Clause-Shortened",
      "BSD-4-Clause-UC",
      "BSD-4.3RENO",
      "BSD-4.3TAHOE",
      "BSD-Advertising-Acknowledgement",
      "BSD-Attribution-HPND-disclaimer",
      "BSD-Inferno-Nettverk",
      "BSD-Protection",
      "BSD-Source-Code",
      "BSD-Source-beginning-file",
      "BSD-Systemics",
      "BSD-Systemics-W3Works",
      "BSL-1.0",
      "BUSL-1.1",
      "Baekmuk",
      "Bahyph",
      "Barr",
      "Beerware",
      "BitTorrent-1.0",
      "BitTorrent-1.1",
      "Bitstream-Charter",
      "Bitstream-Vera",
      "BlueOak-1.0.0",
      "Boehm-GC",
      "Boehm-GC-without-fee",
      "Borceux",
      "Brian-Gladman-2-Clause",
      "Brian-Gladman-3-Clause",
      "C-UDA-1.0",
      "CAL-1.0",
      "CAL-1.0-Combined-Work-Exception",
      "CATOSL-1.1",
      "CC-BY-1.0",
      "CC-BY-2.0",
      "CC-BY-2.5",
      "CC-BY-2.5-AU",
      "CC-BY-3.0",
      "CC-BY-3.0-AT",
      "CC-BY-3.0-AU",
      "CC-BY-3.0-DE",
      "CC-BY-3.0-IGO",
      "CC-BY-3.0-NL",
      "CC-BY-3.0-US",
      "CC-BY-4.0",
      "CC-BY-NC-1.0",
      "CC-BY-NC-2.0",
      "CC-BY-NC-2.5",
      "CC-BY-NC-3.0",
      "CC-BY-NC-3.0-DE",
      "CC-BY-NC-4.0",
      "CC-BY-NC-ND-1.0",
      "CC-BY-NC-ND-2.0",
      "CC-BY-NC-ND-2.5",
      "CC-BY-NC-ND-3.0",
      "CC-BY-NC-ND-3.0-DE",
      "CC-BY-NC-ND-3.0-IGO",
      "CC-BY-NC-ND-4.0",
      "CC-BY-NC-SA-1.0",
      "CC-BY-NC-SA-2.0",
      "CC-BY-NC-SA-2.0-DE",
      "CC-BY-NC-SA-2.0-FR",
      "CC-BY-NC-SA-2.0-UK",
      "CC-BY-NC-SA-2.5",
      "CC-BY-NC-SA-3.0",
      "CC-BY-NC-SA-3.0-DE",
      "CC-BY-NC-SA-3.0-IGO",
      "CC-BY-NC-SA-4.0",
      "CC-BY-ND-1.0",
      "CC-BY-ND-2.0",
      "CC-BY-ND-2.5",
      "CC-BY-ND-3.0",
      "CC-BY-ND-3.0-DE",
      "CC-BY-ND-4.0",
      "CC-BY-SA-1.0",
      "CC-BY-SA-2.0",
      "CC-BY-SA-2.0-UK",
      "CC-BY-SA-2.1-JP",
      "CC-BY-SA-2.5",
      "CC-BY-SA-3.0",
      "CC-BY-SA-3.0-AT",
      "CC-BY-SA-3.0-DE",
      "CC-BY-SA-3.0-IGO",
      "CC-BY-SA-4.0",
      "CC-PDDC",
      "CC-PDM-1.0",
      "CC-SA-1.0",
      "CC0-1.0",
      "CDDL-1.0",
      "CDDL-1.1",
      "CDL-1.0",
      "CDLA-Permissive-1.0",
      "CDLA-Permissive-2.0",
      "CDLA-Sharing-1.0",
      "CECILL-1.0",
      "CECILL-1.1",
      "CECILL-2.0",
      "CECILL-2.1",
      "CECILL-B",
      "CECILL-C",
      "CERN-OHL-1.1",
      "CERN-OHL-1.2",
      "CERN-OHL-P-2.0",
      "CERN-OHL-S-2.0",
      "CERN-OHL-W-2.0",
      "CFITSIO",
      "CMU-Mach",
      "CMU-Mach-nodoc",
      "CNRI-Jython",
      "CNRI-Python",
      "CNRI-Python-GPL-Compatible",
      "COIL-1.0",
      "CPAL-1.0",
      "CPL-1.0",
      "CPOL-1.02",
      "CUA-OPL-1.0",
      "Caldera",
      "Caldera-no-preamble",
      "Catharon",
      "ClArtistic",
      "Clips",
      "Community-Spec-1.0",
      "Condor-1.1",
      "Cornell-Lossless-JPEG",
      "Cronyx",
      "Crossword",
      "CrystalStacker",
      "Cube",
      "D-FSL-1.0",
      "DEC-3-Clause",
      "DL-DE-BY-2.0",
      "DL-DE-ZERO-2.0",
      "DOC",
      "DRL-1.0",
      "DRL-1.1",
      "DSDP",
      "DocBook-Schema",
      "DocBook-Stylesheet",
      "DocBook-XML",
      "Dotseqn",
      "ECL-1.0",
      "ECL-2.0",
      "EFL-1.0",
      "EFL-2.0",
      "EPICS",
      "EPL-1.0",
      "EPL-2.0",
      "EUDatagrid",
      "EUPL-1.0",
      "EUPL-1.1",
      "EUPL-1.2",
      "Elastic-2.0",
      "Entessa",
      "ErlPL-1.1",
      "Eurosym",
      "FBM",
      "FDK-AAC",
      "FSFAP",
      "FSFAP-no-warranty-disclaimer",
      "FSFUL",
      "FSFULLR",
      "FSFULLRWD",
      "FTL",
      "Fair",
      "Ferguson-Twofish",
      "Frameworx-1.0",
      "FreeBSD-DOC",
      "FreeImage",
      "Furuseth",
      "GCR-docs",
      "GD",
      "GFDL-1.1-invariants-only",
      "GFDL-1.1-invariants-or-later",
      "GFDL-1.1-no-invariants-only",
      "GFDL-1.1-no-invariants-or-later",
      "GFDL-1.1-only",
      "GFDL-1.1-or-later",
      "GFDL-1.2-invariants-only",
      "GFDL-1.2-invariants-or-later",
      "GFDL-1.2-no-invariants-only",
      "GFDL-1.2-no-invariants-or-later",
      "GFDL-1.2-only",
      "GFDL-1.2-or-later",
      "GFDL-1.3-invariants-only",
      "GFDL-1.3-invariants-or-later",
      "GFDL-1.3-no-invariants-only",
      "GFDL-1.3-no-invariants-or-later",
      "GFDL-1.3-only",
      "GFDL-1.3-or-later",
      "GL2PS",
      "GLWTPL",
      "GPL-1.0-only",
      "GPL-1.0-or-later",
      "GPL-2.0-only",
      "GPL-2.0-or-later",
      "GPL-3.0-only",
      "GPL-3.0-or-later",
      "Giftware",
      "Glide",
      "Glulxe",
      "Graphics-Gems",
      "Gutmann",
      "HIDAPI",
      "HP-1986",
      "HP-1989",
      "HPND",
      "HPND-DEC",
      "HPND-Fenneberg-Livingston",
      "HPND-INRIA-IMAG",
      "HPND-Intel",
      "HPND-Kevlin-Henney",
      "HPND-MIT-disclaimer",
      "HPND-Markus-Kuhn",
      "HPND-Netrek",
      "HPND-Pbmplus",
      "HPND-UC",
      "HPND-UC-export-US",
      "HPND-doc",
      "HPND-doc-sell",
      "HPND-export-US",
      "HPND-export-US-acknowledgement",
      "HPND-export-US-modify",
      "HPND-export2-US",
      "HPND-merchantability-variant",
      "HPND-sell-MIT-disclaimer-xserver",
      "HPND-sell-regexpr",
      "HPND-sell-variant",
      "HPND-sell-variant-MIT-disclaimer",
      "HPND-sell-variant-MIT-disclaimer-rev",
      "HTMLTIDY",
      "HaskellReport",
      "Hippocratic-2.1",
      "IBM-pibs",
      "ICU",
      "IEC-Code-Components-EULA",
      "IJG",
      "IJG-short",
      "IPA",
      "IPL-1.0",
      "ISC",
      "ISC-Veillard",
      "ImageMagick",
      "Imlib2",
      "Info-ZIP",
      "Inner-Net-2.0",
      "InnoSetup",
      "Intel",
      "Intel-ACPI",
      "Interbase-1.0",
      "JPL-image",
      "JPNIC",
      "JSON",
      "Jam",
      "JasPer-2.0",
      "Kastrup",
      "Kazlib",
      "Knuth-CTAN",
      "LAL-1.2",
      "LAL-1.3",
      "LGPL-2.0-only",
      "LGPL-2.0-or-later",
      "LGPL-2.1-only",
      "LGPL-2.1-or-later",
      "LGPL-3.0-only",
      "LGPL-3.0-or-later",
      "LGPLLR",
      "LOOP",
      "LPD-document",
      "LPL-1.0",
      "LPL-1.02",
      "LPPL-1.0",
      "LPPL-1.1",
      "LPPL-1.2",
      "LPPL-1.3a",
      "LPPL-1.3c",
      "LZMA-SDK-9.11-to-9.20",
      "LZMA-SDK-9.22",
      "Latex2e",
      "Latex2e-translated-notice",
      "Leptonica",
      "LiLiQ-P-1.1",
      "LiLiQ-R-1.1",
      "LiLiQ-Rplus-1.1",
      "Libpng",
      "Linux-OpenIB",
      "Linux-man-pages-1-para",
      "Linux-man-pages-copyleft",
      "Linux-man-pages-copyleft-2-para",
      "Linux-man-pages-copyleft-var",
      "Lucida-Bitmap-Fonts",
      "MIPS",
      "MIT",
      "MIT-0",
      "MIT-CMU",
      "MIT-Click",
      "MIT-Festival",
      "MIT-Khronos-old",
      "MIT-Modern-Variant",
      "MIT-Wu",
      "MIT-advertising",
      "MIT-enna",
      "MIT-feh",
      "MIT-open-group",
      "MIT-testregex",
      "MITNFA",
      "MMIXware",
      "MPEG-SSG",
      "MPL-1.0",
      "MPL-1.1",
      "MPL-2.0",
      "MPL-2.0-no-copyleft-exception",
      "MS-LPL",
      "MS-PL",
      "MS-RL",
      "MTLL",
      "Mackerras-3-Clause",
      "Mackerras-3-Clause-acknowledgment",
      "MakeIndex",
      "Martin-Birgmeier",
      "McPhee-slideshow",
      "Minpack",
      "MirOS",
      "Motosoto",
      "MulanPSL-1.0",
      "MulanPSL-2.0",
      "Multics",
      "Mup",
      "NAIST-2003",
      "NASA-1.3",
      "NBPL-1.0",
      "NCBI-PD",
      "NCGL-UK-2.0",
      "NCL",
      "NCSA",
      "NGPL",
      "NICTA-1.0",
      "NIST-PD",
      "NIST-PD-fallback",
      "NIST-Software",
      "NLOD-1.0",
      "NLOD-2.0",
      "NLPL",
      "NOSL",
      "NPL-1.0",
      "NPL-1.1",
      "NPOSL-3.0",
      "NRL",
      "NTP",
      "NTP-0",
      "Naumen",
      "NetCDF",
      "Newsletr",
      "Nokia",
      "Noweb",
      "O-UDA-1.0",
      "OAR",
      "OCCT-PL",
      "OCLC-2.0",
      "ODC-By-1.0",
      "ODbL-1.0",
      "OFFIS",
      "OFL-1.0",
      "OFL-1.0-RFN",
      "OFL-1.0-no-RFN",
      "OFL-1.1",
      "OFL-1.1-RFN",
      "OFL-1.1-no-RFN",
      "OGC-1.0",
      "OGDL-Taiwan-1.0",
      "OGL-Canada-2.0",
      "OGL-UK-1.0",
      "OGL-UK-2.0",
      "OGL-UK-3.0",
      "OGTSL",
      "OLDAP-1.1",
      "OLDAP-1.2",
      "OLDAP-1.3",
      "OLDAP-1.4",
      "OLDAP-2.0",
      "OLDAP-2.0.1",
      "OLDAP-2.1",
      "OLDAP-2.2",
      "OLDAP-2.2.1",
      "OLDAP-2.2.2",
      "OLDAP-2.3",
      "OLDAP-2.4",
      "OLDAP-2.5",
      "OLDAP-2.6",
      "OLDAP-2.7",
      "OLDAP-2.8",
      "OLFL-1.3",
      "OML",
      "OPL-1.0",
      "OPL-UK-3.0",
      "OPUBL-1.0",
      "OSET-PL-2.1",
      "OSL-1.0",
      "OSL-1.1",
      "OSL-2.0",
      "OSL-2.1",
      "OSL-3.0",
      "OpenPBS-2.3",
      "OpenSSL",
      "OpenSSL-standalone",
      "OpenVision",
      "PADL",
      "PDDL-1.0",
      "PHP-3.0",
      "PHP-3.01",
      "PPL",
      "PSF-2.0",
      "Parity-6.0.0",
      "Parity-7.0.0",
      "Pixar",
      "Plexus",
      "PolyForm-Noncommercial-1.0.0",
      "PolyForm-Small-Business-1.0.0",
      "PostgreSQL",
      "Python-2.0",
      "Python-2.0.1",
      "QPL-1.0",
      "QPL-1.0-INRIA-2004",
      "Qhull",
      "RHeCos-1.1",
      "RPL-1.1",
      "RPL-1.5",
      "RPSL-1.0",
      "RSA-MD",
      "RSCPL",
      "Rdisc",
      "Ruby",
      "Ruby-pty",
      "SAX-PD",
      "SAX-PD-2.0",
      "SCEA",
      "SGI-B-1.0",
      "SGI-B-1.1",
      "SGI-B-2.0",
      "SGI-OpenGL",
      "SGP4",
      "SHL-0.5",
      "SHL-0.51",
      "SISSL",
      "SISSL-1.2",
      "SL",
      "SMAIL-GPL",
      "SMLNJ",
      "SMPPL",
      "SNIA",
      "SPL-1.0",
      "SSH-OpenSSH",
      "SSH-short",
      "SSLeay-standalone",
      "SSPL-1.0",
      "SWL",
      "Saxpath",
      "SchemeReport",
      "Sendmail",
      "Sendmail-8.23",
      "Sendmail-Open-Source-1.1",
      "SimPL-2.0",
      "Sleepycat",
      "Soundex",
      "Spencer-86",
      "Spencer-94",
      "Spencer-99",
      "SugarCRM-1.1.3",
      "Sun-PPP",
      "Sun-PPP-2000",
      "SunPro",
      "Symlinks",
      "TAPR-OHL-1.0",
      "TCL",
      "TCP-wrappers",
      "TGPPL-1.0",
      "TMate",
      "TORQUE-1.1",
      "TOSL",
      "TPDL",
      "TPL-1.0",
      "TTWL",
      "TTYP0",
      "TU-Berlin-1.0",
      "TU-Berlin-2.0",
      "TermReadKey",
      "ThirdEye",
      "TrustedQSL",
      "UCAR",
      "UCL-1.0",
      "UMich-Merit",
      "UPL-1.0",
      "URT-RLE",
      "Ubuntu-font-1.0",
      "Unicode-3.0",
      "Unicode-DFS-2015",
      "Unicode-DFS-2016",
      "Unicode-TOU",
      "UnixCrypt",
      "Unlicense",
      "VOSTROM",
      "VSL-1.0",
      "Vim",
      "W3C",
      "W3C-19980720",
      "W3C-20150513",
      "WTFPL",
      "Watcom-1.0",
      "Widget-Workshop",
      "Wsuipa",
      "X11",
      "X11-distribute-modifications-variant",
      "X11-swapped",
      "XFree86-1.1",
      "XSkat",
      "Xdebug-1.03",
      "Xerox",
      "Xfig",
      "Xnet",
      "YPL-1.0",
      "YPL-1.1",
      "ZPL-1.1",
      "ZPL-2.0",
      "ZPL-2.1",
      "Zed",
      "Zeeff",
      "Zend-2.0",
      "Zimbra-1.3",
      "Zimbra-1.4",
      "Zlib",
      "any-OSI",
      "any-OSI-perl-modules",
      "bcrypt-Solar-Designer",
      "blessing",
      "bzip2-1.0.6",
      "check-cvs",
      "checkmk",
      "copyleft-next-0.3.0",
      "copyleft-next-0.3.1",
      "curl",
      "cve-tou",
      "diffmark",
      "dtoa",
      "dvipdfm",
      "eGenix",
      "etalab-2.0",
      "fwlw",
      "gSOAP-1.3b",
      "generic-xts",
      "gnuplot",
      "gtkbook",
      "hdparm",
      "iMatix",
      "libpng-2.0",
      "libselinux-1.0",
      "libtiff",
      "libutil-David-Nugent",
      "lsof",
      "magaz",
      "mailprio",
      "metamail",
      "mpi-permissive",
      "mpich2",
      "mplus",
      "pkgconf",
      "pnmstitch",
      "psfrag",
      "psutils",
      "python-ldap",
      "radvd",
      "snprintf",
      "softSurfer",
      "ssh-keyscan",
      "swrule",
      "threeparttable",
      "ulem",
      "w3m",
      "wwl",
      "xinetd",
      "xkeyboard-config-Zinoviev",
      "xlock",
      "xpp",
      "xzoom",
      "zlib-acknowledgement"
    ];
  }
});

// node_modules/spdx-license-ids/deprecated.json
var require_deprecated = __commonJS({
  "node_modules/spdx-license-ids/deprecated.json"(exports2, module2) {
    module2.exports = [
      "AGPL-1.0",
      "AGPL-3.0",
      "BSD-2-Clause-FreeBSD",
      "BSD-2-Clause-NetBSD",
      "GFDL-1.1",
      "GFDL-1.2",
      "GFDL-1.3",
      "GPL-1.0",
      "GPL-2.0",
      "GPL-2.0-with-GCC-exception",
      "GPL-2.0-with-autoconf-exception",
      "GPL-2.0-with-bison-exception",
      "GPL-2.0-with-classpath-exception",
      "GPL-2.0-with-font-exception",
      "GPL-3.0",
      "GPL-3.0-with-GCC-exception",
      "GPL-3.0-with-autoconf-exception",
      "LGPL-2.0",
      "LGPL-2.1",
      "LGPL-3.0",
      "Net-SNMP",
      "Nunit",
      "StandardML-NJ",
      "bzip2-1.0.5",
      "eCos-2.0",
      "wxWindows"
    ];
  }
});

// node_modules/spdx-exceptions/index.json
var require_spdx_exceptions = __commonJS({
  "node_modules/spdx-exceptions/index.json"(exports2, module2) {
    module2.exports = [
      "389-exception",
      "Asterisk-exception",
      "Autoconf-exception-2.0",
      "Autoconf-exception-3.0",
      "Autoconf-exception-generic",
      "Autoconf-exception-generic-3.0",
      "Autoconf-exception-macro",
      "Bison-exception-1.24",
      "Bison-exception-2.2",
      "Bootloader-exception",
      "Classpath-exception-2.0",
      "CLISP-exception-2.0",
      "cryptsetup-OpenSSL-exception",
      "DigiRule-FOSS-exception",
      "eCos-exception-2.0",
      "Fawkes-Runtime-exception",
      "FLTK-exception",
      "fmt-exception",
      "Font-exception-2.0",
      "freertos-exception-2.0",
      "GCC-exception-2.0",
      "GCC-exception-2.0-note",
      "GCC-exception-3.1",
      "Gmsh-exception",
      "GNAT-exception",
      "GNOME-examples-exception",
      "GNU-compiler-exception",
      "gnu-javamail-exception",
      "GPL-3.0-interface-exception",
      "GPL-3.0-linking-exception",
      "GPL-3.0-linking-source-exception",
      "GPL-CC-1.0",
      "GStreamer-exception-2005",
      "GStreamer-exception-2008",
      "i2p-gpl-java-exception",
      "KiCad-libraries-exception",
      "LGPL-3.0-linking-exception",
      "libpri-OpenH323-exception",
      "Libtool-exception",
      "Linux-syscall-note",
      "LLGPL",
      "LLVM-exception",
      "LZMA-exception",
      "mif-exception",
      "OCaml-LGPL-linking-exception",
      "OCCT-exception-1.0",
      "OpenJDK-assembly-exception-1.0",
      "openvpn-openssl-exception",
      "PS-or-PDF-font-exception-20170817",
      "QPL-1.0-INRIA-2004-exception",
      "Qt-GPL-exception-1.0",
      "Qt-LGPL-exception-1.1",
      "Qwt-exception-1.0",
      "SANE-exception",
      "SHL-2.0",
      "SHL-2.1",
      "stunnel-exception",
      "SWI-exception",
      "Swift-exception",
      "Texinfo-exception",
      "u-boot-exception-2.0",
      "UBDL-exception",
      "Universal-FOSS-exception-1.0",
      "vsftpd-openssl-exception",
      "WxWindows-exception-3.1",
      "x11vnc-openssl-exception"
    ];
  }
});

// node_modules/spdx-expression-parse/scan.js
var require_scan2 = __commonJS({
  "node_modules/spdx-expression-parse/scan.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var licenses = [].concat(require_spdx_license_ids()).concat(require_deprecated());
    var exceptions = require_spdx_exceptions();
    module2.exports = function(source2) {
      var index = 0;
      function hasMore() {
        return index < source2.length;
      }
      __name(hasMore, "hasMore");
      function read2(value) {
        if (value instanceof RegExp) {
          var chars = source2.slice(index);
          var match2 = chars.match(value);
          if (match2) {
            index += match2[0].length;
            return match2[0];
          }
        } else {
          if (source2.indexOf(value, index) === index) {
            index += value.length;
            return value;
          }
        }
      }
      __name(read2, "read");
      function skipWhitespace() {
        read2(/[ ]*/);
      }
      __name(skipWhitespace, "skipWhitespace");
      function operator2() {
        var string;
        var possibilities = ["WITH", "AND", "OR", "(", ")", ":", "+"];
        for (var i = 0; i < possibilities.length; i++) {
          string = read2(possibilities[i]);
          if (string) {
            break;
          }
        }
        if (string === "+" && index > 1 && source2[index - 2] === " ") {
          throw new Error("Space before `+`");
        }
        return string && {
          type: "OPERATOR",
          string
        };
      }
      __name(operator2, "operator");
      function idstring() {
        return read2(/[A-Za-z0-9-.]+/);
      }
      __name(idstring, "idstring");
      function expectIdstring() {
        var string = idstring();
        if (!string) {
          throw new Error("Expected idstring at offset " + index);
        }
        return string;
      }
      __name(expectIdstring, "expectIdstring");
      function documentRef() {
        if (read2("DocumentRef-")) {
          var string = expectIdstring();
          return { type: "DOCUMENTREF", string };
        }
      }
      __name(documentRef, "documentRef");
      function licenseRef() {
        if (read2("LicenseRef-")) {
          var string = expectIdstring();
          return { type: "LICENSEREF", string };
        }
      }
      __name(licenseRef, "licenseRef");
      function identifier2() {
        var begin = index;
        var string = idstring();
        if (licenses.indexOf(string) !== -1) {
          return {
            type: "LICENSE",
            string
          };
        } else if (exceptions.indexOf(string) !== -1) {
          return {
            type: "EXCEPTION",
            string
          };
        }
        index = begin;
      }
      __name(identifier2, "identifier");
      function parseToken() {
        return operator2() || documentRef() || licenseRef() || identifier2();
      }
      __name(parseToken, "parseToken");
      var tokens = [];
      while (hasMore()) {
        skipWhitespace();
        if (!hasMore()) {
          break;
        }
        var token2 = parseToken();
        if (!token2) {
          throw new Error("Unexpected `" + source2[index] + "` at offset " + index);
        }
        tokens.push(token2);
      }
      return tokens;
    };
  }
});

// node_modules/spdx-expression-parse/parse.js
var require_parse9 = __commonJS({
  "node_modules/spdx-expression-parse/parse.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = function(tokens) {
      var index = 0;
      function hasMore() {
        return index < tokens.length;
      }
      __name(hasMore, "hasMore");
      function token2() {
        return hasMore() ? tokens[index] : null;
      }
      __name(token2, "token");
      function next() {
        if (!hasMore()) {
          throw new Error();
        }
        index++;
      }
      __name(next, "next");
      function parseOperator(operator2) {
        var t2 = token2();
        if (t2 && t2.type === "OPERATOR" && operator2 === t2.string) {
          next();
          return t2.string;
        }
      }
      __name(parseOperator, "parseOperator");
      function parseWith() {
        if (parseOperator("WITH")) {
          var t2 = token2();
          if (t2 && t2.type === "EXCEPTION") {
            next();
            return t2.string;
          }
          throw new Error("Expected exception after `WITH`");
        }
      }
      __name(parseWith, "parseWith");
      function parseLicenseRef() {
        var begin = index;
        var string = "";
        var t2 = token2();
        if (t2.type === "DOCUMENTREF") {
          next();
          string += "DocumentRef-" + t2.string + ":";
          if (!parseOperator(":")) {
            throw new Error("Expected `:` after `DocumentRef-...`");
          }
        }
        t2 = token2();
        if (t2.type === "LICENSEREF") {
          next();
          string += "LicenseRef-" + t2.string;
          return { license: string };
        }
        index = begin;
      }
      __name(parseLicenseRef, "parseLicenseRef");
      function parseLicense() {
        var t2 = token2();
        if (t2 && t2.type === "LICENSE") {
          next();
          var node2 = { license: t2.string };
          if (parseOperator("+")) {
            node2.plus = true;
          }
          var exception = parseWith();
          if (exception) {
            node2.exception = exception;
          }
          return node2;
        }
      }
      __name(parseLicense, "parseLicense");
      function parseParenthesizedExpression() {
        var left3 = parseOperator("(");
        if (!left3) {
          return;
        }
        var expr = parseExpression();
        if (!parseOperator(")")) {
          throw new Error("Expected `)`");
        }
        return expr;
      }
      __name(parseParenthesizedExpression, "parseParenthesizedExpression");
      function parseAtom() {
        return parseParenthesizedExpression() || parseLicenseRef() || parseLicense();
      }
      __name(parseAtom, "parseAtom");
      function makeBinaryOpParser(operator2, nextParser) {
        return /* @__PURE__ */ __name(function parseBinaryOp() {
          var left3 = nextParser();
          if (!left3) {
            return;
          }
          if (!parseOperator(operator2)) {
            return left3;
          }
          var right3 = parseBinaryOp();
          if (!right3) {
            throw new Error("Expected expression");
          }
          return {
            left: left3,
            conjunction: operator2.toLowerCase(),
            right: right3
          };
        }, "parseBinaryOp");
      }
      __name(makeBinaryOpParser, "makeBinaryOpParser");
      var parseAnd = makeBinaryOpParser("AND", parseAtom);
      var parseExpression = makeBinaryOpParser("OR", parseAnd);
      var node = parseExpression();
      if (!node || hasMore()) {
        throw new Error("Syntax error");
      }
      return node;
    };
  }
});

// node_modules/spdx-expression-parse/index.js
var require_spdx_expression_parse = __commonJS({
  "node_modules/spdx-expression-parse/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var scan = require_scan2();
    var parse12 = require_parse9();
    module2.exports = function(source2) {
      return parse12(scan(source2));
    };
  }
});

// node_modules/spdx-correct/index.js
var require_spdx_correct = __commonJS({
  "node_modules/spdx-correct/index.js"(exports2, module2) {
    init_esbuild_shims();
    var parse12 = require_spdx_expression_parse();
    var spdxLicenseIds = require_spdx_license_ids();
    function valid(string) {
      try {
        parse12(string);
        return true;
      } catch (error) {
        return false;
      }
    }
    __name(valid, "valid");
    function sortTranspositions(a, b) {
      var length = b[0].length - a[0].length;
      if (length !== 0) return length;
      return a[0].toUpperCase().localeCompare(b[0].toUpperCase());
    }
    __name(sortTranspositions, "sortTranspositions");
    var transpositions = [
      ["APGL", "AGPL"],
      ["Gpl", "GPL"],
      ["GLP", "GPL"],
      ["APL", "Apache"],
      ["ISD", "ISC"],
      ["GLP", "GPL"],
      ["IST", "ISC"],
      ["Claude", "Clause"],
      [" or later", "+"],
      [" International", ""],
      ["GNU", "GPL"],
      ["GUN", "GPL"],
      ["+", ""],
      ["GNU GPL", "GPL"],
      ["GNU LGPL", "LGPL"],
      ["GNU/GPL", "GPL"],
      ["GNU GLP", "GPL"],
      ["GNU LESSER GENERAL PUBLIC LICENSE", "LGPL"],
      ["GNU Lesser General Public License", "LGPL"],
      ["GNU LESSER GENERAL PUBLIC LICENSE", "LGPL-2.1"],
      ["GNU Lesser General Public License", "LGPL-2.1"],
      ["LESSER GENERAL PUBLIC LICENSE", "LGPL"],
      ["Lesser General Public License", "LGPL"],
      ["LESSER GENERAL PUBLIC LICENSE", "LGPL-2.1"],
      ["Lesser General Public License", "LGPL-2.1"],
      ["GNU General Public License", "GPL"],
      ["Gnu public license", "GPL"],
      ["GNU Public License", "GPL"],
      ["GNU GENERAL PUBLIC LICENSE", "GPL"],
      ["MTI", "MIT"],
      ["Mozilla Public License", "MPL"],
      ["Universal Permissive License", "UPL"],
      ["WTH", "WTF"],
      ["WTFGPL", "WTFPL"],
      ["-License", ""]
    ].sort(sortTranspositions);
    var TRANSPOSED = 0;
    var CORRECT = 1;
    var transforms = [
      // e.g. 'mit'
      function(argument) {
        return argument.toUpperCase();
      },
      // e.g. 'MIT '
      function(argument) {
        return argument.trim();
      },
      // e.g. 'M.I.T.'
      function(argument) {
        return argument.replace(/\./g, "");
      },
      // e.g. 'Apache- 2.0'
      function(argument) {
        return argument.replace(/\s+/g, "");
      },
      // e.g. 'CC BY 4.0''
      function(argument) {
        return argument.replace(/\s+/g, "-");
      },
      // e.g. 'LGPLv2.1'
      function(argument) {
        return argument.replace("v", "-");
      },
      // e.g. 'Apache 2.0'
      function(argument) {
        return argument.replace(/,?\s*(\d)/, "-$1");
      },
      // e.g. 'GPL 2'
      function(argument) {
        return argument.replace(/,?\s*(\d)/, "-$1.0");
      },
      // e.g. 'Apache Version 2.0'
      function(argument) {
        return argument.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, "-$2");
      },
      // e.g. 'Apache Version 2'
      function(argument) {
        return argument.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, "-$2.0");
      },
      // e.g. 'ZLIB'
      function(argument) {
        return argument[0].toUpperCase() + argument.slice(1);
      },
      // e.g. 'MPL/2.0'
      function(argument) {
        return argument.replace("/", "-");
      },
      // e.g. 'Apache 2'
      function(argument) {
        return argument.replace(/\s*V\s*(\d)/, "-$1").replace(/(\d)$/, "$1.0");
      },
      // e.g. 'GPL-2.0', 'GPL-3.0'
      function(argument) {
        if (argument.indexOf("3.0") !== -1) {
          return argument + "-or-later";
        } else {
          return argument + "-only";
        }
      },
      // e.g. 'GPL-2.0-'
      function(argument) {
        return argument + "only";
      },
      // e.g. 'GPL2'
      function(argument) {
        return argument.replace(/(\d)$/, "-$1.0");
      },
      // e.g. 'BSD 3'
      function(argument) {
        return argument.replace(/(-| )?(\d)$/, "-$2-Clause");
      },
      // e.g. 'BSD clause 3'
      function(argument) {
        return argument.replace(/(-| )clause(-| )(\d)/, "-$3-Clause");
      },
      // e.g. 'New BSD license'
      function(argument) {
        return argument.replace(/\b(Modified|New|Revised)(-| )?BSD((-| )License)?/i, "BSD-3-Clause");
      },
      // e.g. 'Simplified BSD license'
      function(argument) {
        return argument.replace(/\bSimplified(-| )?BSD((-| )License)?/i, "BSD-2-Clause");
      },
      // e.g. 'Free BSD license'
      function(argument) {
        return argument.replace(/\b(Free|Net)(-| )?BSD((-| )License)?/i, "BSD-2-Clause-$1BSD");
      },
      // e.g. 'Clear BSD license'
      function(argument) {
        return argument.replace(/\bClear(-| )?BSD((-| )License)?/i, "BSD-3-Clause-Clear");
      },
      // e.g. 'Old BSD License'
      function(argument) {
        return argument.replace(/\b(Old|Original)(-| )?BSD((-| )License)?/i, "BSD-4-Clause");
      },
      // e.g. 'BY-NC-4.0'
      function(argument) {
        return "CC-" + argument;
      },
      // e.g. 'BY-NC'
      function(argument) {
        return "CC-" + argument + "-4.0";
      },
      // e.g. 'Attribution-NonCommercial'
      function(argument) {
        return argument.replace("Attribution", "BY").replace("NonCommercial", "NC").replace("NoDerivatives", "ND").replace(/ (\d)/, "-$1").replace(/ ?International/, "");
      },
      // e.g. 'Attribution-NonCommercial'
      function(argument) {
        return "CC-" + argument.replace("Attribution", "BY").replace("NonCommercial", "NC").replace("NoDerivatives", "ND").replace(/ (\d)/, "-$1").replace(/ ?International/, "") + "-4.0";
      }
    ];
    var licensesWithVersions = spdxLicenseIds.map(function(id) {
      var match2 = /^(.*)-\d+\.\d+$/.exec(id);
      return match2 ? [match2[0], match2[1]] : [id, null];
    }).reduce(function(objectMap, item) {
      var key = item[1];
      objectMap[key] = objectMap[key] || [];
      objectMap[key].push(item[0]);
      return objectMap;
    }, {});
    var licensesWithOneVersion = Object.keys(licensesWithVersions).map(/* @__PURE__ */ __name(function makeEntries(key) {
      return [key, licensesWithVersions[key]];
    }, "makeEntries")).filter(/* @__PURE__ */ __name(function identifySoleVersions(item) {
      return (
        // Licenses has just one valid version suffix.
        item[1].length === 1 && item[0] !== null && // APL will be considered Apache, rather than APL-1.0
        item[0] !== "APL"
      );
    }, "identifySoleVersions")).map(/* @__PURE__ */ __name(function createLastResorts(item) {
      return [item[0], item[1][0]];
    }, "createLastResorts"));
    licensesWithVersions = void 0;
    var lastResorts = [
      ["UNLI", "Unlicense"],
      ["WTF", "WTFPL"],
      ["2 CLAUSE", "BSD-2-Clause"],
      ["2-CLAUSE", "BSD-2-Clause"],
      ["3 CLAUSE", "BSD-3-Clause"],
      ["3-CLAUSE", "BSD-3-Clause"],
      ["AFFERO", "AGPL-3.0-or-later"],
      ["AGPL", "AGPL-3.0-or-later"],
      ["APACHE", "Apache-2.0"],
      ["ARTISTIC", "Artistic-2.0"],
      ["Affero", "AGPL-3.0-or-later"],
      ["BEER", "Beerware"],
      ["BOOST", "BSL-1.0"],
      ["BSD", "BSD-2-Clause"],
      ["CDDL", "CDDL-1.1"],
      ["ECLIPSE", "EPL-1.0"],
      ["FUCK", "WTFPL"],
      ["GNU", "GPL-3.0-or-later"],
      ["LGPL", "LGPL-3.0-or-later"],
      ["GPLV1", "GPL-1.0-only"],
      ["GPL-1", "GPL-1.0-only"],
      ["GPLV2", "GPL-2.0-only"],
      ["GPL-2", "GPL-2.0-only"],
      ["GPL", "GPL-3.0-or-later"],
      ["MIT +NO-FALSE-ATTRIBS", "MITNFA"],
      ["MIT", "MIT"],
      ["MPL", "MPL-2.0"],
      ["X11", "X11"],
      ["ZLIB", "Zlib"]
    ].concat(licensesWithOneVersion).sort(sortTranspositions);
    var SUBSTRING = 0;
    var IDENTIFIER2 = 1;
    var validTransformation = /* @__PURE__ */ __name(function(identifier2) {
      for (var i = 0; i < transforms.length; i++) {
        var transformed = transforms[i](identifier2).trim();
        if (transformed !== identifier2 && valid(transformed)) {
          return transformed;
        }
      }
      return null;
    }, "validTransformation");
    var validLastResort = /* @__PURE__ */ __name(function(identifier2) {
      var upperCased = identifier2.toUpperCase();
      for (var i = 0; i < lastResorts.length; i++) {
        var lastResort = lastResorts[i];
        if (upperCased.indexOf(lastResort[SUBSTRING]) > -1) {
          return lastResort[IDENTIFIER2];
        }
      }
      return null;
    }, "validLastResort");
    var anyCorrection = /* @__PURE__ */ __name(function(identifier2, check) {
      for (var i = 0; i < transpositions.length; i++) {
        var transposition = transpositions[i];
        var transposed = transposition[TRANSPOSED];
        if (identifier2.indexOf(transposed) > -1) {
          var corrected = identifier2.replace(
            transposed,
            transposition[CORRECT]
          );
          var checked = check(corrected);
          if (checked !== null) {
            return checked;
          }
        }
      }
      return null;
    }, "anyCorrection");
    module2.exports = function(identifier2, options2) {
      options2 = options2 || {};
      var upgrade = options2.upgrade === void 0 ? true : !!options2.upgrade;
      function postprocess(value) {
        return upgrade ? upgradeGPLs(value) : value;
      }
      __name(postprocess, "postprocess");
      var validArugment = typeof identifier2 === "string" && identifier2.trim().length !== 0;
      if (!validArugment) {
        throw Error("Invalid argument. Expected non-empty string.");
      }
      identifier2 = identifier2.trim();
      if (valid(identifier2)) {
        return postprocess(identifier2);
      }
      var noPlus = identifier2.replace(/\+$/, "").trim();
      if (valid(noPlus)) {
        return postprocess(noPlus);
      }
      var transformed = validTransformation(identifier2);
      if (transformed !== null) {
        return postprocess(transformed);
      }
      transformed = anyCorrection(identifier2, function(argument) {
        if (valid(argument)) {
          return argument;
        }
        return validTransformation(argument);
      });
      if (transformed !== null) {
        return postprocess(transformed);
      }
      transformed = validLastResort(identifier2);
      if (transformed !== null) {
        return postprocess(transformed);
      }
      transformed = anyCorrection(identifier2, validLastResort);
      if (transformed !== null) {
        return postprocess(transformed);
      }
      return null;
    };
    function upgradeGPLs(value) {
      if ([
        "GPL-1.0",
        "LGPL-1.0",
        "AGPL-1.0",
        "GPL-2.0",
        "LGPL-2.0",
        "AGPL-2.0",
        "LGPL-2.1"
      ].indexOf(value) !== -1) {
        return value + "-only";
      } else if ([
        "GPL-1.0+",
        "GPL-2.0+",
        "GPL-3.0+",
        "LGPL-2.0+",
        "LGPL-2.1+",
        "LGPL-3.0+",
        "AGPL-1.0+",
        "AGPL-3.0+"
      ].indexOf(value) !== -1) {
        return value.replace(/\+$/, "-or-later");
      } else if (["GPL-3.0", "LGPL-3.0", "AGPL-3.0"].indexOf(value) !== -1) {
        return value + "-or-later";
      } else {
        return value;
      }
    }
    __name(upgradeGPLs, "upgradeGPLs");
  }
});

// node_modules/validate-npm-package-license/index.js
var require_validate_npm_package_license = __commonJS({
  "node_modules/validate-npm-package-license/index.js"(exports2, module2) {
    init_esbuild_shims();
    var parse12 = require_spdx_expression_parse();
    var correct = require_spdx_correct();
    var genericWarning = 'license should be a valid SPDX license expression (without "LicenseRef"), "UNLICENSED", or "SEE LICENSE IN <filename>"';
    var fileReferenceRE = /^SEE LICEN[CS]E IN (.+)$/;
    function startsWith(prefix, string) {
      return string.slice(0, prefix.length) === prefix;
    }
    __name(startsWith, "startsWith");
    function usesLicenseRef(ast) {
      if (ast.hasOwnProperty("license")) {
        var license = ast.license;
        return startsWith("LicenseRef", license) || startsWith("DocumentRef", license);
      } else {
        return usesLicenseRef(ast.left) || usesLicenseRef(ast.right);
      }
    }
    __name(usesLicenseRef, "usesLicenseRef");
    module2.exports = function(argument) {
      var ast;
      try {
        ast = parse12(argument);
      } catch (e2) {
        var match2;
        if (argument === "UNLICENSED" || argument === "UNLICENCED") {
          return {
            validForOldPackages: true,
            validForNewPackages: true,
            unlicensed: true
          };
        } else if (match2 = fileReferenceRE.exec(argument)) {
          return {
            validForOldPackages: true,
            validForNewPackages: true,
            inFile: match2[1]
          };
        } else {
          var result = {
            validForOldPackages: false,
            validForNewPackages: false,
            warnings: [genericWarning]
          };
          if (argument.trim().length !== 0) {
            var corrected = correct(argument);
            if (corrected) {
              result.warnings.push(
                'license is similar to the valid expression "' + corrected + '"'
              );
            }
          }
          return result;
        }
      }
      if (usesLicenseRef(ast)) {
        return {
          validForNewPackages: false,
          validForOldPackages: false,
          spdx: true,
          warnings: [genericWarning]
        };
      } else {
        return {
          validForNewPackages: true,
          validForOldPackages: true,
          spdx: true
        };
      }
    };
  }
});

// node_modules/lru-cache/dist/commonjs/index.js
var require_commonjs = __commonJS({
  "node_modules/lru-cache/dist/commonjs/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LRUCache = void 0;
    var perf2 = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
    var warned2 = /* @__PURE__ */ new Set();
    var PROCESS4 = typeof process === "object" && !!process ? process : {};
    var emitWarning2 = /* @__PURE__ */ __name((msg, type, code2, fn) => {
      typeof PROCESS4.emitWarning === "function" ? PROCESS4.emitWarning(msg, type, code2, fn) : console.error(`[${code2}] ${type}: ${msg}`);
    }, "emitWarning");
    var AC2 = globalThis.AbortController;
    var AS2 = globalThis.AbortSignal;
    if (typeof AC2 === "undefined") {
      AS2 = class AbortSignal {
        static {
          __name(this, "AbortSignal");
        }
        onabort;
        _onabort = [];
        reason;
        aborted = false;
        addEventListener(_, fn) {
          this._onabort.push(fn);
        }
      };
      AC2 = class AbortController {
        static {
          __name(this, "AbortController");
        }
        constructor() {
          warnACPolyfill();
        }
        signal = new AS2();
        abort(reason) {
          if (this.signal.aborted)
            return;
          this.signal.reason = reason;
          this.signal.aborted = true;
          for (const fn of this.signal._onabort) {
            fn(reason);
          }
          this.signal.onabort?.(reason);
        }
      };
      let printACPolyfillWarning = PROCESS4.env?.LRU_CACHE_IGNORE_AC_WARNING !== "1";
      const warnACPolyfill = /* @__PURE__ */ __name(() => {
        if (!printACPolyfillWarning)
          return;
        printACPolyfillWarning = false;
        emitWarning2("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", warnACPolyfill);
      }, "warnACPolyfill");
    }
    var shouldWarn2 = /* @__PURE__ */ __name((code2) => !warned2.has(code2), "shouldWarn");
    var TYPE2 = Symbol("type");
    var isPosInt2 = /* @__PURE__ */ __name((n2) => n2 && n2 === Math.floor(n2) && n2 > 0 && isFinite(n2), "isPosInt");
    var getUintArray2 = /* @__PURE__ */ __name((max) => !isPosInt2(max) ? null : max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray2 : null, "getUintArray");
    var ZeroArray2 = class extends Array {
      static {
        __name(this, "ZeroArray");
      }
      constructor(size) {
        super(size);
        this.fill(0);
      }
    };
    var Stack2 = class _Stack {
      static {
        __name(this, "Stack");
      }
      heap;
      length;
      // private constructor
      static #constructing = false;
      static create(max) {
        const HeapCls = getUintArray2(max);
        if (!HeapCls)
          return [];
        _Stack.#constructing = true;
        const s2 = new _Stack(max, HeapCls);
        _Stack.#constructing = false;
        return s2;
      }
      constructor(max, HeapCls) {
        if (!_Stack.#constructing) {
          throw new TypeError("instantiate Stack using Stack.create(n)");
        }
        this.heap = new HeapCls(max);
        this.length = 0;
      }
      push(n2) {
        this.heap[this.length++] = n2;
      }
      pop() {
        return this.heap[--this.length];
      }
    };
    var LRUCache2 = class _LRUCache {
      static {
        __name(this, "LRUCache");
      }
      // options that cannot be changed without disaster
      #max;
      #maxSize;
      #dispose;
      #disposeAfter;
      #fetchMethod;
      #memoMethod;
      /**
       * {@link LRUCache.OptionsBase.ttl}
       */
      ttl;
      /**
       * {@link LRUCache.OptionsBase.ttlResolution}
       */
      ttlResolution;
      /**
       * {@link LRUCache.OptionsBase.ttlAutopurge}
       */
      ttlAutopurge;
      /**
       * {@link LRUCache.OptionsBase.updateAgeOnGet}
       */
      updateAgeOnGet;
      /**
       * {@link LRUCache.OptionsBase.updateAgeOnHas}
       */
      updateAgeOnHas;
      /**
       * {@link LRUCache.OptionsBase.allowStale}
       */
      allowStale;
      /**
       * {@link LRUCache.OptionsBase.noDisposeOnSet}
       */
      noDisposeOnSet;
      /**
       * {@link LRUCache.OptionsBase.noUpdateTTL}
       */
      noUpdateTTL;
      /**
       * {@link LRUCache.OptionsBase.maxEntrySize}
       */
      maxEntrySize;
      /**
       * {@link LRUCache.OptionsBase.sizeCalculation}
       */
      sizeCalculation;
      /**
       * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
       */
      noDeleteOnFetchRejection;
      /**
       * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
       */
      noDeleteOnStaleGet;
      /**
       * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
       */
      allowStaleOnFetchAbort;
      /**
       * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
       */
      allowStaleOnFetchRejection;
      /**
       * {@link LRUCache.OptionsBase.ignoreFetchAbort}
       */
      ignoreFetchAbort;
      // computed properties
      #size;
      #calculatedSize;
      #keyMap;
      #keyList;
      #valList;
      #next;
      #prev;
      #head;
      #tail;
      #free;
      #disposed;
      #sizes;
      #starts;
      #ttls;
      #hasDispose;
      #hasFetchMethod;
      #hasDisposeAfter;
      /**
       * Do not call this method unless you need to inspect the
       * inner workings of the cache.  If anything returned by this
       * object is modified in any way, strange breakage may occur.
       *
       * These fields are private for a reason!
       *
       * @internal
       */
      static unsafeExposeInternals(c3) {
        return {
          // properties
          starts: c3.#starts,
          ttls: c3.#ttls,
          sizes: c3.#sizes,
          keyMap: c3.#keyMap,
          keyList: c3.#keyList,
          valList: c3.#valList,
          next: c3.#next,
          prev: c3.#prev,
          get head() {
            return c3.#head;
          },
          get tail() {
            return c3.#tail;
          },
          free: c3.#free,
          // methods
          isBackgroundFetch: /* @__PURE__ */ __name((p) => c3.#isBackgroundFetch(p), "isBackgroundFetch"),
          backgroundFetch: /* @__PURE__ */ __name((k, index, options2, context2) => c3.#backgroundFetch(k, index, options2, context2), "backgroundFetch"),
          moveToTail: /* @__PURE__ */ __name((index) => c3.#moveToTail(index), "moveToTail"),
          indexes: /* @__PURE__ */ __name((options2) => c3.#indexes(options2), "indexes"),
          rindexes: /* @__PURE__ */ __name((options2) => c3.#rindexes(options2), "rindexes"),
          isStale: /* @__PURE__ */ __name((index) => c3.#isStale(index), "isStale")
        };
      }
      // Protected read-only members
      /**
       * {@link LRUCache.OptionsBase.max} (read-only)
       */
      get max() {
        return this.#max;
      }
      /**
       * {@link LRUCache.OptionsBase.maxSize} (read-only)
       */
      get maxSize() {
        return this.#maxSize;
      }
      /**
       * The total computed size of items in the cache (read-only)
       */
      get calculatedSize() {
        return this.#calculatedSize;
      }
      /**
       * The number of items stored in the cache (read-only)
       */
      get size() {
        return this.#size;
      }
      /**
       * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
       */
      get fetchMethod() {
        return this.#fetchMethod;
      }
      get memoMethod() {
        return this.#memoMethod;
      }
      /**
       * {@link LRUCache.OptionsBase.dispose} (read-only)
       */
      get dispose() {
        return this.#dispose;
      }
      /**
       * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
       */
      get disposeAfter() {
        return this.#disposeAfter;
      }
      constructor(options2) {
        const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort } = options2;
        if (max !== 0 && !isPosInt2(max)) {
          throw new TypeError("max option must be a nonnegative integer");
        }
        const UintArray = max ? getUintArray2(max) : Array;
        if (!UintArray) {
          throw new Error("invalid max value: " + max);
        }
        this.#max = max;
        this.#maxSize = maxSize;
        this.maxEntrySize = maxEntrySize || this.#maxSize;
        this.sizeCalculation = sizeCalculation;
        if (this.sizeCalculation) {
          if (!this.#maxSize && !this.maxEntrySize) {
            throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
          }
          if (typeof this.sizeCalculation !== "function") {
            throw new TypeError("sizeCalculation set to non-function");
          }
        }
        if (memoMethod !== void 0 && typeof memoMethod !== "function") {
          throw new TypeError("memoMethod must be a function if defined");
        }
        this.#memoMethod = memoMethod;
        if (fetchMethod !== void 0 && typeof fetchMethod !== "function") {
          throw new TypeError("fetchMethod must be a function if specified");
        }
        this.#fetchMethod = fetchMethod;
        this.#hasFetchMethod = !!fetchMethod;
        this.#keyMap = /* @__PURE__ */ new Map();
        this.#keyList = new Array(max).fill(void 0);
        this.#valList = new Array(max).fill(void 0);
        this.#next = new UintArray(max);
        this.#prev = new UintArray(max);
        this.#head = 0;
        this.#tail = 0;
        this.#free = Stack2.create(max);
        this.#size = 0;
        this.#calculatedSize = 0;
        if (typeof dispose === "function") {
          this.#dispose = dispose;
        }
        if (typeof disposeAfter === "function") {
          this.#disposeAfter = disposeAfter;
          this.#disposed = [];
        } else {
          this.#disposeAfter = void 0;
          this.#disposed = void 0;
        }
        this.#hasDispose = !!this.#dispose;
        this.#hasDisposeAfter = !!this.#disposeAfter;
        this.noDisposeOnSet = !!noDisposeOnSet;
        this.noUpdateTTL = !!noUpdateTTL;
        this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
        this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
        this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
        this.ignoreFetchAbort = !!ignoreFetchAbort;
        if (this.maxEntrySize !== 0) {
          if (this.#maxSize !== 0) {
            if (!isPosInt2(this.#maxSize)) {
              throw new TypeError("maxSize must be a positive integer if specified");
            }
          }
          if (!isPosInt2(this.maxEntrySize)) {
            throw new TypeError("maxEntrySize must be a positive integer if specified");
          }
          this.#initializeSizeTracking();
        }
        this.allowStale = !!allowStale;
        this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
        this.updateAgeOnGet = !!updateAgeOnGet;
        this.updateAgeOnHas = !!updateAgeOnHas;
        this.ttlResolution = isPosInt2(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1;
        this.ttlAutopurge = !!ttlAutopurge;
        this.ttl = ttl || 0;
        if (this.ttl) {
          if (!isPosInt2(this.ttl)) {
            throw new TypeError("ttl must be a positive integer if specified");
          }
          this.#initializeTTLTracking();
        }
        if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
          throw new TypeError("At least one of max, maxSize, or ttl is required");
        }
        if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
          const code2 = "LRU_CACHE_UNBOUNDED";
          if (shouldWarn2(code2)) {
            warned2.add(code2);
            const msg = "TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.";
            emitWarning2(msg, "UnboundedCacheWarning", code2, _LRUCache);
          }
        }
      }
      /**
       * Return the number of ms left in the item's TTL. If item is not in cache,
       * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
       */
      getRemainingTTL(key) {
        return this.#keyMap.has(key) ? Infinity : 0;
      }
      #initializeTTLTracking() {
        const ttls = new ZeroArray2(this.#max);
        const starts = new ZeroArray2(this.#max);
        this.#ttls = ttls;
        this.#starts = starts;
        this.#setItemTTL = (index, ttl, start = perf2.now()) => {
          starts[index] = ttl !== 0 ? start : 0;
          ttls[index] = ttl;
          if (ttl !== 0 && this.ttlAutopurge) {
            const t2 = setTimeout(() => {
              if (this.#isStale(index)) {
                this.#delete(this.#keyList[index], "expire");
              }
            }, ttl + 1);
            if (t2.unref) {
              t2.unref();
            }
          }
        };
        this.#updateItemAge = (index) => {
          starts[index] = ttls[index] !== 0 ? perf2.now() : 0;
        };
        this.#statusTTL = (status, index) => {
          if (ttls[index]) {
            const ttl = ttls[index];
            const start = starts[index];
            if (!ttl || !start)
              return;
            status.ttl = ttl;
            status.start = start;
            status.now = cachedNow || getNow();
            const age = status.now - start;
            status.remainingTTL = ttl - age;
          }
        };
        let cachedNow = 0;
        const getNow = /* @__PURE__ */ __name(() => {
          const n2 = perf2.now();
          if (this.ttlResolution > 0) {
            cachedNow = n2;
            const t2 = setTimeout(() => cachedNow = 0, this.ttlResolution);
            if (t2.unref) {
              t2.unref();
            }
          }
          return n2;
        }, "getNow");
        this.getRemainingTTL = (key) => {
          const index = this.#keyMap.get(key);
          if (index === void 0) {
            return 0;
          }
          const ttl = ttls[index];
          const start = starts[index];
          if (!ttl || !start) {
            return Infinity;
          }
          const age = (cachedNow || getNow()) - start;
          return ttl - age;
        };
        this.#isStale = (index) => {
          const s2 = starts[index];
          const t2 = ttls[index];
          return !!t2 && !!s2 && (cachedNow || getNow()) - s2 > t2;
        };
      }
      // conditionally set private methods related to TTL
      #updateItemAge = /* @__PURE__ */ __name(() => {
      }, "#updateItemAge");
      #statusTTL = /* @__PURE__ */ __name(() => {
      }, "#statusTTL");
      #setItemTTL = /* @__PURE__ */ __name(() => {
      }, "#setItemTTL");
      /* c8 ignore stop */
      #isStale = /* @__PURE__ */ __name(() => false, "#isStale");
      #initializeSizeTracking() {
        const sizes = new ZeroArray2(this.#max);
        this.#calculatedSize = 0;
        this.#sizes = sizes;
        this.#removeItemSize = (index) => {
          this.#calculatedSize -= sizes[index];
          sizes[index] = 0;
        };
        this.#requireSize = (k, v, size, sizeCalculation) => {
          if (this.#isBackgroundFetch(v)) {
            return 0;
          }
          if (!isPosInt2(size)) {
            if (sizeCalculation) {
              if (typeof sizeCalculation !== "function") {
                throw new TypeError("sizeCalculation must be a function");
              }
              size = sizeCalculation(v, k);
              if (!isPosInt2(size)) {
                throw new TypeError("sizeCalculation return invalid (expect positive integer)");
              }
            } else {
              throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");
            }
          }
          return size;
        };
        this.#addItemSize = (index, size, status) => {
          sizes[index] = size;
          if (this.#maxSize) {
            const maxSize = this.#maxSize - sizes[index];
            while (this.#calculatedSize > maxSize) {
              this.#evict(true);
            }
          }
          this.#calculatedSize += sizes[index];
          if (status) {
            status.entrySize = size;
            status.totalCalculatedSize = this.#calculatedSize;
          }
        };
      }
      #removeItemSize = /* @__PURE__ */ __name((_i) => {
      }, "#removeItemSize");
      #addItemSize = /* @__PURE__ */ __name((_i, _s, _st) => {
      }, "#addItemSize");
      #requireSize = /* @__PURE__ */ __name((_k, _v, size, sizeCalculation) => {
        if (size || sizeCalculation) {
          throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
        }
        return 0;
      }, "#requireSize");
      *#indexes({ allowStale = this.allowStale } = {}) {
        if (this.#size) {
          for (let i = this.#tail; true; ) {
            if (!this.#isValidIndex(i)) {
              break;
            }
            if (allowStale || !this.#isStale(i)) {
              yield i;
            }
            if (i === this.#head) {
              break;
            } else {
              i = this.#prev[i];
            }
          }
        }
      }
      *#rindexes({ allowStale = this.allowStale } = {}) {
        if (this.#size) {
          for (let i = this.#head; true; ) {
            if (!this.#isValidIndex(i)) {
              break;
            }
            if (allowStale || !this.#isStale(i)) {
              yield i;
            }
            if (i === this.#tail) {
              break;
            } else {
              i = this.#next[i];
            }
          }
        }
      }
      #isValidIndex(index) {
        return index !== void 0 && this.#keyMap.get(this.#keyList[index]) === index;
      }
      /**
       * Return a generator yielding `[key, value]` pairs,
       * in order from most recently used to least recently used.
       */
      *entries() {
        for (const i of this.#indexes()) {
          if (this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
            yield [this.#keyList[i], this.#valList[i]];
          }
        }
      }
      /**
       * Inverse order version of {@link LRUCache.entries}
       *
       * Return a generator yielding `[key, value]` pairs,
       * in order from least recently used to most recently used.
       */
      *rentries() {
        for (const i of this.#rindexes()) {
          if (this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
            yield [this.#keyList[i], this.#valList[i]];
          }
        }
      }
      /**
       * Return a generator yielding the keys in the cache,
       * in order from most recently used to least recently used.
       */
      *keys() {
        for (const i of this.#indexes()) {
          const k = this.#keyList[i];
          if (k !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
            yield k;
          }
        }
      }
      /**
       * Inverse order version of {@link LRUCache.keys}
       *
       * Return a generator yielding the keys in the cache,
       * in order from least recently used to most recently used.
       */
      *rkeys() {
        for (const i of this.#rindexes()) {
          const k = this.#keyList[i];
          if (k !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
            yield k;
          }
        }
      }
      /**
       * Return a generator yielding the values in the cache,
       * in order from most recently used to least recently used.
       */
      *values() {
        for (const i of this.#indexes()) {
          const v = this.#valList[i];
          if (v !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
            yield this.#valList[i];
          }
        }
      }
      /**
       * Inverse order version of {@link LRUCache.values}
       *
       * Return a generator yielding the values in the cache,
       * in order from least recently used to most recently used.
       */
      *rvalues() {
        for (const i of this.#rindexes()) {
          const v = this.#valList[i];
          if (v !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
            yield this.#valList[i];
          }
        }
      }
      /**
       * Iterating over the cache itself yields the same results as
       * {@link LRUCache.entries}
       */
      [Symbol.iterator]() {
        return this.entries();
      }
      /**
       * A String value that is used in the creation of the default string
       * description of an object. Called by the built-in method
       * `Object.prototype.toString`.
       */
      [Symbol.toStringTag] = "LRUCache";
      /**
       * Find a value for which the supplied fn method returns a truthy value,
       * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.
       */
      find(fn, getOptions2 = {}) {
        for (const i of this.#indexes()) {
          const v = this.#valList[i];
          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0)
            continue;
          if (fn(value, this.#keyList[i], this)) {
            return this.get(this.#keyList[i], getOptions2);
          }
        }
      }
      /**
       * Call the supplied function on each item in the cache, in order from most
       * recently used to least recently used.
       *
       * `fn` is called as `fn(value, key, cache)`.
       *
       * If `thisp` is provided, function will be called in the `this`-context of
       * the provided object, or the cache if no `thisp` object is provided.
       *
       * Does not update age or recenty of use, or iterate over stale values.
       */
      forEach(fn, thisp = this) {
        for (const i of this.#indexes()) {
          const v = this.#valList[i];
          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0)
            continue;
          fn.call(thisp, value, this.#keyList[i], this);
        }
      }
      /**
       * The same as {@link LRUCache.forEach} but items are iterated over in
       * reverse order.  (ie, less recently used items are iterated over first.)
       */
      rforEach(fn, thisp = this) {
        for (const i of this.#rindexes()) {
          const v = this.#valList[i];
          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0)
            continue;
          fn.call(thisp, value, this.#keyList[i], this);
        }
      }
      /**
       * Delete any stale entries. Returns true if anything was removed,
       * false otherwise.
       */
      purgeStale() {
        let deleted = false;
        for (const i of this.#rindexes({ allowStale: true })) {
          if (this.#isStale(i)) {
            this.#delete(this.#keyList[i], "expire");
            deleted = true;
          }
        }
        return deleted;
      }
      /**
       * Get the extended info about a given entry, to get its value, size, and
       * TTL info simultaneously. Returns `undefined` if the key is not present.
       *
       * Unlike {@link LRUCache#dump}, which is designed to be portable and survive
       * serialization, the `start` value is always the current timestamp, and the
       * `ttl` is a calculated remaining time to live (negative if expired).
       *
       * Always returns stale values, if their info is found in the cache, so be
       * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
       * if relevant.
       */
      info(key) {
        const i = this.#keyMap.get(key);
        if (i === void 0)
          return void 0;
        const v = this.#valList[i];
        const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
        if (value === void 0)
          return void 0;
        const entry = { value };
        if (this.#ttls && this.#starts) {
          const ttl = this.#ttls[i];
          const start = this.#starts[i];
          if (ttl && start) {
            const remain = ttl - (perf2.now() - start);
            entry.ttl = remain;
            entry.start = Date.now();
          }
        }
        if (this.#sizes) {
          entry.size = this.#sizes[i];
        }
        return entry;
      }
      /**
       * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
       * passed to {@link LRLUCache#load}.
       *
       * The `start` fields are calculated relative to a portable `Date.now()`
       * timestamp, even if `performance.now()` is available.
       *
       * Stale entries are always included in the `dump`, even if
       * {@link LRUCache.OptionsBase.allowStale} is false.
       *
       * Note: this returns an actual array, not a generator, so it can be more
       * easily passed around.
       */
      dump() {
        const arr = [];
        for (const i of this.#indexes({ allowStale: true })) {
          const key = this.#keyList[i];
          const v = this.#valList[i];
          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0 || key === void 0)
            continue;
          const entry = { value };
          if (this.#ttls && this.#starts) {
            entry.ttl = this.#ttls[i];
            const age = perf2.now() - this.#starts[i];
            entry.start = Math.floor(Date.now() - age);
          }
          if (this.#sizes) {
            entry.size = this.#sizes[i];
          }
          arr.unshift([key, entry]);
        }
        return arr;
      }
      /**
       * Reset the cache and load in the items in entries in the order listed.
       *
       * The shape of the resulting cache may be different if the same options are
       * not used in both caches.
       *
       * The `start` fields are assumed to be calculated relative to a portable
       * `Date.now()` timestamp, even if `performance.now()` is available.
       */
      load(arr) {
        this.clear();
        for (const [key, entry] of arr) {
          if (entry.start) {
            const age = Date.now() - entry.start;
            entry.start = perf2.now() - age;
          }
          this.set(key, entry.value, entry);
        }
      }
      /**
       * Add a value to the cache.
       *
       * Note: if `undefined` is specified as a value, this is an alias for
       * {@link LRUCache#delete}
       *
       * Fields on the {@link LRUCache.SetOptions} options param will override
       * their corresponding values in the constructor options for the scope
       * of this single `set()` operation.
       *
       * If `start` is provided, then that will set the effective start
       * time for the TTL calculation. Note that this must be a previous
       * value of `performance.now()` if supported, or a previous value of
       * `Date.now()` if not.
       *
       * Options object may also include `size`, which will prevent
       * calling the `sizeCalculation` function and just use the specified
       * number if it is a positive integer, and `noDisposeOnSet` which
       * will prevent calling a `dispose` function in the case of
       * overwrites.
       *
       * If the `size` (or return value of `sizeCalculation`) for a given
       * entry is greater than `maxEntrySize`, then the item will not be
       * added to the cache.
       *
       * Will update the recency of the entry.
       *
       * If the value is `undefined`, then this is an alias for
       * `cache.delete(key)`. `undefined` is never stored in the cache.
       */
      set(k, v, setOptions2 = {}) {
        if (v === void 0) {
          this.delete(k);
          return this;
        }
        const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions2;
        let { noUpdateTTL = this.noUpdateTTL } = setOptions2;
        const size = this.#requireSize(k, v, setOptions2.size || 0, sizeCalculation);
        if (this.maxEntrySize && size > this.maxEntrySize) {
          if (status) {
            status.set = "miss";
            status.maxEntrySizeExceeded = true;
          }
          this.#delete(k, "set");
          return this;
        }
        let index = this.#size === 0 ? void 0 : this.#keyMap.get(k);
        if (index === void 0) {
          index = this.#size === 0 ? this.#tail : this.#free.length !== 0 ? this.#free.pop() : this.#size === this.#max ? this.#evict(false) : this.#size;
          this.#keyList[index] = k;
          this.#valList[index] = v;
          this.#keyMap.set(k, index);
          this.#next[this.#tail] = index;
          this.#prev[index] = this.#tail;
          this.#tail = index;
          this.#size++;
          this.#addItemSize(index, size, status);
          if (status)
            status.set = "add";
          noUpdateTTL = false;
        } else {
          this.#moveToTail(index);
          const oldVal = this.#valList[index];
          if (v !== oldVal) {
            if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
              oldVal.__abortController.abort(new Error("replaced"));
              const { __staleWhileFetching: s2 } = oldVal;
              if (s2 !== void 0 && !noDisposeOnSet) {
                if (this.#hasDispose) {
                  this.#dispose?.(s2, k, "set");
                }
                if (this.#hasDisposeAfter) {
                  this.#disposed?.push([s2, k, "set"]);
                }
              }
            } else if (!noDisposeOnSet) {
              if (this.#hasDispose) {
                this.#dispose?.(oldVal, k, "set");
              }
              if (this.#hasDisposeAfter) {
                this.#disposed?.push([oldVal, k, "set"]);
              }
            }
            this.#removeItemSize(index);
            this.#addItemSize(index, size, status);
            this.#valList[index] = v;
            if (status) {
              status.set = "replace";
              const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal;
              if (oldValue !== void 0)
                status.oldValue = oldValue;
            }
          } else if (status) {
            status.set = "update";
          }
        }
        if (ttl !== 0 && !this.#ttls) {
          this.#initializeTTLTracking();
        }
        if (this.#ttls) {
          if (!noUpdateTTL) {
            this.#setItemTTL(index, ttl, start);
          }
          if (status)
            this.#statusTTL(status, index);
        }
        if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
          const dt = this.#disposed;
          let task;
          while (task = dt?.shift()) {
            this.#disposeAfter?.(...task);
          }
        }
        return this;
      }
      /**
       * Evict the least recently used item, returning its value or
       * `undefined` if cache is empty.
       */
      pop() {
        try {
          while (this.#size) {
            const val = this.#valList[this.#head];
            this.#evict(true);
            if (this.#isBackgroundFetch(val)) {
              if (val.__staleWhileFetching) {
                return val.__staleWhileFetching;
              }
            } else if (val !== void 0) {
              return val;
            }
          }
        } finally {
          if (this.#hasDisposeAfter && this.#disposed) {
            const dt = this.#disposed;
            let task;
            while (task = dt?.shift()) {
              this.#disposeAfter?.(...task);
            }
          }
        }
      }
      #evict(free) {
        const head = this.#head;
        const k = this.#keyList[head];
        const v = this.#valList[head];
        if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
          v.__abortController.abort(new Error("evicted"));
        } else if (this.#hasDispose || this.#hasDisposeAfter) {
          if (this.#hasDispose) {
            this.#dispose?.(v, k, "evict");
          }
          if (this.#hasDisposeAfter) {
            this.#disposed?.push([v, k, "evict"]);
          }
        }
        this.#removeItemSize(head);
        if (free) {
          this.#keyList[head] = void 0;
          this.#valList[head] = void 0;
          this.#free.push(head);
        }
        if (this.#size === 1) {
          this.#head = this.#tail = 0;
          this.#free.length = 0;
        } else {
          this.#head = this.#next[head];
        }
        this.#keyMap.delete(k);
        this.#size--;
        return head;
      }
      /**
       * Check if a key is in the cache, without updating the recency of use.
       * Will return false if the item is stale, even though it is technically
       * in the cache.
       *
       * Check if a key is in the cache, without updating the recency of
       * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
       * to `true` in either the options or the constructor.
       *
       * Will return `false` if the item is stale, even though it is technically in
       * the cache. The difference can be determined (if it matters) by using a
       * `status` argument, and inspecting the `has` field.
       *
       * Will not update item age unless
       * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
       */
      has(k, hasOptions = {}) {
        const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
        const index = this.#keyMap.get(k);
        if (index !== void 0) {
          const v = this.#valList[index];
          if (this.#isBackgroundFetch(v) && v.__staleWhileFetching === void 0) {
            return false;
          }
          if (!this.#isStale(index)) {
            if (updateAgeOnHas) {
              this.#updateItemAge(index);
            }
            if (status) {
              status.has = "hit";
              this.#statusTTL(status, index);
            }
            return true;
          } else if (status) {
            status.has = "stale";
            this.#statusTTL(status, index);
          }
        } else if (status) {
          status.has = "miss";
        }
        return false;
      }
      /**
       * Like {@link LRUCache#get} but doesn't update recency or delete stale
       * items.
       *
       * Returns `undefined` if the item is stale, unless
       * {@link LRUCache.OptionsBase.allowStale} is set.
       */
      peek(k, peekOptions = {}) {
        const { allowStale = this.allowStale } = peekOptions;
        const index = this.#keyMap.get(k);
        if (index === void 0 || !allowStale && this.#isStale(index)) {
          return;
        }
        const v = this.#valList[index];
        return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
      }
      #backgroundFetch(k, index, options2, context2) {
        const v = index === void 0 ? void 0 : this.#valList[index];
        if (this.#isBackgroundFetch(v)) {
          return v;
        }
        const ac = new AC2();
        const { signal } = options2;
        signal?.addEventListener("abort", () => ac.abort(signal.reason), {
          signal: ac.signal
        });
        const fetchOpts = {
          signal: ac.signal,
          options: options2,
          context: context2
        };
        const cb = /* @__PURE__ */ __name((v2, updateCache = false) => {
          const { aborted } = ac.signal;
          const ignoreAbort = options2.ignoreFetchAbort && v2 !== void 0;
          if (options2.status) {
            if (aborted && !updateCache) {
              options2.status.fetchAborted = true;
              options2.status.fetchError = ac.signal.reason;
              if (ignoreAbort)
                options2.status.fetchAbortIgnored = true;
            } else {
              options2.status.fetchResolved = true;
            }
          }
          if (aborted && !ignoreAbort && !updateCache) {
            return fetchFail(ac.signal.reason);
          }
          const bf2 = p;
          if (this.#valList[index] === p) {
            if (v2 === void 0) {
              if (bf2.__staleWhileFetching) {
                this.#valList[index] = bf2.__staleWhileFetching;
              } else {
                this.#delete(k, "fetch");
              }
            } else {
              if (options2.status)
                options2.status.fetchUpdated = true;
              this.set(k, v2, fetchOpts.options);
            }
          }
          return v2;
        }, "cb");
        const eb = /* @__PURE__ */ __name((er) => {
          if (options2.status) {
            options2.status.fetchRejected = true;
            options2.status.fetchError = er;
          }
          return fetchFail(er);
        }, "eb");
        const fetchFail = /* @__PURE__ */ __name((er) => {
          const { aborted } = ac.signal;
          const allowStaleAborted = aborted && options2.allowStaleOnFetchAbort;
          const allowStale = allowStaleAborted || options2.allowStaleOnFetchRejection;
          const noDelete = allowStale || options2.noDeleteOnFetchRejection;
          const bf2 = p;
          if (this.#valList[index] === p) {
            const del = !noDelete || bf2.__staleWhileFetching === void 0;
            if (del) {
              this.#delete(k, "fetch");
            } else if (!allowStaleAborted) {
              this.#valList[index] = bf2.__staleWhileFetching;
            }
          }
          if (allowStale) {
            if (options2.status && bf2.__staleWhileFetching !== void 0) {
              options2.status.returnedStale = true;
            }
            return bf2.__staleWhileFetching;
          } else if (bf2.__returned === bf2) {
            throw er;
          }
        }, "fetchFail");
        const pcall = /* @__PURE__ */ __name((res, rej) => {
          const fmp = this.#fetchMethod?.(k, v, fetchOpts);
          if (fmp && fmp instanceof Promise) {
            fmp.then((v2) => res(v2 === void 0 ? void 0 : v2), rej);
          }
          ac.signal.addEventListener("abort", () => {
            if (!options2.ignoreFetchAbort || options2.allowStaleOnFetchAbort) {
              res(void 0);
              if (options2.allowStaleOnFetchAbort) {
                res = /* @__PURE__ */ __name((v2) => cb(v2, true), "res");
              }
            }
          });
        }, "pcall");
        if (options2.status)
          options2.status.fetchDispatched = true;
        const p = new Promise(pcall).then(cb, eb);
        const bf = Object.assign(p, {
          __abortController: ac,
          __staleWhileFetching: v,
          __returned: void 0
        });
        if (index === void 0) {
          this.set(k, bf, { ...fetchOpts.options, status: void 0 });
          index = this.#keyMap.get(k);
        } else {
          this.#valList[index] = bf;
        }
        return bf;
      }
      #isBackgroundFetch(p) {
        if (!this.#hasFetchMethod)
          return false;
        const b = p;
        return !!b && b instanceof Promise && b.hasOwnProperty("__staleWhileFetching") && b.__abortController instanceof AC2;
      }
      async fetch(k, fetchOptions = {}) {
        const {
          // get options
          allowStale = this.allowStale,
          updateAgeOnGet = this.updateAgeOnGet,
          noDeleteOnStaleGet = this.noDeleteOnStaleGet,
          // set options
          ttl = this.ttl,
          noDisposeOnSet = this.noDisposeOnSet,
          size = 0,
          sizeCalculation = this.sizeCalculation,
          noUpdateTTL = this.noUpdateTTL,
          // fetch exclusive options
          noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
          allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
          ignoreFetchAbort = this.ignoreFetchAbort,
          allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
          context: context2,
          forceRefresh = false,
          status,
          signal
        } = fetchOptions;
        if (!this.#hasFetchMethod) {
          if (status)
            status.fetch = "get";
          return this.get(k, {
            allowStale,
            updateAgeOnGet,
            noDeleteOnStaleGet,
            status
          });
        }
        const options2 = {
          allowStale,
          updateAgeOnGet,
          noDeleteOnStaleGet,
          ttl,
          noDisposeOnSet,
          size,
          sizeCalculation,
          noUpdateTTL,
          noDeleteOnFetchRejection,
          allowStaleOnFetchRejection,
          allowStaleOnFetchAbort,
          ignoreFetchAbort,
          status,
          signal
        };
        let index = this.#keyMap.get(k);
        if (index === void 0) {
          if (status)
            status.fetch = "miss";
          const p = this.#backgroundFetch(k, index, options2, context2);
          return p.__returned = p;
        } else {
          const v = this.#valList[index];
          if (this.#isBackgroundFetch(v)) {
            const stale = allowStale && v.__staleWhileFetching !== void 0;
            if (status) {
              status.fetch = "inflight";
              if (stale)
                status.returnedStale = true;
            }
            return stale ? v.__staleWhileFetching : v.__returned = v;
          }
          const isStale = this.#isStale(index);
          if (!forceRefresh && !isStale) {
            if (status)
              status.fetch = "hit";
            this.#moveToTail(index);
            if (updateAgeOnGet) {
              this.#updateItemAge(index);
            }
            if (status)
              this.#statusTTL(status, index);
            return v;
          }
          const p = this.#backgroundFetch(k, index, options2, context2);
          const hasStale = p.__staleWhileFetching !== void 0;
          const staleVal = hasStale && allowStale;
          if (status) {
            status.fetch = isStale ? "stale" : "refresh";
            if (staleVal && isStale)
              status.returnedStale = true;
          }
          return staleVal ? p.__staleWhileFetching : p.__returned = p;
        }
      }
      async forceFetch(k, fetchOptions = {}) {
        const v = await this.fetch(k, fetchOptions);
        if (v === void 0)
          throw new Error("fetch() returned undefined");
        return v;
      }
      memo(k, memoOptions = {}) {
        const memoMethod = this.#memoMethod;
        if (!memoMethod) {
          throw new Error("no memoMethod provided to constructor");
        }
        const { context: context2, forceRefresh, ...options2 } = memoOptions;
        const v = this.get(k, options2);
        if (!forceRefresh && v !== void 0)
          return v;
        const vv = memoMethod(k, v, {
          options: options2,
          context: context2
        });
        this.set(k, vv, options2);
        return vv;
      }
      /**
       * Return a value from the cache. Will update the recency of the cache
       * entry found.
       *
       * If the key is not found, get() will return `undefined`.
       */
      get(k, getOptions2 = {}) {
        const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions2;
        const index = this.#keyMap.get(k);
        if (index !== void 0) {
          const value = this.#valList[index];
          const fetching = this.#isBackgroundFetch(value);
          if (status)
            this.#statusTTL(status, index);
          if (this.#isStale(index)) {
            if (status)
              status.get = "stale";
            if (!fetching) {
              if (!noDeleteOnStaleGet) {
                this.#delete(k, "expire");
              }
              if (status && allowStale)
                status.returnedStale = true;
              return allowStale ? value : void 0;
            } else {
              if (status && allowStale && value.__staleWhileFetching !== void 0) {
                status.returnedStale = true;
              }
              return allowStale ? value.__staleWhileFetching : void 0;
            }
          } else {
            if (status)
              status.get = "hit";
            if (fetching) {
              return value.__staleWhileFetching;
            }
            this.#moveToTail(index);
            if (updateAgeOnGet) {
              this.#updateItemAge(index);
            }
            return value;
          }
        } else if (status) {
          status.get = "miss";
        }
      }
      #connect(p, n2) {
        this.#prev[n2] = p;
        this.#next[p] = n2;
      }
      #moveToTail(index) {
        if (index !== this.#tail) {
          if (index === this.#head) {
            this.#head = this.#next[index];
          } else {
            this.#connect(this.#prev[index], this.#next[index]);
          }
          this.#connect(this.#tail, index);
          this.#tail = index;
        }
      }
      /**
       * Deletes a key out of the cache.
       *
       * Returns true if the key was deleted, false otherwise.
       */
      delete(k) {
        return this.#delete(k, "delete");
      }
      #delete(k, reason) {
        let deleted = false;
        if (this.#size !== 0) {
          const index = this.#keyMap.get(k);
          if (index !== void 0) {
            deleted = true;
            if (this.#size === 1) {
              this.#clear(reason);
            } else {
              this.#removeItemSize(index);
              const v = this.#valList[index];
              if (this.#isBackgroundFetch(v)) {
                v.__abortController.abort(new Error("deleted"));
              } else if (this.#hasDispose || this.#hasDisposeAfter) {
                if (this.#hasDispose) {
                  this.#dispose?.(v, k, reason);
                }
                if (this.#hasDisposeAfter) {
                  this.#disposed?.push([v, k, reason]);
                }
              }
              this.#keyMap.delete(k);
              this.#keyList[index] = void 0;
              this.#valList[index] = void 0;
              if (index === this.#tail) {
                this.#tail = this.#prev[index];
              } else if (index === this.#head) {
                this.#head = this.#next[index];
              } else {
                const pi = this.#prev[index];
                this.#next[pi] = this.#next[index];
                const ni = this.#next[index];
                this.#prev[ni] = this.#prev[index];
              }
              this.#size--;
              this.#free.push(index);
            }
          }
        }
        if (this.#hasDisposeAfter && this.#disposed?.length) {
          const dt = this.#disposed;
          let task;
          while (task = dt?.shift()) {
            this.#disposeAfter?.(...task);
          }
        }
        return deleted;
      }
      /**
       * Clear the cache entirely, throwing away all values.
       */
      clear() {
        return this.#clear("delete");
      }
      #clear(reason) {
        for (const index of this.#rindexes({ allowStale: true })) {
          const v = this.#valList[index];
          if (this.#isBackgroundFetch(v)) {
            v.__abortController.abort(new Error("deleted"));
          } else {
            const k = this.#keyList[index];
            if (this.#hasDispose) {
              this.#dispose?.(v, k, reason);
            }
            if (this.#hasDisposeAfter) {
              this.#disposed?.push([v, k, reason]);
            }
          }
        }
        this.#keyMap.clear();
        this.#valList.fill(void 0);
        this.#keyList.fill(void 0);
        if (this.#ttls && this.#starts) {
          this.#ttls.fill(0);
          this.#starts.fill(0);
        }
        if (this.#sizes) {
          this.#sizes.fill(0);
        }
        this.#head = 0;
        this.#tail = 0;
        this.#free.length = 0;
        this.#calculatedSize = 0;
        this.#size = 0;
        if (this.#hasDisposeAfter && this.#disposed) {
          const dt = this.#disposed;
          let task;
          while (task = dt?.shift()) {
            this.#disposeAfter?.(...task);
          }
        }
      }
    };
    exports2.LRUCache = LRUCache2;
  }
});

// node_modules/hosted-git-info/lib/hosts.js
var require_hosts = __commonJS({
  "node_modules/hosted-git-info/lib/hosts.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var maybeJoin = /* @__PURE__ */ __name((...args) => args.every((arg) => arg) ? args.join("") : "", "maybeJoin");
    var maybeEncode = /* @__PURE__ */ __name((arg) => arg ? encodeURIComponent(arg) : "", "maybeEncode");
    var formatHashFragment = /* @__PURE__ */ __name((f) => f.toLowerCase().replace(/^\W+|\/|\W+$/g, "").replace(/\W+/g, "-"), "formatHashFragment");
    var defaults3 = {
      sshtemplate: /* @__PURE__ */ __name(({ domain, user, project, committish }) => `git@${domain}:${user}/${project}.git${maybeJoin("#", committish)}`, "sshtemplate"),
      sshurltemplate: /* @__PURE__ */ __name(({ domain, user, project, committish }) => `git+ssh://git@${domain}/${user}/${project}.git${maybeJoin("#", committish)}`, "sshurltemplate"),
      edittemplate: /* @__PURE__ */ __name(({ domain, user, project, committish, editpath, path: path108 }) => `https://${domain}/${user}/${project}${maybeJoin("/", editpath, "/", maybeEncode(committish || "HEAD"), "/", path108)}`, "edittemplate"),
      browsetemplate: /* @__PURE__ */ __name(({ domain, user, project, committish, treepath }) => `https://${domain}/${user}/${project}${maybeJoin("/", treepath, "/", maybeEncode(committish))}`, "browsetemplate"),
      browsetreetemplate: /* @__PURE__ */ __name(({ domain, user, project, committish, treepath, path: path108, fragment, hashformat }) => `https://${domain}/${user}/${project}/${treepath}/${maybeEncode(committish || "HEAD")}/${path108}${maybeJoin("#", hashformat(fragment || ""))}`, "browsetreetemplate"),
      browseblobtemplate: /* @__PURE__ */ __name(({ domain, user, project, committish, blobpath, path: path108, fragment, hashformat }) => `https://${domain}/${user}/${project}/${blobpath}/${maybeEncode(committish || "HEAD")}/${path108}${maybeJoin("#", hashformat(fragment || ""))}`, "browseblobtemplate"),
      docstemplate: /* @__PURE__ */ __name(({ domain, user, project, treepath, committish }) => `https://${domain}/${user}/${project}${maybeJoin("/", treepath, "/", maybeEncode(committish))}#readme`, "docstemplate"),
      httpstemplate: /* @__PURE__ */ __name(({ auth: auth2, domain, user, project, committish }) => `git+https://${maybeJoin(auth2, "@")}${domain}/${user}/${project}.git${maybeJoin("#", committish)}`, "httpstemplate"),
      filetemplate: /* @__PURE__ */ __name(({ domain, user, project, committish, path: path108 }) => `https://${domain}/${user}/${project}/raw/${maybeEncode(committish || "HEAD")}/${path108}`, "filetemplate"),
      shortcuttemplate: /* @__PURE__ */ __name(({ type, user, project, committish }) => `${type}:${user}/${project}${maybeJoin("#", committish)}`, "shortcuttemplate"),
      pathtemplate: /* @__PURE__ */ __name(({ user, project, committish }) => `${user}/${project}${maybeJoin("#", committish)}`, "pathtemplate"),
      bugstemplate: /* @__PURE__ */ __name(({ domain, user, project }) => `https://${domain}/${user}/${project}/issues`, "bugstemplate"),
      hashformat: formatHashFragment
    };
    var hosts = {};
    hosts.github = {
      // First two are insecure and generally shouldn't be used any more, but
      // they are still supported.
      protocols: ["git:", "http:", "git+ssh:", "git+https:", "ssh:", "https:"],
      domain: "github.com",
      treepath: "tree",
      blobpath: "blob",
      editpath: "edit",
      filetemplate: /* @__PURE__ */ __name(({ auth: auth2, user, project, committish, path: path108 }) => `https://${maybeJoin(auth2, "@")}raw.githubusercontent.com/${user}/${project}/${maybeEncode(committish || "HEAD")}/${path108}`, "filetemplate"),
      gittemplate: /* @__PURE__ */ __name(({ auth: auth2, domain, user, project, committish }) => `git://${maybeJoin(auth2, "@")}${domain}/${user}/${project}.git${maybeJoin("#", committish)}`, "gittemplate"),
      tarballtemplate: /* @__PURE__ */ __name(({ domain, user, project, committish }) => `https://codeload.${domain}/${user}/${project}/tar.gz/${maybeEncode(committish || "HEAD")}`, "tarballtemplate"),
      extract: /* @__PURE__ */ __name((url2) => {
        let [, user, project, type, committish] = url2.pathname.split("/", 5);
        if (type && type !== "tree") {
          return;
        }
        if (!type) {
          committish = url2.hash.slice(1);
        }
        if (project && project.endsWith(".git")) {
          project = project.slice(0, -4);
        }
        if (!user || !project) {
          return;
        }
        return { user, project, committish };
      }, "extract")
    };
    hosts.bitbucket = {
      protocols: ["git+ssh:", "git+https:", "ssh:", "https:"],
      domain: "bitbucket.org",
      treepath: "src",
      blobpath: "src",
      editpath: "?mode=edit",
      edittemplate: /* @__PURE__ */ __name(({ domain, user, project, committish, treepath, path: path108, editpath }) => `https://${domain}/${user}/${project}${maybeJoin("/", treepath, "/", maybeEncode(committish || "HEAD"), "/", path108, editpath)}`, "edittemplate"),
      tarballtemplate: /* @__PURE__ */ __name(({ domain, user, project, committish }) => `https://${domain}/${user}/${project}/get/${maybeEncode(committish || "HEAD")}.tar.gz`, "tarballtemplate"),
      extract: /* @__PURE__ */ __name((url2) => {
        let [, user, project, aux] = url2.pathname.split("/", 4);
        if (["get"].includes(aux)) {
          return;
        }
        if (project && project.endsWith(".git")) {
          project = project.slice(0, -4);
        }
        if (!user || !project) {
          return;
        }
        return { user, project, committish: url2.hash.slice(1) };
      }, "extract")
    };
    hosts.gitlab = {
      protocols: ["git+ssh:", "git+https:", "ssh:", "https:"],
      domain: "gitlab.com",
      treepath: "tree",
      blobpath: "tree",
      editpath: "-/edit",
      httpstemplate: /* @__PURE__ */ __name(({ auth: auth2, domain, user, project, committish }) => `git+https://${maybeJoin(auth2, "@")}${domain}/${user}/${project}.git${maybeJoin("#", committish)}`, "httpstemplate"),
      tarballtemplate: /* @__PURE__ */ __name(({ domain, user, project, committish }) => `https://${domain}/${user}/${project}/repository/archive.tar.gz?ref=${maybeEncode(committish || "HEAD")}`, "tarballtemplate"),
      extract: /* @__PURE__ */ __name((url2) => {
        const path108 = url2.pathname.slice(1);
        if (path108.includes("/-/") || path108.includes("/archive.tar.gz")) {
          return;
        }
        const segments = path108.split("/");
        let project = segments.pop();
        if (project.endsWith(".git")) {
          project = project.slice(0, -4);
        }
        const user = segments.join("/");
        if (!user || !project) {
          return;
        }
        return { user, project, committish: url2.hash.slice(1) };
      }, "extract")
    };
    hosts.gist = {
      protocols: ["git:", "git+ssh:", "git+https:", "ssh:", "https:"],
      domain: "gist.github.com",
      editpath: "edit",
      sshtemplate: /* @__PURE__ */ __name(({ domain, project, committish }) => `git@${domain}:${project}.git${maybeJoin("#", committish)}`, "sshtemplate"),
      sshurltemplate: /* @__PURE__ */ __name(({ domain, project, committish }) => `git+ssh://git@${domain}/${project}.git${maybeJoin("#", committish)}`, "sshurltemplate"),
      edittemplate: /* @__PURE__ */ __name(({ domain, user, project, committish, editpath }) => `https://${domain}/${user}/${project}${maybeJoin("/", maybeEncode(committish))}/${editpath}`, "edittemplate"),
      browsetemplate: /* @__PURE__ */ __name(({ domain, project, committish }) => `https://${domain}/${project}${maybeJoin("/", maybeEncode(committish))}`, "browsetemplate"),
      browsetreetemplate: /* @__PURE__ */ __name(({ domain, project, committish, path: path108, hashformat }) => `https://${domain}/${project}${maybeJoin("/", maybeEncode(committish))}${maybeJoin("#", hashformat(path108))}`, "browsetreetemplate"),
      browseblobtemplate: /* @__PURE__ */ __name(({ domain, project, committish, path: path108, hashformat }) => `https://${domain}/${project}${maybeJoin("/", maybeEncode(committish))}${maybeJoin("#", hashformat(path108))}`, "browseblobtemplate"),
      docstemplate: /* @__PURE__ */ __name(({ domain, project, committish }) => `https://${domain}/${project}${maybeJoin("/", maybeEncode(committish))}`, "docstemplate"),
      httpstemplate: /* @__PURE__ */ __name(({ domain, project, committish }) => `git+https://${domain}/${project}.git${maybeJoin("#", committish)}`, "httpstemplate"),
      filetemplate: /* @__PURE__ */ __name(({ user, project, committish, path: path108 }) => `https://gist.githubusercontent.com/${user}/${project}/raw${maybeJoin("/", maybeEncode(committish))}/${path108}`, "filetemplate"),
      shortcuttemplate: /* @__PURE__ */ __name(({ type, project, committish }) => `${type}:${project}${maybeJoin("#", committish)}`, "shortcuttemplate"),
      pathtemplate: /* @__PURE__ */ __name(({ project, committish }) => `${project}${maybeJoin("#", committish)}`, "pathtemplate"),
      bugstemplate: /* @__PURE__ */ __name(({ domain, project }) => `https://${domain}/${project}`, "bugstemplate"),
      gittemplate: /* @__PURE__ */ __name(({ domain, project, committish }) => `git://${domain}/${project}.git${maybeJoin("#", committish)}`, "gittemplate"),
      tarballtemplate: /* @__PURE__ */ __name(({ project, committish }) => `https://codeload.github.com/gist/${project}/tar.gz/${maybeEncode(committish || "HEAD")}`, "tarballtemplate"),
      extract: /* @__PURE__ */ __name((url2) => {
        let [, user, project, aux] = url2.pathname.split("/", 4);
        if (aux === "raw") {
          return;
        }
        if (!project) {
          if (!user) {
            return;
          }
          project = user;
          user = null;
        }
        if (project.endsWith(".git")) {
          project = project.slice(0, -4);
        }
        return { user, project, committish: url2.hash.slice(1) };
      }, "extract"),
      hashformat: /* @__PURE__ */ __name(function(fragment) {
        return fragment && "file-" + formatHashFragment(fragment);
      }, "hashformat")
    };
    hosts.sourcehut = {
      protocols: ["git+ssh:", "https:"],
      domain: "git.sr.ht",
      treepath: "tree",
      blobpath: "tree",
      filetemplate: /* @__PURE__ */ __name(({ domain, user, project, committish, path: path108 }) => `https://${domain}/${user}/${project}/blob/${maybeEncode(committish) || "HEAD"}/${path108}`, "filetemplate"),
      httpstemplate: /* @__PURE__ */ __name(({ domain, user, project, committish }) => `https://${domain}/${user}/${project}.git${maybeJoin("#", committish)}`, "httpstemplate"),
      tarballtemplate: /* @__PURE__ */ __name(({ domain, user, project, committish }) => `https://${domain}/${user}/${project}/archive/${maybeEncode(committish) || "HEAD"}.tar.gz`, "tarballtemplate"),
      bugstemplate: /* @__PURE__ */ __name(() => null, "bugstemplate"),
      extract: /* @__PURE__ */ __name((url2) => {
        let [, user, project, aux] = url2.pathname.split("/", 4);
        if (["archive"].includes(aux)) {
          return;
        }
        if (project && project.endsWith(".git")) {
          project = project.slice(0, -4);
        }
        if (!user || !project) {
          return;
        }
        return { user, project, committish: url2.hash.slice(1) };
      }, "extract")
    };
    for (const [name3, host] of Object.entries(hosts)) {
      hosts[name3] = Object.assign({}, defaults3, host);
    }
    module2.exports = hosts;
  }
});

// node_modules/hosted-git-info/lib/parse-url.js
var require_parse_url = __commonJS({
  "node_modules/hosted-git-info/lib/parse-url.js"(exports2, module2) {
    init_esbuild_shims();
    var url2 = __require("url");
    var lastIndexOfBefore = /* @__PURE__ */ __name((str2, char, beforeChar) => {
      const startPosition = str2.indexOf(beforeChar);
      return str2.lastIndexOf(char, startPosition > -1 ? startPosition : Infinity);
    }, "lastIndexOfBefore");
    var safeUrl = /* @__PURE__ */ __name((u) => {
      try {
        return new url2.URL(u);
      } catch {
      }
    }, "safeUrl");
    var correctProtocol = /* @__PURE__ */ __name((arg, protocols) => {
      const firstColon = arg.indexOf(":");
      const proto3 = arg.slice(0, firstColon + 1);
      if (Object.prototype.hasOwnProperty.call(protocols, proto3)) {
        return arg;
      }
      const firstAt = arg.indexOf("@");
      if (firstAt > -1) {
        if (firstAt > firstColon) {
          return `git+ssh://${arg}`;
        } else {
          return arg;
        }
      }
      const doubleSlash = arg.indexOf("//");
      if (doubleSlash === firstColon + 1) {
        return arg;
      }
      return `${arg.slice(0, firstColon + 1)}//${arg.slice(firstColon + 1)}`;
    }, "correctProtocol");
    var correctUrl = /* @__PURE__ */ __name((giturl) => {
      const firstAt = lastIndexOfBefore(giturl, "@", "#");
      const lastColonBeforeHash = lastIndexOfBefore(giturl, ":", "#");
      if (lastColonBeforeHash > firstAt) {
        giturl = giturl.slice(0, lastColonBeforeHash) + "/" + giturl.slice(lastColonBeforeHash + 1);
      }
      if (lastIndexOfBefore(giturl, ":", "#") === -1 && giturl.indexOf("//") === -1) {
        giturl = `git+ssh://${giturl}`;
      }
      return giturl;
    }, "correctUrl");
    module2.exports = (giturl, protocols) => {
      const withProtocol = protocols ? correctProtocol(giturl, protocols) : giturl;
      return safeUrl(withProtocol) || safeUrl(correctUrl(withProtocol));
    };
  }
});

// node_modules/hosted-git-info/lib/from-url.js
var require_from_url = __commonJS({
  "node_modules/hosted-git-info/lib/from-url.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var parseUrl = require_parse_url();
    var isGitHubShorthand = /* @__PURE__ */ __name((arg) => {
      const firstHash = arg.indexOf("#");
      const firstSlash = arg.indexOf("/");
      const secondSlash = arg.indexOf("/", firstSlash + 1);
      const firstColon = arg.indexOf(":");
      const firstSpace = /\s/.exec(arg);
      const firstAt = arg.indexOf("@");
      const spaceOnlyAfterHash = !firstSpace || firstHash > -1 && firstSpace.index > firstHash;
      const atOnlyAfterHash = firstAt === -1 || firstHash > -1 && firstAt > firstHash;
      const colonOnlyAfterHash = firstColon === -1 || firstHash > -1 && firstColon > firstHash;
      const secondSlashOnlyAfterHash = secondSlash === -1 || firstHash > -1 && secondSlash > firstHash;
      const hasSlash = firstSlash > 0;
      const doesNotEndWithSlash = firstHash > -1 ? arg[firstHash - 1] !== "/" : !arg.endsWith("/");
      const doesNotStartWithDot = !arg.startsWith(".");
      return spaceOnlyAfterHash && hasSlash && doesNotEndWithSlash && doesNotStartWithDot && atOnlyAfterHash && colonOnlyAfterHash && secondSlashOnlyAfterHash;
    }, "isGitHubShorthand");
    module2.exports = (giturl, opts, { gitHosts, protocols }) => {
      if (!giturl) {
        return;
      }
      const correctedUrl = isGitHubShorthand(giturl) ? `github:${giturl}` : giturl;
      const parsed = parseUrl(correctedUrl, protocols);
      if (!parsed) {
        return;
      }
      const gitHostShortcut = gitHosts.byShortcut[parsed.protocol];
      const gitHostDomain = gitHosts.byDomain[parsed.hostname.startsWith("www.") ? parsed.hostname.slice(4) : parsed.hostname];
      const gitHostName = gitHostShortcut || gitHostDomain;
      if (!gitHostName) {
        return;
      }
      const gitHostInfo = gitHosts[gitHostShortcut || gitHostDomain];
      let auth2 = null;
      if (protocols[parsed.protocol]?.auth && (parsed.username || parsed.password)) {
        auth2 = `${parsed.username}${parsed.password ? ":" + parsed.password : ""}`;
      }
      let committish = null;
      let user = null;
      let project = null;
      let defaultRepresentation = null;
      try {
        if (gitHostShortcut) {
          let pathname = parsed.pathname.startsWith("/") ? parsed.pathname.slice(1) : parsed.pathname;
          const firstAt = pathname.indexOf("@");
          if (firstAt > -1) {
            pathname = pathname.slice(firstAt + 1);
          }
          const lastSlash = pathname.lastIndexOf("/");
          if (lastSlash > -1) {
            user = decodeURIComponent(pathname.slice(0, lastSlash));
            if (!user) {
              user = null;
            }
            project = decodeURIComponent(pathname.slice(lastSlash + 1));
          } else {
            project = decodeURIComponent(pathname);
          }
          if (project.endsWith(".git")) {
            project = project.slice(0, -4);
          }
          if (parsed.hash) {
            committish = decodeURIComponent(parsed.hash.slice(1));
          }
          defaultRepresentation = "shortcut";
        } else {
          if (!gitHostInfo.protocols.includes(parsed.protocol)) {
            return;
          }
          const segments = gitHostInfo.extract(parsed);
          if (!segments) {
            return;
          }
          user = segments.user && decodeURIComponent(segments.user);
          project = decodeURIComponent(segments.project);
          committish = decodeURIComponent(segments.committish);
          defaultRepresentation = protocols[parsed.protocol]?.name || parsed.protocol.slice(0, -1);
        }
      } catch (err) {
        if (err instanceof URIError) {
          return;
        } else {
          throw err;
        }
      }
      return [gitHostName, user, auth2, project, committish, defaultRepresentation, opts];
    };
  }
});

// node_modules/hosted-git-info/lib/index.js
var require_lib6 = __commonJS({
  "node_modules/hosted-git-info/lib/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { LRUCache: LRUCache2 } = require_commonjs();
    var hosts = require_hosts();
    var fromUrl = require_from_url();
    var parseUrl = require_parse_url();
    var cache5 = new LRUCache2({ max: 1e3 });
    var GitHost = class _GitHost {
      static {
        __name(this, "GitHost");
      }
      constructor(type, user, auth2, project, committish, defaultRepresentation, opts = {}) {
        Object.assign(this, _GitHost.#gitHosts[type], {
          type,
          user,
          auth: auth2,
          project,
          committish,
          default: defaultRepresentation,
          opts
        });
      }
      static #gitHosts = { byShortcut: {}, byDomain: {} };
      static #protocols = {
        "git+ssh:": { name: "sshurl" },
        "ssh:": { name: "sshurl" },
        "git+https:": { name: "https", auth: true },
        "git:": { auth: true },
        "http:": { auth: true },
        "https:": { auth: true },
        "git+http:": { auth: true }
      };
      static addHost(name3, host) {
        _GitHost.#gitHosts[name3] = host;
        _GitHost.#gitHosts.byDomain[host.domain] = name3;
        _GitHost.#gitHosts.byShortcut[`${name3}:`] = name3;
        _GitHost.#protocols[`${name3}:`] = { name: name3 };
      }
      static fromUrl(giturl, opts) {
        if (typeof giturl !== "string") {
          return;
        }
        const key = giturl + JSON.stringify(opts || {});
        if (!cache5.has(key)) {
          const hostArgs = fromUrl(giturl, opts, {
            gitHosts: _GitHost.#gitHosts,
            protocols: _GitHost.#protocols
          });
          cache5.set(key, hostArgs ? new _GitHost(...hostArgs) : void 0);
        }
        return cache5.get(key);
      }
      static parseUrl(url2) {
        return parseUrl(url2);
      }
      #fill(template, opts) {
        if (typeof template !== "function") {
          return null;
        }
        const options2 = { ...this, ...this.opts, ...opts };
        if (!options2.path) {
          options2.path = "";
        }
        if (options2.path.startsWith("/")) {
          options2.path = options2.path.slice(1);
        }
        if (options2.noCommittish) {
          options2.committish = null;
        }
        const result = template(options2);
        return options2.noGitPlus && result.startsWith("git+") ? result.slice(4) : result;
      }
      hash() {
        return this.committish ? `#${this.committish}` : "";
      }
      ssh(opts) {
        return this.#fill(this.sshtemplate, opts);
      }
      sshurl(opts) {
        return this.#fill(this.sshurltemplate, opts);
      }
      browse(path108, ...args) {
        if (typeof path108 !== "string") {
          return this.#fill(this.browsetemplate, path108);
        }
        if (typeof args[0] !== "string") {
          return this.#fill(this.browsetreetemplate, { ...args[0], path: path108 });
        }
        return this.#fill(this.browsetreetemplate, { ...args[1], fragment: args[0], path: path108 });
      }
      // If the path is known to be a file, then browseFile should be used. For some hosts
      // the url is the same as browse, but for others like GitHub a file can use both `/tree/`
      // and `/blob/` in the path. When using a default committish of `HEAD` then the `/tree/`
      // path will redirect to a specific commit. Using the `/blob/` path avoids this and
      // does not redirect to a different commit.
      browseFile(path108, ...args) {
        if (typeof args[0] !== "string") {
          return this.#fill(this.browseblobtemplate, { ...args[0], path: path108 });
        }
        return this.#fill(this.browseblobtemplate, { ...args[1], fragment: args[0], path: path108 });
      }
      docs(opts) {
        return this.#fill(this.docstemplate, opts);
      }
      bugs(opts) {
        return this.#fill(this.bugstemplate, opts);
      }
      https(opts) {
        return this.#fill(this.httpstemplate, opts);
      }
      git(opts) {
        return this.#fill(this.gittemplate, opts);
      }
      shortcut(opts) {
        return this.#fill(this.shortcuttemplate, opts);
      }
      path(opts) {
        return this.#fill(this.pathtemplate, opts);
      }
      tarball(opts) {
        return this.#fill(this.tarballtemplate, { ...opts, noCommittish: false });
      }
      file(path108, opts) {
        return this.#fill(this.filetemplate, { ...opts, path: path108 });
      }
      edit(path108, opts) {
        return this.#fill(this.edittemplate, { ...opts, path: path108 });
      }
      getDefaultRepresentation() {
        return this.default;
      }
      toString(opts) {
        if (this.default && typeof this[this.default] === "function") {
          return this[this.default](opts);
        }
        return this.sshurl(opts);
      }
    };
    for (const [name3, host] of Object.entries(hosts)) {
      GitHost.addHost(name3, host);
    }
    module2.exports = GitHost;
  }
});

// node_modules/normalize-package-data/lib/extract_description.js
var require_extract_description = __commonJS({
  "node_modules/normalize-package-data/lib/extract_description.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = extractDescription;
    function extractDescription(d) {
      if (!d) {
        return;
      }
      if (d === "ERROR: No README data found!") {
        return;
      }
      d = d.trim().split("\n");
      let s2 = 0;
      while (d[s2] && d[s2].trim().match(/^(#|$)/)) {
        s2++;
      }
      const l2 = d.length;
      let e2 = s2 + 1;
      while (e2 < l2 && d[e2].trim()) {
        e2++;
      }
      return d.slice(s2, e2).join(" ").trim();
    }
    __name(extractDescription, "extractDescription");
  }
});

// node_modules/normalize-package-data/lib/typos.json
var require_typos = __commonJS({
  "node_modules/normalize-package-data/lib/typos.json"(exports2, module2) {
    module2.exports = {
      topLevel: {
        dependancies: "dependencies",
        dependecies: "dependencies",
        depdenencies: "dependencies",
        devEependencies: "devDependencies",
        depends: "dependencies",
        "dev-dependencies": "devDependencies",
        devDependences: "devDependencies",
        devDepenencies: "devDependencies",
        devdependencies: "devDependencies",
        repostitory: "repository",
        repo: "repository",
        prefereGlobal: "preferGlobal",
        hompage: "homepage",
        hampage: "homepage",
        autohr: "author",
        autor: "author",
        contributers: "contributors",
        publicationConfig: "publishConfig",
        script: "scripts"
      },
      bugs: { web: "url", name: "url" },
      script: { server: "start", tests: "test" }
    };
  }
});

// node_modules/normalize-package-data/lib/fixer.js
var require_fixer = __commonJS({
  "node_modules/normalize-package-data/lib/fixer.js"(exports2, module2) {
    init_esbuild_shims();
    var isValidSemver = require_valid();
    var cleanSemver = require_clean();
    var validateLicense = require_validate_npm_package_license();
    var hostedGitInfo = require_lib6();
    var moduleBuiltin = __require("node:module");
    var depTypes = ["dependencies", "devDependencies", "optionalDependencies"];
    var extractDescription = require_extract_description();
    var url2 = __require("url");
    var typos = require_typos();
    var isEmail = /* @__PURE__ */ __name((str2) => str2.includes("@") && str2.indexOf("@") < str2.lastIndexOf("."), "isEmail");
    module2.exports = {
      // default warning function
      warn: /* @__PURE__ */ __name(function() {
      }, "warn"),
      fixRepositoryField: /* @__PURE__ */ __name(function(data) {
        if (data.repositories) {
          this.warn("repositories");
          data.repository = data.repositories[0];
        }
        if (!data.repository) {
          return this.warn("missingRepository");
        }
        if (typeof data.repository === "string") {
          data.repository = {
            type: "git",
            url: data.repository
          };
        }
        var r3 = data.repository.url || "";
        if (r3) {
          var hosted = hostedGitInfo.fromUrl(r3);
          if (hosted) {
            r3 = data.repository.url = hosted.getDefaultRepresentation() === "shortcut" ? hosted.https() : hosted.toString();
          }
        }
        if (r3.match(/github.com\/[^/]+\/[^/]+\.git\.git$/)) {
          this.warn("brokenGitUrl", r3);
        }
      }, "fixRepositoryField"),
      fixTypos: /* @__PURE__ */ __name(function(data) {
        Object.keys(typos.topLevel).forEach(function(d) {
          if (Object.prototype.hasOwnProperty.call(data, d)) {
            this.warn("typo", d, typos.topLevel[d]);
          }
        }, this);
      }, "fixTypos"),
      fixScriptsField: /* @__PURE__ */ __name(function(data) {
        if (!data.scripts) {
          return;
        }
        if (typeof data.scripts !== "object") {
          this.warn("nonObjectScripts");
          delete data.scripts;
          return;
        }
        Object.keys(data.scripts).forEach(function(k) {
          if (typeof data.scripts[k] !== "string") {
            this.warn("nonStringScript");
            delete data.scripts[k];
          } else if (typos.script[k] && !data.scripts[typos.script[k]]) {
            this.warn("typo", k, typos.script[k], "scripts");
          }
        }, this);
      }, "fixScriptsField"),
      fixFilesField: /* @__PURE__ */ __name(function(data) {
        var files = data.files;
        if (files && !Array.isArray(files)) {
          this.warn("nonArrayFiles");
          delete data.files;
        } else if (data.files) {
          data.files = data.files.filter(function(file) {
            if (!file || typeof file !== "string") {
              this.warn("invalidFilename", file);
              return false;
            } else {
              return true;
            }
          }, this);
        }
      }, "fixFilesField"),
      fixBinField: /* @__PURE__ */ __name(function(data) {
        if (!data.bin) {
          return;
        }
        if (typeof data.bin === "string") {
          var b = {};
          var match2;
          if (match2 = data.name.match(/^@[^/]+[/](.*)$/)) {
            b[match2[1]] = data.bin;
          } else {
            b[data.name] = data.bin;
          }
          data.bin = b;
        }
      }, "fixBinField"),
      fixManField: /* @__PURE__ */ __name(function(data) {
        if (!data.man) {
          return;
        }
        if (typeof data.man === "string") {
          data.man = [data.man];
        }
      }, "fixManField"),
      fixBundleDependenciesField: /* @__PURE__ */ __name(function(data) {
        var bdd = "bundledDependencies";
        var bd = "bundleDependencies";
        if (data[bdd] && !data[bd]) {
          data[bd] = data[bdd];
          delete data[bdd];
        }
        if (data[bd] && !Array.isArray(data[bd])) {
          this.warn("nonArrayBundleDependencies");
          delete data[bd];
        } else if (data[bd]) {
          data[bd] = data[bd].filter(function(filtered) {
            if (!filtered || typeof filtered !== "string") {
              this.warn("nonStringBundleDependency", filtered);
              return false;
            } else {
              if (!data.dependencies) {
                data.dependencies = {};
              }
              if (!Object.prototype.hasOwnProperty.call(data.dependencies, filtered)) {
                this.warn("nonDependencyBundleDependency", filtered);
                data.dependencies[filtered] = "*";
              }
              return true;
            }
          }, this);
        }
      }, "fixBundleDependenciesField"),
      fixDependencies: /* @__PURE__ */ __name(function(data) {
        objectifyDeps(data, this.warn);
        addOptionalDepsToDeps(data, this.warn);
        this.fixBundleDependenciesField(data);
        ["dependencies", "devDependencies"].forEach(function(deps) {
          if (!(deps in data)) {
            return;
          }
          if (!data[deps] || typeof data[deps] !== "object") {
            this.warn("nonObjectDependencies", deps);
            delete data[deps];
            return;
          }
          Object.keys(data[deps]).forEach(function(d) {
            var r3 = data[deps][d];
            if (typeof r3 !== "string") {
              this.warn("nonStringDependency", d, JSON.stringify(r3));
              delete data[deps][d];
            }
            var hosted = hostedGitInfo.fromUrl(data[deps][d]);
            if (hosted) {
              data[deps][d] = hosted.toString();
            }
          }, this);
        }, this);
      }, "fixDependencies"),
      fixModulesField: /* @__PURE__ */ __name(function(data) {
        if (data.modules) {
          this.warn("deprecatedModules");
          delete data.modules;
        }
      }, "fixModulesField"),
      fixKeywordsField: /* @__PURE__ */ __name(function(data) {
        if (typeof data.keywords === "string") {
          data.keywords = data.keywords.split(/,\s+/);
        }
        if (data.keywords && !Array.isArray(data.keywords)) {
          delete data.keywords;
          this.warn("nonArrayKeywords");
        } else if (data.keywords) {
          data.keywords = data.keywords.filter(function(kw) {
            if (typeof kw !== "string" || !kw) {
              this.warn("nonStringKeyword");
              return false;
            } else {
              return true;
            }
          }, this);
        }
      }, "fixKeywordsField"),
      fixVersionField: /* @__PURE__ */ __name(function(data, strict) {
        var loose = !strict;
        if (!data.version) {
          data.version = "";
          return true;
        }
        if (!isValidSemver(data.version, loose)) {
          throw new Error('Invalid version: "' + data.version + '"');
        }
        data.version = cleanSemver(data.version, loose);
        return true;
      }, "fixVersionField"),
      fixPeople: /* @__PURE__ */ __name(function(data) {
        modifyPeople(data, unParsePerson);
        modifyPeople(data, parsePerson);
      }, "fixPeople"),
      fixNameField: /* @__PURE__ */ __name(function(data, options2) {
        if (typeof options2 === "boolean") {
          options2 = { strict: options2 };
        } else if (typeof options2 === "undefined") {
          options2 = {};
        }
        var strict = options2.strict;
        if (!data.name && !strict) {
          data.name = "";
          return;
        }
        if (typeof data.name !== "string") {
          throw new Error("name field must be a string.");
        }
        if (!strict) {
          data.name = data.name.trim();
        }
        ensureValidName(data.name, strict, options2.allowLegacyCase);
        if (moduleBuiltin.builtinModules.includes(data.name)) {
          this.warn("conflictingName", data.name);
        }
      }, "fixNameField"),
      fixDescriptionField: /* @__PURE__ */ __name(function(data) {
        if (data.description && typeof data.description !== "string") {
          this.warn("nonStringDescription");
          delete data.description;
        }
        if (data.readme && !data.description) {
          data.description = extractDescription(data.readme);
        }
        if (data.description === void 0) {
          delete data.description;
        }
        if (!data.description) {
          this.warn("missingDescription");
        }
      }, "fixDescriptionField"),
      fixReadmeField: /* @__PURE__ */ __name(function(data) {
        if (!data.readme) {
          this.warn("missingReadme");
          data.readme = "ERROR: No README data found!";
        }
      }, "fixReadmeField"),
      fixBugsField: /* @__PURE__ */ __name(function(data) {
        if (!data.bugs && data.repository && data.repository.url) {
          var hosted = hostedGitInfo.fromUrl(data.repository.url);
          if (hosted && hosted.bugs()) {
            data.bugs = { url: hosted.bugs() };
          }
        } else if (data.bugs) {
          if (typeof data.bugs === "string") {
            if (isEmail(data.bugs)) {
              data.bugs = { email: data.bugs };
            } else if (url2.parse(data.bugs).protocol) {
              data.bugs = { url: data.bugs };
            } else {
              this.warn("nonEmailUrlBugsString");
            }
          } else {
            bugsTypos(data.bugs, this.warn);
            var oldBugs = data.bugs;
            data.bugs = {};
            if (oldBugs.url) {
              if (typeof oldBugs.url === "string" && url2.parse(oldBugs.url).protocol) {
                data.bugs.url = oldBugs.url;
              } else {
                this.warn("nonUrlBugsUrlField");
              }
            }
            if (oldBugs.email) {
              if (typeof oldBugs.email === "string" && isEmail(oldBugs.email)) {
                data.bugs.email = oldBugs.email;
              } else {
                this.warn("nonEmailBugsEmailField");
              }
            }
          }
          if (!data.bugs.email && !data.bugs.url) {
            delete data.bugs;
            this.warn("emptyNormalizedBugs");
          }
        }
      }, "fixBugsField"),
      fixHomepageField: /* @__PURE__ */ __name(function(data) {
        if (!data.homepage && data.repository && data.repository.url) {
          var hosted = hostedGitInfo.fromUrl(data.repository.url);
          if (hosted && hosted.docs()) {
            data.homepage = hosted.docs();
          }
        }
        if (!data.homepage) {
          return;
        }
        if (typeof data.homepage !== "string") {
          this.warn("nonUrlHomepage");
          return delete data.homepage;
        }
        if (!url2.parse(data.homepage).protocol) {
          data.homepage = "http://" + data.homepage;
        }
      }, "fixHomepageField"),
      fixLicenseField: /* @__PURE__ */ __name(function(data) {
        const license = data.license || data.licence;
        if (!license) {
          return this.warn("missingLicense");
        }
        if (typeof license !== "string" || license.length < 1 || license.trim() === "") {
          return this.warn("invalidLicense");
        }
        if (!validateLicense(license).validForNewPackages) {
          return this.warn("invalidLicense");
        }
      }, "fixLicenseField")
    };
    function isValidScopedPackageName(spec) {
      if (spec.charAt(0) !== "@") {
        return false;
      }
      var rest = spec.slice(1).split("/");
      if (rest.length !== 2) {
        return false;
      }
      return rest[0] && rest[1] && rest[0] === encodeURIComponent(rest[0]) && rest[1] === encodeURIComponent(rest[1]);
    }
    __name(isValidScopedPackageName, "isValidScopedPackageName");
    function isCorrectlyEncodedName(spec) {
      return !spec.match(/[/@\s+%:]/) && spec === encodeURIComponent(spec);
    }
    __name(isCorrectlyEncodedName, "isCorrectlyEncodedName");
    function ensureValidName(name3, strict, allowLegacyCase) {
      if (name3.charAt(0) === "." || !(isValidScopedPackageName(name3) || isCorrectlyEncodedName(name3)) || strict && !allowLegacyCase && name3 !== name3.toLowerCase() || name3.toLowerCase() === "node_modules" || name3.toLowerCase() === "favicon.ico") {
        throw new Error("Invalid name: " + JSON.stringify(name3));
      }
    }
    __name(ensureValidName, "ensureValidName");
    function modifyPeople(data, fn) {
      if (data.author) {
        data.author = fn(data.author);
      }
      ["maintainers", "contributors"].forEach(function(set) {
        if (!Array.isArray(data[set])) {
          return;
        }
        data[set] = data[set].map(fn);
      });
      return data;
    }
    __name(modifyPeople, "modifyPeople");
    function unParsePerson(person) {
      if (typeof person === "string") {
        return person;
      }
      var name3 = person.name || "";
      var u = person.url || person.web;
      var wrappedUrl = u ? " (" + u + ")" : "";
      var e2 = person.email || person.mail;
      var wrappedEmail = e2 ? " <" + e2 + ">" : "";
      return name3 + wrappedEmail + wrappedUrl;
    }
    __name(unParsePerson, "unParsePerson");
    function parsePerson(person) {
      if (typeof person !== "string") {
        return person;
      }
      var matchedName = person.match(/^([^(<]+)/);
      var matchedUrl = person.match(/\(([^()]+)\)/);
      var matchedEmail = person.match(/<([^<>]+)>/);
      var obj = {};
      if (matchedName && matchedName[0].trim()) {
        obj.name = matchedName[0].trim();
      }
      if (matchedEmail) {
        obj.email = matchedEmail[1];
      }
      if (matchedUrl) {
        obj.url = matchedUrl[1];
      }
      return obj;
    }
    __name(parsePerson, "parsePerson");
    function addOptionalDepsToDeps(data) {
      var o2 = data.optionalDependencies;
      if (!o2) {
        return;
      }
      var d = data.dependencies || {};
      Object.keys(o2).forEach(function(k) {
        d[k] = o2[k];
      });
      data.dependencies = d;
    }
    __name(addOptionalDepsToDeps, "addOptionalDepsToDeps");
    function depObjectify(deps, type, warn) {
      if (!deps) {
        return {};
      }
      if (typeof deps === "string") {
        deps = deps.trim().split(/[\n\r\s\t ,]+/);
      }
      if (!Array.isArray(deps)) {
        return deps;
      }
      warn("deprecatedArrayDependencies", type);
      var o2 = {};
      deps.filter(function(d) {
        return typeof d === "string";
      }).forEach(function(d) {
        d = d.trim().split(/(:?[@\s><=])/);
        var dn = d.shift();
        var dv = d.join("");
        dv = dv.trim();
        dv = dv.replace(/^@/, "");
        o2[dn] = dv;
      });
      return o2;
    }
    __name(depObjectify, "depObjectify");
    function objectifyDeps(data, warn) {
      depTypes.forEach(function(type) {
        if (!data[type]) {
          return;
        }
        data[type] = depObjectify(data[type], type, warn);
      });
    }
    __name(objectifyDeps, "objectifyDeps");
    function bugsTypos(bugs, warn) {
      if (!bugs) {
        return;
      }
      Object.keys(bugs).forEach(function(k) {
        if (typos.bugs[k]) {
          warn("typo", k, typos.bugs[k], "bugs");
          bugs[typos.bugs[k]] = bugs[k];
          delete bugs[k];
        }
      });
    }
    __name(bugsTypos, "bugsTypos");
  }
});

// node_modules/normalize-package-data/lib/warning_messages.json
var require_warning_messages = __commonJS({
  "node_modules/normalize-package-data/lib/warning_messages.json"(exports2, module2) {
    module2.exports = {
      repositories: "'repositories' (plural) Not supported. Please pick one as the 'repository' field",
      missingRepository: "No repository field.",
      brokenGitUrl: "Probably broken git url: %s",
      nonObjectScripts: "scripts must be an object",
      nonStringScript: "script values must be string commands",
      nonArrayFiles: "Invalid 'files' member",
      invalidFilename: "Invalid filename in 'files' list: %s",
      nonArrayBundleDependencies: "Invalid 'bundleDependencies' list. Must be array of package names",
      nonStringBundleDependency: "Invalid bundleDependencies member: %s",
      nonDependencyBundleDependency: "Non-dependency in bundleDependencies: %s",
      nonObjectDependencies: "%s field must be an object",
      nonStringDependency: "Invalid dependency: %s %s",
      deprecatedArrayDependencies: "specifying %s as array is deprecated",
      deprecatedModules: "modules field is deprecated",
      nonArrayKeywords: "keywords should be an array of strings",
      nonStringKeyword: "keywords should be an array of strings",
      conflictingName: "%s is also the name of a node core module.",
      nonStringDescription: "'description' field should be a string",
      missingDescription: "No description",
      missingReadme: "No README data",
      missingLicense: "No license field.",
      nonEmailUrlBugsString: "Bug string field must be url, email, or {email,url}",
      nonUrlBugsUrlField: "bugs.url field must be a string url. Deleted.",
      nonEmailBugsEmailField: "bugs.email field must be a string email. Deleted.",
      emptyNormalizedBugs: "Normalized value of bugs field is an empty object. Deleted.",
      nonUrlHomepage: "homepage field must be a string url. Deleted.",
      invalidLicense: "license should be a valid SPDX license expression",
      typo: "%s should probably be %s."
    };
  }
});

// node_modules/normalize-package-data/lib/make_warning.js
var require_make_warning = __commonJS({
  "node_modules/normalize-package-data/lib/make_warning.js"(exports2, module2) {
    init_esbuild_shims();
    var util4 = __require("util");
    var messages = require_warning_messages();
    module2.exports = function() {
      var args = Array.prototype.slice.call(arguments, 0);
      var warningName = args.shift();
      if (warningName === "typo") {
        return makeTypoWarning.apply(null, args);
      } else {
        var msgTemplate = messages[warningName] ? messages[warningName] : warningName + ": '%s'";
        args.unshift(msgTemplate);
        return util4.format.apply(null, args);
      }
    };
    function makeTypoWarning(providedName, probableName, field) {
      if (field) {
        providedName = field + "['" + providedName + "']";
        probableName = field + "['" + probableName + "']";
      }
      return util4.format(messages.typo, providedName, probableName);
    }
    __name(makeTypoWarning, "makeTypoWarning");
  }
});

// node_modules/normalize-package-data/lib/normalize.js
var require_normalize2 = __commonJS({
  "node_modules/normalize-package-data/lib/normalize.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = normalize10;
    var fixer = require_fixer();
    normalize10.fixer = fixer;
    var makeWarning = require_make_warning();
    var fieldsToFix = [
      "name",
      "version",
      "description",
      "repository",
      "modules",
      "scripts",
      "files",
      "bin",
      "man",
      "bugs",
      "keywords",
      "readme",
      "homepage",
      "license"
    ];
    var otherThingsToFix = ["dependencies", "people", "typos"];
    var thingsToFix = fieldsToFix.map(function(fieldName) {
      return ucFirst(fieldName) + "Field";
    });
    thingsToFix = thingsToFix.concat(otherThingsToFix);
    function normalize10(data, warn, strict) {
      if (warn === true) {
        warn = null;
        strict = true;
      }
      if (!strict) {
        strict = false;
      }
      if (!warn || data.private) {
        warn = /* @__PURE__ */ __name(function() {
        }, "warn");
      }
      if (data.scripts && data.scripts.install === "node-gyp rebuild" && !data.scripts.preinstall) {
        data.gypfile = true;
      }
      fixer.warn = function() {
        warn(makeWarning.apply(null, arguments));
      };
      thingsToFix.forEach(function(thingName) {
        fixer["fix" + ucFirst(thingName)](data, strict);
      });
      data._id = data.name + "@" + data.version;
    }
    __name(normalize10, "normalize");
    function ucFirst(string) {
      return string.charAt(0).toUpperCase() + string.slice(1);
    }
    __name(ucFirst, "ucFirst");
  }
});

// node_modules/command-exists/lib/command-exists.js
var require_command_exists = __commonJS({
  "node_modules/command-exists/lib/command-exists.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var exec5 = __require("child_process").exec;
    var execSync8 = __require("child_process").execSync;
    var fs95 = __require("fs");
    var path108 = __require("path");
    var access6 = fs95.access;
    var accessSync2 = fs95.accessSync;
    var constants4 = fs95.constants || fs95;
    var isUsingWindows = process.platform == "win32";
    var fileNotExists = /* @__PURE__ */ __name(function(commandName, callback) {
      access6(
        commandName,
        constants4.F_OK,
        function(err) {
          callback(!err);
        }
      );
    }, "fileNotExists");
    var fileNotExistsSync = /* @__PURE__ */ __name(function(commandName) {
      try {
        accessSync2(commandName, constants4.F_OK);
        return false;
      } catch (e2) {
        return true;
      }
    }, "fileNotExistsSync");
    var localExecutable = /* @__PURE__ */ __name(function(commandName, callback) {
      access6(
        commandName,
        constants4.F_OK | constants4.X_OK,
        function(err) {
          callback(null, !err);
        }
      );
    }, "localExecutable");
    var localExecutableSync = /* @__PURE__ */ __name(function(commandName) {
      try {
        accessSync2(commandName, constants4.F_OK | constants4.X_OK);
        return true;
      } catch (e2) {
        return false;
      }
    }, "localExecutableSync");
    var commandExistsUnix = /* @__PURE__ */ __name(function(commandName, cleanedCommandName, callback) {
      fileNotExists(commandName, function(isFile2) {
        if (!isFile2) {
          var child = exec5(
            "command -v " + cleanedCommandName + " 2>/dev/null && { echo >&1 " + cleanedCommandName + "; exit 0; }",
            function(error, stdout, stderr) {
              callback(null, !!stdout);
            }
          );
          return;
        }
        localExecutable(commandName, callback);
      });
    }, "commandExistsUnix");
    var commandExistsWindows = /* @__PURE__ */ __name(function(commandName, cleanedCommandName, callback) {
      if (!/^(?!(?:.*\s|.*\.|\W+)$)(?:[a-zA-Z]:)?(?:(?:[^<>:"\|\?\*\n])+(?:\/\/|\/|\\\\|\\)?)+$/m.test(commandName)) {
        callback(null, false);
        return;
      }
      var child = exec5(
        "where " + cleanedCommandName,
        function(error) {
          if (error !== null) {
            callback(null, false);
          } else {
            callback(null, true);
          }
        }
      );
    }, "commandExistsWindows");
    var commandExistsUnixSync = /* @__PURE__ */ __name(function(commandName, cleanedCommandName) {
      if (fileNotExistsSync(commandName)) {
        try {
          var stdout = execSync8(
            "command -v " + cleanedCommandName + " 2>/dev/null && { echo >&1 " + cleanedCommandName + "; exit 0; }"
          );
          return !!stdout;
        } catch (error) {
          return false;
        }
      }
      return localExecutableSync(commandName);
    }, "commandExistsUnixSync");
    var commandExistsWindowsSync = /* @__PURE__ */ __name(function(commandName, cleanedCommandName, callback) {
      if (!/^(?!(?:.*\s|.*\.|\W+)$)(?:[a-zA-Z]:)?(?:(?:[^<>:"\|\?\*\n])+(?:\/\/|\/|\\\\|\\)?)+$/m.test(commandName)) {
        return false;
      }
      try {
        var stdout = execSync8("where " + cleanedCommandName, { stdio: [] });
        return !!stdout;
      } catch (error) {
        return false;
      }
    }, "commandExistsWindowsSync");
    var cleanInput = /* @__PURE__ */ __name(function(s2) {
      if (/[^A-Za-z0-9_\/:=-]/.test(s2)) {
        s2 = "'" + s2.replace(/'/g, "'\\''") + "'";
        s2 = s2.replace(/^(?:'')+/g, "").replace(/\\'''/g, "\\'");
      }
      return s2;
    }, "cleanInput");
    if (isUsingWindows) {
      cleanInput = /* @__PURE__ */ __name(function(s2) {
        var isPathName = /[\\]/.test(s2);
        if (isPathName) {
          var dirname22 = '"' + path108.dirname(s2) + '"';
          var basename16 = '"' + path108.basename(s2) + '"';
          return dirname22 + ":" + basename16;
        }
        return '"' + s2 + '"';
      }, "cleanInput");
    }
    module2.exports = /* @__PURE__ */ __name(function commandExists3(commandName, callback) {
      var cleanedCommandName = cleanInput(commandName);
      if (!callback && typeof Promise !== "undefined") {
        return new Promise(function(resolve24, reject) {
          commandExists3(commandName, function(error, output) {
            if (output) {
              resolve24(commandName);
            } else {
              reject(error);
            }
          });
        });
      }
      if (isUsingWindows) {
        commandExistsWindows(commandName, cleanedCommandName, callback);
      } else {
        commandExistsUnix(commandName, cleanedCommandName, callback);
      }
    }, "commandExists");
    module2.exports.sync = function(commandName) {
      var cleanedCommandName = cleanInput(commandName);
      if (isUsingWindows) {
        return commandExistsWindowsSync(commandName, cleanedCommandName);
      } else {
        return commandExistsUnixSync(commandName, cleanedCommandName);
      }
    };
  }
});

// node_modules/command-exists/index.js
var require_command_exists2 = __commonJS({
  "node_modules/command-exists/index.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = require_command_exists();
  }
});

// node_modules/@iarna/toml/lib/parser.js
var require_parser = __commonJS({
  "node_modules/@iarna/toml/lib/parser.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var ParserEND = 1114112;
    var ParserError = class _ParserError extends Error {
      static {
        __name(this, "ParserError");
      }
      /* istanbul ignore next */
      constructor(msg, filename, linenumber) {
        super("[ParserError] " + msg, filename, linenumber);
        this.name = "ParserError";
        this.code = "ParserError";
        if (Error.captureStackTrace) Error.captureStackTrace(this, _ParserError);
      }
    };
    var State2 = class {
      static {
        __name(this, "State");
      }
      constructor(parser6) {
        this.parser = parser6;
        this.buf = "";
        this.returned = null;
        this.result = null;
        this.resultTable = null;
        this.resultArr = null;
      }
    };
    var Parser4 = class {
      static {
        __name(this, "Parser");
      }
      constructor() {
        this.pos = 0;
        this.col = 0;
        this.line = 0;
        this.obj = {};
        this.ctx = this.obj;
        this.stack = [];
        this._buf = "";
        this.char = null;
        this.ii = 0;
        this.state = new State2(this.parseStart);
      }
      parse(str2) {
        if (str2.length === 0 || str2.length == null) return;
        this._buf = String(str2);
        this.ii = -1;
        this.char = -1;
        let getNext;
        while (getNext === false || this.nextChar()) {
          getNext = this.runOne();
        }
        this._buf = null;
      }
      nextChar() {
        if (this.char === 10) {
          ++this.line;
          this.col = -1;
        }
        ++this.ii;
        this.char = this._buf.codePointAt(this.ii);
        ++this.pos;
        ++this.col;
        return this.haveBuffer();
      }
      haveBuffer() {
        return this.ii < this._buf.length;
      }
      runOne() {
        return this.state.parser.call(this, this.state.returned);
      }
      finish() {
        this.char = ParserEND;
        let last2;
        do {
          last2 = this.state.parser;
          this.runOne();
        } while (this.state.parser !== last2);
        this.ctx = null;
        this.state = null;
        this._buf = null;
        return this.obj;
      }
      next(fn) {
        if (typeof fn !== "function") throw new ParserError("Tried to set state to non-existent state: " + JSON.stringify(fn));
        this.state.parser = fn;
      }
      goto(fn) {
        this.next(fn);
        return this.runOne();
      }
      call(fn, returnWith) {
        if (returnWith) this.next(returnWith);
        this.stack.push(this.state);
        this.state = new State2(fn);
      }
      callNow(fn, returnWith) {
        this.call(fn, returnWith);
        return this.runOne();
      }
      return(value) {
        if (this.stack.length === 0) throw this.error(new ParserError("Stack underflow"));
        if (value === void 0) value = this.state.buf;
        this.state = this.stack.pop();
        this.state.returned = value;
      }
      returnNow(value) {
        this.return(value);
        return this.runOne();
      }
      consume() {
        if (this.char === ParserEND) throw this.error(new ParserError("Unexpected end-of-buffer"));
        this.state.buf += this._buf[this.ii];
      }
      error(err) {
        err.line = this.line;
        err.col = this.col;
        err.pos = this.pos;
        return err;
      }
      /* istanbul ignore next */
      parseStart() {
        throw new ParserError("Must declare a parseStart method");
      }
    };
    Parser4.END = ParserEND;
    Parser4.Error = ParserError;
    module2.exports = Parser4;
  }
});

// node_modules/@iarna/toml/lib/create-datetime.js
var require_create_datetime = __commonJS({
  "node_modules/@iarna/toml/lib/create-datetime.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = (value) => {
      const date = new Date(value);
      if (isNaN(date)) {
        throw new TypeError("Invalid Datetime");
      } else {
        return date;
      }
    };
  }
});

// node_modules/@iarna/toml/lib/format-num.js
var require_format_num = __commonJS({
  "node_modules/@iarna/toml/lib/format-num.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = (d, num) => {
      num = String(num);
      while (num.length < d) num = "0" + num;
      return num;
    };
  }
});

// node_modules/@iarna/toml/lib/create-datetime-float.js
var require_create_datetime_float = __commonJS({
  "node_modules/@iarna/toml/lib/create-datetime-float.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var f = require_format_num();
    var FloatingDateTime = class extends Date {
      static {
        __name(this, "FloatingDateTime");
      }
      constructor(value) {
        super(value + "Z");
        this.isFloating = true;
      }
      toISOString() {
        const date = `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}`;
        const time = `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}`;
        return `${date}T${time}`;
      }
    };
    module2.exports = (value) => {
      const date = new FloatingDateTime(value);
      if (isNaN(date)) {
        throw new TypeError("Invalid Datetime");
      } else {
        return date;
      }
    };
  }
});

// node_modules/@iarna/toml/lib/create-date.js
var require_create_date = __commonJS({
  "node_modules/@iarna/toml/lib/create-date.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var f = require_format_num();
    var DateTime = globalThis.Date;
    var Date2 = class extends DateTime {
      static {
        __name(this, "Date");
      }
      constructor(value) {
        super(value);
        this.isDate = true;
      }
      toISOString() {
        return `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}`;
      }
    };
    module2.exports = (value) => {
      const date = new Date2(value);
      if (isNaN(date)) {
        throw new TypeError("Invalid Datetime");
      } else {
        return date;
      }
    };
  }
});

// node_modules/@iarna/toml/lib/create-time.js
var require_create_time = __commonJS({
  "node_modules/@iarna/toml/lib/create-time.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var f = require_format_num();
    var Time = class extends Date {
      static {
        __name(this, "Time");
      }
      constructor(value) {
        super(`0000-01-01T${value}Z`);
        this.isTime = true;
      }
      toISOString() {
        return `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}`;
      }
    };
    module2.exports = (value) => {
      const date = new Time(value);
      if (isNaN(date)) {
        throw new TypeError("Invalid Datetime");
      } else {
        return date;
      }
    };
  }
});

// node_modules/@iarna/toml/lib/toml-parser.js
var require_toml_parser = __commonJS({
  "node_modules/@iarna/toml/lib/toml-parser.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = makeParserClass(require_parser());
    module.exports.makeParserClass = makeParserClass;
    var TomlError = class _TomlError extends Error {
      static {
        __name(this, "TomlError");
      }
      constructor(msg) {
        super(msg);
        this.name = "TomlError";
        if (Error.captureStackTrace) Error.captureStackTrace(this, _TomlError);
        this.fromTOML = true;
        this.wrapped = null;
      }
    };
    TomlError.wrap = (err) => {
      const terr = new TomlError(err.message);
      terr.code = err.code;
      terr.wrapped = err;
      return terr;
    };
    module.exports.TomlError = TomlError;
    var createDateTime = require_create_datetime();
    var createDateTimeFloat = require_create_datetime_float();
    var createDate = require_create_date();
    var createTime = require_create_time();
    var CTRL_I = 9;
    var CTRL_J = 10;
    var CTRL_M = 13;
    var CTRL_CHAR_BOUNDARY = 31;
    var CHAR_SP = 32;
    var CHAR_QUOT = 34;
    var CHAR_NUM = 35;
    var CHAR_APOS = 39;
    var CHAR_PLUS = 43;
    var CHAR_COMMA = 44;
    var CHAR_HYPHEN = 45;
    var CHAR_PERIOD = 46;
    var CHAR_0 = 48;
    var CHAR_1 = 49;
    var CHAR_7 = 55;
    var CHAR_9 = 57;
    var CHAR_COLON = 58;
    var CHAR_EQUALS = 61;
    var CHAR_A = 65;
    var CHAR_E = 69;
    var CHAR_F = 70;
    var CHAR_T = 84;
    var CHAR_U = 85;
    var CHAR_Z = 90;
    var CHAR_LOWBAR = 95;
    var CHAR_a = 97;
    var CHAR_b = 98;
    var CHAR_e = 101;
    var CHAR_f = 102;
    var CHAR_i = 105;
    var CHAR_l = 108;
    var CHAR_n = 110;
    var CHAR_o = 111;
    var CHAR_r = 114;
    var CHAR_s = 115;
    var CHAR_t = 116;
    var CHAR_u = 117;
    var CHAR_x = 120;
    var CHAR_z = 122;
    var CHAR_LCUB = 123;
    var CHAR_RCUB = 125;
    var CHAR_LSQB = 91;
    var CHAR_BSOL = 92;
    var CHAR_RSQB = 93;
    var CHAR_DEL = 127;
    var SURROGATE_FIRST = 55296;
    var SURROGATE_LAST = 57343;
    var escapes = {
      [CHAR_b]: "\b",
      [CHAR_t]: "	",
      [CHAR_n]: "\n",
      [CHAR_f]: "\f",
      [CHAR_r]: "\r",
      [CHAR_QUOT]: '"',
      [CHAR_BSOL]: "\\"
    };
    function isDigit(cp2) {
      return cp2 >= CHAR_0 && cp2 <= CHAR_9;
    }
    __name(isDigit, "isDigit");
    function isHexit(cp2) {
      return cp2 >= CHAR_A && cp2 <= CHAR_F || cp2 >= CHAR_a && cp2 <= CHAR_f || cp2 >= CHAR_0 && cp2 <= CHAR_9;
    }
    __name(isHexit, "isHexit");
    function isBit(cp2) {
      return cp2 === CHAR_1 || cp2 === CHAR_0;
    }
    __name(isBit, "isBit");
    function isOctit(cp2) {
      return cp2 >= CHAR_0 && cp2 <= CHAR_7;
    }
    __name(isOctit, "isOctit");
    function isAlphaNumQuoteHyphen(cp2) {
      return cp2 >= CHAR_A && cp2 <= CHAR_Z || cp2 >= CHAR_a && cp2 <= CHAR_z || cp2 >= CHAR_0 && cp2 <= CHAR_9 || cp2 === CHAR_APOS || cp2 === CHAR_QUOT || cp2 === CHAR_LOWBAR || cp2 === CHAR_HYPHEN;
    }
    __name(isAlphaNumQuoteHyphen, "isAlphaNumQuoteHyphen");
    function isAlphaNumHyphen(cp2) {
      return cp2 >= CHAR_A && cp2 <= CHAR_Z || cp2 >= CHAR_a && cp2 <= CHAR_z || cp2 >= CHAR_0 && cp2 <= CHAR_9 || cp2 === CHAR_LOWBAR || cp2 === CHAR_HYPHEN;
    }
    __name(isAlphaNumHyphen, "isAlphaNumHyphen");
    var _type = Symbol("type");
    var _declared = Symbol("declared");
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    var defineProperty = Object.defineProperty;
    var descriptor = { configurable: true, enumerable: true, writable: true, value: void 0 };
    function hasKey(obj, key) {
      if (hasOwnProperty.call(obj, key)) return true;
      if (key === "__proto__") defineProperty(obj, "__proto__", descriptor);
      return false;
    }
    __name(hasKey, "hasKey");
    var INLINE_TABLE = Symbol("inline-table");
    function InlineTable() {
      return Object.defineProperties({}, {
        [_type]: { value: INLINE_TABLE }
      });
    }
    __name(InlineTable, "InlineTable");
    function isInlineTable(obj) {
      if (obj === null || typeof obj !== "object") return false;
      return obj[_type] === INLINE_TABLE;
    }
    __name(isInlineTable, "isInlineTable");
    var TABLE = Symbol("table");
    function Table() {
      return Object.defineProperties({}, {
        [_type]: { value: TABLE },
        [_declared]: { value: false, writable: true }
      });
    }
    __name(Table, "Table");
    function isTable(obj) {
      if (obj === null || typeof obj !== "object") return false;
      return obj[_type] === TABLE;
    }
    __name(isTable, "isTable");
    var _contentType = Symbol("content-type");
    var INLINE_LIST = Symbol("inline-list");
    function InlineList(type) {
      return Object.defineProperties([], {
        [_type]: { value: INLINE_LIST },
        [_contentType]: { value: type }
      });
    }
    __name(InlineList, "InlineList");
    function isInlineList(obj) {
      if (obj === null || typeof obj !== "object") return false;
      return obj[_type] === INLINE_LIST;
    }
    __name(isInlineList, "isInlineList");
    var LIST = Symbol("list");
    function List() {
      return Object.defineProperties([], {
        [_type]: { value: LIST }
      });
    }
    __name(List, "List");
    function isList(obj) {
      if (obj === null || typeof obj !== "object") return false;
      return obj[_type] === LIST;
    }
    __name(isList, "isList");
    var _custom;
    try {
      const utilInspect = eval("require('util').inspect");
      _custom = utilInspect.custom;
    } catch (_) {
    }
    var _inspect = _custom || "inspect";
    var BoxedBigInt = class {
      static {
        __name(this, "BoxedBigInt");
      }
      constructor(value) {
        try {
          this.value = globalThis.BigInt.asIntN(64, value);
        } catch (_) {
          this.value = null;
        }
        Object.defineProperty(this, _type, { value: INTEGER });
      }
      isNaN() {
        return this.value === null;
      }
      /* istanbul ignore next */
      toString() {
        return String(this.value);
      }
      /* istanbul ignore next */
      [_inspect]() {
        return `[BigInt: ${this.toString()}]}`;
      }
      valueOf() {
        return this.value;
      }
    };
    var INTEGER = Symbol("integer");
    function Integer(value) {
      let num = Number(value);
      if (Object.is(num, -0)) num = 0;
      if (globalThis.BigInt && !Number.isSafeInteger(num)) {
        return new BoxedBigInt(value);
      } else {
        return Object.defineProperties(new Number(num), {
          isNaN: { value: /* @__PURE__ */ __name(function() {
            return isNaN(this);
          }, "value") },
          [_type]: { value: INTEGER },
          [_inspect]: { value: /* @__PURE__ */ __name(() => `[Integer: ${value}]`, "value") }
        });
      }
    }
    __name(Integer, "Integer");
    function isInteger(obj) {
      if (obj === null || typeof obj !== "object") return false;
      return obj[_type] === INTEGER;
    }
    __name(isInteger, "isInteger");
    var FLOAT = Symbol("float");
    function Float(value) {
      return Object.defineProperties(new Number(value), {
        [_type]: { value: FLOAT },
        [_inspect]: { value: /* @__PURE__ */ __name(() => `[Float: ${value}]`, "value") }
      });
    }
    __name(Float, "Float");
    function isFloat(obj) {
      if (obj === null || typeof obj !== "object") return false;
      return obj[_type] === FLOAT;
    }
    __name(isFloat, "isFloat");
    function tomlType(value) {
      const type = typeof value;
      if (type === "object") {
        if (value === null) return "null";
        if (value instanceof Date) return "datetime";
        if (_type in value) {
          switch (value[_type]) {
            case INLINE_TABLE:
              return "inline-table";
            case INLINE_LIST:
              return "inline-list";
            /* istanbul ignore next */
            case TABLE:
              return "table";
            /* istanbul ignore next */
            case LIST:
              return "list";
            case FLOAT:
              return "float";
            case INTEGER:
              return "integer";
          }
        }
      }
      return type;
    }
    __name(tomlType, "tomlType");
    function makeParserClass(Parser4) {
      class TOMLParser extends Parser4 {
        static {
          __name(this, "TOMLParser");
        }
        constructor() {
          super();
          this.ctx = this.obj = Table();
        }
        /* MATCH HELPER */
        atEndOfWord() {
          return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine();
        }
        atEndOfLine() {
          return this.char === Parser4.END || this.char === CTRL_J || this.char === CTRL_M;
        }
        parseStart() {
          if (this.char === Parser4.END) {
            return null;
          } else if (this.char === CHAR_LSQB) {
            return this.call(this.parseTableOrList);
          } else if (this.char === CHAR_NUM) {
            return this.call(this.parseComment);
          } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
            return null;
          } else if (isAlphaNumQuoteHyphen(this.char)) {
            return this.callNow(this.parseAssignStatement);
          } else {
            throw this.error(new TomlError(`Unknown character "${this.char}"`));
          }
        }
        // HELPER, this strips any whitespace and comments to the end of the line
        // then RETURNS. Last state in a production.
        parseWhitespaceToEOL() {
          if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
            return null;
          } else if (this.char === CHAR_NUM) {
            return this.goto(this.parseComment);
          } else if (this.char === Parser4.END || this.char === CTRL_J) {
            return this.return();
          } else {
            throw this.error(new TomlError("Unexpected character, expected only whitespace or comments till end of line"));
          }
        }
        /* ASSIGNMENT: key = value */
        parseAssignStatement() {
          return this.callNow(this.parseAssign, this.recordAssignStatement);
        }
        recordAssignStatement(kv) {
          let target = this.ctx;
          let finalKey = kv.key.pop();
          for (let kw of kv.key) {
            if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
              throw this.error(new TomlError("Can't redefine existing key"));
            }
            target = target[kw] = target[kw] || Table();
          }
          if (hasKey(target, finalKey)) {
            throw this.error(new TomlError("Can't redefine existing key"));
          }
          if (isInteger(kv.value) || isFloat(kv.value)) {
            target[finalKey] = kv.value.valueOf();
          } else {
            target[finalKey] = kv.value;
          }
          return this.goto(this.parseWhitespaceToEOL);
        }
        /* ASSSIGNMENT expression, key = value possibly inside an inline table */
        parseAssign() {
          return this.callNow(this.parseKeyword, this.recordAssignKeyword);
        }
        recordAssignKeyword(key) {
          if (this.state.resultTable) {
            this.state.resultTable.push(key);
          } else {
            this.state.resultTable = [key];
          }
          return this.goto(this.parseAssignKeywordPreDot);
        }
        parseAssignKeywordPreDot() {
          if (this.char === CHAR_PERIOD) {
            return this.next(this.parseAssignKeywordPostDot);
          } else if (this.char !== CHAR_SP && this.char !== CTRL_I) {
            return this.goto(this.parseAssignEqual);
          }
        }
        parseAssignKeywordPostDot() {
          if (this.char !== CHAR_SP && this.char !== CTRL_I) {
            return this.callNow(this.parseKeyword, this.recordAssignKeyword);
          }
        }
        parseAssignEqual() {
          if (this.char === CHAR_EQUALS) {
            return this.next(this.parseAssignPreValue);
          } else {
            throw this.error(new TomlError('Invalid character, expected "="'));
          }
        }
        parseAssignPreValue() {
          if (this.char === CHAR_SP || this.char === CTRL_I) {
            return null;
          } else {
            return this.callNow(this.parseValue, this.recordAssignValue);
          }
        }
        recordAssignValue(value) {
          return this.returnNow({ key: this.state.resultTable, value });
        }
        /* COMMENTS: #...eol */
        parseComment() {
          do {
            if (this.char === Parser4.END || this.char === CTRL_J) {
              return this.return();
            }
          } while (this.nextChar());
        }
        /* TABLES AND LISTS, [foo] and [[foo]] */
        parseTableOrList() {
          if (this.char === CHAR_LSQB) {
            this.next(this.parseList);
          } else {
            return this.goto(this.parseTable);
          }
        }
        /* TABLE [foo.bar.baz] */
        parseTable() {
          this.ctx = this.obj;
          return this.goto(this.parseTableNext);
        }
        parseTableNext() {
          if (this.char === CHAR_SP || this.char === CTRL_I) {
            return null;
          } else {
            return this.callNow(this.parseKeyword, this.parseTableMore);
          }
        }
        parseTableMore(keyword) {
          if (this.char === CHAR_SP || this.char === CTRL_I) {
            return null;
          } else if (this.char === CHAR_RSQB) {
            if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) {
              throw this.error(new TomlError("Can't redefine existing key"));
            } else {
              this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table();
              this.ctx[_declared] = true;
            }
            return this.next(this.parseWhitespaceToEOL);
          } else if (this.char === CHAR_PERIOD) {
            if (!hasKey(this.ctx, keyword)) {
              this.ctx = this.ctx[keyword] = Table();
            } else if (isTable(this.ctx[keyword])) {
              this.ctx = this.ctx[keyword];
            } else if (isList(this.ctx[keyword])) {
              this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
            } else {
              throw this.error(new TomlError("Can't redefine existing key"));
            }
            return this.next(this.parseTableNext);
          } else {
            throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"));
          }
        }
        /* LIST [[a.b.c]] */
        parseList() {
          this.ctx = this.obj;
          return this.goto(this.parseListNext);
        }
        parseListNext() {
          if (this.char === CHAR_SP || this.char === CTRL_I) {
            return null;
          } else {
            return this.callNow(this.parseKeyword, this.parseListMore);
          }
        }
        parseListMore(keyword) {
          if (this.char === CHAR_SP || this.char === CTRL_I) {
            return null;
          } else if (this.char === CHAR_RSQB) {
            if (!hasKey(this.ctx, keyword)) {
              this.ctx[keyword] = List();
            }
            if (isInlineList(this.ctx[keyword])) {
              throw this.error(new TomlError("Can't extend an inline array"));
            } else if (isList(this.ctx[keyword])) {
              const next = Table();
              this.ctx[keyword].push(next);
              this.ctx = next;
            } else {
              throw this.error(new TomlError("Can't redefine an existing key"));
            }
            return this.next(this.parseListEnd);
          } else if (this.char === CHAR_PERIOD) {
            if (!hasKey(this.ctx, keyword)) {
              this.ctx = this.ctx[keyword] = Table();
            } else if (isInlineList(this.ctx[keyword])) {
              throw this.error(new TomlError("Can't extend an inline array"));
            } else if (isInlineTable(this.ctx[keyword])) {
              throw this.error(new TomlError("Can't extend an inline table"));
            } else if (isList(this.ctx[keyword])) {
              this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
            } else if (isTable(this.ctx[keyword])) {
              this.ctx = this.ctx[keyword];
            } else {
              throw this.error(new TomlError("Can't redefine an existing key"));
            }
            return this.next(this.parseListNext);
          } else {
            throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"));
          }
        }
        parseListEnd(keyword) {
          if (this.char === CHAR_RSQB) {
            return this.next(this.parseWhitespaceToEOL);
          } else {
            throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"));
          }
        }
        /* VALUE string, number, boolean, inline list, inline object */
        parseValue() {
          if (this.char === Parser4.END) {
            throw this.error(new TomlError("Key without value"));
          } else if (this.char === CHAR_QUOT) {
            return this.next(this.parseDoubleString);
          }
          if (this.char === CHAR_APOS) {
            return this.next(this.parseSingleString);
          } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
            return this.goto(this.parseNumberSign);
          } else if (this.char === CHAR_i) {
            return this.next(this.parseInf);
          } else if (this.char === CHAR_n) {
            return this.next(this.parseNan);
          } else if (isDigit(this.char)) {
            return this.goto(this.parseNumberOrDateTime);
          } else if (this.char === CHAR_t || this.char === CHAR_f) {
            return this.goto(this.parseBoolean);
          } else if (this.char === CHAR_LSQB) {
            return this.call(this.parseInlineList, this.recordValue);
          } else if (this.char === CHAR_LCUB) {
            return this.call(this.parseInlineTable, this.recordValue);
          } else {
            throw this.error(new TomlError("Unexpected character, expecting string, number, datetime, boolean, inline array or inline table"));
          }
        }
        recordValue(value) {
          return this.returnNow(value);
        }
        parseInf() {
          if (this.char === CHAR_n) {
            return this.next(this.parseInf2);
          } else {
            throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
          }
        }
        parseInf2() {
          if (this.char === CHAR_f) {
            if (this.state.buf === "-") {
              return this.return(-Infinity);
            } else {
              return this.return(Infinity);
            }
          } else {
            throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
          }
        }
        parseNan() {
          if (this.char === CHAR_a) {
            return this.next(this.parseNan2);
          } else {
            throw this.error(new TomlError('Unexpected character, expected "nan"'));
          }
        }
        parseNan2() {
          if (this.char === CHAR_n) {
            return this.return(NaN);
          } else {
            throw this.error(new TomlError('Unexpected character, expected "nan"'));
          }
        }
        /* KEYS, barewords or basic, literal, or dotted */
        parseKeyword() {
          if (this.char === CHAR_QUOT) {
            return this.next(this.parseBasicString);
          } else if (this.char === CHAR_APOS) {
            return this.next(this.parseLiteralString);
          } else {
            return this.goto(this.parseBareKey);
          }
        }
        /* KEYS: barewords */
        parseBareKey() {
          do {
            if (this.char === Parser4.END) {
              throw this.error(new TomlError("Key ended without value"));
            } else if (isAlphaNumHyphen(this.char)) {
              this.consume();
            } else if (this.state.buf.length === 0) {
              throw this.error(new TomlError("Empty bare keys are not allowed"));
            } else {
              return this.returnNow();
            }
          } while (this.nextChar());
        }
        /* STRINGS, single quoted (literal) */
        parseSingleString() {
          if (this.char === CHAR_APOS) {
            return this.next(this.parseLiteralMultiStringMaybe);
          } else {
            return this.goto(this.parseLiteralString);
          }
        }
        parseLiteralString() {
          do {
            if (this.char === CHAR_APOS) {
              return this.return();
            } else if (this.atEndOfLine()) {
              throw this.error(new TomlError("Unterminated string"));
            } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
              throw this.errorControlCharInString();
            } else {
              this.consume();
            }
          } while (this.nextChar());
        }
        parseLiteralMultiStringMaybe() {
          if (this.char === CHAR_APOS) {
            return this.next(this.parseLiteralMultiString);
          } else {
            return this.returnNow();
          }
        }
        parseLiteralMultiString() {
          if (this.char === CTRL_M) {
            return null;
          } else if (this.char === CTRL_J) {
            return this.next(this.parseLiteralMultiStringContent);
          } else {
            return this.goto(this.parseLiteralMultiStringContent);
          }
        }
        parseLiteralMultiStringContent() {
          do {
            if (this.char === CHAR_APOS) {
              return this.next(this.parseLiteralMultiEnd);
            } else if (this.char === Parser4.END) {
              throw this.error(new TomlError("Unterminated multi-line string"));
            } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
              throw this.errorControlCharInString();
            } else {
              this.consume();
            }
          } while (this.nextChar());
        }
        parseLiteralMultiEnd() {
          if (this.char === CHAR_APOS) {
            return this.next(this.parseLiteralMultiEnd2);
          } else {
            this.state.buf += "'";
            return this.goto(this.parseLiteralMultiStringContent);
          }
        }
        parseLiteralMultiEnd2() {
          if (this.char === CHAR_APOS) {
            return this.return();
          } else {
            this.state.buf += "''";
            return this.goto(this.parseLiteralMultiStringContent);
          }
        }
        /* STRINGS double quoted */
        parseDoubleString() {
          if (this.char === CHAR_QUOT) {
            return this.next(this.parseMultiStringMaybe);
          } else {
            return this.goto(this.parseBasicString);
          }
        }
        parseBasicString() {
          do {
            if (this.char === CHAR_BSOL) {
              return this.call(this.parseEscape, this.recordEscapeReplacement);
            } else if (this.char === CHAR_QUOT) {
              return this.return();
            } else if (this.atEndOfLine()) {
              throw this.error(new TomlError("Unterminated string"));
            } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
              throw this.errorControlCharInString();
            } else {
              this.consume();
            }
          } while (this.nextChar());
        }
        recordEscapeReplacement(replacement) {
          this.state.buf += replacement;
          return this.goto(this.parseBasicString);
        }
        parseMultiStringMaybe() {
          if (this.char === CHAR_QUOT) {
            return this.next(this.parseMultiString);
          } else {
            return this.returnNow();
          }
        }
        parseMultiString() {
          if (this.char === CTRL_M) {
            return null;
          } else if (this.char === CTRL_J) {
            return this.next(this.parseMultiStringContent);
          } else {
            return this.goto(this.parseMultiStringContent);
          }
        }
        parseMultiStringContent() {
          do {
            if (this.char === CHAR_BSOL) {
              return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement);
            } else if (this.char === CHAR_QUOT) {
              return this.next(this.parseMultiEnd);
            } else if (this.char === Parser4.END) {
              throw this.error(new TomlError("Unterminated multi-line string"));
            } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
              throw this.errorControlCharInString();
            } else {
              this.consume();
            }
          } while (this.nextChar());
        }
        errorControlCharInString() {
          let displayCode = "\\u00";
          if (this.char < 16) {
            displayCode += "0";
          }
          displayCode += this.char.toString(16);
          return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`));
        }
        recordMultiEscapeReplacement(replacement) {
          this.state.buf += replacement;
          return this.goto(this.parseMultiStringContent);
        }
        parseMultiEnd() {
          if (this.char === CHAR_QUOT) {
            return this.next(this.parseMultiEnd2);
          } else {
            this.state.buf += '"';
            return this.goto(this.parseMultiStringContent);
          }
        }
        parseMultiEnd2() {
          if (this.char === CHAR_QUOT) {
            return this.return();
          } else {
            this.state.buf += '""';
            return this.goto(this.parseMultiStringContent);
          }
        }
        parseMultiEscape() {
          if (this.char === CTRL_M || this.char === CTRL_J) {
            return this.next(this.parseMultiTrim);
          } else if (this.char === CHAR_SP || this.char === CTRL_I) {
            return this.next(this.parsePreMultiTrim);
          } else {
            return this.goto(this.parseEscape);
          }
        }
        parsePreMultiTrim() {
          if (this.char === CHAR_SP || this.char === CTRL_I) {
            return null;
          } else if (this.char === CTRL_M || this.char === CTRL_J) {
            return this.next(this.parseMultiTrim);
          } else {
            throw this.error(new TomlError("Can't escape whitespace"));
          }
        }
        parseMultiTrim() {
          if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
            return null;
          } else {
            return this.returnNow();
          }
        }
        parseEscape() {
          if (this.char in escapes) {
            return this.return(escapes[this.char]);
          } else if (this.char === CHAR_u) {
            return this.call(this.parseSmallUnicode, this.parseUnicodeReturn);
          } else if (this.char === CHAR_U) {
            return this.call(this.parseLargeUnicode, this.parseUnicodeReturn);
          } else {
            throw this.error(new TomlError("Unknown escape character: " + this.char));
          }
        }
        parseUnicodeReturn(char) {
          try {
            const codePoint = parseInt(char, 16);
            if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) {
              throw this.error(new TomlError("Invalid unicode, character in range 0xD800 - 0xDFFF is reserved"));
            }
            return this.returnNow(String.fromCodePoint(codePoint));
          } catch (err) {
            throw this.error(TomlError.wrap(err));
          }
        }
        parseSmallUnicode() {
          if (!isHexit(this.char)) {
            throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"));
          } else {
            this.consume();
            if (this.state.buf.length >= 4) return this.return();
          }
        }
        parseLargeUnicode() {
          if (!isHexit(this.char)) {
            throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"));
          } else {
            this.consume();
            if (this.state.buf.length >= 8) return this.return();
          }
        }
        /* NUMBERS */
        parseNumberSign() {
          this.consume();
          return this.next(this.parseMaybeSignedInfOrNan);
        }
        parseMaybeSignedInfOrNan() {
          if (this.char === CHAR_i) {
            return this.next(this.parseInf);
          } else if (this.char === CHAR_n) {
            return this.next(this.parseNan);
          } else {
            return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart);
          }
        }
        parseNumberIntegerStart() {
          if (this.char === CHAR_0) {
            this.consume();
            return this.next(this.parseNumberIntegerExponentOrDecimal);
          } else {
            return this.goto(this.parseNumberInteger);
          }
        }
        parseNumberIntegerExponentOrDecimal() {
          if (this.char === CHAR_PERIOD) {
            this.consume();
            return this.call(this.parseNoUnder, this.parseNumberFloat);
          } else if (this.char === CHAR_E || this.char === CHAR_e) {
            this.consume();
            return this.next(this.parseNumberExponentSign);
          } else {
            return this.returnNow(Integer(this.state.buf));
          }
        }
        parseNumberInteger() {
          if (isDigit(this.char)) {
            this.consume();
          } else if (this.char === CHAR_LOWBAR) {
            return this.call(this.parseNoUnder);
          } else if (this.char === CHAR_E || this.char === CHAR_e) {
            this.consume();
            return this.next(this.parseNumberExponentSign);
          } else if (this.char === CHAR_PERIOD) {
            this.consume();
            return this.call(this.parseNoUnder, this.parseNumberFloat);
          } else {
            const result = Integer(this.state.buf);
            if (result.isNaN()) {
              throw this.error(new TomlError("Invalid number"));
            } else {
              return this.returnNow(result);
            }
          }
        }
        parseNoUnder() {
          if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) {
            throw this.error(new TomlError("Unexpected character, expected digit"));
          } else if (this.atEndOfWord()) {
            throw this.error(new TomlError("Incomplete number"));
          }
          return this.returnNow();
        }
        parseNoUnderHexOctBinLiteral() {
          if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD) {
            throw this.error(new TomlError("Unexpected character, expected digit"));
          } else if (this.atEndOfWord()) {
            throw this.error(new TomlError("Incomplete number"));
          }
          return this.returnNow();
        }
        parseNumberFloat() {
          if (this.char === CHAR_LOWBAR) {
            return this.call(this.parseNoUnder, this.parseNumberFloat);
          } else if (isDigit(this.char)) {
            this.consume();
          } else if (this.char === CHAR_E || this.char === CHAR_e) {
            this.consume();
            return this.next(this.parseNumberExponentSign);
          } else {
            return this.returnNow(Float(this.state.buf));
          }
        }
        parseNumberExponentSign() {
          if (isDigit(this.char)) {
            return this.goto(this.parseNumberExponent);
          } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
            this.consume();
            this.call(this.parseNoUnder, this.parseNumberExponent);
          } else {
            throw this.error(new TomlError("Unexpected character, expected -, + or digit"));
          }
        }
        parseNumberExponent() {
          if (isDigit(this.char)) {
            this.consume();
          } else if (this.char === CHAR_LOWBAR) {
            return this.call(this.parseNoUnder);
          } else {
            return this.returnNow(Float(this.state.buf));
          }
        }
        /* NUMBERS or DATETIMES  */
        parseNumberOrDateTime() {
          if (this.char === CHAR_0) {
            this.consume();
            return this.next(this.parseNumberBaseOrDateTime);
          } else {
            return this.goto(this.parseNumberOrDateTimeOnly);
          }
        }
        parseNumberOrDateTimeOnly() {
          if (this.char === CHAR_LOWBAR) {
            return this.call(this.parseNoUnder, this.parseNumberInteger);
          } else if (isDigit(this.char)) {
            this.consume();
            if (this.state.buf.length > 4) this.next(this.parseNumberInteger);
          } else if (this.char === CHAR_E || this.char === CHAR_e) {
            this.consume();
            return this.next(this.parseNumberExponentSign);
          } else if (this.char === CHAR_PERIOD) {
            this.consume();
            return this.call(this.parseNoUnder, this.parseNumberFloat);
          } else if (this.char === CHAR_HYPHEN) {
            return this.goto(this.parseDateTime);
          } else if (this.char === CHAR_COLON) {
            return this.goto(this.parseOnlyTimeHour);
          } else {
            return this.returnNow(Integer(this.state.buf));
          }
        }
        parseDateTimeOnly() {
          if (this.state.buf.length < 4) {
            if (isDigit(this.char)) {
              return this.consume();
            } else if (this.char === CHAR_COLON) {
              return this.goto(this.parseOnlyTimeHour);
            } else {
              throw this.error(new TomlError("Expected digit while parsing year part of a date"));
            }
          } else {
            if (this.char === CHAR_HYPHEN) {
              return this.goto(this.parseDateTime);
            } else {
              throw this.error(new TomlError("Expected hyphen (-) while parsing year part of date"));
            }
          }
        }
        parseNumberBaseOrDateTime() {
          if (this.char === CHAR_b) {
            this.consume();
            return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerBin);
          } else if (this.char === CHAR_o) {
            this.consume();
            return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerOct);
          } else if (this.char === CHAR_x) {
            this.consume();
            return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerHex);
          } else if (this.char === CHAR_PERIOD) {
            return this.goto(this.parseNumberInteger);
          } else if (isDigit(this.char)) {
            return this.goto(this.parseDateTimeOnly);
          } else {
            return this.returnNow(Integer(this.state.buf));
          }
        }
        parseIntegerHex() {
          if (isHexit(this.char)) {
            this.consume();
          } else if (this.char === CHAR_LOWBAR) {
            return this.call(this.parseNoUnderHexOctBinLiteral);
          } else {
            const result = Integer(this.state.buf);
            if (result.isNaN()) {
              throw this.error(new TomlError("Invalid number"));
            } else {
              return this.returnNow(result);
            }
          }
        }
        parseIntegerOct() {
          if (isOctit(this.char)) {
            this.consume();
          } else if (this.char === CHAR_LOWBAR) {
            return this.call(this.parseNoUnderHexOctBinLiteral);
          } else {
            const result = Integer(this.state.buf);
            if (result.isNaN()) {
              throw this.error(new TomlError("Invalid number"));
            } else {
              return this.returnNow(result);
            }
          }
        }
        parseIntegerBin() {
          if (isBit(this.char)) {
            this.consume();
          } else if (this.char === CHAR_LOWBAR) {
            return this.call(this.parseNoUnderHexOctBinLiteral);
          } else {
            const result = Integer(this.state.buf);
            if (result.isNaN()) {
              throw this.error(new TomlError("Invalid number"));
            } else {
              return this.returnNow(result);
            }
          }
        }
        /* DATETIME */
        parseDateTime() {
          if (this.state.buf.length < 4) {
            throw this.error(new TomlError("Years less than 1000 must be zero padded to four characters"));
          }
          this.state.result = this.state.buf;
          this.state.buf = "";
          return this.next(this.parseDateMonth);
        }
        parseDateMonth() {
          if (this.char === CHAR_HYPHEN) {
            if (this.state.buf.length < 2) {
              throw this.error(new TomlError("Months less than 10 must be zero padded to two characters"));
            }
            this.state.result += "-" + this.state.buf;
            this.state.buf = "";
            return this.next(this.parseDateDay);
          } else if (isDigit(this.char)) {
            this.consume();
          } else {
            throw this.error(new TomlError("Incomplete datetime"));
          }
        }
        parseDateDay() {
          if (this.char === CHAR_T || this.char === CHAR_SP) {
            if (this.state.buf.length < 2) {
              throw this.error(new TomlError("Days less than 10 must be zero padded to two characters"));
            }
            this.state.result += "-" + this.state.buf;
            this.state.buf = "";
            return this.next(this.parseStartTimeHour);
          } else if (this.atEndOfWord()) {
            return this.returnNow(createDate(this.state.result + "-" + this.state.buf));
          } else if (isDigit(this.char)) {
            this.consume();
          } else {
            throw this.error(new TomlError("Incomplete datetime"));
          }
        }
        parseStartTimeHour() {
          if (this.atEndOfWord()) {
            return this.returnNow(createDate(this.state.result));
          } else {
            return this.goto(this.parseTimeHour);
          }
        }
        parseTimeHour() {
          if (this.char === CHAR_COLON) {
            if (this.state.buf.length < 2) {
              throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"));
            }
            this.state.result += "T" + this.state.buf;
            this.state.buf = "";
            return this.next(this.parseTimeMin);
          } else if (isDigit(this.char)) {
            this.consume();
          } else {
            throw this.error(new TomlError("Incomplete datetime"));
          }
        }
        parseTimeMin() {
          if (this.state.buf.length < 2 && isDigit(this.char)) {
            this.consume();
          } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
            this.state.result += ":" + this.state.buf;
            this.state.buf = "";
            return this.next(this.parseTimeSec);
          } else {
            throw this.error(new TomlError("Incomplete datetime"));
          }
        }
        parseTimeSec() {
          if (isDigit(this.char)) {
            this.consume();
            if (this.state.buf.length === 2) {
              this.state.result += ":" + this.state.buf;
              this.state.buf = "";
              return this.next(this.parseTimeZoneOrFraction);
            }
          } else {
            throw this.error(new TomlError("Incomplete datetime"));
          }
        }
        parseOnlyTimeHour() {
          if (this.char === CHAR_COLON) {
            if (this.state.buf.length < 2) {
              throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"));
            }
            this.state.result = this.state.buf;
            this.state.buf = "";
            return this.next(this.parseOnlyTimeMin);
          } else {
            throw this.error(new TomlError("Incomplete time"));
          }
        }
        parseOnlyTimeMin() {
          if (this.state.buf.length < 2 && isDigit(this.char)) {
            this.consume();
          } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
            this.state.result += ":" + this.state.buf;
            this.state.buf = "";
            return this.next(this.parseOnlyTimeSec);
          } else {
            throw this.error(new TomlError("Incomplete time"));
          }
        }
        parseOnlyTimeSec() {
          if (isDigit(this.char)) {
            this.consume();
            if (this.state.buf.length === 2) {
              return this.next(this.parseOnlyTimeFractionMaybe);
            }
          } else {
            throw this.error(new TomlError("Incomplete time"));
          }
        }
        parseOnlyTimeFractionMaybe() {
          this.state.result += ":" + this.state.buf;
          if (this.char === CHAR_PERIOD) {
            this.state.buf = "";
            this.next(this.parseOnlyTimeFraction);
          } else {
            return this.return(createTime(this.state.result));
          }
        }
        parseOnlyTimeFraction() {
          if (isDigit(this.char)) {
            this.consume();
          } else if (this.atEndOfWord()) {
            if (this.state.buf.length === 0) throw this.error(new TomlError("Expected digit in milliseconds"));
            return this.returnNow(createTime(this.state.result + "." + this.state.buf));
          } else {
            throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"));
          }
        }
        parseTimeZoneOrFraction() {
          if (this.char === CHAR_PERIOD) {
            this.consume();
            this.next(this.parseDateTimeFraction);
          } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
            this.consume();
            this.next(this.parseTimeZoneHour);
          } else if (this.char === CHAR_Z) {
            this.consume();
            return this.return(createDateTime(this.state.result + this.state.buf));
          } else if (this.atEndOfWord()) {
            return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf));
          } else {
            throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"));
          }
        }
        parseDateTimeFraction() {
          if (isDigit(this.char)) {
            this.consume();
          } else if (this.state.buf.length === 1) {
            throw this.error(new TomlError("Expected digit in milliseconds"));
          } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
            this.consume();
            this.next(this.parseTimeZoneHour);
          } else if (this.char === CHAR_Z) {
            this.consume();
            return this.return(createDateTime(this.state.result + this.state.buf));
          } else if (this.atEndOfWord()) {
            return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf));
          } else {
            throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"));
          }
        }
        parseTimeZoneHour() {
          if (isDigit(this.char)) {
            this.consume();
            if (/\d\d$/.test(this.state.buf)) return this.next(this.parseTimeZoneSep);
          } else {
            throw this.error(new TomlError("Unexpected character in datetime, expected digit"));
          }
        }
        parseTimeZoneSep() {
          if (this.char === CHAR_COLON) {
            this.consume();
            this.next(this.parseTimeZoneMin);
          } else {
            throw this.error(new TomlError("Unexpected character in datetime, expected colon"));
          }
        }
        parseTimeZoneMin() {
          if (isDigit(this.char)) {
            this.consume();
            if (/\d\d$/.test(this.state.buf)) return this.return(createDateTime(this.state.result + this.state.buf));
          } else {
            throw this.error(new TomlError("Unexpected character in datetime, expected digit"));
          }
        }
        /* BOOLEAN */
        parseBoolean() {
          if (this.char === CHAR_t) {
            this.consume();
            return this.next(this.parseTrue_r);
          } else if (this.char === CHAR_f) {
            this.consume();
            return this.next(this.parseFalse_a);
          }
        }
        parseTrue_r() {
          if (this.char === CHAR_r) {
            this.consume();
            return this.next(this.parseTrue_u);
          } else {
            throw this.error(new TomlError("Invalid boolean, expected true or false"));
          }
        }
        parseTrue_u() {
          if (this.char === CHAR_u) {
            this.consume();
            return this.next(this.parseTrue_e);
          } else {
            throw this.error(new TomlError("Invalid boolean, expected true or false"));
          }
        }
        parseTrue_e() {
          if (this.char === CHAR_e) {
            return this.return(true);
          } else {
            throw this.error(new TomlError("Invalid boolean, expected true or false"));
          }
        }
        parseFalse_a() {
          if (this.char === CHAR_a) {
            this.consume();
            return this.next(this.parseFalse_l);
          } else {
            throw this.error(new TomlError("Invalid boolean, expected true or false"));
          }
        }
        parseFalse_l() {
          if (this.char === CHAR_l) {
            this.consume();
            return this.next(this.parseFalse_s);
          } else {
            throw this.error(new TomlError("Invalid boolean, expected true or false"));
          }
        }
        parseFalse_s() {
          if (this.char === CHAR_s) {
            this.consume();
            return this.next(this.parseFalse_e);
          } else {
            throw this.error(new TomlError("Invalid boolean, expected true or false"));
          }
        }
        parseFalse_e() {
          if (this.char === CHAR_e) {
            return this.return(false);
          } else {
            throw this.error(new TomlError("Invalid boolean, expected true or false"));
          }
        }
        /* INLINE LISTS */
        parseInlineList() {
          if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
            return null;
          } else if (this.char === Parser4.END) {
            throw this.error(new TomlError("Unterminated inline array"));
          } else if (this.char === CHAR_NUM) {
            return this.call(this.parseComment);
          } else if (this.char === CHAR_RSQB) {
            return this.return(this.state.resultArr || InlineList());
          } else {
            return this.callNow(this.parseValue, this.recordInlineListValue);
          }
        }
        recordInlineListValue(value) {
          if (this.state.resultArr) {
            const listType = this.state.resultArr[_contentType];
            const valueType = tomlType(value);
            if (listType !== valueType) {
              throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`));
            }
          } else {
            this.state.resultArr = InlineList(tomlType(value));
          }
          if (isFloat(value) || isInteger(value)) {
            this.state.resultArr.push(value.valueOf());
          } else {
            this.state.resultArr.push(value);
          }
          return this.goto(this.parseInlineListNext);
        }
        parseInlineListNext() {
          if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
            return null;
          } else if (this.char === CHAR_NUM) {
            return this.call(this.parseComment);
          } else if (this.char === CHAR_COMMA) {
            return this.next(this.parseInlineList);
          } else if (this.char === CHAR_RSQB) {
            return this.goto(this.parseInlineList);
          } else {
            throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"));
          }
        }
        /* INLINE TABLE */
        parseInlineTable() {
          if (this.char === CHAR_SP || this.char === CTRL_I) {
            return null;
          } else if (this.char === Parser4.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
            throw this.error(new TomlError("Unterminated inline array"));
          } else if (this.char === CHAR_RCUB) {
            return this.return(this.state.resultTable || InlineTable());
          } else {
            if (!this.state.resultTable) this.state.resultTable = InlineTable();
            return this.callNow(this.parseAssign, this.recordInlineTableValue);
          }
        }
        recordInlineTableValue(kv) {
          let target = this.state.resultTable;
          let finalKey = kv.key.pop();
          for (let kw of kv.key) {
            if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
              throw this.error(new TomlError("Can't redefine existing key"));
            }
            target = target[kw] = target[kw] || Table();
          }
          if (hasKey(target, finalKey)) {
            throw this.error(new TomlError("Can't redefine existing key"));
          }
          if (isInteger(kv.value) || isFloat(kv.value)) {
            target[finalKey] = kv.value.valueOf();
          } else {
            target[finalKey] = kv.value;
          }
          return this.goto(this.parseInlineTableNext);
        }
        parseInlineTableNext() {
          if (this.char === CHAR_SP || this.char === CTRL_I) {
            return null;
          } else if (this.char === Parser4.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
            throw this.error(new TomlError("Unterminated inline array"));
          } else if (this.char === CHAR_COMMA) {
            return this.next(this.parseInlineTable);
          } else if (this.char === CHAR_RCUB) {
            return this.goto(this.parseInlineTable);
          } else {
            throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"));
          }
        }
      }
      return TOMLParser;
    }
    __name(makeParserClass, "makeParserClass");
  }
});

// node_modules/@iarna/toml/parse-pretty-error.js
var require_parse_pretty_error = __commonJS({
  "node_modules/@iarna/toml/parse-pretty-error.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = prettyError;
    function prettyError(err, buf) {
      if (err.pos == null || err.line == null) return err;
      let msg = err.message;
      msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:
`;
      if (buf && buf.split) {
        const lines = buf.split(/\n/);
        const lineNumWidth = String(Math.min(lines.length, err.line + 3)).length;
        let linePadding = " ";
        while (linePadding.length < lineNumWidth) linePadding += " ";
        for (let ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) {
          let lineNum = String(ii + 1);
          if (lineNum.length < lineNumWidth) lineNum = " " + lineNum;
          if (err.line === ii) {
            msg += lineNum + "> " + lines[ii] + "\n";
            msg += linePadding + "  ";
            for (let hh = 0; hh < err.col; ++hh) {
              msg += " ";
            }
            msg += "^\n";
          } else {
            msg += lineNum + ": " + lines[ii] + "\n";
          }
        }
      }
      err.message = msg + "\n";
      return err;
    }
    __name(prettyError, "prettyError");
  }
});

// node_modules/@iarna/toml/parse-string.js
var require_parse_string = __commonJS({
  "node_modules/@iarna/toml/parse-string.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = parseString;
    var TOMLParser = require_toml_parser();
    var prettyError = require_parse_pretty_error();
    function parseString(str2) {
      if (globalThis.Buffer && globalThis.Buffer.isBuffer(str2)) {
        str2 = str2.toString("utf8");
      }
      const parser6 = new TOMLParser();
      try {
        parser6.parse(str2);
        return parser6.finish();
      } catch (err) {
        throw prettyError(err, str2);
      }
    }
    __name(parseString, "parseString");
  }
});

// node_modules/@iarna/toml/parse-async.js
var require_parse_async = __commonJS({
  "node_modules/@iarna/toml/parse-async.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = parseAsync;
    var TOMLParser = require_toml_parser();
    var prettyError = require_parse_pretty_error();
    function parseAsync(str2, opts) {
      if (!opts) opts = {};
      const index = 0;
      const blocksize = opts.blocksize || 40960;
      const parser6 = new TOMLParser();
      return new Promise((resolve24, reject) => {
        setImmediate(parseAsyncNext, index, blocksize, resolve24, reject);
      });
      function parseAsyncNext(index2, blocksize2, resolve24, reject) {
        if (index2 >= str2.length) {
          try {
            return resolve24(parser6.finish());
          } catch (err) {
            return reject(prettyError(err, str2));
          }
        }
        try {
          parser6.parse(str2.slice(index2, index2 + blocksize2));
          setImmediate(parseAsyncNext, index2 + blocksize2, blocksize2, resolve24, reject);
        } catch (err) {
          reject(prettyError(err, str2));
        }
      }
      __name(parseAsyncNext, "parseAsyncNext");
    }
    __name(parseAsync, "parseAsync");
  }
});

// node_modules/@iarna/toml/parse-stream.js
var require_parse_stream = __commonJS({
  "node_modules/@iarna/toml/parse-stream.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = parseStream;
    var stream2 = __require("stream");
    var TOMLParser = require_toml_parser();
    function parseStream(stm) {
      if (stm) {
        return parseReadable(stm);
      } else {
        return parseTransform(stm);
      }
    }
    __name(parseStream, "parseStream");
    function parseReadable(stm) {
      const parser6 = new TOMLParser();
      stm.setEncoding("utf8");
      return new Promise((resolve24, reject) => {
        let readable;
        let ended = false;
        let errored = false;
        function finish() {
          ended = true;
          if (readable) return;
          try {
            resolve24(parser6.finish());
          } catch (err) {
            reject(err);
          }
        }
        __name(finish, "finish");
        function error(err) {
          errored = true;
          reject(err);
        }
        __name(error, "error");
        stm.once("end", finish);
        stm.once("error", error);
        readNext();
        function readNext() {
          readable = true;
          let data;
          while ((data = stm.read()) !== null) {
            try {
              parser6.parse(data);
            } catch (err) {
              return error(err);
            }
          }
          readable = false;
          if (ended) return finish();
          if (errored) return;
          stm.once("readable", readNext);
        }
        __name(readNext, "readNext");
      });
    }
    __name(parseReadable, "parseReadable");
    function parseTransform() {
      const parser6 = new TOMLParser();
      return new stream2.Transform({
        objectMode: true,
        transform(chunk, encoding, cb) {
          try {
            parser6.parse(chunk.toString(encoding));
          } catch (err) {
            this.emit("error", err);
          }
          cb();
        },
        flush(cb) {
          try {
            this.push(parser6.finish());
          } catch (err) {
            this.emit("error", err);
          }
          cb();
        }
      });
    }
    __name(parseTransform, "parseTransform");
  }
});

// node_modules/@iarna/toml/parse.js
var require_parse10 = __commonJS({
  "node_modules/@iarna/toml/parse.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = require_parse_string();
    module2.exports.async = require_parse_async();
    module2.exports.stream = require_parse_stream();
    module2.exports.prettyError = require_parse_pretty_error();
  }
});

// node_modules/@iarna/toml/stringify.js
var require_stringify3 = __commonJS({
  "node_modules/@iarna/toml/stringify.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = stringify5;
    module2.exports.value = stringifyInline;
    function stringify5(obj) {
      if (obj === null) throw typeError("null");
      if (obj === void 0) throw typeError("undefined");
      if (typeof obj !== "object") throw typeError(typeof obj);
      if (typeof obj.toJSON === "function") obj = obj.toJSON();
      if (obj == null) return null;
      const type = tomlType2(obj);
      if (type !== "table") throw typeError(type);
      return stringifyObject("", "", obj);
    }
    __name(stringify5, "stringify");
    function typeError(type) {
      return new Error("Can only stringify objects, not " + type);
    }
    __name(typeError, "typeError");
    function arrayOneTypeError() {
      return new Error("Array values can't have mixed types");
    }
    __name(arrayOneTypeError, "arrayOneTypeError");
    function getInlineKeys(obj) {
      return Object.keys(obj).filter((key) => isInline(obj[key]));
    }
    __name(getInlineKeys, "getInlineKeys");
    function getComplexKeys(obj) {
      return Object.keys(obj).filter((key) => !isInline(obj[key]));
    }
    __name(getComplexKeys, "getComplexKeys");
    function toJSON(obj) {
      let nobj = Array.isArray(obj) ? [] : Object.prototype.hasOwnProperty.call(obj, "__proto__") ? { ["__proto__"]: void 0 } : {};
      for (let prop of Object.keys(obj)) {
        if (obj[prop] && typeof obj[prop].toJSON === "function" && !("toISOString" in obj[prop])) {
          nobj[prop] = obj[prop].toJSON();
        } else {
          nobj[prop] = obj[prop];
        }
      }
      return nobj;
    }
    __name(toJSON, "toJSON");
    function stringifyObject(prefix, indent, obj) {
      obj = toJSON(obj);
      var inlineKeys;
      var complexKeys;
      inlineKeys = getInlineKeys(obj);
      complexKeys = getComplexKeys(obj);
      var result = [];
      var inlineIndent = indent || "";
      inlineKeys.forEach((key) => {
        var type = tomlType2(obj[key]);
        if (type !== "undefined" && type !== "null") {
          result.push(inlineIndent + stringifyKey(key) + " = " + stringifyAnyInline(obj[key], true));
        }
      });
      if (result.length > 0) result.push("");
      var complexIndent = prefix && inlineKeys.length > 0 ? indent + "  " : "";
      complexKeys.forEach((key) => {
        result.push(stringifyComplex(prefix, complexIndent, key, obj[key]));
      });
      return result.join("\n");
    }
    __name(stringifyObject, "stringifyObject");
    function isInline(value) {
      switch (tomlType2(value)) {
        case "undefined":
        case "null":
        case "integer":
        case "nan":
        case "float":
        case "boolean":
        case "string":
        case "datetime":
          return true;
        case "array":
          return value.length === 0 || tomlType2(value[0]) !== "table";
        case "table":
          return Object.keys(value).length === 0;
        /* istanbul ignore next */
        default:
          return false;
      }
    }
    __name(isInline, "isInline");
    function tomlType2(value) {
      if (value === void 0) {
        return "undefined";
      } else if (value === null) {
        return "null";
      } else if (typeof value === "bigint" || Number.isInteger(value) && !Object.is(value, -0)) {
        return "integer";
      } else if (typeof value === "number") {
        return "float";
      } else if (typeof value === "boolean") {
        return "boolean";
      } else if (typeof value === "string") {
        return "string";
      } else if ("toISOString" in value) {
        return isNaN(value) ? "undefined" : "datetime";
      } else if (Array.isArray(value)) {
        return "array";
      } else {
        return "table";
      }
    }
    __name(tomlType2, "tomlType");
    function stringifyKey(key) {
      var keyStr = String(key);
      if (/^[-A-Za-z0-9_]+$/.test(keyStr)) {
        return keyStr;
      } else {
        return stringifyBasicString(keyStr);
      }
    }
    __name(stringifyKey, "stringifyKey");
    function stringifyBasicString(str2) {
      return '"' + escapeString(str2).replace(/"/g, '\\"') + '"';
    }
    __name(stringifyBasicString, "stringifyBasicString");
    function stringifyLiteralString(str2) {
      return "'" + str2 + "'";
    }
    __name(stringifyLiteralString, "stringifyLiteralString");
    function numpad(num, str2) {
      while (str2.length < num) str2 = "0" + str2;
      return str2;
    }
    __name(numpad, "numpad");
    function escapeString(str2) {
      return str2.replace(/\\/g, "\\\\").replace(/[\b]/g, "\\b").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\f/g, "\\f").replace(/\r/g, "\\r").replace(/([\u0000-\u001f\u007f])/, (c3) => "\\u" + numpad(4, c3.codePointAt(0).toString(16)));
    }
    __name(escapeString, "escapeString");
    function stringifyMultilineString(str2) {
      let escaped = str2.split(/\n/).map((str3) => {
        return escapeString(str3).replace(/"(?="")/g, '\\"');
      }).join("\n");
      if (escaped.slice(-1) === '"') escaped += "\\\n";
      return '"""\n' + escaped + '"""';
    }
    __name(stringifyMultilineString, "stringifyMultilineString");
    function stringifyAnyInline(value, multilineOk) {
      let type = tomlType2(value);
      if (type === "string") {
        if (multilineOk && /\n/.test(value)) {
          type = "string-multiline";
        } else if (!/[\b\t\n\f\r']/.test(value) && /"/.test(value)) {
          type = "string-literal";
        }
      }
      return stringifyInline(value, type);
    }
    __name(stringifyAnyInline, "stringifyAnyInline");
    function stringifyInline(value, type) {
      if (!type) type = tomlType2(value);
      switch (type) {
        case "string-multiline":
          return stringifyMultilineString(value);
        case "string":
          return stringifyBasicString(value);
        case "string-literal":
          return stringifyLiteralString(value);
        case "integer":
          return stringifyInteger(value);
        case "float":
          return stringifyFloat(value);
        case "boolean":
          return stringifyBoolean(value);
        case "datetime":
          return stringifyDatetime(value);
        case "array":
          return stringifyInlineArray(value.filter((_) => tomlType2(_) !== "null" && tomlType2(_) !== "undefined" && tomlType2(_) !== "nan"));
        case "table":
          return stringifyInlineTable(value);
        /* istanbul ignore next */
        default:
          throw typeError(type);
      }
    }
    __name(stringifyInline, "stringifyInline");
    function stringifyInteger(value) {
      return String(value).replace(/\B(?=(\d{3})+(?!\d))/g, "_");
    }
    __name(stringifyInteger, "stringifyInteger");
    function stringifyFloat(value) {
      if (value === Infinity) {
        return "inf";
      } else if (value === -Infinity) {
        return "-inf";
      } else if (Object.is(value, NaN)) {
        return "nan";
      } else if (Object.is(value, -0)) {
        return "-0.0";
      }
      var chunks = String(value).split(".");
      var int = chunks[0];
      var dec = chunks[1] || 0;
      return stringifyInteger(int) + "." + dec;
    }
    __name(stringifyFloat, "stringifyFloat");
    function stringifyBoolean(value) {
      return String(value);
    }
    __name(stringifyBoolean, "stringifyBoolean");
    function stringifyDatetime(value) {
      return value.toISOString();
    }
    __name(stringifyDatetime, "stringifyDatetime");
    function isNumber3(type) {
      return type === "float" || type === "integer";
    }
    __name(isNumber3, "isNumber");
    function arrayType2(values) {
      var contentType = tomlType2(values[0]);
      if (values.every((_) => tomlType2(_) === contentType)) return contentType;
      if (values.every((_) => isNumber3(tomlType2(_)))) return "float";
      return "mixed";
    }
    __name(arrayType2, "arrayType");
    function validateArray(values) {
      const type = arrayType2(values);
      if (type === "mixed") {
        throw arrayOneTypeError();
      }
      return type;
    }
    __name(validateArray, "validateArray");
    function stringifyInlineArray(values) {
      values = toJSON(values);
      const type = validateArray(values);
      var result = "[";
      var stringified = values.map((_) => stringifyInline(_, type));
      if (stringified.join(", ").length > 60 || /\n/.test(stringified)) {
        result += "\n  " + stringified.join(",\n  ") + "\n";
      } else {
        result += " " + stringified.join(", ") + (stringified.length > 0 ? " " : "");
      }
      return result + "]";
    }
    __name(stringifyInlineArray, "stringifyInlineArray");
    function stringifyInlineTable(value) {
      value = toJSON(value);
      var result = [];
      Object.keys(value).forEach((key) => {
        result.push(stringifyKey(key) + " = " + stringifyAnyInline(value[key], false));
      });
      return "{ " + result.join(", ") + (result.length > 0 ? " " : "") + "}";
    }
    __name(stringifyInlineTable, "stringifyInlineTable");
    function stringifyComplex(prefix, indent, key, value) {
      var valueType = tomlType2(value);
      if (valueType === "array") {
        return stringifyArrayOfTables(prefix, indent, key, value);
      } else if (valueType === "table") {
        return stringifyComplexTable(prefix, indent, key, value);
      } else {
        throw typeError(valueType);
      }
    }
    __name(stringifyComplex, "stringifyComplex");
    function stringifyArrayOfTables(prefix, indent, key, values) {
      values = toJSON(values);
      validateArray(values);
      var firstValueType = tomlType2(values[0]);
      if (firstValueType !== "table") throw typeError(firstValueType);
      var fullKey = prefix + stringifyKey(key);
      var result = "";
      values.forEach((table) => {
        if (result.length > 0) result += "\n";
        result += indent + "[[" + fullKey + "]]\n";
        result += stringifyObject(fullKey + ".", indent, table);
      });
      return result;
    }
    __name(stringifyArrayOfTables, "stringifyArrayOfTables");
    function stringifyComplexTable(prefix, indent, key, value) {
      var fullKey = prefix + stringifyKey(key);
      var result = "";
      if (getInlineKeys(value).length > 0) {
        result += indent + "[" + fullKey + "]\n";
      }
      return result + stringifyObject(fullKey + ".", indent, value);
    }
    __name(stringifyComplexTable, "stringifyComplexTable");
  }
});

// node_modules/@iarna/toml/toml.js
var require_toml = __commonJS({
  "node_modules/@iarna/toml/toml.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    exports2.parse = require_parse10();
    exports2.stringify = require_stringify3();
  }
});

// node_modules/graceful-fs/polyfills.js
var require_polyfills = __commonJS({
  "node_modules/graceful-fs/polyfills.js"(exports2, module2) {
    init_esbuild_shims();
    var constants4 = __require("constants");
    var origCwd = process.cwd;
    var cwd7 = null;
    var platform15 = process.env.GRACEFUL_FS_PLATFORM || process.platform;
    process.cwd = function() {
      if (!cwd7)
        cwd7 = origCwd.call(process);
      return cwd7;
    };
    try {
      process.cwd();
    } catch (er) {
    }
    if (typeof process.chdir === "function") {
      chdir = process.chdir;
      process.chdir = function(d) {
        cwd7 = null;
        chdir.call(process, d);
      };
      if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir);
    }
    var chdir;
    module2.exports = patch;
    function patch(fs95) {
      if (constants4.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
        patchLchmod(fs95);
      }
      if (!fs95.lutimes) {
        patchLutimes(fs95);
      }
      fs95.chown = chownFix(fs95.chown);
      fs95.fchown = chownFix(fs95.fchown);
      fs95.lchown = chownFix(fs95.lchown);
      fs95.chmod = chmodFix(fs95.chmod);
      fs95.fchmod = chmodFix(fs95.fchmod);
      fs95.lchmod = chmodFix(fs95.lchmod);
      fs95.chownSync = chownFixSync(fs95.chownSync);
      fs95.fchownSync = chownFixSync(fs95.fchownSync);
      fs95.lchownSync = chownFixSync(fs95.lchownSync);
      fs95.chmodSync = chmodFixSync(fs95.chmodSync);
      fs95.fchmodSync = chmodFixSync(fs95.fchmodSync);
      fs95.lchmodSync = chmodFixSync(fs95.lchmodSync);
      fs95.stat = statFix(fs95.stat);
      fs95.fstat = statFix(fs95.fstat);
      fs95.lstat = statFix(fs95.lstat);
      fs95.statSync = statFixSync(fs95.statSync);
      fs95.fstatSync = statFixSync(fs95.fstatSync);
      fs95.lstatSync = statFixSync(fs95.lstatSync);
      if (fs95.chmod && !fs95.lchmod) {
        fs95.lchmod = function(path108, mode, cb) {
          if (cb) process.nextTick(cb);
        };
        fs95.lchmodSync = function() {
        };
      }
      if (fs95.chown && !fs95.lchown) {
        fs95.lchown = function(path108, uid, gid, cb) {
          if (cb) process.nextTick(cb);
        };
        fs95.lchownSync = function() {
        };
      }
      if (platform15 === "win32") {
        fs95.rename = typeof fs95.rename !== "function" ? fs95.rename : function(fs$rename) {
          function rename(from, to, cb) {
            var start = Date.now();
            var backoff = 0;
            fs$rename(from, to, /* @__PURE__ */ __name(function CB(er) {
              if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 6e4) {
                setTimeout(function() {
                  fs95.stat(to, function(stater, st) {
                    if (stater && stater.code === "ENOENT")
                      fs$rename(from, to, CB);
                    else
                      cb(er);
                  });
                }, backoff);
                if (backoff < 100)
                  backoff += 10;
                return;
              }
              if (cb) cb(er);
            }, "CB"));
          }
          __name(rename, "rename");
          if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename);
          return rename;
        }(fs95.rename);
      }
      fs95.read = typeof fs95.read !== "function" ? fs95.read : function(fs$read) {
        function read2(fd, buffer, offset, length, position, callback_) {
          var callback;
          if (callback_ && typeof callback_ === "function") {
            var eagCounter = 0;
            callback = /* @__PURE__ */ __name(function(er, _, __) {
              if (er && er.code === "EAGAIN" && eagCounter < 10) {
                eagCounter++;
                return fs$read.call(fs95, fd, buffer, offset, length, position, callback);
              }
              callback_.apply(this, arguments);
            }, "callback");
          }
          return fs$read.call(fs95, fd, buffer, offset, length, position, callback);
        }
        __name(read2, "read");
        if (Object.setPrototypeOf) Object.setPrototypeOf(read2, fs$read);
        return read2;
      }(fs95.read);
      fs95.readSync = typeof fs95.readSync !== "function" ? fs95.readSync : /* @__PURE__ */ function(fs$readSync) {
        return function(fd, buffer, offset, length, position) {
          var eagCounter = 0;
          while (true) {
            try {
              return fs$readSync.call(fs95, fd, buffer, offset, length, position);
            } catch (er) {
              if (er.code === "EAGAIN" && eagCounter < 10) {
                eagCounter++;
                continue;
              }
              throw er;
            }
          }
        };
      }(fs95.readSync);
      function patchLchmod(fs96) {
        fs96.lchmod = function(path108, mode, callback) {
          fs96.open(
            path108,
            constants4.O_WRONLY | constants4.O_SYMLINK,
            mode,
            function(err, fd) {
              if (err) {
                if (callback) callback(err);
                return;
              }
              fs96.fchmod(fd, mode, function(err2) {
                fs96.close(fd, function(err22) {
                  if (callback) callback(err2 || err22);
                });
              });
            }
          );
        };
        fs96.lchmodSync = function(path108, mode) {
          var fd = fs96.openSync(path108, constants4.O_WRONLY | constants4.O_SYMLINK, mode);
          var threw = true;
          var ret;
          try {
            ret = fs96.fchmodSync(fd, mode);
            threw = false;
          } finally {
            if (threw) {
              try {
                fs96.closeSync(fd);
              } catch (er) {
              }
            } else {
              fs96.closeSync(fd);
            }
          }
          return ret;
        };
      }
      __name(patchLchmod, "patchLchmod");
      function patchLutimes(fs96) {
        if (constants4.hasOwnProperty("O_SYMLINK") && fs96.futimes) {
          fs96.lutimes = function(path108, at, mt, cb) {
            fs96.open(path108, constants4.O_SYMLINK, function(er, fd) {
              if (er) {
                if (cb) cb(er);
                return;
              }
              fs96.futimes(fd, at, mt, function(er2) {
                fs96.close(fd, function(er22) {
                  if (cb) cb(er2 || er22);
                });
              });
            });
          };
          fs96.lutimesSync = function(path108, at, mt) {
            var fd = fs96.openSync(path108, constants4.O_SYMLINK);
            var ret;
            var threw = true;
            try {
              ret = fs96.futimesSync(fd, at, mt);
              threw = false;
            } finally {
              if (threw) {
                try {
                  fs96.closeSync(fd);
                } catch (er) {
                }
              } else {
                fs96.closeSync(fd);
              }
            }
            return ret;
          };
        } else if (fs96.futimes) {
          fs96.lutimes = function(_a6, _b2, _c2, cb) {
            if (cb) process.nextTick(cb);
          };
          fs96.lutimesSync = function() {
          };
        }
      }
      __name(patchLutimes, "patchLutimes");
      function chmodFix(orig) {
        if (!orig) return orig;
        return function(target, mode, cb) {
          return orig.call(fs95, target, mode, function(er) {
            if (chownErOk(er)) er = null;
            if (cb) cb.apply(this, arguments);
          });
        };
      }
      __name(chmodFix, "chmodFix");
      function chmodFixSync(orig) {
        if (!orig) return orig;
        return function(target, mode) {
          try {
            return orig.call(fs95, target, mode);
          } catch (er) {
            if (!chownErOk(er)) throw er;
          }
        };
      }
      __name(chmodFixSync, "chmodFixSync");
      function chownFix(orig) {
        if (!orig) return orig;
        return function(target, uid, gid, cb) {
          return orig.call(fs95, target, uid, gid, function(er) {
            if (chownErOk(er)) er = null;
            if (cb) cb.apply(this, arguments);
          });
        };
      }
      __name(chownFix, "chownFix");
      function chownFixSync(orig) {
        if (!orig) return orig;
        return function(target, uid, gid) {
          try {
            return orig.call(fs95, target, uid, gid);
          } catch (er) {
            if (!chownErOk(er)) throw er;
          }
        };
      }
      __name(chownFixSync, "chownFixSync");
      function statFix(orig) {
        if (!orig) return orig;
        return function(target, options2, cb) {
          if (typeof options2 === "function") {
            cb = options2;
            options2 = null;
          }
          function callback(er, stats) {
            if (stats) {
              if (stats.uid < 0) stats.uid += 4294967296;
              if (stats.gid < 0) stats.gid += 4294967296;
            }
            if (cb) cb.apply(this, arguments);
          }
          __name(callback, "callback");
          return options2 ? orig.call(fs95, target, options2, callback) : orig.call(fs95, target, callback);
        };
      }
      __name(statFix, "statFix");
      function statFixSync(orig) {
        if (!orig) return orig;
        return function(target, options2) {
          var stats = options2 ? orig.call(fs95, target, options2) : orig.call(fs95, target);
          if (stats) {
            if (stats.uid < 0) stats.uid += 4294967296;
            if (stats.gid < 0) stats.gid += 4294967296;
          }
          return stats;
        };
      }
      __name(statFixSync, "statFixSync");
      function chownErOk(er) {
        if (!er)
          return true;
        if (er.code === "ENOSYS")
          return true;
        var nonroot = !process.getuid || process.getuid() !== 0;
        if (nonroot) {
          if (er.code === "EINVAL" || er.code === "EPERM")
            return true;
        }
        return false;
      }
      __name(chownErOk, "chownErOk");
    }
    __name(patch, "patch");
  }
});

// node_modules/graceful-fs/legacy-streams.js
var require_legacy_streams = __commonJS({
  "node_modules/graceful-fs/legacy-streams.js"(exports2, module2) {
    init_esbuild_shims();
    var Stream4 = __require("stream").Stream;
    module2.exports = legacy;
    function legacy(fs95) {
      return {
        ReadStream: ReadStream2,
        WriteStream: WriteStream2
      };
      function ReadStream2(path108, options2) {
        if (!(this instanceof ReadStream2)) return new ReadStream2(path108, options2);
        Stream4.call(this);
        var self2 = this;
        this.path = path108;
        this.fd = null;
        this.readable = true;
        this.paused = false;
        this.flags = "r";
        this.mode = 438;
        this.bufferSize = 64 * 1024;
        options2 = options2 || {};
        var keys = Object.keys(options2);
        for (var index = 0, length = keys.length; index < length; index++) {
          var key = keys[index];
          this[key] = options2[key];
        }
        if (this.encoding) this.setEncoding(this.encoding);
        if (this.start !== void 0) {
          if ("number" !== typeof this.start) {
            throw TypeError("start must be a Number");
          }
          if (this.end === void 0) {
            this.end = Infinity;
          } else if ("number" !== typeof this.end) {
            throw TypeError("end must be a Number");
          }
          if (this.start > this.end) {
            throw new Error("start must be <= end");
          }
          this.pos = this.start;
        }
        if (this.fd !== null) {
          process.nextTick(function() {
            self2._read();
          });
          return;
        }
        fs95.open(this.path, this.flags, this.mode, function(err, fd) {
          if (err) {
            self2.emit("error", err);
            self2.readable = false;
            return;
          }
          self2.fd = fd;
          self2.emit("open", fd);
          self2._read();
        });
      }
      __name(ReadStream2, "ReadStream");
      function WriteStream2(path108, options2) {
        if (!(this instanceof WriteStream2)) return new WriteStream2(path108, options2);
        Stream4.call(this);
        this.path = path108;
        this.fd = null;
        this.writable = true;
        this.flags = "w";
        this.encoding = "binary";
        this.mode = 438;
        this.bytesWritten = 0;
        options2 = options2 || {};
        var keys = Object.keys(options2);
        for (var index = 0, length = keys.length; index < length; index++) {
          var key = keys[index];
          this[key] = options2[key];
        }
        if (this.start !== void 0) {
          if ("number" !== typeof this.start) {
            throw TypeError("start must be a Number");
          }
          if (this.start < 0) {
            throw new Error("start must be >= zero");
          }
          this.pos = this.start;
        }
        this.busy = false;
        this._queue = [];
        if (this.fd === null) {
          this._open = fs95.open;
          this._queue.push([this._open, this.path, this.flags, this.mode, void 0]);
          this.flush();
        }
      }
      __name(WriteStream2, "WriteStream");
    }
    __name(legacy, "legacy");
  }
});

// node_modules/graceful-fs/clone.js
var require_clone = __commonJS({
  "node_modules/graceful-fs/clone.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = clone;
    var getPrototypeOf = Object.getPrototypeOf || function(obj) {
      return obj.__proto__;
    };
    function clone(obj) {
      if (obj === null || typeof obj !== "object")
        return obj;
      if (obj instanceof Object)
        var copy = { __proto__: getPrototypeOf(obj) };
      else
        var copy = /* @__PURE__ */ Object.create(null);
      Object.getOwnPropertyNames(obj).forEach(function(key) {
        Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
      });
      return copy;
    }
    __name(clone, "clone");
  }
});

// node_modules/graceful-fs/graceful-fs.js
var require_graceful_fs = __commonJS({
  "node_modules/graceful-fs/graceful-fs.js"(exports2, module2) {
    init_esbuild_shims();
    var fs95 = __require("fs");
    var polyfills = require_polyfills();
    var legacy = require_legacy_streams();
    var clone = require_clone();
    var util4 = __require("util");
    var gracefulQueue;
    var previousSymbol;
    if (typeof Symbol === "function" && typeof Symbol.for === "function") {
      gracefulQueue = Symbol.for("graceful-fs.queue");
      previousSymbol = Symbol.for("graceful-fs.previous");
    } else {
      gracefulQueue = "___graceful-fs.queue";
      previousSymbol = "___graceful-fs.previous";
    }
    function noop6() {
    }
    __name(noop6, "noop");
    function publishQueue(context2, queue2) {
      Object.defineProperty(context2, gracefulQueue, {
        get: /* @__PURE__ */ __name(function() {
          return queue2;
        }, "get")
      });
    }
    __name(publishQueue, "publishQueue");
    var debug2 = noop6;
    if (util4.debuglog)
      debug2 = util4.debuglog("gfs4");
    else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ""))
      debug2 = /* @__PURE__ */ __name(function() {
        var m = util4.format.apply(util4, arguments);
        m = "GFS4: " + m.split(/\n/).join("\nGFS4: ");
        console.error(m);
      }, "debug");
    if (!fs95[gracefulQueue]) {
      queue = globalThis[gracefulQueue] || [];
      publishQueue(fs95, queue);
      fs95.close = function(fs$close) {
        function close(fd, cb) {
          return fs$close.call(fs95, fd, function(err) {
            if (!err) {
              resetQueue();
            }
            if (typeof cb === "function")
              cb.apply(this, arguments);
          });
        }
        __name(close, "close");
        Object.defineProperty(close, previousSymbol, {
          value: fs$close
        });
        return close;
      }(fs95.close);
      fs95.closeSync = function(fs$closeSync) {
        function closeSync(fd) {
          fs$closeSync.apply(fs95, arguments);
          resetQueue();
        }
        __name(closeSync, "closeSync");
        Object.defineProperty(closeSync, previousSymbol, {
          value: fs$closeSync
        });
        return closeSync;
      }(fs95.closeSync);
      if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
        process.on("exit", function() {
          debug2(fs95[gracefulQueue]);
          __require("assert").equal(fs95[gracefulQueue].length, 0);
        });
      }
    }
    var queue;
    if (!globalThis[gracefulQueue]) {
      publishQueue(globalThis, fs95[gracefulQueue]);
    }
    module2.exports = patch(clone(fs95));
    if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs95.__patched) {
      module2.exports = patch(fs95);
      fs95.__patched = true;
    }
    function patch(fs96) {
      polyfills(fs96);
      fs96.gracefulify = patch;
      fs96.createReadStream = createReadStream;
      fs96.createWriteStream = createWriteStream5;
      var fs$readFile = fs96.readFile;
      fs96.readFile = readFile11;
      function readFile11(path108, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        return go$readFile(path108, options2, cb);
        function go$readFile(path109, options3, cb2, startTime) {
          return fs$readFile(path109, options3, function(err) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$readFile, [path109, options3, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$readFile, "go$readFile");
      }
      __name(readFile11, "readFile");
      var fs$writeFile = fs96.writeFile;
      fs96.writeFile = writeFile12;
      function writeFile12(path108, data, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        return go$writeFile(path108, data, options2, cb);
        function go$writeFile(path109, data2, options3, cb2, startTime) {
          return fs$writeFile(path109, data2, options3, function(err) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$writeFile, [path109, data2, options3, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$writeFile, "go$writeFile");
      }
      __name(writeFile12, "writeFile");
      var fs$appendFile = fs96.appendFile;
      if (fs$appendFile)
        fs96.appendFile = appendFile;
      function appendFile(path108, data, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        return go$appendFile(path108, data, options2, cb);
        function go$appendFile(path109, data2, options3, cb2, startTime) {
          return fs$appendFile(path109, data2, options3, function(err) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$appendFile, [path109, data2, options3, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$appendFile, "go$appendFile");
      }
      __name(appendFile, "appendFile");
      var fs$copyFile = fs96.copyFile;
      if (fs$copyFile)
        fs96.copyFile = copyFile;
      function copyFile(src, dest, flags, cb) {
        if (typeof flags === "function") {
          cb = flags;
          flags = 0;
        }
        return go$copyFile(src, dest, flags, cb);
        function go$copyFile(src2, dest2, flags2, cb2, startTime) {
          return fs$copyFile(src2, dest2, flags2, function(err) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$copyFile, [src2, dest2, flags2, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$copyFile, "go$copyFile");
      }
      __name(copyFile, "copyFile");
      var fs$readdir = fs96.readdir;
      fs96.readdir = readdir10;
      var noReaddirOptionVersions = /^v[0-5]\./;
      function readdir10(path108, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        var go$readdir = noReaddirOptionVersions.test(process.version) ? /* @__PURE__ */ __name(function go$readdir2(path109, options3, cb2, startTime) {
          return fs$readdir(path109, fs$readdirCallback(
            path109,
            options3,
            cb2,
            startTime
          ));
        }, "go$readdir") : /* @__PURE__ */ __name(function go$readdir2(path109, options3, cb2, startTime) {
          return fs$readdir(path109, options3, fs$readdirCallback(
            path109,
            options3,
            cb2,
            startTime
          ));
        }, "go$readdir");
        return go$readdir(path108, options2, cb);
        function fs$readdirCallback(path109, options3, cb2, startTime) {
          return function(err, files) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([
                go$readdir,
                [path109, options3, cb2],
                err,
                startTime || Date.now(),
                Date.now()
              ]);
            else {
              if (files && files.sort)
                files.sort();
              if (typeof cb2 === "function")
                cb2.call(this, err, files);
            }
          };
        }
        __name(fs$readdirCallback, "fs$readdirCallback");
      }
      __name(readdir10, "readdir");
      if (process.version.substr(0, 4) === "v0.8") {
        var legStreams = legacy(fs96);
        ReadStream2 = legStreams.ReadStream;
        WriteStream2 = legStreams.WriteStream;
      }
      var fs$ReadStream = fs96.ReadStream;
      if (fs$ReadStream) {
        ReadStream2.prototype = Object.create(fs$ReadStream.prototype);
        ReadStream2.prototype.open = ReadStream$open;
      }
      var fs$WriteStream = fs96.WriteStream;
      if (fs$WriteStream) {
        WriteStream2.prototype = Object.create(fs$WriteStream.prototype);
        WriteStream2.prototype.open = WriteStream$open;
      }
      Object.defineProperty(fs96, "ReadStream", {
        get: /* @__PURE__ */ __name(function() {
          return ReadStream2;
        }, "get"),
        set: /* @__PURE__ */ __name(function(val) {
          ReadStream2 = val;
        }, "set"),
        enumerable: true,
        configurable: true
      });
      Object.defineProperty(fs96, "WriteStream", {
        get: /* @__PURE__ */ __name(function() {
          return WriteStream2;
        }, "get"),
        set: /* @__PURE__ */ __name(function(val) {
          WriteStream2 = val;
        }, "set"),
        enumerable: true,
        configurable: true
      });
      var FileReadStream = ReadStream2;
      Object.defineProperty(fs96, "FileReadStream", {
        get: /* @__PURE__ */ __name(function() {
          return FileReadStream;
        }, "get"),
        set: /* @__PURE__ */ __name(function(val) {
          FileReadStream = val;
        }, "set"),
        enumerable: true,
        configurable: true
      });
      var FileWriteStream = WriteStream2;
      Object.defineProperty(fs96, "FileWriteStream", {
        get: /* @__PURE__ */ __name(function() {
          return FileWriteStream;
        }, "get"),
        set: /* @__PURE__ */ __name(function(val) {
          FileWriteStream = val;
        }, "set"),
        enumerable: true,
        configurable: true
      });
      function ReadStream2(path108, options2) {
        if (this instanceof ReadStream2)
          return fs$ReadStream.apply(this, arguments), this;
        else
          return ReadStream2.apply(Object.create(ReadStream2.prototype), arguments);
      }
      __name(ReadStream2, "ReadStream");
      function ReadStream$open() {
        var that = this;
        open3(that.path, that.flags, that.mode, function(err, fd) {
          if (err) {
            if (that.autoClose)
              that.destroy();
            that.emit("error", err);
          } else {
            that.fd = fd;
            that.emit("open", fd);
            that.read();
          }
        });
      }
      __name(ReadStream$open, "ReadStream$open");
      function WriteStream2(path108, options2) {
        if (this instanceof WriteStream2)
          return fs$WriteStream.apply(this, arguments), this;
        else
          return WriteStream2.apply(Object.create(WriteStream2.prototype), arguments);
      }
      __name(WriteStream2, "WriteStream");
      function WriteStream$open() {
        var that = this;
        open3(that.path, that.flags, that.mode, function(err, fd) {
          if (err) {
            that.destroy();
            that.emit("error", err);
          } else {
            that.fd = fd;
            that.emit("open", fd);
          }
        });
      }
      __name(WriteStream$open, "WriteStream$open");
      function createReadStream(path108, options2) {
        return new fs96.ReadStream(path108, options2);
      }
      __name(createReadStream, "createReadStream");
      function createWriteStream5(path108, options2) {
        return new fs96.WriteStream(path108, options2);
      }
      __name(createWriteStream5, "createWriteStream");
      var fs$open = fs96.open;
      fs96.open = open3;
      function open3(path108, flags, mode, cb) {
        if (typeof mode === "function")
          cb = mode, mode = null;
        return go$open(path108, flags, mode, cb);
        function go$open(path109, flags2, mode2, cb2, startTime) {
          return fs$open(path109, flags2, mode2, function(err, fd) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$open, [path109, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$open, "go$open");
      }
      __name(open3, "open");
      return fs96;
    }
    __name(patch, "patch");
    function enqueue(elem) {
      debug2("ENQUEUE", elem[0].name, elem[1]);
      fs95[gracefulQueue].push(elem);
      retry();
    }
    __name(enqueue, "enqueue");
    var retryTimer;
    function resetQueue() {
      var now = Date.now();
      for (var i = 0; i < fs95[gracefulQueue].length; ++i) {
        if (fs95[gracefulQueue][i].length > 2) {
          fs95[gracefulQueue][i][3] = now;
          fs95[gracefulQueue][i][4] = now;
        }
      }
      retry();
    }
    __name(resetQueue, "resetQueue");
    function retry() {
      clearTimeout(retryTimer);
      retryTimer = void 0;
      if (fs95[gracefulQueue].length === 0)
        return;
      var elem = fs95[gracefulQueue].shift();
      var fn = elem[0];
      var args = elem[1];
      var err = elem[2];
      var startTime = elem[3];
      var lastTime = elem[4];
      if (startTime === void 0) {
        debug2("RETRY", fn.name, args);
        fn.apply(null, args);
      } else if (Date.now() - startTime >= 6e4) {
        debug2("TIMEOUT", fn.name, args);
        var cb = args.pop();
        if (typeof cb === "function")
          cb.call(null, err);
      } else {
        var sinceAttempt = Date.now() - lastTime;
        var sinceStart = Math.max(lastTime - startTime, 1);
        var desiredDelay = Math.min(sinceStart * 1.2, 100);
        if (sinceAttempt >= desiredDelay) {
          debug2("RETRY", fn.name, args);
          fn.apply(null, args.concat([startTime]));
        } else {
          fs95[gracefulQueue].push(elem);
        }
      }
      if (retryTimer === void 0) {
        retryTimer = setTimeout(retry, 0);
      }
    }
    __name(retry, "retry");
  }
});

// node_modules/semver/functions/diff.js
var require_diff = __commonJS({
  "node_modules/semver/functions/diff.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var parse12 = require_parse8();
    var diff4 = /* @__PURE__ */ __name((version1, version2) => {
      const v12 = parse12(version1, null, true);
      const v2 = parse12(version2, null, true);
      const comparison = v12.compare(v2);
      if (comparison === 0) {
        return null;
      }
      const v1Higher = comparison > 0;
      const highVersion = v1Higher ? v12 : v2;
      const lowVersion = v1Higher ? v2 : v12;
      const highHasPre = !!highVersion.prerelease.length;
      const lowHasPre = !!lowVersion.prerelease.length;
      if (lowHasPre && !highHasPre) {
        if (!lowVersion.patch && !lowVersion.minor) {
          return "major";
        }
        if (lowVersion.compareMain(highVersion) === 0) {
          if (lowVersion.minor && !lowVersion.patch) {
            return "minor";
          }
          return "patch";
        }
      }
      const prefix = highHasPre ? "pre" : "";
      if (v12.major !== v2.major) {
        return prefix + "major";
      }
      if (v12.minor !== v2.minor) {
        return prefix + "minor";
      }
      if (v12.patch !== v2.patch) {
        return prefix + "patch";
      }
      return "prerelease";
    }, "diff");
    module2.exports = diff4;
  }
});

// node_modules/semver/functions/compare.js
var require_compare = __commonJS({
  "node_modules/semver/functions/compare.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var SemVer = require_semver2();
    var compare = /* @__PURE__ */ __name((a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)), "compare");
    module2.exports = compare;
  }
});

// node_modules/semver/functions/gt.js
var require_gt = __commonJS({
  "node_modules/semver/functions/gt.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var compare = require_compare();
    var gt = /* @__PURE__ */ __name((a, b, loose) => compare(a, b, loose) > 0, "gt");
    module2.exports = gt;
  }
});

// node_modules/rc/node_modules/ini/ini.js
var require_ini = __commonJS({
  "node_modules/rc/node_modules/ini/ini.js"(exports2) {
    init_esbuild_shims();
    exports2.parse = exports2.decode = decode2;
    exports2.stringify = exports2.encode = encode4;
    exports2.safe = safe;
    exports2.unsafe = unsafe;
    var eol = typeof process !== "undefined" && process.platform === "win32" ? "\r\n" : "\n";
    function encode4(obj, opt) {
      var children = [];
      var out = "";
      if (typeof opt === "string") {
        opt = {
          section: opt,
          whitespace: false
        };
      } else {
        opt = opt || {};
        opt.whitespace = opt.whitespace === true;
      }
      var separator = opt.whitespace ? " = " : "=";
      Object.keys(obj).forEach(function(k, _, __) {
        var val = obj[k];
        if (val && Array.isArray(val)) {
          val.forEach(function(item) {
            out += safe(k + "[]") + separator + safe(item) + "\n";
          });
        } else if (val && typeof val === "object")
          children.push(k);
        else
          out += safe(k) + separator + safe(val) + eol;
      });
      if (opt.section && out.length)
        out = "[" + safe(opt.section) + "]" + eol + out;
      children.forEach(function(k, _, __) {
        var nk = dotSplit(k).join("\\.");
        var section = (opt.section ? opt.section + "." : "") + nk;
        var child = encode4(obj[k], {
          section,
          whitespace: opt.whitespace
        });
        if (out.length && child.length)
          out += eol;
        out += child;
      });
      return out;
    }
    __name(encode4, "encode");
    function dotSplit(str2) {
      return str2.replace(/\1/g, "LITERAL\\1LITERAL").replace(/\\\./g, "").split(/\./).map(function(part) {
        return part.replace(/\1/g, "\\.").replace(/\2LITERAL\\1LITERAL\2/g, "");
      });
    }
    __name(dotSplit, "dotSplit");
    function decode2(str2) {
      var out = {};
      var p = out;
      var section = null;
      var re2 = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i;
      var lines = str2.split(/[\r\n]+/g);
      lines.forEach(function(line, _, __) {
        if (!line || line.match(/^\s*[;#]/))
          return;
        var match2 = line.match(re2);
        if (!match2)
          return;
        if (match2[1] !== void 0) {
          section = unsafe(match2[1]);
          if (section === "__proto__") {
            p = {};
            return;
          }
          p = out[section] = out[section] || {};
          return;
        }
        var key = unsafe(match2[2]);
        if (key === "__proto__")
          return;
        var value = match2[3] ? unsafe(match2[4]) : true;
        switch (value) {
          case "true":
          case "false":
          case "null":
            value = JSON.parse(value);
        }
        if (key.length > 2 && key.slice(-2) === "[]") {
          key = key.substring(0, key.length - 2);
          if (key === "__proto__")
            return;
          if (!p[key])
            p[key] = [];
          else if (!Array.isArray(p[key]))
            p[key] = [p[key]];
        }
        if (Array.isArray(p[key]))
          p[key].push(value);
        else
          p[key] = value;
      });
      Object.keys(out).filter(function(k, _, __) {
        if (!out[k] || typeof out[k] !== "object" || Array.isArray(out[k]))
          return false;
        var parts = dotSplit(k);
        var p2 = out;
        var l2 = parts.pop();
        var nl2 = l2.replace(/\\\./g, ".");
        parts.forEach(function(part, _2, __2) {
          if (part === "__proto__")
            return;
          if (!p2[part] || typeof p2[part] !== "object")
            p2[part] = {};
          p2 = p2[part];
        });
        if (p2 === out && nl2 === l2)
          return false;
        p2[nl2] = out[k];
        return true;
      }).forEach(function(del, _, __) {
        delete out[del];
      });
      return out;
    }
    __name(decode2, "decode");
    function isQuoted(val) {
      return val.charAt(0) === '"' && val.slice(-1) === '"' || val.charAt(0) === "'" && val.slice(-1) === "'";
    }
    __name(isQuoted, "isQuoted");
    function safe(val) {
      return typeof val !== "string" || val.match(/[=\r\n]/) || val.match(/^\[/) || val.length > 1 && isQuoted(val) || val !== val.trim() ? JSON.stringify(val) : val.replace(/;/g, "\\;").replace(/#/g, "\\#");
    }
    __name(safe, "safe");
    function unsafe(val, doUnesc) {
      val = (val || "").trim();
      if (isQuoted(val)) {
        if (val.charAt(0) === "'")
          val = val.substr(1, val.length - 2);
        try {
          val = JSON.parse(val);
        } catch (_) {
        }
      } else {
        var esc = false;
        var unesc = "";
        for (var i = 0, l2 = val.length; i < l2; i++) {
          var c3 = val.charAt(i);
          if (esc) {
            if ("\\;#".indexOf(c3) !== -1)
              unesc += c3;
            else
              unesc += "\\" + c3;
            esc = false;
          } else if (";#".indexOf(c3) !== -1)
            break;
          else if (c3 === "\\")
            esc = true;
          else
            unesc += c3;
        }
        if (esc)
          unesc += "\\";
        return unesc.trim();
      }
      return val;
    }
    __name(unsafe, "unsafe");
  }
});

// node_modules/rc/node_modules/strip-json-comments/index.js
var require_strip_json_comments2 = __commonJS({
  "node_modules/rc/node_modules/strip-json-comments/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var singleComment = 1;
    var multiComment = 2;
    function stripWithoutWhitespace() {
      return "";
    }
    __name(stripWithoutWhitespace, "stripWithoutWhitespace");
    function stripWithWhitespace(str2, start, end) {
      return str2.slice(start, end).replace(/\S/g, " ");
    }
    __name(stripWithWhitespace, "stripWithWhitespace");
    module2.exports = function(str2, opts) {
      opts = opts || {};
      var currentChar;
      var nextChar;
      var insideString = false;
      var insideComment = false;
      var offset = 0;
      var ret = "";
      var strip = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace;
      for (var i = 0; i < str2.length; i++) {
        currentChar = str2[i];
        nextChar = str2[i + 1];
        if (!insideComment && currentChar === '"') {
          var escaped = str2[i - 1] === "\\" && str2[i - 2] !== "\\";
          if (!escaped) {
            insideString = !insideString;
          }
        }
        if (insideString) {
          continue;
        }
        if (!insideComment && currentChar + nextChar === "//") {
          ret += str2.slice(offset, i);
          offset = i;
          insideComment = singleComment;
          i++;
        } else if (insideComment === singleComment && currentChar + nextChar === "\r\n") {
          i++;
          insideComment = false;
          ret += strip(str2, offset, i);
          offset = i;
          continue;
        } else if (insideComment === singleComment && currentChar === "\n") {
          insideComment = false;
          ret += strip(str2, offset, i);
          offset = i;
        } else if (!insideComment && currentChar + nextChar === "/*") {
          ret += str2.slice(offset, i);
          offset = i;
          insideComment = multiComment;
          i++;
          continue;
        } else if (insideComment === multiComment && currentChar + nextChar === "*/") {
          i++;
          insideComment = false;
          ret += strip(str2, offset, i + 1);
          offset = i + 1;
          continue;
        }
      }
      return ret + (insideComment ? strip(str2.substr(offset)) : str2.substr(offset));
    };
  }
});

// node_modules/rc/lib/utils.js
var require_utils16 = __commonJS({
  "node_modules/rc/lib/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var fs95 = __require("fs");
    var ini3 = require_ini();
    var path108 = __require("path");
    var stripJsonComments4 = require_strip_json_comments2();
    var parse12 = exports2.parse = function(content) {
      if (/^\s*{/.test(content))
        return JSON.parse(stripJsonComments4(content));
      return ini3.parse(content);
    };
    var file = exports2.file = function() {
      var args = [].slice.call(arguments).filter(function(arg) {
        return arg != null;
      });
      for (var i in args)
        if ("string" !== typeof args[i])
          return;
      var file2 = path108.join.apply(null, args);
      var content;
      try {
        return fs95.readFileSync(file2, "utf-8");
      } catch (err) {
        return;
      }
    };
    var json2 = exports2.json = function() {
      var content = file.apply(null, arguments);
      return content ? parse12(content) : null;
    };
    var env7 = exports2.env = function(prefix, env8) {
      env8 = env8 || process.env;
      var obj = {};
      var l2 = prefix.length;
      for (var k in env8) {
        if (k.toLowerCase().indexOf(prefix.toLowerCase()) === 0) {
          var keypath = k.substring(l2).split("__");
          var _emptyStringIndex;
          while ((_emptyStringIndex = keypath.indexOf("")) > -1) {
            keypath.splice(_emptyStringIndex, 1);
          }
          var cursor = obj;
          keypath.forEach(/* @__PURE__ */ __name(function _buildSubObj(_subkey, i) {
            if (!_subkey || typeof cursor !== "object")
              return;
            if (i === keypath.length - 1)
              cursor[_subkey] = env8[k];
            if (cursor[_subkey] === void 0)
              cursor[_subkey] = {};
            cursor = cursor[_subkey];
          }, "_buildSubObj"));
        }
      }
      return obj;
    };
    var find = exports2.find = function() {
      var rel = path108.join.apply(null, [].slice.call(arguments));
      function find2(start, rel2) {
        var file2 = path108.join(start, rel2);
        try {
          fs95.statSync(file2);
          return file2;
        } catch (err) {
          if (path108.dirname(start) !== start)
            return find2(path108.dirname(start), rel2);
        }
      }
      __name(find2, "find");
      return find2(process.cwd(), rel);
    };
  }
});

// node_modules/deep-extend/lib/deep-extend.js
var require_deep_extend = __commonJS({
  "node_modules/deep-extend/lib/deep-extend.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    function isSpecificValue(val) {
      return val instanceof Buffer || val instanceof Date || val instanceof RegExp ? true : false;
    }
    __name(isSpecificValue, "isSpecificValue");
    function cloneSpecificValue(val) {
      if (val instanceof Buffer) {
        var x = Buffer.alloc ? Buffer.alloc(val.length) : new Buffer(val.length);
        val.copy(x);
        return x;
      } else if (val instanceof Date) {
        return new Date(val.getTime());
      } else if (val instanceof RegExp) {
        return new RegExp(val);
      } else {
        throw new Error("Unexpected situation");
      }
    }
    __name(cloneSpecificValue, "cloneSpecificValue");
    function deepCloneArray(arr) {
      var clone = [];
      arr.forEach(function(item, index) {
        if (typeof item === "object" && item !== null) {
          if (Array.isArray(item)) {
            clone[index] = deepCloneArray(item);
          } else if (isSpecificValue(item)) {
            clone[index] = cloneSpecificValue(item);
          } else {
            clone[index] = deepExtend({}, item);
          }
        } else {
          clone[index] = item;
        }
      });
      return clone;
    }
    __name(deepCloneArray, "deepCloneArray");
    function safeGetProperty(object, property) {
      return property === "__proto__" ? void 0 : object[property];
    }
    __name(safeGetProperty, "safeGetProperty");
    var deepExtend = module2.exports = function() {
      if (arguments.length < 1 || typeof arguments[0] !== "object") {
        return false;
      }
      if (arguments.length < 2) {
        return arguments[0];
      }
      var target = arguments[0];
      var args = Array.prototype.slice.call(arguments, 1);
      var val, src, clone;
      args.forEach(function(obj) {
        if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
          return;
        }
        Object.keys(obj).forEach(function(key) {
          src = safeGetProperty(target, key);
          val = safeGetProperty(obj, key);
          if (val === target) {
            return;
          } else if (typeof val !== "object" || val === null) {
            target[key] = val;
            return;
          } else if (Array.isArray(val)) {
            target[key] = deepCloneArray(val);
            return;
          } else if (isSpecificValue(val)) {
            target[key] = cloneSpecificValue(val);
            return;
          } else if (typeof src !== "object" || src === null || Array.isArray(src)) {
            target[key] = deepExtend({}, val);
            return;
          } else {
            target[key] = deepExtend(src, val);
            return;
          }
        });
      });
      return target;
    };
  }
});

// node_modules/minimist/index.js
var require_minimist = __commonJS({
  "node_modules/minimist/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    function hasKey2(obj, keys) {
      var o2 = obj;
      keys.slice(0, -1).forEach(function(key2) {
        o2 = o2[key2] || {};
      });
      var key = keys[keys.length - 1];
      return key in o2;
    }
    __name(hasKey2, "hasKey");
    function isNumber3(x) {
      if (typeof x === "number") {
        return true;
      }
      if (/^0x[0-9a-f]+$/i.test(x)) {
        return true;
      }
      return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
    }
    __name(isNumber3, "isNumber");
    function isConstructorOrProto(obj, key) {
      return key === "constructor" && typeof obj[key] === "function" || key === "__proto__";
    }
    __name(isConstructorOrProto, "isConstructorOrProto");
    module2.exports = function(args, opts) {
      if (!opts) {
        opts = {};
      }
      var flags = {
        bools: {},
        strings: {},
        unknownFn: null
      };
      if (typeof opts.unknown === "function") {
        flags.unknownFn = opts.unknown;
      }
      if (typeof opts.boolean === "boolean" && opts.boolean) {
        flags.allBools = true;
      } else {
        [].concat(opts.boolean).filter(Boolean).forEach(function(key2) {
          flags.bools[key2] = true;
        });
      }
      var aliases = {};
      function aliasIsBoolean(key2) {
        return aliases[key2].some(function(x) {
          return flags.bools[x];
        });
      }
      __name(aliasIsBoolean, "aliasIsBoolean");
      Object.keys(opts.alias || {}).forEach(function(key2) {
        aliases[key2] = [].concat(opts.alias[key2]);
        aliases[key2].forEach(function(x) {
          aliases[x] = [key2].concat(aliases[key2].filter(function(y) {
            return x !== y;
          }));
        });
      });
      [].concat(opts.string).filter(Boolean).forEach(function(key2) {
        flags.strings[key2] = true;
        if (aliases[key2]) {
          [].concat(aliases[key2]).forEach(function(k) {
            flags.strings[k] = true;
          });
        }
      });
      var defaults3 = opts.default || {};
      var argv = { _: [] };
      function argDefined(key2, arg2) {
        return flags.allBools && /^--[^=]+$/.test(arg2) || flags.strings[key2] || flags.bools[key2] || aliases[key2];
      }
      __name(argDefined, "argDefined");
      function setKey(obj, keys, value2) {
        var o2 = obj;
        for (var i2 = 0; i2 < keys.length - 1; i2++) {
          var key2 = keys[i2];
          if (isConstructorOrProto(o2, key2)) {
            return;
          }
          if (o2[key2] === void 0) {
            o2[key2] = {};
          }
          if (o2[key2] === Object.prototype || o2[key2] === Number.prototype || o2[key2] === String.prototype) {
            o2[key2] = {};
          }
          if (o2[key2] === Array.prototype) {
            o2[key2] = [];
          }
          o2 = o2[key2];
        }
        var lastKey = keys[keys.length - 1];
        if (isConstructorOrProto(o2, lastKey)) {
          return;
        }
        if (o2 === Object.prototype || o2 === Number.prototype || o2 === String.prototype) {
          o2 = {};
        }
        if (o2 === Array.prototype) {
          o2 = [];
        }
        if (o2[lastKey] === void 0 || flags.bools[lastKey] || typeof o2[lastKey] === "boolean") {
          o2[lastKey] = value2;
        } else if (Array.isArray(o2[lastKey])) {
          o2[lastKey].push(value2);
        } else {
          o2[lastKey] = [o2[lastKey], value2];
        }
      }
      __name(setKey, "setKey");
      function setArg(key2, val, arg2) {
        if (arg2 && flags.unknownFn && !argDefined(key2, arg2)) {
          if (flags.unknownFn(arg2) === false) {
            return;
          }
        }
        var value2 = !flags.strings[key2] && isNumber3(val) ? Number(val) : val;
        setKey(argv, key2.split("."), value2);
        (aliases[key2] || []).forEach(function(x) {
          setKey(argv, x.split("."), value2);
        });
      }
      __name(setArg, "setArg");
      Object.keys(flags.bools).forEach(function(key2) {
        setArg(key2, defaults3[key2] === void 0 ? false : defaults3[key2]);
      });
      var notFlags = [];
      if (args.indexOf("--") !== -1) {
        notFlags = args.slice(args.indexOf("--") + 1);
        args = args.slice(0, args.indexOf("--"));
      }
      for (var i = 0; i < args.length; i++) {
        var arg = args[i];
        var key;
        var next;
        if (/^--.+=/.test(arg)) {
          var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
          key = m[1];
          var value = m[2];
          if (flags.bools[key]) {
            value = value !== "false";
          }
          setArg(key, value, arg);
        } else if (/^--no-.+/.test(arg)) {
          key = arg.match(/^--no-(.+)/)[1];
          setArg(key, false, arg);
        } else if (/^--.+/.test(arg)) {
          key = arg.match(/^--(.+)/)[1];
          next = args[i + 1];
          if (next !== void 0 && !/^(-|--)[^-]/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
            setArg(key, next, arg);
            i += 1;
          } else if (/^(true|false)$/.test(next)) {
            setArg(key, next === "true", arg);
            i += 1;
          } else {
            setArg(key, flags.strings[key] ? "" : true, arg);
          }
        } else if (/^-[^-]+/.test(arg)) {
          var letters = arg.slice(1, -1).split("");
          var broken = false;
          for (var j = 0; j < letters.length; j++) {
            next = arg.slice(j + 2);
            if (next === "-") {
              setArg(letters[j], next, arg);
              continue;
            }
            if (/[A-Za-z]/.test(letters[j]) && next[0] === "=") {
              setArg(letters[j], next.slice(1), arg);
              broken = true;
              break;
            }
            if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
              setArg(letters[j], next, arg);
              broken = true;
              break;
            }
            if (letters[j + 1] && letters[j + 1].match(/\W/)) {
              setArg(letters[j], arg.slice(j + 2), arg);
              broken = true;
              break;
            } else {
              setArg(letters[j], flags.strings[letters[j]] ? "" : true, arg);
            }
          }
          key = arg.slice(-1)[0];
          if (!broken && key !== "-") {
            if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
              setArg(key, args[i + 1], arg);
              i += 1;
            } else if (args[i + 1] && /^(true|false)$/.test(args[i + 1])) {
              setArg(key, args[i + 1] === "true", arg);
              i += 1;
            } else {
              setArg(key, flags.strings[key] ? "" : true, arg);
            }
          }
        } else {
          if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
            argv._.push(flags.strings._ || !isNumber3(arg) ? arg : Number(arg));
          }
          if (opts.stopEarly) {
            argv._.push.apply(argv._, args.slice(i + 1));
            break;
          }
        }
      }
      Object.keys(defaults3).forEach(function(k) {
        if (!hasKey2(argv, k.split("."))) {
          setKey(argv, k.split("."), defaults3[k]);
          (aliases[k] || []).forEach(function(x) {
            setKey(argv, x.split("."), defaults3[k]);
          });
        }
      });
      if (opts["--"]) {
        argv["--"] = notFlags.slice();
      } else {
        notFlags.forEach(function(k) {
          argv._.push(k);
        });
      }
      return argv;
    };
  }
});

// node_modules/rc/index.js
var require_rc = __commonJS({
  "node_modules/rc/index.js"(exports2, module2) {
    init_esbuild_shims();
    var cc = require_utils16();
    var join35 = __require("path").join;
    var deepExtend = require_deep_extend();
    var etc = "/etc";
    var win2 = process.platform === "win32";
    var home = win2 ? process.env.USERPROFILE : process.env.HOME;
    module2.exports = function(name3, defaults3, argv, parse12) {
      if ("string" !== typeof name3)
        throw new Error("rc(name): name *must* be string");
      if (!argv)
        argv = require_minimist()(process.argv.slice(2));
      defaults3 = ("string" === typeof defaults3 ? cc.json(defaults3) : defaults3) || {};
      parse12 = parse12 || cc.parse;
      var env7 = cc.env(name3 + "_");
      var configs = [defaults3];
      var configFiles = [];
      function addConfigFile(file) {
        if (configFiles.indexOf(file) >= 0) return;
        var fileConfig = cc.file(file);
        if (fileConfig) {
          configs.push(parse12(fileConfig));
          configFiles.push(file);
        }
      }
      __name(addConfigFile, "addConfigFile");
      if (!win2)
        [
          join35(etc, name3, "config"),
          join35(etc, name3 + "rc")
        ].forEach(addConfigFile);
      if (home)
        [
          join35(home, ".config", name3, "config"),
          join35(home, ".config", name3),
          join35(home, "." + name3, "config"),
          join35(home, "." + name3 + "rc")
        ].forEach(addConfigFile);
      addConfigFile(cc.find("." + name3 + "rc"));
      if (env7.config) addConfigFile(env7.config);
      if (argv.config) addConfigFile(argv.config);
      return deepExtend.apply(null, configs.concat([
        env7,
        argv,
        configFiles.length ? { configs: configFiles, config: configFiles[configFiles.length - 1] } : void 0
      ]));
    };
  }
});

// node_modules/@pnpm/network.ca-file/node_modules/graceful-fs/polyfills.js
var require_polyfills2 = __commonJS({
  "node_modules/@pnpm/network.ca-file/node_modules/graceful-fs/polyfills.js"(exports2, module2) {
    init_esbuild_shims();
    var constants4 = __require("constants");
    var origCwd = process.cwd;
    var cwd7 = null;
    var platform15 = process.env.GRACEFUL_FS_PLATFORM || process.platform;
    process.cwd = function() {
      if (!cwd7)
        cwd7 = origCwd.call(process);
      return cwd7;
    };
    try {
      process.cwd();
    } catch (er) {
    }
    if (typeof process.chdir === "function") {
      chdir = process.chdir;
      process.chdir = function(d) {
        cwd7 = null;
        chdir.call(process, d);
      };
      if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir);
    }
    var chdir;
    module2.exports = patch;
    function patch(fs95) {
      if (constants4.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
        patchLchmod(fs95);
      }
      if (!fs95.lutimes) {
        patchLutimes(fs95);
      }
      fs95.chown = chownFix(fs95.chown);
      fs95.fchown = chownFix(fs95.fchown);
      fs95.lchown = chownFix(fs95.lchown);
      fs95.chmod = chmodFix(fs95.chmod);
      fs95.fchmod = chmodFix(fs95.fchmod);
      fs95.lchmod = chmodFix(fs95.lchmod);
      fs95.chownSync = chownFixSync(fs95.chownSync);
      fs95.fchownSync = chownFixSync(fs95.fchownSync);
      fs95.lchownSync = chownFixSync(fs95.lchownSync);
      fs95.chmodSync = chmodFixSync(fs95.chmodSync);
      fs95.fchmodSync = chmodFixSync(fs95.fchmodSync);
      fs95.lchmodSync = chmodFixSync(fs95.lchmodSync);
      fs95.stat = statFix(fs95.stat);
      fs95.fstat = statFix(fs95.fstat);
      fs95.lstat = statFix(fs95.lstat);
      fs95.statSync = statFixSync(fs95.statSync);
      fs95.fstatSync = statFixSync(fs95.fstatSync);
      fs95.lstatSync = statFixSync(fs95.lstatSync);
      if (fs95.chmod && !fs95.lchmod) {
        fs95.lchmod = function(path108, mode, cb) {
          if (cb) process.nextTick(cb);
        };
        fs95.lchmodSync = function() {
        };
      }
      if (fs95.chown && !fs95.lchown) {
        fs95.lchown = function(path108, uid, gid, cb) {
          if (cb) process.nextTick(cb);
        };
        fs95.lchownSync = function() {
        };
      }
      if (platform15 === "win32") {
        fs95.rename = typeof fs95.rename !== "function" ? fs95.rename : function(fs$rename) {
          function rename(from, to, cb) {
            var start = Date.now();
            var backoff = 0;
            fs$rename(from, to, /* @__PURE__ */ __name(function CB(er) {
              if (er && (er.code === "EACCES" || er.code === "EPERM") && Date.now() - start < 6e4) {
                setTimeout(function() {
                  fs95.stat(to, function(stater, st) {
                    if (stater && stater.code === "ENOENT")
                      fs$rename(from, to, CB);
                    else
                      cb(er);
                  });
                }, backoff);
                if (backoff < 100)
                  backoff += 10;
                return;
              }
              if (cb) cb(er);
            }, "CB"));
          }
          __name(rename, "rename");
          if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename);
          return rename;
        }(fs95.rename);
      }
      fs95.read = typeof fs95.read !== "function" ? fs95.read : function(fs$read) {
        function read2(fd, buffer, offset, length, position, callback_) {
          var callback;
          if (callback_ && typeof callback_ === "function") {
            var eagCounter = 0;
            callback = /* @__PURE__ */ __name(function(er, _, __) {
              if (er && er.code === "EAGAIN" && eagCounter < 10) {
                eagCounter++;
                return fs$read.call(fs95, fd, buffer, offset, length, position, callback);
              }
              callback_.apply(this, arguments);
            }, "callback");
          }
          return fs$read.call(fs95, fd, buffer, offset, length, position, callback);
        }
        __name(read2, "read");
        if (Object.setPrototypeOf) Object.setPrototypeOf(read2, fs$read);
        return read2;
      }(fs95.read);
      fs95.readSync = typeof fs95.readSync !== "function" ? fs95.readSync : /* @__PURE__ */ function(fs$readSync) {
        return function(fd, buffer, offset, length, position) {
          var eagCounter = 0;
          while (true) {
            try {
              return fs$readSync.call(fs95, fd, buffer, offset, length, position);
            } catch (er) {
              if (er.code === "EAGAIN" && eagCounter < 10) {
                eagCounter++;
                continue;
              }
              throw er;
            }
          }
        };
      }(fs95.readSync);
      function patchLchmod(fs96) {
        fs96.lchmod = function(path108, mode, callback) {
          fs96.open(
            path108,
            constants4.O_WRONLY | constants4.O_SYMLINK,
            mode,
            function(err, fd) {
              if (err) {
                if (callback) callback(err);
                return;
              }
              fs96.fchmod(fd, mode, function(err2) {
                fs96.close(fd, function(err22) {
                  if (callback) callback(err2 || err22);
                });
              });
            }
          );
        };
        fs96.lchmodSync = function(path108, mode) {
          var fd = fs96.openSync(path108, constants4.O_WRONLY | constants4.O_SYMLINK, mode);
          var threw = true;
          var ret;
          try {
            ret = fs96.fchmodSync(fd, mode);
            threw = false;
          } finally {
            if (threw) {
              try {
                fs96.closeSync(fd);
              } catch (er) {
              }
            } else {
              fs96.closeSync(fd);
            }
          }
          return ret;
        };
      }
      __name(patchLchmod, "patchLchmod");
      function patchLutimes(fs96) {
        if (constants4.hasOwnProperty("O_SYMLINK") && fs96.futimes) {
          fs96.lutimes = function(path108, at, mt, cb) {
            fs96.open(path108, constants4.O_SYMLINK, function(er, fd) {
              if (er) {
                if (cb) cb(er);
                return;
              }
              fs96.futimes(fd, at, mt, function(er2) {
                fs96.close(fd, function(er22) {
                  if (cb) cb(er2 || er22);
                });
              });
            });
          };
          fs96.lutimesSync = function(path108, at, mt) {
            var fd = fs96.openSync(path108, constants4.O_SYMLINK);
            var ret;
            var threw = true;
            try {
              ret = fs96.futimesSync(fd, at, mt);
              threw = false;
            } finally {
              if (threw) {
                try {
                  fs96.closeSync(fd);
                } catch (er) {
                }
              } else {
                fs96.closeSync(fd);
              }
            }
            return ret;
          };
        } else if (fs96.futimes) {
          fs96.lutimes = function(_a6, _b2, _c2, cb) {
            if (cb) process.nextTick(cb);
          };
          fs96.lutimesSync = function() {
          };
        }
      }
      __name(patchLutimes, "patchLutimes");
      function chmodFix(orig) {
        if (!orig) return orig;
        return function(target, mode, cb) {
          return orig.call(fs95, target, mode, function(er) {
            if (chownErOk(er)) er = null;
            if (cb) cb.apply(this, arguments);
          });
        };
      }
      __name(chmodFix, "chmodFix");
      function chmodFixSync(orig) {
        if (!orig) return orig;
        return function(target, mode) {
          try {
            return orig.call(fs95, target, mode);
          } catch (er) {
            if (!chownErOk(er)) throw er;
          }
        };
      }
      __name(chmodFixSync, "chmodFixSync");
      function chownFix(orig) {
        if (!orig) return orig;
        return function(target, uid, gid, cb) {
          return orig.call(fs95, target, uid, gid, function(er) {
            if (chownErOk(er)) er = null;
            if (cb) cb.apply(this, arguments);
          });
        };
      }
      __name(chownFix, "chownFix");
      function chownFixSync(orig) {
        if (!orig) return orig;
        return function(target, uid, gid) {
          try {
            return orig.call(fs95, target, uid, gid);
          } catch (er) {
            if (!chownErOk(er)) throw er;
          }
        };
      }
      __name(chownFixSync, "chownFixSync");
      function statFix(orig) {
        if (!orig) return orig;
        return function(target, options2, cb) {
          if (typeof options2 === "function") {
            cb = options2;
            options2 = null;
          }
          function callback(er, stats) {
            if (stats) {
              if (stats.uid < 0) stats.uid += 4294967296;
              if (stats.gid < 0) stats.gid += 4294967296;
            }
            if (cb) cb.apply(this, arguments);
          }
          __name(callback, "callback");
          return options2 ? orig.call(fs95, target, options2, callback) : orig.call(fs95, target, callback);
        };
      }
      __name(statFix, "statFix");
      function statFixSync(orig) {
        if (!orig) return orig;
        return function(target, options2) {
          var stats = options2 ? orig.call(fs95, target, options2) : orig.call(fs95, target);
          if (stats) {
            if (stats.uid < 0) stats.uid += 4294967296;
            if (stats.gid < 0) stats.gid += 4294967296;
          }
          return stats;
        };
      }
      __name(statFixSync, "statFixSync");
      function chownErOk(er) {
        if (!er)
          return true;
        if (er.code === "ENOSYS")
          return true;
        var nonroot = !process.getuid || process.getuid() !== 0;
        if (nonroot) {
          if (er.code === "EINVAL" || er.code === "EPERM")
            return true;
        }
        return false;
      }
      __name(chownErOk, "chownErOk");
    }
    __name(patch, "patch");
  }
});

// node_modules/@pnpm/network.ca-file/node_modules/graceful-fs/legacy-streams.js
var require_legacy_streams2 = __commonJS({
  "node_modules/@pnpm/network.ca-file/node_modules/graceful-fs/legacy-streams.js"(exports2, module2) {
    init_esbuild_shims();
    var Stream4 = __require("stream").Stream;
    module2.exports = legacy;
    function legacy(fs95) {
      return {
        ReadStream: ReadStream2,
        WriteStream: WriteStream2
      };
      function ReadStream2(path108, options2) {
        if (!(this instanceof ReadStream2)) return new ReadStream2(path108, options2);
        Stream4.call(this);
        var self2 = this;
        this.path = path108;
        this.fd = null;
        this.readable = true;
        this.paused = false;
        this.flags = "r";
        this.mode = 438;
        this.bufferSize = 64 * 1024;
        options2 = options2 || {};
        var keys = Object.keys(options2);
        for (var index = 0, length = keys.length; index < length; index++) {
          var key = keys[index];
          this[key] = options2[key];
        }
        if (this.encoding) this.setEncoding(this.encoding);
        if (this.start !== void 0) {
          if ("number" !== typeof this.start) {
            throw TypeError("start must be a Number");
          }
          if (this.end === void 0) {
            this.end = Infinity;
          } else if ("number" !== typeof this.end) {
            throw TypeError("end must be a Number");
          }
          if (this.start > this.end) {
            throw new Error("start must be <= end");
          }
          this.pos = this.start;
        }
        if (this.fd !== null) {
          process.nextTick(function() {
            self2._read();
          });
          return;
        }
        fs95.open(this.path, this.flags, this.mode, function(err, fd) {
          if (err) {
            self2.emit("error", err);
            self2.readable = false;
            return;
          }
          self2.fd = fd;
          self2.emit("open", fd);
          self2._read();
        });
      }
      __name(ReadStream2, "ReadStream");
      function WriteStream2(path108, options2) {
        if (!(this instanceof WriteStream2)) return new WriteStream2(path108, options2);
        Stream4.call(this);
        this.path = path108;
        this.fd = null;
        this.writable = true;
        this.flags = "w";
        this.encoding = "binary";
        this.mode = 438;
        this.bytesWritten = 0;
        options2 = options2 || {};
        var keys = Object.keys(options2);
        for (var index = 0, length = keys.length; index < length; index++) {
          var key = keys[index];
          this[key] = options2[key];
        }
        if (this.start !== void 0) {
          if ("number" !== typeof this.start) {
            throw TypeError("start must be a Number");
          }
          if (this.start < 0) {
            throw new Error("start must be >= zero");
          }
          this.pos = this.start;
        }
        this.busy = false;
        this._queue = [];
        if (this.fd === null) {
          this._open = fs95.open;
          this._queue.push([this._open, this.path, this.flags, this.mode, void 0]);
          this.flush();
        }
      }
      __name(WriteStream2, "WriteStream");
    }
    __name(legacy, "legacy");
  }
});

// node_modules/@pnpm/network.ca-file/node_modules/graceful-fs/clone.js
var require_clone2 = __commonJS({
  "node_modules/@pnpm/network.ca-file/node_modules/graceful-fs/clone.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = clone;
    var getPrototypeOf = Object.getPrototypeOf || function(obj) {
      return obj.__proto__;
    };
    function clone(obj) {
      if (obj === null || typeof obj !== "object")
        return obj;
      if (obj instanceof Object)
        var copy = { __proto__: getPrototypeOf(obj) };
      else
        var copy = /* @__PURE__ */ Object.create(null);
      Object.getOwnPropertyNames(obj).forEach(function(key) {
        Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
      });
      return copy;
    }
    __name(clone, "clone");
  }
});

// node_modules/@pnpm/network.ca-file/node_modules/graceful-fs/graceful-fs.js
var require_graceful_fs2 = __commonJS({
  "node_modules/@pnpm/network.ca-file/node_modules/graceful-fs/graceful-fs.js"(exports2, module2) {
    init_esbuild_shims();
    var fs95 = __require("fs");
    var polyfills = require_polyfills2();
    var legacy = require_legacy_streams2();
    var clone = require_clone2();
    var util4 = __require("util");
    var gracefulQueue;
    var previousSymbol;
    if (typeof Symbol === "function" && typeof Symbol.for === "function") {
      gracefulQueue = Symbol.for("graceful-fs.queue");
      previousSymbol = Symbol.for("graceful-fs.previous");
    } else {
      gracefulQueue = "___graceful-fs.queue";
      previousSymbol = "___graceful-fs.previous";
    }
    function noop6() {
    }
    __name(noop6, "noop");
    function publishQueue(context2, queue2) {
      Object.defineProperty(context2, gracefulQueue, {
        get: /* @__PURE__ */ __name(function() {
          return queue2;
        }, "get")
      });
    }
    __name(publishQueue, "publishQueue");
    var debug2 = noop6;
    if (util4.debuglog)
      debug2 = util4.debuglog("gfs4");
    else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ""))
      debug2 = /* @__PURE__ */ __name(function() {
        var m = util4.format.apply(util4, arguments);
        m = "GFS4: " + m.split(/\n/).join("\nGFS4: ");
        console.error(m);
      }, "debug");
    if (!fs95[gracefulQueue]) {
      queue = globalThis[gracefulQueue] || [];
      publishQueue(fs95, queue);
      fs95.close = function(fs$close) {
        function close(fd, cb) {
          return fs$close.call(fs95, fd, function(err) {
            if (!err) {
              resetQueue();
            }
            if (typeof cb === "function")
              cb.apply(this, arguments);
          });
        }
        __name(close, "close");
        Object.defineProperty(close, previousSymbol, {
          value: fs$close
        });
        return close;
      }(fs95.close);
      fs95.closeSync = function(fs$closeSync) {
        function closeSync(fd) {
          fs$closeSync.apply(fs95, arguments);
          resetQueue();
        }
        __name(closeSync, "closeSync");
        Object.defineProperty(closeSync, previousSymbol, {
          value: fs$closeSync
        });
        return closeSync;
      }(fs95.closeSync);
      if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
        process.on("exit", function() {
          debug2(fs95[gracefulQueue]);
          __require("assert").equal(fs95[gracefulQueue].length, 0);
        });
      }
    }
    var queue;
    if (!globalThis[gracefulQueue]) {
      publishQueue(globalThis, fs95[gracefulQueue]);
    }
    module2.exports = patch(clone(fs95));
    if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs95.__patched) {
      module2.exports = patch(fs95);
      fs95.__patched = true;
    }
    function patch(fs96) {
      polyfills(fs96);
      fs96.gracefulify = patch;
      fs96.createReadStream = createReadStream;
      fs96.createWriteStream = createWriteStream5;
      var fs$readFile = fs96.readFile;
      fs96.readFile = readFile11;
      function readFile11(path108, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        return go$readFile(path108, options2, cb);
        function go$readFile(path109, options3, cb2, startTime) {
          return fs$readFile(path109, options3, function(err) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$readFile, [path109, options3, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$readFile, "go$readFile");
      }
      __name(readFile11, "readFile");
      var fs$writeFile = fs96.writeFile;
      fs96.writeFile = writeFile12;
      function writeFile12(path108, data, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        return go$writeFile(path108, data, options2, cb);
        function go$writeFile(path109, data2, options3, cb2, startTime) {
          return fs$writeFile(path109, data2, options3, function(err) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$writeFile, [path109, data2, options3, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$writeFile, "go$writeFile");
      }
      __name(writeFile12, "writeFile");
      var fs$appendFile = fs96.appendFile;
      if (fs$appendFile)
        fs96.appendFile = appendFile;
      function appendFile(path108, data, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        return go$appendFile(path108, data, options2, cb);
        function go$appendFile(path109, data2, options3, cb2, startTime) {
          return fs$appendFile(path109, data2, options3, function(err) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$appendFile, [path109, data2, options3, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$appendFile, "go$appendFile");
      }
      __name(appendFile, "appendFile");
      var fs$copyFile = fs96.copyFile;
      if (fs$copyFile)
        fs96.copyFile = copyFile;
      function copyFile(src, dest, flags, cb) {
        if (typeof flags === "function") {
          cb = flags;
          flags = 0;
        }
        return go$copyFile(src, dest, flags, cb);
        function go$copyFile(src2, dest2, flags2, cb2, startTime) {
          return fs$copyFile(src2, dest2, flags2, function(err) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$copyFile, [src2, dest2, flags2, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$copyFile, "go$copyFile");
      }
      __name(copyFile, "copyFile");
      var fs$readdir = fs96.readdir;
      fs96.readdir = readdir10;
      var noReaddirOptionVersions = /^v[0-5]\./;
      function readdir10(path108, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        var go$readdir = noReaddirOptionVersions.test(process.version) ? /* @__PURE__ */ __name(function go$readdir2(path109, options3, cb2, startTime) {
          return fs$readdir(path109, fs$readdirCallback(
            path109,
            options3,
            cb2,
            startTime
          ));
        }, "go$readdir") : /* @__PURE__ */ __name(function go$readdir2(path109, options3, cb2, startTime) {
          return fs$readdir(path109, options3, fs$readdirCallback(
            path109,
            options3,
            cb2,
            startTime
          ));
        }, "go$readdir");
        return go$readdir(path108, options2, cb);
        function fs$readdirCallback(path109, options3, cb2, startTime) {
          return function(err, files) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([
                go$readdir,
                [path109, options3, cb2],
                err,
                startTime || Date.now(),
                Date.now()
              ]);
            else {
              if (files && files.sort)
                files.sort();
              if (typeof cb2 === "function")
                cb2.call(this, err, files);
            }
          };
        }
        __name(fs$readdirCallback, "fs$readdirCallback");
      }
      __name(readdir10, "readdir");
      if (process.version.substr(0, 4) === "v0.8") {
        var legStreams = legacy(fs96);
        ReadStream2 = legStreams.ReadStream;
        WriteStream2 = legStreams.WriteStream;
      }
      var fs$ReadStream = fs96.ReadStream;
      if (fs$ReadStream) {
        ReadStream2.prototype = Object.create(fs$ReadStream.prototype);
        ReadStream2.prototype.open = ReadStream$open;
      }
      var fs$WriteStream = fs96.WriteStream;
      if (fs$WriteStream) {
        WriteStream2.prototype = Object.create(fs$WriteStream.prototype);
        WriteStream2.prototype.open = WriteStream$open;
      }
      Object.defineProperty(fs96, "ReadStream", {
        get: /* @__PURE__ */ __name(function() {
          return ReadStream2;
        }, "get"),
        set: /* @__PURE__ */ __name(function(val) {
          ReadStream2 = val;
        }, "set"),
        enumerable: true,
        configurable: true
      });
      Object.defineProperty(fs96, "WriteStream", {
        get: /* @__PURE__ */ __name(function() {
          return WriteStream2;
        }, "get"),
        set: /* @__PURE__ */ __name(function(val) {
          WriteStream2 = val;
        }, "set"),
        enumerable: true,
        configurable: true
      });
      var FileReadStream = ReadStream2;
      Object.defineProperty(fs96, "FileReadStream", {
        get: /* @__PURE__ */ __name(function() {
          return FileReadStream;
        }, "get"),
        set: /* @__PURE__ */ __name(function(val) {
          FileReadStream = val;
        }, "set"),
        enumerable: true,
        configurable: true
      });
      var FileWriteStream = WriteStream2;
      Object.defineProperty(fs96, "FileWriteStream", {
        get: /* @__PURE__ */ __name(function() {
          return FileWriteStream;
        }, "get"),
        set: /* @__PURE__ */ __name(function(val) {
          FileWriteStream = val;
        }, "set"),
        enumerable: true,
        configurable: true
      });
      function ReadStream2(path108, options2) {
        if (this instanceof ReadStream2)
          return fs$ReadStream.apply(this, arguments), this;
        else
          return ReadStream2.apply(Object.create(ReadStream2.prototype), arguments);
      }
      __name(ReadStream2, "ReadStream");
      function ReadStream$open() {
        var that = this;
        open3(that.path, that.flags, that.mode, function(err, fd) {
          if (err) {
            if (that.autoClose)
              that.destroy();
            that.emit("error", err);
          } else {
            that.fd = fd;
            that.emit("open", fd);
            that.read();
          }
        });
      }
      __name(ReadStream$open, "ReadStream$open");
      function WriteStream2(path108, options2) {
        if (this instanceof WriteStream2)
          return fs$WriteStream.apply(this, arguments), this;
        else
          return WriteStream2.apply(Object.create(WriteStream2.prototype), arguments);
      }
      __name(WriteStream2, "WriteStream");
      function WriteStream$open() {
        var that = this;
        open3(that.path, that.flags, that.mode, function(err, fd) {
          if (err) {
            that.destroy();
            that.emit("error", err);
          } else {
            that.fd = fd;
            that.emit("open", fd);
          }
        });
      }
      __name(WriteStream$open, "WriteStream$open");
      function createReadStream(path108, options2) {
        return new fs96.ReadStream(path108, options2);
      }
      __name(createReadStream, "createReadStream");
      function createWriteStream5(path108, options2) {
        return new fs96.WriteStream(path108, options2);
      }
      __name(createWriteStream5, "createWriteStream");
      var fs$open = fs96.open;
      fs96.open = open3;
      function open3(path108, flags, mode, cb) {
        if (typeof mode === "function")
          cb = mode, mode = null;
        return go$open(path108, flags, mode, cb);
        function go$open(path109, flags2, mode2, cb2, startTime) {
          return fs$open(path109, flags2, mode2, function(err, fd) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$open, [path109, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$open, "go$open");
      }
      __name(open3, "open");
      return fs96;
    }
    __name(patch, "patch");
    function enqueue(elem) {
      debug2("ENQUEUE", elem[0].name, elem[1]);
      fs95[gracefulQueue].push(elem);
      retry();
    }
    __name(enqueue, "enqueue");
    var retryTimer;
    function resetQueue() {
      var now = Date.now();
      for (var i = 0; i < fs95[gracefulQueue].length; ++i) {
        if (fs95[gracefulQueue][i].length > 2) {
          fs95[gracefulQueue][i][3] = now;
          fs95[gracefulQueue][i][4] = now;
        }
      }
      retry();
    }
    __name(resetQueue, "resetQueue");
    function retry() {
      clearTimeout(retryTimer);
      retryTimer = void 0;
      if (fs95[gracefulQueue].length === 0)
        return;
      var elem = fs95[gracefulQueue].shift();
      var fn = elem[0];
      var args = elem[1];
      var err = elem[2];
      var startTime = elem[3];
      var lastTime = elem[4];
      if (startTime === void 0) {
        debug2("RETRY", fn.name, args);
        fn.apply(null, args);
      } else if (Date.now() - startTime >= 6e4) {
        debug2("TIMEOUT", fn.name, args);
        var cb = args.pop();
        if (typeof cb === "function")
          cb.call(null, err);
      } else {
        var sinceAttempt = Date.now() - lastTime;
        var sinceStart = Math.max(lastTime - startTime, 1);
        var desiredDelay = Math.min(sinceStart * 1.2, 100);
        if (sinceAttempt >= desiredDelay) {
          debug2("RETRY", fn.name, args);
          fn.apply(null, args.concat([startTime]));
        } else {
          fs95[gracefulQueue].push(elem);
        }
      }
      if (retryTimer === void 0) {
        retryTimer = setTimeout(retry, 0);
      }
    }
    __name(retry, "retry");
  }
});

// node_modules/@pnpm/network.ca-file/dist/ca-file.js
var require_ca_file = __commonJS({
  "node_modules/@pnpm/network.ca-file/dist/ca-file.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
      return mod2 && mod2.__esModule ? mod2 : { "default": mod2 };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.readCAFileSync = void 0;
    var graceful_fs_1 = __importDefault(require_graceful_fs2());
    function readCAFileSync(filePath) {
      try {
        const contents = graceful_fs_1.default.readFileSync(filePath, "utf8");
        const delim = "-----END CERTIFICATE-----";
        const output = contents.split(delim).filter((ca) => Boolean(ca.trim())).map((ca) => `${ca.trimLeft()}${delim}`);
        return output;
      } catch (err) {
        if (err.code === "ENOENT")
          return void 0;
        throw err;
      }
    }
    __name(readCAFileSync, "readCAFileSync");
    exports2.readCAFileSync = readCAFileSync;
  }
});

// node_modules/@pnpm/network.ca-file/dist/index.js
var require_dist7 = __commonJS({
  "node_modules/@pnpm/network.ca-file/dist/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc2 = Object.getOwnPropertyDescriptor(m, k);
      if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) {
        desc2 = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m[k];
        }, "get") };
      }
      Object.defineProperty(o2, k2, desc2);
    } : function(o2, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o2[k2] = m[k];
    });
    var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    __exportStar(require_ca_file(), exports2);
  }
});

// node_modules/proto-list/proto-list.js
var require_proto_list = __commonJS({
  "node_modules/proto-list/proto-list.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = ProtoList;
    function setProto(obj, proto3) {
      if (typeof Object.setPrototypeOf === "function")
        return Object.setPrototypeOf(obj, proto3);
      else
        obj.__proto__ = proto3;
    }
    __name(setProto, "setProto");
    function ProtoList() {
      this.list = [];
      var root = null;
      Object.defineProperty(this, "root", {
        get: /* @__PURE__ */ __name(function() {
          return root;
        }, "get"),
        set: /* @__PURE__ */ __name(function(r3) {
          root = r3;
          if (this.list.length) {
            setProto(this.list[this.list.length - 1], r3);
          }
        }, "set"),
        enumerable: true,
        configurable: true
      });
    }
    __name(ProtoList, "ProtoList");
    ProtoList.prototype = {
      get length() {
        return this.list.length;
      },
      get keys() {
        var k = [];
        for (var i in this.list[0]) k.push(i);
        return k;
      },
      get snapshot() {
        var o2 = {};
        this.keys.forEach(function(k) {
          o2[k] = this.get(k);
        }, this);
        return o2;
      },
      get store() {
        return this.list[0];
      },
      push: /* @__PURE__ */ __name(function(obj) {
        if (typeof obj !== "object") obj = { valueOf: obj };
        if (this.list.length >= 1) {
          setProto(this.list[this.list.length - 1], obj);
        }
        setProto(obj, this.root);
        return this.list.push(obj);
      }, "push"),
      pop: /* @__PURE__ */ __name(function() {
        if (this.list.length >= 2) {
          setProto(this.list[this.list.length - 2], this.root);
        }
        return this.list.pop();
      }, "pop"),
      unshift: /* @__PURE__ */ __name(function(obj) {
        setProto(obj, this.list[0] || this.root);
        return this.list.unshift(obj);
      }, "unshift"),
      shift: /* @__PURE__ */ __name(function() {
        if (this.list.length === 1) {
          setProto(this.list[0], this.root);
        }
        return this.list.shift();
      }, "shift"),
      get: /* @__PURE__ */ __name(function(key) {
        return this.list[0][key];
      }, "get"),
      set: /* @__PURE__ */ __name(function(key, val, save) {
        if (!this.length) this.push({});
        if (save && this.list[0].hasOwnProperty(key)) this.push({});
        return this.list[0][key] = val;
      }, "set"),
      forEach: /* @__PURE__ */ __name(function(fn, thisp) {
        for (var key in this.list[0]) fn.call(thisp, key, this.list[0][key]);
      }, "forEach"),
      slice: /* @__PURE__ */ __name(function() {
        return this.list.slice.apply(this.list, arguments);
      }, "slice"),
      splice: /* @__PURE__ */ __name(function() {
        var ret = this.list.splice.apply(this.list, arguments);
        for (var i = 0, l2 = this.list.length; i < l2; i++) {
          setProto(this.list[i], this.list[i + 1] || this.root);
        }
        return ret;
      }, "splice")
    };
  }
});

// node_modules/config-chain/node_modules/ini/ini.js
var require_ini2 = __commonJS({
  "node_modules/config-chain/node_modules/ini/ini.js"(exports2) {
    init_esbuild_shims();
    exports2.parse = exports2.decode = decode2;
    exports2.stringify = exports2.encode = encode4;
    exports2.safe = safe;
    exports2.unsafe = unsafe;
    var eol = typeof process !== "undefined" && process.platform === "win32" ? "\r\n" : "\n";
    function encode4(obj, opt) {
      var children = [];
      var out = "";
      if (typeof opt === "string") {
        opt = {
          section: opt,
          whitespace: false
        };
      } else {
        opt = opt || {};
        opt.whitespace = opt.whitespace === true;
      }
      var separator = opt.whitespace ? " = " : "=";
      Object.keys(obj).forEach(function(k, _, __) {
        var val = obj[k];
        if (val && Array.isArray(val)) {
          val.forEach(function(item) {
            out += safe(k + "[]") + separator + safe(item) + "\n";
          });
        } else if (val && typeof val === "object")
          children.push(k);
        else
          out += safe(k) + separator + safe(val) + eol;
      });
      if (opt.section && out.length)
        out = "[" + safe(opt.section) + "]" + eol + out;
      children.forEach(function(k, _, __) {
        var nk = dotSplit(k).join("\\.");
        var section = (opt.section ? opt.section + "." : "") + nk;
        var child = encode4(obj[k], {
          section,
          whitespace: opt.whitespace
        });
        if (out.length && child.length)
          out += eol;
        out += child;
      });
      return out;
    }
    __name(encode4, "encode");
    function dotSplit(str2) {
      return str2.replace(/\1/g, "LITERAL\\1LITERAL").replace(/\\\./g, "").split(/\./).map(function(part) {
        return part.replace(/\1/g, "\\.").replace(/\2LITERAL\\1LITERAL\2/g, "");
      });
    }
    __name(dotSplit, "dotSplit");
    function decode2(str2) {
      var out = {};
      var p = out;
      var section = null;
      var re2 = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i;
      var lines = str2.split(/[\r\n]+/g);
      lines.forEach(function(line, _, __) {
        if (!line || line.match(/^\s*[;#]/))
          return;
        var match2 = line.match(re2);
        if (!match2)
          return;
        if (match2[1] !== void 0) {
          section = unsafe(match2[1]);
          if (section === "__proto__") {
            p = {};
            return;
          }
          p = out[section] = out[section] || {};
          return;
        }
        var key = unsafe(match2[2]);
        if (key === "__proto__")
          return;
        var value = match2[3] ? unsafe(match2[4]) : true;
        switch (value) {
          case "true":
          case "false":
          case "null":
            value = JSON.parse(value);
        }
        if (key.length > 2 && key.slice(-2) === "[]") {
          key = key.substring(0, key.length - 2);
          if (key === "__proto__")
            return;
          if (!p[key])
            p[key] = [];
          else if (!Array.isArray(p[key]))
            p[key] = [p[key]];
        }
        if (Array.isArray(p[key]))
          p[key].push(value);
        else
          p[key] = value;
      });
      Object.keys(out).filter(function(k, _, __) {
        if (!out[k] || typeof out[k] !== "object" || Array.isArray(out[k]))
          return false;
        var parts = dotSplit(k);
        var p2 = out;
        var l2 = parts.pop();
        var nl2 = l2.replace(/\\\./g, ".");
        parts.forEach(function(part, _2, __2) {
          if (part === "__proto__")
            return;
          if (!p2[part] || typeof p2[part] !== "object")
            p2[part] = {};
          p2 = p2[part];
        });
        if (p2 === out && nl2 === l2)
          return false;
        p2[nl2] = out[k];
        return true;
      }).forEach(function(del, _, __) {
        delete out[del];
      });
      return out;
    }
    __name(decode2, "decode");
    function isQuoted(val) {
      return val.charAt(0) === '"' && val.slice(-1) === '"' || val.charAt(0) === "'" && val.slice(-1) === "'";
    }
    __name(isQuoted, "isQuoted");
    function safe(val) {
      return typeof val !== "string" || val.match(/[=\r\n]/) || val.match(/^\[/) || val.length > 1 && isQuoted(val) || val !== val.trim() ? JSON.stringify(val) : val.replace(/;/g, "\\;").replace(/#/g, "\\#");
    }
    __name(safe, "safe");
    function unsafe(val, doUnesc) {
      val = (val || "").trim();
      if (isQuoted(val)) {
        if (val.charAt(0) === "'")
          val = val.substr(1, val.length - 2);
        try {
          val = JSON.parse(val);
        } catch (_) {
        }
      } else {
        var esc = false;
        var unesc = "";
        for (var i = 0, l2 = val.length; i < l2; i++) {
          var c3 = val.charAt(i);
          if (esc) {
            if ("\\;#".indexOf(c3) !== -1)
              unesc += c3;
            else
              unesc += "\\" + c3;
            esc = false;
          } else if (";#".indexOf(c3) !== -1)
            break;
          else if (c3 === "\\")
            esc = true;
          else
            unesc += c3;
        }
        if (esc)
          unesc += "\\";
        return unesc.trim();
      }
      return val;
    }
    __name(unsafe, "unsafe");
  }
});

// node_modules/config-chain/index.js
var require_config_chain = __commonJS({
  "node_modules/config-chain/index.js"(exports2, module2) {
    init_esbuild_shims();
    var ProtoList = require_proto_list();
    var path108 = __require("path");
    var fs95 = __require("fs");
    var ini3 = require_ini2();
    var EE3 = __require("events").EventEmitter;
    var url2 = __require("url");
    var http4 = __require("http");
    var exports2 = module2.exports = function() {
      var args = [].slice.call(arguments), conf = new ConfigChain();
      while (args.length) {
        var a = args.shift();
        if (a) conf.push("string" === typeof a ? json2(a) : a);
      }
      return conf;
    };
    var find = exports2.find = function() {
      var rel = path108.join.apply(null, [].slice.call(arguments));
      function find2(start, rel2) {
        var file = path108.join(start, rel2);
        try {
          fs95.statSync(file);
          return file;
        } catch (err) {
          if (path108.dirname(start) !== start)
            return find2(path108.dirname(start), rel2);
        }
      }
      __name(find2, "find");
      return find2(__dirname, rel);
    };
    var parse12 = exports2.parse = function(content, file, type) {
      content = "" + content;
      if (!type) {
        try {
          return JSON.parse(content);
        } catch (er) {
          return ini3.parse(content);
        }
      } else if (type === "json") {
        if (this.emit) {
          try {
            return JSON.parse(content);
          } catch (er) {
            this.emit("error", er);
          }
        } else {
          return JSON.parse(content);
        }
      } else {
        return ini3.parse(content);
      }
    };
    var json2 = exports2.json = function() {
      var args = [].slice.call(arguments).filter(function(arg) {
        return arg != null;
      });
      var file = path108.join.apply(null, args);
      var content;
      try {
        content = fs95.readFileSync(file, "utf-8");
      } catch (err) {
        return;
      }
      return parse12(content, file, "json");
    };
    var env7 = exports2.env = function(prefix, env8) {
      env8 = env8 || process.env;
      var obj = {};
      var l2 = prefix.length;
      for (var k in env8) {
        if (k.indexOf(prefix) === 0)
          obj[k.substring(l2)] = env8[k];
      }
      return obj;
    };
    exports2.ConfigChain = ConfigChain;
    function ConfigChain() {
      EE3.apply(this);
      ProtoList.apply(this, arguments);
      this._awaiting = 0;
      this._saving = 0;
      this.sources = {};
    }
    __name(ConfigChain, "ConfigChain");
    var extras = {
      constructor: { value: ConfigChain }
    };
    Object.keys(EE3.prototype).forEach(function(k) {
      extras[k] = Object.getOwnPropertyDescriptor(EE3.prototype, k);
    });
    ConfigChain.prototype = Object.create(ProtoList.prototype, extras);
    ConfigChain.prototype.del = function(key, where) {
      if (where) {
        var target = this.sources[where];
        target = target && target.data;
        if (!target) {
          return this.emit("error", new Error("not found " + where));
        }
        delete target[key];
      } else {
        for (var i = 0, l2 = this.list.length; i < l2; i++) {
          delete this.list[i][key];
        }
      }
      return this;
    };
    ConfigChain.prototype.set = function(key, value, where) {
      var target;
      if (where) {
        target = this.sources[where];
        target = target && target.data;
        if (!target) {
          return this.emit("error", new Error("not found " + where));
        }
      } else {
        target = this.list[0];
        if (!target) {
          return this.emit("error", new Error("cannot set, no confs!"));
        }
      }
      target[key] = value;
      return this;
    };
    ConfigChain.prototype.get = function(key, where) {
      if (where) {
        where = this.sources[where];
        if (where) where = where.data;
        if (where && Object.hasOwnProperty.call(where, key)) return where[key];
        return void 0;
      }
      return this.list[0][key];
    };
    ConfigChain.prototype.save = function(where, type, cb) {
      if (typeof type === "function") cb = type, type = null;
      var target = this.sources[where];
      if (!target || !(target.path || target.source) || !target.data) {
        return this.emit("error", new Error("bad save target: " + where));
      }
      if (target.source) {
        var pref = target.prefix || "";
        Object.keys(target.data).forEach(function(k) {
          target.source[pref + k] = target.data[k];
        });
        return this;
      }
      var type = type || target.type;
      var data = target.data;
      if (target.type === "json") {
        data = JSON.stringify(data);
      } else {
        data = ini3.stringify(data);
      }
      this._saving++;
      fs95.writeFile(target.path, data, "utf8", function(er) {
        this._saving--;
        if (er) {
          if (cb) return cb(er);
          else return this.emit("error", er);
        }
        if (this._saving === 0) {
          if (cb) cb();
          this.emit("save");
        }
      }.bind(this));
      return this;
    };
    ConfigChain.prototype.addFile = function(file, type, name3) {
      name3 = name3 || file;
      var marker = { __source__: name3 };
      this.sources[name3] = { path: file, type };
      this.push(marker);
      this._await();
      fs95.readFile(file, "utf8", function(er, data) {
        if (er) this.emit("error", er);
        this.addString(data, file, type, marker);
      }.bind(this));
      return this;
    };
    ConfigChain.prototype.addEnv = function(prefix, env8, name3) {
      name3 = name3 || "env";
      var data = exports2.env(prefix, env8);
      this.sources[name3] = { data, source: env8, prefix };
      return this.add(data, name3);
    };
    ConfigChain.prototype.addUrl = function(req, type, name3) {
      this._await();
      var href = url2.format(req);
      name3 = name3 || href;
      var marker = { __source__: name3 };
      this.sources[name3] = { href, type };
      this.push(marker);
      http4.request(req, function(res) {
        var c3 = [];
        var ct = res.headers["content-type"];
        if (!type) {
          type = ct.indexOf("json") !== -1 ? "json" : ct.indexOf("ini") !== -1 ? "ini" : href.match(/\.json$/) ? "json" : href.match(/\.ini$/) ? "ini" : null;
          marker.type = type;
        }
        res.on("data", c3.push.bind(c3)).on("end", function() {
          this.addString(Buffer.concat(c3), href, type, marker);
        }.bind(this)).on("error", this.emit.bind(this, "error"));
      }.bind(this)).on("error", this.emit.bind(this, "error")).end();
      return this;
    };
    ConfigChain.prototype.addString = function(data, file, type, marker) {
      data = this.parse(data, file, type);
      this.add(data, marker);
      return this;
    };
    ConfigChain.prototype.add = function(data, marker) {
      if (marker && typeof marker === "object") {
        var i = this.list.indexOf(marker);
        if (i === -1) {
          return this.emit("error", new Error("bad marker"));
        }
        this.splice(i, 1, data);
        marker = marker.__source__;
        this.sources[marker] = this.sources[marker] || {};
        this.sources[marker].data = data;
        this._resolve();
      } else {
        if (typeof marker === "string") {
          this.sources[marker] = this.sources[marker] || {};
          this.sources[marker].data = data;
        }
        this._await();
        this.push(data);
        process.nextTick(this._resolve.bind(this));
      }
      return this;
    };
    ConfigChain.prototype.parse = exports2.parse;
    ConfigChain.prototype._await = function() {
      this._awaiting++;
    };
    ConfigChain.prototype._resolve = function() {
      this._awaiting--;
      if (this._awaiting === 0) this.emit("load", this);
    };
  }
});

// node_modules/@pnpm/npm-conf/lib/envKeyToSetting.js
var require_envKeyToSetting = __commonJS({
  "node_modules/@pnpm/npm-conf/lib/envKeyToSetting.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = function(x) {
      const colonIndex = x.indexOf(":");
      if (colonIndex === -1) {
        return normalize10(x);
      }
      const firstPart = x.substr(0, colonIndex);
      const secondPart = x.substr(colonIndex + 1);
      return `${normalize10(firstPart)}:${normalize10(secondPart)}`;
    };
    function normalize10(s2) {
      s2 = s2.toLowerCase();
      if (s2 === "_authtoken") return "_authToken";
      let r3 = s2[0];
      for (let i = 1; i < s2.length; i++) {
        r3 += s2[i] === "_" ? "-" : s2[i];
      }
      return r3;
    }
    __name(normalize10, "normalize");
  }
});

// node_modules/@pnpm/config.env-replace/dist/env-replace.js
var require_env_replace = __commonJS({
  "node_modules/@pnpm/config.env-replace/dist/env-replace.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.envReplace = void 0;
    var ENV_EXPR = /(?<!\\)(\\*)\$\{([^${}]+)\}/g;
    function envReplace(settingValue, env7) {
      return settingValue.replace(ENV_EXPR, replaceEnvMatch.bind(null, env7));
    }
    __name(envReplace, "envReplace");
    exports2.envReplace = envReplace;
    function replaceEnvMatch(env7, orig, escape7, name3) {
      if (escape7.length % 2) {
        return orig.slice((escape7.length + 1) / 2);
      }
      const envValue = getEnvValue(env7, name3);
      if (envValue === void 0) {
        throw new Error(`Failed to replace env in config: ${orig}`);
      }
      return `${escape7.slice(escape7.length / 2)}${envValue}`;
    }
    __name(replaceEnvMatch, "replaceEnvMatch");
    var ENV_VALUE = /([^:-]+)(:?)-(.+)/;
    function getEnvValue(env7, name3) {
      const matched = name3.match(ENV_VALUE);
      if (!matched)
        return env7[name3];
      const [, variableName, colon, fallback] = matched;
      if (Object.prototype.hasOwnProperty.call(env7, variableName)) {
        return !env7[variableName] && colon ? fallback : env7[variableName];
      }
      return fallback;
    }
    __name(getEnvValue, "getEnvValue");
  }
});

// node_modules/@pnpm/config.env-replace/dist/index.js
var require_dist8 = __commonJS({
  "node_modules/@pnpm/config.env-replace/dist/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.envReplace = void 0;
    var env_replace_1 = require_env_replace();
    Object.defineProperty(exports2, "envReplace", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return env_replace_1.envReplace;
    }, "get") });
  }
});

// node_modules/@pnpm/npm-conf/lib/util.js
var require_util18 = __commonJS({
  "node_modules/@pnpm/npm-conf/lib/util.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var fs95 = __require("fs");
    var path108 = __require("path");
    var { envReplace } = require_dist8();
    var parseKey = /* @__PURE__ */ __name((key) => {
      if (typeof key !== "string") {
        return key;
      }
      return envReplace(key, process.env);
    }, "parseKey");
    var parseField = /* @__PURE__ */ __name((types3, field, key) => {
      if (typeof field !== "string") {
        return field;
      }
      const typeList = [].concat(types3[key]);
      const isPath = typeList.indexOf(path108) !== -1;
      const isBool = typeList.indexOf(Boolean) !== -1;
      const isString2 = typeList.indexOf(String) !== -1;
      const isNumber3 = typeList.indexOf(Number) !== -1;
      field = `${field}`.trim();
      if (/^".*"$/.test(field)) {
        try {
          field = JSON.parse(field);
        } catch (error) {
          throw new Error(`Failed parsing JSON config key ${key}: ${field}`);
        }
      }
      if (isBool && !isString2 && field === "") {
        return true;
      }
      switch (field) {
        // eslint-disable-line default-case
        case "true": {
          return true;
        }
        case "false": {
          return false;
        }
        case "null": {
          return null;
        }
        case "undefined": {
          return void 0;
        }
      }
      field = envReplace(field, process.env);
      if (isPath) {
        const regex3 = process.platform === "win32" ? /^~(\/|\\)/ : /^~\//;
        if (regex3.test(field) && process.env.HOME) {
          field = path108.resolve(process.env.HOME, field.substr(2));
        }
        field = path108.resolve(field);
      }
      if (isNumber3 && !isNaN(field)) {
        field = Number(field);
      }
      return field;
    }, "parseField");
    var findPrefix = /* @__PURE__ */ __name((name3) => {
      name3 = path108.resolve(name3);
      let walkedUp = false;
      while (path108.basename(name3) === "node_modules") {
        name3 = path108.dirname(name3);
        walkedUp = true;
      }
      if (walkedUp) {
        return name3;
      }
      const find = /* @__PURE__ */ __name((name4, original) => {
        const regex3 = /^[a-zA-Z]:(\\|\/)?$/;
        if (name4 === "/" || process.platform === "win32" && regex3.test(name4)) {
          return original;
        }
        try {
          const files = fs95.readdirSync(name4);
          if (files.includes("node_modules") || files.includes("package.json") || files.includes("package.json5") || files.includes("package.yaml") || files.includes("pnpm-workspace.yaml")) {
            return name4;
          }
          const dirname22 = path108.dirname(name4);
          if (dirname22 === name4) {
            return original;
          }
          return find(dirname22, original);
        } catch (error) {
          if (name4 === original) {
            if (error.code === "ENOENT") {
              return original;
            }
            throw error;
          }
          return original;
        }
      }, "find");
      return find(name3, name3);
    }, "findPrefix");
    exports2.envReplace = envReplace;
    exports2.findPrefix = findPrefix;
    exports2.parseField = parseField;
    exports2.parseKey = parseKey;
  }
});

// node_modules/@pnpm/npm-conf/lib/types.js
var require_types9 = __commonJS({
  "node_modules/@pnpm/npm-conf/lib/types.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var path108 = __require("path");
    var Stream4 = __require("stream").Stream;
    var url2 = __require("url");
    var Umask = /* @__PURE__ */ __name(() => {
    }, "Umask");
    var getLocalAddresses = /* @__PURE__ */ __name(() => [], "getLocalAddresses");
    var semver3 = /* @__PURE__ */ __name(() => {
    }, "semver");
    exports2.types = {
      access: [null, "restricted", "public"],
      "allow-same-version": Boolean,
      "always-auth": Boolean,
      also: [null, "dev", "development"],
      audit: Boolean,
      "auth-type": ["legacy", "sso", "saml", "oauth"],
      "bin-links": Boolean,
      browser: [null, String],
      ca: [null, String, Array],
      cafile: path108,
      cache: path108,
      "cache-lock-stale": Number,
      "cache-lock-retries": Number,
      "cache-lock-wait": Number,
      "cache-max": Number,
      "cache-min": Number,
      cert: [null, String],
      cidr: [null, String, Array],
      color: ["always", Boolean],
      depth: Number,
      description: Boolean,
      dev: Boolean,
      "dry-run": Boolean,
      editor: String,
      "engine-strict": Boolean,
      force: Boolean,
      "fetch-retries": Number,
      "fetch-retry-factor": Number,
      "fetch-retry-mintimeout": Number,
      "fetch-retry-maxtimeout": Number,
      git: String,
      "git-tag-version": Boolean,
      "commit-hooks": Boolean,
      global: Boolean,
      globalconfig: path108,
      "global-style": Boolean,
      group: [Number, String],
      "https-proxy": [null, url2],
      "user-agent": String,
      "ham-it-up": Boolean,
      "heading": String,
      "if-present": Boolean,
      "ignore-prepublish": Boolean,
      "ignore-scripts": Boolean,
      "init-module": path108,
      "init-author-name": String,
      "init-author-email": String,
      "init-author-url": ["", url2],
      "init-license": String,
      "init-version": semver3,
      json: Boolean,
      key: [null, String],
      "legacy-bundling": Boolean,
      link: Boolean,
      // local-address must be listed as an IP for a local network interface
      // must be IPv4 due to node bug
      "local-address": getLocalAddresses(),
      loglevel: ["silent", "error", "warn", "notice", "http", "timing", "info", "verbose", "silly"],
      logstream: Stream4,
      "logs-max": Number,
      long: Boolean,
      maxsockets: Number,
      message: String,
      "metrics-registry": [null, String],
      "node-options": [null, String],
      "node-version": [null, semver3],
      "no-proxy": [null, String, Array],
      offline: Boolean,
      "onload-script": [null, String],
      only: [null, "dev", "development", "prod", "production"],
      optional: Boolean,
      "package-lock": Boolean,
      otp: [null, String],
      "package-lock-only": Boolean,
      parseable: Boolean,
      "prefer-offline": Boolean,
      "prefer-online": Boolean,
      prefix: path108,
      production: Boolean,
      progress: Boolean,
      proxy: [null, false, url2],
      provenance: Boolean,
      // allow proxy to be disabled explicitly
      "read-only": Boolean,
      "rebuild-bundle": Boolean,
      registry: [null, url2],
      rollback: Boolean,
      save: Boolean,
      "save-bundle": Boolean,
      "save-dev": Boolean,
      "save-exact": Boolean,
      "save-optional": Boolean,
      "save-prefix": String,
      "save-prod": Boolean,
      scope: String,
      "script-shell": [null, String],
      "scripts-prepend-node-path": [false, true, "auto", "warn-only"],
      searchopts: String,
      searchexclude: [null, String],
      searchlimit: Number,
      searchstaleness: Number,
      "send-metrics": Boolean,
      shell: String,
      shrinkwrap: Boolean,
      "sign-git-tag": Boolean,
      "sso-poll-frequency": Number,
      "sso-type": [null, "oauth", "saml"],
      "strict-ssl": Boolean,
      tag: String,
      timing: Boolean,
      tmp: path108,
      unicode: Boolean,
      "unsafe-perm": Boolean,
      usage: Boolean,
      user: [Number, String],
      userconfig: path108,
      umask: Umask,
      version: Boolean,
      "tag-version-prefix": String,
      versions: Boolean,
      viewer: String,
      _exit: Boolean
    };
  }
});

// node_modules/@pnpm/npm-conf/lib/conf.js
var require_conf = __commonJS({
  "node_modules/@pnpm/npm-conf/lib/conf.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { readCAFileSync } = require_dist7();
    var fs95 = __require("fs");
    var path108 = __require("path");
    var { ConfigChain } = require_config_chain();
    var envKeyToSetting = require_envKeyToSetting();
    var util4 = require_util18();
    var Conf = class extends ConfigChain {
      static {
        __name(this, "Conf");
      }
      // https://github.com/npm/cli/blob/latest/lib/config/core.js#L203-L217
      constructor(base, types3) {
        super(base);
        this.root = base;
        this._parseField = util4.parseField.bind(null, types3 || require_types9());
      }
      // https://github.com/npm/cli/blob/latest/lib/config/core.js#L326-L338
      add(data, marker) {
        try {
          for (const [key, value] of Object.entries(data)) {
            const substKey = util4.parseKey(key);
            if (substKey !== key) {
              delete data[key];
            }
            data[substKey] = this._parseField(value, substKey);
          }
        } catch (error) {
          throw error;
        }
        return super.add(data, marker);
      }
      // https://github.com/npm/cli/blob/latest/lib/config/core.js#L306-L319
      addFile(file, name3) {
        name3 = name3 || file;
        const marker = { __source__: name3 };
        this.sources[name3] = { path: file, type: "ini" };
        this.push(marker);
        this._await();
        try {
          const contents = fs95.readFileSync(file, "utf8");
          this.addString(contents, file, "ini", marker);
        } catch (error) {
          if (error.code === "ENOENT") {
            this.add({}, marker);
          } else if (error.code !== "EISDIR") {
            return `Issue while reading "${file}". ${error.message}`;
          }
        }
      }
      // https://github.com/npm/cli/blob/latest/lib/config/core.js#L341-L357
      addEnv(env7) {
        env7 = env7 || process.env;
        const conf = {};
        Object.keys(env7).filter((x) => /^npm_config_/i.test(x)).forEach((x) => {
          if (!env7[x]) {
            return;
          }
          const key = envKeyToSetting(x.substr(11));
          const rawVal = env7[x];
          conf[key] = deserializeEnvVal(key, rawVal);
        });
        return super.addEnv("", conf, "env");
      }
      // https://github.com/npm/cli/blob/latest/lib/config/load-prefix.js
      loadPrefix() {
        const cli = this.list[0];
        Object.defineProperty(this, "prefix", {
          enumerable: true,
          set: /* @__PURE__ */ __name((prefix) => {
            const g = this.get("global");
            this[g ? "globalPrefix" : "localPrefix"] = prefix;
          }, "set"),
          get: /* @__PURE__ */ __name(() => {
            const g = this.get("global");
            return g ? this.globalPrefix : this.localPrefix;
          }, "get")
        });
        Object.defineProperty(this, "globalPrefix", {
          enumerable: true,
          set: /* @__PURE__ */ __name((prefix) => {
            this.set("prefix", prefix);
          }, "set"),
          get: /* @__PURE__ */ __name(() => {
            return path108.resolve(this.get("prefix"));
          }, "get")
        });
        let p;
        Object.defineProperty(this, "localPrefix", {
          enumerable: true,
          set: /* @__PURE__ */ __name((prefix) => {
            p = prefix;
          }, "set"),
          get: /* @__PURE__ */ __name(() => {
            return p;
          }, "get")
        });
        if (Object.prototype.hasOwnProperty.call(cli, "prefix")) {
          p = path108.resolve(cli.prefix);
        } else {
          try {
            const prefix = util4.findPrefix(process.cwd());
            p = prefix;
          } catch (error) {
            throw error;
          }
        }
        return p;
      }
      // https://github.com/npm/cli/blob/latest/lib/config/load-cafile.js
      loadCAFile(file) {
        if (!file) {
          return;
        }
        const ca = readCAFileSync(file);
        if (ca) {
          this.set("ca", ca);
        }
      }
      // https://github.com/npm/cli/blob/latest/lib/config/set-user.js
      loadUser() {
        const defConf = this.root;
        if (this.get("global")) {
          return;
        }
        if (process.env.SUDO_UID) {
          defConf.user = Number(process.env.SUDO_UID);
          return;
        }
        const prefix = path108.resolve(this.get("prefix"));
        try {
          const stats = fs95.statSync(prefix);
          defConf.user = stats.uid;
        } catch (error) {
          if (error.code === "ENOENT") {
            return;
          }
          throw error;
        }
      }
    };
    function deserializeEnvVal(envKey, envValue) {
      function deserializeList(envValue2) {
        const npmConfigSep = "\n\n";
        if (envValue2.indexOf(npmConfigSep)) {
          return envValue2.split(npmConfigSep);
        }
        return envValue2.split(",");
      }
      __name(deserializeList, "deserializeList");
      switch (envKey) {
        case "hoist-pattern":
        case "public-hoist-pattern":
          return deserializeList(envValue);
      }
      return envValue;
    }
    __name(deserializeEnvVal, "deserializeEnvVal");
    module2.exports = Conf;
  }
});

// node_modules/@pnpm/npm-conf/lib/defaults.js
var require_defaults3 = __commonJS({
  "node_modules/@pnpm/npm-conf/lib/defaults.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var os43 = __require("os");
    var path108 = __require("path");
    var temp = os43.tmpdir();
    var uidOrPid = process.getuid ? process.getuid() : process.pid;
    var hasUnicode = /* @__PURE__ */ __name(() => true, "hasUnicode");
    var isWindows8 = process.platform === "win32";
    var osenv = {
      editor: /* @__PURE__ */ __name(() => process.env.EDITOR || process.env.VISUAL || (isWindows8 ? "notepad.exe" : "vi"), "editor"),
      shell: /* @__PURE__ */ __name(() => isWindows8 ? process.env.COMSPEC || "cmd.exe" : process.env.SHELL || "/bin/bash", "shell")
    };
    var umask = {
      fromString: /* @__PURE__ */ __name(() => process.umask(), "fromString")
    };
    var home = os43.homedir();
    if (home) {
      process.env.HOME = home;
    } else {
      home = path108.resolve(temp, "npm-" + uidOrPid);
    }
    var cacheExtra = process.platform === "win32" ? "npm-cache" : ".npm";
    var cacheRoot = process.platform === "win32" && process.env.APPDATA || home;
    var cache5 = path108.resolve(cacheRoot, cacheExtra);
    var defaults3;
    var globalPrefix;
    Object.defineProperty(exports2, "defaults", {
      get: /* @__PURE__ */ __name(function() {
        if (defaults3) return defaults3;
        if (process.env.PREFIX) {
          globalPrefix = process.env.PREFIX;
        } else if (process.platform === "win32") {
          globalPrefix = path108.dirname(process.execPath);
        } else {
          globalPrefix = path108.dirname(path108.dirname(process.execPath));
          if (process.env.DESTDIR) {
            globalPrefix = path108.join(process.env.DESTDIR, globalPrefix);
          }
        }
        defaults3 = {
          access: null,
          "allow-same-version": false,
          "always-auth": false,
          also: null,
          audit: true,
          "auth-type": "legacy",
          "bin-links": true,
          browser: null,
          ca: null,
          cafile: null,
          cache: cache5,
          "cache-lock-stale": 6e4,
          "cache-lock-retries": 10,
          "cache-lock-wait": 1e4,
          "cache-max": Infinity,
          "cache-min": 10,
          cert: null,
          cidr: null,
          color: process.env.NO_COLOR == null,
          depth: Infinity,
          description: true,
          dev: false,
          "dry-run": false,
          editor: osenv.editor(),
          "engine-strict": false,
          force: false,
          "fetch-retries": 2,
          "fetch-retry-factor": 10,
          "fetch-retry-mintimeout": 1e4,
          "fetch-retry-maxtimeout": 6e4,
          git: "git",
          "git-tag-version": true,
          "commit-hooks": true,
          global: false,
          globalconfig: path108.resolve(globalPrefix, "etc", "npmrc"),
          "global-style": false,
          group: process.platform === "win32" ? 0 : process.env.SUDO_GID || process.getgid && process.getgid(),
          "ham-it-up": false,
          heading: "npm",
          "if-present": false,
          "ignore-prepublish": false,
          "ignore-scripts": false,
          "init-module": path108.resolve(home, ".npm-init.js"),
          "init-author-name": "",
          "init-author-email": "",
          "init-author-url": "",
          "init-version": "1.0.0",
          "init-license": "ISC",
          json: false,
          key: null,
          "legacy-bundling": false,
          link: false,
          "local-address": void 0,
          loglevel: "notice",
          logstream: process.stderr,
          "logs-max": 10,
          long: false,
          maxsockets: 50,
          message: "%s",
          "metrics-registry": null,
          "node-options": null,
          // We remove node-version to fix the issue described here: https://github.com/pnpm/pnpm/issues/4203#issuecomment-1133872769
          "offline": false,
          "onload-script": false,
          only: null,
          optional: true,
          otp: null,
          "package-lock": true,
          "package-lock-only": false,
          parseable: false,
          "prefer-offline": false,
          "prefer-online": false,
          prefix: globalPrefix,
          production: process.env.NODE_ENV === "production",
          "progress": !process.env.TRAVIS && !process.env.CI,
          provenance: false,
          proxy: null,
          "https-proxy": null,
          "no-proxy": null,
          "user-agent": "npm/{npm-version} node/{node-version} {platform} {arch}",
          "read-only": false,
          "rebuild-bundle": true,
          registry: "https://registry.npmjs.org/",
          rollback: true,
          save: true,
          "save-bundle": false,
          "save-dev": false,
          "save-exact": false,
          "save-optional": false,
          "save-prefix": "^",
          "save-prod": false,
          scope: "",
          "script-shell": null,
          "scripts-prepend-node-path": "warn-only",
          searchopts: "",
          searchexclude: null,
          searchlimit: 20,
          searchstaleness: 15 * 60,
          "send-metrics": false,
          shell: osenv.shell(),
          shrinkwrap: true,
          "sign-git-tag": false,
          "sso-poll-frequency": 500,
          "sso-type": "oauth",
          "strict-ssl": true,
          tag: "latest",
          "tag-version-prefix": "v",
          timing: false,
          tmp: temp,
          unicode: hasUnicode(),
          "unsafe-perm": process.platform === "win32" || process.platform === "cygwin" || !(process.getuid && process.setuid && process.getgid && process.setgid) || process.getuid() !== 0,
          usage: false,
          user: process.platform === "win32" ? 0 : "nobody",
          userconfig: path108.resolve(home, ".npmrc"),
          umask: process.umask ? process.umask() : umask.fromString("022"),
          version: false,
          versions: false,
          viewer: process.platform === "win32" ? "browser" : "man",
          _exit: true
        };
        return defaults3;
      }, "get")
    });
  }
});

// node_modules/@pnpm/npm-conf/index.js
var require_npm_conf = __commonJS({
  "node_modules/@pnpm/npm-conf/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var path108 = __require("path");
    var Conf = require_conf();
    var _defaults2 = require_defaults3();
    module2.exports = (opts, types3, defaults3) => {
      const conf = new Conf(Object.assign({}, _defaults2.defaults, defaults3), types3);
      conf.add(Object.assign({}, opts), "cli");
      const warnings = [];
      let failedToLoadBuiltInConfig = false;
      if (__require.resolve.paths) {
        const paths = __require.resolve.paths("npm");
        let npmPath;
        try {
          npmPath = __require.resolve("npm", { paths: paths.slice(-1) });
        } catch (error) {
          failedToLoadBuiltInConfig = true;
        }
        if (npmPath) {
          warnings.push(conf.addFile(path108.resolve(path108.dirname(npmPath), "..", "npmrc"), "builtin"));
        }
      }
      conf.addEnv();
      conf.loadPrefix();
      const projectConf = path108.resolve(conf.localPrefix, ".npmrc");
      const userConf = conf.get("userconfig");
      if (!conf.get("global") && projectConf !== userConf) {
        warnings.push(conf.addFile(projectConf, "project"));
      } else {
        conf.add({}, "project");
      }
      if (conf.get("workspace-prefix") && conf.get("workspace-prefix") !== projectConf) {
        const workspaceConf = path108.resolve(conf.get("workspace-prefix"), ".npmrc");
        warnings.push(conf.addFile(workspaceConf, "workspace"));
      }
      warnings.push(conf.addFile(conf.get("userconfig"), "user"));
      if (conf.get("prefix")) {
        const etc = path108.resolve(conf.get("prefix"), "etc");
        conf.root.globalconfig = path108.resolve(etc, "npmrc");
        conf.root.globalignorefile = path108.resolve(etc, "npmignore");
      }
      warnings.push(conf.addFile(conf.get("globalconfig"), "global"));
      conf.loadUser();
      const caFile = conf.get("cafile");
      if (caFile) {
        conf.loadCAFile(caFile);
      }
      return {
        config: conf,
        warnings: warnings.filter(Boolean),
        failedToLoadBuiltInConfig
      };
    };
    Object.defineProperty(module2.exports, "defaults", {
      get() {
        return _defaults2.defaults;
      },
      enumerable: true
    });
  }
});

// node_modules/registry-auth-token/index.js
var require_registry_auth_token = __commonJS({
  "node_modules/registry-auth-token/index.js"(exports2, module2) {
    init_esbuild_shims();
    var npmConf = require_npm_conf();
    var tokenKey = ":_authToken";
    var legacyTokenKey = ":_auth";
    var userKey = ":username";
    var passwordKey = ":_password";
    module2.exports = /* @__PURE__ */ __name(function getRegistryAuthToken() {
      let checkUrl;
      let options2;
      if (arguments.length >= 2) {
        checkUrl = arguments[0];
        options2 = Object.assign({}, arguments[1]);
      } else if (typeof arguments[0] === "string") {
        checkUrl = arguments[0];
      } else {
        options2 = Object.assign({}, arguments[0]);
      }
      options2 = options2 || {};
      const providedNpmrc = options2.npmrc;
      options2.npmrc = (options2.npmrc ? {
        config: {
          get: /* @__PURE__ */ __name((key) => providedNpmrc[key], "get")
        }
      } : npmConf()).config;
      checkUrl = checkUrl || options2.npmrc.get("registry") || npmConf.defaults.registry;
      return getRegistryAuthInfo(checkUrl, options2) || getLegacyAuthInfo(options2.npmrc);
    }, "getRegistryAuthToken");
    function urlResolve(from, to) {
      const resolvedUrl = new URL(to, new URL(from.startsWith("//") ? `./${from}` : from, "resolve://"));
      if (resolvedUrl.protocol === "resolve:") {
        const { pathname, search, hash } = resolvedUrl;
        return pathname + search + hash;
      }
      return resolvedUrl.toString();
    }
    __name(urlResolve, "urlResolve");
    function getRegistryAuthInfo(checkUrl, options2) {
      let parsed = checkUrl instanceof URL ? checkUrl : new URL(checkUrl.startsWith("//") ? `http:${checkUrl}` : checkUrl);
      let pathname;
      while (pathname !== "/" && parsed.pathname !== pathname) {
        pathname = parsed.pathname || "/";
        const regUrl = "//" + parsed.host + pathname.replace(/\/$/, "");
        const authInfo = getAuthInfoForUrl(regUrl, options2.npmrc);
        if (authInfo) {
          return authInfo;
        }
        if (!options2.recursive) {
          return /\/$/.test(checkUrl) ? void 0 : getRegistryAuthInfo(new URL("./", parsed), options2);
        }
        parsed.pathname = urlResolve(normalizePath(pathname), "..") || "/";
      }
      return void 0;
    }
    __name(getRegistryAuthInfo, "getRegistryAuthInfo");
    function getLegacyAuthInfo(npmrc) {
      if (!npmrc.get("_auth")) {
        return void 0;
      }
      const token2 = replaceEnvironmentVariable(npmrc.get("_auth"));
      return { token: token2, type: "Basic" };
    }
    __name(getLegacyAuthInfo, "getLegacyAuthInfo");
    function normalizePath(path108) {
      return path108[path108.length - 1] === "/" ? path108 : path108 + "/";
    }
    __name(normalizePath, "normalizePath");
    function getAuthInfoForUrl(regUrl, npmrc) {
      const bearerAuth = getBearerToken(npmrc.get(regUrl + tokenKey) || npmrc.get(regUrl + "/" + tokenKey));
      if (bearerAuth) {
        return bearerAuth;
      }
      const username = npmrc.get(regUrl + userKey) || npmrc.get(regUrl + "/" + userKey);
      const password = npmrc.get(regUrl + passwordKey) || npmrc.get(regUrl + "/" + passwordKey);
      const basicAuth = getTokenForUsernameAndPassword(username, password);
      if (basicAuth) {
        return basicAuth;
      }
      const basicAuthWithToken = getLegacyAuthToken(npmrc.get(regUrl + legacyTokenKey) || npmrc.get(regUrl + "/" + legacyTokenKey));
      if (basicAuthWithToken) {
        return basicAuthWithToken;
      }
      return void 0;
    }
    __name(getAuthInfoForUrl, "getAuthInfoForUrl");
    function replaceEnvironmentVariable(token2) {
      return token2.replace(/^\$\{?([^}]*)\}?$/, function(fullMatch, envVar) {
        return process.env[envVar];
      });
    }
    __name(replaceEnvironmentVariable, "replaceEnvironmentVariable");
    function getBearerToken(tok) {
      if (!tok) {
        return void 0;
      }
      const token2 = replaceEnvironmentVariable(tok);
      return { token: token2, type: "Bearer" };
    }
    __name(getBearerToken, "getBearerToken");
    function getTokenForUsernameAndPassword(username, password) {
      if (!username || !password) {
        return void 0;
      }
      const pass = Buffer.from(replaceEnvironmentVariable(password), "base64").toString("utf8");
      const token2 = Buffer.from(username + ":" + pass, "utf8").toString("base64");
      return {
        token: token2,
        type: "Basic",
        password: pass,
        username
      };
    }
    __name(getTokenForUsernameAndPassword, "getTokenForUsernameAndPassword");
    function getLegacyAuthToken(tok) {
      if (!tok) {
        return void 0;
      }
      const token2 = replaceEnvironmentVariable(tok);
      return { token: token2, type: "Basic" };
    }
    __name(getLegacyAuthToken, "getLegacyAuthToken");
  }
});

// node_modules/semver/functions/inc.js
var require_inc = __commonJS({
  "node_modules/semver/functions/inc.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var SemVer = require_semver2();
    var inc = /* @__PURE__ */ __name((version2, release3, options2, identifier2, identifierBase) => {
      if (typeof options2 === "string") {
        identifierBase = identifier2;
        identifier2 = options2;
        options2 = void 0;
      }
      try {
        return new SemVer(
          version2 instanceof SemVer ? version2.version : version2,
          options2
        ).inc(release3, identifier2, identifierBase).version;
      } catch (er) {
        return null;
      }
    }, "inc");
    module2.exports = inc;
  }
});

// node_modules/semver/functions/major.js
var require_major = __commonJS({
  "node_modules/semver/functions/major.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var SemVer = require_semver2();
    var major2 = /* @__PURE__ */ __name((a, loose) => new SemVer(a, loose).major, "major");
    module2.exports = major2;
  }
});

// node_modules/semver/functions/minor.js
var require_minor = __commonJS({
  "node_modules/semver/functions/minor.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var SemVer = require_semver2();
    var minor = /* @__PURE__ */ __name((a, loose) => new SemVer(a, loose).minor, "minor");
    module2.exports = minor;
  }
});

// node_modules/semver/functions/patch.js
var require_patch = __commonJS({
  "node_modules/semver/functions/patch.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var SemVer = require_semver2();
    var patch = /* @__PURE__ */ __name((a, loose) => new SemVer(a, loose).patch, "patch");
    module2.exports = patch;
  }
});

// node_modules/semver/functions/prerelease.js
var require_prerelease = __commonJS({
  "node_modules/semver/functions/prerelease.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var parse12 = require_parse8();
    var prerelease = /* @__PURE__ */ __name((version2, options2) => {
      const parsed = parse12(version2, options2);
      return parsed && parsed.prerelease.length ? parsed.prerelease : null;
    }, "prerelease");
    module2.exports = prerelease;
  }
});

// node_modules/semver/functions/rcompare.js
var require_rcompare = __commonJS({
  "node_modules/semver/functions/rcompare.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var compare = require_compare();
    var rcompare = /* @__PURE__ */ __name((a, b, loose) => compare(b, a, loose), "rcompare");
    module2.exports = rcompare;
  }
});

// node_modules/semver/functions/compare-loose.js
var require_compare_loose = __commonJS({
  "node_modules/semver/functions/compare-loose.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var compare = require_compare();
    var compareLoose = /* @__PURE__ */ __name((a, b) => compare(a, b, true), "compareLoose");
    module2.exports = compareLoose;
  }
});

// node_modules/semver/functions/compare-build.js
var require_compare_build = __commonJS({
  "node_modules/semver/functions/compare-build.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var SemVer = require_semver2();
    var compareBuild = /* @__PURE__ */ __name((a, b, loose) => {
      const versionA = new SemVer(a, loose);
      const versionB = new SemVer(b, loose);
      return versionA.compare(versionB) || versionA.compareBuild(versionB);
    }, "compareBuild");
    module2.exports = compareBuild;
  }
});

// node_modules/semver/functions/sort.js
var require_sort = __commonJS({
  "node_modules/semver/functions/sort.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var compareBuild = require_compare_build();
    var sort = /* @__PURE__ */ __name((list3, loose) => list3.sort((a, b) => compareBuild(a, b, loose)), "sort");
    module2.exports = sort;
  }
});

// node_modules/semver/functions/rsort.js
var require_rsort = __commonJS({
  "node_modules/semver/functions/rsort.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var compareBuild = require_compare_build();
    var rsort = /* @__PURE__ */ __name((list3, loose) => list3.sort((a, b) => compareBuild(b, a, loose)), "rsort");
    module2.exports = rsort;
  }
});

// node_modules/semver/functions/lt.js
var require_lt = __commonJS({
  "node_modules/semver/functions/lt.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var compare = require_compare();
    var lt = /* @__PURE__ */ __name((a, b, loose) => compare(a, b, loose) < 0, "lt");
    module2.exports = lt;
  }
});

// node_modules/semver/functions/eq.js
var require_eq = __commonJS({
  "node_modules/semver/functions/eq.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var compare = require_compare();
    var eq = /* @__PURE__ */ __name((a, b, loose) => compare(a, b, loose) === 0, "eq");
    module2.exports = eq;
  }
});

// node_modules/semver/functions/neq.js
var require_neq = __commonJS({
  "node_modules/semver/functions/neq.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var compare = require_compare();
    var neq = /* @__PURE__ */ __name((a, b, loose) => compare(a, b, loose) !== 0, "neq");
    module2.exports = neq;
  }
});

// node_modules/semver/functions/gte.js
var require_gte = __commonJS({
  "node_modules/semver/functions/gte.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var compare = require_compare();
    var gte = /* @__PURE__ */ __name((a, b, loose) => compare(a, b, loose) >= 0, "gte");
    module2.exports = gte;
  }
});

// node_modules/semver/functions/lte.js
var require_lte = __commonJS({
  "node_modules/semver/functions/lte.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var compare = require_compare();
    var lte = /* @__PURE__ */ __name((a, b, loose) => compare(a, b, loose) <= 0, "lte");
    module2.exports = lte;
  }
});

// node_modules/semver/functions/cmp.js
var require_cmp = __commonJS({
  "node_modules/semver/functions/cmp.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var eq = require_eq();
    var neq = require_neq();
    var gt = require_gt();
    var gte = require_gte();
    var lt = require_lt();
    var lte = require_lte();
    var cmp = /* @__PURE__ */ __name((a, op, b, loose) => {
      switch (op) {
        case "===":
          if (typeof a === "object") {
            a = a.version;
          }
          if (typeof b === "object") {
            b = b.version;
          }
          return a === b;
        case "!==":
          if (typeof a === "object") {
            a = a.version;
          }
          if (typeof b === "object") {
            b = b.version;
          }
          return a !== b;
        case "":
        case "=":
        case "==":
          return eq(a, b, loose);
        case "!=":
          return neq(a, b, loose);
        case ">":
          return gt(a, b, loose);
        case ">=":
          return gte(a, b, loose);
        case "<":
          return lt(a, b, loose);
        case "<=":
          return lte(a, b, loose);
        default:
          throw new TypeError(`Invalid operator: ${op}`);
      }
    }, "cmp");
    module2.exports = cmp;
  }
});

// node_modules/semver/functions/coerce.js
var require_coerce = __commonJS({
  "node_modules/semver/functions/coerce.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var SemVer = require_semver2();
    var parse12 = require_parse8();
    var { safeRe: re2, t: t2 } = require_re();
    var coerce2 = /* @__PURE__ */ __name((version2, options2) => {
      if (version2 instanceof SemVer) {
        return version2;
      }
      if (typeof version2 === "number") {
        version2 = String(version2);
      }
      if (typeof version2 !== "string") {
        return null;
      }
      options2 = options2 || {};
      let match2 = null;
      if (!options2.rtl) {
        match2 = version2.match(options2.includePrerelease ? re2[t2.COERCEFULL] : re2[t2.COERCE]);
      } else {
        const coerceRtlRegex = options2.includePrerelease ? re2[t2.COERCERTLFULL] : re2[t2.COERCERTL];
        let next;
        while ((next = coerceRtlRegex.exec(version2)) && (!match2 || match2.index + match2[0].length !== version2.length)) {
          if (!match2 || next.index + next[0].length !== match2.index + match2[0].length) {
            match2 = next;
          }
          coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
        }
        coerceRtlRegex.lastIndex = -1;
      }
      if (match2 === null) {
        return null;
      }
      const major2 = match2[2];
      const minor = match2[3] || "0";
      const patch = match2[4] || "0";
      const prerelease = options2.includePrerelease && match2[5] ? `-${match2[5]}` : "";
      const build = options2.includePrerelease && match2[6] ? `+${match2[6]}` : "";
      return parse12(`${major2}.${minor}.${patch}${prerelease}${build}`, options2);
    }, "coerce");
    module2.exports = coerce2;
  }
});

// node_modules/semver/internal/lrucache.js
var require_lrucache = __commonJS({
  "node_modules/semver/internal/lrucache.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var LRUCache2 = class {
      static {
        __name(this, "LRUCache");
      }
      constructor() {
        this.max = 1e3;
        this.map = /* @__PURE__ */ new Map();
      }
      get(key) {
        const value = this.map.get(key);
        if (value === void 0) {
          return void 0;
        } else {
          this.map.delete(key);
          this.map.set(key, value);
          return value;
        }
      }
      delete(key) {
        return this.map.delete(key);
      }
      set(key, value) {
        const deleted = this.delete(key);
        if (!deleted && value !== void 0) {
          if (this.map.size >= this.max) {
            const firstKey = this.map.keys().next().value;
            this.delete(firstKey);
          }
          this.map.set(key, value);
        }
        return this;
      }
    };
    module2.exports = LRUCache2;
  }
});

// node_modules/semver/classes/range.js
var require_range = __commonJS({
  "node_modules/semver/classes/range.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var SPACE_CHARACTERS = /\s+/g;
    var Range = class _Range {
      static {
        __name(this, "Range");
      }
      constructor(range, options2) {
        options2 = parseOptions(options2);
        if (range instanceof _Range) {
          if (range.loose === !!options2.loose && range.includePrerelease === !!options2.includePrerelease) {
            return range;
          } else {
            return new _Range(range.raw, options2);
          }
        }
        if (range instanceof Comparator) {
          this.raw = range.value;
          this.set = [[range]];
          this.formatted = void 0;
          return this;
        }
        this.options = options2;
        this.loose = !!options2.loose;
        this.includePrerelease = !!options2.includePrerelease;
        this.raw = range.trim().replace(SPACE_CHARACTERS, " ");
        this.set = this.raw.split("||").map((r3) => this.parseRange(r3.trim())).filter((c3) => c3.length);
        if (!this.set.length) {
          throw new TypeError(`Invalid SemVer Range: ${this.raw}`);
        }
        if (this.set.length > 1) {
          const first2 = this.set[0];
          this.set = this.set.filter((c3) => !isNullSet(c3[0]));
          if (this.set.length === 0) {
            this.set = [first2];
          } else if (this.set.length > 1) {
            for (const c3 of this.set) {
              if (c3.length === 1 && isAny(c3[0])) {
                this.set = [c3];
                break;
              }
            }
          }
        }
        this.formatted = void 0;
      }
      get range() {
        if (this.formatted === void 0) {
          this.formatted = "";
          for (let i = 0; i < this.set.length; i++) {
            if (i > 0) {
              this.formatted += "||";
            }
            const comps = this.set[i];
            for (let k = 0; k < comps.length; k++) {
              if (k > 0) {
                this.formatted += " ";
              }
              this.formatted += comps[k].toString().trim();
            }
          }
        }
        return this.formatted;
      }
      format() {
        return this.range;
      }
      toString() {
        return this.range;
      }
      parseRange(range) {
        const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
        const memoKey = memoOpts + ":" + range;
        const cached = cache5.get(memoKey);
        if (cached) {
          return cached;
        }
        const loose = this.options.loose;
        const hr2 = loose ? re2[t2.HYPHENRANGELOOSE] : re2[t2.HYPHENRANGE];
        range = range.replace(hr2, hyphenReplace(this.options.includePrerelease));
        debug2("hyphen replace", range);
        range = range.replace(re2[t2.COMPARATORTRIM], comparatorTrimReplace);
        debug2("comparator trim", range);
        range = range.replace(re2[t2.TILDETRIM], tildeTrimReplace);
        debug2("tilde trim", range);
        range = range.replace(re2[t2.CARETTRIM], caretTrimReplace);
        debug2("caret trim", range);
        let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));
        if (loose) {
          rangeList = rangeList.filter((comp) => {
            debug2("loose invalid filter", comp, this.options);
            return !!comp.match(re2[t2.COMPARATORLOOSE]);
          });
        }
        debug2("range list", rangeList);
        const rangeMap = /* @__PURE__ */ new Map();
        const comparators = rangeList.map((comp) => new Comparator(comp, this.options));
        for (const comp of comparators) {
          if (isNullSet(comp)) {
            return [comp];
          }
          rangeMap.set(comp.value, comp);
        }
        if (rangeMap.size > 1 && rangeMap.has("")) {
          rangeMap.delete("");
        }
        const result = [...rangeMap.values()];
        cache5.set(memoKey, result);
        return result;
      }
      intersects(range, options2) {
        if (!(range instanceof _Range)) {
          throw new TypeError("a Range is required");
        }
        return this.set.some((thisComparators) => {
          return isSatisfiable(thisComparators, options2) && range.set.some((rangeComparators) => {
            return isSatisfiable(rangeComparators, options2) && thisComparators.every((thisComparator) => {
              return rangeComparators.every((rangeComparator) => {
                return thisComparator.intersects(rangeComparator, options2);
              });
            });
          });
        });
      }
      // if ANY of the sets match ALL of its comparators, then pass
      test(version2) {
        if (!version2) {
          return false;
        }
        if (typeof version2 === "string") {
          try {
            version2 = new SemVer(version2, this.options);
          } catch (er) {
            return false;
          }
        }
        for (let i = 0; i < this.set.length; i++) {
          if (testSet(this.set[i], version2, this.options)) {
            return true;
          }
        }
        return false;
      }
    };
    module2.exports = Range;
    var LRU = require_lrucache();
    var cache5 = new LRU();
    var parseOptions = require_parse_options();
    var Comparator = require_comparator();
    var debug2 = require_debug();
    var SemVer = require_semver2();
    var {
      safeRe: re2,
      t: t2,
      comparatorTrimReplace,
      tildeTrimReplace,
      caretTrimReplace
    } = require_re();
    var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants12();
    var isNullSet = /* @__PURE__ */ __name((c3) => c3.value === "<0.0.0-0", "isNullSet");
    var isAny = /* @__PURE__ */ __name((c3) => c3.value === "", "isAny");
    var isSatisfiable = /* @__PURE__ */ __name((comparators, options2) => {
      let result = true;
      const remainingComparators = comparators.slice();
      let testComparator = remainingComparators.pop();
      while (result && remainingComparators.length) {
        result = remainingComparators.every((otherComparator) => {
          return testComparator.intersects(otherComparator, options2);
        });
        testComparator = remainingComparators.pop();
      }
      return result;
    }, "isSatisfiable");
    var parseComparator = /* @__PURE__ */ __name((comp, options2) => {
      debug2("comp", comp, options2);
      comp = replaceCarets(comp, options2);
      debug2("caret", comp);
      comp = replaceTildes(comp, options2);
      debug2("tildes", comp);
      comp = replaceXRanges(comp, options2);
      debug2("xrange", comp);
      comp = replaceStars(comp, options2);
      debug2("stars", comp);
      return comp;
    }, "parseComparator");
    var isX = /* @__PURE__ */ __name((id) => !id || id.toLowerCase() === "x" || id === "*", "isX");
    var replaceTildes = /* @__PURE__ */ __name((comp, options2) => {
      return comp.trim().split(/\s+/).map((c3) => replaceTilde(c3, options2)).join(" ");
    }, "replaceTildes");
    var replaceTilde = /* @__PURE__ */ __name((comp, options2) => {
      const r3 = options2.loose ? re2[t2.TILDELOOSE] : re2[t2.TILDE];
      return comp.replace(r3, (_, M, m, p, pr) => {
        debug2("tilde", comp, _, M, m, p, pr);
        let ret;
        if (isX(M)) {
          ret = "";
        } else if (isX(m)) {
          ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
        } else if (isX(p)) {
          ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
        } else if (pr) {
          debug2("replaceTilde pr", pr);
          ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
        } else {
          ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
        }
        debug2("tilde return", ret);
        return ret;
      });
    }, "replaceTilde");
    var replaceCarets = /* @__PURE__ */ __name((comp, options2) => {
      return comp.trim().split(/\s+/).map((c3) => replaceCaret(c3, options2)).join(" ");
    }, "replaceCarets");
    var replaceCaret = /* @__PURE__ */ __name((comp, options2) => {
      debug2("caret", comp, options2);
      const r3 = options2.loose ? re2[t2.CARETLOOSE] : re2[t2.CARET];
      const z = options2.includePrerelease ? "-0" : "";
      return comp.replace(r3, (_, M, m, p, pr) => {
        debug2("caret", comp, _, M, m, p, pr);
        let ret;
        if (isX(M)) {
          ret = "";
        } else if (isX(m)) {
          ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
        } else if (isX(p)) {
          if (M === "0") {
            ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
          } else {
            ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
          }
        } else if (pr) {
          debug2("replaceCaret pr", pr);
          if (M === "0") {
            if (m === "0") {
              ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;
            } else {
              ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
            }
          } else {
            ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;
          }
        } else {
          debug2("no pr");
          if (M === "0") {
            if (m === "0") {
              ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`;
            } else {
              ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`;
            }
          } else {
            ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;
          }
        }
        debug2("caret return", ret);
        return ret;
      });
    }, "replaceCaret");
    var replaceXRanges = /* @__PURE__ */ __name((comp, options2) => {
      debug2("replaceXRanges", comp, options2);
      return comp.split(/\s+/).map((c3) => replaceXRange(c3, options2)).join(" ");
    }, "replaceXRanges");
    var replaceXRange = /* @__PURE__ */ __name((comp, options2) => {
      comp = comp.trim();
      const r3 = options2.loose ? re2[t2.XRANGELOOSE] : re2[t2.XRANGE];
      return comp.replace(r3, (ret, gtlt, M, m, p, pr) => {
        debug2("xRange", comp, ret, gtlt, M, m, p, pr);
        const xM = isX(M);
        const xm = xM || isX(m);
        const xp = xm || isX(p);
        const anyX = xp;
        if (gtlt === "=" && anyX) {
          gtlt = "";
        }
        pr = options2.includePrerelease ? "-0" : "";
        if (xM) {
          if (gtlt === ">" || gtlt === "<") {
            ret = "<0.0.0-0";
          } else {
            ret = "*";
          }
        } else if (gtlt && anyX) {
          if (xm) {
            m = 0;
          }
          p = 0;
          if (gtlt === ">") {
            gtlt = ">=";
            if (xm) {
              M = +M + 1;
              m = 0;
              p = 0;
            } else {
              m = +m + 1;
              p = 0;
            }
          } else if (gtlt === "<=") {
            gtlt = "<";
            if (xm) {
              M = +M + 1;
            } else {
              m = +m + 1;
            }
          }
          if (gtlt === "<") {
            pr = "-0";
          }
          ret = `${gtlt + M}.${m}.${p}${pr}`;
        } else if (xm) {
          ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
        } else if (xp) {
          ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
        }
        debug2("xRange return", ret);
        return ret;
      });
    }, "replaceXRange");
    var replaceStars = /* @__PURE__ */ __name((comp, options2) => {
      debug2("replaceStars", comp, options2);
      return comp.trim().replace(re2[t2.STAR], "");
    }, "replaceStars");
    var replaceGTE0 = /* @__PURE__ */ __name((comp, options2) => {
      debug2("replaceGTE0", comp, options2);
      return comp.trim().replace(re2[options2.includePrerelease ? t2.GTE0PRE : t2.GTE0], "");
    }, "replaceGTE0");
    var hyphenReplace = /* @__PURE__ */ __name((incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
      if (isX(fM)) {
        from = "";
      } else if (isX(fm)) {
        from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
      } else if (isX(fp)) {
        from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
      } else if (fpr) {
        from = `>=${from}`;
      } else {
        from = `>=${from}${incPr ? "-0" : ""}`;
      }
      if (isX(tM)) {
        to = "";
      } else if (isX(tm)) {
        to = `<${+tM + 1}.0.0-0`;
      } else if (isX(tp)) {
        to = `<${tM}.${+tm + 1}.0-0`;
      } else if (tpr) {
        to = `<=${tM}.${tm}.${tp}-${tpr}`;
      } else if (incPr) {
        to = `<${tM}.${tm}.${+tp + 1}-0`;
      } else {
        to = `<=${to}`;
      }
      return `${from} ${to}`.trim();
    }, "hyphenReplace");
    var testSet = /* @__PURE__ */ __name((set, version2, options2) => {
      for (let i = 0; i < set.length; i++) {
        if (!set[i].test(version2)) {
          return false;
        }
      }
      if (version2.prerelease.length && !options2.includePrerelease) {
        for (let i = 0; i < set.length; i++) {
          debug2(set[i].semver);
          if (set[i].semver === Comparator.ANY) {
            continue;
          }
          if (set[i].semver.prerelease.length > 0) {
            const allowed = set[i].semver;
            if (allowed.major === version2.major && allowed.minor === version2.minor && allowed.patch === version2.patch) {
              return true;
            }
          }
        }
        return false;
      }
      return true;
    }, "testSet");
  }
});

// node_modules/semver/classes/comparator.js
var require_comparator = __commonJS({
  "node_modules/semver/classes/comparator.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var ANY = Symbol("SemVer ANY");
    var Comparator = class _Comparator {
      static {
        __name(this, "Comparator");
      }
      static get ANY() {
        return ANY;
      }
      constructor(comp, options2) {
        options2 = parseOptions(options2);
        if (comp instanceof _Comparator) {
          if (comp.loose === !!options2.loose) {
            return comp;
          } else {
            comp = comp.value;
          }
        }
        comp = comp.trim().split(/\s+/).join(" ");
        debug2("comparator", comp, options2);
        this.options = options2;
        this.loose = !!options2.loose;
        this.parse(comp);
        if (this.semver === ANY) {
          this.value = "";
        } else {
          this.value = this.operator + this.semver.version;
        }
        debug2("comp", this);
      }
      parse(comp) {
        const r3 = this.options.loose ? re2[t2.COMPARATORLOOSE] : re2[t2.COMPARATOR];
        const m = comp.match(r3);
        if (!m) {
          throw new TypeError(`Invalid comparator: ${comp}`);
        }
        this.operator = m[1] !== void 0 ? m[1] : "";
        if (this.operator === "=") {
          this.operator = "";
        }
        if (!m[2]) {
          this.semver = ANY;
        } else {
          this.semver = new SemVer(m[2], this.options.loose);
        }
      }
      toString() {
        return this.value;
      }
      test(version2) {
        debug2("Comparator.test", version2, this.options.loose);
        if (this.semver === ANY || version2 === ANY) {
          return true;
        }
        if (typeof version2 === "string") {
          try {
            version2 = new SemVer(version2, this.options);
          } catch (er) {
            return false;
          }
        }
        return cmp(version2, this.operator, this.semver, this.options);
      }
      intersects(comp, options2) {
        if (!(comp instanceof _Comparator)) {
          throw new TypeError("a Comparator is required");
        }
        if (this.operator === "") {
          if (this.value === "") {
            return true;
          }
          return new Range(comp.value, options2).test(this.value);
        } else if (comp.operator === "") {
          if (comp.value === "") {
            return true;
          }
          return new Range(this.value, options2).test(comp.semver);
        }
        options2 = parseOptions(options2);
        if (options2.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) {
          return false;
        }
        if (!options2.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) {
          return false;
        }
        if (this.operator.startsWith(">") && comp.operator.startsWith(">")) {
          return true;
        }
        if (this.operator.startsWith("<") && comp.operator.startsWith("<")) {
          return true;
        }
        if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
          return true;
        }
        if (cmp(this.semver, "<", comp.semver, options2) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
          return true;
        }
        if (cmp(this.semver, ">", comp.semver, options2) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
          return true;
        }
        return false;
      }
    };
    module2.exports = Comparator;
    var parseOptions = require_parse_options();
    var { safeRe: re2, t: t2 } = require_re();
    var cmp = require_cmp();
    var debug2 = require_debug();
    var SemVer = require_semver2();
    var Range = require_range();
  }
});

// node_modules/semver/functions/satisfies.js
var require_satisfies = __commonJS({
  "node_modules/semver/functions/satisfies.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Range = require_range();
    var satisfies = /* @__PURE__ */ __name((version2, range, options2) => {
      try {
        range = new Range(range, options2);
      } catch (er) {
        return false;
      }
      return range.test(version2);
    }, "satisfies");
    module2.exports = satisfies;
  }
});

// node_modules/semver/ranges/to-comparators.js
var require_to_comparators = __commonJS({
  "node_modules/semver/ranges/to-comparators.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Range = require_range();
    var toComparators = /* @__PURE__ */ __name((range, options2) => new Range(range, options2).set.map((comp) => comp.map((c3) => c3.value).join(" ").trim().split(" ")), "toComparators");
    module2.exports = toComparators;
  }
});

// node_modules/semver/ranges/max-satisfying.js
var require_max_satisfying = __commonJS({
  "node_modules/semver/ranges/max-satisfying.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var SemVer = require_semver2();
    var Range = require_range();
    var maxSatisfying = /* @__PURE__ */ __name((versions, range, options2) => {
      let max = null;
      let maxSV = null;
      let rangeObj = null;
      try {
        rangeObj = new Range(range, options2);
      } catch (er) {
        return null;
      }
      versions.forEach((v) => {
        if (rangeObj.test(v)) {
          if (!max || maxSV.compare(v) === -1) {
            max = v;
            maxSV = new SemVer(max, options2);
          }
        }
      });
      return max;
    }, "maxSatisfying");
    module2.exports = maxSatisfying;
  }
});

// node_modules/semver/ranges/min-satisfying.js
var require_min_satisfying = __commonJS({
  "node_modules/semver/ranges/min-satisfying.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var SemVer = require_semver2();
    var Range = require_range();
    var minSatisfying = /* @__PURE__ */ __name((versions, range, options2) => {
      let min = null;
      let minSV = null;
      let rangeObj = null;
      try {
        rangeObj = new Range(range, options2);
      } catch (er) {
        return null;
      }
      versions.forEach((v) => {
        if (rangeObj.test(v)) {
          if (!min || minSV.compare(v) === 1) {
            min = v;
            minSV = new SemVer(min, options2);
          }
        }
      });
      return min;
    }, "minSatisfying");
    module2.exports = minSatisfying;
  }
});

// node_modules/semver/ranges/min-version.js
var require_min_version = __commonJS({
  "node_modules/semver/ranges/min-version.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var SemVer = require_semver2();
    var Range = require_range();
    var gt = require_gt();
    var minVersion = /* @__PURE__ */ __name((range, loose) => {
      range = new Range(range, loose);
      let minver = new SemVer("0.0.0");
      if (range.test(minver)) {
        return minver;
      }
      minver = new SemVer("0.0.0-0");
      if (range.test(minver)) {
        return minver;
      }
      minver = null;
      for (let i = 0; i < range.set.length; ++i) {
        const comparators = range.set[i];
        let setMin = null;
        comparators.forEach((comparator) => {
          const compver = new SemVer(comparator.semver.version);
          switch (comparator.operator) {
            case ">":
              if (compver.prerelease.length === 0) {
                compver.patch++;
              } else {
                compver.prerelease.push(0);
              }
              compver.raw = compver.format();
            /* fallthrough */
            case "":
            case ">=":
              if (!setMin || gt(compver, setMin)) {
                setMin = compver;
              }
              break;
            case "<":
            case "<=":
              break;
            /* istanbul ignore next */
            default:
              throw new Error(`Unexpected operation: ${comparator.operator}`);
          }
        });
        if (setMin && (!minver || gt(minver, setMin))) {
          minver = setMin;
        }
      }
      if (minver && range.test(minver)) {
        return minver;
      }
      return null;
    }, "minVersion");
    module2.exports = minVersion;
  }
});

// node_modules/semver/ranges/valid.js
var require_valid2 = __commonJS({
  "node_modules/semver/ranges/valid.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Range = require_range();
    var validRange = /* @__PURE__ */ __name((range, options2) => {
      try {
        return new Range(range, options2).range || "*";
      } catch (er) {
        return null;
      }
    }, "validRange");
    module2.exports = validRange;
  }
});

// node_modules/semver/ranges/outside.js
var require_outside = __commonJS({
  "node_modules/semver/ranges/outside.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var SemVer = require_semver2();
    var Comparator = require_comparator();
    var { ANY } = Comparator;
    var Range = require_range();
    var satisfies = require_satisfies();
    var gt = require_gt();
    var lt = require_lt();
    var lte = require_lte();
    var gte = require_gte();
    var outside = /* @__PURE__ */ __name((version2, range, hilo, options2) => {
      version2 = new SemVer(version2, options2);
      range = new Range(range, options2);
      let gtfn, ltefn, ltfn, comp, ecomp;
      switch (hilo) {
        case ">":
          gtfn = gt;
          ltefn = lte;
          ltfn = lt;
          comp = ">";
          ecomp = ">=";
          break;
        case "<":
          gtfn = lt;
          ltefn = gte;
          ltfn = gt;
          comp = "<";
          ecomp = "<=";
          break;
        default:
          throw new TypeError('Must provide a hilo val of "<" or ">"');
      }
      if (satisfies(version2, range, options2)) {
        return false;
      }
      for (let i = 0; i < range.set.length; ++i) {
        const comparators = range.set[i];
        let high = null;
        let low = null;
        comparators.forEach((comparator) => {
          if (comparator.semver === ANY) {
            comparator = new Comparator(">=0.0.0");
          }
          high = high || comparator;
          low = low || comparator;
          if (gtfn(comparator.semver, high.semver, options2)) {
            high = comparator;
          } else if (ltfn(comparator.semver, low.semver, options2)) {
            low = comparator;
          }
        });
        if (high.operator === comp || high.operator === ecomp) {
          return false;
        }
        if ((!low.operator || low.operator === comp) && ltefn(version2, low.semver)) {
          return false;
        } else if (low.operator === ecomp && ltfn(version2, low.semver)) {
          return false;
        }
      }
      return true;
    }, "outside");
    module2.exports = outside;
  }
});

// node_modules/semver/ranges/gtr.js
var require_gtr = __commonJS({
  "node_modules/semver/ranges/gtr.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var outside = require_outside();
    var gtr = /* @__PURE__ */ __name((version2, range, options2) => outside(version2, range, ">", options2), "gtr");
    module2.exports = gtr;
  }
});

// node_modules/semver/ranges/ltr.js
var require_ltr = __commonJS({
  "node_modules/semver/ranges/ltr.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var outside = require_outside();
    var ltr = /* @__PURE__ */ __name((version2, range, options2) => outside(version2, range, "<", options2), "ltr");
    module2.exports = ltr;
  }
});

// node_modules/semver/ranges/intersects.js
var require_intersects = __commonJS({
  "node_modules/semver/ranges/intersects.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Range = require_range();
    var intersects = /* @__PURE__ */ __name((r1, r22, options2) => {
      r1 = new Range(r1, options2);
      r22 = new Range(r22, options2);
      return r1.intersects(r22, options2);
    }, "intersects");
    module2.exports = intersects;
  }
});

// node_modules/semver/ranges/simplify.js
var require_simplify = __commonJS({
  "node_modules/semver/ranges/simplify.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var satisfies = require_satisfies();
    var compare = require_compare();
    module2.exports = (versions, range, options2) => {
      const set = [];
      let first2 = null;
      let prev = null;
      const v = versions.sort((a, b) => compare(a, b, options2));
      for (const version2 of v) {
        const included = satisfies(version2, range, options2);
        if (included) {
          prev = version2;
          if (!first2) {
            first2 = version2;
          }
        } else {
          if (prev) {
            set.push([first2, prev]);
          }
          prev = null;
          first2 = null;
        }
      }
      if (first2) {
        set.push([first2, null]);
      }
      const ranges2 = [];
      for (const [min, max] of set) {
        if (min === max) {
          ranges2.push(min);
        } else if (!max && min === v[0]) {
          ranges2.push("*");
        } else if (!max) {
          ranges2.push(`>=${min}`);
        } else if (min === v[0]) {
          ranges2.push(`<=${max}`);
        } else {
          ranges2.push(`${min} - ${max}`);
        }
      }
      const simplified = ranges2.join(" || ");
      const original = typeof range.raw === "string" ? range.raw : String(range);
      return simplified.length < original.length ? simplified : range;
    };
  }
});

// node_modules/semver/ranges/subset.js
var require_subset = __commonJS({
  "node_modules/semver/ranges/subset.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Range = require_range();
    var Comparator = require_comparator();
    var { ANY } = Comparator;
    var satisfies = require_satisfies();
    var compare = require_compare();
    var subset = /* @__PURE__ */ __name((sub, dom, options2 = {}) => {
      if (sub === dom) {
        return true;
      }
      sub = new Range(sub, options2);
      dom = new Range(dom, options2);
      let sawNonNull = false;
      OUTER: for (const simpleSub of sub.set) {
        for (const simpleDom of dom.set) {
          const isSub = simpleSubset(simpleSub, simpleDom, options2);
          sawNonNull = sawNonNull || isSub !== null;
          if (isSub) {
            continue OUTER;
          }
        }
        if (sawNonNull) {
          return false;
        }
      }
      return true;
    }, "subset");
    var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")];
    var minimumVersion = [new Comparator(">=0.0.0")];
    var simpleSubset = /* @__PURE__ */ __name((sub, dom, options2) => {
      if (sub === dom) {
        return true;
      }
      if (sub.length === 1 && sub[0].semver === ANY) {
        if (dom.length === 1 && dom[0].semver === ANY) {
          return true;
        } else if (options2.includePrerelease) {
          sub = minimumVersionWithPreRelease;
        } else {
          sub = minimumVersion;
        }
      }
      if (dom.length === 1 && dom[0].semver === ANY) {
        if (options2.includePrerelease) {
          return true;
        } else {
          dom = minimumVersion;
        }
      }
      const eqSet = /* @__PURE__ */ new Set();
      let gt, lt;
      for (const c3 of sub) {
        if (c3.operator === ">" || c3.operator === ">=") {
          gt = higherGT(gt, c3, options2);
        } else if (c3.operator === "<" || c3.operator === "<=") {
          lt = lowerLT(lt, c3, options2);
        } else {
          eqSet.add(c3.semver);
        }
      }
      if (eqSet.size > 1) {
        return null;
      }
      let gtltComp;
      if (gt && lt) {
        gtltComp = compare(gt.semver, lt.semver, options2);
        if (gtltComp > 0) {
          return null;
        } else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) {
          return null;
        }
      }
      for (const eq of eqSet) {
        if (gt && !satisfies(eq, String(gt), options2)) {
          return null;
        }
        if (lt && !satisfies(eq, String(lt), options2)) {
          return null;
        }
        for (const c3 of dom) {
          if (!satisfies(eq, String(c3), options2)) {
            return false;
          }
        }
        return true;
      }
      let higher, lower;
      let hasDomLT, hasDomGT;
      let needDomLTPre = lt && !options2.includePrerelease && lt.semver.prerelease.length ? lt.semver : false;
      let needDomGTPre = gt && !options2.includePrerelease && gt.semver.prerelease.length ? gt.semver : false;
      if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) {
        needDomLTPre = false;
      }
      for (const c3 of dom) {
        hasDomGT = hasDomGT || c3.operator === ">" || c3.operator === ">=";
        hasDomLT = hasDomLT || c3.operator === "<" || c3.operator === "<=";
        if (gt) {
          if (needDomGTPre) {
            if (c3.semver.prerelease && c3.semver.prerelease.length && c3.semver.major === needDomGTPre.major && c3.semver.minor === needDomGTPre.minor && c3.semver.patch === needDomGTPre.patch) {
              needDomGTPre = false;
            }
          }
          if (c3.operator === ">" || c3.operator === ">=") {
            higher = higherGT(gt, c3, options2);
            if (higher === c3 && higher !== gt) {
              return false;
            }
          } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c3), options2)) {
            return false;
          }
        }
        if (lt) {
          if (needDomLTPre) {
            if (c3.semver.prerelease && c3.semver.prerelease.length && c3.semver.major === needDomLTPre.major && c3.semver.minor === needDomLTPre.minor && c3.semver.patch === needDomLTPre.patch) {
              needDomLTPre = false;
            }
          }
          if (c3.operator === "<" || c3.operator === "<=") {
            lower = lowerLT(lt, c3, options2);
            if (lower === c3 && lower !== lt) {
              return false;
            }
          } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c3), options2)) {
            return false;
          }
        }
        if (!c3.operator && (lt || gt) && gtltComp !== 0) {
          return false;
        }
      }
      if (gt && hasDomLT && !lt && gtltComp !== 0) {
        return false;
      }
      if (lt && hasDomGT && !gt && gtltComp !== 0) {
        return false;
      }
      if (needDomGTPre || needDomLTPre) {
        return false;
      }
      return true;
    }, "simpleSubset");
    var higherGT = /* @__PURE__ */ __name((a, b, options2) => {
      if (!a) {
        return b;
      }
      const comp = compare(a.semver, b.semver, options2);
      return comp > 0 ? a : comp < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a;
    }, "higherGT");
    var lowerLT = /* @__PURE__ */ __name((a, b, options2) => {
      if (!a) {
        return b;
      }
      const comp = compare(a.semver, b.semver, options2);
      return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a;
    }, "lowerLT");
    module2.exports = subset;
  }
});

// node_modules/semver/index.js
var require_semver3 = __commonJS({
  "node_modules/semver/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var internalRe = require_re();
    var constants4 = require_constants12();
    var SemVer = require_semver2();
    var identifiers = require_identifiers();
    var parse12 = require_parse8();
    var valid = require_valid();
    var clean = require_clean();
    var inc = require_inc();
    var diff4 = require_diff();
    var major2 = require_major();
    var minor = require_minor();
    var patch = require_patch();
    var prerelease = require_prerelease();
    var compare = require_compare();
    var rcompare = require_rcompare();
    var compareLoose = require_compare_loose();
    var compareBuild = require_compare_build();
    var sort = require_sort();
    var rsort = require_rsort();
    var gt = require_gt();
    var lt = require_lt();
    var eq = require_eq();
    var neq = require_neq();
    var gte = require_gte();
    var lte = require_lte();
    var cmp = require_cmp();
    var coerce2 = require_coerce();
    var Comparator = require_comparator();
    var Range = require_range();
    var satisfies = require_satisfies();
    var toComparators = require_to_comparators();
    var maxSatisfying = require_max_satisfying();
    var minSatisfying = require_min_satisfying();
    var minVersion = require_min_version();
    var validRange = require_valid2();
    var outside = require_outside();
    var gtr = require_gtr();
    var ltr = require_ltr();
    var intersects = require_intersects();
    var simplifyRange = require_simplify();
    var subset = require_subset();
    module2.exports = {
      parse: parse12,
      valid,
      clean,
      inc,
      diff: diff4,
      major: major2,
      minor,
      patch,
      prerelease,
      compare,
      rcompare,
      compareLoose,
      compareBuild,
      sort,
      rsort,
      gt,
      lt,
      eq,
      neq,
      gte,
      lte,
      cmp,
      coerce: coerce2,
      Comparator,
      Range,
      satisfies,
      toComparators,
      maxSatisfying,
      minSatisfying,
      minVersion,
      validRange,
      outside,
      gtr,
      ltr,
      intersects,
      simplifyRange,
      subset,
      SemVer,
      re: internalRe.re,
      src: internalRe.src,
      tokens: internalRe.t,
      SEMVER_SPEC_VERSION: constants4.SEMVER_SPEC_VERSION,
      RELEASE_TYPES: constants4.RELEASE_TYPES,
      compareIdentifiers: identifiers.compareIdentifiers,
      rcompareIdentifiers: identifiers.rcompareIdentifiers
    };
  }
});

// node_modules/ini/lib/ini.js
var require_ini3 = __commonJS({
  "node_modules/ini/lib/ini.js"(exports2, module2) {
    init_esbuild_shims();
    var { hasOwnProperty: hasOwnProperty2 } = Object.prototype;
    var encode4 = /* @__PURE__ */ __name((obj, opt = {}) => {
      if (typeof opt === "string") {
        opt = { section: opt };
      }
      opt.align = opt.align === true;
      opt.newline = opt.newline === true;
      opt.sort = opt.sort === true;
      opt.whitespace = opt.whitespace === true || opt.align === true;
      opt.platform = opt.platform || typeof process !== "undefined" && process.platform;
      opt.bracketedArray = opt.bracketedArray !== false;
      const eol = opt.platform === "win32" ? "\r\n" : "\n";
      const separator = opt.whitespace ? " = " : "=";
      const children = [];
      const keys = opt.sort ? Object.keys(obj).sort() : Object.keys(obj);
      let padToChars = 0;
      if (opt.align) {
        padToChars = safe(
          keys.filter((k) => obj[k] === null || Array.isArray(obj[k]) || typeof obj[k] !== "object").map((k) => Array.isArray(obj[k]) ? `${k}[]` : k).concat([""]).reduce((a, b) => safe(a).length >= safe(b).length ? a : b)
        ).length;
      }
      let out = "";
      const arraySuffix = opt.bracketedArray ? "[]" : "";
      for (const k of keys) {
        const val = obj[k];
        if (val && Array.isArray(val)) {
          for (const item of val) {
            out += safe(`${k}${arraySuffix}`).padEnd(padToChars, " ") + separator + safe(item) + eol;
          }
        } else if (val && typeof val === "object") {
          children.push(k);
        } else {
          out += safe(k).padEnd(padToChars, " ") + separator + safe(val) + eol;
        }
      }
      if (opt.section && out.length) {
        out = "[" + safe(opt.section) + "]" + (opt.newline ? eol + eol : eol) + out;
      }
      for (const k of children) {
        const nk = splitSections(k, ".").join("\\.");
        const section = (opt.section ? opt.section + "." : "") + nk;
        const child = encode4(obj[k], {
          ...opt,
          section
        });
        if (out.length && child.length) {
          out += eol;
        }
        out += child;
      }
      return out;
    }, "encode");
    function splitSections(str2, separator) {
      var lastMatchIndex = 0;
      var lastSeparatorIndex = 0;
      var nextIndex = 0;
      var sections = [];
      do {
        nextIndex = str2.indexOf(separator, lastMatchIndex);
        if (nextIndex !== -1) {
          lastMatchIndex = nextIndex + separator.length;
          if (nextIndex > 0 && str2[nextIndex - 1] === "\\") {
            continue;
          }
          sections.push(str2.slice(lastSeparatorIndex, nextIndex));
          lastSeparatorIndex = nextIndex + separator.length;
        }
      } while (nextIndex !== -1);
      sections.push(str2.slice(lastSeparatorIndex));
      return sections;
    }
    __name(splitSections, "splitSections");
    var decode2 = /* @__PURE__ */ __name((str2, opt = {}) => {
      opt.bracketedArray = opt.bracketedArray !== false;
      const out = /* @__PURE__ */ Object.create(null);
      let p = out;
      let section = null;
      const re2 = /^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i;
      const lines = str2.split(/[\r\n]+/g);
      const duplicates = {};
      for (const line of lines) {
        if (!line || line.match(/^\s*[;#]/) || line.match(/^\s*$/)) {
          continue;
        }
        const match2 = line.match(re2);
        if (!match2) {
          continue;
        }
        if (match2[1] !== void 0) {
          section = unsafe(match2[1]);
          if (section === "__proto__") {
            p = /* @__PURE__ */ Object.create(null);
            continue;
          }
          p = out[section] = out[section] || /* @__PURE__ */ Object.create(null);
          continue;
        }
        const keyRaw = unsafe(match2[2]);
        let isArray2;
        if (opt.bracketedArray) {
          isArray2 = keyRaw.length > 2 && keyRaw.slice(-2) === "[]";
        } else {
          duplicates[keyRaw] = (duplicates?.[keyRaw] || 0) + 1;
          isArray2 = duplicates[keyRaw] > 1;
        }
        const key = isArray2 ? keyRaw.slice(0, -2) : keyRaw;
        if (key === "__proto__") {
          continue;
        }
        const valueRaw = match2[3] ? unsafe(match2[4]) : true;
        const value = valueRaw === "true" || valueRaw === "false" || valueRaw === "null" ? JSON.parse(valueRaw) : valueRaw;
        if (isArray2) {
          if (!hasOwnProperty2.call(p, key)) {
            p[key] = [];
          } else if (!Array.isArray(p[key])) {
            p[key] = [p[key]];
          }
        }
        if (Array.isArray(p[key])) {
          p[key].push(value);
        } else {
          p[key] = value;
        }
      }
      const remove2 = [];
      for (const k of Object.keys(out)) {
        if (!hasOwnProperty2.call(out, k) || typeof out[k] !== "object" || Array.isArray(out[k])) {
          continue;
        }
        const parts = splitSections(k, ".");
        p = out;
        const l2 = parts.pop();
        const nl2 = l2.replace(/\\\./g, ".");
        for (const part of parts) {
          if (part === "__proto__") {
            continue;
          }
          if (!hasOwnProperty2.call(p, part) || typeof p[part] !== "object") {
            p[part] = /* @__PURE__ */ Object.create(null);
          }
          p = p[part];
        }
        if (p === out && nl2 === l2) {
          continue;
        }
        p[nl2] = out[k];
        remove2.push(k);
      }
      for (const del of remove2) {
        delete out[del];
      }
      return out;
    }, "decode");
    var isQuoted = /* @__PURE__ */ __name((val) => {
      return val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'");
    }, "isQuoted");
    var safe = /* @__PURE__ */ __name((val) => {
      if (typeof val !== "string" || val.match(/[=\r\n]/) || val.match(/^\[/) || val.length > 1 && isQuoted(val) || val !== val.trim()) {
        return JSON.stringify(val);
      }
      return val.split(";").join("\\;").split("#").join("\\#");
    }, "safe");
    var unsafe = /* @__PURE__ */ __name((val, doUnesc) => {
      val = (val || "").trim();
      if (isQuoted(val)) {
        if (val.charAt(0) === "'") {
          val = val.slice(1, -1);
        }
        try {
          val = JSON.parse(val);
        } catch {
        }
      } else {
        let esc = false;
        let unesc = "";
        for (let i = 0, l2 = val.length; i < l2; i++) {
          const c3 = val.charAt(i);
          if (esc) {
            if ("\\;#".indexOf(c3) !== -1) {
              unesc += c3;
            } else {
              unesc += "\\" + c3;
            }
            esc = false;
          } else if (";#".indexOf(c3) !== -1) {
            break;
          } else if (c3 === "\\") {
            esc = true;
          } else {
            unesc += c3;
          }
        }
        if (esc) {
          unesc += "\\";
        }
        return unesc.trim();
      }
      return val;
    }, "unsafe");
    module2.exports = {
      parse: decode2,
      decode: decode2,
      stringify: encode4,
      encode: encode4,
      safe,
      unsafe
    };
  }
});

// node_modules/update-notifier/node_modules/emoji-regex/index.js
var require_emoji_regex5 = __commonJS({
  "node_modules/update-notifier/node_modules/emoji-regex/index.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = () => {
      return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g;
    };
  }
});

// node_modules/ansi-align/node_modules/strip-ansi/index.js
var require_strip_ansi = __commonJS({
  "node_modules/ansi-align/node_modules/strip-ansi/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var ansiRegex3 = (init_ansi_regex(), __toCommonJS(ansi_regex_exports));
    module2.exports = (string) => typeof string === "string" ? string.replace(ansiRegex3(), "") : string;
  }
});

// node_modules/is-fullwidth-code-point/index.js
var require_is_fullwidth_code_point = __commonJS({
  "node_modules/is-fullwidth-code-point/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var isFullwidthCodePoint4 = /* @__PURE__ */ __name((codePoint) => {
      if (Number.isNaN(codePoint)) {
        return false;
      }
      if (codePoint >= 4352 && (codePoint <= 4447 || // Hangul Jamo
      codePoint === 9001 || // LEFT-POINTING ANGLE BRACKET
      codePoint === 9002 || // RIGHT-POINTING ANGLE BRACKET
      // CJK Radicals Supplement .. Enclosed CJK Letters and Months
      11904 <= codePoint && codePoint <= 12871 && codePoint !== 12351 || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
      12880 <= codePoint && codePoint <= 19903 || // CJK Unified Ideographs .. Yi Radicals
      19968 <= codePoint && codePoint <= 42182 || // Hangul Jamo Extended-A
      43360 <= codePoint && codePoint <= 43388 || // Hangul Syllables
      44032 <= codePoint && codePoint <= 55203 || // CJK Compatibility Ideographs
      63744 <= codePoint && codePoint <= 64255 || // Vertical Forms
      65040 <= codePoint && codePoint <= 65049 || // CJK Compatibility Forms .. Small Form Variants
      65072 <= codePoint && codePoint <= 65131 || // Halfwidth and Fullwidth Forms
      65281 <= codePoint && codePoint <= 65376 || 65504 <= codePoint && codePoint <= 65510 || // Kana Supplement
      110592 <= codePoint && codePoint <= 110593 || // Enclosed Ideographic Supplement
      127488 <= codePoint && codePoint <= 127569 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
      131072 <= codePoint && codePoint <= 262141)) {
        return true;
      }
      return false;
    }, "isFullwidthCodePoint");
    module2.exports = isFullwidthCodePoint4;
    module2.exports.default = isFullwidthCodePoint4;
  }
});

// node_modules/ansi-align/node_modules/emoji-regex/index.js
var require_emoji_regex6 = __commonJS({
  "node_modules/ansi-align/node_modules/emoji-regex/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = function() {
      return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
    };
  }
});

// node_modules/ansi-align/node_modules/string-width/index.js
var require_string_width = __commonJS({
  "node_modules/ansi-align/node_modules/string-width/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var stripAnsi3 = require_strip_ansi();
    var isFullwidthCodePoint4 = require_is_fullwidth_code_point();
    var emojiRegex7 = require_emoji_regex6();
    var stringWidth6 = /* @__PURE__ */ __name((string) => {
      if (typeof string !== "string" || string.length === 0) {
        return 0;
      }
      string = stripAnsi3(string);
      if (string.length === 0) {
        return 0;
      }
      string = string.replace(emojiRegex7(), "  ");
      let width = 0;
      for (let i = 0; i < string.length; i++) {
        const code2 = string.codePointAt(i);
        if (code2 <= 31 || code2 >= 127 && code2 <= 159) {
          continue;
        }
        if (code2 >= 768 && code2 <= 879) {
          continue;
        }
        if (code2 > 65535) {
          i++;
        }
        width += isFullwidthCodePoint4(code2) ? 2 : 1;
      }
      return width;
    }, "stringWidth");
    module2.exports = stringWidth6;
    module2.exports.default = stringWidth6;
  }
});

// node_modules/ansi-align/index.js
var require_ansi_align = __commonJS({
  "node_modules/ansi-align/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var stringWidth6 = require_string_width();
    function ansiAlign2(text, opts) {
      if (!text) return text;
      opts = opts || {};
      const align2 = opts.align || "center";
      if (align2 === "left") return text;
      const split = opts.split || "\n";
      const pad = opts.pad || " ";
      const widthDiffFn = align2 !== "right" ? halfDiff : fullDiff;
      let returnString = false;
      if (!Array.isArray(text)) {
        returnString = true;
        text = String(text).split(split);
      }
      let width;
      let maxWidth = 0;
      text = text.map(function(str2) {
        str2 = String(str2);
        width = stringWidth6(str2);
        maxWidth = Math.max(width, maxWidth);
        return {
          str: str2,
          width
        };
      }).map(function(obj) {
        return new Array(widthDiffFn(maxWidth, obj.width) + 1).join(pad) + obj.str;
      });
      return returnString ? text.join(split) : text;
    }
    __name(ansiAlign2, "ansiAlign");
    ansiAlign2.left = /* @__PURE__ */ __name(function left3(text) {
      return ansiAlign2(text, { align: "left" });
    }, "left");
    ansiAlign2.center = /* @__PURE__ */ __name(function center(text) {
      return ansiAlign2(text, { align: "center" });
    }, "center");
    ansiAlign2.right = /* @__PURE__ */ __name(function right3(text) {
      return ansiAlign2(text, { align: "right" });
    }, "right");
    module2.exports = ansiAlign2;
    function halfDiff(maxWidth, curWidth) {
      return Math.floor((maxWidth - curWidth) / 2);
    }
    __name(halfDiff, "halfDiff");
    function fullDiff(maxWidth, curWidth) {
      return maxWidth - curWidth;
    }
    __name(fullDiff, "fullDiff");
  }
});

// packages/cli/index.ts
init_esbuild_shims();

// packages/cli/src/gemini.tsx
init_esbuild_shims();
var import_react136 = __toESM(require_react(), 1);

// node_modules/ink/build/index.js
init_esbuild_shims();

// node_modules/ink/build/render.js
init_esbuild_shims();
import { Stream } from "node:stream";
import process12 from "node:process";

// node_modules/ink/build/ink.js
init_esbuild_shims();
var import_react13 = __toESM(require_react(), 1);
import process11 from "node:process";

// node_modules/es-toolkit/dist/compat/index.mjs
init_esbuild_shims();

// node_modules/es-toolkit/dist/compat/function/debounce.mjs
init_esbuild_shims();

// node_modules/es-toolkit/dist/function/debounce.mjs
init_esbuild_shims();
function debounce(func, debounceMs, { signal, edges } = {}) {
  let pendingThis = void 0;
  let pendingArgs = null;
  const leading = edges != null && edges.includes("leading");
  const trailing = edges == null || edges.includes("trailing");
  const invoke = /* @__PURE__ */ __name(() => {
    if (pendingArgs !== null) {
      func.apply(pendingThis, pendingArgs);
      pendingThis = void 0;
      pendingArgs = null;
    }
  }, "invoke");
  const onTimerEnd = /* @__PURE__ */ __name(() => {
    if (trailing) {
      invoke();
    }
    cancel();
  }, "onTimerEnd");
  let timeoutId = null;
  const schedule = /* @__PURE__ */ __name(() => {
    if (timeoutId != null) {
      clearTimeout(timeoutId);
    }
    timeoutId = setTimeout(() => {
      timeoutId = null;
      onTimerEnd();
    }, debounceMs);
  }, "schedule");
  const cancelTimer = /* @__PURE__ */ __name(() => {
    if (timeoutId !== null) {
      clearTimeout(timeoutId);
      timeoutId = null;
    }
  }, "cancelTimer");
  const cancel = /* @__PURE__ */ __name(() => {
    cancelTimer();
    pendingThis = void 0;
    pendingArgs = null;
  }, "cancel");
  const flush = /* @__PURE__ */ __name(() => {
    invoke();
  }, "flush");
  const debounced = /* @__PURE__ */ __name(function(...args) {
    if (signal?.aborted) {
      return;
    }
    pendingThis = this;
    pendingArgs = args;
    const isFirstCall = timeoutId == null;
    schedule();
    if (leading && isFirstCall) {
      invoke();
    }
  }, "debounced");
  debounced.schedule = schedule;
  debounced.cancel = cancel;
  debounced.flush = flush;
  signal?.addEventListener("abort", cancel, { once: true });
  return debounced;
}
__name(debounce, "debounce");

// node_modules/es-toolkit/dist/compat/function/debounce.mjs
function debounce2(func, debounceMs = 0, options2 = {}) {
  if (typeof options2 !== "object") {
    options2 = {};
  }
  const { leading = false, trailing = true, maxWait } = options2;
  const edges = Array(2);
  if (leading) {
    edges[0] = "leading";
  }
  if (trailing) {
    edges[1] = "trailing";
  }
  let result = void 0;
  let pendingAt = null;
  const _debounced = debounce(function(...args) {
    result = func.apply(this, args);
    pendingAt = null;
  }, debounceMs, { edges });
  const debounced = /* @__PURE__ */ __name(function(...args) {
    if (maxWait != null) {
      if (pendingAt === null) {
        pendingAt = Date.now();
      }
      if (Date.now() - pendingAt >= maxWait) {
        result = func.apply(this, args);
        pendingAt = Date.now();
        _debounced.cancel();
        _debounced.schedule();
        return result;
      }
    }
    _debounced.apply(this, args);
    return result;
  }, "debounced");
  const flush = /* @__PURE__ */ __name(() => {
    _debounced.flush();
    return result;
  }, "flush");
  debounced.cancel = _debounced.cancel;
  debounced.flush = flush;
  return debounced;
}
__name(debounce2, "debounce");

// node_modules/es-toolkit/dist/compat/function/throttle.mjs
init_esbuild_shims();
function throttle(func, throttleMs = 0, options2 = {}) {
  const { leading = true, trailing = true } = options2;
  return debounce2(func, throttleMs, {
    leading,
    maxWait: throttleMs,
    trailing
  });
}
__name(throttle, "throttle");

// node_modules/ansi-escapes/index.js
init_esbuild_shims();

// node_modules/ansi-escapes/base.js
var base_exports = {};
__export(base_exports, {
  beep: () => beep,
  clearScreen: () => clearScreen,
  clearTerminal: () => clearTerminal,
  cursorBackward: () => cursorBackward,
  cursorDown: () => cursorDown,
  cursorForward: () => cursorForward,
  cursorGetPosition: () => cursorGetPosition,
  cursorHide: () => cursorHide,
  cursorLeft: () => cursorLeft,
  cursorMove: () => cursorMove,
  cursorNextLine: () => cursorNextLine,
  cursorPrevLine: () => cursorPrevLine,
  cursorRestorePosition: () => cursorRestorePosition,
  cursorSavePosition: () => cursorSavePosition,
  cursorShow: () => cursorShow,
  cursorTo: () => cursorTo,
  cursorUp: () => cursorUp,
  enterAlternativeScreen: () => enterAlternativeScreen,
  eraseDown: () => eraseDown,
  eraseEndLine: () => eraseEndLine,
  eraseLine: () => eraseLine,
  eraseLines: () => eraseLines,
  eraseScreen: () => eraseScreen,
  eraseStartLine: () => eraseStartLine,
  eraseUp: () => eraseUp,
  exitAlternativeScreen: () => exitAlternativeScreen,
  iTerm: () => iTerm,
  image: () => image,
  link: () => link,
  scrollDown: () => scrollDown,
  scrollUp: () => scrollUp
});
init_esbuild_shims();
import process2 from "node:process";

// node_modules/environment/index.js
init_esbuild_shims();
var isBrowser = globalThis.window?.document !== void 0;
var isNode = globalThis.process?.versions?.node !== void 0;
var isBun = globalThis.process?.versions?.bun !== void 0;
var isDeno = globalThis.Deno?.version?.deno !== void 0;
var isElectron = globalThis.process?.versions?.electron !== void 0;
var isJsDom = globalThis.navigator?.userAgent?.includes("jsdom") === true;
var isWebWorker = typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope;
var isDedicatedWorker = typeof DedicatedWorkerGlobalScope !== "undefined" && globalThis instanceof DedicatedWorkerGlobalScope;
var isSharedWorker = typeof SharedWorkerGlobalScope !== "undefined" && globalThis instanceof SharedWorkerGlobalScope;
var isServiceWorker = typeof ServiceWorkerGlobalScope !== "undefined" && globalThis instanceof ServiceWorkerGlobalScope;
var platform = globalThis.navigator?.userAgentData?.platform;
var isMacOs = platform === "macOS" || globalThis.navigator?.platform === "MacIntel" || globalThis.navigator?.userAgent?.includes(" Mac ") === true || globalThis.process?.platform === "darwin";
var isWindows = platform === "Windows" || globalThis.navigator?.platform === "Win32" || globalThis.process?.platform === "win32";
var isLinux = platform === "Linux" || globalThis.navigator?.platform?.startsWith("Linux") === true || globalThis.navigator?.userAgent?.includes(" Linux ") === true || globalThis.process?.platform === "linux";
var isIos = platform === "iOS" || globalThis.navigator?.platform === "MacIntel" && globalThis.navigator?.maxTouchPoints > 1 || /iPad|iPhone|iPod/.test(globalThis.navigator?.platform);
var isAndroid = platform === "Android" || globalThis.navigator?.platform === "Android" || globalThis.navigator?.userAgent?.includes(" Android ") === true || globalThis.process?.platform === "android";

// node_modules/ansi-escapes/base.js
var ESC = "\x1B[";
var OSC = "\x1B]";
var BEL = "\x07";
var SEP = ";";
var isTerminalApp = !isBrowser && process2.env.TERM_PROGRAM === "Apple_Terminal";
var isWindows2 = !isBrowser && process2.platform === "win32";
var cwdFunction = isBrowser ? () => {
  throw new Error("`process.cwd()` only works in Node.js, not the browser.");
} : process2.cwd;
var cursorTo = /* @__PURE__ */ __name((x, y) => {
  if (typeof x !== "number") {
    throw new TypeError("The `x` argument is required");
  }
  if (typeof y !== "number") {
    return ESC + (x + 1) + "G";
  }
  return ESC + (y + 1) + SEP + (x + 1) + "H";
}, "cursorTo");
var cursorMove = /* @__PURE__ */ __name((x, y) => {
  if (typeof x !== "number") {
    throw new TypeError("The `x` argument is required");
  }
  let returnValue = "";
  if (x < 0) {
    returnValue += ESC + -x + "D";
  } else if (x > 0) {
    returnValue += ESC + x + "C";
  }
  if (y < 0) {
    returnValue += ESC + -y + "A";
  } else if (y > 0) {
    returnValue += ESC + y + "B";
  }
  return returnValue;
}, "cursorMove");
var cursorUp = /* @__PURE__ */ __name((count = 1) => ESC + count + "A", "cursorUp");
var cursorDown = /* @__PURE__ */ __name((count = 1) => ESC + count + "B", "cursorDown");
var cursorForward = /* @__PURE__ */ __name((count = 1) => ESC + count + "C", "cursorForward");
var cursorBackward = /* @__PURE__ */ __name((count = 1) => ESC + count + "D", "cursorBackward");
var cursorLeft = ESC + "G";
var cursorSavePosition = isTerminalApp ? "\x1B7" : ESC + "s";
var cursorRestorePosition = isTerminalApp ? "\x1B8" : ESC + "u";
var cursorGetPosition = ESC + "6n";
var cursorNextLine = ESC + "E";
var cursorPrevLine = ESC + "F";
var cursorHide = ESC + "?25l";
var cursorShow = ESC + "?25h";
var eraseLines = /* @__PURE__ */ __name((count) => {
  let clear = "";
  for (let i = 0; i < count; i++) {
    clear += eraseLine + (i < count - 1 ? cursorUp() : "");
  }
  if (count) {
    clear += cursorLeft;
  }
  return clear;
}, "eraseLines");
var eraseEndLine = ESC + "K";
var eraseStartLine = ESC + "1K";
var eraseLine = ESC + "2K";
var eraseDown = ESC + "J";
var eraseUp = ESC + "1J";
var eraseScreen = ESC + "2J";
var scrollUp = ESC + "S";
var scrollDown = ESC + "T";
var clearScreen = "\x1Bc";
var clearTerminal = isWindows2 ? `${eraseScreen}${ESC}0f` : `${eraseScreen}${ESC}3J${ESC}H`;
var enterAlternativeScreen = ESC + "?1049h";
var exitAlternativeScreen = ESC + "?1049l";
var beep = BEL;
var link = /* @__PURE__ */ __name((text, url2) => [
  OSC,
  "8",
  SEP,
  SEP,
  url2,
  BEL,
  text,
  OSC,
  "8",
  SEP,
  SEP,
  BEL
].join(""), "link");
var image = /* @__PURE__ */ __name((data, options2 = {}) => {
  let returnValue = `${OSC}1337;File=inline=1`;
  if (options2.width) {
    returnValue += `;width=${options2.width}`;
  }
  if (options2.height) {
    returnValue += `;height=${options2.height}`;
  }
  if (options2.preserveAspectRatio === false) {
    returnValue += ";preserveAspectRatio=0";
  }
  return returnValue + ":" + Buffer.from(data).toString("base64") + BEL;
}, "image");
var iTerm = {
  setCwd: /* @__PURE__ */ __name((cwd7 = cwdFunction()) => `${OSC}50;CurrentDir=${cwd7}${BEL}`, "setCwd"),
  annotation(message, options2 = {}) {
    let returnValue = `${OSC}1337;`;
    const hasX = options2.x !== void 0;
    const hasY = options2.y !== void 0;
    if ((hasX || hasY) && !(hasX && hasY && options2.length !== void 0)) {
      throw new Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");
    }
    message = message.replaceAll("|", "");
    returnValue += options2.isHidden ? "AddHiddenAnnotation=" : "AddAnnotation=";
    if (options2.length > 0) {
      returnValue += (hasX ? [message, options2.length, options2.x, options2.y] : [options2.length, message]).join("|");
    } else {
      returnValue += message;
    }
    return returnValue + BEL;
  }
};

// packages/cli/src/patches/is-in-ci.ts
init_esbuild_shims();
var isInCi = false;
var is_in_ci_default = isInCi;

// node_modules/auto-bind/index.js
init_esbuild_shims();
var getAllProperties = /* @__PURE__ */ __name((object) => {
  const properties = /* @__PURE__ */ new Set();
  do {
    for (const key of Reflect.ownKeys(object)) {
      properties.add([object, key]);
    }
  } while ((object = Reflect.getPrototypeOf(object)) && object !== Object.prototype);
  return properties;
}, "getAllProperties");
function autoBind(self2, { include, exclude } = {}) {
  const filter4 = /* @__PURE__ */ __name((key) => {
    const match2 = /* @__PURE__ */ __name((pattern) => typeof pattern === "string" ? key === pattern : pattern.test(key), "match");
    if (include) {
      return include.some(match2);
    }
    if (exclude) {
      return !exclude.some(match2);
    }
    return true;
  }, "filter");
  for (const [object, key] of getAllProperties(self2.constructor.prototype)) {
    if (key === "constructor" || !filter4(key)) {
      continue;
    }
    const descriptor2 = Reflect.getOwnPropertyDescriptor(object, key);
    if (descriptor2 && typeof descriptor2.value === "function") {
      self2[key] = self2[key].bind(self2);
    }
  }
  return self2;
}
__name(autoBind, "autoBind");

// node_modules/ink/build/ink.js
var import_signal_exit2 = __toESM(require_signal_exit(), 1);

// node_modules/patch-console/dist/index.js
init_esbuild_shims();
import { PassThrough } from "node:stream";
var consoleMethods = [
  "assert",
  "count",
  "countReset",
  "debug",
  "dir",
  "dirxml",
  "error",
  "group",
  "groupCollapsed",
  "groupEnd",
  "info",
  "log",
  "table",
  "time",
  "timeEnd",
  "timeLog",
  "trace",
  "warn"
];
var originalMethods = {};
var patchConsole = /* @__PURE__ */ __name((callback) => {
  const stdout = new PassThrough();
  const stderr = new PassThrough();
  stdout.write = (data) => {
    callback("stdout", data);
  };
  stderr.write = (data) => {
    callback("stderr", data);
  };
  const internalConsole = new console.Console(stdout, stderr);
  for (const method of consoleMethods) {
    originalMethods[method] = console[method];
    console[method] = internalConsole[method];
  }
  return () => {
    for (const method of consoleMethods) {
      console[method] = originalMethods[method];
    }
    originalMethods = {};
  };
}, "patchConsole");
var dist_default = patchConsole;

// node_modules/ink/build/ink.js
var import_constants2 = __toESM(require_constants(), 1);

// node_modules/yoga-layout/dist/src/index.js
init_esbuild_shims();

// node_modules/yoga-layout/dist/binaries/yoga-wasm-base64-esm.js
init_esbuild_shims();
var loadYoga = (() => {
  var _scriptDir = import.meta.url;
  return function(loadYoga2) {
    loadYoga2 = loadYoga2 || {};
    var h;
    h || (h = typeof loadYoga2 !== "undefined" ? loadYoga2 : {});
    var aa, ca;
    h.ready = new Promise(function(a, b) {
      aa = a;
      ca = b;
    });
    var da = Object.assign({}, h), q = "";
    "undefined" != typeof document && document.currentScript && (q = document.currentScript.src);
    _scriptDir && (q = _scriptDir);
    0 !== q.indexOf("blob:") ? q = q.substr(0, q.replace(/[?#].*/, "").lastIndexOf("/") + 1) : q = "";
    var ea = h.print || console.log.bind(console), v = h.printErr || console.warn.bind(console);
    Object.assign(h, da);
    da = null;
    var w;
    h.wasmBinary && (w = h.wasmBinary);
    var noExitRuntime = h.noExitRuntime || true;
    "object" != typeof WebAssembly && x("no native wasm support detected");
    var fa, ha = false;
    function z(a, b, c3) {
      c3 = b + c3;
      for (var d = ""; !(b >= c3); ) {
        var e2 = a[b++];
        if (!e2) break;
        if (e2 & 128) {
          var f = a[b++] & 63;
          if (192 == (e2 & 224)) d += String.fromCharCode((e2 & 31) << 6 | f);
          else {
            var g = a[b++] & 63;
            e2 = 224 == (e2 & 240) ? (e2 & 15) << 12 | f << 6 | g : (e2 & 7) << 18 | f << 12 | g << 6 | a[b++] & 63;
            65536 > e2 ? d += String.fromCharCode(e2) : (e2 -= 65536, d += String.fromCharCode(55296 | e2 >> 10, 56320 | e2 & 1023));
          }
        } else d += String.fromCharCode(e2);
      }
      return d;
    }
    __name(z, "z");
    var ia, ja, A, C, ka, D, E, la, ma;
    function na() {
      var a = fa.buffer;
      ia = a;
      h.HEAP8 = ja = new Int8Array(a);
      h.HEAP16 = C = new Int16Array(a);
      h.HEAP32 = D = new Int32Array(a);
      h.HEAPU8 = A = new Uint8Array(a);
      h.HEAPU16 = ka = new Uint16Array(a);
      h.HEAPU32 = E = new Uint32Array(a);
      h.HEAPF32 = la = new Float32Array(a);
      h.HEAPF64 = ma = new Float64Array(a);
    }
    __name(na, "na");
    var oa, pa = [], qa = [], ra = [];
    function sa() {
      var a = h.preRun.shift();
      pa.unshift(a);
    }
    __name(sa, "sa");
    var F = 0, ta = null, G = null;
    function x(a) {
      if (h.onAbort) h.onAbort(a);
      a = "Aborted(" + a + ")";
      v(a);
      ha = true;
      a = new WebAssembly.RuntimeError(a + ". Build with -sASSERTIONS for more info.");
      ca(a);
      throw a;
    }
    __name(x, "x");
    function ua(a) {
      return a.startsWith("data:application/octet-stream;base64,");
    }
    __name(ua, "ua");
    var H;
    H = "data:application/octet-stream;base64, ";
    if (!ua(H)) {
      var va = H;
      H = h.locateFile ? h.locateFile(va, q) : q + va;
    }
    function wa() {
      var a = H;
      try {
        if (a == H && w) return new Uint8Array(w);
        if (ua(a)) try {
          var b = xa(a.slice(37)), c3 = new Uint8Array(b.length);
          for (a = 0; a < b.length; ++a) c3[a] = b.charCodeAt(a);
          var d = c3;
        } catch (f) {
          throw Error("Converting base64 string to bytes failed.");
        }
        else d = void 0;
        var e2 = d;
        if (e2) return e2;
        throw "both async and sync fetching of the wasm failed";
      } catch (f) {
        x(f);
      }
    }
    __name(wa, "wa");
    function ya() {
      return w || "function" != typeof fetch ? Promise.resolve().then(function() {
        return wa();
      }) : fetch(H, { credentials: "same-origin" }).then(function(a) {
        if (!a.ok) throw "failed to load wasm binary file at '" + H + "'";
        return a.arrayBuffer();
      }).catch(function() {
        return wa();
      });
    }
    __name(ya, "ya");
    function za(a) {
      for (; 0 < a.length; ) a.shift()(h);
    }
    __name(za, "za");
    function Aa(a) {
      if (void 0 === a) return "_unknown";
      a = a.replace(/[^a-zA-Z0-9_]/g, "$");
      var b = a.charCodeAt(0);
      return 48 <= b && 57 >= b ? "_" + a : a;
    }
    __name(Aa, "Aa");
    function Ba(a, b) {
      a = Aa(a);
      return function() {
        return b.apply(this, arguments);
      };
    }
    __name(Ba, "Ba");
    var J = [{}, { value: void 0 }, { value: null }, { value: true }, { value: false }], Ca = [];
    function Da(a) {
      var b = Error, c3 = Ba(a, function(d) {
        this.name = a;
        this.message = d;
        d = Error(d).stack;
        void 0 !== d && (this.stack = this.toString() + "\n" + d.replace(/^Error(:[^\n]*)?\n/, ""));
      });
      c3.prototype = Object.create(b.prototype);
      c3.prototype.constructor = c3;
      c3.prototype.toString = function() {
        return void 0 === this.message ? this.name : this.name + ": " + this.message;
      };
      return c3;
    }
    __name(Da, "Da");
    var K = void 0;
    function L(a) {
      throw new K(a);
    }
    __name(L, "L");
    var M = /* @__PURE__ */ __name((a) => {
      a || L("Cannot use deleted val. handle = " + a);
      return J[a].value;
    }, "M"), Ea = /* @__PURE__ */ __name((a) => {
      switch (a) {
        case void 0:
          return 1;
        case null:
          return 2;
        case true:
          return 3;
        case false:
          return 4;
        default:
          var b = Ca.length ? Ca.pop() : J.length;
          J[b] = { ga: 1, value: a };
          return b;
      }
    }, "Ea"), Fa = void 0, Ga = void 0;
    function N(a) {
      for (var b = ""; A[a]; ) b += Ga[A[a++]];
      return b;
    }
    __name(N, "N");
    var O = [];
    function Ha() {
      for (; O.length; ) {
        var a = O.pop();
        a.M.$ = false;
        a["delete"]();
      }
    }
    __name(Ha, "Ha");
    var P = void 0, Q = {};
    function Ia(a, b) {
      for (void 0 === b && L("ptr should not be undefined"); a.R; ) b = a.ba(b), a = a.R;
      return b;
    }
    __name(Ia, "Ia");
    var R = {};
    function Ja(a) {
      a = Ka(a);
      var b = N(a);
      S(a);
      return b;
    }
    __name(Ja, "Ja");
    function La(a, b) {
      var c3 = R[a];
      void 0 === c3 && L(b + " has unknown type " + Ja(a));
      return c3;
    }
    __name(La, "La");
    function Ma() {
    }
    __name(Ma, "Ma");
    var Na = false;
    function Oa(a) {
      --a.count.value;
      0 === a.count.value && (a.T ? a.U.W(a.T) : a.P.N.W(a.O));
    }
    __name(Oa, "Oa");
    function Pa(a, b, c3) {
      if (b === c3) return a;
      if (void 0 === c3.R) return null;
      a = Pa(a, b, c3.R);
      return null === a ? null : c3.na(a);
    }
    __name(Pa, "Pa");
    var Qa = {};
    function Ra(a, b) {
      b = Ia(a, b);
      return Q[b];
    }
    __name(Ra, "Ra");
    var Sa = void 0;
    function Ta(a) {
      throw new Sa(a);
    }
    __name(Ta, "Ta");
    function Ua(a, b) {
      b.P && b.O || Ta("makeClassHandle requires ptr and ptrType");
      !!b.U !== !!b.T && Ta("Both smartPtrType and smartPtr must be specified");
      b.count = { value: 1 };
      return T(Object.create(a, { M: { value: b } }));
    }
    __name(Ua, "Ua");
    function T(a) {
      if ("undefined" === typeof FinalizationRegistry) return T = /* @__PURE__ */ __name((b) => b, "T"), a;
      Na = new FinalizationRegistry((b) => {
        Oa(b.M);
      });
      T = /* @__PURE__ */ __name((b) => {
        var c3 = b.M;
        c3.T && Na.register(b, { M: c3 }, b);
        return b;
      }, "T");
      Ma = /* @__PURE__ */ __name((b) => {
        Na.unregister(b);
      }, "Ma");
      return T(a);
    }
    __name(T, "T");
    var Va = {};
    function Wa(a) {
      for (; a.length; ) {
        var b = a.pop();
        a.pop()(b);
      }
    }
    __name(Wa, "Wa");
    function Xa(a) {
      return this.fromWireType(D[a >> 2]);
    }
    __name(Xa, "Xa");
    var U = {}, Ya = {};
    function V2(a, b, c3) {
      function d(k) {
        k = c3(k);
        k.length !== a.length && Ta("Mismatched type converter count");
        for (var m = 0; m < a.length; ++m) W(a[m], k[m]);
      }
      __name(d, "d");
      a.forEach(function(k) {
        Ya[k] = b;
      });
      var e2 = Array(b.length), f = [], g = 0;
      b.forEach((k, m) => {
        R.hasOwnProperty(k) ? e2[m] = R[k] : (f.push(k), U.hasOwnProperty(k) || (U[k] = []), U[k].push(() => {
          e2[m] = R[k];
          ++g;
          g === f.length && d(e2);
        }));
      });
      0 === f.length && d(e2);
    }
    __name(V2, "V");
    function Za(a) {
      switch (a) {
        case 1:
          return 0;
        case 2:
          return 1;
        case 4:
          return 2;
        case 8:
          return 3;
        default:
          throw new TypeError("Unknown type size: " + a);
      }
    }
    __name(Za, "Za");
    function W(a, b, c3 = {}) {
      if (!("argPackAdvance" in b)) throw new TypeError("registerType registeredInstance requires argPackAdvance");
      var d = b.name;
      a || L('type "' + d + '" must have a positive integer typeid pointer');
      if (R.hasOwnProperty(a)) {
        if (c3.ua) return;
        L("Cannot register type '" + d + "' twice");
      }
      R[a] = b;
      delete Ya[a];
      U.hasOwnProperty(a) && (b = U[a], delete U[a], b.forEach((e2) => e2()));
    }
    __name(W, "W");
    function $a(a) {
      L(a.M.P.N.name + " instance already deleted");
    }
    __name($a, "$a");
    function X() {
    }
    __name(X, "X");
    function ab2(a, b, c3) {
      if (void 0 === a[b].S) {
        var d = a[b];
        a[b] = function() {
          a[b].S.hasOwnProperty(arguments.length) || L("Function '" + c3 + "' called with an invalid number of arguments (" + arguments.length + ") - expects one of (" + a[b].S + ")!");
          return a[b].S[arguments.length].apply(this, arguments);
        };
        a[b].S = [];
        a[b].S[d.Z] = d;
      }
    }
    __name(ab2, "ab");
    function bb(a, b) {
      h.hasOwnProperty(a) ? (L("Cannot register public name '" + a + "' twice"), ab2(h, a, a), h.hasOwnProperty(void 0) && L("Cannot register multiple overloads of a function with the same number of arguments (undefined)!"), h[a].S[void 0] = b) : h[a] = b;
    }
    __name(bb, "bb");
    function cb(a, b, c3, d, e2, f, g, k) {
      this.name = a;
      this.constructor = b;
      this.X = c3;
      this.W = d;
      this.R = e2;
      this.pa = f;
      this.ba = g;
      this.na = k;
      this.ja = [];
    }
    __name(cb, "cb");
    function db(a, b, c3) {
      for (; b !== c3; ) b.ba || L("Expected null or instance of " + c3.name + ", got an instance of " + b.name), a = b.ba(a), b = b.R;
      return a;
    }
    __name(db, "db");
    function eb(a, b) {
      if (null === b) return this.ea && L("null is not a valid " + this.name), 0;
      b.M || L('Cannot pass "' + fb(b) + '" as a ' + this.name);
      b.M.O || L("Cannot pass deleted object as a pointer of type " + this.name);
      return db(b.M.O, b.M.P.N, this.N);
    }
    __name(eb, "eb");
    function gb(a, b) {
      if (null === b) {
        this.ea && L("null is not a valid " + this.name);
        if (this.da) {
          var c3 = this.fa();
          null !== a && a.push(this.W, c3);
          return c3;
        }
        return 0;
      }
      b.M || L('Cannot pass "' + fb(b) + '" as a ' + this.name);
      b.M.O || L("Cannot pass deleted object as a pointer of type " + this.name);
      !this.ca && b.M.P.ca && L("Cannot convert argument of type " + (b.M.U ? b.M.U.name : b.M.P.name) + " to parameter type " + this.name);
      c3 = db(b.M.O, b.M.P.N, this.N);
      if (this.da) switch (void 0 === b.M.T && L("Passing raw pointer to smart pointer is illegal"), this.Ba) {
        case 0:
          b.M.U === this ? c3 = b.M.T : L("Cannot convert argument of type " + (b.M.U ? b.M.U.name : b.M.P.name) + " to parameter type " + this.name);
          break;
        case 1:
          c3 = b.M.T;
          break;
        case 2:
          if (b.M.U === this) c3 = b.M.T;
          else {
            var d = b.clone();
            c3 = this.xa(c3, Ea(function() {
              d["delete"]();
            }));
            null !== a && a.push(this.W, c3);
          }
          break;
        default:
          L("Unsupporting sharing policy");
      }
      return c3;
    }
    __name(gb, "gb");
    function hb(a, b) {
      if (null === b) return this.ea && L("null is not a valid " + this.name), 0;
      b.M || L('Cannot pass "' + fb(b) + '" as a ' + this.name);
      b.M.O || L("Cannot pass deleted object as a pointer of type " + this.name);
      b.M.P.ca && L("Cannot convert argument of type " + b.M.P.name + " to parameter type " + this.name);
      return db(b.M.O, b.M.P.N, this.N);
    }
    __name(hb, "hb");
    function Y(a, b, c3, d) {
      this.name = a;
      this.N = b;
      this.ea = c3;
      this.ca = d;
      this.da = false;
      this.W = this.xa = this.fa = this.ka = this.Ba = this.wa = void 0;
      void 0 !== b.R ? this.toWireType = gb : (this.toWireType = d ? eb : hb, this.V = null);
    }
    __name(Y, "Y");
    function ib(a, b) {
      h.hasOwnProperty(a) || Ta("Replacing nonexistant public symbol");
      h[a] = b;
      h[a].Z = void 0;
    }
    __name(ib, "ib");
    function jb(a, b) {
      var c3 = [];
      return function() {
        c3.length = 0;
        Object.assign(c3, arguments);
        if (a.includes("j")) {
          var d = h["dynCall_" + a];
          d = c3 && c3.length ? d.apply(null, [b].concat(c3)) : d.call(null, b);
        } else d = oa.get(b).apply(null, c3);
        return d;
      };
    }
    __name(jb, "jb");
    function Z(a, b) {
      a = N(a);
      var c3 = a.includes("j") ? jb(a, b) : oa.get(b);
      "function" != typeof c3 && L("unknown function pointer with signature " + a + ": " + b);
      return c3;
    }
    __name(Z, "Z");
    var mb = void 0;
    function nb(a, b) {
      function c3(f) {
        e2[f] || R[f] || (Ya[f] ? Ya[f].forEach(c3) : (d.push(f), e2[f] = true));
      }
      __name(c3, "c");
      var d = [], e2 = {};
      b.forEach(c3);
      throw new mb(a + ": " + d.map(Ja).join([", "]));
    }
    __name(nb, "nb");
    function ob(a, b, c3, d, e2) {
      var f = b.length;
      2 > f && L("argTypes array size mismatch! Must at least get return value and 'this' types!");
      var g = null !== b[1] && null !== c3, k = false;
      for (c3 = 1; c3 < b.length; ++c3) if (null !== b[c3] && void 0 === b[c3].V) {
        k = true;
        break;
      }
      var m = "void" !== b[0].name, l2 = f - 2, n2 = Array(l2), p = [], r3 = [];
      return function() {
        arguments.length !== l2 && L("function " + a + " called with " + arguments.length + " arguments, expected " + l2 + " args!");
        r3.length = 0;
        p.length = g ? 2 : 1;
        p[0] = e2;
        if (g) {
          var u = b[1].toWireType(r3, this);
          p[1] = u;
        }
        for (var t2 = 0; t2 < l2; ++t2) n2[t2] = b[t2 + 2].toWireType(r3, arguments[t2]), p.push(n2[t2]);
        t2 = d.apply(null, p);
        if (k) Wa(r3);
        else for (var y = g ? 1 : 2; y < b.length; y++) {
          var B = 1 === y ? u : n2[y - 2];
          null !== b[y].V && b[y].V(B);
        }
        u = m ? b[0].fromWireType(t2) : void 0;
        return u;
      };
    }
    __name(ob, "ob");
    function pb(a, b) {
      for (var c3 = [], d = 0; d < a; d++) c3.push(E[b + 4 * d >> 2]);
      return c3;
    }
    __name(pb, "pb");
    function qb(a) {
      4 < a && 0 === --J[a].ga && (J[a] = void 0, Ca.push(a));
    }
    __name(qb, "qb");
    function fb(a) {
      if (null === a) return "null";
      var b = typeof a;
      return "object" === b || "array" === b || "function" === b ? a.toString() : "" + a;
    }
    __name(fb, "fb");
    function rb(a, b) {
      switch (b) {
        case 2:
          return function(c3) {
            return this.fromWireType(la[c3 >> 2]);
          };
        case 3:
          return function(c3) {
            return this.fromWireType(ma[c3 >> 3]);
          };
        default:
          throw new TypeError("Unknown float type: " + a);
      }
    }
    __name(rb, "rb");
    function sb(a, b, c3) {
      switch (b) {
        case 0:
          return c3 ? function(d) {
            return ja[d];
          } : function(d) {
            return A[d];
          };
        case 1:
          return c3 ? function(d) {
            return C[d >> 1];
          } : function(d) {
            return ka[d >> 1];
          };
        case 2:
          return c3 ? function(d) {
            return D[d >> 2];
          } : function(d) {
            return E[d >> 2];
          };
        default:
          throw new TypeError("Unknown integer type: " + a);
      }
    }
    __name(sb, "sb");
    function tb(a, b) {
      for (var c3 = "", d = 0; !(d >= b / 2); ++d) {
        var e2 = C[a + 2 * d >> 1];
        if (0 == e2) break;
        c3 += String.fromCharCode(e2);
      }
      return c3;
    }
    __name(tb, "tb");
    function ub(a, b, c3) {
      void 0 === c3 && (c3 = 2147483647);
      if (2 > c3) return 0;
      c3 -= 2;
      var d = b;
      c3 = c3 < 2 * a.length ? c3 / 2 : a.length;
      for (var e2 = 0; e2 < c3; ++e2) C[b >> 1] = a.charCodeAt(e2), b += 2;
      C[b >> 1] = 0;
      return b - d;
    }
    __name(ub, "ub");
    function vb(a) {
      return 2 * a.length;
    }
    __name(vb, "vb");
    function wb(a, b) {
      for (var c3 = 0, d = ""; !(c3 >= b / 4); ) {
        var e2 = D[a + 4 * c3 >> 2];
        if (0 == e2) break;
        ++c3;
        65536 <= e2 ? (e2 -= 65536, d += String.fromCharCode(55296 | e2 >> 10, 56320 | e2 & 1023)) : d += String.fromCharCode(e2);
      }
      return d;
    }
    __name(wb, "wb");
    function xb(a, b, c3) {
      void 0 === c3 && (c3 = 2147483647);
      if (4 > c3) return 0;
      var d = b;
      c3 = d + c3 - 4;
      for (var e2 = 0; e2 < a.length; ++e2) {
        var f = a.charCodeAt(e2);
        if (55296 <= f && 57343 >= f) {
          var g = a.charCodeAt(++e2);
          f = 65536 + ((f & 1023) << 10) | g & 1023;
        }
        D[b >> 2] = f;
        b += 4;
        if (b + 4 > c3) break;
      }
      D[b >> 2] = 0;
      return b - d;
    }
    __name(xb, "xb");
    function yb(a) {
      for (var b = 0, c3 = 0; c3 < a.length; ++c3) {
        var d = a.charCodeAt(c3);
        55296 <= d && 57343 >= d && ++c3;
        b += 4;
      }
      return b;
    }
    __name(yb, "yb");
    var zb = {};
    function Ab(a) {
      var b = zb[a];
      return void 0 === b ? N(a) : b;
    }
    __name(Ab, "Ab");
    var Bb = [];
    function Cb(a) {
      var b = Bb.length;
      Bb.push(a);
      return b;
    }
    __name(Cb, "Cb");
    function Db(a, b) {
      for (var c3 = Array(a), d = 0; d < a; ++d) c3[d] = La(E[b + 4 * d >> 2], "parameter " + d);
      return c3;
    }
    __name(Db, "Db");
    var Eb = [], Fb = [null, [], []];
    K = h.BindingError = Da("BindingError");
    h.count_emval_handles = function() {
      for (var a = 0, b = 5; b < J.length; ++b) void 0 !== J[b] && ++a;
      return a;
    };
    h.get_first_emval = function() {
      for (var a = 5; a < J.length; ++a) if (void 0 !== J[a]) return J[a];
      return null;
    };
    Fa = h.PureVirtualError = Da("PureVirtualError");
    for (var Gb = Array(256), Hb = 0; 256 > Hb; ++Hb) Gb[Hb] = String.fromCharCode(Hb);
    Ga = Gb;
    h.getInheritedInstanceCount = function() {
      return Object.keys(Q).length;
    };
    h.getLiveInheritedInstances = function() {
      var a = [], b;
      for (b in Q) Q.hasOwnProperty(b) && a.push(Q[b]);
      return a;
    };
    h.flushPendingDeletes = Ha;
    h.setDelayFunction = function(a) {
      P = a;
      O.length && P && P(Ha);
    };
    Sa = h.InternalError = Da("InternalError");
    X.prototype.isAliasOf = function(a) {
      if (!(this instanceof X && a instanceof X)) return false;
      var b = this.M.P.N, c3 = this.M.O, d = a.M.P.N;
      for (a = a.M.O; b.R; ) c3 = b.ba(c3), b = b.R;
      for (; d.R; ) a = d.ba(a), d = d.R;
      return b === d && c3 === a;
    };
    X.prototype.clone = function() {
      this.M.O || $a(this);
      if (this.M.aa) return this.M.count.value += 1, this;
      var a = T, b = Object, c3 = b.create, d = Object.getPrototypeOf(this), e2 = this.M;
      a = a(c3.call(b, d, { M: { value: { count: e2.count, $: e2.$, aa: e2.aa, O: e2.O, P: e2.P, T: e2.T, U: e2.U } } }));
      a.M.count.value += 1;
      a.M.$ = false;
      return a;
    };
    X.prototype["delete"] = function() {
      this.M.O || $a(this);
      this.M.$ && !this.M.aa && L("Object already scheduled for deletion");
      Ma(this);
      Oa(this.M);
      this.M.aa || (this.M.T = void 0, this.M.O = void 0);
    };
    X.prototype.isDeleted = function() {
      return !this.M.O;
    };
    X.prototype.deleteLater = function() {
      this.M.O || $a(this);
      this.M.$ && !this.M.aa && L("Object already scheduled for deletion");
      O.push(this);
      1 === O.length && P && P(Ha);
      this.M.$ = true;
      return this;
    };
    Y.prototype.qa = function(a) {
      this.ka && (a = this.ka(a));
      return a;
    };
    Y.prototype.ha = function(a) {
      this.W && this.W(a);
    };
    Y.prototype.argPackAdvance = 8;
    Y.prototype.readValueFromPointer = Xa;
    Y.prototype.deleteObject = function(a) {
      if (null !== a) a["delete"]();
    };
    Y.prototype.fromWireType = function(a) {
      function b() {
        return this.da ? Ua(this.N.X, { P: this.wa, O: c3, U: this, T: a }) : Ua(this.N.X, { P: this, O: a });
      }
      __name(b, "b");
      var c3 = this.qa(a);
      if (!c3) return this.ha(a), null;
      var d = Ra(this.N, c3);
      if (void 0 !== d) {
        if (0 === d.M.count.value) return d.M.O = c3, d.M.T = a, d.clone();
        d = d.clone();
        this.ha(a);
        return d;
      }
      d = this.N.pa(c3);
      d = Qa[d];
      if (!d) return b.call(this);
      d = this.ca ? d.la : d.pointerType;
      var e2 = Pa(c3, this.N, d.N);
      return null === e2 ? b.call(this) : this.da ? Ua(d.N.X, { P: d, O: e2, U: this, T: a }) : Ua(d.N.X, { P: d, O: e2 });
    };
    mb = h.UnboundTypeError = Da("UnboundTypeError");
    var xa = "function" == typeof atob ? atob : function(a) {
      var b = "", c3 = 0;
      a = a.replace(/[^A-Za-z0-9\+\/=]/g, "");
      do {
        var d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(c3++));
        var e2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(c3++));
        var f = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(c3++));
        var g = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(c3++));
        d = d << 2 | e2 >> 4;
        e2 = (e2 & 15) << 4 | f >> 2;
        var k = (f & 3) << 6 | g;
        b += String.fromCharCode(d);
        64 !== f && (b += String.fromCharCode(e2));
        64 !== g && (b += String.fromCharCode(k));
      } while (c3 < a.length);
      return b;
    }, Jb = {
      l: /* @__PURE__ */ __name(function(a, b, c3, d) {
        x("Assertion failed: " + (a ? z(A, a) : "") + ", at: " + [b ? b ? z(A, b) : "" : "unknown filename", c3, d ? d ? z(A, d) : "" : "unknown function"]);
      }, "l"),
      q: /* @__PURE__ */ __name(function(a, b, c3) {
        a = N(a);
        b = La(b, "wrapper");
        c3 = M(c3);
        var d = [].slice, e2 = b.N, f = e2.X, g = e2.R.X, k = e2.R.constructor;
        a = Ba(a, function() {
          e2.R.ja.forEach(function(l2) {
            if (this[l2] === g[l2]) throw new Fa("Pure virtual function " + l2 + " must be implemented in JavaScript");
          }.bind(this));
          Object.defineProperty(this, "__parent", { value: f });
          this.__construct.apply(this, d.call(arguments));
        });
        f.__construct = function() {
          this === f && L("Pass correct 'this' to __construct");
          var l2 = k.implement.apply(void 0, [this].concat(d.call(arguments)));
          Ma(l2);
          var n2 = l2.M;
          l2.notifyOnDestruction();
          n2.aa = true;
          Object.defineProperties(this, { M: { value: n2 } });
          T(this);
          l2 = n2.O;
          l2 = Ia(e2, l2);
          Q.hasOwnProperty(l2) ? L("Tried to register registered instance: " + l2) : Q[l2] = this;
        };
        f.__destruct = function() {
          this === f && L("Pass correct 'this' to __destruct");
          Ma(this);
          var l2 = this.M.O;
          l2 = Ia(e2, l2);
          Q.hasOwnProperty(l2) ? delete Q[l2] : L("Tried to unregister unregistered instance: " + l2);
        };
        a.prototype = Object.create(f);
        for (var m in c3) a.prototype[m] = c3[m];
        return Ea(a);
      }, "q"),
      j: /* @__PURE__ */ __name(function(a) {
        var b = Va[a];
        delete Va[a];
        var c3 = b.fa, d = b.W, e2 = b.ia, f = e2.map((g) => g.ta).concat(e2.map((g) => g.za));
        V2([a], f, (g) => {
          var k = {};
          e2.forEach((m, l2) => {
            var n2 = g[l2], p = m.ra, r3 = m.sa, u = g[l2 + e2.length], t2 = m.ya, y = m.Aa;
            k[m.oa] = { read: /* @__PURE__ */ __name((B) => n2.fromWireType(p(r3, B)), "read"), write: /* @__PURE__ */ __name((B, ba) => {
              var I2 = [];
              t2(
                y,
                B,
                u.toWireType(I2, ba)
              );
              Wa(I2);
            }, "write") };
          });
          return [{ name: b.name, fromWireType: /* @__PURE__ */ __name(function(m) {
            var l2 = {}, n2;
            for (n2 in k) l2[n2] = k[n2].read(m);
            d(m);
            return l2;
          }, "fromWireType"), toWireType: /* @__PURE__ */ __name(function(m, l2) {
            for (var n2 in k) if (!(n2 in l2)) throw new TypeError('Missing field:  "' + n2 + '"');
            var p = c3();
            for (n2 in k) k[n2].write(p, l2[n2]);
            null !== m && m.push(d, p);
            return p;
          }, "toWireType"), argPackAdvance: 8, readValueFromPointer: Xa, V: d }];
        });
      }, "j"),
      v: /* @__PURE__ */ __name(function() {
      }, "v"),
      B: /* @__PURE__ */ __name(function(a, b, c3, d, e2) {
        var f = Za(c3);
        b = N(b);
        W(a, {
          name: b,
          fromWireType: /* @__PURE__ */ __name(function(g) {
            return !!g;
          }, "fromWireType"),
          toWireType: /* @__PURE__ */ __name(function(g, k) {
            return k ? d : e2;
          }, "toWireType"),
          argPackAdvance: 8,
          readValueFromPointer: /* @__PURE__ */ __name(function(g) {
            if (1 === c3) var k = ja;
            else if (2 === c3) k = C;
            else if (4 === c3) k = D;
            else throw new TypeError("Unknown boolean type size: " + b);
            return this.fromWireType(k[g >> f]);
          }, "readValueFromPointer"),
          V: null
        });
      }, "B"),
      f: /* @__PURE__ */ __name(function(a, b, c3, d, e2, f, g, k, m, l2, n2, p, r3) {
        n2 = N(n2);
        f = Z(e2, f);
        k && (k = Z(g, k));
        l2 && (l2 = Z(m, l2));
        r3 = Z(p, r3);
        var u = Aa(n2);
        bb(u, function() {
          nb("Cannot construct " + n2 + " due to unbound types", [d]);
        });
        V2([a, b, c3], d ? [d] : [], function(t2) {
          t2 = t2[0];
          if (d) {
            var y = t2.N;
            var B = y.X;
          } else B = X.prototype;
          t2 = Ba(u, function() {
            if (Object.getPrototypeOf(this) !== ba) throw new K("Use 'new' to construct " + n2);
            if (void 0 === I2.Y) throw new K(n2 + " has no accessible constructor");
            var kb = I2.Y[arguments.length];
            if (void 0 === kb) throw new K("Tried to invoke ctor of " + n2 + " with invalid number of parameters (" + arguments.length + ") - expected (" + Object.keys(I2.Y).toString() + ") parameters instead!");
            return kb.apply(this, arguments);
          });
          var ba = Object.create(B, { constructor: { value: t2 } });
          t2.prototype = ba;
          var I2 = new cb(n2, t2, ba, r3, y, f, k, l2);
          y = new Y(n2, I2, true, false);
          B = new Y(n2 + "*", I2, false, false);
          var lb = new Y(n2 + " const*", I2, false, true);
          Qa[a] = {
            pointerType: B,
            la: lb
          };
          ib(u, t2);
          return [y, B, lb];
        });
      }, "f"),
      d: /* @__PURE__ */ __name(function(a, b, c3, d, e2, f, g) {
        var k = pb(c3, d);
        b = N(b);
        f = Z(e2, f);
        V2([], [a], function(m) {
          function l2() {
            nb("Cannot call " + n2 + " due to unbound types", k);
          }
          __name(l2, "l");
          m = m[0];
          var n2 = m.name + "." + b;
          b.startsWith("@@") && (b = Symbol[b.substring(2)]);
          var p = m.N.constructor;
          void 0 === p[b] ? (l2.Z = c3 - 1, p[b] = l2) : (ab2(p, b, n2), p[b].S[c3 - 1] = l2);
          V2([], k, function(r3) {
            r3 = ob(n2, [r3[0], null].concat(r3.slice(1)), null, f, g);
            void 0 === p[b].S ? (r3.Z = c3 - 1, p[b] = r3) : p[b].S[c3 - 1] = r3;
            return [];
          });
          return [];
        });
      }, "d"),
      p: /* @__PURE__ */ __name(function(a, b, c3, d, e2, f) {
        0 < b || x();
        var g = pb(
          b,
          c3
        );
        e2 = Z(d, e2);
        V2([], [a], function(k) {
          k = k[0];
          var m = "constructor " + k.name;
          void 0 === k.N.Y && (k.N.Y = []);
          if (void 0 !== k.N.Y[b - 1]) throw new K("Cannot register multiple constructors with identical number of parameters (" + (b - 1) + ") for class '" + k.name + "'! Overload resolution is currently only performed using the parameter count, not actual type info!");
          k.N.Y[b - 1] = () => {
            nb("Cannot construct " + k.name + " due to unbound types", g);
          };
          V2([], g, function(l2) {
            l2.splice(1, 0, null);
            k.N.Y[b - 1] = ob(m, l2, null, e2, f);
            return [];
          });
          return [];
        });
      }, "p"),
      a: /* @__PURE__ */ __name(function(a, b, c3, d, e2, f, g, k) {
        var m = pb(c3, d);
        b = N(b);
        f = Z(e2, f);
        V2([], [a], function(l2) {
          function n2() {
            nb("Cannot call " + p + " due to unbound types", m);
          }
          __name(n2, "n");
          l2 = l2[0];
          var p = l2.name + "." + b;
          b.startsWith("@@") && (b = Symbol[b.substring(2)]);
          k && l2.N.ja.push(b);
          var r3 = l2.N.X, u = r3[b];
          void 0 === u || void 0 === u.S && u.className !== l2.name && u.Z === c3 - 2 ? (n2.Z = c3 - 2, n2.className = l2.name, r3[b] = n2) : (ab2(r3, b, p), r3[b].S[c3 - 2] = n2);
          V2([], m, function(t2) {
            t2 = ob(p, t2, l2, f, g);
            void 0 === r3[b].S ? (t2.Z = c3 - 2, r3[b] = t2) : r3[b].S[c3 - 2] = t2;
            return [];
          });
          return [];
        });
      }, "a"),
      A: /* @__PURE__ */ __name(function(a, b) {
        b = N(b);
        W(
          a,
          { name: b, fromWireType: /* @__PURE__ */ __name(function(c3) {
            var d = M(c3);
            qb(c3);
            return d;
          }, "fromWireType"), toWireType: /* @__PURE__ */ __name(function(c3, d) {
            return Ea(d);
          }, "toWireType"), argPackAdvance: 8, readValueFromPointer: Xa, V: null }
        );
      }, "A"),
      n: /* @__PURE__ */ __name(function(a, b, c3) {
        c3 = Za(c3);
        b = N(b);
        W(a, { name: b, fromWireType: /* @__PURE__ */ __name(function(d) {
          return d;
        }, "fromWireType"), toWireType: /* @__PURE__ */ __name(function(d, e2) {
          return e2;
        }, "toWireType"), argPackAdvance: 8, readValueFromPointer: rb(b, c3), V: null });
      }, "n"),
      e: /* @__PURE__ */ __name(function(a, b, c3, d, e2) {
        b = N(b);
        -1 === e2 && (e2 = 4294967295);
        e2 = Za(c3);
        var f = /* @__PURE__ */ __name((k) => k, "f");
        if (0 === d) {
          var g = 32 - 8 * c3;
          f = /* @__PURE__ */ __name((k) => k << g >>> g, "f");
        }
        c3 = b.includes("unsigned") ? function(k, m) {
          return m >>> 0;
        } : function(k, m) {
          return m;
        };
        W(a, { name: b, fromWireType: f, toWireType: c3, argPackAdvance: 8, readValueFromPointer: sb(b, e2, 0 !== d), V: null });
      }, "e"),
      b: /* @__PURE__ */ __name(function(a, b, c3) {
        function d(f) {
          f >>= 2;
          var g = E;
          return new e2(ia, g[f + 1], g[f]);
        }
        __name(d, "d");
        var e2 = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array][b];
        c3 = N(c3);
        W(a, { name: c3, fromWireType: d, argPackAdvance: 8, readValueFromPointer: d }, { ua: true });
      }, "b"),
      o: /* @__PURE__ */ __name(function(a, b) {
        b = N(b);
        var c3 = "std::string" === b;
        W(a, { name: b, fromWireType: /* @__PURE__ */ __name(function(d) {
          var e2 = E[d >> 2], f = d + 4;
          if (c3) for (var g = f, k = 0; k <= e2; ++k) {
            var m = f + k;
            if (k == e2 || 0 == A[m]) {
              g = g ? z(A, g, m - g) : "";
              if (void 0 === l2) var l2 = g;
              else l2 += String.fromCharCode(0), l2 += g;
              g = m + 1;
            }
          }
          else {
            l2 = Array(e2);
            for (k = 0; k < e2; ++k) l2[k] = String.fromCharCode(A[f + k]);
            l2 = l2.join("");
          }
          S(d);
          return l2;
        }, "fromWireType"), toWireType: /* @__PURE__ */ __name(function(d, e2) {
          e2 instanceof ArrayBuffer && (e2 = new Uint8Array(e2));
          var f, g = "string" == typeof e2;
          g || e2 instanceof Uint8Array || e2 instanceof Uint8ClampedArray || e2 instanceof Int8Array || L("Cannot pass non-string to std::string");
          if (c3 && g) {
            var k = 0;
            for (f = 0; f < e2.length; ++f) {
              var m = e2.charCodeAt(f);
              127 >= m ? k++ : 2047 >= m ? k += 2 : 55296 <= m && 57343 >= m ? (k += 4, ++f) : k += 3;
            }
            f = k;
          } else f = e2.length;
          k = Ib(4 + f + 1);
          m = k + 4;
          E[k >> 2] = f;
          if (c3 && g) {
            if (g = m, m = f + 1, f = A, 0 < m) {
              m = g + m - 1;
              for (var l2 = 0; l2 < e2.length; ++l2) {
                var n2 = e2.charCodeAt(l2);
                if (55296 <= n2 && 57343 >= n2) {
                  var p = e2.charCodeAt(++l2);
                  n2 = 65536 + ((n2 & 1023) << 10) | p & 1023;
                }
                if (127 >= n2) {
                  if (g >= m) break;
                  f[g++] = n2;
                } else {
                  if (2047 >= n2) {
                    if (g + 1 >= m) break;
                    f[g++] = 192 | n2 >> 6;
                  } else {
                    if (65535 >= n2) {
                      if (g + 2 >= m) break;
                      f[g++] = 224 | n2 >> 12;
                    } else {
                      if (g + 3 >= m) break;
                      f[g++] = 240 | n2 >> 18;
                      f[g++] = 128 | n2 >> 12 & 63;
                    }
                    f[g++] = 128 | n2 >> 6 & 63;
                  }
                  f[g++] = 128 | n2 & 63;
                }
              }
              f[g] = 0;
            }
          } else if (g) for (g = 0; g < f; ++g) l2 = e2.charCodeAt(g), 255 < l2 && (S(m), L("String has UTF-16 code units that do not fit in 8 bits")), A[m + g] = l2;
          else for (g = 0; g < f; ++g) A[m + g] = e2[g];
          null !== d && d.push(S, k);
          return k;
        }, "toWireType"), argPackAdvance: 8, readValueFromPointer: Xa, V: /* @__PURE__ */ __name(function(d) {
          S(d);
        }, "V") });
      }, "o"),
      i: /* @__PURE__ */ __name(function(a, b, c3) {
        c3 = N(c3);
        if (2 === b) {
          var d = tb;
          var e2 = ub;
          var f = vb;
          var g = /* @__PURE__ */ __name(() => ka, "g");
          var k = 1;
        } else 4 === b && (d = wb, e2 = xb, f = yb, g = /* @__PURE__ */ __name(() => E, "g"), k = 2);
        W(a, { name: c3, fromWireType: /* @__PURE__ */ __name(function(m) {
          for (var l2 = E[m >> 2], n2 = g(), p, r3 = m + 4, u = 0; u <= l2; ++u) {
            var t2 = m + 4 + u * b;
            if (u == l2 || 0 == n2[t2 >> k]) r3 = d(r3, t2 - r3), void 0 === p ? p = r3 : (p += String.fromCharCode(0), p += r3), r3 = t2 + b;
          }
          S(m);
          return p;
        }, "fromWireType"), toWireType: /* @__PURE__ */ __name(function(m, l2) {
          "string" != typeof l2 && L("Cannot pass non-string to C++ string type " + c3);
          var n2 = f(l2), p = Ib(4 + n2 + b);
          E[p >> 2] = n2 >> k;
          e2(l2, p + 4, n2 + b);
          null !== m && m.push(S, p);
          return p;
        }, "toWireType"), argPackAdvance: 8, readValueFromPointer: Xa, V: /* @__PURE__ */ __name(function(m) {
          S(m);
        }, "V") });
      }, "i"),
      k: /* @__PURE__ */ __name(function(a, b, c3, d, e2, f) {
        Va[a] = { name: N(b), fa: Z(c3, d), W: Z(e2, f), ia: [] };
      }, "k"),
      h: /* @__PURE__ */ __name(function(a, b, c3, d, e2, f, g, k, m, l2) {
        Va[a].ia.push({ oa: N(b), ta: c3, ra: Z(d, e2), sa: f, za: g, ya: Z(k, m), Aa: l2 });
      }, "h"),
      C: /* @__PURE__ */ __name(function(a, b) {
        b = N(b);
        W(a, {
          va: true,
          name: b,
          argPackAdvance: 0,
          fromWireType: /* @__PURE__ */ __name(function() {
          }, "fromWireType"),
          toWireType: /* @__PURE__ */ __name(function() {
          }, "toWireType")
        });
      }, "C"),
      s: /* @__PURE__ */ __name(function(a, b, c3, d, e2) {
        a = Bb[a];
        b = M(b);
        c3 = Ab(c3);
        var f = [];
        E[d >> 2] = Ea(f);
        return a(b, c3, f, e2);
      }, "s"),
      t: /* @__PURE__ */ __name(function(a, b, c3, d) {
        a = Bb[a];
        b = M(b);
        c3 = Ab(c3);
        a(b, c3, null, d);
      }, "t"),
      g: qb,
      m: /* @__PURE__ */ __name(function(a, b) {
        var c3 = Db(a, b), d = c3[0];
        b = d.name + "_$" + c3.slice(1).map(function(g) {
          return g.name;
        }).join("_") + "$";
        var e2 = Eb[b];
        if (void 0 !== e2) return e2;
        var f = Array(a - 1);
        e2 = Cb((g, k, m, l2) => {
          for (var n2 = 0, p = 0; p < a - 1; ++p) f[p] = c3[p + 1].readValueFromPointer(l2 + n2), n2 += c3[p + 1].argPackAdvance;
          g = g[k].apply(
            g,
            f
          );
          for (p = 0; p < a - 1; ++p) c3[p + 1].ma && c3[p + 1].ma(f[p]);
          if (!d.va) return d.toWireType(m, g);
        });
        return Eb[b] = e2;
      }, "m"),
      D: /* @__PURE__ */ __name(function(a) {
        4 < a && (J[a].ga += 1);
      }, "D"),
      r: /* @__PURE__ */ __name(function(a) {
        var b = M(a);
        Wa(b);
        qb(a);
      }, "r"),
      c: /* @__PURE__ */ __name(function() {
        x("");
      }, "c"),
      x: /* @__PURE__ */ __name(function(a, b, c3) {
        A.copyWithin(a, b, b + c3);
      }, "x"),
      w: /* @__PURE__ */ __name(function(a) {
        var b = A.length;
        a >>>= 0;
        if (2147483648 < a) return false;
        for (var c3 = 1; 4 >= c3; c3 *= 2) {
          var d = b * (1 + 0.2 / c3);
          d = Math.min(d, a + 100663296);
          var e2 = Math;
          d = Math.max(a, d);
          e2 = e2.min.call(e2, 2147483648, d + (65536 - d % 65536) % 65536);
          a: {
            try {
              fa.grow(e2 - ia.byteLength + 65535 >>> 16);
              na();
              var f = 1;
              break a;
            } catch (g) {
            }
            f = void 0;
          }
          if (f) return true;
        }
        return false;
      }, "w"),
      z: /* @__PURE__ */ __name(function() {
        return 52;
      }, "z"),
      u: /* @__PURE__ */ __name(function() {
        return 70;
      }, "u"),
      y: /* @__PURE__ */ __name(function(a, b, c3, d) {
        for (var e2 = 0, f = 0; f < c3; f++) {
          var g = E[b >> 2], k = E[b + 4 >> 2];
          b += 8;
          for (var m = 0; m < k; m++) {
            var l2 = A[g + m], n2 = Fb[a];
            0 === l2 || 10 === l2 ? ((1 === a ? ea : v)(z(n2, 0)), n2.length = 0) : n2.push(l2);
          }
          e2 += k;
        }
        E[d >> 2] = e2;
        return 0;
      }, "y")
    };
    (function() {
      function a(e2) {
        h.asm = e2.exports;
        fa = h.asm.E;
        na();
        oa = h.asm.J;
        qa.unshift(h.asm.F);
        F--;
        h.monitorRunDependencies && h.monitorRunDependencies(F);
        0 == F && (null !== ta && (clearInterval(ta), ta = null), G && (e2 = G, G = null, e2()));
      }
      __name(a, "a");
      function b(e2) {
        a(e2.instance);
      }
      __name(b, "b");
      function c3(e2) {
        return ya().then(function(f) {
          return WebAssembly.instantiate(f, d);
        }).then(function(f) {
          return f;
        }).then(e2, function(f) {
          v("failed to asynchronously prepare wasm: " + f);
          x(f);
        });
      }
      __name(c3, "c");
      var d = { a: Jb };
      F++;
      h.monitorRunDependencies && h.monitorRunDependencies(F);
      if (h.instantiateWasm) try {
        return h.instantiateWasm(
          d,
          a
        );
      } catch (e2) {
        v("Module.instantiateWasm callback failed with error: " + e2), ca(e2);
      }
      (function() {
        return w || "function" != typeof WebAssembly.instantiateStreaming || ua(H) || "function" != typeof fetch ? c3(b) : fetch(H, { credentials: "same-origin" }).then(function(e2) {
          return WebAssembly.instantiateStreaming(e2, d).then(b, function(f) {
            v("wasm streaming compile failed: " + f);
            v("falling back to ArrayBuffer instantiation");
            return c3(b);
          });
        });
      })().catch(ca);
      return {};
    })();
    h.___wasm_call_ctors = function() {
      return (h.___wasm_call_ctors = h.asm.F).apply(null, arguments);
    };
    var Ka = h.___getTypeName = function() {
      return (Ka = h.___getTypeName = h.asm.G).apply(null, arguments);
    };
    h.__embind_initialize_bindings = function() {
      return (h.__embind_initialize_bindings = h.asm.H).apply(null, arguments);
    };
    var Ib = h._malloc = function() {
      return (Ib = h._malloc = h.asm.I).apply(null, arguments);
    }, S = h._free = function() {
      return (S = h._free = h.asm.K).apply(null, arguments);
    };
    h.dynCall_jiji = function() {
      return (h.dynCall_jiji = h.asm.L).apply(null, arguments);
    };
    var Kb;
    G = /* @__PURE__ */ __name(function Lb() {
      Kb || Mb();
      Kb || (G = Lb);
    }, "Lb");
    function Mb() {
      function a() {
        if (!Kb && (Kb = true, h.calledRun = true, !ha)) {
          za(qa);
          aa(h);
          if (h.onRuntimeInitialized) h.onRuntimeInitialized();
          if (h.postRun) for ("function" == typeof h.postRun && (h.postRun = [h.postRun]); h.postRun.length; ) {
            var b = h.postRun.shift();
            ra.unshift(b);
          }
          za(ra);
        }
      }
      __name(a, "a");
      if (!(0 < F)) {
        if (h.preRun) for ("function" == typeof h.preRun && (h.preRun = [h.preRun]); h.preRun.length; ) sa();
        za(pa);
        0 < F || (h.setStatus ? (h.setStatus("Running..."), setTimeout(function() {
          setTimeout(function() {
            h.setStatus("");
          }, 1);
          a();
        }, 1)) : a());
      }
    }
    __name(Mb, "Mb");
    if (h.preInit) for ("function" == typeof h.preInit && (h.preInit = [h.preInit]); 0 < h.preInit.length; ) h.preInit.pop()();
    Mb();
    return loadYoga2.ready;
  };
})();
var yoga_wasm_base64_esm_default = loadYoga;

// node_modules/yoga-layout/dist/src/wrapAssembly.js
init_esbuild_shims();

// node_modules/yoga-layout/dist/src/generated/YGEnums.js
init_esbuild_shims();
var Align = /* @__PURE__ */ function(Align2) {
  Align2[Align2["Auto"] = 0] = "Auto";
  Align2[Align2["FlexStart"] = 1] = "FlexStart";
  Align2[Align2["Center"] = 2] = "Center";
  Align2[Align2["FlexEnd"] = 3] = "FlexEnd";
  Align2[Align2["Stretch"] = 4] = "Stretch";
  Align2[Align2["Baseline"] = 5] = "Baseline";
  Align2[Align2["SpaceBetween"] = 6] = "SpaceBetween";
  Align2[Align2["SpaceAround"] = 7] = "SpaceAround";
  Align2[Align2["SpaceEvenly"] = 8] = "SpaceEvenly";
  return Align2;
}({});
var BoxSizing = /* @__PURE__ */ function(BoxSizing2) {
  BoxSizing2[BoxSizing2["BorderBox"] = 0] = "BorderBox";
  BoxSizing2[BoxSizing2["ContentBox"] = 1] = "ContentBox";
  return BoxSizing2;
}({});
var Dimension = /* @__PURE__ */ function(Dimension2) {
  Dimension2[Dimension2["Width"] = 0] = "Width";
  Dimension2[Dimension2["Height"] = 1] = "Height";
  return Dimension2;
}({});
var Direction = /* @__PURE__ */ function(Direction2) {
  Direction2[Direction2["Inherit"] = 0] = "Inherit";
  Direction2[Direction2["LTR"] = 1] = "LTR";
  Direction2[Direction2["RTL"] = 2] = "RTL";
  return Direction2;
}({});
var Display = /* @__PURE__ */ function(Display2) {
  Display2[Display2["Flex"] = 0] = "Flex";
  Display2[Display2["None"] = 1] = "None";
  Display2[Display2["Contents"] = 2] = "Contents";
  return Display2;
}({});
var Edge = /* @__PURE__ */ function(Edge2) {
  Edge2[Edge2["Left"] = 0] = "Left";
  Edge2[Edge2["Top"] = 1] = "Top";
  Edge2[Edge2["Right"] = 2] = "Right";
  Edge2[Edge2["Bottom"] = 3] = "Bottom";
  Edge2[Edge2["Start"] = 4] = "Start";
  Edge2[Edge2["End"] = 5] = "End";
  Edge2[Edge2["Horizontal"] = 6] = "Horizontal";
  Edge2[Edge2["Vertical"] = 7] = "Vertical";
  Edge2[Edge2["All"] = 8] = "All";
  return Edge2;
}({});
var Errata = /* @__PURE__ */ function(Errata2) {
  Errata2[Errata2["None"] = 0] = "None";
  Errata2[Errata2["StretchFlexBasis"] = 1] = "StretchFlexBasis";
  Errata2[Errata2["AbsolutePositionWithoutInsetsExcludesPadding"] = 2] = "AbsolutePositionWithoutInsetsExcludesPadding";
  Errata2[Errata2["AbsolutePercentAgainstInnerSize"] = 4] = "AbsolutePercentAgainstInnerSize";
  Errata2[Errata2["All"] = 2147483647] = "All";
  Errata2[Errata2["Classic"] = 2147483646] = "Classic";
  return Errata2;
}({});
var ExperimentalFeature = /* @__PURE__ */ function(ExperimentalFeature2) {
  ExperimentalFeature2[ExperimentalFeature2["WebFlexBasis"] = 0] = "WebFlexBasis";
  return ExperimentalFeature2;
}({});
var FlexDirection = /* @__PURE__ */ function(FlexDirection2) {
  FlexDirection2[FlexDirection2["Column"] = 0] = "Column";
  FlexDirection2[FlexDirection2["ColumnReverse"] = 1] = "ColumnReverse";
  FlexDirection2[FlexDirection2["Row"] = 2] = "Row";
  FlexDirection2[FlexDirection2["RowReverse"] = 3] = "RowReverse";
  return FlexDirection2;
}({});
var Gutter = /* @__PURE__ */ function(Gutter2) {
  Gutter2[Gutter2["Column"] = 0] = "Column";
  Gutter2[Gutter2["Row"] = 1] = "Row";
  Gutter2[Gutter2["All"] = 2] = "All";
  return Gutter2;
}({});
var Justify = /* @__PURE__ */ function(Justify2) {
  Justify2[Justify2["FlexStart"] = 0] = "FlexStart";
  Justify2[Justify2["Center"] = 1] = "Center";
  Justify2[Justify2["FlexEnd"] = 2] = "FlexEnd";
  Justify2[Justify2["SpaceBetween"] = 3] = "SpaceBetween";
  Justify2[Justify2["SpaceAround"] = 4] = "SpaceAround";
  Justify2[Justify2["SpaceEvenly"] = 5] = "SpaceEvenly";
  return Justify2;
}({});
var LogLevel = /* @__PURE__ */ function(LogLevel2) {
  LogLevel2[LogLevel2["Error"] = 0] = "Error";
  LogLevel2[LogLevel2["Warn"] = 1] = "Warn";
  LogLevel2[LogLevel2["Info"] = 2] = "Info";
  LogLevel2[LogLevel2["Debug"] = 3] = "Debug";
  LogLevel2[LogLevel2["Verbose"] = 4] = "Verbose";
  LogLevel2[LogLevel2["Fatal"] = 5] = "Fatal";
  return LogLevel2;
}({});
var MeasureMode = /* @__PURE__ */ function(MeasureMode2) {
  MeasureMode2[MeasureMode2["Undefined"] = 0] = "Undefined";
  MeasureMode2[MeasureMode2["Exactly"] = 1] = "Exactly";
  MeasureMode2[MeasureMode2["AtMost"] = 2] = "AtMost";
  return MeasureMode2;
}({});
var NodeType = /* @__PURE__ */ function(NodeType2) {
  NodeType2[NodeType2["Default"] = 0] = "Default";
  NodeType2[NodeType2["Text"] = 1] = "Text";
  return NodeType2;
}({});
var Overflow = /* @__PURE__ */ function(Overflow2) {
  Overflow2[Overflow2["Visible"] = 0] = "Visible";
  Overflow2[Overflow2["Hidden"] = 1] = "Hidden";
  Overflow2[Overflow2["Scroll"] = 2] = "Scroll";
  return Overflow2;
}({});
var PositionType = /* @__PURE__ */ function(PositionType2) {
  PositionType2[PositionType2["Static"] = 0] = "Static";
  PositionType2[PositionType2["Relative"] = 1] = "Relative";
  PositionType2[PositionType2["Absolute"] = 2] = "Absolute";
  return PositionType2;
}({});
var Unit = /* @__PURE__ */ function(Unit2) {
  Unit2[Unit2["Undefined"] = 0] = "Undefined";
  Unit2[Unit2["Point"] = 1] = "Point";
  Unit2[Unit2["Percent"] = 2] = "Percent";
  Unit2[Unit2["Auto"] = 3] = "Auto";
  return Unit2;
}({});
var Wrap = /* @__PURE__ */ function(Wrap2) {
  Wrap2[Wrap2["NoWrap"] = 0] = "NoWrap";
  Wrap2[Wrap2["Wrap"] = 1] = "Wrap";
  Wrap2[Wrap2["WrapReverse"] = 2] = "WrapReverse";
  return Wrap2;
}({});
var constants = {
  ALIGN_AUTO: Align.Auto,
  ALIGN_FLEX_START: Align.FlexStart,
  ALIGN_CENTER: Align.Center,
  ALIGN_FLEX_END: Align.FlexEnd,
  ALIGN_STRETCH: Align.Stretch,
  ALIGN_BASELINE: Align.Baseline,
  ALIGN_SPACE_BETWEEN: Align.SpaceBetween,
  ALIGN_SPACE_AROUND: Align.SpaceAround,
  ALIGN_SPACE_EVENLY: Align.SpaceEvenly,
  BOX_SIZING_BORDER_BOX: BoxSizing.BorderBox,
  BOX_SIZING_CONTENT_BOX: BoxSizing.ContentBox,
  DIMENSION_WIDTH: Dimension.Width,
  DIMENSION_HEIGHT: Dimension.Height,
  DIRECTION_INHERIT: Direction.Inherit,
  DIRECTION_LTR: Direction.LTR,
  DIRECTION_RTL: Direction.RTL,
  DISPLAY_FLEX: Display.Flex,
  DISPLAY_NONE: Display.None,
  DISPLAY_CONTENTS: Display.Contents,
  EDGE_LEFT: Edge.Left,
  EDGE_TOP: Edge.Top,
  EDGE_RIGHT: Edge.Right,
  EDGE_BOTTOM: Edge.Bottom,
  EDGE_START: Edge.Start,
  EDGE_END: Edge.End,
  EDGE_HORIZONTAL: Edge.Horizontal,
  EDGE_VERTICAL: Edge.Vertical,
  EDGE_ALL: Edge.All,
  ERRATA_NONE: Errata.None,
  ERRATA_STRETCH_FLEX_BASIS: Errata.StretchFlexBasis,
  ERRATA_ABSOLUTE_POSITION_WITHOUT_INSETS_EXCLUDES_PADDING: Errata.AbsolutePositionWithoutInsetsExcludesPadding,
  ERRATA_ABSOLUTE_PERCENT_AGAINST_INNER_SIZE: Errata.AbsolutePercentAgainstInnerSize,
  ERRATA_ALL: Errata.All,
  ERRATA_CLASSIC: Errata.Classic,
  EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS: ExperimentalFeature.WebFlexBasis,
  FLEX_DIRECTION_COLUMN: FlexDirection.Column,
  FLEX_DIRECTION_COLUMN_REVERSE: FlexDirection.ColumnReverse,
  FLEX_DIRECTION_ROW: FlexDirection.Row,
  FLEX_DIRECTION_ROW_REVERSE: FlexDirection.RowReverse,
  GUTTER_COLUMN: Gutter.Column,
  GUTTER_ROW: Gutter.Row,
  GUTTER_ALL: Gutter.All,
  JUSTIFY_FLEX_START: Justify.FlexStart,
  JUSTIFY_CENTER: Justify.Center,
  JUSTIFY_FLEX_END: Justify.FlexEnd,
  JUSTIFY_SPACE_BETWEEN: Justify.SpaceBetween,
  JUSTIFY_SPACE_AROUND: Justify.SpaceAround,
  JUSTIFY_SPACE_EVENLY: Justify.SpaceEvenly,
  LOG_LEVEL_ERROR: LogLevel.Error,
  LOG_LEVEL_WARN: LogLevel.Warn,
  LOG_LEVEL_INFO: LogLevel.Info,
  LOG_LEVEL_DEBUG: LogLevel.Debug,
  LOG_LEVEL_VERBOSE: LogLevel.Verbose,
  LOG_LEVEL_FATAL: LogLevel.Fatal,
  MEASURE_MODE_UNDEFINED: MeasureMode.Undefined,
  MEASURE_MODE_EXACTLY: MeasureMode.Exactly,
  MEASURE_MODE_AT_MOST: MeasureMode.AtMost,
  NODE_TYPE_DEFAULT: NodeType.Default,
  NODE_TYPE_TEXT: NodeType.Text,
  OVERFLOW_VISIBLE: Overflow.Visible,
  OVERFLOW_HIDDEN: Overflow.Hidden,
  OVERFLOW_SCROLL: Overflow.Scroll,
  POSITION_TYPE_STATIC: PositionType.Static,
  POSITION_TYPE_RELATIVE: PositionType.Relative,
  POSITION_TYPE_ABSOLUTE: PositionType.Absolute,
  UNIT_UNDEFINED: Unit.Undefined,
  UNIT_POINT: Unit.Point,
  UNIT_PERCENT: Unit.Percent,
  UNIT_AUTO: Unit.Auto,
  WRAP_NO_WRAP: Wrap.NoWrap,
  WRAP_WRAP: Wrap.Wrap,
  WRAP_WRAP_REVERSE: Wrap.WrapReverse
};
var YGEnums_default = constants;

// node_modules/yoga-layout/dist/src/wrapAssembly.js
function wrapAssembly(lib) {
  function patch(prototype, name3, fn) {
    const original = prototype[name3];
    prototype[name3] = function() {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      return fn.call(this, original, ...args);
    };
  }
  __name(patch, "patch");
  for (const fnName of ["setPosition", "setMargin", "setFlexBasis", "setWidth", "setHeight", "setMinWidth", "setMinHeight", "setMaxWidth", "setMaxHeight", "setPadding", "setGap"]) {
    const methods = {
      [Unit.Point]: lib.Node.prototype[fnName],
      [Unit.Percent]: lib.Node.prototype[`${fnName}Percent`],
      [Unit.Auto]: lib.Node.prototype[`${fnName}Auto`]
    };
    patch(lib.Node.prototype, fnName, function(original) {
      for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        args[_key2 - 1] = arguments[_key2];
      }
      const value = args.pop();
      let unit, asNumber2;
      if (value === "auto") {
        unit = Unit.Auto;
        asNumber2 = void 0;
      } else if (typeof value === "object") {
        unit = value.unit;
        asNumber2 = value.valueOf();
      } else {
        unit = typeof value === "string" && value.endsWith("%") ? Unit.Percent : Unit.Point;
        asNumber2 = parseFloat(value);
        if (value !== void 0 && !Number.isNaN(value) && Number.isNaN(asNumber2)) {
          throw new Error(`Invalid value ${value} for ${fnName}`);
        }
      }
      if (!methods[unit]) throw new Error(`Failed to execute "${fnName}": Unsupported unit '${value}'`);
      if (asNumber2 !== void 0) {
        return methods[unit].call(this, ...args, asNumber2);
      } else {
        return methods[unit].call(this, ...args);
      }
    });
  }
  function wrapMeasureFunction(measureFunction) {
    return lib.MeasureCallback.implement({
      measure: /* @__PURE__ */ __name(function() {
        const {
          width,
          height
        } = measureFunction(...arguments);
        return {
          width: width ?? NaN,
          height: height ?? NaN
        };
      }, "measure")
    });
  }
  __name(wrapMeasureFunction, "wrapMeasureFunction");
  patch(lib.Node.prototype, "setMeasureFunc", function(original, measureFunc) {
    if (measureFunc) {
      return original.call(this, wrapMeasureFunction(measureFunc));
    } else {
      return this.unsetMeasureFunc();
    }
  });
  function wrapDirtiedFunc(dirtiedFunction) {
    return lib.DirtiedCallback.implement({
      dirtied: dirtiedFunction
    });
  }
  __name(wrapDirtiedFunc, "wrapDirtiedFunc");
  patch(lib.Node.prototype, "setDirtiedFunc", function(original, dirtiedFunc) {
    original.call(this, wrapDirtiedFunc(dirtiedFunc));
  });
  patch(lib.Config.prototype, "free", function() {
    lib.Config.destroy(this);
  });
  patch(lib.Node, "create", (_, config) => {
    return config ? lib.Node.createWithConfig(config) : lib.Node.createDefault();
  });
  patch(lib.Node.prototype, "free", function() {
    lib.Node.destroy(this);
  });
  patch(lib.Node.prototype, "freeRecursive", function() {
    for (let t2 = 0, T = this.getChildCount(); t2 < T; ++t2) {
      this.getChild(0).freeRecursive();
    }
    this.free();
  });
  patch(lib.Node.prototype, "calculateLayout", function(original) {
    let width = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : NaN;
    let height = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : NaN;
    let direction = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : Direction.LTR;
    return original.call(this, width, height, direction);
  });
  return {
    Config: lib.Config,
    Node: lib.Node,
    ...YGEnums_default
  };
}
__name(wrapAssembly, "wrapAssembly");

// node_modules/yoga-layout/dist/src/index.js
var Yoga = wrapAssembly(await yoga_wasm_base64_esm_default());
var src_default = Yoga;

// node_modules/wrap-ansi/index.js
init_esbuild_shims();

// node_modules/wrap-ansi/node_modules/string-width/index.js
init_esbuild_shims();
init_strip_ansi();

// node_modules/get-east-asian-width/index.js
init_esbuild_shims();

// node_modules/get-east-asian-width/lookup.js
init_esbuild_shims();
function isAmbiguous(x) {
  return x === 161 || x === 164 || x === 167 || x === 168 || x === 170 || x === 173 || x === 174 || x >= 176 && x <= 180 || x >= 182 && x <= 186 || x >= 188 && x <= 191 || x === 198 || x === 208 || x === 215 || x === 216 || x >= 222 && x <= 225 || x === 230 || x >= 232 && x <= 234 || x === 236 || x === 237 || x === 240 || x === 242 || x === 243 || x >= 247 && x <= 250 || x === 252 || x === 254 || x === 257 || x === 273 || x === 275 || x === 283 || x === 294 || x === 295 || x === 299 || x >= 305 && x <= 307 || x === 312 || x >= 319 && x <= 322 || x === 324 || x >= 328 && x <= 331 || x === 333 || x === 338 || x === 339 || x === 358 || x === 359 || x === 363 || x === 462 || x === 464 || x === 466 || x === 468 || x === 470 || x === 472 || x === 474 || x === 476 || x === 593 || x === 609 || x === 708 || x === 711 || x >= 713 && x <= 715 || x === 717 || x === 720 || x >= 728 && x <= 731 || x === 733 || x === 735 || x >= 768 && x <= 879 || x >= 913 && x <= 929 || x >= 931 && x <= 937 || x >= 945 && x <= 961 || x >= 963 && x <= 969 || x === 1025 || x >= 1040 && x <= 1103 || x === 1105 || x === 8208 || x >= 8211 && x <= 8214 || x === 8216 || x === 8217 || x === 8220 || x === 8221 || x >= 8224 && x <= 8226 || x >= 8228 && x <= 8231 || x === 8240 || x === 8242 || x === 8243 || x === 8245 || x === 8251 || x === 8254 || x === 8308 || x === 8319 || x >= 8321 && x <= 8324 || x === 8364 || x === 8451 || x === 8453 || x === 8457 || x === 8467 || x === 8470 || x === 8481 || x === 8482 || x === 8486 || x === 8491 || x === 8531 || x === 8532 || x >= 8539 && x <= 8542 || x >= 8544 && x <= 8555 || x >= 8560 && x <= 8569 || x === 8585 || x >= 8592 && x <= 8601 || x === 8632 || x === 8633 || x === 8658 || x === 8660 || x === 8679 || x === 8704 || x === 8706 || x === 8707 || x === 8711 || x === 8712 || x === 8715 || x === 8719 || x === 8721 || x === 8725 || x === 8730 || x >= 8733 && x <= 8736 || x === 8739 || x === 8741 || x >= 8743 && x <= 8748 || x === 8750 || x >= 8756 && x <= 8759 || x === 8764 || x === 8765 || x === 8776 || x === 8780 || x === 8786 || x === 8800 || x === 8801 || x >= 8804 && x <= 8807 || x === 8810 || x === 8811 || x === 8814 || x === 8815 || x === 8834 || x === 8835 || x === 8838 || x === 8839 || x === 8853 || x === 8857 || x === 8869 || x === 8895 || x === 8978 || x >= 9312 && x <= 9449 || x >= 9451 && x <= 9547 || x >= 9552 && x <= 9587 || x >= 9600 && x <= 9615 || x >= 9618 && x <= 9621 || x === 9632 || x === 9633 || x >= 9635 && x <= 9641 || x === 9650 || x === 9651 || x === 9654 || x === 9655 || x === 9660 || x === 9661 || x === 9664 || x === 9665 || x >= 9670 && x <= 9672 || x === 9675 || x >= 9678 && x <= 9681 || x >= 9698 && x <= 9701 || x === 9711 || x === 9733 || x === 9734 || x === 9737 || x === 9742 || x === 9743 || x === 9756 || x === 9758 || x === 9792 || x === 9794 || x === 9824 || x === 9825 || x >= 9827 && x <= 9829 || x >= 9831 && x <= 9834 || x === 9836 || x === 9837 || x === 9839 || x === 9886 || x === 9887 || x === 9919 || x >= 9926 && x <= 9933 || x >= 9935 && x <= 9939 || x >= 9941 && x <= 9953 || x === 9955 || x === 9960 || x === 9961 || x >= 9963 && x <= 9969 || x === 9972 || x >= 9974 && x <= 9977 || x === 9979 || x === 9980 || x === 9982 || x === 9983 || x === 10045 || x >= 10102 && x <= 10111 || x >= 11094 && x <= 11097 || x >= 12872 && x <= 12879 || x >= 57344 && x <= 63743 || x >= 65024 && x <= 65039 || x === 65533 || x >= 127232 && x <= 127242 || x >= 127248 && x <= 127277 || x >= 127280 && x <= 127337 || x >= 127344 && x <= 127373 || x === 127375 || x === 127376 || x >= 127387 && x <= 127404 || x >= 917760 && x <= 917999 || x >= 983040 && x <= 1048573 || x >= 1048576 && x <= 1114109;
}
__name(isAmbiguous, "isAmbiguous");
function isFullWidth(x) {
  return x === 12288 || x >= 65281 && x <= 65376 || x >= 65504 && x <= 65510;
}
__name(isFullWidth, "isFullWidth");
function isWide(x) {
  return x >= 4352 && x <= 4447 || x === 8986 || x === 8987 || x === 9001 || x === 9002 || x >= 9193 && x <= 9196 || x === 9200 || x === 9203 || x === 9725 || x === 9726 || x === 9748 || x === 9749 || x >= 9776 && x <= 9783 || x >= 9800 && x <= 9811 || x === 9855 || x >= 9866 && x <= 9871 || x === 9875 || x === 9889 || x === 9898 || x === 9899 || x === 9917 || x === 9918 || x === 9924 || x === 9925 || x === 9934 || x === 9940 || x === 9962 || x === 9970 || x === 9971 || x === 9973 || x === 9978 || x === 9981 || x === 9989 || x === 9994 || x === 9995 || x === 10024 || x === 10060 || x === 10062 || x >= 10067 && x <= 10069 || x === 10071 || x >= 10133 && x <= 10135 || x === 10160 || x === 10175 || x === 11035 || x === 11036 || x === 11088 || x === 11093 || x >= 11904 && x <= 11929 || x >= 11931 && x <= 12019 || x >= 12032 && x <= 12245 || x >= 12272 && x <= 12287 || x >= 12289 && x <= 12350 || x >= 12353 && x <= 12438 || x >= 12441 && x <= 12543 || x >= 12549 && x <= 12591 || x >= 12593 && x <= 12686 || x >= 12688 && x <= 12773 || x >= 12783 && x <= 12830 || x >= 12832 && x <= 12871 || x >= 12880 && x <= 42124 || x >= 42128 && x <= 42182 || x >= 43360 && x <= 43388 || x >= 44032 && x <= 55203 || x >= 63744 && x <= 64255 || x >= 65040 && x <= 65049 || x >= 65072 && x <= 65106 || x >= 65108 && x <= 65126 || x >= 65128 && x <= 65131 || x >= 94176 && x <= 94180 || x === 94192 || x === 94193 || x >= 94208 && x <= 100343 || x >= 100352 && x <= 101589 || x >= 101631 && x <= 101640 || x >= 110576 && x <= 110579 || x >= 110581 && x <= 110587 || x === 110589 || x === 110590 || x >= 110592 && x <= 110882 || x === 110898 || x >= 110928 && x <= 110930 || x === 110933 || x >= 110948 && x <= 110951 || x >= 110960 && x <= 111355 || x >= 119552 && x <= 119638 || x >= 119648 && x <= 119670 || x === 126980 || x === 127183 || x === 127374 || x >= 127377 && x <= 127386 || x >= 127488 && x <= 127490 || x >= 127504 && x <= 127547 || x >= 127552 && x <= 127560 || x === 127568 || x === 127569 || x >= 127584 && x <= 127589 || x >= 127744 && x <= 127776 || x >= 127789 && x <= 127797 || x >= 127799 && x <= 127868 || x >= 127870 && x <= 127891 || x >= 127904 && x <= 127946 || x >= 127951 && x <= 127955 || x >= 127968 && x <= 127984 || x === 127988 || x >= 127992 && x <= 128062 || x === 128064 || x >= 128066 && x <= 128252 || x >= 128255 && x <= 128317 || x >= 128331 && x <= 128334 || x >= 128336 && x <= 128359 || x === 128378 || x === 128405 || x === 128406 || x === 128420 || x >= 128507 && x <= 128591 || x >= 128640 && x <= 128709 || x === 128716 || x >= 128720 && x <= 128722 || x >= 128725 && x <= 128727 || x >= 128732 && x <= 128735 || x === 128747 || x === 128748 || x >= 128756 && x <= 128764 || x >= 128992 && x <= 129003 || x === 129008 || x >= 129292 && x <= 129338 || x >= 129340 && x <= 129349 || x >= 129351 && x <= 129535 || x >= 129648 && x <= 129660 || x >= 129664 && x <= 129673 || x >= 129679 && x <= 129734 || x >= 129742 && x <= 129756 || x >= 129759 && x <= 129769 || x >= 129776 && x <= 129784 || x >= 131072 && x <= 196605 || x >= 196608 && x <= 262141;
}
__name(isWide, "isWide");

// node_modules/get-east-asian-width/index.js
function validate(codePoint) {
  if (!Number.isSafeInteger(codePoint)) {
    throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
  }
}
__name(validate, "validate");
function eastAsianWidth(codePoint, { ambiguousAsWide = false } = {}) {
  validate(codePoint);
  if (isFullWidth(codePoint) || isWide(codePoint) || ambiguousAsWide && isAmbiguous(codePoint)) {
    return 2;
  }
  return 1;
}
__name(eastAsianWidth, "eastAsianWidth");

// node_modules/wrap-ansi/node_modules/string-width/index.js
var import_emoji_regex = __toESM(require_emoji_regex(), 1);
var segmenter = new Intl.Segmenter();
var defaultIgnorableCodePointRegex = new RegExp("^\\p{Default_Ignorable_Code_Point}$", "u");
function stringWidth(string, options2 = {}) {
  if (typeof string !== "string" || string.length === 0) {
    return 0;
  }
  const {
    ambiguousIsNarrow = true,
    countAnsiEscapeCodes = false
  } = options2;
  if (!countAnsiEscapeCodes) {
    string = stripAnsi(string);
  }
  if (string.length === 0) {
    return 0;
  }
  let width = 0;
  const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
  for (const { segment: character } of segmenter.segment(string)) {
    const codePoint = character.codePointAt(0);
    if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159) {
      continue;
    }
    if (codePoint >= 8203 && codePoint <= 8207 || codePoint === 65279) {
      continue;
    }
    if (codePoint >= 768 && codePoint <= 879 || codePoint >= 6832 && codePoint <= 6911 || codePoint >= 7616 && codePoint <= 7679 || codePoint >= 8400 && codePoint <= 8447 || codePoint >= 65056 && codePoint <= 65071) {
      continue;
    }
    if (codePoint >= 55296 && codePoint <= 57343) {
      continue;
    }
    if (codePoint >= 65024 && codePoint <= 65039) {
      continue;
    }
    if (defaultIgnorableCodePointRegex.test(character)) {
      continue;
    }
    if ((0, import_emoji_regex.default)().test(character)) {
      width += 2;
      continue;
    }
    width += eastAsianWidth(codePoint, eastAsianWidthOptions);
  }
  return width;
}
__name(stringWidth, "stringWidth");

// node_modules/wrap-ansi/index.js
init_strip_ansi();

// node_modules/wrap-ansi/node_modules/ansi-styles/index.js
init_esbuild_shims();
var ANSI_BACKGROUND_OFFSET = 10;
var wrapAnsi16 = /* @__PURE__ */ __name((offset = 0) => (code2) => `\x1B[${code2 + offset}m`, "wrapAnsi16");
var wrapAnsi256 = /* @__PURE__ */ __name((offset = 0) => (code2) => `\x1B[${38 + offset};5;${code2}m`, "wrapAnsi256");
var wrapAnsi16m = /* @__PURE__ */ __name((offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`, "wrapAnsi16m");
var styles = {
  modifier: {
    reset: [0, 0],
    // 21 isn't widely supported and 22 does the same thing
    bold: [1, 22],
    dim: [2, 22],
    italic: [3, 23],
    underline: [4, 24],
    overline: [53, 55],
    inverse: [7, 27],
    hidden: [8, 28],
    strikethrough: [9, 29]
  },
  color: {
    black: [30, 39],
    red: [31, 39],
    green: [32, 39],
    yellow: [33, 39],
    blue: [34, 39],
    magenta: [35, 39],
    cyan: [36, 39],
    white: [37, 39],
    // Bright color
    blackBright: [90, 39],
    gray: [90, 39],
    // Alias of `blackBright`
    grey: [90, 39],
    // Alias of `blackBright`
    redBright: [91, 39],
    greenBright: [92, 39],
    yellowBright: [93, 39],
    blueBright: [94, 39],
    magentaBright: [95, 39],
    cyanBright: [96, 39],
    whiteBright: [97, 39]
  },
  bgColor: {
    bgBlack: [40, 49],
    bgRed: [41, 49],
    bgGreen: [42, 49],
    bgYellow: [43, 49],
    bgBlue: [44, 49],
    bgMagenta: [45, 49],
    bgCyan: [46, 49],
    bgWhite: [47, 49],
    // Bright color
    bgBlackBright: [100, 49],
    bgGray: [100, 49],
    // Alias of `bgBlackBright`
    bgGrey: [100, 49],
    // Alias of `bgBlackBright`
    bgRedBright: [101, 49],
    bgGreenBright: [102, 49],
    bgYellowBright: [103, 49],
    bgBlueBright: [104, 49],
    bgMagentaBright: [105, 49],
    bgCyanBright: [106, 49],
    bgWhiteBright: [107, 49]
  }
};
var modifierNames = Object.keys(styles.modifier);
var foregroundColorNames = Object.keys(styles.color);
var backgroundColorNames = Object.keys(styles.bgColor);
var colorNames = [...foregroundColorNames, ...backgroundColorNames];
function assembleStyles() {
  const codes = /* @__PURE__ */ new Map();
  for (const [groupName, group] of Object.entries(styles)) {
    for (const [styleName, style] of Object.entries(group)) {
      styles[styleName] = {
        open: `\x1B[${style[0]}m`,
        close: `\x1B[${style[1]}m`
      };
      group[styleName] = styles[styleName];
      codes.set(style[0], style[1]);
    }
    Object.defineProperty(styles, groupName, {
      value: group,
      enumerable: false
    });
  }
  Object.defineProperty(styles, "codes", {
    value: codes,
    enumerable: false
  });
  styles.color.close = "\x1B[39m";
  styles.bgColor.close = "\x1B[49m";
  styles.color.ansi = wrapAnsi16();
  styles.color.ansi256 = wrapAnsi256();
  styles.color.ansi16m = wrapAnsi16m();
  styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
  styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
  styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
  Object.defineProperties(styles, {
    rgbToAnsi256: {
      value: /* @__PURE__ */ __name((red, green, blue) => {
        if (red === green && green === blue) {
          if (red < 8) {
            return 16;
          }
          if (red > 248) {
            return 231;
          }
          return Math.round((red - 8) / 247 * 24) + 232;
        }
        return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
      }, "value"),
      enumerable: false
    },
    hexToRgb: {
      value: /* @__PURE__ */ __name((hex) => {
        const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches) {
          return [0, 0, 0];
        }
        let [colorString] = matches;
        if (colorString.length === 3) {
          colorString = [...colorString].map((character) => character + character).join("");
        }
        const integer = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer >> 16 & 255,
          integer >> 8 & 255,
          integer & 255
          /* eslint-enable no-bitwise */
        ];
      }, "value"),
      enumerable: false
    },
    hexToAnsi256: {
      value: /* @__PURE__ */ __name((hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)), "value"),
      enumerable: false
    },
    ansi256ToAnsi: {
      value: /* @__PURE__ */ __name((code2) => {
        if (code2 < 8) {
          return 30 + code2;
        }
        if (code2 < 16) {
          return 90 + (code2 - 8);
        }
        let red;
        let green;
        let blue;
        if (code2 >= 232) {
          red = ((code2 - 232) * 10 + 8) / 255;
          green = red;
          blue = red;
        } else {
          code2 -= 16;
          const remainder = code2 % 36;
          red = Math.floor(code2 / 36) / 5;
          green = Math.floor(remainder / 6) / 5;
          blue = remainder % 6 / 5;
        }
        const value = Math.max(red, green, blue) * 2;
        if (value === 0) {
          return 30;
        }
        let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
        if (value === 2) {
          result += 60;
        }
        return result;
      }, "value"),
      enumerable: false
    },
    rgbToAnsi: {
      value: /* @__PURE__ */ __name((red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), "value"),
      enumerable: false
    },
    hexToAnsi: {
      value: /* @__PURE__ */ __name((hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), "value"),
      enumerable: false
    }
  });
  return styles;
}
__name(assembleStyles, "assembleStyles");
var ansiStyles = assembleStyles();
var ansi_styles_default = ansiStyles;

// node_modules/wrap-ansi/index.js
var ESCAPES = /* @__PURE__ */ new Set([
  "\x1B",
  "\x9B"
]);
var END_CODE = 39;
var ANSI_ESCAPE_BELL = "\x07";
var ANSI_CSI = "[";
var ANSI_OSC = "]";
var ANSI_SGR_TERMINATOR = "m";
var ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
var wrapAnsiCode = /* @__PURE__ */ __name((code2) => `${ESCAPES.values().next().value}${ANSI_CSI}${code2}${ANSI_SGR_TERMINATOR}`, "wrapAnsiCode");
var wrapAnsiHyperlink = /* @__PURE__ */ __name((url2) => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${url2}${ANSI_ESCAPE_BELL}`, "wrapAnsiHyperlink");
var wordLengths = /* @__PURE__ */ __name((string) => string.split(" ").map((character) => stringWidth(character)), "wordLengths");
var wrapWord = /* @__PURE__ */ __name((rows, word, columns) => {
  const characters = [...word];
  let isInsideEscape = false;
  let isInsideLinkEscape = false;
  let visible = stringWidth(stripAnsi(rows.at(-1)));
  for (const [index, character] of characters.entries()) {
    const characterLength = stringWidth(character);
    if (visible + characterLength <= columns) {
      rows[rows.length - 1] += character;
    } else {
      rows.push(character);
      visible = 0;
    }
    if (ESCAPES.has(character)) {
      isInsideEscape = true;
      const ansiEscapeLinkCandidate = characters.slice(index + 1, index + 1 + ANSI_ESCAPE_LINK.length).join("");
      isInsideLinkEscape = ansiEscapeLinkCandidate === ANSI_ESCAPE_LINK;
    }
    if (isInsideEscape) {
      if (isInsideLinkEscape) {
        if (character === ANSI_ESCAPE_BELL) {
          isInsideEscape = false;
          isInsideLinkEscape = false;
        }
      } else if (character === ANSI_SGR_TERMINATOR) {
        isInsideEscape = false;
      }
      continue;
    }
    visible += characterLength;
    if (visible === columns && index < characters.length - 1) {
      rows.push("");
      visible = 0;
    }
  }
  if (!visible && rows.at(-1).length > 0 && rows.length > 1) {
    rows[rows.length - 2] += rows.pop();
  }
}, "wrapWord");
var stringVisibleTrimSpacesRight = /* @__PURE__ */ __name((string) => {
  const words = string.split(" ");
  let last2 = words.length;
  while (last2 > 0) {
    if (stringWidth(words[last2 - 1]) > 0) {
      break;
    }
    last2--;
  }
  if (last2 === words.length) {
    return string;
  }
  return words.slice(0, last2).join(" ") + words.slice(last2).join("");
}, "stringVisibleTrimSpacesRight");
var exec = /* @__PURE__ */ __name((string, columns, options2 = {}) => {
  if (options2.trim !== false && string.trim() === "") {
    return "";
  }
  let returnValue = "";
  let escapeCode;
  let escapeUrl;
  const lengths = wordLengths(string);
  let rows = [""];
  for (const [index, word] of string.split(" ").entries()) {
    if (options2.trim !== false) {
      rows[rows.length - 1] = rows.at(-1).trimStart();
    }
    let rowLength = stringWidth(rows.at(-1));
    if (index !== 0) {
      if (rowLength >= columns && (options2.wordWrap === false || options2.trim === false)) {
        rows.push("");
        rowLength = 0;
      }
      if (rowLength > 0 || options2.trim === false) {
        rows[rows.length - 1] += " ";
        rowLength++;
      }
    }
    if (options2.hard && lengths[index] > columns) {
      const remainingColumns = columns - rowLength;
      const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);
      const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);
      if (breaksStartingNextLine < breaksStartingThisLine) {
        rows.push("");
      }
      wrapWord(rows, word, columns);
      continue;
    }
    if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {
      if (options2.wordWrap === false && rowLength < columns) {
        wrapWord(rows, word, columns);
        continue;
      }
      rows.push("");
    }
    if (rowLength + lengths[index] > columns && options2.wordWrap === false) {
      wrapWord(rows, word, columns);
      continue;
    }
    rows[rows.length - 1] += word;
  }
  if (options2.trim !== false) {
    rows = rows.map((row) => stringVisibleTrimSpacesRight(row));
  }
  const preString = rows.join("\n");
  const pre = [...preString];
  let preStringIndex = 0;
  for (const [index, character] of pre.entries()) {
    returnValue += character;
    if (ESCAPES.has(character)) {
      const { groups } = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).exec(preString.slice(preStringIndex)) || { groups: {} };
      if (groups.code !== void 0) {
        const code3 = Number.parseFloat(groups.code);
        escapeCode = code3 === END_CODE ? void 0 : code3;
      } else if (groups.uri !== void 0) {
        escapeUrl = groups.uri.length === 0 ? void 0 : groups.uri;
      }
    }
    const code2 = ansi_styles_default.codes.get(Number(escapeCode));
    if (pre[index + 1] === "\n") {
      if (escapeUrl) {
        returnValue += wrapAnsiHyperlink("");
      }
      if (escapeCode && code2) {
        returnValue += wrapAnsiCode(code2);
      }
    } else if (character === "\n") {
      if (escapeCode && code2) {
        returnValue += wrapAnsiCode(escapeCode);
      }
      if (escapeUrl) {
        returnValue += wrapAnsiHyperlink(escapeUrl);
      }
    }
    preStringIndex += character.length;
  }
  return returnValue;
}, "exec");
function wrapAnsi(string, columns, options2) {
  return String(string).normalize().replaceAll("\r\n", "\n").split("\n").map((line) => exec(line, columns, options2)).join("\n");
}
__name(wrapAnsi, "wrapAnsi");

// node_modules/ink/build/reconciler.js
init_esbuild_shims();
var import_react_reconciler = __toESM(require_react_reconciler(), 1);
var import_constants = __toESM(require_constants(), 1);
import process3 from "node:process";
var import_react = __toESM(require_react(), 1);

// node_modules/ink/build/dom.js
init_esbuild_shims();

// node_modules/ink/build/measure-text.js
init_esbuild_shims();

// node_modules/ink/node_modules/widest-line/index.js
init_esbuild_shims();

// node_modules/ink/node_modules/string-width/index.js
init_esbuild_shims();
init_strip_ansi();
var import_emoji_regex2 = __toESM(require_emoji_regex2(), 1);
var segmenter2 = new Intl.Segmenter();
var defaultIgnorableCodePointRegex2 = new RegExp("^\\p{Default_Ignorable_Code_Point}$", "u");
function stringWidth2(string, options2 = {}) {
  if (typeof string !== "string" || string.length === 0) {
    return 0;
  }
  const {
    ambiguousIsNarrow = true,
    countAnsiEscapeCodes = false
  } = options2;
  if (!countAnsiEscapeCodes) {
    string = stripAnsi(string);
  }
  if (string.length === 0) {
    return 0;
  }
  let width = 0;
  const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
  for (const { segment: character } of segmenter2.segment(string)) {
    const codePoint = character.codePointAt(0);
    if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159) {
      continue;
    }
    if (codePoint >= 8203 && codePoint <= 8207 || codePoint === 65279) {
      continue;
    }
    if (codePoint >= 768 && codePoint <= 879 || codePoint >= 6832 && codePoint <= 6911 || codePoint >= 7616 && codePoint <= 7679 || codePoint >= 8400 && codePoint <= 8447 || codePoint >= 65056 && codePoint <= 65071) {
      continue;
    }
    if (codePoint >= 55296 && codePoint <= 57343) {
      continue;
    }
    if (codePoint >= 65024 && codePoint <= 65039) {
      continue;
    }
    if (defaultIgnorableCodePointRegex2.test(character)) {
      continue;
    }
    if ((0, import_emoji_regex2.default)().test(character)) {
      width += 2;
      continue;
    }
    width += eastAsianWidth(codePoint, eastAsianWidthOptions);
  }
  return width;
}
__name(stringWidth2, "stringWidth");

// node_modules/ink/node_modules/widest-line/index.js
function widestLine(string) {
  let lineWidth = 0;
  for (const line of string.split("\n")) {
    lineWidth = Math.max(lineWidth, stringWidth2(line));
  }
  return lineWidth;
}
__name(widestLine, "widestLine");

// node_modules/ink/build/measure-text.js
var cache = /* @__PURE__ */ new Map();
var measureText = /* @__PURE__ */ __name((text) => {
  if (text.length === 0) {
    return {
      width: 0,
      height: 0
    };
  }
  const cachedDimensions = cache.get(text);
  if (cachedDimensions) {
    return cachedDimensions;
  }
  const width = widestLine(text);
  const height = text.split("\n").length;
  const dimensions = { width, height };
  cache.set(text, dimensions);
  return dimensions;
}, "measureText");
var measure_text_default = measureText;

// node_modules/ink/build/wrap-text.js
init_esbuild_shims();

// node_modules/cli-truncate/index.js
init_esbuild_shims();

// node_modules/cli-truncate/node_modules/slice-ansi/index.js
init_esbuild_shims();

// node_modules/cli-truncate/node_modules/is-fullwidth-code-point/index.js
init_esbuild_shims();
function isFullwidthCodePoint(codePoint) {
  if (!Number.isInteger(codePoint)) {
    return false;
  }
  return codePoint >= 4352 && (codePoint <= 4447 || // Hangul Jamo
  codePoint === 9001 || // LEFT-POINTING ANGLE BRACKET
  codePoint === 9002 || // RIGHT-POINTING ANGLE BRACKET
  // CJK Radicals Supplement .. Enclosed CJK Letters and Months
  11904 <= codePoint && codePoint <= 12871 && codePoint !== 12351 || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
  12880 <= codePoint && codePoint <= 19903 || // CJK Unified Ideographs .. Yi Radicals
  19968 <= codePoint && codePoint <= 42182 || // Hangul Jamo Extended-A
  43360 <= codePoint && codePoint <= 43388 || // Hangul Syllables
  44032 <= codePoint && codePoint <= 55203 || // CJK Compatibility Ideographs
  63744 <= codePoint && codePoint <= 64255 || // Vertical Forms
  65040 <= codePoint && codePoint <= 65049 || // CJK Compatibility Forms .. Small Form Variants
  65072 <= codePoint && codePoint <= 65131 || // Halfwidth and Fullwidth Forms
  65281 <= codePoint && codePoint <= 65376 || 65504 <= codePoint && codePoint <= 65510 || // Kana Supplement
  110592 <= codePoint && codePoint <= 110593 || // Enclosed Ideographic Supplement
  127488 <= codePoint && codePoint <= 127569 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
  131072 <= codePoint && codePoint <= 262141);
}
__name(isFullwidthCodePoint, "isFullwidthCodePoint");

// node_modules/cli-truncate/node_modules/ansi-styles/index.js
init_esbuild_shims();
var ANSI_BACKGROUND_OFFSET2 = 10;
var wrapAnsi162 = /* @__PURE__ */ __name((offset = 0) => (code2) => `\x1B[${code2 + offset}m`, "wrapAnsi16");
var wrapAnsi2562 = /* @__PURE__ */ __name((offset = 0) => (code2) => `\x1B[${38 + offset};5;${code2}m`, "wrapAnsi256");
var wrapAnsi16m2 = /* @__PURE__ */ __name((offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`, "wrapAnsi16m");
var styles2 = {
  modifier: {
    reset: [0, 0],
    // 21 isn't widely supported and 22 does the same thing
    bold: [1, 22],
    dim: [2, 22],
    italic: [3, 23],
    underline: [4, 24],
    overline: [53, 55],
    inverse: [7, 27],
    hidden: [8, 28],
    strikethrough: [9, 29]
  },
  color: {
    black: [30, 39],
    red: [31, 39],
    green: [32, 39],
    yellow: [33, 39],
    blue: [34, 39],
    magenta: [35, 39],
    cyan: [36, 39],
    white: [37, 39],
    // Bright color
    blackBright: [90, 39],
    gray: [90, 39],
    // Alias of `blackBright`
    grey: [90, 39],
    // Alias of `blackBright`
    redBright: [91, 39],
    greenBright: [92, 39],
    yellowBright: [93, 39],
    blueBright: [94, 39],
    magentaBright: [95, 39],
    cyanBright: [96, 39],
    whiteBright: [97, 39]
  },
  bgColor: {
    bgBlack: [40, 49],
    bgRed: [41, 49],
    bgGreen: [42, 49],
    bgYellow: [43, 49],
    bgBlue: [44, 49],
    bgMagenta: [45, 49],
    bgCyan: [46, 49],
    bgWhite: [47, 49],
    // Bright color
    bgBlackBright: [100, 49],
    bgGray: [100, 49],
    // Alias of `bgBlackBright`
    bgGrey: [100, 49],
    // Alias of `bgBlackBright`
    bgRedBright: [101, 49],
    bgGreenBright: [102, 49],
    bgYellowBright: [103, 49],
    bgBlueBright: [104, 49],
    bgMagentaBright: [105, 49],
    bgCyanBright: [106, 49],
    bgWhiteBright: [107, 49]
  }
};
var modifierNames2 = Object.keys(styles2.modifier);
var foregroundColorNames2 = Object.keys(styles2.color);
var backgroundColorNames2 = Object.keys(styles2.bgColor);
var colorNames2 = [...foregroundColorNames2, ...backgroundColorNames2];
function assembleStyles2() {
  const codes = /* @__PURE__ */ new Map();
  for (const [groupName, group] of Object.entries(styles2)) {
    for (const [styleName, style] of Object.entries(group)) {
      styles2[styleName] = {
        open: `\x1B[${style[0]}m`,
        close: `\x1B[${style[1]}m`
      };
      group[styleName] = styles2[styleName];
      codes.set(style[0], style[1]);
    }
    Object.defineProperty(styles2, groupName, {
      value: group,
      enumerable: false
    });
  }
  Object.defineProperty(styles2, "codes", {
    value: codes,
    enumerable: false
  });
  styles2.color.close = "\x1B[39m";
  styles2.bgColor.close = "\x1B[49m";
  styles2.color.ansi = wrapAnsi162();
  styles2.color.ansi256 = wrapAnsi2562();
  styles2.color.ansi16m = wrapAnsi16m2();
  styles2.bgColor.ansi = wrapAnsi162(ANSI_BACKGROUND_OFFSET2);
  styles2.bgColor.ansi256 = wrapAnsi2562(ANSI_BACKGROUND_OFFSET2);
  styles2.bgColor.ansi16m = wrapAnsi16m2(ANSI_BACKGROUND_OFFSET2);
  Object.defineProperties(styles2, {
    rgbToAnsi256: {
      value: /* @__PURE__ */ __name((red, green, blue) => {
        if (red === green && green === blue) {
          if (red < 8) {
            return 16;
          }
          if (red > 248) {
            return 231;
          }
          return Math.round((red - 8) / 247 * 24) + 232;
        }
        return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
      }, "value"),
      enumerable: false
    },
    hexToRgb: {
      value: /* @__PURE__ */ __name((hex) => {
        const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches) {
          return [0, 0, 0];
        }
        let [colorString] = matches;
        if (colorString.length === 3) {
          colorString = [...colorString].map((character) => character + character).join("");
        }
        const integer = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer >> 16 & 255,
          integer >> 8 & 255,
          integer & 255
          /* eslint-enable no-bitwise */
        ];
      }, "value"),
      enumerable: false
    },
    hexToAnsi256: {
      value: /* @__PURE__ */ __name((hex) => styles2.rgbToAnsi256(...styles2.hexToRgb(hex)), "value"),
      enumerable: false
    },
    ansi256ToAnsi: {
      value: /* @__PURE__ */ __name((code2) => {
        if (code2 < 8) {
          return 30 + code2;
        }
        if (code2 < 16) {
          return 90 + (code2 - 8);
        }
        let red;
        let green;
        let blue;
        if (code2 >= 232) {
          red = ((code2 - 232) * 10 + 8) / 255;
          green = red;
          blue = red;
        } else {
          code2 -= 16;
          const remainder = code2 % 36;
          red = Math.floor(code2 / 36) / 5;
          green = Math.floor(remainder / 6) / 5;
          blue = remainder % 6 / 5;
        }
        const value = Math.max(red, green, blue) * 2;
        if (value === 0) {
          return 30;
        }
        let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
        if (value === 2) {
          result += 60;
        }
        return result;
      }, "value"),
      enumerable: false
    },
    rgbToAnsi: {
      value: /* @__PURE__ */ __name((red, green, blue) => styles2.ansi256ToAnsi(styles2.rgbToAnsi256(red, green, blue)), "value"),
      enumerable: false
    },
    hexToAnsi: {
      value: /* @__PURE__ */ __name((hex) => styles2.ansi256ToAnsi(styles2.hexToAnsi256(hex)), "value"),
      enumerable: false
    }
  });
  return styles2;
}
__name(assembleStyles2, "assembleStyles");
var ansiStyles2 = assembleStyles2();
var ansi_styles_default2 = ansiStyles2;

// node_modules/cli-truncate/node_modules/slice-ansi/index.js
var astralRegex = /^[\uD800-\uDBFF][\uDC00-\uDFFF]$/;
var ESCAPES2 = [
  "\x1B",
  "\x9B"
];
var wrapAnsi2 = /* @__PURE__ */ __name((code2) => `${ESCAPES2[0]}[${code2}m`, "wrapAnsi");
var checkAnsi = /* @__PURE__ */ __name((ansiCodes, isEscapes, endAnsiCode) => {
  let output = [];
  ansiCodes = [...ansiCodes];
  for (let ansiCode of ansiCodes) {
    const ansiCodeOrigin = ansiCode;
    if (ansiCode.includes(";")) {
      ansiCode = ansiCode.split(";")[0][0] + "0";
    }
    const item = ansi_styles_default2.codes.get(Number.parseInt(ansiCode, 10));
    if (item) {
      const indexEscape = ansiCodes.indexOf(item.toString());
      if (indexEscape === -1) {
        output.push(wrapAnsi2(isEscapes ? item : ansiCodeOrigin));
      } else {
        ansiCodes.splice(indexEscape, 1);
      }
    } else if (isEscapes) {
      output.push(wrapAnsi2(0));
      break;
    } else {
      output.push(wrapAnsi2(ansiCodeOrigin));
    }
  }
  if (isEscapes) {
    output = output.filter((element, index) => output.indexOf(element) === index);
    if (endAnsiCode !== void 0) {
      const fistEscapeCode = wrapAnsi2(ansi_styles_default2.codes.get(Number.parseInt(endAnsiCode, 10)));
      output = output.reduce((current, next) => next === fistEscapeCode ? [next, ...current] : [...current, next], []);
    }
  }
  return output.join("");
}, "checkAnsi");
function sliceAnsi(string, begin, end) {
  const characters = [...string];
  const ansiCodes = [];
  let stringEnd = typeof end === "number" ? end : characters.length;
  let isInsideEscape = false;
  let ansiCode;
  let visible = 0;
  let output = "";
  for (const [index, character] of characters.entries()) {
    let leftEscape = false;
    if (ESCAPES2.includes(character)) {
      const code2 = /\d[^m]*/.exec(string.slice(index, index + 18));
      ansiCode = code2 && code2.length > 0 ? code2[0] : void 0;
      if (visible < stringEnd) {
        isInsideEscape = true;
        if (ansiCode !== void 0) {
          ansiCodes.push(ansiCode);
        }
      }
    } else if (isInsideEscape && character === "m") {
      isInsideEscape = false;
      leftEscape = true;
    }
    if (!isInsideEscape && !leftEscape) {
      visible++;
    }
    if (!astralRegex.test(character) && isFullwidthCodePoint(character.codePointAt())) {
      visible++;
      if (typeof end !== "number") {
        stringEnd++;
      }
    }
    if (visible > begin && visible <= stringEnd) {
      output += character;
    } else if (visible === begin && !isInsideEscape && ansiCode !== void 0) {
      output = checkAnsi(ansiCodes);
    } else if (visible >= stringEnd) {
      output += checkAnsi(ansiCodes, true, ansiCode);
      break;
    }
  }
  return output;
}
__name(sliceAnsi, "sliceAnsi");

// node_modules/cli-truncate/node_modules/string-width/index.js
init_esbuild_shims();
init_strip_ansi();
var import_emoji_regex3 = __toESM(require_emoji_regex3(), 1);
var segmenter3 = new Intl.Segmenter();
var defaultIgnorableCodePointRegex3 = new RegExp("^\\p{Default_Ignorable_Code_Point}$", "u");
function stringWidth3(string, options2 = {}) {
  if (typeof string !== "string" || string.length === 0) {
    return 0;
  }
  const {
    ambiguousIsNarrow = true,
    countAnsiEscapeCodes = false
  } = options2;
  if (!countAnsiEscapeCodes) {
    string = stripAnsi(string);
  }
  if (string.length === 0) {
    return 0;
  }
  let width = 0;
  const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
  for (const { segment: character } of segmenter3.segment(string)) {
    const codePoint = character.codePointAt(0);
    if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159) {
      continue;
    }
    if (codePoint >= 8203 && codePoint <= 8207 || codePoint === 65279) {
      continue;
    }
    if (codePoint >= 768 && codePoint <= 879 || codePoint >= 6832 && codePoint <= 6911 || codePoint >= 7616 && codePoint <= 7679 || codePoint >= 8400 && codePoint <= 8447 || codePoint >= 65056 && codePoint <= 65071) {
      continue;
    }
    if (codePoint >= 55296 && codePoint <= 57343) {
      continue;
    }
    if (codePoint >= 65024 && codePoint <= 65039) {
      continue;
    }
    if (defaultIgnorableCodePointRegex3.test(character)) {
      continue;
    }
    if ((0, import_emoji_regex3.default)().test(character)) {
      width += 2;
      continue;
    }
    width += eastAsianWidth(codePoint, eastAsianWidthOptions);
  }
  return width;
}
__name(stringWidth3, "stringWidth");

// node_modules/cli-truncate/index.js
function getIndexOfNearestSpace(string, wantedIndex, shouldSearchRight) {
  if (string.charAt(wantedIndex) === " ") {
    return wantedIndex;
  }
  const direction = shouldSearchRight ? 1 : -1;
  for (let index = 0; index <= 3; index++) {
    const finalIndex = wantedIndex + index * direction;
    if (string.charAt(finalIndex) === " ") {
      return finalIndex;
    }
  }
  return wantedIndex;
}
__name(getIndexOfNearestSpace, "getIndexOfNearestSpace");
function cliTruncate(text, columns, options2 = {}) {
  const {
    position = "end",
    space = false,
    preferTruncationOnSpace = false
  } = options2;
  let { truncationCharacter = "\u2026" } = options2;
  if (typeof text !== "string") {
    throw new TypeError(`Expected \`input\` to be a string, got ${typeof text}`);
  }
  if (typeof columns !== "number") {
    throw new TypeError(`Expected \`columns\` to be a number, got ${typeof columns}`);
  }
  if (columns < 1) {
    return "";
  }
  if (columns === 1) {
    return truncationCharacter;
  }
  const length = stringWidth3(text);
  if (length <= columns) {
    return text;
  }
  if (position === "start") {
    if (preferTruncationOnSpace) {
      const nearestSpace = getIndexOfNearestSpace(text, length - columns + 1, true);
      return truncationCharacter + sliceAnsi(text, nearestSpace, length).trim();
    }
    if (space === true) {
      truncationCharacter += " ";
    }
    return truncationCharacter + sliceAnsi(text, length - columns + stringWidth3(truncationCharacter), length);
  }
  if (position === "middle") {
    if (space === true) {
      truncationCharacter = ` ${truncationCharacter} `;
    }
    const half = Math.floor(columns / 2);
    if (preferTruncationOnSpace) {
      const spaceNearFirstBreakPoint = getIndexOfNearestSpace(text, half);
      const spaceNearSecondBreakPoint = getIndexOfNearestSpace(text, length - (columns - half) + 1, true);
      return sliceAnsi(text, 0, spaceNearFirstBreakPoint) + truncationCharacter + sliceAnsi(text, spaceNearSecondBreakPoint, length).trim();
    }
    return sliceAnsi(text, 0, half) + truncationCharacter + sliceAnsi(text, length - (columns - half) + stringWidth3(truncationCharacter), length);
  }
  if (position === "end") {
    if (preferTruncationOnSpace) {
      const nearestSpace = getIndexOfNearestSpace(text, columns - 1);
      return sliceAnsi(text, 0, nearestSpace) + truncationCharacter;
    }
    if (space === true) {
      truncationCharacter = ` ${truncationCharacter}`;
    }
    return sliceAnsi(text, 0, columns - stringWidth3(truncationCharacter)) + truncationCharacter;
  }
  throw new Error(`Expected \`options.position\` to be either \`start\`, \`middle\` or \`end\`, got ${position}`);
}
__name(cliTruncate, "cliTruncate");

// node_modules/ink/build/wrap-text.js
var cache2 = {};
var wrapText = /* @__PURE__ */ __name((text, maxWidth, wrapType) => {
  const cacheKey = text + String(maxWidth) + String(wrapType);
  const cachedText = cache2[cacheKey];
  if (cachedText) {
    return cachedText;
  }
  let wrappedText = text;
  if (wrapType === "wrap") {
    wrappedText = wrapAnsi(text, maxWidth, {
      trim: false,
      hard: true
    });
  }
  if (wrapType.startsWith("truncate")) {
    let position = "end";
    if (wrapType === "truncate-middle") {
      position = "middle";
    }
    if (wrapType === "truncate-start") {
      position = "start";
    }
    wrappedText = cliTruncate(text, maxWidth, { position });
  }
  cache2[cacheKey] = wrappedText;
  return wrappedText;
}, "wrapText");
var wrap_text_default = wrapText;

// node_modules/ink/build/squash-text-nodes.js
init_esbuild_shims();
var squashTextNodes = /* @__PURE__ */ __name((node) => {
  let text = "";
  for (let index = 0; index < node.childNodes.length; index++) {
    const childNode = node.childNodes[index];
    if (childNode === void 0) {
      continue;
    }
    let nodeText = "";
    if (childNode.nodeName === "#text") {
      nodeText = childNode.nodeValue;
    } else {
      if (childNode.nodeName === "ink-text" || childNode.nodeName === "ink-virtual-text") {
        nodeText = squashTextNodes(childNode);
      }
      if (nodeText.length > 0 && typeof childNode.internal_transform === "function") {
        nodeText = childNode.internal_transform(nodeText, index);
      }
    }
    text += nodeText;
  }
  return text;
}, "squashTextNodes");
var squash_text_nodes_default = squashTextNodes;

// node_modules/ink/build/dom.js
var createNode = /* @__PURE__ */ __name((nodeName) => {
  const node = {
    nodeName,
    style: {},
    attributes: {},
    childNodes: [],
    parentNode: void 0,
    yogaNode: nodeName === "ink-virtual-text" ? void 0 : src_default.Node.create(),
    // eslint-disable-next-line @typescript-eslint/naming-convention
    internal_accessibility: {}
  };
  if (nodeName === "ink-text") {
    node.yogaNode?.setMeasureFunc(measureTextNode.bind(null, node));
  }
  return node;
}, "createNode");
var appendChildNode = /* @__PURE__ */ __name((node, childNode) => {
  if (childNode.parentNode) {
    removeChildNode(childNode.parentNode, childNode);
  }
  childNode.parentNode = node;
  node.childNodes.push(childNode);
  if (childNode.yogaNode) {
    node.yogaNode?.insertChild(childNode.yogaNode, node.yogaNode.getChildCount());
  }
  if (node.nodeName === "ink-text" || node.nodeName === "ink-virtual-text") {
    markNodeAsDirty(node);
  }
}, "appendChildNode");
var insertBeforeNode = /* @__PURE__ */ __name((node, newChildNode, beforeChildNode) => {
  if (newChildNode.parentNode) {
    removeChildNode(newChildNode.parentNode, newChildNode);
  }
  newChildNode.parentNode = node;
  const index = node.childNodes.indexOf(beforeChildNode);
  if (index >= 0) {
    node.childNodes.splice(index, 0, newChildNode);
    if (newChildNode.yogaNode) {
      node.yogaNode?.insertChild(newChildNode.yogaNode, index);
    }
    return;
  }
  node.childNodes.push(newChildNode);
  if (newChildNode.yogaNode) {
    node.yogaNode?.insertChild(newChildNode.yogaNode, node.yogaNode.getChildCount());
  }
  if (node.nodeName === "ink-text" || node.nodeName === "ink-virtual-text") {
    markNodeAsDirty(node);
  }
}, "insertBeforeNode");
var removeChildNode = /* @__PURE__ */ __name((node, removeNode) => {
  if (removeNode.yogaNode) {
    removeNode.parentNode?.yogaNode?.removeChild(removeNode.yogaNode);
  }
  removeNode.parentNode = void 0;
  const index = node.childNodes.indexOf(removeNode);
  if (index >= 0) {
    node.childNodes.splice(index, 1);
  }
  if (node.nodeName === "ink-text" || node.nodeName === "ink-virtual-text") {
    markNodeAsDirty(node);
  }
}, "removeChildNode");
var setAttribute = /* @__PURE__ */ __name((node, key, value) => {
  if (key === "internal_accessibility") {
    node.internal_accessibility = value;
    return;
  }
  node.attributes[key] = value;
}, "setAttribute");
var setStyle = /* @__PURE__ */ __name((node, style) => {
  node.style = style;
}, "setStyle");
var createTextNode = /* @__PURE__ */ __name((text) => {
  const node = {
    nodeName: "#text",
    nodeValue: text,
    yogaNode: void 0,
    parentNode: void 0,
    style: {}
  };
  setTextNodeValue(node, text);
  return node;
}, "createTextNode");
var measureTextNode = /* @__PURE__ */ __name(function(node, width) {
  const text = node.nodeName === "#text" ? node.nodeValue : squash_text_nodes_default(node);
  const dimensions = measure_text_default(text);
  if (dimensions.width <= width) {
    return dimensions;
  }
  if (dimensions.width >= 1 && width > 0 && width < 1) {
    return dimensions;
  }
  const textWrap = node.style?.textWrap ?? "wrap";
  const wrappedText = wrap_text_default(text, width, textWrap);
  return measure_text_default(wrappedText);
}, "measureTextNode");
var findClosestYogaNode = /* @__PURE__ */ __name((node) => {
  if (!node?.parentNode) {
    return void 0;
  }
  return node.yogaNode ?? findClosestYogaNode(node.parentNode);
}, "findClosestYogaNode");
var markNodeAsDirty = /* @__PURE__ */ __name((node) => {
  const yogaNode = findClosestYogaNode(node);
  yogaNode?.markDirty();
}, "markNodeAsDirty");
var setTextNodeValue = /* @__PURE__ */ __name((node, text) => {
  if (typeof text !== "string") {
    text = String(text);
  }
  node.nodeValue = text;
  markNodeAsDirty(node);
}, "setTextNodeValue");

// node_modules/ink/build/styles.js
init_esbuild_shims();
var applyPositionStyles = /* @__PURE__ */ __name((node, style) => {
  if ("position" in style) {
    node.setPositionType(style.position === "absolute" ? src_default.POSITION_TYPE_ABSOLUTE : src_default.POSITION_TYPE_RELATIVE);
  }
}, "applyPositionStyles");
var applyMarginStyles = /* @__PURE__ */ __name((node, style) => {
  if ("margin" in style) {
    node.setMargin(src_default.EDGE_ALL, style.margin ?? 0);
  }
  if ("marginX" in style) {
    node.setMargin(src_default.EDGE_HORIZONTAL, style.marginX ?? 0);
  }
  if ("marginY" in style) {
    node.setMargin(src_default.EDGE_VERTICAL, style.marginY ?? 0);
  }
  if ("marginLeft" in style) {
    node.setMargin(src_default.EDGE_START, style.marginLeft || 0);
  }
  if ("marginRight" in style) {
    node.setMargin(src_default.EDGE_END, style.marginRight || 0);
  }
  if ("marginTop" in style) {
    node.setMargin(src_default.EDGE_TOP, style.marginTop || 0);
  }
  if ("marginBottom" in style) {
    node.setMargin(src_default.EDGE_BOTTOM, style.marginBottom || 0);
  }
}, "applyMarginStyles");
var applyPaddingStyles = /* @__PURE__ */ __name((node, style) => {
  if ("padding" in style) {
    node.setPadding(src_default.EDGE_ALL, style.padding ?? 0);
  }
  if ("paddingX" in style) {
    node.setPadding(src_default.EDGE_HORIZONTAL, style.paddingX ?? 0);
  }
  if ("paddingY" in style) {
    node.setPadding(src_default.EDGE_VERTICAL, style.paddingY ?? 0);
  }
  if ("paddingLeft" in style) {
    node.setPadding(src_default.EDGE_LEFT, style.paddingLeft || 0);
  }
  if ("paddingRight" in style) {
    node.setPadding(src_default.EDGE_RIGHT, style.paddingRight || 0);
  }
  if ("paddingTop" in style) {
    node.setPadding(src_default.EDGE_TOP, style.paddingTop || 0);
  }
  if ("paddingBottom" in style) {
    node.setPadding(src_default.EDGE_BOTTOM, style.paddingBottom || 0);
  }
}, "applyPaddingStyles");
var applyFlexStyles = /* @__PURE__ */ __name((node, style) => {
  if ("flexGrow" in style) {
    node.setFlexGrow(style.flexGrow ?? 0);
  }
  if ("flexShrink" in style) {
    node.setFlexShrink(typeof style.flexShrink === "number" ? style.flexShrink : 1);
  }
  if ("flexWrap" in style) {
    if (style.flexWrap === "nowrap") {
      node.setFlexWrap(src_default.WRAP_NO_WRAP);
    }
    if (style.flexWrap === "wrap") {
      node.setFlexWrap(src_default.WRAP_WRAP);
    }
    if (style.flexWrap === "wrap-reverse") {
      node.setFlexWrap(src_default.WRAP_WRAP_REVERSE);
    }
  }
  if ("flexDirection" in style) {
    if (style.flexDirection === "row") {
      node.setFlexDirection(src_default.FLEX_DIRECTION_ROW);
    }
    if (style.flexDirection === "row-reverse") {
      node.setFlexDirection(src_default.FLEX_DIRECTION_ROW_REVERSE);
    }
    if (style.flexDirection === "column") {
      node.setFlexDirection(src_default.FLEX_DIRECTION_COLUMN);
    }
    if (style.flexDirection === "column-reverse") {
      node.setFlexDirection(src_default.FLEX_DIRECTION_COLUMN_REVERSE);
    }
  }
  if ("flexBasis" in style) {
    if (typeof style.flexBasis === "number") {
      node.setFlexBasis(style.flexBasis);
    } else if (typeof style.flexBasis === "string") {
      node.setFlexBasisPercent(Number.parseInt(style.flexBasis, 10));
    } else {
      node.setFlexBasis(Number.NaN);
    }
  }
  if ("alignItems" in style) {
    if (style.alignItems === "stretch" || !style.alignItems) {
      node.setAlignItems(src_default.ALIGN_STRETCH);
    }
    if (style.alignItems === "flex-start") {
      node.setAlignItems(src_default.ALIGN_FLEX_START);
    }
    if (style.alignItems === "center") {
      node.setAlignItems(src_default.ALIGN_CENTER);
    }
    if (style.alignItems === "flex-end") {
      node.setAlignItems(src_default.ALIGN_FLEX_END);
    }
  }
  if ("alignSelf" in style) {
    if (style.alignSelf === "auto" || !style.alignSelf) {
      node.setAlignSelf(src_default.ALIGN_AUTO);
    }
    if (style.alignSelf === "flex-start") {
      node.setAlignSelf(src_default.ALIGN_FLEX_START);
    }
    if (style.alignSelf === "center") {
      node.setAlignSelf(src_default.ALIGN_CENTER);
    }
    if (style.alignSelf === "flex-end") {
      node.setAlignSelf(src_default.ALIGN_FLEX_END);
    }
  }
  if ("justifyContent" in style) {
    if (style.justifyContent === "flex-start" || !style.justifyContent) {
      node.setJustifyContent(src_default.JUSTIFY_FLEX_START);
    }
    if (style.justifyContent === "center") {
      node.setJustifyContent(src_default.JUSTIFY_CENTER);
    }
    if (style.justifyContent === "flex-end") {
      node.setJustifyContent(src_default.JUSTIFY_FLEX_END);
    }
    if (style.justifyContent === "space-between") {
      node.setJustifyContent(src_default.JUSTIFY_SPACE_BETWEEN);
    }
    if (style.justifyContent === "space-around") {
      node.setJustifyContent(src_default.JUSTIFY_SPACE_AROUND);
    }
    if (style.justifyContent === "space-evenly") {
      node.setJustifyContent(src_default.JUSTIFY_SPACE_EVENLY);
    }
  }
}, "applyFlexStyles");
var applyDimensionStyles = /* @__PURE__ */ __name((node, style) => {
  if ("width" in style) {
    if (typeof style.width === "number") {
      node.setWidth(style.width);
    } else if (typeof style.width === "string") {
      node.setWidthPercent(Number.parseInt(style.width, 10));
    } else {
      node.setWidthAuto();
    }
  }
  if ("height" in style) {
    if (typeof style.height === "number") {
      node.setHeight(style.height);
    } else if (typeof style.height === "string") {
      node.setHeightPercent(Number.parseInt(style.height, 10));
    } else {
      node.setHeightAuto();
    }
  }
  if ("minWidth" in style) {
    if (typeof style.minWidth === "string") {
      node.setMinWidthPercent(Number.parseInt(style.minWidth, 10));
    } else {
      node.setMinWidth(style.minWidth ?? 0);
    }
  }
  if ("minHeight" in style) {
    if (typeof style.minHeight === "string") {
      node.setMinHeightPercent(Number.parseInt(style.minHeight, 10));
    } else {
      node.setMinHeight(style.minHeight ?? 0);
    }
  }
}, "applyDimensionStyles");
var applyDisplayStyles = /* @__PURE__ */ __name((node, style) => {
  if ("display" in style) {
    node.setDisplay(style.display === "flex" ? src_default.DISPLAY_FLEX : src_default.DISPLAY_NONE);
  }
}, "applyDisplayStyles");
var applyBorderStyles = /* @__PURE__ */ __name((node, style) => {
  if ("borderStyle" in style) {
    const borderWidth = style.borderStyle ? 1 : 0;
    if (style.borderTop !== false) {
      node.setBorder(src_default.EDGE_TOP, borderWidth);
    }
    if (style.borderBottom !== false) {
      node.setBorder(src_default.EDGE_BOTTOM, borderWidth);
    }
    if (style.borderLeft !== false) {
      node.setBorder(src_default.EDGE_LEFT, borderWidth);
    }
    if (style.borderRight !== false) {
      node.setBorder(src_default.EDGE_RIGHT, borderWidth);
    }
  }
}, "applyBorderStyles");
var applyGapStyles = /* @__PURE__ */ __name((node, style) => {
  if ("gap" in style) {
    node.setGap(src_default.GUTTER_ALL, style.gap ?? 0);
  }
  if ("columnGap" in style) {
    node.setGap(src_default.GUTTER_COLUMN, style.columnGap ?? 0);
  }
  if ("rowGap" in style) {
    node.setGap(src_default.GUTTER_ROW, style.rowGap ?? 0);
  }
}, "applyGapStyles");
var styles3 = /* @__PURE__ */ __name((node, style = {}) => {
  applyPositionStyles(node, style);
  applyMarginStyles(node, style);
  applyPaddingStyles(node, style);
  applyFlexStyles(node, style);
  applyDimensionStyles(node, style);
  applyDisplayStyles(node, style);
  applyBorderStyles(node, style);
  applyGapStyles(node, style);
}, "styles");
var styles_default = styles3;

// node_modules/ink/build/reconciler.js
if (process3.env["DEV"] === "true") {
  try {
    await Promise.resolve().then(() => (init_devtools(), devtools_exports));
  } catch (error) {
    if (error.code === "ERR_MODULE_NOT_FOUND") {
      console.warn(`
The environment variable DEV is set to true, so Ink tried to import \`react-devtools-core\`,
but this failed as it was not installed. Debugging with React Devtools requires it.

To install use this command:

$ npm install --save-dev react-devtools-core
				`.trim() + "\n");
    } else {
      throw error;
    }
  }
}
var diff = /* @__PURE__ */ __name((before, after) => {
  if (before === after) {
    return;
  }
  if (!before) {
    return after;
  }
  const changed = {};
  let isChanged = false;
  for (const key of Object.keys(before)) {
    const isDeleted = after ? !Object.hasOwn(after, key) : true;
    if (isDeleted) {
      changed[key] = void 0;
      isChanged = true;
    }
  }
  if (after) {
    for (const key of Object.keys(after)) {
      if (after[key] !== before[key]) {
        changed[key] = after[key];
        isChanged = true;
      }
    }
  }
  return isChanged ? changed : void 0;
}, "diff");
var cleanupYogaNode = /* @__PURE__ */ __name((node) => {
  node?.unsetMeasureFunc();
  node?.freeRecursive();
}, "cleanupYogaNode");
var currentUpdatePriority = import_constants.NoEventPriority;
var currentRootNode;
var reconciler_default = (0, import_react_reconciler.default)({
  getRootHostContext: /* @__PURE__ */ __name(() => ({
    isInsideText: false
  }), "getRootHostContext"),
  prepareForCommit: /* @__PURE__ */ __name(() => null, "prepareForCommit"),
  preparePortalMount: /* @__PURE__ */ __name(() => null, "preparePortalMount"),
  clearContainer: /* @__PURE__ */ __name(() => false, "clearContainer"),
  resetAfterCommit(rootNode) {
    if (typeof rootNode.onComputeLayout === "function") {
      rootNode.onComputeLayout();
    }
    if (rootNode.isStaticDirty) {
      rootNode.isStaticDirty = false;
      if (typeof rootNode.onImmediateRender === "function") {
        rootNode.onImmediateRender();
      }
      return;
    }
    if (typeof rootNode.onRender === "function") {
      rootNode.onRender();
    }
  },
  getChildHostContext(parentHostContext, type) {
    const previousIsInsideText = parentHostContext.isInsideText;
    const isInsideText = type === "ink-text" || type === "ink-virtual-text";
    if (previousIsInsideText === isInsideText) {
      return parentHostContext;
    }
    return { isInsideText };
  },
  shouldSetTextContent: /* @__PURE__ */ __name(() => false, "shouldSetTextContent"),
  createInstance(originalType, newProps, rootNode, hostContext) {
    if (hostContext.isInsideText && originalType === "ink-box") {
      throw new Error(`<Box> can\u2019t be nested inside <Text> component`);
    }
    const type = originalType === "ink-text" && hostContext.isInsideText ? "ink-virtual-text" : originalType;
    const node = createNode(type);
    for (const [key, value] of Object.entries(newProps)) {
      if (key === "children") {
        continue;
      }
      if (key === "style") {
        setStyle(node, value);
        if (node.yogaNode) {
          styles_default(node.yogaNode, value);
        }
        continue;
      }
      if (key === "internal_transform") {
        node.internal_transform = value;
        continue;
      }
      if (key === "internal_static") {
        currentRootNode = rootNode;
        node.internal_static = true;
        rootNode.isStaticDirty = true;
        rootNode.staticNode = node;
        continue;
      }
      setAttribute(node, key, value);
    }
    return node;
  },
  createTextInstance(text, _root, hostContext) {
    if (!hostContext.isInsideText) {
      throw new Error(`Text string "${text}" must be rendered inside <Text> component`);
    }
    return createTextNode(text);
  },
  resetTextContent() {
  },
  hideTextInstance(node) {
    setTextNodeValue(node, "");
  },
  unhideTextInstance(node, text) {
    setTextNodeValue(node, text);
  },
  getPublicInstance: /* @__PURE__ */ __name((instance) => instance, "getPublicInstance"),
  hideInstance(node) {
    node.yogaNode?.setDisplay(src_default.DISPLAY_NONE);
  },
  unhideInstance(node) {
    node.yogaNode?.setDisplay(src_default.DISPLAY_FLEX);
  },
  appendInitialChild: appendChildNode,
  appendChild: appendChildNode,
  insertBefore: insertBeforeNode,
  finalizeInitialChildren() {
    return false;
  },
  isPrimaryRenderer: true,
  supportsMutation: true,
  supportsPersistence: false,
  supportsHydration: false,
  scheduleTimeout: setTimeout,
  cancelTimeout: clearTimeout,
  noTimeout: -1,
  beforeActiveInstanceBlur() {
  },
  afterActiveInstanceBlur() {
  },
  detachDeletedInstance() {
  },
  getInstanceFromNode: /* @__PURE__ */ __name(() => null, "getInstanceFromNode"),
  prepareScopeUpdate() {
  },
  getInstanceFromScope: /* @__PURE__ */ __name(() => null, "getInstanceFromScope"),
  appendChildToContainer: appendChildNode,
  insertInContainerBefore: insertBeforeNode,
  removeChildFromContainer(node, removeNode) {
    removeChildNode(node, removeNode);
    cleanupYogaNode(removeNode.yogaNode);
  },
  commitUpdate(node, _type2, oldProps, newProps) {
    if (currentRootNode && node.internal_static) {
      currentRootNode.isStaticDirty = true;
    }
    const props = diff(oldProps, newProps);
    const style = diff(oldProps["style"], newProps["style"]);
    if (!props && !style) {
      return;
    }
    if (props) {
      for (const [key, value] of Object.entries(props)) {
        if (key === "style") {
          setStyle(node, value);
          continue;
        }
        if (key === "internal_transform") {
          node.internal_transform = value;
          continue;
        }
        if (key === "internal_static") {
          node.internal_static = true;
          continue;
        }
        setAttribute(node, key, value);
      }
    }
    if (style && node.yogaNode) {
      styles_default(node.yogaNode, style);
    }
  },
  commitTextUpdate(node, _oldText, newText) {
    setTextNodeValue(node, newText);
  },
  removeChild(node, removeNode) {
    removeChildNode(node, removeNode);
    cleanupYogaNode(removeNode.yogaNode);
  },
  setCurrentUpdatePriority(newPriority) {
    currentUpdatePriority = newPriority;
  },
  getCurrentUpdatePriority: /* @__PURE__ */ __name(() => currentUpdatePriority, "getCurrentUpdatePriority"),
  resolveUpdatePriority() {
    if (currentUpdatePriority !== import_constants.NoEventPriority) {
      return currentUpdatePriority;
    }
    return import_constants.DefaultEventPriority;
  },
  maySuspendCommit() {
    return false;
  },
  // eslint-disable-next-line @typescript-eslint/naming-convention
  NotPendingTransition: void 0,
  // eslint-disable-next-line @typescript-eslint/naming-convention
  HostTransitionContext: (0, import_react.createContext)(null),
  resetFormInstance() {
  },
  requestPostPaintCallback() {
  },
  shouldAttemptEagerTransition() {
    return false;
  },
  trackSchedulerEvent() {
  },
  resolveEventType() {
    return null;
  },
  resolveEventTimeStamp() {
    return -1.1;
  },
  preloadInstance() {
    return true;
  },
  startSuspendingCommit() {
  },
  suspendInstance() {
  },
  waitForCommitToBeReady() {
    return null;
  }
});

// node_modules/ink/build/renderer.js
init_esbuild_shims();

// node_modules/ink/build/render-node-to-output.js
init_esbuild_shims();

// node_modules/indent-string/index.js
init_esbuild_shims();
function indentString(string, count = 1, options2 = {}) {
  const {
    indent = " ",
    includeEmptyLines = false
  } = options2;
  if (typeof string !== "string") {
    throw new TypeError(
      `Expected \`input\` to be a \`string\`, got \`${typeof string}\``
    );
  }
  if (typeof count !== "number") {
    throw new TypeError(
      `Expected \`count\` to be a \`number\`, got \`${typeof count}\``
    );
  }
  if (count < 0) {
    throw new RangeError(
      `Expected \`count\` to be at least 0, got \`${count}\``
    );
  }
  if (typeof indent !== "string") {
    throw new TypeError(
      `Expected \`options.indent\` to be a \`string\`, got \`${typeof indent}\``
    );
  }
  if (count === 0) {
    return string;
  }
  const regex3 = includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
  return string.replace(regex3, indent.repeat(count));
}
__name(indentString, "indentString");

// node_modules/ink/build/get-max-width.js
init_esbuild_shims();
var getMaxWidth = /* @__PURE__ */ __name((yogaNode) => {
  return yogaNode.getComputedWidth() - yogaNode.getComputedPadding(src_default.EDGE_LEFT) - yogaNode.getComputedPadding(src_default.EDGE_RIGHT) - yogaNode.getComputedBorder(src_default.EDGE_LEFT) - yogaNode.getComputedBorder(src_default.EDGE_RIGHT);
}, "getMaxWidth");
var get_max_width_default = getMaxWidth;

// node_modules/ink/build/render-border.js
init_esbuild_shims();
var import_cli_boxes = __toESM(require_cli_boxes(), 1);

// node_modules/ink/node_modules/chalk/source/index.js
init_esbuild_shims();

// node_modules/ink/node_modules/chalk/source/vendor/ansi-styles/index.js
init_esbuild_shims();
var ANSI_BACKGROUND_OFFSET3 = 10;
var wrapAnsi163 = /* @__PURE__ */ __name((offset = 0) => (code2) => `\x1B[${code2 + offset}m`, "wrapAnsi16");
var wrapAnsi2563 = /* @__PURE__ */ __name((offset = 0) => (code2) => `\x1B[${38 + offset};5;${code2}m`, "wrapAnsi256");
var wrapAnsi16m3 = /* @__PURE__ */ __name((offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`, "wrapAnsi16m");
var styles4 = {
  modifier: {
    reset: [0, 0],
    // 21 isn't widely supported and 22 does the same thing
    bold: [1, 22],
    dim: [2, 22],
    italic: [3, 23],
    underline: [4, 24],
    overline: [53, 55],
    inverse: [7, 27],
    hidden: [8, 28],
    strikethrough: [9, 29]
  },
  color: {
    black: [30, 39],
    red: [31, 39],
    green: [32, 39],
    yellow: [33, 39],
    blue: [34, 39],
    magenta: [35, 39],
    cyan: [36, 39],
    white: [37, 39],
    // Bright color
    blackBright: [90, 39],
    gray: [90, 39],
    // Alias of `blackBright`
    grey: [90, 39],
    // Alias of `blackBright`
    redBright: [91, 39],
    greenBright: [92, 39],
    yellowBright: [93, 39],
    blueBright: [94, 39],
    magentaBright: [95, 39],
    cyanBright: [96, 39],
    whiteBright: [97, 39]
  },
  bgColor: {
    bgBlack: [40, 49],
    bgRed: [41, 49],
    bgGreen: [42, 49],
    bgYellow: [43, 49],
    bgBlue: [44, 49],
    bgMagenta: [45, 49],
    bgCyan: [46, 49],
    bgWhite: [47, 49],
    // Bright color
    bgBlackBright: [100, 49],
    bgGray: [100, 49],
    // Alias of `bgBlackBright`
    bgGrey: [100, 49],
    // Alias of `bgBlackBright`
    bgRedBright: [101, 49],
    bgGreenBright: [102, 49],
    bgYellowBright: [103, 49],
    bgBlueBright: [104, 49],
    bgMagentaBright: [105, 49],
    bgCyanBright: [106, 49],
    bgWhiteBright: [107, 49]
  }
};
var modifierNames3 = Object.keys(styles4.modifier);
var foregroundColorNames3 = Object.keys(styles4.color);
var backgroundColorNames3 = Object.keys(styles4.bgColor);
var colorNames3 = [...foregroundColorNames3, ...backgroundColorNames3];
function assembleStyles3() {
  const codes = /* @__PURE__ */ new Map();
  for (const [groupName, group] of Object.entries(styles4)) {
    for (const [styleName, style] of Object.entries(group)) {
      styles4[styleName] = {
        open: `\x1B[${style[0]}m`,
        close: `\x1B[${style[1]}m`
      };
      group[styleName] = styles4[styleName];
      codes.set(style[0], style[1]);
    }
    Object.defineProperty(styles4, groupName, {
      value: group,
      enumerable: false
    });
  }
  Object.defineProperty(styles4, "codes", {
    value: codes,
    enumerable: false
  });
  styles4.color.close = "\x1B[39m";
  styles4.bgColor.close = "\x1B[49m";
  styles4.color.ansi = wrapAnsi163();
  styles4.color.ansi256 = wrapAnsi2563();
  styles4.color.ansi16m = wrapAnsi16m3();
  styles4.bgColor.ansi = wrapAnsi163(ANSI_BACKGROUND_OFFSET3);
  styles4.bgColor.ansi256 = wrapAnsi2563(ANSI_BACKGROUND_OFFSET3);
  styles4.bgColor.ansi16m = wrapAnsi16m3(ANSI_BACKGROUND_OFFSET3);
  Object.defineProperties(styles4, {
    rgbToAnsi256: {
      value(red, green, blue) {
        if (red === green && green === blue) {
          if (red < 8) {
            return 16;
          }
          if (red > 248) {
            return 231;
          }
          return Math.round((red - 8) / 247 * 24) + 232;
        }
        return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
      },
      enumerable: false
    },
    hexToRgb: {
      value(hex) {
        const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches) {
          return [0, 0, 0];
        }
        let [colorString] = matches;
        if (colorString.length === 3) {
          colorString = [...colorString].map((character) => character + character).join("");
        }
        const integer = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer >> 16 & 255,
          integer >> 8 & 255,
          integer & 255
          /* eslint-enable no-bitwise */
        ];
      },
      enumerable: false
    },
    hexToAnsi256: {
      value: /* @__PURE__ */ __name((hex) => styles4.rgbToAnsi256(...styles4.hexToRgb(hex)), "value"),
      enumerable: false
    },
    ansi256ToAnsi: {
      value(code2) {
        if (code2 < 8) {
          return 30 + code2;
        }
        if (code2 < 16) {
          return 90 + (code2 - 8);
        }
        let red;
        let green;
        let blue;
        if (code2 >= 232) {
          red = ((code2 - 232) * 10 + 8) / 255;
          green = red;
          blue = red;
        } else {
          code2 -= 16;
          const remainder = code2 % 36;
          red = Math.floor(code2 / 36) / 5;
          green = Math.floor(remainder / 6) / 5;
          blue = remainder % 6 / 5;
        }
        const value = Math.max(red, green, blue) * 2;
        if (value === 0) {
          return 30;
        }
        let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
        if (value === 2) {
          result += 60;
        }
        return result;
      },
      enumerable: false
    },
    rgbToAnsi: {
      value: /* @__PURE__ */ __name((red, green, blue) => styles4.ansi256ToAnsi(styles4.rgbToAnsi256(red, green, blue)), "value"),
      enumerable: false
    },
    hexToAnsi: {
      value: /* @__PURE__ */ __name((hex) => styles4.ansi256ToAnsi(styles4.hexToAnsi256(hex)), "value"),
      enumerable: false
    }
  });
  return styles4;
}
__name(assembleStyles3, "assembleStyles");
var ansiStyles3 = assembleStyles3();
var ansi_styles_default3 = ansiStyles3;

// node_modules/ink/node_modules/chalk/source/vendor/supports-color/index.js
init_esbuild_shims();
import process4 from "node:process";
import os from "node:os";
import tty from "node:tty";
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process4.argv) {
  const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
  const position = argv.indexOf(prefix + flag);
  const terminatorPosition = argv.indexOf("--");
  return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
}
__name(hasFlag, "hasFlag");
var { env } = process4;
var flagForceColor;
if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
  flagForceColor = 0;
} else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
  flagForceColor = 1;
}
function envForceColor() {
  if ("FORCE_COLOR" in env) {
    if (env.FORCE_COLOR === "true") {
      return 1;
    }
    if (env.FORCE_COLOR === "false") {
      return 0;
    }
    return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
  }
}
__name(envForceColor, "envForceColor");
function translateLevel(level) {
  if (level === 0) {
    return false;
  }
  return {
    level,
    hasBasic: true,
    has256: level >= 2,
    has16m: level >= 3
  };
}
__name(translateLevel, "translateLevel");
function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
  const noFlagForceColor = envForceColor();
  if (noFlagForceColor !== void 0) {
    flagForceColor = noFlagForceColor;
  }
  const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
  if (forceColor === 0) {
    return 0;
  }
  if (sniffFlags) {
    if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
      return 3;
    }
    if (hasFlag("color=256")) {
      return 2;
    }
  }
  if ("TF_BUILD" in env && "AGENT_NAME" in env) {
    return 1;
  }
  if (haveStream && !streamIsTTY && forceColor === void 0) {
    return 0;
  }
  const min = forceColor || 0;
  if (env.TERM === "dumb") {
    return min;
  }
  if (process4.platform === "win32") {
    const osRelease = os.release().split(".");
    if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
      return Number(osRelease[2]) >= 14931 ? 3 : 2;
    }
    return 1;
  }
  if ("CI" in env) {
    if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) {
      return 3;
    }
    if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
      return 1;
    }
    return min;
  }
  if ("TEAMCITY_VERSION" in env) {
    return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
  }
  if (env.COLORTERM === "truecolor") {
    return 3;
  }
  if (env.TERM === "xterm-kitty") {
    return 3;
  }
  if (env.TERM === "xterm-ghostty") {
    return 3;
  }
  if (env.TERM === "wezterm") {
    return 3;
  }
  if ("TERM_PROGRAM" in env) {
    const version2 = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
    switch (env.TERM_PROGRAM) {
      case "iTerm.app": {
        return version2 >= 3 ? 3 : 2;
      }
      case "Apple_Terminal": {
        return 2;
      }
    }
  }
  if (/-256(color)?$/i.test(env.TERM)) {
    return 2;
  }
  if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
    return 1;
  }
  if ("COLORTERM" in env) {
    return 1;
  }
  return min;
}
__name(_supportsColor, "_supportsColor");
function createSupportsColor(stream2, options2 = {}) {
  const level = _supportsColor(stream2, {
    streamIsTTY: stream2 && stream2.isTTY,
    ...options2
  });
  return translateLevel(level);
}
__name(createSupportsColor, "createSupportsColor");
var supportsColor = {
  stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
  stderr: createSupportsColor({ isTTY: tty.isatty(2) })
};
var supports_color_default = supportsColor;

// node_modules/ink/node_modules/chalk/source/utilities.js
init_esbuild_shims();
function stringReplaceAll(string, substring, replacer) {
  let index = string.indexOf(substring);
  if (index === -1) {
    return string;
  }
  const substringLength = substring.length;
  let endIndex = 0;
  let returnValue = "";
  do {
    returnValue += string.slice(endIndex, index) + substring + replacer;
    endIndex = index + substringLength;
    index = string.indexOf(substring, endIndex);
  } while (index !== -1);
  returnValue += string.slice(endIndex);
  return returnValue;
}
__name(stringReplaceAll, "stringReplaceAll");
function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
  let endIndex = 0;
  let returnValue = "";
  do {
    const gotCR = string[index - 1] === "\r";
    returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
    endIndex = index + 1;
    index = string.indexOf("\n", endIndex);
  } while (index !== -1);
  returnValue += string.slice(endIndex);
  return returnValue;
}
__name(stringEncaseCRLFWithFirstIndex, "stringEncaseCRLFWithFirstIndex");

// node_modules/ink/node_modules/chalk/source/index.js
var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
var GENERATOR = Symbol("GENERATOR");
var STYLER = Symbol("STYLER");
var IS_EMPTY = Symbol("IS_EMPTY");
var levelMapping = [
  "ansi",
  "ansi",
  "ansi256",
  "ansi16m"
];
var styles5 = /* @__PURE__ */ Object.create(null);
var applyOptions = /* @__PURE__ */ __name((object, options2 = {}) => {
  if (options2.level && !(Number.isInteger(options2.level) && options2.level >= 0 && options2.level <= 3)) {
    throw new Error("The `level` option should be an integer from 0 to 3");
  }
  const colorLevel = stdoutColor ? stdoutColor.level : 0;
  object.level = options2.level === void 0 ? colorLevel : options2.level;
}, "applyOptions");
var chalkFactory = /* @__PURE__ */ __name((options2) => {
  const chalk7 = /* @__PURE__ */ __name((...strings) => strings.join(" "), "chalk");
  applyOptions(chalk7, options2);
  Object.setPrototypeOf(chalk7, createChalk.prototype);
  return chalk7;
}, "chalkFactory");
function createChalk(options2) {
  return chalkFactory(options2);
}
__name(createChalk, "createChalk");
Object.setPrototypeOf(createChalk.prototype, Function.prototype);
for (const [styleName, style] of Object.entries(ansi_styles_default3)) {
  styles5[styleName] = {
    get() {
      const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
      Object.defineProperty(this, styleName, { value: builder });
      return builder;
    }
  };
}
styles5.visible = {
  get() {
    const builder = createBuilder(this, this[STYLER], true);
    Object.defineProperty(this, "visible", { value: builder });
    return builder;
  }
};
var getModelAnsi = /* @__PURE__ */ __name((model, level, type, ...arguments_) => {
  if (model === "rgb") {
    if (level === "ansi16m") {
      return ansi_styles_default3[type].ansi16m(...arguments_);
    }
    if (level === "ansi256") {
      return ansi_styles_default3[type].ansi256(ansi_styles_default3.rgbToAnsi256(...arguments_));
    }
    return ansi_styles_default3[type].ansi(ansi_styles_default3.rgbToAnsi(...arguments_));
  }
  if (model === "hex") {
    return getModelAnsi("rgb", level, type, ...ansi_styles_default3.hexToRgb(...arguments_));
  }
  return ansi_styles_default3[type][model](...arguments_);
}, "getModelAnsi");
var usedModels = ["rgb", "hex", "ansi256"];
for (const model of usedModels) {
  styles5[model] = {
    get() {
      const { level } = this;
      return function(...arguments_) {
        const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default3.color.close, this[STYLER]);
        return createBuilder(this, styler, this[IS_EMPTY]);
      };
    }
  };
  const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
  styles5[bgModel] = {
    get() {
      const { level } = this;
      return function(...arguments_) {
        const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default3.bgColor.close, this[STYLER]);
        return createBuilder(this, styler, this[IS_EMPTY]);
      };
    }
  };
}
var proto = Object.defineProperties(() => {
}, {
  ...styles5,
  level: {
    enumerable: true,
    get() {
      return this[GENERATOR].level;
    },
    set(level) {
      this[GENERATOR].level = level;
    }
  }
});
var createStyler = /* @__PURE__ */ __name((open3, close, parent) => {
  let openAll;
  let closeAll;
  if (parent === void 0) {
    openAll = open3;
    closeAll = close;
  } else {
    openAll = parent.openAll + open3;
    closeAll = close + parent.closeAll;
  }
  return {
    open: open3,
    close,
    openAll,
    closeAll,
    parent
  };
}, "createStyler");
var createBuilder = /* @__PURE__ */ __name((self2, _styler, _isEmpty) => {
  const builder = /* @__PURE__ */ __name((...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" ")), "builder");
  Object.setPrototypeOf(builder, proto);
  builder[GENERATOR] = self2;
  builder[STYLER] = _styler;
  builder[IS_EMPTY] = _isEmpty;
  return builder;
}, "createBuilder");
var applyStyle = /* @__PURE__ */ __name((self2, string) => {
  if (self2.level <= 0 || !string) {
    return self2[IS_EMPTY] ? "" : string;
  }
  let styler = self2[STYLER];
  if (styler === void 0) {
    return string;
  }
  const { openAll, closeAll } = styler;
  if (string.includes("\x1B")) {
    while (styler !== void 0) {
      string = stringReplaceAll(string, styler.close, styler.open);
      styler = styler.parent;
    }
  }
  const lfIndex = string.indexOf("\n");
  if (lfIndex !== -1) {
    string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
  }
  return openAll + string + closeAll;
}, "applyStyle");
Object.defineProperties(createChalk.prototype, styles5);
var chalk = createChalk();
var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
var source_default = chalk;

// node_modules/ink/build/colorize.js
init_esbuild_shims();
var rgbRegex = /^rgb\(\s?(\d+),\s?(\d+),\s?(\d+)\s?\)$/;
var ansiRegex2 = /^ansi256\(\s?(\d+)\s?\)$/;
var isNamedColor = /* @__PURE__ */ __name((color) => {
  return color in source_default;
}, "isNamedColor");
var colorize = /* @__PURE__ */ __name((str2, color, type) => {
  if (!color) {
    return str2;
  }
  if (isNamedColor(color)) {
    if (type === "foreground") {
      return source_default[color](str2);
    }
    const methodName = `bg${color[0].toUpperCase() + color.slice(1)}`;
    return source_default[methodName](str2);
  }
  if (color.startsWith("#")) {
    return type === "foreground" ? source_default.hex(color)(str2) : source_default.bgHex(color)(str2);
  }
  if (color.startsWith("ansi256")) {
    const matches = ansiRegex2.exec(color);
    if (!matches) {
      return str2;
    }
    const value = Number(matches[1]);
    return type === "foreground" ? source_default.ansi256(value)(str2) : source_default.bgAnsi256(value)(str2);
  }
  if (color.startsWith("rgb")) {
    const matches = rgbRegex.exec(color);
    if (!matches) {
      return str2;
    }
    const firstValue = Number(matches[1]);
    const secondValue = Number(matches[2]);
    const thirdValue = Number(matches[3]);
    return type === "foreground" ? source_default.rgb(firstValue, secondValue, thirdValue)(str2) : source_default.bgRgb(firstValue, secondValue, thirdValue)(str2);
  }
  return str2;
}, "colorize");
var colorize_default = colorize;

// node_modules/ink/build/render-border.js
var renderBorder = /* @__PURE__ */ __name((x, y, node, output) => {
  if (node.style.borderStyle) {
    const width = node.yogaNode.getComputedWidth();
    const height = node.yogaNode.getComputedHeight();
    const box = typeof node.style.borderStyle === "string" ? import_cli_boxes.default[node.style.borderStyle] : node.style.borderStyle;
    const topBorderColor = node.style.borderTopColor ?? node.style.borderColor;
    const bottomBorderColor = node.style.borderBottomColor ?? node.style.borderColor;
    const leftBorderColor = node.style.borderLeftColor ?? node.style.borderColor;
    const rightBorderColor = node.style.borderRightColor ?? node.style.borderColor;
    const dimTopBorderColor = node.style.borderTopDimColor ?? node.style.borderDimColor;
    const dimBottomBorderColor = node.style.borderBottomDimColor ?? node.style.borderDimColor;
    const dimLeftBorderColor = node.style.borderLeftDimColor ?? node.style.borderDimColor;
    const dimRightBorderColor = node.style.borderRightDimColor ?? node.style.borderDimColor;
    const showTopBorder = node.style.borderTop !== false;
    const showBottomBorder = node.style.borderBottom !== false;
    const showLeftBorder = node.style.borderLeft !== false;
    const showRightBorder = node.style.borderRight !== false;
    const contentWidth = width - (showLeftBorder ? 1 : 0) - (showRightBorder ? 1 : 0);
    let topBorder = showTopBorder ? colorize_default((showLeftBorder ? box.topLeft : "") + box.top.repeat(contentWidth) + (showRightBorder ? box.topRight : ""), topBorderColor, "foreground") : void 0;
    if (showTopBorder && dimTopBorderColor) {
      topBorder = source_default.dim(topBorder);
    }
    let verticalBorderHeight = height;
    if (showTopBorder) {
      verticalBorderHeight -= 1;
    }
    if (showBottomBorder) {
      verticalBorderHeight -= 1;
    }
    let leftBorder = (colorize_default(box.left, leftBorderColor, "foreground") + "\n").repeat(verticalBorderHeight);
    if (dimLeftBorderColor) {
      leftBorder = source_default.dim(leftBorder);
    }
    let rightBorder = (colorize_default(box.right, rightBorderColor, "foreground") + "\n").repeat(verticalBorderHeight);
    if (dimRightBorderColor) {
      rightBorder = source_default.dim(rightBorder);
    }
    let bottomBorder = showBottomBorder ? colorize_default((showLeftBorder ? box.bottomLeft : "") + box.bottom.repeat(contentWidth) + (showRightBorder ? box.bottomRight : ""), bottomBorderColor, "foreground") : void 0;
    if (showBottomBorder && dimBottomBorderColor) {
      bottomBorder = source_default.dim(bottomBorder);
    }
    const offsetY = showTopBorder ? 1 : 0;
    if (topBorder) {
      output.write(x, y, topBorder, { transformers: [] });
    }
    if (showLeftBorder) {
      output.write(x, y + offsetY, leftBorder, { transformers: [] });
    }
    if (showRightBorder) {
      output.write(x + width - 1, y + offsetY, rightBorder, {
        transformers: []
      });
    }
    if (bottomBorder) {
      output.write(x, y + height - 1, bottomBorder, { transformers: [] });
    }
  }
}, "renderBorder");
var render_border_default = renderBorder;

// node_modules/ink/build/render-background.js
init_esbuild_shims();
var renderBackground = /* @__PURE__ */ __name((x, y, node, output) => {
  if (!node.style.backgroundColor) {
    return;
  }
  const width = node.yogaNode.getComputedWidth();
  const height = node.yogaNode.getComputedHeight();
  const leftBorderWidth = node.style.borderStyle && node.style.borderLeft !== false ? 1 : 0;
  const rightBorderWidth = node.style.borderStyle && node.style.borderRight !== false ? 1 : 0;
  const topBorderHeight = node.style.borderStyle && node.style.borderTop !== false ? 1 : 0;
  const bottomBorderHeight = node.style.borderStyle && node.style.borderBottom !== false ? 1 : 0;
  const contentWidth = width - leftBorderWidth - rightBorderWidth;
  const contentHeight = height - topBorderHeight - bottomBorderHeight;
  if (!(contentWidth > 0 && contentHeight > 0)) {
    return;
  }
  const backgroundLine = colorize_default(" ".repeat(contentWidth), node.style.backgroundColor, "background");
  for (let row = 0; row < contentHeight; row++) {
    output.write(x + leftBorderWidth, y + topBorderHeight + row, backgroundLine, { transformers: [] });
  }
}, "renderBackground");
var render_background_default = renderBackground;

// node_modules/ink/build/render-node-to-output.js
var applyPaddingToText = /* @__PURE__ */ __name((node, text) => {
  const yogaNode = node.childNodes[0]?.yogaNode;
  if (yogaNode) {
    const offsetX = yogaNode.getComputedLeft();
    const offsetY = yogaNode.getComputedTop();
    text = "\n".repeat(offsetY) + indentString(text, offsetX);
  }
  return text;
}, "applyPaddingToText");
var renderNodeToScreenReaderOutput = /* @__PURE__ */ __name((node, options2 = {}) => {
  if (options2.skipStaticElements && node.internal_static) {
    return "";
  }
  if (node.yogaNode?.getDisplay() === src_default.DISPLAY_NONE) {
    return "";
  }
  let output = "";
  if (node.nodeName === "ink-text") {
    output = squash_text_nodes_default(node);
  } else if (node.nodeName === "ink-box" || node.nodeName === "ink-root") {
    const separator = node.style.flexDirection === "row" || node.style.flexDirection === "row-reverse" ? " " : "\n";
    const childNodes = node.style.flexDirection === "row-reverse" || node.style.flexDirection === "column-reverse" ? [...node.childNodes].reverse() : [...node.childNodes];
    output = childNodes.map((childNode) => {
      const screenReaderOutput = renderNodeToScreenReaderOutput(childNode, {
        parentRole: node.internal_accessibility?.role,
        skipStaticElements: options2.skipStaticElements
      });
      return screenReaderOutput;
    }).filter(Boolean).join(separator);
  }
  if (node.internal_accessibility) {
    const { role, state } = node.internal_accessibility;
    if (state) {
      const stateKeys = Object.keys(state);
      const stateDescription = stateKeys.filter((key) => state[key]).join(", ");
      if (stateDescription) {
        output = `(${stateDescription}) ${output}`;
      }
    }
    if (role && role !== options2.parentRole) {
      output = `${role}: ${output}`;
    }
  }
  return output;
}, "renderNodeToScreenReaderOutput");
var renderNodeToOutput = /* @__PURE__ */ __name((node, output, options2) => {
  const { offsetX = 0, offsetY = 0, transformers = [], skipStaticElements } = options2;
  if (skipStaticElements && node.internal_static) {
    return;
  }
  const { yogaNode } = node;
  if (yogaNode) {
    if (yogaNode.getDisplay() === src_default.DISPLAY_NONE) {
      return;
    }
    const x = offsetX + yogaNode.getComputedLeft();
    const y = offsetY + yogaNode.getComputedTop();
    let newTransformers = transformers;
    if (typeof node.internal_transform === "function") {
      newTransformers = [node.internal_transform, ...transformers];
    }
    if (node.nodeName === "ink-text") {
      let text = squash_text_nodes_default(node);
      if (text.length > 0) {
        const currentWidth = widestLine(text);
        const maxWidth = get_max_width_default(yogaNode);
        if (currentWidth > maxWidth) {
          const textWrap = node.style.textWrap ?? "wrap";
          text = wrap_text_default(text, maxWidth, textWrap);
        }
        text = applyPaddingToText(node, text);
        output.write(x, y, text, { transformers: newTransformers });
      }
      return;
    }
    let clipped = false;
    if (node.nodeName === "ink-box") {
      render_background_default(x, y, node, output);
      render_border_default(x, y, node, output);
      const clipHorizontally = node.style.overflowX === "hidden" || node.style.overflow === "hidden";
      const clipVertically = node.style.overflowY === "hidden" || node.style.overflow === "hidden";
      if (clipHorizontally || clipVertically) {
        const x1 = clipHorizontally ? x + yogaNode.getComputedBorder(src_default.EDGE_LEFT) : void 0;
        const x2 = clipHorizontally ? x + yogaNode.getComputedWidth() - yogaNode.getComputedBorder(src_default.EDGE_RIGHT) : void 0;
        const y1 = clipVertically ? y + yogaNode.getComputedBorder(src_default.EDGE_TOP) : void 0;
        const y2 = clipVertically ? y + yogaNode.getComputedHeight() - yogaNode.getComputedBorder(src_default.EDGE_BOTTOM) : void 0;
        output.clip({ x1, x2, y1, y2 });
        clipped = true;
      }
    }
    if (node.nodeName === "ink-root" || node.nodeName === "ink-box") {
      for (const childNode of node.childNodes) {
        renderNodeToOutput(childNode, output, {
          offsetX: x,
          offsetY: y,
          transformers: newTransformers,
          skipStaticElements
        });
      }
      if (clipped) {
        output.unclip();
      }
    }
  }
}, "renderNodeToOutput");
var render_node_to_output_default = renderNodeToOutput;

// node_modules/ink/build/output.js
init_esbuild_shims();

// node_modules/slice-ansi/index.js
init_esbuild_shims();

// node_modules/slice-ansi/node_modules/ansi-styles/index.js
init_esbuild_shims();
var ANSI_BACKGROUND_OFFSET4 = 10;
var wrapAnsi164 = /* @__PURE__ */ __name((offset = 0) => (code2) => `\x1B[${code2 + offset}m`, "wrapAnsi16");
var wrapAnsi2564 = /* @__PURE__ */ __name((offset = 0) => (code2) => `\x1B[${38 + offset};5;${code2}m`, "wrapAnsi256");
var wrapAnsi16m4 = /* @__PURE__ */ __name((offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`, "wrapAnsi16m");
var styles6 = {
  modifier: {
    reset: [0, 0],
    // 21 isn't widely supported and 22 does the same thing
    bold: [1, 22],
    dim: [2, 22],
    italic: [3, 23],
    underline: [4, 24],
    overline: [53, 55],
    inverse: [7, 27],
    hidden: [8, 28],
    strikethrough: [9, 29]
  },
  color: {
    black: [30, 39],
    red: [31, 39],
    green: [32, 39],
    yellow: [33, 39],
    blue: [34, 39],
    magenta: [35, 39],
    cyan: [36, 39],
    white: [37, 39],
    // Bright color
    blackBright: [90, 39],
    gray: [90, 39],
    // Alias of `blackBright`
    grey: [90, 39],
    // Alias of `blackBright`
    redBright: [91, 39],
    greenBright: [92, 39],
    yellowBright: [93, 39],
    blueBright: [94, 39],
    magentaBright: [95, 39],
    cyanBright: [96, 39],
    whiteBright: [97, 39]
  },
  bgColor: {
    bgBlack: [40, 49],
    bgRed: [41, 49],
    bgGreen: [42, 49],
    bgYellow: [43, 49],
    bgBlue: [44, 49],
    bgMagenta: [45, 49],
    bgCyan: [46, 49],
    bgWhite: [47, 49],
    // Bright color
    bgBlackBright: [100, 49],
    bgGray: [100, 49],
    // Alias of `bgBlackBright`
    bgGrey: [100, 49],
    // Alias of `bgBlackBright`
    bgRedBright: [101, 49],
    bgGreenBright: [102, 49],
    bgYellowBright: [103, 49],
    bgBlueBright: [104, 49],
    bgMagentaBright: [105, 49],
    bgCyanBright: [106, 49],
    bgWhiteBright: [107, 49]
  }
};
var modifierNames4 = Object.keys(styles6.modifier);
var foregroundColorNames4 = Object.keys(styles6.color);
var backgroundColorNames4 = Object.keys(styles6.bgColor);
var colorNames4 = [...foregroundColorNames4, ...backgroundColorNames4];
function assembleStyles4() {
  const codes = /* @__PURE__ */ new Map();
  for (const [groupName, group] of Object.entries(styles6)) {
    for (const [styleName, style] of Object.entries(group)) {
      styles6[styleName] = {
        open: `\x1B[${style[0]}m`,
        close: `\x1B[${style[1]}m`
      };
      group[styleName] = styles6[styleName];
      codes.set(style[0], style[1]);
    }
    Object.defineProperty(styles6, groupName, {
      value: group,
      enumerable: false
    });
  }
  Object.defineProperty(styles6, "codes", {
    value: codes,
    enumerable: false
  });
  styles6.color.close = "\x1B[39m";
  styles6.bgColor.close = "\x1B[49m";
  styles6.color.ansi = wrapAnsi164();
  styles6.color.ansi256 = wrapAnsi2564();
  styles6.color.ansi16m = wrapAnsi16m4();
  styles6.bgColor.ansi = wrapAnsi164(ANSI_BACKGROUND_OFFSET4);
  styles6.bgColor.ansi256 = wrapAnsi2564(ANSI_BACKGROUND_OFFSET4);
  styles6.bgColor.ansi16m = wrapAnsi16m4(ANSI_BACKGROUND_OFFSET4);
  Object.defineProperties(styles6, {
    rgbToAnsi256: {
      value: /* @__PURE__ */ __name((red, green, blue) => {
        if (red === green && green === blue) {
          if (red < 8) {
            return 16;
          }
          if (red > 248) {
            return 231;
          }
          return Math.round((red - 8) / 247 * 24) + 232;
        }
        return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
      }, "value"),
      enumerable: false
    },
    hexToRgb: {
      value: /* @__PURE__ */ __name((hex) => {
        const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches) {
          return [0, 0, 0];
        }
        let [colorString] = matches;
        if (colorString.length === 3) {
          colorString = [...colorString].map((character) => character + character).join("");
        }
        const integer = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer >> 16 & 255,
          integer >> 8 & 255,
          integer & 255
          /* eslint-enable no-bitwise */
        ];
      }, "value"),
      enumerable: false
    },
    hexToAnsi256: {
      value: /* @__PURE__ */ __name((hex) => styles6.rgbToAnsi256(...styles6.hexToRgb(hex)), "value"),
      enumerable: false
    },
    ansi256ToAnsi: {
      value: /* @__PURE__ */ __name((code2) => {
        if (code2 < 8) {
          return 30 + code2;
        }
        if (code2 < 16) {
          return 90 + (code2 - 8);
        }
        let red;
        let green;
        let blue;
        if (code2 >= 232) {
          red = ((code2 - 232) * 10 + 8) / 255;
          green = red;
          blue = red;
        } else {
          code2 -= 16;
          const remainder = code2 % 36;
          red = Math.floor(code2 / 36) / 5;
          green = Math.floor(remainder / 6) / 5;
          blue = remainder % 6 / 5;
        }
        const value = Math.max(red, green, blue) * 2;
        if (value === 0) {
          return 30;
        }
        let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
        if (value === 2) {
          result += 60;
        }
        return result;
      }, "value"),
      enumerable: false
    },
    rgbToAnsi: {
      value: /* @__PURE__ */ __name((red, green, blue) => styles6.ansi256ToAnsi(styles6.rgbToAnsi256(red, green, blue)), "value"),
      enumerable: false
    },
    hexToAnsi: {
      value: /* @__PURE__ */ __name((hex) => styles6.ansi256ToAnsi(styles6.hexToAnsi256(hex)), "value"),
      enumerable: false
    }
  });
  return styles6;
}
__name(assembleStyles4, "assembleStyles");
var ansiStyles4 = assembleStyles4();
var ansi_styles_default4 = ansiStyles4;

// node_modules/slice-ansi/node_modules/is-fullwidth-code-point/index.js
init_esbuild_shims();
function isFullwidthCodePoint2(codePoint) {
  if (!Number.isInteger(codePoint)) {
    return false;
  }
  return eastAsianWidth(codePoint) === 2;
}
__name(isFullwidthCodePoint2, "isFullwidthCodePoint");

// node_modules/slice-ansi/index.js
var ESCAPES3 = /* @__PURE__ */ new Set([27, 155]);
var CODE_POINT_0 = "0".codePointAt(0);
var CODE_POINT_9 = "9".codePointAt(0);
var endCodesSet = /* @__PURE__ */ new Set();
var endCodesMap = /* @__PURE__ */ new Map();
for (const [start, end] of ansi_styles_default4.codes) {
  endCodesSet.add(ansi_styles_default4.color.ansi(end));
  endCodesMap.set(ansi_styles_default4.color.ansi(start), ansi_styles_default4.color.ansi(end));
}
function getEndCode(code2) {
  if (endCodesSet.has(code2)) {
    return code2;
  }
  if (endCodesMap.has(code2)) {
    return endCodesMap.get(code2);
  }
  code2 = code2.slice(2);
  if (code2.includes(";")) {
    code2 = code2[0] + "0";
  }
  const returnValue = ansi_styles_default4.codes.get(Number.parseInt(code2, 10));
  if (returnValue) {
    return ansi_styles_default4.color.ansi(returnValue);
  }
  return ansi_styles_default4.reset.open;
}
__name(getEndCode, "getEndCode");
function findNumberIndex(string) {
  for (let index = 0; index < string.length; index++) {
    const codePoint = string.codePointAt(index);
    if (codePoint >= CODE_POINT_0 && codePoint <= CODE_POINT_9) {
      return index;
    }
  }
  return -1;
}
__name(findNumberIndex, "findNumberIndex");
function parseAnsiCode(string, offset) {
  string = string.slice(offset, offset + 19);
  const startIndex = findNumberIndex(string);
  if (startIndex !== -1) {
    let endIndex = string.indexOf("m", startIndex);
    if (endIndex === -1) {
      endIndex = string.length;
    }
    return string.slice(0, endIndex + 1);
  }
}
__name(parseAnsiCode, "parseAnsiCode");
function tokenize(string, endCharacter = Number.POSITIVE_INFINITY) {
  const returnValue = [];
  let index = 0;
  let visibleCount = 0;
  while (index < string.length) {
    const codePoint = string.codePointAt(index);
    if (ESCAPES3.has(codePoint)) {
      const code2 = parseAnsiCode(string, index);
      if (code2) {
        returnValue.push({
          type: "ansi",
          code: code2,
          endCode: getEndCode(code2)
        });
        index += code2.length;
        continue;
      }
    }
    const isFullWidth2 = isFullwidthCodePoint2(codePoint);
    const character = String.fromCodePoint(codePoint);
    returnValue.push({
      type: "character",
      value: character,
      isFullWidth: isFullWidth2
    });
    index += character.length;
    visibleCount += isFullWidth2 ? 2 : character.length;
    if (visibleCount >= endCharacter) {
      break;
    }
  }
  return returnValue;
}
__name(tokenize, "tokenize");
function reduceAnsiCodes(codes) {
  let returnValue = [];
  for (const code2 of codes) {
    if (code2.code === ansi_styles_default4.reset.open) {
      returnValue = [];
    } else if (endCodesSet.has(code2.code)) {
      returnValue = returnValue.filter((returnValueCode) => returnValueCode.endCode !== code2.code);
    } else {
      returnValue = returnValue.filter((returnValueCode) => returnValueCode.endCode !== code2.endCode);
      returnValue.push(code2);
    }
  }
  return returnValue;
}
__name(reduceAnsiCodes, "reduceAnsiCodes");
function undoAnsiCodes(codes) {
  const reduced = reduceAnsiCodes(codes);
  const endCodes = reduced.map(({ endCode }) => endCode);
  return endCodes.reverse().join("");
}
__name(undoAnsiCodes, "undoAnsiCodes");
function sliceAnsi2(string, start, end) {
  const tokens = tokenize(string, end);
  let activeCodes = [];
  let position = 0;
  let returnValue = "";
  let include = false;
  for (const token2 of tokens) {
    if (end !== void 0 && position >= end) {
      break;
    }
    if (token2.type === "ansi") {
      activeCodes.push(token2);
      if (include) {
        returnValue += token2.code;
      }
    } else {
      if (!include && position >= start) {
        include = true;
        activeCodes = reduceAnsiCodes(activeCodes);
        returnValue = activeCodes.map(({ code: code2 }) => code2).join("");
      }
      if (include) {
        returnValue += token2.value;
      }
      position += token2.isFullWidth ? 2 : token2.value.length;
    }
  }
  returnValue += undoAnsiCodes(activeCodes);
  return returnValue;
}
__name(sliceAnsi2, "sliceAnsi");

// node_modules/@alcalzone/ansi-tokenize/build/index.js
init_esbuild_shims();

// node_modules/@alcalzone/ansi-tokenize/build/ansiCodes.js
init_esbuild_shims();

// node_modules/@alcalzone/ansi-tokenize/node_modules/ansi-styles/index.js
init_esbuild_shims();
var ANSI_BACKGROUND_OFFSET5 = 10;
var wrapAnsi165 = /* @__PURE__ */ __name((offset = 0) => (code2) => `\x1B[${code2 + offset}m`, "wrapAnsi16");
var wrapAnsi2565 = /* @__PURE__ */ __name((offset = 0) => (code2) => `\x1B[${38 + offset};5;${code2}m`, "wrapAnsi256");
var wrapAnsi16m5 = /* @__PURE__ */ __name((offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`, "wrapAnsi16m");
var styles7 = {
  modifier: {
    reset: [0, 0],
    // 21 isn't widely supported and 22 does the same thing
    bold: [1, 22],
    dim: [2, 22],
    italic: [3, 23],
    underline: [4, 24],
    overline: [53, 55],
    inverse: [7, 27],
    hidden: [8, 28],
    strikethrough: [9, 29]
  },
  color: {
    black: [30, 39],
    red: [31, 39],
    green: [32, 39],
    yellow: [33, 39],
    blue: [34, 39],
    magenta: [35, 39],
    cyan: [36, 39],
    white: [37, 39],
    // Bright color
    blackBright: [90, 39],
    gray: [90, 39],
    // Alias of `blackBright`
    grey: [90, 39],
    // Alias of `blackBright`
    redBright: [91, 39],
    greenBright: [92, 39],
    yellowBright: [93, 39],
    blueBright: [94, 39],
    magentaBright: [95, 39],
    cyanBright: [96, 39],
    whiteBright: [97, 39]
  },
  bgColor: {
    bgBlack: [40, 49],
    bgRed: [41, 49],
    bgGreen: [42, 49],
    bgYellow: [43, 49],
    bgBlue: [44, 49],
    bgMagenta: [45, 49],
    bgCyan: [46, 49],
    bgWhite: [47, 49],
    // Bright color
    bgBlackBright: [100, 49],
    bgGray: [100, 49],
    // Alias of `bgBlackBright`
    bgGrey: [100, 49],
    // Alias of `bgBlackBright`
    bgRedBright: [101, 49],
    bgGreenBright: [102, 49],
    bgYellowBright: [103, 49],
    bgBlueBright: [104, 49],
    bgMagentaBright: [105, 49],
    bgCyanBright: [106, 49],
    bgWhiteBright: [107, 49]
  }
};
var modifierNames5 = Object.keys(styles7.modifier);
var foregroundColorNames5 = Object.keys(styles7.color);
var backgroundColorNames5 = Object.keys(styles7.bgColor);
var colorNames5 = [...foregroundColorNames5, ...backgroundColorNames5];
function assembleStyles5() {
  const codes = /* @__PURE__ */ new Map();
  for (const [groupName, group] of Object.entries(styles7)) {
    for (const [styleName, style] of Object.entries(group)) {
      styles7[styleName] = {
        open: `\x1B[${style[0]}m`,
        close: `\x1B[${style[1]}m`
      };
      group[styleName] = styles7[styleName];
      codes.set(style[0], style[1]);
    }
    Object.defineProperty(styles7, groupName, {
      value: group,
      enumerable: false
    });
  }
  Object.defineProperty(styles7, "codes", {
    value: codes,
    enumerable: false
  });
  styles7.color.close = "\x1B[39m";
  styles7.bgColor.close = "\x1B[49m";
  styles7.color.ansi = wrapAnsi165();
  styles7.color.ansi256 = wrapAnsi2565();
  styles7.color.ansi16m = wrapAnsi16m5();
  styles7.bgColor.ansi = wrapAnsi165(ANSI_BACKGROUND_OFFSET5);
  styles7.bgColor.ansi256 = wrapAnsi2565(ANSI_BACKGROUND_OFFSET5);
  styles7.bgColor.ansi16m = wrapAnsi16m5(ANSI_BACKGROUND_OFFSET5);
  Object.defineProperties(styles7, {
    rgbToAnsi256: {
      value: /* @__PURE__ */ __name((red, green, blue) => {
        if (red === green && green === blue) {
          if (red < 8) {
            return 16;
          }
          if (red > 248) {
            return 231;
          }
          return Math.round((red - 8) / 247 * 24) + 232;
        }
        return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
      }, "value"),
      enumerable: false
    },
    hexToRgb: {
      value: /* @__PURE__ */ __name((hex) => {
        const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches) {
          return [0, 0, 0];
        }
        let [colorString] = matches;
        if (colorString.length === 3) {
          colorString = [...colorString].map((character) => character + character).join("");
        }
        const integer = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer >> 16 & 255,
          integer >> 8 & 255,
          integer & 255
          /* eslint-enable no-bitwise */
        ];
      }, "value"),
      enumerable: false
    },
    hexToAnsi256: {
      value: /* @__PURE__ */ __name((hex) => styles7.rgbToAnsi256(...styles7.hexToRgb(hex)), "value"),
      enumerable: false
    },
    ansi256ToAnsi: {
      value: /* @__PURE__ */ __name((code2) => {
        if (code2 < 8) {
          return 30 + code2;
        }
        if (code2 < 16) {
          return 90 + (code2 - 8);
        }
        let red;
        let green;
        let blue;
        if (code2 >= 232) {
          red = ((code2 - 232) * 10 + 8) / 255;
          green = red;
          blue = red;
        } else {
          code2 -= 16;
          const remainder = code2 % 36;
          red = Math.floor(code2 / 36) / 5;
          green = Math.floor(remainder / 6) / 5;
          blue = remainder % 6 / 5;
        }
        const value = Math.max(red, green, blue) * 2;
        if (value === 0) {
          return 30;
        }
        let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
        if (value === 2) {
          result += 60;
        }
        return result;
      }, "value"),
      enumerable: false
    },
    rgbToAnsi: {
      value: /* @__PURE__ */ __name((red, green, blue) => styles7.ansi256ToAnsi(styles7.rgbToAnsi256(red, green, blue)), "value"),
      enumerable: false
    },
    hexToAnsi: {
      value: /* @__PURE__ */ __name((hex) => styles7.ansi256ToAnsi(styles7.hexToAnsi256(hex)), "value"),
      enumerable: false
    }
  });
  return styles7;
}
__name(assembleStyles5, "assembleStyles");
var ansiStyles5 = assembleStyles5();
var ansi_styles_default5 = ansiStyles5;

// node_modules/@alcalzone/ansi-tokenize/build/ansiCodes.js
var ESCAPES4 = /* @__PURE__ */ new Set([27, 155]);
var endCodesSet2 = /* @__PURE__ */ new Set();
var endCodesMap2 = /* @__PURE__ */ new Map();
for (const [start, end] of ansi_styles_default5.codes) {
  endCodesSet2.add(ansi_styles_default5.color.ansi(end));
  endCodesMap2.set(ansi_styles_default5.color.ansi(start), ansi_styles_default5.color.ansi(end));
}
var linkStartCodePrefix = "\x1B]8;;";
var linkStartCodePrefixCharCodes = linkStartCodePrefix.split("").map((char) => char.charCodeAt(0));
var linkCodeSuffix = "\x07";
var linkCodeSuffixCharCode = linkCodeSuffix.charCodeAt(0);
var linkEndCode = `\x1B]8;;${linkCodeSuffix}`;
function getEndCode2(code2) {
  if (endCodesSet2.has(code2))
    return code2;
  if (endCodesMap2.has(code2))
    return endCodesMap2.get(code2);
  if (code2.startsWith(linkStartCodePrefix))
    return linkEndCode;
  code2 = code2.slice(2);
  if (code2.includes(";")) {
    code2 = code2[0] + "0";
  }
  const ret = ansi_styles_default5.codes.get(parseInt(code2, 10));
  if (ret) {
    return ansi_styles_default5.color.ansi(ret);
  } else {
    return ansi_styles_default5.reset.open;
  }
}
__name(getEndCode2, "getEndCode");
function ansiCodesToString(codes) {
  return codes.map((code2) => code2.code).join("");
}
__name(ansiCodesToString, "ansiCodesToString");

// node_modules/@alcalzone/ansi-tokenize/build/diff.js
init_esbuild_shims();

// node_modules/@alcalzone/ansi-tokenize/build/undo.js
init_esbuild_shims();

// node_modules/@alcalzone/ansi-tokenize/build/reduce.js
init_esbuild_shims();
function reduceAnsiCodes2(codes) {
  return reduceAnsiCodesIncremental([], codes);
}
__name(reduceAnsiCodes2, "reduceAnsiCodes");
function reduceAnsiCodesIncremental(codes, newCodes) {
  let ret = [...codes];
  for (const code2 of newCodes) {
    if (code2.code === ansi_styles_default5.reset.open) {
      ret = [];
    } else if (endCodesSet2.has(code2.code)) {
      ret = ret.filter((retCode) => retCode.endCode !== code2.code);
    } else {
      ret = ret.filter((retCode) => retCode.endCode !== code2.endCode);
      ret.push(code2);
    }
  }
  return ret;
}
__name(reduceAnsiCodesIncremental, "reduceAnsiCodesIncremental");

// node_modules/@alcalzone/ansi-tokenize/build/undo.js
function undoAnsiCodes2(codes) {
  return reduceAnsiCodes2(codes).reverse().map((code2) => ({
    ...code2,
    code: code2.endCode
  }));
}
__name(undoAnsiCodes2, "undoAnsiCodes");

// node_modules/@alcalzone/ansi-tokenize/build/diff.js
function diffAnsiCodes(from, to) {
  const endCodesInTo = new Set(to.map((code2) => code2.endCode));
  const startCodesInFrom = new Set(from.map((code2) => code2.code));
  return [
    // Ignore all styles in `from` that are not overwritten or removed by `to`
    // Disable all styles in `from` that are removed in `to`
    ...undoAnsiCodes2(from.filter((code2) => !endCodesInTo.has(code2.endCode))),
    // Add all styles in `to` that don't exist in `from`
    ...to.filter((code2) => !startCodesInFrom.has(code2.code))
  ];
}
__name(diffAnsiCodes, "diffAnsiCodes");

// node_modules/@alcalzone/ansi-tokenize/build/styledChars.js
init_esbuild_shims();
function styledCharsFromTokens(tokens) {
  let codes = [];
  const ret = [];
  for (const token2 of tokens) {
    if (token2.type === "ansi") {
      codes = reduceAnsiCodesIncremental(codes, [token2]);
    } else if (token2.type === "char") {
      ret.push({
        ...token2,
        styles: [...codes]
      });
    }
  }
  return ret;
}
__name(styledCharsFromTokens, "styledCharsFromTokens");
function styledCharsToString(chars) {
  let ret = "";
  for (let i = 0; i < chars.length; i++) {
    const char = chars[i];
    if (i === 0) {
      ret += ansiCodesToString(char.styles);
    } else {
      ret += ansiCodesToString(diffAnsiCodes(chars[i - 1].styles, char.styles));
    }
    ret += char.value;
    if (i === chars.length - 1) {
      ret += ansiCodesToString(diffAnsiCodes(char.styles, []));
    }
  }
  return ret;
}
__name(styledCharsToString, "styledCharsToString");

// node_modules/@alcalzone/ansi-tokenize/build/tokenize.js
init_esbuild_shims();

// node_modules/@alcalzone/ansi-tokenize/node_modules/is-fullwidth-code-point/index.js
init_esbuild_shims();
function isFullwidthCodePoint3(codePoint) {
  if (!Number.isInteger(codePoint)) {
    return false;
  }
  return eastAsianWidth(codePoint) === 2;
}
__name(isFullwidthCodePoint3, "isFullwidthCodePoint");

// node_modules/@alcalzone/ansi-tokenize/build/tokenize.js
function findNumberIndex2(str2) {
  for (let index = 0; index < str2.length; index++) {
    const charCode = str2.charCodeAt(index);
    if (charCode >= 48 && charCode <= 57) {
      return index;
    }
  }
  return -1;
}
__name(findNumberIndex2, "findNumberIndex");
function parseLinkCode(string, offset) {
  string = string.slice(offset);
  for (let index = 1; index < linkStartCodePrefixCharCodes.length; index++) {
    if (string.charCodeAt(index) !== linkStartCodePrefixCharCodes[index]) {
      return void 0;
    }
  }
  const endIndex = string.indexOf("\x07", linkStartCodePrefix.length);
  if (endIndex === -1)
    return void 0;
  return string.slice(0, endIndex + 1);
}
__name(parseLinkCode, "parseLinkCode");
function parseAnsiCode2(string, offset) {
  string = string.slice(offset, offset + 19);
  const startIndex = findNumberIndex2(string);
  if (startIndex !== -1) {
    let endIndex = string.indexOf("m", startIndex);
    if (endIndex === -1) {
      endIndex = string.length;
    }
    return string.slice(0, endIndex + 1);
  }
}
__name(parseAnsiCode2, "parseAnsiCode");
function tokenize2(str2, endChar = Number.POSITIVE_INFINITY) {
  const ret = [];
  let index = 0;
  let visible = 0;
  while (index < str2.length) {
    const codePoint = str2.codePointAt(index);
    if (ESCAPES4.has(codePoint)) {
      const code2 = parseLinkCode(str2, index) || parseAnsiCode2(str2, index);
      if (code2) {
        ret.push({
          type: "ansi",
          code: code2,
          endCode: getEndCode2(code2)
        });
        index += code2.length;
        continue;
      }
    }
    const fullWidth = isFullwidthCodePoint3(codePoint);
    const character = String.fromCodePoint(codePoint);
    ret.push({
      type: "char",
      value: character,
      fullWidth
    });
    index += character.length;
    visible += fullWidth ? 2 : character.length;
    if (visible >= endChar) {
      break;
    }
  }
  return ret;
}
__name(tokenize2, "tokenize");

// node_modules/ink/build/output.js
var Output = class {
  static {
    __name(this, "Output");
  }
  width;
  height;
  operations = [];
  constructor(options2) {
    const { width, height } = options2;
    this.width = width;
    this.height = height;
  }
  write(x, y, text, options2) {
    const { transformers } = options2;
    if (!text) {
      return;
    }
    this.operations.push({
      type: "write",
      x,
      y,
      text,
      transformers
    });
  }
  clip(clip) {
    this.operations.push({
      type: "clip",
      clip
    });
  }
  unclip() {
    this.operations.push({
      type: "unclip"
    });
  }
  get() {
    const output = [];
    for (let y = 0; y < this.height; y++) {
      const row = [];
      for (let x = 0; x < this.width; x++) {
        row.push({
          type: "char",
          value: " ",
          fullWidth: false,
          styles: []
        });
      }
      output.push(row);
    }
    const clips = [];
    for (const operation of this.operations) {
      if (operation.type === "clip") {
        clips.push(operation.clip);
      }
      if (operation.type === "unclip") {
        clips.pop();
      }
      if (operation.type === "write") {
        const { text, transformers } = operation;
        let { x, y } = operation;
        let lines = text.split("\n");
        const clip = clips.at(-1);
        if (clip) {
          const clipHorizontally = typeof clip?.x1 === "number" && typeof clip?.x2 === "number";
          const clipVertically = typeof clip?.y1 === "number" && typeof clip?.y2 === "number";
          if (clipHorizontally) {
            const width = widestLine(text);
            if (x + width < clip.x1 || x > clip.x2) {
              continue;
            }
          }
          if (clipVertically) {
            const height = lines.length;
            if (y + height < clip.y1 || y > clip.y2) {
              continue;
            }
          }
          if (clipHorizontally) {
            lines = lines.map((line) => {
              const from = x < clip.x1 ? clip.x1 - x : 0;
              const width = stringWidth2(line);
              const to = x + width > clip.x2 ? clip.x2 - x : width;
              return sliceAnsi2(line, from, to);
            });
            if (x < clip.x1) {
              x = clip.x1;
            }
          }
          if (clipVertically) {
            const from = y < clip.y1 ? clip.y1 - y : 0;
            const height = lines.length;
            const to = y + height > clip.y2 ? clip.y2 - y : height;
            lines = lines.slice(from, to);
            if (y < clip.y1) {
              y = clip.y1;
            }
          }
        }
        let offsetY = 0;
        for (let [index, line] of lines.entries()) {
          const currentLine = output[y + offsetY];
          if (!currentLine) {
            continue;
          }
          for (const transformer of transformers) {
            line = transformer(line, index);
          }
          const characters = styledCharsFromTokens(tokenize2(line));
          let offsetX = x;
          for (const character of characters) {
            currentLine[offsetX] = character;
            const characterWidth = Math.max(1, stringWidth2(character.value));
            if (characterWidth > 1) {
              for (let index2 = 1; index2 < characterWidth; index2++) {
                currentLine[offsetX + index2] = {
                  type: "char",
                  value: "",
                  fullWidth: false,
                  styles: character.styles
                };
              }
            }
            offsetX += characterWidth;
          }
          offsetY++;
        }
      }
    }
    const generatedOutput = output.map((line) => {
      const lineWithoutEmptyItems = line.filter((item) => item !== void 0);
      return styledCharsToString(lineWithoutEmptyItems).trimEnd();
    }).join("\n");
    return {
      output: generatedOutput,
      height: output.length
    };
  }
};

// node_modules/ink/build/renderer.js
var renderer = /* @__PURE__ */ __name((node, isScreenReaderEnabled) => {
  if (node.yogaNode) {
    if (isScreenReaderEnabled) {
      const output2 = renderNodeToScreenReaderOutput(node, {
        skipStaticElements: true
      });
      const outputHeight2 = output2 === "" ? 0 : output2.split("\n").length;
      let staticOutput2 = "";
      if (node.staticNode) {
        staticOutput2 = renderNodeToScreenReaderOutput(node.staticNode, {
          skipStaticElements: false
        });
      }
      return {
        output: output2,
        outputHeight: outputHeight2,
        staticOutput: staticOutput2 ? `${staticOutput2}
` : ""
      };
    }
    const output = new Output({
      width: node.yogaNode.getComputedWidth(),
      height: node.yogaNode.getComputedHeight()
    });
    render_node_to_output_default(node, output, {
      skipStaticElements: true
    });
    let staticOutput;
    if (node.staticNode?.yogaNode) {
      staticOutput = new Output({
        width: node.staticNode.yogaNode.getComputedWidth(),
        height: node.staticNode.yogaNode.getComputedHeight()
      });
      render_node_to_output_default(node.staticNode, staticOutput, {
        skipStaticElements: false
      });
    }
    const { output: generatedOutput, height: outputHeight } = output.get();
    return {
      output: generatedOutput,
      outputHeight,
      // Newline at the end is needed, because static output doesn't have one, so
      // interactive output will override last line of static output
      staticOutput: staticOutput ? `${staticOutput.get().output}
` : ""
    };
  }
  return {
    output: "",
    outputHeight: 0,
    staticOutput: ""
  };
}, "renderer");
var renderer_default = renderer;

// node_modules/ink/build/log-update.js
init_esbuild_shims();

// node_modules/cli-cursor/index.js
init_esbuild_shims();
import process6 from "node:process";

// node_modules/restore-cursor/index.js
init_esbuild_shims();
var import_onetime = __toESM(require_onetime(), 1);
var import_signal_exit = __toESM(require_signal_exit2(), 1);
import process5 from "node:process";
var restoreCursor = (0, import_onetime.default)(() => {
  (0, import_signal_exit.default)(() => {
    process5.stderr.write("\x1B[?25h");
  }, { alwaysLast: true });
});
var restore_cursor_default = restoreCursor;

// node_modules/cli-cursor/index.js
var isHidden = false;
var cliCursor = {};
cliCursor.show = (writableStream = process6.stderr) => {
  if (!writableStream.isTTY) {
    return;
  }
  isHidden = false;
  writableStream.write("\x1B[?25h");
};
cliCursor.hide = (writableStream = process6.stderr) => {
  if (!writableStream.isTTY) {
    return;
  }
  restore_cursor_default();
  isHidden = true;
  writableStream.write("\x1B[?25l");
};
cliCursor.toggle = (force, writableStream) => {
  if (force !== void 0) {
    isHidden = force;
  }
  if (isHidden) {
    cliCursor.show(writableStream);
  } else {
    cliCursor.hide(writableStream);
  }
};
var cli_cursor_default = cliCursor;

// node_modules/ink/build/log-update.js
var create = /* @__PURE__ */ __name((stream2, { showCursor = false } = {}) => {
  let previousLineCount = 0;
  let previousOutput = "";
  let hasHiddenCursor = false;
  const render3 = /* @__PURE__ */ __name((str2) => {
    if (!showCursor && !hasHiddenCursor) {
      cli_cursor_default.hide();
      hasHiddenCursor = true;
    }
    const output = str2 + "\n";
    if (output === previousOutput) {
      return;
    }
    previousOutput = output;
    stream2.write(base_exports.eraseLines(previousLineCount) + output);
    previousLineCount = output.split("\n").length;
  }, "render");
  render3.clear = () => {
    stream2.write(base_exports.eraseLines(previousLineCount));
    previousOutput = "";
    previousLineCount = 0;
  };
  render3.done = () => {
    previousOutput = "";
    previousLineCount = 0;
    if (!showCursor) {
      cli_cursor_default.show();
      hasHiddenCursor = false;
    }
  };
  render3.sync = (str2) => {
    const output = str2 + "\n";
    previousOutput = output;
    previousLineCount = output.split("\n").length;
  };
  return render3;
}, "create");
var logUpdate = { create };
var log_update_default = logUpdate;

// node_modules/ink/build/instances.js
init_esbuild_shims();
var instances = /* @__PURE__ */ new WeakMap();
var instances_default = instances;

// node_modules/ink/build/components/App.js
init_esbuild_shims();
var import_react12 = __toESM(require_react(), 1);
import { EventEmitter as EventEmitter2 } from "node:events";
import process10 from "node:process";

// node_modules/ink/build/components/AppContext.js
init_esbuild_shims();
var import_react2 = __toESM(require_react(), 1);
var AppContext = (0, import_react2.createContext)({
  exit() {
  }
});
AppContext.displayName = "InternalAppContext";
var AppContext_default = AppContext;

// node_modules/ink/build/components/StdinContext.js
init_esbuild_shims();
var import_react3 = __toESM(require_react(), 1);
import { EventEmitter } from "node:events";
import process7 from "node:process";
var StdinContext = (0, import_react3.createContext)({
  stdin: process7.stdin,
  // eslint-disable-next-line @typescript-eslint/naming-convention
  internal_eventEmitter: new EventEmitter(),
  setRawMode() {
  },
  isRawModeSupported: false,
  // eslint-disable-next-line @typescript-eslint/naming-convention
  internal_exitOnCtrlC: true
});
StdinContext.displayName = "InternalStdinContext";
var StdinContext_default = StdinContext;

// node_modules/ink/build/components/StdoutContext.js
init_esbuild_shims();
var import_react4 = __toESM(require_react(), 1);
import process8 from "node:process";
var StdoutContext = (0, import_react4.createContext)({
  stdout: process8.stdout,
  write() {
  }
});
StdoutContext.displayName = "InternalStdoutContext";
var StdoutContext_default = StdoutContext;

// node_modules/ink/build/components/StderrContext.js
init_esbuild_shims();
var import_react5 = __toESM(require_react(), 1);
import process9 from "node:process";
var StderrContext = (0, import_react5.createContext)({
  stderr: process9.stderr,
  write() {
  }
});
StderrContext.displayName = "InternalStderrContext";
var StderrContext_default = StderrContext;

// node_modules/ink/build/components/FocusContext.js
init_esbuild_shims();
var import_react6 = __toESM(require_react(), 1);
var FocusContext = (0, import_react6.createContext)({
  activeId: void 0,
  add() {
  },
  remove() {
  },
  activate() {
  },
  deactivate() {
  },
  enableFocus() {
  },
  disableFocus() {
  },
  focusNext() {
  },
  focusPrevious() {
  },
  focus() {
  }
});
FocusContext.displayName = "InternalFocusContext";
var FocusContext_default = FocusContext;

// node_modules/ink/build/components/ErrorOverview.js
init_esbuild_shims();
var import_react11 = __toESM(require_react(), 1);
var import_stack_utils = __toESM(require_stack_utils(), 1);
import * as fs from "node:fs";
import { cwd } from "node:process";

// node_modules/code-excerpt/dist/index.js
init_esbuild_shims();

// node_modules/convert-to-spaces/dist/index.js
init_esbuild_shims();
var convertToSpaces = /* @__PURE__ */ __name((input, spaces = 2) => {
  return input.replace(/^\t+/gm, ($1) => " ".repeat($1.length * spaces));
}, "convertToSpaces");
var dist_default2 = convertToSpaces;

// node_modules/code-excerpt/dist/index.js
var generateLineNumbers = /* @__PURE__ */ __name((line, around) => {
  const lineNumbers = [];
  const min = line - around;
  const max = line + around;
  for (let lineNumber = min; lineNumber <= max; lineNumber++) {
    lineNumbers.push(lineNumber);
  }
  return lineNumbers;
}, "generateLineNumbers");
var codeExcerpt = /* @__PURE__ */ __name((source2, line, options2 = {}) => {
  var _a6;
  if (typeof source2 !== "string") {
    throw new TypeError("Source code is missing.");
  }
  if (!line || line < 1) {
    throw new TypeError("Line number must start from `1`.");
  }
  const lines = dist_default2(source2).split(/\r?\n/);
  if (line > lines.length) {
    return;
  }
  return generateLineNumbers(line, (_a6 = options2.around) !== null && _a6 !== void 0 ? _a6 : 3).filter((line2) => lines[line2 - 1] !== void 0).map((line2) => ({ line: line2, value: lines[line2 - 1] }));
}, "codeExcerpt");
var dist_default3 = codeExcerpt;

// node_modules/ink/build/components/Box.js
init_esbuild_shims();
var import_react9 = __toESM(require_react(), 1);

// node_modules/ink/build/components/AccessibilityContext.js
init_esbuild_shims();
var import_react7 = __toESM(require_react(), 1);
var accessibilityContext = (0, import_react7.createContext)({
  isScreenReaderEnabled: false
});

// node_modules/ink/build/components/BackgroundContext.js
init_esbuild_shims();
var import_react8 = __toESM(require_react(), 1);
var backgroundContext = (0, import_react8.createContext)(void 0);

// node_modules/ink/build/components/Box.js
var Box = (0, import_react9.forwardRef)(({ children, backgroundColor, "aria-label": ariaLabel, "aria-hidden": ariaHidden, "aria-role": role, "aria-state": ariaState, ...style }, ref) => {
  const { isScreenReaderEnabled } = (0, import_react9.useContext)(accessibilityContext);
  const label = ariaLabel ? import_react9.default.createElement("ink-text", null, ariaLabel) : void 0;
  if (isScreenReaderEnabled && ariaHidden) {
    return null;
  }
  const boxElement = import_react9.default.createElement("ink-box", { ref, style: {
    flexWrap: "nowrap",
    flexDirection: "row",
    flexGrow: 0,
    flexShrink: 1,
    ...style,
    backgroundColor,
    overflowX: style.overflowX ?? style.overflow ?? "visible",
    overflowY: style.overflowY ?? style.overflow ?? "visible"
  }, internal_accessibility: {
    role,
    state: ariaState
  } }, isScreenReaderEnabled && label ? label : children);
  if (backgroundColor) {
    return import_react9.default.createElement(backgroundContext.Provider, { value: backgroundColor }, boxElement);
  }
  return boxElement;
});
Box.displayName = "Box";
var Box_default = Box;

// node_modules/ink/build/components/Text.js
init_esbuild_shims();
var import_react10 = __toESM(require_react(), 1);
function Text({ color, backgroundColor, dimColor = false, bold = false, italic = false, underline = false, strikethrough = false, inverse = false, wrap: wrap2 = "wrap", children, "aria-label": ariaLabel, "aria-hidden": ariaHidden = false }) {
  const { isScreenReaderEnabled } = (0, import_react10.useContext)(accessibilityContext);
  const inheritedBackgroundColor = (0, import_react10.useContext)(backgroundContext);
  const childrenOrAriaLabel = isScreenReaderEnabled && ariaLabel ? ariaLabel : children;
  if (childrenOrAriaLabel === void 0 || childrenOrAriaLabel === null) {
    return null;
  }
  const transform = /* @__PURE__ */ __name((children2) => {
    if (dimColor) {
      children2 = source_default.dim(children2);
    }
    if (color) {
      children2 = colorize_default(children2, color, "foreground");
    }
    const effectiveBackgroundColor = backgroundColor ?? inheritedBackgroundColor;
    if (effectiveBackgroundColor) {
      children2 = colorize_default(children2, effectiveBackgroundColor, "background");
    }
    if (bold) {
      children2 = source_default.bold(children2);
    }
    if (italic) {
      children2 = source_default.italic(children2);
    }
    if (underline) {
      children2 = source_default.underline(children2);
    }
    if (strikethrough) {
      children2 = source_default.strikethrough(children2);
    }
    if (inverse) {
      children2 = source_default.inverse(children2);
    }
    return children2;
  }, "transform");
  if (isScreenReaderEnabled && ariaHidden) {
    return null;
  }
  return import_react10.default.createElement("ink-text", { style: { flexGrow: 0, flexShrink: 1, flexDirection: "row", textWrap: wrap2 }, internal_transform: transform }, isScreenReaderEnabled && ariaLabel ? ariaLabel : children);
}
__name(Text, "Text");

// node_modules/ink/build/components/ErrorOverview.js
var cleanupPath = /* @__PURE__ */ __name((path108) => {
  return path108?.replace(`file://${cwd()}/`, "");
}, "cleanupPath");
var stackUtils = new import_stack_utils.default({
  cwd: cwd(),
  internals: import_stack_utils.default.nodeInternals()
});
function ErrorOverview({ error }) {
  const stack = error.stack ? error.stack.split("\n").slice(1) : void 0;
  const origin = stack ? stackUtils.parseLine(stack[0]) : void 0;
  const filePath = cleanupPath(origin?.file);
  let excerpt;
  let lineWidth = 0;
  if (filePath && origin?.line && fs.existsSync(filePath)) {
    const sourceCode = fs.readFileSync(filePath, "utf8");
    excerpt = dist_default3(sourceCode, origin.line);
    if (excerpt) {
      for (const { line } of excerpt) {
        lineWidth = Math.max(lineWidth, String(line).length);
      }
    }
  }
  return import_react11.default.createElement(
    Box_default,
    { flexDirection: "column", padding: 1 },
    import_react11.default.createElement(
      Box_default,
      null,
      import_react11.default.createElement(
        Text,
        { backgroundColor: "red", color: "white" },
        " ",
        "ERROR",
        " "
      ),
      import_react11.default.createElement(
        Text,
        null,
        " ",
        error.message
      )
    ),
    origin && filePath && import_react11.default.createElement(
      Box_default,
      { marginTop: 1 },
      import_react11.default.createElement(
        Text,
        { dimColor: true },
        filePath,
        ":",
        origin.line,
        ":",
        origin.column
      )
    ),
    origin && excerpt && import_react11.default.createElement(Box_default, { marginTop: 1, flexDirection: "column" }, excerpt.map(({ line, value }) => import_react11.default.createElement(
      Box_default,
      { key: line },
      import_react11.default.createElement(
        Box_default,
        { width: lineWidth + 1 },
        import_react11.default.createElement(
          Text,
          { dimColor: line !== origin.line, backgroundColor: line === origin.line ? "red" : void 0, color: line === origin.line ? "white" : void 0, "aria-label": line === origin.line ? `Line ${line}, error` : `Line ${line}` },
          String(line).padStart(lineWidth, " "),
          ":"
        )
      ),
      import_react11.default.createElement(Text, { key: line, backgroundColor: line === origin.line ? "red" : void 0, color: line === origin.line ? "white" : void 0 }, " " + value)
    ))),
    error.stack && import_react11.default.createElement(Box_default, { marginTop: 1, flexDirection: "column" }, error.stack.split("\n").slice(1).map((line) => {
      const parsedLine = stackUtils.parseLine(line);
      if (!parsedLine) {
        return import_react11.default.createElement(
          Box_default,
          { key: line },
          import_react11.default.createElement(Text, { dimColor: true }, "- "),
          import_react11.default.createElement(
            Text,
            { dimColor: true, bold: true },
            line,
            "\\t",
            " "
          )
        );
      }
      return import_react11.default.createElement(
        Box_default,
        { key: line },
        import_react11.default.createElement(Text, { dimColor: true }, "- "),
        import_react11.default.createElement(Text, { dimColor: true, bold: true }, parsedLine.function),
        import_react11.default.createElement(
          Text,
          { dimColor: true, color: "gray", "aria-label": `at ${cleanupPath(parsedLine.file) ?? ""} line ${parsedLine.line} column ${parsedLine.column}` },
          " ",
          "(",
          cleanupPath(parsedLine.file) ?? "",
          ":",
          parsedLine.line,
          ":",
          parsedLine.column,
          ")"
        )
      );
    }))
  );
}
__name(ErrorOverview, "ErrorOverview");

// node_modules/ink/build/components/App.js
var tab = "	";
var shiftTab = "\x1B[Z";
var escape2 = "\x1B";
var App = class extends import_react12.PureComponent {
  static {
    __name(this, "App");
  }
  static displayName = "InternalApp";
  static getDerivedStateFromError(error) {
    return { error };
  }
  state = {
    isFocusEnabled: true,
    activeFocusId: void 0,
    focusables: [],
    error: void 0
  };
  // Count how many components enabled raw mode to avoid disabling
  // raw mode until all components don't need it anymore
  rawModeEnabledCount = 0;
  // eslint-disable-next-line @typescript-eslint/naming-convention
  internal_eventEmitter = new EventEmitter2();
  // Determines if TTY is supported on the provided stdin
  isRawModeSupported() {
    return this.props.stdin.isTTY;
  }
  render() {
    return import_react12.default.createElement(
      AppContext_default.Provider,
      {
        // eslint-disable-next-line react/jsx-no-constructed-context-values
        value: {
          exit: this.handleExit
        }
      },
      import_react12.default.createElement(
        StdinContext_default.Provider,
        {
          // eslint-disable-next-line react/jsx-no-constructed-context-values
          value: {
            stdin: this.props.stdin,
            setRawMode: this.handleSetRawMode,
            isRawModeSupported: this.isRawModeSupported(),
            // eslint-disable-next-line @typescript-eslint/naming-convention
            internal_exitOnCtrlC: this.props.exitOnCtrlC,
            // eslint-disable-next-line @typescript-eslint/naming-convention
            internal_eventEmitter: this.internal_eventEmitter
          }
        },
        import_react12.default.createElement(
          StdoutContext_default.Provider,
          {
            // eslint-disable-next-line react/jsx-no-constructed-context-values
            value: {
              stdout: this.props.stdout,
              write: this.props.writeToStdout
            }
          },
          import_react12.default.createElement(
            StderrContext_default.Provider,
            {
              // eslint-disable-next-line react/jsx-no-constructed-context-values
              value: {
                stderr: this.props.stderr,
                write: this.props.writeToStderr
              }
            },
            import_react12.default.createElement(
              FocusContext_default.Provider,
              {
                // eslint-disable-next-line react/jsx-no-constructed-context-values
                value: {
                  activeId: this.state.activeFocusId,
                  add: this.addFocusable,
                  remove: this.removeFocusable,
                  activate: this.activateFocusable,
                  deactivate: this.deactivateFocusable,
                  enableFocus: this.enableFocus,
                  disableFocus: this.disableFocus,
                  focusNext: this.focusNext,
                  focusPrevious: this.focusPrevious,
                  focus: this.focus
                }
              },
              this.state.error ? import_react12.default.createElement(ErrorOverview, { error: this.state.error }) : this.props.children
            )
          )
        )
      )
    );
  }
  componentDidMount() {
    cli_cursor_default.hide(this.props.stdout);
  }
  componentWillUnmount() {
    cli_cursor_default.show(this.props.stdout);
    if (this.isRawModeSupported()) {
      this.handleSetRawMode(false);
    }
  }
  componentDidCatch(error) {
    this.handleExit(error);
  }
  handleSetRawMode = /* @__PURE__ */ __name((isEnabled2) => {
    const { stdin } = this.props;
    if (!this.isRawModeSupported()) {
      if (stdin === process10.stdin) {
        throw new Error("Raw mode is not supported on the current process.stdin, which Ink uses as input stream by default.\nRead about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported");
      } else {
        throw new Error("Raw mode is not supported on the stdin provided to Ink.\nRead about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported");
      }
    }
    stdin.setEncoding("utf8");
    if (isEnabled2) {
      if (this.rawModeEnabledCount === 0) {
        stdin.ref();
        stdin.setRawMode(true);
        stdin.addListener("readable", this.handleReadable);
      }
      this.rawModeEnabledCount++;
      return;
    }
    if (--this.rawModeEnabledCount === 0) {
      stdin.setRawMode(false);
      stdin.removeListener("readable", this.handleReadable);
      stdin.unref();
    }
  }, "handleSetRawMode");
  handleReadable = /* @__PURE__ */ __name(() => {
    let chunk;
    while ((chunk = this.props.stdin.read()) !== null) {
      this.handleInput(chunk);
      this.internal_eventEmitter.emit("input", chunk);
    }
  }, "handleReadable");
  handleInput = /* @__PURE__ */ __name((input) => {
    if (input === "" && this.props.exitOnCtrlC) {
      this.handleExit();
    }
    if (input === escape2 && this.state.activeFocusId) {
      this.setState({
        activeFocusId: void 0
      });
    }
    if (this.state.isFocusEnabled && this.state.focusables.length > 0) {
      if (input === tab) {
        this.focusNext();
      }
      if (input === shiftTab) {
        this.focusPrevious();
      }
    }
  }, "handleInput");
  handleExit = /* @__PURE__ */ __name((error) => {
    if (this.isRawModeSupported()) {
      this.handleSetRawMode(false);
    }
    this.props.onExit(error);
  }, "handleExit");
  enableFocus = /* @__PURE__ */ __name(() => {
    this.setState({
      isFocusEnabled: true
    });
  }, "enableFocus");
  disableFocus = /* @__PURE__ */ __name(() => {
    this.setState({
      isFocusEnabled: false
    });
  }, "disableFocus");
  focus = /* @__PURE__ */ __name((id) => {
    this.setState((previousState) => {
      const hasFocusableId = previousState.focusables.some((focusable) => focusable?.id === id);
      if (!hasFocusableId) {
        return previousState;
      }
      return { activeFocusId: id };
    });
  }, "focus");
  focusNext = /* @__PURE__ */ __name(() => {
    this.setState((previousState) => {
      const firstFocusableId = previousState.focusables.find((focusable) => focusable.isActive)?.id;
      const nextFocusableId = this.findNextFocusable(previousState);
      return {
        activeFocusId: nextFocusableId ?? firstFocusableId
      };
    });
  }, "focusNext");
  focusPrevious = /* @__PURE__ */ __name(() => {
    this.setState((previousState) => {
      const lastFocusableId = previousState.focusables.findLast((focusable) => focusable.isActive)?.id;
      const previousFocusableId = this.findPreviousFocusable(previousState);
      return {
        activeFocusId: previousFocusableId ?? lastFocusableId
      };
    });
  }, "focusPrevious");
  addFocusable = /* @__PURE__ */ __name((id, { autoFocus }) => {
    this.setState((previousState) => {
      let nextFocusId = previousState.activeFocusId;
      if (!nextFocusId && autoFocus) {
        nextFocusId = id;
      }
      return {
        activeFocusId: nextFocusId,
        focusables: [
          ...previousState.focusables,
          {
            id,
            isActive: true
          }
        ]
      };
    });
  }, "addFocusable");
  removeFocusable = /* @__PURE__ */ __name((id) => {
    this.setState((previousState) => ({
      activeFocusId: previousState.activeFocusId === id ? void 0 : previousState.activeFocusId,
      focusables: previousState.focusables.filter((focusable) => {
        return focusable.id !== id;
      })
    }));
  }, "removeFocusable");
  activateFocusable = /* @__PURE__ */ __name((id) => {
    this.setState((previousState) => ({
      focusables: previousState.focusables.map((focusable) => {
        if (focusable.id !== id) {
          return focusable;
        }
        return {
          id,
          isActive: true
        };
      })
    }));
  }, "activateFocusable");
  deactivateFocusable = /* @__PURE__ */ __name((id) => {
    this.setState((previousState) => ({
      activeFocusId: previousState.activeFocusId === id ? void 0 : previousState.activeFocusId,
      focusables: previousState.focusables.map((focusable) => {
        if (focusable.id !== id) {
          return focusable;
        }
        return {
          id,
          isActive: false
        };
      })
    }));
  }, "deactivateFocusable");
  findNextFocusable = /* @__PURE__ */ __name((state) => {
    const activeIndex = state.focusables.findIndex((focusable) => {
      return focusable.id === state.activeFocusId;
    });
    for (let index = activeIndex + 1; index < state.focusables.length; index++) {
      const focusable = state.focusables[index];
      if (focusable?.isActive) {
        return focusable.id;
      }
    }
    return void 0;
  }, "findNextFocusable");
  findPreviousFocusable = /* @__PURE__ */ __name((state) => {
    const activeIndex = state.focusables.findIndex((focusable) => {
      return focusable.id === state.activeFocusId;
    });
    for (let index = activeIndex - 1; index >= 0; index--) {
      const focusable = state.focusables[index];
      if (focusable?.isActive) {
        return focusable.id;
      }
    }
    return void 0;
  }, "findPreviousFocusable");
};

// node_modules/ink/build/ink.js
var noop = /* @__PURE__ */ __name(() => {
}, "noop");
var Ink = class {
  static {
    __name(this, "Ink");
  }
  options;
  log;
  throttledLog;
  isScreenReaderEnabled;
  // Ignore last render after unmounting a tree to prevent empty output before exit
  isUnmounted;
  lastOutput;
  lastOutputHeight;
  container;
  rootNode;
  // This variable is used only in debug mode to store full static output
  // so that it's rerendered every time, not just new static parts, like in non-debug mode
  fullStaticOutput;
  exitPromise;
  restoreConsole;
  unsubscribeResize;
  constructor(options2) {
    autoBind(this);
    this.options = options2;
    this.rootNode = createNode("ink-root");
    this.rootNode.onComputeLayout = this.calculateLayout;
    this.isScreenReaderEnabled = options2.isScreenReaderEnabled ?? process11.env["INK_SCREEN_READER"] === "true";
    const unthrottled = options2.debug || this.isScreenReaderEnabled;
    this.rootNode.onRender = unthrottled ? this.onRender : throttle(this.onRender, 32, {
      leading: true,
      trailing: true
    });
    this.rootNode.onImmediateRender = this.onRender;
    this.log = log_update_default.create(options2.stdout);
    this.throttledLog = unthrottled ? this.log : throttle(this.log, void 0, {
      leading: true,
      trailing: true
    });
    this.isUnmounted = false;
    this.lastOutput = "";
    this.lastOutputHeight = 0;
    this.fullStaticOutput = "";
    this.container = reconciler_default.createContainer(
      this.rootNode,
      import_constants2.LegacyRoot,
      null,
      false,
      null,
      "id",
      () => {
      },
      () => {
      },
      // @ts-expect-error the types for `react-reconciler` are not up to date with the library.
      // See https://github.com/facebook/react/blob/c0464aedb16b1c970d717651bba8d1c66c578729/packages/react-reconciler/src/ReactFiberReconciler.js#L236-L259
      () => {
      },
      () => {
      },
      null
    );
    this.unsubscribeExit = (0, import_signal_exit2.default)(this.unmount, { alwaysLast: false });
    if (process11.env["DEV"] === "true") {
      reconciler_default.injectIntoDevTools({
        bundleType: 0,
        // Reporting React DOM's version, not Ink's
        // See https://github.com/facebook/react/issues/16666#issuecomment-532639905
        version: "16.13.1",
        rendererPackageName: "ink"
      });
    }
    if (options2.patchConsole) {
      this.patchConsole();
    }
    if (!is_in_ci_default) {
      options2.stdout.on("resize", this.resized);
      this.unsubscribeResize = () => {
        options2.stdout.off("resize", this.resized);
      };
    }
  }
  resized = /* @__PURE__ */ __name(() => {
    this.calculateLayout();
    this.onRender();
  }, "resized");
  resolveExitPromise = /* @__PURE__ */ __name(() => {
  }, "resolveExitPromise");
  rejectExitPromise = /* @__PURE__ */ __name(() => {
  }, "rejectExitPromise");
  unsubscribeExit = /* @__PURE__ */ __name(() => {
  }, "unsubscribeExit");
  calculateLayout = /* @__PURE__ */ __name(() => {
    const terminalWidth = this.options.stdout.columns || 80;
    this.rootNode.yogaNode.setWidth(terminalWidth);
    this.rootNode.yogaNode.calculateLayout(void 0, void 0, src_default.DIRECTION_LTR);
  }, "calculateLayout");
  onRender = /* @__PURE__ */ __name(() => {
    if (this.isUnmounted) {
      return;
    }
    const { output, outputHeight, staticOutput } = renderer_default(this.rootNode, this.isScreenReaderEnabled);
    const hasStaticOutput = staticOutput && staticOutput !== "\n";
    if (this.options.debug) {
      if (hasStaticOutput) {
        this.fullStaticOutput += staticOutput;
      }
      this.options.stdout.write(this.fullStaticOutput + output);
      return;
    }
    if (is_in_ci_default) {
      if (hasStaticOutput) {
        this.options.stdout.write(staticOutput);
      }
      this.lastOutput = output;
      this.lastOutputHeight = outputHeight;
      return;
    }
    if (this.isScreenReaderEnabled) {
      if (hasStaticOutput) {
        const erase = this.lastOutputHeight > 0 ? base_exports.eraseLines(this.lastOutputHeight) : "";
        this.options.stdout.write(erase + staticOutput);
        this.lastOutputHeight = 0;
      }
      if (output === this.lastOutput && !hasStaticOutput) {
        return;
      }
      const terminalWidth = this.options.stdout.columns || 80;
      const wrappedOutput = wrapAnsi(output, terminalWidth, {
        trim: false,
        hard: true
      });
      if (hasStaticOutput) {
        this.options.stdout.write(wrappedOutput);
      } else {
        const erase = this.lastOutputHeight > 0 ? base_exports.eraseLines(this.lastOutputHeight) : "";
        this.options.stdout.write(erase + wrappedOutput);
      }
      this.lastOutput = output;
      this.lastOutputHeight = wrappedOutput === "" ? 0 : wrappedOutput.split("\n").length;
      return;
    }
    if (hasStaticOutput) {
      this.fullStaticOutput += staticOutput;
    }
    if (this.lastOutputHeight >= this.options.stdout.rows) {
      this.options.stdout.write(base_exports.clearTerminal + this.fullStaticOutput + output + "\n");
      this.lastOutput = output;
      this.lastOutputHeight = outputHeight;
      this.log.sync(output);
      return;
    }
    if (hasStaticOutput) {
      this.log.clear();
      this.options.stdout.write(staticOutput);
      this.log(output);
    }
    if (!hasStaticOutput && output !== this.lastOutput) {
      this.throttledLog(output);
    }
    this.lastOutput = output;
    this.lastOutputHeight = outputHeight;
  }, "onRender");
  render(node) {
    const tree = import_react13.default.createElement(
      accessibilityContext.Provider,
      { value: { isScreenReaderEnabled: this.isScreenReaderEnabled } },
      import_react13.default.createElement(App, { stdin: this.options.stdin, stdout: this.options.stdout, stderr: this.options.stderr, writeToStdout: this.writeToStdout, writeToStderr: this.writeToStderr, exitOnCtrlC: this.options.exitOnCtrlC, onExit: this.unmount }, node)
    );
    reconciler_default.updateContainerSync(tree, this.container, null, noop);
    reconciler_default.flushSyncWork();
  }
  writeToStdout(data) {
    if (this.isUnmounted) {
      return;
    }
    if (this.options.debug) {
      this.options.stdout.write(data + this.fullStaticOutput + this.lastOutput);
      return;
    }
    if (is_in_ci_default) {
      this.options.stdout.write(data);
      return;
    }
    this.log.clear();
    this.options.stdout.write(data);
    this.log(this.lastOutput);
  }
  writeToStderr(data) {
    if (this.isUnmounted) {
      return;
    }
    if (this.options.debug) {
      this.options.stderr.write(data);
      this.options.stdout.write(this.fullStaticOutput + this.lastOutput);
      return;
    }
    if (is_in_ci_default) {
      this.options.stderr.write(data);
      return;
    }
    this.log.clear();
    this.options.stderr.write(data);
    this.log(this.lastOutput);
  }
  // eslint-disable-next-line @typescript-eslint/ban-types
  unmount(error) {
    if (this.isUnmounted) {
      return;
    }
    this.calculateLayout();
    this.onRender();
    this.unsubscribeExit();
    if (typeof this.restoreConsole === "function") {
      this.restoreConsole();
    }
    if (typeof this.unsubscribeResize === "function") {
      this.unsubscribeResize();
    }
    if (is_in_ci_default) {
      this.options.stdout.write(this.lastOutput + "\n");
    } else if (!this.options.debug) {
      this.log.done();
    }
    this.isUnmounted = true;
    reconciler_default.updateContainerSync(null, this.container, null, noop);
    reconciler_default.flushSyncWork();
    instances_default.delete(this.options.stdout);
    if (error instanceof Error) {
      this.rejectExitPromise(error);
    } else {
      this.resolveExitPromise();
    }
  }
  async waitUntilExit() {
    this.exitPromise ||= new Promise((resolve24, reject) => {
      this.resolveExitPromise = resolve24;
      this.rejectExitPromise = reject;
    });
    return this.exitPromise;
  }
  clear() {
    if (!is_in_ci_default && !this.options.debug) {
      this.log.clear();
    }
  }
  patchConsole() {
    if (this.options.debug) {
      return;
    }
    this.restoreConsole = dist_default((stream2, data) => {
      if (stream2 === "stdout") {
        this.writeToStdout(data);
      }
      if (stream2 === "stderr") {
        const isReactMessage = data.startsWith("The above error occurred");
        if (!isReactMessage) {
          this.writeToStderr(data);
        }
      }
    });
  }
};

// node_modules/ink/build/render.js
var render = /* @__PURE__ */ __name((node, options2) => {
  const inkOptions = {
    stdout: process12.stdout,
    stdin: process12.stdin,
    stderr: process12.stderr,
    debug: false,
    exitOnCtrlC: true,
    patchConsole: true,
    ...getOptions(options2)
  };
  const instance = getInstance(inkOptions.stdout, () => new Ink(inkOptions));
  instance.render(node);
  return {
    rerender: instance.render,
    unmount() {
      instance.unmount();
    },
    waitUntilExit: instance.waitUntilExit,
    cleanup: /* @__PURE__ */ __name(() => instances_default.delete(inkOptions.stdout), "cleanup"),
    clear: instance.clear
  };
}, "render");
var render_default = render;
var getOptions = /* @__PURE__ */ __name((stdout = {}) => {
  if (stdout instanceof Stream) {
    return {
      stdout,
      stdin: process12.stdin
    };
  }
  return stdout;
}, "getOptions");
var getInstance = /* @__PURE__ */ __name((stdout, createInstance2) => {
  let instance = instances_default.get(stdout);
  if (!instance) {
    instance = createInstance2();
    instances_default.set(stdout, instance);
  }
  return instance;
}, "getInstance");

// node_modules/ink/build/components/Static.js
init_esbuild_shims();
var import_react14 = __toESM(require_react(), 1);
function Static(props) {
  const { items, children: render3, style: customStyle } = props;
  const [index, setIndex] = (0, import_react14.useState)(0);
  const itemsToRender = (0, import_react14.useMemo)(() => {
    return items.slice(index);
  }, [items, index]);
  (0, import_react14.useLayoutEffect)(() => {
    setIndex(items.length);
  }, [items.length]);
  const children = itemsToRender.map((item, itemIndex) => {
    return render3(item, index + itemIndex);
  });
  const style = (0, import_react14.useMemo)(() => ({
    position: "absolute",
    flexDirection: "column",
    ...customStyle
  }), [customStyle]);
  return import_react14.default.createElement("ink-box", { internal_static: true, style }, children);
}
__name(Static, "Static");

// node_modules/ink/build/components/Transform.js
init_esbuild_shims();
var import_react15 = __toESM(require_react(), 1);
function Transform({ children, transform, accessibilityLabel }) {
  const { isScreenReaderEnabled } = (0, import_react15.useContext)(accessibilityContext);
  if (children === void 0 || children === null) {
    return null;
  }
  return import_react15.default.createElement("ink-text", { style: { flexGrow: 0, flexShrink: 1, flexDirection: "row" }, internal_transform: transform }, isScreenReaderEnabled && accessibilityLabel ? accessibilityLabel : children);
}
__name(Transform, "Transform");

// node_modules/ink/build/components/Newline.js
init_esbuild_shims();
var import_react16 = __toESM(require_react(), 1);

// node_modules/ink/build/components/Spacer.js
init_esbuild_shims();
var import_react17 = __toESM(require_react(), 1);

// node_modules/ink/build/hooks/use-input.js
init_esbuild_shims();
var import_react19 = __toESM(require_react(), 1);

// node_modules/ink/build/parse-keypress.js
init_esbuild_shims();
var keyName = {
  /* xterm/gnome ESC O letter */
  OP: "f1",
  OQ: "f2",
  OR: "f3",
  OS: "f4",
  /* xterm/rxvt ESC [ number ~ */
  "[11~": "f1",
  "[12~": "f2",
  "[13~": "f3",
  "[14~": "f4",
  /* from Cygwin and used in libuv */
  "[[A": "f1",
  "[[B": "f2",
  "[[C": "f3",
  "[[D": "f4",
  "[[E": "f5",
  /* common */
  "[15~": "f5",
  "[17~": "f6",
  "[18~": "f7",
  "[19~": "f8",
  "[20~": "f9",
  "[21~": "f10",
  "[23~": "f11",
  "[24~": "f12",
  /* xterm ESC [ letter */
  "[A": "up",
  "[B": "down",
  "[C": "right",
  "[D": "left",
  "[E": "clear",
  "[F": "end",
  "[H": "home",
  /* xterm/gnome ESC O letter */
  OA: "up",
  OB: "down",
  OC: "right",
  OD: "left",
  OE: "clear",
  OF: "end",
  OH: "home",
  /* xterm/rxvt ESC [ number ~ */
  "[1~": "home",
  "[2~": "insert",
  "[3~": "delete",
  "[4~": "end",
  "[5~": "pageup",
  "[6~": "pagedown",
  /* putty */
  "[[5~": "pageup",
  "[[6~": "pagedown",
  /* rxvt */
  "[7~": "home",
  "[8~": "end",
  /* rxvt keys with modifiers */
  "[a": "up",
  "[b": "down",
  "[c": "right",
  "[d": "left",
  "[e": "clear",
  "[2$": "insert",
  "[3$": "delete",
  "[5$": "pageup",
  "[6$": "pagedown",
  "[7$": "home",
  "[8$": "end",
  Oa: "up",
  Ob: "down",
  Oc: "right",
  Od: "left",
  Oe: "clear",
  "[2^": "insert",
  "[3^": "delete",
  "[5^": "pageup",
  "[6^": "pagedown",
  "[7^": "home",
  "[8^": "end",
  /* misc. */
  "[Z": "tab"
};
var nonAlphanumericKeys = [...Object.values(keyName), "backspace"];

// node_modules/ink/build/hooks/use-stdin.js
init_esbuild_shims();
var import_react18 = __toESM(require_react(), 1);
var useStdin = /* @__PURE__ */ __name(() => (0, import_react18.useContext)(StdinContext_default), "useStdin");
var use_stdin_default = useStdin;

// node_modules/ink/build/hooks/use-app.js
init_esbuild_shims();
var import_react20 = __toESM(require_react(), 1);

// node_modules/ink/build/hooks/use-stdout.js
init_esbuild_shims();
var import_react21 = __toESM(require_react(), 1);
var useStdout = /* @__PURE__ */ __name(() => (0, import_react21.useContext)(StdoutContext_default), "useStdout");
var use_stdout_default = useStdout;

// node_modules/ink/build/hooks/use-stderr.js
init_esbuild_shims();
var import_react22 = __toESM(require_react(), 1);

// node_modules/ink/build/hooks/use-focus.js
init_esbuild_shims();
var import_react23 = __toESM(require_react(), 1);

// node_modules/ink/build/hooks/use-focus-manager.js
init_esbuild_shims();
var import_react24 = __toESM(require_react(), 1);

// node_modules/ink/build/hooks/use-is-screen-reader-enabled.js
init_esbuild_shims();
var import_react25 = __toESM(require_react(), 1);
var useIsScreenReaderEnabled = /* @__PURE__ */ __name(() => {
  const { isScreenReaderEnabled } = (0, import_react25.useContext)(accessibilityContext);
  return isScreenReaderEnabled;
}, "useIsScreenReaderEnabled");
var use_is_screen_reader_enabled_default = useIsScreenReaderEnabled;

// node_modules/ink/build/measure-element.js
init_esbuild_shims();
var measureElement = /* @__PURE__ */ __name((node) => ({
  width: node.yogaNode?.getComputedWidth() ?? 0,
  height: node.yogaNode?.getComputedHeight() ?? 0
}), "measureElement");
var measure_element_default = measureElement;

// packages/cli/src/ui/AppContainer.tsx
init_esbuild_shims();
var import_react134 = __toESM(require_react(), 1);

// packages/cli/src/ui/App.tsx
init_esbuild_shims();

// packages/cli/src/ui/hooks/useTerminalSize.ts
init_esbuild_shims();
var import_react26 = __toESM(require_react(), 1);
var TERMINAL_PADDING_X = 8;
function useTerminalSize() {
  const [size, setSize] = (0, import_react26.useState)({
    columns: (process.stdout.columns || 60) - TERMINAL_PADDING_X,
    rows: process.stdout.rows || 20
  });
  (0, import_react26.useEffect)(() => {
    function updateSize() {
      setSize({
        columns: (process.stdout.columns || 60) - TERMINAL_PADDING_X,
        rows: process.stdout.rows || 20
      });
    }
    __name(updateSize, "updateSize");
    process.stdout.on("resize", updateSize);
    return () => {
      process.stdout.off("resize", updateSize);
    };
  }, []);
  return size;
}
__name(useTerminalSize, "useTerminalSize");

// packages/cli/src/utils/math.ts
init_esbuild_shims();
var lerp = /* @__PURE__ */ __name((start, end, t2) => start + (end - start) * t2, "lerp");

// packages/cli/src/ui/contexts/UIStateContext.tsx
init_esbuild_shims();
var import_react30 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useHistoryManager.ts
init_esbuild_shims();
var import_react27 = __toESM(require_react(), 1);
function useHistory() {
  const [history, setHistory] = (0, import_react27.useState)([]);
  const messageIdCounterRef = (0, import_react27.useRef)(0);
  const getNextMessageId = (0, import_react27.useCallback)((baseTimestamp) => {
    messageIdCounterRef.current += 1;
    return baseTimestamp + messageIdCounterRef.current;
  }, []);
  const loadHistory = (0, import_react27.useCallback)((newHistory) => {
    setHistory(newHistory);
  }, []);
  const addItem = (0, import_react27.useCallback)(
    (itemData, baseTimestamp) => {
      const id = getNextMessageId(baseTimestamp);
      const newItem = { ...itemData, id };
      setHistory((prevHistory) => {
        if (prevHistory.length > 0) {
          const lastItem = prevHistory[prevHistory.length - 1];
          if (lastItem.type === "user" && newItem.type === "user" && lastItem.text === newItem.text) {
            return prevHistory;
          }
        }
        return [...prevHistory, newItem];
      });
      return id;
    },
    [getNextMessageId]
  );
  const updateItem = (0, import_react27.useCallback)(
    (id, updates) => {
      setHistory(
        (prevHistory) => prevHistory.map((item) => {
          if (item.id === id) {
            const newUpdates = typeof updates === "function" ? updates(item) : updates;
            return { ...item, ...newUpdates };
          }
          return item;
        })
      );
    },
    []
  );
  const clearItems = (0, import_react27.useCallback)(() => {
    setHistory([]);
    messageIdCounterRef.current = 0;
  }, []);
  return {
    history,
    addItem,
    updateItem,
    clearItems,
    loadHistory
  };
}
__name(useHistory, "useHistory");

// packages/cli/src/ui/hooks/useIdeTrustListener.ts
init_esbuild_shims();
var import_react29 = __toESM(require_react(), 1);

// packages/core/dist/index.js
init_esbuild_shims();
init_src();
init_storage();
init_models();
init_terminalSerializer();
init_config3();
init_detect_ide();
init_loggers();
init_types3();

// packages/core/dist/src/test-utils/config.js
init_esbuild_shims();
init_config3();

// packages/core/dist/src/utils/pathReader.js
init_esbuild_shims();
init_esm9();
init_fileUtils();
import { promises as fs51 } from "node:fs";
import path58 from "node:path";
async function readPathFromWorkspace(pathStr, config) {
  const workspace = config.getWorkspaceContext();
  const fileService = config.getFileService();
  let absolutePath = null;
  if (path58.isAbsolute(pathStr)) {
    if (!workspace.isPathWithinWorkspace(pathStr)) {
      throw new Error(`Absolute path is outside of the allowed workspace: ${pathStr}`);
    }
    absolutePath = pathStr;
  } else {
    const searchDirs = workspace.getDirectories();
    for (const dir of searchDirs) {
      const potentialPath = path58.resolve(dir, pathStr);
      try {
        await fs51.access(potentialPath);
        absolutePath = potentialPath;
        break;
      } catch {
      }
    }
  }
  if (!absolutePath) {
    throw new Error(`Path not found in workspace: ${pathStr}`);
  }
  const stats = await fs51.stat(absolutePath);
  if (stats.isDirectory()) {
    const allParts = [];
    allParts.push({
      text: `--- Start of content for directory: ${pathStr} ---
`
    });
    const files = await glob("**/*", {
      cwd: absolutePath,
      nodir: true,
      // We only want files
      dot: true,
      // Include dotfiles
      absolute: true
    });
    const relativeFiles = files.map((p) => path58.relative(config.getTargetDir(), p));
    const filteredFiles = fileService.filterFiles(relativeFiles, {
      respectGitIgnore: true,
      respectQwenIgnore: true
    });
    const finalFiles = filteredFiles.map((p) => path58.resolve(config.getTargetDir(), p));
    for (const filePath of finalFiles) {
      const relativePathForDisplay = path58.relative(absolutePath, filePath);
      allParts.push({ text: `--- ${relativePathForDisplay} ---
` });
      const result = await processSingleFileContent(filePath, config);
      allParts.push(result.llmContent);
      allParts.push({ text: "\n" });
    }
    allParts.push({ text: `--- End of content for directory: ${pathStr} ---` });
    return allParts;
  } else {
    const relativePath = path58.relative(config.getTargetDir(), absolutePath);
    const filtered = fileService.filterFiles([relativePath], {
      respectGitIgnore: true,
      respectQwenIgnore: true
    });
    if (filtered.length === 0) {
      return [];
    }
    const result = await processSingleFileContent(absolutePath, config);
    return [result.llmContent];
  }
}
__name(readPathFromWorkspace, "readPathFromWorkspace");

// packages/core/dist/index.js
init_supportedImageFormats();

// packages/core/dist/src/telemetry/clearcut-logger/clearcut-logger.js
init_esbuild_shims();
var import_https_proxy_agent2 = __toESM(require_dist2(), 1);

// packages/core/dist/src/telemetry/clearcut-logger/event-metadata-key.js
init_esbuild_shims();
var EventMetadataKey;
(function(EventMetadataKey2) {
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_KEY_UNKNOWN"] = 0] = "GEMINI_CLI_KEY_UNKNOWN";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_START_SESSION_MODEL"] = 1] = "GEMINI_CLI_START_SESSION_MODEL";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_START_SESSION_EMBEDDING_MODEL"] = 2] = "GEMINI_CLI_START_SESSION_EMBEDDING_MODEL";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_START_SESSION_SANDBOX"] = 3] = "GEMINI_CLI_START_SESSION_SANDBOX";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_START_SESSION_CORE_TOOLS"] = 4] = "GEMINI_CLI_START_SESSION_CORE_TOOLS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_START_SESSION_APPROVAL_MODE"] = 5] = "GEMINI_CLI_START_SESSION_APPROVAL_MODE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_START_SESSION_API_KEY_ENABLED"] = 6] = "GEMINI_CLI_START_SESSION_API_KEY_ENABLED";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_START_SESSION_VERTEX_API_ENABLED"] = 7] = "GEMINI_CLI_START_SESSION_VERTEX_API_ENABLED";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_START_SESSION_DEBUG_MODE_ENABLED"] = 8] = "GEMINI_CLI_START_SESSION_DEBUG_MODE_ENABLED";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_START_SESSION_MCP_SERVERS"] = 9] = "GEMINI_CLI_START_SESSION_MCP_SERVERS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_START_SESSION_TELEMETRY_ENABLED"] = 10] = "GEMINI_CLI_START_SESSION_TELEMETRY_ENABLED";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED"] = 11] = "GEMINI_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_START_SESSION_RESPECT_GITIGNORE"] = 12] = "GEMINI_CLI_START_SESSION_RESPECT_GITIGNORE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_START_SESSION_OUTPUT_FORMAT"] = 94] = "GEMINI_CLI_START_SESSION_OUTPUT_FORMAT";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_USER_PROMPT_LENGTH"] = 13] = "GEMINI_CLI_USER_PROMPT_LENGTH";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_TOOL_CALL_NAME"] = 14] = "GEMINI_CLI_TOOL_CALL_NAME";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_TOOL_CALL_MCP_SERVER_NAME"] = 95] = "GEMINI_CLI_TOOL_CALL_MCP_SERVER_NAME";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_TOOL_CALL_DECISION"] = 15] = "GEMINI_CLI_TOOL_CALL_DECISION";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_TOOL_CALL_SUCCESS"] = 16] = "GEMINI_CLI_TOOL_CALL_SUCCESS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_TOOL_CALL_DURATION_MS"] = 17] = "GEMINI_CLI_TOOL_CALL_DURATION_MS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_TOOL_ERROR_MESSAGE"] = 18] = "GEMINI_CLI_TOOL_ERROR_MESSAGE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_TOOL_CALL_ERROR_TYPE"] = 19] = "GEMINI_CLI_TOOL_CALL_ERROR_TYPE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_TOOL_CALL_CONTENT_LENGTH"] = 93] = "GEMINI_CLI_TOOL_CALL_CONTENT_LENGTH";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_API_REQUEST_MODEL"] = 20] = "GEMINI_CLI_API_REQUEST_MODEL";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_API_RESPONSE_MODEL"] = 21] = "GEMINI_CLI_API_RESPONSE_MODEL";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_API_RESPONSE_STATUS_CODE"] = 22] = "GEMINI_CLI_API_RESPONSE_STATUS_CODE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_API_RESPONSE_DURATION_MS"] = 23] = "GEMINI_CLI_API_RESPONSE_DURATION_MS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_API_RESPONSE_INPUT_TOKEN_COUNT"] = 25] = "GEMINI_CLI_API_RESPONSE_INPUT_TOKEN_COUNT";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT"] = 26] = "GEMINI_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_API_RESPONSE_CACHED_TOKEN_COUNT"] = 27] = "GEMINI_CLI_API_RESPONSE_CACHED_TOKEN_COUNT";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_API_RESPONSE_THINKING_TOKEN_COUNT"] = 28] = "GEMINI_CLI_API_RESPONSE_THINKING_TOKEN_COUNT";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_API_RESPONSE_TOOL_TOKEN_COUNT"] = 29] = "GEMINI_CLI_API_RESPONSE_TOOL_TOKEN_COUNT";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_API_ERROR_MODEL"] = 30] = "GEMINI_CLI_API_ERROR_MODEL";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_API_ERROR_TYPE"] = 31] = "GEMINI_CLI_API_ERROR_TYPE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_API_ERROR_STATUS_CODE"] = 32] = "GEMINI_CLI_API_ERROR_STATUS_CODE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_API_ERROR_DURATION_MS"] = 33] = "GEMINI_CLI_API_ERROR_DURATION_MS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_END_SESSION_ID"] = 34] = "GEMINI_CLI_END_SESSION_ID";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_PROMPT_ID"] = 35] = "GEMINI_CLI_PROMPT_ID";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_AUTH_TYPE"] = 36] = "GEMINI_CLI_AUTH_TYPE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_GOOGLE_ACCOUNTS_COUNT"] = 37] = "GEMINI_CLI_GOOGLE_ACCOUNTS_COUNT";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_SURFACE"] = 39] = "GEMINI_CLI_SURFACE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_SESSION_ID"] = 40] = "GEMINI_CLI_SESSION_ID";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_VERSION"] = 54] = "GEMINI_CLI_VERSION";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_GIT_COMMIT_HASH"] = 55] = "GEMINI_CLI_GIT_COMMIT_HASH";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_OS"] = 82] = "GEMINI_CLI_OS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_USER_SETTINGS"] = 84] = "GEMINI_CLI_USER_SETTINGS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_LOOP_DETECTED_TYPE"] = 38] = "GEMINI_CLI_LOOP_DETECTED_TYPE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_SLASH_COMMAND_NAME"] = 41] = "GEMINI_CLI_SLASH_COMMAND_NAME";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_SLASH_COMMAND_SUBCOMMAND"] = 42] = "GEMINI_CLI_SLASH_COMMAND_SUBCOMMAND";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_SLASH_COMMAND_STATUS"] = 51] = "GEMINI_CLI_SLASH_COMMAND_STATUS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_RESPONSE_FINISH_REASON"] = 43] = "GEMINI_CLI_RESPONSE_FINISH_REASON";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_NEXT_SPEAKER_CHECK_RESULT"] = 44] = "GEMINI_CLI_NEXT_SPEAKER_CHECK_RESULT";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_MALFORMED_JSON_RESPONSE_MODEL"] = 45] = "GEMINI_CLI_MALFORMED_JSON_RESPONSE_MODEL";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_IDE_CONNECTION_TYPE"] = 46] = "GEMINI_CLI_IDE_CONNECTION_TYPE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_AI_ADDED_LINES"] = 47] = "GEMINI_CLI_AI_ADDED_LINES";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_AI_REMOVED_LINES"] = 48] = "GEMINI_CLI_AI_REMOVED_LINES";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_USER_ADDED_LINES"] = 49] = "GEMINI_CLI_USER_ADDED_LINES";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_USER_REMOVED_LINES"] = 50] = "GEMINI_CLI_USER_REMOVED_LINES";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_AI_ADDED_CHARS"] = 103] = "GEMINI_CLI_AI_ADDED_CHARS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_AI_REMOVED_CHARS"] = 104] = "GEMINI_CLI_AI_REMOVED_CHARS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_USER_ADDED_CHARS"] = 105] = "GEMINI_CLI_USER_ADDED_CHARS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_USER_REMOVED_CHARS"] = 106] = "GEMINI_CLI_USER_REMOVED_CHARS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_KITTY_TRUNCATED_SEQUENCE"] = 52] = "GEMINI_CLI_KITTY_TRUNCATED_SEQUENCE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_KITTY_SEQUENCE_LENGTH"] = 53] = "GEMINI_CLI_KITTY_SEQUENCE_LENGTH";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_APPROVAL_MODE"] = 58] = "GEMINI_CLI_APPROVAL_MODE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_CONVERSATION_TURN_COUNT"] = 59] = "GEMINI_CLI_CONVERSATION_TURN_COUNT";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_COMPRESSION_TOKENS_BEFORE"] = 60] = "GEMINI_CLI_COMPRESSION_TOKENS_BEFORE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_COMPRESSION_TOKENS_AFTER"] = 61] = "GEMINI_CLI_COMPRESSION_TOKENS_AFTER";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_TOOL_TYPE"] = 62] = "GEMINI_CLI_TOOL_TYPE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_START_SESSION_MCP_SERVERS_COUNT"] = 63] = "GEMINI_CLI_START_SESSION_MCP_SERVERS_COUNT";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_START_SESSION_MCP_TOOLS_COUNT"] = 64] = "GEMINI_CLI_START_SESSION_MCP_TOOLS_COUNT";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_START_SESSION_MCP_TOOLS"] = 65] = "GEMINI_CLI_START_SESSION_MCP_TOOLS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_RESEARCH_OPT_IN_STATUS"] = 66] = "GEMINI_CLI_RESEARCH_OPT_IN_STATUS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_RESEARCH_CONTACT_EMAIL"] = 67] = "GEMINI_CLI_RESEARCH_CONTACT_EMAIL";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_RESEARCH_USER_ID"] = 68] = "GEMINI_CLI_RESEARCH_USER_ID";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_RESEARCH_FEEDBACK_TYPE"] = 69] = "GEMINI_CLI_RESEARCH_FEEDBACK_TYPE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_RESEARCH_FEEDBACK_CONTENT"] = 70] = "GEMINI_CLI_RESEARCH_FEEDBACK_CONTENT";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_RESEARCH_SURVEY_RESPONSES"] = 71] = "GEMINI_CLI_RESEARCH_SURVEY_RESPONSES";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_PROGRAMMING_LANGUAGE"] = 56] = "GEMINI_CLI_PROGRAMMING_LANGUAGE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_FILE_OPERATION_TYPE"] = 57] = "GEMINI_CLI_FILE_OPERATION_TYPE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_FILE_OPERATION_LINES"] = 72] = "GEMINI_CLI_FILE_OPERATION_LINES";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_FILE_OPERATION_MIMETYPE"] = 73] = "GEMINI_CLI_FILE_OPERATION_MIMETYPE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_FILE_OPERATION_EXTENSION"] = 74] = "GEMINI_CLI_FILE_OPERATION_EXTENSION";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_INVALID_CHUNK_ERROR_MESSAGE"] = 75] = "GEMINI_CLI_INVALID_CHUNK_ERROR_MESSAGE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_CONTENT_RETRY_ATTEMPT_NUMBER"] = 76] = "GEMINI_CLI_CONTENT_RETRY_ATTEMPT_NUMBER";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_CONTENT_RETRY_ERROR_TYPE"] = 77] = "GEMINI_CLI_CONTENT_RETRY_ERROR_TYPE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_CONTENT_RETRY_DELAY_MS"] = 78] = "GEMINI_CLI_CONTENT_RETRY_DELAY_MS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_ATTEMPTS"] = 79] = "GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_ATTEMPTS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_CONTENT_RETRY_FAILURE_FINAL_ERROR_TYPE"] = 80] = "GEMINI_CLI_CONTENT_RETRY_FAILURE_FINAL_ERROR_TYPE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_DURATION_MS"] = 81] = "GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_DURATION_MS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_NODE_VERSION"] = 83] = "GEMINI_CLI_NODE_VERSION";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_EXTENSION_NAME"] = 85] = "GEMINI_CLI_EXTENSION_NAME";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_EXTENSION_VERSION"] = 86] = "GEMINI_CLI_EXTENSION_VERSION";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_EXTENSION_SOURCE"] = 87] = "GEMINI_CLI_EXTENSION_SOURCE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_EXTENSION_INSTALL_STATUS"] = 88] = "GEMINI_CLI_EXTENSION_INSTALL_STATUS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_EXTENSION_UNINSTALL_STATUS"] = 96] = "GEMINI_CLI_EXTENSION_UNINSTALL_STATUS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_EXTENSION_ENABLE_SETTING_SCOPE"] = 102] = "GEMINI_CLI_EXTENSION_ENABLE_SETTING_SCOPE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_EXTENSION_DISABLE_SETTING_SCOPE"] = 107] = "GEMINI_CLI_EXTENSION_DISABLE_SETTING_SCOPE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_ORIGINAL_LENGTH"] = 89] = "GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_ORIGINAL_LENGTH";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_TRUNCATED_LENGTH"] = 90] = "GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_TRUNCATED_LENGTH";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_THRESHOLD"] = 91] = "GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_THRESHOLD";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_LINES"] = 92] = "GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_LINES";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_ROUTING_DECISION"] = 97] = "GEMINI_CLI_ROUTING_DECISION";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_ROUTING_FAILURE"] = 98] = "GEMINI_CLI_ROUTING_FAILURE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_ROUTING_LATENCY_MS"] = 99] = "GEMINI_CLI_ROUTING_LATENCY_MS";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_ROUTING_FAILURE_REASON"] = 100] = "GEMINI_CLI_ROUTING_FAILURE_REASON";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_ROUTING_DECISION_SOURCE"] = 101] = "GEMINI_CLI_ROUTING_DECISION_SOURCE";
  EventMetadataKey2[EventMetadataKey2["GEMINI_CLI_MODEL_SLASH_COMMAND"] = 108] = "GEMINI_CLI_MODEL_SLASH_COMMAND";
})(EventMetadataKey || (EventMetadataKey = {}));

// packages/core/dist/src/telemetry/clearcut-logger/clearcut-logger.js
init_installationManager();
init_userAccountManager();
init_safeJsonStringify();

// packages/core/dist/src/generated/git-commit.js
init_esbuild_shims();

// packages/core/dist/src/telemetry/clearcut-logger/clearcut-logger.js
init_detect_ide();
var EventNames;
(function(EventNames2) {
  EventNames2["START_SESSION"] = "start_session";
  EventNames2["NEW_PROMPT"] = "new_prompt";
  EventNames2["TOOL_CALL"] = "tool_call";
  EventNames2["FILE_OPERATION"] = "file_operation";
  EventNames2["API_REQUEST"] = "api_request";
  EventNames2["API_RESPONSE"] = "api_response";
  EventNames2["API_ERROR"] = "api_error";
  EventNames2["END_SESSION"] = "end_session";
  EventNames2["FLASH_FALLBACK"] = "flash_fallback";
  EventNames2["RIPGREP_FALLBACK"] = "ripgrep_fallback";
  EventNames2["LOOP_DETECTED"] = "loop_detected";
  EventNames2["LOOP_DETECTION_DISABLED"] = "loop_detection_disabled";
  EventNames2["NEXT_SPEAKER_CHECK"] = "next_speaker_check";
  EventNames2["SLASH_COMMAND"] = "slash_command";
  EventNames2["MALFORMED_JSON_RESPONSE"] = "malformed_json_response";
  EventNames2["IDE_CONNECTION"] = "ide_connection";
  EventNames2["KITTY_SEQUENCE_OVERFLOW"] = "kitty_sequence_overflow";
  EventNames2["CHAT_COMPRESSION"] = "chat_compression";
  EventNames2["CONVERSATION_FINISHED"] = "conversation_finished";
  EventNames2["INVALID_CHUNK"] = "invalid_chunk";
  EventNames2["CONTENT_RETRY"] = "content_retry";
  EventNames2["CONTENT_RETRY_FAILURE"] = "content_retry_failure";
  EventNames2["EXTENSION_ENABLE"] = "extension_enable";
  EventNames2["EXTENSION_DISABLE"] = "extension_disable";
  EventNames2["EXTENSION_INSTALL"] = "extension_install";
  EventNames2["EXTENSION_UNINSTALL"] = "extension_uninstall";
  EventNames2["TOOL_OUTPUT_TRUNCATED"] = "tool_output_truncated";
  EventNames2["MODEL_SLASH_COMMAND"] = "model_slash_command";
})(EventNames || (EventNames = {}));
var FLUSH_INTERVAL_MS2 = 1e3 * 60;

// packages/core/dist/index.js
init_qwen_logger();
init_loggers();

// packages/cli/src/ui/contexts/SettingsContext.tsx
init_esbuild_shims();
var import_react28 = __toESM(require_react(), 1);
var SettingsContext = import_react28.default.createContext(
  void 0
);
var useSettings = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react28.useContext)(SettingsContext);
  if (context2 === void 0) {
    throw new Error("useSettings must be used within a SettingsProvider");
  }
  return context2;
}, "useSettings");

// packages/cli/src/config/trustedFolders.ts
init_esbuild_shims();
import * as fs52 from "node:fs";
import * as path59 from "node:path";
import { homedir as homedir11 } from "node:os";
var import_strip_json_comments = __toESM(require_strip_json_comments(), 1);
var TRUSTED_FOLDERS_FILENAME = "trustedFolders.json";
var SETTINGS_DIRECTORY_NAME = ".qwen";
var USER_SETTINGS_DIR = path59.join(homedir11(), SETTINGS_DIRECTORY_NAME);
function getTrustedFoldersPath() {
  if (process.env["GEMINI_CLI_TRUSTED_FOLDERS_PATH"]) {
    return process.env["GEMINI_CLI_TRUSTED_FOLDERS_PATH"];
  }
  return path59.join(USER_SETTINGS_DIR, TRUSTED_FOLDERS_FILENAME);
}
__name(getTrustedFoldersPath, "getTrustedFoldersPath");
var LoadedTrustedFolders = class {
  constructor(user, errors) {
    this.user = user;
    this.errors = errors;
  }
  static {
    __name(this, "LoadedTrustedFolders");
  }
  get rules() {
    return Object.entries(this.user.config).map(([path108, trustLevel]) => ({
      path: path108,
      trustLevel
    }));
  }
  /**
   * Returns true or false if the path should be "trusted". This function
   * should only be invoked when the folder trust setting is active.
   *
   * @param location path
   * @returns
   */
  isPathTrusted(location) {
    const trustedPaths = [];
    const untrustedPaths = [];
    for (const rule of this.rules) {
      switch (rule.trustLevel) {
        case "TRUST_FOLDER" /* TRUST_FOLDER */:
          trustedPaths.push(rule.path);
          break;
        case "TRUST_PARENT" /* TRUST_PARENT */:
          trustedPaths.push(path59.dirname(rule.path));
          break;
        case "DO_NOT_TRUST" /* DO_NOT_TRUST */:
          untrustedPaths.push(rule.path);
          break;
        default:
          break;
      }
    }
    for (const trustedPath of trustedPaths) {
      if (isWithinRoot(location, trustedPath)) {
        return true;
      }
    }
    for (const untrustedPath of untrustedPaths) {
      if (path59.normalize(location) === path59.normalize(untrustedPath)) {
        return false;
      }
    }
    return void 0;
  }
  setValue(path108, trustLevel) {
    this.user.config[path108] = trustLevel;
    saveTrustedFolders(this.user);
  }
};
var loadedTrustedFolders;
function loadTrustedFolders() {
  if (loadedTrustedFolders) {
    return loadedTrustedFolders;
  }
  const errors = [];
  let userConfig = {};
  const userPath = getTrustedFoldersPath();
  try {
    if (fs52.existsSync(userPath)) {
      const content = fs52.readFileSync(userPath, "utf-8");
      const parsed = JSON.parse((0, import_strip_json_comments.default)(content));
      if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
        errors.push({
          message: "Trusted folders file is not a valid JSON object.",
          path: userPath
        });
      } else {
        userConfig = parsed;
      }
    }
  } catch (error) {
    errors.push({
      message: getErrorMessage(error),
      path: userPath
    });
  }
  loadedTrustedFolders = new LoadedTrustedFolders(
    { path: userPath, config: userConfig },
    errors
  );
  return loadedTrustedFolders;
}
__name(loadTrustedFolders, "loadTrustedFolders");
function saveTrustedFolders(trustedFoldersFile) {
  try {
    const dirPath = path59.dirname(trustedFoldersFile.path);
    if (!fs52.existsSync(dirPath)) {
      fs52.mkdirSync(dirPath, { recursive: true });
    }
    fs52.writeFileSync(
      trustedFoldersFile.path,
      JSON.stringify(trustedFoldersFile.config, null, 2),
      { encoding: "utf-8", mode: 384 }
    );
  } catch (error) {
    console.error("Error saving trusted folders file:", error);
  }
}
__name(saveTrustedFolders, "saveTrustedFolders");
function isFolderTrustEnabled(settings) {
  const folderTrustSetting = settings.security?.folderTrust?.enabled ?? false;
  return folderTrustSetting;
}
__name(isFolderTrustEnabled, "isFolderTrustEnabled");
function getWorkspaceTrustFromLocalConfig(trustConfig) {
  const folders = loadTrustedFolders();
  if (trustConfig) {
    folders.user.config = trustConfig;
  }
  if (folders.errors.length > 0) {
    const errorMessages = folders.errors.map(
      (error) => `Error in ${error.path}: ${error.message}`
    );
    throw new FatalConfigError(
      `${errorMessages.join("\n")}
Please fix the configuration file and try again.`
    );
  }
  const isTrusted = folders.isPathTrusted(process.cwd());
  return {
    isTrusted,
    source: isTrusted !== void 0 ? "file" : void 0
  };
}
__name(getWorkspaceTrustFromLocalConfig, "getWorkspaceTrustFromLocalConfig");
function isWorkspaceTrusted(settings, trustConfig) {
  if (!isFolderTrustEnabled(settings)) {
    return { isTrusted: true, source: void 0 };
  }
  const ideTrust = ideContextStore.get()?.workspaceState?.isTrusted;
  if (ideTrust !== void 0) {
    return { isTrusted: ideTrust, source: "ide" };
  }
  return getWorkspaceTrustFromLocalConfig(trustConfig);
}
__name(isWorkspaceTrusted, "isWorkspaceTrusted");

// packages/cli/src/ui/hooks/useIdeTrustListener.ts
function useIdeTrustListener() {
  const settings = useSettings();
  const [connectionStatus, setConnectionStatus] = (0, import_react29.useState)(
    IDEConnectionStatus.Disconnected
  );
  const previousTrust = (0, import_react29.useRef)(void 0);
  const [restartReason, setRestartReason] = (0, import_react29.useState)("NONE");
  const [needsRestart, setNeedsRestart] = (0, import_react29.useState)(false);
  const subscribe = (0, import_react29.useCallback)((onStoreChange) => {
    const handleStatusChange = /* @__PURE__ */ __name((state) => {
      setConnectionStatus(state.status);
      setRestartReason("CONNECTION_CHANGE");
      onStoreChange();
    }, "handleStatusChange");
    const handleTrustChange = /* @__PURE__ */ __name(() => {
      setRestartReason("TRUST_CHANGE");
      onStoreChange();
    }, "handleTrustChange");
    (async () => {
      const ideClient = await IdeClient.getInstance();
      ideClient.addTrustChangeListener(handleTrustChange);
      ideClient.addStatusChangeListener(handleStatusChange);
      setConnectionStatus(ideClient.getConnectionStatus().status);
    })();
    return () => {
      (async () => {
        const ideClient = await IdeClient.getInstance();
        ideClient.removeTrustChangeListener(handleTrustChange);
        ideClient.removeStatusChangeListener(handleStatusChange);
      })();
    };
  }, []);
  const getSnapshot = /* @__PURE__ */ __name(() => {
    if (connectionStatus !== IDEConnectionStatus.Connected) {
      return void 0;
    }
    return ideContextStore.get()?.workspaceState?.isTrusted;
  }, "getSnapshot");
  const isIdeTrusted = (0, import_react29.useSyncExternalStore)(subscribe, getSnapshot);
  (0, import_react29.useEffect)(() => {
    const currentTrust = isWorkspaceTrusted(settings.merged).isTrusted;
    if (previousTrust.current !== void 0 && previousTrust.current !== currentTrust) {
      setNeedsRestart(true);
    }
    previousTrust.current = currentTrust;
  }, [isIdeTrusted, settings.merged]);
  return { isIdeTrusted, needsRestart, restartReason };
}
__name(useIdeTrustListener, "useIdeTrustListener");

// packages/cli/src/ui/contexts/UIStateContext.tsx
var UIStateContext = (0, import_react30.createContext)(null);
var useUIState = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react30.useContext)(UIStateContext);
  if (!context2) {
    throw new Error("useUIState must be used within a UIStateProvider");
  }
  return context2;
}, "useUIState");

// packages/cli/src/ui/contexts/StreamingContext.tsx
init_esbuild_shims();
var import_react31 = __toESM(require_react(), 1);
var StreamingContext = (0, import_react31.createContext)(
  void 0
);
var useStreamingContext = /* @__PURE__ */ __name(() => {
  const context2 = import_react31.default.useContext(StreamingContext);
  if (context2 === void 0) {
    throw new Error(
      "useStreamingContext must be used within a StreamingContextProvider"
    );
  }
  return context2;
}, "useStreamingContext");

// packages/cli/src/ui/components/QuittingDisplay.tsx
init_esbuild_shims();

// packages/cli/src/ui/components/HistoryItemDisplay.tsx
init_esbuild_shims();
var import_react66 = __toESM(require_react(), 1);

// packages/cli/src/ui/utils/textUtils.ts
init_esbuild_shims();
init_strip_ansi();
init_ansi_regex();
import { stripVTControlCharacters } from "node:util";

// packages/cli/node_modules/string-width/index.js
init_esbuild_shims();
init_strip_ansi();
var import_emoji_regex4 = __toESM(require_emoji_regex4(), 1);
var segmenter4 = new Intl.Segmenter();
var defaultIgnorableCodePointRegex4 = new RegExp("^\\p{Default_Ignorable_Code_Point}$", "u");
function stringWidth4(string, options2 = {}) {
  if (typeof string !== "string" || string.length === 0) {
    return 0;
  }
  const {
    ambiguousIsNarrow = true,
    countAnsiEscapeCodes = false
  } = options2;
  if (!countAnsiEscapeCodes) {
    string = stripAnsi(string);
  }
  if (string.length === 0) {
    return 0;
  }
  let width = 0;
  const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
  for (const { segment: character } of segmenter4.segment(string)) {
    const codePoint = character.codePointAt(0);
    if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159) {
      continue;
    }
    if (codePoint >= 8203 && codePoint <= 8207 || codePoint === 65279) {
      continue;
    }
    if (codePoint >= 768 && codePoint <= 879 || codePoint >= 6832 && codePoint <= 6911 || codePoint >= 7616 && codePoint <= 7679 || codePoint >= 8400 && codePoint <= 8447 || codePoint >= 65056 && codePoint <= 65071) {
      continue;
    }
    if (codePoint >= 55296 && codePoint <= 57343) {
      continue;
    }
    if (codePoint >= 65024 && codePoint <= 65039) {
      continue;
    }
    if (defaultIgnorableCodePointRegex4.test(character)) {
      continue;
    }
    if ((0, import_emoji_regex4.default)().test(character)) {
      width += 2;
      continue;
    }
    width += eastAsianWidth(codePoint, eastAsianWidthOptions);
  }
  return width;
}
__name(stringWidth4, "stringWidth");

// packages/cli/src/ui/utils/textUtils.ts
var getAsciiArtWidth = /* @__PURE__ */ __name((asciiArt) => {
  if (!asciiArt) {
    return 0;
  }
  const lines = asciiArt.split("\n");
  return Math.max(...lines.map((line) => line.length));
}, "getAsciiArtWidth");
var codePointsCache = /* @__PURE__ */ new Map();
var MAX_STRING_LENGTH_TO_CACHE = 1e3;
function toCodePoints(str2) {
  let isAscii2 = true;
  for (let i = 0; i < str2.length; i++) {
    if (str2.charCodeAt(i) > 127) {
      isAscii2 = false;
      break;
    }
  }
  if (isAscii2) {
    return str2.split("");
  }
  if (str2.length <= MAX_STRING_LENGTH_TO_CACHE) {
    const cached = codePointsCache.get(str2);
    if (cached) {
      return cached;
    }
  }
  const result = Array.from(str2);
  if (str2.length <= MAX_STRING_LENGTH_TO_CACHE) {
    codePointsCache.set(str2, result);
  }
  return result;
}
__name(toCodePoints, "toCodePoints");
function cpLen(str2) {
  return toCodePoints(str2).length;
}
__name(cpLen, "cpLen");
function cpSlice(str2, start, end) {
  const arr = toCodePoints(str2).slice(start, end);
  return arr.join("");
}
__name(cpSlice, "cpSlice");
function stripUnsafeCharacters(str2) {
  const strippedAnsi = stripAnsi(str2);
  const strippedVT = stripVTControlCharacters(strippedAnsi);
  return toCodePoints(strippedVT).filter((char) => {
    const code2 = char.codePointAt(0);
    if (code2 === void 0) return false;
    if (code2 === 10 || code2 === 13) return true;
    if (code2 >= 0 && code2 <= 31) return false;
    if (code2 >= 128 && code2 <= 159) return false;
    return true;
  }).join("");
}
__name(stripUnsafeCharacters, "stripUnsafeCharacters");
var stringWidthCache = /* @__PURE__ */ new Map();
var getCachedStringWidth = /* @__PURE__ */ __name((str2) => {
  if (/^[\x20-\x7E]*$/.test(str2)) {
    return str2.length;
  }
  if (stringWidthCache.has(str2)) {
    return stringWidthCache.get(str2);
  }
  const width = stringWidth4(str2);
  stringWidthCache.set(str2, width);
  return width;
}, "getCachedStringWidth");
var regex2 = ansiRegex();
function escapeAnsiCtrlCodes(obj) {
  if (typeof obj === "string") {
    if (obj.search(regex2) === -1) {
      return obj;
    }
    regex2.lastIndex = 0;
    return obj.replace(
      regex2,
      (match2) => JSON.stringify(match2).slice(1, -1)
    );
  }
  if (obj === null || typeof obj !== "object") {
    return obj;
  }
  if (Array.isArray(obj)) {
    let newArr = null;
    for (let i = 0; i < obj.length; i++) {
      const value = obj[i];
      const escapedValue = escapeAnsiCtrlCodes(value);
      if (escapedValue !== value) {
        if (newArr === null) {
          newArr = [...obj];
        }
        newArr[i] = escapedValue;
      }
    }
    return newArr !== null ? newArr : obj;
  }
  let newObj = null;
  const keys = Object.keys(obj);
  for (const key of keys) {
    const value = obj[key];
    const escapedValue = escapeAnsiCtrlCodes(value);
    if (escapedValue !== value) {
      if (newObj === null) {
        newObj = { ...obj };
      }
      newObj[key] = escapedValue;
    }
  }
  return newObj !== null ? newObj : obj;
}
__name(escapeAnsiCtrlCodes, "escapeAnsiCtrlCodes");

// packages/cli/src/ui/components/messages/UserMessage.tsx
init_esbuild_shims();

// packages/cli/src/ui/semantic-colors.ts
init_esbuild_shims();

// packages/cli/src/ui/themes/theme-manager.ts
init_esbuild_shims();

// packages/cli/src/ui/themes/ayu.ts
init_esbuild_shims();

// packages/cli/src/ui/themes/theme.ts
init_esbuild_shims();

// packages/cli/src/ui/themes/color-utils.ts
init_esbuild_shims();
var CSS_NAME_TO_HEX_MAP = {
  aliceblue: "#f0f8ff",
  antiquewhite: "#faebd7",
  aqua: "#00ffff",
  aquamarine: "#7fffd4",
  azure: "#f0ffff",
  beige: "#f5f5dc",
  bisque: "#ffe4c4",
  blanchedalmond: "#ffebcd",
  blueviolet: "#8a2be2",
  brown: "#a52a2a",
  burlywood: "#deb887",
  cadetblue: "#5f9ea0",
  chartreuse: "#7fff00",
  chocolate: "#d2691e",
  coral: "#ff7f50",
  cornflowerblue: "#6495ed",
  cornsilk: "#fff8dc",
  crimson: "#dc143c",
  darkblue: "#00008b",
  darkcyan: "#008b8b",
  darkgoldenrod: "#b8860b",
  darkgray: "#a9a9a9",
  darkgrey: "#a9a9a9",
  darkgreen: "#006400",
  darkkhaki: "#bdb76b",
  darkmagenta: "#8b008b",
  darkolivegreen: "#556b2f",
  darkorange: "#ff8c00",
  darkorchid: "#9932cc",
  darkred: "#8b0000",
  darksalmon: "#e9967a",
  darkseagreen: "#8fbc8f",
  darkslateblue: "#483d8b",
  darkslategray: "#2f4f4f",
  darkslategrey: "#2f4f4f",
  darkturquoise: "#00ced1",
  darkviolet: "#9400d3",
  deeppink: "#ff1493",
  deepskyblue: "#00bfff",
  dimgray: "#696969",
  dimgrey: "#696969",
  dodgerblue: "#1e90ff",
  firebrick: "#b22222",
  floralwhite: "#fffaf0",
  forestgreen: "#228b22",
  fuchsia: "#ff00ff",
  gainsboro: "#dcdcdc",
  ghostwhite: "#f8f8ff",
  gold: "#ffd700",
  goldenrod: "#daa520",
  greenyellow: "#adff2f",
  honeydew: "#f0fff0",
  hotpink: "#ff69b4",
  indianred: "#cd5c5c",
  indigo: "#4b0082",
  ivory: "#fffff0",
  khaki: "#f0e68c",
  lavender: "#e6e6fa",
  lavenderblush: "#fff0f5",
  lawngreen: "#7cfc00",
  lemonchiffon: "#fffacd",
  lightblue: "#add8e6",
  lightcoral: "#f08080",
  lightcyan: "#e0ffff",
  lightgoldenrodyellow: "#fafad2",
  lightgray: "#d3d3d3",
  lightgrey: "#d3d3d3",
  lightgreen: "#90ee90",
  lightpink: "#ffb6c1",
  lightsalmon: "#ffa07a",
  lightseagreen: "#20b2aa",
  lightskyblue: "#87cefa",
  lightslategray: "#778899",
  lightslategrey: "#778899",
  lightsteelblue: "#b0c4de",
  lightyellow: "#ffffe0",
  lime: "#00ff00",
  limegreen: "#32cd32",
  linen: "#faf0e6",
  maroon: "#800000",
  mediumaquamarine: "#66cdaa",
  mediumblue: "#0000cd",
  mediumorchid: "#ba55d3",
  mediumpurple: "#9370db",
  mediumseagreen: "#3cb371",
  mediumslateblue: "#7b68ee",
  mediumspringgreen: "#00fa9a",
  mediumturquoise: "#48d1cc",
  mediumvioletred: "#c71585",
  midnightblue: "#191970",
  mintcream: "#f5fffa",
  mistyrose: "#ffe4e1",
  moccasin: "#ffe4b5",
  navajowhite: "#ffdead",
  navy: "#000080",
  oldlace: "#fdf5e6",
  olive: "#808000",
  olivedrab: "#6b8e23",
  orange: "#ffa500",
  orangered: "#ff4500",
  orchid: "#da70d6",
  palegoldenrod: "#eee8aa",
  palegreen: "#98fb98",
  paleturquoise: "#afeeee",
  palevioletred: "#db7093",
  papayawhip: "#ffefd5",
  peachpuff: "#ffdab9",
  peru: "#cd853f",
  pink: "#ffc0cb",
  plum: "#dda0dd",
  powderblue: "#b0e0e6",
  purple: "#800080",
  rebeccapurple: "#663399",
  rosybrown: "#bc8f8f",
  royalblue: "#4169e1",
  saddlebrown: "#8b4513",
  salmon: "#fa8072",
  sandybrown: "#f4a460",
  seagreen: "#2e8b57",
  seashell: "#fff5ee",
  sienna: "#a0522d",
  silver: "#c0c0c0",
  skyblue: "#87ceeb",
  slateblue: "#6a5acd",
  slategray: "#708090",
  slategrey: "#708090",
  snow: "#fffafa",
  springgreen: "#00ff7f",
  steelblue: "#4682b4",
  tan: "#d2b48c",
  teal: "#008080",
  thistle: "#d8bfd8",
  tomato: "#ff6347",
  turquoise: "#40e0d0",
  violet: "#ee82ee",
  wheat: "#f5deb3",
  whitesmoke: "#f5f5f5",
  yellowgreen: "#9acd32"
};
var INK_SUPPORTED_NAMES = /* @__PURE__ */ new Set([
  "black",
  "red",
  "green",
  "yellow",
  "blue",
  "cyan",
  "magenta",
  "white",
  "gray",
  "grey",
  "blackbright",
  "redbright",
  "greenbright",
  "yellowbright",
  "bluebright",
  "cyanbright",
  "magentabright",
  "whitebright"
]);
function resolveColor(colorValue) {
  const lowerColor = colorValue.toLowerCase();
  if (lowerColor.startsWith("#")) {
    if (/^#[0-9A-Fa-f]{3}([0-9A-Fa-f]{3})?$/.test(colorValue)) {
      return lowerColor;
    } else {
      return void 0;
    }
  } else if (INK_SUPPORTED_NAMES.has(lowerColor)) {
    return lowerColor;
  } else if (CSS_NAME_TO_HEX_MAP[lowerColor]) {
    return CSS_NAME_TO_HEX_MAP[lowerColor];
  }
  console.warn(
    `[ColorUtils] Could not resolve color "${colorValue}" to an Ink-compatible format.`
  );
  return void 0;
}
__name(resolveColor, "resolveColor");

// packages/cli/src/ui/themes/theme.ts
var lightTheme = {
  type: "light",
  Background: "#FAFAFA",
  Foreground: "",
  LightBlue: "#89BDCD",
  AccentBlue: "#3B82F6",
  AccentPurple: "#8B5CF6",
  AccentCyan: "#06B6D4",
  AccentGreen: "#3CA84B",
  AccentYellow: "#D5A40A",
  AccentRed: "#DD4C4C",
  DiffAdded: "#C6EAD8",
  DiffRemoved: "#FFCCCC",
  Comment: "#008000",
  Gray: "#97a0b0",
  GradientColors: ["#4796E4", "#847ACE", "#C3677F"]
};
var darkTheme = {
  type: "dark",
  Background: "#1E1E2E",
  Foreground: "",
  LightBlue: "#ADD8E6",
  AccentBlue: "#89B4FA",
  AccentPurple: "#CBA6F7",
  AccentCyan: "#89DCEB",
  AccentGreen: "#A6E3A1",
  AccentYellow: "#F9E2AF",
  AccentRed: "#F38BA8",
  DiffAdded: "#28350B",
  DiffRemoved: "#430000",
  Comment: "#6C7086",
  Gray: "#6C7086",
  GradientColors: ["#4796E4", "#847ACE", "#C3677F"]
};
var ansiTheme = {
  type: "ansi",
  Background: "black",
  Foreground: "white",
  LightBlue: "blue",
  AccentBlue: "blue",
  AccentPurple: "magenta",
  AccentCyan: "cyan",
  AccentGreen: "green",
  AccentYellow: "yellow",
  AccentRed: "red",
  DiffAdded: "green",
  DiffRemoved: "red",
  Comment: "gray",
  Gray: "gray"
};
var Theme = class _Theme {
  /**
   * Creates a new Theme instance.
   * @param name The name of the theme.
   * @param rawMappings The raw CSSProperties mappings from a react-syntax-highlighter theme object.
   */
  constructor(name3, type, rawMappings, colors, semanticColors) {
    this.name = name3;
    this.type = type;
    this.colors = colors;
    this.semanticColors = semanticColors ?? {
      text: {
        primary: this.colors.Foreground,
        secondary: this.colors.Gray,
        link: this.colors.AccentBlue,
        accent: this.colors.AccentPurple
      },
      background: {
        primary: this.colors.Background,
        diff: {
          added: this.colors.DiffAdded,
          removed: this.colors.DiffRemoved
        }
      },
      border: {
        default: this.colors.Gray,
        focused: this.colors.AccentBlue
      },
      ui: {
        comment: this.colors.Gray,
        symbol: this.colors.AccentCyan,
        gradient: this.colors.GradientColors
      },
      status: {
        error: this.colors.AccentRed,
        success: this.colors.AccentGreen,
        warning: this.colors.AccentYellow
      }
    };
    this._colorMap = Object.freeze(this._buildColorMap(rawMappings));
    const rawDefaultColor = rawMappings["hljs"]?.color;
    this.defaultColor = (rawDefaultColor ? _Theme._resolveColor(rawDefaultColor) : void 0) ?? "";
  }
  static {
    __name(this, "Theme");
  }
  /**
   * The default foreground color for text when no specific highlight rule applies.
   * This is an Ink-compatible color string (hex or name).
   */
  defaultColor;
  /**
   * Stores the mapping from highlight.js class names (e.g., 'hljs-keyword')
   * to Ink-compatible color strings (hex or name).
   */
  _colorMap;
  semanticColors;
  /**
   * Gets the Ink-compatible color string for a given highlight.js class name.
   * @param hljsClass The highlight.js class name (e.g., 'hljs-keyword', 'hljs-string').
   * @returns The corresponding Ink color string (hex or name) if it exists.
   */
  getInkColor(hljsClass) {
    return this._colorMap[hljsClass];
  }
  /**
   * Resolves a CSS color value (name or hex) into an Ink-compatible color string.
   * @param colorValue The raw color string (e.g., 'blue', '#ff0000', 'darkkhaki').
   * @returns An Ink-compatible color string (hex or name), or undefined if not resolvable.
   */
  static _resolveColor(colorValue) {
    return resolveColor(colorValue);
  }
  /**
   * Builds the internal map from highlight.js class names to Ink-compatible color strings.
   * This method is protected and primarily intended for use by the constructor.
   * @param hljsTheme The raw CSSProperties mappings from a react-syntax-highlighter theme object.
   * @returns An Ink-compatible theme map (Record<string, string>).
   */
  _buildColorMap(hljsTheme) {
    const inkTheme = {};
    for (const key in hljsTheme) {
      if (!key.startsWith("hljs-") && key !== "hljs") {
        continue;
      }
      const style = hljsTheme[key];
      if (style?.color) {
        const resolvedColor = _Theme._resolveColor(style.color);
        if (resolvedColor !== void 0) {
          inkTheme[key] = resolvedColor;
        }
      }
    }
    return inkTheme;
  }
};
function createCustomTheme(customTheme) {
  const colors = {
    type: "custom",
    Background: customTheme.background?.primary ?? customTheme.Background ?? "",
    Foreground: customTheme.text?.primary ?? customTheme.Foreground ?? "",
    LightBlue: customTheme.text?.link ?? customTheme.LightBlue ?? "",
    AccentBlue: customTheme.text?.link ?? customTheme.AccentBlue ?? "",
    AccentPurple: customTheme.text?.accent ?? customTheme.AccentPurple ?? "",
    AccentCyan: customTheme.text?.link ?? customTheme.AccentCyan ?? "",
    AccentGreen: customTheme.status?.success ?? customTheme.AccentGreen ?? "",
    AccentYellow: customTheme.status?.warning ?? customTheme.AccentYellow ?? "",
    AccentRed: customTheme.status?.error ?? customTheme.AccentRed ?? "",
    DiffAdded: customTheme.background?.diff?.added ?? customTheme.DiffAdded ?? "",
    DiffRemoved: customTheme.background?.diff?.removed ?? customTheme.DiffRemoved ?? "",
    Comment: customTheme.ui?.comment ?? customTheme.Comment ?? "",
    Gray: customTheme.text?.secondary ?? customTheme.Gray ?? "",
    GradientColors: customTheme.ui?.gradient ?? customTheme.GradientColors
  };
  const rawMappings = {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em",
      background: colors.Background,
      color: colors.Foreground
    },
    "hljs-keyword": {
      color: colors.AccentBlue
    },
    "hljs-literal": {
      color: colors.AccentBlue
    },
    "hljs-symbol": {
      color: colors.AccentBlue
    },
    "hljs-name": {
      color: colors.AccentBlue
    },
    "hljs-link": {
      color: colors.AccentBlue,
      textDecoration: "underline"
    },
    "hljs-built_in": {
      color: colors.AccentCyan
    },
    "hljs-type": {
      color: colors.AccentCyan
    },
    "hljs-number": {
      color: colors.AccentGreen
    },
    "hljs-class": {
      color: colors.AccentGreen
    },
    "hljs-string": {
      color: colors.AccentYellow
    },
    "hljs-meta-string": {
      color: colors.AccentYellow
    },
    "hljs-regexp": {
      color: colors.AccentRed
    },
    "hljs-template-tag": {
      color: colors.AccentRed
    },
    "hljs-subst": {
      color: colors.Foreground
    },
    "hljs-function": {
      color: colors.Foreground
    },
    "hljs-title": {
      color: colors.Foreground
    },
    "hljs-params": {
      color: colors.Foreground
    },
    "hljs-formula": {
      color: colors.Foreground
    },
    "hljs-comment": {
      color: colors.Comment,
      fontStyle: "italic"
    },
    "hljs-quote": {
      color: colors.Comment,
      fontStyle: "italic"
    },
    "hljs-doctag": {
      color: colors.Comment
    },
    "hljs-meta": {
      color: colors.Gray
    },
    "hljs-meta-keyword": {
      color: colors.Gray
    },
    "hljs-tag": {
      color: colors.Gray
    },
    "hljs-variable": {
      color: colors.AccentPurple
    },
    "hljs-template-variable": {
      color: colors.AccentPurple
    },
    "hljs-attr": {
      color: colors.LightBlue
    },
    "hljs-attribute": {
      color: colors.LightBlue
    },
    "hljs-builtin-name": {
      color: colors.LightBlue
    },
    "hljs-section": {
      color: colors.AccentYellow
    },
    "hljs-emphasis": {
      fontStyle: "italic"
    },
    "hljs-strong": {
      fontWeight: "bold"
    },
    "hljs-bullet": {
      color: colors.AccentYellow
    },
    "hljs-selector-tag": {
      color: colors.AccentYellow
    },
    "hljs-selector-id": {
      color: colors.AccentYellow
    },
    "hljs-selector-class": {
      color: colors.AccentYellow
    },
    "hljs-selector-attr": {
      color: colors.AccentYellow
    },
    "hljs-selector-pseudo": {
      color: colors.AccentYellow
    },
    "hljs-addition": {
      backgroundColor: colors.AccentGreen,
      display: "inline-block",
      width: "100%"
    },
    "hljs-deletion": {
      backgroundColor: colors.AccentRed,
      display: "inline-block",
      width: "100%"
    }
  };
  const semanticColors = {
    text: {
      primary: customTheme.text?.primary ?? colors.Foreground,
      secondary: customTheme.text?.secondary ?? colors.Gray,
      link: customTheme.text?.link ?? colors.AccentBlue,
      accent: customTheme.text?.accent ?? colors.AccentPurple
    },
    background: {
      primary: customTheme.background?.primary ?? colors.Background,
      diff: {
        added: customTheme.background?.diff?.added ?? colors.DiffAdded,
        removed: customTheme.background?.diff?.removed ?? colors.DiffRemoved
      }
    },
    border: {
      default: customTheme.border?.default ?? colors.Gray,
      focused: customTheme.border?.focused ?? colors.AccentBlue
    },
    ui: {
      comment: customTheme.ui?.comment ?? colors.Comment,
      symbol: customTheme.ui?.symbol ?? colors.Gray,
      gradient: customTheme.ui?.gradient ?? colors.GradientColors
    },
    status: {
      error: customTheme.status?.error ?? colors.AccentRed,
      success: customTheme.status?.success ?? colors.AccentGreen,
      warning: customTheme.status?.warning ?? colors.AccentYellow
    }
  };
  return new Theme(
    customTheme.name,
    "custom",
    rawMappings,
    colors,
    semanticColors
  );
}
__name(createCustomTheme, "createCustomTheme");
function validateCustomTheme(customTheme) {
  if (customTheme.name && !isValidThemeName(customTheme.name)) {
    return {
      isValid: false,
      error: `Invalid theme name: ${customTheme.name}`
    };
  }
  return {
    isValid: true
  };
}
__name(validateCustomTheme, "validateCustomTheme");
function isValidThemeName(name3) {
  return name3.trim().length > 0 && name3.trim().length <= 50;
}
__name(isValidThemeName, "isValidThemeName");

// packages/cli/src/ui/themes/ayu.ts
var ayuDarkColors = {
  type: "dark",
  Background: "#0b0e14",
  Foreground: "#aeaca6",
  LightBlue: "#59C2FF",
  AccentBlue: "#39BAE6",
  AccentPurple: "#D2A6FF",
  AccentCyan: "#95E6CB",
  AccentGreen: "#AAD94C",
  AccentYellow: "#FFB454",
  AccentRed: "#F26D78",
  DiffAdded: "#293022",
  DiffRemoved: "#3D1215",
  Comment: "#646A71",
  Gray: "#3D4149",
  GradientColors: ["#FFB454", "#F26D78"]
};
var AyuDark = new Theme(
  "Ayu",
  "dark",
  {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em",
      background: ayuDarkColors.Background,
      color: ayuDarkColors.Foreground
    },
    "hljs-keyword": {
      color: ayuDarkColors.AccentYellow
    },
    "hljs-literal": {
      color: ayuDarkColors.AccentPurple
    },
    "hljs-symbol": {
      color: ayuDarkColors.AccentCyan
    },
    "hljs-name": {
      color: ayuDarkColors.LightBlue
    },
    "hljs-link": {
      color: ayuDarkColors.AccentBlue
    },
    "hljs-function .hljs-keyword": {
      color: ayuDarkColors.AccentYellow
    },
    "hljs-subst": {
      color: ayuDarkColors.Foreground
    },
    "hljs-string": {
      color: ayuDarkColors.AccentGreen
    },
    "hljs-title": {
      color: ayuDarkColors.AccentYellow
    },
    "hljs-type": {
      color: ayuDarkColors.AccentBlue
    },
    "hljs-attribute": {
      color: ayuDarkColors.AccentYellow
    },
    "hljs-bullet": {
      color: ayuDarkColors.AccentYellow
    },
    "hljs-addition": {
      color: ayuDarkColors.AccentGreen
    },
    "hljs-variable": {
      color: ayuDarkColors.Foreground
    },
    "hljs-template-tag": {
      color: ayuDarkColors.AccentYellow
    },
    "hljs-template-variable": {
      color: ayuDarkColors.AccentYellow
    },
    "hljs-comment": {
      color: ayuDarkColors.Comment,
      fontStyle: "italic"
    },
    "hljs-quote": {
      color: ayuDarkColors.AccentCyan,
      fontStyle: "italic"
    },
    "hljs-deletion": {
      color: ayuDarkColors.AccentRed
    },
    "hljs-meta": {
      color: ayuDarkColors.AccentYellow
    },
    "hljs-doctag": {
      fontWeight: "bold"
    },
    "hljs-strong": {
      fontWeight: "bold"
    },
    "hljs-emphasis": {
      fontStyle: "italic"
    }
  },
  ayuDarkColors
);

// packages/cli/src/ui/themes/ayu-light.ts
init_esbuild_shims();
var ayuLightColors = {
  type: "light",
  Background: "#f8f9fa",
  Foreground: "#5c6166",
  LightBlue: "#55b4d4",
  AccentBlue: "#399ee6",
  AccentPurple: "#a37acc",
  AccentCyan: "#4cbf99",
  AccentGreen: "#86b300",
  AccentYellow: "#f2ae49",
  AccentRed: "#f07171",
  DiffAdded: "#C6EAD8",
  DiffRemoved: "#FFCCCC",
  Comment: "#ABADB1",
  Gray: "#a6aaaf",
  GradientColors: ["#399ee6", "#86b300"]
};
var AyuLight = new Theme(
  "Ayu Light",
  "light",
  {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em",
      background: ayuLightColors.Background,
      color: ayuLightColors.Foreground
    },
    "hljs-comment": {
      color: ayuLightColors.Comment,
      fontStyle: "italic"
    },
    "hljs-quote": {
      color: ayuLightColors.AccentCyan,
      fontStyle: "italic"
    },
    "hljs-string": {
      color: ayuLightColors.AccentGreen
    },
    "hljs-constant": {
      color: ayuLightColors.AccentCyan
    },
    "hljs-number": {
      color: ayuLightColors.AccentPurple
    },
    "hljs-keyword": {
      color: ayuLightColors.AccentYellow
    },
    "hljs-selector-tag": {
      color: ayuLightColors.AccentYellow
    },
    "hljs-attribute": {
      color: ayuLightColors.AccentYellow
    },
    "hljs-variable": {
      color: ayuLightColors.Foreground
    },
    "hljs-variable.language": {
      color: ayuLightColors.LightBlue,
      fontStyle: "italic"
    },
    "hljs-title": {
      color: ayuLightColors.AccentBlue
    },
    "hljs-section": {
      color: ayuLightColors.AccentGreen,
      fontWeight: "bold"
    },
    "hljs-type": {
      color: ayuLightColors.LightBlue
    },
    "hljs-class .hljs-title": {
      color: ayuLightColors.AccentBlue
    },
    "hljs-tag": {
      color: ayuLightColors.LightBlue
    },
    "hljs-name": {
      color: ayuLightColors.AccentBlue
    },
    "hljs-builtin-name": {
      color: ayuLightColors.AccentYellow
    },
    "hljs-meta": {
      color: ayuLightColors.AccentYellow
    },
    "hljs-symbol": {
      color: ayuLightColors.AccentRed
    },
    "hljs-bullet": {
      color: ayuLightColors.AccentYellow
    },
    "hljs-regexp": {
      color: ayuLightColors.AccentCyan
    },
    "hljs-link": {
      color: ayuLightColors.LightBlue
    },
    "hljs-deletion": {
      color: ayuLightColors.AccentRed
    },
    "hljs-addition": {
      color: ayuLightColors.AccentGreen
    },
    "hljs-emphasis": {
      fontStyle: "italic"
    },
    "hljs-strong": {
      fontWeight: "bold"
    },
    "hljs-literal": {
      color: ayuLightColors.AccentCyan
    },
    "hljs-built_in": {
      color: ayuLightColors.AccentRed
    },
    "hljs-doctag": {
      color: ayuLightColors.AccentRed
    },
    "hljs-template-variable": {
      color: ayuLightColors.AccentCyan
    },
    "hljs-selector-id": {
      color: ayuLightColors.AccentRed
    }
  },
  ayuLightColors
);

// packages/cli/src/ui/themes/atom-one-dark.ts
init_esbuild_shims();
var atomOneDarkColors = {
  type: "dark",
  Background: "#282c34",
  Foreground: "#abb2bf",
  LightBlue: "#61aeee",
  AccentBlue: "#61aeee",
  AccentPurple: "#c678dd",
  AccentCyan: "#56b6c2",
  AccentGreen: "#98c379",
  AccentYellow: "#e6c07b",
  AccentRed: "#e06c75",
  DiffAdded: "#39544E",
  DiffRemoved: "#562B2F",
  Comment: "#5c6370",
  Gray: "#5c6370",
  GradientColors: ["#61aeee", "#98c379"]
};
var AtomOneDark = new Theme(
  "Atom One",
  "dark",
  {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em",
      color: atomOneDarkColors.Foreground,
      background: atomOneDarkColors.Background
    },
    "hljs-comment": {
      color: atomOneDarkColors.Comment,
      fontStyle: "italic"
    },
    "hljs-quote": {
      color: atomOneDarkColors.Comment,
      fontStyle: "italic"
    },
    "hljs-doctag": {
      color: atomOneDarkColors.AccentPurple
    },
    "hljs-keyword": {
      color: atomOneDarkColors.AccentPurple
    },
    "hljs-formula": {
      color: atomOneDarkColors.AccentPurple
    },
    "hljs-section": {
      color: atomOneDarkColors.AccentRed
    },
    "hljs-name": {
      color: atomOneDarkColors.AccentRed
    },
    "hljs-selector-tag": {
      color: atomOneDarkColors.AccentRed
    },
    "hljs-deletion": {
      color: atomOneDarkColors.AccentRed
    },
    "hljs-subst": {
      color: atomOneDarkColors.AccentRed
    },
    "hljs-literal": {
      color: atomOneDarkColors.AccentCyan
    },
    "hljs-string": {
      color: atomOneDarkColors.AccentGreen
    },
    "hljs-regexp": {
      color: atomOneDarkColors.AccentGreen
    },
    "hljs-addition": {
      color: atomOneDarkColors.AccentGreen
    },
    "hljs-attribute": {
      color: atomOneDarkColors.AccentGreen
    },
    "hljs-meta-string": {
      color: atomOneDarkColors.AccentGreen
    },
    "hljs-built_in": {
      color: atomOneDarkColors.AccentYellow
    },
    "hljs-class .hljs-title": {
      color: atomOneDarkColors.AccentYellow
    },
    "hljs-attr": {
      color: atomOneDarkColors.AccentYellow
    },
    "hljs-variable": {
      color: atomOneDarkColors.AccentYellow
    },
    "hljs-template-variable": {
      color: atomOneDarkColors.AccentYellow
    },
    "hljs-type": {
      color: atomOneDarkColors.AccentYellow
    },
    "hljs-selector-class": {
      color: atomOneDarkColors.AccentYellow
    },
    "hljs-selector-attr": {
      color: atomOneDarkColors.AccentYellow
    },
    "hljs-selector-pseudo": {
      color: atomOneDarkColors.AccentYellow
    },
    "hljs-number": {
      color: atomOneDarkColors.AccentYellow
    },
    "hljs-symbol": {
      color: atomOneDarkColors.AccentBlue
    },
    "hljs-bullet": {
      color: atomOneDarkColors.AccentBlue
    },
    "hljs-link": {
      color: atomOneDarkColors.AccentBlue,
      textDecoration: "underline"
    },
    "hljs-meta": {
      color: atomOneDarkColors.AccentBlue
    },
    "hljs-selector-id": {
      color: atomOneDarkColors.AccentBlue
    },
    "hljs-title": {
      color: atomOneDarkColors.AccentBlue
    },
    "hljs-emphasis": {
      fontStyle: "italic"
    },
    "hljs-strong": {
      fontWeight: "bold"
    }
  },
  atomOneDarkColors
);

// packages/cli/src/ui/themes/dracula.ts
init_esbuild_shims();
var draculaColors = {
  type: "dark",
  Background: "#282a36",
  Foreground: "#a3afb7",
  LightBlue: "#8be9fd",
  AccentBlue: "#8be9fd",
  AccentPurple: "#ff79c6",
  AccentCyan: "#8be9fd",
  AccentGreen: "#50fa7b",
  AccentYellow: "#fff783",
  AccentRed: "#ff5555",
  DiffAdded: "#11431d",
  DiffRemoved: "#6e1818",
  Comment: "#6272a4",
  Gray: "#6272a4",
  GradientColors: ["#ff79c6", "#8be9fd"]
};
var Dracula = new Theme(
  "Dracula",
  "dark",
  {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em",
      background: draculaColors.Background,
      color: draculaColors.Foreground
    },
    "hljs-keyword": {
      color: draculaColors.AccentBlue,
      fontWeight: "bold"
    },
    "hljs-selector-tag": {
      color: draculaColors.AccentBlue,
      fontWeight: "bold"
    },
    "hljs-literal": {
      color: draculaColors.AccentBlue,
      fontWeight: "bold"
    },
    "hljs-section": {
      color: draculaColors.AccentBlue,
      fontWeight: "bold"
    },
    "hljs-link": {
      color: draculaColors.AccentBlue
    },
    "hljs-function .hljs-keyword": {
      color: draculaColors.AccentPurple
    },
    "hljs-subst": {
      color: draculaColors.Foreground
    },
    "hljs-string": {
      color: draculaColors.AccentYellow
    },
    "hljs-title": {
      color: draculaColors.AccentYellow,
      fontWeight: "bold"
    },
    "hljs-name": {
      color: draculaColors.AccentYellow,
      fontWeight: "bold"
    },
    "hljs-type": {
      color: draculaColors.AccentYellow,
      fontWeight: "bold"
    },
    "hljs-attribute": {
      color: draculaColors.AccentYellow
    },
    "hljs-symbol": {
      color: draculaColors.AccentYellow
    },
    "hljs-bullet": {
      color: draculaColors.AccentYellow
    },
    "hljs-addition": {
      color: draculaColors.AccentGreen
    },
    "hljs-variable": {
      color: draculaColors.AccentYellow
    },
    "hljs-template-tag": {
      color: draculaColors.AccentYellow
    },
    "hljs-template-variable": {
      color: draculaColors.AccentYellow
    },
    "hljs-comment": {
      color: draculaColors.Comment
    },
    "hljs-quote": {
      color: draculaColors.Comment
    },
    "hljs-deletion": {
      color: draculaColors.AccentRed
    },
    "hljs-meta": {
      color: draculaColors.Comment
    },
    "hljs-doctag": {
      fontWeight: "bold"
    },
    "hljs-strong": {
      fontWeight: "bold"
    },
    "hljs-emphasis": {
      fontStyle: "italic"
    }
  },
  draculaColors
);

// packages/cli/src/ui/themes/github-dark.ts
init_esbuild_shims();
var githubDarkColors = {
  type: "dark",
  Background: "#24292e",
  Foreground: "#c0c4c8",
  LightBlue: "#79B8FF",
  AccentBlue: "#79B8FF",
  AccentPurple: "#B392F0",
  AccentCyan: "#9ECBFF",
  AccentGreen: "#85E89D",
  AccentYellow: "#FFAB70",
  AccentRed: "#F97583",
  DiffAdded: "#3C4636",
  DiffRemoved: "#502125",
  Comment: "#6A737D",
  Gray: "#6A737D",
  GradientColors: ["#79B8FF", "#85E89D"]
};
var GitHubDark = new Theme(
  "GitHub",
  "dark",
  {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em",
      color: githubDarkColors.Foreground,
      background: githubDarkColors.Background
    },
    "hljs-comment": {
      color: githubDarkColors.Comment,
      fontStyle: "italic"
    },
    "hljs-quote": {
      color: githubDarkColors.Comment,
      fontStyle: "italic"
    },
    "hljs-keyword": {
      color: githubDarkColors.AccentRed,
      fontWeight: "bold"
    },
    "hljs-selector-tag": {
      color: githubDarkColors.AccentRed,
      fontWeight: "bold"
    },
    "hljs-subst": {
      color: githubDarkColors.Foreground
    },
    "hljs-number": {
      color: githubDarkColors.LightBlue
    },
    "hljs-literal": {
      color: githubDarkColors.LightBlue
    },
    "hljs-variable": {
      color: githubDarkColors.AccentYellow
    },
    "hljs-template-variable": {
      color: githubDarkColors.AccentYellow
    },
    "hljs-tag .hljs-attr": {
      color: githubDarkColors.AccentYellow
    },
    "hljs-string": {
      color: githubDarkColors.AccentCyan
    },
    "hljs-doctag": {
      color: githubDarkColors.AccentCyan
    },
    "hljs-title": {
      color: githubDarkColors.AccentPurple,
      fontWeight: "bold"
    },
    "hljs-section": {
      color: githubDarkColors.AccentPurple,
      fontWeight: "bold"
    },
    "hljs-selector-id": {
      color: githubDarkColors.AccentPurple,
      fontWeight: "bold"
    },
    "hljs-type": {
      color: githubDarkColors.AccentGreen,
      fontWeight: "bold"
    },
    "hljs-class .hljs-title": {
      color: githubDarkColors.AccentGreen,
      fontWeight: "bold"
    },
    "hljs-tag": {
      color: githubDarkColors.AccentGreen
    },
    "hljs-name": {
      color: githubDarkColors.AccentGreen
    },
    "hljs-attribute": {
      color: githubDarkColors.LightBlue
    },
    "hljs-regexp": {
      color: githubDarkColors.AccentCyan
    },
    "hljs-link": {
      color: githubDarkColors.AccentCyan
    },
    "hljs-symbol": {
      color: githubDarkColors.AccentPurple
    },
    "hljs-bullet": {
      color: githubDarkColors.AccentPurple
    },
    "hljs-built_in": {
      color: githubDarkColors.LightBlue
    },
    "hljs-builtin-name": {
      color: githubDarkColors.LightBlue
    },
    "hljs-meta": {
      color: githubDarkColors.LightBlue,
      fontWeight: "bold"
    },
    "hljs-deletion": {
      background: "#86181D",
      color: githubDarkColors.AccentRed
    },
    "hljs-addition": {
      background: "#144620",
      color: githubDarkColors.AccentGreen
    },
    "hljs-emphasis": {
      fontStyle: "italic"
    },
    "hljs-strong": {
      fontWeight: "bold"
    }
  },
  githubDarkColors
);

// packages/cli/src/ui/themes/github-light.ts
init_esbuild_shims();
var githubLightColors = {
  type: "light",
  Background: "#f8f8f8",
  Foreground: "#24292E",
  LightBlue: "#0086b3",
  AccentBlue: "#458",
  AccentPurple: "#900",
  AccentCyan: "#009926",
  AccentGreen: "#008080",
  AccentYellow: "#990073",
  AccentRed: "#d14",
  DiffAdded: "#C6EAD8",
  DiffRemoved: "#FFCCCC",
  Comment: "#998",
  Gray: "#999",
  GradientColors: ["#458", "#008080"]
};
var GitHubLight = new Theme(
  "GitHub Light",
  "light",
  {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em",
      color: githubLightColors.Foreground,
      background: githubLightColors.Background
    },
    "hljs-comment": {
      color: githubLightColors.Comment,
      fontStyle: "italic"
    },
    "hljs-quote": {
      color: githubLightColors.Comment,
      fontStyle: "italic"
    },
    "hljs-keyword": {
      color: githubLightColors.Foreground,
      fontWeight: "bold"
    },
    "hljs-selector-tag": {
      color: githubLightColors.Foreground,
      fontWeight: "bold"
    },
    "hljs-subst": {
      color: githubLightColors.Foreground,
      fontWeight: "normal"
    },
    "hljs-number": {
      color: githubLightColors.AccentGreen
    },
    "hljs-literal": {
      color: githubLightColors.AccentGreen
    },
    "hljs-variable": {
      color: githubLightColors.AccentGreen
    },
    "hljs-template-variable": {
      color: githubLightColors.AccentGreen
    },
    "hljs-tag .hljs-attr": {
      color: githubLightColors.AccentGreen
    },
    "hljs-string": {
      color: githubLightColors.AccentRed
    },
    "hljs-doctag": {
      color: githubLightColors.AccentRed
    },
    "hljs-title": {
      color: githubLightColors.AccentPurple,
      fontWeight: "bold"
    },
    "hljs-section": {
      color: githubLightColors.AccentPurple,
      fontWeight: "bold"
    },
    "hljs-selector-id": {
      color: githubLightColors.AccentPurple,
      fontWeight: "bold"
    },
    "hljs-type": {
      color: githubLightColors.AccentBlue,
      fontWeight: "bold"
    },
    "hljs-class .hljs-title": {
      color: githubLightColors.AccentBlue,
      fontWeight: "bold"
    },
    "hljs-tag": {
      color: githubLightColors.AccentBlue,
      fontWeight: "normal"
    },
    "hljs-name": {
      color: githubLightColors.AccentBlue,
      fontWeight: "normal"
    },
    "hljs-attribute": {
      color: githubLightColors.AccentBlue,
      fontWeight: "normal"
    },
    "hljs-regexp": {
      color: githubLightColors.AccentCyan
    },
    "hljs-link": {
      color: githubLightColors.AccentCyan
    },
    "hljs-symbol": {
      color: githubLightColors.AccentYellow
    },
    "hljs-bullet": {
      color: githubLightColors.AccentYellow
    },
    "hljs-built_in": {
      color: githubLightColors.LightBlue
    },
    "hljs-builtin-name": {
      color: githubLightColors.LightBlue
    },
    "hljs-meta": {
      color: githubLightColors.Gray,
      fontWeight: "bold"
    },
    "hljs-deletion": {
      background: "#fdd"
    },
    "hljs-addition": {
      background: "#dfd"
    },
    "hljs-emphasis": {
      fontStyle: "italic"
    },
    "hljs-strong": {
      fontWeight: "bold"
    }
  },
  githubLightColors
);

// packages/cli/src/ui/themes/googlecode.ts
init_esbuild_shims();
var googleCodeColors = {
  type: "light",
  Background: "white",
  Foreground: "#444",
  LightBlue: "#066",
  AccentBlue: "#008",
  AccentPurple: "#606",
  AccentCyan: "#066",
  AccentGreen: "#080",
  AccentYellow: "#660",
  AccentRed: "#800",
  DiffAdded: "#C6EAD8",
  DiffRemoved: "#FEDEDE",
  Comment: "#5f6368",
  Gray: lightTheme.Gray,
  GradientColors: ["#066", "#606"]
};
var GoogleCode = new Theme(
  "Google Code",
  "light",
  {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em",
      background: googleCodeColors.Background,
      color: googleCodeColors.Foreground
    },
    "hljs-comment": {
      color: googleCodeColors.AccentRed
    },
    "hljs-quote": {
      color: googleCodeColors.AccentRed
    },
    "hljs-keyword": {
      color: googleCodeColors.AccentBlue
    },
    "hljs-selector-tag": {
      color: googleCodeColors.AccentBlue
    },
    "hljs-section": {
      color: googleCodeColors.AccentBlue
    },
    "hljs-title": {
      color: googleCodeColors.AccentPurple
    },
    "hljs-name": {
      color: googleCodeColors.AccentBlue
    },
    "hljs-variable": {
      color: googleCodeColors.AccentYellow
    },
    "hljs-template-variable": {
      color: googleCodeColors.AccentYellow
    },
    "hljs-string": {
      color: googleCodeColors.AccentGreen
    },
    "hljs-selector-attr": {
      color: googleCodeColors.AccentGreen
    },
    "hljs-selector-pseudo": {
      color: googleCodeColors.AccentGreen
    },
    "hljs-regexp": {
      color: googleCodeColors.AccentGreen
    },
    "hljs-literal": {
      color: googleCodeColors.AccentCyan
    },
    "hljs-symbol": {
      color: googleCodeColors.AccentCyan
    },
    "hljs-bullet": {
      color: googleCodeColors.AccentCyan
    },
    "hljs-meta": {
      color: googleCodeColors.AccentCyan
    },
    "hljs-number": {
      color: googleCodeColors.AccentCyan
    },
    "hljs-link": {
      color: googleCodeColors.AccentCyan
    },
    "hljs-doctag": {
      color: googleCodeColors.AccentPurple,
      fontWeight: "bold"
    },
    "hljs-type": {
      color: googleCodeColors.AccentPurple
    },
    "hljs-attr": {
      color: googleCodeColors.AccentPurple
    },
    "hljs-built_in": {
      color: googleCodeColors.AccentPurple
    },
    "hljs-builtin-name": {
      color: googleCodeColors.AccentPurple
    },
    "hljs-params": {
      color: googleCodeColors.AccentPurple
    },
    "hljs-attribute": {
      color: googleCodeColors.Foreground
    },
    "hljs-subst": {
      color: googleCodeColors.Foreground
    },
    "hljs-formula": {
      backgroundColor: "#eee",
      fontStyle: "italic"
    },
    "hljs-selector-id": {
      color: googleCodeColors.AccentYellow
    },
    "hljs-selector-class": {
      color: googleCodeColors.AccentYellow
    },
    "hljs-addition": {
      backgroundColor: "#baeeba"
    },
    "hljs-deletion": {
      backgroundColor: "#ffc8bd"
    },
    "hljs-strong": {
      fontWeight: "bold"
    },
    "hljs-emphasis": {
      fontStyle: "italic"
    }
  },
  googleCodeColors
);

// packages/cli/src/ui/themes/default-light.ts
init_esbuild_shims();
var DefaultLight = new Theme(
  "Default Light",
  "light",
  {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em",
      background: lightTheme.Background,
      color: lightTheme.Foreground
    },
    "hljs-comment": {
      color: lightTheme.Comment
    },
    "hljs-quote": {
      color: lightTheme.Comment
    },
    "hljs-variable": {
      color: lightTheme.Foreground
    },
    "hljs-keyword": {
      color: lightTheme.AccentBlue
    },
    "hljs-selector-tag": {
      color: lightTheme.AccentBlue
    },
    "hljs-built_in": {
      color: lightTheme.AccentBlue
    },
    "hljs-name": {
      color: lightTheme.AccentBlue
    },
    "hljs-tag": {
      color: lightTheme.AccentBlue
    },
    "hljs-string": {
      color: lightTheme.AccentRed
    },
    "hljs-title": {
      color: lightTheme.AccentRed
    },
    "hljs-section": {
      color: lightTheme.AccentRed
    },
    "hljs-attribute": {
      color: lightTheme.AccentRed
    },
    "hljs-literal": {
      color: lightTheme.AccentRed
    },
    "hljs-template-tag": {
      color: lightTheme.AccentRed
    },
    "hljs-template-variable": {
      color: lightTheme.AccentRed
    },
    "hljs-type": {
      color: lightTheme.AccentRed
    },
    "hljs-addition": {
      color: lightTheme.AccentGreen
    },
    "hljs-deletion": {
      color: lightTheme.AccentRed
    },
    "hljs-selector-attr": {
      color: lightTheme.AccentCyan
    },
    "hljs-selector-pseudo": {
      color: lightTheme.AccentCyan
    },
    "hljs-meta": {
      color: lightTheme.AccentCyan
    },
    "hljs-doctag": {
      color: lightTheme.Gray
    },
    "hljs-attr": {
      color: lightTheme.AccentRed
    },
    "hljs-symbol": {
      color: lightTheme.AccentCyan
    },
    "hljs-bullet": {
      color: lightTheme.AccentCyan
    },
    "hljs-link": {
      color: lightTheme.AccentCyan
    },
    "hljs-emphasis": {
      fontStyle: "italic"
    },
    "hljs-strong": {
      fontWeight: "bold"
    }
  },
  lightTheme
);

// packages/cli/src/ui/themes/default.ts
init_esbuild_shims();
var DefaultDark = new Theme(
  "Default",
  "dark",
  {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em",
      background: darkTheme.Background,
      color: darkTheme.Foreground
    },
    "hljs-keyword": {
      color: darkTheme.AccentBlue
    },
    "hljs-literal": {
      color: darkTheme.AccentBlue
    },
    "hljs-symbol": {
      color: darkTheme.AccentBlue
    },
    "hljs-name": {
      color: darkTheme.AccentBlue
    },
    "hljs-link": {
      color: darkTheme.AccentBlue,
      textDecoration: "underline"
    },
    "hljs-built_in": {
      color: darkTheme.AccentCyan
    },
    "hljs-type": {
      color: darkTheme.AccentCyan
    },
    "hljs-number": {
      color: darkTheme.AccentGreen
    },
    "hljs-class": {
      color: darkTheme.AccentGreen
    },
    "hljs-string": {
      color: darkTheme.AccentYellow
    },
    "hljs-meta-string": {
      color: darkTheme.AccentYellow
    },
    "hljs-regexp": {
      color: darkTheme.AccentRed
    },
    "hljs-template-tag": {
      color: darkTheme.AccentRed
    },
    "hljs-subst": {
      color: darkTheme.Foreground
    },
    "hljs-function": {
      color: darkTheme.Foreground
    },
    "hljs-title": {
      color: darkTheme.Foreground
    },
    "hljs-params": {
      color: darkTheme.Foreground
    },
    "hljs-formula": {
      color: darkTheme.Foreground
    },
    "hljs-comment": {
      color: darkTheme.Comment,
      fontStyle: "italic"
    },
    "hljs-quote": {
      color: darkTheme.Comment,
      fontStyle: "italic"
    },
    "hljs-doctag": {
      color: darkTheme.Comment
    },
    "hljs-meta": {
      color: darkTheme.Gray
    },
    "hljs-meta-keyword": {
      color: darkTheme.Gray
    },
    "hljs-tag": {
      color: darkTheme.Gray
    },
    "hljs-variable": {
      color: darkTheme.AccentPurple
    },
    "hljs-template-variable": {
      color: darkTheme.AccentPurple
    },
    "hljs-attr": {
      color: darkTheme.LightBlue
    },
    "hljs-attribute": {
      color: darkTheme.LightBlue
    },
    "hljs-builtin-name": {
      color: darkTheme.LightBlue
    },
    "hljs-section": {
      color: darkTheme.AccentYellow
    },
    "hljs-emphasis": {
      fontStyle: "italic"
    },
    "hljs-strong": {
      fontWeight: "bold"
    },
    "hljs-bullet": {
      color: darkTheme.AccentYellow
    },
    "hljs-selector-tag": {
      color: darkTheme.AccentYellow
    },
    "hljs-selector-id": {
      color: darkTheme.AccentYellow
    },
    "hljs-selector-class": {
      color: darkTheme.AccentYellow
    },
    "hljs-selector-attr": {
      color: darkTheme.AccentYellow
    },
    "hljs-selector-pseudo": {
      color: darkTheme.AccentYellow
    },
    "hljs-addition": {
      backgroundColor: "#144212",
      display: "inline-block",
      width: "100%"
    },
    "hljs-deletion": {
      backgroundColor: "#600",
      display: "inline-block",
      width: "100%"
    }
  },
  darkTheme
);

// packages/cli/src/ui/themes/shades-of-purple.ts
init_esbuild_shims();
var shadesOfPurpleColors = {
  type: "dark",
  // Required colors for ColorsTheme interface
  Background: "#2d2b57",
  // Main background
  Foreground: "#e3dfff",
  // Default text color (hljs, hljs-subst)
  LightBlue: "#847ace",
  // Light blue/purple accent
  AccentBlue: "#a599e9",
  // Borders, secondary blue
  AccentPurple: "#ac65ff",
  // Comments (main purple)
  AccentCyan: "#a1feff",
  // Names
  AccentGreen: "#A5FF90",
  // Strings and many others
  AccentYellow: "#fad000",
  // Title, main yellow
  AccentRed: "#ff628c",
  // Error/deletion accent
  DiffAdded: "#383E45",
  DiffRemoved: "#572244",
  Comment: "#B362FF",
  // Comment color (same as AccentPurple)
  Gray: "#726c86",
  // Gray color
  GradientColors: ["#4d21fc", "#847ace", "#ff628c"]
};
var additionalColors = {
  AccentYellowAlt: "#f8d000",
  // Attr yellow (slightly different)
  AccentOrange: "#fb9e00",
  // Keywords, built_in, meta
  AccentPink: "#fa658d",
  // Numbers, literals
  AccentLightPurple: "#c991ff",
  // For params and properties
  AccentDarkPurple: "#6943ff",
  // For operators
  AccentTeal: "#2ee2fa"
  // For special constructs
};
var ShadesOfPurple = new Theme(
  "Shades Of Purple",
  "dark",
  {
    // Base styles
    hljs: {
      display: "block",
      overflowX: "auto",
      background: shadesOfPurpleColors.Background,
      color: shadesOfPurpleColors.Foreground
    },
    // Title elements
    "hljs-title": {
      color: shadesOfPurpleColors.AccentYellow,
      fontWeight: "normal"
    },
    // Names
    "hljs-name": {
      color: shadesOfPurpleColors.AccentCyan,
      fontWeight: "normal"
    },
    // Tags
    "hljs-tag": {
      color: shadesOfPurpleColors.Foreground
    },
    // Attributes
    "hljs-attr": {
      color: additionalColors.AccentYellowAlt,
      fontStyle: "italic"
    },
    // Built-ins, selector tags, sections
    "hljs-built_in": {
      color: additionalColors.AccentOrange
    },
    "hljs-selector-tag": {
      color: additionalColors.AccentOrange,
      fontWeight: "normal"
    },
    "hljs-section": {
      color: additionalColors.AccentOrange
    },
    // Keywords
    "hljs-keyword": {
      color: additionalColors.AccentOrange,
      fontWeight: "normal"
    },
    // Default text and substitutions
    "hljs-subst": {
      color: shadesOfPurpleColors.Foreground
    },
    // Strings and related elements (all green)
    "hljs-string": {
      color: shadesOfPurpleColors.AccentGreen
    },
    "hljs-attribute": {
      color: shadesOfPurpleColors.AccentGreen
    },
    "hljs-symbol": {
      color: shadesOfPurpleColors.AccentGreen
    },
    "hljs-bullet": {
      color: shadesOfPurpleColors.AccentGreen
    },
    "hljs-addition": {
      color: shadesOfPurpleColors.AccentGreen
    },
    "hljs-code": {
      color: shadesOfPurpleColors.AccentGreen
    },
    "hljs-regexp": {
      color: shadesOfPurpleColors.AccentGreen
    },
    "hljs-selector-class": {
      color: shadesOfPurpleColors.AccentGreen
    },
    "hljs-selector-attr": {
      color: shadesOfPurpleColors.AccentGreen
    },
    "hljs-selector-pseudo": {
      color: shadesOfPurpleColors.AccentGreen
    },
    "hljs-template-tag": {
      color: shadesOfPurpleColors.AccentGreen
    },
    "hljs-quote": {
      color: shadesOfPurpleColors.AccentGreen
    },
    "hljs-deletion": {
      color: shadesOfPurpleColors.AccentRed
    },
    // Meta elements
    "hljs-meta": {
      color: additionalColors.AccentOrange
    },
    "hljs-meta-string": {
      color: additionalColors.AccentOrange
    },
    // Comments
    "hljs-comment": {
      color: shadesOfPurpleColors.AccentPurple
    },
    // Literals and numbers
    "hljs-literal": {
      color: additionalColors.AccentPink,
      fontWeight: "normal"
    },
    "hljs-number": {
      color: additionalColors.AccentPink
    },
    // Emphasis and strong
    "hljs-emphasis": {
      fontStyle: "italic"
    },
    "hljs-strong": {
      fontWeight: "bold"
    },
    // Diff-specific classes
    "hljs-diff": {
      color: shadesOfPurpleColors.Foreground
    },
    "hljs-meta.hljs-diff": {
      color: shadesOfPurpleColors.AccentBlue
    },
    "hljs-ln": {
      color: shadesOfPurpleColors.Gray
    },
    // Additional elements that might be needed
    "hljs-type": {
      color: shadesOfPurpleColors.AccentYellow,
      fontWeight: "normal"
    },
    "hljs-variable": {
      color: shadesOfPurpleColors.AccentYellow
    },
    "hljs-template-variable": {
      color: shadesOfPurpleColors.AccentGreen
    },
    "hljs-function .hljs-keyword": {
      color: additionalColors.AccentOrange
    },
    "hljs-link": {
      color: shadesOfPurpleColors.LightBlue
    },
    "hljs-doctag": {
      fontWeight: "bold"
    },
    // Function parameters
    "hljs-params": {
      color: additionalColors.AccentLightPurple,
      fontStyle: "italic"
    },
    // Class definitions
    "hljs-class": {
      color: shadesOfPurpleColors.AccentCyan,
      fontWeight: "bold"
    },
    // Function definitions
    "hljs-function": {
      color: shadesOfPurpleColors.AccentCyan
    },
    // Object properties
    "hljs-property": {
      color: shadesOfPurpleColors.AccentBlue
    },
    // Operators
    "hljs-operator": {
      color: additionalColors.AccentDarkPurple
    },
    // Punctuation (if supported by the parser)
    "hljs-punctuation": {
      color: shadesOfPurpleColors.Gray
    },
    // CSS ID selectors
    "hljs-selector-id": {
      color: shadesOfPurpleColors.AccentYellow,
      fontWeight: "bold"
    },
    // Character literals
    "hljs-char": {
      color: shadesOfPurpleColors.AccentGreen
    },
    // Escape sequences
    "hljs-escape": {
      color: additionalColors.AccentPink,
      fontWeight: "bold"
    },
    // Meta keywords
    "hljs-meta-keyword": {
      color: additionalColors.AccentOrange,
      fontWeight: "bold"
    },
    // Built-in names
    "hljs-builtin-name": {
      color: additionalColors.AccentTeal
    },
    // Modules
    "hljs-module": {
      color: shadesOfPurpleColors.AccentCyan
    },
    // Namespaces
    "hljs-namespace": {
      color: shadesOfPurpleColors.LightBlue
    },
    // Important annotations
    "hljs-important": {
      color: shadesOfPurpleColors.AccentRed,
      fontWeight: "bold"
    },
    // Formulas (for LaTeX, etc.)
    "hljs-formula": {
      color: shadesOfPurpleColors.AccentCyan,
      fontStyle: "italic"
    },
    // Language-specific additions
    // Python decorators
    "hljs-decorator": {
      color: additionalColors.AccentTeal,
      fontWeight: "bold"
    },
    // Ruby symbols
    "hljs-symbol.ruby": {
      color: additionalColors.AccentPink
    },
    // SQL keywords
    "hljs-keyword.sql": {
      color: additionalColors.AccentOrange,
      textTransform: "uppercase"
    },
    // Markdown specific
    "hljs-section.markdown": {
      color: shadesOfPurpleColors.AccentYellow,
      fontWeight: "bold"
    },
    // JSON keys
    "hljs-attr.json": {
      color: shadesOfPurpleColors.AccentCyan
    },
    // XML/HTML specific
    "hljs-tag .hljs-name": {
      color: shadesOfPurpleColors.AccentRed
    },
    "hljs-tag .hljs-attr": {
      color: additionalColors.AccentYellowAlt
    },
    // Line highlighting (if line numbers are enabled)
    "hljs.hljs-line-numbers": {
      borderRight: `1px solid ${shadesOfPurpleColors.Gray}`
    },
    "hljs.hljs-line-numbers .hljs-ln-numbers": {
      color: shadesOfPurpleColors.Gray,
      paddingRight: "1em"
    },
    "hljs.hljs-line-numbers .hljs-ln-code": {
      paddingLeft: "1em"
    },
    // Selection styling
    "hljs::selection": {
      background: shadesOfPurpleColors.AccentBlue + "40"
      // 40 = 25% opacity
    },
    "hljs ::-moz-selection": {
      background: shadesOfPurpleColors.AccentBlue + "40"
    },
    // Highlighted lines (for emphasis)
    "hljs .hljs-highlight": {
      background: shadesOfPurpleColors.AccentPurple + "20",
      // 20 = 12.5% opacity
      display: "block",
      width: "100%"
    }
  },
  shadesOfPurpleColors
);

// packages/cli/src/ui/themes/xcode.ts
init_esbuild_shims();
var xcodeColors = {
  type: "light",
  Background: "#fff",
  Foreground: "#444",
  LightBlue: "#0E0EFF",
  AccentBlue: "#1c00cf",
  AccentPurple: "#aa0d91",
  AccentCyan: "#3F6E74",
  AccentGreen: "#007400",
  AccentYellow: "#836C28",
  AccentRed: "#c41a16",
  DiffAdded: "#C6EAD8",
  DiffRemoved: "#FEDEDE",
  Comment: "#007400",
  Gray: "#c0c0c0",
  GradientColors: ["#1c00cf", "#007400"]
};
var XCode = new Theme(
  "Xcode",
  "light",
  {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em",
      background: xcodeColors.Background,
      color: xcodeColors.Foreground
    },
    "xml .hljs-meta": {
      color: xcodeColors.Gray
    },
    "hljs-comment": {
      color: xcodeColors.Comment
    },
    "hljs-quote": {
      color: xcodeColors.Comment
    },
    "hljs-tag": {
      color: xcodeColors.AccentPurple
    },
    "hljs-attribute": {
      color: xcodeColors.AccentPurple
    },
    "hljs-keyword": {
      color: xcodeColors.AccentPurple
    },
    "hljs-selector-tag": {
      color: xcodeColors.AccentPurple
    },
    "hljs-literal": {
      color: xcodeColors.AccentPurple
    },
    "hljs-name": {
      color: xcodeColors.AccentPurple
    },
    "hljs-variable": {
      color: xcodeColors.AccentCyan
    },
    "hljs-template-variable": {
      color: xcodeColors.AccentCyan
    },
    "hljs-code": {
      color: xcodeColors.AccentRed
    },
    "hljs-string": {
      color: xcodeColors.AccentRed
    },
    "hljs-meta-string": {
      color: xcodeColors.AccentRed
    },
    "hljs-regexp": {
      color: xcodeColors.LightBlue
    },
    "hljs-link": {
      color: xcodeColors.LightBlue
    },
    "hljs-title": {
      color: xcodeColors.AccentBlue
    },
    "hljs-symbol": {
      color: xcodeColors.AccentBlue
    },
    "hljs-bullet": {
      color: xcodeColors.AccentBlue
    },
    "hljs-number": {
      color: xcodeColors.AccentBlue
    },
    "hljs-section": {
      color: xcodeColors.AccentYellow
    },
    "hljs-meta": {
      color: xcodeColors.AccentYellow
    },
    "hljs-class .hljs-title": {
      color: xcodeColors.AccentPurple
    },
    "hljs-type": {
      color: xcodeColors.AccentPurple
    },
    "hljs-built_in": {
      color: xcodeColors.AccentPurple
    },
    "hljs-builtin-name": {
      color: xcodeColors.AccentPurple
    },
    "hljs-params": {
      color: xcodeColors.AccentPurple
    },
    "hljs-attr": {
      color: xcodeColors.AccentYellow
    },
    "hljs-subst": {
      color: xcodeColors.Foreground
    },
    "hljs-formula": {
      backgroundColor: "#eee",
      fontStyle: "italic"
    },
    "hljs-addition": {
      backgroundColor: "#baeeba"
    },
    "hljs-deletion": {
      backgroundColor: "#ffc8bd"
    },
    "hljs-selector-id": {
      color: xcodeColors.AccentYellow
    },
    "hljs-selector-class": {
      color: xcodeColors.AccentYellow
    },
    "hljs-doctag": {
      fontWeight: "bold"
    },
    "hljs-strong": {
      fontWeight: "bold"
    },
    "hljs-emphasis": {
      fontStyle: "italic"
    }
  },
  xcodeColors
);

// packages/cli/src/ui/themes/qwen-light.ts
init_esbuild_shims();

// packages/cli/src/ui/themes/semantic-tokens.ts
init_esbuild_shims();
var lightSemanticColors = {
  text: {
    primary: lightTheme.Foreground,
    secondary: lightTheme.Gray,
    link: lightTheme.AccentBlue,
    accent: lightTheme.AccentPurple
  },
  background: {
    primary: lightTheme.Background,
    diff: {
      added: lightTheme.DiffAdded,
      removed: lightTheme.DiffRemoved
    }
  },
  border: {
    default: lightTheme.Gray,
    focused: lightTheme.AccentBlue
  },
  ui: {
    comment: lightTheme.Comment,
    symbol: lightTheme.Gray,
    gradient: lightTheme.GradientColors
  },
  status: {
    error: lightTheme.AccentRed,
    success: lightTheme.AccentGreen,
    warning: lightTheme.AccentYellow
  }
};
var darkSemanticColors = {
  text: {
    primary: darkTheme.Foreground,
    secondary: darkTheme.Gray,
    link: darkTheme.AccentBlue,
    accent: darkTheme.AccentPurple
  },
  background: {
    primary: darkTheme.Background,
    diff: {
      added: darkTheme.DiffAdded,
      removed: darkTheme.DiffRemoved
    }
  },
  border: {
    default: darkTheme.Gray,
    focused: darkTheme.AccentBlue
  },
  ui: {
    comment: darkTheme.Comment,
    symbol: darkTheme.Gray,
    gradient: darkTheme.GradientColors
  },
  status: {
    error: darkTheme.AccentRed,
    success: darkTheme.AccentGreen,
    warning: darkTheme.AccentYellow
  }
};
var ansiSemanticColors = {
  text: {
    primary: ansiTheme.Foreground,
    secondary: ansiTheme.Gray,
    link: ansiTheme.AccentBlue,
    accent: ansiTheme.AccentPurple
  },
  background: {
    primary: ansiTheme.Background,
    diff: {
      added: ansiTheme.DiffAdded,
      removed: ansiTheme.DiffRemoved
    }
  },
  border: {
    default: ansiTheme.Gray,
    focused: ansiTheme.AccentBlue
  },
  ui: {
    comment: ansiTheme.Comment,
    symbol: ansiTheme.Gray,
    gradient: ansiTheme.GradientColors
  },
  status: {
    error: ansiTheme.AccentRed,
    success: ansiTheme.AccentGreen,
    warning: ansiTheme.AccentYellow
  }
};

// packages/cli/src/ui/themes/qwen-light.ts
var qwenLightColors = {
  type: "light",
  Background: "#f8f9fa",
  Foreground: "#5c6166",
  LightBlue: "#55b4d4",
  AccentBlue: "#399ee6",
  AccentPurple: "#a37acc",
  AccentCyan: "#4cbf99",
  AccentGreen: "#86b300",
  AccentYellow: "#f2ae49",
  AccentRed: "#f07171",
  DiffAdded: "#86b300",
  DiffRemoved: "#f07171",
  Comment: "#ABADB1",
  Gray: "#CCCFD3",
  GradientColors: ["#399ee6", "#86b300"]
};
var QwenLight = new Theme(
  "Qwen Light",
  "light",
  {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em",
      background: qwenLightColors.Background,
      color: qwenLightColors.Foreground
    },
    "hljs-comment": {
      color: qwenLightColors.Comment,
      fontStyle: "italic"
    },
    "hljs-quote": {
      color: qwenLightColors.AccentCyan,
      fontStyle: "italic"
    },
    "hljs-string": {
      color: qwenLightColors.AccentGreen
    },
    "hljs-constant": {
      color: qwenLightColors.AccentCyan
    },
    "hljs-number": {
      color: qwenLightColors.AccentPurple
    },
    "hljs-keyword": {
      color: qwenLightColors.AccentYellow
    },
    "hljs-selector-tag": {
      color: qwenLightColors.AccentYellow
    },
    "hljs-attribute": {
      color: qwenLightColors.AccentYellow
    },
    "hljs-variable": {
      color: qwenLightColors.Foreground
    },
    "hljs-variable.language": {
      color: qwenLightColors.LightBlue,
      fontStyle: "italic"
    },
    "hljs-title": {
      color: qwenLightColors.AccentBlue
    },
    "hljs-section": {
      color: qwenLightColors.AccentGreen,
      fontWeight: "bold"
    },
    "hljs-type": {
      color: qwenLightColors.LightBlue
    },
    "hljs-class .hljs-title": {
      color: qwenLightColors.AccentBlue
    },
    "hljs-tag": {
      color: qwenLightColors.LightBlue
    },
    "hljs-name": {
      color: qwenLightColors.AccentBlue
    },
    "hljs-builtin-name": {
      color: qwenLightColors.AccentYellow
    },
    "hljs-meta": {
      color: qwenLightColors.AccentYellow
    },
    "hljs-symbol": {
      color: qwenLightColors.AccentRed
    },
    "hljs-bullet": {
      color: qwenLightColors.AccentYellow
    },
    "hljs-regexp": {
      color: qwenLightColors.AccentCyan
    },
    "hljs-link": {
      color: qwenLightColors.LightBlue
    },
    "hljs-deletion": {
      color: qwenLightColors.AccentRed
    },
    "hljs-addition": {
      color: qwenLightColors.AccentGreen
    },
    "hljs-emphasis": {
      fontStyle: "italic"
    },
    "hljs-strong": {
      fontWeight: "bold"
    },
    "hljs-literal": {
      color: qwenLightColors.AccentCyan
    },
    "hljs-built_in": {
      color: qwenLightColors.AccentRed
    },
    "hljs-doctag": {
      color: qwenLightColors.AccentRed
    },
    "hljs-template-variable": {
      color: qwenLightColors.AccentCyan
    },
    "hljs-selector-id": {
      color: qwenLightColors.AccentRed
    }
  },
  qwenLightColors,
  lightSemanticColors
);

// packages/cli/src/ui/themes/qwen-dark.ts
init_esbuild_shims();
var qwenDarkColors = {
  type: "dark",
  Background: "#0b0e14",
  Foreground: "#bfbdb6",
  LightBlue: "#59C2FF",
  AccentBlue: "#39BAE6",
  AccentPurple: "#D2A6FF",
  AccentCyan: "#95E6CB",
  AccentGreen: "#AAD94C",
  AccentYellow: "#FFD700",
  AccentRed: "#F26D78",
  DiffAdded: "#AAD94C",
  DiffRemoved: "#F26D78",
  Comment: "#646A71",
  Gray: "#3D4149",
  GradientColors: ["#FFD700", "#da7959"]
};
var QwenDark = new Theme(
  "Qwen Dark",
  "dark",
  {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em",
      background: qwenDarkColors.Background,
      color: qwenDarkColors.Foreground
    },
    "hljs-keyword": {
      color: qwenDarkColors.AccentYellow
    },
    "hljs-literal": {
      color: qwenDarkColors.AccentPurple
    },
    "hljs-symbol": {
      color: qwenDarkColors.AccentCyan
    },
    "hljs-name": {
      color: qwenDarkColors.LightBlue
    },
    "hljs-link": {
      color: qwenDarkColors.AccentBlue
    },
    "hljs-function .hljs-keyword": {
      color: qwenDarkColors.AccentYellow
    },
    "hljs-subst": {
      color: qwenDarkColors.Foreground
    },
    "hljs-string": {
      color: qwenDarkColors.AccentGreen
    },
    "hljs-title": {
      color: qwenDarkColors.AccentYellow
    },
    "hljs-type": {
      color: qwenDarkColors.AccentBlue
    },
    "hljs-attribute": {
      color: qwenDarkColors.AccentYellow
    },
    "hljs-bullet": {
      color: qwenDarkColors.AccentYellow
    },
    "hljs-addition": {
      color: qwenDarkColors.AccentGreen
    },
    "hljs-variable": {
      color: qwenDarkColors.Foreground
    },
    "hljs-template-tag": {
      color: qwenDarkColors.AccentYellow
    },
    "hljs-template-variable": {
      color: qwenDarkColors.AccentYellow
    },
    "hljs-comment": {
      color: qwenDarkColors.Comment,
      fontStyle: "italic"
    },
    "hljs-quote": {
      color: qwenDarkColors.AccentCyan,
      fontStyle: "italic"
    },
    "hljs-deletion": {
      color: qwenDarkColors.AccentRed
    },
    "hljs-meta": {
      color: qwenDarkColors.AccentYellow
    },
    "hljs-doctag": {
      fontWeight: "bold"
    },
    "hljs-strong": {
      fontWeight: "bold"
    },
    "hljs-emphasis": {
      fontStyle: "italic"
    }
  },
  qwenDarkColors,
  darkSemanticColors
);

// packages/cli/src/ui/themes/theme-manager.ts
import * as fs53 from "node:fs";
import * as path60 from "node:path";
import * as os23 from "node:os";

// packages/cli/src/ui/themes/ansi.ts
init_esbuild_shims();
var ansiColors = {
  type: "dark",
  Background: "black",
  Foreground: "white",
  LightBlue: "bluebright",
  AccentBlue: "blue",
  AccentPurple: "magenta",
  AccentCyan: "cyan",
  AccentGreen: "green",
  AccentYellow: "yellow",
  AccentRed: "red",
  DiffAdded: "#003300",
  DiffRemoved: "#4D0000",
  Comment: "gray",
  Gray: "gray",
  GradientColors: ["cyan", "green"]
};
var ANSI = new Theme(
  "ANSI",
  "dark",
  // Consistent with its color palette base
  {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em",
      background: "black",
      // Mapped from #1E1E1E
      color: "white"
      // Mapped from #DCDCDC
    },
    "hljs-keyword": {
      color: "blue"
      // Mapped from #569CD6
    },
    "hljs-literal": {
      color: "blue"
      // Mapped from #569CD6
    },
    "hljs-symbol": {
      color: "blue"
      // Mapped from #569CD6
    },
    "hljs-name": {
      color: "blue"
      // Mapped from #569CD6
    },
    "hljs-link": {
      color: "blue"
      // Mapped from #569CD6
      // textDecoration is ignored by Theme class
    },
    "hljs-built_in": {
      color: "cyan"
      // Mapped from #4EC9B0
    },
    "hljs-type": {
      color: "cyan"
      // Mapped from #4EC9B0
    },
    "hljs-number": {
      color: "green"
      // Mapped from #B8D7A3
    },
    "hljs-class": {
      color: "green"
      // Mapped from #B8D7A3
    },
    "hljs-string": {
      color: "yellow"
      // Mapped from #D69D85
    },
    "hljs-meta-string": {
      color: "yellow"
      // Mapped from #D69D85
    },
    "hljs-regexp": {
      color: "red"
      // Mapped from #9A5334
    },
    "hljs-template-tag": {
      color: "red"
      // Mapped from #9A5334
    },
    "hljs-subst": {
      color: "white"
      // Mapped from #DCDCDC
    },
    "hljs-function": {
      color: "white"
      // Mapped from #DCDCDC
    },
    "hljs-title": {
      color: "white"
      // Mapped from #DCDCDC
    },
    "hljs-params": {
      color: "white"
      // Mapped from #DCDCDC
    },
    "hljs-formula": {
      color: "white"
      // Mapped from #DCDCDC
    },
    "hljs-comment": {
      color: "green"
      // Mapped from #57A64A
      // fontStyle is ignored by Theme class
    },
    "hljs-quote": {
      color: "green"
      // Mapped from #57A64A
      // fontStyle is ignored by Theme class
    },
    "hljs-doctag": {
      color: "green"
      // Mapped from #608B4E
    },
    "hljs-meta": {
      color: "gray"
      // Mapped from #9B9B9B
    },
    "hljs-meta-keyword": {
      color: "gray"
      // Mapped from #9B9B9B
    },
    "hljs-tag": {
      color: "gray"
      // Mapped from #9B9B9B
    },
    "hljs-variable": {
      color: "magenta"
      // Mapped from #BD63C5
    },
    "hljs-template-variable": {
      color: "magenta"
      // Mapped from #BD63C5
    },
    "hljs-attr": {
      color: "bluebright"
      // Mapped from #9CDCFE
    },
    "hljs-attribute": {
      color: "bluebright"
      // Mapped from #9CDCFE
    },
    "hljs-builtin-name": {
      color: "bluebright"
      // Mapped from #9CDCFE
    },
    "hljs-section": {
      color: "yellow"
      // Mapped from gold
    },
    "hljs-emphasis": {
      // fontStyle is ignored by Theme class
    },
    "hljs-strong": {
      // fontWeight is ignored by Theme class
    },
    "hljs-bullet": {
      color: "yellow"
      // Mapped from #D7BA7D
    },
    "hljs-selector-tag": {
      color: "yellow"
      // Mapped from #D7BA7D
    },
    "hljs-selector-id": {
      color: "yellow"
      // Mapped from #D7BA7D
    },
    "hljs-selector-class": {
      color: "yellow"
      // Mapped from #D7BA7D
    },
    "hljs-selector-attr": {
      color: "yellow"
      // Mapped from #D7BA7D
    },
    "hljs-selector-pseudo": {
      color: "yellow"
      // Mapped from #D7BA7D
    }
  },
  ansiColors,
  darkSemanticColors
);

// packages/cli/src/ui/themes/ansi-light.ts
init_esbuild_shims();
var ansiLightColors = {
  type: "light",
  Background: "white",
  Foreground: "#444",
  LightBlue: "blue",
  AccentBlue: "blue",
  AccentPurple: "purple",
  AccentCyan: "cyan",
  AccentGreen: "green",
  AccentYellow: "orange",
  AccentRed: "red",
  DiffAdded: "#E5F2E5",
  DiffRemoved: "#FFE5E5",
  Comment: "gray",
  Gray: "gray",
  GradientColors: ["blue", "green"]
};
var ANSILight = new Theme(
  "ANSI Light",
  "light",
  {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em",
      background: "white",
      color: "black"
    },
    "hljs-keyword": {
      color: "blue"
    },
    "hljs-literal": {
      color: "blue"
    },
    "hljs-symbol": {
      color: "blue"
    },
    "hljs-name": {
      color: "blue"
    },
    "hljs-link": {
      color: "blue"
    },
    "hljs-built_in": {
      color: "cyan"
    },
    "hljs-type": {
      color: "cyan"
    },
    "hljs-number": {
      color: "green"
    },
    "hljs-class": {
      color: "green"
    },
    "hljs-string": {
      color: "red"
    },
    "hljs-meta-string": {
      color: "red"
    },
    "hljs-regexp": {
      color: "magenta"
    },
    "hljs-template-tag": {
      color: "magenta"
    },
    "hljs-subst": {
      color: "black"
    },
    "hljs-function": {
      color: "black"
    },
    "hljs-title": {
      color: "black"
    },
    "hljs-params": {
      color: "black"
    },
    "hljs-formula": {
      color: "black"
    },
    "hljs-comment": {
      color: "gray"
    },
    "hljs-quote": {
      color: "gray"
    },
    "hljs-doctag": {
      color: "gray"
    },
    "hljs-meta": {
      color: "gray"
    },
    "hljs-meta-keyword": {
      color: "gray"
    },
    "hljs-tag": {
      color: "gray"
    },
    "hljs-variable": {
      color: "purple"
    },
    "hljs-template-variable": {
      color: "purple"
    },
    "hljs-attr": {
      color: "blue"
    },
    "hljs-attribute": {
      color: "blue"
    },
    "hljs-builtin-name": {
      color: "blue"
    },
    "hljs-section": {
      color: "orange"
    },
    "hljs-bullet": {
      color: "orange"
    },
    "hljs-selector-tag": {
      color: "orange"
    },
    "hljs-selector-id": {
      color: "orange"
    },
    "hljs-selector-class": {
      color: "orange"
    },
    "hljs-selector-attr": {
      color: "orange"
    },
    "hljs-selector-pseudo": {
      color: "orange"
    }
  },
  ansiLightColors,
  lightSemanticColors
);

// packages/cli/src/ui/themes/no-color.ts
init_esbuild_shims();
var noColorColorsTheme = {
  type: "ansi",
  Background: "",
  Foreground: "",
  LightBlue: "",
  AccentBlue: "",
  AccentPurple: "",
  AccentCyan: "",
  AccentGreen: "",
  AccentYellow: "",
  AccentRed: "",
  DiffAdded: "",
  DiffRemoved: "",
  Comment: "",
  Gray: ""
};
var noColorSemanticColors = {
  text: {
    primary: "",
    secondary: "",
    link: "",
    accent: ""
  },
  background: {
    primary: "",
    diff: {
      added: "",
      removed: ""
    }
  },
  border: {
    default: "",
    focused: ""
  },
  ui: {
    comment: "",
    symbol: "",
    gradient: []
  },
  status: {
    error: "",
    success: "",
    warning: ""
  }
};
var NoColorTheme = new Theme(
  "NoColor",
  "dark",
  {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em"
    },
    "hljs-keyword": {},
    "hljs-literal": {},
    "hljs-symbol": {},
    "hljs-name": {},
    "hljs-link": {
      textDecoration: "underline"
    },
    "hljs-built_in": {},
    "hljs-type": {},
    "hljs-number": {},
    "hljs-class": {},
    "hljs-string": {},
    "hljs-meta-string": {},
    "hljs-regexp": {},
    "hljs-template-tag": {},
    "hljs-subst": {},
    "hljs-function": {},
    "hljs-title": {},
    "hljs-params": {},
    "hljs-formula": {},
    "hljs-comment": {
      fontStyle: "italic"
    },
    "hljs-quote": {
      fontStyle: "italic"
    },
    "hljs-doctag": {},
    "hljs-meta": {},
    "hljs-meta-keyword": {},
    "hljs-tag": {},
    "hljs-variable": {},
    "hljs-template-variable": {},
    "hljs-attr": {},
    "hljs-attribute": {},
    "hljs-builtin-name": {},
    "hljs-section": {},
    "hljs-emphasis": {
      fontStyle: "italic"
    },
    "hljs-strong": {
      fontWeight: "bold"
    },
    "hljs-bullet": {},
    "hljs-selector-tag": {},
    "hljs-selector-id": {},
    "hljs-selector-class": {},
    "hljs-selector-attr": {},
    "hljs-selector-pseudo": {},
    "hljs-addition": {
      display: "inline-block",
      width: "100%"
    },
    "hljs-deletion": {
      display: "inline-block",
      width: "100%"
    }
  },
  noColorColorsTheme,
  noColorSemanticColors
);

// packages/cli/src/ui/themes/theme-manager.ts
import process25 from "node:process";
var DEFAULT_THEME = QwenDark;
var ThemeManager = class {
  static {
    __name(this, "ThemeManager");
  }
  availableThemes;
  activeTheme;
  customThemes = /* @__PURE__ */ new Map();
  constructor() {
    this.availableThemes = [
      AyuDark,
      AyuLight,
      AtomOneDark,
      Dracula,
      DefaultLight,
      DefaultDark,
      GitHubDark,
      GitHubLight,
      GoogleCode,
      QwenLight,
      QwenDark,
      ShadesOfPurple,
      XCode,
      ANSI,
      ANSILight
    ];
    this.activeTheme = DEFAULT_THEME;
  }
  /**
   * Loads custom themes from settings.
   * @param customThemesSettings Custom themes from settings.
   */
  loadCustomThemes(customThemesSettings) {
    this.customThemes.clear();
    if (!customThemesSettings) {
      return;
    }
    for (const [name3, customThemeConfig] of Object.entries(
      customThemesSettings
    )) {
      const validation2 = validateCustomTheme(customThemeConfig);
      if (validation2.isValid) {
        if (validation2.warning) {
          console.warn(`Theme "${name3}": ${validation2.warning}`);
        }
        const themeWithDefaults = {
          ...DEFAULT_THEME.colors,
          ...customThemeConfig,
          name: customThemeConfig.name || name3,
          type: "custom"
        };
        try {
          const theme2 = createCustomTheme(themeWithDefaults);
          this.customThemes.set(name3, theme2);
        } catch (error) {
          console.warn(`Failed to load custom theme "${name3}":`, error);
        }
      } else {
        console.warn(`Invalid custom theme "${name3}": ${validation2.error}`);
      }
    }
    if (this.activeTheme && this.activeTheme.type === "custom" && this.customThemes.has(this.activeTheme.name)) {
      this.activeTheme = this.customThemes.get(this.activeTheme.name);
    }
  }
  /**
   * Sets the active theme.
   * @param themeName The name of the theme to set as active.
   * @returns True if the theme was successfully set, false otherwise.
   */
  setActiveTheme(themeName) {
    const theme2 = this.findThemeByName(themeName);
    if (!theme2) {
      return false;
    }
    this.activeTheme = theme2;
    return true;
  }
  /**
   * Gets the currently active theme.
   * @returns The active theme.
   */
  getActiveTheme() {
    if (process25.env["NO_COLOR"]) {
      return NoColorTheme;
    }
    if (this.activeTheme) {
      const isBuiltIn = this.availableThemes.some(
        (t2) => t2.name === this.activeTheme.name
      );
      const isCustom = [...this.customThemes.values()].includes(
        this.activeTheme
      );
      if (isBuiltIn || isCustom) {
        return this.activeTheme;
      }
    }
    this.activeTheme = DEFAULT_THEME;
    return this.activeTheme;
  }
  /**
   * Gets the semantic colors for the active theme.
   * @returns The semantic colors.
   */
  getSemanticColors() {
    return this.getActiveTheme().semanticColors;
  }
  /**
   * Gets a list of custom theme names.
   * @returns Array of custom theme names.
   */
  getCustomThemeNames() {
    return Array.from(this.customThemes.keys());
  }
  /**
   * Checks if a theme name is a custom theme.
   * @param themeName The theme name to check.
   * @returns True if the theme is custom.
   */
  isCustomTheme(themeName) {
    return this.customThemes.has(themeName);
  }
  /**
   * Returns a list of available theme names.
   */
  getAvailableThemes() {
    const builtInThemes = this.availableThemes.map((theme2) => ({
      name: theme2.name,
      type: theme2.type,
      isCustom: false
    }));
    const customThemes = Array.from(this.customThemes.values()).map(
      (theme2) => ({
        name: theme2.name,
        type: theme2.type,
        isCustom: true
      })
    );
    const qwenThemes = builtInThemes.filter(
      (theme2) => theme2.name === QwenLight.name || theme2.name === QwenDark.name
    );
    const otherBuiltInThemes = builtInThemes.filter(
      (theme2) => theme2.name !== QwenLight.name && theme2.name !== QwenDark.name
    );
    const sortedOtherThemes = [...otherBuiltInThemes, ...customThemes].sort(
      (a, b) => {
        const typeOrder = /* @__PURE__ */ __name((type) => {
          switch (type) {
            case "dark":
              return 1;
            case "light":
              return 2;
            case "ansi":
              return 3;
            case "custom":
              return 4;
            // Custom themes at the end
            default:
              return 5;
          }
        }, "typeOrder");
        const typeComparison = typeOrder(a.type) - typeOrder(b.type);
        if (typeComparison !== 0) {
          return typeComparison;
        }
        return a.name.localeCompare(b.name);
      }
    );
    return [...qwenThemes, ...sortedOtherThemes];
  }
  /**
   * Gets a theme by name.
   * @param themeName The name of the theme to get.
   * @returns The theme if found, undefined otherwise.
   */
  getTheme(themeName) {
    return this.findThemeByName(themeName);
  }
  isPath(themeName) {
    return themeName.endsWith(".json") || themeName.startsWith(".") || path60.isAbsolute(themeName);
  }
  loadThemeFromFile(themePath) {
    try {
      const canonicalPath = fs53.realpathSync(path60.resolve(themePath));
      if (this.customThemes.has(canonicalPath)) {
        return this.customThemes.get(canonicalPath);
      }
      const homeDir = path60.resolve(os23.homedir());
      if (!canonicalPath.startsWith(homeDir)) {
        console.warn(
          `Theme file at "${themePath}" is outside your home directory. Only load themes from trusted sources.`
        );
        return void 0;
      }
      const themeContent = fs53.readFileSync(canonicalPath, "utf-8");
      const customThemeConfig = JSON.parse(themeContent);
      const validation2 = validateCustomTheme(customThemeConfig);
      if (!validation2.isValid) {
        console.warn(
          `Invalid custom theme from file "${themePath}": ${validation2.error}`
        );
        return void 0;
      }
      if (validation2.warning) {
        console.warn(`Theme from "${themePath}": ${validation2.warning}`);
      }
      const themeWithDefaults = {
        ...DEFAULT_THEME.colors,
        ...customThemeConfig,
        name: customThemeConfig.name || canonicalPath,
        type: "custom"
      };
      const theme2 = createCustomTheme(themeWithDefaults);
      this.customThemes.set(canonicalPath, theme2);
      return theme2;
    } catch (error) {
      if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {
        console.warn(`Could not load theme from file "${themePath}":`, error);
      }
      return void 0;
    }
  }
  findThemeByName(themeName) {
    if (!themeName) {
      return DEFAULT_THEME;
    }
    const builtInTheme = this.availableThemes.find(
      (theme2) => theme2.name === themeName
    );
    if (builtInTheme) {
      return builtInTheme;
    }
    if (this.isPath(themeName)) {
      return this.loadThemeFromFile(themeName);
    }
    if (this.customThemes.has(themeName)) {
      return this.customThemes.get(themeName);
    }
    return void 0;
  }
};
var themeManager = new ThemeManager();

// packages/cli/src/ui/semantic-colors.ts
var theme = {
  get text() {
    return themeManager.getSemanticColors().text;
  },
  get background() {
    return themeManager.getSemanticColors().background;
  },
  get border() {
    return themeManager.getSemanticColors().border;
  },
  get ui() {
    return themeManager.getSemanticColors().ui;
  },
  get status() {
    return themeManager.getSemanticColors().status;
  }
};

// packages/cli/src/ui/textConstants.ts
init_esbuild_shims();
var SCREEN_READER_USER_PREFIX = "User: ";
var SCREEN_READER_MODEL_PREFIX = "Model: ";
var SCREEN_READER_LOADING = "loading";
var SCREEN_READER_RESPONDING = "responding";

// packages/cli/src/ui/utils/commandUtils.ts
init_esbuild_shims();
import { spawn as spawn6 } from "node:child_process";
var CodePage = {
  UTF8: 65001,
  GBK: 936,
  BIG5: 950,
  LATIN1: 1252
};
var isAtCommand = /* @__PURE__ */ __name((query) => (
  // Check if starts with @ OR has a space, then @
  query.startsWith("@") || /\s@/.test(query)
), "isAtCommand");
var isSlashCommand = /* @__PURE__ */ __name((query) => {
  if (!query.startsWith("/")) {
    return false;
  }
  if (query.startsWith("//")) {
    return false;
  }
  if (query.startsWith("/*")) {
    return false;
  }
  return true;
}, "isSlashCommand");
var copyToClipboard = /* @__PURE__ */ __name(async (text) => {
  const run = /* @__PURE__ */ __name((cmd, args, options2) => new Promise((resolve24, reject) => {
    const child = options2 ? spawn6(cmd, args, options2) : spawn6(cmd, args);
    let stderr = "";
    if (child.stderr) {
      child.stderr.on("data", (chunk) => stderr += chunk.toString());
    }
    child.on("error", reject);
    child.on("close", (code2) => {
      if (code2 === 0) return resolve24();
      const errorMsg = stderr.trim();
      reject(
        new Error(
          `'${cmd}' exited with code ${code2}${errorMsg ? `: ${errorMsg}` : ""}`
        )
      );
    });
    if (child.stdin) {
      child.stdin.on("error", reject);
      child.stdin.write(text);
      child.stdin.end();
    } else {
      reject(new Error("Child process has no stdin stream to write to."));
    }
  }), "run");
  const linuxOptions = { stdio: ["pipe", "inherit", "pipe"] };
  switch (process.platform) {
    case "win32":
      return run("cmd", ["/c", `chcp ${CodePage.UTF8} >nul && clip`]);
    case "darwin":
      return run("pbcopy", []);
    case "linux":
      try {
        await run("xclip", ["-selection", "clipboard"], linuxOptions);
      } catch (primaryError) {
        try {
          await run("xsel", ["--clipboard", "--input"], linuxOptions);
        } catch (fallbackError) {
          const xclipNotFound = primaryError instanceof Error && primaryError.code === "ENOENT";
          const xselNotFound = fallbackError instanceof Error && fallbackError.code === "ENOENT";
          if (xclipNotFound && xselNotFound) {
            throw new Error(
              "Please ensure xclip or xsel is installed and configured."
            );
          }
          let primaryMsg = primaryError instanceof Error ? primaryError.message : String(primaryError);
          if (xclipNotFound) {
            primaryMsg = `xclip not found`;
          }
          let fallbackMsg = fallbackError instanceof Error ? fallbackError.message : String(fallbackError);
          if (xselNotFound) {
            fallbackMsg = `xsel not found`;
          }
          throw new Error(
            `All copy commands failed. "${primaryMsg}", "${fallbackMsg}". `
          );
        }
      }
      return;
    default:
      throw new Error(`Unsupported platform: ${process.platform}`);
  }
}, "copyToClipboard");
var getUrlOpenCommand = /* @__PURE__ */ __name(() => {
  let openCmd;
  switch (process.platform) {
    case "darwin":
      openCmd = "open";
      break;
    case "win32":
      openCmd = "start";
      break;
    case "linux":
      openCmd = "xdg-open";
      break;
    default:
      openCmd = "xdg-open";
      console.warn(
        `Unknown platform: ${process.platform}. Attempting to open URLs with: ${openCmd}.`
      );
      break;
  }
  return openCmd;
}, "getUrlOpenCommand");

// packages/cli/src/ui/components/messages/UserMessage.tsx
var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
var UserMessage = /* @__PURE__ */ __name(({ text }) => {
  const prefix = "> ";
  const prefixWidth = prefix.length;
  const isSlashCommand2 = isSlashCommand(text);
  const textColor = isSlashCommand2 ? theme.text.accent : theme.text.secondary;
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Box_default, { flexDirection: "row", paddingY: 0, marginY: 1, alignSelf: "flex-start", children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: theme.text.accent, "aria-label": SCREEN_READER_USER_PREFIX, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { wrap: "wrap", color: textColor, children: text }) })
  ] });
}, "UserMessage");

// packages/cli/src/ui/components/messages/UserShellMessage.tsx
init_esbuild_shims();
var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
var UserShellMessage = /* @__PURE__ */ __name(({ text }) => {
  const commandToDisplay = text.startsWith("!") ? text.substring(1) : text;
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(Box_default, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Text, { color: theme.text.link, children: "$ " }),
    /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Text, { color: theme.text.primary, children: commandToDisplay })
  ] });
}, "UserShellMessage");

// packages/cli/src/ui/components/messages/GeminiMessage.tsx
init_esbuild_shims();

// packages/cli/src/ui/utils/MarkdownDisplay.tsx
init_esbuild_shims();
var import_react37 = __toESM(require_react(), 1);

// packages/cli/src/ui/utils/CodeColorizer.tsx
init_esbuild_shims();
var import_react34 = __toESM(require_react(), 1);

// node_modules/lowlight/index.js
init_esbuild_shims();

// node_modules/lowlight/lib/common.js
init_esbuild_shims();

// node_modules/highlight.js/es/languages/arduino.js
init_esbuild_shims();
function cPlusPlus(hljs) {
  const regex3 = hljs.regex;
  const C_LINE_COMMENT_MODE = hljs.COMMENT("//", "$", { contains: [{ begin: /\\\n/ }] });
  const DECLTYPE_AUTO_RE = "decltype\\(auto\\)";
  const NAMESPACE_RE = "[a-zA-Z_]\\w*::";
  const TEMPLATE_ARGUMENT_RE = "<[^<>]+>";
  const FUNCTION_TYPE_RE = "(?!struct)(" + DECLTYPE_AUTO_RE + "|" + regex3.optional(NAMESPACE_RE) + "[a-zA-Z_]\\w*" + regex3.optional(TEMPLATE_ARGUMENT_RE) + ")";
  const CPP_PRIMITIVE_TYPES = {
    className: "type",
    begin: "\\b[a-z\\d_]*_t\\b"
  };
  const CHARACTER_ESCAPES = "\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)";
  const STRINGS = {
    className: "string",
    variants: [
      {
        begin: '(u8?|U|L)?"',
        end: '"',
        illegal: "\\n",
        contains: [hljs.BACKSLASH_ESCAPE]
      },
      {
        begin: "(u8?|U|L)?'(" + CHARACTER_ESCAPES + "|.)",
        end: "'",
        illegal: "."
      },
      hljs.END_SAME_AS_BEGIN({
        begin: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,
        end: /\)([^()\\ ]{0,16})"/
      })
    ]
  };
  const NUMBERS = {
    className: "number",
    variants: [
      // Floating-point literal.
      {
        begin: "[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"
      },
      // Integer literal.
      {
        begin: "[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"
        // Note: there are user-defined literal suffixes too, but perhaps having the custom suffix not part of the
        // literal highlight actually makes it stand out more.
      }
    ],
    relevance: 0
  };
  const PREPROCESSOR = {
    className: "meta",
    begin: /#\s*[a-z]+\b/,
    end: /$/,
    keywords: { keyword: "if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include" },
    contains: [
      {
        begin: /\\\n/,
        relevance: 0
      },
      hljs.inherit(STRINGS, { className: "string" }),
      {
        className: "string",
        begin: /<.*?>/
      },
      C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE
    ]
  };
  const TITLE_MODE = {
    className: "title",
    begin: regex3.optional(NAMESPACE_RE) + hljs.IDENT_RE,
    relevance: 0
  };
  const FUNCTION_TITLE = regex3.optional(NAMESPACE_RE) + hljs.IDENT_RE + "\\s*\\(";
  const RESERVED_KEYWORDS = [
    "alignas",
    "alignof",
    "and",
    "and_eq",
    "asm",
    "atomic_cancel",
    "atomic_commit",
    "atomic_noexcept",
    "auto",
    "bitand",
    "bitor",
    "break",
    "case",
    "catch",
    "class",
    "co_await",
    "co_return",
    "co_yield",
    "compl",
    "concept",
    "const_cast|10",
    "consteval",
    "constexpr",
    "constinit",
    "continue",
    "decltype",
    "default",
    "delete",
    "do",
    "dynamic_cast|10",
    "else",
    "enum",
    "explicit",
    "export",
    "extern",
    "false",
    "final",
    "for",
    "friend",
    "goto",
    "if",
    "import",
    "inline",
    "module",
    "mutable",
    "namespace",
    "new",
    "noexcept",
    "not",
    "not_eq",
    "nullptr",
    "operator",
    "or",
    "or_eq",
    "override",
    "private",
    "protected",
    "public",
    "reflexpr",
    "register",
    "reinterpret_cast|10",
    "requires",
    "return",
    "sizeof",
    "static_assert",
    "static_cast|10",
    "struct",
    "switch",
    "synchronized",
    "template",
    "this",
    "thread_local",
    "throw",
    "transaction_safe",
    "transaction_safe_dynamic",
    "true",
    "try",
    "typedef",
    "typeid",
    "typename",
    "union",
    "using",
    "virtual",
    "volatile",
    "while",
    "xor",
    "xor_eq"
  ];
  const RESERVED_TYPES = [
    "bool",
    "char",
    "char16_t",
    "char32_t",
    "char8_t",
    "double",
    "float",
    "int",
    "long",
    "short",
    "void",
    "wchar_t",
    "unsigned",
    "signed",
    "const",
    "static"
  ];
  const TYPE_HINTS = [
    "any",
    "auto_ptr",
    "barrier",
    "binary_semaphore",
    "bitset",
    "complex",
    "condition_variable",
    "condition_variable_any",
    "counting_semaphore",
    "deque",
    "false_type",
    "flat_map",
    "flat_set",
    "future",
    "imaginary",
    "initializer_list",
    "istringstream",
    "jthread",
    "latch",
    "lock_guard",
    "multimap",
    "multiset",
    "mutex",
    "optional",
    "ostringstream",
    "packaged_task",
    "pair",
    "promise",
    "priority_queue",
    "queue",
    "recursive_mutex",
    "recursive_timed_mutex",
    "scoped_lock",
    "set",
    "shared_future",
    "shared_lock",
    "shared_mutex",
    "shared_timed_mutex",
    "shared_ptr",
    "stack",
    "string_view",
    "stringstream",
    "timed_mutex",
    "thread",
    "true_type",
    "tuple",
    "unique_lock",
    "unique_ptr",
    "unordered_map",
    "unordered_multimap",
    "unordered_multiset",
    "unordered_set",
    "variant",
    "vector",
    "weak_ptr",
    "wstring",
    "wstring_view"
  ];
  const FUNCTION_HINTS = [
    "abort",
    "abs",
    "acos",
    "apply",
    "as_const",
    "asin",
    "atan",
    "atan2",
    "calloc",
    "ceil",
    "cerr",
    "cin",
    "clog",
    "cos",
    "cosh",
    "cout",
    "declval",
    "endl",
    "exchange",
    "exit",
    "exp",
    "fabs",
    "floor",
    "fmod",
    "forward",
    "fprintf",
    "fputs",
    "free",
    "frexp",
    "fscanf",
    "future",
    "invoke",
    "isalnum",
    "isalpha",
    "iscntrl",
    "isdigit",
    "isgraph",
    "islower",
    "isprint",
    "ispunct",
    "isspace",
    "isupper",
    "isxdigit",
    "labs",
    "launder",
    "ldexp",
    "log",
    "log10",
    "make_pair",
    "make_shared",
    "make_shared_for_overwrite",
    "make_tuple",
    "make_unique",
    "malloc",
    "memchr",
    "memcmp",
    "memcpy",
    "memset",
    "modf",
    "move",
    "pow",
    "printf",
    "putchar",
    "puts",
    "realloc",
    "scanf",
    "sin",
    "sinh",
    "snprintf",
    "sprintf",
    "sqrt",
    "sscanf",
    "std",
    "stderr",
    "stdin",
    "stdout",
    "strcat",
    "strchr",
    "strcmp",
    "strcpy",
    "strcspn",
    "strlen",
    "strncat",
    "strncmp",
    "strncpy",
    "strpbrk",
    "strrchr",
    "strspn",
    "strstr",
    "swap",
    "tan",
    "tanh",
    "terminate",
    "to_underlying",
    "tolower",
    "toupper",
    "vfprintf",
    "visit",
    "vprintf",
    "vsprintf"
  ];
  const LITERALS3 = [
    "NULL",
    "false",
    "nullopt",
    "nullptr",
    "true"
  ];
  const BUILT_IN = ["_Pragma"];
  const CPP_KEYWORDS = {
    type: RESERVED_TYPES,
    keyword: RESERVED_KEYWORDS,
    literal: LITERALS3,
    built_in: BUILT_IN,
    _type_hints: TYPE_HINTS
  };
  const FUNCTION_DISPATCH = {
    className: "function.dispatch",
    relevance: 0,
    keywords: {
      // Only for relevance, not highlighting.
      _hint: FUNCTION_HINTS
    },
    begin: regex3.concat(
      /\b/,
      /(?!decltype)/,
      /(?!if)/,
      /(?!for)/,
      /(?!switch)/,
      /(?!while)/,
      hljs.IDENT_RE,
      regex3.lookahead(/(<[^<>]+>|)\s*\(/)
    )
  };
  const EXPRESSION_CONTAINS = [
    FUNCTION_DISPATCH,
    PREPROCESSOR,
    CPP_PRIMITIVE_TYPES,
    C_LINE_COMMENT_MODE,
    hljs.C_BLOCK_COMMENT_MODE,
    NUMBERS,
    STRINGS
  ];
  const EXPRESSION_CONTEXT = {
    // This mode covers expression context where we can't expect a function
    // definition and shouldn't highlight anything that looks like one:
    // `return some()`, `else if()`, `(x*sum(1, 2))`
    variants: [
      {
        begin: /=/,
        end: /;/
      },
      {
        begin: /\(/,
        end: /\)/
      },
      {
        beginKeywords: "new throw return else",
        end: /;/
      }
    ],
    keywords: CPP_KEYWORDS,
    contains: EXPRESSION_CONTAINS.concat([
      {
        begin: /\(/,
        end: /\)/,
        keywords: CPP_KEYWORDS,
        contains: EXPRESSION_CONTAINS.concat(["self"]),
        relevance: 0
      }
    ]),
    relevance: 0
  };
  const FUNCTION_DECLARATION = {
    className: "function",
    begin: "(" + FUNCTION_TYPE_RE + "[\\*&\\s]+)+" + FUNCTION_TITLE,
    returnBegin: true,
    end: /[{;=]/,
    excludeEnd: true,
    keywords: CPP_KEYWORDS,
    illegal: /[^\w\s\*&:<>.]/,
    contains: [
      {
        // to prevent it from being confused as the function title
        begin: DECLTYPE_AUTO_RE,
        keywords: CPP_KEYWORDS,
        relevance: 0
      },
      {
        begin: FUNCTION_TITLE,
        returnBegin: true,
        contains: [TITLE_MODE],
        relevance: 0
      },
      // needed because we do not have look-behind on the below rule
      // to prevent it from grabbing the final : in a :: pair
      {
        begin: /::/,
        relevance: 0
      },
      // initializers
      {
        begin: /:/,
        endsWithParent: true,
        contains: [
          STRINGS,
          NUMBERS
        ]
      },
      // allow for multiple declarations, e.g.:
      // extern void f(int), g(char);
      {
        relevance: 0,
        match: /,/
      },
      {
        className: "params",
        begin: /\(/,
        end: /\)/,
        keywords: CPP_KEYWORDS,
        relevance: 0,
        contains: [
          C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE,
          STRINGS,
          NUMBERS,
          CPP_PRIMITIVE_TYPES,
          // Count matching parentheses.
          {
            begin: /\(/,
            end: /\)/,
            keywords: CPP_KEYWORDS,
            relevance: 0,
            contains: [
              "self",
              C_LINE_COMMENT_MODE,
              hljs.C_BLOCK_COMMENT_MODE,
              STRINGS,
              NUMBERS,
              CPP_PRIMITIVE_TYPES
            ]
          }
        ]
      },
      CPP_PRIMITIVE_TYPES,
      C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      PREPROCESSOR
    ]
  };
  return {
    name: "C++",
    aliases: [
      "cc",
      "c++",
      "h++",
      "hpp",
      "hh",
      "hxx",
      "cxx"
    ],
    keywords: CPP_KEYWORDS,
    illegal: "</",
    classNameAliases: { "function.dispatch": "built_in" },
    contains: [].concat(
      EXPRESSION_CONTEXT,
      FUNCTION_DECLARATION,
      FUNCTION_DISPATCH,
      EXPRESSION_CONTAINS,
      [
        PREPROCESSOR,
        {
          // containers: ie, `vector <int> rooms (9);`
          begin: "\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",
          end: ">",
          keywords: CPP_KEYWORDS,
          contains: [
            "self",
            CPP_PRIMITIVE_TYPES
          ]
        },
        {
          begin: hljs.IDENT_RE + "::",
          keywords: CPP_KEYWORDS
        },
        {
          match: [
            // extra complexity to deal with `enum class` and `enum struct`
            /\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,
            /\s+/,
            /\w+/
          ],
          className: {
            1: "keyword",
            3: "title.class"
          }
        }
      ]
    )
  };
}
__name(cPlusPlus, "cPlusPlus");
function arduino(hljs) {
  const ARDUINO_KW = {
    type: [
      "boolean",
      "byte",
      "word",
      "String"
    ],
    built_in: [
      "KeyboardController",
      "MouseController",
      "SoftwareSerial",
      "EthernetServer",
      "EthernetClient",
      "LiquidCrystal",
      "RobotControl",
      "GSMVoiceCall",
      "EthernetUDP",
      "EsploraTFT",
      "HttpClient",
      "RobotMotor",
      "WiFiClient",
      "GSMScanner",
      "FileSystem",
      "Scheduler",
      "GSMServer",
      "YunClient",
      "YunServer",
      "IPAddress",
      "GSMClient",
      "GSMModem",
      "Keyboard",
      "Ethernet",
      "Console",
      "GSMBand",
      "Esplora",
      "Stepper",
      "Process",
      "WiFiUDP",
      "GSM_SMS",
      "Mailbox",
      "USBHost",
      "Firmata",
      "PImage",
      "Client",
      "Server",
      "GSMPIN",
      "FileIO",
      "Bridge",
      "Serial",
      "EEPROM",
      "Stream",
      "Mouse",
      "Audio",
      "Servo",
      "File",
      "Task",
      "GPRS",
      "WiFi",
      "Wire",
      "TFT",
      "GSM",
      "SPI",
      "SD"
    ],
    _hints: [
      "setup",
      "loop",
      "runShellCommandAsynchronously",
      "analogWriteResolution",
      "retrieveCallingNumber",
      "printFirmwareVersion",
      "analogReadResolution",
      "sendDigitalPortPair",
      "noListenOnLocalhost",
      "readJoystickButton",
      "setFirmwareVersion",
      "readJoystickSwitch",
      "scrollDisplayRight",
      "getVoiceCallStatus",
      "scrollDisplayLeft",
      "writeMicroseconds",
      "delayMicroseconds",
      "beginTransmission",
      "getSignalStrength",
      "runAsynchronously",
      "getAsynchronously",
      "listenOnLocalhost",
      "getCurrentCarrier",
      "readAccelerometer",
      "messageAvailable",
      "sendDigitalPorts",
      "lineFollowConfig",
      "countryNameWrite",
      "runShellCommand",
      "readStringUntil",
      "rewindDirectory",
      "readTemperature",
      "setClockDivider",
      "readLightSensor",
      "endTransmission",
      "analogReference",
      "detachInterrupt",
      "countryNameRead",
      "attachInterrupt",
      "encryptionType",
      "readBytesUntil",
      "robotNameWrite",
      "readMicrophone",
      "robotNameRead",
      "cityNameWrite",
      "userNameWrite",
      "readJoystickY",
      "readJoystickX",
      "mouseReleased",
      "openNextFile",
      "scanNetworks",
      "noInterrupts",
      "digitalWrite",
      "beginSpeaker",
      "mousePressed",
      "isActionDone",
      "mouseDragged",
      "displayLogos",
      "noAutoscroll",
      "addParameter",
      "remoteNumber",
      "getModifiers",
      "keyboardRead",
      "userNameRead",
      "waitContinue",
      "processInput",
      "parseCommand",
      "printVersion",
      "readNetworks",
      "writeMessage",
      "blinkVersion",
      "cityNameRead",
      "readMessage",
      "setDataMode",
      "parsePacket",
      "isListening",
      "setBitOrder",
      "beginPacket",
      "isDirectory",
      "motorsWrite",
      "drawCompass",
      "digitalRead",
      "clearScreen",
      "serialEvent",
      "rightToLeft",
      "setTextSize",
      "leftToRight",
      "requestFrom",
      "keyReleased",
      "compassRead",
      "analogWrite",
      "interrupts",
      "WiFiServer",
      "disconnect",
      "playMelody",
      "parseFloat",
      "autoscroll",
      "getPINUsed",
      "setPINUsed",
      "setTimeout",
      "sendAnalog",
      "readSlider",
      "analogRead",
      "beginWrite",
      "createChar",
      "motorsStop",
      "keyPressed",
      "tempoWrite",
      "readButton",
      "subnetMask",
      "debugPrint",
      "macAddress",
      "writeGreen",
      "randomSeed",
      "attachGPRS",
      "readString",
      "sendString",
      "remotePort",
      "releaseAll",
      "mouseMoved",
      "background",
      "getXChange",
      "getYChange",
      "answerCall",
      "getResult",
      "voiceCall",
      "endPacket",
      "constrain",
      "getSocket",
      "writeJSON",
      "getButton",
      "available",
      "connected",
      "findUntil",
      "readBytes",
      "exitValue",
      "readGreen",
      "writeBlue",
      "startLoop",
      "IPAddress",
      "isPressed",
      "sendSysex",
      "pauseMode",
      "gatewayIP",
      "setCursor",
      "getOemKey",
      "tuneWrite",
      "noDisplay",
      "loadImage",
      "switchPIN",
      "onRequest",
      "onReceive",
      "changePIN",
      "playFile",
      "noBuffer",
      "parseInt",
      "overflow",
      "checkPIN",
      "knobRead",
      "beginTFT",
      "bitClear",
      "updateIR",
      "bitWrite",
      "position",
      "writeRGB",
      "highByte",
      "writeRed",
      "setSpeed",
      "readBlue",
      "noStroke",
      "remoteIP",
      "transfer",
      "shutdown",
      "hangCall",
      "beginSMS",
      "endWrite",
      "attached",
      "maintain",
      "noCursor",
      "checkReg",
      "checkPUK",
      "shiftOut",
      "isValid",
      "shiftIn",
      "pulseIn",
      "connect",
      "println",
      "localIP",
      "pinMode",
      "getIMEI",
      "display",
      "noBlink",
      "process",
      "getBand",
      "running",
      "beginSD",
      "drawBMP",
      "lowByte",
      "setBand",
      "release",
      "bitRead",
      "prepare",
      "pointTo",
      "readRed",
      "setMode",
      "noFill",
      "remove",
      "listen",
      "stroke",
      "detach",
      "attach",
      "noTone",
      "exists",
      "buffer",
      "height",
      "bitSet",
      "circle",
      "config",
      "cursor",
      "random",
      "IRread",
      "setDNS",
      "endSMS",
      "getKey",
      "micros",
      "millis",
      "begin",
      "print",
      "write",
      "ready",
      "flush",
      "width",
      "isPIN",
      "blink",
      "clear",
      "press",
      "mkdir",
      "rmdir",
      "close",
      "point",
      "yield",
      "image",
      "BSSID",
      "click",
      "delay",
      "read",
      "text",
      "move",
      "peek",
      "beep",
      "rect",
      "line",
      "open",
      "seek",
      "fill",
      "size",
      "turn",
      "stop",
      "home",
      "find",
      "step",
      "tone",
      "sqrt",
      "RSSI",
      "SSID",
      "end",
      "bit",
      "tan",
      "cos",
      "sin",
      "pow",
      "map",
      "abs",
      "max",
      "min",
      "get",
      "run",
      "put"
    ],
    literal: [
      "DIGITAL_MESSAGE",
      "FIRMATA_STRING",
      "ANALOG_MESSAGE",
      "REPORT_DIGITAL",
      "REPORT_ANALOG",
      "INPUT_PULLUP",
      "SET_PIN_MODE",
      "INTERNAL2V56",
      "SYSTEM_RESET",
      "LED_BUILTIN",
      "INTERNAL1V1",
      "SYSEX_START",
      "INTERNAL",
      "EXTERNAL",
      "DEFAULT",
      "OUTPUT",
      "INPUT",
      "HIGH",
      "LOW"
    ]
  };
  const ARDUINO = cPlusPlus(hljs);
  const kws = (
    /** @type {Record<string,any>} */
    ARDUINO.keywords
  );
  kws.type = [
    ...kws.type,
    ...ARDUINO_KW.type
  ];
  kws.literal = [
    ...kws.literal,
    ...ARDUINO_KW.literal
  ];
  kws.built_in = [
    ...kws.built_in,
    ...ARDUINO_KW.built_in
  ];
  kws._hints = ARDUINO_KW._hints;
  ARDUINO.name = "Arduino";
  ARDUINO.aliases = ["ino"];
  ARDUINO.supersetOf = "cpp";
  return ARDUINO;
}
__name(arduino, "arduino");

// node_modules/highlight.js/es/languages/bash.js
init_esbuild_shims();
function bash(hljs) {
  const regex3 = hljs.regex;
  const VAR = {};
  const BRACED_VAR = {
    begin: /\$\{/,
    end: /\}/,
    contains: [
      "self",
      {
        begin: /:-/,
        contains: [VAR]
      }
      // default values
    ]
  };
  Object.assign(VAR, {
    className: "variable",
    variants: [
      { begin: regex3.concat(
        /\$[\w\d#@][\w\d_]*/,
        // negative look-ahead tries to avoid matching patterns that are not
        // Perl at all like $ident$, @ident@, etc.
        `(?![\\w\\d])(?![$])`
      ) },
      BRACED_VAR
    ]
  });
  const SUBST = {
    className: "subst",
    begin: /\$\(/,
    end: /\)/,
    contains: [hljs.BACKSLASH_ESCAPE]
  };
  const COMMENT = hljs.inherit(
    hljs.COMMENT(),
    {
      match: [
        /(^|\s)/,
        /#.*$/
      ],
      scope: {
        2: "comment"
      }
    }
  );
  const HERE_DOC = {
    begin: /<<-?\s*(?=\w+)/,
    starts: { contains: [
      hljs.END_SAME_AS_BEGIN({
        begin: /(\w+)/,
        end: /(\w+)/,
        className: "string"
      })
    ] }
  };
  const QUOTE_STRING = {
    className: "string",
    begin: /"/,
    end: /"/,
    contains: [
      hljs.BACKSLASH_ESCAPE,
      VAR,
      SUBST
    ]
  };
  SUBST.contains.push(QUOTE_STRING);
  const ESCAPED_QUOTE = {
    match: /\\"/
  };
  const APOS_STRING = {
    className: "string",
    begin: /'/,
    end: /'/
  };
  const ESCAPED_APOS = {
    match: /\\'/
  };
  const ARITHMETIC = {
    begin: /\$?\(\(/,
    end: /\)\)/,
    contains: [
      {
        begin: /\d+#[0-9a-f]+/,
        className: "number"
      },
      hljs.NUMBER_MODE,
      VAR
    ]
  };
  const SH_LIKE_SHELLS = [
    "fish",
    "bash",
    "zsh",
    "sh",
    "csh",
    "ksh",
    "tcsh",
    "dash",
    "scsh"
  ];
  const KNOWN_SHEBANG = hljs.SHEBANG({
    binary: `(${SH_LIKE_SHELLS.join("|")})`,
    relevance: 10
  });
  const FUNCTION = {
    className: "function",
    begin: /\w[\w\d_]*\s*\(\s*\)\s*\{/,
    returnBegin: true,
    contains: [hljs.inherit(hljs.TITLE_MODE, { begin: /\w[\w\d_]*/ })],
    relevance: 0
  };
  const KEYWORDS3 = [
    "if",
    "then",
    "else",
    "elif",
    "fi",
    "time",
    "for",
    "while",
    "until",
    "in",
    "do",
    "done",
    "case",
    "esac",
    "coproc",
    "function",
    "select"
  ];
  const LITERALS3 = [
    "true",
    "false"
  ];
  const PATH_MODE = { match: /(\/[a-z._-]+)+/ };
  const SHELL_BUILT_INS = [
    "break",
    "cd",
    "continue",
    "eval",
    "exec",
    "exit",
    "export",
    "getopts",
    "hash",
    "pwd",
    "readonly",
    "return",
    "shift",
    "test",
    "times",
    "trap",
    "umask",
    "unset"
  ];
  const BASH_BUILT_INS = [
    "alias",
    "bind",
    "builtin",
    "caller",
    "command",
    "declare",
    "echo",
    "enable",
    "help",
    "let",
    "local",
    "logout",
    "mapfile",
    "printf",
    "read",
    "readarray",
    "source",
    "sudo",
    "type",
    "typeset",
    "ulimit",
    "unalias"
  ];
  const ZSH_BUILT_INS = [
    "autoload",
    "bg",
    "bindkey",
    "bye",
    "cap",
    "chdir",
    "clone",
    "comparguments",
    "compcall",
    "compctl",
    "compdescribe",
    "compfiles",
    "compgroups",
    "compquote",
    "comptags",
    "comptry",
    "compvalues",
    "dirs",
    "disable",
    "disown",
    "echotc",
    "echoti",
    "emulate",
    "fc",
    "fg",
    "float",
    "functions",
    "getcap",
    "getln",
    "history",
    "integer",
    "jobs",
    "kill",
    "limit",
    "log",
    "noglob",
    "popd",
    "print",
    "pushd",
    "pushln",
    "rehash",
    "sched",
    "setcap",
    "setopt",
    "stat",
    "suspend",
    "ttyctl",
    "unfunction",
    "unhash",
    "unlimit",
    "unsetopt",
    "vared",
    "wait",
    "whence",
    "where",
    "which",
    "zcompile",
    "zformat",
    "zftp",
    "zle",
    "zmodload",
    "zparseopts",
    "zprof",
    "zpty",
    "zregexparse",
    "zsocket",
    "zstyle",
    "ztcp"
  ];
  const GNU_CORE_UTILS = [
    "chcon",
    "chgrp",
    "chown",
    "chmod",
    "cp",
    "dd",
    "df",
    "dir",
    "dircolors",
    "ln",
    "ls",
    "mkdir",
    "mkfifo",
    "mknod",
    "mktemp",
    "mv",
    "realpath",
    "rm",
    "rmdir",
    "shred",
    "sync",
    "touch",
    "truncate",
    "vdir",
    "b2sum",
    "base32",
    "base64",
    "cat",
    "cksum",
    "comm",
    "csplit",
    "cut",
    "expand",
    "fmt",
    "fold",
    "head",
    "join",
    "md5sum",
    "nl",
    "numfmt",
    "od",
    "paste",
    "ptx",
    "pr",
    "sha1sum",
    "sha224sum",
    "sha256sum",
    "sha384sum",
    "sha512sum",
    "shuf",
    "sort",
    "split",
    "sum",
    "tac",
    "tail",
    "tr",
    "tsort",
    "unexpand",
    "uniq",
    "wc",
    "arch",
    "basename",
    "chroot",
    "date",
    "dirname",
    "du",
    "echo",
    "env",
    "expr",
    "factor",
    // "false", // keyword literal already
    "groups",
    "hostid",
    "id",
    "link",
    "logname",
    "nice",
    "nohup",
    "nproc",
    "pathchk",
    "pinky",
    "printenv",
    "printf",
    "pwd",
    "readlink",
    "runcon",
    "seq",
    "sleep",
    "stat",
    "stdbuf",
    "stty",
    "tee",
    "test",
    "timeout",
    // "true", // keyword literal already
    "tty",
    "uname",
    "unlink",
    "uptime",
    "users",
    "who",
    "whoami",
    "yes"
  ];
  return {
    name: "Bash",
    aliases: [
      "sh",
      "zsh"
    ],
    keywords: {
      $pattern: /\b[a-z][a-z0-9._-]+\b/,
      keyword: KEYWORDS3,
      literal: LITERALS3,
      built_in: [
        ...SHELL_BUILT_INS,
        ...BASH_BUILT_INS,
        // Shell modifiers
        "set",
        "shopt",
        ...ZSH_BUILT_INS,
        ...GNU_CORE_UTILS
      ]
    },
    contains: [
      KNOWN_SHEBANG,
      // to catch known shells and boost relevancy
      hljs.SHEBANG(),
      // to catch unknown shells but still highlight the shebang
      FUNCTION,
      ARITHMETIC,
      COMMENT,
      HERE_DOC,
      PATH_MODE,
      QUOTE_STRING,
      ESCAPED_QUOTE,
      APOS_STRING,
      ESCAPED_APOS,
      VAR
    ]
  };
}
__name(bash, "bash");

// node_modules/highlight.js/es/languages/c.js
init_esbuild_shims();
function c2(hljs) {
  const regex3 = hljs.regex;
  const C_LINE_COMMENT_MODE = hljs.COMMENT("//", "$", { contains: [{ begin: /\\\n/ }] });
  const DECLTYPE_AUTO_RE = "decltype\\(auto\\)";
  const NAMESPACE_RE = "[a-zA-Z_]\\w*::";
  const TEMPLATE_ARGUMENT_RE = "<[^<>]+>";
  const FUNCTION_TYPE_RE = "(" + DECLTYPE_AUTO_RE + "|" + regex3.optional(NAMESPACE_RE) + "[a-zA-Z_]\\w*" + regex3.optional(TEMPLATE_ARGUMENT_RE) + ")";
  const TYPES3 = {
    className: "type",
    variants: [
      { begin: "\\b[a-z\\d_]*_t\\b" },
      { match: /\batomic_[a-z]{3,6}\b/ }
    ]
  };
  const CHARACTER_ESCAPES = "\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)";
  const STRINGS = {
    className: "string",
    variants: [
      {
        begin: '(u8?|U|L)?"',
        end: '"',
        illegal: "\\n",
        contains: [hljs.BACKSLASH_ESCAPE]
      },
      {
        begin: "(u8?|U|L)?'(" + CHARACTER_ESCAPES + "|.)",
        end: "'",
        illegal: "."
      },
      hljs.END_SAME_AS_BEGIN({
        begin: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,
        end: /\)([^()\\ ]{0,16})"/
      })
    ]
  };
  const NUMBERS = {
    className: "number",
    variants: [
      { match: /\b(0b[01']+)/ },
      { match: /(-?)\b([\d']+(\.[\d']*)?|\.[\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)/ },
      { match: /(-?)\b(0[xX][a-fA-F0-9]+(?:'[a-fA-F0-9]+)*(?:\.[a-fA-F0-9]*(?:'[a-fA-F0-9]*)*)?(?:[pP][-+]?[0-9]+)?(l|L)?(u|U)?)/ },
      { match: /(-?)\b\d+(?:'\d+)*(?:\.\d*(?:'\d*)*)?(?:[eE][-+]?\d+)?/ }
    ],
    relevance: 0
  };
  const PREPROCESSOR = {
    className: "meta",
    begin: /#\s*[a-z]+\b/,
    end: /$/,
    keywords: { keyword: "if else elif endif define undef warning error line pragma _Pragma ifdef ifndef elifdef elifndef include" },
    contains: [
      {
        begin: /\\\n/,
        relevance: 0
      },
      hljs.inherit(STRINGS, { className: "string" }),
      {
        className: "string",
        begin: /<.*?>/
      },
      C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE
    ]
  };
  const TITLE_MODE = {
    className: "title",
    begin: regex3.optional(NAMESPACE_RE) + hljs.IDENT_RE,
    relevance: 0
  };
  const FUNCTION_TITLE = regex3.optional(NAMESPACE_RE) + hljs.IDENT_RE + "\\s*\\(";
  const C_KEYWORDS = [
    "asm",
    "auto",
    "break",
    "case",
    "continue",
    "default",
    "do",
    "else",
    "enum",
    "extern",
    "for",
    "fortran",
    "goto",
    "if",
    "inline",
    "register",
    "restrict",
    "return",
    "sizeof",
    "typeof",
    "typeof_unqual",
    "struct",
    "switch",
    "typedef",
    "union",
    "volatile",
    "while",
    "_Alignas",
    "_Alignof",
    "_Atomic",
    "_Generic",
    "_Noreturn",
    "_Static_assert",
    "_Thread_local",
    // aliases
    "alignas",
    "alignof",
    "noreturn",
    "static_assert",
    "thread_local",
    // not a C keyword but is, for all intents and purposes, treated exactly like one.
    "_Pragma"
  ];
  const C_TYPES = [
    "float",
    "double",
    "signed",
    "unsigned",
    "int",
    "short",
    "long",
    "char",
    "void",
    "_Bool",
    "_BitInt",
    "_Complex",
    "_Imaginary",
    "_Decimal32",
    "_Decimal64",
    "_Decimal96",
    "_Decimal128",
    "_Decimal64x",
    "_Decimal128x",
    "_Float16",
    "_Float32",
    "_Float64",
    "_Float128",
    "_Float32x",
    "_Float64x",
    "_Float128x",
    // modifiers
    "const",
    "static",
    "constexpr",
    // aliases
    "complex",
    "bool",
    "imaginary"
  ];
  const KEYWORDS3 = {
    keyword: C_KEYWORDS,
    type: C_TYPES,
    literal: "true false NULL",
    // TODO: apply hinting work similar to what was done in cpp.js
    built_in: "std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr"
  };
  const EXPRESSION_CONTAINS = [
    PREPROCESSOR,
    TYPES3,
    C_LINE_COMMENT_MODE,
    hljs.C_BLOCK_COMMENT_MODE,
    NUMBERS,
    STRINGS
  ];
  const EXPRESSION_CONTEXT = {
    // This mode covers expression context where we can't expect a function
    // definition and shouldn't highlight anything that looks like one:
    // `return some()`, `else if()`, `(x*sum(1, 2))`
    variants: [
      {
        begin: /=/,
        end: /;/
      },
      {
        begin: /\(/,
        end: /\)/
      },
      {
        beginKeywords: "new throw return else",
        end: /;/
      }
    ],
    keywords: KEYWORDS3,
    contains: EXPRESSION_CONTAINS.concat([
      {
        begin: /\(/,
        end: /\)/,
        keywords: KEYWORDS3,
        contains: EXPRESSION_CONTAINS.concat(["self"]),
        relevance: 0
      }
    ]),
    relevance: 0
  };
  const FUNCTION_DECLARATION = {
    begin: "(" + FUNCTION_TYPE_RE + "[\\*&\\s]+)+" + FUNCTION_TITLE,
    returnBegin: true,
    end: /[{;=]/,
    excludeEnd: true,
    keywords: KEYWORDS3,
    illegal: /[^\w\s\*&:<>.]/,
    contains: [
      {
        // to prevent it from being confused as the function title
        begin: DECLTYPE_AUTO_RE,
        keywords: KEYWORDS3,
        relevance: 0
      },
      {
        begin: FUNCTION_TITLE,
        returnBegin: true,
        contains: [hljs.inherit(TITLE_MODE, { className: "title.function" })],
        relevance: 0
      },
      // allow for multiple declarations, e.g.:
      // extern void f(int), g(char);
      {
        relevance: 0,
        match: /,/
      },
      {
        className: "params",
        begin: /\(/,
        end: /\)/,
        keywords: KEYWORDS3,
        relevance: 0,
        contains: [
          C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE,
          STRINGS,
          NUMBERS,
          TYPES3,
          // Count matching parentheses.
          {
            begin: /\(/,
            end: /\)/,
            keywords: KEYWORDS3,
            relevance: 0,
            contains: [
              "self",
              C_LINE_COMMENT_MODE,
              hljs.C_BLOCK_COMMENT_MODE,
              STRINGS,
              NUMBERS,
              TYPES3
            ]
          }
        ]
      },
      TYPES3,
      C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      PREPROCESSOR
    ]
  };
  return {
    name: "C",
    aliases: ["h"],
    keywords: KEYWORDS3,
    // Until differentiations are added between `c` and `cpp`, `c` will
    // not be auto-detected to avoid auto-detect conflicts between C and C++
    disableAutodetect: true,
    illegal: "</",
    contains: [].concat(
      EXPRESSION_CONTEXT,
      FUNCTION_DECLARATION,
      EXPRESSION_CONTAINS,
      [
        PREPROCESSOR,
        {
          begin: hljs.IDENT_RE + "::",
          keywords: KEYWORDS3
        },
        {
          className: "class",
          beginKeywords: "enum class struct union",
          end: /[{;:<>=]/,
          contains: [
            { beginKeywords: "final class struct" },
            hljs.TITLE_MODE
          ]
        }
      ]
    ),
    exports: {
      preprocessor: PREPROCESSOR,
      strings: STRINGS,
      keywords: KEYWORDS3
    }
  };
}
__name(c2, "c");

// node_modules/highlight.js/es/languages/cpp.js
init_esbuild_shims();
function cpp(hljs) {
  const regex3 = hljs.regex;
  const C_LINE_COMMENT_MODE = hljs.COMMENT("//", "$", { contains: [{ begin: /\\\n/ }] });
  const DECLTYPE_AUTO_RE = "decltype\\(auto\\)";
  const NAMESPACE_RE = "[a-zA-Z_]\\w*::";
  const TEMPLATE_ARGUMENT_RE = "<[^<>]+>";
  const FUNCTION_TYPE_RE = "(?!struct)(" + DECLTYPE_AUTO_RE + "|" + regex3.optional(NAMESPACE_RE) + "[a-zA-Z_]\\w*" + regex3.optional(TEMPLATE_ARGUMENT_RE) + ")";
  const CPP_PRIMITIVE_TYPES = {
    className: "type",
    begin: "\\b[a-z\\d_]*_t\\b"
  };
  const CHARACTER_ESCAPES = "\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)";
  const STRINGS = {
    className: "string",
    variants: [
      {
        begin: '(u8?|U|L)?"',
        end: '"',
        illegal: "\\n",
        contains: [hljs.BACKSLASH_ESCAPE]
      },
      {
        begin: "(u8?|U|L)?'(" + CHARACTER_ESCAPES + "|.)",
        end: "'",
        illegal: "."
      },
      hljs.END_SAME_AS_BEGIN({
        begin: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,
        end: /\)([^()\\ ]{0,16})"/
      })
    ]
  };
  const NUMBERS = {
    className: "number",
    variants: [
      // Floating-point literal.
      {
        begin: "[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"
      },
      // Integer literal.
      {
        begin: "[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"
        // Note: there are user-defined literal suffixes too, but perhaps having the custom suffix not part of the
        // literal highlight actually makes it stand out more.
      }
    ],
    relevance: 0
  };
  const PREPROCESSOR = {
    className: "meta",
    begin: /#\s*[a-z]+\b/,
    end: /$/,
    keywords: { keyword: "if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include" },
    contains: [
      {
        begin: /\\\n/,
        relevance: 0
      },
      hljs.inherit(STRINGS, { className: "string" }),
      {
        className: "string",
        begin: /<.*?>/
      },
      C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE
    ]
  };
  const TITLE_MODE = {
    className: "title",
    begin: regex3.optional(NAMESPACE_RE) + hljs.IDENT_RE,
    relevance: 0
  };
  const FUNCTION_TITLE = regex3.optional(NAMESPACE_RE) + hljs.IDENT_RE + "\\s*\\(";
  const RESERVED_KEYWORDS = [
    "alignas",
    "alignof",
    "and",
    "and_eq",
    "asm",
    "atomic_cancel",
    "atomic_commit",
    "atomic_noexcept",
    "auto",
    "bitand",
    "bitor",
    "break",
    "case",
    "catch",
    "class",
    "co_await",
    "co_return",
    "co_yield",
    "compl",
    "concept",
    "const_cast|10",
    "consteval",
    "constexpr",
    "constinit",
    "continue",
    "decltype",
    "default",
    "delete",
    "do",
    "dynamic_cast|10",
    "else",
    "enum",
    "explicit",
    "export",
    "extern",
    "false",
    "final",
    "for",
    "friend",
    "goto",
    "if",
    "import",
    "inline",
    "module",
    "mutable",
    "namespace",
    "new",
    "noexcept",
    "not",
    "not_eq",
    "nullptr",
    "operator",
    "or",
    "or_eq",
    "override",
    "private",
    "protected",
    "public",
    "reflexpr",
    "register",
    "reinterpret_cast|10",
    "requires",
    "return",
    "sizeof",
    "static_assert",
    "static_cast|10",
    "struct",
    "switch",
    "synchronized",
    "template",
    "this",
    "thread_local",
    "throw",
    "transaction_safe",
    "transaction_safe_dynamic",
    "true",
    "try",
    "typedef",
    "typeid",
    "typename",
    "union",
    "using",
    "virtual",
    "volatile",
    "while",
    "xor",
    "xor_eq"
  ];
  const RESERVED_TYPES = [
    "bool",
    "char",
    "char16_t",
    "char32_t",
    "char8_t",
    "double",
    "float",
    "int",
    "long",
    "short",
    "void",
    "wchar_t",
    "unsigned",
    "signed",
    "const",
    "static"
  ];
  const TYPE_HINTS = [
    "any",
    "auto_ptr",
    "barrier",
    "binary_semaphore",
    "bitset",
    "complex",
    "condition_variable",
    "condition_variable_any",
    "counting_semaphore",
    "deque",
    "false_type",
    "flat_map",
    "flat_set",
    "future",
    "imaginary",
    "initializer_list",
    "istringstream",
    "jthread",
    "latch",
    "lock_guard",
    "multimap",
    "multiset",
    "mutex",
    "optional",
    "ostringstream",
    "packaged_task",
    "pair",
    "promise",
    "priority_queue",
    "queue",
    "recursive_mutex",
    "recursive_timed_mutex",
    "scoped_lock",
    "set",
    "shared_future",
    "shared_lock",
    "shared_mutex",
    "shared_timed_mutex",
    "shared_ptr",
    "stack",
    "string_view",
    "stringstream",
    "timed_mutex",
    "thread",
    "true_type",
    "tuple",
    "unique_lock",
    "unique_ptr",
    "unordered_map",
    "unordered_multimap",
    "unordered_multiset",
    "unordered_set",
    "variant",
    "vector",
    "weak_ptr",
    "wstring",
    "wstring_view"
  ];
  const FUNCTION_HINTS = [
    "abort",
    "abs",
    "acos",
    "apply",
    "as_const",
    "asin",
    "atan",
    "atan2",
    "calloc",
    "ceil",
    "cerr",
    "cin",
    "clog",
    "cos",
    "cosh",
    "cout",
    "declval",
    "endl",
    "exchange",
    "exit",
    "exp",
    "fabs",
    "floor",
    "fmod",
    "forward",
    "fprintf",
    "fputs",
    "free",
    "frexp",
    "fscanf",
    "future",
    "invoke",
    "isalnum",
    "isalpha",
    "iscntrl",
    "isdigit",
    "isgraph",
    "islower",
    "isprint",
    "ispunct",
    "isspace",
    "isupper",
    "isxdigit",
    "labs",
    "launder",
    "ldexp",
    "log",
    "log10",
    "make_pair",
    "make_shared",
    "make_shared_for_overwrite",
    "make_tuple",
    "make_unique",
    "malloc",
    "memchr",
    "memcmp",
    "memcpy",
    "memset",
    "modf",
    "move",
    "pow",
    "printf",
    "putchar",
    "puts",
    "realloc",
    "scanf",
    "sin",
    "sinh",
    "snprintf",
    "sprintf",
    "sqrt",
    "sscanf",
    "std",
    "stderr",
    "stdin",
    "stdout",
    "strcat",
    "strchr",
    "strcmp",
    "strcpy",
    "strcspn",
    "strlen",
    "strncat",
    "strncmp",
    "strncpy",
    "strpbrk",
    "strrchr",
    "strspn",
    "strstr",
    "swap",
    "tan",
    "tanh",
    "terminate",
    "to_underlying",
    "tolower",
    "toupper",
    "vfprintf",
    "visit",
    "vprintf",
    "vsprintf"
  ];
  const LITERALS3 = [
    "NULL",
    "false",
    "nullopt",
    "nullptr",
    "true"
  ];
  const BUILT_IN = ["_Pragma"];
  const CPP_KEYWORDS = {
    type: RESERVED_TYPES,
    keyword: RESERVED_KEYWORDS,
    literal: LITERALS3,
    built_in: BUILT_IN,
    _type_hints: TYPE_HINTS
  };
  const FUNCTION_DISPATCH = {
    className: "function.dispatch",
    relevance: 0,
    keywords: {
      // Only for relevance, not highlighting.
      _hint: FUNCTION_HINTS
    },
    begin: regex3.concat(
      /\b/,
      /(?!decltype)/,
      /(?!if)/,
      /(?!for)/,
      /(?!switch)/,
      /(?!while)/,
      hljs.IDENT_RE,
      regex3.lookahead(/(<[^<>]+>|)\s*\(/)
    )
  };
  const EXPRESSION_CONTAINS = [
    FUNCTION_DISPATCH,
    PREPROCESSOR,
    CPP_PRIMITIVE_TYPES,
    C_LINE_COMMENT_MODE,
    hljs.C_BLOCK_COMMENT_MODE,
    NUMBERS,
    STRINGS
  ];
  const EXPRESSION_CONTEXT = {
    // This mode covers expression context where we can't expect a function
    // definition and shouldn't highlight anything that looks like one:
    // `return some()`, `else if()`, `(x*sum(1, 2))`
    variants: [
      {
        begin: /=/,
        end: /;/
      },
      {
        begin: /\(/,
        end: /\)/
      },
      {
        beginKeywords: "new throw return else",
        end: /;/
      }
    ],
    keywords: CPP_KEYWORDS,
    contains: EXPRESSION_CONTAINS.concat([
      {
        begin: /\(/,
        end: /\)/,
        keywords: CPP_KEYWORDS,
        contains: EXPRESSION_CONTAINS.concat(["self"]),
        relevance: 0
      }
    ]),
    relevance: 0
  };
  const FUNCTION_DECLARATION = {
    className: "function",
    begin: "(" + FUNCTION_TYPE_RE + "[\\*&\\s]+)+" + FUNCTION_TITLE,
    returnBegin: true,
    end: /[{;=]/,
    excludeEnd: true,
    keywords: CPP_KEYWORDS,
    illegal: /[^\w\s\*&:<>.]/,
    contains: [
      {
        // to prevent it from being confused as the function title
        begin: DECLTYPE_AUTO_RE,
        keywords: CPP_KEYWORDS,
        relevance: 0
      },
      {
        begin: FUNCTION_TITLE,
        returnBegin: true,
        contains: [TITLE_MODE],
        relevance: 0
      },
      // needed because we do not have look-behind on the below rule
      // to prevent it from grabbing the final : in a :: pair
      {
        begin: /::/,
        relevance: 0
      },
      // initializers
      {
        begin: /:/,
        endsWithParent: true,
        contains: [
          STRINGS,
          NUMBERS
        ]
      },
      // allow for multiple declarations, e.g.:
      // extern void f(int), g(char);
      {
        relevance: 0,
        match: /,/
      },
      {
        className: "params",
        begin: /\(/,
        end: /\)/,
        keywords: CPP_KEYWORDS,
        relevance: 0,
        contains: [
          C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE,
          STRINGS,
          NUMBERS,
          CPP_PRIMITIVE_TYPES,
          // Count matching parentheses.
          {
            begin: /\(/,
            end: /\)/,
            keywords: CPP_KEYWORDS,
            relevance: 0,
            contains: [
              "self",
              C_LINE_COMMENT_MODE,
              hljs.C_BLOCK_COMMENT_MODE,
              STRINGS,
              NUMBERS,
              CPP_PRIMITIVE_TYPES
            ]
          }
        ]
      },
      CPP_PRIMITIVE_TYPES,
      C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      PREPROCESSOR
    ]
  };
  return {
    name: "C++",
    aliases: [
      "cc",
      "c++",
      "h++",
      "hpp",
      "hh",
      "hxx",
      "cxx"
    ],
    keywords: CPP_KEYWORDS,
    illegal: "</",
    classNameAliases: { "function.dispatch": "built_in" },
    contains: [].concat(
      EXPRESSION_CONTEXT,
      FUNCTION_DECLARATION,
      FUNCTION_DISPATCH,
      EXPRESSION_CONTAINS,
      [
        PREPROCESSOR,
        {
          // containers: ie, `vector <int> rooms (9);`
          begin: "\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",
          end: ">",
          keywords: CPP_KEYWORDS,
          contains: [
            "self",
            CPP_PRIMITIVE_TYPES
          ]
        },
        {
          begin: hljs.IDENT_RE + "::",
          keywords: CPP_KEYWORDS
        },
        {
          match: [
            // extra complexity to deal with `enum class` and `enum struct`
            /\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,
            /\s+/,
            /\w+/
          ],
          className: {
            1: "keyword",
            3: "title.class"
          }
        }
      ]
    )
  };
}
__name(cpp, "cpp");

// node_modules/highlight.js/es/languages/csharp.js
init_esbuild_shims();
function csharp(hljs) {
  const BUILT_IN_KEYWORDS = [
    "bool",
    "byte",
    "char",
    "decimal",
    "delegate",
    "double",
    "dynamic",
    "enum",
    "float",
    "int",
    "long",
    "nint",
    "nuint",
    "object",
    "sbyte",
    "short",
    "string",
    "ulong",
    "uint",
    "ushort"
  ];
  const FUNCTION_MODIFIERS = [
    "public",
    "private",
    "protected",
    "static",
    "internal",
    "protected",
    "abstract",
    "async",
    "extern",
    "override",
    "unsafe",
    "virtual",
    "new",
    "sealed",
    "partial"
  ];
  const LITERAL_KEYWORDS = [
    "default",
    "false",
    "null",
    "true"
  ];
  const NORMAL_KEYWORDS = [
    "abstract",
    "as",
    "base",
    "break",
    "case",
    "catch",
    "class",
    "const",
    "continue",
    "do",
    "else",
    "event",
    "explicit",
    "extern",
    "finally",
    "fixed",
    "for",
    "foreach",
    "goto",
    "if",
    "implicit",
    "in",
    "interface",
    "internal",
    "is",
    "lock",
    "namespace",
    "new",
    "operator",
    "out",
    "override",
    "params",
    "private",
    "protected",
    "public",
    "readonly",
    "record",
    "ref",
    "return",
    "scoped",
    "sealed",
    "sizeof",
    "stackalloc",
    "static",
    "struct",
    "switch",
    "this",
    "throw",
    "try",
    "typeof",
    "unchecked",
    "unsafe",
    "using",
    "virtual",
    "void",
    "volatile",
    "while"
  ];
  const CONTEXTUAL_KEYWORDS = [
    "add",
    "alias",
    "and",
    "ascending",
    "args",
    "async",
    "await",
    "by",
    "descending",
    "dynamic",
    "equals",
    "file",
    "from",
    "get",
    "global",
    "group",
    "init",
    "into",
    "join",
    "let",
    "nameof",
    "not",
    "notnull",
    "on",
    "or",
    "orderby",
    "partial",
    "record",
    "remove",
    "required",
    "scoped",
    "select",
    "set",
    "unmanaged",
    "value|0",
    "var",
    "when",
    "where",
    "with",
    "yield"
  ];
  const KEYWORDS3 = {
    keyword: NORMAL_KEYWORDS.concat(CONTEXTUAL_KEYWORDS),
    built_in: BUILT_IN_KEYWORDS,
    literal: LITERAL_KEYWORDS
  };
  const TITLE_MODE = hljs.inherit(hljs.TITLE_MODE, { begin: "[a-zA-Z](\\.?\\w)*" });
  const NUMBERS = {
    className: "number",
    variants: [
      { begin: "\\b(0b[01']+)" },
      { begin: "(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)" },
      { begin: "(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)" }
    ],
    relevance: 0
  };
  const RAW_STRING = {
    className: "string",
    begin: /"""("*)(?!")(.|\n)*?"""\1/,
    relevance: 1
  };
  const VERBATIM_STRING = {
    className: "string",
    begin: '@"',
    end: '"',
    contains: [{ begin: '""' }]
  };
  const VERBATIM_STRING_NO_LF = hljs.inherit(VERBATIM_STRING, { illegal: /\n/ });
  const SUBST = {
    className: "subst",
    begin: /\{/,
    end: /\}/,
    keywords: KEYWORDS3
  };
  const SUBST_NO_LF = hljs.inherit(SUBST, { illegal: /\n/ });
  const INTERPOLATED_STRING = {
    className: "string",
    begin: /\$"/,
    end: '"',
    illegal: /\n/,
    contains: [
      { begin: /\{\{/ },
      { begin: /\}\}/ },
      hljs.BACKSLASH_ESCAPE,
      SUBST_NO_LF
    ]
  };
  const INTERPOLATED_VERBATIM_STRING = {
    className: "string",
    begin: /\$@"/,
    end: '"',
    contains: [
      { begin: /\{\{/ },
      { begin: /\}\}/ },
      { begin: '""' },
      SUBST
    ]
  };
  const INTERPOLATED_VERBATIM_STRING_NO_LF = hljs.inherit(INTERPOLATED_VERBATIM_STRING, {
    illegal: /\n/,
    contains: [
      { begin: /\{\{/ },
      { begin: /\}\}/ },
      { begin: '""' },
      SUBST_NO_LF
    ]
  });
  SUBST.contains = [
    INTERPOLATED_VERBATIM_STRING,
    INTERPOLATED_STRING,
    VERBATIM_STRING,
    hljs.APOS_STRING_MODE,
    hljs.QUOTE_STRING_MODE,
    NUMBERS,
    hljs.C_BLOCK_COMMENT_MODE
  ];
  SUBST_NO_LF.contains = [
    INTERPOLATED_VERBATIM_STRING_NO_LF,
    INTERPOLATED_STRING,
    VERBATIM_STRING_NO_LF,
    hljs.APOS_STRING_MODE,
    hljs.QUOTE_STRING_MODE,
    NUMBERS,
    hljs.inherit(hljs.C_BLOCK_COMMENT_MODE, { illegal: /\n/ })
  ];
  const STRING = { variants: [
    RAW_STRING,
    INTERPOLATED_VERBATIM_STRING,
    INTERPOLATED_STRING,
    VERBATIM_STRING,
    hljs.APOS_STRING_MODE,
    hljs.QUOTE_STRING_MODE
  ] };
  const GENERIC_MODIFIER = {
    begin: "<",
    end: ">",
    contains: [
      { beginKeywords: "in out" },
      TITLE_MODE
    ]
  };
  const TYPE_IDENT_RE = hljs.IDENT_RE + "(<" + hljs.IDENT_RE + "(\\s*,\\s*" + hljs.IDENT_RE + ")*>)?(\\[\\])?";
  const AT_IDENTIFIER = {
    // prevents expressions like `@class` from incorrect flagging
    // `class` as a keyword
    begin: "@" + hljs.IDENT_RE,
    relevance: 0
  };
  return {
    name: "C#",
    aliases: [
      "cs",
      "c#"
    ],
    keywords: KEYWORDS3,
    illegal: /::/,
    contains: [
      hljs.COMMENT(
        "///",
        "$",
        {
          returnBegin: true,
          contains: [
            {
              className: "doctag",
              variants: [
                {
                  begin: "///",
                  relevance: 0
                },
                { begin: "<!--|-->" },
                {
                  begin: "</?",
                  end: ">"
                }
              ]
            }
          ]
        }
      ),
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      {
        className: "meta",
        begin: "#",
        end: "$",
        keywords: { keyword: "if else elif endif define undef warning error line region endregion pragma checksum" }
      },
      STRING,
      NUMBERS,
      {
        beginKeywords: "class interface",
        relevance: 0,
        end: /[{;=]/,
        illegal: /[^\s:,]/,
        contains: [
          { beginKeywords: "where class" },
          TITLE_MODE,
          GENERIC_MODIFIER,
          hljs.C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE
        ]
      },
      {
        beginKeywords: "namespace",
        relevance: 0,
        end: /[{;=]/,
        illegal: /[^\s:]/,
        contains: [
          TITLE_MODE,
          hljs.C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE
        ]
      },
      {
        beginKeywords: "record",
        relevance: 0,
        end: /[{;=]/,
        illegal: /[^\s:]/,
        contains: [
          TITLE_MODE,
          GENERIC_MODIFIER,
          hljs.C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE
        ]
      },
      {
        // [Attributes("")]
        className: "meta",
        begin: "^\\s*\\[(?=[\\w])",
        excludeBegin: true,
        end: "\\]",
        excludeEnd: true,
        contains: [
          {
            className: "string",
            begin: /"/,
            end: /"/
          }
        ]
      },
      {
        // Expression keywords prevent 'keyword Name(...)' from being
        // recognized as a function definition
        beginKeywords: "new return throw await else",
        relevance: 0
      },
      {
        className: "function",
        begin: "(" + TYPE_IDENT_RE + "\\s+)+" + hljs.IDENT_RE + "\\s*(<[^=]+>\\s*)?\\(",
        returnBegin: true,
        end: /\s*[{;=]/,
        excludeEnd: true,
        keywords: KEYWORDS3,
        contains: [
          // prevents these from being highlighted `title`
          {
            beginKeywords: FUNCTION_MODIFIERS.join(" "),
            relevance: 0
          },
          {
            begin: hljs.IDENT_RE + "\\s*(<[^=]+>\\s*)?\\(",
            returnBegin: true,
            contains: [
              hljs.TITLE_MODE,
              GENERIC_MODIFIER
            ],
            relevance: 0
          },
          { match: /\(\)/ },
          {
            className: "params",
            begin: /\(/,
            end: /\)/,
            excludeBegin: true,
            excludeEnd: true,
            keywords: KEYWORDS3,
            relevance: 0,
            contains: [
              STRING,
              NUMBERS,
              hljs.C_BLOCK_COMMENT_MODE
            ]
          },
          hljs.C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE
        ]
      },
      AT_IDENTIFIER
    ]
  };
}
__name(csharp, "csharp");

// node_modules/highlight.js/es/languages/css.js
init_esbuild_shims();
var MODES = /* @__PURE__ */ __name((hljs) => {
  return {
    IMPORTANT: {
      scope: "meta",
      begin: "!important"
    },
    BLOCK_COMMENT: hljs.C_BLOCK_COMMENT_MODE,
    HEXCOLOR: {
      scope: "number",
      begin: /#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/
    },
    FUNCTION_DISPATCH: {
      className: "built_in",
      begin: /[\w-]+(?=\()/
    },
    ATTRIBUTE_SELECTOR_MODE: {
      scope: "selector-attr",
      begin: /\[/,
      end: /\]/,
      illegal: "$",
      contains: [
        hljs.APOS_STRING_MODE,
        hljs.QUOTE_STRING_MODE
      ]
    },
    CSS_NUMBER_MODE: {
      scope: "number",
      begin: hljs.NUMBER_RE + "(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",
      relevance: 0
    },
    CSS_VARIABLE: {
      className: "attr",
      begin: /--[A-Za-z_][A-Za-z0-9_-]*/
    }
  };
}, "MODES");
var HTML_TAGS = [
  "a",
  "abbr",
  "address",
  "article",
  "aside",
  "audio",
  "b",
  "blockquote",
  "body",
  "button",
  "canvas",
  "caption",
  "cite",
  "code",
  "dd",
  "del",
  "details",
  "dfn",
  "div",
  "dl",
  "dt",
  "em",
  "fieldset",
  "figcaption",
  "figure",
  "footer",
  "form",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "header",
  "hgroup",
  "html",
  "i",
  "iframe",
  "img",
  "input",
  "ins",
  "kbd",
  "label",
  "legend",
  "li",
  "main",
  "mark",
  "menu",
  "nav",
  "object",
  "ol",
  "optgroup",
  "option",
  "p",
  "picture",
  "q",
  "quote",
  "samp",
  "section",
  "select",
  "source",
  "span",
  "strong",
  "summary",
  "sup",
  "table",
  "tbody",
  "td",
  "textarea",
  "tfoot",
  "th",
  "thead",
  "time",
  "tr",
  "ul",
  "var",
  "video"
];
var SVG_TAGS = [
  "defs",
  "g",
  "marker",
  "mask",
  "pattern",
  "svg",
  "switch",
  "symbol",
  "feBlend",
  "feColorMatrix",
  "feComponentTransfer",
  "feComposite",
  "feConvolveMatrix",
  "feDiffuseLighting",
  "feDisplacementMap",
  "feFlood",
  "feGaussianBlur",
  "feImage",
  "feMerge",
  "feMorphology",
  "feOffset",
  "feSpecularLighting",
  "feTile",
  "feTurbulence",
  "linearGradient",
  "radialGradient",
  "stop",
  "circle",
  "ellipse",
  "image",
  "line",
  "path",
  "polygon",
  "polyline",
  "rect",
  "text",
  "use",
  "textPath",
  "tspan",
  "foreignObject",
  "clipPath"
];
var TAGS = [
  ...HTML_TAGS,
  ...SVG_TAGS
];
var MEDIA_FEATURES = [
  "any-hover",
  "any-pointer",
  "aspect-ratio",
  "color",
  "color-gamut",
  "color-index",
  "device-aspect-ratio",
  "device-height",
  "device-width",
  "display-mode",
  "forced-colors",
  "grid",
  "height",
  "hover",
  "inverted-colors",
  "monochrome",
  "orientation",
  "overflow-block",
  "overflow-inline",
  "pointer",
  "prefers-color-scheme",
  "prefers-contrast",
  "prefers-reduced-motion",
  "prefers-reduced-transparency",
  "resolution",
  "scan",
  "scripting",
  "update",
  "width",
  // TODO: find a better solution?
  "min-width",
  "max-width",
  "min-height",
  "max-height"
].sort().reverse();
var PSEUDO_CLASSES = [
  "active",
  "any-link",
  "blank",
  "checked",
  "current",
  "default",
  "defined",
  "dir",
  // dir()
  "disabled",
  "drop",
  "empty",
  "enabled",
  "first",
  "first-child",
  "first-of-type",
  "fullscreen",
  "future",
  "focus",
  "focus-visible",
  "focus-within",
  "has",
  // has()
  "host",
  // host or host()
  "host-context",
  // host-context()
  "hover",
  "indeterminate",
  "in-range",
  "invalid",
  "is",
  // is()
  "lang",
  // lang()
  "last-child",
  "last-of-type",
  "left",
  "link",
  "local-link",
  "not",
  // not()
  "nth-child",
  // nth-child()
  "nth-col",
  // nth-col()
  "nth-last-child",
  // nth-last-child()
  "nth-last-col",
  // nth-last-col()
  "nth-last-of-type",
  //nth-last-of-type()
  "nth-of-type",
  //nth-of-type()
  "only-child",
  "only-of-type",
  "optional",
  "out-of-range",
  "past",
  "placeholder-shown",
  "read-only",
  "read-write",
  "required",
  "right",
  "root",
  "scope",
  "target",
  "target-within",
  "user-invalid",
  "valid",
  "visited",
  "where"
  // where()
].sort().reverse();
var PSEUDO_ELEMENTS = [
  "after",
  "backdrop",
  "before",
  "cue",
  "cue-region",
  "first-letter",
  "first-line",
  "grammar-error",
  "marker",
  "part",
  "placeholder",
  "selection",
  "slotted",
  "spelling-error"
].sort().reverse();
var ATTRIBUTES = [
  "accent-color",
  "align-content",
  "align-items",
  "align-self",
  "alignment-baseline",
  "all",
  "anchor-name",
  "animation",
  "animation-composition",
  "animation-delay",
  "animation-direction",
  "animation-duration",
  "animation-fill-mode",
  "animation-iteration-count",
  "animation-name",
  "animation-play-state",
  "animation-range",
  "animation-range-end",
  "animation-range-start",
  "animation-timeline",
  "animation-timing-function",
  "appearance",
  "aspect-ratio",
  "backdrop-filter",
  "backface-visibility",
  "background",
  "background-attachment",
  "background-blend-mode",
  "background-clip",
  "background-color",
  "background-image",
  "background-origin",
  "background-position",
  "background-position-x",
  "background-position-y",
  "background-repeat",
  "background-size",
  "baseline-shift",
  "block-size",
  "border",
  "border-block",
  "border-block-color",
  "border-block-end",
  "border-block-end-color",
  "border-block-end-style",
  "border-block-end-width",
  "border-block-start",
  "border-block-start-color",
  "border-block-start-style",
  "border-block-start-width",
  "border-block-style",
  "border-block-width",
  "border-bottom",
  "border-bottom-color",
  "border-bottom-left-radius",
  "border-bottom-right-radius",
  "border-bottom-style",
  "border-bottom-width",
  "border-collapse",
  "border-color",
  "border-end-end-radius",
  "border-end-start-radius",
  "border-image",
  "border-image-outset",
  "border-image-repeat",
  "border-image-slice",
  "border-image-source",
  "border-image-width",
  "border-inline",
  "border-inline-color",
  "border-inline-end",
  "border-inline-end-color",
  "border-inline-end-style",
  "border-inline-end-width",
  "border-inline-start",
  "border-inline-start-color",
  "border-inline-start-style",
  "border-inline-start-width",
  "border-inline-style",
  "border-inline-width",
  "border-left",
  "border-left-color",
  "border-left-style",
  "border-left-width",
  "border-radius",
  "border-right",
  "border-right-color",
  "border-right-style",
  "border-right-width",
  "border-spacing",
  "border-start-end-radius",
  "border-start-start-radius",
  "border-style",
  "border-top",
  "border-top-color",
  "border-top-left-radius",
  "border-top-right-radius",
  "border-top-style",
  "border-top-width",
  "border-width",
  "bottom",
  "box-align",
  "box-decoration-break",
  "box-direction",
  "box-flex",
  "box-flex-group",
  "box-lines",
  "box-ordinal-group",
  "box-orient",
  "box-pack",
  "box-shadow",
  "box-sizing",
  "break-after",
  "break-before",
  "break-inside",
  "caption-side",
  "caret-color",
  "clear",
  "clip",
  "clip-path",
  "clip-rule",
  "color",
  "color-interpolation",
  "color-interpolation-filters",
  "color-profile",
  "color-rendering",
  "color-scheme",
  "column-count",
  "column-fill",
  "column-gap",
  "column-rule",
  "column-rule-color",
  "column-rule-style",
  "column-rule-width",
  "column-span",
  "column-width",
  "columns",
  "contain",
  "contain-intrinsic-block-size",
  "contain-intrinsic-height",
  "contain-intrinsic-inline-size",
  "contain-intrinsic-size",
  "contain-intrinsic-width",
  "container",
  "container-name",
  "container-type",
  "content",
  "content-visibility",
  "counter-increment",
  "counter-reset",
  "counter-set",
  "cue",
  "cue-after",
  "cue-before",
  "cursor",
  "cx",
  "cy",
  "direction",
  "display",
  "dominant-baseline",
  "empty-cells",
  "enable-background",
  "field-sizing",
  "fill",
  "fill-opacity",
  "fill-rule",
  "filter",
  "flex",
  "flex-basis",
  "flex-direction",
  "flex-flow",
  "flex-grow",
  "flex-shrink",
  "flex-wrap",
  "float",
  "flood-color",
  "flood-opacity",
  "flow",
  "font",
  "font-display",
  "font-family",
  "font-feature-settings",
  "font-kerning",
  "font-language-override",
  "font-optical-sizing",
  "font-palette",
  "font-size",
  "font-size-adjust",
  "font-smooth",
  "font-smoothing",
  "font-stretch",
  "font-style",
  "font-synthesis",
  "font-synthesis-position",
  "font-synthesis-small-caps",
  "font-synthesis-style",
  "font-synthesis-weight",
  "font-variant",
  "font-variant-alternates",
  "font-variant-caps",
  "font-variant-east-asian",
  "font-variant-emoji",
  "font-variant-ligatures",
  "font-variant-numeric",
  "font-variant-position",
  "font-variation-settings",
  "font-weight",
  "forced-color-adjust",
  "gap",
  "glyph-orientation-horizontal",
  "glyph-orientation-vertical",
  "grid",
  "grid-area",
  "grid-auto-columns",
  "grid-auto-flow",
  "grid-auto-rows",
  "grid-column",
  "grid-column-end",
  "grid-column-start",
  "grid-gap",
  "grid-row",
  "grid-row-end",
  "grid-row-start",
  "grid-template",
  "grid-template-areas",
  "grid-template-columns",
  "grid-template-rows",
  "hanging-punctuation",
  "height",
  "hyphenate-character",
  "hyphenate-limit-chars",
  "hyphens",
  "icon",
  "image-orientation",
  "image-rendering",
  "image-resolution",
  "ime-mode",
  "initial-letter",
  "initial-letter-align",
  "inline-size",
  "inset",
  "inset-area",
  "inset-block",
  "inset-block-end",
  "inset-block-start",
  "inset-inline",
  "inset-inline-end",
  "inset-inline-start",
  "isolation",
  "justify-content",
  "justify-items",
  "justify-self",
  "kerning",
  "left",
  "letter-spacing",
  "lighting-color",
  "line-break",
  "line-height",
  "line-height-step",
  "list-style",
  "list-style-image",
  "list-style-position",
  "list-style-type",
  "margin",
  "margin-block",
  "margin-block-end",
  "margin-block-start",
  "margin-bottom",
  "margin-inline",
  "margin-inline-end",
  "margin-inline-start",
  "margin-left",
  "margin-right",
  "margin-top",
  "margin-trim",
  "marker",
  "marker-end",
  "marker-mid",
  "marker-start",
  "marks",
  "mask",
  "mask-border",
  "mask-border-mode",
  "mask-border-outset",
  "mask-border-repeat",
  "mask-border-slice",
  "mask-border-source",
  "mask-border-width",
  "mask-clip",
  "mask-composite",
  "mask-image",
  "mask-mode",
  "mask-origin",
  "mask-position",
  "mask-repeat",
  "mask-size",
  "mask-type",
  "masonry-auto-flow",
  "math-depth",
  "math-shift",
  "math-style",
  "max-block-size",
  "max-height",
  "max-inline-size",
  "max-width",
  "min-block-size",
  "min-height",
  "min-inline-size",
  "min-width",
  "mix-blend-mode",
  "nav-down",
  "nav-index",
  "nav-left",
  "nav-right",
  "nav-up",
  "none",
  "normal",
  "object-fit",
  "object-position",
  "offset",
  "offset-anchor",
  "offset-distance",
  "offset-path",
  "offset-position",
  "offset-rotate",
  "opacity",
  "order",
  "orphans",
  "outline",
  "outline-color",
  "outline-offset",
  "outline-style",
  "outline-width",
  "overflow",
  "overflow-anchor",
  "overflow-block",
  "overflow-clip-margin",
  "overflow-inline",
  "overflow-wrap",
  "overflow-x",
  "overflow-y",
  "overlay",
  "overscroll-behavior",
  "overscroll-behavior-block",
  "overscroll-behavior-inline",
  "overscroll-behavior-x",
  "overscroll-behavior-y",
  "padding",
  "padding-block",
  "padding-block-end",
  "padding-block-start",
  "padding-bottom",
  "padding-inline",
  "padding-inline-end",
  "padding-inline-start",
  "padding-left",
  "padding-right",
  "padding-top",
  "page",
  "page-break-after",
  "page-break-before",
  "page-break-inside",
  "paint-order",
  "pause",
  "pause-after",
  "pause-before",
  "perspective",
  "perspective-origin",
  "place-content",
  "place-items",
  "place-self",
  "pointer-events",
  "position",
  "position-anchor",
  "position-visibility",
  "print-color-adjust",
  "quotes",
  "r",
  "resize",
  "rest",
  "rest-after",
  "rest-before",
  "right",
  "rotate",
  "row-gap",
  "ruby-align",
  "ruby-position",
  "scale",
  "scroll-behavior",
  "scroll-margin",
  "scroll-margin-block",
  "scroll-margin-block-end",
  "scroll-margin-block-start",
  "scroll-margin-bottom",
  "scroll-margin-inline",
  "scroll-margin-inline-end",
  "scroll-margin-inline-start",
  "scroll-margin-left",
  "scroll-margin-right",
  "scroll-margin-top",
  "scroll-padding",
  "scroll-padding-block",
  "scroll-padding-block-end",
  "scroll-padding-block-start",
  "scroll-padding-bottom",
  "scroll-padding-inline",
  "scroll-padding-inline-end",
  "scroll-padding-inline-start",
  "scroll-padding-left",
  "scroll-padding-right",
  "scroll-padding-top",
  "scroll-snap-align",
  "scroll-snap-stop",
  "scroll-snap-type",
  "scroll-timeline",
  "scroll-timeline-axis",
  "scroll-timeline-name",
  "scrollbar-color",
  "scrollbar-gutter",
  "scrollbar-width",
  "shape-image-threshold",
  "shape-margin",
  "shape-outside",
  "shape-rendering",
  "speak",
  "speak-as",
  "src",
  // @font-face
  "stop-color",
  "stop-opacity",
  "stroke",
  "stroke-dasharray",
  "stroke-dashoffset",
  "stroke-linecap",
  "stroke-linejoin",
  "stroke-miterlimit",
  "stroke-opacity",
  "stroke-width",
  "tab-size",
  "table-layout",
  "text-align",
  "text-align-all",
  "text-align-last",
  "text-anchor",
  "text-combine-upright",
  "text-decoration",
  "text-decoration-color",
  "text-decoration-line",
  "text-decoration-skip",
  "text-decoration-skip-ink",
  "text-decoration-style",
  "text-decoration-thickness",
  "text-emphasis",
  "text-emphasis-color",
  "text-emphasis-position",
  "text-emphasis-style",
  "text-indent",
  "text-justify",
  "text-orientation",
  "text-overflow",
  "text-rendering",
  "text-shadow",
  "text-size-adjust",
  "text-transform",
  "text-underline-offset",
  "text-underline-position",
  "text-wrap",
  "text-wrap-mode",
  "text-wrap-style",
  "timeline-scope",
  "top",
  "touch-action",
  "transform",
  "transform-box",
  "transform-origin",
  "transform-style",
  "transition",
  "transition-behavior",
  "transition-delay",
  "transition-duration",
  "transition-property",
  "transition-timing-function",
  "translate",
  "unicode-bidi",
  "user-modify",
  "user-select",
  "vector-effect",
  "vertical-align",
  "view-timeline",
  "view-timeline-axis",
  "view-timeline-inset",
  "view-timeline-name",
  "view-transition-name",
  "visibility",
  "voice-balance",
  "voice-duration",
  "voice-family",
  "voice-pitch",
  "voice-range",
  "voice-rate",
  "voice-stress",
  "voice-volume",
  "white-space",
  "white-space-collapse",
  "widows",
  "width",
  "will-change",
  "word-break",
  "word-spacing",
  "word-wrap",
  "writing-mode",
  "x",
  "y",
  "z-index",
  "zoom"
].sort().reverse();
function css(hljs) {
  const regex3 = hljs.regex;
  const modes = MODES(hljs);
  const VENDOR_PREFIX = { begin: /-(webkit|moz|ms|o)-(?=[a-z])/ };
  const AT_MODIFIERS = "and or not only";
  const AT_PROPERTY_RE = /@-?\w[\w]*(-\w+)*/;
  const IDENT_RE3 = "[a-zA-Z-][a-zA-Z0-9_-]*";
  const STRINGS = [
    hljs.APOS_STRING_MODE,
    hljs.QUOTE_STRING_MODE
  ];
  return {
    name: "CSS",
    case_insensitive: true,
    illegal: /[=|'\$]/,
    keywords: { keyframePosition: "from to" },
    classNameAliases: {
      // for visual continuity with `tag {}` and because we
      // don't have a great class for this?
      keyframePosition: "selector-tag"
    },
    contains: [
      modes.BLOCK_COMMENT,
      VENDOR_PREFIX,
      // to recognize keyframe 40% etc which are outside the scope of our
      // attribute value mode
      modes.CSS_NUMBER_MODE,
      {
        className: "selector-id",
        begin: /#[A-Za-z0-9_-]+/,
        relevance: 0
      },
      {
        className: "selector-class",
        begin: "\\." + IDENT_RE3,
        relevance: 0
      },
      modes.ATTRIBUTE_SELECTOR_MODE,
      {
        className: "selector-pseudo",
        variants: [
          { begin: ":(" + PSEUDO_CLASSES.join("|") + ")" },
          { begin: ":(:)?(" + PSEUDO_ELEMENTS.join("|") + ")" }
        ]
      },
      // we may actually need this (12/2020)
      // { // pseudo-selector params
      //   begin: /\(/,
      //   end: /\)/,
      //   contains: [ hljs.CSS_NUMBER_MODE ]
      // },
      modes.CSS_VARIABLE,
      {
        className: "attribute",
        begin: "\\b(" + ATTRIBUTES.join("|") + ")\\b"
      },
      // attribute values
      {
        begin: /:/,
        end: /[;}{]/,
        contains: [
          modes.BLOCK_COMMENT,
          modes.HEXCOLOR,
          modes.IMPORTANT,
          modes.CSS_NUMBER_MODE,
          ...STRINGS,
          // needed to highlight these as strings and to avoid issues with
          // illegal characters that might be inside urls that would tigger the
          // languages illegal stack
          {
            begin: /(url|data-uri)\(/,
            end: /\)/,
            relevance: 0,
            // from keywords
            keywords: { built_in: "url data-uri" },
            contains: [
              ...STRINGS,
              {
                className: "string",
                // any character other than `)` as in `url()` will be the start
                // of a string, which ends with `)` (from the parent mode)
                begin: /[^)]/,
                endsWithParent: true,
                excludeEnd: true
              }
            ]
          },
          modes.FUNCTION_DISPATCH
        ]
      },
      {
        begin: regex3.lookahead(/@/),
        end: "[{;]",
        relevance: 0,
        illegal: /:/,
        // break on Less variables @var: ...
        contains: [
          {
            className: "keyword",
            begin: AT_PROPERTY_RE
          },
          {
            begin: /\s/,
            endsWithParent: true,
            excludeEnd: true,
            relevance: 0,
            keywords: {
              $pattern: /[a-z-]+/,
              keyword: AT_MODIFIERS,
              attribute: MEDIA_FEATURES.join(" ")
            },
            contains: [
              {
                begin: /[a-z-]+(?=:)/,
                className: "attribute"
              },
              ...STRINGS,
              modes.CSS_NUMBER_MODE
            ]
          }
        ]
      },
      {
        className: "selector-tag",
        begin: "\\b(" + TAGS.join("|") + ")\\b"
      }
    ]
  };
}
__name(css, "css");

// node_modules/highlight.js/es/languages/diff.js
init_esbuild_shims();
function diff3(hljs) {
  const regex3 = hljs.regex;
  return {
    name: "Diff",
    aliases: ["patch"],
    contains: [
      {
        className: "meta",
        relevance: 10,
        match: regex3.either(
          /^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,
          /^\*\*\* +\d+,\d+ +\*\*\*\*$/,
          /^--- +\d+,\d+ +----$/
        )
      },
      {
        className: "comment",
        variants: [
          {
            begin: regex3.either(
              /Index: /,
              /^index/,
              /={3,}/,
              /^-{3}/,
              /^\*{3} /,
              /^\+{3}/,
              /^diff --git/
            ),
            end: /$/
          },
          { match: /^\*{15}$/ }
        ]
      },
      {
        className: "addition",
        begin: /^\+/,
        end: /$/
      },
      {
        className: "deletion",
        begin: /^-/,
        end: /$/
      },
      {
        className: "addition",
        begin: /^!/,
        end: /$/
      }
    ]
  };
}
__name(diff3, "diff");

// node_modules/highlight.js/es/languages/go.js
init_esbuild_shims();
function go(hljs) {
  const LITERALS3 = [
    "true",
    "false",
    "iota",
    "nil"
  ];
  const BUILT_INS3 = [
    "append",
    "cap",
    "close",
    "complex",
    "copy",
    "imag",
    "len",
    "make",
    "new",
    "panic",
    "print",
    "println",
    "real",
    "recover",
    "delete"
  ];
  const TYPES3 = [
    "bool",
    "byte",
    "complex64",
    "complex128",
    "error",
    "float32",
    "float64",
    "int8",
    "int16",
    "int32",
    "int64",
    "string",
    "uint8",
    "uint16",
    "uint32",
    "uint64",
    "int",
    "uint",
    "uintptr",
    "rune"
  ];
  const KWS = [
    "break",
    "case",
    "chan",
    "const",
    "continue",
    "default",
    "defer",
    "else",
    "fallthrough",
    "for",
    "func",
    "go",
    "goto",
    "if",
    "import",
    "interface",
    "map",
    "package",
    "range",
    "return",
    "select",
    "struct",
    "switch",
    "type",
    "var"
  ];
  const KEYWORDS3 = {
    keyword: KWS,
    type: TYPES3,
    literal: LITERALS3,
    built_in: BUILT_INS3
  };
  return {
    name: "Go",
    aliases: ["golang"],
    keywords: KEYWORDS3,
    illegal: "</",
    contains: [
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      {
        className: "string",
        variants: [
          hljs.QUOTE_STRING_MODE,
          hljs.APOS_STRING_MODE,
          {
            begin: "`",
            end: "`"
          }
        ]
      },
      {
        className: "number",
        variants: [
          {
            match: /-?\b0[xX]\.[a-fA-F0-9](_?[a-fA-F0-9])*[pP][+-]?\d(_?\d)*i?/,
            // hex without a present digit before . (making a digit afterwards required)
            relevance: 0
          },
          {
            match: /-?\b0[xX](_?[a-fA-F0-9])+((\.([a-fA-F0-9](_?[a-fA-F0-9])*)?)?[pP][+-]?\d(_?\d)*)?i?/,
            // hex with a present digit before . (making a digit afterwards optional)
            relevance: 0
          },
          {
            match: /-?\b0[oO](_?[0-7])*i?/,
            // leading 0o octal
            relevance: 0
          },
          {
            match: /-?\.\d(_?\d)*([eE][+-]?\d(_?\d)*)?i?/,
            // decimal without a present digit before . (making a digit afterwards required)
            relevance: 0
          },
          {
            match: /-?\b\d(_?\d)*(\.(\d(_?\d)*)?)?([eE][+-]?\d(_?\d)*)?i?/,
            // decimal with a present digit before . (making a digit afterwards optional)
            relevance: 0
          }
        ]
      },
      {
        begin: /:=/
        // relevance booster
      },
      {
        className: "function",
        beginKeywords: "func",
        end: "\\s*(\\{|$)",
        excludeEnd: true,
        contains: [
          hljs.TITLE_MODE,
          {
            className: "params",
            begin: /\(/,
            end: /\)/,
            endsParent: true,
            keywords: KEYWORDS3,
            illegal: /["']/
          }
        ]
      }
    ]
  };
}
__name(go, "go");

// node_modules/highlight.js/es/languages/graphql.js
init_esbuild_shims();
function graphql(hljs) {
  const regex3 = hljs.regex;
  const GQL_NAME = /[_A-Za-z][_0-9A-Za-z]*/;
  return {
    name: "GraphQL",
    aliases: ["gql"],
    case_insensitive: true,
    disableAutodetect: false,
    keywords: {
      keyword: [
        "query",
        "mutation",
        "subscription",
        "type",
        "input",
        "schema",
        "directive",
        "interface",
        "union",
        "scalar",
        "fragment",
        "enum",
        "on"
      ],
      literal: [
        "true",
        "false",
        "null"
      ]
    },
    contains: [
      hljs.HASH_COMMENT_MODE,
      hljs.QUOTE_STRING_MODE,
      hljs.NUMBER_MODE,
      {
        scope: "punctuation",
        match: /[.]{3}/,
        relevance: 0
      },
      {
        scope: "punctuation",
        begin: /[\!\(\)\:\=\[\]\{\|\}]{1}/,
        relevance: 0
      },
      {
        scope: "variable",
        begin: /\$/,
        end: /\W/,
        excludeEnd: true,
        relevance: 0
      },
      {
        scope: "meta",
        match: /@\w+/,
        excludeEnd: true
      },
      {
        scope: "symbol",
        begin: regex3.concat(GQL_NAME, regex3.lookahead(/\s*:/)),
        relevance: 0
      }
    ],
    illegal: [
      /[;<']/,
      /BEGIN/
    ]
  };
}
__name(graphql, "graphql");

// node_modules/highlight.js/es/languages/ini.js
init_esbuild_shims();
function ini(hljs) {
  const regex3 = hljs.regex;
  const NUMBERS = {
    className: "number",
    relevance: 0,
    variants: [
      { begin: /([+-]+)?[\d]+_[\d_]+/ },
      { begin: hljs.NUMBER_RE }
    ]
  };
  const COMMENTS = hljs.COMMENT();
  COMMENTS.variants = [
    {
      begin: /;/,
      end: /$/
    },
    {
      begin: /#/,
      end: /$/
    }
  ];
  const VARIABLES = {
    className: "variable",
    variants: [
      { begin: /\$[\w\d"][\w\d_]*/ },
      { begin: /\$\{(.*?)\}/ }
    ]
  };
  const LITERALS3 = {
    className: "literal",
    begin: /\bon|off|true|false|yes|no\b/
  };
  const STRINGS = {
    className: "string",
    contains: [hljs.BACKSLASH_ESCAPE],
    variants: [
      {
        begin: "'''",
        end: "'''",
        relevance: 10
      },
      {
        begin: '"""',
        end: '"""',
        relevance: 10
      },
      {
        begin: '"',
        end: '"'
      },
      {
        begin: "'",
        end: "'"
      }
    ]
  };
  const ARRAY = {
    begin: /\[/,
    end: /\]/,
    contains: [
      COMMENTS,
      LITERALS3,
      VARIABLES,
      STRINGS,
      NUMBERS,
      "self"
    ],
    relevance: 0
  };
  const BARE_KEY = /[A-Za-z0-9_-]+/;
  const QUOTED_KEY_DOUBLE_QUOTE = /"(\\"|[^"])*"/;
  const QUOTED_KEY_SINGLE_QUOTE = /'[^']*'/;
  const ANY_KEY = regex3.either(
    BARE_KEY,
    QUOTED_KEY_DOUBLE_QUOTE,
    QUOTED_KEY_SINGLE_QUOTE
  );
  const DOTTED_KEY = regex3.concat(
    ANY_KEY,
    "(\\s*\\.\\s*",
    ANY_KEY,
    ")*",
    regex3.lookahead(/\s*=\s*[^#\s]/)
  );
  return {
    name: "TOML, also INI",
    aliases: ["toml"],
    case_insensitive: true,
    illegal: /\S/,
    contains: [
      COMMENTS,
      {
        className: "section",
        begin: /\[+/,
        end: /\]+/
      },
      {
        begin: DOTTED_KEY,
        className: "attr",
        starts: {
          end: /$/,
          contains: [
            COMMENTS,
            ARRAY,
            LITERALS3,
            VARIABLES,
            STRINGS,
            NUMBERS
          ]
        }
      }
    ]
  };
}
__name(ini, "ini");

// node_modules/highlight.js/es/languages/java.js
init_esbuild_shims();
var decimalDigits = "[0-9](_*[0-9])*";
var frac = `\\.(${decimalDigits})`;
var hexDigits = "[0-9a-fA-F](_*[0-9a-fA-F])*";
var NUMERIC = {
  className: "number",
  variants: [
    // DecimalFloatingPointLiteral
    // including ExponentPart
    { begin: `(\\b(${decimalDigits})((${frac})|\\.)?|(${frac}))[eE][+-]?(${decimalDigits})[fFdD]?\\b` },
    // excluding ExponentPart
    { begin: `\\b(${decimalDigits})((${frac})[fFdD]?\\b|\\.([fFdD]\\b)?)` },
    { begin: `(${frac})[fFdD]?\\b` },
    { begin: `\\b(${decimalDigits})[fFdD]\\b` },
    // HexadecimalFloatingPointLiteral
    { begin: `\\b0[xX]((${hexDigits})\\.?|(${hexDigits})?\\.(${hexDigits}))[pP][+-]?(${decimalDigits})[fFdD]?\\b` },
    // DecimalIntegerLiteral
    { begin: "\\b(0|[1-9](_*[0-9])*)[lL]?\\b" },
    // HexIntegerLiteral
    { begin: `\\b0[xX](${hexDigits})[lL]?\\b` },
    // OctalIntegerLiteral
    { begin: "\\b0(_*[0-7])*[lL]?\\b" },
    // BinaryIntegerLiteral
    { begin: "\\b0[bB][01](_*[01])*[lL]?\\b" }
  ],
  relevance: 0
};
function recurRegex(re2, substitution, depth) {
  if (depth === -1) return "";
  return re2.replace(substitution, (_) => {
    return recurRegex(re2, substitution, depth - 1);
  });
}
__name(recurRegex, "recurRegex");
function java(hljs) {
  const regex3 = hljs.regex;
  const JAVA_IDENT_RE = "[\xC0-\u02B8a-zA-Z_$][\xC0-\u02B8a-zA-Z_$0-9]*";
  const GENERIC_IDENT_RE = JAVA_IDENT_RE + recurRegex("(?:<" + JAVA_IDENT_RE + "~~~(?:\\s*,\\s*" + JAVA_IDENT_RE + "~~~)*>)?", /~~~/g, 2);
  const MAIN_KEYWORDS = [
    "synchronized",
    "abstract",
    "private",
    "var",
    "static",
    "if",
    "const ",
    "for",
    "while",
    "strictfp",
    "finally",
    "protected",
    "import",
    "native",
    "final",
    "void",
    "enum",
    "else",
    "break",
    "transient",
    "catch",
    "instanceof",
    "volatile",
    "case",
    "assert",
    "package",
    "default",
    "public",
    "try",
    "switch",
    "continue",
    "throws",
    "protected",
    "public",
    "private",
    "module",
    "requires",
    "exports",
    "do",
    "sealed",
    "yield",
    "permits",
    "goto",
    "when"
  ];
  const BUILT_INS3 = [
    "super",
    "this"
  ];
  const LITERALS3 = [
    "false",
    "true",
    "null"
  ];
  const TYPES3 = [
    "char",
    "boolean",
    "long",
    "float",
    "int",
    "byte",
    "short",
    "double"
  ];
  const KEYWORDS3 = {
    keyword: MAIN_KEYWORDS,
    literal: LITERALS3,
    type: TYPES3,
    built_in: BUILT_INS3
  };
  const ANNOTATION = {
    className: "meta",
    begin: "@" + JAVA_IDENT_RE,
    contains: [
      {
        begin: /\(/,
        end: /\)/,
        contains: ["self"]
        // allow nested () inside our annotation
      }
    ]
  };
  const PARAMS = {
    className: "params",
    begin: /\(/,
    end: /\)/,
    keywords: KEYWORDS3,
    relevance: 0,
    contains: [hljs.C_BLOCK_COMMENT_MODE],
    endsParent: true
  };
  return {
    name: "Java",
    aliases: ["jsp"],
    keywords: KEYWORDS3,
    illegal: /<\/|#/,
    contains: [
      hljs.COMMENT(
        "/\\*\\*",
        "\\*/",
        {
          relevance: 0,
          contains: [
            {
              // eat up @'s in emails to prevent them to be recognized as doctags
              begin: /\w+@/,
              relevance: 0
            },
            {
              className: "doctag",
              begin: "@[A-Za-z]+"
            }
          ]
        }
      ),
      // relevance boost
      {
        begin: /import java\.[a-z]+\./,
        keywords: "import",
        relevance: 2
      },
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      {
        begin: /"""/,
        end: /"""/,
        className: "string",
        contains: [hljs.BACKSLASH_ESCAPE]
      },
      hljs.APOS_STRING_MODE,
      hljs.QUOTE_STRING_MODE,
      {
        match: [
          /\b(?:class|interface|enum|extends|implements|new)/,
          /\s+/,
          JAVA_IDENT_RE
        ],
        className: {
          1: "keyword",
          3: "title.class"
        }
      },
      {
        // Exceptions for hyphenated keywords
        match: /non-sealed/,
        scope: "keyword"
      },
      {
        begin: [
          regex3.concat(/(?!else)/, JAVA_IDENT_RE),
          /\s+/,
          JAVA_IDENT_RE,
          /\s+/,
          /=(?!=)/
        ],
        className: {
          1: "type",
          3: "variable",
          5: "operator"
        }
      },
      {
        begin: [
          /record/,
          /\s+/,
          JAVA_IDENT_RE
        ],
        className: {
          1: "keyword",
          3: "title.class"
        },
        contains: [
          PARAMS,
          hljs.C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE
        ]
      },
      {
        // Expression keywords prevent 'keyword Name(...)' from being
        // recognized as a function definition
        beginKeywords: "new throw return else",
        relevance: 0
      },
      {
        begin: [
          "(?:" + GENERIC_IDENT_RE + "\\s+)",
          hljs.UNDERSCORE_IDENT_RE,
          /\s*(?=\()/
        ],
        className: { 2: "title.function" },
        keywords: KEYWORDS3,
        contains: [
          {
            className: "params",
            begin: /\(/,
            end: /\)/,
            keywords: KEYWORDS3,
            relevance: 0,
            contains: [
              ANNOTATION,
              hljs.APOS_STRING_MODE,
              hljs.QUOTE_STRING_MODE,
              NUMERIC,
              hljs.C_BLOCK_COMMENT_MODE
            ]
          },
          hljs.C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE
        ]
      },
      NUMERIC,
      ANNOTATION
    ]
  };
}
__name(java, "java");

// node_modules/highlight.js/es/languages/javascript.js
init_esbuild_shims();
var IDENT_RE = "[A-Za-z$_][0-9A-Za-z$_]*";
var KEYWORDS = [
  "as",
  // for exports
  "in",
  "of",
  "if",
  "for",
  "while",
  "finally",
  "var",
  "new",
  "function",
  "do",
  "return",
  "void",
  "else",
  "break",
  "catch",
  "instanceof",
  "with",
  "throw",
  "case",
  "default",
  "try",
  "switch",
  "continue",
  "typeof",
  "delete",
  "let",
  "yield",
  "const",
  "class",
  // JS handles these with a special rule
  // "get",
  // "set",
  "debugger",
  "async",
  "await",
  "static",
  "import",
  "from",
  "export",
  "extends",
  // It's reached stage 3, which is "recommended for implementation":
  "using"
];
var LITERALS = [
  "true",
  "false",
  "null",
  "undefined",
  "NaN",
  "Infinity"
];
var TYPES = [
  // Fundamental objects
  "Object",
  "Function",
  "Boolean",
  "Symbol",
  // numbers and dates
  "Math",
  "Date",
  "Number",
  "BigInt",
  // text
  "String",
  "RegExp",
  // Indexed collections
  "Array",
  "Float32Array",
  "Float64Array",
  "Int8Array",
  "Uint8Array",
  "Uint8ClampedArray",
  "Int16Array",
  "Int32Array",
  "Uint16Array",
  "Uint32Array",
  "BigInt64Array",
  "BigUint64Array",
  // Keyed collections
  "Set",
  "Map",
  "WeakSet",
  "WeakMap",
  // Structured data
  "ArrayBuffer",
  "SharedArrayBuffer",
  "Atomics",
  "DataView",
  "JSON",
  // Control abstraction objects
  "Promise",
  "Generator",
  "GeneratorFunction",
  "AsyncFunction",
  // Reflection
  "Reflect",
  "Proxy",
  // Internationalization
  "Intl",
  // WebAssembly
  "WebAssembly"
];
var ERROR_TYPES = [
  "Error",
  "EvalError",
  "InternalError",
  "RangeError",
  "ReferenceError",
  "SyntaxError",
  "TypeError",
  "URIError"
];
var BUILT_IN_GLOBALS = [
  "setInterval",
  "setTimeout",
  "clearInterval",
  "clearTimeout",
  "require",
  "exports",
  "eval",
  "isFinite",
  "isNaN",
  "parseFloat",
  "parseInt",
  "decodeURI",
  "decodeURIComponent",
  "encodeURI",
  "encodeURIComponent",
  "escape",
  "unescape"
];
var BUILT_IN_VARIABLES = [
  "arguments",
  "this",
  "super",
  "console",
  "window",
  "document",
  "localStorage",
  "sessionStorage",
  "module",
  "global"
  // Node.js
];
var BUILT_INS = [].concat(
  BUILT_IN_GLOBALS,
  TYPES,
  ERROR_TYPES
);
function javascript(hljs) {
  const regex3 = hljs.regex;
  const hasClosingTag = /* @__PURE__ */ __name((match2, { after }) => {
    const tag2 = "</" + match2[0].slice(1);
    const pos2 = match2.input.indexOf(tag2, after);
    return pos2 !== -1;
  }, "hasClosingTag");
  const IDENT_RE$1 = IDENT_RE;
  const FRAGMENT = {
    begin: "<>",
    end: "</>"
  };
  const XML_SELF_CLOSING = /<[A-Za-z0-9\\._:-]+\s*\/>/;
  const XML_TAG = {
    begin: /<[A-Za-z0-9\\._:-]+/,
    end: /\/[A-Za-z0-9\\._:-]+>|\/>/,
    /**
     * @param {RegExpMatchArray} match
     * @param {CallbackResponse} response
     */
    isTrulyOpeningTag: /* @__PURE__ */ __name((match2, response) => {
      const afterMatchIndex = match2[0].length + match2.index;
      const nextChar = match2.input[afterMatchIndex];
      if (
        // HTML should not include another raw `<` inside a tag
        // nested type?
        // `<Array<Array<number>>`, etc.
        nextChar === "<" || // the , gives away that this is not HTML
        // `<T, A extends keyof T, V>`
        nextChar === ","
      ) {
        response.ignoreMatch();
        return;
      }
      if (nextChar === ">") {
        if (!hasClosingTag(match2, { after: afterMatchIndex })) {
          response.ignoreMatch();
        }
      }
      let m;
      const afterMatch = match2.input.substring(afterMatchIndex);
      if (m = afterMatch.match(/^\s*=/)) {
        response.ignoreMatch();
        return;
      }
      if (m = afterMatch.match(/^\s+extends\s+/)) {
        if (m.index === 0) {
          response.ignoreMatch();
          return;
        }
      }
    }, "isTrulyOpeningTag")
  };
  const KEYWORDS$1 = {
    $pattern: IDENT_RE,
    keyword: KEYWORDS,
    literal: LITERALS,
    built_in: BUILT_INS,
    "variable.language": BUILT_IN_VARIABLES
  };
  const decimalDigits3 = "[0-9](_?[0-9])*";
  const frac3 = `\\.(${decimalDigits3})`;
  const decimalInteger = `0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`;
  const NUMBER = {
    className: "number",
    variants: [
      // DecimalLiteral
      { begin: `(\\b(${decimalInteger})((${frac3})|\\.)?|(${frac3}))[eE][+-]?(${decimalDigits3})\\b` },
      { begin: `\\b(${decimalInteger})\\b((${frac3})\\b|\\.)?|(${frac3})\\b` },
      // DecimalBigIntegerLiteral
      { begin: `\\b(0|[1-9](_?[0-9])*)n\\b` },
      // NonDecimalIntegerLiteral
      { begin: "\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b" },
      { begin: "\\b0[bB][0-1](_?[0-1])*n?\\b" },
      { begin: "\\b0[oO][0-7](_?[0-7])*n?\\b" },
      // LegacyOctalIntegerLiteral (does not include underscore separators)
      // https://tc39.es/ecma262/#sec-additional-syntax-numeric-literals
      { begin: "\\b0[0-7]+n?\\b" }
    ],
    relevance: 0
  };
  const SUBST = {
    className: "subst",
    begin: "\\$\\{",
    end: "\\}",
    keywords: KEYWORDS$1,
    contains: []
    // defined later
  };
  const HTML_TEMPLATE = {
    begin: ".?html`",
    end: "",
    starts: {
      end: "`",
      returnEnd: false,
      contains: [
        hljs.BACKSLASH_ESCAPE,
        SUBST
      ],
      subLanguage: "xml"
    }
  };
  const CSS_TEMPLATE = {
    begin: ".?css`",
    end: "",
    starts: {
      end: "`",
      returnEnd: false,
      contains: [
        hljs.BACKSLASH_ESCAPE,
        SUBST
      ],
      subLanguage: "css"
    }
  };
  const GRAPHQL_TEMPLATE = {
    begin: ".?gql`",
    end: "",
    starts: {
      end: "`",
      returnEnd: false,
      contains: [
        hljs.BACKSLASH_ESCAPE,
        SUBST
      ],
      subLanguage: "graphql"
    }
  };
  const TEMPLATE_STRING = {
    className: "string",
    begin: "`",
    end: "`",
    contains: [
      hljs.BACKSLASH_ESCAPE,
      SUBST
    ]
  };
  const JSDOC_COMMENT = hljs.COMMENT(
    /\/\*\*(?!\/)/,
    "\\*/",
    {
      relevance: 0,
      contains: [
        {
          begin: "(?=@[A-Za-z]+)",
          relevance: 0,
          contains: [
            {
              className: "doctag",
              begin: "@[A-Za-z]+"
            },
            {
              className: "type",
              begin: "\\{",
              end: "\\}",
              excludeEnd: true,
              excludeBegin: true,
              relevance: 0
            },
            {
              className: "variable",
              begin: IDENT_RE$1 + "(?=\\s*(-)|$)",
              endsParent: true,
              relevance: 0
            },
            // eat spaces (not newlines) so we can find
            // types or variables
            {
              begin: /(?=[^\n])\s/,
              relevance: 0
            }
          ]
        }
      ]
    }
  );
  const COMMENT = {
    className: "comment",
    variants: [
      JSDOC_COMMENT,
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.C_LINE_COMMENT_MODE
    ]
  };
  const SUBST_INTERNALS = [
    hljs.APOS_STRING_MODE,
    hljs.QUOTE_STRING_MODE,
    HTML_TEMPLATE,
    CSS_TEMPLATE,
    GRAPHQL_TEMPLATE,
    TEMPLATE_STRING,
    // Skip numbers when they are part of a variable name
    { match: /\$\d+/ },
    NUMBER
    // This is intentional:
    // See https://github.com/highlightjs/highlight.js/issues/3288
    // hljs.REGEXP_MODE
  ];
  SUBST.contains = SUBST_INTERNALS.concat({
    // we need to pair up {} inside our subst to prevent
    // it from ending too early by matching another }
    begin: /\{/,
    end: /\}/,
    keywords: KEYWORDS$1,
    contains: [
      "self"
    ].concat(SUBST_INTERNALS)
  });
  const SUBST_AND_COMMENTS = [].concat(COMMENT, SUBST.contains);
  const PARAMS_CONTAINS = SUBST_AND_COMMENTS.concat([
    // eat recursive parens in sub expressions
    {
      begin: /(\s*)\(/,
      end: /\)/,
      keywords: KEYWORDS$1,
      contains: ["self"].concat(SUBST_AND_COMMENTS)
    }
  ]);
  const PARAMS = {
    className: "params",
    // convert this to negative lookbehind in v12
    begin: /(\s*)\(/,
    // to match the parms with
    end: /\)/,
    excludeBegin: true,
    excludeEnd: true,
    keywords: KEYWORDS$1,
    contains: PARAMS_CONTAINS
  };
  const CLASS_OR_EXTENDS = {
    variants: [
      // class Car extends vehicle
      {
        match: [
          /class/,
          /\s+/,
          IDENT_RE$1,
          /\s+/,
          /extends/,
          /\s+/,
          regex3.concat(IDENT_RE$1, "(", regex3.concat(/\./, IDENT_RE$1), ")*")
        ],
        scope: {
          1: "keyword",
          3: "title.class",
          5: "keyword",
          7: "title.class.inherited"
        }
      },
      // class Car
      {
        match: [
          /class/,
          /\s+/,
          IDENT_RE$1
        ],
        scope: {
          1: "keyword",
          3: "title.class"
        }
      }
    ]
  };
  const CLASS_REFERENCE = {
    relevance: 0,
    match: regex3.either(
      // Hard coded exceptions
      /\bJSON/,
      // Float32Array, OutT
      /\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,
      // CSSFactory, CSSFactoryT
      /\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,
      // FPs, FPsT
      /\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/
      // P
      // single letters are not highlighted
      // BLAH
      // this will be flagged as a UPPER_CASE_CONSTANT instead
    ),
    className: "title.class",
    keywords: {
      _: [
        // se we still get relevance credit for JS library classes
        ...TYPES,
        ...ERROR_TYPES
      ]
    }
  };
  const USE_STRICT = {
    label: "use_strict",
    className: "meta",
    relevance: 10,
    begin: /^\s*['"]use (strict|asm)['"]/
  };
  const FUNCTION_DEFINITION = {
    variants: [
      {
        match: [
          /function/,
          /\s+/,
          IDENT_RE$1,
          /(?=\s*\()/
        ]
      },
      // anonymous function
      {
        match: [
          /function/,
          /\s*(?=\()/
        ]
      }
    ],
    className: {
      1: "keyword",
      3: "title.function"
    },
    label: "func.def",
    contains: [PARAMS],
    illegal: /%/
  };
  const UPPER_CASE_CONSTANT = {
    relevance: 0,
    match: /\b[A-Z][A-Z_0-9]+\b/,
    className: "variable.constant"
  };
  function noneOf(list3) {
    return regex3.concat("(?!", list3.join("|"), ")");
  }
  __name(noneOf, "noneOf");
  const FUNCTION_CALL = {
    match: regex3.concat(
      /\b/,
      noneOf([
        ...BUILT_IN_GLOBALS,
        "super",
        "import"
      ].map((x) => `${x}\\s*\\(`)),
      IDENT_RE$1,
      regex3.lookahead(/\s*\(/)
    ),
    className: "title.function",
    relevance: 0
  };
  const PROPERTY_ACCESS = {
    begin: regex3.concat(/\./, regex3.lookahead(
      regex3.concat(IDENT_RE$1, /(?![0-9A-Za-z$_(])/)
    )),
    end: IDENT_RE$1,
    excludeBegin: true,
    keywords: "prototype",
    className: "property",
    relevance: 0
  };
  const GETTER_OR_SETTER = {
    match: [
      /get|set/,
      /\s+/,
      IDENT_RE$1,
      /(?=\()/
    ],
    className: {
      1: "keyword",
      3: "title.function"
    },
    contains: [
      {
        // eat to avoid empty params
        begin: /\(\)/
      },
      PARAMS
    ]
  };
  const FUNC_LEAD_IN_RE = "(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|" + hljs.UNDERSCORE_IDENT_RE + ")\\s*=>";
  const FUNCTION_VARIABLE = {
    match: [
      /const|var|let/,
      /\s+/,
      IDENT_RE$1,
      /\s*/,
      /=\s*/,
      /(async\s*)?/,
      // async is optional
      regex3.lookahead(FUNC_LEAD_IN_RE)
    ],
    keywords: "async",
    className: {
      1: "keyword",
      3: "title.function"
    },
    contains: [
      PARAMS
    ]
  };
  return {
    name: "JavaScript",
    aliases: ["js", "jsx", "mjs", "cjs"],
    keywords: KEYWORDS$1,
    // this will be extended by TypeScript
    exports: { PARAMS_CONTAINS, CLASS_REFERENCE },
    illegal: /#(?![$_A-z])/,
    contains: [
      hljs.SHEBANG({
        label: "shebang",
        binary: "node",
        relevance: 5
      }),
      USE_STRICT,
      hljs.APOS_STRING_MODE,
      hljs.QUOTE_STRING_MODE,
      HTML_TEMPLATE,
      CSS_TEMPLATE,
      GRAPHQL_TEMPLATE,
      TEMPLATE_STRING,
      COMMENT,
      // Skip numbers when they are part of a variable name
      { match: /\$\d+/ },
      NUMBER,
      CLASS_REFERENCE,
      {
        scope: "attr",
        match: IDENT_RE$1 + regex3.lookahead(":"),
        relevance: 0
      },
      FUNCTION_VARIABLE,
      {
        // "value" container
        begin: "(" + hljs.RE_STARTERS_RE + "|\\b(case|return|throw)\\b)\\s*",
        keywords: "return throw case",
        relevance: 0,
        contains: [
          COMMENT,
          hljs.REGEXP_MODE,
          {
            className: "function",
            // we have to count the parens to make sure we actually have the
            // correct bounding ( ) before the =>.  There could be any number of
            // sub-expressions inside also surrounded by parens.
            begin: FUNC_LEAD_IN_RE,
            returnBegin: true,
            end: "\\s*=>",
            contains: [
              {
                className: "params",
                variants: [
                  {
                    begin: hljs.UNDERSCORE_IDENT_RE,
                    relevance: 0
                  },
                  {
                    className: null,
                    begin: /\(\s*\)/,
                    skip: true
                  },
                  {
                    begin: /(\s*)\(/,
                    end: /\)/,
                    excludeBegin: true,
                    excludeEnd: true,
                    keywords: KEYWORDS$1,
                    contains: PARAMS_CONTAINS
                  }
                ]
              }
            ]
          },
          {
            // could be a comma delimited list of params to a function call
            begin: /,/,
            relevance: 0
          },
          {
            match: /\s+/,
            relevance: 0
          },
          {
            // JSX
            variants: [
              { begin: FRAGMENT.begin, end: FRAGMENT.end },
              { match: XML_SELF_CLOSING },
              {
                begin: XML_TAG.begin,
                // we carefully check the opening tag to see if it truly
                // is a tag and not a false positive
                "on:begin": XML_TAG.isTrulyOpeningTag,
                end: XML_TAG.end
              }
            ],
            subLanguage: "xml",
            contains: [
              {
                begin: XML_TAG.begin,
                end: XML_TAG.end,
                skip: true,
                contains: ["self"]
              }
            ]
          }
        ]
      },
      FUNCTION_DEFINITION,
      {
        // prevent this from getting swallowed up by function
        // since they appear "function like"
        beginKeywords: "while if switch catch for"
      },
      {
        // we have to count the parens to make sure we actually have the correct
        // bounding ( ).  There could be any number of sub-expressions inside
        // also surrounded by parens.
        begin: "\\b(?!function)" + hljs.UNDERSCORE_IDENT_RE + "\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",
        // end parens
        returnBegin: true,
        label: "func.def",
        contains: [
          PARAMS,
          hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1, className: "title.function" })
        ]
      },
      // catch ... so it won't trigger the property rule below
      {
        match: /\.\.\./,
        relevance: 0
      },
      PROPERTY_ACCESS,
      // hack: prevents detection of keywords in some circumstances
      // .keyword()
      // $keyword = x
      {
        match: "\\$" + IDENT_RE$1,
        relevance: 0
      },
      {
        match: [/\bconstructor(?=\s*\()/],
        className: { 1: "title.function" },
        contains: [PARAMS]
      },
      FUNCTION_CALL,
      UPPER_CASE_CONSTANT,
      CLASS_OR_EXTENDS,
      GETTER_OR_SETTER,
      {
        match: /\$[(.]/
        // relevance booster for a pattern common to JS libs: `$(something)` and `$.something`
      }
    ]
  };
}
__name(javascript, "javascript");

// node_modules/highlight.js/es/languages/json.js
init_esbuild_shims();
function json(hljs) {
  const ATTRIBUTE = {
    className: "attr",
    begin: /"(\\.|[^\\"\r\n])*"(?=\s*:)/,
    relevance: 1.01
  };
  const PUNCTUATION = {
    match: /[{}[\],:]/,
    className: "punctuation",
    relevance: 0
  };
  const LITERALS3 = [
    "true",
    "false",
    "null"
  ];
  const LITERALS_MODE = {
    scope: "literal",
    beginKeywords: LITERALS3.join(" ")
  };
  return {
    name: "JSON",
    aliases: ["jsonc"],
    keywords: {
      literal: LITERALS3
    },
    contains: [
      ATTRIBUTE,
      PUNCTUATION,
      hljs.QUOTE_STRING_MODE,
      LITERALS_MODE,
      hljs.C_NUMBER_MODE,
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE
    ],
    illegal: "\\S"
  };
}
__name(json, "json");

// node_modules/highlight.js/es/languages/kotlin.js
init_esbuild_shims();
var decimalDigits2 = "[0-9](_*[0-9])*";
var frac2 = `\\.(${decimalDigits2})`;
var hexDigits2 = "[0-9a-fA-F](_*[0-9a-fA-F])*";
var NUMERIC2 = {
  className: "number",
  variants: [
    // DecimalFloatingPointLiteral
    // including ExponentPart
    { begin: `(\\b(${decimalDigits2})((${frac2})|\\.)?|(${frac2}))[eE][+-]?(${decimalDigits2})[fFdD]?\\b` },
    // excluding ExponentPart
    { begin: `\\b(${decimalDigits2})((${frac2})[fFdD]?\\b|\\.([fFdD]\\b)?)` },
    { begin: `(${frac2})[fFdD]?\\b` },
    { begin: `\\b(${decimalDigits2})[fFdD]\\b` },
    // HexadecimalFloatingPointLiteral
    { begin: `\\b0[xX]((${hexDigits2})\\.?|(${hexDigits2})?\\.(${hexDigits2}))[pP][+-]?(${decimalDigits2})[fFdD]?\\b` },
    // DecimalIntegerLiteral
    { begin: "\\b(0|[1-9](_*[0-9])*)[lL]?\\b" },
    // HexIntegerLiteral
    { begin: `\\b0[xX](${hexDigits2})[lL]?\\b` },
    // OctalIntegerLiteral
    { begin: "\\b0(_*[0-7])*[lL]?\\b" },
    // BinaryIntegerLiteral
    { begin: "\\b0[bB][01](_*[01])*[lL]?\\b" }
  ],
  relevance: 0
};
function kotlin(hljs) {
  const KEYWORDS3 = {
    keyword: "abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual",
    built_in: "Byte Short Char Int Long Boolean Float Double Void Unit Nothing",
    literal: "true false null"
  };
  const KEYWORDS_WITH_LABEL = {
    className: "keyword",
    begin: /\b(break|continue|return|this)\b/,
    starts: { contains: [
      {
        className: "symbol",
        begin: /@\w+/
      }
    ] }
  };
  const LABEL = {
    className: "symbol",
    begin: hljs.UNDERSCORE_IDENT_RE + "@"
  };
  const SUBST = {
    className: "subst",
    begin: /\$\{/,
    end: /\}/,
    contains: [hljs.C_NUMBER_MODE]
  };
  const VARIABLE = {
    className: "variable",
    begin: "\\$" + hljs.UNDERSCORE_IDENT_RE
  };
  const STRING = {
    className: "string",
    variants: [
      {
        begin: '"""',
        end: '"""(?=[^"])',
        contains: [
          VARIABLE,
          SUBST
        ]
      },
      // Can't use built-in modes easily, as we want to use STRING in the meta
      // context as 'meta-string' and there's no syntax to remove explicitly set
      // classNames in built-in modes.
      {
        begin: "'",
        end: "'",
        illegal: /\n/,
        contains: [hljs.BACKSLASH_ESCAPE]
      },
      {
        begin: '"',
        end: '"',
        illegal: /\n/,
        contains: [
          hljs.BACKSLASH_ESCAPE,
          VARIABLE,
          SUBST
        ]
      }
    ]
  };
  SUBST.contains.push(STRING);
  const ANNOTATION_USE_SITE = {
    className: "meta",
    begin: "@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*" + hljs.UNDERSCORE_IDENT_RE + ")?"
  };
  const ANNOTATION = {
    className: "meta",
    begin: "@" + hljs.UNDERSCORE_IDENT_RE,
    contains: [
      {
        begin: /\(/,
        end: /\)/,
        contains: [
          hljs.inherit(STRING, { className: "string" }),
          "self"
        ]
      }
    ]
  };
  const KOTLIN_NUMBER_MODE = NUMERIC2;
  const KOTLIN_NESTED_COMMENT = hljs.COMMENT(
    "/\\*",
    "\\*/",
    { contains: [hljs.C_BLOCK_COMMENT_MODE] }
  );
  const KOTLIN_PAREN_TYPE = { variants: [
    {
      className: "type",
      begin: hljs.UNDERSCORE_IDENT_RE
    },
    {
      begin: /\(/,
      end: /\)/,
      contains: []
      // defined later
    }
  ] };
  const KOTLIN_PAREN_TYPE2 = KOTLIN_PAREN_TYPE;
  KOTLIN_PAREN_TYPE2.variants[1].contains = [KOTLIN_PAREN_TYPE];
  KOTLIN_PAREN_TYPE.variants[1].contains = [KOTLIN_PAREN_TYPE2];
  return {
    name: "Kotlin",
    aliases: [
      "kt",
      "kts"
    ],
    keywords: KEYWORDS3,
    contains: [
      hljs.COMMENT(
        "/\\*\\*",
        "\\*/",
        {
          relevance: 0,
          contains: [
            {
              className: "doctag",
              begin: "@[A-Za-z]+"
            }
          ]
        }
      ),
      hljs.C_LINE_COMMENT_MODE,
      KOTLIN_NESTED_COMMENT,
      KEYWORDS_WITH_LABEL,
      LABEL,
      ANNOTATION_USE_SITE,
      ANNOTATION,
      {
        className: "function",
        beginKeywords: "fun",
        end: "[(]|$",
        returnBegin: true,
        excludeEnd: true,
        keywords: KEYWORDS3,
        relevance: 5,
        contains: [
          {
            begin: hljs.UNDERSCORE_IDENT_RE + "\\s*\\(",
            returnBegin: true,
            relevance: 0,
            contains: [hljs.UNDERSCORE_TITLE_MODE]
          },
          {
            className: "type",
            begin: /</,
            end: />/,
            keywords: "reified",
            relevance: 0
          },
          {
            className: "params",
            begin: /\(/,
            end: /\)/,
            endsParent: true,
            keywords: KEYWORDS3,
            relevance: 0,
            contains: [
              {
                begin: /:/,
                end: /[=,\/]/,
                endsWithParent: true,
                contains: [
                  KOTLIN_PAREN_TYPE,
                  hljs.C_LINE_COMMENT_MODE,
                  KOTLIN_NESTED_COMMENT
                ],
                relevance: 0
              },
              hljs.C_LINE_COMMENT_MODE,
              KOTLIN_NESTED_COMMENT,
              ANNOTATION_USE_SITE,
              ANNOTATION,
              STRING,
              hljs.C_NUMBER_MODE
            ]
          },
          KOTLIN_NESTED_COMMENT
        ]
      },
      {
        begin: [
          /class|interface|trait/,
          /\s+/,
          hljs.UNDERSCORE_IDENT_RE
        ],
        beginScope: {
          3: "title.class"
        },
        keywords: "class interface trait",
        end: /[:\{(]|$/,
        excludeEnd: true,
        illegal: "extends implements",
        contains: [
          { beginKeywords: "public protected internal private constructor" },
          hljs.UNDERSCORE_TITLE_MODE,
          {
            className: "type",
            begin: /</,
            end: />/,
            excludeBegin: true,
            excludeEnd: true,
            relevance: 0
          },
          {
            className: "type",
            begin: /[,:]\s*/,
            end: /[<\(,){\s]|$/,
            excludeBegin: true,
            returnEnd: true
          },
          ANNOTATION_USE_SITE,
          ANNOTATION
        ]
      },
      STRING,
      {
        className: "meta",
        begin: "^#!/usr/bin/env",
        end: "$",
        illegal: "\n"
      },
      KOTLIN_NUMBER_MODE
    ]
  };
}
__name(kotlin, "kotlin");

// node_modules/highlight.js/es/languages/less.js
init_esbuild_shims();
var MODES2 = /* @__PURE__ */ __name((hljs) => {
  return {
    IMPORTANT: {
      scope: "meta",
      begin: "!important"
    },
    BLOCK_COMMENT: hljs.C_BLOCK_COMMENT_MODE,
    HEXCOLOR: {
      scope: "number",
      begin: /#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/
    },
    FUNCTION_DISPATCH: {
      className: "built_in",
      begin: /[\w-]+(?=\()/
    },
    ATTRIBUTE_SELECTOR_MODE: {
      scope: "selector-attr",
      begin: /\[/,
      end: /\]/,
      illegal: "$",
      contains: [
        hljs.APOS_STRING_MODE,
        hljs.QUOTE_STRING_MODE
      ]
    },
    CSS_NUMBER_MODE: {
      scope: "number",
      begin: hljs.NUMBER_RE + "(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",
      relevance: 0
    },
    CSS_VARIABLE: {
      className: "attr",
      begin: /--[A-Za-z_][A-Za-z0-9_-]*/
    }
  };
}, "MODES");
var HTML_TAGS2 = [
  "a",
  "abbr",
  "address",
  "article",
  "aside",
  "audio",
  "b",
  "blockquote",
  "body",
  "button",
  "canvas",
  "caption",
  "cite",
  "code",
  "dd",
  "del",
  "details",
  "dfn",
  "div",
  "dl",
  "dt",
  "em",
  "fieldset",
  "figcaption",
  "figure",
  "footer",
  "form",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "header",
  "hgroup",
  "html",
  "i",
  "iframe",
  "img",
  "input",
  "ins",
  "kbd",
  "label",
  "legend",
  "li",
  "main",
  "mark",
  "menu",
  "nav",
  "object",
  "ol",
  "optgroup",
  "option",
  "p",
  "picture",
  "q",
  "quote",
  "samp",
  "section",
  "select",
  "source",
  "span",
  "strong",
  "summary",
  "sup",
  "table",
  "tbody",
  "td",
  "textarea",
  "tfoot",
  "th",
  "thead",
  "time",
  "tr",
  "ul",
  "var",
  "video"
];
var SVG_TAGS2 = [
  "defs",
  "g",
  "marker",
  "mask",
  "pattern",
  "svg",
  "switch",
  "symbol",
  "feBlend",
  "feColorMatrix",
  "feComponentTransfer",
  "feComposite",
  "feConvolveMatrix",
  "feDiffuseLighting",
  "feDisplacementMap",
  "feFlood",
  "feGaussianBlur",
  "feImage",
  "feMerge",
  "feMorphology",
  "feOffset",
  "feSpecularLighting",
  "feTile",
  "feTurbulence",
  "linearGradient",
  "radialGradient",
  "stop",
  "circle",
  "ellipse",
  "image",
  "line",
  "path",
  "polygon",
  "polyline",
  "rect",
  "text",
  "use",
  "textPath",
  "tspan",
  "foreignObject",
  "clipPath"
];
var TAGS2 = [
  ...HTML_TAGS2,
  ...SVG_TAGS2
];
var MEDIA_FEATURES2 = [
  "any-hover",
  "any-pointer",
  "aspect-ratio",
  "color",
  "color-gamut",
  "color-index",
  "device-aspect-ratio",
  "device-height",
  "device-width",
  "display-mode",
  "forced-colors",
  "grid",
  "height",
  "hover",
  "inverted-colors",
  "monochrome",
  "orientation",
  "overflow-block",
  "overflow-inline",
  "pointer",
  "prefers-color-scheme",
  "prefers-contrast",
  "prefers-reduced-motion",
  "prefers-reduced-transparency",
  "resolution",
  "scan",
  "scripting",
  "update",
  "width",
  // TODO: find a better solution?
  "min-width",
  "max-width",
  "min-height",
  "max-height"
].sort().reverse();
var PSEUDO_CLASSES2 = [
  "active",
  "any-link",
  "blank",
  "checked",
  "current",
  "default",
  "defined",
  "dir",
  // dir()
  "disabled",
  "drop",
  "empty",
  "enabled",
  "first",
  "first-child",
  "first-of-type",
  "fullscreen",
  "future",
  "focus",
  "focus-visible",
  "focus-within",
  "has",
  // has()
  "host",
  // host or host()
  "host-context",
  // host-context()
  "hover",
  "indeterminate",
  "in-range",
  "invalid",
  "is",
  // is()
  "lang",
  // lang()
  "last-child",
  "last-of-type",
  "left",
  "link",
  "local-link",
  "not",
  // not()
  "nth-child",
  // nth-child()
  "nth-col",
  // nth-col()
  "nth-last-child",
  // nth-last-child()
  "nth-last-col",
  // nth-last-col()
  "nth-last-of-type",
  //nth-last-of-type()
  "nth-of-type",
  //nth-of-type()
  "only-child",
  "only-of-type",
  "optional",
  "out-of-range",
  "past",
  "placeholder-shown",
  "read-only",
  "read-write",
  "required",
  "right",
  "root",
  "scope",
  "target",
  "target-within",
  "user-invalid",
  "valid",
  "visited",
  "where"
  // where()
].sort().reverse();
var PSEUDO_ELEMENTS2 = [
  "after",
  "backdrop",
  "before",
  "cue",
  "cue-region",
  "first-letter",
  "first-line",
  "grammar-error",
  "marker",
  "part",
  "placeholder",
  "selection",
  "slotted",
  "spelling-error"
].sort().reverse();
var ATTRIBUTES2 = [
  "accent-color",
  "align-content",
  "align-items",
  "align-self",
  "alignment-baseline",
  "all",
  "anchor-name",
  "animation",
  "animation-composition",
  "animation-delay",
  "animation-direction",
  "animation-duration",
  "animation-fill-mode",
  "animation-iteration-count",
  "animation-name",
  "animation-play-state",
  "animation-range",
  "animation-range-end",
  "animation-range-start",
  "animation-timeline",
  "animation-timing-function",
  "appearance",
  "aspect-ratio",
  "backdrop-filter",
  "backface-visibility",
  "background",
  "background-attachment",
  "background-blend-mode",
  "background-clip",
  "background-color",
  "background-image",
  "background-origin",
  "background-position",
  "background-position-x",
  "background-position-y",
  "background-repeat",
  "background-size",
  "baseline-shift",
  "block-size",
  "border",
  "border-block",
  "border-block-color",
  "border-block-end",
  "border-block-end-color",
  "border-block-end-style",
  "border-block-end-width",
  "border-block-start",
  "border-block-start-color",
  "border-block-start-style",
  "border-block-start-width",
  "border-block-style",
  "border-block-width",
  "border-bottom",
  "border-bottom-color",
  "border-bottom-left-radius",
  "border-bottom-right-radius",
  "border-bottom-style",
  "border-bottom-width",
  "border-collapse",
  "border-color",
  "border-end-end-radius",
  "border-end-start-radius",
  "border-image",
  "border-image-outset",
  "border-image-repeat",
  "border-image-slice",
  "border-image-source",
  "border-image-width",
  "border-inline",
  "border-inline-color",
  "border-inline-end",
  "border-inline-end-color",
  "border-inline-end-style",
  "border-inline-end-width",
  "border-inline-start",
  "border-inline-start-color",
  "border-inline-start-style",
  "border-inline-start-width",
  "border-inline-style",
  "border-inline-width",
  "border-left",
  "border-left-color",
  "border-left-style",
  "border-left-width",
  "border-radius",
  "border-right",
  "border-right-color",
  "border-right-style",
  "border-right-width",
  "border-spacing",
  "border-start-end-radius",
  "border-start-start-radius",
  "border-style",
  "border-top",
  "border-top-color",
  "border-top-left-radius",
  "border-top-right-radius",
  "border-top-style",
  "border-top-width",
  "border-width",
  "bottom",
  "box-align",
  "box-decoration-break",
  "box-direction",
  "box-flex",
  "box-flex-group",
  "box-lines",
  "box-ordinal-group",
  "box-orient",
  "box-pack",
  "box-shadow",
  "box-sizing",
  "break-after",
  "break-before",
  "break-inside",
  "caption-side",
  "caret-color",
  "clear",
  "clip",
  "clip-path",
  "clip-rule",
  "color",
  "color-interpolation",
  "color-interpolation-filters",
  "color-profile",
  "color-rendering",
  "color-scheme",
  "column-count",
  "column-fill",
  "column-gap",
  "column-rule",
  "column-rule-color",
  "column-rule-style",
  "column-rule-width",
  "column-span",
  "column-width",
  "columns",
  "contain",
  "contain-intrinsic-block-size",
  "contain-intrinsic-height",
  "contain-intrinsic-inline-size",
  "contain-intrinsic-size",
  "contain-intrinsic-width",
  "container",
  "container-name",
  "container-type",
  "content",
  "content-visibility",
  "counter-increment",
  "counter-reset",
  "counter-set",
  "cue",
  "cue-after",
  "cue-before",
  "cursor",
  "cx",
  "cy",
  "direction",
  "display",
  "dominant-baseline",
  "empty-cells",
  "enable-background",
  "field-sizing",
  "fill",
  "fill-opacity",
  "fill-rule",
  "filter",
  "flex",
  "flex-basis",
  "flex-direction",
  "flex-flow",
  "flex-grow",
  "flex-shrink",
  "flex-wrap",
  "float",
  "flood-color",
  "flood-opacity",
  "flow",
  "font",
  "font-display",
  "font-family",
  "font-feature-settings",
  "font-kerning",
  "font-language-override",
  "font-optical-sizing",
  "font-palette",
  "font-size",
  "font-size-adjust",
  "font-smooth",
  "font-smoothing",
  "font-stretch",
  "font-style",
  "font-synthesis",
  "font-synthesis-position",
  "font-synthesis-small-caps",
  "font-synthesis-style",
  "font-synthesis-weight",
  "font-variant",
  "font-variant-alternates",
  "font-variant-caps",
  "font-variant-east-asian",
  "font-variant-emoji",
  "font-variant-ligatures",
  "font-variant-numeric",
  "font-variant-position",
  "font-variation-settings",
  "font-weight",
  "forced-color-adjust",
  "gap",
  "glyph-orientation-horizontal",
  "glyph-orientation-vertical",
  "grid",
  "grid-area",
  "grid-auto-columns",
  "grid-auto-flow",
  "grid-auto-rows",
  "grid-column",
  "grid-column-end",
  "grid-column-start",
  "grid-gap",
  "grid-row",
  "grid-row-end",
  "grid-row-start",
  "grid-template",
  "grid-template-areas",
  "grid-template-columns",
  "grid-template-rows",
  "hanging-punctuation",
  "height",
  "hyphenate-character",
  "hyphenate-limit-chars",
  "hyphens",
  "icon",
  "image-orientation",
  "image-rendering",
  "image-resolution",
  "ime-mode",
  "initial-letter",
  "initial-letter-align",
  "inline-size",
  "inset",
  "inset-area",
  "inset-block",
  "inset-block-end",
  "inset-block-start",
  "inset-inline",
  "inset-inline-end",
  "inset-inline-start",
  "isolation",
  "justify-content",
  "justify-items",
  "justify-self",
  "kerning",
  "left",
  "letter-spacing",
  "lighting-color",
  "line-break",
  "line-height",
  "line-height-step",
  "list-style",
  "list-style-image",
  "list-style-position",
  "list-style-type",
  "margin",
  "margin-block",
  "margin-block-end",
  "margin-block-start",
  "margin-bottom",
  "margin-inline",
  "margin-inline-end",
  "margin-inline-start",
  "margin-left",
  "margin-right",
  "margin-top",
  "margin-trim",
  "marker",
  "marker-end",
  "marker-mid",
  "marker-start",
  "marks",
  "mask",
  "mask-border",
  "mask-border-mode",
  "mask-border-outset",
  "mask-border-repeat",
  "mask-border-slice",
  "mask-border-source",
  "mask-border-width",
  "mask-clip",
  "mask-composite",
  "mask-image",
  "mask-mode",
  "mask-origin",
  "mask-position",
  "mask-repeat",
  "mask-size",
  "mask-type",
  "masonry-auto-flow",
  "math-depth",
  "math-shift",
  "math-style",
  "max-block-size",
  "max-height",
  "max-inline-size",
  "max-width",
  "min-block-size",
  "min-height",
  "min-inline-size",
  "min-width",
  "mix-blend-mode",
  "nav-down",
  "nav-index",
  "nav-left",
  "nav-right",
  "nav-up",
  "none",
  "normal",
  "object-fit",
  "object-position",
  "offset",
  "offset-anchor",
  "offset-distance",
  "offset-path",
  "offset-position",
  "offset-rotate",
  "opacity",
  "order",
  "orphans",
  "outline",
  "outline-color",
  "outline-offset",
  "outline-style",
  "outline-width",
  "overflow",
  "overflow-anchor",
  "overflow-block",
  "overflow-clip-margin",
  "overflow-inline",
  "overflow-wrap",
  "overflow-x",
  "overflow-y",
  "overlay",
  "overscroll-behavior",
  "overscroll-behavior-block",
  "overscroll-behavior-inline",
  "overscroll-behavior-x",
  "overscroll-behavior-y",
  "padding",
  "padding-block",
  "padding-block-end",
  "padding-block-start",
  "padding-bottom",
  "padding-inline",
  "padding-inline-end",
  "padding-inline-start",
  "padding-left",
  "padding-right",
  "padding-top",
  "page",
  "page-break-after",
  "page-break-before",
  "page-break-inside",
  "paint-order",
  "pause",
  "pause-after",
  "pause-before",
  "perspective",
  "perspective-origin",
  "place-content",
  "place-items",
  "place-self",
  "pointer-events",
  "position",
  "position-anchor",
  "position-visibility",
  "print-color-adjust",
  "quotes",
  "r",
  "resize",
  "rest",
  "rest-after",
  "rest-before",
  "right",
  "rotate",
  "row-gap",
  "ruby-align",
  "ruby-position",
  "scale",
  "scroll-behavior",
  "scroll-margin",
  "scroll-margin-block",
  "scroll-margin-block-end",
  "scroll-margin-block-start",
  "scroll-margin-bottom",
  "scroll-margin-inline",
  "scroll-margin-inline-end",
  "scroll-margin-inline-start",
  "scroll-margin-left",
  "scroll-margin-right",
  "scroll-margin-top",
  "scroll-padding",
  "scroll-padding-block",
  "scroll-padding-block-end",
  "scroll-padding-block-start",
  "scroll-padding-bottom",
  "scroll-padding-inline",
  "scroll-padding-inline-end",
  "scroll-padding-inline-start",
  "scroll-padding-left",
  "scroll-padding-right",
  "scroll-padding-top",
  "scroll-snap-align",
  "scroll-snap-stop",
  "scroll-snap-type",
  "scroll-timeline",
  "scroll-timeline-axis",
  "scroll-timeline-name",
  "scrollbar-color",
  "scrollbar-gutter",
  "scrollbar-width",
  "shape-image-threshold",
  "shape-margin",
  "shape-outside",
  "shape-rendering",
  "speak",
  "speak-as",
  "src",
  // @font-face
  "stop-color",
  "stop-opacity",
  "stroke",
  "stroke-dasharray",
  "stroke-dashoffset",
  "stroke-linecap",
  "stroke-linejoin",
  "stroke-miterlimit",
  "stroke-opacity",
  "stroke-width",
  "tab-size",
  "table-layout",
  "text-align",
  "text-align-all",
  "text-align-last",
  "text-anchor",
  "text-combine-upright",
  "text-decoration",
  "text-decoration-color",
  "text-decoration-line",
  "text-decoration-skip",
  "text-decoration-skip-ink",
  "text-decoration-style",
  "text-decoration-thickness",
  "text-emphasis",
  "text-emphasis-color",
  "text-emphasis-position",
  "text-emphasis-style",
  "text-indent",
  "text-justify",
  "text-orientation",
  "text-overflow",
  "text-rendering",
  "text-shadow",
  "text-size-adjust",
  "text-transform",
  "text-underline-offset",
  "text-underline-position",
  "text-wrap",
  "text-wrap-mode",
  "text-wrap-style",
  "timeline-scope",
  "top",
  "touch-action",
  "transform",
  "transform-box",
  "transform-origin",
  "transform-style",
  "transition",
  "transition-behavior",
  "transition-delay",
  "transition-duration",
  "transition-property",
  "transition-timing-function",
  "translate",
  "unicode-bidi",
  "user-modify",
  "user-select",
  "vector-effect",
  "vertical-align",
  "view-timeline",
  "view-timeline-axis",
  "view-timeline-inset",
  "view-timeline-name",
  "view-transition-name",
  "visibility",
  "voice-balance",
  "voice-duration",
  "voice-family",
  "voice-pitch",
  "voice-range",
  "voice-rate",
  "voice-stress",
  "voice-volume",
  "white-space",
  "white-space-collapse",
  "widows",
  "width",
  "will-change",
  "word-break",
  "word-spacing",
  "word-wrap",
  "writing-mode",
  "x",
  "y",
  "z-index",
  "zoom"
].sort().reverse();
var PSEUDO_SELECTORS = PSEUDO_CLASSES2.concat(PSEUDO_ELEMENTS2).sort().reverse();
function less(hljs) {
  const modes = MODES2(hljs);
  const PSEUDO_SELECTORS$1 = PSEUDO_SELECTORS;
  const AT_MODIFIERS = "and or not only";
  const IDENT_RE3 = "[\\w-]+";
  const INTERP_IDENT_RE = "(" + IDENT_RE3 + "|@\\{" + IDENT_RE3 + "\\})";
  const RULES = [];
  const VALUE_MODES = [];
  const STRING_MODE = /* @__PURE__ */ __name(function(c3) {
    return {
      // Less strings are not multiline (also include '~' for more consistent coloring of "escaped" strings)
      className: "string",
      begin: "~?" + c3 + ".*?" + c3
    };
  }, "STRING_MODE");
  const IDENT_MODE = /* @__PURE__ */ __name(function(name3, begin, relevance) {
    return {
      className: name3,
      begin,
      relevance
    };
  }, "IDENT_MODE");
  const AT_KEYWORDS = {
    $pattern: /[a-z-]+/,
    keyword: AT_MODIFIERS,
    attribute: MEDIA_FEATURES2.join(" ")
  };
  const PARENS_MODE = {
    // used only to properly balance nested parens inside mixin call, def. arg list
    begin: "\\(",
    end: "\\)",
    contains: VALUE_MODES,
    keywords: AT_KEYWORDS,
    relevance: 0
  };
  VALUE_MODES.push(
    hljs.C_LINE_COMMENT_MODE,
    hljs.C_BLOCK_COMMENT_MODE,
    STRING_MODE("'"),
    STRING_MODE('"'),
    modes.CSS_NUMBER_MODE,
    // fixme: it does not include dot for numbers like .5em :(
    {
      begin: "(url|data-uri)\\(",
      starts: {
        className: "string",
        end: "[\\)\\n]",
        excludeEnd: true
      }
    },
    modes.HEXCOLOR,
    PARENS_MODE,
    IDENT_MODE("variable", "@@?" + IDENT_RE3, 10),
    IDENT_MODE("variable", "@\\{" + IDENT_RE3 + "\\}"),
    IDENT_MODE("built_in", "~?`[^`]*?`"),
    // inline javascript (or whatever host language) *multiline* string
    {
      // @media features (it’s here to not duplicate things in AT_RULE_MODE with extra PARENS_MODE overriding):
      className: "attribute",
      begin: IDENT_RE3 + "\\s*:",
      end: ":",
      returnBegin: true,
      excludeEnd: true
    },
    modes.IMPORTANT,
    { beginKeywords: "and not" },
    modes.FUNCTION_DISPATCH
  );
  const VALUE_WITH_RULESETS = VALUE_MODES.concat({
    begin: /\{/,
    end: /\}/,
    contains: RULES
  });
  const MIXIN_GUARD_MODE = {
    beginKeywords: "when",
    endsWithParent: true,
    contains: [{ beginKeywords: "and not" }].concat(VALUE_MODES)
    // using this form to override VALUE’s 'function' match
  };
  const RULE_MODE = {
    begin: INTERP_IDENT_RE + "\\s*:",
    returnBegin: true,
    end: /[;}]/,
    relevance: 0,
    contains: [
      { begin: /-(webkit|moz|ms|o)-/ },
      modes.CSS_VARIABLE,
      {
        className: "attribute",
        begin: "\\b(" + ATTRIBUTES2.join("|") + ")\\b",
        end: /(?=:)/,
        starts: {
          endsWithParent: true,
          illegal: "[<=$]",
          relevance: 0,
          contains: VALUE_MODES
        }
      }
    ]
  };
  const AT_RULE_MODE = {
    className: "keyword",
    begin: "@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b",
    starts: {
      end: "[;{}]",
      keywords: AT_KEYWORDS,
      returnEnd: true,
      contains: VALUE_MODES,
      relevance: 0
    }
  };
  const VAR_RULE_MODE = {
    className: "variable",
    variants: [
      // using more strict pattern for higher relevance to increase chances of Less detection.
      // this is *the only* Less specific statement used in most of the sources, so...
      // (we’ll still often loose to the css-parser unless there's '//' comment,
      // simply because 1 variable just can't beat 99 properties :)
      {
        begin: "@" + IDENT_RE3 + "\\s*:",
        relevance: 15
      },
      { begin: "@" + IDENT_RE3 }
    ],
    starts: {
      end: "[;}]",
      returnEnd: true,
      contains: VALUE_WITH_RULESETS
    }
  };
  const SELECTOR_MODE = {
    // first parse unambiguous selectors (i.e. those not starting with tag)
    // then fall into the scary lookahead-discriminator variant.
    // this mode also handles mixin definitions and calls
    variants: [
      {
        begin: "[\\.#:&\\[>]",
        end: "[;{}]"
        // mixin calls end with ';'
      },
      {
        begin: INTERP_IDENT_RE,
        end: /\{/
      }
    ],
    returnBegin: true,
    returnEnd: true,
    illegal: `[<='$"]`,
    relevance: 0,
    contains: [
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      MIXIN_GUARD_MODE,
      IDENT_MODE("keyword", "all\\b"),
      IDENT_MODE("variable", "@\\{" + IDENT_RE3 + "\\}"),
      // otherwise it’s identified as tag
      {
        begin: "\\b(" + TAGS2.join("|") + ")\\b",
        className: "selector-tag"
      },
      modes.CSS_NUMBER_MODE,
      IDENT_MODE("selector-tag", INTERP_IDENT_RE, 0),
      IDENT_MODE("selector-id", "#" + INTERP_IDENT_RE),
      IDENT_MODE("selector-class", "\\." + INTERP_IDENT_RE, 0),
      IDENT_MODE("selector-tag", "&", 0),
      modes.ATTRIBUTE_SELECTOR_MODE,
      {
        className: "selector-pseudo",
        begin: ":(" + PSEUDO_CLASSES2.join("|") + ")"
      },
      {
        className: "selector-pseudo",
        begin: ":(:)?(" + PSEUDO_ELEMENTS2.join("|") + ")"
      },
      {
        begin: /\(/,
        end: /\)/,
        relevance: 0,
        contains: VALUE_WITH_RULESETS
      },
      // argument list of parametric mixins
      { begin: "!important" },
      // eat !important after mixin call or it will be colored as tag
      modes.FUNCTION_DISPATCH
    ]
  };
  const PSEUDO_SELECTOR_MODE = {
    begin: IDENT_RE3 + `:(:)?(${PSEUDO_SELECTORS$1.join("|")})`,
    returnBegin: true,
    contains: [SELECTOR_MODE]
  };
  RULES.push(
    hljs.C_LINE_COMMENT_MODE,
    hljs.C_BLOCK_COMMENT_MODE,
    AT_RULE_MODE,
    VAR_RULE_MODE,
    PSEUDO_SELECTOR_MODE,
    RULE_MODE,
    SELECTOR_MODE,
    MIXIN_GUARD_MODE,
    modes.FUNCTION_DISPATCH
  );
  return {
    name: "Less",
    case_insensitive: true,
    illegal: `[=>'/<($"]`,
    contains: RULES
  };
}
__name(less, "less");

// node_modules/highlight.js/es/languages/lua.js
init_esbuild_shims();
function lua(hljs) {
  const OPENING_LONG_BRACKET = "\\[=*\\[";
  const CLOSING_LONG_BRACKET = "\\]=*\\]";
  const LONG_BRACKETS = {
    begin: OPENING_LONG_BRACKET,
    end: CLOSING_LONG_BRACKET,
    contains: ["self"]
  };
  const COMMENTS = [
    hljs.COMMENT("--(?!" + OPENING_LONG_BRACKET + ")", "$"),
    hljs.COMMENT(
      "--" + OPENING_LONG_BRACKET,
      CLOSING_LONG_BRACKET,
      {
        contains: [LONG_BRACKETS],
        relevance: 10
      }
    )
  ];
  return {
    name: "Lua",
    aliases: ["pluto"],
    keywords: {
      $pattern: hljs.UNDERSCORE_IDENT_RE,
      literal: "true false nil",
      keyword: "and break do else elseif end for goto if in local not or repeat return then until while",
      built_in: (
        // Metatags and globals:
        "_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len __gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall arg self coroutine resume yield status wrap create running debug getupvalue debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv io lines write close flush open output type read stderr stdin input stdout popen tmpfile math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower table setn insert getn foreachi maxn foreach concat sort remove"
      )
    },
    contains: COMMENTS.concat([
      {
        className: "function",
        beginKeywords: "function",
        end: "\\)",
        contains: [
          hljs.inherit(hljs.TITLE_MODE, { begin: "([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*" }),
          {
            className: "params",
            begin: "\\(",
            endsWithParent: true,
            contains: COMMENTS
          }
        ].concat(COMMENTS)
      },
      hljs.C_NUMBER_MODE,
      hljs.APOS_STRING_MODE,
      hljs.QUOTE_STRING_MODE,
      {
        className: "string",
        begin: OPENING_LONG_BRACKET,
        end: CLOSING_LONG_BRACKET,
        contains: [LONG_BRACKETS],
        relevance: 5
      }
    ])
  };
}
__name(lua, "lua");

// node_modules/highlight.js/es/languages/makefile.js
init_esbuild_shims();
function makefile(hljs) {
  const VARIABLE = {
    className: "variable",
    variants: [
      {
        begin: "\\$\\(" + hljs.UNDERSCORE_IDENT_RE + "\\)",
        contains: [hljs.BACKSLASH_ESCAPE]
      },
      { begin: /\$[@%<?\^\+\*]/ }
    ]
  };
  const QUOTE_STRING = {
    className: "string",
    begin: /"/,
    end: /"/,
    contains: [
      hljs.BACKSLASH_ESCAPE,
      VARIABLE
    ]
  };
  const FUNC = {
    className: "variable",
    begin: /\$\([\w-]+\s/,
    end: /\)/,
    keywords: { built_in: "subst patsubst strip findstring filter filter-out sort word wordlist firstword lastword dir notdir suffix basename addsuffix addprefix join wildcard realpath abspath error warning shell origin flavor foreach if or and call eval file value" },
    contains: [
      VARIABLE,
      QUOTE_STRING
      // Added QUOTE_STRING as they can be a part of functions
    ]
  };
  const ASSIGNMENT = { begin: "^" + hljs.UNDERSCORE_IDENT_RE + "\\s*(?=[:+?]?=)" };
  const META2 = {
    className: "meta",
    begin: /^\.PHONY:/,
    end: /$/,
    keywords: {
      $pattern: /[\.\w]+/,
      keyword: ".PHONY"
    }
  };
  const TARGET = {
    className: "section",
    begin: /^[^\s]+:/,
    end: /$/,
    contains: [VARIABLE]
  };
  return {
    name: "Makefile",
    aliases: [
      "mk",
      "mak",
      "make"
    ],
    keywords: {
      $pattern: /[\w-]+/,
      keyword: "define endef undefine ifdef ifndef ifeq ifneq else endif include -include sinclude override export unexport private vpath"
    },
    contains: [
      hljs.HASH_COMMENT_MODE,
      VARIABLE,
      QUOTE_STRING,
      FUNC,
      ASSIGNMENT,
      META2,
      TARGET
    ]
  };
}
__name(makefile, "makefile");

// node_modules/highlight.js/es/languages/markdown.js
init_esbuild_shims();
function markdown(hljs) {
  const regex3 = hljs.regex;
  const INLINE_HTML = {
    begin: /<\/?[A-Za-z_]/,
    end: ">",
    subLanguage: "xml",
    relevance: 0
  };
  const HORIZONTAL_RULE = {
    begin: "^[-\\*]{3,}",
    end: "$"
  };
  const CODE = {
    className: "code",
    variants: [
      // TODO: fix to allow these to work with sublanguage also
      { begin: "(`{3,})[^`](.|\\n)*?\\1`*[ ]*" },
      { begin: "(~{3,})[^~](.|\\n)*?\\1~*[ ]*" },
      // needed to allow markdown as a sublanguage to work
      {
        begin: "```",
        end: "```+[ ]*$"
      },
      {
        begin: "~~~",
        end: "~~~+[ ]*$"
      },
      { begin: "`.+?`" },
      {
        begin: "(?=^( {4}|\\t))",
        // use contains to gobble up multiple lines to allow the block to be whatever size
        // but only have a single open/close tag vs one per line
        contains: [
          {
            begin: "^( {4}|\\t)",
            end: "(\\n)$"
          }
        ],
        relevance: 0
      }
    ]
  };
  const LIST2 = {
    className: "bullet",
    begin: "^[ 	]*([*+-]|(\\d+\\.))(?=\\s+)",
    end: "\\s+",
    excludeEnd: true
  };
  const LINK_REFERENCE = {
    begin: /^\[[^\n]+\]:/,
    returnBegin: true,
    contains: [
      {
        className: "symbol",
        begin: /\[/,
        end: /\]/,
        excludeBegin: true,
        excludeEnd: true
      },
      {
        className: "link",
        begin: /:\s*/,
        end: /$/,
        excludeBegin: true
      }
    ]
  };
  const URL_SCHEME = /[A-Za-z][A-Za-z0-9+.-]*/;
  const LINK2 = {
    variants: [
      // too much like nested array access in so many languages
      // to have any real relevance
      {
        begin: /\[.+?\]\[.*?\]/,
        relevance: 0
      },
      // popular internet URLs
      {
        begin: /\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,
        relevance: 2
      },
      {
        begin: regex3.concat(/\[.+?\]\(/, URL_SCHEME, /:\/\/.*?\)/),
        relevance: 2
      },
      // relative urls
      {
        begin: /\[.+?\]\([./?&#].*?\)/,
        relevance: 1
      },
      // whatever else, lower relevance (might not be a link at all)
      {
        begin: /\[.*?\]\(.*?\)/,
        relevance: 0
      }
    ],
    returnBegin: true,
    contains: [
      {
        // empty strings for alt or link text
        match: /\[(?=\])/
      },
      {
        className: "string",
        relevance: 0,
        begin: "\\[",
        end: "\\]",
        excludeBegin: true,
        returnEnd: true
      },
      {
        className: "link",
        relevance: 0,
        begin: "\\]\\(",
        end: "\\)",
        excludeBegin: true,
        excludeEnd: true
      },
      {
        className: "symbol",
        relevance: 0,
        begin: "\\]\\[",
        end: "\\]",
        excludeBegin: true,
        excludeEnd: true
      }
    ]
  };
  const BOLD = {
    className: "strong",
    contains: [],
    // defined later
    variants: [
      {
        begin: /_{2}(?!\s)/,
        end: /_{2}/
      },
      {
        begin: /\*{2}(?!\s)/,
        end: /\*{2}/
      }
    ]
  };
  const ITALIC = {
    className: "emphasis",
    contains: [],
    // defined later
    variants: [
      {
        begin: /\*(?![*\s])/,
        end: /\*/
      },
      {
        begin: /_(?![_\s])/,
        end: /_/,
        relevance: 0
      }
    ]
  };
  const BOLD_WITHOUT_ITALIC = hljs.inherit(BOLD, { contains: [] });
  const ITALIC_WITHOUT_BOLD = hljs.inherit(ITALIC, { contains: [] });
  BOLD.contains.push(ITALIC_WITHOUT_BOLD);
  ITALIC.contains.push(BOLD_WITHOUT_ITALIC);
  let CONTAINABLE = [
    INLINE_HTML,
    LINK2
  ];
  [
    BOLD,
    ITALIC,
    BOLD_WITHOUT_ITALIC,
    ITALIC_WITHOUT_BOLD
  ].forEach((m) => {
    m.contains = m.contains.concat(CONTAINABLE);
  });
  CONTAINABLE = CONTAINABLE.concat(BOLD, ITALIC);
  const HEADER2 = {
    className: "section",
    variants: [
      {
        begin: "^#{1,6}",
        end: "$",
        contains: CONTAINABLE
      },
      {
        begin: "(?=^.+?\\n[=-]{2,}$)",
        contains: [
          { begin: "^[=-]*$" },
          {
            begin: "^",
            end: "\\n",
            contains: CONTAINABLE
          }
        ]
      }
    ]
  };
  const BLOCKQUOTE = {
    className: "quote",
    begin: "^>\\s+",
    contains: CONTAINABLE,
    end: "$"
  };
  const ENTITY = {
    //https://spec.commonmark.org/0.31.2/#entity-references
    scope: "literal",
    match: /&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/
  };
  return {
    name: "Markdown",
    aliases: [
      "md",
      "mkdown",
      "mkd"
    ],
    contains: [
      HEADER2,
      INLINE_HTML,
      LIST2,
      BOLD,
      ITALIC,
      BLOCKQUOTE,
      CODE,
      HORIZONTAL_RULE,
      LINK2,
      LINK_REFERENCE,
      ENTITY
    ]
  };
}
__name(markdown, "markdown");

// node_modules/highlight.js/es/languages/objectivec.js
init_esbuild_shims();
function objectivec(hljs) {
  const API_CLASS = {
    className: "built_in",
    begin: "\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+"
  };
  const IDENTIFIER_RE = /[a-zA-Z@][a-zA-Z0-9_]*/;
  const TYPES3 = [
    "int",
    "float",
    "char",
    "unsigned",
    "signed",
    "short",
    "long",
    "double",
    "wchar_t",
    "unichar",
    "void",
    "bool",
    "BOOL",
    "id|0",
    "_Bool"
  ];
  const KWS = [
    "while",
    "export",
    "sizeof",
    "typedef",
    "const",
    "struct",
    "for",
    "union",
    "volatile",
    "static",
    "mutable",
    "if",
    "do",
    "return",
    "goto",
    "enum",
    "else",
    "break",
    "extern",
    "asm",
    "case",
    "default",
    "register",
    "explicit",
    "typename",
    "switch",
    "continue",
    "inline",
    "readonly",
    "assign",
    "readwrite",
    "self",
    "@synchronized",
    "id",
    "typeof",
    "nonatomic",
    "IBOutlet",
    "IBAction",
    "strong",
    "weak",
    "copy",
    "in",
    "out",
    "inout",
    "bycopy",
    "byref",
    "oneway",
    "__strong",
    "__weak",
    "__block",
    "__autoreleasing",
    "@private",
    "@protected",
    "@public",
    "@try",
    "@property",
    "@end",
    "@throw",
    "@catch",
    "@finally",
    "@autoreleasepool",
    "@synthesize",
    "@dynamic",
    "@selector",
    "@optional",
    "@required",
    "@encode",
    "@package",
    "@import",
    "@defs",
    "@compatibility_alias",
    "__bridge",
    "__bridge_transfer",
    "__bridge_retained",
    "__bridge_retain",
    "__covariant",
    "__contravariant",
    "__kindof",
    "_Nonnull",
    "_Nullable",
    "_Null_unspecified",
    "__FUNCTION__",
    "__PRETTY_FUNCTION__",
    "__attribute__",
    "getter",
    "setter",
    "retain",
    "unsafe_unretained",
    "nonnull",
    "nullable",
    "null_unspecified",
    "null_resettable",
    "class",
    "instancetype",
    "NS_DESIGNATED_INITIALIZER",
    "NS_UNAVAILABLE",
    "NS_REQUIRES_SUPER",
    "NS_RETURNS_INNER_POINTER",
    "NS_INLINE",
    "NS_AVAILABLE",
    "NS_DEPRECATED",
    "NS_ENUM",
    "NS_OPTIONS",
    "NS_SWIFT_UNAVAILABLE",
    "NS_ASSUME_NONNULL_BEGIN",
    "NS_ASSUME_NONNULL_END",
    "NS_REFINED_FOR_SWIFT",
    "NS_SWIFT_NAME",
    "NS_SWIFT_NOTHROW",
    "NS_DURING",
    "NS_HANDLER",
    "NS_ENDHANDLER",
    "NS_VALUERETURN",
    "NS_VOIDRETURN"
  ];
  const LITERALS3 = [
    "false",
    "true",
    "FALSE",
    "TRUE",
    "nil",
    "YES",
    "NO",
    "NULL"
  ];
  const BUILT_INS3 = [
    "dispatch_once_t",
    "dispatch_queue_t",
    "dispatch_sync",
    "dispatch_async",
    "dispatch_once"
  ];
  const KEYWORDS3 = {
    "variable.language": [
      "this",
      "super"
    ],
    $pattern: IDENTIFIER_RE,
    keyword: KWS,
    literal: LITERALS3,
    built_in: BUILT_INS3,
    type: TYPES3
  };
  const CLASS_KEYWORDS = {
    $pattern: IDENTIFIER_RE,
    keyword: [
      "@interface",
      "@class",
      "@protocol",
      "@implementation"
    ]
  };
  return {
    name: "Objective-C",
    aliases: [
      "mm",
      "objc",
      "obj-c",
      "obj-c++",
      "objective-c++"
    ],
    keywords: KEYWORDS3,
    illegal: "</",
    contains: [
      API_CLASS,
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.C_NUMBER_MODE,
      hljs.QUOTE_STRING_MODE,
      hljs.APOS_STRING_MODE,
      {
        className: "string",
        variants: [
          {
            begin: '@"',
            end: '"',
            illegal: "\\n",
            contains: [hljs.BACKSLASH_ESCAPE]
          }
        ]
      },
      {
        className: "meta",
        begin: /#\s*[a-z]+\b/,
        end: /$/,
        keywords: { keyword: "if else elif endif define undef warning error line pragma ifdef ifndef include" },
        contains: [
          {
            begin: /\\\n/,
            relevance: 0
          },
          hljs.inherit(hljs.QUOTE_STRING_MODE, { className: "string" }),
          {
            className: "string",
            begin: /<.*?>/,
            end: /$/,
            illegal: "\\n"
          },
          hljs.C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE
        ]
      },
      {
        className: "class",
        begin: "(" + CLASS_KEYWORDS.keyword.join("|") + ")\\b",
        end: /(\{|$)/,
        excludeEnd: true,
        keywords: CLASS_KEYWORDS,
        contains: [hljs.UNDERSCORE_TITLE_MODE]
      },
      {
        begin: "\\." + hljs.UNDERSCORE_IDENT_RE,
        relevance: 0
      }
    ]
  };
}
__name(objectivec, "objectivec");

// node_modules/highlight.js/es/languages/perl.js
init_esbuild_shims();
function perl(hljs) {
  const regex3 = hljs.regex;
  const KEYWORDS3 = [
    "abs",
    "accept",
    "alarm",
    "and",
    "atan2",
    "bind",
    "binmode",
    "bless",
    "break",
    "caller",
    "chdir",
    "chmod",
    "chomp",
    "chop",
    "chown",
    "chr",
    "chroot",
    "class",
    "close",
    "closedir",
    "connect",
    "continue",
    "cos",
    "crypt",
    "dbmclose",
    "dbmopen",
    "defined",
    "delete",
    "die",
    "do",
    "dump",
    "each",
    "else",
    "elsif",
    "endgrent",
    "endhostent",
    "endnetent",
    "endprotoent",
    "endpwent",
    "endservent",
    "eof",
    "eval",
    "exec",
    "exists",
    "exit",
    "exp",
    "fcntl",
    "field",
    "fileno",
    "flock",
    "for",
    "foreach",
    "fork",
    "format",
    "formline",
    "getc",
    "getgrent",
    "getgrgid",
    "getgrnam",
    "gethostbyaddr",
    "gethostbyname",
    "gethostent",
    "getlogin",
    "getnetbyaddr",
    "getnetbyname",
    "getnetent",
    "getpeername",
    "getpgrp",
    "getpriority",
    "getprotobyname",
    "getprotobynumber",
    "getprotoent",
    "getpwent",
    "getpwnam",
    "getpwuid",
    "getservbyname",
    "getservbyport",
    "getservent",
    "getsockname",
    "getsockopt",
    "given",
    "glob",
    "gmtime",
    "goto",
    "grep",
    "gt",
    "hex",
    "if",
    "index",
    "int",
    "ioctl",
    "join",
    "keys",
    "kill",
    "last",
    "lc",
    "lcfirst",
    "length",
    "link",
    "listen",
    "local",
    "localtime",
    "log",
    "lstat",
    "lt",
    "ma",
    "map",
    "method",
    "mkdir",
    "msgctl",
    "msgget",
    "msgrcv",
    "msgsnd",
    "my",
    "ne",
    "next",
    "no",
    "not",
    "oct",
    "open",
    "opendir",
    "or",
    "ord",
    "our",
    "pack",
    "package",
    "pipe",
    "pop",
    "pos",
    "print",
    "printf",
    "prototype",
    "push",
    "q|0",
    "qq",
    "quotemeta",
    "qw",
    "qx",
    "rand",
    "read",
    "readdir",
    "readline",
    "readlink",
    "readpipe",
    "recv",
    "redo",
    "ref",
    "rename",
    "require",
    "reset",
    "return",
    "reverse",
    "rewinddir",
    "rindex",
    "rmdir",
    "say",
    "scalar",
    "seek",
    "seekdir",
    "select",
    "semctl",
    "semget",
    "semop",
    "send",
    "setgrent",
    "sethostent",
    "setnetent",
    "setpgrp",
    "setpriority",
    "setprotoent",
    "setpwent",
    "setservent",
    "setsockopt",
    "shift",
    "shmctl",
    "shmget",
    "shmread",
    "shmwrite",
    "shutdown",
    "sin",
    "sleep",
    "socket",
    "socketpair",
    "sort",
    "splice",
    "split",
    "sprintf",
    "sqrt",
    "srand",
    "stat",
    "state",
    "study",
    "sub",
    "substr",
    "symlink",
    "syscall",
    "sysopen",
    "sysread",
    "sysseek",
    "system",
    "syswrite",
    "tell",
    "telldir",
    "tie",
    "tied",
    "time",
    "times",
    "tr",
    "truncate",
    "uc",
    "ucfirst",
    "umask",
    "undef",
    "unless",
    "unlink",
    "unpack",
    "unshift",
    "untie",
    "until",
    "use",
    "utime",
    "values",
    "vec",
    "wait",
    "waitpid",
    "wantarray",
    "warn",
    "when",
    "while",
    "write",
    "x|0",
    "xor",
    "y|0"
  ];
  const REGEX_MODIFIERS = /[dualxmsipngr]{0,12}/;
  const PERL_KEYWORDS = {
    $pattern: /[\w.]+/,
    keyword: KEYWORDS3.join(" ")
  };
  const SUBST = {
    className: "subst",
    begin: "[$@]\\{",
    end: "\\}",
    keywords: PERL_KEYWORDS
  };
  const METHOD = {
    begin: /->\{/,
    end: /\}/
    // contains defined later
  };
  const ATTR = {
    scope: "attr",
    match: /\s+:\s*\w+(\s*\(.*?\))?/
  };
  const VAR = {
    scope: "variable",
    variants: [
      { begin: /\$\d/ },
      {
        begin: regex3.concat(
          /[$%@](?!")(\^\w\b|#\w+(::\w+)*|\{\w+\}|\w+(::\w*)*)/,
          // negative look-ahead tries to avoid matching patterns that are not
          // Perl at all like $ident$, @ident@, etc.
          `(?![A-Za-z])(?![@$%])`
        )
      },
      {
        // Only $= is a special Perl variable and one can't declare @= or %=.
        begin: /[$%@](?!")[^\s\w{=]|\$=/,
        relevance: 0
      }
    ],
    contains: [ATTR]
  };
  const NUMBER = {
    className: "number",
    variants: [
      // decimal numbers:
      // include the case where a number starts with a dot (eg. .9), and
      // the leading 0? avoids mixing the first and second match on 0.x cases
      { match: /0?\.[0-9][0-9_]+\b/ },
      // include the special versioned number (eg. v5.38)
      { match: /\bv?(0|[1-9][0-9_]*(\.[0-9_]+)?|[1-9][0-9_]*)\b/ },
      // non-decimal numbers:
      { match: /\b0[0-7][0-7_]*\b/ },
      { match: /\b0x[0-9a-fA-F][0-9a-fA-F_]*\b/ },
      { match: /\b0b[0-1][0-1_]*\b/ }
    ],
    relevance: 0
  };
  const STRING_CONTAINS = [
    hljs.BACKSLASH_ESCAPE,
    SUBST,
    VAR
  ];
  const REGEX_DELIMS = [
    /!/,
    /\//,
    /\|/,
    /\?/,
    /'/,
    /"/,
    // valid but infrequent and weird
    /#/
    // valid but infrequent and weird
  ];
  const PAIRED_DOUBLE_RE = /* @__PURE__ */ __name((prefix, open3, close = "\\1") => {
    const middle2 = close === "\\1" ? close : regex3.concat(close, open3);
    return regex3.concat(
      regex3.concat("(?:", prefix, ")"),
      open3,
      /(?:\\.|[^\\\/])*?/,
      middle2,
      /(?:\\.|[^\\\/])*?/,
      close,
      REGEX_MODIFIERS
    );
  }, "PAIRED_DOUBLE_RE");
  const PAIRED_RE = /* @__PURE__ */ __name((prefix, open3, close) => {
    return regex3.concat(
      regex3.concat("(?:", prefix, ")"),
      open3,
      /(?:\\.|[^\\\/])*?/,
      close,
      REGEX_MODIFIERS
    );
  }, "PAIRED_RE");
  const PERL_DEFAULT_CONTAINS = [
    VAR,
    hljs.HASH_COMMENT_MODE,
    hljs.COMMENT(
      /^=\w/,
      /=cut/,
      { endsWithParent: true }
    ),
    METHOD,
    {
      className: "string",
      contains: STRING_CONTAINS,
      variants: [
        {
          begin: "q[qwxr]?\\s*\\(",
          end: "\\)",
          relevance: 5
        },
        {
          begin: "q[qwxr]?\\s*\\[",
          end: "\\]",
          relevance: 5
        },
        {
          begin: "q[qwxr]?\\s*\\{",
          end: "\\}",
          relevance: 5
        },
        {
          begin: "q[qwxr]?\\s*\\|",
          end: "\\|",
          relevance: 5
        },
        {
          begin: "q[qwxr]?\\s*<",
          end: ">",
          relevance: 5
        },
        {
          begin: "qw\\s+q",
          end: "q",
          relevance: 5
        },
        {
          begin: "'",
          end: "'",
          contains: [hljs.BACKSLASH_ESCAPE]
        },
        {
          begin: '"',
          end: '"'
        },
        {
          begin: "`",
          end: "`",
          contains: [hljs.BACKSLASH_ESCAPE]
        },
        {
          begin: /\{\w+\}/,
          relevance: 0
        },
        {
          begin: "-?\\w+\\s*=>",
          relevance: 0
        }
      ]
    },
    NUMBER,
    {
      // regexp container
      begin: "(\\/\\/|" + hljs.RE_STARTERS_RE + "|\\b(split|return|print|reverse|grep)\\b)\\s*",
      keywords: "split return print reverse grep",
      relevance: 0,
      contains: [
        hljs.HASH_COMMENT_MODE,
        {
          className: "regexp",
          variants: [
            // allow matching common delimiters
            { begin: PAIRED_DOUBLE_RE("s|tr|y", regex3.either(...REGEX_DELIMS, { capture: true })) },
            // and then paired delmis
            { begin: PAIRED_DOUBLE_RE("s|tr|y", "\\(", "\\)") },
            { begin: PAIRED_DOUBLE_RE("s|tr|y", "\\[", "\\]") },
            { begin: PAIRED_DOUBLE_RE("s|tr|y", "\\{", "\\}") }
          ],
          relevance: 2
        },
        {
          className: "regexp",
          variants: [
            {
              // could be a comment in many languages so do not count
              // as relevant
              begin: /(m|qr)\/\//,
              relevance: 0
            },
            // prefix is optional with /regex/
            { begin: PAIRED_RE("(?:m|qr)?", /\//, /\//) },
            // allow matching common delimiters
            { begin: PAIRED_RE("m|qr", regex3.either(...REGEX_DELIMS, { capture: true }), /\1/) },
            // allow common paired delmins
            { begin: PAIRED_RE("m|qr", /\(/, /\)/) },
            { begin: PAIRED_RE("m|qr", /\[/, /\]/) },
            { begin: PAIRED_RE("m|qr", /\{/, /\}/) }
          ]
        }
      ]
    },
    {
      className: "function",
      beginKeywords: "sub method",
      end: "(\\s*\\(.*?\\))?[;{]",
      excludeEnd: true,
      relevance: 5,
      contains: [hljs.TITLE_MODE, ATTR]
    },
    {
      className: "class",
      beginKeywords: "class",
      end: "[;{]",
      excludeEnd: true,
      relevance: 5,
      contains: [hljs.TITLE_MODE, ATTR, NUMBER]
    },
    {
      begin: "-\\w\\b",
      relevance: 0
    },
    {
      begin: "^__DATA__$",
      end: "^__END__$",
      subLanguage: "mojolicious",
      contains: [
        {
          begin: "^@@.*",
          end: "$",
          className: "comment"
        }
      ]
    }
  ];
  SUBST.contains = PERL_DEFAULT_CONTAINS;
  METHOD.contains = PERL_DEFAULT_CONTAINS;
  return {
    name: "Perl",
    aliases: [
      "pl",
      "pm"
    ],
    keywords: PERL_KEYWORDS,
    contains: PERL_DEFAULT_CONTAINS
  };
}
__name(perl, "perl");

// node_modules/highlight.js/es/languages/php.js
init_esbuild_shims();
function php(hljs) {
  const regex3 = hljs.regex;
  const NOT_PERL_ETC = /(?![A-Za-z0-9])(?![$])/;
  const IDENT_RE3 = regex3.concat(
    /[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/,
    NOT_PERL_ETC
  );
  const PASCAL_CASE_CLASS_NAME_RE = regex3.concat(
    /(\\?[A-Z][a-z0-9_\x7f-\xff]+|\\?[A-Z]+(?=[A-Z][a-z0-9_\x7f-\xff])){1,}/,
    NOT_PERL_ETC
  );
  const UPCASE_NAME_RE = regex3.concat(
    /[A-Z]+/,
    NOT_PERL_ETC
  );
  const VARIABLE = {
    scope: "variable",
    match: "\\$+" + IDENT_RE3
  };
  const PREPROCESSOR = {
    scope: "meta",
    variants: [
      { begin: /<\?php/, relevance: 10 },
      // boost for obvious PHP
      { begin: /<\?=/ },
      // less relevant per PSR-1 which says not to use short-tags
      { begin: /<\?/, relevance: 0.1 },
      { begin: /\?>/ }
      // end php tag
    ]
  };
  const SUBST = {
    scope: "subst",
    variants: [
      { begin: /\$\w+/ },
      {
        begin: /\{\$/,
        end: /\}/
      }
    ]
  };
  const SINGLE_QUOTED = hljs.inherit(hljs.APOS_STRING_MODE, { illegal: null });
  const DOUBLE_QUOTED = hljs.inherit(hljs.QUOTE_STRING_MODE, {
    illegal: null,
    contains: hljs.QUOTE_STRING_MODE.contains.concat(SUBST)
  });
  const HEREDOC = {
    begin: /<<<[ \t]*(?:(\w+)|"(\w+)")\n/,
    end: /[ \t]*(\w+)\b/,
    contains: hljs.QUOTE_STRING_MODE.contains.concat(SUBST),
    "on:begin": /* @__PURE__ */ __name((m, resp) => {
      resp.data._beginMatch = m[1] || m[2];
    }, "on:begin"),
    "on:end": /* @__PURE__ */ __name((m, resp) => {
      if (resp.data._beginMatch !== m[1]) resp.ignoreMatch();
    }, "on:end")
  };
  const NOWDOC = hljs.END_SAME_AS_BEGIN({
    begin: /<<<[ \t]*'(\w+)'\n/,
    end: /[ \t]*(\w+)\b/
  });
  const WHITESPACE = "[ 	\n]";
  const STRING = {
    scope: "string",
    variants: [
      DOUBLE_QUOTED,
      SINGLE_QUOTED,
      HEREDOC,
      NOWDOC
    ]
  };
  const NUMBER = {
    scope: "number",
    variants: [
      { begin: `\\b0[bB][01]+(?:_[01]+)*\\b` },
      // Binary w/ underscore support
      { begin: `\\b0[oO][0-7]+(?:_[0-7]+)*\\b` },
      // Octals w/ underscore support
      { begin: `\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b` },
      // Hex w/ underscore support
      // Decimals w/ underscore support, with optional fragments and scientific exponent (e) suffix.
      { begin: `(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?` }
    ],
    relevance: 0
  };
  const LITERALS3 = [
    "false",
    "null",
    "true"
  ];
  const KWS = [
    // Magic constants:
    // <https://www.php.net/manual/en/language.constants.predefined.php>
    "__CLASS__",
    "__DIR__",
    "__FILE__",
    "__FUNCTION__",
    "__COMPILER_HALT_OFFSET__",
    "__LINE__",
    "__METHOD__",
    "__NAMESPACE__",
    "__TRAIT__",
    // Function that look like language construct or language construct that look like function:
    // List of keywords that may not require parenthesis
    "die",
    "echo",
    "exit",
    "include",
    "include_once",
    "print",
    "require",
    "require_once",
    // These are not language construct (function) but operate on the currently-executing function and can access the current symbol table
    // 'compact extract func_get_arg func_get_args func_num_args get_called_class get_parent_class ' +
    // Other keywords:
    // <https://www.php.net/manual/en/reserved.php>
    // <https://www.php.net/manual/en/language.types.type-juggling.php>
    "array",
    "abstract",
    "and",
    "as",
    "binary",
    "bool",
    "boolean",
    "break",
    "callable",
    "case",
    "catch",
    "class",
    "clone",
    "const",
    "continue",
    "declare",
    "default",
    "do",
    "double",
    "else",
    "elseif",
    "empty",
    "enddeclare",
    "endfor",
    "endforeach",
    "endif",
    "endswitch",
    "endwhile",
    "enum",
    "eval",
    "extends",
    "final",
    "finally",
    "float",
    "for",
    "foreach",
    "from",
    "global",
    "goto",
    "if",
    "implements",
    "instanceof",
    "insteadof",
    "int",
    "integer",
    "interface",
    "isset",
    "iterable",
    "list",
    "match|0",
    "mixed",
    "new",
    "never",
    "object",
    "or",
    "private",
    "protected",
    "public",
    "readonly",
    "real",
    "return",
    "string",
    "switch",
    "throw",
    "trait",
    "try",
    "unset",
    "use",
    "var",
    "void",
    "while",
    "xor",
    "yield"
  ];
  const BUILT_INS3 = [
    // Standard PHP library:
    // <https://www.php.net/manual/en/book.spl.php>
    "Error|0",
    "AppendIterator",
    "ArgumentCountError",
    "ArithmeticError",
    "ArrayIterator",
    "ArrayObject",
    "AssertionError",
    "BadFunctionCallException",
    "BadMethodCallException",
    "CachingIterator",
    "CallbackFilterIterator",
    "CompileError",
    "Countable",
    "DirectoryIterator",
    "DivisionByZeroError",
    "DomainException",
    "EmptyIterator",
    "ErrorException",
    "Exception",
    "FilesystemIterator",
    "FilterIterator",
    "GlobIterator",
    "InfiniteIterator",
    "InvalidArgumentException",
    "IteratorIterator",
    "LengthException",
    "LimitIterator",
    "LogicException",
    "MultipleIterator",
    "NoRewindIterator",
    "OutOfBoundsException",
    "OutOfRangeException",
    "OuterIterator",
    "OverflowException",
    "ParentIterator",
    "ParseError",
    "RangeException",
    "RecursiveArrayIterator",
    "RecursiveCachingIterator",
    "RecursiveCallbackFilterIterator",
    "RecursiveDirectoryIterator",
    "RecursiveFilterIterator",
    "RecursiveIterator",
    "RecursiveIteratorIterator",
    "RecursiveRegexIterator",
    "RecursiveTreeIterator",
    "RegexIterator",
    "RuntimeException",
    "SeekableIterator",
    "SplDoublyLinkedList",
    "SplFileInfo",
    "SplFileObject",
    "SplFixedArray",
    "SplHeap",
    "SplMaxHeap",
    "SplMinHeap",
    "SplObjectStorage",
    "SplObserver",
    "SplPriorityQueue",
    "SplQueue",
    "SplStack",
    "SplSubject",
    "SplTempFileObject",
    "TypeError",
    "UnderflowException",
    "UnexpectedValueException",
    "UnhandledMatchError",
    // Reserved interfaces:
    // <https://www.php.net/manual/en/reserved.interfaces.php>
    "ArrayAccess",
    "BackedEnum",
    "Closure",
    "Fiber",
    "Generator",
    "Iterator",
    "IteratorAggregate",
    "Serializable",
    "Stringable",
    "Throwable",
    "Traversable",
    "UnitEnum",
    "WeakReference",
    "WeakMap",
    // Reserved classes:
    // <https://www.php.net/manual/en/reserved.classes.php>
    "Directory",
    "__PHP_Incomplete_Class",
    "parent",
    "php_user_filter",
    "self",
    "static",
    "stdClass"
  ];
  const dualCase = /* @__PURE__ */ __name((items) => {
    const result = [];
    items.forEach((item) => {
      result.push(item);
      if (item.toLowerCase() === item) {
        result.push(item.toUpperCase());
      } else {
        result.push(item.toLowerCase());
      }
    });
    return result;
  }, "dualCase");
  const KEYWORDS3 = {
    keyword: KWS,
    literal: dualCase(LITERALS3),
    built_in: BUILT_INS3
  };
  const normalizeKeywords = /* @__PURE__ */ __name((items) => {
    return items.map((item) => {
      return item.replace(/\|\d+$/, "");
    });
  }, "normalizeKeywords");
  const CONSTRUCTOR_CALL = { variants: [
    {
      match: [
        /new/,
        regex3.concat(WHITESPACE, "+"),
        // to prevent built ins from being confused as the class constructor call
        regex3.concat("(?!", normalizeKeywords(BUILT_INS3).join("\\b|"), "\\b)"),
        PASCAL_CASE_CLASS_NAME_RE
      ],
      scope: {
        1: "keyword",
        4: "title.class"
      }
    }
  ] };
  const CONSTANT_REFERENCE = regex3.concat(IDENT_RE3, "\\b(?!\\()");
  const LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON = { variants: [
    {
      match: [
        regex3.concat(
          /::/,
          regex3.lookahead(/(?!class\b)/)
        ),
        CONSTANT_REFERENCE
      ],
      scope: { 2: "variable.constant" }
    },
    {
      match: [
        /::/,
        /class/
      ],
      scope: { 2: "variable.language" }
    },
    {
      match: [
        PASCAL_CASE_CLASS_NAME_RE,
        regex3.concat(
          /::/,
          regex3.lookahead(/(?!class\b)/)
        ),
        CONSTANT_REFERENCE
      ],
      scope: {
        1: "title.class",
        3: "variable.constant"
      }
    },
    {
      match: [
        PASCAL_CASE_CLASS_NAME_RE,
        regex3.concat(
          "::",
          regex3.lookahead(/(?!class\b)/)
        )
      ],
      scope: { 1: "title.class" }
    },
    {
      match: [
        PASCAL_CASE_CLASS_NAME_RE,
        /::/,
        /class/
      ],
      scope: {
        1: "title.class",
        3: "variable.language"
      }
    }
  ] };
  const NAMED_ARGUMENT = {
    scope: "attr",
    match: regex3.concat(IDENT_RE3, regex3.lookahead(":"), regex3.lookahead(/(?!::)/))
  };
  const PARAMS_MODE = {
    relevance: 0,
    begin: /\(/,
    end: /\)/,
    keywords: KEYWORDS3,
    contains: [
      NAMED_ARGUMENT,
      VARIABLE,
      LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON,
      hljs.C_BLOCK_COMMENT_MODE,
      STRING,
      NUMBER,
      CONSTRUCTOR_CALL
    ]
  };
  const FUNCTION_INVOKE = {
    relevance: 0,
    match: [
      /\b/,
      // to prevent keywords from being confused as the function title
      regex3.concat("(?!fn\\b|function\\b|", normalizeKeywords(KWS).join("\\b|"), "|", normalizeKeywords(BUILT_INS3).join("\\b|"), "\\b)"),
      IDENT_RE3,
      regex3.concat(WHITESPACE, "*"),
      regex3.lookahead(/(?=\()/)
    ],
    scope: { 3: "title.function.invoke" },
    contains: [PARAMS_MODE]
  };
  PARAMS_MODE.contains.push(FUNCTION_INVOKE);
  const ATTRIBUTE_CONTAINS = [
    NAMED_ARGUMENT,
    LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON,
    hljs.C_BLOCK_COMMENT_MODE,
    STRING,
    NUMBER,
    CONSTRUCTOR_CALL
  ];
  const ATTRIBUTES4 = {
    begin: regex3.concat(
      /#\[\s*\\?/,
      regex3.either(
        PASCAL_CASE_CLASS_NAME_RE,
        UPCASE_NAME_RE
      )
    ),
    beginScope: "meta",
    end: /]/,
    endScope: "meta",
    keywords: {
      literal: LITERALS3,
      keyword: [
        "new",
        "array"
      ]
    },
    contains: [
      {
        begin: /\[/,
        end: /]/,
        keywords: {
          literal: LITERALS3,
          keyword: [
            "new",
            "array"
          ]
        },
        contains: [
          "self",
          ...ATTRIBUTE_CONTAINS
        ]
      },
      ...ATTRIBUTE_CONTAINS,
      {
        scope: "meta",
        variants: [
          { match: PASCAL_CASE_CLASS_NAME_RE },
          { match: UPCASE_NAME_RE }
        ]
      }
    ]
  };
  return {
    case_insensitive: false,
    keywords: KEYWORDS3,
    contains: [
      ATTRIBUTES4,
      hljs.HASH_COMMENT_MODE,
      hljs.COMMENT("//", "$"),
      hljs.COMMENT(
        "/\\*",
        "\\*/",
        { contains: [
          {
            scope: "doctag",
            match: "@[A-Za-z]+"
          }
        ] }
      ),
      {
        match: /__halt_compiler\(\);/,
        keywords: "__halt_compiler",
        starts: {
          scope: "comment",
          end: hljs.MATCH_NOTHING_RE,
          contains: [
            {
              match: /\?>/,
              scope: "meta",
              endsParent: true
            }
          ]
        }
      },
      PREPROCESSOR,
      {
        scope: "variable.language",
        match: /\$this\b/
      },
      VARIABLE,
      FUNCTION_INVOKE,
      LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON,
      {
        match: [
          /const/,
          /\s/,
          IDENT_RE3
        ],
        scope: {
          1: "keyword",
          3: "variable.constant"
        }
      },
      CONSTRUCTOR_CALL,
      {
        scope: "function",
        relevance: 0,
        beginKeywords: "fn function",
        end: /[;{]/,
        excludeEnd: true,
        illegal: "[$%\\[]",
        contains: [
          { beginKeywords: "use" },
          hljs.UNDERSCORE_TITLE_MODE,
          {
            begin: "=>",
            // No markup, just a relevance booster
            endsParent: true
          },
          {
            scope: "params",
            begin: "\\(",
            end: "\\)",
            excludeBegin: true,
            excludeEnd: true,
            keywords: KEYWORDS3,
            contains: [
              "self",
              ATTRIBUTES4,
              VARIABLE,
              LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON,
              hljs.C_BLOCK_COMMENT_MODE,
              STRING,
              NUMBER
            ]
          }
        ]
      },
      {
        scope: "class",
        variants: [
          {
            beginKeywords: "enum",
            illegal: /[($"]/
          },
          {
            beginKeywords: "class interface trait",
            illegal: /[:($"]/
          }
        ],
        relevance: 0,
        end: /\{/,
        excludeEnd: true,
        contains: [
          { beginKeywords: "extends implements" },
          hljs.UNDERSCORE_TITLE_MODE
        ]
      },
      // both use and namespace still use "old style" rules (vs multi-match)
      // because the namespace name can include `\` and we still want each
      // element to be treated as its own *individual* title
      {
        beginKeywords: "namespace",
        relevance: 0,
        end: ";",
        illegal: /[.']/,
        contains: [hljs.inherit(hljs.UNDERSCORE_TITLE_MODE, { scope: "title.class" })]
      },
      {
        beginKeywords: "use",
        relevance: 0,
        end: ";",
        contains: [
          // TODO: title.function vs title.class
          {
            match: /\b(as|const|function)\b/,
            scope: "keyword"
          },
          // TODO: could be title.class or title.function
          hljs.UNDERSCORE_TITLE_MODE
        ]
      },
      STRING,
      NUMBER
    ]
  };
}
__name(php, "php");

// node_modules/highlight.js/es/languages/php-template.js
init_esbuild_shims();
function phpTemplate(hljs) {
  return {
    name: "PHP template",
    subLanguage: "xml",
    contains: [
      {
        begin: /<\?(php|=)?/,
        end: /\?>/,
        subLanguage: "php",
        contains: [
          // We don't want the php closing tag ?> to close the PHP block when
          // inside any of the following blocks:
          {
            begin: "/\\*",
            end: "\\*/",
            skip: true
          },
          {
            begin: 'b"',
            end: '"',
            skip: true
          },
          {
            begin: "b'",
            end: "'",
            skip: true
          },
          hljs.inherit(hljs.APOS_STRING_MODE, {
            illegal: null,
            className: null,
            contains: null,
            skip: true
          }),
          hljs.inherit(hljs.QUOTE_STRING_MODE, {
            illegal: null,
            className: null,
            contains: null,
            skip: true
          })
        ]
      }
    ]
  };
}
__name(phpTemplate, "phpTemplate");

// node_modules/highlight.js/es/languages/plaintext.js
init_esbuild_shims();
function plaintext(hljs) {
  return {
    name: "Plain text",
    aliases: [
      "text",
      "txt"
    ],
    disableAutodetect: true
  };
}
__name(plaintext, "plaintext");

// node_modules/highlight.js/es/languages/python.js
init_esbuild_shims();
function python(hljs) {
  const regex3 = hljs.regex;
  const IDENT_RE3 = new RegExp("[\\p{XID_Start}_]\\p{XID_Continue}*", "u");
  const RESERVED_WORDS = [
    "and",
    "as",
    "assert",
    "async",
    "await",
    "break",
    "case",
    "class",
    "continue",
    "def",
    "del",
    "elif",
    "else",
    "except",
    "finally",
    "for",
    "from",
    "global",
    "if",
    "import",
    "in",
    "is",
    "lambda",
    "match",
    "nonlocal|10",
    "not",
    "or",
    "pass",
    "raise",
    "return",
    "try",
    "while",
    "with",
    "yield"
  ];
  const BUILT_INS3 = [
    "__import__",
    "abs",
    "all",
    "any",
    "ascii",
    "bin",
    "bool",
    "breakpoint",
    "bytearray",
    "bytes",
    "callable",
    "chr",
    "classmethod",
    "compile",
    "complex",
    "delattr",
    "dict",
    "dir",
    "divmod",
    "enumerate",
    "eval",
    "exec",
    "filter",
    "float",
    "format",
    "frozenset",
    "getattr",
    "globals",
    "hasattr",
    "hash",
    "help",
    "hex",
    "id",
    "input",
    "int",
    "isinstance",
    "issubclass",
    "iter",
    "len",
    "list",
    "locals",
    "map",
    "max",
    "memoryview",
    "min",
    "next",
    "object",
    "oct",
    "open",
    "ord",
    "pow",
    "print",
    "property",
    "range",
    "repr",
    "reversed",
    "round",
    "set",
    "setattr",
    "slice",
    "sorted",
    "staticmethod",
    "str",
    "sum",
    "super",
    "tuple",
    "type",
    "vars",
    "zip"
  ];
  const LITERALS3 = [
    "__debug__",
    "Ellipsis",
    "False",
    "None",
    "NotImplemented",
    "True"
  ];
  const TYPES3 = [
    "Any",
    "Callable",
    "Coroutine",
    "Dict",
    "List",
    "Literal",
    "Generic",
    "Optional",
    "Sequence",
    "Set",
    "Tuple",
    "Type",
    "Union"
  ];
  const KEYWORDS3 = {
    $pattern: /[A-Za-z]\w+|__\w+__/,
    keyword: RESERVED_WORDS,
    built_in: BUILT_INS3,
    literal: LITERALS3,
    type: TYPES3
  };
  const PROMPT = {
    className: "meta",
    begin: /^(>>>|\.\.\.) /
  };
  const SUBST = {
    className: "subst",
    begin: /\{/,
    end: /\}/,
    keywords: KEYWORDS3,
    illegal: /#/
  };
  const LITERAL_BRACKET = {
    begin: /\{\{/,
    relevance: 0
  };
  const STRING = {
    className: "string",
    contains: [hljs.BACKSLASH_ESCAPE],
    variants: [
      {
        begin: /([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,
        end: /'''/,
        contains: [
          hljs.BACKSLASH_ESCAPE,
          PROMPT
        ],
        relevance: 10
      },
      {
        begin: /([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,
        end: /"""/,
        contains: [
          hljs.BACKSLASH_ESCAPE,
          PROMPT
        ],
        relevance: 10
      },
      {
        begin: /([fF][rR]|[rR][fF]|[fF])'''/,
        end: /'''/,
        contains: [
          hljs.BACKSLASH_ESCAPE,
          PROMPT,
          LITERAL_BRACKET,
          SUBST
        ]
      },
      {
        begin: /([fF][rR]|[rR][fF]|[fF])"""/,
        end: /"""/,
        contains: [
          hljs.BACKSLASH_ESCAPE,
          PROMPT,
          LITERAL_BRACKET,
          SUBST
        ]
      },
      {
        begin: /([uU]|[rR])'/,
        end: /'/,
        relevance: 10
      },
      {
        begin: /([uU]|[rR])"/,
        end: /"/,
        relevance: 10
      },
      {
        begin: /([bB]|[bB][rR]|[rR][bB])'/,
        end: /'/
      },
      {
        begin: /([bB]|[bB][rR]|[rR][bB])"/,
        end: /"/
      },
      {
        begin: /([fF][rR]|[rR][fF]|[fF])'/,
        end: /'/,
        contains: [
          hljs.BACKSLASH_ESCAPE,
          LITERAL_BRACKET,
          SUBST
        ]
      },
      {
        begin: /([fF][rR]|[rR][fF]|[fF])"/,
        end: /"/,
        contains: [
          hljs.BACKSLASH_ESCAPE,
          LITERAL_BRACKET,
          SUBST
        ]
      },
      hljs.APOS_STRING_MODE,
      hljs.QUOTE_STRING_MODE
    ]
  };
  const digitpart = "[0-9](_?[0-9])*";
  const pointfloat = `(\\b(${digitpart}))?\\.(${digitpart})|\\b(${digitpart})\\.`;
  const lookahead2 = `\\b|${RESERVED_WORDS.join("|")}`;
  const NUMBER = {
    className: "number",
    relevance: 0,
    variants: [
      // exponentfloat, pointfloat
      // https://docs.python.org/3.9/reference/lexical_analysis.html#floating-point-literals
      // optionally imaginary
      // https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals
      // Note: no leading \b because floats can start with a decimal point
      // and we don't want to mishandle e.g. `fn(.5)`,
      // no trailing \b for pointfloat because it can end with a decimal point
      // and we don't want to mishandle e.g. `0..hex()`; this should be safe
      // because both MUST contain a decimal point and so cannot be confused with
      // the interior part of an identifier
      {
        begin: `(\\b(${digitpart})|(${pointfloat}))[eE][+-]?(${digitpart})[jJ]?(?=${lookahead2})`
      },
      {
        begin: `(${pointfloat})[jJ]?`
      },
      // decinteger, bininteger, octinteger, hexinteger
      // https://docs.python.org/3.9/reference/lexical_analysis.html#integer-literals
      // optionally "long" in Python 2
      // https://docs.python.org/2.7/reference/lexical_analysis.html#integer-and-long-integer-literals
      // decinteger is optionally imaginary
      // https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals
      {
        begin: `\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${lookahead2})`
      },
      {
        begin: `\\b0[bB](_?[01])+[lL]?(?=${lookahead2})`
      },
      {
        begin: `\\b0[oO](_?[0-7])+[lL]?(?=${lookahead2})`
      },
      {
        begin: `\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${lookahead2})`
      },
      // imagnumber (digitpart-based)
      // https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals
      {
        begin: `\\b(${digitpart})[jJ](?=${lookahead2})`
      }
    ]
  };
  const COMMENT_TYPE = {
    className: "comment",
    begin: regex3.lookahead(/# type:/),
    end: /$/,
    keywords: KEYWORDS3,
    contains: [
      {
        // prevent keywords from coloring `type`
        begin: /# type:/
      },
      // comment within a datatype comment includes no keywords
      {
        begin: /#/,
        end: /\b\B/,
        endsWithParent: true
      }
    ]
  };
  const PARAMS = {
    className: "params",
    variants: [
      // Exclude params in functions without params
      {
        className: "",
        begin: /\(\s*\)/,
        skip: true
      },
      {
        begin: /\(/,
        end: /\)/,
        excludeBegin: true,
        excludeEnd: true,
        keywords: KEYWORDS3,
        contains: [
          "self",
          PROMPT,
          NUMBER,
          STRING,
          hljs.HASH_COMMENT_MODE
        ]
      }
    ]
  };
  SUBST.contains = [
    STRING,
    NUMBER,
    PROMPT
  ];
  return {
    name: "Python",
    aliases: [
      "py",
      "gyp",
      "ipython"
    ],
    unicodeRegex: true,
    keywords: KEYWORDS3,
    illegal: /(<\/|\?)|=>/,
    contains: [
      PROMPT,
      NUMBER,
      {
        // very common convention
        scope: "variable.language",
        match: /\bself\b/
      },
      {
        // eat "if" prior to string so that it won't accidentally be
        // labeled as an f-string
        beginKeywords: "if",
        relevance: 0
      },
      { match: /\bor\b/, scope: "keyword" },
      STRING,
      COMMENT_TYPE,
      hljs.HASH_COMMENT_MODE,
      {
        match: [
          /\bdef/,
          /\s+/,
          IDENT_RE3
        ],
        scope: {
          1: "keyword",
          3: "title.function"
        },
        contains: [PARAMS]
      },
      {
        variants: [
          {
            match: [
              /\bclass/,
              /\s+/,
              IDENT_RE3,
              /\s*/,
              /\(\s*/,
              IDENT_RE3,
              /\s*\)/
            ]
          },
          {
            match: [
              /\bclass/,
              /\s+/,
              IDENT_RE3
            ]
          }
        ],
        scope: {
          1: "keyword",
          3: "title.class",
          6: "title.class.inherited"
        }
      },
      {
        className: "meta",
        begin: /^[\t ]*@/,
        end: /(?=#)|$/,
        contains: [
          NUMBER,
          PARAMS,
          STRING
        ]
      }
    ]
  };
}
__name(python, "python");

// node_modules/highlight.js/es/languages/python-repl.js
init_esbuild_shims();
function pythonRepl(hljs) {
  return {
    aliases: ["pycon"],
    contains: [
      {
        className: "meta.prompt",
        starts: {
          // a space separates the REPL prefix from the actual code
          // this is purely for cleaner HTML output
          end: / |$/,
          starts: {
            end: "$",
            subLanguage: "python"
          }
        },
        variants: [
          { begin: /^>>>(?=[ ]|$)/ },
          { begin: /^\.\.\.(?=[ ]|$)/ }
        ]
      }
    ]
  };
}
__name(pythonRepl, "pythonRepl");

// node_modules/highlight.js/es/languages/r.js
init_esbuild_shims();
function r2(hljs) {
  const regex3 = hljs.regex;
  const IDENT_RE3 = /(?:(?:[a-zA-Z]|\.[._a-zA-Z])[._a-zA-Z0-9]*)|\.(?!\d)/;
  const NUMBER_TYPES_RE = regex3.either(
    // Special case: only hexadecimal binary powers can contain fractions
    /0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*[pP][+-]?\d+i?/,
    // Hexadecimal numbers without fraction and optional binary power
    /0[xX][0-9a-fA-F]+(?:[pP][+-]?\d+)?[Li]?/,
    // Decimal numbers
    /(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[Li]?/
  );
  const OPERATORS_RE = /[=!<>:]=|\|\||&&|:::?|<-|<<-|->>|->|\|>|[-+*\/?!$&|:<=>@^~]|\*\*/;
  const PUNCTUATION_RE = regex3.either(
    /[()]/,
    /[{}]/,
    /\[\[/,
    /[[\]]/,
    /\\/,
    /,/
  );
  return {
    name: "R",
    keywords: {
      $pattern: IDENT_RE3,
      keyword: "function if in break next repeat else for while",
      literal: "NULL NA TRUE FALSE Inf NaN NA_integer_|10 NA_real_|10 NA_character_|10 NA_complex_|10",
      built_in: (
        // Builtin constants
        "LETTERS letters month.abb month.name pi T F abs acos acosh all any anyNA Arg as.call as.character as.complex as.double as.environment as.integer as.logical as.null.default as.numeric as.raw asin asinh atan atanh attr attributes baseenv browser c call ceiling class Conj cos cosh cospi cummax cummin cumprod cumsum digamma dim dimnames emptyenv exp expression floor forceAndCall gamma gc.time globalenv Im interactive invisible is.array is.atomic is.call is.character is.complex is.double is.environment is.expression is.finite is.function is.infinite is.integer is.language is.list is.logical is.matrix is.na is.name is.nan is.null is.numeric is.object is.pairlist is.raw is.recursive is.single is.symbol lazyLoadDBfetch length lgamma list log max min missing Mod names nargs nzchar oldClass on.exit pos.to.env proc.time prod quote range Re rep retracemem return round seq_along seq_len seq.int sign signif sin sinh sinpi sqrt standardGeneric substitute sum switch tan tanh tanpi tracemem trigamma trunc unclass untracemem UseMethod xtfrm"
      )
    },
    contains: [
      // Roxygen comments
      hljs.COMMENT(
        /#'/,
        /$/,
        { contains: [
          {
            // Handle `@examples` separately to cause all subsequent code
            // until the next `@`-tag on its own line to be kept as-is,
            // preventing highlighting. This code is example R code, so nested
            // doctags shouldn’t be treated as such. See
            // `test/markup/r/roxygen.txt` for an example.
            scope: "doctag",
            match: /@examples/,
            starts: {
              end: regex3.lookahead(regex3.either(
                // end if another doc comment
                /\n^#'\s*(?=@[a-zA-Z]+)/,
                // or a line with no comment
                /\n^(?!#')/
              )),
              endsParent: true
            }
          },
          {
            // Handle `@param` to highlight the parameter name following
            // after.
            scope: "doctag",
            begin: "@param",
            end: /$/,
            contains: [
              {
                scope: "variable",
                variants: [
                  { match: IDENT_RE3 },
                  { match: /`(?:\\.|[^`\\])+`/ }
                ],
                endsParent: true
              }
            ]
          },
          {
            scope: "doctag",
            match: /@[a-zA-Z]+/
          },
          {
            scope: "keyword",
            match: /\\[a-zA-Z]+/
          }
        ] }
      ),
      hljs.HASH_COMMENT_MODE,
      {
        scope: "string",
        contains: [hljs.BACKSLASH_ESCAPE],
        variants: [
          hljs.END_SAME_AS_BEGIN({
            begin: /[rR]"(-*)\(/,
            end: /\)(-*)"/
          }),
          hljs.END_SAME_AS_BEGIN({
            begin: /[rR]"(-*)\{/,
            end: /\}(-*)"/
          }),
          hljs.END_SAME_AS_BEGIN({
            begin: /[rR]"(-*)\[/,
            end: /\](-*)"/
          }),
          hljs.END_SAME_AS_BEGIN({
            begin: /[rR]'(-*)\(/,
            end: /\)(-*)'/
          }),
          hljs.END_SAME_AS_BEGIN({
            begin: /[rR]'(-*)\{/,
            end: /\}(-*)'/
          }),
          hljs.END_SAME_AS_BEGIN({
            begin: /[rR]'(-*)\[/,
            end: /\](-*)'/
          }),
          {
            begin: '"',
            end: '"',
            relevance: 0
          },
          {
            begin: "'",
            end: "'",
            relevance: 0
          }
        ]
      },
      // Matching numbers immediately following punctuation and operators is
      // tricky since we need to look at the character ahead of a number to
      // ensure the number is not part of an identifier, and we cannot use
      // negative look-behind assertions. So instead we explicitly handle all
      // possible combinations of (operator|punctuation), number.
      // TODO: replace with negative look-behind when available
      // { begin: /(?<![a-zA-Z0-9._])0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*[pP][+-]?\d+i?/ },
      // { begin: /(?<![a-zA-Z0-9._])0[xX][0-9a-fA-F]+([pP][+-]?\d+)?[Li]?/ },
      // { begin: /(?<![a-zA-Z0-9._])(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?[Li]?/ }
      {
        relevance: 0,
        variants: [
          {
            scope: {
              1: "operator",
              2: "number"
            },
            match: [
              OPERATORS_RE,
              NUMBER_TYPES_RE
            ]
          },
          {
            scope: {
              1: "operator",
              2: "number"
            },
            match: [
              /%[^%]*%/,
              NUMBER_TYPES_RE
            ]
          },
          {
            scope: {
              1: "punctuation",
              2: "number"
            },
            match: [
              PUNCTUATION_RE,
              NUMBER_TYPES_RE
            ]
          },
          {
            scope: { 2: "number" },
            match: [
              /[^a-zA-Z0-9._]|^/,
              // not part of an identifier, or start of document
              NUMBER_TYPES_RE
            ]
          }
        ]
      },
      // Operators/punctuation when they're not directly followed by numbers
      {
        // Relevance boost for the most common assignment form.
        scope: { 3: "operator" },
        match: [
          IDENT_RE3,
          /\s+/,
          /<-/,
          /\s+/
        ]
      },
      {
        scope: "operator",
        relevance: 0,
        variants: [
          { match: OPERATORS_RE },
          { match: /%[^%]*%/ }
        ]
      },
      {
        scope: "punctuation",
        relevance: 0,
        match: PUNCTUATION_RE
      },
      {
        // Escaped identifier
        begin: "`",
        end: "`",
        contains: [{ begin: /\\./ }]
      }
    ]
  };
}
__name(r2, "r");

// node_modules/highlight.js/es/languages/ruby.js
init_esbuild_shims();
function ruby(hljs) {
  const regex3 = hljs.regex;
  const RUBY_METHOD_RE = "([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)";
  const CLASS_NAME_RE = regex3.either(
    /\b([A-Z]+[a-z0-9]+)+/,
    // ends in caps
    /\b([A-Z]+[a-z0-9]+)+[A-Z]+/
  );
  const CLASS_NAME_WITH_NAMESPACE_RE = regex3.concat(CLASS_NAME_RE, /(::\w+)*/);
  const PSEUDO_KWS = [
    "include",
    "extend",
    "prepend",
    "public",
    "private",
    "protected",
    "raise",
    "throw"
  ];
  const RUBY_KEYWORDS = {
    "variable.constant": [
      "__FILE__",
      "__LINE__",
      "__ENCODING__"
    ],
    "variable.language": [
      "self",
      "super"
    ],
    keyword: [
      "alias",
      "and",
      "begin",
      "BEGIN",
      "break",
      "case",
      "class",
      "defined",
      "do",
      "else",
      "elsif",
      "end",
      "END",
      "ensure",
      "for",
      "if",
      "in",
      "module",
      "next",
      "not",
      "or",
      "redo",
      "require",
      "rescue",
      "retry",
      "return",
      "then",
      "undef",
      "unless",
      "until",
      "when",
      "while",
      "yield",
      ...PSEUDO_KWS
    ],
    built_in: [
      "proc",
      "lambda",
      "attr_accessor",
      "attr_reader",
      "attr_writer",
      "define_method",
      "private_constant",
      "module_function"
    ],
    literal: [
      "true",
      "false",
      "nil"
    ]
  };
  const YARDOCTAG = {
    className: "doctag",
    begin: "@[A-Za-z]+"
  };
  const IRB_OBJECT = {
    begin: "#<",
    end: ">"
  };
  const COMMENT_MODES = [
    hljs.COMMENT(
      "#",
      "$",
      { contains: [YARDOCTAG] }
    ),
    hljs.COMMENT(
      "^=begin",
      "^=end",
      {
        contains: [YARDOCTAG],
        relevance: 10
      }
    ),
    hljs.COMMENT("^__END__", hljs.MATCH_NOTHING_RE)
  ];
  const SUBST = {
    className: "subst",
    begin: /#\{/,
    end: /\}/,
    keywords: RUBY_KEYWORDS
  };
  const STRING = {
    className: "string",
    contains: [
      hljs.BACKSLASH_ESCAPE,
      SUBST
    ],
    variants: [
      {
        begin: /'/,
        end: /'/
      },
      {
        begin: /"/,
        end: /"/
      },
      {
        begin: /`/,
        end: /`/
      },
      {
        begin: /%[qQwWx]?\(/,
        end: /\)/
      },
      {
        begin: /%[qQwWx]?\[/,
        end: /\]/
      },
      {
        begin: /%[qQwWx]?\{/,
        end: /\}/
      },
      {
        begin: /%[qQwWx]?</,
        end: />/
      },
      {
        begin: /%[qQwWx]?\//,
        end: /\//
      },
      {
        begin: /%[qQwWx]?%/,
        end: /%/
      },
      {
        begin: /%[qQwWx]?-/,
        end: /-/
      },
      {
        begin: /%[qQwWx]?\|/,
        end: /\|/
      },
      // in the following expressions, \B in the beginning suppresses recognition of ?-sequences
      // where ? is the last character of a preceding identifier, as in: `func?4`
      { begin: /\B\?(\\\d{1,3})/ },
      { begin: /\B\?(\\x[A-Fa-f0-9]{1,2})/ },
      { begin: /\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/ },
      { begin: /\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/ },
      { begin: /\B\?\\(c|C-)[\x20-\x7e]/ },
      { begin: /\B\?\\?\S/ },
      // heredocs
      {
        // this guard makes sure that we have an entire heredoc and not a false
        // positive (auto-detect, etc.)
        begin: regex3.concat(
          /<<[-~]?'?/,
          regex3.lookahead(/(\w+)(?=\W)[^\n]*\n(?:[^\n]*\n)*?\s*\1\b/)
        ),
        contains: [
          hljs.END_SAME_AS_BEGIN({
            begin: /(\w+)/,
            end: /(\w+)/,
            contains: [
              hljs.BACKSLASH_ESCAPE,
              SUBST
            ]
          })
        ]
      }
    ]
  };
  const decimal = "[1-9](_?[0-9])*|0";
  const digits2 = "[0-9](_?[0-9])*";
  const NUMBER = {
    className: "number",
    relevance: 0,
    variants: [
      // decimal integer/float, optionally exponential or rational, optionally imaginary
      { begin: `\\b(${decimal})(\\.(${digits2}))?([eE][+-]?(${digits2})|r)?i?\\b` },
      // explicit decimal/binary/octal/hexadecimal integer,
      // optionally rational and/or imaginary
      { begin: "\\b0[dD][0-9](_?[0-9])*r?i?\\b" },
      { begin: "\\b0[bB][0-1](_?[0-1])*r?i?\\b" },
      { begin: "\\b0[oO][0-7](_?[0-7])*r?i?\\b" },
      { begin: "\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b" },
      // 0-prefixed implicit octal integer, optionally rational and/or imaginary
      { begin: "\\b0(_?[0-7])+r?i?\\b" }
    ]
  };
  const PARAMS = {
    variants: [
      {
        match: /\(\)/
      },
      {
        className: "params",
        begin: /\(/,
        end: /(?=\))/,
        excludeBegin: true,
        endsParent: true,
        keywords: RUBY_KEYWORDS
      }
    ]
  };
  const INCLUDE_EXTEND = {
    match: [
      /(include|extend)\s+/,
      CLASS_NAME_WITH_NAMESPACE_RE
    ],
    scope: {
      2: "title.class"
    },
    keywords: RUBY_KEYWORDS
  };
  const CLASS_DEFINITION = {
    variants: [
      {
        match: [
          /class\s+/,
          CLASS_NAME_WITH_NAMESPACE_RE,
          /\s+<\s+/,
          CLASS_NAME_WITH_NAMESPACE_RE
        ]
      },
      {
        match: [
          /\b(class|module)\s+/,
          CLASS_NAME_WITH_NAMESPACE_RE
        ]
      }
    ],
    scope: {
      2: "title.class",
      4: "title.class.inherited"
    },
    keywords: RUBY_KEYWORDS
  };
  const UPPER_CASE_CONSTANT = {
    relevance: 0,
    match: /\b[A-Z][A-Z_0-9]+\b/,
    className: "variable.constant"
  };
  const METHOD_DEFINITION = {
    match: [
      /def/,
      /\s+/,
      RUBY_METHOD_RE
    ],
    scope: {
      1: "keyword",
      3: "title.function"
    },
    contains: [
      PARAMS
    ]
  };
  const OBJECT_CREATION = {
    relevance: 0,
    match: [
      CLASS_NAME_WITH_NAMESPACE_RE,
      /\.new[. (]/
    ],
    scope: {
      1: "title.class"
    }
  };
  const CLASS_REFERENCE = {
    relevance: 0,
    match: CLASS_NAME_RE,
    scope: "title.class"
  };
  const RUBY_DEFAULT_CONTAINS = [
    STRING,
    CLASS_DEFINITION,
    INCLUDE_EXTEND,
    OBJECT_CREATION,
    UPPER_CASE_CONSTANT,
    CLASS_REFERENCE,
    METHOD_DEFINITION,
    {
      // swallow namespace qualifiers before symbols
      begin: hljs.IDENT_RE + "::"
    },
    {
      className: "symbol",
      begin: hljs.UNDERSCORE_IDENT_RE + "(!|\\?)?:",
      relevance: 0
    },
    {
      className: "symbol",
      begin: ":(?!\\s)",
      contains: [
        STRING,
        { begin: RUBY_METHOD_RE }
      ],
      relevance: 0
    },
    NUMBER,
    {
      // negative-look forward attempts to prevent false matches like:
      // @ident@ or $ident$ that might indicate this is not ruby at all
      className: "variable",
      begin: `(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])`
    },
    {
      className: "params",
      begin: /\|(?!=)/,
      end: /\|/,
      excludeBegin: true,
      excludeEnd: true,
      relevance: 0,
      // this could be a lot of things (in other languages) other than params
      keywords: RUBY_KEYWORDS
    },
    {
      // regexp container
      begin: "(" + hljs.RE_STARTERS_RE + "|unless)\\s*",
      keywords: "unless",
      contains: [
        {
          className: "regexp",
          contains: [
            hljs.BACKSLASH_ESCAPE,
            SUBST
          ],
          illegal: /\n/,
          variants: [
            {
              begin: "/",
              end: "/[a-z]*"
            },
            {
              begin: /%r\{/,
              end: /\}[a-z]*/
            },
            {
              begin: "%r\\(",
              end: "\\)[a-z]*"
            },
            {
              begin: "%r!",
              end: "![a-z]*"
            },
            {
              begin: "%r\\[",
              end: "\\][a-z]*"
            }
          ]
        }
      ].concat(IRB_OBJECT, COMMENT_MODES),
      relevance: 0
    }
  ].concat(IRB_OBJECT, COMMENT_MODES);
  SUBST.contains = RUBY_DEFAULT_CONTAINS;
  PARAMS.contains = RUBY_DEFAULT_CONTAINS;
  const SIMPLE_PROMPT = "[>?]>";
  const DEFAULT_PROMPT = "[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]";
  const RVM_PROMPT = "(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>";
  const IRB_DEFAULT = [
    {
      begin: /^\s*=>/,
      starts: {
        end: "$",
        contains: RUBY_DEFAULT_CONTAINS
      }
    },
    {
      className: "meta.prompt",
      begin: "^(" + SIMPLE_PROMPT + "|" + DEFAULT_PROMPT + "|" + RVM_PROMPT + ")(?=[ ])",
      starts: {
        end: "$",
        keywords: RUBY_KEYWORDS,
        contains: RUBY_DEFAULT_CONTAINS
      }
    }
  ];
  COMMENT_MODES.unshift(IRB_OBJECT);
  return {
    name: "Ruby",
    aliases: [
      "rb",
      "gemspec",
      "podspec",
      "thor",
      "irb"
    ],
    keywords: RUBY_KEYWORDS,
    illegal: /\/\*/,
    contains: [hljs.SHEBANG({ binary: "ruby" })].concat(IRB_DEFAULT).concat(COMMENT_MODES).concat(RUBY_DEFAULT_CONTAINS)
  };
}
__name(ruby, "ruby");

// node_modules/highlight.js/es/languages/rust.js
init_esbuild_shims();
function rust(hljs) {
  const regex3 = hljs.regex;
  const RAW_IDENTIFIER = /(r#)?/;
  const UNDERSCORE_IDENT_RE = regex3.concat(RAW_IDENTIFIER, hljs.UNDERSCORE_IDENT_RE);
  const IDENT_RE3 = regex3.concat(RAW_IDENTIFIER, hljs.IDENT_RE);
  const FUNCTION_INVOKE = {
    className: "title.function.invoke",
    relevance: 0,
    begin: regex3.concat(
      /\b/,
      /(?!let|for|while|if|else|match\b)/,
      IDENT_RE3,
      regex3.lookahead(/\s*\(/)
    )
  };
  const NUMBER_SUFFIX = "([ui](8|16|32|64|128|size)|f(32|64))?";
  const KEYWORDS3 = [
    "abstract",
    "as",
    "async",
    "await",
    "become",
    "box",
    "break",
    "const",
    "continue",
    "crate",
    "do",
    "dyn",
    "else",
    "enum",
    "extern",
    "false",
    "final",
    "fn",
    "for",
    "if",
    "impl",
    "in",
    "let",
    "loop",
    "macro",
    "match",
    "mod",
    "move",
    "mut",
    "override",
    "priv",
    "pub",
    "ref",
    "return",
    "self",
    "Self",
    "static",
    "struct",
    "super",
    "trait",
    "true",
    "try",
    "type",
    "typeof",
    "union",
    "unsafe",
    "unsized",
    "use",
    "virtual",
    "where",
    "while",
    "yield"
  ];
  const LITERALS3 = [
    "true",
    "false",
    "Some",
    "None",
    "Ok",
    "Err"
  ];
  const BUILTINS = [
    // functions
    "drop ",
    // traits
    "Copy",
    "Send",
    "Sized",
    "Sync",
    "Drop",
    "Fn",
    "FnMut",
    "FnOnce",
    "ToOwned",
    "Clone",
    "Debug",
    "PartialEq",
    "PartialOrd",
    "Eq",
    "Ord",
    "AsRef",
    "AsMut",
    "Into",
    "From",
    "Default",
    "Iterator",
    "Extend",
    "IntoIterator",
    "DoubleEndedIterator",
    "ExactSizeIterator",
    "SliceConcatExt",
    "ToString",
    // macros
    "assert!",
    "assert_eq!",
    "bitflags!",
    "bytes!",
    "cfg!",
    "col!",
    "concat!",
    "concat_idents!",
    "debug_assert!",
    "debug_assert_eq!",
    "env!",
    "eprintln!",
    "panic!",
    "file!",
    "format!",
    "format_args!",
    "include_bytes!",
    "include_str!",
    "line!",
    "local_data_key!",
    "module_path!",
    "option_env!",
    "print!",
    "println!",
    "select!",
    "stringify!",
    "try!",
    "unimplemented!",
    "unreachable!",
    "vec!",
    "write!",
    "writeln!",
    "macro_rules!",
    "assert_ne!",
    "debug_assert_ne!"
  ];
  const TYPES3 = [
    "i8",
    "i16",
    "i32",
    "i64",
    "i128",
    "isize",
    "u8",
    "u16",
    "u32",
    "u64",
    "u128",
    "usize",
    "f32",
    "f64",
    "str",
    "char",
    "bool",
    "Box",
    "Option",
    "Result",
    "String",
    "Vec"
  ];
  return {
    name: "Rust",
    aliases: ["rs"],
    keywords: {
      $pattern: hljs.IDENT_RE + "!?",
      type: TYPES3,
      keyword: KEYWORDS3,
      literal: LITERALS3,
      built_in: BUILTINS
    },
    illegal: "</",
    contains: [
      hljs.C_LINE_COMMENT_MODE,
      hljs.COMMENT("/\\*", "\\*/", { contains: ["self"] }),
      hljs.inherit(hljs.QUOTE_STRING_MODE, {
        begin: /b?"/,
        illegal: null
      }),
      {
        className: "symbol",
        // negative lookahead to avoid matching `'`
        begin: /'[a-zA-Z_][a-zA-Z0-9_]*(?!')/
      },
      {
        scope: "string",
        variants: [
          { begin: /b?r(#*)"(.|\n)*?"\1(?!#)/ },
          {
            begin: /b?'/,
            end: /'/,
            contains: [
              {
                scope: "char.escape",
                match: /\\('|\w|x\w{2}|u\w{4}|U\w{8})/
              }
            ]
          }
        ]
      },
      {
        className: "number",
        variants: [
          { begin: "\\b0b([01_]+)" + NUMBER_SUFFIX },
          { begin: "\\b0o([0-7_]+)" + NUMBER_SUFFIX },
          { begin: "\\b0x([A-Fa-f0-9_]+)" + NUMBER_SUFFIX },
          { begin: "\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)" + NUMBER_SUFFIX }
        ],
        relevance: 0
      },
      {
        begin: [
          /fn/,
          /\s+/,
          UNDERSCORE_IDENT_RE
        ],
        className: {
          1: "keyword",
          3: "title.function"
        }
      },
      {
        className: "meta",
        begin: "#!?\\[",
        end: "\\]",
        contains: [
          {
            className: "string",
            begin: /"/,
            end: /"/,
            contains: [
              hljs.BACKSLASH_ESCAPE
            ]
          }
        ]
      },
      {
        begin: [
          /let/,
          /\s+/,
          /(?:mut\s+)?/,
          UNDERSCORE_IDENT_RE
        ],
        className: {
          1: "keyword",
          3: "keyword",
          4: "variable"
        }
      },
      // must come before impl/for rule later
      {
        begin: [
          /for/,
          /\s+/,
          UNDERSCORE_IDENT_RE,
          /\s+/,
          /in/
        ],
        className: {
          1: "keyword",
          3: "variable",
          5: "keyword"
        }
      },
      {
        begin: [
          /type/,
          /\s+/,
          UNDERSCORE_IDENT_RE
        ],
        className: {
          1: "keyword",
          3: "title.class"
        }
      },
      {
        begin: [
          /(?:trait|enum|struct|union|impl|for)/,
          /\s+/,
          UNDERSCORE_IDENT_RE
        ],
        className: {
          1: "keyword",
          3: "title.class"
        }
      },
      {
        begin: hljs.IDENT_RE + "::",
        keywords: {
          keyword: "Self",
          built_in: BUILTINS,
          type: TYPES3
        }
      },
      {
        className: "punctuation",
        begin: "->"
      },
      FUNCTION_INVOKE
    ]
  };
}
__name(rust, "rust");

// node_modules/highlight.js/es/languages/scss.js
init_esbuild_shims();
var MODES3 = /* @__PURE__ */ __name((hljs) => {
  return {
    IMPORTANT: {
      scope: "meta",
      begin: "!important"
    },
    BLOCK_COMMENT: hljs.C_BLOCK_COMMENT_MODE,
    HEXCOLOR: {
      scope: "number",
      begin: /#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/
    },
    FUNCTION_DISPATCH: {
      className: "built_in",
      begin: /[\w-]+(?=\()/
    },
    ATTRIBUTE_SELECTOR_MODE: {
      scope: "selector-attr",
      begin: /\[/,
      end: /\]/,
      illegal: "$",
      contains: [
        hljs.APOS_STRING_MODE,
        hljs.QUOTE_STRING_MODE
      ]
    },
    CSS_NUMBER_MODE: {
      scope: "number",
      begin: hljs.NUMBER_RE + "(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",
      relevance: 0
    },
    CSS_VARIABLE: {
      className: "attr",
      begin: /--[A-Za-z_][A-Za-z0-9_-]*/
    }
  };
}, "MODES");
var HTML_TAGS3 = [
  "a",
  "abbr",
  "address",
  "article",
  "aside",
  "audio",
  "b",
  "blockquote",
  "body",
  "button",
  "canvas",
  "caption",
  "cite",
  "code",
  "dd",
  "del",
  "details",
  "dfn",
  "div",
  "dl",
  "dt",
  "em",
  "fieldset",
  "figcaption",
  "figure",
  "footer",
  "form",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "header",
  "hgroup",
  "html",
  "i",
  "iframe",
  "img",
  "input",
  "ins",
  "kbd",
  "label",
  "legend",
  "li",
  "main",
  "mark",
  "menu",
  "nav",
  "object",
  "ol",
  "optgroup",
  "option",
  "p",
  "picture",
  "q",
  "quote",
  "samp",
  "section",
  "select",
  "source",
  "span",
  "strong",
  "summary",
  "sup",
  "table",
  "tbody",
  "td",
  "textarea",
  "tfoot",
  "th",
  "thead",
  "time",
  "tr",
  "ul",
  "var",
  "video"
];
var SVG_TAGS3 = [
  "defs",
  "g",
  "marker",
  "mask",
  "pattern",
  "svg",
  "switch",
  "symbol",
  "feBlend",
  "feColorMatrix",
  "feComponentTransfer",
  "feComposite",
  "feConvolveMatrix",
  "feDiffuseLighting",
  "feDisplacementMap",
  "feFlood",
  "feGaussianBlur",
  "feImage",
  "feMerge",
  "feMorphology",
  "feOffset",
  "feSpecularLighting",
  "feTile",
  "feTurbulence",
  "linearGradient",
  "radialGradient",
  "stop",
  "circle",
  "ellipse",
  "image",
  "line",
  "path",
  "polygon",
  "polyline",
  "rect",
  "text",
  "use",
  "textPath",
  "tspan",
  "foreignObject",
  "clipPath"
];
var TAGS3 = [
  ...HTML_TAGS3,
  ...SVG_TAGS3
];
var MEDIA_FEATURES3 = [
  "any-hover",
  "any-pointer",
  "aspect-ratio",
  "color",
  "color-gamut",
  "color-index",
  "device-aspect-ratio",
  "device-height",
  "device-width",
  "display-mode",
  "forced-colors",
  "grid",
  "height",
  "hover",
  "inverted-colors",
  "monochrome",
  "orientation",
  "overflow-block",
  "overflow-inline",
  "pointer",
  "prefers-color-scheme",
  "prefers-contrast",
  "prefers-reduced-motion",
  "prefers-reduced-transparency",
  "resolution",
  "scan",
  "scripting",
  "update",
  "width",
  // TODO: find a better solution?
  "min-width",
  "max-width",
  "min-height",
  "max-height"
].sort().reverse();
var PSEUDO_CLASSES3 = [
  "active",
  "any-link",
  "blank",
  "checked",
  "current",
  "default",
  "defined",
  "dir",
  // dir()
  "disabled",
  "drop",
  "empty",
  "enabled",
  "first",
  "first-child",
  "first-of-type",
  "fullscreen",
  "future",
  "focus",
  "focus-visible",
  "focus-within",
  "has",
  // has()
  "host",
  // host or host()
  "host-context",
  // host-context()
  "hover",
  "indeterminate",
  "in-range",
  "invalid",
  "is",
  // is()
  "lang",
  // lang()
  "last-child",
  "last-of-type",
  "left",
  "link",
  "local-link",
  "not",
  // not()
  "nth-child",
  // nth-child()
  "nth-col",
  // nth-col()
  "nth-last-child",
  // nth-last-child()
  "nth-last-col",
  // nth-last-col()
  "nth-last-of-type",
  //nth-last-of-type()
  "nth-of-type",
  //nth-of-type()
  "only-child",
  "only-of-type",
  "optional",
  "out-of-range",
  "past",
  "placeholder-shown",
  "read-only",
  "read-write",
  "required",
  "right",
  "root",
  "scope",
  "target",
  "target-within",
  "user-invalid",
  "valid",
  "visited",
  "where"
  // where()
].sort().reverse();
var PSEUDO_ELEMENTS3 = [
  "after",
  "backdrop",
  "before",
  "cue",
  "cue-region",
  "first-letter",
  "first-line",
  "grammar-error",
  "marker",
  "part",
  "placeholder",
  "selection",
  "slotted",
  "spelling-error"
].sort().reverse();
var ATTRIBUTES3 = [
  "accent-color",
  "align-content",
  "align-items",
  "align-self",
  "alignment-baseline",
  "all",
  "anchor-name",
  "animation",
  "animation-composition",
  "animation-delay",
  "animation-direction",
  "animation-duration",
  "animation-fill-mode",
  "animation-iteration-count",
  "animation-name",
  "animation-play-state",
  "animation-range",
  "animation-range-end",
  "animation-range-start",
  "animation-timeline",
  "animation-timing-function",
  "appearance",
  "aspect-ratio",
  "backdrop-filter",
  "backface-visibility",
  "background",
  "background-attachment",
  "background-blend-mode",
  "background-clip",
  "background-color",
  "background-image",
  "background-origin",
  "background-position",
  "background-position-x",
  "background-position-y",
  "background-repeat",
  "background-size",
  "baseline-shift",
  "block-size",
  "border",
  "border-block",
  "border-block-color",
  "border-block-end",
  "border-block-end-color",
  "border-block-end-style",
  "border-block-end-width",
  "border-block-start",
  "border-block-start-color",
  "border-block-start-style",
  "border-block-start-width",
  "border-block-style",
  "border-block-width",
  "border-bottom",
  "border-bottom-color",
  "border-bottom-left-radius",
  "border-bottom-right-radius",
  "border-bottom-style",
  "border-bottom-width",
  "border-collapse",
  "border-color",
  "border-end-end-radius",
  "border-end-start-radius",
  "border-image",
  "border-image-outset",
  "border-image-repeat",
  "border-image-slice",
  "border-image-source",
  "border-image-width",
  "border-inline",
  "border-inline-color",
  "border-inline-end",
  "border-inline-end-color",
  "border-inline-end-style",
  "border-inline-end-width",
  "border-inline-start",
  "border-inline-start-color",
  "border-inline-start-style",
  "border-inline-start-width",
  "border-inline-style",
  "border-inline-width",
  "border-left",
  "border-left-color",
  "border-left-style",
  "border-left-width",
  "border-radius",
  "border-right",
  "border-right-color",
  "border-right-style",
  "border-right-width",
  "border-spacing",
  "border-start-end-radius",
  "border-start-start-radius",
  "border-style",
  "border-top",
  "border-top-color",
  "border-top-left-radius",
  "border-top-right-radius",
  "border-top-style",
  "border-top-width",
  "border-width",
  "bottom",
  "box-align",
  "box-decoration-break",
  "box-direction",
  "box-flex",
  "box-flex-group",
  "box-lines",
  "box-ordinal-group",
  "box-orient",
  "box-pack",
  "box-shadow",
  "box-sizing",
  "break-after",
  "break-before",
  "break-inside",
  "caption-side",
  "caret-color",
  "clear",
  "clip",
  "clip-path",
  "clip-rule",
  "color",
  "color-interpolation",
  "color-interpolation-filters",
  "color-profile",
  "color-rendering",
  "color-scheme",
  "column-count",
  "column-fill",
  "column-gap",
  "column-rule",
  "column-rule-color",
  "column-rule-style",
  "column-rule-width",
  "column-span",
  "column-width",
  "columns",
  "contain",
  "contain-intrinsic-block-size",
  "contain-intrinsic-height",
  "contain-intrinsic-inline-size",
  "contain-intrinsic-size",
  "contain-intrinsic-width",
  "container",
  "container-name",
  "container-type",
  "content",
  "content-visibility",
  "counter-increment",
  "counter-reset",
  "counter-set",
  "cue",
  "cue-after",
  "cue-before",
  "cursor",
  "cx",
  "cy",
  "direction",
  "display",
  "dominant-baseline",
  "empty-cells",
  "enable-background",
  "field-sizing",
  "fill",
  "fill-opacity",
  "fill-rule",
  "filter",
  "flex",
  "flex-basis",
  "flex-direction",
  "flex-flow",
  "flex-grow",
  "flex-shrink",
  "flex-wrap",
  "float",
  "flood-color",
  "flood-opacity",
  "flow",
  "font",
  "font-display",
  "font-family",
  "font-feature-settings",
  "font-kerning",
  "font-language-override",
  "font-optical-sizing",
  "font-palette",
  "font-size",
  "font-size-adjust",
  "font-smooth",
  "font-smoothing",
  "font-stretch",
  "font-style",
  "font-synthesis",
  "font-synthesis-position",
  "font-synthesis-small-caps",
  "font-synthesis-style",
  "font-synthesis-weight",
  "font-variant",
  "font-variant-alternates",
  "font-variant-caps",
  "font-variant-east-asian",
  "font-variant-emoji",
  "font-variant-ligatures",
  "font-variant-numeric",
  "font-variant-position",
  "font-variation-settings",
  "font-weight",
  "forced-color-adjust",
  "gap",
  "glyph-orientation-horizontal",
  "glyph-orientation-vertical",
  "grid",
  "grid-area",
  "grid-auto-columns",
  "grid-auto-flow",
  "grid-auto-rows",
  "grid-column",
  "grid-column-end",
  "grid-column-start",
  "grid-gap",
  "grid-row",
  "grid-row-end",
  "grid-row-start",
  "grid-template",
  "grid-template-areas",
  "grid-template-columns",
  "grid-template-rows",
  "hanging-punctuation",
  "height",
  "hyphenate-character",
  "hyphenate-limit-chars",
  "hyphens",
  "icon",
  "image-orientation",
  "image-rendering",
  "image-resolution",
  "ime-mode",
  "initial-letter",
  "initial-letter-align",
  "inline-size",
  "inset",
  "inset-area",
  "inset-block",
  "inset-block-end",
  "inset-block-start",
  "inset-inline",
  "inset-inline-end",
  "inset-inline-start",
  "isolation",
  "justify-content",
  "justify-items",
  "justify-self",
  "kerning",
  "left",
  "letter-spacing",
  "lighting-color",
  "line-break",
  "line-height",
  "line-height-step",
  "list-style",
  "list-style-image",
  "list-style-position",
  "list-style-type",
  "margin",
  "margin-block",
  "margin-block-end",
  "margin-block-start",
  "margin-bottom",
  "margin-inline",
  "margin-inline-end",
  "margin-inline-start",
  "margin-left",
  "margin-right",
  "margin-top",
  "margin-trim",
  "marker",
  "marker-end",
  "marker-mid",
  "marker-start",
  "marks",
  "mask",
  "mask-border",
  "mask-border-mode",
  "mask-border-outset",
  "mask-border-repeat",
  "mask-border-slice",
  "mask-border-source",
  "mask-border-width",
  "mask-clip",
  "mask-composite",
  "mask-image",
  "mask-mode",
  "mask-origin",
  "mask-position",
  "mask-repeat",
  "mask-size",
  "mask-type",
  "masonry-auto-flow",
  "math-depth",
  "math-shift",
  "math-style",
  "max-block-size",
  "max-height",
  "max-inline-size",
  "max-width",
  "min-block-size",
  "min-height",
  "min-inline-size",
  "min-width",
  "mix-blend-mode",
  "nav-down",
  "nav-index",
  "nav-left",
  "nav-right",
  "nav-up",
  "none",
  "normal",
  "object-fit",
  "object-position",
  "offset",
  "offset-anchor",
  "offset-distance",
  "offset-path",
  "offset-position",
  "offset-rotate",
  "opacity",
  "order",
  "orphans",
  "outline",
  "outline-color",
  "outline-offset",
  "outline-style",
  "outline-width",
  "overflow",
  "overflow-anchor",
  "overflow-block",
  "overflow-clip-margin",
  "overflow-inline",
  "overflow-wrap",
  "overflow-x",
  "overflow-y",
  "overlay",
  "overscroll-behavior",
  "overscroll-behavior-block",
  "overscroll-behavior-inline",
  "overscroll-behavior-x",
  "overscroll-behavior-y",
  "padding",
  "padding-block",
  "padding-block-end",
  "padding-block-start",
  "padding-bottom",
  "padding-inline",
  "padding-inline-end",
  "padding-inline-start",
  "padding-left",
  "padding-right",
  "padding-top",
  "page",
  "page-break-after",
  "page-break-before",
  "page-break-inside",
  "paint-order",
  "pause",
  "pause-after",
  "pause-before",
  "perspective",
  "perspective-origin",
  "place-content",
  "place-items",
  "place-self",
  "pointer-events",
  "position",
  "position-anchor",
  "position-visibility",
  "print-color-adjust",
  "quotes",
  "r",
  "resize",
  "rest",
  "rest-after",
  "rest-before",
  "right",
  "rotate",
  "row-gap",
  "ruby-align",
  "ruby-position",
  "scale",
  "scroll-behavior",
  "scroll-margin",
  "scroll-margin-block",
  "scroll-margin-block-end",
  "scroll-margin-block-start",
  "scroll-margin-bottom",
  "scroll-margin-inline",
  "scroll-margin-inline-end",
  "scroll-margin-inline-start",
  "scroll-margin-left",
  "scroll-margin-right",
  "scroll-margin-top",
  "scroll-padding",
  "scroll-padding-block",
  "scroll-padding-block-end",
  "scroll-padding-block-start",
  "scroll-padding-bottom",
  "scroll-padding-inline",
  "scroll-padding-inline-end",
  "scroll-padding-inline-start",
  "scroll-padding-left",
  "scroll-padding-right",
  "scroll-padding-top",
  "scroll-snap-align",
  "scroll-snap-stop",
  "scroll-snap-type",
  "scroll-timeline",
  "scroll-timeline-axis",
  "scroll-timeline-name",
  "scrollbar-color",
  "scrollbar-gutter",
  "scrollbar-width",
  "shape-image-threshold",
  "shape-margin",
  "shape-outside",
  "shape-rendering",
  "speak",
  "speak-as",
  "src",
  // @font-face
  "stop-color",
  "stop-opacity",
  "stroke",
  "stroke-dasharray",
  "stroke-dashoffset",
  "stroke-linecap",
  "stroke-linejoin",
  "stroke-miterlimit",
  "stroke-opacity",
  "stroke-width",
  "tab-size",
  "table-layout",
  "text-align",
  "text-align-all",
  "text-align-last",
  "text-anchor",
  "text-combine-upright",
  "text-decoration",
  "text-decoration-color",
  "text-decoration-line",
  "text-decoration-skip",
  "text-decoration-skip-ink",
  "text-decoration-style",
  "text-decoration-thickness",
  "text-emphasis",
  "text-emphasis-color",
  "text-emphasis-position",
  "text-emphasis-style",
  "text-indent",
  "text-justify",
  "text-orientation",
  "text-overflow",
  "text-rendering",
  "text-shadow",
  "text-size-adjust",
  "text-transform",
  "text-underline-offset",
  "text-underline-position",
  "text-wrap",
  "text-wrap-mode",
  "text-wrap-style",
  "timeline-scope",
  "top",
  "touch-action",
  "transform",
  "transform-box",
  "transform-origin",
  "transform-style",
  "transition",
  "transition-behavior",
  "transition-delay",
  "transition-duration",
  "transition-property",
  "transition-timing-function",
  "translate",
  "unicode-bidi",
  "user-modify",
  "user-select",
  "vector-effect",
  "vertical-align",
  "view-timeline",
  "view-timeline-axis",
  "view-timeline-inset",
  "view-timeline-name",
  "view-transition-name",
  "visibility",
  "voice-balance",
  "voice-duration",
  "voice-family",
  "voice-pitch",
  "voice-range",
  "voice-rate",
  "voice-stress",
  "voice-volume",
  "white-space",
  "white-space-collapse",
  "widows",
  "width",
  "will-change",
  "word-break",
  "word-spacing",
  "word-wrap",
  "writing-mode",
  "x",
  "y",
  "z-index",
  "zoom"
].sort().reverse();
function scss(hljs) {
  const modes = MODES3(hljs);
  const PSEUDO_ELEMENTS$1 = PSEUDO_ELEMENTS3;
  const PSEUDO_CLASSES$1 = PSEUDO_CLASSES3;
  const AT_IDENTIFIER = "@[a-z-]+";
  const AT_MODIFIERS = "and or not only";
  const IDENT_RE3 = "[a-zA-Z-][a-zA-Z0-9_-]*";
  const VARIABLE = {
    className: "variable",
    begin: "(\\$" + IDENT_RE3 + ")\\b",
    relevance: 0
  };
  return {
    name: "SCSS",
    case_insensitive: true,
    illegal: "[=/|']",
    contains: [
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      // to recognize keyframe 40% etc which are outside the scope of our
      // attribute value mode
      modes.CSS_NUMBER_MODE,
      {
        className: "selector-id",
        begin: "#[A-Za-z0-9_-]+",
        relevance: 0
      },
      {
        className: "selector-class",
        begin: "\\.[A-Za-z0-9_-]+",
        relevance: 0
      },
      modes.ATTRIBUTE_SELECTOR_MODE,
      {
        className: "selector-tag",
        begin: "\\b(" + TAGS3.join("|") + ")\\b",
        // was there, before, but why?
        relevance: 0
      },
      {
        className: "selector-pseudo",
        begin: ":(" + PSEUDO_CLASSES$1.join("|") + ")"
      },
      {
        className: "selector-pseudo",
        begin: ":(:)?(" + PSEUDO_ELEMENTS$1.join("|") + ")"
      },
      VARIABLE,
      {
        // pseudo-selector params
        begin: /\(/,
        end: /\)/,
        contains: [modes.CSS_NUMBER_MODE]
      },
      modes.CSS_VARIABLE,
      {
        className: "attribute",
        begin: "\\b(" + ATTRIBUTES3.join("|") + ")\\b"
      },
      { begin: "\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b" },
      {
        begin: /:/,
        end: /[;}{]/,
        relevance: 0,
        contains: [
          modes.BLOCK_COMMENT,
          VARIABLE,
          modes.HEXCOLOR,
          modes.CSS_NUMBER_MODE,
          hljs.QUOTE_STRING_MODE,
          hljs.APOS_STRING_MODE,
          modes.IMPORTANT,
          modes.FUNCTION_DISPATCH
        ]
      },
      // matching these here allows us to treat them more like regular CSS
      // rules so everything between the {} gets regular rule highlighting,
      // which is what we want for page and font-face
      {
        begin: "@(page|font-face)",
        keywords: {
          $pattern: AT_IDENTIFIER,
          keyword: "@page @font-face"
        }
      },
      {
        begin: "@",
        end: "[{;]",
        returnBegin: true,
        keywords: {
          $pattern: /[a-z-]+/,
          keyword: AT_MODIFIERS,
          attribute: MEDIA_FEATURES3.join(" ")
        },
        contains: [
          {
            begin: AT_IDENTIFIER,
            className: "keyword"
          },
          {
            begin: /[a-z-]+(?=:)/,
            className: "attribute"
          },
          VARIABLE,
          hljs.QUOTE_STRING_MODE,
          hljs.APOS_STRING_MODE,
          modes.HEXCOLOR,
          modes.CSS_NUMBER_MODE
        ]
      },
      modes.FUNCTION_DISPATCH
    ]
  };
}
__name(scss, "scss");

// node_modules/highlight.js/es/languages/shell.js
init_esbuild_shims();
function shell(hljs) {
  return {
    name: "Shell Session",
    aliases: [
      "console",
      "shellsession"
    ],
    contains: [
      {
        className: "meta.prompt",
        // We cannot add \s (spaces) in the regular expression otherwise it will be too broad and produce unexpected result.
        // For instance, in the following example, it would match "echo /path/to/home >" as a prompt:
        // echo /path/to/home > t.exe
        begin: /^\s{0,3}[/~\w\d[\]()@-]*[>%$#][ ]?/,
        starts: {
          end: /[^\\](?=\s*$)/,
          subLanguage: "bash"
        }
      }
    ]
  };
}
__name(shell, "shell");

// node_modules/highlight.js/es/languages/sql.js
init_esbuild_shims();
function sql(hljs) {
  const regex3 = hljs.regex;
  const COMMENT_MODE = hljs.COMMENT("--", "$");
  const STRING = {
    scope: "string",
    variants: [
      {
        begin: /'/,
        end: /'/,
        contains: [{ match: /''/ }]
      }
    ]
  };
  const QUOTED_IDENTIFIER = {
    begin: /"/,
    end: /"/,
    contains: [{ match: /""/ }]
  };
  const LITERALS3 = [
    "true",
    "false",
    // Not sure it's correct to call NULL literal, and clauses like IS [NOT] NULL look strange that way.
    // "null",
    "unknown"
  ];
  const MULTI_WORD_TYPES = [
    "double precision",
    "large object",
    "with timezone",
    "without timezone"
  ];
  const TYPES3 = [
    "bigint",
    "binary",
    "blob",
    "boolean",
    "char",
    "character",
    "clob",
    "date",
    "dec",
    "decfloat",
    "decimal",
    "float",
    "int",
    "integer",
    "interval",
    "nchar",
    "nclob",
    "national",
    "numeric",
    "real",
    "row",
    "smallint",
    "time",
    "timestamp",
    "varchar",
    "varying",
    // modifier (character varying)
    "varbinary"
  ];
  const NON_RESERVED_WORDS = [
    "add",
    "asc",
    "collation",
    "desc",
    "final",
    "first",
    "last",
    "view"
  ];
  const RESERVED_WORDS = [
    "abs",
    "acos",
    "all",
    "allocate",
    "alter",
    "and",
    "any",
    "are",
    "array",
    "array_agg",
    "array_max_cardinality",
    "as",
    "asensitive",
    "asin",
    "asymmetric",
    "at",
    "atan",
    "atomic",
    "authorization",
    "avg",
    "begin",
    "begin_frame",
    "begin_partition",
    "between",
    "bigint",
    "binary",
    "blob",
    "boolean",
    "both",
    "by",
    "call",
    "called",
    "cardinality",
    "cascaded",
    "case",
    "cast",
    "ceil",
    "ceiling",
    "char",
    "char_length",
    "character",
    "character_length",
    "check",
    "classifier",
    "clob",
    "close",
    "coalesce",
    "collate",
    "collect",
    "column",
    "commit",
    "condition",
    "connect",
    "constraint",
    "contains",
    "convert",
    "copy",
    "corr",
    "corresponding",
    "cos",
    "cosh",
    "count",
    "covar_pop",
    "covar_samp",
    "create",
    "cross",
    "cube",
    "cume_dist",
    "current",
    "current_catalog",
    "current_date",
    "current_default_transform_group",
    "current_path",
    "current_role",
    "current_row",
    "current_schema",
    "current_time",
    "current_timestamp",
    "current_path",
    "current_role",
    "current_transform_group_for_type",
    "current_user",
    "cursor",
    "cycle",
    "date",
    "day",
    "deallocate",
    "dec",
    "decimal",
    "decfloat",
    "declare",
    "default",
    "define",
    "delete",
    "dense_rank",
    "deref",
    "describe",
    "deterministic",
    "disconnect",
    "distinct",
    "double",
    "drop",
    "dynamic",
    "each",
    "element",
    "else",
    "empty",
    "end",
    "end_frame",
    "end_partition",
    "end-exec",
    "equals",
    "escape",
    "every",
    "except",
    "exec",
    "execute",
    "exists",
    "exp",
    "external",
    "extract",
    "false",
    "fetch",
    "filter",
    "first_value",
    "float",
    "floor",
    "for",
    "foreign",
    "frame_row",
    "free",
    "from",
    "full",
    "function",
    "fusion",
    "get",
    "global",
    "grant",
    "group",
    "grouping",
    "groups",
    "having",
    "hold",
    "hour",
    "identity",
    "in",
    "indicator",
    "initial",
    "inner",
    "inout",
    "insensitive",
    "insert",
    "int",
    "integer",
    "intersect",
    "intersection",
    "interval",
    "into",
    "is",
    "join",
    "json_array",
    "json_arrayagg",
    "json_exists",
    "json_object",
    "json_objectagg",
    "json_query",
    "json_table",
    "json_table_primitive",
    "json_value",
    "lag",
    "language",
    "large",
    "last_value",
    "lateral",
    "lead",
    "leading",
    "left",
    "like",
    "like_regex",
    "listagg",
    "ln",
    "local",
    "localtime",
    "localtimestamp",
    "log",
    "log10",
    "lower",
    "match",
    "match_number",
    "match_recognize",
    "matches",
    "max",
    "member",
    "merge",
    "method",
    "min",
    "minute",
    "mod",
    "modifies",
    "module",
    "month",
    "multiset",
    "national",
    "natural",
    "nchar",
    "nclob",
    "new",
    "no",
    "none",
    "normalize",
    "not",
    "nth_value",
    "ntile",
    "null",
    "nullif",
    "numeric",
    "octet_length",
    "occurrences_regex",
    "of",
    "offset",
    "old",
    "omit",
    "on",
    "one",
    "only",
    "open",
    "or",
    "order",
    "out",
    "outer",
    "over",
    "overlaps",
    "overlay",
    "parameter",
    "partition",
    "pattern",
    "per",
    "percent",
    "percent_rank",
    "percentile_cont",
    "percentile_disc",
    "period",
    "portion",
    "position",
    "position_regex",
    "power",
    "precedes",
    "precision",
    "prepare",
    "primary",
    "procedure",
    "ptf",
    "range",
    "rank",
    "reads",
    "real",
    "recursive",
    "ref",
    "references",
    "referencing",
    "regr_avgx",
    "regr_avgy",
    "regr_count",
    "regr_intercept",
    "regr_r2",
    "regr_slope",
    "regr_sxx",
    "regr_sxy",
    "regr_syy",
    "release",
    "result",
    "return",
    "returns",
    "revoke",
    "right",
    "rollback",
    "rollup",
    "row",
    "row_number",
    "rows",
    "running",
    "savepoint",
    "scope",
    "scroll",
    "search",
    "second",
    "seek",
    "select",
    "sensitive",
    "session_user",
    "set",
    "show",
    "similar",
    "sin",
    "sinh",
    "skip",
    "smallint",
    "some",
    "specific",
    "specifictype",
    "sql",
    "sqlexception",
    "sqlstate",
    "sqlwarning",
    "sqrt",
    "start",
    "static",
    "stddev_pop",
    "stddev_samp",
    "submultiset",
    "subset",
    "substring",
    "substring_regex",
    "succeeds",
    "sum",
    "symmetric",
    "system",
    "system_time",
    "system_user",
    "table",
    "tablesample",
    "tan",
    "tanh",
    "then",
    "time",
    "timestamp",
    "timezone_hour",
    "timezone_minute",
    "to",
    "trailing",
    "translate",
    "translate_regex",
    "translation",
    "treat",
    "trigger",
    "trim",
    "trim_array",
    "true",
    "truncate",
    "uescape",
    "union",
    "unique",
    "unknown",
    "unnest",
    "update",
    "upper",
    "user",
    "using",
    "value",
    "values",
    "value_of",
    "var_pop",
    "var_samp",
    "varbinary",
    "varchar",
    "varying",
    "versioning",
    "when",
    "whenever",
    "where",
    "width_bucket",
    "window",
    "with",
    "within",
    "without",
    "year"
  ];
  const RESERVED_FUNCTIONS = [
    "abs",
    "acos",
    "array_agg",
    "asin",
    "atan",
    "avg",
    "cast",
    "ceil",
    "ceiling",
    "coalesce",
    "corr",
    "cos",
    "cosh",
    "count",
    "covar_pop",
    "covar_samp",
    "cume_dist",
    "dense_rank",
    "deref",
    "element",
    "exp",
    "extract",
    "first_value",
    "floor",
    "json_array",
    "json_arrayagg",
    "json_exists",
    "json_object",
    "json_objectagg",
    "json_query",
    "json_table",
    "json_table_primitive",
    "json_value",
    "lag",
    "last_value",
    "lead",
    "listagg",
    "ln",
    "log",
    "log10",
    "lower",
    "max",
    "min",
    "mod",
    "nth_value",
    "ntile",
    "nullif",
    "percent_rank",
    "percentile_cont",
    "percentile_disc",
    "position",
    "position_regex",
    "power",
    "rank",
    "regr_avgx",
    "regr_avgy",
    "regr_count",
    "regr_intercept",
    "regr_r2",
    "regr_slope",
    "regr_sxx",
    "regr_sxy",
    "regr_syy",
    "row_number",
    "sin",
    "sinh",
    "sqrt",
    "stddev_pop",
    "stddev_samp",
    "substring",
    "substring_regex",
    "sum",
    "tan",
    "tanh",
    "translate",
    "translate_regex",
    "treat",
    "trim",
    "trim_array",
    "unnest",
    "upper",
    "value_of",
    "var_pop",
    "var_samp",
    "width_bucket"
  ];
  const POSSIBLE_WITHOUT_PARENS = [
    "current_catalog",
    "current_date",
    "current_default_transform_group",
    "current_path",
    "current_role",
    "current_schema",
    "current_transform_group_for_type",
    "current_user",
    "session_user",
    "system_time",
    "system_user",
    "current_time",
    "localtime",
    "current_timestamp",
    "localtimestamp"
  ];
  const COMBOS = [
    "create table",
    "insert into",
    "primary key",
    "foreign key",
    "not null",
    "alter table",
    "add constraint",
    "grouping sets",
    "on overflow",
    "character set",
    "respect nulls",
    "ignore nulls",
    "nulls first",
    "nulls last",
    "depth first",
    "breadth first"
  ];
  const FUNCTIONS = RESERVED_FUNCTIONS;
  const KEYWORDS3 = [
    ...RESERVED_WORDS,
    ...NON_RESERVED_WORDS
  ].filter((keyword) => {
    return !RESERVED_FUNCTIONS.includes(keyword);
  });
  const VARIABLE = {
    scope: "variable",
    match: /@[a-z0-9][a-z0-9_]*/
  };
  const OPERATOR = {
    scope: "operator",
    match: /[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,
    relevance: 0
  };
  const FUNCTION_CALL = {
    match: regex3.concat(/\b/, regex3.either(...FUNCTIONS), /\s*\(/),
    relevance: 0,
    keywords: { built_in: FUNCTIONS }
  };
  function kws_to_regex(list3) {
    return regex3.concat(
      /\b/,
      regex3.either(...list3.map((kw) => {
        return kw.replace(/\s+/, "\\s+");
      })),
      /\b/
    );
  }
  __name(kws_to_regex, "kws_to_regex");
  const MULTI_WORD_KEYWORDS = {
    scope: "keyword",
    match: kws_to_regex(COMBOS),
    relevance: 0
  };
  function reduceRelevancy(list3, {
    exceptions,
    when
  } = {}) {
    const qualifyFn = when;
    exceptions = exceptions || [];
    return list3.map((item) => {
      if (item.match(/\|\d+$/) || exceptions.includes(item)) {
        return item;
      } else if (qualifyFn(item)) {
        return `${item}|0`;
      } else {
        return item;
      }
    });
  }
  __name(reduceRelevancy, "reduceRelevancy");
  return {
    name: "SQL",
    case_insensitive: true,
    // does not include {} or HTML tags `</`
    illegal: /[{}]|<\//,
    keywords: {
      $pattern: /\b[\w\.]+/,
      keyword: reduceRelevancy(KEYWORDS3, { when: /* @__PURE__ */ __name((x) => x.length < 3, "when") }),
      literal: LITERALS3,
      type: TYPES3,
      built_in: POSSIBLE_WITHOUT_PARENS
    },
    contains: [
      {
        scope: "type",
        match: kws_to_regex(MULTI_WORD_TYPES)
      },
      MULTI_WORD_KEYWORDS,
      FUNCTION_CALL,
      VARIABLE,
      STRING,
      QUOTED_IDENTIFIER,
      hljs.C_NUMBER_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      COMMENT_MODE,
      OPERATOR
    ]
  };
}
__name(sql, "sql");

// node_modules/highlight.js/es/languages/swift.js
init_esbuild_shims();
function source(re2) {
  if (!re2) return null;
  if (typeof re2 === "string") return re2;
  return re2.source;
}
__name(source, "source");
function lookahead(re2) {
  return concat("(?=", re2, ")");
}
__name(lookahead, "lookahead");
function concat(...args) {
  const joined = args.map((x) => source(x)).join("");
  return joined;
}
__name(concat, "concat");
function stripOptionsFromArgs(args) {
  const opts = args[args.length - 1];
  if (typeof opts === "object" && opts.constructor === Object) {
    args.splice(args.length - 1, 1);
    return opts;
  } else {
    return {};
  }
}
__name(stripOptionsFromArgs, "stripOptionsFromArgs");
function either(...args) {
  const opts = stripOptionsFromArgs(args);
  const joined = "(" + (opts.capture ? "" : "?:") + args.map((x) => source(x)).join("|") + ")";
  return joined;
}
__name(either, "either");
var keywordWrapper = /* @__PURE__ */ __name((keyword) => concat(
  /\b/,
  keyword,
  /\w$/.test(keyword) ? /\b/ : /\B/
), "keywordWrapper");
var dotKeywords = [
  "Protocol",
  // contextual
  "Type"
  // contextual
].map(keywordWrapper);
var optionalDotKeywords = [
  "init",
  "self"
].map(keywordWrapper);
var keywordTypes = [
  "Any",
  "Self"
];
var keywords = [
  // strings below will be fed into the regular `keywords` engine while regex
  // will result in additional modes being created to scan for those keywords to
  // avoid conflicts with other rules
  "actor",
  "any",
  // contextual
  "associatedtype",
  "async",
  "await",
  /as\?/,
  // operator
  /as!/,
  // operator
  "as",
  // operator
  "borrowing",
  // contextual
  "break",
  "case",
  "catch",
  "class",
  "consume",
  // contextual
  "consuming",
  // contextual
  "continue",
  "convenience",
  // contextual
  "copy",
  // contextual
  "default",
  "defer",
  "deinit",
  "didSet",
  // contextual
  "distributed",
  "do",
  "dynamic",
  // contextual
  "each",
  "else",
  "enum",
  "extension",
  "fallthrough",
  /fileprivate\(set\)/,
  "fileprivate",
  "final",
  // contextual
  "for",
  "func",
  "get",
  // contextual
  "guard",
  "if",
  "import",
  "indirect",
  // contextual
  "infix",
  // contextual
  /init\?/,
  /init!/,
  "inout",
  /internal\(set\)/,
  "internal",
  "in",
  "is",
  // operator
  "isolated",
  // contextual
  "nonisolated",
  // contextual
  "lazy",
  // contextual
  "let",
  "macro",
  "mutating",
  // contextual
  "nonmutating",
  // contextual
  /open\(set\)/,
  // contextual
  "open",
  // contextual
  "operator",
  "optional",
  // contextual
  "override",
  // contextual
  "package",
  "postfix",
  // contextual
  "precedencegroup",
  "prefix",
  // contextual
  /private\(set\)/,
  "private",
  "protocol",
  /public\(set\)/,
  "public",
  "repeat",
  "required",
  // contextual
  "rethrows",
  "return",
  "set",
  // contextual
  "some",
  // contextual
  "static",
  "struct",
  "subscript",
  "super",
  "switch",
  "throws",
  "throw",
  /try\?/,
  // operator
  /try!/,
  // operator
  "try",
  // operator
  "typealias",
  /unowned\(safe\)/,
  // contextual
  /unowned\(unsafe\)/,
  // contextual
  "unowned",
  // contextual
  "var",
  "weak",
  // contextual
  "where",
  "while",
  "willSet"
  // contextual
];
var literals = [
  "false",
  "nil",
  "true"
];
var precedencegroupKeywords = [
  "assignment",
  "associativity",
  "higherThan",
  "left",
  "lowerThan",
  "none",
  "right"
];
var numberSignKeywords = [
  "#colorLiteral",
  "#column",
  "#dsohandle",
  "#else",
  "#elseif",
  "#endif",
  "#error",
  "#file",
  "#fileID",
  "#fileLiteral",
  "#filePath",
  "#function",
  "#if",
  "#imageLiteral",
  "#keyPath",
  "#line",
  "#selector",
  "#sourceLocation",
  "#warning"
];
var builtIns = [
  "abs",
  "all",
  "any",
  "assert",
  "assertionFailure",
  "debugPrint",
  "dump",
  "fatalError",
  "getVaList",
  "isKnownUniquelyReferenced",
  "max",
  "min",
  "numericCast",
  "pointwiseMax",
  "pointwiseMin",
  "precondition",
  "preconditionFailure",
  "print",
  "readLine",
  "repeatElement",
  "sequence",
  "stride",
  "swap",
  "swift_unboxFromSwiftValueWithType",
  "transcode",
  "type",
  "unsafeBitCast",
  "unsafeDowncast",
  "withExtendedLifetime",
  "withUnsafeMutablePointer",
  "withUnsafePointer",
  "withVaList",
  "withoutActuallyEscaping",
  "zip"
];
var operatorHead = either(
  /[/=\-+!*%<>&|^~?]/,
  /[\u00A1-\u00A7]/,
  /[\u00A9\u00AB]/,
  /[\u00AC\u00AE]/,
  /[\u00B0\u00B1]/,
  /[\u00B6\u00BB\u00BF\u00D7\u00F7]/,
  /[\u2016-\u2017]/,
  /[\u2020-\u2027]/,
  /[\u2030-\u203E]/,
  /[\u2041-\u2053]/,
  /[\u2055-\u205E]/,
  /[\u2190-\u23FF]/,
  /[\u2500-\u2775]/,
  /[\u2794-\u2BFF]/,
  /[\u2E00-\u2E7F]/,
  /[\u3001-\u3003]/,
  /[\u3008-\u3020]/,
  /[\u3030]/
);
var operatorCharacter = either(
  operatorHead,
  /[\u0300-\u036F]/,
  /[\u1DC0-\u1DFF]/,
  /[\u20D0-\u20FF]/,
  /[\uFE00-\uFE0F]/,
  /[\uFE20-\uFE2F]/
  // TODO: The following characters are also allowed, but the regex isn't supported yet.
  // /[\u{E0100}-\u{E01EF}]/u
);
var operator = concat(operatorHead, operatorCharacter, "*");
var identifierHead = either(
  /[a-zA-Z_]/,
  /[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,
  /[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,
  /[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,
  /[\u1E00-\u1FFF]/,
  /[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,
  /[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,
  /[\u2C00-\u2DFF\u2E80-\u2FFF]/,
  /[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,
  /[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,
  /[\uFE47-\uFEFE\uFF00-\uFFFD]/
  // Should be /[\uFE47-\uFFFD]/, but we have to exclude FEFF.
  // The following characters are also allowed, but the regexes aren't supported yet.
  // /[\u{10000}-\u{1FFFD}\u{20000-\u{2FFFD}\u{30000}-\u{3FFFD}\u{40000}-\u{4FFFD}]/u,
  // /[\u{50000}-\u{5FFFD}\u{60000-\u{6FFFD}\u{70000}-\u{7FFFD}\u{80000}-\u{8FFFD}]/u,
  // /[\u{90000}-\u{9FFFD}\u{A0000-\u{AFFFD}\u{B0000}-\u{BFFFD}\u{C0000}-\u{CFFFD}]/u,
  // /[\u{D0000}-\u{DFFFD}\u{E0000-\u{EFFFD}]/u
);
var identifierCharacter = either(
  identifierHead,
  /\d/,
  /[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/
);
var identifier = concat(identifierHead, identifierCharacter, "*");
var typeIdentifier = concat(/[A-Z]/, identifierCharacter, "*");
var keywordAttributes = [
  "attached",
  "autoclosure",
  concat(/convention\(/, either("swift", "block", "c"), /\)/),
  "discardableResult",
  "dynamicCallable",
  "dynamicMemberLookup",
  "escaping",
  "freestanding",
  "frozen",
  "GKInspectable",
  "IBAction",
  "IBDesignable",
  "IBInspectable",
  "IBOutlet",
  "IBSegueAction",
  "inlinable",
  "main",
  "nonobjc",
  "NSApplicationMain",
  "NSCopying",
  "NSManaged",
  concat(/objc\(/, identifier, /\)/),
  "objc",
  "objcMembers",
  "propertyWrapper",
  "requires_stored_property_inits",
  "resultBuilder",
  "Sendable",
  "testable",
  "UIApplicationMain",
  "unchecked",
  "unknown",
  "usableFromInline",
  "warn_unqualified_access"
];
var availabilityKeywords = [
  "iOS",
  "iOSApplicationExtension",
  "macOS",
  "macOSApplicationExtension",
  "macCatalyst",
  "macCatalystApplicationExtension",
  "watchOS",
  "watchOSApplicationExtension",
  "tvOS",
  "tvOSApplicationExtension",
  "swift"
];
function swift(hljs) {
  const WHITESPACE = {
    match: /\s+/,
    relevance: 0
  };
  const BLOCK_COMMENT = hljs.COMMENT(
    "/\\*",
    "\\*/",
    { contains: ["self"] }
  );
  const COMMENTS = [
    hljs.C_LINE_COMMENT_MODE,
    BLOCK_COMMENT
  ];
  const DOT_KEYWORD = {
    match: [
      /\./,
      either(...dotKeywords, ...optionalDotKeywords)
    ],
    className: { 2: "keyword" }
  };
  const KEYWORD_GUARD = {
    // Consume .keyword to prevent highlighting properties and methods as keywords.
    match: concat(/\./, either(...keywords)),
    relevance: 0
  };
  const PLAIN_KEYWORDS = keywords.filter((kw) => typeof kw === "string").concat(["_|0"]);
  const REGEX_KEYWORDS = keywords.filter((kw) => typeof kw !== "string").concat(keywordTypes).map(keywordWrapper);
  const KEYWORD = { variants: [
    {
      className: "keyword",
      match: either(...REGEX_KEYWORDS, ...optionalDotKeywords)
    }
  ] };
  const KEYWORDS3 = {
    $pattern: either(
      /\b\w+/,
      // regular keywords
      /#\w+/
      // number keywords
    ),
    keyword: PLAIN_KEYWORDS.concat(numberSignKeywords),
    literal: literals
  };
  const KEYWORD_MODES = [
    DOT_KEYWORD,
    KEYWORD_GUARD,
    KEYWORD
  ];
  const BUILT_IN_GUARD = {
    // Consume .built_in to prevent highlighting properties and methods.
    match: concat(/\./, either(...builtIns)),
    relevance: 0
  };
  const BUILT_IN = {
    className: "built_in",
    match: concat(/\b/, either(...builtIns), /(?=\()/)
  };
  const BUILT_INS3 = [
    BUILT_IN_GUARD,
    BUILT_IN
  ];
  const OPERATOR_GUARD = {
    // Prevent -> from being highlighting as an operator.
    match: /->/,
    relevance: 0
  };
  const OPERATOR = {
    className: "operator",
    relevance: 0,
    variants: [
      { match: operator },
      {
        // dot-operator: only operators that start with a dot are allowed to use dots as
        // characters (..., ...<, .*, etc). So there rule here is: a dot followed by one or more
        // characters that may also include dots.
        match: `\\.(\\.|${operatorCharacter})+`
      }
    ]
  };
  const OPERATORS = [
    OPERATOR_GUARD,
    OPERATOR
  ];
  const decimalDigits3 = "([0-9]_*)+";
  const hexDigits3 = "([0-9a-fA-F]_*)+";
  const NUMBER = {
    className: "number",
    relevance: 0,
    variants: [
      // decimal floating-point-literal (subsumes decimal-literal)
      { match: `\\b(${decimalDigits3})(\\.(${decimalDigits3}))?([eE][+-]?(${decimalDigits3}))?\\b` },
      // hexadecimal floating-point-literal (subsumes hexadecimal-literal)
      { match: `\\b0x(${hexDigits3})(\\.(${hexDigits3}))?([pP][+-]?(${decimalDigits3}))?\\b` },
      // octal-literal
      { match: /\b0o([0-7]_*)+\b/ },
      // binary-literal
      { match: /\b0b([01]_*)+\b/ }
    ]
  };
  const ESCAPED_CHARACTER = /* @__PURE__ */ __name((rawDelimiter = "") => ({
    className: "subst",
    variants: [
      { match: concat(/\\/, rawDelimiter, /[0\\tnr"']/) },
      { match: concat(/\\/, rawDelimiter, /u\{[0-9a-fA-F]{1,8}\}/) }
    ]
  }), "ESCAPED_CHARACTER");
  const ESCAPED_NEWLINE = /* @__PURE__ */ __name((rawDelimiter = "") => ({
    className: "subst",
    match: concat(/\\/, rawDelimiter, /[\t ]*(?:[\r\n]|\r\n)/)
  }), "ESCAPED_NEWLINE");
  const INTERPOLATION = /* @__PURE__ */ __name((rawDelimiter = "") => ({
    className: "subst",
    label: "interpol",
    begin: concat(/\\/, rawDelimiter, /\(/),
    end: /\)/
  }), "INTERPOLATION");
  const MULTILINE_STRING = /* @__PURE__ */ __name((rawDelimiter = "") => ({
    begin: concat(rawDelimiter, /"""/),
    end: concat(/"""/, rawDelimiter),
    contains: [
      ESCAPED_CHARACTER(rawDelimiter),
      ESCAPED_NEWLINE(rawDelimiter),
      INTERPOLATION(rawDelimiter)
    ]
  }), "MULTILINE_STRING");
  const SINGLE_LINE_STRING = /* @__PURE__ */ __name((rawDelimiter = "") => ({
    begin: concat(rawDelimiter, /"/),
    end: concat(/"/, rawDelimiter),
    contains: [
      ESCAPED_CHARACTER(rawDelimiter),
      INTERPOLATION(rawDelimiter)
    ]
  }), "SINGLE_LINE_STRING");
  const STRING = {
    className: "string",
    variants: [
      MULTILINE_STRING(),
      MULTILINE_STRING("#"),
      MULTILINE_STRING("##"),
      MULTILINE_STRING("###"),
      SINGLE_LINE_STRING(),
      SINGLE_LINE_STRING("#"),
      SINGLE_LINE_STRING("##"),
      SINGLE_LINE_STRING("###")
    ]
  };
  const REGEXP_CONTENTS = [
    hljs.BACKSLASH_ESCAPE,
    {
      begin: /\[/,
      end: /\]/,
      relevance: 0,
      contains: [hljs.BACKSLASH_ESCAPE]
    }
  ];
  const BARE_REGEXP_LITERAL = {
    begin: /\/[^\s](?=[^/\n]*\/)/,
    end: /\//,
    contains: REGEXP_CONTENTS
  };
  const EXTENDED_REGEXP_LITERAL = /* @__PURE__ */ __name((rawDelimiter) => {
    const begin = concat(rawDelimiter, /\//);
    const end = concat(/\//, rawDelimiter);
    return {
      begin,
      end,
      contains: [
        ...REGEXP_CONTENTS,
        {
          scope: "comment",
          begin: `#(?!.*${end})`,
          end: /$/
        }
      ]
    };
  }, "EXTENDED_REGEXP_LITERAL");
  const REGEXP = {
    scope: "regexp",
    variants: [
      EXTENDED_REGEXP_LITERAL("###"),
      EXTENDED_REGEXP_LITERAL("##"),
      EXTENDED_REGEXP_LITERAL("#"),
      BARE_REGEXP_LITERAL
    ]
  };
  const QUOTED_IDENTIFIER = { match: concat(/`/, identifier, /`/) };
  const IMPLICIT_PARAMETER = {
    className: "variable",
    match: /\$\d+/
  };
  const PROPERTY_WRAPPER_PROJECTION = {
    className: "variable",
    match: `\\$${identifierCharacter}+`
  };
  const IDENTIFIERS = [
    QUOTED_IDENTIFIER,
    IMPLICIT_PARAMETER,
    PROPERTY_WRAPPER_PROJECTION
  ];
  const AVAILABLE_ATTRIBUTE = {
    match: /(@|#(un)?)available/,
    scope: "keyword",
    starts: { contains: [
      {
        begin: /\(/,
        end: /\)/,
        keywords: availabilityKeywords,
        contains: [
          ...OPERATORS,
          NUMBER,
          STRING
        ]
      }
    ] }
  };
  const KEYWORD_ATTRIBUTE = {
    scope: "keyword",
    match: concat(/@/, either(...keywordAttributes), lookahead(either(/\(/, /\s+/)))
  };
  const USER_DEFINED_ATTRIBUTE = {
    scope: "meta",
    match: concat(/@/, identifier)
  };
  const ATTRIBUTES4 = [
    AVAILABLE_ATTRIBUTE,
    KEYWORD_ATTRIBUTE,
    USER_DEFINED_ATTRIBUTE
  ];
  const TYPE2 = {
    match: lookahead(/\b[A-Z]/),
    relevance: 0,
    contains: [
      {
        // Common Apple frameworks, for relevance boost
        className: "type",
        match: concat(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/, identifierCharacter, "+")
      },
      {
        // Type identifier
        className: "type",
        match: typeIdentifier,
        relevance: 0
      },
      {
        // Optional type
        match: /[?!]+/,
        relevance: 0
      },
      {
        // Variadic parameter
        match: /\.\.\./,
        relevance: 0
      },
      {
        // Protocol composition
        match: concat(/\s+&\s+/, lookahead(typeIdentifier)),
        relevance: 0
      }
    ]
  };
  const GENERIC_ARGUMENTS = {
    begin: /</,
    end: />/,
    keywords: KEYWORDS3,
    contains: [
      ...COMMENTS,
      ...KEYWORD_MODES,
      ...ATTRIBUTES4,
      OPERATOR_GUARD,
      TYPE2
    ]
  };
  TYPE2.contains.push(GENERIC_ARGUMENTS);
  const TUPLE_ELEMENT_NAME = {
    match: concat(identifier, /\s*:/),
    keywords: "_|0",
    relevance: 0
  };
  const TUPLE = {
    begin: /\(/,
    end: /\)/,
    relevance: 0,
    keywords: KEYWORDS3,
    contains: [
      "self",
      TUPLE_ELEMENT_NAME,
      ...COMMENTS,
      REGEXP,
      ...KEYWORD_MODES,
      ...BUILT_INS3,
      ...OPERATORS,
      NUMBER,
      STRING,
      ...IDENTIFIERS,
      ...ATTRIBUTES4,
      TYPE2
    ]
  };
  const GENERIC_PARAMETERS = {
    begin: /</,
    end: />/,
    keywords: "repeat each",
    contains: [
      ...COMMENTS,
      TYPE2
    ]
  };
  const FUNCTION_PARAMETER_NAME = {
    begin: either(
      lookahead(concat(identifier, /\s*:/)),
      lookahead(concat(identifier, /\s+/, identifier, /\s*:/))
    ),
    end: /:/,
    relevance: 0,
    contains: [
      {
        className: "keyword",
        match: /\b_\b/
      },
      {
        className: "params",
        match: identifier
      }
    ]
  };
  const FUNCTION_PARAMETERS = {
    begin: /\(/,
    end: /\)/,
    keywords: KEYWORDS3,
    contains: [
      FUNCTION_PARAMETER_NAME,
      ...COMMENTS,
      ...KEYWORD_MODES,
      ...OPERATORS,
      NUMBER,
      STRING,
      ...ATTRIBUTES4,
      TYPE2,
      TUPLE
    ],
    endsParent: true,
    illegal: /["']/
  };
  const FUNCTION_OR_MACRO = {
    match: [
      /(func|macro)/,
      /\s+/,
      either(QUOTED_IDENTIFIER.match, identifier, operator)
    ],
    className: {
      1: "keyword",
      3: "title.function"
    },
    contains: [
      GENERIC_PARAMETERS,
      FUNCTION_PARAMETERS,
      WHITESPACE
    ],
    illegal: [
      /\[/,
      /%/
    ]
  };
  const INIT_SUBSCRIPT = {
    match: [
      /\b(?:subscript|init[?!]?)/,
      /\s*(?=[<(])/
    ],
    className: { 1: "keyword" },
    contains: [
      GENERIC_PARAMETERS,
      FUNCTION_PARAMETERS,
      WHITESPACE
    ],
    illegal: /\[|%/
  };
  const OPERATOR_DECLARATION = {
    match: [
      /operator/,
      /\s+/,
      operator
    ],
    className: {
      1: "keyword",
      3: "title"
    }
  };
  const PRECEDENCEGROUP = {
    begin: [
      /precedencegroup/,
      /\s+/,
      typeIdentifier
    ],
    className: {
      1: "keyword",
      3: "title"
    },
    contains: [TYPE2],
    keywords: [
      ...precedencegroupKeywords,
      ...literals
    ],
    end: /}/
  };
  const CLASS_FUNC_DECLARATION = {
    match: [
      /class\b/,
      /\s+/,
      /func\b/,
      /\s+/,
      /\b[A-Za-z_][A-Za-z0-9_]*\b/
    ],
    scope: {
      1: "keyword",
      3: "keyword",
      5: "title.function"
    }
  };
  const CLASS_VAR_DECLARATION = {
    match: [
      /class\b/,
      /\s+/,
      /var\b/
    ],
    scope: {
      1: "keyword",
      3: "keyword"
    }
  };
  const TYPE_DECLARATION = {
    begin: [
      /(struct|protocol|class|extension|enum|actor)/,
      /\s+/,
      identifier,
      /\s*/
    ],
    beginScope: {
      1: "keyword",
      3: "title.class"
    },
    keywords: KEYWORDS3,
    contains: [
      GENERIC_PARAMETERS,
      ...KEYWORD_MODES,
      {
        begin: /:/,
        end: /\{/,
        keywords: KEYWORDS3,
        contains: [
          {
            scope: "title.class.inherited",
            match: typeIdentifier
          },
          ...KEYWORD_MODES
        ],
        relevance: 0
      }
    ]
  };
  for (const variant of STRING.variants) {
    const interpolation = variant.contains.find((mode) => mode.label === "interpol");
    interpolation.keywords = KEYWORDS3;
    const submodes = [
      ...KEYWORD_MODES,
      ...BUILT_INS3,
      ...OPERATORS,
      NUMBER,
      STRING,
      ...IDENTIFIERS
    ];
    interpolation.contains = [
      ...submodes,
      {
        begin: /\(/,
        end: /\)/,
        contains: [
          "self",
          ...submodes
        ]
      }
    ];
  }
  return {
    name: "Swift",
    keywords: KEYWORDS3,
    contains: [
      ...COMMENTS,
      FUNCTION_OR_MACRO,
      INIT_SUBSCRIPT,
      CLASS_FUNC_DECLARATION,
      CLASS_VAR_DECLARATION,
      TYPE_DECLARATION,
      OPERATOR_DECLARATION,
      PRECEDENCEGROUP,
      {
        beginKeywords: "import",
        end: /$/,
        contains: [...COMMENTS],
        relevance: 0
      },
      REGEXP,
      ...KEYWORD_MODES,
      ...BUILT_INS3,
      ...OPERATORS,
      NUMBER,
      STRING,
      ...IDENTIFIERS,
      ...ATTRIBUTES4,
      TYPE2,
      TUPLE
    ]
  };
}
__name(swift, "swift");

// node_modules/highlight.js/es/languages/typescript.js
init_esbuild_shims();
var IDENT_RE2 = "[A-Za-z$_][0-9A-Za-z$_]*";
var KEYWORDS2 = [
  "as",
  // for exports
  "in",
  "of",
  "if",
  "for",
  "while",
  "finally",
  "var",
  "new",
  "function",
  "do",
  "return",
  "void",
  "else",
  "break",
  "catch",
  "instanceof",
  "with",
  "throw",
  "case",
  "default",
  "try",
  "switch",
  "continue",
  "typeof",
  "delete",
  "let",
  "yield",
  "const",
  "class",
  // JS handles these with a special rule
  // "get",
  // "set",
  "debugger",
  "async",
  "await",
  "static",
  "import",
  "from",
  "export",
  "extends",
  // It's reached stage 3, which is "recommended for implementation":
  "using"
];
var LITERALS2 = [
  "true",
  "false",
  "null",
  "undefined",
  "NaN",
  "Infinity"
];
var TYPES2 = [
  // Fundamental objects
  "Object",
  "Function",
  "Boolean",
  "Symbol",
  // numbers and dates
  "Math",
  "Date",
  "Number",
  "BigInt",
  // text
  "String",
  "RegExp",
  // Indexed collections
  "Array",
  "Float32Array",
  "Float64Array",
  "Int8Array",
  "Uint8Array",
  "Uint8ClampedArray",
  "Int16Array",
  "Int32Array",
  "Uint16Array",
  "Uint32Array",
  "BigInt64Array",
  "BigUint64Array",
  // Keyed collections
  "Set",
  "Map",
  "WeakSet",
  "WeakMap",
  // Structured data
  "ArrayBuffer",
  "SharedArrayBuffer",
  "Atomics",
  "DataView",
  "JSON",
  // Control abstraction objects
  "Promise",
  "Generator",
  "GeneratorFunction",
  "AsyncFunction",
  // Reflection
  "Reflect",
  "Proxy",
  // Internationalization
  "Intl",
  // WebAssembly
  "WebAssembly"
];
var ERROR_TYPES2 = [
  "Error",
  "EvalError",
  "InternalError",
  "RangeError",
  "ReferenceError",
  "SyntaxError",
  "TypeError",
  "URIError"
];
var BUILT_IN_GLOBALS2 = [
  "setInterval",
  "setTimeout",
  "clearInterval",
  "clearTimeout",
  "require",
  "exports",
  "eval",
  "isFinite",
  "isNaN",
  "parseFloat",
  "parseInt",
  "decodeURI",
  "decodeURIComponent",
  "encodeURI",
  "encodeURIComponent",
  "escape",
  "unescape"
];
var BUILT_IN_VARIABLES2 = [
  "arguments",
  "this",
  "super",
  "console",
  "window",
  "document",
  "localStorage",
  "sessionStorage",
  "module",
  "global"
  // Node.js
];
var BUILT_INS2 = [].concat(
  BUILT_IN_GLOBALS2,
  TYPES2,
  ERROR_TYPES2
);
function javascript2(hljs) {
  const regex3 = hljs.regex;
  const hasClosingTag = /* @__PURE__ */ __name((match2, { after }) => {
    const tag2 = "</" + match2[0].slice(1);
    const pos2 = match2.input.indexOf(tag2, after);
    return pos2 !== -1;
  }, "hasClosingTag");
  const IDENT_RE$1 = IDENT_RE2;
  const FRAGMENT = {
    begin: "<>",
    end: "</>"
  };
  const XML_SELF_CLOSING = /<[A-Za-z0-9\\._:-]+\s*\/>/;
  const XML_TAG = {
    begin: /<[A-Za-z0-9\\._:-]+/,
    end: /\/[A-Za-z0-9\\._:-]+>|\/>/,
    /**
     * @param {RegExpMatchArray} match
     * @param {CallbackResponse} response
     */
    isTrulyOpeningTag: /* @__PURE__ */ __name((match2, response) => {
      const afterMatchIndex = match2[0].length + match2.index;
      const nextChar = match2.input[afterMatchIndex];
      if (
        // HTML should not include another raw `<` inside a tag
        // nested type?
        // `<Array<Array<number>>`, etc.
        nextChar === "<" || // the , gives away that this is not HTML
        // `<T, A extends keyof T, V>`
        nextChar === ","
      ) {
        response.ignoreMatch();
        return;
      }
      if (nextChar === ">") {
        if (!hasClosingTag(match2, { after: afterMatchIndex })) {
          response.ignoreMatch();
        }
      }
      let m;
      const afterMatch = match2.input.substring(afterMatchIndex);
      if (m = afterMatch.match(/^\s*=/)) {
        response.ignoreMatch();
        return;
      }
      if (m = afterMatch.match(/^\s+extends\s+/)) {
        if (m.index === 0) {
          response.ignoreMatch();
          return;
        }
      }
    }, "isTrulyOpeningTag")
  };
  const KEYWORDS$1 = {
    $pattern: IDENT_RE2,
    keyword: KEYWORDS2,
    literal: LITERALS2,
    built_in: BUILT_INS2,
    "variable.language": BUILT_IN_VARIABLES2
  };
  const decimalDigits3 = "[0-9](_?[0-9])*";
  const frac3 = `\\.(${decimalDigits3})`;
  const decimalInteger = `0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`;
  const NUMBER = {
    className: "number",
    variants: [
      // DecimalLiteral
      { begin: `(\\b(${decimalInteger})((${frac3})|\\.)?|(${frac3}))[eE][+-]?(${decimalDigits3})\\b` },
      { begin: `\\b(${decimalInteger})\\b((${frac3})\\b|\\.)?|(${frac3})\\b` },
      // DecimalBigIntegerLiteral
      { begin: `\\b(0|[1-9](_?[0-9])*)n\\b` },
      // NonDecimalIntegerLiteral
      { begin: "\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b" },
      { begin: "\\b0[bB][0-1](_?[0-1])*n?\\b" },
      { begin: "\\b0[oO][0-7](_?[0-7])*n?\\b" },
      // LegacyOctalIntegerLiteral (does not include underscore separators)
      // https://tc39.es/ecma262/#sec-additional-syntax-numeric-literals
      { begin: "\\b0[0-7]+n?\\b" }
    ],
    relevance: 0
  };
  const SUBST = {
    className: "subst",
    begin: "\\$\\{",
    end: "\\}",
    keywords: KEYWORDS$1,
    contains: []
    // defined later
  };
  const HTML_TEMPLATE = {
    begin: ".?html`",
    end: "",
    starts: {
      end: "`",
      returnEnd: false,
      contains: [
        hljs.BACKSLASH_ESCAPE,
        SUBST
      ],
      subLanguage: "xml"
    }
  };
  const CSS_TEMPLATE = {
    begin: ".?css`",
    end: "",
    starts: {
      end: "`",
      returnEnd: false,
      contains: [
        hljs.BACKSLASH_ESCAPE,
        SUBST
      ],
      subLanguage: "css"
    }
  };
  const GRAPHQL_TEMPLATE = {
    begin: ".?gql`",
    end: "",
    starts: {
      end: "`",
      returnEnd: false,
      contains: [
        hljs.BACKSLASH_ESCAPE,
        SUBST
      ],
      subLanguage: "graphql"
    }
  };
  const TEMPLATE_STRING = {
    className: "string",
    begin: "`",
    end: "`",
    contains: [
      hljs.BACKSLASH_ESCAPE,
      SUBST
    ]
  };
  const JSDOC_COMMENT = hljs.COMMENT(
    /\/\*\*(?!\/)/,
    "\\*/",
    {
      relevance: 0,
      contains: [
        {
          begin: "(?=@[A-Za-z]+)",
          relevance: 0,
          contains: [
            {
              className: "doctag",
              begin: "@[A-Za-z]+"
            },
            {
              className: "type",
              begin: "\\{",
              end: "\\}",
              excludeEnd: true,
              excludeBegin: true,
              relevance: 0
            },
            {
              className: "variable",
              begin: IDENT_RE$1 + "(?=\\s*(-)|$)",
              endsParent: true,
              relevance: 0
            },
            // eat spaces (not newlines) so we can find
            // types or variables
            {
              begin: /(?=[^\n])\s/,
              relevance: 0
            }
          ]
        }
      ]
    }
  );
  const COMMENT = {
    className: "comment",
    variants: [
      JSDOC_COMMENT,
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.C_LINE_COMMENT_MODE
    ]
  };
  const SUBST_INTERNALS = [
    hljs.APOS_STRING_MODE,
    hljs.QUOTE_STRING_MODE,
    HTML_TEMPLATE,
    CSS_TEMPLATE,
    GRAPHQL_TEMPLATE,
    TEMPLATE_STRING,
    // Skip numbers when they are part of a variable name
    { match: /\$\d+/ },
    NUMBER
    // This is intentional:
    // See https://github.com/highlightjs/highlight.js/issues/3288
    // hljs.REGEXP_MODE
  ];
  SUBST.contains = SUBST_INTERNALS.concat({
    // we need to pair up {} inside our subst to prevent
    // it from ending too early by matching another }
    begin: /\{/,
    end: /\}/,
    keywords: KEYWORDS$1,
    contains: [
      "self"
    ].concat(SUBST_INTERNALS)
  });
  const SUBST_AND_COMMENTS = [].concat(COMMENT, SUBST.contains);
  const PARAMS_CONTAINS = SUBST_AND_COMMENTS.concat([
    // eat recursive parens in sub expressions
    {
      begin: /(\s*)\(/,
      end: /\)/,
      keywords: KEYWORDS$1,
      contains: ["self"].concat(SUBST_AND_COMMENTS)
    }
  ]);
  const PARAMS = {
    className: "params",
    // convert this to negative lookbehind in v12
    begin: /(\s*)\(/,
    // to match the parms with
    end: /\)/,
    excludeBegin: true,
    excludeEnd: true,
    keywords: KEYWORDS$1,
    contains: PARAMS_CONTAINS
  };
  const CLASS_OR_EXTENDS = {
    variants: [
      // class Car extends vehicle
      {
        match: [
          /class/,
          /\s+/,
          IDENT_RE$1,
          /\s+/,
          /extends/,
          /\s+/,
          regex3.concat(IDENT_RE$1, "(", regex3.concat(/\./, IDENT_RE$1), ")*")
        ],
        scope: {
          1: "keyword",
          3: "title.class",
          5: "keyword",
          7: "title.class.inherited"
        }
      },
      // class Car
      {
        match: [
          /class/,
          /\s+/,
          IDENT_RE$1
        ],
        scope: {
          1: "keyword",
          3: "title.class"
        }
      }
    ]
  };
  const CLASS_REFERENCE = {
    relevance: 0,
    match: regex3.either(
      // Hard coded exceptions
      /\bJSON/,
      // Float32Array, OutT
      /\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,
      // CSSFactory, CSSFactoryT
      /\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,
      // FPs, FPsT
      /\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/
      // P
      // single letters are not highlighted
      // BLAH
      // this will be flagged as a UPPER_CASE_CONSTANT instead
    ),
    className: "title.class",
    keywords: {
      _: [
        // se we still get relevance credit for JS library classes
        ...TYPES2,
        ...ERROR_TYPES2
      ]
    }
  };
  const USE_STRICT = {
    label: "use_strict",
    className: "meta",
    relevance: 10,
    begin: /^\s*['"]use (strict|asm)['"]/
  };
  const FUNCTION_DEFINITION = {
    variants: [
      {
        match: [
          /function/,
          /\s+/,
          IDENT_RE$1,
          /(?=\s*\()/
        ]
      },
      // anonymous function
      {
        match: [
          /function/,
          /\s*(?=\()/
        ]
      }
    ],
    className: {
      1: "keyword",
      3: "title.function"
    },
    label: "func.def",
    contains: [PARAMS],
    illegal: /%/
  };
  const UPPER_CASE_CONSTANT = {
    relevance: 0,
    match: /\b[A-Z][A-Z_0-9]+\b/,
    className: "variable.constant"
  };
  function noneOf(list3) {
    return regex3.concat("(?!", list3.join("|"), ")");
  }
  __name(noneOf, "noneOf");
  const FUNCTION_CALL = {
    match: regex3.concat(
      /\b/,
      noneOf([
        ...BUILT_IN_GLOBALS2,
        "super",
        "import"
      ].map((x) => `${x}\\s*\\(`)),
      IDENT_RE$1,
      regex3.lookahead(/\s*\(/)
    ),
    className: "title.function",
    relevance: 0
  };
  const PROPERTY_ACCESS = {
    begin: regex3.concat(/\./, regex3.lookahead(
      regex3.concat(IDENT_RE$1, /(?![0-9A-Za-z$_(])/)
    )),
    end: IDENT_RE$1,
    excludeBegin: true,
    keywords: "prototype",
    className: "property",
    relevance: 0
  };
  const GETTER_OR_SETTER = {
    match: [
      /get|set/,
      /\s+/,
      IDENT_RE$1,
      /(?=\()/
    ],
    className: {
      1: "keyword",
      3: "title.function"
    },
    contains: [
      {
        // eat to avoid empty params
        begin: /\(\)/
      },
      PARAMS
    ]
  };
  const FUNC_LEAD_IN_RE = "(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|" + hljs.UNDERSCORE_IDENT_RE + ")\\s*=>";
  const FUNCTION_VARIABLE = {
    match: [
      /const|var|let/,
      /\s+/,
      IDENT_RE$1,
      /\s*/,
      /=\s*/,
      /(async\s*)?/,
      // async is optional
      regex3.lookahead(FUNC_LEAD_IN_RE)
    ],
    keywords: "async",
    className: {
      1: "keyword",
      3: "title.function"
    },
    contains: [
      PARAMS
    ]
  };
  return {
    name: "JavaScript",
    aliases: ["js", "jsx", "mjs", "cjs"],
    keywords: KEYWORDS$1,
    // this will be extended by TypeScript
    exports: { PARAMS_CONTAINS, CLASS_REFERENCE },
    illegal: /#(?![$_A-z])/,
    contains: [
      hljs.SHEBANG({
        label: "shebang",
        binary: "node",
        relevance: 5
      }),
      USE_STRICT,
      hljs.APOS_STRING_MODE,
      hljs.QUOTE_STRING_MODE,
      HTML_TEMPLATE,
      CSS_TEMPLATE,
      GRAPHQL_TEMPLATE,
      TEMPLATE_STRING,
      COMMENT,
      // Skip numbers when they are part of a variable name
      { match: /\$\d+/ },
      NUMBER,
      CLASS_REFERENCE,
      {
        scope: "attr",
        match: IDENT_RE$1 + regex3.lookahead(":"),
        relevance: 0
      },
      FUNCTION_VARIABLE,
      {
        // "value" container
        begin: "(" + hljs.RE_STARTERS_RE + "|\\b(case|return|throw)\\b)\\s*",
        keywords: "return throw case",
        relevance: 0,
        contains: [
          COMMENT,
          hljs.REGEXP_MODE,
          {
            className: "function",
            // we have to count the parens to make sure we actually have the
            // correct bounding ( ) before the =>.  There could be any number of
            // sub-expressions inside also surrounded by parens.
            begin: FUNC_LEAD_IN_RE,
            returnBegin: true,
            end: "\\s*=>",
            contains: [
              {
                className: "params",
                variants: [
                  {
                    begin: hljs.UNDERSCORE_IDENT_RE,
                    relevance: 0
                  },
                  {
                    className: null,
                    begin: /\(\s*\)/,
                    skip: true
                  },
                  {
                    begin: /(\s*)\(/,
                    end: /\)/,
                    excludeBegin: true,
                    excludeEnd: true,
                    keywords: KEYWORDS$1,
                    contains: PARAMS_CONTAINS
                  }
                ]
              }
            ]
          },
          {
            // could be a comma delimited list of params to a function call
            begin: /,/,
            relevance: 0
          },
          {
            match: /\s+/,
            relevance: 0
          },
          {
            // JSX
            variants: [
              { begin: FRAGMENT.begin, end: FRAGMENT.end },
              { match: XML_SELF_CLOSING },
              {
                begin: XML_TAG.begin,
                // we carefully check the opening tag to see if it truly
                // is a tag and not a false positive
                "on:begin": XML_TAG.isTrulyOpeningTag,
                end: XML_TAG.end
              }
            ],
            subLanguage: "xml",
            contains: [
              {
                begin: XML_TAG.begin,
                end: XML_TAG.end,
                skip: true,
                contains: ["self"]
              }
            ]
          }
        ]
      },
      FUNCTION_DEFINITION,
      {
        // prevent this from getting swallowed up by function
        // since they appear "function like"
        beginKeywords: "while if switch catch for"
      },
      {
        // we have to count the parens to make sure we actually have the correct
        // bounding ( ).  There could be any number of sub-expressions inside
        // also surrounded by parens.
        begin: "\\b(?!function)" + hljs.UNDERSCORE_IDENT_RE + "\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",
        // end parens
        returnBegin: true,
        label: "func.def",
        contains: [
          PARAMS,
          hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1, className: "title.function" })
        ]
      },
      // catch ... so it won't trigger the property rule below
      {
        match: /\.\.\./,
        relevance: 0
      },
      PROPERTY_ACCESS,
      // hack: prevents detection of keywords in some circumstances
      // .keyword()
      // $keyword = x
      {
        match: "\\$" + IDENT_RE$1,
        relevance: 0
      },
      {
        match: [/\bconstructor(?=\s*\()/],
        className: { 1: "title.function" },
        contains: [PARAMS]
      },
      FUNCTION_CALL,
      UPPER_CASE_CONSTANT,
      CLASS_OR_EXTENDS,
      GETTER_OR_SETTER,
      {
        match: /\$[(.]/
        // relevance booster for a pattern common to JS libs: `$(something)` and `$.something`
      }
    ]
  };
}
__name(javascript2, "javascript");
function typescript(hljs) {
  const regex3 = hljs.regex;
  const tsLanguage = javascript2(hljs);
  const IDENT_RE$1 = IDENT_RE2;
  const TYPES3 = [
    "any",
    "void",
    "number",
    "boolean",
    "string",
    "object",
    "never",
    "symbol",
    "bigint",
    "unknown"
  ];
  const NAMESPACE = {
    begin: [
      /namespace/,
      /\s+/,
      hljs.IDENT_RE
    ],
    beginScope: {
      1: "keyword",
      3: "title.class"
    }
  };
  const INTERFACE = {
    beginKeywords: "interface",
    end: /\{/,
    excludeEnd: true,
    keywords: {
      keyword: "interface extends",
      built_in: TYPES3
    },
    contains: [tsLanguage.exports.CLASS_REFERENCE]
  };
  const USE_STRICT = {
    className: "meta",
    relevance: 10,
    begin: /^\s*['"]use strict['"]/
  };
  const TS_SPECIFIC_KEYWORDS = [
    "type",
    // "namespace",
    "interface",
    "public",
    "private",
    "protected",
    "implements",
    "declare",
    "abstract",
    "readonly",
    "enum",
    "override",
    "satisfies"
  ];
  const KEYWORDS$1 = {
    $pattern: IDENT_RE2,
    keyword: KEYWORDS2.concat(TS_SPECIFIC_KEYWORDS),
    literal: LITERALS2,
    built_in: BUILT_INS2.concat(TYPES3),
    "variable.language": BUILT_IN_VARIABLES2
  };
  const DECORATOR = {
    className: "meta",
    begin: "@" + IDENT_RE$1
  };
  const swapMode = /* @__PURE__ */ __name((mode, label, replacement) => {
    const indx = mode.contains.findIndex((m) => m.label === label);
    if (indx === -1) {
      throw new Error("can not find mode to replace");
    }
    mode.contains.splice(indx, 1, replacement);
  }, "swapMode");
  Object.assign(tsLanguage.keywords, KEYWORDS$1);
  tsLanguage.exports.PARAMS_CONTAINS.push(DECORATOR);
  const ATTRIBUTE_HIGHLIGHT = tsLanguage.contains.find((c3) => c3.scope === "attr");
  const OPTIONAL_KEY_OR_ARGUMENT = Object.assign(
    {},
    ATTRIBUTE_HIGHLIGHT,
    { match: regex3.concat(IDENT_RE$1, regex3.lookahead(/\s*\?:/)) }
  );
  tsLanguage.exports.PARAMS_CONTAINS.push([
    tsLanguage.exports.CLASS_REFERENCE,
    // class reference for highlighting the params types
    ATTRIBUTE_HIGHLIGHT,
    // highlight the params key
    OPTIONAL_KEY_OR_ARGUMENT
    // Added for optional property assignment highlighting
  ]);
  tsLanguage.contains = tsLanguage.contains.concat([
    DECORATOR,
    NAMESPACE,
    INTERFACE,
    OPTIONAL_KEY_OR_ARGUMENT
    // Added for optional property assignment highlighting
  ]);
  swapMode(tsLanguage, "shebang", hljs.SHEBANG());
  swapMode(tsLanguage, "use_strict", USE_STRICT);
  const functionDeclaration = tsLanguage.contains.find((m) => m.label === "func.def");
  functionDeclaration.relevance = 0;
  Object.assign(tsLanguage, {
    name: "TypeScript",
    aliases: [
      "ts",
      "tsx",
      "mts",
      "cts"
    ]
  });
  return tsLanguage;
}
__name(typescript, "typescript");

// node_modules/highlight.js/es/languages/vbnet.js
init_esbuild_shims();
function vbnet(hljs) {
  const regex3 = hljs.regex;
  const CHARACTER = {
    className: "string",
    begin: /"(""|[^/n])"C\b/
  };
  const STRING = {
    className: "string",
    begin: /"/,
    end: /"/,
    illegal: /\n/,
    contains: [
      {
        // double quote escape
        begin: /""/
      }
    ]
  };
  const MM_DD_YYYY = /\d{1,2}\/\d{1,2}\/\d{4}/;
  const YYYY_MM_DD = /\d{4}-\d{1,2}-\d{1,2}/;
  const TIME_12H = /(\d|1[012])(:\d+){0,2} *(AM|PM)/;
  const TIME_24H = /\d{1,2}(:\d{1,2}){1,2}/;
  const DATE = {
    className: "literal",
    variants: [
      {
        // #YYYY-MM-DD# (ISO-Date) or #M/D/YYYY# (US-Date)
        begin: regex3.concat(/# */, regex3.either(YYYY_MM_DD, MM_DD_YYYY), / *#/)
      },
      {
        // #H:mm[:ss]# (24h Time)
        begin: regex3.concat(/# */, TIME_24H, / *#/)
      },
      {
        // #h[:mm[:ss]] A# (12h Time)
        begin: regex3.concat(/# */, TIME_12H, / *#/)
      },
      {
        // date plus time
        begin: regex3.concat(
          /# */,
          regex3.either(YYYY_MM_DD, MM_DD_YYYY),
          / +/,
          regex3.either(TIME_12H, TIME_24H),
          / *#/
        )
      }
    ]
  };
  const NUMBER = {
    className: "number",
    relevance: 0,
    variants: [
      {
        // Float
        begin: /\b\d[\d_]*((\.[\d_]+(E[+-]?[\d_]+)?)|(E[+-]?[\d_]+))[RFD@!#]?/
      },
      {
        // Integer (base 10)
        begin: /\b\d[\d_]*((U?[SIL])|[%&])?/
      },
      {
        // Integer (base 16)
        begin: /&H[\dA-F_]+((U?[SIL])|[%&])?/
      },
      {
        // Integer (base 8)
        begin: /&O[0-7_]+((U?[SIL])|[%&])?/
      },
      {
        // Integer (base 2)
        begin: /&B[01_]+((U?[SIL])|[%&])?/
      }
    ]
  };
  const LABEL = {
    className: "label",
    begin: /^\w+:/
  };
  const DOC_COMMENT = hljs.COMMENT(/'''/, /$/, { contains: [
    {
      className: "doctag",
      begin: /<\/?/,
      end: />/
    }
  ] });
  const COMMENT = hljs.COMMENT(null, /$/, { variants: [
    { begin: /'/ },
    {
      // TODO: Use multi-class for leading spaces
      begin: /([\t ]|^)REM(?=\s)/
    }
  ] });
  const DIRECTIVES = {
    className: "meta",
    // TODO: Use multi-class for indentation once available
    begin: /[\t ]*#(const|disable|else|elseif|enable|end|externalsource|if|region)\b/,
    end: /$/,
    keywords: { keyword: "const disable else elseif enable end externalsource if region then" },
    contains: [COMMENT]
  };
  return {
    name: "Visual Basic .NET",
    aliases: ["vb"],
    case_insensitive: true,
    classNameAliases: { label: "symbol" },
    keywords: {
      keyword: "addhandler alias aggregate ansi as async assembly auto binary by byref byval call case catch class compare const continue custom declare default delegate dim distinct do each equals else elseif end enum erase error event exit explicit finally for friend from function get global goto group handles if implements imports in inherits interface into iterator join key let lib loop me mid module mustinherit mustoverride mybase myclass namespace narrowing new next notinheritable notoverridable of off on operator option optional order overloads overridable overrides paramarray partial preserve private property protected public raiseevent readonly redim removehandler resume return select set shadows shared skip static step stop structure strict sub synclock take text then throw to try unicode until using when where while widening with withevents writeonly yield",
      built_in: (
        // Operators https://docs.microsoft.com/dotnet/visual-basic/language-reference/operators
        "addressof and andalso await directcast gettype getxmlnamespace is isfalse isnot istrue like mod nameof new not or orelse trycast typeof xor cbool cbyte cchar cdate cdbl cdec cint clng cobj csbyte cshort csng cstr cuint culng cushort"
      ),
      type: (
        // Data types https://docs.microsoft.com/dotnet/visual-basic/language-reference/data-types
        "boolean byte char date decimal double integer long object sbyte short single string uinteger ulong ushort"
      ),
      literal: "true false nothing"
    },
    illegal: "//|\\{|\\}|endif|gosub|variant|wend|^\\$ ",
    contains: [
      CHARACTER,
      STRING,
      DATE,
      NUMBER,
      LABEL,
      DOC_COMMENT,
      COMMENT,
      DIRECTIVES
    ]
  };
}
__name(vbnet, "vbnet");

// node_modules/highlight.js/es/languages/wasm.js
init_esbuild_shims();
function wasm(hljs) {
  hljs.regex;
  const BLOCK_COMMENT = hljs.COMMENT(/\(;/, /;\)/);
  BLOCK_COMMENT.contains.push("self");
  const LINE_COMMENT = hljs.COMMENT(/;;/, /$/);
  const KWS = [
    "anyfunc",
    "block",
    "br",
    "br_if",
    "br_table",
    "call",
    "call_indirect",
    "data",
    "drop",
    "elem",
    "else",
    "end",
    "export",
    "func",
    "global.get",
    "global.set",
    "local.get",
    "local.set",
    "local.tee",
    "get_global",
    "get_local",
    "global",
    "if",
    "import",
    "local",
    "loop",
    "memory",
    "memory.grow",
    "memory.size",
    "module",
    "mut",
    "nop",
    "offset",
    "param",
    "result",
    "return",
    "select",
    "set_global",
    "set_local",
    "start",
    "table",
    "tee_local",
    "then",
    "type",
    "unreachable"
  ];
  const FUNCTION_REFERENCE = {
    begin: [
      /(?:func|call|call_indirect)/,
      /\s+/,
      /\$[^\s)]+/
    ],
    className: {
      1: "keyword",
      3: "title.function"
    }
  };
  const ARGUMENT = {
    className: "variable",
    begin: /\$[\w_]+/
  };
  const PARENS = {
    match: /(\((?!;)|\))+/,
    className: "punctuation",
    relevance: 0
  };
  const NUMBER = {
    className: "number",
    relevance: 0,
    // borrowed from Prism, TODO: split out into variants
    match: /[+-]?\b(?:\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?|0x[\da-fA-F](?:_?[\da-fA-F])*(?:\.[\da-fA-F](?:_?[\da-fA-D])*)?(?:[pP][+-]?\d(?:_?\d)*)?)\b|\binf\b|\bnan(?::0x[\da-fA-F](?:_?[\da-fA-D])*)?\b/
  };
  const TYPE2 = {
    // look-ahead prevents us from gobbling up opcodes
    match: /(i32|i64|f32|f64)(?!\.)/,
    className: "type"
  };
  const MATH_OPERATIONS = {
    className: "keyword",
    // borrowed from Prism, TODO: split out into variants
    match: /\b(f32|f64|i32|i64)(?:\.(?:abs|add|and|ceil|clz|const|convert_[su]\/i(?:32|64)|copysign|ctz|demote\/f64|div(?:_[su])?|eqz?|extend_[su]\/i32|floor|ge(?:_[su])?|gt(?:_[su])?|le(?:_[su])?|load(?:(?:8|16|32)_[su])?|lt(?:_[su])?|max|min|mul|nearest|neg?|or|popcnt|promote\/f32|reinterpret\/[fi](?:32|64)|rem_[su]|rot[lr]|shl|shr_[su]|store(?:8|16|32)?|sqrt|sub|trunc(?:_[su]\/f(?:32|64))?|wrap\/i64|xor))\b/
  };
  const OFFSET_ALIGN = {
    match: [
      /(?:offset|align)/,
      /\s*/,
      /=/
    ],
    className: {
      1: "keyword",
      3: "operator"
    }
  };
  return {
    name: "WebAssembly",
    keywords: {
      $pattern: /[\w.]+/,
      keyword: KWS
    },
    contains: [
      LINE_COMMENT,
      BLOCK_COMMENT,
      OFFSET_ALIGN,
      ARGUMENT,
      PARENS,
      FUNCTION_REFERENCE,
      hljs.QUOTE_STRING_MODE,
      TYPE2,
      MATH_OPERATIONS,
      NUMBER
    ]
  };
}
__name(wasm, "wasm");

// node_modules/highlight.js/es/languages/xml.js
init_esbuild_shims();
function xml(hljs) {
  const regex3 = hljs.regex;
  const TAG_NAME_RE = regex3.concat(/[\p{L}_]/u, regex3.optional(/[\p{L}0-9_.-]*:/u), /[\p{L}0-9_.-]*/u);
  const XML_IDENT_RE = /[\p{L}0-9._:-]+/u;
  const XML_ENTITIES = {
    className: "symbol",
    begin: /&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/
  };
  const XML_META_KEYWORDS = {
    begin: /\s/,
    contains: [
      {
        className: "keyword",
        begin: /#?[a-z_][a-z1-9_-]+/,
        illegal: /\n/
      }
    ]
  };
  const XML_META_PAR_KEYWORDS = hljs.inherit(XML_META_KEYWORDS, {
    begin: /\(/,
    end: /\)/
  });
  const APOS_META_STRING_MODE = hljs.inherit(hljs.APOS_STRING_MODE, { className: "string" });
  const QUOTE_META_STRING_MODE = hljs.inherit(hljs.QUOTE_STRING_MODE, { className: "string" });
  const TAG_INTERNALS = {
    endsWithParent: true,
    illegal: /</,
    relevance: 0,
    contains: [
      {
        className: "attr",
        begin: XML_IDENT_RE,
        relevance: 0
      },
      {
        begin: /=\s*/,
        relevance: 0,
        contains: [
          {
            className: "string",
            endsParent: true,
            variants: [
              {
                begin: /"/,
                end: /"/,
                contains: [XML_ENTITIES]
              },
              {
                begin: /'/,
                end: /'/,
                contains: [XML_ENTITIES]
              },
              { begin: /[^\s"'=<>`]+/ }
            ]
          }
        ]
      }
    ]
  };
  return {
    name: "HTML, XML",
    aliases: [
      "html",
      "xhtml",
      "rss",
      "atom",
      "xjb",
      "xsd",
      "xsl",
      "plist",
      "wsf",
      "svg"
    ],
    case_insensitive: true,
    unicodeRegex: true,
    contains: [
      {
        className: "meta",
        begin: /<![a-z]/,
        end: />/,
        relevance: 10,
        contains: [
          XML_META_KEYWORDS,
          QUOTE_META_STRING_MODE,
          APOS_META_STRING_MODE,
          XML_META_PAR_KEYWORDS,
          {
            begin: /\[/,
            end: /\]/,
            contains: [
              {
                className: "meta",
                begin: /<![a-z]/,
                end: />/,
                contains: [
                  XML_META_KEYWORDS,
                  XML_META_PAR_KEYWORDS,
                  QUOTE_META_STRING_MODE,
                  APOS_META_STRING_MODE
                ]
              }
            ]
          }
        ]
      },
      hljs.COMMENT(
        /<!--/,
        /-->/,
        { relevance: 10 }
      ),
      {
        begin: /<!\[CDATA\[/,
        end: /\]\]>/,
        relevance: 10
      },
      XML_ENTITIES,
      // xml processing instructions
      {
        className: "meta",
        end: /\?>/,
        variants: [
          {
            begin: /<\?xml/,
            relevance: 10,
            contains: [
              QUOTE_META_STRING_MODE
            ]
          },
          {
            begin: /<\?[a-z][a-z0-9]+/
          }
        ]
      },
      {
        className: "tag",
        /*
        The lookahead pattern (?=...) ensures that 'begin' only matches
        '<style' as a single word, followed by a whitespace or an
        ending bracket.
        */
        begin: /<style(?=\s|>)/,
        end: />/,
        keywords: { name: "style" },
        contains: [TAG_INTERNALS],
        starts: {
          end: /<\/style>/,
          returnEnd: true,
          subLanguage: [
            "css",
            "xml"
          ]
        }
      },
      {
        className: "tag",
        // See the comment in the <style tag about the lookahead pattern
        begin: /<script(?=\s|>)/,
        end: />/,
        keywords: { name: "script" },
        contains: [TAG_INTERNALS],
        starts: {
          end: /<\/script>/,
          returnEnd: true,
          subLanguage: [
            "javascript",
            "handlebars",
            "xml"
          ]
        }
      },
      // we need this for now for jSX
      {
        className: "tag",
        begin: /<>|<\/>/
      },
      // open tag
      {
        className: "tag",
        begin: regex3.concat(
          /</,
          regex3.lookahead(regex3.concat(
            TAG_NAME_RE,
            // <tag/>
            // <tag>
            // <tag ...
            regex3.either(/\/>/, />/, /\s/)
          ))
        ),
        end: /\/?>/,
        contains: [
          {
            className: "name",
            begin: TAG_NAME_RE,
            relevance: 0,
            starts: TAG_INTERNALS
          }
        ]
      },
      // close tag
      {
        className: "tag",
        begin: regex3.concat(
          /<\//,
          regex3.lookahead(regex3.concat(
            TAG_NAME_RE,
            />/
          ))
        ),
        contains: [
          {
            className: "name",
            begin: TAG_NAME_RE,
            relevance: 0
          },
          {
            begin: />/,
            relevance: 0,
            endsParent: true
          }
        ]
      }
    ]
  };
}
__name(xml, "xml");

// node_modules/highlight.js/es/languages/yaml.js
init_esbuild_shims();
function yaml(hljs) {
  const LITERALS3 = "true false yes no null";
  const URI_CHARACTERS = "[\\w#;/?:@&=+$,.~*'()[\\]]+";
  const KEY = {
    className: "attr",
    variants: [
      // added brackets support and special char support
      { begin: /[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/ },
      {
        // double quoted keys - with brackets and special char support
        begin: /"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/
      },
      {
        // single quoted keys - with brackets and special char support
        begin: /'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/
      }
    ]
  };
  const TEMPLATE_VARIABLES = {
    className: "template-variable",
    variants: [
      {
        // jinja templates Ansible
        begin: /\{\{/,
        end: /\}\}/
      },
      {
        // Ruby i18n
        begin: /%\{/,
        end: /\}/
      }
    ]
  };
  const SINGLE_QUOTE_STRING = {
    className: "string",
    relevance: 0,
    begin: /'/,
    end: /'/,
    contains: [
      {
        match: /''/,
        scope: "char.escape",
        relevance: 0
      }
    ]
  };
  const STRING = {
    className: "string",
    relevance: 0,
    variants: [
      {
        begin: /"/,
        end: /"/
      },
      { begin: /\S+/ }
    ],
    contains: [
      hljs.BACKSLASH_ESCAPE,
      TEMPLATE_VARIABLES
    ]
  };
  const CONTAINER_STRING = hljs.inherit(STRING, { variants: [
    {
      begin: /'/,
      end: /'/,
      contains: [
        {
          begin: /''/,
          relevance: 0
        }
      ]
    },
    {
      begin: /"/,
      end: /"/
    },
    { begin: /[^\s,{}[\]]+/ }
  ] });
  const DATE_RE = "[0-9]{4}(-[0-9][0-9]){0,2}";
  const TIME_RE = "([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?";
  const FRACTION_RE = "(\\.[0-9]*)?";
  const ZONE_RE = "([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?";
  const TIMESTAMP = {
    className: "number",
    begin: "\\b" + DATE_RE + TIME_RE + FRACTION_RE + ZONE_RE + "\\b"
  };
  const VALUE_CONTAINER = {
    end: ",",
    endsWithParent: true,
    excludeEnd: true,
    keywords: LITERALS3,
    relevance: 0
  };
  const OBJECT = {
    begin: /\{/,
    end: /\}/,
    contains: [VALUE_CONTAINER],
    illegal: "\\n",
    relevance: 0
  };
  const ARRAY = {
    begin: "\\[",
    end: "\\]",
    contains: [VALUE_CONTAINER],
    illegal: "\\n",
    relevance: 0
  };
  const MODES4 = [
    KEY,
    {
      className: "meta",
      begin: "^---\\s*$",
      relevance: 10
    },
    {
      // multi line string
      // Blocks start with a | or > followed by a newline
      //
      // Indentation of subsequent lines must be the same to
      // be considered part of the block
      className: "string",
      begin: "[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"
    },
    {
      // Ruby/Rails erb
      begin: "<%[%=-]?",
      end: "[%-]?%>",
      subLanguage: "ruby",
      excludeBegin: true,
      excludeEnd: true,
      relevance: 0
    },
    {
      // named tags
      className: "type",
      begin: "!\\w+!" + URI_CHARACTERS
    },
    // https://yaml.org/spec/1.2/spec.html#id2784064
    {
      // verbatim tags
      className: "type",
      begin: "!<" + URI_CHARACTERS + ">"
    },
    {
      // primary tags
      className: "type",
      begin: "!" + URI_CHARACTERS
    },
    {
      // secondary tags
      className: "type",
      begin: "!!" + URI_CHARACTERS
    },
    {
      // fragment id &ref
      className: "meta",
      begin: "&" + hljs.UNDERSCORE_IDENT_RE + "$"
    },
    {
      // fragment reference *ref
      className: "meta",
      begin: "\\*" + hljs.UNDERSCORE_IDENT_RE + "$"
    },
    {
      // array listing
      className: "bullet",
      // TODO: remove |$ hack when we have proper look-ahead support
      begin: "-(?=[ ]|$)",
      relevance: 0
    },
    hljs.HASH_COMMENT_MODE,
    {
      beginKeywords: LITERALS3,
      keywords: { literal: LITERALS3 }
    },
    TIMESTAMP,
    // numbers are any valid C-style number that
    // sit isolated from other words
    {
      className: "number",
      begin: hljs.C_NUMBER_RE + "\\b",
      relevance: 0
    },
    OBJECT,
    ARRAY,
    SINGLE_QUOTE_STRING,
    STRING
  ];
  const VALUE_MODES = [...MODES4];
  VALUE_MODES.pop();
  VALUE_MODES.push(CONTAINER_STRING);
  VALUE_CONTAINER.contains = VALUE_MODES;
  return {
    name: "YAML",
    case_insensitive: true,
    aliases: ["yml"],
    contains: MODES4
  };
}
__name(yaml, "yaml");

// node_modules/lowlight/lib/common.js
var grammars = {
  arduino,
  bash,
  c: c2,
  cpp,
  csharp,
  css,
  diff: diff3,
  go,
  graphql,
  ini,
  java,
  javascript,
  json,
  kotlin,
  less,
  lua,
  makefile,
  markdown,
  objectivec,
  perl,
  php,
  "php-template": phpTemplate,
  plaintext,
  python,
  "python-repl": pythonRepl,
  r: r2,
  ruby,
  rust,
  scss,
  shell,
  sql,
  swift,
  typescript,
  vbnet,
  wasm,
  xml,
  yaml
};

// node_modules/lowlight/lib/index.js
init_esbuild_shims();

// node_modules/devlop/lib/default.js
init_esbuild_shims();
function ok() {
}
__name(ok, "ok");

// node_modules/highlight.js/es/core.js
init_esbuild_shims();
var import_core4 = __toESM(require_core8(), 1);
var core_default = import_core4.default;

// node_modules/lowlight/lib/index.js
var emptyOptions = {};
var defaultPrefix = "hljs-";
function createLowlight(grammars2) {
  const high = core_default.newInstance();
  if (grammars2) {
    register(grammars2);
  }
  return {
    highlight,
    highlightAuto,
    listLanguages,
    register,
    registerAlias,
    registered
  };
  function highlight(language, value, options2) {
    ok(typeof language === "string", "expected `string` as `name`");
    ok(typeof value === "string", "expected `string` as `value`");
    const settings = options2 || emptyOptions;
    const prefix = typeof settings.prefix === "string" ? settings.prefix : defaultPrefix;
    if (!high.getLanguage(language)) {
      throw new Error("Unknown language: `" + language + "` is not registered");
    }
    high.configure({ __emitter: HastEmitter, classPrefix: prefix });
    const result = (
      /** @type {HighlightResult & {_emitter: HastEmitter}} */
      high.highlight(value, { ignoreIllegals: true, language })
    );
    if (result.errorRaised) {
      throw new Error("Could not highlight with `Highlight.js`", {
        cause: result.errorRaised
      });
    }
    const root = result._emitter.root;
    const data = (
      /** @type {RootData} */
      root.data
    );
    data.language = result.language;
    data.relevance = result.relevance;
    return root;
  }
  __name(highlight, "highlight");
  function highlightAuto(value, options2) {
    ok(typeof value === "string", "expected `string` as `value`");
    const settings = options2 || emptyOptions;
    const subset = settings.subset || listLanguages();
    let index = -1;
    let relevance = 0;
    let result;
    while (++index < subset.length) {
      const name3 = subset[index];
      if (!high.getLanguage(name3)) continue;
      const current = highlight(name3, value, options2);
      if (current.data && current.data.relevance !== void 0 && current.data.relevance > relevance) {
        relevance = current.data.relevance;
        result = current;
      }
    }
    return result || {
      type: "root",
      children: [],
      data: { language: void 0, relevance }
    };
  }
  __name(highlightAuto, "highlightAuto");
  function listLanguages() {
    return high.listLanguages();
  }
  __name(listLanguages, "listLanguages");
  function register(grammarsOrName, grammar) {
    if (typeof grammarsOrName === "string") {
      ok(grammar !== void 0, "expected `grammar`");
      high.registerLanguage(grammarsOrName, grammar);
    } else {
      let name3;
      for (name3 in grammarsOrName) {
        if (Object.hasOwn(grammarsOrName, name3)) {
          high.registerLanguage(name3, grammarsOrName[name3]);
        }
      }
    }
  }
  __name(register, "register");
  function registerAlias(aliasesOrName, alias) {
    if (typeof aliasesOrName === "string") {
      ok(alias !== void 0);
      high.registerAliases(
        // Note: copy needed because hljs doesn’t accept readonly arrays yet.
        typeof alias === "string" ? alias : [...alias],
        { languageName: aliasesOrName }
      );
    } else {
      let key;
      for (key in aliasesOrName) {
        if (Object.hasOwn(aliasesOrName, key)) {
          const aliases = aliasesOrName[key];
          high.registerAliases(
            // Note: copy needed because hljs doesn’t accept readonly arrays yet.
            typeof aliases === "string" ? aliases : [...aliases],
            { languageName: key }
          );
        }
      }
    }
  }
  __name(registerAlias, "registerAlias");
  function registered(aliasOrName) {
    return Boolean(high.getLanguage(aliasOrName));
  }
  __name(registered, "registered");
}
__name(createLowlight, "createLowlight");
var HastEmitter = class {
  static {
    __name(this, "HastEmitter");
  }
  /**
   * @param {Readonly<HljsOptions>} options
   *   Configuration.
   * @returns
   *   Instance.
   */
  constructor(options2) {
    this.options = options2;
    this.root = {
      type: "root",
      children: [],
      data: { language: void 0, relevance: 0 }
    };
    this.stack = [this.root];
  }
  /**
   * @param {string} value
   *   Text to add.
   * @returns {undefined}
   *   Nothing.
   *
   */
  addText(value) {
    if (value === "") return;
    const current = this.stack[this.stack.length - 1];
    const tail = current.children[current.children.length - 1];
    if (tail && tail.type === "text") {
      tail.value += value;
    } else {
      current.children.push({ type: "text", value });
    }
  }
  /**
   *
   * @param {unknown} rawName
   *   Name to add.
   * @returns {undefined}
   *   Nothing.
   */
  startScope(rawName) {
    this.openNode(String(rawName));
  }
  /**
   * @returns {undefined}
   *   Nothing.
   */
  endScope() {
    this.closeNode();
  }
  /**
   * @param {HastEmitter} other
   *   Other emitter.
   * @param {string} name
   *   Name of the sublanguage.
   * @returns {undefined}
   *   Nothing.
   */
  __addSublanguage(other2, name3) {
    const current = this.stack[this.stack.length - 1];
    const results = (
      /** @type {Array<ElementContent>} */
      other2.root.children
    );
    if (name3) {
      current.children.push({
        type: "element",
        tagName: "span",
        properties: { className: [name3] },
        children: results
      });
    } else {
      current.children.push(...results);
    }
  }
  /**
   * @param {string} name
   *   Name to add.
   * @returns {undefined}
   *   Nothing.
   */
  openNode(name3) {
    const self2 = this;
    const className = name3.split(".").map(function(d, i) {
      return i ? d + "_".repeat(i) : self2.options.classPrefix + d;
    });
    const current = this.stack[this.stack.length - 1];
    const child = {
      type: "element",
      tagName: "span",
      properties: { className },
      children: []
    };
    current.children.push(child);
    this.stack.push(child);
  }
  /**
   * @returns {undefined}
   *   Nothing.
   */
  closeNode() {
    this.stack.pop();
  }
  /**
   * @returns {undefined}
   *   Nothing.
   */
  finalize() {
  }
  /**
   * @returns {string}
   *   Nothing.
   */
  toHTML() {
    return "";
  }
};

// packages/cli/src/ui/components/shared/MaxSizedBox.tsx
init_esbuild_shims();
var import_react33 = __toESM(require_react(), 1);

// packages/cli/src/ui/contexts/OverflowContext.tsx
init_esbuild_shims();
var import_react32 = __toESM(require_react(), 1);
var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1);
var OverflowStateContext = (0, import_react32.createContext)(
  void 0
);
var OverflowActionsContext = (0, import_react32.createContext)(
  void 0
);
var useOverflowState = /* @__PURE__ */ __name(() => (0, import_react32.useContext)(OverflowStateContext), "useOverflowState");
var useOverflowActions = /* @__PURE__ */ __name(() => (0, import_react32.useContext)(OverflowActionsContext), "useOverflowActions");
var OverflowProvider = /* @__PURE__ */ __name(({
  children
}) => {
  const [overflowingIds, setOverflowingIds] = (0, import_react32.useState)(/* @__PURE__ */ new Set());
  const addOverflowingId = (0, import_react32.useCallback)((id) => {
    setOverflowingIds((prevIds) => {
      if (prevIds.has(id)) {
        return prevIds;
      }
      const newIds = new Set(prevIds);
      newIds.add(id);
      return newIds;
    });
  }, []);
  const removeOverflowingId = (0, import_react32.useCallback)((id) => {
    setOverflowingIds((prevIds) => {
      if (!prevIds.has(id)) {
        return prevIds;
      }
      const newIds = new Set(prevIds);
      newIds.delete(id);
      return newIds;
    });
  }, []);
  const stateValue = (0, import_react32.useMemo)(
    () => ({
      overflowingIds
    }),
    [overflowingIds]
  );
  const actionsValue = (0, import_react32.useMemo)(
    () => ({
      addOverflowingId,
      removeOverflowingId
    }),
    [addOverflowingId, removeOverflowingId]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(OverflowStateContext.Provider, { value: stateValue, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(OverflowActionsContext.Provider, { value: actionsValue, children }) });
}, "OverflowProvider");

// packages/cli/src/ui/components/shared/MaxSizedBox.tsx
var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1);
var enableDebugLog = false;
var MINIMUM_MAX_HEIGHT = 2;
function setMaxSizedBoxDebugging(value) {
  enableDebugLog = value;
}
__name(setMaxSizedBoxDebugging, "setMaxSizedBoxDebugging");
function debugReportError(message, element) {
  if (!enableDebugLog) return;
  if (!import_react33.default.isValidElement(element)) {
    console.error(
      message,
      `Invalid element: '${String(element)}' typeof=${typeof element}`
    );
    return;
  }
  let sourceMessage = "<Unknown file>";
  try {
    const elementWithSource = element;
    const fileName = elementWithSource._source?.fileName;
    const lineNumber = elementWithSource._source?.lineNumber;
    sourceMessage = fileName ? `${fileName}:${lineNumber}` : "<Unknown file>";
  } catch (error) {
    console.error("Error while trying to get file name:", error);
  }
  console.error(message, `${String(element.type)}. Source: ${sourceMessage}`);
}
__name(debugReportError, "debugReportError");
var MaxSizedBox = /* @__PURE__ */ __name(({
  children,
  maxWidth,
  maxHeight,
  overflowDirection = "top",
  additionalHiddenLinesCount = 0
}) => {
  const id = (0, import_react33.useId)();
  const { addOverflowingId, removeOverflowingId } = useOverflowActions() || {};
  const laidOutStyledText = [];
  const targetMaxHeight = Math.max(
    Math.round(maxHeight ?? Number.MAX_SAFE_INTEGER),
    MINIMUM_MAX_HEIGHT
  );
  if (maxWidth === void 0) {
    throw new Error("maxWidth must be defined when maxHeight is set.");
  }
  function visitRows(element) {
    if (!import_react33.default.isValidElement(element)) {
      return;
    }
    if (element.type === import_react33.Fragment) {
      import_react33.default.Children.forEach(element.props.children, visitRows);
      return;
    }
    if (element.type === Box_default) {
      layoutInkElementAsStyledText(element, maxWidth, laidOutStyledText);
      return;
    }
    debugReportError("MaxSizedBox children must be <Box> elements", element);
  }
  __name(visitRows, "visitRows");
  import_react33.default.Children.forEach(children, visitRows);
  const contentWillOverflow = targetMaxHeight !== void 0 && laidOutStyledText.length > targetMaxHeight || additionalHiddenLinesCount > 0;
  const visibleContentHeight = contentWillOverflow && targetMaxHeight !== void 0 ? targetMaxHeight - 1 : targetMaxHeight;
  const hiddenLinesCount = visibleContentHeight !== void 0 ? Math.max(0, laidOutStyledText.length - visibleContentHeight) : 0;
  const totalHiddenLines = hiddenLinesCount + additionalHiddenLinesCount;
  (0, import_react33.useEffect)(() => {
    if (totalHiddenLines > 0) {
      addOverflowingId?.(id);
    } else {
      removeOverflowingId?.(id);
    }
    return () => {
      removeOverflowingId?.(id);
    };
  }, [id, totalHiddenLines, addOverflowingId, removeOverflowingId]);
  const visibleStyledText = hiddenLinesCount > 0 ? overflowDirection === "top" ? laidOutStyledText.slice(hiddenLinesCount, laidOutStyledText.length) : laidOutStyledText.slice(0, visibleContentHeight) : laidOutStyledText;
  const visibleLines = visibleStyledText.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Box_default, { children: line.length > 0 ? line.map((segment, segIndex) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Text, { ...segment.props, children: segment.text }, segIndex)) : /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Text, { children: " " }) }, index));
  return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Box_default, { flexDirection: "column", width: maxWidth, flexShrink: 0, children: [
    totalHiddenLines > 0 && overflowDirection === "top" && /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Text, { color: theme.text.secondary, wrap: "truncate", children: [
      "... first ",
      totalHiddenLines,
      " line",
      totalHiddenLines === 1 ? "" : "s",
      " ",
      "hidden ..."
    ] }),
    visibleLines,
    totalHiddenLines > 0 && overflowDirection === "bottom" && /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Text, { color: theme.text.secondary, wrap: "truncate", children: [
      "... last ",
      totalHiddenLines,
      " line",
      totalHiddenLines === 1 ? "" : "s",
      " ",
      "hidden ..."
    ] })
  ] });
}, "MaxSizedBox");
function visitBoxRow(element) {
  if (!import_react33.default.isValidElement(element) || element.type !== Box_default) {
    debugReportError(
      `All children of MaxSizedBox must be <Box> elements`,
      element
    );
    return {
      noWrapSegments: [{ text: "<ERROR>", props: {} }],
      segments: []
    };
  }
  if (enableDebugLog) {
    const boxProps = element.props;
    let maxExpectedProps = 4;
    if (boxProps.children !== void 0) {
      maxExpectedProps += 1;
    }
    if (boxProps.flexDirection !== void 0 && boxProps.flexDirection !== "row") {
      debugReportError(
        'MaxSizedBox children must have flexDirection="row".',
        element
      );
    }
    if (Object.keys(boxProps).length > maxExpectedProps) {
      debugReportError(
        `Boxes inside MaxSizedBox must not have additional props. ${Object.keys(
          boxProps
        ).join(", ")}`,
        element
      );
    }
  }
  const row = {
    noWrapSegments: [],
    segments: []
  };
  let hasSeenWrapped = false;
  function visitRowChild(element2, parentProps) {
    if (element2 === null) {
      return;
    }
    if (typeof element2 === "string" || typeof element2 === "number") {
      const text = String(element2);
      if (!text) {
        return;
      }
      const segment = { text, props: parentProps ?? {} };
      if (parentProps === void 0 || parentProps["wrap"] === "wrap") {
        hasSeenWrapped = true;
        row.segments.push(segment);
      } else {
        if (!hasSeenWrapped) {
          row.noWrapSegments.push(segment);
        } else {
          row.segments.push(segment);
          debugReportError(
            "Text elements without wrapping cannot appear after elements with wrapping in the same row.",
            element2
          );
        }
      }
      return;
    }
    if (!import_react33.default.isValidElement(element2)) {
      debugReportError("Invalid element.", element2);
      return;
    }
    if (element2.type === import_react33.Fragment) {
      import_react33.default.Children.forEach(
        element2.props.children,
        (child) => visitRowChild(child, parentProps)
      );
      return;
    }
    if (element2.type !== Text) {
      debugReportError(
        "Children of a row Box must be <Text> elements.",
        element2
      );
      return;
    }
    const { children, ...currentProps } = element2.props;
    const mergedProps = parentProps === void 0 ? currentProps : { ...parentProps, ...currentProps };
    import_react33.default.Children.forEach(
      children,
      (child) => visitRowChild(child, mergedProps)
    );
  }
  __name(visitRowChild, "visitRowChild");
  import_react33.default.Children.forEach(
    element.props.children,
    (child) => visitRowChild(child, void 0)
  );
  return row;
}
__name(visitBoxRow, "visitBoxRow");
function layoutInkElementAsStyledText(element, maxWidth, output) {
  const row = visitBoxRow(element);
  if (row.segments.length === 0 && row.noWrapSegments.length === 0) {
    output.push([]);
    return;
  }
  const lines = [];
  const nonWrappingContent = [];
  let noWrappingWidth = 0;
  row.noWrapSegments.forEach((segment) => {
    nonWrappingContent.push(segment);
    noWrappingWidth += stringWidth4(segment.text);
  });
  if (row.segments.length === 0) {
    const lines2 = [];
    let currentLine = [];
    nonWrappingContent.forEach((segment) => {
      const textLines = segment.text.split("\n");
      textLines.forEach((text, index) => {
        if (index > 0) {
          lines2.push(currentLine);
          currentLine = [];
        }
        if (text) {
          currentLine.push({ text, props: segment.props });
        }
      });
    });
    if (currentLine.length > 0 || nonWrappingContent.length > 0 && nonWrappingContent[nonWrappingContent.length - 1].text.endsWith("\n")) {
      lines2.push(currentLine);
    }
    for (const line of lines2) {
      output.push(line);
    }
    return;
  }
  const availableWidth = maxWidth - noWrappingWidth;
  if (availableWidth < 1) {
    const lines2 = [];
    let currentLine = [];
    let currentLineWidth = 0;
    for (const segment of nonWrappingContent) {
      const textLines = segment.text.split("\n");
      textLines.forEach((text, index) => {
        if (index > 0) {
          lines2.push(currentLine);
          currentLine = [];
          currentLineWidth = 0;
        }
        if (text) {
          const textWidth = stringWidth4(text);
          if (index > 0 && textWidth > 0) {
            currentLine.push({ text: "\u2026", props: {} });
            currentLineWidth = stringWidth4("\u2026");
          } else {
            const maxContentWidth = Math.max(0, maxWidth - stringWidth4("\u2026"));
            if (textWidth <= maxContentWidth && currentLineWidth === 0) {
              currentLine.push({ text, props: segment.props });
              currentLineWidth += textWidth;
            } else {
              const codePoints = toCodePoints(text);
              let truncatedWidth = currentLineWidth;
              let sliceEndIndex = 0;
              for (const char of codePoints) {
                const charWidth = stringWidth4(char);
                if (truncatedWidth + charWidth > maxContentWidth) {
                  break;
                }
                truncatedWidth += charWidth;
                sliceEndIndex++;
              }
              const slice = codePoints.slice(0, sliceEndIndex).join("");
              if (slice) {
                currentLine.push({ text: slice, props: segment.props });
              }
              currentLine.push({ text: "\u2026", props: {} });
              currentLineWidth = truncatedWidth + stringWidth4("\u2026");
            }
          }
        }
      });
    }
    if (currentLine.length > 0 || nonWrappingContent.length > 0 && nonWrappingContent[nonWrappingContent.length - 1].text.endsWith("\n")) {
      lines2.push(currentLine);
    }
    if (lines2.length === 0) {
      lines2.push([{ text: "\u2026", props: {} }]);
    }
    for (const line of lines2) {
      output.push(line);
    }
    return;
  }
  let wrappingPart = [];
  let wrappingPartWidth = 0;
  function addWrappingPartToLines() {
    if (lines.length === 0) {
      lines.push([...nonWrappingContent, ...wrappingPart]);
    } else {
      if (noWrappingWidth > 0) {
        lines.push([
          ...[{ text: " ".repeat(noWrappingWidth), props: {} }],
          ...wrappingPart
        ]);
      } else {
        lines.push(wrappingPart);
      }
    }
    wrappingPart = [];
    wrappingPartWidth = 0;
  }
  __name(addWrappingPartToLines, "addWrappingPartToLines");
  function addToWrappingPart(text, props) {
    if (wrappingPart.length > 0 && wrappingPart[wrappingPart.length - 1].props === props) {
      wrappingPart[wrappingPart.length - 1].text += text;
    } else {
      wrappingPart.push({ text, props });
    }
  }
  __name(addToWrappingPart, "addToWrappingPart");
  row.segments.forEach((segment) => {
    const linesFromSegment = segment.text.split("\n");
    linesFromSegment.forEach((lineText, lineIndex) => {
      if (lineIndex > 0) {
        addWrappingPartToLines();
      }
      const words = lineText.split(/(\s+)/);
      words.forEach((word) => {
        if (!word) return;
        const wordWidth = stringWidth4(word);
        if (wrappingPartWidth + wordWidth > availableWidth && wrappingPartWidth > 0) {
          addWrappingPartToLines();
          if (/^\s+$/.test(word)) {
            return;
          }
        }
        if (wordWidth > availableWidth) {
          const wordAsCodePoints = toCodePoints(word);
          let remainingWordAsCodePoints = wordAsCodePoints;
          while (remainingWordAsCodePoints.length > 0) {
            let splitIndex = 0;
            let currentSplitWidth = 0;
            for (const char of remainingWordAsCodePoints) {
              const charWidth = stringWidth4(char);
              if (wrappingPartWidth + currentSplitWidth + charWidth > availableWidth) {
                break;
              }
              currentSplitWidth += charWidth;
              splitIndex++;
            }
            if (splitIndex > 0) {
              const part = remainingWordAsCodePoints.slice(0, splitIndex).join("");
              addToWrappingPart(part, segment.props);
              wrappingPartWidth += stringWidth4(part);
              remainingWordAsCodePoints = remainingWordAsCodePoints.slice(splitIndex);
            }
            if (remainingWordAsCodePoints.length > 0) {
              addWrappingPartToLines();
            }
          }
        } else {
          addToWrappingPart(word, segment.props);
          wrappingPartWidth += wordWidth;
        }
      });
    });
    if (segment.text.endsWith("\n")) {
      addWrappingPartToLines();
    }
  });
  if (wrappingPart.length > 0) {
    addWrappingPartToLines();
  }
  for (const line of lines) {
    output.push(line);
  }
}
__name(layoutInkElementAsStyledText, "layoutInkElementAsStyledText");

// packages/cli/src/ui/utils/CodeColorizer.tsx
var import_jsx_runtime5 = __toESM(require_jsx_runtime(), 1);
var lowlight = createLowlight(grammars);
function renderHastNode(node, theme2, inheritedColor) {
  if (node.type === "text") {
    const color = inheritedColor || theme2.defaultColor;
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text, { color, children: node.value });
  }
  if (node.type === "element") {
    const nodeClasses = node.properties?.["className"] || [];
    let elementColor = void 0;
    for (let i = nodeClasses.length - 1; i >= 0; i--) {
      const color = theme2.getInkColor(nodeClasses[i]);
      if (color) {
        elementColor = color;
        break;
      }
    }
    const colorToPassDown = elementColor || inheritedColor;
    const children = node.children?.map(
      (child, index) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_react34.default.Fragment, { children: renderHastNode(child, theme2, colorToPassDown) }, index)
    );
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_react34.default.Fragment, { children });
  }
  if (node.type === "root") {
    if (!node.children || node.children.length === 0) {
      return null;
    }
    return node.children?.map((child, index) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_react34.default.Fragment, { children: renderHastNode(child, theme2, inheritedColor) }, index));
  }
  return null;
}
__name(renderHastNode, "renderHastNode");
function highlightAndRenderLine(line, language, theme2) {
  try {
    const getHighlightedLine = /* @__PURE__ */ __name(() => !language || !lowlight.registered(language) ? lowlight.highlightAuto(line) : lowlight.highlight(language, line), "getHighlightedLine");
    const renderedNode = renderHastNode(getHighlightedLine(), theme2, void 0);
    return renderedNode !== null ? renderedNode : line;
  } catch (_error) {
    return line;
  }
}
__name(highlightAndRenderLine, "highlightAndRenderLine");
function colorizeLine(line, language, theme2) {
  const activeTheme = theme2 || themeManager.getActiveTheme();
  return highlightAndRenderLine(line, language, activeTheme);
}
__name(colorizeLine, "colorizeLine");
function colorizeCode(code2, language, availableHeight, maxWidth, theme2, settings) {
  const codeToHighlight = code2.replace(/\n$/, "");
  const activeTheme = theme2 || themeManager.getActiveTheme();
  const showLineNumbers = settings?.merged.ui?.showLineNumbers ?? true;
  try {
    let lines = codeToHighlight.split("\n");
    const padWidth = String(lines.length).length;
    let hiddenLinesCount = 0;
    if (availableHeight !== void 0) {
      availableHeight = Math.max(availableHeight, MINIMUM_MAX_HEIGHT);
      if (lines.length > availableHeight) {
        const sliceIndex = lines.length - availableHeight;
        hiddenLinesCount = sliceIndex;
        lines = lines.slice(sliceIndex);
      }
    }
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
      MaxSizedBox,
      {
        maxHeight: availableHeight,
        maxWidth,
        additionalHiddenLinesCount: hiddenLinesCount,
        overflowDirection: "top",
        children: lines.map((line, index) => {
          const contentToRender = highlightAndRenderLine(
            line,
            language,
            activeTheme
          );
          return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(Box_default, { children: [
            showLineNumbers && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text, { color: activeTheme.colors.Gray, children: `${String(index + 1 + hiddenLinesCount).padStart(
              padWidth,
              " "
            )} ` }),
            /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text, { color: activeTheme.defaultColor, wrap: "wrap", children: contentToRender })
          ] }, index);
        })
      }
    );
  } catch (error) {
    console.error(
      `[colorizeCode] Error highlighting code for language "${language}":`,
      error
    );
    const lines = codeToHighlight.split("\n");
    const padWidth = String(lines.length).length;
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
      MaxSizedBox,
      {
        maxHeight: availableHeight,
        maxWidth,
        overflowDirection: "top",
        children: lines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(Box_default, { children: [
          showLineNumbers && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text, { color: activeTheme.defaultColor, children: `${String(index + 1).padStart(padWidth, " ")} ` }),
          /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text, { color: activeTheme.colors.Gray, children: line })
        ] }, index))
      }
    );
  }
}
__name(colorizeCode, "colorizeCode");

// packages/cli/src/ui/utils/TableRenderer.tsx
init_esbuild_shims();
var import_react36 = __toESM(require_react(), 1);

// packages/cli/src/ui/utils/InlineMarkdownRenderer.tsx
init_esbuild_shims();
var import_react35 = __toESM(require_react(), 1);
var import_jsx_runtime6 = __toESM(require_jsx_runtime(), 1);
var BOLD_MARKER_LENGTH = 2;
var ITALIC_MARKER_LENGTH = 1;
var STRIKETHROUGH_MARKER_LENGTH = 2;
var INLINE_CODE_MARKER_LENGTH = 1;
var UNDERLINE_TAG_START_LENGTH = 3;
var UNDERLINE_TAG_END_LENGTH = 4;
var RenderInlineInternal = /* @__PURE__ */ __name(({ text }) => {
  if (!/[*_~`<[https?:]/.test(text)) {
    return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: theme.text.primary, children: text });
  }
  const nodes = [];
  let lastIndex = 0;
  const inlineRegex = /(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>|https?:\/\/\S+)/g;
  let match2;
  while ((match2 = inlineRegex.exec(text)) !== null) {
    if (match2.index > lastIndex) {
      nodes.push(
        /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { children: text.slice(lastIndex, match2.index) }, `t-${lastIndex}`)
      );
    }
    const fullMatch = match2[0];
    let renderedNode = null;
    const key = `m-${match2.index}`;
    try {
      if (fullMatch.startsWith("**") && fullMatch.endsWith("**") && fullMatch.length > BOLD_MARKER_LENGTH * 2) {
        renderedNode = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { bold: true, children: fullMatch.slice(BOLD_MARKER_LENGTH, -BOLD_MARKER_LENGTH) }, key);
      } else if (fullMatch.length > ITALIC_MARKER_LENGTH * 2 && (fullMatch.startsWith("*") && fullMatch.endsWith("*") || fullMatch.startsWith("_") && fullMatch.endsWith("_")) && !/\w/.test(text.substring(match2.index - 1, match2.index)) && !/\w/.test(
        text.substring(inlineRegex.lastIndex, inlineRegex.lastIndex + 1)
      ) && !/\S[./\\]/.test(text.substring(match2.index - 2, match2.index)) && !/[./\\]\S/.test(
        text.substring(inlineRegex.lastIndex, inlineRegex.lastIndex + 2)
      )) {
        renderedNode = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { italic: true, children: fullMatch.slice(ITALIC_MARKER_LENGTH, -ITALIC_MARKER_LENGTH) }, key);
      } else if (fullMatch.startsWith("~~") && fullMatch.endsWith("~~") && fullMatch.length > STRIKETHROUGH_MARKER_LENGTH * 2) {
        renderedNode = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { strikethrough: true, children: fullMatch.slice(
          STRIKETHROUGH_MARKER_LENGTH,
          -STRIKETHROUGH_MARKER_LENGTH
        ) }, key);
      } else if (fullMatch.startsWith("`") && fullMatch.endsWith("`") && fullMatch.length > INLINE_CODE_MARKER_LENGTH) {
        const codeMatch = fullMatch.match(/^(`+)(.+?)\1$/s);
        if (codeMatch && codeMatch[2]) {
          renderedNode = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: theme.text.accent, children: codeMatch[2] }, key);
        }
      } else if (fullMatch.startsWith("[") && fullMatch.includes("](") && fullMatch.endsWith(")")) {
        const linkMatch = fullMatch.match(/\[(.*?)\]\((.*?)\)/);
        if (linkMatch) {
          const linkText = linkMatch[1];
          const url2 = linkMatch[2];
          renderedNode = /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Text, { children: [
            linkText,
            /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Text, { color: theme.text.link, children: [
              " (",
              url2,
              ")"
            ] })
          ] }, key);
        }
      } else if (fullMatch.startsWith("<u>") && fullMatch.endsWith("</u>") && fullMatch.length > UNDERLINE_TAG_START_LENGTH + UNDERLINE_TAG_END_LENGTH - 1) {
        renderedNode = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { underline: true, children: fullMatch.slice(
          UNDERLINE_TAG_START_LENGTH,
          -UNDERLINE_TAG_END_LENGTH
        ) }, key);
      } else if (fullMatch.match(/^https?:\/\//)) {
        renderedNode = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: theme.text.link, children: fullMatch }, key);
      }
    } catch (e2) {
      console.error("Error parsing inline markdown part:", fullMatch, e2);
      renderedNode = null;
    }
    nodes.push(renderedNode ?? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { children: fullMatch }, key));
    lastIndex = inlineRegex.lastIndex;
  }
  if (lastIndex < text.length) {
    nodes.push(/* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { children: text.slice(lastIndex) }, `t-${lastIndex}`));
  }
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_jsx_runtime6.Fragment, { children: nodes.filter((node) => node !== null) });
}, "RenderInlineInternal");
var RenderInline = import_react35.default.memo(RenderInlineInternal);
var getPlainTextLength = /* @__PURE__ */ __name((text) => {
  const cleanText = text.replace(/\*\*(.*?)\*\*/g, "$1").replace(/\*(.*?)\*/g, "$1").replace(/_(.*?)_/g, "$1").replace(/~~(.*?)~~/g, "$1").replace(/`(.*?)`/g, "$1").replace(/<u>(.*?)<\/u>/g, "$1").replace(/.*\[(.*?)\]\(.*\)/g, "$1");
  return stringWidth4(cleanText);
}, "getPlainTextLength");

// packages/cli/src/ui/utils/TableRenderer.tsx
var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1);
var TableRenderer = /* @__PURE__ */ __name(({
  headers,
  rows,
  terminalWidth
}) => {
  const columnWidths = headers.map((header, index) => {
    const headerWidth = getPlainTextLength(header);
    const maxRowWidth = Math.max(
      ...rows.map((row) => getPlainTextLength(row[index] || ""))
    );
    return Math.max(headerWidth, maxRowWidth) + 2;
  });
  const totalWidth = columnWidths.reduce((sum, width) => sum + width + 1, 1);
  const scaleFactor = totalWidth > terminalWidth ? terminalWidth / totalWidth : 1;
  const adjustedWidths = columnWidths.map(
    (width) => Math.floor(width * scaleFactor)
  );
  const renderCell = /* @__PURE__ */ __name((content, width, isHeader = false) => {
    const contentWidth = Math.max(0, width - 2);
    const displayWidth = getPlainTextLength(content);
    let cellContent = content;
    if (displayWidth > contentWidth) {
      if (contentWidth <= 3) {
        cellContent = content.substring(
          0,
          Math.min(content.length, contentWidth)
        );
      } else {
        let left3 = 0;
        let right3 = content.length;
        let bestTruncated = content;
        while (left3 <= right3) {
          const mid = Math.floor((left3 + right3) / 2);
          const candidate = content.substring(0, mid);
          const candidateWidth = getPlainTextLength(candidate);
          if (candidateWidth <= contentWidth - 3) {
            bestTruncated = candidate;
            left3 = mid + 1;
          } else {
            right3 = mid - 1;
          }
        }
        cellContent = bestTruncated + "...";
      }
    }
    const actualDisplayWidth = getPlainTextLength(cellContent);
    const paddingNeeded = Math.max(0, contentWidth - actualDisplayWidth);
    return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { children: [
      isHeader ? /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { bold: true, color: theme.text.link, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(RenderInline, { text: cellContent }) }) : /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(RenderInline, { text: cellContent }),
      " ".repeat(paddingNeeded)
    ] });
  }, "renderCell");
  const renderBorder2 = /* @__PURE__ */ __name((type) => {
    const chars = {
      top: { left: "\u250C", middle: "\u252C", right: "\u2510", horizontal: "\u2500" },
      middle: { left: "\u251C", middle: "\u253C", right: "\u2524", horizontal: "\u2500" },
      bottom: { left: "\u2514", middle: "\u2534", right: "\u2518", horizontal: "\u2500" }
    };
    const char = chars[type];
    const borderParts = adjustedWidths.map((w) => char.horizontal.repeat(w));
    const border = char.left + borderParts.join(char.middle) + char.right;
    return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { color: theme.border.default, children: border });
  }, "renderBorder");
  const renderRow = /* @__PURE__ */ __name((cells, isHeader = false) => {
    const renderedCells = cells.map((cell, index) => {
      const width = adjustedWidths[index] || 0;
      return renderCell(cell || "", width, isHeader);
    });
    return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { color: theme.text.primary, children: [
      "\u2502",
      " ",
      renderedCells.map((cell, index) => /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_react36.default.Fragment, { children: [
        cell,
        index < renderedCells.length - 1 ? " \u2502 " : ""
      ] }, index)),
      " ",
      "\u2502"
    ] });
  }, "renderRow");
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Box_default, { flexDirection: "column", marginY: 1, children: [
    renderBorder2("top"),
    renderRow(headers, true),
    renderBorder2("middle"),
    rows.map((row, index) => /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_react36.default.Fragment, { children: renderRow(row) }, index)),
    renderBorder2("bottom")
  ] });
}, "TableRenderer");

// packages/cli/src/ui/utils/MarkdownDisplay.tsx
var import_jsx_runtime8 = __toESM(require_jsx_runtime(), 1);
var EMPTY_LINE_HEIGHT = 1;
var CODE_BLOCK_PREFIX_PADDING = 1;
var LIST_ITEM_PREFIX_PADDING = 1;
var LIST_ITEM_TEXT_FLEX_GROW = 1;
var MarkdownDisplayInternal = /* @__PURE__ */ __name(({
  text,
  isPending,
  availableTerminalHeight,
  terminalWidth
}) => {
  if (!text) return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_jsx_runtime8.Fragment, {});
  const lines = text.split(/\r?\n/);
  const headerRegex = /^ *(#{1,4}) +(.*)/;
  const codeFenceRegex = /^ *(`{3,}|~{3,}) *(\w*?) *$/;
  const ulItemRegex = /^([ \t]*)([-*+]) +(.*)/;
  const olItemRegex = /^([ \t]*)(\d+)\. +(.*)/;
  const hrRegex = /^ *([-*_] *){3,} *$/;
  const tableRowRegex = /^\s*\|(.+)\|\s*$/;
  const tableSeparatorRegex = /^\s*\|?\s*(:?-+:?)\s*(\|\s*(:?-+:?)\s*)+\|?\s*$/;
  const contentBlocks = [];
  let inCodeBlock = false;
  let lastLineEmpty = true;
  let codeBlockContent = [];
  let codeBlockLang = null;
  let codeBlockFence = "";
  let inTable = false;
  let tableRows = [];
  let tableHeaders = [];
  function addContentBlock(block2) {
    if (block2) {
      contentBlocks.push(block2);
      lastLineEmpty = false;
    }
  }
  __name(addContentBlock, "addContentBlock");
  lines.forEach((line, index) => {
    const key = `line-${index}`;
    if (inCodeBlock) {
      const fenceMatch = line.match(codeFenceRegex);
      if (fenceMatch && fenceMatch[1].startsWith(codeBlockFence[0]) && fenceMatch[1].length >= codeBlockFence.length) {
        addContentBlock(
          /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
            RenderCodeBlock,
            {
              content: codeBlockContent,
              lang: codeBlockLang,
              isPending,
              availableTerminalHeight,
              terminalWidth
            },
            key
          )
        );
        inCodeBlock = false;
        codeBlockContent = [];
        codeBlockLang = null;
        codeBlockFence = "";
      } else {
        codeBlockContent.push(line);
      }
      return;
    }
    const codeFenceMatch = line.match(codeFenceRegex);
    const headerMatch = line.match(headerRegex);
    const ulMatch = line.match(ulItemRegex);
    const olMatch = line.match(olItemRegex);
    const hrMatch = line.match(hrRegex);
    const tableRowMatch = line.match(tableRowRegex);
    const tableSeparatorMatch = line.match(tableSeparatorRegex);
    if (codeFenceMatch) {
      inCodeBlock = true;
      codeBlockFence = codeFenceMatch[1];
      codeBlockLang = codeFenceMatch[2] || null;
    } else if (tableRowMatch && !inTable) {
      if (index + 1 < lines.length && lines[index + 1].match(tableSeparatorRegex)) {
        inTable = true;
        tableHeaders = tableRowMatch[1].split("|").map((cell) => cell.trim());
        tableRows = [];
      } else {
        addContentBlock(
          /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { wrap: "wrap", children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(RenderInline, { text: line }) }) }, key)
        );
      }
    } else if (inTable && tableSeparatorMatch) {
    } else if (inTable && tableRowMatch) {
      const cells = tableRowMatch[1].split("|").map((cell) => cell.trim());
      while (cells.length < tableHeaders.length) {
        cells.push("");
      }
      if (cells.length > tableHeaders.length) {
        cells.length = tableHeaders.length;
      }
      tableRows.push(cells);
    } else if (inTable && !tableRowMatch) {
      if (tableHeaders.length > 0 && tableRows.length > 0) {
        addContentBlock(
          /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
            RenderTable,
            {
              headers: tableHeaders,
              rows: tableRows,
              terminalWidth
            },
            `table-${contentBlocks.length}`
          )
        );
      }
      inTable = false;
      tableRows = [];
      tableHeaders = [];
      if (line.trim().length > 0) {
        addContentBlock(
          /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { wrap: "wrap", children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(RenderInline, { text: line }) }) }, key)
        );
      }
    } else if (hrMatch) {
      addContentBlock(
        /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { dimColor: true, children: "---" }) }, key)
      );
    } else if (headerMatch) {
      const level = headerMatch[1].length;
      const headerText = headerMatch[2];
      let headerNode = null;
      switch (level) {
        case 1:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { bold: true, color: theme.text.link, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(RenderInline, { text: headerText }) });
          break;
        case 2:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { bold: true, color: theme.text.link, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(RenderInline, { text: headerText }) });
          break;
        case 3:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { bold: true, color: theme.text.primary, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(RenderInline, { text: headerText }) });
          break;
        case 4:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { italic: true, color: theme.text.secondary, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(RenderInline, { text: headerText }) });
          break;
        default:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { color: theme.text.primary, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(RenderInline, { text: headerText }) });
          break;
      }
      if (headerNode) addContentBlock(/* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Box_default, { children: headerNode }, key));
    } else if (ulMatch) {
      const leadingWhitespace = ulMatch[1];
      const marker = ulMatch[2];
      const itemText = ulMatch[3];
      addContentBlock(
        /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
          RenderListItem,
          {
            itemText,
            type: "ul",
            marker,
            leadingWhitespace
          },
          key
        )
      );
    } else if (olMatch) {
      const leadingWhitespace = olMatch[1];
      const marker = olMatch[2];
      const itemText = olMatch[3];
      addContentBlock(
        /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
          RenderListItem,
          {
            itemText,
            type: "ol",
            marker,
            leadingWhitespace
          },
          key
        )
      );
    } else {
      if (line.trim().length === 0 && !inCodeBlock) {
        if (!lastLineEmpty) {
          contentBlocks.push(
            /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Box_default, { height: EMPTY_LINE_HEIGHT }, `spacer-${index}`)
          );
          lastLineEmpty = true;
        }
      } else {
        addContentBlock(
          /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { wrap: "wrap", color: theme.text.primary, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(RenderInline, { text: line }) }) }, key)
        );
      }
    }
  });
  if (inCodeBlock) {
    addContentBlock(
      /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
        RenderCodeBlock,
        {
          content: codeBlockContent,
          lang: codeBlockLang,
          isPending,
          availableTerminalHeight,
          terminalWidth
        },
        "line-eof"
      )
    );
  }
  if (inTable && tableHeaders.length > 0 && tableRows.length > 0) {
    addContentBlock(
      /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
        RenderTable,
        {
          headers: tableHeaders,
          rows: tableRows,
          terminalWidth
        },
        `table-${contentBlocks.length}`
      )
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_jsx_runtime8.Fragment, { children: contentBlocks });
}, "MarkdownDisplayInternal");
var RenderCodeBlockInternal = /* @__PURE__ */ __name(({
  content,
  lang,
  isPending,
  availableTerminalHeight,
  terminalWidth
}) => {
  const settings = useSettings();
  const MIN_LINES_FOR_MESSAGE = 1;
  const RESERVED_LINES = 2;
  if (isPending && availableTerminalHeight !== void 0) {
    const MAX_CODE_LINES_WHEN_PENDING = Math.max(
      0,
      availableTerminalHeight - RESERVED_LINES
    );
    if (content.length > MAX_CODE_LINES_WHEN_PENDING) {
      if (MAX_CODE_LINES_WHEN_PENDING < MIN_LINES_FOR_MESSAGE) {
        return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Box_default, { paddingLeft: CODE_BLOCK_PREFIX_PADDING, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { color: theme.text.secondary, children: "... code is being written ..." }) });
      }
      const truncatedContent = content.slice(0, MAX_CODE_LINES_WHEN_PENDING);
      const colorizedTruncatedCode = colorizeCode(
        truncatedContent.join("\n"),
        lang,
        availableTerminalHeight,
        terminalWidth - CODE_BLOCK_PREFIX_PADDING,
        void 0,
        settings
      );
      return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(Box_default, { paddingLeft: CODE_BLOCK_PREFIX_PADDING, flexDirection: "column", children: [
        colorizedTruncatedCode,
        /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { color: theme.text.secondary, children: "... generating more ..." })
      ] });
    }
  }
  const fullContent = content.join("\n");
  const colorizedCode = colorizeCode(
    fullContent,
    lang,
    availableTerminalHeight,
    terminalWidth - CODE_BLOCK_PREFIX_PADDING,
    void 0,
    settings
  );
  return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
    Box_default,
    {
      paddingLeft: CODE_BLOCK_PREFIX_PADDING,
      flexDirection: "column",
      width: terminalWidth,
      flexShrink: 0,
      children: colorizedCode
    }
  );
}, "RenderCodeBlockInternal");
var RenderCodeBlock = import_react37.default.memo(RenderCodeBlockInternal);
var RenderListItemInternal = /* @__PURE__ */ __name(({
  itemText,
  type,
  marker,
  leadingWhitespace = ""
}) => {
  const prefix = type === "ol" ? `${marker}. ` : `${marker} `;
  const prefixWidth = prefix.length;
  const indentation = leadingWhitespace.length;
  return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(
    Box_default,
    {
      paddingLeft: indentation + LIST_ITEM_PREFIX_PADDING,
      flexDirection: "row",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { color: theme.text.primary, children: prefix }) }),
        /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Box_default, { flexGrow: LIST_ITEM_TEXT_FLEX_GROW, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { wrap: "wrap", color: theme.text.primary, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(RenderInline, { text: itemText }) }) })
      ]
    }
  );
}, "RenderListItemInternal");
var RenderListItem = import_react37.default.memo(RenderListItemInternal);
var RenderTableInternal = /* @__PURE__ */ __name(({
  headers,
  rows,
  terminalWidth
}) => /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(TableRenderer, { headers, rows, terminalWidth }), "RenderTableInternal");
var RenderTable = import_react37.default.memo(RenderTableInternal);
var MarkdownDisplay = import_react37.default.memo(MarkdownDisplayInternal);

// packages/cli/src/ui/components/messages/GeminiMessage.tsx
var import_jsx_runtime9 = __toESM(require_jsx_runtime(), 1);
var GeminiMessage = /* @__PURE__ */ __name(({
  text,
  isPending,
  availableTerminalHeight,
  terminalWidth
}) => {
  const prefix = "\u2726 ";
  const prefixWidth = prefix.length;
  return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { color: theme.text.accent, "aria-label": SCREEN_READER_MODEL_PREFIX, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { flexGrow: 1, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
      MarkdownDisplay,
      {
        text,
        isPending,
        availableTerminalHeight,
        terminalWidth
      }
    ) })
  ] });
}, "GeminiMessage");

// packages/cli/src/ui/components/messages/InfoMessage.tsx
init_esbuild_shims();
var import_jsx_runtime10 = __toESM(require_jsx_runtime(), 1);
var InfoMessage = /* @__PURE__ */ __name(({ text }) => {
  if (!text || text.trim() === "") {
    return null;
  }
  const prefix = "\u2139 ";
  const prefixWidth = prefix.length;
  return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Box_default, { flexDirection: "row", marginTop: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { color: theme.status.warning, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { wrap: "wrap", color: theme.status.warning, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(RenderInline, { text }) }) })
  ] });
}, "InfoMessage");

// packages/cli/src/ui/components/messages/ErrorMessage.tsx
init_esbuild_shims();
var import_jsx_runtime11 = __toESM(require_jsx_runtime(), 1);
var ErrorMessage = /* @__PURE__ */ __name(({ text }) => {
  const prefix = "\u2715 ";
  const prefixWidth = prefix.length;
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(Box_default, { flexDirection: "row", marginBottom: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Text, { color: theme.status.error, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Text, { wrap: "wrap", color: theme.status.error, children: text }) })
  ] });
}, "ErrorMessage");

// packages/cli/src/ui/components/messages/ToolGroupMessage.tsx
init_esbuild_shims();
var import_react63 = __toESM(require_react(), 1);

// packages/cli/src/ui/types.ts
init_esbuild_shims();
var import_react38 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/messages/ToolMessage.tsx
init_esbuild_shims();
var import_react61 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/messages/DiffRenderer.tsx
init_esbuild_shims();
import crypto16 from "node:crypto";
var import_jsx_runtime12 = __toESM(require_jsx_runtime(), 1);
function parseDiffWithLineNumbers(diffContent) {
  const lines = diffContent.split("\n");
  const result = [];
  let currentOldLine = 0;
  let currentNewLine = 0;
  let inHunk = false;
  const hunkHeaderRegex = /^@@ -(\d+),?\d* \+(\d+),?\d* @@/;
  for (const line of lines) {
    const hunkMatch = line.match(hunkHeaderRegex);
    if (hunkMatch) {
      currentOldLine = parseInt(hunkMatch[1], 10);
      currentNewLine = parseInt(hunkMatch[2], 10);
      inHunk = true;
      result.push({ type: "hunk", content: line });
      currentOldLine--;
      currentNewLine--;
      continue;
    }
    if (!inHunk) {
      if (line.startsWith("--- ")) {
        continue;
      }
      continue;
    }
    if (line.startsWith("+")) {
      currentNewLine++;
      result.push({
        type: "add",
        newLine: currentNewLine,
        content: line.substring(1)
      });
    } else if (line.startsWith("-")) {
      currentOldLine++;
      result.push({
        type: "del",
        oldLine: currentOldLine,
        content: line.substring(1)
      });
    } else if (line.startsWith(" ")) {
      currentOldLine++;
      currentNewLine++;
      result.push({
        type: "context",
        oldLine: currentOldLine,
        newLine: currentNewLine,
        content: line.substring(1)
      });
    } else if (line.startsWith("\\")) {
      result.push({ type: "other", content: line });
    }
  }
  return result;
}
__name(parseDiffWithLineNumbers, "parseDiffWithLineNumbers");
var DEFAULT_TAB_WIDTH = 4;
var DiffRenderer = /* @__PURE__ */ __name(({
  diffContent,
  filename,
  tabWidth = DEFAULT_TAB_WIDTH,
  availableTerminalHeight,
  terminalWidth,
  theme: theme2
}) => {
  const screenReaderEnabled = use_is_screen_reader_enabled_default();
  if (!diffContent || typeof diffContent !== "string") {
    return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Text, { color: theme.status.warning, children: "No diff content." });
  }
  const parsedLines = parseDiffWithLineNumbers(diffContent);
  if (parsedLines.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        padding: 1,
        children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Text, { dimColor: true, children: "No changes detected." })
      }
    );
  }
  if (screenReaderEnabled) {
    return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Box_default, { flexDirection: "column", children: parsedLines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(Text, { children: [
      line.type,
      ": ",
      line.content
    ] }, index)) });
  }
  const isNewFile = parsedLines.every(
    (line) => line.type === "add" || line.type === "hunk" || line.type === "other" || line.content.startsWith("diff --git") || line.content.startsWith("new file mode")
  );
  let renderedOutput;
  if (isNewFile) {
    const addedContent = parsedLines.filter((line) => line.type === "add").map((line) => line.content).join("\n");
    const fileExtension = filename?.split(".").pop() || null;
    const language = fileExtension ? getLanguageFromExtension(fileExtension) : null;
    renderedOutput = colorizeCode(
      addedContent,
      language,
      availableTerminalHeight,
      terminalWidth,
      theme2
    );
  } else {
    renderedOutput = renderDiffContent(
      parsedLines,
      filename,
      tabWidth,
      availableTerminalHeight,
      terminalWidth
    );
  }
  return renderedOutput;
}, "DiffRenderer");
var renderDiffContent = /* @__PURE__ */ __name((parsedLines, filename, tabWidth = DEFAULT_TAB_WIDTH, availableTerminalHeight, terminalWidth) => {
  const normalizedLines = parsedLines.map((line) => ({
    ...line,
    content: line.content.replace(/\t/g, " ".repeat(tabWidth))
  }));
  const displayableLines = normalizedLines.filter(
    (l2) => l2.type !== "hunk" && l2.type !== "other"
  );
  if (displayableLines.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        padding: 1,
        children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Text, { dimColor: true, children: "No changes detected." })
      }
    );
  }
  const maxLineNumber = Math.max(
    0,
    ...displayableLines.map((l2) => l2.oldLine ?? 0),
    ...displayableLines.map((l2) => l2.newLine ?? 0)
  );
  const gutterWidth = Math.max(1, maxLineNumber.toString().length);
  const fileExtension = filename?.split(".").pop() || null;
  const language = fileExtension ? getLanguageFromExtension(fileExtension) : null;
  let baseIndentation = Infinity;
  for (const line of displayableLines) {
    if (line.content.trim() === "") continue;
    const firstCharIndex = line.content.search(/\S/);
    const currentIndent = firstCharIndex === -1 ? 0 : firstCharIndex;
    baseIndentation = Math.min(baseIndentation, currentIndent);
  }
  if (!isFinite(baseIndentation)) {
    baseIndentation = 0;
  }
  const key = filename ? `diff-box-${filename}` : `diff-box-${crypto16.createHash("sha1").update(JSON.stringify(parsedLines)).digest("hex")}`;
  let lastLineNumber = null;
  const MAX_CONTEXT_LINES_WITHOUT_GAP = 5;
  return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
    MaxSizedBox,
    {
      maxHeight: availableTerminalHeight,
      maxWidth: terminalWidth,
      children: displayableLines.reduce((acc, line, index) => {
        let relevantLineNumberForGapCalc = null;
        if (line.type === "add" || line.type === "context") {
          relevantLineNumberForGapCalc = line.newLine ?? null;
        } else if (line.type === "del") {
          relevantLineNumberForGapCalc = line.oldLine ?? null;
        }
        if (lastLineNumber !== null && relevantLineNumberForGapCalc !== null && relevantLineNumberForGapCalc > lastLineNumber + MAX_CONTEXT_LINES_WITHOUT_GAP + 1) {
          acc.push(
            /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Text, { wrap: "truncate", color: theme.text.secondary, children: "\u2550".repeat(terminalWidth) }) }, `gap-${index}`)
          );
        }
        const lineKey = `diff-line-${index}`;
        let gutterNumStr = "";
        let prefixSymbol = " ";
        switch (line.type) {
          case "add":
            gutterNumStr = (line.newLine ?? "").toString();
            prefixSymbol = "+";
            lastLineNumber = line.newLine ?? null;
            break;
          case "del":
            gutterNumStr = (line.oldLine ?? "").toString();
            prefixSymbol = "-";
            if (line.oldLine !== void 0) {
              lastLineNumber = line.oldLine;
            }
            break;
          case "context":
            gutterNumStr = (line.newLine ?? "").toString();
            prefixSymbol = " ";
            lastLineNumber = line.newLine ?? null;
            break;
          default:
            return acc;
        }
        const displayContent = line.content.substring(baseIndentation);
        acc.push(
          /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(Box_default, { flexDirection: "row", children: [
            /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(
              Text,
              {
                color: theme.text.secondary,
                backgroundColor: line.type === "add" ? theme.background.diff.added : line.type === "del" ? theme.background.diff.removed : void 0,
                children: [
                  gutterNumStr.padStart(gutterWidth),
                  " "
                ]
              }
            ),
            line.type === "context" ? /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(import_jsx_runtime12.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(Text, { children: [
                prefixSymbol,
                " "
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Text, { wrap: "wrap", children: colorizeLine(displayContent, language) })
            ] }) : /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(
              Text,
              {
                backgroundColor: line.type === "add" ? theme.background.diff.added : theme.background.diff.removed,
                wrap: "wrap",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
                    Text,
                    {
                      color: line.type === "add" ? theme.status.success : theme.status.error,
                      children: prefixSymbol
                    }
                  ),
                  " ",
                  colorizeLine(displayContent, language)
                ]
              }
            )
          ] }, lineKey)
        );
        return acc;
      }, [])
    },
    key
  );
}, "renderDiffContent");
var getLanguageFromExtension = /* @__PURE__ */ __name((extension) => {
  const languageMap = {
    js: "javascript",
    ts: "typescript",
    py: "python",
    json: "json",
    css: "css",
    html: "html",
    sh: "bash",
    md: "markdown",
    yaml: "yaml",
    yml: "yaml",
    txt: "plaintext",
    java: "java",
    c: "c",
    cpp: "cpp",
    rb: "ruby"
  };
  return languageMap[extension] || null;
}, "getLanguageFromExtension");

// packages/cli/src/ui/components/AnsiOutput.tsx
init_esbuild_shims();
var import_jsx_runtime13 = __toESM(require_jsx_runtime(), 1);
var DEFAULT_HEIGHT = 24;
var AnsiOutputText = /* @__PURE__ */ __name(({
  data,
  availableTerminalHeight
}) => {
  const lastLines = data.slice(
    -(availableTerminalHeight && availableTerminalHeight > 0 ? availableTerminalHeight : DEFAULT_HEIGHT)
  );
  return lastLines.map((line, lineIndex) => /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Text, { children: line.length > 0 ? line.map((token2, tokenIndex) => /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
    Text,
    {
      color: token2.inverse ? token2.bg : token2.fg,
      backgroundColor: token2.inverse ? token2.fg : token2.bg,
      dimColor: token2.dim,
      bold: token2.bold,
      italic: token2.italic,
      underline: token2.underline,
      children: token2.text
    },
    tokenIndex
  )) : null }, lineIndex));
}, "AnsiOutputText");

// packages/cli/src/ui/components/GeminiRespondingSpinner.tsx
init_esbuild_shims();

// node_modules/ink-spinner/build/index.js
init_esbuild_shims();
var import_react39 = __toESM(require_react(), 1);
var import_cli_spinners = __toESM(require_cli_spinners(), 1);
function Spinner({ type = "dots" }) {
  const [frame, setFrame] = (0, import_react39.useState)(0);
  const spinner = import_cli_spinners.default[type];
  (0, import_react39.useEffect)(() => {
    const timer = setInterval(() => {
      setFrame((previousFrame) => {
        const isLastFrame = previousFrame === spinner.frames.length - 1;
        return isLastFrame ? 0 : previousFrame + 1;
      });
    }, spinner.interval);
    return () => {
      clearInterval(timer);
    };
  }, [spinner]);
  return import_react39.default.createElement(Text, null, spinner.frames[frame]);
}
__name(Spinner, "Spinner");
var build_default = Spinner;

// packages/cli/src/ui/components/GeminiRespondingSpinner.tsx
var import_jsx_runtime14 = __toESM(require_jsx_runtime(), 1);
var GeminiRespondingSpinner = /* @__PURE__ */ __name(({ nonRespondingDisplay, spinnerType = "dots" }) => {
  const streamingState = useStreamingContext();
  const isScreenReaderEnabled = use_is_screen_reader_enabled_default();
  if (streamingState === "responding" /* Responding */) {
    return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
      GeminiSpinner,
      {
        spinnerType,
        altText: SCREEN_READER_RESPONDING
      }
    );
  } else if (nonRespondingDisplay) {
    return isScreenReaderEnabled ? /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { children: SCREEN_READER_LOADING }) : /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { color: theme.text.primary, children: nonRespondingDisplay });
  }
  return null;
}, "GeminiRespondingSpinner");
var GeminiSpinner = /* @__PURE__ */ __name(({
  spinnerType = "dots",
  altText
}) => {
  const isScreenReaderEnabled = use_is_screen_reader_enabled_default();
  return isScreenReaderEnabled ? /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { children: altText }) : /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { color: theme.text.primary, children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(build_default, { type: spinnerType }) });
}, "GeminiSpinner");

// packages/cli/src/ui/components/TodoDisplay.tsx
init_esbuild_shims();

// packages/cli/src/ui/colors.ts
init_esbuild_shims();
var Colors = {
  get type() {
    return themeManager.getActiveTheme().colors.type;
  },
  get Foreground() {
    return themeManager.getActiveTheme().colors.Foreground;
  },
  get Background() {
    return themeManager.getActiveTheme().colors.Background;
  },
  get LightBlue() {
    return themeManager.getActiveTheme().colors.LightBlue;
  },
  get AccentBlue() {
    return themeManager.getActiveTheme().colors.AccentBlue;
  },
  get AccentPurple() {
    return themeManager.getActiveTheme().colors.AccentPurple;
  },
  get AccentCyan() {
    return themeManager.getActiveTheme().colors.AccentCyan;
  },
  get AccentGreen() {
    return themeManager.getActiveTheme().colors.AccentGreen;
  },
  get AccentYellow() {
    return themeManager.getActiveTheme().colors.AccentYellow;
  },
  get AccentRed() {
    return themeManager.getActiveTheme().colors.AccentRed;
  },
  get DiffAdded() {
    return themeManager.getActiveTheme().colors.DiffAdded;
  },
  get DiffRemoved() {
    return themeManager.getActiveTheme().colors.DiffRemoved;
  },
  get Comment() {
    return themeManager.getActiveTheme().colors.Comment;
  },
  get Gray() {
    return themeManager.getActiveTheme().colors.Gray;
  },
  get GradientColors() {
    return themeManager.getActiveTheme().colors.GradientColors;
  }
};

// packages/cli/src/ui/components/TodoDisplay.tsx
var import_jsx_runtime15 = __toESM(require_jsx_runtime(), 1);
var STATUS_ICONS = {
  pending: "\u25CB",
  in_progress: "\u25D0",
  completed: "\u25CF"
};
var TodoDisplay = /* @__PURE__ */ __name(({ todos }) => {
  if (!todos || todos.length === 0) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Box_default, { flexDirection: "column", children: todos.map((todo) => /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(TodoItemRow, { todo }, todo.id)) });
}, "TodoDisplay");
var TodoItemRow = /* @__PURE__ */ __name(({ todo }) => {
  const statusIcon = STATUS_ICONS[todo.status];
  const isCompleted = todo.status === "completed";
  const isInProgress = todo.status === "in_progress";
  const itemColor = isCompleted ? Colors.Foreground : isInProgress ? Colors.AccentGreen : Colors.Foreground;
  return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(Box_default, { flexDirection: "row", minHeight: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Box_default, { width: 3, children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Text, { color: itemColor, children: statusIcon }) }),
    /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Text, { color: itemColor, strikethrough: isCompleted, wrap: "wrap", children: todo.content }) })
  ] });
}, "TodoItemRow");

// packages/cli/src/ui/components/subagents/index.ts
init_esbuild_shims();

// packages/cli/src/ui/components/subagents/create/AgentCreationWizard.tsx
init_esbuild_shims();
var import_react53 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/subagents/reducers.tsx
init_esbuild_shims();

// packages/cli/src/ui/components/subagents/types.ts
init_esbuild_shims();
var MANAGEMENT_STEPS = {
  AGENT_SELECTION: "agent-selection",
  ACTION_SELECTION: "action-selection",
  AGENT_VIEWER: "agent-viewer",
  EDIT_OPTIONS: "edit-options",
  EDIT_TOOLS: "edit-tools",
  EDIT_COLOR: "edit-color",
  DELETE_CONFIRMATION: "delete-confirmation"
};

// packages/cli/src/ui/components/subagents/constants.ts
init_esbuild_shims();
var WIZARD_STEPS = {
  LOCATION_SELECTION: 1,
  GENERATION_METHOD: 2,
  DESCRIPTION_INPUT: 3,
  TOOL_SELECTION: 4,
  COLOR_SELECTION: 5,
  FINAL_CONFIRMATION: 6
};
var TOTAL_WIZARD_STEPS = 6;
var STEP_NAMES = {
  [WIZARD_STEPS.LOCATION_SELECTION]: "Location Selection",
  [WIZARD_STEPS.GENERATION_METHOD]: "Generation Method",
  [WIZARD_STEPS.DESCRIPTION_INPUT]: "Description Input",
  [WIZARD_STEPS.TOOL_SELECTION]: "Tool Selection",
  [WIZARD_STEPS.COLOR_SELECTION]: "Color Selection",
  [WIZARD_STEPS.FINAL_CONFIRMATION]: "Final Confirmation"
};
var COLOR_OPTIONS = [
  {
    id: "auto",
    name: "Automatic Color",
    value: "auto"
  },
  {
    id: "blue",
    name: "Blue",
    value: "#3b82f6"
  },
  {
    id: "green",
    name: "Green",
    value: "#10b981"
  },
  {
    id: "purple",
    name: "Purple",
    value: "#8b5cf6"
  },
  {
    id: "orange",
    name: "Orange",
    value: "#f59e0b"
  },
  {
    id: "red",
    name: "Red",
    value: "#ef4444"
  },
  {
    id: "cyan",
    name: "Cyan",
    value: "#06b6d4"
  }
];

// packages/cli/src/ui/components/subagents/utils.ts
init_esbuild_shims();
var shouldShowColor = /* @__PURE__ */ __name((color) => color !== void 0 && color !== "auto", "shouldShowColor");
var getColorForDisplay = /* @__PURE__ */ __name((colorName) => !colorName || colorName === "auto" ? void 0 : COLOR_OPTIONS.find((color) => color.name === colorName)?.value, "getColorForDisplay");
function sanitizeInput(input) {
  return input.trim().replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "").replace(/\s+/g, " ");
}
__name(sanitizeInput, "sanitizeInput");
function fmtDuration(ms) {
  if (ms < 1e3) return `${Math.round(ms)}ms`;
  if (ms < 6e4) return `${(ms / 1e3).toFixed(1)}s`;
  if (ms < 36e5) {
    const m2 = Math.floor(ms / 6e4);
    const s2 = Math.floor(ms % 6e4 / 1e3);
    return `${m2}m ${s2}s`;
  }
  const h = Math.floor(ms / 36e5);
  const m = Math.floor(ms % 36e5 / 6e4);
  return `${h}h ${m}m`;
}
__name(fmtDuration, "fmtDuration");
function getTotalSteps(method) {
  return method === "manual" ? 8 : TOTAL_WIZARD_STEPS;
}
__name(getTotalSteps, "getTotalSteps");
function getStepKind(method, stepNumber) {
  if (method === "manual") {
    switch (stepNumber) {
      case 1:
        return "LOCATION";
      case 2:
        return "GEN_METHOD";
      case 3:
        return "MANUAL_NAME";
      case 4:
        return "MANUAL_PROMPT";
      case 5:
        return "MANUAL_DESC";
      case 6:
        return "TOOLS";
      case 7:
        return "COLOR";
      case 8:
        return "FINAL";
      default:
        return "FINAL";
    }
  }
  switch (stepNumber) {
    case 1:
      return "LOCATION";
    case 2:
      return "GEN_METHOD";
    case 3:
      return "LLM_DESC";
    case 4:
      return "TOOLS";
    case 5:
      return "COLOR";
    case 6:
      return "FINAL";
    default:
      return "FINAL";
  }
}
__name(getStepKind, "getStepKind");

// packages/cli/src/ui/components/subagents/reducers.tsx
var initialWizardState = {
  currentStep: WIZARD_STEPS.LOCATION_SELECTION,
  location: "project",
  generationMethod: "qwen",
  userDescription: "",
  generatedSystemPrompt: "",
  generatedDescription: "",
  generatedName: "",
  selectedTools: [],
  color: "auto",
  isGenerating: false,
  validationErrors: [],
  canProceed: false
};
function wizardReducer(state, action) {
  switch (action.type) {
    case "SET_STEP":
      return {
        ...state,
        currentStep: Math.max(
          WIZARD_STEPS.LOCATION_SELECTION,
          Math.min(getTotalSteps(state.generationMethod), action.step)
        ),
        validationErrors: []
      };
    case "SET_LOCATION":
      return {
        ...state,
        location: action.location,
        canProceed: true
      };
    case "SET_GENERATION_METHOD":
      return {
        ...state,
        generationMethod: action.method,
        canProceed: true
      };
    case "SET_USER_DESCRIPTION":
      return {
        ...state,
        userDescription: action.description,
        canProceed: action.description.trim().length >= 0
      };
    case "SET_GENERATED_CONTENT":
      return {
        ...state,
        generatedName: action.name,
        generatedDescription: action.description,
        generatedSystemPrompt: action.systemPrompt,
        isGenerating: false,
        canProceed: true
      };
    case "SET_GENERATED_NAME":
      return {
        ...state,
        generatedName: action.name,
        canProceed: action.name.trim().length > 0
      };
    case "SET_GENERATED_SYSTEM_PROMPT":
      return {
        ...state,
        generatedSystemPrompt: action.systemPrompt,
        canProceed: action.systemPrompt.trim().length > 0
      };
    case "SET_GENERATED_DESCRIPTION":
      return {
        ...state,
        generatedDescription: action.description,
        canProceed: action.description.trim().length > 0
      };
    case "SET_TOOLS":
      return {
        ...state,
        selectedTools: action.tools,
        canProceed: true
      };
    case "SET_BACKGROUND_COLOR":
      return {
        ...state,
        color: action.color,
        canProceed: true
      };
    case "SET_GENERATING":
      return {
        ...state,
        isGenerating: action.isGenerating,
        canProceed: !action.isGenerating
      };
    case "SET_VALIDATION_ERRORS":
      return {
        ...state,
        validationErrors: action.errors,
        canProceed: action.errors.length === 0
      };
    case "GO_TO_NEXT_STEP":
      if (state.canProceed && state.currentStep < getTotalSteps(state.generationMethod)) {
        return {
          ...state,
          currentStep: state.currentStep + 1,
          validationErrors: [],
          canProceed: validateStep(state.currentStep + 1, state)
        };
      }
      return state;
    case "GO_TO_PREVIOUS_STEP":
      if (state.currentStep > WIZARD_STEPS.LOCATION_SELECTION) {
        return {
          ...state,
          currentStep: state.currentStep - 1,
          validationErrors: [],
          canProceed: validateStep(state.currentStep - 1, state)
        };
      }
      return state;
    case "RESET_WIZARD":
      return initialWizardState;
    default:
      return state;
  }
}
__name(wizardReducer, "wizardReducer");
function validateStep(step, state) {
  const kind = getStepKind(state.generationMethod, step);
  switch (kind) {
    case "LOCATION":
    case "GEN_METHOD":
      return true;
    case "LLM_DESC":
      return state.userDescription.trim().length >= 0;
    case "MANUAL_NAME":
      return state.generatedName.trim().length > 0;
    case "MANUAL_PROMPT":
      return state.generatedSystemPrompt.trim().length > 0;
    case "MANUAL_DESC":
      return state.generatedDescription.trim().length > 0;
    case "TOOLS":
      return state.generatedName.length > 0 && state.generatedDescription.length > 0 && state.generatedSystemPrompt.length > 0;
    case "COLOR":
      return true;
    case "FINAL":
      return state.color.length > 0;
    default:
      return false;
  }
}
__name(validateStep, "validateStep");

// packages/cli/src/ui/components/subagents/create/LocationSelector.tsx
init_esbuild_shims();

// packages/cli/src/ui/components/shared/RadioButtonSelect.tsx
init_esbuild_shims();

// packages/cli/src/ui/components/shared/BaseSelectionList.tsx
init_esbuild_shims();
var import_react44 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useSelectionList.ts
init_esbuild_shims();
var import_react43 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useKeypress.ts
init_esbuild_shims();
var import_react42 = __toESM(require_react(), 1);

// packages/cli/src/ui/contexts/KeypressContext.tsx
init_esbuild_shims();
var import_react41 = __toESM(require_react(), 1);
import readline3 from "node:readline";
import { PassThrough as PassThrough3 } from "node:stream";

// packages/cli/src/ui/utils/platformConstants.ts
init_esbuild_shims();
var KITTY_CTRL_C = "[99;5u";
var KITTY_KEYCODE_ENTER = 13;
var KITTY_KEYCODE_NUMPAD_ENTER = 57414;
var KITTY_KEYCODE_TAB = 9;
var KITTY_KEYCODE_BACKSPACE = 127;
var KITTY_MODIFIER_BASE = 1;
var KITTY_MODIFIER_EVENT_TYPES_OFFSET = 128;
var MODIFIER_SHIFT_BIT = 1;
var MODIFIER_ALT_BIT = 2;
var MODIFIER_CTRL_BIT = 4;
var VSCODE_SHIFT_ENTER_SEQUENCE = "\\\r\n";
var BACKSLASH_ENTER_DETECTION_WINDOW_MS = 5;
var MAX_KITTY_SEQUENCE_LENGTH = 32;
var CHAR_CODE_ESC = 27;

// packages/cli/src/ui/hooks/useFocus.ts
init_esbuild_shims();
var import_react40 = __toESM(require_react(), 1);
var ENABLE_FOCUS_REPORTING = "\x1B[?1004h";
var DISABLE_FOCUS_REPORTING = "\x1B[?1004l";
var FOCUS_IN = "\x1B[I";
var FOCUS_OUT = "\x1B[O";
var useFocus = /* @__PURE__ */ __name(() => {
  const { stdin } = use_stdin_default();
  const { stdout } = use_stdout_default();
  const [isFocused, setIsFocused] = (0, import_react40.useState)(true);
  (0, import_react40.useEffect)(() => {
    const handleData = /* @__PURE__ */ __name((data) => {
      const sequence = data.toString();
      const lastFocusIn = sequence.lastIndexOf(FOCUS_IN);
      const lastFocusOut = sequence.lastIndexOf(FOCUS_OUT);
      if (lastFocusIn > lastFocusOut) {
        setIsFocused(true);
      } else if (lastFocusOut > lastFocusIn) {
        setIsFocused(false);
      }
    }, "handleData");
    stdout?.write(ENABLE_FOCUS_REPORTING);
    stdin?.on("data", handleData);
    return () => {
      stdout?.write(DISABLE_FOCUS_REPORTING);
      stdin?.removeListener("data", handleData);
    };
  }, [stdin, stdout]);
  useKeypress(
    (_) => {
      if (!isFocused) {
        setIsFocused(true);
      }
    },
    { isActive: true }
  );
  return isFocused;
}, "useFocus");

// packages/cli/src/ui/contexts/KeypressContext.tsx
var import_jsx_runtime16 = __toESM(require_jsx_runtime(), 1);
var ESC2 = "\x1B";
var PASTE_MODE_PREFIX = `${ESC2}[200~`;
var PASTE_MODE_SUFFIX = `${ESC2}[201~`;
var DRAG_COMPLETION_TIMEOUT_MS = 100;
var SINGLE_QUOTE = "'";
var DOUBLE_QUOTE = '"';
var KeypressContext = (0, import_react41.createContext)(
  void 0
);
function useKeypressContext() {
  const context2 = (0, import_react41.useContext)(KeypressContext);
  if (!context2) {
    throw new Error(
      "useKeypressContext must be used within a KeypressProvider"
    );
  }
  return context2;
}
__name(useKeypressContext, "useKeypressContext");
function KeypressProvider({
  children,
  kittyProtocolEnabled,
  pasteWorkaround = false,
  config,
  debugKeystrokeLogging
}) {
  const { stdin, setRawMode } = use_stdin_default();
  const subscribers = (0, import_react41.useRef)(/* @__PURE__ */ new Set()).current;
  const isDraggingRef = (0, import_react41.useRef)(false);
  const dragBufferRef = (0, import_react41.useRef)("");
  const draggingTimerRef = (0, import_react41.useRef)(null);
  const subscribe = (0, import_react41.useCallback)(
    (handler) => {
      subscribers.add(handler);
    },
    [subscribers]
  );
  const unsubscribe = (0, import_react41.useCallback)(
    (handler) => {
      subscribers.delete(handler);
    },
    [subscribers]
  );
  (0, import_react41.useEffect)(() => {
    const clearDraggingTimer = /* @__PURE__ */ __name(() => {
      if (draggingTimerRef.current) {
        clearTimeout(draggingTimerRef.current);
        draggingTimerRef.current = null;
      }
    }, "clearDraggingTimer");
    const wasRaw = stdin.isRaw;
    if (wasRaw === false) {
      setRawMode(true);
    }
    const keypressStream = new PassThrough3();
    let usePassthrough = false;
    if (pasteWorkaround) {
      usePassthrough = true;
    }
    let isPaste = false;
    let pasteBuffer = Buffer.alloc(0);
    let kittySequenceBuffer = "";
    let backslashTimeout = null;
    let waitingForEnterAfterBackslash = false;
    let rawDataBuffer = Buffer.alloc(0);
    let rawFlushTimeout = null;
    const parseKittyPrefix = /* @__PURE__ */ __name((buffer) => {
      const revTabLegacy = new RegExp(`^${ESC2}\\[Z`);
      let m = buffer.match(revTabLegacy);
      if (m) {
        return {
          key: {
            name: "tab",
            ctrl: false,
            meta: false,
            shift: true,
            paste: false,
            sequence: buffer.slice(0, m[0].length),
            kittyProtocol: true
          },
          length: m[0].length
        };
      }
      const revTabParam = new RegExp(`^${ESC2}\\[1;(\\d+)Z`);
      m = buffer.match(revTabParam);
      if (m) {
        let mods = parseInt(m[1], 10);
        if (mods >= KITTY_MODIFIER_EVENT_TYPES_OFFSET) {
          mods -= KITTY_MODIFIER_EVENT_TYPES_OFFSET;
        }
        const bits = mods - KITTY_MODIFIER_BASE;
        const alt = (bits & MODIFIER_ALT_BIT) === MODIFIER_ALT_BIT;
        const ctrl = (bits & MODIFIER_CTRL_BIT) === MODIFIER_CTRL_BIT;
        return {
          key: {
            name: "tab",
            ctrl,
            meta: alt,
            // Reverse tab implies Shift behavior; force shift regardless of mods
            shift: true,
            paste: false,
            sequence: buffer.slice(0, m[0].length),
            kittyProtocol: true
          },
          length: m[0].length
        };
      }
      const arrowPrefix = new RegExp(`^${ESC2}\\[1;(\\d+)([ABCDHFPQSR])`);
      m = buffer.match(arrowPrefix);
      if (m) {
        let mods = parseInt(m[1], 10);
        if (mods >= KITTY_MODIFIER_EVENT_TYPES_OFFSET) {
          mods -= KITTY_MODIFIER_EVENT_TYPES_OFFSET;
        }
        const bits = mods - KITTY_MODIFIER_BASE;
        const shift = (bits & MODIFIER_SHIFT_BIT) === MODIFIER_SHIFT_BIT;
        const alt = (bits & MODIFIER_ALT_BIT) === MODIFIER_ALT_BIT;
        const ctrl = (bits & MODIFIER_CTRL_BIT) === MODIFIER_CTRL_BIT;
        const sym = m[2];
        const symbolToName = {
          A: "up",
          B: "down",
          C: "right",
          D: "left",
          H: "home",
          F: "end",
          P: "f1",
          Q: "f2",
          R: "f3",
          S: "f4"
        };
        const name3 = symbolToName[sym] || "";
        if (!name3) return null;
        return {
          key: {
            name: name3,
            ctrl,
            meta: alt,
            shift,
            paste: false,
            sequence: buffer.slice(0, m[0].length),
            kittyProtocol: true
          },
          length: m[0].length
        };
      }
      const csiUPrefix = new RegExp(`^${ESC2}\\[(\\d+)(;(\\d+))?([u~])`);
      m = buffer.match(csiUPrefix);
      if (m) {
        const keyCode = parseInt(m[1], 10);
        let modifiers = m[3] ? parseInt(m[3], 10) : KITTY_MODIFIER_BASE;
        if (modifiers >= KITTY_MODIFIER_EVENT_TYPES_OFFSET) {
          modifiers -= KITTY_MODIFIER_EVENT_TYPES_OFFSET;
        }
        const modifierBits = modifiers - KITTY_MODIFIER_BASE;
        const shift = (modifierBits & MODIFIER_SHIFT_BIT) === MODIFIER_SHIFT_BIT;
        const alt = (modifierBits & MODIFIER_ALT_BIT) === MODIFIER_ALT_BIT;
        const ctrl = (modifierBits & MODIFIER_CTRL_BIT) === MODIFIER_CTRL_BIT;
        const terminator = m[4];
        if (terminator === "~") {
          let name4 = null;
          switch (keyCode) {
            case 1:
              name4 = "home";
              break;
            case 2:
              name4 = "insert";
              break;
            case 3:
              name4 = "delete";
              break;
            case 4:
              name4 = "end";
              break;
            case 5:
              name4 = "pageup";
              break;
            case 6:
              name4 = "pagedown";
              break;
            default:
              break;
          }
          if (name4) {
            return {
              key: {
                name: name4,
                ctrl,
                meta: alt,
                shift,
                paste: false,
                sequence: buffer.slice(0, m[0].length),
                kittyProtocol: true
              },
              length: m[0].length
            };
          }
        }
        const kittyKeyCodeToName = {
          [CHAR_CODE_ESC]: "escape",
          [KITTY_KEYCODE_TAB]: "tab",
          [KITTY_KEYCODE_BACKSPACE]: "backspace",
          [KITTY_KEYCODE_ENTER]: "return",
          [KITTY_KEYCODE_NUMPAD_ENTER]: "return"
        };
        const name3 = kittyKeyCodeToName[keyCode];
        if (name3) {
          return {
            key: {
              name: name3,
              ctrl,
              meta: alt,
              shift,
              paste: false,
              sequence: buffer.slice(0, m[0].length),
              kittyProtocol: true
            },
            length: m[0].length
          };
        }
        if (ctrl && keyCode >= "a".charCodeAt(0) && keyCode <= "z".charCodeAt(0)) {
          const letter = String.fromCharCode(keyCode);
          return {
            key: {
              name: letter,
              ctrl: true,
              meta: alt,
              shift,
              paste: false,
              sequence: buffer.slice(0, m[0].length),
              kittyProtocol: true
            },
            length: m[0].length
          };
        }
      }
      const legacyFuncKey = new RegExp(`^${ESC2}\\[([ABCDHF])`);
      m = buffer.match(legacyFuncKey);
      if (m) {
        const sym = m[1];
        const nameMap = {
          A: "up",
          B: "down",
          C: "right",
          D: "left",
          H: "home",
          F: "end"
        };
        const name3 = nameMap[sym];
        return {
          key: {
            name: name3,
            ctrl: false,
            meta: false,
            shift: false,
            paste: false,
            sequence: buffer.slice(0, m[0].length),
            kittyProtocol: true
          },
          length: m[0].length
        };
      }
      return null;
    }, "parseKittyPrefix");
    const broadcast = /* @__PURE__ */ __name((key) => {
      for (const handler of subscribers) {
        handler(key);
      }
    }, "broadcast");
    const handleKeypress = /* @__PURE__ */ __name((_, key) => {
      if (key.sequence === FOCUS_IN || key.sequence === FOCUS_OUT) {
        return;
      }
      if (key.name === "paste-start") {
        isPaste = true;
        return;
      }
      if (key.name === "paste-end") {
        isPaste = false;
        broadcast({
          name: "",
          ctrl: false,
          meta: false,
          shift: false,
          paste: true,
          sequence: pasteBuffer.toString()
        });
        pasteBuffer = Buffer.alloc(0);
        return;
      }
      if (isPaste) {
        pasteBuffer = Buffer.concat([pasteBuffer, Buffer.from(key.sequence)]);
        return;
      }
      if (key.sequence === SINGLE_QUOTE || key.sequence === DOUBLE_QUOTE || isDraggingRef.current) {
        isDraggingRef.current = true;
        dragBufferRef.current += key.sequence;
        clearDraggingTimer();
        draggingTimerRef.current = setTimeout(() => {
          isDraggingRef.current = false;
          const seq = dragBufferRef.current;
          dragBufferRef.current = "";
          if (seq) {
            broadcast({ ...key, name: "", paste: true, sequence: seq });
          }
        }, DRAG_COMPLETION_TIMEOUT_MS);
        return;
      }
      if (key.name === "return" && waitingForEnterAfterBackslash) {
        if (backslashTimeout) {
          clearTimeout(backslashTimeout);
          backslashTimeout = null;
        }
        waitingForEnterAfterBackslash = false;
        broadcast({
          ...key,
          shift: true,
          sequence: "\r"
          // Corrected escaping for newline
        });
        return;
      }
      if (key.sequence === "\\" && !key.name) {
        waitingForEnterAfterBackslash = true;
        backslashTimeout = setTimeout(() => {
          waitingForEnterAfterBackslash = false;
          backslashTimeout = null;
          broadcast(key);
        }, BACKSLASH_ENTER_DETECTION_WINDOW_MS);
        return;
      }
      if (waitingForEnterAfterBackslash && key.name !== "return") {
        if (backslashTimeout) {
          clearTimeout(backslashTimeout);
          backslashTimeout = null;
        }
        waitingForEnterAfterBackslash = false;
        broadcast({
          name: "",
          sequence: "\\",
          ctrl: false,
          meta: false,
          shift: false,
          paste: false
        });
      }
      if (["up", "down", "left", "right"].includes(key.name)) {
        broadcast(key);
        return;
      }
      if (key.ctrl && key.name === "c" || key.sequence === `${ESC2}${KITTY_CTRL_C}`) {
        if (kittySequenceBuffer && debugKeystrokeLogging) {
          console.log(
            "[DEBUG] Kitty buffer cleared on Ctrl+C:",
            kittySequenceBuffer
          );
        }
        kittySequenceBuffer = "";
        if (key.sequence === `${ESC2}${KITTY_CTRL_C}`) {
          broadcast({
            name: "c",
            ctrl: true,
            meta: false,
            shift: false,
            paste: false,
            sequence: key.sequence,
            kittyProtocol: true
          });
        } else {
          broadcast(key);
        }
        return;
      }
      if (kittyProtocolEnabled) {
        if (kittySequenceBuffer || key.sequence.startsWith(`${ESC2}[`) && !key.sequence.startsWith(PASTE_MODE_PREFIX) && !key.sequence.startsWith(PASTE_MODE_SUFFIX) && !key.sequence.startsWith(FOCUS_IN) && !key.sequence.startsWith(FOCUS_OUT)) {
          kittySequenceBuffer += key.sequence;
          if (debugKeystrokeLogging) {
            console.log(
              "[DEBUG] Kitty buffer accumulating:",
              kittySequenceBuffer
            );
          }
          let parsedAny = false;
          while (kittySequenceBuffer) {
            const parsed = parseKittyPrefix(kittySequenceBuffer);
            if (!parsed) {
              const nextStart = kittySequenceBuffer.indexOf(`${ESC2}[`, 1);
              if (nextStart > 0) {
                if (debugKeystrokeLogging) {
                  console.log(
                    "[DEBUG] Skipping incomplete/invalid CSI prefix:",
                    kittySequenceBuffer.slice(0, nextStart)
                  );
                }
                kittySequenceBuffer = kittySequenceBuffer.slice(nextStart);
                continue;
              }
              break;
            }
            if (debugKeystrokeLogging) {
              const parsedSequence = kittySequenceBuffer.slice(
                0,
                parsed.length
              );
              if (kittySequenceBuffer.length > parsed.length) {
                console.log(
                  "[DEBUG] Kitty sequence parsed successfully (prefix):",
                  parsedSequence
                );
              } else {
                console.log(
                  "[DEBUG] Kitty sequence parsed successfully:",
                  parsedSequence
                );
              }
            }
            kittySequenceBuffer = kittySequenceBuffer.slice(parsed.length);
            broadcast(parsed.key);
            parsedAny = true;
          }
          if (parsedAny) return;
          if (config?.getDebugMode() || debugKeystrokeLogging) {
            const codes = Array.from(kittySequenceBuffer).map(
              (ch) => ch.charCodeAt(0)
            );
            console.warn("Kitty sequence buffer has char codes:", codes);
          }
          if (kittySequenceBuffer.length > MAX_KITTY_SEQUENCE_LENGTH) {
            if (debugKeystrokeLogging) {
              console.log(
                "[DEBUG] Kitty buffer overflow, clearing:",
                kittySequenceBuffer
              );
            }
            if (config) {
              const event = new KittySequenceOverflowEvent(
                kittySequenceBuffer.length,
                kittySequenceBuffer
              );
              logKittySequenceOverflow(config, event);
            }
            kittySequenceBuffer = "";
          } else {
            return;
          }
        }
      }
      if (key.name === "return" && key.sequence === `${ESC2}\r`) {
        key.meta = true;
      }
      broadcast({ ...key, paste: isPaste });
    }, "handleKeypress");
    const clearRawFlushTimeout = /* @__PURE__ */ __name(() => {
      if (rawFlushTimeout) {
        clearTimeout(rawFlushTimeout);
        rawFlushTimeout = null;
      }
    }, "clearRawFlushTimeout");
    const createPasteKeyEvent = /* @__PURE__ */ __name((name3 = "", sequence = "") => ({
      name: name3,
      ctrl: false,
      meta: false,
      shift: false,
      paste: false,
      sequence
    }), "createPasteKeyEvent");
    const flushRawBuffer = /* @__PURE__ */ __name(() => {
      if (!rawDataBuffer.length) {
        return;
      }
      const pasteModePrefixBuffer = Buffer.from(PASTE_MODE_PREFIX);
      const pasteModeSuffixBuffer = Buffer.from(PASTE_MODE_SUFFIX);
      const data = rawDataBuffer;
      let cursor = 0;
      while (cursor < data.length) {
        const prefixPos = data.indexOf(pasteModePrefixBuffer, cursor);
        const suffixPos = data.indexOf(pasteModeSuffixBuffer, cursor);
        const hasPrefix = prefixPos !== -1 && prefixPos + pasteModePrefixBuffer.length <= data.length;
        const hasSuffix = suffixPos !== -1 && suffixPos + pasteModeSuffixBuffer.length <= data.length;
        let markerPos = -1;
        let markerLength = 0;
        let markerType = null;
        if (hasPrefix && (!hasSuffix || prefixPos < suffixPos)) {
          markerPos = prefixPos;
          markerLength = pasteModePrefixBuffer.length;
          markerType = "prefix";
        } else if (hasSuffix) {
          markerPos = suffixPos;
          markerLength = pasteModeSuffixBuffer.length;
          markerType = "suffix";
        }
        if (markerPos === -1) {
          break;
        }
        const nextData = data.slice(cursor, markerPos);
        if (nextData.length > 0) {
          keypressStream.write(nextData);
        }
        if (markerType === "prefix") {
          handleKeypress(void 0, createPasteKeyEvent("paste-start"));
        } else if (markerType === "suffix") {
          handleKeypress(void 0, createPasteKeyEvent("paste-end"));
        }
        cursor = markerPos + markerLength;
      }
      rawDataBuffer = data.slice(cursor);
      if (rawDataBuffer.length === 0) {
        return;
      }
      if (rawDataBuffer.length <= 2 && rawDataBuffer.includes(13) || !rawDataBuffer.includes(13) || isPaste) {
        keypressStream.write(rawDataBuffer);
      } else {
        handleKeypress(void 0, createPasteKeyEvent("paste-start"));
        keypressStream.write(rawDataBuffer);
        handleKeypress(void 0, createPasteKeyEvent("paste-end"));
      }
      rawDataBuffer = Buffer.alloc(0);
      clearRawFlushTimeout();
    }, "flushRawBuffer");
    const handleRawKeypress = /* @__PURE__ */ __name((_data) => {
      const data = Buffer.isBuffer(_data) ? _data : Buffer.from(_data, "utf8");
      rawDataBuffer = Buffer.concat([rawDataBuffer, data]);
      clearRawFlushTimeout();
      const isReturnChar = rawDataBuffer.length <= 2 && rawDataBuffer.includes(13);
      if (isReturnChar) {
        rawFlushTimeout = setTimeout(flushRawBuffer, 100);
      } else {
        flushRawBuffer();
      }
    }, "handleRawKeypress");
    let rl;
    if (usePassthrough) {
      rl = readline3.createInterface({
        input: keypressStream,
        escapeCodeTimeout: 0
      });
      readline3.emitKeypressEvents(keypressStream, rl);
      keypressStream.on("keypress", handleKeypress);
      stdin.on("data", handleRawKeypress);
    } else {
      rl = readline3.createInterface({ input: stdin, escapeCodeTimeout: 0 });
      readline3.emitKeypressEvents(stdin, rl);
      stdin.on("keypress", handleKeypress);
    }
    return () => {
      if (usePassthrough) {
        keypressStream.removeListener("keypress", handleKeypress);
        stdin.removeListener("data", handleRawKeypress);
      } else {
        stdin.removeListener("keypress", handleKeypress);
      }
      rl.close();
      if (wasRaw === false) {
        setRawMode(false);
      }
      if (backslashTimeout) {
        clearTimeout(backslashTimeout);
        backslashTimeout = null;
      }
      if (rawFlushTimeout) {
        clearTimeout(rawFlushTimeout);
        rawFlushTimeout = null;
      }
      if (isPaste) {
        broadcast({
          name: "",
          ctrl: false,
          meta: false,
          shift: false,
          paste: true,
          sequence: pasteBuffer.toString()
        });
        pasteBuffer = Buffer.alloc(0);
      }
      if (draggingTimerRef.current) {
        clearTimeout(draggingTimerRef.current);
        draggingTimerRef.current = null;
      }
      if (isDraggingRef.current && dragBufferRef.current) {
        broadcast({
          name: "",
          ctrl: false,
          meta: false,
          shift: false,
          paste: true,
          sequence: dragBufferRef.current
        });
        isDraggingRef.current = false;
        dragBufferRef.current = "";
      }
    };
  }, [
    stdin,
    setRawMode,
    kittyProtocolEnabled,
    debugKeystrokeLogging,
    pasteWorkaround,
    config,
    subscribers
  ]);
  return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(KeypressContext.Provider, { value: { subscribe, unsubscribe }, children });
}
__name(KeypressProvider, "KeypressProvider");

// packages/cli/src/ui/hooks/useKeypress.ts
function useKeypress(onKeypress, { isActive }) {
  const { subscribe, unsubscribe } = useKeypressContext();
  (0, import_react42.useEffect)(() => {
    if (!isActive) {
      return;
    }
    subscribe(onKeypress);
    return () => {
      unsubscribe(onKeypress);
    };
  }, [isActive, onKeypress, subscribe, unsubscribe]);
}
__name(useKeypress, "useKeypress");

// packages/cli/src/ui/hooks/useSelectionList.ts
var NUMBER_INPUT_TIMEOUT_MS = 1e3;
var findNextValidIndex = /* @__PURE__ */ __name((currentIndex, direction, items) => {
  const len = items.length;
  if (len === 0) return currentIndex;
  let nextIndex = currentIndex;
  const step = direction === "down" ? 1 : -1;
  for (let i = 0; i < len; i++) {
    nextIndex = (nextIndex + step + len) % len;
    if (!items[nextIndex]?.disabled) {
      return nextIndex;
    }
  }
  return currentIndex;
}, "findNextValidIndex");
var computeInitialIndex = /* @__PURE__ */ __name((initialIndex, items, initialKey) => {
  if (items.length === 0) {
    return 0;
  }
  if (initialKey !== void 0) {
    for (let i = 0; i < items.length; i++) {
      if (items[i].key === initialKey && !items[i].disabled) {
        return i;
      }
    }
  }
  let targetIndex = initialIndex;
  if (targetIndex < 0 || targetIndex >= items.length) {
    targetIndex = 0;
  }
  if (items[targetIndex]?.disabled) {
    const nextValid = findNextValidIndex(targetIndex, "down", items);
    targetIndex = nextValid;
  }
  return targetIndex;
}, "computeInitialIndex");
function selectionListReducer(state, action) {
  switch (action.type) {
    case "SET_ACTIVE_INDEX": {
      const { index, items } = action.payload;
      if (index === state.activeIndex) {
        return state;
      }
      if (index >= 0 && index < items.length) {
        return { ...state, activeIndex: index, pendingHighlight: true };
      }
      return state;
    }
    case "MOVE_UP": {
      const { items } = action.payload;
      const newIndex = findNextValidIndex(state.activeIndex, "up", items);
      if (newIndex !== state.activeIndex) {
        return { ...state, activeIndex: newIndex, pendingHighlight: true };
      }
      return state;
    }
    case "MOVE_DOWN": {
      const { items } = action.payload;
      const newIndex = findNextValidIndex(state.activeIndex, "down", items);
      if (newIndex !== state.activeIndex) {
        return { ...state, activeIndex: newIndex, pendingHighlight: true };
      }
      return state;
    }
    case "SELECT_CURRENT": {
      return { ...state, pendingSelect: true };
    }
    case "INITIALIZE": {
      const { initialIndex, items } = action.payload;
      const activeKey = initialIndex === state.initialIndex && state.activeIndex !== state.initialIndex ? state.items[state.activeIndex]?.key : void 0;
      if (items === state.items && initialIndex === state.initialIndex) {
        return state;
      }
      const targetIndex = computeInitialIndex(initialIndex, items, activeKey);
      return {
        ...state,
        items,
        activeIndex: targetIndex,
        pendingHighlight: false
      };
    }
    case "CLEAR_PENDING_FLAGS": {
      return {
        ...state,
        pendingHighlight: false,
        pendingSelect: false
      };
    }
    default: {
      const exhaustiveCheck = action;
      console.error(`Unknown selection list action: ${exhaustiveCheck}`);
      return state;
    }
  }
}
__name(selectionListReducer, "selectionListReducer");
function useSelectionList({
  items,
  initialIndex = 0,
  onSelect,
  onHighlight,
  isFocused = true,
  showNumbers = false
}) {
  const [state, dispatch] = (0, import_react43.useReducer)(selectionListReducer, {
    activeIndex: computeInitialIndex(initialIndex, items),
    initialIndex,
    pendingHighlight: false,
    pendingSelect: false,
    items
  });
  const numberInputRef = (0, import_react43.useRef)("");
  const numberInputTimer = (0, import_react43.useRef)(null);
  (0, import_react43.useEffect)(() => {
    dispatch({ type: "INITIALIZE", payload: { initialIndex, items } });
  }, [initialIndex, items]);
  (0, import_react43.useEffect)(() => {
    let needsClear = false;
    if (state.pendingHighlight && items[state.activeIndex]) {
      onHighlight?.(items[state.activeIndex].value);
      needsClear = true;
    }
    if (state.pendingSelect && items[state.activeIndex]) {
      const currentItem = items[state.activeIndex];
      if (currentItem && !currentItem.disabled) {
        onSelect(currentItem.value);
      }
      needsClear = true;
    }
    if (needsClear) {
      dispatch({ type: "CLEAR_PENDING_FLAGS" });
    }
  }, [
    state.pendingHighlight,
    state.pendingSelect,
    state.activeIndex,
    items,
    onHighlight,
    onSelect
  ]);
  (0, import_react43.useEffect)(
    () => () => {
      if (numberInputTimer.current) {
        clearTimeout(numberInputTimer.current);
      }
    },
    []
  );
  useKeypress(
    (key) => {
      const { sequence, name: name3 } = key;
      const isNumeric = showNumbers && /^[0-9]$/.test(sequence);
      if (!isNumeric && numberInputTimer.current) {
        clearTimeout(numberInputTimer.current);
        numberInputRef.current = "";
      }
      if (name3 === "k" || name3 === "up") {
        dispatch({ type: "MOVE_UP", payload: { items } });
        return;
      }
      if (name3 === "j" || name3 === "down") {
        dispatch({ type: "MOVE_DOWN", payload: { items } });
        return;
      }
      if (name3 === "return") {
        dispatch({ type: "SELECT_CURRENT", payload: { items } });
        return;
      }
      if (isNumeric) {
        if (numberInputTimer.current) {
          clearTimeout(numberInputTimer.current);
        }
        const newNumberInput = numberInputRef.current + sequence;
        numberInputRef.current = newNumberInput;
        const targetIndex = Number.parseInt(newNumberInput, 10) - 1;
        if (newNumberInput === "0") {
          numberInputTimer.current = setTimeout(() => {
            numberInputRef.current = "";
          }, NUMBER_INPUT_TIMEOUT_MS);
          return;
        }
        if (targetIndex >= 0 && targetIndex < items.length) {
          dispatch({
            type: "SET_ACTIVE_INDEX",
            payload: { index: targetIndex, items }
          });
          const potentialNextNumber = Number.parseInt(newNumberInput + "0", 10);
          if (potentialNextNumber > items.length) {
            dispatch({
              type: "SELECT_CURRENT",
              payload: { items }
            });
            numberInputRef.current = "";
          } else {
            numberInputTimer.current = setTimeout(() => {
              dispatch({
                type: "SELECT_CURRENT",
                payload: { items }
              });
              numberInputRef.current = "";
            }, NUMBER_INPUT_TIMEOUT_MS);
          }
        } else {
          numberInputRef.current = "";
        }
      }
    },
    { isActive: !!(isFocused && items.length > 0) }
  );
  const setActiveIndex = /* @__PURE__ */ __name((index) => {
    dispatch({
      type: "SET_ACTIVE_INDEX",
      payload: { index, items }
    });
  }, "setActiveIndex");
  return {
    activeIndex: state.activeIndex,
    setActiveIndex
  };
}
__name(useSelectionList, "useSelectionList");

// packages/cli/src/ui/components/shared/BaseSelectionList.tsx
var import_jsx_runtime17 = __toESM(require_jsx_runtime(), 1);
function BaseSelectionList({
  items,
  initialIndex = 0,
  onSelect,
  onHighlight,
  isFocused = true,
  showNumbers = true,
  showScrollArrows = false,
  maxItemsToShow: maxItemsToShow2 = 10,
  renderItem
}) {
  const { activeIndex } = useSelectionList({
    items,
    initialIndex,
    onSelect,
    onHighlight,
    isFocused,
    showNumbers
  });
  const [scrollOffset, setScrollOffset] = (0, import_react44.useState)(0);
  (0, import_react44.useEffect)(() => {
    const newScrollOffset = Math.max(
      0,
      Math.min(activeIndex - maxItemsToShow2 + 1, items.length - maxItemsToShow2)
    );
    if (activeIndex < scrollOffset) {
      setScrollOffset(activeIndex);
    } else if (activeIndex >= scrollOffset + maxItemsToShow2) {
      setScrollOffset(newScrollOffset);
    }
  }, [activeIndex, items.length, scrollOffset, maxItemsToShow2]);
  const visibleItems = items.slice(scrollOffset, scrollOffset + maxItemsToShow2);
  const numberColumnWidth = String(items.length).length;
  return /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)(Box_default, { flexDirection: "column", children: [
    showScrollArrows && /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
      Text,
      {
        color: scrollOffset > 0 ? theme.text.primary : theme.text.secondary,
        children: "\u25B2"
      }
    ),
    visibleItems.map((item, index) => {
      const itemIndex = scrollOffset + index;
      const isSelected = activeIndex === itemIndex;
      let titleColor = theme.text.primary;
      let numberColor = theme.text.primary;
      if (isSelected) {
        titleColor = theme.status.success;
        numberColor = theme.status.success;
      } else if (item.disabled) {
        titleColor = theme.text.secondary;
        numberColor = theme.text.secondary;
      }
      if (!isFocused && !item.disabled) {
        numberColor = theme.text.secondary;
      }
      if (!showNumbers) {
        numberColor = theme.text.secondary;
      }
      const itemNumberText = `${String(itemIndex + 1).padStart(
        numberColumnWidth
      )}.`;
      return /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)(Box_default, { alignItems: "flex-start", children: [
        /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Box_default, { minWidth: 2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
          Text,
          {
            color: isSelected ? theme.status.success : theme.text.primary,
            "aria-hidden": true,
            children: isSelected ? "\u25CF" : " "
          }
        ) }),
        showNumbers && /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
          Box_default,
          {
            marginRight: 1,
            flexShrink: 0,
            minWidth: itemNumberText.length,
            "aria-state": { checked: isSelected },
            children: /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Text, { color: numberColor, children: itemNumberText })
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Box_default, { flexGrow: 1, children: renderItem(item, {
          isSelected,
          titleColor,
          numberColor
        }) })
      ] }, item.key);
    }),
    showScrollArrows && /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
      Text,
      {
        color: scrollOffset + maxItemsToShow2 < items.length ? theme.text.primary : theme.text.secondary,
        children: "\u25BC"
      }
    )
  ] });
}
__name(BaseSelectionList, "BaseSelectionList");

// packages/cli/src/ui/components/shared/RadioButtonSelect.tsx
var import_jsx_runtime18 = __toESM(require_jsx_runtime(), 1);
function RadioButtonSelect({
  items,
  initialIndex = 0,
  onSelect,
  onHighlight,
  isFocused = true,
  showScrollArrows = false,
  maxItemsToShow: maxItemsToShow2 = 10,
  showNumbers = true
}) {
  return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
    BaseSelectionList,
    {
      items,
      initialIndex,
      onSelect,
      onHighlight,
      isFocused,
      showNumbers,
      showScrollArrows,
      maxItemsToShow: maxItemsToShow2,
      renderItem: (item, { titleColor }) => {
        if (item.themeNameDisplay && item.themeTypeDisplay) {
          return /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)(Text, { color: titleColor, wrap: "truncate", children: [
            item.themeNameDisplay,
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Text, { color: theme.text.secondary, children: item.themeTypeDisplay })
          ] }, item.key);
        }
        return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Text, { color: titleColor, wrap: "truncate", children: item.label });
      }
    }
  );
}
__name(RadioButtonSelect, "RadioButtonSelect");

// packages/cli/src/ui/components/subagents/create/LocationSelector.tsx
var import_jsx_runtime19 = __toESM(require_jsx_runtime(), 1);
var locationOptions = [
  {
    label: "Project Level (.qwen/agents/)",
    value: "project"
  },
  {
    label: "User Level (~/.qwen/agents/)",
    value: "user"
  }
];
function LocationSelector({ state, dispatch, onNext }) {
  const handleSelect = /* @__PURE__ */ __name((selectedValue) => {
    const location = selectedValue;
    dispatch({ type: "SET_LOCATION", location });
    onNext();
  }, "handleSelect");
  return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
    RadioButtonSelect,
    {
      items: locationOptions.map((option2) => ({
        key: option2.value,
        label: option2.label,
        value: option2.value
      })),
      initialIndex: locationOptions.findIndex(
        (opt) => opt.value === state.location
      ),
      onSelect: handleSelect,
      isFocused: true
    }
  ) });
}
__name(LocationSelector, "LocationSelector");

// packages/cli/src/ui/components/subagents/create/GenerationMethodSelector.tsx
init_esbuild_shims();
var import_jsx_runtime20 = __toESM(require_jsx_runtime(), 1);
var generationOptions = [
  {
    label: "Generate with Qwen Code (Recommended)",
    value: "qwen"
  },
  {
    label: "Manual Creation",
    value: "manual"
  }
];
function GenerationMethodSelector({
  state,
  dispatch,
  onNext,
  onPrevious: _onPrevious
}) {
  const handleSelect = /* @__PURE__ */ __name((selectedValue) => {
    const method = selectedValue;
    dispatch({ type: "SET_GENERATION_METHOD", method });
    onNext();
  }, "handleSelect");
  return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
    RadioButtonSelect,
    {
      items: generationOptions.map((option2) => ({
        key: option2.value,
        label: option2.label,
        value: option2.value
      })),
      initialIndex: generationOptions.findIndex(
        (opt) => opt.value === state.generationMethod
      ),
      onSelect: handleSelect,
      isFocused: true
    }
  ) });
}
__name(GenerationMethodSelector, "GenerationMethodSelector");

// packages/cli/src/ui/components/subagents/create/DescriptionInput.tsx
init_esbuild_shims();
var import_react47 = __toESM(require_react(), 1);

// packages/cli/src/ui/keyMatchers.ts
init_esbuild_shims();

// packages/cli/src/config/keyBindings.ts
init_esbuild_shims();
var Command = /* @__PURE__ */ ((Command2) => {
  Command2["RETURN"] = "return";
  Command2["ESCAPE"] = "escape";
  Command2["HOME"] = "home";
  Command2["END"] = "end";
  Command2["KILL_LINE_RIGHT"] = "killLineRight";
  Command2["KILL_LINE_LEFT"] = "killLineLeft";
  Command2["CLEAR_INPUT"] = "clearInput";
  Command2["DELETE_WORD_BACKWARD"] = "deleteWordBackward";
  Command2["CLEAR_SCREEN"] = "clearScreen";
  Command2["HISTORY_UP"] = "historyUp";
  Command2["HISTORY_DOWN"] = "historyDown";
  Command2["NAVIGATION_UP"] = "navigationUp";
  Command2["NAVIGATION_DOWN"] = "navigationDown";
  Command2["ACCEPT_SUGGESTION"] = "acceptSuggestion";
  Command2["COMPLETION_UP"] = "completionUp";
  Command2["COMPLETION_DOWN"] = "completionDown";
  Command2["SUBMIT"] = "submit";
  Command2["NEWLINE"] = "newline";
  Command2["OPEN_EXTERNAL_EDITOR"] = "openExternalEditor";
  Command2["PASTE_CLIPBOARD_IMAGE"] = "pasteClipboardImage";
  Command2["SHOW_ERROR_DETAILS"] = "showErrorDetails";
  Command2["TOGGLE_TOOL_DESCRIPTIONS"] = "toggleToolDescriptions";
  Command2["TOGGLE_IDE_CONTEXT_DETAIL"] = "toggleIDEContextDetail";
  Command2["QUIT"] = "quit";
  Command2["EXIT"] = "exit";
  Command2["SHOW_MORE_LINES"] = "showMoreLines";
  Command2["REVERSE_SEARCH"] = "reverseSearch";
  Command2["SUBMIT_REVERSE_SEARCH"] = "submitReverseSearch";
  Command2["ACCEPT_SUGGESTION_REVERSE_SEARCH"] = "acceptSuggestionReverseSearch";
  Command2["TOGGLE_SHELL_INPUT_FOCUS"] = "toggleShellInputFocus";
  Command2["EXPAND_SUGGESTION"] = "expandSuggestion";
  Command2["COLLAPSE_SUGGESTION"] = "collapseSuggestion";
  return Command2;
})(Command || {});
var defaultKeyBindings = {
  // Basic bindings
  ["return" /* RETURN */]: [{ key: "return" }],
  ["escape" /* ESCAPE */]: [{ key: "escape" }],
  // Cursor movement
  ["home" /* HOME */]: [{ key: "a", ctrl: true }],
  ["end" /* END */]: [{ key: "e", ctrl: true }],
  // Text deletion
  ["killLineRight" /* KILL_LINE_RIGHT */]: [{ key: "k", ctrl: true }],
  ["killLineLeft" /* KILL_LINE_LEFT */]: [{ key: "u", ctrl: true }],
  ["clearInput" /* CLEAR_INPUT */]: [{ key: "c", ctrl: true }],
  // Added command (meta/alt/option) for mac compatibility
  ["deleteWordBackward" /* DELETE_WORD_BACKWARD */]: [
    { key: "backspace", ctrl: true },
    { key: "backspace", command: true }
  ],
  // Screen control
  ["clearScreen" /* CLEAR_SCREEN */]: [{ key: "l", ctrl: true }],
  // History navigation
  ["historyUp" /* HISTORY_UP */]: [{ key: "p", ctrl: true }],
  ["historyDown" /* HISTORY_DOWN */]: [{ key: "n", ctrl: true }],
  ["navigationUp" /* NAVIGATION_UP */]: [{ key: "up" }],
  ["navigationDown" /* NAVIGATION_DOWN */]: [{ key: "down" }],
  // Auto-completion
  ["acceptSuggestion" /* ACCEPT_SUGGESTION */]: [{ key: "tab" }, { key: "return", ctrl: false }],
  // Completion navigation (arrow or Ctrl+P/N)
  ["completionUp" /* COMPLETION_UP */]: [{ key: "up" }, { key: "p", ctrl: true }],
  ["completionDown" /* COMPLETION_DOWN */]: [{ key: "down" }, { key: "n", ctrl: true }],
  // Text input
  // Must also exclude shift to allow shift+enter for newline
  ["submit" /* SUBMIT */]: [
    {
      key: "return",
      ctrl: false,
      command: false,
      paste: false,
      shift: false
    }
  ],
  // Split into multiple data-driven bindings
  // Now also includes shift+enter for multi-line input
  ["newline" /* NEWLINE */]: [
    { key: "return", ctrl: true },
    { key: "return", command: true },
    { key: "return", paste: true },
    { key: "return", shift: true },
    { key: "j", ctrl: true }
  ],
  // External tools
  ["openExternalEditor" /* OPEN_EXTERNAL_EDITOR */]: [
    { key: "x", ctrl: true },
    { sequence: "", ctrl: true }
  ],
  ["pasteClipboardImage" /* PASTE_CLIPBOARD_IMAGE */]: [{ key: "v", ctrl: true }],
  // App level bindings
  ["showErrorDetails" /* SHOW_ERROR_DETAILS */]: [{ key: "o", ctrl: true }],
  ["toggleToolDescriptions" /* TOGGLE_TOOL_DESCRIPTIONS */]: [{ key: "t", ctrl: true }],
  ["toggleIDEContextDetail" /* TOGGLE_IDE_CONTEXT_DETAIL */]: [{ key: "g", ctrl: true }],
  ["quit" /* QUIT */]: [{ key: "c", ctrl: true }],
  ["exit" /* EXIT */]: [{ key: "d", ctrl: true }],
  ["showMoreLines" /* SHOW_MORE_LINES */]: [{ key: "s", ctrl: true }],
  // Shell commands
  ["reverseSearch" /* REVERSE_SEARCH */]: [{ key: "r", ctrl: true }],
  // Note: original logic ONLY checked ctrl=false, ignored meta/shift/paste
  ["submitReverseSearch" /* SUBMIT_REVERSE_SEARCH */]: [{ key: "return", ctrl: false }],
  ["acceptSuggestionReverseSearch" /* ACCEPT_SUGGESTION_REVERSE_SEARCH */]: [{ key: "tab" }],
  ["toggleShellInputFocus" /* TOGGLE_SHELL_INPUT_FOCUS */]: [{ key: "f", ctrl: true }],
  // Suggestion expansion
  ["expandSuggestion" /* EXPAND_SUGGESTION */]: [{ key: "right" }],
  ["collapseSuggestion" /* COLLAPSE_SUGGESTION */]: [{ key: "left" }]
};

// packages/cli/src/ui/keyMatchers.ts
function matchKeyBinding(keyBinding, key) {
  let keyMatches = false;
  if (keyBinding.key !== void 0) {
    keyMatches = keyBinding.key === key.name;
  } else if (keyBinding.sequence !== void 0) {
    keyMatches = keyBinding.sequence === key.sequence;
  } else {
    return false;
  }
  if (!keyMatches) {
    return false;
  }
  if (keyBinding.ctrl !== void 0 && key.ctrl !== keyBinding.ctrl) {
    return false;
  }
  if (keyBinding.shift !== void 0 && key.shift !== keyBinding.shift) {
    return false;
  }
  if (keyBinding.command !== void 0 && key.meta !== keyBinding.command) {
    return false;
  }
  if (keyBinding.paste !== void 0 && key.paste !== keyBinding.paste) {
    return false;
  }
  return true;
}
__name(matchKeyBinding, "matchKeyBinding");
function matchCommand(command2, key, config = defaultKeyBindings) {
  const bindings = config[command2];
  return bindings.some((binding) => matchKeyBinding(binding, key));
}
__name(matchCommand, "matchCommand");
function createKeyMatchers(config = defaultKeyBindings) {
  const matchers = {};
  for (const command2 of Object.values(Command)) {
    matchers[command2] = (key) => matchCommand(command2, key, config);
  }
  return matchers;
}
__name(createKeyMatchers, "createKeyMatchers");
var keyMatchers = createKeyMatchers(defaultKeyBindings);

// packages/cli/src/ui/components/shared/TextInput.tsx
init_esbuild_shims();
var import_chalk4 = __toESM(require_source(), 1);

// packages/cli/src/ui/components/shared/text-buffer.ts
init_esbuild_shims();
var import_react45 = __toESM(require_react(), 1);
import { spawnSync as spawnSync3 } from "node:child_process";
import fs54 from "node:fs";
import os24 from "node:os";
import pathMod from "node:path";

// packages/cli/src/ui/components/shared/vim-buffer-actions.ts
init_esbuild_shims();

// packages/cli/src/utils/checks.ts
init_esbuild_shims();
function assumeExhaustive(_value) {
}
__name(assumeExhaustive, "assumeExhaustive");
function checkExhaustive(value, msg = `unexpected value ${value}!`) {
  assumeExhaustive(value);
  throw new Error(msg);
}
__name(checkExhaustive, "checkExhaustive");

// packages/cli/src/ui/components/shared/vim-buffer-actions.ts
function isAtEndOfBaseWord(lineCodePoints, col) {
  if (!isWordCharStrict(lineCodePoints[col])) return false;
  let i = col + 1;
  while (i < lineCodePoints.length && isCombiningMark(lineCodePoints[i])) {
    i++;
  }
  return i >= lineCodePoints.length || !isWordCharStrict(lineCodePoints[i]);
}
__name(isAtEndOfBaseWord, "isAtEndOfBaseWord");
function handleVimAction(state, action) {
  const { lines, cursorRow, cursorCol } = state;
  switch (action.type) {
    case "vim_delete_word_forward":
    case "vim_change_word_forward": {
      const { count } = action.payload;
      let endRow = cursorRow;
      let endCol = cursorCol;
      for (let i = 0; i < count; i++) {
        const nextWord = findNextWordAcrossLines(lines, endRow, endCol, true);
        if (nextWord) {
          endRow = nextWord.row;
          endCol = nextWord.col;
        } else {
          const currentLine = lines[endRow] || "";
          const wordEnd = findWordEndInLine(currentLine, endCol);
          if (wordEnd !== null) {
            endCol = wordEnd + 1;
          } else {
            endCol = cpLen(currentLine);
          }
          break;
        }
      }
      if (endRow !== cursorRow || endCol !== cursorCol) {
        const nextState = pushUndo(state);
        return replaceRangeInternal(
          nextState,
          cursorRow,
          cursorCol,
          endRow,
          endCol,
          ""
        );
      }
      return state;
    }
    case "vim_delete_word_backward":
    case "vim_change_word_backward": {
      const { count } = action.payload;
      let startRow = cursorRow;
      let startCol = cursorCol;
      for (let i = 0; i < count; i++) {
        const prevWord = findPrevWordAcrossLines(lines, startRow, startCol);
        if (prevWord) {
          startRow = prevWord.row;
          startCol = prevWord.col;
        } else {
          break;
        }
      }
      if (startRow !== cursorRow || startCol !== cursorCol) {
        const nextState = pushUndo(state);
        return replaceRangeInternal(
          nextState,
          startRow,
          startCol,
          cursorRow,
          cursorCol,
          ""
        );
      }
      return state;
    }
    case "vim_delete_word_end":
    case "vim_change_word_end": {
      const { count } = action.payload;
      let row = cursorRow;
      let col = cursorCol;
      let endRow = cursorRow;
      let endCol = cursorCol;
      for (let i = 0; i < count; i++) {
        const wordEnd = findNextWordAcrossLines(lines, row, col, false);
        if (wordEnd) {
          endRow = wordEnd.row;
          endCol = wordEnd.col + 1;
          if (i < count - 1) {
            const nextWord = findNextWordAcrossLines(
              lines,
              wordEnd.row,
              wordEnd.col + 1,
              true
            );
            if (nextWord) {
              row = nextWord.row;
              col = nextWord.col;
            } else {
              break;
            }
          }
        } else {
          break;
        }
      }
      if (endRow < lines.length) {
        const lineLen = cpLen(lines[endRow] || "");
        endCol = Math.min(endCol, lineLen);
      }
      if (endRow !== cursorRow || endCol !== cursorCol) {
        const nextState = pushUndo(state);
        return replaceRangeInternal(
          nextState,
          cursorRow,
          cursorCol,
          endRow,
          endCol,
          ""
        );
      }
      return state;
    }
    case "vim_delete_line": {
      const { count } = action.payload;
      if (lines.length === 0) return state;
      const linesToDelete = Math.min(count, lines.length - cursorRow);
      const totalLines = lines.length;
      if (totalLines === 1 || linesToDelete >= totalLines) {
        const nextState2 = pushUndo(state);
        return {
          ...nextState2,
          lines: [""],
          cursorRow: 0,
          cursorCol: 0,
          preferredCol: null
        };
      }
      const nextState = pushUndo(state);
      const newLines = [...nextState.lines];
      newLines.splice(cursorRow, linesToDelete);
      const newCursorRow = Math.min(cursorRow, newLines.length - 1);
      const newCursorCol = 0;
      return {
        ...nextState,
        lines: newLines,
        cursorRow: newCursorRow,
        cursorCol: newCursorCol,
        preferredCol: null
      };
    }
    case "vim_change_line": {
      const { count } = action.payload;
      if (lines.length === 0) return state;
      const linesToChange = Math.min(count, lines.length - cursorRow);
      const nextState = pushUndo(state);
      const { startOffset, endOffset } = getLineRangeOffsets(
        cursorRow,
        linesToChange,
        nextState.lines
      );
      const { startRow, startCol, endRow, endCol } = getPositionFromOffsets(
        startOffset,
        endOffset,
        nextState.lines
      );
      return replaceRangeInternal(
        nextState,
        startRow,
        startCol,
        endRow,
        endCol,
        ""
      );
    }
    case "vim_delete_to_end_of_line":
    case "vim_change_to_end_of_line": {
      const currentLine = lines[cursorRow] || "";
      if (cursorCol < cpLen(currentLine)) {
        const nextState = pushUndo(state);
        return replaceRangeInternal(
          nextState,
          cursorRow,
          cursorCol,
          cursorRow,
          cpLen(currentLine),
          ""
        );
      }
      return state;
    }
    case "vim_change_movement": {
      const { movement, count } = action.payload;
      const totalLines = lines.length;
      switch (movement) {
        case "h": {
          const startCol = Math.max(0, cursorCol - count);
          return replaceRangeInternal(
            pushUndo(state),
            cursorRow,
            startCol,
            cursorRow,
            cursorCol,
            ""
          );
        }
        case "j": {
          const linesToChange = Math.min(count, totalLines - cursorRow);
          if (linesToChange > 0) {
            if (totalLines === 1) {
              const currentLine = state.lines[0] || "";
              return replaceRangeInternal(
                pushUndo(state),
                0,
                0,
                0,
                cpLen(currentLine),
                ""
              );
            } else {
              const nextState = pushUndo(state);
              const { startOffset, endOffset } = getLineRangeOffsets(
                cursorRow,
                linesToChange,
                nextState.lines
              );
              const { startRow, startCol, endRow, endCol } = getPositionFromOffsets(startOffset, endOffset, nextState.lines);
              return replaceRangeInternal(
                nextState,
                startRow,
                startCol,
                endRow,
                endCol,
                ""
              );
            }
          }
          return state;
        }
        case "k": {
          const upLines = Math.min(count, cursorRow + 1);
          if (upLines > 0) {
            if (state.lines.length === 1) {
              const currentLine = state.lines[0] || "";
              return replaceRangeInternal(
                pushUndo(state),
                0,
                0,
                0,
                cpLen(currentLine),
                ""
              );
            } else {
              const startRow = Math.max(0, cursorRow - count + 1);
              const linesToChange = cursorRow - startRow + 1;
              const nextState = pushUndo(state);
              const { startOffset, endOffset } = getLineRangeOffsets(
                startRow,
                linesToChange,
                nextState.lines
              );
              const {
                startRow: newStartRow,
                startCol,
                endRow,
                endCol
              } = getPositionFromOffsets(
                startOffset,
                endOffset,
                nextState.lines
              );
              const resultState = replaceRangeInternal(
                nextState,
                newStartRow,
                startCol,
                endRow,
                endCol,
                ""
              );
              return {
                ...resultState,
                cursorRow: startRow,
                cursorCol: 0
              };
            }
          }
          return state;
        }
        case "l": {
          return replaceRangeInternal(
            pushUndo(state),
            cursorRow,
            cursorCol,
            cursorRow,
            Math.min(cpLen(lines[cursorRow] || ""), cursorCol + count),
            ""
          );
        }
        default:
          return state;
      }
    }
    case "vim_move_left": {
      const { count } = action.payload;
      const { cursorRow: cursorRow2, cursorCol: cursorCol2, lines: lines2 } = state;
      let newRow = cursorRow2;
      let newCol = cursorCol2;
      for (let i = 0; i < count; i++) {
        if (newCol > 0) {
          newCol--;
        } else if (newRow > 0) {
          newRow--;
          const prevLine = lines2[newRow] || "";
          const prevLineLength = cpLen(prevLine);
          newCol = prevLineLength === 0 ? 0 : prevLineLength - 1;
        }
      }
      return {
        ...state,
        cursorRow: newRow,
        cursorCol: newCol,
        preferredCol: null
      };
    }
    case "vim_move_right": {
      const { count } = action.payload;
      const { cursorRow: cursorRow2, cursorCol: cursorCol2, lines: lines2 } = state;
      let newRow = cursorRow2;
      let newCol = cursorCol2;
      for (let i = 0; i < count; i++) {
        const currentLine = lines2[newRow] || "";
        const lineLength = cpLen(currentLine);
        if (lineLength === 0) {
          if (newRow < lines2.length - 1) {
            newRow++;
            newCol = 0;
          }
        } else if (newCol < lineLength - 1) {
          newCol++;
          const currentLinePoints = toCodePoints(currentLine);
          while (newCol < currentLinePoints.length && isCombiningMark(currentLinePoints[newCol]) && newCol < lineLength - 1) {
            newCol++;
          }
        } else if (newRow < lines2.length - 1) {
          newRow++;
          newCol = 0;
        }
      }
      return {
        ...state,
        cursorRow: newRow,
        cursorCol: newCol,
        preferredCol: null
      };
    }
    case "vim_move_up": {
      const { count } = action.payload;
      const { cursorRow: cursorRow2, cursorCol: cursorCol2, lines: lines2 } = state;
      const newRow = Math.max(0, cursorRow2 - count);
      const targetLine = lines2[newRow] || "";
      const targetLineLength = cpLen(targetLine);
      const newCol = Math.min(
        cursorCol2,
        targetLineLength > 0 ? targetLineLength - 1 : 0
      );
      return {
        ...state,
        cursorRow: newRow,
        cursorCol: newCol,
        preferredCol: null
      };
    }
    case "vim_move_down": {
      const { count } = action.payload;
      const { cursorRow: cursorRow2, cursorCol: cursorCol2, lines: lines2 } = state;
      const newRow = Math.min(lines2.length - 1, cursorRow2 + count);
      const targetLine = lines2[newRow] || "";
      const targetLineLength = cpLen(targetLine);
      const newCol = Math.min(
        cursorCol2,
        targetLineLength > 0 ? targetLineLength - 1 : 0
      );
      return {
        ...state,
        cursorRow: newRow,
        cursorCol: newCol,
        preferredCol: null
      };
    }
    case "vim_move_word_forward": {
      const { count } = action.payload;
      let row = cursorRow;
      let col = cursorCol;
      for (let i = 0; i < count; i++) {
        const nextWord = findNextWordAcrossLines(lines, row, col, true);
        if (nextWord) {
          row = nextWord.row;
          col = nextWord.col;
        } else {
          break;
        }
      }
      return {
        ...state,
        cursorRow: row,
        cursorCol: col,
        preferredCol: null
      };
    }
    case "vim_move_word_backward": {
      const { count } = action.payload;
      let row = cursorRow;
      let col = cursorCol;
      for (let i = 0; i < count; i++) {
        const prevWord = findPrevWordAcrossLines(lines, row, col);
        if (prevWord) {
          row = prevWord.row;
          col = prevWord.col;
        } else {
          break;
        }
      }
      return {
        ...state,
        cursorRow: row,
        cursorCol: col,
        preferredCol: null
      };
    }
    case "vim_move_word_end": {
      const { count } = action.payload;
      let row = cursorRow;
      let col = cursorCol;
      for (let i = 0; i < count; i++) {
        if (i === 0) {
          const currentLine = lines[row] || "";
          const lineCodePoints = toCodePoints(currentLine);
          const atEndOfWord = col < lineCodePoints.length && isWordCharStrict(lineCodePoints[col]) && (col + 1 >= lineCodePoints.length || !isWordCharWithCombining(lineCodePoints[col + 1]) || // Or if we're on a base char followed only by combining marks until non-word
          isWordCharStrict(lineCodePoints[col]) && isAtEndOfBaseWord(lineCodePoints, col));
          if (atEndOfWord) {
            const nextWord = findNextWordAcrossLines(
              lines,
              row,
              col + 1,
              false
            );
            if (nextWord) {
              row = nextWord.row;
              col = nextWord.col;
              continue;
            }
          }
        }
        const wordEnd = findNextWordAcrossLines(lines, row, col, false);
        if (wordEnd) {
          row = wordEnd.row;
          col = wordEnd.col;
        } else {
          break;
        }
      }
      return {
        ...state,
        cursorRow: row,
        cursorCol: col,
        preferredCol: null
      };
    }
    case "vim_delete_char": {
      const { count } = action.payload;
      const { cursorRow: cursorRow2, cursorCol: cursorCol2, lines: lines2 } = state;
      const currentLine = lines2[cursorRow2] || "";
      const lineLength = cpLen(currentLine);
      if (cursorCol2 < lineLength) {
        const deleteCount = Math.min(count, lineLength - cursorCol2);
        const nextState = pushUndo(state);
        return replaceRangeInternal(
          nextState,
          cursorRow2,
          cursorCol2,
          cursorRow2,
          cursorCol2 + deleteCount,
          ""
        );
      }
      return state;
    }
    case "vim_insert_at_cursor": {
      return state;
    }
    case "vim_append_at_cursor": {
      const { cursorRow: cursorRow2, cursorCol: cursorCol2, lines: lines2 } = state;
      const currentLine = lines2[cursorRow2] || "";
      const newCol = cursorCol2 < cpLen(currentLine) ? cursorCol2 + 1 : cursorCol2;
      return {
        ...state,
        cursorCol: newCol,
        preferredCol: null
      };
    }
    case "vim_open_line_below": {
      const { cursorRow: cursorRow2, lines: lines2 } = state;
      const nextState = pushUndo(state);
      const endOfLine = cpLen(lines2[cursorRow2] || "");
      return replaceRangeInternal(
        nextState,
        cursorRow2,
        endOfLine,
        cursorRow2,
        endOfLine,
        "\n"
      );
    }
    case "vim_open_line_above": {
      const { cursorRow: cursorRow2 } = state;
      const nextState = pushUndo(state);
      const resultState = replaceRangeInternal(
        nextState,
        cursorRow2,
        0,
        cursorRow2,
        0,
        "\n"
      );
      return {
        ...resultState,
        cursorRow: cursorRow2,
        cursorCol: 0
      };
    }
    case "vim_append_at_line_end": {
      const { cursorRow: cursorRow2, lines: lines2 } = state;
      const lineLength = cpLen(lines2[cursorRow2] || "");
      return {
        ...state,
        cursorCol: lineLength,
        preferredCol: null
      };
    }
    case "vim_insert_at_line_start": {
      const { cursorRow: cursorRow2, lines: lines2 } = state;
      const currentLine = lines2[cursorRow2] || "";
      let col = 0;
      const lineCodePoints = toCodePoints(currentLine);
      while (col < lineCodePoints.length && /\s/.test(lineCodePoints[col])) {
        col++;
      }
      return {
        ...state,
        cursorCol: col,
        preferredCol: null
      };
    }
    case "vim_move_to_line_start": {
      return {
        ...state,
        cursorCol: 0,
        preferredCol: null
      };
    }
    case "vim_move_to_line_end": {
      const { cursorRow: cursorRow2, lines: lines2 } = state;
      const lineLength = cpLen(lines2[cursorRow2] || "");
      return {
        ...state,
        cursorCol: lineLength > 0 ? lineLength - 1 : 0,
        preferredCol: null
      };
    }
    case "vim_move_to_first_nonwhitespace": {
      const { cursorRow: cursorRow2, lines: lines2 } = state;
      const currentLine = lines2[cursorRow2] || "";
      let col = 0;
      const lineCodePoints = toCodePoints(currentLine);
      while (col < lineCodePoints.length && /\s/.test(lineCodePoints[col])) {
        col++;
      }
      return {
        ...state,
        cursorCol: col,
        preferredCol: null
      };
    }
    case "vim_move_to_first_line": {
      return {
        ...state,
        cursorRow: 0,
        cursorCol: 0,
        preferredCol: null
      };
    }
    case "vim_move_to_last_line": {
      const { lines: lines2 } = state;
      const lastRow = lines2.length - 1;
      return {
        ...state,
        cursorRow: lastRow,
        cursorCol: 0,
        preferredCol: null
      };
    }
    case "vim_move_to_line": {
      const { lineNumber } = action.payload;
      const { lines: lines2 } = state;
      const targetRow = Math.min(Math.max(0, lineNumber - 1), lines2.length - 1);
      return {
        ...state,
        cursorRow: targetRow,
        cursorCol: 0,
        preferredCol: null
      };
    }
    case "vim_escape_insert_mode": {
      const { cursorCol: cursorCol2 } = state;
      const newCol = cursorCol2 > 0 ? cursorCol2 - 1 : 0;
      return {
        ...state,
        cursorCol: newCol,
        preferredCol: null
      };
    }
    default: {
      assumeExhaustive(action);
      return state;
    }
  }
}
__name(handleVimAction, "handleVimAction");

// packages/cli/src/ui/components/shared/text-buffer.ts
function isWordChar(ch) {
  if (ch === void 0) {
    return false;
  }
  return !/[\s,.;!?]/.test(ch);
}
__name(isWordChar, "isWordChar");
var isWordCharStrict = /* @__PURE__ */ __name((char) => /[\w\p{L}\p{N}]/u.test(char), "isWordCharStrict");
var isWhitespace4 = /* @__PURE__ */ __name((char) => /\s/.test(char), "isWhitespace");
var isCombiningMark = /* @__PURE__ */ __name((char) => new RegExp("\\p{M}", "u").test(char), "isCombiningMark");
var isWordCharWithCombining = /* @__PURE__ */ __name((char) => isWordCharStrict(char) || isCombiningMark(char), "isWordCharWithCombining");
var getCharScript = /* @__PURE__ */ __name((char) => {
  if (/[\p{Script=Latin}]/u.test(char)) return "latin";
  if (/[\p{Script=Han}]/u.test(char)) return "han";
  if (/[\p{Script=Arabic}]/u.test(char)) return "arabic";
  if (/[\p{Script=Hiragana}]/u.test(char)) return "hiragana";
  if (/[\p{Script=Katakana}]/u.test(char)) return "katakana";
  if (/[\p{Script=Cyrillic}]/u.test(char)) return "cyrillic";
  return "other";
}, "getCharScript");
var isDifferentScript = /* @__PURE__ */ __name((char1, char2) => {
  if (!isWordCharStrict(char1) || !isWordCharStrict(char2)) return false;
  return getCharScript(char1) !== getCharScript(char2);
}, "isDifferentScript");
var findNextWordStartInLine = /* @__PURE__ */ __name((line, col) => {
  const chars = toCodePoints(line);
  let i = col;
  if (i >= chars.length) return null;
  const currentChar = chars[i];
  if (isWordCharStrict(currentChar)) {
    while (i < chars.length && isWordCharWithCombining(chars[i])) {
      if (i + 1 < chars.length && isWordCharStrict(chars[i + 1]) && isDifferentScript(chars[i], chars[i + 1])) {
        i++;
        break;
      }
      i++;
    }
  } else if (!isWhitespace4(currentChar)) {
    while (i < chars.length && !isWordCharStrict(chars[i]) && !isWhitespace4(chars[i])) {
      i++;
    }
  }
  while (i < chars.length && isWhitespace4(chars[i])) {
    i++;
  }
  return i < chars.length ? i : null;
}, "findNextWordStartInLine");
var findPrevWordStartInLine = /* @__PURE__ */ __name((line, col) => {
  const chars = toCodePoints(line);
  let i = col;
  if (i <= 0) return null;
  i--;
  while (i >= 0 && isWhitespace4(chars[i])) {
    i--;
  }
  if (i < 0) return null;
  if (isWordCharStrict(chars[i])) {
    while (i >= 0 && isWordCharStrict(chars[i])) {
      if (i - 1 >= 0 && isWordCharStrict(chars[i - 1]) && isDifferentScript(chars[i], chars[i - 1])) {
        return i;
      }
      i--;
    }
    return i + 1;
  } else {
    while (i >= 0 && !isWordCharStrict(chars[i]) && !isWhitespace4(chars[i])) {
      i--;
    }
    return i + 1;
  }
}, "findPrevWordStartInLine");
var findWordEndInLine = /* @__PURE__ */ __name((line, col) => {
  const chars = toCodePoints(line);
  let i = col;
  const atEndOfWordChar = i < chars.length && isWordCharWithCombining(chars[i]) && (i + 1 >= chars.length || !isWordCharWithCombining(chars[i + 1]) || isWordCharStrict(chars[i]) && i + 1 < chars.length && isWordCharStrict(chars[i + 1]) && isDifferentScript(chars[i], chars[i + 1]));
  const atEndOfPunctuation = i < chars.length && !isWordCharWithCombining(chars[i]) && !isWhitespace4(chars[i]) && (i + 1 >= chars.length || isWhitespace4(chars[i + 1]) || isWordCharWithCombining(chars[i + 1]));
  if (atEndOfWordChar || atEndOfPunctuation) {
    i++;
    while (i < chars.length && isWhitespace4(chars[i])) {
      i++;
    }
  }
  if (i < chars.length && !isWordCharWithCombining(chars[i])) {
    while (i < chars.length && isWhitespace4(chars[i])) {
      i++;
    }
  }
  let foundWord = false;
  let lastBaseCharPos = -1;
  if (i < chars.length && isWordCharWithCombining(chars[i])) {
    while (i < chars.length && isWordCharWithCombining(chars[i])) {
      foundWord = true;
      if (isWordCharStrict(chars[i])) {
        lastBaseCharPos = i;
      }
      if (i + 1 < chars.length && isWordCharStrict(chars[i + 1]) && isDifferentScript(chars[i], chars[i + 1])) {
        i++;
        if (isWordCharStrict(chars[i - 1])) {
          lastBaseCharPos = i - 1;
        }
        break;
      }
      i++;
    }
  } else if (i < chars.length && !isWhitespace4(chars[i])) {
    while (i < chars.length && !isWordCharStrict(chars[i]) && !isWhitespace4(chars[i])) {
      foundWord = true;
      lastBaseCharPos = i;
      i++;
    }
  }
  if (foundWord && lastBaseCharPos >= col) {
    return lastBaseCharPos;
  }
  return null;
}, "findWordEndInLine");
var findNextWordAcrossLines = /* @__PURE__ */ __name((lines, cursorRow, cursorCol, searchForWordStart) => {
  const currentLine = lines[cursorRow] || "";
  const colInCurrentLine = searchForWordStart ? findNextWordStartInLine(currentLine, cursorCol) : findWordEndInLine(currentLine, cursorCol);
  if (colInCurrentLine !== null) {
    return { row: cursorRow, col: colInCurrentLine };
  }
  for (let row = cursorRow + 1; row < lines.length; row++) {
    const line = lines[row] || "";
    const chars = toCodePoints(line);
    if (chars.length === 0) {
      let hasWordsInLaterLines = false;
      for (let laterRow = row + 1; laterRow < lines.length; laterRow++) {
        const laterLine = lines[laterRow] || "";
        const laterChars = toCodePoints(laterLine);
        let firstNonWhitespace2 = 0;
        while (firstNonWhitespace2 < laterChars.length && isWhitespace4(laterChars[firstNonWhitespace2])) {
          firstNonWhitespace2++;
        }
        if (firstNonWhitespace2 < laterChars.length) {
          hasWordsInLaterLines = true;
          break;
        }
      }
      if (!hasWordsInLaterLines) {
        return { row, col: 0 };
      }
      continue;
    }
    let firstNonWhitespace = 0;
    while (firstNonWhitespace < chars.length && isWhitespace4(chars[firstNonWhitespace])) {
      firstNonWhitespace++;
    }
    if (firstNonWhitespace < chars.length) {
      if (searchForWordStart) {
        return { row, col: firstNonWhitespace };
      } else {
        const endCol = findWordEndInLine(line, firstNonWhitespace);
        if (endCol !== null) {
          return { row, col: endCol };
        }
      }
    }
  }
  return null;
}, "findNextWordAcrossLines");
var findPrevWordAcrossLines = /* @__PURE__ */ __name((lines, cursorRow, cursorCol) => {
  const currentLine = lines[cursorRow] || "";
  const colInCurrentLine = findPrevWordStartInLine(currentLine, cursorCol);
  if (colInCurrentLine !== null) {
    return { row: cursorRow, col: colInCurrentLine };
  }
  for (let row = cursorRow - 1; row >= 0; row--) {
    const line = lines[row] || "";
    const chars = toCodePoints(line);
    if (chars.length === 0) continue;
    let lastWordStart = chars.length;
    while (lastWordStart > 0 && isWhitespace4(chars[lastWordStart - 1])) {
      lastWordStart--;
    }
    if (lastWordStart > 0) {
      const wordStart = findPrevWordStartInLine(line, lastWordStart);
      if (wordStart !== null) {
        return { row, col: wordStart };
      }
    }
  }
  return null;
}, "findPrevWordAcrossLines");
var getPositionFromOffsets = /* @__PURE__ */ __name((startOffset, endOffset, lines) => {
  let offset = 0;
  let startRow = 0;
  let startCol = 0;
  let endRow = 0;
  let endCol = 0;
  for (let i = 0; i < lines.length; i++) {
    const lineLength = lines[i].length + 1;
    if (offset + lineLength > startOffset) {
      startRow = i;
      startCol = startOffset - offset;
      break;
    }
    offset += lineLength;
  }
  offset = 0;
  for (let i = 0; i < lines.length; i++) {
    const lineLength = lines[i].length + (i < lines.length - 1 ? 1 : 0);
    if (offset + lineLength >= endOffset) {
      endRow = i;
      endCol = endOffset - offset;
      break;
    }
    offset += lineLength;
  }
  return { startRow, startCol, endRow, endCol };
}, "getPositionFromOffsets");
var getLineRangeOffsets = /* @__PURE__ */ __name((startRow, lineCount, lines) => {
  let startOffset = 0;
  for (let i = 0; i < startRow; i++) {
    startOffset += lines[i].length + 1;
  }
  let endOffset = startOffset;
  for (let i = 0; i < lineCount; i++) {
    const lineIndex = startRow + i;
    if (lineIndex < lines.length) {
      endOffset += lines[lineIndex].length;
      if (lineIndex < lines.length - 1) {
        endOffset += 1;
      }
    }
  }
  return { startOffset, endOffset };
}, "getLineRangeOffsets");
var replaceRangeInternal = /* @__PURE__ */ __name((state, startRow, startCol, endRow, endCol, text) => {
  const currentLine = /* @__PURE__ */ __name((row) => state.lines[row] || "", "currentLine");
  const currentLineLen = /* @__PURE__ */ __name((row) => cpLen(currentLine(row)), "currentLineLen");
  const clamp2 = /* @__PURE__ */ __name((value, min, max) => Math.min(Math.max(value, min), max), "clamp");
  if (startRow > endRow || startRow === endRow && startCol > endCol || startRow < 0 || startCol < 0 || endRow >= state.lines.length || endRow < state.lines.length && endCol > currentLineLen(endRow)) {
    return state;
  }
  const newLines = [...state.lines];
  const sCol = clamp2(startCol, 0, currentLineLen(startRow));
  const eCol = clamp2(endCol, 0, currentLineLen(endRow));
  const prefix = cpSlice(currentLine(startRow), 0, sCol);
  const suffix = cpSlice(currentLine(endRow), eCol);
  const normalisedReplacement = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
  const replacementParts = normalisedReplacement.split("\n");
  const firstLine = prefix + replacementParts[0];
  if (replacementParts.length === 1) {
    newLines.splice(startRow, endRow - startRow + 1, firstLine + suffix);
  } else {
    const lastLine = replacementParts[replacementParts.length - 1] + suffix;
    const middleLines = replacementParts.slice(1, -1);
    newLines.splice(
      startRow,
      endRow - startRow + 1,
      firstLine,
      ...middleLines,
      lastLine
    );
  }
  const finalCursorRow = startRow + replacementParts.length - 1;
  const finalCursorCol = (replacementParts.length > 1 ? 0 : sCol) + cpLen(replacementParts[replacementParts.length - 1]);
  return {
    ...state,
    lines: newLines,
    cursorRow: Math.min(Math.max(finalCursorRow, 0), newLines.length - 1),
    cursorCol: Math.max(
      0,
      Math.min(finalCursorCol, cpLen(newLines[finalCursorRow] || ""))
    ),
    preferredCol: null
  };
}, "replaceRangeInternal");
function clamp(v, min, max) {
  return v < min ? min : v > max ? max : v;
}
__name(clamp, "clamp");
function calculateInitialCursorPosition(initialLines, offset) {
  let remainingChars = offset;
  let row = 0;
  while (row < initialLines.length) {
    const lineLength = cpLen(initialLines[row]);
    const totalCharsInLineAndNewline = lineLength + (row < initialLines.length - 1 ? 1 : 0);
    if (remainingChars <= lineLength) {
      return [row, remainingChars];
    }
    remainingChars -= totalCharsInLineAndNewline;
    row++;
  }
  if (initialLines.length > 0) {
    const lastRow = initialLines.length - 1;
    return [lastRow, cpLen(initialLines[lastRow])];
  }
  return [0, 0];
}
__name(calculateInitialCursorPosition, "calculateInitialCursorPosition");
function offsetToLogicalPos(text, offset) {
  let row = 0;
  let col = 0;
  let currentOffset = 0;
  if (offset === 0) return [0, 0];
  const lines = text.split("\n");
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const lineLength = cpLen(line);
    const lineLengthWithNewline = lineLength + (i < lines.length - 1 ? 1 : 0);
    if (offset <= currentOffset + lineLength) {
      row = i;
      col = offset - currentOffset;
      return [row, col];
    } else if (offset <= currentOffset + lineLengthWithNewline) {
      row = i;
      col = lineLength;
      if (offset === currentOffset + lineLengthWithNewline && i < lines.length - 1) {
        return [i + 1, 0];
      }
      return [row, col];
    }
    currentOffset += lineLengthWithNewline;
  }
  if (lines.length > 0) {
    row = lines.length - 1;
    col = cpLen(lines[row]);
  } else {
    row = 0;
    col = 0;
  }
  return [row, col];
}
__name(offsetToLogicalPos, "offsetToLogicalPos");
function logicalPosToOffset(lines, row, col) {
  let offset = 0;
  const actualRow = Math.min(row, lines.length - 1);
  for (let i = 0; i < actualRow; i++) {
    offset += cpLen(lines[i]) + 1;
  }
  if (actualRow >= 0 && actualRow < lines.length) {
    offset += Math.min(col, cpLen(lines[actualRow]));
  }
  return offset;
}
__name(logicalPosToOffset, "logicalPosToOffset");
function calculateLayout(logicalLines, viewportWidth) {
  const visualLines = [];
  const logicalToVisualMap = [];
  const visualToLogicalMap = [];
  logicalLines.forEach((logLine, logIndex) => {
    logicalToVisualMap[logIndex] = [];
    if (logLine.length === 0) {
      logicalToVisualMap[logIndex].push([visualLines.length, 0]);
      visualToLogicalMap.push([logIndex, 0]);
      visualLines.push("");
    } else {
      let currentPosInLogLine = 0;
      const codePointsInLogLine = toCodePoints(logLine);
      while (currentPosInLogLine < codePointsInLogLine.length) {
        let currentChunk = "";
        let currentChunkVisualWidth = 0;
        let numCodePointsInChunk = 0;
        let lastWordBreakPoint = -1;
        let numCodePointsAtLastWordBreak = 0;
        for (let i = currentPosInLogLine; i < codePointsInLogLine.length; i++) {
          const char = codePointsInLogLine[i];
          const charVisualWidth = getCachedStringWidth(char);
          if (currentChunkVisualWidth + charVisualWidth > viewportWidth) {
            if (lastWordBreakPoint !== -1 && numCodePointsAtLastWordBreak > 0 && currentPosInLogLine + numCodePointsAtLastWordBreak < i) {
              currentChunk = codePointsInLogLine.slice(
                currentPosInLogLine,
                currentPosInLogLine + numCodePointsAtLastWordBreak
              ).join("");
              numCodePointsInChunk = numCodePointsAtLastWordBreak;
            } else {
              if (numCodePointsInChunk === 0 && charVisualWidth > viewportWidth) {
                currentChunk = char;
                numCodePointsInChunk = 1;
              } else if (numCodePointsInChunk === 0 && charVisualWidth <= viewportWidth) {
              }
            }
            break;
          }
          currentChunk += char;
          currentChunkVisualWidth += charVisualWidth;
          numCodePointsInChunk++;
          if (char === " ") {
            lastWordBreakPoint = i;
            numCodePointsAtLastWordBreak = numCodePointsInChunk - 1;
          }
        }
        if (numCodePointsInChunk === 0 && currentPosInLogLine < codePointsInLogLine.length) {
          const firstChar = codePointsInLogLine[currentPosInLogLine];
          currentChunk = firstChar;
          numCodePointsInChunk = 1;
        }
        if (numCodePointsInChunk === 0 && currentPosInLogLine < codePointsInLogLine.length) {
          currentChunk = codePointsInLogLine[currentPosInLogLine];
          numCodePointsInChunk = 1;
        }
        logicalToVisualMap[logIndex].push([
          visualLines.length,
          currentPosInLogLine
        ]);
        visualToLogicalMap.push([logIndex, currentPosInLogLine]);
        visualLines.push(currentChunk);
        const logicalStartOfThisChunk = currentPosInLogLine;
        currentPosInLogLine += numCodePointsInChunk;
        if (logicalStartOfThisChunk + numCodePointsInChunk < codePointsInLogLine.length && currentPosInLogLine < codePointsInLogLine.length && // Redundant if previous is true, but safe
        codePointsInLogLine[currentPosInLogLine] === " ") {
          currentPosInLogLine++;
        }
      }
    }
  });
  if (logicalLines.length === 0 || logicalLines.length === 1 && logicalLines[0] === "") {
    if (visualLines.length === 0) {
      visualLines.push("");
      if (!logicalToVisualMap[0]) logicalToVisualMap[0] = [];
      logicalToVisualMap[0].push([0, 0]);
      visualToLogicalMap.push([0, 0]);
    }
  }
  return {
    visualLines,
    logicalToVisualMap,
    visualToLogicalMap
  };
}
__name(calculateLayout, "calculateLayout");
function calculateVisualCursorFromLayout(layout, logicalCursor) {
  const { logicalToVisualMap, visualLines } = layout;
  const [logicalRow, logicalCol] = logicalCursor;
  const segmentsForLogicalLine = logicalToVisualMap[logicalRow];
  if (!segmentsForLogicalLine || segmentsForLogicalLine.length === 0) {
    return [0, 0];
  }
  let targetSegmentIndex = segmentsForLogicalLine.findIndex(
    ([, startColInLogical2], index) => {
      const nextStartColInLogical = index + 1 < segmentsForLogicalLine.length ? segmentsForLogicalLine[index + 1][1] : Infinity;
      return logicalCol >= startColInLogical2 && logicalCol < nextStartColInLogical;
    }
  );
  if (targetSegmentIndex === -1) {
    if (logicalCol === 0) {
      targetSegmentIndex = 0;
    } else {
      targetSegmentIndex = segmentsForLogicalLine.length - 1;
    }
  }
  const [visualRow, startColInLogical] = segmentsForLogicalLine[targetSegmentIndex];
  const visualCol = logicalCol - startColInLogical;
  const clampedVisualCol = Math.min(
    visualCol,
    cpLen(visualLines[visualRow] ?? "")
  );
  return [visualRow, clampedVisualCol];
}
__name(calculateVisualCursorFromLayout, "calculateVisualCursorFromLayout");
var historyLimit = 100;
var pushUndo = /* @__PURE__ */ __name((currentState) => {
  const snapshot = {
    lines: [...currentState.lines],
    cursorRow: currentState.cursorRow,
    cursorCol: currentState.cursorCol
  };
  const newStack = [...currentState.undoStack, snapshot];
  if (newStack.length > historyLimit) {
    newStack.shift();
  }
  return { ...currentState, undoStack: newStack, redoStack: [] };
}, "pushUndo");
function textBufferReducerLogic(state, action) {
  const pushUndoLocal = pushUndo;
  const currentLine = /* @__PURE__ */ __name((r3) => state.lines[r3] ?? "", "currentLine");
  const currentLineLen = /* @__PURE__ */ __name((r3) => cpLen(currentLine(r3)), "currentLineLen");
  switch (action.type) {
    case "set_text": {
      let nextState = state;
      if (action.pushToUndo !== false) {
        nextState = pushUndoLocal(state);
      }
      const newContentLines = action.payload.replace(/\r\n?/g, "\n").split("\n");
      const lines = newContentLines.length === 0 ? [""] : newContentLines;
      const lastNewLineIndex = lines.length - 1;
      return {
        ...nextState,
        lines,
        cursorRow: lastNewLineIndex,
        cursorCol: cpLen(lines[lastNewLineIndex] ?? ""),
        preferredCol: null
      };
    }
    case "insert": {
      const nextState = pushUndoLocal(state);
      const newLines = [...nextState.lines];
      let newCursorRow = nextState.cursorRow;
      let newCursorCol = nextState.cursorCol;
      const currentLine2 = /* @__PURE__ */ __name((r3) => newLines[r3] ?? "", "currentLine");
      const str2 = stripUnsafeCharacters(
        action.payload.replace(/\r\n/g, "\n").replace(/\r/g, "\n")
      );
      const parts = str2.split("\n");
      const lineContent = currentLine2(newCursorRow);
      const before = cpSlice(lineContent, 0, newCursorCol);
      const after = cpSlice(lineContent, newCursorCol);
      if (parts.length > 1) {
        newLines[newCursorRow] = before + parts[0];
        const remainingParts = parts.slice(1);
        const lastPartOriginal = remainingParts.pop() ?? "";
        newLines.splice(newCursorRow + 1, 0, ...remainingParts);
        newLines.splice(
          newCursorRow + parts.length - 1,
          0,
          lastPartOriginal + after
        );
        newCursorRow = newCursorRow + parts.length - 1;
        newCursorCol = cpLen(lastPartOriginal);
      } else {
        newLines[newCursorRow] = before + parts[0] + after;
        newCursorCol = cpLen(before) + cpLen(parts[0]);
      }
      return {
        ...nextState,
        lines: newLines,
        cursorRow: newCursorRow,
        cursorCol: newCursorCol,
        preferredCol: null
      };
    }
    case "backspace": {
      const nextState = pushUndoLocal(state);
      const newLines = [...nextState.lines];
      let newCursorRow = nextState.cursorRow;
      let newCursorCol = nextState.cursorCol;
      const currentLine2 = /* @__PURE__ */ __name((r3) => newLines[r3] ?? "", "currentLine");
      if (newCursorCol === 0 && newCursorRow === 0) return state;
      if (newCursorCol > 0) {
        const lineContent = currentLine2(newCursorRow);
        newLines[newCursorRow] = cpSlice(lineContent, 0, newCursorCol - 1) + cpSlice(lineContent, newCursorCol);
        newCursorCol--;
      } else if (newCursorRow > 0) {
        const prevLineContent = currentLine2(newCursorRow - 1);
        const currentLineContentVal = currentLine2(newCursorRow);
        const newCol = cpLen(prevLineContent);
        newLines[newCursorRow - 1] = prevLineContent + currentLineContentVal;
        newLines.splice(newCursorRow, 1);
        newCursorRow--;
        newCursorCol = newCol;
      }
      return {
        ...nextState,
        lines: newLines,
        cursorRow: newCursorRow,
        cursorCol: newCursorCol,
        preferredCol: null
      };
    }
    case "set_viewport": {
      const { width, height } = action.payload;
      if (width === state.viewportWidth && height === state.viewportHeight) {
        return state;
      }
      return {
        ...state,
        viewportWidth: width,
        viewportHeight: height
      };
    }
    case "move": {
      const { dir } = action.payload;
      const { cursorRow, cursorCol, lines, visualLayout, preferredCol } = state;
      if (dir === "left" || dir === "right" || dir === "up" || dir === "down" || dir === "home" || dir === "end") {
        const visualCursor = calculateVisualCursorFromLayout(visualLayout, [
          cursorRow,
          cursorCol
        ]);
        const { visualLines, visualToLogicalMap } = visualLayout;
        let newVisualRow = visualCursor[0];
        let newVisualCol = visualCursor[1];
        let newPreferredCol = preferredCol;
        const currentVisLineLen = cpLen(visualLines[newVisualRow] ?? "");
        switch (dir) {
          case "left":
            newPreferredCol = null;
            if (newVisualCol > 0) {
              newVisualCol--;
            } else if (newVisualRow > 0) {
              newVisualRow--;
              newVisualCol = cpLen(visualLines[newVisualRow] ?? "");
            }
            break;
          case "right":
            newPreferredCol = null;
            if (newVisualCol < currentVisLineLen) {
              newVisualCol++;
            } else if (newVisualRow < visualLines.length - 1) {
              newVisualRow++;
              newVisualCol = 0;
            }
            break;
          case "up":
            if (newVisualRow > 0) {
              if (newPreferredCol === null) newPreferredCol = newVisualCol;
              newVisualRow--;
              newVisualCol = clamp(
                newPreferredCol,
                0,
                cpLen(visualLines[newVisualRow] ?? "")
              );
            }
            break;
          case "down":
            if (newVisualRow < visualLines.length - 1) {
              if (newPreferredCol === null) newPreferredCol = newVisualCol;
              newVisualRow++;
              newVisualCol = clamp(
                newPreferredCol,
                0,
                cpLen(visualLines[newVisualRow] ?? "")
              );
            }
            break;
          case "home":
            newPreferredCol = null;
            newVisualCol = 0;
            break;
          case "end":
            newPreferredCol = null;
            newVisualCol = currentVisLineLen;
            break;
          default: {
            const exhaustiveCheck = dir;
            console.error(
              `Unknown visual movement direction: ${exhaustiveCheck}`
            );
            return state;
          }
        }
        if (visualToLogicalMap[newVisualRow]) {
          const [logRow, logStartCol] = visualToLogicalMap[newVisualRow];
          return {
            ...state,
            cursorRow: logRow,
            cursorCol: clamp(
              logStartCol + newVisualCol,
              0,
              cpLen(lines[logRow] ?? "")
            ),
            preferredCol: newPreferredCol
          };
        }
        return state;
      }
      switch (dir) {
        case "wordLeft": {
          if (cursorCol === 0 && cursorRow === 0) return state;
          let newCursorRow = cursorRow;
          let newCursorCol = cursorCol;
          if (cursorCol === 0) {
            newCursorRow--;
            newCursorCol = cpLen(lines[newCursorRow] ?? "");
          } else {
            const lineContent = lines[cursorRow];
            const arr = toCodePoints(lineContent);
            let start = cursorCol;
            let onlySpaces = true;
            for (let i = 0; i < start; i++) {
              if (isWordChar(arr[i])) {
                onlySpaces = false;
                break;
              }
            }
            if (onlySpaces && start > 0) {
              start--;
            } else {
              while (start > 0 && !isWordChar(arr[start - 1])) start--;
              while (start > 0 && isWordChar(arr[start - 1])) start--;
            }
            newCursorCol = start;
          }
          return {
            ...state,
            cursorRow: newCursorRow,
            cursorCol: newCursorCol,
            preferredCol: null
          };
        }
        case "wordRight": {
          if (cursorRow === lines.length - 1 && cursorCol === cpLen(lines[cursorRow] ?? "")) {
            return state;
          }
          let newCursorRow = cursorRow;
          let newCursorCol = cursorCol;
          const lineContent = lines[cursorRow] ?? "";
          const arr = toCodePoints(lineContent);
          if (cursorCol >= arr.length) {
            newCursorRow++;
            newCursorCol = 0;
          } else {
            let end = cursorCol;
            while (end < arr.length && !isWordChar(arr[end])) end++;
            while (end < arr.length && isWordChar(arr[end])) end++;
            newCursorCol = end;
          }
          return {
            ...state,
            cursorRow: newCursorRow,
            cursorCol: newCursorCol,
            preferredCol: null
          };
        }
        default:
          return state;
      }
    }
    case "set_cursor": {
      return {
        ...state,
        ...action.payload
      };
    }
    case "delete": {
      const { cursorRow, cursorCol, lines } = state;
      const lineContent = currentLine(cursorRow);
      if (cursorCol < currentLineLen(cursorRow)) {
        const nextState = pushUndoLocal(state);
        const newLines = [...nextState.lines];
        newLines[cursorRow] = cpSlice(lineContent, 0, cursorCol) + cpSlice(lineContent, cursorCol + 1);
        return {
          ...nextState,
          lines: newLines,
          preferredCol: null
        };
      } else if (cursorRow < lines.length - 1) {
        const nextState = pushUndoLocal(state);
        const nextLineContent = currentLine(cursorRow + 1);
        const newLines = [...nextState.lines];
        newLines[cursorRow] = lineContent + nextLineContent;
        newLines.splice(cursorRow + 1, 1);
        return {
          ...nextState,
          lines: newLines,
          preferredCol: null
        };
      }
      return state;
    }
    case "delete_word_left": {
      const { cursorRow, cursorCol } = state;
      if (cursorCol === 0 && cursorRow === 0) return state;
      const nextState = pushUndoLocal(state);
      const newLines = [...nextState.lines];
      let newCursorRow = cursorRow;
      let newCursorCol = cursorCol;
      if (newCursorCol > 0) {
        const lineContent = currentLine(newCursorRow);
        const prevWordStart = findPrevWordStartInLine(
          lineContent,
          newCursorCol
        );
        const start = prevWordStart === null ? 0 : prevWordStart;
        newLines[newCursorRow] = cpSlice(lineContent, 0, start) + cpSlice(lineContent, newCursorCol);
        newCursorCol = start;
      } else {
        const prevLineContent = currentLine(cursorRow - 1);
        const currentLineContentVal = currentLine(cursorRow);
        const newCol = cpLen(prevLineContent);
        newLines[cursorRow - 1] = prevLineContent + currentLineContentVal;
        newLines.splice(cursorRow, 1);
        newCursorRow--;
        newCursorCol = newCol;
      }
      return {
        ...nextState,
        lines: newLines,
        cursorRow: newCursorRow,
        cursorCol: newCursorCol,
        preferredCol: null
      };
    }
    case "delete_word_right": {
      const { cursorRow, cursorCol, lines } = state;
      const lineContent = currentLine(cursorRow);
      const lineLen = cpLen(lineContent);
      if (cursorCol >= lineLen && cursorRow === lines.length - 1) {
        return state;
      }
      const nextState = pushUndoLocal(state);
      const newLines = [...nextState.lines];
      if (cursorCol >= lineLen) {
        const nextLineContent = currentLine(cursorRow + 1);
        newLines[cursorRow] = lineContent + nextLineContent;
        newLines.splice(cursorRow + 1, 1);
      } else {
        const nextWordStart = findNextWordStartInLine(lineContent, cursorCol);
        const end = nextWordStart === null ? lineLen : nextWordStart;
        newLines[cursorRow] = cpSlice(lineContent, 0, cursorCol) + cpSlice(lineContent, end);
      }
      return {
        ...nextState,
        lines: newLines,
        preferredCol: null
      };
    }
    case "kill_line_right": {
      const { cursorRow, cursorCol, lines } = state;
      const lineContent = currentLine(cursorRow);
      if (cursorCol < currentLineLen(cursorRow)) {
        const nextState = pushUndoLocal(state);
        const newLines = [...nextState.lines];
        newLines[cursorRow] = cpSlice(lineContent, 0, cursorCol);
        return {
          ...nextState,
          lines: newLines
        };
      } else if (cursorRow < lines.length - 1) {
        const nextState = pushUndoLocal(state);
        const nextLineContent = currentLine(cursorRow + 1);
        const newLines = [...nextState.lines];
        newLines[cursorRow] = lineContent + nextLineContent;
        newLines.splice(cursorRow + 1, 1);
        return {
          ...nextState,
          lines: newLines,
          preferredCol: null
        };
      }
      return state;
    }
    case "kill_line_left": {
      const { cursorRow, cursorCol } = state;
      if (cursorCol > 0) {
        const nextState = pushUndoLocal(state);
        const lineContent = currentLine(cursorRow);
        const newLines = [...nextState.lines];
        newLines[cursorRow] = cpSlice(lineContent, cursorCol);
        return {
          ...nextState,
          lines: newLines,
          cursorCol: 0,
          preferredCol: null
        };
      }
      return state;
    }
    case "undo": {
      const stateToRestore = state.undoStack[state.undoStack.length - 1];
      if (!stateToRestore) return state;
      const currentSnapshot = {
        lines: [...state.lines],
        cursorRow: state.cursorRow,
        cursorCol: state.cursorCol
      };
      return {
        ...state,
        ...stateToRestore,
        undoStack: state.undoStack.slice(0, -1),
        redoStack: [...state.redoStack, currentSnapshot]
      };
    }
    case "redo": {
      const stateToRestore = state.redoStack[state.redoStack.length - 1];
      if (!stateToRestore) return state;
      const currentSnapshot = {
        lines: [...state.lines],
        cursorRow: state.cursorRow,
        cursorCol: state.cursorCol
      };
      return {
        ...state,
        ...stateToRestore,
        redoStack: state.redoStack.slice(0, -1),
        undoStack: [...state.undoStack, currentSnapshot]
      };
    }
    case "replace_range": {
      const { startRow, startCol, endRow, endCol, text } = action.payload;
      const nextState = pushUndoLocal(state);
      return replaceRangeInternal(
        nextState,
        startRow,
        startCol,
        endRow,
        endCol,
        text
      );
    }
    case "move_to_offset": {
      const { offset } = action.payload;
      const [newRow, newCol] = offsetToLogicalPos(
        state.lines.join("\n"),
        offset
      );
      return {
        ...state,
        cursorRow: newRow,
        cursorCol: newCol,
        preferredCol: null
      };
    }
    case "create_undo_snapshot": {
      return pushUndoLocal(state);
    }
    // Vim-specific operations
    case "vim_delete_word_forward":
    case "vim_delete_word_backward":
    case "vim_delete_word_end":
    case "vim_change_word_forward":
    case "vim_change_word_backward":
    case "vim_change_word_end":
    case "vim_delete_line":
    case "vim_change_line":
    case "vim_delete_to_end_of_line":
    case "vim_change_to_end_of_line":
    case "vim_change_movement":
    case "vim_move_left":
    case "vim_move_right":
    case "vim_move_up":
    case "vim_move_down":
    case "vim_move_word_forward":
    case "vim_move_word_backward":
    case "vim_move_word_end":
    case "vim_delete_char":
    case "vim_insert_at_cursor":
    case "vim_append_at_cursor":
    case "vim_open_line_below":
    case "vim_open_line_above":
    case "vim_append_at_line_end":
    case "vim_insert_at_line_start":
    case "vim_move_to_line_start":
    case "vim_move_to_line_end":
    case "vim_move_to_first_nonwhitespace":
    case "vim_move_to_first_line":
    case "vim_move_to_last_line":
    case "vim_move_to_line":
    case "vim_escape_insert_mode":
      return handleVimAction(state, action);
    default: {
      const exhaustiveCheck = action;
      console.error(`Unknown action encountered: ${exhaustiveCheck}`);
      return state;
    }
  }
}
__name(textBufferReducerLogic, "textBufferReducerLogic");
function textBufferReducer(state, action) {
  const newState = textBufferReducerLogic(state, action);
  if (newState.lines !== state.lines || newState.viewportWidth !== state.viewportWidth) {
    return {
      ...newState,
      visualLayout: calculateLayout(newState.lines, newState.viewportWidth)
    };
  }
  return newState;
}
__name(textBufferReducer, "textBufferReducer");
function useTextBuffer({
  initialText = "",
  initialCursorOffset = 0,
  viewport,
  stdin,
  setRawMode,
  onChange,
  isValidPath,
  shellModeActive = false
}) {
  const initialState2 = (0, import_react45.useMemo)(() => {
    const lines2 = initialText.split("\n");
    const [initialCursorRow, initialCursorCol] = calculateInitialCursorPosition(
      lines2.length === 0 ? [""] : lines2,
      initialCursorOffset
    );
    const visualLayout2 = calculateLayout(
      lines2.length === 0 ? [""] : lines2,
      viewport.width
    );
    return {
      lines: lines2.length === 0 ? [""] : lines2,
      cursorRow: initialCursorRow,
      cursorCol: initialCursorCol,
      preferredCol: null,
      undoStack: [],
      redoStack: [],
      clipboard: null,
      selectionAnchor: null,
      viewportWidth: viewport.width,
      viewportHeight: viewport.height,
      visualLayout: visualLayout2
    };
  }, [initialText, initialCursorOffset, viewport.width, viewport.height]);
  const [state, dispatch] = (0, import_react45.useReducer)(textBufferReducer, initialState2);
  const {
    lines,
    cursorRow,
    cursorCol,
    preferredCol,
    selectionAnchor,
    visualLayout
  } = state;
  const text = (0, import_react45.useMemo)(() => lines.join("\n"), [lines]);
  const visualCursor = (0, import_react45.useMemo)(
    () => calculateVisualCursorFromLayout(visualLayout, [cursorRow, cursorCol]),
    [visualLayout, cursorRow, cursorCol]
  );
  const { visualLines, visualToLogicalMap } = visualLayout;
  const [visualScrollRow, setVisualScrollRow] = (0, import_react45.useState)(0);
  (0, import_react45.useEffect)(() => {
    if (onChange) {
      onChange(text);
    }
  }, [text, onChange]);
  (0, import_react45.useEffect)(() => {
    dispatch({
      type: "set_viewport",
      payload: { width: viewport.width, height: viewport.height }
    });
  }, [viewport.width, viewport.height]);
  (0, import_react45.useEffect)(() => {
    const { height } = viewport;
    const totalVisualLines = visualLines.length;
    const maxScrollStart = Math.max(0, totalVisualLines - height);
    let newVisualScrollRow = visualScrollRow;
    if (visualCursor[0] < visualScrollRow) {
      newVisualScrollRow = visualCursor[0];
    } else if (visualCursor[0] >= visualScrollRow + height) {
      newVisualScrollRow = visualCursor[0] - height + 1;
    }
    newVisualScrollRow = clamp(newVisualScrollRow, 0, maxScrollStart);
    if (newVisualScrollRow !== visualScrollRow) {
      setVisualScrollRow(newVisualScrollRow);
    }
  }, [visualCursor, visualScrollRow, viewport, visualLines.length]);
  const insert = (0, import_react45.useCallback)(
    (ch, { paste = false } = {}) => {
      if (/[\n\r]/.test(ch)) {
        dispatch({ type: "insert", payload: ch });
        return;
      }
      const minLengthToInferAsDragDrop = 3;
      if (ch.length >= minLengthToInferAsDragDrop && !shellModeActive && paste) {
        let potentialPath = ch.trim();
        const quoteMatch = potentialPath.match(/^'(.*)'$/);
        if (quoteMatch) {
          potentialPath = quoteMatch[1];
        }
        potentialPath = potentialPath.trim();
        if (isValidPath(unescapePath(potentialPath))) {
          ch = `@${potentialPath} `;
        }
      }
      let currentText = "";
      for (const char of toCodePoints(ch)) {
        if (char.codePointAt(0) === 127) {
          if (currentText.length > 0) {
            dispatch({ type: "insert", payload: currentText });
            currentText = "";
          }
          dispatch({ type: "backspace" });
        } else {
          currentText += char;
        }
      }
      if (currentText.length > 0) {
        dispatch({ type: "insert", payload: currentText });
      }
    },
    [isValidPath, shellModeActive]
  );
  const newline2 = (0, import_react45.useCallback)(() => {
    dispatch({ type: "insert", payload: "\n" });
  }, []);
  const backspace = (0, import_react45.useCallback)(() => {
    dispatch({ type: "backspace" });
  }, []);
  const del = (0, import_react45.useCallback)(() => {
    dispatch({ type: "delete" });
  }, []);
  const move = (0, import_react45.useCallback)(
    (dir) => {
      dispatch({ type: "move", payload: { dir } });
    },
    [dispatch]
  );
  const undo = (0, import_react45.useCallback)(() => {
    dispatch({ type: "undo" });
  }, []);
  const redo = (0, import_react45.useCallback)(() => {
    dispatch({ type: "redo" });
  }, []);
  const setText = (0, import_react45.useCallback)((newText) => {
    dispatch({ type: "set_text", payload: newText });
  }, []);
  const deleteWordLeft = (0, import_react45.useCallback)(() => {
    dispatch({ type: "delete_word_left" });
  }, []);
  const deleteWordRight = (0, import_react45.useCallback)(() => {
    dispatch({ type: "delete_word_right" });
  }, []);
  const killLineRight = (0, import_react45.useCallback)(() => {
    dispatch({ type: "kill_line_right" });
  }, []);
  const killLineLeft = (0, import_react45.useCallback)(() => {
    dispatch({ type: "kill_line_left" });
  }, []);
  const vimDeleteWordForward = (0, import_react45.useCallback)((count) => {
    dispatch({ type: "vim_delete_word_forward", payload: { count } });
  }, []);
  const vimDeleteWordBackward = (0, import_react45.useCallback)((count) => {
    dispatch({ type: "vim_delete_word_backward", payload: { count } });
  }, []);
  const vimDeleteWordEnd = (0, import_react45.useCallback)((count) => {
    dispatch({ type: "vim_delete_word_end", payload: { count } });
  }, []);
  const vimChangeWordForward = (0, import_react45.useCallback)((count) => {
    dispatch({ type: "vim_change_word_forward", payload: { count } });
  }, []);
  const vimChangeWordBackward = (0, import_react45.useCallback)((count) => {
    dispatch({ type: "vim_change_word_backward", payload: { count } });
  }, []);
  const vimChangeWordEnd = (0, import_react45.useCallback)((count) => {
    dispatch({ type: "vim_change_word_end", payload: { count } });
  }, []);
  const vimDeleteLine = (0, import_react45.useCallback)((count) => {
    dispatch({ type: "vim_delete_line", payload: { count } });
  }, []);
  const vimChangeLine = (0, import_react45.useCallback)((count) => {
    dispatch({ type: "vim_change_line", payload: { count } });
  }, []);
  const vimDeleteToEndOfLine = (0, import_react45.useCallback)(() => {
    dispatch({ type: "vim_delete_to_end_of_line" });
  }, []);
  const vimChangeToEndOfLine = (0, import_react45.useCallback)(() => {
    dispatch({ type: "vim_change_to_end_of_line" });
  }, []);
  const vimChangeMovement = (0, import_react45.useCallback)(
    (movement, count) => {
      dispatch({ type: "vim_change_movement", payload: { movement, count } });
    },
    []
  );
  const vimMoveLeft = (0, import_react45.useCallback)((count) => {
    dispatch({ type: "vim_move_left", payload: { count } });
  }, []);
  const vimMoveRight = (0, import_react45.useCallback)((count) => {
    dispatch({ type: "vim_move_right", payload: { count } });
  }, []);
  const vimMoveUp = (0, import_react45.useCallback)((count) => {
    dispatch({ type: "vim_move_up", payload: { count } });
  }, []);
  const vimMoveDown = (0, import_react45.useCallback)((count) => {
    dispatch({ type: "vim_move_down", payload: { count } });
  }, []);
  const vimMoveWordForward = (0, import_react45.useCallback)((count) => {
    dispatch({ type: "vim_move_word_forward", payload: { count } });
  }, []);
  const vimMoveWordBackward = (0, import_react45.useCallback)((count) => {
    dispatch({ type: "vim_move_word_backward", payload: { count } });
  }, []);
  const vimMoveWordEnd = (0, import_react45.useCallback)((count) => {
    dispatch({ type: "vim_move_word_end", payload: { count } });
  }, []);
  const vimDeleteChar = (0, import_react45.useCallback)((count) => {
    dispatch({ type: "vim_delete_char", payload: { count } });
  }, []);
  const vimInsertAtCursor = (0, import_react45.useCallback)(() => {
    dispatch({ type: "vim_insert_at_cursor" });
  }, []);
  const vimAppendAtCursor = (0, import_react45.useCallback)(() => {
    dispatch({ type: "vim_append_at_cursor" });
  }, []);
  const vimOpenLineBelow = (0, import_react45.useCallback)(() => {
    dispatch({ type: "vim_open_line_below" });
  }, []);
  const vimOpenLineAbove = (0, import_react45.useCallback)(() => {
    dispatch({ type: "vim_open_line_above" });
  }, []);
  const vimAppendAtLineEnd = (0, import_react45.useCallback)(() => {
    dispatch({ type: "vim_append_at_line_end" });
  }, []);
  const vimInsertAtLineStart = (0, import_react45.useCallback)(() => {
    dispatch({ type: "vim_insert_at_line_start" });
  }, []);
  const vimMoveToLineStart = (0, import_react45.useCallback)(() => {
    dispatch({ type: "vim_move_to_line_start" });
  }, []);
  const vimMoveToLineEnd = (0, import_react45.useCallback)(() => {
    dispatch({ type: "vim_move_to_line_end" });
  }, []);
  const vimMoveToFirstNonWhitespace = (0, import_react45.useCallback)(() => {
    dispatch({ type: "vim_move_to_first_nonwhitespace" });
  }, []);
  const vimMoveToFirstLine = (0, import_react45.useCallback)(() => {
    dispatch({ type: "vim_move_to_first_line" });
  }, []);
  const vimMoveToLastLine = (0, import_react45.useCallback)(() => {
    dispatch({ type: "vim_move_to_last_line" });
  }, []);
  const vimMoveToLine = (0, import_react45.useCallback)((lineNumber) => {
    dispatch({ type: "vim_move_to_line", payload: { lineNumber } });
  }, []);
  const vimEscapeInsertMode = (0, import_react45.useCallback)(() => {
    dispatch({ type: "vim_escape_insert_mode" });
  }, []);
  const openInExternalEditor = (0, import_react45.useCallback)(
    async (opts = {}) => {
      const editor = opts.editor ?? process.env["VISUAL"] ?? process.env["EDITOR"] ?? (process.platform === "win32" ? "notepad" : "vi");
      const tmpDir = fs54.mkdtempSync(pathMod.join(os24.tmpdir(), "gemini-edit-"));
      const filePath = pathMod.join(tmpDir, "buffer.txt");
      fs54.writeFileSync(filePath, text, "utf8");
      dispatch({ type: "create_undo_snapshot" });
      const wasRaw = stdin?.isRaw ?? false;
      try {
        setRawMode?.(false);
        const { status, error } = spawnSync3(editor, [filePath], {
          stdio: "inherit"
        });
        if (error) throw error;
        if (typeof status === "number" && status !== 0)
          throw new Error(`External editor exited with status ${status}`);
        let newText = fs54.readFileSync(filePath, "utf8");
        newText = newText.replace(/\r\n?/g, "\n");
        dispatch({ type: "set_text", payload: newText, pushToUndo: false });
      } catch (err) {
        console.error("[useTextBuffer] external editor error", err);
      } finally {
        if (wasRaw) setRawMode?.(true);
        try {
          fs54.unlinkSync(filePath);
        } catch {
        }
        try {
          fs54.rmdirSync(tmpDir);
        } catch {
        }
      }
    },
    [text, stdin, setRawMode]
  );
  const handleInput = (0, import_react45.useCallback)(
    (key) => {
      const { sequence: input } = key;
      if (key.paste) {
        insert(input, { paste: key.paste });
        return;
      }
      if (key.name === "return" || input === "\r" || input === "\n" || input === "\\\r")
        newline2();
      else if (key.name === "left" && !key.meta && !key.ctrl) move("left");
      else if (key.ctrl && key.name === "b") move("left");
      else if (key.name === "right" && !key.meta && !key.ctrl) move("right");
      else if (key.ctrl && key.name === "f") move("right");
      else if (key.name === "up") move("up");
      else if (key.name === "down") move("down");
      else if ((key.ctrl || key.meta) && key.name === "left") move("wordLeft");
      else if (key.meta && key.name === "b") move("wordLeft");
      else if ((key.ctrl || key.meta) && key.name === "right")
        move("wordRight");
      else if (key.meta && key.name === "f") move("wordRight");
      else if (key.name === "home") move("home");
      else if (key.ctrl && key.name === "a") move("home");
      else if (key.name === "end") move("end");
      else if (key.ctrl && key.name === "e") move("end");
      else if (key.ctrl && key.name === "w") deleteWordLeft();
      else if ((key.meta || key.ctrl) && (key.name === "backspace" || input === "\x7F"))
        deleteWordLeft();
      else if ((key.meta || key.ctrl) && key.name === "delete")
        deleteWordRight();
      else if (key.name === "backspace" || input === "\x7F" || key.ctrl && key.name === "h")
        backspace();
      else if (key.name === "delete" || key.ctrl && key.name === "d") del();
      else if (key.ctrl && !key.shift && key.name === "z") undo();
      else if (key.ctrl && key.shift && key.name === "z") redo();
      else if (input && !key.ctrl && !key.meta) {
        insert(input, { paste: key.paste });
      }
    },
    [
      newline2,
      move,
      deleteWordLeft,
      deleteWordRight,
      backspace,
      del,
      insert,
      undo,
      redo
    ]
  );
  const renderedVisualLines = (0, import_react45.useMemo)(
    () => visualLines.slice(visualScrollRow, visualScrollRow + viewport.height),
    [visualLines, visualScrollRow, viewport.height]
  );
  const replaceRange = (0, import_react45.useCallback)(
    (startRow, startCol, endRow, endCol, text2) => {
      dispatch({
        type: "replace_range",
        payload: { startRow, startCol, endRow, endCol, text: text2 }
      });
    },
    []
  );
  const replaceRangeByOffset = (0, import_react45.useCallback)(
    (startOffset, endOffset, replacementText) => {
      const [startRow, startCol] = offsetToLogicalPos(text, startOffset);
      const [endRow, endCol] = offsetToLogicalPos(text, endOffset);
      replaceRange(startRow, startCol, endRow, endCol, replacementText);
    },
    [text, replaceRange]
  );
  const moveToOffset = (0, import_react45.useCallback)((offset) => {
    dispatch({ type: "move_to_offset", payload: { offset } });
  }, []);
  const returnValue = (0, import_react45.useMemo)(
    () => ({
      lines,
      text,
      cursor: [cursorRow, cursorCol],
      preferredCol,
      selectionAnchor,
      allVisualLines: visualLines,
      viewportVisualLines: renderedVisualLines,
      visualCursor,
      visualScrollRow,
      visualToLogicalMap,
      setText,
      insert,
      newline: newline2,
      backspace,
      del,
      move,
      undo,
      redo,
      replaceRange,
      replaceRangeByOffset,
      moveToOffset,
      deleteWordLeft,
      deleteWordRight,
      killLineRight,
      killLineLeft,
      handleInput,
      openInExternalEditor,
      // Vim-specific operations
      vimDeleteWordForward,
      vimDeleteWordBackward,
      vimDeleteWordEnd,
      vimChangeWordForward,
      vimChangeWordBackward,
      vimChangeWordEnd,
      vimDeleteLine,
      vimChangeLine,
      vimDeleteToEndOfLine,
      vimChangeToEndOfLine,
      vimChangeMovement,
      vimMoveLeft,
      vimMoveRight,
      vimMoveUp,
      vimMoveDown,
      vimMoveWordForward,
      vimMoveWordBackward,
      vimMoveWordEnd,
      vimDeleteChar,
      vimInsertAtCursor,
      vimAppendAtCursor,
      vimOpenLineBelow,
      vimOpenLineAbove,
      vimAppendAtLineEnd,
      vimInsertAtLineStart,
      vimMoveToLineStart,
      vimMoveToLineEnd,
      vimMoveToFirstNonWhitespace,
      vimMoveToFirstLine,
      vimMoveToLastLine,
      vimMoveToLine,
      vimEscapeInsertMode
    }),
    [
      lines,
      text,
      cursorRow,
      cursorCol,
      preferredCol,
      selectionAnchor,
      visualLines,
      renderedVisualLines,
      visualCursor,
      visualScrollRow,
      setText,
      insert,
      newline2,
      backspace,
      del,
      move,
      undo,
      redo,
      replaceRange,
      replaceRangeByOffset,
      moveToOffset,
      deleteWordLeft,
      deleteWordRight,
      killLineRight,
      killLineLeft,
      handleInput,
      openInExternalEditor,
      vimDeleteWordForward,
      vimDeleteWordBackward,
      vimDeleteWordEnd,
      vimChangeWordForward,
      vimChangeWordBackward,
      vimChangeWordEnd,
      vimDeleteLine,
      vimChangeLine,
      vimDeleteToEndOfLine,
      vimChangeToEndOfLine,
      vimChangeMovement,
      vimMoveLeft,
      vimMoveRight,
      vimMoveUp,
      vimMoveDown,
      vimMoveWordForward,
      vimMoveWordBackward,
      vimMoveWordEnd,
      vimDeleteChar,
      vimInsertAtCursor,
      vimAppendAtCursor,
      vimOpenLineBelow,
      vimOpenLineAbove,
      vimAppendAtLineEnd,
      vimInsertAtLineStart,
      vimMoveToLineStart,
      vimMoveToLineEnd,
      vimMoveToFirstNonWhitespace,
      vimMoveToFirstLine,
      vimMoveToLastLine,
      vimMoveToLine,
      vimEscapeInsertMode,
      visualToLogicalMap
    ]
  );
  return returnValue;
}
__name(useTextBuffer, "useTextBuffer");

// packages/cli/src/ui/components/shared/TextInput.tsx
var import_react46 = __toESM(require_react(), 1);
var import_jsx_runtime21 = __toESM(require_jsx_runtime(), 1);
function TextInput({
  value,
  onChange,
  onSubmit,
  placeholder,
  height = 1,
  isActive = true,
  validationErrors = [],
  inputWidth = 80
}) {
  const allowMultiline = height > 1;
  const onChangeRef = (0, import_react46.useRef)(onChange);
  (0, import_react46.useEffect)(() => {
    onChangeRef.current = onChange;
  }, [onChange]);
  const stableOnChange = (0, import_react46.useCallback)((text) => {
    onChangeRef.current?.(text);
  }, []);
  const buffer = useTextBuffer({
    initialText: value || "",
    viewport: { height, width: inputWidth },
    isValidPath: /* @__PURE__ */ __name(() => false, "isValidPath"),
    onChange: stableOnChange
  });
  const handleSubmit = /* @__PURE__ */ __name(() => {
    if (!onSubmit) return;
    onSubmit();
  }, "handleSubmit");
  useKeypress(
    (key) => {
      if (!buffer || !isActive) return;
      if (keyMatchers["submit" /* SUBMIT */](key) || key.name === "return") {
        if (allowMultiline) {
          const [row, col] = buffer.cursor;
          const line = buffer.lines[row];
          const charBefore = col > 0 ? cpSlice(line, col - 1, col) : "";
          if (charBefore === "\\") {
            buffer.backspace();
            buffer.newline();
          } else {
            handleSubmit();
          }
        } else {
          handleSubmit();
        }
        return;
      }
      if (allowMultiline && keyMatchers["newline" /* NEWLINE */](key)) {
        buffer.newline();
        return;
      }
      if (keyMatchers["home" /* HOME */](key)) {
        buffer.move("home");
        return;
      }
      if (keyMatchers["end" /* END */](key)) {
        buffer.move("end");
        buffer.moveToOffset(cpLen(buffer.text));
        return;
      }
      if (keyMatchers["clearInput" /* CLEAR_INPUT */](key)) {
        if (buffer.text.length > 0) buffer.setText("");
        return;
      }
      if (keyMatchers["killLineRight" /* KILL_LINE_RIGHT */](key)) {
        buffer.killLineRight();
        return;
      }
      if (keyMatchers["killLineLeft" /* KILL_LINE_LEFT */](key)) {
        buffer.killLineLeft();
        return;
      }
      if (keyMatchers["openExternalEditor" /* OPEN_EXTERNAL_EDITOR */](key)) {
        buffer.openInExternalEditor();
        return;
      }
      buffer.handleInput(key);
    },
    { isActive }
  );
  if (!buffer) return null;
  const linesToRender = buffer.viewportVisualLines;
  const [cursorVisualRowAbsolute, cursorVisualColAbsolute] = buffer.visualCursor;
  const scrollVisualRow = buffer.visualScrollRow;
  return /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text, { color: theme.text.accent, children: "> " }),
      /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Box_default, { flexGrow: 1, flexDirection: "column", children: buffer.text.length === 0 && placeholder ? /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Text, { children: [
        import_chalk4.default.inverse(placeholder.slice(0, 1)),
        /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text, { color: Colors.Gray, children: placeholder.slice(1) })
      ] }) : linesToRender.map((lineText, visualIdxInRenderedSet) => {
        const cursorVisualRow = cursorVisualRowAbsolute - scrollVisualRow;
        let display = cpSlice(lineText, 0, inputWidth);
        const currentVisualWidth = stringWidth4(display);
        if (currentVisualWidth < inputWidth) {
          display = display + " ".repeat(inputWidth - currentVisualWidth);
        }
        if (visualIdxInRenderedSet === cursorVisualRow) {
          const relativeVisualColForHighlight = cursorVisualColAbsolute;
          if (relativeVisualColForHighlight >= 0) {
            if (relativeVisualColForHighlight < cpLen(display)) {
              const charToHighlight = cpSlice(
                display,
                relativeVisualColForHighlight,
                relativeVisualColForHighlight + 1
              ) || " ";
              const highlighted = import_chalk4.default.inverse(charToHighlight);
              display = cpSlice(display, 0, relativeVisualColForHighlight) + highlighted + cpSlice(display, relativeVisualColForHighlight + 1);
            } else if (relativeVisualColForHighlight === cpLen(display) && cpLen(display) === inputWidth) {
              display = display + import_chalk4.default.inverse(" ");
            }
          }
        }
        return /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text, { children: display }, `line-${visualIdxInRenderedSet}`);
      }) })
    ] }),
    validationErrors.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Box_default, { flexDirection: "column", children: validationErrors.map((error, index) => /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Text, { color: theme.status.error, children: [
      "\u26A0 ",
      error
    ] }, index)) })
  ] });
}
__name(TextInput, "TextInput");

// packages/cli/src/ui/components/subagents/create/DescriptionInput.tsx
var import_jsx_runtime22 = __toESM(require_jsx_runtime(), 1);
function DescriptionInput({
  state,
  dispatch,
  onNext,
  config
}) {
  const abortControllerRef = (0, import_react47.useRef)(null);
  const handleTextChange = (0, import_react47.useCallback)(
    (text) => {
      const sanitized = sanitizeInput(text);
      dispatch({
        type: "SET_USER_DESCRIPTION",
        description: sanitized
      });
    },
    [dispatch]
  );
  const handleGenerate = (0, import_react47.useCallback)(
    async (userDescription, dispatch2, config2) => {
      const abortController = new AbortController();
      abortControllerRef.current = abortController;
      try {
        const generated = await subagentGenerator(
          userDescription,
          config2,
          abortController.signal
        );
        if (!abortController.signal.aborted) {
          dispatch2({
            type: "SET_GENERATED_CONTENT",
            name: generated.name,
            description: generated.description,
            systemPrompt: generated.systemPrompt
          });
          onNext();
        }
      } finally {
        abortControllerRef.current = null;
      }
    },
    [onNext]
  );
  const handleSubmit = (0, import_react47.useCallback)(async () => {
    if (!state.canProceed || state.isGenerating) {
      return;
    }
    const inputValue = state.userDescription.trim();
    if (!inputValue) {
      return;
    }
    dispatch({ type: "SET_GENERATING", isGenerating: true });
    try {
      if (!config) {
        throw new Error("Configuration not available");
      }
      await handleGenerate(inputValue, dispatch, config);
    } catch (error) {
      dispatch({ type: "SET_GENERATING", isGenerating: false });
      if (error instanceof Error && error.name === "AbortError") {
        return;
      }
      dispatch({
        type: "SET_VALIDATION_ERRORS",
        errors: [
          `Failed to generate subagent: ${error instanceof Error ? error.message : "Unknown error"}`
        ]
      });
    }
  }, [
    state.canProceed,
    state.isGenerating,
    state.userDescription,
    dispatch,
    config,
    handleGenerate
  ]);
  const handleGenerationKeypress = (0, import_react47.useCallback)(
    (key) => {
      if (keyMatchers["escape" /* ESCAPE */](key)) {
        if (abortControllerRef.current) {
          abortControllerRef.current.abort();
          dispatch({ type: "SET_GENERATING", isGenerating: false });
        }
      }
    },
    [dispatch]
  );
  useKeypress(handleGenerationKeypress, {
    isActive: state.isGenerating
  });
  const placeholder = "e.g., Expert code reviewer that reviews code based on best practices...";
  return /* @__PURE__ */ (0, import_jsx_runtime22.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Text, { color: theme.text.secondary, children: "Describe what this subagent should do and when it should be used. (Be comprehensive for best results)" }) }),
    state.isGenerating ? /* @__PURE__ */ (0, import_jsx_runtime22.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Box_default, { marginRight: 1, children: /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(build_default, {}) }),
      /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Text, { color: theme.text.accent, children: "Generating subagent configuration..." })
    ] }) : /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(
      TextInput,
      {
        value: state.userDescription || "",
        onChange: handleTextChange,
        onSubmit: handleSubmit,
        placeholder,
        height: 10,
        isActive: !state.isGenerating,
        validationErrors: state.validationErrors
      }
    )
  ] });
}
__name(DescriptionInput, "DescriptionInput");

// packages/cli/src/ui/components/subagents/create/ToolSelector.tsx
init_esbuild_shims();
var import_react48 = __toESM(require_react(), 1);
var import_jsx_runtime23 = __toESM(require_jsx_runtime(), 1);
function ToolSelector({
  tools = [],
  onSelect,
  config
}) {
  const {
    toolCategories,
    readTools,
    editTools,
    executeTools,
    initialCategory
  } = (0, import_react48.useMemo)(() => {
    if (!config) {
      return {
        toolCategories: [
          {
            id: "all",
            name: "All Tools (Default)",
            tools: []
          }
        ],
        readTools: [],
        editTools: [],
        executeTools: [],
        initialCategory: "all"
      };
    }
    const toolRegistry = config.getToolRegistry();
    const allTools = toolRegistry.getAllTools();
    const readTools2 = allTools.filter(
      (tool) => tool.kind === Kind.Read || tool.kind === Kind.Search || tool.kind === Kind.Fetch || tool.kind === Kind.Think
    ).map((tool) => tool.displayName).sort();
    const editTools2 = allTools.filter(
      (tool) => tool.kind === Kind.Edit || tool.kind === Kind.Delete || tool.kind === Kind.Move
    ).map((tool) => tool.displayName).sort();
    const executeTools2 = allTools.filter((tool) => tool.kind === Kind.Execute).map((tool) => tool.displayName).sort();
    const toolCategories2 = [
      {
        id: "all",
        name: "All Tools",
        tools: []
      },
      {
        id: "read",
        name: "Read-only Tools",
        tools: readTools2
      },
      {
        id: "edit",
        name: "Read & Edit Tools",
        tools: [...readTools2, ...editTools2]
      },
      {
        id: "execute",
        name: "Read & Edit & Execution Tools",
        tools: [...readTools2, ...editTools2, ...executeTools2]
      }
    ].filter((category) => category.id === "all" || category.tools.length > 0);
    let initialCategory2 = "all";
    if (tools.length === 0) {
      initialCategory2 = "all";
    } else {
      const matchingCategory = toolCategories2.find((category) => {
        if (category.id === "all") return false;
        const categoryToolsSet = new Set(category.tools);
        const inputToolsSet = new Set(tools);
        return categoryToolsSet.size === inputToolsSet.size && [...categoryToolsSet].every((tool) => inputToolsSet.has(tool));
      });
      if (matchingCategory) {
        initialCategory2 = matchingCategory.id;
      }
    }
    return {
      toolCategories: toolCategories2,
      readTools: readTools2,
      editTools: editTools2,
      executeTools: executeTools2,
      initialCategory: initialCategory2
    };
  }, [config, tools]);
  const [selectedCategory, setSelectedCategory] = (0, import_react48.useState)(initialCategory);
  (0, import_react48.useEffect)(() => {
    setSelectedCategory(initialCategory);
  }, [initialCategory]);
  const toolOptions = toolCategories.map((category) => ({
    label: category.name,
    value: category.id,
    category
  }));
  const handleHighlight = /* @__PURE__ */ __name((selectedValue) => {
    setSelectedCategory(selectedValue);
  }, "handleHighlight");
  const handleSelect = /* @__PURE__ */ __name((selectedValue) => {
    const category = toolCategories.find((cat) => cat.id === selectedValue);
    if (category) {
      if (category.id === "all") {
        onSelect([]);
      } else {
        onSelect(category.tools);
      }
    }
  }, "handleSelect");
  const currentCategory = toolCategories.find(
    (cat) => cat.id === selectedCategory
  );
  return /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
      RadioButtonSelect,
      {
        items: toolOptions.map((option2) => ({
          key: option2.value,
          label: option2.label,
          value: option2.value
        })),
        initialIndex: toolOptions.findIndex(
          (opt) => opt.value === selectedCategory
        ),
        onSelect: handleSelect,
        onHighlight: handleHighlight,
        isFocused: true
      }
    ) }),
    currentCategory && /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Box_default, { flexDirection: "column", children: currentCategory.id === "all" ? /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Text, { color: theme.text.secondary, children: "All tools selected, including MCP tools" }) : currentCategory.tools.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(import_jsx_runtime23.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Text, { color: theme.text.secondary, children: "Selected tools:" }),
      /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Box_default, { flexDirection: "column", marginLeft: 2, children: (() => {
        const categoryReadTools = currentCategory.tools.filter(
          (tool) => readTools.includes(tool)
        );
        const categoryEditTools = currentCategory.tools.filter(
          (tool) => editTools.includes(tool)
        );
        const categoryExecuteTools = currentCategory.tools.filter(
          (tool) => executeTools.includes(tool)
        );
        return /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(import_jsx_runtime23.Fragment, { children: [
          categoryReadTools.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Text, { color: theme.text.secondary, children: [
            "\u2022 Read-only tools: ",
            categoryReadTools.join(", ")
          ] }),
          categoryEditTools.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Text, { color: theme.text.secondary, children: [
            "\u2022 Edit tools: ",
            categoryEditTools.join(", ")
          ] }),
          categoryExecuteTools.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Text, { color: theme.text.secondary, children: [
            "\u2022 Execution tools: ",
            categoryExecuteTools.join(", ")
          ] })
        ] });
      })() })
    ] }) : null })
  ] });
}
__name(ToolSelector, "ToolSelector");

// packages/cli/src/ui/components/subagents/create/ColorSelector.tsx
init_esbuild_shims();
var import_react49 = __toESM(require_react(), 1);
var import_jsx_runtime24 = __toESM(require_jsx_runtime(), 1);
var colorOptions = COLOR_OPTIONS;
function ColorSelector({
  color = "auto",
  agentName = "Agent",
  onSelect
}) {
  const [selectedColor, setSelectedColor] = (0, import_react49.useState)(color);
  (0, import_react49.useEffect)(() => {
    setSelectedColor(color);
  }, [color]);
  const handleSelect = /* @__PURE__ */ __name((selectedValue) => {
    const colorOption = colorOptions.find(
      (option2) => option2.id === selectedValue
    );
    if (colorOption) {
      onSelect(colorOption.name);
    }
  }, "handleSelect");
  const handleHighlight = /* @__PURE__ */ __name((selectedValue) => {
    const colorOption = colorOptions.find(
      (option2) => option2.id === selectedValue
    );
    if (colorOption) {
      setSelectedColor(colorOption.name);
    }
  }, "handleHighlight");
  const currentColor = colorOptions.find((option2) => option2.name === selectedColor) || colorOptions[0];
  return /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
      RadioButtonSelect,
      {
        items: colorOptions.map((option2) => ({
          key: option2.id,
          label: option2.name,
          value: option2.id
        })),
        initialIndex: colorOptions.findIndex(
          (opt) => opt.id === currentColor.id
        ),
        onSelect: handleSelect,
        onHighlight: handleHighlight,
        isFocused: true
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(Box_default, { flexDirection: "row", children: [
      /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Text, { color: theme.text.secondary, children: "Preview:" }),
      /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Text, { color: currentColor.value, children: ` ${agentName} ` }) })
    ] })
  ] });
}
__name(ColorSelector, "ColorSelector");

// packages/cli/src/ui/components/subagents/create/CreationSummary.tsx
init_esbuild_shims();
var import_react51 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useLaunchEditor.ts
init_esbuild_shims();
var import_react50 = __toESM(require_react(), 1);
import { spawnSync as spawnSync4 } from "child_process";
function getEditorCommand(preferredEditor) {
  if (preferredEditor) {
    return preferredEditor;
  }
  switch (process.platform) {
    case "darwin":
      return "open -t";
    // TextEdit in plain text mode
    case "win32":
      return "notepad";
    default:
      return process.env["VISUAL"] || process.env["EDITOR"] || "vi";
  }
}
__name(getEditorCommand, "getEditorCommand");
function useLaunchEditor() {
  const settings = useSettings();
  const { stdin, setRawMode } = use_stdin_default();
  const launchEditor = (0, import_react50.useCallback)(
    async (filePath) => {
      const preferredEditor = settings.merged.general?.preferredEditor;
      const editor = getEditorCommand(preferredEditor);
      let editorCommand2;
      let editorArgs;
      if (editor === "open -t") {
        editorCommand2 = "open";
        editorArgs = ["-t", filePath];
      } else {
        editorCommand2 = editor;
        editorArgs = [filePath];
      }
      const wasRaw = stdin?.isRaw ?? false;
      try {
        setRawMode?.(false);
        const { status, error } = spawnSync4(editorCommand2, editorArgs, {
          stdio: "inherit"
        });
        if (error) throw error;
        if (typeof status === "number" && status !== 0) {
          throw new Error(`Editor exited with status ${status}`);
        }
      } finally {
        if (wasRaw) setRawMode?.(true);
      }
    },
    [settings.merged.general?.preferredEditor, setRawMode, stdin]
  );
  return launchEditor;
}
__name(useLaunchEditor, "useLaunchEditor");

// packages/cli/src/ui/components/subagents/create/CreationSummary.tsx
var import_jsx_runtime25 = __toESM(require_jsx_runtime(), 1);
function CreationSummary({
  state,
  onPrevious: _onPrevious,
  onCancel,
  config
}) {
  const [saveError, setSaveError] = (0, import_react51.useState)(null);
  const [saveSuccess, setSaveSuccess] = (0, import_react51.useState)(false);
  const [warnings, setWarnings] = (0, import_react51.useState)([]);
  const launchEditor = useLaunchEditor();
  const truncateText = /* @__PURE__ */ __name((text, maxLength) => {
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength - 3) + "...";
  }, "truncateText");
  (0, import_react51.useEffect)(() => {
    const checkWarnings = /* @__PURE__ */ __name(async () => {
      if (!config || !state.generatedName) return;
      const allWarnings = [];
      try {
        const subagentManager = config.getSubagentManager();
        const isAvailable = await subagentManager.isNameAvailable(
          state.generatedName
        );
        if (!isAvailable) {
          const existing = await subagentManager.loadSubagent(
            state.generatedName
          );
          if (existing) {
            const conflictLevel = existing.level === "project" ? "project" : "user";
            const targetLevel = state.location;
            if (conflictLevel === targetLevel) {
              allWarnings.push(
                `Name "${state.generatedName}" already exists at ${conflictLevel} level - will overwrite existing subagent`
              );
            } else if (targetLevel === "project") {
              allWarnings.push(
                `Name "${state.generatedName}" exists at user level - project level will take precedence`
              );
            } else {
              allWarnings.push(
                `Name "${state.generatedName}" exists at project level - existing subagent will take precedence`
              );
            }
          }
        }
      } catch (error) {
        console.warn("Error checking subagent name availability:", error);
      }
      if (state.generatedDescription.length > 300) {
        allWarnings.push(
          `Description is over ${state.generatedDescription.length} characters`
        );
      }
      if (state.generatedSystemPrompt.length > 1e4) {
        allWarnings.push(
          `System prompt is over ${state.generatedSystemPrompt.length} characters`
        );
      }
      setWarnings(allWarnings);
    }, "checkWarnings");
    checkWarnings();
  }, [
    config,
    state.generatedName,
    state.generatedDescription,
    state.generatedSystemPrompt,
    state.location
  ]);
  const toolsDisplay = state.selectedTools.length === 0 ? "*" : state.selectedTools.join(", ");
  const saveSubagent = (0, import_react51.useCallback)(async () => {
    if (!config) {
      throw new Error("Configuration not available");
    }
    const subagentManager = config.getSubagentManager();
    const subagentConfig = {
      name: state.generatedName,
      description: state.generatedDescription,
      systemPrompt: state.generatedSystemPrompt,
      level: state.location,
      filePath: "",
      // Will be set by manager
      tools: Array.isArray(state.selectedTools) ? state.selectedTools : void 0,
      color: state.color
    };
    await subagentManager.createSubagent(subagentConfig, {
      level: state.location,
      overwrite: true
    });
    return subagentManager;
  }, [state, config]);
  const showSuccessAndClose = (0, import_react51.useCallback)(() => {
    setSaveSuccess(true);
    setTimeout(() => {
      onCancel();
    }, 2e3);
  }, [onCancel]);
  const handleSave = (0, import_react51.useCallback)(async () => {
    setSaveError(null);
    try {
      await saveSubagent();
      showSuccessAndClose();
    } catch (error) {
      setSaveError(
        error instanceof Error ? error.message : "Unknown error occurred"
      );
    }
  }, [saveSubagent, showSuccessAndClose]);
  const handleEdit = (0, import_react51.useCallback)(async () => {
    setSaveError(null);
    try {
      const subagentManager = await saveSubagent();
      const subagentFilePath = subagentManager.getSubagentPath(
        state.generatedName,
        state.location
      );
      await launchEditor(subagentFilePath);
      showSuccessAndClose();
    } catch (error) {
      setSaveError(
        `Failed to save and edit subagent: ${error instanceof Error ? error.message : "Unknown error"}`
      );
    }
  }, [
    saveSubagent,
    showSuccessAndClose,
    state.generatedName,
    state.location,
    launchEditor
  ]);
  useKeypress(
    (key) => {
      if (saveSuccess) return;
      if (key.name === "return" || key.sequence === "s") {
        handleSave();
        return;
      }
      if (key.sequence === "e") {
        handleEdit();
        return;
      }
    },
    { isActive: true }
  );
  if (saveSuccess) {
    return /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text, { bold: true, color: theme.status.success, children: "\u2705 Subagent Created Successfully!" }) }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(Text, { children: [
        'Subagent "',
        state.generatedName,
        '" has been saved to',
        " ",
        state.location,
        " level."
      ] }) })
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text, { color: theme.text.primary, children: "Name: " }),
        /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text, { color: getColorForDisplay(state.color), children: state.generatedName })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text, { color: theme.text.primary, children: "Location: " }),
        /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text, { children: state.location === "project" ? "Project Level (.qwen/agents/)" : "User Level (~/.qwen/agents/)" })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text, { color: theme.text.primary, children: "Tools: " }),
        /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text, { children: toolsDisplay })
      ] }),
      shouldShowColor(state.color) && /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text, { color: theme.text.primary, children: "Color: " }),
        /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text, { color: getColorForDisplay(state.color), children: state.color })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text, { color: theme.text.primary, children: "Description:" }) }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Box_default, { padding: 1, paddingBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text, { wrap: "wrap", children: truncateText(state.generatedDescription, 250) }) }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text, { color: theme.text.primary, children: "System Prompt:" }) }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Box_default, { padding: 1, paddingBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text, { wrap: "wrap", children: truncateText(state.generatedSystemPrompt, 250) }) })
    ] }),
    saveError && /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text, { bold: true, color: theme.status.error, children: "\u274C Error saving subagent:" }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Box_default, { flexDirection: "column", padding: 1, paddingBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text, { color: theme.status.error, wrap: "wrap", children: saveError }) })
    ] }),
    warnings.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text, { bold: true, color: theme.status.warning, children: "Warnings:" }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Box_default, { flexDirection: "column", padding: 1, paddingBottom: 0, children: warnings.map((warning, index) => /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(Text, { color: theme.status.warning, wrap: "wrap", children: [
        "\u2022 ",
        warning
      ] }, index)) })
    ] })
  ] });
}
__name(CreationSummary, "CreationSummary");

// packages/cli/src/ui/components/subagents/create/TextEntryStep.tsx
init_esbuild_shims();
var import_react52 = __toESM(require_react(), 1);
var import_jsx_runtime26 = __toESM(require_jsx_runtime(), 1);
function TextEntryStep({
  state,
  dispatch,
  onNext,
  description,
  placeholder,
  height = 1,
  initialText = "",
  onChange,
  validate: validate4
}) {
  const submit = (0, import_react52.useCallback)(() => {
    const value = initialText ? initialText.trim() : "";
    const error = validate4 ? validate4(value) : value.length === 0 ? "Please enter a value." : null;
    if (error) {
      dispatch({ type: "SET_VALIDATION_ERRORS", errors: [error] });
      return;
    }
    dispatch({ type: "SET_VALIDATION_ERRORS", errors: [] });
    onNext();
  }, [dispatch, onNext, validate4, initialText]);
  return /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    description && /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(Text, { color: theme.text.secondary, children: description }) }),
    /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
      TextInput,
      {
        value: initialText,
        onChange,
        onSubmit: submit,
        placeholder,
        height,
        isActive: !state.isGenerating,
        validationErrors: state.validationErrors
      }
    )
  ] });
}
__name(TextEntryStep, "TextEntryStep");

// packages/cli/src/ui/components/subagents/create/AgentCreationWizard.tsx
var import_jsx_runtime27 = __toESM(require_jsx_runtime(), 1);
function AgentCreationWizard({
  onClose,
  config
}) {
  const [state, dispatch] = (0, import_react53.useReducer)(wizardReducer, initialWizardState);
  const handleNext = (0, import_react53.useCallback)(() => {
    dispatch({ type: "GO_TO_NEXT_STEP" });
  }, []);
  const handlePrevious = (0, import_react53.useCallback)(() => {
    dispatch({ type: "GO_TO_PREVIOUS_STEP" });
  }, []);
  const handleCancel = (0, import_react53.useCallback)(() => {
    dispatch({ type: "RESET_WIZARD" });
    onClose();
  }, [onClose]);
  useKeypress(
    (key) => {
      if (key.name !== "escape") {
        return;
      }
      const kind = getStepKind(state.generationMethod, state.currentStep);
      if (kind === "LLM_DESC" && state.isGenerating) {
        return;
      }
      if (state.currentStep === WIZARD_STEPS.LOCATION_SELECTION) {
        handleCancel();
      } else {
        handlePrevious();
      }
    },
    { isActive: true }
  );
  const stepProps = (0, import_react53.useMemo)(
    () => ({
      state,
      dispatch,
      onNext: handleNext,
      onPrevious: handlePrevious,
      onCancel: handleCancel,
      config
    }),
    [state, dispatch, handleNext, handlePrevious, handleCancel, config]
  );
  const renderStepHeader = (0, import_react53.useCallback)(() => {
    const getStepHeaderText = /* @__PURE__ */ __name(() => {
      const kind = getStepKind(state.generationMethod, state.currentStep);
      const n2 = state.currentStep;
      switch (kind) {
        case "LOCATION":
          return `Step ${n2}: Choose Location`;
        case "GEN_METHOD":
          return `Step ${n2}: Choose Generation Method`;
        case "LLM_DESC":
          return `Step ${n2}: Describe Your Subagent`;
        case "MANUAL_NAME":
          return `Step ${n2}: Enter Subagent Name`;
        case "MANUAL_PROMPT":
          return `Step ${n2}: Enter System Prompt`;
        case "MANUAL_DESC":
          return `Step ${n2}: Enter Description`;
        case "TOOLS":
          return `Step ${n2}: Select Tools`;
        case "COLOR":
          return `Step ${n2}: Choose Background Color`;
        case "FINAL":
          return `Step ${n2}: Confirm and Save`;
        default:
          return "Unknown Step";
      }
    }, "getStepHeaderText");
    return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Text, { bold: true, children: getStepHeaderText() }) });
  }, [state.currentStep, state.generationMethod]);
  const renderDebugContent = (0, import_react53.useCallback)(() => {
    if (process.env["NODE_ENV"] !== "development") {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Box_default, { borderStyle: "single", borderColor: theme.status.warning, padding: 1, children: /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Text, { color: theme.status.warning, bold: true, children: "Debug Info:" }),
      /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Text, { color: theme.text.secondary, children: [
        "Step: ",
        state.currentStep
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Text, { color: theme.text.secondary, children: [
        "Can Proceed: ",
        state.canProceed ? "Yes" : "No"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Text, { color: theme.text.secondary, children: [
        "Generating: ",
        state.isGenerating ? "Yes" : "No"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Text, { color: theme.text.secondary, children: [
        "Location: ",
        state.location
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Text, { color: theme.text.secondary, children: [
        "Method: ",
        state.generationMethod
      ] }),
      state.validationErrors.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Text, { color: theme.status.error, children: [
        "Errors: ",
        state.validationErrors.join(", ")
      ] })
    ] }) });
  }, [
    state.currentStep,
    state.canProceed,
    state.isGenerating,
    state.location,
    state.generationMethod,
    state.validationErrors
  ]);
  const renderStepFooter = (0, import_react53.useCallback)(() => {
    const getNavigationInstructions = /* @__PURE__ */ __name(() => {
      const kind = getStepKind(state.generationMethod, state.currentStep);
      if (kind === "LLM_DESC" && state.isGenerating) {
        return "Esc to cancel";
      }
      if (getStepKind(state.generationMethod, state.currentStep) === "FINAL") {
        return "Press Enter to save, e to save and edit, Esc to go back";
      }
      const kindForNav = getStepKind(state.generationMethod, state.currentStep);
      const hasNavigation = kindForNav === "LOCATION" || kindForNav === "GEN_METHOD" || kindForNav === "TOOLS" || kindForNav === "COLOR";
      const navigationPart = hasNavigation ? "\u2191\u2193 to navigate, " : "";
      const escAction = state.currentStep === WIZARD_STEPS.LOCATION_SELECTION ? "cancel" : "go back";
      return `Press Enter to continue, ${navigationPart}Esc to ${escAction}`;
    }, "getNavigationInstructions");
    return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Text, { color: theme.text.secondary, children: getNavigationInstructions() }) });
  }, [state.currentStep, state.isGenerating, state.generationMethod]);
  const renderStepContent = (0, import_react53.useCallback)(() => {
    const kind = getStepKind(state.generationMethod, state.currentStep);
    switch (kind) {
      case "LOCATION":
        return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(LocationSelector, { ...stepProps });
      case "GEN_METHOD":
        return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(GenerationMethodSelector, { ...stepProps });
      case "LLM_DESC":
        return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(DescriptionInput, { ...stepProps });
      case "MANUAL_NAME":
        return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
          TextEntryStep,
          {
            state,
            dispatch,
            onNext: handleNext,
            description: "Enter a clear, unique name for this subagent.",
            placeholder: "e.g., Code Reviewer",
            height: 1,
            initialText: state.generatedName,
            onChange: (t2) => {
              const value = t2;
              dispatch({ type: "SET_GENERATED_NAME", name: value });
            },
            validate: (t2) => t2.trim().length === 0 ? "Name cannot be empty." : null
          },
          "manual-name"
        );
      case "MANUAL_PROMPT":
        return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
          TextEntryStep,
          {
            state,
            dispatch,
            onNext: handleNext,
            description: "Write the system prompt that defines this subagent's behavior. Be comprehensive for best results.",
            placeholder: "e.g., You are an expert code reviewer...",
            height: 10,
            initialText: state.generatedSystemPrompt,
            onChange: (t2) => {
              dispatch({
                type: "SET_GENERATED_SYSTEM_PROMPT",
                systemPrompt: t2
              });
            },
            validate: (t2) => t2.trim().length === 0 ? "System prompt cannot be empty." : null
          },
          "manual-prompt"
        );
      case "MANUAL_DESC":
        return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
          TextEntryStep,
          {
            state,
            dispatch,
            onNext: handleNext,
            description: "Describe when and how this subagent should be used.",
            placeholder: "e.g., Reviews code for best practices and potential bugs.",
            height: 6,
            initialText: state.generatedDescription,
            onChange: (t2) => {
              dispatch({ type: "SET_GENERATED_DESCRIPTION", description: t2 });
            },
            validate: (t2) => t2.trim().length === 0 ? "Description cannot be empty." : null
          },
          "manual-desc"
        );
      case "TOOLS":
        return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
          ToolSelector,
          {
            tools: state.selectedTools,
            onSelect: (tools) => {
              dispatch({ type: "SET_TOOLS", tools });
              handleNext();
            },
            config
          }
        );
      case "COLOR":
        return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
          ColorSelector,
          {
            color: state.color,
            agentName: state.generatedName,
            onSelect: (color) => {
              dispatch({ type: "SET_BACKGROUND_COLOR", color });
              handleNext();
            }
          }
        );
      case "FINAL":
        return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(CreationSummary, { ...stepProps });
      default:
        return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(Text, { color: theme.status.error, children: [
          "Invalid step: ",
          state.currentStep
        ] }) });
    }
  }, [stepProps, state, config, handleNext, dispatch]);
  return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(
    Box_default,
    {
      borderStyle: "single",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      gap: 1,
      children: [
        renderStepHeader(),
        renderStepContent(),
        renderDebugContent(),
        renderStepFooter()
      ]
    }
  ) });
}
__name(AgentCreationWizard, "AgentCreationWizard");

// packages/cli/src/ui/components/subagents/manage/AgentsManagerDialog.tsx
init_esbuild_shims();
var import_react57 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/subagents/manage/AgentSelectionStep.tsx
init_esbuild_shims();
var import_react54 = __toESM(require_react(), 1);
var import_jsx_runtime28 = __toESM(require_jsx_runtime(), 1);
var AgentSelectionStep = /* @__PURE__ */ __name(({
  availableAgents,
  onAgentSelect
}) => {
  const [navigation, setNavigation] = (0, import_react54.useState)({
    currentBlock: "project",
    projectIndex: 0,
    userIndex: 0,
    builtinIndex: 0
  });
  const projectAgents = (0, import_react54.useMemo)(
    () => availableAgents.filter((agent) => agent.level === "project"),
    [availableAgents]
  );
  const userAgents = (0, import_react54.useMemo)(
    () => availableAgents.filter((agent) => agent.level === "user"),
    [availableAgents]
  );
  const builtinAgents = (0, import_react54.useMemo)(
    () => availableAgents.filter((agent) => agent.level === "builtin"),
    [availableAgents]
  );
  const projectNames = (0, import_react54.useMemo)(
    () => new Set(projectAgents.map((agent) => agent.name)),
    [projectAgents]
  );
  (0, import_react54.useEffect)(() => {
    if (projectAgents.length > 0) {
      setNavigation((prev) => ({ ...prev, currentBlock: "project" }));
    } else if (userAgents.length > 0) {
      setNavigation((prev) => ({ ...prev, currentBlock: "user" }));
    } else if (builtinAgents.length > 0) {
      setNavigation((prev) => ({ ...prev, currentBlock: "builtin" }));
    }
  }, [projectAgents, userAgents, builtinAgents]);
  useKeypress(
    (key) => {
      const { name: name3 } = key;
      if (name3 === "up" || name3 === "k") {
        setNavigation((prev) => {
          if (prev.currentBlock === "project") {
            if (prev.projectIndex > 0) {
              return { ...prev, projectIndex: prev.projectIndex - 1 };
            } else if (builtinAgents.length > 0) {
              return {
                ...prev,
                currentBlock: "builtin",
                builtinIndex: builtinAgents.length - 1
              };
            } else if (userAgents.length > 0) {
              return {
                ...prev,
                currentBlock: "user",
                userIndex: userAgents.length - 1
              };
            } else {
              return { ...prev, projectIndex: projectAgents.length - 1 };
            }
          } else if (prev.currentBlock === "user") {
            if (prev.userIndex > 0) {
              return { ...prev, userIndex: prev.userIndex - 1 };
            } else if (projectAgents.length > 0) {
              return {
                ...prev,
                currentBlock: "project",
                projectIndex: projectAgents.length - 1
              };
            } else if (builtinAgents.length > 0) {
              return {
                ...prev,
                currentBlock: "builtin",
                builtinIndex: builtinAgents.length - 1
              };
            } else {
              return { ...prev, userIndex: userAgents.length - 1 };
            }
          } else {
            if (prev.builtinIndex > 0) {
              return { ...prev, builtinIndex: prev.builtinIndex - 1 };
            } else if (userAgents.length > 0) {
              return {
                ...prev,
                currentBlock: "user",
                userIndex: userAgents.length - 1
              };
            } else if (projectAgents.length > 0) {
              return {
                ...prev,
                currentBlock: "project",
                projectIndex: projectAgents.length - 1
              };
            } else {
              return { ...prev, builtinIndex: builtinAgents.length - 1 };
            }
          }
        });
      } else if (name3 === "down" || name3 === "j") {
        setNavigation((prev) => {
          if (prev.currentBlock === "project") {
            if (prev.projectIndex < projectAgents.length - 1) {
              return { ...prev, projectIndex: prev.projectIndex + 1 };
            } else if (userAgents.length > 0) {
              return { ...prev, currentBlock: "user", userIndex: 0 };
            } else if (builtinAgents.length > 0) {
              return { ...prev, currentBlock: "builtin", builtinIndex: 0 };
            } else {
              return { ...prev, projectIndex: 0 };
            }
          } else if (prev.currentBlock === "user") {
            if (prev.userIndex < userAgents.length - 1) {
              return { ...prev, userIndex: prev.userIndex + 1 };
            } else if (builtinAgents.length > 0) {
              return { ...prev, currentBlock: "builtin", builtinIndex: 0 };
            } else if (projectAgents.length > 0) {
              return { ...prev, currentBlock: "project", projectIndex: 0 };
            } else {
              return { ...prev, userIndex: 0 };
            }
          } else {
            if (prev.builtinIndex < builtinAgents.length - 1) {
              return { ...prev, builtinIndex: prev.builtinIndex + 1 };
            } else if (projectAgents.length > 0) {
              return { ...prev, currentBlock: "project", projectIndex: 0 };
            } else if (userAgents.length > 0) {
              return { ...prev, currentBlock: "user", userIndex: 0 };
            } else {
              return { ...prev, builtinIndex: 0 };
            }
          }
        });
      } else if (name3 === "return" || name3 === "space") {
        let globalIndex;
        if (navigation.currentBlock === "project") {
          globalIndex = navigation.projectIndex;
        } else if (navigation.currentBlock === "user") {
          globalIndex = projectAgents.length + navigation.userIndex;
        } else {
          globalIndex = projectAgents.length + userAgents.length + navigation.builtinIndex;
        }
        if (globalIndex >= 0 && globalIndex < availableAgents.length) {
          onAgentSelect(globalIndex);
        }
      }
    },
    { isActive: true }
  );
  if (availableAgents.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: theme.text.secondary, children: "No subagents found." }),
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: theme.text.secondary, children: "Use '/agents create' to create your first subagent." })
    ] });
  }
  const renderAgentItem = /* @__PURE__ */ __name((agent, index, isSelected) => {
    const textColor = isSelected ? theme.text.accent : theme.text.primary;
    return /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { alignItems: "center", children: [
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { minWidth: 2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: isSelected ? theme.text.accent : theme.text.primary, children: isSelected ? "\u25CF" : " " }) }),
      /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: textColor, wrap: "truncate", children: [
        agent.name,
        agent.isBuiltin && /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: isSelected ? theme.text.accent : theme.text.secondary, children: [
          " ",
          "(built-in)"
        ] }),
        agent.level === "user" && projectNames.has(agent.name) && /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(
          Text,
          {
            color: isSelected ? theme.status.warning : theme.text.secondary,
            children: [
              " ",
              "(overridden by project level agent)"
            ]
          }
        )
      ] })
    ] }, `${agent.name}-${agent.level}`);
  }, "renderAgentItem");
  const enabledAgentsCount = projectAgents.length + userAgents.filter((agent) => !projectNames.has(agent.name)).length + builtinAgents.length;
  return /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", children: [
    projectAgents.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.text.primary, bold: true, children: [
        "Project Level (",
        projectAgents[0].filePath.replace(/\/[^/]+$/, ""),
        ")"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: projectAgents.map((agent, index) => {
        const isSelected = navigation.currentBlock === "project" && navigation.projectIndex === index;
        return renderAgentItem(agent, index, isSelected);
      }) })
    ] }),
    userAgents.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(
      Box_default,
      {
        flexDirection: "column",
        marginBottom: builtinAgents.length > 0 ? 1 : 0,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.text.primary, bold: true, children: [
            "User Level (",
            userAgents[0].filePath.replace(/\/[^/]+$/, ""),
            ")"
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: userAgents.map((agent, index) => {
            const isSelected = navigation.currentBlock === "user" && navigation.userIndex === index;
            return renderAgentItem(agent, index, isSelected);
          }) })
        ]
      }
    ),
    builtinAgents.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: theme.text.primary, bold: true, children: "Built-in Agents" }),
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: builtinAgents.map((agent, index) => {
        const isSelected = navigation.currentBlock === "builtin" && navigation.builtinIndex === index;
        return renderAgentItem(agent, index, isSelected);
      }) })
    ] }),
    (projectAgents.length > 0 || userAgents.length > 0 || builtinAgents.length > 0) && /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.text.secondary, children: [
      "Using: ",
      enabledAgentsCount,
      " agents"
    ] }) })
  ] });
}, "AgentSelectionStep");

// packages/cli/src/ui/components/subagents/manage/ActionSelectionStep.tsx
init_esbuild_shims();
var import_react55 = __toESM(require_react(), 1);
var import_jsx_runtime29 = __toESM(require_jsx_runtime(), 1);
var ActionSelectionStep = /* @__PURE__ */ __name(({
  selectedAgent,
  onNavigateToStep,
  onNavigateBack
}) => {
  const [selectedAction, setSelectedAction] = (0, import_react55.useState)(null);
  const allActions = [
    { key: "view", label: "View Agent", value: "view" },
    { key: "edit", label: "Edit Agent", value: "edit" },
    { key: "delete", label: "Delete Agent", value: "delete" },
    { key: "back", label: "Back", value: "back" }
  ];
  const actions = selectedAgent?.isBuiltin ? allActions.filter(
    (action) => action.value === "view" || action.value === "back"
  ) : allActions;
  const handleActionSelect = /* @__PURE__ */ __name((value) => {
    if (value === "back") {
      onNavigateBack();
      return;
    }
    setSelectedAction(value);
    if (value === "view") {
      onNavigateToStep(MANAGEMENT_STEPS.AGENT_VIEWER);
    } else if (value === "edit") {
      onNavigateToStep(MANAGEMENT_STEPS.EDIT_OPTIONS);
    } else if (value === "delete") {
      onNavigateToStep(MANAGEMENT_STEPS.DELETE_CONFIRMATION);
    }
  }, "handleActionSelect");
  const selectedIndex = selectedAction ? actions.findIndex((action) => action.value === selectedAction) : 0;
  return /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
    RadioButtonSelect,
    {
      items: actions,
      initialIndex: selectedIndex,
      onSelect: handleActionSelect,
      showNumbers: false
    }
  ) });
}, "ActionSelectionStep");

// packages/cli/src/ui/components/subagents/manage/AgentViewerStep.tsx
init_esbuild_shims();
var import_jsx_runtime30 = __toESM(require_jsx_runtime(), 1);
var AgentViewerStep = /* @__PURE__ */ __name(({ selectedAgent }) => {
  if (!selectedAgent) {
    return /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.status.error, children: "No agent selected" }) });
  }
  const agent = selectedAgent;
  const toolsDisplay = agent.tools ? agent.tools.join(", ") : "*";
  return /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { flexDirection: "column", gap: 1, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.text.primary, children: "File Path: " }),
      /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { children: agent.filePath })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.text.primary, children: "Tools: " }),
      /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { children: toolsDisplay })
    ] }),
    shouldShowColor(agent.color) && /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.text.primary, children: "Color: " }),
      /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: getColorForDisplay(agent.color), children: agent.color })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.text.primary, children: "Description:" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { padding: 1, paddingBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { wrap: "wrap", children: agent.description }) }),
    /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.text.primary, children: "System Prompt:" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { padding: 1, paddingBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { wrap: "wrap", children: agent.systemPrompt }) })
  ] }) });
}, "AgentViewerStep");

// packages/cli/src/ui/components/subagents/manage/AgentEditStep.tsx
init_esbuild_shims();
var import_react56 = __toESM(require_react(), 1);
var import_jsx_runtime31 = __toESM(require_jsx_runtime(), 1);
var editOptions = [
  {
    id: "editor",
    label: "Open in editor"
  },
  {
    id: "tools",
    label: "Edit tools"
  },
  {
    id: "color",
    label: "Edit color"
  }
];
function EditOptionsStep({
  selectedAgent,
  onNavigateToStep
}) {
  const [selectedOption, setSelectedOption] = (0, import_react56.useState)("editor");
  const [error, setError] = (0, import_react56.useState)(null);
  const launchEditor = useLaunchEditor();
  const handleHighlight = /* @__PURE__ */ __name((selectedValue) => {
    setSelectedOption(selectedValue);
  }, "handleHighlight");
  const handleSelect = (0, import_react56.useCallback)(
    async (selectedValue) => {
      if (!selectedAgent) return;
      setError(null);
      if (selectedValue === "editor") {
        try {
          await launchEditor(selectedAgent?.filePath);
        } catch (err) {
          setError(
            `Failed to launch editor: ${err instanceof Error ? err.message : "Unknown error"}`
          );
        }
      } else if (selectedValue === "tools") {
        onNavigateToStep(MANAGEMENT_STEPS.EDIT_TOOLS);
      } else if (selectedValue === "color") {
        onNavigateToStep(MANAGEMENT_STEPS.EDIT_COLOR);
      }
    },
    [selectedAgent, onNavigateToStep, launchEditor]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
      RadioButtonSelect,
      {
        items: editOptions.map((option2) => ({
          key: option2.id,
          label: option2.label,
          value: option2.id
        })),
        initialIndex: editOptions.findIndex(
          (opt) => opt.id === selectedOption
        ),
        onSelect: handleSelect,
        onHighlight: handleHighlight,
        isFocused: true
      }
    ) }),
    error && /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text, { bold: true, color: theme.status.error, children: "\u274C Error:" }),
      /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { flexDirection: "column", padding: 1, paddingBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text, { color: theme.status.error, wrap: "wrap", children: error }) })
    ] })
  ] });
}
__name(EditOptionsStep, "EditOptionsStep");

// packages/cli/src/ui/components/subagents/manage/AgentDeleteStep.tsx
init_esbuild_shims();
var import_jsx_runtime32 = __toESM(require_jsx_runtime(), 1);
function AgentDeleteStep({
  selectedAgent,
  onDelete,
  onNavigateBack
}) {
  useKeypress(
    async (key) => {
      if (!selectedAgent) return;
      if (key.name === "y" || key.name === "return") {
        try {
          await onDelete(selectedAgent);
        } catch (error) {
          console.error("Failed to delete agent:", error);
        }
      } else if (key.name === "n") {
        onNavigateBack();
      }
    },
    { isActive: true }
  );
  if (!selectedAgent) {
    return /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(Text, { color: theme.status.error, children: "No agent selected" }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(Box_default, { flexDirection: "column", gap: 1, children: /* @__PURE__ */ (0, import_jsx_runtime32.jsxs)(Text, { color: theme.status.error, children: [
    "Are you sure you want to delete agent \u201C",
    selectedAgent.name,
    "\u201D?"
  ] }) });
}
__name(AgentDeleteStep, "AgentDeleteStep");

// packages/cli/src/ui/components/subagents/manage/AgentsManagerDialog.tsx
var import_jsx_runtime33 = __toESM(require_jsx_runtime(), 1);
function AgentsManagerDialog({
  onClose,
  config
}) {
  const [availableAgents, setAvailableAgents] = (0, import_react57.useState)([]);
  const [selectedAgentIndex, setSelectedAgentIndex] = (0, import_react57.useState)(-1);
  const [navigationStack, setNavigationStack] = (0, import_react57.useState)([
    MANAGEMENT_STEPS.AGENT_SELECTION
  ]);
  const selectedAgent = (0, import_react57.useMemo)(
    () => selectedAgentIndex >= 0 ? availableAgents[selectedAgentIndex] : null,
    [availableAgents, selectedAgentIndex]
  );
  const loadAgents = (0, import_react57.useCallback)(async () => {
    if (!config) return;
    const manager = config.getSubagentManager();
    const allAgents = await manager.listSubagents({ force: true });
    setAvailableAgents(allAgents);
  }, [config]);
  (0, import_react57.useEffect)(() => {
    loadAgents();
  }, [loadAgents]);
  const getCurrentStep = (0, import_react57.useCallback)(
    () => navigationStack[navigationStack.length - 1] || MANAGEMENT_STEPS.AGENT_SELECTION,
    [navigationStack]
  );
  const handleSelectAgent = (0, import_react57.useCallback)((agentIndex) => {
    setSelectedAgentIndex(agentIndex);
    setNavigationStack((prev) => [...prev, MANAGEMENT_STEPS.ACTION_SELECTION]);
  }, []);
  const handleNavigateToStep = (0, import_react57.useCallback)((step) => {
    setNavigationStack((prev) => [...prev, step]);
  }, []);
  const handleNavigateBack = (0, import_react57.useCallback)(() => {
    setNavigationStack((prev) => {
      if (prev.length <= 1) {
        return prev;
      }
      return prev.slice(0, -1);
    });
  }, []);
  const handleDeleteAgent = (0, import_react57.useCallback)(
    async (agent) => {
      if (!config) return;
      try {
        const subagentManager = config.getSubagentManager();
        await subagentManager.deleteSubagent(agent.name, agent.level);
        await loadAgents();
        setNavigationStack([MANAGEMENT_STEPS.AGENT_SELECTION]);
        setSelectedAgentIndex(-1);
      } catch (error) {
        console.error("Failed to delete agent:", error);
        throw error;
      }
    },
    [config, loadAgents]
  );
  useKeypress(
    (key) => {
      if (key.name !== "escape") {
        return;
      }
      const currentStep = getCurrentStep();
      if (currentStep === MANAGEMENT_STEPS.AGENT_SELECTION) {
        onClose();
      } else {
        handleNavigateBack();
      }
    },
    { isActive: true }
  );
  const commonProps = (0, import_react57.useMemo)(
    () => ({
      onNavigateToStep: handleNavigateToStep,
      onNavigateBack: handleNavigateBack
    }),
    [handleNavigateToStep, handleNavigateBack]
  );
  const renderStepHeader = (0, import_react57.useCallback)(() => {
    const currentStep = getCurrentStep();
    const getStepHeaderText = /* @__PURE__ */ __name(() => {
      switch (currentStep) {
        case MANAGEMENT_STEPS.AGENT_SELECTION:
          return "Agents";
        case MANAGEMENT_STEPS.ACTION_SELECTION:
          return "Choose Action";
        case MANAGEMENT_STEPS.AGENT_VIEWER:
          return selectedAgent?.name;
        case MANAGEMENT_STEPS.EDIT_OPTIONS:
          return `Edit ${selectedAgent?.name}`;
        case MANAGEMENT_STEPS.EDIT_TOOLS:
          return `Edit Tools: ${selectedAgent?.name}`;
        case MANAGEMENT_STEPS.EDIT_COLOR:
          return `Edit Color: ${selectedAgent?.name}`;
        case MANAGEMENT_STEPS.DELETE_CONFIRMATION:
          return `Delete ${selectedAgent?.name}`;
        default:
          return "Unknown Step";
      }
    }, "getStepHeaderText");
    const headerColor = currentStep === MANAGEMENT_STEPS.AGENT_VIEWER && selectedAgent && shouldShowColor(selectedAgent.color) ? getColorForDisplay(selectedAgent.color) : void 0;
    return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { bold: true, color: headerColor, children: getStepHeaderText() }) });
  }, [getCurrentStep, selectedAgent]);
  const renderStepFooter = (0, import_react57.useCallback)(() => {
    const currentStep = getCurrentStep();
    const getNavigationInstructions = /* @__PURE__ */ __name(() => {
      if (currentStep === MANAGEMENT_STEPS.AGENT_SELECTION) {
        if (availableAgents.length === 0) {
          return "Esc to close";
        }
        return "Enter to select, \u2191\u2193 to navigate, Esc to close";
      }
      if (currentStep === MANAGEMENT_STEPS.AGENT_VIEWER) {
        return "Esc to go back";
      }
      if (currentStep === MANAGEMENT_STEPS.DELETE_CONFIRMATION) {
        return "Enter to confirm, Esc to cancel";
      }
      return "Enter to select, \u2191\u2193 to navigate, Esc to go back";
    }, "getNavigationInstructions");
    return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { color: theme.text.secondary, children: getNavigationInstructions() }) });
  }, [getCurrentStep, availableAgents]);
  const renderStepContent = (0, import_react57.useCallback)(() => {
    const currentStep = getCurrentStep();
    switch (currentStep) {
      case MANAGEMENT_STEPS.AGENT_SELECTION:
        return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
          AgentSelectionStep,
          {
            availableAgents,
            onAgentSelect: handleSelectAgent,
            ...commonProps
          }
        );
      case MANAGEMENT_STEPS.ACTION_SELECTION:
        return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(ActionSelectionStep, { selectedAgent, ...commonProps });
      case MANAGEMENT_STEPS.AGENT_VIEWER:
        return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(AgentViewerStep, { selectedAgent, ...commonProps });
      case MANAGEMENT_STEPS.EDIT_OPTIONS:
        return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(EditOptionsStep, { selectedAgent, ...commonProps });
      case MANAGEMENT_STEPS.EDIT_TOOLS:
        return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { flexDirection: "column", gap: 1, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
          ToolSelector,
          {
            tools: selectedAgent?.tools || [],
            onSelect: async (tools) => {
              if (selectedAgent && config) {
                try {
                  const subagentManager = config.getSubagentManager();
                  await subagentManager.updateSubagent(
                    selectedAgent.name,
                    { tools },
                    selectedAgent.level
                  );
                  await loadAgents();
                  handleNavigateBack();
                } catch (error) {
                  console.error("Failed to save agent changes:", error);
                }
              }
            },
            config
          }
        ) });
      case MANAGEMENT_STEPS.EDIT_COLOR:
        return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { flexDirection: "column", gap: 1, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
          ColorSelector,
          {
            color: selectedAgent?.color || "auto",
            agentName: selectedAgent?.name || "Agent",
            onSelect: async (color) => {
              if (selectedAgent && config) {
                try {
                  const subagentManager = config.getSubagentManager();
                  await subagentManager.updateSubagent(
                    selectedAgent.name,
                    { color },
                    selectedAgent.level
                  );
                  await loadAgents();
                  handleNavigateBack();
                } catch (error) {
                  console.error("Failed to save color changes:", error);
                }
              }
            }
          }
        ) });
      case MANAGEMENT_STEPS.DELETE_CONFIRMATION:
        return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
          AgentDeleteStep,
          {
            selectedAgent,
            onDelete: handleDeleteAgent,
            ...commonProps
          }
        );
      default:
        return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(Text, { color: theme.status.error, children: [
          "Invalid step: ",
          currentStep
        ] }) });
    }
  }, [
    getCurrentStep,
    availableAgents,
    selectedAgent,
    commonProps,
    config,
    loadAgents,
    handleNavigateBack,
    handleSelectAgent,
    handleDeleteAgent
  ]);
  return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(
    Box_default,
    {
      borderStyle: "single",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      gap: 1,
      children: [
        renderStepHeader(),
        renderStepContent(),
        renderStepFooter()
      ]
    }
  ) });
}
__name(AgentsManagerDialog, "AgentsManagerDialog");

// packages/cli/src/ui/components/subagents/runtime/AgentExecutionDisplay.tsx
init_esbuild_shims();
var import_react59 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx
init_esbuild_shims();
var import_react58 = __toESM(require_react(), 1);
var import_jsx_runtime34 = __toESM(require_jsx_runtime(), 1);
var ToolConfirmationMessage = /* @__PURE__ */ __name(({
  confirmationDetails,
  config,
  isFocused = true,
  availableTerminalHeight,
  terminalWidth,
  compactMode = false
}) => {
  const { onConfirm } = confirmationDetails;
  const childWidth = terminalWidth - 2;
  const settings = useSettings();
  const preferredEditor = settings.merged.general?.preferredEditor;
  const [ideClient, setIdeClient] = (0, import_react58.useState)(null);
  const [isDiffingEnabled, setIsDiffingEnabled] = (0, import_react58.useState)(false);
  (0, import_react58.useEffect)(() => {
    let isMounted = true;
    if (config.getIdeMode()) {
      const getIdeClient = /* @__PURE__ */ __name(async () => {
        const client = await IdeClient.getInstance();
        if (isMounted) {
          setIdeClient(client);
          setIsDiffingEnabled(client?.isDiffingEnabled() ?? false);
        }
      }, "getIdeClient");
      getIdeClient();
    }
    return () => {
      isMounted = false;
    };
  }, [config]);
  const handleConfirm = /* @__PURE__ */ __name(async (outcome) => {
    if (confirmationDetails.type === "edit") {
      if (config.getIdeMode() && isDiffingEnabled) {
        const cliOutcome = outcome === ToolConfirmationOutcome.Cancel ? "rejected" : "accepted";
        await ideClient?.resolveDiffFromCli(
          confirmationDetails.filePath,
          cliOutcome
        );
      }
    }
    onConfirm(outcome);
  }, "handleConfirm");
  const isTrustedFolder = config.isTrustedFolder();
  useKeypress(
    (key) => {
      if (!isFocused) return;
      if (key.name === "escape" || key.ctrl && key.name === "c") {
        handleConfirm(ToolConfirmationOutcome.Cancel);
      }
    },
    { isActive: isFocused }
  );
  const handleSelect = /* @__PURE__ */ __name((item) => handleConfirm(item), "handleSelect");
  if (compactMode) {
    const compactOptions = [
      {
        key: "proceed-once",
        label: "Yes, allow once",
        value: ToolConfirmationOutcome.ProceedOnce
      },
      {
        key: "proceed-always",
        label: "Allow always",
        value: ToolConfirmationOutcome.ProceedAlways
      },
      {
        key: "cancel",
        label: "No",
        value: ToolConfirmationOutcome.Cancel
      }
    ];
    return /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { wrap: "truncate", children: "Do you want to proceed?" }) }),
      /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
        RadioButtonSelect,
        {
          items: compactOptions,
          onSelect: handleSelect,
          isFocused
        }
      ) })
    ] });
  }
  let bodyContent = null;
  let question;
  const options2 = new Array();
  function availableBodyContentHeight() {
    if (options2.length === 0) {
      throw new Error("Options not provided for confirmation message");
    }
    if (availableTerminalHeight === void 0) {
      return void 0;
    }
    const PADDING_OUTER_Y = 2;
    const MARGIN_BODY_BOTTOM = 1;
    const HEIGHT_QUESTION = 1;
    const MARGIN_QUESTION_BOTTOM = 1;
    const HEIGHT_OPTIONS = options2.length;
    const surroundingElementsHeight = PADDING_OUTER_Y + MARGIN_BODY_BOTTOM + HEIGHT_QUESTION + MARGIN_QUESTION_BOTTOM + HEIGHT_OPTIONS;
    return Math.max(availableTerminalHeight - surroundingElementsHeight, 1);
  }
  __name(availableBodyContentHeight, "availableBodyContentHeight");
  if (confirmationDetails.type === "edit") {
    if (confirmationDetails.isModifying) {
      return /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(
        Box_default,
        {
          minWidth: "90%",
          borderStyle: "round",
          borderColor: theme.border.default,
          justifyContent: "space-around",
          padding: 1,
          overflow: "hidden",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { color: theme.text.primary, children: "Modify in progress: " }),
            /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { color: theme.status.success, children: "Save and close external editor to continue" })
          ]
        }
      );
    }
    question = `Apply this change?`;
    options2.push({
      label: "Yes, allow once",
      value: ToolConfirmationOutcome.ProceedOnce,
      key: "Yes, allow once"
    });
    if (isTrustedFolder) {
      options2.push({
        label: "Yes, allow always",
        value: ToolConfirmationOutcome.ProceedAlways,
        key: "Yes, allow always"
      });
    }
    if ((!config.getIdeMode() || !isDiffingEnabled) && preferredEditor) {
      options2.push({
        label: "Modify with external editor",
        value: ToolConfirmationOutcome.ModifyWithEditor,
        key: "Modify with external editor"
      });
    }
    options2.push({
      label: "No, suggest changes (esc)",
      value: ToolConfirmationOutcome.Cancel,
      key: "No, suggest changes (esc)"
    });
    bodyContent = /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
      DiffRenderer,
      {
        diffContent: confirmationDetails.fileDiff,
        filename: confirmationDetails.fileName,
        availableTerminalHeight: availableBodyContentHeight(),
        terminalWidth: childWidth
      }
    );
  } else if (confirmationDetails.type === "exec") {
    const executionProps = confirmationDetails;
    question = `Allow execution of: '${executionProps.rootCommand}'?`;
    options2.push({
      label: "Yes, allow once",
      value: ToolConfirmationOutcome.ProceedOnce,
      key: "Yes, allow once"
    });
    if (isTrustedFolder) {
      options2.push({
        label: `Yes, allow always ...`,
        value: ToolConfirmationOutcome.ProceedAlways,
        key: `Yes, allow always ...`
      });
    }
    options2.push({
      label: "No, suggest changes (esc)",
      value: ToolConfirmationOutcome.Cancel,
      key: "No, suggest changes (esc)"
    });
    let bodyContentHeight = availableBodyContentHeight();
    if (bodyContentHeight !== void 0) {
      bodyContentHeight -= 2;
    }
    bodyContent = /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Box_default, { paddingX: 1, marginLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
      MaxSizedBox,
      {
        maxHeight: bodyContentHeight,
        maxWidth: Math.max(childWidth - 4, 1),
        children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { color: theme.text.link, children: executionProps.command }) })
      }
    ) }) });
  } else if (confirmationDetails.type === "plan") {
    const planProps = confirmationDetails;
    question = planProps.title;
    options2.push({
      key: "proceed-always",
      label: "Yes, and auto-accept edits",
      value: ToolConfirmationOutcome.ProceedAlways
    });
    options2.push({
      key: "proceed-once",
      label: "Yes, and manually approve edits",
      value: ToolConfirmationOutcome.ProceedOnce
    });
    options2.push({
      key: "cancel",
      label: "No, keep planning (esc)",
      value: ToolConfirmationOutcome.Cancel
    });
    bodyContent = /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Box_default, { flexDirection: "column", paddingX: 1, marginLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
      MarkdownDisplay,
      {
        text: planProps.plan,
        isPending: false,
        availableTerminalHeight: availableBodyContentHeight(),
        terminalWidth: childWidth
      }
    ) });
  } else if (confirmationDetails.type === "info") {
    const infoProps = confirmationDetails;
    const displayUrls = infoProps.urls && !(infoProps.urls.length === 1 && infoProps.urls[0] === infoProps.prompt);
    question = `Do you want to proceed?`;
    options2.push({
      label: "Yes, allow once",
      value: ToolConfirmationOutcome.ProceedOnce,
      key: "Yes, allow once"
    });
    if (isTrustedFolder) {
      options2.push({
        label: "Yes, allow always",
        value: ToolConfirmationOutcome.ProceedAlways,
        key: "Yes, allow always"
      });
    }
    options2.push({
      label: "No, suggest changes (esc)",
      value: ToolConfirmationOutcome.Cancel,
      key: "No, suggest changes (esc)"
    });
    bodyContent = /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, marginLeft: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { color: theme.text.link, children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(RenderInline, { text: infoProps.prompt }) }),
      displayUrls && infoProps.urls && infoProps.urls.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { color: theme.text.primary, children: "URLs to fetch:" }),
        infoProps.urls.map((url2) => /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(Text, { children: [
          " ",
          "- ",
          /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(RenderInline, { text: url2 })
        ] }, url2))
      ] })
    ] });
  } else {
    const mcpProps = confirmationDetails;
    bodyContent = /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, marginLeft: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(Text, { color: theme.text.link, children: [
        "MCP Server: ",
        mcpProps.serverName
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(Text, { color: theme.text.link, children: [
        "Tool: ",
        mcpProps.toolName
      ] })
    ] });
    question = `Allow execution of MCP tool "${mcpProps.toolName}" from server "${mcpProps.serverName}"?`;
    options2.push({
      label: "Yes, allow once",
      value: ToolConfirmationOutcome.ProceedOnce,
      key: "Yes, allow once"
    });
    if (isTrustedFolder) {
      options2.push({
        label: `Yes, always allow tool "${mcpProps.toolName}" from server "${mcpProps.serverName}"`,
        value: ToolConfirmationOutcome.ProceedAlwaysTool,
        // Cast until types are updated
        key: `Yes, always allow tool "${mcpProps.toolName}" from server "${mcpProps.serverName}"`
      });
      options2.push({
        label: `Yes, always allow all tools from server "${mcpProps.serverName}"`,
        value: ToolConfirmationOutcome.ProceedAlwaysServer,
        key: `Yes, always allow all tools from server "${mcpProps.serverName}"`
      });
    }
    options2.push({
      label: "No, suggest changes (esc)",
      value: ToolConfirmationOutcome.Cancel,
      key: "No, suggest changes (esc)"
    });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(Box_default, { flexDirection: "column", padding: 1, width: childWidth, children: [
    /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Box_default, { flexGrow: 1, flexShrink: 1, overflow: "hidden", marginBottom: 1, children: bodyContent }),
    /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Box_default, { marginBottom: 1, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { color: theme.text.primary, wrap: "truncate", children: question }) }),
    /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Box_default, { flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
      RadioButtonSelect,
      {
        items: options2,
        onSelect: handleSelect,
        isFocused
      }
    ) })
  ] });
}, "ToolConfirmationMessage");

// packages/cli/src/ui/components/subagents/runtime/AgentExecutionDisplay.tsx
var import_jsx_runtime35 = __toESM(require_jsx_runtime(), 1);
var getStatusColor = /* @__PURE__ */ __name((status) => {
  switch (status) {
    case "running":
    case "executing":
    case "awaiting_approval":
      return theme.status.warning;
    case "completed":
    case "success":
      return theme.status.success;
    case "cancelled":
      return theme.status.warning;
    case "failed":
      return theme.status.error;
    default:
      return theme.text.secondary;
  }
}, "getStatusColor");
var getStatusText = /* @__PURE__ */ __name((status) => {
  switch (status) {
    case "running":
      return "Running";
    case "completed":
      return "Completed";
    case "cancelled":
      return "User Cancelled";
    case "failed":
      return "Failed";
    default:
      return "Unknown";
  }
}, "getStatusText");
var MAX_TOOL_CALLS = 5;
var MAX_TASK_PROMPT_LINES = 5;
var AgentExecutionDisplay = /* @__PURE__ */ __name(({
  data,
  availableHeight,
  childWidth,
  config
}) => {
  const [displayMode, setDisplayMode] = import_react59.default.useState("compact");
  const agentColor = (0, import_react59.useMemo)(() => {
    const colorOption = COLOR_OPTIONS.find(
      (option2) => option2.name === data.subagentColor
    );
    return colorOption?.value || theme.text.accent;
  }, [data.subagentColor]);
  const footerText = import_react59.default.useMemo(() => {
    if (data.status !== "running") return "";
    if (displayMode === "default") {
      const hasMoreLines = data.taskPrompt.split("\n").length > MAX_TASK_PROMPT_LINES;
      const hasMoreToolCalls = data.toolCalls && data.toolCalls.length > MAX_TOOL_CALLS;
      if (hasMoreToolCalls || hasMoreLines) {
        return "Press ctrl+r to show less, ctrl+e to show more.";
      }
      return "Press ctrl+r to show less.";
    }
    if (displayMode === "verbose") {
      return "Press ctrl+e to show less.";
    }
    return "";
  }, [displayMode, data]);
  useKeypress(
    (key) => {
      if (key.ctrl && key.name === "r") {
        setDisplayMode(
          (current) => current === "compact" ? "default" : "compact"
        );
      } else if (key.ctrl && key.name === "e") {
        setDisplayMode(
          (current) => current === "default" ? "verbose" : "default"
        );
      }
    },
    { isActive: true }
  );
  if (displayMode === "compact") {
    return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "column", children: [
      !data.pendingConfirmation && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "row", children: [
        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { bold: true, color: agentColor, children: data.subagentName }),
        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(StatusDot, { status: data.status }),
        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(StatusIndicator, { status: data.status })
      ] }),
      data.status === "running" && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(import_jsx_runtime35.Fragment, { children: [
        data.toolCalls && data.toolCalls.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
            ToolCallItem,
            {
              toolCall: data.toolCalls[data.toolCalls.length - 1],
              compact: true
            }
          ),
          data.toolCalls.length > 1 && !data.pendingConfirmation && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { flexDirection: "row", paddingLeft: 4, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.text.secondary, children: [
            "+",
            data.toolCalls.length - 1,
            " more tool calls (ctrl+r to expand)"
          ] }) })
        ] }),
        data.pendingConfirmation && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { flexDirection: "column", marginTop: 1, paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
          ToolConfirmationMessage,
          {
            confirmationDetails: data.pendingConfirmation,
            isFocused: true,
            availableTerminalHeight: availableHeight,
            terminalWidth: childWidth,
            compactMode: true,
            config
          }
        ) })
      ] }),
      data.status === "completed" && data.executionSummary && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { flexDirection: "row", marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.text.secondary, children: [
        "Execution Summary: ",
        data.executionSummary.totalToolCalls,
        " tool uses \xB7 ",
        data.executionSummary.totalTokens.toLocaleString(),
        " tokens \xB7 ",
        fmtDuration(data.executionSummary.totalDurationMs)
      ] }) }),
      data.status === "failed" && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { flexDirection: "row", marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.status.error, children: [
        "Failed: ",
        data.terminateReason
      ] }) })
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "row", children: [
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { bold: true, color: agentColor, children: data.subagentName }),
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(StatusDot, { status: data.status }),
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(StatusIndicator, { status: data.status })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
      TaskPromptSection,
      {
        taskPrompt: data.taskPrompt,
        displayMode
      }
    ),
    data.status === "running" && data.toolCalls && data.toolCalls.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
      ToolCallsList,
      {
        toolCalls: data.toolCalls,
        displayMode
      }
    ) }),
    data.pendingConfirmation && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
      ToolConfirmationMessage,
      {
        confirmationDetails: data.pendingConfirmation,
        config,
        isFocused: true,
        availableTerminalHeight: availableHeight,
        terminalWidth: childWidth,
        compactMode: true
      }
    ) }),
    (data.status === "completed" || data.status === "failed" || data.status === "cancelled") && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(ResultsSection, { data, displayMode }),
    footerText && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { flexDirection: "row", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.secondary, children: footerText }) })
  ] });
}, "AgentExecutionDisplay");
var TaskPromptSection = /* @__PURE__ */ __name(({ taskPrompt, displayMode }) => {
  const lines = taskPrompt.split("\n");
  const shouldTruncate = lines.length > 10;
  const showFull = displayMode === "verbose";
  const displayLines = showFull ? lines : lines.slice(0, MAX_TASK_PROMPT_LINES);
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "row", children: [
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.primary, children: "Task Detail: " }),
      shouldTruncate && displayMode === "default" && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.text.secondary, children: [
        " ",
        "Showing the first ",
        MAX_TASK_PROMPT_LINES,
        " lines."
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { wrap: "wrap", children: displayLines.join("\n") + (shouldTruncate && !showFull ? "..." : "") }) })
  ] });
}, "TaskPromptSection");
var StatusDot = /* @__PURE__ */ __name(({ status }) => /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { marginLeft: 1, marginRight: 1, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: getStatusColor(status), children: "\u25CF" }) }), "StatusDot");
var StatusIndicator = /* @__PURE__ */ __name(({ status }) => {
  const color = getStatusColor(status);
  const text = getStatusText(status);
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color, children: text });
}, "StatusIndicator");
var ToolCallsList = /* @__PURE__ */ __name(({ toolCalls, displayMode }) => {
  const calls = toolCalls || [];
  const shouldTruncate = calls.length > MAX_TOOL_CALLS;
  const showAll = displayMode === "verbose";
  const displayCalls = showAll ? calls : calls.slice(-MAX_TOOL_CALLS);
  const reversedDisplayCalls = [...displayCalls].reverse();
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "row", marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.primary, children: "Tools:" }),
      shouldTruncate && displayMode === "default" && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.text.secondary, children: [
        " ",
        "Showing the last ",
        MAX_TOOL_CALLS,
        " of ",
        calls.length,
        " tools."
      ] })
    ] }),
    reversedDisplayCalls.map((toolCall, index) => /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(ToolCallItem, { toolCall }, `${toolCall.name}-${index}`))
  ] });
}, "ToolCallsList");
var ToolCallItem = /* @__PURE__ */ __name(({ toolCall, compact = false }) => {
  const STATUS_INDICATOR_WIDTH2 = 3;
  const statusIcon = import_react59.default.useMemo(() => {
    const color = getStatusColor(toolCall.status);
    switch (toolCall.status) {
      case "executing":
        return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color, children: "\u22B7" });
      // Using same as ToolMessage
      case "awaiting_approval":
        return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.status.warning, children: "?" });
      case "success":
        return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color, children: "\u2713" });
      case "failed":
        return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color, bold: true, children: "x" });
      default:
        return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color, children: "o" });
    }
  }, [toolCall.status]);
  const description = import_react59.default.useMemo(() => {
    if (!toolCall.description) return "";
    const firstLine = toolCall.description.split("\n")[0];
    return firstLine.length > 80 ? firstLine.substring(0, 80) + "..." : firstLine;
  }, [toolCall.description]);
  const truncatedOutput = import_react59.default.useMemo(() => {
    if (!toolCall.resultDisplay) return "";
    const firstLine = toolCall.resultDisplay.split("\n")[0];
    return firstLine.length > 80 ? firstLine.substring(0, 80) + "..." : firstLine;
  }, [toolCall.resultDisplay]);
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "column", paddingLeft: 1, marginBottom: 0, children: [
    /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "row", children: [
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { minWidth: STATUS_INDICATOR_WIDTH2, children: statusIcon }),
      /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { wrap: "truncate-end", children: [
        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { children: toolCall.name }),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.secondary, children: description }),
        toolCall.error && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.status.error, children: [
          " - ",
          toolCall.error
        ] })
      ] })
    ] }),
    !compact && truncatedOutput && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { flexDirection: "row", paddingLeft: STATUS_INDICATOR_WIDTH2, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.secondary, children: truncatedOutput }) })
  ] });
}, "ToolCallItem");
var ExecutionSummaryDetails = /* @__PURE__ */ __name(({ data, displayMode: _displayMode }) => {
  const stats = data.executionSummary;
  if (!stats) {
    return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { flexDirection: "column", paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.secondary, children: "\u2022 No summary available" }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "column", paddingLeft: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { children: [
      "\u2022 ",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { children: [
        "Duration: ",
        fmtDuration(stats.totalDurationMs)
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { children: [
      "\u2022 ",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { children: [
        "Rounds: ",
        stats.rounds
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { children: [
      "\u2022 ",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { children: [
        "Tokens: ",
        stats.totalTokens.toLocaleString()
      ] })
    ] })
  ] });
}, "ExecutionSummaryDetails");
var ToolUsageStats = /* @__PURE__ */ __name(({ executionSummary }) => {
  if (!executionSummary) {
    return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { flexDirection: "column", paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.secondary, children: "\u2022 No tool usage data available" }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "column", paddingLeft: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { children: [
      "\u2022 ",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { children: "Total Calls:" }),
      " ",
      executionSummary.totalToolCalls
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { children: [
      "\u2022 ",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { children: "Success Rate:" }),
      " ",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.status.success, children: [
        executionSummary.successRate.toFixed(1),
        "%"
      ] }),
      " ",
      "(",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.status.success, children: [
        executionSummary.successfulToolCalls,
        " success"
      ] }),
      ",",
      " ",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.status.error, children: [
        executionSummary.failedToolCalls,
        " failed"
      ] }),
      ")"
    ] })
  ] });
}, "ToolUsageStats");
var ResultsSection = /* @__PURE__ */ __name(({ data, displayMode }) => /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
  data.toolCalls && data.toolCalls.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(ToolCallsList, { toolCalls: data.toolCalls, displayMode }),
  data.status === "completed" && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { flexDirection: "row", marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.primary, children: "Execution Summary:" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(ExecutionSummaryDetails, { data, displayMode })
  ] }),
  data.status === "completed" && data.executionSummary && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { flexDirection: "row", marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.primary, children: "Tool Usage:" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(ToolUsageStats, { executionSummary: data.executionSummary })
  ] }),
  data.status === "cancelled" && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { flexDirection: "row", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.status.warning, children: "\u23F9 User Cancelled" }) }),
  data.status === "failed" && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.status.error, children: "Task Failed: " }),
    /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.status.error, children: data.terminateReason })
  ] })
] }), "ResultsSection");

// packages/cli/src/ui/components/PlanSummaryDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime36 = __toESM(require_jsx_runtime(), 1);
var PlanSummaryDisplay = /* @__PURE__ */ __name(({
  data,
  availableHeight,
  childWidth
}) => {
  const { message, plan } = data;
  return /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(Text, { color: Colors.AccentGreen, wrap: "wrap", children: message }) }),
    /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
      MarkdownDisplay,
      {
        text: plan,
        isPending: false,
        availableTerminalHeight: availableHeight,
        terminalWidth: childWidth
      }
    )
  ] });
}, "PlanSummaryDisplay");

// packages/cli/src/ui/components/ShellInputPrompt.tsx
init_esbuild_shims();
var import_react60 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/keyToAnsi.ts
init_esbuild_shims();
function keyToAnsi(key) {
  if (key.ctrl) {
    if (key.name >= "a" && key.name <= "z") {
      return String.fromCharCode(
        key.name.charCodeAt(0) - "a".charCodeAt(0) + 1
      );
    }
    switch (key.name) {
      case "c":
        return "";
      // ETX (End of Text), commonly used for interrupt
      // Add other special ctrl cases if needed
      default:
        break;
    }
  }
  switch (key.name) {
    case "up":
      return "\x1B[A";
    case "down":
      return "\x1B[B";
    case "right":
      return "\x1B[C";
    case "left":
      return "\x1B[D";
    case "escape":
      return "\x1B";
    case "tab":
      return "	";
    case "backspace":
      return "\x7F";
    case "delete":
      return "\x1B[3~";
    case "home":
      return "\x1B[H";
    case "end":
      return "\x1B[F";
    case "pageup":
      return "\x1B[5~";
    case "pagedown":
      return "\x1B[6~";
    default:
      break;
  }
  if (key.name === "return") {
    return "\r";
  }
  if (!key.ctrl && !key.meta && key.sequence) {
    return key.sequence;
  }
  return null;
}
__name(keyToAnsi, "keyToAnsi");

// packages/cli/src/ui/components/ShellInputPrompt.tsx
var ShellInputPrompt = /* @__PURE__ */ __name(({
  activeShellPtyId,
  focus = true
}) => {
  const handleShellInputSubmit = (0, import_react60.useCallback)(
    (input) => {
      if (activeShellPtyId) {
        ShellExecutionService.writeToPty(activeShellPtyId, input);
      }
    },
    [activeShellPtyId]
  );
  const handleInput = (0, import_react60.useCallback)(
    (key) => {
      if (!focus || !activeShellPtyId) {
        return;
      }
      if (key.ctrl && key.shift && key.name === "up") {
        ShellExecutionService.scrollPty(activeShellPtyId, -1);
        return;
      }
      if (key.ctrl && key.shift && key.name === "down") {
        ShellExecutionService.scrollPty(activeShellPtyId, 1);
        return;
      }
      const ansiSequence = keyToAnsi(key);
      if (ansiSequence) {
        handleShellInputSubmit(ansiSequence);
      }
    },
    [focus, handleShellInputSubmit, activeShellPtyId]
  );
  useKeypress(handleInput, { isActive: focus });
  return null;
}, "ShellInputPrompt");

// packages/cli/src/ui/constants.ts
init_esbuild_shims();
var EstimatedArtWidth = 59;
var BoxBorderWidth = 1;
var BOX_PADDING_X = 1;
var UI_WIDTH = EstimatedArtWidth + BOX_PADDING_X * 2 + BoxBorderWidth * 2;
var SHELL_COMMAND_NAME = "Shell Command";
var SHELL_NAME = "Shell";
var TOOL_STATUS = {
  SUCCESS: "\u2713",
  PENDING: "o",
  EXECUTING: "\u22B7",
  CONFIRMING: "?",
  CANCELED: "-",
  ERROR: "x"
};

// packages/cli/src/ui/components/messages/ToolMessage.tsx
var import_jsx_runtime37 = __toESM(require_jsx_runtime(), 1);
var STATIC_HEIGHT = 1;
var RESERVED_LINE_COUNT = 5;
var STATUS_INDICATOR_WIDTH = 3;
var MIN_LINES_SHOWN = 2;
var MAXIMUM_RESULT_DISPLAY_CHARACTERS = 1e6;
var useResultDisplayRenderer = /* @__PURE__ */ __name((resultDisplay) => import_react61.default.useMemo(() => {
  if (!resultDisplay) {
    return { type: "none" };
  }
  if (typeof resultDisplay === "object" && resultDisplay !== null && "type" in resultDisplay && resultDisplay.type === "todo_list") {
    return {
      type: "todo",
      data: resultDisplay
    };
  }
  if (typeof resultDisplay === "object" && resultDisplay !== null && "type" in resultDisplay && resultDisplay.type === "plan_summary") {
    return {
      type: "plan",
      data: resultDisplay
    };
  }
  if (typeof resultDisplay === "object" && resultDisplay !== null && "type" in resultDisplay && resultDisplay.type === "task_execution") {
    return {
      type: "task",
      data: resultDisplay
    };
  }
  if (typeof resultDisplay === "object" && resultDisplay !== null && "fileDiff" in resultDisplay) {
    return {
      type: "diff",
      data: resultDisplay
    };
  }
  if (typeof resultDisplay === "object" && resultDisplay !== null && "ansiOutput" in resultDisplay) {
    return { type: "ansi", data: resultDisplay.ansiOutput };
  }
  return {
    type: "string",
    data: resultDisplay
  };
}, [resultDisplay]), "useResultDisplayRenderer");
var TodoResultRenderer = /* @__PURE__ */ __name(({
  data
}) => /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(TodoDisplay, { todos: data.todos }), "TodoResultRenderer");
var PlanResultRenderer = /* @__PURE__ */ __name(({ data, availableHeight, childWidth }) => /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
  PlanSummaryDisplay,
  {
    data,
    availableHeight,
    childWidth
  }
), "PlanResultRenderer");
var SubagentExecutionRenderer = /* @__PURE__ */ __name(({ data, availableHeight, childWidth, config }) => /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
  AgentExecutionDisplay,
  {
    data,
    availableHeight,
    childWidth,
    config
  }
), "SubagentExecutionRenderer");
var StringResultRenderer = /* @__PURE__ */ __name(({ data, renderAsMarkdown, availableHeight, childWidth }) => {
  let displayData = data;
  if (displayData.length > MAXIMUM_RESULT_DISPLAY_CHARACTERS) {
    displayData = "..." + displayData.slice(-MAXIMUM_RESULT_DISPLAY_CHARACTERS);
  }
  if (renderAsMarkdown) {
    return /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
      MarkdownDisplay,
      {
        text: displayData,
        isPending: false,
        availableTerminalHeight: availableHeight,
        terminalWidth: childWidth
      }
    ) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(MaxSizedBox, { maxHeight: availableHeight, maxWidth: childWidth, children: /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text, { wrap: "wrap", color: theme.text.primary, children: displayData }) }) });
}, "StringResultRenderer");
var DiffResultRenderer = /* @__PURE__ */ __name(({ data, availableHeight, childWidth }) => /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
  DiffRenderer,
  {
    diffContent: data.fileDiff,
    filename: data.fileName,
    availableTerminalHeight: availableHeight,
    terminalWidth: childWidth
  }
), "DiffResultRenderer");
var ToolMessage = /* @__PURE__ */ __name(({
  name: name3,
  description,
  resultDisplay,
  status,
  availableTerminalHeight,
  terminalWidth,
  emphasis = "medium",
  renderOutputAsMarkdown = true,
  activeShellPtyId,
  embeddedShellFocused,
  ptyId,
  config
}) => {
  const isThisShellFocused = (name3 === SHELL_COMMAND_NAME || name3 === "Shell") && status === "Executing" /* Executing */ && ptyId === activeShellPtyId && embeddedShellFocused;
  const [lastUpdateTime, setLastUpdateTime] = import_react61.default.useState(null);
  const [userHasFocused, setUserHasFocused] = import_react61.default.useState(false);
  const [showFocusHint, setShowFocusHint] = import_react61.default.useState(false);
  import_react61.default.useEffect(() => {
    if (resultDisplay) {
      setLastUpdateTime(/* @__PURE__ */ new Date());
    }
  }, [resultDisplay]);
  import_react61.default.useEffect(() => {
    if (!lastUpdateTime) {
      return;
    }
    const timer = setTimeout(() => {
      setShowFocusHint(true);
    }, 5e3);
    return () => clearTimeout(timer);
  }, [lastUpdateTime]);
  import_react61.default.useEffect(() => {
    if (isThisShellFocused) {
      setUserHasFocused(true);
    }
  }, [isThisShellFocused]);
  const isThisShellFocusable = (name3 === SHELL_COMMAND_NAME || name3 === "Shell") && status === "Executing" /* Executing */ && config?.getShouldUseNodePtyShell();
  const shouldShowFocusHint = isThisShellFocusable && (showFocusHint || userHasFocused);
  const availableHeight = availableTerminalHeight ? Math.max(
    availableTerminalHeight - STATIC_HEIGHT - RESERVED_LINE_COUNT,
    MIN_LINES_SHOWN + 1
    // enforce minimum lines shown
  ) : void 0;
  if (availableHeight) {
    renderOutputAsMarkdown = false;
  }
  const childWidth = terminalWidth - 3;
  const displayRenderer = useResultDisplayRenderer(resultDisplay);
  return /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(Box_default, { paddingX: 1, paddingY: 0, flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(Box_default, { minHeight: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(ToolStatusIndicator, { status, name: name3 }),
      /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
        ToolInfo,
        {
          name: name3,
          status,
          description,
          emphasis
        }
      ),
      shouldShowFocusHint && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Box_default, { marginLeft: 1, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text, { color: theme.text.accent, children: isThisShellFocused ? "(Focused)" : "(ctrl+f to focus)" }) }),
      emphasis === "high" && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(TrailingIndicator, {})
    ] }),
    displayRenderer.type !== "none" && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Box_default, { paddingLeft: STATUS_INDICATOR_WIDTH, width: "100%", marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(Box_default, { flexDirection: "column", children: [
      displayRenderer.type === "todo" && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(TodoResultRenderer, { data: displayRenderer.data }),
      displayRenderer.type === "plan" && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
        PlanResultRenderer,
        {
          data: displayRenderer.data,
          availableHeight,
          childWidth
        }
      ),
      displayRenderer.type === "task" && config && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
        SubagentExecutionRenderer,
        {
          data: displayRenderer.data,
          availableHeight,
          childWidth,
          config
        }
      ),
      displayRenderer.type === "diff" && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
        DiffResultRenderer,
        {
          data: displayRenderer.data,
          availableHeight,
          childWidth
        }
      ),
      displayRenderer.type === "ansi" && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
        AnsiOutputText,
        {
          data: displayRenderer.data,
          availableTerminalHeight: availableHeight
        }
      ),
      displayRenderer.type === "string" && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
        StringResultRenderer,
        {
          data: displayRenderer.data,
          renderAsMarkdown: renderOutputAsMarkdown,
          availableHeight,
          childWidth
        }
      )
    ] }) }),
    isThisShellFocused && config && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Box_default, { paddingLeft: STATUS_INDICATOR_WIDTH, marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
      ShellInputPrompt,
      {
        activeShellPtyId: activeShellPtyId ?? null,
        focus: embeddedShellFocused
      }
    ) })
  ] });
}, "ToolMessage");
var ToolStatusIndicator = /* @__PURE__ */ __name(({
  status,
  name: name3
}) => {
  const isShell = name3 === SHELL_COMMAND_NAME || name3 === SHELL_NAME;
  const statusColor = isShell ? theme.ui.symbol : theme.status.warning;
  return /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(Box_default, { minWidth: STATUS_INDICATOR_WIDTH, children: [
    status === "Pending" /* Pending */ && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text, { color: theme.status.success, children: TOOL_STATUS.PENDING }),
    status === "Executing" /* Executing */ && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
      GeminiRespondingSpinner,
      {
        spinnerType: "toggle",
        nonRespondingDisplay: TOOL_STATUS.EXECUTING
      }
    ),
    status === "Success" /* Success */ && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text, { color: theme.status.success, "aria-label": "Success:", children: TOOL_STATUS.SUCCESS }),
    status === "Confirming" /* Confirming */ && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text, { color: statusColor, "aria-label": "Confirming:", children: TOOL_STATUS.CONFIRMING }),
    status === "Canceled" /* Canceled */ && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text, { color: statusColor, "aria-label": "Canceled:", bold: true, children: TOOL_STATUS.CANCELED }),
    status === "Error" /* Error */ && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text, { color: theme.status.error, "aria-label": "Error:", bold: true, children: TOOL_STATUS.ERROR })
  ] });
}, "ToolStatusIndicator");
var ToolInfo = /* @__PURE__ */ __name(({
  name: name3,
  description,
  status,
  emphasis
}) => {
  const nameColor = import_react61.default.useMemo(() => {
    switch (emphasis) {
      case "high":
        return theme.text.primary;
      case "medium":
        return theme.text.primary;
      case "low":
        return theme.text.secondary;
      default: {
        const exhaustiveCheck = emphasis;
        return exhaustiveCheck;
      }
    }
  }, [emphasis]);
  return /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(
    Text,
    {
      wrap: "truncate-end",
      strikethrough: status === "Canceled" /* Canceled */,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text, { color: nameColor, bold: true, children: name3 }),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text, { color: theme.text.secondary, children: description })
      ]
    }
  ) });
}, "ToolInfo");
var TrailingIndicator = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(Text, { color: theme.text.primary, wrap: "truncate", children: [
  " ",
  "\u2190"
] }), "TrailingIndicator");

// packages/cli/src/ui/contexts/ConfigContext.tsx
init_esbuild_shims();
var import_react62 = __toESM(require_react(), 1);
var ConfigContext = import_react62.default.createContext(void 0);
var useConfig = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react62.useContext)(ConfigContext);
  if (context2 === void 0) {
    throw new Error("useConfig must be used within a ConfigProvider");
  }
  return context2;
}, "useConfig");

// packages/cli/src/ui/components/messages/ToolGroupMessage.tsx
var import_jsx_runtime38 = __toESM(require_jsx_runtime(), 1);
var ToolGroupMessage = /* @__PURE__ */ __name(({
  toolCalls,
  availableTerminalHeight,
  terminalWidth,
  isFocused = true,
  activeShellPtyId,
  embeddedShellFocused
}) => {
  const isEmbeddedShellFocused = embeddedShellFocused && toolCalls.some(
    (t2) => t2.ptyId === activeShellPtyId && t2.status === "Executing" /* Executing */
  );
  const hasPending = !toolCalls.every(
    (t2) => t2.status === "Success" /* Success */
  );
  const config = useConfig();
  const isShellCommand = toolCalls.some(
    (t2) => t2.name === SHELL_COMMAND_NAME || t2.name === SHELL_NAME
  );
  const borderColor = isShellCommand || isEmbeddedShellFocused ? theme.ui.symbol : hasPending ? theme.status.warning : theme.border.default;
  const staticHeight = (
    /* border */
    2 + /* marginBottom */
    1
  );
  const innerWidth = terminalWidth - 4;
  const toolAwaitingApproval = (0, import_react63.useMemo)(
    () => toolCalls.find((tc) => tc.status === "Confirming" /* Confirming */),
    [toolCalls]
  );
  let countToolCallsWithResults = 0;
  for (const tool of toolCalls) {
    if (tool.resultDisplay !== void 0 && tool.resultDisplay !== "") {
      countToolCallsWithResults++;
    }
  }
  const countOneLineToolCalls = toolCalls.length - countToolCallsWithResults;
  const availableTerminalHeightPerToolMessage = availableTerminalHeight ? Math.max(
    Math.floor(
      (availableTerminalHeight - staticHeight - countOneLineToolCalls) / Math.max(1, countToolCallsWithResults)
    ),
    1
  ) : void 0;
  return /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      width: "100%",
      marginLeft: 1,
      borderDimColor: hasPending && (!isShellCommand || !isEmbeddedShellFocused),
      borderColor,
      gap: 1,
      children: toolCalls.map((tool) => {
        const isConfirming = toolAwaitingApproval?.callId === tool.callId;
        return /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)(Box_default, { flexDirection: "column", minHeight: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Box_default, { flexDirection: "row", alignItems: "center", children: /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
            ToolMessage,
            {
              ...tool,
              availableTerminalHeight: availableTerminalHeightPerToolMessage,
              terminalWidth: innerWidth,
              emphasis: isConfirming ? "high" : toolAwaitingApproval ? "low" : "medium",
              activeShellPtyId,
              embeddedShellFocused,
              config
            }
          ) }),
          tool.status === "Confirming" /* Confirming */ && isConfirming && tool.confirmationDetails && /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
            ToolConfirmationMessage,
            {
              confirmationDetails: tool.confirmationDetails,
              config,
              isFocused,
              availableTerminalHeight: availableTerminalHeightPerToolMessage,
              terminalWidth: innerWidth
            }
          ),
          tool.outputFile && /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Box_default, { marginX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)(Text, { color: theme.text.primary, children: [
            "Output too long and was saved to: ",
            tool.outputFile
          ] }) })
        ] }, tool.callId);
      })
    }
  );
}, "ToolGroupMessage");

// packages/cli/src/ui/components/messages/GeminiMessageContent.tsx
init_esbuild_shims();
var import_jsx_runtime39 = __toESM(require_jsx_runtime(), 1);
var GeminiMessageContent = /* @__PURE__ */ __name(({
  text,
  isPending,
  availableTerminalHeight,
  terminalWidth
}) => {
  const originalPrefix = "\u2726 ";
  const prefixWidth = originalPrefix.length;
  return /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(Box_default, { flexDirection: "column", paddingLeft: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
    MarkdownDisplay,
    {
      text,
      isPending,
      availableTerminalHeight,
      terminalWidth
    }
  ) });
}, "GeminiMessageContent");

// packages/cli/src/ui/components/messages/CompressionMessage.tsx
init_esbuild_shims();
var import_jsx_runtime40 = __toESM(require_jsx_runtime(), 1);
function CompressionMessage({
  compression
}) {
  const { isPending, originalTokenCount, newTokenCount, compressionStatus } = compression;
  const originalTokens = originalTokenCount ?? 0;
  const newTokens = newTokenCount ?? 0;
  const getCompressionText = /* @__PURE__ */ __name(() => {
    if (isPending) {
      return "Compressing chat history";
    }
    switch (compressionStatus) {
      case CompressionStatus.COMPRESSED:
        return `Chat history compressed from ${originalTokens} to ${newTokens} tokens.`;
      case CompressionStatus.COMPRESSION_FAILED_INFLATED_TOKEN_COUNT:
        if (originalTokens < 5e4) {
          return "Compression was not beneficial for this history size.";
        }
        return "Chat history compression did not reduce size. This may indicate issues with the compression prompt.";
      case CompressionStatus.COMPRESSION_FAILED_TOKEN_COUNT_ERROR:
        return "Could not compress chat history due to a token counting error.";
      case CompressionStatus.NOOP:
        return "Nothing to compress.";
      default:
        return "";
    }
  }, "getCompressionText");
  const text = getCompressionText();
  return /* @__PURE__ */ (0, import_jsx_runtime40.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Box_default, { marginRight: 1, children: isPending ? /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(build_default, { type: "dots" }) : /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Text, { color: theme.text.accent, children: "\u2726" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(
      Text,
      {
        color: compression.isPending ? theme.text.accent : theme.status.success,
        "aria-label": SCREEN_READER_MODEL_PREFIX,
        children: text
      }
    ) })
  ] });
}
__name(CompressionMessage, "CompressionMessage");

// packages/cli/src/ui/components/messages/SummaryMessage.tsx
init_esbuild_shims();
var import_jsx_runtime41 = __toESM(require_jsx_runtime(), 1);
var SummaryMessage = /* @__PURE__ */ __name(({ summary }) => {
  const getText3 = /* @__PURE__ */ __name(() => {
    if (summary.isPending) {
      switch (summary.stage) {
        case "generating":
          return "Generating project summary...";
        case "saving":
          return "Saving project summary...";
        default:
          return "Processing summary...";
      }
    }
    const baseMessage = "Project summary generated and saved successfully!";
    if (summary.filePath) {
      return `${baseMessage} Saved to: ${summary.filePath}`;
    }
    return baseMessage;
  }, "getText");
  const getIcon = /* @__PURE__ */ __name(() => {
    if (summary.isPending) {
      return /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(build_default, { type: "dots" });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: Colors.AccentGreen, children: "\u2705" });
  }, "getIcon");
  return /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { marginRight: 1, children: getIcon() }),
    /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(
      Text,
      {
        color: summary.isPending ? Colors.AccentPurple : Colors.AccentGreen,
        children: getText3()
      }
    ) })
  ] });
}, "SummaryMessage");

// packages/cli/src/ui/components/messages/WarningMessage.tsx
init_esbuild_shims();
var import_jsx_runtime42 = __toESM(require_jsx_runtime(), 1);
var WarningMessage = /* @__PURE__ */ __name(({ text }) => {
  const prefix = "\u26A0 ";
  const prefixWidth = 3;
  return /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Box_default, { flexDirection: "row", marginTop: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: Colors.AccentYellow, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { wrap: "wrap", color: Colors.AccentYellow, children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(RenderInline, { text }) }) })
  ] });
}, "WarningMessage");

// packages/cli/src/ui/components/AboutBox.tsx
init_esbuild_shims();

// packages/cli/src/utils/systemInfoFields.ts
init_esbuild_shims();
function getSystemInfoFields(info) {
  const allFields = [
    {
      label: "CLI Version",
      key: "cliVersion"
    },
    {
      label: "Git Commit",
      key: "gitCommit"
    },
    {
      label: "Model",
      key: "modelVersion"
    },
    {
      label: "Sandbox",
      key: "sandboxEnv"
    },
    {
      label: "OS Platform",
      key: "osPlatform"
    },
    {
      label: "OS Arch",
      key: "osArch"
    },
    {
      label: "OS Release",
      key: "osRelease"
    },
    {
      label: "Node.js Version",
      key: "nodeVersion"
    },
    {
      label: "NPM Version",
      key: "npmVersion"
    },
    {
      label: "Session ID",
      key: "sessionId"
    },
    {
      label: "Auth Method",
      key: "selectedAuthType"
    },
    {
      label: "Base URL",
      key: "baseUrl"
    },
    {
      label: "Memory Usage",
      key: "memoryUsage"
    },
    {
      label: "IDE Client",
      key: "ideClient"
    }
  ];
  return allFields.filter((field) => {
    const value = info[field.key];
    if (field.key === "baseUrl" || field.key === "gitCommit" || field.key === "ideClient") {
      return Boolean(value);
    }
    return true;
  });
}
__name(getSystemInfoFields, "getSystemInfoFields");
function getFieldValue(field, info) {
  const value = info[field.key];
  if (value === void 0 || value === null) {
    return "";
  }
  if (field.key === "selectedAuthType") {
    return String(value).startsWith("oauth") ? "OAuth" : String(value);
  }
  return String(value);
}
__name(getFieldValue, "getFieldValue");

// packages/cli/src/ui/components/AboutBox.tsx
var import_jsx_runtime43 = __toESM(require_jsx_runtime(), 1);
var AboutBox = /* @__PURE__ */ __name((props) => {
  const fields = getSystemInfoFields(props);
  return /* @__PURE__ */ (0, import_jsx_runtime43.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      marginY: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Text, { bold: true, color: theme.text.accent, children: "About Qwen Code" }) }),
        fields.map((field) => /* @__PURE__ */ (0, import_jsx_runtime43.jsxs)(Box_default, { flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Box_default, { width: "35%", children: /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Text, { bold: true, color: theme.text.link, children: field.label }) }),
          /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Text, { color: theme.text.primary, children: getFieldValue(field, props) }) })
        ] }, field.key))
      ]
    }
  );
}, "AboutBox");

// packages/cli/src/ui/components/StatsDisplay.tsx
init_esbuild_shims();

// node_modules/ink-gradient/dist/index.js
init_esbuild_shims();
var import_react64 = __toESM(require_react(), 1);
var import_prop_types = __toESM(require_prop_types(), 1);
var import_gradient_string = __toESM(require_gradient_string(), 1);
init_strip_ansi();
var Gradient = /* @__PURE__ */ __name((props) => {
  if (props.name && props.colors) {
    throw new Error("The `name` and `colors` props are mutually exclusive");
  }
  let gradient;
  if (props.name) {
    gradient = import_gradient_string.default[props.name];
  } else if (props.colors) {
    gradient = (0, import_gradient_string.default)(props.colors);
  } else {
    throw new Error("Either `name` or `colors` prop must be provided");
  }
  const applyGradient = /* @__PURE__ */ __name((text) => gradient.multiline(stripAnsi(text)), "applyGradient");
  return import_react64.default.createElement(Transform, { transform: applyGradient }, props.children);
}, "Gradient");
Gradient.propTypes = {
  children: import_prop_types.default.oneOfType([
    import_prop_types.default.arrayOf(import_prop_types.default.node),
    import_prop_types.default.node
  ]).isRequired,
  name: import_prop_types.default.oneOf([
    "cristal",
    "teen",
    "mind",
    "morning",
    "vice",
    "passion",
    "fruit",
    "instagram",
    "atlas",
    "retro",
    "summer",
    "pastel",
    "rainbow"
  ]),
  colors: import_prop_types.default.arrayOf(import_prop_types.default.oneOfType([
    import_prop_types.default.string,
    import_prop_types.default.object
  ]))
};
var dist_default4 = Gradient;

// packages/cli/src/ui/utils/formatters.ts
init_esbuild_shims();
var formatMemoryUsage2 = /* @__PURE__ */ __name((bytes) => {
  const gb = bytes / (1024 * 1024 * 1024);
  if (bytes < 1024 * 1024) {
    return `${(bytes / 1024).toFixed(1)} KB`;
  }
  if (bytes < 1024 * 1024 * 1024) {
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  }
  return `${gb.toFixed(2)} GB`;
}, "formatMemoryUsage");
var formatDuration = /* @__PURE__ */ __name((milliseconds) => {
  if (milliseconds <= 0) {
    return "0s";
  }
  if (milliseconds < 1e3) {
    return `${Math.round(milliseconds)}ms`;
  }
  const totalSeconds = milliseconds / 1e3;
  if (totalSeconds < 60) {
    return `${totalSeconds.toFixed(1)}s`;
  }
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor(totalSeconds % 3600 / 60);
  const seconds = Math.floor(totalSeconds % 60);
  const parts = [];
  if (hours > 0) {
    parts.push(`${hours}h`);
  }
  if (minutes > 0) {
    parts.push(`${minutes}m`);
  }
  if (seconds > 0) {
    parts.push(`${seconds}s`);
  }
  if (parts.length === 0) {
    if (hours > 0) return `${hours}h`;
    if (minutes > 0) return `${minutes}m`;
    return `${seconds}s`;
  }
  return parts.join(" ");
}, "formatDuration");

// packages/cli/src/ui/contexts/SessionContext.tsx
init_esbuild_shims();
var import_react65 = __toESM(require_react(), 1);
var import_jsx_runtime44 = __toESM(require_jsx_runtime(), 1);
function areModelMetricsEqual(a, b) {
  if (a.api.totalRequests !== b.api.totalRequests || a.api.totalErrors !== b.api.totalErrors || a.api.totalLatencyMs !== b.api.totalLatencyMs) {
    return false;
  }
  if (a.tokens.prompt !== b.tokens.prompt || a.tokens.candidates !== b.tokens.candidates || a.tokens.total !== b.tokens.total || a.tokens.cached !== b.tokens.cached || a.tokens.thoughts !== b.tokens.thoughts || a.tokens.tool !== b.tokens.tool) {
    return false;
  }
  return true;
}
__name(areModelMetricsEqual, "areModelMetricsEqual");
function areToolCallStatsEqual(a, b) {
  if (a.count !== b.count || a.success !== b.success || a.fail !== b.fail || a.durationMs !== b.durationMs) {
    return false;
  }
  if (a.decisions["accept" /* ACCEPT */] !== b.decisions["accept" /* ACCEPT */] || a.decisions["reject" /* REJECT */] !== b.decisions["reject" /* REJECT */] || a.decisions["modify" /* MODIFY */] !== b.decisions["modify" /* MODIFY */] || a.decisions["auto_accept" /* AUTO_ACCEPT */] !== b.decisions["auto_accept" /* AUTO_ACCEPT */]) {
    return false;
  }
  return true;
}
__name(areToolCallStatsEqual, "areToolCallStatsEqual");
function areMetricsEqual(a, b) {
  if (a === b) return true;
  if (!a || !b) return false;
  if (a.files.totalLinesAdded !== b.files.totalLinesAdded || a.files.totalLinesRemoved !== b.files.totalLinesRemoved) {
    return false;
  }
  const toolsA = a.tools;
  const toolsB = b.tools;
  if (toolsA.totalCalls !== toolsB.totalCalls || toolsA.totalSuccess !== toolsB.totalSuccess || toolsA.totalFail !== toolsB.totalFail || toolsA.totalDurationMs !== toolsB.totalDurationMs) {
    return false;
  }
  if (toolsA.totalDecisions["accept" /* ACCEPT */] !== toolsB.totalDecisions["accept" /* ACCEPT */] || toolsA.totalDecisions["reject" /* REJECT */] !== toolsB.totalDecisions["reject" /* REJECT */] || toolsA.totalDecisions["modify" /* MODIFY */] !== toolsB.totalDecisions["modify" /* MODIFY */] || toolsA.totalDecisions["auto_accept" /* AUTO_ACCEPT */] !== toolsB.totalDecisions["auto_accept" /* AUTO_ACCEPT */]) {
    return false;
  }
  const toolsByNameAKeys = Object.keys(toolsA.byName);
  const toolsByNameBKeys = Object.keys(toolsB.byName);
  if (toolsByNameAKeys.length !== toolsByNameBKeys.length) return false;
  for (const key of toolsByNameAKeys) {
    const toolA = toolsA.byName[key];
    const toolB = toolsB.byName[key];
    if (!toolB || !areToolCallStatsEqual(toolA, toolB)) {
      return false;
    }
  }
  const modelsAKeys = Object.keys(a.models);
  const modelsBKeys = Object.keys(b.models);
  if (modelsAKeys.length !== modelsBKeys.length) return false;
  for (const key of modelsAKeys) {
    if (!b.models[key] || !areModelMetricsEqual(a.models[key], b.models[key])) {
      return false;
    }
  }
  return true;
}
__name(areMetricsEqual, "areMetricsEqual");
var SessionStatsContext = (0, import_react65.createContext)(
  void 0
);
var SessionStatsProvider = /* @__PURE__ */ __name(({
  children
}) => {
  const [stats, setStats] = (0, import_react65.useState)({
    sessionId,
    sessionStartTime: /* @__PURE__ */ new Date(),
    metrics: uiTelemetryService.getMetrics(),
    lastPromptTokenCount: 0,
    promptCount: 0
  });
  (0, import_react65.useEffect)(() => {
    const handleUpdate2 = /* @__PURE__ */ __name(({
      metrics: metrics2,
      lastPromptTokenCount
    }) => {
      setStats((prevState) => {
        if (prevState.lastPromptTokenCount === lastPromptTokenCount && areMetricsEqual(prevState.metrics, metrics2)) {
          return prevState;
        }
        return {
          ...prevState,
          metrics: metrics2,
          lastPromptTokenCount
        };
      });
    }, "handleUpdate");
    uiTelemetryService.on("update", handleUpdate2);
    handleUpdate2({
      metrics: uiTelemetryService.getMetrics(),
      lastPromptTokenCount: uiTelemetryService.getLastPromptTokenCount()
    });
    return () => {
      uiTelemetryService.off("update", handleUpdate2);
    };
  }, []);
  const startNewPrompt = (0, import_react65.useCallback)(() => {
    setStats((prevState) => ({
      ...prevState,
      promptCount: prevState.promptCount + 1
    }));
  }, []);
  const getPromptCount = (0, import_react65.useCallback)(
    () => stats.promptCount,
    [stats.promptCount]
  );
  const value = (0, import_react65.useMemo)(
    () => ({
      stats,
      startNewPrompt,
      getPromptCount
    }),
    [stats, startNewPrompt, getPromptCount]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(SessionStatsContext.Provider, { value, children });
}, "SessionStatsProvider");
var useSessionStats = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react65.useContext)(SessionStatsContext);
  if (context2 === void 0) {
    throw new Error(
      "useSessionStats must be used within a SessionStatsProvider"
    );
  }
  return context2;
}, "useSessionStats");

// packages/cli/src/ui/utils/displayUtils.ts
init_esbuild_shims();
var TOOL_SUCCESS_RATE_HIGH = 95;
var TOOL_SUCCESS_RATE_MEDIUM = 85;
var USER_AGREEMENT_RATE_HIGH = 75;
var USER_AGREEMENT_RATE_MEDIUM = 45;
var getStatusColor2 = /* @__PURE__ */ __name((value, thresholds, options2 = {}) => {
  if (value >= thresholds.green) {
    return theme.status.success;
  }
  if (value >= thresholds.yellow) {
    return theme.status.warning;
  }
  if (thresholds.red != null && value >= thresholds.red) {
    return theme.status.error;
  }
  return options2.defaultColor ?? theme.status.error;
}, "getStatusColor");

// packages/cli/src/ui/utils/computeStats.ts
init_esbuild_shims();
function calculateErrorRate(metrics2) {
  if (metrics2.api.totalRequests === 0) {
    return 0;
  }
  return metrics2.api.totalErrors / metrics2.api.totalRequests * 100;
}
__name(calculateErrorRate, "calculateErrorRate");
function calculateAverageLatency(metrics2) {
  if (metrics2.api.totalRequests === 0) {
    return 0;
  }
  return metrics2.api.totalLatencyMs / metrics2.api.totalRequests;
}
__name(calculateAverageLatency, "calculateAverageLatency");
function calculateCacheHitRate(metrics2) {
  if (metrics2.tokens.prompt === 0) {
    return 0;
  }
  return metrics2.tokens.cached / metrics2.tokens.prompt * 100;
}
__name(calculateCacheHitRate, "calculateCacheHitRate");
var computeSessionStats = /* @__PURE__ */ __name((metrics2) => {
  const { models, tools, files } = metrics2;
  const totalApiTime = Object.values(models).reduce(
    (acc, model) => acc + model.api.totalLatencyMs,
    0
  );
  const totalToolTime = tools.totalDurationMs;
  const agentActiveTime = totalApiTime + totalToolTime;
  const apiTimePercent = agentActiveTime > 0 ? totalApiTime / agentActiveTime * 100 : 0;
  const toolTimePercent = agentActiveTime > 0 ? totalToolTime / agentActiveTime * 100 : 0;
  const totalCachedTokens = Object.values(models).reduce(
    (acc, model) => acc + model.tokens.cached,
    0
  );
  const totalPromptTokens = Object.values(models).reduce(
    (acc, model) => acc + model.tokens.prompt,
    0
  );
  const cacheEfficiency = totalPromptTokens > 0 ? totalCachedTokens / totalPromptTokens * 100 : 0;
  const totalDecisions = tools.totalDecisions.accept + tools.totalDecisions.reject + tools.totalDecisions.modify;
  const successRate = tools.totalCalls > 0 ? tools.totalSuccess / tools.totalCalls * 100 : 0;
  const agreementRate = totalDecisions > 0 ? tools.totalDecisions.accept / totalDecisions * 100 : 0;
  return {
    totalApiTime,
    totalToolTime,
    agentActiveTime,
    apiTimePercent,
    toolTimePercent,
    cacheEfficiency,
    totalDecisions,
    successRate,
    agreementRate,
    totalCachedTokens,
    totalPromptTokens,
    totalLinesAdded: files.totalLinesAdded,
    totalLinesRemoved: files.totalLinesRemoved
  };
}, "computeSessionStats");

// packages/cli/src/ui/components/StatsDisplay.tsx
var import_jsx_runtime45 = __toESM(require_jsx_runtime(), 1);
var StatRow = /* @__PURE__ */ __name(({ title, children }) => /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Box_default, { children: [
  /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { width: 28, children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { color: theme.text.link, children: title }) }),
  /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { flexGrow: 1, children })
] }), "StatRow");
var SubStatRow = /* @__PURE__ */ __name(({ title, children }) => /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Box_default, { paddingLeft: 2, children: [
  /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { width: 26, children: /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: theme.text.secondary, children: [
    "\xBB ",
    title
  ] }) }),
  /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { flexGrow: 1, children })
] }), "SubStatRow");
var Section = /* @__PURE__ */ __name(({ title, children }) => /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Box_default, { flexDirection: "column", width: "100%", marginBottom: 1, children: [
  /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { bold: true, color: theme.text.primary, children: title }),
  children
] }), "Section");
var ModelUsageTable = /* @__PURE__ */ __name(({ models, totalCachedTokens, cacheEfficiency }) => {
  const nameWidth = 25;
  const requestsWidth = 8;
  const inputTokensWidth = 15;
  const outputTokensWidth = 15;
  return /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { width: nameWidth, children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { bold: true, color: theme.text.primary, children: "Model Usage" }) }),
      /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { width: requestsWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { bold: true, color: theme.text.primary, children: "Reqs" }) }),
      /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { width: inputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { bold: true, color: theme.text.primary, children: "Input Tokens" }) }),
      /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { width: outputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { bold: true, color: theme.text.primary, children: "Output Tokens" }) })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderBottom: true,
        borderTop: false,
        borderLeft: false,
        borderRight: false,
        borderColor: theme.border.default,
        width: nameWidth + requestsWidth + inputTokensWidth + outputTokensWidth
      }
    ),
    Object.entries(models).map(([name3, modelMetrics]) => /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { width: nameWidth, children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { color: theme.text.primary, children: name3.replace("-001", "") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { width: requestsWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { color: theme.text.primary, children: modelMetrics.api.totalRequests }) }),
      /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { width: inputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { color: theme.status.warning, children: modelMetrics.tokens.prompt.toLocaleString() }) }),
      /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { width: outputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { color: theme.status.warning, children: modelMetrics.tokens.candidates.toLocaleString() }) })
    ] }, name3)),
    cacheEfficiency > 0 && /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { color: theme.status.success, children: "Savings Highlight:" }),
        " ",
        totalCachedTokens.toLocaleString(),
        " (",
        cacheEfficiency.toFixed(1),
        "%) of input tokens were served from the cache, reducing costs."
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { height: 1 }),
      /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { color: theme.text.secondary, children: "\xBB Tip: For a full token breakdown, run `/stats model`." })
    ] })
  ] });
}, "ModelUsageTable");
var StatsDisplay = /* @__PURE__ */ __name(({
  duration,
  title
}) => {
  const { stats } = useSessionStats();
  const { metrics: metrics2 } = stats;
  const { models, tools, files } = metrics2;
  const computed = computeSessionStats(metrics2);
  const successThresholds = {
    green: TOOL_SUCCESS_RATE_HIGH,
    yellow: TOOL_SUCCESS_RATE_MEDIUM
  };
  const agreementThresholds = {
    green: USER_AGREEMENT_RATE_HIGH,
    yellow: USER_AGREEMENT_RATE_MEDIUM
  };
  const successColor = getStatusColor2(computed.successRate, successThresholds);
  const agreementColor = getStatusColor2(
    computed.agreementRate,
    agreementThresholds
  );
  const renderTitle = /* @__PURE__ */ __name(() => {
    if (title) {
      return theme.ui.gradient && theme.ui.gradient.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(dist_default4, { colors: theme.ui.gradient, children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { bold: true, color: theme.text.primary, children: title }) }) : /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { bold: true, color: theme.text.accent, children: title });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { bold: true, color: theme.text.accent, children: "Session Stats" });
  }, "renderTitle");
  return /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      children: [
        renderTitle(),
        /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Section, { title: "Interaction Summary", children: [
          /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(StatRow, { title: "Session ID:", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { color: theme.text.primary, children: stats.sessionId }) }),
          /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(StatRow, { title: "Tool Calls:", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: theme.text.primary, children: [
            tools.totalCalls,
            " (",
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: theme.status.success, children: [
              "\u2713 ",
              tools.totalSuccess
            ] }),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: theme.status.error, children: [
              "x ",
              tools.totalFail
            ] }),
            " )"
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(StatRow, { title: "Success Rate:", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: successColor, children: [
            computed.successRate.toFixed(1),
            "%"
          ] }) }),
          computed.totalDecisions > 0 && /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(StatRow, { title: "User Agreement:", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: agreementColor, children: [
            computed.agreementRate.toFixed(1),
            "%",
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: theme.text.secondary, children: [
              "(",
              computed.totalDecisions,
              " reviewed)"
            ] })
          ] }) }),
          files && (files.totalLinesAdded > 0 || files.totalLinesRemoved > 0) && /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(StatRow, { title: "Code Changes:", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: theme.text.primary, children: [
            /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: theme.status.success, children: [
              "+",
              files.totalLinesAdded
            ] }),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: theme.status.error, children: [
              "-",
              files.totalLinesRemoved
            ] })
          ] }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Section, { title: "Performance", children: [
          /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(StatRow, { title: "Wall Time:", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { color: theme.text.primary, children: duration }) }),
          /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(StatRow, { title: "Agent Active:", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { color: theme.text.primary, children: formatDuration(computed.agentActiveTime) }) }),
          /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(SubStatRow, { title: "API Time:", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: theme.text.primary, children: [
            formatDuration(computed.totalApiTime),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: theme.text.secondary, children: [
              "(",
              computed.apiTimePercent.toFixed(1),
              "%)"
            ] })
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(SubStatRow, { title: "Tool Time:", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: theme.text.primary, children: [
            formatDuration(computed.totalToolTime),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: theme.text.secondary, children: [
              "(",
              computed.toolTimePercent.toFixed(1),
              "%)"
            ] })
          ] }) })
        ] }),
        Object.keys(models).length > 0 && /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(
          ModelUsageTable,
          {
            models,
            totalCachedTokens: computed.totalCachedTokens,
            cacheEfficiency: computed.cacheEfficiency
          }
        )
      ]
    }
  );
}, "StatsDisplay");

// packages/cli/src/ui/components/ModelStatsDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime46 = __toESM(require_jsx_runtime(), 1);
var METRIC_COL_WIDTH = 28;
var MODEL_COL_WIDTH = 22;
var StatRow2 = /* @__PURE__ */ __name(({
  title,
  values,
  isSubtle = false,
  isSection = false
}) => /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(Box_default, { children: [
  /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { width: METRIC_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
    Text,
    {
      bold: isSection,
      color: isSection ? theme.text.primary : theme.text.link,
      children: isSubtle ? `  \u21B3 ${title}` : title
    }
  ) }),
  values.map((value, index) => /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { width: MODEL_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text, { color: theme.text.primary, children: value }) }, index))
] }), "StatRow");
var ModelStatsDisplay = /* @__PURE__ */ __name(() => {
  const { stats } = useSessionStats();
  const { models } = stats.metrics;
  const activeModels = Object.entries(models).filter(
    ([, metrics2]) => metrics2.api.totalRequests > 0
  );
  if (activeModels.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        paddingY: 1,
        paddingX: 2,
        children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text, { color: theme.text.primary, children: "No API calls have been made in this session." })
      }
    );
  }
  const modelNames = activeModels.map(([name3]) => name3);
  const getModelValues = /* @__PURE__ */ __name((getter) => activeModels.map(([, metrics2]) => getter(metrics2)), "getModelValues");
  const hasThoughts = activeModels.some(
    ([, metrics2]) => metrics2.tokens.thoughts > 0
  );
  const hasTool = activeModels.some(([, metrics2]) => metrics2.tokens.tool > 0);
  const hasCached = activeModels.some(
    ([, metrics2]) => metrics2.tokens.cached > 0
  );
  return /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text, { bold: true, color: theme.text.accent, children: "Model Stats For Nerds" }),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { width: METRIC_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text, { bold: true, color: theme.text.primary, children: "Metric" }) }),
          modelNames.map((name3) => /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { width: MODEL_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text, { bold: true, color: theme.text.primary, children: name3 }) }, name3))
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
          Box_default,
          {
            borderStyle: "single",
            borderBottom: true,
            borderTop: false,
            borderLeft: false,
            borderRight: false,
            borderColor: theme.border.default
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(StatRow2, { title: "API", values: [], isSection: true }),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
          StatRow2,
          {
            title: "Requests",
            values: getModelValues((m) => m.api.totalRequests.toLocaleString())
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
          StatRow2,
          {
            title: "Errors",
            values: getModelValues((m) => {
              const errorRate = calculateErrorRate(m);
              return /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
                Text,
                {
                  color: m.api.totalErrors > 0 ? theme.status.error : theme.text.primary,
                  children: [
                    m.api.totalErrors.toLocaleString(),
                    " (",
                    errorRate.toFixed(1),
                    "%)"
                  ]
                }
              );
            })
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
          StatRow2,
          {
            title: "Avg Latency",
            values: getModelValues((m) => {
              const avgLatency = calculateAverageLatency(m);
              return formatDuration(avgLatency);
            })
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(StatRow2, { title: "Tokens", values: [], isSection: true }),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
          StatRow2,
          {
            title: "Total",
            values: getModelValues((m) => /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text, { color: theme.status.warning, children: m.tokens.total.toLocaleString() }))
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
          StatRow2,
          {
            title: "Prompt",
            isSubtle: true,
            values: getModelValues((m) => m.tokens.prompt.toLocaleString())
          }
        ),
        hasCached && /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
          StatRow2,
          {
            title: "Cached",
            isSubtle: true,
            values: getModelValues((m) => {
              const cacheHitRate = calculateCacheHitRate(m);
              return /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(Text, { color: theme.status.success, children: [
                m.tokens.cached.toLocaleString(),
                " (",
                cacheHitRate.toFixed(1),
                "%)"
              ] });
            })
          }
        ),
        hasThoughts && /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
          StatRow2,
          {
            title: "Thoughts",
            isSubtle: true,
            values: getModelValues((m) => m.tokens.thoughts.toLocaleString())
          }
        ),
        hasTool && /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
          StatRow2,
          {
            title: "Tool",
            isSubtle: true,
            values: getModelValues((m) => m.tokens.tool.toLocaleString())
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
          StatRow2,
          {
            title: "Output",
            isSubtle: true,
            values: getModelValues((m) => m.tokens.candidates.toLocaleString())
          }
        )
      ]
    }
  );
}, "ModelStatsDisplay");

// packages/cli/src/ui/components/ToolStatsDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime47 = __toESM(require_jsx_runtime(), 1);
var TOOL_NAME_COL_WIDTH = 25;
var CALLS_COL_WIDTH = 8;
var SUCCESS_RATE_COL_WIDTH = 15;
var AVG_DURATION_COL_WIDTH = 15;
var StatRow3 = /* @__PURE__ */ __name(({ name: name3, stats }) => {
  const successRate = stats.count > 0 ? stats.success / stats.count * 100 : 0;
  const avgDuration = stats.count > 0 ? stats.durationMs / stats.count : 0;
  const successColor = getStatusColor2(successRate, {
    green: TOOL_SUCCESS_RATE_HIGH,
    yellow: TOOL_SUCCESS_RATE_MEDIUM
  });
  return /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(Box_default, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { width: TOOL_NAME_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.link, children: name3 }) }),
    /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { width: CALLS_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.primary, children: stats.count }) }),
    /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { width: SUCCESS_RATE_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(Text, { color: successColor, children: [
      successRate.toFixed(1),
      "%"
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.primary, children: formatDuration(avgDuration) }) })
  ] });
}, "StatRow");
var ToolStatsDisplay = /* @__PURE__ */ __name(() => {
  const { stats } = useSessionStats();
  const { tools } = stats.metrics;
  const activeTools = Object.entries(tools.byName).filter(
    ([, metrics2]) => metrics2.count > 0
  );
  if (activeTools.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        paddingY: 1,
        paddingX: 2,
        children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.primary, children: "No tool calls have been made in this session." })
      }
    );
  }
  const totalDecisions = Object.values(tools.byName).reduce(
    (acc, tool) => {
      acc.accept += tool.decisions.accept;
      acc.reject += tool.decisions.reject;
      acc.modify += tool.decisions.modify;
      return acc;
    },
    { accept: 0, reject: 0, modify: 0 }
  );
  const totalReviewed = totalDecisions.accept + totalDecisions.reject + totalDecisions.modify;
  const agreementRate = totalReviewed > 0 ? totalDecisions.accept / totalReviewed * 100 : 0;
  const agreementColor = getStatusColor2(agreementRate, {
    green: USER_AGREEMENT_RATE_HIGH,
    yellow: USER_AGREEMENT_RATE_MEDIUM
  });
  return /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      width: 70,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { bold: true, color: theme.text.accent, children: "Tool Stats For Nerds" }),
        /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { width: TOOL_NAME_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { bold: true, color: theme.text.primary, children: "Tool Name" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { width: CALLS_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { bold: true, color: theme.text.primary, children: "Calls" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { width: SUCCESS_RATE_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { bold: true, color: theme.text.primary, children: "Success Rate" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { bold: true, color: theme.text.primary, children: "Avg Duration" }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(
          Box_default,
          {
            borderStyle: "single",
            borderBottom: true,
            borderTop: false,
            borderLeft: false,
            borderRight: false,
            borderColor: theme.border.default,
            width: "100%"
          }
        ),
        activeTools.map(([name3, stats2]) => /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(StatRow3, { name: name3, stats: stats2 }, name3)),
        /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { bold: true, color: theme.text.primary, children: "User Decision Summary" }),
        /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.link, children: "Total Reviewed Suggestions:" })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.primary, children: totalReviewed }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.primary, children: " \xBB Accepted:" })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.status.success, children: totalDecisions.accept }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.primary, children: " \xBB Rejected:" })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.status.error, children: totalDecisions.reject }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.primary, children: " \xBB Modified:" })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.status.warning, children: totalDecisions.modify }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(
          Box_default,
          {
            borderStyle: "single",
            borderBottom: true,
            borderTop: false,
            borderLeft: false,
            borderRight: false,
            borderColor: theme.border.default,
            width: "100%"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.primary, children: " Overall Agreement Rate:" })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { bold: true, color: totalReviewed > 0 ? agreementColor : void 0, children: totalReviewed > 0 ? `${agreementRate.toFixed(1)}%` : "--" }) })
        ] })
      ]
    }
  );
}, "ToolStatsDisplay");

// packages/cli/src/ui/components/SessionSummaryDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime48 = __toESM(require_jsx_runtime(), 1);
var SessionSummaryDisplay = /* @__PURE__ */ __name(({
  duration
}) => /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(StatsDisplay, { title: "Agent powering down. Goodbye!", duration }), "SessionSummaryDisplay");

// packages/cli/src/ui/components/Help.tsx
init_esbuild_shims();

// packages/cli/src/ui/commands/types.ts
init_esbuild_shims();

// packages/cli/src/ui/components/Help.tsx
var import_jsx_runtime49 = __toESM(require_jsx_runtime(), 1);
var Help = /* @__PURE__ */ __name(({ commands }) => /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(
  Box_default,
  {
    flexDirection: "column",
    marginBottom: 1,
    borderColor: theme.border.default,
    borderStyle: "round",
    padding: 1,
    children: [
      /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.primary, children: "Basics:" }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.accent, children: "Add context" }),
        ": Use",
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.accent, children: "@" }),
        " ",
        "to specify files for context (e.g.,",
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.accent, children: "@src/myFile.ts" }),
        ") to target specific files or folders."
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.accent, children: "Shell mode" }),
        ": Execute shell commands via",
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.accent, children: "!" }),
        " ",
        "(e.g.,",
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.accent, children: "!npm run start" }),
        ") or use natural language (e.g.",
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.accent, children: "start server" }),
        ")."
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Box_default, { height: 1 }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.primary, children: "Commands:" }),
      commands.filter((command2) => command2.description && !command2.hidden).map((command2) => /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Box_default, { flexDirection: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.primary, children: [
          /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { bold: true, color: theme.text.accent, children: [
            " ",
            "/",
            command2.name
          ] }),
          command2.kind === "mcp-prompt" /* MCP_PROMPT */ && /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { color: theme.text.secondary, children: " [MCP]" }),
          command2.description && " - " + command2.description
        ] }),
        command2.subCommands && command2.subCommands.filter((subCommand) => !subCommand.hidden).map((subCommand) => /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.primary, children: [
          /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { bold: true, color: theme.text.accent, children: [
            "   ",
            subCommand.name
          ] }),
          subCommand.description && " - " + subCommand.description
        ] }, subCommand.name))
      ] }, command2.name)),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { bold: true, color: theme.text.accent, children: [
          " ",
          "!",
          " "
        ] }),
        "- shell command"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { color: theme.text.secondary, children: "[MCP]" }),
        " - Model Context Protocol command (from external servers)"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Box_default, { height: 1 }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.primary, children: "Keyboard Shortcuts:" }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.accent, children: "Alt+Left/Right" }),
        " ",
        "- Jump through words in the input"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.accent, children: "Ctrl+C" }),
        " ",
        "- Close dialogs, cancel requests, or quit application"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.accent, children: process.platform === "win32" ? "Ctrl+Enter" : "Ctrl+J" }),
        " ",
        process.platform === "linux" ? "- New line (Alt+Enter works for certain linux distros)" : "- New line"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.accent, children: "Ctrl+L" }),
        " ",
        "- Clear the screen"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.accent, children: process.platform === "darwin" ? "Ctrl+X / Meta+Enter" : "Ctrl+X" }),
        " ",
        "- Open input in external editor"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.accent, children: "Enter" }),
        " ",
        "- Send message"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.accent, children: "Esc" }),
        " ",
        "- Cancel operation / Clear input (double press)"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.accent, children: "Shift+Tab" }),
        " ",
        "- Cycle approval modes"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.accent, children: "Up/Down" }),
        " ",
        "- Cycle through your prompt history"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Box_default, { height: 1 }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.primary, children: [
        "For a full list of shortcuts, see",
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { bold: true, color: theme.text.accent, children: "docs/keyboard-shortcuts.md" })
      ] })
    ]
  }
), "Help");

// packages/cli/src/ui/components/views/ExtensionsList.tsx
init_esbuild_shims();

// packages/cli/src/ui/state/extensions.ts
init_esbuild_shims();
var initialExtensionUpdatesState = {
  extensionStatuses: /* @__PURE__ */ new Map(),
  batchChecksInProgress: 0
};
function extensionUpdatesReducer(state, action) {
  switch (action.type) {
    case "SET_STATE": {
      const existing = state.extensionStatuses.get(action.payload.name);
      if (existing?.status === action.payload.state) {
        return state;
      }
      const newStatuses = new Map(state.extensionStatuses);
      newStatuses.set(action.payload.name, {
        status: action.payload.state,
        processed: false
      });
      return { ...state, extensionStatuses: newStatuses };
    }
    case "SET_PROCESSED": {
      const existing = state.extensionStatuses.get(action.payload.name);
      if (!existing || existing.processed === action.payload.processed) {
        return state;
      }
      const newStatuses = new Map(state.extensionStatuses);
      newStatuses.set(action.payload.name, {
        ...existing,
        processed: action.payload.processed
      });
      return { ...state, extensionStatuses: newStatuses };
    }
    case "BATCH_CHECK_START":
      return {
        ...state,
        batchChecksInProgress: state.batchChecksInProgress + 1
      };
    case "BATCH_CHECK_END":
      return {
        ...state,
        batchChecksInProgress: state.batchChecksInProgress - 1
      };
    default:
      checkExhaustive(action);
  }
}
__name(extensionUpdatesReducer, "extensionUpdatesReducer");

// packages/cli/src/ui/components/views/ExtensionsList.tsx
var import_jsx_runtime50 = __toESM(require_jsx_runtime(), 1);
var ExtensionsList = /* @__PURE__ */ __name(() => {
  const { commandContext, extensionsUpdateState } = useUIState();
  const allExtensions = commandContext.services.config.getExtensions();
  const settings = commandContext.services.settings;
  const disabledExtensions = settings.merged.extensions?.disabled ?? [];
  if (allExtensions.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { children: "No extensions installed." });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, marginBottom: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { children: "Installed extensions:" }),
    /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { flexDirection: "column", paddingLeft: 2, children: allExtensions.map((ext2) => {
      const state = extensionsUpdateState.get(ext2.name);
      const isActive = !disabledExtensions.includes(ext2.name);
      const activeString = isActive ? "active" : "disabled";
      let stateColor = "gray";
      const stateText = state || "unknown state";
      switch (state) {
        case "checking for updates" /* CHECKING_FOR_UPDATES */:
        case "updating" /* UPDATING */:
          stateColor = "cyan";
          break;
        case "update available" /* UPDATE_AVAILABLE */:
        case "updated, needs restart" /* UPDATED_NEEDS_RESTART */:
          stateColor = "yellow";
          break;
        case "error" /* ERROR */:
          stateColor = "red";
          break;
        case "up to date" /* UP_TO_DATE */:
        case "not updatable" /* NOT_UPDATABLE */:
          stateColor = "green";
          break;
        default:
          console.error(`Unhandled ExtensionUpdateState ${state}`);
          break;
      }
      return /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { color: "cyan", children: `${ext2.name} (v${ext2.version})` }),
        ` - ${activeString}`,
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { color: stateColor, children: ` (${stateText})` })
      ] }) }, ext2.name);
    }) })
  ] });
}, "ExtensionsList");

// packages/cli/src/ui/components/views/ToolsList.tsx
init_esbuild_shims();
var import_jsx_runtime51 = __toESM(require_jsx_runtime(), 1);
var ToolsList = /* @__PURE__ */ __name(({
  tools,
  showDescriptions,
  terminalWidth
}) => /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
  /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Text, { bold: true, color: theme.text.primary, children: "Available Qwen Code CLI tools:" }),
  /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Box_default, { height: 1 }),
  tools.length > 0 ? tools.map((tool) => /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Text, { color: theme.text.primary, children: [
      "  ",
      "- "
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Text, { bold: true, color: theme.text.accent, children: [
        tool.displayName,
        showDescriptions ? ` (${tool.name})` : ""
      ] }),
      showDescriptions && tool.description && /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(
        MarkdownDisplay,
        {
          terminalWidth,
          text: tool.description,
          isPending: false
        }
      )
    ] })
  ] }, tool.name)) : /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Text, { color: theme.text.primary, children: " No tools available" })
] }), "ToolsList");

// packages/cli/src/ui/components/views/McpStatus.tsx
init_esbuild_shims();
var import_jsx_runtime52 = __toESM(require_jsx_runtime(), 1);
var McpStatus = /* @__PURE__ */ __name(({
  servers,
  tools,
  prompts,
  blockedServers,
  serverStatus,
  authStatus,
  discoveryInProgress,
  connectingServers,
  showDescriptions,
  showSchema,
  showTips
}) => {
  const serverNames = Object.keys(servers);
  if (serverNames.length === 0 && blockedServers.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { children: "No MCP servers configured." }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { children: [
        "Please view MCP documentation in your browser:",
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.link, children: "https://goo.gle/gemini-cli-docs-mcp" }),
        " ",
        "or use the cli /docs command"
      ] })
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", children: [
    discoveryInProgress && /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { color: theme.status.warning, children: [
        "\u23F3 MCP servers are starting up (",
        connectingServers.length,
        " ",
        "initializing)..."
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.primary, children: "Note: First startup may take longer. Tool availability will update automatically." })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { bold: true, children: "Configured MCP servers:" }),
    /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { height: 1 }),
    serverNames.map((serverName) => {
      const server = servers[serverName];
      const serverTools = tools.filter(
        (tool) => tool.serverName === serverName
      );
      const serverPrompts = prompts.filter(
        (prompt) => prompt.serverName === serverName
      );
      const originalStatus = serverStatus(serverName);
      const hasCachedItems = serverTools.length > 0 || serverPrompts.length > 0;
      const status = originalStatus === MCPServerStatus.DISCONNECTED && hasCachedItems ? MCPServerStatus.CONNECTED : originalStatus;
      let statusIndicator = "";
      let statusText = "";
      let statusColor = theme.text.primary;
      switch (status) {
        case MCPServerStatus.CONNECTED:
          statusIndicator = "\u{1F7E2}";
          statusText = "Ready";
          statusColor = theme.status.success;
          break;
        case MCPServerStatus.CONNECTING:
          statusIndicator = "\u{1F504}";
          statusText = "Starting... (first startup may take longer)";
          statusColor = theme.status.warning;
          break;
        case MCPServerStatus.DISCONNECTED:
        default:
          statusIndicator = "\u{1F534}";
          statusText = "Disconnected";
          statusColor = theme.status.error;
          break;
      }
      let serverDisplayName = serverName;
      if (server.extensionName) {
        serverDisplayName += ` (from ${server.extensionName})`;
      }
      const toolCount = serverTools.length;
      const promptCount = serverPrompts.length;
      const parts = [];
      if (toolCount > 0) {
        parts.push(`${toolCount} ${toolCount === 1 ? "tool" : "tools"}`);
      }
      if (promptCount > 0) {
        parts.push(
          `${promptCount} ${promptCount === 1 ? "prompt" : "prompts"}`
        );
      }
      const serverAuthStatus = authStatus[serverName];
      let authStatusNode = null;
      if (serverAuthStatus === "authenticated") {
        authStatusNode = /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { children: " (OAuth)" });
      } else if (serverAuthStatus === "expired") {
        authStatusNode = /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.status.error, children: " (OAuth expired)" });
      } else if (serverAuthStatus === "unauthenticated") {
        authStatusNode = /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.status.warning, children: " (OAuth not authenticated)" });
      }
      return /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { color: statusColor, children: [
            statusIndicator,
            " "
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { bold: true, children: serverDisplayName }),
          /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { children: [
            " - ",
            statusText,
            status === MCPServerStatus.CONNECTED && parts.length > 0 && ` (${parts.join(", ")})`
          ] }),
          authStatusNode
        ] }),
        status === MCPServerStatus.CONNECTING && /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { children: " (tools and prompts will appear when ready)" }),
        status === MCPServerStatus.DISCONNECTED && toolCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { children: [
          " (",
          toolCount,
          " tools cached)"
        ] }),
        showDescriptions && server?.description && /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.secondary, children: server.description.trim() }),
        serverTools.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", marginLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.primary, children: "Tools:" }),
          serverTools.map((tool) => {
            const schemaContent = showSchema && tool.schema && (tool.schema.parametersJsonSchema || tool.schema.parameters) ? JSON.stringify(
              tool.schema.parametersJsonSchema ?? tool.schema.parameters,
              null,
              2
            ) : null;
            return /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", children: [
              /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { children: [
                "- ",
                /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.primary, children: tool.name })
              ] }),
              showDescriptions && tool.description && /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.secondary, children: tool.description.trim() }) }),
              schemaContent && /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", marginLeft: 4, children: [
                /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.secondary, children: "Parameters:" }),
                /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.secondary, children: schemaContent })
              ] })
            ] }, tool.name);
          })
        ] }),
        serverPrompts.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", marginLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.primary, children: "Prompts:" }),
          serverPrompts.map((prompt) => /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { children: [
              "- ",
              /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.primary, children: prompt.name })
            ] }),
            showDescriptions && prompt.description && /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.primary, children: prompt.description.trim() }) })
          ] }, prompt.name))
        ] })
      ] }, serverName);
    }),
    blockedServers.map((server) => /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.status.error, children: "\u{1F534} " }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { bold: true, children: [
        server.name,
        server.extensionName ? ` (from ${server.extensionName})` : ""
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { children: " - Blocked" })
    ] }, server.name)),
    showTips && /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.accent, children: "\u{1F4A1} Tips:" }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { children: [
        "  ",
        "- Use ",
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.accent, children: "/mcp desc" }),
        " to show server and tool descriptions"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { children: [
        "  ",
        "- Use ",
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.accent, children: "/mcp schema" }),
        " to show tool parameter schemas"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { children: [
        "  ",
        "- Use ",
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.accent, children: "/mcp nodesc" }),
        " to hide descriptions"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { children: [
        "  ",
        "- Use",
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.accent, children: "/mcp auth <server-name>" }),
        " ",
        "to authenticate with OAuth-enabled servers"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { children: [
        "  ",
        "- Press ",
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.accent, children: "Ctrl+T" }),
        " to toggle tool descriptions on/off"
      ] })
    ] })
  ] });
}, "McpStatus");

// packages/cli/src/ui/components/HistoryItemDisplay.tsx
var import_jsx_runtime53 = __toESM(require_jsx_runtime(), 1);
var HistoryItemDisplayComponent = /* @__PURE__ */ __name(({
  item,
  availableTerminalHeight,
  terminalWidth,
  isPending,
  commands,
  isFocused = true,
  activeShellPtyId,
  embeddedShellFocused,
  availableTerminalHeightGemini
}) => {
  const itemForDisplay = (0, import_react66.useMemo)(() => escapeAnsiCtrlCodes(item), [item]);
  return /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { flexDirection: "column", children: [
    itemForDisplay.type === "user" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(UserMessage, { text: itemForDisplay.text }),
    itemForDisplay.type === "user_shell" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(UserShellMessage, { text: itemForDisplay.text }),
    itemForDisplay.type === "gemini" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
      GeminiMessage,
      {
        text: itemForDisplay.text,
        isPending,
        availableTerminalHeight: availableTerminalHeightGemini ?? availableTerminalHeight,
        terminalWidth
      }
    ),
    itemForDisplay.type === "gemini_content" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
      GeminiMessageContent,
      {
        text: itemForDisplay.text,
        isPending,
        availableTerminalHeight: availableTerminalHeightGemini ?? availableTerminalHeight,
        terminalWidth
      }
    ),
    itemForDisplay.type === "info" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(InfoMessage, { text: itemForDisplay.text }),
    itemForDisplay.type === "warning" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(WarningMessage, { text: itemForDisplay.text }),
    itemForDisplay.type === "error" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(ErrorMessage, { text: itemForDisplay.text }),
    itemForDisplay.type === "about" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(AboutBox, { ...itemForDisplay.systemInfo }),
    itemForDisplay.type === "help" && commands && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Help, { commands }),
    itemForDisplay.type === "stats" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(StatsDisplay, { duration: itemForDisplay.duration }),
    itemForDisplay.type === "model_stats" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(ModelStatsDisplay, {}),
    itemForDisplay.type === "tool_stats" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(ToolStatsDisplay, {}),
    itemForDisplay.type === "quit" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(SessionSummaryDisplay, { duration: itemForDisplay.duration }),
    itemForDisplay.type === "quit_confirmation" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(SessionSummaryDisplay, { duration: itemForDisplay.duration }),
    itemForDisplay.type === "tool_group" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
      ToolGroupMessage,
      {
        toolCalls: itemForDisplay.tools,
        groupId: itemForDisplay.id,
        availableTerminalHeight,
        terminalWidth,
        isFocused,
        activeShellPtyId,
        embeddedShellFocused
      }
    ),
    itemForDisplay.type === "compression" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(CompressionMessage, { compression: itemForDisplay.compression }),
    item.type === "summary" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(SummaryMessage, { summary: item.summary }),
    itemForDisplay.type === "extensions_list" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(ExtensionsList, {}),
    itemForDisplay.type === "tools_list" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
      ToolsList,
      {
        terminalWidth,
        tools: itemForDisplay.tools,
        showDescriptions: itemForDisplay.showDescriptions
      }
    ),
    itemForDisplay.type === "mcp_status" && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(McpStatus, { ...itemForDisplay, serverStatus: getMCPServerStatus })
  ] }, itemForDisplay.id);
}, "HistoryItemDisplayComponent");

// packages/cli/src/ui/components/QuittingDisplay.tsx
var import_jsx_runtime54 = __toESM(require_jsx_runtime(), 1);
var QuittingDisplay = /* @__PURE__ */ __name(() => {
  const uiState = useUIState();
  const { rows: terminalHeight, columns: terminalWidth } = useTerminalSize();
  const availableTerminalHeight = terminalHeight;
  if (!uiState.quittingMessages) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Box_default, { flexDirection: "column", marginBottom: 1, children: uiState.quittingMessages.map((item) => /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(
    HistoryItemDisplayComponent,
    {
      availableTerminalHeight: uiState.constrainHeight ? availableTerminalHeight : void 0,
      terminalWidth,
      item,
      isPending: false
    },
    item.id
  )) });
}, "QuittingDisplay");

// packages/cli/src/ui/layouts/ScreenReaderAppLayout.tsx
init_esbuild_shims();

// packages/cli/src/ui/components/Notifications.tsx
init_esbuild_shims();

// packages/cli/src/ui/contexts/AppContext.tsx
init_esbuild_shims();
var import_react67 = __toESM(require_react(), 1);
var AppContext2 = (0, import_react67.createContext)(null);
var useAppContext = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react67.useContext)(AppContext2);
  if (!context2) {
    throw new Error("useAppContext must be used within an AppProvider");
  }
  return context2;
}, "useAppContext");

// packages/cli/src/ui/components/UpdateNotification.tsx
init_esbuild_shims();
var import_jsx_runtime55 = __toESM(require_jsx_runtime(), 1);
var UpdateNotification = /* @__PURE__ */ __name(({ message }) => /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(
  Box_default,
  {
    borderStyle: "round",
    borderColor: theme.status.warning,
    paddingX: 1,
    marginY: 1,
    children: /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { color: theme.status.warning, children: message })
  }
), "UpdateNotification");

// packages/cli/src/ui/components/Notifications.tsx
var import_jsx_runtime56 = __toESM(require_jsx_runtime(), 1);
var Notifications = /* @__PURE__ */ __name(() => {
  const { startupWarnings } = useAppContext();
  const { initError, streamingState, updateInfo } = useUIState();
  const showStartupWarnings = startupWarnings.length > 0;
  const showInitError = initError && streamingState !== "responding" /* Responding */;
  if (!showStartupWarnings && !showInitError && !updateInfo) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(import_jsx_runtime56.Fragment, { children: [
    updateInfo && /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(UpdateNotification, { message: updateInfo.message }),
    showStartupWarnings && /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.status.warning,
        paddingX: 1,
        marginY: 1,
        flexDirection: "column",
        children: startupWarnings.map((warning, index) => /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text, { color: theme.status.warning, children: warning }, index))
      }
    ),
    showInitError && /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.status.error,
        paddingX: 1,
        marginBottom: 1,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text, { color: theme.status.error, children: [
            "Initialization Error: ",
            initError
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text, { color: theme.status.error, children: [
            " ",
            "Please check API key and configuration."
          ] })
        ]
      }
    )
  ] });
}, "Notifications");

// packages/cli/src/ui/components/MainContent.tsx
init_esbuild_shims();

// packages/cli/src/ui/components/ShowMoreLines.tsx
init_esbuild_shims();
var import_jsx_runtime57 = __toESM(require_jsx_runtime(), 1);
var ShowMoreLines = /* @__PURE__ */ __name(({ constrainHeight }) => {
  const overflowState = useOverflowState();
  const streamingState = useStreamingContext();
  if (overflowState === void 0 || overflowState.overflowingIds.size === 0 || !constrainHeight || !(streamingState === "idle" /* Idle */ || streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */)) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(Text, { color: theme.text.secondary, wrap: "truncate", children: "Press ctrl-s to show more lines" }) });
}, "ShowMoreLines");

// packages/cli/src/ui/components/AppHeader.tsx
init_esbuild_shims();

// packages/cli/src/ui/components/Header.tsx
init_esbuild_shims();

// packages/cli/src/ui/components/AsciiArt.ts
init_esbuild_shims();
var shortAsciiLogo = `
 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557    \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2557   \u2588\u2588\u2557
\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551    \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2588\u2588\u2557  \u2588\u2588\u2551
\u2588\u2588\u2551   \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557  \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551
\u2588\u2588\u2551\u2584\u2584 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D  \u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551
\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2554\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551
 \u255A\u2550\u2550\u2580\u2580\u2550\u255D  \u255A\u2550\u2550\u255D\u255A\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D  \u255A\u2550\u2550\u2550\u255D                                     
`;
var longAsciiLogo = `
\u2588\u2588\u2557       \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557    \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2557   \u2588\u2588\u2557
\u255A\u2588\u2588\u2557     \u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551    \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2588\u2588\u2557  \u2588\u2588\u2551
 \u255A\u2588\u2588\u2557    \u2588\u2588\u2551   \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557  \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551
 \u2588\u2588\u2554\u255D    \u2588\u2588\u2551\u2584\u2584 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D  \u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551
\u2588\u2588\u2554\u255D     \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2554\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551
\u255A\u2550\u255D       \u255A\u2550\u2550\u2580\u2580\u2550\u255D  \u255A\u2550\u2550\u255D\u255A\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D  \u255A\u2550\u2550\u2550\u255D
`;
var tinyAsciiLogo = `
 \u2588\u2588\u2588         \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 
\u2591\u2591\u2591\u2588\u2588\u2588      \u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588
  \u2591\u2591\u2591\u2588\u2588\u2588   \u2588\u2588\u2588     \u2591\u2591\u2591 
    \u2591\u2591\u2591\u2588\u2588\u2588\u2591\u2588\u2588\u2588         
     \u2588\u2588\u2588\u2591 \u2591\u2588\u2588\u2588    \u2588\u2588\u2588\u2588\u2588
   \u2588\u2588\u2588\u2591   \u2591\u2591\u2588\u2588\u2588  \u2591\u2591\u2588\u2588\u2588 
 \u2588\u2588\u2588\u2591      \u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 
\u2591\u2591\u2591         \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591  
`;

// packages/cli/src/ui/components/Header.tsx
var import_jsx_runtime58 = __toESM(require_jsx_runtime(), 1);
var Header = /* @__PURE__ */ __name(({
  customAsciiArt,
  version: version2,
  nightly
}) => {
  const { columns: terminalWidth } = useTerminalSize();
  let displayTitle;
  const widthOfLongLogo = getAsciiArtWidth(longAsciiLogo);
  const widthOfShortLogo = getAsciiArtWidth(shortAsciiLogo);
  if (customAsciiArt) {
    displayTitle = customAsciiArt;
  } else if (terminalWidth >= widthOfLongLogo) {
    displayTitle = longAsciiLogo;
  } else if (terminalWidth >= widthOfShortLogo) {
    displayTitle = shortAsciiLogo;
  } else {
    displayTitle = tinyAsciiLogo;
  }
  const artWidth = getAsciiArtWidth(displayTitle);
  return /* @__PURE__ */ (0, import_jsx_runtime58.jsxs)(
    Box_default,
    {
      alignItems: "flex-start",
      width: artWidth,
      flexShrink: 0,
      flexDirection: "column",
      children: [
        theme.ui.gradient ? /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(dist_default4, { colors: theme.ui.gradient, children: /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(Text, { children: displayTitle }) }) : /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(Text, { children: displayTitle }),
        nightly && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(Box_default, { width: "100%", flexDirection: "row", justifyContent: "flex-end", children: theme.ui.gradient ? /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(dist_default4, { colors: theme.ui.gradient, children: /* @__PURE__ */ (0, import_jsx_runtime58.jsxs)(Text, { children: [
          "v",
          version2
        ] }) }) : /* @__PURE__ */ (0, import_jsx_runtime58.jsxs)(Text, { children: [
          "v",
          version2
        ] }) })
      ]
    }
  );
}, "Header");

// packages/cli/src/ui/components/Tips.tsx
init_esbuild_shims();
var import_jsx_runtime59 = __toESM(require_jsx_runtime(), 1);
var Tips = /* @__PURE__ */ __name(({ config }) => {
  const geminiMdFileCount = config.getGeminiMdFileCount();
  return /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Text, { color: theme.text.primary, children: "Tips for getting started:" }),
    /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Text, { color: theme.text.primary, children: "1. Ask questions, edit files, or run commands." }),
    /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Text, { color: theme.text.primary, children: "2. Be specific for the best results." }),
    geminiMdFileCount === 0 && /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)(Text, { color: theme.text.primary, children: [
      "3. Create",
      " ",
      /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Text, { bold: true, color: theme.text.accent, children: "QWEN.md" }),
      " ",
      "files to customize your interactions with Qwen Code."
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)(Text, { color: theme.text.primary, children: [
      geminiMdFileCount === 0 ? "4." : "3.",
      " ",
      /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Text, { bold: true, color: theme.text.accent, children: "/help" }),
      " ",
      "for more information."
    ] })
  ] });
}, "Tips");

// packages/cli/src/ui/components/AppHeader.tsx
var import_jsx_runtime60 = __toESM(require_jsx_runtime(), 1);
var AppHeader = /* @__PURE__ */ __name(({ version: version2 }) => {
  const settings = useSettings();
  const config = useConfig();
  const { nightly } = useUIState();
  return /* @__PURE__ */ (0, import_jsx_runtime60.jsxs)(Box_default, { flexDirection: "column", children: [
    !(settings.merged.ui?.hideBanner || config.getScreenReader()) && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(Header, { version: version2, nightly }),
    !(settings.merged.ui?.hideTips || config.getScreenReader()) && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(Tips, { config })
  ] });
}, "AppHeader");

// packages/cli/src/ui/components/MainContent.tsx
var import_jsx_runtime61 = __toESM(require_jsx_runtime(), 1);
var MAX_GEMINI_MESSAGE_LINES = 65536;
var MainContent = /* @__PURE__ */ __name(() => {
  const { version: version2 } = useAppContext();
  const uiState = useUIState();
  const {
    pendingHistoryItems,
    mainAreaWidth,
    staticAreaMaxItemHeight,
    availableTerminalHeight
  } = uiState;
  return /* @__PURE__ */ (0, import_jsx_runtime61.jsxs)(import_jsx_runtime61.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(
      Static,
      {
        items: [
          /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(AppHeader, { version: version2 }, "app-header"),
          ...uiState.history.map((h) => /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(
            HistoryItemDisplayComponent,
            {
              terminalWidth: mainAreaWidth,
              availableTerminalHeight: staticAreaMaxItemHeight,
              availableTerminalHeightGemini: MAX_GEMINI_MESSAGE_LINES,
              item: h,
              isPending: false,
              commands: uiState.slashCommands
            },
            h.id
          ))
        ],
        children: (item) => item
      },
      uiState.historyRemountKey
    ),
    /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(OverflowProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime61.jsxs)(Box_default, { flexDirection: "column", children: [
      pendingHistoryItems.map((item, i) => /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(
        HistoryItemDisplayComponent,
        {
          availableTerminalHeight: uiState.constrainHeight ? availableTerminalHeight : void 0,
          terminalWidth: mainAreaWidth,
          item: { ...item, id: 0 },
          isPending: true,
          isFocused: !uiState.isEditorDialogOpen,
          activeShellPtyId: uiState.activePtyId,
          embeddedShellFocused: uiState.embeddedShellFocused
        },
        i
      )),
      /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(ShowMoreLines, { constrainHeight: uiState.constrainHeight })
    ] }) })
  ] });
}, "MainContent");

// packages/cli/src/ui/components/DialogManager.tsx
init_esbuild_shims();

// packages/cli/src/ui/IdeIntegrationNudge.tsx
init_esbuild_shims();
var import_jsx_runtime62 = __toESM(require_jsx_runtime(), 1);
function IdeIntegrationNudge({
  ide,
  onComplete
}) {
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onComplete({
          userSelection: "no",
          isExtensionPreInstalled: false
        });
      }
    },
    { isActive: true }
  );
  const { displayName: ideName } = ide;
  const isExtensionPreInstalled = !!process.env["QWEN_CODE_IDE_SERVER_PORT"] && !!process.env["QWEN_CODE_IDE_WORKSPACE_PATH"];
  const OPTIONS = [
    {
      label: "Yes",
      value: {
        userSelection: "yes",
        isExtensionPreInstalled
      },
      key: "Yes"
    },
    {
      label: "No (esc)",
      value: {
        userSelection: "no",
        isExtensionPreInstalled
      },
      key: "No (esc)"
    },
    {
      label: "No, don't ask again",
      value: {
        userSelection: "dismiss",
        isExtensionPreInstalled
      },
      key: "No, don't ask again"
    }
  ];
  const installText = isExtensionPreInstalled ? `If you select Yes, the CLI will have access to your open files and display diffs directly in ${ideName ?? "your editor"}.` : `If you select Yes, we'll install an extension that allows the CLI to access your open files and display diffs directly in ${ideName ?? "your editor"}.`;
  return /* @__PURE__ */ (0, import_jsx_runtime62.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.status.warning,
      padding: 1,
      width: "100%",
      marginLeft: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime62.jsxs)(Box_default, { marginBottom: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime62.jsxs)(Text, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(Text, { color: theme.status.warning, children: "> " }),
            `Do you want to connect ${ideName ?? "your editor"} to Qwen Code?`
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(Text, { color: theme.text.secondary, children: installText })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(RadioButtonSelect, { items: OPTIONS, onSelect: onComplete })
      ]
    }
  );
}
__name(IdeIntegrationNudge, "IdeIntegrationNudge");

// packages/cli/src/ui/components/LoopDetectionConfirmation.tsx
init_esbuild_shims();
var import_jsx_runtime63 = __toESM(require_jsx_runtime(), 1);
function LoopDetectionConfirmation({
  onComplete
}) {
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onComplete({
          userSelection: "keep"
        });
      }
    },
    { isActive: true }
  );
  const OPTIONS = [
    {
      label: "Keep loop detection enabled (esc)",
      value: {
        userSelection: "keep"
      },
      key: "Keep loop detection enabled (esc)"
    },
    {
      label: "Disable loop detection for this session",
      value: {
        userSelection: "disable"
      },
      key: "Disable loop detection for this session"
    }
  ];
  return /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.status.warning,
      width: "100%",
      marginLeft: 1,
      children: /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(Box_default, { paddingX: 1, paddingY: 0, flexDirection: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(Box_default, { minHeight: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Box_default, { minWidth: 3, children: /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text, { color: theme.status.warning, "aria-label": "Loop detected:", children: "?" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(Text, { wrap: "truncate-end", children: [
            /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text, { color: theme.text.primary, bold: true, children: "A potential loop was detected" }),
            " "
          ] }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Box_default, { width: "100%", marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(Box_default, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text, { color: theme.text.secondary, children: "This can happen due to repetitive tool calls or other model behavior. Do you want to keep loop detection enabled or disable it for this session?" }),
          /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(RadioButtonSelect, { items: OPTIONS, onSelect: onComplete }) }),
          /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text, { color: theme.text.secondary, children: 'Note: To disable loop detection checks for all future sessions, set "model.skipLoopDetection" to true in your settings.json.' }) })
        ] }) })
      ] })
    }
  );
}
__name(LoopDetectionConfirmation, "LoopDetectionConfirmation");

// packages/cli/src/ui/components/FolderTrustDialog.tsx
init_esbuild_shims();
var import_react68 = __toESM(require_react(), 1);
import * as process26 from "node:process";
import * as path61 from "node:path";

// packages/cli/src/utils/processUtils.ts
init_esbuild_shims();

// packages/cli/src/utils/cleanup.ts
init_esbuild_shims();
import { promises as fs55 } from "node:fs";
import { join as join25 } from "node:path";
var cleanupFunctions = [];
function registerCleanup(fn) {
  cleanupFunctions.push(fn);
}
__name(registerCleanup, "registerCleanup");
async function runExitCleanup() {
  for (const fn of cleanupFunctions) {
    try {
      await fn();
    } catch (_) {
    }
  }
  cleanupFunctions.length = 0;
}
__name(runExitCleanup, "runExitCleanup");
async function cleanupCheckpoints() {
  const storage = new Storage(process.cwd());
  const tempDir = storage.getProjectTempDir();
  const checkpointsDir = join25(tempDir, "checkpoints");
  try {
    await fs55.rm(checkpointsDir, { recursive: true, force: true });
  } catch {
  }
}
__name(cleanupCheckpoints, "cleanupCheckpoints");

// packages/cli/src/utils/processUtils.ts
var RELAUNCH_EXIT_CODE = 42;
async function relaunchApp() {
  await runExitCleanup();
  process.exit(RELAUNCH_EXIT_CODE);
}
__name(relaunchApp, "relaunchApp");

// packages/cli/src/ui/components/FolderTrustDialog.tsx
var import_jsx_runtime64 = __toESM(require_jsx_runtime(), 1);
var FolderTrustDialog = /* @__PURE__ */ __name(({
  onSelect,
  isRestarting
}) => {
  (0, import_react68.useEffect)(() => {
    const doRelaunch = /* @__PURE__ */ __name(async () => {
      if (isRestarting) {
        setTimeout(async () => {
          await relaunchApp();
        }, 250);
      }
    }, "doRelaunch");
    doRelaunch();
  }, [isRestarting]);
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onSelect("do_not_trust" /* DO_NOT_TRUST */);
      }
    },
    { isActive: !isRestarting }
  );
  const dirName = path61.basename(process26.cwd());
  const parentFolder = path61.basename(path61.dirname(process26.cwd()));
  const options2 = [
    {
      label: `Trust folder (${dirName})`,
      value: "trust_folder" /* TRUST_FOLDER */,
      key: `Trust folder (${dirName})`
    },
    {
      label: `Trust parent folder (${parentFolder})`,
      value: "trust_parent" /* TRUST_PARENT */,
      key: `Trust parent folder (${parentFolder})`
    },
    {
      label: "Don't trust (esc)",
      value: "do_not_trust" /* DO_NOT_TRUST */,
      key: "Don't trust (esc)"
    }
  ];
  return /* @__PURE__ */ (0, import_jsx_runtime64.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime64.jsxs)(
      Box_default,
      {
        flexDirection: "column",
        borderStyle: "round",
        borderColor: theme.status.warning,
        padding: 1,
        width: "100%",
        marginLeft: 1,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime64.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(Text, { bold: true, color: theme.text.primary, children: "Do you trust this folder?" }),
            /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(Text, { color: theme.text.primary, children: "Trusting a folder allows Qwen Code to execute commands it suggests. This is a security feature to prevent accidental execution in untrusted directories." })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(
            RadioButtonSelect,
            {
              items: options2,
              onSelect,
              isFocused: !isRestarting
            }
          )
        ]
      }
    ),
    isRestarting && /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(Box_default, { marginLeft: 1, marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(Text, { color: theme.status.warning, children: "Qwen Code is restarting to apply the trust changes..." }) })
  ] });
}, "FolderTrustDialog");

// packages/cli/src/ui/components/ShellConfirmationDialog.tsx
init_esbuild_shims();
var import_jsx_runtime65 = __toESM(require_jsx_runtime(), 1);
var ShellConfirmationDialog = /* @__PURE__ */ __name(({ request: request4 }) => {
  const { commands, onConfirm } = request4;
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onConfirm(ToolConfirmationOutcome.Cancel);
      }
    },
    { isActive: true }
  );
  const handleSelect = /* @__PURE__ */ __name((item) => {
    if (item === ToolConfirmationOutcome.Cancel) {
      onConfirm(item);
    } else {
      onConfirm(item, commands);
    }
  }, "handleSelect");
  const options2 = [
    {
      label: "Yes, allow once",
      value: ToolConfirmationOutcome.ProceedOnce,
      key: "Yes, allow once"
    },
    {
      label: "Yes, allow always for this session",
      value: ToolConfirmationOutcome.ProceedAlways,
      key: "Yes, allow always for this session"
    },
    {
      label: "No (esc)",
      value: ToolConfirmationOutcome.Cancel,
      key: "No (esc)"
    }
  ];
  return /* @__PURE__ */ (0, import_jsx_runtime65.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.status.warning,
      padding: 1,
      width: "100%",
      marginLeft: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime65.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(Text, { bold: true, color: theme.text.primary, children: "Shell Command Execution" }),
          /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(Text, { color: theme.text.primary, children: "A custom command wants to run the following shell commands:" }),
          /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(
            Box_default,
            {
              flexDirection: "column",
              borderStyle: "round",
              borderColor: theme.border.default,
              paddingX: 1,
              marginTop: 1,
              children: commands.map((cmd) => /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(Text, { color: theme.text.link, children: /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(RenderInline, { text: cmd }) }, cmd))
            }
          )
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(Text, { color: theme.text.primary, children: "Do you want to proceed?" }) }),
        /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(RadioButtonSelect, { items: options2, onSelect: handleSelect, isFocused: true })
      ]
    }
  );
}, "ShellConfirmationDialog");

// packages/cli/src/ui/components/ConsentPrompt.tsx
init_esbuild_shims();
var import_react69 = __toESM(require_react(), 1);
var import_jsx_runtime66 = __toESM(require_jsx_runtime(), 1);
var ConsentPrompt = /* @__PURE__ */ __name((props) => {
  const { prompt, onConfirm, terminalWidth } = props;
  return /* @__PURE__ */ (0, import_jsx_runtime66.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      children: [
        typeof prompt === "string" ? /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(
          MarkdownDisplay,
          {
            isPending: true,
            text: prompt,
            terminalWidth
          }
        ) : prompt,
        /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(
          RadioButtonSelect,
          {
            items: [
              { label: "Yes", value: true, key: "Yes" },
              { label: "No", value: false, key: "No" }
            ],
            onSelect: onConfirm
          }
        ) })
      ]
    }
  );
}, "ConsentPrompt");

// packages/cli/src/ui/components/ThemeDialog.tsx
init_esbuild_shims();
var import_react70 = __toESM(require_react(), 1);

// packages/cli/src/config/settings.ts
init_esbuild_shims();
var dotenv = __toESM(require_main(), 1);
import * as fs70 from "node:fs";
import * as path72 from "node:path";
import { homedir as homedir14, platform as platform12 } from "node:os";
import process27 from "node:process";
var import_strip_json_comments2 = __toESM(require_strip_json_comments(), 1);

// packages/cli/src/config/settingsSchema.ts
init_esbuild_shims();
var TOGGLE_TYPES = /* @__PURE__ */ new Set([
  "boolean",
  "enum"
]);
var SETTINGS_SCHEMA = {
  // Maintained for compatibility/criticality
  mcpServers: {
    type: "object",
    label: "MCP Servers",
    category: "Advanced",
    requiresRestart: true,
    default: {},
    description: "Configuration for MCP servers.",
    showInDialog: false,
    mergeStrategy: "shallow_merge" /* SHALLOW_MERGE */
  },
  general: {
    type: "object",
    label: "General",
    category: "General",
    requiresRestart: false,
    default: {},
    description: "General application settings.",
    showInDialog: false,
    properties: {
      preferredEditor: {
        type: "string",
        label: "Preferred Editor",
        category: "General",
        requiresRestart: false,
        default: void 0,
        description: "The preferred editor to open files in.",
        showInDialog: false
      },
      vimMode: {
        type: "boolean",
        label: "Vim Mode",
        category: "General",
        requiresRestart: false,
        default: false,
        description: "Enable Vim keybindings",
        showInDialog: true
      },
      disableAutoUpdate: {
        type: "boolean",
        label: "Disable Auto Update",
        category: "General",
        requiresRestart: false,
        default: false,
        description: "Disable automatic updates",
        showInDialog: true
      },
      disableUpdateNag: {
        type: "boolean",
        label: "Disable Update Nag",
        category: "General",
        requiresRestart: false,
        default: false,
        description: "Disable update notification prompts.",
        showInDialog: false
      },
      checkpointing: {
        type: "object",
        label: "Checkpointing",
        category: "General",
        requiresRestart: true,
        default: {},
        description: "Session checkpointing settings.",
        showInDialog: false,
        properties: {
          enabled: {
            type: "boolean",
            label: "Enable Checkpointing",
            category: "General",
            requiresRestart: true,
            default: false,
            description: "Enable session checkpointing for recovery",
            showInDialog: false
          }
        }
      },
      debugKeystrokeLogging: {
        type: "boolean",
        label: "Debug Keystroke Logging",
        category: "General",
        requiresRestart: false,
        default: false,
        description: "Enable debug logging of keystrokes to the console.",
        showInDialog: true
      }
    }
  },
  output: {
    type: "object",
    label: "Output",
    category: "General",
    requiresRestart: false,
    default: {},
    description: "Settings for the CLI output.",
    showInDialog: false,
    properties: {
      format: {
        type: "enum",
        label: "Output Format",
        category: "General",
        requiresRestart: false,
        default: "text",
        description: "The format of the CLI output.",
        showInDialog: true,
        options: [
          { value: "text", label: "Text" },
          { value: "json", label: "JSON" }
        ]
      }
    }
  },
  ui: {
    type: "object",
    label: "UI",
    category: "UI",
    requiresRestart: false,
    default: {},
    description: "User interface settings.",
    showInDialog: false,
    properties: {
      theme: {
        type: "string",
        label: "Theme",
        category: "UI",
        requiresRestart: false,
        default: void 0,
        description: "The color theme for the UI.",
        showInDialog: false
      },
      customThemes: {
        type: "object",
        label: "Custom Themes",
        category: "UI",
        requiresRestart: false,
        default: {},
        description: "Custom theme definitions.",
        showInDialog: false
      },
      hideWindowTitle: {
        type: "boolean",
        label: "Hide Window Title",
        category: "UI",
        requiresRestart: true,
        default: false,
        description: "Hide the window title bar",
        showInDialog: true
      },
      showStatusInTitle: {
        type: "boolean",
        label: "Show Status in Title",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Show Gemini CLI status and thoughts in the terminal window title",
        showInDialog: true
      },
      hideTips: {
        type: "boolean",
        label: "Hide Tips",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Hide helpful tips in the UI",
        showInDialog: true
      },
      hideBanner: {
        type: "boolean",
        label: "Hide Banner",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Hide the application banner",
        showInDialog: true
      },
      hideContextSummary: {
        type: "boolean",
        label: "Hide Context Summary",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Hide the context summary (GEMINI.md, MCP servers) above the input.",
        showInDialog: true
      },
      footer: {
        type: "object",
        label: "Footer",
        category: "UI",
        requiresRestart: false,
        default: {},
        description: "Settings for the footer.",
        showInDialog: false,
        properties: {
          hideCWD: {
            type: "boolean",
            label: "Hide CWD",
            category: "UI",
            requiresRestart: false,
            default: false,
            description: "Hide the current working directory path in the footer.",
            showInDialog: true
          },
          hideSandboxStatus: {
            type: "boolean",
            label: "Hide Sandbox Status",
            category: "UI",
            requiresRestart: false,
            default: false,
            description: "Hide the sandbox status indicator in the footer.",
            showInDialog: true
          },
          hideModelInfo: {
            type: "boolean",
            label: "Hide Model Info",
            category: "UI",
            requiresRestart: false,
            default: false,
            description: "Hide the model name and context usage in the footer.",
            showInDialog: true
          }
        }
      },
      hideFooter: {
        type: "boolean",
        label: "Hide Footer",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Hide the footer from the UI",
        showInDialog: true
      },
      showMemoryUsage: {
        type: "boolean",
        label: "Show Memory Usage",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Display memory usage information in the UI",
        showInDialog: true
      },
      showLineNumbers: {
        type: "boolean",
        label: "Show Line Numbers",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Show line numbers in the chat.",
        showInDialog: true
      },
      showCitations: {
        type: "boolean",
        label: "Show Citations",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Show citations for generated text in the chat.",
        showInDialog: true
      },
      customWittyPhrases: {
        type: "array",
        label: "Custom Witty Phrases",
        category: "UI",
        requiresRestart: false,
        default: [],
        description: "Custom witty phrases to display during loading.",
        showInDialog: false
      },
      enableWelcomeBack: {
        type: "boolean",
        label: "Enable Welcome Back",
        category: "UI",
        requiresRestart: false,
        default: true,
        description: "Show welcome back dialog when returning to a project with conversation history.",
        showInDialog: true
      },
      accessibility: {
        type: "object",
        label: "Accessibility",
        category: "UI",
        requiresRestart: true,
        default: {},
        description: "Accessibility settings.",
        showInDialog: false,
        properties: {
          disableLoadingPhrases: {
            type: "boolean",
            label: "Disable Loading Phrases",
            category: "UI",
            requiresRestart: true,
            default: false,
            description: "Disable loading phrases for accessibility",
            showInDialog: true
          },
          screenReader: {
            type: "boolean",
            label: "Screen Reader Mode",
            category: "UI",
            requiresRestart: true,
            default: void 0,
            description: "Render output in plain-text to be more screen reader accessible",
            showInDialog: true
          }
        }
      }
    }
  },
  ide: {
    type: "object",
    label: "IDE",
    category: "IDE",
    requiresRestart: true,
    default: {},
    description: "IDE integration settings.",
    showInDialog: false,
    properties: {
      enabled: {
        type: "boolean",
        label: "IDE Mode",
        category: "IDE",
        requiresRestart: true,
        default: false,
        description: "Enable IDE integration mode",
        showInDialog: true
      },
      hasSeenNudge: {
        type: "boolean",
        label: "Has Seen IDE Integration Nudge",
        category: "IDE",
        requiresRestart: false,
        default: false,
        description: "Whether the user has seen the IDE integration nudge.",
        showInDialog: false
      }
    }
  },
  privacy: {
    type: "object",
    label: "Privacy",
    category: "Privacy",
    requiresRestart: true,
    default: {},
    description: "Privacy-related settings.",
    showInDialog: false,
    properties: {
      usageStatisticsEnabled: {
        type: "boolean",
        label: "Enable Usage Statistics",
        category: "Privacy",
        requiresRestart: true,
        default: true,
        description: "Enable collection of usage statistics",
        showInDialog: false
      }
    }
  },
  telemetry: {
    type: "object",
    label: "Telemetry",
    category: "Advanced",
    requiresRestart: true,
    default: void 0,
    description: "Telemetry configuration.",
    showInDialog: false
  },
  model: {
    type: "object",
    label: "Model",
    category: "Model",
    requiresRestart: false,
    default: {},
    description: "Settings related to the generative model.",
    showInDialog: false,
    properties: {
      name: {
        type: "string",
        label: "Model",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "The Gemini model to use for conversations.",
        showInDialog: false
      },
      maxSessionTurns: {
        type: "number",
        label: "Max Session Turns",
        category: "Model",
        requiresRestart: false,
        default: -1,
        description: "Maximum number of user/model/tool turns to keep in a session. -1 means unlimited.",
        showInDialog: true
      },
      summarizeToolOutput: {
        type: "object",
        label: "Summarize Tool Output",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "Settings for summarizing tool output.",
        showInDialog: false
      },
      chatCompression: {
        type: "object",
        label: "Chat Compression",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "Chat compression settings.",
        showInDialog: false
      },
      sessionTokenLimit: {
        type: "number",
        label: "Session Token Limit",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "The maximum number of tokens allowed in a session.",
        showInDialog: false
      },
      skipNextSpeakerCheck: {
        type: "boolean",
        label: "Skip Next Speaker Check",
        category: "Model",
        requiresRestart: false,
        default: true,
        description: "Skip the next speaker check.",
        showInDialog: true
      },
      skipLoopDetection: {
        type: "boolean",
        label: "Skip Loop Detection",
        category: "Model",
        requiresRestart: false,
        default: false,
        description: "Disable all loop detection checks (streaming and LLM).",
        showInDialog: true
      },
      skipStartupContext: {
        type: "boolean",
        label: "Skip Startup Context",
        category: "Model",
        requiresRestart: true,
        default: false,
        description: "Avoid sending the workspace startup context at the beginning of each session.",
        showInDialog: true
      },
      enableOpenAILogging: {
        type: "boolean",
        label: "Enable OpenAI Logging",
        category: "Model",
        requiresRestart: false,
        default: false,
        description: "Enable OpenAI logging.",
        showInDialog: true
      },
      openAILoggingDir: {
        type: "string",
        label: "OpenAI Logging Directory",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "Custom directory path for OpenAI API logs. If not specified, defaults to logs/openai in the current working directory.",
        showInDialog: true
      },
      generationConfig: {
        type: "object",
        label: "Generation Configuration",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "Generation configuration settings.",
        showInDialog: false,
        properties: {
          timeout: {
            type: "number",
            label: "Timeout",
            category: "Generation Configuration",
            requiresRestart: false,
            default: void 0,
            description: "Request timeout in milliseconds.",
            parentKey: "generationConfig",
            childKey: "timeout",
            showInDialog: true
          },
          maxRetries: {
            type: "number",
            label: "Max Retries",
            category: "Generation Configuration",
            requiresRestart: false,
            default: void 0,
            description: "Maximum number of retries for failed requests.",
            parentKey: "generationConfig",
            childKey: "maxRetries",
            showInDialog: true
          },
          disableCacheControl: {
            type: "boolean",
            label: "Disable Cache Control",
            category: "Generation Configuration",
            requiresRestart: false,
            default: false,
            description: "Disable cache control for DashScope providers.",
            parentKey: "generationConfig",
            childKey: "disableCacheControl",
            showInDialog: true
          }
        }
      }
    }
  },
  context: {
    type: "object",
    label: "Context",
    category: "Context",
    requiresRestart: false,
    default: {},
    description: "Settings for managing context provided to the model.",
    showInDialog: false,
    properties: {
      fileName: {
        type: "object",
        label: "Context File Name",
        category: "Context",
        requiresRestart: false,
        default: void 0,
        description: "The name of the context file.",
        showInDialog: false
      },
      importFormat: {
        type: "string",
        label: "Memory Import Format",
        category: "Context",
        requiresRestart: false,
        default: void 0,
        description: "The format to use when importing memory.",
        showInDialog: false
      },
      discoveryMaxDirs: {
        type: "number",
        label: "Memory Discovery Max Dirs",
        category: "Context",
        requiresRestart: false,
        default: 200,
        description: "Maximum number of directories to search for memory.",
        showInDialog: true
      },
      includeDirectories: {
        type: "array",
        label: "Include Directories",
        category: "Context",
        requiresRestart: false,
        default: [],
        description: "Additional directories to include in the workspace context. Missing directories will be skipped with a warning.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */
      },
      loadMemoryFromIncludeDirectories: {
        type: "boolean",
        label: "Load Memory From Include Directories",
        category: "Context",
        requiresRestart: false,
        default: false,
        description: "Whether to load memory files from include directories.",
        showInDialog: true
      },
      fileFiltering: {
        type: "object",
        label: "File Filtering",
        category: "Context",
        requiresRestart: true,
        default: {},
        description: "Settings for git-aware file filtering.",
        showInDialog: false,
        properties: {
          respectGitIgnore: {
            type: "boolean",
            label: "Respect .gitignore",
            category: "Context",
            requiresRestart: true,
            default: true,
            description: "Respect .gitignore files when searching",
            showInDialog: true
          },
          respectQwenIgnore: {
            type: "boolean",
            label: "Respect .qwenignore",
            category: "Context",
            requiresRestart: true,
            default: true,
            description: "Respect .qwenignore files when searching",
            showInDialog: true
          },
          enableRecursiveFileSearch: {
            type: "boolean",
            label: "Enable Recursive File Search",
            category: "Context",
            requiresRestart: true,
            default: true,
            description: "Enable recursive file search functionality",
            showInDialog: true
          },
          disableFuzzySearch: {
            type: "boolean",
            label: "Disable Fuzzy Search",
            category: "Context",
            requiresRestart: true,
            default: false,
            description: "Disable fuzzy search when searching for files.",
            showInDialog: true
          }
        }
      }
    }
  },
  tools: {
    type: "object",
    label: "Tools",
    category: "Tools",
    requiresRestart: true,
    default: {},
    description: "Settings for built-in and custom tools.",
    showInDialog: false,
    properties: {
      sandbox: {
        type: "object",
        label: "Sandbox",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Sandbox execution environment (can be a boolean or a path string).",
        showInDialog: false
      },
      shell: {
        type: "object",
        label: "Shell",
        category: "Tools",
        requiresRestart: false,
        default: {},
        description: "Settings for shell execution.",
        showInDialog: false,
        properties: {
          enableInteractiveShell: {
            type: "boolean",
            label: "Enable Interactive Shell",
            category: "Tools",
            requiresRestart: true,
            default: false,
            description: "Use node-pty for an interactive shell experience. Fallback to child_process still applies.",
            showInDialog: true
          },
          pager: {
            type: "string",
            label: "Pager",
            category: "Tools",
            requiresRestart: false,
            default: "cat",
            description: "The pager command to use for shell output. Defaults to `cat`.",
            showInDialog: false
          },
          showColor: {
            type: "boolean",
            label: "Show Color",
            category: "Tools",
            requiresRestart: false,
            default: false,
            description: "Show color in shell output.",
            showInDialog: true
          }
        }
      },
      autoAccept: {
        type: "boolean",
        label: "Auto Accept",
        category: "Tools",
        requiresRestart: false,
        default: false,
        description: "Automatically accept and execute tool calls that are considered safe (e.g., read-only operations).",
        showInDialog: true
      },
      core: {
        type: "array",
        label: "Core Tools",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Paths to core tool definitions.",
        showInDialog: false
      },
      allowed: {
        type: "array",
        label: "Allowed Tools",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: "A list of tool names that will bypass the confirmation dialog.",
        showInDialog: false
      },
      exclude: {
        type: "array",
        label: "Exclude Tools",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Tool names to exclude from discovery.",
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      },
      approvalMode: {
        type: "enum",
        label: "Approval Mode",
        category: "Tools",
        requiresRestart: false,
        default: ApprovalMode.DEFAULT,
        description: "Approval mode for tool usage. Controls how tools are approved before execution.",
        showInDialog: true,
        options: [
          { value: ApprovalMode.PLAN, label: "Plan" },
          { value: ApprovalMode.DEFAULT, label: "Default" },
          { value: ApprovalMode.AUTO_EDIT, label: "Auto Edit" },
          { value: ApprovalMode.YOLO, label: "YOLO" }
        ]
      },
      discoveryCommand: {
        type: "string",
        label: "Tool Discovery Command",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Command to run for tool discovery.",
        showInDialog: false
      },
      callCommand: {
        type: "string",
        label: "Tool Call Command",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Command to run for tool calls.",
        showInDialog: false
      },
      useRipgrep: {
        type: "boolean",
        label: "Use Ripgrep",
        category: "Tools",
        requiresRestart: false,
        default: true,
        description: "Use ripgrep for file content search instead of the fallback implementation. Provides faster search performance.",
        showInDialog: true
      },
      useBuiltinRipgrep: {
        type: "boolean",
        label: "Use Builtin Ripgrep",
        category: "Tools",
        requiresRestart: false,
        default: true,
        description: 'Use the bundled ripgrep binary. When set to false, the system-level "rg" command will be used instead. This setting is only effective when useRipgrep is true.',
        showInDialog: true
      },
      enableToolOutputTruncation: {
        type: "boolean",
        label: "Enable Tool Output Truncation",
        category: "General",
        requiresRestart: true,
        default: true,
        description: "Enable truncation of large tool outputs.",
        showInDialog: true
      },
      truncateToolOutputThreshold: {
        type: "number",
        label: "Tool Output Truncation Threshold",
        category: "General",
        requiresRestart: true,
        default: DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD,
        description: "Truncate tool output if it is larger than this many characters. Set to -1 to disable.",
        showInDialog: true
      },
      truncateToolOutputLines: {
        type: "number",
        label: "Tool Output Truncation Lines",
        category: "General",
        requiresRestart: true,
        default: DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES,
        description: "The number of lines to keep when truncating tool output.",
        showInDialog: true
      }
    }
  },
  mcp: {
    type: "object",
    label: "MCP",
    category: "MCP",
    requiresRestart: true,
    default: {},
    description: "Settings for Model Context Protocol (MCP) servers.",
    showInDialog: false,
    properties: {
      serverCommand: {
        type: "string",
        label: "MCP Server Command",
        category: "MCP",
        requiresRestart: true,
        default: void 0,
        description: "Command to start an MCP server.",
        showInDialog: false
      },
      allowed: {
        type: "array",
        label: "Allow MCP Servers",
        category: "MCP",
        requiresRestart: true,
        default: void 0,
        description: "A list of MCP servers to allow.",
        showInDialog: false
      },
      excluded: {
        type: "array",
        label: "Exclude MCP Servers",
        category: "MCP",
        requiresRestart: true,
        default: void 0,
        description: "A list of MCP servers to exclude.",
        showInDialog: false
      }
    }
  },
  useSmartEdit: {
    type: "boolean",
    label: "Use Smart Edit",
    category: "Advanced",
    requiresRestart: false,
    default: false,
    description: "Enable the smart-edit tool instead of the replace tool.",
    showInDialog: false
  },
  security: {
    type: "object",
    label: "Security",
    category: "Security",
    requiresRestart: true,
    default: {},
    description: "Security-related settings.",
    showInDialog: false,
    properties: {
      folderTrust: {
        type: "object",
        label: "Folder Trust",
        category: "Security",
        requiresRestart: false,
        default: {},
        description: "Settings for folder trust.",
        showInDialog: false,
        properties: {
          enabled: {
            type: "boolean",
            label: "Folder Trust",
            category: "Security",
            requiresRestart: true,
            default: false,
            description: "Setting to track whether Folder trust is enabled.",
            showInDialog: true
          }
        }
      },
      auth: {
        type: "object",
        label: "Authentication",
        category: "Security",
        requiresRestart: true,
        default: {},
        description: "Authentication settings.",
        showInDialog: false,
        properties: {
          selectedType: {
            type: "string",
            label: "Selected Auth Type",
            category: "Security",
            requiresRestart: true,
            default: void 0,
            description: "The currently selected authentication type.",
            showInDialog: false
          },
          enforcedType: {
            type: "string",
            label: "Enforced Auth Type",
            category: "Advanced",
            requiresRestart: true,
            default: void 0,
            description: "The required auth type. If this does not match the selected auth type, the user will be prompted to re-authenticate.",
            showInDialog: false
          },
          useExternal: {
            type: "boolean",
            label: "Use External Auth",
            category: "Security",
            requiresRestart: true,
            default: void 0,
            description: "Whether to use an external authentication flow.",
            showInDialog: false
          },
          apiKey: {
            type: "string",
            label: "API Key",
            category: "Security",
            requiresRestart: true,
            default: void 0,
            description: "API key for OpenAI compatible authentication.",
            showInDialog: false
          },
          baseUrl: {
            type: "string",
            label: "Base URL",
            category: "Security",
            requiresRestart: true,
            default: void 0,
            description: "Base URL for OpenAI compatible API.",
            showInDialog: false
          }
        }
      }
    }
  },
  advanced: {
    type: "object",
    label: "Advanced",
    category: "Advanced",
    requiresRestart: true,
    default: {},
    description: "Advanced settings for power users.",
    showInDialog: false,
    properties: {
      autoConfigureMemory: {
        type: "boolean",
        label: "Auto Configure Max Old Space Size",
        category: "Advanced",
        requiresRestart: true,
        default: false,
        description: "Automatically configure Node.js memory limits",
        showInDialog: false
      },
      dnsResolutionOrder: {
        type: "string",
        label: "DNS Resolution Order",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: "The DNS resolution order.",
        showInDialog: false
      },
      excludedEnvVars: {
        type: "array",
        label: "Excluded Project Environment Variables",
        category: "Advanced",
        requiresRestart: false,
        default: ["DEBUG", "DEBUG_MODE"],
        description: "Environment variables to exclude from project context.",
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      },
      bugCommand: {
        type: "object",
        label: "Bug Command",
        category: "Advanced",
        requiresRestart: false,
        default: void 0,
        description: "Configuration for the bug report command.",
        showInDialog: false
      },
      tavilyApiKey: {
        type: "string",
        label: "Tavily API Key (Deprecated)",
        category: "Advanced",
        requiresRestart: false,
        default: void 0,
        description: "\u26A0\uFE0F DEPRECATED: Please use webSearch.provider configuration instead. Legacy API key for the Tavily API.",
        showInDialog: false
      }
    }
  },
  webSearch: {
    type: "object",
    label: "Web Search",
    category: "Advanced",
    requiresRestart: true,
    default: void 0,
    description: "Configuration for web search providers.",
    showInDialog: false
  },
  experimental: {
    type: "object",
    label: "Experimental",
    category: "Experimental",
    requiresRestart: true,
    default: {},
    description: "Setting to enable experimental features",
    showInDialog: false,
    properties: {
      extensionManagement: {
        type: "boolean",
        label: "Extension Management",
        category: "Experimental",
        requiresRestart: true,
        default: true,
        description: "Enable extension management features.",
        showInDialog: false
      },
      visionModelPreview: {
        type: "boolean",
        label: "Vision Model Preview",
        category: "Experimental",
        requiresRestart: false,
        default: true,
        description: "Enable vision model support and auto-switching functionality. When disabled, vision models like qwen-vl-max-latest will be hidden and auto-switching will not occur.",
        showInDialog: true
      },
      vlmSwitchMode: {
        type: "string",
        label: "VLM Switch Mode",
        category: "Experimental",
        requiresRestart: false,
        default: void 0,
        description: "Default behavior when images are detected in input. Values: once (one-time switch), session (switch for entire session), persist (continue with current model). If not set, user will be prompted each time. This is a temporary experimental feature.",
        showInDialog: false
      }
    }
  },
  extensions: {
    type: "object",
    label: "Extensions",
    category: "Extensions",
    requiresRestart: true,
    default: {},
    description: "Settings for extensions.",
    showInDialog: false,
    properties: {
      disabled: {
        type: "array",
        label: "Disabled Extensions",
        category: "Extensions",
        requiresRestart: true,
        default: [],
        description: "List of disabled extensions.",
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      },
      workspacesWithMigrationNudge: {
        type: "array",
        label: "Workspaces with Migration Nudge",
        category: "Extensions",
        requiresRestart: false,
        default: [],
        description: "List of workspaces for which the migration nudge has been shown.",
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      }
    }
  }
};
function getSettingsSchema() {
  return SETTINGS_SCHEMA;
}
__name(getSettingsSchema, "getSettingsSchema");

// packages/cli/src/utils/envVarResolver.ts
init_esbuild_shims();
function resolveEnvVarsInString(value) {
  const envVarRegex = /\$(?:(\w+)|{([^}]+)})/g;
  return value.replace(envVarRegex, (match2, varName1, varName2) => {
    const varName = varName1 || varName2;
    if (process && process.env && typeof process.env[varName] === "string") {
      return process.env[varName];
    }
    return match2;
  });
}
__name(resolveEnvVarsInString, "resolveEnvVarsInString");
function resolveEnvVarsInObject(obj) {
  return resolveEnvVarsInObjectInternal(obj, /* @__PURE__ */ new WeakSet());
}
__name(resolveEnvVarsInObject, "resolveEnvVarsInObject");
function resolveEnvVarsInObjectInternal(obj, visited) {
  if (obj === null || obj === void 0 || typeof obj === "boolean" || typeof obj === "number") {
    return obj;
  }
  if (typeof obj === "string") {
    return resolveEnvVarsInString(obj);
  }
  if (Array.isArray(obj)) {
    if (visited.has(obj)) {
      return [...obj];
    }
    visited.add(obj);
    const result = obj.map(
      (item) => resolveEnvVarsInObjectInternal(item, visited)
    );
    visited.delete(obj);
    return result;
  }
  if (typeof obj === "object") {
    if (visited.has(obj)) {
      return { ...obj };
    }
    visited.add(obj);
    const newObj = { ...obj };
    for (const key in newObj) {
      if (Object.prototype.hasOwnProperty.call(newObj, key)) {
        newObj[key] = resolveEnvVarsInObjectInternal(newObj[key], visited);
      }
    }
    visited.delete(obj);
    return newObj;
  }
  return obj;
}
__name(resolveEnvVarsInObjectInternal, "resolveEnvVarsInObjectInternal");

// packages/cli/src/utils/deepMerge.ts
init_esbuild_shims();
function isPlainObject(item) {
  return !!item && typeof item === "object" && !Array.isArray(item);
}
__name(isPlainObject, "isPlainObject");
function mergeRecursively(target, source2, getMergeStrategyForPath2, path108 = []) {
  for (const key of Object.keys(source2)) {
    if (key === "__proto__" || key === "constructor" || key === "prototype") {
      continue;
    }
    const newPath = [...path108, key];
    const srcValue = source2[key];
    const objValue = target[key];
    const mergeStrategy = getMergeStrategyForPath2(newPath);
    if (mergeStrategy === "shallow_merge" /* SHALLOW_MERGE */ && objValue && srcValue) {
      const obj1 = typeof objValue === "object" && objValue !== null ? objValue : {};
      const obj2 = typeof srcValue === "object" && srcValue !== null ? srcValue : {};
      target[key] = { ...obj1, ...obj2 };
      continue;
    }
    if (Array.isArray(objValue)) {
      const srcArray = Array.isArray(srcValue) ? srcValue : [srcValue];
      if (mergeStrategy === "concat" /* CONCAT */) {
        target[key] = objValue.concat(srcArray);
        continue;
      }
      if (mergeStrategy === "union" /* UNION */) {
        target[key] = [...new Set(objValue.concat(srcArray))];
        continue;
      }
    }
    if (isPlainObject(objValue) && isPlainObject(srcValue)) {
      mergeRecursively(objValue, srcValue, getMergeStrategyForPath2, newPath);
    } else if (isPlainObject(srcValue)) {
      target[key] = {};
      mergeRecursively(
        target[key],
        srcValue,
        getMergeStrategyForPath2,
        newPath
      );
    } else {
      target[key] = srcValue;
    }
  }
  return target;
}
__name(mergeRecursively, "mergeRecursively");
function customDeepMerge(getMergeStrategyForPath2, ...sources) {
  const result = {};
  for (const source2 of sources) {
    if (source2) {
      mergeRecursively(result, source2, getMergeStrategyForPath2);
    }
  }
  return result;
}
__name(customDeepMerge, "customDeepMerge");

// packages/cli/src/utils/commentJson.ts
init_esbuild_shims();
var import_comment_json = __toESM(require_src38(), 1);
import * as fs56 from "node:fs";
function updateSettingsFilePreservingFormat(filePath, updates) {
  if (!fs56.existsSync(filePath)) {
    fs56.writeFileSync(filePath, JSON.stringify(updates, null, 2), "utf-8");
    return;
  }
  const originalContent = fs56.readFileSync(filePath, "utf-8");
  let parsed;
  try {
    parsed = (0, import_comment_json.parse)(originalContent);
  } catch (error) {
    console.error("Error parsing settings file:", error);
    console.error(
      "Settings file may be corrupted. Please check the JSON syntax."
    );
    return;
  }
  const updatedStructure = applyUpdates(parsed, updates);
  const updatedContent = (0, import_comment_json.stringify)(updatedStructure, null, 2);
  fs56.writeFileSync(filePath, updatedContent, "utf-8");
}
__name(updateSettingsFilePreservingFormat, "updateSettingsFilePreservingFormat");
function applyUpdates(current, updates) {
  const result = current;
  for (const key of Object.getOwnPropertyNames(updates)) {
    const value = updates[key];
    if (typeof value === "object" && value !== null && !Array.isArray(value) && typeof result[key] === "object" && result[key] !== null && !Array.isArray(result[key])) {
      result[key] = applyUpdates(
        result[key],
        value
      );
    } else {
      result[key] = value;
    }
  }
  return result;
}
__name(applyUpdates, "applyUpdates");

// packages/cli/src/config/extension.ts
init_esbuild_shims();
import * as fs69 from "node:fs";
import * as path71 from "node:path";
import * as os26 from "node:os";

// packages/cli/src/utils/errors.ts
init_esbuild_shims();
function getErrorMessage3(error) {
  if (error instanceof Error) {
    return error.message;
  }
  return String(error);
}
__name(getErrorMessage3, "getErrorMessage");
function extractErrorCode(error) {
  const errorWithCode = error;
  if (typeof errorWithCode.exitCode === "number") {
    return errorWithCode.exitCode;
  }
  if (errorWithCode.code !== void 0) {
    return errorWithCode.code;
  }
  if (errorWithCode.status !== void 0) {
    return errorWithCode.status;
  }
  return 1;
}
__name(extractErrorCode, "extractErrorCode");
function getNumericExitCode(errorCode) {
  return typeof errorCode === "number" ? errorCode : 1;
}
__name(getNumericExitCode, "getNumericExitCode");
function handleError(error, config, customErrorCode) {
  const errorMessage = parseAndFormatApiError(
    error,
    config.getContentGeneratorConfig()?.authType
  );
  if (config.getOutputFormat() === OutputFormat.JSON) {
    const formatter = new JsonFormatter();
    const errorCode = customErrorCode ?? extractErrorCode(error);
    const formattedError = formatter.formatError(
      error instanceof Error ? error : new Error(getErrorMessage3(error)),
      errorCode
    );
    console.error(formattedError);
    process.exit(getNumericExitCode(errorCode));
  } else {
    console.error(errorMessage);
    throw error;
  }
}
__name(handleError, "handleError");
function handleToolError(toolName, toolError, config, errorCode, resultDisplay) {
  const errorMessage = `Error executing tool ${toolName}: ${resultDisplay || toolError.message}`;
  const toolExecutionError = new FatalToolExecutionError(errorMessage);
  if (config.getOutputFormat() === OutputFormat.JSON) {
    const formatter = new JsonFormatter();
    const formattedError = formatter.formatError(
      toolExecutionError,
      errorCode ?? toolExecutionError.exitCode
    );
    console.error(formattedError);
    process.exit(
      typeof errorCode === "number" ? errorCode : toolExecutionError.exitCode
    );
  } else {
    console.error(errorMessage);
  }
}
__name(handleToolError, "handleToolError");
function handleCancellationError(config) {
  const cancellationError = new FatalCancellationError("Operation cancelled.");
  if (config.getOutputFormat() === OutputFormat.JSON) {
    const formatter = new JsonFormatter();
    const formattedError = formatter.formatError(
      cancellationError,
      cancellationError.exitCode
    );
    console.error(formattedError);
    process.exit(cancellationError.exitCode);
  } else {
    console.error(cancellationError.message);
    process.exit(cancellationError.exitCode);
  }
}
__name(handleCancellationError, "handleCancellationError");
function handleMaxTurnsExceededError(config) {
  const maxTurnsError = new FatalTurnLimitedError(
    "Reached max session turns for this session. Increase the number of turns by specifying maxSessionTurns in settings.json."
  );
  if (config.getOutputFormat() === OutputFormat.JSON) {
    const formatter = new JsonFormatter();
    const formattedError = formatter.formatError(
      maxTurnsError,
      maxTurnsError.exitCode
    );
    console.error(formattedError);
    process.exit(maxTurnsError.exitCode);
  } else {
    console.error(maxTurnsError.message);
    process.exit(maxTurnsError.exitCode);
  }
}
__name(handleMaxTurnsExceededError, "handleMaxTurnsExceededError");

// packages/cli/src/config/extensions/variables.ts
init_esbuild_shims();

// packages/cli/src/config/extensions/variableSchema.ts
init_esbuild_shims();
var PATH_SEPARATOR_DEFINITION = {
  type: "string",
  description: "The path separator."
};
var VARIABLE_SCHEMA = {
  extensionPath: {
    type: "string",
    description: "The path of the extension in the filesystem."
  },
  workspacePath: {
    type: "string",
    description: "The absolute path of the current workspace."
  },
  "/": PATH_SEPARATOR_DEFINITION,
  pathSeparator: PATH_SEPARATOR_DEFINITION
};

// packages/cli/src/config/extensions/variables.ts
function validateVariables(variables, schema) {
  for (const key in schema) {
    const definition = schema[key];
    if (definition.required && !variables[key]) {
      throw new Error(`Missing required variable: ${key}`);
    }
  }
}
__name(validateVariables, "validateVariables");
function hydrateString(str2, context2) {
  validateVariables(context2, VARIABLE_SCHEMA);
  const regex3 = /\${(.*?)}/g;
  return str2.replace(
    regex3,
    (match2, key) => context2[key] == null ? match2 : context2[key]
  );
}
__name(hydrateString, "hydrateString");
function recursivelyHydrateStrings(obj, values) {
  if (typeof obj === "string") {
    return hydrateString(obj, values);
  }
  if (Array.isArray(obj)) {
    return obj.map((item) => recursivelyHydrateStrings(item, values));
  }
  if (typeof obj === "object" && obj !== null) {
    const newObj = {};
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        newObj[key] = recursivelyHydrateStrings(obj[key], values);
      }
    }
    return newObj;
  }
  return obj;
}
__name(recursivelyHydrateStrings, "recursivelyHydrateStrings");

// packages/cli/src/config/extension.ts
import { randomUUID as randomUUID6 } from "node:crypto";

// packages/cli/src/config/extensions/github.ts
init_esbuild_shims();
init_esm10();
import * as os25 from "node:os";
import * as https3 from "node:https";
import * as fs67 from "node:fs";
import * as path69 from "node:path";

// node_modules/tar/dist/esm/index.js
init_esbuild_shims();

// node_modules/tar/dist/esm/create.js
init_esbuild_shims();

// node_modules/@isaacs/fs-minipass/dist/esm/index.js
init_esbuild_shims();
init_esm7();
import EE from "events";
import fs57 from "fs";
var writev = fs57.writev;
var _autoClose = Symbol("_autoClose");
var _close = Symbol("_close");
var _ended = Symbol("_ended");
var _fd = Symbol("_fd");
var _finished = Symbol("_finished");
var _flags = Symbol("_flags");
var _flush = Symbol("_flush");
var _handleChunk = Symbol("_handleChunk");
var _makeBuf = Symbol("_makeBuf");
var _mode = Symbol("_mode");
var _needDrain = Symbol("_needDrain");
var _onerror = Symbol("_onerror");
var _onopen = Symbol("_onopen");
var _onread = Symbol("_onread");
var _onwrite = Symbol("_onwrite");
var _open = Symbol("_open");
var _path = Symbol("_path");
var _pos = Symbol("_pos");
var _queue = Symbol("_queue");
var _read = Symbol("_read");
var _readSize = Symbol("_readSize");
var _reading = Symbol("_reading");
var _remain = Symbol("_remain");
var _size = Symbol("_size");
var _write = Symbol("_write");
var _writing = Symbol("_writing");
var _defaultFlag = Symbol("_defaultFlag");
var _errored = Symbol("_errored");
var ReadStream = class extends Minipass {
  static {
    __name(this, "ReadStream");
  }
  [_errored] = false;
  [_fd];
  [_path];
  [_readSize];
  [_reading] = false;
  [_size];
  [_remain];
  [_autoClose];
  constructor(path108, opt) {
    opt = opt || {};
    super(opt);
    this.readable = true;
    this.writable = false;
    if (typeof path108 !== "string") {
      throw new TypeError("path must be a string");
    }
    this[_errored] = false;
    this[_fd] = typeof opt.fd === "number" ? opt.fd : void 0;
    this[_path] = path108;
    this[_readSize] = opt.readSize || 16 * 1024 * 1024;
    this[_reading] = false;
    this[_size] = typeof opt.size === "number" ? opt.size : Infinity;
    this[_remain] = this[_size];
    this[_autoClose] = typeof opt.autoClose === "boolean" ? opt.autoClose : true;
    if (typeof this[_fd] === "number") {
      this[_read]();
    } else {
      this[_open]();
    }
  }
  get fd() {
    return this[_fd];
  }
  get path() {
    return this[_path];
  }
  //@ts-ignore
  write() {
    throw new TypeError("this is a readable stream");
  }
  //@ts-ignore
  end() {
    throw new TypeError("this is a readable stream");
  }
  [_open]() {
    fs57.open(this[_path], "r", (er, fd) => this[_onopen](er, fd));
  }
  [_onopen](er, fd) {
    if (er) {
      this[_onerror](er);
    } else {
      this[_fd] = fd;
      this.emit("open", fd);
      this[_read]();
    }
  }
  [_makeBuf]() {
    return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain]));
  }
  [_read]() {
    if (!this[_reading]) {
      this[_reading] = true;
      const buf = this[_makeBuf]();
      if (buf.length === 0) {
        return process.nextTick(() => this[_onread](null, 0, buf));
      }
      fs57.read(this[_fd], buf, 0, buf.length, null, (er, br2, b) => this[_onread](er, br2, b));
    }
  }
  [_onread](er, br2, buf) {
    this[_reading] = false;
    if (er) {
      this[_onerror](er);
    } else if (this[_handleChunk](br2, buf)) {
      this[_read]();
    }
  }
  [_close]() {
    if (this[_autoClose] && typeof this[_fd] === "number") {
      const fd = this[_fd];
      this[_fd] = void 0;
      fs57.close(fd, (er) => er ? this.emit("error", er) : this.emit("close"));
    }
  }
  [_onerror](er) {
    this[_reading] = true;
    this[_close]();
    this.emit("error", er);
  }
  [_handleChunk](br2, buf) {
    let ret = false;
    this[_remain] -= br2;
    if (br2 > 0) {
      ret = super.write(br2 < buf.length ? buf.subarray(0, br2) : buf);
    }
    if (br2 === 0 || this[_remain] <= 0) {
      ret = false;
      this[_close]();
      super.end();
    }
    return ret;
  }
  emit(ev, ...args) {
    switch (ev) {
      case "prefinish":
      case "finish":
        return false;
      case "drain":
        if (typeof this[_fd] === "number") {
          this[_read]();
        }
        return false;
      case "error":
        if (this[_errored]) {
          return false;
        }
        this[_errored] = true;
        return super.emit(ev, ...args);
      default:
        return super.emit(ev, ...args);
    }
  }
};
var ReadStreamSync = class extends ReadStream {
  static {
    __name(this, "ReadStreamSync");
  }
  [_open]() {
    let threw = true;
    try {
      this[_onopen](null, fs57.openSync(this[_path], "r"));
      threw = false;
    } finally {
      if (threw) {
        this[_close]();
      }
    }
  }
  [_read]() {
    let threw = true;
    try {
      if (!this[_reading]) {
        this[_reading] = true;
        do {
          const buf = this[_makeBuf]();
          const br2 = buf.length === 0 ? 0 : fs57.readSync(this[_fd], buf, 0, buf.length, null);
          if (!this[_handleChunk](br2, buf)) {
            break;
          }
        } while (true);
        this[_reading] = false;
      }
      threw = false;
    } finally {
      if (threw) {
        this[_close]();
      }
    }
  }
  [_close]() {
    if (this[_autoClose] && typeof this[_fd] === "number") {
      const fd = this[_fd];
      this[_fd] = void 0;
      fs57.closeSync(fd);
      this.emit("close");
    }
  }
};
var WriteStream = class extends EE {
  static {
    __name(this, "WriteStream");
  }
  readable = false;
  writable = true;
  [_errored] = false;
  [_writing] = false;
  [_ended] = false;
  [_queue] = [];
  [_needDrain] = false;
  [_path];
  [_mode];
  [_autoClose];
  [_fd];
  [_defaultFlag];
  [_flags];
  [_finished] = false;
  [_pos];
  constructor(path108, opt) {
    opt = opt || {};
    super(opt);
    this[_path] = path108;
    this[_fd] = typeof opt.fd === "number" ? opt.fd : void 0;
    this[_mode] = opt.mode === void 0 ? 438 : opt.mode;
    this[_pos] = typeof opt.start === "number" ? opt.start : void 0;
    this[_autoClose] = typeof opt.autoClose === "boolean" ? opt.autoClose : true;
    const defaultFlag = this[_pos] !== void 0 ? "r+" : "w";
    this[_defaultFlag] = opt.flags === void 0;
    this[_flags] = opt.flags === void 0 ? defaultFlag : opt.flags;
    if (this[_fd] === void 0) {
      this[_open]();
    }
  }
  emit(ev, ...args) {
    if (ev === "error") {
      if (this[_errored]) {
        return false;
      }
      this[_errored] = true;
    }
    return super.emit(ev, ...args);
  }
  get fd() {
    return this[_fd];
  }
  get path() {
    return this[_path];
  }
  [_onerror](er) {
    this[_close]();
    this[_writing] = true;
    this.emit("error", er);
  }
  [_open]() {
    fs57.open(this[_path], this[_flags], this[_mode], (er, fd) => this[_onopen](er, fd));
  }
  [_onopen](er, fd) {
    if (this[_defaultFlag] && this[_flags] === "r+" && er && er.code === "ENOENT") {
      this[_flags] = "w";
      this[_open]();
    } else if (er) {
      this[_onerror](er);
    } else {
      this[_fd] = fd;
      this.emit("open", fd);
      if (!this[_writing]) {
        this[_flush]();
      }
    }
  }
  end(buf, enc) {
    if (buf) {
      this.write(buf, enc);
    }
    this[_ended] = true;
    if (!this[_writing] && !this[_queue].length && typeof this[_fd] === "number") {
      this[_onwrite](null, 0);
    }
    return this;
  }
  write(buf, enc) {
    if (typeof buf === "string") {
      buf = Buffer.from(buf, enc);
    }
    if (this[_ended]) {
      this.emit("error", new Error("write() after end()"));
      return false;
    }
    if (this[_fd] === void 0 || this[_writing] || this[_queue].length) {
      this[_queue].push(buf);
      this[_needDrain] = true;
      return false;
    }
    this[_writing] = true;
    this[_write](buf);
    return true;
  }
  [_write](buf) {
    fs57.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => this[_onwrite](er, bw));
  }
  [_onwrite](er, bw) {
    if (er) {
      this[_onerror](er);
    } else {
      if (this[_pos] !== void 0 && typeof bw === "number") {
        this[_pos] += bw;
      }
      if (this[_queue].length) {
        this[_flush]();
      } else {
        this[_writing] = false;
        if (this[_ended] && !this[_finished]) {
          this[_finished] = true;
          this[_close]();
          this.emit("finish");
        } else if (this[_needDrain]) {
          this[_needDrain] = false;
          this.emit("drain");
        }
      }
    }
  }
  [_flush]() {
    if (this[_queue].length === 0) {
      if (this[_ended]) {
        this[_onwrite](null, 0);
      }
    } else if (this[_queue].length === 1) {
      this[_write](this[_queue].pop());
    } else {
      const iovec = this[_queue];
      this[_queue] = [];
      writev(this[_fd], iovec, this[_pos], (er, bw) => this[_onwrite](er, bw));
    }
  }
  [_close]() {
    if (this[_autoClose] && typeof this[_fd] === "number") {
      const fd = this[_fd];
      this[_fd] = void 0;
      fs57.close(fd, (er) => er ? this.emit("error", er) : this.emit("close"));
    }
  }
};
var WriteStreamSync = class extends WriteStream {
  static {
    __name(this, "WriteStreamSync");
  }
  [_open]() {
    let fd;
    if (this[_defaultFlag] && this[_flags] === "r+") {
      try {
        fd = fs57.openSync(this[_path], this[_flags], this[_mode]);
      } catch (er) {
        if (er?.code === "ENOENT") {
          this[_flags] = "w";
          return this[_open]();
        } else {
          throw er;
        }
      }
    } else {
      fd = fs57.openSync(this[_path], this[_flags], this[_mode]);
    }
    this[_onopen](null, fd);
  }
  [_close]() {
    if (this[_autoClose] && typeof this[_fd] === "number") {
      const fd = this[_fd];
      this[_fd] = void 0;
      fs57.closeSync(fd);
      this.emit("close");
    }
  }
  [_write](buf) {
    let threw = true;
    try {
      this[_onwrite](null, fs57.writeSync(this[_fd], buf, 0, buf.length, this[_pos]));
      threw = false;
    } finally {
      if (threw) {
        try {
          this[_close]();
        } catch {
        }
      }
    }
  }
};

// node_modules/tar/dist/esm/create.js
import path64 from "node:path";

// node_modules/tar/dist/esm/list.js
init_esbuild_shims();
import fs58 from "node:fs";
import { dirname as dirname16, parse as parse8 } from "path";

// node_modules/tar/dist/esm/make-command.js
init_esbuild_shims();

// node_modules/tar/dist/esm/options.js
init_esbuild_shims();
var argmap = /* @__PURE__ */ new Map([
  ["C", "cwd"],
  ["f", "file"],
  ["z", "gzip"],
  ["P", "preservePaths"],
  ["U", "unlink"],
  ["strip-components", "strip"],
  ["stripComponents", "strip"],
  ["keep-newer", "newer"],
  ["keepNewer", "newer"],
  ["keep-newer-files", "newer"],
  ["keepNewerFiles", "newer"],
  ["k", "keep"],
  ["keep-existing", "keep"],
  ["keepExisting", "keep"],
  ["m", "noMtime"],
  ["no-mtime", "noMtime"],
  ["p", "preserveOwner"],
  ["L", "follow"],
  ["h", "follow"],
  ["onentry", "onReadEntry"]
]);
var isSyncFile = /* @__PURE__ */ __name((o2) => !!o2.sync && !!o2.file, "isSyncFile");
var isAsyncFile = /* @__PURE__ */ __name((o2) => !o2.sync && !!o2.file, "isAsyncFile");
var isSyncNoFile = /* @__PURE__ */ __name((o2) => !!o2.sync && !o2.file, "isSyncNoFile");
var isAsyncNoFile = /* @__PURE__ */ __name((o2) => !o2.sync && !o2.file, "isAsyncNoFile");
var isFile = /* @__PURE__ */ __name((o2) => !!o2.file, "isFile");
var dealiasKey = /* @__PURE__ */ __name((k) => {
  const d = argmap.get(k);
  if (d)
    return d;
  return k;
}, "dealiasKey");
var dealias = /* @__PURE__ */ __name((opt = {}) => {
  if (!opt)
    return {};
  const result = {};
  for (const [key, v] of Object.entries(opt)) {
    const k = dealiasKey(key);
    result[k] = v;
  }
  if (result.chmod === void 0 && result.noChmod === false) {
    result.chmod = true;
  }
  delete result.noChmod;
  return result;
}, "dealias");

// node_modules/tar/dist/esm/make-command.js
var makeCommand = /* @__PURE__ */ __name((syncFile, asyncFile, syncNoFile, asyncNoFile, validate4) => {
  return Object.assign((opt_ = [], entries, cb) => {
    if (Array.isArray(opt_)) {
      entries = opt_;
      opt_ = {};
    }
    if (typeof entries === "function") {
      cb = entries;
      entries = void 0;
    }
    if (!entries) {
      entries = [];
    } else {
      entries = Array.from(entries);
    }
    const opt = dealias(opt_);
    validate4?.(opt, entries);
    if (isSyncFile(opt)) {
      if (typeof cb === "function") {
        throw new TypeError("callback not supported for sync tar functions");
      }
      return syncFile(opt, entries);
    } else if (isAsyncFile(opt)) {
      const p = asyncFile(opt, entries);
      const c3 = cb ? cb : void 0;
      return c3 ? p.then(() => c3(), c3) : p;
    } else if (isSyncNoFile(opt)) {
      if (typeof cb === "function") {
        throw new TypeError("callback not supported for sync tar functions");
      }
      return syncNoFile(opt, entries);
    } else if (isAsyncNoFile(opt)) {
      if (typeof cb === "function") {
        throw new TypeError("callback only supported with file option");
      }
      return asyncNoFile(opt, entries);
    } else {
      throw new Error("impossible options??");
    }
  }, {
    syncFile,
    asyncFile,
    syncNoFile,
    asyncNoFile,
    validate: validate4
  });
}, "makeCommand");

// node_modules/tar/dist/esm/parse.js
init_esbuild_shims();
import { EventEmitter as EE2 } from "events";

// node_modules/minizlib/dist/esm/index.js
init_esbuild_shims();
init_esm7();
import assert from "assert";
import { Buffer as Buffer4 } from "buffer";
import * as realZlib2 from "zlib";

// node_modules/minizlib/dist/esm/constants.js
init_esbuild_shims();
import realZlib from "zlib";
var realZlibConstants = realZlib.constants || { ZLIB_VERNUM: 4736 };
var constants3 = Object.freeze(Object.assign(/* @__PURE__ */ Object.create(null), {
  Z_NO_FLUSH: 0,
  Z_PARTIAL_FLUSH: 1,
  Z_SYNC_FLUSH: 2,
  Z_FULL_FLUSH: 3,
  Z_FINISH: 4,
  Z_BLOCK: 5,
  Z_OK: 0,
  Z_STREAM_END: 1,
  Z_NEED_DICT: 2,
  Z_ERRNO: -1,
  Z_STREAM_ERROR: -2,
  Z_DATA_ERROR: -3,
  Z_MEM_ERROR: -4,
  Z_BUF_ERROR: -5,
  Z_VERSION_ERROR: -6,
  Z_NO_COMPRESSION: 0,
  Z_BEST_SPEED: 1,
  Z_BEST_COMPRESSION: 9,
  Z_DEFAULT_COMPRESSION: -1,
  Z_FILTERED: 1,
  Z_HUFFMAN_ONLY: 2,
  Z_RLE: 3,
  Z_FIXED: 4,
  Z_DEFAULT_STRATEGY: 0,
  DEFLATE: 1,
  INFLATE: 2,
  GZIP: 3,
  GUNZIP: 4,
  DEFLATERAW: 5,
  INFLATERAW: 6,
  UNZIP: 7,
  BROTLI_DECODE: 8,
  BROTLI_ENCODE: 9,
  Z_MIN_WINDOWBITS: 8,
  Z_MAX_WINDOWBITS: 15,
  Z_DEFAULT_WINDOWBITS: 15,
  Z_MIN_CHUNK: 64,
  Z_MAX_CHUNK: Infinity,
  Z_DEFAULT_CHUNK: 16384,
  Z_MIN_MEMLEVEL: 1,
  Z_MAX_MEMLEVEL: 9,
  Z_DEFAULT_MEMLEVEL: 8,
  Z_MIN_LEVEL: -1,
  Z_MAX_LEVEL: 9,
  Z_DEFAULT_LEVEL: -1,
  BROTLI_OPERATION_PROCESS: 0,
  BROTLI_OPERATION_FLUSH: 1,
  BROTLI_OPERATION_FINISH: 2,
  BROTLI_OPERATION_EMIT_METADATA: 3,
  BROTLI_MODE_GENERIC: 0,
  BROTLI_MODE_TEXT: 1,
  BROTLI_MODE_FONT: 2,
  BROTLI_DEFAULT_MODE: 0,
  BROTLI_MIN_QUALITY: 0,
  BROTLI_MAX_QUALITY: 11,
  BROTLI_DEFAULT_QUALITY: 11,
  BROTLI_MIN_WINDOW_BITS: 10,
  BROTLI_MAX_WINDOW_BITS: 24,
  BROTLI_LARGE_MAX_WINDOW_BITS: 30,
  BROTLI_DEFAULT_WINDOW: 22,
  BROTLI_MIN_INPUT_BLOCK_BITS: 16,
  BROTLI_MAX_INPUT_BLOCK_BITS: 24,
  BROTLI_PARAM_MODE: 0,
  BROTLI_PARAM_QUALITY: 1,
  BROTLI_PARAM_LGWIN: 2,
  BROTLI_PARAM_LGBLOCK: 3,
  BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4,
  BROTLI_PARAM_SIZE_HINT: 5,
  BROTLI_PARAM_LARGE_WINDOW: 6,
  BROTLI_PARAM_NPOSTFIX: 7,
  BROTLI_PARAM_NDIRECT: 8,
  BROTLI_DECODER_RESULT_ERROR: 0,
  BROTLI_DECODER_RESULT_SUCCESS: 1,
  BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2,
  BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3,
  BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0,
  BROTLI_DECODER_PARAM_LARGE_WINDOW: 1,
  BROTLI_DECODER_NO_ERROR: 0,
  BROTLI_DECODER_SUCCESS: 1,
  BROTLI_DECODER_NEEDS_MORE_INPUT: 2,
  BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3,
  BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1,
  BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2,
  BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3,
  BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4,
  BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5,
  BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6,
  BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7,
  BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8,
  BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9,
  BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10,
  BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11,
  BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12,
  BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13,
  BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14,
  BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15,
  BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16,
  BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19,
  BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20,
  BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21,
  BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22,
  BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25,
  BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26,
  BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27,
  BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30,
  BROTLI_DECODER_ERROR_UNREACHABLE: -31
}, realZlibConstants));

// node_modules/minizlib/dist/esm/index.js
var OriginalBufferConcat = Buffer4.concat;
var desc = Object.getOwnPropertyDescriptor(Buffer4, "concat");
var noop4 = /* @__PURE__ */ __name((args) => args, "noop");
var passthroughBufferConcat = desc?.writable === true || desc?.set !== void 0 ? (makeNoOp) => {
  Buffer4.concat = makeNoOp ? noop4 : OriginalBufferConcat;
} : (_) => {
};
var _superWrite = Symbol("_superWrite");
var ZlibError = class extends Error {
  static {
    __name(this, "ZlibError");
  }
  code;
  errno;
  constructor(err, origin) {
    super("zlib: " + err.message, { cause: err });
    this.code = err.code;
    this.errno = err.errno;
    if (!this.code)
      this.code = "ZLIB_ERROR";
    this.message = "zlib: " + err.message;
    Error.captureStackTrace(this, origin ?? this.constructor);
  }
  get name() {
    return "ZlibError";
  }
};
var _flushFlag = Symbol("flushFlag");
var ZlibBase = class extends Minipass {
  static {
    __name(this, "ZlibBase");
  }
  #sawError = false;
  #ended = false;
  #flushFlag;
  #finishFlushFlag;
  #fullFlushFlag;
  #handle;
  #onError;
  get sawError() {
    return this.#sawError;
  }
  get handle() {
    return this.#handle;
  }
  /* c8 ignore start */
  get flushFlag() {
    return this.#flushFlag;
  }
  /* c8 ignore stop */
  constructor(opts, mode) {
    if (!opts || typeof opts !== "object")
      throw new TypeError("invalid options for ZlibBase constructor");
    super(opts);
    this.#flushFlag = opts.flush ?? 0;
    this.#finishFlushFlag = opts.finishFlush ?? 0;
    this.#fullFlushFlag = opts.fullFlushFlag ?? 0;
    if (typeof realZlib2[mode] !== "function") {
      throw new TypeError("Compression method not supported: " + mode);
    }
    try {
      this.#handle = new realZlib2[mode](opts);
    } catch (er) {
      throw new ZlibError(er, this.constructor);
    }
    this.#onError = (err) => {
      if (this.#sawError)
        return;
      this.#sawError = true;
      this.close();
      this.emit("error", err);
    };
    this.#handle?.on("error", (er) => this.#onError(new ZlibError(er)));
    this.once("end", () => this.close);
  }
  close() {
    if (this.#handle) {
      this.#handle.close();
      this.#handle = void 0;
      this.emit("close");
    }
  }
  reset() {
    if (!this.#sawError) {
      assert(this.#handle, "zlib binding closed");
      return this.#handle.reset?.();
    }
  }
  flush(flushFlag) {
    if (this.ended)
      return;
    if (typeof flushFlag !== "number")
      flushFlag = this.#fullFlushFlag;
    this.write(Object.assign(Buffer4.alloc(0), { [_flushFlag]: flushFlag }));
  }
  end(chunk, encoding, cb) {
    if (typeof chunk === "function") {
      cb = chunk;
      encoding = void 0;
      chunk = void 0;
    }
    if (typeof encoding === "function") {
      cb = encoding;
      encoding = void 0;
    }
    if (chunk) {
      if (encoding)
        this.write(chunk, encoding);
      else
        this.write(chunk);
    }
    this.flush(this.#finishFlushFlag);
    this.#ended = true;
    return super.end(cb);
  }
  get ended() {
    return this.#ended;
  }
  // overridden in the gzip classes to do portable writes
  [_superWrite](data) {
    return super.write(data);
  }
  write(chunk, encoding, cb) {
    if (typeof encoding === "function")
      cb = encoding, encoding = "utf8";
    if (typeof chunk === "string")
      chunk = Buffer4.from(chunk, encoding);
    if (this.#sawError)
      return;
    assert(this.#handle, "zlib binding closed");
    const nativeHandle = this.#handle._handle;
    const originalNativeClose = nativeHandle.close;
    nativeHandle.close = () => {
    };
    const originalClose = this.#handle.close;
    this.#handle.close = () => {
    };
    passthroughBufferConcat(true);
    let result = void 0;
    try {
      const flushFlag = typeof chunk[_flushFlag] === "number" ? chunk[_flushFlag] : this.#flushFlag;
      result = this.#handle._processChunk(chunk, flushFlag);
      passthroughBufferConcat(false);
    } catch (err) {
      passthroughBufferConcat(false);
      this.#onError(new ZlibError(err, this.write));
    } finally {
      if (this.#handle) {
        ;
        this.#handle._handle = nativeHandle;
        nativeHandle.close = originalNativeClose;
        this.#handle.close = originalClose;
        this.#handle.removeAllListeners("error");
      }
    }
    if (this.#handle)
      this.#handle.on("error", (er) => this.#onError(new ZlibError(er, this.write)));
    let writeReturn;
    if (result) {
      if (Array.isArray(result) && result.length > 0) {
        const r3 = result[0];
        writeReturn = this[_superWrite](Buffer4.from(r3));
        for (let i = 1; i < result.length; i++) {
          writeReturn = this[_superWrite](result[i]);
        }
      } else {
        writeReturn = this[_superWrite](Buffer4.from(result));
      }
    }
    if (cb)
      cb();
    return writeReturn;
  }
};
var Zlib = class extends ZlibBase {
  static {
    __name(this, "Zlib");
  }
  #level;
  #strategy;
  constructor(opts, mode) {
    opts = opts || {};
    opts.flush = opts.flush || constants3.Z_NO_FLUSH;
    opts.finishFlush = opts.finishFlush || constants3.Z_FINISH;
    opts.fullFlushFlag = constants3.Z_FULL_FLUSH;
    super(opts, mode);
    this.#level = opts.level;
    this.#strategy = opts.strategy;
  }
  params(level, strategy) {
    if (this.sawError)
      return;
    if (!this.handle)
      throw new Error("cannot switch params when binding is closed");
    if (!this.handle.params)
      throw new Error("not supported in this implementation");
    if (this.#level !== level || this.#strategy !== strategy) {
      this.flush(constants3.Z_SYNC_FLUSH);
      assert(this.handle, "zlib binding closed");
      const origFlush = this.handle.flush;
      this.handle.flush = (flushFlag, cb) => {
        if (typeof flushFlag === "function") {
          cb = flushFlag;
          flushFlag = this.flushFlag;
        }
        this.flush(flushFlag);
        cb?.();
      };
      try {
        ;
        this.handle.params(level, strategy);
      } finally {
        this.handle.flush = origFlush;
      }
      if (this.handle) {
        this.#level = level;
        this.#strategy = strategy;
      }
    }
  }
};
var Gzip = class extends Zlib {
  static {
    __name(this, "Gzip");
  }
  #portable;
  constructor(opts) {
    super(opts, "Gzip");
    this.#portable = opts && !!opts.portable;
  }
  [_superWrite](data) {
    if (!this.#portable)
      return super[_superWrite](data);
    this.#portable = false;
    data[9] = 255;
    return super[_superWrite](data);
  }
};
var Unzip = class extends Zlib {
  static {
    __name(this, "Unzip");
  }
  constructor(opts) {
    super(opts, "Unzip");
  }
};
var Brotli = class extends ZlibBase {
  static {
    __name(this, "Brotli");
  }
  constructor(opts, mode) {
    opts = opts || {};
    opts.flush = opts.flush || constants3.BROTLI_OPERATION_PROCESS;
    opts.finishFlush = opts.finishFlush || constants3.BROTLI_OPERATION_FINISH;
    opts.fullFlushFlag = constants3.BROTLI_OPERATION_FLUSH;
    super(opts, mode);
  }
};
var BrotliCompress = class extends Brotli {
  static {
    __name(this, "BrotliCompress");
  }
  constructor(opts) {
    super(opts, "BrotliCompress");
  }
};
var BrotliDecompress = class extends Brotli {
  static {
    __name(this, "BrotliDecompress");
  }
  constructor(opts) {
    super(opts, "BrotliDecompress");
  }
};
var Zstd = class extends ZlibBase {
  static {
    __name(this, "Zstd");
  }
  constructor(opts, mode) {
    opts = opts || {};
    opts.flush = opts.flush || constants3.ZSTD_e_continue;
    opts.finishFlush = opts.finishFlush || constants3.ZSTD_e_end;
    opts.fullFlushFlag = constants3.ZSTD_e_flush;
    super(opts, mode);
  }
};
var ZstdCompress = class extends Zstd {
  static {
    __name(this, "ZstdCompress");
  }
  constructor(opts) {
    super(opts, "ZstdCompress");
  }
};
var ZstdDecompress = class extends Zstd {
  static {
    __name(this, "ZstdDecompress");
  }
  constructor(opts) {
    super(opts, "ZstdDecompress");
  }
};

// node_modules/tar/dist/esm/header.js
init_esbuild_shims();
import { posix as pathModule } from "node:path";

// node_modules/tar/dist/esm/large-numbers.js
init_esbuild_shims();
var encode2 = /* @__PURE__ */ __name((num, buf) => {
  if (!Number.isSafeInteger(num)) {
    throw Error("cannot encode number outside of javascript safe integer range");
  } else if (num < 0) {
    encodeNegative(num, buf);
  } else {
    encodePositive(num, buf);
  }
  return buf;
}, "encode");
var encodePositive = /* @__PURE__ */ __name((num, buf) => {
  buf[0] = 128;
  for (var i = buf.length; i > 1; i--) {
    buf[i - 1] = num & 255;
    num = Math.floor(num / 256);
  }
}, "encodePositive");
var encodeNegative = /* @__PURE__ */ __name((num, buf) => {
  buf[0] = 255;
  var flipped = false;
  num = num * -1;
  for (var i = buf.length; i > 1; i--) {
    var byte = num & 255;
    num = Math.floor(num / 256);
    if (flipped) {
      buf[i - 1] = onesComp(byte);
    } else if (byte === 0) {
      buf[i - 1] = 0;
    } else {
      flipped = true;
      buf[i - 1] = twosComp(byte);
    }
  }
}, "encodeNegative");
var parse7 = /* @__PURE__ */ __name((buf) => {
  const pre = buf[0];
  const value = pre === 128 ? pos(buf.subarray(1, buf.length)) : pre === 255 ? twos(buf) : null;
  if (value === null) {
    throw Error("invalid base256 encoding");
  }
  if (!Number.isSafeInteger(value)) {
    throw Error("parsed number outside of javascript safe integer range");
  }
  return value;
}, "parse");
var twos = /* @__PURE__ */ __name((buf) => {
  var len = buf.length;
  var sum = 0;
  var flipped = false;
  for (var i = len - 1; i > -1; i--) {
    var byte = Number(buf[i]);
    var f;
    if (flipped) {
      f = onesComp(byte);
    } else if (byte === 0) {
      f = byte;
    } else {
      flipped = true;
      f = twosComp(byte);
    }
    if (f !== 0) {
      sum -= f * Math.pow(256, len - i - 1);
    }
  }
  return sum;
}, "twos");
var pos = /* @__PURE__ */ __name((buf) => {
  var len = buf.length;
  var sum = 0;
  for (var i = len - 1; i > -1; i--) {
    var byte = Number(buf[i]);
    if (byte !== 0) {
      sum += byte * Math.pow(256, len - i - 1);
    }
  }
  return sum;
}, "pos");
var onesComp = /* @__PURE__ */ __name((byte) => (255 ^ byte) & 255, "onesComp");
var twosComp = /* @__PURE__ */ __name((byte) => (255 ^ byte) + 1 & 255, "twosComp");

// node_modules/tar/dist/esm/types.js
init_esbuild_shims();
var isCode = /* @__PURE__ */ __name((c3) => name2.has(c3), "isCode");
var name2 = /* @__PURE__ */ new Map([
  ["0", "File"],
  // same as File
  ["", "OldFile"],
  ["1", "Link"],
  ["2", "SymbolicLink"],
  // Devices and FIFOs aren't fully supported
  // they are parsed, but skipped when unpacking
  ["3", "CharacterDevice"],
  ["4", "BlockDevice"],
  ["5", "Directory"],
  ["6", "FIFO"],
  // same as File
  ["7", "ContiguousFile"],
  // pax headers
  ["g", "GlobalExtendedHeader"],
  ["x", "ExtendedHeader"],
  // vendor-specific stuff
  // skip
  ["A", "SolarisACL"],
  // like 5, but with data, which should be skipped
  ["D", "GNUDumpDir"],
  // metadata only, skip
  ["I", "Inode"],
  // data = link path of next file
  ["K", "NextFileHasLongLinkpath"],
  // data = path of next file
  ["L", "NextFileHasLongPath"],
  // skip
  ["M", "ContinuationFile"],
  // like L
  ["N", "OldGnuLongPath"],
  // skip
  ["S", "SparseFile"],
  // skip
  ["V", "TapeVolumeHeader"],
  // like x
  ["X", "OldExtendedHeader"]
]);
var code = new Map(Array.from(name2).map((kv) => [kv[1], kv[0]]));

// node_modules/tar/dist/esm/header.js
var Header2 = class {
  static {
    __name(this, "Header");
  }
  cksumValid = false;
  needPax = false;
  nullBlock = false;
  block;
  path;
  mode;
  uid;
  gid;
  size;
  cksum;
  #type = "Unsupported";
  linkpath;
  uname;
  gname;
  devmaj = 0;
  devmin = 0;
  atime;
  ctime;
  mtime;
  charset;
  comment;
  constructor(data, off = 0, ex, gex) {
    if (Buffer.isBuffer(data)) {
      this.decode(data, off || 0, ex, gex);
    } else if (data) {
      this.#slurp(data);
    }
  }
  decode(buf, off, ex, gex) {
    if (!off) {
      off = 0;
    }
    if (!buf || !(buf.length >= off + 512)) {
      throw new Error("need 512 bytes for header");
    }
    this.path = decString(buf, off, 100);
    this.mode = decNumber(buf, off + 100, 8);
    this.uid = decNumber(buf, off + 108, 8);
    this.gid = decNumber(buf, off + 116, 8);
    this.size = decNumber(buf, off + 124, 12);
    this.mtime = decDate(buf, off + 136, 12);
    this.cksum = decNumber(buf, off + 148, 12);
    if (gex)
      this.#slurp(gex, true);
    if (ex)
      this.#slurp(ex);
    const t2 = decString(buf, off + 156, 1);
    if (isCode(t2)) {
      this.#type = t2 || "0";
    }
    if (this.#type === "0" && this.path.slice(-1) === "/") {
      this.#type = "5";
    }
    if (this.#type === "5") {
      this.size = 0;
    }
    this.linkpath = decString(buf, off + 157, 100);
    if (buf.subarray(off + 257, off + 265).toString() === "ustar\x0000") {
      this.uname = decString(buf, off + 265, 32);
      this.gname = decString(buf, off + 297, 32);
      this.devmaj = decNumber(buf, off + 329, 8) ?? 0;
      this.devmin = decNumber(buf, off + 337, 8) ?? 0;
      if (buf[off + 475] !== 0) {
        const prefix = decString(buf, off + 345, 155);
        this.path = prefix + "/" + this.path;
      } else {
        const prefix = decString(buf, off + 345, 130);
        if (prefix) {
          this.path = prefix + "/" + this.path;
        }
        this.atime = decDate(buf, off + 476, 12);
        this.ctime = decDate(buf, off + 488, 12);
      }
    }
    let sum = 8 * 32;
    for (let i = off; i < off + 148; i++) {
      sum += buf[i];
    }
    for (let i = off + 156; i < off + 512; i++) {
      sum += buf[i];
    }
    this.cksumValid = sum === this.cksum;
    if (this.cksum === void 0 && sum === 8 * 32) {
      this.nullBlock = true;
    }
  }
  #slurp(ex, gex = false) {
    Object.assign(this, Object.fromEntries(Object.entries(ex).filter(([k, v]) => {
      return !(v === null || v === void 0 || k === "path" && gex || k === "linkpath" && gex || k === "global");
    })));
  }
  encode(buf, off = 0) {
    if (!buf) {
      buf = this.block = Buffer.alloc(512);
    }
    if (this.#type === "Unsupported") {
      this.#type = "0";
    }
    if (!(buf.length >= off + 512)) {
      throw new Error("need 512 bytes for header");
    }
    const prefixSize = this.ctime || this.atime ? 130 : 155;
    const split = splitPrefix(this.path || "", prefixSize);
    const path108 = split[0];
    const prefix = split[1];
    this.needPax = !!split[2];
    this.needPax = encString(buf, off, 100, path108) || this.needPax;
    this.needPax = encNumber(buf, off + 100, 8, this.mode) || this.needPax;
    this.needPax = encNumber(buf, off + 108, 8, this.uid) || this.needPax;
    this.needPax = encNumber(buf, off + 116, 8, this.gid) || this.needPax;
    this.needPax = encNumber(buf, off + 124, 12, this.size) || this.needPax;
    this.needPax = encDate(buf, off + 136, 12, this.mtime) || this.needPax;
    buf[off + 156] = this.#type.charCodeAt(0);
    this.needPax = encString(buf, off + 157, 100, this.linkpath) || this.needPax;
    buf.write("ustar\x0000", off + 257, 8);
    this.needPax = encString(buf, off + 265, 32, this.uname) || this.needPax;
    this.needPax = encString(buf, off + 297, 32, this.gname) || this.needPax;
    this.needPax = encNumber(buf, off + 329, 8, this.devmaj) || this.needPax;
    this.needPax = encNumber(buf, off + 337, 8, this.devmin) || this.needPax;
    this.needPax = encString(buf, off + 345, prefixSize, prefix) || this.needPax;
    if (buf[off + 475] !== 0) {
      this.needPax = encString(buf, off + 345, 155, prefix) || this.needPax;
    } else {
      this.needPax = encString(buf, off + 345, 130, prefix) || this.needPax;
      this.needPax = encDate(buf, off + 476, 12, this.atime) || this.needPax;
      this.needPax = encDate(buf, off + 488, 12, this.ctime) || this.needPax;
    }
    let sum = 8 * 32;
    for (let i = off; i < off + 148; i++) {
      sum += buf[i];
    }
    for (let i = off + 156; i < off + 512; i++) {
      sum += buf[i];
    }
    this.cksum = sum;
    encNumber(buf, off + 148, 8, this.cksum);
    this.cksumValid = true;
    return this.needPax;
  }
  get type() {
    return this.#type === "Unsupported" ? this.#type : name2.get(this.#type);
  }
  get typeKey() {
    return this.#type;
  }
  set type(type) {
    const c3 = String(code.get(type));
    if (isCode(c3) || c3 === "Unsupported") {
      this.#type = c3;
    } else if (isCode(type)) {
      this.#type = type;
    } else {
      throw new TypeError("invalid entry type: " + type);
    }
  }
};
var splitPrefix = /* @__PURE__ */ __name((p, prefixSize) => {
  const pathSize = 100;
  let pp = p;
  let prefix = "";
  let ret = void 0;
  const root = pathModule.parse(p).root || ".";
  if (Buffer.byteLength(pp) < pathSize) {
    ret = [pp, prefix, false];
  } else {
    prefix = pathModule.dirname(pp);
    pp = pathModule.basename(pp);
    do {
      if (Buffer.byteLength(pp) <= pathSize && Buffer.byteLength(prefix) <= prefixSize) {
        ret = [pp, prefix, false];
      } else if (Buffer.byteLength(pp) > pathSize && Buffer.byteLength(prefix) <= prefixSize) {
        ret = [pp.slice(0, pathSize - 1), prefix, true];
      } else {
        pp = pathModule.join(pathModule.basename(prefix), pp);
        prefix = pathModule.dirname(prefix);
      }
    } while (prefix !== root && ret === void 0);
    if (!ret) {
      ret = [p.slice(0, pathSize - 1), "", true];
    }
  }
  return ret;
}, "splitPrefix");
var decString = /* @__PURE__ */ __name((buf, off, size) => buf.subarray(off, off + size).toString("utf8").replace(/\0.*/, ""), "decString");
var decDate = /* @__PURE__ */ __name((buf, off, size) => numToDate(decNumber(buf, off, size)), "decDate");
var numToDate = /* @__PURE__ */ __name((num) => num === void 0 ? void 0 : new Date(num * 1e3), "numToDate");
var decNumber = /* @__PURE__ */ __name((buf, off, size) => Number(buf[off]) & 128 ? parse7(buf.subarray(off, off + size)) : decSmallNumber(buf, off, size), "decNumber");
var nanUndef = /* @__PURE__ */ __name((value) => isNaN(value) ? void 0 : value, "nanUndef");
var decSmallNumber = /* @__PURE__ */ __name((buf, off, size) => nanUndef(parseInt(buf.subarray(off, off + size).toString("utf8").replace(/\0.*$/, "").trim(), 8)), "decSmallNumber");
var MAXNUM = {
  12: 8589934591,
  8: 2097151
};
var encNumber = /* @__PURE__ */ __name((buf, off, size, num) => num === void 0 ? false : num > MAXNUM[size] || num < 0 ? (encode2(num, buf.subarray(off, off + size)), true) : (encSmallNumber(buf, off, size, num), false), "encNumber");
var encSmallNumber = /* @__PURE__ */ __name((buf, off, size, num) => buf.write(octalString(num, size), off, size, "ascii"), "encSmallNumber");
var octalString = /* @__PURE__ */ __name((num, size) => padOctal(Math.floor(num).toString(8), size), "octalString");
var padOctal = /* @__PURE__ */ __name((str2, size) => (str2.length === size - 1 ? str2 : new Array(size - str2.length - 1).join("0") + str2 + " ") + "\0", "padOctal");
var encDate = /* @__PURE__ */ __name((buf, off, size, date) => date === void 0 ? false : encNumber(buf, off, size, date.getTime() / 1e3), "encDate");
var NULLS = new Array(156).join("\0");
var encString = /* @__PURE__ */ __name((buf, off, size, str2) => str2 === void 0 ? false : (buf.write(str2 + NULLS, off, size, "utf8"), str2.length !== Buffer.byteLength(str2) || str2.length > size), "encString");

// node_modules/tar/dist/esm/pax.js
init_esbuild_shims();
import { basename as basename10 } from "node:path";
var Pax = class _Pax {
  static {
    __name(this, "Pax");
  }
  atime;
  mtime;
  ctime;
  charset;
  comment;
  gid;
  uid;
  gname;
  uname;
  linkpath;
  dev;
  ino;
  nlink;
  path;
  size;
  mode;
  global;
  constructor(obj, global2 = false) {
    this.atime = obj.atime;
    this.charset = obj.charset;
    this.comment = obj.comment;
    this.ctime = obj.ctime;
    this.dev = obj.dev;
    this.gid = obj.gid;
    this.global = global2;
    this.gname = obj.gname;
    this.ino = obj.ino;
    this.linkpath = obj.linkpath;
    this.mtime = obj.mtime;
    this.nlink = obj.nlink;
    this.path = obj.path;
    this.size = obj.size;
    this.uid = obj.uid;
    this.uname = obj.uname;
  }
  encode() {
    const body = this.encodeBody();
    if (body === "") {
      return Buffer.allocUnsafe(0);
    }
    const bodyLen = Buffer.byteLength(body);
    const bufLen = 512 * Math.ceil(1 + bodyLen / 512);
    const buf = Buffer.allocUnsafe(bufLen);
    for (let i = 0; i < 512; i++) {
      buf[i] = 0;
    }
    new Header2({
      // XXX split the path
      // then the path should be PaxHeader + basename, but less than 99,
      // prepend with the dirname
      /* c8 ignore start */
      path: ("PaxHeader/" + basename10(this.path ?? "")).slice(0, 99),
      /* c8 ignore stop */
      mode: this.mode || 420,
      uid: this.uid,
      gid: this.gid,
      size: bodyLen,
      mtime: this.mtime,
      type: this.global ? "GlobalExtendedHeader" : "ExtendedHeader",
      linkpath: "",
      uname: this.uname || "",
      gname: this.gname || "",
      devmaj: 0,
      devmin: 0,
      atime: this.atime,
      ctime: this.ctime
    }).encode(buf);
    buf.write(body, 512, bodyLen, "utf8");
    for (let i = bodyLen + 512; i < buf.length; i++) {
      buf[i] = 0;
    }
    return buf;
  }
  encodeBody() {
    return this.encodeField("path") + this.encodeField("ctime") + this.encodeField("atime") + this.encodeField("dev") + this.encodeField("ino") + this.encodeField("nlink") + this.encodeField("charset") + this.encodeField("comment") + this.encodeField("gid") + this.encodeField("gname") + this.encodeField("linkpath") + this.encodeField("mtime") + this.encodeField("size") + this.encodeField("uid") + this.encodeField("uname");
  }
  encodeField(field) {
    if (this[field] === void 0) {
      return "";
    }
    const r3 = this[field];
    const v = r3 instanceof Date ? r3.getTime() / 1e3 : r3;
    const s2 = " " + (field === "dev" || field === "ino" || field === "nlink" ? "SCHILY." : "") + field + "=" + v + "\n";
    const byteLen = Buffer.byteLength(s2);
    let digits2 = Math.floor(Math.log(byteLen) / Math.log(10)) + 1;
    if (byteLen + digits2 >= Math.pow(10, digits2)) {
      digits2 += 1;
    }
    const len = digits2 + byteLen;
    return len + s2;
  }
  static parse(str2, ex, g = false) {
    return new _Pax(merge2(parseKV(str2), ex), g);
  }
};
var merge2 = /* @__PURE__ */ __name((a, b) => b ? Object.assign({}, b, a) : a, "merge");
var parseKV = /* @__PURE__ */ __name((str2) => str2.replace(/\n$/, "").split("\n").reduce(parseKVLine, /* @__PURE__ */ Object.create(null)), "parseKV");
var parseKVLine = /* @__PURE__ */ __name((set, line) => {
  const n2 = parseInt(line, 10);
  if (n2 !== Buffer.byteLength(line) + 1) {
    return set;
  }
  line = line.slice((n2 + " ").length);
  const kv = line.split("=");
  const r3 = kv.shift();
  if (!r3) {
    return set;
  }
  const k = r3.replace(/^SCHILY\.(dev|ino|nlink)/, "$1");
  const v = kv.join("=");
  set[k] = /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(k) ? new Date(Number(v) * 1e3) : /^[0-9]+$/.test(v) ? +v : v;
  return set;
}, "parseKVLine");

// node_modules/tar/dist/esm/read-entry.js
init_esbuild_shims();
init_esm7();

// node_modules/tar/dist/esm/normalize-windows-path.js
init_esbuild_shims();
var platform7 = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
var normalizeWindowsPath = platform7 !== "win32" ? (p) => p : (p) => p && p.replace(/\\/g, "/");

// node_modules/tar/dist/esm/read-entry.js
var ReadEntry = class extends Minipass {
  static {
    __name(this, "ReadEntry");
  }
  extended;
  globalExtended;
  header;
  startBlockSize;
  blockRemain;
  remain;
  type;
  meta = false;
  ignore = false;
  path;
  mode;
  uid;
  gid;
  uname;
  gname;
  size = 0;
  mtime;
  atime;
  ctime;
  linkpath;
  dev;
  ino;
  nlink;
  invalid = false;
  absolute;
  unsupported = false;
  constructor(header, ex, gex) {
    super({});
    this.pause();
    this.extended = ex;
    this.globalExtended = gex;
    this.header = header;
    this.remain = header.size ?? 0;
    this.startBlockSize = 512 * Math.ceil(this.remain / 512);
    this.blockRemain = this.startBlockSize;
    this.type = header.type;
    switch (this.type) {
      case "File":
      case "OldFile":
      case "Link":
      case "SymbolicLink":
      case "CharacterDevice":
      case "BlockDevice":
      case "Directory":
      case "FIFO":
      case "ContiguousFile":
      case "GNUDumpDir":
        break;
      case "NextFileHasLongLinkpath":
      case "NextFileHasLongPath":
      case "OldGnuLongPath":
      case "GlobalExtendedHeader":
      case "ExtendedHeader":
      case "OldExtendedHeader":
        this.meta = true;
        break;
      // NOTE: gnutar and bsdtar treat unrecognized types as 'File'
      // it may be worth doing the same, but with a warning.
      default:
        this.ignore = true;
    }
    if (!header.path) {
      throw new Error("no path provided for tar.ReadEntry");
    }
    this.path = normalizeWindowsPath(header.path);
    this.mode = header.mode;
    if (this.mode) {
      this.mode = this.mode & 4095;
    }
    this.uid = header.uid;
    this.gid = header.gid;
    this.uname = header.uname;
    this.gname = header.gname;
    this.size = this.remain;
    this.mtime = header.mtime;
    this.atime = header.atime;
    this.ctime = header.ctime;
    this.linkpath = header.linkpath ? normalizeWindowsPath(header.linkpath) : void 0;
    this.uname = header.uname;
    this.gname = header.gname;
    if (ex) {
      this.#slurp(ex);
    }
    if (gex) {
      this.#slurp(gex, true);
    }
  }
  write(data) {
    const writeLen = data.length;
    if (writeLen > this.blockRemain) {
      throw new Error("writing more to entry than is appropriate");
    }
    const r3 = this.remain;
    const br2 = this.blockRemain;
    this.remain = Math.max(0, r3 - writeLen);
    this.blockRemain = Math.max(0, br2 - writeLen);
    if (this.ignore) {
      return true;
    }
    if (r3 >= writeLen) {
      return super.write(data);
    }
    return super.write(data.subarray(0, r3));
  }
  #slurp(ex, gex = false) {
    if (ex.path)
      ex.path = normalizeWindowsPath(ex.path);
    if (ex.linkpath)
      ex.linkpath = normalizeWindowsPath(ex.linkpath);
    Object.assign(this, Object.fromEntries(Object.entries(ex).filter(([k, v]) => {
      return !(v === null || v === void 0 || k === "path" && gex);
    })));
  }
};

// node_modules/tar/dist/esm/warn-method.js
init_esbuild_shims();
var warnMethod = /* @__PURE__ */ __name((self2, code2, message, data = {}) => {
  if (self2.file) {
    data.file = self2.file;
  }
  if (self2.cwd) {
    data.cwd = self2.cwd;
  }
  data.code = message instanceof Error && message.code || code2;
  data.tarCode = code2;
  if (!self2.strict && data.recoverable !== false) {
    if (message instanceof Error) {
      data = Object.assign(message, data);
      message = message.message;
    }
    self2.emit("warn", code2, message, data);
  } else if (message instanceof Error) {
    self2.emit("error", Object.assign(message, data));
  } else {
    self2.emit("error", Object.assign(new Error(`${code2}: ${message}`), data));
  }
}, "warnMethod");

// node_modules/tar/dist/esm/parse.js
var maxMetaEntrySize = 1024 * 1024;
var gzipHeader = Buffer.from([31, 139]);
var zstdHeader = Buffer.from([40, 181, 47, 253]);
var ZIP_HEADER_LEN = Math.max(gzipHeader.length, zstdHeader.length);
var STATE = Symbol("state");
var WRITEENTRY = Symbol("writeEntry");
var READENTRY = Symbol("readEntry");
var NEXTENTRY = Symbol("nextEntry");
var PROCESSENTRY = Symbol("processEntry");
var EX = Symbol("extendedHeader");
var GEX = Symbol("globalExtendedHeader");
var META = Symbol("meta");
var EMITMETA = Symbol("emitMeta");
var BUFFER2 = Symbol("buffer");
var QUEUE = Symbol("queue");
var ENDED = Symbol("ended");
var EMITTEDEND = Symbol("emittedEnd");
var EMIT = Symbol("emit");
var UNZIP = Symbol("unzip");
var CONSUMECHUNK = Symbol("consumeChunk");
var CONSUMECHUNKSUB = Symbol("consumeChunkSub");
var CONSUMEBODY = Symbol("consumeBody");
var CONSUMEMETA = Symbol("consumeMeta");
var CONSUMEHEADER = Symbol("consumeHeader");
var CONSUMING = Symbol("consuming");
var BUFFERCONCAT = Symbol("bufferConcat");
var MAYBEEND = Symbol("maybeEnd");
var WRITING = Symbol("writing");
var ABORTED2 = Symbol("aborted");
var DONE = Symbol("onDone");
var SAW_VALID_ENTRY = Symbol("sawValidEntry");
var SAW_NULL_BLOCK = Symbol("sawNullBlock");
var SAW_EOF = Symbol("sawEOF");
var CLOSESTREAM = Symbol("closeStream");
var noop5 = /* @__PURE__ */ __name(() => true, "noop");
var Parser2 = class extends EE2 {
  static {
    __name(this, "Parser");
  }
  file;
  strict;
  maxMetaEntrySize;
  filter;
  brotli;
  zstd;
  writable = true;
  readable = false;
  [QUEUE] = [];
  [BUFFER2];
  [READENTRY];
  [WRITEENTRY];
  [STATE] = "begin";
  [META] = "";
  [EX];
  [GEX];
  [ENDED] = false;
  [UNZIP];
  [ABORTED2] = false;
  [SAW_VALID_ENTRY];
  [SAW_NULL_BLOCK] = false;
  [SAW_EOF] = false;
  [WRITING] = false;
  [CONSUMING] = false;
  [EMITTEDEND] = false;
  constructor(opt = {}) {
    super();
    this.file = opt.file || "";
    this.on(DONE, () => {
      if (this[STATE] === "begin" || this[SAW_VALID_ENTRY] === false) {
        this.warn("TAR_BAD_ARCHIVE", "Unrecognized archive format");
      }
    });
    if (opt.ondone) {
      this.on(DONE, opt.ondone);
    } else {
      this.on(DONE, () => {
        this.emit("prefinish");
        this.emit("finish");
        this.emit("end");
      });
    }
    this.strict = !!opt.strict;
    this.maxMetaEntrySize = opt.maxMetaEntrySize || maxMetaEntrySize;
    this.filter = typeof opt.filter === "function" ? opt.filter : noop5;
    const isTBR = opt.file && (opt.file.endsWith(".tar.br") || opt.file.endsWith(".tbr"));
    this.brotli = !(opt.gzip || opt.zstd) && opt.brotli !== void 0 ? opt.brotli : isTBR ? void 0 : false;
    const isTZST = opt.file && (opt.file.endsWith(".tar.zst") || opt.file.endsWith(".tzst"));
    this.zstd = !(opt.gzip || opt.brotli) && opt.zstd !== void 0 ? opt.zstd : isTZST ? true : void 0;
    this.on("end", () => this[CLOSESTREAM]());
    if (typeof opt.onwarn === "function") {
      this.on("warn", opt.onwarn);
    }
    if (typeof opt.onReadEntry === "function") {
      this.on("entry", opt.onReadEntry);
    }
  }
  warn(code2, message, data = {}) {
    warnMethod(this, code2, message, data);
  }
  [CONSUMEHEADER](chunk, position) {
    if (this[SAW_VALID_ENTRY] === void 0) {
      this[SAW_VALID_ENTRY] = false;
    }
    let header;
    try {
      header = new Header2(chunk, position, this[EX], this[GEX]);
    } catch (er) {
      return this.warn("TAR_ENTRY_INVALID", er);
    }
    if (header.nullBlock) {
      if (this[SAW_NULL_BLOCK]) {
        this[SAW_EOF] = true;
        if (this[STATE] === "begin") {
          this[STATE] = "header";
        }
        this[EMIT]("eof");
      } else {
        this[SAW_NULL_BLOCK] = true;
        this[EMIT]("nullBlock");
      }
    } else {
      this[SAW_NULL_BLOCK] = false;
      if (!header.cksumValid) {
        this.warn("TAR_ENTRY_INVALID", "checksum failure", { header });
      } else if (!header.path) {
        this.warn("TAR_ENTRY_INVALID", "path is required", { header });
      } else {
        const type = header.type;
        if (/^(Symbolic)?Link$/.test(type) && !header.linkpath) {
          this.warn("TAR_ENTRY_INVALID", "linkpath required", {
            header
          });
        } else if (!/^(Symbolic)?Link$/.test(type) && !/^(Global)?ExtendedHeader$/.test(type) && header.linkpath) {
          this.warn("TAR_ENTRY_INVALID", "linkpath forbidden", {
            header
          });
        } else {
          const entry = this[WRITEENTRY] = new ReadEntry(header, this[EX], this[GEX]);
          if (!this[SAW_VALID_ENTRY]) {
            if (entry.remain) {
              const onend = /* @__PURE__ */ __name(() => {
                if (!entry.invalid) {
                  this[SAW_VALID_ENTRY] = true;
                }
              }, "onend");
              entry.on("end", onend);
            } else {
              this[SAW_VALID_ENTRY] = true;
            }
          }
          if (entry.meta) {
            if (entry.size > this.maxMetaEntrySize) {
              entry.ignore = true;
              this[EMIT]("ignoredEntry", entry);
              this[STATE] = "ignore";
              entry.resume();
            } else if (entry.size > 0) {
              this[META] = "";
              entry.on("data", (c3) => this[META] += c3);
              this[STATE] = "meta";
            }
          } else {
            this[EX] = void 0;
            entry.ignore = entry.ignore || !this.filter(entry.path, entry);
            if (entry.ignore) {
              this[EMIT]("ignoredEntry", entry);
              this[STATE] = entry.remain ? "ignore" : "header";
              entry.resume();
            } else {
              if (entry.remain) {
                this[STATE] = "body";
              } else {
                this[STATE] = "header";
                entry.end();
              }
              if (!this[READENTRY]) {
                this[QUEUE].push(entry);
                this[NEXTENTRY]();
              } else {
                this[QUEUE].push(entry);
              }
            }
          }
        }
      }
    }
  }
  [CLOSESTREAM]() {
    queueMicrotask(() => this.emit("close"));
  }
  [PROCESSENTRY](entry) {
    let go2 = true;
    if (!entry) {
      this[READENTRY] = void 0;
      go2 = false;
    } else if (Array.isArray(entry)) {
      const [ev, ...args] = entry;
      this.emit(ev, ...args);
    } else {
      this[READENTRY] = entry;
      this.emit("entry", entry);
      if (!entry.emittedEnd) {
        entry.on("end", () => this[NEXTENTRY]());
        go2 = false;
      }
    }
    return go2;
  }
  [NEXTENTRY]() {
    do {
    } while (this[PROCESSENTRY](this[QUEUE].shift()));
    if (!this[QUEUE].length) {
      const re2 = this[READENTRY];
      const drainNow = !re2 || re2.flowing || re2.size === re2.remain;
      if (drainNow) {
        if (!this[WRITING]) {
          this.emit("drain");
        }
      } else {
        re2.once("drain", () => this.emit("drain"));
      }
    }
  }
  [CONSUMEBODY](chunk, position) {
    const entry = this[WRITEENTRY];
    if (!entry) {
      throw new Error("attempt to consume body without entry??");
    }
    const br2 = entry.blockRemain ?? 0;
    const c3 = br2 >= chunk.length && position === 0 ? chunk : chunk.subarray(position, position + br2);
    entry.write(c3);
    if (!entry.blockRemain) {
      this[STATE] = "header";
      this[WRITEENTRY] = void 0;
      entry.end();
    }
    return c3.length;
  }
  [CONSUMEMETA](chunk, position) {
    const entry = this[WRITEENTRY];
    const ret = this[CONSUMEBODY](chunk, position);
    if (!this[WRITEENTRY] && entry) {
      this[EMITMETA](entry);
    }
    return ret;
  }
  [EMIT](ev, data, extra) {
    if (!this[QUEUE].length && !this[READENTRY]) {
      this.emit(ev, data, extra);
    } else {
      this[QUEUE].push([ev, data, extra]);
    }
  }
  [EMITMETA](entry) {
    this[EMIT]("meta", this[META]);
    switch (entry.type) {
      case "ExtendedHeader":
      case "OldExtendedHeader":
        this[EX] = Pax.parse(this[META], this[EX], false);
        break;
      case "GlobalExtendedHeader":
        this[GEX] = Pax.parse(this[META], this[GEX], true);
        break;
      case "NextFileHasLongPath":
      case "OldGnuLongPath": {
        const ex = this[EX] ?? /* @__PURE__ */ Object.create(null);
        this[EX] = ex;
        ex.path = this[META].replace(/\0.*/, "");
        break;
      }
      case "NextFileHasLongLinkpath": {
        const ex = this[EX] || /* @__PURE__ */ Object.create(null);
        this[EX] = ex;
        ex.linkpath = this[META].replace(/\0.*/, "");
        break;
      }
      /* c8 ignore start */
      default:
        throw new Error("unknown meta: " + entry.type);
    }
  }
  abort(error) {
    this[ABORTED2] = true;
    this.emit("abort", error);
    this.warn("TAR_ABORT", error, { recoverable: false });
  }
  write(chunk, encoding, cb) {
    if (typeof encoding === "function") {
      cb = encoding;
      encoding = void 0;
    }
    if (typeof chunk === "string") {
      chunk = Buffer.from(
        chunk,
        /* c8 ignore next */
        typeof encoding === "string" ? encoding : "utf8"
      );
    }
    if (this[ABORTED2]) {
      cb?.();
      return false;
    }
    const needSniff = this[UNZIP] === void 0 || this.brotli === void 0 && this[UNZIP] === false;
    if (needSniff && chunk) {
      if (this[BUFFER2]) {
        chunk = Buffer.concat([this[BUFFER2], chunk]);
        this[BUFFER2] = void 0;
      }
      if (chunk.length < ZIP_HEADER_LEN) {
        this[BUFFER2] = chunk;
        cb?.();
        return true;
      }
      for (let i = 0; this[UNZIP] === void 0 && i < gzipHeader.length; i++) {
        if (chunk[i] !== gzipHeader[i]) {
          this[UNZIP] = false;
        }
      }
      let isZstd = false;
      if (this[UNZIP] === false && this.zstd !== false) {
        isZstd = true;
        for (let i = 0; i < zstdHeader.length; i++) {
          if (chunk[i] !== zstdHeader[i]) {
            isZstd = false;
            break;
          }
        }
      }
      const maybeBrotli = this.brotli === void 0 && !isZstd;
      if (this[UNZIP] === false && maybeBrotli) {
        if (chunk.length < 512) {
          if (this[ENDED]) {
            this.brotli = true;
          } else {
            this[BUFFER2] = chunk;
            cb?.();
            return true;
          }
        } else {
          try {
            new Header2(chunk.subarray(0, 512));
            this.brotli = false;
          } catch (_) {
            this.brotli = true;
          }
        }
      }
      if (this[UNZIP] === void 0 || this[UNZIP] === false && (this.brotli || isZstd)) {
        const ended = this[ENDED];
        this[ENDED] = false;
        this[UNZIP] = this[UNZIP] === void 0 ? new Unzip({}) : isZstd ? new ZstdDecompress({}) : new BrotliDecompress({});
        this[UNZIP].on("data", (chunk2) => this[CONSUMECHUNK](chunk2));
        this[UNZIP].on("error", (er) => this.abort(er));
        this[UNZIP].on("end", () => {
          this[ENDED] = true;
          this[CONSUMECHUNK]();
        });
        this[WRITING] = true;
        const ret2 = !!this[UNZIP][ended ? "end" : "write"](chunk);
        this[WRITING] = false;
        cb?.();
        return ret2;
      }
    }
    this[WRITING] = true;
    if (this[UNZIP]) {
      this[UNZIP].write(chunk);
    } else {
      this[CONSUMECHUNK](chunk);
    }
    this[WRITING] = false;
    const ret = this[QUEUE].length ? false : this[READENTRY] ? this[READENTRY].flowing : true;
    if (!ret && !this[QUEUE].length) {
      this[READENTRY]?.once("drain", () => this.emit("drain"));
    }
    cb?.();
    return ret;
  }
  [BUFFERCONCAT](c3) {
    if (c3 && !this[ABORTED2]) {
      this[BUFFER2] = this[BUFFER2] ? Buffer.concat([this[BUFFER2], c3]) : c3;
    }
  }
  [MAYBEEND]() {
    if (this[ENDED] && !this[EMITTEDEND] && !this[ABORTED2] && !this[CONSUMING]) {
      this[EMITTEDEND] = true;
      const entry = this[WRITEENTRY];
      if (entry && entry.blockRemain) {
        const have = this[BUFFER2] ? this[BUFFER2].length : 0;
        this.warn("TAR_BAD_ARCHIVE", `Truncated input (needed ${entry.blockRemain} more bytes, only ${have} available)`, { entry });
        if (this[BUFFER2]) {
          entry.write(this[BUFFER2]);
        }
        entry.end();
      }
      this[EMIT](DONE);
    }
  }
  [CONSUMECHUNK](chunk) {
    if (this[CONSUMING] && chunk) {
      this[BUFFERCONCAT](chunk);
    } else if (!chunk && !this[BUFFER2]) {
      this[MAYBEEND]();
    } else if (chunk) {
      this[CONSUMING] = true;
      if (this[BUFFER2]) {
        this[BUFFERCONCAT](chunk);
        const c3 = this[BUFFER2];
        this[BUFFER2] = void 0;
        this[CONSUMECHUNKSUB](c3);
      } else {
        this[CONSUMECHUNKSUB](chunk);
      }
      while (this[BUFFER2] && this[BUFFER2]?.length >= 512 && !this[ABORTED2] && !this[SAW_EOF]) {
        const c3 = this[BUFFER2];
        this[BUFFER2] = void 0;
        this[CONSUMECHUNKSUB](c3);
      }
      this[CONSUMING] = false;
    }
    if (!this[BUFFER2] || this[ENDED]) {
      this[MAYBEEND]();
    }
  }
  [CONSUMECHUNKSUB](chunk) {
    let position = 0;
    const length = chunk.length;
    while (position + 512 <= length && !this[ABORTED2] && !this[SAW_EOF]) {
      switch (this[STATE]) {
        case "begin":
        case "header":
          this[CONSUMEHEADER](chunk, position);
          position += 512;
          break;
        case "ignore":
        case "body":
          position += this[CONSUMEBODY](chunk, position);
          break;
        case "meta":
          position += this[CONSUMEMETA](chunk, position);
          break;
        /* c8 ignore start */
        default:
          throw new Error("invalid state: " + this[STATE]);
      }
    }
    if (position < length) {
      if (this[BUFFER2]) {
        this[BUFFER2] = Buffer.concat([
          chunk.subarray(position),
          this[BUFFER2]
        ]);
      } else {
        this[BUFFER2] = chunk.subarray(position);
      }
    }
  }
  end(chunk, encoding, cb) {
    if (typeof chunk === "function") {
      cb = chunk;
      encoding = void 0;
      chunk = void 0;
    }
    if (typeof encoding === "function") {
      cb = encoding;
      encoding = void 0;
    }
    if (typeof chunk === "string") {
      chunk = Buffer.from(chunk, encoding);
    }
    if (cb)
      this.once("finish", cb);
    if (!this[ABORTED2]) {
      if (this[UNZIP]) {
        if (chunk)
          this[UNZIP].write(chunk);
        this[UNZIP].end();
      } else {
        this[ENDED] = true;
        if (this.brotli === void 0 || this.zstd === void 0)
          chunk = chunk || Buffer.alloc(0);
        if (chunk)
          this.write(chunk);
        this[MAYBEEND]();
      }
    }
    return this;
  }
};

// node_modules/tar/dist/esm/strip-trailing-slashes.js
init_esbuild_shims();
var stripTrailingSlashes = /* @__PURE__ */ __name((str2) => {
  let i = str2.length - 1;
  let slashesStart = -1;
  while (i > -1 && str2.charAt(i) === "/") {
    slashesStart = i;
    i--;
  }
  return slashesStart === -1 ? str2 : str2.slice(0, slashesStart);
}, "stripTrailingSlashes");

// node_modules/tar/dist/esm/list.js
var onReadEntryFunction = /* @__PURE__ */ __name((opt) => {
  const onReadEntry = opt.onReadEntry;
  opt.onReadEntry = onReadEntry ? (e2) => {
    onReadEntry(e2);
    e2.resume();
  } : (e2) => e2.resume();
}, "onReadEntryFunction");
var filesFilter = /* @__PURE__ */ __name((opt, files) => {
  const map2 = new Map(files.map((f) => [stripTrailingSlashes(f), true]));
  const filter4 = opt.filter;
  const mapHas = /* @__PURE__ */ __name((file, r3 = "") => {
    const root = r3 || parse8(file).root || ".";
    let ret;
    if (file === root)
      ret = false;
    else {
      const m = map2.get(file);
      if (m !== void 0) {
        ret = m;
      } else {
        ret = mapHas(dirname16(file), root);
      }
    }
    map2.set(file, ret);
    return ret;
  }, "mapHas");
  opt.filter = filter4 ? (file, entry) => filter4(file, entry) && mapHas(stripTrailingSlashes(file)) : (file) => mapHas(stripTrailingSlashes(file));
}, "filesFilter");
var listFileSync = /* @__PURE__ */ __name((opt) => {
  const p = new Parser2(opt);
  const file = opt.file;
  let fd;
  try {
    fd = fs58.openSync(file, "r");
    const stat7 = fs58.fstatSync(fd);
    const readSize = opt.maxReadSize || 16 * 1024 * 1024;
    if (stat7.size < readSize) {
      const buf = Buffer.allocUnsafe(stat7.size);
      fs58.readSync(fd, buf, 0, stat7.size, 0);
      p.end(buf);
    } else {
      let pos2 = 0;
      const buf = Buffer.allocUnsafe(readSize);
      while (pos2 < stat7.size) {
        const bytesRead = fs58.readSync(fd, buf, 0, readSize, pos2);
        pos2 += bytesRead;
        p.write(buf.subarray(0, bytesRead));
      }
      p.end();
    }
  } finally {
    if (typeof fd === "number") {
      try {
        fs58.closeSync(fd);
      } catch (er) {
      }
    }
  }
}, "listFileSync");
var listFile = /* @__PURE__ */ __name((opt, _files) => {
  const parse12 = new Parser2(opt);
  const readSize = opt.maxReadSize || 16 * 1024 * 1024;
  const file = opt.file;
  const p = new Promise((resolve24, reject) => {
    parse12.on("error", reject);
    parse12.on("end", resolve24);
    fs58.stat(file, (er, stat7) => {
      if (er) {
        reject(er);
      } else {
        const stream2 = new ReadStream(file, {
          readSize,
          size: stat7.size
        });
        stream2.on("error", reject);
        stream2.pipe(parse12);
      }
    });
  });
  return p;
}, "listFile");
var list2 = makeCommand(listFileSync, listFile, (opt) => new Parser2(opt), (opt) => new Parser2(opt), (opt, files) => {
  if (files?.length)
    filesFilter(opt, files);
  if (!opt.noResume)
    onReadEntryFunction(opt);
});

// node_modules/tar/dist/esm/pack.js
init_esbuild_shims();
import fs60 from "fs";

// node_modules/tar/dist/esm/write-entry.js
init_esbuild_shims();
init_esm7();
import fs59 from "fs";
import path62 from "path";

// node_modules/tar/dist/esm/mode-fix.js
init_esbuild_shims();
var modeFix = /* @__PURE__ */ __name((mode, isDir, portable) => {
  mode &= 4095;
  if (portable) {
    mode = (mode | 384) & ~18;
  }
  if (isDir) {
    if (mode & 256) {
      mode |= 64;
    }
    if (mode & 32) {
      mode |= 8;
    }
    if (mode & 4) {
      mode |= 1;
    }
  }
  return mode;
}, "modeFix");

// node_modules/tar/dist/esm/strip-absolute-path.js
init_esbuild_shims();
import { win32 as win322 } from "node:path";
var { isAbsolute: isAbsolute7, parse: parse9 } = win322;
var stripAbsolutePath = /* @__PURE__ */ __name((path108) => {
  let r3 = "";
  let parsed = parse9(path108);
  while (isAbsolute7(path108) || parsed.root) {
    const root = path108.charAt(0) === "/" && path108.slice(0, 4) !== "//?/" ? "/" : parsed.root;
    path108 = path108.slice(root.length);
    r3 += root;
    parsed = parse9(path108);
  }
  return [r3, path108];
}, "stripAbsolutePath");

// node_modules/tar/dist/esm/winchars.js
init_esbuild_shims();
var raw = ["|", "<", ">", "?", ":"];
var win = raw.map((char) => String.fromCharCode(61440 + char.charCodeAt(0)));
var toWin = new Map(raw.map((char, i) => [char, win[i]]));
var toRaw = new Map(win.map((char, i) => [char, raw[i]]));
var encode3 = /* @__PURE__ */ __name((s2) => raw.reduce((s3, c3) => s3.split(c3).join(toWin.get(c3)), s2), "encode");
var decode = /* @__PURE__ */ __name((s2) => win.reduce((s3, c3) => s3.split(c3).join(toRaw.get(c3)), s2), "decode");

// node_modules/tar/dist/esm/write-entry.js
var prefixPath = /* @__PURE__ */ __name((path108, prefix) => {
  if (!prefix) {
    return normalizeWindowsPath(path108);
  }
  path108 = normalizeWindowsPath(path108).replace(/^\.(\/|$)/, "");
  return stripTrailingSlashes(prefix) + "/" + path108;
}, "prefixPath");
var maxReadSize = 16 * 1024 * 1024;
var PROCESS2 = Symbol("process");
var FILE = Symbol("file");
var DIRECTORY = Symbol("directory");
var SYMLINK = Symbol("symlink");
var HARDLINK = Symbol("hardlink");
var HEADER = Symbol("header");
var READ2 = Symbol("read");
var LSTAT = Symbol("lstat");
var ONLSTAT = Symbol("onlstat");
var ONREAD = Symbol("onread");
var ONREADLINK = Symbol("onreadlink");
var OPENFILE = Symbol("openfile");
var ONOPENFILE = Symbol("onopenfile");
var CLOSE = Symbol("close");
var MODE = Symbol("mode");
var AWAITDRAIN = Symbol("awaitDrain");
var ONDRAIN = Symbol("ondrain");
var PREFIX = Symbol("prefix");
var WriteEntry = class extends Minipass {
  static {
    __name(this, "WriteEntry");
  }
  path;
  portable;
  myuid = process.getuid && process.getuid() || 0;
  // until node has builtin pwnam functions, this'll have to do
  myuser = process.env.USER || "";
  maxReadSize;
  linkCache;
  statCache;
  preservePaths;
  cwd;
  strict;
  mtime;
  noPax;
  noMtime;
  prefix;
  fd;
  blockLen = 0;
  blockRemain = 0;
  buf;
  pos = 0;
  remain = 0;
  length = 0;
  offset = 0;
  win32;
  absolute;
  header;
  type;
  linkpath;
  stat;
  onWriteEntry;
  #hadError = false;
  constructor(p, opt_ = {}) {
    const opt = dealias(opt_);
    super();
    this.path = normalizeWindowsPath(p);
    this.portable = !!opt.portable;
    this.maxReadSize = opt.maxReadSize || maxReadSize;
    this.linkCache = opt.linkCache || /* @__PURE__ */ new Map();
    this.statCache = opt.statCache || /* @__PURE__ */ new Map();
    this.preservePaths = !!opt.preservePaths;
    this.cwd = normalizeWindowsPath(opt.cwd || process.cwd());
    this.strict = !!opt.strict;
    this.noPax = !!opt.noPax;
    this.noMtime = !!opt.noMtime;
    this.mtime = opt.mtime;
    this.prefix = opt.prefix ? normalizeWindowsPath(opt.prefix) : void 0;
    this.onWriteEntry = opt.onWriteEntry;
    if (typeof opt.onwarn === "function") {
      this.on("warn", opt.onwarn);
    }
    let pathWarn = false;
    if (!this.preservePaths) {
      const [root, stripped] = stripAbsolutePath(this.path);
      if (root && typeof stripped === "string") {
        this.path = stripped;
        pathWarn = root;
      }
    }
    this.win32 = !!opt.win32 || process.platform === "win32";
    if (this.win32) {
      this.path = decode(this.path.replace(/\\/g, "/"));
      p = p.replace(/\\/g, "/");
    }
    this.absolute = normalizeWindowsPath(opt.absolute || path62.resolve(this.cwd, p));
    if (this.path === "") {
      this.path = "./";
    }
    if (pathWarn) {
      this.warn("TAR_ENTRY_INFO", `stripping ${pathWarn} from absolute path`, {
        entry: this,
        path: pathWarn + this.path
      });
    }
    const cs = this.statCache.get(this.absolute);
    if (cs) {
      this[ONLSTAT](cs);
    } else {
      this[LSTAT]();
    }
  }
  warn(code2, message, data = {}) {
    return warnMethod(this, code2, message, data);
  }
  emit(ev, ...data) {
    if (ev === "error") {
      this.#hadError = true;
    }
    return super.emit(ev, ...data);
  }
  [LSTAT]() {
    fs59.lstat(this.absolute, (er, stat7) => {
      if (er) {
        return this.emit("error", er);
      }
      this[ONLSTAT](stat7);
    });
  }
  [ONLSTAT](stat7) {
    this.statCache.set(this.absolute, stat7);
    this.stat = stat7;
    if (!stat7.isFile()) {
      stat7.size = 0;
    }
    this.type = getType(stat7);
    this.emit("stat", stat7);
    this[PROCESS2]();
  }
  [PROCESS2]() {
    switch (this.type) {
      case "File":
        return this[FILE]();
      case "Directory":
        return this[DIRECTORY]();
      case "SymbolicLink":
        return this[SYMLINK]();
      // unsupported types are ignored.
      default:
        return this.end();
    }
  }
  [MODE](mode) {
    return modeFix(mode, this.type === "Directory", this.portable);
  }
  [PREFIX](path108) {
    return prefixPath(path108, this.prefix);
  }
  [HEADER]() {
    if (!this.stat) {
      throw new Error("cannot write header before stat");
    }
    if (this.type === "Directory" && this.portable) {
      this.noMtime = true;
    }
    this.onWriteEntry?.(this);
    this.header = new Header2({
      path: this[PREFIX](this.path),
      // only apply the prefix to hard links.
      linkpath: this.type === "Link" && this.linkpath !== void 0 ? this[PREFIX](this.linkpath) : this.linkpath,
      // only the permissions and setuid/setgid/sticky bitflags
      // not the higher-order bits that specify file type
      mode: this[MODE](this.stat.mode),
      uid: this.portable ? void 0 : this.stat.uid,
      gid: this.portable ? void 0 : this.stat.gid,
      size: this.stat.size,
      mtime: this.noMtime ? void 0 : this.mtime || this.stat.mtime,
      /* c8 ignore next */
      type: this.type === "Unsupported" ? void 0 : this.type,
      uname: this.portable ? void 0 : this.stat.uid === this.myuid ? this.myuser : "",
      atime: this.portable ? void 0 : this.stat.atime,
      ctime: this.portable ? void 0 : this.stat.ctime
    });
    if (this.header.encode() && !this.noPax) {
      super.write(new Pax({
        atime: this.portable ? void 0 : this.header.atime,
        ctime: this.portable ? void 0 : this.header.ctime,
        gid: this.portable ? void 0 : this.header.gid,
        mtime: this.noMtime ? void 0 : this.mtime || this.header.mtime,
        path: this[PREFIX](this.path),
        linkpath: this.type === "Link" && this.linkpath !== void 0 ? this[PREFIX](this.linkpath) : this.linkpath,
        size: this.header.size,
        uid: this.portable ? void 0 : this.header.uid,
        uname: this.portable ? void 0 : this.header.uname,
        dev: this.portable ? void 0 : this.stat.dev,
        ino: this.portable ? void 0 : this.stat.ino,
        nlink: this.portable ? void 0 : this.stat.nlink
      }).encode());
    }
    const block2 = this.header?.block;
    if (!block2) {
      throw new Error("failed to encode header");
    }
    super.write(block2);
  }
  [DIRECTORY]() {
    if (!this.stat) {
      throw new Error("cannot create directory entry without stat");
    }
    if (this.path.slice(-1) !== "/") {
      this.path += "/";
    }
    this.stat.size = 0;
    this[HEADER]();
    this.end();
  }
  [SYMLINK]() {
    fs59.readlink(this.absolute, (er, linkpath) => {
      if (er) {
        return this.emit("error", er);
      }
      this[ONREADLINK](linkpath);
    });
  }
  [ONREADLINK](linkpath) {
    this.linkpath = normalizeWindowsPath(linkpath);
    this[HEADER]();
    this.end();
  }
  [HARDLINK](linkpath) {
    if (!this.stat) {
      throw new Error("cannot create link entry without stat");
    }
    this.type = "Link";
    this.linkpath = normalizeWindowsPath(path62.relative(this.cwd, linkpath));
    this.stat.size = 0;
    this[HEADER]();
    this.end();
  }
  [FILE]() {
    if (!this.stat) {
      throw new Error("cannot create file entry without stat");
    }
    if (this.stat.nlink > 1) {
      const linkKey = `${this.stat.dev}:${this.stat.ino}`;
      const linkpath = this.linkCache.get(linkKey);
      if (linkpath?.indexOf(this.cwd) === 0) {
        return this[HARDLINK](linkpath);
      }
      this.linkCache.set(linkKey, this.absolute);
    }
    this[HEADER]();
    if (this.stat.size === 0) {
      return this.end();
    }
    this[OPENFILE]();
  }
  [OPENFILE]() {
    fs59.open(this.absolute, "r", (er, fd) => {
      if (er) {
        return this.emit("error", er);
      }
      this[ONOPENFILE](fd);
    });
  }
  [ONOPENFILE](fd) {
    this.fd = fd;
    if (this.#hadError) {
      return this[CLOSE]();
    }
    if (!this.stat) {
      throw new Error("should stat before calling onopenfile");
    }
    this.blockLen = 512 * Math.ceil(this.stat.size / 512);
    this.blockRemain = this.blockLen;
    const bufLen = Math.min(this.blockLen, this.maxReadSize);
    this.buf = Buffer.allocUnsafe(bufLen);
    this.offset = 0;
    this.pos = 0;
    this.remain = this.stat.size;
    this.length = this.buf.length;
    this[READ2]();
  }
  [READ2]() {
    const { fd, buf, offset, length, pos: pos2 } = this;
    if (fd === void 0 || buf === void 0) {
      throw new Error("cannot read file without first opening");
    }
    fs59.read(fd, buf, offset, length, pos2, (er, bytesRead) => {
      if (er) {
        return this[CLOSE](() => this.emit("error", er));
      }
      this[ONREAD](bytesRead);
    });
  }
  /* c8 ignore start */
  [CLOSE](cb = () => {
  }) {
    if (this.fd !== void 0)
      fs59.close(this.fd, cb);
  }
  [ONREAD](bytesRead) {
    if (bytesRead <= 0 && this.remain > 0) {
      const er = Object.assign(new Error("encountered unexpected EOF"), {
        path: this.absolute,
        syscall: "read",
        code: "EOF"
      });
      return this[CLOSE](() => this.emit("error", er));
    }
    if (bytesRead > this.remain) {
      const er = Object.assign(new Error("did not encounter expected EOF"), {
        path: this.absolute,
        syscall: "read",
        code: "EOF"
      });
      return this[CLOSE](() => this.emit("error", er));
    }
    if (!this.buf) {
      throw new Error("should have created buffer prior to reading");
    }
    if (bytesRead === this.remain) {
      for (let i = bytesRead; i < this.length && bytesRead < this.blockRemain; i++) {
        this.buf[i + this.offset] = 0;
        bytesRead++;
        this.remain++;
      }
    }
    const chunk = this.offset === 0 && bytesRead === this.buf.length ? this.buf : this.buf.subarray(this.offset, this.offset + bytesRead);
    const flushed = this.write(chunk);
    if (!flushed) {
      this[AWAITDRAIN](() => this[ONDRAIN]());
    } else {
      this[ONDRAIN]();
    }
  }
  [AWAITDRAIN](cb) {
    this.once("drain", cb);
  }
  write(chunk, encoding, cb) {
    if (typeof encoding === "function") {
      cb = encoding;
      encoding = void 0;
    }
    if (typeof chunk === "string") {
      chunk = Buffer.from(chunk, typeof encoding === "string" ? encoding : "utf8");
    }
    if (this.blockRemain < chunk.length) {
      const er = Object.assign(new Error("writing more data than expected"), {
        path: this.absolute
      });
      return this.emit("error", er);
    }
    this.remain -= chunk.length;
    this.blockRemain -= chunk.length;
    this.pos += chunk.length;
    this.offset += chunk.length;
    return super.write(chunk, null, cb);
  }
  [ONDRAIN]() {
    if (!this.remain) {
      if (this.blockRemain) {
        super.write(Buffer.alloc(this.blockRemain));
      }
      return this[CLOSE]((er) => er ? this.emit("error", er) : this.end());
    }
    if (!this.buf) {
      throw new Error("buffer lost somehow in ONDRAIN");
    }
    if (this.offset >= this.length) {
      this.buf = Buffer.allocUnsafe(Math.min(this.blockRemain, this.buf.length));
      this.offset = 0;
    }
    this.length = this.buf.length - this.offset;
    this[READ2]();
  }
};
var WriteEntrySync = class extends WriteEntry {
  static {
    __name(this, "WriteEntrySync");
  }
  sync = true;
  [LSTAT]() {
    this[ONLSTAT](fs59.lstatSync(this.absolute));
  }
  [SYMLINK]() {
    this[ONREADLINK](fs59.readlinkSync(this.absolute));
  }
  [OPENFILE]() {
    this[ONOPENFILE](fs59.openSync(this.absolute, "r"));
  }
  [READ2]() {
    let threw = true;
    try {
      const { fd, buf, offset, length, pos: pos2 } = this;
      if (fd === void 0 || buf === void 0) {
        throw new Error("fd and buf must be set in READ method");
      }
      const bytesRead = fs59.readSync(fd, buf, offset, length, pos2);
      this[ONREAD](bytesRead);
      threw = false;
    } finally {
      if (threw) {
        try {
          this[CLOSE](() => {
          });
        } catch (er) {
        }
      }
    }
  }
  [AWAITDRAIN](cb) {
    cb();
  }
  /* c8 ignore start */
  [CLOSE](cb = () => {
  }) {
    if (this.fd !== void 0)
      fs59.closeSync(this.fd);
    cb();
  }
};
var WriteEntryTar = class extends Minipass {
  static {
    __name(this, "WriteEntryTar");
  }
  blockLen = 0;
  blockRemain = 0;
  buf = 0;
  pos = 0;
  remain = 0;
  length = 0;
  preservePaths;
  portable;
  strict;
  noPax;
  noMtime;
  readEntry;
  type;
  prefix;
  path;
  mode;
  uid;
  gid;
  uname;
  gname;
  header;
  mtime;
  atime;
  ctime;
  linkpath;
  size;
  onWriteEntry;
  warn(code2, message, data = {}) {
    return warnMethod(this, code2, message, data);
  }
  constructor(readEntry, opt_ = {}) {
    const opt = dealias(opt_);
    super();
    this.preservePaths = !!opt.preservePaths;
    this.portable = !!opt.portable;
    this.strict = !!opt.strict;
    this.noPax = !!opt.noPax;
    this.noMtime = !!opt.noMtime;
    this.onWriteEntry = opt.onWriteEntry;
    this.readEntry = readEntry;
    const { type } = readEntry;
    if (type === "Unsupported") {
      throw new Error("writing entry that should be ignored");
    }
    this.type = type;
    if (this.type === "Directory" && this.portable) {
      this.noMtime = true;
    }
    this.prefix = opt.prefix;
    this.path = normalizeWindowsPath(readEntry.path);
    this.mode = readEntry.mode !== void 0 ? this[MODE](readEntry.mode) : void 0;
    this.uid = this.portable ? void 0 : readEntry.uid;
    this.gid = this.portable ? void 0 : readEntry.gid;
    this.uname = this.portable ? void 0 : readEntry.uname;
    this.gname = this.portable ? void 0 : readEntry.gname;
    this.size = readEntry.size;
    this.mtime = this.noMtime ? void 0 : opt.mtime || readEntry.mtime;
    this.atime = this.portable ? void 0 : readEntry.atime;
    this.ctime = this.portable ? void 0 : readEntry.ctime;
    this.linkpath = readEntry.linkpath !== void 0 ? normalizeWindowsPath(readEntry.linkpath) : void 0;
    if (typeof opt.onwarn === "function") {
      this.on("warn", opt.onwarn);
    }
    let pathWarn = false;
    if (!this.preservePaths) {
      const [root, stripped] = stripAbsolutePath(this.path);
      if (root && typeof stripped === "string") {
        this.path = stripped;
        pathWarn = root;
      }
    }
    this.remain = readEntry.size;
    this.blockRemain = readEntry.startBlockSize;
    this.onWriteEntry?.(this);
    this.header = new Header2({
      path: this[PREFIX](this.path),
      linkpath: this.type === "Link" && this.linkpath !== void 0 ? this[PREFIX](this.linkpath) : this.linkpath,
      // only the permissions and setuid/setgid/sticky bitflags
      // not the higher-order bits that specify file type
      mode: this.mode,
      uid: this.portable ? void 0 : this.uid,
      gid: this.portable ? void 0 : this.gid,
      size: this.size,
      mtime: this.noMtime ? void 0 : this.mtime,
      type: this.type,
      uname: this.portable ? void 0 : this.uname,
      atime: this.portable ? void 0 : this.atime,
      ctime: this.portable ? void 0 : this.ctime
    });
    if (pathWarn) {
      this.warn("TAR_ENTRY_INFO", `stripping ${pathWarn} from absolute path`, {
        entry: this,
        path: pathWarn + this.path
      });
    }
    if (this.header.encode() && !this.noPax) {
      super.write(new Pax({
        atime: this.portable ? void 0 : this.atime,
        ctime: this.portable ? void 0 : this.ctime,
        gid: this.portable ? void 0 : this.gid,
        mtime: this.noMtime ? void 0 : this.mtime,
        path: this[PREFIX](this.path),
        linkpath: this.type === "Link" && this.linkpath !== void 0 ? this[PREFIX](this.linkpath) : this.linkpath,
        size: this.size,
        uid: this.portable ? void 0 : this.uid,
        uname: this.portable ? void 0 : this.uname,
        dev: this.portable ? void 0 : this.readEntry.dev,
        ino: this.portable ? void 0 : this.readEntry.ino,
        nlink: this.portable ? void 0 : this.readEntry.nlink
      }).encode());
    }
    const b = this.header?.block;
    if (!b)
      throw new Error("failed to encode header");
    super.write(b);
    readEntry.pipe(this);
  }
  [PREFIX](path108) {
    return prefixPath(path108, this.prefix);
  }
  [MODE](mode) {
    return modeFix(mode, this.type === "Directory", this.portable);
  }
  write(chunk, encoding, cb) {
    if (typeof encoding === "function") {
      cb = encoding;
      encoding = void 0;
    }
    if (typeof chunk === "string") {
      chunk = Buffer.from(chunk, typeof encoding === "string" ? encoding : "utf8");
    }
    const writeLen = chunk.length;
    if (writeLen > this.blockRemain) {
      throw new Error("writing more to entry than is appropriate");
    }
    this.blockRemain -= writeLen;
    return super.write(chunk, cb);
  }
  end(chunk, encoding, cb) {
    if (this.blockRemain) {
      super.write(Buffer.alloc(this.blockRemain));
    }
    if (typeof chunk === "function") {
      cb = chunk;
      encoding = void 0;
      chunk = void 0;
    }
    if (typeof encoding === "function") {
      cb = encoding;
      encoding = void 0;
    }
    if (typeof chunk === "string") {
      chunk = Buffer.from(chunk, encoding ?? "utf8");
    }
    if (cb)
      this.once("finish", cb);
    chunk ? super.end(chunk, cb) : super.end(cb);
    return this;
  }
};
var getType = /* @__PURE__ */ __name((stat7) => stat7.isFile() ? "File" : stat7.isDirectory() ? "Directory" : stat7.isSymbolicLink() ? "SymbolicLink" : "Unsupported", "getType");

// node_modules/tar/dist/esm/pack.js
init_esm7();

// node_modules/yallist/dist/esm/index.js
init_esbuild_shims();
var Yallist = class _Yallist {
  static {
    __name(this, "Yallist");
  }
  tail;
  head;
  length = 0;
  static create(list3 = []) {
    return new _Yallist(list3);
  }
  constructor(list3 = []) {
    for (const item of list3) {
      this.push(item);
    }
  }
  *[Symbol.iterator]() {
    for (let walker = this.head; walker; walker = walker.next) {
      yield walker.value;
    }
  }
  removeNode(node) {
    if (node.list !== this) {
      throw new Error("removing node which does not belong to this list");
    }
    const next = node.next;
    const prev = node.prev;
    if (next) {
      next.prev = prev;
    }
    if (prev) {
      prev.next = next;
    }
    if (node === this.head) {
      this.head = next;
    }
    if (node === this.tail) {
      this.tail = prev;
    }
    this.length--;
    node.next = void 0;
    node.prev = void 0;
    node.list = void 0;
    return next;
  }
  unshiftNode(node) {
    if (node === this.head) {
      return;
    }
    if (node.list) {
      node.list.removeNode(node);
    }
    const head = this.head;
    node.list = this;
    node.next = head;
    if (head) {
      head.prev = node;
    }
    this.head = node;
    if (!this.tail) {
      this.tail = node;
    }
    this.length++;
  }
  pushNode(node) {
    if (node === this.tail) {
      return;
    }
    if (node.list) {
      node.list.removeNode(node);
    }
    const tail = this.tail;
    node.list = this;
    node.prev = tail;
    if (tail) {
      tail.next = node;
    }
    this.tail = node;
    if (!this.head) {
      this.head = node;
    }
    this.length++;
  }
  push(...args) {
    for (let i = 0, l2 = args.length; i < l2; i++) {
      push(this, args[i]);
    }
    return this.length;
  }
  unshift(...args) {
    for (var i = 0, l2 = args.length; i < l2; i++) {
      unshift(this, args[i]);
    }
    return this.length;
  }
  pop() {
    if (!this.tail) {
      return void 0;
    }
    const res = this.tail.value;
    const t2 = this.tail;
    this.tail = this.tail.prev;
    if (this.tail) {
      this.tail.next = void 0;
    } else {
      this.head = void 0;
    }
    t2.list = void 0;
    this.length--;
    return res;
  }
  shift() {
    if (!this.head) {
      return void 0;
    }
    const res = this.head.value;
    const h = this.head;
    this.head = this.head.next;
    if (this.head) {
      this.head.prev = void 0;
    } else {
      this.tail = void 0;
    }
    h.list = void 0;
    this.length--;
    return res;
  }
  forEach(fn, thisp) {
    thisp = thisp || this;
    for (let walker = this.head, i = 0; !!walker; i++) {
      fn.call(thisp, walker.value, i, this);
      walker = walker.next;
    }
  }
  forEachReverse(fn, thisp) {
    thisp = thisp || this;
    for (let walker = this.tail, i = this.length - 1; !!walker; i--) {
      fn.call(thisp, walker.value, i, this);
      walker = walker.prev;
    }
  }
  get(n2) {
    let i = 0;
    let walker = this.head;
    for (; !!walker && i < n2; i++) {
      walker = walker.next;
    }
    if (i === n2 && !!walker) {
      return walker.value;
    }
  }
  getReverse(n2) {
    let i = 0;
    let walker = this.tail;
    for (; !!walker && i < n2; i++) {
      walker = walker.prev;
    }
    if (i === n2 && !!walker) {
      return walker.value;
    }
  }
  map(fn, thisp) {
    thisp = thisp || this;
    const res = new _Yallist();
    for (let walker = this.head; !!walker; ) {
      res.push(fn.call(thisp, walker.value, this));
      walker = walker.next;
    }
    return res;
  }
  mapReverse(fn, thisp) {
    thisp = thisp || this;
    var res = new _Yallist();
    for (let walker = this.tail; !!walker; ) {
      res.push(fn.call(thisp, walker.value, this));
      walker = walker.prev;
    }
    return res;
  }
  reduce(fn, initial) {
    let acc;
    let walker = this.head;
    if (arguments.length > 1) {
      acc = initial;
    } else if (this.head) {
      walker = this.head.next;
      acc = this.head.value;
    } else {
      throw new TypeError("Reduce of empty list with no initial value");
    }
    for (var i = 0; !!walker; i++) {
      acc = fn(acc, walker.value, i);
      walker = walker.next;
    }
    return acc;
  }
  reduceReverse(fn, initial) {
    let acc;
    let walker = this.tail;
    if (arguments.length > 1) {
      acc = initial;
    } else if (this.tail) {
      walker = this.tail.prev;
      acc = this.tail.value;
    } else {
      throw new TypeError("Reduce of empty list with no initial value");
    }
    for (let i = this.length - 1; !!walker; i--) {
      acc = fn(acc, walker.value, i);
      walker = walker.prev;
    }
    return acc;
  }
  toArray() {
    const arr = new Array(this.length);
    for (let i = 0, walker = this.head; !!walker; i++) {
      arr[i] = walker.value;
      walker = walker.next;
    }
    return arr;
  }
  toArrayReverse() {
    const arr = new Array(this.length);
    for (let i = 0, walker = this.tail; !!walker; i++) {
      arr[i] = walker.value;
      walker = walker.prev;
    }
    return arr;
  }
  slice(from = 0, to = this.length) {
    if (to < 0) {
      to += this.length;
    }
    if (from < 0) {
      from += this.length;
    }
    const ret = new _Yallist();
    if (to < from || to < 0) {
      return ret;
    }
    if (from < 0) {
      from = 0;
    }
    if (to > this.length) {
      to = this.length;
    }
    let walker = this.head;
    let i = 0;
    for (i = 0; !!walker && i < from; i++) {
      walker = walker.next;
    }
    for (; !!walker && i < to; i++, walker = walker.next) {
      ret.push(walker.value);
    }
    return ret;
  }
  sliceReverse(from = 0, to = this.length) {
    if (to < 0) {
      to += this.length;
    }
    if (from < 0) {
      from += this.length;
    }
    const ret = new _Yallist();
    if (to < from || to < 0) {
      return ret;
    }
    if (from < 0) {
      from = 0;
    }
    if (to > this.length) {
      to = this.length;
    }
    let i = this.length;
    let walker = this.tail;
    for (; !!walker && i > to; i--) {
      walker = walker.prev;
    }
    for (; !!walker && i > from; i--, walker = walker.prev) {
      ret.push(walker.value);
    }
    return ret;
  }
  splice(start, deleteCount = 0, ...nodes) {
    if (start > this.length) {
      start = this.length - 1;
    }
    if (start < 0) {
      start = this.length + start;
    }
    let walker = this.head;
    for (let i = 0; !!walker && i < start; i++) {
      walker = walker.next;
    }
    const ret = [];
    for (let i = 0; !!walker && i < deleteCount; i++) {
      ret.push(walker.value);
      walker = this.removeNode(walker);
    }
    if (!walker) {
      walker = this.tail;
    } else if (walker !== this.tail) {
      walker = walker.prev;
    }
    for (const v of nodes) {
      walker = insertAfter(this, walker, v);
    }
    return ret;
  }
  reverse() {
    const head = this.head;
    const tail = this.tail;
    for (let walker = head; !!walker; walker = walker.prev) {
      const p = walker.prev;
      walker.prev = walker.next;
      walker.next = p;
    }
    this.head = tail;
    this.tail = head;
    return this;
  }
};
function insertAfter(self2, node, value) {
  const prev = node;
  const next = node ? node.next : self2.head;
  const inserted = new Node3(value, prev, next, self2);
  if (inserted.next === void 0) {
    self2.tail = inserted;
  }
  if (inserted.prev === void 0) {
    self2.head = inserted;
  }
  self2.length++;
  return inserted;
}
__name(insertAfter, "insertAfter");
function push(self2, item) {
  self2.tail = new Node3(item, self2.tail, void 0, self2);
  if (!self2.head) {
    self2.head = self2.tail;
  }
  self2.length++;
}
__name(push, "push");
function unshift(self2, item) {
  self2.head = new Node3(item, void 0, self2.head, self2);
  if (!self2.tail) {
    self2.tail = self2.head;
  }
  self2.length++;
}
__name(unshift, "unshift");
var Node3 = class {
  static {
    __name(this, "Node");
  }
  list;
  next;
  prev;
  value;
  constructor(value, prev, next, list3) {
    this.list = list3;
    this.value = value;
    if (prev) {
      prev.next = this;
      this.prev = prev;
    } else {
      this.prev = void 0;
    }
    if (next) {
      next.prev = this;
      this.next = next;
    } else {
      this.next = void 0;
    }
  }
};

// node_modules/tar/dist/esm/pack.js
import path63 from "path";
var PackJob = class {
  static {
    __name(this, "PackJob");
  }
  path;
  absolute;
  entry;
  stat;
  readdir;
  pending = false;
  ignore = false;
  piped = false;
  constructor(path108, absolute) {
    this.path = path108 || "./";
    this.absolute = absolute;
  }
};
var EOF2 = Buffer.alloc(1024);
var ONSTAT = Symbol("onStat");
var ENDED2 = Symbol("ended");
var QUEUE2 = Symbol("queue");
var CURRENT = Symbol("current");
var PROCESS3 = Symbol("process");
var PROCESSING = Symbol("processing");
var PROCESSJOB = Symbol("processJob");
var JOBS = Symbol("jobs");
var JOBDONE = Symbol("jobDone");
var ADDFSENTRY = Symbol("addFSEntry");
var ADDTARENTRY = Symbol("addTarEntry");
var STAT = Symbol("stat");
var READDIR = Symbol("readdir");
var ONREADDIR = Symbol("onreaddir");
var PIPE = Symbol("pipe");
var ENTRY = Symbol("entry");
var ENTRYOPT = Symbol("entryOpt");
var WRITEENTRYCLASS = Symbol("writeEntryClass");
var WRITE = Symbol("write");
var ONDRAIN2 = Symbol("ondrain");
var Pack = class extends Minipass {
  static {
    __name(this, "Pack");
  }
  opt;
  cwd;
  maxReadSize;
  preservePaths;
  strict;
  noPax;
  prefix;
  linkCache;
  statCache;
  file;
  portable;
  zip;
  readdirCache;
  noDirRecurse;
  follow;
  noMtime;
  mtime;
  filter;
  jobs;
  [WRITEENTRYCLASS];
  onWriteEntry;
  // Note: we actually DO need a linked list here, because we
  // shift() to update the head of the list where we start, but still
  // while that happens, need to know what the next item in the queue
  // will be. Since we do multiple jobs in parallel, it's not as simple
  // as just an Array.shift(), since that would lose the information about
  // the next job in the list. We could add a .next field on the PackJob
  // class, but then we'd have to be tracking the tail of the queue the
  // whole time, and Yallist just does that for us anyway.
  [QUEUE2];
  [JOBS] = 0;
  [PROCESSING] = false;
  [ENDED2] = false;
  constructor(opt = {}) {
    super();
    this.opt = opt;
    this.file = opt.file || "";
    this.cwd = opt.cwd || process.cwd();
    this.maxReadSize = opt.maxReadSize;
    this.preservePaths = !!opt.preservePaths;
    this.strict = !!opt.strict;
    this.noPax = !!opt.noPax;
    this.prefix = normalizeWindowsPath(opt.prefix || "");
    this.linkCache = opt.linkCache || /* @__PURE__ */ new Map();
    this.statCache = opt.statCache || /* @__PURE__ */ new Map();
    this.readdirCache = opt.readdirCache || /* @__PURE__ */ new Map();
    this.onWriteEntry = opt.onWriteEntry;
    this[WRITEENTRYCLASS] = WriteEntry;
    if (typeof opt.onwarn === "function") {
      this.on("warn", opt.onwarn);
    }
    this.portable = !!opt.portable;
    if (opt.gzip || opt.brotli || opt.zstd) {
      if ((opt.gzip ? 1 : 0) + (opt.brotli ? 1 : 0) + (opt.zstd ? 1 : 0) > 1) {
        throw new TypeError("gzip, brotli, zstd are mutually exclusive");
      }
      if (opt.gzip) {
        if (typeof opt.gzip !== "object") {
          opt.gzip = {};
        }
        if (this.portable) {
          opt.gzip.portable = true;
        }
        this.zip = new Gzip(opt.gzip);
      }
      if (opt.brotli) {
        if (typeof opt.brotli !== "object") {
          opt.brotli = {};
        }
        this.zip = new BrotliCompress(opt.brotli);
      }
      if (opt.zstd) {
        if (typeof opt.zstd !== "object") {
          opt.zstd = {};
        }
        this.zip = new ZstdCompress(opt.zstd);
      }
      if (!this.zip)
        throw new Error("impossible");
      const zip = this.zip;
      zip.on("data", (chunk) => super.write(chunk));
      zip.on("end", () => super.end());
      zip.on("drain", () => this[ONDRAIN2]());
      this.on("resume", () => zip.resume());
    } else {
      this.on("drain", this[ONDRAIN2]);
    }
    this.noDirRecurse = !!opt.noDirRecurse;
    this.follow = !!opt.follow;
    this.noMtime = !!opt.noMtime;
    if (opt.mtime)
      this.mtime = opt.mtime;
    this.filter = typeof opt.filter === "function" ? opt.filter : () => true;
    this[QUEUE2] = new Yallist();
    this[JOBS] = 0;
    this.jobs = Number(opt.jobs) || 4;
    this[PROCESSING] = false;
    this[ENDED2] = false;
  }
  [WRITE](chunk) {
    return super.write(chunk);
  }
  add(path108) {
    this.write(path108);
    return this;
  }
  end(path108, encoding, cb) {
    if (typeof path108 === "function") {
      cb = path108;
      path108 = void 0;
    }
    if (typeof encoding === "function") {
      cb = encoding;
      encoding = void 0;
    }
    if (path108) {
      this.add(path108);
    }
    this[ENDED2] = true;
    this[PROCESS3]();
    if (cb)
      cb();
    return this;
  }
  write(path108) {
    if (this[ENDED2]) {
      throw new Error("write after end");
    }
    if (path108 instanceof ReadEntry) {
      this[ADDTARENTRY](path108);
    } else {
      this[ADDFSENTRY](path108);
    }
    return this.flowing;
  }
  [ADDTARENTRY](p) {
    const absolute = normalizeWindowsPath(path63.resolve(this.cwd, p.path));
    if (!this.filter(p.path, p)) {
      p.resume();
    } else {
      const job = new PackJob(p.path, absolute);
      job.entry = new WriteEntryTar(p, this[ENTRYOPT](job));
      job.entry.on("end", () => this[JOBDONE](job));
      this[JOBS] += 1;
      this[QUEUE2].push(job);
    }
    this[PROCESS3]();
  }
  [ADDFSENTRY](p) {
    const absolute = normalizeWindowsPath(path63.resolve(this.cwd, p));
    this[QUEUE2].push(new PackJob(p, absolute));
    this[PROCESS3]();
  }
  [STAT](job) {
    job.pending = true;
    this[JOBS] += 1;
    const stat7 = this.follow ? "stat" : "lstat";
    fs60[stat7](job.absolute, (er, stat8) => {
      job.pending = false;
      this[JOBS] -= 1;
      if (er) {
        this.emit("error", er);
      } else {
        this[ONSTAT](job, stat8);
      }
    });
  }
  [ONSTAT](job, stat7) {
    this.statCache.set(job.absolute, stat7);
    job.stat = stat7;
    if (!this.filter(job.path, stat7)) {
      job.ignore = true;
    }
    this[PROCESS3]();
  }
  [READDIR](job) {
    job.pending = true;
    this[JOBS] += 1;
    fs60.readdir(job.absolute, (er, entries) => {
      job.pending = false;
      this[JOBS] -= 1;
      if (er) {
        return this.emit("error", er);
      }
      this[ONREADDIR](job, entries);
    });
  }
  [ONREADDIR](job, entries) {
    this.readdirCache.set(job.absolute, entries);
    job.readdir = entries;
    this[PROCESS3]();
  }
  [PROCESS3]() {
    if (this[PROCESSING]) {
      return;
    }
    this[PROCESSING] = true;
    for (let w = this[QUEUE2].head; !!w && this[JOBS] < this.jobs; w = w.next) {
      this[PROCESSJOB](w.value);
      if (w.value.ignore) {
        const p = w.next;
        this[QUEUE2].removeNode(w);
        w.next = p;
      }
    }
    this[PROCESSING] = false;
    if (this[ENDED2] && !this[QUEUE2].length && this[JOBS] === 0) {
      if (this.zip) {
        this.zip.end(EOF2);
      } else {
        super.write(EOF2);
        super.end();
      }
    }
  }
  get [CURRENT]() {
    return this[QUEUE2] && this[QUEUE2].head && this[QUEUE2].head.value;
  }
  [JOBDONE](_job) {
    this[QUEUE2].shift();
    this[JOBS] -= 1;
    this[PROCESS3]();
  }
  [PROCESSJOB](job) {
    if (job.pending) {
      return;
    }
    if (job.entry) {
      if (job === this[CURRENT] && !job.piped) {
        this[PIPE](job);
      }
      return;
    }
    if (!job.stat) {
      const sc = this.statCache.get(job.absolute);
      if (sc) {
        this[ONSTAT](job, sc);
      } else {
        this[STAT](job);
      }
    }
    if (!job.stat) {
      return;
    }
    if (job.ignore) {
      return;
    }
    if (!this.noDirRecurse && job.stat.isDirectory() && !job.readdir) {
      const rc2 = this.readdirCache.get(job.absolute);
      if (rc2) {
        this[ONREADDIR](job, rc2);
      } else {
        this[READDIR](job);
      }
      if (!job.readdir) {
        return;
      }
    }
    job.entry = this[ENTRY](job);
    if (!job.entry) {
      job.ignore = true;
      return;
    }
    if (job === this[CURRENT] && !job.piped) {
      this[PIPE](job);
    }
  }
  [ENTRYOPT](job) {
    return {
      onwarn: /* @__PURE__ */ __name((code2, msg, data) => this.warn(code2, msg, data), "onwarn"),
      noPax: this.noPax,
      cwd: this.cwd,
      absolute: job.absolute,
      preservePaths: this.preservePaths,
      maxReadSize: this.maxReadSize,
      strict: this.strict,
      portable: this.portable,
      linkCache: this.linkCache,
      statCache: this.statCache,
      noMtime: this.noMtime,
      mtime: this.mtime,
      prefix: this.prefix,
      onWriteEntry: this.onWriteEntry
    };
  }
  [ENTRY](job) {
    this[JOBS] += 1;
    try {
      const e2 = new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job));
      return e2.on("end", () => this[JOBDONE](job)).on("error", (er) => this.emit("error", er));
    } catch (er) {
      this.emit("error", er);
    }
  }
  [ONDRAIN2]() {
    if (this[CURRENT] && this[CURRENT].entry) {
      this[CURRENT].entry.resume();
    }
  }
  // like .pipe() but using super, because our write() is special
  [PIPE](job) {
    job.piped = true;
    if (job.readdir) {
      job.readdir.forEach((entry) => {
        const p = job.path;
        const base = p === "./" ? "" : p.replace(/\/*$/, "/");
        this[ADDFSENTRY](base + entry);
      });
    }
    const source2 = job.entry;
    const zip = this.zip;
    if (!source2)
      throw new Error("cannot pipe without source");
    if (zip) {
      source2.on("data", (chunk) => {
        if (!zip.write(chunk)) {
          source2.pause();
        }
      });
    } else {
      source2.on("data", (chunk) => {
        if (!super.write(chunk)) {
          source2.pause();
        }
      });
    }
  }
  pause() {
    if (this.zip) {
      this.zip.pause();
    }
    return super.pause();
  }
  warn(code2, message, data = {}) {
    warnMethod(this, code2, message, data);
  }
};
var PackSync = class extends Pack {
  static {
    __name(this, "PackSync");
  }
  sync = true;
  constructor(opt) {
    super(opt);
    this[WRITEENTRYCLASS] = WriteEntrySync;
  }
  // pause/resume are no-ops in sync streams.
  pause() {
  }
  resume() {
  }
  [STAT](job) {
    const stat7 = this.follow ? "statSync" : "lstatSync";
    this[ONSTAT](job, fs60[stat7](job.absolute));
  }
  [READDIR](job) {
    this[ONREADDIR](job, fs60.readdirSync(job.absolute));
  }
  // gotta get it all in this tick
  [PIPE](job) {
    const source2 = job.entry;
    const zip = this.zip;
    if (job.readdir) {
      job.readdir.forEach((entry) => {
        const p = job.path;
        const base = p === "./" ? "" : p.replace(/\/*$/, "/");
        this[ADDFSENTRY](base + entry);
      });
    }
    if (!source2)
      throw new Error("Cannot pipe without source");
    if (zip) {
      source2.on("data", (chunk) => {
        zip.write(chunk);
      });
    } else {
      source2.on("data", (chunk) => {
        super[WRITE](chunk);
      });
    }
  }
};

// node_modules/tar/dist/esm/create.js
var createFileSync = /* @__PURE__ */ __name((opt, files) => {
  const p = new PackSync(opt);
  const stream2 = new WriteStreamSync(opt.file, {
    mode: opt.mode || 438
  });
  p.pipe(stream2);
  addFilesSync(p, files);
}, "createFileSync");
var createFile = /* @__PURE__ */ __name((opt, files) => {
  const p = new Pack(opt);
  const stream2 = new WriteStream(opt.file, {
    mode: opt.mode || 438
  });
  p.pipe(stream2);
  const promise = new Promise((res, rej) => {
    stream2.on("error", rej);
    stream2.on("close", res);
    p.on("error", rej);
  });
  addFilesAsync(p, files);
  return promise;
}, "createFile");
var addFilesSync = /* @__PURE__ */ __name((p, files) => {
  files.forEach((file) => {
    if (file.charAt(0) === "@") {
      list2({
        file: path64.resolve(p.cwd, file.slice(1)),
        sync: true,
        noResume: true,
        onReadEntry: /* @__PURE__ */ __name((entry) => p.add(entry), "onReadEntry")
      });
    } else {
      p.add(file);
    }
  });
  p.end();
}, "addFilesSync");
var addFilesAsync = /* @__PURE__ */ __name(async (p, files) => {
  for (let i = 0; i < files.length; i++) {
    const file = String(files[i]);
    if (file.charAt(0) === "@") {
      await list2({
        file: path64.resolve(String(p.cwd), file.slice(1)),
        noResume: true,
        onReadEntry: /* @__PURE__ */ __name((entry) => {
          p.add(entry);
        }, "onReadEntry")
      });
    } else {
      p.add(file);
    }
  }
  p.end();
}, "addFilesAsync");
var createSync = /* @__PURE__ */ __name((opt, files) => {
  const p = new PackSync(opt);
  addFilesSync(p, files);
  return p;
}, "createSync");
var createAsync = /* @__PURE__ */ __name((opt, files) => {
  const p = new Pack(opt);
  addFilesAsync(p, files);
  return p;
}, "createAsync");
var create2 = makeCommand(createFileSync, createFile, createSync, createAsync, (_opt, files) => {
  if (!files?.length) {
    throw new TypeError("no paths specified to add to archive");
  }
});

// node_modules/tar/dist/esm/extract.js
init_esbuild_shims();
import fs65 from "node:fs";

// node_modules/tar/dist/esm/unpack.js
init_esbuild_shims();
import assert2 from "node:assert";
import { randomBytes as randomBytes4 } from "node:crypto";
import fs64 from "node:fs";
import path67 from "node:path";

// node_modules/tar/dist/esm/get-write-flag.js
init_esbuild_shims();
import fs61 from "fs";
var platform8 = process.env.__FAKE_PLATFORM__ || process.platform;
var isWindows4 = platform8 === "win32";
var { O_CREAT, O_TRUNC, O_WRONLY } = fs61.constants;
var UV_FS_O_FILEMAP = Number(process.env.__FAKE_FS_O_FILENAME__) || fs61.constants.UV_FS_O_FILEMAP || 0;
var fMapEnabled = isWindows4 && !!UV_FS_O_FILEMAP;
var fMapLimit = 512 * 1024;
var fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY;
var getWriteFlag = !fMapEnabled ? () => "w" : (size) => size < fMapLimit ? fMapFlag : "w";

// node_modules/tar/dist/esm/mkdir.js
init_esbuild_shims();

// node_modules/chownr/dist/esm/index.js
init_esbuild_shims();
import fs62 from "node:fs";
import path65 from "node:path";
var lchownSync = /* @__PURE__ */ __name((path108, uid, gid) => {
  try {
    return fs62.lchownSync(path108, uid, gid);
  } catch (er) {
    if (er?.code !== "ENOENT")
      throw er;
  }
}, "lchownSync");
var chown = /* @__PURE__ */ __name((cpath, uid, gid, cb) => {
  fs62.lchown(cpath, uid, gid, (er) => {
    cb(er && er?.code !== "ENOENT" ? er : null);
  });
}, "chown");
var chownrKid = /* @__PURE__ */ __name((p, child, uid, gid, cb) => {
  if (child.isDirectory()) {
    chownr(path65.resolve(p, child.name), uid, gid, (er) => {
      if (er)
        return cb(er);
      const cpath = path65.resolve(p, child.name);
      chown(cpath, uid, gid, cb);
    });
  } else {
    const cpath = path65.resolve(p, child.name);
    chown(cpath, uid, gid, cb);
  }
}, "chownrKid");
var chownr = /* @__PURE__ */ __name((p, uid, gid, cb) => {
  fs62.readdir(p, { withFileTypes: true }, (er, children) => {
    if (er) {
      if (er.code === "ENOENT")
        return cb();
      else if (er.code !== "ENOTDIR" && er.code !== "ENOTSUP")
        return cb(er);
    }
    if (er || !children.length)
      return chown(p, uid, gid, cb);
    let len = children.length;
    let errState = null;
    const then = /* @__PURE__ */ __name((er2) => {
      if (errState)
        return;
      if (er2)
        return cb(errState = er2);
      if (--len === 0)
        return chown(p, uid, gid, cb);
    }, "then");
    for (const child of children) {
      chownrKid(p, child, uid, gid, then);
    }
  });
}, "chownr");
var chownrKidSync = /* @__PURE__ */ __name((p, child, uid, gid) => {
  if (child.isDirectory())
    chownrSync(path65.resolve(p, child.name), uid, gid);
  lchownSync(path65.resolve(p, child.name), uid, gid);
}, "chownrKidSync");
var chownrSync = /* @__PURE__ */ __name((p, uid, gid) => {
  let children;
  try {
    children = fs62.readdirSync(p, { withFileTypes: true });
  } catch (er) {
    const e2 = er;
    if (e2?.code === "ENOENT")
      return;
    else if (e2?.code === "ENOTDIR" || e2?.code === "ENOTSUP")
      return lchownSync(p, uid, gid);
    else
      throw e2;
  }
  for (const child of children) {
    chownrKidSync(p, child, uid, gid);
  }
  return lchownSync(p, uid, gid);
}, "chownrSync");

// node_modules/tar/dist/esm/mkdir.js
import fs63 from "node:fs";
import fsp2 from "node:fs/promises";
import path66 from "node:path";

// node_modules/tar/dist/esm/cwd-error.js
init_esbuild_shims();
var CwdError = class extends Error {
  static {
    __name(this, "CwdError");
  }
  path;
  code;
  syscall = "chdir";
  constructor(path108, code2) {
    super(`${code2}: Cannot cd into '${path108}'`);
    this.path = path108;
    this.code = code2;
  }
  get name() {
    return "CwdError";
  }
};

// node_modules/tar/dist/esm/symlink-error.js
init_esbuild_shims();
var SymlinkError = class extends Error {
  static {
    __name(this, "SymlinkError");
  }
  path;
  symlink;
  syscall = "symlink";
  code = "TAR_SYMLINK_ERROR";
  constructor(symlink, path108) {
    super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link");
    this.symlink = symlink;
    this.path = path108;
  }
  get name() {
    return "SymlinkError";
  }
};

// node_modules/tar/dist/esm/mkdir.js
var checkCwd = /* @__PURE__ */ __name((dir, cb) => {
  fs63.stat(dir, (er, st) => {
    if (er || !st.isDirectory()) {
      er = new CwdError(dir, er?.code || "ENOTDIR");
    }
    cb(er);
  });
}, "checkCwd");
var mkdir5 = /* @__PURE__ */ __name((dir, opt, cb) => {
  dir = normalizeWindowsPath(dir);
  const umask = opt.umask ?? 18;
  const mode = opt.mode | 448;
  const needChmod = (mode & umask) !== 0;
  const uid = opt.uid;
  const gid = opt.gid;
  const doChown = typeof uid === "number" && typeof gid === "number" && (uid !== opt.processUid || gid !== opt.processGid);
  const preserve = opt.preserve;
  const unlink3 = opt.unlink;
  const cwd7 = normalizeWindowsPath(opt.cwd);
  const done = /* @__PURE__ */ __name((er, created) => {
    if (er) {
      cb(er);
    } else {
      if (created && doChown) {
        chownr(created, uid, gid, (er2) => done(er2));
      } else if (needChmod) {
        fs63.chmod(dir, mode, cb);
      } else {
        cb();
      }
    }
  }, "done");
  if (dir === cwd7) {
    return checkCwd(dir, done);
  }
  if (preserve) {
    return fsp2.mkdir(dir, { mode, recursive: true }).then(
      (made) => done(null, made ?? void 0),
      // oh, ts
      done
    );
  }
  const sub = normalizeWindowsPath(path66.relative(cwd7, dir));
  const parts = sub.split("/");
  mkdir_(cwd7, parts, mode, unlink3, cwd7, void 0, done);
}, "mkdir");
var mkdir_ = /* @__PURE__ */ __name((base, parts, mode, unlink3, cwd7, created, cb) => {
  if (!parts.length) {
    return cb(null, created);
  }
  const p = parts.shift();
  const part = normalizeWindowsPath(path66.resolve(base + "/" + p));
  fs63.mkdir(part, mode, onmkdir(part, parts, mode, unlink3, cwd7, created, cb));
}, "mkdir_");
var onmkdir = /* @__PURE__ */ __name((part, parts, mode, unlink3, cwd7, created, cb) => (er) => {
  if (er) {
    fs63.lstat(part, (statEr, st) => {
      if (statEr) {
        statEr.path = statEr.path && normalizeWindowsPath(statEr.path);
        cb(statEr);
      } else if (st.isDirectory()) {
        mkdir_(part, parts, mode, unlink3, cwd7, created, cb);
      } else if (unlink3) {
        fs63.unlink(part, (er2) => {
          if (er2) {
            return cb(er2);
          }
          fs63.mkdir(part, mode, onmkdir(part, parts, mode, unlink3, cwd7, created, cb));
        });
      } else if (st.isSymbolicLink()) {
        return cb(new SymlinkError(part, part + "/" + parts.join("/")));
      } else {
        cb(er);
      }
    });
  } else {
    created = created || part;
    mkdir_(part, parts, mode, unlink3, cwd7, created, cb);
  }
}, "onmkdir");
var checkCwdSync = /* @__PURE__ */ __name((dir) => {
  let ok2 = false;
  let code2 = void 0;
  try {
    ok2 = fs63.statSync(dir).isDirectory();
  } catch (er) {
    code2 = er?.code;
  } finally {
    if (!ok2) {
      throw new CwdError(dir, code2 ?? "ENOTDIR");
    }
  }
}, "checkCwdSync");
var mkdirSync6 = /* @__PURE__ */ __name((dir, opt) => {
  dir = normalizeWindowsPath(dir);
  const umask = opt.umask ?? 18;
  const mode = opt.mode | 448;
  const needChmod = (mode & umask) !== 0;
  const uid = opt.uid;
  const gid = opt.gid;
  const doChown = typeof uid === "number" && typeof gid === "number" && (uid !== opt.processUid || gid !== opt.processGid);
  const preserve = opt.preserve;
  const unlink3 = opt.unlink;
  const cwd7 = normalizeWindowsPath(opt.cwd);
  const done = /* @__PURE__ */ __name((created2) => {
    if (created2 && doChown) {
      chownrSync(created2, uid, gid);
    }
    if (needChmod) {
      fs63.chmodSync(dir, mode);
    }
  }, "done");
  if (dir === cwd7) {
    checkCwdSync(cwd7);
    return done();
  }
  if (preserve) {
    return done(fs63.mkdirSync(dir, { mode, recursive: true }) ?? void 0);
  }
  const sub = normalizeWindowsPath(path66.relative(cwd7, dir));
  const parts = sub.split("/");
  let created = void 0;
  for (let p = parts.shift(), part = cwd7; p && (part += "/" + p); p = parts.shift()) {
    part = normalizeWindowsPath(path66.resolve(part));
    try {
      fs63.mkdirSync(part, mode);
      created = created || part;
    } catch (er) {
      const st = fs63.lstatSync(part);
      if (st.isDirectory()) {
        continue;
      } else if (unlink3) {
        fs63.unlinkSync(part);
        fs63.mkdirSync(part, mode);
        created = created || part;
        continue;
      } else if (st.isSymbolicLink()) {
        return new SymlinkError(part, part + "/" + parts.join("/"));
      }
    }
  }
  return done(created);
}, "mkdirSync");

// node_modules/tar/dist/esm/path-reservations.js
init_esbuild_shims();
import { join as join26 } from "node:path";

// node_modules/tar/dist/esm/normalize-unicode.js
init_esbuild_shims();
var normalizeCache2 = /* @__PURE__ */ Object.create(null);
var MAX = 1e4;
var cache4 = /* @__PURE__ */ new Set();
var normalizeUnicode = /* @__PURE__ */ __name((s2) => {
  if (!cache4.has(s2)) {
    normalizeCache2[s2] = s2.normalize("NFD");
  } else {
    cache4.delete(s2);
  }
  cache4.add(s2);
  const ret = normalizeCache2[s2];
  let i = cache4.size - MAX;
  if (i > MAX / 10) {
    for (const s3 of cache4) {
      cache4.delete(s3);
      delete normalizeCache2[s3];
      if (--i <= 0)
        break;
    }
  }
  return ret;
}, "normalizeUnicode");

// node_modules/tar/dist/esm/path-reservations.js
var platform9 = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
var isWindows5 = platform9 === "win32";
var getDirs = /* @__PURE__ */ __name((path108) => {
  const dirs = path108.split("/").slice(0, -1).reduce((set, path109) => {
    const s2 = set[set.length - 1];
    if (s2 !== void 0) {
      path109 = join26(s2, path109);
    }
    set.push(path109 || "/");
    return set;
  }, []);
  return dirs;
}, "getDirs");
var PathReservations = class {
  static {
    __name(this, "PathReservations");
  }
  // path => [function or Set]
  // A Set object means a directory reservation
  // A fn is a direct reservation on that path
  #queues = /* @__PURE__ */ new Map();
  // fn => {paths:[path,...], dirs:[path, ...]}
  #reservations = /* @__PURE__ */ new Map();
  // functions currently running
  #running = /* @__PURE__ */ new Set();
  reserve(paths, fn) {
    paths = isWindows5 ? ["win32 parallelization disabled"] : paths.map((p) => {
      return stripTrailingSlashes(join26(normalizeUnicode(p))).toLowerCase();
    });
    const dirs = new Set(paths.map((path108) => getDirs(path108)).reduce((a, b) => a.concat(b)));
    this.#reservations.set(fn, { dirs, paths });
    for (const p of paths) {
      const q = this.#queues.get(p);
      if (!q) {
        this.#queues.set(p, [fn]);
      } else {
        q.push(fn);
      }
    }
    for (const dir of dirs) {
      const q = this.#queues.get(dir);
      if (!q) {
        this.#queues.set(dir, [/* @__PURE__ */ new Set([fn])]);
      } else {
        const l2 = q[q.length - 1];
        if (l2 instanceof Set) {
          l2.add(fn);
        } else {
          q.push(/* @__PURE__ */ new Set([fn]));
        }
      }
    }
    return this.#run(fn);
  }
  // return the queues for each path the function cares about
  // fn => {paths, dirs}
  #getQueues(fn) {
    const res = this.#reservations.get(fn);
    if (!res) {
      throw new Error("function does not have any path reservations");
    }
    return {
      paths: res.paths.map((path108) => this.#queues.get(path108)),
      dirs: [...res.dirs].map((path108) => this.#queues.get(path108))
    };
  }
  // check if fn is first in line for all its paths, and is
  // included in the first set for all its dir queues
  check(fn) {
    const { paths, dirs } = this.#getQueues(fn);
    return paths.every((q) => q && q[0] === fn) && dirs.every((q) => q && q[0] instanceof Set && q[0].has(fn));
  }
  // run the function if it's first in line and not already running
  #run(fn) {
    if (this.#running.has(fn) || !this.check(fn)) {
      return false;
    }
    this.#running.add(fn);
    fn(() => this.#clear(fn));
    return true;
  }
  #clear(fn) {
    if (!this.#running.has(fn)) {
      return false;
    }
    const res = this.#reservations.get(fn);
    if (!res) {
      throw new Error("invalid reservation");
    }
    const { paths, dirs } = res;
    const next = /* @__PURE__ */ new Set();
    for (const path108 of paths) {
      const q = this.#queues.get(path108);
      if (!q || q?.[0] !== fn) {
        continue;
      }
      const q0 = q[1];
      if (!q0) {
        this.#queues.delete(path108);
        continue;
      }
      q.shift();
      if (typeof q0 === "function") {
        next.add(q0);
      } else {
        for (const f of q0) {
          next.add(f);
        }
      }
    }
    for (const dir of dirs) {
      const q = this.#queues.get(dir);
      const q0 = q?.[0];
      if (!q || !(q0 instanceof Set))
        continue;
      if (q0.size === 1 && q.length === 1) {
        this.#queues.delete(dir);
        continue;
      } else if (q0.size === 1) {
        q.shift();
        const n2 = q[0];
        if (typeof n2 === "function") {
          next.add(n2);
        }
      } else {
        q0.delete(fn);
      }
    }
    this.#running.delete(fn);
    next.forEach((fn2) => this.#run(fn2));
    return true;
  }
};

// node_modules/tar/dist/esm/unpack.js
var ONENTRY = Symbol("onEntry");
var CHECKFS = Symbol("checkFs");
var CHECKFS2 = Symbol("checkFs2");
var ISREUSABLE = Symbol("isReusable");
var MAKEFS = Symbol("makeFs");
var FILE2 = Symbol("file");
var DIRECTORY2 = Symbol("directory");
var LINK = Symbol("link");
var SYMLINK2 = Symbol("symlink");
var HARDLINK2 = Symbol("hardlink");
var UNSUPPORTED = Symbol("unsupported");
var CHECKPATH = Symbol("checkPath");
var MKDIR = Symbol("mkdir");
var ONERROR = Symbol("onError");
var PENDING = Symbol("pending");
var PEND = Symbol("pend");
var UNPEND = Symbol("unpend");
var ENDED3 = Symbol("ended");
var MAYBECLOSE = Symbol("maybeClose");
var SKIP = Symbol("skip");
var DOCHOWN = Symbol("doChown");
var UID = Symbol("uid");
var GID = Symbol("gid");
var CHECKED_CWD = Symbol("checkedCwd");
var platform10 = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
var isWindows6 = platform10 === "win32";
var DEFAULT_MAX_DEPTH = 1024;
var unlinkFile = /* @__PURE__ */ __name((path108, cb) => {
  if (!isWindows6) {
    return fs64.unlink(path108, cb);
  }
  const name3 = path108 + ".DELETE." + randomBytes4(16).toString("hex");
  fs64.rename(path108, name3, (er) => {
    if (er) {
      return cb(er);
    }
    fs64.unlink(name3, cb);
  });
}, "unlinkFile");
var unlinkFileSync = /* @__PURE__ */ __name((path108) => {
  if (!isWindows6) {
    return fs64.unlinkSync(path108);
  }
  const name3 = path108 + ".DELETE." + randomBytes4(16).toString("hex");
  fs64.renameSync(path108, name3);
  fs64.unlinkSync(name3);
}, "unlinkFileSync");
var uint32 = /* @__PURE__ */ __name((a, b, c3) => a !== void 0 && a === a >>> 0 ? a : b !== void 0 && b === b >>> 0 ? b : c3, "uint32");
var Unpack = class extends Parser2 {
  static {
    __name(this, "Unpack");
  }
  [ENDED3] = false;
  [CHECKED_CWD] = false;
  [PENDING] = 0;
  reservations = new PathReservations();
  transform;
  writable = true;
  readable = false;
  uid;
  gid;
  setOwner;
  preserveOwner;
  processGid;
  processUid;
  maxDepth;
  forceChown;
  win32;
  newer;
  keep;
  noMtime;
  preservePaths;
  unlink;
  cwd;
  strip;
  processUmask;
  umask;
  dmode;
  fmode;
  chmod;
  constructor(opt = {}) {
    opt.ondone = () => {
      this[ENDED3] = true;
      this[MAYBECLOSE]();
    };
    super(opt);
    this.transform = opt.transform;
    this.chmod = !!opt.chmod;
    if (typeof opt.uid === "number" || typeof opt.gid === "number") {
      if (typeof opt.uid !== "number" || typeof opt.gid !== "number") {
        throw new TypeError("cannot set owner without number uid and gid");
      }
      if (opt.preserveOwner) {
        throw new TypeError("cannot preserve owner in archive and also set owner explicitly");
      }
      this.uid = opt.uid;
      this.gid = opt.gid;
      this.setOwner = true;
    } else {
      this.uid = void 0;
      this.gid = void 0;
      this.setOwner = false;
    }
    if (opt.preserveOwner === void 0 && typeof opt.uid !== "number") {
      this.preserveOwner = !!(process.getuid && process.getuid() === 0);
    } else {
      this.preserveOwner = !!opt.preserveOwner;
    }
    this.processUid = (this.preserveOwner || this.setOwner) && process.getuid ? process.getuid() : void 0;
    this.processGid = (this.preserveOwner || this.setOwner) && process.getgid ? process.getgid() : void 0;
    this.maxDepth = typeof opt.maxDepth === "number" ? opt.maxDepth : DEFAULT_MAX_DEPTH;
    this.forceChown = opt.forceChown === true;
    this.win32 = !!opt.win32 || isWindows6;
    this.newer = !!opt.newer;
    this.keep = !!opt.keep;
    this.noMtime = !!opt.noMtime;
    this.preservePaths = !!opt.preservePaths;
    this.unlink = !!opt.unlink;
    this.cwd = normalizeWindowsPath(path67.resolve(opt.cwd || process.cwd()));
    this.strip = Number(opt.strip) || 0;
    this.processUmask = !this.chmod ? 0 : typeof opt.processUmask === "number" ? opt.processUmask : process.umask();
    this.umask = typeof opt.umask === "number" ? opt.umask : this.processUmask;
    this.dmode = opt.dmode || 511 & ~this.umask;
    this.fmode = opt.fmode || 438 & ~this.umask;
    this.on("entry", (entry) => this[ONENTRY](entry));
  }
  // a bad or damaged archive is a warning for Parser, but an error
  // when extracting.  Mark those errors as unrecoverable, because
  // the Unpack contract cannot be met.
  warn(code2, msg, data = {}) {
    if (code2 === "TAR_BAD_ARCHIVE" || code2 === "TAR_ABORT") {
      data.recoverable = false;
    }
    return super.warn(code2, msg, data);
  }
  [MAYBECLOSE]() {
    if (this[ENDED3] && this[PENDING] === 0) {
      this.emit("prefinish");
      this.emit("finish");
      this.emit("end");
    }
  }
  [CHECKPATH](entry) {
    const p = normalizeWindowsPath(entry.path);
    const parts = p.split("/");
    if (this.strip) {
      if (parts.length < this.strip) {
        return false;
      }
      if (entry.type === "Link") {
        const linkparts = normalizeWindowsPath(String(entry.linkpath)).split("/");
        if (linkparts.length >= this.strip) {
          entry.linkpath = linkparts.slice(this.strip).join("/");
        } else {
          return false;
        }
      }
      parts.splice(0, this.strip);
      entry.path = parts.join("/");
    }
    if (isFinite(this.maxDepth) && parts.length > this.maxDepth) {
      this.warn("TAR_ENTRY_ERROR", "path excessively deep", {
        entry,
        path: p,
        depth: parts.length,
        maxDepth: this.maxDepth
      });
      return false;
    }
    if (!this.preservePaths) {
      if (parts.includes("..") || /* c8 ignore next */
      isWindows6 && /^[a-z]:\.\.$/i.test(parts[0] ?? "")) {
        this.warn("TAR_ENTRY_ERROR", `path contains '..'`, {
          entry,
          path: p
        });
        return false;
      }
      const [root, stripped] = stripAbsolutePath(p);
      if (root) {
        entry.path = String(stripped);
        this.warn("TAR_ENTRY_INFO", `stripping ${root} from absolute path`, {
          entry,
          path: p
        });
      }
    }
    if (path67.isAbsolute(entry.path)) {
      entry.absolute = normalizeWindowsPath(path67.resolve(entry.path));
    } else {
      entry.absolute = normalizeWindowsPath(path67.resolve(this.cwd, entry.path));
    }
    if (!this.preservePaths && typeof entry.absolute === "string" && entry.absolute.indexOf(this.cwd + "/") !== 0 && entry.absolute !== this.cwd) {
      this.warn("TAR_ENTRY_ERROR", "path escaped extraction target", {
        entry,
        path: normalizeWindowsPath(entry.path),
        resolvedPath: entry.absolute,
        cwd: this.cwd
      });
      return false;
    }
    if (entry.absolute === this.cwd && entry.type !== "Directory" && entry.type !== "GNUDumpDir") {
      return false;
    }
    if (this.win32) {
      const { root: aRoot } = path67.win32.parse(String(entry.absolute));
      entry.absolute = aRoot + encode3(String(entry.absolute).slice(aRoot.length));
      const { root: pRoot } = path67.win32.parse(entry.path);
      entry.path = pRoot + encode3(entry.path.slice(pRoot.length));
    }
    return true;
  }
  [ONENTRY](entry) {
    if (!this[CHECKPATH](entry)) {
      return entry.resume();
    }
    assert2.equal(typeof entry.absolute, "string");
    switch (entry.type) {
      case "Directory":
      case "GNUDumpDir":
        if (entry.mode) {
          entry.mode = entry.mode | 448;
        }
      // eslint-disable-next-line no-fallthrough
      case "File":
      case "OldFile":
      case "ContiguousFile":
      case "Link":
      case "SymbolicLink":
        return this[CHECKFS](entry);
      case "CharacterDevice":
      case "BlockDevice":
      case "FIFO":
      default:
        return this[UNSUPPORTED](entry);
    }
  }
  [ONERROR](er, entry) {
    if (er.name === "CwdError") {
      this.emit("error", er);
    } else {
      this.warn("TAR_ENTRY_ERROR", er, { entry });
      this[UNPEND]();
      entry.resume();
    }
  }
  [MKDIR](dir, mode, cb) {
    mkdir5(normalizeWindowsPath(dir), {
      uid: this.uid,
      gid: this.gid,
      processUid: this.processUid,
      processGid: this.processGid,
      umask: this.processUmask,
      preserve: this.preservePaths,
      unlink: this.unlink,
      cwd: this.cwd,
      mode
    }, cb);
  }
  [DOCHOWN](entry) {
    return this.forceChown || this.preserveOwner && (typeof entry.uid === "number" && entry.uid !== this.processUid || typeof entry.gid === "number" && entry.gid !== this.processGid) || typeof this.uid === "number" && this.uid !== this.processUid || typeof this.gid === "number" && this.gid !== this.processGid;
  }
  [UID](entry) {
    return uint32(this.uid, entry.uid, this.processUid);
  }
  [GID](entry) {
    return uint32(this.gid, entry.gid, this.processGid);
  }
  [FILE2](entry, fullyDone) {
    const mode = typeof entry.mode === "number" ? entry.mode & 4095 : this.fmode;
    const stream2 = new WriteStream(String(entry.absolute), {
      // slight lie, but it can be numeric flags
      flags: getWriteFlag(entry.size),
      mode,
      autoClose: false
    });
    stream2.on("error", (er) => {
      if (stream2.fd) {
        fs64.close(stream2.fd, () => {
        });
      }
      stream2.write = () => true;
      this[ONERROR](er, entry);
      fullyDone();
    });
    let actions = 1;
    const done = /* @__PURE__ */ __name((er) => {
      if (er) {
        if (stream2.fd) {
          fs64.close(stream2.fd, () => {
          });
        }
        this[ONERROR](er, entry);
        fullyDone();
        return;
      }
      if (--actions === 0) {
        if (stream2.fd !== void 0) {
          fs64.close(stream2.fd, (er2) => {
            if (er2) {
              this[ONERROR](er2, entry);
            } else {
              this[UNPEND]();
            }
            fullyDone();
          });
        }
      }
    }, "done");
    stream2.on("finish", () => {
      const abs = String(entry.absolute);
      const fd = stream2.fd;
      if (typeof fd === "number" && entry.mtime && !this.noMtime) {
        actions++;
        const atime = entry.atime || /* @__PURE__ */ new Date();
        const mtime = entry.mtime;
        fs64.futimes(fd, atime, mtime, (er) => er ? fs64.utimes(abs, atime, mtime, (er2) => done(er2 && er)) : done());
      }
      if (typeof fd === "number" && this[DOCHOWN](entry)) {
        actions++;
        const uid = this[UID](entry);
        const gid = this[GID](entry);
        if (typeof uid === "number" && typeof gid === "number") {
          fs64.fchown(fd, uid, gid, (er) => er ? fs64.chown(abs, uid, gid, (er2) => done(er2 && er)) : done());
        }
      }
      done();
    });
    const tx = this.transform ? this.transform(entry) || entry : entry;
    if (tx !== entry) {
      tx.on("error", (er) => {
        this[ONERROR](er, entry);
        fullyDone();
      });
      entry.pipe(tx);
    }
    tx.pipe(stream2);
  }
  [DIRECTORY2](entry, fullyDone) {
    const mode = typeof entry.mode === "number" ? entry.mode & 4095 : this.dmode;
    this[MKDIR](String(entry.absolute), mode, (er) => {
      if (er) {
        this[ONERROR](er, entry);
        fullyDone();
        return;
      }
      let actions = 1;
      const done = /* @__PURE__ */ __name(() => {
        if (--actions === 0) {
          fullyDone();
          this[UNPEND]();
          entry.resume();
        }
      }, "done");
      if (entry.mtime && !this.noMtime) {
        actions++;
        fs64.utimes(String(entry.absolute), entry.atime || /* @__PURE__ */ new Date(), entry.mtime, done);
      }
      if (this[DOCHOWN](entry)) {
        actions++;
        fs64.chown(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry)), done);
      }
      done();
    });
  }
  [UNSUPPORTED](entry) {
    entry.unsupported = true;
    this.warn("TAR_ENTRY_UNSUPPORTED", `unsupported entry type: ${entry.type}`, { entry });
    entry.resume();
  }
  [SYMLINK2](entry, done) {
    this[LINK](entry, String(entry.linkpath), "symlink", done);
  }
  [HARDLINK2](entry, done) {
    const linkpath = normalizeWindowsPath(path67.resolve(this.cwd, String(entry.linkpath)));
    this[LINK](entry, linkpath, "link", done);
  }
  [PEND]() {
    this[PENDING]++;
  }
  [UNPEND]() {
    this[PENDING]--;
    this[MAYBECLOSE]();
  }
  [SKIP](entry) {
    this[UNPEND]();
    entry.resume();
  }
  // Check if we can reuse an existing filesystem entry safely and
  // overwrite it, rather than unlinking and recreating
  // Windows doesn't report a useful nlink, so we just never reuse entries
  [ISREUSABLE](entry, st) {
    return entry.type === "File" && !this.unlink && st.isFile() && st.nlink <= 1 && !isWindows6;
  }
  // check if a thing is there, and if so, try to clobber it
  [CHECKFS](entry) {
    this[PEND]();
    const paths = [entry.path];
    if (entry.linkpath) {
      paths.push(entry.linkpath);
    }
    this.reservations.reserve(paths, (done) => this[CHECKFS2](entry, done));
  }
  [CHECKFS2](entry, fullyDone) {
    const done = /* @__PURE__ */ __name((er) => {
      fullyDone(er);
    }, "done");
    const checkCwd2 = /* @__PURE__ */ __name(() => {
      this[MKDIR](this.cwd, this.dmode, (er) => {
        if (er) {
          this[ONERROR](er, entry);
          done();
          return;
        }
        this[CHECKED_CWD] = true;
        start();
      });
    }, "checkCwd");
    const start = /* @__PURE__ */ __name(() => {
      if (entry.absolute !== this.cwd) {
        const parent = normalizeWindowsPath(path67.dirname(String(entry.absolute)));
        if (parent !== this.cwd) {
          return this[MKDIR](parent, this.dmode, (er) => {
            if (er) {
              this[ONERROR](er, entry);
              done();
              return;
            }
            afterMakeParent();
          });
        }
      }
      afterMakeParent();
    }, "start");
    const afterMakeParent = /* @__PURE__ */ __name(() => {
      fs64.lstat(String(entry.absolute), (lstatEr, st) => {
        if (st && (this.keep || /* c8 ignore next */
        this.newer && st.mtime > (entry.mtime ?? st.mtime))) {
          this[SKIP](entry);
          done();
          return;
        }
        if (lstatEr || this[ISREUSABLE](entry, st)) {
          return this[MAKEFS](null, entry, done);
        }
        if (st.isDirectory()) {
          if (entry.type === "Directory") {
            const needChmod = this.chmod && entry.mode && (st.mode & 4095) !== entry.mode;
            const afterChmod = /* @__PURE__ */ __name((er) => this[MAKEFS](er ?? null, entry, done), "afterChmod");
            if (!needChmod) {
              return afterChmod();
            }
            return fs64.chmod(String(entry.absolute), Number(entry.mode), afterChmod);
          }
          if (entry.absolute !== this.cwd) {
            return fs64.rmdir(String(entry.absolute), (er) => this[MAKEFS](er ?? null, entry, done));
          }
        }
        if (entry.absolute === this.cwd) {
          return this[MAKEFS](null, entry, done);
        }
        unlinkFile(String(entry.absolute), (er) => this[MAKEFS](er ?? null, entry, done));
      });
    }, "afterMakeParent");
    if (this[CHECKED_CWD]) {
      start();
    } else {
      checkCwd2();
    }
  }
  [MAKEFS](er, entry, done) {
    if (er) {
      this[ONERROR](er, entry);
      done();
      return;
    }
    switch (entry.type) {
      case "File":
      case "OldFile":
      case "ContiguousFile":
        return this[FILE2](entry, done);
      case "Link":
        return this[HARDLINK2](entry, done);
      case "SymbolicLink":
        return this[SYMLINK2](entry, done);
      case "Directory":
      case "GNUDumpDir":
        return this[DIRECTORY2](entry, done);
    }
  }
  [LINK](entry, linkpath, link3, done) {
    fs64[link3](linkpath, String(entry.absolute), (er) => {
      if (er) {
        this[ONERROR](er, entry);
      } else {
        this[UNPEND]();
        entry.resume();
      }
      done();
    });
  }
};
var callSync = /* @__PURE__ */ __name((fn) => {
  try {
    return [null, fn()];
  } catch (er) {
    return [er, null];
  }
}, "callSync");
var UnpackSync = class extends Unpack {
  static {
    __name(this, "UnpackSync");
  }
  sync = true;
  [MAKEFS](er, entry) {
    return super[MAKEFS](er, entry, () => {
    });
  }
  [CHECKFS](entry) {
    if (!this[CHECKED_CWD]) {
      const er2 = this[MKDIR](this.cwd, this.dmode);
      if (er2) {
        return this[ONERROR](er2, entry);
      }
      this[CHECKED_CWD] = true;
    }
    if (entry.absolute !== this.cwd) {
      const parent = normalizeWindowsPath(path67.dirname(String(entry.absolute)));
      if (parent !== this.cwd) {
        const mkParent = this[MKDIR](parent, this.dmode);
        if (mkParent) {
          return this[ONERROR](mkParent, entry);
        }
      }
    }
    const [lstatEr, st] = callSync(() => fs64.lstatSync(String(entry.absolute)));
    if (st && (this.keep || /* c8 ignore next */
    this.newer && st.mtime > (entry.mtime ?? st.mtime))) {
      return this[SKIP](entry);
    }
    if (lstatEr || this[ISREUSABLE](entry, st)) {
      return this[MAKEFS](null, entry);
    }
    if (st.isDirectory()) {
      if (entry.type === "Directory") {
        const needChmod = this.chmod && entry.mode && (st.mode & 4095) !== entry.mode;
        const [er3] = needChmod ? callSync(() => {
          fs64.chmodSync(String(entry.absolute), Number(entry.mode));
        }) : [];
        return this[MAKEFS](er3, entry);
      }
      const [er2] = callSync(() => fs64.rmdirSync(String(entry.absolute)));
      this[MAKEFS](er2, entry);
    }
    const [er] = entry.absolute === this.cwd ? [] : callSync(() => unlinkFileSync(String(entry.absolute)));
    this[MAKEFS](er, entry);
  }
  [FILE2](entry, done) {
    const mode = typeof entry.mode === "number" ? entry.mode & 4095 : this.fmode;
    const oner = /* @__PURE__ */ __name((er) => {
      let closeError;
      try {
        fs64.closeSync(fd);
      } catch (e2) {
        closeError = e2;
      }
      if (er || closeError) {
        this[ONERROR](er || closeError, entry);
      }
      done();
    }, "oner");
    let fd;
    try {
      fd = fs64.openSync(String(entry.absolute), getWriteFlag(entry.size), mode);
    } catch (er) {
      return oner(er);
    }
    const tx = this.transform ? this.transform(entry) || entry : entry;
    if (tx !== entry) {
      tx.on("error", (er) => this[ONERROR](er, entry));
      entry.pipe(tx);
    }
    tx.on("data", (chunk) => {
      try {
        fs64.writeSync(fd, chunk, 0, chunk.length);
      } catch (er) {
        oner(er);
      }
    });
    tx.on("end", () => {
      let er = null;
      if (entry.mtime && !this.noMtime) {
        const atime = entry.atime || /* @__PURE__ */ new Date();
        const mtime = entry.mtime;
        try {
          fs64.futimesSync(fd, atime, mtime);
        } catch (futimeser) {
          try {
            fs64.utimesSync(String(entry.absolute), atime, mtime);
          } catch (utimeser) {
            er = futimeser;
          }
        }
      }
      if (this[DOCHOWN](entry)) {
        const uid = this[UID](entry);
        const gid = this[GID](entry);
        try {
          fs64.fchownSync(fd, Number(uid), Number(gid));
        } catch (fchowner) {
          try {
            fs64.chownSync(String(entry.absolute), Number(uid), Number(gid));
          } catch (chowner) {
            er = er || fchowner;
          }
        }
      }
      oner(er);
    });
  }
  [DIRECTORY2](entry, done) {
    const mode = typeof entry.mode === "number" ? entry.mode & 4095 : this.dmode;
    const er = this[MKDIR](String(entry.absolute), mode);
    if (er) {
      this[ONERROR](er, entry);
      done();
      return;
    }
    if (entry.mtime && !this.noMtime) {
      try {
        fs64.utimesSync(String(entry.absolute), entry.atime || /* @__PURE__ */ new Date(), entry.mtime);
      } catch (er2) {
      }
    }
    if (this[DOCHOWN](entry)) {
      try {
        fs64.chownSync(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry)));
      } catch (er2) {
      }
    }
    done();
    entry.resume();
  }
  [MKDIR](dir, mode) {
    try {
      return mkdirSync6(normalizeWindowsPath(dir), {
        uid: this.uid,
        gid: this.gid,
        processUid: this.processUid,
        processGid: this.processGid,
        umask: this.processUmask,
        preserve: this.preservePaths,
        unlink: this.unlink,
        cwd: this.cwd,
        mode
      });
    } catch (er) {
      return er;
    }
  }
  [LINK](entry, linkpath, link3, done) {
    const ls = `${link3}Sync`;
    try {
      fs64[ls](linkpath, String(entry.absolute));
      done();
      entry.resume();
    } catch (er) {
      return this[ONERROR](er, entry);
    }
  }
};

// node_modules/tar/dist/esm/extract.js
var extractFileSync = /* @__PURE__ */ __name((opt) => {
  const u = new UnpackSync(opt);
  const file = opt.file;
  const stat7 = fs65.statSync(file);
  const readSize = opt.maxReadSize || 16 * 1024 * 1024;
  const stream2 = new ReadStreamSync(file, {
    readSize,
    size: stat7.size
  });
  stream2.pipe(u);
}, "extractFileSync");
var extractFile = /* @__PURE__ */ __name((opt, _) => {
  const u = new Unpack(opt);
  const readSize = opt.maxReadSize || 16 * 1024 * 1024;
  const file = opt.file;
  const p = new Promise((resolve24, reject) => {
    u.on("error", reject);
    u.on("close", resolve24);
    fs65.stat(file, (er, stat7) => {
      if (er) {
        reject(er);
      } else {
        const stream2 = new ReadStream(file, {
          readSize,
          size: stat7.size
        });
        stream2.on("error", reject);
        stream2.pipe(u);
      }
    });
  });
  return p;
}, "extractFile");
var extract = makeCommand(extractFileSync, extractFile, (opt) => new UnpackSync(opt), (opt) => new Unpack(opt), (opt, files) => {
  if (files?.length)
    filesFilter(opt, files);
});

// node_modules/tar/dist/esm/replace.js
init_esbuild_shims();
import fs66 from "node:fs";
import path68 from "node:path";
var replaceSync = /* @__PURE__ */ __name((opt, files) => {
  const p = new PackSync(opt);
  let threw = true;
  let fd;
  let position;
  try {
    try {
      fd = fs66.openSync(opt.file, "r+");
    } catch (er) {
      if (er?.code === "ENOENT") {
        fd = fs66.openSync(opt.file, "w+");
      } else {
        throw er;
      }
    }
    const st = fs66.fstatSync(fd);
    const headBuf = Buffer.alloc(512);
    POSITION: for (position = 0; position < st.size; position += 512) {
      for (let bufPos = 0, bytes = 0; bufPos < 512; bufPos += bytes) {
        bytes = fs66.readSync(fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos);
        if (position === 0 && headBuf[0] === 31 && headBuf[1] === 139) {
          throw new Error("cannot append to compressed archives");
        }
        if (!bytes) {
          break POSITION;
        }
      }
      const h = new Header2(headBuf);
      if (!h.cksumValid) {
        break;
      }
      const entryBlockSize = 512 * Math.ceil((h.size || 0) / 512);
      if (position + entryBlockSize + 512 > st.size) {
        break;
      }
      position += entryBlockSize;
      if (opt.mtimeCache && h.mtime) {
        opt.mtimeCache.set(String(h.path), h.mtime);
      }
    }
    threw = false;
    streamSync2(opt, p, position, fd, files);
  } finally {
    if (threw) {
      try {
        fs66.closeSync(fd);
      } catch (er) {
      }
    }
  }
}, "replaceSync");
var streamSync2 = /* @__PURE__ */ __name((opt, p, position, fd, files) => {
  const stream2 = new WriteStreamSync(opt.file, {
    fd,
    start: position
  });
  p.pipe(stream2);
  addFilesSync2(p, files);
}, "streamSync");
var replaceAsync = /* @__PURE__ */ __name((opt, files) => {
  files = Array.from(files);
  const p = new Pack(opt);
  const getPos = /* @__PURE__ */ __name((fd, size, cb_) => {
    const cb = /* @__PURE__ */ __name((er, pos2) => {
      if (er) {
        fs66.close(fd, (_) => cb_(er));
      } else {
        cb_(null, pos2);
      }
    }, "cb");
    let position = 0;
    if (size === 0) {
      return cb(null, 0);
    }
    let bufPos = 0;
    const headBuf = Buffer.alloc(512);
    const onread = /* @__PURE__ */ __name((er, bytes) => {
      if (er || typeof bytes === "undefined") {
        return cb(er);
      }
      bufPos += bytes;
      if (bufPos < 512 && bytes) {
        return fs66.read(fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos, onread);
      }
      if (position === 0 && headBuf[0] === 31 && headBuf[1] === 139) {
        return cb(new Error("cannot append to compressed archives"));
      }
      if (bufPos < 512) {
        return cb(null, position);
      }
      const h = new Header2(headBuf);
      if (!h.cksumValid) {
        return cb(null, position);
      }
      const entryBlockSize = 512 * Math.ceil((h.size ?? 0) / 512);
      if (position + entryBlockSize + 512 > size) {
        return cb(null, position);
      }
      position += entryBlockSize + 512;
      if (position >= size) {
        return cb(null, position);
      }
      if (opt.mtimeCache && h.mtime) {
        opt.mtimeCache.set(String(h.path), h.mtime);
      }
      bufPos = 0;
      fs66.read(fd, headBuf, 0, 512, position, onread);
    }, "onread");
    fs66.read(fd, headBuf, 0, 512, position, onread);
  }, "getPos");
  const promise = new Promise((resolve24, reject) => {
    p.on("error", reject);
    let flag = "r+";
    const onopen = /* @__PURE__ */ __name((er, fd) => {
      if (er && er.code === "ENOENT" && flag === "r+") {
        flag = "w+";
        return fs66.open(opt.file, flag, onopen);
      }
      if (er || !fd) {
        return reject(er);
      }
      fs66.fstat(fd, (er2, st) => {
        if (er2) {
          return fs66.close(fd, () => reject(er2));
        }
        getPos(fd, st.size, (er3, position) => {
          if (er3) {
            return reject(er3);
          }
          const stream2 = new WriteStream(opt.file, {
            fd,
            start: position
          });
          p.pipe(stream2);
          stream2.on("error", reject);
          stream2.on("close", resolve24);
          addFilesAsync2(p, files);
        });
      });
    }, "onopen");
    fs66.open(opt.file, flag, onopen);
  });
  return promise;
}, "replaceAsync");
var addFilesSync2 = /* @__PURE__ */ __name((p, files) => {
  files.forEach((file) => {
    if (file.charAt(0) === "@") {
      list2({
        file: path68.resolve(p.cwd, file.slice(1)),
        sync: true,
        noResume: true,
        onReadEntry: /* @__PURE__ */ __name((entry) => p.add(entry), "onReadEntry")
      });
    } else {
      p.add(file);
    }
  });
  p.end();
}, "addFilesSync");
var addFilesAsync2 = /* @__PURE__ */ __name(async (p, files) => {
  for (let i = 0; i < files.length; i++) {
    const file = String(files[i]);
    if (file.charAt(0) === "@") {
      await list2({
        file: path68.resolve(String(p.cwd), file.slice(1)),
        noResume: true,
        onReadEntry: /* @__PURE__ */ __name((entry) => p.add(entry), "onReadEntry")
      });
    } else {
      p.add(file);
    }
  }
  p.end();
}, "addFilesAsync");
var replace = makeCommand(
  replaceSync,
  replaceAsync,
  /* c8 ignore start */
  () => {
    throw new TypeError("file is required");
  },
  () => {
    throw new TypeError("file is required");
  },
  /* c8 ignore stop */
  (opt, entries) => {
    if (!isFile(opt)) {
      throw new TypeError("file is required");
    }
    if (opt.gzip || opt.brotli || opt.zstd || opt.file.endsWith(".br") || opt.file.endsWith(".tbr")) {
      throw new TypeError("cannot append to compressed archives");
    }
    if (!entries?.length) {
      throw new TypeError("no paths specified to add/replace");
    }
  }
);

// node_modules/tar/dist/esm/update.js
init_esbuild_shims();
var update = makeCommand(replace.syncFile, replace.asyncFile, replace.syncNoFile, replace.asyncNoFile, (opt, entries = []) => {
  replace.validate?.(opt, entries);
  mtimeFilter(opt);
});
var mtimeFilter = /* @__PURE__ */ __name((opt) => {
  const filter4 = opt.filter;
  if (!opt.mtimeCache) {
    opt.mtimeCache = /* @__PURE__ */ new Map();
  }
  opt.filter = filter4 ? (path108, stat7) => filter4(path108, stat7) && !/* c8 ignore start */
  ((opt.mtimeCache?.get(path108) ?? stat7.mtime ?? 0) > (stat7.mtime ?? 0)) : (path108, stat7) => !/* c8 ignore start */
  ((opt.mtimeCache?.get(path108) ?? stat7.mtime ?? 0) > (stat7.mtime ?? 0));
}, "mtimeFilter");

// packages/cli/src/config/extensions/github.ts
var import_extract_zip = __toESM(require_extract_zip(), 1);
function getGitHubToken() {
  return process.env["GITHUB_TOKEN"];
}
__name(getGitHubToken, "getGitHubToken");
async function cloneFromGit(installMetadata, destination) {
  try {
    const git = simpleGit(destination);
    let sourceUrl = installMetadata.source;
    const token2 = getGitHubToken();
    if (token2) {
      try {
        const parsedUrl = new URL(sourceUrl);
        if (parsedUrl.protocol === "https:" && parsedUrl.hostname === "github.com") {
          if (!parsedUrl.username) {
            parsedUrl.username = token2;
          }
          sourceUrl = parsedUrl.toString();
        }
      } catch {
      }
    }
    await git.clone(sourceUrl, "./", ["--depth", "1"]);
    const remotes = await git.getRemotes(true);
    if (remotes.length === 0) {
      throw new Error(
        `Unable to find any remotes for repo ${installMetadata.source}`
      );
    }
    const refToFetch = installMetadata.ref || "HEAD";
    await git.fetch(remotes[0].name, refToFetch);
    await git.checkout("FETCH_HEAD");
  } catch (error) {
    throw new Error(
      `Failed to clone Git repository from ${installMetadata.source} ${getErrorMessage3(error)}`,
      {
        cause: error
      }
    );
  }
}
__name(cloneFromGit, "cloneFromGit");
function parseGitHubRepoForReleases(source2) {
  const parsedUrl = URL.parse(source2, "https://github.com");
  const parts = parsedUrl?.pathname.substring(1).split("/");
  if (parts?.length !== 2 || parsedUrl?.host !== "github.com") {
    throw new Error(
      `Invalid GitHub repository source: ${source2}. Expected "owner/repo" or a github repo uri.`
    );
  }
  const owner = parts[0];
  const repo = parts[1].replace(".git", "");
  if (owner.startsWith("git@github.com")) {
    throw new Error(
      `GitHub release-based extensions are not supported for SSH. You must use an HTTPS URI with a personal access token to download releases from private repositories. You can set your personal access token in the GITHUB_TOKEN environment variable and install the extension via SSH.`
    );
  }
  return { owner, repo };
}
__name(parseGitHubRepoForReleases, "parseGitHubRepoForReleases");
async function fetchReleaseFromGithub(owner, repo, ref) {
  const endpoint = ref ? `releases/tags/${ref}` : "releases/latest";
  const url2 = `https://api.github.com/repos/${owner}/${repo}/${endpoint}`;
  return await fetchJson(url2);
}
__name(fetchReleaseFromGithub, "fetchReleaseFromGithub");
async function checkForExtensionUpdate(extension, setExtensionUpdateState, cwd7 = process.cwd()) {
  setExtensionUpdateState("checking for updates" /* CHECKING_FOR_UPDATES */);
  const installMetadata = extension.installMetadata;
  if (installMetadata?.type === "local") {
    const newExtension = loadExtension({
      extensionDir: installMetadata.source,
      workspaceDir: cwd7
    });
    if (!newExtension) {
      console.error(
        `Failed to check for update for local extension "${extension.name}". Could not load extension from source path: ${installMetadata.source}`
      );
      setExtensionUpdateState("error" /* ERROR */);
      return;
    }
    if (newExtension.config.version !== extension.version) {
      setExtensionUpdateState("update available" /* UPDATE_AVAILABLE */);
      return;
    }
    setExtensionUpdateState("up to date" /* UP_TO_DATE */);
    return;
  }
  if (!installMetadata || installMetadata.type !== "git" && installMetadata.type !== "github-release") {
    setExtensionUpdateState("not updatable" /* NOT_UPDATABLE */);
    return;
  }
  try {
    if (installMetadata.type === "git") {
      const git = simpleGit(extension.path);
      const remotes = await git.getRemotes(true);
      if (remotes.length === 0) {
        console.error("No git remotes found.");
        setExtensionUpdateState("error" /* ERROR */);
        return;
      }
      const remoteUrl = remotes[0].refs.fetch;
      if (!remoteUrl) {
        console.error(`No fetch URL found for git remote ${remotes[0].name}.`);
        setExtensionUpdateState("error" /* ERROR */);
        return;
      }
      const refToCheck = installMetadata.ref || "HEAD";
      const lsRemoteOutput = await git.listRemote([remoteUrl, refToCheck]);
      if (typeof lsRemoteOutput !== "string" || lsRemoteOutput.trim() === "") {
        console.error(`Git ref ${refToCheck} not found.`);
        setExtensionUpdateState("error" /* ERROR */);
        return;
      }
      const remoteHash = lsRemoteOutput.split("	")[0];
      const localHash = await git.revparse(["HEAD"]);
      if (!remoteHash) {
        console.error(
          `Unable to parse hash from git ls-remote output "${lsRemoteOutput}"`
        );
        setExtensionUpdateState("error" /* ERROR */);
        return;
      }
      if (remoteHash === localHash) {
        setExtensionUpdateState("up to date" /* UP_TO_DATE */);
        return;
      }
      setExtensionUpdateState("update available" /* UPDATE_AVAILABLE */);
      return;
    } else {
      const { source: source2, releaseTag } = installMetadata;
      if (!source2) {
        console.error(`No "source" provided for extension.`);
        setExtensionUpdateState("error" /* ERROR */);
        return;
      }
      const { owner, repo } = parseGitHubRepoForReleases(source2);
      const releaseData = await fetchReleaseFromGithub(
        owner,
        repo,
        installMetadata.ref
      );
      if (releaseData.tag_name !== releaseTag) {
        setExtensionUpdateState("update available" /* UPDATE_AVAILABLE */);
        return;
      }
      setExtensionUpdateState("up to date" /* UP_TO_DATE */);
      return;
    }
  } catch (error) {
    console.error(
      `Failed to check for updates for extension "${installMetadata.source}": ${getErrorMessage3(error)}`
    );
    setExtensionUpdateState("error" /* ERROR */);
    return;
  }
}
__name(checkForExtensionUpdate, "checkForExtensionUpdate");
async function downloadFromGitHubRelease(installMetadata, destination) {
  const { source: source2, ref } = installMetadata;
  const { owner, repo } = parseGitHubRepoForReleases(source2);
  try {
    const releaseData = await fetchReleaseFromGithub(owner, repo, ref);
    if (!releaseData) {
      throw new Error(
        `No release data found for ${owner}/${repo} at tag ${ref}`
      );
    }
    const asset = findReleaseAsset(releaseData.assets);
    let archiveUrl;
    let isTar = false;
    let isZip = false;
    if (asset) {
      archiveUrl = asset.browser_download_url;
    } else {
      if (releaseData.tarball_url) {
        archiveUrl = releaseData.tarball_url;
        isTar = true;
      } else if (releaseData.zipball_url) {
        archiveUrl = releaseData.zipball_url;
        isZip = true;
      }
    }
    if (!archiveUrl) {
      throw new Error(
        `No assets found for release with tag ${releaseData.tag_name}`
      );
    }
    let downloadedAssetPath = path69.join(
      destination,
      path69.basename(new URL(archiveUrl).pathname)
    );
    if (isTar && !downloadedAssetPath.endsWith(".tar.gz")) {
      downloadedAssetPath += ".tar.gz";
    } else if (isZip && !downloadedAssetPath.endsWith(".zip")) {
      downloadedAssetPath += ".zip";
    }
    await downloadFile2(archiveUrl, downloadedAssetPath);
    await extractFile2(downloadedAssetPath, destination);
    const entries = await fs67.promises.readdir(destination, {
      withFileTypes: true
    });
    if (entries.length === 2) {
      const lonelyDir = entries.find((entry) => entry.isDirectory());
      if (lonelyDir && fs67.existsSync(
        path69.join(destination, lonelyDir.name, EXTENSIONS_CONFIG_FILENAME)
      )) {
        const dirPathToExtract = path69.join(destination, lonelyDir.name);
        const extractedDirFiles = await fs67.promises.readdir(dirPathToExtract);
        for (const file of extractedDirFiles) {
          await fs67.promises.rename(
            path69.join(dirPathToExtract, file),
            path69.join(destination, file)
          );
        }
        await fs67.promises.rmdir(dirPathToExtract);
      }
    }
    await fs67.promises.unlink(downloadedAssetPath);
    return {
      tagName: releaseData.tag_name,
      type: "github-release"
    };
  } catch (error) {
    throw new Error(
      `Failed to download release from ${installMetadata.source}: ${getErrorMessage3(error)}`
    );
  }
}
__name(downloadFromGitHubRelease, "downloadFromGitHubRelease");
function findReleaseAsset(assets) {
  const platform15 = os25.platform();
  const arch3 = os25.arch();
  const platformArchPrefix = `${platform15}.${arch3}.`;
  const platformPrefix = `${platform15}.`;
  const platformArchAsset = assets.find(
    (asset) => asset.name.toLowerCase().startsWith(platformArchPrefix)
  );
  if (platformArchAsset) {
    return platformArchAsset;
  }
  const platformAsset = assets.find(
    (asset) => asset.name.toLowerCase().startsWith(platformPrefix)
  );
  if (platformAsset) {
    return platformAsset;
  }
  const genericAsset = assets.find(
    (asset) => !asset.name.toLowerCase().includes("darwin") && !asset.name.toLowerCase().includes("linux") && !asset.name.toLowerCase().includes("win32")
  );
  if (assets.length === 1) {
    return genericAsset;
  }
  return void 0;
}
__name(findReleaseAsset, "findReleaseAsset");
async function fetchJson(url2) {
  const headers = {
    "User-Agent": "gemini-cli"
  };
  const token2 = getGitHubToken();
  if (token2) {
    headers.Authorization = `token ${token2}`;
  }
  return new Promise((resolve24, reject) => {
    https3.get(url2, { headers }, (res) => {
      if (res.statusCode !== 200) {
        return reject(
          new Error(`Request failed with status code ${res.statusCode}`)
        );
      }
      const chunks = [];
      res.on("data", (chunk) => chunks.push(chunk));
      res.on("end", () => {
        const data = Buffer.concat(chunks).toString();
        resolve24(JSON.parse(data));
      });
    }).on("error", reject);
  });
}
__name(fetchJson, "fetchJson");
async function downloadFile2(url2, dest) {
  const headers = {
    "User-agent": "gemini-cli"
  };
  const token2 = getGitHubToken();
  if (token2) {
    headers.Authorization = `token ${token2}`;
  }
  return new Promise((resolve24, reject) => {
    https3.get(url2, { headers }, (res) => {
      if (res.statusCode === 302 || res.statusCode === 301) {
        downloadFile2(res.headers.location, dest).then(resolve24).catch(reject);
        return;
      }
      if (res.statusCode !== 200) {
        return reject(
          new Error(`Request failed with status code ${res.statusCode}`)
        );
      }
      const file = fs67.createWriteStream(dest);
      res.pipe(file);
      file.on("finish", () => file.close(resolve24));
    }).on("error", reject);
  });
}
__name(downloadFile2, "downloadFile");
async function extractFile2(file, dest) {
  if (file.endsWith(".tar.gz")) {
    await extract({
      file,
      cwd: dest
    });
  } else if (file.endsWith(".zip")) {
    await (0, import_extract_zip.default)(file, { dir: dest });
  } else {
    throw new Error(`Unsupported file extension for extraction: ${file}`);
  }
}
__name(extractFile2, "extractFile");

// packages/cli/src/config/extensions/extensionEnablement.ts
init_esbuild_shims();
import fs68 from "node:fs";
import path70 from "node:path";
var Override = class _Override {
  constructor(baseRule, isDisable, includeSubdirs) {
    this.baseRule = baseRule;
    this.isDisable = isDisable;
    this.includeSubdirs = includeSubdirs;
  }
  static {
    __name(this, "Override");
  }
  static fromInput(inputRule, includeSubdirs) {
    const isDisable = inputRule.startsWith("!");
    let baseRule = isDisable ? inputRule.substring(1) : inputRule;
    baseRule = ensureLeadingAndTrailingSlash(baseRule);
    return new _Override(baseRule, isDisable, includeSubdirs);
  }
  static fromFileRule(fileRule) {
    const isDisable = fileRule.startsWith("!");
    let baseRule = isDisable ? fileRule.substring(1) : fileRule;
    const includeSubdirs = baseRule.endsWith("*");
    baseRule = includeSubdirs ? baseRule.substring(0, baseRule.length - 1) : baseRule;
    return new _Override(baseRule, isDisable, includeSubdirs);
  }
  conflictsWith(other2) {
    if (this.baseRule === other2.baseRule) {
      return this.includeSubdirs !== other2.includeSubdirs || this.isDisable !== other2.isDisable;
    }
    return false;
  }
  isEqualTo(other2) {
    return this.baseRule === other2.baseRule && this.includeSubdirs === other2.includeSubdirs && this.isDisable === other2.isDisable;
  }
  asRegex() {
    return globToRegex(`${this.baseRule}${this.includeSubdirs ? "*" : ""}`);
  }
  isChildOf(parent) {
    if (!parent.includeSubdirs) {
      return false;
    }
    return parent.asRegex().test(this.baseRule);
  }
  output() {
    return `${this.isDisable ? "!" : ""}${this.baseRule}${this.includeSubdirs ? "*" : ""}`;
  }
  matchesPath(path108) {
    return this.asRegex().test(path108);
  }
};
var ensureLeadingAndTrailingSlash = /* @__PURE__ */ __name(function(dirPath) {
  let result = dirPath.replace(/\\/g, "/");
  if (result.charAt(0) !== "/") {
    result = "/" + result;
  }
  if (result.charAt(result.length - 1) !== "/") {
    result = result + "/";
  }
  return result;
}, "ensureLeadingAndTrailingSlash");
function globToRegex(glob2) {
  const regexString = glob2.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/(\/?)\*/g, "($1.*)?");
  return new RegExp(`^${regexString}$`);
}
__name(globToRegex, "globToRegex");
var ExtensionEnablementManager = class {
  static {
    __name(this, "ExtensionEnablementManager");
  }
  configFilePath;
  configDir;
  // If non-empty, this overrides all other extension configuration and enables
  // only the ones in this list.
  enabledExtensionNamesOverride;
  constructor(configDir, enabledExtensionNames) {
    this.configDir = configDir;
    this.configFilePath = path70.join(configDir, "extension-enablement.json");
    this.enabledExtensionNamesOverride = enabledExtensionNames?.map((name3) => name3.toLowerCase()) ?? [];
  }
  validateExtensionOverrides(extensions) {
    for (const name3 of this.enabledExtensionNamesOverride) {
      if (name3 === "none") continue;
      if (!extensions.some(
        (ext2) => ext2.config.name.toLowerCase() === name3.toLowerCase()
      )) {
        console.error(`Extension not found: ${name3}`);
      }
    }
  }
  /**
   * Determines if an extension is enabled based on its name and the current
   * path. The last matching rule in the overrides list wins.
   *
   * @param extensionName The name of the extension.
   * @param currentPath The absolute path of the current working directory.
   * @returns True if the extension is enabled, false otherwise.
   */
  isEnabled(extensionName, currentPath) {
    if (this.enabledExtensionNamesOverride.length === 1 && this.enabledExtensionNamesOverride[0] === "none") {
      return false;
    }
    if (this.enabledExtensionNamesOverride.length > 0) {
      return this.enabledExtensionNamesOverride.includes(
        extensionName.toLocaleLowerCase()
      );
    }
    const config = this.readConfig();
    const extensionConfig = config[extensionName];
    let enabled = true;
    const allOverrides = extensionConfig?.overrides ?? [];
    for (const rule of allOverrides) {
      const override = Override.fromFileRule(rule);
      if (override.matchesPath(ensureLeadingAndTrailingSlash(currentPath))) {
        enabled = !override.isDisable;
      }
    }
    return enabled;
  }
  readConfig() {
    try {
      const content = fs68.readFileSync(this.configFilePath, "utf-8");
      return JSON.parse(content);
    } catch (error) {
      if (error instanceof Error && "code" in error && error.code === "ENOENT") {
        return {};
      }
      console.error("Error reading extension enablement config:", error);
      return {};
    }
  }
  writeConfig(config) {
    fs68.mkdirSync(this.configDir, { recursive: true });
    fs68.writeFileSync(this.configFilePath, JSON.stringify(config, null, 2));
  }
  enable(extensionName, includeSubdirs, scopePath) {
    const config = this.readConfig();
    if (!config[extensionName]) {
      config[extensionName] = { overrides: [] };
    }
    const override = Override.fromInput(scopePath, includeSubdirs);
    const overrides = config[extensionName].overrides.filter((rule) => {
      const fileOverride = Override.fromFileRule(rule);
      if (fileOverride.conflictsWith(override) || fileOverride.isEqualTo(override)) {
        return false;
      }
      return !fileOverride.isChildOf(override);
    });
    overrides.push(override.output());
    config[extensionName].overrides = overrides;
    this.writeConfig(config);
  }
  disable(extensionName, includeSubdirs, scopePath) {
    this.enable(extensionName, includeSubdirs, `!${scopePath}`);
  }
  remove(extensionName) {
    const config = this.readConfig();
    if (config[extensionName]) {
      delete config[extensionName];
      this.writeConfig(config);
    }
  }
};

// packages/cli/src/config/extension.ts
var import_chalk5 = __toESM(require_source(), 1);
var EXTENSIONS_DIRECTORY_NAME = path71.join(QWEN_DIR5, "extensions");
var EXTENSIONS_CONFIG_FILENAME = "qwen-extension.json";
var INSTALL_METADATA_FILENAME = ".qwen-extension-install.json";
var ExtensionStorage = class _ExtensionStorage {
  static {
    __name(this, "ExtensionStorage");
  }
  extensionName;
  constructor(extensionName) {
    this.extensionName = extensionName;
  }
  getExtensionDir() {
    return path71.join(
      _ExtensionStorage.getUserExtensionsDir(),
      this.extensionName
    );
  }
  getConfigPath() {
    return path71.join(this.getExtensionDir(), EXTENSIONS_CONFIG_FILENAME);
  }
  static getUserExtensionsDir() {
    const storage = new Storage(os26.homedir());
    return storage.getExtensionsDir();
  }
  static async createTmpDir() {
    return await fs69.promises.mkdtemp(path71.join(os26.tmpdir(), "qwen-extension"));
  }
};
function getWorkspaceExtensions(workspaceDir) {
  if (path71.resolve(workspaceDir) === path71.resolve(os26.homedir())) {
    return [];
  }
  return loadExtensionsFromDir(workspaceDir);
}
__name(getWorkspaceExtensions, "getWorkspaceExtensions");
async function copyExtension(source2, destination) {
  await fs69.promises.cp(source2, destination, { recursive: true });
}
__name(copyExtension, "copyExtension");
async function performWorkspaceExtensionMigration(extensions, requestConsent) {
  const failedInstallNames = [];
  for (const extension of extensions) {
    try {
      const installMetadata = {
        source: extension.path,
        type: "local"
      };
      await installExtension(installMetadata, requestConsent);
    } catch (_) {
      failedInstallNames.push(extension.config.name);
    }
  }
  return failedInstallNames;
}
__name(performWorkspaceExtensionMigration, "performWorkspaceExtensionMigration");
function getTelemetryConfig(cwd7) {
  const settings = loadSettings(cwd7);
  const config = new Config({
    telemetry: settings.merged.telemetry,
    interactive: false,
    sessionId: randomUUID6(),
    targetDir: cwd7,
    cwd: cwd7,
    model: "",
    debugMode: false
  });
  return config;
}
__name(getTelemetryConfig, "getTelemetryConfig");
function loadExtensions(extensionEnablementManager, workspaceDir = process.cwd()) {
  const settings = loadSettings(workspaceDir).merged;
  const allExtensions = [...loadUserExtensions()];
  if ((isWorkspaceTrusted(settings) ?? true) && // Default management setting to true
  !(settings.experimental?.extensionManagement ?? true)) {
    allExtensions.push(...getWorkspaceExtensions(workspaceDir));
  }
  const uniqueExtensions = /* @__PURE__ */ new Map();
  for (const extension of allExtensions) {
    if (!uniqueExtensions.has(extension.config.name) && extensionEnablementManager.isEnabled(extension.config.name, workspaceDir)) {
      uniqueExtensions.set(extension.config.name, extension);
    }
  }
  return Array.from(uniqueExtensions.values());
}
__name(loadExtensions, "loadExtensions");
function loadUserExtensions() {
  const userExtensions = loadExtensionsFromDir(os26.homedir());
  const uniqueExtensions = /* @__PURE__ */ new Map();
  for (const extension of userExtensions) {
    if (!uniqueExtensions.has(extension.config.name)) {
      uniqueExtensions.set(extension.config.name, extension);
    }
  }
  return Array.from(uniqueExtensions.values());
}
__name(loadUserExtensions, "loadUserExtensions");
function loadExtensionsFromDir(dir) {
  const storage = new Storage(dir);
  const extensionsDir = storage.getExtensionsDir();
  if (!fs69.existsSync(extensionsDir)) {
    return [];
  }
  const extensions = [];
  for (const subdir of fs69.readdirSync(extensionsDir)) {
    const extensionDir = path71.join(extensionsDir, subdir);
    const extension = loadExtension({ extensionDir, workspaceDir: dir });
    if (extension != null) {
      extensions.push(extension);
    }
  }
  return extensions;
}
__name(loadExtensionsFromDir, "loadExtensionsFromDir");
function loadExtension(context2) {
  const { extensionDir, workspaceDir } = context2;
  if (!fs69.statSync(extensionDir).isDirectory()) {
    return null;
  }
  const installMetadata = loadInstallMetadata(extensionDir);
  let effectiveExtensionPath = extensionDir;
  if (installMetadata?.type === "link") {
    effectiveExtensionPath = installMetadata.source;
  }
  try {
    let config = loadExtensionConfig({
      extensionDir: effectiveExtensionPath,
      workspaceDir
    });
    config = resolveEnvVarsInObject(config);
    if (config.mcpServers) {
      config.mcpServers = Object.fromEntries(
        Object.entries(config.mcpServers).map(([key, value]) => [
          key,
          filterMcpConfig(value)
        ])
      );
    }
    const contextFiles = getContextFileNames(config).map(
      (contextFileName) => path71.join(effectiveExtensionPath, contextFileName)
    ).filter((contextFilePath) => fs69.existsSync(contextFilePath));
    return {
      path: effectiveExtensionPath,
      config,
      contextFiles,
      installMetadata
    };
  } catch (e2) {
    console.error(
      `Warning: Skipping extension in ${effectiveExtensionPath}: ${getErrorMessage3(
        e2
      )}`
    );
    return null;
  }
}
__name(loadExtension, "loadExtension");
function loadExtensionByName(name3, workspaceDir = process.cwd()) {
  const userExtensionsDir = ExtensionStorage.getUserExtensionsDir();
  if (!fs69.existsSync(userExtensionsDir)) {
    return null;
  }
  for (const subdir of fs69.readdirSync(userExtensionsDir)) {
    const extensionDir = path71.join(userExtensionsDir, subdir);
    if (!fs69.statSync(extensionDir).isDirectory()) {
      continue;
    }
    const extension = loadExtension({ extensionDir, workspaceDir });
    if (extension && extension.config.name.toLowerCase() === name3.toLowerCase()) {
      return extension;
    }
  }
  return null;
}
__name(loadExtensionByName, "loadExtensionByName");
function filterMcpConfig(original) {
  const { trust, ...rest } = original;
  return Object.freeze(rest);
}
__name(filterMcpConfig, "filterMcpConfig");
function loadInstallMetadata(extensionDir) {
  const metadataFilePath = path71.join(extensionDir, INSTALL_METADATA_FILENAME);
  try {
    const configContent = fs69.readFileSync(metadataFilePath, "utf-8");
    const metadata = JSON.parse(configContent);
    return metadata;
  } catch (_e) {
    return void 0;
  }
}
__name(loadInstallMetadata, "loadInstallMetadata");
function getContextFileNames(config) {
  if (!config.contextFileName) {
    return ["QWEN.md"];
  } else if (!Array.isArray(config.contextFileName)) {
    return [config.contextFileName];
  }
  return config.contextFileName;
}
__name(getContextFileNames, "getContextFileNames");
function annotateActiveExtensions(extensions, workspaceDir, manager) {
  manager.validateExtensionOverrides(extensions);
  return extensions.map((extension) => ({
    name: extension.config.name,
    version: extension.config.version,
    isActive: manager.isEnabled(extension.config.name, workspaceDir),
    path: extension.path,
    installMetadata: extension.installMetadata
  }));
}
__name(annotateActiveExtensions, "annotateActiveExtensions");
async function requestConsentNonInteractive(consentDescription) {
  console.info(consentDescription);
  const result = await promptForConsentNonInteractive(
    "Do you want to continue? [Y/n]: "
  );
  return result;
}
__name(requestConsentNonInteractive, "requestConsentNonInteractive");
async function requestConsentInteractive(consentDescription, addExtensionUpdateConfirmationRequest) {
  return await promptForConsentInteractive(
    consentDescription + "\n\nDo you want to continue?",
    addExtensionUpdateConfirmationRequest
  );
}
__name(requestConsentInteractive, "requestConsentInteractive");
async function promptForConsentNonInteractive(prompt) {
  const readline4 = await import("node:readline");
  const rl = readline4.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  return new Promise((resolve24) => {
    rl.question(prompt, (answer) => {
      rl.close();
      resolve24(["y", ""].includes(answer.trim().toLowerCase()));
    });
  });
}
__name(promptForConsentNonInteractive, "promptForConsentNonInteractive");
async function promptForConsentInteractive(prompt, addExtensionUpdateConfirmationRequest) {
  return await new Promise((resolve24) => {
    addExtensionUpdateConfirmationRequest({
      prompt,
      onConfirm: /* @__PURE__ */ __name((resolvedConfirmed) => {
        resolve24(resolvedConfirmed);
      }, "onConfirm")
    });
  });
}
__name(promptForConsentInteractive, "promptForConsentInteractive");
async function installExtension(installMetadata, requestConsent, cwd7 = process.cwd(), previousExtensionConfig) {
  const telemetryConfig = getTelemetryConfig(cwd7);
  let newExtensionConfig = null;
  let localSourcePath;
  try {
    const settings = loadSettings(cwd7).merged;
    if (!isWorkspaceTrusted(settings)) {
      throw new Error(
        `Could not install extension from untrusted folder at ${installMetadata.source}`
      );
    }
    const extensionsDir = ExtensionStorage.getUserExtensionsDir();
    await fs69.promises.mkdir(extensionsDir, { recursive: true });
    if (!path71.isAbsolute(installMetadata.source) && (installMetadata.type === "local" || installMetadata.type === "link")) {
      installMetadata.source = path71.resolve(cwd7, installMetadata.source);
    }
    let tempDir;
    if (installMetadata.type === "git" || installMetadata.type === "github-release") {
      tempDir = await ExtensionStorage.createTmpDir();
      try {
        const result = await downloadFromGitHubRelease(
          installMetadata,
          tempDir
        );
        installMetadata.type = result.type;
        installMetadata.releaseTag = result.tagName;
      } catch (_error) {
        await cloneFromGit(installMetadata, tempDir);
        installMetadata.type = "git";
      }
      localSourcePath = tempDir;
    } else if (installMetadata.type === "local" || installMetadata.type === "link") {
      localSourcePath = installMetadata.source;
    } else {
      throw new Error(`Unsupported install type: ${installMetadata.type}`);
    }
    try {
      newExtensionConfig = loadExtensionConfig({
        extensionDir: localSourcePath,
        workspaceDir: cwd7
      });
      const newExtensionName = newExtensionConfig.name;
      const extensionStorage = new ExtensionStorage(newExtensionName);
      const destinationPath = extensionStorage.getExtensionDir();
      const installedExtensions = loadUserExtensions();
      if (installedExtensions.some(
        (installed) => installed.config.name === newExtensionName
      )) {
        throw new Error(
          `Extension "${newExtensionName}" is already installed. Please uninstall it first.`
        );
      }
      await maybeRequestConsentOrFail(
        newExtensionConfig,
        requestConsent,
        previousExtensionConfig
      );
      await fs69.promises.mkdir(destinationPath, { recursive: true });
      if (installMetadata.type === "local" || installMetadata.type === "git" || installMetadata.type === "github-release") {
        await copyExtension(localSourcePath, destinationPath);
      }
      const metadataString = JSON.stringify(installMetadata, null, 2);
      const metadataPath = path71.join(
        destinationPath,
        INSTALL_METADATA_FILENAME
      );
      await fs69.promises.writeFile(metadataPath, metadataString);
    } finally {
      if (tempDir) {
        await fs69.promises.rm(tempDir, { recursive: true, force: true });
      }
    }
    logExtensionInstallEvent(
      telemetryConfig,
      new ExtensionInstallEvent(
        newExtensionConfig.name,
        newExtensionConfig.version,
        installMetadata.source,
        "success"
      )
    );
    enableExtension(newExtensionConfig.name, "User" /* User */);
    return newExtensionConfig.name;
  } catch (error) {
    if (!newExtensionConfig && localSourcePath) {
      try {
        newExtensionConfig = loadExtensionConfig({
          extensionDir: localSourcePath,
          workspaceDir: cwd7
        });
      } catch {
      }
    }
    logExtensionInstallEvent(
      telemetryConfig,
      new ExtensionInstallEvent(
        newExtensionConfig?.name ?? "",
        newExtensionConfig?.version ?? "",
        installMetadata.source,
        "error"
      )
    );
    throw error;
  }
}
__name(installExtension, "installExtension");
function extensionConsentString(extensionConfig) {
  const output = [];
  const mcpServerEntries = Object.entries(extensionConfig.mcpServers || {});
  output.push(`Installing extension "${extensionConfig.name}".`);
  output.push(
    "**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**"
  );
  if (mcpServerEntries.length) {
    output.push("This extension will run the following MCP servers:");
    for (const [key, mcpServer] of mcpServerEntries) {
      const isLocal = !!mcpServer.command;
      const source2 = mcpServer.httpUrl ?? `${mcpServer.command || ""}${mcpServer.args ? " " + mcpServer.args.join(" ") : ""}`;
      output.push(`  * ${key} (${isLocal ? "local" : "remote"}): ${source2}`);
    }
  }
  if (extensionConfig.contextFileName) {
    output.push(
      `This extension will append info to your gemini.md context using ${extensionConfig.contextFileName}`
    );
  }
  if (extensionConfig.excludeTools) {
    output.push(
      `This extension will exclude the following core tools: ${extensionConfig.excludeTools}`
    );
  }
  return output.join("\n");
}
__name(extensionConsentString, "extensionConsentString");
async function maybeRequestConsentOrFail(extensionConfig, requestConsent, previousExtensionConfig) {
  const extensionConsent = extensionConsentString(extensionConfig);
  if (previousExtensionConfig) {
    const previousExtensionConsent = extensionConsentString(
      previousExtensionConfig
    );
    if (previousExtensionConsent === extensionConsent) {
      return;
    }
  }
  if (!await requestConsent(extensionConsent)) {
    throw new Error(`Installation cancelled for "${extensionConfig.name}".`);
  }
}
__name(maybeRequestConsentOrFail, "maybeRequestConsentOrFail");
function validateName(name3) {
  if (!/^[a-zA-Z0-9-]+$/.test(name3)) {
    throw new Error(
      `Invalid extension name: "${name3}". Only letters (a-z, A-Z), numbers (0-9), and dashes (-) are allowed.`
    );
  }
}
__name(validateName, "validateName");
function loadExtensionConfig(context2) {
  const { extensionDir, workspaceDir } = context2;
  const configFilePath2 = path71.join(extensionDir, EXTENSIONS_CONFIG_FILENAME);
  if (!fs69.existsSync(configFilePath2)) {
    throw new Error(`Configuration file not found at ${configFilePath2}`);
  }
  try {
    const configContent = fs69.readFileSync(configFilePath2, "utf-8");
    const config = recursivelyHydrateStrings(JSON.parse(configContent), {
      extensionPath: extensionDir,
      workspacePath: workspaceDir,
      "/": path71.sep,
      pathSeparator: path71.sep
    });
    if (!config.name || !config.version) {
      throw new Error(
        `Invalid configuration in ${configFilePath2}: missing ${!config.name ? '"name"' : '"version"'}`
      );
    }
    validateName(config.name);
    return config;
  } catch (e2) {
    throw new Error(
      `Failed to load extension config from ${configFilePath2}: ${getErrorMessage3(
        e2
      )}`
    );
  }
}
__name(loadExtensionConfig, "loadExtensionConfig");
async function uninstallExtension(extensionIdentifier, cwd7 = process.cwd()) {
  const telemetryConfig = getTelemetryConfig(cwd7);
  const installedExtensions = loadUserExtensions();
  const extensionName = installedExtensions.find(
    (installed) => installed.config.name.toLowerCase() === extensionIdentifier.toLowerCase() || installed.installMetadata?.source.toLowerCase() === extensionIdentifier.toLowerCase()
  )?.config.name;
  if (!extensionName) {
    throw new Error(`Extension not found.`);
  }
  const manager = new ExtensionEnablementManager(
    ExtensionStorage.getUserExtensionsDir(),
    [extensionName]
  );
  manager.remove(extensionName);
  const storage = new ExtensionStorage(extensionName);
  await fs69.promises.rm(storage.getExtensionDir(), {
    recursive: true,
    force: true
  });
  logExtensionUninstall(
    telemetryConfig,
    new ExtensionUninstallEvent(extensionName, "success")
  );
}
__name(uninstallExtension, "uninstallExtension");
function toOutputString(extension, workspaceDir) {
  const manager = new ExtensionEnablementManager(
    ExtensionStorage.getUserExtensionsDir()
  );
  const userEnabled = manager.isEnabled(extension.config.name, os26.homedir());
  const workspaceEnabled = manager.isEnabled(
    extension.config.name,
    workspaceDir
  );
  const status = workspaceEnabled ? import_chalk5.default.green("\u2713") : import_chalk5.default.red("\u2717");
  let output = `${status} ${extension.config.name} (${extension.config.version})`;
  output += `
 Path: ${extension.path}`;
  if (extension.installMetadata) {
    output += `
 Source: ${extension.installMetadata.source} (Type: ${extension.installMetadata.type})`;
    if (extension.installMetadata.ref) {
      output += `
 Ref: ${extension.installMetadata.ref}`;
    }
    if (extension.installMetadata.releaseTag) {
      output += `
 Release tag: ${extension.installMetadata.releaseTag}`;
    }
  }
  output += `
 Enabled (User): ${userEnabled}`;
  output += `
 Enabled (Workspace): ${workspaceEnabled}`;
  if (extension.contextFiles.length > 0) {
    output += `
 Context files:`;
    extension.contextFiles.forEach((contextFile) => {
      output += `
  ${contextFile}`;
    });
  }
  if (extension.config.mcpServers) {
    output += `
 MCP servers:`;
    Object.keys(extension.config.mcpServers).forEach((key) => {
      output += `
  ${key}`;
    });
  }
  if (extension.config.excludeTools) {
    output += `
 Excluded tools:`;
    extension.config.excludeTools.forEach((tool) => {
      output += `
  ${tool}`;
    });
  }
  return output;
}
__name(toOutputString, "toOutputString");
function disableExtension(name3, scope, cwd7 = process.cwd()) {
  const config = getTelemetryConfig(cwd7);
  if (scope === "System" /* System */ || scope === "SystemDefaults" /* SystemDefaults */) {
    throw new Error("System and SystemDefaults scopes are not supported.");
  }
  const extension = loadExtensionByName(name3, cwd7);
  if (!extension) {
    throw new Error(`Extension with name ${name3} does not exist.`);
  }
  const manager = new ExtensionEnablementManager(
    ExtensionStorage.getUserExtensionsDir(),
    [name3]
  );
  const scopePath = scope === "Workspace" /* Workspace */ ? cwd7 : os26.homedir();
  manager.disable(name3, true, scopePath);
  logExtensionDisable(config, new ExtensionDisableEvent(name3, scope));
}
__name(disableExtension, "disableExtension");
function enableExtension(name3, scope, cwd7 = process.cwd()) {
  if (scope === "System" /* System */ || scope === "SystemDefaults" /* SystemDefaults */) {
    throw new Error("System and SystemDefaults scopes are not supported.");
  }
  const extension = loadExtensionByName(name3, cwd7);
  if (!extension) {
    throw new Error(`Extension with name ${name3} does not exist.`);
  }
  const manager = new ExtensionEnablementManager(
    ExtensionStorage.getUserExtensionsDir()
  );
  const scopePath = scope === "Workspace" /* Workspace */ ? cwd7 : os26.homedir();
  manager.enable(name3, true, scopePath);
  const config = getTelemetryConfig(cwd7);
  logExtensionEnable(config, new ExtensionEnableEvent(name3, scope));
}
__name(enableExtension, "enableExtension");

// packages/cli/src/config/settings.ts
function getMergeStrategyForPath(path108) {
  let current = void 0;
  let currentSchema = getSettingsSchema();
  for (const key of path108) {
    if (!currentSchema || !currentSchema[key]) {
      return void 0;
    }
    current = currentSchema[key];
    currentSchema = current.properties;
  }
  return current?.mergeStrategy;
}
__name(getMergeStrategyForPath, "getMergeStrategyForPath");
var SETTINGS_DIRECTORY_NAME2 = ".qwen";
var USER_SETTINGS_PATH = Storage.getGlobalSettingsPath();
var USER_SETTINGS_DIR2 = path72.dirname(USER_SETTINGS_PATH);
var DEFAULT_EXCLUDED_ENV_VARS = ["DEBUG", "DEBUG_MODE"];
var MIGRATE_V2_OVERWRITE = true;
var SETTINGS_VERSION = 2;
var SETTINGS_VERSION_KEY = "$version";
var MIGRATION_MAP = {
  accessibility: "ui.accessibility",
  allowedTools: "tools.allowed",
  allowMCPServers: "mcp.allowed",
  autoAccept: "tools.autoAccept",
  autoConfigureMaxOldSpaceSize: "advanced.autoConfigureMemory",
  bugCommand: "advanced.bugCommand",
  chatCompression: "model.chatCompression",
  checkpointing: "general.checkpointing",
  coreTools: "tools.core",
  contextFileName: "context.fileName",
  customThemes: "ui.customThemes",
  customWittyPhrases: "ui.customWittyPhrases",
  debugKeystrokeLogging: "general.debugKeystrokeLogging",
  disableAutoUpdate: "general.disableAutoUpdate",
  disableUpdateNag: "general.disableUpdateNag",
  dnsResolutionOrder: "advanced.dnsResolutionOrder",
  enforcedAuthType: "security.auth.enforcedType",
  excludeTools: "tools.exclude",
  excludeMCPServers: "mcp.excluded",
  excludedProjectEnvVars: "advanced.excludedEnvVars",
  extensionManagement: "experimental.extensionManagement",
  extensions: "extensions",
  fileFiltering: "context.fileFiltering",
  folderTrustFeature: "security.folderTrust.featureEnabled",
  folderTrust: "security.folderTrust.enabled",
  hasSeenIdeIntegrationNudge: "ide.hasSeenNudge",
  hideWindowTitle: "ui.hideWindowTitle",
  showStatusInTitle: "ui.showStatusInTitle",
  hideTips: "ui.hideTips",
  hideBanner: "ui.hideBanner",
  hideFooter: "ui.hideFooter",
  hideCWD: "ui.footer.hideCWD",
  hideSandboxStatus: "ui.footer.hideSandboxStatus",
  hideModelInfo: "ui.footer.hideModelInfo",
  hideContextSummary: "ui.hideContextSummary",
  showMemoryUsage: "ui.showMemoryUsage",
  showLineNumbers: "ui.showLineNumbers",
  showCitations: "ui.showCitations",
  ideMode: "ide.enabled",
  includeDirectories: "context.includeDirectories",
  loadMemoryFromIncludeDirectories: "context.loadFromIncludeDirectories",
  maxSessionTurns: "model.maxSessionTurns",
  mcpServers: "mcpServers",
  mcpServerCommand: "mcp.serverCommand",
  memoryImportFormat: "context.importFormat",
  memoryDiscoveryMaxDirs: "context.discoveryMaxDirs",
  model: "model.name",
  preferredEditor: "general.preferredEditor",
  sandbox: "tools.sandbox",
  selectedAuthType: "security.auth.selectedType",
  shouldUseNodePtyShell: "tools.shell.enableInteractiveShell",
  shellPager: "tools.shell.pager",
  shellShowColor: "tools.shell.showColor",
  skipNextSpeakerCheck: "model.skipNextSpeakerCheck",
  summarizeToolOutput: "model.summarizeToolOutput",
  telemetry: "telemetry",
  theme: "ui.theme",
  toolDiscoveryCommand: "tools.discoveryCommand",
  toolCallCommand: "tools.callCommand",
  usageStatisticsEnabled: "privacy.usageStatisticsEnabled",
  useExternalAuth: "security.auth.useExternal",
  useRipgrep: "tools.useRipgrep",
  vimMode: "general.vimMode",
  enableWelcomeBack: "ui.enableWelcomeBack",
  approvalMode: "tools.approvalMode",
  sessionTokenLimit: "model.sessionTokenLimit",
  contentGenerator: "model.generationConfig",
  skipLoopDetection: "model.skipLoopDetection",
  skipStartupContext: "model.skipStartupContext",
  enableOpenAILogging: "model.enableOpenAILogging",
  tavilyApiKey: "advanced.tavilyApiKey",
  vlmSwitchMode: "experimental.vlmSwitchMode",
  visionModelPreview: "experimental.visionModelPreview"
};
function getSystemSettingsPath() {
  if (process27.env["QWEN_CODE_SYSTEM_SETTINGS_PATH"]) {
    return process27.env["QWEN_CODE_SYSTEM_SETTINGS_PATH"];
  }
  if (platform12() === "darwin") {
    return "/Library/Application Support/QwenCode/settings.json";
  } else if (platform12() === "win32") {
    return "C:\\ProgramData\\qwen-code\\settings.json";
  } else {
    return "/etc/qwen-code/settings.json";
  }
}
__name(getSystemSettingsPath, "getSystemSettingsPath");
function getSystemDefaultsPath() {
  if (process27.env["QWEN_CODE_SYSTEM_DEFAULTS_PATH"]) {
    return process27.env["QWEN_CODE_SYSTEM_DEFAULTS_PATH"];
  }
  return path72.join(
    path72.dirname(getSystemSettingsPath()),
    "system-defaults.json"
  );
}
__name(getSystemDefaultsPath, "getSystemDefaultsPath");
var SettingScope = /* @__PURE__ */ ((SettingScope2) => {
  SettingScope2["User"] = "User";
  SettingScope2["Workspace"] = "Workspace";
  SettingScope2["System"] = "System";
  SettingScope2["SystemDefaults"] = "SystemDefaults";
  return SettingScope2;
})(SettingScope || {});
function setNestedProperty(obj, path108, value) {
  const keys = path108.split(".");
  const lastKey = keys.pop();
  if (!lastKey) return;
  let current = obj;
  for (const key of keys) {
    if (current[key] === void 0) {
      current[key] = {};
    }
    const next = current[key];
    if (typeof next === "object" && next !== null) {
      current = next;
    } else {
      return;
    }
  }
  current[lastKey] = value;
}
__name(setNestedProperty, "setNestedProperty");
function needsMigration(settings) {
  if (SETTINGS_VERSION_KEY in settings) {
    const version2 = settings[SETTINGS_VERSION_KEY];
    if (typeof version2 === "number" && version2 >= SETTINGS_VERSION) {
      return false;
    }
  }
  const hasV1Keys = Object.entries(MIGRATION_MAP).some(([v1Key, v2Path]) => {
    if (v1Key === v2Path || !(v1Key in settings)) {
      return false;
    }
    if (KNOWN_V2_CONTAINERS.has(v1Key) && typeof settings[v1Key] === "object" && settings[v1Key] !== null) {
      return false;
    }
    return true;
  });
  return hasV1Keys;
}
__name(needsMigration, "needsMigration");
function migrateSettingsToV2(flatSettings) {
  if (!needsMigration(flatSettings)) {
    return null;
  }
  const v2Settings = {};
  const flatKeys = new Set(Object.keys(flatSettings));
  for (const [oldKey, newPath] of Object.entries(MIGRATION_MAP)) {
    if (flatKeys.has(oldKey)) {
      if (KNOWN_V2_CONTAINERS.has(oldKey) && typeof flatSettings[oldKey] === "object" && flatSettings[oldKey] !== null && !Array.isArray(flatSettings[oldKey])) {
        v2Settings[oldKey] = flatSettings[oldKey];
        flatKeys.delete(oldKey);
        continue;
      }
      setNestedProperty(v2Settings, newPath, flatSettings[oldKey]);
      flatKeys.delete(oldKey);
    }
  }
  if (flatSettings["mcpServers"]) {
    v2Settings["mcpServers"] = flatSettings["mcpServers"];
    flatKeys.delete("mcpServers");
  }
  for (const remainingKey of flatKeys) {
    const existingValue = v2Settings[remainingKey];
    const newValue = flatSettings[remainingKey];
    if (typeof existingValue === "object" && existingValue !== null && !Array.isArray(existingValue) && typeof newValue === "object" && newValue !== null && !Array.isArray(newValue)) {
      const pathAwareGetStrategy = /* @__PURE__ */ __name((path108) => getMergeStrategyForPath([remainingKey, ...path108]), "pathAwareGetStrategy");
      v2Settings[remainingKey] = customDeepMerge(
        pathAwareGetStrategy,
        {},
        newValue,
        existingValue
      );
    } else {
      v2Settings[remainingKey] = newValue;
    }
  }
  v2Settings[SETTINGS_VERSION_KEY] = SETTINGS_VERSION;
  return v2Settings;
}
__name(migrateSettingsToV2, "migrateSettingsToV2");
function getNestedProperty(obj, path108) {
  const keys = path108.split(".");
  let current = obj;
  for (const key of keys) {
    if (typeof current !== "object" || current === null || !(key in current)) {
      return void 0;
    }
    current = current[key];
  }
  return current;
}
__name(getNestedProperty, "getNestedProperty");
var REVERSE_MIGRATION_MAP = Object.fromEntries(
  Object.entries(MIGRATION_MAP).map(([key, value]) => [value, key])
);
var KNOWN_V2_CONTAINERS = new Set(
  Object.values(MIGRATION_MAP).map((path108) => path108.split(".")[0])
);
function migrateSettingsToV1(v2Settings) {
  const v1Settings = {};
  const v2Keys = new Set(Object.keys(v2Settings));
  for (const [newPath, oldKey] of Object.entries(REVERSE_MIGRATION_MAP)) {
    const value = getNestedProperty(v2Settings, newPath);
    if (value !== void 0) {
      v1Settings[oldKey] = value;
      v2Keys.delete(newPath.split(".")[0]);
    }
  }
  if (v2Settings["mcpServers"]) {
    v1Settings["mcpServers"] = v2Settings["mcpServers"];
    v2Keys.delete("mcpServers");
  }
  for (const remainingKey of v2Keys) {
    if (remainingKey === SETTINGS_VERSION_KEY) {
      continue;
    }
    const value = v2Settings[remainingKey];
    if (value === void 0) {
      continue;
    }
    if (KNOWN_V2_CONTAINERS.has(remainingKey) && typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length === 0) {
      continue;
    }
    v1Settings[remainingKey] = value;
  }
  return v1Settings;
}
__name(migrateSettingsToV1, "migrateSettingsToV1");
function mergeSettings(system, systemDefaults, user, workspace, isTrusted) {
  const safeWorkspace = isTrusted ? workspace : {};
  return customDeepMerge(
    getMergeStrategyForPath,
    {},
    // Start with an empty object
    systemDefaults,
    user,
    safeWorkspace,
    system
  );
}
__name(mergeSettings, "mergeSettings");
var LoadedSettings = class {
  static {
    __name(this, "LoadedSettings");
  }
  constructor(system, systemDefaults, user, workspace, isTrusted, migratedInMemorScopes) {
    this.system = system;
    this.systemDefaults = systemDefaults;
    this.user = user;
    this.workspace = workspace;
    this.isTrusted = isTrusted;
    this.migratedInMemorScopes = migratedInMemorScopes;
    this._merged = this.computeMergedSettings();
  }
  system;
  systemDefaults;
  user;
  workspace;
  isTrusted;
  migratedInMemorScopes;
  _merged;
  get merged() {
    return this._merged;
  }
  computeMergedSettings() {
    return mergeSettings(
      this.system.settings,
      this.systemDefaults.settings,
      this.user.settings,
      this.workspace.settings,
      this.isTrusted
    );
  }
  forScope(scope) {
    switch (scope) {
      case "User" /* User */:
        return this.user;
      case "Workspace" /* Workspace */:
        return this.workspace;
      case "System" /* System */:
        return this.system;
      case "SystemDefaults" /* SystemDefaults */:
        return this.systemDefaults;
      default:
        throw new Error(`Invalid scope: ${scope}`);
    }
  }
  setValue(scope, key, value) {
    const settingsFile = this.forScope(scope);
    setNestedProperty(settingsFile.settings, key, value);
    setNestedProperty(settingsFile.originalSettings, key, value);
    this._merged = this.computeMergedSettings();
    saveSettings(settingsFile);
  }
};
function findEnvFile(startDir) {
  let currentDir = path72.resolve(startDir);
  while (true) {
    const geminiEnvPath = path72.join(currentDir, QWEN_DIR5, ".env");
    if (fs70.existsSync(geminiEnvPath)) {
      return geminiEnvPath;
    }
    const envPath = path72.join(currentDir, ".env");
    if (fs70.existsSync(envPath)) {
      return envPath;
    }
    const parentDir = path72.dirname(currentDir);
    if (parentDir === currentDir || !parentDir) {
      const homeGeminiEnvPath = path72.join(homedir14(), QWEN_DIR5, ".env");
      if (fs70.existsSync(homeGeminiEnvPath)) {
        return homeGeminiEnvPath;
      }
      const homeEnvPath = path72.join(homedir14(), ".env");
      if (fs70.existsSync(homeEnvPath)) {
        return homeEnvPath;
      }
      return null;
    }
    currentDir = parentDir;
  }
}
__name(findEnvFile, "findEnvFile");
function setUpCloudShellEnvironment(envFilePath) {
  if (envFilePath && fs70.existsSync(envFilePath)) {
    const envFileContent = fs70.readFileSync(envFilePath);
    const parsedEnv = dotenv.parse(envFileContent);
    if (parsedEnv["GOOGLE_CLOUD_PROJECT"]) {
      process27.env["GOOGLE_CLOUD_PROJECT"] = parsedEnv["GOOGLE_CLOUD_PROJECT"];
    } else {
      process27.env["GOOGLE_CLOUD_PROJECT"] = "cloudshell-gca";
    }
  } else {
    process27.env["GOOGLE_CLOUD_PROJECT"] = "cloudshell-gca";
  }
}
__name(setUpCloudShellEnvironment, "setUpCloudShellEnvironment");
function loadEnvironment(settings) {
  const envFilePath = findEnvFile(process27.cwd());
  if (!isWorkspaceTrusted(settings).isTrusted) {
    return;
  }
  if (process27.env["CLOUD_SHELL"] === "true") {
    setUpCloudShellEnvironment(envFilePath);
  }
  if (envFilePath) {
    try {
      const envFileContent = fs70.readFileSync(envFilePath, "utf-8");
      const parsedEnv = dotenv.parse(envFileContent);
      const excludedVars = settings?.advanced?.excludedEnvVars || DEFAULT_EXCLUDED_ENV_VARS;
      const isProjectEnvFile = !envFilePath.includes(QWEN_DIR5);
      for (const key in parsedEnv) {
        if (Object.hasOwn(parsedEnv, key)) {
          if (isProjectEnvFile && excludedVars.includes(key)) {
            continue;
          }
          if (!Object.hasOwn(process27.env, key)) {
            process27.env[key] = parsedEnv[key];
          }
        }
      }
    } catch (_e) {
    }
  }
}
__name(loadEnvironment, "loadEnvironment");
function loadSettings(workspaceDir = process27.cwd()) {
  let systemSettings = {};
  let systemDefaultSettings = {};
  let userSettings = {};
  let workspaceSettings = {};
  const settingsErrors = [];
  const systemSettingsPath = getSystemSettingsPath();
  const systemDefaultsPath = getSystemDefaultsPath();
  const migratedInMemorScopes = /* @__PURE__ */ new Set();
  const resolvedWorkspaceDir = path72.resolve(workspaceDir);
  const resolvedHomeDir = path72.resolve(homedir14());
  let realWorkspaceDir = resolvedWorkspaceDir;
  try {
    realWorkspaceDir = fs70.realpathSync(resolvedWorkspaceDir);
  } catch (_e) {
  }
  const realHomeDir = fs70.realpathSync(resolvedHomeDir);
  const workspaceSettingsPath = new Storage(
    workspaceDir
  ).getWorkspaceSettingsPath();
  const loadAndMigrate = /* @__PURE__ */ __name((filePath, scope) => {
    try {
      if (fs70.existsSync(filePath)) {
        const content = fs70.readFileSync(filePath, "utf-8");
        const rawSettings = JSON.parse((0, import_strip_json_comments2.default)(content));
        if (typeof rawSettings !== "object" || rawSettings === null || Array.isArray(rawSettings)) {
          settingsErrors.push({
            message: "Settings file is not a valid JSON object.",
            path: filePath
          });
          return { settings: {} };
        }
        let settingsObject = rawSettings;
        if (needsMigration(settingsObject)) {
          const migratedSettings = migrateSettingsToV2(settingsObject);
          if (migratedSettings) {
            if (MIGRATE_V2_OVERWRITE) {
              try {
                fs70.renameSync(filePath, `${filePath}.orig`);
                fs70.writeFileSync(
                  filePath,
                  JSON.stringify(migratedSettings, null, 2),
                  "utf-8"
                );
              } catch (e2) {
                console.error(
                  `Error migrating settings file on disk: ${getErrorMessage(
                    e2
                  )}`
                );
              }
            } else {
              migratedInMemorScopes.add(scope);
            }
            settingsObject = migratedSettings;
          }
        } else if (!(SETTINGS_VERSION_KEY in settingsObject)) {
          settingsObject[SETTINGS_VERSION_KEY] = SETTINGS_VERSION;
          if (MIGRATE_V2_OVERWRITE) {
            try {
              fs70.writeFileSync(
                filePath,
                JSON.stringify(settingsObject, null, 2),
                "utf-8"
              );
            } catch (e2) {
              console.error(
                `Error adding version to settings file: ${getErrorMessage(e2)}`
              );
            }
          }
        }
        return { settings: settingsObject, rawJson: content };
      }
    } catch (error) {
      settingsErrors.push({
        message: getErrorMessage(error),
        path: filePath
      });
    }
    return { settings: {} };
  }, "loadAndMigrate");
  const systemResult = loadAndMigrate(systemSettingsPath, "System" /* System */);
  const systemDefaultsResult = loadAndMigrate(
    systemDefaultsPath,
    "SystemDefaults" /* SystemDefaults */
  );
  const userResult = loadAndMigrate(USER_SETTINGS_PATH, "User" /* User */);
  let workspaceResult = {
    settings: {},
    rawJson: void 0
  };
  if (realWorkspaceDir !== realHomeDir) {
    workspaceResult = loadAndMigrate(
      workspaceSettingsPath,
      "Workspace" /* Workspace */
    );
  }
  const systemOriginalSettings = structuredClone(systemResult.settings);
  const systemDefaultsOriginalSettings = structuredClone(
    systemDefaultsResult.settings
  );
  const userOriginalSettings = structuredClone(userResult.settings);
  const workspaceOriginalSettings = structuredClone(workspaceResult.settings);
  systemSettings = resolveEnvVarsInObject(systemResult.settings);
  systemDefaultSettings = resolveEnvVarsInObject(systemDefaultsResult.settings);
  userSettings = resolveEnvVarsInObject(userResult.settings);
  workspaceSettings = resolveEnvVarsInObject(workspaceResult.settings);
  if (userSettings.ui?.theme === "VS") {
    userSettings.ui.theme = DefaultLight.name;
  } else if (userSettings.ui?.theme === "VS2015") {
    userSettings.ui.theme = DefaultDark.name;
  }
  if (workspaceSettings.ui?.theme === "VS") {
    workspaceSettings.ui.theme = DefaultLight.name;
  } else if (workspaceSettings.ui?.theme === "VS2015") {
    workspaceSettings.ui.theme = DefaultDark.name;
  }
  const initialTrustCheckSettings = customDeepMerge(
    getMergeStrategyForPath,
    {},
    systemSettings,
    userSettings
  );
  const isTrusted = isWorkspaceTrusted(initialTrustCheckSettings).isTrusted ?? true;
  const tempMergedSettings = mergeSettings(
    systemSettings,
    systemDefaultSettings,
    userSettings,
    workspaceSettings,
    isTrusted
  );
  loadEnvironment(tempMergedSettings);
  if (settingsErrors.length > 0) {
    const errorMessages = settingsErrors.map(
      (error) => `Error in ${error.path}: ${error.message}`
    );
    throw new FatalConfigError(
      `${errorMessages.join("\n")}
Please fix the configuration file(s) and try again.`
    );
  }
  return new LoadedSettings(
    {
      path: systemSettingsPath,
      settings: systemSettings,
      originalSettings: systemOriginalSettings,
      rawJson: systemResult.rawJson
    },
    {
      path: systemDefaultsPath,
      settings: systemDefaultSettings,
      originalSettings: systemDefaultsOriginalSettings,
      rawJson: systemDefaultsResult.rawJson
    },
    {
      path: USER_SETTINGS_PATH,
      settings: userSettings,
      originalSettings: userOriginalSettings,
      rawJson: userResult.rawJson
    },
    {
      path: workspaceSettingsPath,
      settings: workspaceSettings,
      originalSettings: workspaceOriginalSettings,
      rawJson: workspaceResult.rawJson
    },
    isTrusted,
    migratedInMemorScopes
  );
}
__name(loadSettings, "loadSettings");
function migrateDeprecatedSettings(loadedSettings, workspaceDir = process27.cwd()) {
  const processScope = /* @__PURE__ */ __name((scope) => {
    const settings = loadedSettings.forScope(scope).settings;
    if (settings.extensions?.disabled) {
      console.log(
        `Migrating deprecated extensions.disabled settings from ${scope} settings...`
      );
      for (const extension of settings.extensions.disabled ?? []) {
        disableExtension(extension, scope, workspaceDir);
      }
      const newExtensionsValue = { ...settings.extensions };
      newExtensionsValue.disabled = void 0;
      loadedSettings.setValue(scope, "extensions", newExtensionsValue);
    }
  }, "processScope");
  processScope("User" /* User */);
  processScope("Workspace" /* Workspace */);
}
__name(migrateDeprecatedSettings, "migrateDeprecatedSettings");
function saveSettings(settingsFile) {
  try {
    const dirPath = path72.dirname(settingsFile.path);
    if (!fs70.existsSync(dirPath)) {
      fs70.mkdirSync(dirPath, { recursive: true });
    }
    let settingsToSave = settingsFile.originalSettings;
    if (!MIGRATE_V2_OVERWRITE) {
      settingsToSave = migrateSettingsToV1(
        settingsToSave
      );
    }
    updateSettingsFilePreservingFormat(
      settingsFile.path,
      settingsToSave
    );
  } catch (error) {
    console.error("Error saving user settings file:", error);
    throw error;
  }
}
__name(saveSettings, "saveSettings");

// packages/cli/src/utils/dialogScopeUtils.ts
init_esbuild_shims();

// packages/cli/src/utils/settingsUtils.ts
init_esbuild_shims();
function flattenSchema(schema, prefix = "") {
  let result = {};
  for (const key in schema) {
    const newKey = prefix ? `${prefix}.${key}` : key;
    const definition = schema[key];
    result[newKey] = { ...definition, key: newKey };
    if (definition.properties) {
      result = { ...result, ...flattenSchema(definition.properties, newKey) };
    }
  }
  return result;
}
__name(flattenSchema, "flattenSchema");
var _FLATTENED_SCHEMA;
function getFlattenedSchema() {
  return _FLATTENED_SCHEMA ?? (_FLATTENED_SCHEMA = flattenSchema(getSettingsSchema()));
}
__name(getFlattenedSchema, "getFlattenedSchema");
function getSettingDefinition(key) {
  return getFlattenedSchema()[key];
}
__name(getSettingDefinition, "getSettingDefinition");
function requiresRestart(key) {
  return getFlattenedSchema()[key]?.requiresRestart ?? false;
}
__name(requiresRestart, "requiresRestart");
function getDefaultValue(key) {
  return getFlattenedSchema()[key]?.default;
}
__name(getDefaultValue, "getDefaultValue");
function getNestedValue(obj, path108) {
  const [first2, ...rest] = path108;
  if (!first2 || !(first2 in obj)) {
    return void 0;
  }
  const value = obj[first2];
  if (rest.length === 0) {
    return value;
  }
  if (value && typeof value === "object" && value !== null) {
    return getNestedValue(value, rest);
  }
  return void 0;
}
__name(getNestedValue, "getNestedValue");
function getEffectiveValue(key, settings, mergedSettings) {
  const definition = getSettingDefinition(key);
  if (!definition) {
    return void 0;
  }
  const path108 = key.split(".");
  let value = getNestedValue(settings, path108);
  if (value !== void 0) {
    return value;
  }
  value = getNestedValue(mergedSettings, path108);
  if (value !== void 0) {
    return value;
  }
  return definition.default;
}
__name(getEffectiveValue, "getEffectiveValue");
function getDialogSettingKeys() {
  return Object.values(getFlattenedSchema()).filter((definition) => definition.showInDialog !== false).map((definition) => definition.key);
}
__name(getDialogSettingKeys, "getDialogSettingKeys");
function settingExistsInScope(key, scopeSettings) {
  const path108 = key.split(".");
  const value = getNestedValue(scopeSettings, path108);
  return value !== void 0;
}
__name(settingExistsInScope, "settingExistsInScope");
function setNestedValue(obj, path108, value) {
  const [first2, ...rest] = path108;
  if (!first2) {
    return obj;
  }
  if (rest.length === 0) {
    obj[first2] = value;
    return obj;
  }
  if (!obj[first2] || typeof obj[first2] !== "object") {
    obj[first2] = {};
  }
  setNestedValue(obj[first2], rest, value);
  return obj;
}
__name(setNestedValue, "setNestedValue");
function setPendingSettingValue(key, value, pendingSettings) {
  const path108 = key.split(".");
  const newSettings = JSON.parse(JSON.stringify(pendingSettings));
  setNestedValue(newSettings, path108, value);
  return newSettings;
}
__name(setPendingSettingValue, "setPendingSettingValue");
function setPendingSettingValueAny(key, value, pendingSettings) {
  const path108 = key.split(".");
  const newSettings = structuredClone(pendingSettings);
  setNestedValue(newSettings, path108, value);
  return newSettings;
}
__name(setPendingSettingValueAny, "setPendingSettingValueAny");
function hasRestartRequiredSettings(modifiedSettings) {
  return Array.from(modifiedSettings).some((key) => requiresRestart(key));
}
__name(hasRestartRequiredSettings, "hasRestartRequiredSettings");
function getRestartRequiredFromModified(modifiedSettings) {
  return Array.from(modifiedSettings).filter((key) => requiresRestart(key));
}
__name(getRestartRequiredFromModified, "getRestartRequiredFromModified");
function saveModifiedSettings(modifiedSettings, pendingSettings, loadedSettings, scope) {
  modifiedSettings.forEach((settingKey) => {
    const path108 = settingKey.split(".");
    const value = getNestedValue(
      pendingSettings,
      path108
    );
    if (value === void 0) {
      return;
    }
    const existsInOriginalFile = settingExistsInScope(
      settingKey,
      loadedSettings.forScope(scope).settings
    );
    const isDefaultValue2 = value === getDefaultValue(settingKey);
    if (existsInOriginalFile || !isDefaultValue2) {
      loadedSettings.setValue(scope, settingKey, value);
    }
  });
}
__name(saveModifiedSettings, "saveModifiedSettings");
function getDisplayValue(key, settings, _mergedSettings, modifiedSettings, pendingSettings) {
  const definition = getSettingDefinition(key);
  let value;
  if (pendingSettings && settingExistsInScope(key, pendingSettings)) {
    value = getEffectiveValue(key, pendingSettings, {});
  } else if (settingExistsInScope(key, settings)) {
    value = getEffectiveValue(key, settings, {});
  } else {
    value = getDefaultValue(key);
  }
  let valueString = String(value);
  if (definition?.type === "enum" && definition.options) {
    const option2 = definition.options?.find((option3) => option3.value === value);
    valueString = option2?.label ?? `${value}`;
  }
  const defaultValue = getDefaultValue(key);
  const isChangedFromDefault = value !== defaultValue;
  const isInModifiedSettings = modifiedSettings.has(key);
  if (settingExistsInScope(key, settings) || isInModifiedSettings) {
    return `${valueString}*`;
  }
  if (isChangedFromDefault || isInModifiedSettings) {
    return `${valueString}*`;
  }
  return valueString;
}
__name(getDisplayValue, "getDisplayValue");
function isDefaultValue(key, settings) {
  return !settingExistsInScope(key, settings);
}
__name(isDefaultValue, "isDefaultValue");

// packages/cli/src/utils/dialogScopeUtils.ts
var SCOPE_LABELS = {
  ["User" /* User */]: "User Settings",
  ["Workspace" /* Workspace */]: "Workspace Settings"
  // TODO: migrate system settings to user settings
  // we don't want to save settings to system scope, it is a troublemaker
  // comment it out for now.
  // [SettingScope.System]: 'System Settings',
};
function getScopeItems() {
  return [
    { label: SCOPE_LABELS["User" /* User */], value: "User" /* User */ },
    {
      label: SCOPE_LABELS["Workspace" /* Workspace */],
      value: "Workspace" /* Workspace */
    }
    // { label: SCOPE_LABELS[SettingScope.System], value: SettingScope.System },
  ];
}
__name(getScopeItems, "getScopeItems");
function getScopeMessageForSetting(settingKey, selectedScope, settings) {
  const otherScopes = Object.values(SettingScope).filter(
    (scope) => scope !== selectedScope
  );
  const modifiedInOtherScopes = otherScopes.filter((scope) => {
    const scopeSettings = settings.forScope(scope).settings;
    return settingExistsInScope(settingKey, scopeSettings);
  });
  if (modifiedInOtherScopes.length === 0) {
    return "";
  }
  const modifiedScopesStr = modifiedInOtherScopes.join(", ");
  const currentScopeSettings = settings.forScope(selectedScope).settings;
  const existsInCurrentScope = settingExistsInScope(
    settingKey,
    currentScopeSettings
  );
  return existsInCurrentScope ? `(Also modified in ${modifiedScopesStr})` : `(Modified in ${modifiedScopesStr})`;
}
__name(getScopeMessageForSetting, "getScopeMessageForSetting");

// packages/cli/src/ui/components/shared/ScopeSelector.tsx
init_esbuild_shims();
var import_jsx_runtime67 = __toESM(require_jsx_runtime(), 1);
function ScopeSelector({
  onSelect,
  onHighlight,
  isFocused,
  initialScope
}) {
  const scopeItems = getScopeItems().map((item) => ({
    ...item,
    key: item.value
  }));
  const initialIndex = scopeItems.findIndex(
    (item) => item.value === initialScope
  );
  const safeInitialIndex = initialIndex >= 0 ? initialIndex : 0;
  return /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(Text, { bold: isFocused, wrap: "truncate", children: [
      isFocused ? "> " : "  ",
      "Apply To"
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(
      RadioButtonSelect,
      {
        items: scopeItems,
        initialIndex: safeInitialIndex,
        onSelect,
        onHighlight,
        isFocused,
        showNumbers: isFocused
      }
    )
  ] });
}
__name(ScopeSelector, "ScopeSelector");

// packages/cli/src/ui/components/ThemeDialog.tsx
var import_jsx_runtime68 = __toESM(require_jsx_runtime(), 1);
function ThemeDialog({
  onSelect,
  onHighlight,
  settings,
  availableTerminalHeight,
  terminalWidth
}) {
  const [selectedScope, setSelectedScope] = (0, import_react70.useState)(
    "User" /* User */
  );
  const [highlightedThemeName, setHighlightedThemeName] = (0, import_react70.useState)(settings.merged.ui?.theme || DEFAULT_THEME.name);
  const customThemes = selectedScope === "User" /* User */ ? settings.user.settings.ui?.customThemes || {} : settings.merged.ui?.customThemes || {};
  const builtInThemes = themeManager.getAvailableThemes().filter((theme2) => theme2.type !== "custom");
  const customThemeNames = Object.keys(customThemes);
  const capitalize = /* @__PURE__ */ __name((s2) => s2.charAt(0).toUpperCase() + s2.slice(1), "capitalize");
  const themeItems = [
    ...builtInThemes.map((theme2) => ({
      label: theme2.name,
      value: theme2.name,
      themeNameDisplay: theme2.name,
      themeTypeDisplay: capitalize(theme2.type),
      key: theme2.name
    })),
    ...customThemeNames.map((name3) => ({
      label: name3,
      value: name3,
      themeNameDisplay: name3,
      themeTypeDisplay: "Custom",
      key: name3
    }))
  ];
  const initialThemeIndex = themeItems.findIndex(
    (item) => item.value === highlightedThemeName
  );
  const safeInitialThemeIndex = initialThemeIndex >= 0 ? initialThemeIndex : 0;
  const handleThemeSelect = (0, import_react70.useCallback)(
    (themeName) => {
      onSelect(themeName, selectedScope);
    },
    [onSelect, selectedScope]
  );
  const handleThemeHighlight = /* @__PURE__ */ __name((themeName) => {
    setHighlightedThemeName(themeName);
    onHighlight(themeName);
  }, "handleThemeHighlight");
  const handleScopeHighlight = (0, import_react70.useCallback)((scope) => {
    setSelectedScope(scope);
  }, []);
  const handleScopeSelect = (0, import_react70.useCallback)(
    (scope) => {
      onSelect(highlightedThemeName, scope);
    },
    [onSelect, highlightedThemeName]
  );
  const [mode, setMode] = (0, import_react70.useState)("theme");
  useKeypress(
    (key) => {
      if (key.name === "tab") {
        setMode((prev) => prev === "theme" ? "scope" : "theme");
      }
      if (key.name === "escape") {
        onSelect(void 0, selectedScope);
      }
    },
    { isActive: true }
  );
  const otherScopeModifiedMessage = getScopeMessageForSetting(
    "ui.theme",
    selectedScope,
    settings
  );
  const PREVIEW_PANE_WIDTH_PERCENTAGE = 0.55;
  const PREVIEW_PANE_WIDTH_SAFETY_MARGIN = 0.9;
  const TOTAL_HORIZONTAL_PADDING = 4;
  const colorizeCodeWidth = Math.max(
    Math.floor(
      (terminalWidth - TOTAL_HORIZONTAL_PADDING) * PREVIEW_PANE_WIDTH_PERCENTAGE * PREVIEW_PANE_WIDTH_SAFETY_MARGIN
    ),
    1
  );
  const DIALOG_PADDING = 2;
  const selectThemeHeight = themeItems.length + 1;
  const TAB_TO_SELECT_HEIGHT = 2;
  availableTerminalHeight = availableTerminalHeight ?? Number.MAX_SAFE_INTEGER;
  availableTerminalHeight -= 2;
  availableTerminalHeight -= TAB_TO_SELECT_HEIGHT;
  let totalLeftHandSideHeight = DIALOG_PADDING + selectThemeHeight;
  let includePadding = true;
  if (totalLeftHandSideHeight > availableTerminalHeight) {
    includePadding = false;
    totalLeftHandSideHeight -= DIALOG_PADDING;
  }
  const PREVIEW_PANE_FIXED_VERTICAL_SPACE = 8;
  availableTerminalHeight = Math.max(
    availableTerminalHeight,
    totalLeftHandSideHeight
  );
  const availableTerminalHeightCodeBlock = availableTerminalHeight - PREVIEW_PANE_FIXED_VERTICAL_SPACE - (includePadding ? 2 : 0) * 2;
  const availableHeightForPanes = Math.max(
    0,
    availableTerminalHeightCodeBlock - 1
  );
  const codeBlockHeight = Math.ceil(availableHeightForPanes * 0.6);
  const diffHeight = Math.floor(availableHeightForPanes * 0.4);
  return /* @__PURE__ */ (0, import_jsx_runtime68.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingTop: includePadding ? 1 : 0,
      paddingBottom: includePadding ? 1 : 0,
      paddingLeft: 1,
      paddingRight: 1,
      width: "100%",
      children: [
        mode === "theme" ? /* @__PURE__ */ (0, import_jsx_runtime68.jsxs)(Box_default, { flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime68.jsxs)(Box_default, { flexDirection: "column", width: "45%", paddingRight: 2, children: [
            /* @__PURE__ */ (0, import_jsx_runtime68.jsxs)(Text, { bold: mode === "theme", wrap: "truncate", children: [
              mode === "theme" ? "> " : "  ",
              "Select Theme",
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(Text, { color: theme.text.secondary, children: otherScopeModifiedMessage })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(
              RadioButtonSelect,
              {
                items: themeItems,
                initialIndex: safeInitialThemeIndex,
                onSelect: handleThemeSelect,
                onHighlight: handleThemeHighlight,
                isFocused: mode === "theme",
                maxItemsToShow: 12,
                showScrollArrows: true,
                showNumbers: mode === "theme"
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime68.jsxs)(Box_default, { flexDirection: "column", width: "55%", paddingLeft: 2, children: [
            /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(Text, { bold: true, color: theme.text.primary, children: "Preview" }),
            (() => {
              const previewTheme = themeManager.getTheme(
                highlightedThemeName || DEFAULT_THEME.name
              ) || DEFAULT_THEME;
              return /* @__PURE__ */ (0, import_jsx_runtime68.jsxs)(
                Box_default,
                {
                  borderStyle: "single",
                  borderColor: theme.border.default,
                  paddingTop: includePadding ? 1 : 0,
                  paddingBottom: includePadding ? 1 : 0,
                  paddingLeft: 1,
                  paddingRight: 1,
                  flexDirection: "column",
                  children: [
                    colorizeCode(
                      `# function
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a`,
                      "python",
                      codeBlockHeight,
                      colorizeCodeWidth
                    ),
                    /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(Box_default, { marginTop: 1 }),
                    /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(
                      DiffRenderer,
                      {
                        diffContent: `--- a/util.py
+++ b/util.py
@@ -1,2 +1,2 @@
- print("Hello, " + name)
+ print(f"Hello, {name}!")
`,
                        availableTerminalHeight: diffHeight,
                        terminalWidth: colorizeCodeWidth,
                        theme: previewTheme
                      }
                    )
                  ]
                }
              );
            })()
          ] })
        ] }) : /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(
          ScopeSelector,
          {
            onSelect: handleScopeSelect,
            onHighlight: handleScopeHighlight,
            isFocused: mode === "scope",
            initialScope: selectedScope
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime68.jsxs)(Text, { color: theme.text.secondary, wrap: "truncate", children: [
          "(Use Enter to ",
          mode === "theme" ? "select" : "apply scope",
          ", Tab to",
          " ",
          mode === "theme" ? "configure scope" : "select theme",
          ")"
        ] }) })
      ]
    }
  );
}
__name(ThemeDialog, "ThemeDialog");

// packages/cli/src/ui/components/SettingsDialog.tsx
init_esbuild_shims();
var import_react72 = __toESM(require_react(), 1);

// packages/cli/src/ui/contexts/VimModeContext.tsx
init_esbuild_shims();
var import_react71 = __toESM(require_react(), 1);
var import_jsx_runtime69 = __toESM(require_jsx_runtime(), 1);
var VimModeContext = (0, import_react71.createContext)(void 0);
var VimModeProvider = /* @__PURE__ */ __name(({
  children,
  settings
}) => {
  const initialVimEnabled = settings.merged.general?.vimMode ?? false;
  const [vimEnabled, setVimEnabled] = (0, import_react71.useState)(initialVimEnabled);
  const [vimMode, setVimMode] = (0, import_react71.useState)(
    initialVimEnabled ? "NORMAL" : "INSERT"
  );
  (0, import_react71.useEffect)(() => {
    const enabled = settings.merged.general?.vimMode ?? false;
    setVimEnabled(enabled);
    if (enabled) {
      setVimMode("NORMAL");
    }
  }, [settings.merged.general?.vimMode]);
  const toggleVimEnabled = (0, import_react71.useCallback)(async () => {
    const newValue = !vimEnabled;
    setVimEnabled(newValue);
    if (newValue) {
      setVimMode("NORMAL");
    }
    await settings.setValue("User" /* User */, "general.vimMode", newValue);
    return newValue;
  }, [vimEnabled, settings]);
  const value = {
    vimEnabled,
    vimMode,
    toggleVimEnabled,
    setVimMode
  };
  return /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(VimModeContext.Provider, { value, children });
}, "VimModeProvider");
var useVimMode = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react71.useContext)(VimModeContext);
  if (context2 === void 0) {
    throw new Error("useVimMode must be used within a VimModeProvider");
  }
  return context2;
}, "useVimMode");

// packages/cli/src/ui/components/SettingsDialog.tsx
var import_chalk6 = __toESM(require_source(), 1);
var import_jsx_runtime70 = __toESM(require_jsx_runtime(), 1);
var maxItemsToShow = 8;
function SettingsDialog({
  settings,
  onSelect,
  onRestartRequest,
  availableTerminalHeight,
  config
}) {
  const { vimEnabled, toggleVimEnabled } = useVimMode();
  const [focusSection, setFocusSection] = (0, import_react72.useState)(
    "settings"
  );
  const [selectedScope, setSelectedScope] = (0, import_react72.useState)(
    "User" /* User */
  );
  const [activeSettingIndex, setActiveSettingIndex] = (0, import_react72.useState)(0);
  const [scrollOffset, setScrollOffset] = (0, import_react72.useState)(0);
  const [showRestartPrompt, setShowRestartPrompt] = (0, import_react72.useState)(false);
  const [pendingSettings, setPendingSettings] = (0, import_react72.useState)(
    () => (
      // Deep clone to avoid mutation
      structuredClone(settings.forScope(selectedScope).settings)
    )
  );
  const [modifiedSettings, setModifiedSettings] = (0, import_react72.useState)(
    /* @__PURE__ */ new Set()
  );
  const [globalPendingChanges, setGlobalPendingChanges] = (0, import_react72.useState)(/* @__PURE__ */ new Map());
  const [_restartRequiredSettings, setRestartRequiredSettings] = (0, import_react72.useState)(/* @__PURE__ */ new Set());
  (0, import_react72.useEffect)(() => {
    let updated = structuredClone(settings.forScope(selectedScope).settings);
    const newModified = /* @__PURE__ */ new Set();
    const newRestartRequired = /* @__PURE__ */ new Set();
    for (const [key, value] of globalPendingChanges.entries()) {
      const def2 = getSettingDefinition(key);
      if (def2?.type === "boolean" && typeof value === "boolean") {
        updated = setPendingSettingValue(key, value, updated);
      } else if (def2?.type === "number" && typeof value === "number" || def2?.type === "string" && typeof value === "string") {
        updated = setPendingSettingValueAny(key, value, updated);
      }
      newModified.add(key);
      if (requiresRestart(key)) newRestartRequired.add(key);
    }
    setPendingSettings(updated);
    setModifiedSettings(newModified);
    setRestartRequiredSettings(newRestartRequired);
    setShowRestartPrompt(newRestartRequired.size > 0);
  }, [selectedScope, settings, globalPendingChanges]);
  const generateSettingsItems = /* @__PURE__ */ __name(() => {
    const settingKeys = getDialogSettingKeys();
    return settingKeys.map((key) => {
      const definition = getSettingDefinition(key);
      return {
        label: definition?.label || key,
        value: key,
        type: definition?.type,
        toggle: /* @__PURE__ */ __name(() => {
          if (!TOGGLE_TYPES.has(definition?.type)) {
            return;
          }
          const currentValue = getEffectiveValue(key, pendingSettings, {});
          let newValue;
          if (definition?.type === "boolean") {
            newValue = !currentValue;
            setPendingSettings(
              (prev) => setPendingSettingValue(key, newValue, prev)
            );
          } else if (definition?.type === "enum" && definition.options) {
            const options2 = definition.options;
            const currentIndex = options2?.findIndex(
              (opt) => opt.value === currentValue
            );
            if (currentIndex !== -1 && currentIndex < options2.length - 1) {
              newValue = options2[currentIndex + 1].value;
            } else {
              newValue = options2[0].value;
            }
            setPendingSettings(
              (prev) => setPendingSettingValueAny(key, newValue, prev)
            );
          }
          setPendingSettings(
            (prev) => setPendingSettingValue(key, newValue, prev)
          );
          if (!requiresRestart(key)) {
            const immediateSettings = /* @__PURE__ */ new Set([key]);
            const immediateSettingsObject = setPendingSettingValueAny(
              key,
              newValue,
              {}
            );
            console.log(
              `[DEBUG SettingsDialog] Saving ${key} immediately with value:`,
              newValue
            );
            saveModifiedSettings(
              immediateSettings,
              immediateSettingsObject,
              settings,
              selectedScope
            );
            if (key === "general.vimMode" && newValue !== vimEnabled) {
              toggleVimEnabled().catch((error) => {
                console.error("Failed to toggle vim mode:", error);
              });
            }
            if (key === "tools.approvalMode" && settings.merged.tools?.approvalMode) {
              try {
                config?.setApprovalMode(settings.merged.tools.approvalMode);
              } catch (error) {
                console.error(
                  "Failed to apply approval mode to current session:",
                  error
                );
              }
            }
            setModifiedSettings((prev) => {
              const updated = new Set(prev);
              updated.delete(key);
              return updated;
            });
            setRestartRequiredSettings((prev) => {
              const updated = new Set(prev);
              updated.delete(key);
              return updated;
            });
            setGlobalPendingChanges((prev) => {
              if (!prev.has(key)) return prev;
              const next = new Map(prev);
              next.delete(key);
              return next;
            });
            setPendingSettings(
              structuredClone(settings.forScope(selectedScope).settings)
            );
          } else {
            setModifiedSettings((prev) => {
              const updated = new Set(prev).add(key);
              const needsRestart = hasRestartRequiredSettings(updated);
              console.log(
                `[DEBUG SettingsDialog] Modified settings:`,
                Array.from(updated),
                "Needs restart:",
                needsRestart
              );
              if (needsRestart) {
                setShowRestartPrompt(true);
                setRestartRequiredSettings(
                  (prevRestart) => new Set(prevRestart).add(key)
                );
              }
              return updated;
            });
            setGlobalPendingChanges((prev) => {
              const next = new Map(prev);
              next.set(key, newValue);
              return next;
            });
          }
        }, "toggle")
      };
    });
  }, "generateSettingsItems");
  const items = generateSettingsItems();
  const [editingKey, setEditingKey] = (0, import_react72.useState)(null);
  const [editBuffer, setEditBuffer] = (0, import_react72.useState)("");
  const [editCursorPos, setEditCursorPos] = (0, import_react72.useState)(0);
  const [cursorVisible, setCursorVisible] = (0, import_react72.useState)(true);
  (0, import_react72.useEffect)(() => {
    if (!editingKey) {
      setCursorVisible(true);
      return;
    }
    const id = setInterval(() => setCursorVisible((v) => !v), 500);
    return () => clearInterval(id);
  }, [editingKey]);
  const startEditing = /* @__PURE__ */ __name((key, initial) => {
    setEditingKey(key);
    const initialValue = initial ?? "";
    setEditBuffer(initialValue);
    setEditCursorPos(cpLen(initialValue));
  }, "startEditing");
  const commitEdit = /* @__PURE__ */ __name((key) => {
    const definition = getSettingDefinition(key);
    const type = definition?.type;
    if (editBuffer.trim() === "" && type === "number") {
      setEditingKey(null);
      setEditBuffer("");
      setEditCursorPos(0);
      return;
    }
    let parsed;
    if (type === "number") {
      const numParsed = Number(editBuffer.trim());
      if (Number.isNaN(numParsed)) {
        setEditingKey(null);
        setEditBuffer("");
        setEditCursorPos(0);
        return;
      }
      parsed = numParsed;
    } else {
      parsed = editBuffer;
    }
    setPendingSettings((prev) => setPendingSettingValueAny(key, parsed, prev));
    if (!requiresRestart(key)) {
      const immediateSettings = /* @__PURE__ */ new Set([key]);
      const immediateSettingsObject = setPendingSettingValueAny(
        key,
        parsed,
        {}
      );
      saveModifiedSettings(
        immediateSettings,
        immediateSettingsObject,
        settings,
        selectedScope
      );
      setModifiedSettings((prev) => {
        const updated = new Set(prev);
        updated.delete(key);
        return updated;
      });
      setRestartRequiredSettings((prev) => {
        const updated = new Set(prev);
        updated.delete(key);
        return updated;
      });
      setGlobalPendingChanges((prev) => {
        if (!prev.has(key)) return prev;
        const next = new Map(prev);
        next.delete(key);
        return next;
      });
    } else {
      setModifiedSettings((prev) => {
        const updated = new Set(prev).add(key);
        const needsRestart = hasRestartRequiredSettings(updated);
        if (needsRestart) {
          setShowRestartPrompt(true);
          setRestartRequiredSettings(
            (prevRestart) => new Set(prevRestart).add(key)
          );
        }
        return updated;
      });
      setGlobalPendingChanges((prev) => {
        const next = new Map(prev);
        next.set(key, parsed);
        return next;
      });
    }
    setEditingKey(null);
    setEditBuffer("");
    setEditCursorPos(0);
  }, "commitEdit");
  const handleScopeHighlight = /* @__PURE__ */ __name((scope) => {
    setSelectedScope(scope);
  }, "handleScopeHighlight");
  const handleScopeSelect = /* @__PURE__ */ __name((scope) => {
    handleScopeHighlight(scope);
    setFocusSection("settings");
  }, "handleScopeSelect");
  const DIALOG_PADDING = 2;
  const SETTINGS_TITLE_HEIGHT = 2;
  const SCROLL_ARROWS_HEIGHT = 2;
  const SPACING_HEIGHT = 1;
  const SCOPE_SELECTION_HEIGHT = 4;
  const BOTTOM_HELP_TEXT_HEIGHT = 1;
  const RESTART_PROMPT_HEIGHT = showRestartPrompt ? 1 : 0;
  let currentAvailableTerminalHeight = availableTerminalHeight ?? Number.MAX_SAFE_INTEGER;
  currentAvailableTerminalHeight -= 2;
  let totalFixedHeight = DIALOG_PADDING + SETTINGS_TITLE_HEIGHT + SCROLL_ARROWS_HEIGHT + SPACING_HEIGHT + BOTTOM_HELP_TEXT_HEIGHT + RESTART_PROMPT_HEIGHT;
  let availableHeightForSettings = Math.max(
    1,
    currentAvailableTerminalHeight - totalFixedHeight
  );
  let maxVisibleItems = Math.max(1, Math.floor(availableHeightForSettings / 2));
  let showScopeSelection = true;
  if (availableTerminalHeight && availableTerminalHeight < 25) {
    const totalWithScope = totalFixedHeight + SCOPE_SELECTION_HEIGHT;
    const availableWithScope = Math.max(
      1,
      currentAvailableTerminalHeight - totalWithScope
    );
    const maxItemsWithScope = Math.max(1, Math.floor(availableWithScope / 2));
    if (maxVisibleItems > maxItemsWithScope + 1) {
      showScopeSelection = false;
    } else {
      totalFixedHeight += SCOPE_SELECTION_HEIGHT;
      availableHeightForSettings = Math.max(
        1,
        currentAvailableTerminalHeight - totalFixedHeight
      );
      maxVisibleItems = Math.max(1, Math.floor(availableHeightForSettings / 2));
    }
  } else {
    totalFixedHeight += SCOPE_SELECTION_HEIGHT;
    availableHeightForSettings = Math.max(
      1,
      currentAvailableTerminalHeight - totalFixedHeight
    );
    maxVisibleItems = Math.max(1, Math.floor(availableHeightForSettings / 2));
  }
  const effectiveMaxItemsToShow = availableTerminalHeight ? Math.min(maxVisibleItems, items.length) : maxItemsToShow;
  import_react72.default.useEffect(() => {
    if (!showScopeSelection && focusSection === "scope") {
      setFocusSection("settings");
    }
  }, [showScopeSelection, focusSection]);
  const visibleItems = items.slice(
    scrollOffset,
    scrollOffset + effectiveMaxItemsToShow
  );
  const showScrollUp = items.length > effectiveMaxItemsToShow;
  const showScrollDown = items.length > effectiveMaxItemsToShow;
  useKeypress(
    (key) => {
      const { name: name3, ctrl } = key;
      if (name3 === "tab" && showScopeSelection) {
        setFocusSection((prev) => prev === "settings" ? "scope" : "settings");
      }
      if (focusSection === "settings") {
        if (editingKey) {
          const definition = getSettingDefinition(editingKey);
          const type = definition?.type;
          if (key.paste && key.sequence) {
            let pasted = key.sequence;
            if (type === "number") {
              pasted = key.sequence.replace(/[^0-9\-+.]/g, "");
            }
            if (pasted) {
              setEditBuffer((b) => {
                const before = cpSlice(b, 0, editCursorPos);
                const after = cpSlice(b, editCursorPos);
                return before + pasted + after;
              });
              setEditCursorPos((pos2) => pos2 + cpLen(pasted));
            }
            return;
          }
          if (name3 === "backspace" || name3 === "delete") {
            if (name3 === "backspace" && editCursorPos > 0) {
              setEditBuffer((b) => {
                const before = cpSlice(b, 0, editCursorPos - 1);
                const after = cpSlice(b, editCursorPos);
                return before + after;
              });
              setEditCursorPos((pos2) => pos2 - 1);
            } else if (name3 === "delete" && editCursorPos < cpLen(editBuffer)) {
              setEditBuffer((b) => {
                const before = cpSlice(b, 0, editCursorPos);
                const after = cpSlice(b, editCursorPos + 1);
                return before + after;
              });
            }
            return;
          }
          if (name3 === "escape") {
            commitEdit(editingKey);
            return;
          }
          if (name3 === "return") {
            commitEdit(editingKey);
            return;
          }
          let ch = key.sequence;
          let isValidChar = false;
          if (type === "number") {
            isValidChar = /[0-9\-+.]/.test(ch);
          } else {
            ch = stripUnsafeCharacters(ch);
            isValidChar = ch.length === 1;
          }
          if (isValidChar) {
            setEditBuffer((currentBuffer) => {
              const beforeCursor = cpSlice(currentBuffer, 0, editCursorPos);
              const afterCursor = cpSlice(currentBuffer, editCursorPos);
              return beforeCursor + ch + afterCursor;
            });
            setEditCursorPos((pos2) => pos2 + 1);
            return;
          }
          if (name3 === "left") {
            setEditCursorPos((pos2) => Math.max(0, pos2 - 1));
            return;
          }
          if (name3 === "right") {
            setEditCursorPos((pos2) => Math.min(cpLen(editBuffer), pos2 + 1));
            return;
          }
          if (name3 === "home") {
            setEditCursorPos(0);
            return;
          }
          if (name3 === "end") {
            setEditCursorPos(cpLen(editBuffer));
            return;
          }
          return;
        }
        if (name3 === "up" || name3 === "k") {
          if (editingKey) {
            commitEdit(editingKey);
          }
          const newIndex = activeSettingIndex > 0 ? activeSettingIndex - 1 : items.length - 1;
          setActiveSettingIndex(newIndex);
          if (newIndex === items.length - 1) {
            setScrollOffset(
              Math.max(0, items.length - effectiveMaxItemsToShow)
            );
          } else if (newIndex < scrollOffset) {
            setScrollOffset(newIndex);
          }
        } else if (name3 === "down" || name3 === "j") {
          if (editingKey) {
            commitEdit(editingKey);
          }
          const newIndex = activeSettingIndex < items.length - 1 ? activeSettingIndex + 1 : 0;
          setActiveSettingIndex(newIndex);
          if (newIndex === 0) {
            setScrollOffset(0);
          } else if (newIndex >= scrollOffset + effectiveMaxItemsToShow) {
            setScrollOffset(newIndex - effectiveMaxItemsToShow + 1);
          }
        } else if (name3 === "return" || name3 === "space") {
          const currentItem = items[activeSettingIndex];
          if (currentItem?.type === "number" || currentItem?.type === "string") {
            startEditing(currentItem.value);
          } else {
            currentItem?.toggle();
          }
        } else if (/^[0-9]$/.test(key.sequence || "") && !editingKey) {
          const currentItem = items[activeSettingIndex];
          if (currentItem?.type === "number") {
            startEditing(currentItem.value, key.sequence);
          }
        } else if (ctrl && (name3 === "c" || name3 === "l")) {
          const currentSetting = items[activeSettingIndex];
          if (currentSetting) {
            const defaultValue = getDefaultValue(currentSetting.value);
            const defType = currentSetting.type;
            if (defType === "boolean") {
              const booleanDefaultValue = typeof defaultValue === "boolean" ? defaultValue : false;
              setPendingSettings(
                (prev) => setPendingSettingValue(
                  currentSetting.value,
                  booleanDefaultValue,
                  prev
                )
              );
            } else if (defType === "number" || defType === "string" || defType === "enum") {
              if (typeof defaultValue === "number" || typeof defaultValue === "string") {
                setPendingSettings(
                  (prev) => setPendingSettingValueAny(
                    currentSetting.value,
                    defaultValue,
                    prev
                  )
                );
              }
            }
            setModifiedSettings((prev) => {
              const updated = new Set(prev);
              updated.delete(currentSetting.value);
              return updated;
            });
            setRestartRequiredSettings((prev) => {
              const updated = new Set(prev);
              updated.delete(currentSetting.value);
              return updated;
            });
            if (!requiresRestart(currentSetting.value)) {
              const immediateSettings = /* @__PURE__ */ new Set([currentSetting.value]);
              const toSaveValue = currentSetting.type === "boolean" ? typeof defaultValue === "boolean" ? defaultValue : false : typeof defaultValue === "number" || typeof defaultValue === "string" ? defaultValue : void 0;
              const immediateSettingsObject = toSaveValue !== void 0 ? setPendingSettingValueAny(
                currentSetting.value,
                toSaveValue,
                {}
              ) : {};
              saveModifiedSettings(
                immediateSettings,
                immediateSettingsObject,
                settings,
                selectedScope
              );
              if (currentSetting.value === "tools.approvalMode" && settings.merged.tools?.approvalMode) {
                try {
                  config?.setApprovalMode(settings.merged.tools.approvalMode);
                } catch (error) {
                  console.error(
                    "Failed to apply approval mode to current session:",
                    error
                  );
                }
              }
              setGlobalPendingChanges((prev) => {
                if (!prev.has(currentSetting.value)) return prev;
                const next = new Map(prev);
                next.delete(currentSetting.value);
                return next;
              });
            } else {
              if (currentSetting.type === "boolean" && typeof defaultValue === "boolean" || currentSetting.type === "number" && typeof defaultValue === "number" || currentSetting.type === "string" && typeof defaultValue === "string") {
                setGlobalPendingChanges((prev) => {
                  const next = new Map(prev);
                  next.set(currentSetting.value, defaultValue);
                  return next;
                });
              }
            }
          }
        }
      }
      if (showRestartPrompt && name3 === "r") {
        const restartRequiredSettings = getRestartRequiredFromModified(modifiedSettings);
        const restartRequiredSet = new Set(restartRequiredSettings);
        if (restartRequiredSet.size > 0) {
          saveModifiedSettings(
            restartRequiredSet,
            pendingSettings,
            settings,
            selectedScope
          );
          setGlobalPendingChanges((prev) => {
            if (prev.size === 0) return prev;
            const next = new Map(prev);
            for (const key2 of restartRequiredSet) {
              next.delete(key2);
            }
            return next;
          });
        }
        setShowRestartPrompt(false);
        setRestartRequiredSettings(/* @__PURE__ */ new Set());
        if (onRestartRequest) onRestartRequest();
      }
      if (name3 === "escape") {
        if (editingKey) {
          commitEdit(editingKey);
        } else {
          onSelect(void 0, selectedScope);
        }
      }
    },
    { isActive: true }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "row",
      padding: 1,
      width: "100%",
      height: "100%",
      children: /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)(Box_default, { flexDirection: "column", flexGrow: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)(Text, { bold: focusSection === "settings", wrap: "truncate", children: [
          focusSection === "settings" ? "> " : "  ",
          "Settings"
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Box_default, { height: 1 }),
        showScrollUp && /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Text, { color: theme.text.secondary, children: "\u25B2" }),
        visibleItems.map((item, idx) => {
          const isActive = focusSection === "settings" && activeSettingIndex === idx + scrollOffset;
          const scopeSettings = settings.forScope(selectedScope).settings;
          const mergedSettings = settings.merged;
          let displayValue;
          if (editingKey === item.value) {
            if (cursorVisible && editCursorPos < cpLen(editBuffer)) {
              const beforeCursor = cpSlice(editBuffer, 0, editCursorPos);
              const atCursor = cpSlice(
                editBuffer,
                editCursorPos,
                editCursorPos + 1
              );
              const afterCursor = cpSlice(editBuffer, editCursorPos + 1);
              displayValue = beforeCursor + import_chalk6.default.inverse(atCursor) + afterCursor;
            } else if (cursorVisible && editCursorPos >= cpLen(editBuffer)) {
              displayValue = editBuffer + import_chalk6.default.inverse(" ");
            } else {
              displayValue = editBuffer;
            }
          } else if (item.type === "number" || item.type === "string") {
            const path108 = item.value.split(".");
            const currentValue = getNestedValue(pendingSettings, path108);
            const defaultValue = getDefaultValue(item.value);
            if (currentValue !== void 0 && currentValue !== null) {
              displayValue = String(currentValue);
            } else {
              displayValue = defaultValue !== void 0 && defaultValue !== null ? String(defaultValue) : "";
            }
            const isModified = modifiedSettings.has(item.value);
            const effectiveCurrentValue = currentValue !== void 0 && currentValue !== null ? currentValue : defaultValue;
            const isDifferentFromDefault = effectiveCurrentValue !== defaultValue;
            if (isDifferentFromDefault || isModified) {
              displayValue += "*";
            }
          } else {
            displayValue = getDisplayValue(
              item.value,
              scopeSettings,
              mergedSettings,
              modifiedSettings,
              pendingSettings
            );
          }
          const shouldBeGreyedOut = isDefaultValue(item.value, scopeSettings);
          const scopeMessage = getScopeMessageForSetting(
            item.value,
            selectedScope,
            settings
          );
          return /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)(import_react72.default.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)(Box_default, { flexDirection: "row", alignItems: "center", children: [
              /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Box_default, { minWidth: 2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
                Text,
                {
                  color: isActive ? theme.status.success : theme.text.secondary,
                  children: isActive ? "\u25CF" : ""
                }
              ) }),
              /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Box_default, { minWidth: 50, children: /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)(
                Text,
                {
                  color: isActive ? theme.status.success : theme.text.primary,
                  children: [
                    item.label,
                    scopeMessage && /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)(Text, { color: theme.text.secondary, children: [
                      " ",
                      scopeMessage
                    ] })
                  ]
                }
              ) }),
              /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Box_default, { minWidth: 3 }),
              /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
                Text,
                {
                  color: isActive ? theme.status.success : shouldBeGreyedOut ? theme.text.secondary : theme.text.primary,
                  children: displayValue
                }
              )
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Box_default, { height: 1 })
          ] }, item.value);
        }),
        showScrollDown && /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Text, { color: theme.text.secondary, children: "\u25BC" }),
        /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Box_default, { height: 1 }),
        showScopeSelection && /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
          ScopeSelector,
          {
            onSelect: handleScopeSelect,
            onHighlight: handleScopeHighlight,
            isFocused: focusSection === "scope",
            initialScope: selectedScope
          }
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)(Text, { color: theme.text.secondary, children: [
          "(Use Enter to select",
          showScopeSelection ? ", Tab to change focus" : "",
          ")"
        ] }),
        showRestartPrompt && /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Text, { color: theme.status.warning, children: "To see changes, Qwen Code must be restarted. Press r to exit and apply changes now." })
      ] })
    }
  );
}
__name(SettingsDialog, "SettingsDialog");

// packages/cli/src/ui/components/QwenOAuthProgress.tsx
init_esbuild_shims();
var import_react74 = __toESM(require_react(), 1);

// node_modules/ink-link/dist/index.js
init_esbuild_shims();
var import_react73 = __toESM(require_react(), 1);
var import_prop_types2 = __toESM(require_prop_types(), 1);

// node_modules/ink-link/node_modules/terminal-link/index.js
init_esbuild_shims();

// node_modules/ink-link/node_modules/ansi-escapes/index.js
init_esbuild_shims();
var ESC3 = "\x1B[";
var OSC2 = "\x1B]";
var BEL2 = "\x07";
var SEP2 = ";";
var isTerminalApp2 = process.env.TERM_PROGRAM === "Apple_Terminal";
var ansiEscapes = {};
ansiEscapes.cursorTo = (x, y) => {
  if (typeof x !== "number") {
    throw new TypeError("The `x` argument is required");
  }
  if (typeof y !== "number") {
    return ESC3 + (x + 1) + "G";
  }
  return ESC3 + (y + 1) + ";" + (x + 1) + "H";
};
ansiEscapes.cursorMove = (x, y) => {
  if (typeof x !== "number") {
    throw new TypeError("The `x` argument is required");
  }
  let returnValue = "";
  if (x < 0) {
    returnValue += ESC3 + -x + "D";
  } else if (x > 0) {
    returnValue += ESC3 + x + "C";
  }
  if (y < 0) {
    returnValue += ESC3 + -y + "A";
  } else if (y > 0) {
    returnValue += ESC3 + y + "B";
  }
  return returnValue;
};
ansiEscapes.cursorUp = (count = 1) => ESC3 + count + "A";
ansiEscapes.cursorDown = (count = 1) => ESC3 + count + "B";
ansiEscapes.cursorForward = (count = 1) => ESC3 + count + "C";
ansiEscapes.cursorBackward = (count = 1) => ESC3 + count + "D";
ansiEscapes.cursorLeft = ESC3 + "G";
ansiEscapes.cursorSavePosition = isTerminalApp2 ? "\x1B7" : ESC3 + "s";
ansiEscapes.cursorRestorePosition = isTerminalApp2 ? "\x1B8" : ESC3 + "u";
ansiEscapes.cursorGetPosition = ESC3 + "6n";
ansiEscapes.cursorNextLine = ESC3 + "E";
ansiEscapes.cursorPrevLine = ESC3 + "F";
ansiEscapes.cursorHide = ESC3 + "?25l";
ansiEscapes.cursorShow = ESC3 + "?25h";
ansiEscapes.eraseLines = (count) => {
  let clear = "";
  for (let i = 0; i < count; i++) {
    clear += ansiEscapes.eraseLine + (i < count - 1 ? ansiEscapes.cursorUp() : "");
  }
  if (count) {
    clear += ansiEscapes.cursorLeft;
  }
  return clear;
};
ansiEscapes.eraseEndLine = ESC3 + "K";
ansiEscapes.eraseStartLine = ESC3 + "1K";
ansiEscapes.eraseLine = ESC3 + "2K";
ansiEscapes.eraseDown = ESC3 + "J";
ansiEscapes.eraseUp = ESC3 + "1J";
ansiEscapes.eraseScreen = ESC3 + "2J";
ansiEscapes.scrollUp = ESC3 + "S";
ansiEscapes.scrollDown = ESC3 + "T";
ansiEscapes.clearScreen = "\x1Bc";
ansiEscapes.clearTerminal = process.platform === "win32" ? `${ansiEscapes.eraseScreen}${ESC3}0f` : (
  // 1. Erases the screen (Only done in case `2` is not supported)
  // 2. Erases the whole screen including scrollback buffer
  // 3. Moves cursor to the top-left position
  // More info: https://www.real-world-systems.com/docs/ANSIcode.html
  `${ansiEscapes.eraseScreen}${ESC3}3J${ESC3}H`
);
ansiEscapes.beep = BEL2;
ansiEscapes.link = (text, url2) => {
  return [
    OSC2,
    "8",
    SEP2,
    SEP2,
    url2,
    BEL2,
    text,
    OSC2,
    "8",
    SEP2,
    SEP2,
    BEL2
  ].join("");
};
ansiEscapes.image = (buffer, options2 = {}) => {
  let returnValue = `${OSC2}1337;File=inline=1`;
  if (options2.width) {
    returnValue += `;width=${options2.width}`;
  }
  if (options2.height) {
    returnValue += `;height=${options2.height}`;
  }
  if (options2.preserveAspectRatio === false) {
    returnValue += ";preserveAspectRatio=0";
  }
  return returnValue + ":" + buffer.toString("base64") + BEL2;
};
ansiEscapes.iTerm = {
  setCwd: /* @__PURE__ */ __name((cwd7 = process.cwd()) => `${OSC2}50;CurrentDir=${cwd7}${BEL2}`, "setCwd"),
  annotation: /* @__PURE__ */ __name((message, options2 = {}) => {
    let returnValue = `${OSC2}1337;`;
    const hasX = typeof options2.x !== "undefined";
    const hasY = typeof options2.y !== "undefined";
    if ((hasX || hasY) && !(hasX && hasY && typeof options2.length !== "undefined")) {
      throw new Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");
    }
    message = message.replace(/\|/g, "");
    returnValue += options2.isHidden ? "AddHiddenAnnotation=" : "AddAnnotation=";
    if (options2.length > 0) {
      returnValue += (hasX ? [message, options2.length, options2.x, options2.y] : [options2.length, message]).join("|");
    } else {
      returnValue += message;
    }
    return returnValue + BEL2;
  }, "annotation")
};
var ansi_escapes_default = ansiEscapes;

// node_modules/ink-link/node_modules/terminal-link/index.js
var import_supports_hyperlinks = __toESM(require_supports_hyperlinks(), 1);
function terminalLink(text, url2, { target = "stdout", ...options2 } = {}) {
  if (!import_supports_hyperlinks.default[target]) {
    if (options2.fallback === false) {
      return text;
    }
    return typeof options2.fallback === "function" ? options2.fallback(text, url2) : `${text} (\u200B${url2}\u200B)`;
  }
  return ansi_escapes_default.link(text, url2);
}
__name(terminalLink, "terminalLink");
terminalLink.isSupported = import_supports_hyperlinks.default.stdout;
terminalLink.stderr = (text, url2, options2 = {}) => terminalLink(text, url2, { target: "stderr", ...options2 });
terminalLink.stderr.isSupported = import_supports_hyperlinks.default.stderr;

// node_modules/ink-link/dist/index.js
var Link = /* @__PURE__ */ __name(({ children, url: url2, fallback = true }) => (
  // eslint-disable-line react/function-component-definition
  import_react73.default.createElement(
    Transform,
    { transform: /* @__PURE__ */ __name((children2) => terminalLink(children2, url2, { fallback }), "transform") },
    import_react73.default.createElement(Text, null, children)
  )
), "Link");
Link.propTypes = {
  children: import_prop_types2.default.oneOfType([
    import_prop_types2.default.arrayOf(import_prop_types2.default.node),
    import_prop_types2.default.node
  ]).isRequired,
  url: import_prop_types2.default.string.isRequired,
  fallback: import_prop_types2.default.bool
  // eslint-disable-line react/boolean-prop-naming
};
var dist_default5 = Link;

// packages/cli/src/ui/components/QwenOAuthProgress.tsx
var import_qrcode_terminal = __toESM(require_main2(), 1);
var import_jsx_runtime71 = __toESM(require_jsx_runtime(), 1);
function QrCodeDisplay({
  verificationUrl,
  qrCodeData
}) {
  if (!qrCodeData) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: Colors.AccentBlue,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { bold: true, color: Colors.AccentBlue, children: "Qwen OAuth Authentication" }),
        /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { children: "Please visit this URL to authorize:" }) }),
        /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(dist_default5, { url: verificationUrl, fallback: false, children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { color: Colors.AccentGreen, bold: true, children: verificationUrl }) }),
        /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { children: "Or scan the QR code below:" }) }),
        /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { children: qrCodeData }) })
      ]
    }
  );
}
__name(QrCodeDisplay, "QrCodeDisplay");
function StatusDisplay({
  timeRemaining,
  dots
}) {
  const formatTime = /* @__PURE__ */ __name((seconds) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;
  }, "formatTime");
  return /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: Colors.AccentBlue,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Text, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(build_default, { type: "dots" }),
          " Waiting for authorization",
          dots
        ] }) }),
        /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Box_default, { marginTop: 1, justifyContent: "space-between", children: [
          /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Text, { color: Colors.Gray, children: [
            "Time remaining: ",
            formatTime(timeRemaining)
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { color: Colors.AccentPurple, children: "(Press ESC or CTRL+C to cancel)" })
        ] })
      ]
    }
  );
}
__name(StatusDisplay, "StatusDisplay");
function QwenOAuthProgress({
  onTimeout,
  onCancel,
  deviceAuth,
  authStatus,
  authMessage
}) {
  const defaultTimeout = deviceAuth?.expires_in || 300;
  const [timeRemaining, setTimeRemaining] = (0, import_react74.useState)(defaultTimeout);
  const [dots, setDots] = (0, import_react74.useState)("");
  const [qrCodeData, setQrCodeData] = (0, import_react74.useState)(null);
  useKeypress(
    (key) => {
      if (authStatus === "timeout" || authStatus === "error") {
        onCancel();
      } else if (key.name === "escape" || key.ctrl && key.name === "c") {
        onCancel();
      }
    },
    { isActive: true }
  );
  (0, import_react74.useEffect)(() => {
    if (!deviceAuth?.verification_uri_complete) {
      return;
    }
    const generateQR = /* @__PURE__ */ __name(() => {
      try {
        import_qrcode_terminal.default.generate(
          deviceAuth.verification_uri_complete,
          { small: true },
          (qrcode2) => {
            setQrCodeData(qrcode2);
          }
        );
      } catch (error) {
        console.error("Failed to generate QR code:", error);
        setQrCodeData(null);
      }
    }, "generateQR");
    generateQR();
  }, [deviceAuth?.verification_uri_complete]);
  (0, import_react74.useEffect)(() => {
    const timer = setInterval(() => {
      setTimeRemaining((prev) => {
        if (prev <= 1) {
          onTimeout();
          return 0;
        }
        return prev - 1;
      });
    }, 1e3);
    return () => clearInterval(timer);
  }, [onTimeout]);
  (0, import_react74.useEffect)(() => {
    const dotsTimer = setInterval(() => {
      setDots((prev) => {
        if (prev.length >= 3) return "";
        return prev + ".";
      });
    }, 500);
    return () => clearInterval(dotsTimer);
  }, []);
  const qrCodeDisplay = (0, import_react74.useMemo)(() => {
    if (!deviceAuth?.verification_uri_complete) return null;
    return /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
      QrCodeDisplay,
      {
        verificationUrl: deviceAuth.verification_uri_complete,
        qrCodeData
      }
    );
  }, [deviceAuth?.verification_uri_complete, qrCodeData]);
  if (authStatus === "timeout") {
    return /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: Colors.AccentRed,
        flexDirection: "column",
        padding: 1,
        width: "100%",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { bold: true, color: Colors.AccentRed, children: "Qwen OAuth Authentication Timeout" }),
          /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { children: authMessage || `OAuth token expired (over ${defaultTimeout} seconds). Please select authentication method again.` }) }),
          /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { color: Colors.Gray, children: "Press any key to return to authentication type selection." }) })
        ]
      }
    );
  }
  if (authStatus === "error") {
    return /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: Colors.AccentRed,
        flexDirection: "column",
        padding: 1,
        width: "100%",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { bold: true, color: Colors.AccentRed, children: "Qwen OAuth Authentication Error" }),
          /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { children: authMessage || "An error occurred during authentication. Please try again." }) }),
          /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { color: Colors.Gray, children: "Press any key to return to authentication type selection." }) })
        ]
      }
    );
  }
  if (!deviceAuth) {
    return /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: Colors.Gray,
        flexDirection: "column",
        padding: 1,
        width: "100%",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Text, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(build_default, { type: "dots" }),
            " Waiting for Qwen OAuth authentication..."
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Box_default, { marginTop: 1, justifyContent: "space-between", children: [
            /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Text, { color: Colors.Gray, children: [
              "Time remaining: ",
              Math.floor(timeRemaining / 60),
              ":",
              (timeRemaining % 60).toString().padStart(2, "0")
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { color: Colors.AccentPurple, children: "(Press ESC or CTRL+C to cancel)" })
          ] })
        ]
      }
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Box_default, { flexDirection: "column", width: "100%", children: [
    qrCodeDisplay,
    /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(StatusDisplay, { timeRemaining, dots })
  ] });
}
__name(QwenOAuthProgress, "QwenOAuthProgress");

// packages/cli/src/ui/auth/AuthDialog.tsx
init_esbuild_shims();
var import_react77 = __toESM(require_react(), 1);

// packages/cli/src/ui/contexts/UIActionsContext.tsx
init_esbuild_shims();
var import_react76 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/ModelSwitchDialog.tsx
init_esbuild_shims();
var import_jsx_runtime72 = __toESM(require_jsx_runtime(), 1);
var ModelSwitchDialog = /* @__PURE__ */ __name(({
  onSelect
}) => {
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onSelect("persist" /* ContinueWithCurrentModel */);
      }
    },
    { isActive: true }
  );
  const options2 = [
    {
      key: "switch-once",
      label: "Switch for this request only",
      value: "once" /* SwitchOnce */
    },
    {
      key: "switch-session",
      label: "Switch session to vision model",
      value: "session" /* SwitchSessionToVL */
    },
    {
      key: "continue",
      label: "Continue with current model",
      value: "persist" /* ContinueWithCurrentModel */
    }
  ];
  const handleSelect = /* @__PURE__ */ __name((outcome) => {
    onSelect(outcome);
  }, "handleSelect");
  return /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: Colors.AccentYellow,
      padding: 1,
      width: "100%",
      marginLeft: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Text, { bold: true, children: "Vision Model Switch Required" }),
          /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Text, { children: "Your message contains an image, but the current model doesn't support vision." }),
          /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Text, { children: "How would you like to proceed?" })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(
          RadioButtonSelect,
          {
            items: options2,
            initialIndex: 0,
            onSelect: handleSelect,
            isFocused: true
          }
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Text, { color: Colors.Gray, children: "Press Enter to select, Esc to cancel" }) })
      ]
    }
  );
}, "ModelSwitchDialog");

// packages/cli/src/ui/components/OpenAIKeyPrompt.tsx
init_esbuild_shims();
var import_react75 = __toESM(require_react(), 1);
init_zod();
var import_jsx_runtime73 = __toESM(require_jsx_runtime(), 1);
var credentialSchema = external_exports.object({
  apiKey: external_exports.string().min(1, "API key is required"),
  baseUrl: external_exports.union([external_exports.string().url("Base URL must be a valid URL"), external_exports.literal("")]).optional(),
  model: external_exports.string().min(1, "Model must be a non-empty string").optional()
});
function OpenAIKeyPrompt({
  onSubmit,
  onCancel,
  defaultApiKey,
  defaultBaseUrl,
  defaultModel
}) {
  const [apiKey, setApiKey] = (0, import_react75.useState)(defaultApiKey || "");
  const [baseUrl, setBaseUrl] = (0, import_react75.useState)(defaultBaseUrl || "");
  const [model, setModel] = (0, import_react75.useState)(defaultModel || "");
  const [currentField, setCurrentField] = (0, import_react75.useState)("apiKey");
  const [validationError, setValidationError] = (0, import_react75.useState)(null);
  const validateAndSubmit = /* @__PURE__ */ __name(() => {
    setValidationError(null);
    try {
      const validated = credentialSchema.parse({
        apiKey: apiKey.trim(),
        baseUrl: baseUrl.trim() || void 0,
        model: model.trim() || void 0
      });
      onSubmit(
        validated.apiKey,
        validated.baseUrl === "" ? "" : validated.baseUrl || "",
        validated.model || ""
      );
    } catch (error) {
      if (error instanceof external_exports.ZodError) {
        const errorMessage = error.errors.map((e2) => `${e2.path.join(".")}: ${e2.message}`).join(", ");
        setValidationError(`Invalid credentials: ${errorMessage}`);
      } else {
        setValidationError("Failed to validate credentials");
      }
    }
  }, "validateAndSubmit");
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onCancel();
        return;
      }
      if (key.name === "return") {
        if (currentField === "apiKey") {
          setCurrentField("baseUrl");
          return;
        } else if (currentField === "baseUrl") {
          setCurrentField("model");
          return;
        } else if (currentField === "model") {
          if (apiKey.trim()) {
            validateAndSubmit();
          } else {
            setCurrentField("apiKey");
          }
        }
        return;
      }
      if (key.name === "tab") {
        if (currentField === "apiKey") {
          setCurrentField("baseUrl");
        } else if (currentField === "baseUrl") {
          setCurrentField("model");
        } else if (currentField === "model") {
          setCurrentField("apiKey");
        }
        return;
      }
      if (key.name === "up") {
        if (currentField === "baseUrl") {
          setCurrentField("apiKey");
        } else if (currentField === "model") {
          setCurrentField("baseUrl");
        }
        return;
      }
      if (key.name === "down") {
        if (currentField === "apiKey") {
          setCurrentField("baseUrl");
        } else if (currentField === "baseUrl") {
          setCurrentField("model");
        }
        return;
      }
      if (key.name === "backspace" || key.name === "delete") {
        if (currentField === "apiKey") {
          setApiKey((prev) => prev.slice(0, -1));
        } else if (currentField === "baseUrl") {
          setBaseUrl((prev) => prev.slice(0, -1));
        } else if (currentField === "model") {
          setModel((prev) => prev.slice(0, -1));
        }
        return;
      }
      if (key.paste && key.sequence) {
        let cleanInput = key.sequence.replace(/\u001b\[[0-9;]*[a-zA-Z]/g, "").replace(/\[200~/g, "").replace(/\[201~/g, "").replace(/^\[|~$/g, "");
        cleanInput = cleanInput.split("").filter((ch) => ch.charCodeAt(0) >= 32).join("");
        if (cleanInput.length > 0) {
          if (currentField === "apiKey") {
            setApiKey((prev) => prev + cleanInput);
          } else if (currentField === "baseUrl") {
            setBaseUrl((prev) => prev + cleanInput);
          } else if (currentField === "model") {
            setModel((prev) => prev + cleanInput);
          }
        }
        return;
      }
      if (key.sequence && !key.ctrl && !key.meta) {
        const cleanInput = key.sequence.split("").filter((ch) => ch.charCodeAt(0) >= 32).join("");
        if (cleanInput.length > 0) {
          if (currentField === "apiKey") {
            setApiKey((prev) => prev + cleanInput);
          } else if (currentField === "baseUrl") {
            setBaseUrl((prev) => prev + cleanInput);
          } else if (currentField === "model") {
            setModel((prev) => prev + cleanInput);
          }
        }
      }
    },
    { isActive: true }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime73.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: Colors.AccentBlue,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Text, { bold: true, color: Colors.AccentBlue, children: "OpenAI Configuration Required" }),
        validationError && /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Text, { color: Colors.AccentRed, children: validationError }) }),
        /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime73.jsxs)(Text, { children: [
          "Please enter your OpenAI configuration. You can get an API key from",
          " ",
          /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Text, { color: Colors.AccentBlue, children: "https://bailian.console.aliyun.com/?tab=model#/api-key" })
        ] }) }),
        /* @__PURE__ */ (0, import_jsx_runtime73.jsxs)(Box_default, { marginTop: 1, flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Box_default, { width: 12, children: /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(
            Text,
            {
              color: currentField === "apiKey" ? Colors.AccentBlue : Colors.Gray,
              children: "API Key:"
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime73.jsxs)(Text, { children: [
            currentField === "apiKey" ? "> " : "  ",
            apiKey || " "
          ] }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime73.jsxs)(Box_default, { marginTop: 1, flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Box_default, { width: 12, children: /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(
            Text,
            {
              color: currentField === "baseUrl" ? Colors.AccentBlue : Colors.Gray,
              children: "Base URL:"
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime73.jsxs)(Text, { children: [
            currentField === "baseUrl" ? "> " : "  ",
            baseUrl
          ] }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime73.jsxs)(Box_default, { marginTop: 1, flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Box_default, { width: 12, children: /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(
            Text,
            {
              color: currentField === "model" ? Colors.AccentBlue : Colors.Gray,
              children: "Model:"
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime73.jsxs)(Text, { children: [
            currentField === "model" ? "> " : "  ",
            model
          ] }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Text, { color: Colors.Gray, children: "Press Enter to continue, Tab/\u2191\u2193 to navigate, Esc to cancel" }) })
      ]
    }
  );
}
__name(OpenAIKeyPrompt, "OpenAIKeyPrompt");

// packages/cli/src/ui/contexts/UIActionsContext.tsx
var UIActionsContext = (0, import_react76.createContext)(null);
var useUIActions = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react76.useContext)(UIActionsContext);
  if (!context2) {
    throw new Error("useUIActions must be used within a UIActionsProvider");
  }
  return context2;
}, "useUIActions");

// packages/cli/src/ui/auth/AuthDialog.tsx
var import_jsx_runtime74 = __toESM(require_jsx_runtime(), 1);
function parseDefaultAuthType(defaultAuthType) {
  if (defaultAuthType && Object.values(AuthType2).includes(defaultAuthType)) {
    return defaultAuthType;
  }
  return null;
}
__name(parseDefaultAuthType, "parseDefaultAuthType");
function AuthDialog() {
  const { pendingAuthType, authError } = useUIState();
  const { handleAuthSelect: onAuthSelect } = useUIActions();
  const settings = useSettings();
  const [errorMessage, setErrorMessage] = (0, import_react77.useState)(null);
  const [selectedIndex, setSelectedIndex] = (0, import_react77.useState)(null);
  const items = [
    {
      key: AuthType2.QWEN_OAUTH,
      label: "Qwen OAuth",
      value: AuthType2.QWEN_OAUTH
    },
    { key: AuthType2.USE_OPENAI, label: "OpenAI", value: AuthType2.USE_OPENAI }
  ];
  const initialAuthIndex = Math.max(
    0,
    items.findIndex((item) => {
      if (pendingAuthType) {
        return item.value === pendingAuthType;
      }
      if (settings.merged.security?.auth?.selectedType) {
        return item.value === settings.merged.security?.auth?.selectedType;
      }
      const defaultAuthType = parseDefaultAuthType(
        process.env["QWEN_DEFAULT_AUTH_TYPE"]
      );
      if (defaultAuthType) {
        return item.value === defaultAuthType;
      }
      return item.value === AuthType2.QWEN_OAUTH;
    })
  );
  const hasApiKey = Boolean(settings.merged.security?.auth?.apiKey);
  const currentSelectedAuthType = selectedIndex !== null ? items[selectedIndex]?.value : items[initialAuthIndex]?.value;
  const handleAuthSelect = /* @__PURE__ */ __name(async (authMethod) => {
    setErrorMessage(null);
    await onAuthSelect(authMethod, "User" /* User */);
  }, "handleAuthSelect");
  const handleHighlight = /* @__PURE__ */ __name((authMethod) => {
    const index = items.findIndex((item) => item.value === authMethod);
    setSelectedIndex(index);
  }, "handleHighlight");
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        if (errorMessage) {
          return;
        }
        if (settings.merged.security?.auth?.selectedType === void 0) {
          setErrorMessage(
            "You must select an auth method to proceed. Press Ctrl+C again to exit."
          );
          return;
        }
        onAuthSelect(void 0, "User" /* User */);
      }
    },
    { isActive: true }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: Colors.Gray,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Text, { bold: true, children: "Get started" }),
        /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Text, { children: "How would you like to authenticate for this project?" }) }),
        /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(
          RadioButtonSelect,
          {
            items,
            initialIndex: initialAuthIndex,
            onSelect: handleAuthSelect,
            onHighlight: handleHighlight
          }
        ) }),
        (authError || errorMessage) && /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Text, { color: Colors.AccentRed, children: authError || errorMessage }) }),
        /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Text, { color: Colors.AccentPurple, children: "(Use Enter to Set Auth)" }) }),
        hasApiKey && currentSelectedAuthType === AuthType2.QWEN_OAUTH && /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Text, { color: Colors.Gray, children: "Note: Your existing API key in settings.json will not be cleared when using Qwen OAuth. You can switch back to OpenAI authentication later if needed." }) }),
        /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Text, { children: "Terms of Services and Privacy Notice for Qwen Code" }) }),
        /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Text, { color: Colors.AccentBlue, children: "https://github.com/QwenLM/Qwen3-Coder/blob/main/README.md" }) })
      ]
    }
  );
}
__name(AuthDialog, "AuthDialog");

// packages/cli/src/ui/components/EditorSettingsDialog.tsx
init_esbuild_shims();
var import_react78 = __toESM(require_react(), 1);

// packages/cli/src/ui/editors/editorSettingsManager.ts
init_esbuild_shims();
var EDITOR_DISPLAY_NAMES = {
  cursor: "Cursor",
  emacs: "Emacs",
  neovim: "Neovim",
  vim: "Vim",
  vscode: "VS Code",
  vscodium: "VSCodium",
  windsurf: "Windsurf",
  zed: "Zed",
  trae: "Trae"
};
var EditorSettingsManager = class {
  static {
    __name(this, "EditorSettingsManager");
  }
  availableEditors;
  constructor() {
    const editorTypes = Object.keys(
      EDITOR_DISPLAY_NAMES
    ).sort();
    this.availableEditors = [
      {
        name: "None",
        type: "not_set",
        disabled: false
      },
      ...editorTypes.map((type) => {
        const hasEditor = checkHasEditorType(type);
        const isAllowedInSandbox = allowEditorTypeInSandbox(type);
        let labelSuffix = !isAllowedInSandbox ? " (Not available in sandbox)" : "";
        labelSuffix = !hasEditor ? " (Not installed)" : labelSuffix;
        return {
          name: EDITOR_DISPLAY_NAMES[type] + labelSuffix,
          type,
          disabled: !hasEditor || !isAllowedInSandbox
        };
      })
    ];
  }
  getAvailableEditorDisplays() {
    return this.availableEditors;
  }
};
var editorSettingsManager = new EditorSettingsManager();

// packages/cli/src/ui/components/EditorSettingsDialog.tsx
var import_jsx_runtime75 = __toESM(require_jsx_runtime(), 1);
function EditorSettingsDialog({
  onSelect,
  settings,
  onExit
}) {
  const [selectedScope, setSelectedScope] = (0, import_react78.useState)(
    "User" /* User */
  );
  const [focusedSection, setFocusedSection] = (0, import_react78.useState)(
    "editor"
  );
  useKeypress(
    (key) => {
      if (key.name === "tab") {
        setFocusedSection((prev) => prev === "editor" ? "scope" : "editor");
      }
      if (key.name === "escape") {
        onExit();
      }
    },
    { isActive: true }
  );
  const editorItems = editorSettingsManager.getAvailableEditorDisplays();
  const currentPreference = settings.forScope(selectedScope).settings.general?.preferredEditor;
  let editorIndex = currentPreference ? editorItems.findIndex(
    (item) => item.type === currentPreference
  ) : 0;
  if (editorIndex === -1) {
    console.error(`Editor is not supported: ${currentPreference}`);
    editorIndex = 0;
  }
  const scopeItems = [
    {
      label: "User Settings",
      value: "User" /* User */,
      key: "User" /* User */
    },
    {
      label: "Workspace Settings",
      value: "Workspace" /* Workspace */,
      key: "Workspace" /* Workspace */
    }
  ];
  const handleEditorSelect = /* @__PURE__ */ __name((editorType) => {
    if (editorType === "not_set") {
      onSelect(void 0, selectedScope);
      return;
    }
    onSelect(editorType, selectedScope);
  }, "handleEditorSelect");
  const handleScopeSelect = /* @__PURE__ */ __name((scope) => {
    setSelectedScope(scope);
    setFocusedSection("editor");
  }, "handleScopeSelect");
  let otherScopeModifiedMessage = "";
  const otherScope = selectedScope === "User" /* User */ ? "Workspace" /* Workspace */ : "User" /* User */;
  if (settings.forScope(otherScope).settings.general?.preferredEditor !== void 0) {
    otherScopeModifiedMessage = settings.forScope(selectedScope).settings.general?.preferredEditor !== void 0 ? `(Also modified in ${otherScope})` : `(Modified in ${otherScope})`;
  }
  let mergedEditorName = "None";
  if (settings.merged.general?.preferredEditor && isEditorAvailable(settings.merged.general?.preferredEditor)) {
    mergedEditorName = EDITOR_DISPLAY_NAMES[settings.merged.general?.preferredEditor];
  }
  return /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "row",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(Box_default, { flexDirection: "column", width: "45%", paddingRight: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(Text, { bold: focusedSection === "editor", children: [
            focusedSection === "editor" ? "> " : "  ",
            "Select Editor",
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Text, { color: theme.text.secondary, children: otherScopeModifiedMessage })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
            RadioButtonSelect,
            {
              items: editorItems.map((item) => ({
                label: item.name,
                value: item.type,
                disabled: item.disabled,
                key: item.type
              })),
              initialIndex: editorIndex,
              onSelect: handleEditorSelect,
              isFocused: focusedSection === "editor"
            },
            selectedScope
          ),
          /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(Text, { bold: focusedSection === "scope", children: [
              focusedSection === "scope" ? "> " : "  ",
              "Apply To"
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
              RadioButtonSelect,
              {
                items: scopeItems,
                initialIndex: 0,
                onSelect: handleScopeSelect,
                isFocused: focusedSection === "scope"
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Text, { color: theme.text.secondary, children: "(Use Enter to select, Tab to change focus)" }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(Box_default, { flexDirection: "column", width: "55%", paddingLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Text, { bold: true, color: theme.text.primary, children: "Editor Preference" }),
          /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(Box_default, { flexDirection: "column", gap: 1, marginTop: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Text, { color: theme.text.secondary, children: "These editors are currently supported. Please note that some editors cannot be used in sandbox mode." }),
            /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(Text, { color: theme.text.secondary, children: [
              "Your preferred editor is:",
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
                Text,
                {
                  color: mergedEditorName === "None" ? theme.status.error : theme.text.link,
                  bold: true,
                  children: mergedEditorName
                }
              ),
              "."
            ] })
          ] })
        ] })
      ]
    }
  );
}
__name(EditorSettingsDialog, "EditorSettingsDialog");

// packages/cli/src/ui/components/WorkspaceMigrationDialog.tsx
init_esbuild_shims();
var import_react79 = __toESM(require_react(), 1);
var import_jsx_runtime76 = __toESM(require_jsx_runtime(), 1);
function WorkspaceMigrationDialog(props) {
  const { workspaceExtensions, onOpen, onClose } = props;
  const [migrationComplete, setMigrationComplete] = (0, import_react79.useState)(false);
  const [failedExtensions, setFailedExtensions] = (0, import_react79.useState)([]);
  onOpen();
  const onMigrate = /* @__PURE__ */ __name(async () => {
    const failed = await performWorkspaceExtensionMigration(
      workspaceExtensions,
      // We aren't updating extensions, just moving them around, don't need to ask for consent.
      async (_) => true
    );
    setFailedExtensions(failed);
    setMigrationComplete(true);
  }, "onMigrate");
  useKeypress(
    (key) => {
      if (migrationComplete && key.sequence === "q") {
        process.exit(0);
      }
    },
    { isActive: true }
  );
  if (migrationComplete) {
    return /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(
      Box_default,
      {
        flexDirection: "column",
        borderStyle: "round",
        borderColor: theme.border.default,
        padding: 1,
        children: failedExtensions.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(import_jsx_runtime76.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Text, { color: theme.text.primary, children: "The following extensions failed to migrate. Please try installing them manually. To see other changes, Qwen Code must be restarted. Press 'q' to quit." }),
          /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Box_default, { flexDirection: "column", marginTop: 1, marginLeft: 2, children: failedExtensions.map((failed) => /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(Text, { children: [
            "- ",
            failed
          ] }, failed)) })
        ] }) : /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Text, { color: theme.text.primary, children: "Migration complete. To see changes, Qwen Code must be restarted. Press 'q' to quit." })
      }
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.border.default,
      padding: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(Text, { bold: true, color: theme.text.primary, children: [
          "Workspace-level extensions are deprecated",
          "\n"
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Text, { color: theme.text.primary, children: "Would you like to install them at the user level?" }),
        /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Text, { color: theme.text.primary, children: "The extension definition will remain in your workspace directory." }),
        /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Text, { color: theme.text.primary, children: "If you opt to skip, you can install them manually using the extensions install command." }),
        /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Box_default, { flexDirection: "column", marginTop: 1, marginLeft: 2, children: workspaceExtensions.map((extension) => /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(Text, { children: [
          "- ",
          extension.config.name
        ] }, extension.config.name)) }),
        /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(
          RadioButtonSelect,
          {
            items: [
              { label: "Install all", value: "migrate", key: "migrate" },
              { label: "Skip", value: "skip", key: "skip" }
            ],
            onSelect: (value) => {
              if (value === "migrate") {
                onMigrate();
              } else {
                onClose();
              }
            }
          }
        ) })
      ]
    }
  );
}
__name(WorkspaceMigrationDialog, "WorkspaceMigrationDialog");

// packages/cli/src/ui/components/ProQuotaDialog.tsx
init_esbuild_shims();
var import_jsx_runtime77 = __toESM(require_jsx_runtime(), 1);
function ProQuotaDialog({
  failedModel,
  fallbackModel,
  onChoice
}) {
  const items = [
    {
      label: "Change auth (executes the /auth command)",
      value: "auth",
      key: "auth"
    },
    {
      label: `Continue with ${fallbackModel}`,
      value: "continue",
      key: "continue"
    }
  ];
  const handleSelect = /* @__PURE__ */ __name((choice2) => {
    onChoice(choice2);
  }, "handleSelect");
  return /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Box_default, { borderStyle: "round", flexDirection: "column", paddingX: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Text, { bold: true, color: theme.status.warning, children: [
      "Pro quota limit reached for ",
      failedModel,
      "."
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(
      RadioButtonSelect,
      {
        items,
        initialIndex: 1,
        onSelect: handleSelect
      }
    ) })
  ] });
}
__name(ProQuotaDialog, "ProQuotaDialog");

// packages/cli/src/ui/components/PermissionsModifyTrustDialog.tsx
init_esbuild_shims();

// packages/cli/src/ui/hooks/usePermissionsModifyTrust.ts
init_esbuild_shims();
var import_react80 = __toESM(require_react(), 1);
import * as process28 from "node:process";
function getInitialTrustState(settings, cwd7) {
  const folders = loadTrustedFolders();
  const explicitTrustLevel = folders.user.config[cwd7];
  const { isTrusted, source: source2 } = isWorkspaceTrusted(settings.merged);
  const isInheritedTrust = isTrusted && (!explicitTrustLevel || explicitTrustLevel === "DO_NOT_TRUST" /* DO_NOT_TRUST */);
  return {
    currentTrustLevel: explicitTrustLevel,
    isInheritedTrustFromParent: !!(source2 === "file" && isInheritedTrust),
    isInheritedTrustFromIde: !!(source2 === "ide" && isInheritedTrust)
  };
}
__name(getInitialTrustState, "getInitialTrustState");
var usePermissionsModifyTrust = /* @__PURE__ */ __name((onExit, addItem) => {
  const settings = useSettings();
  const cwd7 = process28.cwd();
  const [initialState2] = (0, import_react80.useState)(() => getInitialTrustState(settings, cwd7));
  const [currentTrustLevel] = (0, import_react80.useState)(
    initialState2.currentTrustLevel
  );
  const [pendingTrustLevel, setPendingTrustLevel] = (0, import_react80.useState)();
  const [isInheritedTrustFromParent] = (0, import_react80.useState)(
    initialState2.isInheritedTrustFromParent
  );
  const [isInheritedTrustFromIde] = (0, import_react80.useState)(
    initialState2.isInheritedTrustFromIde
  );
  const [needsRestart, setNeedsRestart] = (0, import_react80.useState)(false);
  const isFolderTrustEnabled2 = !!settings.merged.security?.folderTrust?.enabled;
  const updateTrustLevel = (0, import_react80.useCallback)(
    (trustLevel) => {
      const wasTrusted = isWorkspaceTrusted(settings.merged).isTrusted;
      const currentConfig = loadTrustedFolders().user.config;
      const newConfig = { ...currentConfig, [cwd7]: trustLevel };
      const { isTrusted, source: source2 } = isWorkspaceTrusted(
        settings.merged,
        newConfig
      );
      if (trustLevel === "DO_NOT_TRUST" /* DO_NOT_TRUST */ && isTrusted) {
        let message = "Note: This folder is still trusted because the connected IDE workspace is trusted.";
        if (source2 === "file") {
          message = "Note: This folder is still trusted because a parent folder is trusted.";
        }
        addItem(
          {
            type: "warning" /* WARNING */,
            text: message
          },
          Date.now()
        );
      }
      if (wasTrusted !== isTrusted) {
        setPendingTrustLevel(trustLevel);
        setNeedsRestart(true);
      } else {
        const folders = loadTrustedFolders();
        folders.setValue(cwd7, trustLevel);
        onExit();
      }
    },
    [cwd7, settings.merged, onExit, addItem]
  );
  const commitTrustLevelChange = (0, import_react80.useCallback)(() => {
    if (pendingTrustLevel) {
      const folders = loadTrustedFolders();
      folders.setValue(cwd7, pendingTrustLevel);
    }
  }, [cwd7, pendingTrustLevel]);
  return {
    cwd: cwd7,
    currentTrustLevel,
    isInheritedTrustFromParent,
    isInheritedTrustFromIde,
    needsRestart,
    updateTrustLevel,
    commitTrustLevelChange,
    isFolderTrustEnabled: isFolderTrustEnabled2
  };
}, "usePermissionsModifyTrust");

// packages/cli/src/ui/components/PermissionsModifyTrustDialog.tsx
var import_jsx_runtime78 = __toESM(require_jsx_runtime(), 1);
var TRUST_LEVEL_ITEMS = [
  {
    label: "Trust this folder",
    value: "TRUST_FOLDER" /* TRUST_FOLDER */,
    key: "TRUST_FOLDER" /* TRUST_FOLDER */
  },
  {
    label: "Trust parent folder",
    value: "TRUST_PARENT" /* TRUST_PARENT */,
    key: "TRUST_PARENT" /* TRUST_PARENT */
  },
  {
    label: "Don't trust",
    value: "DO_NOT_TRUST" /* DO_NOT_TRUST */,
    key: "DO_NOT_TRUST" /* DO_NOT_TRUST */
  }
];
function PermissionsModifyTrustDialog({
  onExit,
  addItem
}) {
  const {
    cwd: cwd7,
    currentTrustLevel,
    isInheritedTrustFromParent,
    isInheritedTrustFromIde,
    needsRestart,
    updateTrustLevel,
    commitTrustLevelChange
  } = usePermissionsModifyTrust(onExit, addItem);
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onExit();
      }
      if (needsRestart && key.name === "r") {
        commitTrustLevelChange();
        relaunchApp();
        onExit();
      }
    },
    { isActive: true }
  );
  const index = TRUST_LEVEL_ITEMS.findIndex(
    (item) => item.value === currentTrustLevel
  );
  const initialIndex = index === -1 ? 0 : index;
  return /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(import_jsx_runtime78.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        flexDirection: "column",
        padding: 1,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(Box_default, { flexDirection: "column", paddingBottom: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(Text, { bold: true, children: [
              "> ",
              "Modify Trust Level"
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Box_default, { marginTop: 1 }),
            /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(Text, { children: [
              "Folder: ",
              cwd7
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(Text, { children: [
              "Current Level: ",
              /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Text, { bold: true, children: currentTrustLevel || "Not Set" })
            ] }),
            isInheritedTrustFromParent && /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Text, { color: theme.text.secondary, children: "Note: This folder behaves as a trusted folder because one of the parent folders is trusted. It will remain trusted even if you set a different trust level here. To change this, you need to modify the trust setting in the parent folder." }),
            isInheritedTrustFromIde && /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Text, { color: theme.text.secondary, children: "Note: This folder behaves as a trusted folder because the connected IDE workspace is trusted. It will remain trusted even if you set a different trust level here." })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(
            RadioButtonSelect,
            {
              items: TRUST_LEVEL_ITEMS,
              onSelect: updateTrustLevel,
              isFocused: true,
              initialIndex
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Text, { color: theme.text.secondary, children: "(Use Enter to select)" }) })
        ]
      }
    ),
    needsRestart && /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Box_default, { marginLeft: 1, marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Text, { color: theme.status.warning, children: "To apply the trust changes, Gemini CLI must be restarted. Press 'r' to restart CLI now." }) })
  ] });
}
__name(PermissionsModifyTrustDialog, "PermissionsModifyTrustDialog");

// packages/cli/src/ui/components/ModelDialog.tsx
init_esbuild_shims();
var import_react81 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/shared/DescriptiveRadioButtonSelect.tsx
init_esbuild_shims();
var import_jsx_runtime79 = __toESM(require_jsx_runtime(), 1);
function DescriptiveRadioButtonSelect({
  items,
  initialIndex = 0,
  onSelect,
  onHighlight,
  isFocused = true,
  showNumbers = false,
  showScrollArrows = false,
  maxItemsToShow: maxItemsToShow2 = 10
}) {
  return /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
    BaseSelectionList,
    {
      items,
      initialIndex,
      onSelect,
      onHighlight,
      isFocused,
      showNumbers,
      showScrollArrows,
      maxItemsToShow: maxItemsToShow2,
      renderItem: (item, { titleColor }) => /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(Box_default, { flexDirection: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Text, { color: titleColor, children: item.title }),
        /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Text, { color: theme.text.secondary, children: item.description })
      ] }, item.key)
    }
  );
}
__name(DescriptiveRadioButtonSelect, "DescriptiveRadioButtonSelect");

// packages/cli/src/ui/models/availableModels.ts
init_esbuild_shims();
var MAINLINE_VLM = "vision-model";
var MAINLINE_CODER = DEFAULT_QWEN_MODEL;
var AVAILABLE_MODELS_QWEN = [
  {
    id: MAINLINE_CODER,
    label: MAINLINE_CODER,
    description: "The latest Qwen Coder model from Alibaba Cloud ModelStudio (version: qwen3-coder-plus-2025-09-23)"
  },
  {
    id: MAINLINE_VLM,
    label: MAINLINE_VLM,
    description: "The latest Qwen Vision model from Alibaba Cloud ModelStudio (version: qwen3-vl-plus-2025-09-23)",
    isVision: true
  }
];
function getOpenAIAvailableModelFromEnv() {
  const id = process.env["OPENAI_MODEL"]?.trim();
  return id ? { id, label: id } : null;
}
__name(getOpenAIAvailableModelFromEnv, "getOpenAIAvailableModelFromEnv");
function getAvailableModelsForAuthType(authType) {
  switch (authType) {
    case AuthType2.QWEN_OAUTH:
      return AVAILABLE_MODELS_QWEN;
    case AuthType2.USE_OPENAI: {
      const openAIModel = getOpenAIAvailableModelFromEnv();
      return openAIModel ? [openAIModel] : [];
    }
    default:
      return [];
  }
}
__name(getAvailableModelsForAuthType, "getAvailableModelsForAuthType");
function getDefaultVisionModel() {
  return MAINLINE_VLM;
}
__name(getDefaultVisionModel, "getDefaultVisionModel");
function isVisionModel(modelId) {
  return AVAILABLE_MODELS_QWEN.some(
    (model) => model.id === modelId && model.isVision
  );
}
__name(isVisionModel, "isVisionModel");

// packages/cli/src/ui/components/ModelDialog.tsx
var import_jsx_runtime80 = __toESM(require_jsx_runtime(), 1);
function ModelDialog({ onClose }) {
  const config = (0, import_react81.useContext)(ConfigContext);
  const authType = config?.getAuthType() ?? AuthType2.QWEN_OAUTH;
  const availableModels = (0, import_react81.useMemo)(
    () => getAvailableModelsForAuthType(authType),
    [authType]
  );
  const MODEL_OPTIONS = (0, import_react81.useMemo)(
    () => availableModels.map((model) => ({
      value: model.id,
      title: model.label,
      description: model.description || "",
      key: model.id
    })),
    [availableModels]
  );
  const preferredModel = config?.getModel() || MAINLINE_CODER;
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onClose();
      }
    },
    { isActive: true }
  );
  const initialIndex = (0, import_react81.useMemo)(
    () => MODEL_OPTIONS.findIndex((option2) => option2.value === preferredModel),
    [MODEL_OPTIONS, preferredModel]
  );
  const handleSelect = (0, import_react81.useCallback)(
    (model) => {
      if (config) {
        config.setModel(model);
        const event = new ModelSlashCommandEvent(model);
        logModelSlashCommand(config, event);
      }
      onClose();
    },
    [config, onClose]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Text, { bold: true, children: "Select Model" }),
        /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(
          DescriptiveRadioButtonSelect,
          {
            items: MODEL_OPTIONS,
            onSelect: handleSelect,
            initialIndex,
            showNumbers: true
          }
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Text, { color: theme.text.secondary, children: "(Press Esc to close)" }) })
      ]
    }
  );
}
__name(ModelDialog, "ModelDialog");

// packages/cli/src/ui/components/ApprovalModeDialog.tsx
init_esbuild_shims();
var import_react82 = __toESM(require_react(), 1);
var import_jsx_runtime81 = __toESM(require_jsx_runtime(), 1);
var formatModeDescription = /* @__PURE__ */ __name((mode) => {
  switch (mode) {
    case ApprovalMode.PLAN:
      return "Analyze only, do not modify files or execute commands";
    case ApprovalMode.DEFAULT:
      return "Require approval for file edits or shell commands";
    case ApprovalMode.AUTO_EDIT:
      return "Automatically approve file edits";
    case ApprovalMode.YOLO:
      return "Automatically approve all tools";
    default:
      return `${mode} mode`;
  }
}, "formatModeDescription");
function ApprovalModeDialog({
  onSelect,
  settings,
  currentMode,
  availableTerminalHeight: _availableTerminalHeight
}) {
  const [selectedScope, setSelectedScope] = (0, import_react82.useState)(
    "User" /* User */
  );
  const [highlightedMode, setHighlightedMode] = (0, import_react82.useState)(
    currentMode || ApprovalMode.DEFAULT
  );
  const modeItems = APPROVAL_MODES.map((mode) => ({
    label: `${mode} - ${formatModeDescription(mode)}`,
    value: mode,
    key: mode
  }));
  const initialModeIndex = modeItems.findIndex(
    (item) => item.value === highlightedMode
  );
  const safeInitialModeIndex = initialModeIndex >= 0 ? initialModeIndex : 0;
  const handleModeSelect = (0, import_react82.useCallback)(
    (mode) => {
      onSelect(mode, selectedScope);
    },
    [onSelect, selectedScope]
  );
  const handleModeHighlight = /* @__PURE__ */ __name((mode) => {
    setHighlightedMode(mode);
  }, "handleModeHighlight");
  const handleScopeHighlight = (0, import_react82.useCallback)((scope) => {
    setSelectedScope(scope);
  }, []);
  const handleScopeSelect = (0, import_react82.useCallback)(
    (scope) => {
      onSelect(highlightedMode, scope);
    },
    [onSelect, highlightedMode]
  );
  const [focusSection, setFocusSection] = (0, import_react82.useState)("mode");
  useKeypress(
    (key) => {
      if (key.name === "tab") {
        setFocusSection((prev) => prev === "mode" ? "scope" : "mode");
      }
      if (key.name === "escape") {
        onSelect(void 0, selectedScope);
      }
    },
    { isActive: true }
  );
  const otherScopeModifiedMessage = getScopeMessageForSetting(
    "tools.approvalMode",
    selectedScope,
    settings
  );
  const showWorkspacePriorityWarning = selectedScope === "User" /* User */ && otherScopeModifiedMessage.toLowerCase().includes("workspace");
  return /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "row",
      padding: 1,
      width: "100%",
      height: "100%",
      children: /* @__PURE__ */ (0, import_jsx_runtime81.jsxs)(Box_default, { flexDirection: "column", flexGrow: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime81.jsxs)(Text, { bold: focusSection === "mode", wrap: "truncate", children: [
          focusSection === "mode" ? "> " : "  ",
          "Approval Mode",
          " ",
          /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text, { color: theme.text.secondary, children: otherScopeModifiedMessage })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(
          RadioButtonSelect,
          {
            items: modeItems,
            initialIndex: safeInitialModeIndex,
            onSelect: handleModeSelect,
            onHighlight: handleModeHighlight,
            isFocused: focusSection === "mode",
            maxItemsToShow: 10,
            showScrollArrows: false,
            showNumbers: focusSection === "mode"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(
          ScopeSelector,
          {
            onSelect: handleScopeSelect,
            onHighlight: handleScopeHighlight,
            isFocused: focusSection === "scope",
            initialScope: selectedScope
          }
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Box_default, { height: 1 }),
        showWorkspacePriorityWarning && /* @__PURE__ */ (0, import_jsx_runtime81.jsxs)(import_jsx_runtime81.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text, { color: theme.status.warning, wrap: "wrap", children: "\u26A0 Workspace approval mode exists and takes priority. User-level change will have no effect." }),
          /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Box_default, { height: 1 })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text, { color: theme.text.secondary, children: "(Use Enter to select, Tab to change focus)" })
      ] })
    }
  );
}
__name(ApprovalModeDialog, "ApprovalModeDialog");

// packages/cli/src/ui/components/DialogManager.tsx
import process29 from "node:process";

// packages/cli/src/ui/components/IdeTrustChangeDialog.tsx
init_esbuild_shims();
var import_jsx_runtime82 = __toESM(require_jsx_runtime(), 1);
var IdeTrustChangeDialog = /* @__PURE__ */ __name(({ reason }) => {
  useKeypress(
    (key) => {
      if (key.name === "r" || key.name === "R") {
        relaunchApp();
      }
    },
    { isActive: true }
  );
  let message = "Workspace trust has changed.";
  if (reason === "NONE") {
    console.error(
      'IdeTrustChangeDialog rendered with unexpected reason "NONE"'
    );
  } else if (reason === "CONNECTION_CHANGE") {
    message = "Workspace trust has changed due to a change in the IDE connection.";
  } else if (reason === "TRUST_CHANGE") {
    message = "Workspace trust has changed due to a change in the IDE trust.";
  }
  return /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { borderStyle: "round", borderColor: theme.status.warning, paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(Text, { color: theme.status.warning, children: [
    message,
    " Press 'r' to restart Gemini to apply the changes."
  ] }) });
}, "IdeTrustChangeDialog");

// packages/cli/src/ui/components/WelcomeBackDialog.tsx
init_esbuild_shims();
var import_jsx_runtime83 = __toESM(require_jsx_runtime(), 1);
function WelcomeBackDialog({
  welcomeBackInfo,
  onSelect,
  onClose
}) {
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onClose();
      }
    },
    { isActive: true }
  );
  const options2 = [
    {
      key: "restart",
      label: "Start new chat session",
      value: "restart"
    },
    {
      key: "continue",
      label: "Continue previous conversation",
      value: "continue"
    }
  ];
  const {
    timeAgo,
    goalContent,
    totalTasks = 0,
    doneCount = 0,
    inProgressCount = 0,
    pendingTasks = []
  } = welcomeBackInfo;
  return /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: Colors.AccentBlue,
      padding: 1,
      width: "100%",
      marginLeft: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Box_default, { flexDirection: "column", marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(Text, { color: Colors.AccentBlue, bold: true, children: [
          "\u{1F44B} Welcome back! (Last updated: ",
          timeAgo,
          ")"
        ] }) }),
        goalContent && /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Text, { color: Colors.Foreground, bold: true, children: "\u{1F3AF} Overall Goal:" }),
          /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Box_default, { marginTop: 1, paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Text, { color: Colors.Gray, children: goalContent }) })
        ] }),
        totalTasks > 0 && /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Text, { color: Colors.Foreground, bold: true, children: "\u{1F4CB} Current Plan:" }),
          /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Box_default, { marginTop: 1, paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(Text, { color: Colors.Gray, children: [
            "Progress: ",
            doneCount,
            "/",
            totalTasks,
            " tasks completed",
            inProgressCount > 0 && `, ${inProgressCount} in progress`
          ] }) }),
          pendingTasks.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, paddingLeft: 2, children: [
            /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Text, { color: Colors.Foreground, bold: true, children: "Pending Tasks:" }),
            pendingTasks.map((task, index) => /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(Text, { color: Colors.Gray, children: [
              "\u2022 ",
              task
            ] }, index))
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Text, { bold: true, children: "What would you like to do?" }),
          /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Text, { children: "Choose how to proceed with your session:" })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(RadioButtonSelect, { items: options2, onSelect, isFocused: true }) })
      ]
    }
  );
}
__name(WelcomeBackDialog, "WelcomeBackDialog");

// packages/cli/src/ui/components/QuitConfirmationDialog.tsx
init_esbuild_shims();
var import_jsx_runtime84 = __toESM(require_jsx_runtime(), 1);
var QuitConfirmationDialog = /* @__PURE__ */ __name(({
  onSelect
}) => {
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onSelect("cancel" /* CANCEL */);
      }
    },
    { isActive: true }
  );
  const options2 = [
    {
      key: "quit",
      label: "Quit immediately (/quit)",
      value: "quit" /* QUIT */
    },
    {
      key: "summary-and-quit",
      label: "Generate summary and quit (/summary)",
      value: "summary_and_quit" /* SUMMARY_AND_QUIT */
    },
    {
      key: "save-and-quit",
      label: "Save conversation and quit (/chat save)",
      value: "save_and_quit" /* SAVE_AND_QUIT */
    },
    {
      key: "cancel",
      label: "Cancel (stay in application)",
      value: "cancel" /* CANCEL */
    }
  ];
  return /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: Colors.AccentYellow,
      padding: 1,
      width: "100%",
      marginLeft: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Box_default, { flexDirection: "column", marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text, { children: "What would you like to do before exiting?" }) }),
        /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(RadioButtonSelect, { items: options2, onSelect, isFocused: true })
      ]
    }
  );
}, "QuitConfirmationDialog");

// packages/cli/src/ui/components/DialogManager.tsx
var import_jsx_runtime85 = __toESM(require_jsx_runtime(), 1);
var DialogManager = /* @__PURE__ */ __name(({
  addItem,
  terminalWidth
}) => {
  const config = useConfig();
  const settings = useSettings();
  const uiState = useUIState();
  const uiActions = useUIActions();
  const { constrainHeight, terminalHeight, staticExtraHeight, mainAreaWidth } = uiState;
  const getDefaultOpenAIConfig = /* @__PURE__ */ __name(() => {
    const fromSettings = settings.merged.security?.auth;
    const modelSettings = settings.merged.model;
    return {
      apiKey: fromSettings?.apiKey || process29.env["OPENAI_API_KEY"] || "",
      baseUrl: fromSettings?.baseUrl || process29.env["OPENAI_BASE_URL"] || "",
      model: modelSettings?.name || process29.env["OPENAI_MODEL"] || ""
    };
  }, "getDefaultOpenAIConfig");
  if (uiState.showWelcomeBackDialog && uiState.welcomeBackInfo?.hasHistory) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      WelcomeBackDialog,
      {
        welcomeBackInfo: uiState.welcomeBackInfo,
        onSelect: uiActions.handleWelcomeBackSelection,
        onClose: uiActions.handleWelcomeBackClose
      }
    );
  }
  if (uiState.showIdeRestartPrompt) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(IdeTrustChangeDialog, { reason: uiState.ideTrustRestartReason });
  }
  if (uiState.showWorkspaceMigrationDialog) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      WorkspaceMigrationDialog,
      {
        workspaceExtensions: uiState.workspaceExtensions,
        onOpen: uiActions.onWorkspaceMigrationDialogOpen,
        onClose: uiActions.onWorkspaceMigrationDialogClose
      }
    );
  }
  if (uiState.proQuotaRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      ProQuotaDialog,
      {
        failedModel: uiState.proQuotaRequest.failedModel,
        fallbackModel: uiState.proQuotaRequest.fallbackModel,
        onChoice: uiActions.handleProQuotaChoice
      }
    );
  }
  if (uiState.shouldShowIdePrompt) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      IdeIntegrationNudge,
      {
        ide: uiState.currentIDE,
        onComplete: uiActions.handleIdePromptComplete
      }
    );
  }
  if (uiState.isFolderTrustDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      FolderTrustDialog,
      {
        onSelect: uiActions.handleFolderTrustSelect,
        isRestarting: uiState.isRestarting
      }
    );
  }
  if (uiState.shellConfirmationRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(ShellConfirmationDialog, { request: uiState.shellConfirmationRequest });
  }
  if (uiState.loopDetectionConfirmationRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      LoopDetectionConfirmation,
      {
        onComplete: uiState.loopDetectionConfirmationRequest.onComplete
      }
    );
  }
  if (uiState.quitConfirmationRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      QuitConfirmationDialog,
      {
        onSelect: (choice2) => {
          if (choice2 === "cancel" /* CANCEL */) {
            uiState.quitConfirmationRequest?.onConfirm(false, "cancel");
          } else if (choice2 === "quit" /* QUIT */) {
            uiState.quitConfirmationRequest?.onConfirm(true, "quit");
          } else if (choice2 === "save_and_quit" /* SAVE_AND_QUIT */) {
            uiState.quitConfirmationRequest?.onConfirm(true, "save_and_quit");
          } else if (choice2 === "summary_and_quit" /* SUMMARY_AND_QUIT */) {
            uiState.quitConfirmationRequest?.onConfirm(
              true,
              "summary_and_quit"
            );
          }
        }
      }
    );
  }
  if (uiState.confirmationRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      ConsentPrompt,
      {
        prompt: uiState.confirmationRequest.prompt,
        onConfirm: uiState.confirmationRequest.onConfirm,
        terminalWidth
      }
    );
  }
  if (uiState.confirmUpdateExtensionRequests.length > 0) {
    const request4 = uiState.confirmUpdateExtensionRequests[0];
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      ConsentPrompt,
      {
        prompt: request4.prompt,
        onConfirm: request4.onConfirm,
        terminalWidth
      }
    );
  }
  if (uiState.isThemeDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Box_default, { flexDirection: "column", children: [
      uiState.themeError && /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text, { color: theme.status.error, children: uiState.themeError }) }),
      /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
        ThemeDialog,
        {
          onSelect: uiActions.handleThemeSelect,
          onHighlight: uiActions.handleThemeHighlight,
          settings,
          availableTerminalHeight: constrainHeight ? terminalHeight - staticExtraHeight : void 0,
          terminalWidth: mainAreaWidth
        }
      )
    ] });
  }
  if (uiState.isSettingsDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      SettingsDialog,
      {
        settings,
        onSelect: () => uiActions.closeSettingsDialog(),
        onRestartRequest: () => process29.exit(0),
        availableTerminalHeight: terminalHeight - staticExtraHeight,
        config
      }
    ) });
  }
  if (uiState.isApprovalModeDialogOpen) {
    const currentMode = config.getApprovalMode();
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      ApprovalModeDialog,
      {
        settings,
        currentMode,
        onSelect: uiActions.handleApprovalModeSelect,
        availableTerminalHeight: constrainHeight ? terminalHeight - staticExtraHeight : void 0
      }
    ) });
  }
  if (uiState.isModelDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(ModelDialog, { onClose: uiActions.closeModelDialog });
  }
  if (uiState.isVisionSwitchDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(ModelSwitchDialog, { onSelect: uiActions.handleVisionSwitchSelect });
  }
  if (uiState.isAuthDialogOpen || uiState.authError) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(AuthDialog, {}) });
  }
  if (uiState.isAuthenticating) {
    if (uiState.pendingAuthType === AuthType2.USE_OPENAI) {
      const defaults3 = getDefaultOpenAIConfig();
      return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
        OpenAIKeyPrompt,
        {
          onSubmit: (apiKey, baseUrl, model) => {
            uiActions.handleAuthSelect(AuthType2.USE_OPENAI, "User" /* User */, {
              apiKey,
              baseUrl,
              model
            });
          },
          onCancel: () => {
            uiActions.cancelAuthentication();
            uiActions.setAuthState("updating" /* Updating */);
          },
          defaultApiKey: defaults3.apiKey,
          defaultBaseUrl: defaults3.baseUrl,
          defaultModel: defaults3.model
        }
      );
    }
    if (uiState.pendingAuthType === AuthType2.QWEN_OAUTH) {
      return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
        QwenOAuthProgress,
        {
          deviceAuth: uiState.qwenAuthState.deviceAuth || void 0,
          authStatus: uiState.qwenAuthState.authStatus,
          authMessage: uiState.qwenAuthState.authMessage,
          onTimeout: () => {
            uiActions.onAuthError("Qwen OAuth authentication timed out.");
            uiActions.cancelAuthentication();
            uiActions.setAuthState("updating" /* Updating */);
          },
          onCancel: () => {
            uiActions.cancelAuthentication();
            uiActions.setAuthState("updating" /* Updating */);
          }
        }
      );
    }
  }
  if (uiState.isEditorDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Box_default, { flexDirection: "column", children: [
      uiState.editorError && /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text, { color: theme.status.error, children: uiState.editorError }) }),
      /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
        EditorSettingsDialog,
        {
          onSelect: uiActions.handleEditorSelect,
          settings,
          onExit: uiActions.exitEditorDialog
        }
      )
    ] });
  }
  if (uiState.isPermissionsDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      PermissionsModifyTrustDialog,
      {
        onExit: uiActions.closePermissionsDialog,
        addItem
      }
    );
  }
  if (uiState.isSubagentCreateDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      AgentCreationWizard,
      {
        onClose: uiActions.closeSubagentCreateDialog,
        config
      }
    );
  }
  if (uiState.isAgentsManagerDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      AgentsManagerDialog,
      {
        onClose: uiActions.closeAgentsManagerDialog,
        config
      }
    );
  }
  return null;
}, "DialogManager");

// packages/cli/src/ui/components/Composer.tsx
init_esbuild_shims();
var import_react96 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/LoadingIndicator.tsx
init_esbuild_shims();

// packages/cli/src/ui/utils/isNarrowWidth.ts
init_esbuild_shims();
function isNarrowWidth(width) {
  return width < 80;
}
__name(isNarrowWidth, "isNarrowWidth");

// packages/cli/src/ui/components/LoadingIndicator.tsx
var import_jsx_runtime86 = __toESM(require_jsx_runtime(), 1);
var LoadingIndicator = /* @__PURE__ */ __name(({
  currentLoadingPhrase,
  elapsedTime,
  rightContent,
  thought
}) => {
  const streamingState = useStreamingContext();
  const { columns: terminalWidth } = useTerminalSize();
  const isNarrow = isNarrowWidth(terminalWidth);
  if (streamingState === "idle" /* Idle */) {
    return null;
  }
  const primaryText = thought?.subject || currentLoadingPhrase;
  const cancelAndTimerContent = streamingState !== "waiting_for_confirmation" /* WaitingForConfirmation */ ? `(esc to cancel, ${elapsedTime < 60 ? `${elapsedTime}s` : formatDuration(elapsedTime * 1e3)})` : null;
  return /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Box_default, { paddingLeft: 0, flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(
      Box_default,
      {
        width: "100%",
        flexDirection: isNarrow ? "column" : "row",
        alignItems: isNarrow ? "flex-start" : "center",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Box_default, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Box_default, { marginRight: 1, children: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
              GeminiRespondingSpinner,
              {
                nonRespondingDisplay: streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */ ? "\u280F" : ""
              }
            ) }),
            primaryText && /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text, { color: theme.text.accent, wrap: "truncate-end", children: primaryText }),
            !isNarrow && cancelAndTimerContent && /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Text, { color: theme.text.secondary, children: [
              " ",
              cancelAndTimerContent
            ] })
          ] }),
          !isNarrow && /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Box_default, { flexGrow: 1 }),
          !isNarrow && rightContent && /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Box_default, { children: rightContent })
        ]
      }
    ),
    isNarrow && cancelAndTimerContent && /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text, { color: theme.text.secondary, children: cancelAndTimerContent }) }),
    isNarrow && rightContent && /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Box_default, { children: rightContent })
  ] });
}, "LoadingIndicator");

// packages/cli/src/ui/components/ContextSummaryDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime87 = __toESM(require_jsx_runtime(), 1);
var ContextSummaryDisplay = /* @__PURE__ */ __name(({
  geminiMdFileCount,
  contextFileNames,
  mcpServers,
  blockedMcpServers,
  showToolDescriptions,
  ideContext
}) => {
  const { columns: terminalWidth } = useTerminalSize();
  const isNarrow = isNarrowWidth(terminalWidth);
  const mcpServerCount = Object.keys(mcpServers || {}).length;
  const blockedMcpServerCount = blockedMcpServers?.length || 0;
  const openFileCount = ideContext?.workspaceState?.openFiles?.length ?? 0;
  if (geminiMdFileCount === 0 && mcpServerCount === 0 && blockedMcpServerCount === 0 && openFileCount === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text, { children: " " });
  }
  const openFilesText = (() => {
    if (openFileCount === 0) {
      return "";
    }
    return `${openFileCount} open file${openFileCount > 1 ? "s" : ""} (ctrl+g to view)`;
  })();
  const geminiMdText = (() => {
    if (geminiMdFileCount === 0) {
      return "";
    }
    const allNamesTheSame = new Set(contextFileNames).size < 2;
    const name3 = allNamesTheSame ? contextFileNames[0] : "context";
    return `${geminiMdFileCount} ${name3} file${geminiMdFileCount > 1 ? "s" : ""}`;
  })();
  const mcpText = (() => {
    if (mcpServerCount === 0 && blockedMcpServerCount === 0) {
      return "";
    }
    const parts = [];
    if (mcpServerCount > 0) {
      parts.push(
        `${mcpServerCount} MCP server${mcpServerCount > 1 ? "s" : ""}`
      );
    }
    if (blockedMcpServerCount > 0) {
      let blockedText = `${blockedMcpServerCount} Blocked`;
      if (mcpServerCount === 0) {
        blockedText += ` MCP server${blockedMcpServerCount > 1 ? "s" : ""}`;
      }
      parts.push(blockedText);
    }
    let text = parts.join(", ");
    if (mcpServers && Object.keys(mcpServers).length > 0) {
      if (showToolDescriptions) {
        text += " (ctrl+t to toggle)";
      } else {
        text += " (ctrl+t to view)";
      }
    }
    return text;
  })();
  const summaryParts = [openFilesText, geminiMdText, mcpText].filter(Boolean);
  if (isNarrow) {
    return /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text, { color: theme.text.secondary, children: "Using:" }),
      summaryParts.map((part, index) => /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)(Text, { color: theme.text.secondary, children: [
        "  ",
        "- ",
        part
      ] }, index))
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)(Text, { color: theme.text.secondary, children: [
    "Using: ",
    summaryParts.join(" | ")
  ] }) });
}, "ContextSummaryDisplay");

// packages/cli/src/ui/components/AutoAcceptIndicator.tsx
init_esbuild_shims();
var import_jsx_runtime88 = __toESM(require_jsx_runtime(), 1);
var AutoAcceptIndicator = /* @__PURE__ */ __name(({
  approvalMode
}) => {
  let textColor = "";
  let textContent2 = "";
  let subText = "";
  switch (approvalMode) {
    case ApprovalMode.PLAN:
      textColor = theme.status.success;
      textContent2 = "plan mode";
      subText = " (shift + tab to cycle)";
      break;
    case ApprovalMode.AUTO_EDIT:
      textColor = theme.status.warning;
      textContent2 = "auto-accept edits";
      subText = " (shift + tab to cycle)";
      break;
    case ApprovalMode.YOLO:
      textColor = theme.status.error;
      textContent2 = "YOLO mode";
      subText = " (shift + tab to cycle)";
      break;
    case ApprovalMode.DEFAULT:
    default:
      break;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Text, { color: textColor, children: [
    textContent2,
    subText && /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text, { color: theme.text.secondary, children: subText })
  ] }) });
}, "AutoAcceptIndicator");

// packages/cli/src/ui/components/ShellModeIndicator.tsx
init_esbuild_shims();
var import_jsx_runtime89 = __toESM(require_jsx_runtime(), 1);
var ShellModeIndicator = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Text, { color: theme.ui.symbol, children: [
  "shell mode enabled",
  /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text, { color: theme.text.secondary, children: " (esc to disable)" })
] }) }), "ShellModeIndicator");

// packages/cli/src/ui/components/DetailedMessagesDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime90 = __toESM(require_jsx_runtime(), 1);
var DetailedMessagesDisplay = /* @__PURE__ */ __name(({ messages, maxHeight, width }) => {
  if (messages.length === 0) {
    return null;
  }
  const borderAndPadding = 4;
  return /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      marginTop: 1,
      borderStyle: "round",
      borderColor: theme.border.default,
      paddingX: 1,
      width,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Text, { bold: true, color: theme.text.primary, children: [
          "Debug Console",
          " ",
          /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text, { color: theme.text.secondary, children: "(ctrl+o to close)" })
        ] }) }),
        /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(MaxSizedBox, { maxHeight, maxWidth: width - borderAndPadding, children: messages.map((msg, index) => {
          let textColor = theme.text.primary;
          let icon = "\u2139";
          switch (msg.type) {
            case "warn":
              textColor = theme.status.warning;
              icon = "\u26A0";
              break;
            case "error":
              textColor = theme.status.error;
              icon = "\u2716";
              break;
            case "debug":
              textColor = theme.text.secondary;
              icon = "\u{1F50D}";
              break;
            case "log":
            default:
              break;
          }
          return /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Box_default, { flexDirection: "row", children: [
            /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Text, { color: textColor, children: [
              icon,
              " "
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Text, { color: textColor, wrap: "wrap", children: [
              msg.content,
              msg.count && msg.count > 1 && /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Text, { color: theme.text.secondary, children: [
                " (x",
                msg.count,
                ")"
              ] })
            ] })
          ] }, index);
        }) })
      ]
    }
  );
}, "DetailedMessagesDisplay");

// packages/cli/src/ui/components/InputPrompt.tsx
init_esbuild_shims();
var import_react92 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/SuggestionsDisplay.tsx
init_esbuild_shims();

// packages/cli/src/ui/components/PrepareLabel.tsx
init_esbuild_shims();
var import_react83 = __toESM(require_react(), 1);
var import_jsx_runtime91 = __toESM(require_jsx_runtime(), 1);
var MAX_WIDTH = 150;
var _PrepareLabel = /* @__PURE__ */ __name(({
  label,
  matchedIndex,
  userInput,
  textColor,
  isExpanded = false
}) => {
  const hasMatch = matchedIndex !== void 0 && matchedIndex >= 0 && matchedIndex < label.length && userInput.length > 0;
  if (!hasMatch) {
    const display = isExpanded ? label : label.length > MAX_WIDTH ? label.slice(0, MAX_WIDTH) + "..." : label;
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Text, { wrap: "wrap", color: textColor, children: display });
  }
  const matchLength = userInput.length;
  let before = "";
  let match2 = "";
  let after = "";
  if (isExpanded || label.length <= MAX_WIDTH) {
    before = label.slice(0, matchedIndex);
    match2 = label.slice(matchedIndex, matchedIndex + matchLength);
    after = label.slice(matchedIndex + matchLength);
  } else if (matchLength >= MAX_WIDTH) {
    match2 = label.slice(matchedIndex, matchedIndex + MAX_WIDTH - 1) + "...";
  } else {
    const contextSpace = MAX_WIDTH - matchLength;
    const beforeSpace = Math.floor(contextSpace / 2);
    const afterSpace = Math.ceil(contextSpace / 2);
    let start = matchedIndex - beforeSpace;
    let end = matchedIndex + matchLength + afterSpace;
    if (start < 0) {
      end += -start;
      start = 0;
    }
    if (end > label.length) {
      start -= end - label.length;
      end = label.length;
    }
    start = Math.max(0, start);
    const finalMatchIndex = matchedIndex - start;
    const slicedLabel = label.slice(start, end);
    before = slicedLabel.slice(0, finalMatchIndex);
    match2 = slicedLabel.slice(finalMatchIndex, finalMatchIndex + matchLength);
    after = slicedLabel.slice(finalMatchIndex + matchLength);
    if (start > 0) {
      before = before.length >= 3 ? "..." + before.slice(3) : "...";
    }
    if (end < label.length) {
      after = after.length >= 3 ? after.slice(0, -3) + "..." : "...";
    }
  }
  return /* @__PURE__ */ (0, import_jsx_runtime91.jsxs)(Text, { color: textColor, wrap: "wrap", children: [
    before,
    match2 ? match2.split(/(\s+)/).map((part, index) => /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
      Text,
      {
        color: theme.background.primary,
        backgroundColor: theme.text.primary,
        children: part
      },
      `match-${index}`
    )) : null,
    after
  ] });
}, "_PrepareLabel");
var PrepareLabel = import_react83.default.memo(_PrepareLabel);

// packages/cli/src/ui/components/SuggestionsDisplay.tsx
var import_jsx_runtime92 = __toESM(require_jsx_runtime(), 1);
var MAX_SUGGESTIONS_TO_SHOW = 8;
function SuggestionsDisplay({
  suggestions,
  activeIndex,
  isLoading,
  width,
  scrollOffset,
  userInput,
  mode,
  expandedIndex
}) {
  if (isLoading) {
    return /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Box_default, { paddingX: 1, width, children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text, { color: "gray", children: "Loading suggestions..." }) });
  }
  if (suggestions.length === 0) {
    return null;
  }
  const startIndex = scrollOffset;
  const endIndex = Math.min(
    scrollOffset + MAX_SUGGESTIONS_TO_SHOW,
    suggestions.length
  );
  const visibleSuggestions = suggestions.slice(startIndex, endIndex);
  const getFullLabel = /* @__PURE__ */ __name((s2) => s2.label + (s2.commandKind === "mcp-prompt" /* MCP_PROMPT */ ? " [MCP]" : ""), "getFullLabel");
  const maxLabelLength = Math.max(
    ...suggestions.map((s2) => getFullLabel(s2).length)
  );
  const commandColumnWidth = mode === "slash" ? Math.min(maxLabelLength, Math.floor(width * 0.5)) : 0;
  return /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, width, children: [
    scrollOffset > 0 && /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text, { color: theme.text.primary, children: "\u25B2" }),
    visibleSuggestions.map((suggestion, index) => {
      const originalIndex = startIndex + index;
      const isActive = originalIndex === activeIndex;
      const isExpanded = originalIndex === expandedIndex;
      const textColor = isActive ? theme.text.accent : theme.text.secondary;
      const isLong = suggestion.value.length >= MAX_WIDTH;
      const labelElement = /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(
        PrepareLabel,
        {
          label: suggestion.value,
          matchedIndex: suggestion.matchedIndex,
          userInput,
          textColor,
          isExpanded
        }
      );
      return /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(Box_default, { flexDirection: "row", children: [
        /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(
          Box_default,
          {
            ...mode === "slash" ? { width: commandColumnWidth, flexShrink: 0 } : { flexShrink: 1 },
            children: /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(Box_default, { children: [
              labelElement,
              suggestion.commandKind === "mcp-prompt" /* MCP_PROMPT */ && /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text, { color: textColor, children: " [MCP]" })
            ] })
          }
        ),
        suggestion.description && /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Box_default, { flexGrow: 1, paddingLeft: 3, children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text, { color: textColor, wrap: "truncate", children: suggestion.description }) }),
        isActive && isLong && /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text, { color: Colors.Gray, children: isExpanded ? " \u2190 " : " \u2192 " }) })
      ] }, `${suggestion.value}-${originalIndex}`);
    }),
    endIndex < suggestions.length && /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text, { color: "gray", children: "\u25BC" }),
    suggestions.length > MAX_SUGGESTIONS_TO_SHOW && /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(Text, { color: "gray", children: [
      "(",
      activeIndex + 1,
      "/",
      suggestions.length,
      ")"
    ] })
  ] });
}
__name(SuggestionsDisplay, "SuggestionsDisplay");

// packages/cli/src/ui/hooks/useInputHistory.ts
init_esbuild_shims();
var import_react84 = __toESM(require_react(), 1);
function useInputHistory({
  userMessages,
  onSubmit,
  isActive,
  currentQuery,
  onChange
}) {
  const [historyIndex, setHistoryIndex] = (0, import_react84.useState)(-1);
  const [originalQueryBeforeNav, setOriginalQueryBeforeNav] = (0, import_react84.useState)("");
  const resetHistoryNav = (0, import_react84.useCallback)(() => {
    setHistoryIndex(-1);
    setOriginalQueryBeforeNav("");
  }, []);
  const handleSubmit = (0, import_react84.useCallback)(
    (value) => {
      const trimmedValue = value.trim();
      if (trimmedValue) {
        onSubmit(trimmedValue);
      }
      resetHistoryNav();
    },
    [onSubmit, resetHistoryNav]
  );
  const navigateUp = (0, import_react84.useCallback)(() => {
    if (!isActive) return false;
    if (userMessages.length === 0) return false;
    let nextIndex = historyIndex;
    if (historyIndex === -1) {
      setOriginalQueryBeforeNav(currentQuery);
      nextIndex = 0;
    } else if (historyIndex < userMessages.length - 1) {
      nextIndex = historyIndex + 1;
    } else {
      return false;
    }
    if (nextIndex !== historyIndex) {
      setHistoryIndex(nextIndex);
      const newValue = userMessages[userMessages.length - 1 - nextIndex];
      onChange(newValue);
      return true;
    }
    return false;
  }, [
    historyIndex,
    setHistoryIndex,
    onChange,
    userMessages,
    isActive,
    currentQuery,
    // Use currentQuery from props
    setOriginalQueryBeforeNav
  ]);
  const navigateDown = (0, import_react84.useCallback)(() => {
    if (!isActive) return false;
    if (historyIndex === -1) return false;
    const nextIndex = historyIndex - 1;
    setHistoryIndex(nextIndex);
    if (nextIndex === -1) {
      onChange(originalQueryBeforeNav);
    } else {
      const newValue = userMessages[userMessages.length - 1 - nextIndex];
      onChange(newValue);
    }
    return true;
  }, [
    historyIndex,
    setHistoryIndex,
    originalQueryBeforeNav,
    onChange,
    userMessages,
    isActive
  ]);
  return {
    handleSubmit,
    navigateUp,
    navigateDown
  };
}
__name(useInputHistory, "useInputHistory");

// packages/cli/src/ui/components/InputPrompt.tsx
var import_chalk7 = __toESM(require_source(), 1);

// packages/cli/src/ui/hooks/useShellHistory.ts
init_esbuild_shims();
var import_react85 = __toESM(require_react(), 1);
import * as fs71 from "node:fs/promises";
import * as path73 from "node:path";
var MAX_HISTORY_LENGTH2 = 100;
async function getHistoryFilePath(projectRoot, configStorage) {
  const storage = configStorage ?? new Storage(projectRoot);
  return storage.getHistoryFilePath();
}
__name(getHistoryFilePath, "getHistoryFilePath");
async function readHistoryFile(filePath) {
  try {
    const text = await fs71.readFile(filePath, "utf-8");
    const result = [];
    let cur = "";
    for (const raw2 of text.split(/\r?\n/)) {
      if (!raw2.trim()) continue;
      const line = raw2;
      const m = cur.match(/(\\+)$/);
      if (m && m[1].length % 2) {
        cur = cur.slice(0, -1) + " " + line;
      } else {
        if (cur) result.push(cur);
        cur = line;
      }
    }
    if (cur) result.push(cur);
    return result;
  } catch (err) {
    if (isNodeError(err) && err.code === "ENOENT") return [];
    console.error("Error reading history:", err);
    return [];
  }
}
__name(readHistoryFile, "readHistoryFile");
async function writeHistoryFile(filePath, history) {
  try {
    await fs71.mkdir(path73.dirname(filePath), { recursive: true });
    await fs71.writeFile(filePath, history.join("\n"));
  } catch (error) {
    console.error("Error writing shell history:", error);
  }
}
__name(writeHistoryFile, "writeHistoryFile");
function useShellHistory(projectRoot, storage) {
  const [history, setHistory] = (0, import_react85.useState)([]);
  const [historyIndex, setHistoryIndex] = (0, import_react85.useState)(-1);
  const [historyFilePath, setHistoryFilePath] = (0, import_react85.useState)(null);
  (0, import_react85.useEffect)(() => {
    async function loadHistory() {
      const filePath = await getHistoryFilePath(projectRoot, storage);
      setHistoryFilePath(filePath);
      const loadedHistory = await readHistoryFile(filePath);
      setHistory(loadedHistory.reverse());
    }
    __name(loadHistory, "loadHistory");
    loadHistory();
  }, [projectRoot, storage]);
  const addCommandToHistory = (0, import_react85.useCallback)(
    (command2) => {
      if (!command2.trim() || !historyFilePath) {
        return;
      }
      const newHistory = [command2, ...history.filter((c3) => c3 !== command2)].slice(0, MAX_HISTORY_LENGTH2).filter(Boolean);
      setHistory(newHistory);
      writeHistoryFile(historyFilePath, [...newHistory].reverse());
      setHistoryIndex(-1);
    },
    [history, historyFilePath]
  );
  const getPreviousCommand = (0, import_react85.useCallback)(() => {
    if (history.length === 0) {
      return null;
    }
    const newIndex = Math.min(historyIndex + 1, history.length - 1);
    setHistoryIndex(newIndex);
    return history[newIndex] ?? null;
  }, [history, historyIndex]);
  const getNextCommand = (0, import_react85.useCallback)(() => {
    if (historyIndex < 0) {
      return null;
    }
    const newIndex = historyIndex - 1;
    setHistoryIndex(newIndex);
    if (newIndex < 0) {
      return "";
    }
    return history[newIndex] ?? null;
  }, [history, historyIndex]);
  const resetHistoryPosition = (0, import_react85.useCallback)(() => {
    setHistoryIndex(-1);
  }, []);
  return {
    history,
    addCommandToHistory,
    getPreviousCommand,
    getNextCommand,
    resetHistoryPosition
  };
}
__name(useShellHistory, "useShellHistory");

// packages/cli/src/ui/hooks/useReverseSearchCompletion.tsx
init_esbuild_shims();
var import_react87 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useCompletion.ts
init_esbuild_shims();
var import_react86 = __toESM(require_react(), 1);
function useCompletion() {
  const [suggestions, setSuggestions] = (0, import_react86.useState)([]);
  const [activeSuggestionIndex, setActiveSuggestionIndex] = (0, import_react86.useState)(-1);
  const [visibleStartIndex, setVisibleStartIndex] = (0, import_react86.useState)(0);
  const [showSuggestions, setShowSuggestions] = (0, import_react86.useState)(false);
  const [isLoadingSuggestions, setIsLoadingSuggestions] = (0, import_react86.useState)(false);
  const [isPerfectMatch, setIsPerfectMatch] = (0, import_react86.useState)(false);
  const resetCompletionState = (0, import_react86.useCallback)(() => {
    setSuggestions([]);
    setActiveSuggestionIndex(-1);
    setVisibleStartIndex(0);
    setShowSuggestions(false);
    setIsLoadingSuggestions(false);
    setIsPerfectMatch(false);
  }, []);
  const navigateUp = (0, import_react86.useCallback)(() => {
    if (suggestions.length === 0) return;
    setActiveSuggestionIndex((prevActiveIndex) => {
      const newActiveIndex = prevActiveIndex <= 0 ? suggestions.length - 1 : prevActiveIndex - 1;
      setVisibleStartIndex((prevVisibleStart) => {
        if (newActiveIndex === suggestions.length - 1 && suggestions.length > MAX_SUGGESTIONS_TO_SHOW) {
          return Math.max(0, suggestions.length - MAX_SUGGESTIONS_TO_SHOW);
        }
        if (newActiveIndex < prevVisibleStart) {
          return newActiveIndex;
        }
        return prevVisibleStart;
      });
      return newActiveIndex;
    });
  }, [suggestions.length]);
  const navigateDown = (0, import_react86.useCallback)(() => {
    if (suggestions.length === 0) return;
    setActiveSuggestionIndex((prevActiveIndex) => {
      const newActiveIndex = prevActiveIndex >= suggestions.length - 1 ? 0 : prevActiveIndex + 1;
      setVisibleStartIndex((prevVisibleStart) => {
        if (newActiveIndex === 0 && suggestions.length > MAX_SUGGESTIONS_TO_SHOW) {
          return 0;
        }
        const visibleEndIndex = prevVisibleStart + MAX_SUGGESTIONS_TO_SHOW;
        if (newActiveIndex >= visibleEndIndex) {
          return newActiveIndex - MAX_SUGGESTIONS_TO_SHOW + 1;
        }
        return prevVisibleStart;
      });
      return newActiveIndex;
    });
  }, [suggestions.length]);
  return {
    suggestions,
    activeSuggestionIndex,
    visibleStartIndex,
    showSuggestions,
    isLoadingSuggestions,
    isPerfectMatch,
    setSuggestions,
    setShowSuggestions,
    setActiveSuggestionIndex,
    setVisibleStartIndex,
    setIsLoadingSuggestions,
    setIsPerfectMatch,
    resetCompletionState,
    navigateUp,
    navigateDown
  };
}
__name(useCompletion, "useCompletion");

// packages/cli/src/ui/hooks/useReverseSearchCompletion.tsx
function useDebouncedValue(value, delay4 = 200) {
  const [debounced, setDebounced] = (0, import_react87.useState)(value);
  (0, import_react87.useEffect)(() => {
    const handle = setTimeout(() => setDebounced(value), delay4);
    return () => clearTimeout(handle);
  }, [value, delay4]);
  return debounced;
}
__name(useDebouncedValue, "useDebouncedValue");
function useReverseSearchCompletion(buffer, history, reverseSearchActive) {
  const {
    suggestions,
    activeSuggestionIndex,
    visibleStartIndex,
    showSuggestions,
    isLoadingSuggestions,
    setSuggestions,
    setShowSuggestions,
    setActiveSuggestionIndex,
    resetCompletionState,
    navigateUp,
    navigateDown,
    setVisibleStartIndex
  } = useCompletion();
  const debouncedQuery = useDebouncedValue(buffer.text, 100);
  const prevQueryRef = (0, import_react87.useRef)("");
  const prevMatchesRef = (0, import_react87.useRef)([]);
  (0, import_react87.useEffect)(() => {
    if (reverseSearchActive) {
      prevQueryRef.current = "";
      prevMatchesRef.current = [];
    }
  }, [reverseSearchActive]);
  (0, import_react87.useEffect)(() => {
    prevQueryRef.current = "";
    prevMatchesRef.current = [];
  }, [history]);
  const searchHistory = (0, import_react87.useCallback)(
    (query, items) => {
      const out = [];
      for (let i = 0; i < items.length; i++) {
        const cmd = items[i];
        const idx = cmd.toLowerCase().indexOf(query);
        if (idx !== -1) {
          out.push({ label: cmd, value: cmd, matchedIndex: idx });
        }
      }
      return out;
    },
    []
  );
  const matches = (0, import_react87.useMemo)(() => {
    if (!reverseSearchActive) return [];
    if (debouncedQuery.length === 0)
      return history.map((cmd) => ({
        label: cmd,
        value: cmd,
        matchedIndex: -1
      }));
    const query = debouncedQuery.toLowerCase();
    const canUseCache = prevQueryRef.current && query.startsWith(prevQueryRef.current) && prevMatchesRef.current.length > 0;
    const source2 = canUseCache ? prevMatchesRef.current.map((m) => m.value) : history;
    return searchHistory(query, source2);
  }, [debouncedQuery, history, reverseSearchActive, searchHistory]);
  (0, import_react87.useEffect)(() => {
    if (!reverseSearchActive) {
      resetCompletionState();
      return;
    }
    setSuggestions(matches);
    const hasAny = matches.length > 0;
    setShowSuggestions(hasAny);
    setActiveSuggestionIndex(hasAny ? 0 : -1);
    setVisibleStartIndex(0);
    prevQueryRef.current = debouncedQuery.toLowerCase();
    prevMatchesRef.current = matches;
  }, [
    debouncedQuery,
    matches,
    reverseSearchActive,
    setSuggestions,
    setShowSuggestions,
    setActiveSuggestionIndex,
    setVisibleStartIndex,
    resetCompletionState
  ]);
  const handleAutocomplete = (0, import_react87.useCallback)(
    (i) => {
      if (i < 0 || i >= suggestions.length) return;
      buffer.setText(suggestions[i].value);
      resetCompletionState();
    },
    [buffer, suggestions, resetCompletionState]
  );
  return {
    suggestions,
    activeSuggestionIndex,
    visibleStartIndex,
    showSuggestions,
    isLoadingSuggestions,
    navigateUp,
    navigateDown,
    handleAutocomplete,
    resetCompletionState
  };
}
__name(useReverseSearchCompletion, "useReverseSearchCompletion");

// packages/cli/src/ui/hooks/useCommandCompletion.tsx
init_esbuild_shims();
var import_react90 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useAtCompletion.ts
init_esbuild_shims();
var import_react88 = __toESM(require_react(), 1);
var initialState = {
  status: "idle" /* IDLE */,
  suggestions: [],
  isLoading: false,
  pattern: null
};
function atCompletionReducer(state, action) {
  switch (action.type) {
    case "INITIALIZE":
      return {
        ...state,
        status: "initializing" /* INITIALIZING */,
        isLoading: true
      };
    case "INITIALIZE_SUCCESS":
      return { ...state, status: "ready" /* READY */, isLoading: false };
    case "SEARCH":
      return {
        ...state,
        status: "searching" /* SEARCHING */,
        pattern: action.payload
      };
    case "SEARCH_SUCCESS":
      return {
        ...state,
        status: "ready" /* READY */,
        suggestions: action.payload,
        isLoading: false
      };
    case "SET_LOADING":
      if (state.status === "searching" /* SEARCHING */) {
        return { ...state, isLoading: action.payload, suggestions: [] };
      }
      return state;
    case "ERROR":
      return {
        ...state,
        status: "error" /* ERROR */,
        isLoading: false,
        suggestions: []
      };
    case "RESET":
      return initialState;
    default:
      return state;
  }
}
__name(atCompletionReducer, "atCompletionReducer");
function useAtCompletion(props) {
  const {
    enabled,
    pattern,
    config,
    cwd: cwd7,
    setSuggestions,
    setIsLoadingSuggestions
  } = props;
  const [state, dispatch] = (0, import_react88.useReducer)(atCompletionReducer, initialState);
  const fileSearch = (0, import_react88.useRef)(null);
  const searchAbortController = (0, import_react88.useRef)(null);
  const slowSearchTimer = (0, import_react88.useRef)(null);
  (0, import_react88.useEffect)(() => {
    setSuggestions(state.suggestions);
  }, [state.suggestions, setSuggestions]);
  (0, import_react88.useEffect)(() => {
    setIsLoadingSuggestions(state.isLoading);
  }, [state.isLoading, setIsLoadingSuggestions]);
  (0, import_react88.useEffect)(() => {
    dispatch({ type: "RESET" });
  }, [cwd7, config]);
  (0, import_react88.useEffect)(() => {
    if (!enabled) {
      if (state.status === "ready" /* READY */ || state.status === "error" /* ERROR */) {
        dispatch({ type: "RESET" });
      }
      return;
    }
    if (pattern === null) {
      dispatch({ type: "RESET" });
      return;
    }
    if (state.status === "idle" /* IDLE */) {
      dispatch({ type: "INITIALIZE" });
    } else if ((state.status === "ready" /* READY */ || state.status === "searching" /* SEARCHING */) && pattern !== state.pattern) {
      dispatch({ type: "SEARCH", payload: pattern });
    }
  }, [enabled, pattern, state.status, state.pattern]);
  (0, import_react88.useEffect)(() => {
    const initialize = /* @__PURE__ */ __name(async () => {
      try {
        const searcher = FileSearchFactory.create({
          projectRoot: cwd7,
          ignoreDirs: [],
          useGitignore: config?.getFileFilteringOptions()?.respectGitIgnore ?? true,
          useQwenignore: config?.getFileFilteringOptions()?.respectQwenIgnore ?? true,
          cache: true,
          cacheTtl: 30,
          // 30 seconds
          enableRecursiveFileSearch: config?.getEnableRecursiveFileSearch() ?? true,
          disableFuzzySearch: config?.getFileFilteringDisableFuzzySearch() ?? false
        });
        await searcher.initialize();
        fileSearch.current = searcher;
        dispatch({ type: "INITIALIZE_SUCCESS" });
        if (state.pattern !== null) {
          dispatch({ type: "SEARCH", payload: state.pattern });
        }
      } catch (_) {
        dispatch({ type: "ERROR" });
      }
    }, "initialize");
    const search = /* @__PURE__ */ __name(async () => {
      if (!fileSearch.current || state.pattern === null) {
        return;
      }
      if (slowSearchTimer.current) {
        clearTimeout(slowSearchTimer.current);
      }
      const controller = new AbortController();
      searchAbortController.current = controller;
      slowSearchTimer.current = setTimeout(() => {
        dispatch({ type: "SET_LOADING", payload: true });
      }, 200);
      try {
        const results = await fileSearch.current.search(state.pattern, {
          signal: controller.signal,
          maxResults: MAX_SUGGESTIONS_TO_SHOW * 3
        });
        if (slowSearchTimer.current) {
          clearTimeout(slowSearchTimer.current);
        }
        if (controller.signal.aborted) {
          return;
        }
        const suggestions = results.map((p) => ({
          label: p,
          value: escapePath(p)
        }));
        dispatch({ type: "SEARCH_SUCCESS", payload: suggestions });
      } catch (error) {
        if (!(error instanceof Error && error.name === "AbortError")) {
          dispatch({ type: "ERROR" });
        }
      }
    }, "search");
    if (state.status === "initializing" /* INITIALIZING */) {
      initialize();
    } else if (state.status === "searching" /* SEARCHING */) {
      search();
    }
    return () => {
      searchAbortController.current?.abort();
      if (slowSearchTimer.current) {
        clearTimeout(slowSearchTimer.current);
      }
    };
  }, [state.status, state.pattern, config, cwd7]);
}
__name(useAtCompletion, "useAtCompletion");

// packages/cli/src/ui/hooks/useSlashCompletion.ts
init_esbuild_shims();
var import_react89 = __toESM(require_react(), 1);
init_fzf_es();
function logErrorSafely(error, context2) {
  if (error instanceof Error) {
    console.error(`[${context2}]`, error);
  } else {
    console.error(`[${context2}] Non-error thrown:`, error);
  }
}
__name(logErrorSafely, "logErrorSafely");
function matchesCommand(cmd, query) {
  return cmd.name.toLowerCase() === query.toLowerCase() || cmd.altNames?.some((alt) => alt.toLowerCase() === query.toLowerCase()) || false;
}
__name(matchesCommand, "matchesCommand");
function useCommandParser(query, slashCommands) {
  return (0, import_react89.useMemo)(() => {
    if (!query) {
      return {
        hasTrailingSpace: false,
        commandPathParts: [],
        partial: "",
        currentLevel: slashCommands,
        leafCommand: null,
        exactMatchAsParent: void 0,
        isArgumentCompletion: false
      };
    }
    const fullPath = query.substring(1) || "";
    const hasTrailingSpace = !!query.endsWith(" ");
    const rawParts = fullPath.split(/\s+/).filter((p) => p);
    let commandPathParts = rawParts;
    let partial = "";
    if (!hasTrailingSpace && rawParts.length > 0) {
      partial = rawParts[rawParts.length - 1];
      commandPathParts = rawParts.slice(0, -1);
    }
    let currentLevel = slashCommands;
    let leafCommand = null;
    for (const part of commandPathParts) {
      if (!currentLevel) {
        leafCommand = null;
        currentLevel = [];
        break;
      }
      const found = currentLevel.find(
        (cmd) => matchesCommand(cmd, part)
      );
      if (found) {
        leafCommand = found;
        currentLevel = found.subCommands;
        if (found.kind === "mcp-prompt" /* MCP_PROMPT */) {
          break;
        }
      } else {
        leafCommand = null;
        currentLevel = [];
        break;
      }
    }
    let exactMatchAsParent;
    if (!hasTrailingSpace && currentLevel) {
      exactMatchAsParent = currentLevel.find(
        (cmd) => matchesCommand(cmd, partial) && cmd.subCommands
      );
      if (exactMatchAsParent) {
        leafCommand = exactMatchAsParent;
        currentLevel = exactMatchAsParent.subCommands;
        partial = "";
      }
    }
    const depth = commandPathParts.length;
    const isArgumentCompletion = !!(leafCommand?.completion && (hasTrailingSpace || rawParts.length > depth && depth > 0 && partial !== ""));
    return {
      hasTrailingSpace,
      commandPathParts,
      partial,
      currentLevel,
      leafCommand,
      exactMatchAsParent,
      isArgumentCompletion
    };
  }, [query, slashCommands]);
}
__name(useCommandParser, "useCommandParser");
function useCommandSuggestions(parserResult, commandContext, getFzfForCommands, getPrefixSuggestions) {
  const [suggestions, setSuggestions] = (0, import_react89.useState)([]);
  const [isLoading, setIsLoading] = (0, import_react89.useState)(false);
  (0, import_react89.useEffect)(() => {
    const abortController = new AbortController();
    const { signal } = abortController;
    const {
      isArgumentCompletion,
      leafCommand,
      commandPathParts,
      partial,
      currentLevel
    } = parserResult;
    if (isArgumentCompletion) {
      const fetchAndSetSuggestions = /* @__PURE__ */ __name(async () => {
        if (signal.aborted) return;
        if (!leafCommand?.completion) {
          console.warn(
            "Attempted argument completion without completion function"
          );
          return;
        }
        setIsLoading(true);
        try {
          const rawParts = [...commandPathParts];
          if (partial) rawParts.push(partial);
          const depth = commandPathParts.length;
          const argString = rawParts.slice(depth).join(" ");
          const results = await leafCommand.completion(
            {
              ...commandContext,
              invocation: {
                raw: `/${rawParts.join(" ")}`,
                name: leafCommand.name,
                args: argString
              }
            },
            argString
          ) || [];
          if (!signal.aborted) {
            const finalSuggestions = results.map((s2) => ({
              label: s2,
              value: s2
            }));
            setSuggestions(finalSuggestions);
            setIsLoading(false);
          }
        } catch (error) {
          if (!signal.aborted) {
            logErrorSafely(error, "Argument completion");
            setSuggestions([]);
            setIsLoading(false);
          }
        }
      }, "fetchAndSetSuggestions");
      fetchAndSetSuggestions();
      return () => abortController.abort();
    }
    const commandsToSearch = currentLevel || [];
    if (commandsToSearch.length > 0) {
      const performFuzzySearch = /* @__PURE__ */ __name(async () => {
        if (signal.aborted) return;
        let potentialSuggestions = [];
        if (partial === "") {
          potentialSuggestions = commandsToSearch.filter(
            (cmd) => cmd.description && !cmd.hidden
          );
        } else {
          const fzfInstance = getFzfForCommands(commandsToSearch);
          if (fzfInstance) {
            try {
              const fzfResults = await fzfInstance.fzf.find(partial);
              if (signal.aborted) return;
              const uniqueCommands = /* @__PURE__ */ new Set();
              fzfResults.forEach((result) => {
                const cmd = fzfInstance.commandMap.get(result.item);
                if (cmd && cmd.description) {
                  uniqueCommands.add(cmd);
                }
              });
              potentialSuggestions = Array.from(uniqueCommands);
            } catch (error) {
              logErrorSafely(
                error,
                "Fuzzy search - falling back to prefix matching"
              );
              potentialSuggestions = getPrefixSuggestions(
                commandsToSearch,
                partial
              );
            }
          } else {
            potentialSuggestions = getPrefixSuggestions(
              commandsToSearch,
              partial
            );
          }
        }
        if (!signal.aborted) {
          const finalSuggestions = potentialSuggestions.map((cmd) => ({
            label: cmd.name,
            value: cmd.name,
            description: cmd.description,
            commandKind: cmd.kind
          }));
          setSuggestions(finalSuggestions);
        }
      }, "performFuzzySearch");
      performFuzzySearch().catch((error) => {
        logErrorSafely(error, "Unexpected fuzzy search error");
        if (!signal.aborted) {
          setSuggestions([]);
        }
      });
      return () => abortController.abort();
    }
    setSuggestions([]);
    return () => abortController.abort();
  }, [parserResult, commandContext, getFzfForCommands, getPrefixSuggestions]);
  return { suggestions, isLoading };
}
__name(useCommandSuggestions, "useCommandSuggestions");
function useCompletionPositions(query, parserResult) {
  return (0, import_react89.useMemo)(() => {
    if (!query) {
      return { start: -1, end: -1 };
    }
    const { hasTrailingSpace, partial, exactMatchAsParent } = parserResult;
    if (hasTrailingSpace || exactMatchAsParent) {
      return { start: query.length, end: query.length };
    } else if (partial) {
      if (parserResult.isArgumentCompletion) {
        const commandSoFar = `/${parserResult.commandPathParts.join(" ")}`;
        const argStartIndex = commandSoFar.length + (parserResult.commandPathParts.length > 0 ? 1 : 0);
        return { start: argStartIndex, end: query.length };
      } else {
        return { start: query.length - partial.length, end: query.length };
      }
    } else {
      return { start: 1, end: query.length };
    }
  }, [query, parserResult]);
}
__name(useCompletionPositions, "useCompletionPositions");
function usePerfectMatch(parserResult) {
  return (0, import_react89.useMemo)(() => {
    const { hasTrailingSpace, partial, leafCommand, currentLevel } = parserResult;
    if (hasTrailingSpace) {
      return { isPerfectMatch: false };
    }
    if (leafCommand && partial === "" && leafCommand.action) {
      return { isPerfectMatch: true };
    }
    if (currentLevel) {
      const perfectMatch = currentLevel.find(
        (cmd) => matchesCommand(cmd, partial) && cmd.action
      );
      if (perfectMatch) {
        return { isPerfectMatch: true };
      }
    }
    return { isPerfectMatch: false };
  }, [parserResult]);
}
__name(usePerfectMatch, "usePerfectMatch");
function useSlashCompletion(props) {
  const {
    enabled,
    query,
    slashCommands,
    commandContext,
    setSuggestions,
    setIsLoadingSuggestions,
    setIsPerfectMatch
  } = props;
  const [completionStart, setCompletionStart] = (0, import_react89.useState)(-1);
  const [completionEnd, setCompletionEnd] = (0, import_react89.useState)(-1);
  const fzfInstanceCache = (0, import_react89.useMemo)(
    () => /* @__PURE__ */ new WeakMap(),
    []
  );
  const getFzfForCommands = (0, import_react89.useMemo)(
    () => (commands) => {
      if (!commands || commands.length === 0) {
        return null;
      }
      const cached = fzfInstanceCache.get(commands);
      if (cached) {
        return cached;
      }
      const commandItems = [];
      const commandMap = /* @__PURE__ */ new Map();
      commands.forEach((cmd) => {
        if (cmd.description && !cmd.hidden) {
          commandItems.push(cmd.name);
          commandMap.set(cmd.name, cmd);
          if (cmd.altNames) {
            cmd.altNames.forEach((alt) => {
              commandItems.push(alt);
              commandMap.set(alt, cmd);
            });
          }
        }
      });
      if (commandItems.length === 0) {
        return null;
      }
      try {
        const instance = {
          fzf: new AsyncFzf(commandItems, {
            fuzzy: "v2",
            casing: "case-insensitive"
            // Explicitly enforce case-insensitivity
          }),
          commandMap
        };
        fzfInstanceCache.set(commands, instance);
        return instance;
      } catch (error) {
        logErrorSafely(error, "FZF instance creation");
        return null;
      }
    },
    [fzfInstanceCache]
  );
  const getPrefixSuggestions = (0, import_react89.useMemo)(
    () => (commands, partial) => commands.filter(
      (cmd) => cmd.description && !cmd.hidden && (cmd.name.toLowerCase().startsWith(partial.toLowerCase()) || cmd.altNames?.some(
        (alt) => alt.toLowerCase().startsWith(partial.toLowerCase())
      ))
    ),
    []
  );
  const parserResult = useCommandParser(query, slashCommands);
  const { suggestions: hookSuggestions, isLoading } = useCommandSuggestions(
    parserResult,
    commandContext,
    getFzfForCommands,
    getPrefixSuggestions
  );
  const { start: calculatedStart, end: calculatedEnd } = useCompletionPositions(
    query,
    parserResult
  );
  const { isPerfectMatch } = usePerfectMatch(parserResult);
  (0, import_react89.useEffect)(() => {
    if (!enabled) {
      setSuggestions([]);
      setIsLoadingSuggestions(false);
      setIsPerfectMatch(false);
      setCompletionStart(-1);
      setCompletionEnd(-1);
    }
  }, [enabled, setSuggestions, setIsLoadingSuggestions, setIsPerfectMatch]);
  (0, import_react89.useEffect)(() => {
    if (!enabled || query === null) {
      return;
    }
    setSuggestions(hookSuggestions);
    setIsLoadingSuggestions(isLoading);
    setIsPerfectMatch(isPerfectMatch);
    setCompletionStart(calculatedStart);
    setCompletionEnd(calculatedEnd);
  }, [
    enabled,
    query,
    hookSuggestions,
    isLoading,
    isPerfectMatch,
    calculatedStart,
    calculatedEnd,
    setSuggestions,
    setIsLoadingSuggestions,
    setIsPerfectMatch
  ]);
  return {
    completionStart,
    completionEnd
  };
}
__name(useSlashCompletion, "useSlashCompletion");

// packages/cli/src/ui/hooks/useCommandCompletion.tsx
function useCommandCompletion(buffer, dirs, cwd7, slashCommands, commandContext, reverseSearchActive = false, config) {
  const {
    suggestions,
    activeSuggestionIndex,
    visibleStartIndex,
    showSuggestions,
    isLoadingSuggestions,
    isPerfectMatch,
    setSuggestions,
    setShowSuggestions,
    setActiveSuggestionIndex,
    setIsLoadingSuggestions,
    setIsPerfectMatch,
    setVisibleStartIndex,
    resetCompletionState,
    navigateUp,
    navigateDown
  } = useCompletion();
  const cursorRow = buffer.cursor[0];
  const cursorCol = buffer.cursor[1];
  const { completionMode, query, completionStart, completionEnd } = (0, import_react90.useMemo)(() => {
    const currentLine = buffer.lines[cursorRow] || "";
    if (cursorRow === 0 && isSlashCommand(currentLine.trim())) {
      return {
        completionMode: "SLASH" /* SLASH */,
        query: currentLine,
        completionStart: 0,
        completionEnd: currentLine.length
      };
    }
    const codePoints = toCodePoints(currentLine);
    for (let i = cursorCol - 1; i >= 0; i--) {
      const char = codePoints[i];
      if (char === " ") {
        let backslashCount = 0;
        for (let j = i - 1; j >= 0 && codePoints[j] === "\\"; j--) {
          backslashCount++;
        }
        if (backslashCount % 2 === 0) {
          break;
        }
      } else if (char === "@") {
        let end = codePoints.length;
        for (let i2 = cursorCol; i2 < codePoints.length; i2++) {
          if (codePoints[i2] === " ") {
            let backslashCount = 0;
            for (let j = i2 - 1; j >= 0 && codePoints[j] === "\\"; j--) {
              backslashCount++;
            }
            if (backslashCount % 2 === 0) {
              end = i2;
              break;
            }
          }
        }
        const pathStart = i + 1;
        const partialPath = currentLine.substring(pathStart, end);
        return {
          completionMode: "AT" /* AT */,
          query: partialPath,
          completionStart: pathStart,
          completionEnd: end
        };
      }
    }
    return {
      completionMode: "IDLE" /* IDLE */,
      query: null,
      completionStart: -1,
      completionEnd: -1
    };
  }, [cursorRow, cursorCol, buffer.lines]);
  useAtCompletion({
    enabled: completionMode === "AT" /* AT */,
    pattern: query || "",
    config,
    cwd: cwd7,
    setSuggestions,
    setIsLoadingSuggestions
  });
  const slashCompletionRange = useSlashCompletion({
    enabled: completionMode === "SLASH" /* SLASH */,
    query,
    slashCommands,
    commandContext,
    setSuggestions,
    setIsLoadingSuggestions,
    setIsPerfectMatch
  });
  (0, import_react90.useEffect)(() => {
    setActiveSuggestionIndex(suggestions.length > 0 ? 0 : -1);
    setVisibleStartIndex(0);
  }, [suggestions, setActiveSuggestionIndex, setVisibleStartIndex]);
  (0, import_react90.useEffect)(() => {
    if (completionMode === "IDLE" /* IDLE */ || reverseSearchActive) {
      resetCompletionState();
      return;
    }
    setShowSuggestions(isLoadingSuggestions || suggestions.length > 0);
  }, [
    completionMode,
    suggestions.length,
    isLoadingSuggestions,
    reverseSearchActive,
    resetCompletionState,
    setShowSuggestions
  ]);
  const handleAutocomplete = (0, import_react90.useCallback)(
    (indexToUse) => {
      if (indexToUse < 0 || indexToUse >= suggestions.length) {
        return;
      }
      const suggestion = suggestions[indexToUse].value;
      let start = completionStart;
      let end = completionEnd;
      if (completionMode === "SLASH" /* SLASH */) {
        start = slashCompletionRange.completionStart;
        end = slashCompletionRange.completionEnd;
      }
      if (start === -1 || end === -1) {
        return;
      }
      let suggestionText = suggestion;
      if (completionMode === "SLASH" /* SLASH */) {
        if (start === end && start > 1 && (buffer.lines[cursorRow] || "")[start - 1] !== " ") {
          suggestionText = " " + suggestionText;
        }
      }
      const lineCodePoints = toCodePoints(buffer.lines[cursorRow] || "");
      const charAfterCompletion = lineCodePoints[end];
      if (charAfterCompletion !== " ") {
        suggestionText += " ";
      }
      buffer.replaceRangeByOffset(
        logicalPosToOffset(buffer.lines, cursorRow, start),
        logicalPosToOffset(buffer.lines, cursorRow, end),
        suggestionText
      );
    },
    [
      cursorRow,
      buffer,
      suggestions,
      completionMode,
      completionStart,
      completionEnd,
      slashCompletionRange
    ]
  );
  return {
    suggestions,
    activeSuggestionIndex,
    visibleStartIndex,
    showSuggestions,
    isLoadingSuggestions,
    isPerfectMatch,
    setActiveSuggestionIndex,
    setShowSuggestions,
    resetCompletionState,
    navigateUp,
    navigateDown,
    handleAutocomplete
  };
}
__name(useCommandCompletion, "useCommandCompletion");

// packages/cli/src/ui/utils/highlight.ts
init_esbuild_shims();
var HIGHLIGHT_REGEX = /(^\/[a-zA-Z0-9_-]+|@(?:\\ |[a-zA-Z0-9_./-])+)/g;
function parseInputForHighlighting(text, index) {
  if (!text) {
    return [{ text: "", type: "default" }];
  }
  const tokens = [];
  let lastIndex = 0;
  let match2;
  while ((match2 = HIGHLIGHT_REGEX.exec(text)) !== null) {
    const [fullMatch] = match2;
    const matchIndex = match2.index;
    if (matchIndex > lastIndex) {
      tokens.push({
        text: text.slice(lastIndex, matchIndex),
        type: "default"
      });
    }
    const type = fullMatch.startsWith("/") ? "command" : "file";
    if (type === "command" && index !== 0) {
      tokens.push({
        text: fullMatch,
        type: "default"
      });
    } else {
      tokens.push({
        text: fullMatch,
        type
      });
    }
    lastIndex = matchIndex + fullMatch.length;
  }
  if (lastIndex < text.length) {
    tokens.push({
      text: text.slice(lastIndex),
      type: "default"
    });
  }
  return tokens;
}
__name(parseInputForHighlighting, "parseInputForHighlighting");
function buildSegmentsForVisualSlice(tokens, sliceStart, sliceEnd) {
  if (sliceStart >= sliceEnd) return [];
  const segments = [];
  let tokenCpStart = 0;
  for (const token2 of tokens) {
    const tokenLen = cpLen(token2.text);
    const tokenStart = tokenCpStart;
    const tokenEnd = tokenStart + tokenLen;
    const overlapStart = Math.max(tokenStart, sliceStart);
    const overlapEnd = Math.min(tokenEnd, sliceEnd);
    if (overlapStart < overlapEnd) {
      const sliceStartInToken = overlapStart - tokenStart;
      const sliceEndInToken = overlapEnd - tokenStart;
      const rawSlice = cpSlice(token2.text, sliceStartInToken, sliceEndInToken);
      const last2 = segments[segments.length - 1];
      if (last2 && last2.type === token2.type) {
        last2.text += rawSlice;
      } else {
        segments.push({ type: token2.type, text: rawSlice });
      }
    }
    tokenCpStart += tokenLen;
  }
  return segments;
}
__name(buildSegmentsForVisualSlice, "buildSegmentsForVisualSlice");

// packages/cli/src/ui/utils/clipboardUtils.ts
init_esbuild_shims();
import * as fs72 from "node:fs/promises";
import * as path74 from "node:path";
async function clipboardHasImage() {
  if (process.platform !== "darwin") {
    return false;
  }
  try {
    const { stdout } = await execCommand("osascript", ["-e", "clipboard info"]);
    const imageRegex = /«class PNGf»|TIFF picture|JPEG picture|GIF picture|«class JPEG»|«class TIFF»/;
    return imageRegex.test(stdout);
  } catch {
    return false;
  }
}
__name(clipboardHasImage, "clipboardHasImage");
async function saveClipboardImage(targetDir) {
  if (process.platform !== "darwin") {
    return null;
  }
  try {
    const baseDir = targetDir || process.cwd();
    const tempDir = path74.join(baseDir, ".gemini-clipboard");
    await fs72.mkdir(tempDir, { recursive: true });
    const timestamp = (/* @__PURE__ */ new Date()).getTime();
    const formats = [
      { class: "PNGf", extension: "png" },
      { class: "JPEG", extension: "jpg" },
      { class: "TIFF", extension: "tiff" },
      { class: "GIFf", extension: "gif" }
    ];
    for (const format4 of formats) {
      const tempFilePath = path74.join(
        tempDir,
        `clipboard-${timestamp}.${format4.extension}`
      );
      const script = `
        try
          set imageData to the clipboard as \xABclass ${format4.class}\xBB
          set fileRef to open for access POSIX file "${tempFilePath}" with write permission
          write imageData to fileRef
          close access fileRef
          return "success"
        on error errMsg
          try
            close access POSIX file "${tempFilePath}"
          end try
          return "error"
        end try
      `;
      const { stdout } = await execCommand("osascript", ["-e", script]);
      if (stdout.trim() === "success") {
        try {
          const stats = await fs72.stat(tempFilePath);
          if (stats.size > 0) {
            return tempFilePath;
          }
        } catch {
        }
      }
      try {
        await fs72.unlink(tempFilePath);
      } catch {
      }
    }
    return null;
  } catch (error) {
    console.error("Error saving clipboard image:", error);
    return null;
  }
}
__name(saveClipboardImage, "saveClipboardImage");
async function cleanupOldClipboardImages(targetDir) {
  try {
    const baseDir = targetDir || process.cwd();
    const tempDir = path74.join(baseDir, ".gemini-clipboard");
    const files = await fs72.readdir(tempDir);
    const oneHourAgo = Date.now() - 60 * 60 * 1e3;
    for (const file of files) {
      if (file.startsWith("clipboard-") && (file.endsWith(".png") || file.endsWith(".jpg") || file.endsWith(".tiff") || file.endsWith(".gif"))) {
        const filePath = path74.join(tempDir, file);
        const stats = await fs72.stat(filePath);
        if (stats.mtimeMs < oneHourAgo) {
          await fs72.unlink(filePath);
        }
      }
    }
  } catch {
  }
}
__name(cleanupOldClipboardImages, "cleanupOldClipboardImages");

// packages/cli/src/ui/components/InputPrompt.tsx
import * as path75 from "node:path";

// packages/cli/src/ui/contexts/ShellFocusContext.tsx
init_esbuild_shims();
var import_react91 = __toESM(require_react(), 1);
var ShellFocusContext = (0, import_react91.createContext)(true);
var useShellFocusState = /* @__PURE__ */ __name(() => (0, import_react91.useContext)(ShellFocusContext), "useShellFocusState");

// packages/cli/src/ui/components/InputPrompt.tsx
var import_jsx_runtime93 = __toESM(require_jsx_runtime(), 1);
var calculatePromptWidths = /* @__PURE__ */ __name((terminalWidth) => {
  const widthFraction = 0.9;
  const FRAME_PADDING_AND_BORDER = 4;
  const PROMPT_PREFIX_WIDTH = 2;
  const MIN_CONTENT_WIDTH = 2;
  const innerContentWidth = Math.floor(terminalWidth * widthFraction) - FRAME_PADDING_AND_BORDER - PROMPT_PREFIX_WIDTH;
  const inputWidth = Math.max(MIN_CONTENT_WIDTH, innerContentWidth);
  const FRAME_OVERHEAD = FRAME_PADDING_AND_BORDER + PROMPT_PREFIX_WIDTH;
  const containerWidth = inputWidth + FRAME_OVERHEAD;
  const suggestionsWidth = Math.max(20, Math.floor(terminalWidth * 1));
  return {
    inputWidth,
    containerWidth,
    suggestionsWidth,
    frameOverhead: FRAME_OVERHEAD
  };
}, "calculatePromptWidths");
var InputPrompt = /* @__PURE__ */ __name(({
  buffer,
  onSubmit,
  userMessages,
  onClearScreen,
  config,
  slashCommands,
  commandContext,
  placeholder = "  Type your message or @path/to/file",
  focus = true,
  suggestionsWidth,
  shellModeActive,
  setShellModeActive,
  approvalMode,
  onEscapePromptChange,
  vimHandleInput,
  isEmbeddedShellFocused
}) => {
  const isShellFocused = useShellFocusState();
  const [justNavigatedHistory, setJustNavigatedHistory] = (0, import_react92.useState)(false);
  const [escPressCount, setEscPressCount] = (0, import_react92.useState)(0);
  const [showEscapePrompt, setShowEscapePrompt] = (0, import_react92.useState)(false);
  const escapeTimerRef = (0, import_react92.useRef)(null);
  const [recentPasteTime, setRecentPasteTime] = (0, import_react92.useState)(null);
  const pasteTimeoutRef = (0, import_react92.useRef)(null);
  const [dirs, setDirs] = (0, import_react92.useState)(
    config.getWorkspaceContext().getDirectories()
  );
  const dirsChanged = config.getWorkspaceContext().getDirectories();
  (0, import_react92.useEffect)(() => {
    if (dirs.length !== dirsChanged.length) {
      setDirs(dirsChanged);
    }
  }, [dirs.length, dirsChanged]);
  const [reverseSearchActive, setReverseSearchActive] = (0, import_react92.useState)(false);
  const [commandSearchActive, setCommandSearchActive] = (0, import_react92.useState)(false);
  const [textBeforeReverseSearch, setTextBeforeReverseSearch] = (0, import_react92.useState)("");
  const [cursorPosition, setCursorPosition] = (0, import_react92.useState)([
    0,
    0
  ]);
  const [expandedSuggestionIndex, setExpandedSuggestionIndex] = (0, import_react92.useState)(-1);
  const shellHistory = useShellHistory(config.getProjectRoot());
  const shellHistoryData = shellHistory.history;
  const completion3 = useCommandCompletion(
    buffer,
    dirs,
    config.getTargetDir(),
    slashCommands,
    commandContext,
    reverseSearchActive,
    config
  );
  const reverseSearchCompletion = useReverseSearchCompletion(
    buffer,
    shellHistoryData,
    reverseSearchActive
  );
  const commandSearchCompletion = useReverseSearchCompletion(
    buffer,
    userMessages,
    commandSearchActive
  );
  const resetCompletionState = completion3.resetCompletionState;
  const resetReverseSearchCompletionState = reverseSearchCompletion.resetCompletionState;
  const resetCommandSearchCompletionState = commandSearchCompletion.resetCompletionState;
  const showCursor = focus && isShellFocused && !isEmbeddedShellFocused;
  const resetEscapeState = (0, import_react92.useCallback)(() => {
    if (escapeTimerRef.current) {
      clearTimeout(escapeTimerRef.current);
      escapeTimerRef.current = null;
    }
    setEscPressCount(0);
    setShowEscapePrompt(false);
  }, []);
  (0, import_react92.useEffect)(() => {
    if (onEscapePromptChange) {
      onEscapePromptChange(showEscapePrompt);
    }
  }, [showEscapePrompt, onEscapePromptChange]);
  (0, import_react92.useEffect)(
    () => () => {
      if (escapeTimerRef.current) {
        clearTimeout(escapeTimerRef.current);
      }
      if (pasteTimeoutRef.current) {
        clearTimeout(pasteTimeoutRef.current);
      }
    },
    []
  );
  const handleSubmitAndClear = (0, import_react92.useCallback)(
    (submittedValue) => {
      if (shellModeActive) {
        shellHistory.addCommandToHistory(submittedValue);
      }
      buffer.setText("");
      onSubmit(submittedValue);
      resetCompletionState();
      resetReverseSearchCompletionState();
    },
    [
      onSubmit,
      buffer,
      resetCompletionState,
      shellModeActive,
      shellHistory,
      resetReverseSearchCompletionState
    ]
  );
  const customSetTextAndResetCompletionSignal = (0, import_react92.useCallback)(
    (newText) => {
      buffer.setText(newText);
      setJustNavigatedHistory(true);
    },
    [buffer, setJustNavigatedHistory]
  );
  const inputHistory = useInputHistory({
    userMessages,
    onSubmit: handleSubmitAndClear,
    isActive: (!completion3.showSuggestions || completion3.suggestions.length === 1) && !shellModeActive,
    currentQuery: buffer.text,
    onChange: customSetTextAndResetCompletionSignal
  });
  (0, import_react92.useEffect)(() => {
    if (justNavigatedHistory) {
      resetCompletionState();
      resetReverseSearchCompletionState();
      resetCommandSearchCompletionState();
      setExpandedSuggestionIndex(-1);
      setJustNavigatedHistory(false);
    }
  }, [
    justNavigatedHistory,
    buffer.text,
    resetCompletionState,
    setJustNavigatedHistory,
    resetReverseSearchCompletionState,
    resetCommandSearchCompletionState
  ]);
  const handleClipboardImage = (0, import_react92.useCallback)(async () => {
    try {
      if (await clipboardHasImage()) {
        const imagePath = await saveClipboardImage(config.getTargetDir());
        if (imagePath) {
          cleanupOldClipboardImages(config.getTargetDir()).catch(() => {
          });
          const relativePath = path75.relative(config.getTargetDir(), imagePath);
          const insertText = `@${relativePath}`;
          const currentText = buffer.text;
          const [row, col] = buffer.cursor;
          let offset = 0;
          for (let i = 0; i < row; i++) {
            offset += buffer.lines[i].length + 1;
          }
          offset += col;
          let textToInsert = insertText;
          const charBefore = offset > 0 ? currentText[offset - 1] : "";
          const charAfter = offset < currentText.length ? currentText[offset] : "";
          if (charBefore && charBefore !== " " && charBefore !== "\n") {
            textToInsert = " " + textToInsert;
          }
          if (!charAfter || charAfter !== " " && charAfter !== "\n") {
            textToInsert = textToInsert + " ";
          }
          buffer.replaceRangeByOffset(offset, offset, textToInsert);
        }
      }
    } catch (error) {
      console.error("Error handling clipboard image:", error);
    }
  }, [buffer, config]);
  const handleInput = (0, import_react92.useCallback)(
    (key) => {
      if (!focus && !key.paste) {
        return;
      }
      if (key.paste) {
        setRecentPasteTime(Date.now());
        if (pasteTimeoutRef.current) {
          clearTimeout(pasteTimeoutRef.current);
        }
        pasteTimeoutRef.current = setTimeout(() => {
          setRecentPasteTime(null);
          pasteTimeoutRef.current = null;
        }, 500);
        buffer.handleInput(key);
        return;
      }
      if (vimHandleInput && vimHandleInput(key)) {
        return;
      }
      if (key.name !== "escape") {
        if (escPressCount > 0 || showEscapePrompt) {
          resetEscapeState();
        }
      }
      if (key.sequence === "!" && buffer.text === "" && !completion3.showSuggestions) {
        setShellModeActive(!shellModeActive);
        buffer.setText("");
        return;
      }
      if (keyMatchers["escape" /* ESCAPE */](key)) {
        const cancelSearch = /* @__PURE__ */ __name((setActive, resetCompletion) => {
          setActive(false);
          resetCompletion();
          buffer.setText(textBeforeReverseSearch);
          const offset = logicalPosToOffset(
            buffer.lines,
            cursorPosition[0],
            cursorPosition[1]
          );
          buffer.moveToOffset(offset);
          setExpandedSuggestionIndex(-1);
        }, "cancelSearch");
        if (reverseSearchActive) {
          cancelSearch(
            setReverseSearchActive,
            reverseSearchCompletion.resetCompletionState
          );
          return;
        }
        if (commandSearchActive) {
          cancelSearch(
            setCommandSearchActive,
            commandSearchCompletion.resetCompletionState
          );
          return;
        }
        if (shellModeActive) {
          setShellModeActive(false);
          resetEscapeState();
          return;
        }
        if (completion3.showSuggestions) {
          completion3.resetCompletionState();
          setExpandedSuggestionIndex(-1);
          resetEscapeState();
          return;
        }
        if (escPressCount === 0) {
          if (buffer.text === "") {
            return;
          }
          setEscPressCount(1);
          setShowEscapePrompt(true);
          if (escapeTimerRef.current) {
            clearTimeout(escapeTimerRef.current);
          }
          escapeTimerRef.current = setTimeout(() => {
            resetEscapeState();
          }, 500);
        } else {
          buffer.setText("");
          resetCompletionState();
          resetEscapeState();
        }
        return;
      }
      if (shellModeActive && keyMatchers["reverseSearch" /* REVERSE_SEARCH */](key)) {
        setReverseSearchActive(true);
        setTextBeforeReverseSearch(buffer.text);
        setCursorPosition(buffer.cursor);
        return;
      }
      if (keyMatchers["clearScreen" /* CLEAR_SCREEN */](key)) {
        onClearScreen();
        return;
      }
      if (reverseSearchActive || commandSearchActive) {
        const isCommandSearch = commandSearchActive;
        const sc = isCommandSearch ? commandSearchCompletion : reverseSearchCompletion;
        const {
          activeSuggestionIndex,
          navigateUp,
          navigateDown,
          showSuggestions,
          suggestions
        } = sc;
        const setActive = isCommandSearch ? setCommandSearchActive : setReverseSearchActive;
        const resetState = sc.resetCompletionState;
        if (showSuggestions) {
          if (keyMatchers["navigationUp" /* NAVIGATION_UP */](key)) {
            navigateUp();
            return;
          }
          if (keyMatchers["navigationDown" /* NAVIGATION_DOWN */](key)) {
            navigateDown();
            return;
          }
          if (keyMatchers["collapseSuggestion" /* COLLAPSE_SUGGESTION */](key)) {
            if (suggestions[activeSuggestionIndex].value.length >= MAX_WIDTH) {
              setExpandedSuggestionIndex(-1);
              return;
            }
          }
          if (keyMatchers["expandSuggestion" /* EXPAND_SUGGESTION */](key)) {
            if (suggestions[activeSuggestionIndex].value.length >= MAX_WIDTH) {
              setExpandedSuggestionIndex(activeSuggestionIndex);
              return;
            }
          }
          if (keyMatchers["acceptSuggestionReverseSearch" /* ACCEPT_SUGGESTION_REVERSE_SEARCH */](key)) {
            sc.handleAutocomplete(activeSuggestionIndex);
            resetState();
            setActive(false);
            return;
          }
        }
        if (keyMatchers["submitReverseSearch" /* SUBMIT_REVERSE_SEARCH */](key)) {
          const textToSubmit = showSuggestions && activeSuggestionIndex > -1 ? suggestions[activeSuggestionIndex].value : buffer.text;
          handleSubmitAndClear(textToSubmit);
          resetState();
          setActive(false);
          return;
        }
        if (keyMatchers["navigationUp" /* NAVIGATION_UP */](key) || keyMatchers["navigationDown" /* NAVIGATION_DOWN */](key)) {
          return;
        }
      }
      if (completion3.isPerfectMatch && keyMatchers["return" /* RETURN */](key)) {
        handleSubmitAndClear(buffer.text);
        return;
      }
      if (completion3.showSuggestions) {
        if (completion3.suggestions.length > 1) {
          if (keyMatchers["completionUp" /* COMPLETION_UP */](key)) {
            completion3.navigateUp();
            setExpandedSuggestionIndex(-1);
            return;
          }
          if (keyMatchers["completionDown" /* COMPLETION_DOWN */](key)) {
            completion3.navigateDown();
            setExpandedSuggestionIndex(-1);
            return;
          }
        }
        if (keyMatchers["acceptSuggestion" /* ACCEPT_SUGGESTION */](key)) {
          if (completion3.suggestions.length > 0) {
            const targetIndex = completion3.activeSuggestionIndex === -1 ? 0 : completion3.activeSuggestionIndex;
            if (targetIndex < completion3.suggestions.length) {
              completion3.handleAutocomplete(targetIndex);
              setExpandedSuggestionIndex(-1);
            }
          }
          return;
        }
      }
      if (!shellModeActive) {
        if (keyMatchers["reverseSearch" /* REVERSE_SEARCH */](key)) {
          setCommandSearchActive(true);
          setTextBeforeReverseSearch(buffer.text);
          setCursorPosition(buffer.cursor);
          return;
        }
        if (keyMatchers["historyUp" /* HISTORY_UP */](key)) {
          inputHistory.navigateUp();
          return;
        }
        if (keyMatchers["historyDown" /* HISTORY_DOWN */](key)) {
          inputHistory.navigateDown();
          return;
        }
        if (keyMatchers["navigationUp" /* NAVIGATION_UP */](key) && (buffer.allVisualLines.length === 1 || buffer.visualCursor[0] === 0 && buffer.visualScrollRow === 0)) {
          inputHistory.navigateUp();
          return;
        }
        if (keyMatchers["navigationDown" /* NAVIGATION_DOWN */](key) && (buffer.allVisualLines.length === 1 || buffer.visualCursor[0] === buffer.allVisualLines.length - 1)) {
          inputHistory.navigateDown();
          return;
        }
      } else {
        if (keyMatchers["navigationUp" /* NAVIGATION_UP */](key)) {
          const prevCommand = shellHistory.getPreviousCommand();
          if (prevCommand !== null) buffer.setText(prevCommand);
          return;
        }
        if (keyMatchers["navigationDown" /* NAVIGATION_DOWN */](key)) {
          const nextCommand = shellHistory.getNextCommand();
          if (nextCommand !== null) buffer.setText(nextCommand);
          return;
        }
      }
      if (keyMatchers["submit" /* SUBMIT */](key)) {
        if (buffer.text.trim()) {
          if (recentPasteTime !== null) {
            return;
          }
          const [row, col] = buffer.cursor;
          const line = buffer.lines[row];
          const charBefore = col > 0 ? cpSlice(line, col - 1, col) : "";
          if (charBefore === "\\") {
            buffer.backspace();
            buffer.newline();
          } else {
            handleSubmitAndClear(buffer.text);
          }
        }
        return;
      }
      if (keyMatchers["newline" /* NEWLINE */](key)) {
        buffer.newline();
        return;
      }
      if (keyMatchers["home" /* HOME */](key)) {
        buffer.move("home");
        return;
      }
      if (keyMatchers["end" /* END */](key)) {
        buffer.move("end");
        return;
      }
      if (keyMatchers["clearInput" /* CLEAR_INPUT */](key)) {
        if (buffer.text.length > 0) {
          buffer.setText("");
          resetCompletionState();
        }
        return;
      }
      if (keyMatchers["killLineRight" /* KILL_LINE_RIGHT */](key)) {
        buffer.killLineRight();
        return;
      }
      if (keyMatchers["killLineLeft" /* KILL_LINE_LEFT */](key)) {
        buffer.killLineLeft();
        return;
      }
      if (keyMatchers["deleteWordBackward" /* DELETE_WORD_BACKWARD */](key)) {
        buffer.deleteWordLeft();
        return;
      }
      if (keyMatchers["openExternalEditor" /* OPEN_EXTERNAL_EDITOR */](key)) {
        buffer.openInExternalEditor();
        return;
      }
      if (keyMatchers["pasteClipboardImage" /* PASTE_CLIPBOARD_IMAGE */](key)) {
        handleClipboardImage();
        return;
      }
      buffer.handleInput(key);
    },
    [
      focus,
      buffer,
      completion3,
      shellModeActive,
      setShellModeActive,
      onClearScreen,
      inputHistory,
      handleSubmitAndClear,
      shellHistory,
      reverseSearchCompletion,
      handleClipboardImage,
      resetCompletionState,
      escPressCount,
      showEscapePrompt,
      resetEscapeState,
      vimHandleInput,
      reverseSearchActive,
      textBeforeReverseSearch,
      cursorPosition,
      recentPasteTime,
      commandSearchActive,
      commandSearchCompletion
    ]
  );
  useKeypress(handleInput, { isActive: !isEmbeddedShellFocused });
  const linesToRender = buffer.viewportVisualLines;
  const [cursorVisualRowAbsolute, cursorVisualColAbsolute] = buffer.visualCursor;
  const scrollVisualRow = buffer.visualScrollRow;
  const getActiveCompletion = /* @__PURE__ */ __name(() => {
    if (commandSearchActive) return commandSearchCompletion;
    if (reverseSearchActive) return reverseSearchCompletion;
    return completion3;
  }, "getActiveCompletion");
  const activeCompletion = getActiveCompletion();
  const shouldShowSuggestions = activeCompletion.showSuggestions;
  const showAutoAcceptStyling = !shellModeActive && approvalMode === ApprovalMode.AUTO_EDIT;
  const showYoloStyling = !shellModeActive && approvalMode === ApprovalMode.YOLO;
  let statusColor;
  let statusText = "";
  if (shellModeActive) {
    statusColor = theme.ui.symbol;
    statusText = "Shell mode";
  } else if (showYoloStyling) {
    statusColor = theme.status.error;
    statusText = "YOLO mode";
  } else if (showAutoAcceptStyling) {
    statusColor = theme.status.warning;
    statusText = "Accepting edits";
  }
  return /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(import_jsx_runtime93.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: isShellFocused && !isEmbeddedShellFocused ? statusColor ?? theme.border.focused : theme.border.default,
        paddingX: 1,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(
            Text,
            {
              color: statusColor ?? theme.text.accent,
              "aria-label": statusText || void 0,
              children: [
                shellModeActive ? reverseSearchActive ? /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(
                  Text,
                  {
                    color: theme.text.link,
                    "aria-label": SCREEN_READER_USER_PREFIX,
                    children: [
                      "(r:)",
                      " "
                    ]
                  }
                ) : "!" : commandSearchActive ? /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text, { color: theme.text.accent, children: "(r:) " }) : showYoloStyling ? "*" : ">",
                " "
              ]
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Box_default, { flexGrow: 1, flexDirection: "column", children: buffer.text.length === 0 && placeholder ? showCursor ? /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Text, { children: [
            import_chalk7.default.inverse(placeholder.slice(0, 1)),
            /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text, { color: theme.text.secondary, children: placeholder.slice(1) })
          ] }) : /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text, { color: theme.text.secondary, children: placeholder }) : linesToRender.map((lineText, visualIdxInRenderedSet) => {
            const absoluteVisualIdx = scrollVisualRow + visualIdxInRenderedSet;
            const mapEntry = buffer.visualToLogicalMap[absoluteVisualIdx];
            const cursorVisualRow = cursorVisualRowAbsolute - scrollVisualRow;
            const isOnCursorLine = focus && visualIdxInRenderedSet === cursorVisualRow;
            const renderedLine = [];
            const [logicalLineIdx, logicalStartCol] = mapEntry;
            const logicalLine = buffer.lines[logicalLineIdx] || "";
            const tokens = parseInputForHighlighting(
              logicalLine,
              logicalLineIdx
            );
            const visualStart = logicalStartCol;
            const visualEnd = logicalStartCol + cpLen(lineText);
            const segments = buildSegmentsForVisualSlice(
              tokens,
              visualStart,
              visualEnd
            );
            let charCount = 0;
            segments.forEach((seg, segIdx) => {
              const segLen = cpLen(seg.text);
              let display = seg.text;
              if (isOnCursorLine) {
                const relativeVisualColForHighlight = cursorVisualColAbsolute;
                const segStart = charCount;
                const segEnd = segStart + segLen;
                if (relativeVisualColForHighlight >= segStart && relativeVisualColForHighlight < segEnd) {
                  const charToHighlight = cpSlice(
                    seg.text,
                    relativeVisualColForHighlight - segStart,
                    relativeVisualColForHighlight - segStart + 1
                  );
                  const highlighted = showCursor ? import_chalk7.default.inverse(charToHighlight) : charToHighlight;
                  display = cpSlice(
                    seg.text,
                    0,
                    relativeVisualColForHighlight - segStart
                  ) + highlighted + cpSlice(
                    seg.text,
                    relativeVisualColForHighlight - segStart + 1
                  );
                }
                charCount = segEnd;
              }
              const color = seg.type === "command" || seg.type === "file" ? theme.text.accent : theme.text.primary;
              renderedLine.push(
                /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text, { color, children: display }, `token-${segIdx}`)
              );
            });
            if (isOnCursorLine && cursorVisualColAbsolute === cpLen(lineText)) {
              renderedLine.push(
                /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text, { children: showCursor ? import_chalk7.default.inverse(" ") : " " }, `cursor-end-${cursorVisualColAbsolute}`)
              );
            }
            return /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Box_default, { height: 1, children: /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text, { children: renderedLine }) }, `line-${visualIdxInRenderedSet}`);
          }) })
        ]
      }
    ),
    shouldShowSuggestions && /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Box_default, { paddingRight: 2, children: /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
      SuggestionsDisplay,
      {
        suggestions: activeCompletion.suggestions,
        activeIndex: activeCompletion.activeSuggestionIndex,
        isLoading: activeCompletion.isLoadingSuggestions,
        width: suggestionsWidth,
        scrollOffset: activeCompletion.visibleStartIndex,
        userInput: buffer.text,
        mode: buffer.text.startsWith("/") && !reverseSearchActive && !commandSearchActive ? "slash" : "reverse",
        expandedIndex: expandedSuggestionIndex
      }
    ) })
  ] });
}, "InputPrompt");

// packages/cli/src/ui/components/Footer.tsx
init_esbuild_shims();

// packages/cli/src/ui/components/ConsoleSummaryDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime94 = __toESM(require_jsx_runtime(), 1);
var ConsoleSummaryDisplay = /* @__PURE__ */ __name(({
  errorCount
}) => {
  if (errorCount === 0) {
    return null;
  }
  const errorIcon = "\u2716";
  return /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Box_default, { children: errorCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)(Text, { color: theme.status.error, children: [
    errorIcon,
    " ",
    errorCount,
    " error",
    errorCount > 1 ? "s" : "",
    " ",
    /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text, { color: theme.text.secondary, children: "(ctrl+o for details)" })
  ] }) });
}, "ConsoleSummaryDisplay");

// packages/cli/src/ui/components/Footer.tsx
import process31 from "node:process";

// packages/cli/src/ui/components/MemoryUsageDisplay.tsx
init_esbuild_shims();
var import_react93 = __toESM(require_react(), 1);
import process30 from "node:process";
var import_jsx_runtime95 = __toESM(require_jsx_runtime(), 1);
var MemoryUsageDisplay = /* @__PURE__ */ __name(() => {
  const [memoryUsage, setMemoryUsage] = (0, import_react93.useState)("");
  const [memoryUsageColor, setMemoryUsageColor] = (0, import_react93.useState)(
    theme.text.secondary
  );
  (0, import_react93.useEffect)(() => {
    const updateMemory = /* @__PURE__ */ __name(() => {
      const usage2 = process30.memoryUsage().rss;
      setMemoryUsage(formatMemoryUsage2(usage2));
      setMemoryUsageColor(
        usage2 >= 2 * 1024 * 1024 * 1024 ? theme.status.error : theme.text.secondary
      );
    }, "updateMemory");
    const intervalId = setInterval(updateMemory, 2e3);
    updateMemory();
    return () => clearInterval(intervalId);
  }, []);
  return /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(Box_default, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text, { color: theme.text.secondary, children: " | " }),
    /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text, { color: memoryUsageColor, children: memoryUsage })
  ] });
}, "MemoryUsageDisplay");

// packages/cli/src/ui/components/ContextUsageDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime96 = __toESM(require_jsx_runtime(), 1);
var ContextUsageDisplay = /* @__PURE__ */ __name(({
  promptTokenCount,
  model,
  terminalWidth
}) => {
  const percentage = promptTokenCount / tokenLimit(model);
  const percentageLeft = ((1 - percentage) * 100).toFixed(0);
  const label = terminalWidth < 100 ? "%" : "% context left";
  return /* @__PURE__ */ (0, import_jsx_runtime96.jsxs)(Text, { color: theme.text.secondary, children: [
    "(",
    percentageLeft,
    label,
    ")"
  ] });
}, "ContextUsageDisplay");

// packages/cli/src/ui/components/DebugProfiler.tsx
init_esbuild_shims();
var import_react94 = __toESM(require_react(), 1);
var import_jsx_runtime97 = __toESM(require_jsx_runtime(), 1);
var DebugProfiler = /* @__PURE__ */ __name(() => {
  const numRenders = (0, import_react94.useRef)(0);
  const [showNumRenders, setShowNumRenders] = (0, import_react94.useState)(false);
  (0, import_react94.useEffect)(() => {
    numRenders.current++;
  });
  useKeypress(
    (key) => {
      if (key.ctrl && key.name === "b") {
        setShowNumRenders((prev) => !prev);
      }
    },
    { isActive: true }
  );
  if (!showNumRenders) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime97.jsxs)(Text, { color: theme.status.warning, children: [
    "Renders: ",
    numRenders.current,
    " "
  ] });
}, "DebugProfiler");

// packages/cli/src/ui/components/Footer.tsx
var import_jsx_runtime98 = __toESM(require_jsx_runtime(), 1);
var Footer = /* @__PURE__ */ __name(() => {
  const uiState = useUIState();
  const config = useConfig();
  const settings = useSettings();
  const { vimEnabled, vimMode } = useVimMode();
  const {
    model,
    targetDir,
    debugMode,
    branchName,
    debugMessage,
    corgiMode,
    errorCount,
    showErrorDetails,
    promptTokenCount,
    nightly,
    isTrustedFolder
  } = {
    model: config.getModel(),
    targetDir: config.getTargetDir(),
    debugMode: config.getDebugMode(),
    branchName: uiState.branchName,
    debugMessage: uiState.debugMessage,
    corgiMode: uiState.corgiMode,
    errorCount: uiState.errorCount,
    showErrorDetails: uiState.showErrorDetails,
    promptTokenCount: uiState.sessionStats.lastPromptTokenCount,
    nightly: uiState.nightly,
    isTrustedFolder: uiState.isTrustedFolder
  };
  const showMemoryUsage = config.getDebugMode() || settings.merged.ui?.showMemoryUsage || false;
  const hideCWD = settings.merged.ui?.footer?.hideCWD || false;
  const hideSandboxStatus = settings.merged.ui?.footer?.hideSandboxStatus || false;
  const hideModelInfo = settings.merged.ui?.footer?.hideModelInfo || false;
  const { columns: terminalWidth } = useTerminalSize();
  const pathLength = Math.max(20, Math.floor(terminalWidth * 0.25));
  const displayPath = shortenPath(tildeifyPath(targetDir), pathLength);
  const justifyContent = hideCWD && hideModelInfo ? "center" : "space-between";
  const displayVimMode = vimEnabled ? vimMode : void 0;
  return /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(
    Box_default,
    {
      justifyContent,
      width: "100%",
      flexDirection: "row",
      alignItems: "center",
      children: [
        (debugMode || displayVimMode || !hideCWD) && /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Box_default, { children: [
          debugMode && /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(DebugProfiler, {}),
          displayVimMode && /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Text, { color: theme.text.secondary, children: [
            "[",
            displayVimMode,
            "] "
          ] }),
          !hideCWD && (nightly ? /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(dist_default4, { colors: theme.ui.gradient, children: /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Text, { children: [
            displayPath,
            branchName && /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Text, { children: [
              " (",
              branchName,
              "*)"
            ] })
          ] }) }) : /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Text, { color: theme.text.link, children: [
            displayPath,
            branchName && /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Text, { color: theme.text.secondary, children: [
              " (",
              branchName,
              "*)"
            ] })
          ] })),
          debugMode && /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text, { color: theme.status.error, children: " " + (debugMessage || "--debug") })
        ] }),
        !hideSandboxStatus && /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(
          Box_default,
          {
            flexGrow: 1,
            alignItems: "center",
            justifyContent: "center",
            display: "flex",
            children: isTrustedFolder === false ? /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text, { color: theme.status.warning, children: "untrusted" }) : process31.env["SANDBOX"] && process31.env["SANDBOX"] !== "sandbox-exec" ? /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text, { color: "green", children: process31.env["SANDBOX"].replace(/^gemini-(?:cli-)?/, "") }) : process31.env["SANDBOX"] === "sandbox-exec" ? /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Text, { color: theme.status.warning, children: [
              "macOS Seatbelt",
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Text, { color: theme.text.secondary, children: [
                "(",
                process31.env["SEATBELT_PROFILE"],
                ")"
              ] })
            ] }) : /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Text, { color: theme.status.error, children: [
              "no sandbox",
              terminalWidth >= 100 && /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text, { color: theme.text.secondary, children: " (see /docs)" })
            ] })
          }
        ),
        !hideModelInfo && /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Box_default, { alignItems: "center", justifyContent: "flex-end", children: [
          /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Box_default, { alignItems: "center", children: [
            /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Text, { color: theme.text.accent, children: [
              model,
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(
                ContextUsageDisplay,
                {
                  promptTokenCount,
                  model,
                  terminalWidth
                }
              )
            ] }),
            showMemoryUsage && /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(MemoryUsageDisplay, {})
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Box_default, { alignItems: "center", paddingLeft: 2, children: [
            corgiMode && /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Text, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text, { color: theme.ui.symbol, children: "| " }),
              /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text, { color: theme.status.error, children: "\u25BC" }),
              /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text, { color: theme.text.primary, children: "(\xB4" }),
              /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text, { color: theme.status.error, children: "\u1D25" }),
              /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text, { color: theme.text.primary, children: "`)" }),
              /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text, { color: theme.status.error, children: "\u25BC " })
            ] }),
            !showErrorDetails && errorCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Box_default, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text, { color: theme.ui.symbol, children: "| " }),
              /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(ConsoleSummaryDisplay, { errorCount })
            ] })
          ] })
        ] })
      ]
    }
  );
}, "Footer");

// packages/cli/src/ui/components/QueuedMessageDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime99 = __toESM(require_jsx_runtime(), 1);
var MAX_DISPLAYED_QUEUED_MESSAGES = 3;
var QueuedMessageDisplay = /* @__PURE__ */ __name(({
  messageQueue
}) => {
  if (messageQueue.length === 0) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
    messageQueue.slice(0, MAX_DISPLAYED_QUEUED_MESSAGES).map((message, index) => {
      const preview = message.replace(/\s+/g, " ");
      return /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Box_default, { paddingLeft: 2, width: "100%", children: /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text, { dimColor: true, wrap: "truncate", children: preview }) }, index);
    }),
    messageQueue.length > MAX_DISPLAYED_QUEUED_MESSAGES && /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Box_default, { paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Text, { dimColor: true, children: [
      "... (+",
      messageQueue.length - MAX_DISPLAYED_QUEUED_MESSAGES,
      " more)"
    ] }) })
  ] });
}, "QueuedMessageDisplay");

// packages/cli/src/ui/components/ConfigInitDisplay.tsx
init_esbuild_shims();
var import_react95 = __toESM(require_react(), 1);

// packages/cli/src/utils/events.ts
init_esbuild_shims();
import { EventEmitter as EventEmitter8 } from "node:events";
var appEvents = new EventEmitter8();

// packages/cli/src/ui/components/ConfigInitDisplay.tsx
var import_jsx_runtime100 = __toESM(require_jsx_runtime(), 1);
var ConfigInitDisplay = /* @__PURE__ */ __name(() => {
  const config = useConfig();
  const [message, setMessage] = (0, import_react95.useState)("Initializing...");
  (0, import_react95.useEffect)(() => {
    const onChange = /* @__PURE__ */ __name((clients) => {
      if (!clients || clients.size === 0) {
        setMessage(`Initializing...`);
        return;
      }
      let connected = 0;
      for (const client of clients.values()) {
        if (client.getStatus() === MCPServerStatus.CONNECTED) {
          connected++;
        }
      }
      setMessage(`Connecting to MCP servers... (${connected}/${clients.size})`);
    }, "onChange");
    appEvents.on("mcp-client-update", onChange);
    return () => {
      appEvents.off("mcp-client-update", onChange);
    };
  }, [config]);
  return /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(Text, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(GeminiSpinner, {}),
    " ",
    /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text, { color: theme.text.primary, children: message })
  ] }) });
}, "ConfigInitDisplay");

// packages/cli/src/ui/components/Composer.tsx
var import_jsx_runtime101 = __toESM(require_jsx_runtime(), 1);
var Composer = /* @__PURE__ */ __name(() => {
  const config = useConfig();
  const settings = useSettings();
  const isScreenReaderEnabled = use_is_screen_reader_enabled_default();
  const uiState = useUIState();
  const uiActions = useUIActions();
  const { vimEnabled } = useVimMode();
  const terminalWidth = process.stdout.columns;
  const isNarrow = isNarrowWidth(terminalWidth);
  const debugConsoleMaxHeight = Math.floor(Math.max(terminalWidth * 0.2, 5));
  const { contextFileNames, showAutoAcceptIndicator } = uiState;
  const { containerWidth } = (0, import_react96.useMemo)(
    () => calculatePromptWidths(uiState.terminalWidth),
    [uiState.terminalWidth]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime101.jsxs)(Box_default, { flexDirection: "column", children: [
    !uiState.embeddedShellFocused && /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(
      LoadingIndicator,
      {
        thought: uiState.streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */ || config.getAccessibility()?.disableLoadingPhrases ? void 0 : uiState.thought,
        currentLoadingPhrase: config.getAccessibility()?.disableLoadingPhrases ? void 0 : uiState.currentLoadingPhrase,
        elapsedTime: uiState.elapsedTime
      }
    ),
    !uiState.isConfigInitialized && /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(ConfigInitDisplay, {}),
    /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(QueuedMessageDisplay, { messageQueue: uiState.messageQueue }),
    /* @__PURE__ */ (0, import_jsx_runtime101.jsxs)(
      Box_default,
      {
        marginTop: 1,
        justifyContent: settings.merged.ui?.hideContextSummary ? "flex-start" : "space-between",
        width: "100%",
        flexDirection: isNarrow ? "column" : "row",
        alignItems: isNarrow ? "flex-start" : "center",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime101.jsxs)(Box_default, { marginRight: 1, children: [
            process.env["GEMINI_SYSTEM_MD"] && /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(Text, { color: theme.status.error, children: "|\u2310\u25A0_\u25A0| " }),
            uiState.ctrlCPressedOnce ? /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(Text, { color: theme.status.warning, children: "Press Ctrl+C again to exit." }) : uiState.ctrlDPressedOnce ? /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(Text, { color: theme.status.warning, children: "Press Ctrl+D again to exit." }) : uiState.showEscapePrompt ? /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(Text, { color: theme.text.secondary, children: "Press Esc again to clear." }) : !settings.merged.ui?.hideContextSummary && /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(
              ContextSummaryDisplay,
              {
                ideContext: uiState.ideContextState,
                geminiMdFileCount: uiState.geminiMdFileCount,
                contextFileNames,
                mcpServers: config.getMcpServers(),
                blockedMcpServers: config.getBlockedMcpServers(),
                showToolDescriptions: uiState.showToolDescriptions
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime101.jsxs)(Box_default, { paddingTop: isNarrow ? 1 : 0, children: [
            showAutoAcceptIndicator !== ApprovalMode.DEFAULT && !uiState.shellModeActive && /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(AutoAcceptIndicator, { approvalMode: showAutoAcceptIndicator }),
            uiState.shellModeActive && /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(ShellModeIndicator, {})
          ] })
        ]
      }
    ),
    uiState.showErrorDetails && /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(OverflowProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime101.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(
        DetailedMessagesDisplay,
        {
          messages: uiState.filteredConsoleMessages,
          maxHeight: uiState.constrainHeight ? debugConsoleMaxHeight : void 0,
          width: containerWidth
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(ShowMoreLines, { constrainHeight: uiState.constrainHeight })
    ] }) }),
    uiState.isInputActive && /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(
      InputPrompt,
      {
        buffer: uiState.buffer,
        inputWidth: uiState.inputWidth,
        suggestionsWidth: uiState.suggestionsWidth,
        onSubmit: uiActions.handleFinalSubmit,
        userMessages: uiState.userMessages,
        onClearScreen: uiActions.handleClearScreen,
        config,
        slashCommands: uiState.slashCommands,
        commandContext: uiState.commandContext,
        shellModeActive: uiState.shellModeActive,
        setShellModeActive: uiActions.setShellModeActive,
        approvalMode: showAutoAcceptIndicator,
        onEscapePromptChange: uiActions.onEscapePromptChange,
        focus: true,
        vimHandleInput: uiActions.vimHandleInput,
        isEmbeddedShellFocused: uiState.embeddedShellFocused,
        placeholder: vimEnabled ? "  Press 'i' for INSERT mode and 'Esc' for NORMAL mode." : "  Type your message or @path/to/file"
      }
    ),
    !settings.merged.ui?.hideFooter && !isScreenReaderEnabled && /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(Footer, {})
  ] });
}, "Composer");

// packages/cli/src/ui/components/ExitWarning.tsx
init_esbuild_shims();
var import_jsx_runtime102 = __toESM(require_jsx_runtime(), 1);
var ExitWarning = /* @__PURE__ */ __name(() => {
  const uiState = useUIState();
  return /* @__PURE__ */ (0, import_jsx_runtime102.jsxs)(import_jsx_runtime102.Fragment, { children: [
    uiState.dialogsVisible && uiState.ctrlCPressedOnce && /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(Text, { color: theme.status.warning, children: "Press Ctrl+C again to exit." }) }),
    uiState.dialogsVisible && uiState.ctrlDPressedOnce && /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(Text, { color: theme.status.warning, children: "Press Ctrl+D again to exit." }) })
  ] });
}, "ExitWarning");

// packages/cli/src/ui/layouts/ScreenReaderAppLayout.tsx
var import_jsx_runtime103 = __toESM(require_jsx_runtime(), 1);
var ScreenReaderAppLayout = /* @__PURE__ */ __name(() => {
  const uiState = useUIState();
  return /* @__PURE__ */ (0, import_jsx_runtime103.jsxs)(Box_default, { flexDirection: "column", width: "90%", height: "100%", children: [
    /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Notifications, {}),
    /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Footer, {}),
    /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Box_default, { flexGrow: 1, overflow: "hidden", children: /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(MainContent, {}) }),
    uiState.dialogsVisible ? /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(
      DialogManager,
      {
        terminalWidth: uiState.terminalWidth,
        addItem: uiState.historyManager.addItem
      }
    ) : /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Composer, {}),
    /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(ExitWarning, {})
  ] });
}, "ScreenReaderAppLayout");

// packages/cli/src/ui/layouts/DefaultAppLayout.tsx
init_esbuild_shims();
var import_jsx_runtime104 = __toESM(require_jsx_runtime(), 1);
var DefaultAppLayout = /* @__PURE__ */ __name(({
  width = "90%"
}) => {
  const uiState = useUIState();
  return /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)(Box_default, { flexDirection: "column", width, children: [
    /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(MainContent, {}),
    /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)(Box_default, { flexDirection: "column", ref: uiState.mainControlsRef, children: [
      /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Notifications, {}),
      uiState.dialogsVisible ? /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
        DialogManager,
        {
          terminalWidth: uiState.terminalWidth,
          addItem: uiState.historyManager.addItem
        }
      ) : /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Composer, {}),
      /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(ExitWarning, {})
    ] })
  ] });
}, "DefaultAppLayout");

// packages/cli/src/ui/App.tsx
var import_jsx_runtime105 = __toESM(require_jsx_runtime(), 1);
var getContainerWidth = /* @__PURE__ */ __name((terminalWidth) => {
  if (terminalWidth <= 80) {
    return "98%";
  }
  if (terminalWidth >= 132) {
    return "90%";
  }
  const t2 = (terminalWidth - 80) / (132 - 80);
  const percentage = lerp(98, 90, t2);
  return `${Math.round(percentage)}%`;
}, "getContainerWidth");
var App2 = /* @__PURE__ */ __name(() => {
  const uiState = useUIState();
  const isScreenReaderEnabled = use_is_screen_reader_enabled_default();
  const { columns } = useTerminalSize();
  const containerWidth = getContainerWidth(columns);
  if (uiState.quittingMessages) {
    return /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(QuittingDisplay, {});
  }
  return /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(StreamingContext.Provider, { value: uiState.streamingState, children: isScreenReaderEnabled ? /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(ScreenReaderAppLayout, {}) : /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(DefaultAppLayout, { width: containerWidth }) });
}, "App");

// packages/cli/src/config/auth.ts
init_esbuild_shims();
function validateAuthMethod(authMethod) {
  const settings = loadSettings();
  loadEnvironment(settings.merged);
  if (authMethod === AuthType2.USE_OPENAI) {
    const hasApiKey = process.env["OPENAI_API_KEY"] || settings.merged.security?.auth?.apiKey;
    if (!hasApiKey) {
      return "OPENAI_API_KEY environment variable not found. You can enter it interactively or add it to your .env file.";
    }
    return null;
  }
  if (authMethod === AuthType2.QWEN_OAUTH) {
    return null;
  }
  return "Invalid auth method selected.";
}
__name(validateAuthMethod, "validateAuthMethod");

// packages/cli/src/config/config.ts
init_esbuild_shims();

// packages/cli/src/commands/extensions.tsx
init_esbuild_shims();

// packages/cli/src/commands/extensions/install.ts
init_esbuild_shims();
import { stat as stat3 } from "node:fs/promises";
async function handleInstall(args) {
  try {
    let installMetadata;
    const { source: source2 } = args;
    if (source2.startsWith("http://") || source2.startsWith("https://") || source2.startsWith("git@") || source2.startsWith("sso://")) {
      installMetadata = {
        source: source2,
        type: "git",
        ref: args.ref,
        autoUpdate: args.autoUpdate
      };
    } else {
      if (args.ref || args.autoUpdate) {
        throw new Error(
          "--ref and --auto-update are not applicable for local extensions."
        );
      }
      try {
        await stat3(source2);
        installMetadata = {
          source: source2,
          type: "local"
        };
      } catch {
        throw new Error("Install source not found.");
      }
    }
    const name3 = await installExtension(
      installMetadata,
      requestConsentNonInteractive
    );
    console.log(`Extension "${name3}" installed successfully and enabled.`);
  } catch (error) {
    console.error(getErrorMessage3(error));
    process.exit(1);
  }
}
__name(handleInstall, "handleInstall");
var installCommand = {
  command: "install <source>",
  describe: "Installs an extension from a git repository URL or a local path.",
  builder: /* @__PURE__ */ __name((yargs) => yargs.positional("source", {
    describe: "The github URL or local path of the extension to install.",
    type: "string",
    demandOption: true
  }).option("ref", {
    describe: "The git ref to install from.",
    type: "string"
  }).option("auto-update", {
    describe: "Enable auto-update for this extension.",
    type: "boolean"
  }).check((argv) => {
    if (!argv.source) {
      throw new Error("The source argument must be provided.");
    }
    return true;
  }), "builder"),
  handler: /* @__PURE__ */ __name(async (argv) => {
    await handleInstall({
      source: argv["source"],
      ref: argv["ref"],
      autoUpdate: argv["auto-update"]
    });
  }, "handler")
};

// packages/cli/src/commands/extensions/uninstall.ts
init_esbuild_shims();
async function handleUninstall(args) {
  try {
    await uninstallExtension(args.name);
    console.log(`Extension "${args.name}" successfully uninstalled.`);
  } catch (error) {
    console.error(getErrorMessage3(error));
    process.exit(1);
  }
}
__name(handleUninstall, "handleUninstall");
var uninstallCommand = {
  command: "uninstall <name>",
  describe: "Uninstalls an extension.",
  builder: /* @__PURE__ */ __name((yargs) => yargs.positional("name", {
    describe: "The name or source path of the extension to uninstall.",
    type: "string"
  }).check((argv) => {
    if (!argv.name) {
      throw new Error(
        "Please include the name of the extension to uninstall as a positional argument."
      );
    }
    return true;
  }), "builder"),
  handler: /* @__PURE__ */ __name(async (argv) => {
    await handleUninstall({
      name: argv["name"]
    });
  }, "handler")
};

// packages/cli/src/commands/extensions/list.ts
init_esbuild_shims();
async function handleList() {
  try {
    const extensions = loadUserExtensions();
    if (extensions.length === 0) {
      console.log("No extensions installed.");
      return;
    }
    console.log(
      extensions.map((extension, _) => toOutputString(extension, process.cwd())).join("\n\n")
    );
  } catch (error) {
    console.error(getErrorMessage3(error));
    process.exit(1);
  }
}
__name(handleList, "handleList");
var listCommand = {
  command: "list",
  describe: "Lists installed extensions.",
  builder: /* @__PURE__ */ __name((yargs) => yargs, "builder"),
  handler: /* @__PURE__ */ __name(async () => {
    await handleList();
  }, "handler")
};

// packages/cli/src/commands/extensions/update.ts
init_esbuild_shims();

// packages/cli/src/config/extensions/update.ts
init_esbuild_shims();
import * as fs73 from "node:fs";
async function updateExtension(extension, cwd7 = process.cwd(), requestConsent, currentState, dispatchExtensionStateUpdate) {
  if (currentState === "updating" /* UPDATING */) {
    return void 0;
  }
  dispatchExtensionStateUpdate({
    type: "SET_STATE",
    payload: { name: extension.name, state: "updating" /* UPDATING */ }
  });
  const installMetadata = loadInstallMetadata(extension.path);
  if (!installMetadata?.type) {
    dispatchExtensionStateUpdate({
      type: "SET_STATE",
      payload: { name: extension.name, state: "error" /* ERROR */ }
    });
    throw new Error(
      `Extension ${extension.name} cannot be updated, type is unknown.`
    );
  }
  if (installMetadata?.type === "link") {
    dispatchExtensionStateUpdate({
      type: "SET_STATE",
      payload: { name: extension.name, state: "up to date" /* UP_TO_DATE */ }
    });
    throw new Error(`Extension is linked so does not need to be updated`);
  }
  const originalVersion = extension.version;
  const tempDir = await ExtensionStorage.createTmpDir();
  try {
    await copyExtension(extension.path, tempDir);
    const previousExtensionConfig = await loadExtensionConfig({
      extensionDir: extension.path,
      workspaceDir: cwd7
    });
    await uninstallExtension(extension.name, cwd7);
    await installExtension(
      installMetadata,
      requestConsent,
      cwd7,
      previousExtensionConfig
    );
    const updatedExtensionStorage = new ExtensionStorage(extension.name);
    const updatedExtension = loadExtension({
      extensionDir: updatedExtensionStorage.getExtensionDir(),
      workspaceDir: cwd7
    });
    if (!updatedExtension) {
      dispatchExtensionStateUpdate({
        type: "SET_STATE",
        payload: { name: extension.name, state: "error" /* ERROR */ }
      });
      throw new Error("Updated extension not found after installation.");
    }
    const updatedVersion = updatedExtension.config.version;
    dispatchExtensionStateUpdate({
      type: "SET_STATE",
      payload: {
        name: extension.name,
        state: "updated, needs restart" /* UPDATED_NEEDS_RESTART */
      }
    });
    return {
      name: extension.name,
      originalVersion,
      updatedVersion
    };
  } catch (e2) {
    console.error(
      `Error updating extension, rolling back. ${getErrorMessage3(e2)}`
    );
    dispatchExtensionStateUpdate({
      type: "SET_STATE",
      payload: { name: extension.name, state: "error" /* ERROR */ }
    });
    await copyExtension(tempDir, extension.path);
    throw e2;
  } finally {
    await fs73.promises.rm(tempDir, { recursive: true, force: true });
  }
}
__name(updateExtension, "updateExtension");
async function updateAllUpdatableExtensions(cwd7 = process.cwd(), requestConsent, extensions, extensionsState, dispatch) {
  return (await Promise.all(
    extensions.filter(
      (extension) => extensionsState.get(extension.name)?.status === "update available" /* UPDATE_AVAILABLE */
    ).map(
      (extension) => updateExtension(
        extension,
        cwd7,
        requestConsent,
        extensionsState.get(extension.name).status,
        dispatch
      )
    )
  )).filter((updateInfo) => !!updateInfo);
}
__name(updateAllUpdatableExtensions, "updateAllUpdatableExtensions");
async function checkForAllExtensionUpdates(extensions, dispatch) {
  dispatch({ type: "BATCH_CHECK_START" });
  const promises6 = [];
  for (const extension of extensions) {
    if (!extension.installMetadata) {
      dispatch({
        type: "SET_STATE",
        payload: {
          name: extension.name,
          state: "not updatable" /* NOT_UPDATABLE */
        }
      });
      continue;
    }
    promises6.push(
      checkForExtensionUpdate(extension, (updatedState) => {
        dispatch({
          type: "SET_STATE",
          payload: { name: extension.name, state: updatedState }
        });
      })
    );
  }
  await Promise.all(promises6);
  dispatch({ type: "BATCH_CHECK_END" });
}
__name(checkForAllExtensionUpdates, "checkForAllExtensionUpdates");

// packages/cli/src/commands/extensions/update.ts
var updateOutput = /* @__PURE__ */ __name((info) => `Extension "${info.name}" successfully updated: ${info.originalVersion} \u2192 ${info.updatedVersion}.`, "updateOutput");
async function handleUpdate(args) {
  const workingDir = process.cwd();
  const extensionEnablementManager = new ExtensionEnablementManager(
    ExtensionStorage.getUserExtensionsDir(),
    // Force enable named extensions, otherwise we will only update the enabled
    // ones.
    args.name ? [args.name] : []
  );
  const allExtensions = loadExtensions(extensionEnablementManager);
  const extensions = annotateActiveExtensions(
    allExtensions,
    workingDir,
    extensionEnablementManager
  );
  if (args.name) {
    try {
      const extension = extensions.find(
        (extension2) => extension2.name === args.name
      );
      if (!extension) {
        console.log(`Extension "${args.name}" not found.`);
        return;
      }
      let updateState;
      if (!extension.installMetadata) {
        console.log(
          `Unable to install extension "${args.name}" due to missing install metadata`
        );
        return;
      }
      await checkForExtensionUpdate(extension, (newState) => {
        updateState = newState;
      });
      if (updateState !== "update available" /* UPDATE_AVAILABLE */) {
        console.log(`Extension "${args.name}" is already up to date.`);
        return;
      }
      const updatedExtensionInfo = await updateExtension(
        extension,
        workingDir,
        requestConsentNonInteractive,
        updateState,
        () => {
        }
      );
      if (updatedExtensionInfo.originalVersion !== updatedExtensionInfo.updatedVersion) {
        console.log(
          `Extension "${args.name}" successfully updated: ${updatedExtensionInfo.originalVersion} \u2192 ${updatedExtensionInfo.updatedVersion}.`
        );
      } else {
        console.log(`Extension "${args.name}" is already up to date.`);
      }
    } catch (error) {
      console.error(getErrorMessage3(error));
    }
  }
  if (args.all) {
    try {
      const extensionState = /* @__PURE__ */ new Map();
      await checkForAllExtensionUpdates(extensions, (action) => {
        if (action.type === "SET_STATE") {
          extensionState.set(action.payload.name, {
            status: action.payload.state,
            processed: true
            // No need to process as we will force the update.
          });
        }
      });
      let updateInfos = await updateAllUpdatableExtensions(
        workingDir,
        requestConsentNonInteractive,
        extensions,
        extensionState,
        () => {
        }
      );
      updateInfos = updateInfos.filter(
        (info) => info.originalVersion !== info.updatedVersion
      );
      if (updateInfos.length === 0) {
        console.log("No extensions to update.");
        return;
      }
      console.log(updateInfos.map((info) => updateOutput(info)).join("\n"));
    } catch (error) {
      console.error(getErrorMessage3(error));
    }
  }
}
__name(handleUpdate, "handleUpdate");
var updateCommand = {
  command: "update [<name>] [--all]",
  describe: "Updates all extensions or a named extension to the latest version.",
  builder: /* @__PURE__ */ __name((yargs) => yargs.positional("name", {
    describe: "The name of the extension to update.",
    type: "string"
  }).option("all", {
    describe: "Update all extensions.",
    type: "boolean"
  }).conflicts("name", "all").check((argv) => {
    if (!argv.all && !argv.name) {
      throw new Error("Either an extension name or --all must be provided");
    }
    return true;
  }), "builder"),
  handler: /* @__PURE__ */ __name(async (argv) => {
    await handleUpdate({
      name: argv["name"],
      all: argv["all"]
    });
  }, "handler")
};

// packages/cli/src/commands/extensions/disable.ts
init_esbuild_shims();

// node_modules/yargs/index.mjs
init_esbuild_shims();

// node_modules/yargs/lib/platform-shims/esm.mjs
init_esbuild_shims();
import { notStrictEqual, strictEqual } from "assert";

// node_modules/cliui/index.mjs
init_esbuild_shims();

// node_modules/cliui/build/lib/index.js
init_esbuild_shims();
var align = {
  right: alignRight,
  center: alignCenter
};
var top = 0;
var right2 = 1;
var bottom = 2;
var left2 = 3;
var UI = class {
  static {
    __name(this, "UI");
  }
  constructor(opts) {
    var _a6;
    this.width = opts.width;
    this.wrap = (_a6 = opts.wrap) !== null && _a6 !== void 0 ? _a6 : true;
    this.rows = [];
  }
  span(...args) {
    const cols = this.div(...args);
    cols.span = true;
  }
  resetOutput() {
    this.rows = [];
  }
  div(...args) {
    if (args.length === 0) {
      this.div("");
    }
    if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === "string") {
      return this.applyLayoutDSL(args[0]);
    }
    const cols = args.map((arg) => {
      if (typeof arg === "string") {
        return this.colFromString(arg);
      }
      return arg;
    });
    this.rows.push(cols);
    return cols;
  }
  shouldApplyLayoutDSL(...args) {
    return args.length === 1 && typeof args[0] === "string" && /[\t\n]/.test(args[0]);
  }
  applyLayoutDSL(str2) {
    const rows = str2.split("\n").map((row) => row.split("	"));
    let leftColumnWidth = 0;
    rows.forEach((columns) => {
      if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) {
        leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0]));
      }
    });
    rows.forEach((columns) => {
      this.div(...columns.map((r3, i) => {
        return {
          text: r3.trim(),
          padding: this.measurePadding(r3),
          width: i === 0 && columns.length > 1 ? leftColumnWidth : void 0
        };
      }));
    });
    return this.rows[this.rows.length - 1];
  }
  colFromString(text) {
    return {
      text,
      padding: this.measurePadding(text)
    };
  }
  measurePadding(str2) {
    const noAnsi = mixin.stripAnsi(str2);
    return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
  }
  toString() {
    const lines = [];
    this.rows.forEach((row) => {
      this.rowToString(row, lines);
    });
    return lines.filter((line) => !line.hidden).map((line) => line.text).join("\n");
  }
  rowToString(row, lines) {
    this.rasterize(row).forEach((rrow, r3) => {
      let str2 = "";
      rrow.forEach((col, c3) => {
        const { width } = row[c3];
        const wrapWidth = this.negatePadding(row[c3]);
        let ts = col;
        if (wrapWidth > mixin.stringWidth(col)) {
          ts += " ".repeat(wrapWidth - mixin.stringWidth(col));
        }
        if (row[c3].align && row[c3].align !== "left" && this.wrap) {
          const fn = align[row[c3].align];
          ts = fn(ts, wrapWidth);
          if (mixin.stringWidth(ts) < wrapWidth) {
            ts += " ".repeat((width || 0) - mixin.stringWidth(ts) - 1);
          }
        }
        const padding = row[c3].padding || [0, 0, 0, 0];
        if (padding[left2]) {
          str2 += " ".repeat(padding[left2]);
        }
        str2 += addBorder(row[c3], ts, "| ");
        str2 += ts;
        str2 += addBorder(row[c3], ts, " |");
        if (padding[right2]) {
          str2 += " ".repeat(padding[right2]);
        }
        if (r3 === 0 && lines.length > 0) {
          str2 = this.renderInline(str2, lines[lines.length - 1]);
        }
      });
      lines.push({
        text: str2.replace(/ +$/, ""),
        span: row.span
      });
    });
    return lines;
  }
  // if the full 'source' can render in
  // the target line, do so.
  renderInline(source2, previousLine) {
    const match2 = source2.match(/^ */);
    const leadingWhitespace = match2 ? match2[0].length : 0;
    const target = previousLine.text;
    const targetTextWidth = mixin.stringWidth(target.trimRight());
    if (!previousLine.span) {
      return source2;
    }
    if (!this.wrap) {
      previousLine.hidden = true;
      return target + source2;
    }
    if (leadingWhitespace < targetTextWidth) {
      return source2;
    }
    previousLine.hidden = true;
    return target.trimRight() + " ".repeat(leadingWhitespace - targetTextWidth) + source2.trimLeft();
  }
  rasterize(row) {
    const rrows = [];
    const widths = this.columnWidths(row);
    let wrapped;
    row.forEach((col, c3) => {
      col.width = widths[c3];
      if (this.wrap) {
        wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split("\n");
      } else {
        wrapped = col.text.split("\n");
      }
      if (col.border) {
        wrapped.unshift("." + "-".repeat(this.negatePadding(col) + 2) + ".");
        wrapped.push("'" + "-".repeat(this.negatePadding(col) + 2) + "'");
      }
      if (col.padding) {
        wrapped.unshift(...new Array(col.padding[top] || 0).fill(""));
        wrapped.push(...new Array(col.padding[bottom] || 0).fill(""));
      }
      wrapped.forEach((str2, r3) => {
        if (!rrows[r3]) {
          rrows.push([]);
        }
        const rrow = rrows[r3];
        for (let i = 0; i < c3; i++) {
          if (rrow[i] === void 0) {
            rrow.push("");
          }
        }
        rrow.push(str2);
      });
    });
    return rrows;
  }
  negatePadding(col) {
    let wrapWidth = col.width || 0;
    if (col.padding) {
      wrapWidth -= (col.padding[left2] || 0) + (col.padding[right2] || 0);
    }
    if (col.border) {
      wrapWidth -= 4;
    }
    return wrapWidth;
  }
  columnWidths(row) {
    if (!this.wrap) {
      return row.map((col) => {
        return col.width || mixin.stringWidth(col.text);
      });
    }
    let unset = row.length;
    let remainingWidth = this.width;
    const widths = row.map((col) => {
      if (col.width) {
        unset--;
        remainingWidth -= col.width;
        return col.width;
      }
      return void 0;
    });
    const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
    return widths.map((w, i) => {
      if (w === void 0) {
        return Math.max(unsetWidth, _minWidth(row[i]));
      }
      return w;
    });
  }
};
function addBorder(col, ts, style) {
  if (col.border) {
    if (/[.']-+[.']/.test(ts)) {
      return "";
    }
    if (ts.trim().length !== 0) {
      return style;
    }
    return "  ";
  }
  return "";
}
__name(addBorder, "addBorder");
function _minWidth(col) {
  const padding = col.padding || [];
  const minWidth = 1 + (padding[left2] || 0) + (padding[right2] || 0);
  if (col.border) {
    return minWidth + 4;
  }
  return minWidth;
}
__name(_minWidth, "_minWidth");
function getWindowWidth() {
  if (typeof process === "object" && process.stdout && process.stdout.columns) {
    return process.stdout.columns;
  }
  return 80;
}
__name(getWindowWidth, "getWindowWidth");
function alignRight(str2, width) {
  str2 = str2.trim();
  const strWidth = mixin.stringWidth(str2);
  if (strWidth < width) {
    return " ".repeat(width - strWidth) + str2;
  }
  return str2;
}
__name(alignRight, "alignRight");
function alignCenter(str2, width) {
  str2 = str2.trim();
  const strWidth = mixin.stringWidth(str2);
  if (strWidth >= width) {
    return str2;
  }
  return " ".repeat(width - strWidth >> 1) + str2;
}
__name(alignCenter, "alignCenter");
var mixin;
function cliui(opts, _mixin) {
  mixin = _mixin;
  return new UI({
    width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
    wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
  });
}
__name(cliui, "cliui");

// node_modules/cliui/build/lib/string-utils.js
init_esbuild_shims();
var ansi = new RegExp("\x1B(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)", "g");
function stripAnsi2(str2) {
  return str2.replace(ansi, "");
}
__name(stripAnsi2, "stripAnsi");
function wrap(str2, width) {
  const [start, end] = str2.match(ansi) || ["", ""];
  str2 = stripAnsi2(str2);
  let wrapped = "";
  for (let i = 0; i < str2.length; i++) {
    if (i !== 0 && i % width === 0) {
      wrapped += "\n";
    }
    wrapped += str2.charAt(i);
  }
  if (start && end) {
    wrapped = `${start}${wrapped}${end}`;
  }
  return wrapped;
}
__name(wrap, "wrap");

// node_modules/cliui/index.mjs
function ui(opts) {
  return cliui(opts, {
    stringWidth: /* @__PURE__ */ __name((str2) => {
      return [...str2].length;
    }, "stringWidth"),
    stripAnsi: stripAnsi2,
    wrap
  });
}
__name(ui, "ui");

// node_modules/escalade/sync/index.mjs
init_esbuild_shims();
import { dirname as dirname19, resolve as resolve17 } from "path";
import { readdirSync as readdirSync3, statSync as statSync3 } from "fs";
function sync_default(start, callback) {
  let dir = resolve17(".", start);
  let tmp, stats = statSync3(dir);
  if (!stats.isDirectory()) {
    dir = dirname19(dir);
  }
  while (true) {
    tmp = callback(dir, readdirSync3(dir));
    if (tmp) return resolve17(dir, tmp);
    dir = dirname19(tmp = dir);
    if (tmp === dir) break;
  }
}
__name(sync_default, "default");

// node_modules/yargs/lib/platform-shims/esm.mjs
import { inspect } from "util";
import { readFileSync as readFileSync13 } from "fs";
import { fileURLToPath as fileURLToPath6 } from "url";

// node_modules/yargs-parser/build/lib/index.js
init_esbuild_shims();
import { format } from "util";
import { normalize as normalize7, resolve as resolve18 } from "path";

// node_modules/yargs-parser/build/lib/string-utils.js
init_esbuild_shims();
function camelCase(str2) {
  const isCamelCase = str2 !== str2.toLowerCase() && str2 !== str2.toUpperCase();
  if (!isCamelCase) {
    str2 = str2.toLowerCase();
  }
  if (str2.indexOf("-") === -1 && str2.indexOf("_") === -1) {
    return str2;
  } else {
    let camelcase = "";
    let nextChrUpper = false;
    const leadingHyphens = str2.match(/^-+/);
    for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str2.length; i++) {
      let chr = str2.charAt(i);
      if (nextChrUpper) {
        nextChrUpper = false;
        chr = chr.toUpperCase();
      }
      if (i !== 0 && (chr === "-" || chr === "_")) {
        nextChrUpper = true;
      } else if (chr !== "-" && chr !== "_") {
        camelcase += chr;
      }
    }
    return camelcase;
  }
}
__name(camelCase, "camelCase");
function decamelize(str2, joinString) {
  const lowercase = str2.toLowerCase();
  joinString = joinString || "-";
  let notCamelcase = "";
  for (let i = 0; i < str2.length; i++) {
    const chrLower = lowercase.charAt(i);
    const chrString = str2.charAt(i);
    if (chrLower !== chrString && i > 0) {
      notCamelcase += `${joinString}${lowercase.charAt(i)}`;
    } else {
      notCamelcase += chrString;
    }
  }
  return notCamelcase;
}
__name(decamelize, "decamelize");
function looksLikeNumber(x) {
  if (x === null || x === void 0)
    return false;
  if (typeof x === "number")
    return true;
  if (/^0x[0-9a-f]+$/i.test(x))
    return true;
  if (/^0[^.]/.test(x))
    return false;
  return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}
__name(looksLikeNumber, "looksLikeNumber");

// node_modules/yargs-parser/build/lib/yargs-parser.js
init_esbuild_shims();

// node_modules/yargs-parser/build/lib/tokenize-arg-string.js
init_esbuild_shims();
function tokenizeArgString(argString) {
  if (Array.isArray(argString)) {
    return argString.map((e2) => typeof e2 !== "string" ? e2 + "" : e2);
  }
  argString = argString.trim();
  let i = 0;
  let prevC = null;
  let c3 = null;
  let opening = null;
  const args = [];
  for (let ii = 0; ii < argString.length; ii++) {
    prevC = c3;
    c3 = argString.charAt(ii);
    if (c3 === " " && !opening) {
      if (!(prevC === " ")) {
        i++;
      }
      continue;
    }
    if (c3 === opening) {
      opening = null;
    } else if ((c3 === "'" || c3 === '"') && !opening) {
      opening = c3;
    }
    if (!args[i])
      args[i] = "";
    args[i] += c3;
  }
  return args;
}
__name(tokenizeArgString, "tokenizeArgString");

// node_modules/yargs-parser/build/lib/yargs-parser-types.js
init_esbuild_shims();
var DefaultValuesForTypeKey;
(function(DefaultValuesForTypeKey2) {
  DefaultValuesForTypeKey2["BOOLEAN"] = "boolean";
  DefaultValuesForTypeKey2["STRING"] = "string";
  DefaultValuesForTypeKey2["NUMBER"] = "number";
  DefaultValuesForTypeKey2["ARRAY"] = "array";
})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {}));

// node_modules/yargs-parser/build/lib/yargs-parser.js
var mixin2;
var YargsParser = class {
  static {
    __name(this, "YargsParser");
  }
  constructor(_mixin) {
    mixin2 = _mixin;
  }
  parse(argsInput, options2) {
    const opts = Object.assign({
      alias: void 0,
      array: void 0,
      boolean: void 0,
      config: void 0,
      configObjects: void 0,
      configuration: void 0,
      coerce: void 0,
      count: void 0,
      default: void 0,
      envPrefix: void 0,
      narg: void 0,
      normalize: void 0,
      string: void 0,
      number: void 0,
      __: void 0,
      key: void 0
    }, options2);
    const args = tokenizeArgString(argsInput);
    const inputIsString = typeof argsInput === "string";
    const aliases = combineAliases(Object.assign(/* @__PURE__ */ Object.create(null), opts.alias));
    const configuration = Object.assign({
      "boolean-negation": true,
      "camel-case-expansion": true,
      "combine-arrays": false,
      "dot-notation": true,
      "duplicate-arguments-array": true,
      "flatten-duplicate-arrays": true,
      "greedy-arrays": true,
      "halt-at-non-option": false,
      "nargs-eats-options": false,
      "negation-prefix": "no-",
      "parse-numbers": true,
      "parse-positional-numbers": true,
      "populate--": false,
      "set-placeholder-key": false,
      "short-option-groups": true,
      "strip-aliased": false,
      "strip-dashed": false,
      "unknown-options-as-args": false
    }, opts.configuration);
    const defaults3 = Object.assign(/* @__PURE__ */ Object.create(null), opts.default);
    const configObjects = opts.configObjects || [];
    const envPrefix = opts.envPrefix;
    const notFlagsOption = configuration["populate--"];
    const notFlagsArgv = notFlagsOption ? "--" : "_";
    const newAliases = /* @__PURE__ */ Object.create(null);
    const defaulted = /* @__PURE__ */ Object.create(null);
    const __ = opts.__ || mixin2.format;
    const flags = {
      aliases: /* @__PURE__ */ Object.create(null),
      arrays: /* @__PURE__ */ Object.create(null),
      bools: /* @__PURE__ */ Object.create(null),
      strings: /* @__PURE__ */ Object.create(null),
      numbers: /* @__PURE__ */ Object.create(null),
      counts: /* @__PURE__ */ Object.create(null),
      normalize: /* @__PURE__ */ Object.create(null),
      configs: /* @__PURE__ */ Object.create(null),
      nargs: /* @__PURE__ */ Object.create(null),
      coercions: /* @__PURE__ */ Object.create(null),
      keys: []
    };
    const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/;
    const negatedBoolean = new RegExp("^--" + configuration["negation-prefix"] + "(.+)");
    [].concat(opts.array || []).filter(Boolean).forEach(function(opt) {
      const key = typeof opt === "object" ? opt.key : opt;
      const assignment = Object.keys(opt).map(function(key2) {
        const arrayFlagKeys = {
          boolean: "bools",
          string: "strings",
          number: "numbers"
        };
        return arrayFlagKeys[key2];
      }).filter(Boolean).pop();
      if (assignment) {
        flags[assignment][key] = true;
      }
      flags.arrays[key] = true;
      flags.keys.push(key);
    });
    [].concat(opts.boolean || []).filter(Boolean).forEach(function(key) {
      flags.bools[key] = true;
      flags.keys.push(key);
    });
    [].concat(opts.string || []).filter(Boolean).forEach(function(key) {
      flags.strings[key] = true;
      flags.keys.push(key);
    });
    [].concat(opts.number || []).filter(Boolean).forEach(function(key) {
      flags.numbers[key] = true;
      flags.keys.push(key);
    });
    [].concat(opts.count || []).filter(Boolean).forEach(function(key) {
      flags.counts[key] = true;
      flags.keys.push(key);
    });
    [].concat(opts.normalize || []).filter(Boolean).forEach(function(key) {
      flags.normalize[key] = true;
      flags.keys.push(key);
    });
    if (typeof opts.narg === "object") {
      Object.entries(opts.narg).forEach(([key, value]) => {
        if (typeof value === "number") {
          flags.nargs[key] = value;
          flags.keys.push(key);
        }
      });
    }
    if (typeof opts.coerce === "object") {
      Object.entries(opts.coerce).forEach(([key, value]) => {
        if (typeof value === "function") {
          flags.coercions[key] = value;
          flags.keys.push(key);
        }
      });
    }
    if (typeof opts.config !== "undefined") {
      if (Array.isArray(opts.config) || typeof opts.config === "string") {
        ;
        [].concat(opts.config).filter(Boolean).forEach(function(key) {
          flags.configs[key] = true;
        });
      } else if (typeof opts.config === "object") {
        Object.entries(opts.config).forEach(([key, value]) => {
          if (typeof value === "boolean" || typeof value === "function") {
            flags.configs[key] = value;
          }
        });
      }
    }
    extendAliases(opts.key, aliases, opts.default, flags.arrays);
    Object.keys(defaults3).forEach(function(key) {
      (flags.aliases[key] || []).forEach(function(alias) {
        defaults3[alias] = defaults3[key];
      });
    });
    let error = null;
    checkConfiguration();
    let notFlags = [];
    const argv = Object.assign(/* @__PURE__ */ Object.create(null), { _: [] });
    const argvReturn = {};
    for (let i = 0; i < args.length; i++) {
      const arg = args[i];
      const truncatedArg = arg.replace(/^-{3,}/, "---");
      let broken;
      let key;
      let letters;
      let m;
      let next;
      let value;
      if (arg !== "--" && /^-/.test(arg) && isUnknownOptionAsArg(arg)) {
        pushPositional(arg);
      } else if (truncatedArg.match(/^---+(=|$)/)) {
        pushPositional(arg);
        continue;
      } else if (arg.match(/^--.+=/) || !configuration["short-option-groups"] && arg.match(/^-.+=/)) {
        m = arg.match(/^--?([^=]+)=([\s\S]*)$/);
        if (m !== null && Array.isArray(m) && m.length >= 3) {
          if (checkAllAliases(m[1], flags.arrays)) {
            i = eatArray(i, m[1], args, m[2]);
          } else if (checkAllAliases(m[1], flags.nargs) !== false) {
            i = eatNargs(i, m[1], args, m[2]);
          } else {
            setArg(m[1], m[2], true);
          }
        }
      } else if (arg.match(negatedBoolean) && configuration["boolean-negation"]) {
        m = arg.match(negatedBoolean);
        if (m !== null && Array.isArray(m) && m.length >= 2) {
          key = m[1];
          setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false);
        }
      } else if (arg.match(/^--.+/) || !configuration["short-option-groups"] && arg.match(/^-[^-]+/)) {
        m = arg.match(/^--?(.+)/);
        if (m !== null && Array.isArray(m) && m.length >= 2) {
          key = m[1];
          if (checkAllAliases(key, flags.arrays)) {
            i = eatArray(i, key, args);
          } else if (checkAllAliases(key, flags.nargs) !== false) {
            i = eatNargs(i, key, args);
          } else {
            next = args[i + 1];
            if (next !== void 0 && (!next.match(/^-/) || next.match(negative)) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) {
              setArg(key, next);
              i++;
            } else if (/^(true|false)$/.test(next)) {
              setArg(key, next);
              i++;
            } else {
              setArg(key, defaultValue(key));
            }
          }
        }
      } else if (arg.match(/^-.\..+=/)) {
        m = arg.match(/^-([^=]+)=([\s\S]*)$/);
        if (m !== null && Array.isArray(m) && m.length >= 3) {
          setArg(m[1], m[2]);
        }
      } else if (arg.match(/^-.\..+/) && !arg.match(negative)) {
        next = args[i + 1];
        m = arg.match(/^-(.\..+)/);
        if (m !== null && Array.isArray(m) && m.length >= 2) {
          key = m[1];
          if (next !== void 0 && !next.match(/^-/) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) {
            setArg(key, next);
            i++;
          } else {
            setArg(key, defaultValue(key));
          }
        }
      } else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
        letters = arg.slice(1, -1).split("");
        broken = false;
        for (let j = 0; j < letters.length; j++) {
          next = arg.slice(j + 2);
          if (letters[j + 1] && letters[j + 1] === "=") {
            value = arg.slice(j + 3);
            key = letters[j];
            if (checkAllAliases(key, flags.arrays)) {
              i = eatArray(i, key, args, value);
            } else if (checkAllAliases(key, flags.nargs) !== false) {
              i = eatNargs(i, key, args, value);
            } else {
              setArg(key, value);
            }
            broken = true;
            break;
          }
          if (next === "-") {
            setArg(letters[j], next);
            continue;
          }
          if (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && checkAllAliases(next, flags.bools) === false) {
            setArg(letters[j], next);
            broken = true;
            break;
          }
          if (letters[j + 1] && letters[j + 1].match(/\W/)) {
            setArg(letters[j], next);
            broken = true;
            break;
          } else {
            setArg(letters[j], defaultValue(letters[j]));
          }
        }
        key = arg.slice(-1)[0];
        if (!broken && key !== "-") {
          if (checkAllAliases(key, flags.arrays)) {
            i = eatArray(i, key, args);
          } else if (checkAllAliases(key, flags.nargs) !== false) {
            i = eatNargs(i, key, args);
          } else {
            next = args[i + 1];
            if (next !== void 0 && (!/^(-|--)[^-]/.test(next) || next.match(negative)) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) {
              setArg(key, next);
              i++;
            } else if (/^(true|false)$/.test(next)) {
              setArg(key, next);
              i++;
            } else {
              setArg(key, defaultValue(key));
            }
          }
        }
      } else if (arg.match(/^-[0-9]$/) && arg.match(negative) && checkAllAliases(arg.slice(1), flags.bools)) {
        key = arg.slice(1);
        setArg(key, defaultValue(key));
      } else if (arg === "--") {
        notFlags = args.slice(i + 1);
        break;
      } else if (configuration["halt-at-non-option"]) {
        notFlags = args.slice(i);
        break;
      } else {
        pushPositional(arg);
      }
    }
    applyEnvVars(argv, true);
    applyEnvVars(argv, false);
    setConfig(argv);
    setConfigObjects();
    applyDefaultsAndAliases(argv, flags.aliases, defaults3, true);
    applyCoercions(argv);
    if (configuration["set-placeholder-key"])
      setPlaceholderKeys(argv);
    Object.keys(flags.counts).forEach(function(key) {
      if (!hasKey2(argv, key.split(".")))
        setArg(key, 0);
    });
    if (notFlagsOption && notFlags.length)
      argv[notFlagsArgv] = [];
    notFlags.forEach(function(key) {
      argv[notFlagsArgv].push(key);
    });
    if (configuration["camel-case-expansion"] && configuration["strip-dashed"]) {
      Object.keys(argv).filter((key) => key !== "--" && key.includes("-")).forEach((key) => {
        delete argv[key];
      });
    }
    if (configuration["strip-aliased"]) {
      ;
      [].concat(...Object.keys(aliases).map((k) => aliases[k])).forEach((alias) => {
        if (configuration["camel-case-expansion"] && alias.includes("-")) {
          delete argv[alias.split(".").map((prop) => camelCase(prop)).join(".")];
        }
        delete argv[alias];
      });
    }
    function pushPositional(arg) {
      const maybeCoercedNumber = maybeCoerceNumber("_", arg);
      if (typeof maybeCoercedNumber === "string" || typeof maybeCoercedNumber === "number") {
        argv._.push(maybeCoercedNumber);
      }
    }
    __name(pushPositional, "pushPositional");
    function eatNargs(i, key, args2, argAfterEqualSign) {
      let ii;
      let toEat = checkAllAliases(key, flags.nargs);
      toEat = typeof toEat !== "number" || isNaN(toEat) ? 1 : toEat;
      if (toEat === 0) {
        if (!isUndefined2(argAfterEqualSign)) {
          error = Error(__("Argument unexpected for: %s", key));
        }
        setArg(key, defaultValue(key));
        return i;
      }
      let available = isUndefined2(argAfterEqualSign) ? 0 : 1;
      if (configuration["nargs-eats-options"]) {
        if (args2.length - (i + 1) + available < toEat) {
          error = Error(__("Not enough arguments following: %s", key));
        }
        available = toEat;
      } else {
        for (ii = i + 1; ii < args2.length; ii++) {
          if (!args2[ii].match(/^-[^0-9]/) || args2[ii].match(negative) || isUnknownOptionAsArg(args2[ii]))
            available++;
          else
            break;
        }
        if (available < toEat)
          error = Error(__("Not enough arguments following: %s", key));
      }
      let consumed = Math.min(available, toEat);
      if (!isUndefined2(argAfterEqualSign) && consumed > 0) {
        setArg(key, argAfterEqualSign);
        consumed--;
      }
      for (ii = i + 1; ii < consumed + i + 1; ii++) {
        setArg(key, args2[ii]);
      }
      return i + consumed;
    }
    __name(eatNargs, "eatNargs");
    function eatArray(i, key, args2, argAfterEqualSign) {
      let argsToSet = [];
      let next = argAfterEqualSign || args2[i + 1];
      const nargsCount = checkAllAliases(key, flags.nargs);
      if (checkAllAliases(key, flags.bools) && !/^(true|false)$/.test(next)) {
        argsToSet.push(true);
      } else if (isUndefined2(next) || isUndefined2(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) {
        if (defaults3[key] !== void 0) {
          const defVal = defaults3[key];
          argsToSet = Array.isArray(defVal) ? defVal : [defVal];
        }
      } else {
        if (!isUndefined2(argAfterEqualSign)) {
          argsToSet.push(processValue(key, argAfterEqualSign, true));
        }
        for (let ii = i + 1; ii < args2.length; ii++) {
          if (!configuration["greedy-arrays"] && argsToSet.length > 0 || nargsCount && typeof nargsCount === "number" && argsToSet.length >= nargsCount)
            break;
          next = args2[ii];
          if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))
            break;
          i = ii;
          argsToSet.push(processValue(key, next, inputIsString));
        }
      }
      if (typeof nargsCount === "number" && (nargsCount && argsToSet.length < nargsCount || isNaN(nargsCount) && argsToSet.length === 0)) {
        error = Error(__("Not enough arguments following: %s", key));
      }
      setArg(key, argsToSet);
      return i;
    }
    __name(eatArray, "eatArray");
    function setArg(key, val, shouldStripQuotes = inputIsString) {
      if (/-/.test(key) && configuration["camel-case-expansion"]) {
        const alias = key.split(".").map(function(prop) {
          return camelCase(prop);
        }).join(".");
        addNewAlias(key, alias);
      }
      const value = processValue(key, val, shouldStripQuotes);
      const splitKey = key.split(".");
      setKey(argv, splitKey, value);
      if (flags.aliases[key]) {
        flags.aliases[key].forEach(function(x) {
          const keyProperties = x.split(".");
          setKey(argv, keyProperties, value);
        });
      }
      if (splitKey.length > 1 && configuration["dot-notation"]) {
        ;
        (flags.aliases[splitKey[0]] || []).forEach(function(x) {
          let keyProperties = x.split(".");
          const a = [].concat(splitKey);
          a.shift();
          keyProperties = keyProperties.concat(a);
          if (!(flags.aliases[key] || []).includes(keyProperties.join("."))) {
            setKey(argv, keyProperties, value);
          }
        });
      }
      if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
        const keys = [key].concat(flags.aliases[key] || []);
        keys.forEach(function(key2) {
          Object.defineProperty(argvReturn, key2, {
            enumerable: true,
            get() {
              return val;
            },
            set(value2) {
              val = typeof value2 === "string" ? mixin2.normalize(value2) : value2;
            }
          });
        });
      }
    }
    __name(setArg, "setArg");
    function addNewAlias(key, alias) {
      if (!(flags.aliases[key] && flags.aliases[key].length)) {
        flags.aliases[key] = [alias];
        newAliases[alias] = true;
      }
      if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
        addNewAlias(alias, key);
      }
    }
    __name(addNewAlias, "addNewAlias");
    function processValue(key, val, shouldStripQuotes) {
      if (shouldStripQuotes) {
        val = stripQuotes(val);
      }
      if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
        if (typeof val === "string")
          val = val === "true";
      }
      let value = Array.isArray(val) ? val.map(function(v) {
        return maybeCoerceNumber(key, v);
      }) : maybeCoerceNumber(key, val);
      if (checkAllAliases(key, flags.counts) && (isUndefined2(value) || typeof value === "boolean")) {
        value = increment();
      }
      if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
        if (Array.isArray(val))
          value = val.map((val2) => {
            return mixin2.normalize(val2);
          });
        else
          value = mixin2.normalize(val);
      }
      return value;
    }
    __name(processValue, "processValue");
    function maybeCoerceNumber(key, value) {
      if (!configuration["parse-positional-numbers"] && key === "_")
        return value;
      if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) {
        const shouldCoerceNumber = looksLikeNumber(value) && configuration["parse-numbers"] && Number.isSafeInteger(Math.floor(parseFloat(`${value}`)));
        if (shouldCoerceNumber || !isUndefined2(value) && checkAllAliases(key, flags.numbers)) {
          value = Number(value);
        }
      }
      return value;
    }
    __name(maybeCoerceNumber, "maybeCoerceNumber");
    function setConfig(argv2) {
      const configLookup = /* @__PURE__ */ Object.create(null);
      applyDefaultsAndAliases(configLookup, flags.aliases, defaults3);
      Object.keys(flags.configs).forEach(function(configKey) {
        const configPath = argv2[configKey] || configLookup[configKey];
        if (configPath) {
          try {
            let config = null;
            const resolvedConfigPath = mixin2.resolve(mixin2.cwd(), configPath);
            const resolveConfig = flags.configs[configKey];
            if (typeof resolveConfig === "function") {
              try {
                config = resolveConfig(resolvedConfigPath);
              } catch (e2) {
                config = e2;
              }
              if (config instanceof Error) {
                error = config;
                return;
              }
            } else {
              config = mixin2.require(resolvedConfigPath);
            }
            setConfigObject(config);
          } catch (ex) {
            if (ex.name === "PermissionDenied")
              error = ex;
            else if (argv2[configKey])
              error = Error(__("Invalid JSON config file: %s", configPath));
          }
        }
      });
    }
    __name(setConfig, "setConfig");
    function setConfigObject(config, prev) {
      Object.keys(config).forEach(function(key) {
        const value = config[key];
        const fullKey = prev ? prev + "." + key : key;
        if (typeof value === "object" && value !== null && !Array.isArray(value) && configuration["dot-notation"]) {
          setConfigObject(value, fullKey);
        } else {
          if (!hasKey2(argv, fullKey.split(".")) || checkAllAliases(fullKey, flags.arrays) && configuration["combine-arrays"]) {
            setArg(fullKey, value);
          }
        }
      });
    }
    __name(setConfigObject, "setConfigObject");
    function setConfigObjects() {
      if (typeof configObjects !== "undefined") {
        configObjects.forEach(function(configObject) {
          setConfigObject(configObject);
        });
      }
    }
    __name(setConfigObjects, "setConfigObjects");
    function applyEnvVars(argv2, configOnly) {
      if (typeof envPrefix === "undefined")
        return;
      const prefix = typeof envPrefix === "string" ? envPrefix : "";
      const env7 = mixin2.env();
      Object.keys(env7).forEach(function(envVar) {
        if (prefix === "" || envVar.lastIndexOf(prefix, 0) === 0) {
          const keys = envVar.split("__").map(function(key, i) {
            if (i === 0) {
              key = key.substring(prefix.length);
            }
            return camelCase(key);
          });
          if ((configOnly && flags.configs[keys.join(".")] || !configOnly) && !hasKey2(argv2, keys)) {
            setArg(keys.join("."), env7[envVar]);
          }
        }
      });
    }
    __name(applyEnvVars, "applyEnvVars");
    function applyCoercions(argv2) {
      let coerce2;
      const applied = /* @__PURE__ */ new Set();
      Object.keys(argv2).forEach(function(key) {
        if (!applied.has(key)) {
          coerce2 = checkAllAliases(key, flags.coercions);
          if (typeof coerce2 === "function") {
            try {
              const value = maybeCoerceNumber(key, coerce2(argv2[key]));
              [].concat(flags.aliases[key] || [], key).forEach((ali) => {
                applied.add(ali);
                argv2[ali] = value;
              });
            } catch (err) {
              error = err;
            }
          }
        }
      });
    }
    __name(applyCoercions, "applyCoercions");
    function setPlaceholderKeys(argv2) {
      flags.keys.forEach((key) => {
        if (~key.indexOf("."))
          return;
        if (typeof argv2[key] === "undefined")
          argv2[key] = void 0;
      });
      return argv2;
    }
    __name(setPlaceholderKeys, "setPlaceholderKeys");
    function applyDefaultsAndAliases(obj, aliases2, defaults4, canLog = false) {
      Object.keys(defaults4).forEach(function(key) {
        if (!hasKey2(obj, key.split("."))) {
          setKey(obj, key.split("."), defaults4[key]);
          if (canLog)
            defaulted[key] = true;
          (aliases2[key] || []).forEach(function(x) {
            if (hasKey2(obj, x.split(".")))
              return;
            setKey(obj, x.split("."), defaults4[key]);
          });
        }
      });
    }
    __name(applyDefaultsAndAliases, "applyDefaultsAndAliases");
    function hasKey2(obj, keys) {
      let o2 = obj;
      if (!configuration["dot-notation"])
        keys = [keys.join(".")];
      keys.slice(0, -1).forEach(function(key2) {
        o2 = o2[key2] || {};
      });
      const key = keys[keys.length - 1];
      if (typeof o2 !== "object")
        return false;
      else
        return key in o2;
    }
    __name(hasKey2, "hasKey");
    function setKey(obj, keys, value) {
      let o2 = obj;
      if (!configuration["dot-notation"])
        keys = [keys.join(".")];
      keys.slice(0, -1).forEach(function(key2) {
        key2 = sanitizeKey(key2);
        if (typeof o2 === "object" && o2[key2] === void 0) {
          o2[key2] = {};
        }
        if (typeof o2[key2] !== "object" || Array.isArray(o2[key2])) {
          if (Array.isArray(o2[key2])) {
            o2[key2].push({});
          } else {
            o2[key2] = [o2[key2], {}];
          }
          o2 = o2[key2][o2[key2].length - 1];
        } else {
          o2 = o2[key2];
        }
      });
      const key = sanitizeKey(keys[keys.length - 1]);
      const isTypeArray = checkAllAliases(keys.join("."), flags.arrays);
      const isValueArray = Array.isArray(value);
      let duplicate = configuration["duplicate-arguments-array"];
      if (!duplicate && checkAllAliases(key, flags.nargs)) {
        duplicate = true;
        if (!isUndefined2(o2[key]) && flags.nargs[key] === 1 || Array.isArray(o2[key]) && o2[key].length === flags.nargs[key]) {
          o2[key] = void 0;
        }
      }
      if (value === increment()) {
        o2[key] = increment(o2[key]);
      } else if (Array.isArray(o2[key])) {
        if (duplicate && isTypeArray && isValueArray) {
          o2[key] = configuration["flatten-duplicate-arrays"] ? o2[key].concat(value) : (Array.isArray(o2[key][0]) ? o2[key] : [o2[key]]).concat([value]);
        } else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
          o2[key] = value;
        } else {
          o2[key] = o2[key].concat([value]);
        }
      } else if (o2[key] === void 0 && isTypeArray) {
        o2[key] = isValueArray ? value : [value];
      } else if (duplicate && !(o2[key] === void 0 || checkAllAliases(key, flags.counts) || checkAllAliases(key, flags.bools))) {
        o2[key] = [o2[key], value];
      } else {
        o2[key] = value;
      }
    }
    __name(setKey, "setKey");
    function extendAliases(...args2) {
      args2.forEach(function(obj) {
        Object.keys(obj || {}).forEach(function(key) {
          if (flags.aliases[key])
            return;
          flags.aliases[key] = [].concat(aliases[key] || []);
          flags.aliases[key].concat(key).forEach(function(x) {
            if (/-/.test(x) && configuration["camel-case-expansion"]) {
              const c3 = camelCase(x);
              if (c3 !== key && flags.aliases[key].indexOf(c3) === -1) {
                flags.aliases[key].push(c3);
                newAliases[c3] = true;
              }
            }
          });
          flags.aliases[key].concat(key).forEach(function(x) {
            if (x.length > 1 && /[A-Z]/.test(x) && configuration["camel-case-expansion"]) {
              const c3 = decamelize(x, "-");
              if (c3 !== key && flags.aliases[key].indexOf(c3) === -1) {
                flags.aliases[key].push(c3);
                newAliases[c3] = true;
              }
            }
          });
          flags.aliases[key].forEach(function(x) {
            flags.aliases[x] = [key].concat(flags.aliases[key].filter(function(y) {
              return x !== y;
            }));
          });
        });
      });
    }
    __name(extendAliases, "extendAliases");
    function checkAllAliases(key, flag) {
      const toCheck = [].concat(flags.aliases[key] || [], key);
      const keys = Object.keys(flag);
      const setAlias = toCheck.find((key2) => keys.includes(key2));
      return setAlias ? flag[setAlias] : false;
    }
    __name(checkAllAliases, "checkAllAliases");
    function hasAnyFlag(key) {
      const flagsKeys = Object.keys(flags);
      const toCheck = [].concat(flagsKeys.map((k) => flags[k]));
      return toCheck.some(function(flag) {
        return Array.isArray(flag) ? flag.includes(key) : flag[key];
      });
    }
    __name(hasAnyFlag, "hasAnyFlag");
    function hasFlagsMatching(arg, ...patterns) {
      const toCheck = [].concat(...patterns);
      return toCheck.some(function(pattern) {
        const match2 = arg.match(pattern);
        return match2 && hasAnyFlag(match2[1]);
      });
    }
    __name(hasFlagsMatching, "hasFlagsMatching");
    function hasAllShortFlags(arg) {
      if (arg.match(negative) || !arg.match(/^-[^-]+/)) {
        return false;
      }
      let hasAllFlags = true;
      let next;
      const letters = arg.slice(1).split("");
      for (let j = 0; j < letters.length; j++) {
        next = arg.slice(j + 2);
        if (!hasAnyFlag(letters[j])) {
          hasAllFlags = false;
          break;
        }
        if (letters[j + 1] && letters[j + 1] === "=" || next === "-" || /[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) || letters[j + 1] && letters[j + 1].match(/\W/)) {
          break;
        }
      }
      return hasAllFlags;
    }
    __name(hasAllShortFlags, "hasAllShortFlags");
    function isUnknownOptionAsArg(arg) {
      return configuration["unknown-options-as-args"] && isUnknownOption(arg);
    }
    __name(isUnknownOptionAsArg, "isUnknownOptionAsArg");
    function isUnknownOption(arg) {
      arg = arg.replace(/^-{3,}/, "--");
      if (arg.match(negative)) {
        return false;
      }
      if (hasAllShortFlags(arg)) {
        return false;
      }
      const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/;
      const normalFlag = /^-+([^=]+?)$/;
      const flagEndingInHyphen = /^-+([^=]+?)-$/;
      const flagEndingInDigits = /^-+([^=]+?\d+)$/;
      const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/;
      return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters);
    }
    __name(isUnknownOption, "isUnknownOption");
    function defaultValue(key) {
      if (!checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts) && `${key}` in defaults3) {
        return defaults3[key];
      } else {
        return defaultForType(guessType2(key));
      }
    }
    __name(defaultValue, "defaultValue");
    function defaultForType(type) {
      const def2 = {
        [DefaultValuesForTypeKey.BOOLEAN]: true,
        [DefaultValuesForTypeKey.STRING]: "",
        [DefaultValuesForTypeKey.NUMBER]: void 0,
        [DefaultValuesForTypeKey.ARRAY]: []
      };
      return def2[type];
    }
    __name(defaultForType, "defaultForType");
    function guessType2(key) {
      let type = DefaultValuesForTypeKey.BOOLEAN;
      if (checkAllAliases(key, flags.strings))
        type = DefaultValuesForTypeKey.STRING;
      else if (checkAllAliases(key, flags.numbers))
        type = DefaultValuesForTypeKey.NUMBER;
      else if (checkAllAliases(key, flags.bools))
        type = DefaultValuesForTypeKey.BOOLEAN;
      else if (checkAllAliases(key, flags.arrays))
        type = DefaultValuesForTypeKey.ARRAY;
      return type;
    }
    __name(guessType2, "guessType");
    function isUndefined2(num) {
      return num === void 0;
    }
    __name(isUndefined2, "isUndefined");
    function checkConfiguration() {
      Object.keys(flags.counts).find((key) => {
        if (checkAllAliases(key, flags.arrays)) {
          error = Error(__("Invalid configuration: %s, opts.count excludes opts.array.", key));
          return true;
        } else if (checkAllAliases(key, flags.nargs)) {
          error = Error(__("Invalid configuration: %s, opts.count excludes opts.narg.", key));
          return true;
        }
        return false;
      });
    }
    __name(checkConfiguration, "checkConfiguration");
    return {
      aliases: Object.assign({}, flags.aliases),
      argv: Object.assign(argvReturn, argv),
      configuration,
      defaulted: Object.assign({}, defaulted),
      error,
      newAliases: Object.assign({}, newAliases)
    };
  }
};
function combineAliases(aliases) {
  const aliasArrays = [];
  const combined = /* @__PURE__ */ Object.create(null);
  let change = true;
  Object.keys(aliases).forEach(function(key) {
    aliasArrays.push([].concat(aliases[key], key));
  });
  while (change) {
    change = false;
    for (let i = 0; i < aliasArrays.length; i++) {
      for (let ii = i + 1; ii < aliasArrays.length; ii++) {
        const intersect = aliasArrays[i].filter(function(v) {
          return aliasArrays[ii].indexOf(v) !== -1;
        });
        if (intersect.length) {
          aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]);
          aliasArrays.splice(ii, 1);
          change = true;
          break;
        }
      }
    }
  }
  aliasArrays.forEach(function(aliasArray) {
    aliasArray = aliasArray.filter(function(v, i, self2) {
      return self2.indexOf(v) === i;
    });
    const lastAlias = aliasArray.pop();
    if (lastAlias !== void 0 && typeof lastAlias === "string") {
      combined[lastAlias] = aliasArray;
    }
  });
  return combined;
}
__name(combineAliases, "combineAliases");
function increment(orig) {
  return orig !== void 0 ? orig + 1 : 1;
}
__name(increment, "increment");
function sanitizeKey(key) {
  if (key === "__proto__")
    return "___proto___";
  return key;
}
__name(sanitizeKey, "sanitizeKey");
function stripQuotes(val) {
  return typeof val === "string" && (val[0] === "'" || val[0] === '"') && val[val.length - 1] === val[0] ? val.substring(1, val.length - 1) : val;
}
__name(stripQuotes, "stripQuotes");

// node_modules/yargs-parser/build/lib/index.js
import { readFileSync as readFileSync11 } from "fs";
var _a5;
var _b;
var _c;
var minNodeVersion = process && process.env && process.env.YARGS_MIN_NODE_VERSION ? Number(process.env.YARGS_MIN_NODE_VERSION) : 12;
var nodeVersion = (_b = (_a5 = process === null || process === void 0 ? void 0 : process.versions) === null || _a5 === void 0 ? void 0 : _a5.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1);
if (nodeVersion) {
  const major2 = Number(nodeVersion.match(/^([^.]+)/)[1]);
  if (major2 < minNodeVersion) {
    throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);
  }
}
var env4 = process ? process.env : {};
var parser5 = new YargsParser({
  cwd: process.cwd,
  env: /* @__PURE__ */ __name(() => {
    return env4;
  }, "env"),
  format,
  normalize: normalize7,
  resolve: resolve18,
  // TODO: figure  out a  way to combine ESM and CJS coverage, such  that
  // we can exercise all the lines below:
  require: /* @__PURE__ */ __name((path108) => {
    if (typeof __require !== "undefined") {
      return __require(path108);
    } else if (path108.match(/\.json$/)) {
      return JSON.parse(readFileSync11(path108, "utf8"));
    } else {
      throw Error("only .json config files are supported in ESM");
    }
  }, "require")
});
var yargsParser = /* @__PURE__ */ __name(function Parser3(args, opts) {
  const result = parser5.parse(args.slice(), opts);
  return result.argv;
}, "Parser");
yargsParser.detailed = function(args, opts) {
  return parser5.parse(args.slice(), opts);
};
yargsParser.camelCase = camelCase;
yargsParser.decamelize = decamelize;
yargsParser.looksLikeNumber = looksLikeNumber;
var lib_default = yargsParser;

// node_modules/yargs/lib/platform-shims/esm.mjs
import { basename as basename12, dirname as dirname20, extname as extname4, relative as relative7, resolve as resolve20 } from "path";

// node_modules/yargs/build/lib/utils/process-argv.js
init_esbuild_shims();
function getProcessArgvBinIndex() {
  if (isBundledElectronApp())
    return 0;
  return 1;
}
__name(getProcessArgvBinIndex, "getProcessArgvBinIndex");
function isBundledElectronApp() {
  return isElectronApp() && !process.defaultApp;
}
__name(isBundledElectronApp, "isBundledElectronApp");
function isElectronApp() {
  return !!process.versions.electron;
}
__name(isElectronApp, "isElectronApp");
function hideBin(argv) {
  return argv.slice(getProcessArgvBinIndex() + 1);
}
__name(hideBin, "hideBin");
function getProcessArgvBin() {
  return process.argv[getProcessArgvBinIndex()];
}
__name(getProcessArgvBin, "getProcessArgvBin");

// node_modules/yargs/build/lib/yerror.js
init_esbuild_shims();
var YError = class _YError extends Error {
  static {
    __name(this, "YError");
  }
  constructor(msg) {
    super(msg || "yargs error");
    this.name = "YError";
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, _YError);
    }
  }
};

// node_modules/y18n/index.mjs
init_esbuild_shims();

// node_modules/y18n/build/lib/platform-shims/node.js
init_esbuild_shims();
import { readFileSync as readFileSync12, statSync as statSync4, writeFile as writeFile8 } from "fs";
import { format as format2 } from "util";
import { resolve as resolve19 } from "path";
var node_default = {
  fs: {
    readFileSync: readFileSync12,
    writeFile: writeFile8
  },
  format: format2,
  resolve: resolve19,
  exists: /* @__PURE__ */ __name((file) => {
    try {
      return statSync4(file).isFile();
    } catch (err) {
      return false;
    }
  }, "exists")
};

// node_modules/y18n/build/lib/index.js
init_esbuild_shims();
var shim;
var Y18N = class {
  static {
    __name(this, "Y18N");
  }
  constructor(opts) {
    opts = opts || {};
    this.directory = opts.directory || "./locales";
    this.updateFiles = typeof opts.updateFiles === "boolean" ? opts.updateFiles : true;
    this.locale = opts.locale || "en";
    this.fallbackToLanguage = typeof opts.fallbackToLanguage === "boolean" ? opts.fallbackToLanguage : true;
    this.cache = /* @__PURE__ */ Object.create(null);
    this.writeQueue = [];
  }
  __(...args) {
    if (typeof arguments[0] !== "string") {
      return this._taggedLiteral(arguments[0], ...arguments);
    }
    const str2 = args.shift();
    let cb = /* @__PURE__ */ __name(function() {
    }, "cb");
    if (typeof args[args.length - 1] === "function")
      cb = args.pop();
    cb = cb || function() {
    };
    if (!this.cache[this.locale])
      this._readLocaleFile();
    if (!this.cache[this.locale][str2] && this.updateFiles) {
      this.cache[this.locale][str2] = str2;
      this._enqueueWrite({
        directory: this.directory,
        locale: this.locale,
        cb
      });
    } else {
      cb();
    }
    return shim.format.apply(shim.format, [this.cache[this.locale][str2] || str2].concat(args));
  }
  __n() {
    const args = Array.prototype.slice.call(arguments);
    const singular = args.shift();
    const plural = args.shift();
    const quantity = args.shift();
    let cb = /* @__PURE__ */ __name(function() {
    }, "cb");
    if (typeof args[args.length - 1] === "function")
      cb = args.pop();
    if (!this.cache[this.locale])
      this._readLocaleFile();
    let str2 = quantity === 1 ? singular : plural;
    if (this.cache[this.locale][singular]) {
      const entry = this.cache[this.locale][singular];
      str2 = entry[quantity === 1 ? "one" : "other"];
    }
    if (!this.cache[this.locale][singular] && this.updateFiles) {
      this.cache[this.locale][singular] = {
        one: singular,
        other: plural
      };
      this._enqueueWrite({
        directory: this.directory,
        locale: this.locale,
        cb
      });
    } else {
      cb();
    }
    const values = [str2];
    if (~str2.indexOf("%d"))
      values.push(quantity);
    return shim.format.apply(shim.format, values.concat(args));
  }
  setLocale(locale) {
    this.locale = locale;
  }
  getLocale() {
    return this.locale;
  }
  updateLocale(obj) {
    if (!this.cache[this.locale])
      this._readLocaleFile();
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        this.cache[this.locale][key] = obj[key];
      }
    }
  }
  _taggedLiteral(parts, ...args) {
    let str2 = "";
    parts.forEach(function(part, i) {
      const arg = args[i + 1];
      str2 += part;
      if (typeof arg !== "undefined") {
        str2 += "%s";
      }
    });
    return this.__.apply(this, [str2].concat([].slice.call(args, 1)));
  }
  _enqueueWrite(work) {
    this.writeQueue.push(work);
    if (this.writeQueue.length === 1)
      this._processWriteQueue();
  }
  _processWriteQueue() {
    const _this = this;
    const work = this.writeQueue[0];
    const directory = work.directory;
    const locale = work.locale;
    const cb = work.cb;
    const languageFile = this._resolveLocaleFile(directory, locale);
    const serializedLocale = JSON.stringify(this.cache[locale], null, 2);
    shim.fs.writeFile(languageFile, serializedLocale, "utf-8", function(err) {
      _this.writeQueue.shift();
      if (_this.writeQueue.length > 0)
        _this._processWriteQueue();
      cb(err);
    });
  }
  _readLocaleFile() {
    let localeLookup = {};
    const languageFile = this._resolveLocaleFile(this.directory, this.locale);
    try {
      if (shim.fs.readFileSync) {
        localeLookup = JSON.parse(shim.fs.readFileSync(languageFile, "utf-8"));
      }
    } catch (err) {
      if (err instanceof SyntaxError) {
        err.message = "syntax error in " + languageFile;
      }
      if (err.code === "ENOENT")
        localeLookup = {};
      else
        throw err;
    }
    this.cache[this.locale] = localeLookup;
  }
  _resolveLocaleFile(directory, locale) {
    let file = shim.resolve(directory, "./", locale + ".json");
    if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf("_")) {
      const languageFile = shim.resolve(directory, "./", locale.split("_")[0] + ".json");
      if (this._fileExistsSync(languageFile))
        file = languageFile;
    }
    return file;
  }
  _fileExistsSync(file) {
    return shim.exists(file);
  }
};
function y18n(opts, _shim) {
  shim = _shim;
  const y18n3 = new Y18N(opts);
  return {
    __: y18n3.__.bind(y18n3),
    __n: y18n3.__n.bind(y18n3),
    setLocale: y18n3.setLocale.bind(y18n3),
    getLocale: y18n3.getLocale.bind(y18n3),
    updateLocale: y18n3.updateLocale.bind(y18n3),
    locale: y18n3.locale
  };
}
__name(y18n, "y18n");

// node_modules/y18n/index.mjs
var y18n2 = /* @__PURE__ */ __name((opts) => {
  return y18n(opts, node_default);
}, "y18n");
var y18n_default = y18n2;

// node_modules/yargs/lib/platform-shims/esm.mjs
var REQUIRE_ERROR = "require is not supported by ESM";
var REQUIRE_DIRECTORY_ERROR = "loading a directory of commands is not supported yet for ESM";
var __dirname4;
try {
  __dirname4 = fileURLToPath6(import.meta.url);
} catch (e2) {
  __dirname4 = process.cwd();
}
var mainFilename = __dirname4.substring(0, __dirname4.lastIndexOf("node_modules"));
var esm_default3 = {
  assert: {
    notStrictEqual,
    strictEqual
  },
  cliui: ui,
  findUp: sync_default,
  getEnv: /* @__PURE__ */ __name((key) => {
    return process.env[key];
  }, "getEnv"),
  inspect,
  getCallerFile: /* @__PURE__ */ __name(() => {
    throw new YError(REQUIRE_DIRECTORY_ERROR);
  }, "getCallerFile"),
  getProcessArgvBin,
  mainFilename: mainFilename || process.cwd(),
  Parser: lib_default,
  path: {
    basename: basename12,
    dirname: dirname20,
    extname: extname4,
    relative: relative7,
    resolve: resolve20
  },
  process: {
    argv: /* @__PURE__ */ __name(() => process.argv, "argv"),
    cwd: process.cwd,
    emitWarning: /* @__PURE__ */ __name((warning, type) => process.emitWarning(warning, type), "emitWarning"),
    execPath: /* @__PURE__ */ __name(() => process.execPath, "execPath"),
    exit: process.exit,
    nextTick: process.nextTick,
    stdColumns: typeof process.stdout.columns !== "undefined" ? process.stdout.columns : null
  },
  readFileSync: readFileSync13,
  require: /* @__PURE__ */ __name(() => {
    throw new YError(REQUIRE_ERROR);
  }, "require"),
  requireDirectory: /* @__PURE__ */ __name(() => {
    throw new YError(REQUIRE_DIRECTORY_ERROR);
  }, "requireDirectory"),
  stringWidth: /* @__PURE__ */ __name((str2) => {
    return [...str2].length;
  }, "stringWidth"),
  y18n: y18n_default({
    directory: resolve20(__dirname4, "../../../locales"),
    updateFiles: false
  })
};

// node_modules/yargs/build/lib/yargs-factory.js
init_esbuild_shims();

// node_modules/yargs/build/lib/command.js
init_esbuild_shims();

// node_modules/yargs/build/lib/typings/common-types.js
init_esbuild_shims();
function assertNotStrictEqual(actual, expected, shim3, message) {
  shim3.assert.notStrictEqual(actual, expected, message);
}
__name(assertNotStrictEqual, "assertNotStrictEqual");
function assertSingleKey(actual, shim3) {
  shim3.assert.strictEqual(typeof actual, "string");
}
__name(assertSingleKey, "assertSingleKey");
function objectKeys(object) {
  return Object.keys(object);
}
__name(objectKeys, "objectKeys");

// node_modules/yargs/build/lib/utils/is-promise.js
init_esbuild_shims();
function isPromise(maybePromise) {
  return !!maybePromise && !!maybePromise.then && typeof maybePromise.then === "function";
}
__name(isPromise, "isPromise");

// node_modules/yargs/build/lib/middleware.js
init_esbuild_shims();

// node_modules/yargs/build/lib/argsert.js
init_esbuild_shims();

// node_modules/yargs/build/lib/parse-command.js
init_esbuild_shims();
function parseCommand(cmd) {
  const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, " ");
  const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/);
  const bregex = /\.*[\][<>]/g;
  const firstCommand = splitCommand.shift();
  if (!firstCommand)
    throw new Error(`No command found in: ${cmd}`);
  const parsedCommand = {
    cmd: firstCommand.replace(bregex, ""),
    demanded: [],
    optional: []
  };
  splitCommand.forEach((cmd2, i) => {
    let variadic = false;
    cmd2 = cmd2.replace(/\s/g, "");
    if (/\.+[\]>]/.test(cmd2) && i === splitCommand.length - 1)
      variadic = true;
    if (/^\[/.test(cmd2)) {
      parsedCommand.optional.push({
        cmd: cmd2.replace(bregex, "").split("|"),
        variadic
      });
    } else {
      parsedCommand.demanded.push({
        cmd: cmd2.replace(bregex, "").split("|"),
        variadic
      });
    }
  });
  return parsedCommand;
}
__name(parseCommand, "parseCommand");

// node_modules/yargs/build/lib/argsert.js
var positionName = ["first", "second", "third", "fourth", "fifth", "sixth"];
function argsert(arg1, arg2, arg3) {
  function parseArgs() {
    return typeof arg1 === "object" ? [{ demanded: [], optional: [] }, arg1, arg2] : [
      parseCommand(`cmd ${arg1}`),
      arg2,
      arg3
    ];
  }
  __name(parseArgs, "parseArgs");
  try {
    let position = 0;
    const [parsed, callerArguments, _length] = parseArgs();
    const args = [].slice.call(callerArguments);
    while (args.length && args[args.length - 1] === void 0)
      args.pop();
    const length = _length || args.length;
    if (length < parsed.demanded.length) {
      throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`);
    }
    const totalCommands = parsed.demanded.length + parsed.optional.length;
    if (length > totalCommands) {
      throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`);
    }
    parsed.demanded.forEach((demanded) => {
      const arg = args.shift();
      const observedType = guessType(arg);
      const matchingTypes = demanded.cmd.filter((type) => type === observedType || type === "*");
      if (matchingTypes.length === 0)
        argumentTypeError(observedType, demanded.cmd, position);
      position += 1;
    });
    parsed.optional.forEach((optional) => {
      if (args.length === 0)
        return;
      const arg = args.shift();
      const observedType = guessType(arg);
      const matchingTypes = optional.cmd.filter((type) => type === observedType || type === "*");
      if (matchingTypes.length === 0)
        argumentTypeError(observedType, optional.cmd, position);
      position += 1;
    });
  } catch (err) {
    console.warn(err.stack);
  }
}
__name(argsert, "argsert");
function guessType(arg) {
  if (Array.isArray(arg)) {
    return "array";
  } else if (arg === null) {
    return "null";
  }
  return typeof arg;
}
__name(guessType, "guessType");
function argumentTypeError(observedType, allowedTypes, position) {
  throw new YError(`Invalid ${positionName[position] || "manyith"} argument. Expected ${allowedTypes.join(" or ")} but received ${observedType}.`);
}
__name(argumentTypeError, "argumentTypeError");

// node_modules/yargs/build/lib/middleware.js
var GlobalMiddleware = class {
  static {
    __name(this, "GlobalMiddleware");
  }
  constructor(yargs) {
    this.globalMiddleware = [];
    this.frozens = [];
    this.yargs = yargs;
  }
  addMiddleware(callback, applyBeforeValidation, global2 = true, mutates = false) {
    argsert("<array|function> [boolean] [boolean] [boolean]", [callback, applyBeforeValidation, global2], arguments.length);
    if (Array.isArray(callback)) {
      for (let i = 0; i < callback.length; i++) {
        if (typeof callback[i] !== "function") {
          throw Error("middleware must be a function");
        }
        const m = callback[i];
        m.applyBeforeValidation = applyBeforeValidation;
        m.global = global2;
      }
      Array.prototype.push.apply(this.globalMiddleware, callback);
    } else if (typeof callback === "function") {
      const m = callback;
      m.applyBeforeValidation = applyBeforeValidation;
      m.global = global2;
      m.mutates = mutates;
      this.globalMiddleware.push(callback);
    }
    return this.yargs;
  }
  addCoerceMiddleware(callback, option2) {
    const aliases = this.yargs.getAliases();
    this.globalMiddleware = this.globalMiddleware.filter((m) => {
      const toCheck = [...aliases[option2] || [], option2];
      if (!m.option)
        return true;
      else
        return !toCheck.includes(m.option);
    });
    callback.option = option2;
    return this.addMiddleware(callback, true, true, true);
  }
  getMiddleware() {
    return this.globalMiddleware;
  }
  freeze() {
    this.frozens.push([...this.globalMiddleware]);
  }
  unfreeze() {
    const frozen = this.frozens.pop();
    if (frozen !== void 0)
      this.globalMiddleware = frozen;
  }
  reset() {
    this.globalMiddleware = this.globalMiddleware.filter((m) => m.global);
  }
};
function commandMiddlewareFactory(commandMiddleware) {
  if (!commandMiddleware)
    return [];
  return commandMiddleware.map((middleware) => {
    middleware.applyBeforeValidation = false;
    return middleware;
  });
}
__name(commandMiddlewareFactory, "commandMiddlewareFactory");
function applyMiddleware(argv, yargs, middlewares, beforeValidation) {
  return middlewares.reduce((acc, middleware) => {
    if (middleware.applyBeforeValidation !== beforeValidation) {
      return acc;
    }
    if (middleware.mutates) {
      if (middleware.applied)
        return acc;
      middleware.applied = true;
    }
    if (isPromise(acc)) {
      return acc.then((initialObj) => Promise.all([initialObj, middleware(initialObj, yargs)])).then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj));
    } else {
      const result = middleware(acc, yargs);
      return isPromise(result) ? result.then((middlewareObj) => Object.assign(acc, middlewareObj)) : Object.assign(acc, result);
    }
  }, argv);
}
__name(applyMiddleware, "applyMiddleware");

// node_modules/yargs/build/lib/utils/maybe-async-result.js
init_esbuild_shims();
function maybeAsyncResult(getResult, resultHandler, errorHandler = (err) => {
  throw err;
}) {
  try {
    const result = isFunction(getResult) ? getResult() : getResult;
    return isPromise(result) ? result.then((result2) => resultHandler(result2)) : resultHandler(result);
  } catch (err) {
    return errorHandler(err);
  }
}
__name(maybeAsyncResult, "maybeAsyncResult");
function isFunction(arg) {
  return typeof arg === "function";
}
__name(isFunction, "isFunction");

// node_modules/yargs/build/lib/utils/which-module.js
init_esbuild_shims();
function whichModule(exported) {
  if (typeof __require === "undefined")
    return null;
  for (let i = 0, files = Object.keys(__require.cache), mod2; i < files.length; i++) {
    mod2 = __require.cache[files[i]];
    if (mod2.exports === exported)
      return mod2;
  }
  return null;
}
__name(whichModule, "whichModule");

// node_modules/yargs/build/lib/command.js
var DEFAULT_MARKER = /(^\*)|(^\$0)/;
var CommandInstance = class {
  static {
    __name(this, "CommandInstance");
  }
  constructor(usage2, validation2, globalMiddleware, shim3) {
    this.requireCache = /* @__PURE__ */ new Set();
    this.handlers = {};
    this.aliasMap = {};
    this.frozens = [];
    this.shim = shim3;
    this.usage = usage2;
    this.globalMiddleware = globalMiddleware;
    this.validation = validation2;
  }
  addDirectory(dir, req, callerFile, opts) {
    opts = opts || {};
    if (typeof opts.recurse !== "boolean")
      opts.recurse = false;
    if (!Array.isArray(opts.extensions))
      opts.extensions = ["js"];
    const parentVisit = typeof opts.visit === "function" ? opts.visit : (o2) => o2;
    opts.visit = (obj, joined, filename) => {
      const visited = parentVisit(obj, joined, filename);
      if (visited) {
        if (this.requireCache.has(joined))
          return visited;
        else
          this.requireCache.add(joined);
        this.addHandler(visited);
      }
      return visited;
    };
    this.shim.requireDirectory({ require: req, filename: callerFile }, dir, opts);
  }
  addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) {
    let aliases = [];
    const middlewares = commandMiddlewareFactory(commandMiddleware);
    handler = handler || (() => {
    });
    if (Array.isArray(cmd)) {
      if (isCommandAndAliases(cmd)) {
        [cmd, ...aliases] = cmd;
      } else {
        for (const command2 of cmd) {
          this.addHandler(command2);
        }
      }
    } else if (isCommandHandlerDefinition(cmd)) {
      let command2 = Array.isArray(cmd.command) || typeof cmd.command === "string" ? cmd.command : this.moduleName(cmd);
      if (cmd.aliases)
        command2 = [].concat(command2).concat(cmd.aliases);
      this.addHandler(command2, this.extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated);
      return;
    } else if (isCommandBuilderDefinition(builder)) {
      this.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated);
      return;
    }
    if (typeof cmd === "string") {
      const parsedCommand = parseCommand(cmd);
      aliases = aliases.map((alias) => parseCommand(alias).cmd);
      let isDefault = false;
      const parsedAliases = [parsedCommand.cmd].concat(aliases).filter((c3) => {
        if (DEFAULT_MARKER.test(c3)) {
          isDefault = true;
          return false;
        }
        return true;
      });
      if (parsedAliases.length === 0 && isDefault)
        parsedAliases.push("$0");
      if (isDefault) {
        parsedCommand.cmd = parsedAliases[0];
        aliases = parsedAliases.slice(1);
        cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd);
      }
      aliases.forEach((alias) => {
        this.aliasMap[alias] = parsedCommand.cmd;
      });
      if (description !== false) {
        this.usage.command(cmd, description, isDefault, aliases, deprecated);
      }
      this.handlers[parsedCommand.cmd] = {
        original: cmd,
        description,
        handler,
        builder: builder || {},
        middlewares,
        deprecated,
        demanded: parsedCommand.demanded,
        optional: parsedCommand.optional
      };
      if (isDefault)
        this.defaultCommand = this.handlers[parsedCommand.cmd];
    }
  }
  getCommandHandlers() {
    return this.handlers;
  }
  getCommands() {
    return Object.keys(this.handlers).concat(Object.keys(this.aliasMap));
  }
  hasDefaultCommand() {
    return !!this.defaultCommand;
  }
  runCommand(command2, yargs, parsed, commandIndex, helpOnly, helpOrVersionSet) {
    const commandHandler = this.handlers[command2] || this.handlers[this.aliasMap[command2]] || this.defaultCommand;
    const currentContext = yargs.getInternalMethods().getContext();
    const parentCommands = currentContext.commands.slice();
    const isDefaultCommand = !command2;
    if (command2) {
      currentContext.commands.push(command2);
      currentContext.fullCommands.push(commandHandler.original);
    }
    const builderResult = this.applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, parsed.aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet);
    return isPromise(builderResult) ? builderResult.then((result) => this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, result.innerArgv, currentContext, helpOnly, result.aliases, yargs)) : this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, builderResult.innerArgv, currentContext, helpOnly, builderResult.aliases, yargs);
  }
  applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet) {
    const builder = commandHandler.builder;
    let innerYargs = yargs;
    if (isCommandBuilderCallback(builder)) {
      yargs.getInternalMethods().getUsageInstance().freeze();
      const builderOutput = builder(yargs.getInternalMethods().reset(aliases), helpOrVersionSet);
      if (isPromise(builderOutput)) {
        return builderOutput.then((output) => {
          innerYargs = isYargsInstance(output) ? output : yargs;
          return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
        });
      }
    } else if (isCommandBuilderOptionDefinitions(builder)) {
      yargs.getInternalMethods().getUsageInstance().freeze();
      innerYargs = yargs.getInternalMethods().reset(aliases);
      Object.keys(commandHandler.builder).forEach((key) => {
        innerYargs.option(key, builder[key]);
      });
    }
    return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
  }
  parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly) {
    if (isDefaultCommand)
      innerYargs.getInternalMethods().getUsageInstance().unfreeze(true);
    if (this.shouldUpdateUsage(innerYargs)) {
      innerYargs.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description);
    }
    const innerArgv = innerYargs.getInternalMethods().runYargsParserAndExecuteCommands(null, void 0, true, commandIndex, helpOnly);
    return isPromise(innerArgv) ? innerArgv.then((argv) => ({
      aliases: innerYargs.parsed.aliases,
      innerArgv: argv
    })) : {
      aliases: innerYargs.parsed.aliases,
      innerArgv
    };
  }
  shouldUpdateUsage(yargs) {
    return !yargs.getInternalMethods().getUsageInstance().getUsageDisabled() && yargs.getInternalMethods().getUsageInstance().getUsage().length === 0;
  }
  usageFromParentCommandsCommandHandler(parentCommands, commandHandler) {
    const c3 = DEFAULT_MARKER.test(commandHandler.original) ? commandHandler.original.replace(DEFAULT_MARKER, "").trim() : commandHandler.original;
    const pc = parentCommands.filter((c4) => {
      return !DEFAULT_MARKER.test(c4);
    });
    pc.push(c3);
    return `$0 ${pc.join(" ")}`;
  }
  handleValidationAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, aliases, yargs, middlewares, positionalMap) {
    if (!yargs.getInternalMethods().getHasOutput()) {
      const validation2 = yargs.getInternalMethods().runValidation(aliases, positionalMap, yargs.parsed.error, isDefaultCommand);
      innerArgv = maybeAsyncResult(innerArgv, (result) => {
        validation2(result);
        return result;
      });
    }
    if (commandHandler.handler && !yargs.getInternalMethods().getHasOutput()) {
      yargs.getInternalMethods().setHasOutput();
      const populateDoubleDash = !!yargs.getOptions().configuration["populate--"];
      yargs.getInternalMethods().postProcess(innerArgv, populateDoubleDash, false, false);
      innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false);
      innerArgv = maybeAsyncResult(innerArgv, (result) => {
        const handlerResult = commandHandler.handler(result);
        return isPromise(handlerResult) ? handlerResult.then(() => result) : result;
      });
      if (!isDefaultCommand) {
        yargs.getInternalMethods().getUsageInstance().cacheHelpMessage();
      }
      if (isPromise(innerArgv) && !yargs.getInternalMethods().hasParseCallback()) {
        innerArgv.catch((error) => {
          try {
            yargs.getInternalMethods().getUsageInstance().fail(null, error);
          } catch (_err) {
          }
        });
      }
    }
    if (!isDefaultCommand) {
      currentContext.commands.pop();
      currentContext.fullCommands.pop();
    }
    return innerArgv;
  }
  applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, helpOnly, aliases, yargs) {
    let positionalMap = {};
    if (helpOnly)
      return innerArgv;
    if (!yargs.getInternalMethods().getHasOutput()) {
      positionalMap = this.populatePositionals(commandHandler, innerArgv, currentContext, yargs);
    }
    const middlewares = this.globalMiddleware.getMiddleware().slice(0).concat(commandHandler.middlewares);
    const maybePromiseArgv = applyMiddleware(innerArgv, yargs, middlewares, true);
    return isPromise(maybePromiseArgv) ? maybePromiseArgv.then((resolvedInnerArgv) => this.handleValidationAndGetResult(isDefaultCommand, commandHandler, resolvedInnerArgv, currentContext, aliases, yargs, middlewares, positionalMap)) : this.handleValidationAndGetResult(isDefaultCommand, commandHandler, maybePromiseArgv, currentContext, aliases, yargs, middlewares, positionalMap);
  }
  populatePositionals(commandHandler, argv, context2, yargs) {
    argv._ = argv._.slice(context2.commands.length);
    const demanded = commandHandler.demanded.slice(0);
    const optional = commandHandler.optional.slice(0);
    const positionalMap = {};
    this.validation.positionalCount(demanded.length, argv._.length);
    while (demanded.length) {
      const demand = demanded.shift();
      this.populatePositional(demand, argv, positionalMap);
    }
    while (optional.length) {
      const maybe = optional.shift();
      this.populatePositional(maybe, argv, positionalMap);
    }
    argv._ = context2.commands.concat(argv._.map((a) => "" + a));
    this.postProcessPositionals(argv, positionalMap, this.cmdToParseOptions(commandHandler.original), yargs);
    return positionalMap;
  }
  populatePositional(positional, argv, positionalMap) {
    const cmd = positional.cmd[0];
    if (positional.variadic) {
      positionalMap[cmd] = argv._.splice(0).map(String);
    } else {
      if (argv._.length)
        positionalMap[cmd] = [String(argv._.shift())];
    }
  }
  cmdToParseOptions(cmdString) {
    const parseOptions = {
      array: [],
      default: {},
      alias: {},
      demand: {}
    };
    const parsed = parseCommand(cmdString);
    parsed.demanded.forEach((d) => {
      const [cmd, ...aliases] = d.cmd;
      if (d.variadic) {
        parseOptions.array.push(cmd);
        parseOptions.default[cmd] = [];
      }
      parseOptions.alias[cmd] = aliases;
      parseOptions.demand[cmd] = true;
    });
    parsed.optional.forEach((o2) => {
      const [cmd, ...aliases] = o2.cmd;
      if (o2.variadic) {
        parseOptions.array.push(cmd);
        parseOptions.default[cmd] = [];
      }
      parseOptions.alias[cmd] = aliases;
    });
    return parseOptions;
  }
  postProcessPositionals(argv, positionalMap, parseOptions, yargs) {
    const options2 = Object.assign({}, yargs.getOptions());
    options2.default = Object.assign(parseOptions.default, options2.default);
    for (const key of Object.keys(parseOptions.alias)) {
      options2.alias[key] = (options2.alias[key] || []).concat(parseOptions.alias[key]);
    }
    options2.array = options2.array.concat(parseOptions.array);
    options2.config = {};
    const unparsed = [];
    Object.keys(positionalMap).forEach((key) => {
      positionalMap[key].map((value) => {
        if (options2.configuration["unknown-options-as-args"])
          options2.key[key] = true;
        unparsed.push(`--${key}`);
        unparsed.push(value);
      });
    });
    if (!unparsed.length)
      return;
    const config = Object.assign({}, options2.configuration, {
      "populate--": false
    });
    const parsed = this.shim.Parser.detailed(unparsed, Object.assign({}, options2, {
      configuration: config
    }));
    if (parsed.error) {
      yargs.getInternalMethods().getUsageInstance().fail(parsed.error.message, parsed.error);
    } else {
      const positionalKeys = Object.keys(positionalMap);
      Object.keys(positionalMap).forEach((key) => {
        positionalKeys.push(...parsed.aliases[key]);
      });
      Object.keys(parsed.argv).forEach((key) => {
        if (positionalKeys.includes(key)) {
          if (!positionalMap[key])
            positionalMap[key] = parsed.argv[key];
          if (!this.isInConfigs(yargs, key) && !this.isDefaulted(yargs, key) && Object.prototype.hasOwnProperty.call(argv, key) && Object.prototype.hasOwnProperty.call(parsed.argv, key) && (Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))) {
            argv[key] = [].concat(argv[key], parsed.argv[key]);
          } else {
            argv[key] = parsed.argv[key];
          }
        }
      });
    }
  }
  isDefaulted(yargs, key) {
    const { default: defaults3 } = yargs.getOptions();
    return Object.prototype.hasOwnProperty.call(defaults3, key) || Object.prototype.hasOwnProperty.call(defaults3, this.shim.Parser.camelCase(key));
  }
  isInConfigs(yargs, key) {
    const { configObjects } = yargs.getOptions();
    return configObjects.some((c3) => Object.prototype.hasOwnProperty.call(c3, key)) || configObjects.some((c3) => Object.prototype.hasOwnProperty.call(c3, this.shim.Parser.camelCase(key)));
  }
  runDefaultBuilderOn(yargs) {
    if (!this.defaultCommand)
      return;
    if (this.shouldUpdateUsage(yargs)) {
      const commandString = DEFAULT_MARKER.test(this.defaultCommand.original) ? this.defaultCommand.original : this.defaultCommand.original.replace(/^[^[\]<>]*/, "$0 ");
      yargs.getInternalMethods().getUsageInstance().usage(commandString, this.defaultCommand.description);
    }
    const builder = this.defaultCommand.builder;
    if (isCommandBuilderCallback(builder)) {
      return builder(yargs, true);
    } else if (!isCommandBuilderDefinition(builder)) {
      Object.keys(builder).forEach((key) => {
        yargs.option(key, builder[key]);
      });
    }
    return void 0;
  }
  moduleName(obj) {
    const mod2 = whichModule(obj);
    if (!mod2)
      throw new Error(`No command name given for module: ${this.shim.inspect(obj)}`);
    return this.commandFromFilename(mod2.filename);
  }
  commandFromFilename(filename) {
    return this.shim.path.basename(filename, this.shim.path.extname(filename));
  }
  extractDesc({ describe, description, desc: desc2 }) {
    for (const test of [describe, description, desc2]) {
      if (typeof test === "string" || test === false)
        return test;
      assertNotStrictEqual(test, true, this.shim);
    }
    return false;
  }
  freeze() {
    this.frozens.push({
      handlers: this.handlers,
      aliasMap: this.aliasMap,
      defaultCommand: this.defaultCommand
    });
  }
  unfreeze() {
    const frozen = this.frozens.pop();
    assertNotStrictEqual(frozen, void 0, this.shim);
    ({
      handlers: this.handlers,
      aliasMap: this.aliasMap,
      defaultCommand: this.defaultCommand
    } = frozen);
  }
  reset() {
    this.handlers = {};
    this.aliasMap = {};
    this.defaultCommand = void 0;
    this.requireCache = /* @__PURE__ */ new Set();
    return this;
  }
};
function command(usage2, validation2, globalMiddleware, shim3) {
  return new CommandInstance(usage2, validation2, globalMiddleware, shim3);
}
__name(command, "command");
function isCommandBuilderDefinition(builder) {
  return typeof builder === "object" && !!builder.builder && typeof builder.handler === "function";
}
__name(isCommandBuilderDefinition, "isCommandBuilderDefinition");
function isCommandAndAliases(cmd) {
  return cmd.every((c3) => typeof c3 === "string");
}
__name(isCommandAndAliases, "isCommandAndAliases");
function isCommandBuilderCallback(builder) {
  return typeof builder === "function";
}
__name(isCommandBuilderCallback, "isCommandBuilderCallback");
function isCommandBuilderOptionDefinitions(builder) {
  return typeof builder === "object";
}
__name(isCommandBuilderOptionDefinitions, "isCommandBuilderOptionDefinitions");
function isCommandHandlerDefinition(cmd) {
  return typeof cmd === "object" && !Array.isArray(cmd);
}
__name(isCommandHandlerDefinition, "isCommandHandlerDefinition");

// node_modules/yargs/build/lib/usage.js
init_esbuild_shims();

// node_modules/yargs/build/lib/utils/obj-filter.js
init_esbuild_shims();
function objFilter(original = {}, filter4 = () => true) {
  const obj = {};
  objectKeys(original).forEach((key) => {
    if (filter4(key, original[key])) {
      obj[key] = original[key];
    }
  });
  return obj;
}
__name(objFilter, "objFilter");

// node_modules/yargs/build/lib/utils/set-blocking.js
init_esbuild_shims();
function setBlocking(blocking) {
  if (typeof process === "undefined")
    return;
  [process.stdout, process.stderr].forEach((_stream) => {
    const stream2 = _stream;
    if (stream2._handle && stream2.isTTY && typeof stream2._handle.setBlocking === "function") {
      stream2._handle.setBlocking(blocking);
    }
  });
}
__name(setBlocking, "setBlocking");

// node_modules/yargs/build/lib/usage.js
function isBoolean(fail) {
  return typeof fail === "boolean";
}
__name(isBoolean, "isBoolean");
function usage(yargs, shim3) {
  const __ = shim3.y18n.__;
  const self2 = {};
  const fails = [];
  self2.failFn = /* @__PURE__ */ __name(function failFn(f) {
    fails.push(f);
  }, "failFn");
  let failMessage = null;
  let globalFailMessage = null;
  let showHelpOnFail = true;
  self2.showHelpOnFail = /* @__PURE__ */ __name(function showHelpOnFailFn(arg1 = true, arg2) {
    const [enabled, message] = typeof arg1 === "string" ? [true, arg1] : [arg1, arg2];
    if (yargs.getInternalMethods().isGlobalContext()) {
      globalFailMessage = message;
    }
    failMessage = message;
    showHelpOnFail = enabled;
    return self2;
  }, "showHelpOnFailFn");
  let failureOutput = false;
  self2.fail = /* @__PURE__ */ __name(function fail(msg, err) {
    const logger6 = yargs.getInternalMethods().getLoggerInstance();
    if (fails.length) {
      for (let i = fails.length - 1; i >= 0; --i) {
        const fail2 = fails[i];
        if (isBoolean(fail2)) {
          if (err)
            throw err;
          else if (msg)
            throw Error(msg);
        } else {
          fail2(msg, err, self2);
        }
      }
    } else {
      if (yargs.getExitProcess())
        setBlocking(true);
      if (!failureOutput) {
        failureOutput = true;
        if (showHelpOnFail) {
          yargs.showHelp("error");
          logger6.error();
        }
        if (msg || err)
          logger6.error(msg || err);
        const globalOrCommandFailMessage = failMessage || globalFailMessage;
        if (globalOrCommandFailMessage) {
          if (msg || err)
            logger6.error("");
          logger6.error(globalOrCommandFailMessage);
        }
      }
      err = err || new YError(msg);
      if (yargs.getExitProcess()) {
        return yargs.exit(1);
      } else if (yargs.getInternalMethods().hasParseCallback()) {
        return yargs.exit(1, err);
      } else {
        throw err;
      }
    }
  }, "fail");
  let usages = [];
  let usageDisabled = false;
  self2.usage = (msg, description) => {
    if (msg === null) {
      usageDisabled = true;
      usages = [];
      return self2;
    }
    usageDisabled = false;
    usages.push([msg, description || ""]);
    return self2;
  };
  self2.getUsage = () => {
    return usages;
  };
  self2.getUsageDisabled = () => {
    return usageDisabled;
  };
  self2.getPositionalGroupName = () => {
    return __("Positionals:");
  };
  let examples = [];
  self2.example = (cmd, description) => {
    examples.push([cmd, description || ""]);
  };
  let commands = [];
  self2.command = /* @__PURE__ */ __name(function command2(cmd, description, isDefault, aliases, deprecated = false) {
    if (isDefault) {
      commands = commands.map((cmdArray) => {
        cmdArray[2] = false;
        return cmdArray;
      });
    }
    commands.push([cmd, description || "", isDefault, aliases, deprecated]);
  }, "command");
  self2.getCommands = () => commands;
  let descriptions = {};
  self2.describe = /* @__PURE__ */ __name(function describe(keyOrKeys, desc2) {
    if (Array.isArray(keyOrKeys)) {
      keyOrKeys.forEach((k) => {
        self2.describe(k, desc2);
      });
    } else if (typeof keyOrKeys === "object") {
      Object.keys(keyOrKeys).forEach((k) => {
        self2.describe(k, keyOrKeys[k]);
      });
    } else {
      descriptions[keyOrKeys] = desc2;
    }
  }, "describe");
  self2.getDescriptions = () => descriptions;
  let epilogs = [];
  self2.epilog = (msg) => {
    epilogs.push(msg);
  };
  let wrapSet = false;
  let wrap2;
  self2.wrap = (cols) => {
    wrapSet = true;
    wrap2 = cols;
  };
  self2.getWrap = () => {
    if (shim3.getEnv("YARGS_DISABLE_WRAP")) {
      return null;
    }
    if (!wrapSet) {
      wrap2 = windowWidth();
      wrapSet = true;
    }
    return wrap2;
  };
  const deferY18nLookupPrefix = "__yargsString__:";
  self2.deferY18nLookup = (str2) => deferY18nLookupPrefix + str2;
  self2.help = /* @__PURE__ */ __name(function help() {
    if (cachedHelpMessage)
      return cachedHelpMessage;
    normalizeAliases();
    const base$0 = yargs.customScriptName ? yargs.$0 : shim3.path.basename(yargs.$0);
    const demandedOptions = yargs.getDemandedOptions();
    const demandedCommands = yargs.getDemandedCommands();
    const deprecatedOptions = yargs.getDeprecatedOptions();
    const groups = yargs.getGroups();
    const options2 = yargs.getOptions();
    let keys = [];
    keys = keys.concat(Object.keys(descriptions));
    keys = keys.concat(Object.keys(demandedOptions));
    keys = keys.concat(Object.keys(demandedCommands));
    keys = keys.concat(Object.keys(options2.default));
    keys = keys.filter(filterHiddenOptions);
    keys = Object.keys(keys.reduce((acc, key) => {
      if (key !== "_")
        acc[key] = true;
      return acc;
    }, {}));
    const theWrap = self2.getWrap();
    const ui2 = shim3.cliui({
      width: theWrap,
      wrap: !!theWrap
    });
    if (!usageDisabled) {
      if (usages.length) {
        usages.forEach((usage2) => {
          ui2.div({ text: `${usage2[0].replace(/\$0/g, base$0)}` });
          if (usage2[1]) {
            ui2.div({ text: `${usage2[1]}`, padding: [1, 0, 0, 0] });
          }
        });
        ui2.div();
      } else if (commands.length) {
        let u = null;
        if (demandedCommands._) {
          u = `${base$0} <${__("command")}>
`;
        } else {
          u = `${base$0} [${__("command")}]
`;
        }
        ui2.div(`${u}`);
      }
    }
    if (commands.length > 1 || commands.length === 1 && !commands[0][2]) {
      ui2.div(__("Commands:"));
      const context2 = yargs.getInternalMethods().getContext();
      const parentCommands = context2.commands.length ? `${context2.commands.join(" ")} ` : "";
      if (yargs.getInternalMethods().getParserConfiguration()["sort-commands"] === true) {
        commands = commands.sort((a, b) => a[0].localeCompare(b[0]));
      }
      const prefix = base$0 ? `${base$0} ` : "";
      commands.forEach((command2) => {
        const commandString = `${prefix}${parentCommands}${command2[0].replace(/^\$0 ?/, "")}`;
        ui2.span({
          text: commandString,
          padding: [0, 2, 0, 2],
          width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4
        }, { text: command2[1] });
        const hints = [];
        if (command2[2])
          hints.push(`[${__("default")}]`);
        if (command2[3] && command2[3].length) {
          hints.push(`[${__("aliases:")} ${command2[3].join(", ")}]`);
        }
        if (command2[4]) {
          if (typeof command2[4] === "string") {
            hints.push(`[${__("deprecated: %s", command2[4])}]`);
          } else {
            hints.push(`[${__("deprecated")}]`);
          }
        }
        if (hints.length) {
          ui2.div({
            text: hints.join(" "),
            padding: [0, 0, 0, 2],
            align: "right"
          });
        } else {
          ui2.div();
        }
      });
      ui2.div();
    }
    const aliasKeys = (Object.keys(options2.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []);
    keys = keys.filter((key) => !yargs.parsed.newAliases[key] && aliasKeys.every((alias) => (options2.alias[alias] || []).indexOf(key) === -1));
    const defaultGroup = __("Options:");
    if (!groups[defaultGroup])
      groups[defaultGroup] = [];
    addUngroupedKeys(keys, options2.alias, groups, defaultGroup);
    const isLongSwitch = /* @__PURE__ */ __name((sw) => /^--/.test(getText2(sw)), "isLongSwitch");
    const displayedGroups = Object.keys(groups).filter((groupName) => groups[groupName].length > 0).map((groupName) => {
      const normalizedKeys = groups[groupName].filter(filterHiddenOptions).map((key) => {
        if (aliasKeys.includes(key))
          return key;
        for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== void 0; i++) {
          if ((options2.alias[aliasKey] || []).includes(key))
            return aliasKey;
        }
        return key;
      });
      return { groupName, normalizedKeys };
    }).filter(({ normalizedKeys }) => normalizedKeys.length > 0).map(({ groupName, normalizedKeys }) => {
      const switches = normalizedKeys.reduce((acc, key) => {
        acc[key] = [key].concat(options2.alias[key] || []).map((sw) => {
          if (groupName === self2.getPositionalGroupName())
            return sw;
          else {
            return (/^[0-9]$/.test(sw) ? options2.boolean.includes(key) ? "-" : "--" : sw.length > 1 ? "--" : "-") + sw;
          }
        }).sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2) ? 0 : isLongSwitch(sw1) ? 1 : -1).join(", ");
        return acc;
      }, {});
      return { groupName, normalizedKeys, switches };
    });
    const shortSwitchesUsed = displayedGroups.filter(({ groupName }) => groupName !== self2.getPositionalGroupName()).some(({ normalizedKeys, switches }) => !normalizedKeys.every((key) => isLongSwitch(switches[key])));
    if (shortSwitchesUsed) {
      displayedGroups.filter(({ groupName }) => groupName !== self2.getPositionalGroupName()).forEach(({ normalizedKeys, switches }) => {
        normalizedKeys.forEach((key) => {
          if (isLongSwitch(switches[key])) {
            switches[key] = addIndentation(switches[key], "-x, ".length);
          }
        });
      });
    }
    displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => {
      ui2.div(groupName);
      normalizedKeys.forEach((key) => {
        const kswitch = switches[key];
        let desc2 = descriptions[key] || "";
        let type = null;
        if (desc2.includes(deferY18nLookupPrefix))
          desc2 = __(desc2.substring(deferY18nLookupPrefix.length));
        if (options2.boolean.includes(key))
          type = `[${__("boolean")}]`;
        if (options2.count.includes(key))
          type = `[${__("count")}]`;
        if (options2.string.includes(key))
          type = `[${__("string")}]`;
        if (options2.normalize.includes(key))
          type = `[${__("string")}]`;
        if (options2.array.includes(key))
          type = `[${__("array")}]`;
        if (options2.number.includes(key))
          type = `[${__("number")}]`;
        const deprecatedExtra = /* @__PURE__ */ __name((deprecated) => typeof deprecated === "string" ? `[${__("deprecated: %s", deprecated)}]` : `[${__("deprecated")}]`, "deprecatedExtra");
        const extra = [
          key in deprecatedOptions ? deprecatedExtra(deprecatedOptions[key]) : null,
          type,
          key in demandedOptions ? `[${__("required")}]` : null,
          options2.choices && options2.choices[key] ? `[${__("choices:")} ${self2.stringifiedValues(options2.choices[key])}]` : null,
          defaultString(options2.default[key], options2.defaultDescription[key])
        ].filter(Boolean).join(" ");
        ui2.span({
          text: getText2(kswitch),
          padding: [0, 2, 0, 2 + getIndentation(kswitch)],
          width: maxWidth(switches, theWrap) + 4
        }, desc2);
        const shouldHideOptionExtras = yargs.getInternalMethods().getUsageConfiguration()["hide-types"] === true;
        if (extra && !shouldHideOptionExtras)
          ui2.div({ text: extra, padding: [0, 0, 0, 2], align: "right" });
        else
          ui2.div();
      });
      ui2.div();
    });
    if (examples.length) {
      ui2.div(__("Examples:"));
      examples.forEach((example) => {
        example[0] = example[0].replace(/\$0/g, base$0);
      });
      examples.forEach((example) => {
        if (example[1] === "") {
          ui2.div({
            text: example[0],
            padding: [0, 2, 0, 2]
          });
        } else {
          ui2.div({
            text: example[0],
            padding: [0, 2, 0, 2],
            width: maxWidth(examples, theWrap) + 4
          }, {
            text: example[1]
          });
        }
      });
      ui2.div();
    }
    if (epilogs.length > 0) {
      const e2 = epilogs.map((epilog) => epilog.replace(/\$0/g, base$0)).join("\n");
      ui2.div(`${e2}
`);
    }
    return ui2.toString().replace(/\s*$/, "");
  }, "help");
  function maxWidth(table, theWrap, modifier) {
    let width = 0;
    if (!Array.isArray(table)) {
      table = Object.values(table).map((v) => [v]);
    }
    table.forEach((v) => {
      width = Math.max(shim3.stringWidth(modifier ? `${modifier} ${getText2(v[0])}` : getText2(v[0])) + getIndentation(v[0]), width);
    });
    if (theWrap)
      width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10));
    return width;
  }
  __name(maxWidth, "maxWidth");
  function normalizeAliases() {
    const demandedOptions = yargs.getDemandedOptions();
    const options2 = yargs.getOptions();
    (Object.keys(options2.alias) || []).forEach((key) => {
      options2.alias[key].forEach((alias) => {
        if (descriptions[alias])
          self2.describe(key, descriptions[alias]);
        if (alias in demandedOptions)
          yargs.demandOption(key, demandedOptions[alias]);
        if (options2.boolean.includes(alias))
          yargs.boolean(key);
        if (options2.count.includes(alias))
          yargs.count(key);
        if (options2.string.includes(alias))
          yargs.string(key);
        if (options2.normalize.includes(alias))
          yargs.normalize(key);
        if (options2.array.includes(alias))
          yargs.array(key);
        if (options2.number.includes(alias))
          yargs.number(key);
      });
    });
  }
  __name(normalizeAliases, "normalizeAliases");
  let cachedHelpMessage;
  self2.cacheHelpMessage = function() {
    cachedHelpMessage = this.help();
  };
  self2.clearCachedHelpMessage = function() {
    cachedHelpMessage = void 0;
  };
  self2.hasCachedHelpMessage = function() {
    return !!cachedHelpMessage;
  };
  function addUngroupedKeys(keys, aliases, groups, defaultGroup) {
    let groupedKeys = [];
    let toCheck = null;
    Object.keys(groups).forEach((group) => {
      groupedKeys = groupedKeys.concat(groups[group]);
    });
    keys.forEach((key) => {
      toCheck = [key].concat(aliases[key]);
      if (!toCheck.some((k) => groupedKeys.indexOf(k) !== -1)) {
        groups[defaultGroup].push(key);
      }
    });
    return groupedKeys;
  }
  __name(addUngroupedKeys, "addUngroupedKeys");
  function filterHiddenOptions(key) {
    return yargs.getOptions().hiddenOptions.indexOf(key) < 0 || yargs.parsed.argv[yargs.getOptions().showHiddenOpt];
  }
  __name(filterHiddenOptions, "filterHiddenOptions");
  self2.showHelp = (level) => {
    const logger6 = yargs.getInternalMethods().getLoggerInstance();
    if (!level)
      level = "error";
    const emit = typeof level === "function" ? level : logger6[level];
    emit(self2.help());
  };
  self2.functionDescription = (fn) => {
    const description = fn.name ? shim3.Parser.decamelize(fn.name, "-") : __("generated-value");
    return ["(", description, ")"].join("");
  };
  self2.stringifiedValues = /* @__PURE__ */ __name(function stringifiedValues(values, separator) {
    let string = "";
    const sep7 = separator || ", ";
    const array = [].concat(values);
    if (!values || !array.length)
      return string;
    array.forEach((value) => {
      if (string.length)
        string += sep7;
      string += JSON.stringify(value);
    });
    return string;
  }, "stringifiedValues");
  function defaultString(value, defaultDescription) {
    let string = `[${__("default:")} `;
    if (value === void 0 && !defaultDescription)
      return null;
    if (defaultDescription) {
      string += defaultDescription;
    } else {
      switch (typeof value) {
        case "string":
          string += `"${value}"`;
          break;
        case "object":
          string += JSON.stringify(value);
          break;
        default:
          string += value;
      }
    }
    return `${string}]`;
  }
  __name(defaultString, "defaultString");
  function windowWidth() {
    const maxWidth2 = 80;
    if (shim3.process.stdColumns) {
      return Math.min(maxWidth2, shim3.process.stdColumns);
    } else {
      return maxWidth2;
    }
  }
  __name(windowWidth, "windowWidth");
  let version2 = null;
  self2.version = (ver) => {
    version2 = ver;
  };
  self2.showVersion = (level) => {
    const logger6 = yargs.getInternalMethods().getLoggerInstance();
    if (!level)
      level = "error";
    const emit = typeof level === "function" ? level : logger6[level];
    emit(version2);
  };
  self2.reset = /* @__PURE__ */ __name(function reset(localLookup) {
    failMessage = null;
    failureOutput = false;
    usages = [];
    usageDisabled = false;
    epilogs = [];
    examples = [];
    commands = [];
    descriptions = objFilter(descriptions, (k) => !localLookup[k]);
    return self2;
  }, "reset");
  const frozens = [];
  self2.freeze = /* @__PURE__ */ __name(function freeze() {
    frozens.push({
      failMessage,
      failureOutput,
      usages,
      usageDisabled,
      epilogs,
      examples,
      commands,
      descriptions
    });
  }, "freeze");
  self2.unfreeze = /* @__PURE__ */ __name(function unfreeze(defaultCommand = false) {
    const frozen = frozens.pop();
    if (!frozen)
      return;
    if (defaultCommand) {
      descriptions = { ...frozen.descriptions, ...descriptions };
      commands = [...frozen.commands, ...commands];
      usages = [...frozen.usages, ...usages];
      examples = [...frozen.examples, ...examples];
      epilogs = [...frozen.epilogs, ...epilogs];
    } else {
      ({
        failMessage,
        failureOutput,
        usages,
        usageDisabled,
        epilogs,
        examples,
        commands,
        descriptions
      } = frozen);
    }
  }, "unfreeze");
  return self2;
}
__name(usage, "usage");
function isIndentedText(text) {
  return typeof text === "object";
}
__name(isIndentedText, "isIndentedText");
function addIndentation(text, indent) {
  return isIndentedText(text) ? { text: text.text, indentation: text.indentation + indent } : { text, indentation: indent };
}
__name(addIndentation, "addIndentation");
function getIndentation(text) {
  return isIndentedText(text) ? text.indentation : 0;
}
__name(getIndentation, "getIndentation");
function getText2(text) {
  return isIndentedText(text) ? text.text : text;
}
__name(getText2, "getText");

// node_modules/yargs/build/lib/completion.js
init_esbuild_shims();

// node_modules/yargs/build/lib/completion-templates.js
init_esbuild_shims();
var completionShTemplate = `###-begin-{{app_name}}-completions-###
#
# yargs command completion script
#
# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc
#    or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.
#
_{{app_name}}_yargs_completions()
{
    local cur_word args type_list

    cur_word="\${COMP_WORDS[COMP_CWORD]}"
    args=("\${COMP_WORDS[@]}")

    # ask yargs to generate completions.
    type_list=$({{app_path}} --get-yargs-completions "\${args[@]}")

    COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) )

    # if no match was found, fall back to filename completion
    if [ \${#COMPREPLY[@]} -eq 0 ]; then
      COMPREPLY=()
    fi

    return 0
}
complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
###-end-{{app_name}}-completions-###
`;
var completionZshTemplate = `#compdef {{app_name}}
###-begin-{{app_name}}-completions-###
#
# yargs command completion script
#
# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc
#    or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX.
#
_{{app_name}}_yargs_completions()
{
  local reply
  local si=$IFS
  IFS=$'
' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}"))
  IFS=$si
  _describe 'values' reply
}
compdef _{{app_name}}_yargs_completions {{app_name}}
###-end-{{app_name}}-completions-###
`;

// node_modules/yargs/build/lib/completion.js
var Completion = class {
  static {
    __name(this, "Completion");
  }
  constructor(yargs, usage2, command2, shim3) {
    var _a6, _b2, _c2;
    this.yargs = yargs;
    this.usage = usage2;
    this.command = command2;
    this.shim = shim3;
    this.completionKey = "get-yargs-completions";
    this.aliases = null;
    this.customCompletionFunction = null;
    this.indexAfterLastReset = 0;
    this.zshShell = (_c2 = ((_a6 = this.shim.getEnv("SHELL")) === null || _a6 === void 0 ? void 0 : _a6.includes("zsh")) || ((_b2 = this.shim.getEnv("ZSH_NAME")) === null || _b2 === void 0 ? void 0 : _b2.includes("zsh"))) !== null && _c2 !== void 0 ? _c2 : false;
  }
  defaultCompletion(args, argv, current, done) {
    const handlers = this.command.getCommandHandlers();
    for (let i = 0, ii = args.length; i < ii; ++i) {
      if (handlers[args[i]] && handlers[args[i]].builder) {
        const builder = handlers[args[i]].builder;
        if (isCommandBuilderCallback(builder)) {
          this.indexAfterLastReset = i + 1;
          const y = this.yargs.getInternalMethods().reset();
          builder(y, true);
          return y.argv;
        }
      }
    }
    const completions = [];
    this.commandCompletions(completions, args, current);
    this.optionCompletions(completions, args, argv, current);
    this.choicesFromOptionsCompletions(completions, args, argv, current);
    this.choicesFromPositionalsCompletions(completions, args, argv, current);
    done(null, completions);
  }
  commandCompletions(completions, args, current) {
    const parentCommands = this.yargs.getInternalMethods().getContext().commands;
    if (!current.match(/^-/) && parentCommands[parentCommands.length - 1] !== current && !this.previousArgHasChoices(args)) {
      this.usage.getCommands().forEach((usageCommand) => {
        const commandName = parseCommand(usageCommand[0]).cmd;
        if (args.indexOf(commandName) === -1) {
          if (!this.zshShell) {
            completions.push(commandName);
          } else {
            const desc2 = usageCommand[1] || "";
            completions.push(commandName.replace(/:/g, "\\:") + ":" + desc2);
          }
        }
      });
    }
  }
  optionCompletions(completions, args, argv, current) {
    if ((current.match(/^-/) || current === "" && completions.length === 0) && !this.previousArgHasChoices(args)) {
      const options2 = this.yargs.getOptions();
      const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
      Object.keys(options2.key).forEach((key) => {
        const negable = !!options2.configuration["boolean-negation"] && options2.boolean.includes(key);
        const isPositionalKey = positionalKeys.includes(key);
        if (!isPositionalKey && !options2.hiddenOptions.includes(key) && !this.argsContainKey(args, key, negable)) {
          this.completeOptionKey(key, completions, current, negable && !!options2.default[key]);
        }
      });
    }
  }
  choicesFromOptionsCompletions(completions, args, argv, current) {
    if (this.previousArgHasChoices(args)) {
      const choices = this.getPreviousArgChoices(args);
      if (choices && choices.length > 0) {
        completions.push(...choices.map((c3) => c3.replace(/:/g, "\\:")));
      }
    }
  }
  choicesFromPositionalsCompletions(completions, args, argv, current) {
    if (current === "" && completions.length > 0 && this.previousArgHasChoices(args)) {
      return;
    }
    const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
    const offset = Math.max(this.indexAfterLastReset, this.yargs.getInternalMethods().getContext().commands.length + 1);
    const positionalKey = positionalKeys[argv._.length - offset - 1];
    if (!positionalKey) {
      return;
    }
    const choices = this.yargs.getOptions().choices[positionalKey] || [];
    for (const choice2 of choices) {
      if (choice2.startsWith(current)) {
        completions.push(choice2.replace(/:/g, "\\:"));
      }
    }
  }
  getPreviousArgChoices(args) {
    if (args.length < 1)
      return;
    let previousArg = args[args.length - 1];
    let filter4 = "";
    if (!previousArg.startsWith("-") && args.length > 1) {
      filter4 = previousArg;
      previousArg = args[args.length - 2];
    }
    if (!previousArg.startsWith("-"))
      return;
    const previousArgKey = previousArg.replace(/^-+/, "");
    const options2 = this.yargs.getOptions();
    const possibleAliases = [
      previousArgKey,
      ...this.yargs.getAliases()[previousArgKey] || []
    ];
    let choices;
    for (const possibleAlias of possibleAliases) {
      if (Object.prototype.hasOwnProperty.call(options2.key, possibleAlias) && Array.isArray(options2.choices[possibleAlias])) {
        choices = options2.choices[possibleAlias];
        break;
      }
    }
    if (choices) {
      return choices.filter((choice2) => !filter4 || choice2.startsWith(filter4));
    }
  }
  previousArgHasChoices(args) {
    const choices = this.getPreviousArgChoices(args);
    return choices !== void 0 && choices.length > 0;
  }
  argsContainKey(args, key, negable) {
    const argsContains = /* @__PURE__ */ __name((s2) => args.indexOf((/^[^0-9]$/.test(s2) ? "-" : "--") + s2) !== -1, "argsContains");
    if (argsContains(key))
      return true;
    if (negable && argsContains(`no-${key}`))
      return true;
    if (this.aliases) {
      for (const alias of this.aliases[key]) {
        if (argsContains(alias))
          return true;
      }
    }
    return false;
  }
  completeOptionKey(key, completions, current, negable) {
    var _a6, _b2, _c2, _d;
    let keyWithDesc = key;
    if (this.zshShell) {
      const descs = this.usage.getDescriptions();
      const aliasKey = (_b2 = (_a6 = this === null || this === void 0 ? void 0 : this.aliases) === null || _a6 === void 0 ? void 0 : _a6[key]) === null || _b2 === void 0 ? void 0 : _b2.find((alias) => {
        const desc3 = descs[alias];
        return typeof desc3 === "string" && desc3.length > 0;
      });
      const descFromAlias = aliasKey ? descs[aliasKey] : void 0;
      const desc2 = (_d = (_c2 = descs[key]) !== null && _c2 !== void 0 ? _c2 : descFromAlias) !== null && _d !== void 0 ? _d : "";
      keyWithDesc = `${key.replace(/:/g, "\\:")}:${desc2.replace("__yargsString__:", "").replace(/(\r\n|\n|\r)/gm, " ")}`;
    }
    const startsByTwoDashes = /* @__PURE__ */ __name((s2) => /^--/.test(s2), "startsByTwoDashes");
    const isShortOption = /* @__PURE__ */ __name((s2) => /^[^0-9]$/.test(s2), "isShortOption");
    const dashes = !startsByTwoDashes(current) && isShortOption(key) ? "-" : "--";
    completions.push(dashes + keyWithDesc);
    if (negable) {
      completions.push(dashes + "no-" + keyWithDesc);
    }
  }
  customCompletion(args, argv, current, done) {
    assertNotStrictEqual(this.customCompletionFunction, null, this.shim);
    if (isSyncCompletionFunction(this.customCompletionFunction)) {
      const result = this.customCompletionFunction(current, argv);
      if (isPromise(result)) {
        return result.then((list3) => {
          this.shim.process.nextTick(() => {
            done(null, list3);
          });
        }).catch((err) => {
          this.shim.process.nextTick(() => {
            done(err, void 0);
          });
        });
      }
      return done(null, result);
    } else if (isFallbackCompletionFunction(this.customCompletionFunction)) {
      return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), (completions) => {
        done(null, completions);
      });
    } else {
      return this.customCompletionFunction(current, argv, (completions) => {
        done(null, completions);
      });
    }
  }
  getCompletion(args, done) {
    const current = args.length ? args[args.length - 1] : "";
    const argv = this.yargs.parse(args, true);
    const completionFunction = this.customCompletionFunction ? (argv2) => this.customCompletion(args, argv2, current, done) : (argv2) => this.defaultCompletion(args, argv2, current, done);
    return isPromise(argv) ? argv.then(completionFunction) : completionFunction(argv);
  }
  generateCompletionScript($0, cmd) {
    let script = this.zshShell ? completionZshTemplate : completionShTemplate;
    const name3 = this.shim.path.basename($0);
    if ($0.match(/\.js$/))
      $0 = `./${$0}`;
    script = script.replace(/{{app_name}}/g, name3);
    script = script.replace(/{{completion_command}}/g, cmd);
    return script.replace(/{{app_path}}/g, $0);
  }
  registerFunction(fn) {
    this.customCompletionFunction = fn;
  }
  setParsed(parsed) {
    this.aliases = parsed.aliases;
  }
};
function completion(yargs, usage2, command2, shim3) {
  return new Completion(yargs, usage2, command2, shim3);
}
__name(completion, "completion");
function isSyncCompletionFunction(completionFunction) {
  return completionFunction.length < 3;
}
__name(isSyncCompletionFunction, "isSyncCompletionFunction");
function isFallbackCompletionFunction(completionFunction) {
  return completionFunction.length > 3;
}
__name(isFallbackCompletionFunction, "isFallbackCompletionFunction");

// node_modules/yargs/build/lib/validation.js
init_esbuild_shims();

// node_modules/yargs/build/lib/utils/levenshtein.js
init_esbuild_shims();
function levenshtein2(a, b) {
  if (a.length === 0)
    return b.length;
  if (b.length === 0)
    return a.length;
  const matrix = [];
  let i;
  for (i = 0; i <= b.length; i++) {
    matrix[i] = [i];
  }
  let j;
  for (j = 0; j <= a.length; j++) {
    matrix[0][j] = j;
  }
  for (i = 1; i <= b.length; i++) {
    for (j = 1; j <= a.length; j++) {
      if (b.charAt(i - 1) === a.charAt(j - 1)) {
        matrix[i][j] = matrix[i - 1][j - 1];
      } else {
        if (i > 1 && j > 1 && b.charAt(i - 2) === a.charAt(j - 1) && b.charAt(i - 1) === a.charAt(j - 2)) {
          matrix[i][j] = matrix[i - 2][j - 2] + 1;
        } else {
          matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1));
        }
      }
    }
  }
  return matrix[b.length][a.length];
}
__name(levenshtein2, "levenshtein");

// node_modules/yargs/build/lib/validation.js
var specialKeys = ["$0", "--", "_"];
function validation(yargs, usage2, shim3) {
  const __ = shim3.y18n.__;
  const __n = shim3.y18n.__n;
  const self2 = {};
  self2.nonOptionCount = /* @__PURE__ */ __name(function nonOptionCount(argv) {
    const demandedCommands = yargs.getDemandedCommands();
    const positionalCount = argv._.length + (argv["--"] ? argv["--"].length : 0);
    const _s = positionalCount - yargs.getInternalMethods().getContext().commands.length;
    if (demandedCommands._ && (_s < demandedCommands._.min || _s > demandedCommands._.max)) {
      if (_s < demandedCommands._.min) {
        if (demandedCommands._.minMsg !== void 0) {
          usage2.fail(demandedCommands._.minMsg ? demandedCommands._.minMsg.replace(/\$0/g, _s.toString()).replace(/\$1/, demandedCommands._.min.toString()) : null);
        } else {
          usage2.fail(__n("Not enough non-option arguments: got %s, need at least %s", "Not enough non-option arguments: got %s, need at least %s", _s, _s.toString(), demandedCommands._.min.toString()));
        }
      } else if (_s > demandedCommands._.max) {
        if (demandedCommands._.maxMsg !== void 0) {
          usage2.fail(demandedCommands._.maxMsg ? demandedCommands._.maxMsg.replace(/\$0/g, _s.toString()).replace(/\$1/, demandedCommands._.max.toString()) : null);
        } else {
          usage2.fail(__n("Too many non-option arguments: got %s, maximum of %s", "Too many non-option arguments: got %s, maximum of %s", _s, _s.toString(), demandedCommands._.max.toString()));
        }
      }
    }
  }, "nonOptionCount");
  self2.positionalCount = /* @__PURE__ */ __name(function positionalCount(required, observed) {
    if (observed < required) {
      usage2.fail(__n("Not enough non-option arguments: got %s, need at least %s", "Not enough non-option arguments: got %s, need at least %s", observed, observed + "", required + ""));
    }
  }, "positionalCount");
  self2.requiredArguments = /* @__PURE__ */ __name(function requiredArguments(argv, demandedOptions) {
    let missing = null;
    for (const key of Object.keys(demandedOptions)) {
      if (!Object.prototype.hasOwnProperty.call(argv, key) || typeof argv[key] === "undefined") {
        missing = missing || {};
        missing[key] = demandedOptions[key];
      }
    }
    if (missing) {
      const customMsgs = [];
      for (const key of Object.keys(missing)) {
        const msg = missing[key];
        if (msg && customMsgs.indexOf(msg) < 0) {
          customMsgs.push(msg);
        }
      }
      const customMsg = customMsgs.length ? `
${customMsgs.join("\n")}` : "";
      usage2.fail(__n("Missing required argument: %s", "Missing required arguments: %s", Object.keys(missing).length, Object.keys(missing).join(", ") + customMsg));
    }
  }, "requiredArguments");
  self2.unknownArguments = /* @__PURE__ */ __name(function unknownArguments(argv, aliases, positionalMap, isDefaultCommand, checkPositionals = true) {
    var _a6;
    const commandKeys = yargs.getInternalMethods().getCommandInstance().getCommands();
    const unknown = [];
    const currentContext = yargs.getInternalMethods().getContext();
    Object.keys(argv).forEach((key) => {
      if (!specialKeys.includes(key) && !Object.prototype.hasOwnProperty.call(positionalMap, key) && !Object.prototype.hasOwnProperty.call(yargs.getInternalMethods().getParseContext(), key) && !self2.isValidAndSomeAliasIsNotNew(key, aliases)) {
        unknown.push(key);
      }
    });
    if (checkPositionals && (currentContext.commands.length > 0 || commandKeys.length > 0 || isDefaultCommand)) {
      argv._.slice(currentContext.commands.length).forEach((key) => {
        if (!commandKeys.includes("" + key)) {
          unknown.push("" + key);
        }
      });
    }
    if (checkPositionals) {
      const demandedCommands = yargs.getDemandedCommands();
      const maxNonOptDemanded = ((_a6 = demandedCommands._) === null || _a6 === void 0 ? void 0 : _a6.max) || 0;
      const expected = currentContext.commands.length + maxNonOptDemanded;
      if (expected < argv._.length) {
        argv._.slice(expected).forEach((key) => {
          key = String(key);
          if (!currentContext.commands.includes(key) && !unknown.includes(key)) {
            unknown.push(key);
          }
        });
      }
    }
    if (unknown.length) {
      usage2.fail(__n("Unknown argument: %s", "Unknown arguments: %s", unknown.length, unknown.map((s2) => s2.trim() ? s2 : `"${s2}"`).join(", ")));
    }
  }, "unknownArguments");
  self2.unknownCommands = /* @__PURE__ */ __name(function unknownCommands(argv) {
    const commandKeys = yargs.getInternalMethods().getCommandInstance().getCommands();
    const unknown = [];
    const currentContext = yargs.getInternalMethods().getContext();
    if (currentContext.commands.length > 0 || commandKeys.length > 0) {
      argv._.slice(currentContext.commands.length).forEach((key) => {
        if (!commandKeys.includes("" + key)) {
          unknown.push("" + key);
        }
      });
    }
    if (unknown.length > 0) {
      usage2.fail(__n("Unknown command: %s", "Unknown commands: %s", unknown.length, unknown.join(", ")));
      return true;
    } else {
      return false;
    }
  }, "unknownCommands");
  self2.isValidAndSomeAliasIsNotNew = /* @__PURE__ */ __name(function isValidAndSomeAliasIsNotNew(key, aliases) {
    if (!Object.prototype.hasOwnProperty.call(aliases, key)) {
      return false;
    }
    const newAliases = yargs.parsed.newAliases;
    return [key, ...aliases[key]].some((a) => !Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]);
  }, "isValidAndSomeAliasIsNotNew");
  self2.limitedChoices = /* @__PURE__ */ __name(function limitedChoices(argv) {
    const options2 = yargs.getOptions();
    const invalid = {};
    if (!Object.keys(options2.choices).length)
      return;
    Object.keys(argv).forEach((key) => {
      if (specialKeys.indexOf(key) === -1 && Object.prototype.hasOwnProperty.call(options2.choices, key)) {
        [].concat(argv[key]).forEach((value) => {
          if (options2.choices[key].indexOf(value) === -1 && value !== void 0) {
            invalid[key] = (invalid[key] || []).concat(value);
          }
        });
      }
    });
    const invalidKeys = Object.keys(invalid);
    if (!invalidKeys.length)
      return;
    let msg = __("Invalid values:");
    invalidKeys.forEach((key) => {
      msg += `
  ${__("Argument: %s, Given: %s, Choices: %s", key, usage2.stringifiedValues(invalid[key]), usage2.stringifiedValues(options2.choices[key]))}`;
    });
    usage2.fail(msg);
  }, "limitedChoices");
  let implied = {};
  self2.implies = /* @__PURE__ */ __name(function implies(key, value) {
    argsert("<string|object> [array|number|string]", [key, value], arguments.length);
    if (typeof key === "object") {
      Object.keys(key).forEach((k) => {
        self2.implies(k, key[k]);
      });
    } else {
      yargs.global(key);
      if (!implied[key]) {
        implied[key] = [];
      }
      if (Array.isArray(value)) {
        value.forEach((i) => self2.implies(key, i));
      } else {
        assertNotStrictEqual(value, void 0, shim3);
        implied[key].push(value);
      }
    }
  }, "implies");
  self2.getImplied = /* @__PURE__ */ __name(function getImplied() {
    return implied;
  }, "getImplied");
  function keyExists(argv, val) {
    const num = Number(val);
    val = isNaN(num) ? val : num;
    if (typeof val === "number") {
      val = argv._.length >= val;
    } else if (val.match(/^--no-.+/)) {
      val = val.match(/^--no-(.+)/)[1];
      val = !Object.prototype.hasOwnProperty.call(argv, val);
    } else {
      val = Object.prototype.hasOwnProperty.call(argv, val);
    }
    return val;
  }
  __name(keyExists, "keyExists");
  self2.implications = /* @__PURE__ */ __name(function implications(argv) {
    const implyFail = [];
    Object.keys(implied).forEach((key) => {
      const origKey = key;
      (implied[key] || []).forEach((value) => {
        let key2 = origKey;
        const origValue = value;
        key2 = keyExists(argv, key2);
        value = keyExists(argv, value);
        if (key2 && !value) {
          implyFail.push(` ${origKey} -> ${origValue}`);
        }
      });
    });
    if (implyFail.length) {
      let msg = `${__("Implications failed:")}
`;
      implyFail.forEach((value) => {
        msg += value;
      });
      usage2.fail(msg);
    }
  }, "implications");
  let conflicting = {};
  self2.conflicts = /* @__PURE__ */ __name(function conflicts2(key, value) {
    argsert("<string|object> [array|string]", [key, value], arguments.length);
    if (typeof key === "object") {
      Object.keys(key).forEach((k) => {
        self2.conflicts(k, key[k]);
      });
    } else {
      yargs.global(key);
      if (!conflicting[key]) {
        conflicting[key] = [];
      }
      if (Array.isArray(value)) {
        value.forEach((i) => self2.conflicts(key, i));
      } else {
        conflicting[key].push(value);
      }
    }
  }, "conflicts");
  self2.getConflicting = () => conflicting;
  self2.conflicting = /* @__PURE__ */ __name(function conflictingFn(argv) {
    Object.keys(argv).forEach((key) => {
      if (conflicting[key]) {
        conflicting[key].forEach((value) => {
          if (value && argv[key] !== void 0 && argv[value] !== void 0) {
            usage2.fail(__("Arguments %s and %s are mutually exclusive", key, value));
          }
        });
      }
    });
    if (yargs.getInternalMethods().getParserConfiguration()["strip-dashed"]) {
      Object.keys(conflicting).forEach((key) => {
        conflicting[key].forEach((value) => {
          if (value && argv[shim3.Parser.camelCase(key)] !== void 0 && argv[shim3.Parser.camelCase(value)] !== void 0) {
            usage2.fail(__("Arguments %s and %s are mutually exclusive", key, value));
          }
        });
      });
    }
  }, "conflictingFn");
  self2.recommendCommands = /* @__PURE__ */ __name(function recommendCommands(cmd, potentialCommands) {
    const threshold = 3;
    potentialCommands = potentialCommands.sort((a, b) => b.length - a.length);
    let recommended = null;
    let bestDistance = Infinity;
    for (let i = 0, candidate; (candidate = potentialCommands[i]) !== void 0; i++) {
      const d = levenshtein2(cmd, candidate);
      if (d <= threshold && d < bestDistance) {
        bestDistance = d;
        recommended = candidate;
      }
    }
    if (recommended)
      usage2.fail(__("Did you mean %s?", recommended));
  }, "recommendCommands");
  self2.reset = /* @__PURE__ */ __name(function reset(localLookup) {
    implied = objFilter(implied, (k) => !localLookup[k]);
    conflicting = objFilter(conflicting, (k) => !localLookup[k]);
    return self2;
  }, "reset");
  const frozens = [];
  self2.freeze = /* @__PURE__ */ __name(function freeze() {
    frozens.push({
      implied,
      conflicting
    });
  }, "freeze");
  self2.unfreeze = /* @__PURE__ */ __name(function unfreeze() {
    const frozen = frozens.pop();
    assertNotStrictEqual(frozen, void 0, shim3);
    ({ implied, conflicting } = frozen);
  }, "unfreeze");
  return self2;
}
__name(validation, "validation");

// node_modules/yargs/build/lib/utils/apply-extends.js
init_esbuild_shims();
var previouslyVisitedConfigs = [];
var shim2;
function applyExtends(config, cwd7, mergeExtends, _shim) {
  shim2 = _shim;
  let defaultConfig = {};
  if (Object.prototype.hasOwnProperty.call(config, "extends")) {
    if (typeof config.extends !== "string")
      return defaultConfig;
    const isPath = /\.json|\..*rc$/.test(config.extends);
    let pathToDefault = null;
    if (!isPath) {
      try {
        pathToDefault = __require.resolve(config.extends);
      } catch (_err) {
        return config;
      }
    } else {
      pathToDefault = getPathToDefaultConfig(cwd7, config.extends);
    }
    checkForCircularExtends(pathToDefault);
    previouslyVisitedConfigs.push(pathToDefault);
    defaultConfig = isPath ? JSON.parse(shim2.readFileSync(pathToDefault, "utf8")) : __require(config.extends);
    delete config.extends;
    defaultConfig = applyExtends(defaultConfig, shim2.path.dirname(pathToDefault), mergeExtends, shim2);
  }
  previouslyVisitedConfigs = [];
  return mergeExtends ? mergeDeep(defaultConfig, config) : Object.assign({}, defaultConfig, config);
}
__name(applyExtends, "applyExtends");
function checkForCircularExtends(cfgPath) {
  if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
    throw new YError(`Circular extended configurations: '${cfgPath}'.`);
  }
}
__name(checkForCircularExtends, "checkForCircularExtends");
function getPathToDefaultConfig(cwd7, pathToExtend) {
  return shim2.path.resolve(cwd7, pathToExtend);
}
__name(getPathToDefaultConfig, "getPathToDefaultConfig");
function mergeDeep(config1, config2) {
  const target = {};
  function isObject3(obj) {
    return obj && typeof obj === "object" && !Array.isArray(obj);
  }
  __name(isObject3, "isObject");
  Object.assign(target, config1);
  for (const key of Object.keys(config2)) {
    if (isObject3(config2[key]) && isObject3(target[key])) {
      target[key] = mergeDeep(config1[key], config2[key]);
    } else {
      target[key] = config2[key];
    }
  }
  return target;
}
__name(mergeDeep, "mergeDeep");

// node_modules/yargs/build/lib/yargs-factory.js
var __classPrivateFieldSet2 = function(receiver, state, value, kind, f) {
  if (kind === "m") throw new TypeError("Private method is not writable");
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet3 = function(receiver, state, kind, f) {
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _YargsInstance_command;
var _YargsInstance_cwd;
var _YargsInstance_context;
var _YargsInstance_completion;
var _YargsInstance_completionCommand;
var _YargsInstance_defaultShowHiddenOpt;
var _YargsInstance_exitError;
var _YargsInstance_detectLocale;
var _YargsInstance_emittedWarnings;
var _YargsInstance_exitProcess;
var _YargsInstance_frozens;
var _YargsInstance_globalMiddleware;
var _YargsInstance_groups;
var _YargsInstance_hasOutput;
var _YargsInstance_helpOpt;
var _YargsInstance_isGlobalContext;
var _YargsInstance_logger;
var _YargsInstance_output;
var _YargsInstance_options;
var _YargsInstance_parentRequire;
var _YargsInstance_parserConfig;
var _YargsInstance_parseFn;
var _YargsInstance_parseContext;
var _YargsInstance_pkgs;
var _YargsInstance_preservedGroups;
var _YargsInstance_processArgs;
var _YargsInstance_recommendCommands;
var _YargsInstance_shim;
var _YargsInstance_strict;
var _YargsInstance_strictCommands;
var _YargsInstance_strictOptions;
var _YargsInstance_usage;
var _YargsInstance_usageConfig;
var _YargsInstance_versionOpt;
var _YargsInstance_validation;
function YargsFactory(_shim) {
  return (processArgs = [], cwd7 = _shim.process.cwd(), parentRequire) => {
    const yargs = new YargsInstance(processArgs, cwd7, parentRequire, _shim);
    Object.defineProperty(yargs, "argv", {
      get: /* @__PURE__ */ __name(() => {
        return yargs.parse();
      }, "get"),
      enumerable: true
    });
    yargs.help();
    yargs.version();
    return yargs;
  };
}
__name(YargsFactory, "YargsFactory");
var kCopyDoubleDash = Symbol("copyDoubleDash");
var kCreateLogger = Symbol("copyDoubleDash");
var kDeleteFromParserHintObject = Symbol("deleteFromParserHintObject");
var kEmitWarning = Symbol("emitWarning");
var kFreeze = Symbol("freeze");
var kGetDollarZero = Symbol("getDollarZero");
var kGetParserConfiguration = Symbol("getParserConfiguration");
var kGetUsageConfiguration = Symbol("getUsageConfiguration");
var kGuessLocale = Symbol("guessLocale");
var kGuessVersion = Symbol("guessVersion");
var kParsePositionalNumbers = Symbol("parsePositionalNumbers");
var kPkgUp = Symbol("pkgUp");
var kPopulateParserHintArray = Symbol("populateParserHintArray");
var kPopulateParserHintSingleValueDictionary = Symbol("populateParserHintSingleValueDictionary");
var kPopulateParserHintArrayDictionary = Symbol("populateParserHintArrayDictionary");
var kPopulateParserHintDictionary = Symbol("populateParserHintDictionary");
var kSanitizeKey = Symbol("sanitizeKey");
var kSetKey = Symbol("setKey");
var kUnfreeze = Symbol("unfreeze");
var kValidateAsync = Symbol("validateAsync");
var kGetCommandInstance = Symbol("getCommandInstance");
var kGetContext = Symbol("getContext");
var kGetHasOutput = Symbol("getHasOutput");
var kGetLoggerInstance = Symbol("getLoggerInstance");
var kGetParseContext = Symbol("getParseContext");
var kGetUsageInstance = Symbol("getUsageInstance");
var kGetValidationInstance = Symbol("getValidationInstance");
var kHasParseCallback = Symbol("hasParseCallback");
var kIsGlobalContext = Symbol("isGlobalContext");
var kPostProcess = Symbol("postProcess");
var kRebase = Symbol("rebase");
var kReset = Symbol("reset");
var kRunYargsParserAndExecuteCommands = Symbol("runYargsParserAndExecuteCommands");
var kRunValidation = Symbol("runValidation");
var kSetHasOutput = Symbol("setHasOutput");
var kTrackManuallySetKeys = Symbol("kTrackManuallySetKeys");
var YargsInstance = class {
  static {
    __name(this, "YargsInstance");
  }
  constructor(processArgs = [], cwd7, parentRequire, shim3) {
    this.customScriptName = false;
    this.parsed = false;
    _YargsInstance_command.set(this, void 0);
    _YargsInstance_cwd.set(this, void 0);
    _YargsInstance_context.set(this, { commands: [], fullCommands: [] });
    _YargsInstance_completion.set(this, null);
    _YargsInstance_completionCommand.set(this, null);
    _YargsInstance_defaultShowHiddenOpt.set(this, "show-hidden");
    _YargsInstance_exitError.set(this, null);
    _YargsInstance_detectLocale.set(this, true);
    _YargsInstance_emittedWarnings.set(this, {});
    _YargsInstance_exitProcess.set(this, true);
    _YargsInstance_frozens.set(this, []);
    _YargsInstance_globalMiddleware.set(this, void 0);
    _YargsInstance_groups.set(this, {});
    _YargsInstance_hasOutput.set(this, false);
    _YargsInstance_helpOpt.set(this, null);
    _YargsInstance_isGlobalContext.set(this, true);
    _YargsInstance_logger.set(this, void 0);
    _YargsInstance_output.set(this, "");
    _YargsInstance_options.set(this, void 0);
    _YargsInstance_parentRequire.set(this, void 0);
    _YargsInstance_parserConfig.set(this, {});
    _YargsInstance_parseFn.set(this, null);
    _YargsInstance_parseContext.set(this, null);
    _YargsInstance_pkgs.set(this, {});
    _YargsInstance_preservedGroups.set(this, {});
    _YargsInstance_processArgs.set(this, void 0);
    _YargsInstance_recommendCommands.set(this, false);
    _YargsInstance_shim.set(this, void 0);
    _YargsInstance_strict.set(this, false);
    _YargsInstance_strictCommands.set(this, false);
    _YargsInstance_strictOptions.set(this, false);
    _YargsInstance_usage.set(this, void 0);
    _YargsInstance_usageConfig.set(this, {});
    _YargsInstance_versionOpt.set(this, null);
    _YargsInstance_validation.set(this, void 0);
    __classPrivateFieldSet2(this, _YargsInstance_shim, shim3, "f");
    __classPrivateFieldSet2(this, _YargsInstance_processArgs, processArgs, "f");
    __classPrivateFieldSet2(this, _YargsInstance_cwd, cwd7, "f");
    __classPrivateFieldSet2(this, _YargsInstance_parentRequire, parentRequire, "f");
    __classPrivateFieldSet2(this, _YargsInstance_globalMiddleware, new GlobalMiddleware(this), "f");
    this.$0 = this[kGetDollarZero]();
    this[kReset]();
    __classPrivateFieldSet2(this, _YargsInstance_command, __classPrivateFieldGet3(this, _YargsInstance_command, "f"), "f");
    __classPrivateFieldSet2(this, _YargsInstance_usage, __classPrivateFieldGet3(this, _YargsInstance_usage, "f"), "f");
    __classPrivateFieldSet2(this, _YargsInstance_validation, __classPrivateFieldGet3(this, _YargsInstance_validation, "f"), "f");
    __classPrivateFieldSet2(this, _YargsInstance_options, __classPrivateFieldGet3(this, _YargsInstance_options, "f"), "f");
    __classPrivateFieldGet3(this, _YargsInstance_options, "f").showHiddenOpt = __classPrivateFieldGet3(this, _YargsInstance_defaultShowHiddenOpt, "f");
    __classPrivateFieldSet2(this, _YargsInstance_logger, this[kCreateLogger](), "f");
  }
  addHelpOpt(opt, msg) {
    const defaultHelpOpt = "help";
    argsert("[string|boolean] [string]", [opt, msg], arguments.length);
    if (__classPrivateFieldGet3(this, _YargsInstance_helpOpt, "f")) {
      this[kDeleteFromParserHintObject](__classPrivateFieldGet3(this, _YargsInstance_helpOpt, "f"));
      __classPrivateFieldSet2(this, _YargsInstance_helpOpt, null, "f");
    }
    if (opt === false && msg === void 0)
      return this;
    __classPrivateFieldSet2(this, _YargsInstance_helpOpt, typeof opt === "string" ? opt : defaultHelpOpt, "f");
    this.boolean(__classPrivateFieldGet3(this, _YargsInstance_helpOpt, "f"));
    this.describe(__classPrivateFieldGet3(this, _YargsInstance_helpOpt, "f"), msg || __classPrivateFieldGet3(this, _YargsInstance_usage, "f").deferY18nLookup("Show help"));
    return this;
  }
  help(opt, msg) {
    return this.addHelpOpt(opt, msg);
  }
  addShowHiddenOpt(opt, msg) {
    argsert("[string|boolean] [string]", [opt, msg], arguments.length);
    if (opt === false && msg === void 0)
      return this;
    const showHiddenOpt = typeof opt === "string" ? opt : __classPrivateFieldGet3(this, _YargsInstance_defaultShowHiddenOpt, "f");
    this.boolean(showHiddenOpt);
    this.describe(showHiddenOpt, msg || __classPrivateFieldGet3(this, _YargsInstance_usage, "f").deferY18nLookup("Show hidden options"));
    __classPrivateFieldGet3(this, _YargsInstance_options, "f").showHiddenOpt = showHiddenOpt;
    return this;
  }
  showHidden(opt, msg) {
    return this.addShowHiddenOpt(opt, msg);
  }
  alias(key, value) {
    argsert("<object|string|array> [string|array]", [key, value], arguments.length);
    this[kPopulateParserHintArrayDictionary](this.alias.bind(this), "alias", key, value);
    return this;
  }
  array(keys) {
    argsert("<array|string>", [keys], arguments.length);
    this[kPopulateParserHintArray]("array", keys);
    this[kTrackManuallySetKeys](keys);
    return this;
  }
  boolean(keys) {
    argsert("<array|string>", [keys], arguments.length);
    this[kPopulateParserHintArray]("boolean", keys);
    this[kTrackManuallySetKeys](keys);
    return this;
  }
  check(f, global2) {
    argsert("<function> [boolean]", [f, global2], arguments.length);
    this.middleware((argv, _yargs) => {
      return maybeAsyncResult(() => {
        return f(argv, _yargs.getOptions());
      }, (result) => {
        if (!result) {
          __classPrivateFieldGet3(this, _YargsInstance_usage, "f").fail(__classPrivateFieldGet3(this, _YargsInstance_shim, "f").y18n.__("Argument check failed: %s", f.toString()));
        } else if (typeof result === "string" || result instanceof Error) {
          __classPrivateFieldGet3(this, _YargsInstance_usage, "f").fail(result.toString(), result);
        }
        return argv;
      }, (err) => {
        __classPrivateFieldGet3(this, _YargsInstance_usage, "f").fail(err.message ? err.message : err.toString(), err);
        return argv;
      });
    }, false, global2);
    return this;
  }
  choices(key, value) {
    argsert("<object|string|array> [string|array]", [key, value], arguments.length);
    this[kPopulateParserHintArrayDictionary](this.choices.bind(this), "choices", key, value);
    return this;
  }
  coerce(keys, value) {
    argsert("<object|string|array> [function]", [keys, value], arguments.length);
    if (Array.isArray(keys)) {
      if (!value) {
        throw new YError("coerce callback must be provided");
      }
      for (const key of keys) {
        this.coerce(key, value);
      }
      return this;
    } else if (typeof keys === "object") {
      for (const key of Object.keys(keys)) {
        this.coerce(key, keys[key]);
      }
      return this;
    }
    if (!value) {
      throw new YError("coerce callback must be provided");
    }
    __classPrivateFieldGet3(this, _YargsInstance_options, "f").key[keys] = true;
    __classPrivateFieldGet3(this, _YargsInstance_globalMiddleware, "f").addCoerceMiddleware((argv, yargs) => {
      let aliases;
      const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys);
      if (!shouldCoerce) {
        return argv;
      }
      return maybeAsyncResult(() => {
        aliases = yargs.getAliases();
        return value(argv[keys]);
      }, (result) => {
        argv[keys] = result;
        const stripAliased = yargs.getInternalMethods().getParserConfiguration()["strip-aliased"];
        if (aliases[keys] && stripAliased !== true) {
          for (const alias of aliases[keys]) {
            argv[alias] = result;
          }
        }
        return argv;
      }, (err) => {
        throw new YError(err.message);
      });
    }, keys);
    return this;
  }
  conflicts(key1, key2) {
    argsert("<string|object> [string|array]", [key1, key2], arguments.length);
    __classPrivateFieldGet3(this, _YargsInstance_validation, "f").conflicts(key1, key2);
    return this;
  }
  config(key = "config", msg, parseFn) {
    argsert("[object|string] [string|function] [function]", [key, msg, parseFn], arguments.length);
    if (typeof key === "object" && !Array.isArray(key)) {
      key = applyExtends(key, __classPrivateFieldGet3(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()["deep-merge-config"] || false, __classPrivateFieldGet3(this, _YargsInstance_shim, "f"));
      __classPrivateFieldGet3(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet3(this, _YargsInstance_options, "f").configObjects || []).concat(key);
      return this;
    }
    if (typeof msg === "function") {
      parseFn = msg;
      msg = void 0;
    }
    this.describe(key, msg || __classPrivateFieldGet3(this, _YargsInstance_usage, "f").deferY18nLookup("Path to JSON config file"));
    (Array.isArray(key) ? key : [key]).forEach((k) => {
      __classPrivateFieldGet3(this, _YargsInstance_options, "f").config[k] = parseFn || true;
    });
    return this;
  }
  completion(cmd, desc2, fn) {
    argsert("[string] [string|boolean|function] [function]", [cmd, desc2, fn], arguments.length);
    if (typeof desc2 === "function") {
      fn = desc2;
      desc2 = void 0;
    }
    __classPrivateFieldSet2(this, _YargsInstance_completionCommand, cmd || __classPrivateFieldGet3(this, _YargsInstance_completionCommand, "f") || "completion", "f");
    if (!desc2 && desc2 !== false) {
      desc2 = "generate completion script";
    }
    this.command(__classPrivateFieldGet3(this, _YargsInstance_completionCommand, "f"), desc2);
    if (fn)
      __classPrivateFieldGet3(this, _YargsInstance_completion, "f").registerFunction(fn);
    return this;
  }
  command(cmd, description, builder, handler, middlewares, deprecated) {
    argsert("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]", [cmd, description, builder, handler, middlewares, deprecated], arguments.length);
    __classPrivateFieldGet3(this, _YargsInstance_command, "f").addHandler(cmd, description, builder, handler, middlewares, deprecated);
    return this;
  }
  commands(cmd, description, builder, handler, middlewares, deprecated) {
    return this.command(cmd, description, builder, handler, middlewares, deprecated);
  }
  commandDir(dir, opts) {
    argsert("<string> [object]", [dir, opts], arguments.length);
    const req = __classPrivateFieldGet3(this, _YargsInstance_parentRequire, "f") || __classPrivateFieldGet3(this, _YargsInstance_shim, "f").require;
    __classPrivateFieldGet3(this, _YargsInstance_command, "f").addDirectory(dir, req, __classPrivateFieldGet3(this, _YargsInstance_shim, "f").getCallerFile(), opts);
    return this;
  }
  count(keys) {
    argsert("<array|string>", [keys], arguments.length);
    this[kPopulateParserHintArray]("count", keys);
    this[kTrackManuallySetKeys](keys);
    return this;
  }
  default(key, value, defaultDescription) {
    argsert("<object|string|array> [*] [string]", [key, value, defaultDescription], arguments.length);
    if (defaultDescription) {
      assertSingleKey(key, __classPrivateFieldGet3(this, _YargsInstance_shim, "f"));
      __classPrivateFieldGet3(this, _YargsInstance_options, "f").defaultDescription[key] = defaultDescription;
    }
    if (typeof value === "function") {
      assertSingleKey(key, __classPrivateFieldGet3(this, _YargsInstance_shim, "f"));
      if (!__classPrivateFieldGet3(this, _YargsInstance_options, "f").defaultDescription[key])
        __classPrivateFieldGet3(this, _YargsInstance_options, "f").defaultDescription[key] = __classPrivateFieldGet3(this, _YargsInstance_usage, "f").functionDescription(value);
      value = value.call();
    }
    this[kPopulateParserHintSingleValueDictionary](this.default.bind(this), "default", key, value);
    return this;
  }
  defaults(key, value, defaultDescription) {
    return this.default(key, value, defaultDescription);
  }
  demandCommand(min = 1, max, minMsg, maxMsg) {
    argsert("[number] [number|string] [string|null|undefined] [string|null|undefined]", [min, max, minMsg, maxMsg], arguments.length);
    if (typeof max !== "number") {
      minMsg = max;
      max = Infinity;
    }
    this.global("_", false);
    __classPrivateFieldGet3(this, _YargsInstance_options, "f").demandedCommands._ = {
      min,
      max,
      minMsg,
      maxMsg
    };
    return this;
  }
  demand(keys, max, msg) {
    if (Array.isArray(max)) {
      max.forEach((key) => {
        assertNotStrictEqual(msg, true, __classPrivateFieldGet3(this, _YargsInstance_shim, "f"));
        this.demandOption(key, msg);
      });
      max = Infinity;
    } else if (typeof max !== "number") {
      msg = max;
      max = Infinity;
    }
    if (typeof keys === "number") {
      assertNotStrictEqual(msg, true, __classPrivateFieldGet3(this, _YargsInstance_shim, "f"));
      this.demandCommand(keys, max, msg, msg);
    } else if (Array.isArray(keys)) {
      keys.forEach((key) => {
        assertNotStrictEqual(msg, true, __classPrivateFieldGet3(this, _YargsInstance_shim, "f"));
        this.demandOption(key, msg);
      });
    } else {
      if (typeof msg === "string") {
        this.demandOption(keys, msg);
      } else if (msg === true || typeof msg === "undefined") {
        this.demandOption(keys);
      }
    }
    return this;
  }
  demandOption(keys, msg) {
    argsert("<object|string|array> [string]", [keys, msg], arguments.length);
    this[kPopulateParserHintSingleValueDictionary](this.demandOption.bind(this), "demandedOptions", keys, msg);
    return this;
  }
  deprecateOption(option2, message) {
    argsert("<string> [string|boolean]", [option2, message], arguments.length);
    __classPrivateFieldGet3(this, _YargsInstance_options, "f").deprecatedOptions[option2] = message;
    return this;
  }
  describe(keys, description) {
    argsert("<object|string|array> [string]", [keys, description], arguments.length);
    this[kSetKey](keys, true);
    __classPrivateFieldGet3(this, _YargsInstance_usage, "f").describe(keys, description);
    return this;
  }
  detectLocale(detect) {
    argsert("<boolean>", [detect], arguments.length);
    __classPrivateFieldSet2(this, _YargsInstance_detectLocale, detect, "f");
    return this;
  }
  env(prefix) {
    argsert("[string|boolean]", [prefix], arguments.length);
    if (prefix === false)
      delete __classPrivateFieldGet3(this, _YargsInstance_options, "f").envPrefix;
    else
      __classPrivateFieldGet3(this, _YargsInstance_options, "f").envPrefix = prefix || "";
    return this;
  }
  epilogue(msg) {
    argsert("<string>", [msg], arguments.length);
    __classPrivateFieldGet3(this, _YargsInstance_usage, "f").epilog(msg);
    return this;
  }
  epilog(msg) {
    return this.epilogue(msg);
  }
  example(cmd, description) {
    argsert("<string|array> [string]", [cmd, description], arguments.length);
    if (Array.isArray(cmd)) {
      cmd.forEach((exampleParams) => this.example(...exampleParams));
    } else {
      __classPrivateFieldGet3(this, _YargsInstance_usage, "f").example(cmd, description);
    }
    return this;
  }
  exit(code2, err) {
    __classPrivateFieldSet2(this, _YargsInstance_hasOutput, true, "f");
    __classPrivateFieldSet2(this, _YargsInstance_exitError, err, "f");
    if (__classPrivateFieldGet3(this, _YargsInstance_exitProcess, "f"))
      __classPrivateFieldGet3(this, _YargsInstance_shim, "f").process.exit(code2);
  }
  exitProcess(enabled = true) {
    argsert("[boolean]", [enabled], arguments.length);
    __classPrivateFieldSet2(this, _YargsInstance_exitProcess, enabled, "f");
    return this;
  }
  fail(f) {
    argsert("<function|boolean>", [f], arguments.length);
    if (typeof f === "boolean" && f !== false) {
      throw new YError("Invalid first argument. Expected function or boolean 'false'");
    }
    __classPrivateFieldGet3(this, _YargsInstance_usage, "f").failFn(f);
    return this;
  }
  getAliases() {
    return this.parsed ? this.parsed.aliases : {};
  }
  async getCompletion(args, done) {
    argsert("<array> [function]", [args, done], arguments.length);
    if (!done) {
      return new Promise((resolve24, reject) => {
        __classPrivateFieldGet3(this, _YargsInstance_completion, "f").getCompletion(args, (err, completions) => {
          if (err)
            reject(err);
          else
            resolve24(completions);
        });
      });
    } else {
      return __classPrivateFieldGet3(this, _YargsInstance_completion, "f").getCompletion(args, done);
    }
  }
  getDemandedOptions() {
    argsert([], 0);
    return __classPrivateFieldGet3(this, _YargsInstance_options, "f").demandedOptions;
  }
  getDemandedCommands() {
    argsert([], 0);
    return __classPrivateFieldGet3(this, _YargsInstance_options, "f").demandedCommands;
  }
  getDeprecatedOptions() {
    argsert([], 0);
    return __classPrivateFieldGet3(this, _YargsInstance_options, "f").deprecatedOptions;
  }
  getDetectLocale() {
    return __classPrivateFieldGet3(this, _YargsInstance_detectLocale, "f");
  }
  getExitProcess() {
    return __classPrivateFieldGet3(this, _YargsInstance_exitProcess, "f");
  }
  getGroups() {
    return Object.assign({}, __classPrivateFieldGet3(this, _YargsInstance_groups, "f"), __classPrivateFieldGet3(this, _YargsInstance_preservedGroups, "f"));
  }
  getHelp() {
    __classPrivateFieldSet2(this, _YargsInstance_hasOutput, true, "f");
    if (!__classPrivateFieldGet3(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) {
      if (!this.parsed) {
        const parse12 = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet3(this, _YargsInstance_processArgs, "f"), void 0, void 0, 0, true);
        if (isPromise(parse12)) {
          return parse12.then(() => {
            return __classPrivateFieldGet3(this, _YargsInstance_usage, "f").help();
          });
        }
      }
      const builderResponse = __classPrivateFieldGet3(this, _YargsInstance_command, "f").runDefaultBuilderOn(this);
      if (isPromise(builderResponse)) {
        return builderResponse.then(() => {
          return __classPrivateFieldGet3(this, _YargsInstance_usage, "f").help();
        });
      }
    }
    return Promise.resolve(__classPrivateFieldGet3(this, _YargsInstance_usage, "f").help());
  }
  getOptions() {
    return __classPrivateFieldGet3(this, _YargsInstance_options, "f");
  }
  getStrict() {
    return __classPrivateFieldGet3(this, _YargsInstance_strict, "f");
  }
  getStrictCommands() {
    return __classPrivateFieldGet3(this, _YargsInstance_strictCommands, "f");
  }
  getStrictOptions() {
    return __classPrivateFieldGet3(this, _YargsInstance_strictOptions, "f");
  }
  global(globals, global2) {
    argsert("<string|array> [boolean]", [globals, global2], arguments.length);
    globals = [].concat(globals);
    if (global2 !== false) {
      __classPrivateFieldGet3(this, _YargsInstance_options, "f").local = __classPrivateFieldGet3(this, _YargsInstance_options, "f").local.filter((l2) => globals.indexOf(l2) === -1);
    } else {
      globals.forEach((g) => {
        if (!__classPrivateFieldGet3(this, _YargsInstance_options, "f").local.includes(g))
          __classPrivateFieldGet3(this, _YargsInstance_options, "f").local.push(g);
      });
    }
    return this;
  }
  group(opts, groupName) {
    argsert("<string|array> <string>", [opts, groupName], arguments.length);
    const existing = __classPrivateFieldGet3(this, _YargsInstance_preservedGroups, "f")[groupName] || __classPrivateFieldGet3(this, _YargsInstance_groups, "f")[groupName];
    if (__classPrivateFieldGet3(this, _YargsInstance_preservedGroups, "f")[groupName]) {
      delete __classPrivateFieldGet3(this, _YargsInstance_preservedGroups, "f")[groupName];
    }
    const seen = {};
    __classPrivateFieldGet3(this, _YargsInstance_groups, "f")[groupName] = (existing || []).concat(opts).filter((key) => {
      if (seen[key])
        return false;
      return seen[key] = true;
    });
    return this;
  }
  hide(key) {
    argsert("<string>", [key], arguments.length);
    __classPrivateFieldGet3(this, _YargsInstance_options, "f").hiddenOptions.push(key);
    return this;
  }
  implies(key, value) {
    argsert("<string|object> [number|string|array]", [key, value], arguments.length);
    __classPrivateFieldGet3(this, _YargsInstance_validation, "f").implies(key, value);
    return this;
  }
  locale(locale) {
    argsert("[string]", [locale], arguments.length);
    if (locale === void 0) {
      this[kGuessLocale]();
      return __classPrivateFieldGet3(this, _YargsInstance_shim, "f").y18n.getLocale();
    }
    __classPrivateFieldSet2(this, _YargsInstance_detectLocale, false, "f");
    __classPrivateFieldGet3(this, _YargsInstance_shim, "f").y18n.setLocale(locale);
    return this;
  }
  middleware(callback, applyBeforeValidation, global2) {
    return __classPrivateFieldGet3(this, _YargsInstance_globalMiddleware, "f").addMiddleware(callback, !!applyBeforeValidation, global2);
  }
  nargs(key, value) {
    argsert("<string|object|array> [number]", [key, value], arguments.length);
    this[kPopulateParserHintSingleValueDictionary](this.nargs.bind(this), "narg", key, value);
    return this;
  }
  normalize(keys) {
    argsert("<array|string>", [keys], arguments.length);
    this[kPopulateParserHintArray]("normalize", keys);
    return this;
  }
  number(keys) {
    argsert("<array|string>", [keys], arguments.length);
    this[kPopulateParserHintArray]("number", keys);
    this[kTrackManuallySetKeys](keys);
    return this;
  }
  option(key, opt) {
    argsert("<string|object> [object]", [key, opt], arguments.length);
    if (typeof key === "object") {
      Object.keys(key).forEach((k) => {
        this.options(k, key[k]);
      });
    } else {
      if (typeof opt !== "object") {
        opt = {};
      }
      this[kTrackManuallySetKeys](key);
      if (__classPrivateFieldGet3(this, _YargsInstance_versionOpt, "f") && (key === "version" || (opt === null || opt === void 0 ? void 0 : opt.alias) === "version")) {
        this[kEmitWarning]([
          '"version" is a reserved word.',
          "Please do one of the following:",
          '- Disable version with `yargs.version(false)` if using "version" as an option',
          "- Use the built-in `yargs.version` method instead (if applicable)",
          "- Use a different option key",
          "https://yargs.js.org/docs/#api-reference-version"
        ].join("\n"), void 0, "versionWarning");
      }
      __classPrivateFieldGet3(this, _YargsInstance_options, "f").key[key] = true;
      if (opt.alias)
        this.alias(key, opt.alias);
      const deprecate = opt.deprecate || opt.deprecated;
      if (deprecate) {
        this.deprecateOption(key, deprecate);
      }
      const demand = opt.demand || opt.required || opt.require;
      if (demand) {
        this.demand(key, demand);
      }
      if (opt.demandOption) {
        this.demandOption(key, typeof opt.demandOption === "string" ? opt.demandOption : void 0);
      }
      if (opt.conflicts) {
        this.conflicts(key, opt.conflicts);
      }
      if ("default" in opt) {
        this.default(key, opt.default);
      }
      if (opt.implies !== void 0) {
        this.implies(key, opt.implies);
      }
      if (opt.nargs !== void 0) {
        this.nargs(key, opt.nargs);
      }
      if (opt.config) {
        this.config(key, opt.configParser);
      }
      if (opt.normalize) {
        this.normalize(key);
      }
      if (opt.choices) {
        this.choices(key, opt.choices);
      }
      if (opt.coerce) {
        this.coerce(key, opt.coerce);
      }
      if (opt.group) {
        this.group(key, opt.group);
      }
      if (opt.boolean || opt.type === "boolean") {
        this.boolean(key);
        if (opt.alias)
          this.boolean(opt.alias);
      }
      if (opt.array || opt.type === "array") {
        this.array(key);
        if (opt.alias)
          this.array(opt.alias);
      }
      if (opt.number || opt.type === "number") {
        this.number(key);
        if (opt.alias)
          this.number(opt.alias);
      }
      if (opt.string || opt.type === "string") {
        this.string(key);
        if (opt.alias)
          this.string(opt.alias);
      }
      if (opt.count || opt.type === "count") {
        this.count(key);
      }
      if (typeof opt.global === "boolean") {
        this.global(key, opt.global);
      }
      if (opt.defaultDescription) {
        __classPrivateFieldGet3(this, _YargsInstance_options, "f").defaultDescription[key] = opt.defaultDescription;
      }
      if (opt.skipValidation) {
        this.skipValidation(key);
      }
      const desc2 = opt.describe || opt.description || opt.desc;
      const descriptions = __classPrivateFieldGet3(this, _YargsInstance_usage, "f").getDescriptions();
      if (!Object.prototype.hasOwnProperty.call(descriptions, key) || typeof desc2 === "string") {
        this.describe(key, desc2);
      }
      if (opt.hidden) {
        this.hide(key);
      }
      if (opt.requiresArg) {
        this.requiresArg(key);
      }
    }
    return this;
  }
  options(key, opt) {
    return this.option(key, opt);
  }
  parse(args, shortCircuit, _parseFn) {
    argsert("[string|array] [function|boolean|object] [function]", [args, shortCircuit, _parseFn], arguments.length);
    this[kFreeze]();
    if (typeof args === "undefined") {
      args = __classPrivateFieldGet3(this, _YargsInstance_processArgs, "f");
    }
    if (typeof shortCircuit === "object") {
      __classPrivateFieldSet2(this, _YargsInstance_parseContext, shortCircuit, "f");
      shortCircuit = _parseFn;
    }
    if (typeof shortCircuit === "function") {
      __classPrivateFieldSet2(this, _YargsInstance_parseFn, shortCircuit, "f");
      shortCircuit = false;
    }
    if (!shortCircuit)
      __classPrivateFieldSet2(this, _YargsInstance_processArgs, args, "f");
    if (__classPrivateFieldGet3(this, _YargsInstance_parseFn, "f"))
      __classPrivateFieldSet2(this, _YargsInstance_exitProcess, false, "f");
    const parsed = this[kRunYargsParserAndExecuteCommands](args, !!shortCircuit);
    const tmpParsed = this.parsed;
    __classPrivateFieldGet3(this, _YargsInstance_completion, "f").setParsed(this.parsed);
    if (isPromise(parsed)) {
      return parsed.then((argv) => {
        if (__classPrivateFieldGet3(this, _YargsInstance_parseFn, "f"))
          __classPrivateFieldGet3(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet3(this, _YargsInstance_exitError, "f"), argv, __classPrivateFieldGet3(this, _YargsInstance_output, "f"));
        return argv;
      }).catch((err) => {
        if (__classPrivateFieldGet3(this, _YargsInstance_parseFn, "f")) {
          __classPrivateFieldGet3(this, _YargsInstance_parseFn, "f")(err, this.parsed.argv, __classPrivateFieldGet3(this, _YargsInstance_output, "f"));
        }
        throw err;
      }).finally(() => {
        this[kUnfreeze]();
        this.parsed = tmpParsed;
      });
    } else {
      if (__classPrivateFieldGet3(this, _YargsInstance_parseFn, "f"))
        __classPrivateFieldGet3(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet3(this, _YargsInstance_exitError, "f"), parsed, __classPrivateFieldGet3(this, _YargsInstance_output, "f"));
      this[kUnfreeze]();
      this.parsed = tmpParsed;
    }
    return parsed;
  }
  parseAsync(args, shortCircuit, _parseFn) {
    const maybePromise = this.parse(args, shortCircuit, _parseFn);
    return !isPromise(maybePromise) ? Promise.resolve(maybePromise) : maybePromise;
  }
  parseSync(args, shortCircuit, _parseFn) {
    const maybePromise = this.parse(args, shortCircuit, _parseFn);
    if (isPromise(maybePromise)) {
      throw new YError(".parseSync() must not be used with asynchronous builders, handlers, or middleware");
    }
    return maybePromise;
  }
  parserConfiguration(config) {
    argsert("<object>", [config], arguments.length);
    __classPrivateFieldSet2(this, _YargsInstance_parserConfig, config, "f");
    return this;
  }
  pkgConf(key, rootPath) {
    argsert("<string> [string]", [key, rootPath], arguments.length);
    let conf = null;
    const obj = this[kPkgUp](rootPath || __classPrivateFieldGet3(this, _YargsInstance_cwd, "f"));
    if (obj[key] && typeof obj[key] === "object") {
      conf = applyExtends(obj[key], rootPath || __classPrivateFieldGet3(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()["deep-merge-config"] || false, __classPrivateFieldGet3(this, _YargsInstance_shim, "f"));
      __classPrivateFieldGet3(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet3(this, _YargsInstance_options, "f").configObjects || []).concat(conf);
    }
    return this;
  }
  positional(key, opts) {
    argsert("<string> <object>", [key, opts], arguments.length);
    const supportedOpts = [
      "default",
      "defaultDescription",
      "implies",
      "normalize",
      "choices",
      "conflicts",
      "coerce",
      "type",
      "describe",
      "desc",
      "description",
      "alias"
    ];
    opts = objFilter(opts, (k, v) => {
      if (k === "type" && !["string", "number", "boolean"].includes(v))
        return false;
      return supportedOpts.includes(k);
    });
    const fullCommand = __classPrivateFieldGet3(this, _YargsInstance_context, "f").fullCommands[__classPrivateFieldGet3(this, _YargsInstance_context, "f").fullCommands.length - 1];
    const parseOptions = fullCommand ? __classPrivateFieldGet3(this, _YargsInstance_command, "f").cmdToParseOptions(fullCommand) : {
      array: [],
      alias: {},
      default: {},
      demand: {}
    };
    objectKeys(parseOptions).forEach((pk) => {
      const parseOption = parseOptions[pk];
      if (Array.isArray(parseOption)) {
        if (parseOption.indexOf(key) !== -1)
          opts[pk] = true;
      } else {
        if (parseOption[key] && !(pk in opts))
          opts[pk] = parseOption[key];
      }
    });
    this.group(key, __classPrivateFieldGet3(this, _YargsInstance_usage, "f").getPositionalGroupName());
    return this.option(key, opts);
  }
  recommendCommands(recommend = true) {
    argsert("[boolean]", [recommend], arguments.length);
    __classPrivateFieldSet2(this, _YargsInstance_recommendCommands, recommend, "f");
    return this;
  }
  required(keys, max, msg) {
    return this.demand(keys, max, msg);
  }
  require(keys, max, msg) {
    return this.demand(keys, max, msg);
  }
  requiresArg(keys) {
    argsert("<array|string|object> [number]", [keys], arguments.length);
    if (typeof keys === "string" && __classPrivateFieldGet3(this, _YargsInstance_options, "f").narg[keys]) {
      return this;
    } else {
      this[kPopulateParserHintSingleValueDictionary](this.requiresArg.bind(this), "narg", keys, NaN);
    }
    return this;
  }
  showCompletionScript($0, cmd) {
    argsert("[string] [string]", [$0, cmd], arguments.length);
    $0 = $0 || this.$0;
    __classPrivateFieldGet3(this, _YargsInstance_logger, "f").log(__classPrivateFieldGet3(this, _YargsInstance_completion, "f").generateCompletionScript($0, cmd || __classPrivateFieldGet3(this, _YargsInstance_completionCommand, "f") || "completion"));
    return this;
  }
  showHelp(level) {
    argsert("[string|function]", [level], arguments.length);
    __classPrivateFieldSet2(this, _YargsInstance_hasOutput, true, "f");
    if (!__classPrivateFieldGet3(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) {
      if (!this.parsed) {
        const parse12 = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet3(this, _YargsInstance_processArgs, "f"), void 0, void 0, 0, true);
        if (isPromise(parse12)) {
          parse12.then(() => {
            __classPrivateFieldGet3(this, _YargsInstance_usage, "f").showHelp(level);
          });
          return this;
        }
      }
      const builderResponse = __classPrivateFieldGet3(this, _YargsInstance_command, "f").runDefaultBuilderOn(this);
      if (isPromise(builderResponse)) {
        builderResponse.then(() => {
          __classPrivateFieldGet3(this, _YargsInstance_usage, "f").showHelp(level);
        });
        return this;
      }
    }
    __classPrivateFieldGet3(this, _YargsInstance_usage, "f").showHelp(level);
    return this;
  }
  scriptName(scriptName) {
    this.customScriptName = true;
    this.$0 = scriptName;
    return this;
  }
  showHelpOnFail(enabled, message) {
    argsert("[boolean|string] [string]", [enabled, message], arguments.length);
    __classPrivateFieldGet3(this, _YargsInstance_usage, "f").showHelpOnFail(enabled, message);
    return this;
  }
  showVersion(level) {
    argsert("[string|function]", [level], arguments.length);
    __classPrivateFieldGet3(this, _YargsInstance_usage, "f").showVersion(level);
    return this;
  }
  skipValidation(keys) {
    argsert("<array|string>", [keys], arguments.length);
    this[kPopulateParserHintArray]("skipValidation", keys);
    return this;
  }
  strict(enabled) {
    argsert("[boolean]", [enabled], arguments.length);
    __classPrivateFieldSet2(this, _YargsInstance_strict, enabled !== false, "f");
    return this;
  }
  strictCommands(enabled) {
    argsert("[boolean]", [enabled], arguments.length);
    __classPrivateFieldSet2(this, _YargsInstance_strictCommands, enabled !== false, "f");
    return this;
  }
  strictOptions(enabled) {
    argsert("[boolean]", [enabled], arguments.length);
    __classPrivateFieldSet2(this, _YargsInstance_strictOptions, enabled !== false, "f");
    return this;
  }
  string(keys) {
    argsert("<array|string>", [keys], arguments.length);
    this[kPopulateParserHintArray]("string", keys);
    this[kTrackManuallySetKeys](keys);
    return this;
  }
  terminalWidth() {
    argsert([], 0);
    return __classPrivateFieldGet3(this, _YargsInstance_shim, "f").process.stdColumns;
  }
  updateLocale(obj) {
    return this.updateStrings(obj);
  }
  updateStrings(obj) {
    argsert("<object>", [obj], arguments.length);
    __classPrivateFieldSet2(this, _YargsInstance_detectLocale, false, "f");
    __classPrivateFieldGet3(this, _YargsInstance_shim, "f").y18n.updateLocale(obj);
    return this;
  }
  usage(msg, description, builder, handler) {
    argsert("<string|null|undefined> [string|boolean] [function|object] [function]", [msg, description, builder, handler], arguments.length);
    if (description !== void 0) {
      assertNotStrictEqual(msg, null, __classPrivateFieldGet3(this, _YargsInstance_shim, "f"));
      if ((msg || "").match(/^\$0( |$)/)) {
        return this.command(msg, description, builder, handler);
      } else {
        throw new YError(".usage() description must start with $0 if being used as alias for .command()");
      }
    } else {
      __classPrivateFieldGet3(this, _YargsInstance_usage, "f").usage(msg);
      return this;
    }
  }
  usageConfiguration(config) {
    argsert("<object>", [config], arguments.length);
    __classPrivateFieldSet2(this, _YargsInstance_usageConfig, config, "f");
    return this;
  }
  version(opt, msg, ver) {
    const defaultVersionOpt = "version";
    argsert("[boolean|string] [string] [string]", [opt, msg, ver], arguments.length);
    if (__classPrivateFieldGet3(this, _YargsInstance_versionOpt, "f")) {
      this[kDeleteFromParserHintObject](__classPrivateFieldGet3(this, _YargsInstance_versionOpt, "f"));
      __classPrivateFieldGet3(this, _YargsInstance_usage, "f").version(void 0);
      __classPrivateFieldSet2(this, _YargsInstance_versionOpt, null, "f");
    }
    if (arguments.length === 0) {
      ver = this[kGuessVersion]();
      opt = defaultVersionOpt;
    } else if (arguments.length === 1) {
      if (opt === false) {
        return this;
      }
      ver = opt;
      opt = defaultVersionOpt;
    } else if (arguments.length === 2) {
      ver = msg;
      msg = void 0;
    }
    __classPrivateFieldSet2(this, _YargsInstance_versionOpt, typeof opt === "string" ? opt : defaultVersionOpt, "f");
    msg = msg || __classPrivateFieldGet3(this, _YargsInstance_usage, "f").deferY18nLookup("Show version number");
    __classPrivateFieldGet3(this, _YargsInstance_usage, "f").version(ver || void 0);
    this.boolean(__classPrivateFieldGet3(this, _YargsInstance_versionOpt, "f"));
    this.describe(__classPrivateFieldGet3(this, _YargsInstance_versionOpt, "f"), msg);
    return this;
  }
  wrap(cols) {
    argsert("<number|null|undefined>", [cols], arguments.length);
    __classPrivateFieldGet3(this, _YargsInstance_usage, "f").wrap(cols);
    return this;
  }
  [(_YargsInstance_command = /* @__PURE__ */ new WeakMap(), _YargsInstance_cwd = /* @__PURE__ */ new WeakMap(), _YargsInstance_context = /* @__PURE__ */ new WeakMap(), _YargsInstance_completion = /* @__PURE__ */ new WeakMap(), _YargsInstance_completionCommand = /* @__PURE__ */ new WeakMap(), _YargsInstance_defaultShowHiddenOpt = /* @__PURE__ */ new WeakMap(), _YargsInstance_exitError = /* @__PURE__ */ new WeakMap(), _YargsInstance_detectLocale = /* @__PURE__ */ new WeakMap(), _YargsInstance_emittedWarnings = /* @__PURE__ */ new WeakMap(), _YargsInstance_exitProcess = /* @__PURE__ */ new WeakMap(), _YargsInstance_frozens = /* @__PURE__ */ new WeakMap(), _YargsInstance_globalMiddleware = /* @__PURE__ */ new WeakMap(), _YargsInstance_groups = /* @__PURE__ */ new WeakMap(), _YargsInstance_hasOutput = /* @__PURE__ */ new WeakMap(), _YargsInstance_helpOpt = /* @__PURE__ */ new WeakMap(), _YargsInstance_isGlobalContext = /* @__PURE__ */ new WeakMap(), _YargsInstance_logger = /* @__PURE__ */ new WeakMap(), _YargsInstance_output = /* @__PURE__ */ new WeakMap(), _YargsInstance_options = /* @__PURE__ */ new WeakMap(), _YargsInstance_parentRequire = /* @__PURE__ */ new WeakMap(), _YargsInstance_parserConfig = /* @__PURE__ */ new WeakMap(), _YargsInstance_parseFn = /* @__PURE__ */ new WeakMap(), _YargsInstance_parseContext = /* @__PURE__ */ new WeakMap(), _YargsInstance_pkgs = /* @__PURE__ */ new WeakMap(), _YargsInstance_preservedGroups = /* @__PURE__ */ new WeakMap(), _YargsInstance_processArgs = /* @__PURE__ */ new WeakMap(), _YargsInstance_recommendCommands = /* @__PURE__ */ new WeakMap(), _YargsInstance_shim = /* @__PURE__ */ new WeakMap(), _YargsInstance_strict = /* @__PURE__ */ new WeakMap(), _YargsInstance_strictCommands = /* @__PURE__ */ new WeakMap(), _YargsInstance_strictOptions = /* @__PURE__ */ new WeakMap(), _YargsInstance_usage = /* @__PURE__ */ new WeakMap(), _YargsInstance_usageConfig = /* @__PURE__ */ new WeakMap(), _YargsInstance_versionOpt = /* @__PURE__ */ new WeakMap(), _YargsInstance_validation = /* @__PURE__ */ new WeakMap(), kCopyDoubleDash)](argv) {
    if (!argv._ || !argv["--"])
      return argv;
    argv._.push.apply(argv._, argv["--"]);
    try {
      delete argv["--"];
    } catch (_err) {
    }
    return argv;
  }
  [kCreateLogger]() {
    return {
      log: /* @__PURE__ */ __name((...args) => {
        if (!this[kHasParseCallback]())
          console.log(...args);
        __classPrivateFieldSet2(this, _YargsInstance_hasOutput, true, "f");
        if (__classPrivateFieldGet3(this, _YargsInstance_output, "f").length)
          __classPrivateFieldSet2(this, _YargsInstance_output, __classPrivateFieldGet3(this, _YargsInstance_output, "f") + "\n", "f");
        __classPrivateFieldSet2(this, _YargsInstance_output, __classPrivateFieldGet3(this, _YargsInstance_output, "f") + args.join(" "), "f");
      }, "log"),
      error: /* @__PURE__ */ __name((...args) => {
        if (!this[kHasParseCallback]())
          console.error(...args);
        __classPrivateFieldSet2(this, _YargsInstance_hasOutput, true, "f");
        if (__classPrivateFieldGet3(this, _YargsInstance_output, "f").length)
          __classPrivateFieldSet2(this, _YargsInstance_output, __classPrivateFieldGet3(this, _YargsInstance_output, "f") + "\n", "f");
        __classPrivateFieldSet2(this, _YargsInstance_output, __classPrivateFieldGet3(this, _YargsInstance_output, "f") + args.join(" "), "f");
      }, "error")
    };
  }
  [kDeleteFromParserHintObject](optionKey) {
    objectKeys(__classPrivateFieldGet3(this, _YargsInstance_options, "f")).forEach((hintKey) => {
      if (/* @__PURE__ */ ((key) => key === "configObjects")(hintKey))
        return;
      const hint = __classPrivateFieldGet3(this, _YargsInstance_options, "f")[hintKey];
      if (Array.isArray(hint)) {
        if (hint.includes(optionKey))
          hint.splice(hint.indexOf(optionKey), 1);
      } else if (typeof hint === "object") {
        delete hint[optionKey];
      }
    });
    delete __classPrivateFieldGet3(this, _YargsInstance_usage, "f").getDescriptions()[optionKey];
  }
  [kEmitWarning](warning, type, deduplicationId) {
    if (!__classPrivateFieldGet3(this, _YargsInstance_emittedWarnings, "f")[deduplicationId]) {
      __classPrivateFieldGet3(this, _YargsInstance_shim, "f").process.emitWarning(warning, type);
      __classPrivateFieldGet3(this, _YargsInstance_emittedWarnings, "f")[deduplicationId] = true;
    }
  }
  [kFreeze]() {
    __classPrivateFieldGet3(this, _YargsInstance_frozens, "f").push({
      options: __classPrivateFieldGet3(this, _YargsInstance_options, "f"),
      configObjects: __classPrivateFieldGet3(this, _YargsInstance_options, "f").configObjects.slice(0),
      exitProcess: __classPrivateFieldGet3(this, _YargsInstance_exitProcess, "f"),
      groups: __classPrivateFieldGet3(this, _YargsInstance_groups, "f"),
      strict: __classPrivateFieldGet3(this, _YargsInstance_strict, "f"),
      strictCommands: __classPrivateFieldGet3(this, _YargsInstance_strictCommands, "f"),
      strictOptions: __classPrivateFieldGet3(this, _YargsInstance_strictOptions, "f"),
      completionCommand: __classPrivateFieldGet3(this, _YargsInstance_completionCommand, "f"),
      output: __classPrivateFieldGet3(this, _YargsInstance_output, "f"),
      exitError: __classPrivateFieldGet3(this, _YargsInstance_exitError, "f"),
      hasOutput: __classPrivateFieldGet3(this, _YargsInstance_hasOutput, "f"),
      parsed: this.parsed,
      parseFn: __classPrivateFieldGet3(this, _YargsInstance_parseFn, "f"),
      parseContext: __classPrivateFieldGet3(this, _YargsInstance_parseContext, "f")
    });
    __classPrivateFieldGet3(this, _YargsInstance_usage, "f").freeze();
    __classPrivateFieldGet3(this, _YargsInstance_validation, "f").freeze();
    __classPrivateFieldGet3(this, _YargsInstance_command, "f").freeze();
    __classPrivateFieldGet3(this, _YargsInstance_globalMiddleware, "f").freeze();
  }
  [kGetDollarZero]() {
    let $0 = "";
    let default$0;
    if (/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet3(this, _YargsInstance_shim, "f").process.argv()[0])) {
      default$0 = __classPrivateFieldGet3(this, _YargsInstance_shim, "f").process.argv().slice(1, 2);
    } else {
      default$0 = __classPrivateFieldGet3(this, _YargsInstance_shim, "f").process.argv().slice(0, 1);
    }
    $0 = default$0.map((x) => {
      const b = this[kRebase](__classPrivateFieldGet3(this, _YargsInstance_cwd, "f"), x);
      return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
    }).join(" ").trim();
    if (__classPrivateFieldGet3(this, _YargsInstance_shim, "f").getEnv("_") && __classPrivateFieldGet3(this, _YargsInstance_shim, "f").getProcessArgvBin() === __classPrivateFieldGet3(this, _YargsInstance_shim, "f").getEnv("_")) {
      $0 = __classPrivateFieldGet3(this, _YargsInstance_shim, "f").getEnv("_").replace(`${__classPrivateFieldGet3(this, _YargsInstance_shim, "f").path.dirname(__classPrivateFieldGet3(this, _YargsInstance_shim, "f").process.execPath())}/`, "");
    }
    return $0;
  }
  [kGetParserConfiguration]() {
    return __classPrivateFieldGet3(this, _YargsInstance_parserConfig, "f");
  }
  [kGetUsageConfiguration]() {
    return __classPrivateFieldGet3(this, _YargsInstance_usageConfig, "f");
  }
  [kGuessLocale]() {
    if (!__classPrivateFieldGet3(this, _YargsInstance_detectLocale, "f"))
      return;
    const locale = __classPrivateFieldGet3(this, _YargsInstance_shim, "f").getEnv("LC_ALL") || __classPrivateFieldGet3(this, _YargsInstance_shim, "f").getEnv("LC_MESSAGES") || __classPrivateFieldGet3(this, _YargsInstance_shim, "f").getEnv("LANG") || __classPrivateFieldGet3(this, _YargsInstance_shim, "f").getEnv("LANGUAGE") || "en_US";
    this.locale(locale.replace(/[.:].*/, ""));
  }
  [kGuessVersion]() {
    const obj = this[kPkgUp]();
    return obj.version || "unknown";
  }
  [kParsePositionalNumbers](argv) {
    const args = argv["--"] ? argv["--"] : argv._;
    for (let i = 0, arg; (arg = args[i]) !== void 0; i++) {
      if (__classPrivateFieldGet3(this, _YargsInstance_shim, "f").Parser.looksLikeNumber(arg) && Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) {
        args[i] = Number(arg);
      }
    }
    return argv;
  }
  [kPkgUp](rootPath) {
    const npath = rootPath || "*";
    if (__classPrivateFieldGet3(this, _YargsInstance_pkgs, "f")[npath])
      return __classPrivateFieldGet3(this, _YargsInstance_pkgs, "f")[npath];
    let obj = {};
    try {
      let startDir = rootPath || __classPrivateFieldGet3(this, _YargsInstance_shim, "f").mainFilename;
      if (!rootPath && __classPrivateFieldGet3(this, _YargsInstance_shim, "f").path.extname(startDir)) {
        startDir = __classPrivateFieldGet3(this, _YargsInstance_shim, "f").path.dirname(startDir);
      }
      const pkgJsonPath = __classPrivateFieldGet3(this, _YargsInstance_shim, "f").findUp(startDir, (dir, names) => {
        if (names.includes("package.json")) {
          return "package.json";
        } else {
          return void 0;
        }
      });
      assertNotStrictEqual(pkgJsonPath, void 0, __classPrivateFieldGet3(this, _YargsInstance_shim, "f"));
      obj = JSON.parse(__classPrivateFieldGet3(this, _YargsInstance_shim, "f").readFileSync(pkgJsonPath, "utf8"));
    } catch (_noop) {
    }
    __classPrivateFieldGet3(this, _YargsInstance_pkgs, "f")[npath] = obj || {};
    return __classPrivateFieldGet3(this, _YargsInstance_pkgs, "f")[npath];
  }
  [kPopulateParserHintArray](type, keys) {
    keys = [].concat(keys);
    keys.forEach((key) => {
      key = this[kSanitizeKey](key);
      __classPrivateFieldGet3(this, _YargsInstance_options, "f")[type].push(key);
    });
  }
  [kPopulateParserHintSingleValueDictionary](builder, type, key, value) {
    this[kPopulateParserHintDictionary](builder, type, key, value, (type2, key2, value2) => {
      __classPrivateFieldGet3(this, _YargsInstance_options, "f")[type2][key2] = value2;
    });
  }
  [kPopulateParserHintArrayDictionary](builder, type, key, value) {
    this[kPopulateParserHintDictionary](builder, type, key, value, (type2, key2, value2) => {
      __classPrivateFieldGet3(this, _YargsInstance_options, "f")[type2][key2] = (__classPrivateFieldGet3(this, _YargsInstance_options, "f")[type2][key2] || []).concat(value2);
    });
  }
  [kPopulateParserHintDictionary](builder, type, key, value, singleKeyHandler) {
    if (Array.isArray(key)) {
      key.forEach((k) => {
        builder(k, value);
      });
    } else if (/* @__PURE__ */ ((key2) => typeof key2 === "object")(key)) {
      for (const k of objectKeys(key)) {
        builder(k, key[k]);
      }
    } else {
      singleKeyHandler(type, this[kSanitizeKey](key), value);
    }
  }
  [kSanitizeKey](key) {
    if (key === "__proto__")
      return "___proto___";
    return key;
  }
  [kSetKey](key, set) {
    this[kPopulateParserHintSingleValueDictionary](this[kSetKey].bind(this), "key", key, set);
    return this;
  }
  [kUnfreeze]() {
    var _a6, _b2, _c2, _d, _e, _f, _g, _h, _j, _k, _l, _m;
    const frozen = __classPrivateFieldGet3(this, _YargsInstance_frozens, "f").pop();
    assertNotStrictEqual(frozen, void 0, __classPrivateFieldGet3(this, _YargsInstance_shim, "f"));
    let configObjects;
    _a6 = this, _b2 = this, _c2 = this, _d = this, _e = this, _f = this, _g = this, _h = this, _j = this, _k = this, _l = this, _m = this, {
      options: { set value(_o) {
        __classPrivateFieldSet2(_a6, _YargsInstance_options, _o, "f");
      } }.value,
      configObjects,
      exitProcess: { set value(_o) {
        __classPrivateFieldSet2(_b2, _YargsInstance_exitProcess, _o, "f");
      } }.value,
      groups: { set value(_o) {
        __classPrivateFieldSet2(_c2, _YargsInstance_groups, _o, "f");
      } }.value,
      output: { set value(_o) {
        __classPrivateFieldSet2(_d, _YargsInstance_output, _o, "f");
      } }.value,
      exitError: { set value(_o) {
        __classPrivateFieldSet2(_e, _YargsInstance_exitError, _o, "f");
      } }.value,
      hasOutput: { set value(_o) {
        __classPrivateFieldSet2(_f, _YargsInstance_hasOutput, _o, "f");
      } }.value,
      parsed: this.parsed,
      strict: { set value(_o) {
        __classPrivateFieldSet2(_g, _YargsInstance_strict, _o, "f");
      } }.value,
      strictCommands: { set value(_o) {
        __classPrivateFieldSet2(_h, _YargsInstance_strictCommands, _o, "f");
      } }.value,
      strictOptions: { set value(_o) {
        __classPrivateFieldSet2(_j, _YargsInstance_strictOptions, _o, "f");
      } }.value,
      completionCommand: { set value(_o) {
        __classPrivateFieldSet2(_k, _YargsInstance_completionCommand, _o, "f");
      } }.value,
      parseFn: { set value(_o) {
        __classPrivateFieldSet2(_l, _YargsInstance_parseFn, _o, "f");
      } }.value,
      parseContext: { set value(_o) {
        __classPrivateFieldSet2(_m, _YargsInstance_parseContext, _o, "f");
      } }.value
    } = frozen;
    __classPrivateFieldGet3(this, _YargsInstance_options, "f").configObjects = configObjects;
    __classPrivateFieldGet3(this, _YargsInstance_usage, "f").unfreeze();
    __classPrivateFieldGet3(this, _YargsInstance_validation, "f").unfreeze();
    __classPrivateFieldGet3(this, _YargsInstance_command, "f").unfreeze();
    __classPrivateFieldGet3(this, _YargsInstance_globalMiddleware, "f").unfreeze();
  }
  [kValidateAsync](validation2, argv) {
    return maybeAsyncResult(argv, (result) => {
      validation2(result);
      return result;
    });
  }
  getInternalMethods() {
    return {
      getCommandInstance: this[kGetCommandInstance].bind(this),
      getContext: this[kGetContext].bind(this),
      getHasOutput: this[kGetHasOutput].bind(this),
      getLoggerInstance: this[kGetLoggerInstance].bind(this),
      getParseContext: this[kGetParseContext].bind(this),
      getParserConfiguration: this[kGetParserConfiguration].bind(this),
      getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
      getUsageInstance: this[kGetUsageInstance].bind(this),
      getValidationInstance: this[kGetValidationInstance].bind(this),
      hasParseCallback: this[kHasParseCallback].bind(this),
      isGlobalContext: this[kIsGlobalContext].bind(this),
      postProcess: this[kPostProcess].bind(this),
      reset: this[kReset].bind(this),
      runValidation: this[kRunValidation].bind(this),
      runYargsParserAndExecuteCommands: this[kRunYargsParserAndExecuteCommands].bind(this),
      setHasOutput: this[kSetHasOutput].bind(this)
    };
  }
  [kGetCommandInstance]() {
    return __classPrivateFieldGet3(this, _YargsInstance_command, "f");
  }
  [kGetContext]() {
    return __classPrivateFieldGet3(this, _YargsInstance_context, "f");
  }
  [kGetHasOutput]() {
    return __classPrivateFieldGet3(this, _YargsInstance_hasOutput, "f");
  }
  [kGetLoggerInstance]() {
    return __classPrivateFieldGet3(this, _YargsInstance_logger, "f");
  }
  [kGetParseContext]() {
    return __classPrivateFieldGet3(this, _YargsInstance_parseContext, "f") || {};
  }
  [kGetUsageInstance]() {
    return __classPrivateFieldGet3(this, _YargsInstance_usage, "f");
  }
  [kGetValidationInstance]() {
    return __classPrivateFieldGet3(this, _YargsInstance_validation, "f");
  }
  [kHasParseCallback]() {
    return !!__classPrivateFieldGet3(this, _YargsInstance_parseFn, "f");
  }
  [kIsGlobalContext]() {
    return __classPrivateFieldGet3(this, _YargsInstance_isGlobalContext, "f");
  }
  [kPostProcess](argv, populateDoubleDash, calledFromCommand, runGlobalMiddleware) {
    if (calledFromCommand)
      return argv;
    if (isPromise(argv))
      return argv;
    if (!populateDoubleDash) {
      argv = this[kCopyDoubleDash](argv);
    }
    const parsePositionalNumbers = this[kGetParserConfiguration]()["parse-positional-numbers"] || this[kGetParserConfiguration]()["parse-positional-numbers"] === void 0;
    if (parsePositionalNumbers) {
      argv = this[kParsePositionalNumbers](argv);
    }
    if (runGlobalMiddleware) {
      argv = applyMiddleware(argv, this, __classPrivateFieldGet3(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false);
    }
    return argv;
  }
  [kReset](aliases = {}) {
    __classPrivateFieldSet2(this, _YargsInstance_options, __classPrivateFieldGet3(this, _YargsInstance_options, "f") || {}, "f");
    const tmpOptions = {};
    tmpOptions.local = __classPrivateFieldGet3(this, _YargsInstance_options, "f").local || [];
    tmpOptions.configObjects = __classPrivateFieldGet3(this, _YargsInstance_options, "f").configObjects || [];
    const localLookup = {};
    tmpOptions.local.forEach((l2) => {
      localLookup[l2] = true;
      (aliases[l2] || []).forEach((a) => {
        localLookup[a] = true;
      });
    });
    Object.assign(__classPrivateFieldGet3(this, _YargsInstance_preservedGroups, "f"), Object.keys(__classPrivateFieldGet3(this, _YargsInstance_groups, "f")).reduce((acc, groupName) => {
      const keys = __classPrivateFieldGet3(this, _YargsInstance_groups, "f")[groupName].filter((key) => !(key in localLookup));
      if (keys.length > 0) {
        acc[groupName] = keys;
      }
      return acc;
    }, {}));
    __classPrivateFieldSet2(this, _YargsInstance_groups, {}, "f");
    const arrayOptions = [
      "array",
      "boolean",
      "string",
      "skipValidation",
      "count",
      "normalize",
      "number",
      "hiddenOptions"
    ];
    const objectOptions = [
      "narg",
      "key",
      "alias",
      "default",
      "defaultDescription",
      "config",
      "choices",
      "demandedOptions",
      "demandedCommands",
      "deprecatedOptions"
    ];
    arrayOptions.forEach((k) => {
      tmpOptions[k] = (__classPrivateFieldGet3(this, _YargsInstance_options, "f")[k] || []).filter((k2) => !localLookup[k2]);
    });
    objectOptions.forEach((k) => {
      tmpOptions[k] = objFilter(__classPrivateFieldGet3(this, _YargsInstance_options, "f")[k], (k2) => !localLookup[k2]);
    });
    tmpOptions.envPrefix = __classPrivateFieldGet3(this, _YargsInstance_options, "f").envPrefix;
    __classPrivateFieldSet2(this, _YargsInstance_options, tmpOptions, "f");
    __classPrivateFieldSet2(this, _YargsInstance_usage, __classPrivateFieldGet3(this, _YargsInstance_usage, "f") ? __classPrivateFieldGet3(this, _YargsInstance_usage, "f").reset(localLookup) : usage(this, __classPrivateFieldGet3(this, _YargsInstance_shim, "f")), "f");
    __classPrivateFieldSet2(this, _YargsInstance_validation, __classPrivateFieldGet3(this, _YargsInstance_validation, "f") ? __classPrivateFieldGet3(this, _YargsInstance_validation, "f").reset(localLookup) : validation(this, __classPrivateFieldGet3(this, _YargsInstance_usage, "f"), __classPrivateFieldGet3(this, _YargsInstance_shim, "f")), "f");
    __classPrivateFieldSet2(this, _YargsInstance_command, __classPrivateFieldGet3(this, _YargsInstance_command, "f") ? __classPrivateFieldGet3(this, _YargsInstance_command, "f").reset() : command(__classPrivateFieldGet3(this, _YargsInstance_usage, "f"), __classPrivateFieldGet3(this, _YargsInstance_validation, "f"), __classPrivateFieldGet3(this, _YargsInstance_globalMiddleware, "f"), __classPrivateFieldGet3(this, _YargsInstance_shim, "f")), "f");
    if (!__classPrivateFieldGet3(this, _YargsInstance_completion, "f"))
      __classPrivateFieldSet2(this, _YargsInstance_completion, completion(this, __classPrivateFieldGet3(this, _YargsInstance_usage, "f"), __classPrivateFieldGet3(this, _YargsInstance_command, "f"), __classPrivateFieldGet3(this, _YargsInstance_shim, "f")), "f");
    __classPrivateFieldGet3(this, _YargsInstance_globalMiddleware, "f").reset();
    __classPrivateFieldSet2(this, _YargsInstance_completionCommand, null, "f");
    __classPrivateFieldSet2(this, _YargsInstance_output, "", "f");
    __classPrivateFieldSet2(this, _YargsInstance_exitError, null, "f");
    __classPrivateFieldSet2(this, _YargsInstance_hasOutput, false, "f");
    this.parsed = false;
    return this;
  }
  [kRebase](base, dir) {
    return __classPrivateFieldGet3(this, _YargsInstance_shim, "f").path.relative(base, dir);
  }
  [kRunYargsParserAndExecuteCommands](args, shortCircuit, calledFromCommand, commandIndex = 0, helpOnly = false) {
    let skipValidation = !!calledFromCommand || helpOnly;
    args = args || __classPrivateFieldGet3(this, _YargsInstance_processArgs, "f");
    __classPrivateFieldGet3(this, _YargsInstance_options, "f").__ = __classPrivateFieldGet3(this, _YargsInstance_shim, "f").y18n.__;
    __classPrivateFieldGet3(this, _YargsInstance_options, "f").configuration = this[kGetParserConfiguration]();
    const populateDoubleDash = !!__classPrivateFieldGet3(this, _YargsInstance_options, "f").configuration["populate--"];
    const config = Object.assign({}, __classPrivateFieldGet3(this, _YargsInstance_options, "f").configuration, {
      "populate--": true
    });
    const parsed = __classPrivateFieldGet3(this, _YargsInstance_shim, "f").Parser.detailed(args, Object.assign({}, __classPrivateFieldGet3(this, _YargsInstance_options, "f"), {
      configuration: { "parse-positional-numbers": false, ...config }
    }));
    const argv = Object.assign(parsed.argv, __classPrivateFieldGet3(this, _YargsInstance_parseContext, "f"));
    let argvPromise = void 0;
    const aliases = parsed.aliases;
    let helpOptSet = false;
    let versionOptSet = false;
    Object.keys(argv).forEach((key) => {
      if (key === __classPrivateFieldGet3(this, _YargsInstance_helpOpt, "f") && argv[key]) {
        helpOptSet = true;
      } else if (key === __classPrivateFieldGet3(this, _YargsInstance_versionOpt, "f") && argv[key]) {
        versionOptSet = true;
      }
    });
    argv.$0 = this.$0;
    this.parsed = parsed;
    if (commandIndex === 0) {
      __classPrivateFieldGet3(this, _YargsInstance_usage, "f").clearCachedHelpMessage();
    }
    try {
      this[kGuessLocale]();
      if (shortCircuit) {
        return this[kPostProcess](argv, populateDoubleDash, !!calledFromCommand, false);
      }
      if (__classPrivateFieldGet3(this, _YargsInstance_helpOpt, "f")) {
        const helpCmds = [__classPrivateFieldGet3(this, _YargsInstance_helpOpt, "f")].concat(aliases[__classPrivateFieldGet3(this, _YargsInstance_helpOpt, "f")] || []).filter((k) => k.length > 1);
        if (helpCmds.includes("" + argv._[argv._.length - 1])) {
          argv._.pop();
          helpOptSet = true;
        }
      }
      __classPrivateFieldSet2(this, _YargsInstance_isGlobalContext, false, "f");
      const handlerKeys = __classPrivateFieldGet3(this, _YargsInstance_command, "f").getCommands();
      const requestCompletions = __classPrivateFieldGet3(this, _YargsInstance_completion, "f").completionKey in argv;
      const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
      if (argv._.length) {
        if (handlerKeys.length) {
          let firstUnknownCommand;
          for (let i = commandIndex || 0, cmd; argv._[i] !== void 0; i++) {
            cmd = String(argv._[i]);
            if (handlerKeys.includes(cmd) && cmd !== __classPrivateFieldGet3(this, _YargsInstance_completionCommand, "f")) {
              const innerArgv = __classPrivateFieldGet3(this, _YargsInstance_command, "f").runCommand(cmd, this, parsed, i + 1, helpOnly, helpOptSet || versionOptSet || helpOnly);
              return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false);
            } else if (!firstUnknownCommand && cmd !== __classPrivateFieldGet3(this, _YargsInstance_completionCommand, "f")) {
              firstUnknownCommand = cmd;
              break;
            }
          }
          if (!__classPrivateFieldGet3(this, _YargsInstance_command, "f").hasDefaultCommand() && __classPrivateFieldGet3(this, _YargsInstance_recommendCommands, "f") && firstUnknownCommand && !skipRecommendation) {
            __classPrivateFieldGet3(this, _YargsInstance_validation, "f").recommendCommands(firstUnknownCommand, handlerKeys);
          }
        }
        if (__classPrivateFieldGet3(this, _YargsInstance_completionCommand, "f") && argv._.includes(__classPrivateFieldGet3(this, _YargsInstance_completionCommand, "f")) && !requestCompletions) {
          if (__classPrivateFieldGet3(this, _YargsInstance_exitProcess, "f"))
            setBlocking(true);
          this.showCompletionScript();
          this.exit(0);
        }
      }
      if (__classPrivateFieldGet3(this, _YargsInstance_command, "f").hasDefaultCommand() && !skipRecommendation) {
        const innerArgv = __classPrivateFieldGet3(this, _YargsInstance_command, "f").runCommand(null, this, parsed, 0, helpOnly, helpOptSet || versionOptSet || helpOnly);
        return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false);
      }
      if (requestCompletions) {
        if (__classPrivateFieldGet3(this, _YargsInstance_exitProcess, "f"))
          setBlocking(true);
        args = [].concat(args);
        const completionArgs = args.slice(args.indexOf(`--${__classPrivateFieldGet3(this, _YargsInstance_completion, "f").completionKey}`) + 1);
        __classPrivateFieldGet3(this, _YargsInstance_completion, "f").getCompletion(completionArgs, (err, completions) => {
          if (err)
            throw new YError(err.message);
          (completions || []).forEach((completion3) => {
            __classPrivateFieldGet3(this, _YargsInstance_logger, "f").log(completion3);
          });
          this.exit(0);
        });
        return this[kPostProcess](argv, !populateDoubleDash, !!calledFromCommand, false);
      }
      if (!__classPrivateFieldGet3(this, _YargsInstance_hasOutput, "f")) {
        if (helpOptSet) {
          if (__classPrivateFieldGet3(this, _YargsInstance_exitProcess, "f"))
            setBlocking(true);
          skipValidation = true;
          this.showHelp("log");
          this.exit(0);
        } else if (versionOptSet) {
          if (__classPrivateFieldGet3(this, _YargsInstance_exitProcess, "f"))
            setBlocking(true);
          skipValidation = true;
          __classPrivateFieldGet3(this, _YargsInstance_usage, "f").showVersion("log");
          this.exit(0);
        }
      }
      if (!skipValidation && __classPrivateFieldGet3(this, _YargsInstance_options, "f").skipValidation.length > 0) {
        skipValidation = Object.keys(argv).some((key) => __classPrivateFieldGet3(this, _YargsInstance_options, "f").skipValidation.indexOf(key) >= 0 && argv[key] === true);
      }
      if (!skipValidation) {
        if (parsed.error)
          throw new YError(parsed.error.message);
        if (!requestCompletions) {
          const validation2 = this[kRunValidation](aliases, {}, parsed.error);
          if (!calledFromCommand) {
            argvPromise = applyMiddleware(argv, this, __classPrivateFieldGet3(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), true);
          }
          argvPromise = this[kValidateAsync](validation2, argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv);
          if (isPromise(argvPromise) && !calledFromCommand) {
            argvPromise = argvPromise.then(() => {
              return applyMiddleware(argv, this, __classPrivateFieldGet3(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false);
            });
          }
        }
      }
    } catch (err) {
      if (err instanceof YError)
        __classPrivateFieldGet3(this, _YargsInstance_usage, "f").fail(err.message, err);
      else
        throw err;
    }
    return this[kPostProcess](argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv, populateDoubleDash, !!calledFromCommand, true);
  }
  [kRunValidation](aliases, positionalMap, parseErrors, isDefaultCommand) {
    const demandedOptions = { ...this.getDemandedOptions() };
    return (argv) => {
      if (parseErrors)
        throw new YError(parseErrors.message);
      __classPrivateFieldGet3(this, _YargsInstance_validation, "f").nonOptionCount(argv);
      __classPrivateFieldGet3(this, _YargsInstance_validation, "f").requiredArguments(argv, demandedOptions);
      let failedStrictCommands = false;
      if (__classPrivateFieldGet3(this, _YargsInstance_strictCommands, "f")) {
        failedStrictCommands = __classPrivateFieldGet3(this, _YargsInstance_validation, "f").unknownCommands(argv);
      }
      if (__classPrivateFieldGet3(this, _YargsInstance_strict, "f") && !failedStrictCommands) {
        __classPrivateFieldGet3(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, positionalMap, !!isDefaultCommand);
      } else if (__classPrivateFieldGet3(this, _YargsInstance_strictOptions, "f")) {
        __classPrivateFieldGet3(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, {}, false, false);
      }
      __classPrivateFieldGet3(this, _YargsInstance_validation, "f").limitedChoices(argv);
      __classPrivateFieldGet3(this, _YargsInstance_validation, "f").implications(argv);
      __classPrivateFieldGet3(this, _YargsInstance_validation, "f").conflicting(argv);
    };
  }
  [kSetHasOutput]() {
    __classPrivateFieldSet2(this, _YargsInstance_hasOutput, true, "f");
  }
  [kTrackManuallySetKeys](keys) {
    if (typeof keys === "string") {
      __classPrivateFieldGet3(this, _YargsInstance_options, "f").key[keys] = true;
    } else {
      for (const k of keys) {
        __classPrivateFieldGet3(this, _YargsInstance_options, "f").key[k] = true;
      }
    }
  }
};
function isYargsInstance(y) {
  return !!y && typeof y.getInternalMethods === "function";
}
__name(isYargsInstance, "isYargsInstance");

// node_modules/yargs/index.mjs
var Yargs = YargsFactory(esm_default3);
var yargs_default = Yargs;

// packages/cli/src/commands/extensions/disable.ts
function handleDisable(args) {
  try {
    if (args.scope?.toLowerCase() === "workspace") {
      disableExtension(args.name, "Workspace" /* Workspace */);
    } else {
      disableExtension(args.name, "User" /* User */);
    }
    console.log(
      `Extension "${args.name}" successfully disabled for scope "${args.scope}".`
    );
  } catch (error) {
    console.error(getErrorMessage3(error));
    process.exit(1);
  }
}
__name(handleDisable, "handleDisable");
var disableCommand = {
  command: "disable [--scope] <name>",
  describe: "Disables an extension.",
  builder: /* @__PURE__ */ __name((yargs) => yargs.positional("name", {
    describe: "The name of the extension to disable.",
    type: "string"
  }).option("scope", {
    describe: "The scope to disable the extenison in.",
    type: "string",
    default: "User" /* User */
  }).check((argv) => {
    if (argv.scope && !Object.values(SettingScope).map((s2) => s2.toLowerCase()).includes(argv.scope.toLowerCase())) {
      throw new Error(
        `Invalid scope: ${argv.scope}. Please use one of ${Object.values(
          SettingScope
        ).map((s2) => s2.toLowerCase()).join(", ")}.`
      );
    }
    return true;
  }), "builder"),
  handler: /* @__PURE__ */ __name((argv) => {
    handleDisable({
      name: argv["name"],
      scope: argv["scope"]
    });
  }, "handler")
};

// packages/cli/src/commands/extensions/enable.ts
init_esbuild_shims();
function handleEnable(args) {
  try {
    if (args.scope?.toLowerCase() === "workspace") {
      enableExtension(args.name, "Workspace" /* Workspace */);
    } else {
      enableExtension(args.name, "User" /* User */);
    }
    if (args.scope) {
      console.log(
        `Extension "${args.name}" successfully enabled for scope "${args.scope}".`
      );
    } else {
      console.log(
        `Extension "${args.name}" successfully enabled in all scopes.`
      );
    }
  } catch (error) {
    throw new FatalConfigError(getErrorMessage(error));
  }
}
__name(handleEnable, "handleEnable");
var enableCommand = {
  command: "enable [--scope] <name>",
  describe: "Enables an extension.",
  builder: /* @__PURE__ */ __name((yargs) => yargs.positional("name", {
    describe: "The name of the extension to enable.",
    type: "string"
  }).option("scope", {
    describe: "The scope to enable the extenison in. If not set, will be enabled in all scopes.",
    type: "string"
  }).check((argv) => {
    if (argv.scope && !Object.values(SettingScope).map((s2) => s2.toLowerCase()).includes(argv.scope.toLowerCase())) {
      throw new Error(
        `Invalid scope: ${argv.scope}. Please use one of ${Object.values(
          SettingScope
        ).map((s2) => s2.toLowerCase()).join(", ")}.`
      );
    }
    return true;
  }), "builder"),
  handler: /* @__PURE__ */ __name((argv) => {
    handleEnable({
      name: argv["name"],
      scope: argv["scope"]
    });
  }, "handler")
};

// packages/cli/src/commands/extensions/link.ts
init_esbuild_shims();
async function handleLink(args) {
  try {
    const installMetadata = {
      source: args.path,
      type: "link"
    };
    const extensionName = await installExtension(
      installMetadata,
      requestConsentNonInteractive
    );
    console.log(
      `Extension "${extensionName}" linked successfully and enabled.`
    );
  } catch (error) {
    console.error(getErrorMessage3(error));
    process.exit(1);
  }
}
__name(handleLink, "handleLink");
var linkCommand = {
  command: "link <path>",
  describe: "Links an extension from a local path. Updates made to the local path will always be reflected.",
  builder: /* @__PURE__ */ __name((yargs) => yargs.positional("path", {
    describe: "The name of the extension to link.",
    type: "string"
  }).check((_) => true), "builder"),
  handler: /* @__PURE__ */ __name(async (argv) => {
    await handleLink({
      path: argv["path"]
    });
  }, "handler")
};

// packages/cli/src/commands/extensions/new.ts
init_esbuild_shims();
import { access as access5, cp, mkdir as mkdir8, readdir as readdir7, writeFile as writeFile9 } from "node:fs/promises";
import { join as join31, dirname as dirname21, basename as basename13 } from "node:path";
import { fileURLToPath as fileURLToPath7 } from "node:url";
var __filename3 = fileURLToPath7(import.meta.url);
var __dirname5 = dirname21(__filename3);
var EXAMPLES_PATH = join31(__dirname5, "examples");
async function pathExists(path108) {
  try {
    await access5(path108);
    return true;
  } catch (_e) {
    return false;
  }
}
__name(pathExists, "pathExists");
async function createDirectory(path108) {
  if (await pathExists(path108)) {
    throw new Error(`Path already exists: ${path108}`);
  }
  await mkdir8(path108, { recursive: true });
}
__name(createDirectory, "createDirectory");
async function copyDirectory(template, path108) {
  await createDirectory(path108);
  const examplePath = join31(EXAMPLES_PATH, template);
  const entries = await readdir7(examplePath, { withFileTypes: true });
  for (const entry of entries) {
    const srcPath = join31(examplePath, entry.name);
    const destPath = join31(path108, entry.name);
    await cp(srcPath, destPath, { recursive: true });
  }
}
__name(copyDirectory, "copyDirectory");
async function handleNew(args) {
  try {
    if (args.template) {
      await copyDirectory(args.template, args.path);
      console.log(
        `Successfully created new extension from template "${args.template}" at ${args.path}.`
      );
    } else {
      await createDirectory(args.path);
      const extensionName = basename13(args.path);
      const manifest = {
        name: extensionName,
        version: "1.0.0"
      };
      await writeFile9(
        join31(args.path, "qwen-extension.json"),
        JSON.stringify(manifest, null, 2)
      );
      console.log(`Successfully created new extension at ${args.path}.`);
    }
    console.log(
      `You can install this using "qwen extensions link ${args.path}" to test it out.`
    );
  } catch (error) {
    console.error(getErrorMessage3(error));
    throw error;
  }
}
__name(handleNew, "handleNew");
async function getBoilerplateChoices() {
  const entries = await readdir7(EXAMPLES_PATH, { withFileTypes: true });
  return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
}
__name(getBoilerplateChoices, "getBoilerplateChoices");
var newCommand = {
  command: "new <path> [template]",
  describe: "Create a new extension from a boilerplate example.",
  builder: /* @__PURE__ */ __name(async (yargs) => {
    const choices = await getBoilerplateChoices();
    return yargs.positional("path", {
      describe: "The path to create the extension in.",
      type: "string"
    }).positional("template", {
      describe: "The boilerplate template to use.",
      type: "string",
      choices
    });
  }, "builder"),
  handler: /* @__PURE__ */ __name(async (args) => {
    await handleNew({
      path: args["path"],
      template: args["template"]
    });
  }, "handler")
};

// packages/cli/src/commands/extensions.tsx
var extensionsCommand = {
  command: "extensions <command>",
  describe: "Manage Qwen Code extensions.",
  builder: /* @__PURE__ */ __name((yargs) => yargs.command(installCommand).command(uninstallCommand).command(listCommand).command(updateCommand).command(disableCommand).command(enableCommand).command(linkCommand).command(newCommand).demandCommand(1, "You need at least one command before continuing.").version(false), "builder"),
  handler: /* @__PURE__ */ __name(() => {
  }, "handler")
};

// node_modules/yargs/helpers/helpers.mjs
init_esbuild_shims();

// packages/cli/src/config/config.ts
import * as fs74 from "node:fs";
import * as path81 from "node:path";
import { homedir as homedir16 } from "node:os";

// packages/cli/src/utils/resolvePath.ts
init_esbuild_shims();
import * as os27 from "node:os";
import * as path76 from "node:path";
function resolvePath2(p) {
  if (!p) {
    return "";
  }
  let expandedPath = p;
  if (p.toLowerCase().startsWith("%userprofile%")) {
    expandedPath = os27.homedir() + p.substring("%userprofile%".length);
  } else if (p === "~" || p.startsWith("~/")) {
    expandedPath = os27.homedir() + p.substring(1);
  }
  return path76.normalize(expandedPath);
}
__name(resolvePath2, "resolvePath");

// packages/cli/src/utils/version.ts
init_esbuild_shims();

// packages/cli/src/utils/package.ts
init_esbuild_shims();

// node_modules/read-package-up/index.js
init_esbuild_shims();
import path79 from "node:path";

// node_modules/find-up-simple/index.js
init_esbuild_shims();
import process32 from "node:process";
import fsPromises3 from "node:fs/promises";
import { fileURLToPath as fileURLToPath8 } from "node:url";
import path77 from "node:path";
var toPath = /* @__PURE__ */ __name((urlOrPath) => urlOrPath instanceof URL ? fileURLToPath8(urlOrPath) : urlOrPath, "toPath");
async function findUp(name3, {
  cwd: cwd7 = process32.cwd(),
  type = "file",
  stopAt
} = {}) {
  let directory = path77.resolve(toPath(cwd7) ?? "");
  const { root } = path77.parse(directory);
  stopAt = path77.resolve(directory, toPath(stopAt ?? root));
  const isAbsoluteName = path77.isAbsolute(name3);
  while (directory) {
    const filePath = isAbsoluteName ? name3 : path77.join(directory, name3);
    try {
      const stats = await fsPromises3.stat(filePath);
      if (type === "file" && stats.isFile() || type === "directory" && stats.isDirectory()) {
        return filePath;
      }
    } catch {
    }
    if (directory === stopAt || directory === root) {
      break;
    }
    directory = path77.dirname(directory);
  }
}
__name(findUp, "findUp");

// node_modules/read-pkg/index.js
init_esbuild_shims();
import fsPromises4 from "node:fs/promises";
import path78 from "node:path";

// node_modules/parse-json/index.js
init_esbuild_shims();
var import_code_frame = __toESM(require_lib5(), 1);

// node_modules/index-to-position/index.js
init_esbuild_shims();
function getPosition(text, textIndex) {
  const lineBreakBefore = textIndex === 0 ? -1 : text.lastIndexOf("\n", textIndex - 1);
  return {
    line: lineBreakBefore === -1 ? 0 : text.slice(0, lineBreakBefore + 1).match(/\n/g).length,
    column: textIndex - lineBreakBefore - 1
  };
}
__name(getPosition, "getPosition");
function indexToPosition(text, textIndex, { oneBased = false } = {}) {
  if (typeof text !== "string") {
    throw new TypeError("Text parameter should be a string");
  }
  if (!Number.isInteger(textIndex)) {
    throw new TypeError("Index parameter should be an integer");
  }
  if (textIndex < 0 || textIndex > text.length) {
    throw new RangeError("Index out of bounds");
  }
  const position = getPosition(text, textIndex);
  return oneBased ? { line: position.line + 1, column: position.column + 1 } : position;
}
__name(indexToPosition, "indexToPosition");

// node_modules/parse-json/index.js
var getCodePoint2 = /* @__PURE__ */ __name((character) => `\\u{${character.codePointAt(0).toString(16)}}`, "getCodePoint");
var JSONError = class _JSONError extends Error {
  static {
    __name(this, "JSONError");
  }
  name = "JSONError";
  fileName;
  #input;
  #jsonParseError;
  #message;
  #codeFrame;
  #rawCodeFrame;
  constructor(messageOrOptions) {
    if (typeof messageOrOptions === "string") {
      super();
      this.#message = messageOrOptions;
    } else {
      const { jsonParseError, fileName, input } = messageOrOptions;
      super(void 0, { cause: jsonParseError });
      this.#input = input;
      this.#jsonParseError = jsonParseError;
      this.fileName = fileName;
    }
    Error.captureStackTrace?.(this, _JSONError);
  }
  get message() {
    this.#message ??= `${addCodePointToUnexpectedToken(this.#jsonParseError.message)}${this.#input === "" ? " while parsing empty string" : ""}`;
    const { codeFrame } = this;
    return `${this.#message}${this.fileName ? ` in ${this.fileName}` : ""}${codeFrame ? `

${codeFrame}
` : ""}`;
  }
  set message(message) {
    this.#message = message;
  }
  #getCodeFrame(highlightCode) {
    if (!this.#jsonParseError) {
      return;
    }
    const input = this.#input;
    const location = getErrorLocation(input, this.#jsonParseError.message);
    if (!location) {
      return;
    }
    return (0, import_code_frame.codeFrameColumns)(input, { start: location }, { highlightCode });
  }
  get codeFrame() {
    this.#codeFrame ??= this.#getCodeFrame(
      /* highlightCode */
      true
    );
    return this.#codeFrame;
  }
  get rawCodeFrame() {
    this.#rawCodeFrame ??= this.#getCodeFrame(
      /* highlightCode */
      false
    );
    return this.#rawCodeFrame;
  }
};
var getErrorLocation = /* @__PURE__ */ __name((string, message) => {
  const match2 = message.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);
  if (!match2) {
    return;
  }
  const { index, line, column } = match2.groups;
  if (line && column) {
    return { line: Number(line), column: Number(column) };
  }
  return indexToPosition(string, Number(index), { oneBased: true });
}, "getErrorLocation");
var addCodePointToUnexpectedToken = /* @__PURE__ */ __name((message) => message.replace(
  // TODO[engine:node@>=20]: The token always quoted after Node.js 20
  /(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,
  (_, _quote, token2) => `"${token2}"(${getCodePoint2(token2)})`
), "addCodePointToUnexpectedToken");
function parseJson(string, reviver, fileName) {
  if (typeof reviver === "string") {
    fileName = reviver;
    reviver = void 0;
  }
  try {
    return JSON.parse(string, reviver);
  } catch (error) {
    throw new JSONError({
      jsonParseError: error,
      fileName,
      input: string
    });
  }
}
__name(parseJson, "parseJson");

// node_modules/read-pkg/index.js
var import_normalize_package_data = __toESM(require_normalize2(), 1);

// node_modules/unicorn-magic/node.js
init_esbuild_shims();
import { fileURLToPath as fileURLToPath9 } from "node:url";
function toPath2(urlOrPath) {
  return urlOrPath instanceof URL ? fileURLToPath9(urlOrPath) : urlOrPath;
}
__name(toPath2, "toPath");

// node_modules/read-pkg/index.js
var getPackagePath = /* @__PURE__ */ __name((cwd7) => path78.resolve(toPath2(cwd7) ?? ".", "package.json"), "getPackagePath");
var _readPackage = /* @__PURE__ */ __name((file, normalize10) => {
  const json2 = typeof file === "string" ? parseJson(file) : file;
  if (normalize10) {
    (0, import_normalize_package_data.default)(json2);
  }
  return json2;
}, "_readPackage");
async function readPackage({ cwd: cwd7, normalize: normalize10 = true } = {}) {
  const packageFile = await fsPromises4.readFile(getPackagePath(cwd7), "utf8");
  return _readPackage(packageFile, normalize10);
}
__name(readPackage, "readPackage");

// node_modules/read-package-up/index.js
async function readPackageUp(options2) {
  const filePath = await findUp("package.json", options2);
  if (!filePath) {
    return;
  }
  return {
    packageJson: await readPackage({ ...options2, cwd: path79.dirname(filePath) }),
    path: filePath
  };
}
__name(readPackageUp, "readPackageUp");

// packages/cli/src/utils/package.ts
import { fileURLToPath as fileURLToPath10 } from "node:url";
import path80 from "node:path";
var __filename4 = fileURLToPath10(import.meta.url);
var __dirname6 = path80.dirname(__filename4);
var packageJson;
async function getPackageJson() {
  if (packageJson) {
    return packageJson;
  }
  const result = await readPackageUp({ cwd: __dirname6 });
  if (!result) {
    return;
  }
  packageJson = result.packageJson;
  return packageJson;
}
__name(getPackageJson, "getPackageJson");

// packages/cli/src/utils/version.ts
async function getCliVersion() {
  const pkgJson = await getPackageJson();
  return "0.2.3";
}
__name(getCliVersion, "getCliVersion");

// packages/cli/src/config/sandboxConfig.ts
init_esbuild_shims();
var import_command_exists = __toESM(require_command_exists2(), 1);
import * as os28 from "node:os";
var VALID_SANDBOX_COMMANDS = [
  "docker",
  "podman",
  "sandbox-exec"
];
function isSandboxCommand(value) {
  return VALID_SANDBOX_COMMANDS.includes(value);
}
__name(isSandboxCommand, "isSandboxCommand");
function getSandboxCommand(sandbox) {
  if (process.env["SANDBOX"]) {
    return "";
  }
  const environmentConfiguredSandbox = process.env["GEMINI_SANDBOX"]?.toLowerCase().trim() ?? "";
  sandbox = environmentConfiguredSandbox?.length > 0 ? environmentConfiguredSandbox : sandbox;
  if (sandbox === "1" || sandbox === "true") sandbox = true;
  else if (sandbox === "0" || sandbox === "false" || !sandbox) sandbox = false;
  if (sandbox === false) {
    return "";
  }
  if (typeof sandbox === "string" && sandbox) {
    if (!isSandboxCommand(sandbox)) {
      throw new FatalSandboxError(
        `Invalid sandbox command '${sandbox}'. Must be one of ${VALID_SANDBOX_COMMANDS.join(
          ", "
        )}`
      );
    }
    if (import_command_exists.default.sync(sandbox)) {
      return sandbox;
    }
    throw new FatalSandboxError(
      `Missing sandbox command '${sandbox}' (from GEMINI_SANDBOX)`
    );
  }
  if (os28.platform() === "darwin" && import_command_exists.default.sync("sandbox-exec")) {
    return "sandbox-exec";
  } else if (import_command_exists.default.sync("docker") && sandbox === true) {
    return "docker";
  } else if (import_command_exists.default.sync("podman") && sandbox === true) {
    return "podman";
  }
  if (sandbox === true) {
    throw new FatalSandboxError(
      "GEMINI_SANDBOX is true but failed to determine command for sandbox; install docker or podman or specify command in GEMINI_SANDBOX"
    );
  }
  return "";
}
__name(getSandboxCommand, "getSandboxCommand");
async function loadSandboxConfig(settings, argv) {
  const sandboxOption = argv.sandbox ?? settings.tools?.sandbox;
  const command2 = getSandboxCommand(sandboxOption);
  const packageJson4 = await getPackageJson();
  const image2 = argv.sandboxImage ?? process.env["GEMINI_SANDBOX_IMAGE"] ?? packageJson4?.config?.sandboxImageUri;
  return command2 && image2 ? { command: command2, image: image2 } : void 0;
}
__name(loadSandboxConfig, "loadSandboxConfig");

// packages/cli/src/commands/mcp.ts
init_esbuild_shims();

// packages/cli/src/commands/mcp/add.ts
init_esbuild_shims();
async function addMcpServer(name3, commandOrUrl, args, options2) {
  const {
    scope,
    transport,
    env: env7,
    header,
    timeout: timeout2,
    trust,
    description,
    includeTools,
    excludeTools
  } = options2;
  const settings = loadSettings(process.cwd());
  const inHome = settings.workspace.path === settings.user.path;
  if (scope === "project" && inHome) {
    console.error(
      "Error: Please use --scope user to edit settings in the home directory."
    );
    process.exit(1);
  }
  const settingsScope = scope === "user" ? "User" /* User */ : "Workspace" /* Workspace */;
  let newServer = {};
  const headers = header?.reduce(
    (acc, curr) => {
      const [key, ...valueParts] = curr.split(":");
      const value = valueParts.join(":").trim();
      if (key.trim() && value) {
        acc[key.trim()] = value;
      }
      return acc;
    },
    {}
  );
  switch (transport) {
    case "sse":
      newServer = {
        url: commandOrUrl,
        headers,
        timeout: timeout2,
        trust,
        description,
        includeTools,
        excludeTools
      };
      break;
    case "http":
      newServer = {
        httpUrl: commandOrUrl,
        headers,
        timeout: timeout2,
        trust,
        description,
        includeTools,
        excludeTools
      };
      break;
    case "stdio":
    default:
      newServer = {
        command: commandOrUrl,
        args: args?.map(String),
        env: env7?.reduce(
          (acc, curr) => {
            const [key, value] = curr.split("=");
            if (key && value) {
              acc[key] = value;
            }
            return acc;
          },
          {}
        ),
        timeout: timeout2,
        trust,
        description,
        includeTools,
        excludeTools
      };
      break;
  }
  const existingSettings = settings.forScope(settingsScope).settings;
  const mcpServers = existingSettings.mcpServers || {};
  const isExistingServer = !!mcpServers[name3];
  if (isExistingServer) {
    console.log(
      `MCP server "${name3}" is already configured within ${scope} settings.`
    );
  }
  mcpServers[name3] = newServer;
  settings.setValue(settingsScope, "mcpServers", mcpServers);
  if (isExistingServer) {
    console.log(`MCP server "${name3}" updated in ${scope} settings.`);
  } else {
    console.log(
      `MCP server "${name3}" added to ${scope} settings. (${transport})`
    );
  }
}
__name(addMcpServer, "addMcpServer");
var addCommand = {
  command: "add <name> <commandOrUrl> [args...]",
  describe: "Add a server",
  builder: /* @__PURE__ */ __name((yargs) => yargs.usage("Usage: gemini mcp add [options] <name> <commandOrUrl> [args...]").parserConfiguration({
    "unknown-options-as-args": true,
    // Pass unknown options as server args
    "populate--": true
    // Populate server args after -- separator
  }).positional("name", {
    describe: "Name of the server",
    type: "string",
    demandOption: true
  }).positional("commandOrUrl", {
    describe: "Command (stdio) or URL (sse, http)",
    type: "string",
    demandOption: true
  }).option("scope", {
    alias: "s",
    describe: "Configuration scope (user or project)",
    type: "string",
    default: "project",
    choices: ["user", "project"]
  }).option("transport", {
    alias: "t",
    describe: "Transport type (stdio, sse, http)",
    type: "string",
    default: "stdio",
    choices: ["stdio", "sse", "http"]
  }).option("env", {
    alias: "e",
    describe: "Set environment variables (e.g. -e KEY=value)",
    type: "array",
    string: true
  }).option("header", {
    alias: "H",
    describe: 'Set HTTP headers for SSE and HTTP transports (e.g. -H "X-Api-Key: abc123" -H "Authorization: Bearer abc123")',
    type: "array",
    string: true
  }).option("timeout", {
    describe: "Set connection timeout in milliseconds",
    type: "number"
  }).option("trust", {
    describe: "Trust the server (bypass all tool call confirmation prompts)",
    type: "boolean"
  }).option("description", {
    describe: "Set the description for the server",
    type: "string"
  }).option("include-tools", {
    describe: "A comma-separated list of tools to include",
    type: "array",
    string: true
  }).option("exclude-tools", {
    describe: "A comma-separated list of tools to exclude",
    type: "array",
    string: true
  }).middleware((argv) => {
    if (argv["--"]) {
      const existingArgs = argv["args"] || [];
      argv["args"] = [...existingArgs, ...argv["--"]];
    }
  }), "builder"),
  handler: /* @__PURE__ */ __name(async (argv) => {
    await addMcpServer(
      argv["name"],
      argv["commandOrUrl"],
      argv["args"],
      {
        scope: argv["scope"],
        transport: argv["transport"],
        env: argv["env"],
        header: argv["header"],
        timeout: argv["timeout"],
        trust: argv["trust"],
        description: argv["description"],
        includeTools: argv["includeTools"],
        excludeTools: argv["excludeTools"]
      }
    );
  }, "handler")
};

// packages/cli/src/commands/mcp/remove.ts
init_esbuild_shims();
async function removeMcpServer(name3, options2) {
  const { scope } = options2;
  const settingsScope = scope === "user" ? "User" /* User */ : "Workspace" /* Workspace */;
  const settings = loadSettings();
  const existingSettings = settings.forScope(settingsScope).settings;
  const mcpServers = existingSettings.mcpServers || {};
  if (!mcpServers[name3]) {
    console.log(`Server "${name3}" not found in ${scope} settings.`);
    return;
  }
  delete mcpServers[name3];
  settings.setValue(settingsScope, "mcpServers", mcpServers);
  console.log(`Server "${name3}" removed from ${scope} settings.`);
}
__name(removeMcpServer, "removeMcpServer");
var removeCommand = {
  command: "remove <name>",
  describe: "Remove a server",
  builder: /* @__PURE__ */ __name((yargs) => yargs.usage("Usage: gemini mcp remove [options] <name>").positional("name", {
    describe: "Name of the server",
    type: "string",
    demandOption: true
  }).option("scope", {
    alias: "s",
    describe: "Configuration scope (user or project)",
    type: "string",
    default: "project",
    choices: ["user", "project"]
  }), "builder"),
  handler: /* @__PURE__ */ __name(async (argv) => {
    await removeMcpServer(argv["name"], {
      scope: argv["scope"]
    });
  }, "handler")
};

// packages/cli/src/commands/mcp/list.ts
init_esbuild_shims();
init_client3();
var COLOR_GREEN = "\x1B[32m";
var COLOR_YELLOW = "\x1B[33m";
var COLOR_RED = "\x1B[31m";
var RESET_COLOR = "\x1B[0m";
async function getMcpServersFromConfig() {
  const settings = loadSettings();
  const extensions = loadExtensions(
    new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir())
  );
  const mcpServers = { ...settings.merged.mcpServers || {} };
  for (const extension of extensions) {
    Object.entries(extension.config.mcpServers || {}).forEach(
      ([key, server]) => {
        if (mcpServers[key]) {
          return;
        }
        mcpServers[key] = {
          ...server,
          extensionName: extension.config.name
        };
      }
    );
  }
  return mcpServers;
}
__name(getMcpServersFromConfig, "getMcpServersFromConfig");
async function testMCPConnection(serverName, config) {
  const client = new Client({
    name: "mcp-test-client",
    version: "0.0.1"
  });
  let transport;
  try {
    transport = await createTransport(serverName, config, false);
  } catch (_error) {
    await client.close();
    return MCPServerStatus.DISCONNECTED;
  }
  try {
    await client.connect(transport, { timeout: 5e3 });
    await client.ping();
    await client.close();
    return MCPServerStatus.CONNECTED;
  } catch (_error) {
    await transport.close();
    return MCPServerStatus.DISCONNECTED;
  }
}
__name(testMCPConnection, "testMCPConnection");
async function getServerStatus(serverName, server) {
  return await testMCPConnection(serverName, server);
}
__name(getServerStatus, "getServerStatus");
async function listMcpServers() {
  const mcpServers = await getMcpServersFromConfig();
  const serverNames = Object.keys(mcpServers);
  if (serverNames.length === 0) {
    console.log("No MCP servers configured.");
    return;
  }
  console.log("Configured MCP servers:\n");
  for (const serverName of serverNames) {
    const server = mcpServers[serverName];
    const status = await getServerStatus(serverName, server);
    let statusIndicator = "";
    let statusText = "";
    switch (status) {
      case MCPServerStatus.CONNECTED:
        statusIndicator = COLOR_GREEN + "\u2713" + RESET_COLOR;
        statusText = "Connected";
        break;
      case MCPServerStatus.CONNECTING:
        statusIndicator = COLOR_YELLOW + "\u2026" + RESET_COLOR;
        statusText = "Connecting";
        break;
      case MCPServerStatus.DISCONNECTED:
      default:
        statusIndicator = COLOR_RED + "\u2717" + RESET_COLOR;
        statusText = "Disconnected";
        break;
    }
    let serverInfo = `${serverName}: `;
    if (server.httpUrl) {
      serverInfo += `${server.httpUrl} (http)`;
    } else if (server.url) {
      serverInfo += `${server.url} (sse)`;
    } else if (server.command) {
      serverInfo += `${server.command} ${server.args?.join(" ") || ""} (stdio)`;
    }
    console.log(`${statusIndicator} ${serverInfo} - ${statusText}`);
  }
}
__name(listMcpServers, "listMcpServers");
var listCommand2 = {
  command: "list",
  describe: "List all configured MCP servers",
  handler: /* @__PURE__ */ __name(async () => {
    await listMcpServers();
  }, "handler")
};

// packages/cli/src/commands/mcp.ts
var mcpCommand = {
  command: "mcp",
  describe: "Manage MCP servers",
  builder: /* @__PURE__ */ __name((yargs) => yargs.command(addCommand).command(removeCommand).command(listCommand2).demandCommand(1, "You need at least one command before continuing.").version(false), "builder"),
  handler: /* @__PURE__ */ __name(() => {
  }, "handler")
};

// packages/cli/src/config/webSearch.ts
init_esbuild_shims();
function buildWebSearchConfig(argv, settings, authType) {
  const isQwenOAuth = authType === AuthType2.QWEN_OAUTH;
  let providers = [];
  let userDefault;
  if (settings.webSearch) {
    providers = [...settings.webSearch.provider];
    userDefault = settings.webSearch.default;
  } else {
    const tavilyKey = argv.tavilyApiKey || settings.advanced?.tavilyApiKey || process.env["TAVILY_API_KEY"];
    if (tavilyKey) {
      providers.push({
        type: "tavily",
        apiKey: tavilyKey
      });
    }
    const googleKey = argv.googleApiKey || process.env["GOOGLE_API_KEY"];
    const googleEngineId = argv.googleSearchEngineId || process.env["GOOGLE_SEARCH_ENGINE_ID"];
    if (googleKey && googleEngineId) {
      providers.push({
        type: "google",
        apiKey: googleKey,
        searchEngineId: googleEngineId
      });
    }
  }
  if (isQwenOAuth) {
    const hasDashscope = providers.some((p) => p.type === "dashscope");
    if (!hasDashscope) {
      providers.push({ type: "dashscope" });
    }
  }
  if (providers.length === 0) {
    return void 0;
  }
  const providerPriority = [
    "tavily",
    "google",
    "dashscope"
  ];
  let defaultProvider = userDefault || argv.webSearchDefault;
  if (!defaultProvider) {
    for (const providerType of providerPriority) {
      if (providers.some((p) => p.type === providerType)) {
        defaultProvider = providerType;
        break;
      }
    }
    if (!defaultProvider) {
      defaultProvider = providers[0]?.type || "dashscope";
    }
  }
  return {
    provider: providers,
    default: defaultProvider
  };
}
__name(buildWebSearchConfig, "buildWebSearchConfig");

// packages/cli/src/config/config.ts
var logger5 = {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  debug: /* @__PURE__ */ __name((...args) => console.debug("[DEBUG]", ...args), "debug"),
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  warn: /* @__PURE__ */ __name((...args) => console.warn("[WARN]", ...args), "warn"),
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  error: /* @__PURE__ */ __name((...args) => console.error("[ERROR]", ...args), "error")
};
var VALID_APPROVAL_MODE_VALUES = [
  "plan",
  "default",
  "auto-edit",
  "yolo"
];
function formatApprovalModeError(value) {
  return new Error(
    `Invalid approval mode: ${value}. Valid values are: ${VALID_APPROVAL_MODE_VALUES.join(
      ", "
    )}`
  );
}
__name(formatApprovalModeError, "formatApprovalModeError");
function parseApprovalModeValue(value) {
  const normalized2 = value.trim().toLowerCase();
  switch (normalized2) {
    case "plan":
      return ApprovalMode.PLAN;
    case "default":
      return ApprovalMode.DEFAULT;
    case "yolo":
      return ApprovalMode.YOLO;
    case "auto_edit":
    case "autoedit":
    case "auto-edit":
      return ApprovalMode.AUTO_EDIT;
    default:
      throw formatApprovalModeError(value);
  }
}
__name(parseApprovalModeValue, "parseApprovalModeValue");
async function parseArguments(settings) {
  const rawArgv = hideBin(process.argv);
  const yargsInstance = yargs_default(rawArgv).locale("en").scriptName("qwen").usage(
    "Usage: qwen [options] [command]\n\nQwen Code - Launch an interactive CLI, use -p/--prompt for non-interactive mode"
  ).option("telemetry", {
    type: "boolean",
    description: "Enable telemetry? This flag specifically controls if telemetry is sent. Other --telemetry-* flags set specific values but do not enable telemetry on their own."
  }).option("telemetry-target", {
    type: "string",
    choices: ["local", "gcp"],
    description: "Set the telemetry target (local or gcp). Overrides settings files."
  }).option("telemetry-otlp-endpoint", {
    type: "string",
    description: "Set the OTLP endpoint for telemetry. Overrides environment variables and settings files."
  }).option("telemetry-otlp-protocol", {
    type: "string",
    choices: ["grpc", "http"],
    description: "Set the OTLP protocol for telemetry (grpc or http). Overrides settings files."
  }).option("telemetry-log-prompts", {
    type: "boolean",
    description: "Enable or disable logging of user prompts for telemetry. Overrides settings files."
  }).option("telemetry-outfile", {
    type: "string",
    description: "Redirect all telemetry output to the specified file."
  }).deprecateOption(
    "telemetry",
    'Use the "telemetry.enabled" setting in settings.json instead. This flag will be removed in a future version.'
  ).deprecateOption(
    "telemetry-target",
    'Use the "telemetry.target" setting in settings.json instead. This flag will be removed in a future version.'
  ).deprecateOption(
    "telemetry-otlp-endpoint",
    'Use the "telemetry.otlpEndpoint" setting in settings.json instead. This flag will be removed in a future version.'
  ).deprecateOption(
    "telemetry-otlp-protocol",
    'Use the "telemetry.otlpProtocol" setting in settings.json instead. This flag will be removed in a future version.'
  ).deprecateOption(
    "telemetry-log-prompts",
    'Use the "telemetry.logPrompts" setting in settings.json instead. This flag will be removed in a future version.'
  ).deprecateOption(
    "telemetry-outfile",
    'Use the "telemetry.outfile" setting in settings.json instead. This flag will be removed in a future version.'
  ).option("debug", {
    alias: "d",
    type: "boolean",
    description: "Run in debug mode?",
    default: false
  }).option("proxy", {
    type: "string",
    description: "Proxy for Qwen Code, like schema://user:password@host:port"
  }).deprecateOption(
    "proxy",
    'Use the "proxy" setting in settings.json instead. This flag will be removed in a future version.'
  ).command(
    "$0 [query..]",
    "Launch Qwen Code CLI",
    (yargsInstance2) => yargsInstance2.positional("query", {
      description: "Positional prompt. Defaults to one-shot; use -i/--prompt-interactive for interactive."
    }).option("model", {
      alias: "m",
      type: "string",
      description: `Model`
    }).option("prompt", {
      alias: "p",
      type: "string",
      description: "Prompt. Appended to input on stdin (if any)."
    }).option("prompt-interactive", {
      alias: "i",
      type: "string",
      description: "Execute the provided prompt and continue in interactive mode"
    }).option("sandbox", {
      alias: "s",
      type: "boolean",
      description: "Run in sandbox?"
    }).option("sandbox-image", {
      type: "string",
      description: "Sandbox image URI."
    }).option("all-files", {
      alias: ["a"],
      type: "boolean",
      description: "Include ALL files in context?",
      default: false
    }).option("show-memory-usage", {
      type: "boolean",
      description: "Show memory usage in status bar",
      default: false
    }).option("yolo", {
      alias: "y",
      type: "boolean",
      description: "Automatically accept all actions (aka YOLO mode, see https://www.youtube.com/watch?v=xvFZjo5PgG0 for more details)?",
      default: false
    }).option("approval-mode", {
      type: "string",
      choices: ["plan", "default", "auto-edit", "yolo"],
      description: "Set the approval mode: plan (plan only), default (prompt for approval), auto-edit (auto-approve edit tools), yolo (auto-approve all tools)"
    }).option("checkpointing", {
      alias: "c",
      type: "boolean",
      description: "Enables checkpointing of file edits",
      default: false
    }).option("experimental-acp", {
      type: "boolean",
      description: "Starts the agent in ACP mode"
    }).option("allowed-mcp-server-names", {
      type: "array",
      string: true,
      description: "Allowed MCP server names",
      coerce: /* @__PURE__ */ __name((mcpServerNames) => (
        // Handle comma-separated values
        mcpServerNames.flatMap(
          (mcpServerName) => mcpServerName.split(",").map((m) => m.trim())
        )
      ), "coerce")
    }).option("allowed-tools", {
      type: "array",
      string: true,
      description: "Tools that are allowed to run without confirmation",
      coerce: /* @__PURE__ */ __name((tools) => (
        // Handle comma-separated values
        tools.flatMap((tool) => tool.split(",").map((t2) => t2.trim()))
      ), "coerce")
    }).option("extensions", {
      alias: "e",
      type: "array",
      string: true,
      description: "A list of extensions to use. If not provided, all extensions are used.",
      coerce: /* @__PURE__ */ __name((extensions) => (
        // Handle comma-separated values
        extensions.flatMap(
          (extension) => extension.split(",").map((e2) => e2.trim())
        )
      ), "coerce")
    }).option("list-extensions", {
      alias: "l",
      type: "boolean",
      description: "List all available extensions and exit."
    }).option("include-directories", {
      type: "array",
      string: true,
      description: "Additional directories to include in the workspace (comma-separated or multiple --include-directories)",
      coerce: /* @__PURE__ */ __name((dirs) => (
        // Handle comma-separated values
        dirs.flatMap((dir) => dir.split(",").map((d) => d.trim()))
      ), "coerce")
    }).option("openai-logging", {
      type: "boolean",
      description: "Enable logging of OpenAI API calls for debugging and analysis"
    }).option("openai-logging-dir", {
      type: "string",
      description: "Custom directory path for OpenAI API logs. Overrides settings files."
    }).option("openai-api-key", {
      type: "string",
      description: "OpenAI API key to use for authentication"
    }).option("openai-base-url", {
      type: "string",
      description: "OpenAI base URL (for custom endpoints)"
    }).option("tavily-api-key", {
      type: "string",
      description: "Tavily API key for web search"
    }).option("google-api-key", {
      type: "string",
      description: "Google Custom Search API key"
    }).option("google-search-engine-id", {
      type: "string",
      description: "Google Custom Search Engine ID"
    }).option("web-search-default", {
      type: "string",
      description: "Default web search provider (dashscope, tavily, google)"
    }).option("screen-reader", {
      type: "boolean",
      description: "Enable screen reader mode for accessibility."
    }).option("vlm-switch-mode", {
      type: "string",
      choices: ["once", "session", "persist"],
      description: "Default behavior when images are detected in input. Values: once (one-time switch), session (switch for entire session), persist (continue with current model). Overrides settings files.",
      default: process.env["VLM_SWITCH_MODE"]
    }).option("output-format", {
      alias: "o",
      type: "string",
      description: "The format of the CLI output.",
      choices: ["text", "json"]
    }).deprecateOption(
      "show-memory-usage",
      'Use the "ui.showMemoryUsage" setting in settings.json instead. This flag will be removed in a future version.'
    ).deprecateOption(
      "sandbox-image",
      'Use the "tools.sandbox" setting in settings.json instead. This flag will be removed in a future version.'
    ).deprecateOption(
      "checkpointing",
      'Use the "general.checkpointing.enabled" setting in settings.json instead. This flag will be removed in a future version.'
    ).deprecateOption(
      "all-files",
      "Use @ includes in the application instead. This flag will be removed in a future version."
    ).deprecateOption(
      "prompt",
      "Use the positional prompt instead. This flag will be removed in a future version."
    ).fail((msg, err, yargs) => {
      console.error(msg || err?.message || "Unknown error");
      yargs.showHelp();
      process.exit(1);
    }).check((argv) => {
      const query = argv["query"];
      const hasPositionalQuery = Array.isArray(query) ? query.length > 0 : !!query;
      if (argv["prompt"] && hasPositionalQuery) {
        return "Cannot use both a positional prompt and the --prompt (-p) flag together";
      }
      if (argv["prompt"] && argv["promptInteractive"]) {
        return "Cannot use both --prompt (-p) and --prompt-interactive (-i) together";
      }
      if (argv["yolo"] && argv["approvalMode"]) {
        return "Cannot use both --yolo (-y) and --approval-mode together. Use --approval-mode=yolo instead.";
      }
      return true;
    })
  ).command(mcpCommand);
  if (settings?.experimental?.extensionManagement ?? true) {
    yargsInstance.command(extensionsCommand);
  }
  yargsInstance.version(await getCliVersion()).alias("v", "version").help().alias("h", "help").strict().demandCommand(0, 0);
  yargsInstance.wrap(yargsInstance.terminalWidth());
  const result = await yargsInstance.parse();
  if (result._.length > 0 && (result._[0] === "mcp" || result._[0] === "extensions")) {
    process.exit(0);
  }
  const queryArg = result.query;
  const q = Array.isArray(queryArg) ? queryArg.join(" ") : queryArg;
  if (q && !result["prompt"]) {
    const hasExplicitInteractive = result["promptInteractive"] === "" || !!result["promptInteractive"];
    if (hasExplicitInteractive) {
      result["promptInteractive"] = q;
    } else {
      result["prompt"] = q;
    }
  }
  result["query"] = q || void 0;
  return result;
}
__name(parseArguments, "parseArguments");
async function loadHierarchicalGeminiMemory(currentWorkingDirectory, includeDirectoriesToReadGemini = [], debugMode, fileService, settings, extensionContextFilePaths = [], folderTrust, memoryImportFormat = "tree", fileFilteringOptions) {
  const realCwd = fs74.realpathSync(path81.resolve(currentWorkingDirectory));
  const realHome = fs74.realpathSync(path81.resolve(homedir16()));
  const isHomeDirectory = realCwd === realHome;
  const effectiveCwd = isHomeDirectory ? "" : currentWorkingDirectory;
  if (debugMode) {
    logger5.debug(
      `CLI: Delegating hierarchical memory load to server for CWD: ${currentWorkingDirectory} (memoryImportFormat: ${memoryImportFormat})`
    );
  }
  return loadServerHierarchicalMemory(
    effectiveCwd,
    includeDirectoriesToReadGemini,
    debugMode,
    fileService,
    extensionContextFilePaths,
    folderTrust,
    memoryImportFormat,
    fileFilteringOptions,
    settings.context?.discoveryMaxDirs
  );
}
__name(loadHierarchicalGeminiMemory, "loadHierarchicalGeminiMemory");
function isDebugMode(argv) {
  return argv.debug || [process.env["DEBUG"], process.env["DEBUG_MODE"]].some(
    (v) => v === "true" || v === "1"
  );
}
__name(isDebugMode, "isDebugMode");
async function loadCliConfig(settings, extensions, extensionEnablementManager, sessionId2, argv, cwd7 = process.cwd()) {
  const debugMode = isDebugMode(argv);
  const memoryImportFormat = settings.context?.importFormat || "tree";
  const ideMode = settings.ide?.enabled ?? false;
  const folderTrust = settings.security?.folderTrust?.enabled ?? false;
  const trustedFolder = isWorkspaceTrusted(settings)?.isTrusted ?? true;
  const allExtensions = annotateActiveExtensions(
    extensions,
    cwd7,
    extensionEnablementManager
  );
  const activeExtensions = extensions.filter(
    (_, i) => allExtensions[i].isActive
  );
  if (settings.context?.fileName) {
    setGeminiMdFilename(settings.context.fileName);
  } else {
    setGeminiMdFilename(getCurrentGeminiMdFilename());
  }
  const extensionContextFilePaths = activeExtensions.flatMap(
    (e2) => e2.contextFiles
  );
  const fileService = new FileDiscoveryService(cwd7);
  const fileFiltering = {
    ...DEFAULT_MEMORY_FILE_FILTERING_OPTIONS,
    ...settings.context?.fileFiltering
  };
  const includeDirectories = (settings.context?.includeDirectories || []).map(resolvePath2).concat((argv.includeDirectories || []).map(resolvePath2));
  const { memoryContent, fileCount } = await loadHierarchicalGeminiMemory(
    cwd7,
    settings.context?.loadMemoryFromIncludeDirectories ? includeDirectories : [],
    debugMode,
    fileService,
    settings,
    extensionContextFilePaths,
    trustedFolder,
    memoryImportFormat,
    fileFiltering
  );
  let mcpServers = mergeMcpServers(settings, activeExtensions);
  const question = argv.promptInteractive || argv.prompt || "";
  let approvalMode;
  if (argv.approvalMode) {
    approvalMode = parseApprovalModeValue(argv.approvalMode);
  } else if (argv.yolo) {
    approvalMode = ApprovalMode.YOLO;
  } else if (settings.tools?.approvalMode) {
    approvalMode = parseApprovalModeValue(settings.tools.approvalMode);
  } else {
    approvalMode = ApprovalMode.DEFAULT;
  }
  if (!trustedFolder && approvalMode !== ApprovalMode.DEFAULT && approvalMode !== ApprovalMode.PLAN) {
    logger5.warn(
      `Approval mode overridden to "default" because the current folder is not trusted.`
    );
    approvalMode = ApprovalMode.DEFAULT;
  }
  let telemetrySettings;
  try {
    telemetrySettings = await resolveTelemetrySettings({
      argv,
      env: process.env,
      settings: settings.telemetry
    });
  } catch (err) {
    if (err instanceof FatalConfigError) {
      throw new FatalConfigError(
        `Invalid telemetry configuration: ${err.message}.`
      );
    }
    throw err;
  }
  const hasQuery = !!argv.query;
  const interactive = !!argv.promptInteractive || process.stdin.isTTY && !hasQuery && !argv.prompt;
  const extraExcludes = [];
  if (!interactive && !argv.experimentalAcp) {
    switch (approvalMode) {
      case ApprovalMode.PLAN:
      case ApprovalMode.DEFAULT:
        extraExcludes.push(ShellTool.Name, EditTool.Name, WriteFileTool.Name);
        break;
      case ApprovalMode.AUTO_EDIT:
        extraExcludes.push(ShellTool.Name);
        break;
      case ApprovalMode.YOLO:
        break;
      default:
        break;
    }
  }
  const excludeTools = mergeExcludeTools(
    settings,
    activeExtensions,
    extraExcludes.length > 0 ? extraExcludes : void 0
  );
  const blockedMcpServers = [];
  if (!argv.allowedMcpServerNames) {
    if (settings.mcp?.allowed) {
      mcpServers = allowedMcpServers(
        mcpServers,
        settings.mcp.allowed,
        blockedMcpServers
      );
    }
    if (settings.mcp?.excluded) {
      const excludedNames = new Set(settings.mcp.excluded.filter(Boolean));
      if (excludedNames.size > 0) {
        mcpServers = Object.fromEntries(
          Object.entries(mcpServers).filter(([key]) => !excludedNames.has(key))
        );
      }
    }
  }
  if (argv.allowedMcpServerNames) {
    mcpServers = allowedMcpServers(
      mcpServers,
      argv.allowedMcpServerNames,
      blockedMcpServers
    );
  }
  const resolvedModel = argv.model || process.env["OPENAI_MODEL"] || process.env["QWEN_MODEL"] || settings.model?.name;
  const sandboxConfig = await loadSandboxConfig(settings, argv);
  const screenReader = argv.screenReader !== void 0 ? argv.screenReader : settings.ui?.accessibility?.screenReader ?? false;
  const vlmSwitchMode = argv.vlmSwitchMode || settings.experimental?.vlmSwitchMode;
  return new Config({
    sessionId: sessionId2,
    embeddingModel: DEFAULT_QWEN_EMBEDDING_MODEL,
    sandbox: sandboxConfig,
    targetDir: cwd7,
    includeDirectories,
    loadMemoryFromIncludeDirectories: settings.context?.loadMemoryFromIncludeDirectories || false,
    debugMode,
    question,
    fullContext: argv.allFiles || false,
    coreTools: settings.tools?.core || void 0,
    allowedTools: argv.allowedTools || settings.tools?.allowed || void 0,
    excludeTools,
    toolDiscoveryCommand: settings.tools?.discoveryCommand,
    toolCallCommand: settings.tools?.callCommand,
    mcpServerCommand: settings.mcp?.serverCommand,
    mcpServers,
    userMemory: memoryContent,
    geminiMdFileCount: fileCount,
    approvalMode,
    showMemoryUsage: argv.showMemoryUsage || settings.ui?.showMemoryUsage || false,
    accessibility: {
      ...settings.ui?.accessibility,
      screenReader
    },
    telemetry: telemetrySettings,
    usageStatisticsEnabled: settings.privacy?.usageStatisticsEnabled ?? true,
    fileFiltering: settings.context?.fileFiltering,
    checkpointing: argv.checkpointing || settings.general?.checkpointing?.enabled,
    proxy: argv.proxy || process.env["HTTPS_PROXY"] || process.env["https_proxy"] || process.env["HTTP_PROXY"] || process.env["http_proxy"],
    cwd: cwd7,
    fileDiscoveryService: fileService,
    bugCommand: settings.advanced?.bugCommand,
    model: resolvedModel,
    extensionContextFilePaths,
    sessionTokenLimit: settings.model?.sessionTokenLimit ?? -1,
    maxSessionTurns: settings.model?.maxSessionTurns ?? -1,
    experimentalZedIntegration: argv.experimentalAcp || false,
    listExtensions: argv.listExtensions || false,
    extensions: allExtensions,
    blockedMcpServers,
    noBrowser: !!process.env["NO_BROWSER"],
    authType: settings.security?.auth?.selectedType,
    generationConfig: {
      ...settings.model?.generationConfig || {},
      model: resolvedModel,
      apiKey: argv.openaiApiKey || process.env["OPENAI_API_KEY"] || settings.security?.auth?.apiKey,
      baseUrl: argv.openaiBaseUrl || process.env["OPENAI_BASE_URL"] || settings.security?.auth?.baseUrl,
      enableOpenAILogging: (typeof argv.openaiLogging === "undefined" ? settings.model?.enableOpenAILogging : argv.openaiLogging) ?? false,
      openAILoggingDir: argv.openaiLoggingDir || settings.model?.openAILoggingDir
    },
    cliVersion: await getCliVersion(),
    webSearch: buildWebSearchConfig(
      argv,
      settings,
      settings.security?.auth?.selectedType
    ),
    summarizeToolOutput: settings.model?.summarizeToolOutput,
    ideMode,
    chatCompression: settings.model?.chatCompression,
    folderTrust,
    interactive,
    trustedFolder,
    useRipgrep: settings.tools?.useRipgrep,
    useBuiltinRipgrep: settings.tools?.useBuiltinRipgrep,
    shouldUseNodePtyShell: settings.tools?.shell?.enableInteractiveShell,
    skipNextSpeakerCheck: settings.model?.skipNextSpeakerCheck,
    skipLoopDetection: settings.model?.skipLoopDetection ?? false,
    skipStartupContext: settings.model?.skipStartupContext ?? false,
    vlmSwitchMode,
    truncateToolOutputThreshold: settings.tools?.truncateToolOutputThreshold,
    truncateToolOutputLines: settings.tools?.truncateToolOutputLines,
    enableToolOutputTruncation: settings.tools?.enableToolOutputTruncation,
    eventEmitter: appEvents,
    useSmartEdit: argv.useSmartEdit ?? settings.useSmartEdit,
    output: {
      format: argv.outputFormat ?? settings.output?.format
    }
  });
}
__name(loadCliConfig, "loadCliConfig");
function allowedMcpServers(mcpServers, allowMCPServers, blockedMcpServers) {
  const allowedNames = new Set(allowMCPServers.filter(Boolean));
  if (allowedNames.size > 0) {
    mcpServers = Object.fromEntries(
      Object.entries(mcpServers).filter(([key, server]) => {
        const isAllowed = allowedNames.has(key);
        if (!isAllowed) {
          blockedMcpServers.push({
            name: key,
            extensionName: server.extensionName || ""
          });
        }
        return isAllowed;
      })
    );
  } else {
    blockedMcpServers.push(
      ...Object.entries(mcpServers).map(([key, server]) => ({
        name: key,
        extensionName: server.extensionName || ""
      }))
    );
    mcpServers = {};
  }
  return mcpServers;
}
__name(allowedMcpServers, "allowedMcpServers");
function mergeMcpServers(settings, extensions) {
  const mcpServers = { ...settings.mcpServers || {} };
  for (const extension of extensions) {
    Object.entries(extension.config.mcpServers || {}).forEach(
      ([key, server]) => {
        if (mcpServers[key]) {
          logger5.warn(
            `Skipping extension MCP config for server with key "${key}" as it already exists.`
          );
          return;
        }
        mcpServers[key] = {
          ...server,
          extensionName: extension.config.name
        };
      }
    );
  }
  return mcpServers;
}
__name(mergeMcpServers, "mergeMcpServers");
function mergeExcludeTools(settings, extensions, extraExcludes) {
  const allExcludeTools = /* @__PURE__ */ new Set([
    ...settings.tools?.exclude || [],
    ...extraExcludes || []
  ]);
  for (const extension of extensions) {
    for (const tool of extension.config.excludeTools || []) {
      allExcludeTools.add(tool);
    }
  }
  return [...allExcludeTools];
}
__name(mergeExcludeTools, "mergeExcludeTools");

// packages/cli/src/ui/AppContainer.tsx
import process50 from "node:process";

// packages/cli/src/ui/hooks/useMemoryMonitor.ts
init_esbuild_shims();
var import_react97 = __toESM(require_react(), 1);
import process33 from "node:process";
var MEMORY_WARNING_THRESHOLD = 7 * 1024 * 1024 * 1024;
var MEMORY_CHECK_INTERVAL = 60 * 1e3;
var useMemoryMonitor = /* @__PURE__ */ __name(({ addItem }) => {
  (0, import_react97.useEffect)(() => {
    const intervalId = setInterval(() => {
      const usage2 = process33.memoryUsage().rss;
      if (usage2 > MEMORY_WARNING_THRESHOLD) {
        addItem(
          {
            type: "warning" /* WARNING */,
            text: `High memory usage detected: ${(usage2 / (1024 * 1024 * 1024)).toFixed(2)} GB. If you experience a crash, please file a bug report by running \`/bug\``
          },
          Date.now()
        );
        clearInterval(intervalId);
      }
    }, MEMORY_CHECK_INTERVAL);
    return () => clearInterval(intervalId);
  }, [addItem]);
}, "useMemoryMonitor");

// packages/cli/src/ui/hooks/useThemeCommand.ts
init_esbuild_shims();
var import_react98 = __toESM(require_react(), 1);
import process34 from "node:process";
var useThemeCommand = /* @__PURE__ */ __name((loadedSettings, setThemeError, addItem, initialThemeError) => {
  const [isThemeDialogOpen, setIsThemeDialogOpen] = (0, import_react98.useState)(!!initialThemeError);
  const openThemeDialog = (0, import_react98.useCallback)(() => {
    if (process34.env["NO_COLOR"]) {
      addItem(
        {
          type: "info" /* INFO */,
          text: "Theme configuration unavailable due to NO_COLOR env variable."
        },
        Date.now()
      );
      return;
    }
    setIsThemeDialogOpen(true);
  }, [addItem]);
  const applyTheme = (0, import_react98.useCallback)(
    (themeName) => {
      if (!themeManager.setActiveTheme(themeName)) {
        setIsThemeDialogOpen(true);
        setThemeError(`Theme "${themeName}" not found.`);
      } else {
        setThemeError(null);
      }
    },
    [setThemeError]
  );
  const handleThemeHighlight = (0, import_react98.useCallback)(
    (themeName) => {
      applyTheme(themeName);
    },
    [applyTheme]
  );
  const handleThemeSelect = (0, import_react98.useCallback)(
    (themeName, scope) => {
      try {
        const mergedCustomThemes = {
          ...loadedSettings.user.settings.ui?.customThemes || {},
          ...loadedSettings.workspace.settings.ui?.customThemes || {}
        };
        const isBuiltIn = themeManager.findThemeByName(themeName);
        const isCustom = themeName && mergedCustomThemes[themeName];
        if (!isBuiltIn && !isCustom) {
          setThemeError(`Theme "${themeName}" not found in selected scope.`);
          setIsThemeDialogOpen(true);
          return;
        }
        loadedSettings.setValue(scope, "ui.theme", themeName);
        if (loadedSettings.merged.ui?.customThemes) {
          themeManager.loadCustomThemes(loadedSettings.merged.ui?.customThemes);
        }
        applyTheme(loadedSettings.merged.ui?.theme);
        setThemeError(null);
      } finally {
        setIsThemeDialogOpen(false);
      }
    },
    [applyTheme, loadedSettings, setThemeError]
  );
  return {
    isThemeDialogOpen,
    openThemeDialog,
    handleThemeSelect,
    handleThemeHighlight
  };
}, "useThemeCommand");

// packages/cli/src/ui/auth/useAuth.ts
init_esbuild_shims();
var import_react100 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useQwenAuth.ts
init_esbuild_shims();
var import_react99 = __toESM(require_react(), 1);
var useQwenAuth = /* @__PURE__ */ __name((pendingAuthType, isAuthenticating) => {
  const [qwenAuthState, setQwenAuthState] = (0, import_react99.useState)({
    deviceAuth: null,
    authStatus: "idle",
    authMessage: null
  });
  const isQwenAuth = pendingAuthType === AuthType2.QWEN_OAUTH;
  (0, import_react99.useEffect)(() => {
    if (!isQwenAuth || !isAuthenticating) {
      setQwenAuthState({
        deviceAuth: null,
        authStatus: "idle",
        authMessage: null
      });
      return;
    }
    setQwenAuthState((prev) => ({
      ...prev,
      authStatus: "idle"
    }));
    const handleDeviceAuth = /* @__PURE__ */ __name((deviceAuth) => {
      setQwenAuthState((prev) => ({
        ...prev,
        deviceAuth: {
          verification_uri: deviceAuth.verification_uri,
          verification_uri_complete: deviceAuth.verification_uri_complete,
          user_code: deviceAuth.user_code,
          expires_in: deviceAuth.expires_in,
          device_code: deviceAuth.device_code
        },
        authStatus: "polling"
      }));
    }, "handleDeviceAuth");
    const handleAuthProgress = /* @__PURE__ */ __name((status, message) => {
      setQwenAuthState((prev) => ({
        ...prev,
        authStatus: status,
        authMessage: message || null
      }));
    }, "handleAuthProgress");
    qwenOAuth2Events.on(QwenOAuth2Event.AuthUri, handleDeviceAuth);
    qwenOAuth2Events.on(QwenOAuth2Event.AuthProgress, handleAuthProgress);
    return () => {
      qwenOAuth2Events.off(QwenOAuth2Event.AuthUri, handleDeviceAuth);
      qwenOAuth2Events.off(QwenOAuth2Event.AuthProgress, handleAuthProgress);
    };
  }, [isQwenAuth, isAuthenticating]);
  const cancelQwenAuth = (0, import_react99.useCallback)(() => {
    qwenOAuth2Events.emit(QwenOAuth2Event.AuthCancel);
    setQwenAuthState({
      deviceAuth: null,
      authStatus: "idle",
      authMessage: null
    });
  }, []);
  return {
    qwenAuthState,
    cancelQwenAuth
  };
}, "useQwenAuth");

// packages/cli/src/ui/auth/useAuth.ts
var useAuthCommand = /* @__PURE__ */ __name((settings, config, addItem) => {
  const unAuthenticated = settings.merged.security?.auth?.selectedType === void 0;
  const [authState, setAuthState] = (0, import_react100.useState)(
    unAuthenticated ? "updating" /* Updating */ : "unauthenticated" /* Unauthenticated */
  );
  const [authError, setAuthError] = (0, import_react100.useState)(null);
  const [isAuthenticating, setIsAuthenticating] = (0, import_react100.useState)(false);
  const [isAuthDialogOpen, setIsAuthDialogOpen] = (0, import_react100.useState)(unAuthenticated);
  const [pendingAuthType, setPendingAuthType] = (0, import_react100.useState)(
    void 0
  );
  const { qwenAuthState, cancelQwenAuth } = useQwenAuth(
    pendingAuthType,
    isAuthenticating
  );
  const onAuthError = (0, import_react100.useCallback)(
    (error) => {
      setAuthError(error);
      if (error) {
        setAuthState("updating" /* Updating */);
        setIsAuthDialogOpen(true);
      }
    },
    [setAuthError, setAuthState]
  );
  const handleAuthFailure = (0, import_react100.useCallback)(
    (error) => {
      setIsAuthenticating(false);
      const errorMessage = `Failed to authenticate. Message: ${getErrorMessage(error)}`;
      onAuthError(errorMessage);
      if (pendingAuthType) {
        const authEvent = new AuthEvent(
          pendingAuthType,
          "manual",
          "error",
          errorMessage
        );
        logAuth(config, authEvent);
      }
    },
    [onAuthError, pendingAuthType, config]
  );
  const handleAuthSuccess = (0, import_react100.useCallback)(
    async (authType, scope, credentials) => {
      try {
        settings.setValue(scope, "security.auth.selectedType", authType);
        if (authType !== AuthType2.QWEN_OAUTH && credentials) {
          if (credentials?.apiKey != null) {
            settings.setValue(
              scope,
              "security.auth.apiKey",
              credentials.apiKey
            );
          }
          if (credentials?.baseUrl != null) {
            settings.setValue(
              scope,
              "security.auth.baseUrl",
              credentials.baseUrl
            );
          }
          if (credentials?.model != null) {
            settings.setValue(scope, "model.name", credentials.model);
          }
          await clearCachedCredentialFile();
        }
      } catch (error) {
        handleAuthFailure(error);
        return;
      }
      setAuthError(null);
      setAuthState("authenticated" /* Authenticated */);
      setPendingAuthType(void 0);
      setIsAuthDialogOpen(false);
      setIsAuthenticating(false);
      const authEvent = new AuthEvent(authType, "manual", "success");
      logAuth(config, authEvent);
      addItem(
        {
          type: "info" /* INFO */,
          text: `Authenticated successfully with ${authType} credentials.`
        },
        Date.now()
      );
    },
    [settings, handleAuthFailure, config, addItem]
  );
  const performAuth = (0, import_react100.useCallback)(
    async (authType, scope, credentials) => {
      try {
        await config.refreshAuth(authType);
        handleAuthSuccess(authType, scope, credentials);
      } catch (e2) {
        handleAuthFailure(e2);
      }
    },
    [config, handleAuthSuccess, handleAuthFailure]
  );
  const handleAuthSelect = (0, import_react100.useCallback)(
    async (authType, scope, credentials) => {
      if (!authType) {
        setIsAuthDialogOpen(false);
        setAuthError(null);
        return;
      }
      setPendingAuthType(authType);
      setAuthError(null);
      setIsAuthDialogOpen(false);
      setIsAuthenticating(true);
      if (authType === AuthType2.USE_OPENAI) {
        if (credentials) {
          config.updateCredentials({
            apiKey: credentials.apiKey,
            baseUrl: credentials.baseUrl,
            model: credentials.model
          });
          await performAuth(authType, scope, credentials);
        }
        return;
      }
      await performAuth(authType, scope);
    },
    [config, performAuth]
  );
  const openAuthDialog = (0, import_react100.useCallback)(() => {
    setIsAuthDialogOpen(true);
  }, []);
  const cancelAuthentication = (0, import_react100.useCallback)(() => {
    if (isAuthenticating && pendingAuthType === AuthType2.QWEN_OAUTH) {
      cancelQwenAuth();
    }
    if (isAuthenticating && pendingAuthType) {
      const authEvent = new AuthEvent(pendingAuthType, "manual", "cancelled");
      logAuth(config, authEvent);
    }
    setIsAuthenticating(false);
    setIsAuthDialogOpen(true);
    setAuthError(null);
  }, [isAuthenticating, pendingAuthType, cancelQwenAuth, config]);
  (0, import_react100.useEffect)(() => {
    const defaultAuthType = process.env["QWEN_DEFAULT_AUTH_TYPE"];
    if (defaultAuthType && ![AuthType2.QWEN_OAUTH, AuthType2.USE_OPENAI].includes(
      defaultAuthType
    )) {
      onAuthError(
        `Invalid QWEN_DEFAULT_AUTH_TYPE value: "${defaultAuthType}". Valid values are: ${[AuthType2.QWEN_OAUTH, AuthType2.USE_OPENAI].join(", ")}`
      );
    }
  }, [onAuthError]);
  return {
    authState,
    setAuthState,
    authError,
    onAuthError,
    isAuthDialogOpen,
    isAuthenticating,
    pendingAuthType,
    qwenAuthState,
    handleAuthSelect,
    openAuthDialog,
    cancelAuthentication
  };
}, "useAuthCommand");

// packages/cli/src/ui/hooks/useQuotaAndFallback.ts
init_esbuild_shims();
var import_react101 = __toESM(require_react(), 1);
function useQuotaAndFallback({
  config,
  historyManager,
  userTier,
  setAuthState,
  setModelSwitchedFromQuotaError
}) {
  const [proQuotaRequest, setProQuotaRequest] = (0, import_react101.useState)(null);
  const isDialogPending = (0, import_react101.useRef)(false);
  (0, import_react101.useEffect)(() => {
    const fallbackHandler = /* @__PURE__ */ __name(async (failedModel, fallbackModel, error) => {
      if (config.isInFallbackMode()) {
        return null;
      }
      const contentGeneratorConfig = config.getContentGeneratorConfig();
      if (!contentGeneratorConfig || contentGeneratorConfig.authType !== AuthType2.LOGIN_WITH_GOOGLE) {
        return null;
      }
      const isPaidTier = userTier === UserTierId.LEGACY || userTier === UserTierId.STANDARD;
      let message;
      if (error && isProQuotaExceededError(error)) {
        if (isPaidTier) {
          message = `\u26A1 You have reached your daily ${failedModel} quota limit.
\u26A1 You can choose to authenticate with a paid API key or continue with the fallback model.
\u26A1 To continue accessing the ${failedModel} model today, consider using /auth to switch to using a paid API key from AI Studio at https://aistudio.google.com/apikey`;
        } else {
          message = `\u26A1 You have reached your daily ${failedModel} quota limit.
\u26A1 You can choose to authenticate with a paid API key or continue with the fallback model.
\u26A1 To increase your limits, upgrade to a Gemini Code Assist Standard or Enterprise plan with higher limits at https://goo.gle/set-up-gemini-code-assist
\u26A1 Or you can utilize a Gemini API Key. See: https://goo.gle/gemini-cli-docs-auth#gemini-api-key
\u26A1 You can switch authentication methods by typing /auth`;
        }
      } else if (error && isGenericQuotaExceededError(error)) {
        const actionMessage = `\u26A1 You have reached your daily quota limit.
\u26A1 Automatically switching from ${failedModel} to ${fallbackModel} for the remainder of this session.`;
        if (isPaidTier) {
          message = `${actionMessage}
\u26A1 To continue accessing the ${failedModel} model today, consider using /auth to switch to using a paid API key from AI Studio at https://aistudio.google.com/apikey`;
        } else {
          message = `${actionMessage}
\u26A1 To increase your limits, upgrade to a Gemini Code Assist Standard or Enterprise plan with higher limits at https://goo.gle/set-up-gemini-code-assist
\u26A1 Or you can utilize a Gemini API Key. See: https://goo.gle/gemini-cli-docs-auth#gemini-api-key
\u26A1 You can switch authentication methods by typing /auth`;
        }
      } else {
        const actionMessage = `\u26A1 Automatically switching from ${failedModel} to ${fallbackModel} for faster responses for the remainder of this session.`;
        if (isPaidTier) {
          message = `${actionMessage}
\u26A1 Possible reasons for this are that you have received multiple consecutive capacity errors or you have reached your daily ${failedModel} quota limit
\u26A1 To continue accessing the ${failedModel} model today, consider using /auth to switch to using a paid API key from AI Studio at https://aistudio.google.com/apikey`;
        } else {
          message = `${actionMessage}
\u26A1 Possible reasons for this are that you have received multiple consecutive capacity errors or you have reached your daily ${failedModel} quota limit
\u26A1 To increase your limits, upgrade to a Gemini Code Assist Standard or Enterprise plan with higher limits at https://goo.gle/set-up-gemini-code-assist
\u26A1 Or you can utilize a Gemini API Key. See: https://goo.gle/gemini-cli-docs-auth#gemini-api-key
\u26A1 You can switch authentication methods by typing /auth`;
        }
      }
      historyManager.addItem(
        {
          type: "info" /* INFO */,
          text: message
        },
        Date.now()
      );
      setModelSwitchedFromQuotaError(true);
      config.setQuotaErrorOccurred(true);
      if (error && isProQuotaExceededError(error)) {
        if (isDialogPending.current) {
          return "stop";
        }
        isDialogPending.current = true;
        const intent = await new Promise(
          (resolve24) => {
            setProQuotaRequest({
              failedModel,
              fallbackModel,
              resolve: resolve24
            });
          }
        );
        return intent;
      }
      return "stop";
    }, "fallbackHandler");
    config.setFallbackModelHandler(fallbackHandler);
  }, [config, historyManager, userTier, setModelSwitchedFromQuotaError]);
  const handleProQuotaChoice = (0, import_react101.useCallback)(
    (choice2) => {
      if (!proQuotaRequest) return;
      const intent = choice2 === "auth" ? "auth" : "retry";
      proQuotaRequest.resolve(intent);
      setProQuotaRequest(null);
      isDialogPending.current = false;
      if (choice2 === "auth") {
        setAuthState("updating" /* Updating */);
      } else {
        historyManager.addItem(
          {
            type: "info" /* INFO */,
            text: "Switched to fallback model. Tip: Press Ctrl+P (or Up Arrow) to recall your previous prompt and submit it again if you wish."
          },
          Date.now()
        );
      }
    },
    [proQuotaRequest, setAuthState, historyManager]
  );
  return {
    proQuotaRequest,
    handleProQuotaChoice
  };
}
__name(useQuotaAndFallback, "useQuotaAndFallback");

// packages/cli/src/ui/hooks/useEditorSettings.ts
init_esbuild_shims();
var import_react102 = __toESM(require_react(), 1);
var useEditorSettings = /* @__PURE__ */ __name((loadedSettings, setEditorError, addItem) => {
  const [isEditorDialogOpen, setIsEditorDialogOpen] = (0, import_react102.useState)(false);
  const openEditorDialog = (0, import_react102.useCallback)(() => {
    setIsEditorDialogOpen(true);
  }, []);
  const handleEditorSelect = (0, import_react102.useCallback)(
    (editorType, scope) => {
      if (editorType && (!checkHasEditorType(editorType) || !allowEditorTypeInSandbox(editorType))) {
        return;
      }
      try {
        loadedSettings.setValue(scope, "general.preferredEditor", editorType);
        addItem(
          {
            type: "info" /* INFO */,
            text: `Editor preference ${editorType ? `set to "${editorType}"` : "cleared"} in ${scope} settings.`
          },
          Date.now()
        );
        setEditorError(null);
        setIsEditorDialogOpen(false);
      } catch (error) {
        setEditorError(`Failed to set editor preference: ${error}`);
      }
    },
    [loadedSettings, setEditorError, addItem]
  );
  const exitEditorDialog = (0, import_react102.useCallback)(() => {
    setIsEditorDialogOpen(false);
  }, []);
  return {
    isEditorDialogOpen,
    openEditorDialog,
    handleEditorSelect,
    exitEditorDialog
  };
}, "useEditorSettings");

// packages/cli/src/ui/hooks/useSettingsCommand.ts
init_esbuild_shims();
var import_react103 = __toESM(require_react(), 1);
function useSettingsCommand() {
  const [isSettingsDialogOpen, setIsSettingsDialogOpen] = (0, import_react103.useState)(false);
  const openSettingsDialog = (0, import_react103.useCallback)(() => {
    setIsSettingsDialogOpen(true);
  }, []);
  const closeSettingsDialog = (0, import_react103.useCallback)(() => {
    setIsSettingsDialogOpen(false);
  }, []);
  return {
    isSettingsDialogOpen,
    openSettingsDialog,
    closeSettingsDialog
  };
}
__name(useSettingsCommand, "useSettingsCommand");

// packages/cli/src/ui/hooks/useModelCommand.ts
init_esbuild_shims();
var import_react104 = __toESM(require_react(), 1);
var useModelCommand = /* @__PURE__ */ __name(() => {
  const [isModelDialogOpen, setIsModelDialogOpen] = (0, import_react104.useState)(false);
  const openModelDialog = (0, import_react104.useCallback)(() => {
    setIsModelDialogOpen(true);
  }, []);
  const closeModelDialog = (0, import_react104.useCallback)(() => {
    setIsModelDialogOpen(false);
  }, []);
  return {
    isModelDialogOpen,
    openModelDialog,
    closeModelDialog
  };
}, "useModelCommand");

// packages/cli/src/ui/hooks/useApprovalModeCommand.ts
init_esbuild_shims();
var import_react105 = __toESM(require_react(), 1);
var useApprovalModeCommand = /* @__PURE__ */ __name((loadedSettings, config) => {
  const [isApprovalModeDialogOpen, setIsApprovalModeDialogOpen] = (0, import_react105.useState)(false);
  const openApprovalModeDialog = (0, import_react105.useCallback)(() => {
    setIsApprovalModeDialogOpen(true);
  }, []);
  const handleApprovalModeSelect = (0, import_react105.useCallback)(
    (mode, scope) => {
      try {
        if (!mode) {
          setIsApprovalModeDialogOpen(false);
          return;
        }
        loadedSettings.setValue(scope, "tools.approvalMode", mode);
        config.setApprovalMode(
          loadedSettings.merged.tools?.approvalMode ?? mode
        );
      } finally {
        setIsApprovalModeDialogOpen(false);
      }
    },
    [config, loadedSettings]
  );
  return {
    isApprovalModeDialogOpen,
    openApprovalModeDialog,
    handleApprovalModeSelect
  };
}, "useApprovalModeCommand");

// packages/cli/src/ui/hooks/slashCommandProcessor.ts
init_esbuild_shims();
var import_react108 = __toESM(require_react(), 1);
init_node();
import process37 from "node:process";

// packages/cli/src/services/CommandService.ts
init_esbuild_shims();
var CommandService = class _CommandService {
  /**
   * Private constructor to enforce the use of the async factory.
   * @param commands A readonly array of the fully loaded and de-duplicated commands.
   */
  constructor(commands) {
    this.commands = commands;
  }
  static {
    __name(this, "CommandService");
  }
  /**
   * Asynchronously creates and initializes a new CommandService instance.
   *
   * This factory method orchestrates the entire command loading process. It
   * runs all provided loaders in parallel, aggregates their results, handles
   * name conflicts for extension commands by renaming them, and then returns a
   * fully constructed `CommandService` instance.
   *
   * Conflict resolution:
   * - Extension commands that conflict with existing commands are renamed to
   *   `extensionName.commandName`
   * - Non-extension commands (built-in, user, project) override earlier commands
   *   with the same name based on loader order
   *
   * @param loaders An array of objects that conform to the `ICommandLoader`
   *   interface. Built-in commands should come first, followed by FileCommandLoader.
   * @param signal An AbortSignal to cancel the loading process.
   * @returns A promise that resolves to a new, fully initialized `CommandService` instance.
   */
  static async create(loaders, signal) {
    const results = await Promise.allSettled(
      loaders.map((loader) => loader.loadCommands(signal))
    );
    const allCommands = [];
    for (const result of results) {
      if (result.status === "fulfilled") {
        allCommands.push(...result.value);
      } else {
        console.debug("A command loader failed:", result.reason);
      }
    }
    const commandMap = /* @__PURE__ */ new Map();
    for (const cmd of allCommands) {
      let finalName = cmd.name;
      if (cmd.extensionName && commandMap.has(cmd.name)) {
        let renamedName = `${cmd.extensionName}.${cmd.name}`;
        let suffix = 1;
        while (commandMap.has(renamedName)) {
          renamedName = `${cmd.extensionName}.${cmd.name}${suffix}`;
          suffix++;
        }
        finalName = renamedName;
      }
      commandMap.set(finalName, {
        ...cmd,
        name: finalName
      });
    }
    const finalCommands = Object.freeze(Array.from(commandMap.values()));
    return new _CommandService(finalCommands);
  }
  /**
   * Retrieves the currently loaded and de-duplicated list of slash commands.
   *
   * This method is a safe accessor for the service's state. It returns a
   * readonly array, preventing consumers from modifying the service's internal state.
   *
   * @returns A readonly, unified array of available `SlashCommand` objects.
   */
  getCommands() {
    return this.commands;
  }
};

// packages/cli/src/services/BuiltinCommandLoader.ts
init_esbuild_shims();

// packages/cli/src/ui/commands/aboutCommand.ts
init_esbuild_shims();

// packages/cli/src/utils/systemInfo.ts
init_esbuild_shims();
import process35 from "node:process";
import os29 from "node:os";
import { execSync as execSync4 } from "node:child_process";

// packages/cli/src/generated/git-commit.ts
init_esbuild_shims();
var GIT_COMMIT_INFO2 = "442a9aed";

// packages/cli/src/utils/systemInfo.ts
async function getNpmVersion() {
  try {
    return execSync4("npm --version", { encoding: "utf-8" }).trim();
  } catch {
    return "unknown";
  }
}
__name(getNpmVersion, "getNpmVersion");
async function getIdeClientName(context2) {
  if (!context2.services.config?.getIdeMode()) {
    return "";
  }
  try {
    const ideClient = await IdeClient.getInstance();
    return ideClient?.getDetectedIdeDisplayName() ?? "";
  } catch {
    return "";
  }
}
__name(getIdeClientName, "getIdeClientName");
function getSandboxEnv(stripPrefix = false) {
  const sandbox = process35.env["SANDBOX"];
  if (!sandbox || sandbox === "sandbox-exec") {
    if (sandbox === "sandbox-exec") {
      const profile = process35.env["SEATBELT_PROFILE"] || "unknown";
      return `sandbox-exec (${profile})`;
    }
    return "no sandbox";
  }
  if (stripPrefix) {
    return sandbox.replace(/^qwen-(?:code-)?/, "");
  }
  return sandbox;
}
__name(getSandboxEnv, "getSandboxEnv");
async function getSystemInfo(context2) {
  const osPlatform = process35.platform;
  const osArch = process35.arch;
  const osRelease = os29.release();
  const nodeVersion2 = process35.version;
  const npmVersion = await getNpmVersion();
  const sandboxEnv = getSandboxEnv();
  const modelVersion = context2.services.config?.getModel() || "Unknown";
  const cliVersion = await getCliVersion();
  const selectedAuthType = context2.services.settings.merged.security?.auth?.selectedType || "";
  const ideClient = await getIdeClientName(context2);
  const sessionId2 = context2.services.config?.getSessionId() || "unknown";
  return {
    cliVersion,
    osPlatform,
    osArch,
    osRelease,
    nodeVersion: nodeVersion2,
    npmVersion,
    sandboxEnv,
    modelVersion,
    selectedAuthType,
    ideClient,
    sessionId: sessionId2
  };
}
__name(getSystemInfo, "getSystemInfo");
async function getExtendedSystemInfo(context2) {
  const baseInfo = await getSystemInfo(context2);
  const memoryUsage = formatMemoryUsage2(process35.memoryUsage().rss);
  const sandboxEnv = getSandboxEnv(true);
  const baseUrl = baseInfo.selectedAuthType === AuthType2.USE_OPENAI ? context2.services.config?.getContentGeneratorConfig()?.baseUrl : void 0;
  const gitCommit = GIT_COMMIT_INFO2 && !["N/A"].includes(GIT_COMMIT_INFO2) ? GIT_COMMIT_INFO2 : void 0;
  return {
    ...baseInfo,
    sandboxEnv,
    memoryUsage,
    baseUrl,
    gitCommit
  };
}
__name(getExtendedSystemInfo, "getExtendedSystemInfo");

// packages/cli/src/ui/commands/aboutCommand.ts
var aboutCommand = {
  name: "about",
  description: "show version info",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2) => {
    const systemInfo = await getExtendedSystemInfo(context2);
    const aboutItem = {
      type: "about" /* ABOUT */,
      systemInfo
    };
    context2.ui.addItem(aboutItem, Date.now());
  }, "action")
};

// packages/cli/src/ui/commands/agentsCommand.ts
init_esbuild_shims();
var agentsCommand = {
  name: "agents",
  description: "Manage subagents for specialized task delegation.",
  kind: "built-in" /* BUILT_IN */,
  subCommands: [
    {
      name: "manage",
      description: "Manage existing subagents (view, edit, delete).",
      kind: "built-in" /* BUILT_IN */,
      action: /* @__PURE__ */ __name(() => ({
        type: "dialog",
        dialog: "subagent_list"
      }), "action")
    },
    {
      name: "create",
      description: "Create a new subagent with guided setup.",
      kind: "built-in" /* BUILT_IN */,
      action: /* @__PURE__ */ __name(() => ({
        type: "dialog",
        dialog: "subagent_create"
      }), "action")
    }
  ]
};

// packages/cli/src/ui/commands/approvalModeCommand.ts
init_esbuild_shims();
var approvalModeCommand = {
  name: "approval-mode",
  description: "View or change the approval mode for tool usage",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (_context, _args) => ({
    type: "dialog",
    dialog: "approval-mode"
  }), "action")
};

// packages/cli/src/ui/commands/authCommand.ts
init_esbuild_shims();
var authCommand = {
  name: "auth",
  description: "change the auth method",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name((_context, _args) => ({
    type: "dialog",
    dialog: "auth"
  }), "action")
};

// packages/cli/src/ui/commands/bugCommand.ts
init_esbuild_shims();
init_open();
var bugCommand = {
  name: "bug",
  description: "submit a bug report",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, args) => {
    const bugDescription = (args || "").trim();
    const systemInfo = await getExtendedSystemInfo(context2);
    const fields = getSystemInfoFields(systemInfo);
    let info = "\n";
    for (const field of fields) {
      info += `* **${field.label}:** ${getFieldValue(field, systemInfo)}
`;
    }
    let bugReportUrl = "https://github.com/QwenLM/qwen-code/issues/new?template=bug_report.yml&title={title}&info={info}";
    const bugCommandSettings = context2.services.config?.getBugCommand();
    if (bugCommandSettings?.urlTemplate) {
      bugReportUrl = bugCommandSettings.urlTemplate;
    }
    bugReportUrl = bugReportUrl.replace("{title}", encodeURIComponent(bugDescription)).replace("{info}", encodeURIComponent(info));
    context2.ui.addItem(
      {
        type: "info" /* INFO */,
        text: `To submit your bug report, please open the following URL in your browser:
${bugReportUrl}`
      },
      Date.now()
    );
    try {
      await open_default(bugReportUrl);
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      context2.ui.addItem(
        {
          type: "error" /* ERROR */,
          text: `Could not open URL in browser: ${errorMessage}`
        },
        Date.now()
      );
    }
  }, "action")
};

// packages/cli/src/ui/commands/chatCommand.ts
init_esbuild_shims();
var import_react106 = __toESM(require_react(), 1);
import * as fsPromises5 from "node:fs/promises";
import path82 from "node:path";
var getSavedChatTags = /* @__PURE__ */ __name(async (context2, mtSortDesc) => {
  const cfg = context2.services.config;
  const geminiDir = cfg?.storage?.getProjectTempDir();
  if (!geminiDir) {
    return [];
  }
  try {
    const file_head = "checkpoint-";
    const file_tail = ".json";
    const files = await fsPromises5.readdir(geminiDir);
    const chatDetails = [];
    for (const file of files) {
      if (file.startsWith(file_head) && file.endsWith(file_tail)) {
        const filePath = path82.join(geminiDir, file);
        const stats = await fsPromises5.stat(filePath);
        const tagName = file.slice(file_head.length, -file_tail.length);
        chatDetails.push({
          name: decodeTagName(tagName),
          mtime: stats.mtime
        });
      }
    }
    chatDetails.sort(
      (a, b) => mtSortDesc ? b.mtime.getTime() - a.mtime.getTime() : a.mtime.getTime() - b.mtime.getTime()
    );
    return chatDetails;
  } catch (_err) {
    return [];
  }
}, "getSavedChatTags");
var listCommand3 = {
  name: "list",
  description: "List saved conversation checkpoints",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2) => {
    const chatDetails = await getSavedChatTags(context2, false);
    if (chatDetails.length === 0) {
      return {
        type: "message",
        messageType: "info",
        content: "No saved conversation checkpoints found."
      };
    }
    const maxNameLength = Math.max(
      ...chatDetails.map((chat) => chat.name.length)
    );
    let message = "List of saved conversations:\n\n";
    for (const chat of chatDetails) {
      const paddedName = chat.name.padEnd(maxNameLength, " ");
      const isoString = chat.mtime.toISOString();
      const match2 = isoString.match(/(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})/);
      const formattedDate = match2 ? `${match2[1]} ${match2[2]}` : "Invalid Date";
      message += `  - ${paddedName}  (saved on ${formattedDate})
`;
    }
    message += `
Note: Newest last, oldest first`;
    return {
      type: "message",
      messageType: "info",
      content: message
    };
  }, "action")
};
var saveCommand = {
  name: "save",
  description: "Save the current conversation as a checkpoint. Usage: /chat save <tag>",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, args) => {
    const tag2 = args.trim();
    if (!tag2) {
      return {
        type: "message",
        messageType: "error",
        content: "Missing tag. Usage: /chat save <tag>"
      };
    }
    const { logger: logger6, config } = context2.services;
    await logger6.initialize();
    if (!context2.overwriteConfirmed) {
      const exists2 = await logger6.checkpointExists(tag2);
      if (exists2) {
        return {
          type: "confirm_action",
          prompt: import_react106.default.createElement(
            Text,
            null,
            "A checkpoint with the tag ",
            import_react106.default.createElement(Text, { color: theme.text.accent }, tag2),
            " already exists. Do you want to overwrite it?"
          ),
          originalInvocation: {
            raw: context2.invocation?.raw || `/chat save ${tag2}`
          }
        };
      }
    }
    const chat = await config?.getGeminiClient()?.getChat();
    if (!chat) {
      return {
        type: "message",
        messageType: "error",
        content: "No chat client available to save conversation."
      };
    }
    const history = chat.getHistory();
    if (history.length > 2) {
      await logger6.saveCheckpoint(history, tag2);
      return {
        type: "message",
        messageType: "info",
        content: `Conversation checkpoint saved with tag: ${decodeTagName(tag2)}.`
      };
    } else {
      return {
        type: "message",
        messageType: "info",
        content: "No conversation found to save."
      };
    }
  }, "action")
};
var resumeCommand = {
  name: "resume",
  altNames: ["load"],
  description: "Resume a conversation from a checkpoint. Usage: /chat resume <tag>",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, args) => {
    const tag2 = args.trim();
    if (!tag2) {
      return {
        type: "message",
        messageType: "error",
        content: "Missing tag. Usage: /chat resume <tag>"
      };
    }
    const { logger: logger6 } = context2.services;
    await logger6.initialize();
    const conversation = await logger6.loadCheckpoint(tag2);
    if (conversation.length === 0) {
      return {
        type: "message",
        messageType: "info",
        content: `No saved checkpoint found with tag: ${decodeTagName(tag2)}.`
      };
    }
    const rolemap = {
      user: "user" /* USER */,
      model: "gemini" /* GEMINI */
    };
    const uiHistory = [];
    let hasSystemPrompt = false;
    let i = 0;
    for (const item of conversation) {
      i += 1;
      const text = item.parts?.filter((m) => !!m.text).map((m) => m.text).join("") || "";
      if (!text) {
        continue;
      }
      if (i === 1 && text.match(/context for our chat/)) {
        hasSystemPrompt = true;
      }
      if (i > 2 || !hasSystemPrompt) {
        uiHistory.push({
          type: item.role && rolemap[item.role] || "gemini" /* GEMINI */,
          text
        });
      }
    }
    return {
      type: "load_history",
      history: uiHistory,
      clientHistory: conversation
    };
  }, "action"),
  completion: /* @__PURE__ */ __name(async (context2, partialArg) => {
    const chatDetails = await getSavedChatTags(context2, true);
    return chatDetails.map((chat) => chat.name).filter((name3) => name3.startsWith(partialArg));
  }, "completion")
};
var deleteCommand = {
  name: "delete",
  description: "Delete a conversation checkpoint. Usage: /chat delete <tag>",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, args) => {
    const tag2 = args.trim();
    if (!tag2) {
      return {
        type: "message",
        messageType: "error",
        content: "Missing tag. Usage: /chat delete <tag>"
      };
    }
    const { logger: logger6 } = context2.services;
    await logger6.initialize();
    const deleted = await logger6.deleteCheckpoint(tag2);
    if (deleted) {
      return {
        type: "message",
        messageType: "info",
        content: `Conversation checkpoint '${decodeTagName(tag2)}' has been deleted.`
      };
    } else {
      return {
        type: "message",
        messageType: "error",
        content: `Error: No checkpoint found with tag '${decodeTagName(tag2)}'.`
      };
    }
  }, "action"),
  completion: /* @__PURE__ */ __name(async (context2, partialArg) => {
    const chatDetails = await getSavedChatTags(context2, true);
    return chatDetails.map((chat) => chat.name).filter((name3) => name3.startsWith(partialArg));
  }, "completion")
};
function serializeHistoryToMarkdown(history) {
  return history.map((item) => {
    const text = item.parts?.map((part) => {
      if (part.text) {
        return part.text;
      }
      if (part.functionCall) {
        return `**Tool Command**:
\`\`\`json
${JSON.stringify(
          part.functionCall,
          null,
          2
        )}
\`\`\``;
      }
      if (part.functionResponse) {
        return `**Tool Response**:
\`\`\`json
${JSON.stringify(
          part.functionResponse,
          null,
          2
        )}
\`\`\``;
      }
      return "";
    }).join("") || "";
    const roleIcon = item.role === "user" ? "\u{1F9D1}\u200D\u{1F4BB}" : "\u2728";
    return `${roleIcon} ## ${(item.role || "model").toUpperCase()}

${text}`;
  }).join("\n\n---\n\n");
}
__name(serializeHistoryToMarkdown, "serializeHistoryToMarkdown");
var shareCommand = {
  name: "share",
  description: "Share the current conversation to a markdown or json file. Usage: /chat share <file>",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, args) => {
    let filePathArg = args.trim();
    if (!filePathArg) {
      filePathArg = `gemini-conversation-${Date.now()}.json`;
    }
    const filePath = path82.resolve(filePathArg);
    const extension = path82.extname(filePath);
    if (extension !== ".md" && extension !== ".json") {
      return {
        type: "message",
        messageType: "error",
        content: "Invalid file format. Only .md and .json are supported."
      };
    }
    const chat = await context2.services.config?.getGeminiClient()?.getChat();
    if (!chat) {
      return {
        type: "message",
        messageType: "error",
        content: "No chat client available to share conversation."
      };
    }
    const history = chat.getHistory();
    if (history.length <= 2) {
      return {
        type: "message",
        messageType: "info",
        content: "No conversation found to share."
      };
    }
    let content = "";
    if (extension === ".json") {
      content = JSON.stringify(history, null, 2);
    } else {
      content = serializeHistoryToMarkdown(history);
    }
    try {
      await fsPromises5.writeFile(filePath, content);
      return {
        type: "message",
        messageType: "info",
        content: `Conversation shared to ${filePath}`
      };
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      return {
        type: "message",
        messageType: "error",
        content: `Error sharing conversation: ${errorMessage}`
      };
    }
  }, "action")
};
var chatCommand = {
  name: "chat",
  description: "Manage conversation history.",
  kind: "built-in" /* BUILT_IN */,
  subCommands: [
    listCommand3,
    saveCommand,
    resumeCommand,
    deleteCommand,
    shareCommand
  ]
};

// packages/cli/src/ui/commands/clearCommand.ts
init_esbuild_shims();
var clearCommand = {
  name: "clear",
  description: "clear the screen and conversation history",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, _args) => {
    const geminiClient = context2.services.config?.getGeminiClient();
    if (geminiClient) {
      context2.ui.setDebugMessage("Clearing terminal and resetting chat.");
      await geminiClient.resetChat();
    } else {
      context2.ui.setDebugMessage("Clearing terminal.");
    }
    uiTelemetryService.setLastPromptTokenCount(0);
    context2.ui.clear();
  }, "action")
};

// packages/cli/src/ui/commands/compressCommand.ts
init_esbuild_shims();
var compressCommand = {
  name: "compress",
  altNames: ["summarize"],
  description: "Compresses the context by replacing it with a summary.",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2) => {
    const { ui: ui2 } = context2;
    if (ui2.pendingItem) {
      ui2.addItem(
        {
          type: "error" /* ERROR */,
          text: "Already compressing, wait for previous request to complete"
        },
        Date.now()
      );
      return;
    }
    const pendingMessage = {
      type: "compression" /* COMPRESSION */,
      compression: {
        isPending: true,
        originalTokenCount: null,
        newTokenCount: null,
        compressionStatus: null
      }
    };
    try {
      ui2.setPendingItem(pendingMessage);
      const promptId = `compress-${Date.now()}`;
      const compressed = await context2.services.config?.getGeminiClient()?.tryCompressChat(promptId, true);
      if (compressed) {
        ui2.addItem(
          {
            type: "compression" /* COMPRESSION */,
            compression: {
              isPending: false,
              originalTokenCount: compressed.originalTokenCount,
              newTokenCount: compressed.newTokenCount,
              compressionStatus: compressed.compressionStatus
            }
          },
          Date.now()
        );
      } else {
        ui2.addItem(
          {
            type: "error" /* ERROR */,
            text: "Failed to compress chat history."
          },
          Date.now()
        );
      }
    } catch (e2) {
      ui2.addItem(
        {
          type: "error" /* ERROR */,
          text: `Failed to compress chat history: ${e2 instanceof Error ? e2.message : String(e2)}`
        },
        Date.now()
      );
    } finally {
      ui2.setPendingItem(null);
    }
  }, "action")
};

// packages/cli/src/ui/commands/copyCommand.ts
init_esbuild_shims();
var copyCommand = {
  name: "copy",
  description: "Copy the last result or code snippet to clipboard",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, _args) => {
    const chat = await context2.services.config?.getGeminiClient()?.getChat();
    const history = chat?.getHistory();
    const lastAiMessage = history ? history.filter((item) => item.role === "model").pop() : void 0;
    if (!lastAiMessage) {
      return {
        type: "message",
        messageType: "info",
        content: "No output in history"
      };
    }
    const lastAiOutput = lastAiMessage.parts?.filter((part) => part.text).map((part) => part.text).join("");
    if (lastAiOutput) {
      try {
        await copyToClipboard(lastAiOutput);
        return {
          type: "message",
          messageType: "info",
          content: "Last output copied to the clipboard"
        };
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        console.debug(message);
        return {
          type: "message",
          messageType: "error",
          content: `Failed to copy to the clipboard. ${message}`
        };
      }
    } else {
      return {
        type: "message",
        messageType: "info",
        content: "Last AI output contains no text to copy."
      };
    }
  }, "action")
};

// packages/cli/src/ui/commands/corgiCommand.ts
init_esbuild_shims();
var corgiCommand = {
  name: "corgi",
  description: "Toggles corgi mode.",
  hidden: true,
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name((context2, _args) => {
    context2.ui.toggleCorgiMode();
  }, "action")
};

// packages/cli/src/ui/commands/docsCommand.ts
init_esbuild_shims();
init_open();
import process36 from "node:process";
var docsCommand = {
  name: "docs",
  description: "open full Qwen Code documentation in your browser",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2) => {
    const docsUrl = "https://qwenlm.github.io/qwen-code-docs/en";
    if (process36.env["SANDBOX"] && process36.env["SANDBOX"] !== "sandbox-exec") {
      context2.ui.addItem(
        {
          type: "info" /* INFO */,
          text: `Please open the following URL in your browser to view the documentation:
${docsUrl}`
        },
        Date.now()
      );
    } else {
      context2.ui.addItem(
        {
          type: "info" /* INFO */,
          text: `Opening documentation in your browser: ${docsUrl}`
        },
        Date.now()
      );
      await open_default(docsUrl);
    }
  }, "action")
};

// packages/cli/src/ui/commands/directoryCommand.tsx
init_esbuild_shims();
import * as os30 from "node:os";
import * as path83 from "node:path";
function expandHomeDir(p) {
  if (!p) {
    return "";
  }
  let expandedPath = p;
  if (p.toLowerCase().startsWith("%userprofile%")) {
    expandedPath = os30.homedir() + p.substring("%userprofile%".length);
  } else if (p === "~" || p.startsWith("~/")) {
    expandedPath = os30.homedir() + p.substring(1);
  }
  return path83.normalize(expandedPath);
}
__name(expandHomeDir, "expandHomeDir");
var directoryCommand = {
  name: "directory",
  altNames: ["dir"],
  description: "Manage workspace directories",
  kind: "built-in" /* BUILT_IN */,
  subCommands: [
    {
      name: "add",
      description: "Add directories to the workspace. Use comma to separate multiple paths",
      kind: "built-in" /* BUILT_IN */,
      action: /* @__PURE__ */ __name(async (context2, args) => {
        const {
          ui: { addItem },
          services: { config }
        } = context2;
        const [...rest] = args.split(" ");
        if (!config) {
          addItem(
            {
              type: "error" /* ERROR */,
              text: "Configuration is not available."
            },
            Date.now()
          );
          return;
        }
        const workspaceContext = config.getWorkspaceContext();
        const pathsToAdd = rest.join(" ").split(",").filter((p) => p);
        if (pathsToAdd.length === 0) {
          addItem(
            {
              type: "error" /* ERROR */,
              text: "Please provide at least one path to add."
            },
            Date.now()
          );
          return;
        }
        if (config.isRestrictiveSandbox()) {
          return {
            type: "message",
            messageType: "error",
            content: "The /directory add command is not supported in restrictive sandbox profiles. Please use --include-directories when starting the session instead."
          };
        }
        const added = [];
        const errors = [];
        for (const pathToAdd of pathsToAdd) {
          try {
            workspaceContext.addDirectory(expandHomeDir(pathToAdd.trim()));
            added.push(pathToAdd.trim());
          } catch (e2) {
            const error = e2;
            errors.push(`Error adding '${pathToAdd.trim()}': ${error.message}`);
          }
        }
        try {
          if (config.shouldLoadMemoryFromIncludeDirectories()) {
            const { memoryContent, fileCount } = await loadServerHierarchicalMemory(
              config.getWorkingDir(),
              [
                ...config.getWorkspaceContext().getDirectories(),
                ...pathsToAdd
              ],
              config.getDebugMode(),
              config.getFileService(),
              config.getExtensionContextFilePaths(),
              config.getFolderTrust(),
              context2.services.settings.merged.context?.importFormat || "tree",
              // Use setting or default to 'tree'
              config.getFileFilteringOptions(),
              context2.services.settings.merged.context?.discoveryMaxDirs
            );
            config.setUserMemory(memoryContent);
            config.setGeminiMdFileCount(fileCount);
            context2.ui.setGeminiMdFileCount(fileCount);
          }
          addItem(
            {
              type: "info" /* INFO */,
              text: `Successfully added GEMINI.md files from the following directories if there are:
- ${added.join("\n- ")}`
            },
            Date.now()
          );
        } catch (error) {
          errors.push(`Error refreshing memory: ${error.message}`);
        }
        if (added.length > 0) {
          const gemini = config.getGeminiClient();
          if (gemini) {
            await gemini.addDirectoryContext();
          }
          addItem(
            {
              type: "info" /* INFO */,
              text: `Successfully added directories:
- ${added.join("\n- ")}`
            },
            Date.now()
          );
        }
        if (errors.length > 0) {
          addItem(
            { type: "error" /* ERROR */, text: errors.join("\n") },
            Date.now()
          );
        }
        return;
      }, "action")
    },
    {
      name: "show",
      description: "Show all directories in the workspace",
      kind: "built-in" /* BUILT_IN */,
      action: /* @__PURE__ */ __name(async (context2) => {
        const {
          ui: { addItem },
          services: { config }
        } = context2;
        if (!config) {
          addItem(
            {
              type: "error" /* ERROR */,
              text: "Configuration is not available."
            },
            Date.now()
          );
          return;
        }
        const workspaceContext = config.getWorkspaceContext();
        const directories = workspaceContext.getDirectories();
        const directoryList = directories.map((dir) => `- ${dir}`).join("\n");
        addItem(
          {
            type: "info" /* INFO */,
            text: `Current workspace directories:
${directoryList}`
          },
          Date.now()
        );
      }, "action")
    }
  ]
};

// packages/cli/src/ui/commands/editorCommand.ts
init_esbuild_shims();
var editorCommand = {
  name: "editor",
  description: "set external editor preference",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(() => ({
    type: "dialog",
    dialog: "editor"
  }), "action")
};

// packages/cli/src/ui/commands/extensionsCommand.ts
init_esbuild_shims();
async function listAction(context2) {
  context2.ui.addItem(
    {
      type: "extensions_list" /* EXTENSIONS_LIST */
    },
    Date.now()
  );
}
__name(listAction, "listAction");
async function updateAction(context2, args) {
  const updateArgs = args.split(" ").filter((value) => value.length > 0);
  const all2 = updateArgs.length === 1 && updateArgs[0] === "--all";
  const names = all2 ? void 0 : updateArgs;
  let updateInfos = [];
  if (!all2 && names?.length === 0) {
    context2.ui.addItem(
      {
        type: "error" /* ERROR */,
        text: "Usage: /extensions update <extension-names>|--all"
      },
      Date.now()
    );
    return;
  }
  try {
    await checkForAllExtensionUpdates(
      context2.services.config.getExtensions(),
      context2.ui.dispatchExtensionStateUpdate
    );
    context2.ui.setPendingItem({
      type: "extensions_list" /* EXTENSIONS_LIST */
    });
    if (all2) {
      updateInfos = await updateAllUpdatableExtensions(
        context2.services.config.getWorkingDir(),
        // We don't have the ability to prompt for consent yet in this flow.
        (description) => requestConsentInteractive(
          description,
          context2.ui.addConfirmUpdateExtensionRequest
        ),
        context2.services.config.getExtensions(),
        context2.ui.extensionsUpdateState,
        context2.ui.dispatchExtensionStateUpdate
      );
    } else if (names?.length) {
      const workingDir = context2.services.config.getWorkingDir();
      const extensions = context2.services.config.getExtensions();
      for (const name3 of names) {
        const extension = extensions.find(
          (extension2) => extension2.name === name3
        );
        if (!extension) {
          context2.ui.addItem(
            {
              type: "error" /* ERROR */,
              text: `Extension ${name3} not found.`
            },
            Date.now()
          );
          continue;
        }
        const updateInfo = await updateExtension(
          extension,
          workingDir,
          (description) => requestConsentInteractive(
            description,
            context2.ui.addConfirmUpdateExtensionRequest
          ),
          context2.ui.extensionsUpdateState.get(extension.name)?.status ?? "unknown" /* UNKNOWN */,
          context2.ui.dispatchExtensionStateUpdate
        );
        if (updateInfo) updateInfos.push(updateInfo);
      }
    }
    if (updateInfos.length === 0) {
      context2.ui.addItem(
        {
          type: "info" /* INFO */,
          text: "No extensions to update."
        },
        Date.now()
      );
      return;
    }
  } catch (error) {
    context2.ui.addItem(
      {
        type: "error" /* ERROR */,
        text: getErrorMessage3(error)
      },
      Date.now()
    );
  } finally {
    context2.ui.addItem(
      {
        type: "extensions_list" /* EXTENSIONS_LIST */
      },
      Date.now()
    );
    context2.ui.setPendingItem(null);
  }
}
__name(updateAction, "updateAction");
var listExtensionsCommand = {
  name: "list",
  description: "List active extensions",
  kind: "built-in" /* BUILT_IN */,
  action: listAction
};
var updateExtensionsCommand = {
  name: "update",
  description: "Update extensions. Usage: update <extension-names>|--all",
  kind: "built-in" /* BUILT_IN */,
  action: updateAction,
  completion: /* @__PURE__ */ __name(async (context2, partialArg) => {
    const extensions = context2.services.config?.getExtensions() ?? [];
    const extensionNames = extensions.map((ext2) => ext2.name);
    const suggestions = extensionNames.filter(
      (name3) => name3.startsWith(partialArg)
    );
    if ("--all".startsWith(partialArg) || "all".startsWith(partialArg)) {
      suggestions.unshift("--all");
    }
    return suggestions;
  }, "completion")
};
var extensionsCommand2 = {
  name: "extensions",
  description: "Manage extensions",
  kind: "built-in" /* BUILT_IN */,
  subCommands: [listExtensionsCommand, updateExtensionsCommand],
  action: /* @__PURE__ */ __name((context2, args) => (
    // Default to list if no subcommand is provided
    listExtensionsCommand.action(context2, args)
  ), "action")
};

// packages/cli/src/ui/commands/helpCommand.ts
init_esbuild_shims();
var helpCommand = {
  name: "help",
  altNames: ["?"],
  kind: "built-in" /* BUILT_IN */,
  description: "for help on Qwen Code",
  action: /* @__PURE__ */ __name(async (context2) => {
    const helpItem = {
      type: "help" /* HELP */,
      timestamp: /* @__PURE__ */ new Date()
    };
    context2.ui.addItem(helpItem, Date.now());
  }, "action")
};

// packages/cli/src/ui/commands/ideCommand.ts
init_esbuild_shims();
import path84 from "node:path";
function getIdeStatusMessage(ideClient) {
  const connection = ideClient.getConnectionStatus();
  switch (connection.status) {
    case IDEConnectionStatus.Connected:
      return {
        messageType: "info",
        content: `\u{1F7E2} Connected to ${ideClient.getDetectedIdeDisplayName()}`
      };
    case IDEConnectionStatus.Connecting:
      return {
        messageType: "info",
        content: `\u{1F7E1} Connecting...`
      };
    default: {
      let content = `\u{1F534} Disconnected`;
      if (connection?.details) {
        content += `: ${connection.details}`;
      }
      return {
        messageType: "error",
        content
      };
    }
  }
}
__name(getIdeStatusMessage, "getIdeStatusMessage");
function formatFileList(openFiles) {
  const basenameCounts = /* @__PURE__ */ new Map();
  for (const file of openFiles) {
    const basename16 = path84.basename(file.path);
    basenameCounts.set(basename16, (basenameCounts.get(basename16) || 0) + 1);
  }
  const fileList = openFiles.map((file) => {
    const basename16 = path84.basename(file.path);
    const isDuplicate = (basenameCounts.get(basename16) || 0) > 1;
    const parentDir = path84.basename(path84.dirname(file.path));
    const displayName = isDuplicate ? `${basename16} (/${parentDir})` : basename16;
    return `  - ${displayName}${file.isActive ? " (active)" : ""}`;
  }).join("\n");
  const infoMessage = `
(Note: The file list is limited to a number of recently accessed files within your workspace and only includes local files on disk)`;
  return `

Open files:
${fileList}
${infoMessage}`;
}
__name(formatFileList, "formatFileList");
async function getIdeStatusMessageWithFiles(ideClient) {
  const connection = ideClient.getConnectionStatus();
  switch (connection.status) {
    case IDEConnectionStatus.Connected: {
      let content = `\u{1F7E2} Connected to ${ideClient.getDetectedIdeDisplayName()}`;
      const context2 = ideContextStore.get();
      const openFiles = context2?.workspaceState?.openFiles;
      if (openFiles && openFiles.length > 0) {
        content += formatFileList(openFiles);
      }
      return {
        messageType: "info",
        content
      };
    }
    case IDEConnectionStatus.Connecting:
      return {
        messageType: "info",
        content: `\u{1F7E1} Connecting...`
      };
    default: {
      let content = `\u{1F534} Disconnected`;
      if (connection?.details) {
        content += `: ${connection.details}`;
      }
      return {
        messageType: "error",
        content
      };
    }
  }
}
__name(getIdeStatusMessageWithFiles, "getIdeStatusMessageWithFiles");
async function setIdeModeAndSyncConnection(config, value) {
  config.setIdeMode(value);
  const ideClient = await IdeClient.getInstance();
  if (value) {
    await ideClient.connect();
    logIdeConnection(config, new IdeConnectionEvent(IdeConnectionType.SESSION));
  } else {
    await ideClient.disconnect();
  }
}
__name(setIdeModeAndSyncConnection, "setIdeModeAndSyncConnection");
var ideCommand = /* @__PURE__ */ __name(async () => {
  const ideClient = await IdeClient.getInstance();
  const currentIDE = ideClient.getCurrentIde();
  if (!currentIDE) {
    return {
      name: "ide",
      description: "manage IDE integration",
      kind: "built-in" /* BUILT_IN */,
      action: /* @__PURE__ */ __name(() => ({
        type: "message",
        messageType: "error",
        content: `IDE integration is not supported in your current environment. To use this feature, run Qwen Code in one of these supported IDEs: VS Code or VS Code forks.`
      }), "action")
    };
  }
  const ideSlashCommand = {
    name: "ide",
    description: "manage IDE integration",
    kind: "built-in" /* BUILT_IN */,
    subCommands: []
  };
  const statusCommand = {
    name: "status",
    description: "check status of IDE integration",
    kind: "built-in" /* BUILT_IN */,
    action: /* @__PURE__ */ __name(async () => {
      const { messageType, content } = await getIdeStatusMessageWithFiles(ideClient);
      return {
        type: "message",
        messageType,
        content
      };
    }, "action")
  };
  const installCommand2 = {
    name: "install",
    description: `install required IDE companion for ${ideClient.getDetectedIdeDisplayName()}`,
    kind: "built-in" /* BUILT_IN */,
    action: /* @__PURE__ */ __name(async (context2) => {
      const installer = getIdeInstaller(currentIDE);
      if (!installer) {
        context2.ui.addItem(
          {
            type: "error",
            text: `No installer is available for ${ideClient.getDetectedIdeDisplayName()}. Please install the '${QWEN_CODE_COMPANION_EXTENSION_NAME}' extension manually from the marketplace.`
          },
          Date.now()
        );
        return;
      }
      context2.ui.addItem(
        {
          type: "info",
          text: `Installing IDE companion...`
        },
        Date.now()
      );
      const result = await installer.install();
      context2.ui.addItem(
        {
          type: result.success ? "info" : "error",
          text: result.message
        },
        Date.now()
      );
      if (result.success) {
        context2.services.settings.setValue(
          "User" /* User */,
          "ide.enabled",
          true
        );
        for (let i = 0; i < 10; i++) {
          await setIdeModeAndSyncConnection(context2.services.config, true);
          if (ideClient.getConnectionStatus().status === IDEConnectionStatus.Connected) {
            break;
          }
          await new Promise((resolve24) => setTimeout(resolve24, 500));
        }
        const { messageType, content } = getIdeStatusMessage(ideClient);
        if (messageType === "error") {
          context2.ui.addItem(
            {
              type: messageType,
              text: `Failed to automatically enable IDE integration. To fix this, run the CLI in a new terminal window.`
            },
            Date.now()
          );
        } else {
          context2.ui.addItem(
            {
              type: messageType,
              text: content
            },
            Date.now()
          );
        }
      }
    }, "action")
  };
  const enableCommand2 = {
    name: "enable",
    description: "enable IDE integration",
    kind: "built-in" /* BUILT_IN */,
    action: /* @__PURE__ */ __name(async (context2) => {
      context2.services.settings.setValue(
        "User" /* User */,
        "ide.enabled",
        true
      );
      await setIdeModeAndSyncConnection(context2.services.config, true);
      const { messageType, content } = getIdeStatusMessage(ideClient);
      context2.ui.addItem(
        {
          type: messageType,
          text: content
        },
        Date.now()
      );
    }, "action")
  };
  const disableCommand2 = {
    name: "disable",
    description: "disable IDE integration",
    kind: "built-in" /* BUILT_IN */,
    action: /* @__PURE__ */ __name(async (context2) => {
      context2.services.settings.setValue(
        "User" /* User */,
        "ide.enabled",
        false
      );
      await setIdeModeAndSyncConnection(context2.services.config, false);
      const { messageType, content } = getIdeStatusMessage(ideClient);
      context2.ui.addItem(
        {
          type: messageType,
          text: content
        },
        Date.now()
      );
    }, "action")
  };
  const { status } = ideClient.getConnectionStatus();
  const isConnected = status === IDEConnectionStatus.Connected;
  if (isConnected) {
    ideSlashCommand.subCommands = [statusCommand, disableCommand2];
  } else {
    ideSlashCommand.subCommands = [
      enableCommand2,
      statusCommand,
      installCommand2
    ];
  }
  return ideSlashCommand;
}, "ideCommand");

// packages/cli/src/ui/commands/initCommand.ts
init_esbuild_shims();
import * as fs75 from "node:fs";
import * as path85 from "node:path";
var import_react107 = __toESM(require_react(), 1);
var initCommand = {
  name: "init",
  description: "Analyzes the project and creates a tailored QWEN.md file.",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, _args) => {
    if (!context2.services.config) {
      return {
        type: "message",
        messageType: "error",
        content: "Configuration not available."
      };
    }
    const targetDir = context2.services.config.getTargetDir();
    const contextFileName = getCurrentGeminiMdFilename();
    const contextFilePath = path85.join(targetDir, contextFileName);
    try {
      if (fs75.existsSync(contextFilePath)) {
        try {
          const existing = fs75.readFileSync(contextFilePath, "utf8");
          if (existing && existing.trim().length > 0) {
            if (!context2.overwriteConfirmed) {
              return {
                type: "confirm_action",
                // TODO: Move to .tsx file to use JSX syntax instead of React.createElement
                // For now, using React.createElement to maintain .ts compatibility for PR review
                prompt: import_react107.default.createElement(
                  Text,
                  null,
                  `A ${contextFileName} file already exists in this directory. Do you want to regenerate it?`
                ),
                originalInvocation: {
                  raw: context2.invocation?.raw || "/init"
                }
              };
            }
          }
        } catch {
        }
      }
      try {
        fs75.writeFileSync(contextFilePath, "", "utf8");
        context2.ui.addItem(
          {
            type: "info",
            text: `Empty ${contextFileName} created. Now analyzing the project to populate it.`
          },
          Date.now()
        );
      } catch (err) {
        return {
          type: "message",
          messageType: "error",
          content: `Failed to create ${contextFileName}: ${err instanceof Error ? err.message : String(err)}`
        };
      }
    } catch (error) {
      return {
        type: "message",
        messageType: "error",
        content: `Unexpected error preparing ${contextFileName}: ${error instanceof Error ? error.message : String(error)}`
      };
    }
    return {
      type: "submit_prompt",
      content: `
You are Qwen Code, an interactive CLI agent. Analyze the current directory and generate a comprehensive ${contextFileName} file to be used as instructional context for future interactions.

**Analysis Process:**

1.  **Initial Exploration:**
    *   Start by listing the files and directories to get a high-level overview of the structure.
    *   Read the README file (e.g., \`README.md\`, \`README.txt\`) if it exists. This is often the best place to start.

2.  **Iterative Deep Dive (up to 10 files):**
    *   Based on your initial findings, select a few files that seem most important (e.g., configuration files, main source files, documentation).
    *   Read them. As you learn more, refine your understanding and decide which files to read next. You don't need to decide all 10 files at once. Let your discoveries guide your exploration.

3.  **Identify Project Type:**
    *   **Code Project:** Look for clues like \`package.json\`, \`requirements.txt\`, \`pom.xml\`, \`go.mod\`, \`Cargo.toml\`, \`build.gradle\`, or a \`src\` directory. If you find them, this is likely a software project.
    *   **Non-Code Project:** If you don't find code-related files, this might be a directory for documentation, research papers, notes, or something else.

**${contextFileName} Content Generation:**

**For a Code Project:**

*   **Project Overview:** Write a clear and concise summary of the project's purpose, main technologies, and architecture.
*   **Building and Running:** Document the key commands for building, running, and testing the project. Infer these from the files you've read (e.g., \`scripts\` in \`package.json\`, \`Makefile\`, etc.). If you can't find explicit commands, provide a placeholder with a TODO.
*   **Development Conventions:** Describe any coding styles, testing practices, or contribution guidelines you can infer from the codebase.

**For a Non-Code Project:**

*   **Directory Overview:** Describe the purpose and contents of the directory. What is it for? What kind of information does it hold?
*   **Key Files:** List the most important files and briefly explain what they contain.
*   **Usage:** Explain how the contents of this directory are intended to be used.

**Final Output:**

Write the complete content to the \`${contextFileName}\` file. The output must be well-formatted Markdown.
`
    };
  }, "action")
};

// packages/cli/src/ui/commands/mcpCommand.ts
init_esbuild_shims();
var authCommand2 = {
  name: "auth",
  description: "Authenticate with an OAuth-enabled MCP server",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, args) => {
    const serverName = args.trim();
    const { config } = context2.services;
    if (!config) {
      return {
        type: "message",
        messageType: "error",
        content: "Config not loaded."
      };
    }
    const mcpServers = config.getMcpServers() || {};
    if (!serverName) {
      const oauthServers = Object.entries(mcpServers).filter(([_, server2]) => server2.oauth?.enabled).map(([name3, _]) => name3);
      if (oauthServers.length === 0) {
        return {
          type: "message",
          messageType: "info",
          content: "No MCP servers configured with OAuth authentication."
        };
      }
      return {
        type: "message",
        messageType: "info",
        content: `MCP servers with OAuth authentication:
${oauthServers.map((s2) => `  - ${s2}`).join("\n")}

Use /mcp auth <server-name> to authenticate.`
      };
    }
    const server = mcpServers[serverName];
    if (!server) {
      return {
        type: "message",
        messageType: "error",
        content: `MCP server '${serverName}' not found.`
      };
    }
    const displayListener = /* @__PURE__ */ __name((message) => {
      context2.ui.addItem({ type: "info", text: message }, Date.now());
    }, "displayListener");
    appEvents.on("oauth-display-message" /* OauthDisplayMessage */, displayListener);
    try {
      context2.ui.addItem(
        {
          type: "info",
          text: `Starting OAuth authentication for MCP server '${serverName}'...`
        },
        Date.now()
      );
      let oauthConfig = server.oauth;
      if (!oauthConfig) {
        oauthConfig = { enabled: false };
      }
      const mcpServerUrl = server.httpUrl || server.url;
      const authProvider = new MCPOAuthProvider(new MCPOAuthTokenStorage());
      await authProvider.authenticate(
        serverName,
        oauthConfig,
        mcpServerUrl,
        appEvents
      );
      context2.ui.addItem(
        {
          type: "info",
          text: `\u2705 Successfully authenticated with MCP server '${serverName}'!`
        },
        Date.now()
      );
      const toolRegistry = config.getToolRegistry();
      if (toolRegistry) {
        context2.ui.addItem(
          {
            type: "info",
            text: `Re-discovering tools from '${serverName}'...`
          },
          Date.now()
        );
        await toolRegistry.discoverToolsForServer(serverName);
      }
      const geminiClient = config.getGeminiClient();
      if (geminiClient) {
        await geminiClient.setTools();
      }
      context2.ui.reloadCommands();
      return {
        type: "message",
        messageType: "info",
        content: `Successfully authenticated and refreshed tools for '${serverName}'.`
      };
    } catch (error) {
      return {
        type: "message",
        messageType: "error",
        content: `Failed to authenticate with MCP server '${serverName}': ${getErrorMessage(error)}`
      };
    } finally {
      appEvents.removeListener("oauth-display-message" /* OauthDisplayMessage */, displayListener);
    }
  }, "action"),
  completion: /* @__PURE__ */ __name(async (context2, partialArg) => {
    const { config } = context2.services;
    if (!config) return [];
    const mcpServers = config.getMcpServers() || {};
    return Object.keys(mcpServers).filter(
      (name3) => name3.startsWith(partialArg)
    );
  }, "completion")
};
var listCommand4 = {
  name: "list",
  description: "List configured MCP servers and tools",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, args) => {
    const { config } = context2.services;
    if (!config) {
      return {
        type: "message",
        messageType: "error",
        content: "Config not loaded."
      };
    }
    const toolRegistry = config.getToolRegistry();
    if (!toolRegistry) {
      return {
        type: "message",
        messageType: "error",
        content: "Could not retrieve tool registry."
      };
    }
    const lowerCaseArgs = args.toLowerCase().split(/\s+/).filter(Boolean);
    const hasDesc = lowerCaseArgs.includes("desc") || lowerCaseArgs.includes("descriptions");
    const hasNodesc = lowerCaseArgs.includes("nodesc") || lowerCaseArgs.includes("nodescriptions");
    const showSchema = lowerCaseArgs.includes("schema");
    const showDescriptions = !hasNodesc && (hasDesc || showSchema);
    const showTips = lowerCaseArgs.length === 0;
    const mcpServers = config.getMcpServers() || {};
    const serverNames = Object.keys(mcpServers);
    const blockedMcpServers = config.getBlockedMcpServers() || [];
    const connectingServers = serverNames.filter(
      (name3) => getMCPServerStatus(name3) === MCPServerStatus.CONNECTING
    );
    const discoveryState = getMCPDiscoveryState();
    const discoveryInProgress = discoveryState === MCPDiscoveryState.IN_PROGRESS || connectingServers.length > 0;
    const allTools = toolRegistry.getAllTools();
    const mcpTools = allTools.filter(
      (tool) => tool instanceof DiscoveredMCPTool
    );
    const promptRegistry = await config.getPromptRegistry();
    const mcpPrompts = promptRegistry.getAllPrompts().filter(
      (prompt) => "serverName" in prompt && serverNames.includes(prompt.serverName)
    );
    const authStatus = {};
    const tokenStorage = new MCPOAuthTokenStorage();
    for (const serverName of serverNames) {
      const server = mcpServers[serverName];
      if (server.oauth?.enabled) {
        const creds = await tokenStorage.getCredentials(serverName);
        if (creds) {
          if (creds.token.expiresAt && creds.token.expiresAt < Date.now()) {
            authStatus[serverName] = "expired";
          } else {
            authStatus[serverName] = "authenticated";
          }
        } else {
          authStatus[serverName] = "unauthenticated";
        }
      } else {
        authStatus[serverName] = "not-configured";
      }
    }
    const mcpStatusItem = {
      type: "mcp_status" /* MCP_STATUS */,
      servers: mcpServers,
      tools: mcpTools.map((tool) => ({
        serverName: tool.serverName,
        name: tool.name,
        description: tool.description,
        schema: tool.schema
      })),
      prompts: mcpPrompts.map((prompt) => ({
        serverName: prompt.serverName,
        name: prompt.name,
        description: prompt.description
      })),
      authStatus,
      blockedServers: blockedMcpServers,
      discoveryInProgress,
      connectingServers,
      showDescriptions,
      showSchema,
      showTips
    };
    context2.ui.addItem(mcpStatusItem, Date.now());
  }, "action")
};
var refreshCommand = {
  name: "refresh",
  description: "Restarts MCP servers.",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2) => {
    const { config } = context2.services;
    if (!config) {
      return {
        type: "message",
        messageType: "error",
        content: "Config not loaded."
      };
    }
    const toolRegistry = config.getToolRegistry();
    if (!toolRegistry) {
      return {
        type: "message",
        messageType: "error",
        content: "Could not retrieve tool registry."
      };
    }
    context2.ui.addItem(
      {
        type: "info",
        text: "Restarting MCP servers..."
      },
      Date.now()
    );
    await toolRegistry.restartMcpServers();
    const geminiClient = config.getGeminiClient();
    if (geminiClient) {
      await geminiClient.setTools();
    }
    context2.ui.reloadCommands();
    return listCommand4.action(context2, "");
  }, "action")
};
var mcpCommand2 = {
  name: "mcp",
  description: "list configured MCP servers and tools, or authenticate with OAuth-enabled servers",
  kind: "built-in" /* BUILT_IN */,
  subCommands: [listCommand4, authCommand2, refreshCommand],
  // Default action when no subcommand is provided
  action: /* @__PURE__ */ __name(async (context2, args) => (
    // If no subcommand, run the list command
    listCommand4.action(context2, args)
  ), "action")
};

// packages/cli/src/ui/commands/memoryCommand.ts
init_esbuild_shims();
import path86 from "node:path";
import os31 from "os";
import fs76 from "fs/promises";
var memoryCommand = {
  name: "memory",
  description: "Commands for interacting with memory.",
  kind: "built-in" /* BUILT_IN */,
  subCommands: [
    {
      name: "show",
      description: "Show the current memory contents.",
      kind: "built-in" /* BUILT_IN */,
      action: /* @__PURE__ */ __name(async (context2) => {
        const memoryContent = context2.services.config?.getUserMemory() || "";
        const fileCount = context2.services.config?.getGeminiMdFileCount() || 0;
        const messageContent = memoryContent.length > 0 ? `Current memory content from ${fileCount} file(s):

---
${memoryContent}
---` : "Memory is currently empty.";
        context2.ui.addItem(
          {
            type: "info" /* INFO */,
            text: messageContent
          },
          Date.now()
        );
      }, "action"),
      subCommands: [
        {
          name: "--project",
          description: "Show project-level memory contents.",
          kind: "built-in" /* BUILT_IN */,
          action: /* @__PURE__ */ __name(async (context2) => {
            try {
              const projectMemoryPath = path86.join(process.cwd(), "QWEN.md");
              const memoryContent = await fs76.readFile(
                projectMemoryPath,
                "utf-8"
              );
              const messageContent = memoryContent.trim().length > 0 ? `Project memory content from ${projectMemoryPath}:

---
${memoryContent}
---` : "Project memory is currently empty.";
              context2.ui.addItem(
                {
                  type: "info" /* INFO */,
                  text: messageContent
                },
                Date.now()
              );
            } catch (_error) {
              context2.ui.addItem(
                {
                  type: "info" /* INFO */,
                  text: "Project memory file not found or is currently empty."
                },
                Date.now()
              );
            }
          }, "action")
        },
        {
          name: "--global",
          description: "Show global memory contents.",
          kind: "built-in" /* BUILT_IN */,
          action: /* @__PURE__ */ __name(async (context2) => {
            try {
              const globalMemoryPath = path86.join(
                os31.homedir(),
                QWEN_DIR5,
                "QWEN.md"
              );
              const globalMemoryContent = await fs76.readFile(
                globalMemoryPath,
                "utf-8"
              );
              const messageContent = globalMemoryContent.trim().length > 0 ? `Global memory content:

---
${globalMemoryContent}
---` : "Global memory is currently empty.";
              context2.ui.addItem(
                {
                  type: "info" /* INFO */,
                  text: messageContent
                },
                Date.now()
              );
            } catch (_error) {
              context2.ui.addItem(
                {
                  type: "info" /* INFO */,
                  text: "Global memory file not found or is currently empty."
                },
                Date.now()
              );
            }
          }, "action")
        }
      ]
    },
    {
      name: "add",
      description: "Add content to the memory. Use --global for global memory or --project for project memory.",
      kind: "built-in" /* BUILT_IN */,
      action: /* @__PURE__ */ __name((context2, args) => {
        if (!args || args.trim() === "") {
          return {
            type: "message",
            messageType: "error",
            content: "Usage: /memory add [--global|--project] <text to remember>"
          };
        }
        const trimmedArgs = args.trim();
        let scope;
        let fact;
        if (trimmedArgs.startsWith("--global ")) {
          scope = "global";
          fact = trimmedArgs.substring("--global ".length).trim();
        } else if (trimmedArgs.startsWith("--project ")) {
          scope = "project";
          fact = trimmedArgs.substring("--project ".length).trim();
        } else if (trimmedArgs === "--global" || trimmedArgs === "--project") {
          return {
            type: "message",
            messageType: "error",
            content: "Usage: /memory add [--global|--project] <text to remember>"
          };
        } else {
          fact = trimmedArgs;
        }
        if (!fact || fact.trim() === "") {
          return {
            type: "message",
            messageType: "error",
            content: "Usage: /memory add [--global|--project] <text to remember>"
          };
        }
        const scopeText = scope ? `(${scope})` : "";
        context2.ui.addItem(
          {
            type: "info" /* INFO */,
            text: `Attempting to save to memory ${scopeText}: "${fact}"`
          },
          Date.now()
        );
        return {
          type: "tool",
          toolName: "save_memory",
          toolArgs: scope ? { fact, scope } : { fact }
        };
      }, "action"),
      subCommands: [
        {
          name: "--project",
          description: "Add content to project-level memory.",
          kind: "built-in" /* BUILT_IN */,
          action: /* @__PURE__ */ __name((context2, args) => {
            if (!args || args.trim() === "") {
              return {
                type: "message",
                messageType: "error",
                content: "Usage: /memory add --project <text to remember>"
              };
            }
            context2.ui.addItem(
              {
                type: "info" /* INFO */,
                text: `Attempting to save to project memory: "${args.trim()}"`
              },
              Date.now()
            );
            return {
              type: "tool",
              toolName: "save_memory",
              toolArgs: { fact: args.trim(), scope: "project" }
            };
          }, "action")
        },
        {
          name: "--global",
          description: "Add content to global memory.",
          kind: "built-in" /* BUILT_IN */,
          action: /* @__PURE__ */ __name((context2, args) => {
            if (!args || args.trim() === "") {
              return {
                type: "message",
                messageType: "error",
                content: "Usage: /memory add --global <text to remember>"
              };
            }
            context2.ui.addItem(
              {
                type: "info" /* INFO */,
                text: `Attempting to save to global memory: "${args.trim()}"`
              },
              Date.now()
            );
            return {
              type: "tool",
              toolName: "save_memory",
              toolArgs: { fact: args.trim(), scope: "global" }
            };
          }, "action")
        }
      ]
    },
    {
      name: "refresh",
      description: "Refresh the memory from the source.",
      kind: "built-in" /* BUILT_IN */,
      action: /* @__PURE__ */ __name(async (context2) => {
        context2.ui.addItem(
          {
            type: "info" /* INFO */,
            text: "Refreshing memory from source files..."
          },
          Date.now()
        );
        try {
          const config = context2.services.config;
          if (config) {
            const { memoryContent, fileCount } = await loadServerHierarchicalMemory(
              config.getWorkingDir(),
              config.shouldLoadMemoryFromIncludeDirectories() ? config.getWorkspaceContext().getDirectories() : [],
              config.getDebugMode(),
              config.getFileService(),
              config.getExtensionContextFilePaths(),
              config.getFolderTrust(),
              context2.services.settings.merged.context?.importFormat || "tree",
              // Use setting or default to 'tree'
              config.getFileFilteringOptions(),
              context2.services.settings.merged.context?.discoveryMaxDirs
            );
            config.setUserMemory(memoryContent);
            config.setGeminiMdFileCount(fileCount);
            const successMessage = memoryContent.length > 0 ? `Memory refreshed successfully. Loaded ${memoryContent.length} characters from ${fileCount} file(s).` : "Memory refreshed successfully. No memory content found.";
            context2.ui.addItem(
              {
                type: "info" /* INFO */,
                text: successMessage
              },
              Date.now()
            );
          }
        } catch (error) {
          const errorMessage = getErrorMessage(error);
          context2.ui.addItem(
            {
              type: "error" /* ERROR */,
              text: `Error refreshing memory: ${errorMessage}`
            },
            Date.now()
          );
        }
      }, "action")
    }
  ]
};

// packages/cli/src/ui/commands/modelCommand.ts
init_esbuild_shims();
var modelCommand = {
  name: "model",
  description: "Switch the model for this session",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2) => {
    const { services } = context2;
    const { config } = services;
    if (!config) {
      return {
        type: "message",
        messageType: "error",
        content: "Configuration not available."
      };
    }
    const contentGeneratorConfig = config.getContentGeneratorConfig();
    if (!contentGeneratorConfig) {
      return {
        type: "message",
        messageType: "error",
        content: "Content generator configuration not available."
      };
    }
    const authType = contentGeneratorConfig.authType;
    if (!authType) {
      return {
        type: "message",
        messageType: "error",
        content: "Authentication type not available."
      };
    }
    const availableModels = getAvailableModelsForAuthType(authType);
    if (availableModels.length === 0) {
      return {
        type: "message",
        messageType: "error",
        content: `No models available for the current authentication type (${authType}).`
      };
    }
    return {
      type: "dialog",
      dialog: "model"
    };
  }, "action")
};

// packages/cli/src/ui/commands/permissionsCommand.ts
init_esbuild_shims();
var permissionsCommand = {
  name: "permissions",
  description: "Manage folder trust settings",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(() => ({
    type: "dialog",
    dialog: "permissions"
  }), "action")
};

// packages/cli/src/ui/commands/quitCommand.ts
init_esbuild_shims();
var quitConfirmCommand = {
  name: "quit-confirm",
  description: "Show quit confirmation dialog",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name((context2) => {
    const now = Date.now();
    const { sessionStartTime } = context2.session.stats;
    const wallDuration = now - sessionStartTime.getTime();
    return {
      type: "quit_confirmation",
      messages: [
        {
          type: "user",
          text: `/quit-confirm`,
          id: now - 1
        },
        {
          type: "quit_confirmation",
          duration: formatDuration(wallDuration),
          id: now
        }
      ]
    };
  }, "action")
};
var quitCommand = {
  name: "quit",
  altNames: ["exit"],
  description: "exit the cli",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name((context2) => {
    const now = Date.now();
    const { sessionStartTime } = context2.session.stats;
    const wallDuration = now - sessionStartTime.getTime();
    return {
      type: "quit",
      messages: [
        {
          type: "user",
          text: `/quit`,
          // Keep it consistent, even if /exit was used
          id: now - 1
        },
        {
          type: "quit",
          duration: formatDuration(wallDuration),
          id: now
        }
      ]
    };
  }, "action")
};

// packages/cli/src/ui/commands/restoreCommand.ts
init_esbuild_shims();
import * as fs77 from "node:fs/promises";
import path87 from "node:path";
async function restoreAction(context2, args) {
  const { services, ui: ui2 } = context2;
  const { config, git: gitService } = services;
  const { addItem, loadHistory } = ui2;
  const checkpointDir = config?.storage.getProjectTempCheckpointsDir();
  if (!checkpointDir) {
    return {
      type: "message",
      messageType: "error",
      content: "Could not determine the .gemini directory path."
    };
  }
  try {
    await fs77.mkdir(checkpointDir, { recursive: true });
    const files = await fs77.readdir(checkpointDir);
    const jsonFiles = files.filter((file) => file.endsWith(".json"));
    if (!args) {
      if (jsonFiles.length === 0) {
        return {
          type: "message",
          messageType: "info",
          content: "No restorable tool calls found."
        };
      }
      const truncatedFiles = jsonFiles.map((file) => {
        const components = file.split(".");
        if (components.length <= 1) {
          return file;
        }
        components.pop();
        return components.join(".");
      });
      const fileList = truncatedFiles.join("\n");
      return {
        type: "message",
        messageType: "info",
        content: `Available tool calls to restore:

${fileList}`
      };
    }
    const selectedFile = args.endsWith(".json") ? args : `${args}.json`;
    if (!jsonFiles.includes(selectedFile)) {
      return {
        type: "message",
        messageType: "error",
        content: `File not found: ${selectedFile}`
      };
    }
    const filePath = path87.join(checkpointDir, selectedFile);
    const data = await fs77.readFile(filePath, "utf-8");
    const toolCallData = JSON.parse(data);
    if (toolCallData.history) {
      if (!loadHistory) {
        return {
          type: "message",
          messageType: "error",
          content: "loadHistory function is not available."
        };
      }
      loadHistory(toolCallData.history);
    }
    if (toolCallData.clientHistory) {
      await config?.getGeminiClient()?.setHistory(toolCallData.clientHistory);
    }
    if (toolCallData.commitHash) {
      await gitService?.restoreProjectFromSnapshot(toolCallData.commitHash);
      addItem(
        {
          type: "info",
          text: "Restored project to the state before the tool call."
        },
        Date.now()
      );
    }
    return {
      type: "tool",
      toolName: toolCallData.toolCall.name,
      toolArgs: toolCallData.toolCall.args
    };
  } catch (error) {
    return {
      type: "message",
      messageType: "error",
      content: `Could not read restorable tool calls. This is the error: ${error}`
    };
  }
}
__name(restoreAction, "restoreAction");
async function completion2(context2, _partialArg) {
  const { services } = context2;
  const { config } = services;
  const checkpointDir = config?.storage.getProjectTempCheckpointsDir();
  if (!checkpointDir) {
    return [];
  }
  try {
    const files = await fs77.readdir(checkpointDir);
    return files.filter((file) => file.endsWith(".json")).map((file) => file.replace(".json", ""));
  } catch (_err) {
    return [];
  }
}
__name(completion2, "completion");
var restoreCommand = /* @__PURE__ */ __name((config) => {
  if (!config?.getCheckpointingEnabled()) {
    return null;
  }
  return {
    name: "restore",
    description: "Restore a tool call. This will reset the conversation and file history to the state it was in when the tool call was suggested",
    kind: "built-in" /* BUILT_IN */,
    action: restoreAction,
    completion: completion2
  };
}, "restoreCommand");

// packages/cli/src/ui/commands/settingsCommand.ts
init_esbuild_shims();
var settingsCommand = {
  name: "settings",
  description: "View and edit Qwen Code settings",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name((_context, _args) => ({
    type: "dialog",
    dialog: "settings"
  }), "action")
};

// packages/cli/src/ui/commands/statsCommand.ts
init_esbuild_shims();
var statsCommand = {
  name: "stats",
  altNames: ["usage"],
  description: "check session stats. Usage: /stats [model|tools]",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name((context2) => {
    const now = /* @__PURE__ */ new Date();
    const { sessionStartTime } = context2.session.stats;
    if (!sessionStartTime) {
      context2.ui.addItem(
        {
          type: "error" /* ERROR */,
          text: "Session start time is unavailable, cannot calculate stats."
        },
        Date.now()
      );
      return;
    }
    const wallDuration = now.getTime() - sessionStartTime.getTime();
    const statsItem = {
      type: "stats" /* STATS */,
      duration: formatDuration(wallDuration)
    };
    context2.ui.addItem(statsItem, Date.now());
  }, "action"),
  subCommands: [
    {
      name: "model",
      description: "Show model-specific usage statistics.",
      kind: "built-in" /* BUILT_IN */,
      action: /* @__PURE__ */ __name((context2) => {
        context2.ui.addItem(
          {
            type: "model_stats" /* MODEL_STATS */
          },
          Date.now()
        );
      }, "action")
    },
    {
      name: "tools",
      description: "Show tool-specific usage statistics.",
      kind: "built-in" /* BUILT_IN */,
      action: /* @__PURE__ */ __name((context2) => {
        context2.ui.addItem(
          {
            type: "tool_stats" /* TOOL_STATS */
          },
          Date.now()
        );
      }, "action")
    }
  ]
};

// packages/cli/src/ui/commands/summaryCommand.ts
init_esbuild_shims();
import * as fsPromises6 from "fs/promises";
import path88 from "path";
var summaryCommand = {
  name: "summary",
  description: "Generate a project summary and save it to .qwen/PROJECT_SUMMARY.md",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2) => {
    const { config } = context2.services;
    const { ui: ui2 } = context2;
    if (!config) {
      return {
        type: "message",
        messageType: "error",
        content: "Config not loaded."
      };
    }
    const geminiClient = config.getGeminiClient();
    if (!geminiClient) {
      return {
        type: "message",
        messageType: "error",
        content: "No chat client available to generate summary."
      };
    }
    if (ui2.pendingItem) {
      ui2.addItem(
        {
          type: "error",
          text: "Already generating summary, wait for previous request to complete"
        },
        Date.now()
      );
      return {
        type: "message",
        messageType: "error",
        content: "Already generating summary, wait for previous request to complete"
      };
    }
    try {
      const chat = geminiClient.getChat();
      const history = chat.getHistory();
      if (history.length <= 2) {
        return {
          type: "message",
          messageType: "info",
          content: "No conversation found to summarize."
        };
      }
      const pendingMessage = {
        type: "summary",
        summary: {
          isPending: true,
          stage: "generating"
        }
      };
      ui2.setPendingItem(pendingMessage);
      const conversationContext = history.map((message) => ({
        role: message.role,
        parts: message.parts
      }));
      const response = await geminiClient.generateContent(
        [
          ...conversationContext,
          {
            role: "user",
            parts: [
              {
                text: getProjectSummaryPrompt()
              }
            ]
          }
        ],
        {},
        new AbortController().signal,
        config.getModel()
      );
      const parts = response.candidates?.[0]?.content?.parts;
      const markdownSummary = parts?.map((part) => part.text).filter((text) => typeof text === "string").join("") || "";
      if (!markdownSummary) {
        throw new Error(
          "Failed to generate summary - no text content received from LLM response"
        );
      }
      ui2.setPendingItem({
        type: "summary",
        summary: {
          isPending: true,
          stage: "saving"
        }
      });
      const projectRoot = config.getProjectRoot();
      const qwenDir = path88.join(projectRoot, ".qwen");
      try {
        await fsPromises6.mkdir(qwenDir, { recursive: true });
      } catch (_err) {
      }
      const summaryPath = path88.join(qwenDir, "PROJECT_SUMMARY.md");
      const summaryContent = `${markdownSummary}

---

## Summary Metadata
**Update time**: ${(/* @__PURE__ */ new Date()).toISOString()} 
`;
      await fsPromises6.writeFile(summaryPath, summaryContent, "utf8");
      ui2.setPendingItem(null);
      const completedSummaryItem = {
        type: "summary",
        summary: {
          isPending: false,
          stage: "completed",
          filePath: ".qwen/PROJECT_SUMMARY.md"
        }
      };
      ui2.addItem(completedSummaryItem, Date.now());
      return {
        type: "message",
        messageType: "info",
        content: ""
        // Empty content since we show the message in UI component
      };
    } catch (error) {
      ui2.setPendingItem(null);
      ui2.addItem(
        {
          type: "error",
          text: `\u274C Failed to generate project context summary: ${error instanceof Error ? error.message : String(error)}`
        },
        Date.now()
      );
      return {
        type: "message",
        messageType: "error",
        content: `Failed to generate project context summary: ${error instanceof Error ? error.message : String(error)}`
      };
    }
  }, "action")
};

// packages/cli/src/ui/commands/terminalSetupCommand.ts
init_esbuild_shims();

// packages/cli/src/ui/utils/terminalSetup.ts
init_esbuild_shims();
import { promises as fs78 } from "node:fs";
import * as os32 from "node:os";
import * as path89 from "node:path";
import { exec as exec3 } from "node:child_process";
import { promisify as promisify7 } from "node:util";

// packages/cli/src/ui/utils/kittyProtocolDetector.ts
init_esbuild_shims();
var detectionComplete = false;
var protocolSupported = false;
var protocolEnabled = false;
async function detectAndEnableKittyProtocol() {
  if (detectionComplete) {
    return protocolSupported;
  }
  return new Promise((resolve24) => {
    if (!process.stdin.isTTY || !process.stdout.isTTY) {
      detectionComplete = true;
      resolve24(false);
      return;
    }
    const originalRawMode = process.stdin.isRaw;
    if (!originalRawMode) {
      process.stdin.setRawMode(true);
    }
    let responseBuffer = "";
    let progressiveEnhancementReceived = false;
    let timeoutId;
    const onTimeout = /* @__PURE__ */ __name(() => {
      timeoutId = void 0;
      process.stdin.removeListener("data", handleData);
      if (!originalRawMode) {
        process.stdin.setRawMode(false);
      }
      detectionComplete = true;
      resolve24(false);
    }, "onTimeout");
    const handleData = /* @__PURE__ */ __name((data) => {
      if (timeoutId === void 0) {
        return;
      }
      responseBuffer += data.toString();
      if (responseBuffer.includes("\x1B[?") && responseBuffer.includes("u")) {
        progressiveEnhancementReceived = true;
        clearTimeout(timeoutId);
        timeoutId = setTimeout(onTimeout, 1e3);
      }
      if (responseBuffer.includes("\x1B[?") && responseBuffer.includes("c")) {
        clearTimeout(timeoutId);
        timeoutId = void 0;
        process.stdin.removeListener("data", handleData);
        if (!originalRawMode) {
          process.stdin.setRawMode(false);
        }
        if (progressiveEnhancementReceived) {
          process.stdout.write("\x1B[>1u");
          protocolSupported = true;
          protocolEnabled = true;
          process.on("exit", disableProtocol);
          process.on("SIGTERM", disableProtocol);
        }
        detectionComplete = true;
        resolve24(protocolSupported);
      }
    }, "handleData");
    process.stdin.on("data", handleData);
    process.stdout.write("\x1B[?u");
    process.stdout.write("\x1B[c");
    timeoutId = setTimeout(onTimeout, 200);
  });
}
__name(detectAndEnableKittyProtocol, "detectAndEnableKittyProtocol");
function disableProtocol() {
  if (protocolEnabled) {
    process.stdout.write("\x1B[<u");
    protocolEnabled = false;
  }
}
__name(disableProtocol, "disableProtocol");
function isKittyProtocolEnabled() {
  return protocolEnabled;
}
__name(isKittyProtocolEnabled, "isKittyProtocolEnabled");
function isKittyProtocolSupported() {
  return protocolSupported;
}
__name(isKittyProtocolSupported, "isKittyProtocolSupported");

// packages/cli/src/ui/utils/terminalSetup.ts
var execAsync2 = promisify7(exec3);
function stripJsonComments3(content) {
  return content.replace(/^\s*\/\/.*$/gm, "");
}
__name(stripJsonComments3, "stripJsonComments");
async function detectTerminal() {
  const termProgram = process.env["TERM_PROGRAM"];
  if (process.env["CURSOR_TRACE_ID"] || process.env["VSCODE_GIT_ASKPASS_MAIN"]?.toLowerCase().includes("cursor")) {
    return "cursor";
  }
  if (process.env["VSCODE_GIT_ASKPASS_MAIN"]?.toLowerCase().includes("windsurf")) {
    return "windsurf";
  }
  if (process.env["TERM_PRODUCT"]?.toLowerCase().includes("trae")) {
    return "trae";
  }
  if (termProgram === "vscode" || process.env["VSCODE_GIT_IPC_HANDLE"]) {
    return "vscode";
  }
  if (os32.platform() !== "win32") {
    try {
      const { stdout } = await execAsync2("ps -o comm= -p $PPID");
      const parentName = stdout.trim();
      if (parentName.includes("windsurf") || parentName.includes("Windsurf"))
        return "windsurf";
      if (parentName.includes("cursor") || parentName.includes("Cursor"))
        return "cursor";
      if (parentName.includes("code") || parentName.includes("Code"))
        return "vscode";
      if (parentName.includes("trae") || parentName.includes("Trae"))
        return "trae";
    } catch (error) {
      console.debug("Parent process detection failed:", error);
    }
  }
  return null;
}
__name(detectTerminal, "detectTerminal");
async function backupFile(filePath) {
  try {
    const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
    const backupPath = `${filePath}.backup.${timestamp}`;
    await fs78.copyFile(filePath, backupPath);
  } catch (error) {
    console.warn(`Failed to create backup of ${filePath}:`, error);
  }
}
__name(backupFile, "backupFile");
function getVSCodeStyleConfigDir(appName) {
  const platform15 = os32.platform();
  if (platform15 === "darwin") {
    return path89.join(
      os32.homedir(),
      "Library",
      "Application Support",
      appName,
      "User"
    );
  } else if (platform15 === "win32") {
    if (!process.env["APPDATA"]) {
      return null;
    }
    return path89.join(process.env["APPDATA"], appName, "User");
  } else {
    return path89.join(os32.homedir(), ".config", appName, "User");
  }
}
__name(getVSCodeStyleConfigDir, "getVSCodeStyleConfigDir");
async function configureVSCodeStyle(terminalName, appName) {
  const configDir = getVSCodeStyleConfigDir(appName);
  if (!configDir) {
    return {
      success: false,
      message: `Could not determine ${terminalName} config path on Windows: APPDATA environment variable is not set.`
    };
  }
  const keybindingsFile = path89.join(configDir, "keybindings.json");
  try {
    await fs78.mkdir(configDir, { recursive: true });
    let keybindings = [];
    try {
      const content = await fs78.readFile(keybindingsFile, "utf8");
      await backupFile(keybindingsFile);
      try {
        const cleanContent = stripJsonComments3(content);
        const parsedContent = JSON.parse(cleanContent);
        if (!Array.isArray(parsedContent)) {
          return {
            success: false,
            message: `${terminalName} keybindings.json exists but is not a valid JSON array. Please fix the file manually or delete it to allow automatic configuration.
File: ${keybindingsFile}`
          };
        }
        keybindings = parsedContent;
      } catch (parseError) {
        return {
          success: false,
          message: `Failed to parse ${terminalName} keybindings.json. The file contains invalid JSON.
Please fix the file manually or delete it to allow automatic configuration.
File: ${keybindingsFile}
Error: ${parseError}`
        };
      }
    } catch {
    }
    const shiftEnterBinding = {
      key: "shift+enter",
      command: "workbench.action.terminal.sendSequence",
      when: "terminalFocus",
      args: { text: VSCODE_SHIFT_ENTER_SEQUENCE }
    };
    const ctrlEnterBinding = {
      key: "ctrl+enter",
      command: "workbench.action.terminal.sendSequence",
      when: "terminalFocus",
      args: { text: VSCODE_SHIFT_ENTER_SEQUENCE }
    };
    const existingShiftEnter = keybindings.find((kb) => {
      const binding = kb;
      return binding.key === "shift+enter";
    });
    const existingCtrlEnter = keybindings.find((kb) => {
      const binding = kb;
      return binding.key === "ctrl+enter";
    });
    if (existingShiftEnter || existingCtrlEnter) {
      const messages = [];
      if (existingShiftEnter) {
        messages.push(`- Shift+Enter binding already exists`);
      }
      if (existingCtrlEnter) {
        messages.push(`- Ctrl+Enter binding already exists`);
      }
      return {
        success: false,
        message: `Existing keybindings detected. Will not modify to avoid conflicts.
` + messages.join("\n") + `
Please check and modify manually if needed: ${keybindingsFile}`
      };
    }
    const hasOurShiftEnter = keybindings.some((kb) => {
      const binding = kb;
      return binding.key === "shift+enter" && binding.command === "workbench.action.terminal.sendSequence" && binding.args?.text === "\\\r\n";
    });
    const hasOurCtrlEnter = keybindings.some((kb) => {
      const binding = kb;
      return binding.key === "ctrl+enter" && binding.command === "workbench.action.terminal.sendSequence" && binding.args?.text === "\\\r\n";
    });
    if (!hasOurShiftEnter || !hasOurCtrlEnter) {
      if (!hasOurShiftEnter) keybindings.unshift(shiftEnterBinding);
      if (!hasOurCtrlEnter) keybindings.unshift(ctrlEnterBinding);
      await fs78.writeFile(keybindingsFile, JSON.stringify(keybindings, null, 4));
      return {
        success: true,
        message: `Added Shift+Enter and Ctrl+Enter keybindings to ${terminalName}.
Modified: ${keybindingsFile}`,
        requiresRestart: true
      };
    } else {
      return {
        success: true,
        message: `${terminalName} keybindings already configured.`
      };
    }
  } catch (error) {
    return {
      success: false,
      message: `Failed to configure ${terminalName}.
File: ${keybindingsFile}
Error: ${error}`
    };
  }
}
__name(configureVSCodeStyle, "configureVSCodeStyle");
async function configureVSCode() {
  return configureVSCodeStyle("VS Code", "Code");
}
__name(configureVSCode, "configureVSCode");
async function configureCursor() {
  return configureVSCodeStyle("Cursor", "Cursor");
}
__name(configureCursor, "configureCursor");
async function configureWindsurf() {
  return configureVSCodeStyle("Windsurf", "Windsurf");
}
__name(configureWindsurf, "configureWindsurf");
async function configureTrae() {
  return configureVSCodeStyle("Trae", "Trae");
}
__name(configureTrae, "configureTrae");
async function terminalSetup() {
  if (isKittyProtocolEnabled()) {
    return {
      success: true,
      message: "Your terminal is already configured for an optimal experience with multiline input (Shift+Enter and Ctrl+Enter)."
    };
  }
  const terminal = await detectTerminal();
  if (!terminal) {
    return {
      success: false,
      message: "Could not detect terminal type. Supported terminals: VS Code, Cursor, and Windsurf."
    };
  }
  switch (terminal) {
    case "vscode":
      return configureVSCode();
    case "cursor":
      return configureCursor();
    case "windsurf":
      return configureWindsurf();
    case "trae":
      return configureTrae();
    default:
      return {
        success: false,
        message: `Terminal "${terminal}" is not supported yet.`
      };
  }
}
__name(terminalSetup, "terminalSetup");

// packages/cli/src/ui/commands/terminalSetupCommand.ts
var terminalSetupCommand = {
  name: "terminal-setup",
  description: "Configure terminal keybindings for multiline input (VS Code, Cursor, Windsurf, Trae)",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async () => {
    try {
      const result = await terminalSetup();
      let content = result.message;
      if (result.requiresRestart) {
        content += "\n\nPlease restart your terminal for the changes to take effect.";
      }
      return {
        type: "message",
        content,
        messageType: result.success ? "info" : "error"
      };
    } catch (error) {
      return {
        type: "message",
        content: `Failed to configure terminal: ${error}`,
        messageType: "error"
      };
    }
  }, "action")
};

// packages/cli/src/ui/commands/themeCommand.ts
init_esbuild_shims();
var themeCommand = {
  name: "theme",
  description: "change the theme",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name((_context, _args) => ({
    type: "dialog",
    dialog: "theme"
  }), "action")
};

// packages/cli/src/ui/commands/toolsCommand.ts
init_esbuild_shims();
var toolsCommand = {
  name: "tools",
  description: "list available Qwen Code tools. Usage: /tools [desc]",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, args) => {
    const subCommand = args?.trim();
    let useShowDescriptions = false;
    if (subCommand === "desc" || subCommand === "descriptions") {
      useShowDescriptions = true;
    }
    const toolRegistry = context2.services.config?.getToolRegistry();
    if (!toolRegistry) {
      context2.ui.addItem(
        {
          type: "error" /* ERROR */,
          text: "Could not retrieve tool registry."
        },
        Date.now()
      );
      return;
    }
    const tools = toolRegistry.getAllTools();
    const geminiTools = tools.filter((tool) => !("serverName" in tool));
    const toolsListItem = {
      type: "tools_list" /* TOOLS_LIST */,
      tools: geminiTools.map((tool) => ({
        name: tool.name,
        displayName: tool.displayName,
        description: tool.description
      })),
      showDescriptions: useShowDescriptions
    };
    context2.ui.addItem(toolsListItem, Date.now());
  }, "action")
};

// packages/cli/src/ui/commands/vimCommand.ts
init_esbuild_shims();
var vimCommand = {
  name: "vim",
  description: "toggle vim mode on/off",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, _args) => {
    const newVimState = await context2.ui.toggleVimEnabled();
    const message = newVimState ? "Entered Vim mode. Run /vim again to exit." : "Exited Vim mode.";
    return {
      type: "message",
      messageType: "info",
      content: message
    };
  }, "action")
};

// packages/cli/src/ui/commands/setupGithubCommand.ts
init_esbuild_shims();
var import_undici5 = __toESM(require_undici(), 1);
import path90 from "node:path";
import * as fs79 from "node:fs";
import { Writable } from "node:stream";

// packages/cli/src/utils/gitUtils.ts
init_esbuild_shims();
var import_undici4 = __toESM(require_undici(), 1);
import { execSync as execSync5 } from "node:child_process";
var isGitHubRepository = /* @__PURE__ */ __name(() => {
  try {
    const remotes = (execSync5("git remote -v", {
      encoding: "utf-8"
    }) || "").trim();
    const pattern = /github\.com/;
    return pattern.test(remotes);
  } catch (_error) {
    console.debug(`Failed to get git remote:`, _error);
    return false;
  }
}, "isGitHubRepository");
var getGitRepoRoot = /* @__PURE__ */ __name(() => {
  const gitRepoRoot = (execSync5("git rev-parse --show-toplevel", {
    encoding: "utf-8"
  }) || "").trim();
  if (!gitRepoRoot) {
    throw new Error(`Git repo returned empty value`);
  }
  return gitRepoRoot;
}, "getGitRepoRoot");
var getLatestGitHubRelease = /* @__PURE__ */ __name(async (proxy) => {
  try {
    const controller = new AbortController();
    const endpoint = `https://api.github.com/repos/google-github-actions/run-gemini-cli/releases/latest`;
    const response = await fetch(endpoint, {
      method: "GET",
      headers: {
        Accept: "application/vnd.github+json",
        "Content-Type": "application/json",
        "X-GitHub-Api-Version": "2022-11-28"
      },
      dispatcher: proxy ? new import_undici4.ProxyAgent(proxy) : void 0,
      signal: AbortSignal.any([AbortSignal.timeout(3e4), controller.signal])
    });
    if (!response.ok) {
      throw new Error(
        `Invalid response code: ${response.status} - ${response.statusText}`
      );
    }
    const releaseTag = (await response.json()).tag_name;
    if (!releaseTag) {
      throw new Error(`Response did not include tag_name field`);
    }
    return releaseTag;
  } catch (_error) {
    console.debug(`Failed to determine latest run-gemini-cli release:`, _error);
    throw new Error(
      `Unable to determine the latest run-gemini-cli release on GitHub.`
    );
  }
}, "getLatestGitHubRelease");
function getGitHubRepoInfo() {
  const remoteUrl = execSync5("git remote get-url origin", {
    encoding: "utf-8"
  }).trim();
  const match2 = remoteUrl.match(
    /(?:https?:\/\/|git@)github\.com(?::|\/)([^/]+)\/([^/]+?)(?:\.git)?$/
  );
  if (!match2 || !match2[1] || !match2[2]) {
    throw new Error(
      `Owner & repo could not be extracted from remote URL: ${remoteUrl}`
    );
  }
  return { owner: match2[1], repo: match2[2] };
}
__name(getGitHubRepoInfo, "getGitHubRepoInfo");

// packages/cli/src/ui/commands/setupGithubCommand.ts
var GITHUB_WORKFLOW_PATHS = [
  "gemini-dispatch/gemini-dispatch.yml",
  "gemini-assistant/gemini-invoke.yml",
  "issue-triage/gemini-triage.yml",
  "issue-triage/gemini-scheduled-triage.yml",
  "pr-review/gemini-review.yml"
];
function getOpenUrlsCommands(readmeUrl) {
  const openCmd = getUrlOpenCommand();
  const urlsToOpen = [readmeUrl];
  const repoInfo = getGitHubRepoInfo();
  if (repoInfo) {
    urlsToOpen.push(
      `https://github.com/${repoInfo.owner}/${repoInfo.repo}/settings/secrets/actions`
    );
  }
  const commands = urlsToOpen.map((url2) => `${openCmd} "${url2}"`);
  return commands;
}
__name(getOpenUrlsCommands, "getOpenUrlsCommands");
async function updateGitignore(gitRepoRoot) {
  const gitignoreEntries = [".gemini/", "gha-creds-*.json"];
  const gitignorePath = path90.join(gitRepoRoot, ".gitignore");
  try {
    let existingContent = "";
    let fileExists2 = true;
    try {
      existingContent = await fs79.promises.readFile(gitignorePath, "utf8");
    } catch (_error) {
      fileExists2 = false;
    }
    if (!fileExists2) {
      const contentToWrite = gitignoreEntries.join("\n") + "\n";
      await fs79.promises.writeFile(gitignorePath, contentToWrite);
    } else {
      const missingEntries = gitignoreEntries.filter(
        (entry) => !existingContent.split(/\r?\n/).some((line) => line.split("#")[0].trim() === entry)
      );
      if (missingEntries.length > 0) {
        const contentToAdd = "\n" + missingEntries.join("\n") + "\n";
        await fs79.promises.appendFile(gitignorePath, contentToAdd);
      }
    }
  } catch (error) {
    console.debug("Failed to update .gitignore:", error);
  }
}
__name(updateGitignore, "updateGitignore");
var setupGithubCommand = {
  name: "setup-github",
  description: "Set up GitHub Actions",
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2) => {
    const abortController = new AbortController();
    if (!isGitHubRepository()) {
      throw new Error(
        "Unable to determine the GitHub repository. /setup-github must be run from a git repository."
      );
    }
    let gitRepoRoot;
    try {
      gitRepoRoot = getGitRepoRoot();
    } catch (_error) {
      console.debug(`Failed to get git repo root:`, _error);
      throw new Error(
        "Unable to determine the GitHub repository. /setup-github must be run from a git repository."
      );
    }
    const proxy = context2?.services?.config?.getProxy();
    const releaseTag = await getLatestGitHubRelease(proxy);
    const readmeUrl = `https://github.com/google-github-actions/run-gemini-cli/blob/${releaseTag}/README.md#quick-start`;
    const githubWorkflowsDir = path90.join(gitRepoRoot, ".github", "workflows");
    try {
      await fs79.promises.mkdir(githubWorkflowsDir, { recursive: true });
    } catch (_error) {
      console.debug(
        `Failed to create ${githubWorkflowsDir} directory:`,
        _error
      );
      throw new Error(
        `Unable to create ${githubWorkflowsDir} directory. Do you have file permissions in the current directory?`
      );
    }
    const downloads = [];
    for (const workflow of GITHUB_WORKFLOW_PATHS) {
      downloads.push(
        (async () => {
          const endpoint = `https://raw.githubusercontent.com/google-github-actions/run-gemini-cli/refs/tags/${releaseTag}/examples/workflows/${workflow}`;
          const response = await fetch(endpoint, {
            method: "GET",
            dispatcher: proxy ? new import_undici5.ProxyAgent(proxy) : void 0,
            signal: AbortSignal.any([
              AbortSignal.timeout(3e4),
              abortController.signal
            ])
          });
          if (!response.ok) {
            throw new Error(
              `Invalid response code downloading ${endpoint}: ${response.status} - ${response.statusText}`
            );
          }
          const body = response.body;
          if (!body) {
            throw new Error(
              `Empty body while downloading ${endpoint}: ${response.status} - ${response.statusText}`
            );
          }
          const destination = path90.resolve(
            githubWorkflowsDir,
            path90.basename(workflow)
          );
          const fileStream = fs79.createWriteStream(destination, {
            mode: 420,
            // -rw-r--r--, user(rw), group(r), other(r)
            flags: "w",
            // write and overwrite
            flush: true
          });
          await body.pipeTo(Writable.toWeb(fileStream));
        })()
      );
    }
    await Promise.all(downloads).finally(() => {
      abortController.abort();
    });
    await updateGitignore(gitRepoRoot);
    const commands = [];
    commands.push("set -eEuo pipefail");
    commands.push(
      `echo "Successfully downloaded ${GITHUB_WORKFLOW_PATHS.length} workflows and updated .gitignore. Follow the steps in ${readmeUrl} (skipping the /setup-github step) to complete setup."`
    );
    commands.push(...getOpenUrlsCommands(readmeUrl));
    const command2 = `(${commands.join(" && ")})`;
    return {
      type: "tool",
      toolName: "run_shell_command",
      toolArgs: {
        description: "Setting up GitHub Actions to triage issues and review PRs with Gemini.",
        command: command2
      }
    };
  }, "action")
};

// packages/cli/src/services/BuiltinCommandLoader.ts
var BuiltinCommandLoader = class {
  constructor(config) {
    this.config = config;
  }
  static {
    __name(this, "BuiltinCommandLoader");
  }
  /**
   * Gathers all raw built-in command definitions, injects dependencies where
   * needed (e.g., config) and filters out any that are not available.
   *
   * @param _signal An AbortSignal (unused for this synchronous loader).
   * @returns A promise that resolves to an array of `SlashCommand` objects.
   */
  async loadCommands(_signal) {
    const allDefinitions = [
      aboutCommand,
      agentsCommand,
      approvalModeCommand,
      authCommand,
      bugCommand,
      chatCommand,
      clearCommand,
      compressCommand,
      copyCommand,
      corgiCommand,
      docsCommand,
      directoryCommand,
      editorCommand,
      extensionsCommand2,
      helpCommand,
      await ideCommand(),
      initCommand,
      mcpCommand2,
      memoryCommand,
      modelCommand,
      ...this.config?.getFolderTrust() ? [permissionsCommand] : [],
      quitCommand,
      quitConfirmCommand,
      restoreCommand(this.config),
      statsCommand,
      summaryCommand,
      themeCommand,
      toolsCommand,
      settingsCommand,
      vimCommand,
      setupGithubCommand,
      terminalSetupCommand
    ];
    return allDefinitions.filter((cmd) => cmd !== null);
  }
};

// packages/cli/src/services/FileCommandLoader.ts
init_esbuild_shims();
var import_toml = __toESM(require_toml(), 1);
init_esm9();
init_zod();
import { promises as fs80 } from "node:fs";
import path91 from "node:path";

// packages/cli/src/services/prompt-processors/argumentProcessor.ts
init_esbuild_shims();
var DefaultArgumentProcessor = class {
  static {
    __name(this, "DefaultArgumentProcessor");
  }
  async process(prompt, context2) {
    if (context2.invocation?.args) {
      return appendToLastTextPart(prompt, context2.invocation.raw);
    }
    return prompt;
  }
};

// packages/cli/src/services/prompt-processors/types.ts
init_esbuild_shims();
var SHORTHAND_ARGS_PLACEHOLDER = "{{args}}";
var SHELL_INJECTION_TRIGGER = "!{";
var AT_FILE_INJECTION_TRIGGER = "@{";

// packages/cli/src/services/prompt-processors/shellProcessor.ts
init_esbuild_shims();

// packages/cli/src/services/prompt-processors/injectionParser.ts
init_esbuild_shims();
function extractInjections(prompt, trigger, contextName) {
  const injections = [];
  let index = 0;
  while (index < prompt.length) {
    const startIndex = prompt.indexOf(trigger, index);
    if (startIndex === -1) {
      break;
    }
    let currentIndex = startIndex + trigger.length;
    let braceCount = 1;
    let foundEnd = false;
    while (currentIndex < prompt.length) {
      const char = prompt[currentIndex];
      if (char === "{") {
        braceCount++;
      } else if (char === "}") {
        braceCount--;
        if (braceCount === 0) {
          const injectionContent = prompt.substring(
            startIndex + trigger.length,
            currentIndex
          );
          const endIndex = currentIndex + 1;
          injections.push({
            content: injectionContent.trim(),
            startIndex,
            endIndex
          });
          index = endIndex;
          foundEnd = true;
          break;
        }
      }
      currentIndex++;
    }
    if (!foundEnd) {
      const contextInfo = contextName ? ` in command '${contextName}'` : "";
      throw new Error(
        `Invalid syntax${contextInfo}: Unclosed injection starting at index ${startIndex} ('${trigger}'). Ensure braces are balanced. Paths or commands with unbalanced braces are not supported directly.`
      );
    }
  }
  return injections;
}
__name(extractInjections, "extractInjections");

// packages/cli/src/services/prompt-processors/shellProcessor.ts
var ConfirmationRequiredError = class extends Error {
  constructor(message, commandsToConfirm) {
    super(message);
    this.commandsToConfirm = commandsToConfirm;
    this.name = "ConfirmationRequiredError";
  }
  static {
    __name(this, "ConfirmationRequiredError");
  }
};
var ShellProcessor = class {
  constructor(commandName) {
    this.commandName = commandName;
  }
  static {
    __name(this, "ShellProcessor");
  }
  async process(prompt, context2) {
    return flatMapTextParts(
      prompt,
      (text) => this.processString(text, context2)
    );
  }
  async processString(prompt, context2) {
    const userArgsRaw = context2.invocation?.args || "";
    if (!prompt.includes(SHELL_INJECTION_TRIGGER)) {
      return [
        { text: prompt.replaceAll(SHORTHAND_ARGS_PLACEHOLDER, userArgsRaw) }
      ];
    }
    const config = context2.services.config;
    if (!config) {
      throw new Error(
        `Security configuration not loaded. Cannot verify shell command permissions for '${this.commandName}'. Aborting.`
      );
    }
    const { sessionShellAllowlist } = context2.session;
    const injections = extractInjections(
      prompt,
      SHELL_INJECTION_TRIGGER,
      this.commandName
    );
    if (injections.length === 0) {
      return [
        { text: prompt.replaceAll(SHORTHAND_ARGS_PLACEHOLDER, userArgsRaw) }
      ];
    }
    const { shell: shell2 } = getShellConfiguration();
    const userArgsEscaped = escapeShellArg(userArgsRaw, shell2);
    const resolvedInjections = injections.map(
      (injection) => {
        const command2 = injection.content;
        if (command2 === "") {
          return { ...injection, resolvedCommand: void 0 };
        }
        const resolvedCommand = command2.replaceAll(
          SHORTHAND_ARGS_PLACEHOLDER,
          userArgsEscaped
        );
        return { ...injection, resolvedCommand };
      }
    );
    const commandsToConfirm = /* @__PURE__ */ new Set();
    for (const injection of resolvedInjections) {
      const command2 = injection.resolvedCommand;
      if (!command2) continue;
      const { allAllowed, disallowedCommands, blockReason, isHardDenial } = checkCommandPermissions(command2, config, sessionShellAllowlist);
      if (!allAllowed) {
        if (isHardDenial) {
          throw new Error(
            `${this.commandName} cannot be run. Blocked command: "${command2}". Reason: ${blockReason || "Blocked by configuration."}`
          );
        }
        if (config.getApprovalMode() !== ApprovalMode.YOLO) {
          disallowedCommands.forEach((uc) => commandsToConfirm.add(uc));
        }
      }
    }
    if (commandsToConfirm.size > 0) {
      throw new ConfirmationRequiredError(
        "Shell command confirmation required",
        Array.from(commandsToConfirm)
      );
    }
    let processedPrompt = "";
    let lastIndex = 0;
    for (const injection of resolvedInjections) {
      const segment = prompt.substring(lastIndex, injection.startIndex);
      processedPrompt += segment.replaceAll(
        SHORTHAND_ARGS_PLACEHOLDER,
        userArgsRaw
      );
      if (injection.resolvedCommand) {
        const activeTheme = themeManager.getActiveTheme();
        const shellExecutionConfig = {
          ...config.getShellExecutionConfig(),
          defaultFg: activeTheme.colors.Foreground,
          defaultBg: activeTheme.colors.Background
        };
        const { result } = await ShellExecutionService.execute(
          injection.resolvedCommand,
          config.getTargetDir(),
          () => {
          },
          new AbortController().signal,
          config.getShouldUseNodePtyShell(),
          shellExecutionConfig
        );
        const executionResult = await result;
        if (executionResult.error && !executionResult.aborted) {
          throw new Error(
            `Failed to start shell command in '${this.commandName}': ${executionResult.error.message}. Command: ${injection.resolvedCommand}`
          );
        }
        processedPrompt += executionResult.output;
        if (executionResult.aborted) {
          processedPrompt += `
[Shell command '${injection.resolvedCommand}' aborted]`;
        } else if (executionResult.exitCode !== 0 && executionResult.exitCode !== null) {
          processedPrompt += `
[Shell command '${injection.resolvedCommand}' exited with code ${executionResult.exitCode}]`;
        } else if (executionResult.signal !== null) {
          processedPrompt += `
[Shell command '${injection.resolvedCommand}' terminated by signal ${executionResult.signal}]`;
        }
      }
      lastIndex = injection.endIndex;
    }
    const finalSegment = prompt.substring(lastIndex);
    processedPrompt += finalSegment.replaceAll(
      SHORTHAND_ARGS_PLACEHOLDER,
      userArgsRaw
    );
    return [{ text: processedPrompt }];
  }
};

// packages/cli/src/services/prompt-processors/atFileProcessor.ts
init_esbuild_shims();
var AtFileProcessor = class {
  constructor(commandName) {
    this.commandName = commandName;
  }
  static {
    __name(this, "AtFileProcessor");
  }
  async process(input, context2) {
    const config = context2.services.config;
    if (!config) {
      return input;
    }
    return flatMapTextParts(input, async (text) => {
      if (!text.includes(AT_FILE_INJECTION_TRIGGER)) {
        return [{ text }];
      }
      const injections = extractInjections(
        text,
        AT_FILE_INJECTION_TRIGGER,
        this.commandName
      );
      if (injections.length === 0) {
        return [{ text }];
      }
      const output = [];
      let lastIndex = 0;
      for (const injection of injections) {
        const prefix = text.substring(lastIndex, injection.startIndex);
        if (prefix) {
          output.push({ text: prefix });
        }
        const pathStr = injection.content;
        try {
          const fileContentParts = await readPathFromWorkspace(pathStr, config);
          if (fileContentParts.length === 0) {
            const uiMessage = `File '@{${pathStr}}' was ignored by .gitignore or .qwenignore and was not included in the prompt.`;
            context2.ui.addItem(
              { type: "info" /* INFO */, text: uiMessage },
              Date.now()
            );
          }
          output.push(...fileContentParts);
        } catch (error) {
          const message = error instanceof Error ? error.message : String(error);
          const uiMessage = `Failed to inject content for '@{${pathStr}}': ${message}`;
          console.error(
            `[AtFileProcessor] ${uiMessage}. Leaving placeholder in prompt.`
          );
          context2.ui.addItem(
            { type: "error" /* ERROR */, text: uiMessage },
            Date.now()
          );
          const placeholder = text.substring(
            injection.startIndex,
            injection.endIndex
          );
          output.push({ text: placeholder });
        }
        lastIndex = injection.endIndex;
      }
      const suffix = text.substring(lastIndex);
      if (suffix) {
        output.push({ text: suffix });
      }
      return output;
    });
  }
};

// packages/cli/src/services/FileCommandLoader.ts
var TomlCommandDefSchema = external_exports.object({
  prompt: external_exports.string({
    required_error: "The 'prompt' field is required.",
    invalid_type_error: "The 'prompt' field must be a string."
  }),
  description: external_exports.string().optional()
});
var FileCommandLoader = class {
  constructor(config) {
    this.config = config;
    this.folderTrustEnabled = !!config?.getFolderTrustFeature();
    this.folderTrust = !!config?.getFolderTrust();
    this.projectRoot = config?.getProjectRoot() || process.cwd();
  }
  static {
    __name(this, "FileCommandLoader");
  }
  projectRoot;
  folderTrustEnabled;
  folderTrust;
  /**
   * Loads all commands from user, project, and extension directories.
   * Returns commands in order: user → project → extensions (alphabetically).
   *
   * Order is important for conflict resolution in CommandService:
   * - User/project commands (without extensionName) use "last wins" strategy
   * - Extension commands (with extensionName) get renamed if conflicts exist
   *
   * @param signal An AbortSignal to cancel the loading process.
   * @returns A promise that resolves to an array of all loaded SlashCommands.
   */
  async loadCommands(signal) {
    const allCommands = [];
    const globOptions = {
      nodir: true,
      dot: true,
      signal,
      follow: true
    };
    const commandDirs = this.getCommandDirectories();
    for (const dirInfo of commandDirs) {
      try {
        const files = await glob("**/*.toml", {
          ...globOptions,
          cwd: dirInfo.path
        });
        if (this.folderTrustEnabled && !this.folderTrust) {
          return [];
        }
        const commandPromises = files.map(
          (file) => this.parseAndAdaptFile(
            path91.join(dirInfo.path, file),
            dirInfo.path,
            dirInfo.extensionName
          )
        );
        const commands = (await Promise.all(commandPromises)).filter(
          (cmd) => cmd !== null
        );
        allCommands.push(...commands);
      } catch (error) {
        const isEnoent = error.code === "ENOENT";
        const isAbortError2 = error instanceof Error && error.name === "AbortError";
        if (!isEnoent && !isAbortError2) {
          console.error(
            `[FileCommandLoader] Error loading commands from ${dirInfo.path}:`,
            error
          );
        }
      }
    }
    return allCommands;
  }
  /**
   * Get all command directories in order for loading.
   * User commands → Project commands → Extension commands
   * This order ensures extension commands can detect all conflicts.
   */
  getCommandDirectories() {
    const dirs = [];
    const storage = this.config?.storage ?? new Storage(this.projectRoot);
    dirs.push({ path: Storage.getUserCommandsDir() });
    dirs.push({ path: storage.getProjectCommandsDir() });
    if (this.config) {
      const activeExtensions = this.config.getExtensions().filter((ext2) => ext2.isActive).sort((a, b) => a.name.localeCompare(b.name));
      const extensionCommandDirs = activeExtensions.map((ext2) => ({
        path: path91.join(ext2.path, "commands"),
        extensionName: ext2.name
      }));
      dirs.push(...extensionCommandDirs);
    }
    return dirs;
  }
  /**
   * Parses a single .toml file and transforms it into a SlashCommand object.
   * @param filePath The absolute path to the .toml file.
   * @param baseDir The root command directory for name calculation.
   * @param extensionName Optional extension name to prefix commands with.
   * @returns A promise resolving to a SlashCommand, or null if the file is invalid.
   */
  async parseAndAdaptFile(filePath, baseDir, extensionName) {
    let fileContent;
    try {
      fileContent = await fs80.readFile(filePath, "utf-8");
    } catch (error) {
      console.error(
        `[FileCommandLoader] Failed to read file ${filePath}:`,
        error instanceof Error ? error.message : String(error)
      );
      return null;
    }
    let parsed;
    try {
      parsed = import_toml.default.parse(fileContent);
    } catch (error) {
      console.error(
        `[FileCommandLoader] Failed to parse TOML file ${filePath}:`,
        error instanceof Error ? error.message : String(error)
      );
      return null;
    }
    const validationResult = TomlCommandDefSchema.safeParse(parsed);
    if (!validationResult.success) {
      console.error(
        `[FileCommandLoader] Skipping invalid command file: ${filePath}. Validation errors:`,
        validationResult.error.flatten()
      );
      return null;
    }
    const validDef = validationResult.data;
    const relativePathWithExt = path91.relative(baseDir, filePath);
    const relativePath = relativePathWithExt.substring(
      0,
      relativePathWithExt.length - 5
      // length of '.toml'
    );
    const baseCommandName = relativePath.split(path91.sep).map((segment) => segment.replaceAll(":", "_")).join(":");
    const defaultDescription = `Custom command from ${path91.basename(filePath)}`;
    let description = validDef.description || defaultDescription;
    if (extensionName) {
      description = `[${extensionName}] ${description}`;
    }
    const processors = [];
    const usesArgs = validDef.prompt.includes(SHORTHAND_ARGS_PLACEHOLDER);
    const usesShellInjection = validDef.prompt.includes(
      SHELL_INJECTION_TRIGGER
    );
    const usesAtFileInjection = validDef.prompt.includes(
      AT_FILE_INJECTION_TRIGGER
    );
    if (usesAtFileInjection) {
      processors.push(new AtFileProcessor(baseCommandName));
    }
    if (usesShellInjection || usesArgs) {
      processors.push(new ShellProcessor(baseCommandName));
    }
    if (!usesArgs) {
      processors.push(new DefaultArgumentProcessor());
    }
    return {
      name: baseCommandName,
      description,
      kind: "file" /* FILE */,
      extensionName,
      action: /* @__PURE__ */ __name(async (context2, _args) => {
        if (!context2.invocation) {
          console.error(
            `[FileCommandLoader] Critical error: Command '${baseCommandName}' was executed without invocation context.`
          );
          return {
            type: "submit_prompt",
            content: [{ text: validDef.prompt }]
            // Fallback to unprocessed prompt
          };
        }
        try {
          let processedContent = [
            { text: validDef.prompt }
          ];
          for (const processor of processors) {
            processedContent = await processor.process(
              processedContent,
              context2
            );
          }
          return {
            type: "submit_prompt",
            content: processedContent
          };
        } catch (e2) {
          if (e2 instanceof ConfirmationRequiredError) {
            return {
              type: "confirm_shell_commands",
              commandsToConfirm: e2.commandsToConfirm,
              originalInvocation: {
                raw: context2.invocation.raw
              }
            };
          }
          throw e2;
        }
      }, "action")
    };
  }
};

// packages/cli/src/services/McpPromptLoader.ts
init_esbuild_shims();
var McpPromptLoader = class {
  constructor(config) {
    this.config = config;
  }
  static {
    __name(this, "McpPromptLoader");
  }
  /**
   * Loads all available prompts from all configured MCP servers and adapts
   * them into executable SlashCommand objects.
   *
   * @param _signal An AbortSignal (unused for this synchronous loader).
   * @returns A promise that resolves to an array of loaded SlashCommands.
   */
  loadCommands(_signal) {
    const promptCommands = [];
    if (!this.config) {
      return Promise.resolve([]);
    }
    const mcpServers = this.config.getMcpServers() || {};
    for (const serverName in mcpServers) {
      const prompts = getMCPServerPrompts(this.config, serverName) || [];
      for (const prompt of prompts) {
        const commandName = `${prompt.name}`;
        const newPromptCommand = {
          name: commandName,
          description: prompt.description || `Invoke prompt ${prompt.name}`,
          kind: "mcp-prompt" /* MCP_PROMPT */,
          subCommands: [
            {
              name: "help",
              description: "Show help for this prompt",
              kind: "mcp-prompt" /* MCP_PROMPT */,
              action: /* @__PURE__ */ __name(async () => {
                if (!prompt.arguments || prompt.arguments.length === 0) {
                  return {
                    type: "message",
                    messageType: "info",
                    content: `Prompt "${prompt.name}" has no arguments.`
                  };
                }
                let helpMessage = `Arguments for "${prompt.name}":

`;
                if (prompt.arguments && prompt.arguments.length > 0) {
                  helpMessage += `You can provide arguments by name (e.g., --argName="value") or by position.

`;
                  helpMessage += `e.g., ${prompt.name} ${prompt.arguments?.map((_) => `"foo"`)} is equivalent to ${prompt.name} ${prompt.arguments?.map((arg) => `--${arg.name}="foo"`)}

`;
                }
                for (const arg of prompt.arguments) {
                  helpMessage += `  --${arg.name}
`;
                  if (arg.description) {
                    helpMessage += `    ${arg.description}
`;
                  }
                  helpMessage += `    (required: ${arg.required ? "yes" : "no"})

`;
                }
                return {
                  type: "message",
                  messageType: "info",
                  content: helpMessage
                };
              }, "action")
            }
          ],
          action: /* @__PURE__ */ __name(async (context2, args) => {
            if (!this.config) {
              return {
                type: "message",
                messageType: "error",
                content: "Config not loaded."
              };
            }
            const promptInputs = this.parseArgs(args, prompt.arguments);
            if (promptInputs instanceof Error) {
              return {
                type: "message",
                messageType: "error",
                content: promptInputs.message
              };
            }
            try {
              const mcpServers2 = this.config.getMcpServers() || {};
              const mcpServerConfig = mcpServers2[serverName];
              if (!mcpServerConfig) {
                return {
                  type: "message",
                  messageType: "error",
                  content: `MCP server config not found for '${serverName}'.`
                };
              }
              const result = await prompt.invoke(promptInputs);
              if (result["error"]) {
                return {
                  type: "message",
                  messageType: "error",
                  content: `Error invoking prompt: ${result["error"]}`
                };
              }
              if (!result.messages?.[0]?.content?.["text"]) {
                return {
                  type: "message",
                  messageType: "error",
                  content: "Received an empty or invalid prompt response from the server."
                };
              }
              return {
                type: "submit_prompt",
                content: JSON.stringify(result.messages[0].content.text)
              };
            } catch (error) {
              return {
                type: "message",
                messageType: "error",
                content: `Error: ${getErrorMessage(error)}`
              };
            }
          }, "action"),
          completion: /* @__PURE__ */ __name(async (commandContext, partialArg) => {
            const invocation = commandContext.invocation;
            if (!prompt || !prompt.arguments || !invocation) {
              return [];
            }
            const indexOfFirstSpace = invocation.raw.indexOf(" ") + 1;
            let promptInputs = indexOfFirstSpace === 0 ? {} : this.parseArgs(
              invocation.raw.substring(indexOfFirstSpace),
              prompt.arguments
            );
            if (promptInputs instanceof Error) {
              promptInputs = {};
            }
            const providedArgNames = Object.keys(promptInputs);
            const unusedArguments = prompt.arguments.filter((arg) => {
              if (!providedArgNames.includes(arg.name)) {
                return true;
              }
              const argValue = promptInputs[arg.name];
              return argValue === partialArg;
            }).map((argument) => `--${argument.name}="`) || [];
            const exactlyMatchingArgumentAtTheEnd = prompt.arguments.map((argument) => `--${argument.name}="`).filter((flagArgument) => {
              const regex3 = new RegExp(`${flagArgument}[^"]*$`);
              return regex3.test(invocation.raw);
            });
            if (exactlyMatchingArgumentAtTheEnd.length === 1) {
              if (exactlyMatchingArgumentAtTheEnd[0] === partialArg) {
                return [`${partialArg}"`];
              }
              if (partialArg.endsWith('"')) {
                return [partialArg];
              }
              return [`${partialArg}"`];
            }
            const matchingArguments = unusedArguments.filter(
              (flagArgument) => flagArgument.startsWith(partialArg)
            );
            return matchingArguments;
          }, "completion")
        };
        promptCommands.push(newPromptCommand);
      }
    }
    return Promise.resolve(promptCommands);
  }
  /**
   * Parses the `userArgs` string representing the prompt arguments (all the text
   * after the command) into a record matching the shape of the `promptArgs`.
   *
   * @param userArgs
   * @param promptArgs
   * @returns A record of the parsed arguments
   * @visibleForTesting
   */
  parseArgs(userArgs, promptArgs) {
    const argValues = {};
    const promptInputs = {};
    const namedArgRegex = /--([^=]+)=(?:"((?:\\.|[^"\\])*)"|([^ ]+))/g;
    let match2;
    let lastIndex = 0;
    const positionalParts = [];
    while ((match2 = namedArgRegex.exec(userArgs)) !== null) {
      const key = match2[1];
      const value = (match2[2] ?? match2[3]).replace(/\\(.)/g, "$1");
      argValues[key] = value;
      if (match2.index > lastIndex) {
        positionalParts.push(userArgs.substring(lastIndex, match2.index));
      }
      lastIndex = namedArgRegex.lastIndex;
    }
    if (lastIndex < userArgs.length) {
      positionalParts.push(userArgs.substring(lastIndex));
    }
    const positionalArgsString = positionalParts.join("").trim();
    const positionalArgRegex = /(?:"((?:\\.|[^"\\])*)"|([^ ]+))/g;
    const positionalArgs = [];
    while ((match2 = positionalArgRegex.exec(positionalArgsString)) !== null) {
      positionalArgs.push((match2[1] ?? match2[2]).replace(/\\(.)/g, "$1"));
    }
    if (!promptArgs) {
      return promptInputs;
    }
    for (const arg of promptArgs) {
      if (argValues[arg.name]) {
        promptInputs[arg.name] = argValues[arg.name];
      }
    }
    const unfilledArgs = promptArgs.filter(
      (arg) => arg.required && !promptInputs[arg.name]
    );
    if (unfilledArgs.length === 1) {
      promptInputs[unfilledArgs[0].name] = positionalArgs.join(" ");
    } else {
      const missingArgs = [];
      for (let i = 0; i < unfilledArgs.length; i++) {
        if (positionalArgs.length > i) {
          promptInputs[unfilledArgs[i].name] = positionalArgs[i];
        } else {
          missingArgs.push(unfilledArgs[i].name);
        }
      }
      if (missingArgs.length > 0) {
        const missingArgNames = missingArgs.map((name3) => `--${name3}`).join(", ");
        return new Error(`Missing required argument(s): ${missingArgNames}`);
      }
    }
    return promptInputs;
  }
};

// packages/cli/src/utils/commands.ts
init_esbuild_shims();
var parseSlashCommand = /* @__PURE__ */ __name((query, commands) => {
  const trimmed2 = query.trim();
  const parts = trimmed2.substring(1).trim().split(/\s+/);
  const commandPath = parts.filter((p) => p);
  let currentCommands = commands;
  let commandToExecute;
  let pathIndex = 0;
  const canonicalPath = [];
  for (const part of commandPath) {
    let foundCommand = currentCommands.find((cmd) => cmd.name === part);
    if (!foundCommand) {
      foundCommand = currentCommands.find(
        (cmd) => cmd.altNames?.includes(part)
      );
    }
    if (foundCommand) {
      commandToExecute = foundCommand;
      canonicalPath.push(foundCommand.name);
      pathIndex++;
      if (foundCommand.subCommands) {
        currentCommands = foundCommand.subCommands;
      } else {
        break;
      }
    } else {
      break;
    }
  }
  const args = parts.slice(pathIndex).join(" ");
  return { commandToExecute, args, canonicalPath };
}, "parseSlashCommand");

// packages/cli/src/ui/hooks/slashCommandProcessor.ts
var useSlashCommandProcessor = /* @__PURE__ */ __name((config, settings, addItem, clearItems, loadHistory, refreshStatic, toggleVimEnabled, setIsProcessing, setGeminiMdFileCount, actions, extensionsUpdateState, isConfigInitialized) => {
  const session = useSessionStats();
  const [commands, setCommands] = (0, import_react108.useState)([]);
  const [reloadTrigger, setReloadTrigger] = (0, import_react108.useState)(0);
  const reloadCommands = (0, import_react108.useCallback)(() => {
    setReloadTrigger((v) => v + 1);
  }, []);
  const [shellConfirmationRequest, setShellConfirmationRequest] = (0, import_react108.useState)(null);
  const [confirmationRequest, setConfirmationRequest] = (0, import_react108.useState)(null);
  const [quitConfirmationRequest, setQuitConfirmationRequest] = (0, import_react108.useState)(null);
  const [sessionShellAllowlist, setSessionShellAllowlist] = (0, import_react108.useState)(
    /* @__PURE__ */ new Set()
  );
  const gitService = (0, import_react108.useMemo)(() => {
    if (!config?.getProjectRoot()) {
      return;
    }
    return new GitService(config.getProjectRoot(), config.storage);
  }, [config]);
  const logger6 = (0, import_react108.useMemo)(() => {
    const l2 = new Logger(
      config?.getSessionId() || "",
      config?.storage ?? new Storage(process37.cwd())
    );
    return l2;
  }, [config]);
  const [pendingItem, setPendingItem] = (0, import_react108.useState)(
    null
  );
  const pendingHistoryItems = (0, import_react108.useMemo)(() => {
    const items = [];
    if (pendingItem != null) {
      items.push(pendingItem);
    }
    return items;
  }, [pendingItem]);
  const addMessage = (0, import_react108.useCallback)(
    (message) => {
      let historyItemContent;
      if (message.type === "about" /* ABOUT */) {
        historyItemContent = {
          type: "about",
          systemInfo: message.systemInfo
        };
      } else if (message.type === "help" /* HELP */) {
        historyItemContent = {
          type: "help",
          timestamp: message.timestamp
        };
      } else if (message.type === "stats" /* STATS */) {
        historyItemContent = {
          type: "stats",
          duration: message.duration
        };
      } else if (message.type === "model_stats" /* MODEL_STATS */) {
        historyItemContent = {
          type: "model_stats"
        };
      } else if (message.type === "tool_stats" /* TOOL_STATS */) {
        historyItemContent = {
          type: "tool_stats"
        };
      } else if (message.type === "quit" /* QUIT */) {
        historyItemContent = {
          type: "quit",
          duration: message.duration
        };
      } else if (message.type === "quit_confirmation" /* QUIT_CONFIRMATION */) {
        historyItemContent = {
          type: "quit_confirmation",
          duration: message.duration
        };
      } else if (message.type === "compression" /* COMPRESSION */) {
        historyItemContent = {
          type: "compression",
          compression: message.compression
        };
      } else if (message.type === "summary" /* SUMMARY */) {
        historyItemContent = {
          type: "summary",
          summary: message.summary
        };
      } else {
        historyItemContent = {
          type: message.type,
          text: message.content
        };
      }
      addItem(historyItemContent, message.timestamp.getTime());
    },
    [addItem]
  );
  const commandContext = (0, import_react108.useMemo)(
    () => ({
      services: {
        config,
        settings,
        git: gitService,
        logger: logger6
      },
      ui: {
        addItem,
        clear: /* @__PURE__ */ __name(() => {
          clearItems();
          console.clear();
          refreshStatic();
        }, "clear"),
        loadHistory,
        setDebugMessage: actions.setDebugMessage,
        pendingItem,
        setPendingItem,
        toggleCorgiMode: actions.toggleCorgiMode,
        toggleVimEnabled,
        setGeminiMdFileCount,
        reloadCommands,
        extensionsUpdateState,
        dispatchExtensionStateUpdate: actions.dispatchExtensionStateUpdate,
        addConfirmUpdateExtensionRequest: actions.addConfirmUpdateExtensionRequest
      },
      session: {
        stats: session.stats,
        sessionShellAllowlist
      }
    }),
    [
      config,
      settings,
      gitService,
      logger6,
      loadHistory,
      addItem,
      clearItems,
      refreshStatic,
      session.stats,
      actions,
      pendingItem,
      setPendingItem,
      toggleVimEnabled,
      sessionShellAllowlist,
      setGeminiMdFileCount,
      reloadCommands,
      extensionsUpdateState
    ]
  );
  (0, import_react108.useEffect)(() => {
    if (!config) {
      return;
    }
    const listener = /* @__PURE__ */ __name(() => {
      reloadCommands();
    }, "listener");
    (async () => {
      const ideClient = await IdeClient.getInstance();
      ideClient.addStatusChangeListener(listener);
    })();
    return () => {
      (async () => {
        const ideClient = await IdeClient.getInstance();
        ideClient.removeStatusChangeListener(listener);
      })();
    };
  }, [config, reloadCommands]);
  (0, import_react108.useEffect)(() => {
    const controller = new AbortController();
    const load = /* @__PURE__ */ __name(async () => {
      const loaders = [
        new McpPromptLoader(config),
        new BuiltinCommandLoader(config),
        new FileCommandLoader(config)
      ];
      const commandService = await CommandService.create(
        loaders,
        controller.signal
      );
      setCommands(commandService.getCommands());
    }, "load");
    load();
    return () => {
      controller.abort();
    };
  }, [config, reloadTrigger, isConfigInitialized]);
  const handleSlashCommand2 = (0, import_react108.useCallback)(
    async (rawQuery, oneTimeShellAllowlist, overwriteConfirmed) => {
      if (typeof rawQuery !== "string") {
        return false;
      }
      const trimmed2 = rawQuery.trim();
      if (!trimmed2.startsWith("/") && !trimmed2.startsWith("?")) {
        return false;
      }
      setIsProcessing(true);
      const userMessageTimestamp = Date.now();
      addItem({ type: "user" /* USER */, text: trimmed2 }, userMessageTimestamp);
      let hasError = false;
      const {
        commandToExecute,
        args,
        canonicalPath: resolvedCommandPath
      } = parseSlashCommand(trimmed2, commands);
      const subcommand = resolvedCommandPath.length > 1 ? resolvedCommandPath.slice(1).join(" ") : void 0;
      try {
        if (commandToExecute) {
          if (commandToExecute.action) {
            const fullCommandContext = {
              ...commandContext,
              invocation: {
                raw: trimmed2,
                name: commandToExecute.name,
                args
              },
              overwriteConfirmed
            };
            if (oneTimeShellAllowlist && oneTimeShellAllowlist.size > 0) {
              fullCommandContext.session = {
                ...fullCommandContext.session,
                sessionShellAllowlist: /* @__PURE__ */ new Set([
                  ...fullCommandContext.session.sessionShellAllowlist,
                  ...oneTimeShellAllowlist
                ])
              };
            }
            const result = await commandToExecute.action(
              fullCommandContext,
              args
            );
            if (result) {
              switch (result.type) {
                case "tool":
                  return {
                    type: "schedule_tool",
                    toolName: result.toolName,
                    toolArgs: result.toolArgs
                  };
                case "message":
                  if (result.messageType === "info") {
                    addMessage({
                      type: "info" /* INFO */,
                      content: result.content,
                      timestamp: /* @__PURE__ */ new Date()
                    });
                  } else {
                    addMessage({
                      type: "error" /* ERROR */,
                      content: result.content,
                      timestamp: /* @__PURE__ */ new Date()
                    });
                  }
                  return { type: "handled" };
                case "dialog":
                  switch (result.dialog) {
                    case "auth":
                      actions.openAuthDialog();
                      return { type: "handled" };
                    case "theme":
                      actions.openThemeDialog();
                      return { type: "handled" };
                    case "editor":
                      actions.openEditorDialog();
                      return { type: "handled" };
                    case "settings":
                      actions.openSettingsDialog();
                      return { type: "handled" };
                    case "model":
                      actions.openModelDialog();
                      return { type: "handled" };
                    case "permissions":
                      actions.openPermissionsDialog();
                      return { type: "handled" };
                    case "subagent_create":
                      actions.openSubagentCreateDialog();
                      return { type: "handled" };
                    case "subagent_list":
                      actions.openAgentsManagerDialog();
                      return { type: "handled" };
                    case "approval-mode":
                      actions.openApprovalModeDialog();
                      return { type: "handled" };
                    case "help":
                      return { type: "handled" };
                    default: {
                      const unhandled = result.dialog;
                      throw new Error(
                        `Unhandled slash command result: ${unhandled}`
                      );
                    }
                  }
                case "load_history": {
                  config?.getGeminiClient()?.setHistory(result.clientHistory);
                  config?.getGeminiClient()?.stripThoughtsFromHistory();
                  fullCommandContext.ui.clear();
                  result.history.forEach((item, index) => {
                    fullCommandContext.ui.addItem(item, index);
                  });
                  return { type: "handled" };
                }
                case "quit_confirmation":
                  setQuitConfirmationRequest({
                    onConfirm: /* @__PURE__ */ __name((shouldQuit, action) => {
                      setQuitConfirmationRequest(null);
                      if (!shouldQuit) {
                        return;
                      }
                      if (shouldQuit) {
                        if (action === "save_and_quit") {
                          const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
                          const autoSaveTag = `auto-save chat ${timestamp}`;
                          handleSlashCommand2(`/chat save "${autoSaveTag}"`);
                          setTimeout(() => handleSlashCommand2("/quit"), 100);
                        } else if (action === "summary_and_quit") {
                          handleSlashCommand2("/summary").then(() => {
                            setTimeout(() => {
                              handleSlashCommand2("/quit");
                            }, 1200);
                          }).catch((error) => {
                            addItem(
                              {
                                type: "error",
                                text: `Failed to generate summary before quit: ${error instanceof Error ? error.message : String(error)}`
                              },
                              Date.now()
                            );
                            setTimeout(() => {
                              handleSlashCommand2("/quit");
                            }, 1e3);
                          });
                        } else {
                          const now = Date.now();
                          const { sessionStartTime } = session.stats;
                          const wallDuration = now - sessionStartTime.getTime();
                          actions.quit([
                            {
                              type: "user",
                              text: `/quit`,
                              id: now - 1
                            },
                            {
                              type: "quit",
                              duration: formatDuration(wallDuration),
                              id: now
                            }
                          ]);
                        }
                      }
                    }, "onConfirm")
                  });
                  return { type: "handled" };
                case "quit":
                  actions.quit(result.messages);
                  return { type: "handled" };
                case "submit_prompt":
                  return {
                    type: "submit_prompt",
                    content: result.content
                  };
                case "confirm_shell_commands": {
                  const { outcome, approvedCommands } = await new Promise((resolve24) => {
                    setShellConfirmationRequest({
                      commands: result.commandsToConfirm,
                      onConfirm: /* @__PURE__ */ __name((resolvedOutcome, resolvedApprovedCommands) => {
                        setShellConfirmationRequest(null);
                        resolve24({
                          outcome: resolvedOutcome,
                          approvedCommands: resolvedApprovedCommands
                        });
                      }, "onConfirm")
                    });
                  });
                  if (outcome === ToolConfirmationOutcome.Cancel || !approvedCommands || approvedCommands.length === 0) {
                    return { type: "handled" };
                  }
                  if (outcome === ToolConfirmationOutcome.ProceedAlways) {
                    setSessionShellAllowlist(
                      (prev) => /* @__PURE__ */ new Set([...prev, ...approvedCommands])
                    );
                  }
                  return await handleSlashCommand2(
                    result.originalInvocation.raw,
                    // Pass the approved commands as a one-time grant for this execution.
                    new Set(approvedCommands)
                  );
                }
                case "confirm_action": {
                  const { confirmed } = await new Promise((resolve24) => {
                    setConfirmationRequest({
                      prompt: result.prompt,
                      onConfirm: /* @__PURE__ */ __name((resolvedConfirmed) => {
                        setConfirmationRequest(null);
                        resolve24({ confirmed: resolvedConfirmed });
                      }, "onConfirm")
                    });
                  });
                  if (!confirmed) {
                    addItem(
                      {
                        type: "info" /* INFO */,
                        text: "Operation cancelled."
                      },
                      Date.now()
                    );
                    return { type: "handled" };
                  }
                  return await handleSlashCommand2(
                    result.originalInvocation.raw,
                    void 0,
                    true
                  );
                }
                default: {
                  const unhandled = result;
                  throw new Error(
                    `Unhandled slash command result: ${unhandled}`
                  );
                }
              }
            }
            return { type: "handled" };
          } else if (commandToExecute.subCommands) {
            const helpText = `Command '/${commandToExecute.name}' requires a subcommand. Available:
${commandToExecute.subCommands.map((sc) => `  - ${sc.name}: ${sc.description || ""}`).join("\n")}`;
            addMessage({
              type: "info" /* INFO */,
              content: helpText,
              timestamp: /* @__PURE__ */ new Date()
            });
            return { type: "handled" };
          }
        }
        addMessage({
          type: "error" /* ERROR */,
          content: `Unknown command: ${trimmed2}`,
          timestamp: /* @__PURE__ */ new Date()
        });
        return { type: "handled" };
      } catch (e2) {
        hasError = true;
        if (config) {
          const event = makeSlashCommandEvent({
            command: resolvedCommandPath[0],
            subcommand,
            status: SlashCommandStatus.ERROR
          });
          logSlashCommand(config, event);
        }
        addItem(
          {
            type: "error" /* ERROR */,
            text: e2 instanceof Error ? e2.message : String(e2)
          },
          Date.now()
        );
        return { type: "handled" };
      } finally {
        if (config && resolvedCommandPath[0] && !hasError) {
          const event = makeSlashCommandEvent({
            command: resolvedCommandPath[0],
            subcommand,
            status: SlashCommandStatus.SUCCESS
          });
          logSlashCommand(config, event);
        }
        setIsProcessing(false);
      }
    },
    [
      config,
      addItem,
      actions,
      commands,
      commandContext,
      addMessage,
      setShellConfirmationRequest,
      setSessionShellAllowlist,
      setIsProcessing,
      setConfirmationRequest,
      session.stats
    ]
  );
  return {
    handleSlashCommand: handleSlashCommand2,
    slashCommands: commands,
    pendingHistoryItems,
    commandContext,
    shellConfirmationRequest,
    confirmationRequest,
    quitConfirmationRequest
  };
}, "useSlashCommandProcessor");

// packages/cli/src/ui/hooks/useConsoleMessages.ts
init_esbuild_shims();
var import_react109 = __toESM(require_react(), 1);
function consoleMessagesReducer(state, action) {
  switch (action.type) {
    case "ADD_MESSAGES": {
      const newMessages = [...state];
      for (const queuedMessage of action.payload) {
        const lastMessage = newMessages[newMessages.length - 1];
        if (lastMessage && lastMessage.type === queuedMessage.type && lastMessage.content === queuedMessage.content) {
          newMessages[newMessages.length - 1] = {
            ...lastMessage,
            count: lastMessage.count + 1
          };
        } else {
          newMessages.push({ ...queuedMessage, count: 1 });
        }
      }
      return newMessages;
    }
    case "CLEAR":
      return [];
    default:
      return state;
  }
}
__name(consoleMessagesReducer, "consoleMessagesReducer");
function useConsoleMessages() {
  const [consoleMessages, dispatch] = (0, import_react109.useReducer)(consoleMessagesReducer, []);
  const messageQueueRef = (0, import_react109.useRef)([]);
  const timeoutRef = (0, import_react109.useRef)(null);
  const [, startTransition] = (0, import_react109.useTransition)();
  const processQueue = (0, import_react109.useCallback)(() => {
    if (messageQueueRef.current.length > 0) {
      const messagesToProcess = messageQueueRef.current;
      messageQueueRef.current = [];
      startTransition(() => {
        dispatch({ type: "ADD_MESSAGES", payload: messagesToProcess });
      });
    }
    timeoutRef.current = null;
  }, []);
  const handleNewMessage = (0, import_react109.useCallback)(
    (message) => {
      messageQueueRef.current.push(message);
      if (!timeoutRef.current) {
        timeoutRef.current = setTimeout(processQueue, 16);
      }
    },
    [processQueue]
  );
  const clearConsoleMessages = (0, import_react109.useCallback)(() => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }
    messageQueueRef.current = [];
    startTransition(() => {
      dispatch({ type: "CLEAR" });
    });
  }, []);
  (0, import_react109.useEffect)(
    () => () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    },
    []
  );
  return { consoleMessages, handleNewMessage, clearConsoleMessages };
}
__name(useConsoleMessages, "useConsoleMessages");

// packages/cli/src/ui/AppContainer.tsx
import * as fs90 from "node:fs";
import { basename as basename14 } from "node:path";

// packages/cli/src/utils/windowTitle.ts
init_esbuild_shims();
function computeWindowTitle(folderName) {
  const title = process.env["CLI_TITLE"] || `Qwen - ${folderName}`;
  return title.replace(
    // eslint-disable-next-line no-control-regex
    /[\x00-\x1F\x7F]/g,
    ""
  );
}
__name(computeWindowTitle, "computeWindowTitle");

// packages/cli/src/ui/hooks/useLogger.ts
init_esbuild_shims();
var import_react110 = __toESM(require_react(), 1);
var useLogger = /* @__PURE__ */ __name((storage) => {
  const [logger6, setLogger] = (0, import_react110.useState)(null);
  (0, import_react110.useEffect)(() => {
    const newLogger = new Logger(sessionId, storage);
    newLogger.initialize().then(() => {
      setLogger(newLogger);
    }).catch(() => {
    });
  }, [storage]);
  return logger6;
}, "useLogger");

// packages/cli/src/ui/hooks/useGeminiStream.ts
init_esbuild_shims();
var import_react115 = __toESM(require_react(), 1);
init_node();

// packages/cli/src/ui/hooks/shellCommandProcessor.ts
init_esbuild_shims();
var import_react111 = __toESM(require_react(), 1);
init_node();
import crypto17 from "node:crypto";
import path92 from "node:path";
import os33 from "node:os";
import fs81 from "node:fs";
var OUTPUT_UPDATE_INTERVAL_MS2 = 1e3;
var MAX_OUTPUT_LENGTH = 1e4;
function addShellCommandToGeminiHistory(geminiClient, rawQuery, resultText) {
  const modelContent = resultText.length > MAX_OUTPUT_LENGTH ? resultText.substring(0, MAX_OUTPUT_LENGTH) + "\n... (truncated)" : resultText;
  geminiClient.addHistory({
    role: "user",
    parts: [
      {
        text: `I ran the following shell command:
\`\`\`sh
${rawQuery}
\`\`\`

This produced the following result:
\`\`\`
${modelContent}
\`\`\``
      }
    ]
  });
}
__name(addShellCommandToGeminiHistory, "addShellCommandToGeminiHistory");
var useShellCommandProcessor = /* @__PURE__ */ __name((addItemToHistory, setPendingHistoryItem, onExec, onDebugMessage, config, geminiClient, setShellInputFocused, terminalWidth, terminalHeight) => {
  const [activeShellPtyId, setActiveShellPtyId] = (0, import_react111.useState)(null);
  const handleShellCommand = (0, import_react111.useCallback)(
    (rawQuery, abortSignal) => {
      if (typeof rawQuery !== "string" || rawQuery.trim() === "") {
        return false;
      }
      const userMessageTimestamp = Date.now();
      const callId = `shell-${userMessageTimestamp}`;
      addItemToHistory(
        { type: "user_shell", text: rawQuery },
        userMessageTimestamp
      );
      const isWindows8 = os33.platform() === "win32";
      const targetDir = config.getTargetDir();
      let commandToExecute = rawQuery;
      let pwdFilePath;
      if (!isWindows8) {
        let command2 = rawQuery.trim();
        const pwdFileName = `shell_pwd_${crypto17.randomBytes(6).toString("hex")}.tmp`;
        pwdFilePath = path92.join(os33.tmpdir(), pwdFileName);
        if (!command2.endsWith(";") && !command2.endsWith("&")) {
          command2 += ";";
        }
        commandToExecute = `{ ${command2} }; __code=$?; pwd > "${pwdFilePath}"; exit $__code`;
      }
      const executeCommand = /* @__PURE__ */ __name(async (resolve24) => {
        let lastUpdateTime = Date.now();
        let cumulativeStdout = "";
        let isBinaryStream = false;
        let binaryBytesReceived = 0;
        const initialToolDisplay = {
          callId,
          name: SHELL_COMMAND_NAME,
          description: rawQuery,
          status: "Executing" /* Executing */,
          resultDisplay: "",
          confirmationDetails: void 0
        };
        setPendingHistoryItem({
          type: "tool_group",
          tools: [initialToolDisplay]
        });
        let executionPid;
        const abortHandler = /* @__PURE__ */ __name(() => {
          onDebugMessage(
            `Aborting shell command (PID: ${executionPid ?? "unknown"})`
          );
        }, "abortHandler");
        abortSignal.addEventListener("abort", abortHandler, { once: true });
        onDebugMessage(`Executing in ${targetDir}: ${commandToExecute}`);
        try {
          const activeTheme = themeManager.getActiveTheme();
          const shellExecutionConfig = {
            ...config.getShellExecutionConfig(),
            terminalWidth,
            terminalHeight,
            defaultFg: activeTheme.colors.Foreground,
            defaultBg: activeTheme.colors.Background
          };
          const { pid, result } = await ShellExecutionService.execute(
            commandToExecute,
            targetDir,
            (event) => {
              let shouldUpdate = false;
              switch (event.type) {
                case "data":
                  if (isBinaryStream) break;
                  if (config.getShouldUseNodePtyShell()) {
                    cumulativeStdout = event.chunk;
                    shouldUpdate = true;
                  } else if (typeof event.chunk === "string" && typeof cumulativeStdout === "string") {
                    cumulativeStdout += event.chunk;
                  }
                  break;
                case "binary_detected":
                  isBinaryStream = true;
                  shouldUpdate = true;
                  break;
                case "binary_progress":
                  isBinaryStream = true;
                  binaryBytesReceived = event.bytesReceived;
                  break;
                default: {
                  throw new Error("An unhandled ShellOutputEvent was found.");
                }
              }
              let currentDisplayOutput;
              if (isBinaryStream) {
                if (binaryBytesReceived > 0) {
                  currentDisplayOutput = `[Receiving binary output... ${formatMemoryUsage2(
                    binaryBytesReceived
                  )} received]`;
                } else {
                  currentDisplayOutput = "[Binary output detected. Halting stream...]";
                }
              } else {
                currentDisplayOutput = cumulativeStdout;
              }
              if (shouldUpdate || Date.now() - lastUpdateTime > OUTPUT_UPDATE_INTERVAL_MS2) {
                setPendingHistoryItem((prevItem) => {
                  if (prevItem?.type === "tool_group") {
                    return {
                      ...prevItem,
                      tools: prevItem.tools.map(
                        (tool) => tool.callId === callId ? {
                          ...tool,
                          resultDisplay: typeof currentDisplayOutput === "string" ? currentDisplayOutput : { ansiOutput: currentDisplayOutput }
                        } : tool
                      )
                    };
                  }
                  return prevItem;
                });
                lastUpdateTime = Date.now();
              }
            },
            abortSignal,
            config.getShouldUseNodePtyShell(),
            shellExecutionConfig
          );
          console.log(terminalHeight, terminalWidth);
          executionPid = pid;
          if (pid) {
            setActiveShellPtyId(pid);
            setPendingHistoryItem((prevItem) => {
              if (prevItem?.type === "tool_group") {
                return {
                  ...prevItem,
                  tools: prevItem.tools.map(
                    (tool) => tool.callId === callId ? { ...tool, ptyId: pid } : tool
                  )
                };
              }
              return prevItem;
            });
          }
          result.then((result2) => {
            setPendingHistoryItem(null);
            let mainContent;
            if (isBinary(result2.rawOutput)) {
              mainContent = "[Command produced binary output, which is not shown.]";
            } else {
              mainContent = result2.output.trim() || "(Command produced no output)";
            }
            let finalOutput = mainContent;
            let finalStatus = "Success" /* Success */;
            if (result2.error) {
              finalStatus = "Error" /* Error */;
              finalOutput = `${result2.error.message}
${finalOutput}`;
            } else if (result2.aborted) {
              finalStatus = "Canceled" /* Canceled */;
              finalOutput = `Command was cancelled.
${finalOutput}`;
            } else if (result2.signal) {
              finalStatus = "Error" /* Error */;
              finalOutput = `Command terminated by signal: ${result2.signal}.
${finalOutput}`;
            } else if (result2.exitCode !== 0) {
              finalStatus = "Error" /* Error */;
              finalOutput = `Command exited with code ${result2.exitCode}.
${finalOutput}`;
            }
            if (pwdFilePath && fs81.existsSync(pwdFilePath)) {
              const finalPwd = fs81.readFileSync(pwdFilePath, "utf8").trim();
              if (finalPwd && finalPwd !== targetDir) {
                const warning = `WARNING: shell mode is stateless; the directory change to '${finalPwd}' will not persist.`;
                finalOutput = `${warning}

${finalOutput}`;
              }
            }
            const finalToolDisplay = {
              ...initialToolDisplay,
              status: finalStatus,
              resultDisplay: finalOutput
            };
            addItemToHistory(
              {
                type: "tool_group",
                tools: [finalToolDisplay]
              },
              userMessageTimestamp
            );
            addShellCommandToGeminiHistory(
              geminiClient,
              rawQuery,
              finalOutput
            );
          }).catch((err) => {
            setPendingHistoryItem(null);
            const errorMessage = err instanceof Error ? err.message : String(err);
            addItemToHistory(
              {
                type: "error",
                text: `An unexpected error occurred: ${errorMessage}`
              },
              userMessageTimestamp
            );
          }).finally(() => {
            abortSignal.removeEventListener("abort", abortHandler);
            if (pwdFilePath && fs81.existsSync(pwdFilePath)) {
              fs81.unlinkSync(pwdFilePath);
            }
            setActiveShellPtyId(null);
            setShellInputFocused(false);
            resolve24();
          });
        } catch (err) {
          setPendingHistoryItem(null);
          const errorMessage = err instanceof Error ? err.message : String(err);
          addItemToHistory(
            {
              type: "error",
              text: `An unexpected error occurred: ${errorMessage}`
            },
            userMessageTimestamp
          );
          if (pwdFilePath && fs81.existsSync(pwdFilePath)) {
            fs81.unlinkSync(pwdFilePath);
          }
          setActiveShellPtyId(null);
          setShellInputFocused(false);
          resolve24();
        }
      }, "executeCommand");
      const execPromise = new Promise((resolve24) => {
        executeCommand(resolve24);
      });
      onExec(execPromise);
      return true;
    },
    [
      config,
      onDebugMessage,
      addItemToHistory,
      setPendingHistoryItem,
      onExec,
      geminiClient,
      setShellInputFocused,
      terminalHeight,
      terminalWidth
    ]
  );
  return { handleShellCommand, activeShellPtyId };
}, "useShellCommandProcessor");

// packages/cli/src/ui/hooks/useVisionAutoSwitch.ts
init_esbuild_shims();
init_node();
var import_react112 = __toESM(require_react(), 1);
function hasImageParts(parts) {
  if (typeof parts === "string") {
    return false;
  }
  if (Array.isArray(parts)) {
    return parts.some((part) => {
      if (typeof part === "string") return false;
      return isImagePart(part);
    });
  }
  if (typeof parts === "object") {
    return isImagePart(parts);
  }
  return false;
}
__name(hasImageParts, "hasImageParts");
function isImagePart(part) {
  if ("inlineData" in part && part.inlineData?.mimeType?.startsWith("image/")) {
    return true;
  }
  if ("fileData" in part && part.fileData?.mimeType?.startsWith("image/")) {
    return true;
  }
  return false;
}
__name(isImagePart, "isImagePart");
function checkImageFormatsSupport(parts) {
  const unsupportedMimeTypes = [];
  let hasImages = false;
  if (typeof parts === "string") {
    return {
      hasImages: false,
      hasUnsupportedFormats: false,
      unsupportedMimeTypes: []
    };
  }
  const partsArray = Array.isArray(parts) ? parts : [parts];
  for (const part of partsArray) {
    if (typeof part === "string") continue;
    let mimeType;
    if ("inlineData" in part && part.inlineData?.mimeType?.startsWith("image/")) {
      hasImages = true;
      mimeType = part.inlineData.mimeType;
    }
    if ("fileData" in part && part.fileData?.mimeType?.startsWith("image/")) {
      hasImages = true;
      mimeType = part.fileData.mimeType;
    }
    if (mimeType && !isSupportedImageMimeType(mimeType)) {
      unsupportedMimeTypes.push(mimeType);
    }
  }
  return {
    hasImages,
    hasUnsupportedFormats: unsupportedMimeTypes.length > 0,
    unsupportedMimeTypes
  };
}
__name(checkImageFormatsSupport, "checkImageFormatsSupport");
function shouldOfferVisionSwitch(parts, authType, currentModel, visionModelPreviewEnabled = true) {
  if (authType !== AuthType2.QWEN_OAUTH) {
    return false;
  }
  if (!visionModelPreviewEnabled) {
    return false;
  }
  if (isVisionModel(currentModel)) {
    return false;
  }
  return hasImageParts(parts);
}
__name(shouldOfferVisionSwitch, "shouldOfferVisionSwitch");
function processVisionSwitchOutcome(outcome) {
  const vlModelId = getDefaultVisionModel();
  switch (outcome) {
    case "once" /* SwitchOnce */:
      return { modelOverride: vlModelId };
    case "session" /* SwitchSessionToVL */:
      return { persistSessionModel: vlModelId };
    case "persist" /* ContinueWithCurrentModel */:
      return {};
    // Continue with current model, no changes needed
    default:
      return {};
  }
}
__name(processVisionSwitchOutcome, "processVisionSwitchOutcome");
function useVisionAutoSwitch(config, addItem, visionModelPreviewEnabled = true, onVisionSwitchRequired) {
  const originalModelRef = (0, import_react112.useRef)(null);
  const handleVisionSwitch = (0, import_react112.useCallback)(
    async (query, userMessageTimestamp, isContinuation) => {
      if (isContinuation || !onVisionSwitchRequired) {
        return { shouldProceed: true };
      }
      const contentGeneratorConfig = config.getContentGeneratorConfig();
      if (contentGeneratorConfig?.authType !== AuthType2.QWEN_OAUTH) {
        return { shouldProceed: true };
      }
      const formatCheck = checkImageFormatsSupport(query);
      if (formatCheck.hasUnsupportedFormats) {
        addItem(
          {
            type: "info" /* INFO */,
            text: getUnsupportedImageFormatWarning()
          },
          userMessageTimestamp
        );
      }
      if (!shouldOfferVisionSwitch(
        query,
        contentGeneratorConfig.authType,
        config.getModel(),
        visionModelPreviewEnabled
      )) {
        return { shouldProceed: true };
      }
      if (config.getApprovalMode() === ApprovalMode.YOLO) {
        const vlModelId = getDefaultVisionModel();
        originalModelRef.current = config.getModel();
        await config.setModel(vlModelId, {
          reason: "vision_auto_switch",
          context: "YOLO mode auto-switch for image content"
        });
        return {
          shouldProceed: true,
          originalModel: originalModelRef.current
        };
      }
      const defaultVlmSwitchMode = config.getVlmSwitchMode();
      if (defaultVlmSwitchMode) {
        let outcome;
        switch (defaultVlmSwitchMode) {
          case "once":
            outcome = "once" /* SwitchOnce */;
            break;
          case "session":
            outcome = "session" /* SwitchSessionToVL */;
            break;
          case "persist":
            outcome = "persist" /* ContinueWithCurrentModel */;
            break;
          default:
            outcome = "persist" /* ContinueWithCurrentModel */;
        }
        const visionSwitchResult = processVisionSwitchOutcome(outcome);
        if (visionSwitchResult.modelOverride) {
          originalModelRef.current = config.getModel();
          await config.setModel(visionSwitchResult.modelOverride, {
            reason: "vision_auto_switch",
            context: `Default VLM switch mode: ${defaultVlmSwitchMode} (one-time override)`
          });
          return {
            shouldProceed: true,
            originalModel: originalModelRef.current
          };
        } else if (visionSwitchResult.persistSessionModel) {
          await config.setModel(visionSwitchResult.persistSessionModel, {
            reason: "vision_auto_switch",
            context: `Default VLM switch mode: ${defaultVlmSwitchMode} (session persistent)`
          });
          return { shouldProceed: true };
        }
        return { shouldProceed: true };
      }
      try {
        const visionSwitchResult = await onVisionSwitchRequired(query);
        if (visionSwitchResult.modelOverride) {
          originalModelRef.current = config.getModel();
          await config.setModel(visionSwitchResult.modelOverride, {
            reason: "vision_auto_switch",
            context: "User-prompted vision switch (one-time override)"
          });
          return {
            shouldProceed: true,
            originalModel: originalModelRef.current
          };
        } else if (visionSwitchResult.persistSessionModel) {
          await config.setModel(visionSwitchResult.persistSessionModel, {
            reason: "vision_auto_switch",
            context: "User-prompted vision switch (session persistent)"
          });
          return { shouldProceed: true };
        }
        return { shouldProceed: true };
      } catch (_error) {
        return { shouldProceed: false };
      }
    },
    [config, addItem, visionModelPreviewEnabled, onVisionSwitchRequired]
  );
  const restoreOriginalModel = (0, import_react112.useCallback)(async () => {
    if (originalModelRef.current) {
      await config.setModel(originalModelRef.current, {
        reason: "vision_auto_switch",
        context: "Restoring original model after vision switch"
      });
      originalModelRef.current = null;
    }
  }, [config]);
  return {
    handleVisionSwitch,
    restoreOriginalModel
  };
}
__name(useVisionAutoSwitch, "useVisionAutoSwitch");

// packages/cli/src/ui/hooks/atCommandProcessor.ts
init_esbuild_shims();
import * as fs82 from "node:fs/promises";
import * as path93 from "node:path";
function parseAllAtCommands(query) {
  const parts = [];
  let currentIndex = 0;
  while (currentIndex < query.length) {
    let atIndex = -1;
    let nextSearchIndex = currentIndex;
    while (nextSearchIndex < query.length) {
      if (query[nextSearchIndex] === "@" && (nextSearchIndex === 0 || query[nextSearchIndex - 1] !== "\\")) {
        atIndex = nextSearchIndex;
        break;
      }
      nextSearchIndex++;
    }
    if (atIndex === -1) {
      if (currentIndex < query.length) {
        parts.push({ type: "text", content: query.substring(currentIndex) });
      }
      break;
    }
    if (atIndex > currentIndex) {
      parts.push({
        type: "text",
        content: query.substring(currentIndex, atIndex)
      });
    }
    let pathEndIndex = atIndex + 1;
    let inEscape = false;
    while (pathEndIndex < query.length) {
      const char = query[pathEndIndex];
      if (inEscape) {
        inEscape = false;
      } else if (char === "\\") {
        inEscape = true;
      } else if (/[,\s;!?()[\]{}]/.test(char)) {
        break;
      } else if (char === ".") {
        const nextChar = pathEndIndex + 1 < query.length ? query[pathEndIndex + 1] : "";
        if (nextChar === "" || /\s/.test(nextChar)) {
          break;
        }
      }
      pathEndIndex++;
    }
    const rawAtPath = query.substring(atIndex, pathEndIndex);
    const atPath = unescapePath(rawAtPath);
    parts.push({ type: "atPath", content: atPath });
    currentIndex = pathEndIndex;
  }
  return parts.filter(
    (part) => !(part.type === "text" && part.content.trim() === "")
  );
}
__name(parseAllAtCommands, "parseAllAtCommands");
async function handleAtCommand({
  query,
  config,
  addItem,
  onDebugMessage,
  messageId: userMessageTimestamp,
  signal
}) {
  const commandParts = parseAllAtCommands(query);
  const atPathCommandParts = commandParts.filter(
    (part) => part.type === "atPath"
  );
  if (atPathCommandParts.length === 0) {
    return { processedQuery: [{ text: query }], shouldProceed: true };
  }
  const fileDiscovery = config.getFileService();
  const respectFileIgnore = config.getFileFilteringOptions();
  const pathSpecsToRead = [];
  const atPathToResolvedSpecMap = /* @__PURE__ */ new Map();
  const contentLabelsForDisplay = [];
  const ignoredByReason = {
    git: [],
    qwen: [],
    both: []
  };
  const toolRegistry = config.getToolRegistry();
  const readManyFilesTool = toolRegistry.getTool("read_many_files");
  const globTool = toolRegistry.getTool("glob");
  if (!readManyFilesTool) {
    addItem(
      { type: "error", text: "Error: read_many_files tool not found." },
      userMessageTimestamp
    );
    return { processedQuery: null, shouldProceed: false };
  }
  for (const atPathPart of atPathCommandParts) {
    const originalAtPath = atPathPart.content;
    if (originalAtPath === "@") {
      onDebugMessage(
        "Lone @ detected, will be treated as text in the modified query."
      );
      continue;
    }
    const pathName = originalAtPath.substring(1);
    if (!pathName) {
      addItem(
        {
          type: "error",
          text: `Error: Invalid @ command '${originalAtPath}'. No path specified.`
        },
        userMessageTimestamp
      );
      return { processedQuery: null, shouldProceed: false };
    }
    const workspaceContext = config.getWorkspaceContext();
    if (!workspaceContext.isPathWithinWorkspace(pathName)) {
      onDebugMessage(
        `Path ${pathName} is not in the workspace and will be skipped.`
      );
      continue;
    }
    const gitIgnored = respectFileIgnore.respectGitIgnore && fileDiscovery.shouldIgnoreFile(pathName, {
      respectGitIgnore: true,
      respectQwenIgnore: false
    });
    const qwenIgnored = respectFileIgnore.respectQwenIgnore && fileDiscovery.shouldIgnoreFile(pathName, {
      respectGitIgnore: false,
      respectQwenIgnore: true
    });
    if (gitIgnored || qwenIgnored) {
      const reason = gitIgnored && qwenIgnored ? "both" : gitIgnored ? "git" : "qwen";
      ignoredByReason[reason].push(pathName);
      const reasonText = reason === "both" ? "ignored by both git and qwen" : reason === "git" ? "git-ignored" : "qwen-ignored";
      onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`);
      continue;
    }
    for (const dir of config.getWorkspaceContext().getDirectories()) {
      let currentPathSpec = pathName;
      let resolvedSuccessfully = false;
      try {
        const absolutePath = path93.resolve(dir, pathName);
        const stats = await fs82.stat(absolutePath);
        if (stats.isDirectory()) {
          currentPathSpec = pathName + (pathName.endsWith(path93.sep) ? `**` : `/**`);
          onDebugMessage(
            `Path ${pathName} resolved to directory, using glob: ${currentPathSpec}`
          );
        } else {
          onDebugMessage(`Path ${pathName} resolved to file: ${absolutePath}`);
        }
        resolvedSuccessfully = true;
      } catch (error) {
        if (isNodeError(error) && error.code === "ENOENT") {
          if (config.getEnableRecursiveFileSearch() && globTool) {
            onDebugMessage(
              `Path ${pathName} not found directly, attempting glob search.`
            );
            try {
              const globResult = await globTool.buildAndExecute(
                {
                  pattern: `**/*${pathName}*`,
                  path: dir
                },
                signal
              );
              if (globResult.llmContent && typeof globResult.llmContent === "string" && !globResult.llmContent.startsWith("No files found") && !globResult.llmContent.startsWith("Error:")) {
                const lines = globResult.llmContent.split("\n");
                if (lines.length > 1 && lines[1]) {
                  const firstMatchAbsolute = lines[1].trim();
                  currentPathSpec = path93.relative(dir, firstMatchAbsolute);
                  onDebugMessage(
                    `Glob search for ${pathName} found ${firstMatchAbsolute}, using relative path: ${currentPathSpec}`
                  );
                  resolvedSuccessfully = true;
                } else {
                  onDebugMessage(
                    `Glob search for '**/*${pathName}*' did not return a usable path. Path ${pathName} will be skipped.`
                  );
                }
              } else {
                onDebugMessage(
                  `Glob search for '**/*${pathName}*' found no files or an error. Path ${pathName} will be skipped.`
                );
              }
            } catch (globError) {
              console.error(
                `Error during glob search for ${pathName}: ${getErrorMessage(globError)}`
              );
              onDebugMessage(
                `Error during glob search for ${pathName}. Path ${pathName} will be skipped.`
              );
            }
          } else {
            onDebugMessage(
              `Glob tool not found. Path ${pathName} will be skipped.`
            );
          }
        } else {
          console.error(
            `Error stating path ${pathName}: ${getErrorMessage(error)}`
          );
          onDebugMessage(
            `Error stating path ${pathName}. Path ${pathName} will be skipped.`
          );
        }
      }
      if (resolvedSuccessfully) {
        pathSpecsToRead.push(currentPathSpec);
        atPathToResolvedSpecMap.set(originalAtPath, currentPathSpec);
        contentLabelsForDisplay.push(pathName);
        break;
      }
    }
  }
  let initialQueryText = "";
  for (let i = 0; i < commandParts.length; i++) {
    const part = commandParts[i];
    if (part.type === "text") {
      initialQueryText += part.content;
    } else {
      const resolvedSpec = atPathToResolvedSpecMap.get(part.content);
      if (i > 0 && initialQueryText.length > 0 && !initialQueryText.endsWith(" ")) {
        const prevPart = commandParts[i - 1];
        if (prevPart.type === "text" || prevPart.type === "atPath" && atPathToResolvedSpecMap.has(prevPart.content)) {
          initialQueryText += " ";
        }
      }
      if (resolvedSpec) {
        initialQueryText += `@${resolvedSpec}`;
      } else {
        if (i > 0 && initialQueryText.length > 0 && !initialQueryText.endsWith(" ") && !part.content.startsWith(" ")) {
          initialQueryText += " ";
        }
        initialQueryText += part.content;
      }
    }
  }
  initialQueryText = initialQueryText.trim();
  const totalIgnored = ignoredByReason["git"].length + ignoredByReason["qwen"].length + ignoredByReason["both"].length;
  if (totalIgnored > 0) {
    const messages = [];
    if (ignoredByReason["git"].length) {
      messages.push(`Git-ignored: ${ignoredByReason["git"].join(", ")}`);
    }
    if (ignoredByReason["qwen"].length) {
      messages.push(`Qwen-ignored: ${ignoredByReason["qwen"].join(", ")}`);
    }
    if (ignoredByReason["both"].length) {
      messages.push(`Ignored by both: ${ignoredByReason["both"].join(", ")}`);
    }
    const message = `Ignored ${totalIgnored} files:
${messages.join("\n")}`;
    console.log(message);
    onDebugMessage(message);
  }
  if (pathSpecsToRead.length === 0) {
    onDebugMessage("No valid file paths found in @ commands to read.");
    if (initialQueryText === "@" && query.trim() === "@") {
      return { processedQuery: [{ text: query }], shouldProceed: true };
    } else if (!initialQueryText && query) {
      return { processedQuery: [{ text: query }], shouldProceed: true };
    }
    return {
      processedQuery: [{ text: initialQueryText || query }],
      shouldProceed: true
    };
  }
  const processedQueryParts = [{ text: initialQueryText }];
  const toolArgs = {
    paths: pathSpecsToRead,
    file_filtering_options: {
      respect_git_ignore: respectFileIgnore.respectGitIgnore,
      respect_qwen_ignore: respectFileIgnore.respectQwenIgnore
    }
    // Use configuration setting
  };
  let toolCallDisplay;
  let invocation = void 0;
  try {
    invocation = readManyFilesTool.build(toolArgs);
    const result = await invocation.execute(signal);
    toolCallDisplay = {
      callId: `client-read-${userMessageTimestamp}`,
      name: readManyFilesTool.displayName,
      description: invocation.getDescription(),
      status: "Success" /* Success */,
      resultDisplay: result.returnDisplay || `Successfully read: ${contentLabelsForDisplay.join(", ")}`,
      confirmationDetails: void 0
    };
    if (Array.isArray(result.llmContent)) {
      const fileContentRegex = /^--- (.*?) ---\n\n([\s\S]*?)\n\n$/;
      processedQueryParts.push({
        text: "\n--- Content from referenced files ---"
      });
      for (const part of result.llmContent) {
        if (typeof part === "string") {
          const match2 = fileContentRegex.exec(part);
          if (match2) {
            const filePathSpecInContent = match2[1];
            const fileActualContent = match2[2].trim();
            processedQueryParts.push({
              text: `
Content from @${filePathSpecInContent}:
`
            });
            processedQueryParts.push({ text: fileActualContent });
          } else {
            processedQueryParts.push({ text: part });
          }
        } else {
          processedQueryParts.push(part);
        }
      }
    } else {
      onDebugMessage(
        "read_many_files tool returned no content or empty content."
      );
    }
    addItem(
      { type: "tool_group", tools: [toolCallDisplay] },
      userMessageTimestamp
    );
    return { processedQuery: processedQueryParts, shouldProceed: true };
  } catch (error) {
    toolCallDisplay = {
      callId: `client-read-${userMessageTimestamp}`,
      name: readManyFilesTool.displayName,
      description: invocation?.getDescription() ?? "Error attempting to execute tool to read files",
      status: "Error" /* Error */,
      resultDisplay: `Error reading files (${contentLabelsForDisplay.join(", ")}): ${getErrorMessage(error)}`,
      confirmationDetails: void 0
    };
    addItem(
      { type: "tool_group", tools: [toolCallDisplay] },
      userMessageTimestamp
    );
    return { processedQuery: null, shouldProceed: false };
  }
}
__name(handleAtCommand, "handleAtCommand");

// packages/cli/src/ui/utils/markdownUtilities.ts
init_esbuild_shims();
var isIndexInsideCodeBlock = /* @__PURE__ */ __name((content, indexToTest) => {
  let fenceCount = 0;
  let searchPos = 0;
  while (searchPos < content.length) {
    const nextFence = content.indexOf("```", searchPos);
    if (nextFence === -1 || nextFence >= indexToTest) {
      break;
    }
    fenceCount++;
    searchPos = nextFence + 3;
  }
  return fenceCount % 2 === 1;
}, "isIndexInsideCodeBlock");
var findEnclosingCodeBlockStart = /* @__PURE__ */ __name((content, index) => {
  if (!isIndexInsideCodeBlock(content, index)) {
    return -1;
  }
  let currentSearchPos = 0;
  while (currentSearchPos < index) {
    const blockStartIndex = content.indexOf("```", currentSearchPos);
    if (blockStartIndex === -1 || blockStartIndex >= index) {
      break;
    }
    const blockEndIndex = content.indexOf("```", blockStartIndex + 3);
    if (blockStartIndex < index) {
      if (blockEndIndex === -1 || index < blockEndIndex + 3) {
        return blockStartIndex;
      }
    }
    if (blockEndIndex === -1) break;
    currentSearchPos = blockEndIndex + 3;
  }
  return -1;
}, "findEnclosingCodeBlockStart");
var findLastSafeSplitPoint = /* @__PURE__ */ __name((content) => {
  const enclosingBlockStart = findEnclosingCodeBlockStart(
    content,
    content.length
  );
  if (enclosingBlockStart !== -1) {
    return enclosingBlockStart;
  }
  let searchStartIndex = content.length;
  while (searchStartIndex >= 0) {
    const dnlIndex = content.lastIndexOf("\n\n", searchStartIndex);
    if (dnlIndex === -1) {
      break;
    }
    const potentialSplitPoint = dnlIndex + 2;
    if (!isIndexInsideCodeBlock(content, potentialSplitPoint)) {
      return potentialSplitPoint;
    }
    searchStartIndex = dnlIndex - 1;
  }
  return content.length;
}, "findLastSafeSplitPoint");

// packages/cli/src/ui/hooks/useStateAndRef.ts
init_esbuild_shims();
var import_react113 = __toESM(require_react(), 1);
var useStateAndRef = /* @__PURE__ */ __name((initialValue) => {
  const [state, setState] = import_react113.default.useState(initialValue);
  const ref = import_react113.default.useRef(initialValue);
  const setStateInternal = import_react113.default.useCallback(
    (newStateOrCallback) => {
      let newValue;
      if (typeof newStateOrCallback === "function") {
        newValue = newStateOrCallback(ref.current);
      } else {
        newValue = newStateOrCallback;
      }
      setState(newValue);
      ref.current = newValue;
    },
    []
  );
  return [state, ref, setStateInternal];
}, "useStateAndRef");

// packages/cli/src/ui/hooks/useReactToolScheduler.ts
init_esbuild_shims();
var import_react114 = __toESM(require_react(), 1);
function useReactToolScheduler(onComplete, config, getPreferredEditor, onEditorClose) {
  const [toolCallsForDisplay, setToolCallsForDisplay] = (0, import_react114.useState)([]);
  const outputUpdateHandler = (0, import_react114.useCallback)(
    (toolCallId, outputChunk) => {
      setToolCallsForDisplay(
        (prevCalls) => prevCalls.map((tc) => {
          if (tc.request.callId === toolCallId && tc.status === "executing") {
            const executingTc = tc;
            return { ...executingTc, liveOutput: outputChunk };
          }
          return tc;
        })
      );
    },
    []
  );
  const allToolCallsCompleteHandler = (0, import_react114.useCallback)(
    async (completedToolCalls) => {
      await onComplete(completedToolCalls);
    },
    [onComplete]
  );
  const toolCallsUpdateHandler = (0, import_react114.useCallback)(
    (updatedCoreToolCalls) => {
      setToolCallsForDisplay(
        (prevTrackedCalls) => updatedCoreToolCalls.map((coreTc) => {
          const existingTrackedCall = prevTrackedCalls.find(
            (ptc) => ptc.request.callId === coreTc.request.callId
          );
          const responseSubmittedToGemini = existingTrackedCall?.responseSubmittedToGemini ?? false;
          if (coreTc.status === "executing") {
            return {
              ...coreTc,
              responseSubmittedToGemini,
              liveOutput: existingTrackedCall?.liveOutput,
              pid: coreTc.pid
            };
          }
          return {
            ...coreTc,
            responseSubmittedToGemini,
            liveOutput: void 0,
            pid: void 0
          };
        })
      );
    },
    [setToolCallsForDisplay]
  );
  const scheduler = (0, import_react114.useMemo)(
    () => new CoreToolScheduler({
      outputUpdateHandler,
      onAllToolCallsComplete: allToolCallsCompleteHandler,
      onToolCallsUpdate: toolCallsUpdateHandler,
      getPreferredEditor,
      config,
      onEditorClose
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    }),
    [
      config,
      outputUpdateHandler,
      allToolCallsCompleteHandler,
      toolCallsUpdateHandler,
      getPreferredEditor,
      onEditorClose
    ]
  );
  const schedule = (0, import_react114.useCallback)(
    (request4, signal) => {
      void scheduler.schedule(request4, signal);
    },
    [scheduler]
  );
  const markToolsAsSubmitted = (0, import_react114.useCallback)(
    (callIdsToMark) => {
      setToolCallsForDisplay(
        (prevCalls) => prevCalls.map(
          (tc) => callIdsToMark.includes(tc.request.callId) ? { ...tc, responseSubmittedToGemini: true } : tc
        )
      );
    },
    []
  );
  return [toolCallsForDisplay, schedule, markToolsAsSubmitted];
}
__name(useReactToolScheduler, "useReactToolScheduler");
function mapCoreStatusToDisplayStatus(coreStatus) {
  switch (coreStatus) {
    case "validating":
      return "Executing" /* Executing */;
    case "awaiting_approval":
      return "Confirming" /* Confirming */;
    case "executing":
      return "Executing" /* Executing */;
    case "success":
      return "Success" /* Success */;
    case "cancelled":
      return "Canceled" /* Canceled */;
    case "error":
      return "Error" /* Error */;
    case "scheduled":
      return "Pending" /* Pending */;
    default: {
      const exhaustiveCheck = coreStatus;
      console.warn(`Unknown core status encountered: ${exhaustiveCheck}`);
      return "Error" /* Error */;
    }
  }
}
__name(mapCoreStatusToDisplayStatus, "mapCoreStatusToDisplayStatus");
function mapToDisplay(toolOrTools) {
  const toolCalls = Array.isArray(toolOrTools) ? toolOrTools : [toolOrTools];
  const toolDisplays = toolCalls.map(
    (trackedCall) => {
      let displayName;
      let description;
      let renderOutputAsMarkdown = false;
      if (trackedCall.status === "error") {
        displayName = trackedCall.tool === void 0 ? trackedCall.request.name : trackedCall.tool.displayName;
        description = JSON.stringify(trackedCall.request.args);
      } else {
        displayName = trackedCall.tool.displayName;
        description = trackedCall.invocation.getDescription();
        renderOutputAsMarkdown = trackedCall.tool.isOutputMarkdown;
      }
      const baseDisplayProperties = {
        callId: trackedCall.request.callId,
        name: displayName,
        description,
        renderOutputAsMarkdown
      };
      switch (trackedCall.status) {
        case "success":
          return {
            ...baseDisplayProperties,
            status: mapCoreStatusToDisplayStatus(trackedCall.status),
            resultDisplay: trackedCall.response.resultDisplay,
            confirmationDetails: void 0,
            outputFile: trackedCall.response.outputFile
          };
        case "error":
          return {
            ...baseDisplayProperties,
            status: mapCoreStatusToDisplayStatus(trackedCall.status),
            resultDisplay: trackedCall.response.resultDisplay,
            confirmationDetails: void 0
          };
        case "cancelled":
          return {
            ...baseDisplayProperties,
            status: mapCoreStatusToDisplayStatus(trackedCall.status),
            resultDisplay: trackedCall.response.resultDisplay,
            confirmationDetails: void 0
          };
        case "awaiting_approval":
          return {
            ...baseDisplayProperties,
            status: mapCoreStatusToDisplayStatus(trackedCall.status),
            resultDisplay: void 0,
            confirmationDetails: trackedCall.confirmationDetails
          };
        case "executing":
          return {
            ...baseDisplayProperties,
            status: mapCoreStatusToDisplayStatus(trackedCall.status),
            resultDisplay: trackedCall.liveOutput ?? void 0,
            confirmationDetails: void 0,
            ptyId: trackedCall.pid
          };
        case "validating":
        // Fallthrough
        case "scheduled":
          return {
            ...baseDisplayProperties,
            status: mapCoreStatusToDisplayStatus(trackedCall.status),
            resultDisplay: void 0,
            confirmationDetails: void 0
          };
        default: {
          const exhaustiveCheck = trackedCall;
          return {
            callId: exhaustiveCheck.request.callId,
            name: "Unknown Tool",
            description: "Encountered an unknown tool call state.",
            status: "Error" /* Error */,
            resultDisplay: "Unknown tool call state",
            confirmationDetails: void 0,
            renderOutputAsMarkdown: false
          };
        }
      }
    }
  );
  return {
    type: "tool_group",
    tools: toolDisplays
  };
}
__name(mapToDisplay, "mapToDisplay");

// packages/cli/src/ui/hooks/useGeminiStream.ts
import { promises as fs83 } from "node:fs";
import path94 from "node:path";
var EDIT_TOOL_NAMES = /* @__PURE__ */ new Set(["replace", "write_file"]);
function showCitations(settings) {
  const enabled = settings?.merged?.ui?.showCitations;
  if (enabled !== void 0) {
    return enabled;
  }
  return true;
}
__name(showCitations, "showCitations");
var useGeminiStream = /* @__PURE__ */ __name((geminiClient, history, addItem, config, settings, onDebugMessage, handleSlashCommand2, shellModeActive, getPreferredEditor, onAuthError, performMemoryRefresh, modelSwitchedFromQuotaError, setModelSwitchedFromQuotaError, onEditorClose, onCancelSubmit, visionModelPreviewEnabled, setShellInputFocused, terminalWidth, terminalHeight, onVisionSwitchRequired, isShellFocused) => {
  const [initError, setInitError] = (0, import_react115.useState)(null);
  const abortControllerRef = (0, import_react115.useRef)(null);
  const turnCancelledRef = (0, import_react115.useRef)(false);
  const isSubmittingQueryRef = (0, import_react115.useRef)(false);
  const [isResponding, setIsResponding] = (0, import_react115.useState)(false);
  const [thought, setThought] = (0, import_react115.useState)(null);
  const [pendingHistoryItem, pendingHistoryItemRef, setPendingHistoryItem] = useStateAndRef(null);
  const processedMemoryToolsRef = (0, import_react115.useRef)(/* @__PURE__ */ new Set());
  const { startNewPrompt, getPromptCount } = useSessionStats();
  const storage = config.storage;
  const logger6 = useLogger(storage);
  const gitService = (0, import_react115.useMemo)(() => {
    if (!config.getProjectRoot()) {
      return;
    }
    return new GitService(config.getProjectRoot(), storage);
  }, [config, storage]);
  const [toolCalls, scheduleToolCalls, markToolsAsSubmitted] = useReactToolScheduler(
    async (completedToolCallsFromScheduler) => {
      if (completedToolCallsFromScheduler.length > 0) {
        addItem(
          mapToDisplay(
            completedToolCallsFromScheduler
          ),
          Date.now()
        );
        await handleCompletedTools(
          completedToolCallsFromScheduler
        );
      }
    },
    config,
    getPreferredEditor,
    onEditorClose
  );
  const pendingToolCallGroupDisplay = (0, import_react115.useMemo)(
    () => toolCalls.length ? mapToDisplay(toolCalls) : void 0,
    [toolCalls]
  );
  const activeToolPtyId = (0, import_react115.useMemo)(() => {
    const executingShellTool = toolCalls?.find(
      (tc) => tc.status === "executing" && tc.request.name === "run_shell_command"
    );
    if (executingShellTool) {
      return executingShellTool.pid;
    }
    return void 0;
  }, [toolCalls]);
  const loopDetectedRef = (0, import_react115.useRef)(false);
  const [
    loopDetectionConfirmationRequest,
    setLoopDetectionConfirmationRequest
  ] = (0, import_react115.useState)(null);
  const onExec = (0, import_react115.useCallback)(async (done) => {
    setIsResponding(true);
    await done;
    setIsResponding(false);
  }, []);
  const { handleShellCommand, activeShellPtyId } = useShellCommandProcessor(
    addItem,
    setPendingHistoryItem,
    onExec,
    onDebugMessage,
    config,
    geminiClient,
    setShellInputFocused,
    terminalWidth,
    terminalHeight
  );
  const { handleVisionSwitch, restoreOriginalModel } = useVisionAutoSwitch(
    config,
    addItem,
    visionModelPreviewEnabled,
    onVisionSwitchRequired
  );
  const activePtyId = activeShellPtyId || activeToolPtyId;
  (0, import_react115.useEffect)(() => {
    if (!activePtyId) {
      setShellInputFocused(false);
    }
  }, [activePtyId, setShellInputFocused]);
  const streamingState = (0, import_react115.useMemo)(() => {
    if (toolCalls.some((tc) => tc.status === "awaiting_approval")) {
      return "waiting_for_confirmation" /* WaitingForConfirmation */;
    }
    if (isResponding || toolCalls.some(
      (tc) => tc.status === "executing" || tc.status === "scheduled" || tc.status === "validating" || (tc.status === "success" || tc.status === "error" || tc.status === "cancelled") && !tc.responseSubmittedToGemini
    )) {
      return "responding" /* Responding */;
    }
    return "idle" /* Idle */;
  }, [isResponding, toolCalls]);
  (0, import_react115.useEffect)(() => {
    if (config.getApprovalMode() === ApprovalMode.YOLO && streamingState === "idle" /* Idle */) {
      const lastUserMessageIndex = history.findLastIndex(
        (item) => item.type === "user" /* USER */
      );
      const turnCount = lastUserMessageIndex === -1 ? 0 : history.length - lastUserMessageIndex;
      if (turnCount > 0) {
        logConversationFinishedEvent(
          config,
          new ConversationFinishedEvent(config.getApprovalMode(), turnCount)
        );
      }
    }
  }, [streamingState, config, history]);
  const cancelOngoingRequest = (0, import_react115.useCallback)(() => {
    if (streamingState !== "responding" /* Responding */) {
      return;
    }
    if (turnCancelledRef.current) {
      return;
    }
    turnCancelledRef.current = true;
    isSubmittingQueryRef.current = false;
    abortControllerRef.current?.abort();
    const prompt_id = config.getSessionId() + "########" + getPromptCount();
    const cancellationEvent = new ApiCancelEvent(
      config.getModel(),
      prompt_id,
      config.getContentGeneratorConfig()?.authType
    );
    logApiCancel(config, cancellationEvent);
    if (pendingHistoryItemRef.current) {
      addItem(pendingHistoryItemRef.current, Date.now());
    }
    addItem(
      {
        type: "info" /* INFO */,
        text: "Request cancelled."
      },
      Date.now()
    );
    setPendingHistoryItem(null);
    onCancelSubmit();
    setIsResponding(false);
    setShellInputFocused(false);
  }, [
    streamingState,
    addItem,
    setPendingHistoryItem,
    onCancelSubmit,
    pendingHistoryItemRef,
    setShellInputFocused,
    config,
    getPromptCount
  ]);
  useKeypress(
    (key) => {
      if (key.name === "escape" && !isShellFocused) {
        cancelOngoingRequest();
      }
    },
    { isActive: streamingState === "responding" /* Responding */ }
  );
  const prepareQueryForGemini = (0, import_react115.useCallback)(
    async (query, userMessageTimestamp, abortSignal, prompt_id) => {
      if (turnCancelledRef.current) {
        return { queryToSend: null, shouldProceed: false };
      }
      if (typeof query === "string" && query.trim().length === 0) {
        return { queryToSend: null, shouldProceed: false };
      }
      let localQueryToSendToGemini = null;
      if (typeof query === "string") {
        const trimmedQuery = query.trim();
        onDebugMessage(`User query: '${trimmedQuery}'`);
        await logger6?.logMessage(MessageSenderType.USER, trimmedQuery);
        const slashCommandResult = isSlashCommand(trimmedQuery) ? await handleSlashCommand2(trimmedQuery) : false;
        if (slashCommandResult) {
          switch (slashCommandResult.type) {
            case "schedule_tool": {
              const { toolName, toolArgs } = slashCommandResult;
              const toolCallRequest = {
                callId: `${toolName}-${Date.now()}-${Math.random().toString(16).slice(2)}`,
                name: toolName,
                args: toolArgs,
                isClientInitiated: true,
                prompt_id
              };
              scheduleToolCalls([toolCallRequest], abortSignal);
              return { queryToSend: null, shouldProceed: false };
            }
            case "submit_prompt": {
              localQueryToSendToGemini = slashCommandResult.content;
              return {
                queryToSend: localQueryToSendToGemini,
                shouldProceed: true
              };
            }
            case "handled": {
              return { queryToSend: null, shouldProceed: false };
            }
            default: {
              const unreachable = slashCommandResult;
              throw new Error(
                `Unhandled slash command result type: ${unreachable}`
              );
            }
          }
        }
        if (shellModeActive && handleShellCommand(trimmedQuery, abortSignal)) {
          return { queryToSend: null, shouldProceed: false };
        }
        if (isAtCommand(trimmedQuery)) {
          const atCommandResult = await handleAtCommand({
            query: trimmedQuery,
            config,
            addItem,
            onDebugMessage,
            messageId: userMessageTimestamp,
            signal: abortSignal
          });
          addItem(
            { type: "user" /* USER */, text: trimmedQuery },
            userMessageTimestamp
          );
          if (!atCommandResult.shouldProceed) {
            return { queryToSend: null, shouldProceed: false };
          }
          localQueryToSendToGemini = atCommandResult.processedQuery;
        } else {
          addItem(
            { type: "user" /* USER */, text: trimmedQuery },
            userMessageTimestamp
          );
          localQueryToSendToGemini = trimmedQuery;
        }
      } else {
        localQueryToSendToGemini = query;
      }
      if (localQueryToSendToGemini === null) {
        onDebugMessage(
          "Query processing resulted in null, not sending to Gemini."
        );
        return { queryToSend: null, shouldProceed: false };
      }
      return { queryToSend: localQueryToSendToGemini, shouldProceed: true };
    },
    [
      config,
      addItem,
      onDebugMessage,
      handleShellCommand,
      handleSlashCommand2,
      logger6,
      shellModeActive,
      scheduleToolCalls
    ]
  );
  const handleContentEvent = (0, import_react115.useCallback)(
    (eventValue, currentGeminiMessageBuffer, userMessageTimestamp) => {
      if (turnCancelledRef.current) {
        return "";
      }
      let newGeminiMessageBuffer = currentGeminiMessageBuffer + eventValue;
      if (pendingHistoryItemRef.current?.type !== "gemini" && pendingHistoryItemRef.current?.type !== "gemini_content") {
        if (pendingHistoryItemRef.current) {
          addItem(pendingHistoryItemRef.current, userMessageTimestamp);
        }
        setPendingHistoryItem({ type: "gemini", text: "" });
        newGeminiMessageBuffer = eventValue;
      }
      const splitPoint = findLastSafeSplitPoint(newGeminiMessageBuffer);
      if (splitPoint === newGeminiMessageBuffer.length) {
        setPendingHistoryItem((item) => ({
          type: item?.type,
          text: newGeminiMessageBuffer
        }));
      } else {
        const beforeText = newGeminiMessageBuffer.substring(0, splitPoint);
        const afterText = newGeminiMessageBuffer.substring(splitPoint);
        addItem(
          {
            type: pendingHistoryItemRef.current?.type,
            text: beforeText
          },
          userMessageTimestamp
        );
        setPendingHistoryItem({ type: "gemini_content", text: afterText });
        newGeminiMessageBuffer = afterText;
      }
      return newGeminiMessageBuffer;
    },
    [addItem, pendingHistoryItemRef, setPendingHistoryItem]
  );
  const handleUserCancelledEvent = (0, import_react115.useCallback)(
    (userMessageTimestamp) => {
      if (turnCancelledRef.current) {
        return;
      }
      if (pendingHistoryItemRef.current) {
        if (pendingHistoryItemRef.current.type === "tool_group") {
          const updatedTools = pendingHistoryItemRef.current.tools.map(
            (tool) => tool.status === "Pending" /* Pending */ || tool.status === "Confirming" /* Confirming */ || tool.status === "Executing" /* Executing */ ? { ...tool, status: "Canceled" /* Canceled */ } : tool
          );
          const pendingItem = {
            ...pendingHistoryItemRef.current,
            tools: updatedTools
          };
          addItem(pendingItem, userMessageTimestamp);
        } else {
          addItem(pendingHistoryItemRef.current, userMessageTimestamp);
        }
        setPendingHistoryItem(null);
      }
      addItem(
        { type: "info" /* INFO */, text: "User cancelled the request." },
        userMessageTimestamp
      );
      setIsResponding(false);
      setThought(null);
    },
    [addItem, pendingHistoryItemRef, setPendingHistoryItem, setThought]
  );
  const handleErrorEvent = (0, import_react115.useCallback)(
    (eventValue, userMessageTimestamp) => {
      if (pendingHistoryItemRef.current) {
        addItem(pendingHistoryItemRef.current, userMessageTimestamp);
        setPendingHistoryItem(null);
      }
      addItem(
        {
          type: "error" /* ERROR */,
          text: parseAndFormatApiError(
            eventValue.error,
            config.getContentGeneratorConfig()?.authType,
            void 0,
            config.getModel(),
            DEFAULT_GEMINI_FLASH_MODEL
          )
        },
        userMessageTimestamp
      );
      setThought(null);
    },
    [addItem, pendingHistoryItemRef, setPendingHistoryItem, config, setThought]
  );
  const handleCitationEvent = (0, import_react115.useCallback)(
    (text, userMessageTimestamp) => {
      if (!showCitations(settings)) {
        return;
      }
      if (pendingHistoryItemRef.current) {
        addItem(pendingHistoryItemRef.current, userMessageTimestamp);
        setPendingHistoryItem(null);
      }
      addItem({ type: "info" /* INFO */, text }, userMessageTimestamp);
    },
    [addItem, pendingHistoryItemRef, setPendingHistoryItem, settings]
  );
  const handleFinishedEvent = (0, import_react115.useCallback)(
    (event, userMessageTimestamp) => {
      const finishReason = event.value.reason;
      if (!finishReason) {
        return;
      }
      const finishReasonMessages = {
        [FinishReason.FINISH_REASON_UNSPECIFIED]: void 0,
        [FinishReason.STOP]: void 0,
        [FinishReason.MAX_TOKENS]: "Response truncated due to token limits.",
        [FinishReason.SAFETY]: "Response stopped due to safety reasons.",
        [FinishReason.RECITATION]: "Response stopped due to recitation policy.",
        [FinishReason.LANGUAGE]: "Response stopped due to unsupported language.",
        [FinishReason.BLOCKLIST]: "Response stopped due to forbidden terms.",
        [FinishReason.PROHIBITED_CONTENT]: "Response stopped due to prohibited content.",
        [FinishReason.SPII]: "Response stopped due to sensitive personally identifiable information.",
        [FinishReason.OTHER]: "Response stopped for other reasons.",
        [FinishReason.MALFORMED_FUNCTION_CALL]: "Response stopped due to malformed function call.",
        [FinishReason.IMAGE_SAFETY]: "Response stopped due to image safety violations.",
        [FinishReason.UNEXPECTED_TOOL_CALL]: "Response stopped due to unexpected tool call."
      };
      const message = finishReasonMessages[finishReason];
      if (message) {
        addItem(
          {
            type: "info",
            text: `\u26A0\uFE0F  ${message}`
          },
          userMessageTimestamp
        );
      }
    },
    [addItem]
  );
  const handleChatCompressionEvent = (0, import_react115.useCallback)(
    (eventValue, userMessageTimestamp) => {
      if (pendingHistoryItemRef.current) {
        addItem(pendingHistoryItemRef.current, userMessageTimestamp);
        setPendingHistoryItem(null);
      }
      return addItem(
        {
          type: "info",
          text: `IMPORTANT: This conversation approached the input token limit for ${config.getModel()}. A compressed context will be sent for future messages (compressed from: ${eventValue?.originalTokenCount ?? "unknown"} to ${eventValue?.newTokenCount ?? "unknown"} tokens).`
        },
        Date.now()
      );
    },
    [addItem, config, pendingHistoryItemRef, setPendingHistoryItem]
  );
  const handleMaxSessionTurnsEvent = (0, import_react115.useCallback)(
    () => addItem(
      {
        type: "info",
        text: `The session has reached the maximum number of turns: ${config.getMaxSessionTurns()}. Please update this limit in your setting.json file.`
      },
      Date.now()
    ),
    [addItem, config]
  );
  const handleSessionTokenLimitExceededEvent = (0, import_react115.useCallback)(
    (value) => addItem(
      {
        type: "error",
        text: `\u{1F6AB} Session token limit exceeded: ${value.currentTokens.toLocaleString()} tokens > ${value.limit.toLocaleString()} limit.

\u{1F4A1} Solutions:
   \u2022 Start a new session: Use /clear command
   \u2022 Increase limit: Add "sessionTokenLimit": (e.g., 128000) to your settings.json
   \u2022 Compress history: Use /compress command to compress history`
      },
      Date.now()
    ),
    [addItem]
  );
  const handleLoopDetectionConfirmation = (0, import_react115.useCallback)(
    (result) => {
      setLoopDetectionConfirmationRequest(null);
      if (result.userSelection === "disable") {
        config.getGeminiClient().getLoopDetectionService().disableForSession();
        addItem(
          {
            type: "info",
            text: `Loop detection has been disabled for this session. Please try your request again.`
          },
          Date.now()
        );
      } else {
        addItem(
          {
            type: "info",
            text: `A potential loop was detected. This can happen due to repetitive tool calls or other model behavior. The request has been halted.`
          },
          Date.now()
        );
      }
    },
    [config, addItem]
  );
  const handleLoopDetectedEvent = (0, import_react115.useCallback)(() => {
    setLoopDetectionConfirmationRequest({
      onComplete: handleLoopDetectionConfirmation
    });
  }, [handleLoopDetectionConfirmation]);
  const processGeminiStreamEvents = (0, import_react115.useCallback)(
    async (stream2, userMessageTimestamp, signal) => {
      let geminiMessageBuffer = "";
      const toolCallRequests = [];
      for await (const event of stream2) {
        switch (event.type) {
          case GeminiEventType.Thought:
            setThought(event.value);
            break;
          case GeminiEventType.Content:
            geminiMessageBuffer = handleContentEvent(
              event.value,
              geminiMessageBuffer,
              userMessageTimestamp
            );
            break;
          case GeminiEventType.ToolCallRequest:
            toolCallRequests.push(event.value);
            break;
          case GeminiEventType.UserCancelled:
            handleUserCancelledEvent(userMessageTimestamp);
            break;
          case GeminiEventType.Error:
            handleErrorEvent(event.value, userMessageTimestamp);
            break;
          case GeminiEventType.ChatCompressed:
            handleChatCompressionEvent(event.value, userMessageTimestamp);
            break;
          case GeminiEventType.ToolCallConfirmation:
          case GeminiEventType.ToolCallResponse:
            break;
          case GeminiEventType.MaxSessionTurns:
            handleMaxSessionTurnsEvent();
            break;
          case GeminiEventType.SessionTokenLimitExceeded:
            handleSessionTokenLimitExceededEvent(event.value);
            break;
          case GeminiEventType.Finished:
            handleFinishedEvent(
              event,
              userMessageTimestamp
            );
            break;
          case GeminiEventType.Citation:
            handleCitationEvent(event.value, userMessageTimestamp);
            break;
          case GeminiEventType.LoopDetected:
            loopDetectedRef.current = true;
            break;
          case GeminiEventType.Retry:
            break;
          default: {
            const unreachable = event;
            return unreachable;
          }
        }
      }
      if (toolCallRequests.length > 0) {
        scheduleToolCalls(toolCallRequests, signal);
      }
      return 0 /* Completed */;
    },
    [
      handleContentEvent,
      handleUserCancelledEvent,
      handleErrorEvent,
      scheduleToolCalls,
      handleChatCompressionEvent,
      handleFinishedEvent,
      handleMaxSessionTurnsEvent,
      handleSessionTokenLimitExceededEvent,
      handleCitationEvent
    ]
  );
  const submitQuery = (0, import_react115.useCallback)(
    async (query, options2, prompt_id) => {
      if (isSubmittingQueryRef.current && !options2?.isContinuation) {
        return;
      }
      if ((streamingState === "responding" /* Responding */ || streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */) && !options2?.isContinuation)
        return;
      isSubmittingQueryRef.current = true;
      const userMessageTimestamp = Date.now();
      if (!options2?.isContinuation) {
        setModelSwitchedFromQuotaError(false);
        config.setQuotaErrorOccurred(false);
      }
      abortControllerRef.current = new AbortController();
      const abortSignal = abortControllerRef.current.signal;
      turnCancelledRef.current = false;
      if (!prompt_id) {
        prompt_id = config.getSessionId() + "########" + getPromptCount();
      }
      return promptIdContext.run(prompt_id, async () => {
        const { queryToSend, shouldProceed } = await prepareQueryForGemini(
          query,
          userMessageTimestamp,
          abortSignal,
          prompt_id
        );
        if (!shouldProceed || queryToSend === null) {
          isSubmittingQueryRef.current = false;
          return;
        }
        const visionSwitchResult = await handleVisionSwitch(
          queryToSend,
          userMessageTimestamp,
          options2?.isContinuation || false
        );
        if (!visionSwitchResult.shouldProceed) {
          isSubmittingQueryRef.current = false;
          return;
        }
        const finalQueryToSend = queryToSend;
        if (!options2?.isContinuation) {
          if (typeof queryToSend === "string") {
            const promptText = queryToSend;
            logUserPrompt(
              config,
              new UserPromptEvent(
                promptText.length,
                prompt_id,
                config.getContentGeneratorConfig()?.authType,
                promptText
              )
            );
          }
          startNewPrompt();
          setThought(null);
        }
        setIsResponding(true);
        setInitError(null);
        try {
          const stream2 = geminiClient.sendMessageStream(
            finalQueryToSend,
            abortSignal,
            prompt_id
          );
          const processingStatus = await processGeminiStreamEvents(
            stream2,
            userMessageTimestamp,
            abortSignal
          );
          if (processingStatus === 1 /* UserCancelled */) {
            restoreOriginalModel().catch((error) => {
              console.error("Failed to restore original model:", error);
            });
            isSubmittingQueryRef.current = false;
            return;
          }
          if (pendingHistoryItemRef.current) {
            addItem(pendingHistoryItemRef.current, userMessageTimestamp);
            setPendingHistoryItem(null);
          }
          if (loopDetectedRef.current) {
            loopDetectedRef.current = false;
            handleLoopDetectedEvent();
          }
          restoreOriginalModel().catch((error) => {
            console.error("Failed to restore original model:", error);
          });
        } catch (error) {
          restoreOriginalModel().catch((error2) => {
            console.error("Failed to restore original model:", error2);
          });
          if (error instanceof UnauthorizedError) {
            onAuthError("Session expired or is unauthorized.");
          } else if (!isNodeError(error) || error.name !== "AbortError") {
            addItem(
              {
                type: "error" /* ERROR */,
                text: parseAndFormatApiError(
                  getErrorMessage(error) || "Unknown error",
                  config.getContentGeneratorConfig()?.authType,
                  void 0,
                  config.getModel(),
                  DEFAULT_GEMINI_FLASH_MODEL
                )
              },
              userMessageTimestamp
            );
          }
        } finally {
          setIsResponding(false);
          isSubmittingQueryRef.current = false;
        }
      });
    },
    [
      streamingState,
      setModelSwitchedFromQuotaError,
      prepareQueryForGemini,
      processGeminiStreamEvents,
      pendingHistoryItemRef,
      addItem,
      setPendingHistoryItem,
      setInitError,
      geminiClient,
      onAuthError,
      config,
      startNewPrompt,
      getPromptCount,
      handleLoopDetectedEvent,
      handleVisionSwitch,
      restoreOriginalModel
    ]
  );
  const handleApprovalModeChange = (0, import_react115.useCallback)(
    async (newApprovalMode) => {
      if (newApprovalMode === ApprovalMode.YOLO || newApprovalMode === ApprovalMode.AUTO_EDIT) {
        let awaitingApprovalCalls = toolCalls.filter(
          (call) => call.status === "awaiting_approval"
        );
        if (newApprovalMode === ApprovalMode.AUTO_EDIT) {
          awaitingApprovalCalls = awaitingApprovalCalls.filter(
            (call) => EDIT_TOOL_NAMES.has(call.request.name)
          );
        }
        for (const call of awaitingApprovalCalls) {
          if (call.confirmationDetails?.onConfirm) {
            try {
              await call.confirmationDetails.onConfirm(
                ToolConfirmationOutcome.ProceedOnce
              );
            } catch (error) {
              console.error(
                `Failed to auto-approve tool call ${call.request.callId}:`,
                error
              );
            }
          }
        }
      }
    },
    [toolCalls]
  );
  const handleCompletedTools = (0, import_react115.useCallback)(
    async (completedToolCallsFromScheduler) => {
      if (isResponding) {
        return;
      }
      const completedAndReadyToSubmitTools = completedToolCallsFromScheduler.filter(
        (tc) => {
          const isTerminalState = tc.status === "success" || tc.status === "error" || tc.status === "cancelled";
          if (isTerminalState) {
            const completedOrCancelledCall = tc;
            return completedOrCancelledCall.response?.responseParts !== void 0;
          }
          return false;
        }
      );
      const clientTools = completedAndReadyToSubmitTools.filter(
        (t2) => t2.request.isClientInitiated
      );
      if (clientTools.length > 0) {
        markToolsAsSubmitted(clientTools.map((t2) => t2.request.callId));
      }
      const newSuccessfulMemorySaves = completedAndReadyToSubmitTools.filter(
        (t2) => t2.request.name === "save_memory" && t2.status === "success" && !processedMemoryToolsRef.current.has(t2.request.callId)
      );
      if (newSuccessfulMemorySaves.length > 0) {
        void performMemoryRefresh();
        newSuccessfulMemorySaves.forEach(
          (t2) => processedMemoryToolsRef.current.add(t2.request.callId)
        );
      }
      const geminiTools = completedAndReadyToSubmitTools.filter(
        (t2) => !t2.request.isClientInitiated
      );
      if (geminiTools.length === 0) {
        return;
      }
      const allToolsCancelled = geminiTools.every(
        (tc) => tc.status === "cancelled"
      );
      if (allToolsCancelled) {
        if (geminiClient) {
          const combinedParts = geminiTools.flatMap(
            (toolCall) => toolCall.response.responseParts
          );
          geminiClient.addHistory({
            role: "user",
            parts: combinedParts
          });
        }
        const callIdsToMarkAsSubmitted2 = geminiTools.map(
          (toolCall) => toolCall.request.callId
        );
        markToolsAsSubmitted(callIdsToMarkAsSubmitted2);
        return;
      }
      const responsesToSend = geminiTools.flatMap(
        (toolCall) => toolCall.response.responseParts
      );
      const callIdsToMarkAsSubmitted = geminiTools.map(
        (toolCall) => toolCall.request.callId
      );
      const prompt_ids = geminiTools.map(
        (toolCall) => toolCall.request.prompt_id
      );
      markToolsAsSubmitted(callIdsToMarkAsSubmitted);
      if (modelSwitchedFromQuotaError) {
        return;
      }
      submitQuery(
        responsesToSend,
        {
          isContinuation: true
        },
        prompt_ids[0]
      );
    },
    [
      isResponding,
      submitQuery,
      markToolsAsSubmitted,
      geminiClient,
      performMemoryRefresh,
      modelSwitchedFromQuotaError
    ]
  );
  const pendingHistoryItems = (0, import_react115.useMemo)(
    () => [pendingHistoryItem, pendingToolCallGroupDisplay].filter(
      (i) => i !== void 0 && i !== null
    ),
    [pendingHistoryItem, pendingToolCallGroupDisplay]
  );
  (0, import_react115.useEffect)(() => {
    const saveRestorableToolCalls = /* @__PURE__ */ __name(async () => {
      if (!config.getCheckpointingEnabled()) {
        return;
      }
      const restorableToolCalls = toolCalls.filter(
        (toolCall) => EDIT_TOOL_NAMES.has(toolCall.request.name) && toolCall.status === "awaiting_approval"
      );
      if (restorableToolCalls.length > 0) {
        const checkpointDir = storage.getProjectTempCheckpointsDir();
        if (!checkpointDir) {
          return;
        }
        try {
          await fs83.mkdir(checkpointDir, { recursive: true });
        } catch (error) {
          if (!isNodeError(error) || error.code !== "EEXIST") {
            onDebugMessage(
              `Failed to create checkpoint directory: ${getErrorMessage(error)}`
            );
            return;
          }
        }
        for (const toolCall of restorableToolCalls) {
          const filePath = toolCall.request.args["file_path"];
          if (!filePath) {
            onDebugMessage(
              `Skipping restorable tool call due to missing file_path: ${toolCall.request.name}`
            );
            continue;
          }
          try {
            if (!gitService) {
              onDebugMessage(
                `Checkpointing is enabled but Git service is not available. Failed to create snapshot for ${filePath}. Ensure Git is installed and working properly.`
              );
              continue;
            }
            let commitHash;
            try {
              commitHash = await gitService.createFileSnapshot(
                `Snapshot for ${toolCall.request.name}`
              );
            } catch (error) {
              onDebugMessage(
                `Failed to create new snapshot: ${getErrorMessage(error)}. Attempting to use current commit.`
              );
            }
            if (!commitHash) {
              commitHash = await gitService.getCurrentCommitHash();
            }
            if (!commitHash) {
              onDebugMessage(
                `Failed to create snapshot for ${filePath}. Checkpointing may not be working properly. Ensure Git is installed and the project directory is accessible.`
              );
              continue;
            }
            const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-").replace(/\./g, "_");
            const toolName = toolCall.request.name;
            const fileName = path94.basename(filePath);
            const toolCallWithSnapshotFileName = `${timestamp}-${fileName}-${toolName}.json`;
            const clientHistory = await geminiClient?.getHistory();
            const toolCallWithSnapshotFilePath = path94.join(
              checkpointDir,
              toolCallWithSnapshotFileName
            );
            await fs83.writeFile(
              toolCallWithSnapshotFilePath,
              JSON.stringify(
                {
                  history,
                  clientHistory,
                  toolCall: {
                    name: toolCall.request.name,
                    args: toolCall.request.args
                  },
                  commitHash,
                  filePath
                },
                null,
                2
              )
            );
          } catch (error) {
            onDebugMessage(
              `Failed to create checkpoint for ${filePath}: ${getErrorMessage(
                error
              )}. This may indicate a problem with Git or file system permissions.`
            );
          }
        }
      }
    }, "saveRestorableToolCalls");
    saveRestorableToolCalls();
  }, [
    toolCalls,
    config,
    onDebugMessage,
    gitService,
    history,
    geminiClient,
    storage
  ]);
  return {
    streamingState,
    submitQuery,
    initError,
    pendingHistoryItems,
    thought,
    cancelOngoingRequest,
    pendingToolCalls: toolCalls,
    handleApprovalModeChange,
    activePtyId,
    loopDetectionConfirmationRequest
  };
}, "useGeminiStream");

// packages/cli/src/ui/hooks/vim.ts
init_esbuild_shims();
var import_react116 = __toESM(require_react(), 1);
var DIGIT_MULTIPLIER = 10;
var DEFAULT_COUNT = 1;
var DIGIT_1_TO_9 = /^[1-9]$/;
var CMD_TYPES = {
  DELETE_WORD_FORWARD: "dw",
  DELETE_WORD_BACKWARD: "db",
  DELETE_WORD_END: "de",
  CHANGE_WORD_FORWARD: "cw",
  CHANGE_WORD_BACKWARD: "cb",
  CHANGE_WORD_END: "ce",
  DELETE_CHAR: "x",
  DELETE_LINE: "dd",
  CHANGE_LINE: "cc",
  DELETE_TO_EOL: "D",
  CHANGE_TO_EOL: "C",
  CHANGE_MOVEMENT: {
    LEFT: "ch",
    DOWN: "cj",
    UP: "ck",
    RIGHT: "cl"
  }
};
var createClearPendingState = /* @__PURE__ */ __name(() => ({
  count: 0,
  pendingOperator: null
}), "createClearPendingState");
var initialVimState = {
  mode: "NORMAL",
  count: 0,
  pendingOperator: null,
  lastCommand: null
};
var vimReducer = /* @__PURE__ */ __name((state, action) => {
  switch (action.type) {
    case "SET_MODE":
      return { ...state, mode: action.mode };
    case "SET_COUNT":
      return { ...state, count: action.count };
    case "INCREMENT_COUNT":
      return { ...state, count: state.count * DIGIT_MULTIPLIER + action.digit };
    case "CLEAR_COUNT":
      return { ...state, count: 0 };
    case "SET_PENDING_OPERATOR":
      return { ...state, pendingOperator: action.operator };
    case "SET_LAST_COMMAND":
      return { ...state, lastCommand: action.command };
    case "CLEAR_PENDING_STATES":
      return {
        ...state,
        ...createClearPendingState()
      };
    case "ESCAPE_TO_NORMAL":
      return {
        ...state,
        ...createClearPendingState()
      };
    default:
      return state;
  }
}, "vimReducer");
function useVim(buffer, onSubmit) {
  const { vimEnabled, vimMode, setVimMode } = useVimMode();
  const [state, dispatch] = (0, import_react116.useReducer)(vimReducer, initialVimState);
  (0, import_react116.useEffect)(() => {
    dispatch({ type: "SET_MODE", mode: vimMode });
  }, [vimMode]);
  const updateMode = (0, import_react116.useCallback)(
    (mode) => {
      setVimMode(mode);
      dispatch({ type: "SET_MODE", mode });
    },
    [setVimMode]
  );
  const getCurrentCount = (0, import_react116.useCallback)(
    () => state.count || DEFAULT_COUNT,
    [state.count]
  );
  const executeCommand = (0, import_react116.useCallback)(
    (cmdType, count) => {
      switch (cmdType) {
        case CMD_TYPES.DELETE_WORD_FORWARD: {
          buffer.vimDeleteWordForward(count);
          break;
        }
        case CMD_TYPES.DELETE_WORD_BACKWARD: {
          buffer.vimDeleteWordBackward(count);
          break;
        }
        case CMD_TYPES.DELETE_WORD_END: {
          buffer.vimDeleteWordEnd(count);
          break;
        }
        case CMD_TYPES.CHANGE_WORD_FORWARD: {
          buffer.vimChangeWordForward(count);
          updateMode("INSERT");
          break;
        }
        case CMD_TYPES.CHANGE_WORD_BACKWARD: {
          buffer.vimChangeWordBackward(count);
          updateMode("INSERT");
          break;
        }
        case CMD_TYPES.CHANGE_WORD_END: {
          buffer.vimChangeWordEnd(count);
          updateMode("INSERT");
          break;
        }
        case CMD_TYPES.DELETE_CHAR: {
          buffer.vimDeleteChar(count);
          break;
        }
        case CMD_TYPES.DELETE_LINE: {
          buffer.vimDeleteLine(count);
          break;
        }
        case CMD_TYPES.CHANGE_LINE: {
          buffer.vimChangeLine(count);
          updateMode("INSERT");
          break;
        }
        case CMD_TYPES.CHANGE_MOVEMENT.LEFT:
        case CMD_TYPES.CHANGE_MOVEMENT.DOWN:
        case CMD_TYPES.CHANGE_MOVEMENT.UP:
        case CMD_TYPES.CHANGE_MOVEMENT.RIGHT: {
          const movementMap = {
            [CMD_TYPES.CHANGE_MOVEMENT.LEFT]: "h",
            [CMD_TYPES.CHANGE_MOVEMENT.DOWN]: "j",
            [CMD_TYPES.CHANGE_MOVEMENT.UP]: "k",
            [CMD_TYPES.CHANGE_MOVEMENT.RIGHT]: "l"
          };
          const movementType = movementMap[cmdType];
          if (movementType) {
            buffer.vimChangeMovement(movementType, count);
            updateMode("INSERT");
          }
          break;
        }
        case CMD_TYPES.DELETE_TO_EOL: {
          buffer.vimDeleteToEndOfLine();
          break;
        }
        case CMD_TYPES.CHANGE_TO_EOL: {
          buffer.vimChangeToEndOfLine();
          updateMode("INSERT");
          break;
        }
        default:
          return false;
      }
      return true;
    },
    [buffer, updateMode]
  );
  const handleInsertModeInput = (0, import_react116.useCallback)(
    (normalizedKey) => {
      if (normalizedKey.name === "escape") {
        buffer.vimEscapeInsertMode();
        dispatch({ type: "ESCAPE_TO_NORMAL" });
        updateMode("NORMAL");
        return true;
      }
      if (normalizedKey.name === "tab" || normalizedKey.name === "return" && !normalizedKey.ctrl || normalizedKey.name === "up" || normalizedKey.name === "down" || normalizedKey.ctrl && normalizedKey.name === "r") {
        return false;
      }
      if (normalizedKey.ctrl && normalizedKey.name === "v") {
        return false;
      }
      if (normalizedKey.sequence === "!" && buffer.text.length === 0) {
        return false;
      }
      if (normalizedKey.name === "return" && !normalizedKey.ctrl && !normalizedKey.meta) {
        if (buffer.text.trim() && onSubmit) {
          const submittedValue = buffer.text;
          buffer.setText("");
          onSubmit(submittedValue);
          return true;
        }
        return true;
      }
      buffer.handleInput(normalizedKey);
      return true;
    },
    [buffer, dispatch, updateMode, onSubmit]
  );
  const normalizeKey = (0, import_react116.useCallback)(
    (key) => ({
      name: key.name || "",
      sequence: key.sequence || "",
      ctrl: key.ctrl || false,
      meta: key.meta || false,
      shift: key.shift || false,
      paste: key.paste || false
    }),
    []
  );
  const handleChangeMovement = (0, import_react116.useCallback)(
    (movement) => {
      const count = getCurrentCount();
      dispatch({ type: "CLEAR_COUNT" });
      buffer.vimChangeMovement(movement, count);
      updateMode("INSERT");
      const cmdTypeMap = {
        h: CMD_TYPES.CHANGE_MOVEMENT.LEFT,
        j: CMD_TYPES.CHANGE_MOVEMENT.DOWN,
        k: CMD_TYPES.CHANGE_MOVEMENT.UP,
        l: CMD_TYPES.CHANGE_MOVEMENT.RIGHT
      };
      dispatch({
        type: "SET_LAST_COMMAND",
        command: { type: cmdTypeMap[movement], count }
      });
      dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
      return true;
    },
    [getCurrentCount, dispatch, buffer, updateMode]
  );
  const handleOperatorMotion = (0, import_react116.useCallback)(
    (operator2, motion) => {
      const count = getCurrentCount();
      const commandMap = {
        d: {
          w: CMD_TYPES.DELETE_WORD_FORWARD,
          b: CMD_TYPES.DELETE_WORD_BACKWARD,
          e: CMD_TYPES.DELETE_WORD_END
        },
        c: {
          w: CMD_TYPES.CHANGE_WORD_FORWARD,
          b: CMD_TYPES.CHANGE_WORD_BACKWARD,
          e: CMD_TYPES.CHANGE_WORD_END
        }
      };
      const cmdType = commandMap[operator2][motion];
      executeCommand(cmdType, count);
      dispatch({
        type: "SET_LAST_COMMAND",
        command: { type: cmdType, count }
      });
      dispatch({ type: "CLEAR_COUNT" });
      dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
      return true;
    },
    [getCurrentCount, executeCommand, dispatch]
  );
  const handleInput = (0, import_react116.useCallback)(
    (key) => {
      if (!vimEnabled) {
        return false;
      }
      let normalizedKey;
      try {
        normalizedKey = normalizeKey(key);
      } catch (error) {
        console.warn("Malformed key input in vim mode:", key, error);
        return false;
      }
      if (state.mode === "INSERT") {
        return handleInsertModeInput(normalizedKey);
      }
      if (state.mode === "NORMAL") {
        if (normalizedKey.name === "escape") {
          if (state.pendingOperator) {
            dispatch({ type: "CLEAR_PENDING_STATES" });
            return true;
          }
          return false;
        }
        if (DIGIT_1_TO_9.test(normalizedKey.sequence) || normalizedKey.sequence === "0" && state.count > 0) {
          dispatch({
            type: "INCREMENT_COUNT",
            digit: parseInt(normalizedKey.sequence, 10)
          });
          return true;
        }
        const repeatCount = getCurrentCount();
        switch (normalizedKey.sequence) {
          case "h": {
            if (state.pendingOperator === "c") {
              return handleChangeMovement("h");
            }
            buffer.vimMoveLeft(repeatCount);
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "j": {
            if (state.pendingOperator === "c") {
              return handleChangeMovement("j");
            }
            buffer.vimMoveDown(repeatCount);
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "k": {
            if (state.pendingOperator === "c") {
              return handleChangeMovement("k");
            }
            buffer.vimMoveUp(repeatCount);
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "l": {
            if (state.pendingOperator === "c") {
              return handleChangeMovement("l");
            }
            buffer.vimMoveRight(repeatCount);
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "w": {
            if (state.pendingOperator === "d") {
              return handleOperatorMotion("d", "w");
            }
            if (state.pendingOperator === "c") {
              return handleOperatorMotion("c", "w");
            }
            buffer.vimMoveWordForward(repeatCount);
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "b": {
            if (state.pendingOperator === "d") {
              return handleOperatorMotion("d", "b");
            }
            if (state.pendingOperator === "c") {
              return handleOperatorMotion("c", "b");
            }
            buffer.vimMoveWordBackward(repeatCount);
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "e": {
            if (state.pendingOperator === "d") {
              return handleOperatorMotion("d", "e");
            }
            if (state.pendingOperator === "c") {
              return handleOperatorMotion("c", "e");
            }
            buffer.vimMoveWordEnd(repeatCount);
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "x": {
            buffer.vimDeleteChar(repeatCount);
            dispatch({
              type: "SET_LAST_COMMAND",
              command: { type: CMD_TYPES.DELETE_CHAR, count: repeatCount }
            });
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "i": {
            buffer.vimInsertAtCursor();
            updateMode("INSERT");
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "a": {
            buffer.vimAppendAtCursor();
            updateMode("INSERT");
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "o": {
            buffer.vimOpenLineBelow();
            updateMode("INSERT");
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "O": {
            buffer.vimOpenLineAbove();
            updateMode("INSERT");
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "0": {
            buffer.vimMoveToLineStart();
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "$": {
            buffer.vimMoveToLineEnd();
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "^": {
            buffer.vimMoveToFirstNonWhitespace();
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "g": {
            if (state.pendingOperator === "g") {
              buffer.vimMoveToFirstLine();
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
            } else {
              dispatch({ type: "SET_PENDING_OPERATOR", operator: "g" });
            }
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "G": {
            if (state.count > 0) {
              buffer.vimMoveToLine(state.count);
            } else {
              buffer.vimMoveToLastLine();
            }
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "I": {
            buffer.vimInsertAtLineStart();
            updateMode("INSERT");
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "A": {
            buffer.vimAppendAtLineEnd();
            updateMode("INSERT");
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "d": {
            if (state.pendingOperator === "d") {
              const repeatCount2 = getCurrentCount();
              executeCommand(CMD_TYPES.DELETE_LINE, repeatCount2);
              dispatch({
                type: "SET_LAST_COMMAND",
                command: { type: CMD_TYPES.DELETE_LINE, count: repeatCount2 }
              });
              dispatch({ type: "CLEAR_COUNT" });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
            } else {
              dispatch({ type: "SET_PENDING_OPERATOR", operator: "d" });
            }
            return true;
          }
          case "c": {
            if (state.pendingOperator === "c") {
              const repeatCount2 = getCurrentCount();
              executeCommand(CMD_TYPES.CHANGE_LINE, repeatCount2);
              dispatch({
                type: "SET_LAST_COMMAND",
                command: { type: CMD_TYPES.CHANGE_LINE, count: repeatCount2 }
              });
              dispatch({ type: "CLEAR_COUNT" });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
            } else {
              dispatch({ type: "SET_PENDING_OPERATOR", operator: "c" });
            }
            return true;
          }
          case "D": {
            executeCommand(CMD_TYPES.DELETE_TO_EOL, 1);
            dispatch({
              type: "SET_LAST_COMMAND",
              command: { type: CMD_TYPES.DELETE_TO_EOL, count: 1 }
            });
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "C": {
            executeCommand(CMD_TYPES.CHANGE_TO_EOL, 1);
            dispatch({
              type: "SET_LAST_COMMAND",
              command: { type: CMD_TYPES.CHANGE_TO_EOL, count: 1 }
            });
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case ".": {
            if (state.lastCommand) {
              const cmdData = state.lastCommand;
              executeCommand(cmdData.type, cmdData.count);
            }
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          default: {
            if (normalizedKey.name === "left") {
              if (state.pendingOperator === "c") {
                return handleChangeMovement("h");
              }
              buffer.vimMoveLeft(repeatCount);
              dispatch({ type: "CLEAR_COUNT" });
              return true;
            }
            if (normalizedKey.name === "down") {
              if (state.pendingOperator === "c") {
                return handleChangeMovement("j");
              }
              buffer.vimMoveDown(repeatCount);
              dispatch({ type: "CLEAR_COUNT" });
              return true;
            }
            if (normalizedKey.name === "up") {
              if (state.pendingOperator === "c") {
                return handleChangeMovement("k");
              }
              buffer.vimMoveUp(repeatCount);
              dispatch({ type: "CLEAR_COUNT" });
              return true;
            }
            if (normalizedKey.name === "right") {
              if (state.pendingOperator === "c") {
                return handleChangeMovement("l");
              }
              buffer.vimMoveRight(repeatCount);
              dispatch({ type: "CLEAR_COUNT" });
              return true;
            }
            dispatch({ type: "CLEAR_PENDING_STATES" });
            return true;
          }
        }
      }
      return false;
    },
    [
      vimEnabled,
      normalizeKey,
      handleInsertModeInput,
      state.mode,
      state.count,
      state.pendingOperator,
      state.lastCommand,
      dispatch,
      getCurrentCount,
      handleChangeMovement,
      handleOperatorMotion,
      buffer,
      executeCommand,
      updateMode
    ]
  );
  return {
    mode: state.mode,
    vimModeEnabled: vimEnabled,
    handleInput
    // Expose the input handler for InputPrompt to use
  };
}
__name(useVim, "useVim");

// packages/cli/src/core/initializer.ts
init_esbuild_shims();

// packages/cli/src/core/auth.ts
init_esbuild_shims();
async function performInitialAuth(config, authType) {
  if (!authType) {
    return null;
  }
  try {
    await config.refreshAuth(authType, true);
    const authEvent = new AuthEvent(authType, "auto", "success");
    logAuth(config, authEvent);
  } catch (e2) {
    const errorMessage = `Failed to login. Message: ${getErrorMessage(e2)}`;
    const authEvent = new AuthEvent(authType, "auto", "error", errorMessage);
    logAuth(config, authEvent);
    return errorMessage;
  }
  return null;
}
__name(performInitialAuth, "performInitialAuth");

// packages/cli/src/core/theme.ts
init_esbuild_shims();
function validateTheme(settings) {
  const effectiveTheme = settings.merged.ui?.theme;
  if (effectiveTheme && !themeManager.findThemeByName(effectiveTheme)) {
    return `Theme "${effectiveTheme}" not found.`;
  }
  return null;
}
__name(validateTheme, "validateTheme");

// packages/cli/src/core/initializer.ts
async function initializeApp(config, settings) {
  const authType = settings.merged.security?.auth?.selectedType;
  const authError = await performInitialAuth(config, authType);
  if (authError) {
    settings.setValue(
      "User" /* User */,
      "security.auth.selectedType",
      void 0
    );
  }
  const themeError = validateTheme(settings);
  const shouldOpenAuthDialog = settings.merged.security?.auth?.selectedType === void 0 || !!authError;
  if (config.getIdeMode()) {
    const ideClient = await IdeClient.getInstance();
    await ideClient.connect();
    logIdeConnection(config, new IdeConnectionEvent(IdeConnectionType.START));
  }
  return {
    authError,
    themeError,
    shouldOpenAuthDialog,
    geminiMdFileCount: config.getGeminiMdFileCount()
  };
}
__name(initializeApp, "initializeApp");

// packages/cli/src/ui/hooks/useBracketedPaste.ts
init_esbuild_shims();
var import_react117 = __toESM(require_react(), 1);
var ENABLE_BRACKETED_PASTE = "\x1B[?2004h";
var DISABLE_BRACKETED_PASTE = "\x1B[?2004l";
var useBracketedPaste = /* @__PURE__ */ __name(() => {
  const cleanup = /* @__PURE__ */ __name(() => {
    process.stdout.write(DISABLE_BRACKETED_PASTE);
  }, "cleanup");
  (0, import_react117.useEffect)(() => {
    process.stdout.write(ENABLE_BRACKETED_PASTE);
    process.on("exit", cleanup);
    process.on("SIGINT", cleanup);
    process.on("SIGTERM", cleanup);
    return () => {
      cleanup();
      process.removeListener("exit", cleanup);
      process.removeListener("SIGINT", cleanup);
      process.removeListener("SIGTERM", cleanup);
    };
  }, []);
}, "useBracketedPaste");

// packages/cli/src/ui/hooks/useLoadingIndicator.ts
init_esbuild_shims();

// packages/cli/src/ui/hooks/useTimer.ts
init_esbuild_shims();
var import_react118 = __toESM(require_react(), 1);
var useTimer = /* @__PURE__ */ __name((isActive, resetKey) => {
  const [elapsedTime, setElapsedTime] = (0, import_react118.useState)(0);
  const timerRef = (0, import_react118.useRef)(null);
  const prevResetKeyRef = (0, import_react118.useRef)(resetKey);
  const prevIsActiveRef = (0, import_react118.useRef)(isActive);
  (0, import_react118.useEffect)(() => {
    let shouldResetTime = false;
    if (prevResetKeyRef.current !== resetKey) {
      shouldResetTime = true;
      prevResetKeyRef.current = resetKey;
    }
    if (prevIsActiveRef.current === false && isActive) {
      shouldResetTime = true;
    }
    if (shouldResetTime) {
      setElapsedTime(0);
    }
    prevIsActiveRef.current = isActive;
    if (isActive) {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
      timerRef.current = setInterval(() => {
        setElapsedTime((prev) => prev + 1);
      }, 1e3);
    } else {
      if (timerRef.current) {
        clearInterval(timerRef.current);
        timerRef.current = null;
      }
    }
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
        timerRef.current = null;
      }
    };
  }, [isActive, resetKey]);
  return elapsedTime;
}, "useTimer");

// packages/cli/src/ui/hooks/usePhraseCycler.ts
init_esbuild_shims();
var import_react119 = __toESM(require_react(), 1);
var WITTY_LOADING_PHRASES = [
  "I'm Feeling Lucky",
  "Shipping awesomeness... ",
  "Painting the serifs back on...",
  "Navigating the slime mold...",
  "Consulting the digital spirits...",
  "Reticulating splines...",
  "Warming up the AI hamsters...",
  "Asking the magic conch shell...",
  "Generating witty retort...",
  "Polishing the algorithms...",
  "Don't rush perfection (or my code)...",
  "Brewing fresh bytes...",
  "Counting electrons...",
  "Engaging cognitive processors...",
  "Checking for syntax errors in the universe...",
  "One moment, optimizing humor...",
  "Shuffling punchlines...",
  "Untangling neural nets...",
  "Compiling brilliance...",
  "Loading wit.exe...",
  "Summoning the cloud of wisdom...",
  "Preparing a witty response...",
  "Just a sec, I'm debugging reality...",
  "Confuzzling the options...",
  "Tuning the cosmic frequencies...",
  "Crafting a response worthy of your patience...",
  "Compiling the 1s and 0s...",
  "Resolving dependencies... and existential crises...",
  "Defragmenting memories... both RAM and personal...",
  "Rebooting the humor module...",
  "Caching the essentials (mostly cat memes)...",
  "Optimizing for ludicrous speed",
  "Swapping bits... don't tell the bytes...",
  "Garbage collecting... be right back...",
  "Assembling the interwebs...",
  "Converting coffee into code...",
  "Updating the syntax for reality...",
  "Rewiring the synapses...",
  "Looking for a misplaced semicolon...",
  "Greasin' the cogs of the machine...",
  "Pre-heating the servers...",
  "Calibrating the flux capacitor...",
  "Engaging the improbability drive...",
  "Channeling the Force...",
  "Aligning the stars for optimal response...",
  "So say we all...",
  "Loading the next great idea...",
  "Just a moment, I'm in the zone...",
  "Preparing to dazzle you with brilliance...",
  "Just a tick, I'm polishing my wit...",
  "Hold tight, I'm crafting a masterpiece...",
  "Just a jiffy, I'm debugging the universe...",
  "Just a moment, I'm aligning the pixels...",
  "Just a sec, I'm optimizing the humor...",
  "Just a moment, I'm tuning the algorithms...",
  "Warp speed engaged...",
  "Mining for more Dilithium crystals...",
  "Don't panic...",
  "Following the white rabbit...",
  "The truth is in here... somewhere...",
  "Blowing on the cartridge...",
  "Loading... Do a barrel roll!",
  "Waiting for the respawn...",
  "Finishing the Kessel Run in less than 12 parsecs...",
  "The cake is not a lie, it's just still loading...",
  "Fiddling with the character creation screen...",
  "Just a moment, I'm finding the right meme...",
  "Pressing 'A' to continue...",
  "Herding digital cats...",
  "Polishing the pixels...",
  "Finding a suitable loading screen pun...",
  "Distracting you with this witty phrase...",
  "Almost there... probably...",
  "Our hamsters are working as fast as they can...",
  "Giving Cloudy a pat on the head...",
  "Petting the cat...",
  "Rickrolling my boss...",
  "Never gonna give you up, never gonna let you down...",
  "Slapping the bass...",
  "Tasting the snozberries...",
  "I'm going the distance, I'm going for speed...",
  "Is this the real life? Is this just fantasy?...",
  "I've got a good feeling about this...",
  "Poking the bear...",
  "Doing research on the latest memes...",
  "Figuring out how to make this more witty...",
  "Hmmm... let me think...",
  "What do you call a fish with no eyes? A fsh...",
  "Why did the computer go to therapy? It had too many bytes...",
  "Why don't programmers like nature? It has too many bugs...",
  "Why do programmers prefer dark mode? Because light attracts bugs...",
  "Why did the developer go broke? Because they used up all their cache...",
  "What can you do with a broken pencil? Nothing, it's pointless...",
  "Applying percussive maintenance...",
  "Searching for the correct USB orientation...",
  "Ensuring the magic smoke stays inside the wires...",
  "Rewriting in Rust for no particular reason...",
  "Trying to exit Vim...",
  "Spinning up the hamster wheel...",
  "That's not a bug, it's an undocumented feature...",
  "Engage.",
  "I'll be back... with an answer.",
  "My other process is a TARDIS...",
  "Communing with the machine spirit...",
  "Letting the thoughts marinate...",
  "Just remembered where I put my keys...",
  "Pondering the orb...",
  "I've seen things you people wouldn't believe... like a user who reads loading messages.",
  "Initiating thoughtful gaze...",
  "What's a computer's favorite snack? Microchips.",
  "Why do Java developers wear glasses? Because they don't C#.",
  "Charging the laser... pew pew!",
  "Dividing by zero... just kidding!",
  "Looking for an adult superviso... I mean, processing.",
  "Making it go beep boop.",
  "Buffering... because even AIs need a moment.",
  "Entangling quantum particles for a faster response...",
  "Polishing the chrome... on the algorithms.",
  "Are you not entertained? (Working on it!)",
  "Summoning the code gremlins... to help, of course.",
  "Just waiting for the dial-up tone to finish...",
  "Recalibrating the humor-o-meter.",
  "My other loading screen is even funnier.",
  "Pretty sure there's a cat walking on the keyboard somewhere...",
  "Enhancing... Enhancing... Still loading.",
  "It's not a bug, it's a feature... of this loading screen.",
  "Have you tried turning it off and on again? (The loading screen, not me.)",
  "Constructing additional pylons...",
  "New line? That\u2019s Ctrl+J."
];
var PHRASE_CHANGE_INTERVAL_MS = 15e3;
var usePhraseCycler = /* @__PURE__ */ __name((isActive, isWaiting, customPhrases) => {
  const loadingPhrases = customPhrases && customPhrases.length > 0 ? customPhrases : WITTY_LOADING_PHRASES;
  const [currentLoadingPhrase, setCurrentLoadingPhrase] = (0, import_react119.useState)(
    loadingPhrases[0]
  );
  const phraseIntervalRef = (0, import_react119.useRef)(null);
  (0, import_react119.useEffect)(() => {
    if (isWaiting) {
      setCurrentLoadingPhrase("Waiting for user confirmation...");
      if (phraseIntervalRef.current) {
        clearInterval(phraseIntervalRef.current);
        phraseIntervalRef.current = null;
      }
    } else if (isActive) {
      if (phraseIntervalRef.current) {
        clearInterval(phraseIntervalRef.current);
      }
      const initialRandomIndex = Math.floor(
        Math.random() * loadingPhrases.length
      );
      setCurrentLoadingPhrase(loadingPhrases[initialRandomIndex]);
      phraseIntervalRef.current = setInterval(() => {
        const randomIndex = Math.floor(Math.random() * loadingPhrases.length);
        setCurrentLoadingPhrase(loadingPhrases[randomIndex]);
      }, PHRASE_CHANGE_INTERVAL_MS);
    } else {
      if (phraseIntervalRef.current) {
        clearInterval(phraseIntervalRef.current);
        phraseIntervalRef.current = null;
      }
      setCurrentLoadingPhrase(loadingPhrases[0]);
    }
    return () => {
      if (phraseIntervalRef.current) {
        clearInterval(phraseIntervalRef.current);
        phraseIntervalRef.current = null;
      }
    };
  }, [isActive, isWaiting, loadingPhrases]);
  return currentLoadingPhrase;
}, "usePhraseCycler");

// packages/cli/src/ui/hooks/useLoadingIndicator.ts
var import_react120 = __toESM(require_react(), 1);
var useLoadingIndicator = /* @__PURE__ */ __name((streamingState, customWittyPhrases) => {
  const [timerResetKey, setTimerResetKey] = (0, import_react120.useState)(0);
  const isTimerActive = streamingState === "responding" /* Responding */;
  const elapsedTimeFromTimer = useTimer(isTimerActive, timerResetKey);
  const isPhraseCyclingActive = streamingState === "responding" /* Responding */;
  const isWaiting = streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */;
  const currentLoadingPhrase = usePhraseCycler(
    isPhraseCyclingActive,
    isWaiting,
    customWittyPhrases
  );
  const [retainedElapsedTime, setRetainedElapsedTime] = (0, import_react120.useState)(0);
  const prevStreamingStateRef = (0, import_react120.useRef)(null);
  (0, import_react120.useEffect)(() => {
    if (prevStreamingStateRef.current === "waiting_for_confirmation" /* WaitingForConfirmation */ && streamingState === "responding" /* Responding */) {
      setTimerResetKey((prevKey) => prevKey + 1);
      setRetainedElapsedTime(0);
    } else if (streamingState === "idle" /* Idle */ && prevStreamingStateRef.current === "responding" /* Responding */) {
      setTimerResetKey((prevKey) => prevKey + 1);
      setRetainedElapsedTime(0);
    } else if (streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */) {
      setRetainedElapsedTime(elapsedTimeFromTimer);
    }
    prevStreamingStateRef.current = streamingState;
  }, [streamingState, elapsedTimeFromTimer]);
  return {
    elapsedTime: streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */ ? retainedElapsedTime : elapsedTimeFromTimer,
    currentLoadingPhrase
  };
}, "useLoadingIndicator");

// packages/cli/src/ui/hooks/useFolderTrust.ts
init_esbuild_shims();
var import_react121 = __toESM(require_react(), 1);
import * as process38 from "node:process";
var useFolderTrust = /* @__PURE__ */ __name((settings, onTrustChange) => {
  const [isTrusted, setIsTrusted] = (0, import_react121.useState)(void 0);
  const [isFolderTrustDialogOpen, setIsFolderTrustDialogOpen] = (0, import_react121.useState)(false);
  const [isRestarting, setIsRestarting] = (0, import_react121.useState)(false);
  const folderTrust = settings.merged.security?.folderTrust?.enabled;
  (0, import_react121.useEffect)(() => {
    const { isTrusted: trusted } = isWorkspaceTrusted(settings.merged);
    setIsTrusted(trusted);
    setIsFolderTrustDialogOpen(trusted === void 0);
    onTrustChange(trusted);
  }, [folderTrust, onTrustChange, settings.merged]);
  const handleFolderTrustSelect = (0, import_react121.useCallback)(
    (choice2) => {
      const trustedFolders = loadTrustedFolders();
      const cwd7 = process38.cwd();
      let trustLevel;
      const wasTrusted = isTrusted ?? true;
      switch (choice2) {
        case "trust_folder" /* TRUST_FOLDER */:
          trustLevel = "TRUST_FOLDER" /* TRUST_FOLDER */;
          break;
        case "trust_parent" /* TRUST_PARENT */:
          trustLevel = "TRUST_PARENT" /* TRUST_PARENT */;
          break;
        case "do_not_trust" /* DO_NOT_TRUST */:
          trustLevel = "DO_NOT_TRUST" /* DO_NOT_TRUST */;
          break;
        default:
          return;
      }
      trustedFolders.setValue(cwd7, trustLevel);
      const currentIsTrusted = trustLevel === "TRUST_FOLDER" /* TRUST_FOLDER */ || trustLevel === "TRUST_PARENT" /* TRUST_PARENT */;
      setIsTrusted(currentIsTrusted);
      onTrustChange(currentIsTrusted);
      const needsRestart = wasTrusted !== currentIsTrusted;
      if (needsRestart) {
        setIsRestarting(true);
        setIsFolderTrustDialogOpen(true);
      } else {
        setIsFolderTrustDialogOpen(false);
      }
    },
    [onTrustChange, isTrusted]
  );
  return {
    isTrusted,
    isFolderTrustDialogOpen,
    handleFolderTrustSelect,
    isRestarting
  };
}, "useFolderTrust");

// packages/cli/src/ui/utils/updateCheck.ts
init_esbuild_shims();

// node_modules/update-notifier/index.js
init_esbuild_shims();

// node_modules/update-notifier/update-notifier.js
init_esbuild_shims();
import process47 from "node:process";
import { spawn as spawn7 } from "node:child_process";
import { fileURLToPath as fileURLToPath12 } from "node:url";
import path102 from "node:path";
import { format as format3 } from "node:util";

// node_modules/configstore/index.js
init_esbuild_shims();
var import_graceful_fs = __toESM(require_graceful_fs(), 1);
import path98 from "node:path";
import os36 from "node:os";

// node_modules/xdg-basedir/index.js
init_esbuild_shims();
import os34 from "os";
import path95 from "path";
var homeDirectory = os34.homedir();
var { env: env5 } = process;
var xdgData = env5.XDG_DATA_HOME || (homeDirectory ? path95.join(homeDirectory, ".local", "share") : void 0);
var xdgConfig = env5.XDG_CONFIG_HOME || (homeDirectory ? path95.join(homeDirectory, ".config") : void 0);
var xdgState = env5.XDG_STATE_HOME || (homeDirectory ? path95.join(homeDirectory, ".local", "state") : void 0);
var xdgCache = env5.XDG_CACHE_HOME || (homeDirectory ? path95.join(homeDirectory, ".cache") : void 0);
var xdgRuntime = env5.XDG_RUNTIME_DIR || void 0;
var xdgDataDirectories = (env5.XDG_DATA_DIRS || "/usr/local/share/:/usr/share/").split(":");
if (xdgData) {
  xdgDataDirectories.unshift(xdgData);
}
var xdgConfigDirectories = (env5.XDG_CONFIG_DIRS || "/etc/xdg").split(":");
if (xdgConfig) {
  xdgConfigDirectories.unshift(xdgConfig);
}

// node_modules/atomically/dist/index.js
init_esbuild_shims();
import path97 from "node:path";

// node_modules/stubborn-fs/dist/index.js
init_esbuild_shims();
import fs84 from "node:fs";
import { promisify as promisify8 } from "node:util";

// node_modules/stubborn-fs/dist/attemptify.js
init_esbuild_shims();
var attemptifyAsync = /* @__PURE__ */ __name((fn, onError2) => {
  return /* @__PURE__ */ __name(function attemptified(...args) {
    return fn.apply(void 0, args).catch(onError2);
  }, "attemptified");
}, "attemptifyAsync");
var attemptifySync = /* @__PURE__ */ __name((fn, onError2) => {
  return /* @__PURE__ */ __name(function attemptified(...args) {
    try {
      return fn.apply(void 0, args);
    } catch (error) {
      return onError2(error);
    }
  }, "attemptified");
}, "attemptifySync");

// node_modules/stubborn-fs/dist/constants.js
init_esbuild_shims();
import process39 from "node:process";
var IS_USER_ROOT = process39.getuid ? !process39.getuid() : false;
var LIMIT_FILES_DESCRIPTORS = 1e4;
var NOOP2 = /* @__PURE__ */ __name(() => void 0, "NOOP");

// node_modules/stubborn-fs/dist/handlers.js
init_esbuild_shims();
var Handlers = {
  /* API */
  isChangeErrorOk: /* @__PURE__ */ __name((error) => {
    if (!Handlers.isNodeError(error))
      return false;
    const { code: code2 } = error;
    if (code2 === "ENOSYS")
      return true;
    if (!IS_USER_ROOT && (code2 === "EINVAL" || code2 === "EPERM"))
      return true;
    return false;
  }, "isChangeErrorOk"),
  isNodeError: /* @__PURE__ */ __name((error) => {
    return error instanceof Error;
  }, "isNodeError"),
  isRetriableError: /* @__PURE__ */ __name((error) => {
    if (!Handlers.isNodeError(error))
      return false;
    const { code: code2 } = error;
    if (code2 === "EMFILE" || code2 === "ENFILE" || code2 === "EAGAIN" || code2 === "EBUSY" || code2 === "EACCESS" || code2 === "EACCES" || code2 === "EACCS" || code2 === "EPERM")
      return true;
    return false;
  }, "isRetriableError"),
  onChangeError: /* @__PURE__ */ __name((error) => {
    if (!Handlers.isNodeError(error))
      throw error;
    if (Handlers.isChangeErrorOk(error))
      return;
    throw error;
  }, "onChangeError")
};
var handlers_default = Handlers;

// node_modules/stubborn-fs/dist/retryify.js
init_esbuild_shims();

// node_modules/stubborn-fs/dist/retryify_queue.js
init_esbuild_shims();
var RetryfyQueue = class {
  static {
    __name(this, "RetryfyQueue");
  }
  constructor() {
    this.interval = 25;
    this.intervalId = void 0;
    this.limit = LIMIT_FILES_DESCRIPTORS;
    this.queueActive = /* @__PURE__ */ new Set();
    this.queueWaiting = /* @__PURE__ */ new Set();
    this.init = () => {
      if (this.intervalId)
        return;
      this.intervalId = setInterval(this.tick, this.interval);
    };
    this.reset = () => {
      if (!this.intervalId)
        return;
      clearInterval(this.intervalId);
      delete this.intervalId;
    };
    this.add = (fn) => {
      this.queueWaiting.add(fn);
      if (this.queueActive.size < this.limit / 2) {
        this.tick();
      } else {
        this.init();
      }
    };
    this.remove = (fn) => {
      this.queueWaiting.delete(fn);
      this.queueActive.delete(fn);
    };
    this.schedule = () => {
      return new Promise((resolve24) => {
        const cleanup = /* @__PURE__ */ __name(() => this.remove(resolver), "cleanup");
        const resolver = /* @__PURE__ */ __name(() => resolve24(cleanup), "resolver");
        this.add(resolver);
      });
    };
    this.tick = () => {
      if (this.queueActive.size >= this.limit)
        return;
      if (!this.queueWaiting.size)
        return this.reset();
      for (const fn of this.queueWaiting) {
        if (this.queueActive.size >= this.limit)
          break;
        this.queueWaiting.delete(fn);
        this.queueActive.add(fn);
        fn();
      }
    };
  }
};
var retryify_queue_default = new RetryfyQueue();

// node_modules/stubborn-fs/dist/retryify.js
var retryifyAsync = /* @__PURE__ */ __name((fn, isRetriableError) => {
  return /* @__PURE__ */ __name(function retrified(timestamp) {
    return /* @__PURE__ */ __name(function attempt(...args) {
      return retryify_queue_default.schedule().then((cleanup) => {
        const onResolve = /* @__PURE__ */ __name((result) => {
          cleanup();
          return result;
        }, "onResolve");
        const onReject = /* @__PURE__ */ __name((error) => {
          cleanup();
          if (Date.now() >= timestamp)
            throw error;
          if (isRetriableError(error)) {
            const delay4 = Math.round(100 * Math.random());
            const delayPromise = new Promise((resolve24) => setTimeout(resolve24, delay4));
            return delayPromise.then(() => attempt.apply(void 0, args));
          }
          throw error;
        }, "onReject");
        return fn.apply(void 0, args).then(onResolve, onReject);
      });
    }, "attempt");
  }, "retrified");
}, "retryifyAsync");
var retryifySync = /* @__PURE__ */ __name((fn, isRetriableError) => {
  return /* @__PURE__ */ __name(function retrified(timestamp) {
    return /* @__PURE__ */ __name(function attempt(...args) {
      try {
        return fn.apply(void 0, args);
      } catch (error) {
        if (Date.now() > timestamp)
          throw error;
        if (isRetriableError(error))
          return attempt.apply(void 0, args);
        throw error;
      }
    }, "attempt");
  }, "retrified");
}, "retryifySync");

// node_modules/stubborn-fs/dist/index.js
var FS = {
  attempt: {
    /* ASYNC */
    chmod: attemptifyAsync(promisify8(fs84.chmod), handlers_default.onChangeError),
    chown: attemptifyAsync(promisify8(fs84.chown), handlers_default.onChangeError),
    close: attemptifyAsync(promisify8(fs84.close), NOOP2),
    fsync: attemptifyAsync(promisify8(fs84.fsync), NOOP2),
    mkdir: attemptifyAsync(promisify8(fs84.mkdir), NOOP2),
    realpath: attemptifyAsync(promisify8(fs84.realpath), NOOP2),
    stat: attemptifyAsync(promisify8(fs84.stat), NOOP2),
    unlink: attemptifyAsync(promisify8(fs84.unlink), NOOP2),
    /* SYNC */
    chmodSync: attemptifySync(fs84.chmodSync, handlers_default.onChangeError),
    chownSync: attemptifySync(fs84.chownSync, handlers_default.onChangeError),
    closeSync: attemptifySync(fs84.closeSync, NOOP2),
    existsSync: attemptifySync(fs84.existsSync, NOOP2),
    fsyncSync: attemptifySync(fs84.fsync, NOOP2),
    mkdirSync: attemptifySync(fs84.mkdirSync, NOOP2),
    realpathSync: attemptifySync(fs84.realpathSync, NOOP2),
    statSync: attemptifySync(fs84.statSync, NOOP2),
    unlinkSync: attemptifySync(fs84.unlinkSync, NOOP2)
  },
  retry: {
    /* ASYNC */
    close: retryifyAsync(promisify8(fs84.close), handlers_default.isRetriableError),
    fsync: retryifyAsync(promisify8(fs84.fsync), handlers_default.isRetriableError),
    open: retryifyAsync(promisify8(fs84.open), handlers_default.isRetriableError),
    readFile: retryifyAsync(promisify8(fs84.readFile), handlers_default.isRetriableError),
    rename: retryifyAsync(promisify8(fs84.rename), handlers_default.isRetriableError),
    stat: retryifyAsync(promisify8(fs84.stat), handlers_default.isRetriableError),
    write: retryifyAsync(promisify8(fs84.write), handlers_default.isRetriableError),
    writeFile: retryifyAsync(promisify8(fs84.writeFile), handlers_default.isRetriableError),
    /* SYNC */
    closeSync: retryifySync(fs84.closeSync, handlers_default.isRetriableError),
    fsyncSync: retryifySync(fs84.fsyncSync, handlers_default.isRetriableError),
    openSync: retryifySync(fs84.openSync, handlers_default.isRetriableError),
    readFileSync: retryifySync(fs84.readFileSync, handlers_default.isRetriableError),
    renameSync: retryifySync(fs84.renameSync, handlers_default.isRetriableError),
    statSync: retryifySync(fs84.statSync, handlers_default.isRetriableError),
    writeSync: retryifySync(fs84.writeSync, handlers_default.isRetriableError),
    writeFileSync: retryifySync(fs84.writeFileSync, handlers_default.isRetriableError)
  }
};
var dist_default6 = FS;

// node_modules/atomically/dist/constants.js
init_esbuild_shims();
import os35 from "node:os";
import process40 from "node:process";
var DEFAULT_ENCODING2 = "utf8";
var DEFAULT_FILE_MODE = 438;
var DEFAULT_FOLDER_MODE = 511;
var DEFAULT_WRITE_OPTIONS = {};
var DEFAULT_USER_UID = os35.userInfo().uid;
var DEFAULT_USER_GID = os35.userInfo().gid;
var DEFAULT_TIMEOUT_SYNC = 1e3;
var IS_POSIX = !!process40.getuid;
var IS_USER_ROOT2 = process40.getuid ? !process40.getuid() : false;
var LIMIT_BASENAME_LENGTH = 128;

// node_modules/atomically/dist/utils/lang.js
init_esbuild_shims();
var isException = /* @__PURE__ */ __name((value) => {
  return value instanceof Error && "code" in value;
}, "isException");
var isString = /* @__PURE__ */ __name((value) => {
  return typeof value === "string";
}, "isString");
var isUndefined = /* @__PURE__ */ __name((value) => {
  return value === void 0;
}, "isUndefined");

// node_modules/atomically/dist/utils/scheduler.js
init_esbuild_shims();

// node_modules/atomically/dist/utils/temp.js
init_esbuild_shims();
import path96 from "node:path";

// node_modules/when-exit/dist/node/index.js
init_esbuild_shims();

// node_modules/when-exit/dist/node/interceptor.js
init_esbuild_shims();
import process42 from "node:process";

// node_modules/when-exit/dist/node/constants.js
init_esbuild_shims();
import process41 from "node:process";
var IS_LINUX = process41.platform === "linux";
var IS_WINDOWS = process41.platform === "win32";

// node_modules/when-exit/dist/node/signals.js
init_esbuild_shims();
var Signals = ["SIGABRT", "SIGALRM", "SIGHUP", "SIGINT", "SIGTERM"];
if (!IS_WINDOWS) {
  Signals.push("SIGVTALRM", "SIGXCPU", "SIGXFSZ", "SIGUSR2", "SIGTRAP", "SIGSYS", "SIGQUIT", "SIGIOT");
}
if (IS_LINUX) {
  Signals.push("SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT", "SIGUNUSED");
}
var signals_default = Signals;

// node_modules/when-exit/dist/node/interceptor.js
var Interceptor = class {
  static {
    __name(this, "Interceptor");
  }
  /* CONSTRUCTOR */
  constructor() {
    this.callbacks = /* @__PURE__ */ new Set();
    this.exited = false;
    this.exit = (signal) => {
      if (this.exited)
        return;
      this.exited = true;
      for (const callback of this.callbacks) {
        callback();
      }
      if (signal) {
        if (IS_WINDOWS && (signal !== "SIGINT" && signal !== "SIGTERM" && signal !== "SIGKILL")) {
          process42.kill(process42.pid, "SIGTERM");
        } else {
          process42.kill(process42.pid, signal);
        }
      }
    };
    this.hook = () => {
      process42.once("exit", () => this.exit());
      for (const signal of signals_default) {
        try {
          process42.once(signal, () => this.exit(signal));
        } catch {
        }
      }
    };
    this.register = (callback) => {
      this.callbacks.add(callback);
      return () => {
        this.callbacks.delete(callback);
      };
    };
    this.hook();
  }
};
var interceptor_default = new Interceptor();

// node_modules/when-exit/dist/node/index.js
var whenExit = interceptor_default.register;
var node_default2 = whenExit;

// node_modules/atomically/dist/utils/temp.js
var Temp = {
  /* VARIABLES */
  store: {},
  /* API */
  create: /* @__PURE__ */ __name((filePath) => {
    const randomness = `000000${Math.floor(Math.random() * 16777215).toString(16)}`.slice(-6);
    const timestamp = Date.now().toString().slice(-10);
    const prefix = "tmp-";
    const suffix = `.${prefix}${timestamp}${randomness}`;
    const tempPath = `${filePath}${suffix}`;
    return tempPath;
  }, "create"),
  get: /* @__PURE__ */ __name((filePath, creator, purge = true) => {
    const tempPath = Temp.truncate(creator(filePath));
    if (tempPath in Temp.store)
      return Temp.get(filePath, creator, purge);
    Temp.store[tempPath] = purge;
    const disposer = /* @__PURE__ */ __name(() => delete Temp.store[tempPath], "disposer");
    return [tempPath, disposer];
  }, "get"),
  purge: /* @__PURE__ */ __name((filePath) => {
    if (!Temp.store[filePath])
      return;
    delete Temp.store[filePath];
    dist_default6.attempt.unlink(filePath);
  }, "purge"),
  purgeSync: /* @__PURE__ */ __name((filePath) => {
    if (!Temp.store[filePath])
      return;
    delete Temp.store[filePath];
    dist_default6.attempt.unlinkSync(filePath);
  }, "purgeSync"),
  purgeSyncAll: /* @__PURE__ */ __name(() => {
    for (const filePath in Temp.store) {
      Temp.purgeSync(filePath);
    }
  }, "purgeSyncAll"),
  truncate: /* @__PURE__ */ __name((filePath) => {
    const basename16 = path96.basename(filePath);
    if (basename16.length <= LIMIT_BASENAME_LENGTH)
      return filePath;
    const truncable = /^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(basename16);
    if (!truncable)
      return filePath;
    const truncationLength = basename16.length - LIMIT_BASENAME_LENGTH;
    return `${filePath.slice(0, -basename16.length)}${truncable[1]}${truncable[2].slice(0, -truncationLength)}${truncable[3]}`;
  }, "truncate")
};
node_default2(Temp.purgeSyncAll);
var temp_default = Temp;

// node_modules/atomically/dist/index.js
function writeFileSync6(filePath, data, options2 = DEFAULT_WRITE_OPTIONS) {
  if (isString(options2))
    return writeFileSync6(filePath, data, { encoding: options2 });
  const timeout2 = Date.now() + ((options2.timeout ?? DEFAULT_TIMEOUT_SYNC) || -1);
  let tempDisposer = null;
  let tempPath = null;
  let fd = null;
  try {
    const filePathReal = dist_default6.attempt.realpathSync(filePath);
    const filePathExists = !!filePathReal;
    filePath = filePathReal || filePath;
    [tempPath, tempDisposer] = temp_default.get(filePath, options2.tmpCreate || temp_default.create, !(options2.tmpPurge === false));
    const useStatChown = IS_POSIX && isUndefined(options2.chown);
    const useStatMode = isUndefined(options2.mode);
    if (filePathExists && (useStatChown || useStatMode)) {
      const stats = dist_default6.attempt.statSync(filePath);
      if (stats) {
        options2 = { ...options2 };
        if (useStatChown) {
          options2.chown = { uid: stats.uid, gid: stats.gid };
        }
        if (useStatMode) {
          options2.mode = stats.mode;
        }
      }
    }
    if (!filePathExists) {
      const parentPath = path97.dirname(filePath);
      dist_default6.attempt.mkdirSync(parentPath, {
        mode: DEFAULT_FOLDER_MODE,
        recursive: true
      });
    }
    fd = dist_default6.retry.openSync(timeout2)(tempPath, "w", options2.mode || DEFAULT_FILE_MODE);
    if (options2.tmpCreated) {
      options2.tmpCreated(tempPath);
    }
    if (isString(data)) {
      dist_default6.retry.writeSync(timeout2)(fd, data, 0, options2.encoding || DEFAULT_ENCODING2);
    } else if (!isUndefined(data)) {
      dist_default6.retry.writeSync(timeout2)(fd, data, 0, data.length, 0);
    }
    if (options2.fsync !== false) {
      if (options2.fsyncWait !== false) {
        dist_default6.retry.fsyncSync(timeout2)(fd);
      } else {
        dist_default6.attempt.fsync(fd);
      }
    }
    dist_default6.retry.closeSync(timeout2)(fd);
    fd = null;
    if (options2.chown && (options2.chown.uid !== DEFAULT_USER_UID || options2.chown.gid !== DEFAULT_USER_GID)) {
      dist_default6.attempt.chownSync(tempPath, options2.chown.uid, options2.chown.gid);
    }
    if (options2.mode && options2.mode !== DEFAULT_FILE_MODE) {
      dist_default6.attempt.chmodSync(tempPath, options2.mode);
    }
    try {
      dist_default6.retry.renameSync(timeout2)(tempPath, filePath);
    } catch (error) {
      if (!isException(error))
        throw error;
      if (error.code !== "ENAMETOOLONG")
        throw error;
      dist_default6.retry.renameSync(timeout2)(tempPath, temp_default.truncate(filePath));
    }
    tempDisposer();
    tempPath = null;
  } finally {
    if (fd)
      dist_default6.attempt.closeSync(fd);
    if (tempPath)
      temp_default.purge(tempPath);
  }
}
__name(writeFileSync6, "writeFileSync");

// node_modules/dot-prop/index.js
init_esbuild_shims();
var isObject = /* @__PURE__ */ __name((value) => {
  const type = typeof value;
  return value !== null && (type === "object" || type === "function");
}, "isObject");
var disallowedKeys = /* @__PURE__ */ new Set([
  "__proto__",
  "prototype",
  "constructor"
]);
var digits = new Set("0123456789");
function getPathSegments(path108) {
  const parts = [];
  let currentSegment = "";
  let currentPart = "start";
  let isIgnoring = false;
  for (const character of path108) {
    switch (character) {
      case "\\": {
        if (currentPart === "index") {
          throw new Error("Invalid character in an index");
        }
        if (currentPart === "indexEnd") {
          throw new Error("Invalid character after an index");
        }
        if (isIgnoring) {
          currentSegment += character;
        }
        currentPart = "property";
        isIgnoring = !isIgnoring;
        break;
      }
      case ".": {
        if (currentPart === "index") {
          throw new Error("Invalid character in an index");
        }
        if (currentPart === "indexEnd") {
          currentPart = "property";
          break;
        }
        if (isIgnoring) {
          isIgnoring = false;
          currentSegment += character;
          break;
        }
        if (disallowedKeys.has(currentSegment)) {
          return [];
        }
        parts.push(currentSegment);
        currentSegment = "";
        currentPart = "property";
        break;
      }
      case "[": {
        if (currentPart === "index") {
          throw new Error("Invalid character in an index");
        }
        if (currentPart === "indexEnd") {
          currentPart = "index";
          break;
        }
        if (isIgnoring) {
          isIgnoring = false;
          currentSegment += character;
          break;
        }
        if (currentPart === "property") {
          if (disallowedKeys.has(currentSegment)) {
            return [];
          }
          parts.push(currentSegment);
          currentSegment = "";
        }
        currentPart = "index";
        break;
      }
      case "]": {
        if (currentPart === "index") {
          parts.push(Number.parseInt(currentSegment, 10));
          currentSegment = "";
          currentPart = "indexEnd";
          break;
        }
        if (currentPart === "indexEnd") {
          throw new Error("Invalid character after an index");
        }
      }
      default: {
        if (currentPart === "index" && !digits.has(character)) {
          throw new Error("Invalid character in an index");
        }
        if (currentPart === "indexEnd") {
          throw new Error("Invalid character after an index");
        }
        if (currentPart === "start") {
          currentPart = "property";
        }
        if (isIgnoring) {
          isIgnoring = false;
          currentSegment += "\\";
        }
        currentSegment += character;
      }
    }
  }
  if (isIgnoring) {
    currentSegment += "\\";
  }
  switch (currentPart) {
    case "property": {
      if (disallowedKeys.has(currentSegment)) {
        return [];
      }
      parts.push(currentSegment);
      break;
    }
    case "index": {
      throw new Error("Index was not closed");
    }
    case "start": {
      parts.push("");
      break;
    }
  }
  return parts;
}
__name(getPathSegments, "getPathSegments");
function isStringIndex(object, key) {
  if (typeof key !== "number" && Array.isArray(object)) {
    const index = Number.parseInt(key, 10);
    return Number.isInteger(index) && object[index] === object[key];
  }
  return false;
}
__name(isStringIndex, "isStringIndex");
function assertNotStringIndex(object, key) {
  if (isStringIndex(object, key)) {
    throw new Error("Cannot use string index");
  }
}
__name(assertNotStringIndex, "assertNotStringIndex");
function getProperty(object, path108, value) {
  if (!isObject(object) || typeof path108 !== "string") {
    return value === void 0 ? object : value;
  }
  const pathArray = getPathSegments(path108);
  if (pathArray.length === 0) {
    return value;
  }
  for (let index = 0; index < pathArray.length; index++) {
    const key = pathArray[index];
    if (isStringIndex(object, key)) {
      object = index === pathArray.length - 1 ? void 0 : null;
    } else {
      object = object[key];
    }
    if (object === void 0 || object === null) {
      if (index !== pathArray.length - 1) {
        return value;
      }
      break;
    }
  }
  return object === void 0 ? value : object;
}
__name(getProperty, "getProperty");
function setProperty(object, path108, value) {
  if (!isObject(object) || typeof path108 !== "string") {
    return object;
  }
  const root = object;
  const pathArray = getPathSegments(path108);
  for (let index = 0; index < pathArray.length; index++) {
    const key = pathArray[index];
    assertNotStringIndex(object, key);
    if (index === pathArray.length - 1) {
      object[key] = value;
    } else if (!isObject(object[key])) {
      object[key] = typeof pathArray[index + 1] === "number" ? [] : {};
    }
    object = object[key];
  }
  return root;
}
__name(setProperty, "setProperty");
function deleteProperty(object, path108) {
  if (!isObject(object) || typeof path108 !== "string") {
    return false;
  }
  const pathArray = getPathSegments(path108);
  for (let index = 0; index < pathArray.length; index++) {
    const key = pathArray[index];
    assertNotStringIndex(object, key);
    if (index === pathArray.length - 1) {
      delete object[key];
      return true;
    }
    object = object[key];
    if (!isObject(object)) {
      return false;
    }
  }
}
__name(deleteProperty, "deleteProperty");
function hasProperty(object, path108) {
  if (!isObject(object) || typeof path108 !== "string") {
    return false;
  }
  const pathArray = getPathSegments(path108);
  if (pathArray.length === 0) {
    return false;
  }
  for (const key of pathArray) {
    if (!isObject(object) || !(key in object) || isStringIndex(object, key)) {
      return false;
    }
    object = object[key];
  }
  return true;
}
__name(hasProperty, "hasProperty");

// node_modules/configstore/index.js
function getConfigDirectory(id, globalConfigPath) {
  const pathPrefix = globalConfigPath ? path98.join(id, "config.json") : path98.join("configstore", `${id}.json`);
  const configDirectory = xdgConfig ?? import_graceful_fs.default.mkdtempSync(import_graceful_fs.default.realpathSync(os36.tmpdir()) + path98.sep);
  return path98.join(configDirectory, pathPrefix);
}
__name(getConfigDirectory, "getConfigDirectory");
var permissionError = "You don't have access to this file.";
var mkdirOptions = { mode: 448, recursive: true };
var writeFileOptions = { mode: 384 };
var Configstore = class {
  static {
    __name(this, "Configstore");
  }
  constructor(id, defaults3, options2 = {}) {
    this._path = options2.configPath ?? getConfigDirectory(id, options2.globalConfigPath);
    if (defaults3) {
      this.all = {
        ...defaults3,
        ...this.all
      };
    }
  }
  get all() {
    try {
      return JSON.parse(import_graceful_fs.default.readFileSync(this._path, "utf8"));
    } catch (error) {
      if (error.code === "ENOENT") {
        return {};
      }
      if (error.code === "EACCES") {
        error.message = `${error.message}
${permissionError}
`;
      }
      if (error.name === "SyntaxError") {
        writeFileSync6(this._path, "", writeFileOptions);
        return {};
      }
      throw error;
    }
  }
  set all(value) {
    try {
      import_graceful_fs.default.mkdirSync(path98.dirname(this._path), mkdirOptions);
      writeFileSync6(this._path, JSON.stringify(value, void 0, "	"), writeFileOptions);
    } catch (error) {
      if (error.code === "EACCES") {
        error.message = `${error.message}
${permissionError}
`;
      }
      throw error;
    }
  }
  get size() {
    return Object.keys(this.all || {}).length;
  }
  get(key) {
    return getProperty(this.all, key);
  }
  set(key, value) {
    const config = this.all;
    if (arguments.length === 1) {
      for (const k of Object.keys(key)) {
        setProperty(config, k, key[k]);
      }
    } else {
      setProperty(config, key, value);
    }
    this.all = config;
  }
  has(key) {
    return hasProperty(this.all, key);
  }
  delete(key) {
    const config = this.all;
    deleteProperty(config, key);
    this.all = config;
  }
  clear() {
    this.all = {};
  }
  get path() {
    return this._path;
  }
};

// node_modules/update-notifier/node_modules/chalk/source/index.js
init_esbuild_shims();

// node_modules/update-notifier/node_modules/chalk/source/vendor/ansi-styles/index.js
init_esbuild_shims();
var ANSI_BACKGROUND_OFFSET6 = 10;
var wrapAnsi166 = /* @__PURE__ */ __name((offset = 0) => (code2) => `\x1B[${code2 + offset}m`, "wrapAnsi16");
var wrapAnsi2566 = /* @__PURE__ */ __name((offset = 0) => (code2) => `\x1B[${38 + offset};5;${code2}m`, "wrapAnsi256");
var wrapAnsi16m6 = /* @__PURE__ */ __name((offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`, "wrapAnsi16m");
var styles8 = {
  modifier: {
    reset: [0, 0],
    // 21 isn't widely supported and 22 does the same thing
    bold: [1, 22],
    dim: [2, 22],
    italic: [3, 23],
    underline: [4, 24],
    overline: [53, 55],
    inverse: [7, 27],
    hidden: [8, 28],
    strikethrough: [9, 29]
  },
  color: {
    black: [30, 39],
    red: [31, 39],
    green: [32, 39],
    yellow: [33, 39],
    blue: [34, 39],
    magenta: [35, 39],
    cyan: [36, 39],
    white: [37, 39],
    // Bright color
    blackBright: [90, 39],
    gray: [90, 39],
    // Alias of `blackBright`
    grey: [90, 39],
    // Alias of `blackBright`
    redBright: [91, 39],
    greenBright: [92, 39],
    yellowBright: [93, 39],
    blueBright: [94, 39],
    magentaBright: [95, 39],
    cyanBright: [96, 39],
    whiteBright: [97, 39]
  },
  bgColor: {
    bgBlack: [40, 49],
    bgRed: [41, 49],
    bgGreen: [42, 49],
    bgYellow: [43, 49],
    bgBlue: [44, 49],
    bgMagenta: [45, 49],
    bgCyan: [46, 49],
    bgWhite: [47, 49],
    // Bright color
    bgBlackBright: [100, 49],
    bgGray: [100, 49],
    // Alias of `bgBlackBright`
    bgGrey: [100, 49],
    // Alias of `bgBlackBright`
    bgRedBright: [101, 49],
    bgGreenBright: [102, 49],
    bgYellowBright: [103, 49],
    bgBlueBright: [104, 49],
    bgMagentaBright: [105, 49],
    bgCyanBright: [106, 49],
    bgWhiteBright: [107, 49]
  }
};
var modifierNames6 = Object.keys(styles8.modifier);
var foregroundColorNames6 = Object.keys(styles8.color);
var backgroundColorNames6 = Object.keys(styles8.bgColor);
var colorNames6 = [...foregroundColorNames6, ...backgroundColorNames6];
function assembleStyles6() {
  const codes = /* @__PURE__ */ new Map();
  for (const [groupName, group] of Object.entries(styles8)) {
    for (const [styleName, style] of Object.entries(group)) {
      styles8[styleName] = {
        open: `\x1B[${style[0]}m`,
        close: `\x1B[${style[1]}m`
      };
      group[styleName] = styles8[styleName];
      codes.set(style[0], style[1]);
    }
    Object.defineProperty(styles8, groupName, {
      value: group,
      enumerable: false
    });
  }
  Object.defineProperty(styles8, "codes", {
    value: codes,
    enumerable: false
  });
  styles8.color.close = "\x1B[39m";
  styles8.bgColor.close = "\x1B[49m";
  styles8.color.ansi = wrapAnsi166();
  styles8.color.ansi256 = wrapAnsi2566();
  styles8.color.ansi16m = wrapAnsi16m6();
  styles8.bgColor.ansi = wrapAnsi166(ANSI_BACKGROUND_OFFSET6);
  styles8.bgColor.ansi256 = wrapAnsi2566(ANSI_BACKGROUND_OFFSET6);
  styles8.bgColor.ansi16m = wrapAnsi16m6(ANSI_BACKGROUND_OFFSET6);
  Object.defineProperties(styles8, {
    rgbToAnsi256: {
      value(red, green, blue) {
        if (red === green && green === blue) {
          if (red < 8) {
            return 16;
          }
          if (red > 248) {
            return 231;
          }
          return Math.round((red - 8) / 247 * 24) + 232;
        }
        return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
      },
      enumerable: false
    },
    hexToRgb: {
      value(hex) {
        const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches) {
          return [0, 0, 0];
        }
        let [colorString] = matches;
        if (colorString.length === 3) {
          colorString = [...colorString].map((character) => character + character).join("");
        }
        const integer = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer >> 16 & 255,
          integer >> 8 & 255,
          integer & 255
          /* eslint-enable no-bitwise */
        ];
      },
      enumerable: false
    },
    hexToAnsi256: {
      value: /* @__PURE__ */ __name((hex) => styles8.rgbToAnsi256(...styles8.hexToRgb(hex)), "value"),
      enumerable: false
    },
    ansi256ToAnsi: {
      value(code2) {
        if (code2 < 8) {
          return 30 + code2;
        }
        if (code2 < 16) {
          return 90 + (code2 - 8);
        }
        let red;
        let green;
        let blue;
        if (code2 >= 232) {
          red = ((code2 - 232) * 10 + 8) / 255;
          green = red;
          blue = red;
        } else {
          code2 -= 16;
          const remainder = code2 % 36;
          red = Math.floor(code2 / 36) / 5;
          green = Math.floor(remainder / 6) / 5;
          blue = remainder % 6 / 5;
        }
        const value = Math.max(red, green, blue) * 2;
        if (value === 0) {
          return 30;
        }
        let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
        if (value === 2) {
          result += 60;
        }
        return result;
      },
      enumerable: false
    },
    rgbToAnsi: {
      value: /* @__PURE__ */ __name((red, green, blue) => styles8.ansi256ToAnsi(styles8.rgbToAnsi256(red, green, blue)), "value"),
      enumerable: false
    },
    hexToAnsi: {
      value: /* @__PURE__ */ __name((hex) => styles8.ansi256ToAnsi(styles8.hexToAnsi256(hex)), "value"),
      enumerable: false
    }
  });
  return styles8;
}
__name(assembleStyles6, "assembleStyles");
var ansiStyles6 = assembleStyles6();
var ansi_styles_default6 = ansiStyles6;

// node_modules/update-notifier/node_modules/chalk/source/vendor/supports-color/index.js
init_esbuild_shims();
import process43 from "node:process";
import os37 from "node:os";
import tty2 from "node:tty";
function hasFlag2(flag, argv = globalThis.Deno ? globalThis.Deno.args : process43.argv) {
  const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
  const position = argv.indexOf(prefix + flag);
  const terminatorPosition = argv.indexOf("--");
  return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
}
__name(hasFlag2, "hasFlag");
var { env: env6 } = process43;
var flagForceColor2;
if (hasFlag2("no-color") || hasFlag2("no-colors") || hasFlag2("color=false") || hasFlag2("color=never")) {
  flagForceColor2 = 0;
} else if (hasFlag2("color") || hasFlag2("colors") || hasFlag2("color=true") || hasFlag2("color=always")) {
  flagForceColor2 = 1;
}
function envForceColor2() {
  if ("FORCE_COLOR" in env6) {
    if (env6.FORCE_COLOR === "true") {
      return 1;
    }
    if (env6.FORCE_COLOR === "false") {
      return 0;
    }
    return env6.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env6.FORCE_COLOR, 10), 3);
  }
}
__name(envForceColor2, "envForceColor");
function translateLevel2(level) {
  if (level === 0) {
    return false;
  }
  return {
    level,
    hasBasic: true,
    has256: level >= 2,
    has16m: level >= 3
  };
}
__name(translateLevel2, "translateLevel");
function _supportsColor2(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
  const noFlagForceColor = envForceColor2();
  if (noFlagForceColor !== void 0) {
    flagForceColor2 = noFlagForceColor;
  }
  const forceColor = sniffFlags ? flagForceColor2 : noFlagForceColor;
  if (forceColor === 0) {
    return 0;
  }
  if (sniffFlags) {
    if (hasFlag2("color=16m") || hasFlag2("color=full") || hasFlag2("color=truecolor")) {
      return 3;
    }
    if (hasFlag2("color=256")) {
      return 2;
    }
  }
  if ("TF_BUILD" in env6 && "AGENT_NAME" in env6) {
    return 1;
  }
  if (haveStream && !streamIsTTY && forceColor === void 0) {
    return 0;
  }
  const min = forceColor || 0;
  if (env6.TERM === "dumb") {
    return min;
  }
  if (process43.platform === "win32") {
    const osRelease = os37.release().split(".");
    if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
      return Number(osRelease[2]) >= 14931 ? 3 : 2;
    }
    return 1;
  }
  if ("CI" in env6) {
    if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env6)) {
      return 3;
    }
    if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env6) || env6.CI_NAME === "codeship") {
      return 1;
    }
    return min;
  }
  if ("TEAMCITY_VERSION" in env6) {
    return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env6.TEAMCITY_VERSION) ? 1 : 0;
  }
  if (env6.COLORTERM === "truecolor") {
    return 3;
  }
  if (env6.TERM === "xterm-kitty") {
    return 3;
  }
  if ("TERM_PROGRAM" in env6) {
    const version2 = Number.parseInt((env6.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
    switch (env6.TERM_PROGRAM) {
      case "iTerm.app": {
        return version2 >= 3 ? 3 : 2;
      }
      case "Apple_Terminal": {
        return 2;
      }
    }
  }
  if (/-256(color)?$/i.test(env6.TERM)) {
    return 2;
  }
  if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env6.TERM)) {
    return 1;
  }
  if ("COLORTERM" in env6) {
    return 1;
  }
  return min;
}
__name(_supportsColor2, "_supportsColor");
function createSupportsColor2(stream2, options2 = {}) {
  const level = _supportsColor2(stream2, {
    streamIsTTY: stream2 && stream2.isTTY,
    ...options2
  });
  return translateLevel2(level);
}
__name(createSupportsColor2, "createSupportsColor");
var supportsColor2 = {
  stdout: createSupportsColor2({ isTTY: tty2.isatty(1) }),
  stderr: createSupportsColor2({ isTTY: tty2.isatty(2) })
};
var supports_color_default2 = supportsColor2;

// node_modules/update-notifier/node_modules/chalk/source/utilities.js
init_esbuild_shims();
function stringReplaceAll2(string, substring, replacer) {
  let index = string.indexOf(substring);
  if (index === -1) {
    return string;
  }
  const substringLength = substring.length;
  let endIndex = 0;
  let returnValue = "";
  do {
    returnValue += string.slice(endIndex, index) + substring + replacer;
    endIndex = index + substringLength;
    index = string.indexOf(substring, endIndex);
  } while (index !== -1);
  returnValue += string.slice(endIndex);
  return returnValue;
}
__name(stringReplaceAll2, "stringReplaceAll");
function stringEncaseCRLFWithFirstIndex2(string, prefix, postfix, index) {
  let endIndex = 0;
  let returnValue = "";
  do {
    const gotCR = string[index - 1] === "\r";
    returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
    endIndex = index + 1;
    index = string.indexOf("\n", endIndex);
  } while (index !== -1);
  returnValue += string.slice(endIndex);
  return returnValue;
}
__name(stringEncaseCRLFWithFirstIndex2, "stringEncaseCRLFWithFirstIndex");

// node_modules/update-notifier/node_modules/chalk/source/index.js
var { stdout: stdoutColor2, stderr: stderrColor2 } = supports_color_default2;
var GENERATOR2 = Symbol("GENERATOR");
var STYLER2 = Symbol("STYLER");
var IS_EMPTY2 = Symbol("IS_EMPTY");
var levelMapping2 = [
  "ansi",
  "ansi",
  "ansi256",
  "ansi16m"
];
var styles9 = /* @__PURE__ */ Object.create(null);
var applyOptions2 = /* @__PURE__ */ __name((object, options2 = {}) => {
  if (options2.level && !(Number.isInteger(options2.level) && options2.level >= 0 && options2.level <= 3)) {
    throw new Error("The `level` option should be an integer from 0 to 3");
  }
  const colorLevel = stdoutColor2 ? stdoutColor2.level : 0;
  object.level = options2.level === void 0 ? colorLevel : options2.level;
}, "applyOptions");
var chalkFactory2 = /* @__PURE__ */ __name((options2) => {
  const chalk7 = /* @__PURE__ */ __name((...strings) => strings.join(" "), "chalk");
  applyOptions2(chalk7, options2);
  Object.setPrototypeOf(chalk7, createChalk2.prototype);
  return chalk7;
}, "chalkFactory");
function createChalk2(options2) {
  return chalkFactory2(options2);
}
__name(createChalk2, "createChalk");
Object.setPrototypeOf(createChalk2.prototype, Function.prototype);
for (const [styleName, style] of Object.entries(ansi_styles_default6)) {
  styles9[styleName] = {
    get() {
      const builder = createBuilder2(this, createStyler2(style.open, style.close, this[STYLER2]), this[IS_EMPTY2]);
      Object.defineProperty(this, styleName, { value: builder });
      return builder;
    }
  };
}
styles9.visible = {
  get() {
    const builder = createBuilder2(this, this[STYLER2], true);
    Object.defineProperty(this, "visible", { value: builder });
    return builder;
  }
};
var getModelAnsi2 = /* @__PURE__ */ __name((model, level, type, ...arguments_) => {
  if (model === "rgb") {
    if (level === "ansi16m") {
      return ansi_styles_default6[type].ansi16m(...arguments_);
    }
    if (level === "ansi256") {
      return ansi_styles_default6[type].ansi256(ansi_styles_default6.rgbToAnsi256(...arguments_));
    }
    return ansi_styles_default6[type].ansi(ansi_styles_default6.rgbToAnsi(...arguments_));
  }
  if (model === "hex") {
    return getModelAnsi2("rgb", level, type, ...ansi_styles_default6.hexToRgb(...arguments_));
  }
  return ansi_styles_default6[type][model](...arguments_);
}, "getModelAnsi");
var usedModels2 = ["rgb", "hex", "ansi256"];
for (const model of usedModels2) {
  styles9[model] = {
    get() {
      const { level } = this;
      return function(...arguments_) {
        const styler = createStyler2(getModelAnsi2(model, levelMapping2[level], "color", ...arguments_), ansi_styles_default6.color.close, this[STYLER2]);
        return createBuilder2(this, styler, this[IS_EMPTY2]);
      };
    }
  };
  const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
  styles9[bgModel] = {
    get() {
      const { level } = this;
      return function(...arguments_) {
        const styler = createStyler2(getModelAnsi2(model, levelMapping2[level], "bgColor", ...arguments_), ansi_styles_default6.bgColor.close, this[STYLER2]);
        return createBuilder2(this, styler, this[IS_EMPTY2]);
      };
    }
  };
}
var proto2 = Object.defineProperties(() => {
}, {
  ...styles9,
  level: {
    enumerable: true,
    get() {
      return this[GENERATOR2].level;
    },
    set(level) {
      this[GENERATOR2].level = level;
    }
  }
});
var createStyler2 = /* @__PURE__ */ __name((open3, close, parent) => {
  let openAll;
  let closeAll;
  if (parent === void 0) {
    openAll = open3;
    closeAll = close;
  } else {
    openAll = parent.openAll + open3;
    closeAll = close + parent.closeAll;
  }
  return {
    open: open3,
    close,
    openAll,
    closeAll,
    parent
  };
}, "createStyler");
var createBuilder2 = /* @__PURE__ */ __name((self2, _styler, _isEmpty) => {
  const builder = /* @__PURE__ */ __name((...arguments_) => applyStyle2(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" ")), "builder");
  Object.setPrototypeOf(builder, proto2);
  builder[GENERATOR2] = self2;
  builder[STYLER2] = _styler;
  builder[IS_EMPTY2] = _isEmpty;
  return builder;
}, "createBuilder");
var applyStyle2 = /* @__PURE__ */ __name((self2, string) => {
  if (self2.level <= 0 || !string) {
    return self2[IS_EMPTY2] ? "" : string;
  }
  let styler = self2[STYLER2];
  if (styler === void 0) {
    return string;
  }
  const { openAll, closeAll } = styler;
  if (string.includes("\x1B")) {
    while (styler !== void 0) {
      string = stringReplaceAll2(string, styler.close, styler.open);
      styler = styler.parent;
    }
  }
  const lfIndex = string.indexOf("\n");
  if (lfIndex !== -1) {
    string = stringEncaseCRLFWithFirstIndex2(string, closeAll, openAll, lfIndex);
  }
  return openAll + string + closeAll;
}, "applyStyle");
Object.defineProperties(createChalk2.prototype, styles9);
var chalk6 = createChalk2();
var chalkStderr2 = createChalk2({ level: stderrColor2 ? stderrColor2.level : 0 });
var source_default2 = chalk6;

// node_modules/update-notifier/update-notifier.js
var import_diff4 = __toESM(require_diff(), 1);
var import_gt = __toESM(require_gt(), 1);

// node_modules/latest-version/index.js
init_esbuild_shims();

// node_modules/package-json/index.js
init_esbuild_shims();

// node_modules/ky/distribution/index.js
init_esbuild_shims();

// node_modules/ky/distribution/core/Ky.js
init_esbuild_shims();

// node_modules/ky/distribution/errors/HTTPError.js
init_esbuild_shims();
var HTTPError = class extends Error {
  static {
    __name(this, "HTTPError");
  }
  response;
  request;
  options;
  constructor(response, request4, options2) {
    const code2 = response.status || response.status === 0 ? response.status : "";
    const title = response.statusText || "";
    const status = `${code2} ${title}`.trim();
    const reason = status ? `status code ${status}` : "an unknown error";
    super(`Request failed with ${reason}: ${request4.method} ${request4.url}`);
    this.name = "HTTPError";
    this.response = response;
    this.request = request4;
    this.options = options2;
  }
};

// node_modules/ky/distribution/errors/TimeoutError.js
init_esbuild_shims();
var TimeoutError = class extends Error {
  static {
    __name(this, "TimeoutError");
  }
  request;
  constructor(request4) {
    super(`Request timed out: ${request4.method} ${request4.url}`);
    this.name = "TimeoutError";
    this.request = request4;
  }
};

// node_modules/ky/distribution/utils/body.js
init_esbuild_shims();

// node_modules/ky/distribution/core/constants.js
init_esbuild_shims();
var supportsRequestStreams = (() => {
  let duplexAccessed = false;
  let hasContentType = false;
  const supportsReadableStream = typeof globalThis.ReadableStream === "function";
  const supportsRequest = typeof globalThis.Request === "function";
  if (supportsReadableStream && supportsRequest) {
    try {
      hasContentType = new globalThis.Request("https://empty.invalid", {
        body: new globalThis.ReadableStream(),
        method: "POST",
        // @ts-expect-error - Types are outdated.
        get duplex() {
          duplexAccessed = true;
          return "half";
        }
      }).headers.has("Content-Type");
    } catch (error) {
      if (error instanceof Error && error.message === "unsupported BodyInit type") {
        return false;
      }
      throw error;
    }
  }
  return duplexAccessed && !hasContentType;
})();
var supportsAbortController = typeof globalThis.AbortController === "function";
var supportsResponseStreams = typeof globalThis.ReadableStream === "function";
var supportsFormData2 = typeof globalThis.FormData === "function";
var requestMethods = ["get", "post", "put", "patch", "head", "delete"];
var validate3 = /* @__PURE__ */ __name(() => void 0, "validate");
validate3();
var responseTypes = {
  json: "application/json",
  text: "text/*",
  formData: "multipart/form-data",
  arrayBuffer: "*/*",
  blob: "*/*"
};
var maxSafeTimeout = 2147483647;
var usualFormBoundarySize = new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length;
var stop = Symbol("stop");
var kyOptionKeys = {
  json: true,
  parseJson: true,
  stringifyJson: true,
  searchParams: true,
  prefixUrl: true,
  retry: true,
  timeout: true,
  hooks: true,
  throwHttpErrors: true,
  onDownloadProgress: true,
  onUploadProgress: true,
  fetch: true
};
var requestOptionsRegistry = {
  method: true,
  headers: true,
  body: true,
  mode: true,
  credentials: true,
  cache: true,
  redirect: true,
  referrer: true,
  referrerPolicy: true,
  integrity: true,
  keepalive: true,
  signal: true,
  window: true,
  dispatcher: true,
  duplex: true,
  priority: true
};

// node_modules/ky/distribution/utils/body.js
var getBodySize = /* @__PURE__ */ __name((body) => {
  if (!body) {
    return 0;
  }
  if (body instanceof FormData) {
    let size = 0;
    for (const [key, value] of body) {
      size += usualFormBoundarySize;
      size += new TextEncoder().encode(`Content-Disposition: form-data; name="${key}"`).length;
      size += typeof value === "string" ? new TextEncoder().encode(value).length : value.size;
    }
    return size;
  }
  if (body instanceof Blob) {
    return body.size;
  }
  if (body instanceof ArrayBuffer) {
    return body.byteLength;
  }
  if (typeof body === "string") {
    return new TextEncoder().encode(body).length;
  }
  if (body instanceof URLSearchParams) {
    return new TextEncoder().encode(body.toString()).length;
  }
  if ("byteLength" in body) {
    return body.byteLength;
  }
  if (typeof body === "object" && body !== null) {
    try {
      const jsonString = JSON.stringify(body);
      return new TextEncoder().encode(jsonString).length;
    } catch {
      return 0;
    }
  }
  return 0;
}, "getBodySize");
var streamResponse = /* @__PURE__ */ __name((response, onDownloadProgress) => {
  const totalBytes = Number(response.headers.get("content-length")) || 0;
  let transferredBytes = 0;
  if (response.status === 204) {
    if (onDownloadProgress) {
      onDownloadProgress({ percent: 1, totalBytes, transferredBytes }, new Uint8Array());
    }
    return new Response(null, {
      status: response.status,
      statusText: response.statusText,
      headers: response.headers
    });
  }
  return new Response(new ReadableStream({
    async start(controller) {
      const reader = response.body.getReader();
      if (onDownloadProgress) {
        onDownloadProgress({ percent: 0, transferredBytes: 0, totalBytes }, new Uint8Array());
      }
      async function read2() {
        const { done, value } = await reader.read();
        if (done) {
          controller.close();
          return;
        }
        if (onDownloadProgress) {
          transferredBytes += value.byteLength;
          const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
          onDownloadProgress({ percent, transferredBytes, totalBytes }, value);
        }
        controller.enqueue(value);
        await read2();
      }
      __name(read2, "read");
      await read2();
    }
  }), {
    status: response.status,
    statusText: response.statusText,
    headers: response.headers
  });
}, "streamResponse");
var streamRequest = /* @__PURE__ */ __name((request4, onUploadProgress) => {
  const totalBytes = getBodySize(request4.body);
  let transferredBytes = 0;
  return new Request(request4, {
    // @ts-expect-error - Types are outdated.
    duplex: "half",
    body: new ReadableStream({
      async start(controller) {
        const reader = request4.body instanceof ReadableStream ? request4.body.getReader() : new Response("").body.getReader();
        async function read2() {
          const { done, value } = await reader.read();
          if (done) {
            if (onUploadProgress) {
              onUploadProgress({ percent: 1, transferredBytes, totalBytes: Math.max(totalBytes, transferredBytes) }, new Uint8Array());
            }
            controller.close();
            return;
          }
          transferredBytes += value.byteLength;
          let percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
          if (totalBytes < transferredBytes || percent === 1) {
            percent = 0.99;
          }
          if (onUploadProgress) {
            onUploadProgress({ percent: Number(percent.toFixed(2)), transferredBytes, totalBytes }, value);
          }
          controller.enqueue(value);
          await read2();
        }
        __name(read2, "read");
        await read2();
      }
    })
  });
}, "streamRequest");

// node_modules/ky/distribution/utils/merge.js
init_esbuild_shims();

// node_modules/ky/distribution/utils/is.js
init_esbuild_shims();
var isObject2 = /* @__PURE__ */ __name((value) => value !== null && typeof value === "object", "isObject");

// node_modules/ky/distribution/utils/merge.js
var validateAndMerge = /* @__PURE__ */ __name((...sources) => {
  for (const source2 of sources) {
    if ((!isObject2(source2) || Array.isArray(source2)) && source2 !== void 0) {
      throw new TypeError("The `options` argument must be an object");
    }
  }
  return deepMerge({}, ...sources);
}, "validateAndMerge");
var mergeHeaders2 = /* @__PURE__ */ __name((source1 = {}, source2 = {}) => {
  const result = new globalThis.Headers(source1);
  const isHeadersInstance = source2 instanceof globalThis.Headers;
  const source3 = new globalThis.Headers(source2);
  for (const [key, value] of source3.entries()) {
    if (isHeadersInstance && value === "undefined" || value === void 0) {
      result.delete(key);
    } else {
      result.set(key, value);
    }
  }
  return result;
}, "mergeHeaders");
function newHookValue(original, incoming, property) {
  return Object.hasOwn(incoming, property) && incoming[property] === void 0 ? [] : deepMerge(original[property] ?? [], incoming[property] ?? []);
}
__name(newHookValue, "newHookValue");
var mergeHooks = /* @__PURE__ */ __name((original = {}, incoming = {}) => ({
  beforeRequest: newHookValue(original, incoming, "beforeRequest"),
  beforeRetry: newHookValue(original, incoming, "beforeRetry"),
  afterResponse: newHookValue(original, incoming, "afterResponse"),
  beforeError: newHookValue(original, incoming, "beforeError")
}), "mergeHooks");
var deepMerge = /* @__PURE__ */ __name((...sources) => {
  let returnValue = {};
  let headers = {};
  let hooks = {};
  for (const source2 of sources) {
    if (Array.isArray(source2)) {
      if (!Array.isArray(returnValue)) {
        returnValue = [];
      }
      returnValue = [...returnValue, ...source2];
    } else if (isObject2(source2)) {
      for (let [key, value] of Object.entries(source2)) {
        if (isObject2(value) && key in returnValue) {
          value = deepMerge(returnValue[key], value);
        }
        returnValue = { ...returnValue, [key]: value };
      }
      if (isObject2(source2.hooks)) {
        hooks = mergeHooks(hooks, source2.hooks);
        returnValue.hooks = hooks;
      }
      if (isObject2(source2.headers)) {
        headers = mergeHeaders2(headers, source2.headers);
        returnValue.headers = headers;
      }
    }
  }
  return returnValue;
}, "deepMerge");

// node_modules/ky/distribution/utils/normalize.js
init_esbuild_shims();
var normalizeRequestMethod = /* @__PURE__ */ __name((input) => requestMethods.includes(input) ? input.toUpperCase() : input, "normalizeRequestMethod");
var retryMethods = ["get", "put", "head", "delete", "options", "trace"];
var retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
var retryAfterStatusCodes = [413, 429, 503];
var defaultRetryOptions = {
  limit: 2,
  methods: retryMethods,
  statusCodes: retryStatusCodes,
  afterStatusCodes: retryAfterStatusCodes,
  maxRetryAfter: Number.POSITIVE_INFINITY,
  backoffLimit: Number.POSITIVE_INFINITY,
  delay: /* @__PURE__ */ __name((attemptCount) => 0.3 * 2 ** (attemptCount - 1) * 1e3, "delay")
};
var normalizeRetryOptions = /* @__PURE__ */ __name((retry = {}) => {
  if (typeof retry === "number") {
    return {
      ...defaultRetryOptions,
      limit: retry
    };
  }
  if (retry.methods && !Array.isArray(retry.methods)) {
    throw new Error("retry.methods must be an array");
  }
  if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
    throw new Error("retry.statusCodes must be an array");
  }
  return {
    ...defaultRetryOptions,
    ...retry
  };
}, "normalizeRetryOptions");

// node_modules/ky/distribution/utils/timeout.js
init_esbuild_shims();
async function timeout(request4, init, abortController, options2) {
  return new Promise((resolve24, reject) => {
    const timeoutId = setTimeout(() => {
      if (abortController) {
        abortController.abort();
      }
      reject(new TimeoutError(request4));
    }, options2.timeout);
    void options2.fetch(request4, init).then(resolve24).catch(reject).then(() => {
      clearTimeout(timeoutId);
    });
  });
}
__name(timeout, "timeout");

// node_modules/ky/distribution/utils/delay.js
init_esbuild_shims();
async function delay3(ms, { signal }) {
  return new Promise((resolve24, reject) => {
    if (signal) {
      signal.throwIfAborted();
      signal.addEventListener("abort", abortHandler, { once: true });
    }
    function abortHandler() {
      clearTimeout(timeoutId);
      reject(signal.reason);
    }
    __name(abortHandler, "abortHandler");
    const timeoutId = setTimeout(() => {
      signal?.removeEventListener("abort", abortHandler);
      resolve24();
    }, ms);
  });
}
__name(delay3, "delay");

// node_modules/ky/distribution/utils/options.js
init_esbuild_shims();
var findUnknownOptions = /* @__PURE__ */ __name((request4, options2) => {
  const unknownOptions = {};
  for (const key in options2) {
    if (!(key in requestOptionsRegistry) && !(key in kyOptionKeys) && !(key in request4)) {
      unknownOptions[key] = options2[key];
    }
  }
  return unknownOptions;
}, "findUnknownOptions");

// node_modules/ky/distribution/core/Ky.js
var Ky = class _Ky {
  static {
    __name(this, "Ky");
  }
  static create(input, options2) {
    const ky2 = new _Ky(input, options2);
    const function_ = /* @__PURE__ */ __name(async () => {
      if (typeof ky2._options.timeout === "number" && ky2._options.timeout > maxSafeTimeout) {
        throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
      }
      await Promise.resolve();
      let response = await ky2._fetch();
      for (const hook of ky2._options.hooks.afterResponse) {
        const modifiedResponse = await hook(ky2.request, ky2._options, ky2._decorateResponse(response.clone()));
        if (modifiedResponse instanceof globalThis.Response) {
          response = modifiedResponse;
        }
      }
      ky2._decorateResponse(response);
      if (!response.ok && ky2._options.throwHttpErrors) {
        let error = new HTTPError(response, ky2.request, ky2._options);
        for (const hook of ky2._options.hooks.beforeError) {
          error = await hook(error);
        }
        throw error;
      }
      if (ky2._options.onDownloadProgress) {
        if (typeof ky2._options.onDownloadProgress !== "function") {
          throw new TypeError("The `onDownloadProgress` option must be a function");
        }
        if (!supportsResponseStreams) {
          throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");
        }
        return streamResponse(response.clone(), ky2._options.onDownloadProgress);
      }
      return response;
    }, "function_");
    const isRetriableMethod = ky2._options.retry.methods.includes(ky2.request.method.toLowerCase());
    const result = (isRetriableMethod ? ky2._retry(function_) : function_()).finally(async () => {
      if (!ky2.request.bodyUsed) {
        await ky2.request.body?.cancel();
      }
    });
    for (const [type, mimeType] of Object.entries(responseTypes)) {
      result[type] = async () => {
        ky2.request.headers.set("accept", ky2.request.headers.get("accept") || mimeType);
        const response = await result;
        if (type === "json") {
          if (response.status === 204) {
            return "";
          }
          const arrayBuffer = await response.clone().arrayBuffer();
          const responseSize = arrayBuffer.byteLength;
          if (responseSize === 0) {
            return "";
          }
          if (options2.parseJson) {
            return options2.parseJson(await response.text());
          }
        }
        return response[type]();
      };
    }
    return result;
  }
  request;
  abortController;
  _retryCount = 0;
  _input;
  _options;
  // eslint-disable-next-line complexity
  constructor(input, options2 = {}) {
    this._input = input;
    this._options = {
      ...options2,
      headers: mergeHeaders2(this._input.headers, options2.headers),
      hooks: mergeHooks({
        beforeRequest: [],
        beforeRetry: [],
        beforeError: [],
        afterResponse: []
      }, options2.hooks),
      method: normalizeRequestMethod(options2.method ?? this._input.method ?? "GET"),
      // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
      prefixUrl: String(options2.prefixUrl || ""),
      retry: normalizeRetryOptions(options2.retry),
      throwHttpErrors: options2.throwHttpErrors !== false,
      timeout: options2.timeout ?? 1e4,
      fetch: options2.fetch ?? globalThis.fetch.bind(globalThis)
    };
    if (typeof this._input !== "string" && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {
      throw new TypeError("`input` must be a string, URL, or Request");
    }
    if (this._options.prefixUrl && typeof this._input === "string") {
      if (this._input.startsWith("/")) {
        throw new Error("`input` must not begin with a slash when using `prefixUrl`");
      }
      if (!this._options.prefixUrl.endsWith("/")) {
        this._options.prefixUrl += "/";
      }
      this._input = this._options.prefixUrl + this._input;
    }
    if (supportsAbortController) {
      const originalSignal = this._options.signal ?? this._input.signal;
      this.abortController = new globalThis.AbortController();
      this._options.signal = originalSignal ? AbortSignal.any([originalSignal, this.abortController.signal]) : this.abortController.signal;
    }
    if (supportsRequestStreams) {
      this._options.duplex = "half";
    }
    if (this._options.json !== void 0) {
      this._options.body = this._options.stringifyJson?.(this._options.json) ?? JSON.stringify(this._options.json);
      this._options.headers.set("content-type", this._options.headers.get("content-type") ?? "application/json");
    }
    this.request = new globalThis.Request(this._input, this._options);
    if (this._options.searchParams) {
      const textSearchParams = typeof this._options.searchParams === "string" ? this._options.searchParams.replace(/^\?/, "") : new URLSearchParams(this._options.searchParams).toString();
      const searchParams = "?" + textSearchParams;
      const url2 = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
      if ((supportsFormData2 && this._options.body instanceof globalThis.FormData || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers["content-type"])) {
        this.request.headers.delete("content-type");
      }
      this.request = new globalThis.Request(new globalThis.Request(url2, { ...this.request }), this._options);
    }
    if (this._options.onUploadProgress) {
      if (typeof this._options.onUploadProgress !== "function") {
        throw new TypeError("The `onUploadProgress` option must be a function");
      }
      if (!supportsRequestStreams) {
        throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");
      }
      const originalBody = this.request.body;
      if (originalBody) {
        this.request = streamRequest(this.request, this._options.onUploadProgress);
      }
    }
  }
  _calculateRetryDelay(error) {
    this._retryCount++;
    if (this._retryCount > this._options.retry.limit || error instanceof TimeoutError) {
      throw error;
    }
    if (error instanceof HTTPError) {
      if (!this._options.retry.statusCodes.includes(error.response.status)) {
        throw error;
      }
      const retryAfter = error.response.headers.get("Retry-After") ?? error.response.headers.get("RateLimit-Reset") ?? error.response.headers.get("X-RateLimit-Reset") ?? error.response.headers.get("X-Rate-Limit-Reset");
      if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
        let after = Number(retryAfter) * 1e3;
        if (Number.isNaN(after)) {
          after = Date.parse(retryAfter) - Date.now();
        } else if (after >= Date.parse("2024-01-01")) {
          after -= Date.now();
        }
        const max = this._options.retry.maxRetryAfter ?? after;
        return after < max ? after : max;
      }
      if (error.response.status === 413) {
        throw error;
      }
    }
    const retryDelay = this._options.retry.delay(this._retryCount);
    return Math.min(this._options.retry.backoffLimit, retryDelay);
  }
  _decorateResponse(response) {
    if (this._options.parseJson) {
      response.json = async () => this._options.parseJson(await response.text());
    }
    return response;
  }
  async _retry(function_) {
    try {
      return await function_();
    } catch (error) {
      const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
      if (this._retryCount < 1) {
        throw error;
      }
      await delay3(ms, { signal: this._options.signal });
      for (const hook of this._options.hooks.beforeRetry) {
        const hookResult = await hook({
          request: this.request,
          options: this._options,
          error,
          retryCount: this._retryCount
        });
        if (hookResult === stop) {
          return;
        }
      }
      return this._retry(function_);
    }
  }
  async _fetch() {
    for (const hook of this._options.hooks.beforeRequest) {
      const result = await hook(this.request, this._options);
      if (result instanceof Request) {
        this.request = result;
        break;
      }
      if (result instanceof Response) {
        return result;
      }
    }
    const nonRequestOptions = findUnknownOptions(this.request, this._options);
    const mainRequest = this.request;
    this.request = mainRequest.clone();
    if (this._options.timeout === false) {
      return this._options.fetch(mainRequest, nonRequestOptions);
    }
    return timeout(mainRequest, nonRequestOptions, this.abortController, this._options);
  }
};

// node_modules/ky/distribution/index.js
var createInstance = /* @__PURE__ */ __name((defaults3) => {
  const ky2 = /* @__PURE__ */ __name((input, options2) => Ky.create(input, validateAndMerge(defaults3, options2)), "ky");
  for (const method of requestMethods) {
    ky2[method] = (input, options2) => Ky.create(input, validateAndMerge(defaults3, options2, { method }));
  }
  ky2.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
  ky2.extend = (newDefaults) => {
    if (typeof newDefaults === "function") {
      newDefaults = newDefaults(defaults3 ?? {});
    }
    return createInstance(validateAndMerge(defaults3, newDefaults));
  };
  ky2.stop = stop;
  return ky2;
}, "createInstance");
var ky = createInstance();
var distribution_default = ky;

// node_modules/registry-url/index.js
init_esbuild_shims();
var import_rc = __toESM(require_rc(), 1);
function registryUrl(scope) {
  const result = (0, import_rc.default)("npm", { registry: "https://registry.npmjs.org/" });
  const url2 = result[`${scope}:registry`] || result.config_registry || result.registry;
  return url2.slice(-1) === "/" ? url2 : `${url2}/`;
}
__name(registryUrl, "registryUrl");

// node_modules/package-json/index.js
var import_registry_auth_token = __toESM(require_registry_auth_token(), 1);
var import_semver2 = __toESM(require_semver3(), 1);
var PackageNotFoundError = class extends Error {
  static {
    __name(this, "PackageNotFoundError");
  }
  constructor(packageName) {
    super(`Package \`${packageName}\` could not be found`);
    this.name = "PackageNotFoundError";
  }
};
var VersionNotFoundError = class extends Error {
  static {
    __name(this, "VersionNotFoundError");
  }
  constructor(packageName, version2) {
    super(`Version \`${version2}\` for package \`${packageName}\` could not be found`);
    this.name = "VersionNotFoundError";
  }
};
async function packageJson2(packageName, options2 = {}) {
  let { version: version2 = "latest" } = options2;
  const { omitDeprecated = true } = options2;
  const scope = packageName.split("/")[0];
  const registryUrl_ = options2.registryUrl ?? registryUrl(scope);
  const packageUrl = new URL(encodeURIComponent(packageName).replace(/^%40/, "@"), registryUrl_);
  const authInfo = (0, import_registry_auth_token.default)(registryUrl_.toString(), { recursive: true });
  const headers = {
    accept: "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"
  };
  if (options2.fullMetadata) {
    delete headers.accept;
  }
  if (authInfo) {
    headers.authorization = `${authInfo.type} ${authInfo.token}`;
  }
  let data;
  try {
    data = await distribution_default(packageUrl, { headers, keepalive: true }).json();
  } catch (error) {
    if (error?.response?.status === 404) {
      throw new PackageNotFoundError(packageName);
    }
    throw error;
  }
  if (options2.allVersions) {
    return data;
  }
  const versionError = new VersionNotFoundError(packageName, version2);
  if (data["dist-tags"][version2]) {
    const { time } = data;
    data = data.versions[data["dist-tags"][version2]];
    data.time = time;
  } else if (version2) {
    const versionExists = Boolean(data.versions[version2]);
    if (omitDeprecated && !versionExists) {
      for (const [metadataVersion, metadata] of Object.entries(data.versions)) {
        if (metadata.deprecated) {
          delete data.versions[metadataVersion];
        }
      }
    }
    if (!versionExists) {
      const versions = Object.keys(data.versions);
      version2 = import_semver2.default.maxSatisfying(versions, version2);
      if (!version2) {
        throw versionError;
      }
    }
    const { time } = data;
    data = data.versions[version2];
    data.time = time;
    if (!data) {
      throw versionError;
    }
  }
  return data;
}
__name(packageJson2, "packageJson");

// node_modules/latest-version/index.js
async function latestVersion(packageName, options2) {
  const { version: version2 } = await packageJson2(packageName.toLowerCase(), options2);
  return version2;
}
__name(latestVersion, "latestVersion");

// node_modules/is-npm/index.js
init_esbuild_shims();
import process44 from "node:process";
var packageJson3 = process44.env.npm_package_json;
var userAgent = process44.env.npm_config_user_agent;
var isNpm6 = Boolean(userAgent && userAgent.startsWith("npm"));
var isNpm7 = Boolean(packageJson3 && packageJson3.endsWith("package.json"));
var isNpm = isNpm6 || isNpm7;
var isYarn = Boolean(userAgent && userAgent.startsWith("yarn"));
var isNpmOrYarn = isNpm || isYarn;

// node_modules/is-installed-globally/index.js
init_esbuild_shims();
import fs87 from "node:fs";
import path101 from "node:path";
import { fileURLToPath as fileURLToPath11 } from "node:url";

// node_modules/global-directory/index.js
init_esbuild_shims();
var import_ini2 = __toESM(require_ini3(), 1);
import process45 from "node:process";
import path99 from "node:path";
import os38 from "node:os";
import fs86 from "node:fs";
var isWindows7 = process45.platform === "win32";
var readRc = /* @__PURE__ */ __name((filePath) => {
  try {
    return import_ini2.default.parse(fs86.readFileSync(filePath, "utf8")).prefix;
  } catch {
  }
}, "readRc");
var getEnvNpmPrefix = /* @__PURE__ */ __name(() => Object.keys(process45.env).reduce((prefix, name3) => /^npm_config_prefix$/i.test(name3) ? process45.env[name3] : prefix, void 0), "getEnvNpmPrefix");
var getGlobalNpmrc = /* @__PURE__ */ __name(() => {
  if (isWindows7 && process45.env.APPDATA) {
    return path99.join(process45.env.APPDATA, "/npm/etc/npmrc");
  }
  if (process45.execPath.includes("/Cellar/node")) {
    const homebrewPrefix = process45.execPath.slice(0, process45.execPath.indexOf("/Cellar/node"));
    return path99.join(homebrewPrefix, "/lib/node_modules/npm/npmrc");
  }
  if (process45.execPath.endsWith("/bin/node")) {
    const installDir = path99.dirname(path99.dirname(process45.execPath));
    return path99.join(installDir, "/etc/npmrc");
  }
}, "getGlobalNpmrc");
var getDefaultNpmPrefix = /* @__PURE__ */ __name(() => {
  if (isWindows7) {
    const { APPDATA } = process45.env;
    return APPDATA ? path99.join(APPDATA, "npm") : path99.dirname(process45.execPath);
  }
  return path99.dirname(path99.dirname(process45.execPath));
}, "getDefaultNpmPrefix");
var getNpmPrefix = /* @__PURE__ */ __name(() => {
  const envPrefix = getEnvNpmPrefix();
  if (envPrefix) {
    return envPrefix;
  }
  const homePrefix = readRc(path99.join(os38.homedir(), ".npmrc"));
  if (homePrefix) {
    return homePrefix;
  }
  if (process45.env.PREFIX) {
    return process45.env.PREFIX;
  }
  const globalPrefix = readRc(getGlobalNpmrc());
  if (globalPrefix) {
    return globalPrefix;
  }
  return getDefaultNpmPrefix();
}, "getNpmPrefix");
var npmPrefix = path99.resolve(getNpmPrefix());
var getYarnWindowsDirectory = /* @__PURE__ */ __name(() => {
  if (isWindows7 && process45.env.LOCALAPPDATA) {
    const dir = path99.join(process45.env.LOCALAPPDATA, "Yarn");
    if (fs86.existsSync(dir)) {
      return dir;
    }
  }
  return false;
}, "getYarnWindowsDirectory");
var getYarnPrefix = /* @__PURE__ */ __name(() => {
  if (process45.env.PREFIX) {
    return process45.env.PREFIX;
  }
  const windowsPrefix = getYarnWindowsDirectory();
  if (windowsPrefix) {
    return windowsPrefix;
  }
  const configPrefix = path99.join(os38.homedir(), ".config/yarn");
  if (fs86.existsSync(configPrefix)) {
    return configPrefix;
  }
  const homePrefix = path99.join(os38.homedir(), ".yarn-config");
  if (fs86.existsSync(homePrefix)) {
    return homePrefix;
  }
  return npmPrefix;
}, "getYarnPrefix");
var globalDirectory = {};
globalDirectory.npm = {};
globalDirectory.npm.prefix = npmPrefix;
globalDirectory.npm.packages = path99.join(npmPrefix, isWindows7 ? "node_modules" : "lib/node_modules");
globalDirectory.npm.binaries = isWindows7 ? npmPrefix : path99.join(npmPrefix, "bin");
var yarnPrefix = path99.resolve(getYarnPrefix());
globalDirectory.yarn = {};
globalDirectory.yarn.prefix = yarnPrefix;
globalDirectory.yarn.packages = path99.join(yarnPrefix, getYarnWindowsDirectory() ? "Data/global/node_modules" : "global/node_modules");
globalDirectory.yarn.binaries = path99.join(globalDirectory.yarn.packages, ".bin");
var global_directory_default = globalDirectory;

// node_modules/is-path-inside/index.js
init_esbuild_shims();
import path100 from "node:path";
function isPathInside(childPath, parentPath) {
  const relation = path100.relative(parentPath, childPath);
  return Boolean(
    relation && relation !== ".." && !relation.startsWith(`..${path100.sep}`) && relation !== path100.resolve(childPath)
  );
}
__name(isPathInside, "isPathInside");

// node_modules/is-installed-globally/index.js
var __dirname7 = path101.dirname(fileURLToPath11(import.meta.url));
var isInstalledGlobally = (() => {
  try {
    return isPathInside(__dirname7, global_directory_default.yarn.packages) || isPathInside(__dirname7, fs87.realpathSync(global_directory_default.npm.packages));
  } catch {
    return false;
  }
})();
var is_installed_globally_default = isInstalledGlobally;

// node_modules/update-notifier/node_modules/boxen/index.js
init_esbuild_shims();
import process46 from "node:process";

// node_modules/update-notifier/node_modules/string-width/index.js
init_esbuild_shims();
init_strip_ansi();
var import_emoji_regex5 = __toESM(require_emoji_regex5(), 1);
var segmenter5 = new Intl.Segmenter();
var defaultIgnorableCodePointRegex5 = new RegExp("^\\p{Default_Ignorable_Code_Point}$", "u");
function stringWidth5(string, options2 = {}) {
  if (typeof string !== "string" || string.length === 0) {
    return 0;
  }
  const {
    ambiguousIsNarrow = true,
    countAnsiEscapeCodes = false
  } = options2;
  if (!countAnsiEscapeCodes) {
    string = stripAnsi(string);
  }
  if (string.length === 0) {
    return 0;
  }
  let width = 0;
  const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
  for (const { segment: character } of segmenter5.segment(string)) {
    const codePoint = character.codePointAt(0);
    if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159) {
      continue;
    }
    if (codePoint >= 8203 && codePoint <= 8207 || codePoint === 65279) {
      continue;
    }
    if (codePoint >= 768 && codePoint <= 879 || codePoint >= 6832 && codePoint <= 6911 || codePoint >= 7616 && codePoint <= 7679 || codePoint >= 8400 && codePoint <= 8447 || codePoint >= 65056 && codePoint <= 65071) {
      continue;
    }
    if (codePoint >= 55296 && codePoint <= 57343) {
      continue;
    }
    if (codePoint >= 65024 && codePoint <= 65039) {
      continue;
    }
    if (defaultIgnorableCodePointRegex5.test(character)) {
      continue;
    }
    if ((0, import_emoji_regex5.default)().test(character)) {
      width += 2;
      continue;
    }
    width += eastAsianWidth(codePoint, eastAsianWidthOptions);
  }
  return width;
}
__name(stringWidth5, "stringWidth");

// node_modules/update-notifier/node_modules/widest-line/index.js
init_esbuild_shims();
function widestLine2(string) {
  let lineWidth = 0;
  for (const line of string.split("\n")) {
    lineWidth = Math.max(lineWidth, stringWidth5(line));
  }
  return lineWidth;
}
__name(widestLine2, "widestLine");

// node_modules/update-notifier/node_modules/boxen/index.js
var import_cli_boxes2 = __toESM(require_cli_boxes(), 1);

// node_modules/update-notifier/node_modules/camelcase/index.js
init_esbuild_shims();
var UPPERCASE = /[\p{Lu}]/u;
var LOWERCASE = /[\p{Ll}]/u;
var LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
var IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
var SEPARATORS = /[_.\- ]+/;
var LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source);
var SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu");
var NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu");
var preserveCamelCase = /* @__PURE__ */ __name((string, toLowerCase, toUpperCase, preserveConsecutiveUppercase2) => {
  let isLastCharLower = false;
  let isLastCharUpper = false;
  let isLastLastCharUpper = false;
  let isLastLastCharPreserved = false;
  for (let index = 0; index < string.length; index++) {
    const character = string[index];
    isLastLastCharPreserved = index > 2 ? string[index - 3] === "-" : true;
    if (isLastCharLower && UPPERCASE.test(character)) {
      string = string.slice(0, index) + "-" + string.slice(index);
      isLastCharLower = false;
      isLastLastCharUpper = isLastCharUpper;
      isLastCharUpper = true;
      index++;
    } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character) && (!isLastLastCharPreserved || preserveConsecutiveUppercase2)) {
      string = string.slice(0, index - 1) + "-" + string.slice(index - 1);
      isLastLastCharUpper = isLastCharUpper;
      isLastCharUpper = false;
      isLastCharLower = true;
    } else {
      isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;
      isLastLastCharUpper = isLastCharUpper;
      isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;
    }
  }
  return string;
}, "preserveCamelCase");
var preserveConsecutiveUppercase = /* @__PURE__ */ __name((input, toLowerCase) => {
  LEADING_CAPITAL.lastIndex = 0;
  return input.replaceAll(LEADING_CAPITAL, (match2) => toLowerCase(match2));
}, "preserveConsecutiveUppercase");
var postProcess2 = /* @__PURE__ */ __name((input, toUpperCase) => {
  SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
  NUMBERS_AND_IDENTIFIER.lastIndex = 0;
  return input.replaceAll(NUMBERS_AND_IDENTIFIER, (match2, pattern, offset) => ["_", "-"].includes(input.charAt(offset + match2.length)) ? match2 : toUpperCase(match2)).replaceAll(SEPARATORS_AND_IDENTIFIER, (_, identifier2) => toUpperCase(identifier2));
}, "postProcess");
function camelCase2(input, options2) {
  if (!(typeof input === "string" || Array.isArray(input))) {
    throw new TypeError("Expected the input to be `string | string[]`");
  }
  options2 = {
    pascalCase: false,
    preserveConsecutiveUppercase: false,
    ...options2
  };
  if (Array.isArray(input)) {
    input = input.map((x) => x.trim()).filter((x) => x.length).join("-");
  } else {
    input = input.trim();
  }
  if (input.length === 0) {
    return "";
  }
  const toLowerCase = options2.locale === false ? (string) => string.toLowerCase() : (string) => string.toLocaleLowerCase(options2.locale);
  const toUpperCase = options2.locale === false ? (string) => string.toUpperCase() : (string) => string.toLocaleUpperCase(options2.locale);
  if (input.length === 1) {
    if (SEPARATORS.test(input)) {
      return "";
    }
    return options2.pascalCase ? toUpperCase(input) : toLowerCase(input);
  }
  const hasUpperCase = input !== toLowerCase(input);
  if (hasUpperCase) {
    input = preserveCamelCase(input, toLowerCase, toUpperCase, options2.preserveConsecutiveUppercase);
  }
  input = input.replace(LEADING_SEPARATORS, "");
  input = options2.preserveConsecutiveUppercase ? preserveConsecutiveUppercase(input, toLowerCase) : toLowerCase(input);
  if (options2.pascalCase) {
    input = toUpperCase(input.charAt(0)) + input.slice(1);
  }
  return postProcess2(input, toUpperCase);
}
__name(camelCase2, "camelCase");

// node_modules/update-notifier/node_modules/boxen/index.js
var import_ansi_align = __toESM(require_ansi_align(), 1);
var import_cli_boxes3 = __toESM(require_cli_boxes(), 1);
var NEWLINE = "\n";
var PAD = " ";
var NONE = "none";
var terminalColumns = /* @__PURE__ */ __name(() => {
  const { env: env7, stdout, stderr } = process46;
  if (stdout?.columns) {
    return stdout.columns;
  }
  if (stderr?.columns) {
    return stderr.columns;
  }
  if (env7.COLUMNS) {
    return Number.parseInt(env7.COLUMNS, 10);
  }
  return 80;
}, "terminalColumns");
var getObject = /* @__PURE__ */ __name((detail) => typeof detail === "number" ? {
  top: detail,
  right: detail * 3,
  bottom: detail,
  left: detail * 3
} : {
  top: 0,
  right: 0,
  bottom: 0,
  left: 0,
  ...detail
}, "getObject");
var getBorderWidth = /* @__PURE__ */ __name((borderStyle) => borderStyle === NONE ? 0 : 2, "getBorderWidth");
var getBorderChars = /* @__PURE__ */ __name((borderStyle) => {
  const sides = [
    "topLeft",
    "topRight",
    "bottomRight",
    "bottomLeft",
    "left",
    "right",
    "top",
    "bottom"
  ];
  let characters;
  if (borderStyle === NONE) {
    borderStyle = {};
    for (const side of sides) {
      borderStyle[side] = "";
    }
  }
  if (typeof borderStyle === "string") {
    characters = import_cli_boxes2.default[borderStyle];
    if (!characters) {
      throw new TypeError(`Invalid border style: ${borderStyle}`);
    }
  } else {
    if (typeof borderStyle?.vertical === "string") {
      borderStyle.left = borderStyle.vertical;
      borderStyle.right = borderStyle.vertical;
    }
    if (typeof borderStyle?.horizontal === "string") {
      borderStyle.top = borderStyle.horizontal;
      borderStyle.bottom = borderStyle.horizontal;
    }
    for (const side of sides) {
      if (borderStyle[side] === null || typeof borderStyle[side] !== "string") {
        throw new TypeError(`Invalid border style: ${side}`);
      }
    }
    characters = borderStyle;
  }
  return characters;
}, "getBorderChars");
var makeTitle = /* @__PURE__ */ __name((text, horizontal, alignment) => {
  let title = "";
  const textWidth = stringWidth5(text);
  switch (alignment) {
    case "left": {
      title = text + horizontal.slice(textWidth);
      break;
    }
    case "right": {
      title = horizontal.slice(textWidth) + text;
      break;
    }
    default: {
      horizontal = horizontal.slice(textWidth);
      if (horizontal.length % 2 === 1) {
        horizontal = horizontal.slice(Math.floor(horizontal.length / 2));
        title = horizontal.slice(1) + text + horizontal;
      } else {
        horizontal = horizontal.slice(horizontal.length / 2);
        title = horizontal + text + horizontal;
      }
      break;
    }
  }
  return title;
}, "makeTitle");
var makeContentText = /* @__PURE__ */ __name((text, { padding, width, textAlignment, height }) => {
  text = (0, import_ansi_align.default)(text, { align: textAlignment });
  let lines = text.split(NEWLINE);
  const textWidth = widestLine2(text);
  const max = width - padding.left - padding.right;
  if (textWidth > max) {
    const newLines = [];
    for (const line of lines) {
      const createdLines = wrapAnsi(line, max, { hard: true });
      const alignedLines = (0, import_ansi_align.default)(createdLines, { align: textAlignment });
      const alignedLinesArray = alignedLines.split("\n");
      const longestLength = Math.max(...alignedLinesArray.map((s2) => stringWidth5(s2)));
      for (const alignedLine of alignedLinesArray) {
        let paddedLine;
        switch (textAlignment) {
          case "center": {
            paddedLine = PAD.repeat((max - longestLength) / 2) + alignedLine;
            break;
          }
          case "right": {
            paddedLine = PAD.repeat(max - longestLength) + alignedLine;
            break;
          }
          default: {
            paddedLine = alignedLine;
            break;
          }
        }
        newLines.push(paddedLine);
      }
    }
    lines = newLines;
  }
  if (textAlignment === "center" && textWidth < max) {
    lines = lines.map((line) => PAD.repeat((max - textWidth) / 2) + line);
  } else if (textAlignment === "right" && textWidth < max) {
    lines = lines.map((line) => PAD.repeat(max - textWidth) + line);
  }
  const paddingLeft = PAD.repeat(padding.left);
  const paddingRight = PAD.repeat(padding.right);
  lines = lines.map((line) => {
    const newLine = paddingLeft + line + paddingRight;
    return newLine + PAD.repeat(width - stringWidth5(newLine));
  });
  if (padding.top > 0) {
    lines = [...Array.from({ length: padding.top }).fill(PAD.repeat(width)), ...lines];
  }
  if (padding.bottom > 0) {
    lines = [...lines, ...Array.from({ length: padding.bottom }).fill(PAD.repeat(width))];
  }
  if (height && lines.length > height) {
    lines = lines.slice(0, height);
  } else if (height && lines.length < height) {
    lines = [...lines, ...Array.from({ length: height - lines.length }).fill(PAD.repeat(width))];
  }
  return lines.join(NEWLINE);
}, "makeContentText");
var boxContent = /* @__PURE__ */ __name((content, contentWidth, options2) => {
  const colorizeBorder = /* @__PURE__ */ __name((border) => {
    const newBorder = options2.borderColor ? getColorFunction(options2.borderColor)(border) : border;
    return options2.dimBorder ? source_default2.dim(newBorder) : newBorder;
  }, "colorizeBorder");
  const colorizeContent = /* @__PURE__ */ __name((content2) => options2.backgroundColor ? getBGColorFunction(options2.backgroundColor)(content2) : content2, "colorizeContent");
  const chars = getBorderChars(options2.borderStyle);
  const columns = terminalColumns();
  let marginLeft = PAD.repeat(options2.margin.left);
  if (options2.float === "center") {
    const marginWidth = Math.max((columns - contentWidth - getBorderWidth(options2.borderStyle)) / 2, 0);
    marginLeft = PAD.repeat(marginWidth);
  } else if (options2.float === "right") {
    const marginWidth = Math.max(columns - contentWidth - options2.margin.right - getBorderWidth(options2.borderStyle), 0);
    marginLeft = PAD.repeat(marginWidth);
  }
  let result = "";
  if (options2.margin.top) {
    result += NEWLINE.repeat(options2.margin.top);
  }
  if (options2.borderStyle !== NONE || options2.title) {
    result += colorizeBorder(marginLeft + chars.topLeft + (options2.title ? makeTitle(options2.title, chars.top.repeat(contentWidth), options2.titleAlignment) : chars.top.repeat(contentWidth)) + chars.topRight) + NEWLINE;
  }
  const lines = content.split(NEWLINE);
  result += lines.map((line) => marginLeft + colorizeBorder(chars.left) + colorizeContent(line) + colorizeBorder(chars.right)).join(NEWLINE);
  if (options2.borderStyle !== NONE) {
    result += NEWLINE + colorizeBorder(marginLeft + chars.bottomLeft + chars.bottom.repeat(contentWidth) + chars.bottomRight);
  }
  if (options2.margin.bottom) {
    result += NEWLINE.repeat(options2.margin.bottom);
  }
  return result;
}, "boxContent");
var sanitizeOptions = /* @__PURE__ */ __name((options2) => {
  if (options2.fullscreen && process46?.stdout) {
    let newDimensions = [process46.stdout.columns, process46.stdout.rows];
    if (typeof options2.fullscreen === "function") {
      newDimensions = options2.fullscreen(...newDimensions);
    }
    options2.width ||= newDimensions[0];
    options2.height ||= newDimensions[1];
  }
  options2.width &&= Math.max(1, options2.width - getBorderWidth(options2.borderStyle));
  options2.height &&= Math.max(1, options2.height - getBorderWidth(options2.borderStyle));
  return options2;
}, "sanitizeOptions");
var formatTitle = /* @__PURE__ */ __name((title, borderStyle) => borderStyle === NONE ? title : ` ${title} `, "formatTitle");
var determineDimensions = /* @__PURE__ */ __name((text, options2) => {
  options2 = sanitizeOptions(options2);
  const widthOverride = options2.width !== void 0;
  const columns = terminalColumns();
  const borderWidth = getBorderWidth(options2.borderStyle);
  const maxWidth = columns - options2.margin.left - options2.margin.right - borderWidth;
  const widest = widestLine2(wrapAnsi(text, columns - borderWidth, { hard: true, trim: false })) + options2.padding.left + options2.padding.right;
  if (options2.title && widthOverride) {
    options2.title = options2.title.slice(0, Math.max(0, options2.width - 2));
    options2.title &&= formatTitle(options2.title, options2.borderStyle);
  } else if (options2.title) {
    options2.title = options2.title.slice(0, Math.max(0, maxWidth - 2));
    if (options2.title) {
      options2.title = formatTitle(options2.title, options2.borderStyle);
      if (stringWidth5(options2.title) > widest) {
        options2.width = stringWidth5(options2.title);
      }
    }
  }
  options2.width ||= widest;
  if (!widthOverride) {
    if (options2.margin.left && options2.margin.right && options2.width > maxWidth) {
      const spaceForMargins = columns - options2.width - borderWidth;
      const multiplier = spaceForMargins / (options2.margin.left + options2.margin.right);
      options2.margin.left = Math.max(0, Math.floor(options2.margin.left * multiplier));
      options2.margin.right = Math.max(0, Math.floor(options2.margin.right * multiplier));
    }
    options2.width = Math.min(options2.width, columns - borderWidth - options2.margin.left - options2.margin.right);
  }
  if (options2.width - (options2.padding.left + options2.padding.right) <= 0) {
    options2.padding.left = 0;
    options2.padding.right = 0;
  }
  if (options2.height && options2.height - (options2.padding.top + options2.padding.bottom) <= 0) {
    options2.padding.top = 0;
    options2.padding.bottom = 0;
  }
  return options2;
}, "determineDimensions");
var isHex2 = /* @__PURE__ */ __name((color) => color.match(/^#(?:[0-f]{3}){1,2}$/i), "isHex");
var isColorValid = /* @__PURE__ */ __name((color) => typeof color === "string" && (source_default2[color] ?? isHex2(color)), "isColorValid");
var getColorFunction = /* @__PURE__ */ __name((color) => isHex2(color) ? source_default2.hex(color) : source_default2[color], "getColorFunction");
var getBGColorFunction = /* @__PURE__ */ __name((color) => isHex2(color) ? source_default2.bgHex(color) : source_default2[camelCase2(["bg", color])], "getBGColorFunction");
function boxen(text, options2) {
  options2 = {
    padding: 0,
    borderStyle: "single",
    dimBorder: false,
    textAlignment: "left",
    float: "left",
    titleAlignment: "left",
    ...options2
  };
  if (options2.align) {
    options2.textAlignment = options2.align;
  }
  if (options2.borderColor && !isColorValid(options2.borderColor)) {
    throw new Error(`${options2.borderColor} is not a valid borderColor`);
  }
  if (options2.backgroundColor && !isColorValid(options2.backgroundColor)) {
    throw new Error(`${options2.backgroundColor} is not a valid backgroundColor`);
  }
  options2.padding = getObject(options2.padding);
  options2.margin = getObject(options2.margin);
  options2 = determineDimensions(text, options2);
  text = makeContentText(text, options2);
  return boxContent(text, options2.width, options2);
}
__name(boxen, "boxen");

// node_modules/pupa/index.js
init_esbuild_shims();

// node_modules/escape-goat/index.js
init_esbuild_shims();
var _htmlEscape = /* @__PURE__ */ __name((string) => string.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#39;").replace(/</g, "&lt;").replace(/>/g, "&gt;"), "_htmlEscape");
function htmlEscape(strings, ...values) {
  if (typeof strings === "string") {
    return _htmlEscape(strings);
  }
  let output = strings[0];
  for (const [index, value] of values.entries()) {
    output = output + _htmlEscape(String(value)) + strings[index + 1];
  }
  return output;
}
__name(htmlEscape, "htmlEscape");

// node_modules/pupa/index.js
var MissingValueError = class extends Error {
  static {
    __name(this, "MissingValueError");
  }
  constructor(key) {
    super(`Missing a value for ${key ? `the placeholder: ${key}` : "a placeholder"}`, key);
    this.name = "MissingValueError";
    this.key = key;
  }
};
function pupa(template, data, { ignoreMissing = false, transform = /* @__PURE__ */ __name(({ value }) => value, "transform") } = {}) {
  if (typeof template !== "string") {
    throw new TypeError(`Expected a \`string\` in the first argument, got \`${typeof template}\``);
  }
  if (typeof data !== "object") {
    throw new TypeError(`Expected an \`object\` or \`Array\` in the second argument, got \`${typeof data}\``);
  }
  const replace2 = /* @__PURE__ */ __name((placeholder, key) => {
    let value = data;
    for (const property of key.split(".")) {
      value = value ? value[property] : void 0;
    }
    const transformedValue = transform({ value, key });
    if (transformedValue === void 0) {
      if (ignoreMissing) {
        return placeholder;
      }
      throw new MissingValueError(key);
    }
    return String(transformedValue);
  }, "replace");
  const composeHtmlEscape = /* @__PURE__ */ __name((replacer) => (...args) => htmlEscape(replacer(...args)), "composeHtmlEscape");
  const doubleBraceRegex = /{{(\d+|[a-z$_][\w\-$]*?(?:\.[\w\-$]*?)*?)}}/gi;
  if (doubleBraceRegex.test(template)) {
    template = template.replace(doubleBraceRegex, composeHtmlEscape(replace2));
  }
  const braceRegex = /{(\d+|[a-z$_][\w\-$]*?(?:\.[\w\-$]*?)*?)}/gi;
  return template.replace(braceRegex, replace2);
}
__name(pupa, "pupa");

// node_modules/update-notifier/update-notifier.js
var __dirname8 = path102.dirname(fileURLToPath12(import.meta.url));
var ONE_DAY = 1e3 * 60 * 60 * 24;
var UpdateNotifier = class {
  static {
    __name(this, "UpdateNotifier");
  }
  // Public
  config;
  update;
  // Semi-private (used for tests)
  _packageName;
  // eslint-disable-line lines-between-class-members
  _shouldNotifyInNpmScript;
  #options;
  // eslint-disable-line lines-between-class-members
  #packageVersion;
  #updateCheckInterval;
  #isDisabled;
  constructor(options2 = {}) {
    this.#options = options2;
    options2.pkg ??= {};
    options2.distTag ??= "latest";
    options2.pkg = {
      name: options2.pkg.name ?? options2.packageName,
      version: options2.pkg.version ?? options2.packageVersion
    };
    if (!options2.pkg.name || !options2.pkg.version) {
      throw new Error("pkg.name and pkg.version required");
    }
    this._packageName = options2.pkg.name;
    this.#packageVersion = options2.pkg.version;
    this.#updateCheckInterval = typeof options2.updateCheckInterval === "number" ? options2.updateCheckInterval : ONE_DAY;
    this.#isDisabled = "NO_UPDATE_NOTIFIER" in process47.env || process47.env.NODE_ENV === "test" || process47.argv.includes("--no-update-notifier") || is_in_ci_default;
    this._shouldNotifyInNpmScript = options2.shouldNotifyInNpmScript;
    if (!this.#isDisabled) {
      try {
        this.config = new Configstore(`update-notifier-${this._packageName}`, {
          optOut: false,
          // Init with the current time so the first check is only
          // after the set interval, so not to bother users right away
          lastUpdateCheck: Date.now()
        });
      } catch {
        const message = source_default2.yellow(format3(" %s update check failed ", options2.pkg.name)) + format3("\n Try running with %s or get access ", source_default2.cyan("sudo")) + "\n to the local update config store via \n" + source_default2.cyan(format3(" sudo chown -R $USER:$(id -gn $USER) %s ", xdgConfig));
        process47.on("exit", () => {
          console.error(boxen(message, { textAlignment: "center" }));
        });
      }
    }
  }
  check() {
    if (!this.config || this.config.get("optOut") || this.#isDisabled) {
      return;
    }
    this.update = this.config.get("update");
    if (this.update) {
      this.update.current = this.#packageVersion;
      this.config.delete("update");
    }
    if (Date.now() - this.config.get("lastUpdateCheck") < this.#updateCheckInterval) {
      return;
    }
    spawn7(process47.execPath, [path102.join(__dirname8, "check.js"), JSON.stringify(this.#options)], {
      detached: true,
      stdio: "ignore"
    }).unref();
  }
  async fetchInfo() {
    const { distTag } = this.#options;
    const latest = await latestVersion(this._packageName, { version: distTag });
    return {
      latest,
      current: this.#packageVersion,
      type: (0, import_diff4.default)(this.#packageVersion, latest) ?? distTag,
      name: this._packageName
    };
  }
  notify(options2) {
    const suppressForNpm = !this._shouldNotifyInNpmScript && isNpmOrYarn;
    if (!process47.stdout.isTTY || suppressForNpm || !this.update || !(0, import_gt.default)(this.update.latest, this.update.current)) {
      return this;
    }
    options2 = {
      isGlobal: is_installed_globally_default,
      ...options2
    };
    const installCommand2 = options2.isGlobal ? `npm i -g ${this._packageName}` : `npm i ${this._packageName}`;
    const defaultTemplate = "Update available " + source_default2.dim("{currentVersion}") + source_default2.reset(" \u2192 ") + source_default2.green("{latestVersion}") + " \nRun " + source_default2.cyan("{updateCommand}") + " to update";
    const template = options2.message || defaultTemplate;
    options2.boxenOptions ??= {
      padding: 1,
      margin: 1,
      textAlignment: "center",
      borderColor: "yellow",
      borderStyle: "round"
    };
    const message = boxen(
      pupa(template, {
        packageName: this._packageName,
        currentVersion: this.update.current,
        latestVersion: this.update.latest,
        updateCommand: installCommand2
      }),
      options2.boxenOptions
    );
    if (options2.defer === false) {
      console.error(message);
    } else {
      process47.on("exit", () => {
        console.error(message);
      });
    }
    return this;
  }
};

// node_modules/update-notifier/index.js
function updateNotifier(options2) {
  const updateNotifier2 = new UpdateNotifier(options2);
  updateNotifier2.check();
  return updateNotifier2;
}
__name(updateNotifier, "updateNotifier");

// packages/cli/src/ui/utils/updateCheck.ts
var import_semver3 = __toESM(require_semver3(), 1);
function getBestAvailableUpdate(nightly, stable) {
  if (!nightly) return stable || null;
  if (!stable) return nightly || null;
  const nightlyVer = nightly.latest;
  const stableVer = stable.latest;
  if (import_semver3.default.coerce(stableVer)?.version === import_semver3.default.coerce(nightlyVer)?.version) {
    return nightly;
  }
  return import_semver3.default.gt(stableVer, nightlyVer) ? stable : nightly;
}
__name(getBestAvailableUpdate, "getBestAvailableUpdate");
async function checkForUpdates() {
  try {
    if (process.env["DEV"] === "true") {
      return null;
    }
    const packageJson4 = await getPackageJson();
    if (!packageJson4 || !packageJson4.name || !packageJson4.version) {
      return null;
    }
    const { name: name3, version: currentVersion } = packageJson4;
    const isNightly = currentVersion.includes("nightly");
    const createNotifier = /* @__PURE__ */ __name((distTag) => updateNotifier({
      pkg: {
        name: name3,
        version: currentVersion
      },
      updateCheckInterval: 0,
      shouldNotifyInNpmScript: true,
      distTag
    }), "createNotifier");
    if (isNightly) {
      const [nightlyUpdateInfo, latestUpdateInfo] = await Promise.all([
        createNotifier("nightly").fetchInfo(),
        createNotifier("latest").fetchInfo()
      ]);
      const bestUpdate = getBestAvailableUpdate(
        nightlyUpdateInfo,
        latestUpdateInfo
      );
      if (bestUpdate && import_semver3.default.gt(bestUpdate.latest, currentVersion)) {
        const message = `A new version of Qwen Code is available! ${currentVersion} \u2192 ${bestUpdate.latest}`;
        return {
          message,
          update: { ...bestUpdate, current: currentVersion }
        };
      }
    } else {
      const updateInfo = await createNotifier("latest").fetchInfo();
      if (updateInfo && import_semver3.default.gt(updateInfo.latest, currentVersion)) {
        const message = `Qwen Code update available! ${currentVersion} \u2192 ${updateInfo.latest}`;
        return {
          message,
          update: { ...updateInfo, current: currentVersion }
        };
      }
    }
    return null;
  } catch (e2) {
    console.warn("Failed to check for updates: " + e2);
    return null;
  }
}
__name(checkForUpdates, "checkForUpdates");

// packages/cli/src/utils/handleAutoUpdate.ts
init_esbuild_shims();

// packages/cli/src/utils/installationInfo.ts
init_esbuild_shims();
import * as fs88 from "node:fs";
import * as path103 from "node:path";
import * as childProcess2 from "node:child_process";
function getInstallationInfo(projectRoot, isAutoUpdateDisabled) {
  const cliPath = process.argv[1];
  if (!cliPath) {
    return { packageManager: "unknown" /* UNKNOWN */, isGlobal: false };
  }
  try {
    const realPath = fs88.realpathSync(cliPath).replace(/\\/g, "/");
    const normalizedProjectRoot = projectRoot?.replace(/\\/g, "/");
    const isGit = isGitRepository(process.cwd());
    if (isGit && normalizedProjectRoot && realPath.startsWith(normalizedProjectRoot) && !realPath.includes("/node_modules/")) {
      return {
        packageManager: "unknown" /* UNKNOWN */,
        // Not managed by a package manager in this sense
        isGlobal: false,
        updateMessage: 'Running from a local git clone. Please update with "git pull".'
      };
    }
    if (realPath.includes("/.npm/_npx") || realPath.includes("/npm/_npx")) {
      return {
        packageManager: "npx" /* NPX */,
        isGlobal: false,
        updateMessage: "Running via npx, update not applicable."
      };
    }
    if (realPath.includes("/.pnpm/_pnpx")) {
      return {
        packageManager: "pnpx" /* PNPX */,
        isGlobal: false,
        updateMessage: "Running via pnpx, update not applicable."
      };
    }
    if (process.platform === "darwin") {
      try {
        childProcess2.execSync('brew list -1 | grep -q "^qwen-code$"', {
          stdio: "ignore"
        });
        return {
          packageManager: "homebrew" /* HOMEBREW */,
          isGlobal: true,
          updateMessage: 'Installed via Homebrew. Please update with "brew upgrade".'
        };
      } catch (_error) {
      }
    }
    if (realPath.includes("/.pnpm/global")) {
      const updateCommand3 = "pnpm add -g @qwen-code/qwen-code@latest";
      return {
        packageManager: "pnpm" /* PNPM */,
        isGlobal: true,
        updateCommand: updateCommand3,
        updateMessage: isAutoUpdateDisabled ? `Please run ${updateCommand3} to update` : "Installed with pnpm. Attempting to automatically update now..."
      };
    }
    if (realPath.includes("/.yarn/global")) {
      const updateCommand3 = "yarn global add @qwen-code/qwen-code@latest";
      return {
        packageManager: "yarn" /* YARN */,
        isGlobal: true,
        updateCommand: updateCommand3,
        updateMessage: isAutoUpdateDisabled ? `Please run ${updateCommand3} to update` : "Installed with yarn. Attempting to automatically update now..."
      };
    }
    if (realPath.includes("/.bun/install/cache")) {
      return {
        packageManager: "bunx" /* BUNX */,
        isGlobal: false,
        updateMessage: "Running via bunx, update not applicable."
      };
    }
    if (realPath.includes("/.bun/bin")) {
      const updateCommand3 = "bun add -g @qwen-code/qwen-code@latest";
      return {
        packageManager: "bun" /* BUN */,
        isGlobal: true,
        updateCommand: updateCommand3,
        updateMessage: isAutoUpdateDisabled ? `Please run ${updateCommand3} to update` : "Installed with bun. Attempting to automatically update now..."
      };
    }
    if (normalizedProjectRoot && realPath.startsWith(`${normalizedProjectRoot}/node_modules`)) {
      let pm = "npm" /* NPM */;
      if (fs88.existsSync(path103.join(projectRoot, "yarn.lock"))) {
        pm = "yarn" /* YARN */;
      } else if (fs88.existsSync(path103.join(projectRoot, "pnpm-lock.yaml"))) {
        pm = "pnpm" /* PNPM */;
      } else if (fs88.existsSync(path103.join(projectRoot, "bun.lockb"))) {
        pm = "bun" /* BUN */;
      }
      return {
        packageManager: pm,
        isGlobal: false,
        updateMessage: "Locally installed. Please update via your project's package.json."
      };
    }
    const updateCommand2 = "npm install -g @qwen-code/qwen-code@latest";
    return {
      packageManager: "npm" /* NPM */,
      isGlobal: true,
      updateCommand: updateCommand2,
      updateMessage: isAutoUpdateDisabled ? `Please run ${updateCommand2} to update` : "Installed with npm. Attempting to automatically update now..."
    };
  } catch (error) {
    console.log(error);
    return { packageManager: "unknown" /* UNKNOWN */, isGlobal: false };
  }
}
__name(getInstallationInfo, "getInstallationInfo");

// packages/cli/src/utils/updateEventEmitter.ts
init_esbuild_shims();
import { EventEmitter as EventEmitter9 } from "node:events";
var updateEventEmitter = new EventEmitter9();

// packages/cli/src/utils/spawnWrapper.ts
init_esbuild_shims();
import { spawn as spawn8 } from "node:child_process";
var spawnWrapper = spawn8;

// packages/cli/src/utils/handleAutoUpdate.ts
function handleAutoUpdate(info, settings, projectRoot, spawnFn = spawnWrapper) {
  if (!info) {
    return;
  }
  if (settings.merged.general?.disableUpdateNag) {
    return;
  }
  const installationInfo = getInstallationInfo(
    projectRoot,
    settings.merged.general?.disableAutoUpdate ?? false
  );
  let combinedMessage = info.message;
  if (installationInfo.updateMessage) {
    combinedMessage += `
${installationInfo.updateMessage}`;
  }
  updateEventEmitter.emit("update-received", {
    message: combinedMessage
  });
  if (!installationInfo.updateCommand || settings.merged.general?.disableAutoUpdate) {
    return;
  }
  const isNightly = info.update.latest.includes("nightly");
  const updateCommand2 = installationInfo.updateCommand.replace(
    "@latest",
    isNightly ? "@nightly" : `@${info.update.latest}`
  );
  const updateProcess = spawnFn(updateCommand2, { stdio: "pipe", shell: true });
  let errorOutput = "";
  updateProcess.stderr.on("data", (data) => {
    errorOutput += data.toString();
  });
  updateProcess.on("close", (code2) => {
    if (code2 === 0) {
      updateEventEmitter.emit("update-success", {
        message: "Update successful! The new version will be used on your next run."
      });
    } else {
      updateEventEmitter.emit("update-failed", {
        message: `Automatic update failed. Please try updating manually. (command: ${updateCommand2}, stderr: ${errorOutput.trim()})`
      });
    }
  });
  updateProcess.on("error", (err) => {
    updateEventEmitter.emit("update-failed", {
      message: `Automatic update failed. Please try updating manually. (error: ${err.message})`
    });
  });
  return updateProcess;
}
__name(handleAutoUpdate, "handleAutoUpdate");
function setUpdateHandler(addItem, setUpdateInfo) {
  let successfullyInstalled = false;
  const handleUpdateRecieved = /* @__PURE__ */ __name((info) => {
    setUpdateInfo(info);
    const savedMessage = info.message;
    setTimeout(() => {
      if (!successfullyInstalled) {
        addItem(
          {
            type: "info" /* INFO */,
            text: savedMessage
          },
          Date.now()
        );
      }
      setUpdateInfo(null);
    }, 6e4);
  }, "handleUpdateRecieved");
  const handleUpdateFailed = /* @__PURE__ */ __name(() => {
    setUpdateInfo(null);
    addItem(
      {
        type: "error" /* ERROR */,
        text: `Automatic update failed. Please try updating manually`
      },
      Date.now()
    );
  }, "handleUpdateFailed");
  const handleUpdateSuccess = /* @__PURE__ */ __name(() => {
    successfullyInstalled = true;
    setUpdateInfo(null);
    addItem(
      {
        type: "info" /* INFO */,
        text: `Update successful! The new version will be used on your next run.`
      },
      Date.now()
    );
  }, "handleUpdateSuccess");
  const handleUpdateInfo = /* @__PURE__ */ __name((data) => {
    addItem(
      {
        type: "info" /* INFO */,
        text: data.message
      },
      Date.now()
    );
  }, "handleUpdateInfo");
  updateEventEmitter.on("update-received", handleUpdateRecieved);
  updateEventEmitter.on("update-failed", handleUpdateFailed);
  updateEventEmitter.on("update-success", handleUpdateSuccess);
  updateEventEmitter.on("update-info", handleUpdateInfo);
  return () => {
    updateEventEmitter.off("update-received", handleUpdateRecieved);
    updateEventEmitter.off("update-failed", handleUpdateFailed);
    updateEventEmitter.off("update-success", handleUpdateSuccess);
    updateEventEmitter.off("update-info", handleUpdateInfo);
  };
}
__name(setUpdateHandler, "setUpdateHandler");

// packages/cli/src/ui/utils/ConsolePatcher.ts
init_esbuild_shims();
import util3 from "node:util";
var ConsolePatcher = class {
  static {
    __name(this, "ConsolePatcher");
  }
  originalConsoleLog = console.log;
  originalConsoleWarn = console.warn;
  originalConsoleError = console.error;
  originalConsoleDebug = console.debug;
  originalConsoleInfo = console.info;
  params;
  constructor(params) {
    this.params = params;
  }
  patch() {
    console.log = this.patchConsoleMethod("log", this.originalConsoleLog);
    console.warn = this.patchConsoleMethod("warn", this.originalConsoleWarn);
    console.error = this.patchConsoleMethod("error", this.originalConsoleError);
    console.debug = this.patchConsoleMethod("debug", this.originalConsoleDebug);
    console.info = this.patchConsoleMethod("info", this.originalConsoleInfo);
  }
  cleanup = /* @__PURE__ */ __name(() => {
    console.log = this.originalConsoleLog;
    console.warn = this.originalConsoleWarn;
    console.error = this.originalConsoleError;
    console.debug = this.originalConsoleDebug;
    console.info = this.originalConsoleInfo;
  }, "cleanup");
  formatArgs = /* @__PURE__ */ __name((args) => util3.format(...args), "formatArgs");
  patchConsoleMethod = /* @__PURE__ */ __name((type, originalMethod) => (...args) => {
    if (this.params.stderr) {
      if (type !== "debug" || this.params.debugMode) {
        this.originalConsoleError(this.formatArgs(args));
      }
    } else {
      if (this.params.debugMode) {
        originalMethod.apply(console, args);
      }
      if (type !== "debug" || this.params.debugMode) {
        this.params.onNewMessage?.({
          type,
          content: this.formatArgs(args),
          count: 1
        });
      }
    }
  }, "patchConsoleMethod");
};

// packages/cli/src/ui/hooks/useMessageQueue.ts
init_esbuild_shims();
var import_react122 = __toESM(require_react(), 1);
function useMessageQueue({
  isConfigInitialized,
  streamingState,
  submitQuery
}) {
  const [messageQueue, setMessageQueue] = (0, import_react122.useState)([]);
  const addMessage = (0, import_react122.useCallback)((message) => {
    const trimmedMessage = message.trim();
    if (trimmedMessage.length > 0) {
      setMessageQueue((prev) => [...prev, trimmedMessage]);
    }
  }, []);
  const clearQueue = (0, import_react122.useCallback)(() => {
    setMessageQueue([]);
  }, []);
  const getQueuedMessagesText = (0, import_react122.useCallback)(() => {
    if (messageQueue.length === 0) return "";
    return messageQueue.join("\n\n");
  }, [messageQueue]);
  (0, import_react122.useEffect)(() => {
    if (isConfigInitialized && streamingState === "idle" /* Idle */ && messageQueue.length > 0) {
      const combinedMessage = messageQueue.join("\n\n");
      setMessageQueue([]);
      submitQuery(combinedMessage);
    }
  }, [isConfigInitialized, streamingState, messageQueue, submitQuery]);
  return {
    messageQueue,
    addMessage,
    clearQueue,
    getQueuedMessagesText
  };
}
__name(useMessageQueue, "useMessageQueue");

// packages/cli/src/ui/hooks/useAutoAcceptIndicator.ts
init_esbuild_shims();
var import_react123 = __toESM(require_react(), 1);
function useAutoAcceptIndicator({
  config,
  addItem,
  onApprovalModeChange
}) {
  const currentConfigValue = config.getApprovalMode();
  const [showAutoAcceptIndicator, setShowAutoAcceptIndicator] = (0, import_react123.useState)(currentConfigValue);
  (0, import_react123.useEffect)(() => {
    setShowAutoAcceptIndicator(currentConfigValue);
  }, [currentConfigValue]);
  useKeypress(
    (key) => {
      if (key.shift && key.name === "tab") {
        const currentMode = config.getApprovalMode();
        const currentIndex = APPROVAL_MODES.indexOf(currentMode);
        const nextIndex = currentIndex === -1 ? 0 : (currentIndex + 1) % APPROVAL_MODES.length;
        const nextApprovalMode = APPROVAL_MODES[nextIndex];
        try {
          config.setApprovalMode(nextApprovalMode);
          setShowAutoAcceptIndicator(nextApprovalMode);
          onApprovalModeChange?.(nextApprovalMode);
        } catch (e2) {
          addItem?.(
            {
              type: "info" /* INFO */,
              text: e2.message
            },
            Date.now()
          );
        }
      }
    },
    { isActive: true }
  );
  return showAutoAcceptIndicator;
}
__name(useAutoAcceptIndicator, "useAutoAcceptIndicator");

// packages/cli/src/ui/hooks/useWorkspaceMigration.ts
init_esbuild_shims();
var import_react124 = __toESM(require_react(), 1);
import process48 from "node:process";
function useWorkspaceMigration(settings) {
  const [showWorkspaceMigrationDialog, setShowWorkspaceMigrationDialog] = (0, import_react124.useState)(false);
  const [workspaceExtensions, setWorkspaceExtensions] = (0, import_react124.useState)(
    []
  );
  (0, import_react124.useEffect)(() => {
    if (!(settings.merged.experimental?.extensionManagement ?? true)) {
      return;
    }
    const cwd7 = process48.cwd();
    const extensions = getWorkspaceExtensions(cwd7);
    if (extensions.length > 0 && !settings.merged.extensions?.workspacesWithMigrationNudge?.includes(cwd7)) {
      setWorkspaceExtensions(extensions);
      setShowWorkspaceMigrationDialog(true);
      console.log(settings.merged.extensions);
    }
  }, [
    settings.merged.extensions,
    settings.merged.experimental?.extensionManagement
  ]);
  const onWorkspaceMigrationDialogOpen = /* @__PURE__ */ __name(() => {
    const userSettings = settings.forScope("User" /* User */);
    const extensionSettings = userSettings.settings.extensions || {
      disabled: []
    };
    const workspacesWithMigrationNudge = extensionSettings.workspacesWithMigrationNudge || [];
    const cwd7 = process48.cwd();
    if (!workspacesWithMigrationNudge.includes(cwd7)) {
      workspacesWithMigrationNudge.push(cwd7);
    }
    extensionSettings.workspacesWithMigrationNudge = workspacesWithMigrationNudge;
    settings.setValue("User" /* User */, "extensions", extensionSettings);
  }, "onWorkspaceMigrationDialogOpen");
  const onWorkspaceMigrationDialogClose = /* @__PURE__ */ __name(() => {
    setShowWorkspaceMigrationDialog(false);
  }, "onWorkspaceMigrationDialogClose");
  return {
    showWorkspaceMigrationDialog,
    workspaceExtensions,
    onWorkspaceMigrationDialogOpen,
    onWorkspaceMigrationDialogClose
  };
}
__name(useWorkspaceMigration, "useWorkspaceMigration");

// packages/cli/src/ui/hooks/useGitBranchName.ts
init_esbuild_shims();
var import_react125 = __toESM(require_react(), 1);
import fs89 from "node:fs";
import fsPromises7 from "node:fs/promises";
import path104 from "node:path";
function useGitBranchName(cwd7) {
  const [branchName, setBranchName] = (0, import_react125.useState)(void 0);
  const fetchBranchName = (0, import_react125.useCallback)(async () => {
    try {
      if (!isCommandAvailable("git").available) {
        return;
      }
      const { stdout } = await execCommand(
        "git",
        ["rev-parse", "--abbrev-ref", "HEAD"],
        { cwd: cwd7 }
      );
      const branch = stdout.toString().trim();
      if (branch && branch !== "HEAD") {
        setBranchName(branch);
      } else {
        const { stdout: hashStdout } = await execCommand(
          "git",
          ["rev-parse", "--short", "HEAD"],
          { cwd: cwd7 }
        );
        setBranchName(hashStdout.toString().trim());
      }
    } catch (_error) {
      setBranchName(void 0);
    }
  }, [cwd7, setBranchName]);
  (0, import_react125.useEffect)(() => {
    fetchBranchName();
    const gitLogsHeadPath = path104.join(cwd7, ".git", "logs", "HEAD");
    let watcher;
    const setupWatcher = /* @__PURE__ */ __name(async () => {
      try {
        await fsPromises7.access(gitLogsHeadPath, fs89.constants.F_OK);
        watcher = fs89.watch(gitLogsHeadPath, (eventType) => {
          if (eventType === "change" || eventType === "rename") {
            fetchBranchName();
          }
        });
      } catch (_watchError) {
      }
    }, "setupWatcher");
    setupWatcher();
    return () => {
      watcher?.close();
    };
  }, [cwd7, fetchBranchName]);
  return branchName;
}
__name(useGitBranchName, "useGitBranchName");

// packages/cli/src/ui/hooks/useExtensionUpdates.ts
init_esbuild_shims();
var import_react126 = __toESM(require_react(), 1);
function confirmationRequestsReducer(state, action) {
  switch (action.type) {
    case "add":
      return [...state, action.request];
    case "remove":
      return state.filter((r3) => r3 !== action.request);
    default:
      checkExhaustive(action);
      return state;
  }
}
__name(confirmationRequestsReducer, "confirmationRequestsReducer");
var useExtensionUpdates = /* @__PURE__ */ __name((extensions, addItem, cwd7) => {
  const [extensionsUpdateState, dispatchExtensionStateUpdate] = (0, import_react126.useReducer)(
    extensionUpdatesReducer,
    initialExtensionUpdatesState
  );
  const [
    confirmUpdateExtensionRequests,
    dispatchConfirmUpdateExtensionRequests
  ] = (0, import_react126.useReducer)(confirmationRequestsReducer, []);
  const addConfirmUpdateExtensionRequest = (0, import_react126.useCallback)(
    (original) => {
      const wrappedRequest = {
        prompt: original.prompt,
        onConfirm: /* @__PURE__ */ __name((confirmed) => {
          dispatchConfirmUpdateExtensionRequests({
            type: "remove",
            request: wrappedRequest
          });
          original.onConfirm(confirmed);
        }, "onConfirm")
      };
      dispatchConfirmUpdateExtensionRequests({
        type: "add",
        request: wrappedRequest
      });
    },
    [dispatchConfirmUpdateExtensionRequests]
  );
  (0, import_react126.useEffect)(() => {
    (async () => {
      await checkForAllExtensionUpdates(
        extensions,
        dispatchExtensionStateUpdate
      );
    })();
  }, [extensions, extensions.length, dispatchExtensionStateUpdate]);
  (0, import_react126.useEffect)(() => {
    if (extensionsUpdateState.batchChecksInProgress > 0) {
      return;
    }
    let extensionsWithUpdatesCount = 0;
    for (const extension of extensions) {
      const currentState = extensionsUpdateState.extensionStatuses.get(
        extension.name
      );
      if (!currentState || currentState.processed || currentState.status !== "update available" /* UPDATE_AVAILABLE */) {
        continue;
      }
      dispatchExtensionStateUpdate({
        type: "SET_PROCESSED",
        payload: { name: extension.name, processed: true }
      });
      if (extension.installMetadata?.autoUpdate) {
        updateExtension(
          extension,
          cwd7,
          (description) => requestConsentInteractive(
            description,
            addConfirmUpdateExtensionRequest
          ),
          currentState.status,
          dispatchExtensionStateUpdate
        ).then((result) => {
          if (!result) return;
          addItem(
            {
              type: "info" /* INFO */,
              text: `Extension "${extension.name}" successfully updated: ${result.originalVersion} \u2192 ${result.updatedVersion}.`
            },
            Date.now()
          );
        }).catch((error) => {
          addItem(
            {
              type: "error" /* ERROR */,
              text: getErrorMessage3(error)
            },
            Date.now()
          );
        });
      } else {
        extensionsWithUpdatesCount++;
      }
    }
    if (extensionsWithUpdatesCount > 0) {
      const s2 = extensionsWithUpdatesCount > 1 ? "s" : "";
      addItem(
        {
          type: "info" /* INFO */,
          text: `You have ${extensionsWithUpdatesCount} extension${s2} with an update available, run "/extensions list" for more information.`
        },
        Date.now()
      );
    }
  }, [
    extensions,
    extensionsUpdateState,
    addConfirmUpdateExtensionRequest,
    addItem,
    cwd7
  ]);
  const extensionsUpdateStateComputed = (0, import_react126.useMemo)(() => {
    const result = /* @__PURE__ */ new Map();
    for (const [
      key,
      value
    ] of extensionsUpdateState.extensionStatuses.entries()) {
      result.set(key, value.status);
    }
    return result;
  }, [extensionsUpdateState]);
  return {
    extensionsUpdateState: extensionsUpdateStateComputed,
    extensionsUpdateStateInternal: extensionsUpdateState.extensionStatuses,
    dispatchExtensionStateUpdate,
    confirmUpdateExtensionRequests,
    addConfirmUpdateExtensionRequest
  };
}, "useExtensionUpdates");

// packages/cli/src/ui/hooks/useQuitConfirmation.ts
init_esbuild_shims();
var import_react127 = __toESM(require_react(), 1);
var useQuitConfirmation = /* @__PURE__ */ __name(() => {
  const [isQuitConfirmationOpen, setIsQuitConfirmationOpen] = (0, import_react127.useState)(false);
  const showQuitConfirmation = (0, import_react127.useCallback)(() => {
    setIsQuitConfirmationOpen(true);
  }, []);
  const handleQuitConfirmationSelect = (0, import_react127.useCallback)((choice2) => {
    setIsQuitConfirmationOpen(false);
    if (choice2 === "cancel" /* CANCEL */) {
      return { shouldQuit: false, action: "cancel" };
    } else if (choice2 === "quit" /* QUIT */) {
      return { shouldQuit: true, action: "quit" };
    } else if (choice2 === "save_and_quit" /* SAVE_AND_QUIT */) {
      return { shouldQuit: true, action: "save_and_quit" };
    } else if (choice2 === "summary_and_quit" /* SUMMARY_AND_QUIT */) {
      return { shouldQuit: true, action: "summary_and_quit" };
    }
    return { shouldQuit: false, action: "cancel" };
  }, []);
  return {
    isQuitConfirmationOpen,
    showQuitConfirmation,
    handleQuitConfirmationSelect
  };
}, "useQuitConfirmation");

// packages/cli/src/ui/hooks/useWelcomeBack.ts
init_esbuild_shims();
var import_react128 = __toESM(require_react(), 1);
function useWelcomeBack(config, submitQuery, buffer, settings) {
  const [welcomeBackInfo, setWelcomeBackInfo] = (0, import_react128.useState)(null);
  const [showWelcomeBackDialog, setShowWelcomeBackDialog] = (0, import_react128.useState)(false);
  const [welcomeBackChoice, setWelcomeBackChoice] = (0, import_react128.useState)(null);
  const [shouldFillInput, setShouldFillInput] = (0, import_react128.useState)(false);
  const [inputFillText, setInputFillText] = (0, import_react128.useState)(null);
  const checkWelcomeBack = (0, import_react128.useCallback)(async () => {
    if (settings.ui?.enableWelcomeBack === false) {
      return;
    }
    try {
      const info = await getProjectSummaryInfo();
      if (info.hasHistory) {
        setWelcomeBackInfo(info);
        setShowWelcomeBackDialog(true);
      }
    } catch (error) {
      console.debug("Welcome back check failed:", error);
    }
  }, [settings.ui?.enableWelcomeBack]);
  const handleWelcomeBackSelection = (0, import_react128.useCallback)(
    (choice2) => {
      setWelcomeBackChoice(choice2);
      setShowWelcomeBackDialog(false);
      if (choice2 === "continue" && welcomeBackInfo?.content) {
        const contextMessage = `@.qwen/PROJECT_SUMMARY.md, Based on our previous conversation,Let's continue?`;
        setInputFillText(contextMessage);
        setShouldFillInput(true);
      }
    },
    [welcomeBackInfo]
  );
  const handleWelcomeBackClose = (0, import_react128.useCallback)(() => {
    setWelcomeBackChoice("restart");
    setShowWelcomeBackDialog(false);
  }, []);
  const clearInputFill = (0, import_react128.useCallback)(() => {
    setShouldFillInput(false);
    setInputFillText(null);
  }, []);
  (0, import_react128.useEffect)(() => {
    if (shouldFillInput && inputFillText) {
      buffer.setText(inputFillText);
      clearInputFill();
    }
  }, [shouldFillInput, inputFillText, buffer, clearInputFill]);
  (0, import_react128.useEffect)(() => {
    checkWelcomeBack();
  }, [checkWelcomeBack]);
  return {
    // State
    welcomeBackInfo,
    showWelcomeBackDialog,
    welcomeBackChoice,
    shouldFillInput,
    inputFillText,
    // Actions
    handleWelcomeBackSelection,
    handleWelcomeBackClose,
    checkWelcomeBack,
    clearInputFill
  };
}
__name(useWelcomeBack, "useWelcomeBack");

// packages/cli/src/ui/hooks/useDialogClose.ts
init_esbuild_shims();
var import_react129 = __toESM(require_react(), 1);
function useDialogClose(options2) {
  const closeAnyOpenDialog = (0, import_react129.useCallback)(() => {
    if (options2.isThemeDialogOpen) {
      options2.handleThemeSelect(void 0, "User" /* User */);
      return true;
    }
    if (options2.isApprovalModeDialogOpen) {
      options2.handleApprovalModeSelect(void 0, "User" /* User */);
      return true;
    }
    if (options2.isEditorDialogOpen) {
      options2.exitEditorDialog();
      return true;
    }
    if (options2.isSettingsDialogOpen) {
      options2.closeSettingsDialog();
      return true;
    }
    if (options2.isFolderTrustDialogOpen) {
      return true;
    }
    if (options2.showWelcomeBackDialog) {
      options2.handleWelcomeBackClose();
      return true;
    }
    return false;
  }, [options2]);
  return { closeAnyOpenDialog };
}
__name(useDialogClose, "useDialogClose");

// packages/cli/src/ui/hooks/useInitializationAuthError.ts
init_esbuild_shims();
var import_react130 = __toESM(require_react(), 1);
var useInitializationAuthError = /* @__PURE__ */ __name((authError, onAuthError) => {
  const hasHandled = (0, import_react130.useRef)(false);
  const authErrorRef = (0, import_react130.useRef)(authError);
  const onAuthErrorRef = (0, import_react130.useRef)(onAuthError);
  authErrorRef.current = authError;
  onAuthErrorRef.current = onAuthError;
  (0, import_react130.useEffect)(() => {
    if (hasHandled.current) {
      return;
    }
    if (authErrorRef.current) {
      hasHandled.current = true;
      onAuthErrorRef.current(authErrorRef.current);
    }
  }, [authError, onAuthError]);
}, "useInitializationAuthError");

// packages/cli/src/ui/hooks/useSubagentCreateDialog.ts
init_esbuild_shims();
var import_react131 = __toESM(require_react(), 1);
function useSubagentCreateDialog() {
  const [isSubagentCreateDialogOpen, setIsSubagentCreateDialogOpen] = (0, import_react131.useState)(false);
  const openSubagentCreateDialog = (0, import_react131.useCallback)(() => {
    setIsSubagentCreateDialogOpen(true);
  }, []);
  const closeSubagentCreateDialog = (0, import_react131.useCallback)(() => {
    setIsSubagentCreateDialogOpen(false);
  }, []);
  return {
    isSubagentCreateDialogOpen,
    openSubagentCreateDialog,
    closeSubagentCreateDialog
  };
}
__name(useSubagentCreateDialog, "useSubagentCreateDialog");

// packages/cli/src/ui/hooks/useAgentsManagerDialog.ts
init_esbuild_shims();
var import_react132 = __toESM(require_react(), 1);
var useAgentsManagerDialog = /* @__PURE__ */ __name(() => {
  const [isAgentsManagerDialogOpen, setIsAgentsManagerDialogOpen] = (0, import_react132.useState)(false);
  const openAgentsManagerDialog = (0, import_react132.useCallback)(() => {
    setIsAgentsManagerDialogOpen(true);
  }, []);
  const closeAgentsManagerDialog = (0, import_react132.useCallback)(() => {
    setIsAgentsManagerDialogOpen(false);
  }, []);
  return {
    isAgentsManagerDialogOpen,
    openAgentsManagerDialog,
    closeAgentsManagerDialog
  };
}, "useAgentsManagerDialog");

// packages/cli/src/ui/hooks/useAttentionNotifications.ts
init_esbuild_shims();
var import_react133 = __toESM(require_react(), 1);

// packages/cli/src/utils/attentionNotification.ts
init_esbuild_shims();
import process49 from "node:process";
var TERMINAL_BELL = "\x07";
function notifyTerminalAttention(_reason, options2 = {}) {
  const stream2 = options2.stream ?? process49.stdout;
  if (!stream2?.write || stream2.isTTY === false) {
    return false;
  }
  try {
    stream2.write(TERMINAL_BELL);
    return true;
  } catch (error) {
    console.warn("Failed to send terminal bell:", error);
    return false;
  }
}
__name(notifyTerminalAttention, "notifyTerminalAttention");

// packages/cli/src/ui/hooks/useAttentionNotifications.ts
var LONG_TASK_NOTIFICATION_THRESHOLD_SECONDS = 20;
var useAttentionNotifications = /* @__PURE__ */ __name(({
  isFocused,
  streamingState,
  elapsedTime
}) => {
  const awaitingNotificationSentRef = (0, import_react133.useRef)(false);
  const respondingElapsedRef = (0, import_react133.useRef)(0);
  (0, import_react133.useEffect)(() => {
    if (streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */ && !isFocused && !awaitingNotificationSentRef.current) {
      notifyTerminalAttention("tool_approval" /* ToolApproval */);
      awaitingNotificationSentRef.current = true;
    }
    if (streamingState !== "waiting_for_confirmation" /* WaitingForConfirmation */ || isFocused) {
      awaitingNotificationSentRef.current = false;
    }
  }, [isFocused, streamingState]);
  (0, import_react133.useEffect)(() => {
    if (streamingState === "responding" /* Responding */) {
      respondingElapsedRef.current = elapsedTime;
      return;
    }
    if (streamingState === "idle" /* Idle */) {
      const wasLongTask = respondingElapsedRef.current >= LONG_TASK_NOTIFICATION_THRESHOLD_SECONDS;
      if (wasLongTask && !isFocused) {
        notifyTerminalAttention("long_task_complete" /* LongTaskComplete */);
      }
      respondingElapsedRef.current = 0;
      return;
    }
  }, [streamingState, elapsedTime, isFocused]);
}, "useAttentionNotifications");

// packages/cli/src/ui/AppContainer.tsx
var import_jsx_runtime106 = __toESM(require_jsx_runtime(), 1);
var CTRL_EXIT_PROMPT_DURATION_MS = 1e3;
function isToolExecuting(pendingHistoryItems) {
  return pendingHistoryItems.some((item) => {
    if (item && item.type === "tool_group") {
      return item.tools.some(
        (tool) => "Executing" /* Executing */ === tool.status
      );
    }
    return false;
  });
}
__name(isToolExecuting, "isToolExecuting");
var SHELL_WIDTH_FRACTION = 0.89;
var SHELL_HEIGHT_PADDING = 10;
var AppContainer = /* @__PURE__ */ __name((props) => {
  const { settings, config, initializationResult } = props;
  const historyManager = useHistory();
  useMemoryMonitor(historyManager);
  const [corgiMode, setCorgiMode] = (0, import_react134.useState)(false);
  const [debugMessage, setDebugMessage] = (0, import_react134.useState)("");
  const [quittingMessages, setQuittingMessages] = (0, import_react134.useState)(null);
  const [themeError, setThemeError] = (0, import_react134.useState)(
    initializationResult.themeError
  );
  const [isProcessing, setIsProcessing] = (0, import_react134.useState)(false);
  const [embeddedShellFocused, setEmbeddedShellFocused] = (0, import_react134.useState)(false);
  const [geminiMdFileCount, setGeminiMdFileCount] = (0, import_react134.useState)(
    initializationResult.geminiMdFileCount
  );
  const [shellModeActive, setShellModeActive] = (0, import_react134.useState)(false);
  const [modelSwitchedFromQuotaError, setModelSwitchedFromQuotaError] = (0, import_react134.useState)(false);
  const [historyRemountKey, setHistoryRemountKey] = (0, import_react134.useState)(0);
  const [updateInfo, setUpdateInfo] = (0, import_react134.useState)(null);
  const [isTrustedFolder, setIsTrustedFolder] = (0, import_react134.useState)(
    config.isTrustedFolder()
  );
  const extensions = config.getExtensions();
  const {
    extensionsUpdateState,
    extensionsUpdateStateInternal,
    dispatchExtensionStateUpdate,
    confirmUpdateExtensionRequests,
    addConfirmUpdateExtensionRequest
  } = useExtensionUpdates(
    extensions,
    historyManager.addItem,
    config.getWorkingDir()
  );
  const [isPermissionsDialogOpen, setPermissionsDialogOpen] = (0, import_react134.useState)(false);
  const openPermissionsDialog = (0, import_react134.useCallback)(
    () => setPermissionsDialogOpen(true),
    []
  );
  const closePermissionsDialog = (0, import_react134.useCallback)(
    () => setPermissionsDialogOpen(false),
    []
  );
  const getEffectiveModel2 = (0, import_react134.useCallback)(() => {
    if (config.isInFallbackMode()) {
      return DEFAULT_GEMINI_FLASH_MODEL;
    }
    return config.getModel();
  }, [config]);
  const [currentModel, setCurrentModel] = (0, import_react134.useState)(getEffectiveModel2());
  const [userTier] = (0, import_react134.useState)(void 0);
  const [isConfigInitialized, setConfigInitialized] = (0, import_react134.useState)(false);
  const logger6 = useLogger(config.storage);
  const [userMessages, setUserMessages] = (0, import_react134.useState)([]);
  const { columns: terminalWidth, rows: terminalHeight } = useTerminalSize();
  const { stdin, setRawMode } = use_stdin_default();
  const { stdout } = use_stdout_default();
  const { stats: sessionStats } = useSessionStats();
  const branchName = useGitBranchName(config.getTargetDir());
  const mainControlsRef = (0, import_react134.useRef)(null);
  const originalTitleRef = (0, import_react134.useRef)(
    computeWindowTitle(basename14(config.getTargetDir()))
  );
  const lastTitleRef = (0, import_react134.useRef)(null);
  const staticExtraHeight = 3;
  (0, import_react134.useEffect)(() => {
    (async () => {
      await config.initialize();
      setConfigInitialized(true);
    })();
    registerCleanup(async () => {
      const ideClient = await IdeClient.getInstance();
      await ideClient.disconnect();
    });
  }, [config]);
  (0, import_react134.useEffect)(
    () => setUpdateHandler(historyManager.addItem, setUpdateInfo),
    [historyManager.addItem]
  );
  (0, import_react134.useEffect)(() => {
    const checkModelChange = /* @__PURE__ */ __name(() => {
      const effectiveModel = getEffectiveModel2();
      if (effectiveModel !== currentModel) {
        setCurrentModel(effectiveModel);
      }
    }, "checkModelChange");
    checkModelChange();
    const interval = setInterval(checkModelChange, 1e3);
    return () => clearInterval(interval);
  }, [config, currentModel, getEffectiveModel2]);
  const {
    consoleMessages,
    handleNewMessage,
    clearConsoleMessages: clearConsoleMessagesState
  } = useConsoleMessages();
  (0, import_react134.useEffect)(() => {
    const consolePatcher = new ConsolePatcher({
      onNewMessage: handleNewMessage,
      debugMode: config.getDebugMode()
    });
    consolePatcher.patch();
    registerCleanup(consolePatcher.cleanup);
  }, [handleNewMessage, config]);
  const { inputWidth, suggestionsWidth } = (0, import_react134.useMemo)(() => {
    const { inputWidth: inputWidth2, suggestionsWidth: suggestionsWidth2 } = calculatePromptWidths(terminalWidth);
    return { inputWidth: inputWidth2, suggestionsWidth: suggestionsWidth2 };
  }, [terminalWidth]);
  const mainAreaWidth = Math.floor(terminalWidth * 0.9);
  const staticAreaMaxItemHeight = Math.max(terminalHeight * 4, 100);
  const isValidPath = (0, import_react134.useCallback)((filePath) => {
    try {
      return fs90.existsSync(filePath) && fs90.statSync(filePath).isFile();
    } catch (_e) {
      return false;
    }
  }, []);
  const buffer = useTextBuffer({
    initialText: "",
    viewport: { height: 10, width: inputWidth },
    stdin,
    setRawMode,
    isValidPath,
    shellModeActive
  });
  (0, import_react134.useEffect)(() => {
    const fetchUserMessages = /* @__PURE__ */ __name(async () => {
      const pastMessagesRaw = await logger6?.getPreviousUserMessages() || [];
      const currentSessionUserMessages = historyManager.history.filter(
        (item) => item.type === "user" && typeof item.text === "string" && item.text.trim() !== ""
      ).map((item) => item.text).reverse();
      const combinedMessages = [
        ...currentSessionUserMessages,
        ...pastMessagesRaw
      ];
      const deduplicatedMessages = [];
      if (combinedMessages.length > 0) {
        deduplicatedMessages.push(combinedMessages[0]);
        for (let i = 1; i < combinedMessages.length; i++) {
          if (combinedMessages[i] !== combinedMessages[i - 1]) {
            deduplicatedMessages.push(combinedMessages[i]);
          }
        }
      }
      setUserMessages(deduplicatedMessages.reverse());
    }, "fetchUserMessages");
    fetchUserMessages();
  }, [historyManager.history, logger6]);
  const refreshStatic = (0, import_react134.useCallback)(() => {
    stdout.write(base_exports.clearTerminal);
    setHistoryRemountKey((prev) => prev + 1);
  }, [setHistoryRemountKey, stdout]);
  const {
    isThemeDialogOpen,
    openThemeDialog,
    handleThemeSelect,
    handleThemeHighlight
  } = useThemeCommand(
    settings,
    setThemeError,
    historyManager.addItem,
    initializationResult.themeError
  );
  const {
    isApprovalModeDialogOpen,
    openApprovalModeDialog,
    handleApprovalModeSelect
  } = useApprovalModeCommand(settings, config);
  const {
    setAuthState,
    authError,
    onAuthError,
    isAuthDialogOpen,
    isAuthenticating,
    pendingAuthType,
    qwenAuthState,
    handleAuthSelect,
    openAuthDialog,
    cancelAuthentication
  } = useAuthCommand(settings, config, historyManager.addItem);
  const { proQuotaRequest, handleProQuotaChoice } = useQuotaAndFallback({
    config,
    historyManager,
    userTier,
    setAuthState,
    setModelSwitchedFromQuotaError
  });
  useInitializationAuthError(initializationResult.authError, onAuthError);
  (0, import_react134.useEffect)(() => {
    if (settings.merged.security?.auth?.enforcedType && settings.merged.security?.auth.selectedType && settings.merged.security?.auth.enforcedType !== settings.merged.security?.auth.selectedType) {
      onAuthError(
        `Authentication is enforced to be ${settings.merged.security?.auth.enforcedType}, but you are currently using ${settings.merged.security?.auth.selectedType}.`
      );
    } else if (settings.merged.security?.auth?.selectedType && !settings.merged.security?.auth?.useExternal) {
      const error = validateAuthMethod(
        settings.merged.security.auth.selectedType
      );
      if (error) {
        onAuthError(error);
      }
    }
  }, [
    settings.merged.security?.auth?.selectedType,
    settings.merged.security?.auth?.enforcedType,
    settings.merged.security?.auth?.useExternal,
    onAuthError
  ]);
  const [editorError, setEditorError] = (0, import_react134.useState)(null);
  const {
    isEditorDialogOpen,
    openEditorDialog,
    handleEditorSelect,
    exitEditorDialog
  } = useEditorSettings(settings, setEditorError, historyManager.addItem);
  const { isSettingsDialogOpen, openSettingsDialog, closeSettingsDialog } = useSettingsCommand();
  const { isModelDialogOpen, openModelDialog, closeModelDialog } = useModelCommand();
  const {
    showWorkspaceMigrationDialog,
    workspaceExtensions,
    onWorkspaceMigrationDialogOpen,
    onWorkspaceMigrationDialogClose
  } = useWorkspaceMigration(settings);
  const { toggleVimEnabled } = useVimMode();
  const { showQuitConfirmation } = useQuitConfirmation();
  const {
    isSubagentCreateDialogOpen,
    openSubagentCreateDialog,
    closeSubagentCreateDialog
  } = useSubagentCreateDialog();
  const {
    isAgentsManagerDialogOpen,
    openAgentsManagerDialog,
    closeAgentsManagerDialog
  } = useAgentsManagerDialog();
  const [isVisionSwitchDialogOpen, setIsVisionSwitchDialogOpen] = (0, import_react134.useState)(false);
  const [visionSwitchResolver, setVisionSwitchResolver] = (0, import_react134.useState)(null);
  const slashCommandActions = (0, import_react134.useMemo)(
    () => ({
      openAuthDialog,
      openThemeDialog,
      openEditorDialog,
      openSettingsDialog,
      openModelDialog,
      openPermissionsDialog,
      openApprovalModeDialog,
      quit: /* @__PURE__ */ __name((messages) => {
        setQuittingMessages(messages);
        setTimeout(async () => {
          await runExitCleanup();
          process50.exit(0);
        }, 100);
      }, "quit"),
      setDebugMessage,
      toggleCorgiMode: /* @__PURE__ */ __name(() => setCorgiMode((prev) => !prev), "toggleCorgiMode"),
      dispatchExtensionStateUpdate,
      addConfirmUpdateExtensionRequest,
      openSubagentCreateDialog,
      openAgentsManagerDialog,
      _showQuitConfirmation: showQuitConfirmation
    }),
    [
      openAuthDialog,
      openThemeDialog,
      openEditorDialog,
      openSettingsDialog,
      openModelDialog,
      setDebugMessage,
      setCorgiMode,
      dispatchExtensionStateUpdate,
      openPermissionsDialog,
      openApprovalModeDialog,
      addConfirmUpdateExtensionRequest,
      showQuitConfirmation,
      openSubagentCreateDialog,
      openAgentsManagerDialog
    ]
  );
  const {
    handleSlashCommand: handleSlashCommand2,
    slashCommands,
    pendingHistoryItems: pendingSlashCommandHistoryItems,
    commandContext,
    shellConfirmationRequest,
    confirmationRequest,
    quitConfirmationRequest
  } = useSlashCommandProcessor(
    config,
    settings,
    historyManager.addItem,
    historyManager.clearItems,
    historyManager.loadHistory,
    refreshStatic,
    toggleVimEnabled,
    setIsProcessing,
    setGeminiMdFileCount,
    slashCommandActions,
    extensionsUpdateStateInternal,
    isConfigInitialized
  );
  const handleVisionSwitchRequired = (0, import_react134.useCallback)(
    async (_query) => new Promise((resolve24, reject) => {
      setVisionSwitchResolver({ resolve: resolve24, reject });
      setIsVisionSwitchDialogOpen(true);
    }),
    []
  );
  const handleVisionSwitchSelect = (0, import_react134.useCallback)(
    (outcome) => {
      setIsVisionSwitchDialogOpen(false);
      if (visionSwitchResolver) {
        const result = processVisionSwitchOutcome(outcome);
        visionSwitchResolver.resolve(result);
        setVisionSwitchResolver(null);
      }
    },
    [visionSwitchResolver]
  );
  const onDebugMessage = (0, import_react134.useCallback)((message) => {
    console.debug(message);
  }, []);
  const performMemoryRefresh = (0, import_react134.useCallback)(async () => {
    historyManager.addItem(
      {
        type: "info" /* INFO */,
        text: "Refreshing hierarchical memory (QWEN.md or other context files)..."
      },
      Date.now()
    );
    try {
      const { memoryContent, fileCount } = await loadHierarchicalGeminiMemory(
        process50.cwd(),
        settings.merged.context?.loadMemoryFromIncludeDirectories ? config.getWorkspaceContext().getDirectories() : [],
        config.getDebugMode(),
        config.getFileService(),
        settings.merged,
        config.getExtensionContextFilePaths(),
        config.isTrustedFolder(),
        settings.merged.context?.importFormat || "tree",
        // Use setting or default to 'tree'
        config.getFileFilteringOptions()
      );
      config.setUserMemory(memoryContent);
      config.setGeminiMdFileCount(fileCount);
      setGeminiMdFileCount(fileCount);
      historyManager.addItem(
        {
          type: "info" /* INFO */,
          text: `Memory refreshed successfully. ${memoryContent.length > 0 ? `Loaded ${memoryContent.length} characters from ${fileCount} file(s).` : "No memory content found."}`
        },
        Date.now()
      );
      if (config.getDebugMode()) {
        console.log(
          `[DEBUG] Refreshed memory content in config: ${memoryContent.substring(
            0,
            200
          )}...`
        );
      }
    } catch (error) {
      const errorMessage = getErrorMessage(error);
      historyManager.addItem(
        {
          type: "error" /* ERROR */,
          text: `Error refreshing memory: ${errorMessage}`
        },
        Date.now()
      );
      console.error("Error refreshing memory:", error);
    }
  }, [config, historyManager, settings.merged]);
  const cancelHandlerRef = (0, import_react134.useRef)(() => {
  });
  const {
    streamingState,
    submitQuery,
    initError,
    pendingHistoryItems: pendingGeminiHistoryItems,
    thought,
    cancelOngoingRequest,
    handleApprovalModeChange,
    activePtyId,
    loopDetectionConfirmationRequest
  } = useGeminiStream(
    config.getGeminiClient(),
    historyManager.history,
    historyManager.addItem,
    config,
    settings,
    onDebugMessage,
    handleSlashCommand2,
    shellModeActive,
    () => settings.merged.general?.preferredEditor,
    onAuthError,
    performMemoryRefresh,
    modelSwitchedFromQuotaError,
    setModelSwitchedFromQuotaError,
    refreshStatic,
    () => cancelHandlerRef.current(),
    settings.merged.experimental?.visionModelPreview ?? false,
    // visionModelPreviewEnabled
    setEmbeddedShellFocused,
    terminalWidth,
    terminalHeight,
    handleVisionSwitchRequired,
    // onVisionSwitchRequired
    embeddedShellFocused
  );
  const showAutoAcceptIndicator = useAutoAcceptIndicator({
    config,
    addItem: historyManager.addItem,
    onApprovalModeChange: handleApprovalModeChange
  });
  const { messageQueue, addMessage, clearQueue, getQueuedMessagesText } = useMessageQueue({
    isConfigInitialized,
    streamingState,
    submitQuery
  });
  const handleFinalSubmit = (0, import_react134.useCallback)(
    (submittedValue) => {
      addMessage(submittedValue);
    },
    [addMessage]
  );
  const {
    welcomeBackInfo,
    showWelcomeBackDialog,
    welcomeBackChoice,
    handleWelcomeBackSelection,
    handleWelcomeBackClose
  } = useWelcomeBack(config, handleFinalSubmit, buffer, settings.merged);
  cancelHandlerRef.current = (0, import_react134.useCallback)(() => {
    const pendingHistoryItems2 = [
      ...pendingSlashCommandHistoryItems,
      ...pendingGeminiHistoryItems
    ];
    if (isToolExecuting(pendingHistoryItems2)) {
      buffer.setText("");
      return;
    }
    const lastUserMessage = userMessages.at(-1);
    let textToSet = lastUserMessage || "";
    const queuedText = getQueuedMessagesText();
    if (queuedText) {
      textToSet = textToSet ? `${textToSet}

${queuedText}` : queuedText;
      clearQueue();
    }
    if (textToSet) {
      buffer.setText(textToSet);
    }
  }, [
    buffer,
    userMessages,
    getQueuedMessagesText,
    clearQueue,
    pendingSlashCommandHistoryItems,
    pendingGeminiHistoryItems
  ]);
  const handleClearScreen = (0, import_react134.useCallback)(() => {
    historyManager.clearItems();
    clearConsoleMessagesState();
    console.clear();
    refreshStatic();
  }, [historyManager, clearConsoleMessagesState, refreshStatic]);
  const { handleInput: vimHandleInput } = useVim(buffer, handleFinalSubmit);
  const isInputActive = !initError && !isProcessing && (streamingState === "idle" /* Idle */ || streamingState === "responding" /* Responding */) && !proQuotaRequest;
  const [controlsHeight, setControlsHeight] = (0, import_react134.useState)(0);
  (0, import_react134.useLayoutEffect)(() => {
    if (mainControlsRef.current) {
      const fullFooterMeasurement = measure_element_default(mainControlsRef.current);
      if (fullFooterMeasurement.height > 0) {
        setControlsHeight(fullFooterMeasurement.height);
      }
    }
  }, [buffer, terminalWidth, terminalHeight]);
  const availableTerminalHeight = Math.max(
    0,
    terminalHeight - controlsHeight - staticExtraHeight - 2
  );
  config.setShellExecutionConfig({
    terminalWidth: Math.floor(terminalWidth * SHELL_WIDTH_FRACTION),
    terminalHeight: Math.max(
      Math.floor(availableTerminalHeight - SHELL_HEIGHT_PADDING),
      1
    ),
    pager: settings.merged.tools?.shell?.pager,
    showColor: settings.merged.tools?.shell?.showColor
  });
  const isFocused = useFocus();
  useBracketedPaste();
  const contextFileNames = (0, import_react134.useMemo)(() => {
    const fromSettings = settings.merged.context?.fileName;
    return fromSettings ? Array.isArray(fromSettings) ? fromSettings : [fromSettings] : getAllGeminiMdFilenames();
  }, [settings.merged.context?.fileName]);
  const initialPrompt = (0, import_react134.useMemo)(() => config.getQuestion(), [config]);
  const initialPromptSubmitted = (0, import_react134.useRef)(false);
  const geminiClient = config.getGeminiClient();
  (0, import_react134.useEffect)(() => {
    if (activePtyId) {
      ShellExecutionService.resizePty(
        activePtyId,
        Math.floor(terminalWidth * SHELL_WIDTH_FRACTION),
        Math.max(Math.floor(availableTerminalHeight - SHELL_HEIGHT_PADDING), 1)
      );
    }
  }, [terminalWidth, availableTerminalHeight, activePtyId]);
  (0, import_react134.useEffect)(() => {
    if (initialPrompt && isConfigInitialized && !initialPromptSubmitted.current && !isAuthenticating && !isAuthDialogOpen && !isThemeDialogOpen && !isEditorDialogOpen && !showWelcomeBackDialog && !isVisionSwitchDialogOpen && welcomeBackChoice !== "restart" && geminiClient?.isInitialized?.()) {
      handleFinalSubmit(initialPrompt);
      initialPromptSubmitted.current = true;
    }
  }, [
    initialPrompt,
    isConfigInitialized,
    handleFinalSubmit,
    isAuthenticating,
    isAuthDialogOpen,
    isThemeDialogOpen,
    isEditorDialogOpen,
    showWelcomeBackDialog,
    isVisionSwitchDialogOpen,
    welcomeBackChoice,
    geminiClient
  ]);
  const [idePromptAnswered, setIdePromptAnswered] = (0, import_react134.useState)(false);
  const [currentIDE, setCurrentIDE] = (0, import_react134.useState)(null);
  (0, import_react134.useEffect)(() => {
    const getIde = /* @__PURE__ */ __name(async () => {
      const ideClient = await IdeClient.getInstance();
      const currentIde = ideClient.getCurrentIde();
      setCurrentIDE(currentIde || null);
    }, "getIde");
    getIde();
  }, []);
  const shouldShowIdePrompt = Boolean(
    currentIDE && !config.getIdeMode() && !settings.merged.ide?.hasSeenNudge && !idePromptAnswered
  );
  const [showErrorDetails, setShowErrorDetails] = (0, import_react134.useState)(false);
  const [showToolDescriptions, setShowToolDescriptions] = (0, import_react134.useState)(false);
  const [ctrlCPressedOnce, setCtrlCPressedOnce] = (0, import_react134.useState)(false);
  const ctrlCTimerRef = (0, import_react134.useRef)(null);
  const [ctrlDPressedOnce, setCtrlDPressedOnce] = (0, import_react134.useState)(false);
  const ctrlDTimerRef = (0, import_react134.useRef)(null);
  const [constrainHeight, setConstrainHeight] = (0, import_react134.useState)(true);
  const [ideContextState, setIdeContextState] = (0, import_react134.useState)();
  const [showEscapePrompt, setShowEscapePrompt] = (0, import_react134.useState)(false);
  const [showIdeRestartPrompt, setShowIdeRestartPrompt] = (0, import_react134.useState)(false);
  const { isFolderTrustDialogOpen, handleFolderTrustSelect, isRestarting } = useFolderTrust(settings, setIsTrustedFolder);
  const {
    needsRestart: ideNeedsRestart,
    restartReason: ideTrustRestartReason
  } = useIdeTrustListener();
  const isInitialMount = (0, import_react134.useRef)(true);
  (0, import_react134.useEffect)(() => {
    if (ideNeedsRestart) {
      setShowIdeRestartPrompt(true);
    }
  }, [ideNeedsRestart]);
  (0, import_react134.useEffect)(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false;
      return;
    }
    const handler = setTimeout(() => {
      refreshStatic();
    }, 300);
    return () => {
      clearTimeout(handler);
    };
  }, [terminalWidth, refreshStatic]);
  (0, import_react134.useEffect)(() => {
    const unsubscribe = ideContextStore.subscribe(setIdeContextState);
    setIdeContextState(ideContextStore.get());
    return unsubscribe;
  }, []);
  (0, import_react134.useEffect)(() => {
    const openDebugConsole = /* @__PURE__ */ __name(() => {
      setShowErrorDetails(true);
      setConstrainHeight(false);
    }, "openDebugConsole");
    appEvents.on("open-debug-console" /* OpenDebugConsole */, openDebugConsole);
    const logErrorHandler = /* @__PURE__ */ __name((errorMessage) => {
      handleNewMessage({
        type: "error",
        content: String(errorMessage),
        count: 1
      });
    }, "logErrorHandler");
    appEvents.on("log-error" /* LogError */, logErrorHandler);
    return () => {
      appEvents.off("open-debug-console" /* OpenDebugConsole */, openDebugConsole);
      appEvents.off("log-error" /* LogError */, logErrorHandler);
    };
  }, [handleNewMessage]);
  const handleEscapePromptChange = (0, import_react134.useCallback)((showPrompt) => {
    setShowEscapePrompt(showPrompt);
  }, []);
  const handleIdePromptComplete = (0, import_react134.useCallback)(
    (result) => {
      if (result.userSelection === "yes") {
        handleSlashCommand2("/ide install");
        settings.setValue("User" /* User */, "ide.hasSeenNudge", true);
      } else if (result.userSelection === "dismiss") {
        settings.setValue("User" /* User */, "ide.hasSeenNudge", true);
      }
      setIdePromptAnswered(true);
    },
    [handleSlashCommand2, settings]
  );
  const { elapsedTime, currentLoadingPhrase } = useLoadingIndicator(
    streamingState,
    settings.merged.ui?.customWittyPhrases
  );
  useAttentionNotifications({
    isFocused,
    streamingState,
    elapsedTime
  });
  const { closeAnyOpenDialog } = useDialogClose({
    isThemeDialogOpen,
    handleThemeSelect,
    isApprovalModeDialogOpen,
    handleApprovalModeSelect,
    isAuthDialogOpen,
    handleAuthSelect,
    pendingAuthType,
    isEditorDialogOpen,
    exitEditorDialog,
    isSettingsDialogOpen,
    closeSettingsDialog,
    isFolderTrustDialogOpen,
    showWelcomeBackDialog,
    handleWelcomeBackClose,
    quitConfirmationRequest
  });
  const handleExit = (0, import_react134.useCallback)(
    (pressedOnce, setPressedOnce, timerRef) => {
      if (pressedOnce) {
        if (timerRef.current) {
          clearTimeout(timerRef.current);
        }
        handleSlashCommand2("/quit");
        return;
      }
      if (quitConfirmationRequest) {
        handleSlashCommand2("/quit");
        return;
      }
      if (isAuthDialogOpen) {
        setPressedOnce(true);
        timerRef.current = setTimeout(() => {
          setPressedOnce(false);
        }, 500);
        return;
      }
      if (closeAnyOpenDialog()) {
        return;
      }
      if (streamingState === "responding" /* Responding */) {
        cancelOngoingRequest?.();
        return;
      }
      if (buffer.text.length > 0) {
        buffer.setText("");
        return;
      }
      handleSlashCommand2("/quit-confirm");
    },
    [
      isAuthDialogOpen,
      handleSlashCommand2,
      closeAnyOpenDialog,
      streamingState,
      cancelOngoingRequest,
      quitConfirmationRequest,
      buffer
    ]
  );
  const handleGlobalKeypress = (0, import_react134.useCallback)(
    (key) => {
      if (settings.merged.general?.debugKeystrokeLogging) {
        console.log("[DEBUG] Keystroke:", JSON.stringify(key));
      }
      if (keyMatchers["quit" /* QUIT */](key)) {
        if (isAuthenticating) {
          return;
        }
        if (!ctrlCPressedOnce) {
          setCtrlCPressedOnce(true);
          ctrlCTimerRef.current = setTimeout(() => {
            setCtrlCPressedOnce(false);
            ctrlCTimerRef.current = null;
          }, CTRL_EXIT_PROMPT_DURATION_MS);
        }
        handleExit(ctrlCPressedOnce, setCtrlCPressedOnce, ctrlCTimerRef);
        return;
      } else if (keyMatchers["exit" /* EXIT */](key)) {
        if (buffer.text.length > 0) {
          return;
        }
        handleExit(ctrlDPressedOnce, setCtrlDPressedOnce, ctrlDTimerRef);
        return;
      }
      let enteringConstrainHeightMode = false;
      if (!constrainHeight) {
        enteringConstrainHeightMode = true;
        setConstrainHeight(true);
      }
      if (keyMatchers["showErrorDetails" /* SHOW_ERROR_DETAILS */](key)) {
        setShowErrorDetails((prev) => !prev);
      } else if (keyMatchers["toggleToolDescriptions" /* TOGGLE_TOOL_DESCRIPTIONS */](key)) {
        const newValue = !showToolDescriptions;
        setShowToolDescriptions(newValue);
        const mcpServers = config.getMcpServers();
        if (Object.keys(mcpServers || {}).length > 0) {
          handleSlashCommand2(newValue ? "/mcp desc" : "/mcp nodesc");
        }
      } else if (keyMatchers["toggleIDEContextDetail" /* TOGGLE_IDE_CONTEXT_DETAIL */](key) && config.getIdeMode() && ideContextState) {
        handleSlashCommand2("/ide status");
      } else if (keyMatchers["showMoreLines" /* SHOW_MORE_LINES */](key) && !enteringConstrainHeightMode) {
        setConstrainHeight(false);
      } else if (keyMatchers["toggleShellInputFocus" /* TOGGLE_SHELL_INPUT_FOCUS */](key)) {
        if (activePtyId || embeddedShellFocused) {
          setEmbeddedShellFocused((prev) => !prev);
        }
      }
    },
    [
      constrainHeight,
      setConstrainHeight,
      setShowErrorDetails,
      showToolDescriptions,
      setShowToolDescriptions,
      config,
      ideContextState,
      handleExit,
      ctrlCPressedOnce,
      setCtrlCPressedOnce,
      ctrlCTimerRef,
      buffer.text.length,
      ctrlDPressedOnce,
      setCtrlDPressedOnce,
      ctrlDTimerRef,
      handleSlashCommand2,
      activePtyId,
      embeddedShellFocused,
      settings.merged.general?.debugKeystrokeLogging,
      isAuthenticating
    ]
  );
  useKeypress(handleGlobalKeypress, { isActive: true });
  (0, import_react134.useEffect)(() => {
    if (!settings.merged.ui?.showStatusInTitle || settings.merged.ui?.hideWindowTitle)
      return;
    let title;
    if (streamingState === "idle" /* Idle */) {
      title = originalTitleRef.current;
    } else {
      const statusText = thought?.subject?.replace(/[\r\n]+/g, " ").substring(0, 80);
      title = statusText || originalTitleRef.current;
    }
    const paddedTitle = title.padEnd(80, " ");
    if (lastTitleRef.current !== paddedTitle) {
      lastTitleRef.current = paddedTitle;
      stdout.write(`\x1B]2;${paddedTitle}\x07`);
    }
  }, [
    streamingState,
    thought,
    settings.merged.ui?.showStatusInTitle,
    settings.merged.ui?.hideWindowTitle,
    stdout
  ]);
  const filteredConsoleMessages = (0, import_react134.useMemo)(() => {
    if (config.getDebugMode()) {
      return consoleMessages;
    }
    return consoleMessages.filter((msg) => msg.type !== "debug");
  }, [consoleMessages, config]);
  const errorCount = (0, import_react134.useMemo)(
    () => filteredConsoleMessages.filter((msg) => msg.type === "error").reduce((total, msg) => total + msg.count, 0),
    [filteredConsoleMessages]
  );
  const nightly = props.version.includes("nightly");
  const dialogsVisible = showWelcomeBackDialog || showWorkspaceMigrationDialog || shouldShowIdePrompt || isFolderTrustDialogOpen || !!shellConfirmationRequest || !!confirmationRequest || confirmUpdateExtensionRequests.length > 0 || !!loopDetectionConfirmationRequest || !!quitConfirmationRequest || isThemeDialogOpen || isSettingsDialogOpen || isModelDialogOpen || isVisionSwitchDialogOpen || isPermissionsDialogOpen || isAuthDialogOpen || isAuthenticating || isEditorDialogOpen || showIdeRestartPrompt || !!proQuotaRequest || isSubagentCreateDialogOpen || isAgentsManagerDialogOpen || isApprovalModeDialogOpen;
  const pendingHistoryItems = (0, import_react134.useMemo)(
    () => [...pendingSlashCommandHistoryItems, ...pendingGeminiHistoryItems],
    [pendingSlashCommandHistoryItems, pendingGeminiHistoryItems]
  );
  const uiState = (0, import_react134.useMemo)(
    () => ({
      history: historyManager.history,
      historyManager,
      isThemeDialogOpen,
      themeError,
      isAuthenticating,
      isConfigInitialized,
      authError,
      isAuthDialogOpen,
      pendingAuthType,
      // Qwen OAuth state
      qwenAuthState,
      editorError,
      isEditorDialogOpen,
      corgiMode,
      debugMessage,
      quittingMessages,
      isSettingsDialogOpen,
      isModelDialogOpen,
      isPermissionsDialogOpen,
      isApprovalModeDialogOpen,
      slashCommands,
      pendingSlashCommandHistoryItems,
      commandContext,
      shellConfirmationRequest,
      confirmationRequest,
      confirmUpdateExtensionRequests,
      loopDetectionConfirmationRequest,
      quitConfirmationRequest,
      geminiMdFileCount,
      streamingState,
      initError,
      pendingGeminiHistoryItems,
      thought,
      shellModeActive,
      userMessages,
      buffer,
      inputWidth,
      suggestionsWidth,
      isInputActive,
      shouldShowIdePrompt,
      isFolderTrustDialogOpen: isFolderTrustDialogOpen ?? false,
      isTrustedFolder,
      constrainHeight,
      showErrorDetails,
      filteredConsoleMessages,
      ideContextState,
      showToolDescriptions,
      ctrlCPressedOnce,
      ctrlDPressedOnce,
      showEscapePrompt,
      isFocused,
      elapsedTime,
      currentLoadingPhrase,
      historyRemountKey,
      messageQueue,
      showAutoAcceptIndicator,
      showWorkspaceMigrationDialog,
      workspaceExtensions,
      currentModel,
      userTier,
      proQuotaRequest,
      contextFileNames,
      errorCount,
      availableTerminalHeight,
      mainAreaWidth,
      staticAreaMaxItemHeight,
      staticExtraHeight,
      dialogsVisible,
      pendingHistoryItems,
      nightly,
      branchName,
      sessionStats,
      terminalWidth,
      terminalHeight,
      mainControlsRef,
      currentIDE,
      updateInfo,
      showIdeRestartPrompt,
      ideTrustRestartReason,
      isRestarting,
      extensionsUpdateState,
      activePtyId,
      embeddedShellFocused,
      // Vision switch dialog
      isVisionSwitchDialogOpen,
      // Welcome back dialog
      showWelcomeBackDialog,
      welcomeBackInfo,
      welcomeBackChoice,
      // Subagent dialogs
      isSubagentCreateDialogOpen,
      isAgentsManagerDialogOpen
    }),
    [
      isThemeDialogOpen,
      themeError,
      isAuthenticating,
      isConfigInitialized,
      authError,
      isAuthDialogOpen,
      pendingAuthType,
      // Qwen OAuth state
      qwenAuthState,
      editorError,
      isEditorDialogOpen,
      corgiMode,
      debugMessage,
      quittingMessages,
      isSettingsDialogOpen,
      isModelDialogOpen,
      isPermissionsDialogOpen,
      isApprovalModeDialogOpen,
      slashCommands,
      pendingSlashCommandHistoryItems,
      commandContext,
      shellConfirmationRequest,
      confirmationRequest,
      confirmUpdateExtensionRequests,
      loopDetectionConfirmationRequest,
      quitConfirmationRequest,
      geminiMdFileCount,
      streamingState,
      initError,
      pendingGeminiHistoryItems,
      thought,
      shellModeActive,
      userMessages,
      buffer,
      inputWidth,
      suggestionsWidth,
      isInputActive,
      shouldShowIdePrompt,
      isFolderTrustDialogOpen,
      isTrustedFolder,
      constrainHeight,
      showErrorDetails,
      filteredConsoleMessages,
      ideContextState,
      showToolDescriptions,
      ctrlCPressedOnce,
      ctrlDPressedOnce,
      showEscapePrompt,
      isFocused,
      elapsedTime,
      currentLoadingPhrase,
      historyRemountKey,
      messageQueue,
      showAutoAcceptIndicator,
      showWorkspaceMigrationDialog,
      workspaceExtensions,
      userTier,
      proQuotaRequest,
      contextFileNames,
      errorCount,
      availableTerminalHeight,
      mainAreaWidth,
      staticAreaMaxItemHeight,
      staticExtraHeight,
      dialogsVisible,
      pendingHistoryItems,
      nightly,
      branchName,
      sessionStats,
      terminalWidth,
      terminalHeight,
      mainControlsRef,
      currentIDE,
      updateInfo,
      showIdeRestartPrompt,
      ideTrustRestartReason,
      isRestarting,
      currentModel,
      extensionsUpdateState,
      activePtyId,
      historyManager,
      embeddedShellFocused,
      // Vision switch dialog
      isVisionSwitchDialogOpen,
      // Welcome back dialog
      showWelcomeBackDialog,
      welcomeBackInfo,
      welcomeBackChoice,
      // Subagent dialogs
      isSubagentCreateDialogOpen,
      isAgentsManagerDialogOpen
    ]
  );
  const uiActions = (0, import_react134.useMemo)(
    () => ({
      handleThemeSelect,
      handleThemeHighlight,
      handleApprovalModeSelect,
      handleAuthSelect,
      setAuthState,
      onAuthError,
      cancelAuthentication,
      handleEditorSelect,
      exitEditorDialog,
      closeSettingsDialog,
      closeModelDialog,
      closePermissionsDialog,
      setShellModeActive,
      vimHandleInput,
      handleIdePromptComplete,
      handleFolderTrustSelect,
      setConstrainHeight,
      onEscapePromptChange: handleEscapePromptChange,
      refreshStatic,
      handleFinalSubmit,
      handleClearScreen,
      onWorkspaceMigrationDialogOpen,
      onWorkspaceMigrationDialogClose,
      handleProQuotaChoice,
      // Vision switch dialog
      handleVisionSwitchSelect,
      // Welcome back dialog
      handleWelcomeBackSelection,
      handleWelcomeBackClose,
      // Subagent dialogs
      closeSubagentCreateDialog,
      closeAgentsManagerDialog
    }),
    [
      handleThemeSelect,
      handleThemeHighlight,
      handleApprovalModeSelect,
      handleAuthSelect,
      setAuthState,
      onAuthError,
      cancelAuthentication,
      handleEditorSelect,
      exitEditorDialog,
      closeSettingsDialog,
      closeModelDialog,
      closePermissionsDialog,
      setShellModeActive,
      vimHandleInput,
      handleIdePromptComplete,
      handleFolderTrustSelect,
      setConstrainHeight,
      handleEscapePromptChange,
      refreshStatic,
      handleFinalSubmit,
      handleClearScreen,
      onWorkspaceMigrationDialogOpen,
      onWorkspaceMigrationDialogClose,
      handleProQuotaChoice,
      handleVisionSwitchSelect,
      handleWelcomeBackSelection,
      handleWelcomeBackClose,
      // Subagent dialogs
      closeSubagentCreateDialog,
      closeAgentsManagerDialog
    ]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(UIStateContext.Provider, { value: uiState, children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(UIActionsContext.Provider, { value: uiActions, children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(ConfigContext.Provider, { value: config, children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(
    AppContext2.Provider,
    {
      value: {
        version: props.version,
        startupWarnings: props.startupWarnings || []
      },
      children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(ShellFocusContext.Provider, { value: isFocused, children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(App2, {}) })
    }
  ) }) }) });
}, "AppContainer");

// packages/cli/src/utils/readStdin.ts
init_esbuild_shims();
async function readStdin() {
  const MAX_STDIN_SIZE = 8 * 1024 * 1024;
  return new Promise((resolve24, reject) => {
    let data = "";
    let totalSize = 0;
    process.stdin.setEncoding("utf8");
    const pipedInputShouldBeAvailableInMs = 500;
    let pipedInputTimerId = setTimeout(() => {
      onEnd();
    }, pipedInputShouldBeAvailableInMs);
    const onReadable = /* @__PURE__ */ __name(() => {
      let chunk;
      while ((chunk = process.stdin.read()) !== null) {
        if (pipedInputTimerId) {
          clearTimeout(pipedInputTimerId);
          pipedInputTimerId = null;
        }
        if (totalSize + chunk.length > MAX_STDIN_SIZE) {
          const remainingSize = MAX_STDIN_SIZE - totalSize;
          data += chunk.slice(0, remainingSize);
          console.warn(
            `Warning: stdin input truncated to ${MAX_STDIN_SIZE} bytes.`
          );
          process.stdin.destroy();
          break;
        }
        data += chunk;
        totalSize += chunk.length;
      }
    }, "onReadable");
    const onEnd = /* @__PURE__ */ __name(() => {
      cleanup();
      resolve24(data);
    }, "onEnd");
    const onError2 = /* @__PURE__ */ __name((err) => {
      cleanup();
      reject(err);
    }, "onError");
    const cleanup = /* @__PURE__ */ __name(() => {
      if (pipedInputTimerId) {
        clearTimeout(pipedInputTimerId);
        pipedInputTimerId = null;
      }
      process.stdin.removeListener("readable", onReadable);
      process.stdin.removeListener("end", onEnd);
      process.stdin.removeListener("error", onError2);
    }, "cleanup");
    process.stdin.on("readable", onReadable);
    process.stdin.on("end", onEnd);
    process.stdin.on("error", onError2);
  });
}
__name(readStdin, "readStdin");

// packages/cli/src/gemini.tsx
import { basename as basename15 } from "node:path";
import v8 from "node:v8";
import os42 from "node:os";
import dns from "node:dns";
import { randomUUID as randomUUID8 } from "node:crypto";

// packages/cli/src/utils/sandbox.ts
init_esbuild_shims();
var import_shell_quote5 = __toESM(require_shell_quote(), 1);
import { exec as exec4, execSync as execSync7, spawn as spawn9 } from "node:child_process";
import os39 from "node:os";
import path105 from "node:path";
import fs91 from "node:fs";
import { readFile as readFile10 } from "node:fs/promises";
import { fileURLToPath as fileURLToPath13 } from "node:url";
import { promisify as promisify9 } from "node:util";
import { randomBytes as randomBytes5 } from "node:crypto";
var execAsync3 = promisify9(exec4);
function getContainerPath(hostPath) {
  if (os39.platform() !== "win32") {
    return hostPath;
  }
  const withForwardSlashes = hostPath.replace(/\\/g, "/");
  const match2 = withForwardSlashes.match(/^([A-Z]):\/(.*)/i);
  if (match2) {
    return `/${match2[1].toLowerCase()}/${match2[2]}`;
  }
  return hostPath;
}
__name(getContainerPath, "getContainerPath");
var LOCAL_DEV_SANDBOX_IMAGE_NAME = "qwen-code-sandbox";
var SANDBOX_NETWORK_NAME = "qwen-code-sandbox";
var SANDBOX_PROXY_NAME = "qwen-code-sandbox-proxy";
var BUILTIN_SEATBELT_PROFILES = [
  "permissive-open",
  "permissive-closed",
  "permissive-proxied",
  "restrictive-open",
  "restrictive-closed",
  "restrictive-proxied"
];
async function shouldUseCurrentUserInSandbox() {
  const envVar = process.env["SANDBOX_SET_UID_GID"]?.toLowerCase().trim();
  if (envVar === "1" || envVar === "true") {
    return true;
  }
  if (envVar === "0" || envVar === "false") {
    return false;
  }
  if (os39.platform() === "linux") {
    try {
      const osReleaseContent = await readFile10("/etc/os-release", "utf8");
      if (osReleaseContent.includes("ID=debian") || osReleaseContent.includes("ID=ubuntu") || osReleaseContent.match(/^ID_LIKE=.*debian.*/m) || // Covers derivatives
      osReleaseContent.match(/^ID_LIKE=.*ubuntu.*/m)) {
        console.error(
          "INFO: Defaulting to use current user UID/GID for Debian/Ubuntu-based Linux."
        );
        return true;
      }
    } catch (_err) {
      console.warn(
        "Warning: Could not read /etc/os-release to auto-detect Debian/Ubuntu for UID/GID default."
      );
    }
  }
  return false;
}
__name(shouldUseCurrentUserInSandbox, "shouldUseCurrentUserInSandbox");
function parseImageName(image2) {
  const [fullName, tag2] = image2.split(":");
  const name3 = fullName.split("/").at(-1) ?? "unknown-image";
  return tag2 ? `${name3}-${tag2}` : name3;
}
__name(parseImageName, "parseImageName");
function ports() {
  return (process.env["SANDBOX_PORTS"] ?? "").split(",").filter((p) => p.trim()).map((p) => p.trim());
}
__name(ports, "ports");
function entrypoint(workdir, cliArgs) {
  const isWindows8 = os39.platform() === "win32";
  const containerWorkdir = getContainerPath(workdir);
  const shellCmds = [];
  const pathSeparator = isWindows8 ? ";" : ":";
  let pathSuffix = "";
  if (process.env["PATH"]) {
    const paths = process.env["PATH"].split(pathSeparator);
    for (const p of paths) {
      const containerPath = getContainerPath(p);
      if (containerPath.toLowerCase().startsWith(containerWorkdir.toLowerCase())) {
        pathSuffix += `:${containerPath}`;
      }
    }
  }
  if (pathSuffix) {
    shellCmds.push(`export PATH="$PATH${pathSuffix}";`);
  }
  let pythonPathSuffix = "";
  if (process.env["PYTHONPATH"]) {
    const paths = process.env["PYTHONPATH"].split(pathSeparator);
    for (const p of paths) {
      const containerPath = getContainerPath(p);
      if (containerPath.toLowerCase().startsWith(containerWorkdir.toLowerCase())) {
        pythonPathSuffix += `:${containerPath}`;
      }
    }
  }
  if (pythonPathSuffix) {
    shellCmds.push(`export PYTHONPATH="$PYTHONPATH${pythonPathSuffix}";`);
  }
  const projectSandboxBashrc = path105.join(
    SETTINGS_DIRECTORY_NAME2,
    "sandbox.bashrc"
  );
  if (fs91.existsSync(projectSandboxBashrc)) {
    shellCmds.push(`source ${getContainerPath(projectSandboxBashrc)};`);
  }
  ports().forEach(
    (p) => shellCmds.push(
      `socat TCP4-LISTEN:${p},bind=$(hostname -i),fork,reuseaddr TCP4:127.0.0.1:${p} 2> /dev/null &`
    )
  );
  const quotedCliArgs = cliArgs.slice(2).map((arg) => (0, import_shell_quote5.quote)([arg]));
  const cliCmd = process.env["NODE_ENV"] === "development" ? process.env["DEBUG"] ? "npm run debug --" : "npm rebuild && npm run start --" : process.env["DEBUG"] ? `node --inspect-brk=0.0.0.0:${process.env["DEBUG_PORT"] || "9229"} $(which qwen)` : "qwen";
  const args = [...shellCmds, cliCmd, ...quotedCliArgs];
  return ["bash", "-c", args.join(" ")];
}
__name(entrypoint, "entrypoint");
async function start_sandbox(config, nodeArgs = [], cliConfig, cliArgs = []) {
  const patcher = new ConsolePatcher({
    debugMode: cliConfig?.getDebugMode() || !!process.env["DEBUG"],
    stderr: true
  });
  patcher.patch();
  try {
    if (config.command === "sandbox-exec") {
      if (process.env["BUILD_SANDBOX"]) {
        throw new FatalSandboxError(
          "Cannot BUILD_SANDBOX when using macOS Seatbelt"
        );
      }
      const profile = process.env["SEATBELT_PROFILE"] ??= "permissive-open";
      let profileFile = fileURLToPath13(
        new URL(`sandbox-macos-${profile}.sb`, import.meta.url)
      );
      if (!BUILTIN_SEATBELT_PROFILES.includes(profile)) {
        profileFile = path105.join(
          SETTINGS_DIRECTORY_NAME2,
          `sandbox-macos-${profile}.sb`
        );
      }
      if (!fs91.existsSync(profileFile)) {
        throw new FatalSandboxError(
          `Missing macos seatbelt profile file '${profileFile}'`
        );
      }
      console.error(`using macos seatbelt (profile: ${profile}) ...`);
      const nodeOptions = [
        ...process.env["DEBUG"] ? ["--inspect-brk"] : [],
        ...nodeArgs
      ].join(" ");
      const args2 = [
        "-D",
        `TARGET_DIR=${fs91.realpathSync(process.cwd())}`,
        "-D",
        `TMP_DIR=${fs91.realpathSync(os39.tmpdir())}`,
        "-D",
        `HOME_DIR=${fs91.realpathSync(os39.homedir())}`,
        "-D",
        `CACHE_DIR=${fs91.realpathSync(execSync7(`getconf DARWIN_USER_CACHE_DIR`).toString().trim())}`
      ];
      const MAX_INCLUDE_DIRS = 5;
      const targetDir = fs91.realpathSync(cliConfig?.getTargetDir() || "");
      const includedDirs = [];
      if (cliConfig) {
        const workspaceContext = cliConfig.getWorkspaceContext();
        const directories = workspaceContext.getDirectories();
        for (const dir of directories) {
          const realDir = fs91.realpathSync(dir);
          if (realDir !== targetDir) {
            includedDirs.push(realDir);
          }
        }
      }
      for (let i = 0; i < MAX_INCLUDE_DIRS; i++) {
        let dirPath = "/dev/null";
        if (i < includedDirs.length) {
          dirPath = includedDirs[i];
        }
        args2.push("-D", `INCLUDE_DIR_${i}=${dirPath}`);
      }
      const finalArgv = cliArgs;
      args2.push(
        "-f",
        profileFile,
        "sh",
        "-c",
        [
          `SANDBOX=sandbox-exec`,
          `NODE_OPTIONS="${nodeOptions}"`,
          ...finalArgv.map((arg) => (0, import_shell_quote5.quote)([arg]))
        ].join(" ")
      );
      const proxyCommand2 = process.env["GEMINI_SANDBOX_PROXY_COMMAND"];
      let proxyProcess2 = void 0;
      let sandboxProcess2 = void 0;
      const sandboxEnv = { ...process.env };
      if (proxyCommand2) {
        const proxy = process.env["HTTPS_PROXY"] || process.env["https_proxy"] || process.env["HTTP_PROXY"] || process.env["http_proxy"] || "http://localhost:8877";
        sandboxEnv["HTTPS_PROXY"] = proxy;
        sandboxEnv["https_proxy"] = proxy;
        sandboxEnv["HTTP_PROXY"] = proxy;
        sandboxEnv["http_proxy"] = proxy;
        const noProxy = process.env["NO_PROXY"] || process.env["no_proxy"];
        if (noProxy) {
          sandboxEnv["NO_PROXY"] = noProxy;
          sandboxEnv["no_proxy"] = noProxy;
        }
        proxyProcess2 = spawn9(proxyCommand2, {
          stdio: ["ignore", "pipe", "pipe"],
          shell: true,
          detached: true
        });
        const stopProxy = /* @__PURE__ */ __name(() => {
          console.log("stopping proxy ...");
          if (proxyProcess2?.pid) {
            process.kill(-proxyProcess2.pid, "SIGTERM");
          }
        }, "stopProxy");
        process.on("exit", stopProxy);
        process.on("SIGINT", stopProxy);
        process.on("SIGTERM", stopProxy);
        proxyProcess2.stderr?.on("data", (data) => {
          console.error(data.toString());
        });
        proxyProcess2.on("close", (code2, signal) => {
          if (sandboxProcess2?.pid) {
            process.kill(-sandboxProcess2.pid, "SIGTERM");
          }
          throw new FatalSandboxError(
            `Proxy command '${proxyCommand2}' exited with code ${code2}, signal ${signal}`
          );
        });
        console.log("waiting for proxy to start ...");
        await execAsync3(
          `until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`
        );
      }
      process.stdin.pause();
      sandboxProcess2 = spawn9(config.command, args2, {
        stdio: "inherit"
      });
      return new Promise((resolve24, reject) => {
        sandboxProcess2?.on("error", reject);
        sandboxProcess2?.on("close", (code2) => {
          process.stdin.resume();
          resolve24(code2 ?? 1);
        });
      });
    }
    console.error(`hopping into sandbox (command: ${config.command}) ...`);
    const gcPath = fs91.realpathSync(process.argv[1]);
    const projectSandboxDockerfile = path105.join(
      SETTINGS_DIRECTORY_NAME2,
      "sandbox.Dockerfile"
    );
    const isCustomProjectSandbox = fs91.existsSync(projectSandboxDockerfile);
    const image2 = config.image;
    const workdir = path105.resolve(process.cwd());
    const containerWorkdir = getContainerPath(workdir);
    if (process.env["BUILD_SANDBOX"]) {
      if (!gcPath.includes("gemini-cli/packages/")) {
        throw new FatalSandboxError(
          "Cannot build sandbox using installed gemini binary; run `npm link ./packages/cli` under gemini-cli repo to switch to linked binary."
        );
      } else {
        console.error("building sandbox ...");
        const gcRoot = gcPath.split("/packages/")[0];
        let buildArgs = "";
        const projectSandboxDockerfile2 = path105.join(
          SETTINGS_DIRECTORY_NAME2,
          "sandbox.Dockerfile"
        );
        if (isCustomProjectSandbox) {
          console.error(`using ${projectSandboxDockerfile2} for sandbox`);
          buildArgs += `-f ${path105.resolve(projectSandboxDockerfile2)} -i ${image2}`;
        }
        execSync7(
          `cd ${gcRoot} && node scripts/build_sandbox.js -s ${buildArgs}`,
          {
            stdio: "inherit",
            env: {
              ...process.env,
              GEMINI_SANDBOX: config.command
              // in case sandbox is enabled via flags (see config.ts under cli package)
            }
          }
        );
      }
    }
    if (!await ensureSandboxImageIsPresent(config.command, image2)) {
      const remedy = image2 === LOCAL_DEV_SANDBOX_IMAGE_NAME ? "Try running `npm run build:all` or `npm run build:sandbox` under the gemini-cli repo to build it locally, or check the image name and your network connection." : "Please check the image name, your network connection, or notify gemini-cli-dev@google.com if the issue persists.";
      throw new FatalSandboxError(
        `Sandbox image '${image2}' is missing or could not be pulled. ${remedy}`
      );
    }
    const args = ["run", "-i", "--rm", "--init", "--workdir", containerWorkdir];
    if (process.env["SANDBOX_FLAGS"]) {
      const flags = (0, import_shell_quote5.parse)(process.env["SANDBOX_FLAGS"], process.env).filter(
        (f) => typeof f === "string"
      );
      args.push(...flags);
    }
    if (process.stdin.isTTY) {
      args.push("-t");
    }
    args.push("--add-host", "host.docker.internal:host-gateway");
    args.push("--volume", `${workdir}:${containerWorkdir}`);
    const userSettingsDirOnHost = USER_SETTINGS_DIR2;
    const userSettingsDirInSandbox = getContainerPath(
      `/home/node/${SETTINGS_DIRECTORY_NAME2}`
    );
    if (!fs91.existsSync(userSettingsDirOnHost)) {
      fs91.mkdirSync(userSettingsDirOnHost);
    }
    args.push(
      "--volume",
      `${userSettingsDirOnHost}:${userSettingsDirInSandbox}`
    );
    if (userSettingsDirInSandbox !== userSettingsDirOnHost) {
      args.push(
        "--volume",
        `${userSettingsDirOnHost}:${getContainerPath(userSettingsDirOnHost)}`
      );
    }
    args.push("--volume", `${os39.tmpdir()}:${getContainerPath(os39.tmpdir())}`);
    const gcloudConfigDir = path105.join(os39.homedir(), ".config", "gcloud");
    if (fs91.existsSync(gcloudConfigDir)) {
      args.push(
        "--volume",
        `${gcloudConfigDir}:${getContainerPath(gcloudConfigDir)}:ro`
      );
    }
    if (process.env["GOOGLE_APPLICATION_CREDENTIALS"]) {
      const adcFile = process.env["GOOGLE_APPLICATION_CREDENTIALS"];
      if (fs91.existsSync(adcFile)) {
        args.push("--volume", `${adcFile}:${getContainerPath(adcFile)}:ro`);
        args.push(
          "--env",
          `GOOGLE_APPLICATION_CREDENTIALS=${getContainerPath(adcFile)}`
        );
      }
    }
    if (process.env["SANDBOX_MOUNTS"]) {
      for (let mount of process.env["SANDBOX_MOUNTS"].split(",")) {
        if (mount.trim()) {
          let [from, to, opts] = mount.trim().split(":");
          to = to || from;
          opts = opts || "ro";
          mount = `${from}:${to}:${opts}`;
          if (!path105.isAbsolute(from)) {
            throw new FatalSandboxError(
              `Path '${from}' listed in SANDBOX_MOUNTS must be absolute`
            );
          }
          if (!fs91.existsSync(from)) {
            throw new FatalSandboxError(
              `Missing mount path '${from}' listed in SANDBOX_MOUNTS`
            );
          }
          console.error(`SANDBOX_MOUNTS: ${from} -> ${to} (${opts})`);
          args.push("--volume", mount);
        }
      }
    }
    ports().forEach((p) => args.push("--publish", `${p}:${p}`));
    if (process.env["DEBUG"]) {
      const debugPort = process.env["DEBUG_PORT"] || "9229";
      args.push(`--publish`, `${debugPort}:${debugPort}`);
    }
    const proxyCommand = process.env["GEMINI_SANDBOX_PROXY_COMMAND"];
    if (proxyCommand) {
      let proxy = process.env["HTTPS_PROXY"] || process.env["https_proxy"] || process.env["HTTP_PROXY"] || process.env["http_proxy"] || "http://localhost:8877";
      proxy = proxy.replace("localhost", SANDBOX_PROXY_NAME);
      if (proxy) {
        args.push("--env", `HTTPS_PROXY=${proxy}`);
        args.push("--env", `https_proxy=${proxy}`);
        args.push("--env", `HTTP_PROXY=${proxy}`);
        args.push("--env", `http_proxy=${proxy}`);
      }
      const noProxy = process.env["NO_PROXY"] || process.env["no_proxy"];
      if (noProxy) {
        args.push("--env", `NO_PROXY=${noProxy}`);
        args.push("--env", `no_proxy=${noProxy}`);
      }
      if (proxy) {
        execSync7(
          `${config.command} network inspect ${SANDBOX_NETWORK_NAME} || ${config.command} network create --internal ${SANDBOX_NETWORK_NAME}`
        );
        args.push("--network", SANDBOX_NETWORK_NAME);
        if (proxyCommand) {
          execSync7(
            `${config.command} network inspect ${SANDBOX_PROXY_NAME} || ${config.command} network create ${SANDBOX_PROXY_NAME}`
          );
        }
      }
    }
    const imageName = parseImageName(image2);
    const isIntegrationTest = process.env["GEMINI_CLI_INTEGRATION_TEST"] === "true";
    let containerName;
    if (isIntegrationTest) {
      containerName = `gemini-cli-integration-test-${randomBytes5(4).toString(
        "hex"
      )}`;
      console.log(`ContainerName: ${containerName}`);
    } else {
      let index = 0;
      const containerNameCheck = execSync7(
        `${config.command} ps -a --format "{{.Names}}"`
      ).toString().trim();
      while (containerNameCheck.includes(`${imageName}-${index}`)) {
        index++;
      }
      containerName = `${imageName}-${index}`;
      console.log(`ContainerName (regular): ${containerName}`);
    }
    args.push("--name", containerName, "--hostname", containerName);
    if (process.env["GEMINI_CLI_TEST_VAR"]) {
      args.push(
        "--env",
        `GEMINI_CLI_TEST_VAR=${process.env["GEMINI_CLI_TEST_VAR"]}`
      );
    }
    if (process.env["GEMINI_API_KEY"]) {
      args.push("--env", `GEMINI_API_KEY=${process.env["GEMINI_API_KEY"]}`);
    }
    if (process.env["GOOGLE_API_KEY"]) {
      args.push("--env", `GOOGLE_API_KEY=${process.env["GOOGLE_API_KEY"]}`);
    }
    if (process.env["OPENAI_API_KEY"]) {
      args.push("--env", `OPENAI_API_KEY=${process.env["OPENAI_API_KEY"]}`);
    }
    if (process.env["TAVILY_API_KEY"]) {
      args.push("--env", `TAVILY_API_KEY=${process.env["TAVILY_API_KEY"]}`);
    }
    if (process.env["OPENAI_BASE_URL"]) {
      args.push("--env", `OPENAI_BASE_URL=${process.env["OPENAI_BASE_URL"]}`);
    }
    if (process.env["OPENAI_MODEL"]) {
      args.push("--env", `OPENAI_MODEL=${process.env["OPENAI_MODEL"]}`);
    }
    if (process.env["GOOGLE_GENAI_USE_VERTEXAI"]) {
      args.push(
        "--env",
        `GOOGLE_GENAI_USE_VERTEXAI=${process.env["GOOGLE_GENAI_USE_VERTEXAI"]}`
      );
    }
    if (process.env["GOOGLE_GENAI_USE_GCA"]) {
      args.push(
        "--env",
        `GOOGLE_GENAI_USE_GCA=${process.env["GOOGLE_GENAI_USE_GCA"]}`
      );
    }
    if (process.env["GOOGLE_CLOUD_PROJECT"]) {
      args.push(
        "--env",
        `GOOGLE_CLOUD_PROJECT=${process.env["GOOGLE_CLOUD_PROJECT"]}`
      );
    }
    if (process.env["GOOGLE_CLOUD_LOCATION"]) {
      args.push(
        "--env",
        `GOOGLE_CLOUD_LOCATION=${process.env["GOOGLE_CLOUD_LOCATION"]}`
      );
    }
    if (process.env["GEMINI_MODEL"]) {
      args.push("--env", `GEMINI_MODEL=${process.env["GEMINI_MODEL"]}`);
    }
    if (process.env["TERM"]) {
      args.push("--env", `TERM=${process.env["TERM"]}`);
    }
    if (process.env["COLORTERM"]) {
      args.push("--env", `COLORTERM=${process.env["COLORTERM"]}`);
    }
    for (const envVar of [
      "QWEN_CODE_IDE_SERVER_PORT",
      "QWEN_CODE_IDE_WORKSPACE_PATH",
      "TERM_PROGRAM"
    ]) {
      if (process.env[envVar]) {
        args.push("--env", `${envVar}=${process.env[envVar]}`);
      }
    }
    if (process.env["VIRTUAL_ENV"]?.toLowerCase().startsWith(workdir.toLowerCase())) {
      const sandboxVenvPath = path105.resolve(
        SETTINGS_DIRECTORY_NAME2,
        "sandbox.venv"
      );
      if (!fs91.existsSync(sandboxVenvPath)) {
        fs91.mkdirSync(sandboxVenvPath, { recursive: true });
      }
      args.push(
        "--volume",
        `${sandboxVenvPath}:${getContainerPath(process.env["VIRTUAL_ENV"])}`
      );
      args.push(
        "--env",
        `VIRTUAL_ENV=${getContainerPath(process.env["VIRTUAL_ENV"])}`
      );
    }
    if (process.env["SANDBOX_ENV"]) {
      for (let env7 of process.env["SANDBOX_ENV"].split(",")) {
        if (env7 = env7.trim()) {
          if (env7.includes("=")) {
            console.error(`SANDBOX_ENV: ${env7}`);
            args.push("--env", env7);
          } else {
            throw new FatalSandboxError(
              "SANDBOX_ENV must be a comma-separated list of key=value pairs"
            );
          }
        }
      }
    }
    const existingNodeOptions = process.env["NODE_OPTIONS"] || "";
    const allNodeOptions = [
      ...existingNodeOptions ? [existingNodeOptions] : [],
      ...nodeArgs
    ].join(" ");
    if (allNodeOptions.length > 0) {
      args.push("--env", `NODE_OPTIONS="${allNodeOptions}"`);
    }
    args.push("--env", `SANDBOX=${containerName}`);
    if (config.command === "podman") {
      const emptyAuthFilePath = path105.join(os39.tmpdir(), "empty_auth.json");
      fs91.writeFileSync(emptyAuthFilePath, "{}", "utf-8");
      args.push("--authfile", emptyAuthFilePath);
    }
    let userFlag = "";
    const finalEntrypoint = entrypoint(workdir, cliArgs);
    if (process.env["GEMINI_CLI_INTEGRATION_TEST"] === "true") {
      args.push("--user", "root");
      userFlag = "--user root";
    } else if (await shouldUseCurrentUserInSandbox()) {
      args.push("--user", "root");
      const uid = execSync7("id -u").toString().trim();
      const gid = execSync7("id -g").toString().trim();
      const username = "gemini";
      const homeDir = getContainerPath(os39.homedir());
      const setupUserCommands = [
        // Use -f with groupadd to avoid errors if the group already exists.
        `groupadd -f -g ${gid} ${username}`,
        // Create user only if it doesn't exist. Use -o for non-unique UID.
        `id -u ${username} &>/dev/null || useradd -o -u ${uid} -g ${gid} -d ${homeDir} -s /bin/bash ${username}`
      ].join(" && ");
      const originalCommand = finalEntrypoint[2];
      const escapedOriginalCommand = originalCommand.replace(/'/g, "'\\''");
      const suCommand = `su -p ${username} -c '${escapedOriginalCommand}'`;
      finalEntrypoint[2] = `${setupUserCommands} && ${suCommand}`;
      userFlag = `--user ${uid}:${gid}`;
      args.push("--env", `HOME=${os39.homedir()}`);
    }
    args.push(image2);
    args.push(...finalEntrypoint);
    let proxyProcess = void 0;
    let sandboxProcess = void 0;
    if (proxyCommand) {
      const proxyContainerCommand = `${config.command} run --rm --init ${userFlag} --name ${SANDBOX_PROXY_NAME} --network ${SANDBOX_PROXY_NAME} -p 8877:8877 -v ${process.cwd()}:${workdir} --workdir ${workdir} ${image2} ${proxyCommand}`;
      proxyProcess = spawn9(proxyContainerCommand, {
        stdio: ["ignore", "pipe", "pipe"],
        shell: true,
        detached: true
      });
      const stopProxy = /* @__PURE__ */ __name(() => {
        console.log("stopping proxy container ...");
        execSync7(`${config.command} rm -f ${SANDBOX_PROXY_NAME}`);
      }, "stopProxy");
      process.on("exit", stopProxy);
      process.on("SIGINT", stopProxy);
      process.on("SIGTERM", stopProxy);
      proxyProcess.stderr?.on("data", (data) => {
        console.error(data.toString().trim());
      });
      proxyProcess.on("close", (code2, signal) => {
        if (sandboxProcess?.pid) {
          process.kill(-sandboxProcess.pid, "SIGTERM");
        }
        throw new FatalSandboxError(
          `Proxy container command '${proxyContainerCommand}' exited with code ${code2}, signal ${signal}`
        );
      });
      console.log("waiting for proxy to start ...");
      await execAsync3(
        `until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`
      );
      await execAsync3(
        `${config.command} network connect ${SANDBOX_NETWORK_NAME} ${SANDBOX_PROXY_NAME}`
      );
    }
    process.stdin.pause();
    sandboxProcess = spawn9(config.command, args, {
      stdio: "inherit"
    });
    return new Promise((resolve24, reject) => {
      sandboxProcess.on("error", (err) => {
        console.error("Sandbox process error:", err);
        reject(err);
      });
      sandboxProcess?.on("close", (code2, signal) => {
        process.stdin.resume();
        if (code2 !== 0 && code2 !== null) {
          console.log(
            `Sandbox process exited with code: ${code2}, signal: ${signal}`
          );
        }
        resolve24(code2 ?? 1);
      });
    });
  } finally {
    patcher.cleanup();
  }
}
__name(start_sandbox, "start_sandbox");
async function imageExists(sandbox, image2) {
  return new Promise((resolve24) => {
    const args = ["images", "-q", image2];
    const checkProcess = spawn9(sandbox, args);
    let stdoutData = "";
    if (checkProcess.stdout) {
      checkProcess.stdout.on("data", (data) => {
        stdoutData += data.toString();
      });
    }
    checkProcess.on("error", (err) => {
      console.warn(
        `Failed to start '${sandbox}' command for image check: ${err.message}`
      );
      resolve24(false);
    });
    checkProcess.on("close", (code2) => {
      if (code2 !== 0) {
      }
      resolve24(stdoutData.trim() !== "");
    });
  });
}
__name(imageExists, "imageExists");
async function pullImage(sandbox, image2) {
  console.info(`Attempting to pull image ${image2} using ${sandbox}...`);
  return new Promise((resolve24) => {
    const args = ["pull", image2];
    const pullProcess = spawn9(sandbox, args, { stdio: "pipe" });
    let stderrData = "";
    const onStdoutData = /* @__PURE__ */ __name((data) => {
      console.info(data.toString().trim());
    }, "onStdoutData");
    const onStderrData = /* @__PURE__ */ __name((data) => {
      stderrData += data.toString();
      console.error(data.toString().trim());
    }, "onStderrData");
    const onError2 = /* @__PURE__ */ __name((err) => {
      console.warn(
        `Failed to start '${sandbox} pull ${image2}' command: ${err.message}`
      );
      cleanup();
      resolve24(false);
    }, "onError");
    const onClose = /* @__PURE__ */ __name((code2) => {
      if (code2 === 0) {
        console.info(`Successfully pulled image ${image2}.`);
        cleanup();
        resolve24(true);
      } else {
        console.warn(
          `Failed to pull image ${image2}. '${sandbox} pull ${image2}' exited with code ${code2}.`
        );
        if (stderrData.trim()) {
        }
        cleanup();
        resolve24(false);
      }
    }, "onClose");
    const cleanup = /* @__PURE__ */ __name(() => {
      if (pullProcess.stdout) {
        pullProcess.stdout.removeListener("data", onStdoutData);
      }
      if (pullProcess.stderr) {
        pullProcess.stderr.removeListener("data", onStderrData);
      }
      pullProcess.removeListener("error", onError2);
      pullProcess.removeListener("close", onClose);
      if (pullProcess.connected) {
        pullProcess.disconnect();
      }
    }, "cleanup");
    if (pullProcess.stdout) {
      pullProcess.stdout.on("data", onStdoutData);
    }
    if (pullProcess.stderr) {
      pullProcess.stderr.on("data", onStderrData);
    }
    pullProcess.on("error", onError2);
    pullProcess.on("close", onClose);
  });
}
__name(pullImage, "pullImage");
async function ensureSandboxImageIsPresent(sandbox, image2) {
  console.info(`Checking for sandbox image: ${image2}`);
  if (await imageExists(sandbox, image2)) {
    console.info(`Sandbox image ${image2} found locally.`);
    return true;
  }
  console.info(`Sandbox image ${image2} not found locally.`);
  if (image2 === LOCAL_DEV_SANDBOX_IMAGE_NAME) {
    return false;
  }
  if (await pullImage(sandbox, image2)) {
    if (await imageExists(sandbox, image2)) {
      console.info(`Sandbox image ${image2} is now available after pulling.`);
      return true;
    } else {
      console.warn(
        `Sandbox image ${image2} still not found after a pull attempt. This might indicate an issue with the image name or registry, or the pull command reported success but failed to make the image available.`
      );
      return false;
    }
  }
  console.error(
    `Failed to obtain sandbox image ${image2} after check and pull attempt.`
  );
  return false;
}
__name(ensureSandboxImageIsPresent, "ensureSandboxImageIsPresent");

// packages/cli/src/utils/startupWarnings.ts
init_esbuild_shims();
import fs92 from "node:fs/promises";
import os40 from "node:os";
import { join as pathJoin } from "node:path";
var warningsFilePath = pathJoin(os40.tmpdir(), "qwen-code-warnings.txt");
async function getStartupWarnings() {
  try {
    await fs92.access(warningsFilePath);
    const warningsContent = await fs92.readFile(warningsFilePath, "utf-8");
    const warnings = warningsContent.split("\n").filter((line) => line.trim() !== "");
    try {
      await fs92.unlink(warningsFilePath);
    } catch {
      warnings.push("Warning: Could not delete temporary warnings file.");
    }
    return warnings;
  } catch (err) {
    if (err instanceof Error && "code" in err && err.code === "ENOENT") {
      return [];
    }
    return [`Error checking/reading warnings file: ${getErrorMessage(err)}`];
  }
}
__name(getStartupWarnings, "getStartupWarnings");

// packages/cli/src/utils/userStartupWarnings.ts
init_esbuild_shims();
import fs93 from "node:fs/promises";
import * as os41 from "node:os";
import path106 from "node:path";
var homeDirectoryCheck = {
  id: "home-directory",
  check: /* @__PURE__ */ __name(async (options2) => {
    try {
      const [workspaceRealPath, homeRealPath] = await Promise.all([
        fs93.realpath(options2.workspaceRoot),
        fs93.realpath(os41.homedir())
      ]);
      if (workspaceRealPath === homeRealPath) {
        return "You are running Qwen Code in your home directory. It is recommended to run in a project-specific directory.";
      }
      return null;
    } catch (_err) {
      return "Could not verify the current directory due to a file system error.";
    }
  }, "check")
};
var rootDirectoryCheck = {
  id: "root-directory",
  check: /* @__PURE__ */ __name(async (options2) => {
    try {
      const workspaceRealPath = await fs93.realpath(options2.workspaceRoot);
      const errorMessage = "Warning: You are running Qwen Code in the root directory. Your entire folder structure will be used for context. It is strongly recommended to run in a project-specific directory.";
      if (path106.dirname(workspaceRealPath) === workspaceRealPath) {
        return errorMessage;
      }
      return null;
    } catch (_err) {
      return "Could not verify the current directory due to a file system error.";
    }
  }, "check")
};
var ripgrepAvailabilityCheck = {
  id: "ripgrep-availability",
  check: /* @__PURE__ */ __name(async (options2) => {
    if (!options2.useRipgrep) {
      return null;
    }
    try {
      const isAvailable = await canUseRipgrep(options2.useBuiltinRipgrep);
      if (!isAvailable) {
        return "Ripgrep not available: Please install ripgrep globally to enable faster file content search. Falling back to built-in grep.";
      }
      return null;
    } catch (error) {
      return `Ripgrep not available: ${error instanceof Error ? error.message : "Unknown error"}. Falling back to built-in grep.`;
    }
  }, "check")
};
var WARNING_CHECKS = [
  homeDirectoryCheck,
  rootDirectoryCheck,
  ripgrepAvailabilityCheck
];
async function getUserStartupWarnings(options2) {
  const results = await Promise.all(
    WARNING_CHECKS.map((check) => check.check(options2))
  );
  return results.filter((msg) => msg !== null);
}
__name(getUserStartupWarnings, "getUserStartupWarnings");

// packages/cli/src/nonInteractiveCli.ts
init_esbuild_shims();

// packages/cli/src/nonInteractiveCliCommands.ts
init_esbuild_shims();

// packages/cli/src/ui/noninteractive/nonInteractiveUi.ts
init_esbuild_shims();
function createNonInteractiveUI() {
  return {
    addItem: /* @__PURE__ */ __name((_item, _timestamp) => 0, "addItem"),
    clear: /* @__PURE__ */ __name(() => {
    }, "clear"),
    setDebugMessage: /* @__PURE__ */ __name((_message) => {
    }, "setDebugMessage"),
    loadHistory: /* @__PURE__ */ __name((_newHistory) => {
    }, "loadHistory"),
    pendingItem: null,
    setPendingItem: /* @__PURE__ */ __name((_item) => {
    }, "setPendingItem"),
    toggleCorgiMode: /* @__PURE__ */ __name(() => {
    }, "toggleCorgiMode"),
    toggleVimEnabled: /* @__PURE__ */ __name(async () => false, "toggleVimEnabled"),
    setGeminiMdFileCount: /* @__PURE__ */ __name((_count) => {
    }, "setGeminiMdFileCount"),
    reloadCommands: /* @__PURE__ */ __name(() => {
    }, "reloadCommands"),
    extensionsUpdateState: /* @__PURE__ */ new Map(),
    dispatchExtensionStateUpdate: /* @__PURE__ */ __name((_action) => {
    }, "dispatchExtensionStateUpdate"),
    addConfirmUpdateExtensionRequest: /* @__PURE__ */ __name((_request) => {
    }, "addConfirmUpdateExtensionRequest")
  };
}
__name(createNonInteractiveUI, "createNonInteractiveUI");

// packages/cli/src/nonInteractiveCliCommands.ts
function filterCommandsForNonInteractive(commands, allowedBuiltinCommandNames) {
  return commands.filter((cmd) => {
    if (cmd.kind === "file" /* FILE */) {
      return true;
    }
    if (cmd.kind === "built-in" /* BUILT_IN */) {
      return allowedBuiltinCommandNames.has(cmd.name);
    }
    return false;
  });
}
__name(filterCommandsForNonInteractive, "filterCommandsForNonInteractive");
var handleSlashCommand = /* @__PURE__ */ __name(async (rawQuery, abortController, config, settings, allowedBuiltinCommandNames) => {
  const trimmed2 = rawQuery.trim();
  if (!trimmed2.startsWith("/")) {
    return;
  }
  const allowedBuiltinSet = new Set(allowedBuiltinCommandNames ?? []);
  const loaders = allowedBuiltinSet.size > 0 ? [new BuiltinCommandLoader(config), new FileCommandLoader(config)] : [new FileCommandLoader(config)];
  const commandService = await CommandService.create(
    loaders,
    abortController.signal
  );
  const commands = commandService.getCommands();
  const filteredCommands = filterCommandsForNonInteractive(
    commands,
    allowedBuiltinSet
  );
  const { commandToExecute, args } = parseSlashCommand(
    rawQuery,
    filteredCommands
  );
  if (commandToExecute) {
    if (commandToExecute.action) {
      const sessionStats = {
        sessionId: config?.getSessionId(),
        sessionStartTime: /* @__PURE__ */ new Date(),
        metrics: uiTelemetryService.getMetrics(),
        lastPromptTokenCount: 0,
        promptCount: 1
      };
      const logger6 = new Logger(config?.getSessionId() || "", config?.storage);
      const context2 = {
        services: {
          config,
          settings,
          git: void 0,
          logger: logger6
        },
        ui: createNonInteractiveUI(),
        session: {
          stats: sessionStats,
          sessionShellAllowlist: /* @__PURE__ */ new Set()
        },
        invocation: {
          raw: trimmed2,
          name: commandToExecute.name,
          args
        }
      };
      const result = await commandToExecute.action(context2, args);
      if (result) {
        switch (result.type) {
          case "submit_prompt":
            return result.content;
          case "confirm_shell_commands":
            throw new FatalInputError(
              "Exiting due to a confirmation prompt requested by the command."
            );
          default:
            throw new FatalInputError(
              "Exiting due to command result that is not supported in non-interactive mode."
            );
        }
      }
    }
  }
  return;
}, "handleSlashCommand");
var getAvailableCommands = /* @__PURE__ */ __name(async (config, settings, abortSignal, allowedBuiltinCommandNames) => {
  try {
    const allowedBuiltinSet = new Set(allowedBuiltinCommandNames ?? []);
    const loaders = allowedBuiltinSet.size > 0 ? [new BuiltinCommandLoader(config), new FileCommandLoader(config)] : [new FileCommandLoader(config)];
    const commandService = await CommandService.create(loaders, abortSignal);
    const commands = commandService.getCommands();
    const filteredCommands = filterCommandsForNonInteractive(
      commands,
      allowedBuiltinSet
    );
    return filteredCommands.filter((cmd) => !cmd.hidden);
  } catch (error) {
    console.error("Error loading available commands:", error);
    return [];
  }
}, "getAvailableCommands");

// packages/cli/src/nonInteractiveCli.ts
async function runNonInteractive(config, settings, input, prompt_id) {
  return promptIdContext.run(prompt_id, async () => {
    const consolePatcher = new ConsolePatcher({
      stderr: true,
      debugMode: config.getDebugMode()
    });
    try {
      consolePatcher.patch();
      process.stdout.on("error", (err) => {
        if (err.code === "EPIPE") {
          process.exit(0);
        }
      });
      const geminiClient = config.getGeminiClient();
      const abortController = new AbortController();
      let query;
      if (isSlashCommand(input)) {
        const slashCommandResult = await handleSlashCommand(
          input,
          abortController,
          config,
          settings
        );
        if (slashCommandResult) {
          query = slashCommandResult;
        }
      }
      if (!query) {
        const { processedQuery, shouldProceed } = await handleAtCommand({
          query: input,
          config,
          addItem: /* @__PURE__ */ __name((_item, _timestamp) => 0, "addItem"),
          onDebugMessage: /* @__PURE__ */ __name(() => {
          }, "onDebugMessage"),
          messageId: Date.now(),
          signal: abortController.signal
        });
        if (!shouldProceed || !processedQuery) {
          throw new FatalInputError(
            "Exiting due to an error processing the @ command."
          );
        }
        query = processedQuery;
      }
      let currentMessages = [{ role: "user", parts: query }];
      let turnCount = 0;
      while (true) {
        turnCount++;
        if (config.getMaxSessionTurns() >= 0 && turnCount > config.getMaxSessionTurns()) {
          handleMaxTurnsExceededError(config);
        }
        const toolCallRequests = [];
        const responseStream = geminiClient.sendMessageStream(
          currentMessages[0]?.parts || [],
          abortController.signal,
          prompt_id
        );
        let responseText = "";
        for await (const event of responseStream) {
          if (abortController.signal.aborted) {
            handleCancellationError(config);
          }
          if (event.type === GeminiEventType.Content) {
            if (config.getOutputFormat() === OutputFormat.JSON) {
              responseText += event.value;
            } else {
              process.stdout.write(event.value);
            }
          } else if (event.type === GeminiEventType.ToolCallRequest) {
            toolCallRequests.push(event.value);
          }
        }
        if (toolCallRequests.length > 0) {
          const toolResponseParts = [];
          for (const requestInfo of toolCallRequests) {
            const toolResponse = await executeToolCall(
              config,
              requestInfo,
              abortController.signal
            );
            if (toolResponse.error) {
              handleToolError(
                requestInfo.name,
                toolResponse.error,
                config,
                toolResponse.errorType || "TOOL_EXECUTION_ERROR",
                typeof toolResponse.resultDisplay === "string" ? toolResponse.resultDisplay : void 0
              );
            }
            if (toolResponse.responseParts) {
              toolResponseParts.push(...toolResponse.responseParts);
            }
          }
          currentMessages = [{ role: "user", parts: toolResponseParts }];
        } else {
          if (config.getOutputFormat() === OutputFormat.JSON) {
            const formatter = new JsonFormatter();
            const stats = uiTelemetryService.getMetrics();
            process.stdout.write(formatter.format(responseText, stats));
          } else {
            process.stdout.write("\n");
          }
          return;
        }
      }
    } catch (error) {
      handleError(error, config);
    } finally {
      consolePatcher.cleanup();
      if (isTelemetrySdkInitialized()) {
        await shutdownTelemetry(config);
      }
    }
  });
}
__name(runNonInteractive, "runNonInteractive");

// packages/cli/src/ui/hooks/useKittyKeyboardProtocol.ts
init_esbuild_shims();
var import_react135 = __toESM(require_react(), 1);
function useKittyKeyboardProtocol() {
  const [status] = (0, import_react135.useState)({
    supported: isKittyProtocolSupported(),
    enabled: isKittyProtocolEnabled(),
    checking: false
  });
  return status;
}
__name(useKittyKeyboardProtocol, "useKittyKeyboardProtocol");

// packages/cli/src/utils/relaunch.ts
init_esbuild_shims();
import { spawn as spawn10 } from "node:child_process";
async function relaunchOnExitCode(runner) {
  while (true) {
    try {
      const exitCode = await runner();
      if (exitCode !== RELAUNCH_EXIT_CODE) {
        process.exit(exitCode);
      }
    } catch (error) {
      process.stdin.resume();
      console.error("Fatal error: Failed to relaunch the CLI process.", error);
      process.exit(1);
    }
  }
}
__name(relaunchOnExitCode, "relaunchOnExitCode");
async function relaunchAppInChildProcess(additionalNodeArgs, additionalScriptArgs) {
  if (process.env["GEMINI_CLI_NO_RELAUNCH"]) {
    return;
  }
  const runner = /* @__PURE__ */ __name(() => {
    const script = process.argv[1];
    const scriptArgs = process.argv.slice(2);
    const nodeArgs = [
      ...process.execArgv,
      ...additionalNodeArgs,
      script,
      ...additionalScriptArgs,
      ...scriptArgs
    ];
    const newEnv = { ...process.env, GEMINI_CLI_NO_RELAUNCH: "true" };
    process.stdin.pause();
    const child = spawn10(process.execPath, nodeArgs, {
      stdio: "inherit",
      env: newEnv
    });
    return new Promise((resolve24, reject) => {
      child.on("error", reject);
      child.on("close", (code2) => {
        process.stdin.resume();
        resolve24(code2 ?? 1);
      });
    });
  }, "runner");
  await relaunchOnExitCode(runner);
}
__name(relaunchAppInChildProcess, "relaunchAppInChildProcess");

// packages/cli/src/validateNonInterActiveAuth.ts
init_esbuild_shims();
function getAuthTypeFromEnv() {
  if (process.env["OPENAI_API_KEY"]) {
    return AuthType2.USE_OPENAI;
  }
  if (process.env["QWEN_OAUTH"]) {
    return AuthType2.QWEN_OAUTH;
  }
  return void 0;
}
__name(getAuthTypeFromEnv, "getAuthTypeFromEnv");
async function validateNonInteractiveAuth(configuredAuthType, useExternalAuth, nonInteractiveConfig, settings) {
  try {
    const enforcedType = settings.merged.security?.auth?.enforcedType;
    if (enforcedType) {
      const currentAuthType = getAuthTypeFromEnv();
      if (currentAuthType !== enforcedType) {
        const message = `The configured auth type is ${enforcedType}, but the current auth type is ${currentAuthType}. Please re-authenticate with the correct type.`;
        throw new Error(message);
      }
    }
    const effectiveAuthType = enforcedType || getAuthTypeFromEnv() || configuredAuthType;
    if (!effectiveAuthType) {
      const message = `Please set an Auth method in your ${USER_SETTINGS_PATH} or specify one of the following environment variables before running: QWEN_OAUTH, OPENAI_API_KEY`;
      throw new Error(message);
    }
    const authType = effectiveAuthType;
    if (!useExternalAuth) {
      const err = validateAuthMethod(String(authType));
      if (err != null) {
        throw new Error(err);
      }
    }
    await nonInteractiveConfig.refreshAuth(authType);
    return nonInteractiveConfig;
  } catch (error) {
    if (nonInteractiveConfig.getOutputFormat() === OutputFormat.JSON) {
      handleError(
        error instanceof Error ? error : new Error(String(error)),
        nonInteractiveConfig,
        1
      );
    } else {
      console.error(error instanceof Error ? error.message : String(error));
      process.exit(1);
    }
  }
}
__name(validateNonInteractiveAuth, "validateNonInteractiveAuth");

// packages/cli/src/zed-integration/zedIntegration.ts
init_esbuild_shims();

// packages/cli/src/zed-integration/acp.ts
init_esbuild_shims();
init_zod();

// packages/cli/src/zed-integration/schema.ts
init_esbuild_shims();
init_zod();
var AGENT_METHODS = {
  authenticate: "authenticate",
  initialize: "initialize",
  session_cancel: "session/cancel",
  session_load: "session/load",
  session_new: "session/new",
  session_prompt: "session/prompt"
};
var CLIENT_METHODS = {
  fs_read_text_file: "fs/read_text_file",
  fs_write_text_file: "fs/write_text_file",
  session_request_permission: "session/request_permission",
  session_update: "session/update"
};
var PROTOCOL_VERSION = 1;
var writeTextFileRequestSchema = external_exports.object({
  content: external_exports.string(),
  path: external_exports.string(),
  sessionId: external_exports.string()
});
var readTextFileRequestSchema = external_exports.object({
  limit: external_exports.number().optional().nullable(),
  line: external_exports.number().optional().nullable(),
  path: external_exports.string(),
  sessionId: external_exports.string()
});
var permissionOptionKindSchema = external_exports.union([
  external_exports.literal("allow_once"),
  external_exports.literal("allow_always"),
  external_exports.literal("reject_once"),
  external_exports.literal("reject_always")
]);
var roleSchema = external_exports.union([external_exports.literal("assistant"), external_exports.literal("user")]);
var textResourceContentsSchema = external_exports.object({
  mimeType: external_exports.string().optional().nullable(),
  text: external_exports.string(),
  uri: external_exports.string()
});
var blobResourceContentsSchema = external_exports.object({
  blob: external_exports.string(),
  mimeType: external_exports.string().optional().nullable(),
  uri: external_exports.string()
});
var toolKindSchema = external_exports.union([
  external_exports.literal("read"),
  external_exports.literal("edit"),
  external_exports.literal("delete"),
  external_exports.literal("move"),
  external_exports.literal("search"),
  external_exports.literal("execute"),
  external_exports.literal("think"),
  external_exports.literal("fetch"),
  external_exports.literal("other")
]);
var toolCallStatusSchema = external_exports.union([
  external_exports.literal("pending"),
  external_exports.literal("in_progress"),
  external_exports.literal("completed"),
  external_exports.literal("failed")
]);
var writeTextFileResponseSchema = external_exports.null();
var readTextFileResponseSchema = external_exports.object({
  content: external_exports.string()
});
var requestPermissionOutcomeSchema = external_exports.union([
  external_exports.object({
    outcome: external_exports.literal("cancelled")
  }),
  external_exports.object({
    optionId: external_exports.string(),
    outcome: external_exports.literal("selected")
  })
]);
var cancelNotificationSchema = external_exports.object({
  sessionId: external_exports.string()
});
var authenticateRequestSchema = external_exports.object({
  methodId: external_exports.string()
});
var authenticateResponseSchema = external_exports.null();
var newSessionResponseSchema = external_exports.object({
  sessionId: external_exports.string()
});
var loadSessionResponseSchema = external_exports.null();
var stopReasonSchema = external_exports.union([
  external_exports.literal("end_turn"),
  external_exports.literal("max_tokens"),
  external_exports.literal("refusal"),
  external_exports.literal("cancelled")
]);
var promptResponseSchema = external_exports.object({
  stopReason: stopReasonSchema
});
var toolCallLocationSchema = external_exports.object({
  line: external_exports.number().optional().nullable(),
  path: external_exports.string()
});
var planEntrySchema = external_exports.object({
  content: external_exports.string(),
  priority: external_exports.union([external_exports.literal("high"), external_exports.literal("medium"), external_exports.literal("low")]),
  status: external_exports.union([
    external_exports.literal("pending"),
    external_exports.literal("in_progress"),
    external_exports.literal("completed")
  ])
});
var permissionOptionSchema = external_exports.object({
  kind: permissionOptionKindSchema,
  name: external_exports.string(),
  optionId: external_exports.string()
});
var annotationsSchema = external_exports.object({
  audience: external_exports.array(roleSchema).optional().nullable(),
  lastModified: external_exports.string().optional().nullable(),
  priority: external_exports.number().optional().nullable()
});
var requestPermissionResponseSchema = external_exports.object({
  outcome: requestPermissionOutcomeSchema
});
var fileSystemCapabilitySchema = external_exports.object({
  readTextFile: external_exports.boolean(),
  writeTextFile: external_exports.boolean()
});
var envVariableSchema = external_exports.object({
  name: external_exports.string(),
  value: external_exports.string()
});
var mcpServerSchema = external_exports.object({
  args: external_exports.array(external_exports.string()),
  command: external_exports.string(),
  env: external_exports.array(envVariableSchema),
  name: external_exports.string()
});
var promptCapabilitiesSchema = external_exports.object({
  audio: external_exports.boolean().optional(),
  embeddedContext: external_exports.boolean().optional(),
  image: external_exports.boolean().optional()
});
var agentCapabilitiesSchema = external_exports.object({
  loadSession: external_exports.boolean().optional(),
  promptCapabilities: promptCapabilitiesSchema.optional()
});
var authMethodSchema = external_exports.object({
  description: external_exports.string().nullable(),
  id: external_exports.string(),
  name: external_exports.string()
});
var clientResponseSchema = external_exports.union([
  writeTextFileResponseSchema,
  readTextFileResponseSchema,
  requestPermissionResponseSchema
]);
var embeddedResourceResourceSchema = external_exports.union([
  textResourceContentsSchema,
  blobResourceContentsSchema
]);
var newSessionRequestSchema = external_exports.object({
  cwd: external_exports.string(),
  mcpServers: external_exports.array(mcpServerSchema)
});
var loadSessionRequestSchema = external_exports.object({
  cwd: external_exports.string(),
  mcpServers: external_exports.array(mcpServerSchema),
  sessionId: external_exports.string()
});
var initializeResponseSchema = external_exports.object({
  agentCapabilities: agentCapabilitiesSchema,
  authMethods: external_exports.array(authMethodSchema),
  protocolVersion: external_exports.number()
});
var contentBlockSchema = external_exports.union([
  external_exports.object({
    annotations: annotationsSchema.optional().nullable(),
    text: external_exports.string(),
    type: external_exports.literal("text")
  }),
  external_exports.object({
    annotations: annotationsSchema.optional().nullable(),
    data: external_exports.string(),
    mimeType: external_exports.string(),
    type: external_exports.literal("image")
  }),
  external_exports.object({
    annotations: annotationsSchema.optional().nullable(),
    data: external_exports.string(),
    mimeType: external_exports.string(),
    type: external_exports.literal("audio")
  }),
  external_exports.object({
    annotations: annotationsSchema.optional().nullable(),
    description: external_exports.string().optional().nullable(),
    mimeType: external_exports.string().optional().nullable(),
    name: external_exports.string(),
    size: external_exports.number().optional().nullable(),
    title: external_exports.string().optional().nullable(),
    type: external_exports.literal("resource_link"),
    uri: external_exports.string()
  }),
  external_exports.object({
    annotations: annotationsSchema.optional().nullable(),
    resource: embeddedResourceResourceSchema,
    type: external_exports.literal("resource")
  })
]);
var toolCallContentSchema = external_exports.union([
  external_exports.object({
    content: contentBlockSchema,
    type: external_exports.literal("content")
  }),
  external_exports.object({
    newText: external_exports.string(),
    oldText: external_exports.string().nullable(),
    path: external_exports.string(),
    type: external_exports.literal("diff")
  })
]);
var toolCallSchema = external_exports.object({
  content: external_exports.array(toolCallContentSchema).optional(),
  kind: toolKindSchema,
  locations: external_exports.array(toolCallLocationSchema).optional(),
  rawInput: external_exports.unknown().optional(),
  status: toolCallStatusSchema,
  title: external_exports.string(),
  toolCallId: external_exports.string()
});
var clientCapabilitiesSchema = external_exports.object({
  fs: fileSystemCapabilitySchema
});
var promptRequestSchema = external_exports.object({
  prompt: external_exports.array(contentBlockSchema),
  sessionId: external_exports.string()
});
var availableCommandInputSchema = external_exports.object({
  hint: external_exports.string()
});
var availableCommandSchema = external_exports.object({
  description: external_exports.string(),
  input: availableCommandInputSchema.nullable().optional(),
  name: external_exports.string()
});
var availableCommandsUpdateSchema = external_exports.object({
  availableCommands: external_exports.array(availableCommandSchema),
  sessionUpdate: external_exports.literal("available_commands_update")
});
var sessionUpdateSchema = external_exports.union([
  external_exports.object({
    content: contentBlockSchema,
    sessionUpdate: external_exports.literal("user_message_chunk")
  }),
  external_exports.object({
    content: contentBlockSchema,
    sessionUpdate: external_exports.literal("agent_message_chunk")
  }),
  external_exports.object({
    content: contentBlockSchema,
    sessionUpdate: external_exports.literal("agent_thought_chunk")
  }),
  external_exports.object({
    content: external_exports.array(toolCallContentSchema).optional(),
    kind: toolKindSchema,
    locations: external_exports.array(toolCallLocationSchema).optional(),
    rawInput: external_exports.unknown().optional(),
    sessionUpdate: external_exports.literal("tool_call"),
    status: toolCallStatusSchema,
    title: external_exports.string(),
    toolCallId: external_exports.string()
  }),
  external_exports.object({
    content: external_exports.array(toolCallContentSchema).optional().nullable(),
    kind: toolKindSchema.optional().nullable(),
    locations: external_exports.array(toolCallLocationSchema).optional().nullable(),
    rawInput: external_exports.unknown().optional(),
    sessionUpdate: external_exports.literal("tool_call_update"),
    status: toolCallStatusSchema.optional().nullable(),
    title: external_exports.string().optional().nullable(),
    toolCallId: external_exports.string()
  }),
  external_exports.object({
    entries: external_exports.array(planEntrySchema),
    sessionUpdate: external_exports.literal("plan")
  }),
  availableCommandsUpdateSchema
]);
var agentResponseSchema = external_exports.union([
  initializeResponseSchema,
  authenticateResponseSchema,
  newSessionResponseSchema,
  loadSessionResponseSchema,
  promptResponseSchema
]);
var requestPermissionRequestSchema = external_exports.object({
  options: external_exports.array(permissionOptionSchema),
  sessionId: external_exports.string(),
  toolCall: toolCallSchema
});
var initializeRequestSchema = external_exports.object({
  clientCapabilities: clientCapabilitiesSchema,
  protocolVersion: external_exports.number()
});
var sessionNotificationSchema = external_exports.object({
  sessionId: external_exports.string(),
  update: sessionUpdateSchema
});
var clientRequestSchema = external_exports.union([
  writeTextFileRequestSchema,
  readTextFileRequestSchema,
  requestPermissionRequestSchema
]);
var agentRequestSchema = external_exports.union([
  initializeRequestSchema,
  authenticateRequestSchema,
  newSessionRequestSchema,
  loadSessionRequestSchema,
  promptRequestSchema
]);

// packages/cli/src/zed-integration/acp.ts
var AgentSideConnection = class {
  static {
    __name(this, "AgentSideConnection");
  }
  #connection;
  constructor(toAgent, input, output) {
    const agent = toAgent(this);
    const handler = /* @__PURE__ */ __name(async (method, params) => {
      switch (method) {
        case AGENT_METHODS.initialize: {
          const validatedParams = initializeRequestSchema.parse(params);
          return agent.initialize(validatedParams);
        }
        case AGENT_METHODS.session_new: {
          const validatedParams = newSessionRequestSchema.parse(params);
          return agent.newSession(validatedParams);
        }
        case AGENT_METHODS.session_load: {
          if (!agent.loadSession) {
            throw RequestError.methodNotFound();
          }
          const validatedParams = loadSessionRequestSchema.parse(params);
          return agent.loadSession(validatedParams);
        }
        case AGENT_METHODS.authenticate: {
          const validatedParams = authenticateRequestSchema.parse(params);
          return agent.authenticate(validatedParams);
        }
        case AGENT_METHODS.session_prompt: {
          const validatedParams = promptRequestSchema.parse(params);
          return agent.prompt(validatedParams);
        }
        case AGENT_METHODS.session_cancel: {
          const validatedParams = cancelNotificationSchema.parse(params);
          return agent.cancel(validatedParams);
        }
        default:
          throw RequestError.methodNotFound(method);
      }
    }, "handler");
    this.#connection = new Connection(handler, input, output);
  }
  /**
   * Streams new content to the client including text, tool calls, etc.
   */
  async sessionUpdate(params) {
    return await this.#connection.sendNotification(
      CLIENT_METHODS.session_update,
      params
    );
  }
  /**
   * Request permission before running a tool
   *
   * The agent specifies a series of permission options with different granularity,
   * and the client returns the chosen one.
   */
  async requestPermission(params) {
    return await this.#connection.sendRequest(
      CLIENT_METHODS.session_request_permission,
      params
    );
  }
  async readTextFile(params) {
    return await this.#connection.sendRequest(
      CLIENT_METHODS.fs_read_text_file,
      params
    );
  }
  async writeTextFile(params) {
    return await this.#connection.sendRequest(
      CLIENT_METHODS.fs_write_text_file,
      params
    );
  }
};
var Connection = class {
  static {
    __name(this, "Connection");
  }
  #pendingResponses = /* @__PURE__ */ new Map();
  #nextRequestId = 0;
  #handler;
  #peerInput;
  #writeQueue = Promise.resolve();
  #textEncoder;
  constructor(handler, peerInput, peerOutput) {
    this.#handler = handler;
    this.#peerInput = peerInput;
    this.#textEncoder = new TextEncoder();
    this.#receive(peerOutput);
  }
  async #receive(output) {
    let content = "";
    const decoder = new TextDecoder();
    for await (const chunk of output) {
      content += decoder.decode(chunk, { stream: true });
      const lines = content.split("\n");
      content = lines.pop() || "";
      for (const line of lines) {
        const trimmedLine = line.trim();
        if (trimmedLine) {
          const message = JSON.parse(trimmedLine);
          this.#processMessage(message);
        }
      }
    }
  }
  async #processMessage(message) {
    if ("method" in message && "id" in message) {
      const response = await this.#tryCallHandler(
        message.method,
        message.params
      );
      await this.#sendMessage({
        jsonrpc: "2.0",
        id: message.id,
        ...response
      });
    } else if ("method" in message) {
      await this.#tryCallHandler(message.method, message.params);
    } else if ("id" in message) {
      this.#handleResponse(message);
    }
  }
  async #tryCallHandler(method, params) {
    try {
      const result = await this.#handler(method, params);
      return { result: result ?? null };
    } catch (error) {
      if (error instanceof RequestError) {
        return error.toResult();
      }
      if (error instanceof external_exports.ZodError) {
        return RequestError.invalidParams(
          JSON.stringify(error.format(), void 0, 2)
        ).toResult();
      }
      let details;
      if (error instanceof Error) {
        details = error.message;
      } else if (typeof error === "object" && error != null && "message" in error && typeof error.message === "string") {
        details = error.message;
      }
      return RequestError.internalError(details).toResult();
    }
  }
  #handleResponse(response) {
    const pendingResponse = this.#pendingResponses.get(response.id);
    if (pendingResponse) {
      if ("result" in response) {
        pendingResponse.resolve(response.result);
      } else if ("error" in response) {
        pendingResponse.reject(response.error);
      }
      this.#pendingResponses.delete(response.id);
    }
  }
  async sendRequest(method, params) {
    const id = this.#nextRequestId++;
    const responsePromise = new Promise((resolve24, reject) => {
      this.#pendingResponses.set(id, { resolve: resolve24, reject });
    });
    await this.#sendMessage({ jsonrpc: "2.0", id, method, params });
    return responsePromise;
  }
  async sendNotification(method, params) {
    await this.#sendMessage({ jsonrpc: "2.0", method, params });
  }
  async #sendMessage(json2) {
    const content = JSON.stringify(json2) + "\n";
    this.#writeQueue = this.#writeQueue.then(async () => {
      const writer = this.#peerInput.getWriter();
      try {
        await writer.write(this.#textEncoder.encode(content));
      } finally {
        writer.releaseLock();
      }
    }).catch((error) => {
      console.error("ACP write error:", error);
    });
    return this.#writeQueue;
  }
};
var RequestError = class _RequestError extends Error {
  constructor(code2, message, details) {
    super(message);
    this.code = code2;
    this.name = "RequestError";
    if (details) {
      this.data = { details };
    }
  }
  static {
    __name(this, "RequestError");
  }
  data;
  static parseError(details) {
    return new _RequestError(-32700, "Parse error", details);
  }
  static invalidRequest(details) {
    return new _RequestError(-32600, "Invalid request", details);
  }
  static methodNotFound(details) {
    return new _RequestError(-32601, "Method not found", details);
  }
  static invalidParams(details) {
    return new _RequestError(-32602, "Invalid params", details);
  }
  static internalError(details) {
    return new _RequestError(-32603, "Internal error", details);
  }
  static authRequired(details) {
    return new _RequestError(-32e3, "Authentication required", details);
  }
  toResult() {
    return {
      error: {
        code: this.code,
        message: this.message,
        data: this.data
      }
    };
  }
};

// packages/cli/src/zed-integration/fileSystemService.ts
init_esbuild_shims();
var AcpFileSystemService = class {
  constructor(client, sessionId2, capabilities, fallback) {
    this.client = client;
    this.sessionId = sessionId2;
    this.capabilities = capabilities;
    this.fallback = fallback;
  }
  static {
    __name(this, "AcpFileSystemService");
  }
  async readTextFile(filePath) {
    if (!this.capabilities.readTextFile) {
      return this.fallback.readTextFile(filePath);
    }
    const response = await this.client.readTextFile({
      path: filePath,
      sessionId: this.sessionId,
      line: null,
      limit: null
    });
    return response.content;
  }
  async writeTextFile(filePath, content) {
    if (!this.capabilities.writeTextFile) {
      return this.fallback.writeTextFile(filePath, content);
    }
    await this.client.writeTextFile({
      path: filePath,
      content,
      sessionId: this.sessionId
    });
  }
  findFiles(fileName, searchPaths) {
    return this.fallback.findFiles(fileName, searchPaths);
  }
};

// packages/cli/src/zed-integration/zedIntegration.ts
import { Readable as Readable3, Writable as Writable2 } from "node:stream";
init_zod();
import * as fs94 from "node:fs/promises";
import * as path107 from "node:path";
import { randomUUID as randomUUID7 } from "node:crypto";
var ALLOWED_BUILTIN_COMMANDS_FOR_ACP = ["init"];
function resolveModel(model, isInFallbackMode) {
  if (model === DEFAULT_GEMINI_MODEL_AUTO) {
    return isInFallbackMode ? DEFAULT_GEMINI_FLASH_MODEL : DEFAULT_GEMINI_MODEL;
  }
  return model;
}
__name(resolveModel, "resolveModel");
async function runZedIntegration(config, settings, extensions, argv) {
  const stdout = Writable2.toWeb(process.stdout);
  const stdin = Readable3.toWeb(process.stdin);
  console.log = console.error;
  console.info = console.error;
  console.debug = console.error;
  new AgentSideConnection(
    (client) => new GeminiAgent(config, settings, extensions, argv, client),
    stdout,
    stdin
  );
}
__name(runZedIntegration, "runZedIntegration");
var GeminiAgent = class {
  constructor(config, settings, extensions, argv, client) {
    this.config = config;
    this.settings = settings;
    this.extensions = extensions;
    this.argv = argv;
    this.client = client;
  }
  static {
    __name(this, "GeminiAgent");
  }
  sessions = /* @__PURE__ */ new Map();
  clientCapabilities;
  async initialize(args) {
    this.clientCapabilities = args.clientCapabilities;
    const authMethods = [
      {
        id: AuthType2.USE_OPENAI,
        name: "Use OpenAI API key",
        description: "Requires setting the `OPENAI_API_KEY` environment variable"
      },
      {
        id: AuthType2.QWEN_OAUTH,
        name: "Qwen OAuth",
        description: "OAuth authentication for Qwen models with 2000 daily requests"
      }
    ];
    return {
      protocolVersion: PROTOCOL_VERSION,
      authMethods,
      agentCapabilities: {
        loadSession: false,
        promptCapabilities: {
          image: true,
          audio: true,
          embeddedContext: true
        }
      }
    };
  }
  async authenticate({ methodId }) {
    const method = external_exports.nativeEnum(AuthType2).parse(methodId);
    await clearCachedCredentialFile();
    await this.config.refreshAuth(method);
    this.settings.setValue(
      "User" /* User */,
      "security.auth.selectedType",
      method
    );
  }
  async newSession({
    cwd: cwd7,
    mcpServers
  }) {
    const sessionId2 = this.config.getSessionId() || randomUUID7();
    const config = await this.newSessionConfig(sessionId2, cwd7, mcpServers);
    let isAuthenticated = false;
    if (this.settings.merged.security?.auth?.selectedType) {
      try {
        await config.refreshAuth(
          this.settings.merged.security.auth.selectedType
        );
        isAuthenticated = true;
      } catch (e2) {
        console.error(`Authentication failed: ${e2}`);
      }
    }
    if (!isAuthenticated) {
      throw RequestError.authRequired();
    }
    if (this.clientCapabilities?.fs) {
      const acpFileSystemService = new AcpFileSystemService(
        this.client,
        sessionId2,
        this.clientCapabilities.fs,
        config.getFileSystemService()
      );
      config.setFileSystemService(acpFileSystemService);
    }
    const geminiClient = config.getGeminiClient();
    const chat = await geminiClient.startChat();
    const session = new Session2(
      sessionId2,
      chat,
      config,
      this.client,
      this.settings
    );
    this.sessions.set(sessionId2, session);
    setTimeout(async () => {
      await session.sendAvailableCommandsUpdate();
    }, 0);
    return {
      sessionId: sessionId2
    };
  }
  async newSessionConfig(sessionId2, cwd7, mcpServers) {
    const mergedMcpServers = { ...this.settings.merged.mcpServers };
    for (const { command: command2, args, env: rawEnv, name: name3 } of mcpServers) {
      const env7 = {};
      for (const { name: envName, value } of rawEnv) {
        env7[envName] = value;
      }
      mergedMcpServers[name3] = new MCPServerConfig(command2, args, env7, cwd7);
    }
    const settings = { ...this.settings.merged, mcpServers: mergedMcpServers };
    const config = await loadCliConfig(
      settings,
      this.extensions,
      new ExtensionEnablementManager(
        ExtensionStorage.getUserExtensionsDir(),
        this.argv.extensions
      ),
      sessionId2,
      this.argv,
      cwd7
    );
    await config.initialize();
    return config;
  }
  async cancel(params) {
    const session = this.sessions.get(params.sessionId);
    if (!session) {
      throw new Error(`Session not found: ${params.sessionId}`);
    }
    await session.cancelPendingPrompt();
  }
  async prompt(params) {
    const session = this.sessions.get(params.sessionId);
    if (!session) {
      throw new Error(`Session not found: ${params.sessionId}`);
    }
    return session.prompt(params);
  }
};
var Session2 = class {
  constructor(id, chat, config, client, settings) {
    this.id = id;
    this.chat = chat;
    this.config = config;
    this.client = client;
    this.settings = settings;
  }
  static {
    __name(this, "Session");
  }
  pendingPrompt = null;
  turn = 0;
  async cancelPendingPrompt() {
    if (!this.pendingPrompt) {
      throw new Error("Not currently generating");
    }
    this.pendingPrompt.abort();
    this.pendingPrompt = null;
  }
  async prompt(params) {
    this.pendingPrompt?.abort();
    const pendingSend = new AbortController();
    this.pendingPrompt = pendingSend;
    this.turn += 1;
    const chat = this.chat;
    const promptId = this.config.getSessionId() + "########" + this.turn;
    const promptText = params.prompt.filter((block2) => block2.type === "text").map((block2) => block2.type === "text" ? block2.text : "").join(" ");
    logUserPrompt(
      this.config,
      new UserPromptEvent(
        promptText.length,
        promptId,
        this.config.getContentGeneratorConfig()?.authType,
        promptText
      )
    );
    const firstTextBlock = params.prompt.find((block2) => block2.type === "text");
    const inputText = firstTextBlock?.text || "";
    let parts;
    if (isSlashCommand(inputText)) {
      const slashCommandResult = await handleSlashCommand(
        inputText,
        pendingSend,
        this.config,
        this.settings,
        ALLOWED_BUILTIN_COMMANDS_FOR_ACP
      );
      if (slashCommandResult) {
        parts = slashCommandResult;
      } else {
        parts = await this.#resolvePrompt(params.prompt, pendingSend.signal);
      }
    } else {
      parts = await this.#resolvePrompt(params.prompt, pendingSend.signal);
    }
    let nextMessage = { role: "user", parts };
    while (nextMessage !== null) {
      if (pendingSend.signal.aborted) {
        chat.addHistory(nextMessage);
        return { stopReason: "cancelled" };
      }
      const functionCalls = [];
      try {
        const responseStream = await chat.sendMessageStream(
          resolveModel(this.config.getModel(), this.config.isInFallbackMode()),
          {
            message: nextMessage?.parts ?? [],
            config: {
              abortSignal: pendingSend.signal
            }
          },
          promptId
        );
        nextMessage = null;
        for await (const resp of responseStream) {
          if (pendingSend.signal.aborted) {
            return { stopReason: "cancelled" };
          }
          if (resp.type === StreamEventType.CHUNK && resp.value.candidates && resp.value.candidates.length > 0) {
            const candidate = resp.value.candidates[0];
            for (const part of candidate.content?.parts ?? []) {
              if (!part.text) {
                continue;
              }
              const content = {
                type: "text",
                text: part.text
              };
              this.sendUpdate({
                sessionUpdate: part.thought ? "agent_thought_chunk" : "agent_message_chunk",
                content
              });
            }
          }
          if (resp.type === StreamEventType.CHUNK && resp.value.functionCalls) {
            functionCalls.push(...resp.value.functionCalls);
          }
        }
      } catch (error) {
        if (getErrorStatus(error) === 429) {
          throw new RequestError(
            429,
            "Rate limit exceeded. Try again later."
          );
        }
        throw error;
      }
      if (functionCalls.length > 0) {
        const toolResponseParts = [];
        for (const fc of functionCalls) {
          const response = await this.runTool(pendingSend.signal, promptId, fc);
          toolResponseParts.push(...response);
        }
        nextMessage = { role: "user", parts: toolResponseParts };
      }
    }
    return { stopReason: "end_turn" };
  }
  async sendUpdate(update2) {
    const params = {
      sessionId: this.id,
      update: update2
    };
    await this.client.sessionUpdate(params);
  }
  async sendAvailableCommandsUpdate() {
    const abortController = new AbortController();
    try {
      const slashCommands = await getAvailableCommands(
        this.config,
        this.settings,
        abortController.signal,
        ALLOWED_BUILTIN_COMMANDS_FOR_ACP
      );
      const availableCommands = slashCommands.map(
        (cmd) => ({
          name: cmd.name,
          description: cmd.description,
          input: null
        })
      );
      const update2 = {
        sessionUpdate: "available_commands_update",
        availableCommands
      };
      await this.sendUpdate(update2);
    } catch (error) {
      console.error("Error sending available commands update:", error);
    }
  }
  async runTool(abortSignal, promptId, fc) {
    const callId = fc.id ?? `${fc.name}-${Date.now()}`;
    const args = fc.args ?? {};
    const startTime = Date.now();
    const errorResponse = /* @__PURE__ */ __name((error) => {
      const durationMs = Date.now() - startTime;
      logToolCall(this.config, {
        "event.name": "tool_call",
        "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
        prompt_id: promptId,
        function_name: fc.name ?? "",
        function_args: args,
        duration_ms: durationMs,
        status: "error",
        success: false,
        error: error.message,
        tool_type: typeof tool !== "undefined" && tool instanceof DiscoveredMCPTool ? "mcp" : "native"
      });
      return [
        {
          functionResponse: {
            id: callId,
            name: fc.name ?? "",
            response: { error: error.message }
          }
        }
      ];
    }, "errorResponse");
    if (!fc.name) {
      return errorResponse(new Error("Missing function name"));
    }
    const toolRegistry = this.config.getToolRegistry();
    const tool = toolRegistry.getTool(fc.name);
    if (!tool) {
      return errorResponse(
        new Error(`Tool "${fc.name}" not found in registry.`)
      );
    }
    const isTodoWriteTool = fc.name === TodoWriteTool.Name || tool.name === TodoWriteTool.Name;
    let subAgentToolEventListeners = [];
    try {
      const invocation = tool.build(args);
      const isTaskTool = tool.name === TaskTool.Name;
      if (isTaskTool && "eventEmitter" in invocation) {
        const taskEventEmitter = invocation.eventEmitter;
        subAgentToolEventListeners = this.setupSubAgentToolTracking(
          taskEventEmitter,
          abortSignal
        );
      }
      const confirmationDetails = await invocation.shouldConfirmExecute(abortSignal);
      if (confirmationDetails) {
        const content = [];
        if (confirmationDetails.type === "edit") {
          content.push({
            type: "diff",
            path: confirmationDetails.fileName,
            oldText: confirmationDetails.originalContent,
            newText: confirmationDetails.newContent
          });
        }
        const params = {
          sessionId: this.id,
          options: toPermissionOptions(confirmationDetails),
          toolCall: {
            toolCallId: callId,
            status: "pending",
            title: invocation.getDescription(),
            content,
            locations: invocation.toolLocations(),
            kind: tool.kind
          }
        };
        const output = await this.client.requestPermission(params);
        const outcome = output.outcome.outcome === "cancelled" ? ToolConfirmationOutcome.Cancel : external_exports.nativeEnum(ToolConfirmationOutcome).parse(output.outcome.optionId);
        await confirmationDetails.onConfirm(outcome);
        switch (outcome) {
          case ToolConfirmationOutcome.Cancel:
            return errorResponse(
              new Error(`Tool "${fc.name}" was canceled by the user.`)
            );
          case ToolConfirmationOutcome.ProceedOnce:
          case ToolConfirmationOutcome.ProceedAlways:
          case ToolConfirmationOutcome.ProceedAlwaysServer:
          case ToolConfirmationOutcome.ProceedAlwaysTool:
          case ToolConfirmationOutcome.ModifyWithEditor:
            break;
          default: {
            const resultOutcome = outcome;
            throw new Error(`Unexpected: ${resultOutcome}`);
          }
        }
      } else if (!isTodoWriteTool) {
        await this.sendUpdate({
          sessionUpdate: "tool_call",
          toolCallId: callId,
          status: "in_progress",
          title: invocation.getDescription(),
          content: [],
          locations: invocation.toolLocations(),
          kind: tool.kind
        });
      }
      const toolResult = await invocation.execute(abortSignal);
      subAgentToolEventListeners.forEach((cleanup) => cleanup());
      if (isTodoWriteTool) {
        let todos = [];
        if (Array.isArray(args["todos"])) {
          todos = args["todos"];
        }
        if (toolResult.returnDisplay && typeof toolResult.returnDisplay === "object" && "type" in toolResult.returnDisplay && toolResult.returnDisplay.type === "todo_list" && "todos" in toolResult.returnDisplay && Array.isArray(toolResult.returnDisplay.todos)) {
          todos = toolResult.returnDisplay.todos;
        }
        if (todos.length > 0 || Array.isArray(args["todos"])) {
          const planEntries = convertTodosToPlanEntries(todos);
          await this.sendUpdate({
            sessionUpdate: "plan",
            entries: planEntries
          });
        }
      } else {
        const content = toToolCallContent(toolResult);
        await this.sendUpdate({
          sessionUpdate: "tool_call_update",
          toolCallId: callId,
          status: "completed",
          content: content ? [content] : []
        });
      }
      const durationMs = Date.now() - startTime;
      logToolCall(this.config, {
        "event.name": "tool_call",
        "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
        function_name: fc.name,
        function_args: args,
        duration_ms: durationMs,
        status: "success",
        success: true,
        prompt_id: promptId,
        tool_type: typeof tool !== "undefined" && tool instanceof DiscoveredMCPTool ? "mcp" : "native"
      });
      return convertToFunctionResponse(fc.name, callId, toolResult.llmContent);
    } catch (e2) {
      subAgentToolEventListeners.forEach((cleanup) => cleanup());
      const error = e2 instanceof Error ? e2 : new Error(String(e2));
      await this.sendUpdate({
        sessionUpdate: "tool_call_update",
        toolCallId: callId,
        status: "failed",
        content: [
          { type: "content", content: { type: "text", text: error.message } }
        ]
      });
      return errorResponse(error);
    }
  }
  /**
   * Sets up event listeners to track sub-agent tool calls within a TaskTool execution.
   * Converts subagent tool call events into zedIntegration session updates.
   *
   * @param eventEmitter - The SubAgentEventEmitter from TaskTool
   * @param abortSignal - Signal to abort tracking if parent is cancelled
   * @returns Array of cleanup functions to remove event listeners
   */
  setupSubAgentToolTracking(eventEmitter, abortSignal) {
    const cleanupFunctions2 = [];
    const toolRegistry = this.config.getToolRegistry();
    const subAgentToolStates = /* @__PURE__ */ new Map();
    const onToolCall = /* @__PURE__ */ __name((...args) => {
      const event = args[0];
      if (abortSignal.aborted) return;
      const subAgentTool = toolRegistry.getTool(event.name);
      let subAgentInvocation;
      let toolKind = "other";
      let locations = [];
      if (subAgentTool) {
        try {
          subAgentInvocation = subAgentTool.build(event.args);
          toolKind = this.mapToolKind(subAgentTool.kind);
          locations = subAgentInvocation.toolLocations().map((loc) => ({
            path: loc.path,
            line: loc.line ?? null
          }));
        } catch (e2) {
          console.warn(`Failed to build subagent tool ${event.name}:`, e2);
        }
      }
      subAgentToolStates.set(event.callId, {
        tool: subAgentTool,
        invocation: subAgentInvocation,
        args: event.args
      });
      if (event.name === TodoWriteTool.Name) {
        return;
      }
      void this.sendUpdate({
        sessionUpdate: "tool_call",
        toolCallId: event.callId,
        status: "in_progress",
        title: event.description || event.name,
        content: [],
        locations,
        kind: toolKind,
        rawInput: event.args
      });
    }, "onToolCall");
    const onToolResult = /* @__PURE__ */ __name((...args) => {
      const event = args[0];
      if (abortSignal.aborted) return;
      const state = subAgentToolStates.get(event.callId);
      if (event.name === TodoWriteTool.Name) {
        let todos;
        if (event.resultDisplay) {
          try {
            const parsed = typeof event.resultDisplay === "string" ? JSON.parse(event.resultDisplay) : event.resultDisplay;
            if (typeof parsed === "object" && parsed !== null && "type" in parsed && parsed.type === "todo_list" && "todos" in parsed && Array.isArray(parsed.todos)) {
              todos = parsed.todos;
            }
          } catch {
          }
        }
        if (!todos && state?.args && Array.isArray(state.args["todos"])) {
          todos = state.args["todos"];
        }
        if (todos) {
          const planEntries = convertTodosToPlanEntries(todos);
          void this.sendUpdate({
            sessionUpdate: "plan",
            entries: planEntries
          });
        }
        subAgentToolStates.delete(event.callId);
        return;
      }
      let content = [];
      if (event.resultDisplay && state?.invocation) {
        if (typeof event.resultDisplay === "string") {
          content = [
            {
              type: "content",
              content: {
                type: "text",
                text: event.resultDisplay
              }
            }
          ];
        }
      }
      void this.sendUpdate({
        sessionUpdate: "tool_call_update",
        toolCallId: event.callId,
        status: event.success ? "completed" : "failed",
        content: content.length > 0 ? content : [],
        title: state?.invocation?.getDescription() ?? event.name,
        kind: state?.tool ? this.mapToolKind(state.tool.kind) : null,
        locations: state?.invocation?.toolLocations().map((loc) => ({
          path: loc.path,
          line: loc.line ?? null
        })) ?? null,
        rawInput: state?.args
      });
      subAgentToolStates.delete(event.callId);
    }, "onToolResult");
    const onToolWaitingApproval = /* @__PURE__ */ __name(async (...args) => {
      const event = args[0];
      if (abortSignal.aborted) return;
      const state = subAgentToolStates.get(event.callId);
      const content = [];
      if (event.confirmationDetails.type === "edit") {
        const editDetails = event.confirmationDetails;
        content.push({
          type: "diff",
          path: editDetails.fileName,
          oldText: editDetails.originalContent ?? "",
          newText: editDetails.newContent
        });
      }
      const fullConfirmationDetails = {
        ...event.confirmationDetails,
        onConfirm: /* @__PURE__ */ __name(async () => {
        }, "onConfirm")
      };
      const params = {
        sessionId: this.id,
        options: toPermissionOptions(fullConfirmationDetails),
        toolCall: {
          toolCallId: event.callId,
          status: "pending",
          title: event.description || event.name,
          content,
          locations: state?.invocation?.toolLocations().map((loc) => ({
            path: loc.path,
            line: loc.line ?? null
          })) ?? [],
          kind: state?.tool ? this.mapToolKind(state.tool.kind) : "other",
          rawInput: state?.args
        }
      };
      try {
        const output = await this.client.requestPermission(params);
        const outcome = output.outcome.outcome === "cancelled" ? ToolConfirmationOutcome.Cancel : external_exports.nativeEnum(ToolConfirmationOutcome).parse(output.outcome.optionId);
        await event.respond(outcome);
      } catch (error) {
        console.error(
          `Permission request failed for subagent tool ${event.name}:`,
          error
        );
        await event.respond(ToolConfirmationOutcome.Cancel);
      }
    }, "onToolWaitingApproval");
    eventEmitter.on(SubAgentEventType.TOOL_CALL, onToolCall);
    eventEmitter.on(SubAgentEventType.TOOL_RESULT, onToolResult);
    eventEmitter.on(
      SubAgentEventType.TOOL_WAITING_APPROVAL,
      onToolWaitingApproval
    );
    cleanupFunctions2.push(() => {
      eventEmitter.off(SubAgentEventType.TOOL_CALL, onToolCall);
      eventEmitter.off(SubAgentEventType.TOOL_RESULT, onToolResult);
      eventEmitter.off(
        SubAgentEventType.TOOL_WAITING_APPROVAL,
        onToolWaitingApproval
      );
    });
    return cleanupFunctions2;
  }
  /**
   * Maps core Tool Kind enum to ACP ToolKind string literals.
   *
   * @param kind - The core Kind enum value
   * @returns The corresponding ACP ToolKind string literal
   */
  mapToolKind(kind) {
    const kindMap = {
      [Kind.Read]: "read",
      [Kind.Edit]: "edit",
      [Kind.Delete]: "delete",
      [Kind.Move]: "move",
      [Kind.Search]: "search",
      [Kind.Execute]: "execute",
      [Kind.Think]: "think",
      [Kind.Fetch]: "fetch",
      [Kind.Other]: "other"
    };
    return kindMap[kind] ?? "other";
  }
  async #resolvePrompt(message, abortSignal) {
    const FILE_URI_SCHEME = "file://";
    const embeddedContext = [];
    const parts = message.map((part) => {
      switch (part.type) {
        case "text":
          return { text: part.text };
        case "image":
        case "audio":
          return {
            inlineData: {
              mimeType: part.mimeType,
              data: part.data
            }
          };
        case "resource_link": {
          if (part.uri.startsWith(FILE_URI_SCHEME)) {
            return {
              fileData: {
                mimeData: part.mimeType,
                name: part.name,
                fileUri: part.uri.slice(FILE_URI_SCHEME.length)
              }
            };
          } else {
            return { text: `@${part.uri}` };
          }
        }
        case "resource": {
          embeddedContext.push(part.resource);
          return { text: `@${part.resource.uri}` };
        }
        default: {
          const unreachable = part;
          throw new Error(`Unexpected chunk type: '${unreachable}'`);
        }
      }
    });
    const atPathCommandParts = parts.filter((part) => "fileData" in part);
    if (atPathCommandParts.length === 0 && embeddedContext.length === 0) {
      return parts;
    }
    const atPathToResolvedSpecMap = /* @__PURE__ */ new Map();
    const fileDiscovery = this.config.getFileService();
    const respectGitIgnore = this.config.getFileFilteringRespectGitIgnore();
    const pathSpecsToRead = [];
    const contentLabelsForDisplay = [];
    const ignoredPaths = [];
    const toolRegistry = this.config.getToolRegistry();
    const readManyFilesTool = toolRegistry.getTool("read_many_files");
    const globTool = toolRegistry.getTool("glob");
    if (!readManyFilesTool) {
      throw new Error("Error: read_many_files tool not found.");
    }
    for (const atPathPart of atPathCommandParts) {
      const pathName = atPathPart.fileData.fileUri;
      if (fileDiscovery.shouldGitIgnoreFile(pathName)) {
        ignoredPaths.push(pathName);
        const reason = respectGitIgnore ? "git-ignored and will be skipped" : "ignored by custom patterns";
        console.warn(`Path ${pathName} is ${reason}.`);
        continue;
      }
      let currentPathSpec = pathName;
      let resolvedSuccessfully = false;
      try {
        const absolutePath = path107.resolve(this.config.getTargetDir(), pathName);
        if (isWithinRoot(absolutePath, this.config.getTargetDir())) {
          const stats = await fs94.stat(absolutePath);
          if (stats.isDirectory()) {
            currentPathSpec = pathName.endsWith("/") ? `${pathName}**` : `${pathName}/**`;
            this.debug(
              `Path ${pathName} resolved to directory, using glob: ${currentPathSpec}`
            );
          } else {
            this.debug(`Path ${pathName} resolved to file: ${currentPathSpec}`);
          }
          resolvedSuccessfully = true;
        } else {
          this.debug(
            `Path ${pathName} is outside the project directory. Skipping.`
          );
        }
      } catch (error) {
        if (isNodeError(error) && error.code === "ENOENT") {
          if (this.config.getEnableRecursiveFileSearch() && globTool) {
            this.debug(
              `Path ${pathName} not found directly, attempting glob search.`
            );
            try {
              const globResult = await globTool.buildAndExecute(
                {
                  pattern: `**/*${pathName}*`,
                  path: this.config.getTargetDir()
                },
                abortSignal
              );
              if (globResult.llmContent && typeof globResult.llmContent === "string" && !globResult.llmContent.startsWith("No files found") && !globResult.llmContent.startsWith("Error:")) {
                const lines = globResult.llmContent.split("\n");
                if (lines.length > 1 && lines[1]) {
                  const firstMatchAbsolute = lines[1].trim();
                  currentPathSpec = path107.relative(
                    this.config.getTargetDir(),
                    firstMatchAbsolute
                  );
                  this.debug(
                    `Glob search for ${pathName} found ${firstMatchAbsolute}, using relative path: ${currentPathSpec}`
                  );
                  resolvedSuccessfully = true;
                } else {
                  this.debug(
                    `Glob search for '**/*${pathName}*' did not return a usable path. Path ${pathName} will be skipped.`
                  );
                }
              } else {
                this.debug(
                  `Glob search for '**/*${pathName}*' found no files or an error. Path ${pathName} will be skipped.`
                );
              }
            } catch (globError) {
              console.error(
                `Error during glob search for ${pathName}: ${getErrorMessage3(globError)}`
              );
            }
          } else {
            this.debug(
              `Glob tool not found. Path ${pathName} will be skipped.`
            );
          }
        } else {
          console.error(
            `Error stating path ${pathName}. Path ${pathName} will be skipped.`
          );
        }
      }
      if (resolvedSuccessfully) {
        pathSpecsToRead.push(currentPathSpec);
        atPathToResolvedSpecMap.set(pathName, currentPathSpec);
        contentLabelsForDisplay.push(pathName);
      }
    }
    let initialQueryText = "";
    for (let i = 0; i < parts.length; i++) {
      const chunk = parts[i];
      if ("text" in chunk) {
        initialQueryText += chunk.text;
      } else {
        const resolvedSpec = chunk.fileData && atPathToResolvedSpecMap.get(chunk.fileData.fileUri);
        if (i > 0 && initialQueryText.length > 0 && !initialQueryText.endsWith(" ") && resolvedSpec) {
          const prevPart = parts[i - 1];
          if ("text" in prevPart || "fileData" in prevPart && atPathToResolvedSpecMap.has(prevPart.fileData.fileUri)) {
            initialQueryText += " ";
          }
        }
        if (resolvedSpec) {
          initialQueryText += `@${resolvedSpec}`;
        } else {
          if (i > 0 && initialQueryText.length > 0 && !initialQueryText.endsWith(" ") && !chunk.fileData?.fileUri.startsWith(" ")) {
            initialQueryText += " ";
          }
          if (chunk.fileData?.fileUri) {
            initialQueryText += `@${chunk.fileData.fileUri}`;
          }
        }
      }
    }
    initialQueryText = initialQueryText.trim();
    if (ignoredPaths.length > 0) {
      const ignoreType = respectGitIgnore ? "git-ignored" : "custom-ignored";
      this.debug(
        `Ignored ${ignoredPaths.length} ${ignoreType} files: ${ignoredPaths.join(", ")}`
      );
    }
    const processedQueryParts = [{ text: initialQueryText }];
    if (pathSpecsToRead.length === 0 && embeddedContext.length === 0) {
      console.warn("No valid file paths found in @ commands to read.");
      return [{ text: initialQueryText }];
    }
    if (pathSpecsToRead.length > 0) {
      const toolArgs = {
        paths: pathSpecsToRead,
        respectGitIgnore
        // Use configuration setting
      };
      const callId = `${readManyFilesTool.name}-${Date.now()}`;
      try {
        const invocation = readManyFilesTool.build(toolArgs);
        await this.sendUpdate({
          sessionUpdate: "tool_call",
          toolCallId: callId,
          status: "in_progress",
          title: invocation.getDescription(),
          content: [],
          locations: invocation.toolLocations(),
          kind: readManyFilesTool.kind
        });
        const result = await invocation.execute(abortSignal);
        const content = toToolCallContent(result) || {
          type: "content",
          content: {
            type: "text",
            text: `Successfully read: ${contentLabelsForDisplay.join(", ")}`
          }
        };
        await this.sendUpdate({
          sessionUpdate: "tool_call_update",
          toolCallId: callId,
          status: "completed",
          content: content ? [content] : []
        });
        if (Array.isArray(result.llmContent)) {
          const fileContentRegex = /^--- (.*?) ---\n\n([\s\S]*?)\n\n$/;
          processedQueryParts.push({
            text: "\n--- Content from referenced files ---"
          });
          for (const part of result.llmContent) {
            if (typeof part === "string") {
              const match2 = fileContentRegex.exec(part);
              if (match2) {
                const filePathSpecInContent = match2[1];
                const fileActualContent = match2[2].trim();
                processedQueryParts.push({
                  text: `
Content from @${filePathSpecInContent}:
`
                });
                processedQueryParts.push({ text: fileActualContent });
              } else {
                processedQueryParts.push({ text: part });
              }
            } else {
              processedQueryParts.push(part);
            }
          }
        } else {
          console.warn(
            "read_many_files tool returned no content or empty content."
          );
        }
      } catch (error) {
        await this.sendUpdate({
          sessionUpdate: "tool_call_update",
          toolCallId: callId,
          status: "failed",
          content: [
            {
              type: "content",
              content: {
                type: "text",
                text: `Error reading files (${contentLabelsForDisplay.join(", ")}): ${getErrorMessage3(error)}`
              }
            }
          ]
        });
        throw error;
      }
    }
    if (embeddedContext.length > 0) {
      processedQueryParts.push({
        text: "\n--- Content from referenced context ---"
      });
      for (const contextPart of embeddedContext) {
        processedQueryParts.push({
          text: `
Content from @${contextPart.uri}:
`
        });
        if ("text" in contextPart) {
          processedQueryParts.push({
            text: contextPart.text
          });
        } else {
          processedQueryParts.push({
            inlineData: {
              mimeType: contextPart.mimeType ?? "application/octet-stream",
              data: contextPart.blob
            }
          });
        }
      }
    }
    return processedQueryParts;
  }
  debug(msg) {
    if (this.config.getDebugMode()) {
      console.warn(msg);
    }
  }
};
function convertTodosToPlanEntries(todos) {
  return todos.map((todo) => ({
    content: todo.content,
    priority: "medium",
    // Default priority since todos don't have priority
    status: todo.status
  }));
}
__name(convertTodosToPlanEntries, "convertTodosToPlanEntries");
function toToolCallContent(toolResult) {
  if (toolResult.error?.message) {
    throw new Error(toolResult.error.message);
  }
  if (toolResult.returnDisplay) {
    if (typeof toolResult.returnDisplay === "string") {
      return {
        type: "content",
        content: { type: "text", text: toolResult.returnDisplay }
      };
    } else if ("type" in toolResult.returnDisplay && toolResult.returnDisplay.type === "plan_summary") {
      const planDisplay = toolResult.returnDisplay;
      const planText = `${planDisplay.message}

${planDisplay.plan}`;
      return {
        type: "content",
        content: { type: "text", text: planText }
      };
    } else {
      if ("fileName" in toolResult.returnDisplay) {
        return {
          type: "diff",
          path: toolResult.returnDisplay.fileName,
          oldText: toolResult.returnDisplay.originalContent,
          newText: toolResult.returnDisplay.newContent
        };
      }
      return null;
    }
  }
  return null;
}
__name(toToolCallContent, "toToolCallContent");
var basicPermissionOptions = [
  {
    optionId: ToolConfirmationOutcome.ProceedOnce,
    name: "Allow",
    kind: "allow_once"
  },
  {
    optionId: ToolConfirmationOutcome.Cancel,
    name: "Reject",
    kind: "reject_once"
  }
];
function toPermissionOptions(confirmation) {
  switch (confirmation.type) {
    case "edit":
      return [
        {
          optionId: ToolConfirmationOutcome.ProceedAlways,
          name: "Allow All Edits",
          kind: "allow_always"
        },
        ...basicPermissionOptions
      ];
    case "exec":
      return [
        {
          optionId: ToolConfirmationOutcome.ProceedAlways,
          name: `Always Allow ${confirmation.rootCommand}`,
          kind: "allow_always"
        },
        ...basicPermissionOptions
      ];
    case "mcp":
      return [
        {
          optionId: ToolConfirmationOutcome.ProceedAlwaysServer,
          name: `Always Allow ${confirmation.serverName}`,
          kind: "allow_always"
        },
        {
          optionId: ToolConfirmationOutcome.ProceedAlwaysTool,
          name: `Always Allow ${confirmation.toolName}`,
          kind: "allow_always"
        },
        ...basicPermissionOptions
      ];
    case "info":
      return [
        {
          optionId: ToolConfirmationOutcome.ProceedAlways,
          name: `Always Allow`,
          kind: "allow_always"
        },
        ...basicPermissionOptions
      ];
    case "plan":
      return [
        {
          optionId: ToolConfirmationOutcome.ProceedAlways,
          name: `Always Allow Plans`,
          kind: "allow_always"
        },
        ...basicPermissionOptions
      ];
    default: {
      const unreachable = confirmation;
      throw new Error(`Unexpected: ${unreachable}`);
    }
  }
}
__name(toPermissionOptions, "toPermissionOptions");

// packages/cli/src/gemini.tsx
var import_jsx_runtime107 = __toESM(require_jsx_runtime(), 1);
function validateDnsResolutionOrder(order) {
  const defaultValue = "ipv4first";
  if (order === void 0) {
    return defaultValue;
  }
  if (order === "ipv4first" || order === "verbatim") {
    return order;
  }
  console.warn(
    `Invalid value for dnsResolutionOrder in settings: "${order}". Using default "${defaultValue}".`
  );
  return defaultValue;
}
__name(validateDnsResolutionOrder, "validateDnsResolutionOrder");
function getNodeMemoryArgs(isDebugMode2) {
  const totalMemoryMB = os42.totalmem() / (1024 * 1024);
  const heapStats = v8.getHeapStatistics();
  const currentMaxOldSpaceSizeMb = Math.floor(
    heapStats.heap_size_limit / 1024 / 1024
  );
  const targetMaxOldSpaceSizeInMB = Math.floor(totalMemoryMB * 0.5);
  if (isDebugMode2) {
    console.debug(
      `Current heap size ${currentMaxOldSpaceSizeMb.toFixed(2)} MB`
    );
  }
  if (process.env["GEMINI_CLI_NO_RELAUNCH"]) {
    return [];
  }
  if (targetMaxOldSpaceSizeInMB > currentMaxOldSpaceSizeMb) {
    if (isDebugMode2) {
      console.debug(
        `Need to relaunch with more memory: ${targetMaxOldSpaceSizeInMB.toFixed(2)} MB`
      );
    }
    return [`--max-old-space-size=${targetMaxOldSpaceSizeInMB}`];
  }
  return [];
}
__name(getNodeMemoryArgs, "getNodeMemoryArgs");
function setupUnhandledRejectionHandler() {
  let unhandledRejectionOccurred = false;
  process.on("unhandledRejection", (reason, _promise) => {
    const errorMessage = `=========================================
This is an unexpected error. Please file a bug report using the /bug tool.
CRITICAL: Unhandled Promise Rejection!
=========================================
Reason: ${reason}${reason instanceof Error && reason.stack ? `
Stack trace:
${reason.stack}` : ""}`;
    appEvents.emit("log-error" /* LogError */, errorMessage);
    if (!unhandledRejectionOccurred) {
      unhandledRejectionOccurred = true;
      appEvents.emit("open-debug-console" /* OpenDebugConsole */);
    }
  });
}
__name(setupUnhandledRejectionHandler, "setupUnhandledRejectionHandler");
async function startInteractiveUI(config, settings, startupWarnings, workspaceRoot = process.cwd(), initializationResult) {
  const version2 = await getCliVersion();
  setWindowTitle(basename15(workspaceRoot), settings);
  const AppWrapper = /* @__PURE__ */ __name(() => {
    const kittyProtocolStatus = useKittyKeyboardProtocol();
    const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10);
    return /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(SettingsContext.Provider, { value: settings, children: /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(
      KeypressProvider,
      {
        kittyProtocolEnabled: kittyProtocolStatus.enabled,
        config,
        debugKeystrokeLogging: settings.merged.general?.debugKeystrokeLogging,
        pasteWorkaround: process.platform === "win32" || nodeMajorVersion < 20,
        children: /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(SessionStatsProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(VimModeProvider, { settings, children: /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(
          AppContainer,
          {
            config,
            settings,
            startupWarnings,
            version: version2,
            initializationResult
          }
        ) }) })
      }
    ) });
  }, "AppWrapper");
  const instance = render_default(
    process.env["DEBUG"] ? /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(import_react136.default.StrictMode, { children: /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(AppWrapper, {}) }) : /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(AppWrapper, {}),
    {
      exitOnCtrlC: false,
      isScreenReaderEnabled: config.getScreenReader()
    }
  );
  checkForUpdates().then((info) => {
    handleAutoUpdate(info, settings, config.getProjectRoot());
  }).catch((err) => {
    if (config.getDebugMode()) {
      console.error("Update check failed:", err);
    }
  });
  registerCleanup(() => instance.unmount());
}
__name(startInteractiveUI, "startInteractiveUI");
async function main() {
  setupUnhandledRejectionHandler();
  const settings = loadSettings();
  migrateDeprecatedSettings(settings);
  await cleanupCheckpoints();
  const sessionId2 = randomUUID8();
  const argv = await parseArguments(settings.merged);
  if (argv.promptInteractive && !process.stdin.isTTY) {
    console.error(
      "Error: The --prompt-interactive flag cannot be used when input is piped from stdin."
    );
    process.exit(1);
  }
  const isDebugMode2 = isDebugMode(argv);
  const consolePatcher = new ConsolePatcher({
    stderr: true,
    debugMode: isDebugMode2
  });
  consolePatcher.patch();
  registerCleanup(consolePatcher.cleanup);
  dns.setDefaultResultOrder(
    validateDnsResolutionOrder(settings.merged.advanced?.dnsResolutionOrder)
  );
  themeManager.loadCustomThemes(settings.merged.ui?.customThemes);
  if (settings.merged.ui?.theme) {
    if (!themeManager.setActiveTheme(settings.merged.ui?.theme)) {
      console.warn(`Warning: Theme "${settings.merged.ui?.theme}" not found.`);
    }
  }
  if (!process.env["SANDBOX"]) {
    const memoryArgs = settings.merged.advanced?.autoConfigureMemory ? getNodeMemoryArgs(isDebugMode2) : [];
    const sandboxConfig = await loadSandboxConfig(settings.merged, argv);
    if (sandboxConfig) {
      const partialConfig = await loadCliConfig(
        settings.merged,
        [],
        new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()),
        sessionId2,
        argv
      );
      if (settings.merged.security?.auth?.selectedType && !settings.merged.security?.auth?.useExternal) {
        try {
          const err = validateAuthMethod(
            settings.merged.security.auth.selectedType
          );
          if (err) {
            throw new Error(err);
          }
          await partialConfig.refreshAuth(
            settings.merged.security.auth.selectedType
          );
        } catch (err) {
          console.error("Error authenticating:", err);
          process.exit(1);
        }
      }
      let stdinData = "";
      if (!process.stdin.isTTY) {
        stdinData = await readStdin();
      }
      const injectStdinIntoArgs = /* @__PURE__ */ __name((args, stdinData2) => {
        const finalArgs = [...args];
        if (stdinData2) {
          const promptIndex = finalArgs.findIndex(
            (arg) => arg === "--prompt" || arg === "-p"
          );
          if (promptIndex > -1 && finalArgs.length > promptIndex + 1) {
            finalArgs[promptIndex + 1] = `${stdinData2}

${finalArgs[promptIndex + 1]}`;
          } else {
            finalArgs.push("--prompt", stdinData2);
          }
        }
        return finalArgs;
      }, "injectStdinIntoArgs");
      const sandboxArgs = injectStdinIntoArgs(process.argv, stdinData);
      await relaunchOnExitCode(
        () => start_sandbox(sandboxConfig, memoryArgs, partialConfig, sandboxArgs)
      );
      process.exit(0);
    } else {
      await relaunchAppInChildProcess(memoryArgs, []);
    }
  }
  {
    const extensionEnablementManager = new ExtensionEnablementManager(
      ExtensionStorage.getUserExtensionsDir(),
      argv.extensions
    );
    const extensions = loadExtensions(extensionEnablementManager);
    const config = await loadCliConfig(
      settings.merged,
      extensions,
      extensionEnablementManager,
      sessionId2,
      argv
    );
    if (config.getListExtensions()) {
      console.log("Installed extensions:");
      for (const extension of extensions) {
        console.log(`- ${extension.config.name}`);
      }
      process.exit(0);
    }
    const wasRaw = process.stdin.isRaw;
    let kittyProtocolDetectionComplete;
    if (config.isInteractive() && !wasRaw && process.stdin.isTTY) {
      process.stdin.setRawMode(true);
      process.on("SIGTERM", () => {
        process.stdin.setRawMode(wasRaw);
      });
      process.on("SIGINT", () => {
        process.stdin.setRawMode(wasRaw);
      });
      kittyProtocolDetectionComplete = detectAndEnableKittyProtocol();
    }
    setMaxSizedBoxDebugging(isDebugMode2);
    const initializationResult = await initializeApp(config, settings);
    if (settings.merged.security?.auth?.selectedType === AuthType2.LOGIN_WITH_GOOGLE && config.isBrowserLaunchSuppressed()) {
      await getOauthClient(settings.merged.security.auth.selectedType, config);
    }
    if (config.getExperimentalZedIntegration()) {
      return runZedIntegration(config, settings, extensions, argv);
    }
    let input = config.getQuestion();
    const startupWarnings = [
      ...await getStartupWarnings(),
      ...await getUserStartupWarnings({
        workspaceRoot: process.cwd(),
        useRipgrep: settings.merged.tools?.useRipgrep ?? true,
        useBuiltinRipgrep: settings.merged.tools?.useBuiltinRipgrep ?? true
      })
    ];
    if (config.isInteractive()) {
      await kittyProtocolDetectionComplete;
      await startInteractiveUI(
        config,
        settings,
        startupWarnings,
        process.cwd(),
        initializationResult
      );
      return;
    }
    await config.initialize();
    if (!process.stdin.isTTY) {
      const stdinData = await readStdin();
      if (stdinData) {
        input = `${stdinData}

${input}`;
      }
    }
    if (!input) {
      console.error(
        `No input provided via stdin. Input can be provided by piping data into gemini or using the --prompt option.`
      );
      process.exit(1);
    }
    const prompt_id = Math.random().toString(16).slice(2);
    logUserPrompt(config, {
      "event.name": "user_prompt",
      "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
      prompt: input,
      prompt_id,
      auth_type: config.getContentGeneratorConfig()?.authType,
      prompt_length: input.length
    });
    const nonInteractiveConfig = await validateNonInteractiveAuth(
      settings.merged.security?.auth?.selectedType,
      settings.merged.security?.auth?.useExternal,
      config,
      settings
    );
    if (config.getDebugMode()) {
      console.log("Session ID: %s", sessionId2);
    }
    await runNonInteractive(nonInteractiveConfig, settings, input, prompt_id);
    await runExitCleanup();
    process.exit(0);
  }
}
__name(main, "main");
function setWindowTitle(title, settings) {
  if (!settings.merged.ui?.hideWindowTitle) {
    const windowTitle = computeWindowTitle(title);
    process.stdout.write(`\x1B]2;${windowTitle}\x07`);
    process.on("exit", () => {
      process.stdout.write(`\x1B]2;\x07`);
    });
  }
}
__name(setWindowTitle, "setWindowTitle");

// packages/cli/index.ts
main().catch((error) => {
  if (error instanceof FatalError) {
    let errorMessage = error.message;
    if (!process.env["NO_COLOR"]) {
      errorMessage = `\x1B[31m${errorMessage}\x1B[0m`;
    }
    console.error(errorMessage);
    process.exit(error.exitCode);
  }
  console.error("An unexpected critical error occurred:");
  if (error instanceof Error) {
    console.error(error.stack);
  } else {
    console.error(String(error));
  }
  process.exit(1);
});
/**
 * @license
 * Copyright 2025 Qwen
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
/*! Bundled license information:

react/cjs/react.production.js:
  (**
   * @license React
   * react.production.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

react/cjs/react.development.js:
  (**
   * @license React
   * react.development.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

react-reconciler/cjs/react-reconciler-constants.production.js:
  (**
   * @license React
   * react-reconciler-constants.production.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

react-reconciler/cjs/react-reconciler-constants.development.js:
  (**
   * @license React
   * react-reconciler-constants.development.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

scheduler/cjs/scheduler.production.js:
  (**
   * @license React
   * scheduler.production.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

scheduler/cjs/scheduler.development.js:
  (**
   * @license React
   * scheduler.development.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

react-reconciler/cjs/react-reconciler.production.js:
  (**
   * @license React
   * react-reconciler.production.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

react-reconciler/cjs/react-reconciler.development.js:
  (**
   * @license React
   * react-reconciler.development.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

react-devtools-core/dist/backend.js:
  (**
   * @license React
   * react-debug-tools.production.min.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)
  (**
   * @license React
   * react-is.production.min.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)
  (**
   * @license React
   * react.production.min.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

undici/lib/web/fetch/body.js:
  (*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)

undici/lib/web/websocket/frame.js:
  (*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> *)

safe-buffer/index.js:
  (*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)

@google/genai/dist/node/index.mjs:
  (**
   * @license
   * Copyright 2025 Google LLC
   * SPDX-License-Identifier: Apache-2.0
   *)

@grpc/proto-loader/build/src/util.js:
@grpc/proto-loader/build/src/index.js:
  (**
   * @license
   * Copyright 2018 gRPC authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *
   *)

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

uri-js/dist/es5/uri.all.js:
  (** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js *)

fzf/dist/fzf.es.js:
  (** @license
   * fzf v0.5.2
   * Copyright (c) 2021 Ajit
   * Licensed under BSD 3-Clause
   *)

react/cjs/react-jsx-runtime.production.js:
  (**
   * @license React
   * react-jsx-runtime.production.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

react/cjs/react-jsx-runtime.development.js:
  (**
   * @license React
   * react-jsx-runtime.development.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

react-is/cjs/react-is.production.min.js:
  (** @license React v16.13.1
   * react-is.production.min.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

react-is/cjs/react-is.development.js:
  (** @license React v16.13.1
   * react-is.development.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

object-assign/index.js:
  (*
  object-assign
  (c) Sindre Sorhus
  @license MIT
  *)

repeat-string/index.js:
  (*!
   * repeat-string <https://github.com/jonschlinkert/repeat-string>
   *
   * Copyright (c) 2014-2015, Jon Schlinkert.
   * Licensed under the MIT License.
   *)

deep-extend/lib/deep-extend.js:
  (*!
   * @description Recursive object extending
   * @author Viacheslav Lotsmanov <lotsmanov89@gmail.com>
   * @license MIT
   *
   * The MIT License (MIT)
   *
   * Copyright (c) 2013-2018 Viacheslav Lotsmanov
   *
   * Permission is hereby granted, free of charge, to any person obtaining a copy of
   * this software and associated documentation files (the "Software"), to deal in
   * the Software without restriction, including without limitation the rights to
   * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
   * the Software, and to permit persons to whom the Software is furnished to do so,
   * subject to the following conditions:
   *
   * The above copyright notice and this permission notice shall be included in all
   * copies or substantial portions of the Software.
   *
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
   * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
   * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
   * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
   *)

yargs-parser/build/lib/string-utils.js:
yargs-parser/build/lib/tokenize-arg-string.js:
yargs-parser/build/lib/yargs-parser-types.js:
yargs-parser/build/lib/yargs-parser.js:
  (**
   * @license
   * Copyright (c) 2016, Contributors
   * SPDX-License-Identifier: ISC
   *)

yargs-parser/build/lib/index.js:
  (**
   * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
   * CJS and ESM environments.
   *
   * @license
   * Copyright (c) 2016, Contributors
   * SPDX-License-Identifier: ISC
   *)

ky/distribution/index.js:
  (*! MIT License © Sindre Sorhus *)
*/
